diff --git a/.crumb b/.crumb index 06f512f0c..048b11ed8 100644 --- a/.crumb +++ b/.crumb @@ -42,68 +42,68 @@ "children": [ { "digest": "9f19f11674ca5dfc3c9c3ae35fe6106557aee9583210da13d257e1b9d88e052c", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "calibration", "purpose": "Directory calibration. Purpose not yet described by a human." }, { "digest": "ab620fb23433db5887c549b5484a1268399f08d4fcfdb285d7d178ac58b89dd9", - "last_commit": "c095c17df", + "last_commit": "1fe5976d", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, { "digest": "536f7b8db9a92a1f586bad4379d47544a30d1b8e83c2d799c18e66cf8660c9ae", - "last_commit": "30bb116cc", + "last_commit": "30bb116c", "name": "doctrine", "purpose": "Directory doctrine. Purpose not yet described by a human." }, { - "digest": "8f0e5cb325040247440527f6b54b65cf72c47ff5adca75b4f32a1ddf2b2d6ade", - "last_commit": "1f320caad", + "digest": "5fb34d7988eea79177ebfa6b8245c1131a63e09789572b5633278936d11295ae", + "last_commit": "174f647a", "name": "mk", "purpose": "Directory mk. Purpose not yet described by a human." }, { "digest": "62b92244c52fa8af6f511012dee2967e98dff162cc1d8bf45d0b2f15cb0adc5f", - "last_commit": "450bbefd4", + "last_commit": "450bbefd", "name": "research", "purpose": "Directory research. Purpose not yet described by a human." }, { "digest": "055cfcb74d741695ca12b8dbefe0fab71a234291b3ca136984f736a6213accef", - "last_commit": "107f93545", + "last_commit": "107f9354", "name": "spec", "purpose": "Directory spec. Purpose not yet described by a human." }, { - "digest": "36bd5a00a116cad009672752dcac449a48515f0ef74e759d1710492967158315", - "last_commit": "c815809d9", + "digest": "356bac6620b52492f1e1c8464ce092e11845d12ff857857cf32ad4009228d2c9", + "last_commit": "9a6340d6", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "4f54ac0e02337bf2bd58142881e60cb25241457eb40b659235360a4eadebfb82", - "last_commit": "56dfcbd9b", + "digest": "f8324a406c96486b9fc156b0cbd9fab2ad57bdcf33eda1614d97ec9585fb70a0", + "last_commit": "174f647a", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, { - "digest": "4e83dea21da137c30076c2dc0ca4f3a488f576f30a94e334558ad5ea523f3a6b", - "last_commit": "a50c3bd41", + "digest": "1a49f30057f97de35b3a9ea43e4d964ec9a2211294b12ffe8ed08abe80c2ba1e", + "last_commit": "174f647a", "name": "tools", "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:555a98b414f4a51bac364cecefcbc8c46f02f72ba8aee8b6cf38da55bea9ded6", - "compiled_at": "2026-10-28T09:49:40Z", + "children_root": "sha256:2a37feb3c2d21093e100e1abdf6d589e9dacb686a6646456a7697167ca02bc89", + "compiled_at": "2026-10-28T21:12:07Z", "compiler": "crumb-compile/1", - "digest": "sha256:23619aae22042fc9c7f3ec9938f0da3692964c3bebe8d4fbe006875201a46ba8", + "digest": "sha256:569bbc21c454681a78e7f9d898c0eb559018e9b3460e84549166e0e4162e4c14", "evidence_files": 12477, "evidence_root": "sha256:9d96c8c22e5c574c4768d1eadd333b9750f73cd27be276a0f190c876960008a1", - "files": 17564, - "generated_at_commit": "56dfcbd9b284a88618983e3eac7512630ad70b3e", - "source_tree": "sha256:20bbed51f47dd0d11180520f489e436b54f970840ca38d290c1780073e50592f" + "files": 17448, + "generated_at_commit": "174f647a6694c61212ab90aa9e204ea2d3a69952", + "source_tree": "sha256:8b64baaf984c009aadef35dcb6e5d788e77140939049e061f11eb3c331aaa94e" }, "owner_lane": "", "provenance": { diff --git a/AGENTS.md b/AGENTS.md index 4df279aac..9fcf7a648 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,11 +31,13 @@ Some gates expect sibling checkouts next to this one: `../physics` (physics-mv) ## Configuration -- `physics.lock`, `aienos.lock`, `argus.lock`: commits of the sibling sources the full build and some gates pin. `crumb.lock`: the aien-architecture commit the crumb tool is built from. `om/omega-bridge.lock`: the omega-bridge commit whose `src/native.om` generates `src/omega_om_units.inc`. +- `physics.lock`, `aienos.lock`, `argus.lock`: commits of the sibling sources the full build and some gates pin. `crumb.lock`: the aien-architecture commit the crumb tool is built from. `om/omega-bridge.lock`: the bridge for the retained CPU SHA-256/BLAKE3 binding generated by `om/units.sh`. - `PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0` on `make` builds the host suites without a physics checkout. - `OUT_DIR`: per-step build directory; `tests/gates/run.sh` sets it to `build/step-`. - `.aien/always` lists the gates every commit must pass (`CRUMB-VERIFY`, `OMEGA-EVIDENCE-IMMUTABLE`, `OMEGA-ZERO-DISK-SECRETS`); `.aien/verify.pub` is the Spark judge's public key. - `AIEN_OMEGA_FP8_GROUPED_WAVE=1` and `AIEN_OMEGA_FP8_GROUPED_CTAS=n` change the GB10 FP8 grouped expert launch (off by default; see `README.md`). +- `cudapp.lock`: canonical native GPU source. Set `CUDAPP_DIR` to a checkout at that exact HEAD, `OMEGA_OMC` to the seeded compiler SHA-256 `2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f`, and `OMEGA_BRIDGE` to `0c4cb9ff980af278890b231b994eaede4dc7621c`. `check-cudapp` stages and authenticates committed sources, generated units and archive on every native entry, without a lock-check bypass. Canonical headers precede Physics headers; the canonical archive follows retained Omega CPU objects. +- Do not restore duplicate GPU sources or rewrite historical receipts. The 123-path retirement ledger is `tests/cudapp_retirement_sources.json`. Unique Omega gate/resident adapters remain local. Host-only fixtures and source provenance are not GPU or full-model qualification; production native candidate admission remains refused until independently accepted exact-artifact qualification. ## Usage diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 5dc4ef563..fb79d4573 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -5,6 +5,7 @@ Every model below did real work. A model is listed only for work it did. The orc | Model | What it did | |---|---| +| Codex (GPT-6.1 Sol) | Canonical CUDApp source staging and native caller integration, graph/session lifecycle binding, preserved full-union GPU source retirement, and independent host refusal controls; GPU and full-model qualification not claimed | | Codex (GPT-6.1 Sol) | Corrected qty prefix-query types and capacity-only diagnostic repairability, with exact-record regression controls (#911) | | Codex | Inference-cost driver compiler-failure status repair, host-only refusal regression probes and independent review; native Omega execution NOT_RUN | | Codex (GPT-6 Astra) | Bounded native peer credentials, multi-descriptor polling, single-iovec sendmsg, socket-option allowlist and host fixtures (#788) | diff --git a/Makefile b/Makefile index 4e068c1de..ff1235461 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,7 @@ CC ?= gcc .DEFAULT_GOAL := all PHYSICS_DIR ?= ../physics OUT_DIR ?= build +include mk/cudapp-consumer.mk -include mk/*.mk PHYSICS_LOCK_CHECK ?= 1 @@ -11,67 +12,17 @@ CFLAGS ?= -std=gnu11 -Wall -Wextra -Werror -MMD -MP -D_GNU_SOURCE -O2 -Isrc \ -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 +override CFLAGS := -Isrc $(CUDAPP_HEADER_FLAGS) $(filter-out -Isrc,$(CFLAGS)) +# Omega owns its CPU substrate and evidence adapters. Native GPU implementation +# and bundled driver objects come only from the pinned canonical CUDApp archive. SRCS = src/omega_om_units.c src/omega_canonical.c src/omega_validate.c src/omega_core.c src/omega_codec.c \ src/aarch64_encoder.c src/aarch64_decoder.c src/omega_realize.c src/omega_exec.c \ src/omega_self_host.c src/omega_verify.c src/omega_program.c src/omega_synthesis.c \ src/omega_library.c src/omega_discovery.c src/omega_machine.c src/omega_realize_synth.c \ src/omega_matvec.c src/omega_accelerator.c src/omega_accelerator_world.c \ - src/omega_vector.c src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \ - src/omega_blackwell_realize.c src/omega_blackwell_submit.c src/omega_blackwell_engine.c src/omega_gpu_engine.c src/omega_blackwell_gates.c src/omega_blackwell_matmul.c src/omega_blackwell_codegen.c 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_elementwise_api.c src/omega_gpu_attention_api.c src/omega_gpu_serving.c src/omega_world_gates.c src/omega_gpu_wait.c \ - src/omega_evidence.c \ - $(PHYSICS_DIR)/m16/m16_native.c $(PHYSICS_DIR)/nvrm/nvrm.c \ - tools/omegatool.c -# OWN-30B cut 2 (2026-10-13): column windows over a resident bf16 tensor for the MoE path. New file, -# adds exports only (8B decode-speed lane collision rule: no existing GPU source moves). -SRCS += src/omega_gpu_moe_api.c - -# OWN-30B Cut 6 / Cut 5 (2026-10-13): FP8 e4m3 GEMV kernel family, new files only (omega_gpu_fp8_api.h) -SRCS += src/omega_blackwell_codegen_moe.c src/omega_gpu_fp8_pack.c src/omega_gpu_fp8_api.c -# OWN-30B W-L2c (2026-10-14): FP8 GEMV variant 2, row-pipelined (omega_blackwell_codegen_moe2.h), selectable, variant 1 untouched -SRCS += src/omega_blackwell_codegen_moe2.c -# OWN-30B cut 8 (2026-10-13): one-launch decode attention (omega_gpu_decode_attn_api.h), new files only -SRCS += src/omega_blackwell_codegen_attn.c src/omega_gpu_decode_attn_api.c -# Qwen3.8-27B (omega-mv#544, 2026-10-18): decode attention head_dim 256, new files only -SRCS += src/omega_blackwell_codegen_attn256.c src/omega_gpu_decode_attn256_api.c -# Qwen3.8-27B (omega-mv#545, 2026-10-18): prefill attention head_dim 256 on the decode cache, new files only -SRCS += src/omega_blackwell_codegen_pattn256.c src/omega_gpu_prefill_attn256_api.c -# OWN-30B (2026-10-13): libm-free host math (omega_gpu_hostmath.h) so libomega_gpu.a links without -lm -SRCS += src/omega_gpu_hostmath.c -# OWN-30B cut 8 item 2 (2026-10-13): one-launch MoE router (omega_gpu_router_api.h), new files only -SRCS += src/omega_blackwell_codegen_router.c src/omega_gpu_router_api.c -# Qwen3.8-27B Gated DeltaNet decode step (omega#542, 2026-10-18): one launch per layer (omega_gpu_gdn_api.h), new files only -SRCS += src/omega_blackwell_codegen_gdn.c src/omega_gpu_gdn_api.c -# OWN-30B W-L2 (2026-10-13): decode launch collapse, new files only: command list (N launches, one submit) + glue kernels -SRCS += src/omega_gpu_cmdlist.c src/omega_blackwell_codegen_dec.c -# C3 (docs/OMEGA.md): reductions and prefix sums of any length, bit-exact against the frozen-order host reference. -SRCS += src/omega_gpu_scan.c src/omega_gpu_scan_ref.c -# C3: matrix multiply of any shape, BF16 and FP8, both layouts, on the tensor cores (pack kernels + one multiply kernel). -SRCS += src/omega_gpu_gemm.c -SRCS += src/omega_gpu_mem_cached.c -SRCS += src/omega_gpu_decode_graph.c -# sc #642 (2026-10-18): one Qwen3.8-27B decode token as one command list (GDN + hd256 attention layers, dense MLP) -SRCS += src/omega_gpu_q38_graph.c -SRCS += src/omega_gpu_q36_graph.c -# C6 (L386): Omega's own sm_121 disassembler; the listing checks in tests/ call it instead of nvdisasm -SRCS += src/omega_sm121_disasm.c -# OWN-30B (2026-10-13): bf16 streaming GEMV for the lm_head (omega_gpu_bf16_gemv_api.h), new files only -SRCS += src/omega_blackwell_codegen_bf16.c src/omega_gpu_bf16_gemv_api.c -# OWN-30B prefill (2026-10-13): FP8 grouped GEMM, each expert streamed once per pass (omega_gpu_fp8gemm_api.h), new files only -SRCS += src/omega_blackwell_codegen_gemm.c src/omega_gpu_fp8gemm_api.c -# OWN-30B T3 (2026-10-13): tensor-core prefill kernels (omega_blackwell_codegen_tc.h), new files only -SRCS += src/omega_blackwell_codegen_tc.c -SRCS += src/omega_gpu_tcgemm_api.c -# OWN-30B L1 attention (2026-10-13): tensor-core causal prefill attention (omega_gpu_prefill_attn_api.h), new files only -SRCS += src/omega_blackwell_codegen_pattn.c src/omega_gpu_prefill_attn_api.c -# OWN-30B T3b (2026-10-13): device-resident prefill (omega_gpu_prefill.h), new files only -SRCS += src/omega_blackwell_codegen_pf.c src/omega_gpu_prefill.c src/omega_blackwell_codegen_tc2.c src/omega_gpu_pfgemm.c -# OWN-30B L1 GEMM (W-L1G, 2026-10-14): native FP8 QMMA, new files only -SRCS += src/omega_blackwell_codegen_qmma.c src/omega_blackwell_codegen_qg.c -# OWN-30B W-L1G-D (2026-10-14): router logits + MoE combine for the whole-prompt prefill, new files only -SRCS += src/omega_blackwell_codegen_pfhost.c src/omega_gpu_pfhost.c -# Ternary engine T0 (2026-10-15): KT1, the W2A8 ternary GEMV (omega_gpu_tern_api.h), new files only -SRCS += src/omega_blackwell_codegen_tern.c src/omega_gpu_tern_api.c + src/omega_vector.c src/omega_blackwell_gates.c src/omega_world_gates.c \ + src/omega_evidence.c tools/omegatool.c OBJS = $(patsubst %.c,$(OUT_DIR)/%.o,$(notdir $(SRCS))) DEPS = $(OBJS:.o=.d) -include $(DEPS) @@ -116,12 +67,6 @@ $(OUT_DIR): $(OUT_DIR)/%.o: src/%.c | $(OUT_DIR) $(CC) $(CFLAGS) -c $< -o $@ -$(OUT_DIR)/m16_native.o: $(PHYSICS_DIR)/m16/m16_native.c | $(OUT_DIR) - $(CC) $(CFLAGS) -c $< -o $@ - -$(OUT_DIR)/nvrm.o: $(PHYSICS_DIR)/nvrm/nvrm.c | $(OUT_DIR) - $(CC) $(CFLAGS) -c $< -o $@ - $(OUT_DIR)/crumbline/%.o: src/crumbline/%.c | $(OUT_DIR) mkdir -p $(OUT_DIR)/crumbline $(CC) $(CFLAGS) -c $< -o $@ @@ -141,8 +86,8 @@ $(LEARNER): $(LEARNER_OBJS) $(OUT_DIR)/omegatool.o: tools/omegatool.c | $(OUT_DIR) $(CC) $(CFLAGS) -c $< -o $@ -$(TARGET): $(OBJS) | check-physics-lock - $(CC) $(CFLAGS) -o $@.tmp.$$$$ $(OBJS) && mv -f $@.tmp.$$$$ $@ +$(TARGET): $(OBJS) $(CUDAPP_LIB) | check-physics-lock check-cudapp + $(CC) $(CFLAGS) -o $@.tmp.$$$$ $(OBJS) $(CUDAPP_LIB) && mv -f $@.tmp.$$$$ $@ test: $(TARGET) ./$(TARGET) --run-gates @@ -251,9 +196,9 @@ NUMERIC_CPU_SRCS = tests/test_omega_numeric.c src/omega_numeric.c src/omega_nume $(NUMERIC_BW_SRCS) NUMERIC_CPU_HDRS = src/omega_numeric.h src/omega_numeric_provenance.h src/omega_numeric_divsqrt_gb10.h tests/numeric_oracle.h \ $(NUMERIC_BW_HDRS) -build/test_omega_numeric_cpu: $(NUMERIC_CPU_SRCS) $(NUMERIC_CPU_HDRS) +build/test_omega_numeric_cpu: $(NUMERIC_CPU_SRCS) $(NUMERIC_CPU_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc -DOMEGA_NUMERIC_CPU_ONLY -o $@ $(NUMERIC_CPU_SRCS) + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc $(CUDAPP_HEADER_FLAGS) -DOMEGA_NUMERIC_CPU_ONLY -o $@ $(NUMERIC_CPU_SRCS) $(CUDAPP_LIB) -lpthread # test-numeric-cpu exit status: 0 means no host test failed and the only SKIPs # are the five declared chip-only IDs (CHIP_ONLY_IDS in the test; the last line # prints "Gate 5 Verdict: PASS_EXCEPT_DECLARED_CHIP_ONLY"). Nonzero means a real @@ -291,9 +236,9 @@ test-numeric-e1-exhaustive: build/test_omega_numeric_cpu REDUCE_CPU_SRCS = tests/test_omega_reduce.c src/omega_numeric_reduce.c src/omega_numeric_reduce_gb10.c \ src/omega_numeric.c src/omega_numeric_provenance.c src/omega_numeric_divsqrt_gb10.c \ $(NUMERIC_BW_SRCS) -build/test_omega_reduce_cpu: $(REDUCE_CPU_SRCS) src/omega_numeric_reduce.h $(NUMERIC_CPU_HDRS) +build/test_omega_reduce_cpu: $(REDUCE_CPU_SRCS) src/omega_numeric_reduce.h $(NUMERIC_CPU_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc -DOMEGA_NUMERIC_CPU_ONLY -o $@ $(REDUCE_CPU_SRCS) + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc $(CUDAPP_HEADER_FLAGS) -DOMEGA_NUMERIC_CPU_ONLY -o $@ $(REDUCE_CPU_SRCS) $(CUDAPP_LIB) -lpthread test-numeric-reduce-cpu: build/test_omega_reduce_cpu ./build/test_omega_reduce_cpu @@ -676,16 +621,13 @@ test-cortex: $(RX_CX_TEST) $(RX_CXJ_TEST) RX_R12_SILICON_SRCS = src/runtime/rx_caproot.c src/runtime/rx_world.c \ src/runtime/rx_coherent.c src/runtime/rx_native_bind.c \ src/runtime/rx_resident_gpu.c src/omega_om_units.c src/omega_evidence.c \ - src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c \ - src/omega_blackwell_qmd.c src/omega_blackwell_matmul.c \ - $(PHYSICS_DIR)/m16/m16_native.c $(PHYSICS_DIR)/nvrm/nvrm.c \ tests/runtime/rx_r12_silicon.c RX_R12_SILICON = $(OUT_DIR)/rx_r12_silicon_test $(RX_R12_SILICON): $(RX_R12_SILICON_SRCS) src/runtime/rx_world.h \ src/runtime/rx_resident_gpu.h src/runtime/rx_caproot.h src/runtime/aienos_cap.h \ - src/omega_blackwell_codegen.h $(AIENOS_CAP_LIB) | $(OUT_DIR) - $(CC) $(CFLAGS) -pthread -o $@ $(RX_R12_SILICON_SRCS) $(AIENOS_CAP_LIB) -ldl -lm + $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h $(AIENOS_CAP_LIB) $(CUDAPP_LIB) | check-cudapp $(OUT_DIR) + $(CC) $(CFLAGS) -pthread -o $@ $(RX_R12_SILICON_SRCS) $(AIENOS_CAP_LIB) $(CUDAPP_LIB) -ldl -lm test-r12-silicon: $(RX_R12_SILICON) ./$(RX_R12_SILICON) @@ -745,9 +687,7 @@ RX_R13_SRCS = src/runtime/rx_caproot.c src/runtime/rx_world.c \ # RX_ERR_AUTHORITY (sovereign-core abi-qualify, 2026-10-12). -include $(RXC_LIB_OBJS:.o=.d) RX_R13_TEST_SRCS = $(RX_R13_SRCS) $(RX_FABRIC_TEST_SRCS) -RX_R13_SILICON_EXTRA = src/runtime/rx_resident_gpu.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c src/omega_blackwell_matmul.c \ - $(PHYSICS_DIR)/m16/m16_native.c $(PHYSICS_DIR)/nvrm/nvrm.c +RX_R13_SILICON_EXTRA = src/runtime/rx_resident_gpu.c # Production program (rules after the ARGUS block below: they link ARGUS). RX_R13_HOST = $(OUT_DIR)/rx_r13_living_host RX_R13_SILICON = $(OUT_DIR)/rx_r13_living_silicon @@ -762,9 +702,9 @@ $(RX_R13_TEST_HOST): $(RX_R13_TEST_SRCS) src/runtime/rx_living.h $(RX_COMPOSE_LI # Lane 17: the Fabric phase runs in the silicon test build too; its Fabric part # is CPU-only loopback. The composition phase stays host-only. $(RX_R13_TEST_SILICON): $(RX_R13_TEST_SRCS) $(RX_R13_SILICON_EXTRA) src/runtime/rx_living.h \ - $(RX_COMPOSE_LIVING_CHECKS) $(RX_R13_TEST_CHECKS) $(AIENOS_CAP_LIB) | $(OUT_DIR) + $(RX_COMPOSE_LIVING_CHECKS) $(RX_R13_TEST_CHECKS) $(AIENOS_CAP_LIB) $(CUDAPP_LIB) | check-cudapp $(OUT_DIR) $(CC) $(CFLAGS) $(AIEN_TEST_FLAGS) -DR13_SILICON -pthread -o $@ $(RX_R13_TEST_SRCS) \ - $(RX_R13_SILICON_EXTRA) $(AIENOS_CAP_LIB) -ldl -lm + $(RX_R13_SILICON_EXTRA) $(AIENOS_CAP_LIB) $(CUDAPP_LIB) -ldl -lm test-r13-host: $(RX_R13_HOST) ./$(RX_R13_HOST) @@ -815,15 +755,9 @@ $(RX_R14_HOST): $(RX_R14_SRCS) src/runtime/rx_living.h $(RX_COMPOSE_LIVING_CHECK $(CC) $(CFLAGS) -pthread -o $@ $(RX_R14_SRCS) $(AIENOS_CAP_LIB) -lm $(RX_R14_SILICON): $(RX_R14_SRCS) src/runtime/rx_resident_gpu.c \ - src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c \ - src/omega_blackwell_qmd.c src/omega_blackwell_matmul.c \ - $(PHYSICS_DIR)/m16/m16_native.c $(PHYSICS_DIR)/nvrm/nvrm.c \ - $(AIENOS_CAP_LIB) | $(OUT_DIR) + $(AIENOS_CAP_LIB) $(CUDAPP_LIB) | check-cudapp $(OUT_DIR) $(CC) $(CFLAGS) -DR14_SILICON -pthread -o $@ $(RX_R14_SRCS) \ - src/runtime/rx_resident_gpu.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \ - src/omega_blackwell_matmul.c $(PHYSICS_DIR)/m16/m16_native.c \ - $(PHYSICS_DIR)/nvrm/nvrm.c $(AIENOS_CAP_LIB) -ldl -lm + src/runtime/rx_resident_gpu.c $(AIENOS_CAP_LIB) $(CUDAPP_LIB) -ldl -lm test-r14-host: $(RX_R14_HOST) ./$(RX_R14_HOST) @@ -851,9 +785,7 @@ RX_R15_RIG_SRCS = $(filter-out tests/runtime/rx_r13_living.c src/runtime/rx_oper src/runtime/rx_seq_reference.c tests/runtime/rx_r15_rig.c RX_R15_RIG_HDRS = src/runtime/rx_living.h src/runtime/rx_seq_reference.h \ src/runtime/rx_world.h tests/runtime/rx_r15_rig.h -RX_R15_GPU_SRCS = src/runtime/rx_resident_gpu.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \ - src/omega_blackwell_matmul.c $(PHYSICS_DIR)/m16/m16_native.c $(PHYSICS_DIR)/nvrm/nvrm.c +RX_R15_GPU_SRCS = src/runtime/rx_resident_gpu.c RX_R15_PARITY_HOST = $(OUT_DIR)/rx_r15_parity_host RX_R15_PARITY_SILICON = $(OUT_DIR)/rx_r15_parity_silicon @@ -863,9 +795,9 @@ $(RX_R15_PARITY_HOST): $(RX_R15_RIG_SRCS) tests/runtime/rx_r15_parity.c $(RX_R15 $(AIENOS_CAP_LIB) -lm $(RX_R15_PARITY_SILICON): $(RX_R15_RIG_SRCS) tests/runtime/rx_r15_parity.c $(RX_R15_RIG_HDRS) \ - $(RX_R15_GPU_SRCS) $(AIENOS_CAP_LIB) | $(OUT_DIR) + $(RX_R15_GPU_SRCS) $(AIENOS_CAP_LIB) $(CUDAPP_LIB) | check-cudapp $(OUT_DIR) $(CC) $(CFLAGS) -DR15_SILICON -pthread -o $@ $(RX_R15_RIG_SRCS) \ - tests/runtime/rx_r15_parity.c $(RX_R15_GPU_SRCS) $(AIENOS_CAP_LIB) -ldl -lm + tests/runtime/rx_r15_parity.c $(RX_R15_GPU_SRCS) $(AIENOS_CAP_LIB) $(CUDAPP_LIB) -ldl -lm test-r15-parity-host: $(RX_R15_PARITY_HOST) ./$(RX_R15_PARITY_HOST) @@ -887,9 +819,9 @@ R15_GPU_LOAD_SRCS = src/runtime/rx_caproot.c src/runtime/rx_world.c src/runtime/ tests/runtime/r15_gpu_load.c $(R15_GPU_LOAD): $(R15_GPU_LOAD_SRCS) $(RX_R15_GPU_SRCS) src/runtime/rx_world.h \ - $(AIENOS_CAP_LIB) | $(OUT_DIR) + $(AIENOS_CAP_LIB) $(CUDAPP_LIB) | check-cudapp $(OUT_DIR) $(CC) $(CFLAGS) -pthread -o $@ $(R15_GPU_LOAD_SRCS) $(RX_R15_GPU_SRCS) \ - $(AIENOS_CAP_LIB) -ldl -lm + $(AIENOS_CAP_LIB) $(CUDAPP_LIB) -ldl -lm r15-gpu-load: $(R15_GPU_LOAD) @@ -916,14 +848,14 @@ $(RX_R15_PERF_HOST_ND): $(RX_R15_PERF_SRCS) $(RX_R15_PERF_HDRS) $(AIENOS_CAP_LIB $(AIENOS_CAP_LIB) -ldl -lm $(RX_R15_PERF_SILICON): $(RX_R15_PERF_SRCS) $(RX_R15_PERF_HDRS) $(RX_R15_GPU_SRCS) \ - $(AIENOS_CAP_LIB) | $(OUT_DIR) + $(AIENOS_CAP_LIB) $(CUDAPP_LIB) | check-cudapp $(OUT_DIR) $(CC) $(CFLAGS) -DR15_SILICON -pthread -o $@ $(RX_R15_PERF_SRCS) $(RX_R15_GPU_SRCS) \ - $(AIENOS_CAP_LIB) -ldl -lm + $(AIENOS_CAP_LIB) $(CUDAPP_LIB) -ldl -lm $(RX_R15_PERF_SILICON_ND): $(RX_R15_PERF_SRCS) $(RX_R15_PERF_HDRS) $(RX_R15_GPU_SRCS) \ - $(AIENOS_CAP_LIB) | $(OUT_DIR) + $(AIENOS_CAP_LIB) $(CUDAPP_LIB) | check-cudapp $(OUT_DIR) $(CC) $(CFLAGS) -DR15_SILICON -DRX_MEASURE_NO_CAUSAL_DIGEST -pthread -o $@ \ - $(RX_R15_PERF_SRCS) $(RX_R15_GPU_SRCS) $(AIENOS_CAP_LIB) -ldl -lm + $(RX_R15_PERF_SRCS) $(RX_R15_GPU_SRCS) $(AIENOS_CAP_LIB) $(CUDAPP_LIB) -ldl -lm $(R15_REDUCE): tools/r15_reduce.c src/omega_om_units.c src/sha256.h | $(OUT_DIR) $(CC) $(CFLAGS) -o $@ tools/r15_reduce.c src/omega_om_units.c -lm @@ -1004,10 +936,7 @@ test-r16-authpath: $(RX_R13_HOST) $(RX_R14_HOST) test-r16-authpath-silicon: $(RX_R13_SILICON) $(RX_R14_SILICON) sh tools/r16_authpath.sh silicon $(RX_R13_SILICON) $(RX_R14_SILICON) \ $(OUT_DIR)/r16/authpath/silicon-$(R16_STAMP) $(RX_R13_SRCS) $(RX_PROD_ARGUS_SRCS) \ - src/runtime/rx_resident_gpu.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \ - src/omega_blackwell_matmul.c $(PHYSICS_DIR)/m16/m16_native.c \ - $(PHYSICS_DIR)/nvrm/nvrm.c $(AIENOS_CAP_LIB) + src/runtime/rx_resident_gpu.c $(AIENOS_CAP_LIB) $(CUDAPP_LIB) # R16-G3 checks 1-3 only (sources, link map, shared libraries, embedded names) # on the current living-system build, for CI runners. Nothing is executed, so @@ -1022,10 +951,7 @@ test-r16-authpath-linkmap: $(RX_R13_HOST) $(RX_R14_HOST) test-r16-authpath-linkmap-silicon: $(RX_R13_SILICON) $(RX_R14_SILICON) R16_G3_STATIC_ONLY=1 sh tools/r16_authpath.sh silicon $(RX_R13_SILICON) $(RX_R14_SILICON) \ $(OUT_DIR)/r16/authpath/linkmap-silicon-$(R16_STAMP) $(RX_R13_SRCS) $(RX_PROD_ARGUS_SRCS) \ - src/runtime/rx_resident_gpu.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \ - src/omega_blackwell_matmul.c $(PHYSICS_DIR)/m16/m16_native.c \ - $(PHYSICS_DIR)/nvrm/nvrm.c $(AIENOS_CAP_LIB) + src/runtime/rx_resident_gpu.c $(AIENOS_CAP_LIB) $(CUDAPP_LIB) # R16-G4: legacy paths cannot bypass authority. The R13 body (R15 rig, RES-4, # host seat) is started; a legacy context tries six acts and each must be @@ -1415,10 +1341,10 @@ test-regulate: $(RX_REGULATE_TEST) ./$(RX_REGULATE_TEST) $(RX_R13_SILICON): $(RX_R13_SRCS) $(RX_R13_SILICON_EXTRA) src/runtime/rx_living.h src/runtime/rx_argus.h \ - $(RX_COMPOSE_LIVING_CHECKS) $(ARGUS_STAMP) $(AIENOS_CAP_LIB) | $(OUT_DIR) + $(RX_COMPOSE_LIVING_CHECKS) $(ARGUS_STAMP) $(AIENOS_CAP_LIB) $(CUDAPP_LIB) | check-cudapp $(OUT_DIR) $(RX_PROD_REFUSE_TEST) $(CC) $(CFLAGS) $(RX_PROD_ARGUS_FLAGS) -DR13_SILICON -pthread -o $@ $(RX_R13_SRCS) \ - $(RX_PROD_ARGUS_SRCS) $(RX_R13_SILICON_EXTRA) $(AIENOS_CAP_LIB) -ldl -lm + $(RX_PROD_ARGUS_SRCS) $(RX_R13_SILICON_EXTRA) $(AIENOS_CAP_LIB) $(CUDAPP_LIB) -ldl -lm # Production hygiene (link map + strings + ARGUS present; host run of the # ARGUS probe where the binary can run) and the negative build test: compiling @@ -1862,15 +1788,12 @@ print-c4-requal-bin: # tests/runtime/rx_compose_gpu_skill.h. A chip run: take the quiet flag and # use tools/composition_gate.sh --gpu (clean tree, content-addressed receipt). RX_COMPOSE_GATE_GPU = $(OUT_DIR)/rx_composition_gate_gpu -RX_COMPOSE_GPU_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_gpu_wait.c \ - $(PHYSICS_DIR)/m16/m16_native.c $(PHYSICS_DIR)/nvrm/nvrm.c +RX_COMPOSE_GPU_SRCS = src/omega_vector.c src/omega_validate.c $(RX_COMPOSE_GATE_GPU): $(RX_COMPOSE_DEPS) $(RX_COMPOSE_GPU_SRCS) tests/runtime/rx_composition_gate.c \ - tests/runtime/rx_compose_gpu_skill.h | check-physics-lock $(OUT_DIR) + tests/runtime/rx_compose_gpu_skill.h $(CUDAPP_LIB) | check-physics-lock check-cudapp $(OUT_DIR) $(CC) $(CFLAGS) -DRXC_GATE_GPU -Itests/runtime -pthread -o $@ $(RX_COMPOSE_SRCS) \ - $(RX_COMPOSE_GPU_SRCS) tests/runtime/rx_composition_gate.c $(RX_COMPOSE_LINK) -ldl + $(RX_COMPOSE_GPU_SRCS) tests/runtime/rx_composition_gate.c $(RX_COMPOSE_LINK) $(CUDAPP_LIB) -ldl test-composition-gate-gpu: $(RX_COMPOSE_GATE_GPU) ./$(RX_COMPOSE_GATE_GPU) "$$(git rev-parse HEAD)" $(OUT_DIR)/composition_gate_gpu_receipt.json @@ -1888,12 +1811,11 @@ print-composition-gate-gpu-bin: # tools/run_divsqrt_gate.sh only (quiet flag, detached, receipt). DIVSQRT_SRCS = tests/test_omega_divsqrt_gb10.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric.c \ src/omega_numeric_provenance.c $(NUMERIC_BW_SRCS) -DIVSQRT_HDRS = src/omega_numeric_divsqrt_gb10.h src/omega_numeric.h src/omega_blackwell_encoder.h \ - src/omega_blackwell_qmd.h src/sha256.h +DIVSQRT_HDRS = src/omega_numeric_divsqrt_gb10.h src/omega_numeric.h $(NUMERIC_BW_HDRS) .PHONY: test-divsqrt-host test-divsqrt-nvdisasm test-divsqrt-sweep -build/test_omega_divsqrt_gb10_cpu: $(DIVSQRT_SRCS) $(DIVSQRT_HDRS) +build/test_omega_divsqrt_gb10_cpu: $(DIVSQRT_SRCS) $(DIVSQRT_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc -DOMEGA_NUMERIC_CPU_ONLY -pthread -o $@ $(DIVSQRT_SRCS) + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc $(CUDAPP_HEADER_FLAGS) -DOMEGA_NUMERIC_CPU_ONLY -pthread -o $@ $(DIVSQRT_SRCS) $(CUDAPP_LIB) test-divsqrt-host: build/test_omega_divsqrt_gb10_cpu ./build/test_omega_divsqrt_gb10_cpu test-divsqrt-nvdisasm: @@ -1910,9 +1832,9 @@ TRANSC_GB10_SRCS = tests/test_omega_numeric_transc_gb10.c src/omega_numeric_divs src/omega_numeric_transc.c src/omega_numeric.c src/omega_numeric_provenance.c \ $(NUMERIC_BW_SRCS) .PHONY: test-numeric-transc-gb10-host -build/test_omega_numeric_transc_gb10_cpu: $(TRANSC_GB10_SRCS) $(DIVSQRT_HDRS) src/omega_numeric_transc.h +build/test_omega_numeric_transc_gb10_cpu: $(TRANSC_GB10_SRCS) $(DIVSQRT_HDRS) src/omega_numeric_transc.h $(CUDAPP_LIB) | check-cudapp @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -fno-fast-math -Isrc -DOMEGA_NUMERIC_CPU_ONLY -pthread -o $@ $(TRANSC_GB10_SRCS) + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -fno-fast-math -Isrc $(CUDAPP_HEADER_FLAGS) -DOMEGA_NUMERIC_CPU_ONLY -pthread -o $@ $(TRANSC_GB10_SRCS) $(CUDAPP_LIB) test-numeric-transc-gb10-host: build/test_omega_numeric_transc_gb10_cpu ./build/test_omega_numeric_transc_gb10_cpu @@ -1931,14 +1853,12 @@ test-unwritten-trap-host: build/test_omega_unwritten_trap # docs/numeric/E1_LDST_GB10.md). test-ldst-host needs no device; test-ldst-nvdisasm # decodes every table kernel offline; the chip run is tools/run_numeric_ldst_chip.sh. LDST_SRCS = tests/test_omega_ldst_gb10.c src/omega_numeric_ldst_gb10.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric.c \ - src/omega_numeric_provenance.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c -LDST_HDRS = src/omega_numeric_ldst_gb10.h src/omega_numeric_divsqrt_gb10.h src/omega_numeric.h src/omega_blackwell_encoder.h \ - src/omega_blackwell_qmd.h src/sha256.h + src/omega_numeric_provenance.c $(NUMERIC_BW_SRCS) +LDST_HDRS = src/omega_numeric_ldst_gb10.h src/omega_numeric_divsqrt_gb10.h src/omega_numeric.h $(NUMERIC_BW_HDRS) .PHONY: test-ldst-host test-ldst-nvdisasm -build/test_omega_ldst_gb10_cpu: $(LDST_SRCS) $(LDST_HDRS) +build/test_omega_ldst_gb10_cpu: $(LDST_SRCS) $(LDST_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc -DOMEGA_NUMERIC_CPU_ONLY -pthread -o $@ $(LDST_SRCS) + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc $(CUDAPP_HEADER_FLAGS) -DOMEGA_NUMERIC_CPU_ONLY -pthread -o $@ $(LDST_SRCS) $(CUDAPP_LIB) test-ldst-host: build/test_omega_ldst_gb10_cpu ./build/test_omega_ldst_gb10_cpu test-ldst-nvdisasm: @@ -2396,9 +2316,9 @@ test-vc-bridge: tests/test_omega_vc_bridge.c src/omega_vc_bridge.c src/omega_vc_ @echo "test-vc-bridge: PASS (bridge verifies and recomputes the id, bridge records refused in build, ASan/UBSan clean, 4 mutants killed)" # FB-1 cut 1: native (no CUDA) matmul entry point for the inference stack. -# libomega_gpu.a = everything the tool links except its main; the Rust FFI crate -# (cut 2) links it. test-gpu-matmul-api runs the host-only refusals; the chip -# sweep is `./build/gpu_matmul_api_test --out receipt.json` through the heavy queue. +# libomega_gpu.a is the Omega CPU/evidence adapter companion, not a +# second GPU implementation. Consumers link it FIRST and the pinned canonical +# CUDApp archive LAST. Host-only API refusals do not qualify the chip path. .PHONY: libomega_gpu test-gpu-matmul-api # The two gate-runner objects (omegatool's M17/M18/M19 and World gates) are NOT part of the # library: nothing in the library or in the Rust FFI crate calls them (checked with nm), and @@ -2406,22 +2326,25 @@ test-vc-bridge: tests/test_omega_vc_bridge.c src/omega_vc_bridge.c src/omega_vc_ # archive digest depend on where physics was checked out. Without them libomega_gpu.a is # byte-identical for any PHYSICS_DIR and any omega checkout directory. GPU_API_OBJS = $(filter-out $(OUT_DIR)/omegatool.o $(OUT_DIR)/omega_blackwell_gates.o $(OUT_DIR)/omega_world_gates.o,$(OBJS)) +GPU_LINK_LIBS = $(OUT_DIR)/libomega_gpu.a $(CUDAPP_LIB) GPU_API_TEST = $(OUT_DIR)/gpu_matmul_api_test GPU_R4_RECEIPT = $(OUT_DIR)/gpu_matmul_r4_receipt -$(OUT_DIR)/libomega_gpu.a: $(GPU_API_OBJS) | check-physics-lock - ar rcs $@ $(GPU_API_OBJS) -libomega_gpu: $(OUT_DIR)/libomega_gpu.a +$(OUT_DIR)/libomega_gpu.a: $(GPU_API_OBJS) | check-physics-lock check-cudapp + ar rcs $@.tmp.$$$$ $(GPU_API_OBJS) && mv -f $@.tmp.$$$$ $@ +libomega_gpu: $(GPU_LINK_LIBS) # omega-mv#471: the archive must link without -lm (omegatool, the Rust FFI crate and AIENOS link it bare). Fails if any symbol # the archive leaves undefined is one libm exports (the export list is read from this toolchain's libm.so.6). .PHONY: test-gpu-libm-free -test-gpu-libm-free: $(OUT_DIR)/libomega_gpu.a +test-gpu-libm-free: $(GPU_LINK_LIBS) @export LC_ALL=C; libm="$$($(CC) -print-file-name=libm.so.6)"; test -f "$$libm" || { echo "libm-free: no libm.so.6 from $(CC)"; exit 1; }; \ - nm -D --defined-only "$$libm" | awk '{print $$3}' | sed 's/@.*//' | sort -u > $(OUT_DIR)/libm.syms; \ - nm -u $(OUT_DIR)/libomega_gpu.a | awk '{print $$2}' | sort -u | comm -12 - $(OUT_DIR)/libm.syms > $(OUT_DIR)/libm-refs.txt; \ - n=$$(wc -l < $(OUT_DIR)/libm-refs.txt); echo "libm-free: $$n libm symbols referenced by libomega_gpu.a ($$(wc -l < $(OUT_DIR)/libm.syms) libm exports checked)"; \ - if [ "$$n" -ne 0 ]; then sed 's/^/ /' $(OUT_DIR)/libm-refs.txt; echo "FAIL: libomega_gpu.a is not libm-free"; exit 1; fi; echo "PASS: libomega_gpu.a is libm-free" -$(GPU_API_TEST): tests/gpu_matmul_api_test.c src/omega_gpu_matmul_api.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -o $@ tests/gpu_matmul_api_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm + nm -D --defined-only "$$libm" > $(OUT_DIR)/libm-exports.raw || exit $$?; \ + awk '{print $$3}' $(OUT_DIR)/libm-exports.raw | sed 's/@.*//' | sort -u > $(OUT_DIR)/libm.syms; \ + nm -u $(GPU_LINK_LIBS) > $(OUT_DIR)/gpu-undefined.raw || exit $$?; \ + awk '{print $$2}' $(OUT_DIR)/gpu-undefined.raw | sort -u | comm -12 - $(OUT_DIR)/libm.syms > $(OUT_DIR)/libm-refs.txt; \ + n=$$(wc -l < $(OUT_DIR)/libm-refs.txt); echo "libm-free: $$n libm symbols referenced by the adapter plus canonical GPU archives ($$(wc -l < $(OUT_DIR)/libm.syms) libm exports checked)"; \ + if [ "$$n" -ne 0 ]; then sed 's/^/ /' $(OUT_DIR)/libm-refs.txt; echo "FAIL: adapter plus canonical GPU archives are not libm-free"; exit 1; fi; echo "PASS: adapter plus canonical GPU archives are libm-free" +$(GPU_API_TEST): tests/gpu_matmul_api_test.c $(CUDAPP_SOURCE)/src/omega_gpu_matmul_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ tests/gpu_matmul_api_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-matmul-api: $(GPU_API_TEST) $(GPU_R4_RECEIPT) ./$(GPU_API_TEST) --host-only ./$(GPU_R4_RECEIPT) --host-only @@ -2429,8 +2352,8 @@ test-gpu-matmul-api: $(GPU_API_TEST) $(GPU_R4_RECEIPT) # omega #473 R4: the sealed CTA-budget receipt (full-output comparison at the training shapes, # every budget, repeats, I42 stale-output check, negative controls). Host-only self-test above; the # chip receipt is `quietlock run -- ./build/gpu_matmul_r4_receipt --out receipt.json`. -$(GPU_R4_RECEIPT): tests/gpu_matmul_r4_receipt.c src/omega_gpu_matmul_api.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -o $@ tests/gpu_matmul_r4_receipt.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_R4_RECEIPT): tests/gpu_matmul_r4_receipt.c $(CUDAPP_SOURCE)/src/omega_gpu_matmul_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ tests/gpu_matmul_r4_receipt.c $(GPU_LINK_LIBS) -lpthread -lm # FB-1 cut 4: native rmsnorm / rope / swiglu (+ EX2 and shared-exchange probes). # test-gpu-elementwise is host-only (refusals, codegen, word fixtures, nvdisasm @@ -2438,8 +2361,8 @@ $(GPU_R4_RECEIPT): tests/gpu_matmul_r4_receipt.c src/omega_gpu_matmul_api.h $(OU # through the heavy queue. -ffp-contract=off keeps the f32 oracle free of FMA. .PHONY: test-gpu-elementwise GPU_EW_TEST = $(OUT_DIR)/gpu_elementwise_test -$(GPU_EW_TEST): tests/gpu_elementwise_test.c src/omega_gpu_elementwise_api.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_elementwise_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_EW_TEST): tests/gpu_elementwise_test.c $(CUDAPP_SOURCE)/src/omega_gpu_elementwise_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_elementwise_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-elementwise: $(GPU_EW_TEST) ./$(GPU_EW_TEST) --host-only @@ -2447,8 +2370,8 @@ test-gpu-elementwise: $(GPU_EW_TEST) # into instruction word 3. Host only; the golden-word checks compare words 0..2, so this is the check for word 3. .PHONY: test-bw-encode-control BW_ENCODE_CONTROL_TEST = $(OUT_DIR)/bw_encode_control_test -$(BW_ENCODE_CONTROL_TEST): tests/bw_encode_control_test.c src/omega_blackwell_codegen.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -o $@ tests/bw_encode_control_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(BW_ENCODE_CONTROL_TEST): tests/bw_encode_control_test.c $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ tests/bw_encode_control_test.c $(GPU_LINK_LIBS) -lpthread -lm test-bw-encode-control: $(BW_ENCODE_CONTROL_TEST) ./$(BW_ENCODE_CONTROL_TEST) @@ -2458,8 +2381,8 @@ test-bw-encode-control: $(BW_ENCODE_CONTROL_TEST) # controls); the chip gate is tools/run_gpu_reconv_chip.sh. .PHONY: test-gpu-reconv GPU_RECONV_TEST = $(OUT_DIR)/gpu_reconv_test -$(GPU_RECONV_TEST): tests/gpu_reconv_test.c tests/bw_warp_sim.h src/omega_gpu_elementwise_api.h src/omega_bw_reconv.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -Itests -o $@ tests/gpu_reconv_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_RECONV_TEST): tests/gpu_reconv_test.c tests/bw_warp_sim.h $(CUDAPP_SOURCE)/src/omega_gpu_elementwise_api.h $(CUDAPP_SOURCE)/src/omega_bw_reconv.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -Itests -o $@ tests/gpu_reconv_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-reconv: $(GPU_RECONV_TEST) ./$(GPU_RECONV_TEST) --host-only @@ -2472,8 +2395,8 @@ test-gpu-reconv: $(GPU_RECONV_TEST) # (tools/run_gpu_attention_chip.sh). -ffp-contract=off keeps the oracle free of FMA. .PHONY: test-gpu-attention GPU_ATTN_TEST = $(OUT_DIR)/gpu_attention_test -$(GPU_ATTN_TEST): tests/gpu_attention_test.c tests/bw_warp_sim.h src/omega_gpu_attention_api.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_attention_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_ATTN_TEST): tests/gpu_attention_test.c tests/bw_warp_sim.h $(CUDAPP_SOURCE)/src/omega_gpu_attention_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_attention_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-attention: $(GPU_ATTN_TEST) ./$(GPU_ATTN_TEST) --host-only ./$(GPU_ATTN_TEST) --sim @@ -2483,15 +2406,15 @@ test-gpu-attention: $(GPU_ATTN_TEST) ./$(GPU_ATTN_TEST) --hd 128 --divergent --sim # FB-1 cut 4b: fresh-process device-open probe (flake investigation, tools/probe_gpu_open.sh) -$(OUT_DIR)/gpu_session_probe: tests/gpu_session_probe.c src/omega_gpu_session.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -o $@ tests/gpu_session_probe.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(OUT_DIR)/gpu_session_probe: tests/gpu_session_probe.c $(CUDAPP_SOURCE)/src/omega_gpu_session.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ tests/gpu_session_probe.c $(GPU_LINK_LIBS) -lpthread -lm # OWN-30B cut 2: window matmul gate (tests/gpu_moe_window_test.c). test-gpu-moe-window runs the host-only # refusals and the packed-window byte rule; the chip gate is `./build/gpu_moe_window_test --out r.json` # under /tmp/aien-gb10.lock (equivalence to the whole-tensor columns, mutants, window timing). GPU_MOE_TEST = $(OUT_DIR)/gpu_moe_window_test -$(GPU_MOE_TEST): tests/gpu_moe_window_test.c src/omega_gpu_moe_api.h src/omega_gpu_matmul_api.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -o $@ tests/gpu_moe_window_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_MOE_TEST): tests/gpu_moe_window_test.c $(CUDAPP_SOURCE)/src/omega_gpu_moe_api.h $(CUDAPP_SOURCE)/src/omega_gpu_matmul_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ tests/gpu_moe_window_test.c $(GPU_LINK_LIBS) -lpthread -lm .PHONY: test-gpu-moe-window test-gpu-moe-window: $(GPU_MOE_TEST) ./$(GPU_MOE_TEST) --host-only @@ -2502,8 +2425,8 @@ test-gpu-moe-window: $(GPU_MOE_TEST) # -ffp-contract=off keeps the double oracle free of FMA. .PHONY: test-gpu-fp8 GPU_FP8_TEST = $(OUT_DIR)/gpu_fp8_api_test -$(GPU_FP8_TEST): tests/gpu_fp8_api_test.c tests/bw_warp_sim.h src/omega_gpu_fp8_api.h src/omega_blackwell_codegen_moe.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_fp8_api_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_FP8_TEST): tests/gpu_fp8_api_test.c tests/bw_warp_sim.h $(CUDAPP_SOURCE)/src/omega_gpu_fp8_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_moe.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_fp8_api_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-fp8: $(GPU_FP8_TEST) ./$(GPU_FP8_TEST) --host-only AIEN_OMEGA_FP8_COAL=0 ./$(GPU_FP8_TEST) --coal-default @@ -2513,15 +2436,15 @@ test-gpu-fp8: $(GPU_FP8_TEST) # omega #457 (2026-10-15): host rewrite of a GPU-cached buffer must be visible to the next launch. Chip only; the gate # is tools/run_gpu_l2_stale_chip.sh. GPU_L2_STALE_TEST = $(OUT_DIR)/gpu_l2_stale_test -$(GPU_L2_STALE_TEST): tests/gpu_l2_stale_test.c src/omega_gpu_fp8_api.h src/omega_gpu_session.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_l2_stale_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_L2_STALE_TEST): tests/gpu_l2_stale_test.c $(CUDAPP_SOURCE)/src/omega_gpu_fp8_api.h $(CUDAPP_SOURCE)/src/omega_gpu_session.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_l2_stale_test.c $(GPU_LINK_LIBS) -lpthread -lm # OWN-30B cut 8 (2026-10-13): one-launch decode attention (omega_gpu_decode_attn_api.h). test-gpu-decode-attn is # host-only + simulator; the chip gate is tools/run_gpu_decode_attn_chip.sh. .PHONY: test-gpu-decode-attn GPU_DATTN_TEST = $(OUT_DIR)/gpu_decode_attn_test -$(GPU_DATTN_TEST): tests/gpu_decode_attn_test.c tests/bw_warp_sim_k.h src/omega_gpu_decode_attn_api.h src/omega_blackwell_codegen_attn.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_decode_attn_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_DATTN_TEST): tests/gpu_decode_attn_test.c tests/bw_warp_sim_k.h $(CUDAPP_SOURCE)/src/omega_gpu_decode_attn_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_attn.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_decode_attn_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-decode-attn: $(GPU_DATTN_TEST) $(GPU_DATTN_TEST) --host-only $(GPU_DATTN_TEST) --sim @@ -2531,8 +2454,8 @@ test-gpu-decode-attn: $(GPU_DATTN_TEST) # tools/run_gpu_decode_attn256_chip.sh. .PHONY: test-gpu-decode-attn256 GPU_DATTN256_TEST = $(OUT_DIR)/gpu_decode_attn256_test -$(GPU_DATTN256_TEST): tests/gpu_decode_attn256_test.c tests/bw_warp_sim_k.h src/omega_gpu_decode_attn256_api.h src/omega_blackwell_codegen_attn256.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_decode_attn256_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_DATTN256_TEST): tests/gpu_decode_attn256_test.c tests/bw_warp_sim_k.h $(CUDAPP_SOURCE)/src/omega_gpu_decode_attn256_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_attn256.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_decode_attn256_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-decode-attn256: $(GPU_DATTN256_TEST) $(GPU_DATTN256_TEST) --host-only $(GPU_DATTN256_TEST) --sim @@ -2541,8 +2464,8 @@ test-gpu-decode-attn256: $(GPU_DATTN256_TEST) # (oracle, budgets) plus the warp simulator; the chip gate is tools/run_gpu_router_chip.sh under the GB10 lock. .PHONY: test-gpu-router GPU_ROUTER_TEST = $(OUT_DIR)/gpu_router_test -$(GPU_ROUTER_TEST): tests/gpu_router_test.c tests/bw_warp_sim_k.h src/omega_gpu_router_api.h src/omega_blackwell_codegen_router.h src/omega_gpu_fp8_api.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_router_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_ROUTER_TEST): tests/gpu_router_test.c tests/bw_warp_sim_k.h $(CUDAPP_SOURCE)/src/omega_gpu_router_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_router.h $(CUDAPP_SOURCE)/src/omega_gpu_fp8_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_router_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-router: $(GPU_ROUTER_TEST) ./$(GPU_ROUTER_TEST) --host-only ./$(GPU_ROUTER_TEST) --sim @@ -2551,15 +2474,15 @@ test-gpu-router: $(GPU_ROUTER_TEST) # test-gpu-gdn is host-only plus the warp simulator over the whole grid; the chip run is ./build/gpu_gdn_test under the GB10 lock. .PHONY: test-gpu-gdn GPU_GDN_TEST = $(OUT_DIR)/gpu_gdn_test -$(GPU_GDN_TEST): tests/gpu_gdn_test.c tests/bw_warp_sim_k.h src/omega_gpu_gdn_api.h src/omega_blackwell_codegen_gdn.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_gdn_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_GDN_TEST): tests/gpu_gdn_test.c tests/bw_warp_sim_k.h $(CUDAPP_SOURCE)/src/omega_gpu_gdn_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_gdn.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_gdn_test.c $(GPU_LINK_LIBS) -lpthread -lm # L369: the multi-token GDN decode == T decode steps bit for bit (--sim: simulator; default: the chip, under the GB10 lock) GPU_GDN_MULTI_TEST = $(OUT_DIR)/gpu_gdn_multi_test -$(GPU_GDN_MULTI_TEST): tests/gpu_gdn_multi_test.c tests/bw_warp_sim_k.h src/omega_gpu_gdn_api.h src/omega_blackwell_codegen_gdn.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_gdn_multi_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_GDN_MULTI_TEST): tests/gpu_gdn_multi_test.c tests/bw_warp_sim_k.h $(CUDAPP_SOURCE)/src/omega_gpu_gdn_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_gdn.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_gdn_multi_test.c $(GPU_LINK_LIBS) -lpthread -lm GPU_DATTN256_MULTI_TEST = $(OUT_DIR)/gpu_dattn256_multi_test -$(GPU_DATTN256_MULTI_TEST): tests/gpu_dattn256_multi_test.c src/omega_gpu_decode_attn256_api.h src/omega_blackwell_codegen_attn256.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -Itests -o $@ tests/gpu_dattn256_multi_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_DATTN256_MULTI_TEST): tests/gpu_dattn256_multi_test.c $(CUDAPP_SOURCE)/src/omega_gpu_decode_attn256_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_attn256.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -Itests -o $@ tests/gpu_dattn256_multi_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-gdn: $(GPU_GDN_TEST) ./$(GPU_GDN_TEST) --host-only ./$(GPU_GDN_TEST) --sim @@ -2569,8 +2492,8 @@ test-gpu-gdn: $(GPU_GDN_TEST) # gate is tools/run_gpu_bf16_gemv_chip.sh under the GB10 lock. .PHONY: test-gpu-bf16-gemv GPU_BF16_TEST = $(OUT_DIR)/gpu_bf16_gemv_test -$(GPU_BF16_TEST): tests/gpu_bf16_gemv_test.c tests/bw_warp_sim_k.h src/omega_gpu_bf16_gemv_api.h src/omega_blackwell_codegen_bf16.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_bf16_gemv_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_BF16_TEST): tests/gpu_bf16_gemv_test.c tests/bw_warp_sim_k.h $(CUDAPP_SOURCE)/src/omega_gpu_bf16_gemv_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_bf16.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_bf16_gemv_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-bf16-gemv: $(GPU_BF16_TEST) $(GPU_BF16_TEST) --host-only $(GPU_BF16_TEST) --sim @@ -2580,30 +2503,30 @@ test-gpu-bf16-gemv: $(GPU_BF16_TEST) # epilogue, mutants 1-3 caught); the chip gate is tools/run_gpu_tern_chip.sh with the quiet flag held. .PHONY: test-gpu-tern GPU_TERN_TEST = $(OUT_DIR)/gpu_tern_test -$(GPU_TERN_TEST): tests/gpu_tern_test.c tests/bw_warp_sim_k.h src/omega_gpu_tern_api.h src/omega_blackwell_codegen_tern.h $(OMA_RZ_SRCS) $(OMA_RZ_HDRS) $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off $(OMA_RZ_ARCH) -Itests -o $@ tests/gpu_tern_test.c $(OMA_RZ_SRCS) $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_TERN_TEST): tests/gpu_tern_test.c tests/bw_warp_sim_k.h $(CUDAPP_SOURCE)/src/omega_gpu_tern_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_tern.h $(OMA_RZ_SRCS) $(OMA_RZ_HDRS) $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off $(OMA_RZ_ARCH) -Itests -o $@ tests/gpu_tern_test.c $(OMA_RZ_SRCS) $(GPU_LINK_LIBS) -lpthread -lm test-gpu-tern: $(GPU_TERN_TEST) $(GPU_TERN_TEST) --host-only $(GPU_TERN_TEST) --sim # OWN-30B (2026-10-13): report-only lm_head study, fp8 vs bf16 argmax agreement on the real checkpoint (chip, GB10 lock). -$(OUT_DIR)/gpu_lmhead_fp8_study: tests/gpu_lmhead_fp8_study.c src/omega_gpu_bf16_gemv_api.h src/omega_gpu_fp8_api.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -O2 -o $@ tests/gpu_lmhead_fp8_study.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(OUT_DIR)/gpu_lmhead_fp8_study: tests/gpu_lmhead_fp8_study.c $(CUDAPP_SOURCE)/src/omega_gpu_bf16_gemv_api.h $(CUDAPP_SOURCE)/src/omega_gpu_fp8_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -O2 -o $@ tests/gpu_lmhead_fp8_study.c $(GPU_LINK_LIBS) -lpthread -lm # OWN-30B prefill (2026-10-13): FP8 grouped GEMM (omega_gpu_fp8gemm_api.h). test-gpu-fp8gemm is host-only (emulation, # permutation, budgets) plus the warp simulator (512 threads); the chip gate is tools/run_gpu_fp8gemm_chip.sh under the GB10 lock. .PHONY: test-gpu-fp8gemm GPU_FP8GEMM_TEST = $(OUT_DIR)/gpu_fp8gemm_test -$(GPU_FP8GEMM_TEST): tests/gpu_fp8gemm_test.c tests/bw_warp_sim_k.h src/omega_gpu_fp8gemm_api.h src/omega_blackwell_codegen_gemm.h src/omega_gpu_fp8_api.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/gpu_fp8gemm_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_FP8GEMM_TEST): tests/gpu_fp8gemm_test.c tests/bw_warp_sim_k.h $(CUDAPP_SOURCE)/src/omega_gpu_fp8gemm_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_gemm.h $(CUDAPP_SOURCE)/src/omega_gpu_fp8_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/gpu_fp8gemm_test.c $(GPU_LINK_LIBS) -lpthread -lm # Qwen3.6-35B (sc L306 / L312) host-only simulator checks of the decode glue kernels, and the codegen hash pin Q36_DEC_SIM_TEST = $(OUT_DIR)/q36_dec_sim_test -$(Q36_DEC_SIM_TEST): tests/q36_dec_sim_test.c tests/bw_warp_sim_k.h src/omega_blackwell_codegen_dec.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/q36_dec_sim_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(Q36_DEC_SIM_TEST): tests/q36_dec_sim_test.c tests/bw_warp_sim_k.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_dec.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/q36_dec_sim_test.c $(GPU_LINK_LIBS) -lpthread -lm Q36_CODEGEN_HASH = $(OUT_DIR)/q36_codegen_hash -$(Q36_CODEGEN_HASH): tests/q36_codegen_hash.c $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -Itests -o $@ tests/q36_codegen_hash.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(Q36_CODEGEN_HASH): tests/q36_codegen_hash.c $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -Itests -o $@ tests/q36_codegen_hash.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-fp8gemm: $(GPU_FP8GEMM_TEST) $(GPU_FP8GEMM_TEST) --host-only $(GPU_FP8GEMM_TEST) --sim @@ -2611,56 +2534,56 @@ test-gpu-fp8gemm: $(GPU_FP8GEMM_TEST) # OWN-30B (2026-10-13): host-only audit that every launcher declares peak + 2 registers (the chip hung at peak + 1). .PHONY: test-gpu-gpr-boundary GPU_GPR_BOUNDARY_TEST = $(OUT_DIR)/gpu_gpr_boundary_test -$(GPU_GPR_BOUNDARY_TEST): tests/gpu_gpr_boundary_test.c src/omega_blackwell_codegen.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -o $@ tests/gpu_gpr_boundary_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_GPR_BOUNDARY_TEST): tests/gpu_gpr_boundary_test.c $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ tests/gpu_gpr_boundary_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-gpr-boundary: $(GPU_GPR_BOUNDARY_TEST) $(GPU_GPR_BOUNDARY_TEST) # OWN-30B T3 (2026-10-13): HMMA arithmetic probe (host model self-checks; chip run under the GB10 lock). GPU_TC_PROBE_TEST = $(OUT_DIR)/gpu_tc_probe_test -$(GPU_TC_PROBE_TEST): tests/gpu_tc_probe_test.c tests/bw_hmma_model.h src/omega_blackwell_codegen_tc.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_tc_probe_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_TC_PROBE_TEST): tests/gpu_tc_probe_test.c tests/bw_hmma_model.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_tc.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_tc_probe_test.c $(GPU_LINK_LIBS) -lpthread -lm GPU_TCGEMM_TEST = $(OUT_DIR)/gpu_tcgemm_test -$(GPU_TCGEMM_TEST): tests/gpu_tcgemm_test.c tests/bw_hmma_model.h tests/bw_warp_sim_tc.h src/omega_blackwell_codegen_tc.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/gpu_tcgemm_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_TCGEMM_TEST): tests/gpu_tcgemm_test.c tests/bw_hmma_model.h tests/bw_warp_sim_tc.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_tc.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/gpu_tcgemm_test.c $(GPU_LINK_LIBS) -lpthread -lm GPU_TC_PEAK_TEST = $(OUT_DIR)/gpu_tc_peak_test -$(GPU_TC_PEAK_TEST): tests/gpu_tc_peak_test.c tests/bw_hmma_model.h tests/bw_warp_sim_tc.h src/omega_blackwell_codegen_tc.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/gpu_tc_peak_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_TC_PEAK_TEST): tests/gpu_tc_peak_test.c tests/bw_hmma_model.h tests/bw_warp_sim_tc.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_tc.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/gpu_tc_peak_test.c $(GPU_LINK_LIBS) -lpthread -lm # OWN-30B L1 attention (2026-10-13): tensor-core causal prefill attention. --host-only and --sim are host proofs; # the chip gate is tools/run_gpu_prefill_attn_chip.sh. GPU_PATTN_TEST = $(OUT_DIR)/gpu_prefill_attn_test -$(GPU_PATTN_TEST): tests/gpu_prefill_attn_test.c tests/bw_hmma_model.h tests/bw_warp_sim_pa.h src/omega_gpu_prefill_attn_api.h src/omega_blackwell_codegen_pattn.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=256 -Itests -o $@ tests/gpu_prefill_attn_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_PATTN_TEST): tests/gpu_prefill_attn_test.c tests/bw_hmma_model.h tests/bw_warp_sim_pa.h $(CUDAPP_SOURCE)/src/omega_gpu_prefill_attn_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_pattn.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=256 -Itests -o $@ tests/gpu_prefill_attn_test.c $(GPU_LINK_LIBS) -lpthread -lm # Qwen3.8-27B (omega-mv#545, 2026-10-18): head_dim 256 prefill attention on the decode cache. --host-only and --sim # are host proofs; the chip run is the default mode (under the GB10 lock). GPU_PATTN256_TEST = $(OUT_DIR)/gpu_prefill_attn256_test -$(GPU_PATTN256_TEST): tests/gpu_prefill_attn256_test.c tests/bw_hmma_model.h tests/bw_warp_sim_pa.h src/omega_gpu_prefill_attn256_api.h src/omega_blackwell_codegen_pattn256.h src/omega_blackwell_codegen_attn256.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=256 -Itests -o $@ tests/gpu_prefill_attn256_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_PATTN256_TEST): tests/gpu_prefill_attn256_test.c tests/bw_hmma_model.h tests/bw_warp_sim_pa.h $(CUDAPP_SOURCE)/src/omega_gpu_prefill_attn256_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_pattn256.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_attn256.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=256 -Itests -o $@ tests/gpu_prefill_attn256_test.c $(GPU_LINK_LIBS) -lpthread -lm # OWN-30B T3b (2026-10-13): device-resident prefill module tests (host sim first; chip parts under the GB10 lock) GPU_PF_MEM_TEST = $(OUT_DIR)/gpu_pf_mem_test -$(GPU_PF_MEM_TEST): tests/gpu_pf_mem_test.c tests/bw_warp_sim_tc.h src/omega_gpu_prefill.h src/omega_blackwell_codegen_pf.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/gpu_pf_mem_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_PF_MEM_TEST): tests/gpu_pf_mem_test.c tests/bw_warp_sim_tc.h $(CUDAPP_SOURCE)/src/omega_gpu_prefill.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_pf.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/gpu_pf_mem_test.c $(GPU_LINK_LIBS) -lpthread -lm GPU_PFGEMM_TEST = $(OUT_DIR)/gpu_pfgemm_test -$(GPU_PFGEMM_TEST): tests/gpu_pfgemm_test.c tests/bw_hmma_model.h tests/bw_warp_sim_tc.h src/omega_gpu_prefill.h src/omega_blackwell_codegen_tc2.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/gpu_pfgemm_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_PFGEMM_TEST): tests/gpu_pfgemm_test.c tests/bw_hmma_model.h tests/bw_warp_sim_tc.h $(CUDAPP_SOURCE)/src/omega_gpu_prefill.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_tc2.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=512 -Itests -o $@ tests/gpu_pfgemm_test.c $(GPU_LINK_LIBS) -lpthread -lm GPU_QMMA_PROBE_TEST = $(OUT_DIR)/gpu_qmma_probe_test -$(GPU_QMMA_PROBE_TEST): tests/gpu_qmma_probe_test.c tests/bw_qmma_model.h src/omega_blackwell_codegen_qmma.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_qmma_probe_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_QMMA_PROBE_TEST): tests/gpu_qmma_probe_test.c tests/bw_qmma_model.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_qmma.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_qmma_probe_test.c $(GPU_LINK_LIBS) -lpthread -lm GPU_QGEMM_TEST = $(OUT_DIR)/gpu_qgemm_test -$(GPU_QGEMM_TEST): tests/gpu_qgemm_test.c tests/bw_qmma_model.h tests/bw_warp_sim_tc.h src/omega_gpu_prefill.h src/omega_blackwell_codegen_qg.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=1024 -Itests -o $@ tests/gpu_qgemm_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_QGEMM_TEST): tests/gpu_qgemm_test.c tests/bw_qmma_model.h tests/bw_warp_sim_tc.h $(CUDAPP_SOURCE)/src/omega_gpu_prefill.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_qg.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=1024 -Itests -o $@ tests/gpu_qgemm_test.c $(GPU_LINK_LIBS) -lpthread -lm GPU_PFHOST_TEST = $(OUT_DIR)/gpu_pfhost_test -$(GPU_PFHOST_TEST): tests/gpu_pfhost_test.c tests/bw_warp_sim_tc.h src/omega_gpu_pfhost.h src/omega_blackwell_codegen_pfhost.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=1024 -Itests -o $@ tests/gpu_pfhost_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_PFHOST_TEST): tests/gpu_pfhost_test.c tests/bw_warp_sim_tc.h $(CUDAPP_SOURCE)/src/omega_gpu_pfhost.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_pfhost.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -DWS_MAX_THREADS=1024 -Itests -o $@ tests/gpu_pfhost_test.c $(GPU_LINK_LIBS) -lpthread -lm # OWN-30B W-L2 (2026-10-13): command list (many launches, one submission) + decode glue kernels. test-gpu-cmdlist is # host-only + warp simulator; the chip gate is tools/run_gpu_cmdlist_chip.sh under the GB10 lock. .PHONY: test-gpu-cmdlist GPU_CMDLIST_TEST = $(OUT_DIR)/gpu_cmdlist_test -$(GPU_CMDLIST_TEST): tests/gpu_cmdlist_test.c tests/bw_warp_sim_k.h src/omega_gpu_cmdlist.h src/omega_blackwell_codegen_dec.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_cmdlist_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_CMDLIST_TEST): tests/gpu_cmdlist_test.c tests/bw_warp_sim_k.h $(CUDAPP_SOURCE)/src/omega_gpu_cmdlist.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_dec.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_cmdlist_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-cmdlist: $(GPU_CMDLIST_TEST) ./$(GPU_CMDLIST_TEST) --host-only ./$(GPU_CMDLIST_TEST) --sim @@ -2670,8 +2593,8 @@ test-gpu-cmdlist: $(GPU_CMDLIST_TEST) # with no flag, under the GB10 lock (timings need an exclusive window). .PHONY: test-gpu-streams GPU_STREAMS_TEST = $(OUT_DIR)/gpu_streams_test -$(GPU_STREAMS_TEST): tests/gpu_streams_test.c tests/bw_warp_sim.h src/omega_gpu_cmdlist.h src/omega_bw_em.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_streams_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_STREAMS_TEST): tests/gpu_streams_test.c tests/bw_warp_sim.h $(CUDAPP_SOURCE)/src/omega_gpu_cmdlist.h $(CUDAPP_SOURCE)/src/omega_bw_em.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_streams_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-streams: $(GPU_STREAMS_TEST) ./$(GPU_STREAMS_TEST) --sim @@ -2680,8 +2603,8 @@ test-gpu-streams: $(GPU_STREAMS_TEST) # the chip tier is "$(GPU_ISOLATION_TEST)" with no flag, under the GB10 lock. .PHONY: test-gpu-isolation GPU_ISOLATION_TEST = $(OUT_DIR)/gpu_isolation_test -$(GPU_ISOLATION_TEST): tests/gpu_isolation_test.c tests/bw_warp_sim.h src/omega_gpu_session.h src/omega_bw_em.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_isolation_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_ISOLATION_TEST): tests/gpu_isolation_test.c tests/bw_warp_sim.h $(CUDAPP_SOURCE)/src/omega_gpu_session.h $(CUDAPP_SOURCE)/src/omega_bw_em.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_isolation_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-isolation: $(GPU_ISOLATION_TEST) ./$(GPU_ISOLATION_TEST) --host-only @@ -2689,39 +2612,39 @@ test-gpu-isolation: $(GPU_ISOLATION_TEST) # host-only; the chip gate is tools/run_gpu_decode_graph_chip.sh under the GB10 lock. .PHONY: test-gpu-decode-graph GPU_DECODE_GRAPH_TEST = $(OUT_DIR)/gpu_decode_graph_test -$(GPU_DECODE_GRAPH_TEST): tests/gpu_decode_graph_test.c src/omega_gpu_decode_graph.h src/omega_gpu_cmdlist.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_decode_graph_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_DECODE_GRAPH_TEST): tests/gpu_decode_graph_test.c $(CUDAPP_SOURCE)/src/omega_gpu_decode_graph.h $(CUDAPP_SOURCE)/src/omega_gpu_cmdlist.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_decode_graph_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-decode-graph: $(GPU_DECODE_GRAPH_TEST) ./$(GPU_DECODE_GRAPH_TEST) --host-only # OWN-30B W-L2c (2026-10-14): per-launch fixed cost inside a command list (tests/gpu_launch_cost_test.c, chip only, GB10 lock). GPU_LAUNCH_COST_TEST = $(OUT_DIR)/gpu_launch_cost_test -$(GPU_LAUNCH_COST_TEST): tests/gpu_launch_cost_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_launch_cost_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_LAUNCH_COST_TEST): tests/gpu_launch_cost_test.c $(CUDAPP_SOURCE)/src/omega_gpu_fp8_api.h $(CUDAPP_SOURCE)/src/omega_gpu_cmdlist.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_launch_cost_test.c $(GPU_LINK_LIBS) -lpthread -lm # OWN-30B W-L2d (2026-10-14): L2 reuse of FP8 GEMV weights between two launches of one list (tests/gpu_l2_reuse_test.c, chip only, GB10 lock). 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 +$(GPU_L2_REUSE_TEST): tests/gpu_l2_reuse_test.c $(CUDAPP_SOURCE)/src/omega_gpu_fp8_api.h $(CUDAPP_SOURCE)/src/omega_gpu_cmdlist.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_l2_reuse_test.c $(GPU_LINK_LIBS) -lpthread -lm # sc #642 (2026-10-18): Qwen3.8-27B decode graph (one token = one command list), chip test vs the APIs one call at a time .PHONY: test-gpu-q38-graph-host GPU_Q38_GRAPH_TEST = $(OUT_DIR)/gpu_q38_graph_test -$(GPU_Q38_GRAPH_TEST): tests/gpu_q38_graph_test.c src/omega_gpu_q38_graph.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_q38_graph_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_Q38_GRAPH_TEST): tests/gpu_q38_graph_test.c $(CUDAPP_SOURCE)/src/omega_gpu_q38_graph.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_q38_graph_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-q38-graph-host: $(GPU_Q38_GRAPH_TEST) ./$(GPU_Q38_GRAPH_TEST) --host-only # HUM L314 exact two-pass lm_head (XBOUND simulator proofs; the chip run comes with the export) GPU_EXACT_HEAD_TEST = $(OUT_DIR)/gpu_exact_head_test -$(GPU_EXACT_HEAD_TEST): tests/gpu_exact_head_test.c tests/bw_warp_sim_k.h src/omega_blackwell_codegen_dec.h src/omega_gpu_bf16_gemv_api.h src/omega_gpu_fp8_api.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_exact_head_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_EXACT_HEAD_TEST): tests/gpu_exact_head_test.c tests/bw_warp_sim_k.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_dec.h $(CUDAPP_SOURCE)/src/omega_gpu_bf16_gemv_api.h $(CUDAPP_SOURCE)/src/omega_gpu_fp8_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_exact_head_test.c $(GPU_LINK_LIBS) -lpthread -lm # C3 (docs/OMEGA.md): sum, max, min and prefix sum of any length 1..2^28, bit-exact against the frozen order. # test-gpu-scan: host refusals, codegen, references vs exact sums and vs the E1 reference, then the warp simulator # (both orders, mutants caught). The chip tier is "$(GPU_SCAN_TEST)" with no flag, under the GB10 lock. GPU_SCAN_TEST = $(OUT_DIR)/gpu_scan_test -$(GPU_SCAN_TEST): tests/gpu_scan_test.c tests/bw_warp_sim.h src/omega_gpu_scan.h src/omega_numeric_reduce.c src/omega_numeric.c $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_scan_test.c src/omega_numeric_reduce.c src/omega_numeric.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_SCAN_TEST): tests/gpu_scan_test.c tests/bw_warp_sim.h $(CUDAPP_SOURCE)/src/omega_gpu_scan.h src/omega_numeric_reduce.c src/omega_numeric.c $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_scan_test.c src/omega_numeric_reduce.c src/omega_numeric.c $(GPU_LINK_LIBS) -lpthread -lm .PHONY: test-gpu-scan test-gpu-scan: $(GPU_SCAN_TEST) ./$(GPU_SCAN_TEST) --sim @@ -2730,8 +2653,8 @@ test-gpu-scan: $(GPU_SCAN_TEST) # against the chip-measured tensor-core model. test-gpu-gemm: host refusals and codegen, then the warp simulator. # The chip tier is "$(GPU_GEMM_TEST)" with no flag (>= 200 shapes up to 8192, speed vs the measured ceiling), under the GB10 lock. GPU_GEMM_TEST = $(OUT_DIR)/gpu_gemm_test -$(GPU_GEMM_TEST): tests/gpu_gemm_test.c tests/bw_warp_sim_tc.h tests/bw_hmma_model.h tests/bw_qmma_model.h src/omega_gpu_gemm.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_gemm_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_GEMM_TEST): tests/gpu_gemm_test.c tests/bw_warp_sim_tc.h tests/bw_hmma_model.h tests/bw_qmma_model.h $(CUDAPP_SOURCE)/src/omega_gpu_gemm.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -Itests -o $@ tests/gpu_gemm_test.c $(GPU_LINK_LIBS) -lpthread -lm .PHONY: test-gpu-gemm test-gpu-gemm: $(GPU_GEMM_TEST) ./$(GPU_GEMM_TEST) --sim diff --git a/README.md b/README.md index 6cff6147d..6b7e6fc20 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,74 @@ The live status is owned by [aien-architecture](https://github.com/aien-spark/ai [aienux](https://github.com/aien-dev/aienux) holds Aienux, the kernel of AienOS, which 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 aienux (`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. +### Canonical native GPU sources + +`cudapp.lock` pins the CUDApp source consumed by this tree. Native GPU implementation, driver closure, generated native GPU units and their public headers come from that revision, not from a second Omega copy. `tools/cudapp-stage.sh` authenticates the checkout, materializes its committed tree, checks native-unit regeneration, builds the canonical archive and publishes an immutable stage under `OUT_DIR/cudapp`. Every native build authenticates that stage again, including a build without `make clean`. A missing or different pin, missing source, changed source or changed archive refuses the build. There is no lock-check bypass. + +Set `CUDAPP_DIR` to a checkout whose HEAD is exactly `cudapp.lock`, `OMEGA_OMC` to the seeded compiler with SHA-256 `2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f` (Omega `e5b32567a7aff3ce594e3254a622a846a6cd190b`), and `OMEGA_BRIDGE` to omega-bridge `0c4cb9ff980af278890b231b994eaede4dc7621c`. The canonical library is linked after Omega's retained CPU objects. Omega's CPU SHA-256/BLAKE3 binding retains its separately recorded compiler and bridge pins in `om/units.sh` and `om/omega-bridge.lock`; those are not the native GPU binding. + +`tests/cudapp_retirement_sources.json` records all 123 removed source/header paths, their exact historical and canonical object identities, and the SHA-256 of the preserved original-source archive. Omega retains its unique Blackwell qualification adapter and resident runtime adapter. Historical receipts and unmerged branches, including #618, are not rewritten or represented as newly qualified. The remaining CPU implementation overlap is explicit: Omega's CPU companion objects precede the canonical archive; native GPU implementation comes only from CUDApp. + +Visor and program host callers also link the canonical archive after retained CPU +objects; they do not require retired local Blackwell object rules. Tensor mutation +and GB10-host controls authenticate/stage before invoking their standalone runner, +including parallel builds. `test-numeric-cpu`, `test-program-fp32`, +`test-program-realize`, `test-program-id`, `test-tensor`, `test-tensor-store` and +`test-tensor-mutations` exercise host behavior only. + +Standalone chip collectors use the same authenticated stage or disposable canonical overlay and retain their existing device-authorization requirements. Their `canonical_source` field embeds the existing `.om` stage-verifier object unchanged; it is source provenance, not qualification authority. M17 reruns refuse an existing receipt or corpus manifest: set `M17_EVIDENCE_DIR` to a fresh evidence directory rather than replacing historical evidence. A build-only check of a chip collector is not a chip run. + +This ownership cutover does not activate new native candidates. Existing artifact admission remains authoritative; new candidates have no production qualification record and remain refused. Host fixtures use explicitly synthetic handles. GPU execution, exact-artifact independent hardware qualification and full-model parity/performance are separate authorized gates, not consequences of staging, compilation or host tests. + +#### Existing 35B candidate acceptance boundary + +The first whole-model target is the existing Q36 35B inference path on Spark, +not a new operator, adapter or hardware backend. Before an authorized device run, +freeze one manifest containing the Core source and executable hashes, this Omega +source, `cudapp.lock`, staged source/archive hashes, all generated-unit identities, +compiler and bridge pins, model/config/tokenizer/weight/scale content identities, +exact command/environment, admission records and workload inputs. The capacity +repair CUDApp #173 and command-lifetime repair #174 are candidate prerequisites; +pending source is not merged source and historical component receipts are not +qualification of that manifest. +This isolated host-integration branch pins local, unmerged CUDApp +`685f6c38924383667469fa32d1f6495490b94bc9`: combines the prior candidate +`6ed24d1618e06b6e8f92e307f731a38c0d515a4b` with MMIO instruction repair #172 +at `885e32017eaae6208719eefcfa516ceaa853a846`. The prior candidate combines +`491da3ce11c74fe66b49d679aafb0334915b7ab4` (#175 on accepted #173 +`ca441c5a92f5a951a67de00aeddae0e077f10216`) and +`8cd1c912e8c7a68b7adcca75c6f71d1652401a54` (#174 evidence head; +corrected code `05be6d98211d7fdc043d173da8f661bbb51e0138`). +This is not canonical main, merged source, device qualification or production admission. +The original #924 draft pin and all earlier component receipts remain unchanged. + +Build the canonical archive through `check-cudapp`, then build the existing Core +35B consumer against that exact archive without an alternate GPU implementation. +Retain the link map and verify the consumed archive and generated-unit identities. +Run host/refusal controls first, including wrong pin, changed source/archive, +shape/grouped-MoE admission, capacity exhaustion, command disposal and recovery. +Production resolver `NULL` and record count zero remain unchanged; a build-only +candidate does not acquire production admission. + +Actual inference requires a current authorized GPU reservation and an isolated +endpoint, never an unapproved replacement or second large model beside the resident +service. Compare the candidate with the saved qualified incumbent using identical +model bytes, prompts, decoding settings, context and slot configuration. Record +correctness and numerical/model-quality results, complete prefill/decode timings, +peak and steady memory, repeated-run reliability, timeout/refusal and recovery +behavior, and effects on neighboring processes. Cover one-user and existing +multi-user workloads, ragged/large-M prefill and grouped experts; bind every actual +recorded code/launch occurrence before submission. A partial run, a mismatched +artifact or any unaccepted qualification refuses activation. GPU, full-model, +memory, speed, recovery and neighboring-process outcomes remain NOT_RUN until +measured against the frozen candidate; publish new receipts without changing old ones. + +This path still depends on Linux and NVIDIA's kernel driver/firmware; the vendored +driver interface headers are version `580.173.02`. Record the actual running driver +and firmware versions in the candidate manifest. Removing CUDA userspace imports +does not establish an independent driver, generic CUDA compatibility or a drop-in +replacement for arbitrary applications. + ## Standing rules Language rule: `.om` is the only forward first-party implementation language. Implement and qualify each replacement, switch its actual consumers, then remove the superseded first-party source and obsolete build/runtime dependencies from the active tree. This includes compiler/runtime code, services, tools, automation and project-owned tests; C/Rust/shell remaining today are unfinished migration, not permanent exemptions. Preserve Git history and immutable evidence. External protocol formats, generated machine code, device firmware and independently sourced qualification oracles have separately declared roles; they must not conceal a foreign implementation of Omega. See the [replacement/deletion contract](https://github.com/aien-dev/aien-architecture-mv/issues/300). diff --git a/cudapp.lock b/cudapp.lock new file mode 100644 index 000000000..d983de03c --- /dev/null +++ b/cudapp.lock @@ -0,0 +1 @@ +685f6c38924383667469fa32d1f6495490b94bc9 diff --git a/mk/.crumb b/mk/.crumb index e38efa48f..d4f893173 100644 --- a/mk/.crumb +++ b/mk/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-28T03:06:12Z", + "compiled_at": "2026-10-28T20:28:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:8f0e5cb325040247440527f6b54b65cf72c47ff5adca75b4f32a1ddf2b2d6ade", + "digest": "sha256:5fb34d7988eea79177ebfa6b8245c1131a63e09789572b5633278936d11295ae", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 75, - "generated_at_commit": "79b8c1f9c24195c53ac8dad111d35175a4431506", - "source_tree": "sha256:b8302c1e15664dfe98c550a03830f5d4cf75c5451a6c75eed5042e623dea5d10" + "files": 76, + "generated_at_commit": "cafb7be08e4a92d6dd7347b011a833f524140dee", + "source_tree": "sha256:4c099e8fef751278a3ffcc52b1a206de6108dcc8135bf3a6699e72527132e852" }, "owner_lane": "", "provenance": { diff --git a/mk/00-visor-core.mk b/mk/00-visor-core.mk index d5e243a92..b30a7dcd7 100644 --- a/mk/00-visor-core.mk +++ b/mk/00-visor-core.mk @@ -3,7 +3,7 @@ # from a clean checkout with PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0. VISOR_CORE = omega_om_units omega_canonical omega_validate omega_core omega_codec aarch64_encoder aarch64_decoder \ omega_realize omega_realize_synth omega_machine omega_exec omega_verify omega_program omega_synthesis omega_library \ - omega_vector omega_blackwell_qmd omega_blackwell_encoder omega_blackwell_realize + omega_vector VISOR_CORE_OBJS = $(addprefix $(OUT_DIR)/,$(addsuffix .o,$(VISOR_CORE))) VISOR_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -MMD -MP -D_GNU_SOURCE -O2 -Isrc -Isrc/visor -Isrc/language VISOR_SRCS = $(wildcard src/visor/*.c) @@ -26,7 +26,7 @@ $(OUT_DIR)/language/%.o: src/language/%.c | $(OUT_DIR)/language $(OUT_DIR)/omega_main.o: tools/omega.c | $(OUT_DIR) $(CC) $(VISOR_CFLAGS) -c $< -o $@ -$(OMEGA_BIN): $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) $(OUT_DIR)/omega_main.o +$(OMEGA_BIN): $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) $(OUT_DIR)/omega_main.o $(CUDAPP_LIB) | check-cudapp $(CC) $(VISOR_CFLAGS) -o $@ $^ .PHONY: omega @@ -34,11 +34,11 @@ omega: $(OMEGA_BIN) cp $(OMEGA_BIN) ./omega # Generic rule for lane tests: tests/visor/test_X.c -> build/tests-visor/test_X -$(OUT_DIR)/tests-visor/%: tests/visor/%.c $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) | $(OUT_DIR)/tests-visor - $(CC) $(VISOR_CFLAGS) -Itests/visor -o $@ $< $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) +$(OUT_DIR)/tests-visor/%: tests/visor/%.c $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) $(CUDAPP_LIB) | $(OUT_DIR)/tests-visor check-cudapp + $(CC) $(VISOR_CFLAGS) -Itests/visor -o $@ $< $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) $(CUDAPP_LIB) -$(OUT_DIR)/tests-language/%: tests/language/%.c $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) | $(OUT_DIR)/tests-language - $(CC) $(VISOR_CFLAGS) -Itests/language -o $@ $< $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) +$(OUT_DIR)/tests-language/%: tests/language/%.c $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) $(CUDAPP_LIB) | $(OUT_DIR)/tests-language check-cudapp + $(CC) $(VISOR_CFLAGS) -Itests/language -o $@ $< $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) $(CUDAPP_LIB) # ---- aggregate Visor gates (lead-owned) -------------------------------------- # Physics-free lane tests (no PHYSICS_DIR needed): diff --git a/mk/autodiff.mk b/mk/autodiff.mk index 1ef131765..9f727d75a 100644 --- a/mk/autodiff.mk +++ b/mk/autodiff.mk @@ -14,26 +14,25 @@ ifndef AUTODIFF_MK AUTODIFF_MK := 1 .PHONY: test-autodiff test-autodiff-mutations autodiff-mutants AUTODIFF_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -Isrc -Isrc/tensor \ - -Isrc/autodiff -DOMEGA_NUMERIC_CPU_ONLY + -Isrc/autodiff -DOMEGA_NUMERIC_CPU_ONLY $(CUDAPP_HEADER_FLAGS) AUTODIFF_SRCS = src/autodiff/omega_autodiff.c AUTODIFF_TENSOR_SRCS = src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c \ src/tensor/omega_tensor_reduce_seam.c src/omega_numeric_reduce.c src/omega_numeric_transc.c -AUTODIFF_DEPS = src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c \ - src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c +AUTODIFF_DEPS = src/omega_numeric.c src/omega_numeric_provenance.c src/omega_om_units.c AUTODIFF_HDRS = src/autodiff/omega_autodiff.h src/tensor/omega_tensor.h src/tensor/omega_tensor_reduce_seam.h \ src/omega_numeric_reduce.h src/omega_numeric.h src/sha256.h src/omega_numeric_transc.h $(OUT_DIR)/test_omega_autodiff: tests/test_omega_autodiff.c $(AUTODIFF_SRCS) $(AUTODIFF_TENSOR_SRCS) \ - $(AUTODIFF_DEPS) $(AUTODIFF_HDRS) + $(AUTODIFF_DEPS) $(AUTODIFF_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p $(OUT_DIR) gcc $(AUTODIFF_CFLAGS) -O2 -o $@ tests/test_omega_autodiff.c $(AUTODIFF_SRCS) $(AUTODIFF_TENSOR_SRCS) \ - $(AUTODIFF_DEPS) + $(AUTODIFF_DEPS) $(CUDAPP_LIB) $(OUT_DIR)/test_omega_autodiff_asan: tests/test_omega_autodiff.c $(AUTODIFF_SRCS) $(AUTODIFF_TENSOR_SRCS) \ - $(AUTODIFF_DEPS) $(AUTODIFF_HDRS) + $(AUTODIFF_DEPS) $(AUTODIFF_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p $(OUT_DIR) gcc $(AUTODIFF_CFLAGS) -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all \ - -o $@ tests/test_omega_autodiff.c $(AUTODIFF_SRCS) $(AUTODIFF_TENSOR_SRCS) $(AUTODIFF_DEPS) + -o $@ tests/test_omega_autodiff.c $(AUTODIFF_SRCS) $(AUTODIFF_TENSOR_SRCS) $(AUTODIFF_DEPS) $(CUDAPP_LIB) test-autodiff: $(OUT_DIR)/test_omega_autodiff $(OUT_DIR)/test_omega_autodiff_asan ./$(OUT_DIR)/test_omega_autodiff diff --git a/mk/cudapp-consumer.mk b/mk/cudapp-consumer.mk new file mode 100644 index 000000000..3a6e6ee25 --- /dev/null +++ b/mk/cudapp-consumer.mk @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# Source identity is checked on every native entry, including stale-output builds. +ifndef OMEGA_CUDAPP_CONSUMER_MK +OMEGA_CUDAPP_CONSUMER_MK := 1 +CUDAPP_DIR ?= ../CUDApp +CUDAPP_STAGE = $(OUT_DIR)/cudapp +CUDAPP_SOURCE = $(CUDAPP_STAGE)/source +CUDAPP_LIB = $(CUDAPP_STAGE)/build/libcudapp.a +CUDAPP_HEADER_FLAGS = -I"$(CUDAPP_SOURCE)/src" -I"$(CUDAPP_SOURCE)/m16" -I"$(CUDAPP_SOURCE)/nvrm" \ + -I"$(CUDAPP_SOURCE)/third_party/nvidia-open-580.173.02/src/common/sdk/nvidia/inc" \ + -I"$(CUDAPP_SOURCE)/third_party/nvidia-open-580.173.02/kernel-open/common/inc" \ + -I"$(CUDAPP_SOURCE)/third_party/nvidia-open-580.173.02/kernel-open/nvidia-uvm" \ + -I"$(CUDAPP_SOURCE)/third_party/nvidia-open-580.173.02/src/nvidia/arch/nvalloc/unix/include" \ + -DOMEGA_CUDAPP_SOURCE='"$(abspath $(CUDAPP_SOURCE))"' +.PHONY: check-cudapp test-cudapp-stage-hermetic +check-cudapp: + sh tools/cudapp-stage.sh cudapp.lock "$(CUDAPP_DIR)" "$(CUDAPP_STAGE)" + +test-cudapp-stage-hermetic: + sh tests/cudapp_stage_hermetic.sh "$(CUDAPP_DIR)" + +$(CUDAPP_LIB): cudapp.lock | check-cudapp + @test -f "$@" + +# Required canonical source/header prerequisites may not exist until staging. +# A missing member is an error; it is never silently dropped from a read set. +$(CUDAPP_SOURCE)/%: | check-cudapp + @test -f "$@" + +$(OUT_DIR)/omegatool.o $(OUT_DIR)/omega_blackwell_gates.o $(OUT_DIR)/omega_world_gates.o \ +$(OUT_DIR)/omega_vector.o $(OUT_DIR)/omega_accelerator.o $(OUT_DIR)/omega_accelerator_world.o \ +$(OUT_DIR)/rx_resident_gpu.o: cudapp.lock $(CUDAPP_SOURCE)/src/cudapp_native.h | check-cudapp + +endif diff --git a/mk/numeric-slices.mk b/mk/numeric-slices.mk index ff2125f03..7d8ea79db 100644 --- a/mk/numeric-slices.mk +++ b/mk/numeric-slices.mk @@ -1,4 +1,3 @@ -# Numeric Blackwell source slice, declared once. The numeric CPU/host test -# source lists in Makefile end with this run, in this order. -NUMERIC_BW_SRCS = src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c -NUMERIC_BW_HDRS = src/omega_blackwell_qmd.h src/omega_blackwell_codegen.h src/omega_blackwell_encoder.h src/sha256.h +# Hosted numerics retain Omega CPU/provenance units; GPU code comes from CUDA++. +NUMERIC_BW_SRCS = src/omega_om_units.c +NUMERIC_BW_HDRS = $(CUDAPP_SOURCE)/src/omega_blackwell_qmd.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h $(CUDAPP_SOURCE)/src/omega_blackwell_encoder.h src/sha256.h diff --git a/mk/omega-gpu-code-alloc.mk b/mk/omega-gpu-code-alloc.mk index 3b217c32d..92ede96c1 100644 --- a/mk/omega-gpu-code-alloc.mk +++ b/mk/omega-gpu-code-alloc.mk @@ -1,18 +1,34 @@ -# GPU code buffer sizing (src/omega_gpu_code_alloc.h): the 2 KB instruction prefetch tail after every +# Canonical GPU code buffer sizing: 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_SRC = $(wildcard $(CUDAPP_SOURCE)/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 +.PHONY: test-gpu-code-alloc test-gpu-code-alloc-scan +build/test_omega_gpu_code_alloc: tests/test_omega_gpu_code_alloc.c $(CUDAPP_SOURCE)/src/omega_gpu_code_alloc.h | check-cudapp @mkdir -p build - gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -o $@ tests/test_omega_gpu_code_alloc.c + gcc -std=gnu11 -O2 -Wall -Wextra -Werror $(CUDAPP_HEADER_FLAGS) -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 + @gcc -std=gnu11 -O2 -Wall -Wextra -Werror -DOMEGA_GPU_CODE_ALLOC_MUTANT_NO_TAIL $(CUDAPP_HEADER_FLAGS) -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" + @$(MAKE) --no-print-directory test-gpu-code-alloc-scan + @if $(MAKE) --no-print-directory test-gpu-code-alloc-scan CODE_ALLOC_SCAN_SRC=build/code-alloc-missing-input.c >build/code-alloc-missing.log 2>&1; then echo "source scan accepted a missing input"; exit 1; fi + @grep -q '^source scan failed (grep exit 2)' build/code-alloc-missing.log + @if $(MAKE) --no-print-directory test-gpu-code-alloc-scan CODE_ALLOC_SCAN_SRC= >build/code-alloc-empty.log 2>&1; then echo "source scan accepted an empty readset"; exit 1; fi + @grep -q '^source scan has no inputs' build/code-alloc-empty.log + @printf '%s\n' 'code_size + 0xfff' >build/code-alloc-forbidden.c + @if $(MAKE) --no-print-directory test-gpu-code-alloc-scan CODE_ALLOC_SCAN_SRC=build/code-alloc-forbidden.c >build/code-alloc-forbidden.log 2>&1; then echo "source scan accepted forbidden sizing"; exit 1; fi + @grep -q '^code buffer sized without the prefetch tail' build/code-alloc-forbidden.log @echo "OMEGA_GPU_CODE_ALLOC_GATE PASS" + +# A canonical stage must exist before expanding the default optional source globs. +test-gpu-code-alloc-scan: | check-cudapp + @test -n "$(strip $(CODE_ALLOC_SCAN_SRC))" || { echo "source scan has no inputs"; exit 2; } + @rc=0; grep -nE '$(CODE_ALLOC_SCAN_RE)' $(CODE_ALLOC_SCAN_SRC) || rc=$$?; \ + case $$rc in \ + 1) echo "source scan: no page-only code sizing" ;; \ + 0) echo "code buffer sized without the prefetch tail (use omega_gpu_code_alloc_bytes)"; exit 1 ;; \ + *) echo "source scan failed (grep exit $$rc)"; exit 2 ;; \ + esac diff --git a/mk/omega-gpu-engine.mk b/mk/omega-gpu-engine.mk index ac62777ff..b2e9f0fe2 100644 --- a/mk/omega-gpu-engine.mk +++ b/mk/omega-gpu-engine.mk @@ -17,32 +17,27 @@ # 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 +build/test_omega_gpu_engine_compile: tests/test_omega_gpu_engine_compile.c $(CUDAPP_SOURCE)/src/omega_gpu_engine.h $(CUDAPP_LIB) | check-cudapp @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 + gcc -std=gnu11 -O2 -Wall -Wextra -Werror $(CUDAPP_HEADER_FLAGS) -Isrc -DOMEGA_NUMERIC_CPU_ONLY -o $@ tests/test_omega_gpu_engine_compile.c $(CUDAPP_LIB) 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 +build/test_omega_gpu_engine: tests/test_omega_gpu_engine.c $(CUDAPP_SOURCE)/src/omega_gpu_engine.h $(CUDAPP_LIB) | check-cudapp @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 + gcc -std=gnu11 -O2 -Wall -Wextra -Werror $(CUDAPP_HEADER_FLAGS) -Isrc -DOMEGA_NUMERIC_CPU_ONLY -o $@ tests/test_omega_gpu_engine.c $(CUDAPP_LIB) 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 +# Syntax-check the canonical backend, using its bundled driver headers. +GPU_ENGINE_PHYS_INC = $(CUDAPP_HEADER_FLAGS) -build/omega_blackwell_engine_syntax.o: src/omega_blackwell_engine.c src/omega_blackwell_engine.h src/omega_gpu_engine.h +build/omega_blackwell_engine_syntax.o: $(CUDAPP_SOURCE)/src/omega_blackwell_engine.c $(CUDAPP_SOURCE)/src/omega_blackwell_engine.h $(CUDAPP_SOURCE)/src/omega_gpu_engine.h | check-cudapp @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 + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE $(GPU_ENGINE_PHYS_INC) -Isrc -c -o $@ $(CUDAPP_SOURCE)/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. @@ -52,17 +47,15 @@ test-gpu-engine-prod-build: # 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 \ +GPU_ENGINE_SIM_SRCS = src/omega_vector.c src/omega_validate.c \ src/omega_core.c src/omega_canonical.c src/omega_om_units.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 + $(GPU_ENGINE_SIM_SRCS) $(CUDAPP_SOURCE)/src/omega_gpu_engine.h $(CUDAPP_SOURCE)/src/omega_blackwell_engine.h $(CUDAPP_LIB) | check-cudapp @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 + $(GPU_ENGINE_SIM_SRCS) -Wl,--gc-sections -lm $(CUDAPP_LIB) test-gpu-engine-sim: build/test_omega_blackwell_engine ./build/test_omega_blackwell_engine @@ -71,7 +64,7 @@ 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 +build/test_omega_gpu_engine_gb10.o: tests/test_omega_gpu_engine_gb10.c $(CUDAPP_SOURCE)/src/omega_gpu_engine.h $(CUDAPP_SOURCE)/src/omega_blackwell_engine.h $(CUDAPP_SOURCE)/src/omega_blackwell_submit.h | check-cudapp @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 @@ -79,13 +72,11 @@ 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/omega_om_units.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) +GPU_SERVE_ALLOC_SRCS = src/omega_om_units.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) $(CUDAPP_LIB) | check-cudapp @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 + -o $@ tests/gpu_serving_alloc_count_test.c tests/fake_m16_native.c $(GPU_SERVE_ALLOC_SRCS) -lm $(CUDAPP_LIB) .PHONY: test-gpu-serving-alloc test-gpu-serving-alloc: build/gpu_serving_alloc_count_test ./build/gpu_serving_alloc_count_test plain @@ -112,23 +103,27 @@ test-gpu-serving-alloc: build/gpu_serving_alloc_count_test # 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 + -U_FORTIFY_SOURCE -DOMEGA_GPU_NO_POSIX -DOMEGA_NUMERIC_CPU_ONLY $(CUDAPP_HEADER_FLAGS) -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/omega_om_units.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_NAMES = omega_gpu_engine omega_gpu_platform omega_blackwell_encoder omega_blackwell_codegen \ + omega_blackwell_matmul omega_blackwell_qmd omega_blackwell_realize \ + omega_gpu_session omega_gpu_fmt omega_gpu_matmul_api omega_gpu_attention_api \ + omega_gpu_serving omega_gpu_wait cudapp_freest_units +GPU_FS_SRCS = $(addprefix $(CUDAPP_SOURCE)/src/,$(addsuffix .c,$(GPU_FS_NAMES))) src/omega_om_units.c +GPU_FS_HDRS = $(addprefix $(CUDAPP_SOURCE)/src/,omega_gpu_engine.h omega_gpu_platform.h omega_blackwell_codegen.h omega_blackwell_matmul.h \ + omega_gpu_session.h omega_gpu_fmt.h omega_gpu_matmul_api.h omega_gpu_attention_api.h omega_gpu_serving.h omega_gpu_wait.h) +GPU_FS_OBJS = $(addprefix $(GPU_FS_DIR)/,$(addsuffix .o,$(GPU_FS_NAMES))) $(GPU_FS_DIR)/omega_om_units.o 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) +$(GPU_FS_DIR)/%.o: $(CUDAPP_SOURCE)/src/%.c $(GPU_FS_HDRS) | check-cudapp + @mkdir -p $(GPU_FS_DIR) + gcc $(GPU_FS_CFLAGS) -c -o $@ $< + +$(GPU_FS_DIR)/omega_om_units.o: src/omega_om_units.c $(GPU_FS_HDRS) | check-cudapp @mkdir -p $(GPU_FS_DIR) gcc $(GPU_FS_CFLAGS) -c -o $@ $< @@ -139,13 +134,13 @@ $(GPU_FS_LINK): $(GPU_FS_OBJS) @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 +build/test_omega_gpu_engine_freestanding: tests/test_omega_gpu_engine.c $(GPU_FS_LINK) $(CUDAPP_SOURCE)/src/omega_gpu_engine.h | check-cudapp @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 + gcc -std=gnu11 -O2 -Wall -Wextra -Werror $(CUDAPP_HEADER_FLAGS) -Isrc -DOMEGA_NUMERIC_CPU_ONLY -DOMEGA_GPU_NO_POSIX \ + -o $@ tests/test_omega_gpu_engine.c $(GPU_FS_LINK) +build/test_omega_gpu_platform: tests/test_omega_gpu_platform.c $(GPU_FS_LINK) $(CUDAPP_SOURCE)/src/omega_gpu_platform.h | check-cudapp @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 + gcc -std=gnu11 -O2 -Wall -Wextra -Werror $(CUDAPP_HEADER_FLAGS) -Isrc -o $@ tests/test_omega_gpu_platform.c $(GPU_FS_LINK) 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 @@ -158,15 +153,15 @@ test-gpu-engine-freestanding: $(GPU_FS_LINK) build/test_omega_gpu_engine_freesta # 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/omega_om_units.c +CODEGEN_FS_TEST_DEPS = tests/test_omega_codegen_freestanding.c $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h $(CUDAPP_SOURCE)/src/omega_blackwell_matmul.h +build/test_codegen_hosted: $(CODEGEN_FS_TEST_DEPS) src/omega_om_units.c $(CUDAPP_LIB) | check-cudapp @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/omega_om_units.c -build/test_codegen_freestanding: $(CODEGEN_FS_TEST_DEPS) $(GPU_FS_LINK) + gcc -std=gnu11 -O2 -Wall -Wextra -Werror $(CUDAPP_HEADER_FLAGS) -Isrc -o $@ tests/test_omega_codegen_freestanding.c \ + src/omega_om_units.c $(CUDAPP_LIB) +build/test_codegen_freestanding: $(CODEGEN_FS_TEST_DEPS) $(GPU_FS_LINK) | check-cudapp @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)/omega_om_units.o + gcc -std=gnu11 -O2 -Wall -Wextra -Werror $(CUDAPP_HEADER_FLAGS) -Isrc -DOMEGA_GPU_NO_POSIX -o $@ tests/test_omega_codegen_freestanding.c \ + $(GPU_FS_LINK) 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 @@ -192,19 +187,14 @@ test-gpu-fs-allowlist-control: $(GPU_FS_LINK) # - 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) +build/test_omega_gpu_session_platform: tests/test_omega_gpu_session_platform.c $(GPU_FS_LINK) | check-cudapp @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/omega_om_units.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) + gcc -std=gnu11 -O2 -Wall -Wextra -Werror $(CUDAPP_HEADER_FLAGS) -Isrc -DOMEGA_GPU_NO_POSIX -o $@ tests/test_omega_gpu_session_platform.c $(GPU_FS_LINK) +GPU_LINUX_REF_SRCS = src/omega_om_units.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) $(CUDAPP_LIB) | check-cudapp @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 + -o $@ tests/test_omega_gpu_platform_linux.c tests/fake_m16_native.c $(GPU_LINUX_REF_SRCS) -lm $(CUDAPP_LIB) 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 @@ -214,11 +204,11 @@ 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; \ + sed -e "$$script" $(CUDAPP_SOURCE)/src/omega_gpu_session.c > $(GPU_SESSION_MUT_DIR)/$$name.c; \ + if cmp -s $(CUDAPP_SOURCE)/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 \ + gcc -std=gnu11 -O2 -Wall -Wextra -Werror $(CUDAPP_HEADER_FLAGS) -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)); }; \ diff --git a/mk/omega-gpu-wait.mk b/mk/omega-gpu-wait.mk index 42e5ed25b..8f46eca72 100644 --- a/mk/omega-gpu-wait.mk +++ b/mk/omega-gpu-wait.mk @@ -1,15 +1,15 @@ -# Shared GPU completion wait primitive (src/omega_gpu_wait.c): host unit test with +# Shared canonical GPU completion wait primitive: 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 +build/test_omega_gpu_wait: tests/test_omega_gpu_wait.c $(CUDAPP_SOURCE)/src/omega_gpu_wait.h $(CUDAPP_LIB) | check-cudapp @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 + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE $(CUDAPP_HEADER_FLAGS) -Isrc -o $@ tests/test_omega_gpu_wait.c $(CUDAPP_LIB) 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. +# Real-code mutants: the canonical omega_gpu_wait.c carries 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 @@ -18,7 +18,7 @@ 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; \ + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -D$$m $(CUDAPP_HEADER_FLAGS) -Isrc -o build/test_omega_gpu_wait_$$m tests/test_omega_gpu_wait.c $(CUDAPP_SOURCE)/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 diff --git a/mk/prime_race_gb10.mk b/mk/prime_race_gb10.mk index 67634702a..53a8602a5 100644 --- a/mk/prime_race_gb10.mk +++ b/mk/prime_race_gb10.mk @@ -1,6 +1,6 @@ -# AIEN Prime Drag Race: native GB10 implementation (bench/prime_race/gb10_native.c) on Omega's -# own Blackwell codegen + session (libomega_gpu.a, no CUDA). Picked up by `-include mk/*.mk`; -# not part of `all` or `test`. Needs PHYSICS_DIR at the physics.lock commit (libomega_gpu). +# AIEN Prime Drag Race: native GB10 implementation (bench/prime_race/gb10_native.c) +# linked to the pinned canonical CUDA++ archive. No CUDA runtime; chip execution +# remains separate from the host build and simulation checks. # # prime-race-gb10 build bench/prime_race/build/gb10_native (+ _mutant, the chip test's # negative control) and refuse them if nm finds a CUDA symbol @@ -20,33 +20,33 @@ GB_OPT = -O3 -mcpu=native GB_SRC_COMMIT := $(shell git rev-parse HEAD 2>/dev/null || echo unknown)$(shell git status --porcelain -- src bench/prime_race mk 2>/dev/null | head -c1 | sed 's/.\+/+dirty/') GB_LABEL_STAMP = $(GB_BUILD)/.gb_source_label GB_DEFS = -DPR_SOURCE_COMMIT='"$(GB_SRC_COMMIT)"' -DPR_CC='"$(CC)"' \ - -DPR_CFLAGS='"$(GB_OPT) -I$(GB_DIR) + omega CFLAGS; libomega_gpu.a built with omega CFLAGS"' + -DPR_CFLAGS='"$(GB_OPT) -I$(GB_DIR) + omega CFLAGS; pinned canonical libcudapp.a"' GB_DEPS = $(GB_DIR)/gb10_native.c $(GB_LABEL_STAMP) $(GB_DIR)/prime_race_impl.c $(GB_DIR)/prime_race_impl.h \ - src/omega_gpu_elementwise_api.h src/omega_gpu_session.h $(OUT_DIR)/libomega_gpu.a + $(CUDAPP_SOURCE)/src/omega_gpu_elementwise_api.h $(CUDAPP_SOURCE)/src/omega_gpu_session.h $(CUDAPP_LIB) # Same pattern as tools/chip_run.sh REFUSAL:cuda GB_NM_CHECK = if nm -u $@ | grep -Eiq 'cuda|cuInit|cuLaunch|nvrtc|cublas'; then echo "CUDA symbols in $@"; rm -f $@; exit 1; fi -$(GB_BUILD)/gb10_native: $(GB_DEPS) +$(GB_BUILD)/gb10_native: $(GB_DEPS) | check-cudapp @mkdir -p $(GB_BUILD) - $(CC) $(CFLAGS) $(GB_OPT) -I$(GB_DIR) $(GB_DEFS) -o $@ $(GB_DIR)/gb10_native.c $(GB_DIR)/prime_race_impl.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm + $(CC) $(CFLAGS) $(GB_OPT) -I$(GB_DIR) $(GB_DEFS) -o $@ $(GB_DIR)/gb10_native.c $(GB_DIR)/prime_race_impl.c -lpthread -lm $(CUDAPP_LIB) @$(GB_NM_CHECK) -$(GB_BUILD)/gb10_native_mutant: $(GB_DEPS) +$(GB_BUILD)/gb10_native_mutant: $(GB_DEPS) | check-cudapp @mkdir -p $(GB_BUILD) - $(CC) $(CFLAGS) $(GB_OPT) -I$(GB_DIR) $(GB_DEFS) -DPR_GB10_MUTANT=1 -o $@ $(GB_DIR)/gb10_native.c $(GB_DIR)/prime_race_impl.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm + $(CC) $(CFLAGS) $(GB_OPT) -I$(GB_DIR) $(GB_DEFS) -DPR_GB10_MUTANT=1 -o $@ $(GB_DIR)/gb10_native.c $(GB_DIR)/prime_race_impl.c -lpthread -lm $(CUDAPP_LIB) @$(GB_NM_CHECK) prime-race-gb10: $(GB_BUILD)/gb10_native $(GB_BUILD)/gb10_native_mutant $(GB_LABEL_STAMP): PRIME_RACE_FORCE @mkdir -p $(GB_BUILD) @echo '$(GB_SRC_COMMIT)' > $@.tmp; cmp -s $@.tmp $@ && rm $@.tmp || mv $@.tmp $@ -$(GB_BUILD)/gb10_sieve_host_test: $(GB_DIR)/tests/gb10_sieve_host_test.c $(GB_DIR)/prime_race_impl.h src/omega_blackwell_codegen.h src/omega_gpu_elementwise_api.h tests/bw_warp_sim.h $(OUT_DIR)/libomega_gpu.a +$(GB_BUILD)/gb10_sieve_host_test: $(GB_DIR)/tests/gb10_sieve_host_test.c $(GB_DIR)/prime_race_impl.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h $(CUDAPP_SOURCE)/src/omega_gpu_elementwise_api.h tests/bw_warp_sim.h $(CUDAPP_LIB) | check-cudapp @mkdir -p $(GB_BUILD) - $(CC) $(CFLAGS) -I$(GB_DIR) -Itests -o $@ $(GB_DIR)/tests/gb10_sieve_host_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm + $(CC) $(CFLAGS) -I$(GB_DIR) -Itests -o $@ $(GB_DIR)/tests/gb10_sieve_host_test.c -lpthread -lm $(CUDAPP_LIB) prime-race-gb10-host-test: $(GB_BUILD)/gb10_sieve_host_test ./$(GB_BUILD)/gb10_sieve_host_test -$(GB_BUILD)/gb10_launch_cost: $(GB_DIR)/tests/gb10_launch_cost.c src/omega_blackwell_codegen.h src/omega_gpu_elementwise_api.h src/omega_gpu_session.h $(OUT_DIR)/libomega_gpu.a +$(GB_BUILD)/gb10_launch_cost: $(GB_DIR)/tests/gb10_launch_cost.c $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h $(CUDAPP_SOURCE)/src/omega_gpu_elementwise_api.h $(CUDAPP_SOURCE)/src/omega_gpu_session.h $(CUDAPP_LIB) | check-cudapp @mkdir -p $(GB_BUILD) - $(CC) $(CFLAGS) $(GB_OPT) -o $@ $(GB_DIR)/tests/gb10_launch_cost.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm + $(CC) $(CFLAGS) $(GB_OPT) -o $@ $(GB_DIR)/tests/gb10_launch_cost.c -lpthread -lm $(CUDAPP_LIB) @$(GB_NM_CHECK) prime-race-gb10-launch-cost: $(GB_BUILD)/gb10_launch_cost endif diff --git a/mk/program-fp32.mk b/mk/program-fp32.mk index 41dacb2e1..bc943bcfc 100644 --- a/mk/program-fp32.mk +++ b/mk/program-fp32.mk @@ -1,11 +1,10 @@ # FP32 in the program IR (spec/program-fp32.md, E1 gap row 12). Physics-free, host-only. PROGRAM_FP32_TEST = $(OUT_DIR)/tests-realize/test_program_fp32 -PROGRAM_FP32_NUM = src/omega_numeric.c src/omega_numeric_provenance.c src/omega_numeric_divsqrt_gb10.c \ - src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c +PROGRAM_FP32_NUM = src/omega_numeric.c src/omega_numeric_provenance.c -$(PROGRAM_FP32_TEST): tests/realize/test_program_fp32.c src/omega_program_fp32.c src/omega_program_fp32.h $(VISOR_CORE_OBJS) $(PROGRAM_FP32_NUM) +$(PROGRAM_FP32_TEST): tests/realize/test_program_fp32.c src/omega_program_fp32.c src/omega_program_fp32.h $(VISOR_CORE_OBJS) $(PROGRAM_FP32_NUM) $(CUDAPP_LIB) | check-cudapp mkdir -p $(dir $@) - $(CC) $(VISOR_CFLAGS) -ffp-contract=off -DOMEGA_NUMERIC_CPU_ONLY -o $@ tests/realize/test_program_fp32.c src/omega_program_fp32.c $(PROGRAM_FP32_NUM) $(VISOR_CORE_OBJS) + $(CC) $(VISOR_CFLAGS) $(CUDAPP_HEADER_FLAGS) -ffp-contract=off -DOMEGA_NUMERIC_CPU_ONLY -o $@ tests/realize/test_program_fp32.c src/omega_program_fp32.c $(PROGRAM_FP32_NUM) $(VISOR_CORE_OBJS) $(CUDAPP_LIB) .PHONY: test-program-fp32 test-program-fp32: $(PROGRAM_FP32_TEST) diff --git a/mk/program-id.mk b/mk/program-id.mk index 1a28bbf6b..0526d4c5e 100644 --- a/mk/program-id.mk +++ b/mk/program-id.mk @@ -6,9 +6,9 @@ PROGRAM_ID_TEST = $(OUT_DIR)/tests-program/test_program_id PROGRAM_ID_BRIDGE_OBJS = $(addprefix $(OUT_DIR)/,$(addsuffix .o,omega_program_ir omega_vc_bridge omega_resolve omega_receipt omega_blake3 omega_vcstore)) $(PROGRAM_ID_TEST): tests/program/test_program_id.c $(VISOR_CORE_OBJS) $(OUT_DIR)/omega_discovery.o \ - $(VISOR_OBJS) $(LANG_OBJS) $(PROGRAM_ID_BRIDGE_OBJS) + $(VISOR_OBJS) $(LANG_OBJS) $(PROGRAM_ID_BRIDGE_OBJS) $(CUDAPP_LIB) | check-cudapp mkdir -p $(dir $@) - $(CC) $(VISOR_CFLAGS) -o $@ $< $(VISOR_CORE_OBJS) $(OUT_DIR)/omega_discovery.o $(VISOR_OBJS) $(LANG_OBJS) $(PROGRAM_ID_BRIDGE_OBJS) + $(CC) $(VISOR_CFLAGS) -o $@ $< $(VISOR_CORE_OBJS) $(OUT_DIR)/omega_discovery.o $(VISOR_OBJS) $(LANG_OBJS) $(PROGRAM_ID_BRIDGE_OBJS) $(CUDAPP_LIB) .PHONY: test-program-id test-program-id: $(PROGRAM_ID_TEST) diff --git a/mk/program-realize.mk b/mk/program-realize.mk index 64a5dfeeb..c0e1eacc4 100644 --- a/mk/program-realize.mk +++ b/mk/program-realize.mk @@ -2,9 +2,9 @@ # Visor core object set. Executes generated code natively: run on an AArch64 host. PROGRAM_REALIZE_TEST = $(OUT_DIR)/tests-realize/test_program_realize -$(PROGRAM_REALIZE_TEST): tests/realize/test_program_realize.c $(VISOR_CORE_OBJS) +$(PROGRAM_REALIZE_TEST): tests/realize/test_program_realize.c $(VISOR_CORE_OBJS) $(CUDAPP_LIB) | check-cudapp mkdir -p $(dir $@) - $(CC) $(VISOR_CFLAGS) -o $@ $< $(VISOR_CORE_OBJS) + $(CC) $(VISOR_CFLAGS) -o $@ $< $(VISOR_CORE_OBJS) $(CUDAPP_LIB) .PHONY: test-program-realize test-program-realize: $(PROGRAM_REALIZE_TEST) diff --git a/mk/reservoir.mk b/mk/reservoir.mk index 5063f3dc8..8088f1090 100644 --- a/mk/reservoir.mk +++ b/mk/reservoir.mk @@ -24,13 +24,12 @@ ifndef RESERVOIR_MK RESERVOIR_MK := 1 .PHONY: test-reservoir reservoir-purity qualify-reservoir RES_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -O2 -Isrc -Isrc/reservoir -Itests/reservoir \ - -ffp-contract=off -fno-fast-math -fno-math-errno -DOMEGA_NUMERIC_CPU_ONLY + -ffp-contract=off -fno-fast-math -fno-math-errno -DOMEGA_NUMERIC_CPU_ONLY $(CUDAPP_HEADER_FLAGS) RES_ASAN = -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all -DRES_QUICK RES_SRCS = src/reservoir/omega_reservoir.c src/reservoir/omega_reservoir_readout.c RES_HDRS = src/reservoir/omega_reservoir.h src/reservoir/omega_reservoir_readout.h src/omega_numeric.h src/sha256.h -# omega_numeric.c pulls in the provenance and encoder objects at link time. -RES_DEPS = src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c \ - src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c +# CPU numerics retain provenance and Omega units; GPU definitions are canonical. +RES_DEPS = src/omega_numeric.c src/omega_numeric_provenance.c src/omega_om_units.c RES_TEST_SRCS = tests/reservoir/test_reservoir.c tests/reservoir/res_oracle64.c RES_TEST_HDRS = tests/reservoir/res_fixtures.h tests/reservoir/res_oracle64.h RES_DIR = $(OUT_DIR)/tests-reservoir @@ -42,7 +41,7 @@ RES_TOOL_CFLAGS = $(RES_CFLAGS) -Itools/reservoir -pthread RES_MAT_SRCS = tools/reservoir/res_mat.c tools/reservoir/res_inflate.c src/omega_om_units.c RES_MAT_TEST = tests/reservoir/test_res_mat.c -$(RES_DIR)/%.o: src/reservoir/%.c $(RES_HDRS) +$(RES_DIR)/%.o: src/reservoir/%.c $(RES_HDRS) | check-cudapp @mkdir -p $(RES_DIR) $(CC) $(RES_CFLAGS) -pedantic -c -o $@ $< @@ -51,20 +50,20 @@ reservoir-purity: $(RES_DIR)/omega_reservoir.o $(RES_DIR)/omega_reservoir_readou echo "reservoir object references an allocator, libm or an I/O or process operation"; exit 1; fi @echo "reservoir-purity: omega_reservoir.o and omega_reservoir_readout.o reference no forbidden symbol" -$(RES_DIR)/test_reservoir: $(RES_TEST_SRCS) $(RES_SRCS) $(RES_DEPS) $(RES_HDRS) $(RES_TEST_HDRS) +$(RES_DIR)/test_reservoir: $(RES_TEST_SRCS) $(RES_SRCS) $(RES_DEPS) $(RES_HDRS) $(RES_TEST_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p $(RES_DIR) - $(CC) $(RES_CFLAGS) -o $@ $(RES_TEST_SRCS) $(RES_SRCS) $(RES_DEPS) -lm -$(RES_DIR)/test_reservoir_asan: $(RES_TEST_SRCS) $(RES_SRCS) $(RES_DEPS) $(RES_HDRS) $(RES_TEST_HDRS) + $(CC) $(RES_CFLAGS) -o $@ $(RES_TEST_SRCS) $(RES_SRCS) $(RES_DEPS) -lm $(CUDAPP_LIB) +$(RES_DIR)/test_reservoir_asan: $(RES_TEST_SRCS) $(RES_SRCS) $(RES_DEPS) $(RES_HDRS) $(RES_TEST_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p $(RES_DIR) - $(CC) $(RES_CFLAGS) $(RES_ASAN) -o $@ $(RES_TEST_SRCS) $(RES_SRCS) $(RES_DEPS) -lm + $(CC) $(RES_CFLAGS) $(RES_ASAN) -o $@ $(RES_TEST_SRCS) $(RES_SRCS) $(RES_DEPS) -lm $(CUDAPP_LIB) -$(RES_DIR)/res_qualify: $(RES_TOOL_SRCS) $(RES_TOOL_HDRS) $(RES_SRCS) $(RES_DEPS) $(RES_HDRS) $(RES_TEST_HDRS) +$(RES_DIR)/res_qualify: $(RES_TOOL_SRCS) $(RES_TOOL_HDRS) $(RES_SRCS) $(RES_DEPS) $(RES_HDRS) $(RES_TEST_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p $(RES_DIR) - $(CC) $(RES_TOOL_CFLAGS) -DRES_BUILD_FLAGS='"$(strip $(RES_TOOL_CFLAGS))"' -o $@ $(RES_TOOL_SRCS) $(RES_SRCS) $(RES_DEPS) -lm -$(RES_DIR)/test_res_mat: $(RES_MAT_TEST) $(RES_MAT_SRCS) $(RES_TOOL_HDRS) $(RES_TEST_HDRS) + $(CC) $(RES_TOOL_CFLAGS) -DRES_BUILD_FLAGS='"$(strip $(RES_TOOL_CFLAGS))"' -o $@ $(RES_TOOL_SRCS) $(RES_SRCS) $(RES_DEPS) -lm $(CUDAPP_LIB) +$(RES_DIR)/test_res_mat: $(RES_MAT_TEST) $(RES_MAT_SRCS) $(RES_TOOL_HDRS) $(RES_TEST_HDRS) | check-cudapp @mkdir -p $(RES_DIR) $(CC) $(RES_TOOL_CFLAGS) -o $@ $(RES_MAT_TEST) $(RES_MAT_SRCS) -$(RES_DIR)/test_res_mat_asan: $(RES_MAT_TEST) $(RES_MAT_SRCS) $(RES_TOOL_HDRS) $(RES_TEST_HDRS) +$(RES_DIR)/test_res_mat_asan: $(RES_MAT_TEST) $(RES_MAT_SRCS) $(RES_TOOL_HDRS) $(RES_TEST_HDRS) | check-cudapp @mkdir -p $(RES_DIR) $(CC) $(RES_TOOL_CFLAGS) $(RES_ASAN) -o $@ $(RES_MAT_TEST) $(RES_MAT_SRCS) diff --git a/mk/sm121dis.mk b/mk/sm121dis.mk index d29fcba32..f7781c32d 100644 --- a/mk/sm121dis.mk +++ b/mk/sm121dis.mk @@ -7,12 +7,12 @@ SM121DIS = $(OUT_DIR)/sm121dis SM121DIS_RED = $(OUT_DIR)/sm121dis_red SM121DIS_K = $(OUT_DIR)/sm121dis-kernels -$(SM121DIS): tools/sm121dis/sm121dis.c src/omega_sm121_disasm.c src/omega_sm121_disasm.h +$(SM121DIS): tools/sm121dis/sm121dis.c $(CUDAPP_SOURCE)/src/omega_sm121_disasm.h $(CUDAPP_LIB) | check-cudapp @mkdir -p $(OUT_DIR) - $(CC) -std=gnu11 -Wall -Wextra -Werror -O2 -Isrc -o $@ tools/sm121dis/sm121dis.c src/omega_sm121_disasm.c -$(SM121DIS_RED): tools/sm121dis/sm121dis.c src/omega_sm121_disasm.c src/omega_sm121_disasm.h + $(CC) -std=gnu11 -Wall -Wextra -Werror -O2 $(CUDAPP_HEADER_FLAGS) -Isrc -o $@ tools/sm121dis/sm121dis.c $(CUDAPP_LIB) +$(SM121DIS_RED): tools/sm121dis/sm121dis.c $(CUDAPP_SOURCE)/src/omega_sm121_disasm.c $(CUDAPP_SOURCE)/src/omega_sm121_disasm.h | check-cudapp @mkdir -p $(OUT_DIR) - $(CC) -std=gnu11 -Wall -Wextra -Werror -O2 -DSM121DIS_MUTANT=1 -Isrc -o $@ tools/sm121dis/sm121dis.c src/omega_sm121_disasm.c + $(CC) -std=gnu11 -Wall -Wextra -Werror -O2 -DSM121DIS_MUTANT=1 $(CUDAPP_HEADER_FLAGS) -Isrc -o $@ tools/sm121dis/sm121dis.c $(CUDAPP_SOURCE)/src/omega_sm121_disasm.c sm121dis-corpus-bins: $(addprefix $(OUT_DIR)/,gpu_matmul_api_test gpu_elementwise_test gpu_reconv_test gpu_attention_test \ gpu_moe_window_test gpu_fp8_api_test gpu_decode_attn_test gpu_router_test gpu_bf16_gemv_test gpu_tern_test gpu_fp8gemm_test \ @@ -35,9 +35,9 @@ test-sm121dis: $(SM121DIS) $(SM121DIS_RED) sm121dis-corpus-bins test-sm121dis-co # The provenance checks (tools/divsqrt_nvdisasm_check.sh, tools/ldst_nvdisasm_check.sh, test-numeric-reduce-nvdisasm) # call build/sm121dis by that name, whatever OUT_DIR is. ifneq ($(OUT_DIR),build) -build/sm121dis: tools/sm121dis/sm121dis.c src/omega_sm121_disasm.c src/omega_sm121_disasm.h +build/sm121dis: tools/sm121dis/sm121dis.c $(CUDAPP_SOURCE)/src/omega_sm121_disasm.h $(CUDAPP_LIB) | check-cudapp @mkdir -p build - $(CC) -std=gnu11 -Wall -Wextra -Werror -O2 -Isrc -o $@ tools/sm121dis/sm121dis.c src/omega_sm121_disasm.c + $(CC) -std=gnu11 -Wall -Wextra -Werror -O2 $(CUDAPP_HEADER_FLAGS) -Isrc -o $@ tools/sm121dis/sm121dis.c $(CUDAPP_LIB) endif # ZERO-NVDISASM (bar C6, second half: nothing calls nvdisasm). tools/sm121dis/zero_nvdisasm.sh runs every listing and diff --git a/mk/tensor.mk b/mk/tensor.mk index d257cc2a3..e66fbaa11 100644 --- a/mk/tensor.mk +++ b/mk/tensor.mk @@ -22,11 +22,10 @@ ifndef TENSOR_MK TENSOR_MK := 1 .PHONY: test-tensor test-tensor-no-hooks test-tensor-mutations test-tensor-e1-reduce test-tensor-store TENSOR_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -Isrc -Isrc/tensor \ - -DOMEGA_NUMERIC_CPU_ONLY + -DOMEGA_NUMERIC_CPU_ONLY $(CUDAPP_HEADER_FLAGS) TENSOR_SRCS = src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c src/tensor/omega_tensor_reduce_seam.c \ src/omega_numeric_reduce.c src/omega_numeric_transc.c -TENSOR_DEPS = src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c \ - src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c +TENSOR_DEPS = src/omega_numeric.c src/omega_numeric_provenance.c src/omega_om_units.c TENSOR_HDRS = src/tensor/omega_tensor.h src/tensor/omega_tensor_reduce_seam.h src/omega_numeric_reduce.h src/omega_numeric.h src/sha256.h src/omega_numeric_transc.h # CR-5 tests are #included by tests/test_omega_tensor.c: rebuild when they change. TENSOR_HDRS += tests/tensor_reduce_multi_tests.inc @@ -37,14 +36,14 @@ TENSOR_HOOK_SYMS = omega_tensor_test_set_storage_generation omega_tensor_store_t TENSOR_STORE_SRCS = src/tensor/omega_tensor_store.c TENSOR_STORE_HDRS = src/tensor/omega_tensor_store.h -$(OUT_DIR)/test_omega_tensor: tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) $(TENSOR_HDRS) +$(OUT_DIR)/test_omega_tensor: tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) $(TENSOR_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p $(OUT_DIR) - gcc $(TENSOR_CFLAGS) $(TENSOR_TEST_FLAGS) -O2 -o $@ tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) + gcc $(TENSOR_CFLAGS) $(TENSOR_TEST_FLAGS) -O2 -o $@ tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) $(CUDAPP_LIB) -$(OUT_DIR)/test_omega_tensor_asan: tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) $(TENSOR_HDRS) +$(OUT_DIR)/test_omega_tensor_asan: tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) $(TENSOR_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p $(OUT_DIR) gcc $(TENSOR_CFLAGS) $(TENSOR_TEST_FLAGS) -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all \ - -o $@ tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) + -o $@ tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) $(CUDAPP_LIB) test-tensor: $(OUT_DIR)/test_omega_tensor $(OUT_DIR)/test_omega_tensor_asan ./$(OUT_DIR)/test_omega_tensor @@ -54,7 +53,7 @@ test-tensor: $(OUT_DIR)/test_omega_tensor $(OUT_DIR)/test_omega_tensor_asan # Default (library) build of the tensor sources: no OMEGA_TENSOR_TEST_HOOKS. # Fails if any test-only hook symbol is defined or referenced in the objects. test-tensor-no-hooks: src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c src/tensor/omega_tensor_reduce_seam.c $(TENSOR_HDRS) \ - $(TENSOR_STORE_SRCS) $(TENSOR_STORE_HDRS) + $(TENSOR_STORE_SRCS) $(TENSOR_STORE_HDRS) | check-cudapp @mkdir -p $(OUT_DIR)/tensor-lib gcc $(TENSOR_CFLAGS) -O2 -c -o $(OUT_DIR)/tensor-lib/omega_tensor.o src/tensor/omega_tensor.c gcc $(TENSOR_CFLAGS) -O2 -c -o $(OUT_DIR)/tensor-lib/omega_tensor_cpu.o src/tensor/omega_tensor_cpu.c @@ -69,7 +68,7 @@ test-tensor-no-hooks: src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c sr echo "test-tensor-no-hooks: FAIL ($$s present in default build)"; exit 1; fi; \ done; echo "test-tensor-no-hooks: PASS (test-only hook absent from default build)" -test-tensor-mutations: +test-tensor-mutations: | check-cudapp tools/tensor_mutations.sh # Kept as an alias: the seam now always calls omega_reduce_cpu (E1 WP-D, #134 merged). @@ -85,16 +84,16 @@ test-m20-receipt: # only under $TMPDIR (default /tmp). Its mutants run in test-tensor-mutations. $(OUT_DIR)/test_omega_tensor_store: tests/test_omega_tensor_store.c $(TENSOR_STORE_SRCS) $(TENSOR_SRCS) $(TENSOR_DEPS) \ - $(TENSOR_HDRS) $(TENSOR_STORE_HDRS) + $(TENSOR_HDRS) $(TENSOR_STORE_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p $(OUT_DIR) gcc $(TENSOR_CFLAGS) $(TENSOR_TEST_FLAGS) -O2 -o $@ tests/test_omega_tensor_store.c $(TENSOR_STORE_SRCS) \ - $(TENSOR_SRCS) $(TENSOR_DEPS) + $(TENSOR_SRCS) $(TENSOR_DEPS) $(CUDAPP_LIB) $(OUT_DIR)/test_omega_tensor_store_asan: tests/test_omega_tensor_store.c $(TENSOR_STORE_SRCS) $(TENSOR_SRCS) \ - $(TENSOR_DEPS) $(TENSOR_HDRS) $(TENSOR_STORE_HDRS) + $(TENSOR_DEPS) $(TENSOR_HDRS) $(TENSOR_STORE_HDRS) $(CUDAPP_LIB) | check-cudapp @mkdir -p $(OUT_DIR) gcc $(TENSOR_CFLAGS) $(TENSOR_TEST_FLAGS) -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all \ - -o $@ tests/test_omega_tensor_store.c $(TENSOR_STORE_SRCS) $(TENSOR_SRCS) $(TENSOR_DEPS) + -o $@ tests/test_omega_tensor_store.c $(TENSOR_STORE_SRCS) $(TENSOR_SRCS) $(TENSOR_DEPS) $(CUDAPP_LIB) test-tensor-store: $(OUT_DIR)/test_omega_tensor_store $(OUT_DIR)/test_omega_tensor_store_asan ./$(OUT_DIR)/test_omega_tensor_store @@ -112,7 +111,7 @@ test-tensor-store: $(OUT_DIR)/test_omega_tensor_store $(OUT_DIR)/test_omega_tens # unless GB10_CHIP_RUN=1 is set, so it never runs by # accident. Never pass a quiet flag. .PHONY: test-tensor-gb10-host test-tensor-gb10-chip -test-tensor-gb10-host: +test-tensor-gb10-host: | check-cudapp @test -n "$(PHYSICS_DIR)" && test -d "$(PHYSICS_DIR)" \ || { echo "test-tensor-gb10-host: set PHYSICS_DIR to the physics checkout"; exit 2; } tools/tensor_mutations.sh --gb10 "$(PHYSICS_DIR)" diff --git a/mk/visor-authority.mk b/mk/visor-authority.mk index 946e6cdb0..dec0c45bd 100644 --- a/mk/visor-authority.mk +++ b/mk/visor-authority.mk @@ -30,10 +30,10 @@ $(OUT_DIR)/tests-visor-authority: $(VISOR_AUTH_TEST): tests/visor/test_visor_authority.c $(VISOR_AUTH_RX_SRCS) \ $(OUT_DIR)/visor/visor_effect_request.o $(VISOR_CORE_OBJS) src/visor/visor_effect_request.h \ src/runtime/rx_aegis.h src/runtime/rx_caproot.h src/runtime/rx_world.h \ - src/runtime/rx_generation.h $(VISOR_AUTH_CAP_LIB) | $(OUT_DIR)/tests-visor-authority + src/runtime/rx_generation.h $(VISOR_AUTH_CAP_LIB) $(CUDAPP_LIB) | $(OUT_DIR)/tests-visor-authority check-cudapp @test -f "$(VISOR_AUTH_CAP_LIB)" || { echo "error: VISOR_AUTH_CAP_LIB=$(VISOR_AUTH_CAP_LIB) not found (needed by rx_aegis.c); pass VISOR_AUTH_CAP_LIB=" >&2; exit 1; } $(CC) $(CFLAGS) -Isrc/visor -pthread -o $@ tests/visor/test_visor_authority.c $(VISOR_AUTH_RX_SRCS) \ - $(OUT_DIR)/visor/visor_effect_request.o $(VISOR_CORE_OBJS) $(VISOR_AUTH_CAP_LIB) -lm + $(OUT_DIR)/visor/visor_effect_request.o $(VISOR_CORE_OBJS) $(VISOR_AUTH_CAP_LIB) $(CUDAPP_LIB) -lm .PHONY: test-visor-authority visor-authority-check test-visor-authority: $(VISOR_AUTH_TEST) diff --git a/mk/visor-console.mk b/mk/visor-console.mk index d849520e7..f7dd59c2c 100644 --- a/mk/visor-console.mk +++ b/mk/visor-console.mk @@ -11,8 +11,8 @@ VISOR_CONSOLE_OBJS = $(OUT_DIR)/visor/visor.o $(OUT_DIR)/visor/visor_console.o $ $(OUT_DIR)/lane2: mkdir -p $@ -$(OUT_DIR)/lane2/test_visor_console: tests/visor/test_visor_console.c $(VISOR_CORE_OBJS) $(VISOR_CONSOLE_OBJS) | $(OUT_DIR)/lane2 - $(CC) $(VISOR_CFLAGS) -DVISOR_CONSOLE_LANE_ONLY -Itests/visor -o $@ $< $(VISOR_CORE_OBJS) $(VISOR_CONSOLE_OBJS) +$(OUT_DIR)/lane2/test_visor_console: tests/visor/test_visor_console.c $(VISOR_CORE_OBJS) $(VISOR_CONSOLE_OBJS) $(CUDAPP_LIB) | $(OUT_DIR)/lane2 check-cudapp + $(CC) $(VISOR_CFLAGS) -DVISOR_CONSOLE_LANE_ONLY -Itests/visor -o $@ $< $(VISOR_CORE_OBJS) $(VISOR_CONSOLE_OBJS) $(CUDAPP_LIB) # The full test #includes tools/omega.c (with OMEGA_TOOL_NO_MAIN) for the wiring. $(OUT_DIR)/tests-visor/test_visor_console: tools/omega.c diff --git a/mk/visor-machine.mk b/mk/visor-machine.mk index 6299c02b4..30c3d99db 100644 --- a/mk/visor-machine.mk +++ b/mk/visor-machine.mk @@ -1,16 +1,14 @@ # Omega Visor V1 lane 5 (machine + realization lab) test targets. -# The Blackwell realize objects compile and link physics-free (only sha256 + -# omega_core deps). visor_machine.c references omega_blackwell_get_machine_id -# WEAKLY, so build/omega links with or without them; these lane tests link -# them explicitly so the declared Blackwell target shows linked=yes. -VISOR_BW_CORE = omega_vector omega_blackwell_qmd omega_blackwell_encoder omega_blackwell_realize -VISOR_BW_OBJS = $(addprefix $(OUT_DIR)/,$(addsuffix .o,$(filter-out $(VISOR_CORE),$(VISOR_BW_CORE)))) +# The Blackwell realization implementation comes from the canonical archive. +# Its identity is a weak reference in visor_machine.c, so explicitly retain that +# member for these tests, matching their former explicit local-object linkage. +VISOR_BW_LINK = -Wl,--undefined=omega_blackwell_get_machine_id -$(OUT_DIR)/tests-visor/test_visor_machine: tests/visor/test_visor_machine.c $(VISOR_CORE_OBJS) $(VISOR_BW_OBJS) $(VISOR_OBJS) $(LANG_OBJS) | $(OUT_DIR)/tests-visor - $(CC) $(VISOR_CFLAGS) -Itests/visor -o $@ $< $(VISOR_CORE_OBJS) $(VISOR_BW_OBJS) $(VISOR_OBJS) $(LANG_OBJS) +$(OUT_DIR)/tests-visor/test_visor_machine: tests/visor/test_visor_machine.c $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) $(CUDAPP_LIB) | $(OUT_DIR)/tests-visor check-cudapp + $(CC) $(VISOR_CFLAGS) -Itests/visor -o $@ $< $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) $(VISOR_BW_LINK) $(CUDAPP_LIB) -$(OUT_DIR)/tests-visor/test_visor_realization: tests/visor/test_visor_realization.c $(VISOR_CORE_OBJS) $(VISOR_BW_OBJS) $(VISOR_OBJS) $(LANG_OBJS) | $(OUT_DIR)/tests-visor - $(CC) $(VISOR_CFLAGS) -Itests/visor -o $@ $< $(VISOR_CORE_OBJS) $(VISOR_BW_OBJS) $(VISOR_OBJS) $(LANG_OBJS) +$(OUT_DIR)/tests-visor/test_visor_realization: tests/visor/test_visor_realization.c $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) $(CUDAPP_LIB) | $(OUT_DIR)/tests-visor check-cudapp + $(CC) $(VISOR_CFLAGS) -Itests/visor -o $@ $< $(VISOR_CORE_OBJS) $(VISOR_OBJS) $(LANG_OBJS) $(VISOR_BW_LINK) $(CUDAPP_LIB) .PHONY: test-visor-machine test-visor-realization test-visor-machine: $(OUT_DIR)/tests-visor/test_visor_machine diff --git a/om/consumer.om b/om/consumer.om new file mode 100644 index 000000000..81aa38aec --- /dev/null +++ b/om/consumer.om @@ -0,0 +1,50 @@ +note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +note Existing one-line CUDApp commit lock followed by observed source revision. +global data uchar 83 +fn main to int +n = ulong 0 +while lt n 83 +r = read 0 data n sub ulong 83 n +if lt r 0 +ret 3 +end +if eq r 0 +break +end +n = add n ulong r +end +if ne n 82 +ret 3 +end +if ne get data 40 10 +ret 3 +end +if ne get data 81 10 +ret 3 +end +nonzero = false +for i ulong 40 +c = get data i +if lt c 48 +ret 3 +end +if gt c 57 +if lt c 97 +ret 3 +end +if gt c 102 +ret 3 +end +end +if ne c 48 +nonzero = true +end +if ne c get data add i 41 +ret 3 +end +end +if not nonzero +ret 3 +end +ret 0 +end diff --git a/om/consumer_receipt.om b/om/consumer_receipt.om new file mode 100644 index 000000000..5b74e905a --- /dev/null +++ b/om/consumer_receipt.om @@ -0,0 +1,121 @@ +om2 +note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +note Receipt serialization only, never admission or qualification authority. +text JHead "{\"source\":\"git-object\",\"cudapp_pin\":\"" +text JSrc "\",\"source_archive_sha256\":\"" +text JGuard "\",\"guard_sha256\":\"" +text JLib "\",\"library_sha256\":\"" +text JPath "\",\"source_path\":\"" +text JEnd "\"}\n" +text JHex "0123456789abcdef" +fn jr_copy dst edit uchar 16384 pos ulong src view uchar * n ulong to ulong +if gt add pos n len dst +exit 3 +end +for i ulong n +put dst add pos i get src i +end +ret add pos n +end +fn jr_hex b view uchar 8192 start ulong n ulong to void +for i ulong n +c = get b add start i +if not or and ge c 48 le c 57 and ge c 97 le c 102 +exit 3 +end +end +end +fn main to int +b = new uchar 8192 0 +dst = new uchar 16384 0 +used = ulong 0 +while lt used len b bound 8192 +r = read 0 b used sub len b used +if eq r 0 +break +end +if eq r -4 +continue +end +if lt r 0 +ret 3 +end +used = add used ulong r +end +if or lt used 238 ge used len b +ret 3 +end +if or ne get b 40 10 or ne get b 105 10 or ne get b 170 10 ne get b 235 10 +ret 3 +end +if ne get b sub used 1 10 +ret 3 +end +jr_hex b 0 40 +jr_hex b 41 64 +jr_hex b 106 64 +jr_hex b 171 64 +pos = jr_copy dst 0 JHead len JHead +for i ulong 40 +put dst pos get b i +pos = add pos 1 +end +pos = jr_copy dst pos JSrc len JSrc +for i ulong 64 +put dst pos get b add 41 i +pos = add pos 1 +end +pos = jr_copy dst pos JGuard len JGuard +for i ulong 64 +put dst pos get b add 106 i +pos = add pos 1 +end +pos = jr_copy dst pos JLib len JLib +for i ulong 64 +put dst pos get b add 171 i +pos = add pos 1 +end +pos = jr_copy dst pos JPath len JPath +for i ulong sub used 237 +if gt add pos 6 len dst +ret 3 +end +c = get b add 236 i +if eq c 0 +ret 3 +end +if or eq c 34 eq c 92 +put dst pos 92 +pos = add pos 1 +else +if lt c 32 +put dst pos 92 +put dst add pos 1 117 +put dst add pos 2 48 +put dst add pos 3 48 +put dst add pos 4 get JHex shr c 4 +put dst add pos 5 get JHex and c 15 +pos = add pos 6 +continue +end +end +put dst pos c +pos = add pos 1 +end +pos = jr_copy dst pos JEnd len JEnd +sent = ulong 0 +while lt sent pos bound 16384 +r = write 1 dst sent sub pos sent +if eq r -4 +continue +end +if le r 0 +ret 3 +end +sent = add sent ulong r +end +if ne sent pos +ret 3 +end +ret 0 +end diff --git a/src/.crumb b/src/.crumb index 02231d7a7..f2c0ddf32 100644 --- a/src/.crumb +++ b/src/.crumb @@ -62,140 +62,140 @@ "children": [ { "digest": "728ab6985dea994eb78a7eb2521384a911492d1c36819c17970a5dc3a8a0c5e2", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "algebra", "purpose": "Directory src/algebra. Purpose not yet described by a human." }, { "digest": "1881ed1d139a405a777d24d4b26f97bc8405dee0552d6ce21841ce4833560ce2", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "ans", "purpose": "ANS (Alignment Navigation System), Inertial Alignment v1: frozen reference atoms, drift filter o" }, { "digest": "92c3e2481f7457afd6c7717e6c1a75ebab950ec9114b48025dd137a6edb2975c", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "autodiff", "purpose": "M21 OMEGA_AUTODIFF: reverse-mode tape over M20 tensor CPU ops, caller-owned nodes and scratch, p" }, { "digest": "3bd51397fcd28cd54db65c1df72c320883798bc8550779b2b79c8498b28ffb0d", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "compiler", "purpose": "Directory src/compiler. Purpose not yet described by a human." }, { "digest": "36a66980895553ae73884798bc09a92141e1aeba5e5068a7d9d62a99bad02548", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "crumbline", "purpose": "Directory src/crumbline. Purpose not yet described by a human." }, { "digest": "c75df77ddb2bae35ac5e1225a0ae9dcef77b24608775c7b8d02dce1af0ec3ca4", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "dual_experiment", "purpose": "DUAL applicability experiment library (ARCH-0031 offline evidence lane): deterministic discrete " }, { "digest": "8856d5162c55cb33997201cd580638f80ea933b46e11c61e1913185d419731d7", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "estimation", "purpose": "Directory src/estimation. Purpose not yet described by a human." }, { "digest": "391e337c60cb8b2ae549595394482c23717c1757d83747a7446e81cd780750c1", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "fabric", "purpose": "Directory src/fabric. Purpose not yet described by a human." }, { "digest": "2d33eb528dafb5954bb027cdd9a7c7923594c177f17181194311155b4e1f40b3", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "language", "purpose": "Directory src/language. Purpose not yet described by a human." }, { "digest": "cd0551dbfb6fc354741efe9a3ad1808ffaaf6a8d7e9e7345851333d7a721cee0", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "osh", "purpose": "osh (Omega-native shell, arch#158) lexer unit: layout list, generator, osh_lex.osc, C reference " }, { "digest": "2b5dd2c64d4bbba8c41471dc1af5a0b00bfc1361a2c680d78b99fb30b5b547fe", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "path", "purpose": "Directory src/path. Purpose not yet described by a human." }, { "digest": "e0b91129cc9c188fc0e47b7f3189a3a9a09f9c55eecd018786794571ffc39aad", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "physics0", "purpose": "PD-0 hidden-equation benchmark (Physics-0 Discovery Engine cut 1): world, oracle, scorer, ladder" }, { "digest": "8b923fb5dc1de3b04afae043a4770f7b1fb27d959a8f597191ae2556d822a1cf", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "polyglot", "purpose": "Directory src/polyglot. Purpose not yet described by a human." }, { "digest": "076f486fdf51e12a26160e7f0bf7686fea611db54216f7fef81367620e7a6bdb", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "reservoir", "purpose": "Ionic-droplet reservoir simulator (omega#440): binary32 fixed-step RK4 of the authors' droplet m" }, { "digest": "1e400d9b84494347892448fd576be7bf596ef810ed6e88bcd70f7e7d9a6b5746", - "last_commit": "97a960f5c", + "last_commit": "97a960f5", "name": "runtime", "purpose": "Directory src/runtime. Purpose not yet described by a human." }, { "digest": "71502e9ef65e0620b94ea156cef5034e4c97d703d5ea13c489e4b65713014f84", - "last_commit": "97a960f5c", + "last_commit": "97a960f5", "name": "searchtrace", "purpose": "Directory src/searchtrace. Purpose not yet described by a human." }, { "digest": "b82288db7e732d10f954e921ac98c60e19579a3e58118cc12c49230587929ea2", - "last_commit": "ed8de5736", + "last_commit": "ed8de573", "name": "synapse", "purpose": "Synapse ADR 0003 J1 binary codec port: layout list, generator, syn_codec.osc (A1 WAL records + c" }, { "digest": "9723dd7c18d4e2c22db631680974e1025bccb9c309619424e2f4dfcc43cc7068", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "tensor", "purpose": "M20 OMEGA_TENSOR: immutable tensor semantic layer, views, generation-checked storage, CPU realiz" }, { "digest": "06d9fb18dddf7ab0f8ad02fffd15ce8b80808c77d0904609b6baae83c2b05ce5", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "train", "purpose": "Directory src/train. Purpose not yet described by a human." }, { "digest": "812a7faed07b21e066b732ed596eb0aea609379a2b2af0e8b61dd1ea05bef602", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "turing", "purpose": "Directory src/turing. Purpose not yet described by a human." }, { "digest": "b2e34b2ea0392059ac30d17e27289b1146e523db60a02ef825edef96036817ab", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "visor", "purpose": "Directory src/visor. Purpose not yet described by a human." } ], "children_root": "sha256:2f729945214be989a74d7c2064ae4ba3c2deb52ebea3f334b459198a7bd032ed", - "compiled_at": "2026-10-28T09:49:40Z", + "compiled_at": "2026-10-28T17:51:16Z", "compiler": "crumb-compile/1", - "digest": "sha256:36bd5a00a116cad009672752dcac449a48515f0ef74e759d1710492967158315", + "digest": "sha256:356bac6620b52492f1e1c8464ce092e11845d12ff857857cf32ad4009228d2c9", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 568, - "generated_at_commit": "56dfcbd9b284a88618983e3eac7512630ad70b3e", - "source_tree": "sha256:71e9997b13e6e2ba75a76864788474ba76a313e86bab6ba8b74a7f82ea411499" + "files": 445, + "generated_at_commit": "841001e42fdc87b9d627334add9288f8748a578d", + "source_tree": "sha256:3ef8500f74e76a7ffe380b0d5be357be8a7ce0b5fa2f4e233805dad2055c6a12" }, "owner_lane": "", "provenance": { diff --git a/src/omega_blackwell_codegen.c b/src/omega_blackwell_codegen.c deleted file mode 100644 index debdea0ea..000000000 --- a/src/omega_blackwell_codegen.c +++ /dev/null @@ -1,2598 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 -#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, or up to the program's opt-in gpr_limit) and UGPRs (UR4..UR31). - * Enforces even-alignment and dual-register reservation for 64-bit pairs. - */ - const int gpr_lim = ra->gpr_limit ? (int)ra->gpr_limit : BW_PHYS_GPR_MAX; - bool gpr_busy[BW_PHYS_GPR_HW_LIMIT]; - 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 < gpr_lim) { - 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) < gpr_lim; 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 <= gpr_lim - 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 <= gpr_lim - 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 < gpr_lim; 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] = insn->control ? insn->control : 0x002fda00; - } else { - w[0] = 0x780c | ((uint32_t)(dst & 0xff) << 16) | ((uint32_t)(src1 & 0xff) << 24); - w[1] = insn->imm; - w[2] = 0x03f06270; - w[3] = insn->control ? insn->control : 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] = insn->control ? insn->control : 0x010fca00; /* omega-mv#545: the emitter's waits, not a fixed SB4 wait */ - 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_LG2: - /* MUFU.LG2 Rd, Ra (nvdisasm 13.0 -b SM121 decodes sub-op 0x0c00 as MUFU.LG2) */ - w[0] = 0x7308U | ((uint32_t)(dst & 0xff) << 16); - w[1] = (uint32_t)(src1 & 0xff); - w[2] = 0x00000c00; - 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] = insn->control ? insn->control : 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; -} - -/* Kernel capture (C6 of docs/OMEGA.md, tools/sm121dis): with OMEGA_KERNEL_DUMP_DIR set, every encoded kernel is written - * there as .bin, once per distinct body, so the disassembler can be checked against nvdisasm on - * every kernel the library builds. Unset (the normal case) it does nothing; the freestanding build has no files. */ -void omega_kernel_dump(const uint8_t *code, size_t len) { -#ifndef OMEGA_GPU_NO_POSIX - const char *dir = getenv("OMEGA_KERNEL_DUMP_DIR"); - if (!dir || !dir[0] || !code || !len) return; - uint8_t d[SHA256_DIGEST_SIZE]; sha256_hash(code, len, d); - char path[4096]; - int n = snprintf(path, sizeof path, "%s/%02x%02x%02x%02x%02x%02x%02x%02x.bin", - dir, (unsigned)d[0], (unsigned)d[1], (unsigned)d[2], (unsigned)d[3], - (unsigned)d[4], (unsigned)d[5], (unsigned)d[6], (unsigned)d[7]); - if (n < 0 || (size_t)n >= sizeof path) return; - /* Private, exclusive creation: an existing body or symlink is left alone. */ - int fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); - if (fd < 0) return; - FILE *f = fdopen(fd, "wb"); - if (!f) { close(fd); return; } - if (fwrite(code, 1, len, f) != len) BW_DIAG("omega_kernel_dump: short write %s\n", path); - if (fclose(f) != 0) BW_DIAG("omega_kernel_dump: close failed %s\n", path); -#else - (void)code; (void)len; -#endif -} - -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; - } - - omega_kernel_dump(code_buf, req_bytes); - *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; } - -int omega_bw_ir_set_gpr_limit(BlackwellIRProgram *prog, uint32_t limit) { - if (!prog || limit <= BW_PHYS_GPR_MAX || limit > BW_PHYS_GPR_HW_LIMIT) return -1; - prog->regalloc.gpr_limit = limit; - return 0; -} diff --git a/src/omega_blackwell_codegen.h b/src/omega_blackwell_codegen.h deleted file mode 100644 index 30ff38983..000000000 --- a/src/omega_blackwell_codegen.h +++ /dev/null @@ -1,362 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 /* default allocation limit (R2..R127); a program may opt into more (omega_bw_ir_set_gpr_limit) */ -/* Highest limit a program may ask for: the chip allows 255 registers per thread and 64K per block (CUDA Programming - * Guide, Compute Capabilities appendix: "per thread is 255"); a peak of 246 declares 248 (peak + 2 rounded up to 8). - * The launcher must keep threads * declared <= 65536 (omega#545). */ -#define BW_PHYS_GPR_HW_LIMIT 246 -#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] */ - /* Gated DeltaNet softplus (2026-10-18, omega#542): sub-op 0x0c00 checked with nvdisasm 13.0 -b SM121, which decodes - * "MUFU.LG2 R2, R4" (EX2 0x0800, RCP 0x1000, RSQ 0x1400 decode the same way). log2(x), approximate. */ - BW_IR_MUFU_LG2 /* MUFU.LG2 Rd, Ra */ -} 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; - uint32_t gpr_limit; /* 0: BW_PHYS_GPR_MAX; else the exclusive physical limit, <= BW_PHYS_GPR_HW_LIMIT */ -} 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); -/* Opt this program into physical registers up to limit - 1 (BW_PHYS_GPR_MAX < limit <= BW_PHYS_GPR_HW_LIMIT); call after - * omega_bw_ir_init. Every other program keeps the default, so its allocation is unchanged. 0 ok, -1 out of range. */ -int omega_bw_ir_set_gpr_limit(BlackwellIRProgram *prog, uint32_t limit); - -/* 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); -/* C6 kernel capture: writes code to $OMEGA_KERNEL_DUMP_DIR/.bin when that is set; no-op otherwise (see the .c) */ -void omega_kernel_dump(const uint8_t *code, size_t 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 060e25cff..000000000 --- a/src/omega_blackwell_codegen_attn.c +++ /dev/null @@ -1,565 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 4f84bba33..000000000 --- a/src/omega_blackwell_codegen_attn.h +++ /dev/null @@ -1,106 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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_attn256.c b/src/omega_blackwell_codegen_attn256.c deleted file mode 100644 index ecb4c1dae..000000000 --- a/src/omega_blackwell_codegen_attn256.c +++ /dev/null @@ -1,646 +0,0 @@ -/* - * omega_blackwell_codegen_attn256.c: the one-launch decode attention kernel for head_dim 256 (see the header). The - * emitter helpers are the ones of omega_blackwell_codegen_attn.c (control words, read barrier on every load, loop - * live ranges); the program follows that kernel with the 27B geometry and the dim-split V pass. - */ -#include "omega_blackwell_codegen_attn256.h" -#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_dattn256_shape(const OmegaDecodeAttn256Spec *spec, OmegaDattn256Shape *s) { - const uint32_t qh = spec->q_heads ? spec->q_heads : OMEGA_DATTN256_Q_HEADS; - const uint32_t kvh = spec->kv_heads ? spec->kv_heads : OMEGA_DATTN256_KV_HEADS; - const uint32_t h = spec->q_per_cta ? spec->q_per_cta : OMEGA_DATTN256_Q_PER_KV; - if (h < 1u || h > 6u || qh % h || kvh == 0 || (qh / h) % kvh) return -1; - const uint32_t g = (qh / h) / kvh; - if (g != 1u && g != 2u) return -1; - s->qh = qh; s->kvh = kvh; s->h = h; s->vy = qh / h; s->g = g; - s->qkv_words = (qh + 2u * kvh) * 256u; s->out_words = qh * 256u; - return 0; -} -#define RB OMEGA_DATTN256_ROW_BYTES -#define PBYTES (OMEGA_DATTN256_PARTIAL_WORDS * 4u) - -/* 8 consecutive f32 words (two quads) to shared at base + 0 .. 28 */ -static void sts8(Em *e, int base, int one, int t, int qa, int qb) { - for (unsigned i = 0; i < 8; i++) { imadi(e, R(t), R(one), i * 4u, base); sts32(e, t, i < 4 ? S(qa, i) : S(qb, i - 4)); } -} -/* sum of squares of 8 values, warp-reduced, broadcast through shared word `addr` (lane 0 writes), rs = RSQ(sum/256 + eps) */ -static void rms_scale(Em *e, int qa, int qb, int sq, int ts, int rs, int addr, int lane, int one, int eps) { - fmul(e, R(sq), S(qa, 0), S(qa, 0)); - for (unsigned i = 1; i < 4; i++) ffma(e, R(sq), S(qa, i), S(qa, i), R(sq)); - for (unsigned i = 0; i < 4; i++) ffma(e, R(sq), S(qb, i), S(qb, 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)); } - isetp_ge_u32(e, lane, one); - { Region r = region_skip_if_p0(e); sts32(e, addr, R(sq)); region_end(e, r); } - bar_sync(e); - lds32(e, R(sq), addr, 1); - movi(e, ts, 0x3b800000u); /* 1/256 */ - ffma(e, R(rs), R(sq), R(ts), R(eps)); - mufu(e, BW_IR_MUFU_RSQ, R(rs), R(rs)); -} - -int omega_blackwell_codegen_decode_attn256_prog(const OmegaDecodeAttn256Spec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog || spec->depth < 1 || spec->depth > OMEGA_DATTN256_MAX_DEPTH || spec->mutant < 0 || spec->mutant > 5 || spec->prep > 1 || spec->multi > 1) 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; - OmegaDattn256Shape SH; - if (omega_dattn256_shape(spec, &SH)) return -1; - const uint32_t H = SH.h; /* q heads per CTA row */ - const int OLD = SH.qh == OMEGA_DATTN256_Q_HEADS && SH.kvh == OMEGA_DATTN256_KV_HEADS && H == OMEGA_DATTN256_Q_PER_KV; - 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); - int pos = V(e), per = V(e), splits = 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); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pqkv, OMEGA_DATTN256_ARG_QKV); ldc64(e, pkc, OMEGA_DATTN256_ARG_KC); ldc64(e, pvc, OMEGA_DATTN256_ARG_VC); - ldc64(e, prope, OMEGA_DATTN256_ARG_ROPE); ldc64(e, pqn, OMEGA_DATTN256_ARG_QN); /* k_norm is read at q_norm + 1024 bytes (ARG_KN is informational) */ - ldc32(e, pos, OMEGA_DATTN256_ARG_POS); ldc32(e, per, OMEGA_DATTN256_ARG_PER_SPLIT); ldc32(e, splits, OMEGA_DATTN256_ARG_SPLITS); - ldc32(e, kvs, OMEGA_DATTN256_ARG_KV_STRIDE); ldc32(e, eps, OMEGA_DATTN256_ARG_EPS); - ldc32(e, qks, OMEGA_DATTN256_ARG_QK_SCALE); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - if (spec->prep && !spec->multi) { /* prefill prep (#545): CTA cx = token cx at position pos0 + cx, its qkv row */ - iadd(e, pos, pos, cx); - { int rowoff = V(e); if (e->err) return -1; imadi(e, R(rowoff), R(cx), SH.qkv_words * 4u, NOREG); imadw(e, pqkv, rowoff, 1u, pqkv); } - } - 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); - if (spec->multi) { /* L369 multi-token: the token, its position and qkv row (ARG_XSTRIDE bytes per row) */ - int tok = V(e), xs = V(e); if (e->err) return -1; - ldc32(e, xs, OMEGA_DATTN256_ARG_XSTRIDE); - if (spec->prep) mov(e, R(tok), R(cx)); /* prep: CTA (token, row) */ - else { /* attend: CTA (split, token * vy + row) */ - uint32_t lg = 0; while ((1u << lg) < SH.vy) lg++; - if ((1u << lg) != SH.vy) return -1; - shr(e, tok, cy, lg); andi(e, R(cy), R(cy), SH.vy - 1u); - } - iadd(e, pos, pos, tok); - imadr(e, xs, tok, xs, NOREG); imadw(e, pqkv, xs, 1u, pqkv); - if (!spec->prep) { /* this token's splits (per_split 256): CTAs past them exit */ - shr(e, splits, pos, 8); imadi(e, R(splits), R(splits), 1u, one); - imadi(e, R(xs), R(one), 0xffffffffu, splits); - isetp_ge_u32(e, xs, cx); - int bk = bra_if_p0_fwd(e); exit_k(e); patch_bra(e, bk, here(e)); - } - } - - /* 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); - if (SH.g == 1u) imadr(e, cyk, cy, kvs, NOREG); /* byte offset of this KV head's plane */ - else { shr(e, t1, cy, 1); imadr(e, cyk, t1, kvs, NOREG); } /* G = 2: KV head cy / 2 */ - - /* ---- prologue: one norm + rope block for all 8 warps. Warp h < 6 builds q'[h] (head cy*6+h, q_norm, * qk_scale); - * warp 6 builds k_new (k[cy], k_norm = q_norm + 1024 bytes, scale 1); warp 7 runs the block on v[cy] (the result is - * discarded) and reloads the raw v at the store. Warps 6, 7 stage in the s[][] region (unused until the chunk loop). ---- */ - int qa = V128(e), qb = V128(e), wa = V128(e), wb = V128(e), pa_ = V128(e), pb_ = V128(e); - int cosa = V128(e), cosb = V128(e), sina = V128(e), sinb = V128(e); - int sq = V(e), ts = V(e), rs = V(e), a0 = V(e), a1 = V(e), ad64 = V64(e), rope64 = V64(e), sgn = V(e), pl = V(e), f = V(e), voff = V(e), qksw = V(e); - if (e->err) return -1; - movi(e, t1, 5u); imadi(e, R(t1), R(warp), 0xffffffffu, t1); /* 5 - warp */ - shr(e, f, t1, 31); /* f = 1 for warps 6, 7 */ - /* byte offset of the vector in qkv: q head cy*6 + warp at (cy*6 + warp)*1024; k[cy] at 24576 + cy*1024 = warp*4096 + cy*1024 - * for warp 6; v[cy] at 28672 + cy*1024 = warp*4096 + cy*1024 for warp 7 */ - imadi(e, R(t1), R(cy), H, warp); imadi(e, R(t1), R(t1), 1024u, NOREG); - if (OLD) { imadi(e, R(t2), R(warp), 4096u, NOREG); imadi(e, R(t2), R(cy), 1024u, t2); } - else { /* q_heads*1024 + (warp - 6)*kv_heads*1024 + (cy / G)*1024 */ - if (SH.g == 1u) mov(e, R(t2), R(cy)); else shr(e, t2, cy, 1); - imadi(e, R(t2), R(t2), 1024u, NOREG); - imadi(e, R(t2), R(warp), SH.kvh * 1024u, t2); - imadi(e, R(t2), R(one), (SH.qh - 6u * SH.kvh) * 1024u, t2); - } - imadi(e, R(t2), R(t1), 0xffffffffu, t2); /* off_kv - off_q */ - imadr(e, voff, f, t2, t1); /* f ? off_kv : off_q */ - imadi(e, R(voff), R(lane), 32u, voff); /* + this lane's 8 dims */ - imadw(e, ad64, voff, 1u, pqkv); - ldg_wide(e, BW_IR_LDG_E_128, qa, ad64, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, qb, ad64, 16, udesc, 0); - imadi(e, R(t2), R(f), 1024u, NOREG); imadi(e, R(t2), R(lane), 32u, t2); /* q_norm, or k_norm 1024 bytes after it */ - imadw(e, ad64, t2, 1u, pqn); - ldg_wide(e, BW_IR_LDG_E_128, wa, ad64, 0, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, wb, ad64, 16, udesc, 0); - /* rope row for this lane: pair index = (lane & 15) * 8 .. +7 (dims 8i..8i+7 for lanes < 16, dims 128 + 8(i-16) above) */ - andi(e, R(t2), R(lane), 15u); - imadi(e, R(t2), R(t2), 32u, NOREG); - imadi(e, R(t2), R(pos), OMEGA_DATTN256_ROPE_ROW_BYTES, t2); - imadw(e, rope64, t2, 1u, prope); - ldg_wide(e, BW_IR_LDG_E_128, cosa, rope64, 0, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, cosb, rope64, 16, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, sina, rope64, 512, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, sinb, rope64, 528, udesc, 0); - /* sign of the sin term: lanes < 16 take x[d] * cos - x[d+128] * sin, lanes >= 16 take x[d] * cos + x[d-128] * 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(sina, i), S(sina, i), R(sgn)); xorr(e, S(sinb, i), S(sinb, i), R(sgn)); } - xorr(e, R(pl), R(lane), R(c16)); /* partner lane */ - - /* RMSNorm of the lane's 8 dims: sum of squares over the warp, broadcast through shared memory */ - imadi(e, R(a0), R(warp), 4u, NOREG); imadi(e, R(a0), R(one), OMEGA_DATTN256_SM_L, a0); - rms_scale(e, qa, qb, sq, ts, rs, a0, lane, one, eps); - for (unsigned i = 0; i < 4; i++) { fmul(e, S(qa, i), S(qa, i), R(rs)); fmul(e, S(qa, i), S(qa, i), S(wa, i)); fmul(e, S(qb, i), S(qb, i), R(rs)); fmul(e, S(qb, i), S(qb, i), S(wb, i)); } - /* stage, read the partner half, rotate */ - imadi(e, R(a0), R(warp), 1024u, NOREG); imadi(e, R(a0), R(lane), 32u, a0); /* SM_Q + warp*1024 + lane*32 (SM_Q = 0) */ - sts8(e, a0, one, t1, qa, qb); - bar_sync(e); - imadi(e, R(t2), R(warp), 1024u, NOREG); imadi(e, R(t2), R(pl), 32u, t2); - lds128(e, pa_, t2, 0, 1); lds128(e, pb_, t2, 16, 0); - if (MUT != 1) for (unsigned i = 0; i < 4; i++) { - fmul(e, R(ts), S(qa, i), S(cosa, i)); ffma(e, S(qa, i), S(pa_, i), S(sina, i), R(ts)); - fmul(e, R(ts), S(qb, i), S(cosb, i)); ffma(e, S(qb, i), S(pb_, i), S(sinb, i), R(ts)); - } - /* qksw = qk_scale for the q warps, 1.0f for warps 6, 7 (integer select on the bit patterns) */ - movi(e, ts, 0x3f800000u); imadi(e, R(ts), R(qks), 0xffffffffu, ts); imadr(e, qksw, f, ts, qks); - for (unsigned i = 0; i < 4; i++) { fmul(e, S(qa, i), S(qa, i), R(qksw)); fmul(e, S(qb, i), S(qb, i), R(qksw)); } - bar_sync(e); /* every partner read done before q' overwrites the staging */ - sts8(e, a0, one, t1, qa, qb); /* warps 6, 7 write scratch inside s[][] */ - if (spec->prep && !spec->multi) { - /* q' as bf16 in the attend kernel's A-fragment layout (omega_blackwell_codegen_pattn256.h, OMEGA_PATTN256_QF_*): - * word i of lane L (dims 8L+2i, +1) goes to ((((cx>>1)*4 + cy)*6 + warp)*16 + (L>>1))*64 + i*16 + ((L&1)*2 + (cx&1))*4. - * Warps 6, 7 (k, v) skip it. */ - int qw = V128(e), pqf = V64(e), qa64 = V64(e), h0q = V(e), h1q = V(e), tbq = V(e), fq = f; if (e->err) return -1; - if (H < 6u) { /* warps H .. 5 hold no head of this row: they skip q' too */ - fq = V(e); if (e->err) return -1; - movi(e, t1, H - 1u); imadi(e, R(t1), R(warp), 0xffffffffu, t1); shr(e, fq, t1, 31); - } - isetp_ge_u32(e, fq, one); - int bq = bra_if_p0_fwd(e); - for (unsigned w = 0; w < 4; w++) { - int src = w < 2 ? qa : qb; unsigned s0 = (2 * w) % 4; - bf16_of(e, h0q, S(src, s0), c7fff, tbq); bf16_of(e, h1q, S(src, s0 + 1), c7fff, tbq); imadi(e, S(qw, w), R(h1q), 65536u, h0q); - } - ldc64(e, pqf, OMEGA_DATTN256_ARG_OUT); - shr(e, t1, cx, 1); imadi(e, R(t1), R(t1), SH.vy, cy); imadi(e, R(t1), R(t1), H, warp); - shr(e, t2, lane, 1); imadi(e, R(t1), R(t1), 16u, t2); imadi(e, R(t1), R(t1), 64u, NOREG); - andi(e, R(t2), R(lane), 1u); imadi(e, R(t2), R(t2), 2u, NOREG); - { int cb = V(e); if (e->err) return -1; andi(e, R(cb), R(cx), 1u); iadd(e, t2, t2, cb); } - imadi(e, R(t1), R(t2), 4u, t1); - for (unsigned w = 0; w < 4; w++) { imadi(e, R(t2), R(one), 16u * w, t1); imadw(e, qa64, t2, 1u, pqf); stg(e, BW_IR_STG_E, qa64, S(qw, w), udesc); } - patch_bra(e, bq, here(e)); - } - - /* ---- the new token's K (warp 6: the rotated k) and V (warp 7: the raw v), bf16 into the cache by the CTA that owns `pos` ---- */ - if (MUT != 3 && !(spec->multi && !spec->prep)) { /* multi attend: the prep launch wrote every token's K/V */ - int sa64 = V64(e), sb64 = V64(e), key = V(e), h0 = V(e), h1 = V(e), tb = V(e); - /* key = (splits - 1 - cx) + 1 - f: zero only for warps 6, 7 of the last split */ - imadi(e, R(t2), R(cx), 0xffffffffu, splitsm1); - imadi(e, R(t2), R(one), 1u, t2); - if (spec->prep) imadi(e, R(key), R(f), 0xffffffffu, one); /* prep: every CTA owns its token: key = 1 - f */ - else imadi(e, R(key), R(f), 0xffffffffu, t2); - isetp_ge_u32(e, key, one); - int b1 = bra_if_p0_fwd(e); - /* cache row address of position pos for this lane: 8 bf16 = 16 bytes per lane; K plane, V plane for warp 7 */ - imadi(e, R(t1), R(pos), RB, cyk); imadi(e, R(t1), R(lane), 16u, t1); - imadw(e, sa64, t1, 1u, pkc); - movi(e, t2, 7u); imadi(e, R(t2), R(warp), 0xffffffffu, t2); /* 7 - warp: zero for warp 7 */ - isetp_ge_u32(e, t2, one); - { Region r = region_skip_if_p0(e); - imadw(e, sb64, voff, 1u, pqkv); - ldg_wide(e, BW_IR_LDG_E_128, qa, sb64, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, qb, sb64, 16, udesc, 0); - imadw(e, sa64, t1, 1u, pvc); - region_end(e, r); } - for (unsigned w = 0; w < 4; w++) { - int src = w < 2 ? qa : qb; unsigned s0 = (2 * w) % 4; - bf16_of(e, h0, S(src, s0), c7fff, tb); bf16_of(e, h1, S(src, s0 + 1), c7fff, tb); imadi(e, S(wa, w), R(h1), 65536u, h0); - } - for (unsigned w = 0; w < 4; w++) { imadw(e, sb64, one, 4u * w, sa64); stg(e, BW_IR_STG_E, sb64, S(wa, w), udesc); } - patch_bra(e, b1, here(e)); - } - membar(e); - if (spec->prep) { /* prep ends here: the K/V rows and q' are written */ - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); - } - bar_sync(e); - - /* ---- running state ---- */ - int acc[6], m[6], l[6], sc[6], dl[6], wd[8], mn = V(e); - for (unsigned h = 0; h < H; h++) { acc[h] = V128(e); m[h] = V(e); l[h] = V(e); sc[h] = V(e); dl[h] = V(e); } - for (unsigned q = 0; q < 8; q++) wd[q] = V(e); - int kq[OMEGA_DATTN256_MAX_DEPTH], vq[OMEGA_DATTN256_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), hoff = V(e), wp = V(e), negwp = V(e), ccnt = V(e); - if (e->err) return -1; - for (unsigned h = 0; h < H; 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_DATTN256_SM_S); - shr(e, wp, warp, 1); /* warp pair index 0..3 */ - imadi(e, R(negwp), R(wp), 0xffffffffu, NOREG); - andi(e, R(hoff), R(warp), 1u); - imadi(e, R(hoff), R(hoff), 256u, NOREG); /* byte offset of this warp's dim half in the row */ - imadi(e, R(hoff), R(lane), 8u, hoff); /* + 4 bf16 = 8 bytes per lane */ - if (MUT == 2) imadi(e, R(hoff), R(one), RB, hoff); - movi(e, ccnt, 32); - 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), RB, cyk); - imadw(e, krow, t1, 1u, pkc); - for (unsigned h = 0; h < H; 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 < H; h++) { - lds128(e, qa4, qoff, h * 1024u, 1); lds128(e, qb4, qoff, h * 1024u + 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 < H; 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 + wp + 4 i, i < n = max(0, ceil((min(end, cb + 256) - cb - wp) / 4)) */ - imadi(e, R(t1), R(one), OMEGA_DATTN256_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, negwp); /* x = cend - cb - wp */ - shr(e, over, t1, 31); - imadi(e, R(n), R(one), 3u, t1); - shr(e, n, n, 2); - imadr(e, t2, over, n, NOREG); - imadi(e, R(n), R(t2), 0xffffffffu, n); - imadi(e, R(t1), R(cb), 1u, wp); - imadi(e, R(t1), R(t1), RB, hoff); - 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 * 4u * RB, udesc, d == 0); - imadw(e, vpf, one, D * 4u * RB, vrow); - imadi(e, R(pa), R(wp), 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); -#define SH(h) ((h) < 4 ? S(qa4, (h)) : S(qb4, (h) - 4)) - for (unsigned h = 0; h < H; h++) { fmaxx(e, R(mn), R(m[h]), SH(h)); 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 < H; 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 < H; h++) mufu(e, BW_IR_MUFU_EX2, R(dl[h]), R(dl[h])); - for (unsigned h = 0; h < H; 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 < H; h++) { fsub(e, R(dl[h]), SH(h), R(m[h])); mufu(e, BW_IR_MUFU_EX2, R(dl[h]), R(dl[h])); } -#undef SH - for (unsigned h = 0; h < H; 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, 4u * RB, vpf); - imadi(e, R(pa), R(one), 4u * 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_DATTN256_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_DATTN256_ARG_OUT); ldc64(e, ppart, OMEGA_DATTN256_ARG_PART); ldc64(e, pcnt, OMEGA_DATTN256_ARG_CNT); ldc32(e, oscale, OMEGA_DATTN256_ARG_OUT_SCALE); - if (spec->multi) { /* the token's output row, partials block and counters (ctaid.y re-read: no live register) */ - int tk = V(e), so = V(e); if (e->err) return -1; - uint32_t lg = 0; while ((1u << lg) < SH.vy) lg++; - s2r(e, tk, BW_SR_CTAID_Y); shr(e, tk, tk, lg); - ldc32(e, so, OMEGA_DATTN256_ARG_OSTRIDE); imadr(e, so, tk, so, NOREG); imadw(e, pout, so, 1u, pout); - ldc32(e, so, OMEGA_DATTN256_ARG_PSTRIDE); imadr(e, so, tk, so, NOREG); imadw(e, ppart, so, 1u, ppart); - imadi(e, R(so), R(tk), SH.vy * 4u, NOREG); imadw(e, pcnt, so, 1u, pcnt); - } - /* 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_DATTN256_SM_M, a0); - isetp_ge_u32(e, lane, one); - { Region r = region_skip_if_p0(e); for (unsigned h = 0; h < H; 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..5 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, H); - 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_DATTN256_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_DATTN256_SM_M + 256u); - lds128(e, qa4, t1, 0, 1); lds128(e, qb4, t1, 16, 0); - for (unsigned h = 0; h < H; 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 < H; 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..5 (l summed over the even warps: the odd ones repeat them) */ - imadi(e, R(a0), R(warp), 32u, NOREG); imadi(e, R(a0), R(one), OMEGA_DATTN256_SM_L, a0); - isetp_ge_u32(e, lane, one); - { Region r = region_skip_if_p0(e); for (unsigned h = 0; h < H; 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), PBYTES, NOREG); - imadw(e, pp, t2, 1u, ppart); - isetp_ge_u32(e, tid, ccnt); /* tid >= 6 skips */ - { - Region r = region_skip_if_p0(e); - imadi(e, R(a1), R(tid), 4u, NOREG); imadi(e, R(a1), R(one), OMEGA_DATTN256_SM_L, a1); - for (unsigned w = 0; w < 4; w++) { imadi(e, R(t1), R(one), w * 64u, a1); lds32(e, R(ep[w]), t1, w == 0); } - for (unsigned w = 1; w < 4; 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_DATTN256_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, 4u * H, pa64); - stg(e, BW_IR_STG_E, pb64, R(ep[0]), udesc); /* l[h] */ - region_end(e, r); - } - /* acc: 6 rounds of one head through the s[][] region as r[w][256]: warp w writes its dim half, thread tid sums the - * 4 warps that hold dim tid (warps (tid >> 7) + 2k); the store and load addresses computed once */ - imadi(e, R(a0), R(warp), 1024u, NOREG); imadi(e, R(a0), R(lane), 16u, a0); - andi(e, R(t1), R(warp), 1u); imadi(e, R(a0), R(t1), 512u, a0); imadi(e, R(a0), R(one), OMEGA_DATTN256_SM_S, a0); - shr(e, t1, tid, 7); - if (MUT == 5) movrz(e, R(t1)); - imadi(e, R(a1), R(t1), 1024u, NOREG); imadi(e, R(a1), R(tid), 4u, a1); imadi(e, R(a1), R(one), OMEGA_DATTN256_SM_S, a1); - for (unsigned q = 0; q < 4; q++) imadi(e, R(eb[q]), R(one), q * 4u, a0); - for (unsigned w = 0; w < 4; w++) imadi(e, R(ea[w]), R(one), w * 2048u, a1); - imadw(e, pa64, tid, 4u, pp); - for (unsigned rd = 0; rd < H; rd++) { - for (unsigned q = 0; q < 4; q++) sts32(e, eb[q], S(acc[rd], q)); - bar_sync(e); - for (unsigned w = 0; w < 4; w++) lds32(e, R(ep[w]), ea[w], w == 0); - for (unsigned w = 1; w < 4; w++) fadd(e, R(ep[0]), R(ep[0]), R(ep[w])); - imadw(e, pb64, one, 8u * H + 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_DATTN256_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 r, dim tid), r = 0..5 */ - 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; - movrz(e, R(ho)); - mov(e, R(oidx), R(tid)); - movrz(e, R(rr)); - movi(e, ccnt, H); - imadr(e, t2, cy, splits, NOREG); - imadi(e, R(t2), R(t2), PBYTES, 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, 4u * H, ma); - imadi(e, R(t1), R(oidx), 4u, t2); imadw(e, aa, t1, 1u, ppart); imadw(e, aa, one, 8u * H, 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, PBYTES, ma); - imadw(e, la, one, PBYTES, la); - imadw(e, aa, one, PBYTES, 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), H * 256u, oidx); - imadw(e, pb64, t1, 4u, pout); - stg(e, BW_IR_STG_E, pb64, R(num), udesc); - imadi(e, R(ho), R(one), 1u, 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_attn256_prog_stats(const OmegaDecodeAttn256Spec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_decode_attn256_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_attn256.h b/src/omega_blackwell_codegen_attn256.h deleted file mode 100644 index cf72ac548..000000000 --- a/src/omega_blackwell_codegen_attn256.h +++ /dev/null @@ -1,130 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_ATTN256_H -#define OMEGA_BLACKWELL_CODEGEN_ATTN256_H -/* - * omega_blackwell_codegen_attn256: decode attention for Qwen3.8-27B in ONE launch per layer (omega-mv#544, - * 2026-10-18). A derivative of omega_blackwell_codegen_attn.h (head_dim 128, 8 q per kv) for the 27B's full-attention - * layers: 24 query heads, 4 KV heads (6 q per kv), head_dim 256, per-head RMSNorm on q and k (the caller folds the - * model's zero-centred weights to 1 + w), rotary embedding from a host-built cos/sin table, the new token's K/V - * appended to the GPU-resident bf16 cache inside the kernel, softmax over the whole context, output scaled by - * `out_scale` ready for the gate (sigmoid(gate) * out happens outside) and o_proj. - * - * Partial RoPE by permutation (design decision 1 of #544): the kernel rotates the standard half pairs (i, i + 128) of - * its 256-wide head with table row [cos 128 | sin 128]; the host builds the table so only the first P pairs rotate - * (inv_freq_j = theta^(-2j / rotary_dim), rotary_dim = 2P) and the rest are identity (cos 1, sin 0). The engine - * permutes the q and k dims (and q_norm / k_norm) at load with omega_dattn256_perm (omega_gpu_decode_attn256_api.h) - * so the model's rotate-half within its first rotary_dim dims lands on those P pairs. Scores are invariant to a - * shared q/k permutation; V and the output are not permuted. The K cache holds permuted rows. - * - * Grid: (splits, kv_heads). CTA (cx, cy) handles KV head cy and the positions [cx*per_split, min(+per_split, pos+1)); - * the host picks splits = ceil((pos+1)/per_split), so no CTA is empty. 8 warps = 256 threads per CTA. - * - * Per CTA: - * prologue one norm + rope block for all 8 warps (8 f32 per lane): warp h < 6 builds q'[h] = RoPE(table[pos], - * RMSNorm(q[cy*6+h], q_norm, eps)) * qk_scale, staged in shared memory as q'[h][256]; warp 6 builds - * k_new = RoPE(RMSNorm(k[cy], k_norm)) the same way (k_norm lives 1024 bytes after q_norm); warp 7 runs - * the block on v[cy] (result discarded) and reloads the raw v. In the CTA whose range holds `pos` (the - * last split) warps 6 and 7 write k_new and v_new as bf16 into the cache at [cy][pos], then MEMBAR + - * BAR.SYNC, so its own stream reads them back. - * chunks of 256 positions: score pass (thread = position: the 512-byte bf16 K row streamed in 32 quads with a - * `depth`-deep prefetch, 6 dot products against q' from shared memory, scores to shared s[t][8], 6 used); - * V pass (warp pair: warp w handles positions (w>>1) + 4i of the chunk and the dims 128*(w&1) .. +127; - * lane = 4 dims, LDG.64 per position; 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. The two - * warps of a pair see the same positions, so their (m, l) are bit-identical). - * epilogue warps combine (m over all 8, l over the even warps, acc over the 4 warps that hold each dim half) - * through shared memory and write the CTA partial {m[6], l[6], acc[6][256]} 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*6+h)*256+d] * out_scale, and resets the counter. - * - * Numbers (f32 on the chip, double in the host reference, tolerances in tests/gpu_decode_attn256_test.c): - * scores in log2 units: q' already carries (1/sqrt(256)) * 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. - * - * Shared memory stays under the 16 KiB QMD cap (14896 bytes), registers under the chip allocator's 126. - * 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_DATTN256_HEAD_DIM 256u -#define OMEGA_DATTN256_Q_PER_KV 6u -#define OMEGA_DATTN256_KV_HEADS 4u -#define OMEGA_DATTN256_Q_HEADS 24u -#define OMEGA_DATTN256_WARPS 8u -#define OMEGA_DATTN256_CHUNK 256u /* positions per score pass = threads per CTA */ -#define OMEGA_DATTN256_ROW_BYTES 512u /* one bf16 K or V row */ -#define OMEGA_DATTN256_ROPE_ROW_BYTES 1024u /* cos[128] then sin[128], f32 */ -#define OMEGA_DATTN256_PARTIAL_WORDS 1548u /* m[6], l[6], acc[6][256] */ -#define OMEGA_DATTN256_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_DATTN256_PLANE_SLACK (OMEGA_DATTN256_MAX_DEPTH * 4u * OMEGA_DATTN256_ROW_BYTES + 64u) -#define OMEGA_DATTN256_QKV_WORDS (OMEGA_DATTN256_Q_HEADS * 256u + 2u * OMEGA_DATTN256_KV_HEADS * 256u) /* 8192 */ -#define OMEGA_DATTN256_OUT_WORDS (OMEGA_DATTN256_Q_HEADS * 256u) /* 6144 */ - -/* constant bank: every address at 0x380 + 8n, then the scalars */ -#define OMEGA_DATTN256_ARG_QKV 0x380u /* f32 [24*256 q | 4*256 k | 4*256 v] (the gate is NOT part of it) */ -#define OMEGA_DATTN256_ARG_KC 0x388u /* bf16 K cache base: [kv_head][max_pos][256], kv_stride bytes per head */ -#define OMEGA_DATTN256_ARG_VC 0x390u /* bf16 V cache base, same layout */ -#define OMEGA_DATTN256_ARG_ROPE 0x398u /* f32 [max_pos][cos 128 | sin 128] */ -#define OMEGA_DATTN256_ARG_QN 0x3a0u /* f32 [256] q_norm weight (1 + w, permuted) */ -#define OMEGA_DATTN256_ARG_KN 0x3a8u /* f32 [256] k_norm weight (1 + w, permuted); MUST be ARG_QN + 1024 bytes: the kernel addresses it so */ -#define OMEGA_DATTN256_ARG_OUT 0x3b0u /* f32 [24][256] */ -#define OMEGA_DATTN256_ARG_PART 0x3b8u /* f32 [kv_heads][splits][1548] */ -#define OMEGA_DATTN256_ARG_CNT 0x3c0u /* u32 [kv_heads], zero before the launch */ -#define OMEGA_DATTN256_ARG_POS 0x3c8u /* u32 position of the new token; context = pos + 1 */ -#define OMEGA_DATTN256_ARG_PER_SPLIT 0x3ccu /* u32 positions per CTA (multiple of 256) */ -#define OMEGA_DATTN256_ARG_SPLITS 0x3d0u /* u32 = grid_x */ -#define OMEGA_DATTN256_ARG_KV_STRIDE 0x3d4u /* u32 bytes per KV head plane */ -#define OMEGA_DATTN256_ARG_EPS 0x3d8u /* f32 rms eps */ -#define OMEGA_DATTN256_ARG_OUT_SCALE 0x3dcu /* f32 multiplier on the output */ -#define OMEGA_DATTN256_ARG_QK_SCALE 0x3e0u /* f32 (1/sqrt(256)) * log2(e) */ -#define OMEGA_DATTN256_ARGS_WORDS 25u -/* L369 multi-token mode (spec.multi = 1) only: */ -#define OMEGA_DATTN256_ARG_XSTRIDE 0x3e4u /* u32 bytes between token t and t+1 qkv rows */ -#define OMEGA_DATTN256_ARG_OSTRIDE 0x3e8u /* u32 bytes between output rows (attend) */ -#define OMEGA_DATTN256_ARG_PSTRIDE 0x3ecu /* u32 bytes between tokens' partial blocks (attend; >= vy * splits * 6192) */ -#define OMEGA_DATTN256_MULTI_ARGS_WORDS 28u - -/* shared memory map (bytes) */ -#define OMEGA_DATTN256_SM_Q 0u /* q'[6][256] f32: 6144 (warps 6, 7 stage k and v at 6144.. 8191: inside SM_S, unused then) */ -#define OMEGA_DATTN256_SM_S 6144u /* s[256][8] f32 (6 used): 8192; reused as the reduce buffer r[8 warps][256] */ -#define OMEGA_DATTN256_SM_M 14336u /* m[8 warps][8] then the head maxes M[8]: 256 + 32 */ -#define OMEGA_DATTN256_SM_L 14624u /* l[8 warps][8]: 256 */ -#define OMEGA_DATTN256_SM_FLAG 14880u /* the atomic's old value: 16 */ -#define OMEGA_DATTN256_SHARED_BYTES 14896u - -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); - * 5 the odd warps' dim half is dropped from the partial (dims 128..255 wrong). */ - uint32_t prep; /* 1: the prefill prep launch (omega-mv#545): grid (m, 4), CTA (cx, cy) runs this kernel's prologue for - * token cx at position ARG_POS + cx (qkv row cx, 32768 bytes per row), writes k_new / v_new into the - * cache rows as the decode step does (same instruction sequence, so the same bits), writes q' as bf16 - * to ARG_OUT in the attend kernel's A-fragment layout (OMEGA_PATTN256_QF_*), and exits. Mutants 1 - * and 3 apply; ARG_PART, ARG_CNT, ARG_PER_SPLIT, ARG_SPLITS and ARG_OUT_SCALE are not read. */ - uint32_t q_heads, kv_heads, q_per_cta; /* Q36 (sc L306): the model shape. 0, 0, 0 = 24, 4, 6 (Qwen3.8-27B, the program - * before these fields existed). Qwen3.6-35B-A3B: 16, 2, 4. The grid is (splits, q_heads / q_per_cta): CTA row cy - * ("virtual head") owns q heads cy*q_per_cta .. +q_per_cta-1 and reads KV head cy / G, G = (q_heads / q_per_cta) / - * kv_heads (1 or 2; with 2 both CTA rows of a KV head write the same new K/V bits to the cache). q_per_cta <= 6 - * (warps 6, 7 build k and v). Appended last. */ - uint32_t multi; /* L369: 1 = T prompt tokens at positions ARG_POS + t, qkv rows ARG_XSTRIDE bytes apart (per_split must be 256; - * vy a power of two). With prep = 1: grid (T, vy), CTA (t, cy) writes token t's k_new / v_new into the cache - * exactly as prep does and nothing else (no q'). With prep = 0 (attend): grid (splits_max, T * vy), CTA (cx, t * - * vy + cy) is the decode step of token t (splits = pos_t / 256 + 1; CTAs with cx >= splits exit at once) WITHOUT - * the K/V append (the prep launch before it wrote every token's rows; a split never reads past its token); - * out row t at ARG_OUT + t * ARG_OSTRIDE, partials at ARG_PART + t * ARG_PSTRIDE, counters at ARG_CNT + t * vy * 4. - * Every value is the decode launch's, bit for bit (same instructions, same combine order). */ -} OmegaDecodeAttn256Spec; - -/* The shape a spec selects: 0 ok, -1 unsupported. */ -typedef struct { uint32_t qh, kvh, h, vy, g, qkv_words, out_words; } OmegaDattn256Shape; -int omega_dattn256_shape(const OmegaDecodeAttn256Spec *spec, OmegaDattn256Shape *s); - -/* Builds the IR program (register-allocated) into *prog. 0 ok, -1 refused (depth 0 or > 4, mutant outside 0..5, - * or the program outgrew BW_MAX_IR_INSNS / BW_MAX_VREGS). */ -int omega_blackwell_codegen_decode_attn256_prog(const OmegaDecodeAttn256Spec *spec, BlackwellIRProgram *prog); -/* Instruction and peak-register counts of the program (host, no device). */ -int omega_decode_attn256_prog_stats(const OmegaDecodeAttn256Spec *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 4a02b058f..000000000 --- a/src/omega_blackwell_codegen_bf16.c +++ /dev/null @@ -1,333 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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" -#include "omega_blackwell_qmd.h" /* OMEGA_BW_QMD_MAX_SHARED_BYTES: the XBATCH x stage must fit the launch descriptor */ -#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); } -static void fmaxr(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 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); } -/* 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 int bra_ifnot_p0_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.predicate_not = true; i.imm = 1; emit(e, i, K_BRA); return at; } -static int bra_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); 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->mask > 1) return 0; - if (s->mask && (s->rows != 1 || s->ystride || s->xbatch > 1)) return 0; /* MASK form: one row per warp, one x row */ - const uint32_t xb = s->xbatch ? s->xbatch : 1u; - if (xb > OMEGA_BF16_MAX_XBATCH) return 0; - if (xb > 1u && (s->ystride == 0 || s->rows * xb > 16u || (uint64_t)xb * s->k * 4u > OMEGA_BW_QMD_MAX_SHARED_BYTES)) return 0; - if (xb > 1u && ((uint64_t)xb * s->k > 512u * s->warps || (uint64_t)(xb - 1u) * s->ystride * 4u >= (1ull << 31))) return 0; /* 16 staging rounds; y row offsets as immediates */ - /* mutant 4: MASK inverts the skip, XBATCH reads row 0's x for every row (the forms never mix) */ - if (s->mutant < 0 || s->mutant > 4 || (s->mutant == 4 && !s->mask && xb < 2u)) return 0; - if (s->ystride > (1u << 28)) return 0; /* ystride * 4 fits the 32-bit IMAD.WIDE immediate */ - 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 * (spec->xbatch ? spec->xbatch : 1u) : 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; - const uint32_t XB = spec->xbatch ? spec->xbatch : 1u; /* XBATCH form: x rows per CTA sharing every weight read */ - 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); - if (spec->ystride && XB == 1u) { /* ROWS form: this CTA row's x and y */ - int cy = V(e); - if (e->err) return -1; - s2r(e, cy, BW_SR_CTAID_Y); - imadw(e, px, cy, K * 4u, px); - imadw(e, py, cy, spec->ystride * 4u, py); - } - 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, XB rows back to back) in shared memory: one 32-bit word per thread per round ---- */ - { - const uint32_t rounds = XB * 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][4], wq[4][16], xq[4][2]; - for (uint32_t r = 0; r < R; r++) { for (uint32_t m = 0; m < XB; m++) acc[r][m] = V(e); for (uint32_t s = 0; s < D; s++) wq[r][s] = V128(e); } - for (uint32_t m = 0; m < XB; m++) { xq[m][0] = V128(e); xq[m][1] = V128(e); } - if (e->err) return -1; - /* ---- MASK form: tau once, normalized (-0 -> +0); -inf for the skipped rows ---- */ - int phi = NOREG, tn = NOREG, zero = NOREG, ninf = NOREG, phr = NOREG, hv = NOREG, mv = NOREG; - if (spec->mask) { - int ptau = V64(e); - phi = V64(e); tn = V(e); zero = V(e); ninf = V(e); phr = V64(e); hv = V(e); mv = V(e); - if (e->err) return -1; - ldc64(e, phi, OMEGA_BF16_ARG_HI); ldc64(e, ptau, OMEGA_BF16_ARG_TAU); - ldg32(e, tn, ptau, udesc, 1); - movrz(e, zero); - fadd(e, tn, tn, zero); - movi(e, ninf, 0xff800000u); - } - - /* ---- 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); - int bra_skip_row = -1; - if (spec->mask) { /* warp-uniform: every lane loads the same hi[rg] */ - imadw(e, phr, rg, 4u, phi); - ldg32(e, hv, phr, udesc, 1); - fadd(e, hv, hv, zero); - fmaxr(e, mv, hv, tn); - xorr(e, mv, mv, hv); - isetp_ge_u32(e, mv, one); /* P0: hi < tau (the max is not hi) */ - bra_skip_row = spec->mutant == 4 ? bra_ifnot_p0_fwd(e) : 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++) for (uint32_t m = 0; m < XB; m++) movrz(e, acc[r][m]); - 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; - for (uint32_t m = 0; m < XB; m++) { /* x row m of this step (mutant 4: every row reads row 0) */ - const uint32_t moff = spec->mutant == 4 ? 0u : m * K * 4u; - lds128(e, xq[m][0], xl, xoff + moff, m == 0); lds128(e, xq[m][1], xl, xoff + moff + 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 unsigned sub = (word & 1u) * 2u; - /* low half = element 2 word, high half = element 2 word + 1; the same FMA order per (r, m) as with one x row */ - imadi(e, f, wq[r][s], word, 65536u, NOREG); - for (uint32_t m = 0; m < XB; m++) ffma(e, acc[r][m], f, xq[m][word >> 1], spec->mutant == 1 ? sub + 1u : sub, acc[r][m]); - andi(e, f, wq[r][s], word, 0xffff0000u); - for (uint32_t m = 0; m < XB; m++) ffma(e, acc[r][m], f, xq[m][word >> 1], spec->mutant == 1 ? sub : sub + 1u, acc[r][m]); - } - } - } - 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 m = 0; m < XB; m++) - for (uint32_t o = 16; o >= 1; o /= 2) { shfl_down(e, t, acc[r][m], o); fadd(e, acc[r][m], acc[r][m], 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++) - for (uint32_t m = 0; m < XB; m++) { imadw(e, pya, one, r * 4u + m * spec->ystride * 4u, pyr); stg(e, pya, 0, acc[r][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); - if (spec->mask) { /* skipped row: every lane stores the same -inf to y[rg] */ - const int bra_next = bra_fwd(e); - patch_bra(e, bra_skip_row, here(e)); - imadw(e, pyr, rg, 4u, py); - stg(e, pyr, 0, ninf, udesc); - patch_bra(e, bra_next, here(e)); - } - 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 d3153eaa2..000000000 --- a/src/omega_blackwell_codegen_bf16.h +++ /dev/null @@ -1,106 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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. ROWS form (spec.ystride != 0, sc #642 prefill): grid_y token rows, row cy reads x + cy * k - * floats and writes y + cy * ystride floats (the Qwen3.8-27B DeltaNet a|b projection of a prefill chunk). - * MASK form (spec.mask = 1, rows 1, one x row; HUM L314 exact two-pass head): before row r's K loop the warp loads - * hi[r] (f32) and the threshold tau (one f32: the max of the screen's lower bounds, written by ARGMAX); a row with - * hi[r] < tau stores -inf and skips its K loop, every other row runs the unchanged K loop and reduction, so its y[r] - * is bit for bit the plain kernel's. No FSETP (never proven on the chip): h = hi + 0, t = tau + 0 (-0 becomes +0), - * m = FMNMX.MAX(h, t), skip iff (m XOR h) != 0. hi and tau must not be NaN (the screen writes finite values). - * - * XBATCH form (spec.xbatch 2..4, L312 stroke: the lm_head once for all heads): xbatch x rows (row m at x + m * k floats, - * all staged in shared memory: k * 4 * xbatch bytes) share every weight read; each (weight row, x row) accumulates in the - * SAME order as the one-row kernel, so every output row is bit-identical to the one-row GEMV of its own x; y row m - * goes to y + m * ystride floats (ystride >= n, required). grid_y stays 1. - * MASK and XBATCH never mix (spec_ok refuses mask with xbatch > 1). - * - * 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. - * 4 (MASK form): inverts the skip decision. - * 4 (XBATCH form): every x row reads row 0's x (rows 1.. wrong). Must be caught by the xbatch 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_ARG_HI 0x3a0u /* MASK form: u64 hi (f32, n) */ -#define OMEGA_BF16_ARG_TAU 0x3a8u /* MASK form: u64 tau (one f32) */ -#define OMEGA_BF16_MASK_ARGS_WORDS 12u -#define OMEGA_BF16_STEP_BYTES 512u /* weight bytes per row per K step (32 lanes x 16) */ -#define OMEGA_BF16_MAX_XBATCH 4u /* x rows per CTA in the XBATCH form (f32 rows staged in shared: 4 x 8 KiB at k 2048) */ - -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 */ - uint32_t ystride; /* 0: one x row (grid_y 1). Else the ROWS form: token row ctaid.y reads x + cy * k and writes - * y + cy * ystride (floats; ystride >= n). The default program is unchanged. */ - uint32_t xbatch; /* 0 or 1: one x row. 2..OMEGA_BF16_MAX_XBATCH: the XBATCH form (needs ystride >= n): x rows at - * x + m * k floats share every weight read, y row m at y + m * ystride. */ - uint32_t mask; /* 0: every row. 1: the MASK form (rows 1, ystride 0). The default program is unchanged. */ -} 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 ce13b27c4..000000000 --- a/src/omega_blackwell_codegen_dec.c +++ /dev/null @@ -1,697 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 uint32_t f32_bits(float f) { uint32_t u; memcpy(&u, &f, sizeof u); return u; } - -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; -} - -/* n quads of a thread's contiguous run at a + 16 q: one read barrier chain (the first load opens it) */ -static void ldg_quads(Em *e, const int *q, unsigned n, int a, uint32_t base, int udesc) { - for (unsigned k = 0; k < n; k++) ldg(e, BW_IR_LDG_E_128, q[k], a, base + 16u * k, udesc, k == 0); -} -static int new_quads(Em *e, int *q, unsigned n) { for (unsigned k = 0; k < n; k++) q[k] = V128(e); return e->err; } - -#define RES_MAX_VALS 32u /* width 8192 */ - -static int gen_res(Em *e, const OmegaDecSpec *sp) { - const uint32_t M = sp->mode, H = sp->width ? sp->width : OMEGA_DEC_HIDDEN, N = H / OMEGA_DEC_THREADS, Q = N / 4u; - if ((M & 7u) == 0 || M > 15 || ((M & OMEGA_DEC_RES_ADD) && (M & OMEGA_DEC_RES_COMBINE))) return -1; - /* COMBINE in the rows form (L356): row ctaid.y also moves the routing weights by stride bytes (16-aligned, the 128-bit loads) - * and the down outputs by groups * 2048 floats; every row's arithmetic is the one-row program's */ - if ((M & OMEGA_DEC_RES_ROWS) && (M & OMEGA_DEC_RES_COMBINE) && (sp->stride == 0 || sp->stride % 16u)) return -1; - if ((sp->groups && (sp->groups != 8u && sp->groups != 9u)) || (sp->groups == 9u && !(M & OMEGA_DEC_RES_COMBINE)) || (sp->mutant == 3 && sp->groups != 9u)) return -1; - if (H % (4u * OMEGA_DEC_THREADS) || N > RES_MAX_VALS || ((M & OMEGA_DEC_RES_COMBINE) && H != OMEGA_DEC_HIDDEN)) 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), xq[RES_MAX_VALS / 4]; - if (new_quads(e, xq, Q)) 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), 4u * N, NOREG); - int cy = -1; - int roff = toff; /* the row's x, a and y offset: toff, plus ctaid.y * width in the rows form */ - if (M & OMEGA_DEC_RES_ROWS) { - cy = V(e); roff = V(e); - if (e->err) return -1; - s2r(e, cy, BW_SR_CTAID_Y); - imadi(e, R(roff), R(cy), 4u * H, toff); - } - imadw(e, xa, roff, 1u, px); - ldg_quads(e, xq, Q, xa, 0, udesc); - Op x[RES_MAX_VALS]; - for (unsigned i = 0; i < N; i++) x[i] = S(xq[i / 4], i % 4); - if (M & OMEGA_DEC_RES_ADD) { - int aa = V64(e), aq[RES_MAX_VALS / 4]; - if (new_quads(e, aq, Q)) return -1; - imadw(e, aa, roff, 1u, pa); - ldg_quads(e, aq, Q, aa, 0, udesc); - for (unsigned i = 0; i < N; i++) fadd(e, x[i], x[i], S(aq[i / 4], i % 4)); - } - if (M & OMEGA_DEC_RES_COMBINE) { - const unsigned GR = sp->groups ? sp->groups : OMEGA_DEC_TOPK; /* 8, or 9 with the shared expert (Qwen3.6-35B-A3B) */ - int wq0 = V128(e), wq1 = V128(e), wq8 = GR > 8u ? V(e) : -1, 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; - int pwr = pw, doff = toff; /* the row's weights and down outputs: row 0's, moved by ctaid.y in the rows form */ - if (M & OMEGA_DEC_RES_ROWS) { - pwr = V64(e); doff = V(e); - if (e->err) return -1; - imadw(e, pwr, cy, sp->stride, pw); - imadi(e, R(doff), R(cy), GR * OMEGA_DEC_HIDDEN * 4u, toff); - } - ldg(e, BW_IR_LDG_E_128, wq0, pwr, 0, udesc, 1); ldg(e, BW_IR_LDG_E_128, wq1, pwr, 16, udesc, 0); - if (GR > 8u) { /* the 32-bit LDG.E carries no immediate offset: its own address */ - int pw8 = V64(e); if (e->err) return -1; - imadw(e, pw8, one, 32u, pwr); ldg(e, BW_IR_LDG_E, wq8, pw8, 0, udesc, 0); - } - imadw(e, da, doff, 1u, pa); - const unsigned G = sp->mutant == 2 ? 7u : sp->mutant == 3 ? 8u : GR; - 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) : g < 8 ? S(wq1, g - 4) : R(wq8); - 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 < N; i++) { if (i == 0) imadw(e, sa, roff, 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), nq[RES_MAX_VALS / 4]; - new_quads(e, nq, Q); - int ya = V64(e), yv = V(e); /* allocated after the quads, as before the width field: the same program at 2048 */ - if (e->err) return -1; - imadw(e, na, toff, 1u, pnw); - ldg_quads(e, nq, Q, na, 0, udesc); - fmul(e, R(sq), x[0], x[0]); - for (unsigned i = 1; i < N; 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, H == OMEGA_DEC_HIDDEN ? C_INV2048 : f32_bits(1.0f / (float)H)); - ffma(e, R(rs), R(sq), R(t2), R(eps)); - mufu(e, BW_IR_MUFU_RSQ, R(rs), R(rs)); - imadw(e, ya, roff, 1u, py); - for (unsigned i = 0; i < N; i++) { - fmul(e, R(yv), x[i], R(rs)); - if (sp->mutant != 1) fmul(e, R(yv), R(yv), S(nq[i / 4], 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) { - const uint32_t I = sp->width ? sp->width : OMEGA_DEC_INTER; - if (I % OMEGA_DEC_THREADS) return -1; - 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 * I, c); - imadi(e, R(ai), R(cy), I, 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 ? I - 1u : I); - 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; -} - -static int gen_gather(Em *e, const OmegaDecSpec *sp) { - const uint32_t N = sp->width, IS = sp->stride; - if (N == 0 || IS == 0) return -1; - int udesc = UV64(e), pin = V64(e), ptab = V64(e), pout = V64(e), tid = V(e), cx = V(e), cy = V(e), n = V(e), lim = V(e); - int ta = V64(e), tv = V(e), idx = V(e), ia = V64(e), val = V(e), o = V(e), oa = V64(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pin, OMEGA_DEC_GA_IN); ldc64(e, ptab, OMEGA_DEC_GA_TAB); ldc64(e, pout, OMEGA_DEC_GA_OUT); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - imadi(e, R(n), R(cx), OMEGA_DEC_THREADS, tid); - movi(e, lim, N); - isetp_ge_u32(e, n, lim); - Region r = region_skip_if_p0(e); - imadw(e, ta, n, 4u, ptab); - ldg(e, BW_IR_LDG_E, tv, ta, 0, udesc, 1); - imadi(e, R(idx), R(cy), IS, tv); - if (sp->mutant == 1) { movi(e, lim, 1); imadi(e, R(idx), R(lim), 1u, idx); } - imadw(e, ia, idx, 4u, pin); - ldg(e, BW_IR_LDG_E, val, ia, 0, udesc, 1); - imadi(e, R(o), R(cy), N, n); - imadw(e, oa, o, 4u, pout); - stg(e, oa, R(val), udesc); - region_end(e, r); - tail(e); - return e->err; -} - -static int gen_gate(Em *e, const OmegaDecSpec *sp) { - int udesc = UV64(e), pa = V64(e), pg = V64(e), pout = V64(e), lim = V(e), tid = V(e), cx = V(e), n = V(e); - int aa = V64(e), ga = V64(e), oa = V64(e), av = V(e), gv = V(e), t = V(e), cst = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pa, OMEGA_DEC_GT_A); ldc64(e, pg, OMEGA_DEC_GT_G); ldc64(e, pout, OMEGA_DEC_GT_OUT); ldc32(e, lim, OMEGA_DEC_GT_N); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); - imadi(e, R(n), R(cx), OMEGA_DEC_THREADS, tid); - isetp_ge_u32(e, n, lim); - Region r = region_skip_if_p0(e); - if (sp->mode & 1u) { /* rows (L369): row ctaid.y; a and out move by width floats a row, g by stride floats */ - int cy = V(e), ro = V(e); if (e->err) return -1; - s2r(e, cy, BW_SR_CTAID_Y); - imadi(e, R(ro), R(cy), sp->width, n); imadw(e, aa, ro, 4u, pa); imadw(e, oa, ro, 4u, pout); - imadi(e, R(ro), R(cy), sp->stride, n); imadw(e, ga, ro, 4u, pg); - } else { imadw(e, aa, n, 4u, pa); imadw(e, ga, n, 4u, pg); imadw(e, oa, n, 4u, pout); } - ldg(e, BW_IR_LDG_E, av, aa, 0, udesc, 1); - ldg(e, BW_IR_LDG_E, gv, ga, 0, udesc, 0); - if (sp->mutant == 1) mov(e, R(t), R(av)); - else { - 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(av), R(t)); - } - stg(e, oa, R(t), udesc); - region_end(e, r); - tail(e); - return e->err; -} - -/* XBOUND mode 1: lo[n] = s[n] * 2^64, n < count (the screen's x' row from the plain hidden: exact, a power of two) */ -static int gen_xscale(Em *e) { - int udesc = UV64(e), ps = V64(e), plo = V64(e), lim = V(e), tid = V(e), cx = V(e), n = V(e), sa = V64(e), la = V64(e), v = V(e), cst = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, ps, OMEGA_DEC_XB_S); ldc64(e, plo, OMEGA_DEC_XB_LO); ldc32(e, lim, OMEGA_DEC_XB_N); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); - imadi(e, R(n), R(cx), OMEGA_DEC_THREADS, tid); - isetp_ge_u32(e, n, lim); - Region r = region_skip_if_p0(e); - imadw(e, sa, n, 4u, ps); imadw(e, la, n, 4u, plo); - ldg(e, BW_IR_LDG_E, v, sa, 0, udesc, 1); - movi(e, cst, 0x5F800000u); /* 2^64 */ - fmul(e, R(v), R(v), R(cst)); - stg(e, la, R(v), udesc); - region_end(e, r); - tail(e); - return e->err; -} - -static int gen_xbound(Em *e, const OmegaDecSpec *sp) { - if (sp->mode > 1 || sp->mutant < 0 || sp->mutant > 1 || (sp->mode == 1 && sp->mutant)) return -1; - if (sp->mode == 1) return gen_xscale(e); - int udesc = UV64(e), ps = V64(e), pc = V64(e), ph = V64(e), plo = V64(e), phi = V64(e), lim = V(e); - int tid = V(e), cx = V(e), warp = V(e), lane = V(e), one = V(e), t = V(e), a0 = V(e), acc = V(e), tot = V(e), r = V(e); - int hn = V(e), cst = V(e), n = V(e), ha = V64(e), sa = V64(e), ca = V64(e), la = V64(e), hia = V64(e); - int sv = V(e), cv = V(e), b = V(e), ab = V(e), lo = V(e), hi = V(e), hq[2]; - if (new_quads(e, hq, 2)) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, ps, OMEGA_DEC_XB_S); ldc64(e, pc, OMEGA_DEC_XB_C); ldc64(e, ph, OMEGA_DEC_XB_H); - ldc64(e, plo, OMEGA_DEC_XB_LO); ldc64(e, phi, OMEGA_DEC_XB_HI); ldc32(e, lim, OMEGA_DEC_XB_N); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); - movi(e, one, 1); - shr(e, warp, tid, 5); - andi(e, R(lane), R(tid), 31u); - /* |h|: 8 values per thread, warp sums, the 8 warp partials in shared memory */ - imadw(e, ha, tid, 32u, ph); - ldg_quads(e, hq, 2, ha, 0, udesc); - movrz(e, R(acc)); - for (unsigned i = 0; i < 8; i++) ffma(e, R(acc), S(hq[i / 4], i % 4), S(hq[i / 4], i % 4), R(acc)); - warp_sum(e, acc, t); - imadi(e, R(a0), R(warp), 4u, NOREG); - lane0_sts(e, lane, one, a0, R(acc)); - bar_sync(e); - cta_reduce8(e, tot, OMEGA_DEC_SM_RED, 0, a0); - movi(e, cst, 0x0D800000u); /* 2^-100: t > 0, so RSQ(t) is finite */ - fadd(e, R(tot), R(tot), R(cst)); - mufu(e, BW_IR_MUFU_RSQ, R(r), R(tot)); - fmul(e, R(hn), R(tot), R(r)); - movi(e, cst, 0x3F802000u); /* 1 + 2^-10 */ - fmul(e, R(hn), R(hn), R(cst)); - /* this thread's row */ - imadi(e, R(n), R(cx), OMEGA_DEC_THREADS, tid); - isetp_ge_u32(e, n, lim); - Region rg = region_skip_if_p0(e); - imadw(e, sa, n, 4u, ps); imadw(e, ca, n, 4u, pc); imadw(e, la, n, 4u, plo); imadw(e, hia, n, 4u, phi); - ldg(e, BW_IR_LDG_E, sv, sa, 0, udesc, 1); - ldg(e, BW_IR_LDG_E, cv, ca, 0, udesc, 0); - if (sp->mutant == 1) movrz(e, R(b)); - else fmul(e, R(b), R(cv), R(hn)); - andi(e, R(ab), R(sv), 0x7fffffffu); - movi(e, cst, 0x35800000u); /* 2^-20 */ - ffma(e, R(b), R(ab), R(cst), R(b)); - movi(e, cst, 0x0D800000u); /* 2^-100 */ - fadd(e, R(b), R(b), R(cst)); - fadd(e, R(hi), R(sv), R(b)); - movi(e, cst, 0x80000000u); - xorr(e, R(b), R(b), R(cst)); - fadd(e, R(lo), R(sv), R(b)); - stg(e, la, R(lo), udesc); - stg(e, hia, R(hi), udesc); - region_end(e, rg); - tail(e); - return e->err; -} - -/* ---- GROUP: the stroke's segment table (L312 v2) ---- */ -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 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); } -/* store v at base64 + off (tmp64 scratch; one = a register holding 1) */ -static void stg_at(Em *e, int tmp64, int one, int base64, uint32_t off, Op v, int udesc) { imadw(e, tmp64, one, off, base64); stg(e, tmp64, v, udesc); } -/* d = 1 iff a < b (unsigned, both < 2^31): (a - b) >> 31 */ -static void lt_u(Em *e, int d, int a, int b) { imadi(e, R(d), R(b), 0xffffffffu, a); shr(e, d, d, 31); } -/* d = both: (a + b) >> 1 for 0/1 flags */ -static void and_flag(Em *e, int d, int a, int b) { imadi(e, R(d), R(a), 1u, b); shr(e, d, d, 1); } - -/* One CTA. Shared: ids [R] u32 at 0, first-of-id flags [R] at 512 (R <= 128). Every thread runs both counting passes with - * the uniform trip count R (no divergence around the barriers); only threads t < R hold a row. Row t = h * S + j. */ -static int gen_group(Em *e, const OmegaDecSpec *sp) { - const uint32_t SL = sp->groups ? sp->groups : OMEGA_DEC_TOPK; /* slots per head */ - if (SL < 1u || SL > 16u || sp->mode || sp->width || sp->stride) return -1; - const uint32_t magic = (65536u + SL - 1u) / SL; /* h = (t * magic) >> 16 = t / SL exactly for t < 256 (the error t * (magic * SL - 65536) / 65536 stays below 1 / SL) */ - if (magic * SL - 65536u >= 256u) return -1; - int udesc = UV64(e), pids = V64(e), ptgu = V64(e), ptdn = V64(e), psgu = V64(e), psdn = V64(e), pxm = V64(e), pym = V64(e); - int stride = V(e), heads = V(e), tid = V(e), Rr = V(e), one = V(e), zero = V(e), c512 = V(e); - int h = V(e), j = V(e), off = V(e), id = V(e), key = V(e), sa = V(e), sa2 = V(e), inr = V(e); - int q = V(e), idq = V(e), keyq = V(e), t1 = V(e), t2 = V(e), eq = V(e), p = V(e), cnt = V(e), nb = V(e), first = V(e), fq = V(e), sidx = V(e), D = V(e), fl = V(e); - int ia = V64(e), oa = V64(e), ta = V64(e), wv = V64(e), sv = V64(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pids, OMEGA_DEC_GR_IDS); ldc64(e, ptgu, OMEGA_DEC_GR_TGU); ldc64(e, ptdn, OMEGA_DEC_GR_TDN); - ldc64(e, psgu, OMEGA_DEC_GR_SGU); ldc64(e, psdn, OMEGA_DEC_GR_SDN); ldc64(e, pxm, OMEGA_DEC_GR_XMAP); ldc64(e, pym, OMEGA_DEC_GR_YMAP); - ldc32(e, stride, OMEGA_DEC_GR_STRIDE); ldc32(e, heads, OMEGA_DEC_GR_HEADS); - s2r(e, tid, BW_SR_TID_X); - movi(e, one, 1); movrz(e, R(zero)); movi(e, c512, 512); - imadi(e, R(Rr), R(heads), SL, NOREG); /* R = N * S rows */ - lt_u(e, inr, tid, Rr); /* 1 iff this thread holds a row */ - imadi(e, R(h), R(tid), magic, NOREG); shr(e, h, h, 16); /* h = t / S */ - imadi(e, R(j), R(h), 0u - SL, tid); /* j = t - h * S */ - movi(e, id, 0xffffffffu); - imadi(e, R(sa), R(tid), 4u, NOREG); - /* pass 0 (t < R): id and key; the id to shared */ - isetp_ge_u32(e, tid, Rr); - Region r0 = region_skip_if_p0(e); - imadr(e, off, h, stride, NOREG); imadi(e, R(off), R(j), 4u, off); - imadw(e, ia, off, 1u, pids); - ldg(e, BW_IR_LDG_E, id, ia, 0, udesc, 1); - sts32(e, sa, R(id)); - region_end(e, r0); - if (sp->mutant == 1) imadi(e, R(key), R(id), 128u, NOREG); else imadi(e, R(key), R(id), 128u, tid); - bar_sync(e); - /* pass 1 (all threads, q over the R rows): p = rows with a smaller key; cnt = rows with this id; nb = of those, rows before t */ - movrz(e, R(p)); movrz(e, R(cnt)); movrz(e, R(nb)); movrz(e, R(q)); movrz(e, R(sa2)); - const int L1 = here(e); - loop_begin(e); - isetp_ge_u32(e, q, Rr); - const int done1 = bra_if_p0_fwd(e); - lds32(e, idq, sa2); - imadi(e, R(keyq), R(idq), 128u, q); - lt_u(e, t1, keyq, key); imadi(e, R(p), R(t1), 1u, p); - lt_u(e, t1, idq, id); lt_u(e, t2, id, idq); - imadi(e, R(eq), R(t1), 0xffffffffu, one); imadi(e, R(eq), R(t2), 0xffffffffu, eq); /* eq = 1 - lt - gt */ - imadi(e, R(cnt), R(eq), 1u, cnt); - lt_u(e, t1, q, tid); and_flag(e, t1, t1, eq); imadi(e, R(nb), R(t1), 1u, nb); - imadi(e, R(q), R(one), 1u, q); imadi(e, R(sa2), R(one), 4u, sa2); - bra(e, L1); - loop_end(e); - patch_bra(e, done1, here(e)); - /* first = (nb == 0) and the thread holds a row */ - imadi(e, R(first), R(one), 0xffffffffu, nb); shr(e, first, first, 31); and_flag(e, first, first, inr); - imadi(e, R(sa), R(tid), 4u, c512); - isetp_ge_u32(e, tid, Rr); - Region r1 = region_skip_if_p0(e); - sts32(e, sa, R(first)); - region_end(e, r1); - bar_sync(e); - /* pass 2 (all threads): sidx = distinct ids below this one; D = distinct ids */ - movrz(e, R(sidx)); movrz(e, R(D)); movrz(e, R(q)); movrz(e, R(sa2)); - const int L2 = here(e); - loop_begin(e); - isetp_ge_u32(e, q, Rr); - const int done2 = bra_if_p0_fwd(e); - lds32(e, idq, sa2); - imadi(e, R(sa), R(one), 512u, sa2); - lds32(e, fq, sa); - imadi(e, R(D), R(fq), 1u, D); - lt_u(e, t1, idq, id); and_flag(e, t1, t1, fq); imadi(e, R(sidx), R(t1), 1u, sidx); - imadi(e, R(q), R(one), 1u, q); imadi(e, R(sa2), R(one), 4u, sa2); - bra(e, L2); - loop_end(e); - patch_bra(e, done2, here(e)); - /* maps (t < R): XMAP[p] = h, YMAP[p] = t */ - isetp_ge_u32(e, tid, Rr); - Region r2 = region_skip_if_p0(e); - imadw(e, oa, p, 4u, pxm); stg(e, oa, R(h), udesc); - imadw(e, oa, p, 4u, pym); stg(e, oa, R(tid), udesc); - region_end(e, r2); - /* segment of a first-of-id row: {w_va, s_va, row0 = p, cnt, 0, 0} from the head's directory entry j */ - if (sp->mutant == 2) imadi(e, R(cnt), R(one), 0xffffffffu, cnt); - isetp_ge_u32(e, zero, first); - Region r3 = region_skip_if_p0(e); - imadr(e, off, h, stride, NOREG); imadi(e, R(off), R(j), 16u, off); - imadw(e, ia, off, 1u, ptgu); - ldg(e, BW_IR_LDG_E_64, wv, ia, 0, udesc, 1); ldg(e, BW_IR_LDG_E_64, sv, ia, 8, udesc, 0); - imadw(e, oa, sidx, OMEGA_DEC_GR_SEG_BYTES, psgu); - stg_at(e, ta, one, oa, 0, S(wv, 0), udesc); stg_at(e, ta, one, oa, 4, S(wv, 1), udesc); - stg_at(e, ta, one, oa, 8, S(sv, 0), udesc); stg_at(e, ta, one, oa, 12, S(sv, 1), udesc); - stg_at(e, ta, one, oa, 16, R(p), udesc); stg_at(e, ta, one, oa, 20, R(cnt), udesc); - stg_at(e, ta, one, oa, 24, R(zero), udesc); stg_at(e, ta, one, oa, 28, R(zero), udesc); - imadw(e, ia, off, 1u, ptdn); - ldg(e, BW_IR_LDG_E_64, wv, ia, 0, udesc, 1); ldg(e, BW_IR_LDG_E_64, sv, ia, 8, udesc, 0); - imadw(e, oa, sidx, OMEGA_DEC_GR_SEG_BYTES, psdn); - stg_at(e, ta, one, oa, 0, S(wv, 0), udesc); stg_at(e, ta, one, oa, 4, S(wv, 1), udesc); - stg_at(e, ta, one, oa, 8, S(sv, 0), udesc); stg_at(e, ta, one, oa, 12, S(sv, 1), udesc); - stg_at(e, ta, one, oa, 16, R(p), udesc); stg_at(e, ta, one, oa, 20, R(cnt), udesc); - stg_at(e, ta, one, oa, 24, R(zero), udesc); stg_at(e, ta, one, oa, 28, R(zero), udesc); - region_end(e, r3); - /* trailing empty segments: D <= t < R write zeros at SEG[t] */ - if (sp->mutant != 3) { - lt_u(e, t1, tid, D); imadi(e, R(t1), R(t1), 0xffffffffu, one); and_flag(e, fl, t1, inr); /* (t >= D) & (t < R) */ - isetp_ge_u32(e, zero, fl); - Region r4 = region_skip_if_p0(e); - imadw(e, oa, tid, OMEGA_DEC_GR_SEG_BYTES, psgu); - for (uint32_t w = 0; w < OMEGA_DEC_GR_SEG_BYTES; w += 4) stg_at(e, ta, one, oa, w, R(zero), udesc); - imadw(e, oa, tid, OMEGA_DEC_GR_SEG_BYTES, psdn); - for (uint32_t w = 0; w < OMEGA_DEC_GR_SEG_BYTES; w += 4) stg_at(e, ta, one, oa, w, R(zero), udesc); - region_end(e, r4); - } - /* map padding: R <= t < R + 8 write zeros */ - imadi(e, R(t2), R(one), OMEGA_DEC_GR_PAD, Rr); - lt_u(e, t1, tid, t2); imadi(e, R(t2), R(inr), 0xffffffffu, one); and_flag(e, fl, t1, t2); /* (t < R + 8) & (t >= R) */ - isetp_ge_u32(e, zero, fl); - Region r5 = region_skip_if_p0(e); - imadw(e, oa, tid, 4u, pxm); stg(e, oa, R(zero), udesc); - imadw(e, oa, tid, 4u, pym); stg(e, oa, R(zero), udesc); - region_end(e, r5); - 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; - case OMEGA_DEC_GATHER: rc = gen_gather(&em, spec); break; - case OMEGA_DEC_GATE: rc = gen_gate(&em, spec); break; - case OMEGA_DEC_GROUP: rc = gen_group(&em, spec); break; - case OMEGA_DEC_XBOUND: rc = gen_xbound(&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 3a1129484..000000000 --- a/src/omega_blackwell_codegen_dec.h +++ /dev/null @@ -1,165 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 residual row (2048 wide by default, spec.width), width / 256 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][I + c] * scale, g = ctaid.y (8 experts, or 1 dense row), c = ctaid.x * 256 - * + tid, I the intermediate size (768 by default, spec.width; grid I / 256 x groups). - * silu(v) = v * RCP(1 + EX2(-v * log2 e)). - * GATHER out[r][n] = in[r * stride + tab[n]] for n < width (spec.width, spec.stride: floats), r = ctaid.y. Qwen3.8-27B - * attention: the fused q|gate|k|v GEMV row to the attention kernel's permuted q|k|v plus the gate (sc #642; - * the permutation crosses the FP8 weights' 128-row scale blocks, so it cannot be folded into the weights). - * GATE out[n] = a[n] * sigmoid(g[n]) for n < count, sigmoid(v) = RCP(1 + EX2(-v * log2 e)): the attention output gate. - * XBOUND (HUM L314 exact two-pass head) every CTA computes t = sum h^2 + 2^-100 over the 2048 plain hidden values and - * hn = t * RSQ(t) * (1 + 2^-10) >= |h| (the widening covers the f32 sum, RSQ and the products); then row r - * (r = ctaid * 256 + tid < count) writes B = c[r] * hn + |s[r]| * 2^-20 + 2^-100, lo = s + (-B), hi = s + B, so - * lo <= s - c|h| and hi >= s + c|h| exactly despite rounding. No FSUB / FSETP (negation by the sign bit). - * Mutant 1 drops the c[r] * hn term (the bound is then far too small: the identity gate must catch it). - * Mode 1 (SCALE): lo[n] = s[n] * 2^64, n < count, grid ceil(count / 256): the FP8 screen's x' row made from the - * plain hidden, exactly h * 2^64, so the screen and the recheck see the same h. - * GROUP (L312 v2, the stroke) one CTA turns the expert picks of N conversations into one grouped-GEMM segment table. - * Row t = h * S + j (head h, slot j; S = spec.groups slots per head, 9 for the 35B) carries expert id - * IDS[h * STRIDE + j * 4]. Rows are sorted by (id, t): sorted row p of row t is its rank. XMAP[p] = h (the x' - * row the gate|up GEMM reads), YMAP[p] = t (its y row, head order). Distinct ids in ascending order get - * segments s = 0, 1, ...: SEG_GU[s] = {TGU[h][j].w_va, .s_va, row0 = rank of its first row, cnt}, SEG_DN[s] - * the same from TDN; segments D..R-1 (D distinct of R = N * S rows) are written as zeros (cnt 0: the GEMM - * CTA leaves); map entries R..R+7 are 0 (the GEMM's padding rows). N * S <= 128, N = HEADS at run time. - * 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, OMEGA_DEC_GATHER = 5, OMEGA_DEC_GATE = 6, OMEGA_DEC_GROUP = 7, OMEGA_DEC_XBOUND = 8 } OmegaDecKind; - -#define OMEGA_DEC_RES_ADD 1u -#define OMEGA_DEC_RES_COMBINE 2u -#define OMEGA_DEC_RES_NORM 4u -#define OMEGA_DEC_RES_ROWS 8u /* row ctaid.y of a [rows][width] block: x, a and y move by width per row, nw does not; with COMBINE - * (L356) a moves by groups * 2048 and the weights by stride bytes per row */ - -#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 -/* GATHER args (out[r][n] = in[r * stride + tab[n]], n < width; grid ceil(width / 256) x rows) */ -#define OMEGA_DEC_GA_IN 0x380u -#define OMEGA_DEC_GA_TAB 0x388u /* u32 [width] source index within an input row */ -#define OMEGA_DEC_GA_OUT 0x390u -#define OMEGA_DEC_GA_WORDS 6u -/* GATE args (out[n] = a[n] * sigmoid(g[n]), n < count; grid ceil(count / 256); out may be a); mode 1 (L369, rows): row ctaid.y, - * a and out at + row * width floats, g at + row * stride floats, count per row; every element the one-row arithmetic */ -#define OMEGA_DEC_GT_A 0x380u -#define OMEGA_DEC_GT_G 0x388u -#define OMEGA_DEC_GT_OUT 0x390u -#define OMEGA_DEC_GT_N 0x398u /* u32 count */ -#define OMEGA_DEC_GT_WORDS 7u -/* XBOUND args (HUM L314 exact head; lo[r] = s[r] - B[r], hi[r] = s[r] + B[r], r < count; grid ceil(count / 256)) */ -#define OMEGA_DEC_XB_S 0x380u /* f32 [count] screen logits */ -#define OMEGA_DEC_XB_C 0x388u /* f32 [count] Row bound coefficients */ -#define OMEGA_DEC_XB_H 0x390u /* f32 [2048] the plain hidden (the recheck x) */ -#define OMEGA_DEC_XB_LO 0x398u -#define OMEGA_DEC_XB_HI 0x3a0u -#define OMEGA_DEC_XB_N 0x3a8u /* u32 count */ -#define OMEGA_DEC_XB_WORDS 11u -/* GROUP args (one CTA of 256 threads; shared: ids at 0, first-of-id flags at 512) */ -#define OMEGA_DEC_GR_IDS 0x380u /* u32 [S] of head 0; head h at + h * STRIDE */ -#define OMEGA_DEC_GR_TGU 0x388u /* {w_va, s_va} [S] of head 0 (gate|up directory entries), head h at + h * STRIDE */ -#define OMEGA_DEC_GR_TDN 0x390u /* the same for down */ -#define OMEGA_DEC_GR_SGU 0x398u /* out: OMEGA_GEMM_SEG_BYTES [R] segment table for gate|up */ -#define OMEGA_DEC_GR_SDN 0x3a0u /* out: [R] for down */ -#define OMEGA_DEC_GR_XMAP 0x3a8u /* out: u32 [R + 8] */ -#define OMEGA_DEC_GR_YMAP 0x3b0u /* out: u32 [R + 8] */ -#define OMEGA_DEC_GR_STRIDE 0x3b8u /* u32 bytes between one head's router buffer and the next */ -#define OMEGA_DEC_GR_HEADS 0x3bcu /* u32 N */ -#define OMEGA_DEC_GR_WORDS 16u -#define OMEGA_DEC_GR_PAD 8u /* map padding entries (the GEMM's largest rows-per-pass) */ -#define OMEGA_DEC_GR_MAX_ROWS 128u -#define OMEGA_DEC_GR_SHARED_BYTES 1024u -#define OMEGA_DEC_GR_SEG_BYTES 32u - -#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). GATHER: the input row stride (floats). RES COMBINE|ROWS: - the routing weights row stride (bytes, a multiple of 16) */ - 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. - GATHER: 1 = source index + 1. GATE: 1 = the gate dropped (out = a). - GROUP: 1 = sort key without the row tie-break; 2 = segment cnt one short; 3 = the trailing - empty segments left unwritten. 0 none */ - uint32_t width; /* RES: the row width (0 = OMEGA_DEC_HIDDEN; a multiple of 1024 up to 8192, COMBINE only at 2048). - SWIGLU: the intermediate size (0 = OMEGA_DEC_INTER; a multiple of 256). Qwen3.8-27B: 5120 and - 17408 (sc #642). The default widths emit the same program as before the field existed. */ - uint32_t groups; /* RES COMBINE: 0 or 8 routed experts, 9 = 8 + the shared expert (Qwen3.6-35B-A3B; the weights and down rows - have 9 entries, slot 8 the shared expert). Mutant 3 (9 only): the shared slot is skipped. - GROUP: slots per head S (0 = 8; 9 for the 35B), 1..16. */ -} 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_gdn.c b/src/omega_blackwell_codegen_gdn.c deleted file mode 100644 index 429c611c4..000000000 --- a/src/omega_blackwell_codegen_gdn.c +++ /dev/null @@ -1,1129 +0,0 @@ -/* - * omega_blackwell_codegen_gdn.c: the one-launch Gated DeltaNet decode step (see the header). Emitter rules follow - * omega_blackwell_codegen_router.c (control words, read barrier on every load) and the held-scoreboard prefetch of - * omega_bw_em.h (the state loads are in flight through the conv, norm and scalar phases). - */ -#include "omega_blackwell_codegen_gdn.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 SB_STATE 3u /* held: the 16 state quads */ -#define SB_GATE 4u /* held: z and the norm weight */ -#define NOREG (-1) - -enum { K_FIXED, K_PRED, K_VAR, K_VAR_MORE, K_UVAR, K_STORE, K_SYNC, K_EXIT, K_BRA, K_BSSY, K_BSYNC }; - -#define MAX_LOOPS 2 - -typedef struct { - BlackwellIRProgram *p; - uint32_t pending, held; - int err; - int depth, open_start[MAX_LOOPS]; - uint32_t placeholders; /* SHFL.BFLY words omega_tc_patch_code must patch */ -} 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); } -/* 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, 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 i2fp(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 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); } -/* A prefetch load: scoreboard `sb` is held, not waited for, until consume() */ -static void ldg_pf(Em *e, int d, int addr64, uint32_t imm, int udesc, unsigned sb) { - BlackwellIRInsn in = I0(BW_IR_LDG_E_128); 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; -} -/* L313: the bf16 state prefetch, LDG.E.64 (four bf16 of one state row) under the held scoreboard `sb` */ -static void ldg_pf64(Em *e, int d, int addr64, uint32_t imm, int udesc, unsigned sb) { - BlackwellIRInsn in = I0(BW_IR_LDG_E_64); 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); } -/* STG.E [addr64 + imm], val (imm: signed 24-bit byte offset) */ -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.src2_vreg = val.v; i.src2_subreg = (uint8_t)val.s; i.imm = imm; i.ureg = udesc; emit(e, i, K_STORE); } -/* L313 bf16 state. F2FP.BF16.F32.PACK_AB d = bf16_rn(hi) << 16 | bf16_rn(lo) (a placeholder omega_tc_patch_code patches, - * omega_blackwell_codegen_tc.h; counted by omega_gdn_bfly_count). */ -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++; -} -/* Four f32 (q, a V128) from four bf16 (w, a V64; element 0 in the low half of word 0): the exact widen. */ -static void bf16x4_widen(Em *e, int q, int w) { - for (unsigned j = 0; j < 4; j++) { - if (j % 2 == 0) imadi(e, S(q, j), S(w, j / 2), 65536u, NOREG); - else andi(e, S(q, j), S(w, j / 2), 0xffff0000u); - } -} -/* Four f32 (q) to four bf16 (w), round to nearest even. */ -static void bf16x4_pack(Em *e, int w, int q) { - f2fp(e, S(w, 0), S(q, 1), S(q, 0)); - f2fp(e, S(w, 1), S(q, 3), S(q, 2)); -} -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 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_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_fwd(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = 1; emit(e, i, K_BRA); return at; } -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; -} - -/* 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); } -/* 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; omega_blackwell_codegen_pattn.c). */ -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 void mov(Em *e, Op d, Op a) { imadi(e, d, a, 1u, NOREG); } -/* 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++; } -/* butterfly sum over lane strides lo, 2 lo .. hi: every lane of a group ends with the same bits (a + b == b + a) */ -static void bfly_sum(Em *e, int v, int t, uint32_t lo, uint32_t hi) { for (uint32_t o = lo; o <= hi; o *= 2) { shfl_bfly(e, t, v, o); fadd(e, R(v), R(v), R(t)); } } -/* warp sum: 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)); } } -/* lane 0 of every warp stores v to shared [addr] */ -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); -} -/* x = x * sigmoid(x) = x * RCP(1 + EX2(-x * log2 e)); t scratch */ -static void silu(Em *e, Op x, int t, int nlog2e, int fone) { - fmul(e, R(t), x, R(nlog2e)); mufu(e, BW_IR_MUFU_EX2, R(t), R(t)); fadd(e, R(t), R(t), R(fone)); - mufu(e, BW_IR_MUFU_RCP, R(t), R(t)); fmul(e, x, x, R(t)); -} -static uint32_t fbits(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -/* The 8-way cross-warp sum of acc[0..3] (columns 4L..4L+3 of each warp) through shared SM_P: pa = this thread's - * partial slot, la = lane * 16. Every warp ends with the same totals, summed in warp order 0..7. */ -static void cross_warp_sum(Em *e, int acc[4], int pa, int one, int la) { - int pj = V(e), b0 = V128(e), b1 = V128(e); - if (e->err) return; - sts32(e, pa, R(acc[0])); - for (unsigned j = 1; j < 4; j++) { imadi(e, R(pj), R(one), 4u * j, pa); sts32(e, pj, R(acc[j])); } - bar_sync(e); - for (unsigned w2 = 0; w2 < 8; w2 += 2) { - lds128(e, b0, la, OMEGA_GDN_SM_P + w2 * OMEGA_GDN_HEAD_DIM * 4u, 1); - lds128(e, b1, la, OMEGA_GDN_SM_P + (w2 + 1) * OMEGA_GDN_HEAD_DIM * 4u, 0); - for (unsigned j = 0; j < 4; j++) { - if (w2 == 0) fadd(e, R(acc[j]), S(b0, j), S(b1, j)); - else { fadd(e, R(acc[j]), R(acc[j]), S(b0, j)); fadd(e, R(acc[j]), R(acc[j]), S(b1, j)); } - } - } -} - -int omega_gdn_shape(const OmegaGdnSpec *spec, OmegaGdnShape *s) { - uint32_t r = spec->ratio ? spec->ratio : 3u; - if (r < 1u || r > 3u) return -1; - s->r = r; - s->vh = OMEGA_GDN_KEY_HEADS * r; - s->vdim = s->vh * OMEGA_GDN_HEAD_DIM; - s->conv = 2u * OMEGA_GDN_KEY_HEADS * OMEGA_GDN_HEAD_DIM + s->vdim; - s->par_scal = s->conv * OMEGA_GDN_TAPS * 4u; - s->par_norm = s->par_scal + s->vh * 8u; - s->par_bytes = s->par_norm + OMEGA_GDN_HEAD_DIM * 4u; - s->tail_bytes = s->vh * OMEGA_GDN_TAIL_HEAD_BYTES; - s->state_bytes = spec->state_bf16 ? s->vh * (OMEGA_GDN_STATE_HEAD_BYTES / 2u) : s->vh * OMEGA_GDN_STATE_HEAD_BYTES; - s->post_grid_y = s->vh / 8u; - return 0; -} - -int omega_blackwell_codegen_gdn_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog || spec->copy || spec->mutant < 0 || spec->mutant > 4) return -1; - OmegaGdnShape G; - if (omega_gdn_shape(spec, &G)) return -1; - const uint32_t RR = G.r, NC = 2u + G.r; - (void)RR; (void)NC; - const int MUT = spec->mutant; - const uint32_t C_LOG2E = fbits(1.44269504f), C_NLOG2E = fbits(-1.44269504f), C_LN2 = fbits(0.693147181f); - const uint32_t C_ONE = fbits(1.0f), C_M1 = fbits(-1.0f), C_INV128 = fbits(1.0f / 128.0f); - const float qs = 0.0883883476f; /* 1 / sqrt(128) */ - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - - /* ---- identities; the state address ---- */ - int udesc = UV64(e); - int tid = V(e), cx = V(e), cy = V(e), h = V(e), warp = V(e), lane = V(e), one = V(e); - int ps = V64(e), sa = V64(e), toff = V(e), sq[16]; - for (unsigned r = 0; r < 16; r++) sq[r] = V128(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, ps, OMEGA_GDN_ARG_STATE); - 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); - imadi(e, R(h), R(cy), RR, cx); - shr(e, warp, tid, 5); - andi(e, R(lane), R(tid), 31u); - /* the state element size: 4 (f32) or 2 (bf16, L313); this thread holds rows 16 warp .. +15, columns 4 lane .. +3 */ - const unsigned sel = spec->state_bf16 ? 2u : 4u; - imadi(e, R(toff), R(h), OMEGA_GDN_HEAD_DIM * OMEGA_GDN_HEAD_DIM * sel, NOREG); - imadi(e, R(toff), R(warp), 16u * OMEGA_GDN_HEAD_DIM * sel, toff); - imadi(e, R(toff), R(lane), 4u * sel, toff); - imadw(e, sa, toff, 1u, ps); - - /* ---- phase A: conv + SiLU of channel A (q or k) and channel V ---- */ - int half = V(e), c = V(e), gi = V(e), slv = V(e); - int pqkv = V64(e), ppar = V64(e), ptail = V64(e); - int axA = V64(e), awA = V64(e), atA = V64(e), axV = V64(e), awV = V64(e), atV = V64(e); - int xA = V(e), xV = V(e), wA = V128(e), wV = V128(e), tA = V128(e), tV = V128(e); - int insc = V(e), accA = V(e), accV = V(e), t1 = V(e), cnl2e = V(e), fone = V(e); - if (e->err) return -1; - ldc64(e, pqkv, OMEGA_GDN_ARG_QKV); ldc64(e, ppar, OMEGA_GDN_ARG_PAR); ldc64(e, ptail, OMEGA_GDN_ARG_TAIL); - ldc32(e, insc, OMEGA_GDN_ARG_IN_SCALE); - shr(e, half, tid, 7); - andi(e, R(c), R(tid), 127u); - imadi(e, R(gi), R(cy), OMEGA_GDN_HEAD_DIM, tid); /* q channel hk*128 + t; k channel 2048 + hk*128 + (t - 128) */ - imadi(e, R(gi), R(half), 2048u - 128u, gi); - imadw(e, axA, gi, 4u, pqkv); imadw(e, awA, gi, 16u, ppar); - imadi(e, R(gi), R(h), OMEGA_GDN_HEAD_DIM, c); /* v channel 4096 + h*128 + c */ - imadi(e, R(gi), R(one), 2u * OMEGA_GDN_KEY_HEADS * OMEGA_GDN_HEAD_DIM, gi); - imadw(e, axV, gi, 4u, pqkv); imadw(e, awV, gi, 16u, ppar); - imadw(e, atA, tid, 16u, ptail); imadw(e, atA, h, OMEGA_GDN_TAIL_HEAD_BYTES, atA); - imadi(e, R(slv), R(one), 256u, c); - imadw(e, atV, slv, 16u, ptail); imadw(e, atV, h, OMEGA_GDN_TAIL_HEAD_BYTES, atV); - ldg32(e, xA, axA, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, wA, awA, 0, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, tA, atA, 0, udesc, 0); - ldg32(e, xV, axV, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, wV, awV, 0, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, tV, atV, 0, udesc, 0); - fmul(e, R(xA), R(xA), R(insc)); fmul(e, R(xV), R(xV), R(insc)); - fmul(e, R(accA), S(wA, 0), S(tA, 0)); ffma(e, R(accA), S(wA, 1), S(tA, 1), R(accA)); - ffma(e, R(accA), S(wA, 2), S(tA, 2), R(accA)); ffma(e, R(accA), S(wA, 3), R(xA), R(accA)); - fmul(e, R(accV), S(wV, 0), S(tV, 0)); ffma(e, R(accV), S(wV, 1), S(tV, 1), R(accV)); - ffma(e, R(accV), S(wV, 2), S(tV, 2), R(accV)); ffma(e, R(accV), S(wV, 3), R(xV), R(accV)); - movi(e, cnl2e, C_NLOG2E); movi(e, fone, C_ONE); - silu(e, R(accA), t1, cnl2e, fone); - silu(e, R(accV), t1, cnl2e, fone); - /* the state prefetch (here, not earlier: the conv phase is the register peak) */ - int sw[16]; - if (spec->state_bf16) { - for (unsigned r = 0; r < 16; r++) sw[r] = V64(e); - if (e->err) return -1; - for (unsigned r = 0; r < 16; r++) ldg_pf64(e, sw[r], sa, r * OMEGA_GDN_HEAD_DIM * 2u, udesc, SB_STATE); - } else { - for (unsigned r = 0; r < 16; r++) ldg_pf(e, sq[r], sa, r * OMEGA_GDN_HEAD_DIM * 4u, udesc, SB_STATE); - } - - /* ---- phase B: l2 norms; q|k and v to shared; the tail shift ---- */ - int sqs = V(e), ts = V(e), ra = V(e); - if (e->err) return -1; - fmul(e, R(sqs), R(accA), R(accA)); - warp_sum(e, sqs, ts); - imadi(e, R(ra), R(warp), 4u, NOREG); imadi(e, R(ra), R(one), OMEGA_GDN_SM_RED, ra); - lane0_sts(e, lane, one, ra, R(sqs)); - imadi(e, R(ra), R(c), 4u, NOREG); imadi(e, R(ra), R(one), OMEGA_GDN_SM_V, ra); - sts32(e, ra, R(accV)); - bar_sync(e); - if (MUT != 4) { - stg(e, atA, 0, S(tA, 1), udesc); stg(e, atA, 4, S(tA, 2), udesc); stg(e, atA, 8, R(xA), udesc); - stg(e, atV, 0, S(tV, 1), udesc); stg(e, atV, 4, S(tV, 2), udesc); stg(e, atV, 8, R(xV), udesc); - } - { - int rq = V128(e), el2 = V(e), hf = V(e), fq = V(e); - if (e->err) return -1; - ldc32(e, el2, OMEGA_GDN_ARG_EPS_L2); - imadi(e, R(ra), R(half), 16u, NOREG); - lds128(e, rq, ra, OMEGA_GDN_SM_RED, 1); - fadd(e, R(sqs), S(rq, 0), S(rq, 1)); fadd(e, R(sqs), R(sqs), S(rq, 2)); fadd(e, R(sqs), R(sqs), S(rq, 3)); - fadd(e, R(sqs), R(sqs), R(el2)); - mufu(e, BW_IR_MUFU_RSQ, R(sqs), R(sqs)); - /* q gets 1/sqrt(128) more: factor = qs + half * (1 - qs) */ - i2fp(e, hf, half); - movi(e, fq, fbits(qs)); movi(e, t1, fbits(1.0f - qs)); - ffma(e, R(fq), R(hf), R(t1), R(fq)); - fmul(e, R(accA), R(accA), R(sqs)); fmul(e, R(accA), R(accA), R(fq)); - imadi(e, R(ra), R(tid), 4u, NOREG); /* SM_Q = 0, SM_K = SM_Q + 512 */ - sts32(e, ra, R(accA)); - bar_sync(e); /* q and k are read across warps in phase D (a zero state hides a missing barrier here: 0 * poison = 0) */ - } - - /* ---- phase C: scalars ---- */ - int pab = V64(e), aab = V64(e), asc = V64(e), abq = V64(e), scq = V64(e); - int xs = V(e), mn = V(e), sp = V(e), dec = V(e), beta = V(e), cl2e = V(e); - if (e->err) return -1; - ldc64(e, pab, OMEGA_GDN_ARG_AB); - imadw(e, aab, h, 8u, pab); imadw(e, asc, h, 8u, ppar); - ldg_wide(e, BW_IR_LDG_E_64, abq, aab, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_64, scq, asc, G.par_scal, udesc, 0); - /* softplus(x) = max(x, 0) + ln2 * LG2(1 + EX2(-|x| * log2 e)), x = a + dt_bias */ - fadd(e, R(xs), S(abq, 0), S(scq, 1)); - movi(e, mn, C_M1); fmul(e, R(mn), R(xs), R(mn)); fminn(e, R(mn), R(xs), R(mn)); - movi(e, cl2e, C_LOG2E); - fmul(e, R(mn), R(mn), R(cl2e)); mufu(e, BW_IR_MUFU_EX2, R(mn), R(mn)); fadd(e, R(mn), R(mn), R(fone)); - mufu(e, BW_IR_MUFU_LG2, R(mn), R(mn)); - movrz(e, R(sp)); fmaxx(e, R(sp), R(xs), R(sp)); - movi(e, t1, C_LN2); ffma(e, R(sp), R(mn), R(t1), R(sp)); - /* decay = EX2(negA * softplus * log2 e) */ - if (MUT == 1) movi(e, dec, C_ONE); - else { fmul(e, R(dec), S(scq, 0), R(sp)); fmul(e, R(dec), R(dec), R(cl2e)); mufu(e, BW_IR_MUFU_EX2, R(dec), R(dec)); } - /* beta = sigmoid(b) */ - if (MUT == 2) movi(e, beta, C_ONE); - else { - fmul(e, R(beta), S(abq, 1), R(cnl2e)); mufu(e, BW_IR_MUFU_EX2, R(beta), R(beta)); - fadd(e, R(beta), R(beta), R(fone)); mufu(e, BW_IR_MUFU_RCP, R(beta), R(beta)); - } - - /* ---- phase D: the state update (fresh registers per step: a reused name stays live across all its uses) ---- */ - int aw = V(e), pa = V(e), la = V(e), kq[4], kv[4], dl[4], vq = V128(e); - for (unsigned i = 0; i < 4; i++) { kq[i] = V128(e); kv[i] = V(e); dl[i] = V(e); } - if (e->err) return -1; - imadi(e, R(aw), R(warp), 16u * 4u, NOREG); - imadi(e, R(pa), R(warp), OMEGA_GDN_HEAD_DIM * 4u, NOREG); imadi(e, R(pa), R(lane), 16u, pa); imadi(e, R(pa), R(one), OMEGA_GDN_SM_P, pa); - imadi(e, R(la), R(lane), 16u, NOREG); - consume(e, SB_STATE); - if (spec->state_bf16) for (unsigned r = 0; r < 16; r++) bf16x4_widen(e, sq[r], sw[r]); - for (unsigned r = 0; r < 16; r++) for (unsigned j = 0; j < 4; j++) fmul(e, S(sq[r], j), S(sq[r], j), R(dec)); - /* kv partial over this warp's 16 rows: kv_j = sum_r S[r][j] k[r], then the 8-way cross-warp sum */ - for (unsigned i = 0; i < 4; i++) lds128(e, kq[i], aw, OMEGA_GDN_SM_K + i * 16u, i == 0); - for (unsigned j = 0; j < 4; j++) fmul(e, R(kv[j]), S(sq[0], j), S(kq[0], 0)); - for (unsigned r = 1; r < 16; r++) for (unsigned j = 0; j < 4; j++) ffma(e, R(kv[j]), S(sq[r], j), S(kq[r / 4], r % 4), R(kv[j])); - cross_warp_sum(e, kv, pa, one, la); - /* delta = (v - kv) * beta; S += k (outer) delta; S back to memory */ - lds128(e, vq, la, OMEGA_GDN_SM_V, 1); - for (unsigned j = 0; j < 4; j++) { fsub(e, R(dl[j]), S(vq, j), R(kv[j])); fmul(e, R(dl[j]), R(dl[j]), R(beta)); } - { - int k2[4]; - for (unsigned i = 0; i < 4; i++) k2[i] = V128(e); - if (e->err) return -1; - for (unsigned i = 0; i < 4; i++) lds128(e, k2[i], aw, OMEGA_GDN_SM_K + i * 16u, i == 0); - for (unsigned r = 0; r < 16; r++) for (unsigned j = 0; j < 4; j++) ffma(e, S(sq[r], j), S(k2[r / 4], r % 4), R(dl[j]), S(sq[r], j)); - } - if (spec->state_bf16) { - int pk[16]; - for (unsigned r = 0; r < 16; r++) pk[r] = V64(e); - if (e->err) return -1; - for (unsigned r = 0; r < 16; r++) { - bf16x4_pack(e, pk[r], sq[r]); - for (unsigned w = 0; w < 2; w++) stg(e, sa, r * OMEGA_GDN_HEAD_DIM * 2u + w * 4u, S(pk[r], w), udesc); - } - } else { - for (unsigned r = 0; r < 16; r++) for (unsigned j = 0; j < 4; j++) stg(e, sa, r * OMEGA_GDN_HEAD_DIM * 4u + j * 4u, S(sq[r], j), udesc); - } - /* the gate prefetch: z[h] and the norm weight, consumed in phase E */ - int pz = V64(e), ppar2 = V64(e), az = V64(e), an = V64(e), zq = V128(e), nq = V128(e); - if (e->err) return -1; - ldc64(e, pz, OMEGA_GDN_ARG_Z); ldc64(e, ppar2, OMEGA_GDN_ARG_PAR); - imadw(e, az, lane, 16u, pz); imadw(e, az, h, OMEGA_GDN_HEAD_DIM * 4u, az); - imadw(e, an, lane, 16u, ppar2); - ldg_pf(e, zq, az, 0, udesc, SB_GATE); - ldg_pf(e, nq, an, G.par_norm, udesc, SB_GATE); - /* o partial: o_j = sum_r S[r][j] q[r], then the cross-warp sum */ - int p[4]; - { - int q2[4]; - for (unsigned i = 0; i < 4; i++) { q2[i] = V128(e); p[i] = V(e); } - if (e->err) return -1; - for (unsigned i = 0; i < 4; i++) lds128(e, q2[i], aw, OMEGA_GDN_SM_Q + i * 16u, i == 0); - for (unsigned j = 0; j < 4; j++) fmul(e, R(p[j]), S(sq[0], j), S(q2[0], 0)); - for (unsigned r = 1; r < 16; r++) for (unsigned j = 0; j < 4; j++) ffma(e, R(p[j]), S(sq[r], j), S(q2[r / 4], r % 4), R(p[j])); - } - bar_sync(e); /* every warp has read the kv partials */ - cross_warp_sum(e, p, pa, one, la); - - /* ---- phase E: gated RMSNorm, the output ---- */ - int ss = V(e), en = V(e), osc = V(e), pout = V64(e), ao = V64(e), g = V(e); - if (e->err) return -1; - fmul(e, R(ss), R(p[0]), R(p[0])); - for (unsigned j = 1; j < 4; j++) ffma(e, R(ss), R(p[j]), R(p[j]), R(ss)); - warp_sum(e, ss, ts); - imadi(e, R(ra), R(warp), 4u, NOREG); imadi(e, R(ra), R(one), OMEGA_GDN_SM_RED2, ra); - lane0_sts(e, lane, one, ra, R(ss)); - bar_sync(e); - ldc32(e, en, OMEGA_GDN_ARG_EPS_NORM); ldc32(e, osc, OMEGA_GDN_ARG_OUT_SCALE); ldc64(e, pout, OMEGA_GDN_ARG_OUT); - lds32(e, R(ss), ra, 0); - movi(e, t1, C_INV128); - ffma(e, R(ss), R(ss), R(t1), R(en)); - mufu(e, BW_IR_MUFU_RSQ, R(ss), R(ss)); - imadw(e, ao, lane, 16u, pout); imadw(e, ao, h, OMEGA_GDN_HEAD_DIM * 4u, ao); - consume(e, SB_GATE); - for (unsigned j = 0; j < 4; j++) { - fmul(e, R(g), S(zq, j), R(insc)); - if (MUT != 3) silu(e, R(g), t1, cnl2e, fone); - fmul(e, R(p[j]), R(p[j]), R(ss)); fmul(e, R(p[j]), R(p[j]), S(nq, j)); - fmul(e, R(p[j]), R(p[j]), R(g)); fmul(e, R(p[j]), R(p[j]), R(osc)); - } - for (unsigned j = 0; j < 4; j++) stg(e, ao, j * 4u, R(p[j]), udesc); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_gdn_prog_stats(const OmegaGdnSpec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_gdn_prog(spec, &prog) != 0) return -1; - if (insns) *insns = (uint32_t)prog.count; - if (gprs) *gprs = prog.regalloc.peak_gpr_usage; - return 0; -} - -/* ======== state copy / zero (see the header) ======== */ -int omega_blackwell_codegen_gdn_copy_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog || spec->mutant || (spec->copy != OMEGA_GDN_COPY && spec->copy != OMEGA_GDN_ZERO)) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - int udesc = UV64(e), tid = V(e), cx = V(e), w = V(e), pd = V64(e), ad = V64(e), v[4]; - for (unsigned j = 0; j < 4; j++) v[j] = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pd, OMEGA_GDN_COPY_ARG_DST); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); - imadi(e, R(w), R(cx), OMEGA_GDN_COPY_WORDS_PER_CTA, tid); - imadw(e, ad, w, 4u, pd); - if (spec->copy == OMEGA_GDN_COPY) { - /* the 32-bit LDG.E carries no immediate: one address per word */ - int ps = V64(e), one = V(e), wj[4], as[4]; - for (unsigned j = 0; j < 4; j++) { wj[j] = V(e); as[j] = V64(e); } - if (e->err) return -1; - ldc64(e, ps, OMEGA_GDN_COPY_ARG_SRC); - movi(e, one, 1); - for (unsigned j = 0; j < 4; j++) { imadi(e, R(wj[j]), R(one), j * OMEGA_GDN_COPY_THREADS, w); imadw(e, as[j], wj[j], 4u, ps); } - for (unsigned j = 0; j < 4; j++) ldg_wide(e, BW_IR_LDG_E, v[j], as[j], 0, udesc, j == 0); - } else { - for (unsigned j = 0; j < 4; j++) movrz(e, R(v[j])); - } - for (unsigned j = 0; j < 4; j++) stg(e, ad, j * OMEGA_GDN_COPY_THREADS * 4u, R(v[j]), udesc); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -/* ======== prefill (omega#543): prep, scan, post (layouts in the header) ======== */ - -/* softplus, decay and beta of one value head (the decode phase C maths): abq = {a, b}, scq = {negA, dt_bias} */ -static void gdn_scalars(Em *e, int MUT, int abq, int scq, int dec, int beta, int t1, int cnl2e, int fone) { - int xs = V(e), mn = V(e), sp = V(e), cl2e = V(e); - if (e->err) return; - fadd(e, R(xs), S(abq, 0), S(scq, 1)); - movi(e, mn, fbits(-1.0f)); fmul(e, R(mn), R(xs), R(mn)); fminn(e, R(mn), R(xs), R(mn)); - movi(e, cl2e, fbits(1.44269504f)); - fmul(e, R(mn), R(mn), R(cl2e)); mufu(e, BW_IR_MUFU_EX2, R(mn), R(mn)); fadd(e, R(mn), R(mn), R(fone)); - mufu(e, BW_IR_MUFU_LG2, R(mn), R(mn)); - movrz(e, R(sp)); fmaxx(e, R(sp), R(xs), R(sp)); - movi(e, t1, fbits(0.693147181f)); ffma(e, R(sp), R(mn), R(t1), R(sp)); - if (MUT == 1) movi(e, dec, fbits(1.0f)); - else { fmul(e, R(dec), S(scq, 0), R(sp)); fmul(e, R(dec), R(dec), R(cl2e)); mufu(e, BW_IR_MUFU_EX2, R(dec), R(dec)); } - if (MUT == 2) movi(e, beta, fbits(1.0f)); - else { - fmul(e, R(beta), S(abq, 1), R(cnl2e)); mufu(e, BW_IR_MUFU_EX2, R(beta), R(beta)); - fadd(e, R(beta), R(beta), R(fone)); mufu(e, BW_IR_MUFU_RCP, R(beta), R(beta)); - } -} - -int omega_blackwell_codegen_gdn_prep_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog || spec->copy || spec->mutant < 0 || spec->mutant > 4) return -1; - OmegaGdnShape G; - if (omega_gdn_shape(spec, &G)) return -1; - const uint32_t RR = G.r, NC = 2u + G.r; - (void)RR; (void)NC; - const int MUT = spec->mutant; - const float qs = 0.0883883476f; /* 1 / sqrt(128) */ - const uint32_t ROW = G.conv * 4u, REC_ROW = G.vh * OMEGA_GDN_REC_BYTES; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - - int udesc = UV64(e); - int c = V(e), cx = V(e), hk = V(e), warp = V(e), lane = V(e), one = V(e), T = V(e), t0 = V(e), n = V(e), t1 = V(e); - int pqkv = V64(e), ppar = V64(e), ptail = V64(e), prec = V64(e), pab = V64(e), insc = V(e); - int ch[5], tw[5], wq[5], ax[5]; - for (unsigned i = 0; i < NC; i++) { ch[i] = V(e); tw[i] = V128(e); wq[i] = V128(e); ax[i] = V64(e); } - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - s2r(e, c, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, hk, BW_SR_CTAID_Y); - ldc64(e, pqkv, OMEGA_GDN_PREP_ARG_QKV); ldc64(e, ppar, OMEGA_GDN_PREP_ARG_PAR); ldc64(e, ptail, OMEGA_GDN_PREP_ARG_TAIL); - ldc64(e, prec, OMEGA_GDN_PREP_ARG_REC); ldc64(e, pab, OMEGA_GDN_PREP_ARG_AB); - ldc32(e, T, OMEGA_GDN_PREP_ARG_T); ldc32(e, insc, OMEGA_GDN_PREP_ARG_IN_SCALE); - movi(e, one, 1); - shr(e, warp, c, 5); - andi(e, R(lane), R(c), 31u); - imadi(e, R(t0), R(cx), OMEGA_GDN_PREP_TOKENS, NOREG); - /* n = min(16, T - t0) >= 1 */ - imadi(e, R(n), R(t0), 0xffffffffu, T); - movi(e, t1, OMEGA_GDN_PREP_TOKENS); - isetp_ge_u32(e, t1, n); - { int b = bra_if_p0_fwd(e); movi(e, n, OMEGA_GDN_PREP_TOKENS); patch_bra(e, b, here(e)); } - /* channels: q hk*128 + c, k 2048 + hk*128 + c, v_i 4096 + (3 hk + i)*128 + c */ - imadi(e, R(ch[0]), R(hk), OMEGA_GDN_HEAD_DIM, c); - imadi(e, R(ch[1]), R(one), 2048u, ch[0]); - imadi(e, R(ch[2]), R(hk), RR * OMEGA_GDN_HEAD_DIM, c); imadi(e, R(ch[2]), R(one), 4096u, ch[2]); - for (unsigned i = 3; i < NC; i++) imadi(e, R(ch[i]), R(one), (i - 2u) * OMEGA_GDN_HEAD_DIM, ch[2]); - /* taps */ - { - int aq = V64(e), av = V64(e); - if (e->err) return -1; - imadw(e, aq, ch[0], 16u, ppar); imadw(e, av, ch[2], 16u, ppar); - ldg_wide(e, BW_IR_LDG_E_128, tw[0], aq, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, tw[1], aq, 2048u * 16u, udesc, 0); - for (unsigned i = 0; i < RR; i++) ldg_wide(e, BW_IR_LDG_E_128, tw[2 + i], av, i * OMEGA_GDN_HEAD_DIM * 16u, udesc, 0); - } - /* the window {x_{t0-3}, x_{t0-2}, x_{t0-1}}: CTA 0 from the tail, the others from the rows before t0 (uniform) */ - isetp_ge_u32(e, cx, one); - const int b_rows = bra_if_p0_fwd(e); - { - int at = V64(e); - if (e->err) return -1; - imadi(e, R(t1), R(hk), RR * OMEGA_GDN_TAIL_HEAD_BYTES, NOREG); - imadw(e, at, t1, 1u, ptail); imadw(e, at, c, 16u, at); - ldg_wide(e, BW_IR_LDG_E_128, wq[0], at, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, wq[1], at, OMEGA_GDN_HEAD_DIM * 16u, udesc, 0); - for (unsigned i = 0; i < RR; i++) ldg_wide(e, BW_IR_LDG_E_128, wq[2 + i], at, i * OMEGA_GDN_TAIL_HEAD_BYTES + 256u * 16u, udesc, 0); - } - const int b_join = bra_fwd(e); - patch_bra(e, b_rows, here(e)); - { - int base = V64(e), a[5][3]; - for (unsigned i = 0; i < NC; i++) for (unsigned r = 0; r < 3; r++) a[i][r] = V64(e); - if (e->err) return -1; - imadi(e, R(t1), R(one), 0xfffffffdu, t0); /* t0 - 3 (t0 >= 16 here) */ - imadw(e, base, t1, ROW, pqkv); - for (unsigned i = 0; i < NC; i++) { - imadw(e, a[i][0], ch[i], 4u, base); - imadw(e, a[i][1], one, ROW, a[i][0]); imadw(e, a[i][2], one, ROW, a[i][1]); - } - for (unsigned i = 0; i < NC; i++) for (unsigned r = 0; r < 3; r++) { - BlackwellIRInsn in = I0(BW_IR_LDG_E); in.dst_vreg = wq[i]; in.dst_subreg = (uint8_t)r; in.src1_vreg = a[i][r]; in.ureg = udesc; - emit(e, in, (i == 0 && r == 0) ? K_VAR : K_VAR_MORE); - } - for (unsigned i = 0; i < NC; i++) for (unsigned r = 0; r < 3; r++) fmul(e, S(wq[i], r), S(wq[i], r), R(insc)); - } - patch_bra(e, b_join, here(e)); - - /* per-thread addresses at token t0 */ - int idx = V(e), arec = V64(e), asc = V64(e), aab = V64(e), scq = V64(e); - int cnl2e = V(e), fone = V(e), el2 = V(e), cqs = V(e), c3 = V(e), zero = V(e), raq = V(e), rak = V(e); - if (e->err) return -1; - { - int base = V64(e); - if (e->err) return -1; - imadw(e, base, t0, ROW, pqkv); - for (unsigned i = 0; i < NC; i++) imadw(e, ax[i], ch[i], 4u, base); - } - imadi(e, R(idx), R(t0), G.vh, NOREG); imadi(e, R(idx), R(hk), RR, idx); - imadw(e, arec, idx, OMEGA_GDN_REC_BYTES, prec); imadw(e, arec, c, 4u, arec); - imadi(e, R(t1), R(c), 1u, idx); /* the scalar threads' head index t0*48 + 3hk + c */ - imadw(e, asc, t1, OMEGA_GDN_REC_BYTES, prec); - imadw(e, aab, t1, 8u, pab); - movi(e, c3, RR); - isetp_ge_u32(e, c, c3); - { - Region r = region_skip_if_p0(e); - int as = V64(e); - if (e->err) return -1; - imadi(e, R(t1), R(hk), RR, c); - imadw(e, as, t1, 8u, ppar); - ldg_wide(e, BW_IR_LDG_E_64, scq, as, G.par_scal, udesc, 1); - region_end(e, r); - } - movi(e, cnl2e, fbits(-1.44269504f)); movi(e, fone, fbits(1.0f)); movi(e, cqs, fbits(qs)); - ldc32(e, el2, OMEGA_GDN_PREP_ARG_EPS_L2); - movi(e, zero, 0u); - imadi(e, R(raq), R(warp), 4u, NOREG); imadi(e, R(rak), R(one), 16u, raq); - - const int L = here(e); - loop_begin(e); - { - int x[5], acc[5], sq = V(e), sk = V(e), ts = V(e), rq = V128(e), rk = V128(e), nq = V(e), nk = V(e); - for (unsigned i = 0; i < NC; i++) { x[i] = V(e); acc[i] = V(e); } - if (e->err) return -1; - for (unsigned i = 0; i < NC; i++) ldg32(e, x[i], ax[i], udesc, i == 0); - for (unsigned i = 0; i < NC; i++) { - fmul(e, R(x[i]), R(x[i]), R(insc)); - fmul(e, R(acc[i]), S(tw[i], 0), S(wq[i], 0)); ffma(e, R(acc[i]), S(tw[i], 1), S(wq[i], 1), R(acc[i])); - ffma(e, R(acc[i]), S(tw[i], 2), S(wq[i], 2), R(acc[i])); ffma(e, R(acc[i]), S(tw[i], 3), R(x[i]), R(acc[i])); - silu(e, R(acc[i]), t1, cnl2e, fone); - mov(e, S(wq[i], 0), S(wq[i], 1)); mov(e, S(wq[i], 1), S(wq[i], 2)); mov(e, S(wq[i], 2), R(x[i])); - } - /* l2 norms of q and k across the 4 warps (the decode order: warp sums, then partials 0 + 1 + 2 + 3) */ - fmul(e, R(sq), R(acc[0]), R(acc[0])); warp_sum(e, sq, ts); lane0_sts(e, lane, one, raq, R(sq)); - fmul(e, R(sk), R(acc[1]), R(acc[1])); warp_sum(e, sk, ts); lane0_sts(e, lane, one, rak, R(sk)); - bar_sync(e); - lds128(e, rq, zero, 0, 1); lds128(e, rk, zero, 16, 0); - fadd(e, R(nq), S(rq, 0), S(rq, 1)); fadd(e, R(nq), R(nq), S(rq, 2)); fadd(e, R(nq), R(nq), S(rq, 3)); fadd(e, R(nq), R(nq), R(el2)); - fadd(e, R(nk), S(rk, 0), S(rk, 1)); fadd(e, R(nk), R(nk), S(rk, 2)); fadd(e, R(nk), R(nk), S(rk, 3)); fadd(e, R(nk), R(nk), R(el2)); - mufu(e, BW_IR_MUFU_RSQ, R(nq), R(nq)); mufu(e, BW_IR_MUFU_RSQ, R(nk), R(nk)); - fmul(e, R(acc[0]), R(acc[0]), R(nq)); fmul(e, R(acc[0]), R(acc[0]), R(cqs)); - fmul(e, R(acc[1]), R(acc[1]), R(nk)); - for (unsigned i = 0; i < RR; i++) { - stg(e, arec, i * OMEGA_GDN_REC_BYTES, R(acc[0]), udesc); - stg(e, arec, i * OMEGA_GDN_REC_BYTES + OMEGA_GDN_REC_K, R(acc[1]), udesc); - stg(e, arec, i * OMEGA_GDN_REC_BYTES + OMEGA_GDN_REC_V, R(acc[2 + i]), udesc); - } - /* threads 0..2: decay and beta of value head 3 hk + c */ - isetp_ge_u32(e, c, c3); - { - Region r = region_skip_if_p0(e); - int abq = V64(e), dec = V(e), beta = V(e); - if (e->err) return -1; - ldg_wide(e, BW_IR_LDG_E_64, abq, aab, 0, udesc, 1); - gdn_scalars(e, MUT, abq, scq, dec, beta, t1, cnl2e, fone); - stg(e, asc, OMEGA_GDN_REC_SC, R(dec), udesc); stg(e, asc, OMEGA_GDN_REC_SC + 4u, R(beta), udesc); - region_end(e, r); - } - bar_sync(e); /* every warp has read the partials before the next token writes them */ - for (unsigned i = 0; i < NC; i++) imadw(e, ax[i], one, ROW, ax[i]); - imadw(e, arec, one, REC_ROW, arec); imadw(e, asc, one, REC_ROW, asc); - imadw(e, aab, one, G.vh * 8u, aab); - imadi(e, R(n), R(one), 0xffffffffu, n); - isetp_ge_u32(e, n, one); - bra_if_p0(e, L); - } - loop_end(e); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_blackwell_codegen_gdn_scan_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog || spec->copy || spec->mutant < 0 || spec->mutant > 4) return -1; - OmegaGdnShape G; - if (omega_gdn_shape(spec, &G)) return -1; - const uint32_t RR = G.r, NC = 2u + G.r; - (void)RR; (void)NC; - const int MUT = spec->mutant; - const uint32_t ROW = G.conv * 4u, CHUNK_ROW = OMEGA_GDN_SCAN_CHUNK * G.vh * OMEGA_GDN_REC_BYTES; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - - int udesc = UV64(e); - int tid = V(e), cx = V(e), cy = V(e), h = V(e), warp = V(e), lane = V(e), one = V(e), cq = V(e), rg = V(e), c0 = V(e); - int T = V(e), tm1 = V(e), t = V(e), t1 = V(e), sl = V(e), srec = V(e); - int ps = V64(e), sa = V64(e), prec = V64(e), grec = V64(e), gsc = V64(e), po = V64(e), sq[16]; - for (unsigned r = 0; r < 16; r++) sq[r] = V128(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - s2r(e, tid, BW_SR_TID_X); s2r(e, cx, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - ldc64(e, ps, OMEGA_GDN_SCAN_ARG_STATE); ldc64(e, prec, OMEGA_GDN_SCAN_ARG_REC); ldc64(e, po, OMEGA_GDN_SCAN_ARG_O); - ldc32(e, T, OMEGA_GDN_SCAN_ARG_T); - movi(e, one, 1); - imadi(e, R(h), R(cy), RR, cx); - shr(e, warp, tid, 5); - andi(e, R(lane), R(tid), 31u); - andi(e, R(cq), R(lane), 3u); - shr(e, rg, lane, 2); - /* this thread's block of S: rows 16 rg .. +15, columns c0 = 16 warp + 4 cq .. +3 */ - imadi(e, R(c0), R(warp), 16u, NOREG); imadi(e, R(c0), R(cq), 4u, c0); - const unsigned sel = spec->state_bf16 ? 2u : 4u; /* f32 or bf16 (L313) state element */ - imadi(e, R(t1), R(h), OMEGA_GDN_HEAD_DIM * OMEGA_GDN_HEAD_DIM * sel, NOREG); - imadi(e, R(t1), R(rg), 16u * OMEGA_GDN_HEAD_DIM * sel, t1); - imadi(e, R(t1), R(c0), sel, t1); - imadw(e, sa, t1, 1u, ps); - if (spec->state_bf16) { - int sw[16]; - for (unsigned r = 0; r < 16; r++) sw[r] = V64(e); - if (e->err) return -1; - for (unsigned r = 0; r < 16; r++) ldg_wide(e, BW_IR_LDG_E_64, sw[r], sa, r * OMEGA_GDN_HEAD_DIM * 2u, udesc, r == 0); - for (unsigned r = 0; r < 16; r++) bf16x4_widen(e, sq[r], sw[r]); - } else { - for (unsigned r = 0; r < 16; r++) ldg_wide(e, BW_IR_LDG_E_128, sq[r], sa, r * OMEGA_GDN_HEAD_DIM * 4u, udesc, r == 0); - } - imadi(e, R(tm1), R(one), 0xffffffffu, T); - /* the record copy: warp w brings token tc + w into shared slot w */ - imadi(e, R(t1), R(warp), G.vh, h); - imadw(e, gsc, t1, OMEGA_GDN_REC_BYTES, prec); - imadw(e, grec, lane, 16u, gsc); - imadi(e, R(srec), R(warp), OMEGA_GDN_REC_BYTES, NOREG); - imadi(e, R(sl), R(lane), 16u, srec); - /* o row of (token 0, head h), columns c0 .. c0 + 3 */ - imadi(e, R(t1), R(h), OMEGA_GDN_HEAD_DIM, c0); - imadw(e, po, t1, 4u, po); - movrz(e, R(t)); - - const int L = here(e); - loop_begin(e); - { - int tm = V(e), sb = V(e), ak = V(e), av = V(e), scq = V128(e), vq = V128(e), ts = V(e), kv[4], dl[4], p[4]; - for (unsigned j = 0; j < 4; j++) { kv[j] = V(e); dl[j] = V(e); p[j] = V(e); } - if (e->err) return -1; - andi(e, R(tm), R(t), OMEGA_GDN_SCAN_CHUNK - 1u); - isetp_ge_u32(e, tm, one); - const int b_copy = bra_if_p0_fwd(e); - { - int rr[4], a = V(e); - for (unsigned k = 0; k < 4; k++) rr[k] = V128(e); - if (e->err) return -1; - bar_sync(e); /* every warp is done with the last chunk */ - for (unsigned k = 0; k < 3; k++) ldg_wide(e, BW_IR_LDG_E_128, rr[k], grec, k * 512u, udesc, k == 0); - ldg_wide(e, BW_IR_LDG_E_128, rr[3], gsc, OMEGA_GDN_REC_SC, udesc, 0); - for (unsigned k = 0; k < 3; k++) for (unsigned j = 0; j < 4; j++) { - if (k == 0 && j == 0) sts32(e, sl, S(rr[0], 0)); - else { imadi(e, R(a), R(one), k * 512u + j * 4u, sl); sts32(e, a, S(rr[k], j)); } - } - for (unsigned j = 0; j < 4; j++) { imadi(e, R(a), R(one), OMEGA_GDN_REC_SC + j * 4u, srec); sts32(e, a, S(rr[3], j)); } - bar_sync(e); - imadw(e, grec, one, CHUNK_ROW, grec); imadw(e, gsc, one, CHUNK_ROW, gsc); - } - patch_bra(e, b_copy, here(e)); - imadi(e, R(sb), R(tm), OMEGA_GDN_REC_BYTES, NOREG); - imadi(e, R(ak), R(rg), 16u * 4u, sb); - imadi(e, R(av), R(c0), 4u, sb); - lds128(e, scq, sb, OMEGA_GDN_REC_SC, 1); - for (unsigned r = 0; r < 16; r++) for (unsigned j = 0; j < 4; j++) fmul(e, S(sq[r], j), S(sq[r], j), S(scq, 0)); - /* kv_j = sum over 128 rows of S[r][j] k[r]: 16 rows here, then lanes ^ 4, 8, 16 (the 8 row groups) */ - for (unsigned i = 0; i < 4; i++) { - int kq = V128(e); - if (e->err) return -1; - lds128(e, kq, ak, OMEGA_GDN_REC_K + i * 16u, 1); - for (unsigned r = 4 * i; r < 4 * i + 4; r++) for (unsigned j = 0; j < 4; j++) { - if (r == 0) fmul(e, R(kv[j]), S(sq[0], j), S(kq, 0)); - else ffma(e, R(kv[j]), S(sq[r], j), S(kq, r % 4), R(kv[j])); - } - } - for (unsigned j = 0; j < 4; j++) bfly_sum(e, kv[j], ts, 4u, 16u); - lds128(e, vq, av, OMEGA_GDN_REC_V, 1); - for (unsigned j = 0; j < 4; j++) { fsub(e, R(dl[j]), S(vq, j), R(kv[j])); fmul(e, R(dl[j]), R(dl[j]), S(scq, 1)); } - for (unsigned i = 0; i < 4; i++) { - int kq = V128(e); - if (e->err) return -1; - lds128(e, kq, ak, OMEGA_GDN_REC_K + i * 16u, 1); - for (unsigned r = 4 * i; r < 4 * i + 4; r++) for (unsigned j = 0; j < 4; j++) ffma(e, S(sq[r], j), S(kq, r % 4), R(dl[j]), S(sq[r], j)); - } - for (unsigned i = 0; i < 4; i++) { - int qq = V128(e); - if (e->err) return -1; - lds128(e, qq, ak, i * 16u, 1); - for (unsigned r = 4 * i; r < 4 * i + 4; r++) for (unsigned j = 0; j < 4; j++) { - if (r == 0) fmul(e, R(p[j]), S(sq[0], j), S(qq, 0)); - else ffma(e, R(p[j]), S(sq[r], j), S(qq, r % 4), R(p[j])); - } - } - for (unsigned j = 0; j < 4; j++) bfly_sum(e, p[j], ts, 4u, 16u); - isetp_ge_u32(e, rg, one); - { - Region r = region_skip_if_p0(e); - for (unsigned j = 0; j < 4; j++) stg(e, po, j * 4u, R(p[j]), udesc); - region_end(e, r); - } - imadw(e, po, one, G.vdim * 4u, po); - imadi(e, R(t), R(one), 1u, t); - isetp_ge_u32(e, tm1, t); - bra_if_p0(e, L); - } - loop_end(e); - if (spec->state_bf16) { - int pk[16]; - for (unsigned r = 0; r < 16; r++) pk[r] = V64(e); - if (e->err) return -1; - for (unsigned r = 0; r < 16; r++) { - bf16x4_pack(e, pk[r], sq[r]); - for (unsigned w = 0; w < 2; w++) stg(e, sa, r * OMEGA_GDN_HEAD_DIM * 2u + w * 4u, S(pk[r], w), udesc); - } - } else { - for (unsigned r = 0; r < 16; r++) for (unsigned j = 0; j < 4; j++) stg(e, sa, r * OMEGA_GDN_HEAD_DIM * 4u + j * 4u, S(sq[r], j), udesc); - } - - /* the new tail: qkv rows T-3 .. T-1 (times in_scale) of slot A (tid) and slot V (256 + (tid & 127)), as decode */ - if (MUT != 4) { - int half = V(e), cc = V(e), gA = V(e), gV = V(e), insc = V(e), pqkv = V64(e), ptail = V64(e), base = V64(e); - int atA = V64(e), atV = V64(e), aA[3], aV[3], xA[3], xV[3]; - for (unsigned r = 0; r < 3; r++) { aA[r] = V64(e); aV[r] = V64(e); xA[r] = V(e); xV[r] = V(e); } - if (e->err) return -1; - ldc64(e, pqkv, OMEGA_GDN_SCAN_ARG_QKV); ldc64(e, ptail, OMEGA_GDN_SCAN_ARG_TAIL); ldc32(e, insc, OMEGA_GDN_SCAN_ARG_IN_SCALE); - shr(e, half, tid, 7); - andi(e, R(cc), R(tid), 127u); - imadi(e, R(gA), R(cy), OMEGA_GDN_HEAD_DIM, tid); imadi(e, R(gA), R(half), 2048u - 128u, gA); - imadi(e, R(gV), R(h), OMEGA_GDN_HEAD_DIM, cc); imadi(e, R(gV), R(one), 2u * OMEGA_GDN_KEY_HEADS * OMEGA_GDN_HEAD_DIM, gV); - imadi(e, R(t1), R(one), 0xfffffffdu, T); - imadw(e, base, t1, ROW, pqkv); - imadw(e, aA[0], gA, 4u, base); imadw(e, aV[0], gV, 4u, base); - for (unsigned r = 1; r < 3; r++) { imadw(e, aA[r], one, ROW, aA[r - 1]); imadw(e, aV[r], one, ROW, aV[r - 1]); } - for (unsigned r = 0; r < 3; r++) { ldg32(e, xA[r], aA[r], udesc, r == 0); ldg32(e, xV[r], aV[r], udesc, 0); } - for (unsigned r = 0; r < 3; r++) { fmul(e, R(xA[r]), R(xA[r]), R(insc)); fmul(e, R(xV[r]), R(xV[r]), R(insc)); } - imadw(e, atA, tid, 16u, ptail); imadw(e, atA, h, OMEGA_GDN_TAIL_HEAD_BYTES, atA); - imadi(e, R(t1), R(one), 256u, cc); - imadw(e, atV, t1, 16u, ptail); imadw(e, atV, h, OMEGA_GDN_TAIL_HEAD_BYTES, atV); - for (unsigned r = 0; r < 3; r++) { stg(e, atA, 4u * r, R(xA[r]), udesc); stg(e, atV, 4u * r, R(xV[r]), udesc); } - } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_blackwell_codegen_gdn_post_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog || spec->copy || spec->mutant < 0 || spec->mutant > 4) return -1; - OmegaGdnShape G; - if (omega_gdn_shape(spec, &G)) return -1; - const uint32_t RR = G.r, NC = 2u + G.r; - (void)RR; (void)NC; - const int MUT = spec->mutant; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - - int udesc = UV64(e); - int tid = V(e), t = V(e), cy = V(e), warp = V(e), lane = V(e), idx = V(e), ss = V(e), ts = V(e), g = V(e), t1 = V(e); - int en = V(e), osc = V(e), insc = V(e), cinv = V(e), cnl2e = V(e), fone = V(e); - int po = V64(e), pz = V64(e), ppar = V64(e), pout = V64(e), ao = V64(e), az = V64(e), an = V64(e), ay = V64(e); - int oq = V128(e), zq = V128(e), nq = V128(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - s2r(e, tid, BW_SR_TID_X); s2r(e, t, BW_SR_CTAID_X); s2r(e, cy, BW_SR_CTAID_Y); - ldc64(e, po, OMEGA_GDN_POST_ARG_O); ldc64(e, pz, OMEGA_GDN_POST_ARG_Z); ldc64(e, ppar, OMEGA_GDN_POST_ARG_PAR); - ldc64(e, pout, OMEGA_GDN_POST_ARG_OUT); - ldc32(e, en, OMEGA_GDN_POST_ARG_EPS_NORM); ldc32(e, insc, OMEGA_GDN_POST_ARG_IN_SCALE); ldc32(e, osc, OMEGA_GDN_POST_ARG_OUT_SCALE); - shr(e, warp, tid, 5); - andi(e, R(lane), R(tid), 31u); - /* row (token t, head 8 cy + warp): o, z and out share the [T][48][128] layout */ - imadi(e, R(idx), R(cy), 8u, warp); - imadi(e, R(idx), R(t), G.vh, idx); - imadw(e, ao, idx, OMEGA_GDN_HEAD_DIM * 4u, po); imadw(e, ao, lane, 16u, ao); - imadw(e, az, idx, OMEGA_GDN_HEAD_DIM * 4u, pz); imadw(e, az, lane, 16u, az); - imadw(e, ay, idx, OMEGA_GDN_HEAD_DIM * 4u, pout); imadw(e, ay, lane, 16u, ay); - imadw(e, an, lane, 16u, ppar); - ldg_wide(e, BW_IR_LDG_E_128, oq, ao, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, zq, az, 0, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, nq, an, G.par_norm, udesc, 0); - fmul(e, R(ss), S(oq, 0), S(oq, 0)); - for (unsigned j = 1; j < 4; j++) ffma(e, R(ss), S(oq, j), S(oq, j), R(ss)); - bfly_sum(e, ss, ts, 1u, 16u); - movi(e, cinv, fbits(1.0f / 128.0f)); - ffma(e, R(ss), R(ss), R(cinv), R(en)); - mufu(e, BW_IR_MUFU_RSQ, R(ss), R(ss)); - movi(e, cnl2e, fbits(-1.44269504f)); movi(e, fone, fbits(1.0f)); - for (unsigned j = 0; j < 4; j++) { - fmul(e, R(g), S(zq, j), R(insc)); - if (MUT != 3) silu(e, R(g), t1, cnl2e, fone); - fmul(e, S(oq, j), S(oq, j), R(ss)); fmul(e, S(oq, j), S(oq, j), S(nq, j)); - fmul(e, S(oq, j), S(oq, j), R(g)); fmul(e, S(oq, j), S(oq, j), R(osc)); - } - for (unsigned j = 0; j < 4; j++) stg(e, ay, j * 4u, S(oq, j), udesc); - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -/* number of placeholders in a program, SHFL.BFLY and (bf16 state, L313) F2FP: what omega_tc_patch_code must report */ -uint32_t omega_gdn_bfly_count(const BlackwellIRProgram *prog) { - uint32_t n = 0; - for (size_t i = 0; i < prog->count; i++) - if ((prog->insns[i].op == BW_IR_SHFL_DOWN && (prog->insns[i].imm & OMEGA_TC_MARK_BFLY)) - || (prog->insns[i].op == BW_IR_FMNMX_MAX && prog->insns[i].imm == OMEGA_TC_MARK_F2FP)) n++; - return n; -} - -int omega_gdn_pf_prog_stats(unsigned kind, const OmegaGdnSpec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; - int rc = kind == 0 ? omega_blackwell_codegen_gdn_prep_prog(spec, &prog) - : kind == 1 ? omega_blackwell_codegen_gdn_scan_prog(spec, &prog) - : kind == 2 ? omega_blackwell_codegen_gdn_post_prog(spec, &prog) : -1; - if (rc != 0) return -1; - if (insns) *insns = (uint32_t)prog.count; - if (gprs) *gprs = prog.regalloc.peak_gpr_usage; - return 0; -} - -/* ======== multi-token decode (L369, see the header): T decode steps of one head in one CTA, state and tails on chip ======== - * Every token runs the decode program's phases A..E with the same instructions in the same order on the same values; the - * changes are where values live: S stays in the 64 registers between tokens (one load before the loop, one store after - * it), the conv tails are shifted in registers (one load, one store), and the loop-invariant loads (conv taps, negA and - * dt_bias, the norm weight) are issued once. */ -int omega_blackwell_codegen_gdn_multi_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog || spec->copy || spec->mutant < 0 || spec->mutant > 4) return -1; - OmegaGdnShape G; - if (omega_gdn_shape(spec, &G)) return -1; - const uint32_t RR = G.r; - const int MUT = spec->mutant; - const uint32_t C_LOG2E = fbits(1.44269504f), C_NLOG2E = fbits(-1.44269504f), C_LN2 = fbits(0.693147181f); - const uint32_t C_ONE = fbits(1.0f), C_M1 = fbits(-1.0f), C_INV128 = fbits(1.0f / 128.0f); - const float qs = 0.0883883476f; /* 1 / sqrt(128) */ - omega_bw_ir_init(prog); - if (omega_bw_ir_set_gpr_limit(prog, BW_PHYS_GPR_HW_LIMIT) != 0) return -1; - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - - /* ---- identities; the state address; the loop bounds and strides ---- */ - int udesc = UV64(e); - int tid = V(e), cx = V(e), cy = V(e), h = V(e), warp = V(e), lane = V(e), one = V(e); - int ps = V64(e), sa = V64(e), toff = V(e), sq[16]; - int T = V(e), tm1 = V(e), t = V(e), xs = V(e), abs_ = V(e), os = V(e); - for (unsigned r = 0; r < 16; r++) sq[r] = V128(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, ps, OMEGA_GDN_ARG_STATE); - 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); - imadi(e, R(h), R(cy), RR, cx); - shr(e, warp, tid, 5); - andi(e, R(lane), R(tid), 31u); - imadi(e, R(toff), R(h), OMEGA_GDN_STATE_HEAD_BYTES, NOREG); - imadi(e, R(toff), R(warp), 16u * OMEGA_GDN_HEAD_DIM * 4u, toff); - imadi(e, R(toff), R(lane), 16u, toff); - imadw(e, sa, toff, 1u, ps); - ldc32(e, T, OMEGA_GDN_MULTI_ARG_T); ldc32(e, xs, OMEGA_GDN_MULTI_ARG_XSTRIDE); - ldc32(e, abs_, OMEGA_GDN_MULTI_ARG_ABSTRIDE); ldc32(e, os, OMEGA_GDN_MULTI_ARG_OSTRIDE); - imadi(e, R(tm1), R(one), 0xffffffffu, T); - - /* ---- the loop-invariant loads: taps, tails, scalars, norm weight; the state ---- */ - int half = V(e), c = V(e), gi = V(e), slv = V(e); - int pqkv = V64(e), ppar = V64(e), ptail = V64(e); - int axA = V64(e), awA = V64(e), atA = V64(e), axV = V64(e), awV = V64(e), atV = V64(e); - int wA = V128(e), wV = V128(e), tA = V128(e), tV = V128(e); - int insc = V(e), t1 = V(e), cnl2e = V(e), fone = V(e), cl2e = V(e); - int pab = V64(e), aab = V64(e), asc = V64(e), scq = V64(e); - int pz = V64(e), az = V64(e), an = V64(e), nq = V128(e), pout = V64(e), ao = V64(e); - int el2 = V(e), en = V(e), osc = V(e); - if (e->err) return -1; - ldc64(e, pqkv, OMEGA_GDN_ARG_QKV); ldc64(e, ppar, OMEGA_GDN_ARG_PAR); ldc64(e, ptail, OMEGA_GDN_ARG_TAIL); - ldc32(e, insc, OMEGA_GDN_ARG_IN_SCALE); - shr(e, half, tid, 7); - andi(e, R(c), R(tid), 127u); - imadi(e, R(gi), R(cy), OMEGA_GDN_HEAD_DIM, tid); /* q channel hk*128 + t; k channel 2048 + hk*128 + (t - 128) */ - imadi(e, R(gi), R(half), 2048u - 128u, gi); - imadw(e, axA, gi, 4u, pqkv); imadw(e, awA, gi, 16u, ppar); - imadi(e, R(gi), R(h), OMEGA_GDN_HEAD_DIM, c); /* v channel 4096 + h*128 + c */ - imadi(e, R(gi), R(one), 2u * OMEGA_GDN_KEY_HEADS * OMEGA_GDN_HEAD_DIM, gi); - imadw(e, axV, gi, 4u, pqkv); imadw(e, awV, gi, 16u, ppar); - imadw(e, atA, tid, 16u, ptail); imadw(e, atA, h, OMEGA_GDN_TAIL_HEAD_BYTES, atA); - imadi(e, R(slv), R(one), 256u, c); - imadw(e, atV, slv, 16u, ptail); imadw(e, atV, h, OMEGA_GDN_TAIL_HEAD_BYTES, atV); - ldc64(e, pab, OMEGA_GDN_ARG_AB); - imadw(e, aab, h, 8u, pab); imadw(e, asc, h, 8u, ppar); - ldc64(e, pz, OMEGA_GDN_ARG_Z); - imadw(e, az, lane, 16u, pz); imadw(e, az, h, OMEGA_GDN_HEAD_DIM * 4u, az); - imadw(e, an, lane, 16u, ppar); - ldc64(e, pout, OMEGA_GDN_ARG_OUT); - imadw(e, ao, lane, 16u, pout); imadw(e, ao, h, OMEGA_GDN_HEAD_DIM * 4u, ao); - ldc32(e, el2, OMEGA_GDN_ARG_EPS_L2); ldc32(e, en, OMEGA_GDN_ARG_EPS_NORM); ldc32(e, osc, OMEGA_GDN_ARG_OUT_SCALE); - ldg_wide(e, BW_IR_LDG_E_128, wA, awA, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, tA, atA, 0, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, wV, awV, 0, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, tV, atV, 0, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_64, scq, asc, G.par_scal, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, nq, an, G.par_norm, udesc, 0); - for (unsigned r = 0; r < 16; r++) ldg_pf(e, sq[r], sa, r * OMEGA_GDN_HEAD_DIM * 4u, udesc, SB_STATE); - movi(e, cnl2e, C_NLOG2E); movi(e, fone, C_ONE); movi(e, cl2e, C_LOG2E); - consume(e, SB_STATE); - movrz(e, R(t)); /* waits for every load above: the loop is entered with nothing pending */ - - const int L = here(e); - loop_begin(e); - { - /* ---- phase A: conv + SiLU of channel A (q or k) and channel V, token t ---- */ - int xA = V(e), xV = V(e), accA = V(e), accV = V(e); - if (e->err) return -1; - ldg32(e, xA, axA, udesc, 1); - ldg32(e, xV, axV, udesc, 0); - fmul(e, R(xA), R(xA), R(insc)); fmul(e, R(xV), R(xV), R(insc)); - fmul(e, R(accA), S(wA, 0), S(tA, 0)); ffma(e, R(accA), S(wA, 1), S(tA, 1), R(accA)); - ffma(e, R(accA), S(wA, 2), S(tA, 2), R(accA)); ffma(e, R(accA), S(wA, 3), R(xA), R(accA)); - fmul(e, R(accV), S(wV, 0), S(tV, 0)); ffma(e, R(accV), S(wV, 1), S(tV, 1), R(accV)); - ffma(e, R(accV), S(wV, 2), S(tV, 2), R(accV)); ffma(e, R(accV), S(wV, 3), R(xV), R(accV)); - silu(e, R(accA), t1, cnl2e, fone); - silu(e, R(accV), t1, cnl2e, fone); - - /* ---- phase B: l2 norms; q|k and v to shared; the tails shift in registers ---- */ - int sqs = V(e), ts = V(e), ra = V(e); - if (e->err) return -1; - fmul(e, R(sqs), R(accA), R(accA)); - warp_sum(e, sqs, ts); - imadi(e, R(ra), R(warp), 4u, NOREG); imadi(e, R(ra), R(one), OMEGA_GDN_SM_RED, ra); - lane0_sts(e, lane, one, ra, R(sqs)); - imadi(e, R(ra), R(c), 4u, NOREG); imadi(e, R(ra), R(one), OMEGA_GDN_SM_V, ra); - sts32(e, ra, R(accV)); - bar_sync(e); - if (MUT != 4) { - mov(e, S(tA, 0), S(tA, 1)); mov(e, S(tA, 1), S(tA, 2)); mov(e, S(tA, 2), R(xA)); - mov(e, S(tV, 0), S(tV, 1)); mov(e, S(tV, 1), S(tV, 2)); mov(e, S(tV, 2), R(xV)); - } - { - int rq = V128(e), hf = V(e), fq = V(e); - if (e->err) return -1; - imadi(e, R(ra), R(half), 16u, NOREG); - lds128(e, rq, ra, OMEGA_GDN_SM_RED, 1); - fadd(e, R(sqs), S(rq, 0), S(rq, 1)); fadd(e, R(sqs), R(sqs), S(rq, 2)); fadd(e, R(sqs), R(sqs), S(rq, 3)); - fadd(e, R(sqs), R(sqs), R(el2)); - mufu(e, BW_IR_MUFU_RSQ, R(sqs), R(sqs)); - i2fp(e, hf, half); - movi(e, fq, fbits(qs)); movi(e, t1, fbits(1.0f - qs)); - ffma(e, R(fq), R(hf), R(t1), R(fq)); - fmul(e, R(accA), R(accA), R(sqs)); fmul(e, R(accA), R(accA), R(fq)); - imadi(e, R(ra), R(tid), 4u, NOREG); - sts32(e, ra, R(accA)); - bar_sync(e); - } - - /* ---- phase C: scalars of token t ---- */ - int abq = V64(e), xsc = V(e), mn = V(e), sp = V(e), dec = V(e), beta = V(e); - if (e->err) return -1; - ldg_wide(e, BW_IR_LDG_E_64, abq, aab, 0, udesc, 1); - fadd(e, R(xsc), S(abq, 0), S(scq, 1)); - movi(e, mn, C_M1); fmul(e, R(mn), R(xsc), R(mn)); fminn(e, R(mn), R(xsc), R(mn)); - fmul(e, R(mn), R(mn), R(cl2e)); mufu(e, BW_IR_MUFU_EX2, R(mn), R(mn)); fadd(e, R(mn), R(mn), R(fone)); - mufu(e, BW_IR_MUFU_LG2, R(mn), R(mn)); - movrz(e, R(sp)); fmaxx(e, R(sp), R(xsc), R(sp)); - movi(e, t1, C_LN2); ffma(e, R(sp), R(mn), R(t1), R(sp)); - if (MUT == 1) movi(e, dec, C_ONE); - else { fmul(e, R(dec), S(scq, 0), R(sp)); fmul(e, R(dec), R(dec), R(cl2e)); mufu(e, BW_IR_MUFU_EX2, R(dec), R(dec)); } - if (MUT == 2) movi(e, beta, C_ONE); - else { - fmul(e, R(beta), S(abq, 1), R(cnl2e)); mufu(e, BW_IR_MUFU_EX2, R(beta), R(beta)); - fadd(e, R(beta), R(beta), R(fone)); mufu(e, BW_IR_MUFU_RCP, R(beta), R(beta)); - } - - /* ---- phase D: the state update (S stays in registers) ---- */ - int aw = V(e), pa = V(e), la = V(e), kq[4], kv[4], dl[4], vq = V128(e), zq = V128(e); - for (unsigned i = 0; i < 4; i++) { kq[i] = V128(e); kv[i] = V(e); dl[i] = V(e); } - if (e->err) return -1; - imadi(e, R(aw), R(warp), 16u * 4u, NOREG); - imadi(e, R(pa), R(warp), OMEGA_GDN_HEAD_DIM * 4u, NOREG); imadi(e, R(pa), R(lane), 16u, pa); imadi(e, R(pa), R(one), OMEGA_GDN_SM_P, pa); - imadi(e, R(la), R(lane), 16u, NOREG); - for (unsigned r = 0; r < 16; r++) for (unsigned j = 0; j < 4; j++) fmul(e, S(sq[r], j), S(sq[r], j), R(dec)); - for (unsigned i = 0; i < 4; i++) lds128(e, kq[i], aw, OMEGA_GDN_SM_K + i * 16u, i == 0); - for (unsigned j = 0; j < 4; j++) fmul(e, R(kv[j]), S(sq[0], j), S(kq[0], 0)); - for (unsigned r = 1; r < 16; r++) for (unsigned j = 0; j < 4; j++) ffma(e, R(kv[j]), S(sq[r], j), S(kq[r / 4], r % 4), R(kv[j])); - cross_warp_sum(e, kv, pa, one, la); - lds128(e, vq, la, OMEGA_GDN_SM_V, 1); - for (unsigned j = 0; j < 4; j++) { fsub(e, R(dl[j]), S(vq, j), R(kv[j])); fmul(e, R(dl[j]), R(dl[j]), R(beta)); } - { - int k2[4]; - for (unsigned i = 0; i < 4; i++) k2[i] = V128(e); - if (e->err) return -1; - for (unsigned i = 0; i < 4; i++) lds128(e, k2[i], aw, OMEGA_GDN_SM_K + i * 16u, i == 0); - for (unsigned r = 0; r < 16; r++) for (unsigned j = 0; j < 4; j++) ffma(e, S(sq[r], j), S(k2[r / 4], r % 4), R(dl[j]), S(sq[r], j)); - } - ldg_pf(e, zq, az, 0, udesc, SB_GATE); - int p[4]; - { - int q2[4]; - for (unsigned i = 0; i < 4; i++) { q2[i] = V128(e); p[i] = V(e); } - if (e->err) return -1; - for (unsigned i = 0; i < 4; i++) lds128(e, q2[i], aw, OMEGA_GDN_SM_Q + i * 16u, i == 0); - for (unsigned j = 0; j < 4; j++) fmul(e, R(p[j]), S(sq[0], j), S(q2[0], 0)); - for (unsigned r = 1; r < 16; r++) for (unsigned j = 0; j < 4; j++) ffma(e, R(p[j]), S(sq[r], j), S(q2[r / 4], r % 4), R(p[j])); - } - bar_sync(e); - cross_warp_sum(e, p, pa, one, la); - - /* ---- phase E: gated RMSNorm, out row t ---- */ - int ss = V(e), g = V(e); - if (e->err) return -1; - fmul(e, R(ss), R(p[0]), R(p[0])); - for (unsigned j = 1; j < 4; j++) ffma(e, R(ss), R(p[j]), R(p[j]), R(ss)); - warp_sum(e, ss, ts); - imadi(e, R(ra), R(warp), 4u, NOREG); imadi(e, R(ra), R(one), OMEGA_GDN_SM_RED2, ra); - lane0_sts(e, lane, one, ra, R(ss)); - bar_sync(e); - lds32(e, R(ss), ra, 0); - movi(e, t1, C_INV128); - ffma(e, R(ss), R(ss), R(t1), R(en)); - mufu(e, BW_IR_MUFU_RSQ, R(ss), R(ss)); - consume(e, SB_GATE); - for (unsigned j = 0; j < 4; j++) { - fmul(e, R(g), S(zq, j), R(insc)); - if (MUT != 3) silu(e, R(g), t1, cnl2e, fone); - fmul(e, R(p[j]), R(p[j]), R(ss)); fmul(e, R(p[j]), R(p[j]), S(nq, j)); - fmul(e, R(p[j]), R(p[j]), R(g)); fmul(e, R(p[j]), R(p[j]), R(osc)); - } - for (unsigned j = 0; j < 4; j++) stg(e, ao, j * 4u, R(p[j]), udesc); - /* every warp is done with this token's shared memory before the next token writes it */ - bar_sync(e); - imadw(e, axA, xs, 1u, axA); imadw(e, axV, xs, 1u, axV); imadw(e, az, xs, 1u, az); - imadw(e, aab, abs_, 1u, aab); imadw(e, ao, os, 1u, ao); - imadi(e, R(t), R(one), 1u, t); - isetp_ge_u32(e, tm1, t); - bra_if_p0(e, L); - } - loop_end(e); - - /* ---- the state and the tails back to memory, once ---- */ - for (unsigned r = 0; r < 16; r++) for (unsigned j = 0; j < 4; j++) stg(e, sa, r * OMEGA_GDN_HEAD_DIM * 4u + j * 4u, S(sq[r], j), udesc); - if (MUT != 4) { - stg(e, atA, 0, S(tA, 0), udesc); stg(e, atA, 4, S(tA, 1), udesc); stg(e, atA, 8, S(tA, 2), udesc); - stg(e, atV, 0, S(tV, 0), udesc); stg(e, atV, 4, S(tV, 1), udesc); stg(e, atV, 8, S(tV, 2), udesc); - } - tail(e); - if (e->err) return -1; - return omega_bw_regalloc_solve(prog); -} - -int omega_gdn_multi_prog_stats(const OmegaGdnSpec *spec, uint32_t *insns, uint32_t *gprs) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_gdn_multi_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_gdn.h b/src/omega_blackwell_codegen_gdn.h deleted file mode 100644 index edfcce876..000000000 --- a/src/omega_blackwell_codegen_gdn.h +++ /dev/null @@ -1,191 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_GDN_H -#define OMEGA_BLACKWELL_CODEGEN_GDN_H -/* - * omega_blackwell_codegen_gdn: one decode step of a Gated DeltaNet layer of Qwen3.8-27B in ONE launch (omega#542, - * 2026-10-18). The maths is the host reference sc crates/aien-inference-abi/src/qwen38.rs `delta_net`, from the - * projections on: the caller runs in_proj_qkv / in_proj_z (FP8 GEMVs) and the stacked a/b rows (bf16 GEMV) first and - * out_proj (FP8 GEMV) after. Per value head h (48): - * conv channels q[hk], k[hk] (128 each, hk = h / 3) and v[h] (128) of the 10240-wide qkv row: causal depthwise - * conv over {tail0, tail1, tail2, x} with the layer's 4 taps, then SiLU; the tail shifts by one. - * l2norm q and k: x / sqrt(sum x^2 + eps_l2); q also / sqrt(128). - * scalars beta = sigmoid(b[h]); g = negA[h] * softplus(a[h] + dt_bias[h]), negA = -exp(A_log); decay = exp(g). - * state S[h] (128 k x 128 v, f32): S *= decay; kv = S^T k; delta = (v - kv) * beta; S += k (outer) delta; - * o = S^T q. - * output y = o / sqrt(mean(o^2) + eps_norm) * norm_w * silu(z[h]) * out_scale (norm_w shared by the heads). - * - * Grid 3 x 16 (h = ctaid.y * 3 + ctaid.x, hk = ctaid.y), 256 threads, no host round trip, no atomics. Per CTA: - * prefetch thread (warp w, lane L) owns S[h] rows 16w .. 16w+15, columns 4L .. 4L+3: 16 LDG.128 issued first on a - * held scoreboard, consumed at the state phase (the conv, norm and scalar phases hide the latency). - * phase A thread t convolves channel A (slot t: q channel t for t < 128, k channel t - 128 above) and channel V - * (slot 256 + (t & 127), computed by both halves alike); taps and tail are one LDG.128 each. - * phase B sums of squares of q and k per 4-warp half (SHFL + shared), rsqrt, q|k to shared, v to shared; then the - * shifted tails are stored (after the barrier: the two halves read the same v tail slot). - * phase C every thread: a and b (one LDG.64), negA and dt_bias (one LDG.64), softplus via EX2/LG2, decay, beta. - * phase D the state update in registers; kv and o are 8-way cross-warp sums through shared memory; S is stored - * back with 64 STG.E per thread (immediate offsets). - * phase E every warp holds all 128 o values: sum of squares by SHFL, broadcast through shared, gated norm, store. - * Branch-free except the lane-0 shared stores (BSSY / BSYNC regions). Ops used: the router's set plus MUFU.LG2 - * (encoding checked with nvdisasm, omega_blackwell_codegen.h) and I2FP. - */ -#include "omega_blackwell_codegen.h" -#include - -#define OMEGA_GDN_KEY_HEADS 16u -#define OMEGA_GDN_VALUE_HEADS 48u -#define OMEGA_GDN_HEAD_DIM 128u /* k and v head dim */ -#define OMEGA_GDN_CONV_DIM 10240u /* q 2048 | k 2048 | v 6144 */ -#define OMEGA_GDN_V_DIM (OMEGA_GDN_VALUE_HEADS * OMEGA_GDN_HEAD_DIM) /* 6144 */ -#define OMEGA_GDN_TAPS 4u -#define OMEGA_GDN_SLOTS 384u /* conv channels one head reads: q | k | v */ - -/* per-layer parameter block (bytes): conv taps f32 [10240][4] | {negA, dt_bias} f32 [48][2] | norm_w f32 [128] */ -#define OMEGA_GDN_PAR_CONV 0u -#define OMEGA_GDN_PAR_SCAL 163840u -#define OMEGA_GDN_PAR_NORM 164224u -#define OMEGA_GDN_PAR_BYTES 164736u -/* per-layer conv tail: f32 [48 heads][384 slots][4] = {x_{t-3}, x_{t-2}, x_{t-1}, unused}; each head keeps its own - * copy of the q/k channels of its key head (the three heads of a key head hold equal copies), so no CTA reads a word - * another CTA writes */ -#define OMEGA_GDN_TAIL_HEAD_BYTES (OMEGA_GDN_SLOTS * 16u) /* 6144 */ -#define OMEGA_GDN_TAIL_BYTES (OMEGA_GDN_VALUE_HEADS * OMEGA_GDN_TAIL_HEAD_BYTES) -/* per-layer state: f32 [48][128 k][128 v], the reference layout */ -#define OMEGA_GDN_STATE_HEAD_BYTES (OMEGA_GDN_HEAD_DIM * OMEGA_GDN_HEAD_DIM * 4u) /* 65536 */ -#define OMEGA_GDN_STATE_BYTES (OMEGA_GDN_VALUE_HEADS * OMEGA_GDN_STATE_HEAD_BYTES) - -/* constant bank: addresses at 0x380 + 8n, then the scalars */ -#define OMEGA_GDN_ARG_QKV 0x380u /* f32 [10240] in_proj_qkv row (times in_scale) */ -#define OMEGA_GDN_ARG_Z 0x388u /* f32 [6144] in_proj_z row (times in_scale) */ -#define OMEGA_GDN_ARG_AB 0x390u /* f32 [48][2] {a[h], b[h]}: the bf16 GEMV of in_proj_a / in_proj_b rows interleaved */ -#define OMEGA_GDN_ARG_PAR 0x398u /* the layer's parameter block */ -#define OMEGA_GDN_ARG_TAIL 0x3a0u /* the layer's conv tail */ -#define OMEGA_GDN_ARG_STATE 0x3a8u /* the layer's state */ -#define OMEGA_GDN_ARG_OUT 0x3b0u /* f32 [6144] y (the out_proj input) */ -#define OMEGA_GDN_ARG_EPS_L2 0x3b8u /* f32, 1e-6 in the reference */ -#define OMEGA_GDN_ARG_EPS_NORM 0x3bcu /* f32, rms_norm_eps */ -#define OMEGA_GDN_ARG_IN_SCALE 0x3c0u /* f32: qkv and z are multiplied by it on read */ -#define OMEGA_GDN_ARG_OUT_SCALE 0x3c4u /* f32: y is multiplied by it */ -#define OMEGA_GDN_ARGS_WORDS 18u - -/* shared memory map (bytes) */ -#define OMEGA_GDN_SM_Q 0u /* q[128] f32, normalised and / sqrt(128) */ -#define OMEGA_GDN_SM_K 512u /* k[128] f32 */ -#define OMEGA_GDN_SM_V 1024u /* v[128] f32 */ -#define OMEGA_GDN_SM_RED 1536u /* per-warp sums of squares of q|k [8] */ -#define OMEGA_GDN_SM_P 1600u /* per-warp partials [8][128] f32 (kv, then o) */ -#define OMEGA_GDN_SM_RED2 5696u /* per-warp sums of squares of o [8] */ -#define OMEGA_GDN_SHARED_BYTES 5728u - -#define OMEGA_GDN_THREADS 256u -#define OMEGA_GDN_GRID_X 3u -#define OMEGA_GDN_GRID_Y 16u - -typedef struct { - int mutant; /* TEST ONLY. 0 none; 1 no decay (decay = 1); 2 beta = 1; 3 the output gate is z, not silu(z); - * 4 the conv tail is not shifted (the next step convolves stale history). */ - int copy; /* 0: the GDN kernels. OMEGA_GDN_COPY / OMEGA_GDN_ZERO: omega_blackwell_codegen_gdn_copy_prog */ - uint32_t ratio; /* value heads per key head (16 key heads): 0 = 3 (Qwen3.8-27B, 48 value heads, the program before - * this field existed); 2 = Qwen3.6-35B-A3B (32 value heads, conv 8192). Appended last. */ - uint32_t state_bf16; /* L313: 1 = the state is stored bf16 (round to nearest even on store, exact widen on load), half the - * bytes; compute stays f32. 0 = f32 (the program before this field existed). Appended last. */ -} OmegaGdnSpec; - -/* The shape a spec selects (Q36, sc L306). The 27B constants above are the ratio-3 values. */ -typedef struct { - uint32_t r, vh; /* ratio, value heads (16 r) */ - uint32_t conv, vdim; /* conv channels 4096 + 128 vh, value width 128 vh */ - uint32_t par_scal, par_norm, par_bytes; /* the parameter block: conv taps [conv][4] | {negA, dt_bias} [vh] | norm [128] */ - uint32_t tail_bytes, state_bytes; /* per layer */ - uint32_t post_grid_y; /* vh / 8 */ -} OmegaGdnShape; -int omega_gdn_shape(const OmegaGdnSpec *spec, OmegaGdnShape *s); /* 0 ok, -1 unsupported ratio */ - -/* Builds the register-allocated IR program into *prog. 0 ok, -1 refused. */ -int omega_blackwell_codegen_gdn_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog); -/* Instruction and peak-register counts (host, no device). */ -int omega_gdn_prog_stats(const OmegaGdnSpec *spec, uint32_t *insns, uint32_t *gprs); - -/* ---- multi-token decode (L369, 2026-10-21): T decode steps of every head in ONE launch, bit for bit the decode program - * T times (omega_blackwell_codegen_gdn.c). Same grid, threads, shared memory and argument block as the decode step plus - * the four words below; token t reads qkv + t * xstride, z + t * xstride, ab + t * abstride and writes out + t * ostride - * (bytes). Per CTA the state S stays in the 64 registers and the conv tails in registers for the whole loop (one load - * before it, one store after it); the per-token arithmetic is the decode step's, instruction for instruction. T >= 1. */ -#define OMEGA_GDN_MULTI_ARG_T 0x3c8u /* u32 tokens */ -#define OMEGA_GDN_MULTI_ARG_XSTRIDE 0x3ccu /* u32 bytes between the qkv rows (and the z rows) of consecutive tokens */ -#define OMEGA_GDN_MULTI_ARG_ABSTRIDE 0x3d0u /* u32 bytes between the ab rows */ -#define OMEGA_GDN_MULTI_ARG_OSTRIDE 0x3d4u /* u32 bytes between the out rows */ -#define OMEGA_GDN_MULTI_ARGS_WORDS 22u -int omega_blackwell_codegen_gdn_multi_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog); -int omega_gdn_multi_prog_stats(const OmegaGdnSpec *spec, uint32_t *insns, uint32_t *gprs); - -/* ---- state copy / zero (qwen38/decode-speed, 2026-10-19): the tail and state live in GPU-cached memory (nvos.h - * NVOS32_ATTR2_GPU_CACHEABLE_YES: "For system memory this will not be coherent with direct CPU mappings"), so the host - * never writes or reads them directly: reset zeroes them on the chip, set_state / get_state copy through an uncached - * staging buffer. One launch moves 1024 words per CTA (grid words / 1024, 256 threads, thread t word 1024 c + 256 j + t, - * j = 0..3: every LDG.E / STG.E of a warp covers 128 contiguous bytes). COPY: dst[i] = src[i]; ZERO: dst[i] = 0. */ -#define OMEGA_GDN_COPY 1 -#define OMEGA_GDN_ZERO 2 -#define OMEGA_GDN_COPY_WORDS_PER_CTA 1024u -#define OMEGA_GDN_COPY_THREADS 256u -#define OMEGA_GDN_COPY_ARG_SRC 0x380u /* COPY only */ -#define OMEGA_GDN_COPY_ARG_DST 0x388u -#define OMEGA_GDN_COPY_ARGS_WORDS 4u -int omega_blackwell_codegen_gdn_copy_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog); - -/* ---- prefill (omega#543, 2026-10-18): three launches per layer over T >= 3 new tokens, the same tail and state ---- - * prep grid (ceil(T / 16), 16 key heads), 128 threads. Thread c convolves 5 channels of its key head (q c, k c and v c - * of the three value heads), sliding each window in registers over 16 tokens (the CTA starting at token 0 takes - * its window from the layer's tail, the others from the qkv rows before it), then SiLU, the q/k l2 norms (two - * barriers per token) and, threads 0..2, the scalars of the three value heads. It writes one record per (token, - * value head): q^ | k^ | v | {decay, beta, 0, 0}. It reads the tail and never writes it. - * scan grid 3 x 16 (one CTA per value head), 256 threads. Thread (warp w, lane L) holds S rows 16 (L >> 2) .. +15, - * columns 16 w + 4 (L & 3) .. +3 in registers for the whole prompt. Per 8-token chunk every warp copies one - * token's record into shared memory (two barriers); per token kv and o are summed across the 8 row groups by - * SHFL.BFLY (lanes ^ 4, 8, 16; a butterfly gives every lane the same bits), no barrier. It writes o (before the - * norm) per token, the state at the end and the new tail (the last three qkv rows). - * post grid (T, 6), 256 threads: warp w normalises (token, head 8 ctaid.y + w): gated RMSNorm, silu(z), out_scale. - * The mutants keep the decode meanings: 1 and 2 act in prep, 3 in post, 4 in scan. */ -#define OMEGA_GDN_REC_BYTES 1552u -#define OMEGA_GDN_REC_K 512u -#define OMEGA_GDN_REC_V 1024u -#define OMEGA_GDN_REC_SC 1536u -#define OMEGA_GDN_PF_MIN_T 3u -#define OMEGA_GDN_PREP_TOKENS 16u -#define OMEGA_GDN_PREP_THREADS 128u -#define OMEGA_GDN_PREP_SHARED_BYTES 32u /* per-warp sums of squares: q [4] | k [4] */ -#define OMEGA_GDN_PREP_ARG_QKV 0x380u /* f32 [T][10240] (times in_scale) */ -#define OMEGA_GDN_PREP_ARG_AB 0x388u /* f32 [T][48][2] */ -#define OMEGA_GDN_PREP_ARG_PAR 0x390u -#define OMEGA_GDN_PREP_ARG_TAIL 0x398u -#define OMEGA_GDN_PREP_ARG_REC 0x3a0u /* [T rounded up to 8][48] records */ -#define OMEGA_GDN_PREP_ARG_T 0x3a8u /* u32 */ -#define OMEGA_GDN_PREP_ARG_EPS_L2 0x3acu -#define OMEGA_GDN_PREP_ARG_IN_SCALE 0x3b0u -#define OMEGA_GDN_PREP_ARGS_WORDS 13u -#define OMEGA_GDN_SCAN_CHUNK 8u -#define OMEGA_GDN_SCAN_SHARED_BYTES (OMEGA_GDN_SCAN_CHUNK * OMEGA_GDN_REC_BYTES) /* 12416 */ -#define OMEGA_GDN_SCAN_ARG_REC 0x380u -#define OMEGA_GDN_SCAN_ARG_QKV 0x388u -#define OMEGA_GDN_SCAN_ARG_TAIL 0x390u -#define OMEGA_GDN_SCAN_ARG_STATE 0x398u -#define OMEGA_GDN_SCAN_ARG_O 0x3a0u /* f32 [T][48][128] */ -#define OMEGA_GDN_SCAN_ARG_T 0x3a8u -#define OMEGA_GDN_SCAN_ARG_IN_SCALE 0x3acu -#define OMEGA_GDN_SCAN_ARGS_WORDS 12u -#define OMEGA_GDN_POST_ARG_O 0x380u -#define OMEGA_GDN_POST_ARG_Z 0x388u /* f32 [T][6144] (times in_scale) */ -#define OMEGA_GDN_POST_ARG_PAR 0x390u -#define OMEGA_GDN_POST_ARG_OUT 0x398u /* f32 [T][6144] */ -#define OMEGA_GDN_POST_ARG_EPS_NORM 0x3a0u -#define OMEGA_GDN_POST_ARG_IN_SCALE 0x3a4u -#define OMEGA_GDN_POST_ARG_OUT_SCALE 0x3a8u -#define OMEGA_GDN_POST_ARGS_WORDS 11u -#define OMEGA_GDN_POST_GRID_Y 6u - -int omega_blackwell_codegen_gdn_prep_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog); -int omega_blackwell_codegen_gdn_scan_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog); -int omega_blackwell_codegen_gdn_post_prog(const OmegaGdnSpec *spec, BlackwellIRProgram *prog); -/* SHFL.BFLY placeholders in a built program; prefill stats: kind 0 prep, 1 scan, 2 post. */ -uint32_t omega_gdn_bfly_count(const BlackwellIRProgram *prog); -int omega_gdn_pf_prog_stats(unsigned kind, const OmegaGdnSpec *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 d8bbfb877..000000000 --- a/src/omega_blackwell_codegen_gemm.c +++ /dev/null @@ -1,390 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 > 4) return 0; - if (s->rowmap > 1u || (s->rowmap && s->mt > 4u)) return 0; /* the mapped form keeps NJ row bases and MT y rows in registers: mt 8 needs 135 at 16 warps, past the file */ - 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), z = V(e); - const int RM = spec->rowmap ? 1 : 0; - int pxm = RM ? V64(e) : NOREG, pym = RM ? V64(e) : NOREG; - 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); - if (RM) { ldc64(e, pxm, OMEGA_GEMM_ARG_XMAP); ldc64(e, pym, OMEGA_GEMM_ARG_YMAP); } - 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); - /* an empty segment (cnt 0, a stroke table slot without an expert): the whole CTA leaves before the loops. Without this the - * pass loop (do-while, pc = passes - 1 wraps) runs 2^32 passes: the warp simulator's step budget caught it (2026-10-21). */ - int bra_empty = -1; - if (spec->mutant != 4) { /* mutant 4 (tests): the guard dropped */ - imadi(e, z, one, 0, 0xffffffffu, cnt); shr(e, z, z, 0, 31); /* 1 iff cnt == 0 */ - isetp_ge_u32(e, z, one); - bra_empty = bra_if_p0_fwd(e); - } - 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 xb[16], yi[16], xso = NOREG, ma = NOREG; /* rowmap: x' base per staged quad (row through XMAP), the step byte offset, y rows through YMAP */ - if (RM) { if (NJ > 16u) return -1; for (uint32_t j = 0; j < NJ; j++) xb[j] = V64(e); for (uint32_t m = 0; m < MT; m++) yi[m] = V(e); xso = V(e); ma = V64(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); - if (!RM) { imadw(e, xrp, t, K * 4u, px); imadw(e, xrp, off4, 1, xrp); imadw(e, xs, one, 0, xrp); } - else { - /* sorted row p = rowp + mrow + pos / ROWW of each staged quad: its x' row is XMAP[p] (one u32 load per quad per pass) */ - for (uint32_t j = 0; j < NJ; j++) { /* the NJ index loads back to back (one batch), the index in the low word of xb[j] */ - imadi(e, tq, one, 0, (j * T) / ROWW, t); imadw(e, ma, tq, 4u, pxm); - ldg32(e, xb[j], ma, udesc, j == 0); - } - for (uint32_t j = 0; j < NJ; j++) { - const uint32_t pos = j * T; - imadw(e, xb[j], xb[j], K * 4u, px); imadw(e, xb[j], off4, 1, xb[j]); imadw(e, xb[j], one, (pos % ROWW) * 4u, xb[j]); - } - movi(e, xso, 0); - } - 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; if (RM) imadw(e, xa[q], xso, 1u, xb[j0 + q]); else 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); - if (RM) imadi(e, xso, one, 0, ROWW * 4u, xso); else 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); - if (RM) { /* y row of sorted row rowp + m: YMAP[rowp + m], uniform loads, before the predicated stores */ - for (uint32_t m = 0; m < MT; m++) { imadi(e, tq, one, 0, m, rowp); imadw(e, ma, tq, 4u, pym); ldg32(e, yi[m], ma, udesc, m == 0); } - } - 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); - if (RM) { imadr(e, tq, yi[m], ysn, NOREG); imadw(e, pya, tq, 1, pyrg); } else 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); - if (bra_empty >= 0) patch_bra(e, bra_empty, 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 b3e45726f..000000000 --- a/src/omega_blackwell_codegen_gemm.h +++ /dev/null @@ -1,94 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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) - * A segment with cnt 0 is skipped (its CTAs exit at once): the stroke's expert table has one slot per (head, expert pick) and only - * the distinct experts are filled, so grid_y can be the slot count at record time. - * 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, 4 drops the empty-segment guard (a cnt 0 segment then runs 2^32 passes: the - * warp simulator's step budget catches it). 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_ARG_XMAP 0x3a0u /* rowmap: u32 [rows + mt] x' row of sorted row p (padding entries 0) */ -#define OMEGA_GEMM_ARG_YMAP 0x3a8u /* rowmap: u32 [rows + mt] y row of sorted row p */ -#define OMEGA_GEMM_ARGS_WORDS 8u -#define OMEGA_GEMM_ARGS_WORDS_MAP 12u -#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; - uint32_t rowmap; /* 1: x' rows and y rows are addressed through XMAP / YMAP (the decode stroke: N heads' rows grouped by - * expert on the chip; the x' buffer holds one permuted row per head, the outputs land in head order). 0: the - * prefill form, x' row i and y row i are sorted row i. mt <= 4 (registers); the dense trunk of a stroke (one - * segment, the heads' rows in head order) needs no map and runs at mt 8. */ -} 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 36300b59d..000000000 --- a/src/omega_blackwell_codegen_moe.c +++ /dev/null @@ -1,519 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 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 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 > 5 || (s->mutant >= 4 && !s->coal)) return 0; - if (s->sched > 1 || s->coal > 1 || s->wfirst > 1) return 0; - if (s->coal && s->warps * s->rows > 32u) return 0; /* warp 0 stores the round: one row per lane */ - 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; } -/* deep: x' (k words) + one dummy slot for the clamped threads of a partial staging round; coal: then two output slot sets */ -static uint32_t x_stage_bytes(const OmegaFp8GemvSpec *s) { return s->depth ? s->k * 4u + 16u : 0u; } -static uint32_t out_slot_bytes(const OmegaFp8GemvSpec *s) { return s->warps * s->rows * 4u; } -uint32_t omega_fp8_gemv_shared_bytes(const OmegaFp8GemvSpec *spec) { - if (!spec_ok(spec)) return 0u; - return x_stage_bytes(spec) + (spec->coal ? 2u * out_slot_bytes(spec) : 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); /* 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); -} - -/* ---- sched 1 (CUT5): pipelined byte decode ---- - * Byte b of a K step (word b / 4, byte b % 4) goes through five instructions: E (shift the byte to bits 20..27), - * S (isolate its sign), M (mask the magnitude), F (sign to bit 31 plus magnitude = the f32 bits) and C (the FFMA into - * dot). Iteration c emits E(c), S(c), M(c - 2), F(c - 3), C(c - 5): every producer is at least 6 instructions ahead of - * its user (E->M 12, S->F 12+, M->F 6, F->C 11), so the stall pass below can give most instructions stall 1 while the - * FFMA chain (one per 5 instructions) runs at the 6-cycle fixed latency. t1 holds a byte from E to F (4 slots), t2 from - * S to C (6 slots). The FFMA order (byte 0, 1, ... of word 0, then word 1 ...) and every operand are those of the - * sched 0 loop, so y is bit-identical. */ -#define PIPE_T1 4 -#define PIPE_T2 6 -static void decode_pipe(Em *e, int wqv, uint32_t words, const int *xq, int dot, const int *t1, const int *t2) { - const uint32_t M = 0x07F00000u, NB = 4u * words; - for (uint32_t c = 0; c < NB + 5u; c++) { - if (c < NB) { - const uint32_t word = c / 4u, i = c % 4u; - const int u = t1[c % PIPE_T1], sg = t2[c % PIPE_T2]; - if (i < 3) imadi(e, u, wqv, word, 1u << (20u - 8u * i), NOREG); else shr(e, u, wqv, word, 4); - andi(e, sg, wqv, word, 0x80u << (8u * i)); - } - if (c >= 2 && c - 2u < NB) { const int u = t1[(c - 2u) % PIPE_T1]; andi(e, u, u, 0, M); } - if (c >= 3 && c - 3u < NB) { - const uint32_t b = c - 3u, i = b % 4u; - const int sg = t2[b % PIPE_T2], u = t1[b % PIPE_T1]; - imadi(e, sg, sg, 0, i < 3 ? 1u << (24u - 8u * i) : 1u, u); - } - if (c >= 5 && c - 5u < NB) { const uint32_t b = c - 5u; ffma(e, dot, t2[b % PIPE_T2], xq[b / 4u], b % 4u, dot); } - } -} - -/* ---- sched 1: dependency-driven stall counts (after register allocation) ---- - * The 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). Same pass as omega_blackwell_codegen_tern.c (chip-proven at TERN-T0 2300f164) with - * this kernel's fixed-latency set, which adds FFMA, FADD and LOP3_XOR: walk the program in order on physical registers - * and give each instruction the smallest stall that keeps the next instruction >= OMEGA_FP8_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. Other instructions - * keep at least their emitted stall (loads 4, ISETP 14 before a predicated branch); wait masks are untouched. */ -static int fp8_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_LOP3_XOR: case BW_IR_MOV_IMM: - case BW_IR_MOV_RZ: case BW_IR_FFMA: case BW_IR_FADD: return 1; - default: return 0; - } -} -static int fp8_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; -} -static void fp8_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 fp8_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; - const int fixed = fp8_fixed(in->op); - if (fixed) { - int lo, c; fp8_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_FP8_FIXED_LAT; } - if (c && T + OMEGA_FP8_FIXED_LAT > all) all = T + OMEGA_FP8_FIXED_LAT; - } - uint64_t need = T + (fixed ? 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; fp8_span(p, ops[q], &lo, &c); - for (int k = 0; k < c; k++) if (lo + k < BW_MAX_VREGS + 8 && ready[lo + k] > need) need = ready[lo + k]; - } - if ((fp8_control(nx->op) || target[i + 1]) && all > need) need = all; - } - const uint64_t s = need - T; - if (s > 15 || (s == 0 && (fixed || s_emit != 0))) return -1; /* stall 0 only where emitted (the final self-branch) */ - if (fixed || s > s_emit) in->control = (in->control & ~(0xfu << 9)) | ((uint32_t)s << 9); - T = need; - } - return 0; -} - -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); - int pt1[PIPE_T1], pt2[PIPE_T2]; /* sched 1 only: allocated after every sched 0 register, so sched 0 code is unchanged */ - if (spec->sched) { for (int q = 0; q < PIPE_T1; q++) pt1[q] = V(e); for (int q = 0; q < PIPE_T2; q++) pt2[q] = V(e); } - /* coal 1 only, allocated last for the same reason: uc first row group of the CTA's round, rgx the clamped row group */ - const int coal = spec->coal != 0; - int uc = NOREG, rgx = rg, um1 = NOREG, negU = NOREG, negn = NOREG, okw = NOREG, tq = NOREG, slb = NOREG, stog = NOREG; - int so = NOREG, sa = NOREG, wl1 = NOREG, val = NOREG, row = NOREG, skip = NOREG; - if (coal) { - uc = V(e); rgx = V(e); um1 = V(e); negU = V(e); negn = V(e); okw = V(e); tq = V(e); slb = V(e); stog = V(e); - so = V(e); sa = V(e); wl1 = V(e); val = V(e); row = V(e); skip = 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 */ - } - - if (coal) { - /* ---- coalesced output (variant A): per-CTA round variables. All values stay below 2^31 (RG, n <= 2^24), - * so (a - b) >> 31 is the 0/1 test a < b. ---- */ - const uint32_t nrow = W * R; - imadi(e, um1, one, 0, 0xffffffffu, rgn); /* RG - 1 */ - imadi(e, negU, rgn, 0, 0xffffffffu, NOREG); /* -RG */ - imadi(e, negn, rgn, 0, 0u - R, NOREG); /* -n (n = RG * R) */ - movi(e, slb, x_stage_bytes(spec)); /* slot set of this round (alternates) */ - /* stog = sum of the two set bases: slb = stog - slb alternates (XOR would need a base aligned to the set size) */ - movi(e, stog, 2u * x_stage_bytes(spec) + (spec->mutant == 4 ? 0u : out_slot_bytes(spec))); /* mutant 4: one slot set, the round race */ - imadi(e, so, warp, 0, R * 4u, NOREG); /* this warp's slot: warp * R words */ - imadi(e, tq, lane, 0, 0xffffffffu, NOREG); imadi(e, tq, one, 0, nrow - 1u, tq); shr(e, tq, tq, 0, 31); /* lane >= W R */ - imadi(e, wl1, warp, 0, 1, tq); imadi(e, wl1, one, 0, 1, wl1); /* warp + (lane >= W R) + 1 */ - imadi(e, uc, cx, 0, W, NOREG); /* first row group of this CTA's round (CTA-uniform) */ - } - - /* ---- row-group loop ---- */ - const int L_rg = here(e); - loop_begin(e); - isetp_ge_u32(e, coal ? uc : rg, rgn); /* coal: the whole CTA leaves together (barriers inside) */ - const int bra_end = bra_if_p0_fwd(e); - if (coal) { - /* a warp past the last row group recomputes row group RG - 1 (inside the tensor); its slot is never stored */ - imadi(e, tq, rg, 0, 1, negU); /* rg - RG */ - shr(e, okw, tq, 0, 31); /* 1 if rg < RG */ - imadi(e, tq, one, 0, 1, tq); /* rg - RG + 1 */ - if (spec->mutant == 5) imadi(e, rgx, rg, 0, 1, NOREG); /* mutant 5: no clamp, a warp past RG reads past the tensor */ - else imadr(e, rgx, okw, tq, um1); /* rg < RG ? rg : RG - 1 */ - } - imadw(e, pw, rgx, R * K, wbase); imadw(e, pw, wlane, 1, pw); - shr(e, srg, rgx, 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; - const int xfirst = !deep && !spec->wfirst, xlast = !deep && spec->wfirst; - if (xfirst) { 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); - if (xlast) for (uint32_t q = 0; q < WORDS; q++) ldg_wide(e, BW_IR_LDG_E_128, xq[q], pxc, q * 16u, udesc, 0); /* variant B */ - } - 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); - if (spec->sched) decode_pipe(e, wq[r][s], WORDS, xq, dot, pt1, pt2); - else - 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); } - if (!coal) { - 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); - } else { - /* lane 0 of each warp parks its R results in this round's slot set */ - isetp_ge_u32(e, lane, one); - int at_bssy = bssy_fwd(e), bra_skip = bra_if_p0_fwd(e); - imadi(e, sa, slb, 0, 1, so); /* slot set + warp * R words */ - for (uint32_t r = 0; r < R; r++) { if (r) imadi(e, sa, one, 0, 4u, sa); sts32(e, sa, acc[r]); } - int at_bsync = here(e); - bsync(e); - patch_bra(e, bra_skip, at_bsync); - patch_bra(e, at_bssy, at_bsync + 1); - bar_sync(e); - /* warp 0, lanes < W R: row = R uc + lane, stored when < n, one coalesced STG for the round */ - imadi(e, row, uc, 0, R, lane); - imadi(e, okw, row, 0, 1, negn); shr(e, okw, okw, 0, 31); /* 1 if row < n */ - imadi(e, skip, okw, 0, 0xffffffffu, wl1); /* warp + (lane >= W R) + 1 - (row < n): 0 only for a store */ - isetp_ge_u32(e, skip, one); - at_bssy = bssy_fwd(e); bra_skip = bra_if_p0_fwd(e); - imadi(e, sa, lane, 0, 4u, slb); - lds32(e, val, sa); - imadw(e, pya, row, 4u, yrow); - stg(e, pya, 0, val, udesc); - at_bsync = here(e); - bsync(e); - patch_bra(e, bra_skip, at_bsync); - patch_bra(e, at_bssy, at_bsync + 1); - imadi(e, slb, slb, 0, 0xffffffffu, stog); /* next round parks in the other slot set: stog - slb */ - imadi(e, uc, stride, 0, 1, uc); - } - 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; - if (omega_bw_regalloc_solve(prog) != 0) return -1; - return spec->sched ? fp8_schedule_stalls(prog) : 0; -} - -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 dd915865d..000000000 --- a/src/omega_blackwell_codegen_moe.h +++ /dev/null @@ -1,143 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 32768u /* the step kernel and the tensor-core kernel loop over k; 17408 is the Qwen3.8-27B down_proj (omega#541) */ -#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; 4, 5 with coal = 1 (below) */ - uint32_t sched; /* 0 (default, chip-proven): every fixed-latency instruction stalls 6, one byte decoded at a time. - * 1 (CUT5, measurement variant): the bytes of a step are decoded in a 3-deep software pipeline with - * their own temporaries, and a pass after register allocation (omega_fp8_schedule_stalls) gives each - * instruction the smallest stall that keeps every user >= OMEGA_FP8_FIXED_LAT cycles behind each - * fixed-latency write (the repo rule, omega_gpu_elementwise_api.c:13). The FFMA order is unchanged, - * so y is bit-identical to sched 0. Appended last: earlier fields keep their offsets. */ - uint32_t coal; /* 0 (default): lane 0 of each warp stores its R row results (4-byte STG each) to y. - * 1 (CUT5 variant A, after omega#490 KT1): the CTA works in rounds (row groups uc .. uc + W - 1, - * uc uniform); lane 0 of each warp parks its R results in shared slots (two slot sets alternating by - * round, one BAR.SYNC per round) and warp 0 stores the round's W * R consecutive rows with one - * coalesced STG. A warp past the last row group recomputes row group RG - 1 and its slot is never - * stored. Needs warps * rows <= 32. Test mutants: 4 = one slot set (the round race), 5 = no clamp. */ - uint32_t wfirst; /* 0 (default): each K step issues the x' loads, then the scale address IMADs, then the weight and - * scale loads. The IMADs wait on the x' loads' scoreboard (every fixed-latency op waits on the pending - * loads, emit()), so each step pays the x' round trip before any weight load goes out. - * 1 (CUT5 variant B): scale addresses first, then weight, scale and x' loads in one batch with no wait - * between them. Ignored by deep kernels (depth >= 1), which read x' from shared memory. */ -} OmegaFp8GemvSpec; - -#define OMEGA_FP8_FIXED_LAT 6u /* cycles a fixed-latency result needs before a user (the repo keeps 6; hardware minimum 5) */ - -/* 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 + 16 for a deep kernel, 0 otherwise, plus 2 * warps * rows * 4 - * (the two output slot sets) when coal = 1. */ -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 eee933b5f..000000000 --- a/src/omega_blackwell_codegen_moe2.c +++ /dev/null @@ -1,358 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 fc8533a34..000000000 --- a/src/omega_blackwell_codegen_moe2.h +++ /dev/null @@ -1,73 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 83dee6b00..000000000 --- a/src/omega_blackwell_codegen_pattn.c +++ /dev/null @@ -1,574 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 b7f8ff1a2..000000000 --- a/src/omega_blackwell_codegen_pattn.h +++ /dev/null @@ -1,99 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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_pattn256.c b/src/omega_blackwell_codegen_pattn256.c deleted file mode 100644 index 572f15f33..000000000 --- a/src/omega_blackwell_codegen_pattn256.c +++ /dev/null @@ -1,398 +0,0 @@ -/* - * omega_blackwell_codegen_pattn256.c: causal prefill attention for Qwen3.8-27B on tensor cores, the attend launch - * (see the header). The emitter helpers are those of omega_blackwell_codegen_pattn.c, copied unchanged (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). - */ -#include "omega_blackwell_codegen_pattn256.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 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 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 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 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 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); } - - -/* shared memory map */ -#define SM_K 0u /* K block, [s 16][lane 32][16 B]: lane (g, t) holds b0, b1 of key g and of key 8 + g */ -#define SM_V 8192u /* V block, [np 16][lane 32][16 B]: b0, b1 of dim tiles 2np and 2np + 1 */ -static const uint32_t NEG_BIG = 0xF149F2CAu; /* -1e30f */ - -int omega_pattn256_shape(const OmegaPrefillAttn256Spec *spec, OmegaPattn256Shape *s) { - const uint32_t qh = spec->q_heads ? spec->q_heads : 24u, kvh = spec->kv_heads ? spec->kv_heads : 4u; - if (kvh == 0 || qh % kvh || qh / kvh > 8u) return -1; - s->qh = qh; s->kvh = kvh; s->group = qh / kvh; s->out_words = qh * 256u; s->qf_pair_bytes = qh * 1024u; - return 0; -} - -int omega_pattn256_spec_ok(const OmegaPrefillAttn256Spec *s) { - OmegaPattn256Shape sh; - return s && s->mutant >= 0 && s->mutant <= 2 && omega_pattn256_shape(s, &sh) == 0; -} - -int omega_blackwell_codegen_prefill_attn256_prog(const OmegaPrefillAttn256Spec *spec, BlackwellIRProgram *prog) { - if (!omega_pattn256_spec_ok(spec) || !prog) return -1; - omega_bw_ir_init(prog); - if (omega_bw_ir_set_gpr_limit(prog, BW_PHYS_GPR_HW_LIMIT) != 0) return -1; - Em em; memset(&em, 0, sizeof em); em.p = prog; Em *e = &em; - const int MUT = spec->mutant; - OmegaPattn256Shape SH; - if (omega_pattn256_shape(spec, &SH) != 0) return -1; - - /* ---- arguments and identities ---- */ - int udesc = UV64(e); - int pqf = V64(e), pkc = V64(e), pvc = V64(e); - int pos0 = V(e), mc = V(e), kvs = V(e); - int tid = V(e), cx = V(e), cy = V(e), warp = V(e), lane = V(e), one = V(e), zero = V(e); - int cyk = V(e), nk = V(e), t1 = V(e), t2 = V(e), cxw = V(e), cnt = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pqf, OMEGA_PATTN256_ARG_QF); ldc64(e, pkc, OMEGA_PATTN256_ARG_KC); ldc64(e, pvc, OMEGA_PATTN256_ARG_VC); - ldc32(e, pos0, OMEGA_PATTN256_ARG_POS0); ldc32(e, mc, OMEGA_PATTN256_ARG_MC); ldc32(e, kvs, OMEGA_PATTN256_ARG_KV_STRIDE); - 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)); - 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), OMEGA_PATTN256_TOKENS, NOREG); /* first chunk token of the CTA */ - /* nk = min(cxw + 8, mc) = hi + over * (mc - hi), over = 1 when hi > mc */ - imadi(e, R(t2), R(one), OMEGA_PATTN256_TOKENS, 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); } - - /* ---- Q: the tile's 16 A fragments straight from QF (16 LDG.128 from one address) ---- */ - int q[16]; - for (unsigned s = 0; s < 16; s++) q[s] = V128(e); - int tokA = V(e), dqa = V(e); - if (e->err) return -1; - { - int g = V(e), hg = V(e), tp = V(e), tpm = V(e), c5 = V(e), ad64 = V64(e); if (e->err) return -1; - shr(e, g, lane, 2); - movi(e, R(c5), SH.group - 1u); - imadi(e, R(t1), R(g), 0xffffffffu, c5); /* group-1 - g */ - shr(e, t2, t1, 31); /* 1 when g > group-1 */ - imadr(e, hg, t2, t1, g); /* min(g, group-1) */ - shr(e, t1, warp, 1); - imadi(e, R(tokA), R(t1), 2u, cxw); /* the tile's first chunk token */ - shr(e, tp, tokA, 1); - /* token pair clamped to the last written one: tpm = (mc - 1) >> 1; tp = min(tp, tpm) */ - imadi(e, R(tpm), R(one), 0xffffffffu, mc); shr(e, tpm, tpm, 1); - imadi(e, R(t1), R(tp), 0xffffffffu, tpm); /* tpm - tp */ - shr(e, t2, t1, 31); imadr(e, tp, t2, t1, tp); - imadi(e, R(t1), R(tp), SH.kvh, cy); imadi(e, R(t1), R(t1), SH.group, hg); imadi(e, R(t1), R(t1), 1024u, NOREG); - andi(e, R(t2), R(lane), 3u); imadi(e, R(t1), R(t2), 16u, t1); - imadw(e, ad64, t1, 1u, pqf); - for (unsigned s = 0; s < 16; s++) ldg_wide(e, BW_IR_LDG_E_128, q[s], ad64, s * 64u, udesc, s == 0); - iadd(e, dqa, pos0, tokA); /* row-A position - kb (kb = 0) */ - } - - /* ---- main loop state ---- */ - int o[16], sc[4], kf[2], pp, vf[4]; - for (unsigned i = 0; i < 16; i++) o[i] = V128(e); - int mA = V(e), mB = V(e), lA = V(e), lB = V(e), gK = V64(e), gV = V64(e), sKb = V(e), sVb = V(e); - int lane16 = V(e), vfb = V(e), negc = V(e); - if (e->err) return -1; - { - int ka = V(e), c = V(e), tq = V(e); if (e->err) return -1; - /* blocks: kend = pos0 + nk - 1; nblk = kend / 16 + 1 */ - iadd(e, t1, pos0, nk); imadi(e, R(t1), R(one), 0xffffffffu, t1); shr(e, t1, t1, 4); imadi(e, R(cnt), R(one), 1u, t1); - shr(e, ka, tid, 5); andi(e, R(c), R(tid), 31u); - /* staging pointers: K units (key ka + 8i, chunk c), V unit (keys 2ka, 2ka + 1, chunk c) */ - imadi(e, R(t1), R(c), 16u, NOREG); - imadw(e, gK, cyk, 1u, pkc); imadw(e, gK, ka, 512u, gK); imadw(e, gK, t1, 1u, gK); - imadw(e, gV, cyk, 1u, pvc); imadw(e, gV, ka, 1024u, gV); imadw(e, gV, t1, 1u, gV); - /* sKb = (c>>1)*512 + ka*64 + (c&1)*4 (+ t'*16 for word t', + i*8 for key ka + 8i) */ - shr(e, t1, c, 1); imadi(e, R(sKb), R(t1), 512u, NOREG); - imadi(e, R(sKb), R(ka), 64u, sKb); - andi(e, R(t2), R(c), 1u); imadi(e, R(sKb), R(t2), 4u, sKb); - /* sVb = SM_V + (c>>1)*512 + (ka&3)*16 + ((c&1)*2 + (ka>>2))*4 (+ j*64 for dim 8c + j) */ - shr(e, t1, c, 1); imadi(e, R(sVb), R(t1), 512u, NOREG); - andi(e, R(t1), R(ka), 3u); imadi(e, R(sVb), R(t1), 16u, sVb); - shr(e, tq, ka, 2); imadi(e, R(t1), R(t2), 2u, tq); 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), 4096u, lane16); imadi(e, R(vfb), R(one), SM_V, vfb); - } - for (unsigned i = 0; i < 16; 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[2], va4 = V128(e), vb4 = V128(e); - for (unsigned i = 0; i < 2; i++) kq4[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); - kf[0] = V128(e); kf[1] = V128(e); pp = 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 */ - /* ---- stage the block ---- */ - ldg_wide(e, BW_IR_LDG_E_128, kq4[0], gK, 0, udesc, 1); - ldg_wide(e, BW_IR_LDG_E_128, kq4[1], gK, 8u * 512u, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, va4, gV, 0, udesc, 0); - ldg_wide(e, BW_IR_LDG_E_128, vb4, gV, 512u, udesc, 0); - for (unsigned i = 0; i < 2; i++) for (unsigned k = 0; k < 4; k++) { imadi(e, R(sa), R(one), i * 8u + 16u * k, sKb); sts32(e, sa, S(kq4[i], k)); } - for (unsigned k = 0; k < 4; k++) { - andi(e, R(t1), S(va4, k), 0xffffu); imadi(e, R(ev), S(vb4, k), 65536u, t1); - shrs(e, t1, S(va4, k), 16); andi(e, R(t2), S(vb4, k), 0xffff0000u); iadd(e, od, t1, t2); - imadi(e, R(sa), R(one), (2u * k) * 64u, sVb); sts32(e, sa, R(ev)); - imadi(e, R(sa), R(one), (2u * k + 1u) * 64u, sVb); sts32(e, sa, R(od)); - } - bar_sync(e); - - /* ---- S = Q K^T: 16 k-steps x 2 key tiles, even / odd k-steps into separate accumulators, K fragments - * double-buffered on scoreboards 3/4 ---- */ - lds_pf(e, kf[0], lane16, SM_K, 3); - consume(e, 3); - for (unsigned s = 0; s < 16; s++) { - const unsigned cur = s & 1u, nx = cur ^ 1u, sbn = 3u + nx, a = (s & 1u) * 2u; - if (s < 15) lds_pf(e, kf[nx], lane16, SM_K + (s + 1u) * 512u, sbn); - hmma(e, sc[a], q[s], kf[cur], 0, s >= 2 ? sc[a] : NOREG, 8); - hmma(e, sc[a + 1], q[s], kf[cur], 2, s >= 2 ? sc[a + 1] : NOREG, 8); - if (s < 15) consume(e, sbn); - } - nop(e, 15); nop(e, 14); - for (unsigned k = 0; k < 4; k++) { fadd(e, S(sc[0], k), S(sc[0], k), S(sc[2], k)); fadd(e, S(sc[1], k), S(sc[1], k), S(sc[3], k)); } - - /* ---- causal mask: key kb + 8j + 2t + (k&1) > row position (row A for k < 2, A + 1 for k >= 2) ---- */ - if (MUT != 1) { - imadi(e, R(t1), R(one), 0xfffffff1u, dqa); shr(e, t1, t1, 31); /* 1 when kb + 15 > 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 < 2; 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)); - fmaxx(e, R(mxA), R(mxA), S(sc[1], 0)); fmaxx(e, R(mxA), R(mxA), S(sc[1], 1)); - fmaxx(e, R(mxB), R(mxB), S(sc[1], 2)); fmaxx(e, R(mxB), R(mxB), S(sc[1], 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 < 2; 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 < 2; 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 < 2; 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 != 2) for (unsigned i = 0; i < 16; i++) for (unsigned k = 0; k < 4; k++) fmul(e, S(o[i], k), S(o[i], k), R(k < 2 ? alA : alB)); - f2fp(e, S(pp, 0), S(sc[0], 1), S(sc[0], 0)); f2fp(e, S(pp, 1), S(sc[0], 3), S(sc[0], 2)); - f2fp(e, S(pp, 2), S(sc[1], 1), S(sc[1], 0)); f2fp(e, S(pp, 3), S(sc[1], 3), S(sc[1], 2)); - - /* ---- O += P V: one k-step (16 keys) x 16 dim tiles of this warp's 128 dims, in two rounds of 4 fragments ---- */ - for (unsigned r = 0; r < 2; r++) { - for (unsigned np = 0; np < 4; np++) lds128(e, vf[np], vfb, (r * 4u + np) * 512u, np == 0); - for (unsigned np = 0; np < 4; np++) { - const unsigned n = 2u * (4u * r + np); - hmma(e, o[n], pp, vf[np], 0, o[n], 8); hmma(e, o[n + 1], pp, vf[np], 2, o[n + 1], 8); - } - } - imadw(e, gK, one, 16u * 512u, gK); imadw(e, gV, one, 16u * 512u, gV); - imadi(e, R(dqa), R(one), 0xfffffff0u, 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: rows g < 6 (a lane-divergent region), tokens < mc (warp-uniform) ---- */ - 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), c6 = V(e); - if (e->err) return -1; - ldc64(e, pout, OMEGA_PATTN256_ARG_OUT); ldc32(e, osc, OMEGA_PATTN256_ARG_OUT_SCALE); ldc32(e, emc, OMEGA_PATTN256_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), OMEGA_PATTN256_TOKENS, 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 < 16; i++) for (unsigned k = 0; k < 4; k++) fmul(e, S(o[i], k), S(o[i], k), R(k < 2 ? lA : lB)); - /* out + ((etok*qh + cy*group + g)*256 + (warp&1)*128 + 2t)*4 */ - shr(e, g, elane, 2); andi(e, R(tq), R(elane), 3u); - imadi(e, R(t1), R(etok), SH.qh, NOREG); imadi(e, R(t1), R(ecy), SH.group, t1); iadd(e, t1, t1, g); imadi(e, R(t1), R(t1), 1024u, NOREG); - andi(e, R(t2), R(ewarp), 1u); imadi(e, R(t1), R(t2), 512u, t1); imadi(e, R(t1), R(tq), 8u, t1); - imadw(e, po, t1, 1u, pout); - movi(e, R(c6), SH.group); - isetp_ge_u32(e, g, c6); - Region rg = region_skip_if_p0(e); - 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 < 16; i++) { - const uint32_t off = row * SH.out_words * 4u + i * 32u; - stg(e, po, off, S(o[i], 2 * row), udesc); stg(e, po, off + 4u, S(o[i], 2 * row + 1), udesc); - } - patch_bra(e, b, here(e)); - } - region_end(e, rg); - } - tail(e); - if (e->err) return -1; - if (omega_bw_regalloc_solve(prog) != 0) return -1; - return 0; -} - -int omega_prefill_attn256_prog_stats(const OmegaPrefillAttn256Spec *spec, uint32_t *insns, uint32_t *gprs, uint32_t *placeholders) { - static BlackwellIRProgram p; - if (omega_blackwell_codegen_prefill_attn256_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_pattn256.h b/src/omega_blackwell_codegen_pattn256.h deleted file mode 100644 index c910401b6..000000000 --- a/src/omega_blackwell_codegen_pattn256.h +++ /dev/null @@ -1,77 +0,0 @@ -#ifndef OMEGA_BLACKWELL_CODEGEN_PATTN256_H -#define OMEGA_BLACKWELL_CODEGEN_PATTN256_H -/* - * omega_blackwell_codegen_pattn256: causal prefill attention for Qwen3.8-27B on tensor cores (omega-mv#545, - * 2026-10-18): head_dim 256, 24 query heads over 4 KV heads (6 per KV head), the decode attention's cache - * (omega_gpu_decode_attn256_api.h). A derivative of omega_blackwell_codegen_pattn.h (the 30B's head_dim 128 kernel, - * untouched). Two launches per call (omega_gpu_prefill_attn256_api.h): - * - * prep the decode kernel's prologue in prep mode (OmegaDecodeAttn256Spec.prep): per token, q' = RoPE(RMSNorm(q) - * * q_norm) * qk_scale as bf16 into the QF buffer below, and k_new / v_new into the cache rows with the - * decode step's own instruction sequence (so the rows a prompt leaves are the rows m decode steps leave). - * attend this kernel: grid (ceil(m / 8), 4), 8 warps. CTA (cx, cy) serves KV head cy and the chunk tokens - * cx*8 .. cx*8+7. Row tile = 16 rows: row g (0..7) = token 2*tile, head cy*6 + min(g, 5); row g + 8 = the - * next token, same head (rows 6, 7 repeat head 5 and are never stored: a quarter of the tensor-core work of - * this first cut is spent on them). Warp w: tile w >> 1, output dims 128*(w & 1) .. +127. Both warps of a - * tile compute its scores (16 k-steps; Q's 16 A fragments = 64 registers, loaded once). - * Main loop over key blocks of 16 (kb = 0, 16, .. <= kend = pos0 + nk - 1, nk = min(cx*8 + 8, m)): 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 - * (8 KiB each), S = Q K^T (HMMA.16816.F32.BF16, four accumulators), 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. - * Epilogue: l summed over the quad, out = O * RCP(l) * out_scale for rows g < 6 and tokens < m. - * - * Keys past kend in the last block are read from the cache (rows the prompt has not reached) and masked; the cache - * is zero at allocation and only ever holds finite K/V rows, so 0 * row stays 0 in P V. - * Registers: the program opts into BW_PHYS_GPR_HW_LIMIT (omega_bw_ir_set_gpr_limit); 256 threads x the declared - * count must stay <= 65536 (the launcher checks). Shared memory: 16 KiB, the QMD cap. - * The host simulator (tests/bw_warp_sim_pa.h) runs both launches; a simulator pass is never a chip result. - */ -#include "omega_blackwell_codegen.h" -#include - -#define OMEGA_PATTN256_WARPS 8u -#define OMEGA_PATTN256_THREADS 256u -#define OMEGA_PATTN256_TOKENS 8u /* tokens per CTA */ -#define OMEGA_PATTN256_KEYS 16u /* keys per main-loop block */ -#define OMEGA_PATTN256_SHARED_BYTES 16384u /* K block 8 KiB + V block 8 KiB (the QMD cap) */ -#define OMEGA_PATTN256_OUT_WORDS 6144u /* f32 per token row of the output (24 heads x 256) */ - -/* QF: q' bf16 in A-fragment order. For token pair tp = tok >> 1, KV head c, head g of the group (0..5), k-step s - * (dims 16s .. 16s+15) and quad lane t (0..3), 16 bytes at QF_OFF(tp, c, g, s, t) hold the four A registers - * {a0, a1, a2, a3} = {(tok 2tp, dims 16s+2t, +1), (tok 2tp+1, same), (tok 2tp, dims 16s+8+2t, +1), (tok 2tp+1, same)}, - * each register = bf16 of the lower dim in the low half. */ -#define OMEGA_PATTN256_QF_PAIR_BYTES 24576u /* one token pair, all 4 KV heads */ -#define OMEGA_PATTN256_QF_OFF(tp, c, g, s, t) OMEGA_PATTN256_QF_OFF_SHAPE(4u, 6u, tp, c, g, s, t) -/* the same layout at kvh KV heads of grp query heads each */ -#define OMEGA_PATTN256_QF_OFF_SHAPE(kvh, grp, tp, c, g, s, t) \ - ((((((uint64_t)(tp) * (kvh) + (c)) * (grp) + (g)) * 16u + (s)) * 4u + (t)) * 16u) - -/* constant bank 0 at 0x380 */ -#define OMEGA_PATTN256_ARG_QF 0x380u /* bf16 QF, ceil(m / 2) token pairs */ -#define OMEGA_PATTN256_ARG_KC 0x388u /* bf16 K plane base of the layer [kv_head][max_pos][256] */ -#define OMEGA_PATTN256_ARG_VC 0x390u /* bf16 V plane base */ -#define OMEGA_PATTN256_ARG_OUT 0x398u /* f32 [m][6144] (token-major, head h at h * 256, model dim order) */ -#define OMEGA_PATTN256_ARG_POS0 0x3a0u /* u32 position of chunk token 0 */ -#define OMEGA_PATTN256_ARG_MC 0x3a4u /* u32 tokens, >= 1 */ -#define OMEGA_PATTN256_ARG_KV_STRIDE 0x3a8u /* u32 bytes per KV head plane (max_pos * 512) */ -#define OMEGA_PATTN256_ARG_OUT_SCALE 0x3acu /* f32 */ -#define OMEGA_PATTN256_ARGS_WORDS 12u - -typedef struct { - int mutant; /* TEST ONLY. 0 none; 1 no causal mask; 2 O is never rescaled by alpha. Each must be caught. */ - uint32_t q_heads, kv_heads; /* 0 = the 27B (24, 4). Grid y = kv_heads; q_heads / kv_heads (1..8) heads per CTA, - * the tile rows past the group repeat its last head and are never stored (Q36: 16, 2). */ -} OmegaPrefillAttn256Spec; - -/* Shape of one spec: the QF layout is QF_OFF with c < kv and g < group, a token pair = q * 1024 bytes. */ -typedef struct { uint32_t qh, kvh, group, out_words, qf_pair_bytes; } OmegaPattn256Shape; -int omega_pattn256_shape(const OmegaPrefillAttn256Spec *spec, OmegaPattn256Shape *s); - -int omega_pattn256_spec_ok(const OmegaPrefillAttn256Spec *spec); -/* Builds the register-allocated IR program. 0 ok, -1 refused or over BW_MAX_IR_INSNS / BW_MAX_VREGS / the registers. */ -int omega_blackwell_codegen_prefill_attn256_prog(const OmegaPrefillAttn256Spec *spec, BlackwellIRProgram *prog); -/* Instruction, peak-register and placeholder counts (host, no device). */ -int omega_prefill_attn256_prog_stats(const OmegaPrefillAttn256Spec *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 25e0f54ff..000000000 --- a/src/omega_blackwell_codegen_pf.c +++ /dev/null @@ -1,38 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 f4a126d3e..000000000 --- a/src/omega_blackwell_codegen_pf.h +++ /dev/null @@ -1,38 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 50883404e..000000000 --- a/src/omega_blackwell_codegen_pfhost.c +++ /dev/null @@ -1,161 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 02bcef486..000000000 --- a/src/omega_blackwell_codegen_pfhost.h +++ /dev/null @@ -1,64 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 c35bd4758..000000000 --- a/src/omega_blackwell_codegen_qg.c +++ /dev/null @@ -1,292 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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) { - if (!s || s->k < 128u || s->k > 32768u || s->k % 128u) return 0; - const uint32_t kb = s->k / 128u, g = s->groups ? s->groups : kb; - return g <= 32u && kb % g == 0 && s->in_type <= OMEGA_QG_IN_BF16 && s->mutant >= 0 && s->mutant <= 3; -} - -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); - if (spec->groups) { /* row split over ctaid.y: this CTA's groups start at y G */ - int cy = V(e); if (e->err) return -1; - s2r(e, cy, BW_SR_CTAID_Y); if (spec->mutant != 3) imadi(e, tid, cy, 0, 32u * spec->groups, tid); - } - 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 > 32768u || s->k % 128u) return 0; /* the k loop counts at run time: no k-sized immediate */ - 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->epi == OMEGA_QG_EPI_F32 ? 4u : 1u) * s->n * 16u * s->rt >= (1u << 23)) return 0; /* row stride (n f32, or n / 2 bf16 = n bytes) x 16 rt: the store offsets fit the signed 24-bit field */ - 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 872eabf96..000000000 --- a/src/omega_blackwell_codegen_qg.h +++ /dev/null @@ -1,86 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 (k <= 4096). - * groups G > 0 (any k <= 32768, G <= 32 dividing k / 128): a row spans k / (128 G) CTAs along ctaid.y, 32 G threads each; - * CTA y covers groups yG .. yG+G-1 (thread index offset by 32 G y). groups 0 is the one-CTA form (programs unchanged). - * Arguments (cbank 0x380): x u64, q u64, s u64. - * mutant (tests only): 1 skips the butterfly (lane-local amax), 2 uses c = 0, 3 drops the ctaid.y offset (groups form). - */ -#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; uint32_t groups; } 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 .. 32768 */ - 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 388c162f7..000000000 --- a/src/omega_blackwell_codegen_qmma.c +++ /dev/null @@ -1,154 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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++; - } - if (n > 0) { size_t b = omega_bw_program_code_bytes(prog); omega_kernel_dump(code, b && b <= len ? b : prog->count * 16u); } /* the patched body is a different kernel */ - 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 757bc0bc8..000000000 --- a/src/omega_blackwell_codegen_qmma.h +++ /dev/null @@ -1,65 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 0fab8c4eb..000000000 --- a/src/omega_blackwell_codegen_router.c +++ /dev/null @@ -1,468 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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_router_smem(const OmegaRouterSpec *spec, OmegaRouterSmem *m) { - const uint32_t ex = spec->experts ? spec->experts : OMEGA_ROUTER_EXPERTS; - if ((ex != 128u && ex != 256u) || spec->shared > 1u) return -1; - if (ex == OMEGA_ROUTER_EXPERTS && !spec->shared) { - m->logit = OMEGA_ROUTER_SM_LOGIT; m->red = OMEGA_ROUTER_SM_RED; m->bc = OMEGA_ROUTER_SM_BC; - m->sel = OMEGA_ROUTER_SM_SEL; m->selv = OMEGA_ROUTER_SM_SELV; m->total = OMEGA_ROUTER_SHARED_BYTES; - return 0; - } - m->logit = OMEGA_ROUTER_SM_XN + OMEGA_ROUTER_HIDDEN * 4u; - m->red = m->logit + (((ex + spec->shared) * 4u + 15u) & 0xfffffff0u); - m->bc = m->red + 128u; m->sel = m->bc + 16u; m->selv = m->sel + 48u; m->total = m->selv + 32u; - return 0; -} - -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; - OmegaRouterSmem L; - const uint32_t XST = spec->xstride, LBST = spec->lbstride; /* ROWS form when set */ - if ((W != 8 && W != 16 && W != 32) || (D != 1 && D != 2 && D != 4 && D != 8) || MUT < 0 || MUT > 6 || omega_router_smem(spec, &L)) return -1; - if ((XST != 0) != (LBST != 0) || (XST && (XST < OMEGA_ROUTER_HIDDEN * 4u || (XST & 15u) || (LBST & 15u))) || (MUT == 6 && !XST)) return -1; - const uint32_t EX = spec->experts ? spec->experts : OMEGA_ROUTER_EXPERTS, SHX = spec->shared, EPL = EX / 32u; /* logits per lane */ - if (MUT == 5 && !SHX) 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); - if (XST) { /* ROWS form: this CTA's x row and output buffer */ - int cy = V(e); - if (e->err) return -1; - s2r(e, cy, BW_SR_CTAID_Y); - if (MUT != 6) imadw(e, px, cy, XST, px); - imadw(e, pxout, cy, LBST, pxout); - } - 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), L.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, L.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, EX + SHX); /* rows: the experts, then the shared gate */ - 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), L.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), vq2 = EPL > 4u ? V128(e) : -1, lane4 = V(e), ej[8], fj[8], 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 < EPL; j++) { ej[j] = V(e); fj[j] = V(e); } - if (e->err) return -1; -#define VQ(j) ((j) < 4u ? S(vq, (j)) : S(vq2, (j) - 4u)) - /* lane L holds logits EPL*L .. EPL*L + EPL-1 (the shared gate row, index EX, is never loaded here) */ - if (EPL == 4u) lds128(e, vq, lane16, L.logit, 1); - else { lds128(e, vq, lane32, L.logit, 1); lds128(e, vq2, lane32, L.logit + 16u, 0); } - imadi(e, R(lane4), R(lane), EPL, NOREG); - for (unsigned j = 0; j < EPL; 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, L.bc); movi(e, bc4, L.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), VQ(0u), VQ(1u)); - for (unsigned j = 2; j < EPL; j++) fmaxx(e, R(lm), R(lm), VQ(j)); - 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 < EPL; j++) { - ne_of(e, ne, 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), L.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), EX - 1u); /* 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), L.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 < EPL; j++) { - ne_of(e, ne, R(ej[j]), R(cm), t1, t2); - imadi(e, R(cj), R(ne), 0x80000000u, cneg); - fminn(e, VQ(j), 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)); - if (SHX) { movi(e, t1, EX); movi(e, sa, L.sel + 32u); lane0_sts(e, lane, one, sa, R(t1)); } /* slot 8: the shared expert */ - 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); - if (EPL == 4u) lds128(e, vq, lane16, L.logit, 1); - else { lds128(e, vq, lane32, L.logit, 1); lds128(e, vq2, lane32, L.logit + 16u, 0); } - movi(e, sa, L.selv); - lds32(e, R(m0), sa, 0); - for (unsigned j = 0; j < EPL; j++) { - fsub(e, R(ts), 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); - if (XST) { /* ROWS form: the outputs of this CTA's row (the directories are shared) */ - int cy = V(e); - if (e->err) return -1; - s2r(e, cy, BW_SR_CTAID_Y); - imadw(e, pids, cy, LBST, pids); imadw(e, pwts, cy, LBST, pwts); - imadw(e, ptgu, cy, LBST, ptgu); imadw(e, ptdn, cy, LBST, ptdn); - } - ldc32(e, ntk, OMEGA_ROUTER_ARG_NORM_TOPK); - movi(e, sa, L.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); } - if (SHX) { /* slot 8: sigmoid(shared gate) = RCP(1 + EX2(-l * log2 e)) */ - movi(e, sa, L.logit + EX * 4u); lds32(e, R(ts), sa, 1); - movi(e, t1, 0xBFB8AA3Bu); fmul(e, R(ts), R(ts), R(t1)); mufu(e, BW_IR_MUFU_EX2, R(ts), R(ts)); - movi(e, t1, 0x3f800000u); fadd(e, R(ts), R(ts), R(t1)); mufu(e, BW_IR_MUFU_RCP, R(ts), R(ts)); - if (MUT == 5) movi(e, ts, 0x3f800000u); - imadw(e, wa64, one, 32u, pwts); stg(e, BW_IR_STG_E, wa64, R(ts), udesc); - } - region_end(e, rg); - } - /* lanes 0..7 (0..8 with the shared slot): id_g and the two directory entries of id_g into the two group tables */ - if (SHX) movi(e, c8, OMEGA_ROUTER_TOPK + 1u); - 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), L.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 a149b630f..000000000 --- a/src/omega_blackwell_codegen_router.h +++ /dev/null @@ -1,117 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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). ROWS form (spec.xstride and spec.lbstride set; L312 stroke lever 2, the router - * once per layer for every conversation): grid 1 x rows, CTA cy reads the residual row at X + cy * xstride bytes and writes - * x', ids, weights and both tables at their pointers + cy * lbstride bytes (the directories are shared); every row is - * computed exactly as the plain kernel computes it alone. 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); 5 (shared only) the shared expert's - * weight is 1 instead of sigmoid(gate); 6 (ROWS form only) every CTA reads row 0's x (rows 1.. wrong). - * Mutant 6 must be caught by the rows parity test. */ - uint32_t experts; /* routed experts: 0 or 128 (the 30B), 256 (Qwen3.6-35B-A3B) */ - uint32_t shared; /* 0, or 1: the weight has one more row (the shared expert gate, row `experts`) that never - * enters the top-8 or the softmax; slot 8 of ids / weights / both tables is the shared expert: - * id = experts, weight = sigmoid(row . xn), directory[experts] (the directory has experts + 1 - * entries). */ - uint32_t xstride; /* 0: one row (grid_y 1). Else the ROWS form (with lbstride): bytes between consecutive x rows - * (>= 8192, a multiple of 16); CTA cy reads X + cy * xstride. */ - uint32_t lbstride; /* ROWS form: bytes between consecutive output buffers (a multiple of 16): CTA cy writes - * XOUT, IDS, WTS, TAB_GU and TAB_DN at + cy * lbstride. Both or neither of the strides are set. */ -} OmegaRouterSpec; - -/* Shared memory map of a spec (bytes); the OMEGA_ROUTER_SM_* constants are the 128 / no-shared case. */ -typedef struct { uint32_t logit, red, bc, sel, selv, total; } OmegaRouterSmem; -int omega_router_smem(const OmegaRouterSpec *spec, OmegaRouterSmem *m); /* 0 ok, -1 refused shape */ - -/* 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 6a882d7e1..000000000 --- a/src/omega_blackwell_codegen_tc.c +++ /dev/null @@ -1,358 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 > OMEGA_TCGEMM_MAX_K || 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++; - } - } - if (n > 0) { size_t b = omega_bw_program_code_bytes(prog); omega_kernel_dump(code, b && b <= len ? b : prog->count * 16u); } /* the patched body is a different kernel */ - 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 a27f71f81..000000000 --- a/src/omega_blackwell_codegen_tc.h +++ /dev/null @@ -1,120 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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. */ -#define OMEGA_TCGEMM_MAX_K 32768u /* the K loop runs KB = k / 128 iterations; nothing else grows with k (omega#541) */ -typedef struct { - uint32_t k; /* multiple of 128, 128 .. OMEGA_TCGEMM_MAX_K */ - 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 4feb021fb..000000000 --- a/src/omega_blackwell_codegen_tc2.c +++ /dev/null @@ -1,245 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 38d17fdd1..000000000 --- a/src/omega_blackwell_codegen_tc2.h +++ /dev/null @@ -1,73 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 6177d45ad..000000000 --- a/src/omega_blackwell_codegen_tern.c +++ /dev/null @@ -1,436 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 a9a7472cc..000000000 --- a/src/omega_blackwell_codegen_tern.h +++ /dev/null @@ -1,124 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 373a98cda..000000000 --- a/src/omega_blackwell_encoder.c +++ /dev/null @@ -1,126 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 9050a2f03..000000000 --- a/src/omega_blackwell_encoder.h +++ /dev/null @@ -1,43 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 8923ab0ea..000000000 --- a/src/omega_blackwell_engine.c +++ /dev/null @@ -1,679 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 31948b06a..000000000 --- a/src/omega_blackwell_engine.h +++ /dev/null @@ -1,71 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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_gates.c b/src/omega_blackwell_gates.c index 54ec7f769..998ed8f1a 100644 --- a/src/omega_blackwell_gates.c +++ b/src/omega_blackwell_gates.c @@ -558,19 +558,59 @@ static bool test_m18_gate5_instruction_sequencing(void) { return valid; } +/* Host provenance adapter only; authentication policy lives in seeded Omega. + * Proposed replacement: a bounded .om source scanner plus SHA-256 receipt unit, + * returning refusal on empty input, read errors, forbidden tokens or pin drift. */ +static bool canonical_stage_path(char *path, size_t capacity, const char *suffix) { + const char *stage = getenv("CUDAPP_STAGE"); + const char *out = getenv("OUT_DIR"); + char fallback[PATH_MAX]; + if (!stage || !stage[0]) { + int n = snprintf(fallback, sizeof fallback, "%s/cudapp", + out && out[0] ? out : "build"); + if (n < 0 || (size_t)n >= sizeof fallback) return false; + stage = fallback; + } + int n = snprintf(path, capacity, "%s/%s", stage, suffix); + return n >= 0 && (size_t)n < capacity; +} + +static bool canonical_stage_verified(FILE *receipt) { + /* Generic I/O only: the fresh JSON is authored by the seeded .om guard + * and receipt unit. Never deserialize/recreate its policy here. */ + FILE *child = popen("sh tools/cudapp-stage.sh --verify cudapp.lock " + "\"${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp}\"", "r"); + if (!child) return false; + unsigned char bytes[4096]; + size_t n; + bool nonempty = false, ok = true; + while ((n = fread(bytes, 1, sizeof bytes, child)) != 0) { + nonempty = true; + if (receipt && fwrite(bytes, 1, n, receipt) != n) ok = false; + } + if (ferror(child)) ok = false; + if (pclose(child) != 0) ok = false; + return nonempty && ok; +} + static bool test_m18_gate6_code_truth(void) { - FILE *f = fopen("src/omega_blackwell_codegen.c", "r"); + char path[PATH_MAX]; + if (!canonical_stage_verified(NULL) || + !canonical_stage_path(path, sizeof path, "source/src/omega_blackwell_codegen.c")) return false; + FILE *f = fopen(path, "r"); if (!f) return false; char line[512]; - bool has_static_table = false; + bool has_static_table = false, nonempty = false; while (fgets(line, sizeof(line), f)) { + nonempty = true; if (strstr(line, "MATMUL_INSTRUCTIONS") || strstr(line, "static const uint32_t MATMUL_CODE")) { has_static_table = true; break; } } - fclose(f); - return !has_static_table; + bool read_ok = !ferror(f); + if (fclose(f) != 0) read_ok = false; + return nonempty && read_ok && !has_static_table; } static bool test_m18_gate7_codegen_variation(void) { @@ -1004,17 +1044,28 @@ static bool test_m18_gate16_clean_clone(void) { fprintf(stderr, "%s\n", physics_err); return false; } - char command[4608]; - int len = snprintf(command, sizeof(command), - "root=$(git rev-parse --show-toplevel) && " - "rm -rf /tmp/omega_clean_m18 && " - "cp -r \"$root\" /tmp/omega_clean_m18 && " - "cd /tmp/omega_clean_m18 && " - "make OUT_DIR=build clean >/dev/null 2>&1 && " - "make -j OUT_DIR=build PHYSICS_DIR='%s' >/dev/null 2>&1 && " - "OMEGA_IN_CLEAN_CLONE=1 ./build/omegatool --run-m18-gates >/tmp/clean_clone_m18.log 2>&1", - physics_dir_resolved); - if (len < 0 || (size_t)len >= sizeof(command)) return false; + /* Resolve every inherited checkout/tool path before changing directories. + * The stage repository is the default canonical source, never a retired + * Omega duplicate or an unrelated sibling checkout. */ + const char command[] = + "root=$(git rev-parse --show-toplevel) && " + "PHYSICS_DIR=$(realpath -- \"${PHYSICS_DIR:-../physics}\") && " + "CUDAPP_STAGE=$(realpath -- \"${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp}\") && " + "if [ -z \"${CUDAPP_DIR:-}\" ]; then " + "IFS= read -r CUDAPP_DIR < \"$CUDAPP_STAGE/repository\"; fi && " + "CUDAPP_DIR=$(realpath -- \"$CUDAPP_DIR\") && " + "OMEGA_OMC=$(realpath -- \"${OMEGA_OMC:?}\") && " + "OMEGA_BRIDGE=$(realpath -- \"${OMEGA_BRIDGE:?}\") && " + "export PHYSICS_DIR CUDAPP_DIR CUDAPP_STAGE OMEGA_OMC OMEGA_BRIDGE && " + "sh tools/cudapp-stage.sh --verify cudapp.lock \"$CUDAPP_STAGE\" >/dev/null && " + "rm -rf /tmp/omega_clean_m18 && " + "cp -r \"$root\" /tmp/omega_clean_m18 && " + "cd /tmp/omega_clean_m18 && " + "make OUT_DIR=build clean >/dev/null 2>&1 && " + "make -j OUT_DIR=build PHYSICS_DIR=\"$PHYSICS_DIR\" " + "CUDAPP_DIR=\"$CUDAPP_DIR\" CUDAPP_STAGE=\"$CUDAPP_STAGE\" " + "OMEGA_OMC=\"$OMEGA_OMC\" OMEGA_BRIDGE=\"$OMEGA_BRIDGE\" >/dev/null 2>&1 && " + "OMEGA_IN_CLEAN_CLONE=1 ./build/omegatool --run-m18-gates >/tmp/clean_clone_m18.log 2>&1"; int rc = system(command); return (rc == 0); } @@ -1041,7 +1092,9 @@ static bool compute_file_sha256(const char *path, uint8_t digest[32], char hex[6 while ((n = fread(buf, 1, sizeof(buf), f)) > 0) { sha256_update(&ctx, buf, n); } - fclose(f); + bool read_ok = !ferror(f); + if (fclose(f) != 0) read_ok = false; + if (!read_ok) return false; sha256_final(&ctx, digest); for (int i = 0; i < 32; i++) { sprintf(&hex[i * 2], "%02x", digest[i]); @@ -1161,20 +1214,27 @@ static bool test_m18_gate18_receipt(void) { if (!compute_file_sha256(self_path, bin_digest, bin_hex)) return false; /* 5. Generate the SHA256SUMS manifest under the run-scoped evidence area. */ + char source_receipt_path[1024]; + if (omega_evidence_path("CUDAPP-SOURCE.json", source_receipt_path, + sizeof source_receipt_path) != 0) return false; + FILE *source_receipt = fopen(source_receipt_path, "w"); + if (!source_receipt) return false; + bool source_verified = canonical_stage_verified(source_receipt); + if (fclose(source_receipt) != 0) source_verified = false; + if (!source_verified) return false; + const char *canonical_files[] = { + "source/src/omega_blackwell_matmul.h", "source/src/omega_blackwell_matmul.c", + "source/src/omega_blackwell_codegen.h", "source/src/omega_blackwell_codegen.c", + "source/src/omega_blackwell_qmd.h", "source/src/omega_blackwell_qmd.c", + "source/src/omega_blackwell_submit.h", "source/src/omega_blackwell_submit.c", + "source/src/omega_blackwell_engine.h", "source/src/omega_blackwell_engine.c", + "pin", "observed", "source.tar", "hashes", "build/libcudapp.a" + }; const char *manifest_files[] = { - "src/omega_blackwell_matmul.h", - "src/omega_blackwell_matmul.c", - "src/omega_blackwell_codegen.h", - "src/omega_blackwell_codegen.c", - "src/omega_blackwell_qmd.h", - "src/omega_blackwell_qmd.c", - "src/omega_blackwell_submit.h", - "src/omega_blackwell_submit.c", - "src/omega_blackwell_engine.h", - "src/omega_blackwell_engine.c", "src/omega_blackwell_gates.h", "src/omega_blackwell_gates.c", "tools/omegatool.c", + source_receipt_path, self_path }; size_t num_files = sizeof(manifest_files) / sizeof(manifest_files[0]); @@ -1184,14 +1244,25 @@ static bool test_m18_gate18_receipt(void) { FILE *f_sums = fopen(sums_path, "w"); if (!f_sums) return false; + bool sums_ok = true; + for (size_t i = 0; i < sizeof canonical_files / sizeof canonical_files[0]; i++) { + char path[PATH_MAX], h[65]; + uint8_t d[32]; + if (!canonical_stage_path(path, sizeof path, canonical_files[i]) || + !compute_file_sha256(path, d, h) || + fprintf(f_sums, "%s cudapp/%s\n", h, canonical_files[i]) < 0) { + sums_ok = false; + break; + } + } for (size_t i = 0; i < num_files; i++) { uint8_t d[32]; char h[65]; - if (compute_file_sha256(manifest_files[i], d, h)) { - fprintf(f_sums, "%s %s\n", h, manifest_files[i]); - } + if (!compute_file_sha256(manifest_files[i], d, h) || + fprintf(f_sums, "%s %s\n", h, manifest_files[i]) < 0) sums_ok = false; } - fclose(f_sums); + if (fclose(f_sums) != 0) sums_ok = false; + if (!sums_ok) return false; /* 6. Compute manifest digest */ uint8_t manifest_digest[32]; diff --git a/src/omega_blackwell_matmul.c b/src/omega_blackwell_matmul.c deleted file mode 100644 index 28805cfe4..000000000 --- a/src/omega_blackwell_matmul.c +++ /dev/null @@ -1,205 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 2b612e679..000000000 --- a/src/omega_blackwell_matmul.h +++ /dev/null @@ -1,98 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 efcab9eee..000000000 --- a/src/omega_blackwell_qmd.c +++ /dev/null @@ -1,253 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 ab4ac3616..000000000 --- a/src/omega_blackwell_qmd.h +++ /dev/null @@ -1,87 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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: word 36 declares - * MIN_ and TARGET_SM_CONFIG_SHARED_MEM_SIZE 9 = 32 KB (mesa nak qmd.rs gv100_smem_size_to_hw: - * size_kb / 4 + 1; SM >= 120 configs 0, 8, 16, 32, 64, 100 KB, nouveau_device.c), and a CTA must fit - * the MIN config. Raised from 16 KiB for the bf16 GEMV at k 5120 (20 KiB of x, sc #642); above - * 32 KiB the MIN / TARGET fields must follow the size (not done yet: every launch keeps one word 36). */ - uint32_t shared_bytes; -} OmegaBlackwellQmdConfig; -#define OMEGA_BW_QMD_MAX_SHARED_BYTES 32768u - -/* 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 ab63ddb27..000000000 --- a/src/omega_blackwell_realize.c +++ /dev/null @@ -1,68 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 5e7d27f80..000000000 --- a/src/omega_blackwell_realize.h +++ /dev/null @@ -1,51 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 5efba9c2e..000000000 --- a/src/omega_blackwell_submit.c +++ /dev/null @@ -1,740 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 41b36dcc3..000000000 --- a/src/omega_blackwell_submit.h +++ /dev/null @@ -1,111 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 fd61cdd84..000000000 --- a/src/omega_bw_em.h +++ /dev/null @@ -1,161 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 13c2803a1..000000000 --- a/src/omega_bw_em_q.h +++ /dev/null @@ -1,34 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 a10e07a37..000000000 --- a/src/omega_bw_reconv.h +++ /dev/null @@ -1,99 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 2170d07a3..000000000 --- a/src/omega_gpu_attention_api.c +++ /dev/null @@ -1,1452 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 b20e4315e..000000000 --- a/src/omega_gpu_bf16_gemv_api.c +++ /dev/null @@ -1,338 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 */ -static int g_mask_mutant; /* TEST ONLY: the MASK form's mutant (4 = keep / drop inverted), other kernels untouched */ - -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(); } -void omega_gpu_bf16_test_set_mask_mutant(int m) { omega_gpu_session_lock(); g_mask_mutant = m; 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; -} - -static int prepare_spec(const OmegaBf16GemvSpec *spec) { - 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; -} -int omega_gpu_bf16_prepare(uint32_t k) { - OmegaBf16GemvSpec spec; uint32_t ctas; spec_for(k, &spec, &ctas); - return prepare_spec(&spec); -} -int omega_gpu_bf16_prepare_xbatch(uint32_t k, uint32_t xbatch, uint32_t ystride) { - if (xbatch <= 1u) return omega_gpu_bf16_prepare(k); - if (xbatch > OMEGA_BF16_MAX_XBATCH || ystride == 0) return OMEGA_GPU_BF16_BAD_ARGS; - OmegaBf16GemvSpec spec; uint32_t ctas; spec_for(k, &spec, &ctas); - spec.xbatch = xbatch; spec.ystride = ystride; - return prepare_spec(&spec); -} -/* the MASK kernel as gemv_core builds it (rows 1, mask 1), pinned: the exact head's record never compiles mid-token */ -int omega_gpu_bf16_prepare_mask(uint32_t k) { - OmegaBf16GemvSpec spec; uint32_t ctas; spec_for(k, &spec, &ctas); - spec.rows = 1; spec.mask = 1; - return prepare_spec(&spec); -} - -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, uint32_t xrows, uint32_t xbatch, uint32_t ystride, - uint64_t mask_hi, uint64_t mask_tau) { - 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; - if (xrows && (!rec || xrows > 65535u)) return OMEGA_GPU_BF16_BAD_ARGS; /* the ROWS form is record-only */ - OmegaBf16GemvSpec spec; uint32_t ctas; spec_for(k, &spec, &ctas); - if (xrows) spec.ystride = n; - const int masked = mask_hi != 0; - if (masked && (!rec || xrows || xbatch > 1u || !mask_tau)) return OMEGA_GPU_BF16_BAD_ARGS; /* the MASK form is record-only */ - if (masked) { spec.rows = 1; spec.mask = 1; if (g_mask_mutant) spec.mutant = g_mask_mutant; } /* one row per warp: each row's bits are the plain kernel's */ - if (xbatch > 1u) { /* XBATCH form (record-only): xbatch x rows share every weight read; y row m at y + m * ystride f32 */ - if (!rec || xrows || xbatch > OMEGA_BF16_MAX_XBATCH || ystride < n) return OMEGA_GPU_BF16_BAD_ARGS; - spec.xbatch = xbatch; spec.ystride = ystride; - } - 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_MASK_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; - args[8] = (uint32_t)mask_hi; args[9] = (uint32_t)(mask_hi >> 32); args[10] = (uint32_t)mask_tau; args[11] = (uint32_t)(mask_tau >> 32); - 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 = xrows ? xrows : 1u, - .num_elements = (size_t)n * (xrows ? xrows : xbatch > 1u ? xbatch : 1u), - .args = args, .n_args = masked ? OMEGA_BF16_MASK_ARGS_WORDS : 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, 0, 0, 0, 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, 0, 0, 0, 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, 0, 0, 0, 0, 0); -} - -/* ROWS form record path (sc #642 prefill): see the header. Caller holds omega_gpu_session_lock(). */ -int omega_gpu_bf16_gemv_rows_record(OmegaGpuCmdList *cl, const OmegaGpuBf16Tensor *t, uint32_t rows, uint64_t x_va, uint64_t y_va) { - if (!cl || rows == 0) return OMEGA_GPU_BF16_BAD_ARGS; - return gemv_core(t, NULL, NULL, NULL, NULL, cl, x_va, y_va, rows, 0, 0, 0, 0); -} - -/* MASK form record path (HUM L314 exact head): see the header. Caller holds omega_gpu_session_lock(). */ -int omega_gpu_bf16_gemv_mask_record(OmegaGpuCmdList *cl, const OmegaGpuBf16Tensor *t, uint64_t x_va, uint64_t y_va, uint64_t hi_va, uint64_t tau_va) { - if (!cl || !hi_va || !tau_va) return OMEGA_GPU_BF16_BAD_ARGS; - return gemv_core(t, NULL, NULL, NULL, NULL, cl, x_va, y_va, 0, 0, 0, hi_va, tau_va); -} -/* XBATCH form record path (the lm_head of several conversations in one stroke): see the header. Caller holds the lock. */ -int omega_gpu_bf16_gemv_xbatch_record(OmegaGpuCmdList *cl, const OmegaGpuBf16Tensor *t, uint32_t xbatch, uint64_t x_va, uint64_t y_va, uint32_t ystride) { - if (!cl || xbatch == 0) return OMEGA_GPU_BF16_BAD_ARGS; - if (xbatch == 1u) return gemv_core(t, NULL, NULL, NULL, NULL, cl, x_va, y_va, 0, 0, 0, 0, 0); - return gemv_core(t, NULL, NULL, NULL, NULL, cl, x_va, y_va, 0, xbatch, ystride, 0, 0); -} diff --git a/src/omega_gpu_bf16_gemv_api.h b/src/omega_gpu_bf16_gemv_api.h deleted file mode 100644 index 685201375..000000000 --- a/src/omega_gpu_bf16_gemv_api.h +++ /dev/null @@ -1,125 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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); -/* ROWS form (sc #642 prefill): `rows` token rows in one launch (grid_y = rows <= 65535); row r reads x_va + r * k f32 - * and writes y_va + r * n f32. Record-only; the kernel (spec.ystride = n) is cached per n like any other shape. */ -int omega_gpu_bf16_gemv_rows_record(struct OmegaGpuCmdList *cl, const OmegaGpuBf16Tensor *t, uint32_t rows, uint64_t x_va, uint64_t y_va); -/* MASK form (HUM L314 exact two-pass head; omega_blackwell_codegen_bf16.h): record-only, rows 1. Row r with - * hi[r] < *tau (hi_va: n f32, tau_va: one f32, both device) gets -inf in y; every other row gets the plain kernel's - * bits. Caller holds omega_gpu_session_lock(); the first call compiles into a free cache slot. */ -int omega_gpu_bf16_gemv_mask_record(struct OmegaGpuCmdList *cl, const OmegaGpuBf16Tensor *t, uint64_t x_va, uint64_t y_va, uint64_t hi_va, uint64_t tau_va); -/* XBATCH form (the 35B stroke: one lm_head read for several conversations): `xbatch` (1..OMEGA_BF16_MAX_XBATCH) x rows - * at x_va + m * k f32 share every weight read inside one CTA (every row staged in shared memory, so xbatch * k * 4 bytes - * must fit the launch descriptor's shared limit); y row m at y_va + m * ystride f32 (ystride >= n; the gap stays - * untouched). Row m equals the one-row result of its x bit for bit (the same FMA order). xbatch 1 is the plain launch. - * Record-only; the kernel (spec.xbatch, spec.ystride) is cached per (k, xbatch, ystride): pin it with prepare_xbatch. */ -int omega_gpu_bf16_gemv_xbatch_record(struct OmegaGpuCmdList *cl, const OmegaGpuBf16Tensor *t, uint32_t xbatch, uint64_t x_va, uint64_t y_va, uint32_t ystride); -int omega_gpu_bf16_prepare(uint32_t k); -int omega_gpu_bf16_prepare_mask(uint32_t k); /* build and pin the MASK kernel for width k (the exact head, serving) */ -int omega_gpu_bf16_prepare_xbatch(uint32_t k, uint32_t xbatch, uint32_t ystride); /* build and pin the XBATCH kernel (xbatch <= 1: prepare(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); -/* TEST ONLY: the MASK form alone under mutant m (4: rows with hi >= tau get -inf, the others the plain bits). 0 none. */ -void omega_gpu_bf16_test_set_mask_mutant(int m); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_cmdlist.c b/src/omega_gpu_cmdlist.c deleted file mode 100644 index 809243d34..000000000 --- a/src/omega_gpu_cmdlist.c +++ /dev/null @@ -1,530 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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) */ - uint64_t *wait_va; /* per launch: semaphore word of another list's launch to wait for before it (wait_for), 0 = none */ - uint64_t pending_wait;/* wait_for recorded, taken by the next add */ - uint32_t nwaits; /* launches with a wait (6 more words each) */ - const OmegaGpuCmdList *wait_other; /* the one list this list waits on (it must be the other list of the pair) */ - uint32_t wait_max; /* highest launch index of wait_other waited on */ - uint32_t gen; /* omega_gpu_session_recoveries() at create: a list from before a recovery is stale (C5) */ -}; - -static uint32_t g_latched; /* 1 + omega_gpu_session_recoveries() at the latch; 0 never latched (C5: a recovery lifts it) */ - -int omega_gpu_cmdlist_is_latched(void) { return __atomic_load_n(&g_latched, __ATOMIC_ACQUIRE) == omega_gpu_session_recoveries() + 1u ? 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; cl->pending_wait = 0; cl->nwaits = 0; cl->wait_other = NULL; cl->wait_max = 0; } } -/* C5: every handle of a list made before the latest session recovery belongs to the closed device */ -static int stale(const OmegaGpuCmdList *cl) { - if (cl->gen == omega_gpu_session_recoveries()) return 0; - omega_gpu_session_set_error("cmdlist: made before a session recovery (its buffers are gone): create a new list"); - return 1; -} -int omega_gpu_cmdlist_wait_for(OmegaGpuCmdList *cl, const OmegaGpuCmdList *other, uint32_t index) { - if (!cl || !other || cl == other || index >= other->n) { omega_gpu_session_set_error("cmdlist wait_for: another list and one of its launches"); return -1; } - if (stale(cl) || stale(other)) return -1; - if (cl->wait_other && cl->wait_other != other) { omega_gpu_session_set_error("cmdlist wait_for: a list waits on one other list only"); return -1; } - cl->wait_other = other; - if (index > cl->wait_max) cl->wait_max = index; - cl->pending_wait = other->sems.va + (uint64_t)index * 16u; - return 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->gen = omega_gpu_session_recoveries(); - 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); - cl->wait_va = omega_gpu_host_calloc(cap, sizeof *cl->wait_va); - int rc = cl->words && cl->indep && cl->wait_va ? 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->wait_va); - 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 (stale(cl)) 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->wait_va[cl->n] = cl->pending_wait; - if (cl->pending_wait) cl->nwaits++; - cl->pending_wait = 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, omega_gpu_session_recoveries() + 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_note_module_latch(); /* C5: so omega_gpu_session_recover lifts it even when the check launch completed */ - 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; -} - -/* One submission's method stream for launches [done, end) into cl->words, ending with the completion tail at marker_va. - * Shared by submit and submit_pair (L136) so both emit the same words. Returns the word count. */ -static size_t emit_chunk(OmegaGpuCmdList *cl, const OmegaGpuCmdListOpts *op, uint32_t done, uint32_t end, uint64_t marker_va) { - const OmegaGpuCmdListOpts o = *op; - uint32_t *pb = cl->words; - size_t n = 0; - memcpy(pb, SETUP_WORDS, sizeof SETUP_WORDS); n += 18; - for (uint32_t i = done; i < end; i++) { - if (cl->wait_va[i]) { - /* wait_for: host semaphore ACQUIRE (clc96f.h SEM_ADDR_LO 0x5c .. SEM_EXECUTE 0x6c, OPERATION_ACQUIRE 0, 32-bit - * payload; the omega-mv#580 ORDER_SEM words, chip-proven): this queue stops here until the other list's launch - * released DONE. Before the barrier, so the launch's cache invalidate comes after the wait. */ - const uint64_t va = cl->wait_va[i]; - pb[n++] = bw_mthd(0, 0x005c, 5); pb[n++] = (uint32_t)va; pb[n++] = (uint32_t)(va >> 32); - pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE; pb[n++] = 0; pb[n++] = 0; - } - if (o.skip_launch && i == (uint32_t)(o.skip_launch - 1)) continue; - /* the first launch of a submission gets the full barrier (CPU-written QMDs, code and banks before it), unless - * opts.first_barrier_none (C4 streams measurement: a WAIT_FOR_IDLE may also wait for another queue's grids) */ - const int indep = i != done && cl->indep[i]; /* marked independent: no barrier, overlaps the launch before it */ - /* a launch that waited (wait_for) always gets the full barrier: its invalidate must come after the wait */ - const OmegaGpuCmdListBarrier b = cl->wait_va[i] ? OMEGA_GPU_CMDLIST_BARRIER_WFI - : i == done ? (i == 0 && o.first_barrier_none ? OMEGA_GPU_CMDLIST_BARRIER_NONE : 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); - return n; -} - -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 (stale(cl)) return -1; - if (cl->nwaits) { omega_gpu_session_set_error("cmdlist submit: a list with waits (wait_for) runs only in a pair (submit_pair)"); 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) + (cl->nwaits ? 6u : 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); - const uint32_t end = (cl->n - done > room) ? done + room : cl->n; - uint32_t *pb = cl->words; - size_t n = emit_chunk(cl, &o, done, end, 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; -} - -/* L136: list a on the session queue and list b on extra queue 1, both in flight before either is waited. Each list gets - * the same prefix as submit (semaphores INIT, banks / QMDs / semaphores synced) and the same words (emit_chunk); b's - * completion markers sit at MARKER_OFF + PAIR_B_MARKER on the same uncached page. */ -#define PAIR_B_MARKER 0x80ull -static int pair_prep(const OmegaGpuPlatform *p, OmegaGpuCmdList *cl) { - uint32_t *sem = cl->sems.cpu; - for (uint32_t i = 0; i < cl->n; i++) sem[4 * i] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; - cl->stamped = 0; - return 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->sems.handle, 0, (uint64_t)cl->n * 16u) == OMEGA_GPU_PLAT_OK ? 0 : -1; -} - -static int pair_check(const OmegaGpuPlatform *p, OmegaGpuCmdList *cl, uint32_t nwords, uint64_t elapsed, uint64_t host, OmegaGpuCmdListStats *st) { - (void)p->sync_gpu_to_cpu(p->ctx, cl->sems.handle, 0, (uint64_t)cl->n * 16u); - const uint32_t *sem = cl->sems.cpu; - 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 = 1; st->words = nwords; 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 pair: a launch semaphore is not DONE (launch did not run)"); return -1; } - return 0; -} - -/* Uncertain completion of a pair: queue 1 may still run, so a nop on queue 0 proves nothing; latch the session directly. */ -static void pair_latch(const char *why) { - __atomic_store_n(&g_latched, omega_gpu_session_recoveries() + 1u, __ATOMIC_RELEASE); - omega_gpu_session_latch_uncertain(why); -} - -int omega_gpu_cmdlist_submit_pair(OmegaGpuCmdList *a, OmegaGpuCmdList *b, const OmegaGpuCmdListOpts *opts, OmegaGpuCmdListStats *sa, OmegaGpuCmdListStats *sb) { - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); - if (opts) o = *opts; - if (sa) { memset(sa, 0, sizeof *sa); sa->first_missing = -1; } - if (sb) { memset(sb, 0, sizeof *sb); sb->first_missing = -1; } - const OmegaGpuPlatform *p = omega_gpu_session_platform(); - if (!a || !b || a == b || a->n == 0 || b->n == 0 || !p) { omega_gpu_session_set_error("cmdlist pair: two distinct non-empty lists and a platform"); return -1; } - if (stale(a) || stale(b)) return -1; - for (int k = 0; k < 2; k++) { /* a wait must point into the other list of this pair, at a launch it still has */ - const OmegaGpuCmdList *me = k ? b : a, *peer = k ? a : b; - if (me->nwaits && (me->wait_other != peer || me->wait_max >= peer->n)) { - omega_gpu_session_set_error("cmdlist pair: a wait_for points outside the other list of this pair"); return -1; - } - } - if (o.mode != OMEGA_GPU_CMDLIST_PCAS || o.stamps || o.skip_launch) { omega_gpu_session_set_error("cmdlist pair: PCAS mode only, no stamps, no skip"); return -1; } - if (omega_gpu_cmdlist_is_latched() || omega_gpu_session_is_blocked()) { omega_gpu_session_set_error("cmdlist pair: latched"); return -1; } - OmegaGpuSession *s = omega_gpu_session_open(); - if (!s) return -1; - if (!s->marker.cpu || s->marker.size < MARKER_OFF + PAIR_B_MARKER + 0x20) { omega_gpu_session_set_error("cmdlist pair: session marker page"); return -1; } - OmegaGpuQueueHandle q1; - if (omega_gpu_session_extra_queue(1, &q1) != 0) return -1; /* names the refusing stage */ - 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); - /* one submission per list: both must fit their ring with the platform prefix (a q38 token is ~650 launches x 8 words) */ - const uint32_t prefix = omega_gpu_session_submit_prefix_words(); - const OmegaGpuCmdList *L[2] = { a, b }; - for (int k = 0; k < 2; k++) { - const uint32_t avail = L[k]->words_cap - 18u - TAIL_WORDS - 2u - STAMP_WORDS; - if (prefix > avail || (avail - prefix) / (L[k]->nwaits ? 14u : 8u) < L[k]->n) { omega_gpu_session_set_error("cmdlist pair: a list does not fit one submission"); return -1; } - } - if (pair_prep(p, a) || pair_prep(p, b)) { omega_gpu_session_set_error("cmdlist pair: sync_cpu_to_gpu"); return -1; } - const size_t na = emit_chunk(a, &o, 0, a->n, marker_va), nb = emit_chunk(b, &o, 0, b->n, marker_va + PAIR_B_MARKER); - volatile uint32_t *mk = (volatile uint32_t *)((uint8_t *)marker->cpu + MARKER_OFF); - mk[0] = 0; mk[4] = 0; mk[PAIR_B_MARKER / 4] = 0; mk[PAIR_B_MARKER / 4 + 4] = 0; - if (p->sync_cpu_to_gpu(p->ctx, a->qmds.handle, 0, (uint64_t)a->n * OMEGA_GPU_CMDLIST_QMD_BYTES) != OMEGA_GPU_PLAT_OK || - p->sync_cpu_to_gpu(p->ctx, b->qmds.handle, 0, (uint64_t)b->n * OMEGA_GPU_CMDLIST_QMD_BYTES) != OMEGA_GPU_PLAT_OK || - p->sync_cpu_to_gpu(p->ctx, marker->handle, MARKER_OFF, PAIR_B_MARKER + 0x20) != OMEGA_GPU_PLAT_OK) { - omega_gpu_session_set_error("cmdlist pair: sync qmd / marker"); return -1; - } - const uint64_t t0 = p->time_now_ns(p->ctx); - const uint64_t host = t0 - th0; - if (p->queue_submit(p->ctx, s->queue, a->words, (uint32_t)na) != OMEGA_GPU_PLAT_OK) { - omega_gpu_session_set_error("cmdlist pair: queue_submit (queue 0) refused"); return -1; /* nothing in flight */ - } - const int b_ok = p->queue_submit(p->ctx, q1, b->words, (uint32_t)nb) == OMEGA_GPU_PLAT_OK; - 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 && b_ok) w = wait_word(p, marker, PAIR_B_MARKER, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, timeout, spin); - if (w == WAIT_OK && b_ok) w = wait_word(p, marker, PAIR_B_MARKER + 0x10, OMEGA_BW_MARKER2_PAYLOAD, timeout, spin); - if (w != WAIT_OK) { pair_latch(w == WAIT_TIMED_OUT ? "cmdlist pair: marker wait timed out (latched)" : "cmdlist pair: marker poll refused (latched)"); return -1; } - (void)p->sync_gpu_to_cpu(p->ctx, marker->handle, MARKER_OFF, PAIR_B_MARKER + 0x20); - const uint64_t elapsed = p->time_now_ns(p->ctx) - t0; - (void)p->queue_retire(p->ctx, s->queue); - if (!b_ok) { omega_gpu_session_set_error("cmdlist pair: queue_submit (queue 1) refused"); return -1; } /* a completed and is retired */ - (void)p->queue_retire(p->ctx, q1); - const int ra = pair_check(p, a, (uint32_t)na, elapsed, host, sa), rb = pair_check(p, b, (uint32_t)nb, elapsed, host, sb); - return ra == 0 && rb == 0 ? 0 : -1; -} - -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 889bdd1e4..000000000 --- a/src/omega_gpu_cmdlist.h +++ /dev/null @@ -1,144 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 4096u -#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. */ - int first_barrier_none; /* C4 streams: no WAIT_FOR_IDLE + invalidate before launch 0 (the CPU-written code, banks and QMDs - must not sit in a stale cache line: fresh slots or unchanged contents). A WAIT_FOR_IDLE may also - wait for grids of another queue of the group; the streams test measures both. 0 = the barrier. */ -} 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). A list - * belongs to the device it was made on: after omega_gpu_session_recover, add / submit / wait_for refuse it (C5). */ -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); -/* L136 (roadblock R3): caller holds the lock. List a on the session queue and list b on extra queue 1 - * (omega_gpu_session_extra_queue; needs AIEN_OMEGA_GPU_CHANNELS >= 2 at device open), both submitted before either is - * waited, so the two may run at the same time. The lists must share no written buffer. PCAS mode, no stamps, each list in - * one submission. Both stats get the pair wall time (first submit to the last marker). 0 ok; -1 with the stage named; - * a marker timeout latches the session. */ -int omega_gpu_cmdlist_submit_pair(OmegaGpuCmdList *a, OmegaGpuCmdList *b, const OmegaGpuCmdListOpts *opts, OmegaGpuCmdListStats *sa, OmegaGpuCmdListStats *sb); -/* C4 events. Caller holds the lock. The next launch added to cl waits, on the chip, until launch `index` of list `other` - * (already added there) has completed: a host semaphore ACQUIRE on that launch's release semaphore (DONE), emitted - * before the launch's barrier, which is always the full WAIT_FOR_IDLE + invalidate (whatever the options say), so the - * launch reads what the other launch wrote. A list waits on one other list only, and a list with waits runs only in - * submit_pair with that list (submit refuses it; submit_pair refuses a wait outside the pair or past its launches). - * 0 ok, -1 (no such launch, a second other list, or a list made before a session recovery). */ -int omega_gpu_cmdlist_wait_for(OmegaGpuCmdList *cl, const OmegaGpuCmdList *other, uint32_t index); -/* 1 once a timeout latched this module, until omega_gpu_session_recover (C5). */ -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 3628a88fa..000000000 --- a/src/omega_gpu_code_alloc.h +++ /dev/null @@ -1,52 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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_attn256_api.c b/src/omega_gpu_decode_attn256_api.c deleted file mode 100644 index 77fc4ba1f..000000000 --- a/src/omega_gpu_decode_attn256_api.c +++ /dev/null @@ -1,360 +0,0 @@ -/* - * omega_gpu_decode_attn256_api.c: resident KV cache, RoPE table and launch for the head_dim 256 decode attention - * (omega-mv#544). A derivative of omega_gpu_decode_attn_api.c (see the header); the double-precision host reference - * lives in tests/gpu_decode_attn256_test.c so the library links without libm. Session use mirrors the 128 kernel: - * 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_attn256_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) -#define HD OMEGA_DATTN256_HEAD_DIM -#define RB OMEGA_DATTN256_ROW_BYTES -#define KVH OMEGA_DATTN256_KV_HEADS -#define OUTW OMEGA_DATTN256_OUT_WORDS - -struct OmegaGpuDecodeAttn256Cache { - uint32_t layers, max_pos, max_splits, rotary_dim; - OmegaDecodeAttn256Spec shape; /* q_heads / kv_heads / q_per_cta (0 = the 27B) */ - OmegaDattn256Shape sh; - double theta; - uint64_t plane_bytes; /* one K or V plane of a layer: 4 * max_pos * 512 + slack */ - OmegaGpuMem kv[OMEGA_GPU_DATTN256_MAX_LAYERS]; /* [K plane | V plane] per layer */ - OmegaGpuMem rope, norms, part, cnt, qkv, out; -}; - -typedef struct { - bool valid; - OmegaDecodeAttn256Spec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; -} Slot; - -static struct { - bool hooked; - Slot slot[3]; /* the decode kernel and the L369 multi-token prep and attend kernels */ - uint32_t depth, per_split; - int mutant, multi_mut; - OmegaGpuMem mpart, mcnt; /* L369 multi-token partials and counters, shared by every cache (launches run in order) */ -} g; -static int g_rec; /* 1 while a record call runs (lock held): kernel_for must not evict */ - -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.slot, 0, sizeof g.slot); memset(&g.mpart, 0, sizeof g.mpart); memset(&g.mcnt, 0, sizeof g.mcnt); } -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); } - -void omega_gpu_decode_attn256_set_depth(uint32_t depth) { omega_gpu_session_lock(); g.depth = depth; slot_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_decode_attn256_set_per_split(uint32_t per_split) { omega_gpu_session_lock(); g.per_split = per_split; omega_gpu_session_unlock(); } -void omega_gpu_decode_attn256_test_set_mutant(int mutant) { omega_gpu_session_lock(); g.mutant = mutant; slot_clear_locked(); omega_gpu_session_unlock(); } - -/* ---- host math ---- */ -void omega_dattn256_rope_row(uint32_t pos, double theta, uint32_t rotary_dim, float *row256) { - const uint32_t P = rotary_dim / 2u; - for (unsigned i = 0; i < 128; i++) { - if (i < P) { - double inv = omega_hostmath_pow(theta, -(double)(2 * i) / (double)rotary_dim), ang = (double)pos * inv, s, c; - omega_hostmath_sincos(ang, &s, &c); - row256[i] = (float)c; row256[128 + i] = (float)s; - } else { row256[i] = 1.0f; row256[128 + i] = 0.0f; } - } -} -/* ---- cache ---- */ -int omega_gpu_decode_attn256_cache_alloc(uint32_t layers, uint32_t max_pos, double rope_theta, uint32_t rotary_dim, OmegaGpuDecodeAttn256Cache **out) { - return omega_gpu_decode_attn256_cache_alloc_shape(layers, max_pos, rope_theta, rotary_dim, 0, 0, 0, out); -} - -int omega_gpu_decode_attn256_cache_alloc_shape(uint32_t layers, uint32_t max_pos, double rope_theta, uint32_t rotary_dim, uint32_t q_heads, - uint32_t kv_heads, uint32_t q_per_cta, OmegaGpuDecodeAttn256Cache **out) { - if (!out) return OMEGA_GPU_DATTN_BAD_ARGS; - OmegaDecodeAttn256Spec shape; memset(&shape, 0, sizeof shape); - shape.q_heads = q_heads; shape.kv_heads = kv_heads; shape.q_per_cta = q_per_cta; - OmegaDattn256Shape sh; - if (omega_dattn256_shape(&shape, &sh) || sh.vy > 16u) return OMEGA_GPU_DATTN_BAD_ARGS; - *out = NULL; - if (layers == 0 || layers > OMEGA_GPU_DATTN256_MAX_LAYERS || max_pos == 0 || max_pos > OMEGA_GPU_DATTN256_MAX_POS || max_pos % OMEGA_DATTN256_CHUNK || - !(rope_theta > 0) || rotary_dim < 2 || rotary_dim > HD || rotary_dim % 2) return OMEGA_GPU_DATTN_BAD_ARGS; - OmegaGpuDecodeAttn256Cache *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->rotary_dim = rotary_dim; - c->shape = shape; c->sh = sh; - c->max_splits = max_pos / OMEGA_DATTN256_CHUNK; - c->plane_bytes = (uint64_t)c->sh.kvh * max_pos * RB + OMEGA_DATTN256_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_DATTN256_ROPE_ROW_BYTES, &c->rope) != 0 || - omega_gpu_session_alloc((size_t)layers * 2 * HD * 4, &c->norms) != 0 || - omega_gpu_session_alloc((size_t)c->sh.vy * c->max_splits * OMEGA_DATTN256_PARTIAL_WORDS * 4, &c->part) != 0 || - omega_gpu_session_alloc(64, &c->cnt) != 0 || - omega_gpu_session_alloc((size_t)c->sh.qkv_words * 4, &c->qkv) != 0 || - omega_gpu_session_alloc((size_t)c->sh.out_words * 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_dattn256_rope_row(p, rope_theta, rotary_dim, r + (size_t)p * 256); - memset(c->cnt.cpu, 0, 64); - memset(c->norms.cpu, 0, (size_t)layers * 2 * HD * 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_attn256_cache_free(c); return rc; } - *out = c; - return OMEGA_GPU_DATTN_OK; -} -void omega_gpu_decode_attn256_cache_free(OmegaGpuDecodeAttn256Cache *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_attn256_set_norms(OmegaGpuDecodeAttn256Cache *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 * 2 * HD; - memcpy(n, q_norm, HD * 4); memcpy(n + HD, k_norm, HD * 4); - 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(OmegaGpuDecodeAttn256Cache *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) * RB); -} -int omega_gpu_decode_attn256_cache_write(OmegaGpuDecodeAttn256Cache *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 >= c->sh.kvh || 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 * RB); memcpy(row_ptr(c, layer, kv_head, pos, 1), v, (size_t)count * RB); - 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_attn256_cache_read(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t kv_head, uint32_t pos, uint16_t *k, uint16_t *v) { - if (!c || layer >= c->layers || kv_head >= c->sh.kvh || 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), RB); memcpy(v, row_ptr(c, layer, kv_head, pos, 1), RB); } - omega_gpu_session_unlock(); - return rc; -} - -/* ---- kernel ---- */ -static int kernel_for(const OmegaDecodeAttn256Spec *spec, Slot **out, bool *hit) { - Slot *s = NULL; - for (unsigned i = 0; i < 3; i++) if (g.slot[i].valid && memcmp(&g.slot[i].spec, spec, sizeof *spec) == 0) { *out = &g.slot[i]; *hit = true; return OMEGA_GPU_DATTN_OK; } - for (unsigned i = 0; i < 3 && !s; i++) if (!g.slot[i].valid) s = &g.slot[i]; - if (!s && g_rec) { omega_gpu_session_set_error("decode attn256 record: kernel cache miss would evict a resident kernel (warm up before recording)"); return OMEGA_GPU_DATTN_TOO_LARGE; } - if (!s) { slot_clear_locked(); s = &g.slot[0]; } - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) { omega_gpu_session_set_error("decode attn256 codegen: host memory"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } - int cg = omega_blackwell_codegen_decode_attn256_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 attn256 codegen refused the spec"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } - if ((uint64_t)OMEGA_DATTN256_CHUNK * gpr_declared(prog->regalloc.peak_gpr_usage) > 65536u) { omega_gpu_host_free(prog); omega_gpu_session_set_error("decode attn256: 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 attn256 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. */ -static int dattn_core(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos, const float *qkv, float eps, float out_scale, - float *out, OmegaGpuDecodeAttn256Info *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_DATTN256_PER_SPLIT; - if (per % OMEGA_DATTN256_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; - OmegaDecodeAttn256Spec spec; memset(&spec, 0, sizeof spec); - spec.depth = g.depth ? g.depth : OMEGA_GPU_DATTN256_DEPTH; spec.mutant = g.mutant; - spec.q_heads = c->shape.q_heads; spec.kv_heads = c->shape.kv_heads; spec.q_per_cta = c->shape.q_per_cta; - - 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)c->sh.qkv_words * 4); - for (size_t i = 0; i < c->sh.out_words; 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_DATTN256_ARGS_WORDS]; - const uint64_t kc = c->kv[layer].va, vc = kc + c->plane_bytes, nm = c->norms.va + (uint64_t)layer * 2 * HD * 4; - 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.0625 * 1.4426950408889634); /* log2(e) / sqrt(256) */ - 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 + HD * 4); 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 * RB); 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 = c->sh.vy; info->threads = OMEGA_DATTN256_CHUNK; - info->kv_bytes = 2ull * c->sh.kvh * (pos + 1ull) * RB; - 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_DATTN256_CHUNK, .threads_y = 1, .grid_x = splits, .grid_y = c->sh.vy, - .num_elements = (size_t)c->sh.out_words, - .args = args, .n_args = OMEGA_DATTN256_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = OMEGA_DATTN256_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 < c->sh.out_words; i++) if (od[i] == POISON_F32) unchanged++; - const uint32_t *cn = c->cnt.cpu; - uint32_t any = 0; - for (uint32_t i = 0; i < c->sh.vy; i++) any |= cn[i]; - if (unchanged) { omega_gpu_session_set_error("decode attn256: output poison survived"); rc = OMEGA_GPU_DATTN_CHIP_FAIL; } - else if (any) { omega_gpu_session_set_error("decode attn256: a split counter did not return to zero"); rc = OMEGA_GPU_DATTN_CHIP_FAIL; } - else memcpy(out, od, (size_t)c->sh.out_words * 4); - } - UNLOCK(); -#undef UNLOCK - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} - -int omega_gpu_decode_attn256_cache_view(const OmegaGpuDecodeAttn256Cache *c, uint32_t layer, OmegaGpuDecodeAttn256CacheView *v) { - if (!c || !v || layer >= c->layers) return OMEGA_GPU_DATTN_BAD_ARGS; - v->layers = c->layers; v->max_pos = c->max_pos; v->rotary_dim = c->rotary_dim; v->theta = c->theta; - 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 * 2 * HD * 4; v->k_norm_va = v->q_norm_va + HD * 4; - v->part_va = c->part.va; v->cnt_va = c->cnt.va; - v->q_heads = c->sh.qh; v->kv_heads = c->sh.kvh; v->q_per_cta = c->sh.h; v->qkv_words = c->sh.qkv_words; v->out_words = c->sh.out_words; - return OMEGA_GPU_DATTN_OK; -} - -int omega_gpu_decode_attn256(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos, const float *qkv, float eps, float out_scale, float *out, OmegaGpuDecodeAttn256Info *info) { - return dattn_core(c, layer, pos, qkv, eps, out_scale, out, info, NULL, 0, 0); -} - -int omega_gpu_decode_attn256_record(OmegaGpuCmdList *cl, OmegaGpuDecodeAttn256Cache *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); -} - -int omega_gpu_decode_attn256_counters_check(OmegaGpuDecodeAttn256Cache *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; - uint32_t any = 0; for (uint32_t i = 0; i < c->sh.vy; i++) any |= cn[i]; - if (any) { omega_gpu_session_set_error("decode attn256: a split counter did not return to zero"); return OMEGA_GPU_DATTN_CHIP_FAIL; } - return OMEGA_GPU_DATTN_OK; -} - -/* ---- L369 multi-token prompt attention ---- */ -#define MULTI_PART_BYTES (64ull << 20) -#define MULTI_MAX_TOKENS 128u -#define PB ((uint64_t)OMEGA_DATTN256_PARTIAL_WORDS * 4u) - -void omega_gpu_decode_attn256_test_set_multi_mutant(int mutant) { omega_gpu_session_lock(); g.multi_mut = mutant; omega_gpu_session_unlock(); } - -static void multi_spec(const OmegaGpuDecodeAttn256Cache *c, uint32_t prep, OmegaDecodeAttn256Spec *spec) { - memset(spec, 0, sizeof *spec); - spec->depth = g.depth ? g.depth : OMEGA_GPU_DATTN256_DEPTH; spec->mutant = g.mutant; spec->prep = prep; spec->multi = 1; - spec->q_heads = c->shape.q_heads; spec->kv_heads = c->shape.kv_heads; spec->q_per_cta = c->shape.q_per_cta; -} - -int omega_gpu_decode_attn256_multi_prepare(OmegaGpuDecodeAttn256Cache *c) { - if (!c || (c->sh.vy & (c->sh.vy - 1u))) return OMEGA_GPU_DATTN_BAD_ARGS; - omega_gpu_session_lock(); - int rc = dev_open_locked() ? OMEGA_GPU_DATTN_OK : OMEGA_GPU_DATTN_CHIP_FAIL; - if (rc == OMEGA_GPU_DATTN_OK && !g.mpart.cpu) { - if (omega_gpu_session_alloc((size_t)MULTI_PART_BYTES, &g.mpart) != 0 || omega_gpu_session_alloc((size_t)MULTI_MAX_TOKENS * 16u * 4u, &g.mcnt) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - else { memset(g.mcnt.cpu, 0, (size_t)MULTI_MAX_TOKENS * 16u * 4u); if (omega_gpu_session_sync_to_gpu(&g.mcnt) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; } - } - for (uint32_t prep = 0; prep < 2 && rc == OMEGA_GPU_DATTN_OK; prep++) { - OmegaDecodeAttn256Spec spec; multi_spec(c, prep, &spec); - Slot *s = NULL; bool hit = false; - rc = kernel_for(&spec, &s, &hit); - } - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_decode_attn256_multi_record(OmegaGpuCmdList *cl, OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t tokens, - uint64_t qkv_va, uint32_t xstride, float eps, float out_scale, uint64_t out_va, uint32_t ostride) { - if (!cl || !c || layer >= c->layers || tokens == 0 || pos0 >= c->max_pos || tokens > c->max_pos - pos0 || !qkv_va || !out_va || - xstride < c->sh.qkv_words * 4u || xstride % 16u || qkv_va % 16u || ostride < c->sh.out_words * 4u || ostride % 4u || !g.mpart.cpu) return OMEGA_GPU_DATTN_BAD_ARGS; - if ((g.per_split && g.per_split != OMEGA_DATTN256_CHUNK) || (c->sh.vy & (c->sh.vy - 1u))) return OMEGA_GPU_DATTN_BAD_ARGS; - Slot *sp = NULL, *sa = NULL; bool hit = false; - OmegaDecodeAttn256Spec spec; - g_rec = 1; - multi_spec(c, 1, &spec); int rc = kernel_for(&spec, &sp, &hit); - if (rc == OMEGA_GPU_DATTN_OK) { multi_spec(c, 0, &spec); rc = kernel_for(&spec, &sa, &hit); } - g_rec = 0; - if (rc != OMEGA_GPU_DATTN_OK) return rc; - uint32_t args[OMEGA_DATTN256_MULTI_ARGS_WORDS]; memset(args, 0, sizeof args); - const uint64_t kc = c->kv[layer].va, vc = kc + c->plane_bytes, nm = c->norms.va + (uint64_t)layer * 2 * HD * 4; - float fe = eps, fo = out_scale, fq = (float)(0.0625 * 1.4426950408889634); - 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(2, kc); A64(4, vc); A64(6, c->rope.va); A64(8, nm); A64(10, nm + HD * 4); A64(14, g.mpart.va); A64(16, g.mcnt.va); - args[19] = OMEGA_DATTN256_CHUNK; args[21] = (uint32_t)(c->max_pos * RB); args[22] = ue; args[23] = uo; args[24] = uq; - args[25] = xstride; args[26] = ostride; - /* prep: every token's K/V rows into the cache (TEST mutant 1: skipped, the chunk's own rows stay stale) */ - if (g.multi_mut != 1) { - A64(0, qkv_va); A64(12, out_va); args[18] = pos0; args[20] = 1; args[27] = 0; - OmegaGpuLaunch L = { .code_va = sp->code.va, .gpr_count = gpr_declared(sp->kernel.gpr_count), .threads_x = OMEGA_DATTN256_CHUNK, .threads_y = 1, - .grid_x = tokens, .grid_y = c->sh.vy, .num_elements = (size_t)tokens * c->sh.qkv_words, .args = args, - .n_args = OMEGA_DATTN256_MULTI_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, .shared_bytes = OMEGA_DATTN256_SHARED_BYTES }; - if (!omega_bw_gpr_declared_ok(L.gpr_count, sp->kernel.gpr_count) || omega_gpu_cmdlist_add(cl, &L) < 0) return OMEGA_GPU_DATTN_CHIP_FAIL; - } - /* attend: groups of tokens whose partials fit the shared buffer */ - for (uint32_t t0 = 0; t0 < tokens;) { - uint32_t n = tokens - t0 < MULTI_MAX_TOKENS ? tokens - t0 : MULTI_MAX_TOKENS; - while (n > 1 && (uint64_t)n * c->sh.vy * ((pos0 + t0 + n - 1) / OMEGA_DATTN256_CHUNK + 1) * PB > MULTI_PART_BYTES) n--; - const uint32_t smax = (pos0 + t0 + n - 1) / OMEGA_DATTN256_CHUNK + 1; - const uint64_t ps = (uint64_t)c->sh.vy * smax * PB; - if ((uint64_t)n * ps > MULTI_PART_BYTES) return OMEGA_GPU_DATTN_TOO_LARGE; - A64(0, qkv_va + (uint64_t)t0 * xstride); A64(12, out_va + (uint64_t)t0 * ostride); args[18] = pos0 + t0; args[20] = smax; args[27] = (uint32_t)ps; - OmegaGpuLaunch L = { .code_va = sa->code.va, .gpr_count = gpr_declared(sa->kernel.gpr_count), .threads_x = OMEGA_DATTN256_CHUNK, .threads_y = 1, - .grid_x = smax, .grid_y = n * c->sh.vy, .num_elements = (size_t)n * c->sh.out_words, .args = args, - .n_args = OMEGA_DATTN256_MULTI_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, .shared_bytes = OMEGA_DATTN256_SHARED_BYTES }; - if (!omega_bw_gpr_declared_ok(L.gpr_count, sa->kernel.gpr_count) || omega_gpu_cmdlist_add(cl, &L) < 0) return OMEGA_GPU_DATTN_CHIP_FAIL; - t0 += n; - } -#undef A64 - return OMEGA_GPU_DATTN_OK; -} diff --git a/src/omega_gpu_decode_attn256_api.h b/src/omega_gpu_decode_attn256_api.h deleted file mode 100644 index d0212c2cb..000000000 --- a/src/omega_gpu_decode_attn256_api.h +++ /dev/null @@ -1,135 +0,0 @@ -#ifndef OMEGA_GPU_DECODE_ATTN256_API_H -#define OMEGA_GPU_DECODE_ATTN256_API_H -/* - * omega_gpu_decode_attn256_api: one-launch decode attention for Qwen3.8-27B (omega-mv#544, 2026-10-18): head_dim 256, - * 24 query heads over 4 KV heads, partial RoPE by permutation. A derivative of omega_gpu_decode_attn_api.h (the 30B's - * head_dim 128 kernel, untouched); the kernel is described in omega_blackwell_codegen_attn256.h. Return codes and the - * bf16 helpers are shared with that API (OMEGA_GPU_DATTN_*, omega_dattn_bf16_rne). - * - * int omega_gpu_decode_attn256_cache_alloc(uint32_t layers, uint32_t max_pos, double rope_theta, uint32_t rotary_dim, - * OmegaGpuDecodeAttn256Cache **out); - * GPU-resident bf16 KV cache for `layers` layers of 4 KV heads x `max_pos` positions x 256 (one allocation per - * layer, 2 * 4 * max_pos * 512 bytes + slack), the RoPE table (f32 [max_pos][cos 128 | sin 128], built in double: - * pair j < rotary_dim / 2 rotates with inv_freq theta^(-2j / rotary_dim), the rest is identity), the per-layer - * q_norm / k_norm weights, the cross-split partials and counters. rotary_dim: even, 2..256 (64 for Qwen3.8-27B, - * 256 = full RoPE). Opens the session. The Qwen3.8-27B cache at 131072 positions is 512 MiB per layer. - * void omega_gpu_decode_attn256_cache_free(OmegaGpuDecodeAttn256Cache *c); - * int omega_gpu_decode_attn256_set_norms(c, layer, q_norm, k_norm): 256 f32 each, ALREADY folded to 1 + w (the model's - * zero-centred RMSNorm) and permuted with omega_dattn256_perm_vec. - * int omega_gpu_decode_attn256(c, layer, pos, qkv, eps, out_scale, out, info); - * qkv: f32 [8192] = q 24 heads x 256 (permuted dims, gate NOT included), then k 4 x 256 (permuted), then v 4 x 256 - * (NOT permuted); pos: the new token's position (< max_pos; positions 0..pos-1 already in the cache for that - * layer). Appends K/V at pos and writes out[24][256] * out_scale in the model's dim order (V and the output are - * never permuted). The gate (sigmoid of the second half of each head's q_proj rows) is applied by the caller. - * Returns OMEGA_GPU_DATTN_OK or an OMEGA_GPU_DATTN_* code; the chip failure text is in - * omega_gpu_decode_attn_last_error(). - * Test helpers: cache_write moves `count` consecutive bf16 K and V rows (256 each; K rows in permuted order) of a layer - * and KV head into the cache in one sync; cache_read returns one row of each. - * - * The permutation (design decision 1 of #544; rotary_dim R = 2P, P pairs; slot i of the kernel's head holds the model's - * dim omega_dattn256_perm_slot(i, R)): - * i < P: model dim i (first half of the rotated dims) - * P <= i < 128: model dim R + (i - P) (unrotated dims, in order) - * 128 <= i < 128+P: model dim P + (i - 128) (second half of the rotated dims: the partner of slot i - 128) - * 128+P <= i: model dim i (the rest of the unrotated dims) - * so the kernel's rotate-half pairs (i, i + 128), i < P, are exactly the model's pairs (j, j + P) and the table's - * identity pairs i >= P leave the other dims alone. R = 256 gives the identity permutation. q, k and the two norm - * weights are permuted; the K cache holds permuted rows; V and the output are not permuted. - * - * Launch shape: grid (splits, 4), 256 threads, splits = ceil((pos + 1) / per_split), per_split a multiple of 256. - * Every buffer is GPU-uncached host-visible session memory (nvos.h:1117 rule), launched through - * omega_gpu_session_launch. 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. - */ -#include "omega_blackwell_codegen_attn256.h" -#include "omega_gpu_decode_attn_api.h" -#include -#include - -#define OMEGA_GPU_DATTN256_PER_SPLIT 256u -#define OMEGA_GPU_DATTN256_MAX_LAYERS 64u -#define OMEGA_GPU_DATTN256_MAX_POS 131072u -#define OMEGA_GPU_DATTN256_DEPTH 4u - -typedef struct OmegaGpuDecodeAttn256Cache OmegaGpuDecodeAttn256Cache; - -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) * 512 */ - uint64_t elapsed_ns; /* marker-to-marker chip time */ - uint64_t call_ns; /* whole call */ - uint32_t completion_marker; - int kernel_cache_hit; -} OmegaGpuDecodeAttn256Info; - -int omega_gpu_decode_attn256_cache_alloc(uint32_t layers, uint32_t max_pos, double rope_theta, uint32_t rotary_dim, OmegaGpuDecodeAttn256Cache **out); -/* Q36 (sc L306): the same for another model shape (OmegaDecodeAttn256Spec.q_heads / kv_heads / q_per_cta; 0, 0, 0 = the 27B, - * the plain alloc). Qwen3.6-35B-A3B: 16, 2, 4. qkv rows are (q_heads + 2 kv_heads) * 256 f32, out q_heads * 256; the cache has - * kv_heads planes; partials and split counters one per CTA row (q_heads / q_per_cta <= 16). */ -int omega_gpu_decode_attn256_cache_alloc_shape(uint32_t layers, uint32_t max_pos, double rope_theta, uint32_t rotary_dim, uint32_t q_heads, - uint32_t kv_heads, uint32_t q_per_cta, OmegaGpuDecodeAttn256Cache **out); -void omega_gpu_decode_attn256_cache_free(OmegaGpuDecodeAttn256Cache *c); -int omega_gpu_decode_attn256_set_norms(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, const float *q_norm, const float *k_norm); -int omega_gpu_decode_attn256(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos, const float *qkv, float eps, - float out_scale, float *out, OmegaGpuDecodeAttn256Info *info); -/* Record path (decode graph; omega_gpu_cmdlist.h): the launch appended to cl instead of submitted. qkv_va: f32 [8192] on - * the device; out_va: f32 [24 * 256]. The caller holds omega_gpu_session_lock(). 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_attn256_record(struct OmegaGpuCmdList *cl, OmegaGpuDecodeAttn256Cache *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_attn256_counters_check(OmegaGpuDecodeAttn256Cache *c); -/* L369 multi-token prompt attention: tokens prompt tokens of one conversation at positions pos0 .. pos0 + tokens - 1 (qkv rows - * xstride bytes apart, outputs ostride bytes apart), every output bit-identical to `tokens` decode records in order. Records - * one prep launch (every token's K/V rows, the decode step's own instructions) and the attend launches (grid (splits, n * vy), - * groups of n tokens whose partials fit a shared 64 MiB buffer). per_split must be the default 256. multi_prepare builds the - * two kernels and the buffer (call before recording, outside the record lock). TEST: set_multi_mutant(1) drops the prep launch. */ -int omega_gpu_decode_attn256_multi_prepare(OmegaGpuDecodeAttn256Cache *c); -int omega_gpu_decode_attn256_multi_record(struct OmegaGpuCmdList *cl, OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t tokens, - uint64_t qkv_va, uint32_t xstride, float eps, float out_scale, uint64_t out_va, uint32_t ostride); -void omega_gpu_decode_attn256_test_set_multi_mutant(int mutant); -int omega_gpu_decode_attn256_cache_write(OmegaGpuDecodeAttn256Cache *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_attn256_cache_read(OmegaGpuDecodeAttn256Cache *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: device addresses only. */ -typedef struct { - uint32_t layers, max_pos, rotary_dim; - double theta; - uint64_t k_va, v_va; /* K and V plane bases of `layer` (row (kv_head, pos) at + (kv_head * max_pos + pos) * 512) */ - uint64_t rope_va; /* f32 [max_pos][cos 128 | sin 128] */ - uint64_t q_norm_va, k_norm_va; /* f32 [256] each for `layer` */ - uint64_t part_va, cnt_va; /* the cross-split partials and counters (prefill may reuse them) */ - uint32_t q_heads, kv_heads, q_per_cta; /* the cache's head shape, resolved (24 / 4 / 6 for the 27B) */ - uint32_t qkv_words, out_words; /* f32 per token row of the q|k|v input and of the output */ -} OmegaGpuDecodeAttn256CacheView; -int omega_gpu_decode_attn256_cache_view(const OmegaGpuDecodeAttn256Cache *c, uint32_t layer, OmegaGpuDecodeAttn256CacheView *out); - -/* ---- measurement knobs (tests; each clears the kernel cache) ---- */ -void omega_gpu_decode_attn256_set_depth(uint32_t depth); /* 0 = default (OMEGA_GPU_DATTN256_DEPTH) */ -void omega_gpu_decode_attn256_set_per_split(uint32_t per_split); /* 0 = default; multiple of 256 */ -void omega_gpu_decode_attn256_test_set_mutant(int mutant); /* TEST ONLY: OmegaDecodeAttn256Spec.mutant */ - -/* ---- host side ---- */ -/* RoPE table row for `pos`: cos[128] then sin[128], f32 from double; pairs j < rotary_dim/2 rotate with - * inv_freq[j] = theta^(-2j/rotary_dim), the rest are cos 1, sin 0 */ -void omega_dattn256_rope_row(uint32_t pos, double theta, uint32_t rotary_dim, float *row256); -/* the model dim held by kernel slot i (see above); rotary_dim even, 2..256 */ -static inline uint32_t omega_dattn256_perm_slot(uint32_t i, uint32_t rotary_dim) { - const uint32_t P = rotary_dim / 2u; - if (i < 128u) return i < P ? i : rotary_dim + (i - P); - const uint32_t j = i - 128u; - return j < P ? P + j : i; -} -/* dst[i] = src[perm_slot(i)] for 256 f32 (q, k, norm weights); src and dst must not overlap */ -static inline void omega_dattn256_perm_vec(const float *src, float *dst, uint32_t rotary_dim) { - for (uint32_t i = 0; i < 256u; i++) dst[i] = src[omega_dattn256_perm_slot(i, rotary_dim)]; -} -static inline void omega_dattn256_perm_vec_bf16(const uint16_t *src, uint16_t *dst, uint32_t rotary_dim) { - for (uint32_t i = 0; i < 256u; i++) dst[i] = src[omega_dattn256_perm_slot(i, rotary_dim)]; -} -/* The double-precision reference of the whole layer step lives in tests/gpu_decode_attn256_test.c (libm). */ - -#endif diff --git a/src/omega_gpu_decode_attn_api.c b/src/omega_gpu_decode_attn_api.c deleted file mode 100644 index ac6542487..000000000 --- a/src/omega_gpu_decode_attn_api.c +++ /dev/null @@ -1,295 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 ba84b0439..000000000 --- a/src/omega_gpu_decode_attn_api.h +++ /dev/null @@ -1,124 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 bba753564..000000000 --- a/src/omega_gpu_decode_graph.c +++ /dev/null @@ -1,428 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 c213585b2..000000000 --- a/src/omega_gpu_decode_graph.h +++ /dev/null @@ -1,204 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 7871035b9..000000000 --- a/src/omega_gpu_elementwise_api.c +++ /dev/null @@ -1,1155 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 9965ca19a..000000000 --- a/src/omega_gpu_engine.c +++ /dev/null @@ -1,480 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 3733d534a..000000000 --- a/src/omega_gpu_engine.h +++ /dev/null @@ -1,274 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 270f3fe3e..000000000 --- a/src/omega_gpu_fmt.c +++ /dev/null @@ -1,81 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 8a308f4b2..000000000 --- a/src/omega_gpu_fmt.h +++ /dev/null @@ -1,26 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 d642cc519..000000000 --- a/src/omega_gpu_fp8_api.c +++ /dev/null @@ -1,597 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 "omega_blackwell_qmd.h" /* OMEGA_BW_QMD_MAX_SHARED_BYTES: the deep kernel's x stage must fit the launch descriptor */ -#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) */ - int sched, sched_set; /* CUT5: kernel schedule 0 (default) or 1 (pipelined decode + stall pass), variant 1 only; env AIEN_OMEGA_FP8_SCHED when never set */ - int coal, coal_set, wfirst, wfirst_set; /* CUT5 variants A (coalesced output) and B (weights before x), variant 1 only; env AIEN_OMEGA_FP8_COAL / AIEN_OMEGA_FP8_WFIRST when never set */ - int deep, deep_set; /* SPEED-1B: automatic deep kernel for single projections whenever it fits (1, default) or never (0); env AIEN_OMEGA_FP8_DEEP when never set */ - int bigk, bigk_set; /* qwen38/decode-speed: single projections with k > 4096 (Qwen3.8-27B) get 16 warps and a partial-depth deep kernel when x fits; default on, env AIEN_OMEGA_FP8_BIGK when never set */ - 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(); } - -/* ---- kernel schedule (CUT5): 0 = emitted stalls (default), 1 = pipelined decode + dependency stall pass (variant 1 only) ---- */ -static int sched_now(void) { - if (!g.sched_set) { - const char *v = getenv("AIEN_OMEGA_FP8_SCHED"); - g.sched = (v && v[0] == '1' && v[1] == 0) ? 1 : 0; - g.sched_set = 1; - } - return g.sched; -} -void omega_gpu_fp8_set_sched(int sched) { - omega_gpu_session_lock(); - g.sched = sched == 1 ? 1 : 0; g.sched_set = 1; - cache_clear_locked(); - omega_gpu_session_unlock(); -} -int omega_gpu_fp8_sched(void) { return sched_now(); } -/* ---- CUT5 variants A and B (variant 1 only): 0 = off, 1 = on. Never set: the env decides once; A (coal) defaults ON (env - * value "0" turns it off; SPEED-A 2026-10-17: OWN-30B decode graph 24.49 -> 21.34 ms/token, tokens identical), B (wfirst) - * defaults OFF (env value "1" turns it on; cold bench: not distinguishable from noise) ---- */ -static int flag_now(int *v, int *set, const char *env, int dflt) { - if (!*set) { - const char *s = getenv(env); - *v = (s && s[0] == '0' && s[1] == 0) ? 0 : (s && s[0] == '1' && s[1] == 0) ? 1 : dflt; - *set = 1; - } - return *v; -} -static void flag_set(int *v, int *set, int on) { omega_gpu_session_lock(); *v = on == 1 ? 1 : 0; *set = 1; cache_clear_locked(); omega_gpu_session_unlock(); } -void omega_gpu_fp8_set_coal(int on) { flag_set(&g.coal, &g.coal_set, on); } -int omega_gpu_fp8_coal(void) { return flag_now(&g.coal, &g.coal_set, "AIEN_OMEGA_FP8_COAL", 1); } -void omega_gpu_fp8_set_wfirst(int on) { flag_set(&g.wfirst, &g.wfirst_set, on); } -int omega_gpu_fp8_wfirst(void) { return flag_now(&g.wfirst, &g.wfirst_set, "AIEN_OMEGA_FP8_WFIRST", 0); } -void omega_gpu_fp8_set_deep(int on) { flag_set(&g.deep, &g.deep_set, on); } -int omega_gpu_fp8_deep(void) { return flag_now(&g.deep, &g.deep_set, "AIEN_OMEGA_FP8_DEEP", 1); } -void omega_gpu_fp8_set_bigk(int on) { flag_set(&g.bigk, &g.bigk_set, on); } -int omega_gpu_fp8_bigk(void) { return flag_now(&g.bigk, &g.bigk_set, "AIEN_OMEGA_FP8_BIGK", 1); } -/* 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); - /* big k (qwen38/decode-speed, opt-in AIEN_OMEGA_FP8_BIGK=1): the whole row cannot be in flight, so the largest step - * count that divides KS within the 128-byte lane budget; x' still has to fit the launch descriptor's shared memory */ - const int partial = ks * spec->rows * spec->lane_bytes > 128u && spec->k > 4096u && groups == 1u && omega_gpu_fp8_bigk(); - if (partial) { do ks--; while (ks > 1u && (spec->k / (32u * spec->lane_bytes) % ks || ks * spec->rows * spec->lane_bytes > 128u)); if (ks < 2u) return 0; } - 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, before variant A): the deep kernel won on - * single projections up to a few MB (gate+up 1536x2048: 30 us vs 51; k_proj: 30 vs 44) and lost 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), so the rule - * was "classic above 4 MB". Re-measured under A (SPEED-1B, 2026-10-17, cold GPU-stamped, 5/5 interleaved, - * ~/workspace/investigations/2026-10-17-SPEED-1B): deep wins on qkv 5120 x 2048 (10.5 MB) 51.8 us vs 60.4 (0.853 vs 0.732 - * of the 237.2 GB/s line, floor spread 0.078), so the size clause is gone. o_proj 2048 x 4096 is not a candidate: its deep - * kernel's x stage exceeds the launch descriptor's shared-memory limit (qmd build (shared_bytes), 5/5), which is the bound - * checked below. AIEN_OMEGA_FP8_DEEP=0 or set_deep(0) restores the classic kernel everywhere. */ - (void)n; - if (groups != 1u || !omega_gpu_fp8_deep()) return 0; - OmegaFp8GemvSpec deep = *spec; deep.depth = ks; deep.mutant = 0; - if (omega_fp8_gemv_shared_bytes(&deep) > (partial ? OMEGA_BW_QMD_MAX_SHARED_BYTES : OMEGA_GPU_FP8_DEEP_MAX_SHARED_BYTES)) return 0; - /* The register check builds the whole kernel (codegen + register allocation). spec_for runs on every launch and every - * record, so the answer is remembered per spec: SPEED-1B graph A/B (2026-10-17) measured the unremembered check at - * 853..1172 us of host record time per token (48 qkv records) against 45..113 us without the deep default. The answer is - * a pure function of the spec (deterministic codegen), so the memo never needs clearing; spec_for zeroes the struct, - * so memcmp over the padding is exact. */ - static struct { OmegaFp8GemvSpec spec; uint32_t fits; } memo[8]; - static unsigned memo_n, memo_next; - for (unsigned i = 0; i < memo_n; i++) - if (memcmp(&memo[i].spec, &deep, sizeof deep) == 0) return memo[i].fits ? ks : 0; - uint32_t peak = 0; - const uint32_t fits = omega_fp8_gemv_prog_stats(&deep, NULL, &peak) == 0 && (uint64_t)32u * spec->warps * gpr_declared(peak) <= 65536u; - const unsigned at = memo_n < 8u ? memo_n++ : (memo_next++ % 8u); - memo[at].spec = deep; memo[at].fits = fits; - return fits ? ks : 0; -} - -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; - /* big k (opt-in AIEN_OMEGA_FP8_BIGK=1): 16 warps per CTA (sweep 2026-10-19, ~/workspace/omega-q38-speed-work/runs/sweep1: - * warps 16 beat 8 on every Qwen3.8-27B projection, 4 lost) */ - if (groups == 1u && k > 4096u && !g.warps && omega_gpu_fp8_bigk()) spec->warps = 16u; - 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->sched = (uint32_t)sched_now(); - spec->coal = omega_gpu_fp8_coal() && spec->warps * spec->rows <= 32u; /* A: shapes whose round fits one store warp */ - spec->wfirst = (uint32_t)omega_gpu_fp8_wfirst(); /* B: deep kernels ignore it */ - spec->depth = omega_gpu_fp8_depth_for(spec, n, groups); /* after coal: the deep kernel's shared bytes include A's slots */ - } - spec->mutant = g.mutant; -} -/* Host-only: the spec the automatic choice makes for a call (no chip, no cache; tests check the defaults with it). */ -void omega_gpu_fp8_spec_for(uint32_t k, uint32_t n, uint32_t groups, OmegaFp8GemvSpec *spec) { spec_for(k, n, groups, spec); } - -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) ---- */ - -/* L310 (2026-10-24): CTAs per group of a grouped launch. A grouped CTA is 32 warps = 1024 threads; CC 12.x holds 1536 - * resident threads per SM (CUDA Programming Guide, Compute Capabilities, Table 30), so one such CTA fits per SM and the - * GB10's 48 SMs (GB10 Superchip Whitepaper WP-12718-001_v02, Table 4) hold one wave of 48 CTAs. The compiled 6 was - * measured on 8 groups (48 CTAs = one wave). The 35B launches 9 groups: 54 CTAs run as two waves, the second 6 CTAs wide; - * 5 per group (45 = one wave) measured gate_up + down 6.962 -> 5.874 ms per 1-row step - * (~/workspace/investigations/2026-10-24-l310-grouped-ctas). Env, read once like the other switches: - * AIEN_OMEGA_FP8_GROUPED_CTAS=1..256 exact CTAs per group (experiments; wins over the wave rule); - * AIEN_OMEGA_FP8_GROUPED_WAVE=1 wave rule: min(GROUPED_CTAS, SM_COUNT / groups), at least 1. - * Neither set: the compiled GROUPED_CTAS, unchanged until the merge train has judged the wave arm. */ -uint32_t omega_gpu_fp8_grouped_ctas_rule(uint32_t groups, uint32_t forced, int wave) { - if (forced >= 1u && forced <= OMEGA_GPU_FP8_MAX_CTAS) return forced; - if (!wave || groups == 0u) return OMEGA_GPU_FP8_GROUPED_CTAS; - uint32_t one_wave = OMEGA_GPU_SM_COUNT / groups; - if (one_wave == 0u) one_wave = 1u; - return one_wave < OMEGA_GPU_FP8_GROUPED_CTAS ? one_wave : OMEGA_GPU_FP8_GROUPED_CTAS; -} -static uint32_t env_u32(const char *name) { /* 0 when unset, empty or not a plain number */ - const char *e = getenv(name); uint32_t n = 0; - if (!e || !*e) return 0; - for (; *e >= '0' && *e <= '9' && n < 1000u; e++) n = n * 10u + (uint32_t)(*e - '0'); - return *e ? 0 : n; -} -uint32_t omega_gpu_fp8_grouped_ctas_auto(uint32_t groups) { - static uint32_t forced; static int wave, set; - if (!set) { forced = env_u32("AIEN_OMEGA_FP8_GROUPED_CTAS"); const char *w = getenv("AIEN_OMEGA_FP8_GROUPED_WAVE"); wave = w && w[0] == '1' && !w[1]; set = 1; } - return omega_gpu_fp8_grouped_ctas_rule(groups, forced, wave); -} - -/* 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_auto(groups)) : OMEGA_GPU_FP8_MAX_CTAS); - /* big-k grid (qwen38/decode-speed): up to OMEGA_GPU_FP8_BIGK_CTAS CTAs, split so every warp gets the same number of row - * groups, at least two (measured, runs/sweep5 and sweep7: budget 384 over 256 gave mix +3%, gate_up +2.6%; the n = 5120 - * shapes run best at 160 CTAs, two row groups per warp: o_proj 186 -> 198 GB/s) */ - const int bigk_grid = !g.cta_budget_set && groups == 1u && k > 4096u && omega_gpu_fp8_bigk(); - if (bigk_grid) { uint32_t waves = (grid_x + OMEGA_GPU_FP8_BIGK_CTAS - 1u) / OMEGA_GPU_FP8_BIGK_CTAS; if (waves < 2u) waves = 2u; grid_x = (grid_x + waves - 1u) / waves; budget = grid_x; } - 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; } - -/* ---- host quantiser (qwen38/decode-speed: the FP8 lm_head) ---- */ - -/* f32 -> e4m3 (bias 7, max 448, no infinities), round to nearest, ties to even; |v| >= 448 (and NaN) saturate to 448: - * 0x7F (NaN) is never produced. Pure integer/float bit work, no libm. */ -uint8_t omega_gpu_fp8_e4m3_rne(float v) { - uint32_t u; memcpy(&u, &v, 4); - const uint8_t s = (uint8_t)((u >> 24) & 0x80u); - u &= 0x7FFFFFFFu; - float a; memcpy(&a, &u, 4); - if (!(a < 448.0f)) return (uint8_t)(s | 0x7Eu); - const int ex = (int)(u >> 23) - 127; - if (ex < -6) { /* e4m3 subnormals: units of 2^-9 (code 8 is the smallest normal, 2^-6) */ - const float x = a * 512.0f; uint32_t xi = (uint32_t)x; const float fr = x - (float)xi; - if (fr > 0.5f || (fr == 0.5f && (xi & 1u))) xi++; - return (uint8_t)(s | xi); - } - const uint32_t m = u & 0x7FFFFFu, rb = (m >> 19) & 1u, st = m & 0x7FFFFu; - uint32_t q = m >> 20, e = (uint32_t)(ex + 7); - if (rb && (st || (q & 1u))) q++; - if (q == 8u) { q = 0; e++; } - uint32_t code = (e << 3) | q; - if (code > 0x7Eu) code = 0x7Eu; - return (uint8_t)(s | code); -} - -int omega_gpu_fp8_quantize_bf16(uint32_t n, uint32_t k, const uint16_t *w, uint8_t *w8, uint16_t *scale_inv_bf16) { - if (!w || !w8 || !scale_inv_bf16 || n == 0 || k == 0 || n % OMEGA_FP8_BLOCK || k % OMEGA_FP8_BLOCK) return OMEGA_GPU_FP8_BAD_ARGS; - const uint32_t kb = k / OMEGA_FP8_BLOCK; - for (uint32_t bn = 0; bn < n / OMEGA_FP8_BLOCK; bn++) - for (uint32_t bk = 0; bk < kb; bk++) { - float amax = 0.0f; - for (uint32_t r = 0; r < OMEGA_FP8_BLOCK; r++) { - const uint16_t *row = w + ((size_t)bn * OMEGA_FP8_BLOCK + r) * k + (size_t)bk * OMEGA_FP8_BLOCK; - for (uint32_t c = 0; c < OMEGA_FP8_BLOCK; c++) { - uint32_t b = (uint32_t)(row[c] & 0x7FFFu) << 16; float f; memcpy(&f, &b, 4); - if (!(f <= 3.0e38f)) return OMEGA_GPU_FP8_BAD_ARGS; /* inf / NaN weight */ - if (f > amax) amax = f; - } - } - /* scale = amax / 448 rounded UP to bf16, so every |w / scale| <= 448 before rounding; an all-zero block gets 1 */ - uint16_t sb = 0x3F80u; - if (amax > 0.0f) { - const float q = amax / 448.0f; uint32_t b; memcpy(&b, &q, 4); - sb = (uint16_t)((b >> 16) + ((b & 0xFFFFu) ? 1u : 0u)); - } - scale_inv_bf16[(size_t)bn * kb + bk] = sb; - uint32_t sbits = (uint32_t)sb << 16; float sc; memcpy(&sc, &sbits, 4); - for (uint32_t r = 0; r < OMEGA_FP8_BLOCK; r++) { - const size_t at = ((size_t)bn * OMEGA_FP8_BLOCK + r) * k + (size_t)bk * OMEGA_FP8_BLOCK; - for (uint32_t c = 0; c < OMEGA_FP8_BLOCK; c++) { - uint32_t b = (uint32_t)w[at + c] << 16; float f; memcpy(&f, &b, 4); - w8[at + c] = omega_gpu_fp8_e4m3_rne(f / sc); - } - } - } - return OMEGA_GPU_FP8_OK; -} diff --git a/src/omega_gpu_fp8_api.h b/src/omega_gpu_fp8_api.h deleted file mode 100644 index 9c7caf2d2..000000000 --- a/src/omega_gpu_fp8_api.h +++ /dev/null @@ -1,245 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 <= 32768 (omega#541), 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_BIGK_CTAS 384u /* big-k rule: CTA budget of a single projection with k > 4096 (Qwen3.8-27B), split evenly (2026-10-19) */ -#define OMEGA_GPU_FP8_GROUPED_CTAS 6u /* CTAs per group for a grouped launch (32 warps each): measured best for 8 experts */ -#define OMEGA_GPU_SM_COUNT 48u /* GB10: 48 SMs (NVIDIA GB10 Superchip Whitepaper WP-12718-001_v02, Table 4); one 32-warp CTA per SM (CC 12.x, 1536 resident threads, CUDA Programming Guide Table 30) */ - -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); -/* Host-only quantiser (qwen38/decode-speed, the FP8 lm_head): bf16 [n][k] -> e4m3 [n][k] + scale_inv bf16 [n/128][k/128], the - * upload format above. Per 128 x 128 block: scale = max|w| / 448 rounded up to bf16 (1 for an all-zero block), w8 = e4m3(w / scale), - * round to nearest even, saturating at 448 (never the NaN code). n, k multiples of 128. OMEGA_GPU_FP8_BAD_ARGS on an inf/NaN weight. */ -int omega_gpu_fp8_quantize_bf16(uint32_t n, uint32_t k, const uint16_t *w_bf16, uint8_t *w8, uint16_t *scale_inv_bf16); -uint8_t omega_gpu_fp8_e4m3_rne(float v); /* one value, the rounding the quantiser uses */ -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); -/* The deep default was measured (SPEED-1B, 2026-10-17) while the launch descriptor allowed 16 KiB of shared memory; the - * 32 KiB cap (#559, Qwen3.8 bf16 GEMV) would newly admit the 30B o_proj (16464 bytes), which no run has measured. The - * automatic choice keeps the measured bound; set_depth still reaches anything the descriptor allows. */ -#define OMEGA_GPU_FP8_DEEP_MAX_SHARED_BYTES 16384u -/* 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); -/* Grouped-launch CTA rule (L310, 2026-10-24). rule(groups, forced, wave): forced in 1..MAX_CTAS wins; else wave != 0 gives - * min(GROUPED_CTAS, SM_COUNT / groups) (at least 1), the count that keeps groups x CTAs inside one wave of the 48 SMs; - * else the compiled GROUPED_CTAS. auto(groups) applies the rule with the env read once at the first call: - * AIEN_OMEGA_FP8_GROUPED_CTAS=n (exact, experiments) and AIEN_OMEGA_FP8_GROUPED_WAVE=1 (wave rule). Default: neither set, - * the compiled 6 (measured on 8 groups = one wave). The 35B launches 9 groups: 54 CTAs = two waves, the wave rule gives 5 - * (measured: gate_up + down 6.962 -> 5.874 ms per 1-row step, investigations/2026-10-24-l310-grouped-ctas). Servers log auto(). */ -uint32_t omega_gpu_fp8_grouped_ctas_rule(uint32_t groups, uint32_t forced, int wave); -uint32_t omega_gpu_fp8_grouped_ctas_auto(uint32_t groups); -/* 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); -/* Kernel schedule (CUT5, measurement knob; clears the kernel cache): 0 (default) = the emitted stalls, 1 = the bytes of a step - * decoded in a software pipeline plus the dependency-driven stall pass (OmegaFp8GemvSpec.sched; y bit-identical to 0). Variant 1 - * only (variant 2 ignores it). Never set: the first kernel build reads env AIEN_OMEGA_FP8_SCHED ("1" = 1). */ -void omega_gpu_fp8_set_sched(int sched); -int omega_gpu_fp8_sched(void); -/* CUT5 variants (variant 1 only; each setter clears the kernel cache; never set: the env is read once at the first build). - * A, coalesced output (OmegaFp8GemvSpec.coal; applied where warps * rows <= 32): ON by default since SPEED-A (2026-10-17, - * OWN-30B decode graph 24.49 -> 21.34 ms/token, tokens identical to golden); AIEN_OMEGA_FP8_COAL=0 or set_coal(0) restores - * the earlier kernel (one 4-byte STG per row, no shared slots). - * B, weight loads before the x loads in each K step (OmegaFp8GemvSpec.wfirst): OFF by default; AIEN_OMEGA_FP8_WFIRST=1 turns it on. */ -void omega_gpu_fp8_set_coal(int on); -int omega_gpu_fp8_coal(void); -void omega_gpu_fp8_set_wfirst(int on); -int omega_gpu_fp8_wfirst(void); -/* SPEED-1B (2026-10-17): the automatic deep kernel (x staged in shared memory, every load of the row in flight) for single - * projections whenever it fits the register file and the launch descriptor's shared-memory limit; ON by default (qkv 5120 x 2048 - * cold 0.732 -> 0.853 of line). AIEN_OMEGA_FP8_DEEP=0 or set_deep(0) keeps the step-by-step kernel everywhere. */ -void omega_gpu_fp8_set_deep(int on); -int omega_gpu_fp8_deep(void); -/* Big-k rule (qwen38/decode-speed): single projections with k > 4096 get 16 warps per CTA and, when x fits the launch - * descriptor's shared memory, the deep kernel at the largest step count that divides the row within the lane budget - * (k 5120: 5 steps, k 6144: 6). 1 (default since 2026-10-19: Qwen3.8-27B whole model 151.6 -> 142-143 ms per token, - * golden 24/24) or 0; env AIEN_OMEGA_FP8_BIGK when never set. Shapes with k <= 4096 (the 30B lane) are unchanged. */ -void omega_gpu_fp8_set_bigk(int on); -int omega_gpu_fp8_bigk(void); -/* Host-only: the spec the automatic choice makes for a call of k columns, n rows, `groups` experts under the current knobs - * (shape, depth, sched, coal, wfirst, mutant). No chip, no kernel build. */ -void omega_gpu_fp8_spec_for(uint32_t k, uint32_t n, uint32_t groups, OmegaFp8GemvSpec *spec); -#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 77bd62063..000000000 --- a/src/omega_gpu_fp8_pack.c +++ /dev/null @@ -1,91 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 "omega_gpu_hostmath.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 * omega_hostmath_pow2f(-9); - return sign * (1.0f + mantissa / 8.0f) * omega_hostmath_pow2f(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 : omega_hostmath_pow2f(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 = omega_hostmath_pow2f(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 = omega_hostmath_pow2f(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 5605a6ea8..000000000 --- a/src/omega_gpu_fp8gemm_api.c +++ /dev/null @@ -1,337 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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_cmdlist.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 g_rec; /* 1 while a record call runs (lock held): kernel_for must not evict */ -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; } - if (g_rec && s->valid) { omega_gpu_session_set_error("fp8 gemm record: kernel cache miss would evict a resident kernel (prepare the shape before recording)"); 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; -} - -/* ---- the stroke's record path (L312 v2): one launch appended to a command list, every buffer the caller's ---- */ -static void spec_for_stroke(uint32_t k, uint32_t segs, uint32_t mt, int rowmap, OmegaFp8GemmSpec *spec) { - spec_for(k, segs, spec); - if (mt) spec->mt = mt; - spec->rowmap = rowmap ? 1u : 0u; -} -int omega_gpu_fp8gemm_prepare_shape(uint32_t k, uint32_t segs, uint32_t mt, int rowmap) { - OmegaFp8GemmSpec spec; spec_for_stroke(k, segs, mt, rowmap, &spec); - if (omega_fp8gemm_shared_bytes(&spec) == 0) { omega_gpu_session_set_error("fp8 gemm prepare: shape refused (rowmap needs mt <= 4)"); return OMEGA_GPU_FP8GEMM_BAD_ARGS; } - omega_gpu_session_lock(); - int rc = OMEGA_GPU_FP8GEMM_OK; - if (!dev_open_locked()) rc = OMEGA_GPU_FP8GEMM_CHIP_FAIL; - else { Slot *s = NULL; bool hit = false; rc = kernel_for(&spec, &s, &hit); if (rc == OMEGA_GPU_FP8GEMM_OK) s->pinned = true; } - omega_gpu_session_unlock(); - return rc; -} -uint32_t omega_gpu_fp8gemm_cta_budget_for(uint32_t segs) { return g.ctas ? g.ctas : (segs >= 64u ? 2u : segs >= 8u ? 12u : 96u); } - -int omega_gpu_fp8gemm_record(OmegaGpuCmdList *cl, const OmegaGpuFp8Tensor *t, uint32_t rows, uint32_t segs, uint64_t seg_va, uint64_t xp_va, - uint64_t y_va, uint64_t xmap_va, uint64_t ymap_va, uint32_t mt, uint32_t cta_budget, OmegaGpuFp8GemmInfo *info) { - 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 (!cl || !t || !experts || !seg_va || !xp_va || !y_va || rows == 0 || segs == 0 || (!xmap_va) != (!ymap_va)) return OMEGA_GPU_FP8GEMM_BAD_ARGS; - if (rows > OMEGA_GPU_FP8GEMM_MAX_ROWS || segs > OMEGA_GPU_FP8GEMM_MAX_SEGMENTS) return OMEGA_GPU_FP8GEMM_TOO_LARGE; - OmegaFp8GemmSpec spec; spec_for_stroke(k, segs, mt, xmap_va != 0, &spec); - if (omega_fp8gemm_shared_bytes(&spec) == 0) { omega_gpu_session_set_error("fp8 gemm record: shape refused (rowmap needs mt <= 4)"); return OMEGA_GPU_FP8GEMM_BAD_ARGS; } - const uint32_t W = spec.warps; - uint32_t grid_x = (n + W - 1) / W; - const uint32_t budget = cta_budget ? cta_budget : omega_gpu_fp8gemm_cta_budget_for(segs); - if (grid_x > budget) grid_x = budget; - if (grid_x == 0) grid_x = 1; - /* caller holds the session lock */ - if (!dev_open_locked()) return OMEGA_GPU_FP8GEMM_CHIP_FAIL; - Slot *ks = NULL; bool hit = false; - g_rec = 1; - int rc = kernel_for(&spec, &ks, &hit); - g_rec = 0; - if (rc != OMEGA_GPU_FP8GEMM_OK) return rc; - uint32_t args[OMEGA_GEMM_ARGS_WORDS_MAP]; memset(args, 0, sizeof args); - args[0] = (uint32_t)seg_va; args[1] = (uint32_t)(seg_va >> 32); - args[2] = (uint32_t)xp_va; args[3] = (uint32_t)(xp_va >> 32); - args[4] = (uint32_t)y_va; args[5] = (uint32_t)(y_va >> 32); - args[6] = n; args[7] = grid_x * W; - args[8] = (uint32_t)xmap_va; args[9] = (uint32_t)(xmap_va >> 32); - args[10] = (uint32_t)ymap_va; args[11] = (uint32_t)(ymap_va >> 32); - if (info) { - info->rows = rows; info->segments = segs; info->n = n; info->k = k; info->mt = spec.mt; info->warps_per_cta = W; info->lane_bytes = spec.lane_bytes; - info->grid_x = grid_x; info->grid_y = segs; info->kernel_cache_hit = hit; - } - 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 = segs, - .num_elements = (size_t)rows * n, - .args = args, .n_args = spec.rowmap ? OMEGA_GEMM_ARGS_WORDS_MAP : 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"); return OMEGA_GPU_FP8GEMM_CHIP_FAIL; } - if (omega_gpu_cmdlist_add(cl, &L) < 0) return OMEGA_GPU_FP8GEMM_CHIP_FAIL; - return OMEGA_GPU_FP8GEMM_OK; -} - -/* 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 2f14e9a41..000000000 --- a/src/omega_gpu_fp8gemm_api.h +++ /dev/null @@ -1,124 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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); - -/* ---- the stroke's record path (L312 v2: one weight read per layer for every conversation on the chip) ---- - * omega_gpu_fp8gemm_record appends ONE launch of the grouped GEMM to cl; every buffer is the caller's, in device memory: - * seg_va: segs entries of OMEGA_GEMM_SEG_BYTES {w_va, s_va, row0, cnt} (omega_gpu_fp8_tensor_entry, or a kernel on - * the chip writes them); a segment with cnt 0 is skipped by its CTAs (the group kernel leaves trailing - * segments empty when fewer experts are distinct); - * xp_va: x' rows (k f32 each, permuted and * 2^64, omega_fp8gemm_permute_x) followed by mt rows of padding the - * kernel may read; y_va: rows * n f32; - * xmap_va, ymap_va: both 0 (x' row and y row of sorted row p are p) or both u32 tables of rows + mt entries: - * x' row XMAP[p] feeds sorted row p and its output lands in y row YMAP[p] (padding entries 0). With maps the - * kernel runs at mt <= 4 (rowmap at mt 8 does not fit the register file); mt 0 = the API's choice for segs. - * cta_budget 0 = the API's choice (omega_gpu_fp8gemm_cta_budget_for). rows: the y rows (num_elements), <= 1024. - * The caller holds omega_gpu_session_lock(). 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). A kernel cache miss that would evict a resident kernel - * is refused (TOO_LARGE): call omega_gpu_fp8gemm_prepare_shape for the shape first (segs, mt, rowmap as recorded). */ -struct OmegaGpuCmdList; -int omega_gpu_fp8gemm_record(struct OmegaGpuCmdList *cl, const OmegaGpuFp8Tensor *t, uint32_t rows, uint32_t segs, uint64_t seg_va, - uint64_t xp_va, uint64_t y_va, uint64_t xmap_va, uint64_t ymap_va, uint32_t mt, uint32_t cta_budget, - OmegaGpuFp8GemmInfo *info); -int omega_gpu_fp8gemm_prepare_shape(uint32_t k, uint32_t segs, uint32_t mt, int rowmap); -uint32_t omega_gpu_fp8gemm_cta_budget_for(uint32_t segs); - -/* 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_gdn_api.c b/src/omega_gpu_gdn_api.c deleted file mode 100644 index 6d56e0e14..000000000 --- a/src/omega_gpu_gdn_api.c +++ /dev/null @@ -1,644 +0,0 @@ -/* - * omega_gpu_gdn_api.c: resident Gated DeltaNet parameters, tails, states and the one-launch decode step (see the - * header). Session use mirrors omega_gpu_router_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 call; the tails and states - * are the exception (GPU-cached, reached by the host only through the copy / zero launches). - */ -#include "omega_gpu_gdn_api.h" -#include "omega_gpu_hostmath.h" -#include "omega_gpu_session.h" -#include "omega_gpu_cmdlist.h" -#include "omega_blackwell_codegen_tc.h" -#include -#include -#include -#include -#include "omega_gpu_mem_cached.h" - -#define MARKER_TIMEOUT_MS 20000ull -#define POISON_F32 (-999.0f) - -/* the launch buffer: one allocation, fixed offsets (bytes) */ -#define LB_QKV 0u -#define LB_Z (LB_QKV + OMEGA_GDN_CONV_DIM * 4u) -#define LB_AB (LB_Z + OMEGA_GDN_V_DIM * 4u) -#define LB_OUT (LB_AB + OMEGA_GDN_VALUE_HEADS * 8u) -#define LB_BYTES (LB_OUT + OMEGA_GDN_V_DIM * 4u) - -struct OmegaGpuGdn { - uint32_t layers; - uint32_t ratio; /* OmegaGdnSpec.ratio (0 = 3, the 27B) */ - OmegaGdnShape sh; - OmegaGpuMem par; /* [layers][OMEGA_GDN_PAR_BYTES] */ - OmegaGpuMem tail; /* [layers][OMEGA_GDN_TAIL_BYTES] */ - OmegaGpuMem state; /* [layers][OMEGA_GDN_STATE_BYTES] */ - OmegaGpuMem lb; /* launch buffer */ - int cached; /* tail and state GPU-cached: the host reaches them only through the chip (reset, stage) */ - int bf16; /* L313: the state is stored bf16 (AIEN_OMEGA_GDN_STATE_BF16=1 at alloc); set/get_state keep the f32 layout */ - OmegaGpuMem stage; /* cached: uncached staging for set_state / get_state, [state of one layer][tail of one layer] */ - OmegaGpuScratch pf; /* prefill scratch (see pf_layout) */ -}; - -typedef struct { - bool valid; - OmegaGdnSpec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; - uint32_t insns; -} Slot; - -/* the resident kernels: decode, prefill prep, scan, post; the state copy and zero */ -enum { KK_DECODE, KK_PREP, KK_SCAN, KK_POST, KK_COPY, KK_ZERO, KK_MULTI, KK_N }; -static const uint32_t kk_threads[KK_N] = { OMEGA_GDN_THREADS, OMEGA_GDN_PREP_THREADS, OMEGA_GDN_THREADS, OMEGA_GDN_THREADS, - OMEGA_GDN_COPY_THREADS, OMEGA_GDN_COPY_THREADS, OMEGA_GDN_THREADS }; -static struct { - bool hooked; - Slot slot[KK_N]; - int mutant; -} g_k; -static int g_rec; /* 1 while a record call runs (lock held): kernel_for must not evict */ - -static void slot_clear_locked(void) { - for (unsigned k = 0; k < KK_N; k++) { if (g_k.slot[k].valid) omega_gpu_session_free(&g_k.slot[k].code); memset(&g_k.slot[k], 0, sizeof g_k.slot[k]); } -} -static void on_session_close(void) { memset(g_k.slot, 0, sizeof g_k.slot); } -static OmegaGpuSession *dev_open_locked(void) { - if (!g_k.hooked) { (void)omega_gpu_session_on_close(on_session_close); g_k.hooked = true; } - return omega_gpu_session_open(); -} - -void omega_gpu_gdn_test_set_mutant(int mutant) { omega_gpu_session_lock(); g_k.mutant = mutant; slot_clear_locked(); omega_gpu_session_unlock(); } -const char *omega_gpu_gdn_last_error(void) { return omega_gpu_session_last_error(); } -const char *omega_gpu_gdn_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_GDN_OK: return "OK"; - case OMEGA_GPU_GDN_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_GDN_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_GDN_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_GDN_CHIP_FAIL: return "CHIP_FAIL"; - default: return "?"; - } -} - -/* ---- host layout ---- */ -/* the qkv channel slot s of value head h reads */ -static uint32_t slot_channel(const OmegaGdnShape *shp, uint32_t h, uint32_t s) { - const uint32_t hk = h / (shp->vh / OMEGA_GDN_KEY_HEADS), D = OMEGA_GDN_HEAD_DIM; - if (s < D) return hk * D + s; - if (s < 2u * D) return OMEGA_GDN_KEY_HEADS * D + hk * D + (s - D); - return 2u * OMEGA_GDN_KEY_HEADS * D + h * D + (s - 2u * D); -} - -static int shape_of(uint32_t ratio, OmegaGdnShape *s) { OmegaGdnSpec sp; memset(&sp, 0, sizeof sp); sp.ratio = ratio; return omega_gdn_shape(&sp, s); } - -int omega_gdn_pack_params(const float *conv_w, const float *a_log, const float *dt_bias, const float *norm_w, uint8_t *block) { - return omega_gdn_pack_params_r(0, conv_w, a_log, dt_bias, norm_w, block); -} - -int omega_gdn_pack_params_r(uint32_t ratio, const float *conv_w, const float *a_log, const float *dt_bias, const float *norm_w, uint8_t *block) { - OmegaGdnShape S; const OmegaGdnShape *shp = &S; - if (shape_of(ratio, &S) || !conv_w || !a_log || !dt_bias || !norm_w || !block) return -1; - memcpy(block + OMEGA_GDN_PAR_CONV, conv_w, (size_t)shp->conv * OMEGA_GDN_TAPS * 4u); - float *sc = (float *)(block + shp->par_scal); - for (uint32_t h = 0; h < shp->vh; h++) { sc[2 * h] = -(float)omega_hostmath_exp((double)a_log[h]); /* libm-free: omegatool links without -lm */ sc[2 * h + 1] = dt_bias[h]; } - memcpy(block + shp->par_norm, norm_w, OMEGA_GDN_HEAD_DIM * 4u); - return 0; -} - -void omega_gdn_pack_tail(const float *tail, float *dev) { (void)omega_gdn_pack_tail_r(0, tail, dev); } - -int omega_gdn_pack_tail_r(uint32_t ratio, const float *tail, float *dev) { - OmegaGdnShape S; const OmegaGdnShape *shp = &S; - if (shape_of(ratio, &S)) return -1; - for (uint32_t h = 0; h < shp->vh; h++) - for (uint32_t s = 0; s < OMEGA_GDN_SLOTS; s++) { - float *d = dev + ((size_t)h * OMEGA_GDN_SLOTS + s) * 4u; - const uint32_t ch = slot_channel(shp, h, s); - for (uint32_t j = 0; j < 3; j++) d[j] = tail[(size_t)j * shp->conv + ch]; - d[3] = 0.0f; - } - return 0; -} - -int omega_gdn_unpack_tail(const float *dev, float *tail) { return omega_gdn_unpack_tail_r(0, dev, tail); } - -int omega_gdn_unpack_tail_r(uint32_t ratio, const float *dev, float *tail) { - OmegaGdnShape S; const OmegaGdnShape *shp = &S; - if (shape_of(ratio, &S)) return -1; - int rc = 0; - for (uint32_t h = 0; h < shp->vh; h++) - for (uint32_t s = 0; s < OMEGA_GDN_SLOTS; s++) { - const float *d = dev + ((size_t)h * OMEGA_GDN_SLOTS + s) * 4u; - const uint32_t ch = slot_channel(shp, h, s); - const bool first = s >= 2u * OMEGA_GDN_HEAD_DIM || h % (shp->vh / OMEGA_GDN_KEY_HEADS) == 0; - for (uint32_t j = 0; j < 3; j++) { - float *t = &tail[(size_t)j * shp->conv + ch]; - if (first) *t = d[j]; - else if (memcmp(t, &d[j], 4) != 0) rc = -1; - } - } - return rc; -} - -/* ---- buffers ---- */ -static int zero_ts_locked(OmegaGpuGdn *g); -static int move_locked(unsigned kind, uint64_t src, uint64_t dst, size_t bytes); -int omega_gpu_gdn_alloc(uint32_t layers, OmegaGpuGdn **out) { return omega_gpu_gdn_alloc_ratio(layers, 0, out); } - -int omega_gpu_gdn_alloc_ratio(uint32_t layers, uint32_t ratio, OmegaGpuGdn **out) { - OmegaGdnShape S; - if (!out || layers == 0 || layers > OMEGA_GPU_GDN_MAX_LAYERS || shape_of(ratio, &S)) return OMEGA_GPU_GDN_BAD_ARGS; - /* L313: AIEN_OMEGA_GDN_STATE_BF16=1 stores the state bf16 (half the bytes per conversation; compute stays f32) */ - const char *pb = getenv("AIEN_OMEGA_GDN_STATE_BF16"); - const int bf16 = pb && pb[0] == '1' && pb[1] == 0; - if (bf16) { OmegaGdnSpec sp; memset(&sp, 0, sizeof sp); sp.ratio = ratio; sp.state_bf16 = 1; if (omega_gdn_shape(&sp, &S)) return OMEGA_GPU_GDN_BAD_ARGS; } - *out = NULL; - OmegaGpuGdn *g = omega_gpu_host_calloc(1, sizeof *g); - if (!g) return OMEGA_GPU_GDN_BAD_ARGS; - g->bf16 = bf16; - g->layers = layers; - g->ratio = ratio; - g->sh = S; - omega_gpu_session_lock(); - int rc = OMEGA_GPU_GDN_OK; - if (!dev_open_locked()) rc = OMEGA_GPU_GDN_CHIP_FAIL; - if (rc == OMEGA_GPU_GDN_OK && omega_gpu_session_alloc((size_t)layers * g->sh.par_bytes, &g->par) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - /* tail and state GPU-cached unless AIEN_OMEGA_GDN_STATE_CACHED=0 (measured: the decode step 129 -> 43 us per layer, - * runs/probe-gdn): the step's 64 scalar state stores per thread merge in L2 instead of going to DRAM one by one */ - const char *pc = getenv("AIEN_OMEGA_GDN_STATE_CACHED"); - g->cached = !(pc && pc[0] == '0' && pc[1] == 0); - int (*const alloc_ts)(size_t, OmegaGpuMem *) = g->cached ? omega_gpu_session_alloc_cached : omega_gpu_session_alloc; - if (rc == OMEGA_GPU_GDN_OK && alloc_ts((size_t)layers * g->sh.tail_bytes, &g->tail) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - if (rc == OMEGA_GPU_GDN_OK && alloc_ts((size_t)layers * g->sh.state_bytes, &g->state) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - if (rc == OMEGA_GPU_GDN_OK && omega_gpu_session_alloc(LB_BYTES, &g->lb) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - if (rc == OMEGA_GPU_GDN_OK) { - memset(g->par.cpu, 0, (size_t)layers * g->sh.par_bytes); - memset(g->lb.cpu, 0, LB_BYTES); - if (omega_gpu_session_sync_to_gpu(&g->par) != 0 || omega_gpu_session_sync_to_gpu(&g->lb) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - } - /* tail and state start at zero (cached: zeroed by the chip, since a recycled page may still have lines in L2 that a - * CPU write would not reach) */ - if (rc == OMEGA_GPU_GDN_OK) rc = zero_ts_locked(g); - omega_gpu_session_unlock(); - if (rc != OMEGA_GPU_GDN_OK) { omega_gpu_gdn_free(g); return rc; } - *out = g; - return OMEGA_GPU_GDN_OK; -} - -void omega_gpu_gdn_free(OmegaGpuGdn *g) { - if (!g) return; - omega_gpu_session_lock(); - if (g->par.cpu) omega_gpu_session_free(&g->par); - if (g->tail.cpu) omega_gpu_session_free(&g->tail); - if (g->state.cpu) omega_gpu_session_free(&g->state); - if (g->lb.cpu) omega_gpu_session_free(&g->lb); - if (g->stage.cpu) omega_gpu_session_free(&g->stage); - omega_gpu_session_scratch_free(&g->pf); - omega_gpu_session_unlock(); - omega_gpu_host_free(g); -} - -int omega_gpu_gdn_set_layer(OmegaGpuGdn *g, uint32_t layer, const float *conv_w, const float *a_log, const float *dt_bias, - const float *norm_w) { - if (!g || layer >= g->layers) return OMEGA_GPU_GDN_BAD_ARGS; - omega_gpu_session_lock(); - int rc = omega_gdn_pack_params_r(g->ratio, conv_w, a_log, dt_bias, norm_w, (uint8_t *)g->par.cpu + (size_t)layer * g->sh.par_bytes) == 0 - ? OMEGA_GPU_GDN_OK : OMEGA_GPU_GDN_BAD_ARGS; - if (rc == OMEGA_GPU_GDN_OK && omega_gpu_session_sync_to_gpu(&g->par) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_gdn_reset(OmegaGpuGdn *g) { - if (!g) return OMEGA_GPU_GDN_BAD_ARGS; - omega_gpu_session_lock(); - int rc = dev_open_locked() ? zero_ts_locked(g) : OMEGA_GPU_GDN_CHIP_FAIL; - omega_gpu_session_unlock(); - return rc; -} - -/* L313: one layer's state between the f32 reference layout and the stored format (bf16: round to nearest even, the chip's - * F2FP.BF16.F32 rule; widen exact). */ -static void state_put(const OmegaGpuGdn *g, void *dst, const float *src) { - if (!g->bf16) { memcpy(dst, src, g->sh.state_bytes); return; } - uint16_t *d = dst; - for (size_t i = 0; i < g->sh.state_bytes / 2u; i++) { - uint32_t b; memcpy(&b, &src[i], 4); - d[i] = (b & 0x7fffffffu) > 0x7f800000u ? (uint16_t)0x7fc0u : (uint16_t)((b + 0x7fffu + ((b >> 16) & 1u)) >> 16); - } -} -static void state_get(const OmegaGpuGdn *g, float *dst, const void *src) { - if (!g->bf16) { memcpy(dst, src, g->sh.state_bytes); return; } - const uint16_t *s = src; - for (size_t i = 0; i < g->sh.state_bytes / 2u; i++) { uint32_t b = (uint32_t)s[i] << 16; memcpy(&dst[i], &b, 4); } -} - -/* cached: the staging buffer [state][tail] of one layer (uncached), made on first use */ -static int stage_locked(OmegaGpuGdn *g) { - if (g->stage.cpu) return OMEGA_GPU_GDN_OK; - return omega_gpu_session_alloc((size_t)g->sh.state_bytes + g->sh.tail_bytes, &g->stage) == 0 ? OMEGA_GPU_GDN_OK : OMEGA_GPU_GDN_CHIP_FAIL; -} - -int omega_gpu_gdn_set_state(OmegaGpuGdn *g, uint32_t layer, const float *tail, const float *state) { - if (!g || layer >= g->layers || !tail || !state) return OMEGA_GPU_GDN_BAD_ARGS; - omega_gpu_session_lock(); - int rc = OMEGA_GPU_GDN_OK; - const size_t so = (size_t)layer * g->sh.state_bytes, to = (size_t)layer * g->sh.tail_bytes; - if (!g->cached) { - omega_gdn_pack_tail_r(g->ratio, tail, (float *)((uint8_t *)g->tail.cpu + to)); - state_put(g, (uint8_t *)g->state.cpu + so, state); - rc = (omega_gpu_session_sync_to_gpu(&g->tail) == 0 && omega_gpu_session_sync_to_gpu(&g->state) == 0) ? OMEGA_GPU_GDN_OK : OMEGA_GPU_GDN_CHIP_FAIL; - } else { - rc = dev_open_locked() ? stage_locked(g) : OMEGA_GPU_GDN_CHIP_FAIL; - if (rc == OMEGA_GPU_GDN_OK) { - state_put(g, g->stage.cpu, state); - omega_gdn_pack_tail_r(g->ratio, tail, (float *)((uint8_t *)g->stage.cpu + g->sh.state_bytes)); - if (omega_gpu_session_sync_to_gpu(&g->stage) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - } - if (rc == OMEGA_GPU_GDN_OK) rc = move_locked(KK_COPY, g->stage.va, g->state.va + so, g->sh.state_bytes); - if (rc == OMEGA_GPU_GDN_OK) rc = move_locked(KK_COPY, g->stage.va + g->sh.state_bytes, g->tail.va + to, g->sh.tail_bytes); - } - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_gdn_get_state(OmegaGpuGdn *g, uint32_t layer, float *tail, float *state) { - if (!g || layer >= g->layers || (!tail && !state)) return OMEGA_GPU_GDN_BAD_ARGS; - omega_gpu_session_lock(); - int rc = OMEGA_GPU_GDN_OK; - const size_t so = (size_t)layer * g->sh.state_bytes, to = (size_t)layer * g->sh.tail_bytes; - const uint8_t *sp, *tp; - if (!g->cached) { - rc = (omega_gpu_session_sync_to_cpu(&g->tail) == 0 && omega_gpu_session_sync_to_cpu(&g->state) == 0) ? OMEGA_GPU_GDN_OK : OMEGA_GPU_GDN_CHIP_FAIL; - sp = (const uint8_t *)g->state.cpu + so; tp = (const uint8_t *)g->tail.cpu + to; - } else { - rc = dev_open_locked() ? stage_locked(g) : OMEGA_GPU_GDN_CHIP_FAIL; - if (rc == OMEGA_GPU_GDN_OK) rc = move_locked(KK_COPY, g->state.va + so, g->stage.va, g->sh.state_bytes); - if (rc == OMEGA_GPU_GDN_OK) rc = move_locked(KK_COPY, g->tail.va + to, g->stage.va + g->sh.state_bytes, g->sh.tail_bytes); - if (rc == OMEGA_GPU_GDN_OK && omega_gpu_session_sync_to_cpu(&g->stage) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - sp = g->stage.cpu; tp = sp + g->sh.state_bytes; - } - if (rc == OMEGA_GPU_GDN_OK && tail && omega_gdn_unpack_tail_r(g->ratio, (const float *)tp, tail) != 0) { - omega_gpu_session_set_error("gdn: the per-head copies of a key head's conv tail disagree"); - rc = OMEGA_GPU_GDN_CHIP_FAIL; - } - if (rc == OMEGA_GPU_GDN_OK && state) state_get(g, state, sp); - omega_gpu_session_unlock(); - return rc; -} - -/* ---- kernel ---- */ -static int kernel_build(unsigned kind, const OmegaGdnSpec *spec, BlackwellIRProgram *prog) { - switch (kind) { - case KK_DECODE: return omega_blackwell_codegen_gdn_prog(spec, prog); - case KK_PREP: return omega_blackwell_codegen_gdn_prep_prog(spec, prog); - case KK_SCAN: return omega_blackwell_codegen_gdn_scan_prog(spec, prog); - case KK_POST: return omega_blackwell_codegen_gdn_post_prog(spec, prog); - case KK_COPY: case KK_ZERO: return omega_blackwell_codegen_gdn_copy_prog(spec, prog); - case KK_MULTI: return omega_blackwell_codegen_gdn_multi_prog(spec, prog); - default: return -1; - } -} -static int kernel_for(unsigned kind, const OmegaGdnSpec *spec, Slot **out, bool *hit) { - Slot *s = &g_k.slot[kind]; - if (s->valid && memcmp(&s->spec, spec, sizeof *spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_GDN_OK; } - if (g_rec && s->valid) { omega_gpu_session_set_error("gdn record: kernel cache miss would evict the resident kernel (warm up before recording)"); return OMEGA_GPU_GDN_TOO_LARGE; } - 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("gdn codegen: host memory"); return OMEGA_GPU_GDN_CODEGEN_FAIL; } - int cg = kernel_build(kind, 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("gdn codegen refused the spec"); return OMEGA_GPU_GDN_CODEGEN_FAIL; } - if ((uint64_t)kk_threads[kind] * omega_bw_gpr_declared(prog->regalloc.peak_gpr_usage) > 65536u) { omega_gpu_host_free(prog); omega_gpu_session_set_error("gdn: register file"); return OMEGA_GPU_GDN_TOO_LARGE; } - const uint32_t insns = (uint32_t)prog->count, expect = omega_gdn_bfly_count(prog); - OmegaGpuMem code; - if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_GDN_CHIP_FAIL; } - OmegaBlackwellKernel kernel; - cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); - /* SHFL.BFLY placeholders become real butterflies (omega_blackwell_codegen_tc.h); the count must match */ - const 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("gdn encode"); return OMEGA_GPU_GDN_CODEGEN_FAIL; } - if (np < 0 || (uint32_t)np != expect) { omega_gpu_session_free(&code); omega_gpu_session_set_error("gdn: butterfly patch count mismatch"); return OMEGA_GPU_GDN_CODEGEN_FAIL; } - if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_GDN_CHIP_FAIL; } - memset(s, 0, sizeof *s); - s->valid = true; s->spec = *spec; s->kernel = kernel; s->code = code; s->insns = insns; - *out = s; *hit = false; - return OMEGA_GPU_GDN_OK; -} - - -/* One copy (KK_COPY: dst = src) or zero (KK_ZERO: dst = 0, src unused) launch over `bytes` (a multiple of 4096), submitted - * and waited for. Caller holds the session lock with the device open. */ -static int move_locked(unsigned kind, uint64_t src, uint64_t dst, size_t bytes) { - const size_t per = (size_t)OMEGA_GDN_COPY_WORDS_PER_CTA * 4u; - if ((kind != KK_COPY && kind != KK_ZERO) || !dst || bytes == 0 || bytes % per || bytes / per > 0x7fffffffu) return OMEGA_GPU_GDN_BAD_ARGS; - OmegaGdnSpec spec; memset(&spec, 0, sizeof spec); - spec.copy = kind == KK_COPY ? OMEGA_GDN_COPY : OMEGA_GDN_ZERO; - Slot *ks = NULL; bool hit = false; - int rc = kernel_for(kind, &spec, &ks, &hit); - if (rc != OMEGA_GPU_GDN_OK) return rc; - uint32_t args[OMEGA_GDN_COPY_ARGS_WORDS] = { (uint32_t)src, (uint32_t)(src >> 32), (uint32_t)dst, (uint32_t)(dst >> 32) }; - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = omega_bw_gpr_declared(ks->kernel.gpr_count), - .threads_x = OMEGA_GDN_COPY_THREADS, .threads_y = 1, .grid_x = (uint32_t)(bytes / per), .grid_y = 1, - .num_elements = bytes / 4u, .args = args, .n_args = OMEGA_GDN_COPY_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_GDN_CHIP_FAIL; } - return omega_gpu_session_launch(&L, NULL, NULL) == 0 ? OMEGA_GPU_GDN_OK : OMEGA_GPU_GDN_CHIP_FAIL; -} - -/* Every layer's tail and state to zero: cached on the chip, uncached by the host. Caller holds the lock, device open. */ -static int zero_ts_locked(OmegaGpuGdn *g) { - const size_t tb = (size_t)g->layers * g->sh.tail_bytes, sb = (size_t)g->layers * g->sh.state_bytes; - if (!g->cached) { - memset(g->tail.cpu, 0, tb); memset(g->state.cpu, 0, sb); - return (omega_gpu_session_sync_to_gpu(&g->tail) == 0 && omega_gpu_session_sync_to_gpu(&g->state) == 0) ? OMEGA_GPU_GDN_OK : OMEGA_GPU_GDN_CHIP_FAIL; - } - int rc = move_locked(KK_ZERO, 0, g->tail.va, tb); - return rc == OMEGA_GPU_GDN_OK ? move_locked(KK_ZERO, 0, g->state.va, sb) : rc; -} -/* rec non-NULL (record path, caller holds the session lock): the inputs are the device rows dev_*, the launch is - * appended to rec instead of submitted, nothing is staged, poisoned or read back. */ -static int gdn_core(OmegaGpuGdn *g, uint32_t layer, const float *qkv, const float *z, const float *ab, float eps_l2, - float eps_norm, float in_scale, float out_scale, float *out, OmegaGpuGdnInfo *info, - OmegaGpuCmdList *rec, uint64_t dev_qkv, uint64_t dev_z, uint64_t dev_ab) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - if (!g || layer >= g->layers || (rec ? (!dev_qkv || !dev_z || !dev_ab) : (!qkv || !z || !ab || !out))) return OMEGA_GPU_GDN_BAD_ARGS; - if (!isfinite(eps_l2) || !isfinite(eps_norm) || !isfinite(in_scale) || !isfinite(out_scale)) return OMEGA_GPU_GDN_BAD_ARGS; - OmegaGdnSpec spec; memset(&spec, 0, sizeof spec); - spec.mutant = g_k.mutant; - spec.ratio = g->ratio; - spec.state_bf16 = (uint32_t)g->bf16; - - if (!rec) omega_gpu_session_lock(); -#define UNLOCK() do { if (!rec) omega_gpu_session_unlock(); } while (0) - int rc = OMEGA_GPU_GDN_OK; - if (!dev_open_locked()) { UNLOCK(); return OMEGA_GPU_GDN_CHIP_FAIL; } - Slot *ks = NULL; bool hit = false; - g_rec = rec != NULL; - rc = kernel_for(KK_DECODE, &spec, &ks, &hit); - g_rec = 0; - if (rc != OMEGA_GPU_GDN_OK) { UNLOCK(); return rc; } - uint8_t *b = g->lb.cpu; - float *yo = (float *)(b + LB_OUT); - if (!rec) { - memcpy(b + LB_QKV, qkv, g->sh.conv * 4u); - memcpy(b + LB_Z, z, g->sh.vdim * 4u); - memcpy(b + LB_AB, ab, g->sh.vh * 8u); - for (size_t i = 0; i < g->sh.vdim; i++) yo[i] = POISON_F32; - if (omega_gpu_session_sync_to_gpu(&g->lb) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - } - - uint32_t args[OMEGA_GDN_ARGS_WORDS]; -#define A64(i, v) do { args[i] = (uint32_t)(v); args[(i) + 1] = (uint32_t)((v) >> 32); } while (0) - A64(0, rec ? dev_qkv : g->lb.va + LB_QKV); A64(2, rec ? dev_z : g->lb.va + LB_Z); A64(4, rec ? dev_ab : g->lb.va + LB_AB); - A64(6, g->par.va + (uint64_t)layer * g->sh.par_bytes); A64(8, g->tail.va + (uint64_t)layer * g->sh.tail_bytes); - A64(10, g->state.va + (uint64_t)layer * g->sh.state_bytes); A64(12, g->lb.va + LB_OUT); -#undef A64 - memcpy(&args[14], &eps_l2, 4); memcpy(&args[15], &eps_norm, 4); memcpy(&args[16], &in_scale, 4); memcpy(&args[17], &out_scale, 4); - if (info) { - info->layer = layer; info->threads = OMEGA_GDN_THREADS; info->grid_x = g->sh.r; info->grid_y = OMEGA_GDN_GRID_Y; - info->insns = ks->insns; info->gprs = ks->kernel.gpr_count; - info->state_bytes = 2ull * g->sh.state_bytes; - info->kernel_cache_hit = hit; - } - if (rc == OMEGA_GPU_GDN_OK) { - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = omega_bw_gpr_declared(ks->kernel.gpr_count), - .threads_x = OMEGA_GDN_THREADS, .threads_y = 1, .grid_x = g->sh.r, .grid_y = OMEGA_GDN_GRID_Y, - .num_elements = (size_t)g->sh.vdim, - .args = args, .n_args = OMEGA_GDN_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = OMEGA_GDN_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_GDN_CHIP_FAIL; } - else if (rec) { if (omega_gpu_cmdlist_add(rec, &L) < 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; } - else if (omega_gpu_session_launch(&L, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - } - if (rc == OMEGA_GPU_GDN_OK && !rec && omega_gpu_session_sync_to_cpu(&g->lb) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - if (rc == OMEGA_GPU_GDN_OK && !rec) { - size_t unchanged = 0; - for (size_t i = 0; i < g->sh.vdim; i++) if (yo[i] == POISON_F32) unchanged++; - if (unchanged) { omega_gpu_session_set_error("gdn: output poison survived"); rc = OMEGA_GPU_GDN_CHIP_FAIL; } - else memcpy(out, yo, g->sh.vdim * 4u); - } - UNLOCK(); -#undef UNLOCK - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} - -int omega_gpu_gdn_step(OmegaGpuGdn *g, uint32_t layer, const float *qkv, const float *z, const float *ab, float eps_l2, - float eps_norm, float in_scale, float out_scale, float *out, OmegaGpuGdnInfo *info) { - return gdn_core(g, layer, qkv, z, ab, eps_l2, eps_norm, in_scale, out_scale, out, info, NULL, 0, 0, 0); -} - -/* Record path (decode graph): see the header. Caller holds omega_gpu_session_lock(). */ -int omega_gpu_gdn_record(OmegaGpuCmdList *cl, OmegaGpuGdn *g, uint32_t layer, uint64_t qkv_va, uint64_t z_va, uint64_t ab_va, - float eps_l2, float eps_norm, float in_scale, float out_scale, uint64_t *out_va) { - if (!cl) return OMEGA_GPU_GDN_BAD_ARGS; - int rc = gdn_core(g, layer, NULL, NULL, NULL, eps_l2, eps_norm, in_scale, out_scale, NULL, NULL, cl, qkv_va, z_va, ab_va); - if (rc == OMEGA_GPU_GDN_OK && out_va) *out_va = g->lb.va + LB_OUT; - return rc; -} - -/* ---- multi-token decode (L369): see the header ---- */ -int omega_gpu_gdn_multi_prepare(OmegaGpuGdn *g) { - if (!g) return OMEGA_GPU_GDN_BAD_ARGS; - OmegaGdnSpec spec; memset(&spec, 0, sizeof spec); - spec.mutant = g_k.mutant; spec.ratio = g->ratio; - omega_gpu_session_lock(); - int rc = dev_open_locked() ? OMEGA_GPU_GDN_OK : OMEGA_GPU_GDN_CHIP_FAIL; - Slot *ks = NULL; bool hit = false; - if (rc == OMEGA_GPU_GDN_OK) rc = kernel_for(KK_MULTI, &spec, &ks, &hit); - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_gdn_multi_record(OmegaGpuCmdList *cl, OmegaGpuGdn *g, uint32_t layer, uint32_t tokens, uint64_t qkv_va, uint64_t z_va, - uint32_t xstride, uint64_t ab_va, uint32_t abstride, uint64_t out_va, uint32_t ostride, float eps_l2, - float eps_norm, float in_scale, float out_scale) { - if (!cl || !g || layer >= g->layers || tokens == 0 || !qkv_va || !z_va || !ab_va || !out_va) return OMEGA_GPU_GDN_BAD_ARGS; - if (!isfinite(eps_l2) || !isfinite(eps_norm) || !isfinite(in_scale) || !isfinite(out_scale)) return OMEGA_GPU_GDN_BAD_ARGS; - if (((qkv_va | z_va | out_va | xstride | ostride) & 15u) || ((ab_va | abstride) & 7u)) return OMEGA_GPU_GDN_BAD_ARGS; - OmegaGdnSpec spec; memset(&spec, 0, sizeof spec); - spec.mutant = g_k.mutant; spec.ratio = g->ratio; - /* caller holds the session lock */ - if (!dev_open_locked()) return OMEGA_GPU_GDN_CHIP_FAIL; - Slot *ks = NULL; bool hit = false; - g_rec = 1; - int rc = kernel_for(KK_MULTI, &spec, &ks, &hit); - g_rec = 0; - if (rc != OMEGA_GPU_GDN_OK) return rc; - uint32_t args[OMEGA_GDN_MULTI_ARGS_WORDS]; -#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, z_va); A64(4, ab_va); - A64(6, g->par.va + (uint64_t)layer * g->sh.par_bytes); A64(8, g->tail.va + (uint64_t)layer * g->sh.tail_bytes); - A64(10, g->state.va + (uint64_t)layer * g->sh.state_bytes); A64(12, out_va); -#undef A64 - memcpy(&args[14], &eps_l2, 4); memcpy(&args[15], &eps_norm, 4); memcpy(&args[16], &in_scale, 4); memcpy(&args[17], &out_scale, 4); - args[18] = tokens; args[19] = xstride; args[20] = abstride; args[21] = ostride; - OmegaGpuLaunch L = { - .code_va = ks->code.va, .gpr_count = omega_bw_gpr_declared(ks->kernel.gpr_count), - .threads_x = OMEGA_GDN_THREADS, .threads_y = 1, .grid_x = g->sh.r, .grid_y = OMEGA_GDN_GRID_Y, - .num_elements = (size_t)g->sh.vdim, - .args = args, .n_args = OMEGA_GDN_MULTI_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = OMEGA_GDN_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_GDN_CHIP_FAIL; } - return omega_gpu_cmdlist_add(cl, &L) < 0 ? OMEGA_GPU_GDN_CHIP_FAIL : OMEGA_GPU_GDN_OK; -} - -int omega_gpu_gdn_read_out(OmegaGpuGdn *g, float *out) { - if (!g || !out) return OMEGA_GPU_GDN_BAD_ARGS; - omega_gpu_session_lock(); - int rc = omega_gpu_session_sync_to_cpu(&g->lb) == 0 ? OMEGA_GPU_GDN_OK : OMEGA_GPU_GDN_CHIP_FAIL; - if (rc == OMEGA_GPU_GDN_OK) memcpy(out, (const uint8_t *)g->lb.cpu + LB_OUT, g->sh.vdim * 4u); - omega_gpu_session_unlock(); - return rc; -} - -/* ---- prefill (omega#543) ---- */ -/* scratch sections for T tokens (bytes, 256-aligned): qkv [T][10240] | z [T][6144] | ab [T][48][2] | out [T][6144] | - * o [T][6144] | records [T rounded up to 8][48] */ -enum { PF_QKV, PF_Z, PF_AB, PF_OUT, PF_O, PF_REC, PF_N }; -static size_t pf_layout(const OmegaGdnShape *shp, uint32_t T, size_t off[PF_N]) { - const uint64_t T8 = ((uint64_t)T + OMEGA_GDN_SCAN_CHUNK - 1u) / OMEGA_GDN_SCAN_CHUNK * OMEGA_GDN_SCAN_CHUNK; - const uint64_t sz[PF_N] = { (uint64_t)T * shp->conv * 4u, (uint64_t)T * shp->vdim * 4u, (uint64_t)T * shp->vh * 8u, - (uint64_t)T * shp->vdim * 4u, (uint64_t)T * shp->vdim * 4u, T8 * shp->vh * OMEGA_GDN_REC_BYTES }; - size_t at = 0; - for (unsigned i = 0; i < PF_N; i++) { off[i] = at; at += (size_t)((sz[i] + 255u) & ~(uint64_t)255u); } - return at; -} - -int omega_gpu_gdn_prefill_reserve(OmegaGpuGdn *g, uint32_t max_tokens) { - if (!g || max_tokens < OMEGA_GDN_PF_MIN_T || max_tokens > OMEGA_GPU_GDN_PF_MAX_T) return OMEGA_GPU_GDN_BAD_ARGS; - size_t off[PF_N]; - const size_t bytes = pf_layout(&g->sh, max_tokens, off); - omega_gpu_session_lock(); - int rc = OMEGA_GPU_GDN_OK; - if (!dev_open_locked()) rc = OMEGA_GPU_GDN_CHIP_FAIL; - else { - omega_gpu_session_scratch_unreserve(&g->pf); - if (omega_gpu_session_scratch_reserve(&g->pf, bytes) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - } - omega_gpu_session_unlock(); - return rc; -} - -/* rec non-NULL (record path, caller holds the lock): the inputs are device rows, the scratch must already hold T - * tokens (omega_gpu_gdn_prefill_reserve), the three launches are appended to rec. */ -static int pf_core(OmegaGpuGdn *g, uint32_t layer, uint32_t T, const float *qkv, const float *z, const float *ab, float eps_l2, - float eps_norm, float in_scale, float out_scale, float *out, OmegaGpuGdnPfInfo *info, - OmegaGpuCmdList *rec, uint64_t dev_qkv, uint64_t dev_z, uint64_t dev_ab, uint64_t *out_va) { - uint64_t c0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - if (!g || layer >= g->layers || T < OMEGA_GDN_PF_MIN_T || T > OMEGA_GPU_GDN_PF_MAX_T) return OMEGA_GPU_GDN_BAD_ARGS; - if (rec ? (!dev_qkv || !dev_z || !dev_ab) : (!qkv || !z || !ab || !out)) return OMEGA_GPU_GDN_BAD_ARGS; - if (!isfinite(eps_l2) || !isfinite(eps_norm) || !isfinite(in_scale) || !isfinite(out_scale)) return OMEGA_GPU_GDN_BAD_ARGS; - OmegaGdnSpec spec; memset(&spec, 0, sizeof spec); - spec.mutant = g_k.mutant; - spec.ratio = g->ratio; - spec.state_bf16 = (uint32_t)g->bf16; - size_t off[PF_N]; - const size_t bytes = pf_layout(&g->sh, T, off); - - if (!rec) omega_gpu_session_lock(); -#define UNLOCK() do { if (!rec) omega_gpu_session_unlock(); } while (0) - if (!dev_open_locked()) { UNLOCK(); return OMEGA_GPU_GDN_CHIP_FAIL; } - if (rec && (!g->pf.mem.cpu || g->pf.cap < bytes)) { - omega_gpu_session_set_error("gdn prefill record: scratch below T tokens (call omega_gpu_gdn_prefill_reserve first)"); - UNLOCK(); return OMEGA_GPU_GDN_TOO_LARGE; - } - if (!rec && omega_gpu_session_scratch(&g->pf, bytes) != 0) { UNLOCK(); return OMEGA_GPU_GDN_TOO_LARGE; } - Slot *ks[3] = { NULL, NULL, NULL }; - int rc = OMEGA_GPU_GDN_OK, hits = 0; - g_rec = rec != NULL; - for (unsigned k = 0; k < 3 && rc == OMEGA_GPU_GDN_OK; k++) { bool hit = false; rc = kernel_for(KK_PREP + k, &spec, &ks[k], &hit); hits += hit; } - g_rec = 0; - if (rc != OMEGA_GPU_GDN_OK) { UNLOCK(); return rc; } - uint8_t *b = g->pf.mem.cpu; - const uint64_t va = g->pf.mem.va; - float *yo = (float *)(b + off[PF_OUT]); - const size_t nout = (size_t)T * g->sh.vdim; - if (!rec) { - memcpy(b + off[PF_QKV], qkv, (size_t)T * g->sh.conv * 4u); - memcpy(b + off[PF_Z], z, nout * 4u); - memcpy(b + off[PF_AB], ab, (size_t)T * g->sh.vh * 8u); - for (size_t i = 0; i < nout; i++) yo[i] = POISON_F32; - if (omega_gpu_session_sync_to_gpu(&g->pf.mem) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - } - const uint64_t a_qkv = rec ? dev_qkv : va + off[PF_QKV], a_z = rec ? dev_z : va + off[PF_Z], a_ab = rec ? dev_ab : va + off[PF_AB]; - const uint64_t a_par = g->par.va + (uint64_t)layer * g->sh.par_bytes, a_tail = g->tail.va + (uint64_t)layer * g->sh.tail_bytes; - const uint64_t a_state = g->state.va + (uint64_t)layer * g->sh.state_bytes, a_rec = va + off[PF_REC], a_o = va + off[PF_O]; - const uint64_t a_out = va + off[PF_OUT]; - uint32_t ap[OMEGA_GDN_PREP_ARGS_WORDS], as[OMEGA_GDN_SCAN_ARGS_WORDS], aq[OMEGA_GDN_POST_ARGS_WORDS]; -#define A64(arr, i, v) do { (arr)[i] = (uint32_t)(v); (arr)[(i) + 1] = (uint32_t)((v) >> 32); } while (0) - A64(ap, 0, a_qkv); A64(ap, 2, a_ab); A64(ap, 4, a_par); A64(ap, 6, a_tail); A64(ap, 8, a_rec); - ap[10] = T; memcpy(&ap[11], &eps_l2, 4); memcpy(&ap[12], &in_scale, 4); - A64(as, 0, a_rec); A64(as, 2, a_qkv); A64(as, 4, a_tail); A64(as, 6, a_state); A64(as, 8, a_o); - as[10] = T; memcpy(&as[11], &in_scale, 4); - A64(aq, 0, a_o); A64(aq, 2, a_z); A64(aq, 4, a_par); A64(aq, 6, a_out); - memcpy(&aq[8], &eps_norm, 4); memcpy(&aq[9], &in_scale, 4); memcpy(&aq[10], &out_scale, 4); -#undef A64 - const uint32_t thr[3] = { OMEGA_GDN_PREP_THREADS, OMEGA_GDN_THREADS, OMEGA_GDN_THREADS }; - const uint32_t gx[3] = { (T + OMEGA_GDN_PREP_TOKENS - 1u) / OMEGA_GDN_PREP_TOKENS, g->sh.r, T }; - const uint32_t gy[3] = { OMEGA_GDN_KEY_HEADS, OMEGA_GDN_GRID_Y, g->sh.post_grid_y }; - const uint32_t sh[3] = { OMEGA_GDN_PREP_SHARED_BYTES, OMEGA_GDN_SCAN_SHARED_BYTES, 0 }; - const uint32_t *args[3] = { ap, as, aq }; - const uint32_t nargs[3] = { OMEGA_GDN_PREP_ARGS_WORDS, OMEGA_GDN_SCAN_ARGS_WORDS, OMEGA_GDN_POST_ARGS_WORDS }; - if (info) { - info->layer = layer; info->tokens = T; info->kernel_cache_hits = (uint32_t)hits; - for (unsigned k = 0; k < 3; k++) { info->insns[k] = ks[k]->insns; info->gprs[k] = ks[k]->kernel.gpr_count; } - } - for (unsigned k = 0; k < 3 && rc == OMEGA_GPU_GDN_OK; k++) { - OmegaGpuLaunch L = { - .code_va = ks[k]->code.va, .gpr_count = omega_bw_gpr_declared(ks[k]->kernel.gpr_count), - .threads_x = thr[k], .threads_y = 1, .grid_x = gx[k], .grid_y = gy[k], - .num_elements = nout, - .args = args[k], .n_args = nargs[k], .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = sh[k], - }; - if (!omega_bw_gpr_declared_ok(L.gpr_count, ks[k]->kernel.gpr_count)) { omega_gpu_session_set_error("declared registers below peak + 2: refusing to launch"); rc = OMEGA_GPU_GDN_CHIP_FAIL; } - else if (rec) { if (omega_gpu_cmdlist_add(rec, &L) < 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; } - else if (omega_gpu_session_launch(&L, info ? &info->elapsed_ns[k] : NULL, NULL) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - } - if (rc == OMEGA_GPU_GDN_OK && !rec && omega_gpu_session_sync_to_cpu(&g->pf.mem) != 0) rc = OMEGA_GPU_GDN_CHIP_FAIL; - if (rc == OMEGA_GPU_GDN_OK && !rec) { - size_t unchanged = 0; - for (size_t i = 0; i < nout; i++) if (yo[i] == POISON_F32) unchanged++; - if (unchanged) { omega_gpu_session_set_error("gdn prefill: output poison survived"); rc = OMEGA_GPU_GDN_CHIP_FAIL; } - else memcpy(out, yo, nout * 4u); - } - if (rc == OMEGA_GPU_GDN_OK && out_va) *out_va = a_out; - UNLOCK(); -#undef UNLOCK - if (info) info->call_ns = omega_gpu_session_now_ns() - c0; - return rc; -} - -int omega_gpu_gdn_prefill(OmegaGpuGdn *g, uint32_t layer, uint32_t tokens, const float *qkv, const float *z, const float *ab, - float eps_l2, float eps_norm, float in_scale, float out_scale, float *out, OmegaGpuGdnPfInfo *info) { - return pf_core(g, layer, tokens, qkv, z, ab, eps_l2, eps_norm, in_scale, out_scale, out, info, NULL, 0, 0, 0, NULL); -} - -int omega_gpu_gdn_prefill_record(OmegaGpuCmdList *cl, OmegaGpuGdn *g, uint32_t layer, uint32_t tokens, uint64_t qkv_va, - uint64_t z_va, uint64_t ab_va, float eps_l2, float eps_norm, float in_scale, float out_scale, - uint64_t *out_va) { - if (!cl) return OMEGA_GPU_GDN_BAD_ARGS; - return pf_core(g, layer, tokens, NULL, NULL, NULL, eps_l2, eps_norm, in_scale, out_scale, NULL, NULL, cl, qkv_va, z_va, ab_va, out_va); -} - -int omega_gpu_gdn_prefill_read_out(OmegaGpuGdn *g, uint32_t tokens, float *out) { - if (!g || !out || tokens < OMEGA_GDN_PF_MIN_T || tokens > OMEGA_GPU_GDN_PF_MAX_T) return OMEGA_GPU_GDN_BAD_ARGS; - size_t off[PF_N]; - const size_t bytes = pf_layout(&g->sh, tokens, off); - omega_gpu_session_lock(); - int rc = (!g->pf.mem.cpu || g->pf.cap < bytes) ? OMEGA_GPU_GDN_BAD_ARGS - : omega_gpu_session_sync_to_cpu(&g->pf.mem) == 0 ? OMEGA_GPU_GDN_OK : OMEGA_GPU_GDN_CHIP_FAIL; - if (rc == OMEGA_GPU_GDN_OK) memcpy(out, (const uint8_t *)g->pf.mem.cpu + off[PF_OUT], (size_t)tokens * g->sh.vdim * 4u); - omega_gpu_session_unlock(); - return rc; -} diff --git a/src/omega_gpu_gdn_api.h b/src/omega_gpu_gdn_api.h deleted file mode 100644 index cbb53e51f..000000000 --- a/src/omega_gpu_gdn_api.h +++ /dev/null @@ -1,137 +0,0 @@ -#ifndef OMEGA_GPU_GDN_API_H -#define OMEGA_GPU_GDN_API_H -/* - * omega_gpu_gdn_api: the Gated DeltaNet decode step of Qwen3.8-27B in one launch per layer (omega#542, 2026-10-18). - * The kernel is described in omega_blackwell_codegen_gdn.h; the maths is sc qwen38.rs `delta_net`. - * - * int omega_gpu_gdn_alloc(uint32_t layers, OmegaGpuGdn **out); - * Device-resident per-layer parameters, conv tails and recurrent states (zeroed), plus the launch buffer. - * The tails and states are GPU-cached (2026-10-19; AIEN_OMEGA_GDN_STATE_CACHED=0 keeps them uncached): the host - * never touches them directly, reset zeroes them with a chip launch and set_state / get_state copy one layer through - * an uncached staging buffer with chip launches (omega_blackwell_codegen_gdn.h, state copy / zero). - * int omega_gpu_gdn_set_layer(OmegaGpuGdn *g, uint32_t layer, const float *conv_w, const float *a_log, - * const float *dt_bias, const float *norm_w); - * conv_w: linear_attn.conv1d.weight [10240][1][4] widened to f32 ([10240][4]); a_log, dt_bias: [48]; - * norm_w: linear_attn.norm.weight [128]. negA = -exp(a_log) is computed here (double, libm-free omega_hostmath_exp, rounded to float). - * int omega_gpu_gdn_set_state / omega_gpu_gdn_get_state(OmegaGpuGdn *g, uint32_t layer, float *tail, float *state); - * The reference layouts: tail [3][10240] (oldest first, qwen38.rs conv_tail), state [48][128 k][128 v]. - * get_state refuses (CHIP_FAIL) when the three per-head copies of a key head's q/k tail disagree. - * int omega_gpu_gdn_reset(OmegaGpuGdn *g); every layer's tail and state to zero (a new sequence) - * int omega_gpu_gdn_step(OmegaGpuGdn *g, uint32_t layer, const float *qkv, const float *z, const float *ab, - * float eps_l2, float eps_norm, float in_scale, float out_scale, float *out, - * OmegaGpuGdnInfo *info); - * qkv [10240] and z [6144] are the in_proj outputs (times 1 / in_scale: the kernel multiplies them by in_scale); - * ab [48][2] = {a[h], b[h]}: the in_proj_a and in_proj_b rows stacked interleaved (row 2h = a_h, 2h + 1 = b_h) - * give it from one bf16 GEMV. out [6144] = the out_proj input times out_scale. Updates the layer's tail and - * state on the device. eps_l2 is 1e-6 in the reference; eps_norm is rms_norm_eps. - * int omega_gpu_gdn_record(cl, g, layer, qkv_va, z_va, ab_va, eps_l2, eps_norm, in_scale, out_scale, &out_va); - * The same launch appended to a command list (caller holds omega_gpu_session_lock()); inputs are device - * addresses, out lands in the launch buffer (out_va). A kernel cache miss that would evict is refused. - * - * Every buffer is GPU-uncached host-visible session memory (nvos.h:1117 rule), launched through - * omega_gpu_session_launch like the router. The output is poisoned before the launch; a surviving poison word is - * CHIP_FAIL. - */ -#include "omega_blackwell_codegen_gdn.h" -#include -#include - -enum { - OMEGA_GPU_GDN_OK = 0, - OMEGA_GPU_GDN_BAD_ARGS = -1, - OMEGA_GPU_GDN_TOO_LARGE = -2, - OMEGA_GPU_GDN_CODEGEN_FAIL = -3, - OMEGA_GPU_GDN_CHIP_FAIL = -4 -}; - -#define OMEGA_GPU_GDN_MAX_LAYERS 64u -#define OMEGA_GPU_GDN_TAIL_FLOATS (3u * OMEGA_GDN_CONV_DIM) /* reference tail */ -#define OMEGA_GPU_GDN_STATE_FLOATS (OMEGA_GDN_VALUE_HEADS * OMEGA_GDN_HEAD_DIM * OMEGA_GDN_HEAD_DIM) /* 786432 */ - -typedef struct OmegaGpuGdn OmegaGpuGdn; - -typedef struct { - uint32_t layer, threads, grid_x, grid_y, insns, gprs; - uint64_t state_bytes; /* state bytes read and written: 2 * 48 * 128 * 128 * 4 */ - uint64_t elapsed_ns; /* marker-to-marker chip time */ - uint64_t call_ns; /* whole call */ - uint32_t completion_marker; - int kernel_cache_hit; -} OmegaGpuGdnInfo; - -int omega_gpu_gdn_alloc(uint32_t layers, OmegaGpuGdn **out); -/* Q36 (sc L306): the same with value heads per key head `ratio` (OmegaGdnSpec.ratio: 0 = 3, Qwen3.8-27B, the plain alloc; - * 2 = Qwen3.6-35B-A3B). Every size the other calls use (conv dim, value width, tail, state, parameter block, prefill - * rows) follows the ratio; the comments elsewhere in this header give the ratio-3 numbers. */ -int omega_gpu_gdn_alloc_ratio(uint32_t layers, uint32_t ratio, OmegaGpuGdn **out); -void omega_gpu_gdn_free(OmegaGpuGdn *g); -int omega_gpu_gdn_set_layer(OmegaGpuGdn *g, uint32_t layer, const float *conv_w, const float *a_log, const float *dt_bias, - const float *norm_w); -int omega_gpu_gdn_reset(OmegaGpuGdn *g); -int omega_gpu_gdn_set_state(OmegaGpuGdn *g, uint32_t layer, const float *tail, const float *state); -int omega_gpu_gdn_get_state(OmegaGpuGdn *g, uint32_t layer, float *tail, float *state); -int omega_gpu_gdn_step(OmegaGpuGdn *g, uint32_t layer, const float *qkv, const float *z, const float *ab, float eps_l2, - float eps_norm, float in_scale, float out_scale, float *out, OmegaGpuGdnInfo *info); -struct OmegaGpuCmdList; -int omega_gpu_gdn_record(struct OmegaGpuCmdList *cl, OmegaGpuGdn *g, uint32_t layer, uint64_t qkv_va, uint64_t z_va, - uint64_t ab_va, float eps_l2, float eps_norm, float in_scale, float out_scale, uint64_t *out_va); -/* Test helper: the out row the last launch wrote to the launch buffer (after a record + submit, for example). */ -int omega_gpu_gdn_read_out(OmegaGpuGdn *g, float *out); -const char *omega_gpu_gdn_last_error(void); -const char *omega_gpu_gdn_rc_name(int rc); - -/* ---- multi-token decode (L369, 2026-10-21): T decode steps of layer `layer` in ONE launch, bit for bit the decode step - * T times (omega_blackwell_codegen_gdn.h, multi-token decode). Token t reads qkv_va + t * xstride, z_va + t * xstride, - * ab_va + t * abstride and writes its [vdim] output row at out_va + t * ostride (bytes; 16-byte aligned rows, 8 for ab). - * int omega_gpu_gdn_multi_prepare(g); builds the kernel now (the record path refuses a kernel cache miss) - * int omega_gpu_gdn_multi_record(cl, g, layer, T, qkv_va, z_va, xstride, ab_va, abstride, out_va, ostride, eps_l2, - * eps_norm, in_scale, out_scale); appended to cl; the caller holds the session lock */ -int omega_gpu_gdn_multi_prepare(OmegaGpuGdn *g); -int omega_gpu_gdn_multi_record(struct OmegaGpuCmdList *cl, OmegaGpuGdn *g, uint32_t layer, uint32_t tokens, uint64_t qkv_va, - uint64_t z_va, uint32_t xstride, uint64_t ab_va, uint32_t abstride, uint64_t out_va, uint32_t ostride, - float eps_l2, float eps_norm, float in_scale, float out_scale); - -/* ---- prefill (omega#543, 2026-10-18): T >= 3 new tokens of one layer in three launches (prep, scan, post; see - * omega_blackwell_codegen_gdn.h), continuing from the layer's tail and state exactly as T decode steps would, and leaving - * them where the next prefill chunk or decode step picks them up. A long prompt is prefilled in chunks. - * int omega_gpu_gdn_prefill(g, layer, T, qkv [T][10240], z [T][6144], ab [T][48][2], eps_l2, eps_norm, in_scale, - * out_scale, out [T][6144], info); the decode step's row layouts, one row per token - * int omega_gpu_gdn_prefill_reserve(g, max_tokens); sizes the prefill scratch now and pins it (the record path needs - * it: a recorded launch must never see its scratch move); a later prefill of more tokens is refused - * int omega_gpu_gdn_prefill_record(cl, g, layer, T, qkv_va, z_va, ab_va, eps_l2, eps_norm, in_scale, out_scale, &out_va); - * the three launches appended to a command list (caller holds the lock); out_va = the [T][6144] rows in the scratch - * Scratch bytes for T tokens: T * (40960 + 3 * 24576 + 384) + ceil8(T) * 74496 (the per-token records dominate). */ -#define OMEGA_GPU_GDN_PF_MAX_T 65536u - -typedef struct { - uint32_t layer, tokens; - uint32_t insns[3], gprs[3]; /* prep, scan, post */ - uint64_t elapsed_ns[3]; /* marker-to-marker chip time per launch (host path) */ - uint64_t call_ns; - uint32_t kernel_cache_hits; /* 0..3 */ -} OmegaGpuGdnPfInfo; - -int omega_gpu_gdn_prefill(OmegaGpuGdn *g, uint32_t layer, uint32_t tokens, const float *qkv, const float *z, const float *ab, - float eps_l2, float eps_norm, float in_scale, float out_scale, float *out, OmegaGpuGdnPfInfo *info); -int omega_gpu_gdn_prefill_reserve(OmegaGpuGdn *g, uint32_t max_tokens); -int omega_gpu_gdn_prefill_record(struct OmegaGpuCmdList *cl, OmegaGpuGdn *g, uint32_t layer, uint32_t tokens, uint64_t qkv_va, - uint64_t z_va, uint64_t ab_va, float eps_l2, float eps_norm, float in_scale, float out_scale, - uint64_t *out_va); -/* Test helper: the out rows the last prefill wrote (after a record + submit). */ -int omega_gpu_gdn_prefill_read_out(OmegaGpuGdn *g, uint32_t tokens, float *out); - -/* Host layout helpers (no device; the test's simulator path uses them too). */ -/* The parameter block (OMEGA_GDN_PAR_BYTES) from the checkpoint tensors (see set_layer). -1 on a NULL pointer. */ -int omega_gdn_pack_params(const float *conv_w, const float *a_log, const float *dt_bias, const float *norm_w, uint8_t *block); -/* reference tail [3][10240] <-> device tail [48][384][4] (unpack: the q/k channels from head 3 * hk; -1 when the - * three copies of a key head disagree bit for bit) */ -void omega_gdn_pack_tail(const float *tail, float *dev); -int omega_gdn_unpack_tail(const float *dev, float *tail); -/* The same for a ratio (see omega_gpu_gdn_alloc_ratio); -1 on an unsupported ratio. */ -int omega_gdn_pack_params_r(uint32_t ratio, const float *conv_w, const float *a_log, const float *dt_bias, const float *norm_w, uint8_t *block); -int omega_gdn_pack_tail_r(uint32_t ratio, const float *tail, float *dev); -int omega_gdn_unpack_tail_r(uint32_t ratio, const float *dev, float *tail); - -void omega_gpu_gdn_test_set_mutant(int mutant); /* TEST ONLY: OmegaGdnSpec.mutant; clears the kernel cache */ - -#endif diff --git a/src/omega_gpu_gemm.c b/src/omega_gpu_gemm.c deleted file mode 100644 index 42b47a7d6..000000000 --- a/src/omega_gpu_gemm.c +++ /dev/null @@ -1,381 +0,0 @@ -/* omega_gpu_gemm.c -- matrix multiply of any shape on the GB10 tensor cores (C3). See the header. */ -#include "omega_gpu_gemm.h" -#include "omega_bw_em.h" -#include "omega_bw_em_q.h" -#include "omega_gpu_session.h" - -#include -#include - -#define POISON 0x7fa00badu /* a signalling NaN no tensor-core op writes: a word still holding it was never stored */ -#define TIMEOUT_MS 60000ull -#define FRAG 512u /* bytes of one warp fragment: 32 lanes x 16 */ - -static uint32_t esz(OmegaGpuGemmType t) { return t == OMEGA_GPU_GEMM_BF16 ? 2u : 1u; } -static uint32_t kstep(OmegaGpuGemmType t) { return t == OMEGA_GPU_GEMM_BF16 ? 16u : 32u; } -static int pow124(uint32_t v) { return v == 1u || v == 2u || v == 4u; } - -void omega_gpu_gemm_default_cfg(OmegaGpuGemmType type, OmegaGemmCfg *cfg) { - memset(cfg, 0, sizeof *cfg); - cfg->type = type; cfg->rt = 2; cfg->ct = 4; cfg->wm = 2; cfg->wn = 2; cfg->stall = type == OMEGA_GPU_GEMM_BF16 ? 4u : 2u; -} - -int omega_gpu_gemm_cfg_ok(const OmegaGemmCfg *c) { - return c && (c->type == OMEGA_GPU_GEMM_BF16 || c->type == OMEGA_GPU_GEMM_E4M3) && pow124(c->rt) && pow124(c->ct) && - pow124(c->wm) && pow124(c->wn) && c->stall >= 1u && c->stall <= 15u && c->mutant >= 0 && c->mutant <= 3 && - 4u * (4u * c->rt + 2u * c->ct + c->rt * c->ct) <= 100u; /* registers: two operand sets + accumulators, R2..R127 in all */ -} - -/* ------------------------------------------------------------------ IR helpers */ - -typedef struct { int bssy, bra; } Region; -static 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); } -/* d = a - b */ -static void isub(Em *e, int d, int a, int b) { imadi(e, d, b, 0, 0xffffffffu, a); } -/* d = 1 when a < b (both below 2^31), else 0 */ -static void lt_bit(Em *e, int d, int a, int b) { isub(e, d, a, b); shr(e, d, d, 0, 31); } -static void and_r(Em *e, int d, int a, int b) { lop3(e, d, a, b, NOREG, 0xc0u); } -/* tensor-core op d = a * b[bsub..bsub+1] + c */ -static void mma(Em *e, int fp8, 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; - if (fp8) 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; -} - -/* ------------------------------------------------------------------ PACK_A / PACK_B - * CTA (pair cx, row group cy), 128 threads; thread tid writes word tid of each of the F fragments of the block: - * lane L = tid / 4, register q = tid % 4, g = L / 4, t = L % 4, r = elements per register (2 bf16, 4 e4m3). - * A fragment f = u * rt + i: row 16 (rt cy + i) + g + 8 (q & 1), k = 2 step cx + step u + r t + 4 r (q >> 1) - * B fragment f = j: row 8 (ct cy + j) + g, k = 2 step cx + step (q >> 1) + r t + 4 r (q & 1) - * Element (row, k) of the source is at (row * row_stride + k * k_stride) * esz; past rows or kdim it is 0. */ -static int gen_pack(Em *e, const OmegaGemmCfg *c, int isb) { - const int fp8 = c->type == OMEGA_GPU_GEMM_E4M3; - const uint32_t ks = kstep(c->type), r = 4u / esz(c->type), F = isb ? c->ct : 2u * c->rt; - int udesc = UV64(e), psrc = V64(e), pdst = V64(e), R = V(e), Kd = V(e), sr = V(e), sk = V(e), ks2 = V(e); - int tid = V(e), cx = V(e), cy = V(e), one = V(e), g = V(e), t = V(e), qa = V(e), qb = V(e), row0 = V(e), k0 = V(e); - int tmp = V(e), pd = V64(e), row = V(e), vrow = V(e), rowoff = V(e), kx = V(e), v = V(e), off = V(e), word = V(e); - int addr[4], val[4], mask[4], odd[4]; - for (unsigned x = 0; x < 4; x++) { addr[x] = V64(e); val[x] = V(e); mask[x] = V(e); odd[x] = V(e); } - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, psrc, 0x380); ldc64(e, pdst, 0x388); - ldc32(e, R, 0x390); ldc32(e, Kd, 0x394); ldc32(e, sr, 0x398); ldc32(e, sk, 0x39c); ldc32(e, ks2, 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, g, tid, 0, 4); - shr(e, t, tid, 0, 2); andi(e, t, t, 0, 3); - andi(e, qa, tid, 0, 1); - shr(e, qb, tid, 0, 1); andi(e, qb, qb, 0, 1); - if (!isb) { - imadi(e, row0, cy, 0, 16u * c->rt, g); imadi(e, row0, qa, 0, 8u, row0); - imadi(e, k0, cx, 0, 2u * ks, NOREG); imadi(e, k0, t, 0, r, k0); imadi(e, k0, qb, 0, 4u * r, k0); - } else { - imadi(e, row0, cy, 0, 8u * c->ct, g); - imadi(e, k0, cx, 0, 2u * ks, NOREG); imadi(e, k0, t, 0, r, k0); imadi(e, k0, qb, 0, ks, k0); imadi(e, k0, qa, 0, 4u * r, k0); - } - /* this thread's word of fragment 0: ((cy * KS2 + cx) * F * 128 + tid) words */ - imadr(e, tmp, cy, ks2, cx); imadi(e, tmp, tmp, 0, F * 128u, tid); imadw(e, pd, tmp, 4u, pdst); - for (uint32_t f = 0; f < F; f++) { - const uint32_t drow = isb ? 8u * f : 16u * (f % c->rt), dk = isb ? 0u : ks * (f / c->rt); - imadi(e, row, one, 0, drow, row0); - lt_bit(e, vrow, row, R); - imadr(e, rowoff, row, sr, NOREG); - for (uint32_t x = 0; x < r; x++) { - imadi(e, kx, one, 0, dk + x, k0); - lt_bit(e, v, kx, Kd); - and_r(e, v, v, vrow); - imadr(e, off, kx, sk, rowoff); - imadr(e, off, off, v, NOREG); /* outside: element 0, always readable, then masked */ - if (c->mutant == 2) movi(e, mask[x], 0xffffffffu); /* the red check: element 0 leaks in past the edges */ - else imadi(e, mask[x], v, 0, 0xffffffffu, NOREG); - if (fp8) { andi(e, odd[x], off, 0, 1u); andi(e, off, off, 0, 0xfffffffeu); imadw(e, addr[x], off, 1u, psrc); } - else imadw(e, addr[x], off, 2u, psrc); - } - for (uint32_t x = 0; x < r; x++) ldg_wide(e, BW_IR_LDG_E_U16, val[x], addr[x], 0, udesc, x == 0); - for (uint32_t x = 0; x < r; x++) { - if (fp8) { /* the byte at off: low or high half of the u16 */ - andi(e, kx, val[x], 0, 0xffu); - shr(e, v, val[x], 0, 8); andi(e, v, v, 0, 0xffu); - isub(e, v, v, kx); - imadr(e, val[x], v, odd[x], kx); - } - and_r(e, val[x], val[x], mask[x]); - } - imadi(e, word, val[0], 0, 1u, NOREG); - for (uint32_t x = 1; x < r; x++) imadi(e, word, val[x], 0, 1u << (x * (32u / r)), word); - stg(e, pd, f * FRAG, word, udesc); - } - tail(e); - return e->err; -} - -/* ------------------------------------------------------------------ MAIN */ -static int gen_main(Em *e, const OmegaGemmCfg *c) { - const int fp8 = c->type == OMEGA_GPU_GEMM_E4M3; - const uint32_t RT = c->rt, CT = c->ct, FA = 2u * RT, FB = CT; - int udesc = UV64(e), pa = V64(e), pb = V64(e), pc = V64(e), M = V(e), N = V(e), ks2 = V(e); - int tid = V(e), cx = V(e), cy = V(e), warp = V(e), lane = V(e), g = V(e), t = V(e), one = V(e), zr = V(e); - int rga = V(e), rgb = V(e), tmp = V(e), cnt = V(e); - int acc[16], as[2][8], bs[2][4]; - for (uint32_t x = 0; x < RT * CT; x++) acc[x] = V128(e); - for (unsigned s = 0; s < 2; s++) { for (uint32_t f = 0; f < FA; f++) as[s][f] = V128(e); for (uint32_t j = 0; j < FB; j++) bs[s][j] = V128(e); } - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pa, 0x380); ldc64(e, pb, 0x388); ldc64(e, pc, 0x390); - ldc32(e, M, 0x398); ldc32(e, N, 0x39c); ldc32(e, ks2, 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); movrz(e, zr); - shr(e, warp, tid, 0, 5); andi(e, lane, tid, 0, 31u); - /* warp (wm, wn) = (warp / WN, warp % WN); row groups rga = cy WM + wm, rgb = cx WN + wn */ - shr(e, tmp, warp, 0, (uint32_t)log2u(c->wn)); imadi(e, rga, cy, 0, c->wm, tmp); - andi(e, tmp, warp, 0, c->wn - 1u); imadi(e, rgb, cx, 0, c->wn, tmp); - imadr(e, tmp, rga, ks2, NOREG); imadw(e, pa, tmp, FA * FRAG, pa); - imadr(e, tmp, rgb, ks2, NOREG); imadw(e, pb, tmp, FB * FRAG, pb); - imadi(e, tmp, lane, 0, 16u, NOREG); imadw(e, pa, tmp, 1u, pa); imadw(e, pb, tmp, 1u, pb); - 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); } - shr(e, cnt, ks2, 0, 1); /* loop iterations: two k pairs each */ - - #define ISSUE(s, sb) do { \ - for (uint32_t f = 0; f < FA; f++) ldw_pf(e, BW_IR_LDG_E_128, as[s][f], pa, f * FRAG, udesc, (sb)); \ - for (uint32_t j = 0; j < FB; j++) ldw_pf(e, BW_IR_LDG_E_128, bs[s][j], pb, j * FRAG, udesc, (sb)); \ - imadw(e, pa, one, FA * FRAG, pa); imadw(e, pb, one, FB * FRAG, pb); } while (0) - #define COMPUTE(s) do { \ - for (uint32_t u = 0; u < 2; u++) { \ - if (c->mutant == 1 && u == 1) break; \ - for (uint32_t i = 0; i < RT; i++) for (uint32_t j = 0; j < CT; j++) \ - mma(e, fp8, acc[i * CT + j], as[s][u * RT + i], bs[s][j], 2u * u, acc[i * CT + j], c->stall); } } while (0) - - ISSUE(0, 3u); - const int top = here(e); - loop_begin(e); - ISSUE(1, 4u); - consume(e, 3); - COMPUTE(0); - nop(e, 15); /* the tensor ops have read set 0 before it is reloaded */ - ISSUE(0, 3u); /* the last iteration reads one pair past the end: slack */ - consume(e, 4); - COMPUTE(1); - nop(e, 15); - imadi(e, cnt, one, 0, 0xffffffffu, cnt); - isetp_ge_u32(e, cnt, one); - bra_if_p0(e, top); - loop_end(e); - #undef ISSUE - #undef COMPUTE - consume(e, 3); - nop(e, 15); nop(e, 15); nop(e, 15); nop(e, 15); /* the last results settle before the stores read them */ - - /* stores: C[m][n] for m = 16 (RT rga + i) + 8 h + g, n = 8 (CT rgb + j) + 2 t + cc, when m < M and n < N */ - int mb = V(e), nb = V(e), m = V(e), n = V(e), vm = V(e), vn = V(e), rowoff = V(e), ca = V64(e); - if (e->err) return -1; - shr(e, g, lane, 0, 2); andi(e, t, lane, 0, 3u); - imadi(e, mb, rga, 0, 16u * RT, g); - imadi(e, tmp, t, 0, 2u, NOREG); imadi(e, nb, rgb, 0, 8u * CT, tmp); - for (uint32_t i = 0; i < RT; i++) for (uint32_t h = 0; h < 2; h++) { - imadi(e, m, one, 0, 16u * i + 8u * h, mb); - lt_bit(e, vm, m, M); - imadr(e, rowoff, m, N, NOREG); - for (uint32_t j = 0; j < CT; j++) for (uint32_t cc = 0; cc < 2; cc++) { - imadi(e, n, one, 0, 8u * j + cc, nb); - lt_bit(e, vn, n, N); - and_r(e, vn, vn, vm); - isetp_ge_u32(e, zr, vn); /* P0: 0 >= ok, i.e. outside: skip */ - Region rg = skip_if_p0(e); - iadd(e, tmp, rowoff, n); imadw(e, ca, tmp, 4u, pc); - BlackwellIRInsn st = I0(BW_IR_STG_E); st.src1_vreg = ca; st.src2_vreg = acc[i * CT + j]; - st.src2_subreg = (uint8_t)(2u * h + (c->mutant == 3 ? 1u - cc : cc)); st.ureg = udesc; emit(e, st, K_STORE); - region_end(e, rg); - } - } - tail(e); - return e->err; -} - -int omega_gpu_gemm_codegen(const OmegaGemmCfg *cfg, OmegaGemmKind kind, BlackwellIRProgram *prog) { - if (!omega_gpu_gemm_cfg_ok(cfg) || !prog || (unsigned)kind >= OMEGA_GEMM_K_COUNT) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - int rc = kind == OMEGA_GEMM_K_MAIN ? gen_main(&em, cfg) : gen_pack(&em, cfg, kind == OMEGA_GEMM_K_PACK_B); - if (rc != 0 || em.err || em.depth != 0) return -1; - return omega_bw_regalloc_solve(prog); -} - -/* ------------------------------------------------------------------ plan and driver */ - -static uint32_t roundup(uint32_t v, uint32_t m) { return (v + m - 1u) / m * m; } - -int omega_gpu_gemm_plan(const OmegaGemmCfg *c, uint32_t M, uint32_t N, uint32_t K, OmegaGemmPlan *p) { - if (!omega_gpu_gemm_cfg_ok(c) || !p || !M || !N || !K) return OMEGA_GPU_GEMM_BAD_ARGS; - if (M > OMEGA_GPU_GEMM_MAX_DIM || N > OMEGA_GPU_GEMM_MAX_DIM || K > OMEGA_GPU_GEMM_MAX_DIM) return OMEGA_GPU_GEMM_TOO_LARGE; - memset(p, 0, sizeof *p); - const uint32_t ks = kstep(c->type), ga = 16u * c->rt, gb = 8u * c->ct, FA = 2u * c->rt, FB = c->ct; - p->Mp = roundup(M, ga * c->wm); p->Np = roundup(N, gb * c->wn); p->Kp = roundup(K, 4u * ks); - p->KS2 = p->Kp / (2u * ks); - p->a_bytes = (uint64_t)M * K * esz(c->type); p->b_bytes = (uint64_t)K * N * esz(c->type); - p->ap_bytes = (uint64_t)(p->Mp / ga) * p->KS2 * FA * FRAG + 2u * FA * FRAG; - p->bp_bytes = (uint64_t)(p->Np / gb) * p->KS2 * FB * FRAG + 2u * FB * FRAG; - p->grid[OMEGA_GEMM_K_PACK_A][0] = p->KS2; p->grid[OMEGA_GEMM_K_PACK_A][1] = p->Mp / ga; - p->grid[OMEGA_GEMM_K_PACK_B][0] = p->KS2; p->grid[OMEGA_GEMM_K_PACK_B][1] = p->Np / gb; - p->grid[OMEGA_GEMM_K_MAIN][0] = p->Np / (gb * c->wn); p->grid[OMEGA_GEMM_K_MAIN][1] = p->Mp / (ga * c->wm); - p->threads[OMEGA_GEMM_K_PACK_A] = p->threads[OMEGA_GEMM_K_PACK_B] = 128u; - p->threads[OMEGA_GEMM_K_MAIN] = 32u * c->wm * c->wn; - return OMEGA_GPU_GEMM_OK; -} - -static void put64(uint32_t *a, unsigned w, uint64_t v) { a[w] = (uint32_t)v; a[w + 1] = (uint32_t)(v >> 32); } - -int omega_gpu_gemm_drive(const OmegaGemmCfg *c, unsigned layout, uint32_t M, uint32_t N, uint32_t K, uint64_t a_va, - uint64_t b_va, uint64_t ap_va, uint64_t bp_va, uint64_t c_va, OmegaGemmLaunchFn launch, void *ctx) { - if (!launch || (layout & ~3u)) return OMEGA_GPU_GEMM_BAD_ARGS; - OmegaGemmPlan p; - int rc = omega_gpu_gemm_plan(c, M, N, K, &p); - if (rc != OMEGA_GPU_GEMM_OK) return rc; - uint32_t a[OMEGA_GPU_GEMM_ARGS_WORDS]; - /* A element (m, k): row-major m K + k, column-major k M + m */ - memset(a, 0, sizeof a); - put64(a, 0, a_va); put64(a, 2, ap_va); a[4] = M; a[5] = K; - a[6] = layout & OMEGA_GPU_GEMM_A_COL ? 1u : K; a[7] = layout & OMEGA_GPU_GEMM_A_COL ? M : 1u; a[8] = p.KS2; - if (launch(ctx, OMEGA_GEMM_K_PACK_A, a, p.grid[0][0], p.grid[0][1], p.threads[0]) != 0) return OMEGA_GPU_GEMM_CHIP_FAIL; - /* B element (k, n) as packed row n: row-major k N + n, column-major n K + k */ - memset(a, 0, sizeof a); - put64(a, 0, b_va); put64(a, 2, bp_va); a[4] = N; a[5] = K; - a[6] = layout & OMEGA_GPU_GEMM_B_COL ? K : 1u; a[7] = layout & OMEGA_GPU_GEMM_B_COL ? 1u : N; a[8] = p.KS2; - if (launch(ctx, OMEGA_GEMM_K_PACK_B, a, p.grid[1][0], p.grid[1][1], p.threads[1]) != 0) return OMEGA_GPU_GEMM_CHIP_FAIL; - memset(a, 0, sizeof a); - put64(a, 0, ap_va); put64(a, 2, bp_va); put64(a, 4, c_va); a[6] = M; a[7] = N; a[8] = p.KS2; - if (launch(ctx, OMEGA_GEMM_K_MAIN, a, p.grid[2][0], p.grid[2][1], p.threads[2]) != 0) return OMEGA_GPU_GEMM_CHIP_FAIL; - return OMEGA_GPU_GEMM_OK; -} - -/* ------------------------------------------------------------------ the chip */ - -static struct { - int set[2]; - OmegaGemmCfg cfg[2]; - OmegaGpuMem code[2][OMEGA_GEMM_K_COUNT]; - uint32_t gpr[2][OMEGA_GEMM_K_COUNT]; - int hooked; -} g; - -/* lock held; the session calls it right before it closes the device (also in omega_gpu_session_recover): the kernels go - * with the device, the next call builds them again on the new one */ -static void on_session_close(void) { - for (unsigned t = 0; t < 2; t++) - for (unsigned k = 0; k < OMEGA_GEMM_K_COUNT; k++) if (g.code[t][k].cpu) omega_gpu_session_free(&g.code[t][k]); - memset(g.code, 0, sizeof g.code); -} - -static const OmegaGemmCfg *cfg_of(OmegaGpuGemmType t) { - if (!g.set[t]) { omega_gpu_gemm_default_cfg(t, &g.cfg[t]); g.set[t] = 1; } - return &g.cfg[t]; -} - -int omega_gpu_gemm_test_set_cfg(OmegaGpuGemmType type, const OmegaGemmCfg *cfg) { - if ((unsigned)type > OMEGA_GPU_GEMM_E4M3 || (cfg && (!omega_gpu_gemm_cfg_ok(cfg) || cfg->type != type))) return OMEGA_GPU_GEMM_BAD_ARGS; - omega_gpu_session_lock(); - for (unsigned k = 0; k < OMEGA_GEMM_K_COUNT; k++) if (g.code[type][k].cpu) omega_gpu_session_free(&g.code[type][k]); - memset(g.code[type], 0, sizeof g.code[type]); - if (cfg) g.cfg[type] = *cfg; else omega_gpu_gemm_default_cfg(type, &g.cfg[type]); - g.set[type] = 1; - omega_gpu_session_unlock(); - return OMEGA_GPU_GEMM_OK; -} - -const char *omega_gpu_gemm_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_GEMM_OK: return "OK"; - case OMEGA_GPU_GEMM_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_GEMM_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_GEMM_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_GEMM_CHIP_FAIL: return "CHIP_FAIL"; - default: return "?"; - } -} - -/* lock held */ -static int kernel_locked(OmegaGpuGemmType t, OmegaGemmKind k) { - if (g.code[t][k].cpu) return OMEGA_GPU_GEMM_OK; - if (!g.hooked) { /* without the hook a kernel would outlive its device */ - if (omega_gpu_session_on_close(on_session_close) != 0) return OMEGA_GPU_GEMM_CHIP_FAIL; - g.hooked = 1; - } - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) return OMEGA_GPU_GEMM_CODEGEN_FAIL; - int rc = OMEGA_GPU_GEMM_OK; - size_t need = 0; - if (omega_gpu_gemm_codegen(cfg_of(t), k, prog) != 0 || (need = omega_bw_program_code_bytes(prog)) == 0) rc = OMEGA_GPU_GEMM_CODEGEN_FAIL; - else if (omega_gpu_session_alloc_code(need, &g.code[t][k]) != 0) rc = OMEGA_GPU_GEMM_CHIP_FAIL; - else { - OmegaBlackwellKernel kk; - if (omega_blackwell_kernel_encode_into(prog, g.code[t][k].cpu, need, &kk) != 0 || kk.code_size != need || - omega_qmma_patch_code(prog, g.code[t][k].cpu, need) < 0) rc = OMEGA_GPU_GEMM_CODEGEN_FAIL; - else if ((g.gpr[t][k] = omega_bw_gpr_declared(kk.gpr_count)) > 255u) rc = OMEGA_GPU_GEMM_CODEGEN_FAIL; - else if (omega_gpu_session_sync_to_gpu(&g.code[t][k]) != 0) rc = OMEGA_GPU_GEMM_CHIP_FAIL; - if (g.gpr[t][k] < 64u) g.gpr[t][k] = 64u; - if (rc != OMEGA_GPU_GEMM_OK) { omega_gpu_session_free(&g.code[t][k]); memset(&g.code[t][k], 0, sizeof g.code[t][k]); } - } - if (rc == OMEGA_GPU_GEMM_CODEGEN_FAIL) omega_gpu_session_set_error("gemm: our codegen refused a kernel"); - omega_gpu_host_free(prog); - return rc; -} - -typedef struct { OmegaGpuGemmType t; uint64_t pack_ns, main_ns; } ChipCtx; - -/* lock held */ -static int chip_launch(void *ctx, OmegaGemmKind k, const uint32_t args[OMEGA_GPU_GEMM_ARGS_WORDS], uint32_t gx, uint32_t gy, uint32_t threads) { - ChipCtx *c = ctx; - if (kernel_locked(c->t, k) != OMEGA_GPU_GEMM_OK) return -1; - OmegaGpuLaunch L = { - .code_va = g.code[c->t][k].va, .gpr_count = g.gpr[c->t][k], .threads_x = threads, .threads_y = 1, - .grid_x = gx, .grid_y = gy, .num_elements = (size_t)gx * gy * threads, - .args = args, .n_args = OMEGA_GPU_GEMM_ARGS_WORDS, .timeout_ms = TIMEOUT_MS, - }; - uint64_t ns = 0; - if (omega_gpu_session_launch(&L, &ns, NULL) != 0) return -1; - if (k == OMEGA_GEMM_K_MAIN) c->main_ns += ns; else c->pack_ns += ns; - return 0; -} - -static uint64_t up16(uint64_t v) { return (v + 255u) & ~(uint64_t)255u; } - -int omega_gpu_gemm(OmegaGpuGemmType type, unsigned layout, uint32_t M, uint32_t N, uint32_t K, const void *A, const void *B, - float *C, OmegaGpuGemmInfo *info) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - if ((unsigned)type > OMEGA_GPU_GEMM_E4M3 || (layout & ~3u) || !A || !B || !C) return OMEGA_GPU_GEMM_BAD_ARGS; - omega_gpu_session_lock(); - const OmegaGemmCfg *cfg = cfg_of(type); - OmegaGemmPlan p; - int rc = omega_gpu_gemm_plan(cfg, M, N, K, &p); - if (rc != OMEGA_GPU_GEMM_OK) { omega_gpu_session_unlock(); return rc; } - /* one buffer: A | B | packed A | packed B | C (each 256-byte aligned; A and B carry 16 bytes of readable slack) */ - const uint64_t oa = 0, ob = up16(p.a_bytes + 16u), oap = ob + up16(p.b_bytes + 16u), obp = oap + up16(p.ap_bytes), - oc = obp + up16(p.bp_bytes), total = oc + (uint64_t)M * N * 4u; - OmegaGpuMem m; - if (!omega_gpu_session_open() || omega_gpu_session_alloc(total, &m) != 0) { omega_gpu_session_unlock(); return OMEGA_GPU_GEMM_CHIP_FAIL; } - uint8_t *base = m.cpu; - memcpy(base + oa, A, p.a_bytes); memcpy(base + ob, B, p.b_bytes); - uint32_t *cw = (uint32_t *)(base + oc); - for (uint64_t i = 0; i < (uint64_t)M * N; i++) cw[i] = POISON; - ChipCtx cc = { type, 0, 0 }; - if (omega_gpu_session_sync_to_gpu(&m) != 0) rc = OMEGA_GPU_GEMM_CHIP_FAIL; - else rc = omega_gpu_gemm_drive(cfg, layout, M, N, K, m.va + oa, m.va + ob, m.va + oap, m.va + obp, m.va + oc, chip_launch, &cc); - if (rc == OMEGA_GPU_GEMM_OK && omega_gpu_session_sync_to_cpu(&m) != 0) rc = OMEGA_GPU_GEMM_CHIP_FAIL; - if (rc == OMEGA_GPU_GEMM_OK) { - uint64_t unwritten = 0; - for (uint64_t i = 0; i < (uint64_t)M * N; i++) unwritten += cw[i] == POISON; - if (unwritten) { omega_gpu_session_set_error("gemm: output words never written"); rc = OMEGA_GPU_GEMM_CHIP_FAIL; } - else memcpy(C, cw, (size_t)M * N * 4u); - } - if (info) { - info->pack_ns = cc.pack_ns; info->main_ns = cc.main_ns; - for (unsigned k = 0; k < OMEGA_GEMM_K_COUNT; k++) info->gpr[k] = g.gpr[type][k]; - } - omega_gpu_session_free(&m); - omega_gpu_session_unlock(); - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} diff --git a/src/omega_gpu_gemm.h b/src/omega_gpu_gemm.h deleted file mode 100644 index 66a6b0485..000000000 --- a/src/omega_gpu_gemm.h +++ /dev/null @@ -1,96 +0,0 @@ -/* omega_gpu_gemm.h -- matrix multiply of any shape on the GB10 tensor cores (row C3 of docs/OMEGA.md). - * - * C = A * B A is M x K, B is K x N, C is M x N f32 (row-major), every M, N, K from 1 to OMEGA_GPU_GEMM_MAX_DIM - * BF16: A and B hold bf16 values, the product runs on HMMA.16816.F32.BF16 - * E4M3: A and B hold FP8 e4m3 bytes, the product runs on QMMA.16832.F32.E4M3.E4M3 - * Layouts: A row-major (M rows of K) or column-major (K rows of M); B row-major (K rows of N) or column-major (N rows of K). - * - * The arithmetic is fixed by the shape alone: every C[m][n] starts at +0 and takes one tensor-core step per 16 (BF16) or - * 32 (E4M3) values of k, in increasing k, k past K counting as zero. The rounding of one step is the chip-measured model - * (tests/bw_hmma_model.h { 16, 2, RZ, 2, 0 }, tests/bw_qmma_model.h { 32, 26, RZ, 2, 0 }), so a host model of the same - * steps reproduces the chip bit for bit (tests/gpu_gemm_test.c). - * - * Kernels, all from Omega's own code generator (no CUDA): - * PACK_A, PACK_B copy A and B, whatever their layout, into the tensor cores' fragment order (each lane's operand - * registers are 16 contiguous bytes; a warp's fragment is 512 contiguous bytes), zero past the edges. - * MAIN each warp computes a 16 rt x 8 ct block of C from the packed operands (LDG.128 straight into the - * operand registers, two register sets so the next loads fly while the tensor cores work), a CTA holds - * wm x wn warps; edge elements past M or N are not stored. - * Packed operand layout (bytes): block (row group, k pair) at ((group * KS2 + pair) * F + f) * 512, lane L at + 16 L, where - * a k pair is two tensor-core steps, KS2 = Kp / (2 * step), F = 2 rt (A: f = u * rt + i, step u of the pair, row tile i) - * or ct (B: f = column tile j; registers 0, 1 step 0 and 2, 3 step 1). */ -#ifndef OMEGA_GPU_GEMM_H -#define OMEGA_GPU_GEMM_H - -#include -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_GPU_GEMM_MAX_DIM 16384u - -enum { - OMEGA_GPU_GEMM_OK = 0, - OMEGA_GPU_GEMM_BAD_ARGS = -1, /* NULL pointer, a zero dimension, unknown type or layout bits, a bad configuration */ - OMEGA_GPU_GEMM_TOO_LARGE = -2, /* a dimension past OMEGA_GPU_GEMM_MAX_DIM */ - OMEGA_GPU_GEMM_CODEGEN_FAIL = -3, /* our codegen refused a kernel */ - OMEGA_GPU_GEMM_CHIP_FAIL = -4 /* device, allocation, launch, or an output word the chip never wrote */ -}; - -typedef enum { OMEGA_GPU_GEMM_BF16 = 0, OMEGA_GPU_GEMM_E4M3 = 1 } OmegaGpuGemmType; -#define OMEGA_GPU_GEMM_A_COL 1u /* A is column-major: K rows of M */ -#define OMEGA_GPU_GEMM_B_COL 2u /* B is column-major: N rows of K */ - -typedef enum { OMEGA_GEMM_K_PACK_A = 0, OMEGA_GEMM_K_PACK_B, OMEGA_GEMM_K_MAIN, OMEGA_GEMM_K_COUNT } OmegaGemmKind; - -/* rt row tiles of 16 and ct column tiles of 8 per warp (1, 2 or 4 each), wm x wn warps per CTA (1, 2 or 4 each), - * with 4 (4 rt + 2 ct + rt ct) <= 100 (the registers of two operand sets and the accumulators; rt 2 ct 4 is the largest), - * stall: issue cycles after each tensor-core op (1 .. 15). - * mutant (red checks): 1 MAIN drops the second step of every k pair, 2 the packs let element 0 in past the edges (instead of zero), - * 3 MAIN stores each column pair swapped. */ -typedef struct { OmegaGpuGemmType type; uint32_t rt, ct, wm, wn, stall; int mutant; } OmegaGemmCfg; -void omega_gpu_gemm_default_cfg(OmegaGpuGemmType type, OmegaGemmCfg *cfg); -int omega_gpu_gemm_cfg_ok(const OmegaGemmCfg *cfg); - -/* Argument words (constant bank 0x380). Packs: src u64, dst u64, rows, kdim, row stride, k stride (elements), KS2. - * MAIN: packed A u64, packed B u64, C u64, M, N, KS2. */ -#define OMEGA_GPU_GEMM_ARGS_WORDS 9u -int omega_gpu_gemm_codegen(const OmegaGemmCfg *cfg, OmegaGemmKind kind, BlackwellIRProgram *prog); - -typedef struct { - uint32_t Mp, Np, Kp, KS2; /* padded sizes; KS2 k pairs (even) */ - uint64_t a_bytes, b_bytes; /* the inputs as given */ - uint64_t ap_bytes, bp_bytes; /* the packed operands, slack for the last prefetch included */ - uint32_t grid[OMEGA_GEMM_K_COUNT][2]; - uint32_t threads[OMEGA_GEMM_K_COUNT]; -} OmegaGemmPlan; -int omega_gpu_gemm_plan(const OmegaGemmCfg *cfg, uint32_t M, uint32_t N, uint32_t K, OmegaGemmPlan *plan); - -/* Runs the three kernels through a launch callback (the chip, or the warp simulator in the test). Device addresses - * are plain numbers. */ -typedef int (*OmegaGemmLaunchFn)(void *ctx, OmegaGemmKind kind, const uint32_t args[OMEGA_GPU_GEMM_ARGS_WORDS], - uint32_t grid_x, uint32_t grid_y, uint32_t threads); -int omega_gpu_gemm_drive(const OmegaGemmCfg *cfg, unsigned layout, uint32_t M, uint32_t N, uint32_t K, uint64_t a_va, - uint64_t b_va, uint64_t ap_va, uint64_t bp_va, uint64_t c_va, OmegaGemmLaunchFn launch, void *ctx); - -typedef struct { - uint64_t pack_ns; /* the two pack kernels, launch to completion */ - uint64_t main_ns; /* the multiply kernel */ - uint64_t call_ns; /* the whole call, uploads and readback included */ - uint32_t gpr[OMEGA_GEMM_K_COUNT]; -} OmegaGpuGemmInfo; - -/* On the chip, with the configuration set by omega_gpu_gemm_test_set_cfg (default: omega_gpu_gemm_default_cfg). */ -int omega_gpu_gemm(OmegaGpuGemmType type, unsigned layout, uint32_t M, uint32_t N, uint32_t K, const void *A, const void *B, - float *C, OmegaGpuGemmInfo *info); -/* Tests and tuning: later calls of that type use cfg (NULL: back to the default); clears the kernel cache. */ -int omega_gpu_gemm_test_set_cfg(OmegaGpuGemmType type, const OmegaGemmCfg *cfg); -const char *omega_gpu_gemm_rc_name(int rc); - -#ifdef __cplusplus -} -#endif -#endif /* OMEGA_GPU_GEMM_H */ diff --git a/src/omega_gpu_hostmath.c b/src/omega_gpu_hostmath.c deleted file mode 100644 index c1af7a178..000000000 --- a/src/omega_gpu_hostmath.c +++ /dev/null @@ -1,107 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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; - } -} - -float omega_hostmath_pow2f(int e) { - uint32_t u; - if (e > 127) u = 0x7f800000u; /* +inf */ - else if (e >= -126) u = (uint32_t)(e + 127) << 23; /* normal: biased exponent, zero mantissa */ - else if (e >= -149) u = 1u << (e + 149); /* subnormal: one mantissa bit */ - else u = 0; - float f; memcpy(&f, &u, 4); return f; -} diff --git a/src/omega_gpu_hostmath.h b/src/omega_gpu_hostmath.h deleted file mode 100644 index 48f1be7de..000000000 --- a/src/omega_gpu_hostmath.h +++ /dev/null @@ -1,39 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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. - * pow2f(e): 2^e as f32, exact (built from the bit pattern) for -149 <= e <= 127; 0 below, +inf above. - * Replaces ldexpf(1.0f, e) (omega-mv#471). - */ -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); -float omega_hostmath_pow2f(int e); -#endif diff --git a/src/omega_gpu_matmul_api.c b/src/omega_gpu_matmul_api.c deleted file mode 100644 index b2885b546..000000000 --- a/src/omega_gpu_matmul_api.c +++ /dev/null @@ -1,656 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 e0c00adf7..000000000 --- a/src/omega_gpu_mem_cached.c +++ /dev/null @@ -1,40 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 3aaa42243..000000000 --- a/src/omega_gpu_mem_cached.h +++ /dev/null @@ -1,38 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 d5e57dcdf..000000000 --- a/src/omega_gpu_moe_api.c +++ /dev/null @@ -1,440 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 db6f5d46b..000000000 --- a/src/omega_gpu_moe_api.h +++ /dev/null @@ -1,132 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 1172458fe..000000000 --- a/src/omega_gpu_pfgemm.c +++ /dev/null @@ -1,241 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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_cmdlist.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); } -/* cl non-NULL: record (caller holds the lock) instead of launch */ -static int pq_core(OmegaGpuCmdList *cl, 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; - const uint32_t kb = k / 128u; - if (k % 128u == 0 && kb > 32u) for (s.groups = 32u; kb % s.groups; s.groups--) {} /* wide row: split over ctaid.y */ - const uint32_t g = s.groups ? s.groups : kb, gy = s.groups ? kb / s.groups : 1u; - 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) }; - if (!cl) 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 = cl ? omega_gpu_pf_record_locked(cl, &kern, 32u * g, rows, gy, 0, args, OMEGA_PQ_ARGS_WORDS) - : omega_gpu_pf_launch_locked(&kern, 32u * g, rows, gy, 0, args, OMEGA_PQ_ARGS_WORDS, ns); - if (!cl) omega_gpu_session_unlock(); - return rc; -} -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) { - return pq_core(NULL, k, in_type, rows, x_va, q_va, s_va, ns); -} -int omega_gpu_pf_quant_record(OmegaGpuCmdList *cl, uint32_t k, uint32_t in_type, uint32_t rows, uint64_t x_va, uint64_t q_va, uint64_t s_va) { - if (!cl) return OMEGA_GPU_PF_BAD_ARGS; - return pq_core(cl, k, in_type, rows, x_va, q_va, s_va, NULL); -} - -/* ---- 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); } - -static int qg_core(OmegaGpuCmdList *cl, 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; - if (!cl) 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 = cl ? omega_gpu_pf_record_locked(cl, &kern, 32u * s.warps, n / span, ntiles, omega_qg_shared_bytes(&s), args, OMEGA_QG_ARGS_WORDS) - : omega_gpu_pf_launch_locked(&kern, 32u * s.warps, n / span, ntiles, omega_qg_shared_bytes(&s), args, OMEGA_QG_ARGS_WORDS, ns); - if (!cl) omega_gpu_session_unlock(); - return rc; -} -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) { - return qg_core(NULL, n, k, layout, tiles_va, ntiles, rowidx_va, xq_va, xs_va, y_va, ns); -} -int omega_gpu_pf_qgemm_record(OmegaGpuCmdList *cl, 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) { - if (!cl) return OMEGA_GPU_PF_BAD_ARGS; - return qg_core(cl, n, k, layout, tiles_va, ntiles, rowidx_va, xq_va, xs_va, y_va, NULL); -} diff --git a/src/omega_gpu_pfhost.c b/src/omega_gpu_pfhost.c deleted file mode 100644 index 59fff7bc6..000000000 --- a/src/omega_gpu_pfhost.c +++ /dev/null @@ -1,75 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 64662d767..000000000 --- a/src/omega_gpu_pfhost.h +++ /dev/null @@ -1,53 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 4c8e59b93..000000000 --- a/src/omega_gpu_platform.c +++ /dev/null @@ -1,208 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 fe4427fc6..000000000 --- a/src/omega_gpu_platform.h +++ /dev/null @@ -1,267 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 4096u /* 1.1: a serving session holds one buffer per weight tensor (Qwen3-8B: ~260); - * speed5/batching: each Qwen3.8 conversation slot adds about 29 (16 KV planes, the - * DeltaNet state, launch buffers), so 32 slots on top of the 27B weights passed 1024 */ - -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 23f046209..000000000 --- a/src/omega_gpu_platform_linux.c +++ /dev/null @@ -1,454 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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; - /* L136: extra queues on extra channels of the same channel group (nvrm_channel_n), opened only when - * AIEN_OMEGA_GPU_CHANNELS > 1 at device_open; queue 0 above is unchanged. */ - uint32_t nchan; - OmegaGpuQueueHandle xq[NVRM_MAX_EXTRA_CHANNELS]; - NvrmMem xring[NVRM_MAX_EXTRA_CHANNELS]; - uint8_t x_l2_pending[NVRM_MAX_EXTRA_CHANNELS]; - 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 = 1u + NVRM_MAX_EXTRA_CHANNELS, /* queues past the first need AIEN_OMEGA_GPU_CHANNELS (L136) */ - .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; -} - -uint32_t omega_gpu_platform_linux_channels_env(void) { - const char *e = getenv("AIEN_OMEGA_GPU_CHANNELS"); - if (!e || e[1] != '\0' || e[0] < '2' || e[0] > (char)('1' + NVRM_MAX_EXTRA_CHANNELS)) return 1u; - return (uint32_t)(e[0] - '0'); -} - -/* Extra queue slot of q (0..nchan-2), or -1 when q is not an open extra queue. Caller holds r->mu. */ -static int xq_slot(const LinuxRef *r, OmegaGpuQueueHandle q) { - for (uint32_t i = 0; i + 1u < r->nchan; i++) - if (r->xq[i].generation != 0u && r->xq[i].index == q.index && r->xq[i].generation == q.generation) return (int)i; - return -1; -} - -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; - } - r->nchan = omega_gpu_platform_linux_channels_env(); - if (r->nchan == 1u ? m16_native_create_channel(&r->m16) != 0 : nvrm_channel_n(&r->m16.rm, r->nchan - 1u) != 0) { - rc = refuse(r, OMEGA_GPU_PLAT_REFUSED_DEVICE, r->nchan == 1u ? "m16_native_create_channel" : "nvrm_channel_n"); - (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); - memset(r->xq, 0, sizeof r->xq); memset(r->xring, 0, sizeof r->xring); memset(r->x_l2_pending, 0, sizeof r->x_l2_pending); - r->nchan = 0; - /* C5: the driver's close result is the proof that this process's channels (and any grid still on them) are gone. - * The state above is closed either way; a teardown fault is reported so omega_gpu_session_recover stays latched. */ - rc = m16_native_close(&r->m16) == 0 ? OMEGA_GPU_PLAT_OK : refuse(r, OMEGA_GPU_PLAT_REFUSED_DEVICE, "device_close (driver teardown fault)"); - ref_unlock(r); - return rc; -} - -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 */ - for (uint32_t i = 0; rc == OMEGA_GPU_PLAT_OK && i + 1u < r->nchan; i++) - if (r->xq[i].generation != 0u && r->xring[i].handle == r->mem[b.index].handle) rc = OMEGA_GPU_PLAT_REFUSED_BUSY; - 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; memset(r->x_l2_pending, 1, sizeof r->x_l2_pending); } - 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; - /* queue 0 first (channel 0); then, with AIEN_OMEGA_GPU_CHANNELS > 1, one queue per extra channel (L136) */ - int slot = -1; - if (rc == OMEGA_GPU_PLAT_OK && r->queue.generation != 0u) { - for (uint32_t i = 0; i + 1u < r->nchan && slot < 0; i++) if (r->xq[i].generation == 0u) slot = (int)i; - if (slot < 0) rc = OMEGA_GPU_PLAT_REFUSED_LIMIT; - } - if (rc == OMEGA_GPU_PLAT_OK) rc = omega_gpu_handles_open(&r->t, OMEGA_GPU_HANDLE_QUEUE, 0, r->nchan, 0, &out->index, &out->generation); /* one queue per channel (L136: nchan is 1 unless AIEN_OMEGA_GPU_CHANNELS) */ - if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "queue_open"); ref_unlock(r); return rc; } - if (slot >= 0) { r->xring[slot] = r->mem[ring.index]; r->xq[slot] = *out; r->x_l2_pending[slot] = (uint8_t)r->l2_inval_pending; ref_unlock(r); return OMEGA_GPU_PLAT_OK; } - 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; } - const int slot = xq_slot(r, q); - if (slot >= 0) { memset(&r->xq[slot], 0, sizeof r->xq[slot]); memset(&r->xring[slot], 0, sizeof r->xring[slot]); ref_unlock(r); return OMEGA_GPU_PLAT_OK; } - 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; - const int slot = rc == OMEGA_GPU_PLAT_OK ? xq_slot(r, q) : -1; - if (slot >= 0) { - /* an extra channel: the same #457 prefix rule (its own pending flag), the same copy-to-ring-offset-0 + one GP - * entry + doorbell as m16_native_submit_methods, on channel slot + 1 */ - NvrmMem *ring = &r->xring[slot]; - const uint32_t xpre = r->x_l2_pending[slot] ? L2_INVAL_PREFIX_WORDS : 0u; - if (((uint64_t)nwords + xpre) * 4u > ring->size) rc = OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - else { - uint32_t *dst = ring->cpu; - if (xpre) memcpy(dst, L2_INVAL_PREFIX, sizeof L2_INVAL_PREFIX); - memcpy(dst + xpre, words, (size_t)nwords * 4u); - __asm__ volatile("dsb sy" ::: "memory"); - if (nvrm_chan_submit(&r->m16.rm, (uint32_t)slot + 1u, ring, 0, nwords + xpre) != 0) rc = OMEGA_GPU_PLAT_REFUSED_DEVICE; - else r->x_l2_pending[slot] = 0; - } - if (rc != OMEGA_GPU_PLAT_OK) rc = refuse(r, rc, "submit_methods (extra channel)"); - ref_unlock(r); - return rc; - } - /* 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); - const int slot = rc == OMEGA_GPU_PLAT_OK ? xq_slot(r, q) : -1; - if (slot >= 0) nvrm_chan_retire(&r->m16.rm, (uint32_t)slot + 1u, nvrm_chan_put(&r->m16.rm, (uint32_t)slot + 1u)); - else 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 cee1b961d..000000000 --- a/src/omega_gpu_platform_linux.h +++ /dev/null @@ -1,61 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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); - -/* L136: channels (GPFIFO queues) the next device_open creates, from env AIEN_OMEGA_GPU_CHANNELS: 1 (unset, empty, "1" or - * anything not 2..4) is today's single channel exactly; 2..4 adds that many minus one channels in the same channel group - * (nvrm_channel_n). Queue i (0-based, in queue_open order) submits on channel i. Read at every device_open. */ -uint32_t omega_gpu_platform_linux_channels_env(void); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_prefill.c b/src/omega_gpu_prefill.c deleted file mode 100644 index b286e6378..000000000 --- a/src/omega_gpu_prefill.c +++ /dev/null @@ -1,196 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 "omega_gpu_cmdlist.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; -} - -int omega_gpu_pf_record_locked(OmegaGpuCmdList *cl, 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) { - if (!cl || !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 record: 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 record"); 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 }; - return omega_gpu_cmdlist_add(cl, &L) < 0 ? OMEGA_GPU_PF_CHIP_FAIL : 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 8879c6b27..000000000 --- a/src/omega_gpu_prefill.h +++ /dev/null @@ -1,128 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 */ -/* lock held: the same launch appended to a command list (omega_gpu_cmdlist.h) instead of submitted (sc #642: a whole Qwen3.8 - * prefill chunk is one list). Prefill kernels are never evicted, so a recorded launch's code stays valid until the submit. */ -struct OmegaGpuCmdList; -int omega_gpu_pf_record_locked(struct OmegaGpuCmdList *cl, 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); - -/* ---- 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); -/* Record paths (sc #642): the same launches appended to cl; the caller holds omega_gpu_session_lock(). A first use compiles the - * kernel there (prefill kernels are never evicted). */ -struct OmegaGpuCmdList; -int omega_gpu_pf_quant_record(struct OmegaGpuCmdList *cl, uint32_t k, uint32_t in_type, uint32_t rows, uint64_t x_va, uint64_t q_va, uint64_t s_va); -int omega_gpu_pf_qgemm_record(struct OmegaGpuCmdList *cl, 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); -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_attn256_api.c b/src/omega_gpu_prefill_attn256_api.c deleted file mode 100644 index 7b9fcd22c..000000000 --- a/src/omega_gpu_prefill_attn256_api.c +++ /dev/null @@ -1,246 +0,0 @@ -/* - * omega_gpu_prefill_attn256_api.c: the two launches of the head_dim 256 prefill attention (omega-mv#545; see the - * header). The prep kernel is the decode kernel's own program in prep mode (omega_blackwell_codegen_attn256.h), the - * attend kernel is omega_blackwell_codegen_pattn256.h; it uses the SHFL.BFLY / F2FP placeholders of - * omega_blackwell_codegen_tc.h, so its code is patched after encoding and the patch count must equal the program's - * placeholder count. Session use mirrors omega_gpu_prefill_attn_api.c. - */ -#include "omega_gpu_prefill_attn256_api.h" -#include "omega_blackwell_codegen_tc.h" -#include "omega_gpu_session.h" -#include "omega_gpu_cmdlist.h" -#include - -#define MARKER_TIMEOUT_MS 60000ull -#define POISON_F32 (-999.0f) -enum { KK_PREP, KK_ATTEND, KK_N }; - -typedef struct { - bool valid; - union { OmegaDecodeAttn256Spec prep; OmegaPrefillAttn256Spec att; } spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; - uint32_t insns; -} Slot; - -static struct { - bool hooked; - Slot slot[KK_N]; - int prep_mut, att_mut; - OmegaGpuMem qf; size_t qf_size; bool have_qf; /* q' scratch */ - OmegaGpuMem qkv, out; size_t qkv_size, out_size; bool have_bufs; /* host-entry staging */ -} g; - -static void bufs_forget(void) { g.have_qf = false; g.qf_size = 0; g.have_bufs = false; g.qkv_size = g.out_size = 0; } -static void on_session_close(void) { memset(g.slot, 0, sizeof g.slot); bufs_forget(); } -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 void slots_clear_locked(void) { - for (unsigned k = 0; k < KK_N; k++) { if (g.slot[k].valid) omega_gpu_session_free(&g.slot[k].code); memset(&g.slot[k], 0, sizeof g.slot[k]); } -} -void omega_gpu_prefill_attn256_test_set_mutant(int prep_mutant, int attend_mutant) { - omega_gpu_session_lock(); g.prep_mut = prep_mutant; g.att_mut = attend_mutant; slots_clear_locked(); omega_gpu_session_unlock(); -} -void omega_gpu_prefill_attn256_release(void) { - omega_gpu_session_lock(); - if (g.have_qf) omega_gpu_session_free(&g.qf); - if (g.have_bufs) { omega_gpu_session_free(&g.qkv); omega_gpu_session_free(&g.out); } - bufs_forget(); - omega_gpu_session_unlock(); -} - -/* sh: the cache's head shape (q_heads / kv_heads / q_per_cta; NULL = the 27B) */ -static void spec_of(unsigned kind, const uint32_t *sh, Slot *tmp) { - memset(tmp, 0, sizeof *tmp); - if (kind == KK_PREP) { - tmp->spec.prep.depth = OMEGA_GPU_DATTN256_DEPTH; tmp->spec.prep.mutant = g.prep_mut; tmp->spec.prep.prep = 1; - if (sh) { tmp->spec.prep.q_heads = sh[0]; tmp->spec.prep.kv_heads = sh[1]; tmp->spec.prep.q_per_cta = sh[2]; } - } else { - tmp->spec.att.mutant = g.att_mut; - if (sh) { tmp->spec.att.q_heads = sh[0]; tmp->spec.att.kv_heads = sh[1]; } - } -} -static int prog_of(unsigned kind, const Slot *tmp, BlackwellIRProgram *prog) { - return kind == KK_PREP ? omega_blackwell_codegen_decode_attn256_prog(&tmp->spec.prep, prog) - : omega_blackwell_codegen_prefill_attn256_prog(&tmp->spec.att, prog); -} -static uint32_t placeholders_of(const BlackwellIRProgram *prog) { - uint32_t n = 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)) n++; - } - return n; -} - -size_t omega_gpu_prefill_attn256_encode(unsigned kind, uint8_t *code, size_t cap, uint32_t *gprs, int *patched) { - if (kind >= KK_N) return 0; - Slot tmp; spec_of(kind, NULL, &tmp); - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) return 0; - size_t need = 0; - if (prog_of(kind, &tmp, 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; - const int ok = np >= 0 && (uint32_t)np == placeholders_of(prog); - omega_gpu_host_free(prog); - return ok ? need : 0; -} - -/* rec: a record call is running (lock held): a miss is refused instead of compiled */ -static int kernel_for(unsigned kind, const uint32_t *sh, int rec, Slot **out, bool *hit) { - Slot tmp; spec_of(kind, sh, &tmp); - Slot *s = &g.slot[kind]; - if (s->valid && memcmp(&s->spec, &tmp.spec, sizeof tmp.spec) == 0) { *out = s; *hit = true; return OMEGA_GPU_DATTN_OK; } - if (rec) { omega_gpu_session_set_error("prefill attn256 record: kernel cache miss (warm up before recording)"); return OMEGA_GPU_DATTN_TOO_LARGE; } - 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 attn256 codegen: host memory"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } - int cg = prog_of(kind, &tmp, 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 attn256 codegen refused the spec"); return OMEGA_GPU_DATTN_CODEGEN_FAIL; } - /* both launches run 256 threads per CTA: the declared registers must fit the 64K register file (CUDA Programming - * Guide, Compute Capabilities: "maximum number of 32-bit registers per thread block is 64K") */ - if ((uint64_t)OMEGA_PATTN256_THREADS * omega_bw_gpr_declared(prog->regalloc.peak_gpr_usage) > 65536u) { omega_gpu_host_free(prog); omega_gpu_session_set_error("prefill attn256: register file"); return OMEGA_GPU_DATTN_TOO_LARGE; } - const uint32_t expect = placeholders_of(prog), insns = (uint32_t)prog->count; - 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 attn256 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 attn256: 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 = tmp.spec; s->kernel = kernel; s->code = code; s->insns = insns; - *out = s; *hit = false; - return OMEGA_GPU_DATTN_OK; -} - -/* q heads: a token pair of q' takes q_heads * 1024 bytes (OMEGA_PATTN256_QF_OFF_SHAPE) */ -static size_t qf_bytes(uint32_t rows, uint32_t q_heads) { return (size_t)((rows + 1u) / 2u) * q_heads * 1024u; } -static int qf_locked(size_t need) { - if (g.have_qf && g.qf_size >= need) return 0; - if (g.have_qf) { omega_gpu_session_free(&g.qf); g.have_qf = false; g.qf_size = 0; } - if (omega_gpu_session_alloc(need, &g.qf) != 0) return -1; - g.have_qf = true; g.qf_size = need; - return 0; -} -int omega_gpu_prefill_attn256_reserve(uint32_t max_m) { return omega_gpu_prefill_attn256_reserve_for(NULL, max_m); } -int omega_gpu_prefill_attn256_reserve_for(const OmegaGpuDecodeAttn256Cache *c, uint32_t max_m) { - if (max_m == 0 || max_m > OMEGA_GPU_PATTN256_MAX_M) return OMEGA_GPU_DATTN_BAD_ARGS; - OmegaGpuDecodeAttn256CacheView v; - if (c && omega_gpu_decode_attn256_cache_view(c, 0, &v) != OMEGA_GPU_DATTN_OK) return OMEGA_GPU_DATTN_BAD_ARGS; - const uint32_t shv[3] = { c ? v.q_heads : OMEGA_DATTN256_Q_HEADS, c ? v.kv_heads : OMEGA_DATTN256_KV_HEADS, c ? v.q_per_cta : OMEGA_DATTN256_Q_PER_KV }; - const uint32_t *sh = c ? shv : NULL; - omega_gpu_session_lock(); - int rc = dev_open_locked() && qf_locked(qf_bytes(max_m, shv[0])) == 0 ? OMEGA_GPU_DATTN_OK : OMEGA_GPU_DATTN_CHIP_FAIL; - /* and builds both kernels, so a record call after reserve never misses the cache (sc #642 prefill graph) */ - for (unsigned k = 0; k < KK_N && rc == OMEGA_GPU_DATTN_OK; k++) { Slot *s = NULL; bool hit = false; rc = kernel_for(k, sh, 0, &s, &hit); } - omega_gpu_session_unlock(); - return rc; -} -static int bufs_locked(size_t qkv_size, size_t out_size) { - if (g.have_bufs && g.qkv_size >= qkv_size && g.out_size >= out_size) return 0; - if (g.have_bufs) { omega_gpu_session_free(&g.qkv); omega_gpu_session_free(&g.out); g.have_bufs = false; g.qkv_size = g.out_size = 0; } - if (omega_gpu_session_alloc(qkv_size, &g.qkv) != 0) return -1; - if (omega_gpu_session_alloc(out_size, &g.out) != 0) { omega_gpu_session_free(&g.qkv); return -1; } - g.have_bufs = true; g.qkv_size = qkv_size; g.out_size = out_size; - return 0; -} - -/* host != 0: qkv / out are host arrays staged through the module buffers (poison-checked); else qkv_va / out_va are - * device buffers. rec non-NULL: record path (lock held, nothing allocated, compiled or submitted). */ -static int core(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, const float *qkv, float *out, - uint64_t qkv_va, uint64_t out_va, float eps, float out_scale, OmegaGpuPrefillAttn256Info *info, OmegaGpuCmdList *rec) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - const int host = qkv != NULL; - OmegaGpuDecodeAttn256CacheView v; - if (!c || m == 0 || m > OMEGA_GPU_PATTN256_MAX_M || omega_gpu_decode_attn256_cache_view(c, layer, &v) != OMEGA_GPU_DATTN_OK || - pos0 > v.max_pos || m > v.max_pos - pos0 || (host ? !out : (!qkv_va || !out_va || (qkv_va & 15u) || (out_va & 15u)))) return OMEGA_GPU_DATTN_BAD_ARGS; - const uint32_t sh[3] = { v.q_heads, v.kv_heads, v.q_per_cta }, QKVW = v.qkv_words, OUTW = v.out_words; - if (!rec) omega_gpu_session_lock(); -#define UNLOCK() do { if (!rec) omega_gpu_session_unlock(); } while (0) - if (!dev_open_locked()) { UNLOCK(); return OMEGA_GPU_DATTN_CHIP_FAIL; } - Slot *ks[KK_N] = { NULL, NULL }; bool hit[KK_N] = { false, false }; - int rc = OMEGA_GPU_DATTN_OK; - for (unsigned k = 0; k < KK_N && rc == OMEGA_GPU_DATTN_OK; k++) rc = kernel_for(k, sh, rec != NULL, &ks[k], &hit[k]); - if (rc != OMEGA_GPU_DATTN_OK) { UNLOCK(); return rc; } - if (rec) { if (!g.have_qf || g.qf_size < qf_bytes(m, v.q_heads)) { omega_gpu_session_set_error("prefill attn256 record: q' scratch not reserved for m tokens"); return OMEGA_GPU_DATTN_TOO_LARGE; } } - else if (qf_locked(qf_bytes(m, v.q_heads)) != 0) { UNLOCK(); return OMEGA_GPU_DATTN_CHIP_FAIL; } - if (host) { - if (bufs_locked((size_t)m * QKVW * 4u, (size_t)m * OUTW * 4u) != 0) { UNLOCK(); return OMEGA_GPU_DATTN_CHIP_FAIL; } - memcpy(g.qkv.cpu, qkv, (size_t)m * QKVW * 4u); - float *od = g.out.cpu; - for (size_t i = 0; i < (size_t)m * OUTW; 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; - qkv_va = g.qkv.va; out_va = g.out.va; - } - const uint32_t kvs = v.max_pos * OMEGA_DATTN256_ROW_BYTES, gx_att = (m + OMEGA_PATTN256_TOKENS - 1u) / OMEGA_PATTN256_TOKENS; - float fe = eps, f1 = 1.0f, fo = out_scale, fq = (float)(0.0625 * 1.4426950408889634); /* log2(e) / sqrt(256) */ - uint32_t ue, u1, uo, uq; memcpy(&ue, &fe, 4); memcpy(&u1, &f1, 4); memcpy(&uo, &fo, 4); memcpy(&uq, &fq, 4); - uint32_t ap[OMEGA_DATTN256_ARGS_WORDS], aa[OMEGA_PATTN256_ARGS_WORDS]; -#define A64(a, i, x) do { (a)[i] = (uint32_t)(x); (a)[(i) + 1] = (uint32_t)((uint64_t)(x) >> 32); } while (0) - A64(ap, 0, qkv_va); A64(ap, 2, v.k_va); A64(ap, 4, v.v_va); A64(ap, 6, v.rope_va); A64(ap, 8, v.q_norm_va); A64(ap, 10, v.k_norm_va); - A64(ap, 12, g.qf.va); A64(ap, 14, v.part_va); A64(ap, 16, v.cnt_va); - ap[18] = pos0; ap[19] = OMEGA_DATTN256_CHUNK; ap[20] = 1u; ap[21] = kvs; ap[22] = ue; ap[23] = u1; ap[24] = uq; - A64(aa, 0, g.qf.va); A64(aa, 2, v.k_va); A64(aa, 4, v.v_va); A64(aa, 6, out_va); - aa[8] = pos0; aa[9] = m; aa[10] = kvs; aa[11] = uo; -#undef A64 - OmegaGpuLaunch L[KK_N] = { - { .code_va = ks[KK_PREP]->code.va, .gpr_count = omega_bw_gpr_declared(ks[KK_PREP]->kernel.gpr_count), - .threads_x = OMEGA_PATTN256_THREADS, .threads_y = 1, .grid_x = m, .grid_y = v.q_heads / v.q_per_cta, - .num_elements = (size_t)m * QKVW, .args = ap, .n_args = OMEGA_DATTN256_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = OMEGA_DATTN256_SHARED_BYTES }, - { .code_va = ks[KK_ATTEND]->code.va, .gpr_count = omega_bw_gpr_declared(ks[KK_ATTEND]->kernel.gpr_count), - .threads_x = OMEGA_PATTN256_THREADS, .threads_y = 1, .grid_x = gx_att, .grid_y = v.kv_heads, - .num_elements = (size_t)m * OUTW, .args = aa, .n_args = OMEGA_PATTN256_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = OMEGA_PATTN256_SHARED_BYTES }, - }; - if (info) { - info->layer = layer; info->pos0 = pos0; info->m = m; info->grid_x[0] = m; info->grid_x[1] = gx_att; - for (unsigned k = 0; k < KK_N; k++) { info->insns[k] = ks[k]->insns; info->gprs[k] = ks[k]->kernel.gpr_count; info->kernel_cache_hits += hit[k]; } - } - for (unsigned k = 0; k < KK_N && rc == OMEGA_GPU_DATTN_OK; k++) { - if (!omega_bw_gpr_declared_ok(L[k].gpr_count, ks[k]->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[k]) < 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; } - else if (omega_gpu_session_launch(&L[k], info ? &info->elapsed_ns[k] : NULL, NULL) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - } - if (rc == OMEGA_GPU_DATTN_OK && host) { - if (omega_gpu_session_sync_to_cpu(&g.out) != 0) rc = OMEGA_GPU_DATTN_CHIP_FAIL; - else { - const float *od = g.out.cpu; - size_t unchanged = 0; - for (size_t i = 0; i < (size_t)m * OUTW; i++) if (od[i] == POISON_F32) unchanged++; - if (unchanged) { omega_gpu_session_set_error("prefill attn256: output poison survived"); rc = OMEGA_GPU_DATTN_CHIP_FAIL; } - else memcpy(out, od, (size_t)m * OUTW * 4u); - } - } - UNLOCK(); -#undef UNLOCK - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} - -int omega_gpu_prefill_attn256(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, - const float *qkv, float eps, float out_scale, float *out, OmegaGpuPrefillAttn256Info *info) { - if (!qkv) return OMEGA_GPU_DATTN_BAD_ARGS; - return core(c, layer, pos0, m, qkv, out, 0, 0, eps, out_scale, info, NULL); -} -int omega_gpu_prefill_attn256_dev(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, - uint64_t qkv_va, float eps, float out_scale, uint64_t out_va, OmegaGpuPrefillAttn256Info *info) { - return core(c, layer, pos0, m, NULL, NULL, qkv_va, out_va, eps, out_scale, info, NULL); -} -int omega_gpu_prefill_attn256_record(OmegaGpuCmdList *cl, OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, - uint32_t m, uint64_t qkv_va, float eps, float out_scale, uint64_t out_va) { - if (!cl) return OMEGA_GPU_DATTN_BAD_ARGS; - return core(c, layer, pos0, m, NULL, NULL, qkv_va, out_va, eps, out_scale, NULL, cl); -} diff --git a/src/omega_gpu_prefill_attn256_api.h b/src/omega_gpu_prefill_attn256_api.h deleted file mode 100644 index a2960150d..000000000 --- a/src/omega_gpu_prefill_attn256_api.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef OMEGA_GPU_PREFILL_ATTN256_API_H -#define OMEGA_GPU_PREFILL_ATTN256_API_H -/* - * omega_gpu_prefill_attn256_api: causal prefill attention for Qwen3.8-27B (omega-mv#545, 2026-10-18), on the decode - * attention's cache (omega_gpu_decode_attn256_api.h); the kernels are described in omega_blackwell_codegen_pattn256.h. - * - * int omega_gpu_prefill_attn256(c, layer, pos0, m, qkv, eps, out_scale, out, info) - * qkv: host f32 [m][8192], one row per token in the decode call's layout (q 24 x 256 permuted, k 4 x 256 permuted, - * v 4 x 256; the gate is not part of it), tokens at positions pos0 .. pos0+m-1 (positions 0 .. pos0-1 of `layer` - * already in the cache). Appends K and V for those positions with the decode step's instruction sequence (the - * rows equal m decode steps' rows on the same chip) and writes out: host f32 [m][6144] (token-major, head h at - * h * 256, model dim order) multiplied by out_scale. pos0 + m <= max_pos, 1 <= m <= OMEGA_GPU_PATTN256_MAX_M. - * Two launches: prep (grid m x 4), attend (grid ceil(m / 8) x 4). Returns OMEGA_GPU_DATTN_OK or an - * OMEGA_GPU_DATTN_* code; the text is in omega_gpu_decode_attn_last_error(). - * int omega_gpu_prefill_attn256_dev(c, layer, pos0, m, qkv_va, eps, out_scale, out_va, info) - * The same with device buffers (qkv_va: f32 [m][8192], out_va: f32 [m][6144], 16-byte aligned GPU VAs in the - * session); no host copies and no poison check (the caller's download path is the check). - * int omega_gpu_prefill_attn256_record(cl, c, layer, pos0, m, qkv_va, eps, out_scale, out_va) - * Record path (omega_gpu_cmdlist.h): both launches appended to cl. The caller holds omega_gpu_session_lock(), has - * reserved the q' scratch for m tokens (omega_gpu_prefill_attn256_reserve) and warmed both kernels with one - * non-record call (a kernel cache miss is refused, never compiled while recording). - * int omega_gpu_prefill_attn256_reserve(max_m): allocates the q' scratch for max_m tokens now (ceil(max_m / 2) x - * 24576 bytes) and builds both kernels (the warm-up the record path needs; sc #642); calls beyond it grow the - * scratch (host and dev paths) or are refused (record path: TOO_LARGE). - * void omega_gpu_prefill_attn256_release(void): frees the module's buffers (also released when the session closes). - * - * Every buffer is GPU-uncached host-visible session memory (nvos.h:1117 rule), launched through - * omega_gpu_session_launch. - */ -#include "omega_gpu_decode_attn256_api.h" -#include "omega_blackwell_codegen_pattn256.h" -#include - -#define OMEGA_GPU_PATTN256_MAX_M 32768u - -typedef struct { - uint32_t layer, pos0, m; - uint32_t grid_x[2]; /* prep, attend */ - uint32_t insns[2], gprs[2]; /* allocator peak registers */ - uint64_t elapsed_ns[2]; /* marker-to-marker chip time of each launch (host and dev paths) */ - uint64_t call_ns; - uint32_t kernel_cache_hits; /* 0..2 */ -} OmegaGpuPrefillAttn256Info; - -int omega_gpu_prefill_attn256(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, - const float *qkv, float eps, float out_scale, float *out, OmegaGpuPrefillAttn256Info *info); -int omega_gpu_prefill_attn256_dev(OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, uint32_t m, - uint64_t qkv_va, float eps, float out_scale, uint64_t out_va, OmegaGpuPrefillAttn256Info *info); -struct OmegaGpuCmdList; -int omega_gpu_prefill_attn256_record(struct OmegaGpuCmdList *cl, OmegaGpuDecodeAttn256Cache *c, uint32_t layer, uint32_t pos0, - uint32_t m, uint64_t qkv_va, float eps, float out_scale, uint64_t out_va); -int omega_gpu_prefill_attn256_reserve(uint32_t max_m); -/* the same for the head shape of cache c (the q' scratch is q_heads * 512 bytes per token; reserve(m) = the 27B) */ -int omega_gpu_prefill_attn256_reserve_for(const OmegaGpuDecodeAttn256Cache *c, uint32_t max_m); -void omega_gpu_prefill_attn256_release(void); - -/* ---- tests ---- */ -void omega_gpu_prefill_attn256_test_set_mutant(int prep_mutant, int attend_mutant); /* OmegaDecodeAttn256Spec / OmegaPrefillAttn256Spec .mutant */ -/* host: build + encode + patch a kernel (0 prep, 1 attend) into code (cap bytes); returns the code size or 0 */ -size_t omega_gpu_prefill_attn256_encode(unsigned kind, uint8_t *code, size_t cap, uint32_t *gprs, int *patched); - -#endif diff --git a/src/omega_gpu_prefill_attn_api.c b/src/omega_gpu_prefill_attn_api.c deleted file mode 100644 index 40b9fa33f..000000000 --- a/src/omega_gpu_prefill_attn_api.c +++ /dev/null @@ -1,411 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 3bf4bd3bf..000000000 --- a/src/omega_gpu_prefill_attn_api.h +++ /dev/null @@ -1,94 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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_q36_graph.c b/src/omega_gpu_q36_graph.c deleted file mode 100644 index 57fe6ddc2..000000000 --- a/src/omega_gpu_q36_graph.c +++ /dev/null @@ -1,1160 +0,0 @@ -/* - * omega_gpu_q36_graph.c: one Qwen3.6-35B-A3B decode token as one command list (see the header). Records the FP8 / bf16 GEMV, - * GDN, hd256 attention and router APIs' *_record launches and the omega_blackwell_codegen_dec glue kernels at width 2048 into an - * omega_gpu_cmdlist. Buffers: buf from omega_gpu_session_alloc (GPU-uncached, nvos.h:1117) holds every region the host - * touches: x (before), token and logits (after), the tables; dbuf (GPU-cached, omega_gpu_mem_cached.h) holds the chip-only - * intermediates (see Layout). - */ -#include "omega_gpu_q36_graph.h" -#include "omega_gpu_cmdlist.h" -#include "omega_blackwell_codegen_dec.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include "omega_gpu_mem_cached.h" -#include "omega_gpu_fp8gemm_api.h" -#include -#include - -#define TIMEOUT_MS 20000ull -#define SCALE_2P64 18446744073709551616.0f -#define NEG_PAD (-1e30f) -#define TOKEN_POISON 0xffffffffu -#define TOKEN_STRIDE 256u /* bytes per head's token slot (two u32, 256-aligned) */ -#define H OMEGA_GPU_Q36_HIDDEN -#define EI OMEGA_GPU_Q36_EXPERT_INTER -#define NG OMEGA_GPU_Q36_GROUPS - -/* glue kernels */ -enum { K_NORM, K_ADD, K_CN, K_SW, K_GATHER, K_GATE, K_AM0, K_AM1, K_SW_M1, K_GATHER_M1, K_GATE_M1, K_CN_M3, K_COPY, - K_NORM_R, K_ADD_R, K_PERM_XQ, K_PERM_O, K_PERM_XO, K_PERM_ACT, K_GROUP, K_XS, K_XB, K_XB_M1, - K_CN_R, K_CN_R_M3, K_GATE_R, K_COUNT }; /* K_NORM_R .. K_GROUP: the batch (v2) kernels; K_XS .. K_XB_M1: the exact head; K_CN_R: COMBINE|NORM of every head in one launch (L356) */ -#define SEGD_ROWS 2u /* dense segment entries per layer in the batch: mix, o */ -#define COPY_ROW 256u /* K_COPY: GATHER rows of 256 floats through the identity table */ - -typedef struct { OmegaGpuMem code; uint32_t gpr; } Kern; - -/* byte offsets into two buffers, every region 256-byte aligned (RES loads 16-byte vectors). [0, split): buf, GPU-uncached, - * every region the host writes or reads. [split, bytes): dbuf, the chip-only intermediates, GPU-cached unless - * AIEN_OMEGA_Q36_BUF_CACHED=0 (measured 2026-10-19: every FP8 GEMV CTA reads the whole x' row, and uncached each of those - * reads goes to DRAM; cached, down 2100 -> 1735 us and mix 1596 -> 1458 us over 4 layers, runs/probe-buf). read_buf copies - * a dbuf region into stage with a chip launch (K_COPY) before the host reads it. */ -typedef struct { - size_t x, ab, hidden, logits, am_v, am_i, token, norms, fnorm, tabs, gtab, idtab, stage, segd, ptab, split; - size_t xq, mix, agg, att, o, gu, act, dn; - /* the batch (v2, L312): every conversation of a layer in one set of launches. N = heads laid out; R = N * NG expert rows */ - size_t xp, mixN, abN, aggN, attN, op, oN, rlb, sgu, sdn, xmap, ymap, xp2, guN, actN, actp, dnN, bytes; - uint32_t lb_stride; /* bytes per conversation's router buffer (rlb), 256-aligned */ -} Layout; - -struct OmegaGpuQ36Graph { - OmegaGpuQ36GraphConfig cfg; - uint32_t am_ctas; /* stage-1 ARGMAX CTAs = ceil(vocab / 2048) */ - Layout lo; - OmegaGpuMem buf, dbuf; /* the host-visible regions; the chip-only regions (see Layout) */ - Kern k[K_COUNT]; - OmegaGpuCmdList *cl; - struct { const OmegaGpuFp8Tensor *mix, *o, *gu, *dn; const OmegaGpuBf16Tensor *ab; uint32_t kind_index; int attn, set; } layer[OMEGA_GPU_Q36_MAX_LAYERS]; - int final_set; - const OmegaGpuFp8Tensor *head8; /* set_lm_head_fp8: FP8 lm_head (hidden is then written x 2^64, read() undoes it) */ - /* heads (strokes): slot h of x, hidden, logits and token; head 0's state objects are cfg.gdn / cfg.attn */ - uint32_t heads; /* slots laid out (create_heads); 1 = the plain graph */ - OmegaGpuGdn *gdn_h[OMEGA_GPU_Q36_MAX_HEADS]; - OmegaGpuDecodeAttn256Cache *attn_h[OMEGA_GPU_Q36_MAX_HEADS]; - struct { /* set_exact_head: the HUM L314 two-pass head (bf16 lm_head only) */ - const OmegaGpuFp8Tensor *screen; /* fp8b copy of lm_head (128 x 128 block scales) */ - OmegaGpuMem mem; /* h8 | s | c | hi | lo (am_ctas * 2048, padded) | tau | tab */ - uint64_t h8, s, c, hi, lo, tau, tab; - uint8_t on[OMEGA_GPU_Q36_MAX_HEADS]; /* per head: its next tokens use it (greedy rows); set_exact_head_on sets every head */ - } xh; - /* token / stroke state */ - int in_token, failed; - uint32_t stroke_heads; /* heads in the open stroke */ - int xq_layer[OMEGA_GPU_Q36_MAX_HEADS]; /* per head: layer whose input-norm x' sits in the head's xq slot, -1 none - * (COMBINE|NORM of layer l writes layer l+1's x' there: the one value that - * crosses layers, so it is per head; 02:50Z, found by the stroke gate) */ - int hidden_ready[OMEGA_GPU_Q36_MAX_HEADS]; - uint64_t t_begin; - OmegaGpuDecodeGraphStats acc; - int flush_each, mutant; - int batch; /* 1: stroke() records every conversation of a layer at once (v2); set_batch */ - /* the prefill (L369): one conversation's prompt chunk as rows through the batch's GEMMs; GDN and attention per token in order */ - struct { uint32_t cap; OmegaGpuMem hb, db; size_t x, rlb, sgu, sdn, sgu2, sdn2, xmap, ymap, xmap2, ymap2; - size_t xq, xp, mixN, abN, aggN, attN, op, oN, xp2, guN, actN, actp, dnN; int mutant; - uint64_t streamed; /* fp8 GEMM weight bytes every prefill call so far streamed (one pass per mt rows) */ - int attn_multi; /* 1 (default): each attention layer in one prep + attend launch pair; AIEN_OMEGA_Q36_PF_ATTN=0: one decode step per token */ - int gdn_multi; /* 1 (default): the GDN layers in one multi-token launch; AIEN_OMEGA_Q36_PF_GDN=0: one decode step per token */ } pf; - 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 OmegaGpuQ36Graph *g, size_t off) { return off < g->lo.split ? g->buf.va + off : g->dbuf.va + (off - g->lo.split); } -static void *cpu_of(const OmegaGpuQ36Graph *g, size_t off) { return (uint8_t *)g->buf.cpu + off; } /* host regions only (off < split) */ -static size_t x_of(const OmegaGpuQ36Graph *g, uint32_t h) { return g->lo.x + (size_t)h * H * 4u; } -static size_t hidden_of(const OmegaGpuQ36Graph *g, uint32_t h) { return g->lo.hidden + (size_t)h * H * 4u; } -static size_t xq_of(const OmegaGpuQ36Graph *g, uint32_t h) { return g->lo.xq + (size_t)h * H * 4u; } -static size_t logits_of(const OmegaGpuQ36Graph *g, uint32_t h) { return g->lo.logits + (size_t)h * g->am_ctas * OMEGA_DEC_ARGMAX_SPAN * 4u; } -static size_t token_of(const OmegaGpuQ36Graph *g, uint32_t h) { return g->lo.token + (size_t)h * TOKEN_STRIDE; } -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(OmegaGpuQ36Graph *g, const char *what, int rc) { - if (g) g->failed = 1; - if (what) omega_gpu_session_set_error(what); - return rc; -} - -void omega_q36_gather_table(uint32_t *tab) { - const uint32_t R = OMEGA_GPU_Q36_ROTARY, QP = 16u * 512u, KP = QP + 2u * 256u; - for (uint32_t n = 0; n < OMEGA_GPU_Q36_ATT_MIX; n++) { - uint32_t s; - if (n < 4096u) s = (n / 256u) * 512u + omega_dattn256_perm_slot(n % 256u, R); /* q, permuted */ - else if (n < 4608u) s = QP + ((n - 4096u) / 256u) * 256u + omega_dattn256_perm_slot(n % 256u, R); /* k, permuted */ - else if (n < 5120u) s = KP + (n - 4608u); /* v */ - else s = ((n - 5120u) / 256u) * 512u + 256u + (n - 5120u) % 256u; /* gate */ - tab[n] = s; - } -} - -/* lock held */ -/* GATHER table of the FP8 GEMM's x' lane layout (omega_fp8gemm_permute_x, lane bytes 16: k a multiple of 512): permuted index - * i = s*512 + (w*32 + L)*4 + e holds source column c = s*512 + L*16 + w*4 + e, so tab[i] = c. */ -void omega_q36_perm_table(uint32_t *tab, uint32_t k) { - for (uint32_t s0 = 0; s0 < k; s0 += 512u) - for (uint32_t L = 0; L < 32u; L++) - for (uint32_t w = 0; w < 4u; w++) - for (uint32_t e = 0; e < 4u; e++) tab[s0 + (w * 32u + L) * 4u + e] = s0 + L * 16u + w * 4u + e; -} - -static void write_dense_segments(OmegaGpuQ36Graph *g, uint32_t heads); - -static int kern_build(Kern *k, const OmegaDecSpec *s) { - 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 the decode graph */ - 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_q36_graph_free(OmegaGpuQ36Graph *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); - if (g->dbuf.cpu) omega_gpu_session_free(&g->dbuf); - if (g->pf.hb.cpu) omega_gpu_session_free(&g->pf.hb); - if (g->pf.db.cpu) omega_gpu_session_free(&g->pf.db); - if (g->xh.mem.cpu) omega_gpu_session_free(&g->xh.mem); - omega_gpu_session_unlock(); - omega_gpu_host_free(g); -} - -int omega_gpu_q36_graph_create(const OmegaGpuQ36GraphConfig *cfg, OmegaGpuQ36Graph **out) { return omega_gpu_q36_graph_create_heads(cfg, 1, out); } - -int omega_gpu_q36_graph_create_heads(const OmegaGpuQ36GraphConfig *cfg, uint32_t heads, OmegaGpuQ36Graph **out) { - if (out) *out = NULL; - if (heads == 0 || heads > OMEGA_GPU_Q36_MAX_HEADS) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (!cfg || !out || cfg->layers == 0 || cfg->layers > OMEGA_GPU_Q36_MAX_LAYERS || !cfg->gdn || !cfg->attn || !cfg->router || !cfg->lm_head || - cfg->vocab == 0 || cfg->vocab > OMEGA_DEC_ARGMAX_SPAN * OMEGA_DEC_ARGMAX_SPAN) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (cfg->layers < 64u && (cfg->attn_mask >> cfg->layers) != 0) 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 != H) return OMEGA_GPU_DGRAPH_BAD_ARGS; - OmegaGpuQ36Graph *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->heads = heads; g->gdn_h[0] = cfg->gdn; g->attn_h[0] = cfg->attn; - for (uint32_t h = 0; h < OMEGA_GPU_Q36_MAX_HEADS; h++) g->xq_layer[h] = -1; - for (uint32_t l = 0, na = 0, ng = 0; l < cfg->layers; l++) { - g->layer[l].attn = (int)((cfg->attn_mask >> l) & 1u); - g->layer[l].kind_index = g->layer[l].attn ? na++ : ng++; - } - Layout *L = &g->lo; size_t o = 0; -#define REG(f, bytes) do { L->f = o; o = al(o + (bytes)); } while (0) - REG(x, (size_t)H * 4 * heads); REG(ab, OMEGA_GPU_Q36_AB * 4); REG(hidden, (size_t)H * 4 * heads); - REG(logits, (size_t)g->am_ctas * OMEGA_DEC_ARGMAX_SPAN * 4 * heads); REG(am_v, OMEGA_DEC_ARGMAX_SPAN * 4); REG(am_i, OMEGA_DEC_ARGMAX_SPAN * 4); - REG(token, (size_t)TOKEN_STRIDE * heads); REG(norms, (size_t)cfg->layers * H * 4); REG(fnorm, H * 4); REG(tabs, (size_t)cfg->layers * 4 * 16 + 16); /* + the FP8 lm_head entry */ - REG(gtab, OMEGA_GPU_Q36_ATT_MIX * 4); REG(idtab, COPY_ROW * 4); REG(stage, (size_t)NG * H * 4); /* the largest read_buf region (dn) */ - REG(segd, (size_t)cfg->layers * SEGD_ROWS * OMEGA_GEMM_SEG_BYTES); REG(ptab, (size_t)(H + OMEGA_GPU_Q36_MIXER_OUT + EI) * 4); /* batch: dense segment entries, the x' lane permutations */ - L->split = o; - REG(xq, (size_t)H * 4 * heads); REG(mix, OMEGA_GPU_Q36_GDN_MIX * 4); REG(agg, OMEGA_GPU_Q36_ATT_MIX * 4); - REG(att, OMEGA_GPU_Q36_MIXER_OUT * 4); REG(o, H * 4); REG(gu, (size_t)NG * 2 * EI * 4); REG(act, (size_t)NG * EI * 4); REG(dn, (size_t)NG * H * 4); - { /* batch regions (N rows each, R = N * NG expert rows; x' inputs of the dense GEMMs hold MAX_HEADS rows: 8 rows per pass) */ - const size_t N = heads, R = (size_t)heads * NG, M8 = OMEGA_GPU_Q36_MAX_HEADS; - L->lb_stride = (uint32_t)al(omega_gpu_router_layout_bytes(cfg->router)); - REG(xp, M8 * H * 4); REG(mixN, N * OMEGA_GPU_Q36_GDN_MIX * 4); REG(abN, N * OMEGA_GPU_Q36_AB * 4); REG(aggN, N * OMEGA_GPU_Q36_ATT_MIX * 4); - REG(attN, N * OMEGA_GPU_Q36_MIXER_OUT * 4); REG(op, M8 * OMEGA_GPU_Q36_MIXER_OUT * 4); REG(oN, N * H * 4); REG(rlb, N * L->lb_stride); - REG(sgu, R * OMEGA_GEMM_SEG_BYTES); REG(sdn, R * OMEGA_GEMM_SEG_BYTES); REG(xmap, (R + OMEGA_DEC_GR_PAD) * 4); REG(ymap, (R + OMEGA_DEC_GR_PAD) * 4); - REG(xp2, M8 * H * 4); REG(guN, R * 2 * EI * 4); REG(actN, R * EI * 4); REG(actp, R * EI * 4); REG(dnN, R * H * 4); - } -#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_q36_graph_free(g); return OMEGA_GPU_DGRAPH_CHIP_FAIL; } - omega_gpu_session_lock(); - const char *pbc = getenv("AIEN_OMEGA_Q36_BUF_CACHED"); - int (*const dalloc)(size_t, OmegaGpuMem *) = (pbc && pbc[0] == '0' && pbc[1] == 0) ? omega_gpu_session_alloc : omega_gpu_session_alloc_cached; - if (!omega_gpu_session_open() || omega_gpu_session_alloc(L->split, &g->buf) != 0 || dalloc(L->bytes - L->split, &g->dbuf) != 0) - rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - OmegaDecSpec spec[K_COUNT] = { - [K_NORM] = { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_NORM }, - [K_ADD] = { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_ADD }, - [K_CN] = { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, .groups = NG }, - [K_SW] = { .kind = OMEGA_DEC_SWIGLU, .width = EI }, - [K_GATHER] = { .kind = OMEGA_DEC_GATHER, .width = OMEGA_GPU_Q36_ATT_MIX, .stride = OMEGA_GPU_Q36_ATT_MIX }, - [K_GATE] = { .kind = OMEGA_DEC_GATE }, - [K_AM0] = { .kind = OMEGA_DEC_ARGMAX, .mode = 0 }, - [K_AM1] = { .kind = OMEGA_DEC_ARGMAX, .mode = 1 }, - [K_SW_M1] = { .kind = OMEGA_DEC_SWIGLU, .width = EI, .mutant = 1 }, - [K_GATHER_M1] = { .kind = OMEGA_DEC_GATHER, .width = OMEGA_GPU_Q36_ATT_MIX, .stride = OMEGA_GPU_Q36_ATT_MIX, .mutant = 1 }, - [K_GATE_M1] = { .kind = OMEGA_DEC_GATE, .mutant = 1 }, - [K_CN_M3] = { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, .groups = NG, .mutant = 3 }, - [K_COPY] = { .kind = OMEGA_DEC_GATHER, .width = COPY_ROW, .stride = COPY_ROW }, - /* the batch (v2): N-row norm and add, the x' lane permutations (GATHER through ptab), the segment-table kernel */ - [K_NORM_R] = { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_NORM | OMEGA_DEC_RES_ROWS }, - [K_ADD_R] = { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_ROWS }, - [K_PERM_XQ] = { .kind = OMEGA_DEC_GATHER, .width = H, .stride = H }, - [K_PERM_O] = { .kind = OMEGA_DEC_GATHER, .width = OMEGA_GPU_Q36_MIXER_OUT, .stride = OMEGA_GPU_Q36_MIXER_OUT }, - [K_PERM_XO] = { .kind = OMEGA_DEC_GATHER, .width = H, .stride = H }, /* stride = lb_stride / 4, set below */ - [K_PERM_ACT] = { .kind = OMEGA_DEC_GATHER, .width = EI, .stride = EI }, - [K_GROUP] = { .kind = OMEGA_DEC_GROUP, .groups = NG }, - [K_XS] = { .kind = OMEGA_DEC_XBOUND, .mode = 1 }, - [K_XB] = { .kind = OMEGA_DEC_XBOUND }, - [K_XB_M1] = { .kind = OMEGA_DEC_XBOUND, .mutant = 1 }, - [K_CN_R] = { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM | OMEGA_DEC_RES_ROWS, .groups = NG }, /* stride set below */ - [K_CN_R_M3] = { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM | OMEGA_DEC_RES_ROWS, .groups = NG, .mutant = 3 }, - [K_GATE_R] = { .kind = OMEGA_DEC_GATE, .mode = 1, .width = OMEGA_GPU_Q36_MIXER_OUT, .stride = OMEGA_GPU_Q36_ATT_MIX }, /* L369 prefill: every token's gate */ - }; - spec[K_PERM_XO].stride = L->lb_stride / 4u; - spec[K_CN_R].stride = L->lb_stride; spec[K_CN_R_M3].stride = L->lb_stride; /* head h's routing weights: wts_va + h * lb_stride */ - for (unsigned i = 0; i < K_COUNT && rc == OMEGA_GPU_DGRAPH_OK; i++) rc = kern_build(&g->k[i], &spec[i]); - if (rc == OMEGA_GPU_DGRAPH_OK) { - memset(g->buf.cpu, 0, L->split); - memset(g->dbuf.cpu, 0, L->bytes - L->split); /* fresh; every region is written by the chip before a launch reads it */ - uint32_t *id = cpu_of(g, L->idtab); - for (uint32_t i = 0; i < COPY_ROW; i++) id[i] = i; - float *amv = cpu_of(g, L->am_v); - for (uint32_t h = 0; h < heads; h++) { - float *lg = cpu_of(g, logits_of(g, h)); - 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 */ - omega_q36_gather_table(cpu_of(g, L->gtab)); - { uint32_t *pt = cpu_of(g, L->ptab); omega_q36_perm_table(pt, H); omega_q36_perm_table(pt + H, OMEGA_GPU_Q36_MIXER_OUT); omega_q36_perm_table(pt + H + OMEGA_GPU_Q36_MIXER_OUT, EI); } - if (omega_gpu_session_sync_to_gpu(&g->buf) != 0 || omega_gpu_session_sync_to_gpu(&g->dbuf) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - } - omega_gpu_session_unlock(); - if (rc != OMEGA_GPU_DGRAPH_OK) { omega_gpu_q36_graph_free(g); return rc; } - { const char *e = getenv("AIEN_OMEGA_Q36_BATCH"); if (e && e[0] == '1' && e[1] == 0 && omega_gpu_q36_graph_set_batch(g, 1) != OMEGA_GPU_DGRAPH_OK) { omega_gpu_q36_graph_free(g); return OMEGA_GPU_DGRAPH_CHIP_FAIL; } } - *out = g; - return OMEGA_GPU_DGRAPH_OK; -} - -static int shape_e(const OmegaGpuFp8Tensor *t, uint32_t e, uint32_t n, uint32_t k) { - uint32_t te = 0, tn = 0, tk = 0; if (t) omega_gpu_fp8_tensor_shape(t, &te, &tn, &tk); - return t && te == e && tn == n && tk == k; -} -static int shape_is(const OmegaGpuFp8Tensor *t, uint32_t n, uint32_t k) { return shape_e(t, 1, n, k); } -#define N_EXPERTS 257u /* routed experts + the shared one (the router's directory) */ - -int omega_gpu_q36_graph_set_head_state(OmegaGpuQ36Graph *g, uint32_t head, OmegaGpuGdn *gdn, OmegaGpuDecodeAttn256Cache *attn) { - if (!g || head >= g->heads || !gdn || !attn || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - g->gdn_h[head] = gdn; g->attn_h[head] = attn; - return OMEGA_GPU_DGRAPH_OK; -} - -int omega_gpu_q36_graph_set_layer(OmegaGpuQ36Graph *g, uint32_t layer, const OmegaGpuFp8Tensor *mix, const OmegaGpuBf16Tensor *ab, - const OmegaGpuFp8Tensor *o, const OmegaGpuFp8Tensor *gate_up, const OmegaGpuFp8Tensor *down, - const float *in_norm) { - if (!g || layer >= g->cfg.layers || !in_norm || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - const int attn = g->layer[layer].attn; - if (!shape_is(mix, attn ? OMEGA_GPU_Q36_ATT_MIX : OMEGA_GPU_Q36_GDN_MIX, H) || !shape_is(o, H, OMEGA_GPU_Q36_MIXER_OUT) || - !shape_e(gate_up, N_EXPERTS, 2 * EI, H) || !shape_e(down, N_EXPERTS, H, EI)) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (attn ? ab != NULL : ab == NULL) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (!attn) { uint32_t n = 0, k = 0; omega_gpu_bf16_tensor_shape(ab, &n, &k); if (n != OMEGA_GPU_Q36_AB || k != H) return OMEGA_GPU_DGRAPH_BAD_ARGS; } - uint64_t t[8] = { 0 }; /* mix, o; the experts' group tables come from the router */ - if (omega_gpu_fp8_tensor_entry(mix, 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 * 64u, t, sizeof t); - memcpy((float *)cpu_of(g, g->lo.norms) + (size_t)layer * H, in_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].mix = mix; g->layer[layer].ab = ab; 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_q36_graph_set_final_norm(OmegaGpuQ36Graph *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, 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->final_set = 1; - return rc; -} - -int omega_gpu_q36_graph_set_lm_head_fp8(OmegaGpuQ36Graph *g, const OmegaGpuFp8Tensor *head) { - if (!g || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (!head) { g->head8 = NULL; return OMEGA_GPU_DGRAPH_OK; } - uint64_t t[2]; - if (!shape_is(head, g->cfg.vocab, H) || omega_gpu_fp8_tensor_entry(head, 0, &t[0], &t[1]) != 0) return OMEGA_GPU_DGRAPH_BAD_ARGS; - omega_gpu_session_lock(); - memcpy((uint8_t *)cpu_of(g, g->lo.tabs) + (size_t)g->cfg.layers * 64u, t, sizeof t); - 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->head8 = head; - return rc; -} - -int omega_gpu_q36_graph_set_exact_head(OmegaGpuQ36Graph *g, const OmegaGpuFp8Tensor *screen, const float *coef) { - if (!g || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (!screen) { - omega_gpu_session_lock(); - if (g->xh.mem.cpu) omega_gpu_session_free(&g->xh.mem); - omega_gpu_session_unlock(); - memset(&g->xh, 0, sizeof g->xh); - return OMEGA_GPU_DGRAPH_OK; - } - uint64_t t[2]; - if (!coef || g->xh.screen || !shape_is(screen, g->cfg.vocab, H) || omega_gpu_fp8_tensor_entry(screen, 0, &t[0], &t[1]) != 0) - return OMEGA_GPU_DGRAPH_BAD_ARGS; - const size_t n = g->cfg.vocab, P = (size_t)g->am_ctas * OMEGA_DEC_ARGMAX_SPAN; - const size_t o_h8 = 0, o_s = al(o_h8 + H * 4), o_c = al(o_s + n * 4), o_hi = al(o_c + n * 4), o_lo = al(o_hi + n * 4), - o_tau = al(o_lo + P * 4), o_tab = al(o_tau + 16), total = al(o_tab + 16); - if (omega_gpu_bf16_prepare_mask(H) != 0) return fail(g, "q36 graph: exact head MASK kernel", OMEGA_GPU_DGRAPH_CHIP_FAIL); - omega_gpu_session_lock(); - int rc = omega_gpu_session_alloc(total, &g->xh.mem) == 0 ? OMEGA_GPU_DGRAPH_OK : OMEGA_GPU_DGRAPH_CHIP_FAIL; - if (rc == OMEGA_GPU_DGRAPH_OK) { - uint8_t *B = g->xh.mem.cpu; - memset(B, 0, total); - memcpy(B + o_c, coef, n * 4); - for (size_t i = n; i < P; i++) ((float *)(B + o_lo))[i] = NEG_PAD; /* XBOUND writes [0, vocab) only */ - memcpy(B + o_tab, t, sizeof t); - if (omega_gpu_session_sync_to_gpu(&g->xh.mem) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - } - if (rc == OMEGA_GPU_DGRAPH_OK) { - const uint64_t V = g->xh.mem.va; - g->xh.h8 = V + o_h8; g->xh.s = V + o_s; g->xh.c = V + o_c; g->xh.hi = V + o_hi; g->xh.lo = V + o_lo; g->xh.tau = V + o_tau; g->xh.tab = V + o_tab; - g->xh.screen = screen; memset(g->xh.on, 1, sizeof g->xh.on); - } else if (g->xh.mem.cpu) omega_gpu_session_free(&g->xh.mem); - omega_gpu_session_unlock(); - return rc; -} - -void omega_gpu_q36_graph_set_exact_head_on(OmegaGpuQ36Graph *g, int on) { if (g && !g->in_token) memset(g->xh.on, on ? 1 : 0, sizeof g->xh.on); } -void omega_gpu_q36_graph_set_head_exact_head_on(OmegaGpuQ36Graph *g, uint32_t head, int on) { - if (g && !g->in_token && head < OMEGA_GPU_Q36_MAX_HEADS) g->xh.on[head] = on ? 1 : 0; -} -int omega_gpu_q36_graph_exact_head_active_head(const OmegaGpuQ36Graph *g, uint32_t head) { - return g && head < OMEGA_GPU_Q36_MAX_HEADS && g->xh.screen && g->xh.on[head] && !g->head8; -} -int omega_gpu_q36_graph_exact_head_active(const OmegaGpuQ36Graph *g) { return omega_gpu_q36_graph_exact_head_active_head(g, 0); } - -void omega_gpu_q36_graph_set_flush_each(OmegaGpuQ36Graph *g, int on) { if (g) g->flush_each = on ? 1 : 0; } -void omega_gpu_q36_graph_test_set_mutant(OmegaGpuQ36Graph *g, int mutant) { - if (!g) return; - g->mutant = mutant; - omega_gpu_bf16_test_set_mask_mutant(mutant == 5 ? 4 : 0); /* process-wide, the MASK form only */ -} - -/* ---- the list ---- */ - -static OmegaGpuCmdListOpts list_opts(const OmegaGpuQ36Graph *g) { - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); - o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = (OmegaGpuCmdListBarrier)omega_gpu_decode_graph_barrier(); o.timeout_ms = TIMEOUT_MS; o.stamps = g->stamps; - return o; -} - -static int submit_now(OmegaGpuQ36Graph *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) { - 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 && g->n_stamp <= OMEGA_GPU_CMDLIST_MAX_LAUNCHES; 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, "q36 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; -} - -static void tag(OmegaGpuQ36Graph *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; -} - -static int after_op(OmegaGpuQ36Graph *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(OmegaGpuQ36Graph *g, uint8_t kind, int ki, uint32_t gx, uint32_t gy, size_t elems, const uint32_t *args, uint32_t n_args) { - const Kern *k = &g->k[ki]; - 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); -} - -/* RES at width 2048: NORM (x -> y), ADD (x += a) or COMBINE|NORM (x += sum_g wts[g] * a[g]; y = norm(x)) */ -static int rec_res_w(OmegaGpuQ36Graph *g, int ki, uint64_t x, uint64_t a, uint64_t wts, uint64_t nw, uint64_t y, float scale) { - uint32_t w[OMEGA_DEC_RES_WORDS]; memset(w, 0, sizeof w); - put64(w, OMEGA_DEC_RES_X, x); put64(w, OMEGA_DEC_RES_A, a); put64(w, OMEGA_DEC_RES_W, wts); put64(w, OMEGA_DEC_RES_NW, nw); - put64(w, OMEGA_DEC_RES_Y, y); putf(w, OMEGA_DEC_RES_EPS, g->cfg.eps); putf(w, OMEGA_DEC_RES_SCALE, scale); - return add_glue(g, ki == K_NORM ? OMEGA_GPU_Q36_K_NORM : OMEGA_GPU_Q36_K_RES, ki, 1, 1, H, w, OMEGA_DEC_RES_WORDS); -} -static int rec_res(OmegaGpuQ36Graph *g, int ki, uint64_t x, uint64_t a, uint64_t nw, uint64_t y, float scale) { - return rec_res_w(g, ki, x, a, 0, nw, y, scale); -} - -/* The a|b GEMV beside the mix GEMV (a speed lever of the 27B, values identical): OFF by default here until the plain graph - * has passed its gates (PRIORITY CHANGE 2026-10-20); env AIEN_OMEGA_Q36_OVERLAP_AB=1 turns it on. */ -static int g_overlap_ab = -1; -static int q36_overlap_ab(void) { - if (g_overlap_ab < 0) { const char *e = getenv("AIEN_OMEGA_Q36_OVERLAP_AB"); g_overlap_ab = (e && e[0] == '1' && e[1] == 0) ? 1 : 0; } - return g_overlap_ab; -} - -static int rec_fp8(OmegaGpuQ36Graph *g, uint8_t kind, const OmegaGpuFp8Tensor *t, uint64_t tab, uint64_t x, uint64_t y) { - return after_op(g, kind, omega_gpu_fp8_gemv_grouped_record(g->cl, t, 1, tab, x, 1, y)); -} - -int omega_gpu_q36_graph_begin_token(OmegaGpuQ36Graph *g, const float *x_embed) { return omega_gpu_q36_graph_begin_stroke(g, x_embed, 1); } - -int omega_gpu_q36_graph_begin_stroke(OmegaGpuQ36Graph *g, const float *x_embed, uint32_t heads) { - if (!g || g->in_token || heads == 0 || heads > g->heads) return OMEGA_GPU_DGRAPH_BAD_ARGS; - for (uint32_t h = 1; h < heads; h++) if (!g->gdn_h[h] || !g->attn_h[h]) 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->stroke_heads = heads; - for (uint32_t h = 0; h < heads; h++) { g->xq_layer[h] = -1; g->hidden_ready[h] = 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); - for (uint32_t h = 0; h < heads; h++) { - uint32_t *tok = cpu_of(g, token_of(g, h)); - tok[0] = TOKEN_POISON; tok[1] = TOKEN_POISON; - if (x_embed) memcpy(cpu_of(g, x_of(g, h)), x_embed + (size_t)h * H, H * 4u); - } - if (g->batch) write_dense_segments(g, heads); - 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_q36_graph_record_layer(OmegaGpuQ36Graph *g, uint32_t l, uint32_t pos) { return omega_gpu_q36_graph_record_head_layer(g, 0, l, pos); } - -int omega_gpu_q36_graph_record_head_layer(OmegaGpuQ36Graph *g, uint32_t h, 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 (h >= g->stroke_heads) return fail(g, "q36 graph: head not in the stroke", OMEGA_GPU_DGRAPH_BAD_ARGS); - if (l >= g->cfg.layers || !g->layer[l].set || g->hidden_ready[h] || (l + 1 == g->cfg.layers && !g->final_set)) - return fail(g, "q36 graph: layer not set, out of order, or final norm missing", OMEGA_GPU_DGRAPH_BAD_ARGS); - const uint64_t x = va_of(g, x_of(g, h)), xq = va_of(g, xq_of(g, h)), mix = va_of(g, g->lo.mix), agg = va_of(g, g->lo.agg); - const uint64_t att = va_of(g, g->lo.att), o = va_of(g, g->lo.o), gu = va_of(g, g->lo.gu), act = va_of(g, g->lo.act), dn = va_of(g, g->lo.dn); - const uint64_t in_norm = va_of(g, g->lo.norms) + (uint64_t)l * H * 4u, tab = va_of(g, g->lo.tabs) + (uint64_t)l * 64u; - const uint32_t ki = g->layer[l].kind_index; - int rc = OMEGA_GPU_DGRAPH_OK; - if (g->xq_layer[h] != (int)l) rc = rec_res(g, K_NORM, x, 0, in_norm, xq, SCALE_2P64); - /* GDN layers: the a|b GEMV (latency-bound, ~18 us) is recorded first and the mix GEMV marked independent of it: both only - * read xq and write their own buffers, so the two grids overlap; the GDN step after them waits for both (normal barrier). - * AIEN_OMEGA_Q36_OVERLAP_AB=0 or set_overlap_ab(0): the old order, mix then a|b, each behind a barrier. */ - const int overlap = !g->layer[l].attn && q36_overlap_ab(); - if (overlap && rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_Q36_K_AB, omega_gpu_bf16_gemv_record(g->cl, g->layer[l].ab, xq, va_of(g, g->lo.ab))); - if (rc == OMEGA_GPU_DGRAPH_OK) { - int mrc = omega_gpu_fp8_gemv_grouped_record(g->cl, g->layer[l].mix, 1, tab, xq, 1, mix); - if (mrc == 0 && overlap && !g->flush_each && omega_gpu_cmdlist_mark_independent(g->cl) != 0) mrc = -1; - rc = after_op(g, OMEGA_GPU_Q36_K_MIX, mrc); - } - uint64_t mixer_out = att; - if (!g->layer[l].attn) { - const uint64_t ab = va_of(g, g->lo.ab); - if (!overlap && rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_Q36_K_AB, omega_gpu_bf16_gemv_record(g->cl, g->layer[l].ab, xq, ab)); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_GDN, omega_gpu_gdn_record(g->cl, g->gdn_h[h], ki, mix, mix + OMEGA_GPU_Q36_GDN_QKV * 4u, ab, - g->cfg.eps_l2, g->cfg.eps, 1.0f, SCALE_2P64, &mixer_out)); - } else { - uint32_t w[OMEGA_DEC_GA_WORDS]; memset(w, 0, sizeof w); - put64(w, OMEGA_DEC_GA_IN, mix); put64(w, OMEGA_DEC_GA_TAB, va_of(g, g->lo.gtab)); put64(w, OMEGA_DEC_GA_OUT, agg); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q36_K_GATHER, g->mutant == 2 ? K_GATHER_M1 : K_GATHER, (OMEGA_GPU_Q36_ATT_MIX + OMEGA_DEC_THREADS - 1) / OMEGA_DEC_THREADS, 1, - OMEGA_GPU_Q36_ATT_MIX, w, OMEGA_DEC_GA_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_ATTN, omega_gpu_decode_attn256_record(g->cl, g->attn_h[h], ki, pos, agg, g->cfg.eps, SCALE_2P64, att)); - uint32_t w2[OMEGA_DEC_GT_WORDS]; memset(w2, 0, sizeof w2); - put64(w2, OMEGA_DEC_GT_A, att); put64(w2, OMEGA_DEC_GT_G, agg + OMEGA_GPU_Q36_ATT_QKV * 4u); put64(w2, OMEGA_DEC_GT_OUT, att); - w2[(OMEGA_DEC_GT_N - 0x380) / 4] = OMEGA_GPU_Q36_MIXER_OUT; - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q36_K_GATE, g->mutant == 3 ? K_GATE_M1 : K_GATE, OMEGA_GPU_Q36_MIXER_OUT / OMEGA_DEC_THREADS, 1, - OMEGA_GPU_Q36_MIXER_OUT, w2, OMEGA_DEC_GT_WORDS); - } - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_fp8(g, OMEGA_GPU_Q36_K_O, g->layer[l].o, tab + 16u, mixer_out, o); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_res_w(g, K_ADD, x, o, 0, 0, 0, 1.0f); - /* the sparse block: router (post-attention norm, top-8 + the shared slot), 9 expert groups, COMBINE|NORM */ - OmegaGpuRouterDevOut r; memset(&r, 0, sizeof r); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_ROUTER, omega_gpu_router_record(g->cl, g->cfg.router, l, x, g->cfg.eps, 1, SCALE_2P64, &r)); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_GATE_UP, omega_gpu_fp8_gemv_grouped_record(g->cl, g->layer[l].gu, NG, r.tab_gu_va, r.xout_va, 1, gu)); - uint32_t w3[OMEGA_DEC_SW_WORDS]; memset(w3, 0, sizeof w3); - put64(w3, OMEGA_DEC_SW_GU, gu); put64(w3, OMEGA_DEC_SW_ACT, act); putf(w3, OMEGA_DEC_SW_SCALE, SCALE_2P64); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q36_K_SWIGLU, g->mutant == 1 ? K_SW_M1 : K_SW, EI / OMEGA_DEC_THREADS, NG, (size_t)NG * EI, w3, OMEGA_DEC_SW_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_DOWN, omega_gpu_fp8_gemv_grouped_record(g->cl, g->layer[l].dn, NG, r.tab_dn_va, act, NG, 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) : in_norm + H * 4u; - rc = rec_res_w(g, g->mutant == 4 ? K_CN_M3 : K_CN, x, dn, r.wts_va, nw, last ? va_of(g, hidden_of(g, h)) : xq, - last && !g->head8 ? 1.0f : SCALE_2P64); - if (rc == OMEGA_GPU_DGRAPH_OK) { if (last) g->hidden_ready[h] = 1; else g->xq_layer[h] = (int)l + 1; } - } - return rc == OMEGA_GPU_DGRAPH_OK ? rc : fail(g, NULL, rc); -} - -/* ---- the batch (v2, L312): every conversation of a layer in one set of launches, each weight read once per layer ---- */ -typedef struct { uint64_t w_va, s_va; uint32_t row0, cnt, pad[2]; } Seg32; -_Static_assert(sizeof(Seg32) == OMEGA_GEMM_SEG_BYTES, "segment entry layout"); - -int omega_gpu_q36_graph_set_batch(OmegaGpuQ36Graph *g, int on) { - if (!g || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (!on) { g->batch = 0; return OMEGA_GPU_DGRAPH_OK; } - /* pin the four GEMM shapes the batch records (a kernel cache miss while recording is refused): the dense trunk at 8 rows - * per pass without maps, the expert blocks at 4 rows per pass with the row maps */ - const uint32_t R = g->heads * NG; - int rc = omega_gpu_fp8gemm_prepare_shape(H, 1, 0, 0); - if (rc == 0) rc = omega_gpu_fp8gemm_prepare_shape(OMEGA_GPU_Q36_MIXER_OUT, 1, 0, 0); - if (rc == 0) rc = omega_gpu_fp8gemm_prepare_shape(H, R, 0, 1); - if (rc == 0) rc = omega_gpu_fp8gemm_prepare_shape(EI, R, 0, 1); - if (rc != 0) return OMEGA_GPU_DGRAPH_CHIP_FAIL; - /* lever 2: the router once per layer for every head (record_layer_heads; the ROWS kernel has its own cache slot) */ - if (g->heads > 1u && omega_gpu_router_prepare_rows(g->cfg.router, H * 4u, g->lo.lb_stride) != OMEGA_GPU_ROUTER_OK) return OMEGA_GPU_DGRAPH_CHIP_FAIL; - /* lever 1: the bf16 lm_head read once per group of up to OMEGA_BF16_MAX_XBATCH heads (record_final_heads) */ - if (!g->head8) { - uint32_t n = 0, k = 0; omega_gpu_bf16_tensor_shape(g->cfg.lm_head, &n, &k); - for (uint32_t xb = 2; xb <= OMEGA_BF16_MAX_XBATCH && xb <= g->heads; xb++) - if (omega_gpu_bf16_prepare_xbatch(k, xb, g->am_ctas * OMEGA_DEC_ARGMAX_SPAN) != OMEGA_GPU_BF16_OK) return OMEGA_GPU_DGRAPH_CHIP_FAIL; - } - g->batch = 1; - return OMEGA_GPU_DGRAPH_OK; -} -int omega_gpu_q36_graph_batch(const OmegaGpuQ36Graph *g) { return g ? g->batch : 0; } - -/* the dense segment entries of the open stroke: {mix, o} per layer, row0 0, cnt = the stroke's heads (host region, synced by begin_stroke) */ -static void write_dense_segments(OmegaGpuQ36Graph *g, uint32_t heads) { - Seg32 *s = cpu_of(g, g->lo.segd); - for (uint32_t l = 0; l < g->cfg.layers; l++) { - memset(&s[l * SEGD_ROWS], 0, SEGD_ROWS * sizeof *s); - if (!g->layer[l].set) continue; - (void)omega_gpu_fp8_tensor_entry(g->layer[l].mix, 0, &s[l * SEGD_ROWS].w_va, &s[l * SEGD_ROWS].s_va); - (void)omega_gpu_fp8_tensor_entry(g->layer[l].o, 0, &s[l * SEGD_ROWS + 1].w_va, &s[l * SEGD_ROWS + 1].s_va); - s[l * SEGD_ROWS].cnt = heads; s[l * SEGD_ROWS + 1].cnt = heads; - } -} - -static int rec_gemm(OmegaGpuQ36Graph *g, uint8_t kind, const OmegaGpuFp8Tensor *t, uint32_t rows, uint32_t segs, uint64_t seg, uint64_t xp, - uint64_t y, uint64_t xm, uint64_t ym) { - return after_op(g, kind, omega_gpu_fp8gemm_record(g->cl, t, rows, segs, seg, xp, y, xm, ym, 0, 0, NULL)); -} -/* rows of width floats permuted through tab into out (the GEMM's x' lane layout); the input row stride is the kernel's */ -static int rec_perm(OmegaGpuQ36Graph *g, int ki, uint64_t in, uint64_t tab, uint64_t out, uint32_t width, uint32_t rows) { - uint32_t w[OMEGA_DEC_GA_WORDS]; memset(w, 0, sizeof w); - put64(w, OMEGA_DEC_GA_IN, in); put64(w, OMEGA_DEC_GA_TAB, tab); put64(w, OMEGA_DEC_GA_OUT, out); - return add_glue(g, OMEGA_GPU_Q36_K_PERM, ki, (width + OMEGA_DEC_THREADS - 1) / OMEGA_DEC_THREADS, rows, (size_t)width * rows, w, OMEGA_DEC_GA_WORDS); -} -/* COMBINE|NORM of every head in one launch (L356): head h's residual x + h * 2048, down outputs a + h * 9 * 2048, weights - * w + h * lb_stride, output y + h * 2048 (the xq or hidden slots). Each row runs the one-head program. ON unless - * AIEN_OMEGA_Q36_CN_ROWS=0 (the per-head launches). */ -static int g_cn_rows = -1; -static int q36_cn_rows(void) { - if (g_cn_rows < 0) { const char *e = getenv("AIEN_OMEGA_Q36_CN_ROWS"); g_cn_rows = (e && e[0] == '0' && e[1] == 0) ? 0 : 1; } - return g_cn_rows; -} -static int rec_cn_rows(OmegaGpuQ36Graph *g, uint64_t x, uint64_t a, uint64_t wts, uint64_t nw, uint64_t y, float scale, uint32_t rows) { - uint32_t w[OMEGA_DEC_RES_WORDS]; memset(w, 0, sizeof w); - put64(w, OMEGA_DEC_RES_X, x); put64(w, OMEGA_DEC_RES_A, a); put64(w, OMEGA_DEC_RES_W, wts); put64(w, OMEGA_DEC_RES_NW, nw); - put64(w, OMEGA_DEC_RES_Y, y); putf(w, OMEGA_DEC_RES_EPS, g->cfg.eps); putf(w, OMEGA_DEC_RES_SCALE, scale); - return add_glue(g, OMEGA_GPU_Q36_K_RES, g->mutant == 4 ? K_CN_R_M3 : K_CN_R, 1, rows, (size_t)H * rows, w, OMEGA_DEC_RES_WORDS); -} -/* RES NORM|ROWS or ADD|ROWS over rows of 2048 (x, a, y move by the width per row) */ -static int rec_res_rows(OmegaGpuQ36Graph *g, int ki, uint64_t x, uint64_t a, uint64_t nw, uint64_t y, float scale, uint32_t rows) { - uint32_t w[OMEGA_DEC_RES_WORDS]; memset(w, 0, sizeof w); - put64(w, OMEGA_DEC_RES_X, x); put64(w, OMEGA_DEC_RES_A, a); put64(w, OMEGA_DEC_RES_NW, nw); put64(w, OMEGA_DEC_RES_Y, y); - putf(w, OMEGA_DEC_RES_EPS, g->cfg.eps); putf(w, OMEGA_DEC_RES_SCALE, scale); - return add_glue(g, ki == K_NORM_R ? OMEGA_GPU_Q36_K_NORM : OMEGA_GPU_Q36_K_RES, ki, 1, rows, (size_t)H * rows, w, OMEGA_DEC_RES_WORDS); -} - -int omega_gpu_q36_graph_record_layer_heads(OmegaGpuQ36Graph *g, uint32_t l, const uint32_t *pos) { - if (!g || !g->in_token || !pos) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (g->failed) return OMEGA_GPU_DGRAPH_CHIP_FAIL; - if (!g->batch) return fail(g, "q36 graph: record_layer_heads needs set_batch", OMEGA_GPU_DGRAPH_BAD_ARGS); - if (l >= g->cfg.layers || !g->layer[l].set || (l + 1 == g->cfg.layers && !g->final_set)) - return fail(g, "q36 graph: layer not set, out of order, or final norm missing", OMEGA_GPU_DGRAPH_BAD_ARGS); - const uint32_t N = g->stroke_heads, R = N * NG, ki = g->layer[l].kind_index; - for (uint32_t h = 0; h < N; h++) - if (g->hidden_ready[h] || g->xq_layer[h] != g->xq_layer[0]) return fail(g, "q36 graph: heads out of step", OMEGA_GPU_DGRAPH_BAD_ARGS); - const Layout *L = &g->lo; - const uint64_t x0 = va_of(g, x_of(g, 0)), xq0 = va_of(g, xq_of(g, 0)), xp = va_of(g, L->xp), mixN = va_of(g, L->mixN), abN = va_of(g, L->abN); - const uint64_t aggN = va_of(g, L->aggN), attN = va_of(g, L->attN), op = va_of(g, L->op), oN = va_of(g, L->oN), rlb = va_of(g, L->rlb); - const uint64_t sgu = va_of(g, L->sgu), sdn = va_of(g, L->sdn), xmap = va_of(g, L->xmap), ymap = va_of(g, L->ymap), xp2 = va_of(g, L->xp2); - const uint64_t guN = va_of(g, L->guN), actN = va_of(g, L->actN), actp = va_of(g, L->actp), dnN = va_of(g, L->dnN); - const uint64_t pt2048 = va_of(g, L->ptab), pt4096 = pt2048 + (uint64_t)H * 4u, pt512 = pt4096 + (uint64_t)OMEGA_GPU_Q36_MIXER_OUT * 4u; - const uint64_t in_norm = va_of(g, L->norms) + (uint64_t)l * H * 4u, segd = va_of(g, L->segd) + (uint64_t)l * SEGD_ROWS * OMEGA_GEMM_SEG_BYTES; - const uint64_t XS = (uint64_t)H * 4u, MOS = (uint64_t)OMEGA_GPU_Q36_MIXER_OUT * 4u; - int rc = OMEGA_GPU_DGRAPH_OK; - /* input norm of every head (layer 0; after that the previous layer's COMBINE|NORM left layer l's x' in the xq slots) */ - if (g->xq_layer[0] != (int)l) rc = rec_res_rows(g, K_NORM_R, x0, 0, in_norm, xq0, SCALE_2P64, N); - /* x' of the dense trunk: the N xq rows in the GEMM's lane layout */ - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_XQ, xq0, pt2048, xp, H, N); - if (!g->layer[l].attn) { - if (rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_Q36_K_AB, omega_gpu_bf16_gemv_rows_record(g->cl, g->layer[l].ab, N, xq0, abN)); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_gemm(g, OMEGA_GPU_Q36_K_MIX, g->layer[l].mix, N, 1, segd, xp, mixN, 0, 0); - for (uint32_t h = 0; h < N && rc == OMEGA_GPU_DGRAPH_OK; h++) { - const uint64_t mix_h = mixN + (uint64_t)h * OMEGA_GPU_Q36_GDN_MIX * 4u; - uint64_t mo = 0; - rc = after_op(g, OMEGA_GPU_Q36_K_GDN, omega_gpu_gdn_record(g->cl, g->gdn_h[h], ki, mix_h, mix_h + OMEGA_GPU_Q36_GDN_QKV * 4u, - abN + (uint64_t)h * OMEGA_GPU_Q36_AB * 4u, g->cfg.eps_l2, g->cfg.eps, 1.0f, SCALE_2P64, &mo)); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_O, mo, pt4096, op + h * MOS, OMEGA_GPU_Q36_MIXER_OUT, 1); - } - } else { - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_gemm(g, OMEGA_GPU_Q36_K_MIX, g->layer[l].mix, N, 1, segd, xp, mixN, 0, 0); /* n 9216: the rows are 9216 apart */ - uint32_t w[OMEGA_DEC_GA_WORDS]; memset(w, 0, sizeof w); - put64(w, OMEGA_DEC_GA_IN, mixN); put64(w, OMEGA_DEC_GA_TAB, va_of(g, L->gtab)); put64(w, OMEGA_DEC_GA_OUT, aggN); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q36_K_GATHER, g->mutant == 2 ? K_GATHER_M1 : K_GATHER, (OMEGA_GPU_Q36_ATT_MIX + OMEGA_DEC_THREADS - 1) / OMEGA_DEC_THREADS, N, - (size_t)OMEGA_GPU_Q36_ATT_MIX * N, w, OMEGA_DEC_GA_WORDS); - for (uint32_t h = 0; h < N && rc == OMEGA_GPU_DGRAPH_OK; h++) { - const uint64_t agg_h = aggN + (uint64_t)h * OMEGA_GPU_Q36_ATT_MIX * 4u, att_h = attN + h * MOS; - rc = after_op(g, OMEGA_GPU_Q36_K_ATTN, omega_gpu_decode_attn256_record(g->cl, g->attn_h[h], ki, pos[h], agg_h, g->cfg.eps, SCALE_2P64, att_h)); - uint32_t w2[OMEGA_DEC_GT_WORDS]; memset(w2, 0, sizeof w2); - put64(w2, OMEGA_DEC_GT_A, att_h); put64(w2, OMEGA_DEC_GT_G, agg_h + OMEGA_GPU_Q36_ATT_QKV * 4u); put64(w2, OMEGA_DEC_GT_OUT, att_h); - w2[(OMEGA_DEC_GT_N - 0x380) / 4] = OMEGA_GPU_Q36_MIXER_OUT; - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q36_K_GATE, g->mutant == 3 ? K_GATE_M1 : K_GATE, OMEGA_GPU_Q36_MIXER_OUT / OMEGA_DEC_THREADS, 1, - OMEGA_GPU_Q36_MIXER_OUT, w2, OMEGA_DEC_GT_WORDS); - } - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_O, attN, pt4096, op, OMEGA_GPU_Q36_MIXER_OUT, N); - } - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_gemm(g, OMEGA_GPU_Q36_K_O, g->layer[l].o, N, 1, segd + OMEGA_GEMM_SEG_BYTES, op, oN, 0, 0); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_res_rows(g, K_ADD_R, x0, oN, 0, 0, 1.0f, N); - /* the sparse block: one router launch for the N heads (lever 2: the gate table read once; head h's buffer at rlb + h * lb_stride), - * GROUP sorts their picks into one segment table, two grouped GEMMs */ - OmegaGpuRouterDevOut r0; memset(&r0, 0, sizeof r0); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_ROUTER, omega_gpu_router_record_rows(g->cl, g->cfg.router, l, x0, (uint32_t)XS, g->cfg.eps, 1, SCALE_2P64, - rlb, L->lb_stride, N, &r0)); - uint32_t wg[OMEGA_DEC_GR_WORDS]; memset(wg, 0, sizeof wg); - put64(wg, OMEGA_DEC_GR_IDS, r0.ids_va); put64(wg, OMEGA_DEC_GR_TGU, r0.tab_gu_va); put64(wg, OMEGA_DEC_GR_TDN, r0.tab_dn_va); - put64(wg, OMEGA_DEC_GR_SGU, sgu); put64(wg, OMEGA_DEC_GR_SDN, sdn); put64(wg, OMEGA_DEC_GR_XMAP, xmap); put64(wg, OMEGA_DEC_GR_YMAP, ymap); - wg[(OMEGA_DEC_GR_STRIDE - 0x380) / 4] = L->lb_stride; wg[(OMEGA_DEC_GR_HEADS - 0x380) / 4] = N; - if (rc == OMEGA_GPU_DGRAPH_OK) rc = add_glue(g, OMEGA_GPU_Q36_K_GROUP, K_GROUP, 1, 1, R, wg, OMEGA_DEC_GR_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_XO, r0.xout_va, pt2048, xp2, H, N); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_gemm(g, OMEGA_GPU_Q36_K_GATE_UP, g->layer[l].gu, R, R, sgu, xp2, guN, xmap, ymap); - uint32_t w3[OMEGA_DEC_SW_WORDS]; memset(w3, 0, sizeof w3); - put64(w3, OMEGA_DEC_SW_GU, guN); put64(w3, OMEGA_DEC_SW_ACT, actN); putf(w3, OMEGA_DEC_SW_SCALE, SCALE_2P64); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q36_K_SWIGLU, g->mutant == 1 ? K_SW_M1 : K_SW, EI / OMEGA_DEC_THREADS, R, (size_t)R * EI, w3, OMEGA_DEC_SW_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_ACT, actN, pt512, actp, EI, R); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_gemm(g, OMEGA_GPU_Q36_K_DOWN, g->layer[l].dn, R, R, sdn, actp, dnN, ymap, ymap); - const int last = l + 1 == g->cfg.layers; - const uint64_t nw = last ? va_of(g, L->fnorm) : in_norm + H * 4u; - if (q36_cn_rows()) { - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = rec_cn_rows(g, x0, dnN, r0.wts_va, nw, last ? va_of(g, hidden_of(g, 0)) : xq0, last && !g->head8 ? 1.0f : SCALE_2P64, N); - for (uint32_t h = 0; h < N && rc == OMEGA_GPU_DGRAPH_OK; h++) { if (last) g->hidden_ready[h] = 1; else g->xq_layer[h] = (int)l + 1; } - } else for (uint32_t h = 0; h < N && rc == OMEGA_GPU_DGRAPH_OK; h++) { - rc = rec_res_w(g, g->mutant == 4 ? K_CN_M3 : K_CN, x0 + h * XS, dnN + (uint64_t)h * NG * H * 4u, r0.wts_va + (uint64_t)h * L->lb_stride, nw, - last ? va_of(g, hidden_of(g, h)) : xq0 + h * XS, last && !g->head8 ? 1.0f : SCALE_2P64); - if (rc == OMEGA_GPU_DGRAPH_OK) { if (last) g->hidden_ready[h] = 1; else g->xq_layer[h] = (int)l + 1; } - } - return rc == OMEGA_GPU_DGRAPH_OK ? rc : fail(g, NULL, rc); -} - -/* the two-stage argmax of one head's logits slot into its token slot (token: index, token + 4: value) */ -static int rec_argmax(OmegaGpuQ36Graph *g, uint64_t logits, uint64_t token) { - 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, 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, token + 4u); put64(a1, OMEGA_DEC_AM_OI, token); - int rc = add_glue(g, OMEGA_GPU_Q36_K_ARGMAX, 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_Q36_K_ARGMAX, K_AM1, 1, 1, OMEGA_DEC_ARGMAX_SPAN, a1, OMEGA_DEC_AM_WORDS); - return rc; -} - -int omega_gpu_q36_graph_record_final(OmegaGpuQ36Graph *g) { return omega_gpu_q36_graph_record_head_final(g, 0); } - -int omega_gpu_q36_graph_record_head_final(OmegaGpuQ36Graph *g, uint32_t h) { - if (!g || !g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (g->failed) return OMEGA_GPU_DGRAPH_CHIP_FAIL; - if (h >= g->stroke_heads) return fail(g, "q36 graph: head not in the stroke", OMEGA_GPU_DGRAPH_BAD_ARGS); - if (!g->final_set) return fail(g, "q36 graph: final norm not set", OMEGA_GPU_DGRAPH_BAD_ARGS); - const uint64_t x = va_of(g, x_of(g, h)), hidden = va_of(g, hidden_of(g, h)), logits = va_of(g, logits_of(g, h)), token = va_of(g, token_of(g, h)); - int rc = OMEGA_GPU_DGRAPH_OK; - if (!g->hidden_ready[h]) rc = rec_res(g, K_NORM, x, 0, va_of(g, g->lo.fnorm), hidden, g->head8 ? SCALE_2P64 : 1.0f); - const uint64_t amv = va_of(g, g->lo.am_v), ami = va_of(g, g->lo.am_i); - if (rc == OMEGA_GPU_DGRAPH_OK && omega_gpu_q36_graph_exact_head_active_head(g, h)) { - /* HUM L314 two-pass head: h8 = hidden * 2^64 (exact); s = screen . h8; lo / hi = s -/+ c|hidden|; tau = max lo; - * logits = lm_head . hidden on the rows with hi >= tau (today's bits), -inf elsewhere. The argmax below is then - * today's token: the full argmax row has hi >= its logit >= tau (omega_blackwell_codegen_dec.h XBOUND). */ - uint32_t xs[OMEGA_DEC_XB_WORDS], xb[OMEGA_DEC_XB_WORDS], t0[OMEGA_DEC_AM_WORDS], t1[OMEGA_DEC_AM_WORDS]; - memset(xs, 0, sizeof xs); memset(xb, 0, sizeof xb); memset(t0, 0, sizeof t0); memset(t1, 0, sizeof t1); - put64(xs, OMEGA_DEC_XB_S, hidden); put64(xs, OMEGA_DEC_XB_LO, g->xh.h8); xs[(OMEGA_DEC_XB_N - 0x380) / 4] = H; - put64(xb, OMEGA_DEC_XB_S, g->xh.s); put64(xb, OMEGA_DEC_XB_C, g->xh.c); put64(xb, OMEGA_DEC_XB_H, hidden); - put64(xb, OMEGA_DEC_XB_LO, g->xh.lo); put64(xb, OMEGA_DEC_XB_HI, g->xh.hi); xb[(OMEGA_DEC_XB_N - 0x380) / 4] = g->cfg.vocab; - put64(t0, OMEGA_DEC_AM_V, g->xh.lo); put64(t0, OMEGA_DEC_AM_I, 0); put64(t0, OMEGA_DEC_AM_OV, amv); put64(t0, OMEGA_DEC_AM_OI, ami); - put64(t1, OMEGA_DEC_AM_V, amv); put64(t1, OMEGA_DEC_AM_I, ami); put64(t1, OMEGA_DEC_AM_OV, g->xh.tau); put64(t1, OMEGA_DEC_AM_OI, g->xh.tau + 4u); - rc = add_glue(g, OMEGA_GPU_Q36_K_LM_HEAD, K_XS, H / OMEGA_DEC_THREADS, 1, H, xs, OMEGA_DEC_XB_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_fp8(g, OMEGA_GPU_Q36_K_LM_HEAD, g->xh.screen, g->xh.tab, g->xh.h8, g->xh.s); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q36_K_LM_HEAD, g->mutant == 6 ? K_XB_M1 : K_XB, (g->cfg.vocab + OMEGA_DEC_THREADS - 1) / OMEGA_DEC_THREADS, 1, - g->cfg.vocab, xb, OMEGA_DEC_XB_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = add_glue(g, OMEGA_GPU_Q36_K_ARGMAX, K_AM0, g->am_ctas, 1, (size_t)g->am_ctas * OMEGA_DEC_ARGMAX_SPAN, t0, OMEGA_DEC_AM_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = add_glue(g, OMEGA_GPU_Q36_K_ARGMAX, K_AM1, 1, 1, OMEGA_DEC_ARGMAX_SPAN, t1, OMEGA_DEC_AM_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_LM_HEAD, omega_gpu_bf16_gemv_mask_record(g->cl, g->cfg.lm_head, hidden, logits, g->xh.hi, g->xh.tau)); - } else if (rc == OMEGA_GPU_DGRAPH_OK) - rc = g->head8 ? rec_fp8(g, OMEGA_GPU_Q36_K_LM_HEAD, g->head8, va_of(g, g->lo.tabs) + (uint64_t)g->cfg.layers * 64u, hidden, logits) - : after_op(g, OMEGA_GPU_Q36_K_LM_HEAD, omega_gpu_bf16_gemv_record(g->cl, g->cfg.lm_head, hidden, logits)); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_argmax(g, logits, token); - return rc == OMEGA_GPU_DGRAPH_OK ? rc : fail(g, NULL, rc); -} - -/* The batch's final head (v2 lever 1, L312): every head's hidden is ready after the last layer (record_layer_heads), so - * the bf16 lm_head runs once per group of up to OMEGA_BF16_MAX_XBATCH heads (the XBATCH form: x rows hidden_of(h0..), - * y rows logits_of(h0..), ystride the logits slot; each row bit-identical to its own one-head launch), then the argmax - * per head. The FP8 head keeps the per-head path (stroke() calls record_head_final). */ -static int record_final_heads(OmegaGpuQ36Graph *g) { - const uint32_t N = g->stroke_heads; - if (!g->final_set) return fail(g, "q36 graph: final norm not set", OMEGA_GPU_DGRAPH_BAD_ARGS); - for (uint32_t h = 0; h < N; h++) - if (!g->hidden_ready[h]) return fail(g, "q36 graph: batch final before the last layer", OMEGA_GPU_DGRAPH_BAD_ARGS); - int rc = OMEGA_GPU_DGRAPH_OK; - for (uint32_t h0 = 0; h0 < N && rc == OMEGA_GPU_DGRAPH_OK; h0 += OMEGA_BF16_MAX_XBATCH) { - const uint32_t xb = N - h0 < OMEGA_BF16_MAX_XBATCH ? N - h0 : OMEGA_BF16_MAX_XBATCH; - rc = after_op(g, OMEGA_GPU_Q36_K_LM_HEAD, omega_gpu_bf16_gemv_xbatch_record(g->cl, g->cfg.lm_head, xb, va_of(g, hidden_of(g, h0)), - va_of(g, logits_of(g, h0)), g->am_ctas * OMEGA_DEC_ARGMAX_SPAN)); - } - for (uint32_t h = 0; h < N && rc == OMEGA_GPU_DGRAPH_OK; h++) rc = rec_argmax(g, va_of(g, logits_of(g, h)), va_of(g, token_of(g, h))); - return rc == OMEGA_GPU_DGRAPH_OK ? rc : fail(g, NULL, rc); -} - -int omega_gpu_q36_graph_end_token(OmegaGpuQ36Graph *g, uint32_t *token, OmegaGpuDecodeGraphStats *st) { return omega_gpu_q36_graph_end_stroke(g, token, st); } - -int omega_gpu_q36_graph_end_stroke(OmegaGpuQ36Graph *g, uint32_t *tokens, 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); - for (uint32_t h = 0; h < g->stroke_heads && rc == OMEGA_GPU_DGRAPH_OK; h++) - if (omega_gpu_decode_attn256_counters_check(g->attn_h[h]) != 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); - for (uint32_t h = 0; h < g->stroke_heads && rc == OMEGA_GPU_DGRAPH_OK; h++) { - const uint32_t t = ((const uint32_t *)cpu_of(g, token_of(g, h)))[0]; - if (t == TOKEN_POISON || t >= g->cfg.vocab) { - char e[96]; omega_gpu_fmt(e, sizeof e, "q36 graph: head %u token output %u not written or out of range", h, t); - rc = fail(g, e, OMEGA_GPU_DGRAPH_CHIP_FAIL); - } else if (tokens) tokens[h] = 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_q36_graph_token(OmegaGpuQ36Graph *g, const float *x_embed, uint32_t pos, uint32_t *token, OmegaGpuDecodeGraphStats *st) { - if (!g) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (omega_gpu_q36_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_q36_graph_record_layer(g, l, pos); - if (!g->failed) (void)omega_gpu_q36_graph_record_final(g); - return omega_gpu_q36_graph_end_token(g, token, st); -} - -int omega_gpu_q36_graph_stroke(OmegaGpuQ36Graph *g, const float *x_embed, const uint32_t *pos, uint32_t heads, uint32_t *tokens, - OmegaGpuDecodeGraphStats *st) { - if (!g || !pos) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (omega_gpu_q36_graph_begin_stroke(g, x_embed, heads) == OMEGA_GPU_DGRAPH_BAD_ARGS) return OMEGA_GPU_DGRAPH_BAD_ARGS; - /* layer-major: every head's layer l before layer l + 1, so one layer's expert rows are warm across the heads; the batch - * (set_batch) records the layer for every head in one set of launches, each weight read once */ - for (uint32_t l = 0; l < g->cfg.layers && !g->failed; l++) { - if (g->batch) (void)omega_gpu_q36_graph_record_layer_heads(g, l, pos); - else for (uint32_t h = 0; h < heads && !g->failed; h++) (void)omega_gpu_q36_graph_record_head_layer(g, h, l, pos[h]); - } - if (g->batch && !g->head8) { if (!g->failed) (void)record_final_heads(g); } - else for (uint32_t h = 0; h < heads && !g->failed; h++) (void)omega_gpu_q36_graph_record_head_final(g, h); - return omega_gpu_q36_graph_end_stroke(g, tokens, st); -} - -int omega_gpu_q36_graph_read(OmegaGpuQ36Graph *g, float *x, float *hidden, float *logits) { return omega_gpu_q36_graph_read_head(g, 0, x, hidden, logits); } - -int omega_gpu_q36_graph_read_head(OmegaGpuQ36Graph *g, uint32_t h, float *x, float *hidden, float *logits) { - if (!g || g->in_token || h >= g->heads) 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, x_of(g, h)), H * 4u); - if (hidden) memcpy(hidden, cpu_of(g, hidden_of(g, h)), H * 4u); - if (hidden && g->head8) for (unsigned i = 0; i < H; i++) hidden[i] *= 0x1p-64f; /* exact: a power of two */ - if (logits) memcpy(logits, cpu_of(g, logits_of(g, h)), (size_t)g->cfg.vocab * 4u); - } - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_q36_graph_read_buf(OmegaGpuQ36Graph *g, int which, float *out, uint32_t n) { - if (!g || g->in_token || !out || which < 0 || which >= OMEGA_GPU_Q36_BUF_COUNT) return OMEGA_GPU_DGRAPH_BAD_ARGS; - const struct { size_t off; uint32_t cap; } b[OMEGA_GPU_Q36_BUF_COUNT] = { - [OMEGA_GPU_Q36_BUF_X] = { g->lo.x, H }, [OMEGA_GPU_Q36_BUF_XQ] = { g->lo.xq, H }, [OMEGA_GPU_Q36_BUF_MIX] = { g->lo.mix, OMEGA_GPU_Q36_GDN_MIX }, - [OMEGA_GPU_Q36_BUF_AB] = { g->lo.ab, OMEGA_GPU_Q36_AB }, [OMEGA_GPU_Q36_BUF_AGG] = { g->lo.agg, OMEGA_GPU_Q36_ATT_MIX }, - [OMEGA_GPU_Q36_BUF_ATT] = { g->lo.att, OMEGA_GPU_Q36_MIXER_OUT }, [OMEGA_GPU_Q36_BUF_O] = { g->lo.o, H }, - [OMEGA_GPU_Q36_BUF_GU] = { g->lo.gu, NG * 2 * EI }, [OMEGA_GPU_Q36_BUF_ACT] = { g->lo.act, NG * EI }, [OMEGA_GPU_Q36_BUF_HIDDEN] = { g->lo.hidden, H }, - [OMEGA_GPU_Q36_BUF_DN] = { g->lo.dn, NG * H }, - }; - if (n > b[which].cap) return OMEGA_GPU_DGRAPH_BAD_ARGS; - omega_gpu_session_lock(); - int rc = OMEGA_GPU_DGRAPH_OK; - size_t from = b[which].off; - if (from >= g->lo.split && n) { - /* a chip-only region: K_COPY moves ceil(n / 256) rows of 256 floats into stage (every cap is a multiple of 256) */ - uint32_t w[OMEGA_DEC_GA_WORDS]; memset(w, 0, sizeof w); - put64(w, OMEGA_DEC_GA_IN, va_of(g, from)); put64(w, OMEGA_DEC_GA_TAB, va_of(g, g->lo.idtab)); put64(w, OMEGA_DEC_GA_OUT, va_of(g, g->lo.stage)); - const Kern *k = &g->k[K_COPY]; - 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 = 1; L.grid_y = (n + COPY_ROW - 1) / COPY_ROW; - L.num_elements = (size_t)L.grid_y * COPY_ROW; L.args = w; L.n_args = OMEGA_DEC_GA_WORDS; L.timeout_ms = TIMEOUT_MS; - if (!omega_gpu_session_open() || omega_gpu_session_launch(&L, NULL, NULL) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - from = g->lo.stage; - } - if (rc == OMEGA_GPU_DGRAPH_OK && omega_gpu_session_sync_to_cpu(&g->buf) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - if (rc == OMEGA_GPU_DGRAPH_OK) memcpy(out, cpu_of(g, from), (size_t)n * 4u); - omega_gpu_session_unlock(); - return rc; -} - -/* ---- timeline ---- */ -void omega_gpu_q36_graph_set_stamps(OmegaGpuQ36Graph *g, int on) { if (g && !g->in_token) g->stamps = on ? 1 : 0; } - -int omega_gpu_q36_graph_stamps(const OmegaGpuQ36Graph *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("q36 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("q36 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_q36_graph_kind_name(uint8_t kind) { - static const char *const names[OMEGA_GPU_Q36_K_COUNT] = { "norm", "mix", "ab", "gdn", "gather", "attn", "gate", "o_proj", "res", "router", - "gate_up", "swiglu", "down", "lm_head", "argmax", "perm", "group" }; - return kind < OMEGA_GPU_Q36_K_COUNT ? names[kind] : "?"; -} - -/* ---- the prefill (L369): one conversation's prompt chunk through the chip as rows ---- - * Every arithmetic step of a prompt token is the decode step's: the dense trunk and the experts through the fp8 gemm record - * path (bit-identical to the GEMV per row), a|b through the bf16 ROWS form, the router through its ROWS form, and the GDN step - * and the attention launched once per token, in token order, on the conversation's own state at pos0 + t. The expert rows are - * grouped on the host between two lists per layer (the GROUP kernel holds 128 rows; a chunk holds up to 128 x 8). */ -#define PF_PAD 8u -#define PF_EXPERT_BYTES ((uint64_t)3u * EI * H) /* one expert's e4m3 gate|up (2 x EI x H) and down (H x EI) */ -static int pf_fail(OmegaGpuQ36Graph *g, const char *what) { return fail(g, what, OMEGA_GPU_DGRAPH_BAD_ARGS); } - -int omega_gpu_q36_graph_prefill_alloc(OmegaGpuQ36Graph *g, uint32_t cap) { - if (!g || g->in_token || cap == 0 || cap > OMEGA_GPU_Q36_PREFILL_MAX_ROWS) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (g->pf.cap >= cap) return OMEGA_GPU_DGRAPH_OK; - const size_t P = cap, R = P * NG, RR = P * (NG - 1u), lbs = g->lo.lb_stride; - size_t ho = 0, dof = 0; -#define HREG(f, b) do { g->pf.f = ho; ho += al(b); } while (0) -#define DREG(f, b) do { g->pf.f = dof; dof += al(b); } while (0) - HREG(x, P * H * 4); HREG(rlb, P * lbs); HREG(sgu, 256u * OMEGA_GEMM_SEG_BYTES); HREG(sdn, 256u * OMEGA_GEMM_SEG_BYTES); - HREG(sgu2, OMEGA_GEMM_SEG_BYTES); HREG(sdn2, OMEGA_GEMM_SEG_BYTES); HREG(xmap, (RR + PF_PAD) * 4); HREG(ymap, (RR + PF_PAD) * 4); - HREG(xmap2, (P + PF_PAD) * 4); HREG(ymap2, (P + PF_PAD) * 4); - DREG(xq, P * H * 4); DREG(xp, (P + PF_PAD) * H * 4); DREG(mixN, P * OMEGA_GPU_Q36_GDN_MIX * 4); DREG(abN, P * OMEGA_GPU_Q36_AB * 4); - DREG(aggN, P * OMEGA_GPU_Q36_ATT_MIX * 4); DREG(attN, P * OMEGA_GPU_Q36_MIXER_OUT * 4); DREG(op, (P + PF_PAD) * OMEGA_GPU_Q36_MIXER_OUT * 4); - DREG(oN, P * H * 4); DREG(xp2, (P + PF_PAD) * H * 4); DREG(guN, R * 2 * EI * 4); DREG(actN, R * EI * 4); DREG(actp, (R + PF_PAD) * EI * 4); - DREG(dnN, R * H * 4); -#undef HREG -#undef DREG - omega_gpu_session_lock(); - if (g->pf.hb.cpu) omega_gpu_session_free(&g->pf.hb); - if (g->pf.db.cpu) omega_gpu_session_free(&g->pf.db); - g->pf.cap = 0; - const char *pbc = getenv("AIEN_OMEGA_Q36_BUF_CACHED"); - int (*const dalloc)(size_t, OmegaGpuMem *) = (pbc && pbc[0] == '0' && pbc[1] == 0) ? omega_gpu_session_alloc : omega_gpu_session_alloc_cached; - int rc = (!omega_gpu_session_open() || omega_gpu_session_alloc(ho, &g->pf.hb) != 0 || dalloc(dof, &g->pf.db) != 0) ? OMEGA_GPU_DGRAPH_CHIP_FAIL - : OMEGA_GPU_DGRAPH_OK; - if (rc == OMEGA_GPU_DGRAPH_OK) memset(g->pf.hb.cpu, 0, ho); - omega_gpu_session_unlock(); - /* pin the shapes the prefill records (a kernel cache miss while recording is refused): the dense trunk without maps (8 rows - * per pass), the expert blocks with the row maps at 4 rows per pass, the router's ROWS kernel */ - if (rc == OMEGA_GPU_DGRAPH_OK) { - int r = omega_gpu_fp8gemm_prepare_shape(H, 1, 0, 0); - if (r == 0) r = omega_gpu_fp8gemm_prepare_shape(OMEGA_GPU_Q36_MIXER_OUT, 1, 0, 0); - if (r == 0) r = omega_gpu_fp8gemm_prepare_shape(H, 64, 4, 1); - if (r == 0) r = omega_gpu_fp8gemm_prepare_shape(EI, 64, 4, 1); - if (r == 0 && omega_gpu_router_prepare_rows(g->cfg.router, H * 4u, g->lo.lb_stride) != OMEGA_GPU_ROUTER_OK) r = -1; - if (r != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - } - if (rc != OMEGA_GPU_DGRAPH_OK) return rc; - const char *m = getenv("AIEN_OMEGA_Q36_PF_MUTANT"); - g->pf.mutant = m ? atoi(m) : 0; - const char *gm = getenv("AIEN_OMEGA_Q36_PF_GDN"); - g->pf.gdn_multi = !(gm && gm[0] == '0' && gm[1] == 0); - for (uint32_t h = 0; h < g->heads && g->pf.gdn_multi; h++) - if (g->gdn_h[h] && omega_gpu_gdn_multi_prepare(g->gdn_h[h]) != OMEGA_GPU_GDN_OK) return OMEGA_GPU_DGRAPH_CHIP_FAIL; - const char *am = getenv("AIEN_OMEGA_Q36_PF_ATTN"); - g->pf.attn_multi = !(am && am[0] == '0' && am[1] == 0); - for (uint32_t h = 0; h < g->heads && g->pf.attn_multi; h++) - if (g->attn_h[h] && omega_gpu_decode_attn256_multi_prepare(g->attn_h[h]) != OMEGA_GPU_DATTN_OK) return OMEGA_GPU_DGRAPH_CHIP_FAIL; - omega_gpu_decode_attn256_test_set_multi_mutant(g->pf.mutant == 6 ? 1 : 0); /* TEST mutant 6: the attention prep launch dropped */ - g->pf.cap = cap; - return OMEGA_GPU_DGRAPH_OK; -} -uint32_t omega_gpu_q36_graph_prefill_cap(const OmegaGpuQ36Graph *g) { return g ? g->pf.cap : 0; } -uint64_t omega_gpu_q36_graph_prefill_streamed(const OmegaGpuQ36Graph *g) { return g ? g->pf.streamed : 0; } - -static uint64_t pf_h(const OmegaGpuQ36Graph *g, size_t off) { return g->pf.hb.va + off; } -static void *pf_hc(const OmegaGpuQ36Graph *g, size_t off) { return (uint8_t *)g->pf.hb.cpu + off; } -static uint64_t pf_d(const OmegaGpuQ36Graph *g, size_t off) { return g->pf.db.va + off; } - -/* part (a) of layer l: the mixer of every row and the router; ends with the router outputs in pf.rlb */ -static int pf_record_mixer(OmegaGpuQ36Graph *g, uint32_t head, uint32_t l, uint32_t n, uint32_t pos0, uint32_t *ids_off, uint32_t *wts_off, uint32_t *xo_off) { - const uint32_t ki = g->layer[l].kind_index; - const uint64_t x0 = pf_h(g, g->pf.x), xq0 = pf_d(g, g->pf.xq), xp = pf_d(g, g->pf.xp), mixN = pf_d(g, g->pf.mixN), abN = pf_d(g, g->pf.abN); - const uint64_t aggN = pf_d(g, g->pf.aggN), attN = pf_d(g, g->pf.attN), op = pf_d(g, g->pf.op), oN = pf_d(g, g->pf.oN), rlb = pf_h(g, g->pf.rlb); - const uint64_t pt2048 = va_of(g, g->lo.ptab), pt4096 = pt2048 + (uint64_t)H * 4u; - const uint64_t in_norm = va_of(g, g->lo.norms) + (uint64_t)l * H * 4u, segd = va_of(g, g->lo.segd) + (uint64_t)l * SEGD_ROWS * OMEGA_GEMM_SEG_BYTES; - const uint64_t XS = (uint64_t)H * 4u, MOS = (uint64_t)OMEGA_GPU_Q36_MIXER_OUT * 4u; - int rc = OMEGA_GPU_DGRAPH_OK; - /* layer 0 normalizes the embeddings; after that the previous layer's per-token COMBINE|NORM left layer l's x' in xq */ - if (l == 0) rc = rec_res_rows(g, K_NORM_R, x0, 0, in_norm, xq0, SCALE_2P64, n); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_XQ, xq0, pt2048, xp, H, n); - if (!g->layer[l].attn) { - if (rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_Q36_K_AB, omega_gpu_bf16_gemv_rows_record(g->cl, g->layer[l].ab, n, xq0, abN)); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_gemm(g, OMEGA_GPU_Q36_K_MIX, g->layer[l].mix, n, 1, segd, xp, mixN, 0, 0); - if (g->pf.gdn_multi && g->pf.mutant != 1 && g->pf.mutant != 3) { - /* every token's recurrence step in one launch (the decode step T times, bit for bit: omega_gpu_gdn_api.h), the rows - * into attN (unused on a GDN layer), then one PERM over the rows. TEST mutant 5: every token reads token 0's a|b. */ - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_GDN, omega_gpu_gdn_multi_record(g->cl, g->gdn_h[head], ki, n, mixN, mixN + OMEGA_GPU_Q36_GDN_QKV * 4u, - OMEGA_GPU_Q36_GDN_MIX * 4u, abN, g->pf.mutant == 5 ? 0u : OMEGA_GPU_Q36_AB * 4u, - attN, (uint32_t)MOS, g->cfg.eps_l2, g->cfg.eps, 1.0f, SCALE_2P64)); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_O, attN, pt4096, op, OMEGA_GPU_Q36_MIXER_OUT, n); - } else - for (uint32_t i = 0; i < n && rc == OMEGA_GPU_DGRAPH_OK; i++) { - /* TEST mutant 1: the last two tokens' recurrence steps in swapped order */ - const uint32_t t = (g->pf.mutant == 1 && n >= 2 && i + 2 >= n) ? (i + 2 == n ? n - 1 : n - 2) : i; - const uint64_t mix_t = mixN + (uint64_t)t * OMEGA_GPU_Q36_GDN_MIX * 4u; - uint64_t mo = 0; - rc = after_op(g, OMEGA_GPU_Q36_K_GDN, omega_gpu_gdn_record(g->cl, g->gdn_h[head], ki, mix_t, mix_t + OMEGA_GPU_Q36_GDN_QKV * 4u, - abN + (uint64_t)t * OMEGA_GPU_Q36_AB * 4u, g->cfg.eps_l2, g->cfg.eps, 1.0f, SCALE_2P64, &mo)); - /* TEST mutant 3: the copy out of the GDN launch buffer deferred past the next token's step (the buffer is the - * state object's own, one per conversation: every row would read a later token's output) */ - if (rc == OMEGA_GPU_DGRAPH_OK && !(g->pf.mutant == 3 && t + 1 < n)) rc = rec_perm(g, K_PERM_O, mo, pt4096, op + t * MOS, OMEGA_GPU_Q36_MIXER_OUT, 1); - if (rc == OMEGA_GPU_DGRAPH_OK && g->pf.mutant == 3 && t > 0) rc = rec_perm(g, K_PERM_O, mo, pt4096, op + (t - 1) * MOS, OMEGA_GPU_Q36_MIXER_OUT, 1); - } - } else { - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_gemm(g, OMEGA_GPU_Q36_K_MIX, g->layer[l].mix, n, 1, segd, xp, mixN, 0, 0); - uint32_t w[OMEGA_DEC_GA_WORDS]; memset(w, 0, sizeof w); - put64(w, OMEGA_DEC_GA_IN, mixN); put64(w, OMEGA_DEC_GA_TAB, va_of(g, g->lo.gtab)); put64(w, OMEGA_DEC_GA_OUT, aggN); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q36_K_GATHER, g->mutant == 2 ? K_GATHER_M1 : K_GATHER, (OMEGA_GPU_Q36_ATT_MIX + OMEGA_DEC_THREADS - 1) / OMEGA_DEC_THREADS, n, - (size_t)OMEGA_GPU_Q36_ATT_MIX * n, w, OMEGA_DEC_GA_WORDS); - const int attn_multi = g->pf.attn_multi; - if (attn_multi && rc == OMEGA_GPU_DGRAPH_OK) /* every token's attention in one prep + attend pair, bit-identical to the steps */ - rc = after_op(g, OMEGA_GPU_Q36_K_ATTN, omega_gpu_decode_attn256_multi_record(g->cl, g->attn_h[head], ki, pos0, n, aggN, OMEGA_GPU_Q36_ATT_MIX * 4u, - g->cfg.eps, SCALE_2P64, attN, (uint32_t)MOS)); - const int gate_rows = attn_multi && g->mutant != 3; /* every token's gate in one rows launch (the one-row arithmetic per element) */ - if (gate_rows && rc == OMEGA_GPU_DGRAPH_OK) { - uint32_t w2[OMEGA_DEC_GT_WORDS]; memset(w2, 0, sizeof w2); - put64(w2, OMEGA_DEC_GT_A, attN); put64(w2, OMEGA_DEC_GT_G, aggN + OMEGA_GPU_Q36_ATT_QKV * 4u); put64(w2, OMEGA_DEC_GT_OUT, attN); - w2[(OMEGA_DEC_GT_N - 0x380) / 4] = OMEGA_GPU_Q36_MIXER_OUT; - rc = add_glue(g, OMEGA_GPU_Q36_K_GATE, K_GATE_R, OMEGA_GPU_Q36_MIXER_OUT / OMEGA_DEC_THREADS, n, (size_t)OMEGA_GPU_Q36_MIXER_OUT * n, w2, OMEGA_DEC_GT_WORDS); - } - for (uint32_t t = 0; t < n && rc == OMEGA_GPU_DGRAPH_OK && !gate_rows; t++) { - const uint64_t agg_t = aggN + (uint64_t)t * OMEGA_GPU_Q36_ATT_MIX * 4u, att_t = attN + t * MOS; - if (!attn_multi) rc = after_op(g, OMEGA_GPU_Q36_K_ATTN, omega_gpu_decode_attn256_record(g->cl, g->attn_h[head], ki, pos0 + t, agg_t, g->cfg.eps, SCALE_2P64, att_t)); - uint32_t w2[OMEGA_DEC_GT_WORDS]; memset(w2, 0, sizeof w2); - put64(w2, OMEGA_DEC_GT_A, att_t); put64(w2, OMEGA_DEC_GT_G, agg_t + OMEGA_GPU_Q36_ATT_QKV * 4u); put64(w2, OMEGA_DEC_GT_OUT, att_t); - w2[(OMEGA_DEC_GT_N - 0x380) / 4] = OMEGA_GPU_Q36_MIXER_OUT; - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q36_K_GATE, g->mutant == 3 ? K_GATE_M1 : K_GATE, OMEGA_GPU_Q36_MIXER_OUT / OMEGA_DEC_THREADS, 1, - OMEGA_GPU_Q36_MIXER_OUT, w2, OMEGA_DEC_GT_WORDS); - } - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_O, attN, pt4096, op, OMEGA_GPU_Q36_MIXER_OUT, n); - } - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_gemm(g, OMEGA_GPU_Q36_K_O, g->layer[l].o, n, 1, segd + OMEGA_GEMM_SEG_BYTES, op, oN, 0, 0); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_res_rows(g, K_ADD_R, x0, oN, 0, 0, 1.0f, n); - for (uint32_t r0 = 0; r0 < n && rc == OMEGA_GPU_DGRAPH_OK; r0 += OMEGA_GPU_ROUTER_MAX_ROWS) { - const uint32_t rows = n - r0 < OMEGA_GPU_ROUTER_MAX_ROWS ? n - r0 : OMEGA_GPU_ROUTER_MAX_ROWS; - OmegaGpuRouterDevOut r; memset(&r, 0, sizeof r); - const uint64_t lb = rlb + (uint64_t)r0 * g->lo.lb_stride; - rc = after_op(g, OMEGA_GPU_Q36_K_ROUTER, omega_gpu_router_record_rows(g->cl, g->cfg.router, l, x0 + r0 * XS, (uint32_t)XS, g->cfg.eps, 1, SCALE_2P64, - lb, g->lo.lb_stride, rows, &r)); - if (rc == OMEGA_GPU_DGRAPH_OK && r0 == 0) { *ids_off = (uint32_t)(r.ids_va - lb); *wts_off = (uint32_t)(r.wts_va - lb); *xo_off = (uint32_t)(r.xout_va - lb); } - } - return rc; -} - -/* the host GROUP: the n * 8 routed picks sorted by expert id (then token, then slot) into segments and row maps, the shared - * expert as its own one-segment table (x' row t, y row t * 9 + 8). Returns the routed segment count. */ -static uint32_t pf_group(OmegaGpuQ36Graph *g, uint32_t l, uint32_t n, uint32_t ids_off) { - const uint32_t S = NG - 1u; - uint32_t cnt[256], start[256]; - memset(cnt, 0, sizeof cnt); - for (uint32_t t = 0; t < n; t++) { - const uint32_t *id = pf_hc(g, g->pf.rlb + (size_t)t * g->lo.lb_stride + ids_off); - for (uint32_t s = 0; s < S; s++) cnt[id[s] & 255u]++; - } - Seg32 *sg = pf_hc(g, g->pf.sgu), *sd = pf_hc(g, g->pf.sdn); - uint32_t segs = 0, row = 0; - for (uint32_t e = 0; e < 256u; e++) { - start[e] = row; - if (!cnt[e]) continue; - memset(&sg[segs], 0, sizeof *sg); memset(&sd[segs], 0, sizeof *sd); - (void)omega_gpu_fp8_tensor_entry(g->layer[l].gu, e, &sg[segs].w_va, &sg[segs].s_va); - (void)omega_gpu_fp8_tensor_entry(g->layer[l].dn, e, &sd[segs].w_va, &sd[segs].s_va); - sg[segs].row0 = sd[segs].row0 = row; sg[segs].cnt = sd[segs].cnt = cnt[e]; - if (g->pf.mutant == 2 && cnt[e] > 1u) { sg[segs].cnt--; sd[segs].cnt--; } /* TEST mutant 2: every segment one row short */ - g->pf.streamed += (uint64_t)((cnt[e] + 3u) / 4u) * PF_EXPERT_BYTES; /* gate|up and down, 4 rows per pass */ - row += cnt[e]; segs++; - } - uint32_t *xm = pf_hc(g, g->pf.xmap), *ym = pf_hc(g, g->pf.ymap); - for (uint32_t t = 0; t < n; t++) { - const uint32_t *id = pf_hc(g, g->pf.rlb + (size_t)t * g->lo.lb_stride + ids_off); - for (uint32_t s = 0; s < S; s++) { const uint32_t p = start[id[s] & 255u]++; xm[p] = t; ym[p] = t * NG + s; } - } - for (uint32_t p = n * S; p < n * S + PF_PAD; p++) { xm[p] = 0; ym[p] = 0; } - Seg32 *g2 = pf_hc(g, g->pf.sgu2), *d2 = pf_hc(g, g->pf.sdn2); - memset(g2, 0, sizeof *g2); memset(d2, 0, sizeof *d2); - (void)omega_gpu_fp8_tensor_entry(g->layer[l].gu, 256u, &g2->w_va, &g2->s_va); /* expert 256 = the shared expert */ - (void)omega_gpu_fp8_tensor_entry(g->layer[l].dn, 256u, &d2->w_va, &d2->s_va); - g2->cnt = d2->cnt = n; - g->pf.streamed += (uint64_t)((n + 3u) / 4u) * PF_EXPERT_BYTES; - uint32_t *xm2 = pf_hc(g, g->pf.xmap2), *ym2 = pf_hc(g, g->pf.ymap2); - for (uint32_t t = 0; t < n; t++) { xm2[t] = t; ym2[t] = t * NG + S; } - for (uint32_t p = n; p < n + PF_PAD; p++) { xm2[p] = 0; ym2[p] = 0; } - return segs; -} - -/* part (b) of layer l: the experts of every row and the per-token COMBINE|NORM */ -static int pf_record_experts(OmegaGpuQ36Graph *g, uint32_t head, uint32_t l, uint32_t n, uint32_t segs, uint32_t wts_off, uint32_t xo_off) { - const uint64_t x0 = pf_h(g, g->pf.x), xq0 = pf_d(g, g->pf.xq), xp2 = pf_d(g, g->pf.xp2), guN = pf_d(g, g->pf.guN), actN = pf_d(g, g->pf.actN); - const uint64_t actp = pf_d(g, g->pf.actp), dnN = pf_d(g, g->pf.dnN), rlb = pf_h(g, g->pf.rlb); - const uint64_t pt2048 = va_of(g, g->lo.ptab), pt512 = pt2048 + (uint64_t)(H + OMEGA_GPU_Q36_MIXER_OUT) * 4u; - const uint64_t in_norm = va_of(g, g->lo.norms) + (uint64_t)l * H * 4u, XS = (uint64_t)H * 4u; - const uint32_t R = n * NG; const uint32_t S = NG - 1u; /* rows each expert GEMM touches: 8 routed per token, 1 shared */ - int rc = rec_perm(g, K_PERM_XO, rlb + xo_off, pt2048, xp2, H, n); /* the router's x' rows, one launch buffer apart */ - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_GATE_UP, omega_gpu_fp8gemm_record(g->cl, g->layer[l].gu, n * S, segs, pf_h(g, g->pf.sgu), xp2, guN, pf_h(g, g->pf.xmap), - pf_h(g, g->pf.ymap), 4, 0, NULL)); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_GATE_UP, omega_gpu_fp8gemm_record(g->cl, g->layer[l].gu, n, 1, pf_h(g, g->pf.sgu2), xp2, guN, pf_h(g, g->pf.xmap2), - pf_h(g, g->pf.ymap2), 4, 0, NULL)); - uint32_t w3[OMEGA_DEC_SW_WORDS]; memset(w3, 0, sizeof w3); - put64(w3, OMEGA_DEC_SW_GU, guN); put64(w3, OMEGA_DEC_SW_ACT, actN); putf(w3, OMEGA_DEC_SW_SCALE, SCALE_2P64); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q36_K_SWIGLU, g->mutant == 1 ? K_SW_M1 : K_SW, EI / OMEGA_DEC_THREADS, R, (size_t)R * EI, w3, OMEGA_DEC_SW_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_perm(g, K_PERM_ACT, actN, pt512, actp, EI, R); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_DOWN, omega_gpu_fp8gemm_record(g->cl, g->layer[l].dn, n * S, segs, pf_h(g, g->pf.sdn), actp, dnN, pf_h(g, g->pf.ymap), - pf_h(g, g->pf.ymap), 4, 0, NULL)); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q36_K_DOWN, omega_gpu_fp8gemm_record(g->cl, g->layer[l].dn, n, 1, pf_h(g, g->pf.sdn2), actp, dnN, pf_h(g, g->pf.ymap2), - pf_h(g, g->pf.ymap2), 4, 0, NULL)); - const int last = l + 1 == g->cfg.layers; - const uint64_t nw = last ? va_of(g, g->lo.fnorm) : in_norm + H * 4u; - /* the last layer: only the last token's COMBINE|NORM is needed (its hidden feeds the head; the state is complete) */ - if (!last && n > 1u && q36_cn_rows()) /* every token's COMBINE|NORM in one rows launch (L356's rows form, each row the one-row program) */ - return rc == OMEGA_GPU_DGRAPH_OK ? rec_cn_rows(g, x0, dnN, rlb + wts_off, nw, xq0, SCALE_2P64, n) : rc; - for (uint32_t t = last ? n - 1u : 0u; t < n && rc == OMEGA_GPU_DGRAPH_OK; t++) - rc = rec_res_w(g, g->mutant == 4 ? K_CN_M3 : K_CN, x0 + t * XS, dnN + (uint64_t)t * NG * H * 4u, rlb + (uint64_t)t * g->lo.lb_stride + wts_off, nw, - last ? va_of(g, hidden_of(g, head)) : xq0 + t * XS, last && !g->head8 ? 1.0f : SCALE_2P64); - return rc; -} - -int omega_gpu_q36_graph_prefill(OmegaGpuQ36Graph *g, uint32_t head, const float *x_embed, uint32_t n, uint32_t pos0, int want_token, - uint32_t *token, OmegaGpuDecodeGraphStats *st) { - if (!g || g->in_token || !x_embed || n == 0 || head >= g->heads) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (n > g->pf.cap) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (!g->gdn_h[head] || !g->attn_h[head]) return OMEGA_GPU_DGRAPH_BAD_ARGS; - for (uint32_t l = 0; l < g->cfg.layers; l++) if (!g->layer[l].set) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (!g->final_set) 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->stroke_heads = head + 1u; - for (uint32_t h = 0; h <= head; h++) { g->xq_layer[h] = -1; g->hidden_ready[h] = 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); - int rc = OMEGA_GPU_DGRAPH_OK; - if (!omega_gpu_session_open()) rc = fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); - if (rc == OMEGA_GPU_DGRAPH_OK) { - uint32_t *tok = cpu_of(g, token_of(g, head)); tok[0] = TOKEN_POISON; tok[1] = TOKEN_POISON; - memcpy(pf_hc(g, g->pf.x), x_embed, (size_t)n * H * 4u); - write_dense_segments(g, n); - if (omega_gpu_session_sync_to_gpu(&g->buf) != 0 || omega_gpu_session_sync_to_gpu(&g->pf.hb) != 0) rc = fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); - } - for (uint32_t l = 0; l < g->cfg.layers && rc == OMEGA_GPU_DGRAPH_OK; l++) { - uint32_t ids_off = 0, wts_off = 0, xo_off = 0; - rc = pf_record_mixer(g, head, l, n, pos0, &ids_off, &wts_off, &xo_off); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = submit_now(g); - if (rc == OMEGA_GPU_DGRAPH_OK && omega_gpu_session_sync_to_cpu(&g->pf.hb) != 0) rc = fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); - uint32_t segs = 0; - if (rc == OMEGA_GPU_DGRAPH_OK) { - /* the dense trunk: mix (or q|k|v) and o, 8 rows per pass */ - g->pf.streamed += (uint64_t)((n + 7u) / 8u) * H * ((g->layer[l].attn ? OMEGA_GPU_Q36_ATT_MIX : OMEGA_GPU_Q36_GDN_MIX) + OMEGA_GPU_Q36_MIXER_OUT); - segs = pf_group(g, l, n, ids_off); - if (segs == 0 || segs > 256u) rc = pf_fail(g, "q36 prefill: router picks out of range"); - } - if (rc == OMEGA_GPU_DGRAPH_OK && omega_gpu_session_sync_to_gpu(&g->pf.hb) != 0) rc = fail(g, NULL, OMEGA_GPU_DGRAPH_CHIP_FAIL); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = pf_record_experts(g, head, l, n, segs, wts_off, xo_off); - if (rc == OMEGA_GPU_DGRAPH_OK && l + 1 < g->cfg.layers) rc = submit_now(g); - } - if (rc == OMEGA_GPU_DGRAPH_OK) { - g->hidden_ready[head] = 1; - if (want_token) { - rc = omega_gpu_q36_graph_record_head_final(g, head); - } - } - if (rc == OMEGA_GPU_DGRAPH_OK) rc = submit_now(g); - if (rc == OMEGA_GPU_DGRAPH_OK && omega_gpu_decode_attn256_counters_check(g->attn_h[head]) != 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 && want_token) { - const uint32_t t = ((const uint32_t *)cpu_of(g, token_of(g, head)))[0]; - if (t == TOKEN_POISON || t >= g->cfg.vocab) rc = fail(g, "q36 prefill: token output not written or out of range", 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 = t_end - g->t_begin; st->total_ns = t_end - g->t_begin; } - omega_gpu_session_unlock(); - return rc; -} diff --git a/src/omega_gpu_q36_graph.h b/src/omega_gpu_q36_graph.h deleted file mode 100644 index c14475acf..000000000 --- a/src/omega_gpu_q36_graph.h +++ /dev/null @@ -1,197 +0,0 @@ -#ifndef OMEGA_GPU_Q36_GRAPH_H -#define OMEGA_GPU_Q36_GRAPH_H -/* - * omega_gpu_q36_graph: one Qwen3.6-35B-A3B decode token as ONE command list (sc L306, 2026-10-20). The layer mixers are the - * Qwen3.8-27B graph's (omega_gpu_q38_graph.h) at the 35B's shapes; the MLP is the 30B decode graph's sparse block - * (omega_gpu_decode_graph.h) with a ninth group, the shared expert: - * - * (layer 0 only) NORM xq = RMSNorm(x) * in_norm[0] * 2^64 (the FP8 GEMV x' row) - * GDN layer l: fp8 mix mix[12288] = W_qkvz[l] . xq (in_proj_qkv 8192 | in_proj_z 4096) - * bf16 ab ab[64] = W_ab[l] . xq (a/b rows interleaved, uploaded * 2^-64: plain ab out) - * gdn att[4096] = GDN step(mix, mix + 8192, ab) * 2^64 omega_gpu_gdn_record (ratio 2) - * attention l: fp8 mix mix[9216] = W_qgkv[l] . xq (q_proj 16 x [q 256 | gate 256], k_proj 512, v_proj 512) - * GATHER agg[9216] = permuted q | permuted k | v (5120, the attention kernel's row) | gate (4096) - * attn att[4096] = attention(agg, KV[l], pos) * 2^64 omega_gpu_decode_attn256_record (16 / 2) - * GATE att *= sigmoid(agg + 5120) - * every layer: fp8 o o[2048] = W_o[l] . att - * ADD x += o - * router xr = RMSNorm(x) * post_norm[l] * 2^64, ids[9], wts[9], tables omega_gpu_router_record - * (slot 8 = the shared expert, weight sigmoid(shared_expert_gate . xn); omega_gpu_router_alloc_shape) - * fp8 gu gu[9][1024] = W_gu[ids] . xr (gate 512 | up 512; tensor of experts + 1, the last the shared one) - * SWIGLU act[9][512] = silu(gate) * up * 2^64 - * fp8 down dn[9][2048] = W_dn[ids] . act[g] - * COMBINE|NORM x += sum_g wts[g] * dn[g] (9 groups); xq = RMSNorm(x) * in_norm[l + 1] * 2^64, or (last - * layer) hidden = RMSNorm(x) * final_norm - * final: bf16 lm_head logits = W_lm . hidden; ARGMAX x2 (122 CTAs over 248320, then 1) - * (or the exact two-pass head, omega_gpu_q36_graph_set_exact_head: + 5 launches) - * - * Launches: GDN layer 10, attention layer 11, plus 1 + 3. - * Norm weights are passed already folded to (1 + w) (the model's zero-centred RMSNorm); the post-attention norm lives in the - * router (omega_gpu_router_set_layer), the router's directories in the caller's omega_gpu_router_set_directory_fp8. - * Memory, threading and kernel caches: as omega_gpu_q38_graph.h. - * - * ============ C signatures (for the Rust binding) ============ - * int omega_gpu_q36_graph_create(const OmegaGpuQ36GraphConfig *cfg, OmegaGpuQ36Graph **out); - * void omega_gpu_q36_graph_free(OmegaGpuQ36Graph *g); - * int omega_gpu_q36_graph_set_layer(g, layer, mix, ab, o, gate_up, down, in_norm); - * int omega_gpu_q36_graph_set_final_norm(g, final_norm); - * int omega_gpu_q36_graph_token(g, x_embed, pos, &token, &stats); - * int omega_gpu_q36_graph_read(g, x, hidden, logits); - * int omega_gpu_q36_graph_read_buf(g, which, out, n); - * Return codes: the decode graph's OMEGA_GPU_DGRAPH_*. - */ -#include "omega_gpu_decode_graph.h" -#include "omega_gpu_decode_attn256_api.h" -#include "omega_gpu_gdn_api.h" -#include "omega_gpu_router_api.h" -#include -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_GPU_Q36_HIDDEN 2048u -#define OMEGA_GPU_Q36_EXPERT_INTER 512u /* routed and shared expert width */ -#define OMEGA_GPU_Q36_GROUPS 9u /* 8 routed + the shared expert */ -#define OMEGA_GPU_Q36_GDN_MIX 12288u /* in_proj_qkv 8192 | in_proj_z 4096 */ -#define OMEGA_GPU_Q36_GDN_QKV 8192u -#define OMEGA_GPU_Q36_AB 64u /* 32 heads x {a, b} */ -#define OMEGA_GPU_Q36_ATT_MIX 9216u /* q_proj 8192 | k_proj 512 | v_proj 512 */ -#define OMEGA_GPU_Q36_ATT_QKV 5120u /* the attention kernel's row: q 16 x 256 | k 2 x 256 | v 2 x 256 */ -#define OMEGA_GPU_Q36_MIXER_OUT 4096u /* GDN 32 x 128 = attention 16 x 256 */ -#define OMEGA_GPU_Q36_ROTARY 64u -#define OMEGA_GPU_Q36_MAX_LAYERS 64u -/* Heads per stroke (conversations through one command list): a 40-layer token records up to 11 * 40 + 4 = 444 launches, - * and the list holds OMEGA_GPU_CMDLIST_MAX_LAUNCHES (4096), so eight (3552; the submit splits a list over the ring as it - * needs). v1 reads the weights once per head per stroke; v2 batches the dense GEMVs at M = heads, not the list grows further. */ -#define OMEGA_GPU_Q36_MAX_HEADS 8u - -typedef struct { - uint32_t layers; /* 1..64 (a model prefix in tests) */ - uint64_t attn_mask; /* bit l set: model layer l is full attention, else GDN */ - uint32_t vocab; /* lm_head rows (248320), <= 2048 * 2048 */ - float eps; /* rms_norm_eps (1e-6) */ - float eps_l2; /* GDN q/k l2norm eps (1e-6) */ - OmegaGpuGdn *gdn; /* omega_gpu_gdn_alloc_ratio(.., 2, ..), >= GDN layers entries, parameters set */ - OmegaGpuDecodeAttn256Cache *attn; /* omega_gpu_decode_attn256_cache_alloc_shape(.., 16, 2, 4, ..), q/k norms set */ - OmegaGpuRouter *router; /* omega_gpu_router_alloc_shape(layers, 256, 1, ..), every layer and directory set */ - const OmegaGpuBf16Tensor *lm_head; /* [vocab][2048] */ -} OmegaGpuQ36GraphConfig; - -typedef struct OmegaGpuQ36Graph OmegaGpuQ36Graph; - -int omega_gpu_q36_graph_create(const OmegaGpuQ36GraphConfig *cfg, OmegaGpuQ36Graph **out); -void omega_gpu_q36_graph_free(OmegaGpuQ36Graph *g); -/* Shapes are checked. GDN layer: mix [1][12288][2048], ab bf16 [64][2048] (row 2h = in_proj_a[h], 2h + 1 = in_proj_b[h], - * each value * 2^-64), o [1][2048][4096]. Attention layer: mix [1][9216][2048], ab NULL, o [1][2048][4096]. - * Both: gate_up [257][1024][2048], down [257][2048][512] (expert 256 = the shared expert), in_norm f32 [2048] as (1 + w). - * The tensors stay owned by the caller. */ -int omega_gpu_q36_graph_set_layer(OmegaGpuQ36Graph *g, uint32_t layer, const OmegaGpuFp8Tensor *mix, const OmegaGpuBf16Tensor *ab, - const OmegaGpuFp8Tensor *o, const OmegaGpuFp8Tensor *gate_up, const OmegaGpuFp8Tensor *down, - const float *in_norm); -int omega_gpu_q36_graph_set_final_norm(OmegaGpuQ36Graph *g, const float *final_norm); /* f32 [2048] as (1 + w) */ -/* Optional FP8 lm_head: as omega_gpu_q38_graph_set_lm_head_fp8 ([vocab][2048]). */ -int omega_gpu_q36_graph_set_lm_head_fp8(OmegaGpuQ36Graph *g, const OmegaGpuFp8Tensor *head); -/* Strokes: N heads (conversations) through ONE command list, one submit. create_heads lays out N slots of x, hidden, logits - * and token; head 0 uses cfg.gdn / cfg.attn, every head (0 included) can be pointed at other state objects by set_head_state (same shapes; - * head swap = pointing a slot at another conversation's objects). The router, the weights and the per-layer scratch are - * shared: launches run in order (barriers by default) and every head's layer launches stay contiguous. The one value that - * crosses layers, the fused COMBINE|NORM's x' for the next layer (xq), is per head (2026-10-21 02:50Z: shared, every head - * read the last head's x'; the stroke gate caught it). create() == create_heads(cfg, 1). */ -int omega_gpu_q36_graph_create_heads(const OmegaGpuQ36GraphConfig *cfg, uint32_t heads, OmegaGpuQ36Graph **out); -int omega_gpu_q36_graph_set_head_state(OmegaGpuQ36Graph *g, uint32_t head, OmegaGpuGdn *gdn, OmegaGpuDecodeAttn256Cache *attn); -/* x_embed f32 [heads][2048], pos [heads] -> tokens [heads]; layer-major (every head's layer l before layer l + 1). */ -int omega_gpu_q36_graph_stroke(OmegaGpuQ36Graph *g, const float *x_embed, const uint32_t *pos, uint32_t heads, uint32_t *tokens, - OmegaGpuDecodeGraphStats *st); -int omega_gpu_q36_graph_begin_stroke(OmegaGpuQ36Graph *g, const float *x_embed, uint32_t heads); -int omega_gpu_q36_graph_record_head_layer(OmegaGpuQ36Graph *g, uint32_t head, uint32_t layer, uint32_t pos); -int omega_gpu_q36_graph_record_head_final(OmegaGpuQ36Graph *g, uint32_t head); -int omega_gpu_q36_graph_end_stroke(OmegaGpuQ36Graph *g, uint32_t *tokens, OmegaGpuDecodeGraphStats *st); -/* As read(), for head h of the last stroke. */ -int omega_gpu_q36_graph_read_head(OmegaGpuQ36Graph *g, uint32_t head, float *x, float *hidden, float *logits); -/* HUM L314 exact two-pass head (bf16 lm_head only; ignored while an FP8 lm_head is set). screen: the fp8b copy of lm_head - * ([vocab][2048], one bf16 scale per 128 x 128 block); coef: f32 [vocab] Row bound coefficients, c[r] >= |w_r - w~_r| + - * gamma(2100)(|w_r| + |w~_r|) (sc exact_head.rs). The final step then records - * XBOUND SCALE h8 = hidden * 2^64; fp8 screen s = W~ . h8; XBOUND lo / hi = s -/+ c|hidden|; ARGMAX x2 tau = max lo; - * bf16 MASK logits = W_lm . hidden where hi >= tau (bit-identical to the plain head), -inf elsewhere; ARGMAX x2 - * so the greedy token is the plain head's by construction, but the logits read back are -inf off the candidates: use it - * only for greedy tokens (set_exact_head_on(g, 0) for sampled ones). Copies coef; screen must outlive g. NULL screen - * removes it. On by default once set. */ -int omega_gpu_q36_graph_set_exact_head(OmegaGpuQ36Graph *g, const OmegaGpuFp8Tensor *screen, const float *coef); -void omega_gpu_q36_graph_set_exact_head_on(OmegaGpuQ36Graph *g, int on); /* between tokens */ -int omega_gpu_q36_graph_exact_head_active(const OmegaGpuQ36Graph *g); /* head 0: set, on, and no FP8 lm_head */ -/* Strokes: the switch is per head (a stroke may mix greedy and sampled rows); set_exact_head_on sets every head. The - * heads share the exact head's scratch (h8, s, lo, hi, tau): their final launches run in list order, each head's whole - * two-pass sequence before the next head's. */ -void omega_gpu_q36_graph_set_head_exact_head_on(OmegaGpuQ36Graph *g, uint32_t head, int on); -int omega_gpu_q36_graph_exact_head_active_head(const OmegaGpuQ36Graph *g, uint32_t head); -/* One whole token: x_embed (f32 [2048]) -> greedy token at position pos. */ -int omega_gpu_q36_graph_token(OmegaGpuQ36Graph *g, const float *x_embed, uint32_t pos, uint32_t *token, OmegaGpuDecodeGraphStats *st); -int omega_gpu_q36_graph_begin_token(OmegaGpuQ36Graph *g, const float *x_embed); -int omega_gpu_q36_graph_record_layer(OmegaGpuQ36Graph *g, uint32_t layer, uint32_t pos); -int omega_gpu_q36_graph_record_final(OmegaGpuQ36Graph *g); -int omega_gpu_q36_graph_end_token(OmegaGpuQ36Graph *g, uint32_t *token, OmegaGpuDecodeGraphStats *st); -/* Takes the lock; copies the device x, hidden and logits (vocab values) of the last token; any pointer may be NULL. */ -int omega_gpu_q36_graph_read(OmegaGpuQ36Graph *g, float *x, float *hidden, float *logits); -enum { OMEGA_GPU_Q36_BUF_X, OMEGA_GPU_Q36_BUF_XQ, OMEGA_GPU_Q36_BUF_MIX, OMEGA_GPU_Q36_BUF_AB, OMEGA_GPU_Q36_BUF_AGG, - OMEGA_GPU_Q36_BUF_ATT, OMEGA_GPU_Q36_BUF_O, OMEGA_GPU_Q36_BUF_GU, OMEGA_GPU_Q36_BUF_ACT, OMEGA_GPU_Q36_BUF_HIDDEN, - OMEGA_GPU_Q36_BUF_DN, OMEGA_GPU_Q36_BUF_COUNT }; -int omega_gpu_q36_graph_read_buf(OmegaGpuQ36Graph *g, int which, float *out, uint32_t n); -/* Prefill (L369): a prompt chunk of n tokens (embeddings x_embed f32 [n][2048]) of the conversation in head slot `head` at - * positions pos0 .. pos0 + n - 1, as if each token went through token() in turn: every step uses the decode step's kernels - * (the dense trunk and the experts through the fp8 gemm record path, bit-identical to the GEMV per row; a|b and the router - * in their ROWS forms; the GDN step and the attention launched per token in order on the head's own state). Per layer two - * lists: the mixers and the router, then (after a host sort of the expert picks) the experts and COMBINE|NORM. want_token: - * the last token's head and argmax as record_head_final (token, read_head(head) as after a token). prefill_alloc(cap) - * sizes the buffers for chunks of up to cap tokens (1 .. OMEGA_GPU_Q36_PREFILL_MAX_ROWS; nothing shrinks). - * TEST ONLY: AIEN_OMEGA_Q36_PF_MUTANT=1 swaps the last two tokens' GDN steps, 2 drops one row of every expert segment, - * 3 defers each GDN output copy past the next token's step, 5 gives the multi-token GDN a|b row stride 0 (every token - * reads token 0's gates), 6 drops the attention prep launch (the chunk's own K/V rows never reach the cache). The GDN runs - * as ONE multi-token launch per layer (the decode step's arithmetic in a loop, bit-identical to the per-token launches; - * mutants 1 and 3 use the per-token form); AIEN_OMEGA_Q36_PF_GDN=0 forces the per-token launches. Each attention layer is - * one prep launch (every token's K/V rows) and one attend launch (grid (splits, tokens x rows), the decode kernel per - * token, bit-identical; omega_gpu_decode_attn256_multi_record); AIEN_OMEGA_Q36_PF_ATTN=0 forces the per-token launches. */ -#define OMEGA_GPU_Q36_PREFILL_MAX_ROWS 128u /* x 8 routed expert rows <= the fp8 gemm's 1024 (the shared expert is its own GEMM) */ -int omega_gpu_q36_graph_prefill_alloc(OmegaGpuQ36Graph *g, uint32_t cap); -uint32_t omega_gpu_q36_graph_prefill_cap(const OmegaGpuQ36Graph *g); -/* fp8 GEMM weight bytes every prefill call on g so far streamed (a running count: take the difference around a call): every expert once per 4 of its rows, the dense mix/o once per 8 - * rows (the ceiling receipt: these bytes over the call time against the memory bandwidth). The bf16 a|b, router and head - * reads are not counted. */ -uint64_t omega_gpu_q36_graph_prefill_streamed(const OmegaGpuQ36Graph *g); -int omega_gpu_q36_graph_prefill(OmegaGpuQ36Graph *g, uint32_t head, const float *x_embed, uint32_t n, uint32_t pos0, int want_token, - uint32_t *token, OmegaGpuDecodeGraphStats *st); -/* The gather table (u32 [9216]): agg[n] = mix[tab[n]]. */ -void omega_q36_gather_table(uint32_t *tab); -/* the FP8 GEMM's x' lane permutation as a GATHER table (k a multiple of 512) */ -void omega_q36_perm_table(uint32_t *tab, uint32_t k); - -/* The batch (v2, L312 "the ignition"): with set_batch(g, 1), stroke() records each layer for every conversation at once: - * the dense GEMVs become one grouped GEMM over the N rows (mix, o: one weight read per layer for all N), the expert blocks - * one grouped GEMM over the N x 9 rows sorted by expert (GROUP kernel: every expert any conversation picked is read once), - * the per-conversation state kernels (GDN, attention, router, COMBINE) stay per head. Values are those of the per-head - * stroke (the gate: every head word-identical to its run alone). The final head (lever 1): the bf16 lm_head read once per - * group of up to OMEGA_BF16_MAX_XBATCH heads (the XBATCH GEMV form), then the argmax per head; the FP8 head stays per head. - * set_batch pins the GEMM and XBATCH kernels (session, once); AIEN_OMEGA_Q36_BATCH=1 at create does the same. - * record_layer_heads is the per-layer step stroke() uses. */ -int omega_gpu_q36_graph_set_batch(OmegaGpuQ36Graph *g, int on); -int omega_gpu_q36_graph_batch(const OmegaGpuQ36Graph *g); -int omega_gpu_q36_graph_record_layer_heads(OmegaGpuQ36Graph *g, uint32_t layer, const uint32_t *pos); - -enum { - OMEGA_GPU_Q36_K_NORM = 0, OMEGA_GPU_Q36_K_MIX, OMEGA_GPU_Q36_K_AB, OMEGA_GPU_Q36_K_GDN, OMEGA_GPU_Q36_K_GATHER, OMEGA_GPU_Q36_K_ATTN, - OMEGA_GPU_Q36_K_GATE, OMEGA_GPU_Q36_K_O, OMEGA_GPU_Q36_K_RES, OMEGA_GPU_Q36_K_ROUTER, OMEGA_GPU_Q36_K_GATE_UP, OMEGA_GPU_Q36_K_SWIGLU, - OMEGA_GPU_Q36_K_DOWN, OMEGA_GPU_Q36_K_LM_HEAD, OMEGA_GPU_Q36_K_ARGMAX, OMEGA_GPU_Q36_K_PERM, OMEGA_GPU_Q36_K_GROUP, OMEGA_GPU_Q36_K_COUNT -}; -void omega_gpu_q36_graph_set_stamps(OmegaGpuQ36Graph *g, int on); -int omega_gpu_q36_graph_stamps(const OmegaGpuQ36Graph *g, uint64_t *stamps, uint8_t *kinds, uint32_t cap); -const char *omega_gpu_q36_graph_kind_name(uint8_t kind); -void omega_gpu_q36_graph_set_flush_each(OmegaGpuQ36Graph *g, int on); -/* TEST ONLY: 1 SWIGLU up half off by one, 2 GATHER index + 1, 3 GATE dropped, 4 COMBINE skips the shared expert, - * 5 the exact head's MASK keeps the rows it should drop and drops the candidates (the greedy gate must catch it), - * 6 the exact head's XBOUND drops the c|h| bound (too weak to change most tokens: the host gate saw one golden of five - * diverge at its full scale x0). 0 none. */ -void omega_gpu_q36_graph_test_set_mutant(OmegaGpuQ36Graph *g, int mutant); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_q38_graph.c b/src/omega_gpu_q38_graph.c deleted file mode 100644 index d890d8261..000000000 --- a/src/omega_gpu_q38_graph.c +++ /dev/null @@ -1,490 +0,0 @@ -/* - * omega_gpu_q38_graph.c: one Qwen3.8-27B decode token as one command list (see the header). Records the FP8 / bf16 GEMV, - * GDN and hd256 attention APIs' *_record launches and the omega_blackwell_codegen_dec glue kernels at width 5120 into an - * omega_gpu_cmdlist. Buffers: buf from omega_gpu_session_alloc (GPU-uncached, nvos.h:1117) holds every region the host - * touches: x (before), token and logits (after), the tables; dbuf (GPU-cached, omega_gpu_mem_cached.h) holds the chip-only - * intermediates (see Layout). - */ -#include "omega_gpu_q38_graph.h" -#include "omega_gpu_cmdlist.h" -#include "omega_blackwell_codegen_dec.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include "omega_gpu_mem_cached.h" -#include -#include - -#define TIMEOUT_MS 20000ull -#define SCALE_2P64 18446744073709551616.0f -#define NEG_PAD (-1e30f) -#define TOKEN_POISON 0xffffffffu -#define H OMEGA_GPU_Q38_HIDDEN -#define I OMEGA_GPU_Q38_INTER - -/* glue kernels */ -enum { K_NORM, K_ADDNORM, K_SW, K_GATHER, K_GATE, K_AM0, K_AM1, K_SW_M1, K_GATHER_M1, K_GATE_M1, K_ADDNORM_M1, K_COPY, K_COUNT }; -#define COPY_ROW 256u /* K_COPY: GATHER rows of 256 floats through the identity table */ - -typedef struct { OmegaGpuMem code; uint32_t gpr; } Kern; - -/* byte offsets into two buffers, every region 256-byte aligned (RES loads 16-byte vectors). [0, split): buf, GPU-uncached, - * every region the host writes or reads. [split, bytes): dbuf, the chip-only intermediates, GPU-cached unless - * AIEN_OMEGA_Q38_BUF_CACHED=0 (measured 2026-10-19: every FP8 GEMV CTA reads the whole x' row, and uncached each of those - * reads goes to DRAM; cached, down 2100 -> 1735 us and mix 1596 -> 1458 us over 4 layers, runs/probe-buf). read_buf copies - * a dbuf region into stage with a chip launch (K_COPY) before the host reads it. */ -typedef struct { - size_t x, ab, hidden, logits, am_v, am_i, token, norms, fnorm, tabs, gtab, idtab, stage, split; - size_t xq, mix, agg, att, o, gu, act, bytes; -} Layout; - -struct OmegaGpuQ38Graph { - OmegaGpuQ38GraphConfig cfg; - uint32_t am_ctas; /* stage-1 ARGMAX CTAs = ceil(vocab / 2048) */ - Layout lo; - OmegaGpuMem buf, dbuf; /* the host-visible regions; the chip-only regions (see Layout) */ - Kern k[K_COUNT]; - OmegaGpuCmdList *cl; - struct { const OmegaGpuFp8Tensor *mix, *o, *gu, *dn; const OmegaGpuBf16Tensor *ab; uint32_t kind_index; int attn, set; } layer[OMEGA_GPU_Q38_MAX_LAYERS]; - int final_set; - const OmegaGpuFp8Tensor *head8; /* set_lm_head_fp8: FP8 lm_head (hidden is then written x 2^64, read() undoes it) */ - /* 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; - 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 OmegaGpuQ38Graph *g, size_t off) { return off < g->lo.split ? g->buf.va + off : g->dbuf.va + (off - g->lo.split); } -static void *cpu_of(const OmegaGpuQ38Graph *g, size_t off) { return (uint8_t *)g->buf.cpu + off; } /* host regions only (off < split) */ -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(OmegaGpuQ38Graph *g, const char *what, int rc) { - if (g) g->failed = 1; - if (what) omega_gpu_session_set_error(what); - return rc; -} - -void omega_q38_gather_table(uint32_t *tab) { - const uint32_t R = OMEGA_GPU_Q38_ROTARY, QP = 24u * 512u, KP = QP + 4u * 256u; - for (uint32_t n = 0; n < OMEGA_GPU_Q38_ATT_MIX; n++) { - uint32_t s; - if (n < 6144u) s = (n / 256u) * 512u + omega_dattn256_perm_slot(n % 256u, R); /* q, permuted */ - else if (n < 7168u) s = QP + ((n - 6144u) / 256u) * 256u + omega_dattn256_perm_slot(n % 256u, R); /* k, permuted */ - else if (n < 8192u) s = KP + (n - 7168u); /* v */ - else s = ((n - 8192u) / 256u) * 512u + 256u + (n - 8192u) % 256u; /* gate */ - tab[n] = s; - } -} - -/* lock held */ -static int kern_build(Kern *k, const OmegaDecSpec *s) { - 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 the decode graph */ - 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_q38_graph_free(OmegaGpuQ38Graph *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); - if (g->dbuf.cpu) omega_gpu_session_free(&g->dbuf); - omega_gpu_session_unlock(); - omega_gpu_host_free(g); -} - -int omega_gpu_q38_graph_create(const OmegaGpuQ38GraphConfig *cfg, OmegaGpuQ38Graph **out) { - if (out) *out = NULL; - if (!cfg || !out || cfg->layers == 0 || cfg->layers > OMEGA_GPU_Q38_MAX_LAYERS || !cfg->gdn || !cfg->attn || !cfg->lm_head || - cfg->vocab == 0 || cfg->vocab > OMEGA_DEC_ARGMAX_SPAN * OMEGA_DEC_ARGMAX_SPAN) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (cfg->layers < 64u && (cfg->attn_mask >> cfg->layers) != 0) 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 != H) return OMEGA_GPU_DGRAPH_BAD_ARGS; - OmegaGpuQ38Graph *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; - for (uint32_t l = 0, na = 0, ng = 0; l < cfg->layers; l++) { - g->layer[l].attn = (int)((cfg->attn_mask >> l) & 1u); - g->layer[l].kind_index = g->layer[l].attn ? na++ : ng++; - } - 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(ab, OMEGA_GPU_Q38_AB * 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 * 2 * H * 4); REG(fnorm, H * 4); REG(tabs, (size_t)cfg->layers * 4 * 16 + 16); /* + the FP8 lm_head entry */ - REG(gtab, OMEGA_GPU_Q38_ATT_MIX * 4); REG(idtab, COPY_ROW * 4); REG(stage, 2 * I * 4); - L->split = o; - REG(xq, H * 4); REG(mix, OMEGA_GPU_Q38_GDN_MIX * 4); REG(agg, OMEGA_GPU_Q38_ATT_MIX * 4); - REG(att, OMEGA_GPU_Q38_MIXER_OUT * 4); REG(o, H * 4); REG(gu, 2 * I * 4); REG(act, I * 4); -#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_q38_graph_free(g); return OMEGA_GPU_DGRAPH_CHIP_FAIL; } - omega_gpu_session_lock(); - const char *pbc = getenv("AIEN_OMEGA_Q38_BUF_CACHED"); - int (*const dalloc)(size_t, OmegaGpuMem *) = (pbc && pbc[0] == '0' && pbc[1] == 0) ? omega_gpu_session_alloc : omega_gpu_session_alloc_cached; - if (!omega_gpu_session_open() || omega_gpu_session_alloc(L->split, &g->buf) != 0 || dalloc(L->bytes - L->split, &g->dbuf) != 0) - rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - static const OmegaDecSpec spec[K_COUNT] = { - [K_NORM] = { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_NORM, .width = H }, - [K_ADDNORM] = { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM, .width = H }, - [K_SW] = { .kind = OMEGA_DEC_SWIGLU, .width = I }, - [K_GATHER] = { .kind = OMEGA_DEC_GATHER, .width = OMEGA_GPU_Q38_ATT_MIX, .stride = OMEGA_GPU_Q38_ATT_MIX }, - [K_GATE] = { .kind = OMEGA_DEC_GATE }, - [K_AM0] = { .kind = OMEGA_DEC_ARGMAX, .mode = 0 }, - [K_AM1] = { .kind = OMEGA_DEC_ARGMAX, .mode = 1 }, - [K_SW_M1] = { .kind = OMEGA_DEC_SWIGLU, .width = I, .mutant = 1 }, - [K_GATHER_M1] = { .kind = OMEGA_DEC_GATHER, .width = OMEGA_GPU_Q38_ATT_MIX, .stride = OMEGA_GPU_Q38_ATT_MIX, .mutant = 1 }, - [K_GATE_M1] = { .kind = OMEGA_DEC_GATE, .mutant = 1 }, - [K_ADDNORM_M1] = { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM, .width = H, .mutant = 1 }, - [K_COPY] = { .kind = OMEGA_DEC_GATHER, .width = COPY_ROW, .stride = COPY_ROW }, - }; - for (unsigned i = 0; i < K_COUNT && rc == OMEGA_GPU_DGRAPH_OK; i++) rc = kern_build(&g->k[i], &spec[i]); - if (rc == OMEGA_GPU_DGRAPH_OK) { - memset(g->buf.cpu, 0, L->split); - memset(g->dbuf.cpu, 0, L->bytes - L->split); /* fresh; every region is written by the chip before a launch reads it */ - uint32_t *id = cpu_of(g, L->idtab); - for (uint32_t i = 0; i < COPY_ROW; i++) id[i] = i; - 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 */ - omega_q38_gather_table(cpu_of(g, L->gtab)); - if (omega_gpu_session_sync_to_gpu(&g->buf) != 0 || omega_gpu_session_sync_to_gpu(&g->dbuf) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - } - omega_gpu_session_unlock(); - if (rc != OMEGA_GPU_DGRAPH_OK) { omega_gpu_q38_graph_free(g); return rc; } - *out = g; - return OMEGA_GPU_DGRAPH_OK; -} - -static int shape_is(const OmegaGpuFp8Tensor *t, uint32_t n, uint32_t k) { - uint32_t te = 0, tn = 0, tk = 0; if (t) omega_gpu_fp8_tensor_shape(t, &te, &tn, &tk); - return t && te == 1 && tn == n && tk == k; -} - -int omega_gpu_q38_graph_set_layer(OmegaGpuQ38Graph *g, uint32_t layer, const OmegaGpuFp8Tensor *mix, const OmegaGpuBf16Tensor *ab, - const OmegaGpuFp8Tensor *o, const OmegaGpuFp8Tensor *gate_up, const OmegaGpuFp8Tensor *down, - const float *in_norm, const float *post_norm) { - if (!g || layer >= g->cfg.layers || !in_norm || !post_norm || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - const int attn = g->layer[layer].attn; - if (!shape_is(mix, attn ? OMEGA_GPU_Q38_ATT_MIX : OMEGA_GPU_Q38_GDN_MIX, H) || !shape_is(o, H, OMEGA_GPU_Q38_MIXER_OUT) || - !shape_is(gate_up, 2 * I, H) || !shape_is(down, H, I)) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (attn ? ab != NULL : ab == NULL) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (!attn) { uint32_t n = 0, k = 0; omega_gpu_bf16_tensor_shape(ab, &n, &k); if (n != OMEGA_GPU_Q38_AB || k != H) return OMEGA_GPU_DGRAPH_BAD_ARGS; } - uint64_t t[8]; - if (omega_gpu_fp8_tensor_entry(mix, 0, &t[0], &t[1]) != 0 || omega_gpu_fp8_tensor_entry(o, 0, &t[2], &t[3]) != 0 || - omega_gpu_fp8_tensor_entry(gate_up, 0, &t[4], &t[5]) != 0 || omega_gpu_fp8_tensor_entry(down, 0, &t[6], &t[7]) != 0) return OMEGA_GPU_DGRAPH_BAD_ARGS; - omega_gpu_session_lock(); - memcpy((uint8_t *)cpu_of(g, g->lo.tabs) + (size_t)layer * 64u, t, sizeof t); - memcpy((float *)cpu_of(g, g->lo.norms) + (size_t)layer * 2 * H, in_norm, H * 4u); - memcpy((float *)cpu_of(g, g->lo.norms) + (size_t)layer * 2 * H + H, post_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].mix = mix; g->layer[layer].ab = ab; 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_q38_graph_set_final_norm(OmegaGpuQ38Graph *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, 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->final_set = 1; - return rc; -} - -int omega_gpu_q38_graph_set_lm_head_fp8(OmegaGpuQ38Graph *g, const OmegaGpuFp8Tensor *head) { - if (!g || g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (!head) { g->head8 = NULL; return OMEGA_GPU_DGRAPH_OK; } - uint64_t t[2]; - if (!shape_is(head, g->cfg.vocab, H) || omega_gpu_fp8_tensor_entry(head, 0, &t[0], &t[1]) != 0) return OMEGA_GPU_DGRAPH_BAD_ARGS; - omega_gpu_session_lock(); - memcpy((uint8_t *)cpu_of(g, g->lo.tabs) + (size_t)g->cfg.layers * 64u, t, sizeof t); - 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->head8 = head; - return rc; -} - -void omega_gpu_q38_graph_set_flush_each(OmegaGpuQ38Graph *g, int on) { if (g) g->flush_each = on ? 1 : 0; } -void omega_gpu_q38_graph_test_set_mutant(OmegaGpuQ38Graph *g, int mutant) { if (g) g->mutant = mutant; } - -/* ---- the list ---- */ - -static OmegaGpuCmdListOpts list_opts(const OmegaGpuQ38Graph *g) { - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); - o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = (OmegaGpuCmdListBarrier)omega_gpu_decode_graph_barrier(); o.timeout_ms = TIMEOUT_MS; o.stamps = g->stamps; - return o; -} - -static int submit_now(OmegaGpuQ38Graph *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) { - 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, "q38 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; -} - -static void tag(OmegaGpuQ38Graph *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; -} - -static int after_op(OmegaGpuQ38Graph *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(OmegaGpuQ38Graph *g, uint8_t kind, int ki, uint32_t gx, uint32_t gy, size_t elems, const uint32_t *args, uint32_t n_args) { - const Kern *k = &g->k[ki]; - 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); -} - -/* RES at width 5120: NORM (x -> y) or ADD|NORM (x += a; y = norm(x)) */ -static int rec_res(OmegaGpuQ38Graph *g, int ki, uint64_t x, uint64_t a, uint64_t nw, uint64_t y, float scale) { - uint32_t w[OMEGA_DEC_RES_WORDS]; memset(w, 0, sizeof w); - put64(w, OMEGA_DEC_RES_X, x); put64(w, OMEGA_DEC_RES_A, a); put64(w, OMEGA_DEC_RES_NW, nw); put64(w, OMEGA_DEC_RES_Y, y); - putf(w, OMEGA_DEC_RES_EPS, g->cfg.eps); putf(w, OMEGA_DEC_RES_SCALE, scale); - return add_glue(g, ki == K_NORM ? OMEGA_GPU_Q38_K_NORM : OMEGA_GPU_Q38_K_RES, ki, 1, 1, H, w, OMEGA_DEC_RES_WORDS); -} - -static int g_overlap_ab = -1; -void omega_gpu_q38_graph_set_overlap_ab(int on) { g_overlap_ab = on ? 1 : 0; } -static int q38_overlap_ab(void) { - if (g_overlap_ab < 0) { const char *e = getenv("AIEN_OMEGA_Q38_OVERLAP_AB"); g_overlap_ab = (e && e[0] == '0' && e[1] == 0) ? 0 : 1; } - return g_overlap_ab; -} - -static int rec_fp8(OmegaGpuQ38Graph *g, uint8_t kind, const OmegaGpuFp8Tensor *t, uint64_t tab, uint64_t x, uint64_t y) { - return after_op(g, kind, omega_gpu_fp8_gemv_grouped_record(g->cl, t, 1, tab, x, 1, y)); -} - -int omega_gpu_q38_graph_begin_token(OmegaGpuQ38Graph *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, H * 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_q38_graph_record_layer(OmegaGpuQ38Graph *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, "q38 graph: layer not set, out of order, or final norm missing", OMEGA_GPU_DGRAPH_BAD_ARGS); - const uint64_t x = va_of(g, g->lo.x), xq = va_of(g, g->lo.xq), mix = va_of(g, g->lo.mix), agg = va_of(g, g->lo.agg); - const uint64_t att = va_of(g, g->lo.att), o = va_of(g, g->lo.o), gu = va_of(g, g->lo.gu), act = va_of(g, g->lo.act); - const uint64_t in_norm = va_of(g, g->lo.norms) + (uint64_t)l * 2 * H * 4u, post_norm = in_norm + H * 4u, tab = va_of(g, g->lo.tabs) + (uint64_t)l * 64u; - const uint32_t ki = g->layer[l].kind_index; - int rc = OMEGA_GPU_DGRAPH_OK; - if (g->xq_layer != (int)l) rc = rec_res(g, K_NORM, x, 0, in_norm, xq, SCALE_2P64); - /* GDN layers: the a|b GEMV (latency-bound, ~18 us) is recorded first and the mix GEMV marked independent of it: both only - * read xq and write their own buffers, so the two grids overlap; the GDN step after them waits for both (normal barrier). - * AIEN_OMEGA_Q38_OVERLAP_AB=0 or set_overlap_ab(0): the old order, mix then a|b, each behind a barrier. */ - const int overlap = !g->layer[l].attn && q38_overlap_ab(); - if (overlap && rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_Q38_K_AB, omega_gpu_bf16_gemv_record(g->cl, g->layer[l].ab, xq, va_of(g, g->lo.ab))); - if (rc == OMEGA_GPU_DGRAPH_OK) { - int mrc = omega_gpu_fp8_gemv_grouped_record(g->cl, g->layer[l].mix, 1, tab, xq, 1, mix); - if (mrc == 0 && overlap && !g->flush_each && omega_gpu_cmdlist_mark_independent(g->cl) != 0) mrc = -1; - rc = after_op(g, OMEGA_GPU_Q38_K_MIX, mrc); - } - uint64_t mixer_out = att; - if (!g->layer[l].attn) { - const uint64_t ab = va_of(g, g->lo.ab); - if (!overlap && rc == OMEGA_GPU_DGRAPH_OK) rc = after_op(g, OMEGA_GPU_Q38_K_AB, omega_gpu_bf16_gemv_record(g->cl, g->layer[l].ab, xq, ab)); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q38_K_GDN, omega_gpu_gdn_record(g->cl, g->cfg.gdn, ki, mix, mix + OMEGA_GPU_Q38_GDN_QKV * 4u, ab, - g->cfg.eps_l2, g->cfg.eps, 1.0f, SCALE_2P64, &mixer_out)); - } else { - uint32_t w[OMEGA_DEC_GA_WORDS]; memset(w, 0, sizeof w); - put64(w, OMEGA_DEC_GA_IN, mix); put64(w, OMEGA_DEC_GA_TAB, va_of(g, g->lo.gtab)); put64(w, OMEGA_DEC_GA_OUT, agg); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q38_K_GATHER, g->mutant == 2 ? K_GATHER_M1 : K_GATHER, (OMEGA_GPU_Q38_ATT_MIX + OMEGA_DEC_THREADS - 1) / OMEGA_DEC_THREADS, 1, - OMEGA_GPU_Q38_ATT_MIX, w, OMEGA_DEC_GA_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = after_op(g, OMEGA_GPU_Q38_K_ATTN, omega_gpu_decode_attn256_record(g->cl, g->cfg.attn, ki, pos, agg, g->cfg.eps, SCALE_2P64, att)); - uint32_t w2[OMEGA_DEC_GT_WORDS]; memset(w2, 0, sizeof w2); - put64(w2, OMEGA_DEC_GT_A, att); put64(w2, OMEGA_DEC_GT_G, agg + OMEGA_GPU_Q38_ATT_QKV * 4u); put64(w2, OMEGA_DEC_GT_OUT, att); - w2[(OMEGA_DEC_GT_N - 0x380) / 4] = OMEGA_GPU_Q38_MIXER_OUT; - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = add_glue(g, OMEGA_GPU_Q38_K_GATE, g->mutant == 3 ? K_GATE_M1 : K_GATE, OMEGA_GPU_Q38_MIXER_OUT / OMEGA_DEC_THREADS, 1, - OMEGA_GPU_Q38_MIXER_OUT, w2, OMEGA_DEC_GT_WORDS); - } - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_fp8(g, OMEGA_GPU_Q38_K_O, g->layer[l].o, tab + 16u, mixer_out, o); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_res(g, g->mutant == 4 ? K_ADDNORM_M1 : K_ADDNORM, x, o, post_norm, xq, SCALE_2P64); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_fp8(g, OMEGA_GPU_Q38_K_GATE_UP, g->layer[l].gu, tab + 32u, xq, gu); - uint32_t w3[OMEGA_DEC_SW_WORDS]; memset(w3, 0, sizeof w3); - put64(w3, OMEGA_DEC_SW_GU, gu); put64(w3, OMEGA_DEC_SW_ACT, act); putf(w3, OMEGA_DEC_SW_SCALE, SCALE_2P64); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = add_glue(g, OMEGA_GPU_Q38_K_SWIGLU, g->mutant == 1 ? K_SW_M1 : K_SW, I / OMEGA_DEC_THREADS, 1, I, w3, OMEGA_DEC_SW_WORDS); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = rec_fp8(g, OMEGA_GPU_Q38_K_DOWN, g->layer[l].dn, tab + 48u, act, o); - 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) : in_norm + 2 * H * 4u; - rc = rec_res(g, K_ADDNORM, x, o, nw, last ? va_of(g, g->lo.hidden) : xq, last && !g->head8 ? 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_q38_graph_record_final(OmegaGpuQ38Graph *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, "q38 graph: final norm not set", OMEGA_GPU_DGRAPH_BAD_ARGS); - const uint64_t x = va_of(g, g->lo.x), hidden = va_of(g, g->lo.hidden), logits = va_of(g, g->lo.logits), token = va_of(g, g->lo.token); - int rc = OMEGA_GPU_DGRAPH_OK; - if (!g->hidden_ready) rc = rec_res(g, K_NORM, x, 0, va_of(g, g->lo.fnorm), hidden, g->head8 ? SCALE_2P64 : 1.0f); - if (rc == OMEGA_GPU_DGRAPH_OK) - rc = g->head8 ? rec_fp8(g, OMEGA_GPU_Q38_K_LM_HEAD, g->head8, va_of(g, g->lo.tabs) + (uint64_t)g->cfg.layers * 64u, hidden, logits) - : after_op(g, OMEGA_GPU_Q38_K_LM_HEAD, omega_gpu_bf16_gemv_record(g->cl, g->cfg.lm_head, hidden, 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, 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, token + 4u); put64(a1, OMEGA_DEC_AM_OI, token); - if (rc == OMEGA_GPU_DGRAPH_OK) rc = add_glue(g, OMEGA_GPU_Q38_K_ARGMAX, 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_Q38_K_ARGMAX, 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_q38_graph_end_token(OmegaGpuQ38Graph *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_attn256_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, "q38 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_q38_graph_token(OmegaGpuQ38Graph *g, const float *x_embed, uint32_t pos, uint32_t *token, OmegaGpuDecodeGraphStats *st) { - if (!g) return OMEGA_GPU_DGRAPH_BAD_ARGS; - if (omega_gpu_q38_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_q38_graph_record_layer(g, l, pos); - if (!g->failed) (void)omega_gpu_q38_graph_record_final(g); - return omega_gpu_q38_graph_end_token(g, token, st); -} - -int omega_gpu_q38_graph_read(OmegaGpuQ38Graph *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), H * 4u); - if (hidden) memcpy(hidden, cpu_of(g, g->lo.hidden), H * 4u); - if (hidden && g->head8) for (unsigned i = 0; i < H; i++) hidden[i] *= 0x1p-64f; /* exact: a power of two */ - if (logits) memcpy(logits, cpu_of(g, g->lo.logits), (size_t)g->cfg.vocab * 4u); - } - omega_gpu_session_unlock(); - return rc; -} - -int omega_gpu_q38_graph_read_buf(OmegaGpuQ38Graph *g, int which, float *out, uint32_t n) { - if (!g || g->in_token || !out || which < 0 || which >= OMEGA_GPU_Q38_BUF_COUNT) return OMEGA_GPU_DGRAPH_BAD_ARGS; - const struct { size_t off; uint32_t cap; } b[OMEGA_GPU_Q38_BUF_COUNT] = { - [OMEGA_GPU_Q38_BUF_X] = { g->lo.x, H }, [OMEGA_GPU_Q38_BUF_XQ] = { g->lo.xq, H }, [OMEGA_GPU_Q38_BUF_MIX] = { g->lo.mix, OMEGA_GPU_Q38_GDN_MIX }, - [OMEGA_GPU_Q38_BUF_AB] = { g->lo.ab, OMEGA_GPU_Q38_AB }, [OMEGA_GPU_Q38_BUF_AGG] = { g->lo.agg, OMEGA_GPU_Q38_ATT_MIX }, - [OMEGA_GPU_Q38_BUF_ATT] = { g->lo.att, OMEGA_GPU_Q38_MIXER_OUT }, [OMEGA_GPU_Q38_BUF_O] = { g->lo.o, H }, - [OMEGA_GPU_Q38_BUF_GU] = { g->lo.gu, 2 * I }, [OMEGA_GPU_Q38_BUF_ACT] = { g->lo.act, I }, [OMEGA_GPU_Q38_BUF_HIDDEN] = { g->lo.hidden, H }, - }; - if (n > b[which].cap) return OMEGA_GPU_DGRAPH_BAD_ARGS; - omega_gpu_session_lock(); - int rc = OMEGA_GPU_DGRAPH_OK; - size_t from = b[which].off; - if (from >= g->lo.split && n) { - /* a chip-only region: K_COPY moves ceil(n / 256) rows of 256 floats into stage (every cap is a multiple of 256) */ - uint32_t w[OMEGA_DEC_GA_WORDS]; memset(w, 0, sizeof w); - put64(w, OMEGA_DEC_GA_IN, va_of(g, from)); put64(w, OMEGA_DEC_GA_TAB, va_of(g, g->lo.idtab)); put64(w, OMEGA_DEC_GA_OUT, va_of(g, g->lo.stage)); - const Kern *k = &g->k[K_COPY]; - 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 = 1; L.grid_y = (n + COPY_ROW - 1) / COPY_ROW; - L.num_elements = (size_t)L.grid_y * COPY_ROW; L.args = w; L.n_args = OMEGA_DEC_GA_WORDS; L.timeout_ms = TIMEOUT_MS; - if (!omega_gpu_session_open() || omega_gpu_session_launch(&L, NULL, NULL) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - from = g->lo.stage; - } - if (rc == OMEGA_GPU_DGRAPH_OK && omega_gpu_session_sync_to_cpu(&g->buf) != 0) rc = OMEGA_GPU_DGRAPH_CHIP_FAIL; - if (rc == OMEGA_GPU_DGRAPH_OK) memcpy(out, cpu_of(g, from), (size_t)n * 4u); - omega_gpu_session_unlock(); - return rc; -} - -/* ---- timeline ---- */ -void omega_gpu_q38_graph_set_stamps(OmegaGpuQ38Graph *g, int on) { if (g && !g->in_token) g->stamps = on ? 1 : 0; } - -int omega_gpu_q38_graph_stamps(const OmegaGpuQ38Graph *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("q38 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("q38 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_q38_graph_kind_name(uint8_t kind) { - static const char *const names[OMEGA_GPU_Q38_K_COUNT] = { "norm", "mix", "ab", "gdn", "gather", "attn", "gate", "o_proj", "res", - "gate_up", "swiglu", "down", "lm_head", "argmax" }; - return kind < OMEGA_GPU_Q38_K_COUNT ? names[kind] : "?"; -} diff --git a/src/omega_gpu_q38_graph.h b/src/omega_gpu_q38_graph.h deleted file mode 100644 index 263b1a3a1..000000000 --- a/src/omega_gpu_q38_graph.h +++ /dev/null @@ -1,131 +0,0 @@ -#ifndef OMEGA_GPU_Q38_GRAPH_H -#define OMEGA_GPU_Q38_GRAPH_H -/* - * omega_gpu_q38_graph: one Qwen3.8-27B decode token as ONE command list (sc #642, 2026-10-18). The 30B's - * omega_gpu_decode_graph (MoE, hidden 2048) is the template; this one is dense, hidden 5120, and mixes two layer kinds: - * Gated DeltaNet (48 layers) and full attention with head_dim 256 (16 layers, every 4th). - * - * (layer 0 only) NORM xq = RMSNorm(x) * in_norm[0] * 2^64 (the FP8 GEMV x' row) - * GDN layer l: fp8 mix mix[16384] = W_qkvz[l] . xq (in_proj_qkv 10240 | in_proj_z 6144) - * bf16 ab ab[96] = W_ab[l] . xq (a/b rows interleaved, uploaded * 2^-64: plain ab out) - * gdn att[6144] = GDN step(mix, mix + 10240, ab) * 2^64 omega_gpu_gdn_record - * attention l: fp8 mix mix[14336] = W_qgkv[l] . xq (q_proj 24 x [q 256 | gate 256], k_proj 1024, v_proj 1024) - * GATHER agg[14336] = permuted q | permuted k | v (8192, the attention kernel's row) | gate (6144) - * attn att[6144] = attention(agg, KV[l], pos) * 2^64 omega_gpu_decode_attn256_record - * GATE att *= sigmoid(agg + 8192) - * every layer: fp8 o o[5120] = W_o[l] . att - * ADD|NORM x += o; xr = RMSNorm(x) * post_norm[l] * 2^64 - * fp8 gu gu[34816] = W_gu[l] . xr (gate 17408 | up 17408) - * SWIGLU act[17408] = silu(gate) * up * 2^64 - * fp8 down o[5120] = W_down[l] . act - * ADD|NORM x += o; xq = RMSNorm(x) * in_norm[l + 1] * 2^64, or (last layer) hidden = RMSNorm(x) * final_norm - * final: bf16 lm_head logits = W_lm . hidden; ARGMAX x2 (122 CTAs over 248320, then 1) - * - * Launches: GDN layer 9, attention layer 10, plus 1 + 3: 48 * 9 + 16 * 10 + 4 = 596 for the whole model. - * Norm weights are passed already folded to (1 + w) (the model's zero-centred RMSNorm). The GDN and attention state live - * in the caller's OmegaGpuGdn (one entry per GDN layer, in model order) and OmegaGpuDecodeAttn256Cache (one per attention - * layer, in model order); the graph maps model layer l to its index of that kind. - * - * Memory: one omega_gpu_session_alloc buffer (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 and kernel caches: as omega_gpu_decode_graph.h (begin_token takes omega_gpu_session_lock(), end_token - * releases it; the record APIs refuse a cache eviction, so warm each shape up with one non-record call first). - * - * ============ C signatures (for the Rust binding) ============ - * int omega_gpu_q38_graph_create(const OmegaGpuQ38GraphConfig *cfg, OmegaGpuQ38Graph **out); - * void omega_gpu_q38_graph_free(OmegaGpuQ38Graph *g); - * int omega_gpu_q38_graph_set_layer(g, layer, mix, ab, o, gate_up, down, in_norm, post_norm); - * int omega_gpu_q38_graph_set_final_norm(g, final_norm); - * int omega_gpu_q38_graph_token(g, x_embed, pos, &token, &stats); - * int omega_gpu_q38_graph_read(g, x, hidden, logits); - * int omega_gpu_q38_graph_read_buf(g, which, out, n); - * Return codes: the decode graph's OMEGA_GPU_DGRAPH_* (0 OK, -1 BAD_ARGS, -3 CODEGEN_FAIL, -4 CHIP_FAIL); the failing - * stage is in omega_gpu_session_last_error(). - */ -#include "omega_gpu_decode_graph.h" -#include "omega_gpu_decode_attn256_api.h" -#include "omega_gpu_gdn_api.h" -#include -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_GPU_Q38_HIDDEN 5120u -#define OMEGA_GPU_Q38_INTER 17408u -#define OMEGA_GPU_Q38_GDN_MIX 16384u /* in_proj_qkv 10240 | in_proj_z 6144 */ -#define OMEGA_GPU_Q38_GDN_QKV 10240u -#define OMEGA_GPU_Q38_AB 96u /* 48 heads x {a, b} */ -#define OMEGA_GPU_Q38_ATT_MIX 14336u /* q_proj 12288 | k_proj 1024 | v_proj 1024 */ -#define OMEGA_GPU_Q38_ATT_QKV 8192u /* the attention kernel's row: q 24 x 256 | k 4 x 256 | v 4 x 256 */ -#define OMEGA_GPU_Q38_MIXER_OUT 6144u /* GDN 48 x 128 = attention 24 x 256 */ -#define OMEGA_GPU_Q38_ROTARY 64u -#define OMEGA_GPU_Q38_MAX_LAYERS 64u - -typedef struct { - uint32_t layers; /* 1..64 (a model prefix in tests) */ - uint64_t attn_mask; /* bit l set: model layer l is full attention, else GDN */ - uint32_t vocab; /* lm_head rows (248320), <= 2048 * 2048 */ - float eps; /* rms_norm_eps (1e-6) */ - float eps_l2; /* GDN q/k l2norm eps (1e-6) */ - OmegaGpuGdn *gdn; /* >= (layers - attention layers) entries, parameters set */ - OmegaGpuDecodeAttn256Cache *attn; /* >= attention layers entries, q/k norms set; rotary 64 */ - const OmegaGpuBf16Tensor *lm_head; /* [vocab][5120] */ -} OmegaGpuQ38GraphConfig; - -typedef struct OmegaGpuQ38Graph OmegaGpuQ38Graph; - -int omega_gpu_q38_graph_create(const OmegaGpuQ38GraphConfig *cfg, OmegaGpuQ38Graph **out); -void omega_gpu_q38_graph_free(OmegaGpuQ38Graph *g); -/* Shapes are checked. GDN layer: mix [1][16384][5120], ab bf16 [96][5120] (row 2h = in_proj_a[h], 2h + 1 = in_proj_b[h], - * each value * 2^-64), o [1][5120][6144]. Attention layer: mix [1][14336][5120], ab NULL, o [1][5120][6144]. - * Both: gate_up [1][34816][5120], down [1][5120][17408], in_norm and post_norm f32 [5120] as (1 + w). The tensors stay - * owned by the caller. */ -int omega_gpu_q38_graph_set_layer(OmegaGpuQ38Graph *g, uint32_t layer, const OmegaGpuFp8Tensor *mix, const OmegaGpuBf16Tensor *ab, - const OmegaGpuFp8Tensor *o, const OmegaGpuFp8Tensor *gate_up, const OmegaGpuFp8Tensor *down, - const float *in_norm, const float *post_norm); -int omega_gpu_q38_graph_set_final_norm(OmegaGpuQ38Graph *g, const float *final_norm); /* f32 [5120] as (1 + w) */ -/* Optional FP8 lm_head (qwen38/decode-speed): an FP8 tensor [vocab][5120] (experts 1, e.g. from omega_gpu_fp8_quantize_bf16) - * replaces the bf16 lm_head in every later token (half the bytes); NULL goes back to bf16. The tensor must outlive its use. - * While set, the device hidden buffer (OMEGA_GPU_Q38_BUF_HIDDEN) holds hidden x 2^64 (the FP8 GEMV input scale); - * omega_gpu_q38_graph_read returns the unscaled hidden (exact power-of-two rescale). Logits are those of the quantised head: - * callers own the drift study against the bf16 head. */ -int omega_gpu_q38_graph_set_lm_head_fp8(OmegaGpuQ38Graph *g, const OmegaGpuFp8Tensor *head); -/* GDN layers record the a|b GEMV first and the mix GEMV beside it (no barrier between the two; both only read xq), process-wide. - * 1 (default) or 0 (mix then a|b, each behind a barrier); env AIEN_OMEGA_Q38_OVERLAP_AB when never set. Values are identical. */ -void omega_gpu_q38_graph_set_overlap_ab(int on); -/* One whole token: x_embed (f32 [5120]) -> greedy token; pos: the token's position (attention layers append K/V there, - * GDN layers advance their state). */ -int omega_gpu_q38_graph_token(OmegaGpuQ38Graph *g, const float *x_embed, uint32_t pos, uint32_t *token, OmegaGpuDecodeGraphStats *st); -/* The same in steps (between begin and end only record calls on this thread). */ -int omega_gpu_q38_graph_begin_token(OmegaGpuQ38Graph *g, const float *x_embed); -int omega_gpu_q38_graph_record_layer(OmegaGpuQ38Graph *g, uint32_t layer, uint32_t pos); -int omega_gpu_q38_graph_record_final(OmegaGpuQ38Graph *g); -int omega_gpu_q38_graph_end_token(OmegaGpuQ38Graph *g, uint32_t *token, OmegaGpuDecodeGraphStats *st); -/* Takes the lock; copies the device x, hidden and logits (vocab values) of the last token; any pointer may be NULL. */ -int omega_gpu_q38_graph_read(OmegaGpuQ38Graph *g, float *x, float *hidden, float *logits); -/* Test and trace reads of one intermediate of the last token (f32, n values from the start of the buffer). */ -enum { OMEGA_GPU_Q38_BUF_X, OMEGA_GPU_Q38_BUF_XQ, OMEGA_GPU_Q38_BUF_MIX, OMEGA_GPU_Q38_BUF_AB, OMEGA_GPU_Q38_BUF_AGG, - OMEGA_GPU_Q38_BUF_ATT, OMEGA_GPU_Q38_BUF_O, OMEGA_GPU_Q38_BUF_GU, OMEGA_GPU_Q38_BUF_ACT, OMEGA_GPU_Q38_BUF_HIDDEN, - OMEGA_GPU_Q38_BUF_COUNT }; -int omega_gpu_q38_graph_read_buf(OmegaGpuQ38Graph *g, int which, float *out, uint32_t n); -/* The gather table (u32 [14336]): agg[n] = mix[tab[n]] (host side; the graph uploads it at create). */ -void omega_q38_gather_table(uint32_t *tab); - -/* ---- timeline (measurement; as the decode graph) ---- */ -enum { - OMEGA_GPU_Q38_K_NORM = 0, OMEGA_GPU_Q38_K_MIX, OMEGA_GPU_Q38_K_AB, OMEGA_GPU_Q38_K_GDN, OMEGA_GPU_Q38_K_GATHER, OMEGA_GPU_Q38_K_ATTN, - OMEGA_GPU_Q38_K_GATE, OMEGA_GPU_Q38_K_O, OMEGA_GPU_Q38_K_RES, OMEGA_GPU_Q38_K_GATE_UP, OMEGA_GPU_Q38_K_SWIGLU, OMEGA_GPU_Q38_K_DOWN, - OMEGA_GPU_Q38_K_LM_HEAD, OMEGA_GPU_Q38_K_ARGMAX, OMEGA_GPU_Q38_K_COUNT -}; -void omega_gpu_q38_graph_set_stamps(OmegaGpuQ38Graph *g, int on); -int omega_gpu_q38_graph_stamps(const OmegaGpuQ38Graph *g, uint64_t *stamps, uint8_t *kinds, uint32_t cap); -const char *omega_gpu_q38_graph_kind_name(uint8_t kind); -/* 1: submit after every launch (the comparison path). */ -void omega_gpu_q38_graph_set_flush_each(OmegaGpuQ38Graph *g, int on); -/* TEST ONLY: 1 SWIGLU up half off by one, 2 GATHER index + 1, 3 GATE dropped, 4 post-norm without its weight. 0 none. */ -void omega_gpu_q38_graph_test_set_mutant(OmegaGpuQ38Graph *g, int mutant); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/omega_gpu_router_api.c b/src/omega_gpu_router_api.c deleted file mode 100644 index fc06a7b08..000000000 --- a/src/omega_gpu_router_api.c +++ /dev/null @@ -1,355 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 /* 8 slots; with the shared slot (9) the down table is at LB_TAB_DN9 */ -#define LB_BYTES 16768u -#define LB_TAB_DN9 16656u -#define LB_BYTES9 16800u - -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 */ - uint32_t experts, shared; /* routed experts (128 or 256) and the shared slot (0 or 1) */ - uint32_t rows, slots; /* gate rows = experts + shared; output slots = 8 + shared */ - uint32_t lb_tab_dn, lb_bytes; -}; -#define ROWB(r) ((size_t)(r)->rows * OMEGA_ROUTER_ROW_BYTES) /* gate bytes per layer */ -#define DIRB(r) ((size_t)(r)->rows * 16u) /* one directory per layer */ - -typedef struct { - bool valid; - OmegaRouterSpec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; -} Slot; - -static struct { - bool hooked; - Slot slot; /* the plain kernel (grid 1 x 1) */ - Slot rows; /* the ROWS form (lever 2: one launch per layer for every conversation); omega_gpu_router_prepare_rows */ - 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_free(Slot *s) { if (s->valid) omega_gpu_session_free(&s->code); memset(s, 0, sizeof *s); } -static void slot_clear_locked(void) { slot_free(&g.slot); slot_free(&g.rows); } -static void on_session_close(void) { memset(&g.slot, 0, sizeof g.slot); memset(&g.rows, 0, sizeof g.rows); } -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) { return omega_gpu_router_alloc_shape(layers, 0, 0, out); } -int omega_gpu_router_alloc_shape(uint32_t layers, uint32_t experts, uint32_t shared, OmegaGpuRouter **out) { - if (!out || layers == 0 || layers > OMEGA_GPU_ROUTER_MAX_LAYERS) return OMEGA_GPU_ROUTER_BAD_ARGS; - *out = NULL; - if (!experts) experts = OMEGA_ROUTER_EXPERTS; - if ((experts != 128u && experts != 256u) || shared > 1u) return OMEGA_GPU_ROUTER_BAD_ARGS; - OmegaGpuRouter *r = omega_gpu_host_calloc(1, sizeof *r); - if (!r) return OMEGA_GPU_ROUTER_BAD_ARGS; - r->layers = layers; r->experts = experts; r->shared = shared; r->rows = experts + shared; r->slots = OMEGA_ROUTER_TOPK + shared; - r->lb_tab_dn = shared ? LB_TAB_DN9 : LB_TAB_DN; r->lb_bytes = shared ? LB_BYTES9 : LB_BYTES; - 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 * ROWB(r), &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 * DIRB(r), &r->dir) != 0) rc = OMEGA_GPU_ROUTER_CHIP_FAIL; - if (rc == OMEGA_GPU_ROUTER_OK && omega_gpu_session_alloc(r->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 * DIRB(r)); - memset(r->lb.cpu, 0, r->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 * ROWB(r), gate_bf16, ROWB(r)); - 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 * DIRB(r); - memcpy(d, gu, DIRB(r)); - memcpy(d + DIRB(r), dn, DIRB(r)); - 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[(256u + 1u) * 2], dn[(256u + 1u) * 2]; - for (uint32_t x = 0; x < r->rows; 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 + r->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, (size_t)r->slots * 16u); - if (tab_dn) memcpy(tab_dn, b + r->lb_tab_dn, (size_t)r->slots * 16u); - } - omega_gpu_session_unlock(); - return rc; -} - -/* ---- kernel ---- */ -static int kernel_for(const OmegaRouterSpec *spec, Slot **out, bool *hit) { - Slot *s = spec->xstride ? &g.rows : &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_free(s); - 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; -} - -static void spec_for(const OmegaGpuRouter *r, OmegaRouterSpec *spec, uint32_t xstride, uint32_t lbstride) { - 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; - spec->experts = r->experts == OMEGA_ROUTER_EXPERTS ? 0u : r->experts; spec->shared = r->shared; - spec->xstride = xstride; spec->lbstride = lbstride; -} - -/* 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). - * rows >= 2 (record path only, lever 2): the ROWS kernel, grid_y rows, row i at dev_x + i * xstride and rec_lb + i * lbstride. */ -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 rec_lb, - uint32_t xstride, uint32_t lbstride, uint32_t rows) { - 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; - if (rows > 1u && (!rec || !rec_lb)) return OMEGA_GPU_ROUTER_BAD_ARGS; - OmegaRouterSpec spec; spec_for(r, &spec, rows > 1u ? xstride : 0u, rows > 1u ? lbstride : 0u); - OmegaRouterSmem sm; - if (omega_router_smem(&spec, &sm) != 0) return OMEGA_GPU_ROUTER_BAD_ARGS; - - 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 < r->slots; i++) { wd[i] = POISON_F32; idd[i] = POISON_ID; } - memset(b + LB_TAB_GU, 0, (size_t)r->slots * 16u); memset(b + r->lb_tab_dn, 0, (size_t)r->slots * 16u); - 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 * ROWB(r); - 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 * DIRB(r), ddn = dgu + DIRB(r); - 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) - const uint64_t lb = rec_lb ? rec_lb : r->lb.va; /* record_to: the outputs land in the caller's buffer (one per conversation in the stroke) */ - A64(0, rec ? dev_x : r->lb.va + LB_X); A64(2, gate); A64(4, norm); A64(6, lb + LB_XOUT); A64(8, lb + LB_IDS); A64(10, lb + LB_WTS); - A64(12, dgu); A64(14, ddn); A64(16, lb + LB_TAB_GU); A64(18, lb + r->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 = ROWB(r); - 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 = rows > 1u ? rows : 1u, - .num_elements = (size_t)OMEGA_ROUTER_HIDDEN * (rows > 1u ? rows : 1u), - .args = args, .n_args = OMEGA_ROUTER_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, - .shared_bytes = sm.total, - }; - 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 < r->slots; 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 + r->lb_tab_dn); - size_t tab_zero = 0; - for (size_t i = 0; i < 2u * r->slots; 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] >= r->experts) bad_id++; - if (r->shared && idd[OMEGA_ROUTER_TOPK] != r->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, (size_t)r->slots * 4u); memcpy(weights, wd, (size_t)r->slots * 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, 0, 0, 0, 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, 0, 0, 0, 0); - 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 + r->lb_tab_dn; - } - return rc; -} -/* Record path with the outputs in the caller's buffer (L312 v2, the stroke: one buffer per conversation, the layout of - * omega_gpu_router_layout_bytes). Caller holds omega_gpu_session_lock(). */ -int omega_gpu_router_record_to(OmegaGpuCmdList *cl, OmegaGpuRouter *r, uint32_t layer, uint64_t x_va, float eps, int norm_topk, - float out_scale, uint64_t lb_va, OmegaGpuRouterDevOut *out) { - if (!cl || !r || !lb_va || (lb_va & 255u)) return OMEGA_GPU_ROUTER_BAD_ARGS; - int rc = router_core(r, layer, NULL, eps, norm_topk, out_scale, NULL, NULL, NULL, cl, x_va, lb_va, 0, 0, 0); - if (rc == OMEGA_GPU_ROUTER_OK && out) { - out->xout_va = lb_va + LB_XOUT; out->ids_va = lb_va + LB_IDS; out->wts_va = lb_va + LB_WTS; - out->tab_gu_va = lb_va + LB_TAB_GU; out->tab_dn_va = lb_va + r->lb_tab_dn; - } - return rc; -} -/* Lever 2 (L312): one launch for `rows` conversations of one layer (the ROWS form of the kernel, grid_y rows). Caller holds - * omega_gpu_session_lock(). rows 1 is record_to. The rows kernel must be resident (omega_gpu_router_prepare_rows). */ -int omega_gpu_router_record_rows(OmegaGpuCmdList *cl, OmegaGpuRouter *r, uint32_t layer, uint64_t x_va, uint32_t xstride, float eps, - int norm_topk, float out_scale, uint64_t lb_va, uint32_t lbstride, uint32_t rows, OmegaGpuRouterDevOut *out) { - if (!cl || !r || !lb_va || (lb_va & 255u) || rows == 0 || rows > OMEGA_GPU_ROUTER_MAX_ROWS) return OMEGA_GPU_ROUTER_BAD_ARGS; - if (rows == 1u) return omega_gpu_router_record_to(cl, r, layer, x_va, eps, norm_topk, out_scale, lb_va, out); - if (xstride < OMEGA_ROUTER_HIDDEN * 4u || (xstride & 15u) || lbstride < r->lb_bytes || (lbstride & 255u)) return OMEGA_GPU_ROUTER_BAD_ARGS; - int rc = router_core(r, layer, NULL, eps, norm_topk, out_scale, NULL, NULL, NULL, cl, x_va, lb_va, xstride, lbstride, rows); - if (rc == OMEGA_GPU_ROUTER_OK && out) { - out->xout_va = lb_va + LB_XOUT; out->ids_va = lb_va + LB_IDS; out->wts_va = lb_va + LB_WTS; - out->tab_gu_va = lb_va + LB_TAB_GU; out->tab_dn_va = lb_va + r->lb_tab_dn; - } - return rc; -} -/* Builds (or finds) the ROWS kernel for these strides and keeps it resident beside the plain one (its own cache slot). */ -int omega_gpu_router_prepare_rows(OmegaGpuRouter *r, uint32_t xstride, uint32_t lbstride) { - if (!r || xstride < OMEGA_ROUTER_HIDDEN * 4u || (xstride & 15u) || lbstride < r->lb_bytes || (lbstride & 255u)) return OMEGA_GPU_ROUTER_BAD_ARGS; - OmegaRouterSpec spec; spec_for(r, &spec, xstride, lbstride); - omega_gpu_session_lock(); - int rc = OMEGA_GPU_ROUTER_CHIP_FAIL; - if (dev_open_locked()) { Slot *ks = NULL; bool hit = false; g_rec = 0; rc = kernel_for(&spec, &ks, &hit); } - omega_gpu_session_unlock(); - return rc; -} -uint32_t omega_gpu_router_layout_bytes(const OmegaGpuRouter *r) { return r ? r->lb_bytes : 0u; } diff --git a/src/omega_gpu_router_api.h b/src/omega_gpu_router_api.h deleted file mode 100644 index 1232e8aaa..000000000 --- a/src/omega_gpu_router_api.h +++ /dev/null @@ -1,124 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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); -/* Qwen3.6-35B-A3B shape (sc L306): experts 256 (0 = 128) and shared 1. Then set_layer's gate_bf16 is [experts + 1][2048] - * (the last row = shared_expert_gate), the directories have experts + 1 entries (entry `experts` = the shared expert), - * and ids / weights / both tables have 9 slots: slot 8 = {experts, sigmoid(shared gate . xn), directory[experts]}. */ -int omega_gpu_router_alloc_shape(uint32_t layers, uint32_t experts, uint32_t shared, 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); -/* The stroke (L312 v2): the same launch with every output in the caller's device buffer at lb_va (256-byte aligned, - * omega_gpu_router_layout_bytes(r) bytes, the launch buffer's layout: xout, ids, wts, tab_gu, tab_dn at the offsets - * out reports). One buffer per conversation, so N routers of one layer can sit in one list. */ -int omega_gpu_router_record_to(struct OmegaGpuCmdList *cl, OmegaGpuRouter *r, uint32_t layer, uint64_t x_va, float eps, int norm_topk, - float out_scale, uint64_t lb_va, OmegaGpuRouterDevOut *out); -/* Lever 2 (L312, the stroke): one launch routes `rows` conversations of one layer, each exactly as it is routed alone: - * row i reads the residual row at x_va + i * xstride (bytes, >= 8192, a multiple of 16) and writes the record_to layout at - * lb_va + i * lbstride (lb_va 256-aligned, lbstride a multiple of 256 >= omega_gpu_router_layout_bytes). out = row 0's - * buffers (row i's are + i * lbstride). rows 1 = record_to. The rows kernel has its own cache slot beside the plain one and - * must be resident before recording: omega_gpu_router_prepare_rows (a cache miss while recording is refused). */ -#define OMEGA_GPU_ROUTER_MAX_ROWS 64u -int omega_gpu_router_prepare_rows(OmegaGpuRouter *r, uint32_t xstride, uint32_t lbstride); -int omega_gpu_router_record_rows(struct OmegaGpuCmdList *cl, OmegaGpuRouter *r, uint32_t layer, uint64_t x_va, uint32_t xstride, float eps, - int norm_topk, float out_scale, uint64_t lb_va, uint32_t lbstride, uint32_t rows, OmegaGpuRouterDevOut *out); -uint32_t omega_gpu_router_layout_bytes(const OmegaGpuRouter *r); -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_scan.c b/src/omega_gpu_scan.c deleted file mode 100644 index 0094072e3..000000000 --- a/src/omega_gpu_scan.c +++ /dev/null @@ -1,332 +0,0 @@ -/* omega_gpu_scan.c -- see omega_gpu_scan.h. Kernels from Omega's IR (emitter helpers of omega_bw_em.h, the - * chip-proven scheduling rules of the tensor-core generators), host references, the level driver, the chip calls. */ -#include "omega_gpu_scan.h" -#include "omega_bw_em.h" -#include "omega_gpu_session.h" - -#include -#include - -#define PAD_SUM 0x80000000u /* -0.0: x + -0.0 == x for every x */ -#define PAD_MINMAX 0x7fc00000u /* quiet NaN: max(NaN, x) == min(NaN, x) == x */ -#define POISON 0x7fa00badu /* a signalling NaN: no FADD or FMNMX writes it, so a word still holding it was never written */ -#define TIMEOUT_MS 20000ull - -/* ------------------------------------------------------------------ IR */ - -static void fmnmx(Em *e, BlackwellIROpcode op, int d, int a, int b) { - BlackwellIRInsn i = I0(op); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); -} -typedef struct { int bssy, bra; } Region; -/* the lanes with P0 set skip to the region's end; the warp joins again there */ -static 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 int gen(Em *e, const OmegaScanSpec *sp) { - const OmegaScanKind k = sp->kind; - const int red = k <= OMEGA_SCAN_K_RED_MIN; - int udesc = UV64(e), pin = V64(e), pout = V64(e), ptot = V64(e), len = V(e), tiles = V(e), warps = V(e); - int tid = V(e), cta = V(e), lane = V(e), gw = V(e), one = V(e), tile = V(e), el = V(e), v = V(e), t = V(e); - int a64 = V64(e), b64 = V64(e), rl = V(e), nz = V(e), c31 = V(e), m1 = V(e), off = V(e), tm1 = V(e); - int mask[5]; - for (unsigned s = 0; s < 5; s++) mask[s] = k == OMEGA_SCAN_K_TILE ? V(e) : NOREG; - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pin, OMEGA_GPU_SCAN_A_IN); ldc64(e, pout, OMEGA_GPU_SCAN_A_OUT); - if (k == OMEGA_SCAN_K_TILE) ldc64(e, ptot, OMEGA_GPU_SCAN_A_TOT); - ldc32(e, len, OMEGA_GPU_SCAN_A_LEN); ldc32(e, tiles, OMEGA_GPU_SCAN_A_TILES); ldc32(e, warps, OMEGA_GPU_SCAN_A_WARPS); - s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - movi(e, one, 1); movi(e, m1, 0xffffffffu); movi(e, nz, PAD_SUM); - andi(e, lane, tid, 0, 31u); - shr(e, t, tid, 0, 5); - imadi(e, gw, cta, 0, OMEGA_GPU_SCAN_THREADS / 32u, t); /* global warp = cta * 8 + warp */ - if (k == OMEGA_SCAN_K_ADD) imadi(e, tile, gw, 0, 1u, one); /* the carry starts at tile 1 */ - else imadi(e, tile, gw, 0, 1u, NOREG); - if (k == OMEGA_SCAN_K_TILE) { - /* reversed lanes: lane L holds tile position 31 - L, so SHFL.DOWN by d reads position - d */ - movi(e, c31, 31u); - lop3(e, rl, lane, c31, NOREG, 0x3cu); /* 31 - L == L ^ 31 for L < 32 */ - /* mask[s] = all ones when position - d exists (L + d <= 31), else 0: ((L + d) >> 5) - 1 */ - for (unsigned s = 0; s < 5; s++) { - movi(e, t, 1u << s); - iadd(e, mask[s], lane, t); - shr(e, mask[s], mask[s], 0, 5); - imadi(e, mask[s], mask[s], 0, 1u, m1); - } - } - - const int top = here(e); - loop_begin(e); - isetp_ge_u32(e, tile, tiles); - const int done = bra_if_p0_fwd(e); - if (red) { - const BlackwellIROpcode op = k == OMEGA_SCAN_K_RED_MAX ? BW_IR_FMNMX_MAX : BW_IR_FMNMX_MIN; - imadi(e, el, tile, 0, 32u, lane); - movi(e, v, k == OMEGA_SCAN_K_RED_SUM ? PAD_SUM : PAD_MINMAX); - isetp_ge_u32(e, el, len); - { Region r = skip_if_p0(e); imadw(e, a64, el, 4u, pin); ldg32(e, v, a64, udesc, 1); region_end(e, r); } - for (uint32_t d = 16; d >= 1; d /= 2) { - if (sp->mutant == 1 && d == 1) break; - shfl_down(e, t, v, d); - if (k == OMEGA_SCAN_K_RED_SUM) fadd(e, v, v, t); else fmnmx(e, op, v, v, t); - } - isetp_ge_u32(e, lane, one); - { Region r = skip_if_p0(e); imadw(e, a64, tile, 4u, pout); stg(e, a64, 0, v, udesc); region_end(e, r); } - } else if (k == OMEGA_SCAN_K_TILE) { - imadi(e, el, tile, 0, 32u, rl); - movi(e, v, PAD_SUM); - isetp_ge_u32(e, el, len); - { Region r = skip_if_p0(e); imadw(e, a64, el, 4u, pin); ldg32(e, v, a64, udesc, 1); region_end(e, r); } - for (unsigned s = 0; s < 5; s++) { - if (sp->mutant == 2 && s == 4) break; - shfl_down(e, t, v, 1u << s); - lop3(e, t, t, mask[s], nz, 0xe2u); /* (t & mask) | (-0.0 & ~mask) */ - fadd(e, v, t, v); /* lower position on the left */ - } - isetp_ge_u32(e, el, len); - { Region r = skip_if_p0(e); imadw(e, a64, el, 4u, pout); stg(e, a64, 0, v, udesc); region_end(e, r); } - isetp_ge_u32(e, lane, one); /* lane 0 holds position 31: the tile total */ - { Region r = skip_if_p0(e); imadw(e, a64, tile, 4u, ptot); stg(e, a64, 0, v, udesc); region_end(e, r); } - } else { - imadi(e, el, tile, 0, 32u, lane); - isetp_ge_u32(e, el, len); - { - Region r = skip_if_p0(e); - if (sp->mutant == 3) imadi(e, tm1, tile, 0, 1u, NOREG); else imadi(e, tm1, tile, 0, 1u, m1); - imadw(e, b64, tm1, 4u, pout); imadw(e, a64, el, 4u, pin); - ldg32(e, off, b64, udesc, 1); ldg32(e, v, a64, udesc, 0); - fadd(e, v, off, v); - stg(e, a64, 0, v, udesc); - region_end(e, r); - } - } - iadd(e, tile, tile, warps); - bra(e, top); - loop_end(e); - patch_bra(e, done, here(e)); - tail(e); - return e->err; -} - -int omega_gpu_scan_codegen(const OmegaScanSpec *spec, BlackwellIRProgram *prog) { - if (!spec || !prog || (unsigned)spec->kind >= OMEGA_SCAN_K_COUNT) return -1; - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - if (gen(&em, spec) != 0 || em.err || em.depth != 0) return -1; - return omega_bw_regalloc_solve(prog); -} - -/* ------------------------------------------------------------------ the level driver */ - -uint32_t omega_gpu_scan_grid(size_t len) { - size_t tiles = (len + 31) / 32, ctas = (tiles + OMEGA_GPU_SCAN_THREADS / 32u - 1) / (OMEGA_GPU_SCAN_THREADS / 32u); - return ctas > OMEGA_GPU_SCAN_MAX_CTAS ? OMEGA_GPU_SCAN_MAX_CTAS : (uint32_t)(ctas ? ctas : 1); -} - -static void args_for(uint32_t a[OMEGA_GPU_SCAN_ARGS_WORDS], uint64_t in, uint64_t out, uint64_t tot, size_t len) { - memset(a, 0, OMEGA_GPU_SCAN_ARGS_WORDS * 4u); - a[0] = (uint32_t)in; a[1] = (uint32_t)(in >> 32); a[2] = (uint32_t)out; a[3] = (uint32_t)(out >> 32); - a[4] = (uint32_t)tot; a[5] = (uint32_t)(tot >> 32); - a[6] = (uint32_t)len; a[7] = (uint32_t)((len + 31) / 32); a[8] = omega_gpu_scan_grid(len) * (OMEGA_GPU_SCAN_THREADS / 32u); -} - -size_t omega_gpu_scan_reduce_scratch_words(size_t n) { - size_t w = 0; - do { n = (n + 31) / 32; w += n; } while (n > 1); - return w; -} - -size_t omega_gpu_scan_prefix_scratch_words(size_t n) { - size_t w = 0; - while (n > 32) { n = (n + 31) / 32; w += n; } - return w + 1; /* the last level's single total */ -} - -int omega_gpu_scan_drive_reduce(OmegaGpuRedOp op, size_t n, uint64_t in_va, uint64_t scratch_va, uint64_t *out_va, - OmegaScanLaunchFn launch, void *ctx, uint32_t *launches) { - if ((unsigned)op > OMEGA_GPU_RED_MIN || n == 0 || !launch || !out_va) return OMEGA_GPU_SCAN_BAD_ARGS; - if (n > OMEGA_GPU_SCAN_MAX_N) return OMEGA_GPU_SCAN_TOO_LARGE; - const OmegaScanKind k = (OmegaScanKind)(OMEGA_SCAN_K_RED_SUM + (int)op); - uint64_t in = in_va, out = scratch_va; - size_t len = n; - uint32_t a[OMEGA_GPU_SCAN_ARGS_WORDS]; - do { - args_for(a, in, out, 0, len); - if (launch(ctx, k, a, omega_gpu_scan_grid(len)) != 0) return OMEGA_GPU_SCAN_CHIP_FAIL; - if (launches) (*launches)++; - len = (len + 31) / 32; - in = out; out += len * 4u; - } while (len > 1); - *out_va = in; - return OMEGA_GPU_SCAN_OK; -} - -int omega_gpu_scan_drive_prefix(size_t n, uint64_t in_va, uint64_t out_va, uint64_t scratch_va, - OmegaScanLaunchFn launch, void *ctx, uint32_t *launches) { - if (n == 0 || !launch) return OMEGA_GPU_SCAN_BAD_ARGS; - if (n > OMEGA_GPU_SCAN_MAX_N) return OMEGA_GPU_SCAN_TOO_LARGE; - enum { MAXL = 8 }; /* 32^6 >= 2^28 */ - uint64_t buf[MAXL], tot[MAXL]; - size_t len[MAXL]; - unsigned L = 0; - uint64_t in = in_va, sp = scratch_va; - buf[0] = out_va; len[0] = n; - uint32_t a[OMEGA_GPU_SCAN_ARGS_WORDS]; - for (;;) { /* forward: scan every level, its totals become the next level (scanned in place) */ - size_t nt = (len[L] + 31) / 32; - tot[L] = sp; sp += nt * 4u; - args_for(a, in, buf[L], tot[L], len[L]); - if (launch(ctx, OMEGA_SCAN_K_TILE, a, omega_gpu_scan_grid(len[L])) != 0) return OMEGA_GPU_SCAN_CHIP_FAIL; - if (launches) (*launches)++; - if (nt == 1) break; - if (L + 1 >= MAXL) return OMEGA_GPU_SCAN_TOO_LARGE; - buf[L + 1] = tot[L]; len[L + 1] = nt; in = tot[L]; - L++; - } - while (L-- > 0) { /* back down: carry the scanned totals of level L + 1 into level L */ - args_for(a, buf[L], buf[L + 1], 0, len[L]); - if (launch(ctx, OMEGA_SCAN_K_ADD, a, omega_gpu_scan_grid(len[L])) != 0) return OMEGA_GPU_SCAN_CHIP_FAIL; - if (launches) (*launches)++; - } - return OMEGA_GPU_SCAN_OK; -} - -/* ------------------------------------------------------------------ the chip */ - -static struct { - int mutant; - OmegaGpuMem code[OMEGA_SCAN_K_COUNT]; - uint32_t gpr[OMEGA_SCAN_K_COUNT]; - int hooked; -} g; - -/* lock held; the session calls it right before it closes the device (also in omega_gpu_session_recover): the kernels go - * with the device, the next call builds them again on the new one */ -static void on_session_close(void) { - for (unsigned k = 0; k < OMEGA_SCAN_K_COUNT; k++) if (g.code[k].cpu) omega_gpu_session_free(&g.code[k]); - memset(g.code, 0, sizeof g.code); -} - -void omega_gpu_scan_test_set_mutant(int mutant) { - omega_gpu_session_lock(); - for (unsigned k = 0; k < OMEGA_SCAN_K_COUNT; k++) if (g.code[k].cpu) omega_gpu_session_free(&g.code[k]); - memset(g.code, 0, sizeof g.code); - g.mutant = mutant; - omega_gpu_session_unlock(); -} - -const char *omega_gpu_scan_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_SCAN_OK: return "OK"; - case OMEGA_GPU_SCAN_BAD_ARGS: return "BAD_ARGS"; - case OMEGA_GPU_SCAN_TOO_LARGE: return "TOO_LARGE"; - case OMEGA_GPU_SCAN_CODEGEN_FAIL: return "CODEGEN_FAIL"; - case OMEGA_GPU_SCAN_CHIP_FAIL: return "CHIP_FAIL"; - default: return "?"; - } -} - -/* lock held */ -static int kernel_locked(OmegaScanKind k) { - if (g.code[k].cpu) return OMEGA_GPU_SCAN_OK; - if (!g.hooked) { /* without the hook a kernel would outlive its device */ - if (omega_gpu_session_on_close(on_session_close) != 0) return OMEGA_GPU_SCAN_CHIP_FAIL; - g.hooked = 1; - } - BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); - if (!prog) return OMEGA_GPU_SCAN_CODEGEN_FAIL; - OmegaScanSpec s = { k, g.mutant }; - int rc = OMEGA_GPU_SCAN_OK; - size_t need = 0; - if (omega_gpu_scan_codegen(&s, prog) != 0 || (need = omega_bw_program_code_bytes(prog)) == 0) rc = OMEGA_GPU_SCAN_CODEGEN_FAIL; - else if (omega_gpu_session_alloc_code(need, &g.code[k]) != 0) rc = OMEGA_GPU_SCAN_CHIP_FAIL; - else { - OmegaBlackwellKernel kk; - if (omega_blackwell_kernel_encode_into(prog, g.code[k].cpu, need, &kk) != 0 || kk.code_size != need) rc = OMEGA_GPU_SCAN_CODEGEN_FAIL; - else if (omega_gpu_session_sync_to_gpu(&g.code[k]) != 0) rc = OMEGA_GPU_SCAN_CHIP_FAIL; - else { g.gpr[k] = omega_bw_gpr_declared(kk.gpr_count); if (g.gpr[k] < 64u) g.gpr[k] = 64u; } - if (rc != OMEGA_GPU_SCAN_OK) { omega_gpu_session_free(&g.code[k]); memset(&g.code[k], 0, sizeof g.code[k]); } - } - omega_gpu_host_free(prog); - return rc; -} - -typedef struct { uint64_t elapsed_ns; } ChipCtx; - -/* lock held */ -static int chip_launch(void *ctx, OmegaScanKind k, const uint32_t args[OMEGA_GPU_SCAN_ARGS_WORDS], uint32_t grid_x) { - if (kernel_locked(k) != OMEGA_GPU_SCAN_OK) return -1; - OmegaGpuLaunch L = { - .code_va = g.code[k].va, .gpr_count = g.gpr[k], .threads_x = OMEGA_GPU_SCAN_THREADS, .threads_y = 1, - .grid_x = grid_x, .grid_y = 1, .num_elements = (size_t)grid_x * OMEGA_GPU_SCAN_THREADS, - .args = args, .n_args = OMEGA_GPU_SCAN_ARGS_WORDS, .timeout_ms = TIMEOUT_MS, - }; - uint64_t ns = 0; - if (omega_gpu_session_launch(&L, &ns, NULL) != 0) return -1; - ((ChipCtx *)ctx)->elapsed_ns += ns; - return 0; -} - -/* lock held: one data buffer [in n | out n | scratch], the input copied in, outputs poisoned */ -static int stage_locked(const float *x, size_t n, size_t out_words, size_t scratch_words, OmegaGpuMem *m) { - if (!omega_gpu_session_open()) return OMEGA_GPU_SCAN_CHIP_FAIL; - if (omega_gpu_session_alloc((n + out_words + scratch_words) * 4u, m) != 0) return OMEGA_GPU_SCAN_CHIP_FAIL; - uint32_t *w = m->cpu; - memcpy(w, x, n * 4u); - for (size_t i = n; i < n + out_words + scratch_words; i++) w[i] = POISON; - if (omega_gpu_session_sync_to_gpu(m) != 0) { omega_gpu_session_free(m); return OMEGA_GPU_SCAN_CHIP_FAIL; } - return OMEGA_GPU_SCAN_OK; -} - -int omega_gpu_reduce(OmegaGpuRedOp op, const float *x, size_t n, float *out, OmegaGpuScanInfo *info) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - if ((unsigned)op > OMEGA_GPU_RED_MIN || !x || !out || n == 0) return OMEGA_GPU_SCAN_BAD_ARGS; - if (n > OMEGA_GPU_SCAN_MAX_N) return OMEGA_GPU_SCAN_TOO_LARGE; - omega_gpu_session_lock(); - OmegaGpuMem m; - const size_t sw = omega_gpu_scan_reduce_scratch_words(n); - int rc = stage_locked(x, n, 0, sw, &m); - if (rc == OMEGA_GPU_SCAN_OK) { - ChipCtx c = { 0 }; uint64_t res = 0; uint32_t nl = 0; - rc = omega_gpu_scan_drive_reduce(op, n, m.va, m.va + n * 4u, &res, chip_launch, &c, &nl); - if (rc == OMEGA_GPU_SCAN_OK && omega_gpu_session_sync_to_cpu(&m) != 0) rc = OMEGA_GPU_SCAN_CHIP_FAIL; - if (rc == OMEGA_GPU_SCAN_OK) { - uint32_t r; memcpy(&r, (const uint8_t *)m.cpu + (res - m.va), 4); - if (r == POISON) { omega_gpu_session_set_error("reduce: the result word was never written"); rc = OMEGA_GPU_SCAN_CHIP_FAIL; } - else memcpy(out, &r, 4); - } - if (info) { info->launches = nl; info->elapsed_ns = c.elapsed_ns; } - omega_gpu_session_free(&m); - } - omega_gpu_session_unlock(); - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} - -int omega_gpu_prefix_sum(const float *x, size_t n, float *y, OmegaGpuScanInfo *info) { - uint64_t t0 = omega_gpu_session_now_ns(); - if (info) memset(info, 0, sizeof *info); - if (!x || !y || n == 0) return OMEGA_GPU_SCAN_BAD_ARGS; - if (n > OMEGA_GPU_SCAN_MAX_N) return OMEGA_GPU_SCAN_TOO_LARGE; - omega_gpu_session_lock(); - OmegaGpuMem m; - int rc = stage_locked(x, n, n, omega_gpu_scan_prefix_scratch_words(n), &m); - if (rc == OMEGA_GPU_SCAN_OK) { - ChipCtx c = { 0 }; uint32_t nl = 0; - rc = omega_gpu_scan_drive_prefix(n, m.va, m.va + n * 4u, m.va + 2 * n * 4u, chip_launch, &c, &nl); - if (rc == OMEGA_GPU_SCAN_OK && omega_gpu_session_sync_to_cpu(&m) != 0) rc = OMEGA_GPU_SCAN_CHIP_FAIL; - if (rc == OMEGA_GPU_SCAN_OK) { - const uint32_t *w = (const uint32_t *)m.cpu + n; - size_t unwritten = 0; - for (size_t i = 0; i < n; i++) unwritten += w[i] == POISON; - if (unwritten) { omega_gpu_session_set_error("prefix sum: output words never written"); rc = OMEGA_GPU_SCAN_CHIP_FAIL; } - else memcpy(y, w, n * 4u); - } - if (info) { info->launches = nl; info->elapsed_ns = c.elapsed_ns; } - omega_gpu_session_free(&m); - } - omega_gpu_session_unlock(); - if (info) info->call_ns = omega_gpu_session_now_ns() - t0; - return rc; -} diff --git a/src/omega_gpu_scan.h b/src/omega_gpu_scan.h deleted file mode 100644 index 3c775cf6a..000000000 --- a/src/omega_gpu_scan.h +++ /dev/null @@ -1,110 +0,0 @@ -/* omega_gpu_scan.h -- reductions and prefix sums of any length on the GB10 (row C3 of docs/OMEGA.md). - * - * The sum, the maximum and the minimum of n float values, and the inclusive prefix sum (the running total - * y[i] = x[0] + ... + x[i]), for every n from 1 to 2^28. The order of the additions is frozen: it depends only on n - * and the element index, never on the grid, the scheduling or the chip, so the chip result equals the host - * reference below bit for bit. - * - * Reductions (the order of docs/numeric/E1_REDUCTION_CONTRACT.md, omega_numeric_reduce.h): one level turns len values - * into ceil(len / 32) values; value j is the 32-lane tree over values [32j, 32j + 32) with lane i combining lane i + d - * for d = 16, 8, 4, 2, 1 (lower lane on the left), positions past len filled with the identity (-0.0 for the sum, a - * quiet NaN for the maximum and minimum, which those operations ignore). Levels repeat until one value is left; at - * least one level runs. - * - * Prefix sum, same tile structure: - * level scan inside each tile of 32 (positions past len filled with -0.0), for d = 1, 2, 4, 8, 16 in that order, - * every position i >= d takes v[i - d] + v[i] (both from before the step); the tile total T[j] is the - * value at position 31. - * carry when there is more than one tile, the totals T are prefix-summed by the same definition (recursively) - * into S, and every element of tile j >= 1 becomes S[j - 1] + (its tile value). - * Inputs are any float values. Results with no NaN are bit-exact; a NaN result is a NaN (the chip writes one canonical - * NaN, the host may keep another payload). - * - * On the chip each level is one launch of a kernel from Omega's own codegen (no CUDA): the reduction tree and the - * tile scan are warp shuffles (SHFL.DOWN; the scan holds each tile in reversed lane order so a shuffle down reads the - * lower element), the carry is a separate pass. omega_gpu_scan_drive_* run the levels through a launch callback, so - * the same driver runs on the chip (omega_gpu_reduce, omega_gpu_prefix_sum) and in the warp simulator - * (tests/gpu_scan_test.c). */ -#ifndef OMEGA_GPU_SCAN_H -#define OMEGA_GPU_SCAN_H - -#include -#include -#include "omega_blackwell_codegen.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_GPU_SCAN_MAX_N ((size_t)1 << 28) -#define OMEGA_GPU_SCAN_THREADS 256u /* 8 warps per CTA; each warp walks tiles gw, gw + warps, ... */ -#define OMEGA_GPU_SCAN_MAX_CTAS 1024u - -enum { - OMEGA_GPU_SCAN_OK = 0, - OMEGA_GPU_SCAN_BAD_ARGS = -1, /* NULL pointer, n == 0, unknown op */ - OMEGA_GPU_SCAN_TOO_LARGE = -2, /* n > OMEGA_GPU_SCAN_MAX_N */ - OMEGA_GPU_SCAN_CODEGEN_FAIL = -3, /* our codegen refused a kernel */ - OMEGA_GPU_SCAN_CHIP_FAIL = -4 /* device, allocation, launch, or an output word the chip never wrote */ -}; - -typedef enum { OMEGA_GPU_RED_SUM = 0, OMEGA_GPU_RED_MAX = 1, OMEGA_GPU_RED_MIN = 2 } OmegaGpuRedOp; - -/* The kernels. Argument words at constant bank 0x380 (OMEGA_GPU_SCAN_A_*). */ -typedef enum { - OMEGA_SCAN_K_RED_SUM = 0, OMEGA_SCAN_K_RED_MAX, OMEGA_SCAN_K_RED_MIN, /* one reduction level: in -> out[tile] */ - OMEGA_SCAN_K_TILE, /* one scan level: in -> out (may alias), tot[tile] */ - OMEGA_SCAN_K_ADD, /* carry: out[e] = S[tile - 1] + out[e], tiles >= 1 */ - OMEGA_SCAN_K_COUNT -} OmegaScanKind; -#define OMEGA_GPU_SCAN_A_IN 0x380u /* u64: level input (K_ADD: the level being carried into) */ -#define OMEGA_GPU_SCAN_A_OUT 0x388u /* u64: level output (K_ADD: S, the scanned totals) */ -#define OMEGA_GPU_SCAN_A_TOT 0x390u /* u64: tile totals (K_TILE only) */ -#define OMEGA_GPU_SCAN_A_LEN 0x398u /* u32: values in this level */ -#define OMEGA_GPU_SCAN_A_TILES 0x39cu /* u32: ceil(len / 32) */ -#define OMEGA_GPU_SCAN_A_WARPS 0x3a0u /* u32: warps in the grid (the tile stride) */ -#define OMEGA_GPU_SCAN_ARGS_WORDS 9u - -/* Mutants for the red checks (each must change some result): 1 the reduction tree skips d = 1, 2 the tile scan skips - * d = 16, 3 the carry adds S[tile] instead of S[tile - 1]. 0 = the real kernels. */ -typedef struct { OmegaScanKind kind; int mutant; } OmegaScanSpec; - -/* Builds the IR program of one kernel and allocates its registers; 0 or -1. */ -int omega_gpu_scan_codegen(const OmegaScanSpec *spec, BlackwellIRProgram *prog); - -/* Host references, the frozen order above. 0, or -1 for bad arguments or out of memory. */ -int omega_gpu_reduce_reference(OmegaGpuRedOp op, const float *x, size_t n, float *out); -int omega_gpu_prefix_sum_reference(const float *x, size_t n, float *y); - -/* The level driver. Device addresses are plain numbers (host pointers in the simulator). launch runs one kernel over - * grid_x CTAs of OMEGA_GPU_SCAN_THREADS threads with the given argument words and returns 0 when it completed. */ -typedef int (*OmegaScanLaunchFn)(void *ctx, OmegaScanKind kind, const uint32_t args[OMEGA_GPU_SCAN_ARGS_WORDS], uint32_t grid_x); -/* Scratch words a call needs beyond its input and output. */ -size_t omega_gpu_scan_reduce_scratch_words(size_t n); -size_t omega_gpu_scan_prefix_scratch_words(size_t n); -/* Reduction: the result lands in the scratch word the function returns through *out_va. */ -int omega_gpu_scan_drive_reduce(OmegaGpuRedOp op, size_t n, uint64_t in_va, uint64_t scratch_va, uint64_t *out_va, - OmegaScanLaunchFn launch, void *ctx, uint32_t *launches); -/* Prefix sum of in into out (out may equal in). */ -int omega_gpu_scan_drive_prefix(size_t n, uint64_t in_va, uint64_t out_va, uint64_t scratch_va, - OmegaScanLaunchFn launch, void *ctx, uint32_t *launches); -/* CTAs for a level of len values. */ -uint32_t omega_gpu_scan_grid(size_t len); - -typedef struct { - uint32_t launches; /* kernels run */ - uint64_t elapsed_ns; /* sum of launch-to-completion over the launches */ - uint64_t call_ns; /* the whole call, uploads and readback included */ -} OmegaGpuScanInfo; - -/* On the chip. x is read, out / y written; nothing else is kept between calls except the kernels. */ -int omega_gpu_reduce(OmegaGpuRedOp op, const float *x, size_t n, float *out, OmegaGpuScanInfo *info); -int omega_gpu_prefix_sum(const float *x, size_t n, float *y, OmegaGpuScanInfo *info); -/* Red checks: every later call builds its kernels with this mutant (clears the kernel cache). */ -void omega_gpu_scan_test_set_mutant(int mutant); -const char *omega_gpu_scan_rc_name(int rc); - -#ifdef __cplusplus -} -#endif -#endif /* OMEGA_GPU_SCAN_H */ diff --git a/src/omega_gpu_scan_ref.c b/src/omega_gpu_scan_ref.c deleted file mode 100644 index ab5ee16a5..000000000 --- a/src/omega_gpu_scan_ref.c +++ /dev/null @@ -1,75 +0,0 @@ -/* omega_gpu_scan_ref.c -- the host references of omega_gpu_scan.h: the frozen order, in plain C on the CPU. - * Separate from the chip code so a CPU-only program can check them against the E1 reduction reference - * (tests/gpu_scan_ref_check.c). Additions only, so no fused multiply-add can change a bit. */ -#include "omega_gpu_scan.h" - -#include -#include - -#define PAD_SUM 0x80000000u /* -0.0 */ -#define PAD_MINMAX 0x7fc00000u /* quiet NaN */ - - -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } - -static float combine(OmegaGpuRedOp op, float a, float b) { - if (op == OMEGA_GPU_RED_SUM) return a + b; - return op == OMEGA_GPU_RED_MAX ? __builtin_fmaxf(a, b) : __builtin_fminf(a, b); /* AArch64 FMAXNM / FMINNM: NaN ignored */ -} - -int omega_gpu_reduce_reference(OmegaGpuRedOp op, const float *x, size_t n, float *out) { - if ((unsigned)op > OMEGA_GPU_RED_MIN || !x || !out || n == 0) return -1; - const float pad = u2f(op == OMEGA_GPU_RED_SUM ? PAD_SUM : PAD_MINMAX); - float *cur = NULL; - size_t len = n; - const float *in = x; - do { - size_t nt = (len + 31) / 32; - float *next = malloc(nt * sizeof *next); - if (!next) { free(cur); return -1; } - for (size_t j = 0; j < nt; j++) { - float v[32]; - for (size_t i = 0; i < 32; i++) v[i] = j * 32 + i < len ? in[j * 32 + i] : pad; - for (size_t d = 16; d >= 1; d /= 2) - for (size_t i = 0; i + d < 32; i++) v[i] = combine(op, v[i], v[i + d]); /* ascending: v[i + d] is still old */ - next[j] = v[0]; - } - free(cur); - cur = next; in = next; len = nt; - } while (len > 1); - *out = cur[0]; - free(cur); - return 0; -} - -/* one scan level of len values: out (may alias in) and the tile totals */ -static void ref_scan_level(const float *in, float *out, float *tot, size_t len) { - for (size_t j = 0; j * 32 < len; j++) { - float v[32]; - for (size_t i = 0; i < 32; i++) v[i] = j * 32 + i < len ? in[j * 32 + i] : u2f(PAD_SUM); - for (size_t d = 1; d <= 16; d *= 2) - for (size_t i = 31; i >= d; i--) v[i] = v[i - d] + v[i]; /* descending: v[i - d] is still old */ - for (size_t i = 0; i < 32 && j * 32 + i < len; i++) out[j * 32 + i] = v[i]; - tot[j] = v[31]; - } -} - -static int ref_prefix(const float *in, float *out, size_t len) { - size_t nt = (len + 31) / 32; - float *tot = malloc(nt * sizeof *tot); - if (!tot) return -1; - ref_scan_level(in, out, tot, len); - int rc = 0; - if (nt > 1) { - rc = ref_prefix(tot, tot, nt); - for (size_t e = 32; rc == 0 && e < len; e++) out[e] = tot[e / 32 - 1] + out[e]; - } - free(tot); - return rc; -} - -int omega_gpu_prefix_sum_reference(const float *x, size_t n, float *y) { - if (!x || !y || n == 0) return -1; - return ref_prefix(x, y, n); -} - diff --git a/src/omega_gpu_serving.c b/src/omega_gpu_serving.c deleted file mode 100644 index 9aba1a20d..000000000 --- a/src/omega_gpu_serving.c +++ /dev/null @@ -1,41 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 d4acb7a24..000000000 --- a/src/omega_gpu_serving.h +++ /dev/null @@ -1,64 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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 41a72e285..000000000 --- a/src/omega_gpu_session.c +++ /dev/null @@ -1,634 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 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; -} - -/* L136: queues past the first (omega_gpu_session_extra_queue), each with its own 64 KB ring; opened on demand, closed - * and freed before queue 0 at close, parked at the latch like the session ring. */ -#define XQ_MAX 3u -static OmegaGpuQueueHandle g_xq[XQ_MAX]; -static OmegaGpuMem g_xpb[XQ_MAX]; - -/* Uncertain completion: the device may still touch any session buffer. Keep everything, refuse everything. */ -static void latch(const char *why) { - STORE(g_blocked, 1u); - for (uint32_t i = 0; i < XQ_MAX; i++) if (g_xpb[i].cpu) park(&g_xpb[i]); - 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); -} - -void omega_gpu_session_latch_uncertain(const char *why) { latch(why ? why : "uncertain completion (latched by a caller)"); } - -/* ---- 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_extra_queue(uint32_t i, OmegaGpuQueueHandle *out) { - const OmegaGpuPlatform *p = platform(); - if (!out || i == 0u || i > XQ_MAX) { omega_gpu_session_set_error("extra_queue: index outside 1..3"); return -1; } - if (LOAD(g_blocked) || !g_open || !p) { omega_gpu_session_set_error("extra_queue: device not open or latched"); return -1; } - if (g_xq[i - 1u].generation != 0u) { *out = g_xq[i - 1u]; return 0; } - for (uint32_t j = 0; j + 1u < i; j++) - if (g_xq[j].generation == 0u) { omega_gpu_session_set_error("extra_queue: open queues in order (1, then 2, ...)"); return -1; } - if (mem_alloc(OMEGA_GPU_HANDLE_BUF_QUEUE, RIGHTS_RING, 0x10000, &g_xpb[i - 1u])) return -1; - const int rc = p->queue_open(p->ctx, g_s.dev, g_xpb[i - 1u].handle, &g_xq[i - 1u]); - if (rc != OMEGA_GPU_PLAT_OK) { - fail_plat("queue_open (extra queue)", rc); - memset(&g_xq[i - 1u], 0, sizeof g_xq[i - 1u]); - omega_gpu_session_free(&g_xpb[i - 1u]); - return -1; - } - *out = g_xq[i - 1u]; - return 0; -} - -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 */ - for (uint32_t i = XQ_MAX; i-- > 0;) { /* L136: extra queues first, then queue 0 */ - if (g_xq[i].generation != 0u) (void)p->queue_close(p->ctx, g_xq[i]); - memset(&g_xq[i], 0, sizeof g_xq[i]); - omega_gpu_session_free(&g_xpb[i]); - } - (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(); -} - - -/* C5: the way back from a latch without restarting the process. The on-close hooks run first, still latched, so the APIs - * drop their resident kernels and scratch (their frees park: nothing is released while the old device may run). Then - * the device closes: the Linux reference closes the RM client, which destroys every channel of this process (extra - * queues first) and with it every grid still running on them, then frees and unmaps every buffer, parked ones - * included. Only after the close returned OK is the latch lifted; the next open starts a new device. */ -static uint32_t g_recoveries; -static uint32_t g_module_latched; /* a module (the command lists) latched itself while the session stayed usable */ - -void omega_gpu_session_note_module_latch(void) { STORE(g_module_latched, 1u); } - -int omega_gpu_session_recover(void) { - omega_gpu_session_lock(); - const OmegaGpuPlatform *p = LOAD(g_p); - int rc = -1; - const int latched = LOAD(g_blocked) || LOAD(g_module_latched); - if (!latched || !g_open || !p) { - omega_gpu_session_set_error(latched ? "recover: latched but no device is open" : "recover: not latched (nothing to recover)"); - goto out; - } - for (unsigned i = 0; i < g_nhooks; i++) g_hooks[i](); - const int prc = p->device_close(p->ctx, g_s.dev); - if (prc != OMEGA_GPU_PLAT_OK) { fail_plat("recover: the device close reported a teardown fault (still latched: the old grid may live on, exit the process)", prc); goto out; } - memset(g_xq, 0, sizeof g_xq); - memset(g_xpb, 0, sizeof g_xpb); - const uint32_t opens = g_s.opens; - memset(&g_s, 0, sizeof g_s); - g_s.opens = opens; - g_open = false; - memset(g_parked, 0, sizeof g_parked); - memset(&g_park, 0, sizeof g_park); - BUMP(g_recoveries, 1u); - STORE(g_module_latched, 0u); - STORE(g_blocked, 0u); - omega_gpu_session_set_error(""); - rc = 0; -out: - omega_gpu_session_unlock(); - return rc; -} - -uint32_t omega_gpu_session_recoveries(void) { return LOAD(g_recoveries); } -/* ---- 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 8a4ae6727..000000000 --- a/src/omega_gpu_session.h +++ /dev/null @@ -1,295 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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); - -/* L136 (roadblock R3): caller holds the lock, device open. Queue i (1..3) past the session's own queue, with its own - * 64 KB ring, opened on first use (in order: 1, then 2, ...) and kept until close. The Linux reference grants it only - * when the device was opened with AIEN_OMEGA_GPU_CHANNELS > i (a second GPFIFO channel in the same channel group and - * VA space); otherwise the platform refuses and this returns -1 with the stage named. Work on different queues is not - * ordered against each other. 0 ok. */ -int omega_gpu_session_extra_queue(uint32_t i, OmegaGpuQueueHandle *out); -/* L136: latch the process now (uncertain completion seen by a caller that cannot prove it with a queue-0 launch, e.g. a - * list on an extra queue timed out). Parks every session buffer; every later launch of every API is refused. */ -void omega_gpu_session_latch_uncertain(const char *why); - -/* C5: after a latch (a timeout or a cancel after submit), throw the device away and lift the latch, in the same process. - * Takes the lock itself. Runs the on-close hooks (still latched), closes the device (Linux reference: the RM client - * close destroys this process's channels, and so any grid still running on them, then frees every buffer, parked ones - * included) and only then clears the latch and the parked list. Every handle and command list of the old device is - * stale; the next open starts a new device. 0 ok; -1 with the reason: not latched, or the close was refused or reported - * a driver teardown fault (then it stays latched for good: the old grid may still run, the process must exit). */ -int omega_gpu_session_recover(void); -/* A module that latched itself (the command lists after a timeout whose check launch completed) tells the session, so - * omega_gpu_session_recover accepts it as latched. Launches of other APIs are not refused by it. */ -void omega_gpu_session_note_module_latch(void); -/* Recoveries so far in this process (a command list latched before the latest recovery no longer blocks). */ -uint32_t omega_gpu_session_recoveries(void); - -/* 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 50e740472..000000000 --- a/src/omega_gpu_tcgemm_api.c +++ /dev/null @@ -1,204 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 f75884996..000000000 --- a/src/omega_gpu_tcgemm_api.h +++ /dev/null @@ -1,68 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 36f052a92..000000000 --- a/src/omega_gpu_tern_api.c +++ /dev/null @@ -1,364 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* 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 4e81e02c1..000000000 --- a/src/omega_gpu_tern_api.h +++ /dev/null @@ -1,121 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 57325f0fd..000000000 --- a/src/omega_gpu_wait.c +++ /dev/null @@ -1,171 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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 f007dbca9..000000000 --- a/src/omega_gpu_wait.h +++ /dev/null @@ -1,116 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 - * Copyright 2026 Drake Stapleton (AIEN / aien-dev) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#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/src/omega_sm121_disasm.c b/src/omega_sm121_disasm.c deleted file mode 100644 index 796db0339..000000000 --- a/src/omega_sm121_disasm.c +++ /dev/null @@ -1,288 +0,0 @@ -/* omega_sm121_disasm.c -- see omega_sm121_disasm.h. - * - * Layout of a word (lo = bits 0..63, hi = bits 64..127): opcode bits 0..11; guard predicate bits 12..14 with its - * negation at 15 (7 and no negation = no guard); destination register 16..23, first source 24..31, second source - * 32..39 or a 32-bit immediate at 32..63; third source at hi 0..7; modifiers in hi 8..40; control from hi 41 on. - * - * A row of the table is one instruction form: its opcode and fixed bits (lov, hiv) and a format. Each operand code - * in the format names the bits it reads; every other bit of lo and of hi 0..40 (outside the guard) must equal the - * row's fixed value, or the row does not match. The rows come from the words Omega's builders write - * (src/omega_blackwell_codegen.c encode_single_insn, the em helpers, src/omega_osc_gpu.c); the text of each was - * checked against nvdisasm 13.0 -b SM121 by tools/sm121dis/check.sh. */ -#include "omega_sm121_disasm.h" -#include -#include -#include - -#define HI_BITS 41 -#define HI_MASK ((1ULL << HI_BITS) - 1) - -typedef struct { - uint64_t lov, hiv; /* fixed bits (operand fields zero) */ - const char *fmt; /* text; %x codes are operands, see field() */ -} Row; - -/* operand codes: which bits they read (lo or hi, first bit, width); several fields for the branch target */ -typedef struct { char code; int hi; int at; int n; } Field; -static const Field FIELDS[] = { - {'d', 0, 16, 8}, {'a', 0, 24, 8}, {'b', 0, 32, 8}, {'c', 1, 0, 8}, /* R registers */ - {'D', 0, 16, 8}, {'A', 0, 24, 8}, {'B', 0, 32, 8}, {'C', 1, 0, 8}, /* uniform registers */ - {'i', 0, 32, 32}, {'s', 0, 32, 32}, {'f', 0, 32, 32}, /* 32-bit immediate: unsigned, signed, float */ - {'K', 0, 38, 21}, /* c[bank][offset]: offset 38..53, bank 54..58 */ - {'U', 0, 37, 22}, /* uniform load c[bank][offset]: offset 37..53 */ - {'o', 0, 40, 24}, /* signed 24-bit address offset */ - {'Y', 0, 32, 32}, /* BSSY target: signed byte distance */ - {'y', 0, 16, 4}, /* convergence barrier B0..B15 */ - {'P', 1, 17, 3}, {'Q', 1, 20, 3}, {'R', 1, 23, 4}, /* predicates; R carries its negation (hi 26) */ - {'l', 1, 8, 8}, /* LOP3 truth table */ - {'h', 0, 53, 5}, {'m', 0, 40, 13}, /* SHFL lane distance, clamp */ - {'S', 1, 8, 8}, /* special register */ - {'G', 1, 12, 3}, {'g', 1, 12, 4}, /* integer and float compare */ - {'Z', 1, 9, 1}, {'z', 1, 9, 3}, /* ISETP signed flag; memory access size */ - {'N', 1, 8, 1}, {'M', 0, 63, 1}, /* IADD3 negations: first, second source */ - {'j', 0, 32, 32}, /* ISETP immediate (printed signed) */ -}; - -static const Field *field_of(char c) { - for (size_t i = 0; i < sizeof FIELDS / sizeof FIELDS[0]; i++) if (FIELDS[i].code == c) return &FIELDS[i]; - return NULL; -} - -static uint64_t bits(uint64_t v, int at, int n) { return n >= 64 ? v >> at : (v >> at) & ((1ULL << n) - 1); } -static uint64_t mask(int at, int n) { return (n >= 64 ? ~0ULL : ((1ULL << n) - 1)) << at; } - -/* the BRA distance: 4-byte units, low 8 bits at 16..23, the rest (signed) at 34..81 */ -#define BRA_LO_MASK (mask(16, 8) | mask(34, 30)) -#define BRA_HI_MASK mask(0, 18) - -typedef struct { char *o; size_t n, at; int ok; } Out; - -static void put(Out *w, const char *fmt, ...) { - if (w->at >= w->n) { w->ok = 0; return; } - va_list ap; va_start(ap, fmt); - int k = vsnprintf(w->o + w->at, w->n - w->at, fmt, ap); - va_end(ap); - if (k < 0 || (size_t)k >= w->n - w->at) { w->ok = 0; w->at = w->n; return; } - w->at += (size_t)k; -} - -static void reg(Out *w, const char *p, uint64_t r) { if (r == 255) put(w, "%sZ", p); else put(w, "%s%u", p, (unsigned)r); } -static void hex_s(Out *w, int64_t v) { if (v < 0) put(w, "-0x%llx", (unsigned long long)(-v)); else put(w, "0x%llx", (unsigned long long)v); } -static void pred(Out *w, uint64_t p, int neg) { put(w, "%s", neg ? "!" : ""); if (p == 7) put(w, "PT"); else put(w, "P%u", (unsigned)p); } - -static const char *SR[256] = { - [0x21] = "SR_TID.X", [0x22] = "SR_TID.Y", [0x23] = "SR_TID.Z", - [0x25] = "SR_CTAID.X", [0x26] = "SR_CTAID.Y", [0x27] = "SR_CTAID.Z", - [0x00] = "SR_LANEID", [0x50] = "SR_CLOCKLO", [0x51] = "SR_CLOCKHI", -}; -static const char *ICMP[8] = { "F", "LT", "EQ", "LE", "GT", "NE", "GE", "T" }; -static const char *FCMP[16] = { "F", "LT", "EQ", "LE", "GT", "NE", "GE", "NUM", "NAN", "LTU", "EQU", "LEU", "GTU", "NEU", "GEU", "T" }; -static const char *MSIZE[8] = { ".U8" , ".S8", ".U16", ".S16", "", ".64", ".128", ".U.128" }; - -/* nvdisasm prints a float immediate the shortest way that reads back exactly, with INF and NAN by name */ -static void fimm(Out *w, uint32_t u) { - float f; memcpy(&f, &u, 4); - if ((u & 0x7f800000u) == 0x7f800000u) { - if (u & 0x007fffffu) put(w, "%sQNAN", (u >> 31) ? "-" : "+"); - else put(w, "%sINF", (u >> 31) ? "-" : "+"); - return; - } - char b[64]; - for (int p = 1; p <= 20; p++) { - snprintf(b, sizeof b, "%.*g", p, (double)f); - float g; if (sscanf(b, "%g", &g) == 1 && memcmp(&g, &f, 4) == 0) break; - } - put(w, "%s", b); -} - -/* Prints row's format for (lo, hi); 0 when every operand could be printed */ -static void render(Out *w, const char *fmt, uint64_t lo, uint64_t hi, uint64_t pc) { - for (const char *p = fmt; *p; p++) { - if (*p != '%') { put(w, "%c", *p); continue; } - char c = *++p; - const Field *f = field_of(c); - uint64_t v = f ? bits(f->hi ? hi : lo, f->at, f->n) : 0; - switch (c) { -#ifdef SM121DIS_MUTANT - case 'a': reg(w, "R", v == 255 ? v : v ^ 1); break; /* the red check: first source register off by one bit */ - case 'd': case 'b': case 'c': reg(w, "R", v); break; -#else - case 'd': case 'a': case 'b': case 'c': reg(w, "R", v); break; -#endif - case 'D': case 'A': case 'B': case 'C': reg(w, "UR", v); break; - case 'i': put(w, "0x%x", (unsigned)v); break; - case 's': hex_s(w, (int32_t)(uint32_t)v); break; - case 'f': fimm(w, (uint32_t)v); break; - case 'K': put(w, "c[0x%x][0x%x]", (unsigned)bits(lo, 54, 5), (unsigned)bits(lo, 38, 16)); break; - case 'U': put(w, "c[0x%x][0x%x]", (unsigned)bits(lo, 54, 5), (unsigned)bits(lo, 37, 17)); break; - case 'o': { int32_t off = (int32_t)((uint32_t)v << 8) >> 8; if (off) { put(w, "+"); hex_s(w, off); } /* nvdisasm writes a negative offset as +-0x4 */ break; } - case 'Y': put(w, "0x%llx", (unsigned long long)(pc + 16 + (int64_t)(int32_t)(uint32_t)v)); break; - case 'y': put(w, "B%u", (unsigned)v); break; - case 'P': case 'Q': pred(w, v, 0); break; - case 'R': pred(w, v & 7, (int)((v >> 3) & 1)); break; - case 'l': put(w, "0x%x", (unsigned)v); break; - case 'h': case 'm': put(w, "0x%x", (unsigned)v); break; - case 'S': if (SR[v]) put(w, "%s", SR[v]); else put(w, "SR%u", (unsigned)v); break; - case 'G': put(w, "%s", ICMP[v]); break; - case 'Z': if (!v) put(w, ".U32"); break; - case 'z': put(w, "%s", MSIZE[v]); break; - case 'N': case 'M': if (v) put(w, "-"); break; - case 'j': hex_s(w, (int32_t)(uint32_t)v); break; /* signed even in a .U32 compare, as nvdisasm prints it */ - case 'g': put(w, "%s", FCMP[v]); break; - case 'T': { - uint64_t units = bits(lo, 16, 8) | (bits(lo, 34, 30) << 8) | (bits(hi, 0, 18) << 38); - int64_t s = (int64_t)(units << 8) >> 8; /* 56-bit signed */ - put(w, "0x%llx", (unsigned long long)(pc + 16 + s * 4)); - break; - } - default: w->ok = 0; return; - } - } -} - -/* the bits a format reads */ -static void fields_mask(const char *fmt, uint64_t *lom, uint64_t *him) { - *lom = 0; *him = 0; - for (const char *p = fmt; *p; p++) { - if (*p != '%') continue; - char c = *++p; - if (c == 'T') { *lom |= BRA_LO_MASK; *him |= BRA_HI_MASK; continue; } - const Field *f = field_of(c); - if (!f) continue; - if (f->hi) *him |= mask(f->at, f->n); else *lom |= mask(f->at, f->n); - } -} - -/* The forms. lo values include the opcode (bits 0..11); guard bits 12..15 are never part of a row. */ -static const Row ROWS[] = { - /* moves, constants, special registers */ - { 0x0000000000007802ull, 0x00000f00ull, "MOV %d, %i" }, - { 0x00000000ff007202ull, 0x00000f00ull, "MOV %d, %b" }, - { 0x0000000000007202ull, 0x00000f00ull, "MOV %d, %b" }, - { 0x0000000000007919ull, 0x00000000ull, "S2R %d, %S" }, - { 0x00000000ff007b82ull, 0x00000800ull, "LDC %d, %K" }, - { 0x00000000ff007b82ull, 0x00000a00ull, "LDC.64 %d, %K" }, - { 0x00000000ff0077acull, 0x08000800ull, "LDCU %D, %U" }, - { 0x00000000ff0077acull, 0x08000a00ull, "LDCU.64 %D, %U" }, - /* integer */ - { 0x0000000000007224ull, 0x078e0200ull, "IMAD %d, %a, %b, %c" }, - { 0x0000000000007c24ull, 0x0f8e0200ull, "IMAD %d, %a, %B, %c" }, - { 0x0000000000007825ull, 0x078e0000ull, "IMAD.WIDE.U32 %d, %a, %i, %c" }, - { 0x0000000000007227ull, 0x078e0000ull, "IMAD.HI.U32 %d, %a, %b, %c" }, - { 0x0000000000007210ull, 0x07ffe000ull, "IADD3 %d, PT, PT, %N%a, %M%b, %c" }, - { 0x0000000000007810ull, 0x07ffe000ull, "IADD3 %d, PT, PT, %N%a, %s, %c" }, - { 0x0000000000007212ull, 0x000e0000ull, "LOP3.LUT %d, %a, %b, %c, %l, %R" }, - { 0x0000000000007812ull, 0x000e0000ull, "LOP3.LUT %d, %a, %i, %c, %l, %R" }, - { 0x0000000000007819ull, 0x00011600ull, "SHF.R.U32.HI %d, %a, %i, %c" }, - { 0x0000000000007219ull, 0x00011600ull, "SHF.R.U32.HI %d, %a, %b, %c" }, - { 0x0000000000007219ull, 0x00000600ull, "SHF.L.U32 %d, %a, %b, %c" }, - { 0x0000000000007819ull, 0x00000600ull, "SHF.L.U32 %d, %a, %i, %c" }, - { 0x000000000000720cull, 0x00000070ull, "ISETP.%G%Z.AND %P, %Q, %a, %b, %R" }, - { 0x000000000000780cull, 0x00000070ull, "ISETP.%G%Z.AND %P, %Q, %a, %j, %R" }, - { 0x0000000000007c0cull, 0x08000070ull, "ISETP.%G%Z.AND %P, %Q, %a, %B, %R" }, - { 0x0000000000007207ull, 0x00000000ull, "SEL %d, %a, %b, %R" }, - { 0x0000000000007807ull, 0x00000000ull, "SEL %d, %a, %i, %R" }, - /* float */ - { 0x0000000000007221ull, 0x00000000ull, "FADD %d, %a, %b" }, - { 0x8000000000007221ull, 0x00000000ull, "FADD %d, %a, -%b" }, - { 0x0000000000007220ull, 0x00400000ull, "FMUL %d, %a, %b" }, - { 0x0000000000007223ull, 0x00000000ull, "FFMA %d, %a, %b, %c" }, - { 0x0000000000007209ull, 0x00000000ull, "FMNMX %d, %a, %b, %R" }, - { 0x000000000000720bull, 0x00000000ull, "FSETP.%g.AND %P, %Q, %a, %b, %R" }, - { 0x0000000000007245ull, 0x00201000ull, "I2FP.F32.U32 %d, %b" }, - { 0x0000000000007245ull, 0x00201400ull, "I2FP.F32.S32 %d, %b" }, - { 0x0000000000007305ull, 0x0020f000ull, "F2I.U32.TRUNC.NTZ %d, %b" }, - { 0x000000000000723eull, 0x0004807000ull, "F2FP.SATFINITE.E4M3.F32.PACK_AB_MERGE_C %d, %a, %b, %c" }, - { 0x000000000000723eull, 0x00000010ffull, "F2FP.BF16.F32.PACK_AB %d, %a, %b" }, - /* tensor cores */ - { 0x000000000000723cull, 0x00041800ull, "HMMA.16816.F32.BF16 %d, %a, %b, %c" }, - { 0x000000000000727aull, 0x00002c00ull, "QMMA.16832.F32.E4M3.E4M3 %d, %a, %b, %c" }, - { 0x0000000000007308ull, 0x00000800ull, "MUFU.EX2 %d, %b" }, - { 0x0000000000007308ull, 0x00001000ull, "MUFU.RCP %d, %b" }, - { 0x0000000000007308ull, 0x00001400ull, "MUFU.RSQ %d, %b" }, - /* memory */ - { 0x0000000000007981ull, 0x0c1e1100ull, "LDG.E%z %d, desc[%B][%a.64%o]" }, - { 0x0000000000007986ull, 0x0c101100ull, "STG.E%z desc[%C][%a.64%o], %b" }, - { 0x0000000000007984ull, 0x08000800ull, "LDS %d, [%a+%B]" }, - { 0x0000000000007988ull, 0x08000800ull, "STS [%a+%C], %b" }, - { 0x0000000000007984ull, 0x00000000ull, "LDS%z %d, [%a%o]" }, - { 0x0000000000007992ull, 0x0000b000ull, "MEMBAR.ALL.SYS" }, - { 0x0800000000007f89ull, 0x000e0000ull, "SHFL.DOWN PT, %d, %a, %h, %m" }, - { 0x0c00000000007f89ull, 0x000e0000ull, "SHFL.BFLY PT, %d, %a, %h, %m" }, - /* control */ - { 0x0000000000007918ull, 0x00000000ull, "NOP" }, - { 0x000000000000794dull, 0x03800000ull, "EXIT" }, - { 0x0000000000007947ull, 0x03800000ull, "BRA %T" }, - { 0x0000000000007945ull, 0x03800200ull, "BSSY.RECONVERGENT %y, %Y" }, - { 0x0000000000007941ull, 0x03800200ull, "BSYNC.RECONVERGENT %y" }, - { 0x0000000000007b1dull, 0x00010000ull, "BAR.SYNC.DEFER_BLOCKING 0x0" }, -}; - -/* IMAD with an immediate: nvdisasm names the special cases. Returns 0 for another instruction, 1 when printed, - * -1 for a shift by a power of two whose name nvdisasm was never seen to print (so it is reported, not guessed). */ -static int imad_imm(Out *w, uint64_t lo, uint64_t hi) { - if (bits(lo, 0, 12) != 0x824 || (hi & HI_MASK & ~0xffull) != 0x078e0200ull) return 0; - uint32_t imm = (uint32_t)bits(lo, 32, 32); - uint64_t c = bits(hi, 0, 8); - const char *name = "IMAD"; - if (imm == 0) name = "IMAD.MOV"; /* d = c */ - else if (imm == 1) name = c == 255 ? "IMAD.MOV" : "IMAD.IADD"; /* d = a, d = a + c */ - else if (c == 255 && (imm & (imm - 1)) == 0) { - /* a shift. Seen in the corpus: .SHL for 2^1..2^6, 2^9, 2^10, 2^12, 2^20; plain IMAD for 2^16 and 2^31 */ - int n = __builtin_ctz(imm); - if (n == 16 || n == 31) name = "IMAD"; - else if (n <= 6 || n == 9 || n == 10 || n == 12 || n == 20) name = "IMAD.SHL"; - else return -1; - } - put(w, "%s ", name); - reg(w, "R", bits(lo, 16, 8)); put(w, ", "); reg(w, "R", bits(lo, 24, 8)); put(w, ", "); - hex_s(w, (int32_t)imm); put(w, ", "); reg(w, "R", c); - return 1; -} - -int omega_sm121_disasm(uint64_t lo, uint64_t hi, uint64_t pc, char *out, size_t outn) { - if (!out || outn < 40) return -2; - Out w = { out, outn, 0, 1 }; - out[0] = 0; - uint64_t g = bits(lo, 12, 3); int gneg = (int)bits(lo, 15, 1); - if (!(g == 7 && !gneg)) { put(&w, "@"); pred(&w, g, gneg); put(&w, " "); } - const uint64_t lo_body = lo & ~mask(12, 4), hi_body = hi & HI_MASK; - size_t start = w.at; - int im = imad_imm(&w, lo_body, hi_body); - if (im > 0) return w.ok ? 0 : -2; - for (size_t i = 0; im == 0 && i < sizeof ROWS / sizeof ROWS[0]; i++) { - const Row *r = &ROWS[i]; - if ((lo_body & 0xfff) != (r->lov & 0xfff)) continue; - uint64_t lom, him; fields_mask(r->fmt, &lom, &him); - lom = ~(lom | mask(12, 4)); him = HI_MASK & ~him; - if ((lo_body & lom) != (r->lov & lom) || (hi_body & him) != (r->hiv & him)) continue; - w.at = start; render(&w, r->fmt, lo, hi, pc); - return w.ok ? 0 : -2; - } - w.at = 0; - put(&w, "?? 0x%016llx%016llx", (unsigned long long)hi, (unsigned long long)lo); - return w.ok ? -1 : -2; -} - -static uint64_t word_half(const uint8_t *w) { uint64_t v = 0; for (int i = 7; i >= 0; i--) v = v << 8 | w[i]; return v; } - -size_t omega_sm121_padding_start(const uint8_t *code, size_t len) { - size_t end = 0; - for (size_t at = 0; code && at + 16 <= len; at += 16) - if ((word_half(code + at) & 0xfff) == 0x94d) end = at + 16; /* EXIT, any guard */ - return end; -} - -int omega_sm121_listing(const uint8_t *code, size_t len, FILE *out) { - if (!code || !out || len % 16) return -1; - size_t pad = omega_sm121_padding_start(code, len); - int unknown = 0; - for (size_t at = 0; at < len; at += 16) { - char t[256]; - int rc = omega_sm121_disasm(word_half(code + at), word_half(code + at + 8), at, t, sizeof t); - if (rc == -2) return -1; - if (rc) unknown++; - fprintf(out, " /*%04llx*/ %s%s;\n", (unsigned long long)at, t, pad && at >= pad ? "" : " "); - } - return unknown; -} diff --git a/src/omega_sm121_disasm.h b/src/omega_sm121_disasm.h deleted file mode 100644 index aaf815d63..000000000 --- a/src/omega_sm121_disasm.h +++ /dev/null @@ -1,35 +0,0 @@ -/* omega_sm121_disasm.h -- Omega's own sm_121 (GB10) disassembler (C6 of docs/OMEGA.md). - * - * Turns one 128-bit instruction word into the text nvdisasm prints for it, so no NVIDIA tool is needed to read - * machine code back. It knows the instruction forms Omega's own builders emit (src/omega_blackwell_codegen*.c, - * src/omega_osc_gpu.c), each as an exact template: the fixed bits must match exactly and only the operand fields - * vary. A word that matches no template is printed as "?? " and reported, never guessed, so a comparison - * with nvdisasm fails on any form this file does not know. The control bits (stall, barriers, yield, reuse: - * bits 105..127) are not part of the text, as in nvdisasm's default listing. - * - * tools/sm121dis/sm121dis.c is the command line (a listing in nvdisasm's layout); tools/sm121dis/check.sh compares - * it with nvdisasm, the oracle, on every kernel the library builds (captured with OMEGA_KERNEL_DUMP_DIR). */ -#ifndef OMEGA_SM121_DISASM_H -#define OMEGA_SM121_DISASM_H - -#include -#include -#include - -/* Writes the text of the instruction (lo = bits 0..63, hi = bits 64..127) at byte address pc into out, without the - * trailing " ;". Returns 0 when the word matched a known form, -1 when it did not (out then holds "?? 0x"), - * -2 for a NULL or too small buffer. */ -int omega_sm121_disasm(uint64_t lo, uint64_t hi, uint64_t pc, char *out, size_t outn); - -/* Writes a listing of a whole kernel (len bytes, a whole number of 16-byte words) to out in nvdisasm's layout - * (one line per word: the address in a comment, then TEXT ;), the form the listing checks in tests/ read. Returns - * the number of words that matched no known form (printed "?? ..."), or -1 for a bad argument or a length that is - * not whole words. */ -int omega_sm121_listing(const uint8_t *code, size_t len, FILE *out); - -/* The byte offset where a kernel's padding starts: just after its last EXIT (0 when it has none). nvdisasm prints the - * words from there on (the branch to itself and the NOPs) as "TEXT;" with no space before the semicolon, and every - * word before as "TEXT ;" (so on every library kernel tools/sm121dis/check.sh compares). */ -size_t omega_sm121_padding_start(const uint8_t *code, size_t len); - -#endif /* OMEGA_SM121_DISASM_H */ diff --git a/tests/.crumb b/tests/.crumb index 78c828208..af908a8b8 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -110,206 +110,206 @@ "children": [ { "digest": "2c1deaaa1bae6257789749edde641df61413250fe91ce6aa61a99dfb3b271306", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "algebra", "purpose": "Directory tests/algebra. Purpose not yet described by a human." }, { "digest": "63f086b68bb9ffc032cbd74931309ab34df3c8c341b57935e5db43d8bf475800", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "ans", "purpose": "Tests 1-10 for ANS (docs/ans/INERTIAL_ALIGNMENT_SPEC_V1.md): freeze/digest, hostile reference mu" }, { "digest": "7b69a19958c5a5f55bba4fbc33bc6f26423358efd46311b0eacfe83bb665d4c1", - "last_commit": "450bbefd4", + "last_commit": "450bbefd", "name": "brownian", "purpose": "Directory tests/brownian. Purpose not yet described by a human." }, { "digest": "1cd97575b2b10d9313ca0df4997391612056754778bb2851bf052c146144f15e", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "canonicalization", "purpose": "Directory tests/canonicalization. Purpose not yet described by a human." }, { "digest": "088f526f8cae115209dd0162f28669812483ce5c926e41e8810dada1eefcb81a", - "last_commit": "450bbefd4", + "last_commit": "450bbefd", "name": "compiler", "purpose": "Directory tests/compiler. Purpose not yet described by a human." }, { "digest": "9e372cfc9747befacdcf31bc8643356aaff861e81ee6640b4866170be67b5e6c", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "constraints", "purpose": "Directory tests/constraints. Purpose not yet described by a human." }, { "digest": "87a3efa5cd0aefa7821046f9a31594bfa0a109e95005a1e12f40c99a1bc6cd3d", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "crumbline", "purpose": "Directory tests/crumbline. Purpose not yet described by a human." }, { "digest": "10aa3424eded7768fee0bae0eedd062b9deac3279d2e5721439fd024493bc42b", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "dual_experiment", "purpose": "Tests for the DUAL applicability experiment: determinism (same seed, byte-identical results dige" }, { "digest": "758dde696afa847d9347fad76b0c4935e968f8af4551f0f9810ec2a37ad9847a", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "effect", "purpose": "Directory tests/effect. Purpose not yet described by a human." }, { "digest": "23e559d13ff664995baca31dc157a8cf5a860615f3ecb07a9a40fe4626b57ae3", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "estimation", "purpose": "Directory tests/estimation. Purpose not yet described by a human." }, { "digest": "b7b6391caf653c76707a21f9969126abcbc730d1243259219225fdb9bc0084e0", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "fabric", "purpose": "Directory tests/fabric. Purpose not yet described by a human." }, { "digest": "defc52a44ea0f65ba5de3468de786148ba58d292ffa217fb95629a28a569a977", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "identity", "purpose": "Directory tests/identity. Purpose not yet described by a human." }, { "digest": "6ba43d622b712a4215767cab29425016f29cce4b28eb9e4961fc67fd20e9d765", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "language", "purpose": "Directory tests/language. Purpose not yet described by a human." }, { "digest": "54f43a3416595ff5d4e64bd12afe013359e706651c39c78e2896a5799638d263", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "malformed", "purpose": "Directory tests/malformed. Purpose not yet described by a human." }, { "digest": "a03a4dd9a72f7b449342e562f6d9df1a3348fb03fb640b662956caf163dcd7e9", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "numeric_native", "purpose": "Simulated M16 driver for numeric resource-lifecycle tests. No device execution or numeric parity" }, { "digest": "d958af5413726ddc48a47721800d9766939129f480b26492332ba094577837cb", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "osh", "purpose": "osh lexer host driver, vendored aien-protocols PR#16 draft vectors (5ae5292)" }, { "digest": "65e84051bb8dc00b180c6b06bec58103773785eebd6d6c69c9783de5fd0e2ba9", - "last_commit": "450bbefd4", + "last_commit": "450bbefd", "name": "path", "purpose": "Directory tests/path. Purpose not yet described by a human." }, { "digest": "51f14936b27d3d21379cf05ea1b6b532cf3175a40844dac85f023a61e7a0912c", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "physics0", "purpose": "PD-0 gates: world self-test, oracle calibration, learner L0/L1/NULL, mutations, OSC differential" }, { "digest": "c8524317c751fa8f464cabc31b760cef262abba822f1843482a02e239daa81b3", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "polyglot", "purpose": "Directory tests/polyglot. Purpose not yet described by a human." }, { "digest": "6569e2cd6dbf6f792edb5d83bf0715df9dece42ca7bd9b3a291535de0492d3aa", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "program", "purpose": "Directory tests/program. Purpose not yet described by a human." }, { "digest": "c549b5b82fd026d664b35e4b1a5d7fd2aaafa13b60b541cfbba87d7522517b1d", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "r16_inventory", "purpose": "Directory tests/r16_inventory. Purpose not yet described by a human." }, { "digest": "855bd23e4c526fb49eeb430c4ea5967d3f2f9da3a5b3aa3ec9dae5b814b11a21", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "r16_negative", "purpose": "Directory tests/r16_negative. Purpose not yet described by a human." }, { "digest": "f21be04969cbf51de17118c4f81b103f712db56fd517a1f12dd0d3ac4ff3afe4", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "r16_surface", "purpose": "Directory tests/r16_surface. Purpose not yet described by a human." }, { "digest": "b0ba3448394d5f27958c38b7233ae389e5e437e327f0859749a774fb252d6b02", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "realize", "purpose": "Directory tests/realize. Purpose not yet described by a human." }, { "digest": "157018d66de5bfd149015654cf0bda1346a9cfcefe5fd552c1d54859cd9ece81", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "relations", "purpose": "Directory tests/relations. Purpose not yet described by a human." }, { "digest": "e5f68362c083510e34c41f65de3ba2d553eac8a52fbc3e4cc1f69314eac9cc32", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "reservoir", "purpose": "Reservoir tests (omega#440): Gate 1 simulator and readout checks against an independent binary64" }, { "digest": "10d19641e4bb5b435ec6363d4ea7d3c1596af47d97b86f4de35d6ae57770241e", - "last_commit": "45f7d7691", + "last_commit": "45f7d769", "name": "runtime", "purpose": "Directory tests/runtime. Purpose not yet described by a human." }, { "digest": "467652c09505ecbd82d96a5e0e7ea24b19d9216cfd1dad7c60fa8258e47594c0", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "searchtrace", "purpose": "Directory tests/searchtrace. Purpose not yet described by a human." }, { "digest": "e69616ad471704066a86bf2796776301179eada5c0aa36a7166b9aca788619f4", - "last_commit": "ed8de5736", + "last_commit": "ed8de573", "name": "synapse", "purpose": "J1 parity driver for syn_codec.osc against the sealed Rust A1 corpus (aien-dev/synapse j1-codec-" }, { "digest": "5c97916fbf20310eff2e502c526337cb093e912cb48f18d44b0345ed8a3c3240", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "train", "purpose": "Directory tests/train. Purpose not yet described by a human." }, { "digest": "7679bd1c49c7e89d8c26ccf8dfb91478f4e6e2f584745806fa8d26061dbdbb9c", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "turing", "purpose": "Directory tests/turing. Purpose not yet described by a human." }, { "digest": "930fcb9ce348c604424e5380796a77c3586a835b43d42b504325c36b12d166d7", - "last_commit": "450bbefd4", + "last_commit": "450bbefd", "name": "visor", "purpose": "Directory tests/visor. Purpose not yet described by a human." } ], "children_root": "sha256:0c57282ff8cf1d34e5685e2729755f2978917e66debb5423961033be9d25c902", - "compiled_at": "2026-10-28T09:49:40Z", + "compiled_at": "2026-10-28T20:28:56Z", "compiler": "crumb-compile/1", - "digest": "sha256:4f54ac0e02337bf2bd58142881e60cb25241457eb40b659235360a4eadebfb82", + "digest": "sha256:f8324a406c96486b9fc156b0cbd9fab2ad57bdcf33eda1614d97ec9585fb70a0", "evidence_files": 16, "evidence_root": "sha256:96d08097822ad95f4e562c19e0ba5df5a035774c48632f1832912c40a27bd27a", - "files": 1299, - "generated_at_commit": "56dfcbd9b284a88618983e3eac7512630ad70b3e", - "source_tree": "sha256:d962bc7e9701791bad887c4647b3af7a197a7f28484155467134aeebcf5f36a6" + "files": 1301, + "generated_at_commit": "3d254d95c382bf4127d1265cd1ed369fbfb54172", + "source_tree": "sha256:665a657dddbcd5957225c07c1c7320db161973153f284074451e8246f3ddcdd7" }, "owner_lane": "", "provenance": { diff --git a/tests/chip_run_transc_receipt_allowlist.txt b/tests/chip_run_transc_receipt_allowlist.txt index 50a8d227c..2f06fc956 100644 --- a/tests/chip_run_transc_receipt_allowlist.txt +++ b/tests/chip_run_transc_receipt_allowlist.txt @@ -3,5 +3,6 @@ # One entry per line: "+key reason" (new receipt has a key the old one lacked) or # "-key reason" (old key missing from the new receipt). Blank lines and # lines are ignored. # tests/test_chip_run_transc_manifest.sh fails on a difference that is not listed here AND on a -# listed entry that is not a real difference. The manifest rebuilds the old object in the old -# key order, so the list is empty on purpose: no receipt field was added, removed or renamed. +# listed entry that is not a real difference. The old object keeps its old key +# order; its sole intentional extension authenticates source, not qualification. ++canonical_source authenticated staged CUDApp closure from the seeded .om verifier diff --git a/tests/cudapp_retirement_sources.json b/tests/cudapp_retirement_sources.json new file mode 100644 index 000000000..f316a1dfe --- /dev/null +++ b/tests/cudapp_retirement_sources.json @@ -0,0 +1,1141 @@ +{ + "schema": "AIEN_CANONICAL_GPU_RETIREMENT_V1", + "old_omega_commit": "841001e42fdc87b9d627334add9288f8748a578d", + "old_omega_baseline": "e5b32567a7aff3ce594e3254a622a846a6cd190b", + "canonical_cudapp_commit": "7a354dbda9eddd405610fdcabf4fc4e24c1a0f47", + "preserved_archive": "native-omega-retired-source-841001e4.tar", + "preserved_archive_sha256": "a0880e63de42c8f4cf4f9ff9b833657b74dd24c3a460b29b62f3e8d32d2bff06", + "retained_unique_adapters": [ + "src/omega_blackwell_gates.c", + "src/omega_blackwell_gates.h", + "src/runtime/rx_resident_gpu.c", + "src/runtime/rx_resident_gpu.h" + ], + "cpu_ownership": "Omega CPU objects and generated Omega SHA are the deliberate embedded owners; canonical CUDApp GPU archive is linked last. Source equality alone is not behavioral or hardware qualification.", + "open_618_conflict": { + "url": "https://github.com/aien-dev/omega-mv/pull/618", + "head": "67c70741c8cec5c33e28a099d7c83bbd4f3ab839", + "branch": "opencuda/consume", + "observed_state": "OPEN", + "observed_merge_state": "DIRTY", + "overlapping_retired_paths": 92, + "shared_consumer_paths": [ + "Makefile", + "README.md", + "cudapp.lock", + "mk/omega-gpu-code-alloc.mk", + "mk/omega-gpu-engine.mk", + "mk/omega-gpu-wait.mk" + ], + "disposition": "Preserve the unmerged branch and its evidence. Do not stack the older consumer cutover onto this one: reconcile the source pin, 92 overlapping retirements and shared Make ownership explicitly. This entry records a source conflict, not a merge or qualification verdict." + }, + "files": [ + { + "path": "src/omega_blackwell_codegen.c", + "old_git_blob": "debdea0eacfc7c5aed717ea52a7137b7e3902b33", + "canonical_git_blob": "a740e29f2dc7b0cc4b0c140c664ba17ba2fe7f55", + "old_sha256": "0ebca24132e48a42581c6da66b3ca44ae249ca146bbfbd2db89e818a1519fb17", + "canonical_sha256": "5fad4042ea39e498a634dd34a6b833106430c934907a59bdfc8d5ddb074263b6", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen.h", + "old_git_blob": "30ff3898369d226b6b68c0af2c0d435b4dc1db2c", + "canonical_git_blob": "9dd4f62116ed66ff12c60c06e9070f5aa8ead679", + "old_sha256": "f468199786d72fddcbe1dbf83a0edda8ebcbf9eb61feef81d4b98f6dbd09ecb8", + "canonical_sha256": "4d7e077e9e5b9682fe8fa14c0ea115eb8a4b6670fe2b8082b21c58b7d9ee4146", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_attn.c", + "old_git_blob": "060e25cff987ff43fdb234aee39497253cf25c3a", + "canonical_git_blob": "526b262037fcf69da362d61c3a1b3c8495b39c82", + "old_sha256": "cb0a6bbecb84583df797e308f1fd97900c4d9df51a91d0c597f8f1be53dbb05b", + "canonical_sha256": "700c3eb0fd51cb4c74f92a74f14e34f7646b8d5a6a06cc4a4b3f0c907d008235", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_attn.h", + "old_git_blob": "4f84bba33c4cf4dfca8834335b6900aba01b677b", + "canonical_git_blob": "1a39eec1cb9d461fff919814f655002b22e74967", + "old_sha256": "a9361efe1f40e4deab0036a2631d831c221254d138bf7c88843d72d424a12dc4", + "canonical_sha256": "8a2a9fc3c4b48895831951b5b07ac735ec42663e5c3711d869b9aafe38eaec81", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_attn256.c", + "old_git_blob": "ecb4c1dae47bfa0b7d25f90468b17de79247c040", + "canonical_git_blob": "ecb4c1dae47bfa0b7d25f90468b17de79247c040", + "old_sha256": "338d11202ce8f1b9f50689eeef6caedfac42565eb26a010f4180154ef25b0464", + "canonical_sha256": "338d11202ce8f1b9f50689eeef6caedfac42565eb26a010f4180154ef25b0464", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_blackwell_codegen_attn256.h", + "old_git_blob": "cf72ac548b54748165732bc781296b069b2ce073", + "canonical_git_blob": "cf72ac548b54748165732bc781296b069b2ce073", + "old_sha256": "ff9b219d753179e59023b2445304f9b0e30947e47345d0dc6e5cdc68f572a81d", + "canonical_sha256": "ff9b219d753179e59023b2445304f9b0e30947e47345d0dc6e5cdc68f572a81d", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_blackwell_codegen_bf16.c", + "old_git_blob": "4a02b058fb8a94417cffa4263b40b65cd96d2ad6", + "canonical_git_blob": "0a17718e370080cf71990ac3ebe40f02edafbd2b", + "old_sha256": "201c3634ac1f4b47d0f1925db0ef7c797464d600d548b8a54373c35841e8fd50", + "canonical_sha256": "e7aa00034d08d4de5de1062bd36579162042872dbab0d390dc58d6c8c356571e", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_bf16.h", + "old_git_blob": "d3153eaa2dd8fffa4f47c877b7afec90243f0c9b", + "canonical_git_blob": "0593eb00485e30489d94c19e22fcb1b80ad842b5", + "old_sha256": "37e0d9297fccbec9994ec2d7cf4a9477e808994a27e454b327bf4259c1654128", + "canonical_sha256": "b49e9afc7d479fad76fa0cb34d25bbaad50a07855bfaf8f5318908c11d1dae8e", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_dec.c", + "old_git_blob": "ce13b27c46c24e80592474c8179932b0c03897e2", + "canonical_git_blob": "8ad70f50c0e2ad48b43d6808a978526f2efbc921", + "old_sha256": "6d90b90296d4357d0bfc703fd51a727b0d9d4eeb97cc901038f625023e3c8d64", + "canonical_sha256": "02c52d69865f4e1ca5c517f983906e3bcd733bd838b0b23f3cfbc44f1f9024ed", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_dec.h", + "old_git_blob": "3a1129484435d8bb168ee2d234553972f7a61105", + "canonical_git_blob": "70744b18560ee4da7770df8643ef3392061643dd", + "old_sha256": "f6bbb342f2a60f8e7ff0b14d852db02066937e480453135c24eeec1517a6a979", + "canonical_sha256": "459dc57b09f5235bf628ba699641ca5e5d7a6196f012d7aedbf61c0f2793b2ef", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_gdn.c", + "old_git_blob": "429c611c45880e5adabaea5f1d189713e70251ba", + "canonical_git_blob": "429c611c45880e5adabaea5f1d189713e70251ba", + "old_sha256": "f32c91d4efe94653b211750d8923c1cca41e74e95266049142d7ca2b7f68f901", + "canonical_sha256": "f32c91d4efe94653b211750d8923c1cca41e74e95266049142d7ca2b7f68f901", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_blackwell_codegen_gdn.h", + "old_git_blob": "edfcce876a5b4556e241a9a2e2539558bd521942", + "canonical_git_blob": "edfcce876a5b4556e241a9a2e2539558bd521942", + "old_sha256": "66e921c0951812181f6cf0e5c6daf5a842463bf0d0a08c19291efca30c75c3f3", + "canonical_sha256": "66e921c0951812181f6cf0e5c6daf5a842463bf0d0a08c19291efca30c75c3f3", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_blackwell_codegen_gemm.c", + "old_git_blob": "d8bbfb87767081c4f9619fd75c20632a52dddd38", + "canonical_git_blob": "10bf71b40b3bf0bbb6f603535d88d95c9b81b4ab", + "old_sha256": "f0fa664526967bb59ebdf10355dd0d9c277ca28ca77bbf72051313d71d2991a6", + "canonical_sha256": "3bea15f1790dcb26be81cd98c40e52b6059256bb3c15c57b8726708a70d59921", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_gemm.h", + "old_git_blob": "b3e45726f764b0c7e56bc8f79c1ebf3d7f2d421b", + "canonical_git_blob": "74abbcfa6dd92a3d3a75bb6e2e037cea48b12623", + "old_sha256": "e96bd303e09c4ab5f968e41d53a8f8f772361b721b64cb375fce782f18389623", + "canonical_sha256": "3c432983706481b675fe6d2c4cc3950397538a7d46a43cabd70eb58c811448a7", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_moe.c", + "old_git_blob": "36300b59da5582abe70bc02eafd75e8be42f1c38", + "canonical_git_blob": "406287e94623b2e16468aa50aa36618e0b864702", + "old_sha256": "4968214e3da4b8b73d5d8110e1ea62be57d2b7c4a547afc2179940b5ea0ade2a", + "canonical_sha256": "5db114eebcbb02ef0a4c016d7f94757f076b403d72a8ee0400d72d5e956af85d", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_moe.h", + "old_git_blob": "dd915865d1fd5a05210a839c438033bada20fccc", + "canonical_git_blob": "f2cbf3a933eedce323578cf04b71ab2a4d0101c5", + "old_sha256": "7e3c17790a5023055d585c793ca536b95730fb05c5ea4b31e0e025ffaa93105a", + "canonical_sha256": "9d5bc8a7f015347a6776bf2218e0215b80e22cc9efc91248ff60d59f1b2f2ac4", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_moe2.c", + "old_git_blob": "eee933b5fb6a882dbdf8ad1a1c9a29d1360ad1a7", + "canonical_git_blob": "1b4489503af9dea02f814cb1257e326432f6c2c1", + "old_sha256": "8f7b5cbbf72283e91f293ced5303867a7048620625d56f6ce6579148a9ea58f9", + "canonical_sha256": "8032e43778c11da167697be3f20cd408fc8a37ee3b6863c894623c83292f5f19", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_moe2.h", + "old_git_blob": "fc8533a34d7a016e06331d8f4d2785c8c21b5dd1", + "canonical_git_blob": "7e556b6eba1dc1ac0b3300387e1fdc691f4bb431", + "old_sha256": "c29c96ec4fbcdff9efa3ea8b9491b343b9531b63cfb9cbedd15202e4bf1ba608", + "canonical_sha256": "bf9c430f69a0d98deb5f5e0aad8ab14a940e188d1e67fc10036d22d4e2b3c10b", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_pattn.c", + "old_git_blob": "83dee6b001df1a0c71984d7541e0fa260cb3de2a", + "canonical_git_blob": "30990e4b5b82d439b0ca33f5410076c5a225cf03", + "old_sha256": "dfa595e162a2be096c116384b5d9752006c8d1affff5eee32f5c653e1110418a", + "canonical_sha256": "39cc964e81823c7386d959b2f6180ea65db5f515073039ad27d9b3137dc5e1cf", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_pattn.h", + "old_git_blob": "b7f8ff1a27031a7470e6467c0b387c3bec9920df", + "canonical_git_blob": "98e6542d503cb449809c1727e7c70f38c56c7375", + "old_sha256": "681615a9c1d2febc7cebc3cdf578b6b4ae46db64a630a563297f082dd4c316d1", + "canonical_sha256": "14f5d5bd1c635c224b1a488d389bbdab1b55bc7a6530e3ea1e007ac587cd9f26", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_pattn256.c", + "old_git_blob": "572f15f3309bbf311fb8b853c07c7a6f3aeca1e6", + "canonical_git_blob": "572f15f3309bbf311fb8b853c07c7a6f3aeca1e6", + "old_sha256": "75659ad5270889ef02e177a46cf44fc0b2d99dbe9d0d8e19f55510da8a789d23", + "canonical_sha256": "75659ad5270889ef02e177a46cf44fc0b2d99dbe9d0d8e19f55510da8a789d23", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_blackwell_codegen_pattn256.h", + "old_git_blob": "c910401b6a548e7bf838fdb81eabac9e13a7f557", + "canonical_git_blob": "c910401b6a548e7bf838fdb81eabac9e13a7f557", + "old_sha256": "588c6dee94025eb04efe87f02e884171a70b32ab1a5f320087e038868b24039c", + "canonical_sha256": "588c6dee94025eb04efe87f02e884171a70b32ab1a5f320087e038868b24039c", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_blackwell_codegen_pf.c", + "old_git_blob": "25e0f54ff096d731b56b8b6b0913a02d9f1e7549", + "canonical_git_blob": "34f7d985f2b8befebf3025fce11384f6f8afed70", + "old_sha256": "b76e7cf9a6cb687db9632a2f85b92eddd5110747b56ae5a43605ddec507badcb", + "canonical_sha256": "89c122edcedaf3711826bcf67205f44c92405ab9b7e06609f2e8e46497e20c4a", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_pf.h", + "old_git_blob": "f4a126d3ee888b49ed664d380c810b7fab866b37", + "canonical_git_blob": "747ecca38c8a081b7306faba7dc9da81a6baff9e", + "old_sha256": "3a4831077693b1b8c0e303a24529cacbd1d52ab0f233ebd00a20610edd0d3658", + "canonical_sha256": "c795f550a8302cb19a0fa86474477732b6b0a5e9ae38d30f87d94fac901a243d", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_pfhost.c", + "old_git_blob": "50883404e9c384e502034170aaf7587da7e34c46", + "canonical_git_blob": "f1df3803bd6142bb54947001bfc9f34b2f7bfac7", + "old_sha256": "a218f68ead6f3db4f7622197ac22048a99b8766e2983c04c21d025b0c2f7669b", + "canonical_sha256": "3414042eea14ce59d059119c2a5db8b762d20bef255eb054f0d61f2f7016591b", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_pfhost.h", + "old_git_blob": "02bcef48636dda77518c270527a161d022a4a564", + "canonical_git_blob": "c5e4b81ce0fa58ff7faf34899fd0ea4ff46b65de", + "old_sha256": "e5875e1c2b23a8c6c7ce06479c12b7c0b410cd53a228fcfc1f466f2d008ffce6", + "canonical_sha256": "0be2291a509fbfae8be866c1fec1c4382a35aa066968628f8efacdc8014cf3a5", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_qg.c", + "old_git_blob": "c35bd4758e3a5444dea2342f3cc08df65705bce3", + "canonical_git_blob": "a2764c5f1e9f8c29388388df3aecb872d1b33cb9", + "old_sha256": "7bc72a54fba08bb242f9de21554310fe2409907baaf46463478cb97bafa1f154", + "canonical_sha256": "937acbf8a24c0cc86623cd6a6cc918d8009ed98f6ed5b358b856a19127aeb80c", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_qg.h", + "old_git_blob": "872eabf96c0a4464a66f7d1be9ef67a3ef6f762f", + "canonical_git_blob": "552028312d3c28efce0ffe6e1bd247c0ae1348e4", + "old_sha256": "e9bc20dba5e101f4a61ad96e546f8c9c705c0305bef025426b876d96f3fbb27e", + "canonical_sha256": "a538634681a2cd7fceb4573ff16eda674b76c28c035b47bc848c5c339817e319", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_qmma.c", + "old_git_blob": "388c162f7a8bb9282d27c0271f96281f338c1aeb", + "canonical_git_blob": "eba9513d7761acab9e14e184d4452837bcd63882", + "old_sha256": "277e2466aec2fd840f51ac927c5c0a7f3ad0ae9641e3d96a1f96fefe682508bd", + "canonical_sha256": "8be9d5cbb1e9e55529655b2c7ca8ae72eee4d3afa8006a24479bf2201f87caf4", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_qmma.h", + "old_git_blob": "757bc0bc86c4e48de389b665709d4f4d04507489", + "canonical_git_blob": "2909901735d526372c76bdfb1ad0641b1b6ff150", + "old_sha256": "e9012a075c32c3f878d17328340ce57f3be49a7c5f7e6867aae72a5575c5aedf", + "canonical_sha256": "232fbc9d8b3f9d3ea7677f533c42b01b4eb95d9fec66c6cd7699617131d1167b", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_router.c", + "old_git_blob": "0fab8c4eb8b95b1b703e3aad5d751827bca1eefb", + "canonical_git_blob": "643e5cf974d43fc3f3f4458582a5a89bd076b8fd", + "old_sha256": "81926585f0db7ac3041acbf0cea3518252b71996d88d36f084088d45c9009940", + "canonical_sha256": "4a29d76c2ab61629e8292c1d6c623ca22d93ab27b34eed78926964bf7e397a3f", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_router.h", + "old_git_blob": "a149b630f7fb68a742c8501038613c03547e6989", + "canonical_git_blob": "97ebb791bc8bb239ae44aa483cdbd42970295b52", + "old_sha256": "af7787a0e97d206b71e67eb0ed2dbe340adef1510946fb6c4b2e8d7664b6f932", + "canonical_sha256": "8d10ac620fe8e6ecf57bc8eeab0b09354fc9fc19d10f061c32646dc13842f6f0", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_tc.c", + "old_git_blob": "6a882d7e197ebfcf428d173e2d8ee3986090a748", + "canonical_git_blob": "02550672197e8b92d3e30aec0e27faa5e4a20d0a", + "old_sha256": "e88178b5075dafeae2668fc45e587fd725f4f37fa14488762e9f05fdbb55eeb1", + "canonical_sha256": "3df8bb1424275b8a36331668edd6b82ca75d671b948612aecccd3b06c0c08ee6", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_tc.h", + "old_git_blob": "a27f71f81774f9ee0e9be521ac57b1e935083f71", + "canonical_git_blob": "fd98a983c277643f2ab4057c5c9d6a29981b63e5", + "old_sha256": "3d131b9a0501972a0bd7f97ab018a9a4039b44418d5c0082d40a052af780e698", + "canonical_sha256": "8b7be87a4456956c99c0f5292aa677fa14c7244bfc9ad2a271d9fb8207611d0b", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_tc2.c", + "old_git_blob": "4feb021fb579af433ac37d0fc37e060a96ac0533", + "canonical_git_blob": "6a1c52e38028204e90f10f048fc02d36f276c297", + "old_sha256": "58cdb5d79f4996fcfe6b53d3567f73e45364f335ccf3c00f1f93a9bb9913b5e4", + "canonical_sha256": "184897f05729b83478cffc0dee21425323ce8bfcb2ebaea30471588be3b88610", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_tc2.h", + "old_git_blob": "38d17fdd1667afe82ced90d4702b44445fba5058", + "canonical_git_blob": "538155c709f5ab2d0f4bd6bf9a971d2e44b09c8c", + "old_sha256": "c04126a6b77fbc27310f4efa13bf73108d2262e1b895587b3d0820c0fa4323de", + "canonical_sha256": "66e17a9ce0d08ea1e5fca5e6067ccd26f4f4c59303307e16e55236ccb24a4377", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_tern.c", + "old_git_blob": "6177d45ad13dc53cdb8cb4b3f7a133240ef3c3c6", + "canonical_git_blob": "6915cd2535ead80caf036188601cd0806c7b5be6", + "old_sha256": "1f7c31370ea67327b3cb800004ab951e3a277e29a86d807877a9d1a9d274fe8a", + "canonical_sha256": "a7230815042ef8412887016f350f55405bc209aa5377c4b5cc2dd7fdafabb059", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_tern.h", + "old_git_blob": "a9a7472cc5606fc285c330231c2a54a9f6e82490", + "canonical_git_blob": "5c7520779cd5113e4289da414e4329722f705181", + "old_sha256": "69e71b849995fea0362efe15b889b6d333e7f4989ba4dd2c55da6448199465b4", + "canonical_sha256": "3c9bd1c59ee5ca9aa2a7a7241c0c5b891be8f1a7fb85dd2df0d8d0f40bf63b25", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_encoder.c", + "old_git_blob": "373a98cdac7c8bdbf3921579f013eac4cafe6647", + "canonical_git_blob": "24ae548632068369f87fbd9fe65839ee42bdc4ee", + "old_sha256": "ff8835615ad6d54252e259b7e5c89c57abb010f04b3f480abca3be588d32cfc5", + "canonical_sha256": "fc24b1790c662924b5893d3c27d8acaa18085113be879cfbe708ca55b9881245", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_encoder.h", + "old_git_blob": "9050a2f03dcf7b072775d1182cc558b8d8e5b623", + "canonical_git_blob": "260c1b0857a87cc35e71be2c1a6dcccce20bcde0", + "old_sha256": "42d5b497a8025ac7a13c75df6153d33c75a914ff67a41b7cf7636aafd704784b", + "canonical_sha256": "7f7457fda076d401b863a6cfd31893f207533b07f6e1948bebb7bb2324fb3550", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_engine.c", + "old_git_blob": "8923ab0ea1cac03f08155c75251e108c7b9e1f0c", + "canonical_git_blob": "bc053f133613d3dd22930f9eb461a426f397e3d3", + "old_sha256": "72dfe81703830f6096c4012de05519764fe2d4e1d5a307826f0108ff43bcab03", + "canonical_sha256": "5450e23625a7b2de16f837231184fcd1cb641bf649580878da8b10ee13108bb7", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_engine.h", + "old_git_blob": "31948b06a78e3070af045ad905679908b1813778", + "canonical_git_blob": "f807ea72db1a56a31a52b90145d4cac72e9b49bd", + "old_sha256": "fbfddf59aaaf524d5ee72cca026b027431b4dcb3e14ba21c1f5ba7e831e37264", + "canonical_sha256": "07ce6ebd5e20bf72c8d31d5da5794a58380fcae8e1b3ff8b039c8c62b8c388f2", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_matmul.c", + "old_git_blob": "28805cfe482265828c6ca6b7b1b583f60852df71", + "canonical_git_blob": "e0375f14fa6815b881e39eda2031e26ed361914a", + "old_sha256": "fafbc42777d5013c7a0a25e8541108503708a528f90759b9e8ad4c57d37a8cd7", + "canonical_sha256": "457cafc15d3d040091e64830b1856367a3150d061dd450f15939d1c4462bde69", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_matmul.h", + "old_git_blob": "2b612e6798ba47a57768e7c02342015455ab17e2", + "canonical_git_blob": "6802d76940524c28f7d80b2e3878e22cf1a22351", + "old_sha256": "5ab157c30f303b259d7fd330df2ce8d3d355d52d45ebb403f086ea463b172986", + "canonical_sha256": "2243909d707c205f60011b10e2bbfe698d6c6071a518fae4e4b7981058cf1f6b", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_qmd.c", + "old_git_blob": "efcab9eee15987002d22a03c52a412d4957fd9d3", + "canonical_git_blob": "dd13ec5a2c0d712627240afa8b1151e45643cd06", + "old_sha256": "66f29b0b6fdb6d7675fd51c9212709cd6f1d80de275c303dd910899d26d58340", + "canonical_sha256": "fe6cd2cf1ea06452fa30beed569fba04f732ac005b5fecf205adf65ee0b08eb1", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_qmd.h", + "old_git_blob": "ab4ac3616d7fbccfe33ea3713ac33cddc3d79cc1", + "canonical_git_blob": "1d56f1a9198ee0e7f8d18f2712207b7a6c37b21a", + "old_sha256": "d93c47537d36540f361d34a0394ff1de2d979a9e73a6dba9da922c31367caf9d", + "canonical_sha256": "9256fcf79e72235c8a457e571d3b47488b2afd5ed82397eeb3400bf856d8307c", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_realize.c", + "old_git_blob": "ab63ddb27a1f9aed0ff740aa7a4722efd61f26fc", + "canonical_git_blob": "aec77f89fc9525da8d02d9426667e7e6d9c064e5", + "old_sha256": "17f4c95bc7ef942a510fabe5e246426ca532e1c817c6e6c54ba1cbaf2042a000", + "canonical_sha256": "f478a1713ad8eb027c895305e4c3cd326d779cf191a099689e6fd94d4f64e76f", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_realize.h", + "old_git_blob": "5e7d27f8085ab43bd00b828d7e5b76e33c22cf61", + "canonical_git_blob": "bab54b5e1951fdb6e146e8008a9843e83aa22a77", + "old_sha256": "88f55d91a20f766a5babbb5e259c510e411e3ffe03682839d3b0e01c9c1f97fd", + "canonical_sha256": "1866a37e58df2ab3a76797f9329e3aa16cae3ad4519a5387768295424388ea44", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_submit.c", + "old_git_blob": "5efba9c2ec7bd697487462361d851ce99777f5e6", + "canonical_git_blob": "8ec564e33b4761d3cb3217cf9cc630ee83d6361e", + "old_sha256": "514f547b70dda2c0cc78e648850c3ea1992687fb8019b1759814366a65436047", + "canonical_sha256": "436f2603379c72282b4e2626bd4a0c616d394fcebf216f690f10bfeab90d9cdb", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_submit.h", + "old_git_blob": "41b36dcc36c576d3159b27e4d627a149a24d4ae3", + "canonical_git_blob": "b7387119c89906bd69f6c254c2c8f325bb6453c4", + "old_sha256": "b3a8deeb689718c32c972bb9422ca0b8181c88443a60296d79cdcf065ce90e23", + "canonical_sha256": "b3ff0079d31bb71fd32a7aafed18a0ee357e2f9da4ee3be55ae7dd63121e985f", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_bw_em.h", + "old_git_blob": "fd61cdd84e5d26fd72ee9a4c1d7d7ecccf61d297", + "canonical_git_blob": "6b06c7e30b994ce1bd04b2ed0af5bcd17a4ee7ac", + "old_sha256": "e722a2e935e88c1eb99b29b06e40e9a4e9144867355c152fbdbec69cf7602011", + "canonical_sha256": "f299f993f0308bf2d14c10f3ed3f1d0c639fec7771fd5841329669b0effd281e", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_bw_em_q.h", + "old_git_blob": "13c2803a1867df08fd9628fd98cab4059b999fa6", + "canonical_git_blob": "8f69867d97b410205941f6445f602727a9e70082", + "old_sha256": "22a9d8c2656409e614d1549906d00de237fef519c9ab706e28362a1b193b8b1c", + "canonical_sha256": "c976bd6cf799360eb817cbec8fd536d2e83c0b8be70d74e9432c89cbcd1ac234", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_bw_reconv.h", + "old_git_blob": "a10e07a371acdadcad8bdeb8bc498fcd3e43f1c5", + "canonical_git_blob": "4bd47bf24e15ef94c9f18adab8c054c30365b68f", + "old_sha256": "336f37a2783cee596e7ca26fce71ef4462e65f89ff97fe11ab5160c4d5b3f5cc", + "canonical_sha256": "61431ee06fee8a0978dfa1924a148881baedf0047484828ba2a5856a6768d736", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_attention_api.c", + "old_git_blob": "2170d07a3b83edb55861ca008c81150b9019a8f1", + "canonical_git_blob": "7f048ada25f904a423f36783ee95b7e310409908", + "old_sha256": "369a334ff2908e75e00f74c3ef0f62314d046a8bdb99b6aa6b12e1bf416cadd2", + "canonical_sha256": "322bb5782451338d88f309f2f489fb37d1d0f482076b17fbfaa0d8c1950e6e82", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_attention_api.h", + "old_git_blob": "3610af04755909465aa4e854f9af257aae9f13f1", + "canonical_git_blob": "0e0e650081d91769f2f8ab7940fb0ab3b1ace07c", + "old_sha256": "f9be0e256e10e0664bc0602e862b544041a658248bd7200b463753fde81b396a", + "canonical_sha256": "40291d706e13639d21c1609a63f23a72e9e585690c285c7962d709d861d1bae1", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_bf16_gemv_api.c", + "old_git_blob": "b20e4315e66b84bac702791e7f96c08354e66441", + "canonical_git_blob": "eaece6ae47c73e1ad52172869e71d12f7d673e24", + "old_sha256": "27f2944c5dfc491806c2438061c06af4a1327676ef049526a6fbb6a74ee7e13e", + "canonical_sha256": "13b61a5f43e6dacc1daaa7ff6e084dd08774a88d781d41ec33d1e4147c14e0e6", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_bf16_gemv_api.h", + "old_git_blob": "6852013752b84f7a605d1d2defe980f13554112c", + "canonical_git_blob": "a51e703a9b6ed5a9b0e32ce3f34d4033e3a690ef", + "old_sha256": "c5475f5bddc874e022edfd2435cd4e33955e5e0820ec89e3bdfa65871265133e", + "canonical_sha256": "ac979800a90e3bd02a63f11c0f2d4cae5011a14e6417420a552fc681a08d3826", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_cmdlist.c", + "old_git_blob": "809243d345e4347637c21f47983fb6156b05ff08", + "canonical_git_blob": "bc5caf51b4143c6b108ee2cfdc4362f7b9f5522c", + "old_sha256": "8eace7c1e3c37c30e832b0efbd2ce62d68a49a0d6f5214445e3801a5ba3e225f", + "canonical_sha256": "649ec9ed604da17d30a2b51183300e97276436e1d41a6089032a110f1e3b18e7", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_cmdlist.h", + "old_git_blob": "889bdd1e48e2c5354ed90a57d33e2204ab146aea", + "canonical_git_blob": "d81694ac27968ec9f2cdc9530e9cf7652e9179c4", + "old_sha256": "07e46ded947baf9a6b50bb7cffc0830f8deb3e5a0303d0edb0a9d699dfa594bd", + "canonical_sha256": "7ff797b261a3e2314cf1fb2c81c2ad6c37567052f267fce514c181aebc6a7901", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_code_alloc.h", + "old_git_blob": "3628a88fac33627e4b95dea7759ffa8aba7d1cda", + "canonical_git_blob": "8632295fe9ea4a9a12cdb226bcea0391103c8203", + "old_sha256": "e4e5e950cc1b1d206ac2c6a3bcf7d78ed3ce61317f4c0524739e42ef75a29e34", + "canonical_sha256": "be1085c11198f0f5ff314dcafbd6b1a57041b69d3a56c0ae2f7b319386c5b0b6", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_decode_attn256_api.c", + "old_git_blob": "77fc4ba1fd9df0939a57df3aa669e18fd9be2785", + "canonical_git_blob": "77fc4ba1fd9df0939a57df3aa669e18fd9be2785", + "old_sha256": "8f4e8cbd19b5e9f5ae4e6ea0b51021e99095c9e27516ab5e0274b6593a8a6367", + "canonical_sha256": "8f4e8cbd19b5e9f5ae4e6ea0b51021e99095c9e27516ab5e0274b6593a8a6367", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_decode_attn256_api.h", + "old_git_blob": "d0212c2cbac34dcd69b8e50b298a94c715039a7f", + "canonical_git_blob": "d0212c2cbac34dcd69b8e50b298a94c715039a7f", + "old_sha256": "8982e000ee58423f7883dee59b80f7ee89ca9d0c5e04b93523a1b1e332b04d35", + "canonical_sha256": "8982e000ee58423f7883dee59b80f7ee89ca9d0c5e04b93523a1b1e332b04d35", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_decode_attn_api.c", + "old_git_blob": "ac6542487249e5571684e00dc115d4e00c1462a1", + "canonical_git_blob": "7d11bf9588938daf72496dd15ac99a6e103db4c8", + "old_sha256": "104f7df58bb280b9a6978330a8e5bc35494780e07b0dc4b02cfc4ae2139e9393", + "canonical_sha256": "2b2a04f13280657baa83eea7026d716034451113a4ee87300e81ec68951b70e9", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_decode_attn_api.h", + "old_git_blob": "ba84b0439b8832678dbdddc026d58bcc780d4b02", + "canonical_git_blob": "94a510075d1dee3d3012b9ef6f7d138dd573c806", + "old_sha256": "7d1d236ff8e022d8af10cecb19d50ca3e1dff9cd2b1fb24a67dd1f74ac4560c3", + "canonical_sha256": "6e33a6f547b77b794b7a169cfdbffcc99440c67cfe89458a70b46ce0975565e6", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_decode_graph.c", + "old_git_blob": "bba75356453992af2a18622c3b7db084f4136acd", + "canonical_git_blob": "09db68408fbfc1aa7caaf9a26b9058cf245ffb75", + "old_sha256": "c20888d43c0dc3c05f50d2f71b5b34fb1c121848c19688a333d91dce89d50bbd", + "canonical_sha256": "c1007e1381919ca9ad424250e0b9cd5df9788b25db18a83780388410257805b8", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_decode_graph.h", + "old_git_blob": "c213585b224849424bccf2b088ad8b6c46eba984", + "canonical_git_blob": "8d6ead8446b6a3cc9ef84c826f3cae0a65a6775a", + "old_sha256": "f627563161b6ff68d0646d1a7f4ba9ce9ce5c9ef249ee5a209be723d0c2b3145", + "canonical_sha256": "576bd4b1a056543084b68791930a5ceddb225eda578e8a3d75397ff80b12ad12", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_elementwise_api.c", + "old_git_blob": "7871035b91175ed90cb2c384c9c757236a41ff5a", + "canonical_git_blob": "3df511ce88ed4482065f17025a3ea19c202e1a63", + "old_sha256": "4b9c0dcf32f3babd063f4d0877968c370e47469c307501ef21395f04354c3329", + "canonical_sha256": "f7cbe91ad5eb97eaa0cff56a3ed25c300500a1dd763ea25b4d9606d49fa2b0c9", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_elementwise_api.h", + "old_git_blob": "243b1ed9ca99c563fa2ad5c7fe95be01d63f1f58", + "canonical_git_blob": "03e61e20f22b709e594ee8b82a14ee2bdfb2b528", + "old_sha256": "5d62a2ea6209fc5a0133f866b60469a74d3ef2a32da67a30312e4daacc96b97f", + "canonical_sha256": "2755547573d95ec1f809d177932ef174391384b68741b3eae326d0bfcdd7b46f", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_engine.c", + "old_git_blob": "9965ca19a345fa8fc441102146bf99d0706dc045", + "canonical_git_blob": "4bc93b492d7a0a0fa209ac237e0e171c27ee3463", + "old_sha256": "c4fbae4a2bcf32a7d1db8141723258e4549cecff1ea57e69d76dc61c87bcce73", + "canonical_sha256": "f5f73b3c5fd5c202dfea80cb6b69f8f2df9560de6a467e065d33596b7a1ddd85", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_engine.h", + "old_git_blob": "3733d534aaab756e0bfaff361021fe695d248f20", + "canonical_git_blob": "4eb4cdb08eda9729a5e6394e420afedfb39dae2b", + "old_sha256": "0d2a364e634d8ba299fdcddf6502f6cf801876036ebf3e646a4336fcf98e829e", + "canonical_sha256": "8dfdf5ffeda889bef260d6bdb2f1b3513263d6ff8e78670dc8a008d92d630e54", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_fmt.c", + "old_git_blob": "270f3fe3e6d9715650867cbb04afdde88c63adec", + "canonical_git_blob": "d30360bb22ca45b231c62173b0817648e69304ce", + "old_sha256": "795e962048429c7b43b21ff6b521534676de410f6d3b6bc64620f47bd5d1fefa", + "canonical_sha256": "09409c3fc6d1b7d0912591fc7189590d3e2b5db098326ade3f1521732e8a2473", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_fmt.h", + "old_git_blob": "8a308f4b22f43c340c03ffe7acff43319c58fed2", + "canonical_git_blob": "f2e6224209bbe7798c897dd4856537257ce5bac9", + "old_sha256": "dd9f13c1a136edea6816b00ba30299670d801fad0a1dd7ca45a31bb19e762ba8", + "canonical_sha256": "7a09a508c15d6652dda229b2893ba9e19e6879d271bbd8fbd3adf003ed40a39f", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_fp8_api.c", + "old_git_blob": "d642cc51935d346d4e4b696ea1e4b61d124b093d", + "canonical_git_blob": "5ed26549cea3bbdd02bbbec2262338dc09241063", + "old_sha256": "abba3810e41173747efc8ac1ee18971460ff33f25ee3e9a454e88323b379dcea", + "canonical_sha256": "b28f14a218295a4ae17fcede12a7f7a96e96bd3b641ebd0afbaec09d9e5f6d14", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_fp8_api.h", + "old_git_blob": "9c7caf2d269947e80554d029a1ed01a6c04f279b", + "canonical_git_blob": "9720f9a19988ab55c158b2cb48f3f1d921f4ba50", + "old_sha256": "ddebec3158b0d938c93a527b135cf5e125f93e951041a197672edb870436b668", + "canonical_sha256": "15bcda0f7ea4119a23ffcc7720f16d227bff76307f6cbb7f41d783f2e097116a", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_fp8_pack.c", + "old_git_blob": "77bd62063fb3b6641221466e813760282cb3b81c", + "canonical_git_blob": "df13ee5ab1654ffa1462a9319dfd51db94bb4cc6", + "old_sha256": "881daeaf1d33f31f8ccf5cf4243ef7f5c9748f266fb36c60fe9469ac6296fe79", + "canonical_sha256": "eaa651e04da8bd72957b374395e419e41872e3e1af761e9fba7135014445c87a", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_fp8gemm_api.c", + "old_git_blob": "5605a6ea823d9b41db741f249523cf38e75818ff", + "canonical_git_blob": "d7c55ca186f5dc13f8f256714bc1e1050480917c", + "old_sha256": "0d745f7a63623f064020e2d9fcba93e67b996d7ea74b6a03729160fe4c316d9f", + "canonical_sha256": "8ce0fdda2e33bf35035181d695123b3111686341589684327c3ab6940822673a", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_fp8gemm_api.h", + "old_git_blob": "2f14e9a41753a061a6a973c11233639a01ab554c", + "canonical_git_blob": "071097813e000e0b71d2fe670645b741d3e64926", + "old_sha256": "c02fe409ba68103e6c09593f6eb234486ac5e967ea05400881c86bc8ea3cef92", + "canonical_sha256": "ca0327dbc7e7617be5e783f2a5d5335978aacb24ba61d9f4d9988e216b4bc5f6", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_gdn_api.c", + "old_git_blob": "6d56e0e14ee5fbdcdd04e9fee880434af355013a", + "canonical_git_blob": "6d56e0e14ee5fbdcdd04e9fee880434af355013a", + "old_sha256": "fac508112f066825932aa9c1ea71838000da94c5d8db941b02e68e8b51405189", + "canonical_sha256": "fac508112f066825932aa9c1ea71838000da94c5d8db941b02e68e8b51405189", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_gdn_api.h", + "old_git_blob": "cbb53e51f8077b8f1746fc853f542d574873e39b", + "canonical_git_blob": "cbb53e51f8077b8f1746fc853f542d574873e39b", + "old_sha256": "7329f43b66c8664d0612a0bf51c384f08a0786b20d918060895d86f7a1fb30a1", + "canonical_sha256": "7329f43b66c8664d0612a0bf51c384f08a0786b20d918060895d86f7a1fb30a1", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_gemm.c", + "old_git_blob": "42b47a7d634494221641c977d7f810e314762985", + "canonical_git_blob": "b81a03f90762e7131e1b87347f63b207c6a9fc6e", + "old_sha256": "c1d3f2cbf54f129a680a1c3a16efe217a70b1c35f13547e3c7bb33f0b014bdc5", + "canonical_sha256": "b22cfb4ce6343687e39fda11666f9b7919dd6580d26208b0afc07f15dcae626d", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_gemm.h", + "old_git_blob": "66a6b0485e1c3156e91135d793e6ff1d512559ed", + "canonical_git_blob": "b71176c8e4edc7744b0eaba11af2ad867d5cc13f", + "old_sha256": "b657f8a93b97904570b99d4da8a6879117edae8a83ae6747f1a299019a869661", + "canonical_sha256": "ace69c591b350c49cf9f7d4d38d9a3271ea0adeae98368a109fcb1f05bc7a1c8", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_hostmath.c", + "old_git_blob": "c1af7a178fe5fac5aaff9527a3eb2ccb0c5e625d", + "canonical_git_blob": "2adc8ace888df0c87e868a7e5773f0ed304061ba", + "old_sha256": "4ee994d79539baabc365deb867bca618bfdd2e397bb7283b5ded7dfb9dcdf1eb", + "canonical_sha256": "9aee5b24d788434236f8dd0fd5d201c4dd6d78712adad966f44ce5797e71b622", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_hostmath.h", + "old_git_blob": "48f1be7decd8eec7bf02411710e4869168c71f71", + "canonical_git_blob": "91b58c7f8265a2da9233ffa6dbfc2a7de56463a7", + "old_sha256": "10ae3b45cd42a2d92b2331f32491b61b35b68a6cc749c1a12dbbc0dcfc7c0d4b", + "canonical_sha256": "cf9d209b352c835e08fa36cec1887179b5216b92b58ce6b2e6cdfa6f4e837d57", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_matmul_api.c", + "old_git_blob": "b2885b5464c040ae504dffe7d4d21757c2d8b7bc", + "canonical_git_blob": "72e2d61b14508a8793aaf341a8c30d2b9daf017f", + "old_sha256": "40efdede82011469626b0f014c1c17181e928c0d3a01069a203f0528a8659185", + "canonical_sha256": "3b3db0d25201469c00b0c8c6396efc67a445899d63b1f74b5c663b27d3bc1380", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_matmul_api.h", + "old_git_blob": "d75b09962d0cb28b8cd5c496d7bd63f2c7c61367", + "canonical_git_blob": "5141cd361797bdd9e67828440e74d761afb8145f", + "old_sha256": "c513761dce03887a87b34aec4d21279a3b24ecd75115d30fb54d145cf8e75bad", + "canonical_sha256": "a156d835939aec350b1f5d60c020870283b6d0aaaade55a0186fe7fcfbc4647b", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_mem_cached.c", + "old_git_blob": "e0c00adf7da39af5b16f11b61686f5dc015f236e", + "canonical_git_blob": "4dcef50684aeca130adc44a224fcb9c3e1884684", + "old_sha256": "ba8e658f8363d8b0062fdfc298078d6bb09c3ab0372f67bb36ac0ef4e29b9939", + "canonical_sha256": "498f1e96fa6b0728c24fc084ccfce37643c492b547f9f89b25151cb24667aa26", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_mem_cached.h", + "old_git_blob": "3aaa422432027d1a1d910d083d522ece8997aa82", + "canonical_git_blob": "c8dc191079510cddedd13d4ef58b574d005a602b", + "old_sha256": "3650bd34ef9d9e3d27a53addb497b9a6e66df20ad146bd1e3f9fcfef7c526e42", + "canonical_sha256": "c48cb9b7abc0d31ab2e86ff3f3fdea2e284e3df5c4009b5acf4a7f9287dcc06c", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_moe_api.c", + "old_git_blob": "d5e57dcdfac0c95f2cda389da17676343ada2c04", + "canonical_git_blob": "fe2d89ad5500000eb3acb218ff36afc1ad1cd954", + "old_sha256": "46e398de6227157bce893e9e49ae04821c09fe02bb899fb644b34a53ed3fa001", + "canonical_sha256": "87e4c8bc7421c8141c3a0f1923a6eb01a4457ef6394f82818148b75041005440", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_moe_api.h", + "old_git_blob": "db6f5d46b000008e331b05580cbaf7480b825465", + "canonical_git_blob": "cb4b2ef3685f4890ac0da8b54a4335673c3a450a", + "old_sha256": "73ab66f68ecef2d7bfc2215a56a087a36f2b4fb40adb202dfbfd9d7d90e93045", + "canonical_sha256": "a25836d808ba0f3c4df59d0d30bb2c8efb32e74e42cbd28f19f3f27a1857c123", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_pfgemm.c", + "old_git_blob": "1172458fe7375d19c0e9afd64b0fd092843f11bd", + "canonical_git_blob": "00f79f75de9a913e86218f26f1697f70469ab410", + "old_sha256": "4e893ca95a185a830384c9b67d13cd7f0a353db21d2e0feb955418b626fe14da", + "canonical_sha256": "9335666196f3ce0a1d5f436045395f5b0e577f7712a43a2e685755a4bfc25d0a", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_pfhost.c", + "old_git_blob": "59fff7bc65aa34960bc75a1bdff204772517ebc7", + "canonical_git_blob": "04e8e25cc51bfdff6c60de705c68e235856bd7ea", + "old_sha256": "6a48403fe004b7513cea756f41c1f300bf41c0791a892d6276c0b430d3653cb3", + "canonical_sha256": "7e321e8ce0208ab24a3f1cd8f92087c769ba3c4b707bc5537a2cd6869ffc89c6", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_pfhost.h", + "old_git_blob": "64662d7671bfa0da549616687782b37f1191fa7f", + "canonical_git_blob": "fea8ad39cc6811d2d2dc92a61f0e932e8a180c7c", + "old_sha256": "0ec5ee3c119f854386e00c5c0d0c7ad8970d02af96835ac112cd53bdae3b1968", + "canonical_sha256": "7c1f2100a56da57827efa392eb60be07f3688c7a0307f2baf0174a6c15c49154", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_platform.c", + "old_git_blob": "4c8e59b93e69ea4faa0f169888d1f26b8c8c1972", + "canonical_git_blob": "b5d79369d01b1ba9d76dba289094e7de0b458d4a", + "old_sha256": "721ecbd276f0e8adfc05035c3f14439af777f4d7ea4f08d06d7c716dcabaf337", + "canonical_sha256": "e3089c6c30454b0373fa4700949b9bb0c70db0c6b65ec8989797a77ebaf74f44", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_platform.h", + "old_git_blob": "fe4427fc60d948fa9991d1d22fd1961b0f13ae11", + "canonical_git_blob": "d71a262f9c2750981a0acfe10b1820ccb52fd6af", + "old_sha256": "26b55b6525b1316c9635700915b3eaa4a745254a86a4a8cb8f3db2de31c944ba", + "canonical_sha256": "1a9dc0d86c0426e11381b55e5d9051e5c9a978c723557ec77c6fb64841675eb7", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_platform_linux.c", + "old_git_blob": "23f046209862515a5a84cd7f331a9222459831a8", + "canonical_git_blob": "7b1c507d5308289c0c3123c0a3858902c52470dd", + "old_sha256": "fd4e87328ae9f7cfc353595635dea7020d711873e8aa98e69017b7086271153e", + "canonical_sha256": "33da224f6efcf92f67da1fa558723576b42bcbcceaff9021313a61e993dcae82", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_platform_linux.h", + "old_git_blob": "cee1b961ddf8cf48280853f426ef704d904df115", + "canonical_git_blob": "834ad9349fa9f695d835f337dca8f6dcf227f0f0", + "old_sha256": "83333e21aeeb9a93edfe41328468cd42c691f8f61fe4eb1c3502be4b1a093538", + "canonical_sha256": "b925e045b9e3ac86f89d13d61f5ff3faedd171e51cdb82e1f07b20d727990521", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_prefill.c", + "old_git_blob": "b286e63782ebef41129fc7559aa1936ad57dadcb", + "canonical_git_blob": "258972928c5c0da244259a174b528def9aabce71", + "old_sha256": "907c72cfefbdaf3d678d5ac23fe7abf9ca4875ee490b10c32db02cf846e3425d", + "canonical_sha256": "e3b442e9c6dd6318a82cfd216f16ba9420e25f583851da6e8af46d3ba6465761", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_prefill.h", + "old_git_blob": "8879c6b27da5edb2519248fada9c1a7c169046af", + "canonical_git_blob": "9a365c64535b871177743d09557093f404ad072e", + "old_sha256": "fb9e455023165b6a2f587b16c60e8004430b910e78219db54db072f4f4fffe7d", + "canonical_sha256": "a199409021de03a716680de0b2beecd6dae8f014acfe2b75ae646e888ee8e9dc", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_prefill_attn256_api.c", + "old_git_blob": "7b9fcd22c5a4670644070452c80b4d6feaa03160", + "canonical_git_blob": "7b9fcd22c5a4670644070452c80b4d6feaa03160", + "old_sha256": "aff7aa1ad520b0e84085877f69e23ae45ad5a714f1f9741c492a2fff41045a38", + "canonical_sha256": "aff7aa1ad520b0e84085877f69e23ae45ad5a714f1f9741c492a2fff41045a38", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_prefill_attn256_api.h", + "old_git_blob": "a2960150d2c78881468e4f7b5a4603b60c08af5e", + "canonical_git_blob": "a2960150d2c78881468e4f7b5a4603b60c08af5e", + "old_sha256": "76a921e323f020eb592d1890a92c132690a9ac8269b7f82f7f236d37562d707c", + "canonical_sha256": "76a921e323f020eb592d1890a92c132690a9ac8269b7f82f7f236d37562d707c", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_prefill_attn_api.c", + "old_git_blob": "40b9fa33f23e355308056629e0f63e36005da079", + "canonical_git_blob": "d558f227a69c28b7218c90467f5f0bbac5bfaf73", + "old_sha256": "461f3b5b51bce1bae9ab214b6bde61fafb72e2873ce545a63e63fc164b458445", + "canonical_sha256": "a249c5a01c7e244352fdebbcf1be4348135fee551f90403bf25ad8c628bcc227", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_prefill_attn_api.h", + "old_git_blob": "3bf4bd3bf2ae2e7e3b4d7e5877e9eb78c63965b1", + "canonical_git_blob": "f7d19c0110dbaa024bdfb88596d47210d10798f4", + "old_sha256": "7c68b29fc5e24819a936db0db654975bf587b718a8c63c36135ba3b7bbe9fa51", + "canonical_sha256": "d331dbf601ab73e0677e2f30ce857787732a3a428de32e4c0dc253585aa7344f", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_q36_graph.c", + "old_git_blob": "57fe6ddc2bb7483520c6b8dc6a0e3dbc9cb6f38c", + "canonical_git_blob": "95a6dadd39479e2d66e4baa9d8fba7830f0ef5be", + "old_sha256": "46b940b6310d6e18669693d411469c87c2e17e3b7538e6bd4eb1fb48f9705c99", + "canonical_sha256": "5e4e7c65a45e45c41cc63ada5e6d2b89e53676887f7771fdb4579dd86e59de30", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_q36_graph.h", + "old_git_blob": "c14475acfa644db8938c6152e8886c76d778232c", + "canonical_git_blob": "c14475acfa644db8938c6152e8886c76d778232c", + "old_sha256": "b9c609e006f9f3f82455deee81ba4ea954c249e4f542bc8466427ba49f0c9a86", + "canonical_sha256": "b9c609e006f9f3f82455deee81ba4ea954c249e4f542bc8466427ba49f0c9a86", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_q38_graph.c", + "old_git_blob": "d890d8261aafcdad70d57686de95bced654c1158", + "canonical_git_blob": "d890d8261aafcdad70d57686de95bced654c1158", + "old_sha256": "95df5f21c5537705ea9ab8ecd1ffe5c80bcaf7b197ec4a1dc5e4e35c64e32130", + "canonical_sha256": "95df5f21c5537705ea9ab8ecd1ffe5c80bcaf7b197ec4a1dc5e4e35c64e32130", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_q38_graph.h", + "old_git_blob": "263b1a3a10f4c51e8a1d06b91d440fe72e9ea814", + "canonical_git_blob": "263b1a3a10f4c51e8a1d06b91d440fe72e9ea814", + "old_sha256": "d679f32675ce970c2902867c7f089b667d9f7cc594354e92d724464caf2755da", + "canonical_sha256": "d679f32675ce970c2902867c7f089b667d9f7cc594354e92d724464caf2755da", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_router_api.c", + "old_git_blob": "fc06a7b08711016feefffdec0efc756ff92ac3f3", + "canonical_git_blob": "6d4025b50be4702602949ee903705111123c5edb", + "old_sha256": "4e9ff509aee85ccda9f9092f3298a399e0f29e9b936dfc539d28ef21a7ac17f2", + "canonical_sha256": "f23bb63e9fe4a0b266afa5a2e8e3fbca1ee37be0d46a2ad1c06ddeac7675c9bf", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_router_api.h", + "old_git_blob": "1232e8aaa21242fa04c5ae6a839f604fe4c3ed9f", + "canonical_git_blob": "f2fa71916304b985caae320ee03ffa04bc4f0fa2", + "old_sha256": "003443de4ee2df16af1e660073ceddfad869d9ffab99895ef9d139aab20dfc0e", + "canonical_sha256": "bb33fc94b00208ac4f6a55977565da07ead1899d2cd2f2d07026ade7f5196175", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_scan.c", + "old_git_blob": "0094072e36d8b6f7b53f92152c6b21776fa86bae", + "canonical_git_blob": "0094072e36d8b6f7b53f92152c6b21776fa86bae", + "old_sha256": "c1412bcd0d61c880b7b659991551bd71d76a32a3a803d7abb66fe74b4be22b98", + "canonical_sha256": "c1412bcd0d61c880b7b659991551bd71d76a32a3a803d7abb66fe74b4be22b98", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_scan.h", + "old_git_blob": "3c775cf6a61cedbc378a07f1880ea22e7695248d", + "canonical_git_blob": "3c775cf6a61cedbc378a07f1880ea22e7695248d", + "old_sha256": "71cfb07202533bda9d74ff8bbf3fb96ea7fe02ceb24edb218029cb9fd1af5849", + "canonical_sha256": "71cfb07202533bda9d74ff8bbf3fb96ea7fe02ceb24edb218029cb9fd1af5849", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_scan_ref.c", + "old_git_blob": "ab5ee16a5df4f2317fd67ecee2c6e3f7d1e4285d", + "canonical_git_blob": "ab5ee16a5df4f2317fd67ecee2c6e3f7d1e4285d", + "old_sha256": "115a55a9977e6da15c0b1a4dc1490a21b36ca892118108d3e24d8417ef656ed5", + "canonical_sha256": "115a55a9977e6da15c0b1a4dc1490a21b36ca892118108d3e24d8417ef656ed5", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_gpu_serving.c", + "old_git_blob": "9aba1a20d7cf505812b5bb170b628bb6ad54b94a", + "canonical_git_blob": "a430331e2b5bb78477250b853704c221bb2b2218", + "old_sha256": "a10af5c215bae722915d0451bb1f43aeade9c92a4986bc078474a7b6aa3e6191", + "canonical_sha256": "ee69efd59335d898d2cbd9e1b4dd4deb574282304aa407553d581008c25fd170", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_serving.h", + "old_git_blob": "d4acb7a2455c1a43e488bbeb07ebd3359c3e8152", + "canonical_git_blob": "4adbb1e6717f57a53cbbf6b32e42867017ab6d76", + "old_sha256": "f31fadef64f3c77c93513581fd5b7f459632f9d8e872ec23ca934c8e4fefe345", + "canonical_sha256": "fba56a8bab172bec94af1c85598d1d86f5d4d21ae0f42e069c20e6373a432585", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_session.c", + "old_git_blob": "41a72e285ccdf17baf8548dac5a7e3d35517aa51", + "canonical_git_blob": "a8e5ffad962012acd7da66f0c5714548e5ca68aa", + "old_sha256": "83ef897f0849636f3ce6ab5eacb33c0ebbbe1107bab06b2a6efb596813f843ca", + "canonical_sha256": "6cd71d392baa145e09f5b94c312e48682697c3684dbceb989337caca41973d1f", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_session.h", + "old_git_blob": "8a4ae6727a165efb918a962e72370323f820a29d", + "canonical_git_blob": "5b6830f0c159c4d66517405a3ed94acc072acbf6", + "old_sha256": "3391b3b7a074a1c37fffede68a7ce1a48c9f1dd04201162b91ec7ccae46ae26a", + "canonical_sha256": "a7a9254d4e01040b948c36dcde80ab9961ed6deea45c40d3445935b03d915ffd", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_tcgemm_api.c", + "old_git_blob": "50e740472332f536069462a04cc89cb5680f298f", + "canonical_git_blob": "bffd0630be5a29ee51532fc95e728a0a47481b37", + "old_sha256": "a423e592120b55665158261289d1de29866a611c5601dc9f7fa39573eb96fb9e", + "canonical_sha256": "1be4d930ad2843589aecd8e6f30b4540bf286e496118b76bedddeea90af39285", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_tcgemm_api.h", + "old_git_blob": "f75884996cbbd4a9531a39d363c55019ec070616", + "canonical_git_blob": "f213ca15d249df841dd638e6c625203ce0412b30", + "old_sha256": "b41d06ea801831cc01a49ad02d34c76d67a88d9c21487eb8018192946c220bf0", + "canonical_sha256": "951fbeac82706957c686f73fc5837f68c63d19322e676ee5a57c4eb90013c3a1", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_tern_api.c", + "old_git_blob": "36f052a92daa588b5032aca0476648de6103094e", + "canonical_git_blob": "d160c5a5ce8cc0426d9382a017ab4d26e07bdd4d", + "old_sha256": "b4a808102fb1c9740e0e90207b6c60ac96ab765ef057f313f7b248f53d62aee9", + "canonical_sha256": "1d325eac7a38c1cfb571c20119ac9f9449177d6ca548010a40cf19edc8e7b767", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_tern_api.h", + "old_git_blob": "4e81e02c195418de8859415498a61108ea0ad23b", + "canonical_git_blob": "763ca0f71bdb3139580afa76eb228d3075dccf15", + "old_sha256": "5fd6566760a22c91d26966e366ed2f561d1440afc93387d086031768ce6249d2", + "canonical_sha256": "57d000100abbaa83b964608ab414551e83320fee6e0133d63b288b973847b146", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_wait.c", + "old_git_blob": "57325f0fd0564a9e4e5815372e62c4810a076331", + "canonical_git_blob": "28c267f662c019bcaf5d23c1a550f30394fb583d", + "old_sha256": "a8451df31e7c868bc96d1539e09303de7eff8dd1f692af975f7f18614322abd1", + "canonical_sha256": "59f7d47edc96842c749cda75de7c5accb016b9137b8307cb2c2c23fdba8d0d14", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_wait.h", + "old_git_blob": "f007dbca95527ef6266daf85397779ce6f8e84e2", + "canonical_git_blob": "5db23ff0821d29cc0abf40ef516b71852c0ac34b", + "old_sha256": "895d3e4ffe0998faf0606e44a426b49d777ed4f47420f7c008c933e6ef74a165", + "canonical_sha256": "1e5a4119e3dc67538667ca984b10b8024b9a5e89b1c39257bc53f16663e58e66", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_sm121_disasm.c", + "old_git_blob": "796db0339247b998fa37c60a15aeac6105705774", + "canonical_git_blob": "796db0339247b998fa37c60a15aeac6105705774", + "old_sha256": "085e13f304b48e712f434fad27ab6bcef9328b066c2d9b71ebbf25c4c5be46e0", + "canonical_sha256": "085e13f304b48e712f434fad27ab6bcef9328b066c2d9b71ebbf25c4c5be46e0", + "old_matches_e5b32567": true, + "byte_identical": true + }, + { + "path": "src/omega_sm121_disasm.h", + "old_git_blob": "aaf815d6387018ff0ac2598c23dac1398672cb60", + "canonical_git_blob": "aaf815d6387018ff0ac2598c23dac1398672cb60", + "old_sha256": "0ac5f436eccde482f9acd61ed0e8358b1e7aeb33f4bdb9ae82f41ba04c41f26b", + "canonical_sha256": "0ac5f436eccde482f9acd61ed0e8358b1e7aeb33f4bdb9ae82f41ba04c41f26b", + "old_matches_e5b32567": true, + "byte_identical": true + } + ] +} diff --git a/tests/cudapp_stage_hermetic.sh b/tests/cudapp_stage_hermetic.sh new file mode 100755 index 000000000..c403aff62 --- /dev/null +++ b/tests/cudapp_stage_hermetic.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# The canonical archive must be built only from the authenticated CUDApp tree. A parent +# make passes PHYSICS_DIR through MAKEFLAGS; exported PHYSICS_DIR/CFLAGS/CUDAPP_ENCODER +# must not substitute another driver client, flags or encoder either. +# Usage: tests/cudapp_stage_hermetic.sh CUDAPP_CHECKOUT (needs OMEGA_OMC, OMEGA_BRIDGE) +set -eu +checkout=${1:?usage: tests/cudapp_stage_hermetic.sh CUDAPP_CHECKOUT} +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +work=$(mktemp -d "${TMPDIR:-/tmp}/cudapp-stage-hermetic.XXXXXX") +trap 'rm -rf -- "$work"' EXIT HUP INT TERM +cd "$root" +env -u MAKEFLAGS -u MFLAGS -u MAKELEVEL -u PHYSICS_DIR -u CFLAGS -u CUDAPP_ENCODER \ + sh tools/cudapp-stage.sh cudapp.lock "$checkout" "$work/clean" > /dev/null +# Hostile driver client: the authenticated nvrm/m16 plus a marker symbol. +mkdir "$work/hostile" +cp -R "$work/clean/source/nvrm" "$work/clean/source/m16" "$work/clean/source/third_party" "$work/hostile/" +printf '\nconst char omega_stage_hostile_marker[] = "OMEGA_STAGE_HOSTILE_MARKER";\n' >> "$work/hostile/nvrm/nvrm.c" +clean=$(sha256sum < "$work/clean/build/libcudapp.a" | cut -c1-64) +fail() { echo "FAIL CUDAPP_STAGE_HERMETIC $1" >&2; exit 1; } +# Case 1: a parent make's PHYSICS_DIR (MAKEFLAGS and environment) naming the hostile client. +MAKEFLAGS=" -- PHYSICS_DIR=$work/hostile" PHYSICS_DIR="$work/hostile" \ + sh tools/cudapp-stage.sh cudapp.lock "$checkout" "$work/physics" > /dev/null 2>&1 || + fail "physics: stage failed under inherited PHYSICS_DIR" +grep -q OMEGA_STAGE_HOSTILE_MARKER "$work/physics/build/libcudapp.a" && + fail "physics: inherited PHYSICS_DIR driver client entered the archive" +[ "$(sha256sum < "$work/physics/build/libcudapp.a" | cut -c1-64)" = "$clean" ] || + fail "physics: archive depends on inherited PHYSICS_DIR" +# Case 2: exported compiler flags and encoder selection. +CFLAGS=-O0 CUDAPP_ENCODER=c \ + sh tools/cudapp-stage.sh cudapp.lock "$checkout" "$work/flags" > /dev/null 2>&1 || + fail "flags: stage failed under exported CFLAGS/CUDAPP_ENCODER" +[ "$(sha256sum < "$work/flags/build/libcudapp.a" | cut -c1-64)" = "$clean" ] || + fail "flags: archive depends on exported CFLAGS/CUDAPP_ENCODER" +echo "PASS CUDAPP_STAGE_HERMETIC archive=$clean" diff --git a/tests/run_m17_gates.sh b/tests/run_m17_gates.sh index f38317157..4147043b1 100755 --- a/tests/run_m17_gates.sh +++ b/tests/run_m17_gates.sh @@ -15,13 +15,18 @@ # limitations under the License. # tests/run_m17_gates.sh: Master Qualification Gate Runner for Milestone 17 (OMEGA_BLACKWELL_VECTOR) -set -eu +set -euC OMEGA_ROOT=$(cd "$(dirname "$0")/.." && pwd -P) cd "$OMEGA_ROOT" TOOL="$OMEGA_ROOT/${OUT_DIR:-build}/omegatool" -EVIDENCE_DIR="$OMEGA_ROOT/evidence" +EVIDENCE_DIR=${M17_EVIDENCE_DIR:-"$OMEGA_ROOT/evidence"} RECEIPT="$EVIDENCE_DIR/omega_blackwell_vector_qualification_receipt.json" +# A canonical rerun must never replace a historical qualification receipt. +if [ -e "$RECEIPT" ] || [ -e "$EVIDENCE_DIR/m17_corpus_digests.txt" ]; then + echo "M17 evidence already exists; choose a fresh M17_EVIDENCE_DIR" >&2 + exit 2 +fi echo "================================================================================" echo " AIEN OMEGA SUBSTRATE: MILESTONE 17: BLACKWELL VECTOR QUALIFICATION" @@ -37,6 +42,16 @@ make -C "$OMEGA_ROOT" clean make -C "$OMEGA_ROOT" -j echo " Build OK." echo "" +# The existing .om stage verifier supplies provenance, not qualification. +CANONICAL="$EVIDENCE_DIR/m17_blackwell_vector/canonical-source" +bash "$OMEGA_ROOT/tools/e1_manifest.sh" --canonical-evidence "$CANONICAL" \ + src/omega_blackwell_encoder.c src/omega_blackwell_encoder.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_blackwell_engine.c src/omega_blackwell_engine.h +CANONICAL_SOURCE=$(cat "$CANONICAL/CUDAPP-SOURCE.json") + # Step 2: Run all 18 M17 qualification gates echo "[*] Step 2: Evaluating 18 canonical M17 qualification gates on physical GB10 SM..." @@ -68,20 +83,20 @@ echo "" # Step 5: Compute artifact digests echo "[*] Step 5: Computing artifact digests..." mkdir -p "$EVIDENCE_DIR/m17_blackwell_vector" -sha256sum "$OMEGA_ROOT/src/omega_vector."* "$OMEGA_ROOT/src/omega_blackwell_encoder."* "$OMEGA_ROOT/src/omega_blackwell_qmd."* "$OMEGA_ROOT/src/omega_blackwell_realize."* "$OMEGA_ROOT/src/omega_blackwell_submit."* "$OMEGA_ROOT/src/omega_blackwell_engine."* "$OMEGA_ROOT/src/omega_blackwell_gates."* "$TOOL" > "$EVIDENCE_DIR/m17_corpus_digests.txt" +sha256sum "$OMEGA_ROOT/src/omega_vector."* "$OMEGA_ROOT/src/omega_blackwell_gates."* "$CANONICAL/"* "$TOOL" > "$EVIDENCE_DIR/m17_corpus_digests.txt" DIGEST_VEC_C=$(sha256sum "$OMEGA_ROOT/src/omega_vector.c" | cut -d' ' -f1) DIGEST_VEC_H=$(sha256sum "$OMEGA_ROOT/src/omega_vector.h" | cut -d' ' -f1) -DIGEST_ENC_C=$(sha256sum "$OMEGA_ROOT/src/omega_blackwell_encoder.c" | cut -d' ' -f1) -DIGEST_ENC_H=$(sha256sum "$OMEGA_ROOT/src/omega_blackwell_encoder.h" | cut -d' ' -f1) -DIGEST_QMD_C=$(sha256sum "$OMEGA_ROOT/src/omega_blackwell_qmd.c" | cut -d' ' -f1) -DIGEST_QMD_H=$(sha256sum "$OMEGA_ROOT/src/omega_blackwell_qmd.h" | cut -d' ' -f1) -DIGEST_REAL_C=$(sha256sum "$OMEGA_ROOT/src/omega_blackwell_realize.c" | cut -d' ' -f1) -DIGEST_REAL_H=$(sha256sum "$OMEGA_ROOT/src/omega_blackwell_realize.h" | cut -d' ' -f1) -DIGEST_SUB_C=$(sha256sum "$OMEGA_ROOT/src/omega_blackwell_submit.c" | cut -d' ' -f1) -DIGEST_SUB_H=$(sha256sum "$OMEGA_ROOT/src/omega_blackwell_submit.h" | cut -d' ' -f1) -DIGEST_ENGINE_C=$(sha256sum "$OMEGA_ROOT/src/omega_blackwell_engine.c" | cut -d' ' -f1) -DIGEST_ENGINE_H=$(sha256sum "$OMEGA_ROOT/src/omega_blackwell_engine.h" | cut -d' ' -f1) +DIGEST_ENC_C=$(sha256sum "$CANONICAL/omega_blackwell_encoder.c" | cut -d' ' -f1) +DIGEST_ENC_H=$(sha256sum "$CANONICAL/omega_blackwell_encoder.h" | cut -d' ' -f1) +DIGEST_QMD_C=$(sha256sum "$CANONICAL/omega_blackwell_qmd.c" | cut -d' ' -f1) +DIGEST_QMD_H=$(sha256sum "$CANONICAL/omega_blackwell_qmd.h" | cut -d' ' -f1) +DIGEST_REAL_C=$(sha256sum "$CANONICAL/omega_blackwell_realize.c" | cut -d' ' -f1) +DIGEST_REAL_H=$(sha256sum "$CANONICAL/omega_blackwell_realize.h" | cut -d' ' -f1) +DIGEST_SUB_C=$(sha256sum "$CANONICAL/omega_blackwell_submit.c" | cut -d' ' -f1) +DIGEST_SUB_H=$(sha256sum "$CANONICAL/omega_blackwell_submit.h" | cut -d' ' -f1) +DIGEST_ENGINE_C=$(sha256sum "$CANONICAL/omega_blackwell_engine.c" | cut -d' ' -f1) +DIGEST_ENGINE_H=$(sha256sum "$CANONICAL/omega_blackwell_engine.h" | cut -d' ' -f1) DIGEST_TOOL=$(sha256sum "$TOOL" | cut -d' ' -f1) QUALIFIED_COMMIT="$(git -C "$OMEGA_ROOT" rev-parse HEAD)" @@ -113,6 +128,7 @@ cat < "$RECEIPT" "contract_id": "CONTRACT-OMEGA-BLACKWELL-VECTOR-M17", "generated_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)", "qualified_implementation_commit": "$QUALIFIED_COMMIT", + "canonical_source": $CANONICAL_SOURCE, "host": { "os": "$(uname -s)", "arch": "$(uname -m)", diff --git a/tests/run_numeric_gates.sh b/tests/run_numeric_gates.sh index 4dade3ab4..e45724131 100755 --- a/tests/run_numeric_gates.sh +++ b/tests/run_numeric_gates.sh @@ -162,19 +162,24 @@ num_check_physics() { # num_build OMEGA PHYSICS OUT LOG -- build the chip test binary. num_build() { - local omega=$1 p=$2 out=$3 log=$4 nv + local omega=$1 p=$2 out=$3 log=$4 nv stage nv=$p/third_party/nvidia-open-580.173.02 - (cd "$omega" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off \ - -Isrc -I"$p/forge" -I"$p/nvrm" -I"$p/m16" \ - -I"$nv/src/common/sdk/nvidia/inc" -I"$nv/kernel-open/common/inc" \ + stage=${CUDAPP_STAGE:-$omega/build/cudapp} + case $stage in /*) ;; *) stage=$omega/$stage;; esac + (cd "$omega" && + sh tools/cudapp-stage.sh cudapp.lock "${CUDAPP_DIR:-../CUDApp}" "$stage" && + CUDAPP_STAGE="$stage" bash tools/e1_manifest.sh --canonical-evidence "$out.canonical" \ + src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c \ + src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c && + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off \ + -Isrc -I"$stage/source/src" -I"$stage/source/m16" -I"$stage/source/nvrm" \ + -I"$p/forge" -I"$nv/src/common/sdk/nvidia/inc" -I"$nv/kernel-open/common/inc" \ -I"$nv/kernel-open/nvidia-uvm" -I"$nv/src/nvidia/arch/nvalloc/unix/include" \ -o "$out" tests/test_omega_numeric.c src/omega_numeric.c src/omega_numeric_gb10.c \ - src/omega_numeric_divsqrt_gb10.c \ - src/omega_numeric_provenance.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_encoder.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c \ + src/omega_numeric_divsqrt_gb10.c src/omega_numeric_provenance.c \ src/forge_realization.c src/aegis_verification.c src/omega_om_units.c \ "$p/forge/forge_descriptor.c" "$p/forge/forge_realize.c" "$p/sha256_clean.c" \ - "$p/nvrm/nvrm.c" "$p/m16/m16_native.c") > "$log" 2>&1 || + "$stage/build/libcudapp.a" -lpthread) > "$log" 2>&1 || m19r_fail "build failed; see $log" || return 1 if nm -u "$out" | grep -Eq '\b(sqrtf?|expf?|logf?|powf?|fmaf?|sinf?|cosf?|roundf?|fabsf?)\b'; then m19r_fail "libm math symbols found in $out"; return 1 diff --git a/tests/run_reduce_chip.sh b/tests/run_reduce_chip.sh index a6487635f..685471c58 100755 --- a/tests/run_reduce_chip.sh +++ b/tests/run_reduce_chip.sh @@ -71,17 +71,22 @@ RUN_ID=$(basename "$OUT") BIN=$OUT/test_omega_reduce_gb10 NV=$PHYS/third_party/nvidia-open-580.173.02 FAIL_REASON="" -(cd "$OMEGA" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off \ - -Isrc -I"$PHYS/forge" -I"$PHYS/nvrm" -I"$PHYS/m16" \ - -I"$NV/src/common/sdk/nvidia/inc" -I"$NV/kernel-open/common/inc" \ +STAGE=${CUDAPP_STAGE:-$OMEGA/build/cudapp} +case $STAGE in /*) ;; *) STAGE=$OMEGA/$STAGE;; esac +(cd "$OMEGA" && + sh tools/cudapp-stage.sh cudapp.lock "${CUDAPP_DIR:-../CUDApp}" "$STAGE" && + CUDAPP_STAGE="$STAGE" bash tools/e1_manifest.sh --canonical-evidence "$OUT/canonical" \ + src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c \ + src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c && + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off \ + -Isrc -I"$STAGE/source/src" -I"$STAGE/source/m16" -I"$STAGE/source/nvrm" \ + -I"$PHYS/forge" -I"$NV/src/common/sdk/nvidia/inc" -I"$NV/kernel-open/common/inc" \ -I"$NV/kernel-open/nvidia-uvm" -I"$NV/src/nvidia/arch/nvalloc/unix/include" \ -o "$BIN" tests/test_omega_reduce.c src/omega_numeric_reduce.c src/omega_numeric_reduce_gb10.c \ src/omega_numeric.c src/omega_numeric_gb10.c src/omega_numeric_divsqrt_gb10.c \ - src/omega_numeric_provenance.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_encoder.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c \ - src/forge_realization.c src/aegis_verification.c src/omega_om_units.c \ + src/omega_numeric_provenance.c src/forge_realization.c src/aegis_verification.c src/omega_om_units.c \ "$PHYS/forge/forge_descriptor.c" "$PHYS/forge/forge_realize.c" "$PHYS/sha256_clean.c" \ - "$PHYS/nvrm/nvrm.c" "$PHYS/m16/m16_native.c") > "$OUT/build.log" 2>&1 || FAIL_REASON="build failed" + "$STAGE/build/libcudapp.a" -lpthread) > "$OUT/build.log" 2>&1 || FAIL_REASON="build failed" if [ -z "$FAIL_REASON" ]; then nm -u "$BIN" | grep -Eq '\b(sqrtf?|expf?|logf?|powf?|fmaf?|sinf?|cosf?|roundf?|fabsf?)\b' && FAIL_REASON="libm symbols in binary" nm -u "$BIN" | grep -Eq 'libcuda(rt)?\.so|\b(cuInit|cuCtx|cuMem|cuStream|cudaMalloc)\b' && FAIL_REASON="CUDA symbols in binary" diff --git a/tests/run_tensor_chip.sh b/tests/run_tensor_chip.sh index 4c6029af8..fa3c3a3a4 100755 --- a/tests/run_tensor_chip.sh +++ b/tests/run_tensor_chip.sh @@ -70,9 +70,12 @@ mkdir -p "$OMEGA/build/tensor-runs" || die "cannot create build/tensor-runs" OUT=$(mktemp -d "$OMEGA/build/tensor-runs/$RUN_ID.XXXXXX") || die "cannot create a run directory" RUN_ID=$(basename "$OUT") BIN=$OUT/test_omega_tensor_gb10 +make -s -C "$OMEGA" PHYSICS_DIR="$PHYS" check-cudapp || die "canonical source stage failed" +WORK=$OUT/source +bash "$OMEGA/tools/e1_manifest.sh" --canonical-overlay "$WORK" || die "canonical source verification failed" NV=$PHYS/third_party/nvidia-open-580.173.02 FAIL_REASON="" -(cd "$OMEGA" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off \ +(cd "$WORK" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off \ -Isrc -Isrc/tensor -I"$PHYS/forge" -I"$PHYS/nvrm" -I"$PHYS/m16" \ -I"$NV/src/common/sdk/nvidia/inc" -I"$NV/kernel-open/common/inc" \ -I"$NV/kernel-open/nvidia-uvm" -I"$NV/src/nvidia/arch/nvalloc/unix/include" \ @@ -82,7 +85,7 @@ FAIL_REASON="" src/omega_numeric.c src/omega_numeric_gb10.c src/omega_numeric_divsqrt_gb10.c \ src/omega_numeric_provenance.c src/omega_blackwell_codegen.c \ src/omega_blackwell_encoder.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c \ - src/forge_realization.c src/aegis_verification.c src/omega_om_units.c \ + src/forge_realization.c src/aegis_verification.c src/omega_om_units.c src/cudapp_om_units.c \ "$PHYS/forge/forge_descriptor.c" "$PHYS/forge/forge_realize.c" "$PHYS/sha256_clean.c" \ "$PHYS/nvrm/nvrm.c" "$PHYS/m16/m16_native.c") > "$OUT/build.log" 2>&1 || FAIL_REASON="build failed" if [ -z "$FAIL_REASON" ]; then @@ -148,6 +151,7 @@ jq -n --arg suite M20_TENSOR_GB10_PARITY --arg status "$VERDICT" --arg reason "$ --arg run_id "$RUN_ID" --arg commit "$COMMIT" --arg physics "$PHEAD" --arg pin "$LOCKED" \ --argjson clean_after "$CLEAN_AFTER" --argjson head_same "$HEAD_SAME" \ --argjson pclean_after "$PCLEAN_AFTER" --argjson phead_same "$PHEAD_SAME" \ + --slurpfile canonical "$WORK/cudapp-source.json" \ --arg started "$STARTED" --arg finished "$FINISHED" \ --arg order "RECURSIVE_TILE32_PAIRWISE_TREE_LANE_DELTA_16_8_4_2_1_PAD_IDENTITY_MIN_ONE_LEVEL" \ --arg mm_order "MATMUL_V1_FMUL_RNE_PRODUCTS_THEN_E1_REDUCE_SUM_RECURSIVE_TILE32_PAIRWISE_TREE_LANE_DELTA_16_8_4_2_1_PAD_IDENTITY_MIN_ONE_LEVEL" \ @@ -160,6 +164,7 @@ jq -n --arg suite M20_TENSOR_GB10_PARITY --arg status "$VERDICT" --arg reason "$ '{suite:$suite,status:$status,reason:$reason,run_id:$run_id,started_utc:$started,finished_utc:$finished, omega_commit:$commit,omega_tree_clean_before:true,omega_tree_clean_after:$clean_after, omega_commit_unchanged_after:$head_same,physics_commit:$physics,physics_lock_pin:$pin, + canonical_source:$canonical[0], physics_tree_clean_before:true,physics_tree_clean_after:$pclean_after,physics_commit_unchanged_after:$phead_same, reduce_declared_order:$order,matmul_declared_order:$mm_order,binary_sha256:$bin,chip_log_sha256:$log, chip_stderr_sha256:$errlog,devfail_lines:$devfail_n,failed_gb10_calls:$failed_calls_n, diff --git a/tests/test_chip_run_transc_manifest.sh b/tests/test_chip_run_transc_manifest.sh index eb4b7a987..5691a7424 100755 --- a/tests/test_chip_run_transc_manifest.sh +++ b/tests/test_chip_run_transc_manifest.sh @@ -15,14 +15,14 @@ # limitations under the License. # Host-only check of tools/manifests/numeric_transc.chiprun and its wrapper -# tools/run_numeric_transc_gate.sh. No GPU, no chip sources, no real build: a fake omega and -# fake physics (git repos in a temp dir), a tiny fake chip binary and fake host tier, run through -# the real module via the CHIPRUN_SELFTEST seam (same method as tests/test_chip_run.sh). +# tools/run_numeric_transc_gate.sh. No GPU or chip execution: authenticated real +# staged sources, fake omega/physics git repos, a tiny fake chip binary and fake +# host tier run through the existing CHIPRUN_SELFTEST seam. # tests/test_chip_run_transc_manifest.sh -# Checks: (1) receipt keys and key order equal the old script's (pinned below; cross-checked with -# origin/main:tools/run_numeric_transc_gate.sh while main still has the old script); the sorted -# difference must be empty or listed in tests/chip_run_transc_receipt_allowlist.txt, and no stale -# allowlist entry may remain; (2) gcc source list equals the old script's; (3) refusal line and +# Checks: (1) old receipt keys keep their order, followed by authenticated +# canonical_source; sorted differences must exactly match the explicit allowlist +# (no stale entries); (2) canonical routing preserves old source order and adds +# exactly one generated unit; (3) refusal line and # exit code for an unknown op and for a missing physics checkout; (4) verdicts, console lines, # exit codes, receipt values, quiet flag, host tier refusal, fuser refusal. # Each check is also run against a mutated manifest and must fail there. @@ -35,9 +35,17 @@ FAILS=0 ok() { echo "PASS $1"; } bad() { echo "FAIL $1"; FAILS=$((FAILS + 1)); } FAKE_PHYS=/nonexistent-physics-for-test +# The fake Physics and prebuilt binary remain host fixtures; source provenance +# always uses the real authenticated stage and the actual seeded .om verifier. +canonical_stage=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} +case $canonical_stage in /*) ;; *) canonical_stage=$HERE/$canonical_stage;; esac +CUDAPP_STAGE=$(realpath -- "$canonical_stage") || exit 1 +export CUDAPP_STAGE +EXPECTED_CANONICAL=$(sh "$HERE/tools/cudapp-stage.sh" --verify "$HERE/cudapp.lock" "$CUDAPP_STAGE") || exit 1 # Pinned from the old script (origin/main before this change): receipt keys in order, gcc sources in order. OLD_KEYS="gate row reference omega_commit omega_tree_clean_before omega_tree_clean_after omega_commit_unchanged_after physics_commit physics_lock_pin physics_tree_clean_before physics_tree_clean_after physics_commit_unchanged_after binary_sha256 chip_log_sha256 kernels nvdisasm_check host_tier ops_requested ops chip_exit_status started_utc finished_utc verdict" +EXPECTED_KEYS="$OLD_KEYS canonical_source" OLD_SRCS="tests/test_omega_numeric_transc_gb10.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric_transc.c src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c $FAKE_PHYS/nvrm/nvrm.c $FAKE_PHYS/m16/m16_native.c" # Cross-check of the pins against the old script, only while origin/main still has it. @@ -84,6 +92,10 @@ build_world() { # MANIFEST git init -q "$OM" cp "$HERE/tools/chip_run.sh" "$HERE/tools/run_numeric_transc_gate.sh" "$OM/tools/" cp "$1" "$OM/tools/manifests/numeric_transc.chiprun" + mkdir -p "$OM/om" + cp "$HERE/tools/cudapp-stage.sh" "$HERE/tools/aienos_lock_source.sh" "$OM/tools/" || exit 1 + cp "$HERE/om/consumer.om" "$HERE/om/consumer_receipt.om" "$OM/om/" || exit 1 + cp "$HERE/cudapp.lock" "$OM/cudapp.lock" || exit 1 git -C "$PHYS" rev-parse HEAD > "$OM/physics.lock" echo "build/" > "$OM/.gitignore" printf '#!/bin/sh\nif [ "$1" = --digest ]; then printf "EXP2 12 aaaa\\nLOG2 34 bbbb\\n"; exit ${FAKE_DIGEST_RC:-0}; fi\necho "[PASS] fake host check"; echo "FAKE_HOST_LAST"; exit ${FAKE_HOST_RC:-0}\n' > "$OM/tools/fakehost.sh" @@ -119,6 +131,10 @@ suite() { has() { grep -Eq -- "$1" "$OUT"; } lacks() { ! grep -Eq -- "$1" "$OUT"; } rj() { [ -n "${R:-}" ] && jq -e "$1" "$R" > /dev/null 2>&1; } + canonical_matches() { + [ -n "${R:-}" ] && jq -e --argjson expected "$EXPECTED_CANONICAL" \ + '.canonical_source == $expected' "$R" > /dev/null 2>&1 + } # happy path, default ops through the wrapper runw happy -- ; HAPPY_R=$R @@ -134,12 +150,13 @@ suite() { ck happy_nvd rj '.nvdisasm_check == "nvdisasm fake provenance line"' ck happy_host_tier rj '.host_tier == "FAKE_HOST_LAST"' ck happy_gate_fields rj '.gate == "E1-TRANSC-GB10" and .verdict == "PASS" and .chip_exit_status == 0 and (.row | startswith("E1 gap table row 10")) and (.reference | startswith("omega_math_"))' + ck happy_canonical_source canonical_matches ck happy_flag_dropped test ! -e "$FLAG" ck happy_flag_owner grep -q 'flag=lane2 E1 transcendental GB10 chip run start=' "$W"/ev-happy/blobs/*.log ck happy_mode_0444 test "$(stat -c %a "$R" 2>/dev/null)" = 444 - # (1) receipt keys, ordered, equal the old script's + # The historical ordered prefix is unchanged; source provenance is explicit. jq -r 'keys_unsorted | join(" ")' "$HAPPY_R" > "$W/newkeys" 2>/dev/null - ck keys_ordered test "$(cat "$W/newkeys")" = "$OLD_KEYS" + ck keys_ordered test "$(cat "$W/newkeys")" = "$EXPECTED_KEYS" # (1b) sorted difference against the allowlist, both directions tr ' ' '\n' <<< "$OLD_KEYS" | sort > "$W/ko"; tr ' ' '\n' < "$W/newkeys" | sed '/^$/d' | sort > "$W/kn" { comm -13 "$W/ko" "$W/kn" | sed 's/^/+/'; comm -23 "$W/ko" "$W/kn" | sed 's/^/-/'; } | sort > "$W/diff" @@ -211,15 +228,32 @@ suite() { } # (2) gcc source list -load_list() { ( PHYSICS=$FAKE_PHYS; . "$1" 2>/dev/null || exit 1; read -ra A <<< "$TEST_SOURCE $SOURCES $EXTRA_BUILD_SOURCES"; echo "${A[*]}" ); } +load_list() { ( + PHYSICS=$FAKE_PHYS + . "$1" 2>/dev/null || exit 1 + [ "$PHYSICS" = "$FAKE_PHYS" ] && [ "$GPU_SOURCE_ROOT" = "$canonical_root" ] || exit 1 + read -ra A <<< "$TEST_SOURCE $SOURCES $EXTRA_BUILD_SOURCES" + local_list=(); generated=0; archives=0 + for s in "${A[@]}"; do + case $s in + "$canonical_root/src/cudapp_om_units.c") generated=$((generated + 1)); continue;; + "$canonical_stage/build/libcudapp.a") archives=$((archives + 1)); continue;; + "$canonical_root/src/"*) s=src/${s#"$canonical_root/src/"};; + "$canonical_root/nvrm/"*|"$canonical_root/m16/"*) s=$FAKE_PHYS/${s#"$canonical_root/"};; + esac + local_list+=("$s") + done + [ "$generated" = 1 ] && [ "$archives" = 1 ] || exit 1 + echo "${local_list[*]}" +); } suite "$MAN" > "$T/suite.out" cat "$T/suite.out"; grep -c '^FAIL' "$T/suite.out" > "$T/nfail"; FAILS=$((FAILS + $(cat "$T/nfail"))) [ "$(grep -c '^PASS' "$T/suite.out")" -ge 45 ] || bad "suite ran fewer than 45 checks" -[ "$(load_list "$MAN")" = "$OLD_SRCS" ] && ok "2 source list identical to old script" || bad "2 source list: $(load_list "$MAN")" +[ "$(load_list "$MAN")" = "$OLD_SRCS" ] && ok "2 canonical mapping preserves old source order plus one generated unit" || bad "2 source list: $(load_list "$MAN")" # every file the manifest names exists in the real tree -( PHYSICS=$FAKE_PHYS; . "$MAN"; for s in $TEST_SOURCE $SOURCES; do [ -f "$HERE/$s" ] || { echo "missing $s"; exit 1; }; done ) && ok "2b sources exist" || bad "2b a named source is missing" +( PHYSICS=$FAKE_PHYS; . "$MAN" || exit 1; for s in $TEST_SOURCE $SOURCES; do case $s in /*) ;; *) s=$HERE/$s;; esac; [ -s "$s" ] || { echo "missing $s"; exit 1; }; done ) && ok "2b sources exist" || bad "2b a named source is missing" # ---------- mutants: each manifest or wrapper change must make a named check fail ---------- mutant() { # NAME SED-EXPR EXPECTED-FAILING-ID @@ -247,12 +281,14 @@ mutant nohost "/^HOST_TIER_CMD=/,/^'\$/c\\HOST_TIER_CMD=true" hostfail_refusal mutant dirtyok 's/^REFUSE_DIRTY_OMEGA=1/REFUSE_DIRTY_OMEGA=0/' dirty_refusal mutant nonvd 's#^tools/divsqrt_nvdisasm_check.sh > #true > #' nvdfail_refusal mutant nokdig 's#^build/test_omega_numeric_transc_gb10_cpu --digest > .*#true#' happy_kernels +mutant missingprovenance '/^RECEIPT_EXTRA_JQ="\$RECEIPT_EXTRA_JQ |/d' happy_canonical_source +mutant alteredprovenance 's/canonical_source: \$canonical_metadata/canonical_source: null/' happy_canonical_source mutant nokdigcheck 's#^build/test_omega_numeric_transc_gb10_cpu --digest > \(.*\) || { echo "kernel digest failed"; exit 1; }$#build/test_omega_numeric_transc_gb10_cpu --digest > \1#' digfail_refusal mutant pass_loose "s/^PASS_LINE=.*/PASS_LINE='^VERDICT'/" notrun0_receipt sed 's#^SOURCES="src/omega_numeric_divsqrt_gb10.c #SOURCES="#' "$MAN" > "$T/m_dropsrc" sed 's#src/omega_om_units.c#src/sha256_nope.c#' "$MAN" > "$T/m_badfile" for m in m_dropsrc m_badfile; do [ "$(load_list "$T/$m")" = "$OLD_SRCS" ] && bad "mutant $m passed check 2" || ok "mutant $m fails check 2"; done -( PHYSICS=$FAKE_PHYS; . "$T/m_badfile"; for s in $TEST_SOURCE $SOURCES; do [ -f "$HERE/$s" ] || exit 1; done ) && bad "mutant badfile passed 2b" || ok "mutant badfile fails 2b" +( PHYSICS=$FAKE_PHYS; . "$T/m_badfile" || exit 1; for s in $TEST_SOURCE $SOURCES; do case $s in /*) ;; *) s=$HERE/$s;; esac; [ -s "$s" ] || exit 1; done ) && bad "mutant badfile passed 2b" || ok "mutant badfile fails 2b" [ "$FAILS" = 0 ] && { echo "CHIP_RUN_TRANSC_MANIFEST: PASS"; exit 0; } echo "CHIP_RUN_TRANSC_MANIFEST: FAIL ($FAILS)"; exit 1 diff --git a/tests/test_chip_run_trap_manifest.sh b/tests/test_chip_run_trap_manifest.sh index bef114f42..6ba6b7052 100755 --- a/tests/test_chip_run_trap_manifest.sh +++ b/tests/test_chip_run_trap_manifest.sh @@ -14,10 +14,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Host-only check of tools/manifests/unwritten_trap.chiprun and its wrapper. No GPU, no build. -# tests/test_chip_run_trap_manifest.sh -# Checks: (1) manifest sets every required variable and names only existing sources; -# (2) its gcc source list equals the old script's, pinned as a literal (git show 2dc9dd8:tools/run_unwritten_trap.sh); +# Host-only check of tools/manifests/unwritten_trap.chiprun and its wrapper. +# No GPU or chip build; stage authentication uses the actual seeded .om verifier. +# Checks: (1) required variables, exact provenance and nonempty sources; +# (2) canonical routing preserves the pinned old order plus one generated unit; # (3) the wrapper with a missing physics dir prints REFUSED and the NOT_RUN line, exit 2; # (4) the module gcc flags equal the old script's; (5) the wrapper passes exit 0/1/2 through; # (6) the manifest sets CHILD_EXIT_PASSTHROUGH=1 and the old default args. @@ -30,15 +30,41 @@ FAILS=0 ok() { echo "PASS $1"; } bad() { echo "FAIL $1"; FAILS=$((FAILS + 1)); } FAKE_PHYS=/nonexistent-physics-for-test +# Authentication is real even though the wrapper/device fixtures remain fake. +canonical_stage=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} +case $canonical_stage in /*) ;; *) canonical_stage=$HERE/$canonical_stage;; esac +CUDAPP_STAGE=$(realpath -- "$canonical_stage") || exit 1 +export CUDAPP_STAGE +EXPECTED_CANONICAL=$(sh "$HERE/tools/cudapp-stage.sh" --verify "$HERE/cudapp.lock" "$CUDAPP_STAGE") || exit 1 # Prints " " as one token per line, or fails. -load_list() { ( PHYSICS=$FAKE_PHYS; . "$1" 2>/dev/null || exit 1; read -ra A <<< "$TEST_SOURCE $SOURCES $EXTRA_BUILD_SOURCES"; printf '%s\n' "${A[@]}" ); } +load_list() { ( + PHYSICS=$FAKE_PHYS + . "$1" 2>/dev/null || exit 1 + [ "$PHYSICS" = "$FAKE_PHYS" ] && [ "$GPU_SOURCE_ROOT" = "$canonical_root" ] || exit 1 + read -ra A <<< "$TEST_SOURCE $SOURCES $EXTRA_BUILD_SOURCES" + generated=0; archives=0 + for s in "${A[@]}"; do + case $s in + "$canonical_root/src/cudapp_om_units.c") generated=$((generated + 1)); continue;; + "$canonical_stage/build/libcudapp.a") archives=$((archives + 1)); continue;; + "$canonical_root/src/"*) s=src/${s#"$canonical_root/src/"};; + "$canonical_root/nvrm/"*|"$canonical_root/m16/"*) s=$FAKE_PHYS/${s#"$canonical_root/"};; + esac + printf '%s\n' "$s" + done + [ "$generated" = 1 ] && [ "$archives" = 1 ] +); } check_vars() { ( PHYSICS=$FAKE_PHYS; . "$1" 2>/dev/null || exit 1 + [ "$PHYSICS" = "$FAKE_PHYS" ] && [ "$GPU_SOURCE_ROOT" = "$canonical_root" ] || exit 1 + actual=$(jq -cn "$RECEIPT_EXTRA_JQ") || exit 1 + jq -en --argjson actual "$actual" --argjson expected "$EXPECTED_CANONICAL" \ + '$actual.canonical_source == $expected' > /dev/null || exit 1 for v in GATE OWNER TEST_SOURCE SOURCES EXTRA_BUILD_SOURCES RUN_ARGS VERDICT_RE PASS_LINE EVIDENCE_DIR REFUSE_VERDICT_LINE REFUSE_EXIT REFUSE_DIRTY_OMEGA; do [ -n "${!v:-}" ] || { echo "unset $v"; exit 1; }; done [ "$REFUSE_EXIT" = 2 ] && [ "$REFUSE_VERDICT_LINE" = "OMEGA_UNWRITTEN_TRAP: NOT_RUN" ] && [ "$RUN_ARGS" = "--chip --repeats 3000" ] || { echo "old exit/line/args not kept"; exit 1; } [ "$EVIDENCE_DIR" = "$HOME/workspace/evidence-out/OMEGA-UNWRITTEN-TRAP" ] && [ "${REQUIRE_ALL_PASS:-}" = 0 ] && [ "${CHILD_EXIT_PASSTHROUGH:-}" = 1 ] || { echo "evidence dir, REQUIRE_ALL_PASS or CHILD_EXIT_PASSTHROUGH wrong"; exit 1; } - for s in $TEST_SOURCE $SOURCES; do [ -f "$HERE/$s" ] || { echo "missing $s"; exit 1; }; done ); } + for s in $TEST_SOURCE $SOURCES; do case $s in /*) ;; *) s=$HERE/$s;; esac; [ -s "$s" ] || { echo "missing $s"; exit 1; }; done ); } # Old script, pinned as literals. Source: git show 2dc9dd8:tools/run_unwritten_trap.sh (the last # commit before the wrapper replaced it). origin/main no longer holds it once the wrapper merges. OLD_LIST='tests/test_omega_unwritten_trap_gb10.c @@ -74,9 +100,11 @@ check_list_matches_old() { printf '%s\n' "$OLD_LIST" > "$T/old.list" load_list "$1" > "$T/new.list" || { echo "manifest failed to load"; return 1; } diff "$T/old.list" "$T/new.list" > "$T/diff.out" || { cat "$T/diff.out"; return 1; }; } -# $1 = a copy of tools/chip_run.sh. Its gcc flags must equal OLD_FLAGS. +# Compiler options stay fixed; only authenticated source/header routing changes. check_flags_match_old() { - sed -n '/gcc -std=gnu11/,/-o "\$BIN"/p' "$1" | tr -s ' \\\n' '\n\n\n' | grep -E '^-' | grep -vx -- '-o' > "$T/new.flags" + sed -n '/gcc -std=gnu11/,/-o "\$BIN"/p' "$1" | tr -s ' \\\n' '\n\n\n' | grep -E '^-' | grep -vx -- '-o' > "$T/routed.flags" + grep -Fx -- '-I"$GPU_SOURCE_ROOT/src"' "$T/routed.flags" > /dev/null || return 1 + sed '/^-I"\$GPU_SOURCE_ROOT\/src"$/d; s/\$GPU_SOURCE_ROOT/\$PHYSICS/g' "$T/routed.flags" > "$T/new.flags" printf '%s\n' "$OLD_FLAGS" > "$T/old.flags" [ -s "$T/new.flags" ] || { echo "no gcc line found"; return 1; } diff "$T/old.flags" "$T/new.flags" > "$T/diff.out" || { cat "$T/diff.out"; return 1; }; } @@ -95,15 +123,17 @@ sed 's#^REFUSE_EXIT=2#REFUSE_EXIT=1#' "$MAN" > "$T/m_exit" sed "s#evidence-out/OMEGA-UNWRITTEN-TRAP#evidence/unwritten_trap#" "$MAN" > "$T/m_evid" sed '/^CHILD_EXIT_PASSTHROUGH=/d' "$MAN" > "$T/m_nopass" sed 's#^RUN_ARGS="--chip --repeats 3000"#RUN_ARGS="--chip --repeats 300"#' "$MAN" > "$T/m_args" +sed '/^RECEIPT_EXTRA_JQ=/d' "$MAN" > "$T/m_noprovenance" +sed 's/canonical_source: \$canonical_metadata/canonical_source: null/' "$MAN" > "$T/m_badprovenance" sed 's#-Werror #-Wno-error #' "$HERE/tools/chip_run.sh" > "$T/cr_noerror" sed 's#-O2 #-O3 #' "$HERE/tools/chip_run.sh" > "$T/cr_o3" sed 's#-fno-fast-math ##' "$HERE/tools/chip_run.sh" > "$T/cr_fastmath" sed 's#^exec \(.*\)$#\1; [ $? = 0 ] || exit 1#' "$HERE/tools/run_unwritten_trap.sh" > "$T/w_map" check_vars "$MAN" > "$T/o" 2>&1 && ok "1 manifest variables and source files" || { bad "1 manifest variables and source files: $(cat "$T/o")"; } -check_list_matches_old "$MAN" > "$T/o" 2>&1 && ok "2 source list identical to old script" || bad "2 source list identical to old script: $(cat "$T/o")" +check_list_matches_old "$MAN" > "$T/o" 2>&1 && ok "2 canonical mapping preserves old source order plus one generated unit" || bad "2 canonical source mapping: $(cat "$T/o")" -for m in m_novar m_badfile m_exit m_evid m_nopass m_args; do check_vars "$T/$m" > /dev/null 2>&1 && bad "mutant $m passed check 1" || ok "mutant $m fails check 1"; done +for m in m_novar m_badfile m_exit m_evid m_nopass m_args m_noprovenance m_badprovenance; do check_vars "$T/$m" > /dev/null 2>&1 && bad "mutant $m passed check 1" || ok "mutant $m fails check 1"; done for m in m_dropsrc m_badfile; do check_list_matches_old "$T/$m" > /dev/null 2>&1 && bad "mutant $m passed check 2" || ok "mutant $m fails check 2"; done check_flags_match_old "$HERE/tools/chip_run.sh" > "$T/o" 2>&1 && ok "4 module gcc flags identical to old script" || bad "4 module gcc flags identical to old script: $(cat "$T/o")" diff --git a/tools/.crumb b/tools/.crumb index 5f1a7214f..4531fc83d 100644 --- a/tools/.crumb +++ b/tools/.crumb @@ -26,50 +26,50 @@ "children": [ { "digest": "9f82d33852a7cdcedb210ee1525f42c4d963c18940cae1df7f69d1210de71985", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "argus", "purpose": "Directory tools/argus. Purpose not yet described by a human." }, { "digest": "4b3a030252eaa6f1c693105a76092e8a5fccfd340658a982f5bb1130ce9aba33", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "brownian", "purpose": "Directory tools/brownian. Purpose not yet described by a human." }, { "digest": "1d21e7e466d0fd96abf30d11b2d7e45718bc42ada1784bc8bc2a749f541b3ab7", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "dual_experiment", "purpose": "Runner for the DUAL applicability experiment: runs the pre-registered campaign and writes result" }, { "digest": "2a1bd46e9c9502d02144e3f76c784863001323c564a22bdae2905c0660a5f7a4", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "estimation", "purpose": "Directory tools/estimation. Purpose not yet described by a human." }, { "digest": "b3241d8cdc884bbfcca5cf9d5f4ed0aac8f7e2df43d9ab47ca2789432dd49a75", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "reservoir", "purpose": "Gate 2 tooling for the reservoir (omega#440): in-house zlib inflate and MAT v5 reader, the archi" }, { "digest": "f1a1a7f24d51a52f01171d01edbd59e8b15c53b15eeffb97e3c0ffc553e639af", - "last_commit": "d863780eb", + "last_commit": "d863780e", "name": "turing_verify_indep", "purpose": "Directory tools/turing_verify_indep. Purpose not yet described by a human." } ], "children_root": "sha256:8d3d3b952374b3b72e667521f07bf028c4c02bcefff772ad1a71cfff3e5266f2", - "compiled_at": "2026-10-28T02:06:07Z", + "compiled_at": "2026-10-28T20:28:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:4e83dea21da137c30076c2dc0ca4f3a488f576f30a94e334558ad5ea523f3a6b", + "digest": "sha256:1a49f30057f97de35b3a9ea43e4d964ec9a2211294b12ffe8ed08abe80c2ba1e", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 295, - "generated_at_commit": "82509c4f949504dc63f13371607b211c14cdee74", - "source_tree": "sha256:319916f06e7ad69219b50ea9df5420b8baec42170d0ba675632059208dda0949" + "files": 296, + "generated_at_commit": "cafb7be08e4a92d6dd7347b011a833f524140dee", + "source_tree": "sha256:e817d276fdf0c70086bce9e07b9f4560a14aeed7aadb47ccf733e5205cd522da" }, "owner_lane": "", "provenance": { diff --git a/tools/autodiff_mutations.sh b/tools/autodiff_mutations.sh index d448ab7e0..9fecd621f 100755 --- a/tools/autodiff_mutations.sh +++ b/tools/autodiff_mutations.sh @@ -24,10 +24,12 @@ set -u cd "$(dirname "$0")/.." || exit 2 SCRATCH=$(mktemp -d "${TMPDIR:-/tmp}/autodiff-mut.XXXXXX") || exit 2 trap 'rm -rf "$SCRATCH"' EXIT INT TERM +bash tools/e1_manifest.sh --canonical-overlay "$SCRATCH/source" >/dev/null || exit 2 +cat "$SCRATCH/source/cudapp-source.json" >&2 TENSOR="src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c src/tensor/omega_tensor_reduce_seam.c \ src/omega_numeric_reduce.c src/omega_numeric_transc.c" DEPS="src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c \ -src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c" +src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c src/cudapp_om_units.c" FLAGS="-std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -O2 -DOMEGA_NUMERIC_CPU_ONLY" # name|file|sed expression (applied only to the line carrying MUT:) @@ -54,8 +56,9 @@ DIV_FORMULA|omega_autodiff.c|{s/OMEGA_TB_DIV, n->value, nb->value, &tmp)/OMEGA_T BUILD="gcc $FLAGS -Isrc -Isrc/tensor -Isrc/autodiff -o t tests/test_omega_autodiff.c src/autodiff/omega_autodiff.c \ $TENSOR $DEPS" printf '%s\n' "$MUTATIONS" | sed 's#^\([A-Z_]*\)|#\1|src/autodiff/#' > "$SCRATCH/rows" -tools/mutation_runner.sh -k marker -m "$SCRATCH/rows" -d . -c "src tests/test_omega_autodiff.c" \ +tools/mutation_runner.sh -k marker -m "$SCRATCH/rows" -d "$SCRATCH/source" -c "src tests/test_omega_autodiff.c" \ -b "$BUILD" -t ./t -f FAIL -B > "$SCRATCH/runner.out" 2> "$SCRATCH/runner.err" +runner_rc=$? if grep -q 'unmutated baseline' "$SCRATCH/runner.out"; then cat "$SCRATCH/runner.err" echo "autodiff mutation sweep: FAIL (unmutated baseline does not pass)"; exit 1 @@ -86,5 +89,6 @@ while IFS= read -r line; do esac done < "$SCRATCH/runner.err" if [ "$total" -lt 5 ]; then echo "autodiff mutation sweep: FAIL (fewer than 5 mutations)"; exit 1; fi +if [ "$runner_rc" -ne 0 ]; then cat "$SCRATCH/runner.err"; echo "autodiff mutation sweep: FAIL (runner error)"; exit 1; fi if [ "$fail" -ne 0 ]; then echo "autodiff mutation sweep: FAIL"; exit 1; fi echo "autodiff mutation sweep: PASS ($total of $total mutations caught)" diff --git a/tools/chip_run.sh b/tools/chip_run.sh index 67547f7f7..45c186563 100755 --- a/tools/chip_run.sh +++ b/tools/chip_run.sh @@ -20,6 +20,8 @@ # The gcc line is the transc/unwritten-trap one; reduce differs (see NOT COVERED). # MANIFEST is shell syntax setting: GATE TEST_SOURCE SOURCES EXTRA_BUILD_SOURCES (relative # to the omega root, may use $PHYSICS and $HERE) RUN_ARGS VERDICT_RE PASS_LINE OWNER +# GPU_SOURCE_ROOT (native headers/driver closure; defaults to the independently +# pinned Physics checkout; canonical manifests authenticate their CUDApp root) # EVIDENCE_DIR RAISE_QUIET TAKE_GPU_LOCK REFUSE_DIRTY_OMEGA (default 1) REFUSE_EXIT # (default 2; must be an integer 1..125, else exit 1 "CHIP_RUN: BAD_MANIFEST") REFUSE_VERDICT_LINE # (default "CHIP_RUN: NOT_RUN") REQUIRE_ALL_PASS (default 0; 0 or 1; when 1 EVERY line matching @@ -136,6 +138,7 @@ seam_check # REFUSAL:seam_before # Physics dir resolution lives here and nowhere else. PHYSICS=${PHYS_FLAG:-${PHYSICS_DIR:-${PHYSICS:-$HOME/workspace/physics}}} PHYSICS=$(realpath -m "$PHYSICS") +GPU_SOURCE_ROOT=$PHYSICS GATE=""; TEST_SOURCE=""; SOURCES=""; EXTRA_BUILD_SOURCES=""; RUN_ARGS=""; VERDICT_RE=""; PASS_LINE="" OWNER=""; EVIDENCE_DIR=""; RAISE_QUIET=1; TAKE_GPU_LOCK=1; REFUSE_DIRTY_OMEGA=1; HOST_TIER_CMD=""; RECEIPT_EXTRA_JQ=""; REQUIRE_ALL_PASS=0; CHILD_EXIT_PASSTHROUGH=0; ECHO_RE=""; GPU_LOCK_MODE=flock @@ -205,9 +208,9 @@ else BIN=$RUN/$GATE.bin read -ra SRCS <<< "$TEST_SOURCE $SOURCES $EXTRA_BUILD_SOURCES" for s in "${SRCS[@]}"; do case $s in /*) f=$s ;; *) f=$HERE/$s ;; esac; [ -f "$f" ] || refuse "missing source $s"; done # REFUSAL:missing_source - NV=$PHYSICS/$NVDIR + NV=$GPU_SOURCE_ROOT/$NVDIR (cd "$HERE" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -fno-fast-math -pthread \ - -Isrc -I"$PHYSICS/nvrm" -I"$PHYSICS/m16" \ + -I"$GPU_SOURCE_ROOT/src" -Isrc -I"$GPU_SOURCE_ROOT/nvrm" -I"$GPU_SOURCE_ROOT/m16" \ -I"$NV/src/common/sdk/nvidia/inc" -I"$NV/kernel-open/common/inc" \ -I"$NV/kernel-open/nvidia-uvm" -I"$NV/src/nvidia/arch/nvalloc/unix/include" \ -o "$BIN" "${SRCS[@]}") > "$RUN/chip-build.log" 2>&1; BRC=$? diff --git a/tools/cudapp-stage.sh b/tools/cudapp-stage.sh new file mode 100755 index 000000000..0dfd9feb6 --- /dev/null +++ b/tools/cudapp-stage.sh @@ -0,0 +1,90 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# Host I/O/build glue only. Pin policy is the seeded om/consumer.om program. +set -eu +export GIT_NO_REPLACE_OBJECTS=1 GIT_GRAFT_FILE=/nonexistent/cudapp-stage-grafts +if [ "$#" != 3 ]; then + echo 'usage: cudapp-stage.sh LOCK CHECKOUT OUTPUT_LINK | --verify LOCK STAGE | --source LOCK STAGE' >&2 + exit 3 +fi +: "${OMEGA_OMC:?set OMEGA_OMC to the pinned seeded compiler}" +: "${OMEGA_BRIDGE:?set OMEGA_BRIDGE to the pinned bridge checkout}" +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +printf '%s %s\n' 2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f "$OMEGA_OMC" | sha256sum -c - >&2 +# Reuse the existing raw-object read-only checker, including every actual and +# expected top-level entry. Build outputs live outside this pristine source. +verify_source() { + checked_lock=$1 checked_stage=$2 checked_work=$3 + IFS= read -r repository < "$checked_stage/repository" + IFS= read -r revision < "$checked_stage/observed" + git -C "$repository" ls-tree -z --name-only "$revision" > "$checked_work/expected-roots" + find "$checked_stage/source" -mindepth 1 -maxdepth 1 -printf '%f\0' > "$checked_work/actual-roots" + LC_ALL=C sort -zu "$checked_work/expected-roots" "$checked_work/actual-roots" > "$checked_work/roots" + test -s "$checked_work/roots" + xargs -0 env AIENOS_LOCK= AIENOS_LOCK_FILE="$checked_lock" AIENOS_LOCK_REPO="$repository" \ + bash "$root/tools/aienos_lock_source.sh" verify-dir "$checked_stage/source" < "$checked_work/roots" +} +if [ "$1" = --verify ] || [ "$1" = --source ]; then + mode=$1 + lock=$(realpath -- "$2") + stage=$(realpath -- "$3") + work=$(mktemp -d) + trap 'rm -rf -- "$work"' EXIT HUP INT TERM + "$OMEGA_OMC" < "$root/om/consumer.om" > "$work/pincheck" + chmod 700 "$work/pincheck" + cat "$lock" "$stage/pin" > "$work/pair" + "$work/pincheck" < "$work/pair" + cat "$lock" "$stage/observed" > "$work/pair" + "$work/pincheck" < "$work/pair" + verify_source "$lock" "$stage" "$work" >&2 + sha256sum -c "$stage/source.sha256" "$stage/guard.sha256" "$stage/archive.sha256" >&2 + if [ "$mode" = --source ]; then + printf '%s\n' "$stage/source" + else + "$OMEGA_OMC" < "$root/om/consumer_receipt.om" > "$work/receipt" + chmod 700 "$work/receipt" + { cat "$lock"; sha256sum "$stage/source.tar" "$work/pincheck" "$stage/build/libcudapp.a" | cut -c1-64; + printf '%s\n' "$stage/source"; } | "$work/receipt" + fi + exit 0 +fi +lock=$1 +checkout=$2 +output=$3 +mkdir -p -- "$(dirname -- "$output")" +parent=$(CDPATH= cd -- "$(dirname -- "$output")" && pwd) +output=$parent/$(basename -- "$output") +if [ -e "$output" ] || [ -L "$output" ]; then + if [ ! -L "$output" ]; then + echo 'cudapp-stage: output exists and is not a generated snapshot link' >&2 + exit 3 + fi +fi +stage=$(mktemp -d "$parent/.cudapp-stage.XXXXXX") +link=$stage.publish +trap 'rm -f -- "$link"; rm -rf -- "$stage"' EXIT HUP INT TERM +cp -- "$lock" "$stage/pin" +printf '%s\n' "$(CDPATH= cd -- "$checkout" && pwd)" > "$stage/repository" +git -C "$checkout" rev-parse HEAD > "$stage/observed" +cat "$stage/pin" "$stage/observed" > "$stage/guard-input" +"$OMEGA_OMC" < "$root/om/consumer.om" > "$stage/pincheck" +chmod 700 "$stage/pincheck" +"$stage/pincheck" < "$stage/guard-input" +# Read only the revision already frozen and accepted by the .om guard. +IFS= read -r revision < "$stage/observed" +git -C "$checkout" archive --format=tar "$revision" > "$stage/source.tar" +mkdir "$stage/source" +tar -xf "$stage/source.tar" -C "$stage/source" +verify_source "$stage/pin" "$stage" "$stage" >&2 +sh "$stage/source/om/units.sh" --check +# Build only the authenticated tree: no inherited MAKEFLAGS/PHYSICS_DIR/CFLAGS/CC may +# substitute another driver client or flags (a parent make passes PHYSICS_DIR via MAKEFLAGS). +env -i PATH="$PATH" make -C "$stage/source" PHYSICS_DIR=. OUT_DIR="$stage/build" CC=cc CUDAPP_ENCODER=om all +sha256sum "$stage/source.tar" > "$stage/source.sha256" +sha256sum "$stage/pincheck" > "$stage/guard.sha256" +sha256sum "$stage/build/libcudapp.a" > "$stage/archive.sha256" +cat "$stage/source.sha256" "$stage/guard.sha256" "$stage/archive.sha256" > "$stage/hashes" +ln -s -- "$stage" "$link" +mv -T -- "$link" "$output" +trap - EXIT HUP INT TERM +printf '%s\n' "$stage" diff --git a/tools/divsqrt_check_sweep.sh b/tools/divsqrt_check_sweep.sh index cd4c48f98..37a863012 100755 --- a/tools/divsqrt_check_sweep.sh +++ b/tools/divsqrt_check_sweep.sh @@ -26,22 +26,26 @@ # Run: make test-divsqrt-sweep (or run this file). set -u HERE=$(cd -P "$(dirname "$0")/.." && pwd) -SRC=$HERE/src/omega_numeric_divsqrt_gb10.c TMP=$(mktemp -d) trap 'rm -rf "$TMP"' EXIT +bash "$HERE/tools/e1_manifest.sh" --canonical-overlay "$TMP/source" >/dev/null || exit 2 +cat "$TMP/source/cudapp-source.json" >&2 +SRC=$TMP/source/src/omega_numeric_divsqrt_gb10.c +[ -s "$SRC" ] || exit 2 OTHER="tests/test_omega_divsqrt_gb10.c src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c - src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c" -names=$(grep -o '/\* CHECK:[a-z0-9_]* \*/' "$SRC" | sed 's|/\* CHECK:\([a-z0-9_]*\) \*/|\1|') + src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c src/cudapp_om_units.c" +grep -o '/\* CHECK:[a-z0-9_]* \*/' "$SRC" > "$TMP/markers" || { echo "scanner failed or no CHECK markers" >&2; exit 2; } +names=$(sed 's|/\* CHECK:\([a-z0-9_]*\) \*/|\1|' "$TMP/markers") || exit 2 total=0 killed=0 survived=0 broken=0 for name in $names; do total=$((total + 1)) mut=$TMP/omega_numeric_divsqrt_gb10.c - grep -v "/\* CHECK:$name \*/" "$SRC" > "$mut" + grep -v "/\* CHECK:$name \*/" "$SRC" > "$mut" || { echo "source scanner failed" >&2; exit 2; } if [ "$(wc -l < "$SRC")" -ne $(( $(wc -l < "$mut") + 1 )) ]; then echo " [BROKEN] $name: marker is not on exactly one line"; broken=$((broken + 1)); continue fi # shellcheck disable=SC2086 - if ! (cd "$HERE" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc -pthread \ + if ! (cd "$TMP/source" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc -pthread \ -Wno-unused-variable -Wno-unused-but-set-variable -Wno-unused-parameter \ -DOMEGA_NUMERIC_CPU_ONLY -o "$TMP/t" "$mut" $OTHER) > "$TMP/build.log" 2>&1; then echo " [BROKEN] $name: scratch copy does not build"; broken=$((broken + 1)); continue diff --git a/tools/e1_host_rerun.sh b/tools/e1_host_rerun.sh index 9fde999ca..a1517751f 100755 --- a/tools/e1_host_rerun.sh +++ b/tools/e1_host_rerun.sh @@ -32,13 +32,16 @@ HERE=$(cd -P "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) LINES="GB10-COMPILE NUMERIC-HOST PROGRAM TRANSC MANIFEST HOSTALL" run_all() { - local L=$1 PHYS=${2:-${PHYSICS_DIR:-}} NV name s r + local L=$1 PHYS=${2:-${PHYSICS_DIR:-}} name s r [ -n "$PHYS" ] && [ -d "$PHYS/nvrm" ] || { echo "run: need PHYSICS_DIR (a checkout of aien-dev/physics at physics.lock)" >&2; exit 2; } - NV=$PHYS/third_party/nvidia-open-580.173.02 + local stage canonical + stage=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} + case $stage in /*) ;; *) stage=$HERE/$stage;; esac + canonical=$(sh "$HERE/tools/cudapp-stage.sh" --source "$HERE/cudapp.lock" "$stage") || exit 2 mkdir -p "$L"; cd "$HERE" || exit 2 echo "HEAD $(git rev-parse HEAD) dirty_tracked=$(git status --porcelain --untracked-files=no | wc -l) start $(date -u +%FT%TZ)" > "$L/summary.txt" run() { name=$1; shift; s=$(date +%s); if bash -c "$*" > "$L/$name.log" 2>&1; then r=PASS; else r="FAIL(rc=$?)"; fi; echo "$name: $r ($(( $(date +%s) - s ))s)" >> "$L/summary.txt"; } - run GB10-COMPILE "D=\$(mktemp -d /tmp/e1r-compile.XXXXXX); rc=0; for v in -DE1N_NONE -DOMEGA_C3_PROTECT_OFF; do for f in tests/test_omega_c3_ab_gb10.c src/omega_numeric_gb10.c src/omega_numeric_reduce_gb10.c src/omega_numeric_ldst_gb10.c src/omega_numeric_divsqrt_gb10.c; do gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -fno-fast-math -pthread -Isrc -I$PHYS/nvrm -I$PHYS/m16 -I$NV/src/common/sdk/nvidia/inc -I$NV/kernel-open/common/inc -I$NV/kernel-open/nvidia-uvm -I$NV/src/nvidia/arch/nvalloc/unix/include \$v -c \$f -o \$D/x.o || { echo COMPILE_FAIL \$v \$f; rc=1; }; done; done; rm -rf \$D; test \$rc = 0 && echo GB10_COMPILE_OK; exit \$rc" + run GB10-COMPILE "D=\$(mktemp -d /tmp/e1r-compile.XXXXXX); rc=0; for v in -DE1N_NONE -DOMEGA_C3_PROTECT_OFF; do for f in tests/test_omega_c3_ab_gb10.c src/omega_numeric_gb10.c src/omega_numeric_reduce_gb10.c src/omega_numeric_ldst_gb10.c src/omega_numeric_divsqrt_gb10.c; do gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -fno-fast-math -pthread -I\"$canonical/src\" -Isrc -I\"$canonical/nvrm\" -I\"$canonical/m16\" -I\"$canonical/third_party/nvidia-open-580.173.02/src/common/sdk/nvidia/inc\" -I\"$canonical/third_party/nvidia-open-580.173.02/kernel-open/common/inc\" -I\"$canonical/third_party/nvidia-open-580.173.02/kernel-open/nvidia-uvm\" -I\"$canonical/third_party/nvidia-open-580.173.02/src/nvidia/arch/nvalloc/unix/include\" \$v -c \$f -o \$D/x.o || { echo COMPILE_FAIL \$v \$f; rc=1; }; done; done; rm -rf \$D; test \$rc = 0 && echo GB10_COMPILE_OK; exit \$rc" run NUMERIC-HOST "make -k PHYSICS_DIR=$PHYS test-numeric-cpu test-numeric-transc-gb10-host test-divsqrt-host test-divsqrt-nvdisasm test-numeric-reduce-cpu test-numeric-reduce-nvdisasm test-ldst-host test-ldst-nvdisasm" run PROGRAM "make -k PHYSICS_DIR=$PHYS test-program-fp32 test-program-realize test-program-id test-visor-core" run TRANSC "make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-numeric-transc test-numeric-transc-digest test-numeric-transc-full" diff --git a/tools/e1_manifest.sh b/tools/e1_manifest.sh index 9b80a808f..5e40637ef 100755 --- a/tools/e1_manifest.sh +++ b/tools/e1_manifest.sh @@ -33,7 +33,111 @@ # tier was rerun on main (tools/e1_combine.sh enforces this) # # Shell + git + coreutils + jq + gcc. No Python. -set -u +# Shared canonical consumer adapter. The stage guard owns authentication; this +# adapter only composes a disposable mutation tree, never a second authority. +# Extension proposal (source pin 6999fa9e): seeded .om has bounded byte I/O +# and process words but no regex rewrite primitive used by mutation_runner. +# Add `textedit input(view uchar N), size(ulong), pattern(view uchar P), +# replacement(view uchar R), output(edit uchar N) -> long`, with an explicit +# bounded POSIX-BRE subset and exact-one-match policy. Return output length; +# refuse malformed pattern (-22), zero/multiple matches (-61), overflow (-28), +# and unsupported backreferences (-95). No implicit shell or regex host call. +# Gate against retained sed/perl read-only oracles at recorded versions, with +# zero/two-match, bad-pattern, overflow and scanner read-error controls. +# Then implement a seeded .om conductor using fork/exec packed argv, directory +# traversal and SHA-256 units, preserving runner exit and baseline semantics. +# Until that lands, bash/git/coreutils/jq/gcc and runner sed/perl/awk remain +# explicit host dependencies, not an Omega implementation. +# Snapshot only authenticated canonical inputs for the chip receipt collectors. +# This mode never builds a binary, takes a GPU lock or opens a device. +if [ "${1:-}" = --canonical-evidence ]; then + set -eu + root=$(cd -P "$(dirname "$0")/.." && pwd) + stage=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} + case $stage in /*) ;; *) stage=$root/$stage;; esac + metadata=$(sh "$root/tools/cudapp-stage.sh" --verify "$root/cudapp.lock" "$stage") + [ -n "$metadata" ] + source=$(cd -P "$stage/source" && pwd) + target=${2:?evidence directory required} + shift 2 + [ "$#" -gt 0 ] + mkdir -p "$target" + for input in "$@"; do + case $input in src/*.[ch]) ;; *) echo "invalid canonical source: $input" >&2; exit 2;; esac + case $input in */../*|*/./*) exit 2;; esac + [ -s "$source/$input" ] && [ -f "$source/$input" ] || { + echo "missing or empty canonical source: $input" >&2; exit 2; + } + cp -- "$source/$input" "$target/" + done + [ -s "$stage/source.tar" ] + cp -- "$stage/source.tar" "$target/cudapp-source.tar" + cp -- "$stage/pin" "$target/cudapp.pin" + for oracle in bash git sha256sum gcc make; do + "$oracle" --version > "$target/$oracle.version" 2>&1 + [ -s "$target/$oracle.version" ] + done + printf '%s\n' "$metadata" > "$target/CUDAPP-SOURCE.json" + exit 0 +fi +if [ "${1:-}" = --canonical-overlay ]; then + set -eu + root=$(cd -P "$(dirname "$0")/.." && pwd) + target=${2:?missing disposable output directory} + stage=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} + case $stage in /*) ;; *) stage=$root/$stage;; esac + metadata=$(sh "$root/tools/cudapp-stage.sh" --verify "$root/cudapp.lock" "$stage") + source=$(cd -P "$stage/source" && pwd) + [ -d "$source/src" ] && [ -s "$source/src/cudapp_om_units.c" ] || exit 2 + for required in omega_gpu_engine.c omega_gpu_engine.h omega_numeric.c omega_numeric.h \ + omega_numeric_reduce.c omega_blackwell_codegen.c omega_blackwell_codegen.h \ + omega_blackwell_encoder.c omega_blackwell_encoder.h omega_blackwell_matmul.c \ + omega_blackwell_matmul.h omega_blackwell_qmd.c omega_blackwell_qmd.h \ + omega_blackwell_engine.c omega_blackwell_engine.h omega_blackwell_submit.c \ + omega_blackwell_submit.h omega_blackwell_realize.c cudapp_om_units.c; do + [ -s "$source/src/$required" ] || { + echo "canonical source closure missing required member: $required" >&2; exit 2; + } + done + mkdir -p "$target" + cp -R "$source/src" "$target/" + # Retained Omega CPU/adapters keep ownership; retired GPU paths no longer + # exist here and therefore remain the authenticated canonical versions. + cp -R "$root/src/." "$target/src/" + # Canonical GPU translation units use the public SHA facade, not Omega's + # generated CPU declaration header (whose native ABI guard is independent). + # The unchanged Omega binding remains the linked SHA implementation. + cp -- "$source/src/sha256.h" "$target/src/sha256.h" + cp -R "$root/tests" "$target/" + # Capture each oracle's version as a checked command, not a command + # substitution whose failure jq could otherwise mask. + oracle_version() { + local name=$1; shift + "$@" > "$target/$name.version" 2>&1 + [ -s "$target/$name.version" ] + } + oracle_version bash bash --version + oracle_version git git --version + oracle_version coreutils sha256sum --version + oracle_version jq jq --version + oracle_version gcc gcc --version + oracle_version sed sed --version + oracle_version perl perl -v + oracle_version awk awk -W version + printf '%s\n' "$metadata" | jq -e ' + . + {host_dependencies: { + bash: $bash, git: $git, coreutils: $coreutils, jq: $jq, gcc: $gcc, + sed: $sed, perl: $perl, awk: $awk}, + omega_replacement: "bounded seeded .om conductor; proposal in tools/e1_manifest.sh"} + ' --rawfile bash "$target/bash.version" --rawfile git "$target/git.version" \ + --rawfile coreutils "$target/coreutils.version" --rawfile jq "$target/jq.version" \ + --rawfile gcc "$target/gcc.version" --rawfile sed "$target/sed.version" \ + --rawfile perl "$target/perl.version" --rawfile awk "$target/awk.version" > "$target/cudapp-source.json" + printf '%s\n' "$target" + exit 0 +fi +set -eu +set -o pipefail HERE=$(cd -P "$(dirname "$0")/.." && pwd) CAND= MAIN= PHYS= OUT= while [ $# -gt 0 ]; do @@ -49,6 +153,13 @@ done cd "$HERE" || exit 2 git cat-file -e "$CAND^{commit}" 2>/dev/null || { echo "unknown commit $CAND" >&2; exit 2; } git cat-file -e "$MAIN^{commit}" 2>/dev/null || { echo "unknown commit $MAIN" >&2; exit 2; } +STAGE=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} +CANONICAL=$(sh tools/cudapp-stage.sh --verify cudapp.lock "$STAGE") || exit 2 +SOURCE=$(cd -P "$STAGE/source" && pwd) +for revision in "$CAND" "$MAIN"; do + git show "$revision:cudapp.lock" | cmp - "$STAGE/pin" || + { echo "comparison requires the exact staged CUDApp pin at both revisions" >&2; exit 2; } +done # Chip-class patterns: sources of the four chip binaries (Gate 5, reduce, ldst, # transc), the chip gate scripts and manifests, the physics pin. Host-class: @@ -56,14 +167,23 @@ git cat-file -e "$MAIN^{commit}" 2>/dev/null || { echo "unknown commit $MAIN" >& CHIP_RE='^(src/omega_numeric.*|src/omega_blackwell_(codegen|encoder|matmul|qmd)\.[ch]|src/forge_realization\.[ch]|src/aegis_verification\.[ch]|src/sha256\.[ch]|src/omega_program_fp32\.[ch]|src/omega_unwritten_trap.*|tests/test_omega_numeric.*|tests/test_omega_reduce\.c|tests/test_omega_ldst_gb10\.c|tests/test_omega_divsqrt_gb10\.c|tests/numeric_oracle\.h|tests/tensor_reduce_multi_tests\.inc|tests/numeric_native/.*|tests/run_numeric_gates\.sh|tests/run_reduce_chip\.sh|tests/chip_run_transc_receipt_allowlist\.txt|tools/chip_run\.sh|tools/run_numeric_ldst_chip\.sh|tools/run_numeric_transc_gate\.sh|tools/run_divsqrt_gate\.sh|tools/run_unwritten_trap\.sh|tools/ldst_nvdisasm_check\.sh|tools/divsqrt_nvdisasm_check\.sh|tools/manifests/.*|physics\.lock)$' HOST_RE='^(Makefile|mk/numeric-.*\.mk|mk/program-fp32\.mk|tests/test_omega_transc\.c|tests/test_numeric_lifecycle\.c|tests/test_omega_unwritten_trap\.c|tests/test_chip_run.*\.sh|tools/numeric_check_sweep\.sh|tools/divsqrt_check_sweep\.sh)$' -sha_at() { git cat-file -e "$1:$2" 2>/dev/null && git show "$1:$2" | sha256sum | cut -c1-64 || echo ABSENT; } +sha_at() { + if git cat-file -e "$1:$2" 2>/dev/null; then + git show "$1:$2" | sha256sum | cut -c1-64 + else printf '%s\n' ABSENT; fi +} files=$( (git ls-tree -r --name-only "$CAND"; git ls-tree -r --name-only "$MAIN") | sort -u | grep -E "$CHIP_RE|$HOST_RE") +[ -n "$files" ] || { echo "empty artifact read set" >&2; exit 2; } entries= n_eq=0 n_ne=0 chip_ne=0 for f in $files; do a=$(sha_at "$CAND" "$f"); b=$(sha_at "$MAIN" "$f") if echo "$f" | grep -Eq "$CHIP_RE"; then cls=chip; else cls=host; fi - if [ "$a" = "$b" ]; then eq=true; n_eq=$((n_eq+1)); else eq=false; n_ne=$((n_ne+1)); [ $cls = chip ] && chip_ne=$((chip_ne+1)); fi + if [ "$a" = "$b" ]; then eq=true; n_eq=$((n_eq+1)) + else + eq=false; n_ne=$((n_ne+1)) + if [ "$cls" = chip ]; then chip_ne=$((chip_ne+1)); fi + fi entries+="${entries:+,}{\"path\":\"$f\",\"class\":\"$cls\",\"sha256_candidate\":\"$a\",\"sha256_main\":\"$b\",\"equal\":$eq}" done @@ -74,18 +194,27 @@ if [ -n "$PHYS" ]; then [ -d "$PHYS/nvrm" ] || { echo "no physics tree at $PHYS" >&2; exit 2; } [ "$(git rev-parse HEAD)" = "$MAIN" ] || { echo "checkout must be at --main $MAIN to rebuild" >&2; exit 2; } [ -z "$(git status --porcelain --untracked-files=no)" ] || { echo "tracked files are modified; refusing to rebuild" >&2; exit 2; } - NV=$PHYS/third_party/nvidia-open-580.173.02 - INC=(-Isrc -I"$PHYS/nvrm" -I"$PHYS/m16" -I"$NV/src/common/sdk/nvidia/inc" -I"$NV/kernel-open/common/inc" -I"$NV/kernel-open/nvidia-uvm" -I"$NV/src/nvidia/arch/nvalloc/unix/include") - FORGE="src/forge_realization.c src/aegis_verification.c src/omega_om_units.c $PHYS/forge/forge_descriptor.c $PHYS/forge/forge_realize.c $PHYS/sha256_clean.c $PHYS/nvrm/nvrm.c $PHYS/m16/m16_native.c" + NV=$SOURCE/third_party/nvidia-open-580.173.02 + INC=(-Isrc -I"$SOURCE/nvrm" -I"$SOURCE/m16" -I"$NV/src/common/sdk/nvidia/inc" -I"$NV/kernel-open/common/inc" -I"$NV/kernel-open/nvidia-uvm" -I"$NV/src/nvidia/arch/nvalloc/unix/include") + FORGE="src/forge_realization.c src/aegis_verification.c src/omega_om_units.c $PHYS/forge/forge_descriptor.c $PHYS/forge/forge_realize.c $PHYS/sha256_clean.c $SOURCE/nvrm/nvrm.c $SOURCE/m16/m16_native.c" BLK="src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c" TMPB=$(mktemp -d "${TMPDIR:-/tmp}/e1manifest.XXXXXX") || exit 2 trap 'rm -rf "$TMPB"' EXIT build() { # NAME SOURCE_SCRIPT FLAGS... -- SOURCES... - local name=$1 script=$2; shift 2; local flags=() s + local name=$1 script=$2; shift 2; local flags=() sources=() s while [ "$1" != "--" ]; do flags+=("$1"); shift; done; shift - if gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off "${flags[@]}" "${INC[@]}" -o "$TMPB/$name" "$@" > "$TMPB/$name.log" 2>&1; then + for s in "$@"; do + case $s in + src/omega_blackwell_*.c|src/omega_numeric.c|src/omega_numeric_reduce.c|src/omega_core.c|src/omega_vector.c|src/omega_canonical.c) + [ -s "$SOURCE/$s" ] || return 2 + sources+=("$SOURCE/$s");; + *) sources+=("$s");; + esac + done + sources+=("$SOURCE/src/cudapp_om_units.c") + if gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -I"$SOURCE/src" "${flags[@]}" "${INC[@]}" -o "$TMPB/$name" "${sources[@]}" > "$TMPB/$name.log" 2>&1; then s=$(sha256sum "$TMPB/$name" | cut -c1-64) - else s=BUILD_FAILED; fi + else cat "$TMPB/$name.log" >&2; return 2; fi bins+="${bins:+,}{\"gate\":\"$name\",\"build_line_of\":\"$script\",\"sha256_main\":\"$s\"}" } # shellcheck disable=SC2086 @@ -93,14 +222,15 @@ if [ -n "$PHYS" ]; then # shellcheck disable=SC2086 build REDUCE tests/run_reduce_chip.sh -I"$PHYS/forge" -- tests/test_omega_reduce.c src/omega_numeric_reduce.c src/omega_numeric_reduce_gb10.c src/omega_numeric.c src/omega_numeric_gb10.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric_provenance.c $BLK $FORGE # shellcheck disable=SC2086 - build LDST tools/run_numeric_ldst_chip.sh -pthread -- tests/test_omega_ldst_gb10.c src/omega_numeric_ldst_gb10.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c $PHYS/nvrm/nvrm.c $PHYS/m16/m16_native.c + build LDST tools/run_numeric_ldst_chip.sh -pthread -- tests/test_omega_ldst_gb10.c src/omega_numeric_ldst_gb10.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c "$SOURCE/nvrm/nvrm.c" "$SOURCE/m16/m16_native.c" # shellcheck disable=SC2086 - build TRANSC tools/chip_run.sh+tools/manifests/numeric_transc.chiprun -fno-fast-math -pthread -- tests/test_omega_numeric_transc_gb10.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric_transc.c src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c $PHYS/nvrm/nvrm.c $PHYS/m16/m16_native.c + build TRANSC tools/chip_run.sh+tools/manifests/numeric_transc.chiprun -fno-fast-math -pthread -- tests/test_omega_numeric_transc_gb10.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric_transc.c src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c "$SOURCE/nvrm/nvrm.c" "$SOURCE/m16/m16_native.c" fi body="{\"schema\":\"AIEN_E1_EQUIVALENCE_MANIFEST_V1\",\"candidate_git_commit\":\"$CAND\",\"main_git_commit\":\"$MAIN\"" body+=",\"whole_tree_identical\":$([ "$(git rev-parse "$CAND^{tree}")" = "$(git rev-parse "$MAIN^{tree}")" ] && echo true || echo false)" body+=",\"files_equal\":$n_eq,\"files_differ\":$n_ne,\"chip_files_differ\":$chip_ne,\"files\":[$entries]" +body+=",\"canonical_source\":$CANONICAL" [ -z "$bins" ] || body+=",\"rebuilt_chip_binaries\":[$bins]" body+=",\"timestamp_utc\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}" if [ -n "$OUT" ]; then printf '%s\n' "$body" | jq . > "$OUT" && echo "manifest: $OUT (equal=$n_eq differ=$n_ne chip_differ=$chip_ne)" diff --git a/tools/gpu_engine_backend_mutations.sh b/tools/gpu_engine_backend_mutations.sh index 443b3585a..e1711e2c6 100755 --- a/tools/gpu_engine_backend_mutations.sh +++ b/tools/gpu_engine_backend_mutations.sh @@ -41,20 +41,22 @@ set -u cd "$(dirname "$0")/.." || exit 2 unset ONLY +WORK=$(mktemp -d "${TMPDIR:-/tmp}/gpu-backend-canonical.XXXXXX") || exit 2 +trap 'rm -rf "$WORK"' EXIT HUP INT TERM +bash tools/e1_manifest.sh --canonical-overlay "$WORK" >/dev/null || exit 2 +cat "$WORK/cudapp-source.json" >&2 -# 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 -} +# Driver declarations come from the same authenticated closure as the C sources; +# the fake implementation remains the Omega test oracle, never a live driver. +STAGE=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} +PHYS=$(cd "$STAGE/source" && pwd -P) || 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/omega_om_units.c" +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/omega_om_units.c src/cudapp_om_units.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" \ +set -- -k table -m - -d "$WORK" -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" @@ -188,3 +190,9 @@ WRAP_PROGRAM_LENGTH~src/omega_blackwell_submit.c~/^int omega_blackwell_execute_v 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 +rc=$? +if [ -n "$OUT" ] && [ -s "$OUT" ]; then + jq --slurpfile source "$WORK/cudapp-source.json" '. + {canonical_source: $source[0]}' "$OUT" > "$WORK/receipt.json" && + cp "$WORK/receipt.json" "$OUT" || exit 2 +fi +exit "$rc" diff --git a/tools/gpu_engine_mutations.sh b/tools/gpu_engine_mutations.sh index a909493d1..ee5412772 100755 --- a/tools/gpu_engine_mutations.sh +++ b/tools/gpu_engine_mutations.sh @@ -25,6 +25,10 @@ set -u cd "$(dirname "$0")/.." || exit 2 unset ONLY +WORK=$(mktemp -d "${TMPDIR:-/tmp}/gpu-engine-canonical.XXXXXX") || exit 2 +trap 'rm -rf "$WORK"' EXIT HUP INT TERM +bash tools/e1_manifest.sh --canonical-overlay "$WORK" >/dev/null || exit 2 +cat "$WORK/cudapp-source.json" >&2 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' @@ -82,8 +86,14 @@ 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" \ +set -- -k marker -m - -d "$WORK" -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 "$@" +rc=$? +if [ -n "$OUT" ] && [ -s "$OUT" ]; then + jq --slurpfile source "$WORK/cudapp-source.json" '. + {canonical_source: $source[0]}' "$OUT" > "$WORK/receipt.json" && + cp "$WORK/receipt.json" "$OUT" || exit 2 +fi +exit "$rc" diff --git a/tools/manifests/gpu_engine.chiprun b/tools/manifests/gpu_engine.chiprun index 5250ff390..b7be99b67 100644 --- a/tools/manifests/gpu_engine.chiprun +++ b/tools/manifests/gpu_engine.chiprun @@ -13,7 +13,6 @@ TEST_SOURCE="tests/test_omega_gpu_engine_gb10.c" # The real engine core, the Blackwell backend, the vector wrapper and what the vector builder needs. # Not the fake driver: the real m16_native.c and nvrm.c come in below. SOURCES="src/omega_gpu_engine.c src/omega_blackwell_engine.c src/omega_blackwell_submit.c src/omega_blackwell_realize.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_vector.c src/omega_validate.c src/omega_core.c src/omega_canonical.c src/omega_om_units.c" -EXTRA_BUILD_SOURCES="$PHYSICS/nvrm/nvrm.c $PHYSICS/m16/m16_native.c" RUN_ARGS="--chip" VERDICT_RE='^GPU_ENGINE: ' PASS_LINE='^GPU_ENGINE: PASS$' @@ -29,3 +28,27 @@ REQUIRE_ALL_PASS=0 CHILD_EXIT_PASSTHROUGH=1 # Host tier first (nonzero refuses): the simulated-driver test and the backend mutants, real target names. HOST_TIER_CMD="make test-gpu-engine-sim test-gpu-engine-backend-mutants PHYSICS_DIR=\"$PHYSICS\"" +# Authenticate before any host build; the final stage is the only GPU source authority. +canonical_stage=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} +case $canonical_stage in /*) ;; *) canonical_stage=$HERE/$canonical_stage;; esac +canonical_log=$(mktemp) || return 2 +if ! canonical_metadata=$(sh "$HERE/tools/cudapp-stage.sh" --verify "$HERE/cudapp.lock" "$canonical_stage" 2>"$canonical_log"); then + cat "$canonical_log" >&2; rm -f -- "$canonical_log"; return 2 +fi +rm -f -- "$canonical_log" || return 2 +canonical_root=$(cd -P "$canonical_stage/source" && pwd) || return 2 +GPU_SOURCE_ROOT=$canonical_root +EXTRA_BUILD_SOURCES="$GPU_SOURCE_ROOT/nvrm/nvrm.c $GPU_SOURCE_ROOT/m16/m16_native.c $canonical_stage/build/libcudapp.a" +canonical_sources= +for canonical_file in $SOURCES; do + case $canonical_file in + src/omega_validate.c|src/omega_om_units.c) + canonical_sources="$canonical_sources $canonical_file";; + *) + [ -s "$canonical_root/$canonical_file" ] || return 2 + canonical_sources="$canonical_sources $canonical_root/$canonical_file";; + esac +done +SOURCES="$canonical_sources $canonical_root/src/cudapp_om_units.c" +CPATH="$canonical_root/src${CPATH:+:$CPATH}"; export CPATH +RECEIPT_EXTRA_JQ=". + {canonical_source: $canonical_metadata}" diff --git a/tools/manifests/numeric_transc.chiprun b/tools/manifests/numeric_transc.chiprun index b39c2c452..61b1a1551 100644 --- a/tools/manifests/numeric_transc.chiprun +++ b/tools/manifests/numeric_transc.chiprun @@ -12,7 +12,6 @@ GATE=E1-TRANSC-GB10 OWNER="lane2 E1 transcendental GB10 chip run" TEST_SOURCE="tests/test_omega_numeric_transc_gb10.c" SOURCES="src/omega_numeric_divsqrt_gb10.c src/omega_numeric_transc.c src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c" -EXTRA_BUILD_SOURCES="$PHYSICS/nvrm/nvrm.c $PHYSICS/m16/m16_native.c" # The wrapper passes "--chip OP..." itself; this is the old default for direct use. RUN_ARGS="--chip EXP2 LOG2 SIGMOID TANH SIN COS ERF GELU RSQRT" # Old verdict: the last "VERDICT " line of the chip log. RESULT lines come before it. @@ -87,3 +86,26 @@ def opsjson: try ([$log | split("\n")[] | select(startswith("RESULT chip ")) | s verdict: (if $r.verdict == "PASS" then "PASS" elif $cw == "PASS" then "FAIL" elif $cw == "" then "NOT_RUN" else $cw end) } ' +canonical_stage=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} +case $canonical_stage in /*) ;; *) canonical_stage=$HERE/$canonical_stage;; esac +canonical_log=$(mktemp) || return 1 +if ! canonical_metadata=$(sh "$HERE/tools/cudapp-stage.sh" --verify "$HERE/cudapp.lock" "$canonical_stage" 2>"$canonical_log"); then + cat "$canonical_log" >&2; rm -f -- "$canonical_log"; return 1 +fi +rm -f -- "$canonical_log" || return 1 +canonical_root=$(cd -P "$canonical_stage/source" && pwd) || return 1 +GPU_SOURCE_ROOT=$canonical_root +EXTRA_BUILD_SOURCES="$GPU_SOURCE_ROOT/nvrm/nvrm.c $GPU_SOURCE_ROOT/m16/m16_native.c $canonical_stage/build/libcudapp.a" +canonical_sources= +for canonical_file in $SOURCES; do + case $canonical_file in + src/omega_numeric_divsqrt_gb10.c|src/omega_numeric_transc.c|src/omega_numeric_provenance.c|src/omega_om_units.c) + canonical_sources="$canonical_sources $canonical_file";; + *) + [ -s "$canonical_root/$canonical_file" ] || return 1 + canonical_sources="$canonical_sources $canonical_root/$canonical_file";; + esac +done +SOURCES="$canonical_sources $canonical_root/src/cudapp_om_units.c" +CPATH="$canonical_root/src${CPATH:+:$CPATH}"; export CPATH +RECEIPT_EXTRA_JQ="$RECEIPT_EXTRA_JQ | . + {canonical_source: $canonical_metadata}" diff --git a/tools/manifests/unwritten_trap.chiprun b/tools/manifests/unwritten_trap.chiprun index 97c6fed9b..aa90ec610 100644 --- a/tools/manifests/unwritten_trap.chiprun +++ b/tools/manifests/unwritten_trap.chiprun @@ -9,7 +9,6 @@ GATE=unwritten_trap OWNER=unwritten_trap TEST_SOURCE="tests/test_omega_unwritten_trap_gb10.c" SOURCES="src/omega_unwritten_trap.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric_transc.c src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c" -EXTRA_BUILD_SOURCES="$PHYSICS/nvrm/nvrm.c $PHYSICS/m16/m16_native.c" # Same default as the old script. RUN_ARGS="--chip --repeats 3000" # Every line starting with the trap tag is a verdict candidate (this includes NOT_RUN lines); @@ -37,3 +36,26 @@ REQUIRE_ALL_PASS=0 # Old script exit codes passed straight through: 0 clean, 1 hits or device error, 2 NOT_RUN # printed by the harness (tests/test_omega_unwritten_trap_gb10.c lines 87,104,110,113,123). CHILD_EXIT_PASSTHROUGH=1 +canonical_stage=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} +case $canonical_stage in /*) ;; *) canonical_stage=$HERE/$canonical_stage;; esac +canonical_log=$(mktemp) || return 2 +if ! canonical_metadata=$(sh "$HERE/tools/cudapp-stage.sh" --verify "$HERE/cudapp.lock" "$canonical_stage" 2>"$canonical_log"); then + cat "$canonical_log" >&2; rm -f -- "$canonical_log"; return 2 +fi +rm -f -- "$canonical_log" || return 2 +canonical_root=$(cd -P "$canonical_stage/source" && pwd) || return 2 +GPU_SOURCE_ROOT=$canonical_root +EXTRA_BUILD_SOURCES="$GPU_SOURCE_ROOT/nvrm/nvrm.c $GPU_SOURCE_ROOT/m16/m16_native.c $canonical_stage/build/libcudapp.a" +canonical_sources= +for canonical_file in $SOURCES; do + case $canonical_file in + src/omega_unwritten_trap.c|src/omega_numeric_divsqrt_gb10.c|src/omega_numeric_transc.c|src/omega_numeric_provenance.c|src/omega_om_units.c) + canonical_sources="$canonical_sources $canonical_file";; + *) + [ -s "$canonical_root/$canonical_file" ] || return 2 + canonical_sources="$canonical_sources $canonical_root/$canonical_file";; + esac +done +SOURCES="$canonical_sources $canonical_root/src/cudapp_om_units.c" +CPATH="$canonical_root/src${CPATH:+:$CPATH}"; export CPATH +RECEIPT_EXTRA_JQ=". + {canonical_source: $canonical_metadata}" diff --git a/tools/numeric_check_sweep.sh b/tools/numeric_check_sweep.sh index 6d195a61b..82da8c82d 100755 --- a/tools/numeric_check_sweep.sh +++ b/tools/numeric_check_sweep.sh @@ -26,22 +26,34 @@ # Run: make test-numeric-sweep (or run this file). set -u HERE=$(cd -P "$(dirname "$0")/.." && pwd) -SRC=$HERE/src/omega_numeric.c -TMP=$(mktemp -d) +TMP=$(mktemp -d) || exit 2 trap 'rm -rf "$TMP"' EXIT +WORK=$TMP/source +bash "$HERE/tools/e1_manifest.sh" --canonical-overlay "$WORK" >/dev/null || exit 2 +cat "$WORK/cudapp-source.json" >&2 +SRC=$WORK/src/omega_numeric.c OTHER="tests/test_omega_numeric.c src/omega_numeric_provenance.c src/omega_numeric_divsqrt_gb10.c src/omega_blackwell_encoder.c - src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c" -names=$(grep -o '/\* CHECK:[a-z0-9_]* \*/' "$SRC" | sed 's|/\* CHECK:\([a-z0-9_]*\) \*/|\1|') + src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c src/cudapp_om_units.c" +grep -o '/\* CHECK:[a-z0-9_]* \*/' "$SRC" > "$TMP/markers" || exit 2 +[ -s "$TMP/markers" ] || exit 2 +names=$(sed 's|/\* CHECK:\([a-z0-9_]*\) \*/|\1|' "$TMP/markers") || exit 2 +# A broken baseline is not evidence that removing a guard was caught. +if ! (cd "$WORK" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc \ + -DOMEGA_NUMERIC_CPU_ONLY -o "$TMP/baseline" "$SRC" $OTHER) > "$TMP/build.log" 2>&1; then + cat "$TMP/build.log"; exit 2 +fi +"$TMP/baseline" > "$TMP/baseline.log" 2>&1 || { cat "$TMP/baseline.log"; exit 2; } total=0 killed=0 survived=0 broken=0 for name in $names; do total=$((total + 1)) mut=$TMP/omega_numeric.c - grep -v "/\* CHECK:$name \*/" "$SRC" > "$mut" + grep -v "/\* CHECK:$name \*/" "$SRC" > "$mut"; scan=$? + [ "$scan" -le 1 ] && [ -s "$mut" ] || exit 2 if [ "$(wc -l < "$SRC")" -ne $(( $(wc -l < "$mut") + 1 )) ]; then echo " [BROKEN] $name: marker is not on exactly one line"; broken=$((broken + 1)); continue fi # shellcheck disable=SC2086 - if ! (cd "$HERE" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc \ + if ! (cd "$WORK" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc \ -Wno-unused-variable -Wno-unused-but-set-variable \ -DOMEGA_NUMERIC_CPU_ONLY -o "$TMP/t" "$mut" $OTHER) > "$TMP/build.log" 2>&1; then echo " [BROKEN] $name: scratch copy does not build"; broken=$((broken + 1)); continue diff --git a/tools/numeric_oracle_mutations.sh b/tools/numeric_oracle_mutations.sh index 0ef6d9d02..f449c36d4 100755 --- a/tools/numeric_oracle_mutations.sh +++ b/tools/numeric_oracle_mutations.sh @@ -33,11 +33,14 @@ # named id is reported; it records the binary's exit status for the legacy line. set -u HERE=$(cd -P "$(dirname "$0")/.." && pwd) -TMP=$(mktemp -d) +TMP=$(mktemp -d) || exit 2 trap 'rm -rf "$TMP"' EXIT +WORK=$TMP/source +bash "$HERE/tools/e1_manifest.sh" --canonical-overlay "$WORK" >/dev/null || exit 2 +cat "$WORK/cudapp-source.json" >&2 # One line on purpose: $SRCS is interpolated into the runner's -b string, which # the runner executes with sh -c, so a newline here would split the gcc command. -SRCS="tests/test_omega_numeric.c src/omega_numeric.c src/omega_numeric_provenance.c src/omega_numeric_divsqrt_gb10.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c" +SRCS="tests/test_omega_numeric.c src/omega_numeric.c src/omega_numeric_provenance.c src/omega_numeric_divsqrt_gb10.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c src/cudapp_om_units.c" # id ~ file ~ edit ~ test ID that must FAIL (or UNDECLARED_SKIP) cat > "$TMP/rows" <<'ROWS_EOF' @@ -73,7 +76,7 @@ while IFS='~' read -r name file edit want; do printf '%s~%s~%s~%s\n' "$name" "$file" "$edit" "$want" > "$TMP/row" # shellcheck disable=SC2086 ONLY=$name "$HERE/tools/mutation_runner.sh" -k table -m "$TMP/row" \ - -d "$HERE" -c "src tests/test_omega_numeric.c tests/numeric_oracle.h" \ + -d "$WORK" -c "src tests/test_omega_numeric.c tests/numeric_oracle.h" \ -b "gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc -DOMEGA_NUMERIC_CPU_ONLY -o $TMP/t $SRCS > $TMP/build.log 2>&1" \ -t "sh $TMP/judge.sh $TMP $want" -o "$TMP/out.json" > /dev/null 2> "$TMP/runner.err" < /dev/null status=$(sed -n "s/^$name \([A-Z_]*\) .*/\1/p" "$TMP/runner.err" | head -1) diff --git a/tools/probe_gpu_open.sh b/tools/probe_gpu_open.sh index b0af4a3f2..5c91bff95 100755 --- a/tools/probe_gpu_open.sh +++ b/tools/probe_gpu_open.sh @@ -31,6 +31,8 @@ OUT=${1:?out dir}; N=${2:-30} cd "$(dirname "$0")/.." || exit 2 P=${PHYSICS_DIR:-../physics} mkdir -p "$OUT" +bash tools/e1_manifest.sh --canonical-evidence "$OUT" \ + src/omega_gpu_session.c src/omega_gpu_platform.c src/omega_gpu_platform_linux.c || exit 2 make PHYSICS_DIR="$P" build/gpu_session_probe > "$OUT/build.log" 2>&1 || { echo "PROBE BUILD FAIL"; exit 1; } PR=./build/gpu_session_probe LOG="$OUT/probe.log"; : > "$LOG" @@ -58,7 +60,10 @@ run_variant overlap grep -c 'rc=OK' "$LOG" > "$OUT/ok_count.txt" grep 'rc=' "$LOG" | grep -v 'rc=OK' | grep -v negative_control > "$OUT/failures.txt" echo "end $(date -u +%FT%TZ)" >> "$OUT/device.txt" -cp tests/gpu_session_probe.c src/omega_gpu_session.c src/omega_gpu_platform.c src/omega_gpu_platform_linux.c tools/probe_gpu_open.sh "$OUT/" -(cd "$OUT" && sha256sum -- * > SHA256SUMS) +cp tests/gpu_session_probe.c tools/probe_gpu_open.sh "$OUT/" || exit 2 +(cd "$OUT" && for file in *; do + [ "$file" != SHA256SUMS ] || continue + [ -f "$file" ] && sha256sum -- "$file" || exit 2 +done > SHA256SUMS) || exit 2 echo "PROBE_GPU_OPEN: negative_control_exit=$neg_rc first_call_failures=$fails/$total (details $OUT/failures.txt)" [ "$neg_rc" != 0 ] || { echo "PROBE_GPU_OPEN: INSTRUMENT FAIL (negative control passed)"; exit 3; } diff --git a/tools/r16_authpath.sh b/tools/r16_authpath.sh index 8c3b2118a..b67129f78 100755 --- a/tools/r16_authpath.sh +++ b/tools/r16_authpath.sh @@ -70,6 +70,28 @@ printf '%s\n' "$@" > "$out/sources.txt" argus_short=$(head -n 1 argus.lock 2>/dev/null | cut -c1-7) [ -n "$argus_short" ] || fail "argus.lock is missing or empty" argus_dir="*/argus-src/$argus_short/native/argus" +# AuthClosureReview: accept authenticated direct children, never a prefix glob. +stage=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} +sh tools/cudapp-stage.sh --verify cudapp.lock "$stage" > "$out/cudapp-source.json" || + fail "canonical CUDApp stage authentication failed" +stage=$(cd -P "$stage" && pwd) || fail "canonical stage missing" +canonical_source() { + candidate=$1 + case $candidate in /*) ;; *) candidate=$PWD/$candidate;; esac + case $candidate in */../*|*/./*) return 1;; esac + [ -f "$candidate" ] && [ -s "$candidate" ] && [ ! -L "$candidate" ] || return 1 + [ ! -L "$stage/source" ] && [ ! -L "$stage/source/src" ] && + [ ! -L "$stage/build" ] || return 1 + parent=$(CDPATH= cd -P "$(dirname "$candidate")" && pwd) || return 1 + case $parent in + "$stage/source/src") + case ${candidate##*/} in *.c) return 0;; esac;; + "$stage/build") + # The archive contains the physical driver closure, not a host seat. + [ "$mode" = silicon ] && [ "${candidate##*/}" = libcudapp.a ] && return 0;; + esac + return 1 +} for s in "$@"; do case "$s" in tools/omegatool.c|*/omegatool.c) fail "source list links omegatool: $s" ;; @@ -79,10 +101,10 @@ for s in "$@"; do *libaienos_capability.a) ;; */m16/m16_native.c|*/nvrm/nvrm.c) [ "$mode" = silicon ] || fail "physical seat source in a host build: $s" ;; $argus_dir/argus_*.c) ;; # ARGUS pinned by argus.lock (git archive extract; pattern unquoted on purpose) - *) fail "source outside omega src/ and tests/runtime/: $s" ;; + *) canonical_source "$s" || fail "source outside authenticated Omega/CUDApp closure: $s" ;; esac done -note "sources: $# files, omega, the native AIENOS capability library and ARGUS pinned by argus.lock only" +note "sources: $# files, Omega, native AIENOS capability, ARGUS and authenticated CUDApp (physical archive silicon-only)" # 2. link map ---------------------------------------------------------------- # Rust runtime symbols are rust_* or __rust_*, so "rust_" is matched only at a @@ -93,15 +115,22 @@ for b in "$r13" "$r14"; do [ -x "$b" ] || fail "binary missing: $b" n=$(basename "$b") nm "$b" > "$out/$n.nm" 2>&1 || fail "nm failed on $b" - if awk '{print $NF}' "$out/$n.nm" | grep -Ei "$legacy_sym" > "$out/$n.legacy-symbols"; then - fail "$n links legacy orchestrator symbols: $(tr '\n' ' ' < "$out/$n.legacy-symbols")" - fi - awk '{print $NF}' "$out/$n.nm" | grep -E 'sequential_reference|rx_world_seq_' \ - > "$out/$n.reference-hooks" || true + awk '{print $NF}' "$out/$n.nm" > "$out/$n.symbols" || fail "symbol scanner failed" + [ -s "$out/$n.symbols" ] || fail "empty symbol scanner input: $b" + grep -Ei "$legacy_sym" "$out/$n.symbols" > "$out/$n.legacy-symbols"; scan=$? + case $scan in + 0) fail "$n links legacy orchestrator symbols: $(tr '\n' ' ' < "$out/$n.legacy-symbols")";; + 1) ;; *) fail "legacy symbol scanner failed";; + esac + grep -E 'sequential_reference|rx_world_seq_' "$out/$n.symbols" > "$out/$n.reference-hooks"; scan=$? + [ "$scan" -le 1 ] || fail "reference symbol scanner failed" ldd "$b" > "$out/$n.ldd" 2>&1 || fail "ldd failed on $b" - if grep -vE 'linux-vdso|libc\.so|libm\.so|libpthread\.so|ld-linux|libdl\.so' "$out/$n.ldd" | grep -q .; then - fail "$n needs a shared library outside the C runtime: $(grep -vE 'linux-vdso|libc\.so|libm\.so|libpthread\.so|ld-linux|libdl\.so' "$out/$n.ldd" | tr '\n' ' ')" - fi + [ -s "$out/$n.ldd" ] || fail "empty shared library scanner input: $b" + grep -vE 'linux-vdso|libc\.so|libm\.so|libpthread\.so|ld-linux|libdl\.so' "$out/$n.ldd" > "$out/$n.foreign-libraries"; scan=$? + case $scan in + 0) fail "$n needs a shared library outside the C runtime: $(cat "$out/$n.foreign-libraries")";; + 1) ;; *) fail "shared library scanner failed";; + esac note "link map $n: no legacy orchestrator symbol; C runtime libraries only; SEQ world hooks present (reference, refused on production worlds): $(wc -l < "$out/$n.reference-hooks")" done @@ -116,9 +145,13 @@ note "production program: $(grep -E '^R16 prod: ' "$out/prod-hygiene.out" | head legacy_exe='spark-aegis|aegis-runtime|aien-cli|aien-runtime|aien-server|spark-dream|sovereign-core|omegatool' for b in "$r13" "$r14"; do n=$(basename "$b") - if strings -a "$b" | grep -E "$legacy_exe" > "$out/$n.legacy-strings"; then - fail "$n embeds a legacy program name: $(head -3 "$out/$n.legacy-strings" | tr '\n' ' ')" - fi + strings -a "$b" > "$out/$n.strings" || fail "strings scanner failed" + [ -s "$out/$n.strings" ] || fail "empty embedded name scanner input: $b" + grep -E "$legacy_exe" "$out/$n.strings" > "$out/$n.legacy-strings"; scan=$? + case $scan in + 0) fail "$n embeds a legacy program name: $(cat "$out/$n.legacy-strings")";; + 1) ;; *) fail "legacy name scanner failed";; + esac done note "strings: no legacy program name embedded" diff --git a/tools/run_divsqrt_gate.sh b/tools/run_divsqrt_gate.sh index e5dff2977..a5a117634 100755 --- a/tools/run_divsqrt_gate.sh +++ b/tools/run_divsqrt_gate.sh @@ -55,13 +55,16 @@ PHYS_COMMIT=$(git -C "$PHYSICS" rev-parse HEAD) || refuse "cannot read physics H fuser /tmp/aien-gb10.lock >/dev/null 2>&1 && refuse "/tmp/aien-gb10.lock is held" echo "== host tier" -make -s -C "$HERE" build/test_omega_divsqrt_gb10_cpu > "$RUN/host-build.log" 2>&1 || refuse "host build failed" +make -s -C "$HERE" PHYSICS_DIR="$PHYSICS" build/test_omega_divsqrt_gb10_cpu >"$RUN/build-host.log" 2>&1 || refuse "host binary did not build" "$HERE/build/test_omega_divsqrt_gb10_cpu" > "$RUN/host.log" 2>&1; HOST_RC=$? tail -1 "$RUN/host.log" echo "== nvdisasm provenance" "$HERE/tools/divsqrt_nvdisasm_check.sh" > "$RUN/nvdisasm.log" 2>&1; NVD_RC=$? grep -E '^\[|^VERDICT|^disassembler' "$RUN/nvdisasm.log" [ "$HOST_RC" = 0 ] && [ "$NVD_RC" = 0 ] || refuse "host tier ($HOST_RC) or nvdisasm check ($NVD_RC) failed; no chip run" +# Reuse the authenticated canonical collector; this is source/caller glue only. +WORK=$RUN/source +bash "$HERE/tools/e1_manifest.sh" --canonical-overlay "$WORK" || refuse "canonical source verification failed" KDIG=$("$HERE/build/test_omega_divsqrt_gb10_cpu" --digest) START=$(date -u +%Y-%m-%dT%H:%M:%SZ) @@ -75,13 +78,13 @@ flock -x 9 || refuse "cannot take /tmp/aien-gb10.lock" echo "== chip build" NV=$PHYSICS/third_party/nvidia-open-580.173.02 BIN=$RUN/test_omega_divsqrt_gb10 -(cd "$HERE" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -pthread \ +(cd "$WORK" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -pthread \ -Isrc -I"$PHYSICS/nvrm" -I"$PHYSICS/m16" \ -I"$NV/src/common/sdk/nvidia/inc" -I"$NV/kernel-open/common/inc" \ -I"$NV/kernel-open/nvidia-uvm" -I"$NV/src/nvidia/arch/nvalloc/unix/include" \ -o "$BIN" tests/test_omega_divsqrt_gb10.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric.c \ src/omega_numeric_provenance.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c \ + src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c src/cudapp_om_units.c \ "$PHYSICS/nvrm/nvrm.c" "$PHYSICS/m16/m16_native.c") > "$RUN/chip-build.log" 2>&1 || { cat "$RUN/chip-build.log"; refuse "chip build failed"; } if nm -u "$BIN" | grep -Eq '\b(sqrtf?|expf?|logf?|powf?|fmaf?|sinf?|cosf?|fdiv|divf)\b'; then refuse "libm math symbols in $BIN"; fi if nm -u "$BIN" | grep -Eiq 'cuda|cuInit|cuLaunch|nvrtc|cublas'; then refuse "CUDA symbols in $BIN"; fi @@ -110,6 +113,7 @@ num() { local v; v=$(field "$1" "$2"); echo "${v:-null}"; } BODY=$(jq -n --arg gate "E1-DIVSQRT" --arg omega "$OMEGA_COMMIT" --arg phys "$PHYS_COMMIT" --arg pin "$PIN" \ --argjson oclean true --argjson pclean true --argjson oafter "$OMEGA_CLEAN_AFTER" --argjson pafter "$PHYS_CLEAN_AFTER" \ --argjson osame "$OMEGA_SAME_AFTER" --argjson psame "$PHYS_SAME_AFTER" \ + --slurpfile canonical "$WORK/cudapp-source.json" \ --arg bin "$BIN_SHA" --arg log "$LOG_SHA" --arg kd "$KDIG" --arg start "$START" --arg end "$END" \ --arg nvd "$(grep '^disassembler' "$RUN/nvdisasm.log")" --arg host "$(tail -1 "$RUN/host.log")" \ --argjson dchk "$(num DIV checked)" --argjson dedge "$(num DIV edge_and_corpus)" \ @@ -120,6 +124,7 @@ BODY=$(jq -n --arg gate "E1-DIVSQRT" --arg omega "$OMEGA_COMMIT" --arg phys "$PH --arg verdict "$VERDICT" --argjson rc "$CHIP_RC" '{ gate: $gate, row: "E1 gap table row 7: GB10 correctly rounded FP32 DIV and SQRT", omega_commit: $omega, omega_tree_clean_before: $oclean, omega_tree_clean_after: $oafter, omega_commit_unchanged_after: $osame, + canonical_source: $canonical[0], physics_commit: $phys, physics_lock_pin: $pin, physics_tree_clean_before: $pclean, physics_tree_clean_after: $pafter, physics_commit_unchanged_after: $psame, binary_sha256: $bin, chip_log_sha256: $log, kernels: ($kd | split("\n") | map(select(length > 0) | split(" ") | {op: .[0], instructions: (.[1] | tonumber), sha256: .[2]})), nvdisasm_check: $nvd, host_tier: $host, diff --git a/tools/run_gpu_attention_chip.sh b/tools/run_gpu_attention_chip.sh index d6c3c5ba8..184e65f78 100755 --- a/tools/run_gpu_attention_chip.sh +++ b/tools/run_gpu_attention_chip.sh @@ -34,6 +34,8 @@ P=${PHYSICS_DIR:-../physics} SHA=$(git rev-parse --short HEAD) OUT=${1:-$HOME/workspace/evidence-out}/FB1-CUT5-$SHA mkdir -p "$OUT" +bash tools/e1_manifest.sh --canonical-evidence "$OUT" \ + src/omega_gpu_attention_api.c src/omega_gpu_attention_api.h || exit 2 if ! make PHYSICS_DIR="$P" build/gpu_attention_test > "$OUT/build.log" 2>&1; then echo "FB1-CUT5 BUILD FAIL (see $OUT/build.log)"; exit 1 fi @@ -59,8 +61,11 @@ sweep_rc=$? timing_rc=$? [ "$rc" -eq 0 ] && rc=$sweep_rc [ "$rc" -eq 0 ] && rc=$timing_rc -cp src/omega_gpu_attention_api.c src/omega_gpu_attention_api.h tests/gpu_attention_test.c "$OUT/" -(cd "$OUT" && sha256sum -- * > SHA256SUMS) +cp tests/gpu_attention_test.c "$OUT/" || exit 2 +(cd "$OUT" && for file in *; do + [ "$file" != SHA256SUMS ] || continue + [ -f "$file" ] && sha256sum -- "$file" || exit 2 +done > SHA256SUMS) || exit 2 tail -1 "$OUT/run.log"; tail -1 "$OUT/sweep.log"; tail -1 "$OUT/timing.log" echo "FB1-CUT5 chip gate rc=$rc (sweep rc=$sweep_rc timing rc=$timing_rc) receipt=$OUT/receipt.json sweep=$OUT/sweep.json" exit $rc diff --git a/tools/run_gpu_cut4b_chip.sh b/tools/run_gpu_cut4b_chip.sh index 638e5a1c0..c0d93f3e0 100755 --- a/tools/run_gpu_cut4b_chip.sh +++ b/tools/run_gpu_cut4b_chip.sh @@ -35,6 +35,11 @@ SHA=$(git rev-parse --short HEAD) OUT=${1:-$HOME/workspace/evidence-out}/FB1-CUT4B-$SHA PROBE_N=${2:-30} mkdir -p "$OUT" +bash tools/e1_manifest.sh --canonical-evidence "$OUT" \ + src/omega_gpu_session.c src/omega_gpu_session.h \ + 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_elementwise_api.c src/omega_gpu_elementwise_api.h \ + src/omega_gpu_attention_api.c src/omega_gpu_attention_api.h || exit 2 if ! make PHYSICS_DIR="$P" build/gpu_elementwise_test build/gpu_attention_test build/gpu_matmul_api_test build/gpu_session_probe > "$OUT/build.log" 2>&1; then echo "FB1-CUT4B BUILD FAIL (see $OUT/build.log)"; exit 1 fi @@ -62,8 +67,11 @@ step matmul_timing ./build/gpu_matmul_api_test --timing --out "$OUT/matmul_ ./tools/probe_gpu_open.sh "$OUT/probe" "$PROBE_N" > "$OUT/probe.log" 2>&1; prc=$? tail -1 "$OUT/probe.log" echo "end $(date -u +%FT%TZ)" >> "$OUT/device.txt" -cp src/omega_gpu_session.c src/omega_gpu_session.h 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_elementwise_api.c src/omega_gpu_elementwise_api.h \ - src/omega_gpu_attention_api.c src/omega_gpu_attention_api.h tests/gpu_elementwise_test.c tests/gpu_attention_test.c tests/gpu_matmul_api_test.c "$OUT/" -(cd "$OUT" && sha256sum -- * probe/* 2>/dev/null > SHA256SUMS) +cp tests/gpu_elementwise_test.c tests/gpu_attention_test.c tests/gpu_matmul_api_test.c "$OUT/" || exit 2 +(cd "$OUT" && for file in * probe/*; do + [ "$file" != SHA256SUMS ] || continue + [ ! -d "$file" ] || continue + [ -f "$file" ] && sha256sum -- "$file" || exit 2 +done > SHA256SUMS) || exit 2 echo "FB1-CUT4B chip gate failed_steps=$fail probe_rc=$prc receipt=$OUT" [ "$fail" -eq 0 ] && [ "$prc" -ne 3 ] diff --git a/tools/run_gpu_elementwise_chip.sh b/tools/run_gpu_elementwise_chip.sh index a5b10200a..5e0d32c6c 100755 --- a/tools/run_gpu_elementwise_chip.sh +++ b/tools/run_gpu_elementwise_chip.sh @@ -28,6 +28,8 @@ P=${PHYSICS_DIR:-../physics} SHA=$(git rev-parse --short HEAD) OUT=${1:-$HOME/workspace/evidence-out}/FB1-CUT4-$SHA mkdir -p "$OUT" +bash tools/e1_manifest.sh --canonical-evidence "$OUT" \ + src/omega_gpu_elementwise_api.c src/omega_gpu_elementwise_api.h || exit 2 if ! make PHYSICS_DIR="$P" build/gpu_elementwise_test > "$OUT/build.log" 2>&1; then echo "FB1-CUT4 BUILD FAIL (see $OUT/build.log)"; exit 1 fi @@ -40,8 +42,11 @@ fi } > "$OUT/device.txt" ./build/gpu_elementwise_test --out "$OUT/receipt.json" > "$OUT/run.log" 2>&1 rc=$? -cp src/omega_gpu_elementwise_api.c src/omega_gpu_elementwise_api.h tests/gpu_elementwise_test.c "$OUT/" -(cd "$OUT" && sha256sum -- * > SHA256SUMS) +cp tests/gpu_elementwise_test.c "$OUT/" || exit 2 +(cd "$OUT" && for file in *; do + [ "$file" != SHA256SUMS ] || continue + [ -f "$file" ] && sha256sum -- "$file" || exit 2 +done > SHA256SUMS) || exit 2 tail -1 "$OUT/run.log" echo "FB1-CUT4 chip gate rc=$rc receipt=$OUT/receipt.json" exit $rc diff --git a/tools/run_gpu_reconv_chip.sh b/tools/run_gpu_reconv_chip.sh index 20e719684..e2db9bac6 100755 --- a/tools/run_gpu_reconv_chip.sh +++ b/tools/run_gpu_reconv_chip.sh @@ -37,6 +37,9 @@ if [ $# -gt 0 ] && [ "$1" = "--" ]; then shift; EXTRA="$*"; fi SHA=$(git rev-parse --short HEAD) OUT=$OUT_ROOT/GPU-RECONV-$SHA mkdir -p "$OUT" +bash tools/e1_manifest.sh --canonical-evidence "$OUT" \ + src/omega_gpu_elementwise_api.c src/omega_gpu_elementwise_api.h \ + src/omega_bw_reconv.h src/omega_blackwell_codegen.c || exit 2 if ! make PHYSICS_DIR="$P" build/gpu_reconv_test > "$OUT/build.log" 2>&1; then echo "GPU-RECONV BUILD FAIL (see $OUT/build.log)"; exit 1 fi @@ -50,9 +53,11 @@ fi # shellcheck disable=SC2086 ./build/gpu_reconv_test --out "$OUT/receipt.json" $EXTRA > "$OUT/run.log" 2>&1 rc=$? -cp src/omega_gpu_elementwise_api.c src/omega_gpu_elementwise_api.h src/omega_bw_reconv.h src/omega_blackwell_codegen.c \ - tests/gpu_reconv_test.c tests/bw_warp_sim.h "$OUT/" -(cd "$OUT" && sha256sum -- * > SHA256SUMS) +cp tests/gpu_reconv_test.c tests/bw_warp_sim.h "$OUT/" || exit 2 +(cd "$OUT" && for file in *; do + [ "$file" != SHA256SUMS ] || continue + [ -f "$file" ] && sha256sum -- "$file" || exit 2 +done > SHA256SUMS) || exit 2 tail -1 "$OUT/run.log" echo "GPU-RECONV chip gate rc=$rc receipt=$OUT/receipt.json" exit $rc diff --git a/tools/run_numeric_ldst_chip.sh b/tools/run_numeric_ldst_chip.sh index c1eaab81d..f0bf6f835 100755 --- a/tools/run_numeric_ldst_chip.sh +++ b/tools/run_numeric_ldst_chip.sh @@ -34,6 +34,12 @@ PIN=$(tr -d '[:space:]' < "$HERE/physics.lock") [ -n "$(pgrep est_load)" ] && refuse "an est_load process is running" RUN=$(mktemp -d /tmp/ldst-chip.XXXXXX) echo "omega $(git -C "$HERE" rev-parse HEAD) physics $PIN" +WORK=$RUN/source +bash "$HERE/tools/e1_manifest.sh" --canonical-overlay "$WORK" >/dev/null || refuse "canonical CUDApp authentication failed" +cp "$WORK/cudapp-source.json" "$RUN/CUDAPP-SOURCE.json" || refuse "cannot record canonical identity" +STAGE=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} +case $STAGE in /*) ;; *) STAGE=$HERE/$STAGE;; esac +CANONICAL=$(cd "$STAGE/source" && pwd -P) || refuse "canonical source missing" echo "== host tier" make -s -C "$HERE" build/test_omega_ldst_gb10_cpu > "$RUN/host-build.log" 2>&1 || refuse "host build failed" "$HERE/build/test_omega_ldst_gb10_cpu" > "$RUN/host.log" 2>&1 || { tail -5 "$RUN/host.log"; refuse "host tier failed"; } @@ -44,16 +50,16 @@ tail -3 "$RUN/nvdisasm.log" exec 9> /tmp/aien-gb10.lock || refuse "cannot open /tmp/aien-gb10.lock" flock -x 9 || refuse "cannot take /tmp/aien-gb10.lock" echo "== chip build" -NV=$PHYSICS/third_party/nvidia-open-580.173.02 +NV=$CANONICAL/third_party/nvidia-open-580.173.02 BIN=$RUN/test_omega_ldst_gb10 -(cd "$HERE" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -pthread \ - -Isrc -I"$PHYSICS/nvrm" -I"$PHYSICS/m16" \ +(cd "$WORK" && gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -pthread \ + -Isrc -I"$CANONICAL/nvrm" -I"$CANONICAL/m16" \ -I"$NV/src/common/sdk/nvidia/inc" -I"$NV/kernel-open/common/inc" \ -I"$NV/kernel-open/nvidia-uvm" -I"$NV/src/nvidia/arch/nvalloc/unix/include" \ -o "$BIN" tests/test_omega_ldst_gb10.c src/omega_numeric_ldst_gb10.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric.c \ src/omega_numeric_provenance.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c \ - "$PHYSICS/nvrm/nvrm.c" "$PHYSICS/m16/m16_native.c") > "$RUN/chip-build.log" 2>&1 || { cat "$RUN/chip-build.log"; refuse "chip build failed"; } + src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c src/cudapp_om_units.c \ + "$CANONICAL/nvrm/nvrm.c" "$CANONICAL/m16/m16_native.c") > "$RUN/chip-build.log" 2>&1 || { cat "$RUN/chip-build.log"; refuse "chip build failed"; } echo "== chip run (not killed, not timed out)" # LDST_CHIP_ARGS (optional) e.g. "--spec 129 --repeats 500" reruns one spec; default is the whole table. "$BIN" --chip ${LDST_CHIP_ARGS:-} > "$RUN/chip.log" 2>&1; RC=$? diff --git a/tools/sm121dis/README.md b/tools/sm121dis/README.md index c10aeb978..e696222ef 100644 --- a/tools/sm121dis/README.md +++ b/tools/sm121dis/README.md @@ -1,8 +1,9 @@ -# sm121dis: Omega's own GB10 disassembler +# sm121dis: canonical GB10 disassembler consumer -A disassembler turns the GPU's machine code back into readable instructions. Omega used to borrow NVIDIA's -`nvdisasm` for that, in every check that reads a kernel back. `sm121dis` is our own (row C6 of `docs/OMEGA.md`): -the decoder is `src/omega_sm121_disasm.c`, this folder holds the command line and the comparison with NVIDIA's tool. +A disassembler turns GPU machine code back into readable instructions. This command consumes the +decoder at `src/omega_sm121_disasm.c` from the exact CUDApp revision in `cudapp.lock`; Omega no longer +carries a second decoder implementation. This folder retains the command-line adapter and the +comparison with NVIDIA's independently versioned `nvdisasm` oracle. ## What it proves diff --git a/tools/tensor_mutations.sh b/tools/tensor_mutations.sh index 11457f4c0..be8ea3b78 100755 --- a/tools/tensor_mutations.sh +++ b/tools/tensor_mutations.sh @@ -24,42 +24,54 @@ set -u cd "$(dirname "$0")/.." || exit 2 SCRATCH=$(mktemp -d "${TMPDIR:-/tmp}/tensor-mut.XXXXXX") || exit 2 trap 'rm -rf "$SCRATCH"' EXIT INT TERM +WORK=$SCRATCH/source +bash tools/e1_manifest.sh --canonical-overlay "$WORK" >/dev/null || exit 2 +cat "$WORK/cudapp-source.json" >&2 # --gb10 PHYSICS_DIR: the GB10 realization table (src/tensor/omega_tensor_gb10.c, -# M20 cut gb10). Builds tests/test_omega_tensor_gb10.c against the physics -# checkout and runs it WITHOUT --chip (host self checks, no device). Also -# requires, via nm, that the GB10 table references no CPU or reference tier +# M20 cut gb10). Builds against the authenticated CUDApp source/driver closure +# plus the existing physics forge oracle, then runs WITHOUT --chip (host only). +# Also requires, via nm, that the GB10 table references no CPU or reference tier # (no silent CPU fallback). Each GB10_MUTATIONS rule must then make the host # run or the nm check fail. Never opens the device. if [ "${1:-}" = "--gb10" ]; then PHYS=${2:-} [ -n "$PHYS" ] && [ -d "$PHYS" ] || { echo "tensor gb10 mutation sweep: --gb10 needs the physics checkout"; exit 2; } - NV=$PHYS/third_party/nvidia-open-580.173.02 - GFLAGS="-std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -Isrc -I$PHYS/forge -I$PHYS/nvrm -I$PHYS/m16 \ + PHYS=$(cd "$PHYS" && pwd -P) || exit 2 + STAGE=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} + CANONICAL=$(cd "$STAGE/source" && pwd -P) || exit 2 + NV=$CANONICAL/third_party/nvidia-open-580.173.02 + GFLAGS="-std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -Isrc -I$PHYS/forge -I$CANONICAL/nvrm -I$CANONICAL/m16 \ -I$NV/src/common/sdk/nvidia/inc -I$NV/kernel-open/common/inc -I$NV/kernel-open/nvidia-uvm -I$NV/src/nvidia/arch/nvalloc/unix/include" GDEPS="src/omega_numeric_reduce.c src/omega_numeric_transc.c src/omega_numeric_reduce_gb10.c src/omega_numeric.c src/omega_numeric_gb10.c \ src/omega_numeric_divsqrt_gb10.c src/omega_numeric_provenance.c src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c \ -src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/forge_realization.c src/aegis_verification.c src/omega_om_units.c \ -$PHYS/forge/forge_descriptor.c $PHYS/forge/forge_realize.c $PHYS/sha256_clean.c $PHYS/nvrm/nvrm.c $PHYS/m16/m16_native.c" +src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/forge_realization.c src/aegis_verification.c src/omega_om_units.c src/cudapp_om_units.c \ +$PHYS/forge/forge_descriptor.c $PHYS/forge/forge_realize.c $PHYS/sha256_clean.c $CANONICAL/nvrm/nvrm.c $CANONICAL/m16/m16_native.c" CPU_TIER='\b(omega_numeric_cpu_realize|omega_numeric_reference|omega_numeric_reference_ftz|omega_reduce_cpu|omega_reduce_rows_cpu|omega_reduce_reference|omega_reduce_rows_reference|omega_tensor_seam_reduce_cpu)\b' GB10_MUTATIONS='GB10_NO_CPU_FALLBACK|s/return OMEGA_NUMERIC_ERR_NOT_ENCODED;/return omega_numeric_cpu_realize(op, a, b, c, out, n);/ GB10_REDUCE_MAX_N|s/if (n > OMEGA_REDUCE_GB10_MAX_N) return OMEGA_NUMERIC_ERR_OPERANDS;/(void)0;/ GB10_ROWS_MAX_N|s/if (n > OMEGA_REDUCE_GB10_MAX_N) return OMEGA_NUMERIC_ERR_OPERANDS;/(void)0;/' # gb10_try DIR: 0 if build + host run + nm check all pass, 1 otherwise gb10_try() { - gcc $GFLAGS -I"$1" -o "$SCRATCH/g" tests/test_omega_tensor_gb10.c "$1/omega_tensor.c" "$1/omega_tensor_cpu.c" \ - "$1/omega_tensor_reduce_seam.c" "$1/omega_tensor_gb10.c" $GDEPS > "$SCRATCH/gbuild.log" 2>&1 || return 2 - gcc $GFLAGS -I"$1" -c -o "$SCRATCH/g.o" "$1/omega_tensor_gb10.c" >> "$SCRATCH/gbuild.log" 2>&1 || return 2 - if nm -u "$SCRATCH/g.o" | grep -Eq "$CPU_TIER"; then echo " nm: GB10 table references a CPU/reference tier"; return 1; fi + (cd "$WORK" && gcc $GFLAGS -I"$1" -o "$SCRATCH/g" tests/test_omega_tensor_gb10.c "$1/omega_tensor.c" "$1/omega_tensor_cpu.c" \ + "$1/omega_tensor_reduce_seam.c" "$1/omega_tensor_gb10.c" $GDEPS) > "$SCRATCH/gbuild.log" 2>&1 || return 2 + (cd "$WORK" && gcc $GFLAGS -I"$1" -c -o "$SCRATCH/g.o" "$1/omega_tensor_gb10.c") >> "$SCRATCH/gbuild.log" 2>&1 || return 2 + nm -u "$SCRATCH/g.o" > "$SCRATCH/undefined-symbols" || return 2 + [ -s "$SCRATCH/undefined-symbols" ] || return 2 + grep -E "$CPU_TIER" "$SCRATCH/undefined-symbols" > "$SCRATCH/cpu-references"; scan=$? + case $scan in + 0) echo " nm: GB10 table references a CPU/reference tier"; return 1;; + 1) ;; *) return 2;; + esac "$SCRATCH/g" > "$SCRATCH/grun.log" 2>&1 || return 1 return 0 } - gb10_try src/tensor; rc=$? + gb10_try "$WORK/src/tensor"; rc=$? if [ "$rc" -ne 0 ]; then head -20 "$SCRATCH/gbuild.log" "$SCRATCH/grun.log" 2>/dev/null echo "tensor gb10 mutation sweep: FAIL (unmutated GB10 baseline does not pass, rc $rc)"; exit 1 fi - grep -E '^(TENSOR_GB10_HOST|HOST_HARNESS_MUTANTS|HOST_MUTANT_)' "$SCRATCH/grun.log" + grep -E '^(TENSOR_GB10_HOST|HOST_HARNESS_MUTANTS|HOST_MUTANT_)' "$SCRATCH/grun.log" || exit 2 echo "GB10 nm check: PASS (no CPU or reference tier referenced by omega_tensor_gb10.c)" gfail=0; gtotal=0 old_ifs=$IFS @@ -69,9 +81,9 @@ GB10_ROWS_MAX_N|s/if (n > OMEGA_REDUCE_GB10_MAX_N) return OMEGA_NUMERIC_ERR_OPER IFS=$old_ifs gname=${m%%|*}; gexpr=${m#*|} gtotal=$((gtotal + 1)) - rm -rf "$SCRATCH/tensor" && cp -r src/tensor "$SCRATCH/tensor" - sed -i "/MUT:$gname/ $gexpr" "$SCRATCH/tensor/omega_tensor_gb10.c" - if cmp -s src/tensor/omega_tensor_gb10.c "$SCRATCH/tensor/omega_tensor_gb10.c"; then + rm -rf "$SCRATCH/tensor" && cp -r "$WORK/src/tensor" "$SCRATCH/tensor" || exit 2 + sed -i "/MUT:$gname/ $gexpr" "$SCRATCH/tensor/omega_tensor_gb10.c" || exit 2 + if cmp -s "$WORK/src/tensor/omega_tensor_gb10.c" "$SCRATCH/tensor/omega_tensor_gb10.c"; then echo "MUTATION $gname: NOT APPLIED (marker or pattern missing)"; gfail=1; continue fi gb10_try "$SCRATCH/tensor"; rc=$? @@ -87,7 +99,7 @@ GB10_ROWS_MAX_N|s/if (n > OMEGA_REDUCE_GB10_MAX_N) return OMEGA_NUMERIC_ERR_OPER exit 0 fi DEPS="src/omega_numeric_reduce.c src/omega_numeric_transc.c src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c \ -src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c" +src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_om_units.c src/cudapp_om_units.c" FLAGS="-std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -O2 -DOMEGA_NUMERIC_CPU_ONLY -DOMEGA_TENSOR_TEST_HOOKS" # name|file|sed expression (applied only to the line carrying MUT:) @@ -144,8 +156,10 @@ total=0 # is replaced by the runner's one-line build error note. run_block() { rb_rows=$1 - "tools/mutation_runner.sh" -k marker -m "$rb_rows" -t "$3" -b "$2" -c "src tests" -f FAIL -B \ + "tools/mutation_runner.sh" -k marker -m "$rb_rows" -d "$WORK" -t "$3" -b "$2" -c "src tests" -f FAIL -B \ > "$SCRATCH/rb.out" 2> "$SCRATCH/rb.err" + rb_rc=$? + [ "$rb_rc" -eq 0 ] || fail=1 if grep -q 'unmutated baseline does not pass' "$SCRATCH/rb.out"; then cat "$SCRATCH/rb.err"; return 3 fi @@ -170,7 +184,8 @@ run_block() { # The legacy sweep walked the rows itself, so a row could not be skipped. # A runner that died, was killed or reported nothing must not pass silently: # one verdict line per row is required. - rb_want=$(grep -c '|' "$rb_rows") + rb_want=$(grep -c '|' "$rb_rows") || { fail=1; return 2; } + [ "$rb_want" -gt 0 ] || { fail=1; return 2; } if [ "$rb_seen" -ne "$rb_want" ]; then echo "MUTATION $rb_rows: runner reported $rb_seen verdicts for $rb_want rows (runner died or reported nothing)" fail=1