diff --git a/.crumb b/.crumb index 4c29c6660..4b1f89d5b 100644 --- a/.crumb +++ b/.crumb @@ -47,8 +47,8 @@ "purpose": "Directory calibration. Purpose not yet described by a human." }, { - "digest": "f00281122c0cb3bce9288b99d79cae539f9824faa48ac0bf3e0ce9e3020fed80", - "last_commit": "27997f9ba", + "digest": "5687ce12cd5ab387b3ec020ca7325923acdc085b4ccbfe45913ac38c36e7d296", + "last_commit": "28fbba3e4", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, @@ -59,8 +59,8 @@ "purpose": "Directory doctrine. Purpose not yet described by a human." }, { - "digest": "c0668c8969cceab0f03ac6ab352ae579c8b473a9ec743d80c89fc187b769c12c", - "last_commit": "22011cbc9", + "digest": "5490f02828f11619c2a427905af48d9d2e3711067e60f72a34ea7b7a69a041b2", + "last_commit": "8e6277d4e", "name": "mk", "purpose": "Directory mk. Purpose not yet described by a human." }, @@ -84,38 +84,38 @@ }, { "digest": "18cd9ce64969204d94b2c93ffa14e83324eebdc71b2c8b468bcaa0b02eee19cf", - "last_commit": "f5c9bd89a", + "last_commit": "0ccdd31d7", "name": "spec", "purpose": "Directory spec. Purpose not yet described by a human." }, { - "digest": "0b45b3b8037fb89222c06563d9cde31caf762b9751994fafa603e1c84d350d91", - "last_commit": "9920aab14", + "digest": "0b8df0bac6a60addd4eb8323b0251db5b55b901a9c965d0d12a2e76bfaae661f", + "last_commit": "28fbba3e4", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "0a1bedfebbcc0e923a70af1b3537bc5af1f45a79c527e517aace0bf4c5287dcf", - "last_commit": "089d63253", + "digest": "42ce588746fbb9982a309142a06639206247d5fada0e859b804eb7e7b17a164a", + "last_commit": "9c340520d", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, { - "digest": "c9c0eb6fcb03f5be2576714a9b49e2ead49190277059fcbbd253f49db07c047d", - "last_commit": "22011cbc9", + "digest": "d4c5b2b33f12a1d46e845315d1e5ec71c40b7104ecaef4542ceebede179c5f54", + "last_commit": "ef2aba148", "name": "tools", "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:7685e485f4351c4a698eaf416894e06aa7d845cbc9269c9ef43f4eb561d2ba6e", - "compiled_at": "2026-10-31T13:29:24Z", + "children_root": "sha256:9906a77f425aebf392693aeed8598ec544e5964676ff83a2c723a46e553844d4", + "compiled_at": "2026-10-31T13:42:24Z", "compiler": "crumb-compile/1", - "digest": "sha256:4e146d21cc7e24b5245ee33654daa0a487eacb5ebb53b0d033d4cff531686259", + "digest": "sha256:712d04319e148c6a5fde5ef766412c43be47d1a863b229ceb24814268e340eaf", "evidence_files": 14989, "evidence_root": "sha256:90148c46bbc2cd096c96064273ac90d63efb54260fe285e18d84429cdf657830", - "files": 23228, - "generated_at_commit": "1840dd869407c96429bab4780b69a7da9b194950", - "source_tree": "sha256:d6c3fb10bc3468b319246f34bd5697741b292c1c42ef4b2370f7aa8eb525ef59" + "files": 23040, + "generated_at_commit": "9c340520d54efa93c955f008e50defaccfae7fb5", + "source_tree": "sha256:1fe2f167afd3a05a8baffc1702720df131c8928c354a21771d6f25ec0cd2a740" }, "owner_lane": "", "provenance": { diff --git a/AGENTS.md b/AGENTS.md index 9085b3de2..7c6f53629 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 6cc82c7db..34275099a 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -7,6 +7,7 @@ The current development method is [Human-Directed Agentic Engineering (HDAE)](RE | 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 | | Claude Opus 5.5 (via omp) | OM-2 `scrub` keeps live float registers: since #853 an f32/f64 local name and a held float value live in the V16+j twin of their pool slot, but #875's scrub still zeroed V0-V31, so a live float read back 0 after `scrub` (repro exit 50 on omc `24caacf4…abb7`). scrub now spares exactly the twins of live slots that hold their value there (vsl) and zeroes V0-V15 and every dead twin; s5 fixtures `scrub-flive`/`scrub-femit` and mutants `m-twinall`/`m-twinnone`; OMEGESE 9.13.1; reseed, omc `be8c5130…448a`, pins moved, src units regenerated, size-history row. | | Claude Opus 5.5 (via omp) | #857 merged with main `157bab57` (#848 squash): `omc.om` is main plus only #857's for-bound, IR bound/count range and IR for-guard edits (ir_if/ir_else/ir_doret stay folded as on main); gate16/gate-ir tables and OMEGESE text kept from both sides; reseed, omc `24caacf4…abb7`, pins moved from `90c8884c…3983`, src units regenerated, size-history row. | | Claude Opus 5.5 (via omp) | #857 residual: IR mode refuses a `for` count that is a number or integer constant outside 0..1000000 (a minus sign included) with error 8, the C oracle's count range; before, `for i ulong 1000001` and `const K ulong 1000001` compiled to an unguarded loop checker2 rejects (C2-LOOP-UNBOUNDED) and `for i long -1`/`-0` compiled where the oracle refuses. gate-ir units for both sides; reseed, omc `0d4c722b…a008`. | diff --git a/Makefile b/Makefile index 6011dfa5d..9ebb7d6ab 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,82 +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)) -# sm_121 instruction encoder (twin of aien-dev/CUDApp#79): om (default) = om/encoder/bw_enc_sm121.om through the -# generated binding src/omega_om_units.c; c = the migration-pending C encoder, the differential oracle; diff = both on -# every call, abort on any difference (mk/om-encoder.mk). Use a separate OUT_DIR per value. The macro names keep -# CUDApp's spelling so src/omega_blackwell_codegen.c stays the same file in both repositories. -CUDAPP_ENCODER ?= om -CUDAPP_ENCODER_DEFS_om := -CUDAPP_ENCODER_DEFS_c := -DCUDAPP_MIGRATION_PENDING_C_ENCODER -CUDAPP_ENCODER_DEFS_diff := -DCUDAPP_MIGRATION_PENDING_ENCODER_DIFF -CUDAPP_ENCODER_DEFS = $(CUDAPP_ENCODER_DEFS_$(CUDAPP_ENCODER)) -ifeq ($(filter om c diff,$(CUDAPP_ENCODER)),) -$(error CUDAPP_ENCODER must be om, c or diff) -endif - +# 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 src/omega_clean_clone.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 -# Expert Ribbon P1 (aienix#4 / omega#533, 2026-10-18): versioned replaceable FP8 expert slots, new files only -SRCS += src/omega_fp8_slot_table.c src/omega_gpu_fp8_slots.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 src/omega_clean_clone.c tools/omegatool.c OBJS = $(patsubst %.c,$(OUT_DIR)/%.o,$(notdir $(SRCS))) DEPS = $(OBJS:.o=.d) -include $(DEPS) @@ -149,12 +85,6 @@ $(PHYSICS_STAMP): check-physics-lock | $(OUT_DIR) if [ "$$(cat $@ 2>/dev/null)" != "$$new" ]; then printf '%s\n' "$$new" > $@; fi $(PHYSICS_OBJS): $(PHYSICS_STAMP) -$(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 $@ @@ -174,8 +104,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 @@ -284,9 +214,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 @@ -324,9 +254,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 @@ -709,16 +639,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) @@ -778,9 +705,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 @@ -795,9 +720,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) @@ -848,15 +773,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) @@ -884,9 +803,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 @@ -896,9 +813,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) @@ -920,9 +837,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) @@ -949,14 +866,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 @@ -1037,10 +954,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 @@ -1055,10 +969,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 @@ -1256,7 +1167,7 @@ $(RX_ROUTE_OBJ): src/runtime/rx_route.c src/runtime/rx_route.h src/runtime/rx_ge $(RX_ROUTE_TEST): $(RX_ROUTE_SRCS) $(RX_ROUTE_OBJ) tests/runtime/rx_cog_engines.h \ src/runtime/aienos_cap.h $(AIENOS_CAP_LIB) | $(OUT_DIR) - $(CC) $(CFLAGS) -Itests -o $@ $(RX_ROUTE_SRCS) $(RX_ROUTE_OBJ) $(AIENOS_CAP_LIB) -lm + $(CC) $(CFLAGS) -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(RX_ROUTE_SRCS) $(RX_ROUTE_OBJ) $(AIENOS_CAP_LIB) -lm test-cognitive-routing: $(RX_ROUTE_TEST) ./$(RX_ROUTE_TEST) @@ -1495,10 +1406,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 @@ -1942,15 +1853,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 @@ -1968,12 +1876,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: @@ -1990,9 +1897,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 @@ -2011,14 +1918,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: @@ -2321,7 +2226,7 @@ RESOLVE_HDRS += src/omega_genesis.h src/omega_vcstore_priv.h src/omega_program_i .PHONY: test-genesis GENESIS_DIR = $(OUT_DIR)/genesis-test GENESIS_STACK = src/omega_receipt.c src/omega_blake3.c src/omega_om_units.c $(RESOLVE_PROGRAM_STACK) -GENESIS_CFLAGS = $(RESOLVE_FLAGS) -I$(GENESIS_DIR) -Itests +GENESIS_CFLAGS = $(RESOLVE_FLAGS) -I$(GENESIS_DIR) -I$(CUDAPP_SOURCE)/tests -Itests test-genesis: tests/test_omega_genesis_set.c tests/genesis_variant/member.inc src/omega_vcstore.c src/omega_resolve.c src/omega_genesis.h $(RESOLVE_HDRS) @set -eu; mkdir -p $(GENESIS_DIR)/genesis_variant; \ sed -e 's|^#define OMEGA_GENESIS_1_COUNT 0u|#define OMEGA_GENESIS_1_COUNT 1u|' -e 's|^#define OMEGA_GENESIS_SET_NAME "VC-GENESIS-1"|#define OMEGA_GENESIS_SET_NAME "VC-GENESIS-1-TEST-VARIANT"|' src/omega_genesis.h \ @@ -2500,9 +2405,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 @@ -2510,22 +2415,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 $(OUT_DIR)/omega_clean_clone.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): $(CUDAPP_SOURCE)/tests/gpu_matmul_api_test.c $(CUDAPP_SOURCE)/src/omega_gpu_matmul_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ $(CUDAPP_SOURCE)/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 @@ -2533,8 +2441,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): $(CUDAPP_SOURCE)/tests/gpu_matmul_r4_receipt.c $(CUDAPP_SOURCE)/src/omega_gpu_matmul_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ $(CUDAPP_SOURCE)/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 @@ -2542,8 +2450,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): $(CUDAPP_SOURCE)/tests/gpu_elementwise_test.c $(CUDAPP_SOURCE)/src/omega_gpu_elementwise_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -o $@ $(CUDAPP_SOURCE)/tests/gpu_elementwise_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-elementwise: $(GPU_EW_TEST) ./$(GPU_EW_TEST) --host-only @@ -2551,19 +2459,19 @@ 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): $(CUDAPP_SOURCE)/tests/bw_encode_control_test.c $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ $(CUDAPP_SOURCE)/tests/bw_encode_control_test.c $(GPU_LINK_LIBS) -lpthread -lm test-bw-encode-control: $(BW_ENCODE_CONTROL_TEST) ./$(BW_ENCODE_CONTROL_TEST) # omega #308: structured warp reconvergence (BSSY/BSYNC regions). test-gpu-reconv is # host-only (encoder goldens, region bookkeeping, refusals, nvdisasm listing, every probe -# kernel through the SIMT warp simulator tests/bw_warp_sim.h against the oracle, mutation +# kernel through the SIMT warp simulator $(CUDAPP_SOURCE)/tests/bw_warp_sim.h against the oracle, mutation # 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): $(CUDAPP_SOURCE)/tests/gpu_reconv_test.c $(CUDAPP_SOURCE)/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) -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/tests/gpu_reconv_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-reconv: $(GPU_RECONV_TEST) ./$(GPU_RECONV_TEST) --host-only @@ -2574,8 +2482,8 @@ test-gpu-reconv: $(GPU_RECONV_TEST) .PHONY: test-gpu-imadhi-rc GPU_IMADHI_SIMS = bw_warp_sim bw_warp_sim_tc bw_warp_sim_k bw_warp_sim_pa GPU_IMADHI_TESTS = $(GPU_IMADHI_SIMS:%=$(OUT_DIR)/gpu_imadhi_rc_test_%) -$(OUT_DIR)/gpu_imadhi_rc_test_%: tests/gpu_imadhi_rc_test.c tests/%.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -Itests -DSIM_HEADER='"$*.h"' -o $@ tests/gpu_imadhi_rc_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(OUT_DIR)/gpu_imadhi_rc_test_%: $(CUDAPP_SOURCE)/tests/gpu_imadhi_rc_test.c tests/%.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -I$(CUDAPP_SOURCE)/tests -Itests -DSIM_HEADER='"$*.h"' -o $@ $(CUDAPP_SOURCE)/tests/gpu_imadhi_rc_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-imadhi-rc: $(GPU_IMADHI_TESTS) @for t in $(GPU_IMADHI_TESTS); do ./$$t || exit 1; done @@ -2588,8 +2496,8 @@ test-gpu-imadhi-rc: $(GPU_IMADHI_TESTS) # (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): $(CUDAPP_SOURCE)/tests/gpu_attention_test.c $(CUDAPP_SOURCE)/tests/bw_warp_sim.h $(CUDAPP_SOURCE)/src/omega_gpu_attention_api.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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 @@ -2599,15 +2507,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: $(CUDAPP_SOURCE)/tests/gpu_session_probe.c $(CUDAPP_SOURCE)/src/omega_gpu_session.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ $(CUDAPP_SOURCE)/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 +# OWN-30B cut 2: window matmul gate ($(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/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 @@ -2618,8 +2526,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): $(CUDAPP_SOURCE)/tests/gpu_fp8_api_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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 @@ -2629,39 +2537,39 @@ 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): $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_decode_attn_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/tests/gpu_decode_attn_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-decode-attn: $(GPU_DATTN_TEST) test-gpu-decode-attn-maxpos $(GPU_DATTN_TEST) --host-only $(GPU_DATTN_TEST) --sim # omega #535: the 128k position bound (OMEGA_GPU_DATTN_MAX_POS 131072) on a fake platform, no device. A sanitized copy -# of src/omega_gpu_decode_attn_api.c is linked ahead of the library, so cache writes, the RoPE fill and launch staging +# of $(CUDAPP_SOURCE)/src/omega_gpu_decode_attn_api.c is linked ahead of the library, so cache writes, the RoPE fill and launch staging # are ASan/UBSan checked against the fake's exact-size buffers. Each mutant breaks one bound in a copy of that file; # the test must FAIL on it. .PHONY: test-gpu-decode-attn-maxpos GPU_DATTN_MAXPOS_TEST = $(OUT_DIR)/test_omega_gpu_decode_attn_maxpos GPU_DATTN_MAXPOS_MUT = $(OUT_DIR)/dattn_maxpos_mut GPU_DATTN_MAXPOS_SAN = -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all -$(GPU_DATTN_MAXPOS_TEST): tests/test_omega_gpu_decode_attn_maxpos.c src/omega_gpu_decode_attn_api.c src/omega_gpu_decode_attn_api.h src/omega_blackwell_codegen_attn.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(filter-out -MMD -MP -O2,$(CFLAGS)) $(GPU_DATTN_MAXPOS_SAN) -o $@ tests/test_omega_gpu_decode_attn_maxpos.c \ - src/omega_gpu_decode_attn_api.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_DATTN_MAXPOS_TEST): $(CUDAPP_SOURCE)/tests/test_omega_gpu_decode_attn_maxpos.c $(CUDAPP_SOURCE)/src/omega_gpu_decode_attn_api.c $(CUDAPP_SOURCE)/src/omega_gpu_decode_attn_api.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_attn.h $(GPU_LINK_LIBS) + $(CC) $(filter-out -MMD -MP -O2,$(CFLAGS)) $(GPU_DATTN_MAXPOS_SAN) -o $@ $(CUDAPP_SOURCE)/tests/test_omega_gpu_decode_attn_maxpos.c \ + $(CUDAPP_SOURCE)/src/omega_gpu_decode_attn_api.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-decode-attn-maxpos: $(GPU_DATTN_MAXPOS_TEST) $(GPU_DATTN_MAXPOS_TEST) @mkdir -p $(GPU_DATTN_MAXPOS_MUT) @set -e; \ tmut() { name=$$1; script=$$2; \ - sed -e "$$script" src/omega_gpu_decode_attn_api.c > $(GPU_DATTN_MAXPOS_MUT)/$$name.c; \ - if cmp -s src/omega_gpu_decode_attn_api.c $(GPU_DATTN_MAXPOS_MUT)/$$name.c; then echo "mutant $$name: pattern not found"; exit 1; fi; \ + sed -e "$$script" $(CUDAPP_SOURCE)/src/omega_gpu_decode_attn_api.c > $(GPU_DATTN_MAXPOS_MUT)/$$name.c; \ + if cmp -s $(CUDAPP_SOURCE)/src/omega_gpu_decode_attn_api.c $(GPU_DATTN_MAXPOS_MUT)/$$name.c; then echo "mutant $$name: pattern not found"; exit 1; fi; \ $(CC) $(filter-out -MMD -MP -O2,$(CFLAGS)) $(GPU_DATTN_MAXPOS_SAN) -o $(GPU_DATTN_MAXPOS_MUT)/$$name \ - tests/test_omega_gpu_decode_attn_maxpos.c $(GPU_DATTN_MAXPOS_MUT)/$$name.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm; \ + $(CUDAPP_SOURCE)/tests/test_omega_gpu_decode_attn_maxpos.c $(GPU_DATTN_MAXPOS_MUT)/$$name.c $(GPU_LINK_LIBS) -lpthread -lm; \ if $(GPU_DATTN_MAXPOS_MUT)/$$name > $(GPU_DATTN_MAXPOS_MUT)/$$name.log 2>&1; then echo "mutant $$name SURVIVED"; exit 1; fi; \ if ! grep -q '^FAIL ' $(GPU_DATTN_MAXPOS_MUT)/$$name.log; then \ echo "mutant $$name: no FAIL case (did not run?)"; cat $(GPU_DATTN_MAXPOS_MUT)/$$name.log; exit 1; fi; \ @@ -2680,8 +2588,8 @@ test-gpu-decode-attn-maxpos: $(GPU_DATTN_MAXPOS_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): $(CUDAPP_SOURCE)/tests/gpu_decode_attn256_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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 @@ -2690,8 +2598,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): $(CUDAPP_SOURCE)/tests/gpu_router_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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 @@ -2700,15 +2608,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): $(CUDAPP_SOURCE)/tests/gpu_gdn_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_gdn_multi_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/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) -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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 @@ -2718,8 +2626,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): $(CUDAPP_SOURCE)/tests/gpu_bf16_gemv_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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 @@ -2729,30 +2637,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 $(CUDAPP_SOURCE)/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) -I$(CUDAPP_SOURCE)/tests -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: $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_fp8gemm_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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 $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -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) -I$(CUDAPP_SOURCE)/tests -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 @@ -2760,8 +2668,8 @@ 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): $(CUDAPP_SOURCE)/tests/gpu_gpr_boundary_test.c $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ $(CUDAPP_SOURCE)/tests/gpu_gpr_boundary_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-gpr-boundary: $(GPU_GPR_BOUNDARY_TEST) $(GPU_GPR_BOUNDARY_TEST) @@ -2772,8 +2680,8 @@ test-gpu-gpr-boundary: $(GPU_GPR_BOUNDARY_TEST) # kernel (bar C6: every check that called nvdisasm calls ours; test-sm121dis checks that disassembler against the oracle). .PHONY: test-bw-hazard test-bw-hazard-nvdisasm BW_HAZARD_TEST = $(OUT_DIR)/bw_hazard_test -$(BW_HAZARD_TEST): tests/bw_hazard_test.c src/omega_bw_hazard.c src/omega_bw_hazard.h src/omega_sm121_disasm.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -o $@ tests/bw_hazard_test.c src/omega_bw_hazard.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(BW_HAZARD_TEST): $(CUDAPP_SOURCE)/tests/bw_hazard_test.c $(CUDAPP_SOURCE)/src/omega_bw_hazard.c $(CUDAPP_SOURCE)/src/omega_bw_hazard.h $(CUDAPP_SOURCE)/src/omega_sm121_disasm.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ $(CUDAPP_SOURCE)/tests/bw_hazard_test.c $(CUDAPP_SOURCE)/src/omega_bw_hazard.c $(GPU_LINK_LIBS) -lpthread -lm test-bw-hazard: $(BW_HAZARD_TEST) $(BW_HAZARD_TEST) test-bw-hazard-nvdisasm: $(BW_HAZARD_TEST) @@ -2781,43 +2689,43 @@ test-bw-hazard-nvdisasm: $(BW_HAZARD_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): $(CUDAPP_SOURCE)/tests/gpu_tc_probe_test.c $(CUDAPP_SOURCE)/tests/bw_hmma_model.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_tc.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_tcgemm_test.c $(CUDAPP_SOURCE)/tests/bw_hmma_model.h $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_tc_peak_test.c $(CUDAPP_SOURCE)/tests/bw_hmma_model.h $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_prefill_attn_test.c $(CUDAPP_SOURCE)/tests/bw_hmma_model.h $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_prefill_attn256_test.c $(CUDAPP_SOURCE)/tests/bw_hmma_model.h $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_pf_mem_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_pfgemm_test.c $(CUDAPP_SOURCE)/tests/bw_hmma_model.h $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_qmma_probe_test.c $(CUDAPP_SOURCE)/tests/bw_qmma_model.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen_qmma.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_qgemm_test.c $(CUDAPP_SOURCE)/tests/bw_qmma_model.h $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_pfhost_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/tests/gpu_pfhost_test.c $(GPU_LINK_LIBS) -lpthread -lm # omega#456: the prefill tests above, host model and warp simulator only. Every run names --host-only or --sim, the two # modes that never open the device (each test's main returns before its chip part); chip runs stay under the GB10 lock. .PHONY: test-gpu-prefill-host @@ -2840,7 +2748,7 @@ test-gpu-prefill-host: $(GPU_TC_PROBE_TEST) $(GPU_TCGEMM_TEST) $(GPU_PATTN_TEST) # omega#456: tools/own30b_decode_profile.c is a link-only recorder built by hand on the Spark; compile it with the # project's -Werror flags so a warning cannot land unseen. .PHONY: check-own30b-decode-profile -check-own30b-decode-profile: tools/own30b_decode_profile.c +check-own30b-decode-profile: tools/own30b_decode_profile.c | check-cudapp @mkdir -p $(OUT_DIR) $(CC) $(CFLAGS) -c -o $(OUT_DIR)/own30b_decode_profile.o tools/own30b_decode_profile.c @echo "check-own30b-decode-profile: PASS (compiles with -Werror)" @@ -2848,8 +2756,8 @@ check-own30b-decode-profile: tools/own30b_decode_profile.c # 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): $(CUDAPP_SOURCE)/tests/gpu_cmdlist_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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 @@ -2859,8 +2767,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): $(CUDAPP_SOURCE)/tests/gpu_streams_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/tests/gpu_streams_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-streams: $(GPU_STREAMS_TEST) ./$(GPU_STREAMS_TEST) --sim @@ -2869,8 +2777,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): $(CUDAPP_SOURCE)/tests/gpu_isolation_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/tests/gpu_isolation_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-isolation: $(GPU_ISOLATION_TEST) ./$(GPU_ISOLATION_TEST) --host-only @@ -2879,8 +2787,8 @@ test-gpu-isolation: $(GPU_ISOLATION_TEST) .PHONY: test-gpu-decode-graph GPU_DECODE_GRAPH_TEST = $(OUT_DIR)/gpu_decode_graph_test GPU_DGRAPH_ABORT_TEST = $(OUT_DIR)/test_omega_gpu_decode_graph_abort -$(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): $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/tests/gpu_decode_graph_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-decode-graph: $(GPU_DECODE_GRAPH_TEST) $(GPU_DGRAPH_ABORT_TEST) test-gpu-decode-graph-abort-mutants test-gpu-decode-graph-timeline ./$(GPU_DECODE_GRAPH_TEST) --host-only ./$(GPU_DGRAPH_ABORT_TEST) @@ -2890,17 +2798,17 @@ test-gpu-decode-graph: $(GPU_DECODE_GRAPH_TEST) $(GPU_DGRAPH_ABORT_TEST) test-gp # Each mutant breaks one rule in a copy of omega_gpu_decode_graph.c linked ahead of the library; the test must FAIL on it. .PHONY: test-gpu-decode-graph-abort-mutants GPU_DGRAPH_MUT_DIR = $(OUT_DIR)/dgraph_mut -$(GPU_DGRAPH_ABORT_TEST): tests/test_omega_gpu_decode_graph_abort.c src/omega_gpu_decode_graph.h src/omega_gpu_platform.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -o $@ tests/test_omega_gpu_decode_graph_abort.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm -test-gpu-decode-graph-abort-mutants: $(OUT_DIR)/libomega_gpu.a +$(GPU_DGRAPH_ABORT_TEST): $(CUDAPP_SOURCE)/tests/test_omega_gpu_decode_graph_abort.c $(CUDAPP_SOURCE)/src/omega_gpu_decode_graph.h $(CUDAPP_SOURCE)/src/omega_gpu_platform.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ $(CUDAPP_SOURCE)/tests/test_omega_gpu_decode_graph_abort.c $(GPU_LINK_LIBS) -lpthread -lm +test-gpu-decode-graph-abort-mutants: $(GPU_LINK_LIBS) @mkdir -p $(GPU_DGRAPH_MUT_DIR) @set -e; killed=0; \ dmut() { name=$$1; script=$$2; \ - sed -e "$$script" src/omega_gpu_decode_graph.c > $(GPU_DGRAPH_MUT_DIR)/$$name.c; \ - if cmp -s src/omega_gpu_decode_graph.c $(GPU_DGRAPH_MUT_DIR)/$$name.c; then echo "mutant $$name: pattern not found"; exit 1; fi; \ + sed -e "$$script" $(CUDAPP_SOURCE)/src/omega_gpu_decode_graph.c > $(GPU_DGRAPH_MUT_DIR)/$$name.c; \ + if cmp -s $(CUDAPP_SOURCE)/src/omega_gpu_decode_graph.c $(GPU_DGRAPH_MUT_DIR)/$$name.c; then echo "mutant $$name: pattern not found"; exit 1; fi; \ $(CC) $(filter-out -MMD -MP,$(CFLAGS)) -c -o $(GPU_DGRAPH_MUT_DIR)/$$name.o $(GPU_DGRAPH_MUT_DIR)/$$name.c; \ - $(CC) $(filter-out -MMD -MP,$(CFLAGS)) -o $(GPU_DGRAPH_MUT_DIR)/$$name tests/test_omega_gpu_decode_graph_abort.c \ - $(GPU_DGRAPH_MUT_DIR)/$$name.o $(OUT_DIR)/libomega_gpu.a -lpthread -lm; \ + $(CC) $(filter-out -MMD -MP,$(CFLAGS)) -o $(GPU_DGRAPH_MUT_DIR)/$$name $(CUDAPP_SOURCE)/tests/test_omega_gpu_decode_graph_abort.c \ + $(GPU_DGRAPH_MUT_DIR)/$$name.o $(GPU_LINK_LIBS) -lpthread -lm; \ if ./$(GPU_DGRAPH_MUT_DIR)/$$name > $(GPU_DGRAPH_MUT_DIR)/$$name.log 2>&1; then echo "mutant $$name SURVIVED"; exit 1; fi; \ nfail=$$(grep -c '^FAIL' $(GPU_DGRAPH_MUT_DIR)/$$name.log || true); \ if [ "$$nfail" -eq 0 ]; then echo "mutant $$name: nonzero exit but no FAIL case (did not run?)"; cat $(GPU_DGRAPH_MUT_DIR)/$$name.log; exit 1; fi; \ @@ -2919,17 +2827,17 @@ test-gpu-decode-graph-abort-mutants: $(OUT_DIR)/libomega_gpu.a .PHONY: test-gpu-decode-graph-timeline GPU_DGRAPH_TL_TEST = $(OUT_DIR)/test_omega_gpu_decode_graph_timeline GPU_DGRAPH_TL_MUT = $(OUT_DIR)/dgraph_tl_mut -$(GPU_DGRAPH_TL_TEST): tests/test_omega_gpu_decode_graph_timeline.c src/omega_gpu_decode_graph.h src/omega_gpu_platform.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -o $@ tests/test_omega_gpu_decode_graph_timeline.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_DGRAPH_TL_TEST): $(CUDAPP_SOURCE)/tests/test_omega_gpu_decode_graph_timeline.c $(CUDAPP_SOURCE)/src/omega_gpu_decode_graph.h $(CUDAPP_SOURCE)/src/omega_gpu_platform.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -o $@ $(CUDAPP_SOURCE)/tests/test_omega_gpu_decode_graph_timeline.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-decode-graph-timeline: $(GPU_DGRAPH_TL_TEST) ./$(GPU_DGRAPH_TL_TEST) @mkdir -p $(GPU_DGRAPH_TL_MUT) @set -e; \ tmut() { name=$$1; script=$$2; \ - sed -e "$$script" src/omega_gpu_decode_graph.c > $(GPU_DGRAPH_TL_MUT)/$$name.c; \ - if cmp -s src/omega_gpu_decode_graph.c $(GPU_DGRAPH_TL_MUT)/$$name.c; then echo "mutant $$name: pattern not found"; exit 1; fi; \ - $(CC) $(filter-out -MMD -MP,$(CFLAGS)) -o $(GPU_DGRAPH_TL_MUT)/$$name tests/test_omega_gpu_decode_graph_timeline.c \ - $(GPU_DGRAPH_TL_MUT)/$$name.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm; \ + sed -e "$$script" $(CUDAPP_SOURCE)/src/omega_gpu_decode_graph.c > $(GPU_DGRAPH_TL_MUT)/$$name.c; \ + if cmp -s $(CUDAPP_SOURCE)/src/omega_gpu_decode_graph.c $(GPU_DGRAPH_TL_MUT)/$$name.c; then echo "mutant $$name: pattern not found"; exit 1; fi; \ + $(CC) $(filter-out -MMD -MP,$(CFLAGS)) -o $(GPU_DGRAPH_TL_MUT)/$$name $(CUDAPP_SOURCE)/tests/test_omega_gpu_decode_graph_timeline.c \ + $(GPU_DGRAPH_TL_MUT)/$$name.c $(GPU_LINK_LIBS) -lpthread -lm; \ if ./$(GPU_DGRAPH_TL_MUT)/$$name > $(GPU_DGRAPH_TL_MUT)/$$name.log 2>&1; then echo "mutant $$name SURVIVED"; exit 1; fi; \ if ! grep -q '^FAIL one launch past the timeline' $(GPU_DGRAPH_TL_MUT)/$$name.log; then \ echo "mutant $$name: no FAIL case (did not run?)"; cat $(GPU_DGRAPH_TL_MUT)/$$name.log; exit 1; fi; \ @@ -2938,34 +2846,34 @@ test-gpu-decode-graph-timeline: $(GPU_DGRAPH_TL_TEST) tmut timeline-after-failure 's#if (!g->stamps || g->failed || #if (!g->stamps || #'; \ echo "test-gpu-decode-graph-timeline: 2 of 2 mutants killed" -# 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). +# OWN-30B W-L2c (2026-10-14): per-launch fixed cost inside a command list ($(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/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). +# OWN-30B W-L2d (2026-10-14): L2 reuse of FP8 GEMV weights between two launches of one list ($(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_q38_graph_test.c $(CUDAPP_SOURCE)/src/omega_gpu_q38_graph.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_exact_head_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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): $(CUDAPP_SOURCE)/tests/gpu_scan_test.c $(CUDAPP_SOURCE)/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 -I$(CUDAPP_SOURCE)/tests -Itests -o $@ $(CUDAPP_SOURCE)/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 @@ -2973,9 +2881,11 @@ test-gpu-scan: $(GPU_SCAN_TEST) # C3 (docs/OMEGA.md): matrix multiply of any shape, BF16 and FP8 (e4m3), both layouts, on the tensor cores; bit-exact # 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. +# The test and its tensor-core models are CUDApp's ($(CUDAPP_SOURCE)/tests), the owner of omega_gpu_gemm.h. 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): $(CUDAPP_SOURCE)/tests/gpu_gemm_test.c $(CUDAPP_SOURCE)/tests/bw_warp_sim_tc.h $(CUDAPP_SOURCE)/tests/bw_hmma_model.h \ + $(CUDAPP_SOURCE)/tests/bw_qmma_model.h $(CUDAPP_SOURCE)/src/omega_gpu_gemm.h $(GPU_LINK_LIBS) | check-cudapp + $(CC) $(CFLAGS) -ffp-contract=off -I"$(CUDAPP_SOURCE)/tests" -o $@ $(CUDAPP_SOURCE)/tests/gpu_gemm_test.c $(GPU_LINK_LIBS) -lpthread -lm .PHONY: test-gpu-gemm test-gpu-gemm: $(GPU_GEMM_TEST) ./$(GPU_GEMM_TEST) --sim @@ -2985,7 +2895,7 @@ test-gpu-gemm: $(GPU_GEMM_TEST) # tools/run_gpu_fp8_slots_chip.sh under the GB10 lock (parity vs resident, churn, reader fence via a command list, negative control). .PHONY: test-gpu-fp8-slots GPU_FP8_SLOTS_TEST = $(OUT_DIR)/gpu_fp8_slots_test -$(GPU_FP8_SLOTS_TEST): tests/gpu_fp8_slots_test.c src/omega_gpu_fp8_slots.h src/omega_fp8_slot_table.h src/omega_gpu_fp8_api.h src/omega_gpu_cmdlist.h $(OUT_DIR)/libomega_gpu.a - $(CC) $(CFLAGS) -ffp-contract=off -o $@ tests/gpu_fp8_slots_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +$(GPU_FP8_SLOTS_TEST): $(CUDAPP_SOURCE)/tests/gpu_fp8_slots_test.c $(CUDAPP_SOURCE)/src/omega_gpu_fp8_slots.h $(CUDAPP_SOURCE)/src/omega_fp8_slot_table.h $(CUDAPP_SOURCE)/src/omega_gpu_fp8_api.h $(CUDAPP_SOURCE)/src/omega_gpu_cmdlist.h $(GPU_LINK_LIBS) + $(CC) $(CFLAGS) -ffp-contract=off -o $@ $(CUDAPP_SOURCE)/tests/gpu_fp8_slots_test.c $(GPU_LINK_LIBS) -lpthread -lm test-gpu-fp8-slots: $(GPU_FP8_SLOTS_TEST) ./$(GPU_FP8_SLOTS_TEST) --host-only diff --git a/README.md b/README.md index 8664459b4..71e7a4153 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,65 @@ Not yet true on main: the GPU C under `src/omega_blackwell_*`, `src/omega_gpu_*` [aienux](https://github.com/aien-dev/aienux) holds Aienux, the kernel of AienOS, which Omega is meant to run on. [physics-mv](https://github.com/aien-dev/physics-mv) provides FORGE machine realization and the GB10 native path (pinned in `physics.lock`). [aien-architecture-mv](https://github.com/aien-dev/aien-architecture-mv) 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-mv 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 pinned +CUDApp revision `6bfd376` contains the LDG MMIO repair (#172, `27bce88`), the +capacity repair (#173, landed as `a25fb9f`) and the command-list lifetime and +grouped host-acceptance repairs (#174/#175, landed as `8717565`). Merged source +and historical component receipts are not qualification of that manifest. + +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..c8d0215cc --- /dev/null +++ b/cudapp.lock @@ -0,0 +1 @@ +c944ee82fcfb536f44edef3697b081319039b6ca diff --git a/docs/.crumb b/docs/.crumb index 21e93ea0a..13a530336 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -124,14 +124,14 @@ } ], "children_root": "sha256:c81d43c0c392dfec2b6ed5b38ba95ea7c592782b283950e32b777e7b9cfd9d61", - "compiled_at": "2026-10-31T11:59:10Z", + "compiled_at": "2026-10-31T13:42:24Z", "compiler": "crumb-compile/1", - "digest": "sha256:f00281122c0cb3bce9288b99d79cae539f9824faa48ac0bf3e0ce9e3020fed80", + "digest": "sha256:5687ce12cd5ab387b3ec020ca7325923acdc085b4ccbfe45913ac38c36e7d296", "evidence_files": 34, "evidence_root": "sha256:589d8b3706e6d7a202ab20b278dac5fc5bafc973f1c2a867b2668aa7210b65cc", - "files": 147, - "generated_at_commit": "474197e4fa0207e0e2fb3c0494594a975f5031fa", - "source_tree": "sha256:29540f872c6ce1408cb626bc0ed03fb20190295bae8f139baef650dd94727c2d" + "files": 145, + "generated_at_commit": "9c340520d54efa93c955f008e50defaccfae7fb5", + "source_tree": "sha256:2bfb2a14a62503ba6ec3961c4a6676a257dfe52d3fcdeb67886eb8de53e24f39" }, "owner_lane": "", "provenance": { diff --git a/docs/runtime/API.md b/docs/runtime/API.md deleted file mode 100644 index 9f5f34321..000000000 --- a/docs/runtime/API.md +++ /dev/null @@ -1,577 +0,0 @@ -# Omega Runtime API v0 - -Omega Runtime API version: 0.1 - -Status: first written version, 2026-10-19 (slice R1, omega-mv#594, tracking #593). Source of truth is the C headers in -`src/`. This file describes them; `docs/runtime/omega_runtime_api.manifest` lists them; `make test-runtime-api` checks the -list against the headers (a host check, no GPU). Review state: the first version was reviewed by Opus 5.5 on 2026-10-22 (L386). -The sections changed for main 62d1d0d6 (head 2908f13a) were reviewed again by a separate review lane (ApiReview594); its -findings F1-F7 and N1-N5 are fixed in this version. Those fixes were reviewed at head 7be2c6f7 (Rev955), and its six -findings are fixed too; `docs/runtime/API-REVIEW.md` records both reviews. The fixes of the second review have not been -reviewed again. The check proves the list and every quoted C signature match the headers; prose is checked by review. - -The version number lives in one header, `src/omega_runtime_api.h` (`OMEGA_RUNTIME_API_VERSION_MAJOR`, `_MINOR`). - -## 1. What this is - -Omega is a GPU compute runtime that does not use CUDA. This file is the written contract for the part a program calls -directly: find and open the GPU, get memory, copy data in and out, run a kernel, run many kernels in one submission, run a -packaged job, and read errors. It covers what exists on the main branch today, on one machine type (GB10, the DGX Spark), -through the Linux open-driver backend. Nothing here claims more than that. - -How to read an entry: - -| Tier | Meaning | -| --- | --- | -| **STABLE** | Used by other code in the project, covered by chip results, and kept compatible under the rule in section 2. Has its own `####` section below. | -| **EXPERIMENTAL** | Works and is listed, but may change in any minor version, because the design is still moving or only one use of it exists. Listed in tables with the reason. | -| **INTERNAL** | Exists in a header for the project's own libraries or tests. Not part of the API; not in the manifest; may change or disappear any time. Every one declared in a manifest header is named in section 10, so nobody builds on it by accident (the check enforces that list). | - -Every C signature in this file is copied from the header it names. `tools/runtime_api_check.sh` re-checks every quoted -signature against the headers on every run. - -## 2. Version and compatibility rule - -The version is MAJOR.MINOR, currently **0.1**. It is a property of the list of entries and their behaviour, not of the -library build. - -**A MINOR bump (0.1 to 0.2) is allowed to:** -- add a function, a constant, an enum value at the end of an existing enum, or a new struct; -- add an EXPERIMENTAL entry, change or remove an EXPERIMENTAL entry, or move an entry from EXPERIMENTAL to STABLE; -- fix a STABLE function that did not do what this file says (the fix makes it match); -- add a new failure name for the same call to report (callers must treat an unknown failure code or stage text as a failure). - -**It needs a MAJOR bump (0.x to 1.0, then 1.x to 2.0) to:** -- remove or rename a STABLE function, struct, field or constant; -- change a STABLE function's argument or return types, a STABLE struct's size, field order or field offsets, or the value - of a STABLE constant or enum value; -- change documented behaviour of a STABLE entry: what the lock covers, what a latch does, which buffers get parked, what - a return value means; -- move a STABLE entry down to EXPERIMENTAL or INTERNAL; -- raise the platform contract's major number (section 9.2). - -MAJOR 0 means "the first written version", not "anything goes": the rule above already binds STABLE entries in 0.x. What -0 adds is a warning: the project may promote entries to STABLE freely until 1.0 (moving a STABLE entry down still needs a -MAJOR bump, as above), and the first 1.0 will be cut only when -section 8 (what v0 does not have) has been looked at again. - -How it is enforced: a header change that moves any listed entry fails `make test-runtime-api` until the manifest line is -edited on purpose (`tools/runtime_api_check.sh --bless` refreshes the numbers; the diff is reviewed). A reviewer then decides -MINOR or MAJOR using the rule above and edits the version macros and the `Omega Runtime API version:` line in this file; -the check fails if the three disagree. The check cannot tell whether the bump was the right size. That is a review duty. - -The platform contract has its own number (`OMEGA_GPU_PLATFORM_ABI_MAJOR` 1, `OMEGA_GPU_PLATFORM_ABI_MINOR` 2, set in -`src/omega_gpu_platform.h`). A platform minor bump needs at least a runtime MINOR bump; a platform major bump needs a runtime MAJOR bump. - -## 3. How the pieces fit (plain English) - -**Device and platform.** Omega talks to the GPU through a small "platform" layer: a table of services (a clock, a lock, -device-visible memory, a submission queue, a way to poll for completion). Today one platform exists, the Linux reference -(`src/omega_gpu_platform_linux.c`), which uses NVIDIA's open kernel driver. The contract is written so a second backend -(WSL2 on Windows, or AIENOS with no Linux driver) can fill the same table. A program normally never touches the platform: -the first call that needs the GPU installs the Linux reference by itself. There is **one device, one channel per process**. -There is no call to ask the device its name, SM count or memory size yet (section 8). - -**Memory.** You ask the session for a buffer and get an `OmegaGpuMem`: a handle, a CPU pointer, a GPU address and a size. -Every ordinary buffer is GPU-uncached, because the CPU writes inputs the chip reads and polls markers the chip writes. -You make CPU writes visible to the GPU with `omega_gpu_session_sync_to_gpu` and GPU writes visible to the CPU with -`omega_gpu_session_sync_to_cpu`. Code (the machine code of a kernel) lives in a separate kind of buffer -(`omega_gpu_session_alloc_code`): the CPU writes it once, the GPU only executes it. Handles carry a generation number, so a -handle from a closed device or an already freed buffer is refused instead of silently reused. A buffer you mean to reuse and -grow, such as staging space, can be an `OmegaGpuScratch`. For read-only weights there is a GPU-cached allocation -(`omega_gpu_session_alloc_cached`, EXPERIMENTAL). There is no async copy and no unified memory in v0. - -**Launch.** One kernel launch is an `OmegaGpuLaunch`: where the code is, how many registers, the block and grid size, the -argument words, shared memory, and a timeout. `omega_gpu_session_launch` submits it and waits for the chip to finish (it -is synchronous). The wait is by polling a completion word, never by an interrupt. - -**Command lists.** `omega_gpu_cmdlist_*` records many launches and submits them as one unit with one completion wait. By -default each launch is preceded by a barrier so dependent launches cannot overlap; a launch can be marked independent. -EXPERIMENTAL: streams, events and dependency-ordered execution are being built on top of it (omega-mv#580), so its options -and statistics will grow. - -**Job engine.** `omega_gpu_execute` runs one already-built job (today only a 1-D vector job: two inputs, one output) through -named states and returns success or exactly one named failure. EXPERIMENTAL. - -**Errors, the latch and parked buffers.** -- A failing call returns a non-zero value and names its stage in text: `omega_gpu_session_last_error()`. A device-open failure - carries the driver's own text. Do not read a bare return code as the cause. -- If the chip's completion cannot be confirmed (a completion wait ran out of time, the completion poll was refused, or a launch was cancelled after submit), - the work may still be running and still be reading or writing your buffers. The process then **latches**: - `omega_gpu_session_is_blocked()` returns 1 for the rest of the process, every later launch is refused, close and reopen are - refused, and nothing is returned to the platform. -- After the latch, every buffer freed through `omega_gpu_session_free` is **parked**: kept allocated, counted by - `omega_gpu_session_parked`, never released. Handles stay valid for inspection (`omega_gpu_session_is_parked`). -- Recovery in the same process is EXPERIMENTAL (section 9.1; cut C5, `evidence/C5-ISOLATION/`): `omega_gpu_session_recover` - runs the on-close hooks while still latched, closes the device through the platform, and only then lifts the latch. If - the close is refused or reports a driver teardown fault, the process stays latched for good and must exit (header). - That ordering is checked on the host with a fake platform (`evidence/C5-ISOLATION/02-session-platform.log`). What the - Linux reference's close does on the chip is intended, not shown: its RM client close is meant to destroy this process's - channels, and with them any grid still running, and to release the driver objects. The chip run of this path has not - been done (`evidence/C5-ISOLATION/README.md`: NO RESULT, then NOT RUN). The reference does not unmap buffers the caller - did not free (`src/omega_gpu_platform_linux.c:198-199`), so whether each recovery leaks CPU mappings is not known. - Every handle and command list of the old device is stale afterwards. A latch held only by the command lists also - counts: `omega_gpu_session_is_blocked()` is then 0 while `omega_gpu_cmdlist_is_latched()` is 1, so check both. - -**Threads.** One process-wide lock (the platform LOCK service, lock id `OMEGA_GPU_SESSION_LOCK_ID`, which is 0). A call -sequence that touches the device (open, alloc, launch, readback) is done between `omega_gpu_session_lock()` and -`omega_gpu_session_unlock()`. Threads therefore take turns on the one channel. The Linux reference lock is a plain -(non-recursive) pthread mutex (`locks[id]`, `src/omega_gpu_platform_linux.c:45` and `:141`), so taking it twice from one thread -deadlocks. These take the lock themselves and must be called without it: `omega_gpu_session_close`, `omega_gpu_session_recover`, -`omega_gpu_cmdlist_create`, `omega_gpu_cmdlist_free`, and the section 9.5 calls that touch the device or a library cache -(the compute and upload calls, `omega_gpu_tensor_free`, `omega_gpu_matmul_cache_clear`, `omega_gpu_matmul_set_cta_budget`, -`omega_gpu_matmul_prepare`, `omega_gpu_attention_pool_alloc`, `omega_gpu_attention_pool_free`, the serving reserve, seal and -release calls, and `omega_gpu_device_close` through `omega_gpu_session_close`). The section 9.5 accessors do not take the lock: -`omega_gpu_matmul_cta_budget`, `omega_gpu_tensor_shape`, `omega_gpu_matmul_rc_name`, `omega_gpu_matmul_last_error`, -`omega_gpu_elementwise_rc_name`, `omega_gpu_attention_rc_name`, `omega_gpu_attention_last_error` and -`omega_gpu_matmul_is_blocked` (an atomic read); neither does the INTERNAL `omega_gpu_elementwise_last_error` (section 10). -`omega_gpu_matmul_cta_budget` reads without the lock the value that -`omega_gpu_matmul_set_cta_budget` writes under it (`src/omega_gpu_matmul_api.c:146-153`), so calling the two from different -threads at once is a data race. -`omega_gpu_session_cancel` may be called from any thread without the lock (header). `omega_gpu_session_is_blocked` reads the latch with an atomic load (`src/omega_gpu_session.c:173`), so it is safe without the lock too. -`omega_gpu_session_last_error` returns a pointer into one process-wide text buffer: read it under the lock, before the next call. - -### 3.1 A minimal sequence (sketch) - -```c example -omega_gpu_session_lock(); -OmegaGpuSession *s = omega_gpu_session_open(); /* NULL: see omega_gpu_session_last_error() */ -OmegaGpuMem in, code; -omega_gpu_session_alloc(bytes, &in); /* GPU-uncached data buffer */ -omega_gpu_session_alloc_code(code_size, &code); /* write the machine code to code.cpu */ -omega_gpu_session_sync_to_gpu(&in); -OmegaGpuLaunch L = { .code_va = code.va, .timeout_ms = 1000, /* gpr_count, threads_*, grid_*, args, n_args ... */ }; -uint64_t elapsed_ns = 0; uint32_t marker = 0; /* launch adds to elapsed_ns: start it at 0 */ -int rc = omega_gpu_session_launch(&L, &elapsed_ns, &marker); -omega_gpu_session_sync_to_cpu(&in); -omega_gpu_session_free(&in); -omega_gpu_session_unlock(); -``` - -This is a shape sketch, not a worked example (the worked example is slice R2). - -## 4. Session: device, lock and state - -#### `omega_gpu_session_lock` -STABLE: used by every library API and chip-proven; the lock model is the documented one. -```c -void omega_gpu_session_lock(void); -``` -Takes the process-wide session lock (platform LOCK service, id `OMEGA_GPU_SESSION_LOCK_ID`). Does not touch the device. -In the hosted build the first call installs the Linux reference platform (`pthread_once`, `src/omega_gpu_session.c:109-115`), -so it takes a real mutex. Freestanding build only: with no platform installed it does nothing, and the open that follows refuses. - -#### `omega_gpu_session_unlock` -STABLE: pairs with the lock. -```c -void omega_gpu_session_unlock(void); -``` - -#### `omega_gpu_session_open` -STABLE: used by every library API and chip-proven. Treat the returned pointer as "the device is open"; the fields of -`OmegaGpuSession` are EXPERIMENTAL (the session's own launch buffers) and a caller needs none of them. -```c -OmegaGpuSession *omega_gpu_session_open(void); -``` -Caller holds the lock. Opens the device on first use. Returns NULL when the process is latched, no platform is installed or the -open failed; the stage is in `omega_gpu_session_last_error()`. - -#### `omega_gpu_session_is_open` -STABLE: simple state query. -```c -bool omega_gpu_session_is_open(void); -``` - -#### `omega_gpu_session_is_blocked` -STABLE: the latch query that every caller needs. -```c -int omega_gpu_session_is_blocked(void); -``` -Returns 1 once an uncertain completion has latched this process, else 0. Any thread. - -#### `omega_gpu_session_close` -STABLE: the only way to close the device; its refusal after a latch is part of the error model. -```c -void omega_gpu_session_close(void); -``` -Closes the device and frees every session buffer. **Takes the lock itself.** Refused (a no-op) after an uncertain completion. -The next open reopens; every handle of the closed device is stale from then on. - -#### `omega_gpu_session_open_count` -STABLE: diagnostic with a fixed meaning. -```c -uint32_t omega_gpu_session_open_count(void); -``` -Device opens so far in this process (a persistent session shows 1). - -#### `omega_gpu_session_set_spin_us` -STABLE: used by sovereign-core's binding; fixed meaning and limit. -```c -int omega_gpu_session_set_spin_us(uint32_t us); -``` -Process-wide marker-poll spin window, used by every launch whose own `spin_us` is 0. 0 (the default) keeps the platform's -sleep-poll. Returns 0 on success, -1 above `OMEGA_GPU_SESSION_MAX_SPIN_US` (setting unchanged). - -#### `omega_gpu_session_spin_us` -STABLE: reads the setting above. -```c -uint32_t omega_gpu_session_spin_us(void); -``` - -## 5. Session: memory - -All allocation calls need the caller to hold the lock with the device open. - -#### `OmegaGpuMem` -STABLE: the buffer type every API passes around. -A device buffer: a typed handle, its kind, the CPU view, the GPU virtual address and the size. A `cpu` of NULL means there is no CPU view. - -| Field | Meaning (from `src/omega_gpu_session.h`) | -| --- | --- | -| `handle` | `OmegaGpuBufferHandle`: index and generation | -| `kind` | `OMEGA_GPU_HANDLE_BUF_DATA`, `_BUF_CODE` or `_BUF_QUEUE` | -| `cpu` | CPU view | -| `va` | GPU virtual address | -| `size` | bytes of both views | - -#### `OmegaGpuBufferHandle` -STABLE: a field of `OmegaGpuMem`, so its layout is part of it. -`{ uint32_t index; uint32_t generation; }`. Generation 0 is never issued, so a zeroed handle means "none". -A handle is valid only while its slot generation matches; a closed handle is refused. - -#### `OmegaGpuDeviceHandle` -STABLE: same shape and rule as the buffer handle; named in the platform contract. -`{ uint32_t index; uint32_t generation; }`. - -#### `OmegaGpuQueueHandle` -STABLE: same shape and rule as the buffer handle; named in the platform contract. -`{ uint32_t index; uint32_t generation; }`. - -#### `omega_gpu_session_alloc` -STABLE: the ordinary buffer call, used by every library. -```c -int omega_gpu_session_alloc(size_t bytes, OmegaGpuMem *out); -``` -A GPU-uncached DATA buffer, CPU and GPU read/write, rounded up to a page. Returns 0 on success; non-zero with the stage named on -failure (the driver can refuse, for example with no memory; the refusal is counted in `OmegaGpuAllocStats.alloc_failures`). - -#### `omega_gpu_session_alloc_code` -STABLE: the only way to place kernel code; chip-proven. -```c -int omega_gpu_session_alloc_code(size_t code_size, OmegaGpuMem *out); -``` -A CODE buffer (CPU writes, GPU executes, GPU never writes) for `code_size` bytes plus the 2 KB instruction-prefetch tail -(`src/omega_gpu_code_alloc.h`), the tail zero-filled. The caller writes the code to `out->cpu`. A size of 0 still gets one page (`omega_gpu_code_alloc_bytes` rounds up to at least one page). - -#### `omega_gpu_session_free` -STABLE: the release call; its latch behaviour is part of the error model. -```c -void omega_gpu_session_free(OmegaGpuMem *m); -``` -Releases `m` to the platform and zeroes `*m`. **Latched: `m` is parked instead (never released).** A stale handle (from a -closed device) or a closed session is refused: nothing is released, the refusal is counted -(`OmegaGpuAllocStats.stale_refusals`) and `*m` is zeroed. - -#### `omega_gpu_session_sync_to_gpu` -STABLE: the visibility rule for CPU writes. -```c -int omega_gpu_session_sync_to_gpu(const OmegaGpuMem *m); -``` -Makes CPU writes to the whole buffer visible to the device (platform SYNC). Returns 0, also for a buffer with no CPU view; --1 with the stage named when refused or when there is no device. - -#### `omega_gpu_session_sync_to_cpu` -STABLE: the visibility rule for GPU writes. -```c -int omega_gpu_session_sync_to_cpu(const OmegaGpuMem *m); -``` -Makes device writes to the whole buffer visible to the CPU. Same return values as `sync_to_gpu`. - -#### `OmegaGpuScratch` -STABLE: the staging-buffer type the library APIs use. -A caller-owned staging buffer that grows to its high-water mark: `mem` (an `OmegaGpuMem`), `cap` (usable bytes), `high_water` -(largest request so far) and `reserved` (a serving reservation is active, see `omega_gpu_session_scratch_reserve`). -Zero-initialise it before first use. This is required: `omega_gpu_session_scratch` reads `reserved`, `cap`, `mem.cpu` and -`high_water` before it writes them (`src/omega_gpu_session.c:315-321`). - -#### `omega_gpu_session_scratch` -STABLE: used by every library API. -```c -int omega_gpu_session_scratch(OmegaGpuScratch *s, size_t bytes); -``` -Makes `s->mem` at least `bytes` long (reallocated when it grows; **contents are not kept**). Returns 0 or -1; with a -reservation active, a request past the reserved size returns `OMEGA_GPU_SESSION_SCRATCH_RESERVED` (-2) and allocates nothing. - -#### `omega_gpu_session_scratch_free` -STABLE: the matching release. -```c -void omega_gpu_session_scratch_free(OmegaGpuScratch *s); -``` - -#### `OmegaGpuAllocStats` -STABLE: used by sovereign-core's binding to show that serving asks the driver for nothing. -Counters of driver allocations made through `omega_gpu_session_alloc` since the process started: `allocs`, `alloc_bytes` -(page-rounded), `alloc_failures`, `frees`, `stale_refusals`. Covers the session layer only. - -#### `omega_gpu_session_alloc_stats` -STABLE: reads the counters above. -```c -void omega_gpu_session_alloc_stats(OmegaGpuAllocStats *out); -``` - -## 6. Session: launch - -#### `OmegaGpuLaunch` -STABLE: the launch descriptor; chip-proven by every library. -One launch: a kernel already resident at `code_va`, argument words for constant bank 0 at 0x380 (buffer addresses, then -parameters), and the grid. - -Argument layout and the checks `omega_gpu_session_launch` makes (`src/omega_gpu_session.c:525-537`): -- a 64-bit GPU address takes two words, the low word first, then the high word; -- `L` is not NULL, `n_args` is 1 to `OMEGA_GPU_SESSION_MAX_ARGS`, `args` is not NULL, `threads_x`, `grid_x` and `grid_y` - are not 0 (a `threads_y` of 0 means 1), and `spin_us` is at most `OMEGA_GPU_SESSION_MAX_SPIN_US` (1000000); otherwise the - launch is refused with "launch arguments" and nothing runs; -- `gpr_count` is rounded up to a multiple of 8, and to at least 64; -- `elapsed_ns` is added to, not set: start it at 0. -What the kernel itself may read in constant bank 0 besides these words, and where GB10 machine code comes from, is slice -R2 (`examples/hello_gpu`, README "Run your first kernel"). - -| Field | Meaning (from `src/omega_gpu_session.h`) | -| --- | --- | -| `code_va` | GPU address of the kernel code | -| `gpr_count` | registers the QMD (the launch descriptor the hardware reads) declares; multiple of 8, at least 64 in practice | -| `threads_x`, `threads_y` | block size | -| `grid_x`, `grid_y` | grid size | -| `num_elements` | QMD config num_elements (kept per API for identical words) | -| `args`, `n_args` | `n_args` words written at constant bank + 0x380; `n_args` at most `OMEGA_GPU_SESSION_MAX_ARGS` (32) | -| `timeout_ms` | completion poll limit, applied to each of the launch's two markers in turn (so a launch can wait up to twice this); past it the completion is uncertain and **the process latches**. Do not pass 0: the marker is then polled once (after the spin window, if any) and the launch latches unless the grid had already finished | -| `shared_bytes` | shared memory per block; 0 = the default (1024) | -| `spin_us` | spin-poll window before the platform's sleep-poll; 0 = the process-wide setting; at most `OMEGA_GPU_SESSION_MAX_SPIN_US` | - -#### `omega_gpu_session_launch` -STABLE: the single-kernel launch; chip-proven. -```c -int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint32_t *marker_out); -``` -Caller holds the lock, device open, not latched. Submits one launch and polls for both completion markers, so it returns when -the chip is done. 0 on success; -1 with the stage named on failure; `OMEGA_GPU_SESSION_CANCELLED` (-3) when a cancel request -was seen. A marker timeout latches the process. `elapsed_ns` (submit to second marker) is added to when the pointer is given; -`marker_out` receives the first marker word observed. - -## 7. Session: errors, the latch, parked buffers - -#### `omega_gpu_session_last_error` -STABLE: the error-model entry point. -```c -const char *omega_gpu_session_last_error(void); -``` -The stage of the most recent failure, `""` if none. Shared by every API. Points into one process-wide buffer: read it under -the lock, before the next call. - -#### `OmegaGpuParkStats` -STABLE: the parked-buffer report. -`buffers` (parked, listed plus untracked), `untracked` (parked past the listed `OMEGA_GPU_SESSION_PARK_MAX` = 512) and -`bytes`. - -#### `omega_gpu_session_parked` -STABLE: how a caller sees what the latch kept. -```c -void omega_gpu_session_parked(OmegaGpuParkStats *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 and every later free parks too. - -#### `omega_gpu_session_is_parked` -STABLE: per-handle form of the above. -```c -int omega_gpu_session_is_parked(OmegaGpuBufferHandle h); -``` -1 if this handle is parked and listed. - -## 8. Not in v0 (so nobody assumes it) - -Each line is a gap named in `docs/runtime/ROADMAP.md` section 1 (on branch `runtime/roadmap`, not yet merged); the gaps themselves are not in the manifest. -- A device query (name, SM count, memory): there is no API call for it. -- More than one device in a process; sharing the GPU between processes (a second channel failed under load: omega-mv#523). - Extra queues on the one device (`omega_gpu_session_extra_queue`, `omega_gpu_cmdlist_submit_pair`) are EXPERIMENTAL (9.1, 9.3). -- A STABLE recovery contract: `omega_gpu_session_recover` is EXPERIMENTAL in v0 (section 9.1). -- Async copy, streams, events, host callbacks (omega-mv#580 is building ordering on command lists). -- Cached read-write buffers; unified memory. -- Launches with more than the 32 argument words, or an asynchronous single launch. -- A second real backend (WSL2 `/dev/dxg` is on branch `rig/gb20x`; native AIENOS is planned), so the platform contract has only been exercised by one. -- A runtime function that reports the version of the linked library (the version is a compile-time macro only). - -## 9. EXPERIMENTAL entries - -Listed in the manifest, may change in any minor version. Signatures are in the manifest and the headers; the names are -checked there. The reason is why each is not STABLE yet. - -### 9.1 Session extras (`src/omega_gpu_session.h`, `src/omega_gpu_mem_cached.h`) - -| Entry | Reason it is EXPERIMENTAL | -| --- | --- | -| `omega_gpu_session_alloc_cached` | GPU-cached memory is correct only for write-once, never-polled, GPU-read-only weights; the API cannot enforce that (the caller must). | -| `omega_gpu_session_scratch_reserve`, `omega_gpu_session_scratch_unreserve` | Serving-daemon feature (no driver call after warm-up); one user. | -| `omega_gpu_session_cancel` | A cancel after submit cannot stop the chip: it latches the process. Semantics may tighten as recovery matures. | -| `omega_gpu_session_recover`, `omega_gpu_session_recoveries` | C5 recovery after a latch (`evidence/C5-ISOLATION/`): new on main after this API was first drafted; its device-close path is one backend's (Linux RM client close) behaviour and has no chip run yet (section 3). `recover` returns 0 when the latch is lifted, -1 with the reason named when nothing was latched (neither the process nor the command lists), no device is open, or the close was refused (then the process stays latched). | -| `omega_gpu_session_extra_queue` | Queues 1..3 past the session queue, each with its own 64 KB ring; granted only when the device was opened with `AIEN_OMEGA_GPU_CHANNELS` > i. Work on different queues is not ordered. One backend, one user (the command-list pair). | -| `omega_gpu_session_set_platform`, `omega_gpu_session_platform`, `omega_gpu_session_submit_prefix_words`, `omega_gpu_session_completion_mode`, `omega_gpu_session_now_ns` | Tied to the platform contract, which has one real backend. | -| `omega_gpu_host_alloc`, `omega_gpu_host_calloc`, `omega_gpu_host_free` | CPU-only memory from the platform HOST_MEM service; the freestanding build needs them, hosted code can use malloc. | -| `OmegaGpuSession` | The session's own launch buffers; a caller needs none of its fields. | - -### 9.2 Platform contract (`src/omega_gpu_platform.h`, ABI 1.2) - -Types: `OmegaGpuPlatform` (the service table), `OmegaGpuPlatformCaps`, `OmegaGpuBufferDesc`, `OmegaCpuView`, `OmegaGpuVa`, -`OmegaGpuBusAddr`, `OmegaGpuHandleTable`. Functions: `omega_gpu_platform_refusal_name`, `omega_gpu_platform_negotiate`, -`omega_gpu_platform_check`, `omega_gpu_platform_check_for`, `omega_gpu_platform_check_buffer`, `omega_gpu_handles_init`, -`omega_gpu_handles_open`, `omega_gpu_handles_check`, `omega_gpu_handles_close`. Enums and constants: the handle kinds, -rights (`OMEGA_GPU_RIGHT_*`), cache policy, services (`OMEGA_GPU_SVC_*`) and refusal names (`OMEGA_GPU_PLAT_*`). - -Reason: the contract is written for three backends but only the Linux reference has run; the second backend (`rig/gb20x`) and -the native one will likely force changes. What it already promises (from the header): resources are typed handles with a -generation; every byte range carries a length and rights; anything the CPU polls is `OMEGA_GPU_RIGHT_HOST_POLLED` and must be -GPU-uncached; polling a word is never claimed as interrupt support; a missing service is refused, never emulated. - -### 9.3 Command lists (`src/omega_gpu_cmdlist.h`) - -Types: `OmegaGpuCmdListOpts`, `OmegaGpuCmdListStats`, the opaque `OmegaGpuCmdList`. Functions: `omega_gpu_cmdlist_create` -(takes the lock itself), `omega_gpu_cmdlist_free`, `omega_gpu_cmdlist_reset`, `omega_gpu_cmdlist_count`, -`omega_gpu_cmdlist_add`, `omega_gpu_cmdlist_mark_independent`, `omega_gpu_cmdlist_submit`, `omega_gpu_cmdlist_is_latched`, -`omega_gpu_cmdlist_stamps`, `omega_gpu_cmdlist_barrier_name`, `omega_gpu_cmdlist_submit_pair` (list a on the session queue -and list b on extra queue 1, both submitted before either is waited; caller holds the lock), `omega_gpu_cmdlist_wait_for` -(C4 event: the next launch added waits on the chip for a launch of the other list of the pair). Up to -`OMEGA_GPU_CMDLIST_MAX_LAUNCHES` (4096) launches per list. A list made before `omega_gpu_session_recover` is refused after it. - -Reason: omega-mv#580 is building pipelined and dependency-ordered execution on this module, so the options, statistics -and barrier modes will grow. The measured extra cost of each launch in a list is about 30 us with a wait-for-idle barrier -(`evidence/OWN30B-LAUNCH-COST-20261014T0120Z/r1/receipt.json`, verdict FAIL on 4 of 11 checks). A timeout latches the list; -the session latches as well only if the 1 ms check launch queued behind the list also times out -(`src/omega_gpu_cmdlist.c:233-240`, section 3). The `OMEGA_GPU_CMDLIST_BARRIER_NONE` mode and `skip_launch` option are test-only. -`OmegaGpuCmdListOpts.first_barrier_none` (C4 streams) drops the WAIT_FOR_IDLE and the shader-cache invalidate before launch 0 -of a list. The caller must make sure the code, constant banks and QMDs that launch 0 reads are not in a stale cache line -(fresh slots or unchanged contents), or launch 0 may read old bytes (`src/omega_gpu_cmdlist.h:85-87`). 0 keeps the barrier. - -### 9.4 Job engine (`src/omega_gpu_engine.h`) - -Types: `OmegaGpuJob`, `OmegaGpuResult`, `OmegaGpuTimeouts`, `OmegaGpuBackend`, `OmegaGpuBackendDiag`. Functions: -`omega_gpu_execute`, `omega_gpu_engine_set_backend`, `omega_gpu_engine_is_blocked`, `omega_gpu_engine_set_clock`, -`omega_gpu_engine_failure_name`, `omega_gpu_engine_state_name`, `omega_gpu_engine_wait_name`, `omega_gpu_engine_step_name`. One failure name per run -(`OMEGA_GPU_ENGINE_*`), states `INITIAL` to `SUCCESS`, the failed step recorded, and an uncertain completion blocks every -later `omega_gpu_execute` in the process with `UNCERTAIN_COMPLETION_BLOCKED`. - -Reason: accepts one job shape (`OMEGA_GPU_LAYOUT_VECTOR_1D`); #580 widens it; the chip receipt for the vector-add job is on an -unmerged branch (`hive/DEEP2-A3-gpu-engine-impl`). Note: the status paragraph at the top of `omega_gpu_engine.h` says only a -fake backend exists; `src/omega_blackwell_engine.c` is on main and `src/omega_blackwell_submit.c` installs it, so that -paragraph is out of date (whether it is chip-qualified on main is UNVERIFIED here). - -### 9.5 Libraries (matmul, elementwise, attention, serving) - -The entries carried over from aien-sovereign-core's manifest: `src/omega_gpu_matmul_api.h`, `omega_gpu_elementwise_api.h`, -`omega_gpu_attention_api.h`, `omega_gpu_serving.h` (the functions and structs after the `libraries` comment in the -manifest). Reason: shapes and formats follow one model (Qwen3-30B); there is no general any-shape GEMM yet -(`docs/runtime/ROADMAP.md` 1.3, branch `runtime/roadmap`). They are the surface sovereign-core's Rust binding uses today. They are not described entry by entry in v0; -their headers are the description. One value differs from sovereign-core's pinned copy: `OMEGA_GPU_MATMUL_MAX_CTAS` is 1024 in -the header (changed by omega #473, commit 98cecadc), 64 in their manifest. Omega's manifest is canonical; R12 brings theirs level. - - -### 9.6 Library entries (manifest spelling) - -Types are the manifest's Rust spelling (`*const`, `*mut`, `u32`, ...); the headers hold the C. Every entry here is EXPERIMENTAL. - -| Entry | Signature | -| --- | --- | -| `OmegaGpuMatmulInfo` | struct, 160 bytes (fields in the manifest) | -| `OmegaGpuServingBounds` | struct, 44 bytes (fields in the manifest) | -| `OmegaGpuEwInfo` | struct, 120 bytes (fields in the manifest) | -| `OmegaGpuAttnInfo` | struct, 176 bytes (fields in the manifest) | -| `OmegaGpuKvLayout` | struct, 64 bytes (fields in the manifest) | -| `omega_gpu_matmul_bf16` | `fn(u32, u32, u32, *const u16, *const u16, *mut f32, *mut OmegaGpuMatmulInfo) -> i32` | -| `omega_gpu_matmul_f32` | `fn(u32, u32, u32, *const f32, *const f32, *mut f32, *mut OmegaGpuMatmulInfo) -> i32` | -| `omega_gpu_matmul_rc_name` | `fn(i32) -> *const c_char` | -| `omega_gpu_matmul_cache_clear` | `fn() -> ()` | -| `omega_gpu_tensor_upload_bf16` | `fn(u32, u32, *const u16, *mut *mut OmegaGpuTensor) -> i32` | -| `omega_gpu_tensor_upload_f32` | `fn(u32, u32, *const f32, *mut *mut OmegaGpuTensor) -> i32` | -| `omega_gpu_tensor_free` | `fn(*mut OmegaGpuTensor) -> ()` | -| `omega_gpu_tensor_shape` | `fn(*const OmegaGpuTensor, *mut u32, *mut u32) -> ()` | -| `omega_gpu_matmul_resident_bf16` | `fn(u32, *const u16, *const OmegaGpuTensor, *mut f32, *mut OmegaGpuMatmulInfo) -> i32` | -| `omega_gpu_matmul_resident_f32` | `fn(u32, *const f32, *const OmegaGpuTensor, *mut f32, *mut OmegaGpuMatmulInfo) -> i32` | -| `omega_gpu_matmul_last_error` | `fn() -> *const c_char` | -| `omega_gpu_matmul_is_blocked` | `fn() -> i32` | -| `omega_gpu_device_close` | `fn() -> ()` | -| `omega_gpu_matmul_set_cta_budget` | `fn(u32) -> ()` | -| `omega_gpu_matmul_cta_budget` | `fn() -> u32` | -| `omega_gpu_reserve_serving` | `fn(*const OmegaGpuServingBounds) -> i32` | -| `omega_gpu_serving_release` | `fn() -> ()` | -| `omega_gpu_matmul_prepare` | `fn(u32, u32, u32) -> i32` | -| `omega_gpu_serving_seal` | `fn() -> ()` | -| `omega_gpu_rmsnorm_f32` | `fn(u32, u32, *const f32, *const f32, f32, *mut f32, *mut OmegaGpuEwInfo) -> i32` | -| `omega_gpu_rope_f32` | `fn(u32, u32, *const f32, *const f32, *const f32, *mut f32, *mut OmegaGpuEwInfo) -> i32` | -| `omega_gpu_swiglu_f32` | `fn(u32, *const f32, *const f32, *mut f32, *mut OmegaGpuEwInfo) -> i32` | -| `omega_gpu_elementwise_rc_name` | `fn(i32) -> *const c_char` | -| `omega_gpu_gqa_attention_f32` | `fn(*const f32, *const f32, *const f32, u32, u32, u32, u32, *mut f32, *mut OmegaGpuAttnInfo) -> i32` | -| `omega_gpu_gqa_attention_rows_f32` | `fn(*const f32, *const f32, *const f32, u32, u32, u32, u32, u32, *mut f32, *mut OmegaGpuAttnInfo) -> i32` | -| `omega_gpu_attention_pool_alloc` | `fn(usize, *mut *mut c_void) -> i32` | -| `omega_gpu_attention_pool_free` | `fn() -> ()` | -| `omega_gpu_paged_attention_bf16` | `fn(*const f32, *const c_void, *const OmegaGpuKvLayout, *const u32, u32, u32, u32, u32, u32, u32, *mut f32, *mut OmegaGpuAttnInfo) -> i32` | -| `omega_gpu_paged_attention_batch_bf16` | `fn(*const f32, *const c_void, *const OmegaGpuKvLayout, *const i32, *const i32, u32, u32, u32, u32, u32, u32, *mut f32, *mut OmegaGpuAttnInfo) -> i32` | -| `omega_gpu_attention_rc_name` | `fn(i32) -> *const c_char` | -| `omega_gpu_attention_last_error` | `fn() -> *const c_char` | - -## 10. INTERNAL (not part of the API) - -Not in the manifest; may change or vanish without notice. Every external function a manifest header declares is either -a manifest `fn` or named below as one of the leading names of a bullet (the names before any other text; names in the -prose after them do not count); `make test-runtime-api` fails on any other, and on a name that is both (section 11). - -Session (`src/omega_gpu_session.h`): -- `omega_gpu_session_set_error` (library code names its failure stage through it). -- `omega_gpu_session_on_close` (lets a library drop its resident kernels before the session closes; up to 8 hooks). -- `omega_gpu_session_latch_uncertain`, `omega_gpu_session_note_module_latch` (a module such as the command lists tells the session it latched). - -Job engine (`src/omega_gpu_engine.h`): -- `omega_gpu_engine_test_reset_block`, `omega_gpu_engine_test_force_block`, `omega_gpu_engine_test_set_clock`: TEST ONLY. A blocked process must stay blocked because the GPU may still be running. - -Matmul (`src/omega_gpu_matmul_api.h`): -- `omega_gpu_matmul_reserve`, `omega_gpu_matmul_unreserve`, `omega_gpu_matmul_seal` (the serving reservation; callers use `omega_gpu_reserve_serving`, `omega_gpu_serving_seal` and `omega_gpu_serving_release`). -- `omega_gpu_tensor_update_bf16`, `omega_gpu_tensor_update_f32` (rewrite a resident B in place). -- `omega_gpu_matmul_last_stages`, `omega_gpu_matmul_set_oracle` (per-stage timing of the last call; host oracle on the non-resident calls). -- `omega_gpu_matmul_test_set_mutant`, `omega_gpu_matmul_test_set_unroll`, `omega_gpu_matmul_test_a_row0_hits`: TEST ONLY. - -Elementwise (`src/omega_gpu_elementwise_api.h`): -- `omega_gpu_elementwise_cache_clear`, `omega_gpu_elementwise_last_error`. -- `omega_gpu_elementwise_codegen`, `omega_gpu_elementwise_codegen_ir` (build a kernel without launching it, for offline disassembly and the host IR simulator). -- `omega_gpu_ex2_f32`, `omega_gpu_shared_xchg_u32`, `omega_gpu_reconv_probe_u32` (chip probes). -- `omega_gpu_elementwise_test_set_mutant`, `omega_gpu_elementwise_test_set_mutant_level`: TEST ONLY. - -Attention (`src/omega_gpu_attention_api.h`): -- `omega_gpu_attention_cache_clear`, `omega_gpu_attention_heads_per_cta`, `omega_gpu_attention_mutant_name`. -- `omega_gpu_attention_reserve`, `omega_gpu_attention_reserve_rows`, `omega_gpu_attention_unreserve` (the serving reservation; callers use `omega_gpu_reserve_serving`). -- `omega_gpu_attention_codegen`, `omega_gpu_attention_codegen_hd` (build a kernel without launching it). -- `omega_gpu_attention_test_set_mutant`, `omega_gpu_attention_test_set_divergent`, `omega_gpu_attention_test_set_dedupe`, `omega_gpu_attention_test_set_split`, `omega_gpu_attention_test_set_simulator`, `omega_gpu_attention_test_shared_bytes`, `omega_gpu_attention_test_resident_fits`: TEST ONLY. - -Everything else under `src/omega_gpu_*` and `src/omega_blackwell_*` in headers the manifest does not list (kernel builder, encoder, per-model APIs, launch helpers). - -## 11. Checking this file - -`make test-runtime-api` runs `tools/runtime_api_check.sh` on the real headers and then `tools/runtime_api_negative.sh`, which breaks a -copy of the headers, the manifest or this file in sixteen ways and requires the check to fail each time: a removed function (twice: a STABLE one and the EXPERIMENTAL `omega_gpu_session_recover`), a missing version macro, a -changed function signature, a changed struct, a changed constant, a version line in this file that disagrees with the macro, a quoted signature in this file that no header has, a quoted -signature that only appears inside a longer one (`int32_t` inside `uint32_t`), a STABLE entry with no section here, a removed -struct field the manifest lists (`OmegaGpuCmdListOpts.first_barrier_none`), a new function in a manifest header with no -manifest line, the same for a function that returns a function pointer, an INTERNAL function dropped from section 10, a -manifest `fn` dropped from the manifest while section 10's prose still mentions it (`omega_gpu_serving_seal`), and a -manifest `fn` also listed as INTERNAL. It needs no GPU and no physics checkout. It checks: every manifest function against its header -with exact types; sizes, offsets and constants against a compiled probe; the version macros against the manifest and this file; -that every STABLE entry has a `####` section here and every EXPERIMENTAL one is named here; that every C signature quoted -in this file appears verbatim in a header; and, with gcc's `-aux-info`, that every external function a manifest header -declares is either a manifest `fn` or a leading name of a section-10 bullet, never both, and every such name is still -declared (another compiler fails -the check with "needs a compiler with -aux-info"). It does not check that the prose is true. Not seen: a new struct or -constant (nothing to compare it with), a field added inside padding that the manifest does not list, a field that changes -type but keeps its size, and a constant value quoted in prose. - -Where it runs: the gate `OMEGA-RUNTIME-API` (`tests/gates/omega-runtime-api.gate`, requires `portable`) runs -`make test-runtime-api` through `tests/gates/run.sh runtime-api`. The Spark judge runs it on a pull request that touches -its inputs. The hosted AIEN Checks job runs the portable gates it finds on main (`.github/workflows/aien-verification.yml`), -so it runs there from the first pull request after the gate file is on main. It needs gcc (for `-aux-info`), make, perl, -sed and a POSIX awk. diff --git a/docs/runtime/PORTABILITY.md b/docs/runtime/PORTABILITY.md index 7b923a91e..d1c505f39 100644 --- a/docs/runtime/PORTABILITY.md +++ b/docs/runtime/PORTABILITY.md @@ -8,6 +8,11 @@ UNVERIFIED. Nothing here was run on a GPU; this slice is read-only analysis plus Companion documents, not repeated here: `docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md` (which driver call each part makes today and which cut removes it) and `docs/numeric/OMEGA_GPU_ENGINE.md` (the engine contract). +Since omega-mv#924 the GPU sources this document describes are CUDApp's, consumed from the exact revision in +`cudapp.lock`; their table is `docs/runtime/portability_table.tsv` of that revision, and `make test-runtime-portability` +checks it in the staged source (`$(CUDAPP_SOURCE)`). This repository's table keeps only the rows of the GPU-named files +Omega still carries (`src/omega_blackwell_gates.{c,h}`). The totals below are the historical review of omega-mv main. + ## 1. Two separate questions Porting Omega means answering two questions that are easy to mix up: diff --git a/docs/runtime/omega_runtime_api.manifest b/docs/runtime/omega_runtime_api.manifest deleted file mode 100644 index d02c0ebe0..000000000 --- a/docs/runtime/omega_runtime_api.manifest +++ /dev/null @@ -1,553 +0,0 @@ -# Omega Runtime API manifest: the canonical list of the C entries that docs/runtime/API.md describes. -# Canonical from R1 (2026-10-19): Omega's copy leads; aien-sovereign-core's crates/aien-omega-gpu/abi/omega_gpu.manifest -# must match it (R12 checks that). The part from "libraries" down to the end of the `fn` lines of those headers was -# copied from that file at aien-sovereign-core origin/main (see the "carried over" comment below) and kept unchanged. -# Line format = aien-abi-conformance src/manifest.rs (header, struct, field, const, fn); `#` starts a comment. -# Additions to that format, all inside comments or in the free `kind` column, so its parser still reads the file: -# - every `struct` and `fn` line ends with a tier comment: `# STABLE` or `# EXPERIMENTAL` (INTERNAL entries are not listed); -# - field kinds beyond its list: `ptr` (any pointer, 8 bytes), `enum` (4 bytes), `struct:Name` (a struct by value); -# `usize`/size_t fields are written `u64` (LP64), as it does. -# Checked by tools/runtime_api_check.sh (make test-runtime-api): every `fn` against its header with the exact types, -# every size, offset and constant against a compiled probe, the version macros against src/omega_runtime_api.h. -# After a deliberate header change: edit the line here, run `tools/runtime_api_check.sh --bless` to refresh numbers, review the diff. -abi omega_runtime 0.1 -header src/omega_runtime_api.h -header src/omega_gpu_platform.h -header src/omega_gpu_session.h -header src/omega_gpu_mem_cached.h -header src/omega_gpu_cmdlist.h -header src/omega_gpu_engine.h -header src/omega_gpu_matmul_api.h -header src/omega_gpu_serving.h -header src/omega_gpu_elementwise_api.h -header src/omega_gpu_attention_api.h -# ---- version ---- -const OMEGA_RUNTIME_API_VERSION_MAJOR 0 -const OMEGA_RUNTIME_API_VERSION_MINOR 1 -# ---- platform contract (src/omega_gpu_platform.h, ABI 1.2) ---- -struct OmegaGpuDeviceHandle 8 4 # STABLE -field OmegaGpuDeviceHandle index 0 4 u32 1 -field OmegaGpuDeviceHandle generation 4 4 u32 1 -struct OmegaGpuBufferHandle 8 4 # STABLE -field OmegaGpuBufferHandle index 0 4 u32 1 -field OmegaGpuBufferHandle generation 4 4 u32 1 -struct OmegaGpuQueueHandle 8 4 # STABLE -field OmegaGpuQueueHandle index 0 4 u32 1 -field OmegaGpuQueueHandle generation 4 4 u32 1 -struct OmegaCpuView 16 8 # EXPERIMENTAL -field OmegaCpuView ptr 0 8 ptr 1 -field OmegaCpuView len 8 8 u64 1 -struct OmegaGpuVa 8 8 # EXPERIMENTAL -field OmegaGpuVa va 0 8 u64 1 -struct OmegaGpuBusAddr 8 8 # EXPERIMENTAL -field OmegaGpuBusAddr iova 0 8 u64 1 -struct OmegaGpuBufferDesc 24 8 # EXPERIMENTAL -field OmegaGpuBufferDesc kind 0 4 u32 1 -field OmegaGpuBufferDesc rights 4 4 u32 1 -field OmegaGpuBufferDesc gpu_cache 8 4 u32 1 -field OmegaGpuBufferDesc align 12 4 u32 1 -field OmegaGpuBufferDesc bytes 16 8 u64 1 -struct OmegaGpuPlatformCaps 56 8 # EXPERIMENTAL -field OmegaGpuPlatformCaps abi_major 0 4 u32 1 -field OmegaGpuPlatformCaps abi_minor 4 4 u32 1 -field OmegaGpuPlatformCaps services 8 4 u32 1 -field OmegaGpuPlatformCaps max_devices 12 4 u32 1 -field OmegaGpuPlatformCaps max_buffers 16 4 u32 1 -field OmegaGpuPlatformCaps max_queues 20 4 u32 1 -field OmegaGpuPlatformCaps max_inflight 24 4 u32 1 -field OmegaGpuPlatformCaps max_buffer_bytes 32 8 u64 1 -field OmegaGpuPlatformCaps max_total_bytes 40 8 u64 1 -field OmegaGpuPlatformCaps submit_prefix_words 48 4 u32 1 -struct OmegaGpuPlatform 184 8 # EXPERIMENTAL -field OmegaGpuPlatform ctx 0 8 ptr 1 -field OmegaGpuPlatform time_now_ms 8 8 ptr 1 -field OmegaGpuPlatform wait_ms 16 8 ptr 1 -field OmegaGpuPlatform lock 24 8 ptr 1 -field OmegaGpuPlatform unlock 32 8 ptr 1 -field OmegaGpuPlatform mmio_read32 40 8 ptr 1 -field OmegaGpuPlatform mmio_write32 48 8 ptr 1 -field OmegaGpuPlatform dma_alloc 56 8 ptr 1 -field OmegaGpuPlatform dma_free 64 8 ptr 1 -field OmegaGpuPlatform sync_cpu_to_gpu 72 8 ptr 1 -field OmegaGpuPlatform sync_gpu_to_cpu 80 8 ptr 1 -field OmegaGpuPlatform poll_word 88 8 ptr 1 -field OmegaGpuPlatform irq_wait 96 8 ptr 1 -field OmegaGpuPlatform device_open 104 8 ptr 1 -field OmegaGpuPlatform device_close 112 8 ptr 1 -field OmegaGpuPlatform diag_text 120 8 ptr 1 -field OmegaGpuPlatform queue_open 128 8 ptr 1 -field OmegaGpuPlatform queue_close 136 8 ptr 1 -field OmegaGpuPlatform queue_submit 144 8 ptr 1 -field OmegaGpuPlatform queue_retire 152 8 ptr 1 -field OmegaGpuPlatform time_now_ns 160 8 ptr 1 -field OmegaGpuPlatform host_alloc 168 8 ptr 1 -field OmegaGpuPlatform host_free 176 8 ptr 1 -struct OmegaGpuHandleTable 69648 8 # EXPERIMENTAL -field OmegaGpuHandleTable generation 0 16384 u32 4096 -field OmegaGpuHandleTable kind 16384 16384 u32 4096 -field OmegaGpuHandleTable bytes 32768 32768 u64 4096 -field OmegaGpuHandleTable live 65536 4096 u8 4096 -field OmegaGpuHandleTable nlive 69632 4 u32 1 -field OmegaGpuHandleTable total_bytes 69640 8 u64 1 -fn omega_gpu_platform_refusal_name fn(i32) -> *const c_char # EXPERIMENTAL -fn omega_gpu_platform_negotiate fn(*const OmegaGpuPlatformCaps, *const OmegaGpuPlatformCaps) -> i32 # EXPERIMENTAL -fn omega_gpu_platform_check fn(*const OmegaGpuPlatform, *const OmegaGpuPlatformCaps) -> i32 # EXPERIMENTAL -fn omega_gpu_platform_check_for fn(*const OmegaGpuPlatform, *const OmegaGpuPlatformCaps, u32) -> i32 # EXPERIMENTAL -fn omega_gpu_platform_check_buffer fn(*const OmegaGpuBufferDesc, *const OmegaGpuPlatformCaps) -> i32 # EXPERIMENTAL -fn omega_gpu_handles_init fn(*mut OmegaGpuHandleTable) -> () # EXPERIMENTAL -fn omega_gpu_handles_open fn(*mut OmegaGpuHandleTable, u32, u64, u32, u64, *mut u32, *mut u32) -> i32 # EXPERIMENTAL -fn omega_gpu_handles_check fn(*const OmegaGpuHandleTable, u32, u32, u32) -> i32 # EXPERIMENTAL -fn omega_gpu_handles_close fn(*mut OmegaGpuHandleTable, u32, u32, u32) -> i32 # EXPERIMENTAL -# ---- session: device, memory, launch, errors (src/omega_gpu_session.h, src/omega_gpu_mem_cached.h) ---- -struct OmegaGpuMem 40 8 # STABLE -field OmegaGpuMem handle 0 8 struct:OmegaGpuBufferHandle 1 -field OmegaGpuMem kind 8 4 u32 1 -field OmegaGpuMem cpu 16 8 ptr 1 -field OmegaGpuMem va 24 8 u64 1 -field OmegaGpuMem size 32 8 u64 1 -struct OmegaGpuSession 192 8 # EXPERIMENTAL -field OmegaGpuSession dev 0 8 struct:OmegaGpuDeviceHandle 1 -field OmegaGpuSession queue 8 8 struct:OmegaGpuQueueHandle 1 -field OmegaGpuSession pb 16 40 struct:OmegaGpuMem 1 -field OmegaGpuSession cbank 56 40 struct:OmegaGpuMem 1 -field OmegaGpuSession marker 96 40 struct:OmegaGpuMem 1 -field OmegaGpuSession qmd 136 40 struct:OmegaGpuMem 1 -field OmegaGpuSession opens 176 4 u32 1 -field OmegaGpuSession last_open_ns 184 8 u64 1 -struct OmegaGpuScratch 64 8 # STABLE -field OmegaGpuScratch mem 0 40 struct:OmegaGpuMem 1 -field OmegaGpuScratch cap 40 8 u64 1 -field OmegaGpuScratch high_water 48 8 u64 1 -field OmegaGpuScratch reserved 56 1 bool 1 -struct OmegaGpuLaunch 72 8 # STABLE -field OmegaGpuLaunch code_va 0 8 u64 1 -field OmegaGpuLaunch gpr_count 8 4 u32 1 -field OmegaGpuLaunch threads_x 12 4 u32 1 -field OmegaGpuLaunch threads_y 16 4 u32 1 -field OmegaGpuLaunch grid_x 20 4 u32 1 -field OmegaGpuLaunch grid_y 24 4 u32 1 -field OmegaGpuLaunch num_elements 32 8 u64 1 -field OmegaGpuLaunch args 40 8 ptr 1 -field OmegaGpuLaunch n_args 48 4 u32 1 -field OmegaGpuLaunch timeout_ms 56 8 u64 1 -field OmegaGpuLaunch shared_bytes 64 4 u32 1 -field OmegaGpuLaunch spin_us 68 4 u32 1 -struct OmegaGpuParkStats 16 8 # STABLE -field OmegaGpuParkStats buffers 0 4 u32 1 -field OmegaGpuParkStats untracked 4 4 u32 1 -field OmegaGpuParkStats bytes 8 8 u64 1 -fn omega_gpu_session_lock fn() -> () # STABLE -fn omega_gpu_session_unlock fn() -> () # STABLE -fn omega_gpu_session_open fn() -> *mut OmegaGpuSession # STABLE -fn omega_gpu_session_is_open fn() -> bool # STABLE -fn omega_gpu_session_is_blocked fn() -> i32 # STABLE -fn omega_gpu_session_close fn() -> () # STABLE -fn omega_gpu_session_open_count fn() -> u32 # STABLE -fn omega_gpu_session_alloc fn(usize, *mut OmegaGpuMem) -> i32 # STABLE -fn omega_gpu_session_alloc_code fn(usize, *mut OmegaGpuMem) -> i32 # STABLE -fn omega_gpu_session_free fn(*mut OmegaGpuMem) -> () # STABLE -fn omega_gpu_session_sync_to_gpu fn(*const OmegaGpuMem) -> i32 # STABLE -fn omega_gpu_session_sync_to_cpu fn(*const OmegaGpuMem) -> i32 # STABLE -fn omega_gpu_session_scratch fn(*mut OmegaGpuScratch, usize) -> i32 # STABLE -fn omega_gpu_session_scratch_free fn(*mut OmegaGpuScratch) -> () # STABLE -fn omega_gpu_session_launch fn(*const OmegaGpuLaunch, *mut u64, *mut u32) -> i32 # STABLE -fn omega_gpu_session_last_error fn() -> *const c_char # STABLE -fn omega_gpu_session_parked fn(*mut OmegaGpuParkStats) -> () # STABLE -fn omega_gpu_session_is_parked fn(OmegaGpuBufferHandle) -> i32 # STABLE -fn omega_gpu_session_alloc_cached fn(usize, *mut OmegaGpuMem) -> i32 # EXPERIMENTAL -fn omega_gpu_session_scratch_reserve fn(*mut OmegaGpuScratch, usize) -> i32 # EXPERIMENTAL -fn omega_gpu_session_scratch_unreserve fn(*mut OmegaGpuScratch) -> () # EXPERIMENTAL -fn omega_gpu_session_cancel fn() -> () # EXPERIMENTAL -fn omega_gpu_session_recover fn() -> i32 # EXPERIMENTAL -fn omega_gpu_session_recoveries fn() -> u32 # EXPERIMENTAL -fn omega_gpu_session_extra_queue fn(u32, *mut OmegaGpuQueueHandle) -> i32 # EXPERIMENTAL -fn omega_gpu_session_set_platform fn(*const OmegaGpuPlatform, *const OmegaGpuPlatformCaps) -> i32 # EXPERIMENTAL -fn omega_gpu_session_platform fn() -> *const OmegaGpuPlatform # EXPERIMENTAL -fn omega_gpu_session_submit_prefix_words fn() -> u32 # EXPERIMENTAL -fn omega_gpu_session_completion_mode fn() -> OmegaGpuCompletionMode # EXPERIMENTAL -fn omega_gpu_session_now_ns fn() -> u64 # EXPERIMENTAL -fn omega_gpu_host_alloc fn(usize) -> *mut c_void # EXPERIMENTAL -fn omega_gpu_host_calloc fn(usize, usize) -> *mut c_void # EXPERIMENTAL -fn omega_gpu_host_free fn(*mut c_void) -> () # EXPERIMENTAL -# ---- command lists (src/omega_gpu_cmdlist.h) ---- -struct OmegaGpuCmdListOpts 32 8 # EXPERIMENTAL -field OmegaGpuCmdListOpts mode 0 4 enum 1 -field OmegaGpuCmdListOpts barrier 4 4 enum 1 -field OmegaGpuCmdListOpts timeout_ms 8 8 u64 1 -field OmegaGpuCmdListOpts spin_us 16 4 u32 1 -field OmegaGpuCmdListOpts stamps 20 4 i32 1 -field OmegaGpuCmdListOpts skip_launch 24 4 i32 1 -field OmegaGpuCmdListOpts first_barrier_none 28 4 i32 1 -struct OmegaGpuCmdListStats 40 8 # EXPERIMENTAL -field OmegaGpuCmdListStats launches 0 4 u32 1 -field OmegaGpuCmdListStats submits 4 4 u32 1 -field OmegaGpuCmdListStats words 8 4 u32 1 -field OmegaGpuCmdListStats elapsed_ns 16 8 u64 1 -field OmegaGpuCmdListStats host_ns 24 8 u64 1 -field OmegaGpuCmdListStats sems_done 32 4 u32 1 -field OmegaGpuCmdListStats first_missing 36 4 i32 1 -fn omega_gpu_cmdlist_barrier_name fn(OmegaGpuCmdListBarrier) -> *const c_char # EXPERIMENTAL -fn omega_gpu_cmdlist_create fn(u32, *mut *mut OmegaGpuCmdList) -> i32 # EXPERIMENTAL -fn omega_gpu_cmdlist_free fn(*mut OmegaGpuCmdList) -> () # EXPERIMENTAL -fn omega_gpu_cmdlist_reset fn(*mut OmegaGpuCmdList) -> () # EXPERIMENTAL -fn omega_gpu_cmdlist_count fn(*const OmegaGpuCmdList) -> u32 # EXPERIMENTAL -fn omega_gpu_cmdlist_mark_independent fn(*mut OmegaGpuCmdList) -> i32 # EXPERIMENTAL -fn omega_gpu_cmdlist_add fn(*mut OmegaGpuCmdList, *const OmegaGpuLaunch) -> i32 # EXPERIMENTAL -fn omega_gpu_cmdlist_submit fn(*mut OmegaGpuCmdList, *const OmegaGpuCmdListOpts, *mut OmegaGpuCmdListStats) -> i32 # EXPERIMENTAL -fn omega_gpu_cmdlist_is_latched fn() -> i32 # EXPERIMENTAL -fn omega_gpu_cmdlist_stamps fn(*const OmegaGpuCmdList, *mut u64, u32) -> i32 # EXPERIMENTAL -fn omega_gpu_cmdlist_submit_pair fn(*mut OmegaGpuCmdList, *mut OmegaGpuCmdList, *const OmegaGpuCmdListOpts, *mut OmegaGpuCmdListStats, *mut OmegaGpuCmdListStats) -> i32 # EXPERIMENTAL -fn omega_gpu_cmdlist_wait_for fn(*mut OmegaGpuCmdList, *const OmegaGpuCmdList, u32) -> i32 # EXPERIMENTAL -# ---- job engine (src/omega_gpu_engine.h) ---- -struct OmegaGpuTimeouts 32 8 # EXPERIMENTAL -field OmegaGpuTimeouts marker_ms 0 8 u64 1 -field OmegaGpuTimeouts release_semaphore_ms 8 8 u64 1 -field OmegaGpuTimeouts marker2_ms 16 8 u64 1 -field OmegaGpuTimeouts visibility_ms 24 8 u64 1 -struct OmegaGpuJob 128 8 # EXPERIMENTAL -field OmegaGpuJob program 0 8 ptr 1 -field OmegaGpuJob program_len 8 8 u64 1 -field OmegaGpuJob layout 16 4 i32 1 -field OmegaGpuJob element_count 20 4 u32 1 -field OmegaGpuJob input_a 24 8 ptr 1 -field OmegaGpuJob input_a_len 32 8 u64 1 -field OmegaGpuJob input_b 40 8 ptr 1 -field OmegaGpuJob input_b_len 48 8 u64 1 -field OmegaGpuJob output 56 8 ptr 1 -field OmegaGpuJob output_len 64 8 u64 1 -field OmegaGpuJob poison 72 8 ptr 1 -field OmegaGpuJob poison_count 80 8 u64 1 -field OmegaGpuJob timeouts 88 32 struct:OmegaGpuTimeouts 1 -field OmegaGpuJob flags 120 4 u32 1 -struct OmegaGpuResult 208 8 # EXPERIMENTAL -field OmegaGpuResult failure 0 4 i32 1 -field OmegaGpuResult last_state 4 4 i32 1 -field OmegaGpuResult failed_step 8 4 i32 1 -field OmegaGpuResult wait 12 4 i32 1 -field OmegaGpuResult wait_timeout_ms 16 8 u64 1 -field OmegaGpuResult waited_ms 24 8 u64 1 -field OmegaGpuResult drv_rc 32 4 i32 1 -field OmegaGpuResult err_no 36 4 i32 1 -field OmegaGpuResult drv_text 40 128 c_char 128 -field OmegaGpuResult sync_valid 168 4 u32 1 -field OmegaGpuResult marker 172 4 u32 1 -field OmegaGpuResult marker2 176 4 u32 1 -field OmegaGpuResult semaphore 180 4 u32 1 -field OmegaGpuResult retained 184 4 i32 1 -field OmegaGpuResult cleanup_failed 188 4 i32 1 -field OmegaGpuResult n_outputs 192 8 u64 1 -field OmegaGpuResult output_unchanged_words 200 8 u64 1 -struct OmegaGpuBackendDiag 148 4 # EXPERIMENTAL -field OmegaGpuBackendDiag drv_rc 0 4 i32 1 -field OmegaGpuBackendDiag drv_text 4 128 c_char 128 -field OmegaGpuBackendDiag sync_valid 132 4 u32 1 -field OmegaGpuBackendDiag marker 136 4 u32 1 -field OmegaGpuBackendDiag marker2 140 4 u32 1 -field OmegaGpuBackendDiag semaphore 144 4 u32 1 -struct OmegaGpuBackend 128 8 # EXPERIMENTAL -field OmegaGpuBackend ctx 0 8 ptr 1 -field OmegaGpuBackend open_device 8 8 ptr 1 -field OmegaGpuBackend create_channel 16 8 ptr 1 -field OmegaGpuBackend alloc 24 8 ptr 1 -field OmegaGpuBackend copy_in 32 8 ptr 1 -field OmegaGpuBackend fill_poison 40 8 ptr 1 -field OmegaGpuBackend build 48 8 ptr 1 -field OmegaGpuBackend submit 56 8 ptr 1 -field OmegaGpuBackend wait_marker 64 8 ptr 1 -field OmegaGpuBackend wait_marker2 72 8 ptr 1 -field OmegaGpuBackend wait_release_semaphore 80 8 ptr 1 -field OmegaGpuBackend barrier 88 8 ptr 1 -field OmegaGpuBackend copy_out 96 8 ptr 1 -field OmegaGpuBackend diagnostics 104 8 ptr 1 -field OmegaGpuBackend free_buf 112 8 ptr 1 -field OmegaGpuBackend close 120 8 ptr 1 -fn omega_gpu_execute fn(*const OmegaGpuJob, *mut OmegaGpuResult) -> i32 # EXPERIMENTAL -fn omega_gpu_engine_set_backend fn(*const OmegaGpuBackend) -> () # EXPERIMENTAL -fn omega_gpu_engine_is_blocked fn() -> i32 # EXPERIMENTAL -fn omega_gpu_engine_set_clock fn(fn() -> u64) -> () # EXPERIMENTAL -fn omega_gpu_engine_failure_name fn(i32) -> *const c_char # EXPERIMENTAL -fn omega_gpu_engine_state_name fn(i32) -> *const c_char # EXPERIMENTAL -fn omega_gpu_engine_wait_name fn(i32) -> *const c_char # EXPERIMENTAL -fn omega_gpu_engine_step_name fn(i32) -> *const c_char # EXPERIMENTAL -# ---- libraries: carried over unchanged from aien-sovereign-core origin/main 10b4f851d6b082df6c2c477fbab700b551b854be crates/aien-omega-gpu/abi/omega_gpu.manifest ---- -# (matmul, elementwise, attention, serving; all EXPERIMENTAL: shapes follow one model, see docs/runtime/ROADMAP.md 1.3). -# ONE DIFFERENCE from that file: OMEGA_GPU_MATMUL_MAX_CTAS is 1024 here, 64 there (omega 98cecadc, #473, changed the header; sovereign-core pin is older). R12 must bring theirs to match. -# (omega_gpu_session_set_spin_us / _spin_us / _alloc_stats are STABLE session entries; they live in the session section of API.md) -struct OmegaGpuMatmulInfo 160 8 # EXPERIMENTAL -field OmegaGpuMatmulInfo m 0 4 u32 1 -field OmegaGpuMatmulInfo k 4 4 u32 1 -field OmegaGpuMatmulInfo n 8 4 u32 1 -field OmegaGpuMatmulInfo padded_m 12 4 u32 1 -field OmegaGpuMatmulInfo padded_n 16 4 u32 1 -field OmegaGpuMatmulInfo k_slices 20 4 u32 1 -field OmegaGpuMatmulInfo chip_calls 24 4 u32 1 -field OmegaGpuMatmulInfo rows_per_call 28 4 u32 1 -field OmegaGpuMatmulInfo elapsed_ns 32 8 u64 1 -field OmegaGpuMatmulInfo max_abs_err 40 4 f32 1 -field OmegaGpuMatmulInfo max_rel_err 44 4 f32 1 -field OmegaGpuMatmulInfo mismatch_count 48 8 u64 1 -field OmegaGpuMatmulInfo parity_verified 56 1 bool 1 -field OmegaGpuMatmulInfo completion_marker 60 4 u32 1 -field OmegaGpuMatmulInfo kernel_cache_hit 64 1 bool 1 -field OmegaGpuMatmulInfo target_chip 65 64 c_char 64 -field OmegaGpuMatmulInfo sm_architecture 132 4 u32 1 -field OmegaGpuMatmulInfo grid_x 136 4 u32 1 -field OmegaGpuMatmulInfo grid_y 140 4 u32 1 -field OmegaGpuMatmulInfo padded_k 144 4 u32 1 -field OmegaGpuMatmulInfo resident 148 1 bool 1 -field OmegaGpuMatmulInfo oracle_ran 149 1 bool 1 -field OmegaGpuMatmulInfo call_ns 152 8 u64 1 -struct OmegaGpuAllocStats 40 8 # STABLE -field OmegaGpuAllocStats allocs 0 8 u64 1 -field OmegaGpuAllocStats alloc_bytes 8 8 u64 1 -field OmegaGpuAllocStats alloc_failures 16 8 u64 1 -field OmegaGpuAllocStats frees 24 8 u64 1 -field OmegaGpuAllocStats stale_refusals 32 8 u64 1 -struct OmegaGpuServingBounds 44 4 # EXPERIMENTAL -field OmegaGpuServingBounds max_context 0 4 u32 1 -field OmegaGpuServingBounds max_seqs 4 4 u32 1 -field OmegaGpuServingBounds num_q_heads 8 4 u32 1 -field OmegaGpuServingBounds num_kv_heads 12 4 u32 1 -field OmegaGpuServingBounds head_dim 16 4 u32 1 -field OmegaGpuServingBounds kv_block_size 20 4 u32 1 -field OmegaGpuServingBounds max_rows 24 4 u32 1 -field OmegaGpuServingBounds max_k 28 4 u32 1 -field OmegaGpuServingBounds max_n 32 4 u32 1 -field OmegaGpuServingBounds max_n_one_row 36 4 u32 1 -field OmegaGpuServingBounds kernel_slots 40 4 u32 1 -struct OmegaGpuEwInfo 120 8 # EXPERIMENTAL -field OmegaGpuEwInfo chip_calls 0 4 u32 1 -field OmegaGpuEwInfo elapsed_ns 8 8 u64 1 -field OmegaGpuEwInfo completion_marker 16 4 u32 1 -field OmegaGpuEwInfo unwritten_words 20 4 u32 1 -field OmegaGpuEwInfo kernel_cache_hit 24 1 bool 1 -field OmegaGpuEwInfo gpr_count 28 4 u32 1 -field OmegaGpuEwInfo insn_count 32 4 u32 1 -field OmegaGpuEwInfo threads_per_cta 36 4 u32 1 -field OmegaGpuEwInfo ctas_last_launch 40 4 u32 1 -field OmegaGpuEwInfo target_chip 44 64 c_char 64 -field OmegaGpuEwInfo sm_architecture 108 4 u32 1 -field OmegaGpuEwInfo call_ns 112 8 u64 1 -struct OmegaGpuAttnInfo 176 8 # EXPERIMENTAL -field OmegaGpuAttnInfo chip_calls 0 4 u32 1 -field OmegaGpuAttnInfo elapsed_ns 8 8 u64 1 -field OmegaGpuAttnInfo call_ns 16 8 u64 1 -field OmegaGpuAttnInfo completion_marker 24 4 u32 1 -field OmegaGpuAttnInfo unwritten_words 28 4 u32 1 -field OmegaGpuAttnInfo gpr_count 32 4 u32 1 -field OmegaGpuAttnInfo insn_count 36 4 u32 1 -field OmegaGpuAttnInfo kernel_cache_hit 40 1 bool 1 -field OmegaGpuAttnInfo ctas_last_launch 44 4 u32 1 -field OmegaGpuAttnInfo threads_per_cta 48 4 u32 1 -field OmegaGpuAttnInfo target_chip 52 64 c_char 64 -field OmegaGpuAttnInfo sm_architecture 116 4 u32 1 -field OmegaGpuAttnInfo kv_bytes_staged 120 8 u64 1 -field OmegaGpuAttnInfo kv_bytes_naive 128 8 u64 1 -field OmegaGpuAttnInfo kv_blocks_logical 136 4 u32 1 -field OmegaGpuAttnInfo kv_blocks_unique 140 4 u32 1 -field OmegaGpuAttnInfo q_bytes 144 8 u64 1 -field OmegaGpuAttnInfo tab_bytes 152 8 u64 1 -field OmegaGpuAttnInfo out_bytes 160 8 u64 1 -field OmegaGpuAttnInfo kv_source 168 4 u32 1 -struct OmegaGpuKvLayout 64 8 # EXPERIMENTAL -field OmegaGpuKvLayout block_stride_bytes 0 8 u64 1 -field OmegaGpuKvLayout layer_stride_bytes 8 8 u64 1 -field OmegaGpuKvLayout kv_plane_stride_bytes 16 8 u64 1 -field OmegaGpuKvLayout token_stride_bytes 24 8 u64 1 -field OmegaGpuKvLayout head_stride_bytes 32 8 u64 1 -field OmegaGpuKvLayout pool_bytes 40 8 u64 1 -field OmegaGpuKvLayout num_blocks 48 4 u32 1 -field OmegaGpuKvLayout num_layers 52 4 u32 1 -field OmegaGpuKvLayout block_size 56 4 u32 1 -const OMEGA_GPU_MATMUL_OK 0 -const OMEGA_GPU_MATMUL_BAD_ARGS -1 -const OMEGA_GPU_MATMUL_TOO_LARGE -2 -const OMEGA_GPU_MATMUL_CODEGEN_FAIL -3 -const OMEGA_GPU_MATMUL_CHIP_FAIL -4 -const OMEGA_GPU_MATMUL_PARITY_FAIL -5 -const OMEGA_GPU_MATMUL_TILE_M 16 -const OMEGA_GPU_MATMUL_TILE_N 8 -const OMEGA_GPU_MATMUL_TILE_K 16 -const OMEGA_GPU_MATMUL_MAX_CTAS 1024 -const OMEGA_GPU_EW_OK 0 -const OMEGA_GPU_EW_BAD_ARGS -1 -const OMEGA_GPU_EW_TOO_LARGE -2 -const OMEGA_GPU_EW_CODEGEN_FAIL -3 -const OMEGA_GPU_EW_CHIP_FAIL -4 -const OMEGA_GPU_EW_UNWRITTEN -5 -const OMEGA_GPU_ATTN_OK 0 -const OMEGA_GPU_ATTN_BAD_ARGS -1 -const OMEGA_GPU_ATTN_TOO_LARGE -2 -const OMEGA_GPU_ATTN_CODEGEN_FAIL -3 -const OMEGA_GPU_ATTN_CHIP_FAIL -4 -const OMEGA_GPU_ATTN_UNWRITTEN -5 -const OMEGA_GPU_ATTN_KV_STAGED 0 -fn omega_gpu_matmul_bf16 fn(u32, u32, u32, *const u16, *const u16, *mut f32, *mut OmegaGpuMatmulInfo) -> i32 # EXPERIMENTAL -fn omega_gpu_matmul_f32 fn(u32, u32, u32, *const f32, *const f32, *mut f32, *mut OmegaGpuMatmulInfo) -> i32 # EXPERIMENTAL -fn omega_gpu_matmul_rc_name fn(i32) -> *const c_char # EXPERIMENTAL -fn omega_gpu_matmul_cache_clear fn() -> () # EXPERIMENTAL -fn omega_gpu_tensor_upload_bf16 fn(u32, u32, *const u16, *mut *mut OmegaGpuTensor) -> i32 # EXPERIMENTAL -fn omega_gpu_tensor_upload_f32 fn(u32, u32, *const f32, *mut *mut OmegaGpuTensor) -> i32 # EXPERIMENTAL -fn omega_gpu_tensor_free fn(*mut OmegaGpuTensor) -> () # EXPERIMENTAL -fn omega_gpu_tensor_shape fn(*const OmegaGpuTensor, *mut u32, *mut u32) -> () # EXPERIMENTAL -fn omega_gpu_matmul_resident_bf16 fn(u32, *const u16, *const OmegaGpuTensor, *mut f32, *mut OmegaGpuMatmulInfo) -> i32 # EXPERIMENTAL -fn omega_gpu_matmul_resident_f32 fn(u32, *const f32, *const OmegaGpuTensor, *mut f32, *mut OmegaGpuMatmulInfo) -> i32 # EXPERIMENTAL -fn omega_gpu_matmul_last_error fn() -> *const c_char # EXPERIMENTAL -fn omega_gpu_matmul_is_blocked fn() -> i32 # EXPERIMENTAL -fn omega_gpu_device_close fn() -> () # EXPERIMENTAL -fn omega_gpu_matmul_set_cta_budget fn(u32) -> () # EXPERIMENTAL -fn omega_gpu_matmul_cta_budget fn() -> u32 # EXPERIMENTAL -fn omega_gpu_session_set_spin_us fn(u32) -> i32 # STABLE -fn omega_gpu_session_spin_us fn() -> u32 # STABLE -fn omega_gpu_reserve_serving fn(*const OmegaGpuServingBounds) -> i32 # EXPERIMENTAL -fn omega_gpu_serving_release fn() -> () # EXPERIMENTAL -fn omega_gpu_matmul_prepare fn(u32, u32, u32) -> i32 # EXPERIMENTAL -fn omega_gpu_serving_seal fn() -> () # EXPERIMENTAL -fn omega_gpu_session_alloc_stats fn(*mut OmegaGpuAllocStats) -> () # STABLE -fn omega_gpu_rmsnorm_f32 fn(u32, u32, *const f32, *const f32, f32, *mut f32, *mut OmegaGpuEwInfo) -> i32 # EXPERIMENTAL -fn omega_gpu_rope_f32 fn(u32, u32, *const f32, *const f32, *const f32, *mut f32, *mut OmegaGpuEwInfo) -> i32 # EXPERIMENTAL -fn omega_gpu_swiglu_f32 fn(u32, *const f32, *const f32, *mut f32, *mut OmegaGpuEwInfo) -> i32 # EXPERIMENTAL -fn omega_gpu_elementwise_rc_name fn(i32) -> *const c_char # EXPERIMENTAL -fn omega_gpu_gqa_attention_f32 fn(*const f32, *const f32, *const f32, u32, u32, u32, u32, *mut f32, *mut OmegaGpuAttnInfo) -> i32 # EXPERIMENTAL -fn omega_gpu_gqa_attention_rows_f32 fn(*const f32, *const f32, *const f32, u32, u32, u32, u32, u32, *mut f32, *mut OmegaGpuAttnInfo) -> i32 # EXPERIMENTAL -fn omega_gpu_attention_pool_alloc fn(usize, *mut *mut c_void) -> i32 # EXPERIMENTAL -fn omega_gpu_attention_pool_free fn() -> () # EXPERIMENTAL -fn omega_gpu_paged_attention_bf16 fn(*const f32, *const c_void, *const OmegaGpuKvLayout, *const u32, u32, u32, u32, u32, u32, u32, *mut f32, *mut OmegaGpuAttnInfo) -> i32 # EXPERIMENTAL -fn omega_gpu_paged_attention_batch_bf16 fn(*const f32, *const c_void, *const OmegaGpuKvLayout, *const i32, *const i32, u32, u32, u32, u32, u32, u32, *mut f32, *mut OmegaGpuAttnInfo) -> i32 # EXPERIMENTAL -fn omega_gpu_attention_rc_name fn(i32) -> *const c_char # EXPERIMENTAL -fn omega_gpu_attention_last_error fn() -> *const c_char # EXPERIMENTAL -# ---- constants of the runtime headers (values blessed from the headers) ---- -const OMEGA_GPU_PLATFORM_ABI_MAJOR 1 -const OMEGA_GPU_PLATFORM_ABI_MINOR 2 -const OMEGA_GPU_POLL_TIMED_OUT 100 -const OMEGA_GPU_HANDLE_SLOTS 4096 -const OMEGA_GPU_HANDLE_DEVICE 1 -const OMEGA_GPU_HANDLE_BUF_DATA 2 -const OMEGA_GPU_HANDLE_BUF_CODE 3 -const OMEGA_GPU_HANDLE_BUF_QUEUE 4 -const OMEGA_GPU_HANDLE_QUEUE 5 -const OMEGA_GPU_HANDLE_KIND_COUNT 6 -const OMEGA_GPU_RIGHT_CPU_READ 1 -const OMEGA_GPU_RIGHT_CPU_WRITE 2 -const OMEGA_GPU_RIGHT_GPU_READ 4 -const OMEGA_GPU_RIGHT_GPU_WRITE 8 -const OMEGA_GPU_RIGHT_GPU_EXEC 16 -const OMEGA_GPU_RIGHT_HOST_POLLED 32 -const OMEGA_GPU_RIGHT_ALL 63 -const OMEGA_GPU_CACHE_GPU_UNCACHED 0 -const OMEGA_GPU_CACHE_GPU_CACHED 1 -const OMEGA_GPU_SVC_TIME 1 -const OMEGA_GPU_SVC_WAIT 2 -const OMEGA_GPU_SVC_LOCK 4 -const OMEGA_GPU_SVC_MMIO 8 -const OMEGA_GPU_SVC_DMA 16 -const OMEGA_GPU_SVC_SYNC 32 -const OMEGA_GPU_SVC_COMPLETION 64 -const OMEGA_GPU_SVC_IRQ 128 -const OMEGA_GPU_SVC_REQUIRED_V1 127 -const OMEGA_GPU_SVC_DEVICE 256 -const OMEGA_GPU_SVC_QUEUE 512 -const OMEGA_GPU_SVC_CLOCK_NS 1024 -const OMEGA_GPU_SVC_HOST_MEM 2048 -const OMEGA_GPU_SVC_REQUIRED_SESSION 3959 -const OMEGA_GPU_SVC_ALL 4095 -const OMEGA_GPU_PLAT_OK 0 -const OMEGA_GPU_PLAT_REFUSED_ARGS 1 -const OMEGA_GPU_PLAT_REFUSED_ABI 2 -const OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE 3 -const OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE 4 -const OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE 5 -const OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE 6 -const OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH 7 -const OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS 8 -const OMEGA_GPU_PLAT_REFUSED_BAD_KIND 9 -const OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY 10 -const OMEGA_GPU_PLAT_REFUSED_LIMIT 11 -const OMEGA_GPU_PLAT_REFUSED_BUSY 12 -const OMEGA_GPU_PLAT_REFUSED_DEVICE 13 -const OMEGA_GPU_PLAT_REFUSAL_COUNT 14 -const OMEGA_GPU_SESSION_MAX_SPIN_US 1000000 -const OMEGA_GPU_SESSION_MAX_ARGS 32 -const OMEGA_GPU_SESSION_POLL_SLICE_MS 1 -const OMEGA_GPU_SESSION_LOCK_ID 0 -const OMEGA_GPU_SESSION_SCRATCH_RESERVED -2 -const OMEGA_GPU_SESSION_CANCELLED -3 -const OMEGA_GPU_SESSION_PARK_MAX 512 -const OMEGA_GPU_COMPLETION_POLLING 1 -const OMEGA_GPU_CMDLIST_MAX_LAUNCHES 4096 -const OMEGA_GPU_CMDLIST_BANK_BYTES 1024 -const OMEGA_GPU_CMDLIST_QMD_BYTES 1024 -const OMEGA_GPU_CMDLIST_PCAS 0 -const OMEGA_GPU_CMDLIST_INLINE 1 -const OMEGA_GPU_CMDLIST_BARRIER_WFI 0 -const OMEGA_GPU_CMDLIST_BARRIER_NONE 1 -const OMEGA_GPU_CMDLIST_BARRIER_WFI_ONLY 2 -const OMEGA_GPU_CMDLIST_BARRIER_WFI_DATA 3 -const OMEGA_GPU_CMDLIST_BARRIER_FLUSH_DATA 4 -const OMEGA_GPU_ENGINE_FLAG_NO_C3 1 -const OMEGA_GPU_ENGINE_JOB_OUTPUTS 1 -const OMEGA_GPU_ENGINE_SEMAPHORE_WORDS 1 -const OMEGA_GPU_ENGINE_DRV_TEXT_BYTES 128 -const OMEGA_GPU_SYNC_MARKER 1 -const OMEGA_GPU_SYNC_MARKER2 2 -const OMEGA_GPU_SYNC_SEMAPHORE 4 -const OMEGA_GPU_BACKEND_TIMEOUT 1 -const OMEGA_GPU_BACKEND_UNKNOWN_STATE 2 -const OMEGA_GPU_ENGINE_OK 0 -const OMEGA_GPU_ENGINE_DEVICE_OPEN 1 -const OMEGA_GPU_ENGINE_CHANNEL_CREATE 2 -const OMEGA_GPU_ENGINE_ALLOC 3 -const OMEGA_GPU_ENGINE_PREPARE 4 -const OMEGA_GPU_ENGINE_SUBMIT 5 -const OMEGA_GPU_ENGINE_COMPLETION_WAIT 6 -const OMEGA_GPU_ENGINE_RELEASE_WAIT 7 -const OMEGA_GPU_ENGINE_VISIBILITY_WAIT 8 -const OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED 9 -const OMEGA_GPU_ENGINE_INVALID_ARGS 10 -const OMEGA_GPU_ENGINE_INTERNAL_INVARIANT 11 -const OMEGA_GPU_ENGINE_CLEANUP 12 -const OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED 13 -const OMEGA_GPU_ENGINE_FAILURE_COUNT 14 -const OMEGA_GPU_ENGINE_STATE_INITIAL 0 -const OMEGA_GPU_ENGINE_STATE_PREPARED 1 -const OMEGA_GPU_ENGINE_STATE_SUBMITTED 2 -const OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE 3 -const OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE 4 -const OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED 5 -const OMEGA_GPU_ENGINE_STATE_SUCCESS 6 -const OMEGA_GPU_ENGINE_STATE_COUNT 7 -const OMEGA_GPU_ENGINE_WAIT_NONE 0 -const OMEGA_GPU_ENGINE_WAIT_MARKER 1 -const OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE 2 -const OMEGA_GPU_ENGINE_WAIT_MARKER2 3 -const OMEGA_GPU_ENGINE_WAIT_COUNT 4 -const OMEGA_GPU_ENGINE_STEP_NONE 0 -const OMEGA_GPU_ENGINE_STEP_VALIDATE 1 -const OMEGA_GPU_ENGINE_STEP_BACKEND_CHECK 2 -const OMEGA_GPU_ENGINE_STEP_BLOCKED 3 -const OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED 4 -const OMEGA_GPU_ENGINE_STEP_OPEN_DEVICE 5 -const OMEGA_GPU_ENGINE_STEP_CREATE_CHANNEL 6 -const OMEGA_GPU_ENGINE_STEP_ALLOC 7 -const OMEGA_GPU_ENGINE_STEP_COPY_IN 8 -const OMEGA_GPU_ENGINE_STEP_FILL_POISON 9 -const OMEGA_GPU_ENGINE_STEP_BUILD 10 -const OMEGA_GPU_ENGINE_STEP_SUBMIT 11 -const OMEGA_GPU_ENGINE_STEP_WAIT_MARKER 12 -const OMEGA_GPU_ENGINE_STEP_WAIT_MARKER2 13 -const OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE 14 -const OMEGA_GPU_ENGINE_STEP_BARRIER 15 -const OMEGA_GPU_ENGINE_STEP_COPY_OUT 16 -const OMEGA_GPU_ENGINE_STEP_SCAN 17 -const OMEGA_GPU_ENGINE_STEP_FREE 18 -const OMEGA_GPU_ENGINE_STEP_CLOSE 19 -const OMEGA_GPU_ENGINE_STEP_CLOCK_CHECK 20 -const OMEGA_GPU_ENGINE_STEP_COUNT 21 -const OMEGA_GPU_LAYOUT_VECTOR_1D 0 -const OMEGA_GPU_LAYOUT_COUNT 1 -const OMEGA_GPU_BUF_SCRATCH 0 -const OMEGA_GPU_BUF_PROGRAM 1 -const OMEGA_GPU_BUF_INPUT_A 2 -const OMEGA_GPU_BUF_INPUT_B 3 -const OMEGA_GPU_BUF_OUTPUT 4 -const OMEGA_GPU_BUF_ROLE_COUNT 5 diff --git a/docs/runtime/portability_table.tsv b/docs/runtime/portability_table.tsv index 7d927220d..8cd739d2b 100644 --- a/docs/runtime/portability_table.tsv +++ b/docs/runtime/portability_table.tsv @@ -1,133 +1,8 @@ -# Omega portability table (omega-mv#596, slice R3). Checked by: make test-runtime-portability (tools/runtime_portability_check.sh). +# Omega portability table (omega-mv#596, slice R3): the rows of the GPU-named files Omega still carries. Every other GPU source, +# and its row, is CUDApp's ($(CUDAPP_SOURCE)/docs/runtime/portability_table.tsv). Checked by: make test-runtime-portability-check. # Columns, tab separated: file, class, reason, os_binding. Explained in docs/runtime/PORTABILITY.md. # class: CHIP_SPECIFIC carries knowledge of the GB10 / Blackwell chip or of the driver interface that exposes it; PORTABLE carries neither. # os_binding: FREESTANDING_PROVEN (a .c file in GPU_FS_SRCS, mk/omega-gpu-engine.mk, built by make gpu-engine-freestanding), NO_HOSTED_INCLUDE (no hosted header by include scan only; not linked freestanding), HOSTED_LIBC (includes stdio, stdlib, time, errno, math or pthread), LINUX_DRIVER (includes nvrm.h, m16_native.h or omega_gpu_platform_linux.h). file class reason os_binding -src/omega_blackwell_codegen.c CHIP_SPECIFIC Instruction generators for the sm_121 kernels (vector add, matmul, the Qwen decode set); emits Blackwell machine code through the encoder. In the freestanding closure; the allocating generators and the printing self-test are hosted-only (docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md section 3). FREESTANDING_PROVEN -src/omega_blackwell_codegen.h CHIP_SPECIFIC Blackwell IR opcodes and kernel-generator API; includes omega_blackwell_matmul.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_attn.c CHIP_SPECIFIC Generates the single-launch decode attention kernel (sm_121 machine code, 8 query heads per KV head, head_dim 128). NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_attn.h CHIP_SPECIFIC Interface of the decode attention kernel generator; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_attn256.c CHIP_SPECIFIC Generates the one-launch decode attention kernel for head_dim 256 (Qwen3.8-27B: 24 query heads over 4 KV heads, KV append inside the kernel) as sm_121 machine code; reuses the emitter helpers of omega_blackwell_codegen_attn.c. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_attn256.h CHIP_SPECIFIC Interface of the head_dim 256 decode attention generator; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_bf16.c CHIP_SPECIFIC Generates the bf16 streaming GEMV (lm_head) as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_bf16.h CHIP_SPECIFIC Interface of the bf16 GEMV generator; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_dec.c CHIP_SPECIFIC Generates the decode glue kernels (residual add, RMSNorm, SwiGLU, expert combine, argmax) as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_dec.h CHIP_SPECIFIC Interface of the decode glue kernel generators; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_gdn.c CHIP_SPECIFIC Generates the one-launch Gated DeltaNet decode step as sm_121 machine code (control words, read barriers, held-scoreboard prefetch of omega_bw_em.h). NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_gdn.h CHIP_SPECIFIC Interface of the Gated DeltaNet generator; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_gemm.c CHIP_SPECIFIC Generates the FP8 block-scaled grouped GEMM for prefill as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_gemm.h CHIP_SPECIFIC Interface of the FP8 prefill GEMM generator; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_moe.c CHIP_SPECIFIC Generates the FP8 GEMV kernel family (MoE) as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_moe.h CHIP_SPECIFIC Interface of the FP8 GEMV generator; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_moe2.c CHIP_SPECIFIC Generates FP8 GEMV variant 2 (row-pipelined) as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_moe2.h CHIP_SPECIFIC Interface of FP8 GEMV variant 2; includes omega_blackwell_codegen_moe.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_pattn.c CHIP_SPECIFIC Generates the causal prefill attention kernel on tensor cores (HMMA, SHFL) as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_pattn.h CHIP_SPECIFIC Interface of the prefill attention generator; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_pattn256.c CHIP_SPECIFIC Generates the head_dim 256 causal prefill attention attend kernel on tensor cores (HMMA spacing, SHFL.BFLY / F2FP placeholders) as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_pattn256.h CHIP_SPECIFIC Interface of the head_dim 256 prefill attention generator; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_pf.c CHIP_SPECIFIC Generates the small device-resident prefill kernels (copy and friends) as sm_121 machine code through the omega_bw_em.h emitters. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_pf.h CHIP_SPECIFIC Interface of the prefill helper kernels; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_pfhost.c CHIP_SPECIFIC Generates the on-chip router-logits and MoE-combine kernels as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_pfhost.h CHIP_SPECIFIC Interface of the on-chip router and combine generators; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_qg.c CHIP_SPECIFIC Generates the native FP8 prefill kernels (activation quantiser, QMMA GEMM) as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_qg.h CHIP_SPECIFIC Interface of the native FP8 prefill generators; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_qmma.c CHIP_SPECIFIC Encodes the FP8 tensor-core op QMMA.16832, patched in after the shared encoder (which lacks it); values come from an nvcc sm_121 oracle. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_qmma.h CHIP_SPECIFIC Describes the QMMA.16832.F32.E4M3.E4M3 encoding for sm_121. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_router.c CHIP_SPECIFIC Generates the MoE router kernel (RMSNorm, logits, softmax, top-8) as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_router.h CHIP_SPECIFIC Interface of the router kernel generator; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_tc2.c CHIP_SPECIFIC Generates the tensor-core grouped FP8 GEMM v2 as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_tc2.h CHIP_SPECIFIC Interface of the tensor-core GEMM v2 generator; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_tc.c CHIP_SPECIFIC Generates tensor-core kernels (HMMA.16816 fragment layout) as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_tc.h CHIP_SPECIFIC Interface of the tensor-core kernel generators; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_tern.c CHIP_SPECIFIC Generates the ternary W2A8 GEMV as sm_121 machine code. NO_HOSTED_INCLUDE -src/omega_blackwell_codegen_tern.h CHIP_SPECIFIC Interface of the ternary GEMV generator; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_blackwell_encoder.c CHIP_SPECIFIC The sm_121 machine-code encoder: packs instructions into 16-byte words. OS-free (in the freestanding closure) but the words it writes are Blackwell's. FREESTANDING_PROVEN -src/omega_blackwell_encoder.h CHIP_SPECIFIC Encoder interface; OMEGA_BW_INSTRUCTION_BYTES is 16, the Blackwell instruction size. NO_HOSTED_INCLUDE -src/omega_blackwell_engine.c CHIP_SPECIFIC The Linux backend of OmegaGpuBackend: calls m16_native_* and carries the GB10 compute-class setup words (class 0xcec0). LINUX_DRIVER -src/omega_blackwell_engine.h CHIP_SPECIFIC Declares the Blackwell GB10 backend function table for the engine core. NO_HOSTED_INCLUDE src/omega_blackwell_gates.c CHIP_SPECIFIC Milestone 17 and 18 qualification gates and a silicon vector-add demonstration on GB10; host tooling. HOSTED_LIBC src/omega_blackwell_gates.h CHIP_SPECIFIC Entry points of the M17 and M18 GB10 qualification gates. NO_HOSTED_INCLUDE -src/omega_blackwell_matmul.c CHIP_SPECIFIC Plans the Blackwell matmul kernels; in the freestanding closure, but the kernel shapes are sm_121 tensor-core shapes. FREESTANDING_PROVEN -src/omega_blackwell_matmul.h CHIP_SPECIFIC Types of the Blackwell matmul kernel (OmegaBlackwellKernel) and its size limits. NO_HOSTED_INCLUDE -src/omega_blackwell_qmd.c CHIP_SPECIFIC Builds the 384-byte QMD launch descriptor (96 words) for Blackwell compute class 0xcec0. In the freestanding closure. FREESTANDING_PROVEN -src/omega_blackwell_qmd.h CHIP_SPECIFIC QMD layout: OMEGA_BW_QMD_BYTES 384, field evidence tiers (documented, observed, reverse engineered), shared-memory field per clcec0qmd.h. NO_HOSTED_INCLUDE -src/omega_blackwell_realize.c CHIP_SPECIFIC Turns an Omega vector program into Blackwell code plus QMD plus constant bank. In the freestanding closure. FREESTANDING_PROVEN -src/omega_blackwell_realize.h CHIP_SPECIFIC Realization interface; includes omega_blackwell_qmd.h and omega_blackwell_encoder.h. NO_HOSTED_INCLUDE -src/omega_blackwell_submit.c CHIP_SPECIFIC The vector executor: allocates and submits through m16_native_* on the Linux driver; its setup words and launch methods are GB10's. Pinned by the M17 and M18 gates. LINUX_DRIVER -src/omega_blackwell_submit.h CHIP_SPECIFIC Launch constants and executor interface for GB10; includes the realize and matmul headers. NO_HOSTED_INCLUDE -src/omega_bw_em.h CHIP_SPECIFIC Private IR emitter helpers for the sm_121 tensor-core generators (scheduling rules proven on the chip). NO_HOSTED_INCLUDE -src/omega_bw_em_q.h CHIP_SPECIFIC Private emitters for the FP8 QMMA placeholders (sm_121). NO_HOSTED_INCLUDE -src/omega_bw_hazard.c CHIP_SPECIFIC Static scoreboard hazard checker over encoded sm_121 kernel bytes (RAW, WAR, WAW against the Blackwell write and read barriers); decodes the operand positions the encoder writes. Includes stdlib.h. HOSTED_LIBC -src/omega_bw_hazard.h CHIP_SPECIFIC Interface of the sm_121 scoreboard hazard checker; includes only stddef.h and stdint.h. NO_HOSTED_INCLUDE -src/omega_bw_reconv.h CHIP_SPECIFIC Warp reconvergence regions (BSSY, BSYNC) for the Blackwell IR emitters. NO_HOSTED_INCLUDE -src/omega_gpu_attention_api.c CHIP_SPECIFIC Builds and launches its own sm_121 attention kernels (stall counts as nvcc writes them for sm_121) through the session. In the freestanding closure. FREESTANDING_PROVEN -src/omega_gpu_attention_api.h CHIP_SPECIFIC Attention API; its kernel type OmegaBlackwellKernel comes from omega_blackwell_matmul.h. NO_HOSTED_INCLUDE -src/omega_gpu_bf16_gemv_api.c CHIP_SPECIFIC Launches the bf16 GEMV through a command list; uses the Blackwell bf16 generator. NO_HOSTED_INCLUDE -src/omega_gpu_bf16_gemv_api.h CHIP_SPECIFIC bf16 GEMV API; includes omega_blackwell_codegen_bf16.h. NO_HOSTED_INCLUDE -src/omega_gpu_cmdlist.c CHIP_SPECIFIC Records launches into one method stream using clcec0 method numbers (WAIT_FOR_IDLE 0x0110, SEND_PCAS_A 0x02b4), the compute-class setup words, and the completion tail with an L2 flush. NO_HOSTED_INCLUDE -src/omega_gpu_cmdlist.h CHIP_SPECIFIC Command-list interface; documents the uncached marker page and the L2_FLUSH_DIRTY tail. NO_HOSTED_INCLUDE -src/omega_gpu_code_alloc.h CHIP_SPECIFIC Code buffers keep a 2 KB tail after the last instruction because the SM instruction cache prefetches past it (omega#323; the cause on GB10 is INFERRED). NO_HOSTED_INCLUDE -src/omega_gpu_decode_attn256_api.c CHIP_SPECIFIC Resident KV cache, RoPE table and launch of the head_dim 256 decode attention kernel on the session and command list. NO_HOSTED_INCLUDE -src/omega_gpu_decode_attn256_api.h CHIP_SPECIFIC head_dim 256 decode attention API; includes omega_blackwell_codegen_attn256.h. NO_HOSTED_INCLUDE -src/omega_gpu_decode_attn_api.c CHIP_SPECIFIC Launches the decode attention kernel from the Blackwell generator through a command list. NO_HOSTED_INCLUDE -src/omega_gpu_decode_attn_api.h CHIP_SPECIFIC Decode attention API; includes omega_blackwell_codegen_attn.h. NO_HOSTED_INCLUDE -src/omega_gpu_decode_graph.c CHIP_SPECIFIC Chains a whole decode token into one command list from Blackwell kernels. HOSTED_LIBC -src/omega_gpu_decode_graph.h CHIP_SPECIFIC Decode graph interface over the FP8, router, attention and bf16 GEMV APIs. NO_HOSTED_INCLUDE -src/omega_gpu_elementwise_api.c CHIP_SPECIFIC Generates and launches its own elementwise sm_121 kernels; still hosted (stdio, stdlib, time), outside the freestanding closure (boundary doc section 6). HOSTED_LIBC -src/omega_gpu_elementwise_api.h CHIP_SPECIFIC Elementwise API; kernel type OmegaBlackwellKernel comes from omega_blackwell_matmul.h. NO_HOSTED_INCLUDE -src/omega_gpu_engine.c PORTABLE The engine state machine (open, validate, submit, verify, close, named failure steps). Builds in make gpu-engine-freestanding; errno and the default clock exist only in the hosted build. FREESTANDING_PROVEN -src/omega_gpu_engine.h PORTABLE Engine contract and OmegaGpuBackend function table; includes only stddef.h and stdint.h. NO_HOSTED_INCLUDE -src/omega_gpu_fmt.c PORTABLE Bounded text formatter that replaces snprintf in the session. Builds in make gpu-engine-freestanding. FREESTANDING_PROVEN -src/omega_gpu_fmt.h PORTABLE Formatter interface; includes only stddef.h. NO_HOSTED_INCLUDE -src/omega_gpu_fp8_api.c CHIP_SPECIFIC Launches the FP8 GEMV through Blackwell generators and command lists, with GPU-cached weight buffers. HOSTED_LIBC -src/omega_gpu_fp8_api.h CHIP_SPECIFIC FP8 GEMV API; includes omega_blackwell_codegen_moe.h. NO_HOSTED_INCLUDE -src/omega_gpu_fp8gemm_api.c CHIP_SPECIFIC Launches the FP8 prefill GEMM through the session. HOSTED_LIBC -src/omega_gpu_fp8gemm_api.h CHIP_SPECIFIC FP8 GEMM API; includes omega_blackwell_codegen_gemm.h. NO_HOSTED_INCLUDE -src/omega_gpu_fp8_pack.c CHIP_SPECIFIC Packs FP8 weights into the layout the sm_121 GEMV kernels read; host side. HOSTED_LIBC -src/omega_gpu_fp8_internal.h CHIP_SPECIFIC Library-internal helpers of omega_gpu_fp8_api.c for the slot pool (GPU-UNCACHED FP8 tensor allocation, CPU views of one expert); includes omega_gpu_fp8_api.h. NO_HOSTED_INCLUDE -src/omega_gpu_fp8_slots.c CHIP_SPECIFIC Versioned replaceable FP8 expert slots backed by one OmegaGpuFp8Tensor; uses the session's platform SYNC and the grouped FP8 GEMV launch. Includes stdlib.h. HOSTED_LIBC -src/omega_gpu_fp8_slots.h CHIP_SPECIFIC FP8 expert slot pool API (load, pin, entry, evict, grouped GEMV); includes omega_gpu_fp8_api.h. NO_HOSTED_INCLUDE -src/omega_gpu_gdn_api.c CHIP_SPECIFIC Resident Gated DeltaNet parameters, GPU-cached tails and states (omega_gpu_mem_cached.h) and the one-launch decode step from the Blackwell generator. HOSTED_LIBC -src/omega_gpu_gdn_api.h CHIP_SPECIFIC Gated DeltaNet API; includes omega_blackwell_codegen_gdn.h. NO_HOSTED_INCLUDE -src/omega_gpu_gemm.c CHIP_SPECIFIC Matrix multiply of any shape on the GB10 tensor cores (HMMA.16816 BF16, QMMA.16832 E4M3) through the omega_bw_em emitters. HOSTED_LIBC -src/omega_gpu_gemm.h CHIP_SPECIFIC GEMM API whose arithmetic order is fixed by the GB10 tensor-core step shapes; includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_gpu_hostmath.c PORTABLE libm-free double-precision log, exp and pow for host-side tables; plain arithmetic, no chip or OS call. NO_HOSTED_INCLUDE -src/omega_gpu_hostmath.h PORTABLE Interface of the libm-free host math; no includes. NO_HOSTED_INCLUDE -src/omega_gpu_matmul_api.c CHIP_SPECIFIC Builds Blackwell matmul kernels, fills the QMD and launches; reports target_chip GB10. In the freestanding closure. FREESTANDING_PROVEN -src/omega_gpu_matmul_api.h CHIP_SPECIFIC Public contract exposes Blackwell tile macros TILE_M=16, TILE_N=8, TILE_K=16, chip CTA envelope and GPU-uncached resident storage; plain C types do not make these semantics chip-neutral. NO_HOSTED_INCLUDE -src/omega_gpu_mem_cached.c CHIP_SPECIFIC Allocates GPU-cached weight buffers; relies on the GB10 rule that a write-once buffer the CPU never reads cannot hold a stale L2 line. NO_HOSTED_INCLUDE -src/omega_gpu_mem_cached.h CHIP_SPECIFIC Documents the GPU-cached read-only weight invariant (nvos.h GPU_CACHEABLE: not coherent with CPU mappings). NO_HOSTED_INCLUDE -src/omega_gpu_moe_api.c CHIP_SPECIFIC Launches MoE matmul kernels from the Blackwell generators and the QMD builder. NO_HOSTED_INCLUDE -src/omega_gpu_moe_api.h CHIP_SPECIFIC Public packing contract is Blackwell tile-major B with col0 modulo 8 alignment and OMEGA_BW_MATMUL_MAX limits; includes omega_gpu_matmul_api.h. NO_HOSTED_INCLUDE -src/omega_gpu_pfgemm.c CHIP_SPECIFIC Prefill GEMM driver over the Blackwell tensor-core generators. HOSTED_LIBC -src/omega_gpu_pfhost.c CHIP_SPECIFIC Prefill router and combine launcher over the Blackwell pfhost generators. NO_HOSTED_INCLUDE -src/omega_gpu_pfhost.h CHIP_SPECIFIC Prefill router and combine API; documents bit-exact sm_121 kernel semantics. NO_HOSTED_INCLUDE -src/omega_gpu_platform.c PORTABLE Platform contract checks, negotiation and handle table. Builds in make gpu-engine-freestanding. FREESTANDING_PROVEN -src/omega_gpu_platform.h CHIP_SPECIFIC ABI 1.2 has reusable typed handles but its current queue_submit contract specifies one GPFIFO entry and its HOST_POLLED rights require the NVIDIA GPU-uncached visibility policy. Device ordinal 0 is documented as the GB10; review this contract on another chip. NO_HOSTED_INCLUDE -src/omega_gpu_platform_linux.c CHIP_SPECIFIC The Linux reference platform: nvrm_open and m16_native_create_channel on the NVIDIA open driver. Hosted only, outside the freestanding closure. LINUX_DRIVER -src/omega_gpu_platform_linux.h CHIP_SPECIFIC Declares the Linux driver platform; the implementation behind it is the Linux binding. NO_HOSTED_INCLUDE -src/omega_gpu_prefill_attn256_api.c CHIP_SPECIFIC Launches the two head_dim 256 prefill attention kernels and patches the tensor-core placeholders of omega_blackwell_codegen_tc.h. NO_HOSTED_INCLUDE -src/omega_gpu_prefill_attn256_api.h CHIP_SPECIFIC head_dim 256 prefill attention API; includes omega_blackwell_codegen_pattn256.h. NO_HOSTED_INCLUDE -src/omega_gpu_prefill_attn_api.c CHIP_SPECIFIC Launches the prefill attention kernel from the Blackwell generator on the session. NO_HOSTED_INCLUDE -src/omega_gpu_prefill_attn_api.h CHIP_SPECIFIC Prefill attention API; includes omega_blackwell_codegen_pattn.h. NO_HOSTED_INCLUDE -src/omega_gpu_prefill.c CHIP_SPECIFIC Device-resident prefill: GPU-cached device buffers and a copy kernel, with the stale-L2 rules for GB10. NO_HOSTED_INCLUDE -src/omega_gpu_prefill.h CHIP_SPECIFIC Documents the prefill memory policy: GPU-cached device-private buffers and L2_FLUSH_DIRTY. NO_HOSTED_INCLUDE -src/omega_gpu_q36_graph.c CHIP_SPECIFIC One Qwen3.6-35B-A3B decode token as one command list of Blackwell kernels with GPU-cached intermediates (omega_gpu_mem_cached.h). HOSTED_LIBC -src/omega_gpu_q36_graph.h CHIP_SPECIFIC Qwen3.6-35B-A3B decode graph interface over the decode graph, hd256 attention, GDN and router APIs. NO_HOSTED_INCLUDE -src/omega_gpu_q38_graph.c CHIP_SPECIFIC One Qwen3.8-27B decode token as one command list of Blackwell kernels with GPU-cached intermediates (omega_gpu_mem_cached.h). HOSTED_LIBC -src/omega_gpu_q38_graph.h CHIP_SPECIFIC Qwen3.8-27B decode graph interface over the decode graph, hd256 attention and GDN APIs. NO_HOSTED_INCLUDE -src/omega_gpu_router_api.c CHIP_SPECIFIC Launches the router kernel through a command list. NO_HOSTED_INCLUDE -src/omega_gpu_router_api.h CHIP_SPECIFIC Router API; includes omega_blackwell_codegen_router.h. NO_HOSTED_INCLUDE -src/omega_gpu_scan.c CHIP_SPECIFIC Reduction and prefix-sum kernels from the omega_bw_em emitters (SHFL.DOWN warp trees) and the chip launch driver. HOSTED_LIBC -src/omega_gpu_scan.h CHIP_SPECIFIC Reduction and prefix-sum API; the chip calls take Blackwell kernels and the header includes omega_blackwell_codegen.h. NO_HOSTED_INCLUDE -src/omega_gpu_scan_ref.c PORTABLE Host references of the frozen reduction and prefix-sum order, which depends only on n and the element index (docs/numeric/E1_REDUCTION_CONTRACT.md); plain C additions, no chip or OS call. Its own header omega_gpu_scan.h still pulls in omega_blackwell_codegen.h, so reusing it off this tree needs the declarations split out. HOSTED_LIBC -src/omega_gpu_serving.c CHIP_SPECIFIC Thin wrapper calls omega_gpu_matmul_reserve and the current attention reservation APIs with their chip-specific contracts; it does not implement an independent generic accounting layer. OS-free in make gpu-engine-freestanding. FREESTANDING_PROVEN -src/omega_gpu_serving.h CHIP_SPECIFIC Current GB10 serving contract delegates to chip-specific matmul/attention reservations and documents at-most-16-row handling and fixed kernel-cache defaults/limits; absence of hosted includes is not a chip-neutral contract. NO_HOSTED_INCLUDE -src/omega_gpu_session.c CHIP_SPECIFIC The persistent session over OmegaGpuPlatform. OS-free (in the freestanding closure) but carries GB10 constants: the compute-class setup words (class 0xcec0), the cache-invalidate method 0x021c, launch constants from omega_blackwell_submit.h. FREESTANDING_PROVEN -src/omega_gpu_session.h CHIP_SPECIFIC Session exposes QMD scratch, register-count rules and QMD shared-memory default 1024, plus the GB10 two-marker/L2 flush launch protocol; platform handles remove OS types, not chip assumptions. NO_HOSTED_INCLUDE -src/omega_gpu_tcgemm_api.c CHIP_SPECIFIC Launches the tensor-core GEMM through the session. HOSTED_LIBC -src/omega_gpu_tcgemm_api.h CHIP_SPECIFIC Tensor-core GEMM API; includes omega_blackwell_codegen_tc.h. NO_HOSTED_INCLUDE -src/omega_gpu_tern_api.c CHIP_SPECIFIC Launches the ternary GEMV with GPU-cached weights through a command list. HOSTED_LIBC -src/omega_gpu_tern_api.h CHIP_SPECIFIC Ternary GEMV API; includes omega_blackwell_codegen_tern.h. NO_HOSTED_INCLUDE -src/omega_gpu_wait.c PORTABLE Bounded wait with a caller-supplied clock and hooks; no default clock in the freestanding build. Builds in make gpu-engine-freestanding. FREESTANDING_PROVEN -src/omega_gpu_wait.h PORTABLE Bounded wait interface; includes only stdbool.h and stdint.h. NO_HOSTED_INCLUDE diff --git a/mk/.crumb b/mk/.crumb index e7c066246..5a802c107 100644 --- a/mk/.crumb +++ b/mk/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-31T02:35:18Z", + "compiled_at": "2026-10-31T10:38:06Z", "compiler": "crumb-compile/1", - "digest": "sha256:c0668c8969cceab0f03ac6ab352ae579c8b473a9ec743d80c89fc187b769c12c", + "digest": "sha256:5490f02828f11619c2a427905af48d9d2e3711067e60f72a34ea7b7a69a041b2", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 97, - "generated_at_commit": "6d7b883844a0f17a7a3ceb427108be7e01e4c677", - "source_tree": "sha256:bca5f08744bd80629e47ac0c27aaeda59e174ed0a3e0cc1d55378862bae21e78" + "generated_at_commit": "a84088331cab756df49419eb03049d7b9a70eb2c", + "source_tree": "sha256:ef1eb39feb05c1ac78a55cb4cfac4d22f7a05a197cc5d2c6e5d64c44a141455c" }, "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/om-encoder.mk b/mk/om-encoder.mk deleted file mode 100644 index 16de2e0d0..000000000 --- a/mk/om-encoder.mk +++ /dev/null @@ -1,83 +0,0 @@ -# The sm_121 instruction encoder in seeded Omega (om/encoder/bw_enc_sm121.om, twin of aien-dev/CUDApp#79), linked -# through the omega-bridge native binding src/omega_om_units.c that om/units.sh generates. The C encoder in -# src/omega_blackwell_codegen.c is migration-pending: the freestanding build and the oracle builds only. -# make test-om-encoder (no Omega tools needed) -# 1. the golden-word fixture verifiers (nvcc/nvdisasm oracles) through the .om encoder; -# 2. a build with CUDAPP_MIGRATION_PENDING_ENCODER_DIFF encodes every codegen fixture both ways and must log -# only SAME lines; 3. its red check: the same build with one flipped output bit must abort. -# make test-om-encoder-corpus every kernel of the sm121dis corpus (tools/sm121dis/corpus.sh) built three ways: -# .om (OUT_DIR), C oracle ($(OUT_DIR)-enc-c), diff ($(OUT_DIR)-enc-diff); the .om and C kernel sets must be -# identical file for file, and the diff build must log no DIFFER line. The num_*.bin kernels come from the -# numeric encoder (build/test_omega_{divsqrt,ldst}_gb10_cpu, shared by all three runs), not from this one. -# make test-om-encoder-mutants three mutant .om encoders, each compiled by the pinned omc, must go red -# The binding itself regenerates byte for byte in tests/gates/run.sh om-units (om/units.sh --check). The mutants need -# OMEGA_OMC (default seed/out/omc, born from the seed by seed/omega-from-seed.sh) and OMEGA_BRIDGE_DIR (an -# aien-dev/omega-bridge checkout at om/omega-bridge.lock); without them they exit 3 (NOT_RUN), never PASS. -OMEGA_OMC ?= seed/out/omc -OMEGA_BRIDGE_DIR ?= ../omega-bridge -OM_ENC_DIR = $(OUT_DIR)/om-encoder -OM_ENC_TEST_DEPS = tests/test_omega_codegen_freestanding.c src/omega_blackwell_codegen.h src/omega_blackwell_matmul.h -OM_ENC_SRCS = src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c -OM_ENC_BUILD = gcc -std=gnu11 -O2 -Wall -Wextra -Werror -pthread -Isrc -# The mutant bindings keep the other units, so sha256_* (src/omega_api_decl.h) still resolves; only the encoder changes. -OM_ENC_OTHER_UNITS = om/sha256/sha256-om2.om om/blake3/b3unit.om - -.PHONY: test-om-encoder test-om-encoder-corpus test-om-encoder-mutants -$(OM_ENC_DIR)/codegen_om: $(OM_ENC_TEST_DEPS) $(OM_ENC_SRCS) src/omega_om_units.c src/omega_native.h - @mkdir -p $(OM_ENC_DIR) - $(OM_ENC_BUILD) -o $@ tests/test_omega_codegen_freestanding.c $(OM_ENC_SRCS) src/omega_om_units.c -$(OM_ENC_DIR)/codegen_diff: $(OM_ENC_TEST_DEPS) $(OM_ENC_SRCS) src/omega_om_units.c src/omega_native.h - @mkdir -p $(OM_ENC_DIR) - $(OM_ENC_BUILD) -DCUDAPP_MIGRATION_PENDING_ENCODER_DIFF -o $@ tests/test_omega_codegen_freestanding.c \ - $(OM_ENC_SRCS) src/omega_om_units.c -$(OM_ENC_DIR)/codegen_diff_red: $(OM_ENC_TEST_DEPS) $(OM_ENC_SRCS) src/omega_om_units.c src/omega_native.h - @mkdir -p $(OM_ENC_DIR) - $(OM_ENC_BUILD) -DCUDAPP_MIGRATION_PENDING_ENCODER_DIFF -DCUDAPP_ENCODER_DIFF_SELFTEST -o $@ \ - tests/test_omega_codegen_freestanding.c $(OM_ENC_SRCS) src/omega_om_units.c - -test-om-encoder: $(OM_ENC_DIR)/codegen_om $(OM_ENC_DIR)/codegen_diff $(OM_ENC_DIR)/codegen_diff_red - $(OM_ENC_DIR)/codegen_om --golden - rm -f $(OM_ENC_DIR)/diff.log - CUDAPP_ENCODER_DIFF_LOG=$(OM_ENC_DIR)/diff.log $(OM_ENC_DIR)/codegen_diff --golden - CUDAPP_ENCODER_DIFF_LOG=$(OM_ENC_DIR)/diff.log $(OM_ENC_DIR)/codegen_diff --dump > $(OM_ENC_DIR)/dump_diff.txt - @same=$$(grep -c ' SAME$$' $(OM_ENC_DIR)/diff.log); other=$$(grep -vc ' SAME$$' $(OM_ENC_DIR)/diff.log); \ - if [ "$$same" -eq 0 ] || [ "$$other" -ne 0 ]; then echo "FAIL encoder diff: $$same SAME, $$other other lines"; exit 1; fi; \ - echo "encoder diff: .om and C byte-identical on $$(grep -c '^insn ' $(OM_ENC_DIR)/diff.log) golden instructions and $$(grep -c '^program ' $(OM_ENC_DIR)/diff.log) fixture programs" - @if CUDAPP_ENCODER_DIFF_LOG=$(OM_ENC_DIR)/diff_red.log $(OM_ENC_DIR)/codegen_diff_red --dump > /dev/null 2>&1; then \ - echo "RED CHECK BROKEN: a flipped bit passed the encoder diff"; exit 1; \ - else echo "red check: one flipped bit aborts the encoder diff, as it must"; fi - -test-om-encoder-corpus: - $(MAKE) OUT_DIR=$(OUT_DIR) CUDAPP_ENCODER=om sm121dis-corpus-bins - $(MAKE) OUT_DIR=$(OUT_DIR)-enc-c CUDAPP_ENCODER=c sm121dis-corpus-bins - $(MAKE) OUT_DIR=$(OUT_DIR)-enc-diff CUDAPP_ENCODER=diff sm121dis-corpus-bins - rm -rf $(OM_ENC_DIR)/k-om $(OM_ENC_DIR)/k-c $(OM_ENC_DIR)/k-diff $(OM_ENC_DIR)/corpus-diff.log - @mkdir -p $(OM_ENC_DIR) - sh tools/sm121dis/corpus.sh $(OUT_DIR) $(OM_ENC_DIR)/k-om - sh tools/sm121dis/corpus.sh $(OUT_DIR)-enc-c $(OM_ENC_DIR)/k-c - CUDAPP_ENCODER_DIFF_LOG=$(abspath $(OM_ENC_DIR))/corpus-diff.log sh tools/sm121dis/corpus.sh $(OUT_DIR)-enc-diff $(OM_ENC_DIR)/k-diff - diff -r $(OM_ENC_DIR)/k-om $(OM_ENC_DIR)/k-c - diff -r $(OM_ENC_DIR)/k-om $(OM_ENC_DIR)/k-diff - @if grep -v ' SAME$$' $(OM_ENC_DIR)/corpus-diff.log; then echo "FAIL corpus encoder diff"; exit 1; fi - @echo "encoder corpus: $$(ls $(OM_ENC_DIR)/k-om/*.bin | grep -vc '/num_') distinct codegen kernels identical .om vs C (plus $$(ls $(OM_ENC_DIR)/k-om/num_*.bin | wc -l) numeric-encoder kernels); diff build $$(grep -c '^program ' $(OM_ENC_DIR)/corpus-diff.log) program encodes and $$(grep -c '^insn ' $(OM_ENC_DIR)/corpus-diff.log) single-instruction encodes, all SAME" - -# Each mutant is one edit of the .om source, compiled by the pinned omc into its own binding; the hosted -# fixture test linked with it must fail the golden words or differ from the C-encoded freestanding dump. -OM_ENC_MUTANTS = 's/^ret or base shl rb o 1 16$$/ret or base shl rb o 1 17/' \ - 's/^p = 262144$$/p = 0/' \ - 's/^const NOPC ulong 1032192$$/const NOPC ulong 1032193/' -test-om-encoder-mutants: build/test_codegen_freestanding - @[ -x $(OMEGA_OMC) ] && [ -f $(OMEGA_BRIDGE_DIR)/src/native.om ] || { echo "NOT_RUN: set OMEGA_OMC and OMEGA_BRIDGE_DIR"; exit 3; } - @mkdir -p $(OM_ENC_DIR) - ./build/test_codegen_freestanding --dump > $(OM_ENC_DIR)/c-dump.txt - @n=0; for m in $(OM_ENC_MUTANTS); do n=$$((n+1)); d=$(OM_ENC_DIR)/mutant$$n; rm -rf $$d; mkdir -p $$d; \ - sed "$$m" om/encoder/bw_enc_sm121.om > $$d/bw_enc_sm121.om; \ - if cmp -s $$d/bw_enc_sm121.om om/encoder/bw_enc_sm121.om; then echo "MUTANT $$n BROKEN: '$$m' changed nothing"; exit 1; fi; \ - OMEGA_UNITS="$(OM_ENC_OTHER_UNITS) $$(pwd)/$$d/bw_enc_sm121.om" OMEGA_UNITS_DEST=$$d OMEGA_OMC=$(abspath $(OMEGA_OMC)) \ - OMEGA_BRIDGE=$(OMEGA_BRIDGE_DIR) sh om/units.sh > /dev/null || exit 1; \ - $(OM_ENC_BUILD) -o $$d/codegen tests/test_omega_codegen_freestanding.c $(OM_ENC_SRCS) $$d/omega_om_units.c || exit 1; \ - g=0; $$d/codegen --golden > $$d/golden.log 2>&1 || g=1; \ - c=0; $$d/codegen --dump > $$d/dump.txt 2>&1; cmp -s $$d/dump.txt $(OM_ENC_DIR)/c-dump.txt || c=1; \ - if [ $$g = 0 ] && [ $$c = 0 ]; then echo "MUTANT $$n SURVIVED: '$$m'"; exit 1; fi; \ - echo "mutant $$n red ('$$m'): golden words $$( [ $$g = 1 ] && echo FAIL || echo pass ), dump vs C $$( [ $$c = 1 ] && echo DIFFERS || echo same )"; \ - done diff --git a/mk/omega-gpu-code-alloc.mk b/mk/omega-gpu-code-alloc.mk index 3b217c32d..0de14ea51 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: $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/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 $(CUDAPP_SOURCE)/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 f3f5dd632..5a647fd4e 100644 --- a/mk/omega-gpu-engine.mk +++ b/mk/omega-gpu-engine.mk @@ -3,46 +3,41 @@ # part of `all` or `test`. # test-gpu-engine-compile header + core compile, enum names, refusals, no-op backend (A2/A3a) # test-gpu-engine the engine core against a fake backend (every state and failure) -# test-gpu-engine-backend-compile syntax-checks src/omega_blackwell_engine.c (A3b1): -c only, no link, no device +# test-gpu-engine-backend-compile syntax-checks $(CUDAPP_SOURCE)/src/omega_blackwell_engine.c (A3b1): -c only, no link, no device # test-gpu-engine-prod-build production build of build/omegatool at the physics pin: links only, opens no device -# test-gpu-engine-mutants removes each protection from src/omega_gpu_engine.c in a scratch +# test-gpu-engine-mutants removes each protection from $(CUDAPP_SOURCE)/src/omega_gpu_engine.c in a scratch # copy; the host test must fail each one (exit nonzero on a survivor) # test-gpu-engine-sim (A3b2) the REAL engine core + Blackwell backend + vector wrapper against a simulated driver -# (tests/fake_m16_native.c); host only, no device, no physics C sources +# ($(CUDAPP_SOURCE)/tests/fake_m16_native.c); host only, no device, no physics C sources # test-gpu-engine-backend-mutants (A3b2) one mutant per protection in the backend and the vector wrapper -# test-gpu-engine-gb10-compile (A3b2) compile-only check of tests/test_omega_gpu_engine_gb10.c (Phase B chip test, never run here) +# test-gpu-engine-gb10-compile (A3b2) compile-only check of $(CUDAPP_SOURCE)/tests/test_omega_gpu_engine_gb10.c (Phase B chip test, never run here) # gpu-engine-freestanding (native v1 P07 cut A) the portable GPU files built -ffreestanding with # OMEGA_GPU_NO_POSIX: no Linux header, no errno, no clock, no libc beyond mem*/str* # test-codegen-freestanding (cut A.2) codegen hosted vs freestanding byte-identical, bounded code buffers # test-gpu-engine-freestanding the engine contract test and the platform contract test linked against # those freestanding objects (host runner, opens no device) .PHONY: test-gpu-engine-compile test-gpu-engine test-gpu-engine-mutants test-gpu-engine-backend-compile test-gpu-engine-prod-build test-gpu-engine-sim test-gpu-engine-backend-mutants test-gpu-engine-gb10-compile gpu-engine-freestanding test-gpu-engine-freestanding -build/test_omega_gpu_engine_compile: tests/test_omega_gpu_engine_compile.c src/omega_gpu_engine.c src/omega_gpu_engine.h +build/test_omega_gpu_engine_compile: $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/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: $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/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. @@ -50,19 +45,17 @@ test-gpu-engine-prod-build: $(MAKE) build/omegatool # A3b2: simulated-driver host test. Links the sources of the Makefile RX_COMPOSE_GPU_SRCS list (plus the -# three core files the vector builder needs) with tests/fake_m16_native.c in place of the physics +# three core files the vector builder needs) with $(CUDAPP_SOURCE)/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 +build/test_omega_blackwell_engine: $(CUDAPP_SOURCE)/tests/test_omega_blackwell_engine.c $(CUDAPP_SOURCE)/tests/fake_m16_native.c $(CUDAPP_SOURCE)/tests/fake_m16_native.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 + -Isrc -I$(CUDAPP_SOURCE)/tests -Itests $(GPU_ENGINE_PHYS_INC) -o $@ $(CUDAPP_SOURCE)/tests/test_omega_blackwell_engine.c $(CUDAPP_SOURCE)/tests/fake_m16_native.c \ + $(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,21 +64,19 @@ 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: $(CUDAPP_SOURCE)/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 + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -fno-fast-math -pthread -Isrc $(GPU_ENGINE_PHYS_INC) -c -o $@ $(CUDAPP_SOURCE)/tests/test_omega_gpu_engine_gb10.c test-gpu-engine-gb10-compile: build/test_omega_gpu_engine_gb10.o # Measurement (sc#277): driver allocations and frees made by the REAL session + matmul + attention # APIs while serving a Qwen3-4B-shaped sequence, against the simulated driver. Host only, no device. # Prints MEASURE lines; asserts only bookkeeping. Links no physics C sources, only its headers. -GPU_SERVE_ALLOC_SRCS = src/omega_gpu_session.c src/omega_gpu_platform.c src/omega_gpu_platform_linux.c src/omega_gpu_fmt.c src/omega_gpu_matmul_api.c src/omega_gpu_attention_api.c src/omega_gpu_serving.c \ - src/omega_gpu_wait.c src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \ - src/omega_blackwell_matmul.c src/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: $(CUDAPP_SOURCE)/tests/gpu_serving_alloc_count_test.c $(CUDAPP_SOURCE)/tests/fake_m16_native.c $(CUDAPP_SOURCE)/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 + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -pthread -ffp-contract=off -Isrc -I$(CUDAPP_SOURCE)/tests -Itests $(GPU_ENGINE_PHYS_INC) \ + -o $@ $(CUDAPP_SOURCE)/tests/gpu_serving_alloc_count_test.c $(CUDAPP_SOURCE)/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,26 +103,30 @@ 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 +# ($(CUDAPP_SOURCE)/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). # SHA-256 here is the migration-pending C of src/omega_sha256_fs.c, not the Omega unit: the omega-bridge binding in # src/omega_om_units.c needs pthread, mmap, mprotect and abort (outside GPU_FS_ALLOWED). test-sha256-fs-parity # holds the two equal; successor: a freestanding bridge binding with a caller-supplied stack. -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_sha256_fs.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_sha256_fs.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_sha256_fs.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_sha256_fs.o: src/omega_sha256_fs.c src/sha256.h $(GPU_FS_HDRS) | check-cudapp @mkdir -p $(GPU_FS_DIR) gcc $(GPU_FS_CFLAGS) -c -o $@ $< @@ -142,13 +137,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: $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/tests/test_omega_gpu_engine.c $(GPU_FS_LINK) +build/test_omega_gpu_platform: $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/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 @@ -161,18 +156,18 @@ 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 -# The hosted side encodes through the .om encoder (om/encoder/bw_enc_sm121.om via src/omega_om_units.c), the -# freestanding side through the migration-pending C encoder, so the cmp below is also an .om-vs-C differential. -build/test_codegen_hosted: $(CODEGEN_FS_TEST_DEPS) src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_om_units.c \ - src/omega_native.h +CODEGEN_FS_TEST_DEPS = $(CUDAPP_SOURCE)/tests/test_omega_codegen_freestanding.c $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h $(CUDAPP_SOURCE)/src/omega_blackwell_matmul.h +# The hosted side encodes through CUDApp's canonical .om encoder (om/encoder/bw_enc_sm121.om of the pinned stage, +# bound in libcudapp.a by cudapp_om_units.c; omega_om_units.c carries only SHA-256 and BLAKE3), the freestanding +# side through the migration-pending C encoder, so the cmp below is also an .om-vs-C differential. +build/test_codegen_hosted: $(CODEGEN_FS_TEST_DEPS) src/omega_om_units.c src/omega_native.h $(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 $@ $(CUDAPP_SOURCE)/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_sha256_fs.o + gcc -std=gnu11 -O2 -Wall -Wextra -Werror $(CUDAPP_HEADER_FLAGS) -Isrc -DOMEGA_GPU_NO_POSIX -o $@ $(CUDAPP_SOURCE)/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 @@ -210,7 +205,7 @@ test-sha256-fs-parity: build/test_codegen_hosted echo "control: hosted compile of src/omega_sha256_fs.c refused; hosted codegen test links $$n omega2_sha256_* functions" sed 's/0x428a2f98/0x428a2f99/' src/omega_sha256_fs.c > $(SHA_FS_DIR)/red.c @! cmp -s $(SHA_FS_DIR)/red.c src/omega_sha256_fs.c || { echo "RED MUTANT BROKEN: sed changed nothing"; exit 1; } - gcc $(GPU_FS_CFLAGS) $(SHA_FS_RENAME) -c -o $(SHA_FS_DIR)/red.o $(SHA_FS_DIR)/red.c + gcc $(GPU_FS_CFLAGS) -iquote src $(SHA_FS_RENAME) -c -o $(SHA_FS_DIR)/red.o $(SHA_FS_DIR)/red.c gcc -std=gnu11 -O2 -Wall -Wextra -Werror -pthread -Isrc -o $(SHA_FS_DIR)/parity_red tests/test_sha256_fs_parity.c \ $(SHA_FS_DIR)/red.o src/omega_om_units.c @if ./$(SHA_FS_DIR)/parity_red > $(SHA_FS_DIR)/red.log; then echo "RED CHECK BROKEN: a wrong round constant passed"; exit 1; \ @@ -225,19 +220,14 @@ test-sha256-fs-parity: build/test_codegen_hosted # - 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: $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/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: $(CUDAPP_SOURCE)/tests/test_omega_gpu_platform_linux.c $(CUDAPP_SOURCE)/tests/fake_m16_native.c $(CUDAPP_SOURCE)/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 + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -pthread -Isrc -I$(CUDAPP_SOURCE)/tests -Itests $(GPU_ENGINE_PHYS_INC) \ + -o $@ $(CUDAPP_SOURCE)/tests/test_omega_gpu_platform_linux.c $(CUDAPP_SOURCE)/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 @@ -247,12 +237,12 @@ 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 \ - tests/test_omega_gpu_session_platform.c $$objs $(GPU_SESSION_MUT_DIR)/$$name.o; \ + gcc -std=gnu11 -O2 -Wall -Wextra -Werror $(CUDAPP_HEADER_FLAGS) -Isrc -DOMEGA_GPU_NO_POSIX -o $(GPU_SESSION_MUT_DIR)/$$name \ + $(CUDAPP_SOURCE)/tests/test_omega_gpu_session_platform.c $$objs $(GPU_SESSION_MUT_DIR)/$$name.o; \ if ./$(GPU_SESSION_MUT_DIR)/$$name > $(GPU_SESSION_MUT_DIR)/$$name.log 2>&1; then echo "mutant $$name SURVIVED"; exit 1; fi; \ echo "mutant $$name killed: $$(grep -c '^FAIL' $(GPU_SESSION_MUT_DIR)/$$name.log) case(s) failed"; killed=$$((killed+1)); }; \ smut release-when-latched 's|if (LOAD(g_blocked)) {$$|if (0) {|'; \ diff --git a/mk/omega-gpu-wait.mk b/mk/omega-gpu-wait.mk index 42e5ed25b..237dc0e8b 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: $(CUDAPP_SOURCE)/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 $@ $(CUDAPP_SOURCE)/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 $(CUDAPP_SOURCE)/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/omega-mufu-ftz.mk b/mk/omega-mufu-ftz.mk index 00ebb48d3..8c31fe1e5 100644 --- a/mk/omega-mufu-ftz.mk +++ b/mk/omega-mufu-ftz.mk @@ -1,18 +1,18 @@ # MUFU flush rule (omega #462): the GB10 MUFU unit (EX2 / RCP / RSQ) flushes a subnormal input or result to a -# sign-preserving zero. tests/bw_mufu_ftz.h is the one host model of it; every warp simulator and SwiGLU host reference +# sign-preserving zero. $(CUDAPP_SOURCE)/tests/bw_mufu_ftz.h is the one host model of it; every warp simulator and SwiGLU host reference # routes through it. test-mufu-ftz runs the helper unit test, then one MUFU instruction through each simulator's # ws_lane_exec (bw_warp_sim.h, _k, _pa, _tc). Picked up by `-include mk/*.mk`. Host only: opens no device, needs no # physics headers, takes no chip lock. The attention test's own per-thread simulator is checked by # `gpu_attention_test --host-only` (test-gpu-attention). MUFU_FTZ_SIMS := bw_warp_sim bw_warp_sim_k bw_warp_sim_pa bw_warp_sim_tc -MUFU_FTZ_CFLAGS := -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -Isrc -Itests +MUFU_FTZ_CFLAGS := -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -Isrc -I$(CUDAPP_SOURCE)/tests -Itests .PHONY: test-mufu-ftz -$(OUT_DIR)/test_mufu_ftz_helper: tests/bw_mufu_ftz_test.c tests/bw_mufu_ftz.h +$(OUT_DIR)/test_mufu_ftz_helper: $(CUDAPP_SOURCE)/tests/bw_mufu_ftz_test.c $(CUDAPP_SOURCE)/tests/bw_mufu_ftz.h @mkdir -p $(OUT_DIR) - gcc $(MUFU_FTZ_CFLAGS) -o $@ tests/bw_mufu_ftz_test.c -lm -$(OUT_DIR)/test_mufu_ftz_%: tests/bw_mufu_ftz_test.c tests/bw_mufu_ftz.h tests/%.h tests/bw_hmma_model.h tests/bw_qmma_model.h src/omega_blackwell_codegen.h + gcc $(MUFU_FTZ_CFLAGS) -o $@ $(CUDAPP_SOURCE)/tests/bw_mufu_ftz_test.c -lm +$(OUT_DIR)/test_mufu_ftz_%: $(CUDAPP_SOURCE)/tests/bw_mufu_ftz_test.c $(CUDAPP_SOURCE)/tests/bw_mufu_ftz.h tests/%.h $(CUDAPP_SOURCE)/tests/bw_hmma_model.h $(CUDAPP_SOURCE)/tests/bw_qmma_model.h $(CUDAPP_SOURCE)/src/omega_blackwell_codegen.h @mkdir -p $(OUT_DIR) - gcc $(MUFU_FTZ_CFLAGS) -DWS_SIM_HDR='"$*.h"' -o $@ tests/bw_mufu_ftz_test.c -lm + gcc $(MUFU_FTZ_CFLAGS) -DWS_SIM_HDR='"$*.h"' -o $@ $(CUDAPP_SOURCE)/tests/bw_mufu_ftz_test.c -lm test-mufu-ftz: $(OUT_DIR)/test_mufu_ftz_helper $(addprefix $(OUT_DIR)/test_mufu_ftz_,$(MUFU_FTZ_SIMS)) $(OUT_DIR)/test_mufu_ftz_helper @for s in $(MUFU_FTZ_SIMS); do $(OUT_DIR)/test_mufu_ftz_$$s || exit 1; done diff --git a/mk/prime_race_gb10.mk b/mk/prime_race_gb10.mk index 67634702a..9fcf65520 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 $(CUDAPP_SOURCE)/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) -I$(CUDAPP_SOURCE)/tests -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/runtime-r1.mk b/mk/runtime-r1.mk index a6cc401cf..b95d43e57 100644 --- a/mk/runtime-r1.mk +++ b/mk/runtime-r1.mk @@ -1,9 +1,11 @@ # Omega runtime R1 (omega-mv#594): the Runtime API manifest checked against the headers. Host only, no GPU, no physics checkout. # Picked up by `-include mk/*.mk` at the top of the Makefile, so no extra include line is needed. -RUNTIME_API_MANIFEST ?= docs/runtime/omega_runtime_api.manifest -RUNTIME_API_MD ?= docs/runtime/API.md +# The Runtime API headers, manifest, API.md and both checkers are CUDApp's: the staged source of the exact revision in +# cudapp.lock ($(CUDAPP_SOURCE), check-cudapp). Without a stage the target fails; it never falls back to a local copy. +RUNTIME_API_MANIFEST ?= $(CUDAPP_SOURCE)/docs/runtime/omega_runtime_api.manifest +RUNTIME_API_MD ?= $(CUDAPP_SOURCE)/docs/runtime/API.md RUNTIME_API_WORK ?= $(OUT_DIR)/runtime-api .PHONY: test-runtime-api -test-runtime-api: - CC="$(CC)" tools/runtime_api_check.sh $(RUNTIME_API_MANIFEST) . $(RUNTIME_API_WORK)/real $(RUNTIME_API_MD) - CC="$(CC)" tools/runtime_api_negative.sh $(RUNTIME_API_MANIFEST) . $(RUNTIME_API_WORK) $(RUNTIME_API_MD) +test-runtime-api: | check-cudapp + CC="$(CC)" sh $(CUDAPP_SOURCE)/tools/runtime_api_check.sh $(RUNTIME_API_MANIFEST) $(CUDAPP_SOURCE) $(RUNTIME_API_WORK)/real $(RUNTIME_API_MD) + CC="$(CC)" sh $(CUDAPP_SOURCE)/tools/runtime_api_negative.sh $(RUNTIME_API_MANIFEST) $(CUDAPP_SOURCE) $(RUNTIME_API_WORK) $(RUNTIME_API_MD) diff --git a/mk/runtime-r3.mk b/mk/runtime-r3.mk index 9c541fbb2..d37d7bf05 100644 --- a/mk/runtime-r3.mk +++ b/mk/runtime-r3.mk @@ -1,14 +1,22 @@ -# Omega runtime R3 (omega-mv#596): the portability table (docs/runtime/portability_table.tsv) must match src/. +# Omega runtime R3 (omega-mv#596): the portability table must match the source tree. # Picked up by `-include mk/*.mk`. Host only: no compiler, no device, no physics headers. -# test-runtime-portability-check every src/omega_gpu_*, omega_blackwell_*, omega_bw_* file has a row, every row names a -# file, a PORTABLE row's file includes no Linux/NVRM or Blackwell header, and the -# os_binding column agrees with the include scan and the freestanding file list -# test-runtime-portability-controls breaks one thing at a time in scratch copies; the check must FAIL each (and PASS the -# guarded-include control) +# The GPU sources, their table (docs/runtime/portability_table.tsv), the freestanding list (mk/omega-gpu-engine.mk) and +# both scripts are CUDApp's: the staged source of the exact revision in cudapp.lock ($(CUDAPP_SOURCE), check-cudapp). +# Omega's own docs/runtime/portability_table.tsv holds only the rows of the GPU-named files Omega still carries +# (src/omega_blackwell_gates.*), checked by the same canonical script against this tree and this mk/omega-gpu-engine.mk. +# test-runtime-portability-check the canonical tree against the canonical table, then Omega's tree against Omega's +# table: every src/omega_gpu_*, omega_blackwell_*, omega_bw_* file has a row, every +# row names a file, a PORTABLE row's file includes no Linux/NVRM or Blackwell header, +# and the os_binding column agrees with the include scan and the freestanding list +# test-runtime-portability-controls breaks one thing at a time in scratch copies of the canonical tree; the check must +# FAIL each (and PASS the guarded-include control) # test-runtime-portability both .PHONY: test-runtime-portability test-runtime-portability-check test-runtime-portability-controls -test-runtime-portability-check: - sh tools/runtime_portability_check.sh . docs/runtime/portability_table.tsv mk/omega-gpu-engine.mk -test-runtime-portability-controls: - sh tools/runtime_portability_controls.sh build/runtime_r3_controls docs/runtime/portability_table.tsv mk/omega-gpu-engine.mk +test-runtime-portability-check: | check-cudapp + sh $(CUDAPP_SOURCE)/tools/runtime_portability_check.sh $(CUDAPP_SOURCE) $(CUDAPP_SOURCE)/docs/runtime/portability_table.tsv \ + $(CUDAPP_SOURCE)/mk/omega-gpu-engine.mk + sh $(CUDAPP_SOURCE)/tools/runtime_portability_check.sh . docs/runtime/portability_table.tsv mk/omega-gpu-engine.mk +test-runtime-portability-controls: | check-cudapp + cd $(CUDAPP_SOURCE) && sh tools/runtime_portability_controls.sh $(abspath $(OUT_DIR)/runtime_r3_controls) \ + docs/runtime/portability_table.tsv mk/omega-gpu-engine.mk test-runtime-portability: test-runtime-portability-check test-runtime-portability-controls diff --git a/mk/sm121dis.mk b/mk/sm121dis.mk index c9440caa7..6a8f9cd85 100644 --- a/mk/sm121dis.mk +++ b/mk/sm121dis.mk @@ -1,4 +1,4 @@ -# C6 of docs/OMEGA.md: Omega's own sm_121 disassembler (src/omega_sm121_disasm.c, tools/sm121dis/). +# C6 of docs/OMEGA.md: Omega's own sm_121 disassembler ($(CUDAPP_SOURCE)/src/omega_sm121_disasm.c, tools/sm121dis/). # make test-sm121dis collect every kernel the library builds (no GPU), compare our text with nvdisasm's, word by word; # then the red check: a decoder built with one deliberate fault must FAIL the same comparison. # Picked up by the `-include mk/*.mk` line of the Makefile. The test binaries are named as files, not through the @@ -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 \ @@ -40,9 +40,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/om/encoder/bw_enc_sm121.om b/om/encoder/bw_enc_sm121.om deleted file mode 100644 index 4c17bec4a..000000000 --- a/om/encoder/bw_enc_sm121.om +++ /dev/null @@ -1,515 +0,0 @@ -note bw_enc_sm121.om: the sm_121 instruction encoder of CUDApp (aien-dev/CUDApp#79, OM-GPU-RETIRE). -note It turns a solved BlackwellIR program into machine code: four 32-bit words per instruction, -note little-endian, padded with NOPs to a multiple of 8 and at least 32 instructions. -note It replaces encode_single_insn and omega_bw_encode_program of src/omega_blackwell_codegen.c, -note which stays compiled only behind CUDAPP_MIGRATION_PENDING_C_ENCODER as the differential oracle -note (and in the freestanding build, which has no native binding yet). -note -note Input (bw_om_encode in src/omega_blackwell_codegen.c packs it; 8 ulong per instruction, at most 1024 instructions): -note 0 op (the BlackwellIROpcode number) 1 dst_vreg 2 src1_vreg 3 src2_vreg 4 src3_vreg -note 5 ureg (the five vreg fields are C int, passed as 64-bit two's complement: negative = none) -note 6 imm or control shl 32 -note 7 is_uniform or predicate_p0 shl 1 or predicate_not shl 2 or bar_reg shl 8 -note or dst_subreg shl 16 or src1_subreg shl 24 or src2_subreg shl 32 or src3_subreg shl 40 -note phys: vreg_to_phys 0..255 then uvreg_to_phys at 256..287 (C int, two's complement). -note pad 1: omega_bw_encode_program (pad to the multiple of 8, at least 32); pad 0: exactly n instructions. -note Result: the bytes written, or 0 when an instruction is refused (unknown op, an offset outside its -note field, a BSSY delta below 2, a barrier register above 15) or n is above 1024. -note Every constant is the decimal form of the C encoder's hex word (conversions by Wolfram, -note evidence/CUDAPP-OM-ENCODER/wolfram-constants.txt). - -const NEG ulong 9223372036854775808 -const NOPW ulong 31000 -const NOPC ulong 1032192 - -fn put4 w edit ulong 4 a ulong b ulong c ulong d ulong to void -put w 0 a -put w 1 b -put w 2 c -put w 3 d -end - -note the physical register of one operand field: phys + subreg, or dflt when the vreg is negative -fn preg phys view ulong 288 v ulong sb ulong dflt ulong to ulong -if ge v NEG -ret dflt -end -ret add get phys v sb -end - -note 1 when a vreg field is given (not negative), else 0 -fn pres v ulong to ulong -if ge v NEG -ret 0 -end -ret 1 -end - -fn opnds ins view ulong 8192 i ulong phys view ulong 288 o edit ulong 16 to void -b = mul i 8 -f = get ins add b 7 -put o 0 get ins b -put o 1 preg phys get ins add b 1 and shr f 16 255 0 -put o 2 preg phys get ins add b 2 and shr f 24 255 0 -put o 3 preg phys get ins add b 3 and shr f 32 255 0 -put o 4 preg phys get ins add b 4 and shr f 40 255 255 -u = get ins add b 5 -put o 5 0 -if lt u NEG -put o 5 get phys add u 256 -end -put o 14 pres u -x = get ins add b 6 -put o 6 and x 4294967295 -put o 7 shr x 32 -put o 8 and f 1 -put o 9 and shr f 1 1 -put o 10 and shr f 2 1 -put o 11 and shr f 8 255 -put o 12 pres get ins add b 2 -put o 13 pres get ins add b 3 -d = get ins add b 1 -if and eq and f 1 1 lt d NEG -put o 1 get phys add d 256 -end -end - -note the control word: the instruction's own, else the op's default -fn ctl o view ulong 16 dflt ulong to ulong -c = get o 7 -if ne c 0 -ret c -end -ret dflt -end - -note low 8 bits of operand slot k -fn rb o view ulong 16 k ulong to ulong -ret and get o k 255 -end - -note slot k when its vreg (presence slot h) is given, else RZ -fn rz o view ulong 16 k ulong h ulong to ulong -if ne get o h 0 -ret rb o k -end -ret 255 -end - -fn wd o view ulong 16 base ulong to ulong -ret or base shl rb o 1 16 -end - -fn wa o view ulong 16 base ulong to ulong -ret or base shl rb o 2 24 -end - -fn wda o view ulong 16 base ulong to ulong -ret or wd o base shl rb o 2 24 -end - -note the 4-bit guard predicate field: 7 always, 0 @P0, 8 @!P0 -fn pred o view ulong 16 to ulong -if eq get o 9 0 -ret 7 -end -if eq get o 10 0 -ret 0 -end -ret 8 -end - -note a signed 24-bit byte offset (imm read as int32) fits -fn off24 imm ulong to bool -ret or lt imm 8388608 ge imm 4286578688 -end - -note ops 0..14: moves, constants, integer multiply-add, compares and global memory -fn enc_a o view ulong 16 w edit ulong 4 to ulong -op = get o 0 -imm = get o 6 -if eq op 0 -put4 w NOPW 0 0 ctl o NOPC -ret 0 -end -if eq op 1 -put4 w wd o 29186 255 3840 ctl o 1040896 -ret 0 -end -if eq op 2 -put4 w wd o 30722 imm 3840 ctl o 1040896 -ret 0 -end -if eq op 3 -put4 w wd o 31001 0 shl and imm 255 8 ctl o 926208 -ret 0 -end -if eq op 4 -put4 w wd o 4278221698 and shl imm 6 16776960 2048 ctl o 1040896 -ret 0 -end -if eq op 5 -put4 w wd o 4278221698 and shl imm 6 16776960 2560 ctl o 926208 -ret 0 -end -if eq op 6 -put4 w wd o 4278220716 and shl imm 5 16776960 134219776 ctl o 926208 -ret 0 -end -if eq op 7 -put4 w wd o 4278220716 and shl imm 5 16776960 134220288 ctl o 945664 -ret 0 -end -if eq op 8 -if ne get o 13 0 -put4 w wda o 29220 rb o 3 or 126747136 rb o 4 ctl o 2083328 -ret 0 -end -if and ne get o 8 0 ne get o 14 0 -put4 w wda o 31780 rb o 5 or 260964864 rb o 4 ctl o 2083328 -ret 0 -end -put4 w wda o 30756 imm or 126747136 rb o 4 ctl o 2083328 -ret 0 -end -if eq op 9 -put4 w wda o 30757 imm or 126746624 rb o 4 ctl o 2083840 -ret 0 -end -if eq op 10 -if and ne get o 8 0 ne get o 14 0 -put4 w wda o 31756 rb o 5 200302704 ctl o 3136000 -ret 0 -end -put4 w wda o 30732 imm 66085488 ctl o 2087424 -ret 0 -end -if eq op 11 -put4 w wda o 31105 rb o 5 203299072 ctl o 991744 -ret 0 -end -if eq op 12 -if not off24 imm -ret 1 -end -put4 w wa o 31110 or rb o 3 shl and imm 16777215 8 or 202381568 rb o 5 ctl o 1040896 -ret 0 -end -if eq op 13 -put4 w wa o 31110 rb o 3 or 202447104 rb o 5 ctl o 1040896 -ret 0 -end -if eq op 14 -put4 w wda o 29200 rb o 3 134209791 ctl o 17811968 -ret 0 -end -ret 1 -end - -note ops 15..29: tensor core, shifts, wide and strong loads, stores, fences, atomics -fn enc_b o view ulong 16 w edit ulong 4 to ulong -op = get o 0 -imm = get o 6 -if or eq op 15 eq op 16 -p = ulong 0 -if eq op 16 -p = 262144 -end -put4 w wda o 29244 rb o 3 or or rb o 4 6144 p ctl o 1040896 -ret 0 -end -if eq op 17 -put4 w or wd o 30745 4278190080 imm or 71168 rb o 2 ctl o 2083328 -ret 0 -end -if eq op 18 -put4 w wda o 30738 imm 126796031 ctl o 2083328 -ret 0 -end -if eq op 19 -put4 w wda o 31105 rb o 5 203298048 ctl o 991744 -ret 0 -end -if eq op 20 -put4 w wda o 31105 rb o 5 203380992 ctl o 991744 -ret 0 -end -if eq op 21 -put4 w wda o 31105 rb o 5 202250496 ctl o 991744 -ret 0 -end -if eq op 22 -a = wa o 31110 -if ne get o 9 0 -a = or wa o 2438 shl pred o 12 -end -put4 w a rb o 3 or 202463488 rb o 5 ctl o 1040896 -ret 0 -end -if eq op 23 -put4 w 31122 0 45056 ctl o 1043456 -ret 0 -end -if eq op 24 -put4 w 31122 0 12288 ctl o 1043456 -ret 0 -end -if eq op 25 -put4 w 4278221199 0 33554432 ctl o 1042432 -ret 0 -end -if eq op 26 -put4 w wda o 31144 or rb o 3 2147483648 or 136270080 rb o 5 ctl o 3284480 -ret 0 -end -if eq op 27 -put4 w wda o 31144 or rb o 3 2147483648 or 203378944 rb o 5 ctl o 3284480 -ret 0 -end -if eq op 28 -put4 w wa o 29196 rb o 3 66084976 ctl o 2087424 -ret 0 -end -if eq op 29 -put4 w wda o 29202 rb o 3 126762239 ctl o 2083328 -ret 0 -end -ret 1 -end - -note ops 30..45: floating point, special functions, shuffles, shared memory, exit -fn enc_c o view ulong 16 w edit ulong 4 to ulong -op = get o 0 -imm = get o 6 -if eq op 30 -put4 w wda o 29217 rb o 3 0 ctl o 5227520 -ret 0 -end -if eq op 31 -put4 w wda o 29217 or rb o 3 2147483648 0 ctl o 5227520 -ret 0 -end -if eq op 32 -put4 w wda o 29216 rb o 3 4194304 ctl o 5227520 -ret 0 -end -if eq op 33 -put4 w wda o 29219 rb o 3 rb o 4 ctl o 5227520 -ret 0 -end -if eq op 34 -c = ulong 66084864 -if ne imm 0 -c = imm -end -a = or or 29195 shl and get o 1 7 16 shl rb o 2 24 -put4 w a rb o 3 c ctl o 5227520 -ret 0 -end -if eq op 35 -put4 w wda o 29192 rb o 3 and get o 4 7 ctl o 1034752 -ret 0 -end -if eq op 36 -put4 w wda o 29193 rb o 3 58720256 ctl o 5227520 -ret 0 -end -if eq op 37 -put4 w wda o 29193 rb o 3 125829120 ctl o 5227520 -ret 0 -end -if eq op 38 -put4 w wd o 29253 rb o 2 2102272 ctl o 5235200 -ret 0 -end -if eq op 39 -put4 w wd o 29445 rb o 2 2158848 ctl o 5120512 -ret 0 -end -if eq op 40 -put4 w wd o 29448 rb o 2 4096 ctl o 926720 -ret 0 -end -if eq op 41 -put4 w wd o 29448 rb o 2 5120 ctl o 926720 -ret 0 -end -if eq op 42 -put4 w wda o 32649 or 134225664 shl and imm 31 21 917504 ctl o 926720 -ret 0 -end -if eq op 43 -put4 w wda o 31108 0 and imm 65535 ctl o 1040896 -ret 0 -end -if eq op 44 -put4 w wa o 29576 rb o 3 and imm 65535 ctl o 1040896 -ret 0 -end -if eq op 45 -a = ulong 31053 -if ne get o 9 0 -a = 2381 -end -put4 w a 0 58720256 ctl o 1042944 -ret 0 -end -ret 1 -end - -note op 46: BRA. rel = imm - 1 as int32; low 6 bits at w0 18..23, rel arithmetic-shifted by 6 at w1 bit 2 -fn enc_bra o view ulong 16 w edit ulong 4 to ulong -imm = get o 6 -rel = and sub imm 1 4294967295 -s = shr rel 6 -c = ulong 58720256 -if ge rel 2147483648 -s = or s 4227858432 -c = 58982399 -end -d = get o 7 -if eq d 0 -d = 1042944 -if and eq imm 0 eq get o 9 0 -d = NOPC -end -end -a = or or 2375 shl pred o 12 shl and rel 63 18 -put4 w a and shl s 2 4294967295 c d -ret 0 -end - -note ops 46..59: branches, reconvergence, barriers, wide shared loads, three-source integer ops -fn enc_d o view ulong 16 w edit ulong 4 to ulong -op = get o 0 -imm = get o 6 -bar = get o 11 -if eq op 46 -ret enc_bra o w -end -if eq op 47 -put4 w wd o 29448 rb o 2 2048 ctl o 926720 -ret 0 -end -if eq op 48 -put4 w 31517 0 65536 ctl o 1043456 -ret 0 -end -if eq op 49 -put4 w wda o 31108 255 134219776 ctl o 927744 -ret 0 -end -if eq op 50 -put4 w wa o 31112 rb o 3 134220031 ctl o 1040896 -ret 0 -end -if eq op 51 -a = or or 29202 shl rb o 1 16 shl rz o 2 12 24 -put4 w a rz o 3 13 or or 126746624 shl and imm 255 8 rb o 4 ctl o 2083328 -ret 0 -end -if eq op 52 -a = or or 29209 shl rb o 1 16 shl rz o 2 12 24 -put4 w a rz o 3 13 or 1536 rb o 4 ctl o 2083328 -ret 0 -end -if eq op 53 -a = or or 29223 shl rb o 1 16 shl rz o 2 12 24 -put4 w a rz o 3 13 or 126746624 rb o 4 ctl o 2083328 -ret 0 -end -if eq op 54 -if or or lt imm 2 ge imm 2147483648 ge bar 16 -ret 1 -end -a = or or 2373 shl pred o 12 shl bar 16 -put4 w a and mul sub imm 1 16 4294967295 58720768 ctl o 1040896 -ret 0 -end -if eq op 55 -if ge bar 16 -ret 1 -end -a = or or 2369 shl pred o 12 shl bar 16 -put4 w a 0 58720768 ctl o 1042944 -ret 0 -end -if eq op 56 -if not off24 imm -ret 1 -end -put4 w wda o 31105 or rb o 5 shl and imm 16777215 8 203299584 ctl o 991744 -ret 0 -end -if eq op 57 -if not off24 imm -ret 1 -end -put4 w wda o 31105 or rb o 5 shl and imm 16777215 8 203300096 ctl o 991744 -ret 0 -end -if eq op 58 -if ge imm 8388608 -ret 1 -end -put4 w wda o 31108 shl and imm 16777215 8 3072 ctl o 1042432 -ret 0 -end -if eq op 59 -put4 w wd o 29448 rb o 2 3072 ctl o 926720 -ret 0 -end -ret 1 -end - -fn enc1 o view ulong 16 w edit ulong 4 to ulong -op = get o 0 -if lt op 15 -ret enc_a o w -end -if lt op 30 -ret enc_b o w -end -if lt op 46 -ret enc_c o w -end -ret enc_d o w -end - -note the 16 bytes of instruction i, each word little-endian -fn store code edit uchar 16384 i ulong w view ulong 4 to void -for k ulong 4 -x = get w k -q = add mul i 16 mul k 4 -for j ulong 4 -put code add q j uchar and shr x mul j 8 255 -end -end -end - -fn bw_enc_sm121 ins view ulong 8192 phys view ulong 288 n ulong pad ulong code edit uchar 16384 to ulong -o = new ulong 16 0 -w = new ulong 4 0 -if gt n 1024 -ret 0 -end -cnt = n -if ne pad 0 -cnt = mul div add n 7 8 8 -if lt cnt 32 -cnt = 32 -end -end -for i ulong cnt -if lt i n -opnds ins i phys edit o -if ne enc1 view o edit w 0 -ret 0 -end -else -put4 edit w NOPW 0 0 NOPC -end -store code i view w -end -ret mul cnt 16 -end diff --git a/om/units.sh b/om/units.sh index 0129b777e..8aa762ae6 100755 --- a/om/units.sh +++ b/om/units.sh @@ -16,14 +16,13 @@ # unit also embeds its identity (omega2_ident_() in omega_om_units.c). # A unit, compiler or profile that changes without regenerating these files fails --check. # OMEGA_UNITS (the unit list, repo-relative or absolute) and OMEGA_UNITS_DEST (output directory, default src) -# override the defaults; mk/om-encoder.mk uses them to build mutant encoders beside the real binding. +# override the defaults. set -eu OMC_PIN=be8c51301307555254fc59e351d281aae1aa096d91521777e33a41c8b446448a NATIVE_PIN=c77a5922f91d53d4a0bbd4e7b1c4703f7098263abc843be2918db1ece7496782 ROOT=$(cd "$(dirname "$0")/.." && pwd) # One generated library for all units: the bindings share one ABI runtime (ombr_enter). -# om/encoder/bw_enc_sm121.om: the sm_121 instruction encoder, twin of aien-dev/CUDApp's (mk/om-encoder.mk). -UNITS="${OMEGA_UNITS:-om/sha256/sha256-om2.om om/blake3/b3unit.om om/encoder/bw_enc_sm121.om}" +UNITS="${OMEGA_UNITS:-om/sha256/sha256-om2.om om/blake3/b3unit.om}" DEST="${OMEGA_UNITS_DEST:-$ROOT/src}" OUTS="omega_om_units.c omega_native.h omega_api_decl.h omega_om_units.ident" [ -n "${OMEGA_OMC:-}" ] && [ -n "${OMEGA_BRIDGE:-}" ] || { echo "NOT_RUN: set OMEGA_OMC and OMEGA_BRIDGE"; exit 3; } diff --git a/src/.crumb b/src/.crumb index 85650d7f0..b201a270b 100644 --- a/src/.crumb +++ b/src/.crumb @@ -188,14 +188,14 @@ } ], "children_root": "sha256:6ade3e583c9df260fbfc768469dae662b88153725b14f7086431861419cfffe3", - "compiled_at": "2026-10-31T10:16:13Z", + "compiled_at": "2026-10-31T10:53:52Z", "compiler": "crumb-compile/1", - "digest": "sha256:0b45b3b8037fb89222c06563d9cde31caf762b9751994fafa603e1c84d350d91", + "digest": "sha256:0b8df0bac6a60addd4eb8323b0251db5b55b901a9c965d0d12a2e76bfaae661f", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 599, - "generated_at_commit": "7715c4e792abc9d99496d4e1ecfe8bccc79a5c17", - "source_tree": "sha256:efcba46d11640ffaa85dc9c407a9dea9d0cbe2b6cc60319505dfd327b4d852d2" + "files": 468, + "generated_at_commit": "8e6277d4e57cf59698be10b268d8a6243526d2ff", + "source_tree": "sha256:f415b6f50e4ab171fa3c1937b6eb64959bc92f8c74f591e9b9038ad324e03370" }, "owner_lane": "", "provenance": { diff --git a/src/omega_blackwell_codegen.c b/src/omega_blackwell_codegen.c deleted file mode 100644 index a0520f4c9..000000000 --- a/src/omega_blackwell_codegen.c +++ /dev/null @@ -1,2737 +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; -} - -/* ---- sm_121 instruction encoder (aien-dev/CUDApp#79) --------------------------------------------------- - * The hosted build encodes through om/encoder/bw_enc_sm121.om: seeded Omega, compiled by the pinned omc and - * linked through the omega-bridge native binding src/omega_om_units.c (generated by om/units.sh, never edited - * by hand). The C encoder below is migration-pending: it is compiled only - * - in the freestanding build (OMEGA_GPU_NO_POSIX), because the bridge binding needs pthread and mmap and the - * freestanding binding is still a proposal (successor: the same .om unit behind a caller-stack binding); - * - with CUDAPP_MIGRATION_PENDING_C_ENCODER, the differential oracle build (make CUDAPP_ENCODER=c); - * - with CUDAPP_MIGRATION_PENDING_ENCODER_DIFF, which encodes every instruction and program both ways, aborts on - * any byte difference and logs each agreement to $CUDAPP_ENCODER_DIFF_LOG (make CUDAPP_ENCODER=diff). - * Successor of the C body: bw_enc_sm121.om; it is deleted once the freestanding binding lands. */ -#if defined(OMEGA_GPU_NO_POSIX) || defined(CUDAPP_MIGRATION_PENDING_C_ENCODER) -#define BW_ENC_C_PRIMARY 1 -#endif -#if defined(BW_ENC_C_PRIMARY) && defined(CUDAPP_MIGRATION_PENDING_ENCODER_DIFF) -#error "CUDAPP_MIGRATION_PENDING_ENCODER_DIFF needs the .om encoder: not with OMEGA_GPU_NO_POSIX or the C encoder" -#endif -#if defined(BW_ENC_C_PRIMARY) || defined(CUDAPP_MIGRATION_PENDING_ENCODER_DIFF) -static int bw_c_encode_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; -} -#endif /* C encoder, migration-pending */ - -#ifdef BW_ENC_C_PRIMARY -static int encode_single_insn(const BlackwellIRInsn *insn, const OmegaRegAlloc *ra, uint32_t w[4]) { - return bw_c_encode_insn(insn, ra, w); -} -#else -#include "omega_native.h" -/* The .om unit reads the IR as 8 ulongs per instruction and the allocation as one 288-entry table; these are the - * layouts its source documents (om/encoder/bw_enc_sm121.om), so the enum values and sizes are pinned here. */ -#define BW_OM_INS_LEN 8192u /* BW_MAX_IR_INSNS * 8 */ -#define BW_OM_PHYS_LEN 288u /* BW_MAX_VREGS + BW_MAX_UVREGS */ -#define BW_OM_CODE_LEN 16384u /* BW_MAX_IR_INSNS * 16 */ -_Static_assert(BW_MAX_IR_INSNS == 1024 && BW_MAX_VREGS == 256 && BW_MAX_UVREGS == 32, "bw_enc_sm121.om array sizes"); -_Static_assert(BW_IR_NOP == 0 && BW_IR_MOV_RZ == 1 && BW_IR_MOV_IMM == 2 && BW_IR_S2R == 3 && BW_IR_LDC == 4 && - BW_IR_LDC64 == 5 && BW_IR_LDCU == 6 && BW_IR_LDCU64 == 7 && BW_IR_IMAD == 8 && BW_IR_IMAD_WIDE == 9 && - BW_IR_ISETP_GE == 10 && BW_IR_LDG_E == 11 && BW_IR_STG_E == 12 && BW_IR_STG_EF == 13 && - BW_IR_IADD3 == 14 && BW_IR_HMMA_F16 == 15 && BW_IR_HMMA_BF16 == 16 && BW_IR_SHF_R == 17 && - BW_IR_LOP3_AND == 18 && BW_IR_LDG_E_U16 == 19 && BW_IR_LDG_STRONG_SYS == 20 && BW_IR_LDG_MMIO == 21 && - BW_IR_STG_STRONG_SYS == 22 && BW_IR_MEMBAR_ALL_SYS == 23 && BW_IR_MEMBAR_SC_SYS == 24 && - BW_IR_CCTL_IVALL == 25 && BW_IR_ATOMG_ADD_STRONG_SYS == 26 && BW_IR_ATOMG_EXCH_STRONG_SYS == 27 && - BW_IR_ISETP_GE_U32 == 28 && BW_IR_LOP3_XOR == 29, "bw_enc_sm121.om opcode numbers 0-29"); -_Static_assert(BW_IR_FADD == 30 && BW_IR_FSUB == 31 && BW_IR_FMUL == 32 && BW_IR_FFMA == 33 && BW_IR_FSETP == 34 && - BW_IR_FSEL == 35 && BW_IR_FMNMX_MIN == 36 && BW_IR_FMNMX_MAX == 37 && BW_IR_I2FP == 38 && - BW_IR_F2I == 39 && BW_IR_MUFU_RCP == 40 && BW_IR_MUFU_RSQ == 41 && BW_IR_SHFL_DOWN == 42 && - BW_IR_LDS == 43 && BW_IR_STS == 44 && BW_IR_EXIT == 45 && BW_IR_BRA == 46 && BW_IR_MUFU_EX2 == 47 && - BW_IR_BAR_SYNC == 48 && BW_IR_LDS32 == 49 && BW_IR_STS32 == 50 && BW_IR_LOP3_LUT == 51 && - BW_IR_SHF_L_U32 == 52 && BW_IR_IMAD_HI_U32 == 53 && BW_IR_BSSY == 54 && BW_IR_BSYNC == 55 && - BW_IR_LDG_E_64 == 56 && BW_IR_LDG_E_128 == 57 && BW_IR_LDS128 == 58 && BW_IR_MUFU_LG2 == 59, - "bw_enc_sm121.om opcode numbers 30-59"); - -/* Encodes n instructions through the .om unit into code (BW_OM_CODE_LEN bytes). pad != 0 is program mode (NOP - * padding to a multiple of 8, at least 32). Returns the bytes written; 0 = refused. */ -static size_t bw_om_encode(const BlackwellIRInsn *insns, size_t n, const OmegaRegAlloc *ra, int pad, uint8_t *code) { - if (n > BW_MAX_IR_INSNS) return 0; - uint64_t ins[BW_OM_INS_LEN], phys[BW_OM_PHYS_LEN]; - for (size_t i = 0; i < n; i++) { - const BlackwellIRInsn *in = &insns[i]; - uint64_t *r = &ins[i * 8]; - r[0] = (uint64_t)(int64_t)(int)in->op; - r[1] = (uint64_t)(int64_t)in->dst_vreg; - r[2] = (uint64_t)(int64_t)in->src1_vreg; - r[3] = (uint64_t)(int64_t)in->src2_vreg; - r[4] = (uint64_t)(int64_t)in->src3_vreg; - r[5] = (uint64_t)(int64_t)in->ureg; - r[6] = (uint64_t)in->imm | (uint64_t)in->control << 32; - r[7] = (uint64_t)in->is_uniform | (uint64_t)in->predicate_p0 << 1 | (uint64_t)in->predicate_not << 2 | - (uint64_t)in->bar_reg << 8 | (uint64_t)in->dst_subreg << 16 | (uint64_t)in->src1_subreg << 24 | - (uint64_t)in->src2_subreg << 32 | (uint64_t)in->src3_subreg << 40; - } - for (size_t i = n * 8; i < BW_OM_INS_LEN; i++) ins[i] = 0; - for (int i = 0; i < BW_MAX_VREGS; i++) phys[i] = (uint64_t)(int64_t)ra->vreg_to_phys[i]; - for (int i = 0; i < BW_MAX_UVREGS; i++) phys[BW_MAX_VREGS + i] = (uint64_t)(int64_t)ra->uvreg_to_phys[i]; - uint64_t bytes = 0; - if (omega_bw_enc_sm121(&bytes, ins, BW_OM_INS_LEN, phys, BW_OM_PHYS_LEN, (uint64_t)n, pad ? 1u : 0u, code, - BW_OM_CODE_LEN) != OMEGA_OK) - return 0; - return (size_t)bytes; -} - -#ifdef CUDAPP_MIGRATION_PENDING_ENCODER_DIFF -/* One line per agreement, appended; any disagreement aborts the process after naming it. */ -static void bw_enc_diff_note(const char *what, size_t insns, const uint8_t *code, size_t len, int agree) { - char hex[17] = "-"; - if (len) { - uint8_t d[SHA256_DIGEST_SIZE]; sha256_hash(code, len, d); - for (int i = 0; i < 8; i++) snprintf(hex + 2 * i, 3, "%02x", (unsigned)d[i]); - } - const char *path = getenv("CUDAPP_ENCODER_DIFF_LOG"); - if (path && path[0]) { - int fd = open(path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0600); - if (fd >= 0) { - char line[160]; - int k = snprintf(line, sizeof line, "%s insns=%zu bytes=%zu sha16=%s %s\n", what, insns, len, hex, - agree ? "SAME" : "DIFFER"); - if (k > 0 && write(fd, line, (size_t)k) != k) BW_DIAG("encoder diff: short log write\n"); - close(fd); - } - } - if (!agree) { - BW_DIAG("ENCODER DIFF: .om and C encoders disagree (%s, %zu insns)\n", what, insns); - abort(); - } -} -#endif - -static int encode_single_insn(const BlackwellIRInsn *insn, const OmegaRegAlloc *ra, uint32_t w[4]) { - uint8_t code[BW_OM_CODE_LEN]; - int rc = bw_om_encode(insn, 1, ra, 0, code) == 16 ? 0 : -1; - memset(w, 0, 16); - if (rc == 0) - for (int k = 0; k < 4; k++) - w[k] = (uint32_t)code[4 * k] | (uint32_t)code[4 * k + 1] << 8 | (uint32_t)code[4 * k + 2] << 16 | - (uint32_t)code[4 * k + 3] << 24; -#ifdef CUDAPP_MIGRATION_PENDING_ENCODER_DIFF - uint32_t c[4]; - int crc = bw_c_encode_insn(insn, ra, c); - bw_enc_diff_note("insn", 1, rc == 0 ? code : NULL, rc == 0 ? 16 : 0, - crc == rc && (rc != 0 || memcmp(c, w, 16) == 0)); -#endif - return rc; -} -#endif - -/* 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); unlink(path); BW_DIAG("omega_kernel_dump: write failed, removed %s\n", path); return; } - /* A body cut short (a full disk) must not stay under its full-content name: it would be compared as a smaller kernel - * and, created O_EXCL, never rewritten. tools/sm121dis/corpus.sh fails on these diagnostics. */ - int bad = fwrite(code, 1, len, f) != len; - if (fclose(f) != 0) bad = 1; - if (bad) { unlink(path); BW_DIAG("omega_kernel_dump: write failed, removed %s\n", path); } -#else - (void)code; (void)len; -#endif -} - -#ifdef BW_ENC_C_PRIMARY -static int bw_encode_program_bytes(const BlackwellIRProgram *prog, uint8_t *code_buf, size_t req_bytes) { - size_t padded_insns = req_bytes / 16; - 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; - } - for (int k = 0; k < 4; k++) { - p[4 * k] = (uint8_t)(w[k] & 0xff); - p[4 * k + 1] = (uint8_t)((w[k] >> 8) & 0xff); - p[4 * k + 2] = (uint8_t)((w[k] >> 16) & 0xff); - p[4 * k + 3] = (uint8_t)((w[k] >> 24) & 0xff); - } - p += 16; - } - return 0; -} -#else -static int bw_encode_program_bytes(const BlackwellIRProgram *prog, uint8_t *code_buf, size_t req_bytes) { - uint8_t code[BW_OM_CODE_LEN]; - size_t got = bw_om_encode(prog->insns, prog->count, &prog->regalloc, 1, code); - int rc = (got == req_bytes && got != 0) ? 0 : -1; -#ifdef CUDAPP_MIGRATION_PENDING_ENCODER_DIFF - /* The C oracle encodes the same program, instruction by instruction, NOP-padded the same way. */ -#ifdef CUDAPP_ENCODER_DIFF_SELFTEST - if (rc == 0) code[0] ^= 1; /* red check of the comparison itself: one flipped bit must abort */ -#endif - uint8_t ref[BW_OM_CODE_LEN]; - int crc = 0; - for (size_t i = 0; i < req_bytes / 16 && crc == 0; i++) { - uint32_t w[4] = { 0x00007918, 0, 0, 0x000fc000 }; - if (i < prog->count) crc = bw_c_encode_insn(&prog->insns[i], &prog->regalloc, w); - for (int k = 0; k < 16; k++) ref[16 * i + (size_t)k] = (uint8_t)(w[k / 4] >> (8 * (k % 4))); - } - bw_enc_diff_note("program", prog->count, rc == 0 ? code : NULL, rc == 0 ? req_bytes : 0, - crc == rc && (rc != 0 || memcmp(code, ref, req_bytes) == 0)); -#endif - if (rc == 0) memcpy(code_buf, code, req_bytes); - return rc; -} -#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; - - if (bw_encode_program_bytes(prog, code_buf, req_bytes) != 0) return -1; - - 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 d1d65f013..000000000 --- a/src/omega_blackwell_codegen.h +++ /dev/null @@ -1,367 +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+1:Rc), low word Rc. Rc is a 64-bit register - * pair, NOT one 32-bit word: nvcc 13.0 zeroes the upper half before using a 32-bit c, puts - * __umulhi(a, b) + c through the pair {lo 0, hi c}, and emits only even pair bases (R2, R4, UR4 - * in evidence/IMADHI-RC-ORACLE-nvcc13.0-20261016). Compiler reading, not chip-probed (omega #492). - * The warp simulators model an even Rc as that pair and refuse an odd Rc (no evidence). - * hi32(Ra * Rb) + c32 is NOT this instruction with Rc = c32: use RZ then IADD3, or SHF.R + IADD3 - * (the PR #487 odd-column bug, tests/gpu_imadhi_rc_test.c). Rc = RZ: src3_vreg = -1 */ - /* 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 12465d8b6..000000000 --- a/src/omega_blackwell_codegen_tern.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_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 (32 KiB, omega_blackwell_qmd.h) per CTA. - * x takes 2 bytes per column in shared memory, so one chunk of OMEGA_TERN_CHUNK_MAX columns uses 16 KiB, and 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 436de40ed..000000000 --- a/src/omega_blackwell_engine.c +++ /dev/null @@ -1,758 +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 -#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; - -/* Persistent device (omega-mv#575, measured 2026-10-19 on the Spark): of 38.8 ms per - * omega_gpu_execute job, open_device took 7.5 ms, create_channel 19.2 ms and close - * 11.3 ms; the work itself (alloc, copy, submit, wait, readback, free) under 1 ms. - * So the RM client, device and channel stay open between jobs. Per-job buffers and - * the scratch are still allocated and freed per job (the engine's state machine is - * unchanged). A full close happens when the driver reports a fault, when - * omega_blackwell_engine_shutdown() is called, or when OMEGA_GPU_ENGINE_NO_PERSIST=1 - * is set in the environment (the old one-open-per-job behaviour, for A/B runs). - * A retained run (uncertain completion) never reaches be_close, as before. */ -/* nvrm_retire lives in physics/nvrm/nvrm.c; the simulated-driver host build - * (tests/fake_m16_native.c) links no nvrm, so the reference is weak there. */ -extern void nvrm_retire(Nvrm *rm, uint32_t upto) __attribute__((weak)); -static int g_dev_open; /* m16_native_open succeeded and was not closed */ -static int g_chan_open; /* m16_native_create_channel succeeded on that device */ - -static int persist_enabled(void) -{ - const char *e = getenv("OMEGA_GPU_ENGINE_NO_PERSIST"); - return !(e && e[0] == '1'); -} - -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; - M16NativeContext keep; - int reuse; - int rc; - if (atomic_flag_test_and_set(&g_busy)) return -1; /* another run is active; touch nothing */ - reuse = g_dev_open && persist_enabled() && !c->m.rm.faulted; - if (g_dev_open && !reuse) { - /* persistence off, or the driver faulted: close the old device first */ - (void)m16_native_close(&c->m); - g_dev_open = 0; - g_chan_open = 0; - } - keep = c->m; - memset(c, 0, sizeof *c); - c->native_open = 1; - if (reuse) { - c->m = keep; /* the open device and channel carry over; every per-job field is fresh */ - return 0; - } - 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; - } - g_dev_open = 1; - return 0; -} - -static int be_create_channel(void *ctx) -{ - BeCtx *c = (BeCtx *)ctx; - int rc; - begin(c); - if (g_chan_open) return 0; /* persistent channel from an earlier job */ - rc = m16_native_create_channel(&c->m); /* SUB@676f16f line 46 */ - c->last_rc = rc; - if (rc == 0) g_chan_open = 1; - 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); - - /* 1b. invalidate the shader instruction, data and constant caches (clcec0.h - * NVCEC0_INVALIDATE_SHADER_CACHES 0x021c). With the device kept open between - * jobs (omega-mv#575) the PROGRAM buffer of the next job can land at the - * address of the last one, and the chip then ran the OLD code from its - * instruction cache: the no-store control in tests/test_omega_gpu_engine_gb10.c - * caught it on the Spark 2026-10-19 (unchanged=0). The session path has done - * this every launch since cut 1b (src/omega_gpu_session.c). */ - pb_put(c, nvrm_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1)); - pb_put(c, OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL); - - /* 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 = 0; - begin(c); - c->hmarker = NULL; - c->hmarker2 = NULL; - c->hsem = NULL; - if (g_dev_open && persist_enabled() && !c->m.rm.faulted) { - /* Keep the device and channel. The job's GPFIFO entries are complete (the - * engine only reaches close after the completion waits or on a failure before - * submit), so retire them; the ring never fills across jobs. */ - if (nvrm_retire) nvrm_retire(&c->m.rm, c->m.rm.put); - atomic_flag_clear(&g_busy); - return 0; - } - rc = m16_native_close(&c->m); /* SUB@676f16f line 225 */ - c->last_rc = rc; - g_dev_open = 0; - g_chan_open = 0; - atomic_flag_clear(&g_busy); - return rc; -} - -int omega_blackwell_engine_shutdown(void) -{ - BeCtx *c = &g_be; - int rc; - if (atomic_flag_test_and_set(&g_busy)) - return -1; /* a run is active (or retained): leave it */ - if (!g_dev_open) { atomic_flag_clear(&g_busy); return 0; } - rc = m16_native_close(&g_be.m); - g_dev_open = 0; - g_chan_open = 0; - memset(c, 0, sizeof(BeCtx)); - atomic_flag_clear(&g_busy); - return rc; -} - -int omega_blackwell_engine_device_is_open(void) -{ - return g_dev_open; -} - -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 b2e931f24..000000000 --- a/src/omega_blackwell_engine.h +++ /dev/null @@ -1,77 +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); - -/* The device and channel stay open between jobs (omega-mv#575). This closes them - * when no run is active; returns 0 (closed or nothing open), -1 when a run is - * active or retained. OMEGA_GPU_ENGINE_NO_PERSIST=1 restores one open per job. */ -int omega_blackwell_engine_shutdown(void); -int omega_blackwell_engine_device_is_open(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 3c248417e..68666134d 100644 --- a/src/omega_blackwell_gates.c +++ b/src/omega_blackwell_gates.c @@ -561,19 +561,88 @@ 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. + * + * The stage directory is resolved only by the child shell, with the same + * expression the --verify run uses; this file never builds a filesystem path + * from the environment. Callers name a stage file by its index in this fixed + * table, so no other file can be requested. */ +static const char *const canonical_stage_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" +}; +#define CANONICAL_STAGE_FILE_COUNT (sizeof canonical_stage_files / sizeof canonical_stage_files[0]) +#define CANONICAL_STAGE_CODEGEN_C 3u + +/* Returns a pipe carrying the bytes of one stage file; close it with pclose() + * and treat a nonzero status as a read failure. */ +static FILE *canonical_stage_open(size_t index) { + if (index >= CANONICAL_STAGE_FILE_COUNT) return NULL; + char command[256]; + int n = snprintf(command, sizeof command, + "cat -- \"${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp}/%s\"", + canonical_stage_files[index]); + if (n < 0 || (size_t)n >= sizeof command) return NULL; + return popen(command, "r"); +} + +/* Runs the seeded .om stage verifier. On success, when receipt is not NULL, + * it holds the verifier's JSON receipt without its trailing newline. */ +static bool canonical_stage_verified(char *receipt, size_t capacity) { + /* Generic I/O only: the fresh JSON is authored by the seeded .om guard + * and receipt unit. Never deserialize/recreate its policy here. */ + if (receipt && capacity == 0) return false; + 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, used = 0; + bool nonempty = false, ok = true; + while ((n = fread(bytes, 1, sizeof bytes, child)) != 0) { + nonempty = true; + if (receipt) { + if (n >= capacity - used) { + ok = false; + } else { + memcpy(receipt + used, bytes, n); + used += n; + } + } + } + if (ferror(child)) ok = false; + if (pclose(child) != 0) ok = false; + if (receipt) { + while (used > 0 && receipt[used - 1] == '\n') used--; + receipt[used] = '\0'; + if (used == 0 || memchr(receipt, '\n', used) != NULL) ok = false; + } + return nonempty && ok; +} + static bool test_m18_gate6_code_truth(void) { - FILE *f = fopen("src/omega_blackwell_codegen.c", "r"); + if (!canonical_stage_verified(NULL, 0)) return false; + FILE *f = canonical_stage_open(CANONICAL_STAGE_CODEGEN_C); 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; + /* Drain after an early match so the child never dies of SIGPIPE. */ + while (has_static_table && fread(line, 1, sizeof line, f) != 0) {} + bool read_ok = !ferror(f); + if (pclose(f) != 0) read_ok = false; + return nonempty && read_ok && !has_static_table; } static bool test_m18_gate7_codegen_variation(void) { @@ -1007,6 +1076,55 @@ static void m18_clean_clone_remove_checkout(const char *clone) { } } +/* Absolute path of an environment value (or fallback when unset or empty). */ +static bool m18_clean_clone_realpath(const char *name, const char *value, char out[PATH_MAX]) { + if (!value || !*value || !realpath(value, out)) { + fprintf(stderr, "M18 clean clone: cannot resolve %s (%s)\n", name, value ? value : "unset"); + return false; + } + return true; +} + +/* The CUDApp inputs of the nested build, resolved in this process: the stage + * (CUDAPP_STAGE, else ${OUT_DIR:-build}/cudapp), the checkout (CUDAPP_DIR, else + * the repository the stage recorded) and the pinned tools OMEGA_OMC and + * OMEGA_BRIDGE, which tools/cudapp-stage.sh requires. The stage is only + * verified here and names the checkout; it is never handed to the nested build, + * which stages its own copy under its own build/ (a resolved stage directory is + * not a snapshot link, so cudapp-stage.sh refuses to publish over it, and the + * caller's link would otherwise be republished by the copy). */ +static bool m18_clean_clone_cudapp_inputs(char stage[PATH_MAX], char cudapp[PATH_MAX], char omc[PATH_MAX], + char bridge[PATH_MAX]) { + char fallback[PATH_MAX]; + const char *value = getenv("CUDAPP_STAGE"); + if (!value || !*value) { + const char *out_dir = getenv("OUT_DIR"); + int n = snprintf(fallback, sizeof(fallback), "%s/cudapp", out_dir && *out_dir ? out_dir : "build"); + if (n < 0 || (size_t)n >= sizeof(fallback)) return false; + value = fallback; + } + if (!m18_clean_clone_realpath("CUDAPP_STAGE", value, stage)) return false; + value = getenv("CUDAPP_DIR"); + if (!value || !*value) { + char repository[PATH_MAX + 16]; + int n = snprintf(repository, sizeof(repository), "%s/repository", stage); + if (n < 0 || (size_t)n >= sizeof(repository)) return false; + FILE *f = fopen(repository, "r"); + if (!f) { + fprintf(stderr, "M18 clean clone: %s: %s\n", repository, strerror(errno)); + return false; + } + bool got = fgets(fallback, sizeof(fallback), f) != NULL; + fclose(f); + if (!got) return false; + fallback[strcspn(fallback, "\n")] = '\0'; + value = fallback; + } + return m18_clean_clone_realpath("CUDAPP_DIR", value, cudapp) && + m18_clean_clone_realpath("OMEGA_OMC", getenv("OMEGA_OMC"), omc) && + m18_clean_clone_realpath("OMEGA_BRIDGE", getenv("OMEGA_BRIDGE"), bridge); +} + static bool test_m18_gate16_clean_clone(void) { if (getenv("OMEGA_IN_CLEAN_CLONE") != NULL) { return true; @@ -1032,6 +1150,11 @@ static bool test_m18_gate16_clean_clone(void) { fprintf(stderr, "%s\n", physics_err); 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. */ + char stage_dir[PATH_MAX], cudapp_dir[PATH_MAX], omc_path[PATH_MAX], bridge_dir[PATH_MAX]; + if (!m18_clean_clone_cudapp_inputs(stage_dir, cudapp_dir, omc_path, bridge_dir)) return false; const char *tmp = getenv("TMPDIR"); if (!tmp || !*tmp) tmp = "/tmp"; char clone[PATH_MAX]; @@ -1042,15 +1165,19 @@ static bool test_m18_gate16_clean_clone(void) { return false; } /* No shell (omega#565): each step is its own program with an argument vector, - * so nothing in TMPDIR or PHYSICS_DIR can change what runs. Paths outside the - * plain charset are refused (fail closed); make would also expand a '$'. */ - if (!omega_cc_path_is_plain(clone) || !omega_cc_path_is_plain(physics_dir_resolved)) { - fprintf(stderr, "M18 clean clone: refusing a path with characters outside [A-Za-z0-9/._+-]: %s | %s\n", - clone, physics_dir_resolved); + * so nothing in TMPDIR, PHYSICS_DIR or the CUDApp inputs can change what runs. + * Paths outside the plain charset are refused (fail closed); make would also + * expand a '$'. */ + if (!omega_cc_path_is_plain(clone) || !omega_cc_path_is_plain(physics_dir_resolved) || + !omega_cc_path_is_plain(stage_dir) || !omega_cc_path_is_plain(cudapp_dir) || + !omega_cc_path_is_plain(omc_path) || !omega_cc_path_is_plain(bridge_dir)) { + fprintf(stderr, "M18 clean clone: refusing a path with characters outside [A-Za-z0-9/._+-]: %s | %s | %s | %s | %s | %s\n", + clone, physics_dir_resolved, stage_dir, cudapp_dir, omc_path, bridge_dir); (void)rmdir(clone); return false; } char root[PATH_MAX], checkout[PATH_MAX], log_path[PATH_MAX], physics_arg[PATH_MAX + 16]; + char cudapp_arg[PATH_MAX + 16], omc_arg[PATH_MAX + 16], bridge_arg[PATH_MAX + 16]; char *git_top[] = {"git", "rev-parse", "--show-toplevel", NULL}; if (!omega_cc_capture_line(NULL, "git", git_top, root, sizeof(root))) { fprintf(stderr, "M18 clean clone: git rev-parse --show-toplevel failed\n"); @@ -1060,17 +1187,23 @@ static bool test_m18_gate16_clean_clone(void) { int n1 = snprintf(checkout, sizeof(checkout), "%s/checkout", clone); int n2 = snprintf(log_path, sizeof(log_path), "%s/clean_clone_m18.log", clone); int n3 = snprintf(physics_arg, sizeof(physics_arg), "PHYSICS_DIR=%s", physics_dir_resolved); + int n4 = snprintf(cudapp_arg, sizeof(cudapp_arg), "CUDAPP_DIR=%s", cudapp_dir); + int n6 = snprintf(omc_arg, sizeof(omc_arg), "OMEGA_OMC=%s", omc_path); + int n7 = snprintf(bridge_arg, sizeof(bridge_arg), "OMEGA_BRIDGE=%s", bridge_dir); if (n1 < 0 || (size_t)n1 >= sizeof(checkout) || n2 < 0 || (size_t)n2 >= sizeof(log_path) || - n3 < 0 || (size_t)n3 >= sizeof(physics_arg)) { + n3 < 0 || (size_t)n3 >= sizeof(physics_arg) || n4 < 0 || (size_t)n4 >= sizeof(cudapp_arg) || + n6 < 0 || (size_t)n6 >= sizeof(omc_arg) || n7 < 0 || (size_t)n7 >= sizeof(bridge_arg)) { (void)rmdir(clone); return false; } + char *verify_argv[] = {"sh", "tools/cudapp-stage.sh", "--verify", "cudapp.lock", stage_dir, NULL}; char *cp_argv[] = {"cp", "-r", "--", root, checkout, NULL}; char *clean_argv[] = {"make", "clean", NULL}; - char *make_argv[] = {"make", "-j", physics_arg, NULL}; + char *make_argv[] = {"make", "-j", physics_arg, cudapp_arg, omc_arg, bridge_arg, NULL}; char *run_argv[] = {"./build/omegatool", "--run-m18-gates", NULL}; - const char *step = "cp"; - int rc = omega_cc_run(NULL, "cp", cp_argv, NULL, false); + const char *step = "cudapp-stage --verify"; + int rc = omega_cc_run(root, "sh", verify_argv, NULL, false); + if (rc == 0) { step = "cp"; rc = omega_cc_run(NULL, "cp", cp_argv, NULL, false); } if (rc == 0) { step = "make clean"; rc = omega_cc_run(checkout, "make", clean_argv, NULL, false); } if (rc == 0) { step = "make"; rc = omega_cc_run(checkout, "make", make_argv, NULL, false); } /* The log sits beside the checkout: /clean_clone_m18.log. */ @@ -1092,9 +1225,8 @@ static bool test_m18_gate17_regression(void) { return (run_m17_gates() == 0); } -static bool compute_file_sha256(const char *path, uint8_t digest[32], char hex[65]) { - FILE *f = fopen(path, "rb"); - if (!f) return false; +/* Hashes f to EOF; the caller closes f and owns its close status. */ +static bool stream_sha256(FILE *f, uint8_t digest[32], char hex[65]) { sha256_ctx ctx; sha256_init(&ctx); uint8_t buf[4096]; @@ -1102,7 +1234,7 @@ 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); + if (ferror(f)) return false; sha256_final(&ctx, digest); for (int i = 0; i < 32; i++) { sprintf(&hex[i * 2], "%02x", digest[i]); @@ -1111,6 +1243,14 @@ static bool compute_file_sha256(const char *path, uint8_t digest[32], char hex[6 return true; } +static bool compute_file_sha256(const char *path, uint8_t digest[32], char hex[65]) { + FILE *f = fopen(path, "rb"); + if (!f) return false; + bool read_ok = stream_sha256(f, digest, hex); + if (fclose(f) != 0) read_ok = false; + return read_ok; +} + static void bytes_to_hex_str(const uint8_t *bytes, size_t len, char *hex) { for (size_t i = 0; i < len; i++) { sprintf(&hex[i * 2], "%02x", bytes[i]); @@ -1221,18 +1361,12 @@ static bool test_m18_gate18_receipt(void) { char bin_hex[65] = {0}; if (!compute_file_sha256(self_path, bin_digest, bin_hex)) return false; - /* 5. Generate the SHA256SUMS manifest under the run-scoped evidence area. */ + /* 5. Generate the SHA256SUMS manifest under the run-scoped evidence area. + * The verifier's CUDApp source receipt is recorded verbatim in the M18 + * receipt below (cudapp_source), not in a separate evidence file. */ + char cudapp_source[4096]; + if (!canonical_stage_verified(cudapp_source, sizeof cudapp_source)) return false; 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", @@ -1245,14 +1379,26 @@ 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 < CANONICAL_STAGE_FILE_COUNT; i++) { + char h[65]; + uint8_t d[32]; + FILE *stage_file = canonical_stage_open(i); + bool hashed = stage_file && stream_sha256(stage_file, d, h); + if (stage_file && pclose(stage_file) != 0) hashed = false; + if (!hashed || fprintf(f_sums, "%s cudapp/%s\n", h, canonical_stage_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]; @@ -1306,6 +1452,7 @@ static bool test_m18_gate18_receipt(void) { fprintf(f, " \"bf16_realization_id\": \"%s\",\n", bf16_real_hex); fprintf(f, " \"binary_sha256\": \"%s\",\n", bin_hex); fprintf(f, " \"evidence_manifest_sha256\": \"%s\",\n", manifest_hex); + fprintf(f, " \"cudapp_source\": %s,\n", cudapp_source); fprintf(f, " \"tested_configurations\": [\n"); for (size_t i = 0; i < m18_parity_count; i++) { m18_print_parity_record(f, &m18_parity[i], i + 1 < m18_parity_count); 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_hazard.c b/src/omega_bw_hazard.c deleted file mode 100644 index 026ae76bd..000000000 --- a/src/omega_bw_hazard.c +++ /dev/null @@ -1,267 +0,0 @@ -/* omega_bw_hazard.c: static scoreboard hazard checker over encoded sm_121 kernel bytes (omega-mv#554). See the header. - * - * Every form decoded below is a form src/omega_blackwell_codegen.c (encode_single_insn) or a post-encode patch - * (omega_tc_patch_code, omega_qmma_patch_code) writes. The operand positions are the encoder's: Rd = word 0 bits 16..23, - * Ra = word 0 bits 24..31, Rb = word 1 bits 0..7, Rc = word 2 bits 0..7. tests/bw_hazard_test.c checks the decoder - * against the encoder for every IR op and against nvdisasm on every kernel. */ -#include "omega_bw_hazard.h" - -#include -#include - -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; } - -/* registers of a memory access of size field (word 2 bits 9..11): 0..4 one register, 5 a pair (.64), 6 a quad (.128) */ -static int size_regs(uint32_t w2) { - unsigned s = (w2 >> 9) & 7u; - return s <= 4 ? 1 : s == 5 ? 2 : s == 6 ? 4 : -1; -} - -static void R(OmegaBwInsn *d, unsigned reg, int n, int uniform) { - if (reg == OMEGA_BW_RZ || n <= 0 || d->nr >= 5) return; - d->rd[d->nr].reg = (uint8_t)reg; d->rd[d->nr].n = (uint8_t)n; d->rd[d->nr].uniform = (uint8_t)uniform; d->nr++; -} -static void W(OmegaBwInsn *d, unsigned reg, int n, int uniform) { - if (reg == OMEGA_BW_RZ || n <= 0 || d->nw >= 1) return; - d->wr[0].reg = (uint8_t)reg; d->wr[0].n = (uint8_t)n; d->wr[0].uniform = (uint8_t)uniform; d->nw = 1; -} - -int omega_bw_decode(const uint8_t b[16], OmegaBwInsn *d) { - if (!b || !d) return -1; - uint32_t w0 = rd32(b), w1 = rd32(b + 4), w2 = rd32(b + 8), w3 = rd32(b + 12); - memset(d, 0, sizeof *d); - d->op = (uint16_t)(w0 & 0xfffu); - d->guard = (uint8_t)((w0 >> 12) & 0xfu); - d->stall = (uint8_t)((w3 >> 9) & 0xfu); - d->yield = (uint8_t)((w3 >> 13) & 1u); - d->wbar = (uint8_t)((w3 >> 14) & 7u); - d->rbar = (uint8_t)((w3 >> 17) & 7u); - d->wait = (uint8_t)((w3 >> 20) & 0x3fu); - unsigned D = (w0 >> 16) & 0xffu, A = w0 >> 24, B = w1 & 0xffu, C = w2 & 0xffu; - int n; - switch (d->op) { - case 0x918: d->name = "NOP"; break; - case 0xb1d: d->name = "BAR"; break; - case 0x992: d->name = "MEMBAR"; break; - case 0x98f: d->name = "CCTL"; R(d, A, 1, 0); d->late = 1; break; - case 0x94d: d->name = "EXIT"; d->flow = OMEGA_BW_FLOW_EXIT; break; - case 0x947: { - d->name = "BRA"; d->flow = OMEGA_BW_FLOW_BRA; - int32_t rel = (int32_t)((uint32_t)((int32_t)w1 >> 2) << 6) | (int32_t)((w0 >> 18) & 0x3fu); - d->target = rel + 1; - break; - } - case 0x945: d->name = "BSSY"; break; - case 0x941: d->name = "BSYNC"; break; - case 0x202: d->name = "MOV"; W(d, D, 1, 0); R(d, B, 1, 0); break; - case 0x802: d->name = "MOV"; W(d, D, 1, 0); break; - case 0x919: d->name = "S2R"; W(d, D, 1, 0); d->var = 1; break; - case 0xb82: - d->name = "LDC"; if ((n = size_regs(w2)) < 0) return -1; - W(d, D, n, 0); R(d, A, 1, 0); d->var = 1; d->late = 1; break; - case 0x7ac: - d->name = "LDCU"; if ((n = size_regs(w2)) < 0) return -1; - W(d, D, n, 1); R(d, A, 1, 1); d->var = 1; d->late = 1; break; - case 0x224: d->name = "IMAD"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 0); R(d, C, 1, 0); break; - case 0x824: d->name = "IMAD"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, C, 1, 0); break; - case 0xc24: d->name = "IMAD"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 1); R(d, C, 1, 0); break; - case 0x825: d->name = "IMAD.WIDE"; W(d, D, 2, 0); R(d, A, 1, 0); R(d, C, 2, 0); break; - case 0x227: d->name = "IMAD.HI"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 0); R(d, C, 1, 0); break; - case 0x20c: d->name = "ISETP"; R(d, A, 1, 0); R(d, B, 1, 0); break; - case 0x80c: d->name = "ISETP"; R(d, A, 1, 0); break; - case 0xc0c: d->name = "ISETP"; R(d, A, 1, 0); R(d, B, 1, 1); break; - case 0x210: d->name = "IADD3"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 0); R(d, C, 1, 0); break; - case 0x23c: d->name = "HMMA"; W(d, D, 4, 0); R(d, A, 4, 0); R(d, B, 2, 0); R(d, C, 4, 0); break; - case 0x27a: d->name = "QMMA"; W(d, D, 4, 0); R(d, A, 4, 0); R(d, B, 2, 0); R(d, C, 4, 0); break; - case 0x819: d->name = "SHF"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, C, 1, 0); break; - case 0x219: d->name = "SHF"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 0); R(d, C, 1, 0); break; - case 0x812: d->name = "LOP3"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, C, 1, 0); break; - case 0x212: d->name = "LOP3"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 0); R(d, C, 1, 0); break; - case 0x221: d->name = "FADD"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 0); break; - case 0x220: d->name = "FMUL"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 0); break; - case 0x223: d->name = "FFMA"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 0); R(d, C, 1, 0); break; - case 0x20b: d->name = "FSETP"; R(d, A, 1, 0); R(d, B, 1, 0); break; - case 0x208: d->name = "FSEL"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 0); break; - case 0x209: d->name = "FMNMX"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 0); break; - case 0x23e: d->name = "F2FP"; W(d, D, 1, 0); R(d, A, 1, 0); R(d, B, 1, 0); break; - case 0x245: d->name = "I2FP"; W(d, D, 1, 0); R(d, B, 1, 0); break; - case 0x305: d->name = "F2I"; W(d, D, 1, 0); R(d, B, 1, 0); d->var = 1; break; - case 0x308: d->name = "MUFU"; W(d, D, 1, 0); R(d, B, 1, 0); d->var = 1; break; - case 0xf89: d->name = "SHFL"; W(d, D, 1, 0); R(d, A, 1, 0); d->var = 1; break; - case 0x981: /* LDG Rd, desc[URb][Ra.64+imm]: word 2 bit 8 = 64-bit address, bit 27 = descriptor */ - d->name = "LDG"; if ((n = size_regs(w2)) < 0) return -1; - W(d, D, n, 0); R(d, A, (w2 & 0x100u) ? 2 : 1, 0); if (w2 & 0x08000000u) R(d, B, 1, 1); - d->var = 1; d->late = 1; break; - case 0x986: /* STG desc[URc][Ra.64+imm], Rb */ - d->name = "STG"; if ((n = size_regs(w2)) < 0) return -1; - R(d, A, (w2 & 0x100u) ? 2 : 1, 0); R(d, B, n, 0); if (w2 & 0x08000000u) R(d, C, 1, 1); - d->late = 1; break; - case 0x9a8: /* ATOMG desc[URc][Ra.64], Rb -> Rd */ - d->name = "ATOMG"; W(d, D, 1, 0); R(d, A, (w2 & 0x100u) ? 2 : 1, 0); R(d, B, 1, 0); - if (w2 & 0x08000000u) R(d, C, 1, 1); - d->var = 1; d->late = 1; break; - case 0x984: /* LDS Rd, [Ra+URb+imm]: word 2 bit 27 = uniform offset */ - d->name = "LDS"; if ((n = size_regs(w2)) < 0) return -1; - W(d, D, n, 0); R(d, A, 1, 0); if (w2 & 0x08000000u) R(d, B, 1, 1); - d->var = 1; d->late = 1; break; - case 0x388: case 0x988: /* STS [Ra+URc], Rb */ - d->name = "STS"; if ((n = size_regs(w2)) < 0) return -1; - R(d, A, 1, 0); R(d, B, n, 0); if (w2 & 0x08000000u) R(d, C, 1, 1); - d->late = 1; break; - default: - return -1; - } - return 0; -} - -const char *omega_bw_hazard_kind(uint8_t kind) { - return kind == OMEGA_BW_HZ_RAW ? "RAW" : kind == OMEGA_BW_HZ_WAR ? "WAR" : kind == OMEGA_BW_HZ_WAW ? "WAW" : "?"; -} - -/* ---- the walk --------------------------------------------------------------------------------------------------- - * State per register: two 64-bit sets of "release masks". An outstanding op is entered as the bit (1 << m), m the - * 6-bit set of barriers whose wait releases it (m = 0: the op declared none, nothing releases it). A wait mask W - * releases every entry m with m & W != 0, so it clears kill(W). Union over paths is OR. */ -#define NREG 512 /* 256 general + 256 uniform */ - -typedef struct { - uint64_t w[NREG]; /* pending writes (RAW / WAW) */ - uint64_t r[NREG]; /* pending late reads (WAR) */ - uint32_t wpc[NREG]; /* last producer / queued reader seen (a hint for the report) */ - uint32_t rpc[NREG]; -} State; - -static uint64_t kill_mask(unsigned wait) { - uint64_t k = 0; - for (unsigned m = 1; m < 64; m++) - if (m & wait) k |= 1ull << m; - return k; -} - -static void note(OmegaBwHazardReport *r, uint32_t pc, uint32_t src, uint8_t kind, unsigned idx, uint64_t pending) { - unsigned rel = 0; - for (unsigned m = 0; m < 64; m++) - if (pending >> m & 1u) { rel = m; break; } /* the smallest mask: 0 when an op declared no barrier */ - for (size_t i = 0; i < r->count && i < OMEGA_BW_HAZARD_MAX; i++) - if (r->f[i].pc == pc && r->f[i].kind == kind && r->f[i].reg == (uint8_t)idx && r->f[i].uniform == (idx >= 256)) - return; - if (r->count < OMEGA_BW_HAZARD_MAX) { - OmegaBwHazard *h = &r->f[r->count]; - h->pc = pc; h->src_pc = src; h->kind = kind; h->reg = (uint8_t)idx; h->uniform = (uint8_t)(idx >= 256); h->release = (uint8_t)rel; - } - r->count++; -} - -/* one instruction: IN state s -> OUT state s (in place). rep != NULL records the findings. */ -static void step(const OmegaBwInsn *d, uint32_t pc, State *s, OmegaBwHazardReport *rep) { - if (d->wait) { - uint64_t k = ~kill_mask(d->wait); - for (unsigned i = 0; i < NREG; i++) { s->w[i] &= k; s->r[i] &= k; } - } - /* reads: RAW against pending writes; the first reader is reported and the entry dropped (no cascade) */ - for (unsigned j = 0; j < d->nr; j++) - for (unsigned q = 0; q < d->rd[j].n; q++) { - unsigned i = (d->rd[j].uniform ? 256u : 0u) + ((d->rd[j].reg + q) & 0xffu); - if ((i & 0xffu) == OMEGA_BW_RZ) continue; - if (s->w[i]) { if (rep) note(rep, pc, s->wpc[i], OMEGA_BW_HZ_RAW, i, s->w[i]); s->w[i] = 0; } - } - /* writes: WAR against queued late readers, WAW against pending writes */ - for (unsigned j = 0; j < d->nw; j++) - for (unsigned q = 0; q < d->wr[j].n; q++) { - unsigned i = (d->wr[j].uniform ? 256u : 0u) + ((d->wr[j].reg + q) & 0xffu); - if ((i & 0xffu) == OMEGA_BW_RZ) continue; - if (s->r[i]) { if (rep) note(rep, pc, s->rpc[i], OMEGA_BW_HZ_WAR, i, s->r[i]); s->r[i] = 0; } - if (s->w[i]) { if (rep) note(rep, pc, s->wpc[i], OMEGA_BW_HZ_WAW, i, s->w[i]); s->w[i] = 0; } - int has_w = d->wbar != OMEGA_BW_NOBAR; - if (has_w || d->var) { s->w[i] |= 1ull << (has_w ? (1u << d->wbar) : 0u); s->wpc[i] = pc; } - } - /* late source reads: held until a wait on the read barrier or on the write barrier (completion) */ - if (d->late || d->rbar != OMEGA_BW_NOBAR) { - unsigned m = (d->rbar != OMEGA_BW_NOBAR ? 1u << d->rbar : 0u) | (d->wbar != OMEGA_BW_NOBAR ? 1u << d->wbar : 0u); - for (unsigned j = 0; j < d->nr; j++) - for (unsigned q = 0; q < d->rd[j].n; q++) { - unsigned i = (d->rd[j].uniform ? 256u : 0u) + ((d->rd[j].reg + q) & 0xffu); - if ((i & 0xffu) == OMEGA_BW_RZ) continue; - s->r[i] |= 1ull << m; s->rpc[i] = pc; - } - } -} - -/* OR src into dst; 1 if dst changed */ -static int join(State *dst, const State *src) { - int ch = 0; - for (unsigned i = 0; i < NREG; i++) { - uint64_t w = dst->w[i] | src->w[i], r = dst->r[i] | src->r[i]; - if (w != dst->w[i]) { dst->w[i] = w; dst->wpc[i] = src->wpc[i]; ch = 1; } - if (r != dst->r[i]) { dst->r[i] = r; dst->rpc[i] = src->rpc[i]; ch = 1; } - } - return ch; -} - -int omega_bw_hazard_check(const uint8_t *code, size_t len, OmegaBwHazardReport *r) { - if (!r) return -1; - memset(r, 0, sizeof *r); - r->bad_pc = -1; - if (!code || len == 0 || len % 16u) return -1; - size_t n = len / 16u; - r->insns = n; - OmegaBwInsn *ins = calloc(n, sizeof *ins); - State *in = calloc(n, sizeof *in); - uint8_t *seen = calloc(n, 1), *queued = calloc(n, 1); - uint32_t *work = calloc(n, sizeof *work); - State *cur = malloc(sizeof *cur); - int rc = -1; - if (!ins || !in || !seen || !queued || !work || !cur) goto out; - - /* decode what is reachable from 0 (padding after the final EXIT is never decoded) */ - { - size_t top = 0; - work[top++] = 0; queued[0] = 1; - while (top) { - uint32_t pc = work[--top]; - if (omega_bw_decode(code + (size_t)pc * 16u, &ins[pc]) != 0) { r->bad_pc = pc; goto out; } - seen[pc] = 1; - const OmegaBwInsn *d = &ins[pc]; - int64_t succ[2]; int ns = 0; - if (d->flow == OMEGA_BW_FLOW_NEXT || d->guard != 7u) succ[ns++] = (int64_t)pc + 1; - if (d->flow == OMEGA_BW_FLOW_BRA) succ[ns++] = (int64_t)pc + d->target; - for (int k = 0; k < ns; k++) { - if (succ[k] < 0 || succ[k] >= (int64_t)n) { r->bad_pc = pc; goto out; } - if (!queued[succ[k]]) { queued[succ[k]] = 1; work[top++] = (uint32_t)succ[k]; } - } - } - } - for (size_t i = 0; i < n; i++) r->reachable += seen[i]; - - /* fixed point: IN states only grow (OR), the lattice is finite. Every reachable instruction is stepped at least - * once (seen is reused as "not yet stepped"), later only when its IN state grew. */ - memset(queued, 0, n); - { - size_t top = 0; - work[top++] = 0; queued[0] = 1; - while (top) { - uint32_t pc = work[--top]; - queued[pc] = 0; seen[pc] = 2; - *cur = in[pc]; - step(&ins[pc], pc, cur, NULL); - const OmegaBwInsn *d = &ins[pc]; - int64_t succ[2]; int ns = 0; - if (d->flow == OMEGA_BW_FLOW_NEXT || d->guard != 7u) succ[ns++] = (int64_t)pc + 1; - if (d->flow == OMEGA_BW_FLOW_BRA) succ[ns++] = (int64_t)pc + d->target; - for (int k = 0; k < ns; k++) { - uint32_t t = (uint32_t)succ[k]; - if ((join(&in[t], cur) || seen[t] == 1) && !queued[t]) { queued[t] = 1; work[top++] = t; } - } - } - } - /* record: one pass over the reachable instructions with their fixed-point IN states */ - for (size_t pc = 0; pc < n; pc++) { - if (!seen[pc]) continue; - *cur = in[pc]; - step(&ins[pc], (uint32_t)pc, cur, r); - } - rc = 0; -out: - free(ins); free(in); free(seen); free(queued); free(work); free(cur); - return rc; -} diff --git a/src/omega_bw_hazard.h b/src/omega_bw_hazard.h deleted file mode 100644 index cd80642c1..000000000 --- a/src/omega_bw_hazard.h +++ /dev/null @@ -1,85 +0,0 @@ -/* omega_bw_hazard.h: static scoreboard hazard checker over encoded sm_121 kernel bytes (omega-mv#554). - * - * The warp simulators run the IR and model no scoreboards, so a dropped wait mask passes every host test and only - * shows on the chip (omega-mv#545: the encoder wrote a fixed word 3 for IADD3, the wait on the Q loads' read barrier - * was lost and a MOV zeroed the address of 16 queued LDG.E.128; Xid 13). This checker reads the bytes the chip runs, - * after every encode and patch step, and walks the control flow with the scoreboard rules: - * - * RAW a reader of a register written by a variable-latency op must have waited on that op's write barrier; - * WAR a writer of a register still being read by a queued load or store must have waited on its read barrier - * (or on its write barrier: an op that has completed has read its sources); - * WAW a writer of a register a variable-latency op has not yet written must have waited on that op's write - * barrier (the late result would land over the new value). - * - * Control word (word 3 of each 16-byte instruction, the same layout as CW() in omega_bw_em.h): stall bits 9..12, - * yield 13, write barrier 14..16, read barrier 17..19 (7 = none), wait mask 20..25. A wait on barrier n releases every - * register any outstanding op on n holds (the barrier is a counter that reaches zero). The analysis is a may-analysis - * over all paths (branches, predicated EXIT/BRA, loops) to a fixed point; a predicated instruction may or may not - * write, and its wait mask is taken as applied (UNKNOWN whether the chip applies the wait of a predicated-off - * instruction; if it does not, this checker can miss a hazard behind such an instruction). - * - * Limits, said out loud: fixed-latency hazards (stall counts too short) are not checked; predicate registers are not - * tracked; HMMA/QMMA are tracked only through the barriers their bytes declare. NVIDIA documents none of the control - * field; the layout is our own decode, cross-checked against nvdisasm on every kernel (tests/bw_hazard_test.c). */ -#ifndef OMEGA_BW_HAZARD_H -#define OMEGA_BW_HAZARD_H - -#include -#include - -#define OMEGA_BW_RZ 0xffu /* register 255 is RZ, uniform 255 is URZ: never tracked */ -#define OMEGA_BW_NOBAR 7u - -enum { OMEGA_BW_FLOW_NEXT = 0, OMEGA_BW_FLOW_EXIT, OMEGA_BW_FLOW_BRA }; - -typedef struct { - uint8_t reg; /* first register */ - uint8_t n; /* 1, 2 or 4 consecutive registers */ - uint8_t uniform; /* 1 = uniform register file */ -} OmegaBwOperand; - -typedef struct { - uint16_t op; /* word 0 bits 0..11 */ - uint8_t guard; /* word 0 bits 12..15: 7 = always (PT) */ - uint8_t stall, yield, wbar, rbar, wait; - uint8_t var; /* variable-latency writer: its result needs a write barrier */ - uint8_t late; /* reads its sources late (loads, stores, atomics, constant loads) */ - uint8_t nr, nw; - OmegaBwOperand rd[5], wr[1]; - uint8_t flow; /* OMEGA_BW_FLOW_* */ - int32_t target; /* FLOW_BRA: target instruction index relative to this one */ - const char *name; -} OmegaBwInsn; - -/* Decodes one 16-byte instruction. 0 ok, -1 an opcode or form this decoder does not know (the kernel is then - * reported as not checked, never as clean). */ -int omega_bw_decode(const uint8_t b[16], OmegaBwInsn *d); - -enum { OMEGA_BW_HZ_RAW = 1, OMEGA_BW_HZ_WAR = 2, OMEGA_BW_HZ_WAW = 3 }; - -typedef struct { - uint32_t pc; /* instruction index of the offending reader / writer */ - uint32_t src_pc; /* the last producer / queued reader of the register seen on some path (a hint) */ - uint8_t kind; /* OMEGA_BW_HZ_* */ - uint8_t reg; - uint8_t uniform; - uint8_t release; /* barrier mask whose wait would have released it; 0 = the op declared no barrier at all */ -} OmegaBwHazard; - -#define OMEGA_BW_HAZARD_MAX 256 - -typedef struct { - size_t insns; /* instructions in the buffer */ - size_t reachable; /* reachable from instruction 0 */ - size_t count; /* findings (the first OMEGA_BW_HAZARD_MAX are kept) */ - OmegaBwHazard f[OMEGA_BW_HAZARD_MAX]; - int64_t bad_pc; /* -1, or the first instruction that could not be decoded or branches out of range */ -} OmegaBwHazardReport; - -/* Checks code[0..len). 0 = decoded and walked (r->count findings, possibly 0); -1 = not checked (bad_pc set, or a - * NULL / misaligned argument, or out of memory). Host only; allocates its work state. */ -int omega_bw_hazard_check(const uint8_t *code, size_t len, OmegaBwHazardReport *r); - -const char *omega_bw_hazard_kind(uint8_t kind); - -#endif /* OMEGA_BW_HAZARD_H */ 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_clean_clone.c b/src/omega_clean_clone.c index db83e4d17..5f40c01ea 100644 --- a/src/omega_clean_clone.c +++ b/src/omega_clean_clone.c @@ -23,9 +23,11 @@ bool omega_cc_path_is_plain(const char *s) { return true; } -/* Child side: environment, directory, output, then exec. Never returns. */ +/* Child side: environment, directory, output, then exec. Never returns. + * OUT_DIR and CUDAPP_STAGE are dropped so the copy builds, stages and reads its + * own build/ and build/cudapp, never the caller's. */ static void cc_child(const char *dir, const char *prog, char *const argv[], const char *out_rel, bool in_clean_clone) { - if (unsetenv("OUT_DIR") != 0) _exit(127); + if (unsetenv("OUT_DIR") != 0 || unsetenv("CUDAPP_STAGE") != 0) _exit(127); if (in_clean_clone && setenv("OMEGA_IN_CLEAN_CLONE", "1", 1) != 0) _exit(127); if (dir && chdir(dir) != 0) _exit(127); /* Opened after chdir: the name is fixed by the caller, never built from a path. */ diff --git a/src/omega_fp8_slot_table.c b/src/omega_fp8_slot_table.c deleted file mode 100644 index ca4acd47b..000000000 --- a/src/omega_fp8_slot_table.c +++ /dev/null @@ -1,117 +0,0 @@ -/* omega_fp8_slot_table.c: host-only slot state machine (see the header). */ -#include "omega_fp8_slot_table.h" -#include -#include - -int omega_fp8_slot_table_init(OmegaFp8SlotTable *t, uint32_t slots) { - if (!t || slots == 0) return OMEGA_FP8_SLOT_BAD_ARGS; - memset(t, 0, sizeof *t); - t->rec = calloc(slots, sizeof *t->rec); - if (!t->rec) return OMEGA_FP8_SLOT_BAD_ARGS; - if (pthread_mutex_init(&t->mu, NULL) != 0) { free(t->rec); t->rec = NULL; return OMEGA_FP8_SLOT_BAD_ARGS; } - t->slots = slots; - t->next_version = 1; - return OMEGA_FP8_SLOT_OK; -} - -void omega_fp8_slot_table_fini(OmegaFp8SlotTable *t) { - if (!t || !t->rec) return; - pthread_mutex_destroy(&t->mu); - free(t->rec); - t->rec = NULL; - t->slots = 0; -} - -#define LOCKED(t, body) do { pthread_mutex_lock(&(t)->mu); body; pthread_mutex_unlock(&(t)->mu); } while (0) - -int omega_fp8_slot_begin_load(OmegaFp8SlotTable *t, uint32_t slot) { - if (!t || !t->rec || slot >= t->slots) return OMEGA_FP8_SLOT_BAD_ARGS; - int rc = OMEGA_FP8_SLOT_OK; - LOCKED(t, { - OmegaFp8SlotRec *r = &t->rec[slot]; - if (r->state == OMEGA_FP8_SLOT_LOADING || (r->pins && !t->mutant)) { rc = OMEGA_FP8_SLOT_BUSY; t->stats.busy_refusals++; } - else r->state = OMEGA_FP8_SLOT_LOADING; /* hides the old version: pin(old) is STALE from here */ - }); - return rc; -} - -int omega_fp8_slot_finish_load(OmegaFp8SlotTable *t, uint32_t slot, uint64_t key, int ok, uint64_t *version) { - if (version) *version = 0; - if (!t || !t->rec || slot >= t->slots) return OMEGA_FP8_SLOT_BAD_ARGS; - int rc = OMEGA_FP8_SLOT_OK; - LOCKED(t, { - OmegaFp8SlotRec *r = &t->rec[slot]; - if (r->state != OMEGA_FP8_SLOT_LOADING) rc = OMEGA_FP8_SLOT_BAD_ARGS; - else if (ok) { - r->state = OMEGA_FP8_SLOT_READY; r->key = key; r->version = t->next_version++; - if (version) *version = r->version; - t->stats.loads++; - } else { r->state = OMEGA_FP8_SLOT_EMPTY; r->key = 0; t->stats.load_failures++; } - }); - return rc; -} - -int omega_fp8_slot_pin(OmegaFp8SlotTable *t, uint32_t slot, uint64_t version) { - if (!t || !t->rec || slot >= t->slots) return OMEGA_FP8_SLOT_BAD_ARGS; - int rc = OMEGA_FP8_SLOT_OK; - LOCKED(t, { - OmegaFp8SlotRec *r = &t->rec[slot]; - if (r->state != OMEGA_FP8_SLOT_READY || r->version != version || version == 0) { rc = OMEGA_FP8_SLOT_STALE; t->stats.stale_refusals++; } - else { - r->pins++; t->stats.pins++; t->stats.pinned_now++; - if (t->stats.pinned_now > t->stats.pinned_high) t->stats.pinned_high = t->stats.pinned_now; - } - }); - return rc; -} - -int omega_fp8_slot_unpin(OmegaFp8SlotTable *t, uint32_t slot, uint64_t version) { - if (!t || !t->rec || slot >= t->slots) return OMEGA_FP8_SLOT_BAD_ARGS; - int rc = OMEGA_FP8_SLOT_OK; - LOCKED(t, { - OmegaFp8SlotRec *r = &t->rec[slot]; - /* Under the mutant a pinned slot may have been reloaded: the pin is still dropped (version not checked). */ - if (r->pins == 0 || (!t->mutant && r->version != version)) rc = OMEGA_FP8_SLOT_BAD_ARGS; - else { r->pins--; t->stats.pinned_now--; } - }); - return rc; -} - -int omega_fp8_slot_evict(OmegaFp8SlotTable *t, uint32_t slot) { - if (!t || !t->rec || slot >= t->slots) return OMEGA_FP8_SLOT_BAD_ARGS; - int rc = OMEGA_FP8_SLOT_OK; - LOCKED(t, { - OmegaFp8SlotRec *r = &t->rec[slot]; - if (r->pins || r->state == OMEGA_FP8_SLOT_LOADING) { rc = OMEGA_FP8_SLOT_BUSY; t->stats.busy_refusals++; } - else { if (r->state == OMEGA_FP8_SLOT_READY) t->stats.evictions++; r->state = OMEGA_FP8_SLOT_EMPTY; r->key = 0; } - }); - return rc; -} - -int omega_fp8_slot_query(OmegaFp8SlotTable *t, uint32_t slot, OmegaFp8SlotRec *out) { - if (!t || !t->rec || slot >= t->slots || !out) return OMEGA_FP8_SLOT_BAD_ARGS; - LOCKED(t, { *out = t->rec[slot]; }); - return OMEGA_FP8_SLOT_OK; -} - -int omega_fp8_slot_table_idle(OmegaFp8SlotTable *t) { - if (!t || !t->rec) return 1; - int idle = 1; - LOCKED(t, { - for (uint32_t i = 0; i < t->slots; i++) - if (t->rec[i].pins || t->rec[i].state == OMEGA_FP8_SLOT_LOADING) { idle = 0; break; } - }); - return idle; -} - -void omega_fp8_slot_table_stats(OmegaFp8SlotTable *t, OmegaFp8SlotStats *out) { - if (!out) return; - memset(out, 0, sizeof *out); - if (!t || !t->rec) return; - LOCKED(t, { *out = t->stats; }); -} - -void omega_fp8_slot_table_set_mutant(OmegaFp8SlotTable *t, int mutant) { - if (!t || !t->rec) return; - LOCKED(t, { t->mutant = mutant; }); -} diff --git a/src/omega_fp8_slot_table.h b/src/omega_fp8_slot_table.h deleted file mode 100644 index 66dca74ce..000000000 --- a/src/omega_fp8_slot_table.h +++ /dev/null @@ -1,77 +0,0 @@ -#ifndef OMEGA_FP8_SLOT_TABLE_H -#define OMEGA_FP8_SLOT_TABLE_H -/* - * omega_fp8_slot_table: the host-only state machine behind omega_gpu_fp8_slots (Expert Ribbon, omega#533). - * No device code: every rule about who may read or rewrite a slot lives here so it can be tested without a chip. - * - * One record per slot: state, pins, key (caller's expert identity), version. - * EMPTY --begin_load--> LOADING --finish_load(ok)--> READY (version = next ring-wide version, never reused) - * LOADING --finish_load(fail)-> EMPTY (nothing published) - * READY --begin_load (0 pins)--> LOADING (the old version dies at that moment: pin(old) is STALE from then on) - * READY --evict (0 pins)--> EMPTY - * pin(slot, version) succeeds only on READY with exactly that version; begin_load and evict refuse (BUSY) while - * pins > 0. A pin is held for as long as any launch or recorded command list may read the slot; the caller drops it - * after the launch's completion marker (synchronous APIs: when the call returns; command lists: after submit). - * Versions are a single ring-wide counter starting at 1, so a (slot, version) pair names exactly one load (no ABA). - * Thread-safe (one mutex per table). - */ -#include -#include -#ifdef __cplusplus -extern "C" { -#endif - -enum { - OMEGA_FP8_SLOT_OK = 0, - OMEGA_FP8_SLOT_BAD_ARGS = -1, /* slot out of range, unpin without a pin, NULL */ - OMEGA_FP8_SLOT_BUSY = -6, /* pinned or already loading: nothing changed */ - OMEGA_FP8_SLOT_STALE = -7 /* the slot is not READY at that version (evicted, reloaded or never loaded) */ -}; - -typedef enum { OMEGA_FP8_SLOT_EMPTY = 0, OMEGA_FP8_SLOT_LOADING = 1, OMEGA_FP8_SLOT_READY = 2 } OmegaFp8SlotState; - -typedef struct { - uint32_t state; /* OmegaFp8SlotState */ - uint32_t pins; - uint64_t key; /* caller's identity of the loaded expert (meaningful in READY) */ - uint64_t version; /* version of the READY contents; 0 = never published */ -} OmegaFp8SlotRec; - -typedef struct { - uint64_t loads; /* finish_load(ok) */ - uint64_t load_failures; /* finish_load(fail) */ - uint64_t busy_refusals; /* begin_load / evict refused because pinned or loading */ - uint64_t stale_refusals; /* pin refused */ - uint64_t evictions; - uint64_t pins; /* successful pins */ - uint32_t pinned_now; /* sum of pins over slots */ - uint32_t pinned_high; /* high-water of pinned_now */ -} OmegaFp8SlotStats; - -typedef struct { - pthread_mutex_t mu; - uint32_t slots; - OmegaFp8SlotRec *rec; - uint64_t next_version; - int mutant; /* TEST ONLY: 1 = begin_load ignores pins (the negative control must catch a rewritten in-use slot) */ - OmegaFp8SlotStats stats; -} OmegaFp8SlotTable; - -int omega_fp8_slot_table_init(OmegaFp8SlotTable *t, uint32_t slots); -void omega_fp8_slot_table_fini(OmegaFp8SlotTable *t); -int omega_fp8_slot_begin_load(OmegaFp8SlotTable *t, uint32_t slot); -/* ok != 0 publishes (READY, *version = new version); ok == 0 leaves the slot EMPTY. Must follow begin_load. */ -int omega_fp8_slot_finish_load(OmegaFp8SlotTable *t, uint32_t slot, uint64_t key, int ok, uint64_t *version); -int omega_fp8_slot_pin(OmegaFp8SlotTable *t, uint32_t slot, uint64_t version); -int omega_fp8_slot_unpin(OmegaFp8SlotTable *t, uint32_t slot, uint64_t version); -int omega_fp8_slot_evict(OmegaFp8SlotTable *t, uint32_t slot); -int omega_fp8_slot_query(OmegaFp8SlotTable *t, uint32_t slot, OmegaFp8SlotRec *out); -/* 1 when no slot is pinned or loading (safe to free the memory behind the table). */ -int omega_fp8_slot_table_idle(OmegaFp8SlotTable *t); -void omega_fp8_slot_table_stats(OmegaFp8SlotTable *t, OmegaFp8SlotStats *out); -void omega_fp8_slot_table_set_mutant(OmegaFp8SlotTable *t, int mutant); - -#ifdef __cplusplus -} -#endif -#endif 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 c3e88b2eb..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 131072u - -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 211a08ec3..000000000 --- a/src/omega_gpu_decode_graph.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_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; - const uint32_t room = (uint32_t)(sizeof g->stamp / sizeof g->stamp[0]) - g->n_stamp; - if (cnt > from && (uint32_t)(cnt - from) > room) { /* more launches this token than the timeline holds */ - omega_gpu_session_set_error("decode graph: timeline full (more launches per token than OMEGA_GPU_CMDLIST_MAX_LAUNCHES)"); - rc = -1; - } else { - 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); -} - -/* A failed begin leaves no token behind: list emptied, out of the token, lock released (no end_token owed, omega #518). */ -static int begin_fail(OmegaGpuDecodeGraph *g) { - omega_gpu_cmdlist_reset(g->cl); - g->in_token = 0; g->failed = 1; - omega_gpu_session_unlock(); /* begin_fail releases */ - return OMEGA_GPU_DGRAPH_CHIP_FAIL; -} - -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 begin_fail(g); - 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 begin_fail(g); - 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_abort_token(OmegaGpuDecodeGraph *g) { - if (!g || !g->in_token) return OMEGA_GPU_DGRAPH_BAD_ARGS; - omega_gpu_cmdlist_reset(g->cl); - g->in_token = 0; g->tagged_in_list = 0; g->n_stamp = 0; /* no timeline for an abandoned token */ - omega_gpu_session_unlock(); - return OMEGA_GPU_DGRAPH_OK; -} - -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; - const int brc = omega_gpu_decode_graph_begin_token(g, x_embed); - if (brc != OMEGA_GPU_DGRAPH_OK) { if (st) memset(st, 0, sizeof *st); return brc; } /* nothing begun, lock free */ - 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->failed || 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 bb8a78b32..000000000 --- a/src/omega_gpu_decode_graph.h +++ /dev/null @@ -1,222 +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 (or abort_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. - * Lock and token state after each call (omega #518; tests/test_omega_gpu_decode_graph_abort.c enforces it): - * begin_token OK: lock held, in the token; exactly one end_token or abort_token is owed. - * BAD_ARGS (NULL graph, already in a token): nothing taken, nothing changed. - * CHIP_FAIL (device open refused or latched, x / token visibility sync refused): lock RELEASED, out of - * the token, list empty; nothing owed (end_token and abort_token answer BAD_ARGS). Nothing was - * submitted, so nothing is uncertain; the next begin_token may simply be called again (a latched - * process fails it again at once: the graph never retries on its own). - * record_* lock still held, still in the token, whatever they return; a failure sticks (later records refuse). - * end_token always releases the lock and leaves the token, success or failure. - * abort_token releases the lock and leaves the token without submitting what was recorded. - * token (one-shot) returns with the lock released in every case. - * 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_abort_token(OmegaGpuDecodeGraph *g); - * 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. On - * CHIP_FAIL it has already released the lock and left the token (see Threading above): do not call end_token. */ -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); -/* Abandons a begun token: drops the recorded launches WITHOUT submitting them, leaves the token, releases the lock. - * OK, or BAD_ARGS when no token is begun. Nothing reaches the device, so nothing is uncertain; launches flush_each - * already submitted stay done. The device x keeps what begin_token wrote; the timeline is cleared. */ -int omega_gpu_decode_graph_abort_token(OmegaGpuDecodeGraph *g); - -/* 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 b9b9b5296..000000000 --- a/src/omega_gpu_fp8_api.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_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 "omega_gpu_fp8_internal.h" -#include -#include - -#define CACHE_SLOTS 16 -#define MARKER_TIMEOUT_MS 20000ull -#define POISON_F32 (-999.0f) - -struct OmegaGpuFp8Tensor { - uint32_t experts, n, k; - OmegaGpuMem w; /* experts * n * k e4m3 bytes, row-major */ - OmegaGpuMem s; /* experts * (n/128) * (k/128) f32 (scale * 2^56) */ -}; - -typedef struct { - bool valid, pinned; - uint32_t variant; /* 1 or 2: which generator built the kernel (part of the cache key) */ - OmegaFp8GemvSpec spec; - OmegaBlackwellKernel kernel; - OmegaGpuMem code; -} Slot; - -static struct { - OmegaGpuScratch x_buf, y_buf; - OmegaGpuMem tab; /* group table, OMEGA_GPU_FP8_MAX_GROUPS * 16 bytes */ - uint32_t cta_budget; int cta_budget_set; - uint32_t lane_bytes, rows, warps; /* overrides, 0 = automatic */ - int depth_set; uint32_t depth; /* depth override (depth_set: 0 = automatic) */ - uint32_t gpr_pad; /* registers declared beyond the kernel's peak (diagnosis knob) */ - int mutant, no_fold, sealed; - int variant, variant_set; /* GEMV variant 1 or 2 (omega_gpu_fp8_set_variant / AIEN_OMEGA_FP8_GEMV), read once */ - int weights_cached; /* omega_gpu_fp8_set_weight_cache: uploads after it allocate GPU-cached (read-only weights) */ - int weights_cached_set; /* 0: never set, the first upload reads env AIEN_OMEGA_FP8_WEIGHT_CACHE (W-L2d: "1" = cached) */ - 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) { omega_gpu_session_lock(); g.no_fold = on ? 1 : 0; omega_gpu_session_unlock(); } -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; - /* Fill and sync under the lock (omega#456): t is not shared yet, but its CPU views belong to the open device, and a - * device close on another thread between unlock and memcpy would unmap them; sync_to_gpu also reads the open state. - * g.no_fold is read under the lock, as its setter now writes it. The cost is holding the lock for one weight copy. */ - 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; - } - omega_gpu_session_unlock(); - 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; -} - -/* ---- slot pool support (omega_gpu_fp8_internal.h, Expert Ribbon omega#533) ---- */ -int omega_gpu_fp8_tensor_alloc_uncached(uint32_t experts, uint32_t n, uint32_t k, OmegaGpuFp8Tensor **out) { - if (out) *out = NULL; - if (!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); - 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 (!dev_open_locked() || omega_gpu_session_alloc(wbytes, &t->w) != 0 || omega_gpu_session_alloc(scount * 4u, &t->s) != 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; - omega_gpu_session_unlock(); - if (rc == OMEGA_GPU_FP8_OK) { - memset(t->w.cpu, 0, wbytes); - memset(t->s.cpu, 0, scount * 4u); - 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; -} -int omega_gpu_fp8_tensor_cpu_view(const OmegaGpuFp8Tensor *t, uint32_t expert, uint8_t **w, float **s) { - if (!t || !t->w.cpu || !t->s.cpu || expert >= t->experts || !w || !s) return OMEGA_GPU_FP8_BAD_ARGS; - *w = (uint8_t *)t->w.cpu + (size_t)expert * t->n * t->k; - *s = (float *)t->s.cpu + (size_t)expert * (t->n / OMEGA_FP8_BLOCK) * (t->k / OMEGA_FP8_BLOCK); - return OMEGA_GPU_FP8_OK; -} -int omega_gpu_fp8_tensor_sync_to_gpu(const OmegaGpuFp8Tensor *t) { - if (!t) return -1; - return (omega_gpu_session_sync_to_gpu(&t->w) != 0 || omega_gpu_session_sync_to_gpu(&t->s) != 0) ? -1 : 0; -} 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_internal.h b/src/omega_gpu_fp8_internal.h deleted file mode 100644 index 4ceca4bcf..000000000 --- a/src/omega_gpu_fp8_internal.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef OMEGA_GPU_FP8_INTERNAL_H -#define OMEGA_GPU_FP8_INTERNAL_H -/* Library-internal helpers of omega_gpu_fp8_api.c for omega_gpu_fp8_slots.c (Expert Ribbon, omega#533). Not part of the - * public ABI: the slot pool owns its tensor and is the only caller. */ -#include "omega_gpu_fp8_api.h" -#include -#include -/* A zero-filled FP8 tensor of `experts` x [n][k] in GPU-UNCACHED memory, whatever omega_gpu_fp8_set_weight_cache says: - * slots are rewritten by the CPU while the process runs, and nvos.h:1117-1118 says GPU-cached system memory "will not be - * coherent with direct CPU mappings" (omega #457 measured 4096/4096 stale lines on a cached rewrite; uncached FRESH). */ -int omega_gpu_fp8_tensor_alloc_uncached(uint32_t experts, uint32_t n, uint32_t k, OmegaGpuFp8Tensor **out); -/* CPU views of one expert: n*k weight bytes and (n/128)*(k/128) packed f32 scales. */ -int omega_gpu_fp8_tensor_cpu_view(const OmegaGpuFp8Tensor *t, uint32_t expert, uint8_t **w, float **s); -/* CPU writes before the device reads them (platform SYNC on both buffers; Linux reference: dsb sy). 0 ok, -1. */ -int omega_gpu_fp8_tensor_sync_to_gpu(const OmegaGpuFp8Tensor *t); -#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_fp8_slots.c b/src/omega_gpu_fp8_slots.c deleted file mode 100644 index 839f466a0..000000000 --- a/src/omega_gpu_fp8_slots.c +++ /dev/null @@ -1,155 +0,0 @@ -/* omega_gpu_fp8_slots.c: versioned replaceable FP8 expert slots (see the header). */ -#include "omega_gpu_fp8_slots.h" -#include "omega_gpu_fp8_internal.h" -#include "omega_fp8_slot_table.h" -#include "omega_gpu_session.h" -#include "omega_gpu_fmt.h" -#include -#include - -struct OmegaGpuFp8Slots { - uint32_t slots, n, k; - OmegaGpuFp8Tensor *t; - OmegaFp8SlotTable tab; - pthread_mutex_t mu; /* bytes_loaded / load_ns */ - uint64_t bytes_loaded, load_ns; -}; - -const char *omega_gpu_fp8_slots_rc_name(int rc) { - switch (rc) { - case OMEGA_GPU_FP8_SLOTS_BUSY: return "BUSY"; - case OMEGA_GPU_FP8_SLOTS_STALE: return "STALE"; - default: return omega_gpu_fp8_rc_name(rc); - } -} - -/* The table's codes are the pool's codes (OK 0, BAD_ARGS -1, BUSY -6, STALE -7). */ -_Static_assert(OMEGA_FP8_SLOT_BUSY == OMEGA_GPU_FP8_SLOTS_BUSY && OMEGA_FP8_SLOT_STALE == OMEGA_GPU_FP8_SLOTS_STALE && - (int)OMEGA_FP8_SLOT_BAD_ARGS == (int)OMEGA_GPU_FP8_BAD_ARGS, "slot table codes"); - -int omega_gpu_fp8_slots_alloc(uint32_t slots, uint32_t n, uint32_t k, OmegaGpuFp8Slots **out) { - if (out) *out = NULL; - if (!out || slots == 0) return OMEGA_GPU_FP8_BAD_ARGS; - OmegaGpuFp8Slots *p = calloc(1, sizeof *p); - if (!p) return OMEGA_GPU_FP8_BAD_ARGS; - p->slots = slots; p->n = n; p->k = k; - int rc = omega_gpu_fp8_tensor_alloc_uncached(slots, n, k, &p->t); - if (rc != OMEGA_GPU_FP8_OK) { free(p); return rc; } - if (omega_fp8_slot_table_init(&p->tab, slots) != 0 || pthread_mutex_init(&p->mu, NULL) != 0) { - omega_gpu_fp8_tensor_free(p->t); omega_fp8_slot_table_fini(&p->tab); free(p); return OMEGA_GPU_FP8_BAD_ARGS; - } - *out = p; - return OMEGA_GPU_FP8_OK; -} - -int omega_gpu_fp8_slots_free(OmegaGpuFp8Slots *p) { - if (!p) return OMEGA_GPU_FP8_OK; - if (!omega_fp8_slot_table_idle(&p->tab)) return OMEGA_GPU_FP8_SLOTS_BUSY; - omega_gpu_fp8_tensor_free(p->t); - omega_fp8_slot_table_fini(&p->tab); - pthread_mutex_destroy(&p->mu); - free(p); - return OMEGA_GPU_FP8_OK; -} - -const OmegaGpuFp8Tensor *omega_gpu_fp8_slots_tensor(const OmegaGpuFp8Slots *p) { return p ? p->t : NULL; } - -int omega_gpu_fp8_slots_load(OmegaGpuFp8Slots *p, uint32_t slot, uint64_t key, const uint8_t *w, const uint16_t *scale, - uint64_t *version) { - if (version) *version = 0; - if (!p || !w || !scale || !version) return OMEGA_GPU_FP8_BAD_ARGS; - if (omega_gpu_session_is_blocked()) return OMEGA_GPU_FP8_CHIP_FAIL; - const uint64_t t0 = omega_gpu_session_now_ns(); - int rc = omega_fp8_slot_begin_load(&p->tab, slot); - if (rc != OMEGA_FP8_SLOT_OK) return rc; - /* From here the slot is LOADING: invisible to pin, so the bytes below are never read half-written. */ - const size_t wbytes = (size_t)p->n * p->k, scount = (size_t)(p->n / OMEGA_FP8_BLOCK) * (p->k / OMEGA_FP8_BLOCK); - uint8_t *wd = NULL; float *sd = NULL; - size_t first = 0; - if (omega_gpu_fp8_tensor_cpu_view(p->t, slot, &wd, &sd) != 0) rc = OMEGA_GPU_FP8_BAD_ARGS; - else if (omega_fp8_pack_scan_nan(w, wbytes, &first)) { - char e[120]; omega_gpu_fmt(e, sizeof e, "fp8 slot load: e4m3 NaN code at byte %zu", first); - omega_gpu_session_set_error(e); - rc = OMEGA_GPU_FP8_NAN_WEIGHT; - } else if (omega_fp8_pack_scales(scale, scount, sd, 0) != 0) { - omega_gpu_session_set_error("fp8 slot load: NaN, inf or overflowing scale"); - rc = OMEGA_GPU_FP8_BAD_ARGS; - } else { - memcpy(wd, w, wbytes); - if (omega_gpu_fp8_tensor_sync_to_gpu(p->t) != 0) rc = OMEGA_GPU_FP8_CHIP_FAIL; - } - int frc = omega_fp8_slot_finish_load(&p->tab, slot, key, rc == OMEGA_GPU_FP8_OK, version); - if (rc == OMEGA_GPU_FP8_OK && frc != OMEGA_FP8_SLOT_OK) rc = frc; - if (rc == OMEGA_GPU_FP8_OK) { - pthread_mutex_lock(&p->mu); - p->bytes_loaded += wbytes + scount * 4u; - p->load_ns += omega_gpu_session_now_ns() - t0; - pthread_mutex_unlock(&p->mu); - } - return rc; -} - -int omega_gpu_fp8_slots_pin(OmegaGpuFp8Slots *p, uint32_t slot, uint64_t version) { - return p ? omega_fp8_slot_pin(&p->tab, slot, version) : OMEGA_GPU_FP8_BAD_ARGS; -} -int omega_gpu_fp8_slots_unpin(OmegaGpuFp8Slots *p, uint32_t slot, uint64_t version) { - return p ? omega_fp8_slot_unpin(&p->tab, slot, version) : OMEGA_GPU_FP8_BAD_ARGS; -} -int omega_gpu_fp8_slots_evict(OmegaGpuFp8Slots *p, uint32_t slot) { - return p ? omega_fp8_slot_evict(&p->tab, slot) : OMEGA_GPU_FP8_BAD_ARGS; -} - -int omega_gpu_fp8_slots_entry(OmegaGpuFp8Slots *p, uint32_t slot, uint64_t version, uint64_t *w_va, uint64_t *s_va) { - if (!p || !w_va || !s_va) return OMEGA_GPU_FP8_BAD_ARGS; - OmegaFp8SlotRec r; - int rc = omega_fp8_slot_query(&p->tab, slot, &r); - if (rc != OMEGA_FP8_SLOT_OK) return rc; - if (r.state != OMEGA_FP8_SLOT_READY || r.version != version || version == 0) return OMEGA_GPU_FP8_SLOTS_STALE; - if (r.pins == 0) { omega_gpu_session_set_error("fp8 slot entry: slot not pinned (pin before taking its address)"); return OMEGA_GPU_FP8_BAD_ARGS; } - return omega_gpu_fp8_tensor_entry(p->t, slot, w_va, s_va); -} - -int omega_gpu_fp8_slots_query(OmegaGpuFp8Slots *p, uint32_t slot, OmegaGpuFp8SlotInfo *out) { - if (!p || !out) return OMEGA_GPU_FP8_BAD_ARGS; - OmegaFp8SlotRec r; - int rc = omega_fp8_slot_query(&p->tab, slot, &r); - if (rc != OMEGA_FP8_SLOT_OK) return rc; - out->state = r.state; out->pins = r.pins; out->key = r.key; out->version = r.version; - return OMEGA_GPU_FP8_OK; -} - -void omega_gpu_fp8_slots_stats(OmegaGpuFp8Slots *p, OmegaGpuFp8SlotsStats *out) { - if (!out) return; - memset(out, 0, sizeof *out); - if (!p) return; - OmegaFp8SlotStats s; - omega_fp8_slot_table_stats(&p->tab, &s); - out->slots = p->slots; out->n = p->n; out->k = p->k; - out->device_bytes = (uint64_t)p->slots * ((uint64_t)p->n * p->k + (uint64_t)(p->n / OMEGA_FP8_BLOCK) * (p->k / OMEGA_FP8_BLOCK) * 4u); - out->loads = s.loads; out->load_failures = s.load_failures; out->busy_refusals = s.busy_refusals; - out->stale_refusals = s.stale_refusals; out->evictions = s.evictions; out->pins = s.pins; - out->pinned_now = s.pinned_now; out->pinned_high = s.pinned_high; - pthread_mutex_lock(&p->mu); - out->bytes_loaded = p->bytes_loaded; out->load_ns = p->load_ns; - pthread_mutex_unlock(&p->mu); -} - -int omega_gpu_fp8_slots_gemv_grouped_f32(OmegaGpuFp8Slots *p, uint32_t groups, const uint32_t *slots, const uint64_t *versions, - const float *x, uint32_t x_rows, float *y, OmegaGpuFp8Info *info) { - if (!p || !slots || !versions || groups == 0) return OMEGA_GPU_FP8_BAD_ARGS; - if (groups > OMEGA_GPU_FP8_MAX_GROUPS) return OMEGA_GPU_FP8_TOO_LARGE; - uint32_t pinned = 0; - int rc = OMEGA_GPU_FP8_OK; - for (; pinned < groups; pinned++) { - rc = omega_fp8_slot_pin(&p->tab, slots[pinned], versions[pinned]); - if (rc != OMEGA_FP8_SLOT_OK) break; - } - if (rc == OMEGA_GPU_FP8_OK) rc = omega_gpu_fp8_gemv_grouped_f32(p->t, groups, slots, x, x_rows, y, info); - /* The call returned after the launch's completion marker (or failed): no reader of these slots remains. */ - for (uint32_t i = 0; i < pinned; i++) (void)omega_fp8_slot_unpin(&p->tab, slots[i], versions[i]); - return rc; -} - -void omega_gpu_fp8_slots_test_set_mutant(OmegaGpuFp8Slots *p, int mutant) { - if (p) omega_fp8_slot_table_set_mutant(&p->tab, mutant); -} diff --git a/src/omega_gpu_fp8_slots.h b/src/omega_gpu_fp8_slots.h deleted file mode 100644 index 1ad8f6475..000000000 --- a/src/omega_gpu_fp8_slots.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef OMEGA_GPU_FP8_SLOTS_H -#define OMEGA_GPU_FP8_SLOTS_H -/* - * omega_gpu_fp8_slots: versioned, replaceable FP8 expert slots (Expert Ribbon, aienix#4 / omega#533). - * - * A pool is S fixed slots of one FP8 projection shape [n][k] (weights + block-128 scales), backed by ONE - * OmegaGpuFp8Tensor with experts = S, so every existing FP8 launch (grouped GEMV by slot index, the record path through - * a group table of omega_gpu_fp8_slots_entry addresses) reads a slot exactly as it reads a resident expert. Same kernel, - * same arithmetic: a slot holding expert E gives bit-identical y to a resident tensor holding E. - * - * Memory: GPU-UNCACHED always (nvos.h:1117-1118: GPU-cached system memory "will not be coherent with direct CPU - * mappings"; omega #457 gpu_l2_stale_test: a CPU rewrite of a cached weight buffer read stale lines, uncached FRESH). - * The AIEN_OMEGA_FP8_WEIGHT_CACHE / omega_gpu_fp8_set_weight_cache setting does not apply to pools. - * - * Protocol (state machine in omega_fp8_slot_table.h, host-tested): - * load(slot, key, w, scales) -> version - * refused BUSY while the slot is pinned or loading; the slot is hidden (LOADING) before the first byte is written, - * so no reader can pin the old or the half-written contents. NaN e4m3 codes refuse (NAN_WEIGHT), NaN/inf scales - * refuse (BAD_ARGS); a refused load leaves the slot EMPTY. Weights are copied byte for byte, scales packed as by - * omega_gpu_fp8_tensor_upload (f32 * 2^56); then the platform SYNC (CPU writes before device reads); only then is a - * new ring-wide version published. Versions never repeat, so (slot, version) names one load (no ABA). - * Does NOT take the session lock: a load may run while launches on other slots are in flight. - * pin(slot, version) / unpin(slot, version) - * a pin is the reader fence: hold it from before the launch is built until its completion marker is seen - * (synchronous APIs: until the call returns; a command list: until omega_gpu_cmdlist_submit returns). - * pin is refused STALE when the slot was reloaded, evicted or never loaded. - * entry(slot, version) -> {w_va, s_va}: only while pinned at that version (for a group table / router directory). - * evict(slot): BUSY while pinned. - * gemv_grouped_f32(slots, versions, ...): pins every slot, one grouped launch, unpins after the completion marker. - * - * Return codes: OMEGA_GPU_FP8_* (omega_gpu_fp8_api.h) plus BUSY / STALE below. - */ -#include "omega_gpu_fp8_api.h" -#include -#ifdef __cplusplus -extern "C" { -#endif - -#define OMEGA_GPU_FP8_SLOTS_BUSY (-6) -#define OMEGA_GPU_FP8_SLOTS_STALE (-7) - -typedef struct OmegaGpuFp8Slots OmegaGpuFp8Slots; - -typedef struct { - uint32_t state; /* 0 EMPTY, 1 LOADING, 2 READY */ - uint32_t pins; - uint64_t key; /* caller's expert identity of the READY contents */ - uint64_t version; /* 0 = never published */ -} OmegaGpuFp8SlotInfo; - -typedef struct { - uint32_t slots, n, k; - uint64_t device_bytes; /* weights + packed scales of the whole pool */ - uint64_t loads, load_failures, busy_refusals, stale_refusals, evictions, pins; - uint32_t pinned_now, pinned_high; - uint64_t bytes_loaded; /* weight + scale bytes copied by successful loads */ - uint64_t load_ns; /* summed wall time of successful loads (scan + copy + pack + sync) */ -} OmegaGpuFp8SlotsStats; - -int omega_gpu_fp8_slots_alloc(uint32_t slots, uint32_t n, uint32_t k, OmegaGpuFp8Slots **out); -/* BUSY (nothing freed) while any slot is pinned or loading. */ -int omega_gpu_fp8_slots_free(OmegaGpuFp8Slots *p); -/* The backing tensor (experts = slots): pass slot indices as expert ids to the FP8 launches. */ -const OmegaGpuFp8Tensor *omega_gpu_fp8_slots_tensor(const OmegaGpuFp8Slots *p); -int omega_gpu_fp8_slots_load(OmegaGpuFp8Slots *p, uint32_t slot, uint64_t key, const uint8_t *w, const uint16_t *scale_inv_bf16, - uint64_t *version); -int omega_gpu_fp8_slots_pin(OmegaGpuFp8Slots *p, uint32_t slot, uint64_t version); -int omega_gpu_fp8_slots_unpin(OmegaGpuFp8Slots *p, uint32_t slot, uint64_t version); -int omega_gpu_fp8_slots_evict(OmegaGpuFp8Slots *p, uint32_t slot); -int omega_gpu_fp8_slots_entry(OmegaGpuFp8Slots *p, uint32_t slot, uint64_t version, uint64_t *w_va, uint64_t *s_va); -int omega_gpu_fp8_slots_query(OmegaGpuFp8Slots *p, uint32_t slot, OmegaGpuFp8SlotInfo *out); -void omega_gpu_fp8_slots_stats(OmegaGpuFp8Slots *p, OmegaGpuFp8SlotsStats *out); -/* Pins every (slot, version) (STALE: nothing launched, nothing left pinned), one grouped launch on the pool tensor - * (omega_gpu_fp8_gemv_grouped_f32 semantics: x_rows 1 or groups), unpins after it returned. */ -int omega_gpu_fp8_slots_gemv_grouped_f32(OmegaGpuFp8Slots *p, uint32_t groups, const uint32_t *slots, const uint64_t *versions, - const float *x, uint32_t x_rows, float *y, OmegaGpuFp8Info *info); -const char *omega_gpu_fp8_slots_rc_name(int rc); -/* TEST ONLY: 1 = load ignores pins (negative control: a reader must then see replaced weights). */ -void omega_gpu_fp8_slots_test_set_mutant(OmegaGpuFp8Slots *p, int mutant); - -#ifdef __cplusplus -} -#endif -#endif 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 d5c4ce729..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 < 131072). 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 4772b5982..000000000 --- a/src/omega_gpu_session.h +++ /dev/null @@ -1,303 +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 = the process-wide setting - (omega_gpu_session_set_spin_us) */ -} 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.2) ---- */ - -/* 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); -/* INTERNAL (not part of the Runtime API; docs/runtime/API.md section 10): library code names its failure stage. */ -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); -/* INTERNAL (not part of the Runtime API; docs/runtime/API.md section 10). - * 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 through the platform, and only - * then clears the latch and the parked list. The Linux reference's RM client close is meant to destroy this process's - * channels, and so any grid still running on them, and to release the driver objects; that has no chip run yet - * (evidence/C5-ISOLATION), and buffers the caller did not free are not unmapped by it (omega_gpu_platform_linux.c, - * ref_device_close). Every handle and command list of the old device is stale; the next open starts a new device. - * A latch noted by a module (omega_gpu_session_note_module_latch) counts as latched. 0 ok; -1 with the reason: not - * latched, latched but no device open, 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); -/* INTERNAL (not part of the Runtime API; docs/runtime/API.md section 10). - * 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); - -/* INTERNAL (not part of the Runtime API; docs/runtime/API.md section 10). - * 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_native.h b/src/omega_native.h index 64d029382..f2a7a4645 100644 --- a/src/omega_native.h +++ b/src/omega_native.h @@ -27,8 +27,6 @@ uint32_t omega2_sha256_final(uint64_t *result, uint8_t *o_c, uint8_t *o_o); uint32_t omega2_sha256_hash(uint64_t *result, const uint8_t *o_d, uint64_t o_d_len, uint8_t *o_o); /* fn omb3 st edit ulong 448 b view uchar 1024 n ulong fin ulong o edit uchar 32 to void */ uint32_t omega_omb3(uint64_t *result, void *o_st, uint64_t o_st_len, const void *o_b, uint64_t o_b_len, uint64_t o_n, uint64_t o_fin, void *o_o, uint64_t o_o_len); -/* fn bw_enc_sm121 ins view ulong 8192 phys view ulong 288 n ulong pad ulong code edit uchar 16384 to ulong */ -uint32_t omega_bw_enc_sm121(uint64_t *result, const void *o_ins, uint64_t o_ins_len, const void *o_phys, uint64_t o_phys_len, uint64_t o_n, uint64_t o_pad, void *o_code, uint64_t o_code_len); #ifdef __cplusplus } #endif diff --git a/src/omega_om_units.c b/src/omega_om_units.c index f8057b82c..b9cad763e 100644 --- a/src/omega_om_units.c +++ b/src/omega_om_units.c @@ -315,30 +315,6 @@ __attribute__((visibility("default"))) uint32_t omega_omb3(uint64_t *result, voi return OMEGA_BAD_ARG; return ombr_run(ombr_entry_omb3, a, result, 0); } -__asm__(".section .text.omega_bridge,\"ax\",@progbits\n.balign 4\n.globl ombr_code_bw_enc_sm121\n.hidden ombr_code_bw_enc_sm121\nombr_code_bw_enc_sm121:\n.byte 0x42,0x18,0x00,0x14,0x05,0x00,0x80,0xd2,0x01,0x78,0x25,0xf8,0x25,0x00,0x80,0xd2,0x02,0x78,0x25,0xf8,0x45,0x00,0x80,0xd2,0x03,0x78,0x25,0xf8,0x65,0x00,0x80,0xd2,0x04,0x78,0x25,0xf8,0xc0,0x03,0x5f,0xd6,0xe4,0xff,0x9f,0x92,0x04,0x00,0xa0,0xf2,0x04,0x00,0xc0,0xf2,0x04,0x00,0xf0,0xf2,0x3f,0x00,0x04,0xeb,0x63,0x00,0x00,0x54,0xe0,0x03,0x03,0xaa,0xc0,0x03,0x5f,0xd6,0x3f,0x80,0x04,0xf1,0xe2,0x00,0x00,0x54,0x04,0x78,0x61,0xf8,0x80,0x00,0x02,0x8b,0xc0,0x03,0x5f,0xd6,0xe0,0x03,0x07,0xaa,0xf0,0x08,0x40,0xf9,0x00,0x02,0x1f,0xd6,0x61,0x00,0x80,0xd2,0xfc,0xff,0xff,0x17,0xe1,0xff,0x9f,0x92,0x01,0x00,0xa0,0xf2,0x01,0x00,0xc0,0xf2,0x01,0x00,0xf0,0xf2,0x1f,0x00,0x01,0xeb,0x63,0x00,0x00,0x54,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x20,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x05,0x01,0x80,0xd2,0x24,0x7c,0x05,0x9b,0x86,0x1c,0x00,0x91,0x08,0x00,0x84,0xd2,0xdf,0x00,0x08,0xeb,0x02,0x29,0x00,0x54,0x05,0x78,0x66,0xf8,0x06,0x00,0x84,0xd2,0x9f,0x00,0x06,0xeb,0x82,0x28,0x00,0x54,0x08,0x78,0x64,0xf8,0x09,0x00,0x80,0xd2,0x68,0x78,0x29,0xf8,0x86,0x04,0x00,0x91,0x08,0x00,0x84,0xd2,0xdf,0x00,0x08,0xeb,0xa2,0x27,0x00,0x54,0x09,0x78,0x66,0xf8,0xaa,0xfc,0x50,0xd3,0xeb,0x1f,0x80,0xd2,0x4c,0x01,0x0b,0x8a,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xfe,0x33,0x00,0xf9,0xe0,0x0b,0x40,0xf9,0xe1,0x23,0x40,0xf9,0xe2,0x2f,0x40,0xf9,0x03,0x00,0x80,0xd2,0xbd,0xff,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x33,0x40,0xf9,0xff,0xc3,0x01,0x91,0x28,0x00,0x80,0xd2,0x66,0x78,0x28,0xf8,0x86,0x08,0x00,0x91,0x08,0x00,0x84,0xd2,0xdf,0x00,0x08,0xeb,0xe2,0x22,0x00,0x54,0x09,0x78,0x66,0xf8,0xaa,0xfc,0x58,0xd3,0xeb,0x1f,0x80,0xd2,0x4c,0x01,0x0b,0x8a,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xfe,0x33,0x00,0xf9,0xe0,0x0b,0x40,0xf9,0xe1,0x23,0x40,0xf9,0xe2,0x2f,0x40,0xf9,0x03,0x00,0x80,0xd2,0x97,0xff,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x33,0x40,0xf9,0xff,0xc3,0x01,0x91,0x48,0x00,0x80,0xd2,0x66,0x78,0x28,0xf8,0x86,0x0c,0x00,0x91,0x08,0x00,0x84,0xd2,0xdf,0x00,0x08,0xeb,0x22,0x1e,0x00,0x54,0x09,0x78,0x66,0xf8,0xaa,0xfc,0x60,0xd3,0xeb,0x1f,0x80,0xd2,0x4c,0x01,0x0b,0x8a,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xfe,0x33,0x00,0xf9,0xe0,0x0b,0x40,0xf9,0xe1,0x23,0x40,0xf9,0xe2,0x2f,0x40,0xf9,0x03,0x00,0x80,0xd2,0x71,0xff,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x33,0x40,0xf9,0xff,0xc3,0x01,0x91,0x68,0x00,0x80,0xd2,0x66,0x78,0x28,0xf8,0x86,0x10,0x00,0x91,0x08,0x00,0x84,0xd2,0xdf,0x00,0x08,0xeb,0x62,0x19,0x00,0x54,0x09,0x78,0x66,0xf8,0xaa,0xfc,0x68,0xd3,0xeb,0x1f,0x80,0xd2,0x4c,0x01,0x0b,0x8a,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xfe,0x33,0x00,0xf9,0xe0,0x0b,0x40,0xf9,0xe1,0x23,0x40,0xf9,0xe2,0x2f,0x40,0xf9,0xe3,0x1f,0x80,0xd2,0x4b,0xff,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x33,0x40,0xf9,0xff,0xc3,0x01,0x91,0x88,0x00,0x80,0xd2,0x66,0x78,0x28,0xf8,0x88,0x14,0x00,0x91,0x09,0x00,0x84,0xd2,0x1f,0x01,0x09,0xeb,0xa2,0x14,0x00,0x54,0x06,0x78,0x68,0xf8,0x08,0x00,0x80,0xd2,0xa9,0x00,0x80,0xd2,0x68,0x78,0x29,0xf8,0xe8,0xff,0x9f,0x92,0x08,0x00,0xa0,0xf2,0x08,0x00,0xc0,0xf2,0x08,0x00,0xf0,0xf2,0xdf,0x00,0x08,0xeb,0xe2,0x00,0x00,0x54,0xc8,0x00,0x04,0x91,0x1f,0x81,0x04,0xf1,0x02,0x13,0x00,0x54,0x49,0x78,0x68,0xf8,0xaa,0x00,0x80,0xd2,0x69,0x78,0x2a,0xf8,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x1b,0x40,0xf9,0x33,0xff,0xff,0x97,0xe8,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0xc9,0x01,0x80,0xd2,0x68,0x78,0x29,0xf8,0x89,0x18,0x00,0x91,0x0a,0x00,0x84,0xd2,0x3f,0x01,0x0a,0xeb,0x42,0x0f,0x00,0x54,0x08,0x78,0x69,0xf8,0xe9,0xff,0x9f,0xd2,0xe9,0xff,0xbf,0xf2,0x0a,0x01,0x09,0x8a,0xcb,0x00,0x80,0xd2,0x6a,0x78,0x2b,0xf8,0x09,0xfd,0x60,0xd3,0xea,0x00,0x80,0xd2,0x69,0x78,0x2a,0xf8,0x29,0x00,0x80,0xd2,0xaa,0x00,0x09,0x8a,0x0b,0x01,0x80,0xd2,0x6a,0x78,0x2b,0xf8,0xa9,0xfc,0x41,0xd3,0x2a,0x00,0x80,0xd2,0x2b,0x01,0x0a,0x8a,0x2c,0x01,0x80,0xd2,0x6b,0x78,0x2c,0xf8,0xa9,0xfc,0x42,0xd3,0x2a,0x00,0x80,0xd2,0x2b,0x01,0x0a,0x8a,0x4c,0x01,0x80,0xd2,0x6b,0x78,0x2c,0xf8,0xa9,0xfc,0x48,0xd3,0xea,0x1f,0x80,0xd2,0x2b,0x01,0x0a,0x8a,0x6c,0x01,0x80,0xd2,0x6b,0x78,0x2c,0xf8,0x89,0x08,0x00,0x91,0x0a,0x00,0x84,0xd2,0x3f,0x01,0x0a,0xeb,0x42,0x0b,0x00,0x54,0x0b,0x78,0x69,0xf8,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x2b,0x40,0xf9,0xf3,0xfe,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0x8a,0x01,0x80,0xd2,0x69,0x78,0x2a,0xf8,0x89,0x0c,0x00,0x91,0x0a,0x00,0x84,0xd2,0x3f,0x01,0x0a,0xeb,0x22,0x07,0x00,0x54,0x0b,0x78,0x69,0xf8,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x2b,0x40,0xf9,0xd2,0xfe,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0xaa,0x01,0x80,0xd2,0x69,0x78,0x2a,0xf8,0x8a,0x04,0x00,0x91,0x0b,0x00,0x84,0xd2,0x5f,0x01,0x0b,0xeb,0x02,0x03,0x00,0x54,0x09,0x78,0x6a,0xf8,0x2a,0x00,0x80,0xd2,0xab,0x00,0x0a,0x8a,0x7f,0x05,0x00,0xf1,0xec,0x17,0x9f,0x9a,0xed,0xff,0x9f,0x92,0x0d,0x00,0xa0,0xf2,0x0d,0x00,0xc0,0xf2,0x0d,0x00,0xf0,0xf2,0x3f,0x01,0x0d,0xeb,0xee,0x27,0x9f,0x9a,0x8f,0x01,0x0e,0x8a,0xef,0x00,0x00,0xb4,0x2a,0x01,0x04,0x91,0x5f,0x81,0x04,0xf1,0x02,0x01,0x00,0x54,0x4b,0x78,0x6a,0xf8,0x2c,0x00,0x80,0xd2,0x6b,0x78,0x2c,0xf8,0xc0,0x03,0x5f,0xd6,0xe0,0x03,0x07,0xaa,0xf0,0x08,0x40,0xf9,0x00,0x02,0x1f,0xd6,0x61,0x00,0x80,0xd2,0xfc,0xff,0xff,0x17,0xe3,0x00,0x80,0xd2,0x02,0x78,0x63,0xf8,0x5f,0x00,0x00,0xf1,0x60,0x00,0x00,0x54,0xe0,0x03,0x02,0xaa,0xc0,0x03,0x5f,0xd6,0xe0,0x03,0x01,0xaa,0xc0,0x03,0x5f,0xd6,0x3f,0x40,0x00,0xf1,0x02,0x01,0x00,0x54,0x02,0x78,0x61,0xf8,0xe3,0x1f,0x80,0xd2,0x40,0x00,0x03,0x8a,0xc0,0x03,0x5f,0xd6,0xe0,0x03,0x07,0xaa,0xf0,0x08,0x40,0xf9,0x00,0x02,0x1f,0xd6,0x61,0x00,0x80,0xd2,0xfc,0xff,0xff,0x17,0x5f,0x40,0x00,0xf1,0xc2,0x02,0x00,0x54,0x03,0x78,0x62,0xf8,0x7f,0x00,0x00,0xf1,0xc0,0x01,0x00,0x54,0xff,0x83,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xfe,0x0f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe9,0xff,0xff,0x97,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xfe,0x0f,0x40,0xf9,0xff,0x83,0x00,0x91,0xc0,0x03,0x5f,0xd6,0xe0,0x1f,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0xe0,0x03,0x07,0xaa,0xf0,0x08,0x40,0xf9,0x00,0x02,0x1f,0xd6,0x61,0x00,0x80,0xd2,0xfc,0xff,0xff,0x17,0xff,0x83,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xfe,0x0b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x00,0x80,0xd2,0xd6,0xff,0xff,0x97,0xe2,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xfe,0x0b,0x40,0xf9,0xff,0x83,0x00,0x91,0x43,0xbc,0x70,0xd3,0x20,0x00,0x03,0xaa,0xc0,0x03,0x5f,0xd6,0xff,0x83,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xfe,0x0b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0xc7,0xff,0xff,0x97,0xe2,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xfe,0x0b,0x40,0xf9,0xff,0x83,0x00,0x91,0x43,0x9c,0x68,0xd3,0x20,0x00,0x03,0xaa,0xc0,0x03,0x5f,0xd6,0xff,0x83,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xfe,0x0b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xdc,0xff,0xff,0x97,0xe2,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xfe,0x0b,0x40,0xf9,0xff,0x83,0x00,0x91,0xff,0x83,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xfe,0x0f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0xab,0xff,0xff,0x97,0xe3,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xfe,0x0f,0x40,0xf9,0xff,0x83,0x00,0x91,0x64,0x9c,0x68,0xd3,0x40,0x00,0x04,0xaa,0xc0,0x03,0x5f,0xd6,0x21,0x01,0x80,0xd2,0x02,0x78,0x61,0xf8,0x5f,0x00,0x00,0xf1,0x61,0x00,0x00,0x54,0xe0,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x41,0x01,0x80,0xd2,0x02,0x78,0x61,0xf8,0x5f,0x00,0x00,0xf1,0x61,0x00,0x00,0x54,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x00,0x01,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x01,0x10,0xa0,0xd2,0x1f,0x00,0x01,0xeb,0xe2,0x27,0x9f,0x9a,0x03,0xf0,0xbf,0xd2,0x1f,0x00,0x03,0xeb,0xe4,0x37,0x9f,0x9a,0x40,0x00,0x04,0xaa,0xc0,0x03,0x5f,0xd6,0x03,0x00,0x80,0xd2,0x02,0x78,0x63,0xf8,0xc4,0x00,0x80,0xd2,0x03,0x78,0x64,0xf8,0x5f,0x00,0x00,0xf1,0xe1,0x04,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x00,0x98,0xd2,0xe1,0x01,0xa0,0xf2,0x74,0xff,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x07,0x40,0xf9,0x01,0x23,0x8f,0xd2,0x02,0x00,0x80,0xd2,0x03,0x00,0x80,0xd2,0xe4,0x13,0x40,0xf9,0xec,0xfd,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x04,0x00,0xf1,0x41,0x07,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x40,0x8e,0xd2,0x79,0xff,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x01,0xa0,0xf2,0x3b,0xff,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x1f,0x80,0xd2,0x03,0xe0,0x81,0xd2,0xe4,0x17,0x40,0xf9,0xb1,0xfd,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x08,0x00,0xf1,0x41,0x07,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x8f,0xd2,0x3e,0xff,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x01,0xa0,0xf2,0x00,0xff,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x0f,0x40,0xf9,0x03,0xe0,0x81,0xd2,0xe4,0x17,0x40,0xf9,0x76,0xfd,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x0c,0x00,0xf1,0xc1,0x08,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x23,0x8f,0xd2,0x03,0xff,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xe5,0x1f,0x80,0xd2,0x66,0x00,0x05,0x8a,0xc8,0xdc,0x78,0xd3,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x84,0xd2,0xc1,0x01,0xa0,0xf2,0xbf,0xfe,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0x02,0x00,0x80,0xd2,0xe3,0x1f,0x40,0xf9,0xe4,0x23,0x40,0xf9,0x2f,0xfd,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x10,0x00,0xf1,0x01,0x09,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x70,0x8f,0xd2,0x01,0xe0,0xbf,0xf2,0xbb,0xfe,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0x65,0xe4,0x7a,0xd3,0x06,0xe0,0x9f,0xd2,0xe6,0x1f,0xa0,0xf2,0xa8,0x00,0x06,0x8a,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x01,0xa0,0xf2,0x76,0xfe,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x1f,0x40,0xf9,0x03,0x00,0x81,0xd2,0xe4,0x23,0x40,0xf9,0xe6,0xfc,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x14,0x00,0xf1,0x01,0x09,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x70,0x8f,0xd2,0x01,0xe0,0xbf,0xf2,0x72,0xfe,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0x65,0xe4,0x7a,0xd3,0x06,0xe0,0x9f,0xd2,0xe6,0x1f,0xa0,0xf2,0xa8,0x00,0x06,0x8a,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x84,0xd2,0xc1,0x01,0xa0,0xf2,0x2d,0xfe,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x1f,0x40,0xf9,0x03,0x40,0x81,0xd2,0xe4,0x23,0x40,0xf9,0x9d,0xfc,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x18,0x00,0xf1,0x21,0x09,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0xf5,0x8e,0xd2,0x01,0xe0,0xbf,0xf2,0x29,0xfe,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0x65,0xe8,0x7b,0xd3,0x06,0xe0,0x9f,0xd2,0xe6,0x1f,0xa0,0xf2,0xa8,0x00,0x06,0x8a,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x84,0xd2,0xc1,0x01,0xa0,0xf2,0xe4,0xfd,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x1f,0x40,0xf9,0x03,0x00,0x81,0xd2,0x03,0x00,0xa1,0xf2,0xe4,0x23,0x40,0xf9,0x53,0xfc,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x1c,0x00,0xf1,0x21,0x09,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0xf5,0x8e,0xd2,0x01,0xe0,0xbf,0xf2,0xdf,0xfd,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0x65,0xe8,0x7b,0xd3,0x06,0xe0,0x9f,0xd2,0xe6,0x1f,0xa0,0xf2,0xa8,0x00,0x06,0x8a,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0xc0,0x8d,0xd2,0xc1,0x01,0xa0,0xf2,0x9a,0xfd,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x1f,0x40,0xf9,0x03,0x40,0x81,0xd2,0x03,0x00,0xa1,0xf2,0xe4,0x23,0x40,0xf9,0x09,0xfc,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x20,0x00,0xf1,0x41,0x28,0x00,0x54,0xa4,0x01,0x80,0xd2,0x05,0x78,0x64,0xf8,0xbf,0x00,0x00,0xf1,0xe0,0x0d,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x44,0x8e,0xd2,0xb0,0xfd,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x5d,0xfd,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x00,0x80,0xd2,0x4a,0xfd,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0x08,0x40,0x80,0xd2,0xc8,0xf1,0xa0,0xf2,0x09,0x01,0x06,0xaa,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x99,0xd2,0xe1,0x03,0xa0,0xf2,0x27,0xfd,0xff,0x97,0xea,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0xe3,0x23,0x40,0xf9,0xe4,0x27,0x40,0xf9,0x95,0xfb,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x04,0x01,0x80,0xd2,0x05,0x78,0x64,0xf8,0xbf,0x00,0x00,0xf1,0xe6,0x07,0x9f,0x9a,0xc8,0x01,0x80,0xd2,0x09,0x78,0x68,0xf8,0x3f,0x01,0x00,0xf1,0xea,0x07,0x9f,0x9a,0xcb,0x00,0x0a,0x8a,0xeb,0x0d,0x00,0xb4,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x84,0x8f,0xd2,0x38,0xfd,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0xe5,0xfc,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x00,0x80,0xd2,0xd2,0xfc,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0x08,0x40,0x80,0xd2,0xc8,0xf1,0xa1,0xf2,0x09,0x01,0x06,0xaa,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x99,0xd2,0xe1,0x03,0xa0,0xf2,0xaf,0xfc,0xff,0x97,0xea,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0xe3,0x23,0x40,0xf9,0xe4,0x27,0x40,0xf9,0x1d,0xfb,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x04,0x8f,0xd2,0xca,0xfc,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x00,0x80,0xd2,0x77,0xfc,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0x06,0x40,0x80,0xd2,0xc6,0xf1,0xa0,0xf2,0xc8,0x00,0x05,0xaa,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x99,0xd2,0xe1,0x03,0xa0,0xf2,0x56,0xfc,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x0f,0x40,0xf9,0xe3,0x1f,0x40,0xf9,0xe4,0x23,0x40,0xf9,0xc6,0xfa,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x24,0x00,0xf1,0xe1,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x04,0x8f,0xd2,0x71,0xfc,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x00,0x80,0xd2,0x1e,0xfc,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xc6,0xf1,0xa0,0xd2,0xc8,0x00,0x05,0xaa,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x99,0xd2,0xe1,0x03,0xa0,0xf2,0xfe,0xfb,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x0f,0x40,0xf9,0xe3,0x1f,0x40,0xf9,0xe4,0x23,0x40,0xf9,0x6e,0xfa,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x28,0x00,0xf1,0x81,0x12,0x00,0x54,0x04,0x01,0x80,0xd2,0x05,0x78,0x64,0xf8,0xbf,0x00,0x00,0xf1,0xe6,0x07,0x9f,0x9a,0xc8,0x01,0x80,0xd2,0x09,0x78,0x68,0xf8,0x3f,0x01,0x00,0xf1,0xea,0x07,0x9f,0x9a,0xcb,0x00,0x0a,0x8a,0x0b,0x0a,0x00,0xb4,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x81,0x8f,0xd2,0x0f,0xfc,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0xbc,0xfb,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9b,0xd2,0xe1,0x05,0xa0,0xf2,0xa0,0xfb,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x0e,0x8c,0xd2,0x03,0x7e,0xa1,0xf2,0xe4,0x1b,0x40,0xf9,0x13,0xfa,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x01,0x8f,0xd2,0xc0,0xfb,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9b,0xd2,0xe1,0x03,0xa0,0xf2,0x64,0xfb,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x0f,0x40,0xf9,0x03,0x4e,0x8c,0xd2,0x03,0x7e,0xa0,0xf2,0xe4,0x17,0x40,0xf9,0xd9,0xf9,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x2c,0x00,0xf1,0x01,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x30,0x8f,0xd2,0x84,0xfb,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0x31,0xfb,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x84,0xd2,0xe1,0x01,0xa0,0xf2,0x15,0xfb,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x20,0x83,0xd2,0xc3,0x83,0xa1,0xf2,0xe4,0x1b,0x40,0xf9,0x88,0xf9,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x30,0x00,0xf1,0x61,0x13,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x0f,0x40,0xf9,0x5f,0xfb,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0x85,0x00,0x40,0xd2,0x65,0x00,0x00,0xb4,0x20,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xc1,0x30,0x8f,0xd2,0x11,0xfb,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0xcd,0xfa,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xe6,0xff,0x9f,0xd2,0xe6,0x1f,0xa0,0xf2,0x68,0x00,0x06,0x8a,0x09,0xdd,0x78,0xd3,0xaa,0x00,0x09,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0xb1,0xfa,0xff,0x97,0xeb,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0x0c,0x20,0x83,0xd2,0x0c,0x82,0xa1,0xf2,0x8d,0x01,0x0b,0xaa,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xed,0x33,0x00,0xf9,0xfe,0x37,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x01,0xa0,0xf2,0x86,0xfa,0xff,0x97,0xee,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xeb,0x2b,0x40,0xf9,0xec,0x2f,0x40,0xf9,0xed,0x33,0x40,0xf9,0xfe,0x37,0x40,0xf9,0xff,0xc3,0x01,0x91,0xff,0x03,0x02,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xed,0x33,0x00,0xf9,0xee,0x37,0x00,0xf9,0xfe,0x3b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x27,0x40,0xf9,0xe3,0x33,0x40,0xf9,0xe4,0x37,0x40,0xf9,0xec,0xf8,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x3b,0x40,0xf9,0xff,0x03,0x02,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x34,0x00,0xf1,0xe1,0x0d,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xc1,0x30,0x8f,0xd2,0x88,0xfa,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x44,0xfa,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0x31,0xfa,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0x08,0x20,0x83,0xd2,0x28,0x82,0xa1,0xf2,0x09,0x01,0x06,0xaa,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x01,0xa0,0xf2,0x0e,0xfa,0xff,0x97,0xea,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0xe3,0x23,0x40,0xf9,0xe4,0x27,0x40,0xf9,0x7c,0xf8,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x38,0x00,0xf1,0x01,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x42,0x8e,0xd2,0x27,0xfa,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0xd4,0xf9,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x99,0xd2,0xe1,0x21,0xa0,0xf2,0xb8,0xf9,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0xe3,0x1f,0x9c,0xd2,0xe3,0xff,0xa0,0xf2,0xe4,0x1b,0x40,0xf9,0x2b,0xf8,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x20,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x03,0x00,0x80,0xd2,0x02,0x78,0x63,0xf8,0xc4,0x00,0x80,0xd2,0x03,0x78,0x64,0xf8,0x5f,0x3c,0x00,0xf1,0xe4,0x17,0x9f,0x9a,0x5f,0x40,0x00,0xf1,0xe5,0x17,0x9f,0x9a,0x86,0x00,0x05,0xaa,0x06,0x10,0x00,0xb4,0x04,0x00,0x80,0xd2,0x5f,0x40,0x00,0xf1,0x41,0x00,0x00,0x54,0x84,0x00,0xa0,0xd2,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x47,0x8e,0xd2,0xc7,0xf9,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x72,0xf9,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x00,0x80,0xd2,0x5d,0xf9,0xff,0x97,0xe8,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x09,0x00,0x83,0xd2,0x0a,0x01,0x09,0xaa,0x4b,0x01,0x04,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x01,0xa0,0xf2,0x37,0xf9,0xff,0x97,0xec,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xeb,0x2b,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xfe,0x33,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x1b,0x40,0xf9,0xe3,0x2b,0x40,0xf9,0xe4,0x2f,0x40,0xf9,0xa1,0xf7,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x33,0x40,0xf9,0xff,0xc3,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x44,0x00,0xf1,0x81,0x0c,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x03,0x8f,0xd2,0x2d,0xf9,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0x05,0xe0,0xbf,0xd2,0x86,0x00,0x05,0xaa,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0xf4,0xf8,0xff,0x97,0xe8,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x09,0xc0,0x82,0xd2,0x29,0x00,0xa0,0xf2,0x2a,0x01,0x08,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x99,0xd2,0xe1,0x03,0xa0,0xf2,0xcf,0xf8,0xff,0x97,0xeb,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x1b,0x40,0xf9,0xe2,0x0f,0x40,0xf9,0xe3,0x27,0x40,0xf9,0xe4,0x2b,0x40,0xf9,0x3b,0xf7,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x48,0x00,0xf1,0x61,0x07,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x02,0x8f,0xd2,0xe6,0xf8,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x99,0xd2,0xe1,0x03,0xa0,0xf2,0x8a,0xf8,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x0f,0x40,0xf9,0xe3,0x1f,0x98,0xd2,0xc3,0xf1,0xa0,0xf2,0xe4,0x17,0x40,0xf9,0xff,0xf6,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x4c,0x00,0xf1,0x01,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x30,0x8f,0xd2,0xaa,0xf8,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0x57,0xf8,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x84,0xd2,0xe1,0x01,0xa0,0xf2,0x3b,0xf8,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0xa0,0x82,0xd2,0xc3,0x83,0xa1,0xf2,0xe4,0x1b,0x40,0xf9,0xae,0xf6,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x50,0x00,0xf1,0x01,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x30,0x8f,0xd2,0x59,0xf8,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0x06,0xf8,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x84,0xd2,0xe1,0x01,0xa0,0xf2,0xea,0xf7,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x20,0x8b,0xd2,0xe3,0x83,0xa1,0xf2,0xe4,0x1b,0x40,0xf9,0x5d,0xf6,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x54,0x00,0xf1,0x01,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x30,0x8f,0xd2,0x08,0xf8,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0xb5,0xf7,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x84,0xd2,0xe1,0x01,0xa0,0xf2,0x99,0xf7,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x20,0x83,0xd2,0xc3,0x81,0xa1,0xf2,0xe4,0x1b,0x40,0xf9,0x0c,0xf6,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x58,0x00,0xf1,0x81,0x13,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xc1,0x30,0x8f,0xd2,0xa7,0xf7,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0x25,0x01,0x80,0xd2,0x06,0x78,0x65,0xf8,0xdf,0x00,0x00,0xf1,0x00,0x05,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xc1,0x30,0x81,0xd2,0x92,0xf7,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xac,0xf7,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xc8,0xcc,0x74,0xd3,0xa4,0x00,0x08,0xaa,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x38,0xf7,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0x25,0xf7,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0x08,0x20,0x8b,0xd2,0x28,0x82,0xa1,0xf2,0x09,0x01,0x06,0xaa,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x01,0xa0,0xf2,0x02,0xf7,0xff,0x97,0xea,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0xe3,0x23,0x40,0xf9,0xe4,0x27,0x40,0xf9,0x70,0xf5,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x5c,0x00,0xf1,0xe1,0x04,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x9d,0xd2,0xe1,0x01,0xa0,0xf2,0xcf,0xf6,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x07,0x40,0xf9,0x41,0x32,0x8f,0xd2,0x02,0x00,0x80,0xd2,0x03,0x00,0x96,0xd2,0xe4,0x13,0x40,0xf9,0x47,0xf5,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x60,0x00,0xf1,0xe1,0x04,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x9d,0xd2,0xe1,0x01,0xa0,0xf2,0xa7,0xf6,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x07,0x40,0xf9,0x41,0x32,0x8f,0xd2,0x02,0x00,0x80,0xd2,0x03,0x00,0x86,0xd2,0xe4,0x13,0x40,0xf9,0x1f,0xf5,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x64,0x00,0xf1,0x01,0x05,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x00,0x9d,0xd2,0xe1,0x01,0xa0,0xf2,0x7f,0xf6,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x31,0x8f,0xd2,0x01,0xe0,0xbf,0xf2,0x02,0x00,0x80,0xd2,0x03,0x40,0xa0,0xd2,0xe4,0x13,0x40,0xf9,0xf6,0xf4,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x68,0x00,0xf1,0x61,0x0f,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x35,0x8f,0xd2,0xa1,0xf6,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x4e,0xf6,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0x06,0x00,0xb0,0xd2,0xa8,0x00,0x06,0xaa,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0x37,0xf6,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0x0a,0x20,0x8a,0xd2,0xea,0x03,0xa1,0xf2,0x4b,0x01,0x09,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0xc0,0x83,0xd2,0x41,0x06,0xa0,0xf2,0x10,0xf6,0xff,0x97,0xec,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xeb,0x2b,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xfe,0x33,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x1f,0x40,0xf9,0xe3,0x2b,0x40,0xf9,0xe4,0x2f,0x40,0xf9,0x7a,0xf4,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x33,0x40,0xf9,0xff,0xc3,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x6c,0x00,0xf1,0x61,0x0f,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x35,0x8f,0xd2,0x25,0xf6,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0xd2,0xf5,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0x06,0x00,0xb0,0xd2,0xa8,0x00,0x06,0xaa,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0xbb,0xf5,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0x0a,0x20,0x8a,0xd2,0xea,0x83,0xa1,0xf2,0x4b,0x01,0x09,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0xc0,0x83,0xd2,0x41,0x06,0xa0,0xf2,0x94,0xf5,0xff,0x97,0xec,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xeb,0x2b,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xfe,0x33,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x1f,0x40,0xf9,0xe3,0x2b,0x40,0xf9,0xe4,0x2f,0x40,0xf9,0xfe,0xf3,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x33,0x40,0xf9,0xff,0xc3,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x70,0x00,0xf1,0x01,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x41,0x8e,0xd2,0x9a,0xf5,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x56,0xf5,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9b,0xd2,0xe1,0x03,0xa0,0xf2,0x3a,0xf5,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x0e,0x8c,0xd2,0x03,0x7e,0xa0,0xf2,0xe4,0x1b,0x40,0xf9,0xad,0xf3,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x74,0x00,0xf1,0x01,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x42,0x8e,0xd2,0x58,0xf5,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x05,0xf5,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x99,0xd2,0xe1,0x03,0xa0,0xf2,0xe9,0xf4,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0xe3,0x9f,0x87,0xd2,0xc3,0xf1,0xa0,0xf2,0xe4,0x1b,0x40,0xf9,0x5c,0xf3,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x20,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x03,0x00,0x80,0xd2,0x02,0x78,0x63,0xf8,0xc4,0x00,0x80,0xd2,0x03,0x78,0x64,0xf8,0x5f,0x78,0x00,0xf1,0xe1,0x09,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x44,0x8e,0xd2,0x01,0xf5,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0xae,0xf4,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x98,0xd2,0xe1,0x09,0xa0,0xf2,0x92,0xf4,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x00,0x80,0xd2,0xe4,0x1b,0x40,0xf9,0x06,0xf3,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x7c,0x00,0xf1,0xe1,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x44,0x8e,0xd2,0xb1,0xf4,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x5e,0xf4,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0x06,0x00,0xb0,0xd2,0xa8,0x00,0x06,0xaa,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x98,0xd2,0xe1,0x09,0xa0,0xf2,0x3e,0xf4,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x1f,0x40,0xf9,0x03,0x00,0x80,0xd2,0xe4,0x23,0x40,0xf9,0xae,0xf2,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x80,0x00,0xf1,0xe1,0x09,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x44,0x8e,0xd2,0x59,0xf4,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x06,0xf4,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x98,0xd2,0xe1,0x09,0xa0,0xf2,0xea,0xf3,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x08,0xa0,0xd2,0xe4,0x1b,0x40,0xf9,0x5e,0xf2,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x84,0x00,0xf1,0xc1,0x0c,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x44,0x8e,0xd2,0x09,0xf4,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0xb6,0xf3,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x00,0x80,0xd2,0xa3,0xf3,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x98,0xd2,0xe1,0x09,0xa0,0xf2,0x85,0xf3,0xff,0x97,0xe8,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0xe3,0x1b,0x40,0xf9,0xe4,0x1f,0x40,0xf9,0xf7,0xf1,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x88,0x00,0xf1,0xc1,0x0e,0x00,0x54,0x04,0x00,0x8c,0xd2,0x04,0x7e,0xa0,0xf2,0x7f,0x00,0x00,0xf1,0x40,0x00,0x00,0x54,0xe4,0x03,0x03,0xaa,0x26,0x00,0x80,0xd2,0x08,0x78,0x66,0xf8,0xe9,0x00,0x80,0xd2,0x0a,0x01,0x09,0x8a,0x4b,0xbd,0x70,0xd3,0x6c,0x41,0x8e,0xd2,0x8d,0x01,0x0b,0xaa,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xed,0x33,0x00,0xf9,0xfe,0x37,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0x4b,0xf3,0xff,0x97,0xee,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xeb,0x2b,0x40,0xf9,0xec,0x2f,0x40,0xf9,0xed,0x33,0x40,0xf9,0xfe,0x37,0x40,0xf9,0xff,0xc3,0x01,0x91,0xcf,0x9d,0x68,0xd3,0xa5,0x01,0x0f,0xaa,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x2e,0xf3,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x98,0xd2,0xe1,0x09,0xa0,0xf2,0x10,0xf3,0xff,0x97,0xe8,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x1b,0x40,0xf9,0xe3,0x13,0x40,0xf9,0xe4,0x1f,0x40,0xf9,0x82,0xf1,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x8c,0x00,0xf1,0xe1,0x0b,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x41,0x8e,0xd2,0x2b,0xf3,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0xd8,0xf2,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0x86,0x00,0x80,0xd2,0x08,0x78,0x66,0xf8,0xe9,0x00,0x80,0xd2,0x0a,0x01,0x09,0x8a,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x99,0xd2,0xe1,0x01,0xa0,0xf2,0xb4,0xf2,0xff,0x97,0xeb,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0xe3,0x27,0x40,0xf9,0xe4,0x2b,0x40,0xf9,0x20,0xf1,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x90,0x00,0xf1,0xe1,0x09,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x41,0x8e,0xd2,0xcb,0xf2,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x78,0xf2,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x98,0xd2,0xe1,0x09,0xa0,0xf2,0x5c,0xf2,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x70,0xa0,0xd2,0xe4,0x1b,0x40,0xf9,0xd0,0xf0,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x94,0x00,0xf1,0xe1,0x09,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x41,0x8e,0xd2,0x7b,0xf2,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x28,0xf2,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x98,0xd2,0xe1,0x09,0xa0,0xf2,0x0c,0xf2,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0xf0,0xa0,0xd2,0xe4,0x1b,0x40,0xf9,0x80,0xf0,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x98,0x00,0xf1,0x01,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x48,0x8e,0xd2,0x0d,0xf2,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0xd8,0xf1,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x09,0xa0,0xf2,0xbc,0xf1,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x80,0x82,0xd2,0x03,0x04,0xa0,0xf2,0xe4,0x1b,0x40,0xf9,0x2f,0xf0,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0x9c,0x00,0xf1,0x01,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x60,0x8e,0xd2,0xbc,0xf1,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0x87,0xf1,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x84,0xd2,0xc1,0x09,0xa0,0xf2,0x6b,0xf1,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x20,0x9e,0xd2,0x03,0x04,0xa0,0xf2,0xe4,0x1b,0x40,0xf9,0xde,0xef,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xa0,0x00,0xf1,0xe1,0x09,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x61,0x8e,0xd2,0x6b,0xf1,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0x36,0xf1,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x84,0xd2,0xc1,0x01,0xa0,0xf2,0x1a,0xf1,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x00,0x82,0xd2,0xe4,0x1b,0x40,0xf9,0x8e,0xef,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xa4,0x00,0xf1,0xe1,0x09,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x61,0x8e,0xd2,0x1b,0xf1,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0xe6,0xf0,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x84,0xd2,0xc1,0x01,0xa0,0xf2,0xca,0xf0,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0x03,0x80,0x82,0xd2,0xe4,0x1b,0x40,0xf9,0x3e,0xef,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xa8,0x00,0xf1,0xe1,0x09,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0xf1,0x8f,0xd2,0xe9,0xf0,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xe5,0x03,0x80,0xd2,0x66,0x00,0x05,0x8a,0xc8,0xa8,0x6b,0xd3,0x09,0xe0,0x83,0xd2,0x09,0x00,0xa1,0xf2,0x2a,0x01,0x08,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x84,0xd2,0xc1,0x01,0xa0,0xf2,0x82,0xf0,0xff,0x97,0xeb,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x27,0x40,0xf9,0xc3,0x01,0xa0,0xd2,0xe4,0x2b,0x40,0xf9,0xee,0xee,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xac,0x00,0xf1,0x41,0x08,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x30,0x8f,0xd2,0x99,0xf0,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xe5,0xff,0x9f,0xd2,0x66,0x00,0x05,0x8a,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x01,0xa0,0xf2,0x39,0xf0,0xff,0x97,0xe8,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0x02,0x00,0x80,0xd2,0xe3,0x1b,0x40,0xf9,0xe4,0x1f,0x40,0xf9,0xab,0xee,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xb0,0x00,0xf1,0xe1,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xfe,0x13,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x71,0x8e,0xd2,0x47,0xf0,0xff,0x97,0xe4,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x13,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x03,0xf0,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xe6,0xff,0x9f,0xd2,0x68,0x00,0x06,0x8a,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x01,0xa0,0xf2,0xe3,0xef,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0xe2,0x17,0x40,0xf9,0xe3,0x1f,0x40,0xf9,0xe4,0x23,0x40,0xf9,0x53,0xee,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xb4,0x00,0xf1,0x21,0x06,0x00,0x54,0xa4,0x29,0x8f,0xd2,0x25,0x01,0x80,0xd2,0x06,0x78,0x65,0xf8,0xdf,0x00,0x00,0xf1,0x40,0x00,0x00,0x54,0xa4,0x29,0x81,0xd2,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9d,0xd2,0xe1,0x01,0xa0,0xf2,0xac,0xef,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x13,0x40,0xf9,0x02,0x00,0x80,0xd2,0x03,0x70,0xa0,0xd2,0xe4,0x17,0x40,0xf9,0x22,0xee,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x20,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0xc3,0x00,0x80,0xd2,0x02,0x78,0x63,0xf8,0x44,0x04,0x00,0xd1,0xe5,0xff,0x9f,0xd2,0xe5,0xff,0xbf,0xf2,0x83,0x00,0x05,0x8a,0x64,0xfc,0x46,0xd3,0x05,0x70,0xa0,0xd2,0x06,0x00,0xb0,0xd2,0x7f,0x00,0x06,0xeb,0xa3,0x00,0x00,0x54,0x06,0x80,0xbf,0xd2,0x84,0x00,0x06,0xaa,0xe5,0xff,0x9f,0xd2,0x65,0x70,0xa0,0xf2,0xe8,0x00,0x80,0xd2,0x06,0x78,0x68,0xf8,0xdf,0x00,0x00,0xf1,0xa1,0x01,0x00,0x54,0x06,0x40,0x9d,0xd2,0xe6,0x01,0xa0,0xf2,0x5f,0x00,0x00,0xf1,0xe8,0x17,0x9f,0x9a,0x29,0x01,0x80,0xd2,0x0a,0x78,0x69,0xf8,0x5f,0x01,0x00,0xf1,0xeb,0x17,0x9f,0x9a,0x0c,0x01,0x0b,0x8a,0x6c,0x00,0x00,0xb4,0x06,0x00,0x98,0xd2,0xe6,0x01,0xa0,0xf2,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xc7,0xef,0xff,0x97,0xe9,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0x2a,0xcd,0x74,0xd3,0xeb,0x28,0x81,0xd2,0x6c,0x01,0x0a,0xaa,0xed,0x07,0x80,0xd2,0x6e,0x00,0x0d,0x8a,0xcf,0xb5,0x6e,0xd3,0x88,0x01,0x0f,0xaa,0x89,0xf4,0x7e,0xd3,0xea,0xff,0x9f,0xd2,0xea,0xff,0xbf,0xf2,0x2b,0x01,0x0a,0x8a,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x1f,0x40,0xf9,0xe2,0x2b,0x40,0xf9,0xe3,0x17,0x40,0xf9,0xe4,0x1b,0x40,0xf9,0xc3,0xed,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x03,0x00,0x80,0xd2,0x02,0x78,0x63,0xf8,0xc4,0x00,0x80,0xd2,0x03,0x78,0x64,0xf8,0x65,0x01,0x80,0xd2,0x04,0x78,0x65,0xf8,0x5f,0xb8,0x00,0xf1,0x41,0x02,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0x8f,0xff,0xff,0x97,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xc0,0x03,0x5f,0xd6,0x5f,0xbc,0x00,0xf1,0xe1,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x61,0x8e,0xd2,0x32,0xef,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0xfb,0xee,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x84,0xd2,0xc1,0x01,0xa0,0xf2,0xdd,0xee,0xff,0x97,0xe8,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x1b,0x40,0xf9,0x03,0x00,0x81,0xd2,0xe4,0x1f,0x40,0xf9,0x4f,0xed,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xc0,0x00,0xf1,0x61,0x05,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x9d,0xd2,0xe1,0x01,0xa0,0xf2,0xad,0xee,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xa1,0x63,0x8f,0xd2,0x02,0x00,0x80,0xd2,0x23,0x00,0xa0,0xd2,0xe4,0x17,0x40,0xf9,0x23,0xed,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xc4,0x00,0xf1,0x21,0x08,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x30,0x8f,0xd2,0xcc,0xee,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x00,0x85,0xd2,0xc1,0x01,0xa0,0xf2,0x6e,0xee,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x1f,0x80,0xd2,0x03,0x00,0x81,0xd2,0x03,0x00,0xa1,0xf2,0xe4,0x1b,0x40,0xf9,0xe1,0xec,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xc8,0x00,0xf1,0x01,0x0b,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x31,0x8f,0xd2,0x7b,0xee,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0x35,0xee,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x01,0xa0,0xf2,0x17,0xee,0xff,0x97,0xe8,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x1b,0x40,0xf9,0xe3,0x1f,0x81,0xd2,0x03,0x00,0xa1,0xf2,0xe4,0x1f,0x40,0xf9,0x88,0xec,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xcc,0x00,0xf1,0x01,0x17,0x00,0x54,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x00,0x80,0xd2,0xee,0xed,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xc8,0xbc,0x70,0xd3,0x49,0x42,0x8e,0xd2,0x2a,0x01,0x08,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0x82,0x01,0x80,0xd2,0xdd,0xed,0xff,0x97,0xeb,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0x6c,0x9d,0x68,0xd3,0x45,0x01,0x0c,0xaa,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0xa2,0x01,0x80,0xd2,0xc2,0xed,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xe8,0x1f,0x80,0xd2,0x69,0x00,0x08,0x8a,0x2a,0xdd,0x78,0xd3,0xcb,0xf1,0xa0,0xd2,0x6c,0x01,0x0a,0xaa,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xfe,0x33,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x00,0x80,0xd2,0x98,0xed,0xff,0x97,0xed,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xeb,0x2b,0x40,0xf9,0xec,0x2f,0x40,0xf9,0xfe,0x33,0x40,0xf9,0xff,0xc3,0x01,0x91,0x8e,0x01,0x0d,0xaa,0xff,0x03,0x02,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xed,0x33,0x00,0xf9,0xee,0x37,0x00,0xf9,0xfe,0x3b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x99,0xd2,0xe1,0x03,0xa0,0xf2,0x6c,0xed,0xff,0x97,0xef,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xeb,0x2b,0x40,0xf9,0xec,0x2f,0x40,0xf9,0xed,0x33,0x40,0xf9,0xee,0x37,0x40,0xf9,0xfe,0x3b,0x40,0xf9,0xff,0x03,0x02,0x91,0xff,0x03,0x02,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xed,0x33,0x00,0xf9,0xee,0x37,0x00,0xf9,0xef,0x3b,0x00,0xf9,0xfe,0x3f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x1b,0x40,0xf9,0xe3,0x37,0x40,0xf9,0xe4,0x3b,0x40,0xf9,0xd0,0xeb,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x3f,0x40,0xf9,0xff,0x03,0x02,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xd0,0x00,0xf1,0xc1,0x13,0x00,0x54,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x00,0x80,0xd2,0x35,0xed,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xc8,0xbc,0x70,0xd3,0x29,0x43,0x8e,0xd2,0x2a,0x01,0x08,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0x82,0x01,0x80,0xd2,0x24,0xed,0xff,0x97,0xeb,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0x6c,0x9d,0x68,0xd3,0x45,0x01,0x0c,0xaa,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0xa2,0x01,0x80,0xd2,0x09,0xed,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x00,0x80,0xd2,0xe9,0xec,0xff,0x97,0xe8,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x09,0xc0,0x80,0xd2,0x2a,0x01,0x08,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x99,0xd2,0xe1,0x03,0xa0,0xf2,0xc5,0xec,0xff,0x97,0xeb,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x1b,0x40,0xf9,0xe3,0x27,0x40,0xf9,0xe4,0x2b,0x40,0xf9,0x31,0xeb,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xd4,0x00,0xf1,0xc1,0x13,0x00,0x54,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x00,0x80,0xd2,0x96,0xec,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xc8,0xbc,0x70,0xd3,0xe9,0x44,0x8e,0xd2,0x2a,0x01,0x08,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0x82,0x01,0x80,0xd2,0x85,0xec,0xff,0x97,0xeb,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0x6c,0x9d,0x68,0xd3,0x45,0x01,0x0c,0xaa,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x61,0x00,0x80,0xd2,0xa2,0x01,0x80,0xd2,0x6a,0xec,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x00,0x80,0xd2,0x4a,0xec,0xff,0x97,0xe8,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0xc9,0xf1,0xa0,0xd2,0x2a,0x01,0x08,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x99,0xd2,0xe1,0x03,0xa0,0xf2,0x26,0xec,0xff,0x97,0xeb,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x1b,0x40,0xf9,0xe3,0x27,0x40,0xf9,0xe4,0x2b,0x40,0xf9,0x92,0xea,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xd8,0x00,0xf1,0x21,0x0d,0x00,0x54,0x7f,0x08,0x00,0xf1,0xe5,0x27,0x9f,0x9a,0x06,0x00,0xb0,0xd2,0x7f,0x00,0x06,0xeb,0xe8,0x37,0x9f,0x9a,0xa9,0x00,0x08,0xaa,0x9f,0x40,0x00,0xf1,0xea,0x37,0x9f,0x9a,0x2b,0x01,0x0a,0xaa,0x6b,0x00,0x00,0xb4,0x20,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x4b,0xec,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xc8,0xcc,0x74,0xd3,0xa9,0x28,0x81,0xd2,0x2a,0x01,0x08,0xaa,0x8b,0xbc,0x70,0xd3,0x45,0x01,0x0b,0xaa,0x66,0x04,0x00,0xd1,0x08,0x02,0x80,0xd2,0xc9,0x7c,0x08,0x9b,0xea,0xff,0x9f,0xd2,0xea,0xff,0xbf,0xf2,0x2b,0x01,0x0a,0x8a,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9c,0xd2,0xe1,0x01,0xa0,0xf2,0xbf,0xeb,0xff,0x97,0xec,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xeb,0x2b,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xfe,0x33,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x2b,0x40,0xf9,0x03,0x40,0x80,0xd2,0x03,0x70,0xa0,0xf2,0xe4,0x2f,0x40,0xf9,0x28,0xea,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x33,0x40,0xf9,0xff,0xc3,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xdc,0x00,0xf1,0x81,0x09,0x00,0x54,0x9f,0x40,0x00,0xf1,0x63,0x00,0x00,0x54,0x20,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xe9,0xeb,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xc8,0xcc,0x74,0xd3,0x29,0x28,0x81,0xd2,0x2a,0x01,0x08,0xaa,0x8b,0xbc,0x70,0xd3,0x45,0x01,0x0b,0xaa,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x9d,0xd2,0xe1,0x01,0xa0,0xf2,0x68,0xeb,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0x02,0x00,0x80,0xd2,0x03,0x40,0x80,0xd2,0x03,0x70,0xa0,0xf2,0xe4,0x1b,0x40,0xf9,0xdb,0xe9,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xe0,0x00,0xf1,0xc1,0x0f,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x0f,0x40,0xf9,0xaf,0xeb,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xa6,0x00,0x40,0xd2,0x66,0x00,0x00,0xb4,0x20,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x30,0x8f,0xd2,0x6e,0xeb,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0x19,0xeb,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xe8,0xff,0x9f,0xd2,0xe8,0x1f,0xa0,0xf2,0x69,0x00,0x08,0x8a,0x2a,0xdd,0x78,0xd3,0xcb,0x00,0x0a,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x84,0xd2,0xe1,0x01,0xa0,0xf2,0xf2,0xea,0xff,0x97,0xec,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xeb,0x2b,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xfe,0x33,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x2b,0x40,0xf9,0x03,0x60,0x83,0xd2,0xc3,0x83,0xa1,0xf2,0xe4,0x2f,0x40,0xf9,0x5b,0xe9,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x33,0x40,0xf9,0xff,0xc3,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xe4,0x00,0xf1,0xc1,0x0f,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x0f,0x40,0xf9,0x30,0xeb,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xa6,0x00,0x40,0xd2,0x66,0x00,0x00,0xb4,0x20,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x21,0x30,0x8f,0xd2,0xef,0xea,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xa1,0x00,0x80,0xd2,0x9a,0xea,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xe8,0xff,0x9f,0xd2,0xe8,0x1f,0xa0,0xf2,0x69,0x00,0x08,0x8a,0x2a,0xdd,0x78,0xd3,0xcb,0x00,0x0a,0xaa,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xfe,0x2f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x40,0x84,0xd2,0xe1,0x01,0xa0,0xf2,0x73,0xea,0xff,0x97,0xec,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xeb,0x2b,0x40,0xf9,0xfe,0x2f,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0xc3,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xeb,0x2b,0x00,0xf9,0xec,0x2f,0x00,0xf9,0xfe,0x33,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x2b,0x40,0xf9,0x03,0xa0,0x83,0xd2,0xc3,0x83,0xa1,0xf2,0xe4,0x2f,0x40,0xf9,0xdc,0xe8,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x33,0x40,0xf9,0xff,0xc3,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xe8,0x00,0xf1,0x41,0x0a,0x00,0x54,0x05,0x10,0xa0,0xd2,0x7f,0x00,0x05,0xeb,0x63,0x00,0x00,0x54,0x20,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x81,0x30,0x8f,0xd2,0x80,0xea,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xe6,0xff,0x9f,0xd2,0xe6,0x1f,0xa0,0xf2,0x68,0x00,0x06,0x8a,0x09,0xdd,0x78,0xd3,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xfe,0x27,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x00,0x9d,0xd2,0xe1,0x01,0xa0,0xf2,0x1b,0xea,0xff,0x97,0xea,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xfe,0x27,0x40,0xf9,0xff,0x43,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x23,0x40,0xf9,0x03,0x80,0x81,0xd2,0xe4,0x27,0x40,0xf9,0x89,0xe8,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x5f,0xec,0x00,0xf1,0xe1,0x0a,0x00,0x54,0xff,0xc3,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xfe,0x17,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x61,0x8e,0xd2,0x14,0xea,0xff,0x97,0xe5,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x17,0x40,0xf9,0xff,0xc3,0x00,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xfe,0x1b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x41,0x00,0x80,0xd2,0xdd,0xe9,0xff,0x97,0xe6,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xfe,0x1b,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x03,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xfe,0x1f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0x01,0x80,0x84,0xd2,0xc1,0x01,0xa0,0xf2,0xbf,0xe9,0xff,0x97,0xe8,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xfe,0x1f,0x40,0xf9,0xff,0x03,0x01,0x91,0xff,0x43,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xfe,0x23,0x00,0xf9,0xe0,0x07,0x40,0xf9,0xe1,0x17,0x40,0xf9,0xe2,0x1b,0x40,0xf9,0x03,0x80,0x81,0xd2,0xe4,0x1f,0x40,0xf9,0x31,0xe8,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xfe,0x23,0x40,0xf9,0xff,0x43,0x01,0x91,0x00,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x20,0x00,0x80,0xd2,0xc0,0x03,0x5f,0xd6,0x03,0x00,0x80,0xd2,0x02,0x78,0x63,0xf8,0x5f,0x3c,0x00,0xf1,0xc2,0x01,0x00,0x54,0xff,0x83,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xfe,0x0f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0x0b,0xea,0xff,0x97,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xfe,0x0f,0x40,0xf9,0xff,0x83,0x00,0x91,0xc0,0x03,0x5f,0xd6,0x5f,0x78,0x00,0xf1,0xc2,0x01,0x00,0x54,0xff,0x83,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xfe,0x0f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xeb,0xef,0xff,0x97,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xfe,0x0f,0x40,0xf9,0xff,0x83,0x00,0x91,0xc0,0x03,0x5f,0xd6,0x5f,0xb8,0x00,0xf1,0xc2,0x01,0x00,0x54,0xff,0x83,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xfe,0x0f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xab,0xf4,0xff,0x97,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xfe,0x0f,0x40,0xf9,0xff,0x83,0x00,0x91,0xc0,0x03,0x5f,0xd6,0xff,0x83,0x00,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xfe,0x0f,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0x39,0xfa,0xff,0x97,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xfe,0x0f,0x40,0xf9,0xff,0x83,0x00,0x91,0xc0,0x03,0x5f,0xd6,0x03,0x00,0x80,0xd2,0x7f,0x10,0x00,0xf1,0xc2,0x03,0x00,0x54,0x7f,0x10,0x00,0xf1,0x02,0x04,0x00,0x54,0x44,0x78,0x63,0xf8,0x06,0x02,0x80,0xd2,0x28,0x7c,0x06,0x9b,0x89,0x00,0x80,0xd2,0x6a,0x7c,0x09,0x9b,0x05,0x01,0x0a,0x8b,0x06,0x00,0x80,0xd2,0xdf,0x10,0x00,0xf1,0x22,0x02,0x00,0x54,0xa8,0x00,0x06,0x8b,0x09,0x01,0x80,0xd2,0xca,0x7c,0x09,0x9b,0x5f,0x01,0x01,0xf1,0xc2,0x02,0x00,0x54,0x8b,0x24,0xca,0x9a,0xec,0x1f,0x80,0xd2,0x6d,0x01,0x0c,0x8a,0xae,0xfd,0x48,0xd3,0xee,0x01,0x00,0xb5,0x0f,0x00,0x88,0xd2,0x1f,0x01,0x0f,0xeb,0x42,0x01,0x00,0x54,0x0d,0x68,0x28,0x38,0xc6,0x04,0x00,0x91,0xef,0xff,0xff,0x17,0x63,0x04,0x00,0x91,0xe2,0xff,0xff,0x17,0xc0,0x03,0x5f,0xd6,0xe0,0x03,0x07,0xaa,0xf0,0x08,0x40,0xf9,0x00,0x02,0x1f,0xd6,0x61,0x00,0x80,0xd2,0xfc,0xff,0xff,0x17,0xa1,0x00,0x80,0xd2,0xfa,0xff,0xff,0x17,0xe1,0x00,0x80,0xd2,0xf8,0xff,0xff,0x17,0x06,0x00,0x80,0xd2,0xff,0x03,0x02,0xd1,0xe5,0x03,0x00,0x91,0x08,0x00,0x80,0xd2,0xa6,0x78,0x28,0xf8,0x08,0x05,0x00,0x91,0x1f,0x41,0x00,0xf1,0xa3,0xff,0xff,0x54,0x08,0x00,0x80,0xd2,0xff,0x83,0x00,0xd1,0xe6,0x03,0x00,0x91,0x09,0x00,0x80,0xd2,0xc8,0x78,0x29,0xf8,0x29,0x05,0x00,0x91,0x3f,0x11,0x00,0xf1,0xa3,0xff,0xff,0x54,0x5f,0x00,0x10,0xf1,0x89,0x00,0x00,0x54,0x00,0x00,0x80,0xd2,0xff,0x83,0x02,0x91,0xc0,0x03,0x5f,0xd6,0xe8,0x03,0x02,0xaa,0x7f,0x00,0x00,0xf1,0x20,0x01,0x00,0x54,0x49,0x1c,0x00,0x91,0x0a,0x01,0x80,0xd2,0x2b,0x09,0xca,0x9a,0x0c,0x01,0x80,0xd2,0x68,0x7d,0x0c,0x9b,0x1f,0x81,0x00,0xf1,0x42,0x00,0x00,0x54,0x08,0x04,0x80,0xd2,0x09,0x00,0x80,0xd2,0x0a,0x00,0x80,0xd2,0x3f,0x01,0x08,0xeb,0x82,0x10,0x00,0x54,0x0b,0x48,0x88,0xd2,0xeb,0x01,0xa0,0xf2,0x5f,0x01,0x0b,0xeb,0xe2,0x10,0x00,0x54,0x4a,0x05,0x00,0x91,0x3f,0x01,0x02,0xeb,0x02,0x08,0x00,0x54,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x03,0x40,0xf9,0xe1,0x23,0x40,0xf9,0xe2,0x07,0x40,0xf9,0xe3,0x17,0x40,0xf9,0xa9,0xe7,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x17,0x40,0xf9,0xe1,0x1b,0x40,0xf9,0x44,0xff,0xff,0x97,0xeb,0x03,0x00,0xaa,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0x7f,0x01,0x00,0xf1,0x80,0x00,0x00,0x54,0x00,0x00,0x80,0xd2,0xff,0x83,0x02,0x91,0xc0,0x03,0x5f,0xd6,0x20,0x00,0x00,0x14,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x1b,0x40,0xf9,0x01,0x23,0x8f,0xd2,0x02,0x00,0x80,0xd2,0x03,0x00,0x80,0xd2,0x04,0x00,0x98,0xd2,0xe4,0x01,0xa0,0xf2,0x43,0xe7,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0xff,0x83,0x01,0xd1,0xe0,0x03,0x00,0xf9,0xe1,0x07,0x00,0xf9,0xe2,0x0b,0x00,0xf9,0xe3,0x0f,0x00,0xf9,0xe4,0x13,0x00,0xf9,0xe5,0x17,0x00,0xf9,0xe6,0x1b,0x00,0xf9,0xe8,0x1f,0x00,0xf9,0xe9,0x23,0x00,0xf9,0xea,0x27,0x00,0xf9,0xfe,0x2b,0x00,0xf9,0xe0,0x13,0x40,0xf9,0xe1,0x23,0x40,0xf9,0xe2,0x1b,0x40,0xf9,0x3e,0xff,0xff,0x97,0xe0,0x03,0x40,0xf9,0xe1,0x07,0x40,0xf9,0xe2,0x0b,0x40,0xf9,0xe3,0x0f,0x40,0xf9,0xe4,0x13,0x40,0xf9,0xe5,0x17,0x40,0xf9,0xe6,0x1b,0x40,0xf9,0xe8,0x1f,0x40,0xf9,0xe9,0x23,0x40,0xf9,0xea,0x27,0x40,0xf9,0xfe,0x2b,0x40,0xf9,0xff,0x83,0x01,0x91,0x29,0x05,0x00,0x91,0x7c,0xff,0xff,0x17,0x09,0x02,0x80,0xd2,0x00,0x7d,0x09,0x9b,0xff,0x83,0x02,0x91,0xc0,0x03,0x5f,0xd6,0xe0,0x03,0x07,0xaa,0xf0,0x08,0x40,0xf9,0x00,0x02,0x1f,0xd6,0x81,0x00,0x80,0xd2,0xfc,0xff,0xff,0x17\n.globl ombr_entry_bw_enc_sm121\n.hidden ombr_entry_bw_enc_sm121\nombr_entry_bw_enc_sm121:\nhint #34\nb ombr_code_bw_enc_sm121\n.previous\n"); -extern const unsigned char ombr_entry_bw_enc_sm121[] __attribute__((visibility("hidden"))); -__attribute__((visibility("default"))) uint32_t omega_bw_enc_sm121(uint64_t *result, const void *o_ins, uint64_t o_ins_len, const void *o_phys, uint64_t o_phys_len, uint64_t o_n, uint64_t o_pad, void *o_code, uint64_t o_code_len) -{ - ombr_span sp[7]; - unsigned ns = 0; - uint64_t a[6] = {0}; - if (ombr_span_add(sp, &ns, result, 1u, 1u, 8u, 1)) - return OMEGA_BAD_ARG; - if (ombr_span_add(sp, &ns, o_ins, o_ins_len, 8192u, 8u, 0)) - return OMEGA_BAD_ARG; - a[0] = (uint64_t)(uintptr_t)o_ins; - if (ombr_span_add(sp, &ns, o_phys, o_phys_len, 288u, 8u, 0)) - return OMEGA_BAD_ARG; - a[1] = (uint64_t)(uintptr_t)o_phys; - a[2] = o_n; - a[3] = o_pad; - if (ombr_span_add(sp, &ns, o_code, o_code_len, 16384u, 1u, 1)) - return OMEGA_BAD_ARG; - a[4] = (uint64_t)(uintptr_t)o_code; - if (ombr_overlap(sp, ns)) - return OMEGA_BAD_ARG; - return ombr_run(ombr_entry_bw_enc_sm121, a, result, 1); -} /* Generated by omega-bridge src/native.om: the definitions of the C API declared in * omega_api_decl.h (output apic). Each calls omega2_ and calls abort() on a nonzero status. * Regenerate it; do not edit it. */ diff --git a/src/omega_om_units.ident b/src/omega_om_units.ident index 66dcc4abc..59fa7f1f4 100644 --- a/src/omega_om_units.ident +++ b/src/omega_om_units.ident @@ -1,3 +1,2 @@ omega-ident 1 unit=sha256_om2 abi=2 profile=OM-2 src=dbf002dd6aa36585632b9d01d98ac3f0bd2fa0f0475082940de53638847994bb omc=be8c51301307555254fc59e351d281aae1aa096d91521777e33a41c8b446448a path=om/sha256/sha256-om2.om omega-ident 1 unit=b3unit abi=1 profile=OM-1 src=124c19e6343133d45146e565eeb9307bbe7350a07fca01a736d6da8c3e5d4863 omc=be8c51301307555254fc59e351d281aae1aa096d91521777e33a41c8b446448a path=om/blake3/b3unit.om -omega-ident 1 unit=bw_enc_sm121 abi=1 profile=OM-1 src=12369bf1e383e79a4926e7758aaf5f3f778f2945c91327ce0aa570babffc05e6 omc=be8c51301307555254fc59e351d281aae1aa096d91521777e33a41c8b446448a path=om/encoder/bw_enc_sm121.om diff --git a/src/omega_runtime_api.h b/src/omega_runtime_api.h deleted file mode 100644 index 89e2acbee..000000000 --- a/src/omega_runtime_api.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef OMEGA_RUNTIME_API_H -#define OMEGA_RUNTIME_API_H -/* - * Omega Runtime API version (R1, omega-mv#594). Defines the version and nothing else; includes nothing. - * - * The API is the set of entries listed in docs/runtime/omega_runtime_api.manifest and described in - * docs/runtime/API.md, which also states the compatibility rule: - * MINOR goes up when something is added; MAJOR goes up when a STABLE entry is removed, renamed or changes - * signature, layout, constant value or documented behaviour. MAJOR 0 is the first, written-down version. - * tools/runtime_api_check.sh (make test-runtime-api) fails when this header, the manifest and API.md disagree. - */ -#define OMEGA_RUNTIME_API_VERSION_MAJOR 0 -#define OMEGA_RUNTIME_API_VERSION_MINOR 1 -/* One number for #if comparisons: (MAJOR << 16) | MINOR. */ -#define OMEGA_RUNTIME_API_VERSION ((OMEGA_RUNTIME_API_VERSION_MAJOR << 16) | OMEGA_RUNTIME_API_VERSION_MINOR) -#endif diff --git a/src/omega_sm121_disasm.c b/src/omega_sm121_disasm.c deleted file mode 100644 index 17a1ef14b..000000000 --- a/src/omega_sm121_disasm.c +++ /dev/null @@ -1,296 +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" }, - { 0x000000000000723cull, 0x00001800ull, "HMMA.16816.F32 %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" }, - /* the .STRONG.SYS forms (and ATOMG) are the ones the bw_hazard_test sweep builds (decode_attn); only the 32-bit - * size and the PT predicate seen there are rows, every other bit pattern stays reported, not guessed. The sweep - * has these forms only with a zero offset, so their %o is checked by the plain LDG/STG rows above (same opcode, - * same offset field, nonzero offsets throughout the corpus), not by a STRONG listing of its own */ - { 0x0000000000007981ull, 0x0c1f5900ull, "LDG.E.STRONG.SYS %d, desc[%B][%a.64%o]" }, - { 0x0000000000007986ull, 0x0c115900ull, "STG.E.STRONG.SYS desc[%C][%a.64%o], %b" }, - { 0x80000000000079a8ull, 0x081f5100ull, "ATOMG.E.ADD.STRONG.SYS PT, %d, desc[%C][%a.64], %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^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 <= 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 2cfdee8e1..c441db0b4 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -272,7 +272,7 @@ }, { "digest": "bd7d40c4941f8820fb03ff558b323e41a80edf02caf0068baf7307ed855dcaa5", - "last_commit": "1b9e0b553", + "last_commit": "f5c9bd89a", "name": "runtime", "purpose": "Directory tests/runtime. Purpose not yet described by a human." }, @@ -308,14 +308,14 @@ } ], "children_root": "sha256:de9b552720cd8a79c9152deabd8c8087c756688d8a849af5e987373f2d0c512d", - "compiled_at": "2026-10-31T12:25:49Z", + "compiled_at": "2026-10-31T13:05:45Z", "compiler": "crumb-compile/1", - "digest": "sha256:0a1bedfebbcc0e923a70af1b3537bc5af1f45a79c527e517aace0bf4c5287dcf", + "digest": "sha256:42ce588746fbb9982a309142a06639206247d5fada0e859b804eb7e7b17a164a", "evidence_files": 74, "evidence_root": "sha256:9aa38bf7dcfa5eb3499356a0a2a1dd7704fedfae2d16822a7c9e1400f3a72723", - "files": 2047, - "generated_at_commit": "1b9e0b5530e5956f8967940fb001d632f0e61859", - "source_tree": "sha256:642df6ca0dad60e320b57318643b02c41ac8bf9b6cfef4a3a03586260d8f289b" + "files": 1992, + "generated_at_commit": "ef2aba1488304ba91c342d80a54b4535f255711f", + "source_tree": "sha256:ee316429d6555989325a5cc255ef433df1c7352e12c8f2e8c946cacf365f3391" }, "owner_lane": "", "provenance": { diff --git a/tests/bw_encode_control_test.c b/tests/bw_encode_control_test.c deleted file mode 100644 index 46a67b11d..000000000 --- a/tests/bw_encode_control_test.c +++ /dev/null @@ -1,50 +0,0 @@ -/* - * bw_encode_control_test: every opcode the encoder accepts must carry the control word the emitter scheduled - * (BlackwellIRInsn.control: stall, yield, write / read scoreboards, wait mask) into the instruction's top word - * (omega-mv#545, 2026-10-18). The encoder's golden-word checks compare words 0..2 only, so an opcode that wrote a - * fixed word 3 kept its own wait mask and dropped the emitter's: IADD3 always waited on scoreboard 4 instead of the - * Q loads' scoreboards, the next MOVs overwrote the loads' address registers while loads were still queued, and the - * prefill attention faulted (Xid 13, Invalid Address Space) on the chip. - * - * Host only, no device. Exit 0 when every accepted opcode honours the control word. - */ -#include "omega_blackwell_codegen.h" -#include -#include - -#define CTL_FIELD 0x03fffe00u /* stall 9..12, yield 13, wbar 14..16, rbar 17..19, wait 20..25 */ - -static const uint32_t sentinels[] = { - (3u << 9) | (5u << 14) | (4u << 17) | (0x2au << 20), /* stall 3, wbar 5, rbar 4, wait 0x2a */ - (12u << 9) | 0x2000u | (2u << 14) | (7u << 17) | (0x15u << 20), /* stall 12, yield, wbar 2, rbar none, wait 0x15 */ -}; - -int main(void) { - int checked = 0, refused = 0, bad = 0; - for (int op = 0; op <= (int)BW_IR_MUFU_LG2; op++) { - for (int form = 0; form < 4; form++) { - const int pred = form & 1, uni = form >> 1; - int accepted_any = 0; - for (unsigned s = 0; s < sizeof sentinels / sizeof sentinels[0]; s++) { - BlackwellIRInsn in; - memset(&in, 0, sizeof in); - in.op = (BlackwellIROpcode)op; - in.dst_vreg = 4; in.src1_vreg = 6; in.src2_vreg = 8; in.src3_vreg = 10; in.ureg = 4; - in.imm = 2; in.predicate_p0 = pred != 0; in.is_uniform = uni != 0; - in.control = sentinels[s]; - uint32_t w[4] = { 0, 0, 0, 0 }; - if (omega_blackwell_encode_one(&in, w) != 0) continue; - accepted_any = 1; - checked++; - if ((w[3] & CTL_FIELD) != (sentinels[s] & CTL_FIELD)) { - bad++; - printf("FAIL: op %d%s%s: control 0x%08x encoded as 0x%08x\n", op, pred ? " (@P0)" : "", uni ? " (uniform)" : "", sentinels[s], w[3]); - } - } - if (!accepted_any && form == 0) refused++; - } - } - printf("bw_encode_control_test: %d encodings checked, %d opcodes refused (no operands), %d dropped the control word: %s\n", - checked, refused, bad, bad ? "FAIL" : "PASS"); - return bad ? 1 : 0; -} diff --git a/tests/bw_hazard_test.c b/tests/bw_hazard_test.c deleted file mode 100644 index e052b0904..000000000 --- a/tests/bw_hazard_test.c +++ /dev/null @@ -1,646 +0,0 @@ -/* bw_hazard_test.c: the static scoreboard hazard checker (src/omega_bw_hazard.c, omega-mv#554) run over every kernel - * Omega generates, plus its own proofs. Host only, no device. - * - * 1. decoder vs encoder: every IR op encoded with known registers decodes to exactly those registers; - * 2. red receipt: the pre-#553 head_dim 256 attend kernel (the bytes that faulted on the GB10) fails with WAR on - * R22/R23 at IR 88/89; the same kernel after the encoder fix passes; the fixed kernel with the one lost wait - * cleared fails again; - * 3. negative controls: small encoded programs with one hazard each are caught, the same programs with the wait - * in place pass, and an undecodable word is "not checked", never clean; - * 4. sweep: every generator over its accepted shapes (production kernels, mutant 0), encoded and patched as the - * launchers do; every finding is printed and must be on the triaged list below. - * - * --disasm: additionally cross-checks the decoder against Omega's own sm_121 disassembler (src/omega_sm121_disasm.c, - * in process) on every distinct kernel: the base registers each instruction names must be the ones the decoder found. - * The disassembler is checked word for word against nvdisasm by test-sm121dis; this test never calls nvdisasm (bar C6 - * of docs/OMEGA.md: every check that called nvdisasm calls ours). */ -#include "omega_bw_hazard.h" -#include "omega_sm121_disasm.h" -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_codegen_moe.h" -#include "omega_blackwell_codegen_moe2.h" -#include "omega_blackwell_codegen_bf16.h" -#include "omega_blackwell_codegen_router.h" -#include "omega_blackwell_codegen_attn.h" -#include "omega_blackwell_codegen_gemm.h" -#include "omega_blackwell_codegen_tern.h" -#include "omega_blackwell_codegen_tc.h" -#include "omega_blackwell_codegen_tc2.h" -#include "omega_blackwell_codegen_qg.h" -#include "omega_blackwell_codegen_qmma.h" -#include "omega_blackwell_codegen_pf.h" -#include "omega_blackwell_codegen_pfhost.h" -#include "omega_blackwell_codegen_dec.h" -#include "omega_blackwell_codegen_pattn.h" -#include "omega_gpu_attention_api.h" -#include "omega_gpu_elementwise_api.h" -#include "omega_gpu_prefill_attn_api.h" -#include -#include -#include -#include -#include - -static int g_checks, g_failed, g_disasm; -static const char *g_dump_dir; /* --dump DIR: write each distinct kernel with findings as DIR/-.bin (triage) */ -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static BlackwellIRProgram g_prog; -static uint8_t g_code[OMEGA_BW_CODE_CAP_MAX + 4096]; -static OmegaBwHazardReport g_rep; - -#define CW(stall, wbar, rbar, wait) \ - (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) - -/* ------------------------------------------------------------------------------------------- 1. decoder vs encoder */ -typedef struct { int w[3]; int r[6]; } Ops; /* entries: reg | n << 8 | uniform << 12, 0 terminates */ -#define G(reg, n) ((reg) | (n) << 8) -#define U(reg, n) ((reg) | (n) << 8 | 1 << 12) - -static int has(const OmegaBwOperand *o, unsigned cnt, int want) { - for (unsigned i = 0; i < cnt; i++) - if (o[i].reg == (want & 0xff) && o[i].n == ((want >> 8) & 0xf) && o[i].uniform == ((want >> 12) & 1)) return 1; - return 0; -} -static int count(const int *a, int max) { int n = 0; while (n < max && a[n]) n++; return n; } - -static void test_decoder_vs_encoder(void) { - /* registers: dst 8, src1 12, src2 16, src3 20, uniform 6 (encode_one maps vreg n to Rn / URn) */ - static const struct { BlackwellIROpcode op; int src2, src3, ureg; Ops e; } t[] = { - { BW_IR_NOP, -1, -1, -1, { {0}, {0} } }, - { BW_IR_MOV_RZ, -1, -1, -1, { {G(8,1)}, {0} } }, - { BW_IR_MOV_IMM, -1, -1, -1, { {G(8,1)}, {0} } }, - { BW_IR_S2R, -1, -1, -1, { {G(8,1)}, {0} } }, - { BW_IR_LDC, -1, -1, -1, { {G(8,1)}, {0} } }, - { BW_IR_LDC64, -1, -1, -1, { {G(8,2)}, {0} } }, - { BW_IR_IMAD, 16, 20, -1, { {G(8,1)}, {G(12,1), G(16,1), G(20,1)} } }, - { BW_IR_IMAD, -1, 20, 6, { {G(8,1)}, {G(12,1), U(6,1), G(20,1)} } }, - { BW_IR_IMAD, -1, 20, -1, { {G(8,1)}, {G(12,1), G(20,1)} } }, - { BW_IR_IMAD_WIDE, -1, 20, -1, { {G(8,2)}, {G(12,1), G(20,2)} } }, - { BW_IR_ISETP_GE, -1, -1, -1, { {0}, {G(12,1)} } }, - { BW_IR_ISETP_GE, -1, -1, 6, { {0}, {G(12,1), U(6,1)} } }, - { BW_IR_LDG_E, -1, -1, 6, { {G(8,1)}, {G(12,2), U(6,1)} } }, - { BW_IR_STG_E, 16, -1, 6, { {0}, {G(12,2), G(16,1), U(6,1)} } }, - { BW_IR_STG_EF, 16, -1, 6, { {0}, {G(12,2), G(16,1), U(6,1)} } }, - { BW_IR_IADD3, 16, -1, -1, { {G(8,1)}, {G(12,1), G(16,1)} } }, - { BW_IR_HMMA_F16, 16, 20, -1, { {G(8,4)}, {G(12,4), G(16,2), G(20,4)} } }, - { BW_IR_HMMA_BF16, 16, 20, -1, { {G(8,4)}, {G(12,4), G(16,2), G(20,4)} } }, - { BW_IR_SHF_R, -1, -1, -1, { {G(8,1)}, {G(12,1)} } }, - { BW_IR_LOP3_AND, -1, -1, -1, { {G(8,1)}, {G(12,1)} } }, - { BW_IR_LDG_E_U16, -1, -1, 6, { {G(8,1)}, {G(12,2), U(6,1)} } }, - { BW_IR_LDG_STRONG_SYS, -1, -1, 6, { {G(8,1)}, {G(12,2), U(6,1)} } }, - { BW_IR_LDG_MMIO, -1, -1, 6, { {G(8,1)}, {G(12,2), U(6,1)} } }, - { BW_IR_STG_STRONG_SYS, 16, -1, 6, { {0}, {G(12,2), G(16,1), U(6,1)} } }, - { BW_IR_MEMBAR_ALL_SYS, -1, -1, -1, { {0}, {0} } }, - { BW_IR_MEMBAR_SC_SYS, -1, -1, -1, { {0}, {0} } }, - { BW_IR_CCTL_IVALL, -1, -1, -1, { {0}, {0} } }, - { BW_IR_ATOMG_ADD_STRONG_SYS, 16, -1, 6, { {G(8,1)}, {G(12,2), G(16,1), U(6,1)} } }, - { BW_IR_ATOMG_EXCH_STRONG_SYS, 16, -1, 6, { {G(8,1)}, {G(12,2), G(16,1), U(6,1)} } }, - { BW_IR_ISETP_GE_U32, 16, -1, -1, { {0}, {G(12,1), G(16,1)} } }, - { BW_IR_LOP3_XOR, 16, -1, -1, { {G(8,1)}, {G(12,1), G(16,1)} } }, - { BW_IR_FADD, 16, -1, -1, { {G(8,1)}, {G(12,1), G(16,1)} } }, - { BW_IR_FSUB, 16, -1, -1, { {G(8,1)}, {G(12,1), G(16,1)} } }, - { BW_IR_FMUL, 16, -1, -1, { {G(8,1)}, {G(12,1), G(16,1)} } }, - { BW_IR_FFMA, 16, 20, -1, { {G(8,1)}, {G(12,1), G(16,1), G(20,1)} } }, - { BW_IR_FSETP, 16, -1, -1, { {0}, {G(12,1), G(16,1)} } }, - { BW_IR_FSEL, 16, -1, -1, { {G(8,1)}, {G(12,1), G(16,1)} } }, - { BW_IR_FMNMX_MIN, 16, -1, -1, { {G(8,1)}, {G(12,1), G(16,1)} } }, - { BW_IR_FMNMX_MAX, 16, -1, -1, { {G(8,1)}, {G(12,1), G(16,1)} } }, - { BW_IR_I2FP, -1, -1, -1, { {G(8,1)}, {G(12,1)} } }, - { BW_IR_F2I, -1, -1, -1, { {G(8,1)}, {G(12,1)} } }, - { BW_IR_MUFU_RCP, -1, -1, -1, { {G(8,1)}, {G(12,1)} } }, - { BW_IR_MUFU_RSQ, -1, -1, -1, { {G(8,1)}, {G(12,1)} } }, - { BW_IR_SHFL_DOWN, -1, -1, -1, { {G(8,1)}, {G(12,1)} } }, - { BW_IR_LDS, -1, -1, -1, { {G(8,1)}, {G(12,1)} } }, - { BW_IR_STS, 16, -1, -1, { {0}, {G(12,1), G(16,1)} } }, - { BW_IR_EXIT, -1, -1, -1, { {0}, {0} } }, - { BW_IR_MUFU_EX2, -1, -1, -1, { {G(8,1)}, {G(12,1)} } }, - { BW_IR_BAR_SYNC, -1, -1, -1, { {0}, {0} } }, - { BW_IR_LDS32, -1, -1, -1, { {G(8,1)}, {G(12,1)} } }, - { BW_IR_STS32, 16, -1, -1, { {0}, {G(12,1), G(16,1)} } }, - { BW_IR_LOP3_LUT, 16, 20, -1, { {G(8,1)}, {G(12,1), G(16,1), G(20,1)} } }, - { BW_IR_SHF_L_U32, 16, 20, -1, { {G(8,1)}, {G(12,1), G(16,1), G(20,1)} } }, - { BW_IR_IMAD_HI_U32, 16, 20, -1, { {G(8,1)}, {G(12,1), G(16,1), G(20,1)} } }, - { BW_IR_LDG_E_64, -1, -1, 6, { {G(8,2)}, {G(12,2), U(6,1)} } }, - { BW_IR_LDG_E_128, -1, -1, 6, { {G(8,4)}, {G(12,2), U(6,1)} } }, - { BW_IR_LDS128, -1, -1, -1, { {G(8,4)}, {G(12,1)} } }, - }; - int bad = 0; - for (unsigned i = 0; i < sizeof t / sizeof *t; i++) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); - in.op = t[i].op; in.dst_vreg = 8; in.src1_vreg = 12; in.src2_vreg = t[i].src2; in.src3_vreg = t[i].src3; in.ureg = t[i].ureg; - in.control = CW(3, 2, 5, 0x29) | 0x2000u; - /* IMAD and ISETP_GE take the uniform-operand form only with is_uniform set */ - if ((t[i].op == BW_IR_IMAD || t[i].op == BW_IR_ISETP_GE) && t[i].ureg >= 0) in.is_uniform = true; - uint32_t w[4]; uint8_t b[16]; OmegaBwInsn d; - if (omega_blackwell_encode_one(&in, w) != 0) { CHECK(0, "encode op %d", (int)t[i].op); bad++; continue; } - for (int k = 0; k < 4; k++) { b[4*k] = (uint8_t)w[k]; b[4*k+1] = (uint8_t)(w[k] >> 8); b[4*k+2] = (uint8_t)(w[k] >> 16); b[4*k+3] = (uint8_t)(w[k] >> 24); } - if (omega_bw_decode(b, &d) != 0) { CHECK(0, "decode of op %d (word0 %08x) refused", (int)t[i].op, w[0]); bad++; continue; } - int nw = count(t[i].e.w, 3), nr = count(t[i].e.r, 6), ok = d.nw == nw && d.nr == nr; - for (int k = 0; k < nw && ok; k++) ok = has(d.wr, d.nw, t[i].e.w[k]); - for (int k = 0; k < nr && ok; k++) ok = has(d.rd, d.nr, t[i].e.r[k]); - if (!ok) { bad++; CHECK(0, "op %d (%s): decoded %u writes %u reads, expected %d / %d", (int)t[i].op, d.name ? d.name : "?", d.nw, d.nr, nw, nr); } - } - { /* uniform loads write the uniform file */ - BlackwellIROpcode u[2] = { BW_IR_LDCU, BW_IR_LDCU64 }; - for (int i = 0; i < 2; i++) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); in.op = u[i]; in.dst_vreg = 6; in.src1_vreg = in.src2_vreg = in.src3_vreg = in.ureg = -1; in.is_uniform = true; - uint32_t w[4]; uint8_t b[16]; OmegaBwInsn d; - CHECK(omega_blackwell_encode_one(&in, w) == 0, "encode LDCU"); - memcpy(b, w, 16); - CHECK(omega_bw_decode(b, &d) == 0 && d.nw == 1 && d.wr[0].uniform && d.wr[0].reg == 6 && d.wr[0].n == (i ? 2 : 1) && d.nr == 0 && d.var, - "LDCU%s decodes to a uniform write of UR6", i ? ".64" : ""); - } - } - { /* the control word: every field at a distinct value (NOP keeps insn->control on every encoder version) */ - BlackwellIRInsn in; memset(&in, 0, sizeof in); in.op = BW_IR_NOP; in.dst_vreg = in.src1_vreg = in.src2_vreg = in.src3_vreg = in.ureg = -1; - in.control = CW(3, 2, 5, 0x29) | 0x2000u; - uint32_t w[4]; OmegaBwInsn d; CHECK(omega_blackwell_encode_one(&in, w) == 0, "encode NOP"); - CHECK(omega_bw_decode((const uint8_t *)w, &d) == 0 && d.stall == 3 && d.yield == 1 && d.wbar == 2 && d.rbar == 5 && d.wait == 0x29, - "control fields stall %u yield %u wbar %u rbar %u wait 0x%x", d.stall, d.yield, d.wbar, d.rbar, d.wait); - } - { /* branch targets, both signs, both predicate senses */ - int32_t deltas[] = { -300, -64, -63, -5, -1, 0, 1, 2, 63, 64, 65, 1000 }; - for (unsigned i = 0; i < sizeof deltas / sizeof *deltas; i++) - for (int p = 0; p < 3; p++) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); in.op = BW_IR_BRA; in.imm = (uint32_t)deltas[i]; - in.dst_vreg = in.src1_vreg = in.src2_vreg = in.src3_vreg = in.ureg = -1; in.predicate_p0 = p > 0; in.predicate_not = p == 2; - uint32_t w[4]; OmegaBwInsn d; - CHECK(omega_blackwell_encode_one(&in, w) == 0 && omega_bw_decode((const uint8_t *)w, &d) == 0 && d.flow == OMEGA_BW_FLOW_BRA && - d.target == deltas[i] && d.guard == (p == 0 ? 7u : p == 1 ? 0u : 8u), "BRA delta %d pred %d decodes to %d guard %u", deltas[i], p, d.target, d.guard); - } - } - printf("decoder vs encoder: %zu forms, %d mismatched\n", sizeof t / sizeof *t, bad); -} - -/* -------------------------------------------------------------------------------------------- fixtures and helpers */ -static size_t load(const char *dir, const char *name, uint8_t *buf, size_t cap) { - char path[512]; snprintf(path, sizeof path, "%s/%s", dir, name); - FILE *f = fopen(path, "rb"); if (!f) return 0; - size_t n = fread(buf, 1, cap, f); fclose(f); return n; -} -static int finding(const OmegaBwHazardReport *r, uint32_t pc, uint8_t kind, uint8_t reg) { - for (size_t i = 0; i < r->count && i < OMEGA_BW_HAZARD_MAX; i++) - if (r->f[i].pc == pc && r->f[i].kind == kind && r->f[i].reg == reg && !r->f[i].uniform) return 1; - return 0; -} -static void print_findings(const char *tag, const OmegaBwHazardReport *r) { - for (size_t i = 0; i < r->count && i < OMEGA_BW_HAZARD_MAX; i++) - printf(" %s: IR %u %s %sR%u (release mask 0x%x, last producer/reader IR %u)\n", tag, r->f[i].pc, omega_bw_hazard_kind(r->f[i].kind), - r->f[i].uniform ? "U" : "", r->f[i].reg, r->f[i].release, r->f[i].src_pc); -} -static void set_wait(uint8_t *code, uint32_t pc, unsigned wait) { - uint8_t *p = code + (size_t)pc * 16u + 12u; uint32_t w3 = (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; - w3 = (w3 & ~(0x3fu << 20)) | (wait & 0x3fu) << 20; - p[0] = (uint8_t)w3; p[1] = (uint8_t)(w3 >> 8); p[2] = (uint8_t)(w3 >> 16); p[3] = (uint8_t)(w3 >> 24); -} - -/* ---------------------------------------------------------------------------------------------- 2. red receipt */ -static void test_red_receipt(const char *dir) { - static uint8_t a[1 << 16]; - size_t n = load(dir, "pattn256_attend_ad5d650b.bin", a, sizeof a); - CHECK(n == 10112, "fixture pattn256_attend_ad5d650b.bin (%zu bytes)", n); - if (n == 10112) { - int rc = omega_bw_hazard_check(a, n, &g_rep); - CHECK(rc == 0 && g_rep.count == 2 && finding(&g_rep, 88, OMEGA_BW_HZ_WAR, 22) && finding(&g_rep, 89, OMEGA_BW_HZ_WAR, 23) && - g_rep.f[0].release == 0x3 && g_rep.f[1].release == 0x3, - "RED: pre-#553 attend must fail with WAR R22/R23 at IR 88/89 (rc %d, %zu findings)", rc, g_rep.count); - printf("red receipt, pre-#553 attend (the kernel that faulted on the GB10): %zu findings\n", g_rep.count); - print_findings("pre-#553 attend", &g_rep); - } - n = load(dir, "pattn256_attend_e3a26848.bin", a, sizeof a); - CHECK(n == 10112, "fixture pattn256_attend_e3a26848.bin (%zu bytes)", n); - if (n == 10112) { - int rc = omega_bw_hazard_check(a, n, &g_rep); - CHECK(rc == 0 && g_rep.count == 0, "GREEN: the fixed attend must pass (rc %d, %zu findings)", rc, g_rep.count); - printf("fixed attend (e3a26848): rc %d, %zu findings, %zu of %zu instructions reachable\n", rc, g_rep.count, g_rep.reachable, g_rep.insns); - /* the one wait the old encoder lost: the IADD3 at IR 55 waits on the Q loads' barriers 0x3 */ - OmegaBwInsn d; CHECK(omega_bw_decode(a + 55 * 16, &d) == 0 && d.op == 0x210 && d.wait == 0x3, "IR 55 is the IADD3 waiting 0x3"); - set_wait(a, 55, 0x10); - rc = omega_bw_hazard_check(a, n, &g_rep); - CHECK(rc == 0 && g_rep.count == 2 && finding(&g_rep, 88, OMEGA_BW_HZ_WAR, 22) && finding(&g_rep, 89, OMEGA_BW_HZ_WAR, 23), - "MUTANT: the fixed attend with IR 55 waiting 0x10 must fail again (%zu findings)", g_rep.count); - } - n = load(dir, "pattn256_prep_ad5d650b.bin", a, sizeof a); - CHECK(n == 5376, "fixture pattn256_prep_ad5d650b.bin"); - if (n == 5376) { - int rc = omega_bw_hazard_check(a, n, &g_rep); - CHECK(rc == 0 && g_rep.count == 1 && finding(&g_rep, 35, OMEGA_BW_HZ_RAW, 20) && g_rep.f[0].release == 0x1, - "pre-#553 prep: RAW R20 at IR 35 (S2R at IR 14 on barrier 0; the IADD3 at IR 15 waited on 4 only), %zu findings", g_rep.count); - print_findings("pre-#553 prep", &g_rep); - } - n = load(dir, "pattn256_prep_e3a26848.bin", a, sizeof a); - CHECK(n == 5376 && omega_bw_hazard_check(a, n, &g_rep) == 0 && g_rep.count == 0, "fixed prep passes (%zu findings)", g_rep.count); -} - -/* -------------------------------------------------------------------------------------------- 3. negative controls */ -static size_t enc(const BlackwellIRInsn *ins, size_t n, uint8_t *out) { - for (size_t i = 0; i < n; i++) { uint32_t w[4]; if (omega_blackwell_encode_one(&ins[i], w) != 0) return 0; memcpy(out + 16 * i, w, 16); } - return 16 * n; -} -static BlackwellIRInsn mk(BlackwellIROpcode op, int d, int a, int b, int c, int u, uint32_t control) { - BlackwellIRInsn in; memset(&in, 0, sizeof in); - in.op = op; in.dst_vreg = d; in.src1_vreg = a; in.src2_vreg = b; in.src3_vreg = c; in.ureg = u; in.control = control; return in; -} -static void test_controls(void) { - uint8_t c[16 * 16]; size_t n; - const uint32_t FIX = CW(6, 7, 7, 0), LD = CW(4, 0, 1, 0) | 0x2000u, ST = CW(4, 7, 1, 0) | 0x2000u, ENDW = CW(5, 7, 7, 0); - /* RAW: a load's result read with no wait / with the wait / with a wait on an unrelated barrier (the #545 pattern) */ - BlackwellIRInsn raw[] = { mk(BW_IR_LDG_E, 4, 2, -1, -1, 4, LD), mk(BW_IR_FADD, 6, 4, 4, -1, -1, FIX), mk(BW_IR_EXIT, -1, -1, -1, -1, -1, ENDW) }; - n = enc(raw, 3, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 1 && finding(&g_rep, 1, OMEGA_BW_HZ_RAW, 4), "control RAW caught"); - raw[1].control = CW(6, 7, 7, 0x1); n = enc(raw, 3, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 0, "control RAW with the wait passes"); - raw[1].control = CW(6, 7, 7, 0x10); n = enc(raw, 3, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 1 && finding(&g_rep, 1, OMEGA_BW_HZ_RAW, 4), "control RAW behind a wait on barrier 4 caught"); - raw[1].control = CW(6, 7, 7, 0x2); n = enc(raw, 3, c); /* waiting on the read barrier does not cover the result */ - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 1 && finding(&g_rep, 1, OMEGA_BW_HZ_RAW, 4), "control RAW behind the read barrier only caught"); - /* WAR: a store's data register overwritten before the store's read barrier */ - BlackwellIRInsn war[] = { mk(BW_IR_STG_E, -1, 2, 4, -1, 4, ST), mk(BW_IR_MOV_RZ, 4, -1, -1, -1, -1, FIX), mk(BW_IR_EXIT, -1, -1, -1, -1, -1, ENDW) }; - n = enc(war, 3, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 1 && finding(&g_rep, 1, OMEGA_BW_HZ_WAR, 4), "control WAR (store data) caught"); - war[1].dst_vreg = 3; n = enc(war, 3, c); /* the store's address pair is R2:R3 */ - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 1 && finding(&g_rep, 1, OMEGA_BW_HZ_WAR, 3), "control WAR (address high half) caught"); - war[1].control = CW(6, 7, 7, 0x2); n = enc(war, 3, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 0, "control WAR with the wait passes"); - war[1].dst_vreg = 5; war[1].control = FIX; n = enc(war, 3, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 0, "control: a register the store does not read passes"); - /* WAR released by the load's completion: waiting on the write barrier also frees the address */ - BlackwellIRInsn warc[] = { mk(BW_IR_LDG_E, 4, 2, -1, -1, 4, LD), mk(BW_IR_MOV_RZ, 2, -1, -1, -1, -1, CW(6, 7, 7, 0x1)), mk(BW_IR_EXIT, -1, -1, -1, -1, -1, ENDW) }; - n = enc(warc, 3, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 0, "control: address overwrite after the load completed passes"); - warc[1].control = FIX; n = enc(warc, 3, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 1 && finding(&g_rep, 1, OMEGA_BW_HZ_WAR, 2), "control WAR (load address) caught"); - /* WAW: a pending load's destination overwritten */ - BlackwellIRInsn waw[] = { mk(BW_IR_LDG_E, 4, 2, -1, -1, 4, LD), mk(BW_IR_MOV_RZ, 4, -1, -1, -1, -1, CW(6, 7, 7, 0x2)), mk(BW_IR_EXIT, -1, -1, -1, -1, -1, ENDW) }; - n = enc(waw, 3, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 1 && finding(&g_rep, 1, OMEGA_BW_HZ_WAW, 4), "control WAW caught"); - /* a variable-latency result with no write barrier at all: nothing can release it */ - BlackwellIRInsn nob[] = { mk(BW_IR_S2R, 4, -1, -1, -1, -1, CW(4, 7, 7, 0)), mk(BW_IR_FADD, 6, 4, 4, -1, -1, CW(6, 7, 7, 0x3f)), mk(BW_IR_EXIT, -1, -1, -1, -1, -1, ENDW) }; - nob[0].imm = BW_SR_TID_X; n = enc(nob, 3, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 1 && finding(&g_rep, 1, OMEGA_BW_HZ_RAW, 4) && g_rep.f[0].release == 0, - "control: S2R with no write barrier caught even behind a wait on every barrier"); - /* a hazard carried round a loop: the read at the top sees the load issued at the bottom of the previous trip */ - BlackwellIRInsn loop[] = { mk(BW_IR_MOV_RZ, 4, -1, -1, -1, -1, FIX), mk(BW_IR_FADD, 6, 4, 4, -1, -1, FIX), mk(BW_IR_LDG_E, 4, 2, -1, -1, 4, LD), - mk(BW_IR_BRA, -1, -1, -1, -1, -1, CW(5, 7, 7, 0)), mk(BW_IR_EXIT, -1, -1, -1, -1, -1, ENDW) }; - loop[3].imm = (uint32_t)-2; loop[3].predicate_p0 = true; - n = enc(loop, 5, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && finding(&g_rep, 1, OMEGA_BW_HZ_RAW, 4) && finding(&g_rep, 0, OMEGA_BW_HZ_WAW, 4) == 0, - "control: RAW across the loop back edge caught (%zu findings)", g_rep.count); - loop[3].control = CW(5, 7, 7, 0x1); n = enc(loop, 5, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 0, "control: the loop with the wait on the branch passes (%zu findings)", g_rep.count); - /* the path the hazard is on is not the straight line: an unpredicated branch skips the wait */ - BlackwellIRInsn skip[] = { mk(BW_IR_LDG_E, 4, 2, -1, -1, 4, LD), mk(BW_IR_BRA, -1, -1, -1, -1, -1, CW(5, 7, 7, 0)), mk(BW_IR_NOP, -1, -1, -1, -1, -1, CW(1, 7, 7, 0x1)), - mk(BW_IR_FADD, 6, 4, 4, -1, -1, FIX), mk(BW_IR_EXIT, -1, -1, -1, -1, -1, ENDW) }; - skip[1].imm = 2; skip[1].predicate_p0 = true; n = enc(skip, 5, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 1 && finding(&g_rep, 3, OMEGA_BW_HZ_RAW, 4), "control: RAW on the branch-taken path caught"); - skip[1].predicate_p0 = false; n = enc(skip, 5, c); - CHECK(n && omega_bw_hazard_check(c, n, &g_rep) == 0 && g_rep.count == 1 && g_rep.reachable == 4, "control: unreachable wait does not count (%zu reachable)", g_rep.reachable); - /* undecodable word: not checked, never clean */ - n = enc(raw, 3, c); c[16] = 0x55; c[17] = 0x7f; - CHECK(omega_bw_hazard_check(c, n, &g_rep) == -1 && g_rep.bad_pc == 1, "control: an unknown opcode is refused (bad_pc %lld)", (long long)g_rep.bad_pc); - /* branch out of range */ - BlackwellIRInsn far[] = { mk(BW_IR_BRA, -1, -1, -1, -1, -1, CW(5, 7, 7, 0)) }; far[0].imm = 5; n = enc(far, 1, c); - CHECK(omega_bw_hazard_check(c, n, &g_rep) == -1 && g_rep.bad_pc == 0, "control: a branch out of the buffer is refused"); - CHECK(omega_bw_hazard_check(c, 15, &g_rep) == -1 && omega_bw_hazard_check(NULL, 16, &g_rep) == -1, "control: bad length / NULL refused"); -} - -/* ------------------------------------------------------------------------------------------------------- 4. sweep */ -typedef struct { const char *family; char variant[96]; uint64_t hash; size_t findings; } Seen; -#define MAX_SEEN 8192 -static Seen g_seen[MAX_SEEN]; -static size_t g_nseen, g_variants, g_unchecked, g_findings_total; - -/* Triaged findings on main a8ffd2b9 (2026-10-19), each read in the bytes (instruction, barrier, every wait between). - * Every finding the sweep prints must be listed here; a listed entry no longer seen prints a NOTE (fixed: remove it). - * The rule behind A and B is the one ptxas follows (offline oracle, nvcc 13.0 -arch=sm_121: an LDG whose address - * register is overwritten while in flight gets a read barrier and the overwriting IADD.64 waits on it; the first - * reader of an LDCU.64 descriptor waits on the LDCU's write barrier) and the one the chip taught us twice (#545; the - * fp8 GEMV hang in omega_bw_em.h, evidence OWN30B-FP8-GEMV-c4006391). None of A..C is observed failing on the chip: - * they are contract violations that timing has hidden so far. - * A the LDCU.64 descriptor UR4 (write barrier 1) is read by the first LDG with no wait on barrier 1 in between - * (matmul generators in omega_blackwell_codegen.c, default control words). Not caused by the #553 encoder bug. - * B matmul_tensor: the LDG / STG address pair R16:R17 is rewritten by the next IMAD.WIDE before the op read it: - * the loads only have write barrier 2 and nothing waits on it; the STGs carry no barrier at all (release 0). - * C prime sieve kernels: a second LDG / LDS writes its destination into the first load's address register while - * the first load (write barrier 0, no read barrier) is in flight; the pattern of the fp8 GEMV chip hang. - * D (gone) RMSNORM: round the loop the IMAD.WIDE / FMUL rewrite registers the STG (read barrier 1) still read; the - * IADD3s scheduled to wait on barrier 1 carried the fixed word 3 (wait 0x10) of the #553 encoder bug. PR #553 - * (main b11bd1f6) fixed the encoder and the sweep no longer sees them, so their three entries are removed. */ -#define ANY_PC UINT32_MAX -typedef struct { const char *family; uint32_t pc; uint8_t kind; uint8_t reg; uint8_t uniform; char cls; int seen; } Known; -static Known g_known[] = { - { "matmul_i32", ANY_PC, OMEGA_BW_HZ_RAW, 4, 1, 'A', 0 }, - { "matmul_tensor", ANY_PC, OMEGA_BW_HZ_RAW, 4, 1, 'A', 0 }, - { "matmul_tensor_loop", ANY_PC, OMEGA_BW_HZ_RAW, 4, 1, 'A', 0 }, - { "matmul_frag", ANY_PC, OMEGA_BW_HZ_RAW, 4, 1, 'A', 0 }, - { "matmul_frag_block", ANY_PC, OMEGA_BW_HZ_RAW, 4, 1, 'A', 0 }, - { "matmul_tensor", ANY_PC, OMEGA_BW_HZ_WAR, 16, 0, 'B', 0 }, - { "matmul_tensor", ANY_PC, OMEGA_BW_HZ_WAR, 17, 0, 'B', 0 }, - { "elementwise", 25, OMEGA_BW_HZ_WAR, 22, 0, 'C', 0 }, /* PRIME_SIEVE */ - { "elementwise", 26, OMEGA_BW_HZ_WAR, 23, 0, 'C', 0 }, - { "elementwise", 39, OMEGA_BW_HZ_WAR, 21, 0, 'C', 0 }, /* PRIME_SIEVE_SHARED */ - { "elementwise", 25, OMEGA_BW_HZ_WAR, 20, 0, 'C', 0 }, /* PRIME_SIEVE_DIV1 */ - { "elementwise", 26, OMEGA_BW_HZ_WAR, 21, 0, 'C', 0 }, - { "elementwise", 41, OMEGA_BW_HZ_WAR, 19, 0, 'C', 0 }, /* PRIME_SIEVE_SHARED_DIV1 */ - { "elementwise", 26, OMEGA_BW_HZ_WAR, 20, 0, 'C', 0 }, /* PRIME_SIEVE_DIV2 */ - { "elementwise", 27, OMEGA_BW_HZ_WAR, 21, 0, 'C', 0 }, - { "elementwise", 42, OMEGA_BW_HZ_WAR, 19, 0, 'C', 0 }, /* PRIME_SIEVE_SHARED_DIV2 */ - { NULL, 0, 0, 0, 0, 0, 0 } -}; - -static uint64_t fnv(const uint8_t *p, size_t n) { uint64_t h = 1469598103934665603ull; for (size_t i = 0; i < n; i++) { h ^= p[i]; h *= 1099511628211ull; } return h; } - -static void disasm_cross_check(const char *family, const char *variant, const uint8_t *code, size_t len); - -static void sweep_bytes(const char *family, const char *variant, const uint8_t *code, size_t len) { - g_variants++; - uint64_t h = fnv(code, len); - for (size_t i = 0; i < g_nseen; i++) if (g_seen[i].hash == h) return; /* identical bytes already checked */ - int rc = omega_bw_hazard_check(code, len, &g_rep); - if (g_nseen < MAX_SEEN) { Seen *s = &g_seen[g_nseen++]; s->family = family; snprintf(s->variant, sizeof s->variant, "%s", variant); s->hash = h; s->findings = g_rep.count; } - if (rc != 0) { - g_unchecked++; - OmegaBwInsn d; long long pc = g_rep.bad_pc; uint32_t w0 = 0; - if (pc >= 0) memcpy(&w0, code + pc * 16, 4); - CHECK(0, "%s %s: not checked (instruction %lld, word 0 %08x, decode %d)", family, variant, pc, w0, pc >= 0 ? omega_bw_decode(code + pc * 16, &d) : -9); - return; - } - for (size_t i = 0; i < g_rep.count && i < OMEGA_BW_HAZARD_MAX; i++) { - const OmegaBwHazard *f = &g_rep.f[i]; int known = 0; - for (size_t k = 0; g_known[k].family; k++) - if (!strcmp(g_known[k].family, family) && (g_known[k].pc == ANY_PC || g_known[k].pc == f->pc) && g_known[k].kind == f->kind && - g_known[k].reg == f->reg && g_known[k].uniform == f->uniform) { g_known[k].seen = 1; known = g_known[k].cls; } - printf("FINDING %s %s: IR %u %s %sR%u release 0x%x (last producer/reader IR %u) [%s %c]\n", family, variant, f->pc, omega_bw_hazard_kind(f->kind), - f->uniform ? "U" : "", f->reg, f->release, f->src_pc, known ? "triaged" : "UNTRIAGED", known ? known : '-'); - CHECK(known, "%s %s: untriaged %s at IR %u", family, variant, omega_bw_hazard_kind(f->kind), f->pc); - } - g_findings_total += g_rep.count; - if (g_dump_dir && g_rep.count) { - char path[512]; snprintf(path, sizeof path, "%s/%s-%zu.bin", g_dump_dir, family, g_nseen - 1); - /* 0644, not fopen's 0666 & ~umask: a dump is never world-writable */ - int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); - FILE *f = fd >= 0 ? fdopen(fd, "wb") : NULL; - if (fd >= 0 && !f) close(fd); - if (f) { fwrite(code, 1, len, f); fclose(f); printf("DUMP %s = %s %s\n", path, family, variant); } - } - if (g_disasm) disasm_cross_check(family, variant, code, len); -} - -/* encode + the launcher's patch steps */ -enum { P_NONE = 0, P_TC = 1, P_QMMA = 2 }; -static void sweep_prog(const char *family, const char *variant, int patch) { - size_t len = 0; - if (omega_bw_encode_program(&g_prog, g_code, sizeof g_code, &len) != 0) { CHECK(0, "%s %s: encode failed", family, variant); return; } - if ((patch & P_TC) && omega_tc_patch_code(&g_prog, g_code, len) < 0) { CHECK(0, "%s %s: tc patch failed", family, variant); return; } - if ((patch & P_QMMA) && omega_qmma_patch_code(&g_prog, g_code, len) < 0) { CHECK(0, "%s %s: qmma patch failed", family, variant); return; } - sweep_bytes(family, variant, g_code, len); -} -#define BUILD(call) (memset(&g_prog, 0, sizeof g_prog), (call) == 0) - -static void sweep(void) { - char v[96]; - /* fp8 GEMV (MoE experts, attention projections): k values of the live models, every buildable lane / rows / warps / depth */ - { unsigned ks[] = { 256, 768, 2048, 4096, 8192 }; - for (unsigned a = 0; a < 5; a++) for (unsigned lb = 8; lb <= 16; lb += 8) for (unsigned rows = 1; rows <= 8; rows *= 2) - for (unsigned w = 1; w <= 32; w *= 2) for (unsigned dp = 0; dp <= 8; dp += dp ? dp : 1) { - OmegaFp8GemvSpec s = { .k = ks[a], .lane_bytes = lb, .rows = rows, .warps = w, .depth = dp }; - snprintf(v, sizeof v, "k%u lane%u rows%u warps%u depth%u", ks[a], lb, rows, w, dp); - if (BUILD(omega_blackwell_codegen_fp8_gemv_prog(&s, &g_prog))) sweep_prog("fp8_gemv", v, P_NONE); - if (BUILD(omega_blackwell_codegen_fp8_gemv2_prog(&s, &g_prog))) sweep_prog("fp8_gemv2", v, P_NONE); - } } - /* bf16 GEMV (lm_head) */ - { unsigned ks[] = { 256, 2048, 4096, 5120 }; - for (unsigned a = 0; a < 4; a++) for (unsigned rows = 1; rows <= 4; rows *= 2) for (unsigned w = 1; w <= 32; w *= 2) for (unsigned dp = 1; dp <= 16; dp *= 2) { - OmegaBf16GemvSpec s = { .k = ks[a], .rows = rows, .warps = w, .depth = dp }; - snprintf(v, sizeof v, "k%u rows%u warps%u depth%u", ks[a], rows, w, dp); - if (BUILD(omega_blackwell_codegen_bf16_gemv_prog(&s, &g_prog))) sweep_prog("bf16_gemv", v, P_NONE); - } } - /* fp8 grouped GEMM */ - { unsigned ks[] = { 768, 2048, 4096 }; - for (unsigned a = 0; a < 3; a++) for (unsigned lb = 8; lb <= 16; lb += 8) for (unsigned mt = 1; mt <= 16; mt *= 2) for (unsigned w = 1; w <= 32; w *= 2) { - OmegaFp8GemmSpec s = { .k = ks[a], .lane_bytes = lb, .mt = mt, .warps = w }; - snprintf(v, sizeof v, "k%u lane%u mt%u warps%u", ks[a], lb, mt, w); - if (BUILD(omega_blackwell_codegen_fp8gemm_prog(&s, &g_prog))) sweep_prog("fp8gemm", v, P_NONE); - } } - /* ternary GEMV */ - { unsigned ks[] = { 256, 2048, 4096, 8192, 16384 }; - for (unsigned a = 0; a < 5; a++) for (unsigned lay = 0; lay <= 1; lay++) for (unsigned rows = 1; rows <= 4; rows *= 2) for (unsigned w = 1; w <= 32; w *= 2) - for (unsigned dp = 1; dp <= 16; dp *= 2) for (unsigned epi = 0; epi <= 1; epi++) { - OmegaTernGemvSpec s = { ks[a], lay, rows, w, dp, epi, 0 }; - snprintf(v, sizeof v, "k%u layout%u rows%u warps%u depth%u epi%u", ks[a], lay, rows, w, dp, epi); - if (BUILD(omega_blackwell_codegen_tern_gemv_prog(&s, &g_prog))) sweep_prog("tern_gemv", v, P_NONE); - } } - /* router, decode attention */ - for (unsigned w = 8; w <= 32; w *= 2) for (unsigned dp = 1; dp <= 8; dp *= 2) { - OmegaRouterSpec s = { .warps = w, .depth = dp }; snprintf(v, sizeof v, "warps%u depth%u", w, dp); - if (BUILD(omega_blackwell_codegen_router_prog(&s, &g_prog))) sweep_prog("router", v, P_NONE); - } - for (unsigned dp = 1; dp <= 4; dp++) { - OmegaDecodeAttnSpec s = { dp, 0 }; snprintf(v, sizeof v, "depth%u", dp); - if (BUILD(omega_blackwell_codegen_decode_attn_prog(&s, &g_prog))) sweep_prog("decode_attn", v, P_NONE); - } - /* decode glue kernels (command list / decode graph) */ - { struct { OmegaDecKind k; uint32_t mode, stride; } d[] = { - { OMEGA_DEC_AXPY, 0, 256 }, { OMEGA_DEC_AXPY, 0, 512 }, { OMEGA_DEC_AXPY, 0, 2048 }, { OMEGA_DEC_AXPY, 0, 12288 }, - { OMEGA_DEC_SWIGLU, 0, 0 }, { OMEGA_DEC_ARGMAX, 0, 0 }, { OMEGA_DEC_ARGMAX, 1, 0 } }; - for (unsigned i = 0; i < sizeof d / sizeof *d; i++) { - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = d[i].k; s.mode = d[i].mode; s.stride = d[i].stride; - snprintf(v, sizeof v, "kind%d mode%u stride%u", (int)d[i].k, d[i].mode, d[i].stride); - if (BUILD(omega_blackwell_codegen_dec_prog(&s, &g_prog))) sweep_prog("dec", v, P_NONE); - } - for (uint32_t mode = 0; mode < 8; mode++) { - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = mode; - snprintf(v, sizeof v, "RES mode%u", mode); - if (BUILD(omega_blackwell_codegen_dec_prog(&s, &g_prog))) sweep_prog("dec", v, P_NONE); - } } - /* tensor-core GEMM and probes */ - { unsigned ks[] = { 128, 768, 2048, 4096, 16384 }; - for (unsigned a = 0; a < 5; a++) for (unsigned rt = 1; rt <= 4; rt *= 2) for (unsigned ct = 1; ct <= 4; ct *= 2) for (unsigned w = 1; w <= 8; w *= 2) { - OmegaTcGemmSpec s = { ks[a], rt, ct, w, 0 }; snprintf(v, sizeof v, "k%u rt%u ct%u warps%u", ks[a], rt, ct, w); - if (BUILD(omega_blackwell_codegen_tcgemm_prog(&s, &g_prog))) sweep_prog("tcgemm", v, P_NONE); - } } - if (BUILD(omega_blackwell_codegen_tc_probe_prog(0, &g_prog))) sweep_prog("tc_probe", "mutant0", P_TC); - for (unsigned ch = 1; ch <= 16; ch *= 2) for (unsigned st = 1; st <= 4; st++) { - snprintf(v, sizeof v, "iters5 chains%u stall%u threads64", ch, st); - if (BUILD(omega_blackwell_codegen_tc_peak_prog(5, ch, st, 64, &g_prog))) sweep_prog("tc_peak", v, P_TC); - snprintf(v, sizeof v, "iters64 chains%u stall%u threads128", ch, st); - if (BUILD(omega_blackwell_codegen_qmma_peak_prog(64, ch, st, 128, &g_prog))) sweep_prog("qmma_peak", v, P_QMMA); - } - for (unsigned g = 1; g <= 8; g *= 2) for (unsigned t = 32; t <= 512; t *= 2) { - snprintf(v, sizeof v, "iters16 groups%u threads%u", g, t); - if (BUILD(omega_blackwell_codegen_tc_bw_prog(16, g, t, &g_prog))) sweep_prog("tc_bw", v, P_NONE); - } - for (unsigned nops = 0; nops <= 8; nops += 4) { - snprintf(v, sizeof v, "nops%u", nops); - if (BUILD(omega_blackwell_codegen_qmma_probe_prog(0, nops, &g_prog))) sweep_prog("qmma_probe", v, P_QMMA); - } - if (BUILD(omega_blackwell_codegen_f2e4_probe_prog(&g_prog))) sweep_prog("f2e4_probe", "-", P_QMMA); - /* prefill module kernels (omega_gpu_prefill.c applies both patches to every one of them) */ - { unsigned ks[] = { 128, 768, 2048, 4096, 16384 }; - for (unsigned a = 0; a < 5; a++) for (unsigned rt = 2; rt <= 8; rt *= 2) for (unsigned w = 4; w <= 16; w *= 2) for (unsigned aq = 1; aq <= 2; aq++) - for (unsigned epi = 0; epi <= 1; epi++) for (unsigned dir = 0; dir <= 1; dir++) { - OmegaTc2Spec s = { ks[a], rt, 2, w, aq, epi, dir, 0, 0 }; - s.n = 4u * w * 8u * 2u; if (epi) s.n *= 2u; - snprintf(v, sizeof v, "k%u rt%u warps%u aqn%u epi%u direct%u n%u", ks[a], rt, w, aq, epi, dir, s.n); - if (BUILD(omega_blackwell_codegen_tc2_prog(&s, &g_prog))) sweep_prog("tc2", v, P_TC | P_QMMA); - } - for (unsigned a = 0; a < 5; a++) for (unsigned w = 8; w <= 16; w *= 2) for (unsigned epi = 0; epi <= 1; epi++) for (unsigned dir = 0; dir <= 1; dir++) - for (unsigned wt = 0; wt <= 120; wt += 60) { - OmegaQgSpec s = { ks[a], 4, w, epi, dir, 512, wt, 0 }; - snprintf(v, sizeof v, "k%u warps%u epi%u direct%u n512 wait%u", ks[a], w, epi, dir, wt); - if (BUILD(omega_blackwell_codegen_qgemm_prog(&s, &g_prog))) sweep_prog("qgemm", v, P_TC | P_QMMA); - } - for (unsigned a = 0; a < 4; a++) for (unsigned it = 0; it <= 2; it++) { - OmegaPqSpec s = { .k = ks[a], .in_type = it }; snprintf(v, sizeof v, "k%u in_type%u", ks[a], it); - if (BUILD(omega_blackwell_codegen_pq_prog(&s, &g_prog))) sweep_prog("pq", v, P_TC | P_QMMA); - } } - { unsigned ks[] = { 768, 2048, 4096 }, es[] = { 8, 64, 128 }, ts[] = { 1, 16, 128, 1024 }; - for (unsigned a = 0; a < 3; a++) for (unsigned b = 0; b < 3; b++) for (unsigned c = 0; c < 4; c++) { - OmegaRlSpec s = { ks[a], es[b], ts[c], 0 }; snprintf(v, sizeof v, "k%u e%u t%u", ks[a], es[b], ts[c]); - if (BUILD(omega_blackwell_codegen_rl_prog(&s, &g_prog))) sweep_prog("rl", v, P_TC | P_QMMA); - } - unsigned hs[] = { 768, 2048, 4096 }; - for (unsigned a = 0; a < 3; a++) for (unsigned tk = 1; tk <= 8; tk *= 2) { - OmegaMcSpec s = { hs[a], tk, 0 }; snprintf(v, sizeof v, "h%u top_k%u", hs[a], tk); - if (BUILD(omega_blackwell_codegen_mc_prog(&s, &g_prog))) sweep_prog("mc", v, P_TC | P_QMMA); - } } - if (BUILD(omega_blackwell_codegen_pf_copy_prog(&g_prog))) sweep_prog("pf_copy", "-", P_TC | P_QMMA); - /* prefill attention: the API's own host encode (build + encode + tc patch) */ - for (unsigned w = 4; w <= 8; w *= 2) for (unsigned md = 0; md <= 2; md++) for (unsigned mir = 0; mir <= 1; mir++) { - OmegaPrefillAttnSpec s = { w, 0, md, mir }; - static uint8_t pa[OMEGA_BW_CODE_CAP_MAX + 4096]; uint32_t gp = 0; int np = 0; - size_t len = omega_gpu_prefill_attn_encode(&s, pa, sizeof pa, &gp, &np); - snprintf(v, sizeof v, "warps%u mode%u mirror%u", w, md, mir); - if (len) sweep_bytes("prefill_attn", v, pa, len); - } - /* gqa / paged attention (FB-1 cut 5): the API's codegen */ - for (int f32 = 0; f32 <= 1; f32++) for (uint32_t lb = 0; lb <= 8; lb++) for (uint32_t lg = 0; lg <= 4; lg++) for (uint32_t hd = 64; hd <= 128; hd *= 2) { - OmegaBlackwellKernel k; memset(&k, 0, sizeof k); - if (omega_gpu_attention_codegen_hd(f32 != 0, lb, lg, hd, &k) != 0 || !k.code) { free(k.code); continue; } - snprintf(v, sizeof v, "kv_f32 %d log2_block %u log2_gqa %u hd %u", f32, lb, lg, hd); - sweep_bytes("attention", v, k.code, k.code_size); - free(k.code); - } - /* elementwise kernels and the reconvergence probes */ - for (int op = OMEGA_GPU_EW_EX2; op <= OMEGA_GPU_EW_RC_REFUSE_JOIN_ONLY; op++) { - OmegaBlackwellKernel k; memset(&k, 0, sizeof k); - if (omega_gpu_elementwise_codegen_ir((OmegaGpuEwOp)op, 0, &g_prog, &k) != 0 || !k.code) { free(k.code); continue; } - snprintf(v, sizeof v, "op%d", op); - sweep_bytes("elementwise", v, k.code, k.code_size); - free(k.code); - } - /* matmul: integer, single-tile tensor, looped tensor, fragment, blocked fragment */ - { OmegaMatMulSpec s; - uint32_t i32[][3] = { {16,16,16}, {32,16,64}, {16,32,16}, {64,32,64} }; - for (unsigned i = 0; i < 4; i++) if (omega_matmul_spec_init(&s, i32[i][0], i32[i][1], i32[i][2], OMEGA_MATMUL_PRECISION_INT32) == 0) { - snprintf(v, sizeof v, "m%u k%u n%u", i32[i][0], i32[i][1], i32[i][2]); - if (BUILD(omega_blackwell_codegen_matmul_i32_prog(&s, &g_prog))) sweep_prog("matmul_i32", v, P_NONE); - } - for (int pr = 0; pr < 2; pr++) { - OmegaMatMulPrecision p = pr ? OMEGA_MATMUL_PRECISION_FP16 : OMEGA_MATMUL_PRECISION_BF16; - if (omega_matmul_spec_init(&s, 16, 16, 8, p) == 0 && BUILD(omega_blackwell_codegen_matmul_tensor_prog(&s, &g_prog))) sweep_prog("matmul_tensor", pr ? "fp16" : "bf16", P_NONE); - uint32_t kk[] = { 16, 64, 2048 }, nn[] = { 8, 64, 2048 }; - for (unsigned a = 0; a < 3; a++) for (unsigned b = 0; b < 3; b++) for (uint32_t gx = 1; gx <= 8; gx *= 2) { - if (omega_matmul_spec_init(&s, 16, kk[a], nn[b], p) != 0) continue; - snprintf(v, sizeof v, "%s k%u n%u grid_x%u", pr ? "fp16" : "bf16", kk[a], nn[b], gx); - if (BUILD(omega_blackwell_codegen_matmul_tensor_loop_prog(&s, gx, 0, &g_prog))) sweep_prog("matmul_tensor_loop", v, P_NONE); - } - } - unsigned kps[] = { 768, 2048, 4096 }, nps[] = { 8, 128, 2048 }; - for (unsigned a = 0; a < 3; a++) for (unsigned b = 0; b < 3; b++) { - if (omega_matmul_spec_init(&s, 16, kps[a], nps[b], OMEGA_MATMUL_PRECISION_BF16) != 0) continue; - for (uint32_t un = 1; un <= 4; un *= 2) { - snprintf(v, sizeof v, "k%u n%u unroll%u", kps[a], nps[b], un); - if (BUILD(omega_blackwell_codegen_matmul_frag_prog(&s, 48, un, 0, &g_prog))) sweep_prog("matmul_frag", v, P_NONE); - } - for (unsigned rt = 1; rt <= 8; rt *= 2) for (unsigned ct = 1; ct <= 4; ct *= 2) for (uint32_t un = 1; un <= 2; un++) { - if (rt * ct < 2) continue; - snprintf(v, sizeof v, "k%u n%u rt%u ct%u unroll%u", kps[a], nps[b], rt, ct, un); - if (BUILD(omega_blackwell_codegen_matmul_frag_block_prog(&s, 1, un, rt, ct, 0, &g_prog))) sweep_prog("matmul_frag_block", v, P_NONE); - } - } } - /* the command list's no-op kernel: EXIT; BRA self */ - { omega_bw_ir_init(&g_prog); - BlackwellIRInsn ex = mk(BW_IR_EXIT, -1, -1, -1, -1, -1, 0), self = mk(BW_IR_BRA, -1, -1, -1, -1, -1, 0x000fc000u); - if (omega_bw_ir_append(&g_prog, &ex) >= 0 && omega_bw_ir_append(&g_prog, &self) >= 0 && omega_bw_regalloc_solve(&g_prog) == 0) sweep_prog("cmdlist_nop", "-", P_NONE); } -} - -/* ----------------------------------------------------------------------------------- disassembler cross-check (C6) */ -static size_t g_dis_insns, g_dis_bad, g_dis_kernels; -static int decoded_has(const OmegaBwInsn *d, int reg, int uniform) { - for (unsigned j = 0; j < d->nr; j++) if (d->rd[j].uniform == uniform && d->rd[j].reg == reg) return 1; - for (unsigned j = 0; j < d->nw; j++) if (d->wr[j].uniform == uniform && d->wr[j].reg == reg) return 1; - return 0; -} -static void disasm_cross_check(const char *family, const char *variant, const uint8_t *code, size_t len) { - size_t seen = 0; g_dis_kernels++; - for (size_t pc = 0; pc * 16u + 16u <= len; pc++) { - const uint8_t *w = code + pc * 16u; - OmegaBwInsn d; if (omega_bw_decode(w, &d) != 0) continue; /* unreachable padding words are not decoded either */ - seen++; g_dis_insns++; - uint64_t lo = 0, hi = 0; - for (int i = 7; i >= 0; i--) { lo = lo << 8 | w[i]; hi = hi << 8 | w[8 + i]; } - char t[256]; - int rc = omega_sm121_disasm(lo, hi, pc * 16u, t, sizeof t); - if (rc != 0) { g_dis_bad++; if (g_dis_bad <= 20) printf("DISASM UNKNOWN %s %s IR %zu: decoder %s, disassembler rc %d lo %016llx hi %016llx\n", family, variant, pc, d.name, rc, (unsigned long long)lo, (unsigned long long)hi); continue; } - /* every register token the disassembler prints must be a base register the decoder has, and vice versa */ - int nvr[16], nvu[16], nn = 0, nu = 0; - for (char *q = t; *q; q++) { - int uni = 0; char *r = q; - if (r[0] == 'U' && r[1] == 'R') { uni = 1; r++; } else if (q > t && (q[-1] == 'U' || q[-1] == 'S' || q[-1] == '_')) continue; - if (r[0] != 'R' || r[1] < '0' || r[1] > '9') continue; - if (q > t && ((q[-1] >= 'A' && q[-1] <= 'Z') || (q[-1] >= 'a' && q[-1] <= 'z') || q[-1] == '_')) continue; - int reg = atoi(r + 1); - if (uni) { if (nu < 16) nvu[nu++] = reg; } else { if (nn < 16) nvr[nn++] = reg; } - q = r + 1; - } - int ok = 1; - for (int i = 0; i < nn && ok; i++) ok = decoded_has(&d, nvr[i], 0); - for (int i = 0; i < nu && ok; i++) ok = decoded_has(&d, nvu[i], 1); - for (unsigned j = 0; j < d.nr + d.nw && ok; j++) { - const OmegaBwOperand *o = j < d.nr ? &d.rd[j] : &d.wr[j - d.nr]; int f2 = 0; - for (int i = 0; i < (o->uniform ? nu : nn); i++) if ((o->uniform ? nvu[i] : nvr[i]) == o->reg) f2 = 1; - ok = f2; - } - if (!ok) { g_dis_bad++; if (g_dis_bad <= 20) printf("DISASM MISMATCH %s %s IR %zu: '%s' vs decoder %s (%u reads, %u writes)\n", family, variant, pc, t, d.name, d.nr, d.nw); } - } - CHECK(seen > 0, "%s %s: disassembled %zu instructions", family, variant, seen); -} - -int main(int argc, char **argv) { - const char *dir = "tests/fixtures/bw_hazard"; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--disasm")) g_disasm = 1; - else if (!strcmp(argv[i], "--fixtures") && i + 1 < argc) dir = argv[++i]; - else if (!strcmp(argv[i], "--dump") && i + 1 < argc) g_dump_dir = argv[++i]; - } - test_decoder_vs_encoder(); - test_red_receipt(dir); - test_controls(); - sweep(); - size_t clean = 0; - printf("sweep per generator (distinct kernels, clean, findings):\n"); - for (size_t i = 0; i < g_nseen; i++) { - clean += g_seen[i].findings == 0; - int first = 1; - for (size_t j = 0; j < i && first; j++) if (!strcmp(g_seen[j].family, g_seen[i].family)) first = 0; - if (!first) continue; - size_t fk = 0, fc = 0, fv = 0; - for (size_t j = i; j < g_nseen; j++) - if (!strcmp(g_seen[j].family, g_seen[i].family)) { fk++; fc += g_seen[j].findings == 0; fv += g_seen[j].findings; } - printf(" %-20s %4zu distinct, %4zu clean, %4zu findings\n", g_seen[i].family, fk, fc, fv); - } - for (size_t k = 0; g_known[k].family; k++) - if (!g_known[k].seen) printf("NOTE: triaged finding %s IR %d %s %sR%u (class %c) no longer seen\n", g_known[k].family, g_known[k].pc == ANY_PC ? -1 : (int)g_known[k].pc, - omega_bw_hazard_kind(g_known[k].kind), g_known[k].uniform ? "U" : "", g_known[k].reg, g_known[k].cls); - printf("sweep: %zu variants built, %zu distinct kernels, %zu clean, %zu with findings, %zu findings, %zu not checked\n", - g_variants, g_nseen, clean, g_nseen - clean - g_unchecked, g_findings_total, g_unchecked); - CHECK(g_nseen >= 50, "the sweep built only %zu distinct kernels", g_nseen); - if (g_disasm) { - printf("disassembler cross-check (sm121dis, in process): %zu kernels, %zu instructions, %zu mismatched\n", g_dis_kernels, g_dis_insns, g_dis_bad); - CHECK(g_dis_bad == 0 && g_dis_insns > 0, "disassembler cross-check"); - } - printf("bw_hazard_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} 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..ba75aff73 --- /dev/null +++ b/tests/cudapp_retirement_sources.json @@ -0,0 +1,1221 @@ +{ + "schema": "AIEN_CANONICAL_GPU_RETIREMENT_V1", + "old_omega_commit": "841001e42fdc87b9d627334add9288f8748a578d", + "old_omega_baseline": "e5b32567a7aff3ce594e3254a622a846a6cd190b", + "canonical_cudapp_commit": "c76412e8941d17df3bb8450c5f546896ba687043", + "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": "13d2e25d92e90c65f3fd41350d454ed1a2dc93e2", + "old_sha256": "0ebca24132e48a42581c6da66b3ca44ae249ca146bbfbd2db89e818a1519fb17", + "canonical_sha256": "ba29abbb988c2573a667c3256dae6bd98b506b9a2948ca5d5ad2ce26979dafeb", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen.h", + "old_git_blob": "30ff3898369d226b6b68c0af2c0d435b4dc1db2c", + "canonical_git_blob": "d1d65f013b92e1e712cdfa39966ec690d9738f78", + "old_sha256": "f468199786d72fddcbe1dbf83a0edda8ebcbf9eb61feef81d4b98f6dbd09ecb8", + "canonical_sha256": "c258e3f5be84a505b1bcc7556f645ee2f335a78494805ceb65d4cfa29f9a7d0d", + "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": "1cec482d7c5bea64ceeac16f6621fc72d876d206", + "old_sha256": "338d11202ce8f1b9f50689eeef6caedfac42565eb26a010f4180154ef25b0464", + "canonical_sha256": "7ecda300ccc39bb55a0f3591b77d4a1c8f734c51bac9de851b0693599b630c63", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_attn256.h", + "old_git_blob": "cf72ac548b54748165732bc781296b069b2ce073", + "canonical_git_blob": "caec480e3f29e0a83e0e0d468bbd8408cfaa647b", + "old_sha256": "ff9b219d753179e59023b2445304f9b0e30947e47345d0dc6e5cdc68f572a81d", + "canonical_sha256": "674495d1cd7b664d66bc526a5430780c4c48ecec44f57b7a1f20b36a4a8716b9", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "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": "c1abd4c6b19c4ef00fd96bd3b1c2a86b01e5b7fd", + "old_sha256": "f32c91d4efe94653b211750d8923c1cca41e74e95266049142d7ca2b7f68f901", + "canonical_sha256": "aa60811aaeec2c240fafd2ae7bcd5efc04fd46cc118c81f55096e74390d88f97", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_gdn.h", + "old_git_blob": "edfcce876a5b4556e241a9a2e2539558bd521942", + "canonical_git_blob": "d82e7c975c293c28c1b02dd44da803f5779d6664", + "old_sha256": "66e921c0951812181f6cf0e5c6daf5a842463bf0d0a08c19291efca30c75c3f3", + "canonical_sha256": "0df446349fea2d8ff38145957e4f983b5eca699e2108bd38904a838394c56d65", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "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": "cd622e2a64226d4c0dca00c995844e8e04476a39", + "old_sha256": "8f7b5cbbf72283e91f293ced5303867a7048620625d56f6ce6579148a9ea58f9", + "canonical_sha256": "d9e9d5619d7e7a3bd3ec3a638458dda2c4073ec2afabcd81321d3c0259245b46", + "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": "c2324467ef061cc46a22ab8d4fb6da2dcdb262bf", + "old_sha256": "681615a9c1d2febc7cebc3cdf578b6b4ae46db64a630a563297f082dd4c316d1", + "canonical_sha256": "2f392a463ce38d7c853a9c9b6568032e57805cfcf67449d31f6d5c3efe69bdf3", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_pattn256.c", + "old_git_blob": "572f15f3309bbf311fb8b853c07c7a6f3aeca1e6", + "canonical_git_blob": "2ee690bc2b3ca5849afd2c52d1c4b733cc6d4723", + "old_sha256": "75659ad5270889ef02e177a46cf44fc0b2d99dbe9d0d8e19f55510da8a789d23", + "canonical_sha256": "573133121b73b8bba792eb0e8e04b0810d149756b0e9f3c3b483b4341088dd7c", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_codegen_pattn256.h", + "old_git_blob": "c910401b6a548e7bf838fdb81eabac9e13a7f557", + "canonical_git_blob": "463e1a9ff851f379b6d441a5edbb7a8fcdd5f3f7", + "old_sha256": "588c6dee94025eb04efe87f02e884171a70b32ab1a5f320087e038868b24039c", + "canonical_sha256": "f605757f163922d764c730429f242bf6f297104093c2fa924a35ad6f7b3768fb", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "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": "1455f9f9dee14c60c38d0a3f2868f8975429749e", + "old_sha256": "7bc72a54fba08bb242f9de21554310fe2409907baaf46463478cb97bafa1f154", + "canonical_sha256": "827fe712309e7685150a3affa4ffe8ea47519b7f0ff847d75d6d954af8b2da1c", + "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": "469dba4b3b4ebd902ac8687e15b2cf69afe32cfb", + "old_sha256": "69e71b849995fea0362efe15b889b6d333e7f4989ba4dd2c55da6448199465b4", + "canonical_sha256": "670aba3eeb0f6c017685b69ea7edebe84466002d2c1150b2050a0d4dbcfa5cb2", + "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": "4c7bc0670527680a6376209d569f08270cbc06bf", + "old_sha256": "72dfe81703830f6096c4012de05519764fe2d4e1d5a307826f0108ff43bcab03", + "canonical_sha256": "f233e776fb28813dbaf73d923c7be83bd9fd160d281e2cc01540efc466d9e3a7", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_engine.h", + "old_git_blob": "31948b06a78e3070af045ad905679908b1813778", + "canonical_git_blob": "658fba52b41a747bb8c52337cb2d91f45c7f104f", + "old_sha256": "fbfddf59aaaf524d5ee72cca026b027431b4dcb3e14ba21c1f5ba7e831e37264", + "canonical_sha256": "a67b60f94429154f0583e52ad3202774923aa35fb09c31a9be99ab51438a482a", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_matmul.c", + "old_git_blob": "28805cfe482265828c6ca6b7b1b583f60852df71", + "canonical_git_blob": "115ec7d79b204a5f0ba34b5f8b049b4d27feaead", + "old_sha256": "fafbc42777d5013c7a0a25e8541108503708a528f90759b9e8ad4c57d37a8cd7", + "canonical_sha256": "b82d777614acb49818bbf7cc2e70a9b41f0e125f4eeef40c0d82421a2f3c39c8", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_blackwell_matmul.h", + "old_git_blob": "2b612e6798ba47a57768e7c02342015455ab17e2", + "canonical_git_blob": "3680e22e2ab8d821bbde32dfe2cc5468a3d31afe", + "old_sha256": "5ab157c30f303b259d7fd330df2ce8d3d355d52d45ebb403f086ea463b172986", + "canonical_sha256": "7e7d7db4018ce64819aaeb6f9ff40f6dea58302c19ba9dc02ba7f254fa2f23ca", + "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": "d435dd9948264589abdce0ea75dc00ef74055e2e", + "old_sha256": "514f547b70dda2c0cc78e648850c3ea1992687fb8019b1759814366a65436047", + "canonical_sha256": "5aac743b0e8234ed7d11f03cae2d1f76db998a39f4689affabbcf2fbfd32ea7f", + "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": "6fadab9d0b4ceb037ab7dac7734286079597f22d", + "old_sha256": "8eace7c1e3c37c30e832b0efbd2ce62d68a49a0d6f5214445e3801a5ba3e225f", + "canonical_sha256": "54382d74a46109f8aeb0f8d57f8388f78a1007aab8de57fe23540d3504c13e8a", + "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": "9b9fdfaefde59645f6c8cd2f61a0075fbc7a5f12", + "old_sha256": "8f4e8cbd19b5e9f5ae4e6ea0b51021e99095c9e27516ab5e0274b6593a8a6367", + "canonical_sha256": "e6bd86bc45b9593c86c409dea10c904608919a54d6199440ec217f68e071fbfb", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_decode_attn256_api.h", + "old_git_blob": "d0212c2cbac34dcd69b8e50b298a94c715039a7f", + "canonical_git_blob": "4dc5cbceb1c95e7d73c5cb8d8773f695faec0df1", + "old_sha256": "8982e000ee58423f7883dee59b80f7ee89ca9d0c5e04b93523a1b1e332b04d35", + "canonical_sha256": "a3f66cfb264e18ce5b44511a607783295b8d0642e55992881a31b2528f272c3a", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "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": "43da6e556a878daaa9ec2d03c80464c1338fa567", + "old_sha256": "7d1d236ff8e022d8af10cecb19d50ca3e1dff9cd2b1fb24a67dd1f74ac4560c3", + "canonical_sha256": "f3f181b7ad799f01e66351976ad273c43b18abf40334d3df8ad824dbfed3319c", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_decode_graph.c", + "old_git_blob": "bba75356453992af2a18622c3b7db084f4136acd", + "canonical_git_blob": "dba9984f72394fa4be71f64894b112e05f966bd6", + "old_sha256": "c20888d43c0dc3c05f50d2f71b5b34fb1c121848c19688a333d91dce89d50bbd", + "canonical_sha256": "5407c95696c717348f62ac496cbd1b3ffd31f8cbd5d1e2788f6dc95a4a92d5ef", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_decode_graph.h", + "old_git_blob": "c213585b224849424bccf2b088ad8b6c46eba984", + "canonical_git_blob": "09706ddf9ed860e5a6279b8f4ee9c9f987e7d9b6", + "old_sha256": "f627563161b6ff68d0646d1a7f4ba9ce9ce5c9ef249ee5a209be723d0c2b3145", + "canonical_sha256": "befb585ee26a86f4e3d577fd9eb7c84339b6013bb2402b2ac570e7d0912ca229", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_elementwise_api.c", + "old_git_blob": "7871035b91175ed90cb2c384c9c757236a41ff5a", + "canonical_git_blob": "6877c8641be2c0a2d57bdf72271468f0e5e6b458", + "old_sha256": "4b9c0dcf32f3babd063f4d0877968c370e47469c307501ef21395f04354c3329", + "canonical_sha256": "9dcf9802d2e32b7e9c4d863363ae4b8d646dba781c8bf1c62ac27eaa76473568", + "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": "5e502950d7cab8b554353d83cfc7e7b6863a1d32", + "old_sha256": "abba3810e41173747efc8ac1ee18971460ff33f25ee3e9a454e88323b379dcea", + "canonical_sha256": "b3cccfe793599561de2823fb76ac13dbc5c0a14fd4ee74c17f908d909bb2a074", + "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": "c8fd2be454262748e4329e05abc65f7901b3ea75", + "old_sha256": "fac508112f066825932aa9c1ea71838000da94c5d8db941b02e68e8b51405189", + "canonical_sha256": "c5e5918604c86241547d16b1c90722a965453aa4755ff2ceac377f9dda148c99", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_gdn_api.h", + "old_git_blob": "cbb53e51f8077b8f1746fc853f542d574873e39b", + "canonical_git_blob": "a2300ebc0f8764c710980333aa37acf944d1d655", + "old_sha256": "7329f43b66c8664d0612a0bf51c384f08a0786b20d918060895d86f7a1fb30a1", + "canonical_sha256": "ee0a73c4b29d67f180006bd2767b08e0959d3fdb0cde1de6486c36fb8dd29ac3", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_gemm.c", + "old_git_blob": "42b47a7d634494221641c977d7f810e314762985", + "canonical_git_blob": "18301a491d2bbafd82dc40ea1269f0ae5907e09f", + "old_sha256": "c1d3f2cbf54f129a680a1c3a16efe217a70b1c35f13547e3c7bb33f0b014bdc5", + "canonical_sha256": "7b36ca11da6a5eb86d1751f6c60e3e019e2809717bb2242a45e351c27da8b0b4", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_gemm.h", + "old_git_blob": "66a6b0485e1c3156e91135d793e6ff1d512559ed", + "canonical_git_blob": "0cb8e4459887248c53bc9f0e9e9c4d3f2d7555c3", + "old_sha256": "b657f8a93b97904570b99d4da8a6879117edae8a83ae6747f1a299019a869661", + "canonical_sha256": "08202866345ee01d567ba7e2de7eb1c36f0f5db6b908365c3398584a53955eef", + "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": "7609b4cc778d55b02ccda5d5aa29fcf3e9c3ead5", + "old_sha256": "10ae3b45cd42a2d92b2331f32491b61b35b68a6cc749c1a12dbbc0dcfc7c0d4b", + "canonical_sha256": "218c86ce796ef12b6ffd56f43ecfb6dec00c84113d6faf05fa03764ca0681698", + "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": "70bb2311863d325ea6ced5753d174ed8277a2d51", + "old_sha256": "fd4e87328ae9f7cfc353595635dea7020d711873e8aa98e69017b7086271153e", + "canonical_sha256": "1f64fc692c1f84e3851de0594e536f640bccd7e03d46cf242b257226f0ca98d3", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_platform_linux.h", + "old_git_blob": "cee1b961ddf8cf48280853f426ef704d904df115", + "canonical_git_blob": "d41374ac9de233bca6ec943fff24b96507ac81f0", + "old_sha256": "83333e21aeeb9a93edfe41328468cd42c691f8f61fe4eb1c3502be4b1a093538", + "canonical_sha256": "52dedbb61dc6d0e940c5adf2f91ad001ce19de96e2256f95be9a0162954c352c", + "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": "6224685a2e6937a659baefd62fbd977cb9e0b1ef", + "old_sha256": "aff7aa1ad520b0e84085877f69e23ae45ad5a714f1f9741c492a2fff41045a38", + "canonical_sha256": "3763d9f2c9e76062a13b6c9d6780f9a67170dc05623d279b5b27f15781de6462", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_prefill_attn256_api.h", + "old_git_blob": "a2960150d2c78881468e4f7b5a4603b60c08af5e", + "canonical_git_blob": "116c3c2513e9845ea50a4de34339641530c0c587", + "old_sha256": "76a921e323f020eb592d1890a92c132690a9ac8269b7f82f7f236d37562d707c", + "canonical_sha256": "f9ee97e304836b89c5ee555dc0598b3e31be47ac613aef412d2c129fd7dfed3b", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "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": "3173682944df6ad3cb030a7cfc9447ad24183e18", + "old_sha256": "46b940b6310d6e18669693d411469c87c2e17e3b7538e6bd4eb1fb48f9705c99", + "canonical_sha256": "4d077a9c13a95d39340b0b90b30364cbcab391d9702de5afa903fc4ad57d492e", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_q36_graph.h", + "old_git_blob": "c14475acfa644db8938c6152e8886c76d778232c", + "canonical_git_blob": "076b03f732ae6b0dde3aea139dca36e2cadd0aa3", + "old_sha256": "b9c609e006f9f3f82455deee81ba4ea954c249e4f542bc8466427ba49f0c9a86", + "canonical_sha256": "8e8c9e47f0ae1e90bedb0489073c63400c0e0e34f579595feaa97033c72f8dbe", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_q38_graph.c", + "old_git_blob": "d890d8261aafcdad70d57686de95bced654c1158", + "canonical_git_blob": "ea1756c46e5349d7baf97816f23e6ed35284f926", + "old_sha256": "95df5f21c5537705ea9ab8ecd1ffe5c80bcaf7b197ec4a1dc5e4e35c64e32130", + "canonical_sha256": "4ef4aad7ad7664425fb03ee1d8dfd1434f91b72603128ffccd7b8f0f7c55d984", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_q38_graph.h", + "old_git_blob": "263b1a3a10f4c51e8a1d06b91d440fe72e9ea814", + "canonical_git_blob": "3e122e2c7ca3a6c33a383da82674d5167cee97ea", + "old_sha256": "d679f32675ce970c2902867c7f089b667d9f7cc594354e92d724464caf2755da", + "canonical_sha256": "75ac3ac0d68b9e93b7b317bb334f36ce9af0767f6b53716c6d20750c616db45b", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "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": "70d8bc3e56f15786242aeb9208888d0999d0f1e4", + "old_sha256": "c1412bcd0d61c880b7b659991551bd71d76a32a3a803d7abb66fe74b4be22b98", + "canonical_sha256": "d62129615e402115ded6d1084c50a23c3eefe1ae26b8073c3851e32e15448239", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_scan.h", + "old_git_blob": "3c775cf6a61cedbc378a07f1880ea22e7695248d", + "canonical_git_blob": "cc97832254040b8b606ed7a748f062d74e69d1ad", + "old_sha256": "71cfb07202533bda9d74ff8bbf3fb96ea7fe02ceb24edb218029cb9fd1af5849", + "canonical_sha256": "0831bded3119cf0e0136e19ff9a4ba053efb2da74a8fea8dab17a588cd656a3e", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_gpu_scan_ref.c", + "old_git_blob": "ab5ee16a5df4f2317fd67ecee2c6e3f7d1e4285d", + "canonical_git_blob": "983cd909501b1ff103533953f828569e67e4e3f0", + "old_sha256": "115a55a9977e6da15c0b1a4dc1490a21b36ca892118108d3e24d8417ef656ed5", + "canonical_sha256": "36dba3ce05e02ea9cd1bdc1f3067270e7cf4bcf31eceb82c50f4c3c2050f7e75", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "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": "95d426cd245a3f7458d7909471a3797d52ed42f1", + "old_sha256": "3391b3b7a074a1c37fffede68a7ce1a48c9f1dd04201162b91ec7ccae46ae26a", + "canonical_sha256": "2cd6865cf7d11673352616c8760484e2c1561a71807d28e469a7a955bafee1f3", + "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": "6a1f7c65aa8af6954dd91c86df27c4c55ed4f238", + "old_sha256": "085e13f304b48e712f434fad27ab6bcef9328b066c2d9b71ebbf25c4c5be46e0", + "canonical_sha256": "439d762560e60fd52bb1418deb9de954217b6f165cb27ad5d03af7b0a012f514", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "src/omega_sm121_disasm.h", + "old_git_blob": "aaf815d6387018ff0ac2598c23dac1398672cb60", + "canonical_git_blob": "8d4b9a88b2f9fd8a89045693e191abaaa8123870", + "old_sha256": "0ac5f436eccde482f9acd61ed0e8358b1e7aeb33f4bdb9ae82f41ba04c41f26b", + "canonical_sha256": "28c2a504ceb4592c517ca05f1dfa9182cf9fe34f3987062ec0728116631abecf", + "old_matches_e5b32567": true, + "byte_identical": false + }, + { + "path": "om/encoder/bw_enc_sm121.om", + "old_git_blob": "4c17bec4a92c5343ba71dbed7689d090afd449a4", + "canonical_git_blob": "a5743c64ae44a92bb9ab70c48aa2bd3352e3ef8c", + "old_sha256": "12369bf1e383e79a4926e7758aaf5f3f778f2945c91327ce0aa570babffc05e6", + "canonical_sha256": "78697de6e6fea65a3afcb5917e85ae18b69bc9833747c376d43d6a7c9ec7f5c7", + "old_matches_e5b32567": false, + "byte_identical": false, + "old_omega_commit": "3a163bc5eafa5be4b9ca97b7f17046c33f0d9032" + }, + { + "path": "src/omega_bw_hazard.c", + "old_git_blob": "026ae76bd0928051186e6ef95fe254d8e837173e", + "canonical_git_blob": "026ae76bd0928051186e6ef95fe254d8e837173e", + "old_sha256": "422da50f12dfa0b322d7a8a63c80b80069181c9c885512fd0c1a789a2807f585", + "canonical_sha256": "422da50f12dfa0b322d7a8a63c80b80069181c9c885512fd0c1a789a2807f585", + "old_matches_e5b32567": false, + "byte_identical": true, + "old_omega_commit": "3a163bc5eafa5be4b9ca97b7f17046c33f0d9032" + }, + { + "path": "src/omega_bw_hazard.h", + "old_git_blob": "cd80642c186037bd172c9b340510b7a7fe994c46", + "canonical_git_blob": "cd80642c186037bd172c9b340510b7a7fe994c46", + "old_sha256": "fb4c85c9151626b62f89f09880778f358d5c438b75b0c909932876c58cc49426", + "canonical_sha256": "fb4c85c9151626b62f89f09880778f358d5c438b75b0c909932876c58cc49426", + "old_matches_e5b32567": false, + "byte_identical": true, + "old_omega_commit": "3a163bc5eafa5be4b9ca97b7f17046c33f0d9032" + }, + { + "path": "src/omega_fp8_slot_table.c", + "old_git_blob": "ca4acd47b8d51a8ff8ebd9d0358799497594ba31", + "canonical_git_blob": "ca4acd47b8d51a8ff8ebd9d0358799497594ba31", + "old_sha256": "4a362c0846ef5bd3546e804c2792752b3cfb74c65b4c05174ed7b9cb816a92bc", + "canonical_sha256": "4a362c0846ef5bd3546e804c2792752b3cfb74c65b4c05174ed7b9cb816a92bc", + "old_matches_e5b32567": false, + "byte_identical": true, + "old_omega_commit": "3a163bc5eafa5be4b9ca97b7f17046c33f0d9032" + }, + { + "path": "src/omega_fp8_slot_table.h", + "old_git_blob": "66dca74ce6fb535764f253aeb119604e4551343f", + "canonical_git_blob": "66dca74ce6fb535764f253aeb119604e4551343f", + "old_sha256": "a38462ed252264371aa87020192eb777f0ba3bdc8fbc28d0300f16d2fb2eb9e7", + "canonical_sha256": "a38462ed252264371aa87020192eb777f0ba3bdc8fbc28d0300f16d2fb2eb9e7", + "old_matches_e5b32567": false, + "byte_identical": true, + "old_omega_commit": "3a163bc5eafa5be4b9ca97b7f17046c33f0d9032" + }, + { + "path": "src/omega_gpu_fp8_internal.h", + "old_git_blob": "4ceca4bcf84ea4b1fc7728cd11fd102d44a59740", + "canonical_git_blob": "4ceca4bcf84ea4b1fc7728cd11fd102d44a59740", + "old_sha256": "13a9606e84f873a0e7b0408c06933c7fcc2052513811c56aef5917f3c7ceacf7", + "canonical_sha256": "13a9606e84f873a0e7b0408c06933c7fcc2052513811c56aef5917f3c7ceacf7", + "old_matches_e5b32567": false, + "byte_identical": true, + "old_omega_commit": "3a163bc5eafa5be4b9ca97b7f17046c33f0d9032" + }, + { + "path": "src/omega_gpu_fp8_slots.c", + "old_git_blob": "839f466a09f20db060d6badab70776cfdf9cbc93", + "canonical_git_blob": "839f466a09f20db060d6badab70776cfdf9cbc93", + "old_sha256": "3d00d9992b4ece148de9f3bcbd1dc1b1b30f0f765d437fbae150dfc10d04fb86", + "canonical_sha256": "3d00d9992b4ece148de9f3bcbd1dc1b1b30f0f765d437fbae150dfc10d04fb86", + "old_matches_e5b32567": false, + "byte_identical": true, + "old_omega_commit": "3a163bc5eafa5be4b9ca97b7f17046c33f0d9032" + }, + { + "path": "src/omega_gpu_fp8_slots.h", + "old_git_blob": "1ad8f6475a2eca4708798175b8a550e7bb706398", + "canonical_git_blob": "1ad8f6475a2eca4708798175b8a550e7bb706398", + "old_sha256": "626a77b5e136a54db8933c9c353fa5e0aad5f887ba195224b4217724d1800d36", + "canonical_sha256": "626a77b5e136a54db8933c9c353fa5e0aad5f887ba195224b4217724d1800d36", + "old_matches_e5b32567": false, + "byte_identical": true, + "old_omega_commit": "3a163bc5eafa5be4b9ca97b7f17046c33f0d9032" + } + ] +} 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/fake_m16_native.c b/tests/fake_m16_native.c deleted file mode 100644 index 54f204c26..000000000 --- a/tests/fake_m16_native.c +++ /dev/null @@ -1,500 +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. - */ - -/* - * Simulated GB10 driver. See tests/fake_m16_native.h for what it models. - * NOT_RUN: written in cut A3b2, never compiled or executed by its author. - * - * Linked INSTEAD of physics/m16/m16_native.c and physics/nvrm/nvrm.c. The - * physics headers are still included, so the types (Nvrm, NvrmMem, - * M16NativeContext) and the prototypes are the real ones. - */ -#include "fake_m16_native.h" -#include "m16_native.h" - -#include -#include -#include -#include - - -FakeDriver fk; - -typedef struct { - uint32_t handle; - void *ptr; - uint64_t size; -} LiveAlloc; - -static LiveAlloc g_live[FK_LIVE_MAX]; -static uint32_t g_next_handle; -static void *g_chan_pb; /* the channel's own 4 KiB pushbuffer, not counted in fk.live */ - -/* ---- test-side helpers ---------------------------------------------------- */ - -void fake_release_all(void) -{ - size_t i; - for (i = 0; i < FK_LIVE_MAX; i++) { - if (g_live[i].handle != 0) { - free(g_live[i].ptr); - g_live[i].handle = 0; - g_live[i].ptr = NULL; - } - } - fk.live = 0; - free(g_chan_pb); - g_chan_pb = NULL; -} - -void fake_reset(void) -{ - fake_release_all(); - memset(&fk, 0, sizeof fk); - g_next_handle = 0; -} - -uint64_t fake_now_ms(void) -{ - return fk.clock_ms; -} - -int fake_count(int kind) -{ - int i; - int n = 0; - for (i = 0; i < fk.nev; i++) - if (fk.ev[i].kind == kind) n++; - return n; -} - -int fake_nth(int kind, int nth) -{ - int i; - int n = 0; - for (i = 0; i < fk.nev; i++) { - if (fk.ev[i].kind != kind) continue; - n++; - if (n == nth) return i; - } - return -1; -} - -/* ---- internal ------------------------------------------------------------- */ - -static void logev(int kind, uint64_t a, uint64_t b, uint64_t c) -{ - if (fk.nev >= FK_EV_MAX) { - fk.ev_overflow = 1; - return; - } - fk.ev[fk.nev].kind = kind; - fk.ev[fk.nev].a = a; - fk.ev[fk.nev].b = b; - fk.ev[fk.nev].c = c; - fk.nev++; -} - -/* A failed driver call: errno and the driver's own text, like the real nvrm does. */ -static int inject(Nvrm *rm, int rc) -{ - errno = EIO; - if (rm) (void)snprintf(rm->err, sizeof rm->err, "%s", FK_TEXT); - return rc; -} - -static void live_add(uint32_t handle, void *ptr, uint64_t size) -{ - size_t i; - for (i = 0; i < FK_LIVE_MAX; i++) { - if (g_live[i].handle == 0) { - g_live[i].handle = handle; - g_live[i].ptr = ptr; - g_live[i].size = size; - fk.live++; - return; - } - } - free(ptr); /* the table is full: more live buffers than any test needs */ -} - -/* Returns 1 if the handle was live and is now released, else 0. */ -static int live_release(uint32_t handle) -{ - size_t i; - for (i = 0; i < FK_LIVE_MAX; i++) { - if (g_live[i].handle == handle) { - free(g_live[i].ptr); - g_live[i].handle = 0; - g_live[i].ptr = NULL; - fk.live--; - return 1; - } - } - return 0; -} - -static volatile uint32_t *word_at(uint64_t va) -{ - return (volatile uint32_t *)(uintptr_t)va; -} - -/* ---- the simulated GPU: pushbuffer parser and kernel ---------------------- */ - -/* The vector kernel: QMD1 words give the program address (32, 33), the thread - * count (34 and 39), the constant bank (42, 43) and the completion semaphore - * (15, 16, 17), as written by src/omega_blackwell_qmd.c. The arguments are read - * from constant bank + 0x380: a, b, c addresses (lo, hi) and the element count. */ -static void run_kernel(const uint32_t *q) -{ - uint64_t prog = ((uint64_t)(q[33] & 0x1fffffu) << 36) | ((uint64_t)q[32] << 4); - uint64_t cb = ((uint64_t)(q[43] & 0x7ffffu) << 38) | ((uint64_t)q[42] << 6); - uint64_t threads = (uint64_t)(q[34] & 0xffffu) * (uint64_t)q[39]; - const uint32_t *args = (const uint32_t *)(uintptr_t)(cb + 0x380u); - uint32_t *a = (uint32_t *)(uintptr_t)(((uint64_t)args[1] << 32) | args[0]); - uint32_t *b = (uint32_t *)(uintptr_t)(((uint64_t)args[3] << 32) | args[2]); - uint32_t *c = (uint32_t *)(uintptr_t)(((uint64_t)args[5] << 32) | args[4]); - uint32_t n = args[6]; - uint64_t sem = ((uint64_t)q[16] << 32) | q[15]; - - if (fk.kernel_mode == FK_KERNEL_SKIP) { /* the kernel is not modelled: count the launch, release the semaphore */ - fk.kernel_ran++; - if (fk.sem_mode != FK_SYNC_NEVER) *word_at(sem) = q[17] + (fk.sem_mode == FK_SYNC_OVERSHOOT ? 1u : 0u); - return; - } - uint64_t count = n < threads ? n : threads; - uint32_t i; - int ok = 1; - - fk.kernel_ran++; - fk.kernel_threads = threads; - fk.arg_a = (uint64_t)(uintptr_t)a; - fk.arg_b = (uint64_t)(uintptr_t)b; - fk.arg_c = (uint64_t)(uintptr_t)c; - fk.prog_va_seen = prog; - fk.cbank_va_seen = cb; - fk.kernel_n = n; - if (fk.prog_expect != NULL && fk.prog_len != 0) - ok = memcmp((const void *)(uintptr_t)prog, fk.prog_expect, fk.prog_len) == 0; - fk.prog_matched = ok; - logev(FK_EV_KERNEL, threads, n, 0); - - /* What the device output holds just before the kernel runs, and whether the - * poison words collide with the correct sums. */ - fk.snap_n = n < FK_SNAP_WORDS ? n : FK_SNAP_WORDS; - for (i = 0; i < fk.snap_n; i++) { - fk.out_before[i] = c[i]; - if (c[i] == (uint32_t)(a[i] + b[i])) fk.poison_collisions++; - } - - if (ok && fk.kernel_mode != FK_KERNEL_NO_WRITE) { - if (fk.kernel_mode == FK_KERNEL_HALF) count /= 2u; - for (i = 0; i < count; i++) { - c[i] = (uint32_t)(a[i] + b[i]); - if (fk.kernel_mode == FK_KERNEL_WRONG) c[i] += 1u; - } - } - - /* Completion semaphore (RELEASE_SEMAPHORE0 of the QMD): value q[17]. */ - if (fk.sem_mode != FK_SYNC_NEVER) - *word_at(sem) = q[17] + (fk.sem_mode == FK_SYNC_OVERSHOOT ? 1u : 0u); -} - -/* SEND_PCAS_A carries the QMD address >> 8 in 32 bits (a 40-bit GPU address). The fake's GPU address is the host - * pointer, which can be wider: find the live allocation whose low 40 bits match. NULL if none does. */ -static const uint32_t *qmd_from_shifted8(uint32_t s8) -{ - const uint64_t low = (uint64_t)s8 << 8, mask40 = (1ull << 40) - 1u; - size_t i; - for (i = 0; i < FK_LIVE_MAX; i++) { - uint64_t base = (uint64_t)(uintptr_t)g_live[i].ptr, a = (base & ~mask40) | low; - if (g_live[i].handle == 0) continue; - if (a < base) a += 1ull << 40; - if (a >= base && a + 96u * 4u <= base + g_live[i].size) return (const uint32_t *)(uintptr_t)a; - } - return NULL; -} - -/* Walks the submitted pushbuffer. exec == 0 only collects addresses (so the - * state at the doorbell can be captured first); exec == 1 runs it. Every packet - * is a header (type 2 or 6 in bits 31:28, count in 28:16, subchannel in 15:13, - * method in 11:0 times 4) followed by count data words. */ -static void walk(const uint32_t *w, size_t n, int exec) -{ - size_t i = 0; - uint64_t dst = 0; - uint32_t line_bytes = 0; - uint32_t lines = 0; - int nrel = 0; - int flushed = 0; - - while (i < n) { - uint32_t h = w[i++]; - uint32_t type = h >> 28; - uint32_t cnt = (h >> 16) & 0x1fffu; - uint32_t subc = (h >> 13) & 7u; - uint32_t mthd = (h & 0xfffu) << 2; - const uint32_t *d; - - if ((type != 2u && type != 6u) || i + cnt > n) { - fk.pb_parse_error = 1; - return; - } - d = &w[i]; - i += cnt; - - if (subc == 1u && mthd == 0x0188u && cnt == 2u) { - dst = ((uint64_t)d[0] << 32) | d[1]; - } else if (subc == 1u && mthd == 0x0180u && cnt == 2u) { - line_bytes = d[0]; - lines = d[1]; - } else if (subc == 1u && mthd == 0x01b4u) { - if (dst == 0 || (uint64_t)cnt * 4u != (uint64_t)line_bytes * lines) { - fk.pb_parse_error = 1; - continue; - } - if (!exec) { - if (cnt == 1u) { - fk.sem_va = dst; - fk.sem_init_value = d[0]; - } - } else { - memcpy((void *)(uintptr_t)dst, d, (size_t)cnt * 4u); - if (cnt == 224u) logev(FK_EV_PB_CBANK, dst, cnt, 0); - else if (cnt == 7u) logev(FK_EV_PB_ARGS, dst, cnt, 0); - else if (cnt == 1u) logev(FK_EV_PB_SEM_INIT, dst, d[0], 0); - } - } else if (subc == 1u && mthd == 0x0318u && cnt == 98u) { - uint64_t qaddr = ((uint64_t)(d[0] & 0x1ffu) << 40) | ((uint64_t)d[1] << 8); - const uint32_t *q = d + 2; - int launch = ((d[0] >> 30) & 1u) != 0; - if (exec) { - if (qaddr == 0) { - fk.pb_parse_error = 1; - continue; - } - memcpy((void *)(uintptr_t)qaddr, q, 96u * 4u); - logev(FK_EV_PB_QMD, qaddr, (launch && (q[9] & 1u) != 0) ? 1u : 0u, 0); - if (launch && (q[9] & 1u) != 0) run_kernel(q); - } - } else if (subc == 1u && mthd == 0x02b4u && cnt == 1u) { - /* SEND_PCAS_A (clcec0.h, QMD address >> 8): a standalone QMD the command list (src/omega_gpu_cmdlist.c) - * wrote to memory. Modelled only with FK_KERNEL_SKIP: the launch releases its completion semaphore. */ - const uint32_t *q = exec && fk.kernel_mode == FK_KERNEL_SKIP ? qmd_from_shifted8(d[0]) : NULL; - if (q && (q[9] & 1u) != 0) run_kernel(q); - } else if (subc == 0u && mthd == 0x005cu && cnt == 5u) { - uint64_t addr = ((uint64_t)d[1] << 32) | d[0]; - uint32_t payload = d[2]; - uint32_t flags = d[4]; - nrel++; - if (!exec) { - if (nrel == 1) fk.marker1_va = addr; - else if (nrel == 2) fk.marker2_va = addr; - } else { - int mode = nrel == 1 ? fk.marker_mode : fk.marker2_mode; - int writes = (flags & 1u) != 0; - logev(FK_EV_PB_RELEASE, addr, payload, flags); - if (nrel <= 2) fk.release_flags[nrel - 1] = flags; - /* Modelling choice: the second release only lands if an L2 flush - * memory operation came between the two releases. */ - if (nrel == 2 && !flushed) writes = 0; - if (mode == FK_SYNC_NEVER) writes = 0; - if (writes && addr != 0) - *word_at(addr) = payload + (mode == FK_SYNC_OVERSHOOT ? 1u : 0u); - flushed = 0; - } - } else if (subc == 0u && mthd == 0x0028u && cnt == 4u) { - if (exec) { - logev(FK_EV_PB_FLUSH, d[3], 0, 0); - if (d[3] == (0x10u << 27)) flushed = 1; - } - } - /* every other packet is a setup method: ignored */ - } -} - -/* ---- the seven faked symbols ---------------------------------------------- */ - -int m16_native_open(M16NativeContext *ctx) -{ - if (!ctx) return -1; - memset(ctx, 0, sizeof *ctx); - fk.open_calls++; - logev(FK_EV_OPEN, 0, 0, 0); - if (fk.open_fail) return inject(&ctx->rm, -1); - fk.device_open = 1; - return 0; -} - -int m16_native_create_channel(M16NativeContext *ctx) -{ - void *p = NULL; - if (!ctx) return -1; - fk.channel_calls++; - logev(FK_EV_CHANNEL, 0, 0, 0); - if (fk.channel_fail) return inject(&ctx->rm, -1); - if (posix_memalign(&p, 4096, 0x1000) != 0) return -1; - memset(p, 0, 0x1000); - ctx->pb_mem.handle = ++g_next_handle; - ctx->pb_mem.size = 0x1000; - ctx->pb_mem.cpu = p; - ctx->pb_mem.va = (uint64_t)(uintptr_t)p; - g_chan_pb = p; - fk.channel_up = 1; - return 0; -} - -int nvrm_alloc(Nvrm *rm, uint64_t size, NvrmMem *out) -{ - void *p = NULL; - int mode = -1; - fk.alloc_calls++; - logev(FK_EV_ALLOC, size, 0, 0); - if (!out || size == 0 || size > (fk.alloc_max ? fk.alloc_max : 0x100000u)) return -1; - if (fk.alloc_fail_nth != 0 && fk.alloc_fail_nth == fk.alloc_calls) { - mode = fk.alloc_mode; - if (mode == FK_ALLOC_FAIL) return inject(rm, -1); - } - if (posix_memalign(&p, 4096, (size_t)size) != 0) return -1; - memset(p, 0x5a, (size_t)size); /* dirty memory */ - out->handle = ++g_next_handle; - out->size = size; - out->cpu = p; - out->va = (uint64_t)(uintptr_t)p; - live_add(out->handle, p, size); - if (fk.alloc_size_n < FK_SIZE_LOG) fk.alloc_size_log[fk.alloc_size_n] = size; - fk.alloc_size_n++; - if (fk.alloc_calls >= 1 && fk.alloc_calls <= 16) fk.alloc_va[fk.alloc_calls - 1] = out->va; - if (mode == FK_ALLOC_NO_CPU) out->cpu = NULL; - else if (mode == FK_ALLOC_SHORT) out->size = size / 2u; - else if (mode == FK_ALLOC_MISALIGNED) out->va += 0x10u; - return 0; -} - -/* Same as nvrm_alloc (the fake has no GPU cache); only counts the uncached request. */ -int nvrm_alloc_gpu_uncached(Nvrm *rm, uint64_t size, NvrmMem *out) -{ - fk.uncached_calls++; - return nvrm_alloc(rm, size, out); -} - -int nvrm_free(Nvrm *rm, NvrmMem *m) -{ - if (!m || m->handle == 0) return 0; /* a zeroed NvrmMem is a no-op (nvrm.h) */ - fk.free_calls++; - logev(FK_EV_FREE, m->handle, 0, 0); - if (fk.free_fail_nth != 0 && fk.free_fail_nth == fk.free_calls) return inject(rm, -1); - if (fk.free_size_n < FK_SIZE_LOG) fk.free_size_log[fk.free_size_n] = m->size; - fk.free_size_n++; - if (!live_release(m->handle)) { - fk.double_free++; - errno = EINVAL; - return -1; - } - memset(m, 0, sizeof *m); - errno = EBADF; /* a real free runs munmap and ioctl calls, which may change errno */ - return 0; -} - -int m16_native_submit_methods(M16NativeContext *ctx, const uint32_t *methods, size_t count) -{ - if (!ctx || !methods || count == 0) return -1; - fk.submit_calls++; - logev(FK_EV_SUBMIT, count, 0, 0); - if (fk.submit_fail && fk.submit_faults_device) ctx->rm.faulted = 1; - if (!fk.channel_up || fk.submit_fail) return inject(&ctx->rm, -1); - /* Like m16_native_enqueue_methods: the words must fit the ring buffer. */ - if (count > ctx->pb_mem.size / sizeof(uint32_t) || count > FK_PB_MAX) return inject(&ctx->rm, -1); - fk.pb_mem_size = ctx->pb_mem.size; - memcpy(fk.pb, methods, count * sizeof(uint32_t)); - fk.pb_len = count; - - walk(fk.pb, count, 0); - if (fk.marker1_va != 0 && fk.sem_va != 0) { - fk.pre_marker1 = *word_at(fk.marker1_va); - fk.pre_marker2 = fk.marker2_va != 0 ? *word_at(fk.marker2_va) : 0u; - fk.pre_sem = *word_at(fk.sem_va); - fk.pre_valid = 1; - } - walk(fk.pb, count, 1); - return 0; -} - -static int which_word(volatile uint32_t *p) -{ - uint64_t a = (uint64_t)(uintptr_t)p; - if (p == NULL) return FK_W_UNKNOWN; - if (fk.marker1_va != 0 && a == fk.marker1_va) return FK_W_MARKER1; - if (fk.marker2_va != 0 && a == fk.marker2_va) return FK_W_MARKER2; - if (fk.sem_va != 0 && a == fk.sem_va) return FK_W_SEM; - return FK_W_UNKNOWN; -} - -/* The real wait is a ">=" serial compare in a loop with a deadline. The fake - * checks once and, if it is not satisfied, "waits" the whole timeout by - * advancing the fake clock. */ -int m16_native_wait_marker(volatile uint32_t *marker, uint32_t expected, uint64_t timeout_ms) -{ - int w = which_word(marker); - fk.wait_calls++; - fk.wait_n[w]++; - fk.wait_ms[w] = timeout_ms; - fk.wait_expected[w] = expected; - logev(FK_EV_WAIT, (uint64_t)w, expected, timeout_ms); - if (!marker) return -1; - if ((int32_t)(*marker - expected) >= 0) return 0; - fk.clock_ms += timeout_ms; - return -1; -} - -int m16_native_close(M16NativeContext *ctx) -{ - int rc = 0; - if (!ctx) return -1; - fk.close_calls++; - fk.live_at_close = fk.live; - logev(FK_EV_CLOSE, (uint64_t)fk.live, 0, 0); - /* Like nvrm_close: whatever is still allocated is released here. */ - fake_release_all(); - fk.device_open = 0; - if (fk.close_fail) rc = inject(&ctx->rm, -1); - return rc; -} - -/* L136: the simulated driver has one channel. Extra channels (AIEN_OMEGA_GPU_CHANNELS > 1) are refused here, so the - * platform's device_open refuses with stage "nvrm_channel_n"; the multi-channel path is proven on the chip only. */ -int nvrm_channel_n(Nvrm *rm, uint32_t extra) -{ - (void)rm; (void)extra; - return -1; -} - -int nvrm_chan_submit(Nvrm *rm, uint32_t ch, const NvrmMem *pb, uint32_t off_bytes, uint32_t nwords) -{ - (void)rm; (void)ch; (void)pb; (void)off_bytes; (void)nwords; - return -1; -} - -void nvrm_chan_retire(Nvrm *rm, uint32_t ch, uint32_t upto) -{ - (void)rm; (void)ch; (void)upto; -} - -uint32_t nvrm_chan_put(const Nvrm *rm, uint32_t ch) -{ - (void)rm; (void)ch; - return 0; -} diff --git a/tests/fake_m16_native.h b/tests/fake_m16_native.h deleted file mode 100644 index cdb48ee87..000000000 --- a/tests/fake_m16_native.h +++ /dev/null @@ -1,184 +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. - */ - -/* - * Simulated GB10 driver for the host test of the Blackwell GPU engine backend - * (tests/test_omega_blackwell_engine.c). NOT_RUN: written in cut A3b2 and never - * compiled or executed by its author. - * - * It replaces seven symbols of the real driver stack, so the REAL backend - * (src/omega_blackwell_engine.c) and the REAL vector wrapper - * (src/omega_blackwell_submit.c) run unchanged on a machine with no GPU: - * m16_native_open, m16_native_create_channel, m16_native_submit_methods, - * m16_native_wait_marker, m16_native_close, nvrm_alloc, nvrm_free. - * The signatures come from physics/m16/m16_native.h and physics/nvrm/nvrm.h at - * the physics pin; the fake file includes those headers, so a mismatch is a - * compile error. - * - * What it models (every point is a MODEL, UNVERIFIED on the chip, confidence - * about 70 percent that it matches the real driver): - * - "device" memory is host memory, GPU address equals CPU address, dirty - * (0x5a fill) so a missing zeroing step shows up; - * - the submitted pushbuffer is parsed and executed in order: DMA uploads, - * the two inline QMDs, the semaphore initial value, the release packets and - * the L2 flush memory operation (method 0x28, operation 0x10 << 27); - * - the vector kernel is a simple loop (c[i] = a[i] + b[i] for the threads the - * QMD asks for) and only runs if the program bytes in device memory are the - * bytes the test expects; - * - the second marker release is only written if an L2 flush operation - * appears between the two releases (modelling choice, see the doc); - * - m16_native_wait_marker is the real ">=" serial compare with no loop; a - * timeout advances the fake clock by the timeout so waited_ms is exact; - * - nvrm_free of a zeroed NvrmMem is a no-op that counts nothing, a real free - * zeroes the NvrmMem and clobbers errno (like a munmap or ioctl might). - */ -#ifndef FAKE_M16_NATIVE_H -#define FAKE_M16_NATIVE_H - -#include -#include - -#define FK_TEXT "fake driver says no" -#define FK_EV_MAX 512 -#define FK_SNAP_WORDS 256 -#define FK_PB_MAX 16384 /* the whole 64 KiB session ring (omega_gpu_cmdlist.c RING_WORDS), so a near-full command list fits */ - -/* Event kinds in the log (fk.ev). */ -enum { - FK_EV_OPEN = 1, - FK_EV_CHANNEL, - FK_EV_ALLOC, /* a = bytes asked */ - FK_EV_FREE, /* a = handle */ - FK_EV_SUBMIT, /* a = word count */ - FK_EV_WAIT, /* a = FK_W_*, b = expected value, c = timeout ms */ - FK_EV_CLOSE, /* a = live allocations at the moment of close */ - FK_EV_PB_CBANK, /* a = destination, b = words (224) */ - FK_EV_PB_ARGS, /* a = destination, b = words (7) */ - FK_EV_PB_SEM_INIT, /* a = destination, b = value */ - FK_EV_PB_QMD, /* a = QMD address, b = 1 if it is the kernel QMD */ - FK_EV_PB_RELEASE, /* a = address, b = payload, c = flags word */ - FK_EV_PB_FLUSH, /* a = operation word (last word of the packet) */ - FK_EV_KERNEL /* a = threads, b = element count */ -}; - -/* Which coherent word a wait looked at. */ -enum { FK_W_UNKNOWN = 0, FK_W_MARKER1, FK_W_MARKER2, FK_W_SEM, FK_W_COUNT }; - -enum { FK_ALLOC_FAIL = 0, FK_ALLOC_NO_CPU, FK_ALLOC_SHORT, FK_ALLOC_MISALIGNED }; -enum { FK_SYNC_NORMAL = 0, FK_SYNC_NEVER, FK_SYNC_OVERSHOOT }; -/* FK_KERNEL_SKIP: run no kernel at all and only release the completion semaphore (for tests that count - * driver calls with kernels the fake does not model, such as the matmul and attention launches). */ -enum { FK_KERNEL_OK = 0, FK_KERNEL_NO_WRITE, FK_KERNEL_HALF, FK_KERNEL_WRONG, FK_KERNEL_SKIP }; - -#define FK_SIZE_LOG 8192 -#define FK_LIVE_MAX 128 /* live driver buffers the fake can track at once */ - -typedef struct { - int kind; - uint64_t a; - uint64_t b; - uint64_t c; -} FakeEvent; - -typedef struct { - /* ---- faults and behaviour, set by the test after fake_reset ---- */ - int open_fail; - int channel_fail; - int submit_fail; - int submit_faults_device; /* with submit_fail: the failed submit also sets rm.faulted, as a channel error does */ - int close_fail; - uint64_t alloc_max; /* largest nvrm_alloc the fake grants, 0 = the default 1 MiB */ - int alloc_fail_nth; /* 1-based nvrm_alloc call that misbehaves, 0 = none */ - int alloc_mode; /* FK_ALLOC_* for that call */ - int free_fail_nth; /* 1-based real nvrm_free call that fails, 0 = none */ - int marker_mode; /* FK_SYNC_*: first marker release */ - int marker2_mode; /* FK_SYNC_*: second marker release */ - int sem_mode; /* FK_SYNC_*: kernel completion semaphore */ - int kernel_mode; /* FK_KERNEL_* */ - const void *prog_expect; /* program bytes the device memory must hold, NULL = do not check */ - size_t prog_len; - - /* ---- observations ---- */ - uint64_t clock_ms; /* the fake millisecond clock (fake_now_ms) */ - int open_calls; - int channel_calls; - int alloc_calls; - int uncached_calls; /* allocations made through nvrm_alloc_gpu_uncached (also counted in alloc_calls) */ - int free_calls; /* real frees only (a zeroed NvrmMem is not counted) */ - int close_calls; - int submit_calls; - int wait_calls; - int double_free; /* frees of a handle that was not live */ - int live; /* live backend allocations right now (not the channel's own 4 KiB buffer) */ - int live_at_close; /* live allocations when m16_native_close was called */ - int device_open; - int channel_up; - uint64_t pb_mem_size; /* ctx->pb_mem.size when the pushbuffer was submitted */ - int pb_parse_error; /* the pushbuffer had a packet the fake could not parse */ - uint32_t pb[FK_PB_MAX]; - size_t pb_len; - - uint64_t marker1_va; /* first release address, from the pushbuffer */ - uint64_t marker2_va; /* second release address, 0 with NO_C3 */ - uint64_t sem_va; /* destination of the semaphore initial value DMA */ - uint32_t sem_init_value; - uint32_t pre_marker1; /* values the GPU would see at the doorbell */ - uint32_t pre_marker2; - uint32_t pre_sem; - int pre_valid; /* the three pre_* values were captured */ - int kernel_ran; - int prog_matched; - uint64_t kernel_threads; - uint64_t kernel_n; - uint32_t out_before[FK_SNAP_WORDS]; /* device output words just before the kernel ran */ - size_t snap_n; - int poison_collisions; /* snapshot words equal to the correct sum (a bad poison word) */ - uint32_t release_flags[2]; - uint64_t alloc_va[16]; /* GPU address of the nth nvrm_alloc (1-based nth stored at [nth - 1]) */ - uint64_t arg_a; /* kernel argument addresses the device saw in the constant bank */ - uint64_t arg_b; - uint64_t arg_c; - uint64_t prog_va_seen; /* program address from QMD1 */ - uint64_t cbank_va_seen;/* constant bank address from QMD1 */ - - int wait_n[FK_W_COUNT]; - uint64_t wait_ms[FK_W_COUNT]; - uint32_t wait_expected[FK_W_COUNT]; - - uint64_t alloc_size_log[FK_SIZE_LOG]; /* size asked by the nth granted nvrm_alloc (0-based), first FK_SIZE_LOG only */ - int alloc_size_n; - uint64_t free_size_log[FK_SIZE_LOG]; /* size of the nth real nvrm_free */ - int free_size_n; - - FakeEvent ev[FK_EV_MAX]; - int nev; - int ev_overflow; -} FakeDriver; - -extern FakeDriver fk; - -/* Frees every host allocation the fake still holds (the test's own teardown, not a driver call). */ -void fake_release_all(void); -/* fake_release_all, then zero the whole state. Call at the start of every case. */ -void fake_reset(void); -/* Millisecond clock for omega_gpu_engine_test_set_clock. */ -uint64_t fake_now_ms(void); -/* Number of events of this kind in the log. */ -int fake_count(int kind); -/* Index of the nth (1-based) event of this kind, or -1. */ -int fake_nth(int kind, int nth); - -#endif diff --git a/tests/gates/omega-argus.gate b/tests/gates/omega-argus.gate index 1d22b9fda..b15dbf1b3 100644 --- a/tests/gates/omega-argus.gate +++ b/tests/gates/omega-argus.gate @@ -18,6 +18,7 @@ inputs: - src/omega_evidence.c - src/omega_evidence.h - physics.lock + - cudapp.lock - aienos.lock - argus.lock - tests/gates/ diff --git a/tests/gates/omega-base.gate b/tests/gates/omega-base.gate index c22391275..186320f5f 100644 --- a/tests/gates/omega-base.gate +++ b/tests/gates/omega-base.gate @@ -13,6 +13,7 @@ inputs: - tools/ - tests/gates/ - physics.lock + - cudapp.lock run: exec: tests/gates/run.sh args: ["base"] diff --git a/tests/gates/omega-bw-hazard.gate b/tests/gates/omega-bw-hazard.gate index 9b225944b..3242d9d51 100644 --- a/tests/gates/omega-bw-hazard.gate +++ b/tests/gates/omega-bw-hazard.gate @@ -12,6 +12,7 @@ inputs: - tests/ - tools/ - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-gpu-attention.gate b/tests/gates/omega-gpu-attention.gate index 35a0752b5..007ac020f 100644 --- a/tests/gates/omega-gpu-attention.gate +++ b/tests/gates/omega-gpu-attention.gate @@ -12,6 +12,7 @@ inputs: - tests/gpu_attention_test.c - tests/bw_warp_sim.h - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-gpu-decode-graph.gate b/tests/gates/omega-gpu-decode-graph.gate index 2eed6c402..4fe7b300f 100644 --- a/tests/gates/omega-gpu-decode-graph.gate +++ b/tests/gates/omega-gpu-decode-graph.gate @@ -12,6 +12,7 @@ inputs: - tests/ - tools/ - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-gpu-libm-free.gate b/tests/gates/omega-gpu-libm-free.gate index 385fe79b4..6dd76dff5 100644 --- a/tests/gates/omega-gpu-libm-free.gate +++ b/tests/gates/omega-gpu-libm-free.gate @@ -10,6 +10,7 @@ inputs: - mk/ - src/ - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-m10.gate b/tests/gates/omega-m10.gate index 61518c313..64169bbd4 100644 --- a/tests/gates/omega-m10.gate +++ b/tests/gates/omega-m10.gate @@ -13,6 +13,7 @@ inputs: - tests/ - tools/omegatool.c - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-m11.gate b/tests/gates/omega-m11.gate index 86936d883..cc9a49339 100644 --- a/tests/gates/omega-m11.gate +++ b/tests/gates/omega-m11.gate @@ -13,6 +13,7 @@ inputs: - tests/ - tools/omegatool.c - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-m12.gate b/tests/gates/omega-m12.gate index fd6d6576f..9ca09e73c 100644 --- a/tests/gates/omega-m12.gate +++ b/tests/gates/omega-m12.gate @@ -13,6 +13,7 @@ inputs: - tests/ - tools/omegatool.c - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-m13.gate b/tests/gates/omega-m13.gate index 1c333dfd9..b20ade9ee 100644 --- a/tests/gates/omega-m13.gate +++ b/tests/gates/omega-m13.gate @@ -13,6 +13,7 @@ inputs: - tests/ - tools/omegatool.c - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-m14.gate b/tests/gates/omega-m14.gate index 32a125976..3dd5140e9 100644 --- a/tests/gates/omega-m14.gate +++ b/tests/gates/omega-m14.gate @@ -13,6 +13,7 @@ inputs: - tests/ - tools/omegatool.c - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-m15.gate b/tests/gates/omega-m15.gate index a8702cb91..33c2395df 100644 --- a/tests/gates/omega-m15.gate +++ b/tests/gates/omega-m15.gate @@ -13,6 +13,7 @@ inputs: - tests/ - tools/omegatool.c - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-m17.gate b/tests/gates/omega-m17.gate index 2aa3a72b9..f71508f09 100644 --- a/tests/gates/omega-m17.gate +++ b/tests/gates/omega-m17.gate @@ -11,6 +11,7 @@ inputs: - src/ - tests/ - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-m6.gate b/tests/gates/omega-m6.gate index 1bee2e814..b140e70c8 100644 --- a/tests/gates/omega-m6.gate +++ b/tests/gates/omega-m6.gate @@ -13,6 +13,7 @@ inputs: - tests/ - tools/omegatool.c - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-m7.gate b/tests/gates/omega-m7.gate index 28413a2c9..ee5b3d63d 100644 --- a/tests/gates/omega-m7.gate +++ b/tests/gates/omega-m7.gate @@ -13,6 +13,7 @@ inputs: - tests/ - tools/omegatool.c - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-m8.gate b/tests/gates/omega-m8.gate index 39f362e8e..55924e9e3 100644 --- a/tests/gates/omega-m8.gate +++ b/tests/gates/omega-m8.gate @@ -13,6 +13,7 @@ inputs: - tests/ - tools/omegatool.c - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-m9.gate b/tests/gates/omega-m9.gate index 763a7ab99..4e0b058a5 100644 --- a/tests/gates/omega-m9.gate +++ b/tests/gates/omega-m9.gate @@ -13,6 +13,7 @@ inputs: - tests/ - tools/omegatool.c - physics.lock + - cudapp.lock - tests/gates/ run: exec: tests/gates/run.sh diff --git a/tests/gates/omega-runtime-api-pin.gate b/tests/gates/omega-runtime-api-pin.gate new file mode 100644 index 000000000..92febfcbd --- /dev/null +++ b/tests/gates/omega-runtime-api-pin.gate @@ -0,0 +1,29 @@ +# tests/gates/omega-runtime-api-pin.gate +# The Runtime API checks omega used to run on its own copy (OMEGA-RUNTIME-API before #924), now run by CUDApp's own +# checker on the CUDApp tree staged at cudapp.lock (make test-runtime-api, mk/runtime-r1.mk): the manifest against +# API.md and the 22 headers (functions, structs, fields, constants, version, public surface, INTERNAL list) and every +# negative control. Then omega's consumer tools/own30b_decode_profile.c compiled -Werror against the staged headers. +# requires: host: sibling clones ../CUDApp, ../omega-bridge and ../physics (pinned under build/pins), gcc (-aux-info); +# no GPU. Mirrors hosted: none (no omega workflow checks out CUDApp); CUDApp's runtime-api.yml runs the same checker. +gate: OMEGA-RUNTIME-API-PIN +manifest_version: 2 +owner: omega +requires: + - host +inputs: + - cudapp.lock + - physics.lock + - Makefile + - mk/ + - tools/cudapp-stage.sh + - tools/own30b_decode_profile.c + - tests/gates/ +run: + exec: tests/gates/run.sh + args: ["runtime-api-pin"] +expects: + exit: 0 + verdict: PASS +timeout: 30m +exactness: EXACT +cache_scope: machine diff --git a/tests/gates/omega-runtime-api.gate b/tests/gates/omega-runtime-api.gate index 3fce55276..4c9173963 100644 --- a/tests/gates/omega-runtime-api.gate +++ b/tests/gates/omega-runtime-api.gate @@ -1,18 +1,22 @@ # tests/gates/omega-runtime-api.gate # Mirrors hosted: no dedicated workflow; as a portable gate it runs in the AIEN Checks portable smoke set (aien-verification.yml) -# requires: portable: the tree plus gcc (-aux-info), make, perl, sed and awk; no GPU, no physics checkout, no sibling repo. +# Since #924 CUDApp owns the Omega Runtime API (CUDApp gate CUDAPP-RUNTIME-API: manifest against API.md and the headers, +# with every negative control this gate used to run). This gate checks what omega still owns: the cudapp.lock pin, no +# second copy of the API in omega, and the consumer recipe in mk/runtime-r1.mk (tools/runtime_api_owner.sh, with its +# own negative controls). The checker itself runs on the pinned CUDApp tree in OMEGA-RUNTIME-API-PIN (host). +# requires: portable: the tree plus git, sh, awk, sed and grep; no GPU, no compiler, no sibling repo. gate: OMEGA-RUNTIME-API manifest_version: 2 owner: omega requires: - portable inputs: + - cudapp.lock - docs/runtime/ - mk/runtime-r1.mk - src/ - - tools/runtime_api_check.sh - - tools/runtime_api_negative.sh - - tests/gates/ + - tests/ + - tools/ run: exec: tests/gates/run.sh args: ["runtime-api"] diff --git a/tests/gates/omega-runtime.gate b/tests/gates/omega-runtime.gate index 1793df34e..bfcc71ffa 100644 --- a/tests/gates/omega-runtime.gate +++ b/tests/gates/omega-runtime.gate @@ -20,6 +20,7 @@ inputs: - evidence/R15/ - evidence/ALLEN/ - physics.lock + - cudapp.lock - aienos.lock - src/ - tests/gates/ diff --git a/tests/gates/omega-sm121dis.gate b/tests/gates/omega-sm121dis.gate index 6ca5d55e1..eecc55a10 100644 --- a/tests/gates/omega-sm121dis.gate +++ b/tests/gates/omega-sm121dis.gate @@ -19,6 +19,7 @@ inputs: - tools/divsqrt_nvdisasm_check.sh - tools/ldst_nvdisasm_check.sh - physics.lock + - cudapp.lock run: exec: tests/gates/run.sh args: ["sm121dis"] diff --git a/tests/gates/run.sh b/tests/gates/run.sh index 2c4ca3ffa..9c8e8745b 100755 --- a/tests/gates/run.sh +++ b/tests/gates/run.sh @@ -64,7 +64,28 @@ pin() { ) 9>"$PINS/.$name.lock" obs "pin_${name//-/_}" "\"$sha\"" } -physics_pin() { pin physics-src physics "$(lock physics.lock)"; export PHYSICS_DIR="$PINS/physics-src"; } +physics_pin() { pin physics-src physics "$(lock physics.lock)"; export PHYSICS_DIR="$PINS/physics-src"; cudapp_pin; } +# The canonical native GPU source (cudapp.lock, mk/cudapp-consumer.mk, README.md "cudapp.lock"): CUDApp at the lock, +# staged by tools/cudapp-stage.sh with the seeded compiler of omega e5b32567 (seed/out/omc at that commit, the sha256 +# 2c824805... cudapp-stage.sh demands) and omega-bridge 0c4cb9ff. Every step that pins physics builds native code, +# which since #924 links the staged CUDApp archive, so physics_pin pins CUDApp too. +CUDAPP_OMC_COMMIT=e5b32567a7aff3ce594e3254a622a846a6cd190b +CUDAPP_BRIDGE_COMMIT=0c4cb9ff980af278890b231b994eaede4dc7621c +cudapp_pin() { + pin cudapp-src CUDApp "$(lock cudapp.lock)"; export CUDAPP_DIR="$PINS/cudapp-src" + pin cudapp-bridge omega-bridge "$CUDAPP_BRIDGE_COMMIT"; export OMEGA_BRIDGE="$PINS/cudapp-bridge" + local dir="$PINS/cudapp-omc" + ( + flock -x 9 + if [ ! -d "$dir" ] || [ "$(git -C "$dir" rev-parse HEAD 2>/dev/null)" != "$CUDAPP_OMC_COMMIT" ]; then + rm -rf "$dir" + git clone --quiet --shared --no-checkout "$ROOT" "$dir" + git -C "$dir" checkout --quiet --detach "$CUDAPP_OMC_COMMIT" + fi + ) 9>"$PINS/.cudapp-omc.lock" + export OMEGA_OMC="$dir/seed/out/omc" + obs pin_cudapp_omc "\"$CUDAPP_OMC_COMMIT\"" +} aienos_pin() { pin aienos-src aienos "$(lock aienos.lock)"; export AIENOS_R7_DIR="$PINS/aienos-src"; export AIENOS_COMMIT="$(lock aienos.lock)"; } argus_pin() { pin aienos-argus aienos "$(lock argus.lock)"; export ARGUS_REPO="$PINS/aienos-argus"; } export OMEGA_CANDIDATE_COMMIT="$(git rev-parse HEAD)" @@ -331,9 +352,17 @@ case "$step" in obs env_files_found false echo "Zero plaintext .env files verified." ;; - runtime-api) # omega-mv#594: the Runtime API manifest against the C headers, plus its negative controls. - # Host only (gcc for -aux-info), no GPU, no physics checkout. - make $NOPHYS test-runtime-api ;; + runtime-api) # omega-mv#594, moved to CUDApp by #924 (CUDApp gate CUDAPP-RUNTIME-API owns the manifest + # against API.md and the headers). Portable: what omega still owns (tools/runtime_api_owner.sh): + # the cudapp.lock pin, no second copy of the API in omega, and the consumer recipe that runs + # CUDApp's checker plus its negative controls; with its own negative controls. + sh tools/runtime_api_owner.sh ;; + runtime-api-pin) # The manifest against API.md and the 22 headers, plus every negative control, by CUDApp's own + # checker on the CUDApp tree staged at cudapp.lock (mk/runtime-r1.mk); then omega's consumer + # tools/own30b_decode_profile.c compiled -Werror against those staged headers. Host only, no GPU. + physics_pin + make test-runtime-api + make check-own30b-decode-profile ;; om-units) # The C entry points whose algorithm is Omega (om/units.sh): omc born from the seed here, # the generator pinned by om/omega-bridge.lock; regenerated binding, SHA-256 and BLAKE3 # byte parity against the C they replaced, and the BLAKE3 mutants. NOT_RUN (3) without tools. diff --git a/tests/gpu_bf16_gemv_test.c b/tests/gpu_bf16_gemv_test.c deleted file mode 100644 index f37a59500..000000000 --- a/tests/gpu_bf16_gemv_test.c +++ /dev/null @@ -1,433 +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. - */ - -/* - * gpu_bf16_gemv_test: the bf16 streaming GEMV (omega_gpu_bf16_gemv_api.h), OWN-30B lm_head. - * --host-only emulation vs double oracle, codegen budgets and refusals (no device) - * --sim warp-simulator parity at 8 warps (both fragment orders, rows 1/2/4, depths, k 512/2048, multi-CTA - * with the row-group loop): bit-identical to the host f32 emulation; mutants 1-3 caught - * (default) the chip: all 151936 logits bit-identical to the host emulation and within tolerance of the double - * oracle, second call bit-identical, bf16-x entry, mutants 1-3 caught on a small tensor, timing - * (--reps N, --n N, --rows R, --warps W, --depth D, --ctas C, --no-evict, --spin-us, --out receipt.json) - * Verdict line last: "gpu_bf16_gemv_test: N checks, F failed: PASS|FAIL". - */ -#include "omega_gpu_bf16_gemv_api.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); } -static float bf16_f32(uint16_t b) { uint32_t x = (uint32_t)b << 16; float f; memcpy(&f, &x, 4); return f; } - -/* The kernel's exact f32 result for one row: per lane one FFMA chain (step, word, low half, high half), then the - * SHFL.DOWN tree 16, 8, 4, 2, 1 (lane L adds lane L + o's value; lane 0 is the result). */ -static float emu_row(const uint16_t *w, const float *x, uint32_t k) { - float a[32]; - for (unsigned lane = 0; lane < 32; lane++) { - float acc = 0.0f; - for (uint32_t s = 0; s < k / 256u; s++) { - const uint16_t *wl = w + s * 256u + lane * 8u; const float *xl = x + s * 256u + lane * 8u; - for (unsigned i = 0; i < 8; i++) acc = fmaf(bf16_f32(wl[i]), xl[i], acc); - } - a[lane] = acc; - } - for (unsigned o = 16; o >= 1; o /= 2) { float b[32]; for (unsigned l = 0; l < 32; l++) b[l] = a[l + o < 32 ? l + o : l]; for (unsigned l = 0; l < 32; l++) a[l] += b[l]; } - return a[0]; -} -static void oracle_row(const uint16_t *w, const float *x, uint32_t k, double *y, double *ys) { - double s = 0, m = 0; - for (uint32_t c = 0; c < k; c++) { double t = (double)bf16_f32(w[c]) * x[c]; s += t; m += fabs(t); } - *y = s; *ys = m; -} -static uint16_t *make_w(size_t count, uint32_t seed) { - uint16_t *w = malloc(count * 2); uint32_t s = seed; - for (size_t i = 0; i < count; i++) w[i] = bf16_rne(frand(&s, -0.06f, 0.06f)); - return w; -} -static float *make_x(uint32_t k, uint32_t seed) { - float *x = malloc((size_t)k * 4); uint32_t s = seed; - for (uint32_t i = 0; i < k; i++) x[i] = frand(&s, -2.0f, 2.0f); - return x; -} -/* bit-identical compare of n outputs against the emulation; returns the number of differing rows */ -static size_t compare_emu(const uint16_t *w, const float *x, uint32_t n, uint32_t k, const float *y, size_t *first) { - size_t bad = 0; *first = (size_t)-1; - for (uint32_t r = 0; r < n; r++) { - float e = emu_row(w + (size_t)r * k, x, k); - if (memcmp(&e, &y[r], 4) != 0) { if (!bad) *first = r; bad++; } - } - return bad; -} - -static void host_only(void) { - printf("host-only: emulation, oracle, budgets\n"); - { uint16_t *w = make_w(2048, 5); float *x = make_x(2048, 6); - double yo, ys; oracle_row(w, x, 2048, &yo, &ys); - float e = emu_row(w, x, 2048); - CHECK(fabs((double)e - yo) <= 1e-6 * ys, "emulation within 1e-6 of the double oracle (%.9g vs %.9g, scale %.3g)", (double)e, yo, ys); - printf("emulation vs oracle: abs %.3e, scale %.3f\n", fabs((double)e - yo), ys); - /* a known hand case: w = 1 on the first 256 columns, x = c: sum 0..255 = 32640 */ - uint16_t hw[256]; float hx[256]; for (unsigned i = 0; i < 256; i++) { hw[i] = 0x3f80; hx[i] = (float)i; } - CHECK(emu_row(hw, hx, 256) == 32640.0f, "hand case sum 0..255 = 32640"); - free(w); free(x); } - uint32_t ws[] = { 4, 8, 16, 32 }, rs[] = { 1, 2, 4 }; - for (unsigned i = 0; i < 4; i++) for (unsigned j = 0; j < 3; j++) for (uint32_t d = 1; d <= 8; d *= 2) for (int m = 0; m <= 3; m++) { - OmegaBf16GemvSpec s = { 2048, rs[j], ws[i], d, m, 0, 0, 0 }; - if (rs[j] * d > 16u) continue; - uint32_t n = 0, g = 0; int rc = omega_bf16_gemv_prog_stats(&s, &n, &g); - uint32_t decl = ((g + 1 + 7) / 8) * 8; - CHECK(rc == 0 && n <= 1024, "codegen k2048 rows %u warps %u depth %u mutant %d: rc %d insns %u gprs %u", rs[j], ws[i], d, m, rc, n, g); - if (m == 0 && rc == 0 && rs[j] == 1 && d == 8) printf("codegen rows %u warps %2u depth %u: %u instructions, %u registers (declared %u, register file %u of 65536)%s\n", rs[j], ws[i], d, n, g, decl, 32u * ws[i] * decl, 32u * ws[i] * decl <= 65536u ? "" : " DOES NOT FIT"); - } - { OmegaBf16GemvSpec s = { 2048, 3, 8, 8, 0, 0, 0, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "rows 3 refused"); } - { OmegaBf16GemvSpec s = { 2000, 1, 8, 8, 0, 0, 0, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "k 2000 refused"); } - { OmegaBf16GemvSpec s = { 2048, 1, 8, 3, 0, 0, 0, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "depth 3 refused"); } - { OmegaBf16GemvSpec s = { 2048, 1, 8, 8, 4, 0, 0, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "mutant 4 refused"); } - { /* the XBATCH form (L312 lever 1): the 35B lm_head shape, 4 x rows per CTA, 32 KiB of shared memory */ - OmegaBf16GemvSpec s = { 2048, 1, 16, 8, 0, 249856, 4, 0 }; uint32_t ni = 0, gg = 0; int rc = omega_bf16_gemv_prog_stats(&s, &ni, &gg); - uint32_t decl = ((gg + 1 + 7) / 8) * 8; - CHECK(rc == 0 && omega_bf16_gemv_shared_bytes(&s) == 32768u && 32u * 16u * decl <= 65536u, "codegen XBATCH 4 k 2048 warps 16 depth 8: rc %d insns %u gprs %u shared %u", rc, ni, gg, omega_bf16_gemv_shared_bytes(&s)); - printf("codegen XBATCH 4 k 2048 warps 16 depth 8: %u instructions, %u registers (declared %u), shared %u bytes\n", ni, gg, decl, omega_bf16_gemv_shared_bytes(&s)); } - { OmegaBf16GemvSpec s = { 2048, 1, 16, 8, 0, 249856, 5, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "xbatch 5 refused"); } - { OmegaBf16GemvSpec s = { 2048, 1, 16, 8, 0, 0, 2, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "xbatch without ystride refused"); } - { OmegaBf16GemvSpec s = { 4096, 1, 16, 16, 0, 249856, 4, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "xbatch 4 x k 4096 (64 KiB shared) refused"); } - { OmegaBf16GemvSpec s = { 2048, 1, 8, 8, 0, 249856, 4, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "xbatch 4 x k 2048 at 8 warps (more than 16 staging rounds) refused"); } - { OmegaBf16GemvSpec s = { 2048, 1, 16, 8, 4, 249856, 1, 0 }; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, NULL) != 0, "mutant 4 at xbatch 1 refused"); } - CHECK(OMEGA_BF16_ARGS_WORDS <= OMEGA_GPU_SESSION_MAX_ARGS, "argument words fit the constant bank window"); - uint16_t bad[256]; memset(bad, 0, sizeof bad); bad[7] = 0x7f80; - OmegaGpuBf16Tensor *t = NULL; - CHECK(omega_gpu_bf16_tensor_upload(1, 256, bad, &t) == OMEGA_GPU_BF16_NAN_WEIGHT && !t, "an infinite bf16 weight is refused before any device use"); - CHECK(omega_gpu_bf16_tensor_upload(1, 200, bad, &t) == OMEGA_GPU_BF16_BAD_ARGS, "k 200 refused at upload"); -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -static int sim_point(uint32_t k, uint32_t n, uint32_t rows, uint32_t warps, uint32_t depth, uint32_t grid_x, int mutant, uint32_t seed, char *msg, size_t msgn, size_t *bad) { - static BlackwellIRProgram prog; - OmegaBf16GemvSpec spec = { k, rows, warps, depth, mutant, 0, 0, 0 }; - if (omega_blackwell_codegen_bf16_gemv_prog(&spec, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - uint16_t *w = aligned_alloc(16, (size_t)n * k * 2); { uint16_t *t = make_w((size_t)n * k, seed); memcpy(w, t, (size_t)n * k * 2); free(t); } - float *x = aligned_alloc(16, (size_t)k * 4); { float *t = make_x(k, seed + 1); memcpy(x, t, (size_t)k * 4); free(t); } - float *y = aligned_alloc(16, ((size_t)n * 4 + 15) & ~15ull); - uint8_t *smem = aligned_alloc(16, omega_bf16_gemv_shared_bytes(&spec)); - float first[1] = { 0 }; float *ycopy = NULL; int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * warps; s.order = order; s.smem = smem; s.smem_bytes = omega_bf16_gemv_shared_bytes(&spec); - for (uint32_t i = 0; i < n; i++) y[i] = -999.0f; - uint64_t A[3] = { (uintptr_t)w, (uintptr_t)x, (uintptr_t)y }; - for (unsigned i = 0; i < 3; i++) { s.cbank[(OMEGA_BF16_ARG_W + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(OMEGA_BF16_ARG_W + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - s.cbank[OMEGA_BF16_ARG_RG / 4] = n / rows; s.cbank[OMEGA_BF16_ARG_STRIDE / 4] = grid_x * warps; - s.nranges = 3; - s.ranges[0].lo = (uintptr_t)w; s.ranges[0].hi = (uintptr_t)w + (size_t)n * k * 2; - s.ranges[1].lo = (uintptr_t)x; s.ranges[1].hi = (uintptr_t)x + (size_t)k * 4; - s.ranges[2].lo = (uintptr_t)y; s.ranges[2].hi = (uintptr_t)y + (size_t)n * 4; - err = ws_run(&s, grid_x, 1); - if (err) { snprintf(msg, msgn, "order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (uint32_t i = 0; i < n; i++) if (y[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, msgn, "%zu output words never written", unwritten); break; } - if (order == 0) { ycopy = malloc((size_t)n * 4); memcpy(ycopy, y, (size_t)n * 4); } - else if (memcmp(ycopy, y, (size_t)n * 4) != 0) { err = -1; snprintf(msg, msgn, "the fragment order changed the result"); } - } - (void)first; - if (!err) { size_t f; *bad = compare_emu(w, x, n, k, y, &f); snprintf(msg, msgn, "%zu of %u rows differ from the emulation%s", *bad, n, *bad ? "" : " (bit-identical)"); } - free(ycopy); free(w); free(x); free(y); free(smem); - return err; -} -/* ROWS form (spec.ystride, sc #642 prefill; xb 0): grid_y = T token rows; row r reads x + r * k and writes y + r * ystride. - * XBATCH form (spec.xbatch = xb = T, L312 lever 1): one CTA row stages all T x rows and every weight read feeds them all. - * Each row must equal the one-row emulation of its own x, and the ystride - n gap after every row stays untouched. */ -static int sim_multi_point(uint32_t k, uint32_t n, uint32_t T, uint32_t xb, uint32_t ystride, uint32_t grid_x, int mutant, uint32_t seed, char *msg, size_t msgn, size_t *bad) { - static BlackwellIRProgram prog; - const uint32_t rows = 1, warps = 8, depth = 4; /* the host simulator runs up to 8 warps, so k (xb * k for XBATCH) <= 4096 here */ - OmegaBf16GemvSpec spec = { k, rows, warps, depth, mutant, ystride, xb, 0 }; - if (omega_blackwell_codegen_bf16_gemv_prog(&spec, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - uint16_t *w = aligned_alloc(16, (size_t)n * k * 2); { uint16_t *t = make_w((size_t)n * k, seed); memcpy(w, t, (size_t)n * k * 2); free(t); } - float *x = aligned_alloc(16, (size_t)T * k * 4); - for (uint32_t r = 0; r < T; r++) { float *t = make_x(k, seed + 1 + r); memcpy(x + (size_t)r * k, t, (size_t)k * 4); free(t); } - const size_t ywords = (size_t)T * ystride; - float *y = aligned_alloc(16, (ywords * 4 + 15) & ~15ull); - uint8_t *smem = aligned_alloc(16, omega_bf16_gemv_shared_bytes(&spec)); - for (size_t i = 0; i < ywords; i++) y[i] = -999.0f; - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * warps; s.smem = smem; s.smem_bytes = omega_bf16_gemv_shared_bytes(&spec); - uint64_t A[3] = { (uintptr_t)w, (uintptr_t)x, (uintptr_t)y }; - for (unsigned i = 0; i < 3; i++) { s.cbank[(OMEGA_BF16_ARG_W + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(OMEGA_BF16_ARG_W + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - s.cbank[OMEGA_BF16_ARG_RG / 4] = n / rows; s.cbank[OMEGA_BF16_ARG_STRIDE / 4] = grid_x * warps; - s.nranges = 3; - s.ranges[0].lo = (uintptr_t)w; s.ranges[0].hi = (uintptr_t)w + (size_t)n * k * 2; - s.ranges[1].lo = (uintptr_t)x; s.ranges[1].hi = (uintptr_t)x + (size_t)T * k * 4; - s.ranges[2].lo = (uintptr_t)y; s.ranges[2].hi = (uintptr_t)y + ywords * 4; - int err = ws_run(&s, grid_x, xb > 1u ? 1u : T); - if (err) snprintf(msg, msgn, "%s (pc %d)", s.msg, s.err_pc); - *bad = 0; - size_t gap_written = 0; - for (uint32_t r = 0; !err && r < T; r++) { - size_t f; *bad += compare_emu(w, x + (size_t)r * k, n, k, y + (size_t)r * ystride, &f); - for (uint32_t i = n; i < ystride; i++) if (y[(size_t)r * ystride + i] != -999.0f) gap_written++; - } - if (!err && gap_written) { err = -1; snprintf(msg, msgn, "%zu words written inside the ystride gap", gap_written); } - else if (!err) snprintf(msg, msgn, "%zu of %u rows x %u tokens differ from the emulation%s", *bad, n, T, *bad ? "" : " (bit-identical)"); - free(w); free(x); free(y); free(smem); - return err; -} -/* MASK form (HUM L314 exact head): rows with hi >= tau must equal the plain kernel's row bit for bit (the emulation), - * every other row must hold -inf. hi covers below / equal / above tau and -0 against tau = +0 (a candidate). */ -static int sim_mask_point(uint32_t k, uint32_t n, uint32_t warps, uint32_t depth, uint32_t grid_x, int mutant, uint32_t seed, - char *msg, size_t msgn, size_t *bad, size_t *cands) { - static BlackwellIRProgram prog; - OmegaBf16GemvSpec spec = { k, 1, warps, depth, mutant, 0, 0, 1 }; - if (omega_blackwell_codegen_bf16_gemv_prog(&spec, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - uint16_t *w = aligned_alloc(16, (size_t)n * k * 2); { uint16_t *t = make_w((size_t)n * k, seed); memcpy(w, t, (size_t)n * k * 2); free(t); } - float *x = aligned_alloc(16, (size_t)k * 4); { float *t = make_x(k, seed + 1); memcpy(x, t, (size_t)k * 4); free(t); } - float *y = aligned_alloc(16, ((size_t)n * 4 + 15) & ~15ull); - float *hi = aligned_alloc(16, ((size_t)n * 4 + 15) & ~15ull); - float *tau = aligned_alloc(16, 16); - uint8_t *smem = aligned_alloc(16, omega_bf16_gemv_shared_bytes(&spec)); - const float T = seed & 1 ? 0.0f : 0.25f; - tau[0] = T; - for (uint32_t i = 0; i < n; i++) { - uint32_t h = (i * 2654435761u) ^ seed; - hi[i] = (h % 3 == 0) ? T + 0.5f : (h % 3 == 1) ? T - 0.5f : (h % 5 == 0) ? T : T - 1e-6f; - } - hi[1] = T; hi[2] = nextafterf(T, -1.0f); - if (T == 0.0f) hi[3] = -0.0f; /* -0 >= +0 numerically: a candidate */ - *cands = 0; - for (uint32_t i = 0; i < n; i++) *cands += hi[i] >= T; - int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * warps; s.order = order; s.smem = smem; s.smem_bytes = omega_bf16_gemv_shared_bytes(&spec); - for (uint32_t i = 0; i < n; i++) y[i] = -999.0f; - uint64_t A[5] = { (uintptr_t)w, (uintptr_t)x, (uintptr_t)y, 0, (uintptr_t)hi }; - for (unsigned i = 0; i < 3; i++) { s.cbank[(OMEGA_BF16_ARG_W + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(OMEGA_BF16_ARG_W + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - s.cbank[OMEGA_BF16_ARG_HI / 4] = (uint32_t)A[4]; s.cbank[OMEGA_BF16_ARG_HI / 4 + 1] = (uint32_t)(A[4] >> 32); - s.cbank[OMEGA_BF16_ARG_TAU / 4] = (uint32_t)(uintptr_t)tau; s.cbank[OMEGA_BF16_ARG_TAU / 4 + 1] = (uint32_t)((uint64_t)(uintptr_t)tau >> 32); - s.cbank[OMEGA_BF16_ARG_RG / 4] = n; s.cbank[OMEGA_BF16_ARG_STRIDE / 4] = grid_x * warps; - s.nranges = 5; - s.ranges[0].lo = (uintptr_t)w; s.ranges[0].hi = (uintptr_t)w + (size_t)n * k * 2; - s.ranges[1].lo = (uintptr_t)x; s.ranges[1].hi = (uintptr_t)x + (size_t)k * 4; - s.ranges[2].lo = (uintptr_t)y; s.ranges[2].hi = (uintptr_t)y + (size_t)n * 4; - s.ranges[3].lo = (uintptr_t)hi; s.ranges[3].hi = (uintptr_t)hi + (size_t)n * 4; - s.ranges[4].lo = (uintptr_t)tau; s.ranges[4].hi = (uintptr_t)tau + 4; - err = ws_run(&s, grid_x, 1); - if (err) { snprintf(msg, msgn, "order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t b = 0; - for (uint32_t i = 0; i < n; i++) { - float want = hi[i] >= T ? emu_row(w + (size_t)i * k, x, k) : -INFINITY; - b += memcmp(&want, &y[i], 4) != 0; - } - *bad = b; - snprintf(msg, msgn, "%zu candidates of %u rows, %zu rows wrong%s", *cands, n, b, b ? "" : " (candidates bit-identical, the rest -inf)"); - } - free(w); free(x); free(y); free(hi); free(tau); free(smem); - return err; -} -static void sim_battery(void) { - { /* MASK form (L314): two thresholds (0 with a -0 row, 0.25), two grids, and mutant 4 must be caught */ - static const struct { uint32_t k, n, warps, depth, grid, seed; } mp[] = { { 2048, 100, 8, 8, 2, 7 }, { 2048, 96, 8, 4, 3, 10 }, { 512, 70, 4, 2, 2, 13 } }; - for (size_t i = 0; i < sizeof mp / sizeof mp[0]; i++) { - char msg[300]; size_t bad = 1, c = 0; - int err = sim_mask_point(mp[i].k, mp[i].n, mp[i].warps, mp[i].depth, mp[i].grid, 0, mp[i].seed, msg, sizeof msg, &bad, &c); - CHECK(!err && bad == 0 && c > 0 && c < mp[i].n, "sim MASK k %u n %u: %s", mp[i].k, mp[i].n, msg); - printf("sim MASK k %u n %u warps %u depth %u grid %u: %s %s\n", mp[i].k, mp[i].n, mp[i].warps, mp[i].depth, mp[i].grid, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - char msg[300]; size_t bad = 0, c = 0; - int err = sim_mask_point(2048, 64, 8, 4, 2, 4, 7, msg, sizeof msg, &bad, &c); - CHECK(!err && bad != 0, "sim MASK mutant 4 must be caught: %s", msg); - printf("sim MASK mutant 4: %s %s\n", err ? "ERROR" : bad ? "caught" : "NOT CAUGHT", msg); - OmegaBf16GemvSpec r2 = { 2048, 2, 8, 4, 0, 0, 0, 1 }, ys = { 2048, 1, 8, 4, 0, 64, 0, 1 }, m4 = { 2048, 1, 8, 4, 4, 0, 0, 0 }; - CHECK(omega_bf16_gemv_prog_stats(&r2, NULL, NULL) != 0 && omega_bf16_gemv_prog_stats(&ys, NULL, NULL) != 0 && - omega_bf16_gemv_prog_stats(&m4, NULL, NULL) != 0, "MASK refuses rows 2, ystride, and mutant 4 without MASK"); - } - { /* ROWS form: 3 token rows, ystride n + 4 (the gap must stay untouched); and ystride == n as the graph uses it */ - static const struct { uint32_t k, n, T, ystride, grid; } rp[] = { { 2048, 96, 3, 100, 2 }, { 4096, 96, 4, 96, 3 } }; - for (size_t i = 0; i < sizeof rp / sizeof rp[0]; i++) { - char msg[300]; size_t bad = 1; - int err = sim_multi_point(rp[i].k, rp[i].n, rp[i].T, 0, rp[i].ystride, rp[i].grid, 0, 91 + (uint32_t)i, msg, sizeof msg, &bad); - CHECK(!err && bad == 0, "sim ROWS k %u n %u T %u ystride %u: %s", rp[i].k, rp[i].n, rp[i].T, rp[i].ystride, msg); - printf("sim ROWS k %u n %u T %u ystride %u: %s %s\n", rp[i].k, rp[i].n, rp[i].T, rp[i].ystride, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - } - { /* XBATCH form: every weight read feeds xb x rows; mutant 4 (every row reads x row 0) must be caught */ - struct { uint32_t k, n, xb, ystride, grid; } xp[] = { { 1024, 96, 2, 100, 2 }, { 1024, 96, 4, 96, 3 }, { 2048, 64, 2, 70, 2 }, { 1024, 40, 3, 50, 2 } }; - for (size_t i = 0; i < sizeof xp / sizeof xp[0]; i++) { - char msg[300]; size_t bad = 1; - int err = sim_multi_point(xp[i].k, xp[i].n, xp[i].xb, xp[i].xb, xp[i].ystride, xp[i].grid, 0, 61 + (uint32_t)i, msg, sizeof msg, &bad); - CHECK(!err && bad == 0, "sim XBATCH k %u n %u xb %u ystride %u: %s", xp[i].k, xp[i].n, xp[i].xb, xp[i].ystride, msg); - printf("sim XBATCH k %u n %u xb %u ystride %u: %s %s\n", xp[i].k, xp[i].n, xp[i].xb, xp[i].ystride, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - char msg[300]; size_t bad = 0; - int err = sim_multi_point(1024, 64, 2, 2, 64, 2, 4, 79, msg, sizeof msg, &bad); - CHECK(!err && bad != 0, "sim XBATCH mutant 4 must be caught: %s", msg); - printf("sim XBATCH mutant 4: %s %s\n", err ? "ERROR" : bad ? "caught" : "NOT CAUGHT", msg); - } - struct { uint32_t k, n, rows, warps, depth, grid; } pts[] = { - { 2048, 100, 1, 8, 8, 2 }, { 2048, 100, 1, 8, 4, 3 }, { 2048, 64, 1, 8, 1, 2 }, { 2048, 96, 2, 8, 4, 2 }, { 2048, 96, 4, 8, 4, 1 }, - { 512, 70, 1, 8, 2, 2 }, { 512, 70, 2, 4, 1, 3 }, { 4096, 40, 1, 8, 16, 2 }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - char msg[300]; size_t bad = 1; - int err = sim_point(pts[i].k, pts[i].n, pts[i].rows, pts[i].warps, pts[i].depth, pts[i].grid, 0, 31 + (uint32_t)i, msg, sizeof msg, &bad); - CHECK(!err && bad == 0, "sim k %u n %u rows %u warps %u depth %u grid %u: %s", pts[i].k, pts[i].n, pts[i].rows, pts[i].warps, pts[i].depth, pts[i].grid, msg); - printf("sim k %u n %u rows %u warps %u depth %u grid %u: %s %s\n", pts[i].k, pts[i].n, pts[i].rows, pts[i].warps, pts[i].depth, pts[i].grid, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - for (int m = 1; m <= 3; m++) { - char msg[300]; size_t bad = 0; - int err = sim_point(2048, 64, 1, 8, 4, 2, m, 77, msg, sizeof msg, &bad); - CHECK(!err && bad != 0, "sim mutant %d must be caught: %s", m, msg); - printf("sim mutant %d: %s %s\n", m, err ? "ERROR" : bad ? "caught" : "NOT CAUGHT", msg); - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static int g_evict = 1; -static void evict_host_caches(void) { - static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass; - if (!buf) buf = malloc(sz); - if (!buf) return; - memset(buf, ++pass, sz); - volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i]; -} -static double med(uint64_t *v, uint32_t n) { qsort(v, n, 8, cmp_u64); return (double)v[n / 2]; } - -static int chip_run(const char *out_path, uint32_t reps, uint32_t N, uint32_t K) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot write %s\n", out_path); return 1; } - if (out) fprintf(out, "{\"receipt\":\"OMEGA_GPU_BF16_GEMV_V1\",\"n\":%u,\"k\":%u,\"reps\":%u,\"evict\":%d,\"spin_us\":%u,\"points\":[", N, K, reps, g_evict, omega_gpu_session_spin_us()); - uint16_t *w = make_w((size_t)N * K, 90001); float *x = make_x(K, 90002); - OmegaGpuBf16Tensor *t = NULL; - double t0 = now_ms(); - int rc = omega_gpu_bf16_tensor_upload(N, K, w, &t); - printf("upload %u x %u bf16 (%.0f MB): rc=%s %.0f ms (%s)\n", N, K, (double)N * K * 2 / 1e6, omega_gpu_bf16_rc_name(rc), now_ms() - t0, rc ? omega_gpu_bf16_last_error() : ""); - CHECK(rc == 0, "upload"); - if (rc) { if (out) { fprintf(out, "],\"verdict\":\"FAIL\"}\n"); fclose(out); } return 1; } - float *y = malloc((size_t)N * 4), *y2 = malloc((size_t)N * 4); OmegaGpuBf16Info info; - rc = omega_gpu_bf16_gemv_f32(t, x, y, &info); - CHECK(rc == 0, "gemv: %s %s", omega_gpu_bf16_rc_name(rc), rc ? omega_gpu_bf16_last_error() : ""); - if (rc == 0) { - size_t first; size_t bad = compare_emu(w, x, N, K, y, &first); - CHECK(bad == 0, "chip vs host emulation: %zu of %u rows differ (first %zd)", bad, N, (ssize_t)first); - double worst = 0, wy = 0; size_t arg_o = 0, arg_c = 0; double bo = -1e300; float bc = -1e30f; - for (uint32_t r = 0; r < N; r++) { - double yo, ys; oracle_row(w + (size_t)r * K, x, K, &yo, &ys); - double d = fabs((double)y[r] - yo) / (ys + 1e-30); if (d > worst) { worst = d; wy = yo; } - if (yo > bo) { bo = yo; arg_o = r; } - if (y[r] > bc) { bc = y[r]; arg_c = r; } - } - CHECK(worst < 1e-5, "chip vs double oracle: worst rel-to-scale %.2e", worst); - printf("parity: %zu of %u rows differ from the f32 emulation (bit compare); worst error vs double oracle %.2e of the term scale (y %.4g); argmax chip %zu oracle %zu\n", bad, N, worst, wy, arg_c, arg_o); - if (out) fprintf(out, "{\"point\":\"parity\",\"rows_bad\":%zu,\"worst_rel\":%.3e,\"argmax_chip\":%zu,\"argmax_oracle\":%zu}", bad, worst, arg_c, arg_o); - rc = omega_gpu_bf16_gemv_f32(t, x, y2, NULL); - CHECK(rc == 0 && memcmp(y, y2, (size_t)N * 4) == 0, "second call bit-identical"); - printf("second call: %s\n", rc == 0 && memcmp(y, y2, (size_t)N * 4) == 0 ? "bit-identical" : "DIFFERS"); - uint16_t *xb = malloc(K * 2); float *xf = malloc(K * 4); - for (uint32_t i = 0; i < K; i++) { xb[i] = bf16_rne(x[i]); xf[i] = bf16_f32(xb[i]); } - rc = omega_gpu_bf16_gemv_bf16(t, xb, y2, NULL); - size_t b2 = 0, f2; if (rc == 0) b2 = compare_emu(w, xf, N, K, y2, &f2); - CHECK(rc == 0 && b2 == 0, "bf16-x entry equals the emulation on the rounded x (%zu rows differ)", b2); - printf("bf16-x entry: %s\n", rc == 0 && b2 == 0 ? "bit-identical to the emulation" : "MISMATCH"); - free(xb); free(xf); - } - /* timing */ - { - uint64_t *ce = malloc(reps * 8), *cc = malloc(reps * 8); uint32_t done = 0; int ok = 1; - for (uint32_t i = 0; i < reps && ok; i++) { - if (g_evict) evict_host_caches(); - if (omega_gpu_bf16_gemv_f32(t, x, y2, &info) != 0) { ok = 0; break; } - ce[done] = info.elapsed_ns; cc[done] = info.call_ns; done++; - } - CHECK(done == reps, "timing loop completed %u of %u", done, reps); - if (done) { - double mc = med(ce, done), ma = med(cc, done); - printf("timing (medians of %u, evict %d): rows %u warps %u depth %u ctas %u: chip %.1f us = %.1f GB/s on %.0f MB; call %.1f us = %.1f GB/s\n", - done, g_evict, info.rows_per_warp, info.warps_per_cta, info.depth, info.grid_x, mc / 1e3, (double)info.weight_bytes / mc, (double)info.weight_bytes / 1e6, ma / 1e3, (double)info.weight_bytes / ma); - if (out) fprintf(out, ",{\"point\":\"timing\",\"rows\":%u,\"warps\":%u,\"depth\":%u,\"ctas\":%u,\"reps\":%u,\"chip_median_ns\":%.0f,\"call_median_ns\":%.0f,\"weight_bytes\":%" PRIu64 ",\"chip_gbps\":%.2f,\"call_gbps\":%.2f,\"marker\":%u}", - info.rows_per_warp, info.warps_per_cta, info.depth, info.grid_x, done, mc, ma, info.weight_bytes, (double)info.weight_bytes / mc, (double)info.weight_bytes / ma, info.completion_marker); - } - free(ce); free(cc); - } - omega_gpu_bf16_tensor_free(t); - /* mutants on a small tensor */ - { - const uint32_t MN = 4096; OmegaGpuBf16Tensor *ts = NULL; - rc = omega_gpu_bf16_tensor_upload(MN, K, w, &ts); - CHECK(rc == 0, "small tensor upload"); - if (rc == 0) { - float *ys = malloc(MN * 4); - rc = omega_gpu_bf16_gemv_f32(ts, x, ys, NULL); size_t f; size_t b0 = rc == 0 ? compare_emu(w, x, MN, K, ys, &f) : (size_t)-1; - CHECK(b0 == 0, "small tensor unmutated parity (%zu rows differ)", b0); - for (int m = 1; m <= 3; m++) { - omega_gpu_bf16_test_set_mutant(m); - rc = omega_gpu_bf16_gemv_f32(ts, x, ys, NULL); - size_t b = rc == 0 ? compare_emu(w, x, MN, K, ys, &f) : (size_t)-1; - CHECK(b != 0, "chip mutant %d must be caught (rc %s)", m, omega_gpu_bf16_rc_name(rc)); - printf("chip mutant %d: %s (%zu of %u rows differ)\n", m, b ? "caught" : "NOT CAUGHT", b == (size_t)-1 ? (size_t)MN : b, MN); - if (out) fprintf(out, ",{\"point\":\"mutant %d\",\"caught\":%d}", m, b != 0); - } - omega_gpu_bf16_test_set_mutant(0); - free(ys); - } - omega_gpu_bf16_tensor_free(ts); - } - free(w); free(x); free(y); free(y2); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - return g_failed ? 1 : 0; -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; const char *out_path = NULL; uint32_t reps = 0, rows = 0, warps = 0, depth = 0, ctas = 0, spin = 2000, N = 151936, K = 2048; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--rows") == 0 && i + 1 < argc) rows = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--warps") == 0 && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--depth") == 0 && i + 1 < argc) depth = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--ctas") == 0 && i + 1 < argc) ctas = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--n") == 0 && i + 1 < argc) N = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--k") == 0 && i + 1 < argc) K = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0; - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - if (host) host_only(); - if (sim) sim_battery(); - if (!host && !sim) { - if (rows || warps || depth) omega_gpu_bf16_set_shape(rows, warps, depth); - if (ctas) omega_gpu_bf16_set_cta_budget(ctas); - (void)omega_gpu_session_set_spin_us(spin); - chip_run(out_path, reps ? reps : 1, N, K); - omega_gpu_session_close(); - } - printf("gpu_bf16_gemv_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_cmdlist_test.c b/tests/gpu_cmdlist_test.c deleted file mode 100644 index f32d36cae..000000000 --- a/tests/gpu_cmdlist_test.c +++ /dev/null @@ -1,633 +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. - */ - -/* - * gpu_cmdlist_test: OWN-30B W-L2 decode launch collapse (omega_gpu_cmdlist.h + omega_blackwell_codegen_dec.h). - * --host-only codegen budgets and refusals of the four glue kernels (no device) - * --sim warp-simulator parity of AXPY chain, RES (ADD / COMBINE / NORM, scale 1 and 2^64), SWIGLU, ARGMAX - * (two stages, tie case) against the host reference; mutants caught - * (default) chip, caller holds the GB10 lock: - * baseline: L dependent AXPY launches one omega_gpu_session_launch at a time - * main: the same L launches recorded once and submitted once (PCAS) and in INLINE mode; x bit-identical - * to the baseline, every launch semaphore DONE; negative control skip_launch (must fail, first_missing - * named, x short by one a); BARRIER_NONE recorded (informational); per-launch medians (--reps N); - * glue kernels in one list: RES ADD|NORM, SWIGLU, RES COMBINE|NORM, ARGMAX x2 against the host - * reference; mutants caught on chip. --out receipt.json - * Verdict: exit 0 when every CHECK passed. - */ -#include "omega_gpu_cmdlist.h" -#include "omega_blackwell_codegen_dec.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint64_t median_u64(uint64_t *v, unsigned n) { qsort(v, n, sizeof *v, cmp_u64); return v[n / 2]; } - -#define H OMEGA_DEC_HIDDEN -#define TK OMEGA_DEC_TOPK -#define INTER OMEGA_DEC_INTER -#define VOCAB 151936u -#define AM_CTAS ((VOCAB + OMEGA_DEC_ARGMAX_SPAN - 1) / OMEGA_DEC_ARGMAX_SPAN) /* 75 */ -#define AM_PAD (AM_CTAS * OMEGA_DEC_ARGMAX_SPAN) /* 153600 */ -#define EPS 1e-6f -#define SCALE_2P64 18446744073709551616.0f - -/* ---- host references (float, the kernel's operation order where it matters; -ffp-contract=off) ---- */ -static void ref_res(uint32_t mode, float *x, const float *a, const float *w, const float *nw, float *y, float eps, float scale) { - if (mode & OMEGA_DEC_RES_ADD) for (unsigned i = 0; i < H; i++) x[i] = x[i] + a[i]; - if (mode & OMEGA_DEC_RES_COMBINE) for (unsigned i = 0; i < H; i++) { - float m = w[0] * a[i]; - for (unsigned g = 1; g < TK; g++) { float t = w[g] * a[g * H + i]; m = m + t; } - x[i] = x[i] + m; - } - if (mode & OMEGA_DEC_RES_NORM) { - double sq = 0; for (unsigned i = 0; i < H; i++) sq += (double)x[i] * x[i]; - float rs = (float)(1.0 / sqrt(sq / H + (double)eps)); - for (unsigned i = 0; i < H; i++) { float v = x[i] * rs; v = v * nw[i]; y[i] = v * scale; } - } -} -static void ref_swiglu(const float *gu, float *act, float scale) { - for (unsigned g = 0; g < TK; g++) for (unsigned c = 0; c < INTER; c++) { - float v = gu[g * 2 * INTER + c], u = gu[g * 2 * INTER + INTER + c]; - float s = v / (1.0f + expf(-v)); - act[g * INTER + c] = s * u * scale; - } -} -static uint32_t ref_argmax(const float *v, uint32_t n) { uint32_t b = 0; for (uint32_t i = 1; i < n; i++) if (v[i] > v[b]) b = i; return b; } -static int close_rel(float a, float b, float rel, float abs_) { float d = fabsf(a - b); return d <= abs_ || d <= rel * fabsf(b); } - -/* ---- one glue-kernel case: buffers in plain host memory (sim) or in device buffers (chip) ---- */ -typedef struct { - float *x, *a8, *w, *nw, *y, *gu, *act, *logits, *ov; uint32_t *oi; - float x_ref[H], y_ref[H], act_ref[TK * INTER]; uint32_t am_ref; -} Glue; -static void glue_fill(Glue *g, uint32_t seed, int tie) { - uint32_t s = seed; - for (unsigned i = 0; i < H; i++) { g->x[i] = frand(&s, -2, 2); g->nw[i] = frand(&s, 0.5f, 1.5f); } - for (unsigned i = 0; i < TK * H; i++) g->a8[i] = frand(&s, -1, 1); - for (unsigned i = 0; i < TK; i++) g->w[i] = frand(&s, 0, 0.3f); - for (unsigned i = 0; i < TK * 2 * INTER; i++) g->gu[i] = frand(&s, -4, 4); - for (unsigned i = 0; i < AM_PAD; i++) g->logits[i] = i < VOCAB ? frand(&s, -50, 50) : -1e30f; - if (tie) { g->logits[1007] = 60.0f; g->logits[90007] = 60.0f; } /* lowest index wins: 1007 (a j == 7 slot) */ - for (unsigned i = 0; i < OMEGA_DEC_ARGMAX_SPAN; i++) { g->ov[i] = -1e30f; g->oi[i] = 0; } - g->am_ref = ref_argmax(g->logits, VOCAB); -} - -/* ---- kernels ---- */ -typedef struct { BlackwellIRProgram prog; OmegaGpuMem code; uint32_t gpr; int built; } Kern; -static Kern K_axpy, K_res_an, K_res_cn, K_sw, K_am0, K_am1, K_res_m1, K_res_m2, K_res_cn_m1, K_sw_m1, K_am_m1, K_axpy_big; - -static int kern_prog(Kern *k, const OmegaDecSpec *sp) { k->built = 0; return omega_blackwell_codegen_dec_prog(sp, &k->prog); } -static int kern_upload(Kern *k) { - size_t need = omega_bw_program_code_bytes(&k->prog); - if (need == 0 || omega_gpu_session_alloc_code(need, &k->code) != 0) return -1; - OmegaBlackwellKernel kk; - if (omega_blackwell_kernel_encode_into(&k->prog, k->code.cpu, need, &kk) != 0 || omega_gpu_session_sync_to_gpu(&k->code) != 0) return -1; - k->gpr = omega_bw_gpr_declared(kk.gpr_count); - if (k->gpr < 64u) k->gpr = 64u; - k->built = 1; - return 0; -} -static void put64(uint32_t *a, unsigned off, uint64_t v) { a[(off - 0x380) / 4] = (uint32_t)v; a[(off - 0x380) / 4 + 1] = (uint32_t)(v >> 32); } -static void putf(uint32_t *a, unsigned off, float f) { memcpy(&a[(off - 0x380) / 4], &f, 4); } - -#define AXPY_STRIDE 2048u /* small launch: 8 CTAs x 256 threads, one element each */ -#define AXPY_BIG_STRIDE 65536u /* heavy launch for the no-barrier control: 256 CTAs x 16 iterations */ -#define AXPY_BIG_ITERS 16u - -static int specs_build(void) { - OmegaDecSpec s; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_AXPY; s.stride = AXPY_STRIDE; if (kern_prog(&K_axpy, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_AXPY; s.stride = AXPY_BIG_STRIDE; if (kern_prog(&K_axpy_big, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM; if (kern_prog(&K_res_an, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM; if (kern_prog(&K_res_cn, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM; s.mutant = 1; if (kern_prog(&K_res_m1, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM; s.mutant = 2; if (kern_prog(&K_res_m2, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM; s.mutant = 1; if (kern_prog(&K_res_cn_m1, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_SWIGLU; if (kern_prog(&K_sw, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_SWIGLU; s.mutant = 1; if (kern_prog(&K_sw_m1, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_ARGMAX; s.mode = 0; if (kern_prog(&K_am0, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_ARGMAX; s.mode = 1; if (kern_prog(&K_am1, &s)) return -1; - memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_ARGMAX; s.mode = 0; s.mutant = 1; if (kern_prog(&K_am_m1, &s)) return -1; - return 0; -} - -/* ---- host-only ---- */ -static int host_only(void) { - const struct { const char *name; OmegaDecSpec s; } cases[] = { - { "axpy", { .kind = OMEGA_DEC_AXPY, .stride = AXPY_STRIDE } }, - { "res add|norm", { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM } }, - { "res combine|norm", { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM } }, - { "res add", { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_ADD } }, - { "swiglu", { .kind = OMEGA_DEC_SWIGLU } }, - { "argmax", { .kind = OMEGA_DEC_ARGMAX } }, - { "argmax indexed", { .kind = OMEGA_DEC_ARGMAX, .mode = 1 } }, - }; - for (unsigned i = 0; i < sizeof cases / sizeof cases[0]; i++) { - uint32_t insns = 0, gprs = 0; - int rc = omega_dec_prog_stats(&cases[i].s, &insns, &gprs); - CHECK(rc == 0, "codegen %s", cases[i].name); - CHECK(gprs <= 200, "%s gprs %u within budget", cases[i].name, gprs); - printf("codegen %s: %u insns, peak %u gprs, declared %u\n", cases[i].name, insns, gprs, omega_bw_gpr_declared(gprs)); - } - OmegaDecSpec bad[] = { { .kind = OMEGA_DEC_AXPY }, { .kind = OMEGA_DEC_AXPY, .stride = 100 }, { .kind = OMEGA_DEC_RES }, - { .kind = OMEGA_DEC_RES, .mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_COMBINE }, { .kind = (OmegaDecKind)0 }, { .kind = OMEGA_DEC_RES, .mode = 8 } }; - for (unsigned i = 0; i < sizeof bad / sizeof bad[0]; i++) CHECK(omega_dec_prog_stats(&bad[i], NULL, NULL) != 0, "refusal %u", i); - /* widths (sc #642): 5120 and 8192 build; not a multiple of 1024, above 8192, COMBINE off 2048, SWIGLU off 256 refuse */ - OmegaDecSpec w; memset(&w, 0, sizeof w); w.kind = OMEGA_DEC_RES; w.mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM; - w.width = 5120; CHECK(omega_dec_prog_stats(&w, NULL, NULL) == 0, "codegen res width 5120"); - w.width = 8192; CHECK(omega_dec_prog_stats(&w, NULL, NULL) == 0, "codegen res width 8192"); - w.width = 3000; CHECK(omega_dec_prog_stats(&w, NULL, NULL) != 0, "refusal res width 3000"); - w.width = 9216; CHECK(omega_dec_prog_stats(&w, NULL, NULL) != 0, "refusal res width 9216"); - w.width = 5120; w.mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM; CHECK(omega_dec_prog_stats(&w, NULL, NULL) != 0, "refusal combine width 5120"); - memset(&w, 0, sizeof w); w.kind = OMEGA_DEC_SWIGLU; w.width = 17408; CHECK(omega_dec_prog_stats(&w, NULL, NULL) == 0, "codegen swiglu width 17408"); - w.width = 17409; CHECK(omega_dec_prog_stats(&w, NULL, NULL) != 0, "refusal swiglu width 17409"); - return g_failed ? 1 : 0; -} - -/* ---- simulator ---- */ -static int sim_one(Kern *k, const uint32_t *args, unsigned n_args, uint32_t gx, uint32_t gy, WsRange *ranges, int nr, const char *what) { - static uint8_t smem[OMEGA_DEC_SHARED_BYTES]; - WsSim s; memset(&s, 0, sizeof s); - s.p = &k->prog; s.threads = OMEGA_DEC_THREADS; s.smem = smem; s.smem_bytes = sizeof smem; - memcpy(&s.cbank[0x380 / 4], args, n_args * 4u); - s.nranges = nr; for (int i = 0; i < nr; i++) s.ranges[i] = ranges[i]; - int err = ws_run(&s, gx, gy); - CHECK(err == 0, "sim %s: %s (pc %d)", what, s.msg, s.err_pc); - return err; -} -static int sim_mode(void) { - if (specs_build()) { printf("FAIL: codegen\n"); return 1; } - /* AXPY chain: 3 launches x += a over 2048 */ - { - static float x[AXPY_STRIDE], a[AXPY_STRIDE], xr[AXPY_STRIDE]; - uint32_t s = 7; for (unsigned i = 0; i < AXPY_STRIDE; i++) { x[i] = frand(&s, -1, 1); a[i] = frand(&s, -1, 1); xr[i] = x[i]; } - uint32_t args[OMEGA_DEC_AXPY_WORDS] = { 0 }; put64(args, OMEGA_DEC_AXPY_X, (uintptr_t)x); put64(args, OMEGA_DEC_AXPY_A, (uintptr_t)a); args[(OMEGA_DEC_AXPY_ITERS - 0x380) / 4] = 1; - WsRange r[2] = { { (uintptr_t)x, (uintptr_t)x + sizeof x }, { (uintptr_t)a, (uintptr_t)a + sizeof a } }; - for (int l = 0; l < 3; l++) { if (sim_one(&K_axpy, args, OMEGA_DEC_AXPY_WORDS, AXPY_STRIDE / OMEGA_DEC_THREADS, 1, r, 2, "axpy")) return 1; for (unsigned i = 0; i < AXPY_STRIDE; i++) xr[i] = xr[i] + a[i]; } - CHECK(memcmp(x, xr, sizeof x) == 0, "sim axpy chain bit-identical"); - } - /* glue kernels */ - static float x[H], a8[TK * H], w[TK], nw[H], y[H], gu[TK * 2 * INTER], act[TK * INTER], logits[AM_PAD], ov[OMEGA_DEC_ARGMAX_SPAN]; - static uint32_t oi[OMEGA_DEC_ARGMAX_SPAN]; - Glue g = { x, a8, w, nw, y, gu, act, logits, ov, oi, { 0 }, { 0 }, { 0 }, 0 }; - WsRange rr[6] = { { (uintptr_t)x, (uintptr_t)x + sizeof x }, { (uintptr_t)a8, (uintptr_t)a8 + sizeof a8 }, { (uintptr_t)w, (uintptr_t)w + sizeof w }, - { (uintptr_t)nw, (uintptr_t)nw + sizeof nw }, { (uintptr_t)y, (uintptr_t)y + sizeof y }, { (uintptr_t)gu, (uintptr_t)gu + sizeof gu } }; - const float scales[2] = { 1.0f, SCALE_2P64 }; - for (int sc = 0; sc < 2; sc++) for (int mode = 0; mode < 2; mode++) for (int mut = 0; mut < 2; mut++) { - glue_fill(&g, 100 + sc, 0); - memcpy(g.x_ref, x, sizeof x); - const uint32_t M = mode == 0 ? (OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM) : (OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM); - ref_res(M, g.x_ref, a8, w, nw, g.y_ref, EPS, scales[sc]); - uint32_t args[OMEGA_DEC_RES_WORDS] = { 0 }; - put64(args, OMEGA_DEC_RES_X, (uintptr_t)x); put64(args, OMEGA_DEC_RES_A, (uintptr_t)a8); put64(args, OMEGA_DEC_RES_W, (uintptr_t)w); - put64(args, OMEGA_DEC_RES_NW, (uintptr_t)nw); put64(args, OMEGA_DEC_RES_Y, (uintptr_t)y); putf(args, OMEGA_DEC_RES_EPS, EPS); putf(args, OMEGA_DEC_RES_SCALE, scales[sc]); - Kern *k = mut ? (mode == 0 ? &K_res_m1 : &K_res_m2) : (mode == 0 ? &K_res_an : &K_res_cn); - if (sim_one(k, args, OMEGA_DEC_RES_WORDS, 1, 1, rr, 5, "res")) return 1; - int xbad = memcmp(x, g.x_ref, sizeof x) != 0, ybad = 0; - for (unsigned i = 0; i < H; i++) if (!close_rel(y[i], g.y_ref[i], 2e-5f, 1e-6f)) ybad++; - if (!mut) { CHECK(!xbad, "sim res mode %u scale %d: x bit-identical", M, sc); CHECK(ybad == 0, "sim res mode %u scale %d: y within 2e-5 (%d bad)", M, sc, ybad); } - else CHECK(xbad || ybad, "sim res mutant (mode %u) caught", M); - printf("sim res mode %u scale %s mutant %d: x %s, y %d/%u outside tolerance\n", M, sc ? "2^64" : "1", mut, xbad ? "DIFFERS" : "identical", ybad, H); - } - for (int mut = 0; mut < 2; mut++) { - glue_fill(&g, 200, 0); - ref_swiglu(gu, g.act_ref, 1.0f); - uint32_t args[OMEGA_DEC_SW_WORDS] = { 0 }; put64(args, OMEGA_DEC_SW_GU, (uintptr_t)gu); put64(args, OMEGA_DEC_SW_ACT, (uintptr_t)act); putf(args, OMEGA_DEC_SW_SCALE, 1.0f); - WsRange r2[2] = { rr[5], { (uintptr_t)act, (uintptr_t)act + sizeof act } }; - if (sim_one(mut ? &K_sw_m1 : &K_sw, args, OMEGA_DEC_SW_WORDS, INTER / OMEGA_DEC_THREADS, TK, r2, 2, "swiglu")) return 1; - int bad = 0; for (unsigned i = 0; i < TK * INTER; i++) if (!close_rel(act[i], g.act_ref[i], 5e-5f, 1e-6f)) bad++; - if (!mut) CHECK(bad == 0, "sim swiglu within 5e-5 (%d bad)", bad); else CHECK(bad > 0, "sim swiglu mutant caught"); - printf("sim swiglu mutant %d: %d/%u outside tolerance\n", mut, bad, TK * INTER); - } - for (int tie = 0; tie < 2; tie++) for (int mut = 0; mut < 2; mut++) { - glue_fill(&g, 300 + tie, tie); - uint32_t a0[OMEGA_DEC_AM_WORDS] = { 0 }, a1[OMEGA_DEC_AM_WORDS] = { 0 }; - static float ov2[1]; static uint32_t oi2[1]; - put64(a0, OMEGA_DEC_AM_V, (uintptr_t)logits); put64(a0, OMEGA_DEC_AM_I, 0); put64(a0, OMEGA_DEC_AM_OV, (uintptr_t)ov); put64(a0, OMEGA_DEC_AM_OI, (uintptr_t)oi); - put64(a1, OMEGA_DEC_AM_V, (uintptr_t)ov); put64(a1, OMEGA_DEC_AM_I, (uintptr_t)oi); put64(a1, OMEGA_DEC_AM_OV, (uintptr_t)ov2); put64(a1, OMEGA_DEC_AM_OI, (uintptr_t)oi2); - WsRange r3[4] = { { (uintptr_t)logits, (uintptr_t)logits + sizeof logits }, { (uintptr_t)ov, (uintptr_t)ov + sizeof ov }, { (uintptr_t)oi, (uintptr_t)oi + sizeof oi }, - { (uintptr_t)ov2, (uintptr_t)ov2 + 4 } }; - WsRange r4[5] = { r3[0], r3[1], r3[2], r3[3], { (uintptr_t)oi2, (uintptr_t)oi2 + 4 } }; - if (sim_one(mut ? &K_am_m1 : &K_am0, a0, OMEGA_DEC_AM_WORDS, AM_CTAS, 1, r4, 5, "argmax stage 1")) return 1; - if (sim_one(&K_am1, a1, OMEGA_DEC_AM_WORDS, 1, 1, r4, 5, "argmax stage 2")) return 1; - if (!mut) CHECK(oi2[0] == g.am_ref && ov2[0] == logits[g.am_ref], "sim argmax tie %d: %u (ref %u)", tie, oi2[0], g.am_ref); - else if (tie) CHECK(oi2[0] != g.am_ref, "sim argmax mutant caught (max at a j == 7 slot)"); - printf("sim argmax tie %d mutant %d: index %u value %g (ref %u)\n", tie, mut, oi2[0], ov2[0], g.am_ref); - } - return g_failed ? 1 : 0; -} - -/* ---- Qwen3.8-27B widths (sc #642): RES over 5120, SWIGLU over one dense 17408 row ---- */ -#define WH 5120u -#define WI 17408u -static int sim_wide(void) { - static Kern kw[4]; - static float x[WH], xr[WH], a[WH], nw[WH], y[WH], yr[WH], gu[2 * WI], act[WI], actr[WI]; - const uint32_t modes[3] = { OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM, OMEGA_DEC_RES_NORM, OMEGA_DEC_RES_ADD }; - for (int mi = 0; mi < 3; mi++) for (int mut = 0; mut < 2; mut++) { - if (mut && !(modes[mi] & OMEGA_DEC_RES_NORM)) continue; - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = modes[mi]; s.mutant = mut; s.width = WH; - if (kern_prog(&kw[0], &s)) { CHECK(0, "codegen res width %u mode %u", WH, modes[mi]); return 1; } - uint32_t sd = 300 + mi; - for (unsigned i = 0; i < WH; i++) { x[i] = frand(&sd, -2, 2); a[i] = frand(&sd, -1, 1); nw[i] = frand(&sd, 0.5f, 1.5f); y[i] = -7.0f; } - memcpy(xr, x, sizeof x); - /* ref_res at width WH */ - if (modes[mi] & OMEGA_DEC_RES_ADD) for (unsigned i = 0; i < WH; i++) xr[i] = xr[i] + a[i]; - if (modes[mi] & OMEGA_DEC_RES_NORM) { - double sq = 0; for (unsigned i = 0; i < WH; i++) sq += (double)xr[i] * xr[i]; - float rs = (float)(1.0 / sqrt(sq / WH + (double)EPS)); - for (unsigned i = 0; i < WH; i++) { float v = xr[i] * rs; v = v * nw[i]; yr[i] = v * SCALE_2P64; } - } - uint32_t args[OMEGA_DEC_RES_WORDS] = { 0 }; - put64(args, OMEGA_DEC_RES_X, (uintptr_t)x); put64(args, OMEGA_DEC_RES_A, (uintptr_t)a); put64(args, OMEGA_DEC_RES_NW, (uintptr_t)nw); - put64(args, OMEGA_DEC_RES_Y, (uintptr_t)y); putf(args, OMEGA_DEC_RES_EPS, EPS); putf(args, OMEGA_DEC_RES_SCALE, SCALE_2P64); - WsRange r[4] = { { (uintptr_t)x, (uintptr_t)x + sizeof x }, { (uintptr_t)a, (uintptr_t)a + sizeof a }, - { (uintptr_t)nw, (uintptr_t)nw + sizeof nw }, { (uintptr_t)y, (uintptr_t)y + sizeof y } }; - if (sim_one(&kw[0], args, OMEGA_DEC_RES_WORDS, 1, 1, r, 4, "res wide")) return 1; - int xbad = memcmp(x, xr, sizeof x) != 0, ybad = 0; - if (modes[mi] & OMEGA_DEC_RES_NORM) for (unsigned i = 0; i < WH; i++) if (!close_rel(y[i], yr[i], 2e-5f, 1e-6f)) ybad++; - if (!mut) { CHECK(!xbad, "sim res width %u mode %u: x bit-identical", WH, modes[mi]); CHECK(ybad == 0, "sim res width %u mode %u: y within 2e-5 (%d bad)", WH, modes[mi], ybad); } - else CHECK(ybad > 0, "sim res width %u mode %u mutant caught", WH, modes[mi]); - printf("sim res width %u mode %u mutant %d: x %s, y %d/%u outside tolerance\n", WH, modes[mi], mut, xbad ? "DIFFERS" : "identical", ybad, WH); - } - for (int mut = 0; mut < 2; mut++) { - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_SWIGLU; s.mutant = mut; s.width = WI; - if (kern_prog(&kw[1], &s)) { CHECK(0, "codegen swiglu width %u", WI); return 1; } - uint32_t sd = 400; - for (unsigned i = 0; i < 2 * WI; i++) gu[i] = frand(&sd, -4, 4); - for (unsigned c = 0; c < WI; c++) { float v = gu[c], u = gu[WI + c]; actr[c] = v / (1.0f + expf(-v)) * u * SCALE_2P64; act[c] = -7.0f; } - uint32_t args[OMEGA_DEC_SW_WORDS] = { 0 }; put64(args, OMEGA_DEC_SW_GU, (uintptr_t)gu); put64(args, OMEGA_DEC_SW_ACT, (uintptr_t)act); putf(args, OMEGA_DEC_SW_SCALE, SCALE_2P64); - WsRange r[2] = { { (uintptr_t)gu, (uintptr_t)gu + sizeof gu }, { (uintptr_t)act, (uintptr_t)act + sizeof act } }; - if (sim_one(&kw[1], args, OMEGA_DEC_SW_WORDS, WI / OMEGA_DEC_THREADS, 1, r, 2, "swiglu wide")) return 1; - int bad = 0; for (unsigned i = 0; i < WI; i++) if (!close_rel(act[i], actr[i], 5e-5f, 1e-6f)) bad++; - if (!mut) CHECK(bad == 0, "sim swiglu width %u within 5e-5 (%d bad)", WI, bad); else CHECK(bad > 0, "sim swiglu width %u mutant caught", WI); - printf("sim swiglu width %u mutant %d: %d/%u outside tolerance\n", WI, mut, bad, WI); - } - /* RES rows form: 3 rows of [5120], ADD|NORM, row r at r * 5120 (nw shared); the mutant drops the weight */ - { - enum { ROWS = 3 }; - static float rx[ROWS * WH], rxr[ROWS * WH], ra[ROWS * WH], ry[ROWS * WH], ryr[ROWS * WH]; - for (int mut = 0; mut < 2; mut++) { - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_RES; s.mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM | OMEGA_DEC_RES_ROWS; s.mutant = mut; s.width = WH; - if (kern_prog(&kw[2], &s)) { CHECK(0, "codegen res rows"); return 1; } - uint32_t sd = 500; - for (unsigned i = 0; i < ROWS * WH; i++) { rx[i] = frand(&sd, -2, 2); ra[i] = frand(&sd, -1, 1); ry[i] = -7.0f; } - for (unsigned i = 0; i < WH; i++) nw[i] = frand(&sd, 0.5f, 1.5f); - for (unsigned r = 0; r < ROWS; r++) { - float *xx = rxr + r * WH; - for (unsigned i = 0; i < WH; i++) xx[i] = rx[r * WH + i] + ra[r * WH + i]; - double sq = 0; for (unsigned i = 0; i < WH; i++) sq += (double)xx[i] * xx[i]; - float rs = (float)(1.0 / sqrt(sq / WH + (double)EPS)); - for (unsigned i = 0; i < WH; i++) { float v = xx[i] * rs; v = v * nw[i]; ryr[r * WH + i] = v * SCALE_2P64; } - } - uint32_t args[OMEGA_DEC_RES_WORDS] = { 0 }; - put64(args, OMEGA_DEC_RES_X, (uintptr_t)rx); put64(args, OMEGA_DEC_RES_A, (uintptr_t)ra); put64(args, OMEGA_DEC_RES_NW, (uintptr_t)nw); - put64(args, OMEGA_DEC_RES_Y, (uintptr_t)ry); putf(args, OMEGA_DEC_RES_EPS, EPS); putf(args, OMEGA_DEC_RES_SCALE, SCALE_2P64); - WsRange r[4] = { { (uintptr_t)rx, (uintptr_t)rx + sizeof rx }, { (uintptr_t)ra, (uintptr_t)ra + sizeof ra }, - { (uintptr_t)nw, (uintptr_t)nw + sizeof nw }, { (uintptr_t)ry, (uintptr_t)ry + sizeof ry } }; - if (sim_one(&kw[2], args, OMEGA_DEC_RES_WORDS, 1, ROWS, r, 4, "res rows")) return 1; - int xbad = memcmp(rx, rxr, sizeof rx) != 0, ybad = 0; - for (unsigned i = 0; i < ROWS * WH; i++) if (!close_rel(ry[i], ryr[i], 2e-5f, 1e-6f)) ybad++; - if (!mut) { CHECK(!xbad, "sim res rows: x bit-identical"); CHECK(ybad == 0, "sim res rows: y within 2e-5 (%d bad)", ybad); } - else CHECK(ybad > 0, "sim res rows mutant caught"); - printf("sim res rows %d x %u mutant %d: x %s, y %d/%u outside tolerance\n", ROWS, WH, mut, xbad ? "DIFFERS" : "identical", ybad, ROWS * WH); - } - OmegaDecSpec bad; memset(&bad, 0, sizeof bad); bad.kind = OMEGA_DEC_RES; bad.mode = OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_ROWS; - CHECK(omega_dec_prog_stats(&bad, NULL, NULL) != 0, "refusal res rows with combine"); - bad.mode = OMEGA_DEC_RES_ROWS; CHECK(omega_dec_prog_stats(&bad, NULL, NULL) != 0, "refusal res rows alone"); - } - /* GATHER: 3 rows, input stride 14343, out width 14336 (the Qwen3.8 attention row), random source table */ - { - enum { ROWS = 3, GW = 14336, GS = 14343 }; - static float gin[ROWS * GS], gout[ROWS * GW]; - static uint32_t tab[GW]; - for (int mut = 0; mut < 2; mut++) { - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_GATHER; s.mutant = mut; s.width = GW; s.stride = GS; - if (kern_prog(&kw[3], &s)) { CHECK(0, "codegen gather"); return 1; } - uint32_t sd = 600; - for (unsigned i = 0; i < ROWS * GS; i++) gin[i] = frand(&sd, -3, 3); - for (unsigned i = 0; i < GW; i++) { sd = sd * 1664525u + 1013904223u; tab[i] = sd % (GS - 1); } - for (unsigned i = 0; i < ROWS * GW; i++) gout[i] = -7.0f; - uint32_t args[OMEGA_DEC_GA_WORDS] = { 0 }; - put64(args, OMEGA_DEC_GA_IN, (uintptr_t)gin); put64(args, OMEGA_DEC_GA_TAB, (uintptr_t)tab); put64(args, OMEGA_DEC_GA_OUT, (uintptr_t)gout); - WsRange r[3] = { { (uintptr_t)gin, (uintptr_t)gin + sizeof gin }, { (uintptr_t)tab, (uintptr_t)tab + sizeof tab }, { (uintptr_t)gout, (uintptr_t)gout + sizeof gout } }; - if (sim_one(&kw[3], args, OMEGA_DEC_GA_WORDS, (GW + OMEGA_DEC_THREADS - 1) / OMEGA_DEC_THREADS, ROWS, r, 3, "gather")) return 1; - int bad = 0; - for (unsigned rr = 0; rr < ROWS; rr++) for (unsigned n = 0; n < GW; n++) if (memcmp(&gout[rr * GW + n], &gin[rr * GS + tab[n]], 4)) bad++; - if (!mut) CHECK(bad == 0, "sim gather bit-exact (%d bad)", bad); else CHECK(bad > 0, "sim gather mutant caught"); - printf("sim gather %d x %u mutant %d: %d/%u wrong\n", ROWS, GW, mut, bad, ROWS * GW); - } - OmegaDecSpec bad; memset(&bad, 0, sizeof bad); bad.kind = OMEGA_DEC_GATHER; bad.width = 0; bad.stride = 1; - CHECK(omega_dec_prog_stats(&bad, NULL, NULL) != 0, "refusal gather width 0"); - } - /* GATE in place over 6144 + 100 values (a tail CTA), mutant drops the gate */ - { - enum { GN = 6244 }; - static float a[GN], g[GN], ref[GN]; - for (int mut = 0; mut < 2; mut++) { - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_GATE; s.mutant = mut; - if (kern_prog(&kw[3], &s)) { CHECK(0, "codegen gate"); return 1; } - uint32_t sd = 700; - for (unsigned i = 0; i < GN; i++) { a[i] = frand(&sd, -3, 3) * SCALE_2P64; g[i] = frand(&sd, -8, 8); ref[i] = a[i] * (1.0f / (1.0f + expf(-g[i]))); } - uint32_t args[OMEGA_DEC_GT_WORDS] = { 0 }; - put64(args, OMEGA_DEC_GT_A, (uintptr_t)a); put64(args, OMEGA_DEC_GT_G, (uintptr_t)g); put64(args, OMEGA_DEC_GT_OUT, (uintptr_t)a); - args[(OMEGA_DEC_GT_N - 0x380) / 4] = GN; - WsRange r[2] = { { (uintptr_t)a, (uintptr_t)a + sizeof a }, { (uintptr_t)g, (uintptr_t)g + sizeof g } }; - if (sim_one(&kw[3], args, OMEGA_DEC_GT_WORDS, (GN + OMEGA_DEC_THREADS - 1) / OMEGA_DEC_THREADS, 1, r, 2, "gate")) return 1; - int bad = 0; for (unsigned i = 0; i < GN; i++) if (!close_rel(a[i], ref[i], 5e-5f, 1e-6f)) bad++; - if (!mut) CHECK(bad == 0, "sim gate within 5e-5 (%d bad)", bad); else CHECK(bad > 0, "sim gate mutant caught"); - printf("sim gate %u mutant %d: %d/%u outside tolerance\n", GN, mut, bad, GN); - } - } - /* SWIGLU over rows: the group index is the row (gu [3][2 * 17408] -> act [3][17408]) */ - { - enum { ROWS = 3 }; - static float rgu[ROWS * 2 * WI], ract[ROWS * WI]; - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = OMEGA_DEC_SWIGLU; s.width = WI; - if (kern_prog(&kw[1], &s)) { CHECK(0, "codegen swiglu rows"); return 1; } - uint32_t sd = 800; - for (unsigned i = 0; i < ROWS * 2 * WI; i++) rgu[i] = frand(&sd, -4, 4); - uint32_t args[OMEGA_DEC_SW_WORDS] = { 0 }; put64(args, OMEGA_DEC_SW_GU, (uintptr_t)rgu); put64(args, OMEGA_DEC_SW_ACT, (uintptr_t)ract); putf(args, OMEGA_DEC_SW_SCALE, 1.0f); - WsRange r[2] = { { (uintptr_t)rgu, (uintptr_t)rgu + sizeof rgu }, { (uintptr_t)ract, (uintptr_t)ract + sizeof ract } }; - if (sim_one(&kw[1], args, OMEGA_DEC_SW_WORDS, WI / OMEGA_DEC_THREADS, ROWS, r, 2, "swiglu rows")) return 1; - int bad = 0; - for (unsigned rr = 0; rr < ROWS; rr++) for (unsigned c = 0; c < WI; c++) { - float v = rgu[rr * 2 * WI + c], u = rgu[rr * 2 * WI + WI + c], want = v / (1.0f + expf(-v)) * u; - if (!close_rel(ract[rr * WI + c], want, 5e-5f, 1e-6f)) bad++; - } - CHECK(bad == 0, "sim swiglu rows within 5e-5 (%d bad)", bad); - printf("sim swiglu rows %d x %u: %d outside tolerance\n", ROWS, WI, bad); - } - return g_failed ? 1 : 0; -} - -/* ---- chip ---- */ -static OmegaGpuLaunch axpy_launch(const Kern *k, uint32_t *args, uint32_t stride, uint32_t iters) { - OmegaGpuLaunch L; memset(&L, 0, sizeof L); - L.code_va = k->code.va; L.gpr_count = k->gpr; L.threads_x = OMEGA_DEC_THREADS; L.threads_y = 1; L.grid_x = stride / OMEGA_DEC_THREADS; L.grid_y = 1; - L.num_elements = (size_t)stride * iters; L.args = args; L.n_args = OMEGA_DEC_AXPY_WORDS; L.timeout_ms = 20000; - return L; -} -static int chip_fail(const char *what) { printf("FAIL: %s: %s\n", what, omega_gpu_session_last_error()); g_checks++; g_failed++; return 1; } - -typedef struct { uint32_t L; uint64_t base_ns, pcas_ns, inline_ns, base_wall_ns, pcas_wall_ns, pcas_submits, inline_submits; int pcas_ok, inline_ok; uint64_t stamps_span_ns, stamps_min_ns, stamps_max_ns, stamps_chip_ns; } Row; - -static int chip_run(const char *out_path, uint32_t reps) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot write %s\n", out_path); return 1; } - if (specs_build()) { printf("FAIL: codegen\n"); return 1; } - OmegaGpuCmdList *cl = NULL; - if (omega_gpu_cmdlist_create(OMEGA_GPU_CMDLIST_MAX_LAUNCHES, &cl) != 0) return chip_fail("cmdlist create"); - omega_gpu_session_lock(); - Kern *ks[] = { &K_axpy, &K_axpy_big, &K_res_an, &K_res_cn, &K_res_m1, &K_res_m2, &K_res_cn_m1, &K_sw, &K_sw_m1, &K_am0, &K_am1, &K_am_m1 }; - for (unsigned i = 0; i < sizeof ks / sizeof ks[0]; i++) if (kern_upload(ks[i])) { omega_gpu_session_unlock(); return chip_fail("kernel upload"); } - OmegaGpuMem bx, ba, bx0; - const size_t big = (size_t)AXPY_BIG_STRIDE * AXPY_BIG_ITERS * 4u; - if (omega_gpu_session_alloc(big, &bx) || omega_gpu_session_alloc(big, &ba) || omega_gpu_session_alloc(big, &bx0)) { omega_gpu_session_unlock(); return chip_fail("alloc"); } - uint32_t s = 11; float *x0 = bx0.cpu, *a = ba.cpu, *x = bx.cpu; - for (size_t i = 0; i < big / 4; i++) { x0[i] = frand(&s, -1, 1); a[i] = frand(&s, -1, 1); } - omega_gpu_session_sync_to_gpu(&ba); - uint32_t args[OMEGA_DEC_AXPY_WORDS] = { 0 }; put64(args, OMEGA_DEC_AXPY_X, bx.va); put64(args, OMEGA_DEC_AXPY_A, ba.va); args[(OMEGA_DEC_AXPY_ITERS - 0x380) / 4] = 1; - OmegaGpuLaunch L = axpy_launch(&K_axpy, args, AXPY_STRIDE, 1); - static float base[AXPY_STRIDE], xref[AXPY_STRIDE]; - const uint32_t Ls[] = { 64, 289, 1024 }; - Row rows[3]; memset(rows, 0, sizeof rows); - if (out) fprintf(out, "{\"receipt\":\"OMEGA_GPU_CMDLIST_V1\",\"reps\":%u,\"spin_us\":%u,\"rows\":[", reps, omega_gpu_session_spin_us()); - for (unsigned li = 0; li < 3; li++) { - const uint32_t N = Ls[li]; - Row *r = &rows[li]; r->L = N; - memcpy(xref, x0, sizeof xref); for (uint32_t l = 0; l < N; l++) for (unsigned i = 0; i < AXPY_STRIDE; i++) xref[i] = xref[i] + a[i]; - /* baseline: one session launch at a time */ - uint64_t *tb = calloc(reps, 8), *tw = calloc(reps, 8), *tp = calloc(reps, 8), *tpw = calloc(reps, 8), *ti = calloc(reps, 8); - int base_ok = 1; - for (uint32_t rep = 0; rep < reps && base_ok; rep++) { - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - uint64_t ns = 0; struct timespec t0, t1; clock_gettime(CLOCK_MONOTONIC, &t0); - for (uint32_t l = 0; l < N; l++) if (omega_gpu_session_launch(&L, &ns, NULL) != 0) { base_ok = 0; chip_fail("baseline launch"); break; } - clock_gettime(CLOCK_MONOTONIC, &t1); - omega_gpu_session_sync_to_cpu(&bx); - if (rep == 0) memcpy(base, x, sizeof base); - tb[rep] = ns; tw[rep] = (uint64_t)(t1.tv_sec - t0.tv_sec) * 1000000000ull + (uint64_t)(t1.tv_nsec - t0.tv_nsec); - } - if (!base_ok) break; - CHECK(memcmp(base, xref, sizeof base) == 0, "L=%u baseline x == host reference (bit-identical)", N); - r->base_ns = median_u64(tb, reps); r->base_wall_ns = median_u64(tw, reps); - /* main: one list, PCAS */ - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.timeout_ms = 20000; - OmegaGpuCmdListStats st; int ok = 1; - for (uint32_t rep = 0; rep < reps && ok; rep++) { - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) if (omega_gpu_cmdlist_add(cl, &L) < 0) { ok = 0; chip_fail("cmdlist add"); break; } - if (!ok) break; - struct timespec t0, t1; clock_gettime(CLOCK_MONOTONIC, &t0); - int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - clock_gettime(CLOCK_MONOTONIC, &t1); - omega_gpu_session_sync_to_cpu(&bx); - if (rc != 0) { ok = 0; printf("PCAS L=%u rep %u: submit rc %d (%s) sems_done %u first_missing %d\n", N, rep, rc, omega_gpu_session_last_error(), st.sems_done, st.first_missing); break; } - if (memcmp(x, base, sizeof base) != 0) { ok = 0; printf("PCAS L=%u rep %u: x differs from the baseline\n", N, rep); break; } - tp[rep] = st.elapsed_ns; tpw[rep] = (uint64_t)(t1.tv_sec - t0.tv_sec) * 1000000000ull + (uint64_t)(t1.tv_nsec - t0.tv_nsec); - r->pcas_submits = st.submits; - } - r->pcas_ok = ok; - CHECK(ok, "L=%u PCAS list: every rep bit-identical to the baseline, all semaphores DONE", N); - if (ok) { r->pcas_ns = median_u64(tp, reps); r->pcas_wall_ns = median_u64(tpw, reps); } - if (omega_gpu_cmdlist_is_latched()) { printf("cmdlist latched; stopping\n"); break; } - /* instrument: GPU timestamps around every launch (stamps on), x still identical; stamps off -> accessor refuses */ - if (ok) { - static uint64_t stamps[1025]; - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) (void)omega_gpu_cmdlist_add(cl, &L); - OmegaGpuCmdListOpts os = o; os.stamps = 1; - int rc = omega_gpu_cmdlist_submit(cl, &os, &st); - omega_gpu_session_sync_to_cpu(&bx); - int cnt = omega_gpu_cmdlist_stamps(cl, stamps, 1025); - int mono = 1; uint64_t mn = UINT64_MAX, mx = 0; - for (int i = 1; i < cnt; i++) { if (stamps[i] < stamps[i - 1]) mono = 0; uint64_t d = stamps[i] - stamps[i - 1]; if (d < mn) mn = d; if (d > mx) mx = d; } - const uint64_t span = cnt > 1 ? stamps[cnt - 1] - stamps[0] : 0; - CHECK(rc == 0 && memcmp(x, base, sizeof base) == 0 && cnt == (int)N + 1 && mono && span > 0 && span <= st.elapsed_ns, - "L=%u stamps on: rc %d, x identical, %d stamps (want %u), monotonic %d, span %.1f us <= chip %.1f us, per launch min %.2f max %.2f us", - N, rc, cnt, N + 1, mono, span / 1e3, st.elapsed_ns / 1e3, mn / 1e3, mx / 1e3); - r->stamps_span_ns = span; r->stamps_min_ns = mn; r->stamps_max_ns = mx; r->stamps_chip_ns = st.elapsed_ns; - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) (void)omega_gpu_cmdlist_add(cl, &L); - rc = omega_gpu_cmdlist_submit(cl, &o, &st); - cnt = omega_gpu_cmdlist_stamps(cl, stamps, 1025); - CHECK(rc == 0 && cnt < 0, "L=%u stamps off: submit rc %d, stamps accessor refuses (%d)", N, rc, cnt); - } - /* INLINE mode (the session's own words per launch, several submissions) */ - o.mode = OMEGA_GPU_CMDLIST_INLINE; ok = 1; - for (uint32_t rep = 0; rep < reps && ok; rep++) { - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) if (omega_gpu_cmdlist_add(cl, &L) < 0) { ok = 0; chip_fail("cmdlist add"); break; } - if (!ok) break; - int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - omega_gpu_session_sync_to_cpu(&bx); - if (rc != 0) { ok = 0; printf("INLINE L=%u rep %u: submit rc %d (%s) sems_done %u first_missing %d\n", N, rep, rc, omega_gpu_session_last_error(), st.sems_done, st.first_missing); break; } - if (memcmp(x, base, sizeof base) != 0) { ok = 0; printf("INLINE L=%u rep %u: x differs from the baseline\n", N, rep); break; } - ti[rep] = st.elapsed_ns; r->inline_submits = st.submits; - } - r->inline_ok = ok; - CHECK(ok, "L=%u INLINE list: every rep bit-identical to the baseline, all semaphores DONE", N); - if (ok) r->inline_ns = median_u64(ti, reps); - if (omega_gpu_cmdlist_is_latched()) { printf("cmdlist latched; stopping\n"); break; } - printf("L=%u: baseline %.1f us/launch (chip %.1f us, wall %.1f us per launch); PCAS %s %.2f us/launch (wall %.2f, %" PRIu64 " submits); INLINE %s %.2f us/launch (%" PRIu64 " submits)\n", - N, r->base_ns / 1e3 / N, r->base_ns / 1e3 / N, r->base_wall_ns / 1e3 / N, r->pcas_ok ? "ok" : "FAIL", r->pcas_ns / 1e3 / N, r->pcas_wall_ns / 1e3 / N, r->pcas_submits, - r->inline_ok ? "ok" : "FAIL", r->inline_ns / 1e3 / N, r->inline_submits); - if (out) fprintf(out, "%s{\"L\":%u,\"baseline_ns\":%" PRIu64 ",\"baseline_wall_ns\":%" PRIu64 ",\"pcas_ok\":%d,\"pcas_ns\":%" PRIu64 ",\"pcas_wall_ns\":%" PRIu64 ",\"pcas_submits\":%" PRIu64 ",\"inline_ok\":%d,\"inline_ns\":%" PRIu64 ",\"inline_submits\":%" PRIu64 ",\"stamps_span_ns\":%" PRIu64 ",\"stamps_min_ns\":%" PRIu64 ",\"stamps_max_ns\":%" PRIu64 ",\"stamps_chip_ns\":%" PRIu64 "}", - li ? "," : "", N, r->base_ns, r->base_wall_ns, r->pcas_ok, r->pcas_ns, r->pcas_wall_ns, r->pcas_submits, r->inline_ok, r->inline_ns, r->inline_submits, r->stamps_span_ns, r->stamps_min_ns, r->stamps_max_ns, r->stamps_chip_ns); - free(tb); free(tw); free(tp); free(tpw); free(ti); - } - if (out) fprintf(out, "],"); - /* negative control: drop launch 32 of 64 from the stream; the semaphore check must name it */ - if (!omega_gpu_cmdlist_is_latched()) { - const uint32_t N = 64; - memcpy(xref, x0, sizeof xref); for (uint32_t l = 0; l + 1 < N; l++) for (unsigned i = 0; i < AXPY_STRIDE; i++) xref[i] = xref[i] + a[i]; - memcpy(x, x0, sizeof base); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) omega_gpu_cmdlist_add(cl, &L); - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.timeout_ms = 20000; o.skip_launch = 33; - OmegaGpuCmdListStats st; int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - omega_gpu_session_sync_to_cpu(&bx); - CHECK(rc != 0 && st.first_missing == 32 && st.sems_done == N - 1, "negative control: skipped launch 32 caught (rc %d, first_missing %d, sems_done %u)", rc, st.first_missing, st.sems_done); - CHECK(memcmp(x, xref, sizeof base) == 0, "negative control: x == x0 + 63 a (the other 63 launches ran)"); - printf("negative control skip_launch=33: rc %d first_missing %d sems_done %u/%u x %s\n", rc, st.first_missing, st.sems_done, N, memcmp(x, xref, sizeof base) == 0 ? "x0+63a" : "UNEXPECTED"); - if (out) fprintf(out, "\"skip_control\":{\"rc\":%d,\"first_missing\":%d,\"sems_done\":%u},", rc, st.first_missing, st.sems_done); - } - /* informational: no WFI between heavy dependent launches (256 CTAs x 16 iterations each, 32 launches) */ - if (!omega_gpu_cmdlist_is_latched()) { - const uint32_t N = 32; const size_t n = (size_t)AXPY_BIG_STRIDE * AXPY_BIG_ITERS; - float *xr = malloc(n * 4); memcpy(xr, x0, n * 4); - for (uint32_t l = 0; l < N; l++) for (size_t i = 0; i < n; i++) xr[i] = xr[i] + a[i]; - uint32_t ab[OMEGA_DEC_AXPY_WORDS] = { 0 }; put64(ab, OMEGA_DEC_AXPY_X, bx.va); put64(ab, OMEGA_DEC_AXPY_A, ba.va); ab[(OMEGA_DEC_AXPY_ITERS - 0x380) / 4] = AXPY_BIG_ITERS; - OmegaGpuLaunch LB = axpy_launch(&K_axpy_big, ab, AXPY_BIG_STRIDE, AXPY_BIG_ITERS); - size_t diff_wfi = 0, diff_none = 0; uint64_t ns_wfi = 0, ns_none = 0; int rc_wfi = -1, rc_none = -1; - for (int variant = 0; variant < 2; variant++) { - memcpy(x, x0, n * 4); omega_gpu_session_sync_to_gpu(&bx); - omega_gpu_cmdlist_reset(cl); - for (uint32_t l = 0; l < N; l++) omega_gpu_cmdlist_add(cl, &LB); - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.timeout_ms = 20000; - o.barrier = variant ? OMEGA_GPU_CMDLIST_BARRIER_NONE : OMEGA_GPU_CMDLIST_BARRIER_WFI; - OmegaGpuCmdListStats st; int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - omega_gpu_session_sync_to_cpu(&bx); - size_t d = 0; for (size_t i = 0; i < n; i++) if (x[i] != xr[i]) d++; - if (variant) { diff_none = d; ns_none = st.elapsed_ns; rc_none = rc; } else { diff_wfi = d; ns_wfi = st.elapsed_ns; rc_wfi = rc; } - if (omega_gpu_cmdlist_is_latched()) break; - } - CHECK(rc_wfi == 0 && diff_wfi == 0, "heavy chain with WFI: rc %d, %zu of %zu elements differ", rc_wfi, diff_wfi, n); - printf("heavy chain (32 x 1M elements): WFI rc %d %zu differ %.1f us; BARRIER_NONE rc %d %zu differ %.1f us (informational: %s)\n", - rc_wfi, diff_wfi, ns_wfi / 1e3, rc_none, diff_none, ns_none / 1e3, - diff_none ? "grids overlapped without the barrier: the WFI is load-bearing" : "no difference seen; this does not prove ordering without a barrier"); - if (out) fprintf(out, "\"no_barrier_control\":{\"wfi_rc\":%d,\"wfi_diff\":%zu,\"wfi_ns\":%" PRIu64 ",\"none_rc\":%d,\"none_diff\":%zu,\"none_ns\":%" PRIu64 "},", rc_wfi, diff_wfi, ns_wfi, rc_none, diff_none, ns_none); - free(xr); - } - /* glue kernels in one list: RES ADD|NORM, SWIGLU, RES COMBINE|NORM, ARGMAX x2; then mutants */ - if (!omega_gpu_cmdlist_is_latched()) { - OmegaGpuMem m; if (omega_gpu_session_alloc(4u * (H + TK * H + TK + H + H + TK * 2 * INTER + TK * INTER + AM_PAD + 2 * OMEGA_DEC_ARGMAX_SPAN + 2 * OMEGA_DEC_ARGMAX_SPAN), &m)) { omega_gpu_session_unlock(); return chip_fail("alloc glue"); } - float *p = m.cpu; uint64_t va = m.va; - Glue g; g.x = p; g.a8 = p + H; g.w = g.a8 + TK * H; g.nw = g.w + TK; g.y = g.nw + H; g.gu = g.y + H; g.act = g.gu + TK * 2 * INTER; g.logits = g.act + TK * INTER; - g.ov = g.logits + AM_PAD; g.oi = (uint32_t *)(g.ov + OMEGA_DEC_ARGMAX_SPAN); float *ov2 = (float *)(g.oi + OMEGA_DEC_ARGMAX_SPAN); uint32_t *oi2 = (uint32_t *)(ov2 + OMEGA_DEC_ARGMAX_SPAN); -#define VA(ptr) (va + (uint64_t)((const uint8_t *)(ptr) - (const uint8_t *)p)) - static float x_after_an[H], y_an[H], y_cn[H], act_ref[TK * INTER], x_after_cn[H]; - /* 0 real; 1 norm-without-weight in slot 2 (the norm whose output is compared: slot 0 norm output is overwritten by - * slot 2, chip run r2 showed a slot-0 mutant cannot show); 2 combine skips expert 7 in slot 2; 3 argmax mutant */ - for (int mut = 0; mut < 4; mut++) { - for (int tie = mut == 0 ? 0 : 1; tie < 2; tie++) { /* mutants run on the tie case: the max sits in a j == 7 slot */ - glue_fill(&g, 400 + tie, tie); - memcpy(x_after_an, g.x, sizeof x_after_an); ref_res(OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_NORM, x_after_an, g.a8, g.w, g.nw, y_an, EPS, 1.0f); - ref_swiglu(g.gu, act_ref, 1.0f); - memcpy(x_after_cn, x_after_an, sizeof x_after_cn); ref_res(OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, x_after_cn, g.a8, g.w, g.nw, y_cn, EPS, SCALE_2P64); - omega_gpu_session_sync_to_gpu(&m); - uint32_t ra[OMEGA_DEC_RES_WORDS] = { 0 }, rb[OMEGA_DEC_RES_WORDS] = { 0 }, sa[OMEGA_DEC_SW_WORDS] = { 0 }, a0[OMEGA_DEC_AM_WORDS] = { 0 }, a1[OMEGA_DEC_AM_WORDS] = { 0 }; - put64(ra, OMEGA_DEC_RES_X, VA(g.x)); put64(ra, OMEGA_DEC_RES_A, VA(g.a8)); put64(ra, OMEGA_DEC_RES_W, VA(g.w)); put64(ra, OMEGA_DEC_RES_NW, VA(g.nw)); put64(ra, OMEGA_DEC_RES_Y, VA(g.y)); putf(ra, OMEGA_DEC_RES_EPS, EPS); putf(ra, OMEGA_DEC_RES_SCALE, 1.0f); - memcpy(rb, ra, sizeof rb); putf(rb, OMEGA_DEC_RES_SCALE, SCALE_2P64); - put64(sa, OMEGA_DEC_SW_GU, VA(g.gu)); put64(sa, OMEGA_DEC_SW_ACT, VA(g.act)); putf(sa, OMEGA_DEC_SW_SCALE, 1.0f); - put64(a0, OMEGA_DEC_AM_V, VA(g.logits)); put64(a0, OMEGA_DEC_AM_I, 0); put64(a0, OMEGA_DEC_AM_OV, VA(g.ov)); put64(a0, OMEGA_DEC_AM_OI, VA(g.oi)); - put64(a1, OMEGA_DEC_AM_V, VA(g.ov)); put64(a1, OMEGA_DEC_AM_I, VA(g.oi)); put64(a1, OMEGA_DEC_AM_OV, VA(ov2)); put64(a1, OMEGA_DEC_AM_OI, VA(oi2)); - OmegaGpuLaunch l[5]; memset(l, 0, sizeof l); - for (int i = 0; i < 5; i++) { l[i].threads_x = OMEGA_DEC_THREADS; l[i].threads_y = 1; l[i].grid_y = 1; l[i].timeout_ms = 20000; } - Kern *k0 = &K_res_an, *k2 = mut == 1 ? &K_res_cn_m1 : mut == 2 ? &K_res_m2 : &K_res_cn, *k3 = mut == 3 ? &K_am_m1 : &K_am0; - l[0].code_va = k0->code.va; l[0].gpr_count = k0->gpr; l[0].grid_x = 1; l[0].num_elements = H; l[0].args = ra; l[0].n_args = OMEGA_DEC_RES_WORDS; - l[1].code_va = K_sw.code.va; l[1].gpr_count = K_sw.gpr; l[1].grid_x = INTER / OMEGA_DEC_THREADS; l[1].grid_y = TK; l[1].num_elements = TK * INTER; l[1].args = sa; l[1].n_args = OMEGA_DEC_SW_WORDS; - l[2].code_va = k2->code.va; l[2].gpr_count = k2->gpr; l[2].grid_x = 1; l[2].num_elements = H; l[2].args = rb; l[2].n_args = OMEGA_DEC_RES_WORDS; - l[3].code_va = k3->code.va; l[3].gpr_count = k3->gpr; l[3].grid_x = AM_CTAS; l[3].num_elements = AM_PAD; l[3].args = a0; l[3].n_args = OMEGA_DEC_AM_WORDS; - l[4].code_va = K_am1.code.va; l[4].gpr_count = K_am1.gpr; l[4].grid_x = 1; l[4].num_elements = OMEGA_DEC_ARGMAX_SPAN; l[4].args = a1; l[4].n_args = OMEGA_DEC_AM_WORDS; - omega_gpu_cmdlist_reset(cl); - int ok = 1; for (int i = 0; i < 5; i++) if (omega_gpu_cmdlist_add(cl, &l[i]) < 0) { ok = 0; chip_fail("glue add"); } - if (!ok) break; - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.timeout_ms = 20000; - OmegaGpuCmdListStats st; int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - omega_gpu_session_sync_to_cpu(&m); - int xbad = memcmp(g.x, x_after_cn, sizeof x_after_cn) != 0, ybad = 0, abad = 0; - for (unsigned i = 0; i < H; i++) if (!close_rel(g.y[i], y_cn[i], 2e-5f, 1e-6f)) ybad++; - for (unsigned i = 0; i < TK * INTER; i++) if (!close_rel(g.act[i], act_ref[i], 5e-5f, 1e-6f)) abad++; - int ambad = oi2[0] != g.am_ref; - if (mut == 0) { - CHECK(rc == 0, "glue list rc %d (%s)", rc, rc ? omega_gpu_session_last_error() : ""); - CHECK(!xbad, "glue tie %d: residual x after ADD then COMBINE bit-identical to the host reference", tie); - CHECK(ybad == 0, "glue tie %d: final RMSNorm (scale 2^64) within 2e-5 (%d bad)", tie, ybad); - CHECK(abad == 0, "glue tie %d: SwiGLU within 5e-5 (%d bad)", tie, abad); - CHECK(!ambad, "glue tie %d: argmax %u == host %u (value %g)", tie, oi2[0], g.am_ref, ov2[0]); - printf("glue list tie %d: rc %d, 5 launches in %u submit(s) %.1f us chip; x %s, y %d bad, act %d bad, argmax %u (ref %u)\n", tie, rc, st.submits, st.elapsed_ns / 1e3, xbad ? "DIFFERS" : "identical", ybad, abad, oi2[0], g.am_ref); - if (out) fprintf(out, "\"glue_tie%d\":{\"rc\":%d,\"chip_ns\":%" PRIu64 ",\"x_identical\":%d,\"y_bad\":%d,\"act_bad\":%d,\"argmax\":%u,\"argmax_ref\":%u},", tie, rc, st.elapsed_ns, !xbad, ybad, abad, oi2[0], g.am_ref); - } else { - int caught = mut == 3 ? ambad : (xbad || ybad); - CHECK(rc == 0 && caught, "chip mutant %d caught (rc %d, x %s, y %d bad, argmax %u ref %u)", mut, rc, xbad ? "differs" : "same", ybad, oi2[0], g.am_ref); - printf("chip mutant %d: rc %d, x %s, y %d bad, argmax %u (ref %u): %s\n", mut, rc, xbad ? "differs" : "same", ybad, oi2[0], g.am_ref, caught ? "caught" : "NOT CAUGHT"); - } - if (omega_gpu_cmdlist_is_latched()) break; - } - if (omega_gpu_cmdlist_is_latched()) break; - } -#undef VA - omega_gpu_session_free(&m); - } - omega_gpu_session_free(&bx); omega_gpu_session_free(&ba); omega_gpu_session_free(&bx0); - omega_gpu_session_unlock(); - omega_gpu_cmdlist_free(cl); - if (out) { fprintf(out, "\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - return g_failed ? 1 : 0; -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; uint32_t reps = 20; const char *out = NULL; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) omega_gpu_session_set_spin_us((uint32_t)atoi(argv[++i])); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out = argv[++i]; - else { printf("usage: %s [--host-only|--sim] [--reps N] [--spin-us U] [--out receipt.json]\n", argv[0]); return 2; } - } - if (reps == 0) reps = 1; - int rc = host ? host_only() : sim ? (sim_mode() | sim_wide()) : chip_run(out, reps); - printf("%s: %d checks, %d failed: %s\n", host ? "host-only" : sim ? "sim" : "chip", g_checks, g_failed, rc ? "FAIL" : "PASS"); - return rc; -} diff --git a/tests/gpu_dattn256_multi_test.c b/tests/gpu_dattn256_multi_test.c deleted file mode 100644 index daef69b87..000000000 --- a/tests/gpu_dattn256_multi_test.c +++ /dev/null @@ -1,118 +0,0 @@ -/* - * gpu_dattn256_multi_test (chip): the multi-token decode attention (L369, omega_gpu_decode_attn256_multi_record) must be - * T decode steps (omega_gpu_decode_attn256 at positions pos0 .. pos0 + T - 1) bit for bit: every output row and every - * K/V row it appends. Qwen3.6-35B-A3B shape (16 q heads, 2 KV heads, 4 q heads per CTA row, rotary 64), two caches with - * the same random history, qkv rows 36864 bytes apart as the 35B graph lays them out (the attention row is the first - * 20480 bytes of the q|k|v mix row). Cases cross split boundaries, start mid-context and reach 8k (several attend groups). - * Controls that must differ: the prep launch dropped (test mutant 1) and a wrong row stride. - * Verdict line last: "gpu_dattn256_multi_test: N checks, F failed: PASS|FAIL". - */ -#include "omega_gpu_decode_attn256_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_cmdlist.h" -#include -#include -#include -#include - -#define QH 16u -#define KVH 2u -#define QPC 4u -#define ROT 64u -#define QKVW ((QH + 2u * KVH) * 256u) /* 5120 */ -#define OUTW (QH * 256u) /* 4096 */ -#define XROW 36864u /* the graph's ATT_MIX row: 9216 f32 */ -#define OROW (OUTW * 4u) -#define MAXP 8448u -static const float EPS = 1e-6f, OSCALE = 18446744073709551616.0f; /* 2^64, as the graph */ - -static int g_checks, g_failed; -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf(" FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t rs = 12345u; -static float frand(void) { rs = rs * 1664525u + 1013904223u; return ((float)(rs >> 8) / 16777216.0f) * 2.0f - 1.0f; } -static uint16_t bf(float x) { uint32_t u; memcpy(&u, &x, 4); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } - - -static int make_cache(OmegaGpuDecodeAttn256Cache **c, const float *qn, const float *kn, const uint16_t *hk, const uint16_t *hv, uint32_t hist) { - if (omega_gpu_decode_attn256_cache_alloc_shape(1, MAXP, 1e7, ROT, QH, KVH, QPC, c) != 0) return -1; - if (omega_gpu_decode_attn256_set_norms(*c, 0, qn, kn) != 0) return -1; - for (uint32_t h = 0; h < KVH && hist; h++) - if (omega_gpu_decode_attn256_cache_write(*c, 0, h, 0, hist, hk + (size_t)h * MAXP * 256, hv + (size_t)h * MAXP * 256) != 0) return -1; - return 0; -} - -/* one multi record of T tokens from pos0; rows: T rows of XROW bytes */ -static int run_multi(OmegaGpuDecodeAttn256Cache *c, uint32_t pos0, uint32_t T, const uint8_t *rows, uint32_t xstride, float *out) { - if (omega_gpu_decode_attn256_multi_prepare(c) != 0) return -1; - OmegaGpuCmdList *cl = NULL; - if (omega_gpu_cmdlist_create(16, &cl) != 0) return -1; - omega_gpu_session_lock(); - OmegaGpuMem m; memset(&m, 0, sizeof m); - const size_t s_rows = (size_t)T * XROW, s_out = (size_t)T * OROW; - int ok = omega_gpu_session_open() != NULL && omega_gpu_session_alloc(s_rows + s_out, &m) == 0; - if (ok) { - memcpy(m.cpu, rows, s_rows); - float *o = (float *)((uint8_t *)m.cpu + s_rows); - for (size_t i = 0; i < (size_t)T * OUTW; i++) o[i] = NAN; - ok = omega_gpu_session_sync_to_gpu(&m) == 0; - } - if (ok) ok = omega_gpu_decode_attn256_multi_record(cl, c, 0, pos0, T, m.va, xstride, EPS, OSCALE, m.va + s_rows, OROW) == 0; - OmegaGpuCmdListOpts opts; memset(&opts, 0, sizeof opts); - OmegaGpuCmdListStats st; memset(&st, 0, sizeof st); - if (ok) ok = omega_gpu_cmdlist_submit(cl, &opts, &st) == 0 && st.sems_done == st.launches; - if (ok) ok = omega_gpu_session_sync_to_cpu(&m) == 0; - if (ok) memcpy(out, (uint8_t *)m.cpu + s_rows, s_out); - if (m.cpu) omega_gpu_session_free(&m); - omega_gpu_session_unlock(); - omega_gpu_cmdlist_free(cl); - if (!ok) return -1; - return omega_gpu_decode_attn256_counters_check(c) == 0 ? 0 : -1; -} - -static int one_case(uint32_t pos0, uint32_t T, int control) { - float qn[256], kn[256]; - for (unsigned i = 0; i < 256; i++) { qn[i] = 1.0f + 0.2f * frand(); kn[i] = 1.0f + 0.2f * frand(); } - uint16_t *hk = calloc((size_t)KVH * MAXP * 256, 2), *hv = calloc((size_t)KVH * MAXP * 256, 2); - uint8_t *rows = calloc((size_t)T, XROW); - float *oa = malloc((size_t)T * OROW), *ob = malloc((size_t)T * OROW); - if (!hk || !hv || !rows || !oa || !ob) return -1; - for (uint32_t h = 0; h < KVH; h++) for (uint32_t p = 0; p < pos0; p++) for (unsigned d = 0; d < 256; d++) { - hk[((size_t)h * MAXP + p) * 256 + d] = bf(frand() * 3.0f); hv[((size_t)h * MAXP + p) * 256 + d] = bf(frand()); - } - for (uint32_t t = 0; t < T; t++) { float *r = (float *)(rows + (size_t)t * XROW); for (unsigned i = 0; i < XROW / 4u; i++) r[i] = frand() * 2.0f; } - OmegaGpuDecodeAttn256Cache *ca = NULL, *cb = NULL; - int rc = make_cache(&ca, qn, kn, hk, hv, pos0) || make_cache(&cb, qn, kn, hk, hv, pos0) ? -1 : 0; - for (uint32_t t = 0; t < T && rc == 0; t++) - if (omega_gpu_decode_attn256(ca, 0, pos0 + t, (const float *)(rows + (size_t)t * XROW), EPS, OSCALE, oa + (size_t)t * OUTW, NULL) != 0) rc = -1; - if (rc == 0) { - if (control == 1) omega_gpu_decode_attn256_test_set_multi_mutant(1); - rc = run_multi(cb, pos0, T, rows, control == 2 ? QKVW * 4u : XROW, ob); - omega_gpu_decode_attn256_test_set_multi_mutant(0); - } - size_t odiff = 0, kdiff = 0; - if (rc == 0) { - odiff = 0; for (size_t i = 0; i < (size_t)T * OUTW; i++) { uint32_t a, b; memcpy(&a, &oa[i], 4); memcpy(&b, &ob[i], 4); if (a != b) odiff++; } - uint16_t ka[256], va[256], kb[256], vb[256]; - for (uint32_t h = 0; h < KVH && rc == 0; h++) for (uint32_t t = 0; t < T; t++) { - if (omega_gpu_decode_attn256_cache_read(ca, 0, h, pos0 + t, ka, va) != 0 || omega_gpu_decode_attn256_cache_read(cb, 0, h, pos0 + t, kb, vb) != 0) { rc = -1; break; } - if (memcmp(ka, kb, sizeof ka) || memcmp(va, vb, sizeof va)) kdiff++; - } - } - const char *what = control == 1 ? "control prep dropped" : control == 2 ? "control row stride 20480" : "real"; - if (rc != 0) { CHECK(0, "pos0 %u T %u %s: chip call failed (%s)", pos0, T, what, omega_gpu_decode_attn_last_error()); } - else if (control) { CHECK(odiff > 0, "pos0 %u T %u %s: NOT caught", pos0, T, what); printf("chip pos0 %u T %u %s: %zu output words differ, %zu K/V rows differ -> %s\n", pos0, T, what, odiff, kdiff, odiff ? "caught" : "MISSED"); } - else { CHECK(odiff == 0 && kdiff == 0, "pos0 %u T %u: %zu output words, %zu K/V rows differ", pos0, T, odiff, kdiff); printf("chip pos0 %u T %u: outputs %s, K/V rows %s\n", pos0, T, odiff ? "DIFFER" : "identical", kdiff ? "DIFFER" : "identical"); } - omega_gpu_decode_attn256_cache_free(ca); omega_gpu_decode_attn256_cache_free(cb); - free(hk); free(hv); free(rows); free(oa); free(ob); - return rc; -} - -int main(void) { - static const uint32_t cases[][2] = { { 0, 1 }, { 0, 7 }, { 5, 128 }, { 250, 10 }, { 1000, 37 }, { 2040, 128 }, { 6000, 128 }, { 8191, 1 } }; - for (unsigned i = 0; i < sizeof cases / sizeof cases[0]; i++) one_case(cases[i][0], cases[i][1], 0); - one_case(300, 16, 1); - one_case(300, 16, 2); - printf("gpu_dattn256_multi_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_decode_attn256_test.c b/tests/gpu_decode_attn256_test.c deleted file mode 100644 index b8b71061a..000000000 --- a/tests/gpu_decode_attn256_test.c +++ /dev/null @@ -1,480 +0,0 @@ -/* - * gpu_decode_attn256_test: the one-launch decode attention for Qwen3.8-27B (omega-mv#544, omega_gpu_decode_attn256_api.h). - * --host-only host pieces: RoPE rows (partial: pairs >= rotary_dim/2 are identity), the permutation (bijection, and - * "full rotate-half on the permuted head with the partial table == the model's rotate-half within the - * first rotary_dim dims", double), reference sanity (context 1 returns v_new), codegen budget per depth - * and mutant, refusals. No device. - * --sim the kernel through tests/bw_warp_sim_k.h (no chip): contexts 1, 7, 256, 257, 301, 701 (1..3 splits, - * the cross-split combine, 2 chunks per CTA), rotary_dim 64 and 256, both fragment orders, every mutant - * caught at context 301. - * (default) the chip: parity against the double reference at contexts 1, 7, 256, 301 (sharp q), 1024, 4096, 8192, - * 32768 (and 131072 with --max-pos 131072), the appended K/V row read back and compared, second call - * identical, out_scale 2^64 path, timing medians with the host caches evicted, every mutant caught at - * context 301, JSON receipt with --out. - * The reference is the model's maths in the model's dim order (crates/aien-inference-abi/src/qwen38.rs `attention`: - * zero-centred RMSNorm x * rsqrt(mean + eps) * (1 + w), RoPE on the first rotary_dim dims with pairs (j, j + rotary_dim/2), - * scale 1/sqrt(256), causal softmax over the context). The test permutes q, k and the norm weights with - * omega_dattn256_perm_vec before handing them to the kernel, stores history K rows permuted, and un-permutes nothing on - * the way back (V and the output are in model order). The gate (sigmoid) is outside the kernel and outside this test. - * Tolerance: |out - ref| <= 3e-3 * max|v| + 1e-6 per element. Host and simulator passes are never chip results. - */ -#include "omega_gpu_decode_attn256_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_hostmath.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static const double THETA = 10000000.0; /* Qwen3.8-27B rope_theta */ -static const float EPS = 1e-6f; -#define HD 256u -/* Model shape under test: 0 = the 27B (24 q / 4 KV heads, 6 q per CTA row); -DDATTN_TEST_Q36 builds Qwen3.6-35B-A3B (16 / 2 / 4, - * two CTA rows per KV head; sc L306). */ -#ifdef DATTN_TEST_Q36 -#define QH 16u -#define KVH 2u -#define QPC 4u -#else -#define QH 24u -#define KVH 4u -#define QPC 6u -#endif -#define SPEC_SHAPE , .q_heads = QH, .kv_heads = KVH, .q_per_cta = QPC -#define VY (QH / QPC) /* CTA rows */ -#define QW ((QH + 2u * KVH) * HD) /* 8192 */ -#define OW (QH * HD) /* 6144 */ -#define QEND (QH * HD) /* 6144: k block starts here */ -#define KEND (QEND + KVH * HD) /* 7168: v block starts here */ - -/* one layer's random state in MODEL order: qkv, history rows (bf16) for 4 KV heads, zero-centred norm weights w */ -typedef struct { - uint32_t max_pos, pos, rotary; - float qkv[QW], qn[HD], kn[HD]; - uint16_t *kc, *vc; /* [4][max_pos][256] model order (history 0..pos-1 filled; the rest zero) */ - float vmax; -} Case; -static void case_make(Case *c, uint32_t max_pos, uint32_t pos, uint32_t rotary, uint32_t seed, float qscale) { - uint32_t s = seed; - c->max_pos = max_pos; c->pos = pos; c->rotary = rotary; - for (size_t i = 0; i < QW; i++) c->qkv[i] = frand(&s, -1.0f, 1.0f) * (i < QEND ? qscale : 1.0f); - for (unsigned i = 0; i < HD; i++) { c->qn[i] = frand(&s, -0.2f, 0.2f); c->kn[i] = frand(&s, -0.2f, 0.2f); } - size_t words = (size_t)KVH * max_pos * HD; - c->kc = calloc(words, 2); c->vc = calloc(words, 2); - c->vmax = 1.0f; - for (unsigned g = 0; g < KVH; g++) for (uint32_t t = 0; t < pos; t++) for (unsigned i = 0; i < HD; i++) { - size_t o = ((size_t)g * max_pos + t) * HD + i; - c->kc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); c->vc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); - } -} -static void case_free(Case *c) { free(c->kc); free(c->vc); } -/* what the kernel sees: q and k heads permuted, v as is; norms 1 + w permuted; K history rows permuted */ -static void case_kernel_inputs(const Case *c, float *qkv_k, float *qn_k, float *kn_k) { - for (unsigned h = 0; h < QH + KVH; h++) omega_dattn256_perm_vec(c->qkv + h * HD, qkv_k + h * HD, c->rotary); - memcpy(qkv_k + KEND, c->qkv + KEND, (size_t)KVH * HD * 4); - float t[HD]; - for (unsigned i = 0; i < HD; i++) t[i] = 1.0f + c->qn[i]; - omega_dattn256_perm_vec(t, qn_k, c->rotary); - for (unsigned i = 0; i < HD; i++) t[i] = 1.0f + c->kn[i]; - omega_dattn256_perm_vec(t, kn_k, c->rotary); -} -static uint16_t *case_kc_perm(const Case *c) { - size_t rows = (size_t)KVH * c->max_pos; - uint16_t *p = calloc(rows * HD, 2); - for (size_t r = 0; r < rows; r++) omega_dattn256_perm_vec_bf16(c->kc + r * HD, p + r * HD, c->rotary); - return p; -} - -/* ---- double-precision oracle (test-owned: libm) in MODEL order ---- */ -static void norm_rope(double *x, const float *w, float eps, uint32_t rotary, uint32_t pos, double theta, int rope) { - double ss = 0; for (unsigned i = 0; i < HD; i++) ss += x[i] * x[i]; - double r = 1.0 / sqrt(ss / (double)HD + (double)eps); - for (unsigned i = 0; i < HD; i++) x[i] = x[i] * r * (1.0 + (double)w[i]); - if (!rope) return; - const unsigned half = rotary / 2; - for (unsigned j = 0; j < half; j++) { - double inv = 1.0 / pow(theta, (double)(2 * j) / (double)rotary), ang = (double)pos * inv, cs = cos(ang), sn = sin(ang); - double x1 = x[j], x2 = x[j + half]; - x[j] = x1 * cs - x2 * sn; x[j + half] = x2 * cs + x1 * sn; - } -} -/* Reference of the whole layer step. kc/vc: this layer's bf16 planes [4][max_pos][256] (model order) holding positions - * 0..pos-1; out: [24*256] doubles (already * out_scale); k_new/v_new: the bf16 rows (model order) the kernel must have - * appended at pos ([4][256] each). The reference rounds its k_new/v_new to bf16 and attends over the rounded values. */ -static void reference(const float *qkv, const uint16_t *kc, const uint16_t *vc, uint32_t max_pos, uint32_t pos, uint32_t rotary, - const float *q_w, const float *k_w, float eps, double theta, float out_scale, double *out, uint16_t *k_new, uint16_t *v_new) { - const double qscale = 1.0 / sqrt((double)HD); - for (unsigned gk = 0; gk < KVH; gk++) { - double k[HD]; - for (unsigned i = 0; i < HD; i++) k[i] = qkv[QEND + gk * HD + i]; - norm_rope(k, k_w, eps, rotary, pos, theta, 1); - for (unsigned i = 0; i < HD; i++) { k_new[gk * HD + i] = omega_dattn_bf16_rne((float)k[i]); v_new[gk * HD + i] = omega_dattn_bf16_rne(qkv[KEND + gk * HD + i]); } - } - double *p = calloc((size_t)pos + 1, sizeof(double)); - for (unsigned h = 0; h < QH; h++) { - unsigned gk = h / (QH / KVH); - double q[HD]; - for (unsigned i = 0; i < HD; i++) q[i] = qkv[h * HD + i]; - norm_rope(q, q_w, eps, rotary, pos, theta, 1); - double mx = -1e300; - for (uint32_t t = 0; t <= pos; t++) { - const uint16_t *kr = t == pos ? k_new + gk * HD : kc + ((size_t)gk * max_pos + t) * HD; - double s = 0; for (unsigned i = 0; i < HD; i++) s += q[i] * (double)omega_dattn_bf16_f32(kr[i]); - s *= qscale; p[t] = s; if (s > mx) mx = s; - } - double l = 0; for (uint32_t t = 0; t <= pos; t++) { p[t] = exp(p[t] - mx); l += p[t]; } - double o[HD]; memset(o, 0, sizeof o); - for (uint32_t t = 0; t <= pos; t++) { - const uint16_t *vr = t == pos ? v_new + gk * HD : vc + ((size_t)gk * max_pos + t) * HD; - for (unsigned i = 0; i < HD; i++) o[i] += p[t] * (double)omega_dattn_bf16_f32(vr[i]); - } - for (unsigned i = 0; i < HD; i++) out[h * HD + i] = o[i] / l * (double)out_scale; - } - free(p); -} - -/* compares out (f32 [6144]) against the reference; returns the number of elements outside the tolerance and the worst ratio */ -static size_t parity(const Case *c, const float *out, float out_scale, double *worst, uint16_t *k_new, uint16_t *v_new) { - double *ref = malloc(OW * sizeof(double)); - reference(c->qkv, c->kc, c->vc, c->max_pos, c->pos, c->rotary, c->qn, c->kn, EPS, THETA, out_scale, ref, k_new, v_new); - double tol = 3e-3 * c->vmax * out_scale + 1e-6 * out_scale; size_t bad = 0; *worst = 0; - for (size_t i = 0; i < OW; i++) { double d = fabs((double)out[i] - ref[i]); if (d / tol > *worst) *worst = d / tol; if (d > tol) bad++; } - free(ref); - return bad; -} -/* appended rows (chip rows: K permuted, V model order) against the reference rows (model order): v exact, k within one - * bf16 ulp on at most 32 elements over the 4 heads */ -static int rows_ok(const uint16_t *k_chip, const uint16_t *v_chip, const uint16_t *k_ref, const uint16_t *v_ref, uint32_t rotary, char *why, size_t n) { - unsigned kflips = 0; - for (unsigned g = 0; g < KVH; g++) for (unsigned i = 0; i < HD; i++) { - unsigned ci = g * HD + i, ri = g * HD + omega_dattn256_perm_slot(i, rotary); - if (v_chip[ci] != v_ref[ci]) { snprintf(why, n, "v[%u] chip %04x ref %04x", ci, v_chip[ci], v_ref[ci]); return 0; } - if (k_chip[ci] != k_ref[ri]) { int d = (int)k_chip[ci] - (int)k_ref[ri]; if (d < -1 || d > 1) { snprintf(why, n, "k slot %u (model dim %u) chip %04x ref %04x", ci, ri, k_chip[ci], k_ref[ri]); return 0; } kflips++; } - } - if (kflips > 32) { snprintf(why, n, "%u one-ulp k flips", kflips); return 0; } - snprintf(why, n, "ok (%u one-ulp k flips)", kflips); - return 1; -} - -/* ------------------------------------------------------------- host only */ -static void perm_checks(void) { - static const uint32_t rots[] = { 64, 256, 2, 128, 32 }; - for (unsigned ri = 0; ri < sizeof rots / sizeof rots[0]; ri++) { - uint32_t R = rots[ri], P = R / 2; uint8_t seen[HD]; memset(seen, 0, sizeof seen); int bij = 1; - for (uint32_t i = 0; i < HD; i++) { uint32_t m = omega_dattn256_perm_slot(i, R); if (m >= HD || seen[m]) bij = 0; else seen[m] = 1; } - CHECK(bij, "perm rotary %u is a bijection", R); - int pairs = 1; for (uint32_t i = 0; i < P; i++) pairs &= omega_dattn256_perm_slot(i, R) == i && omega_dattn256_perm_slot(i + 128, R) == i + P; - CHECK(pairs, "perm rotary %u: slots (i, i+128), i < %u hold the model pairs (i, i+%u)", R, P, P); - if (R == 256) { int id = 1; for (uint32_t i = 0; i < HD; i++) id &= omega_dattn256_perm_slot(i, R) == i; CHECK(id, "perm rotary 256 is the identity"); } - /* the kernel's rotate-half on the permuted head with the partial table == the model's rope, in double */ - uint32_t s = 99 + R; double maxd = 0; - for (unsigned trial = 0; trial < 50; trial++) { - uint32_t pos = trial < 3 ? trial : lcg(&s) % 131072u; - double x[HD], y_model[HD], xp[HD], yp[HD], y_back[HD]; float row[HD]; - for (unsigned i = 0; i < HD; i++) x[i] = frand(&s, -2.0f, 2.0f); - memcpy(y_model, x, sizeof x); - { float w0[HD]; for (unsigned i = 0; i < HD; i++) w0[i] = 0.0f; /* rope only: norm with w = 0 then undo the scale */ - double ss = 0; for (unsigned i = 0; i < HD; i++) ss += x[i] * x[i]; double r = 1.0 / sqrt(ss / HD + (double)EPS); - norm_rope(y_model, w0, EPS, R, pos, THETA, 1); for (unsigned i = 0; i < HD; i++) y_model[i] /= r; } - omega_dattn256_rope_row(pos, THETA, R, row); - for (unsigned i = 0; i < HD; i++) xp[i] = x[omega_dattn256_perm_slot(i, R)]; - for (unsigned i = 0; i < 128; i++) { double cs = row[i], sn = row[128 + i]; yp[i] = xp[i] * cs - xp[i + 128] * sn; yp[i + 128] = xp[i + 128] * cs + xp[i] * sn; } - for (unsigned i = 0; i < HD; i++) y_back[omega_dattn256_perm_slot(i, R)] = yp[i]; - for (unsigned i = 0; i < HD; i++) { double d = fabs(y_back[i] - y_model[i]); if (d > maxd) maxd = d; } - } - CHECK(maxd < 1e-5, "perm rotary %u: rotate-half on the permuted head == model rope (max abs diff %.3g; f32 table)", R, maxd); - printf("perm rotary %3u: bijection, pairs, rope-by-permutation max abs diff %.3g over 50 positions\n", R, maxd); - } -} -static void host_only(void) { - float row[HD]; omega_dattn256_rope_row(0, THETA, 64, row); - int ok = 1; for (unsigned i = 0; i < 128; i++) ok &= row[i] == 1.0f && row[128 + i] == 0.0f; - CHECK(ok, "rope row 0 is cos 1 sin 0"); - omega_dattn256_rope_row(100, THETA, 64, row); - CHECK(fabs((double)row[0] - cos(100.0)) < 1e-6 && fabs((double)row[128] - sin(100.0)) < 1e-6, "rope row 100 pair 0 is cos/sin(100)"); - CHECK(fabs((double)row[31] - cos(100.0 * pow(THETA, -62.0 / 64.0))) < 1e-6, "rope row 100 pair 31 uses theta^(-62/64)"); - ok = 1; for (unsigned i = 32; i < 128; i++) ok &= row[i] == 1.0f && row[128 + i] == 0.0f; - CHECK(ok, "rope row 100: pairs 32..127 are identity for rotary_dim 64"); - omega_dattn256_rope_row(100, THETA, 256, row); - CHECK(fabs((double)row[127] - cos(100.0 * pow(THETA, -254.0 / 256.0))) < 1e-6, "rope row 100 rotary 256 pair 127 uses theta^(-254/256)"); - perm_checks(); - /* reference sanity: context 1 returns v_new (rounded), whatever q and k */ - { Case c; case_make(&c, 256, 0, 64, 11, 1.0f); double *ref = malloc(OW * sizeof(double)); uint16_t kn[KVH * HD], vn[KVH * HD]; - reference(c.qkv, c.kc, c.vc, 256, 0, 64, c.qn, c.kn, EPS, THETA, 1.0f, ref, kn, vn); - int good = 1; for (unsigned h = 0; h < QH && good; h++) for (unsigned i = 0; i < HD; i++) if (ref[h * HD + i] != (double)omega_dattn_bf16_f32(vn[(h / (QH / KVH)) * HD + i])) { good = 0; break; } - CHECK(good, "reference: context 1 returns the rounded v_new of the head's KV group"); - free(ref); case_free(&c); } - { Case c; case_make(&c, 256, 8, 64, 12, 1.0f); - double *ref = malloc(OW * sizeof(double)); uint16_t kn[KVH * HD], vn[KVH * HD]; - reference(c.qkv, c.kc, c.vc, 256, 8, 64, c.qn, c.kn, EPS, THETA, 1.0f, ref, kn, vn); - double ss = 0; for (unsigned i = 0; i < HD; i++) { double v = omega_dattn_bf16_f32(kn[i]); ss += v * v; } - CHECK(ss / HD > 0.6 && ss / HD < 1.5, "reference: k_new has rms about 1 after RMSNorm (%.3f)", ss / HD); - double os = 0; for (unsigned i = 0; i < OW; i++) os += fabs(ref[i]); - CHECK(os / OW < 0.6, "reference: a 9-token softmax average of U(-1,1) rows is small (%.3f)", os / OW); - free(ref); case_free(&c); } - /* codegen budget */ - for (uint32_t d = 1; d <= 4; d++) for (int m = 0; m <= 5; m++) { - OmegaDecodeAttn256Spec s = { .depth = d, .mutant = m SPEC_SHAPE }; uint32_t n = 0, gp = 0; - int rc = omega_decode_attn256_prog_stats(&s, &n, &gp); - CHECK(rc == 0 && n <= 1024 && gp <= 126, "codegen depth %u mutant %d: rc %d insns %u gprs %u", d, m, rc, n, gp); - if (rc == 0 && m == 0) printf("codegen depth %u: %u instructions, %u registers (declared %u, 256 threads -> %u of 65536)\n", d, n, gp, omega_bw_gpr_declared(gp), 256 * omega_bw_gpr_declared(gp)); - } - { OmegaDecodeAttn256Spec s = { .depth = 0 SPEC_SHAPE }; CHECK(omega_decode_attn256_prog_stats(&s, NULL, NULL) != 0, "depth 0 refused"); - s.depth = 5; CHECK(omega_decode_attn256_prog_stats(&s, NULL, NULL) != 0, "depth 5 refused"); - s.depth = 1; s.mutant = 6; CHECK(omega_decode_attn256_prog_stats(&s, NULL, NULL) != 0, "mutant 6 refused"); - s.mutant = 0; s.q_heads = 24; s.kv_heads = 4; s.q_per_cta = 5; CHECK(omega_decode_attn256_prog_stats(&s, NULL, NULL) != 0, "q_per_cta not dividing q heads refused"); - s.q_heads = 24; s.kv_heads = 2; s.q_per_cta = 4; CHECK(omega_decode_attn256_prog_stats(&s, NULL, NULL) != 0, "three CTA rows per KV head refused"); - s.q_heads = 16; s.kv_heads = 2; s.q_per_cta = 8; CHECK(omega_decode_attn256_prog_stats(&s, NULL, NULL) != 0, "more than 6 q heads per CTA row refused"); } - CHECK(omega_gpu_decode_attn256_cache_alloc_shape(0, 256, THETA, 64, QH, KVH, QPC, NULL) == OMEGA_GPU_DATTN_BAD_ARGS, "NULL out refused"); - { OmegaGpuDecodeAttn256Cache *c = (OmegaGpuDecodeAttn256Cache *)1; - CHECK(omega_gpu_decode_attn256_cache_alloc_shape(1, 100, THETA, 64, QH, KVH, QPC, &c) == OMEGA_GPU_DATTN_BAD_ARGS && c == NULL, "max_pos not a multiple of 256 refused before any device work"); - c = (OmegaGpuDecodeAttn256Cache *)1; - CHECK(omega_gpu_decode_attn256_cache_alloc_shape(1, 256, THETA, 63, QH, KVH, QPC, &c) == OMEGA_GPU_DATTN_BAD_ARGS && c == NULL, "odd rotary_dim refused"); - c = (OmegaGpuDecodeAttn256Cache *)1; - CHECK(omega_gpu_decode_attn256_cache_alloc_shape(1, 256, THETA, 258, QH, KVH, QPC, &c) == OMEGA_GPU_DATTN_BAD_ARGS && c == NULL, "rotary_dim > 256 refused"); - c = (OmegaGpuDecodeAttn256Cache *)1; - CHECK(omega_gpu_decode_attn256_cache_alloc_shape(1, 131072 + 256, THETA, 64, QH, KVH, QPC, &c) == OMEGA_GPU_DATTN_BAD_ARGS && c == NULL, "max_pos > 131072 refused"); } - CHECK(OMEGA_DATTN256_SHARED_BYTES <= 16384u, "shared memory within the QMD cap (%u)", OMEGA_DATTN256_SHARED_BYTES); - CHECK(OMEGA_DATTN256_SM_FLAG + 16u == OMEGA_DATTN256_SHARED_BYTES && OMEGA_DATTN256_SM_S + 8192u <= OMEGA_DATTN256_SM_M && OMEGA_DATTN256_SM_M + 288u <= OMEGA_DATTN256_SM_L && OMEGA_DATTN256_SM_L + 256u <= OMEGA_DATTN256_SM_FLAG, "shared map does not overlap"); -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -static int sim_point(uint32_t max_pos, uint32_t pos, uint32_t rotary, uint32_t depth, int mutant, uint32_t per_split, float qscale, uint32_t seed, char *msg, size_t n, double *worst, size_t *bad, char *rows, size_t rn) { - static BlackwellIRProgram prog; - OmegaDecodeAttn256Spec spec = { .depth = depth, .mutant = mutant SPEC_SHAPE }; - if (omega_blackwell_codegen_decode_attn256_prog(&spec, &prog) != 0) { snprintf(msg, n, "codegen refused"); return -1; } - Case c; case_make(&c, max_pos, pos, rotary, seed, qscale); - uint16_t *kcp = case_kc_perm(&c); - const uint32_t splits = (pos + per_split) / per_split; - size_t plane = (size_t)KVH * max_pos * OMEGA_DATTN256_ROW_BYTES + OMEGA_DATTN256_PLANE_SLACK, hist = (size_t)KVH * max_pos * OMEGA_DATTN256_ROW_BYTES; - uint8_t *kv = aligned_alloc(16, 2 * plane); memset(kv, 0, 2 * plane); - float *rope = aligned_alloc(16, (size_t)max_pos * OMEGA_DATTN256_ROPE_ROW_BYTES); for (uint32_t p = 0; p < max_pos; p++) omega_dattn256_rope_row(p, THETA, rotary, rope + (size_t)p * 256); - float *norms = aligned_alloc(16, 2048); - float *qkv = aligned_alloc(16, sizeof c.qkv); - case_kernel_inputs(&c, qkv, norms, norms + HD); - float *out = aligned_alloc(16, OW * 4), *copy = malloc(OW * 4); - float *part = aligned_alloc(16, (size_t)VY * splits * OMEGA_DATTN256_PARTIAL_WORDS * 4); - uint32_t *cnt = aligned_alloc(16, 16); - int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 256; s.order = order; - static uint8_t smem[OMEGA_DATTN256_SHARED_BYTES]; s.smem = smem; s.smem_bytes = OMEGA_DATTN256_SHARED_BYTES; - memset(cnt, 0, 16); for (unsigned i = 0; i < OW; i++) out[i] = -999.0f; - memcpy(kv, kcp, hist); memcpy(kv + plane, c.vc, hist); /* fresh history (the kernel appends) */ - uint64_t A[9] = { (uintptr_t)qkv, (uintptr_t)kv, (uintptr_t)(kv + plane), (uintptr_t)rope, (uintptr_t)norms, (uintptr_t)(norms + HD), (uintptr_t)out, (uintptr_t)part, (uintptr_t)cnt }; - for (unsigned i = 0; i < 9; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - float fe = EPS, fo = 1.0f, fq = (float)((1.0 / 16.0) * 1.4426950408889634); - memcpy(&s.cbank[OMEGA_DATTN256_ARG_EPS / 4], &fe, 4); memcpy(&s.cbank[OMEGA_DATTN256_ARG_OUT_SCALE / 4], &fo, 4); memcpy(&s.cbank[OMEGA_DATTN256_ARG_QK_SCALE / 4], &fq, 4); - s.cbank[OMEGA_DATTN256_ARG_POS / 4] = pos; s.cbank[OMEGA_DATTN256_ARG_PER_SPLIT / 4] = per_split; s.cbank[OMEGA_DATTN256_ARG_SPLITS / 4] = splits; s.cbank[OMEGA_DATTN256_ARG_KV_STRIDE / 4] = max_pos * OMEGA_DATTN256_ROW_BYTES; - s.nranges = 7; - s.ranges[0].lo = (uintptr_t)qkv; s.ranges[0].hi = (uintptr_t)qkv + sizeof c.qkv; - s.ranges[1].lo = (uintptr_t)kv; s.ranges[1].hi = (uintptr_t)kv + 2 * plane; - s.ranges[2].lo = (uintptr_t)rope; s.ranges[2].hi = (uintptr_t)rope + (size_t)max_pos * OMEGA_DATTN256_ROPE_ROW_BYTES; - s.ranges[3].lo = (uintptr_t)norms; s.ranges[3].hi = (uintptr_t)norms + 2048; - s.ranges[4].lo = (uintptr_t)out; s.ranges[4].hi = (uintptr_t)out + OW * 4; - s.ranges[5].lo = (uintptr_t)part; s.ranges[5].hi = (uintptr_t)part + (size_t)VY * splits * OMEGA_DATTN256_PARTIAL_WORDS * 4; - s.ranges[6].lo = (uintptr_t)cnt; s.ranges[6].hi = (uintptr_t)cnt + 16; - err = ws_run(&s, splits, VY); - if (err) { snprintf(msg, n, "order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (unsigned i = 0; i < OW; i++) if (out[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, n, "%zu output words never written", unwritten); break; } - if (cnt[0] | cnt[1] | cnt[2] | cnt[3]) { err = -1; snprintf(msg, n, "counters not reset: %u %u %u %u", cnt[0], cnt[1], cnt[2], cnt[3]); break; } - if (order == 0) memcpy(copy, out, OW * 4); - else if (memcmp(copy, out, OW * 4) != 0) { err = -1; snprintf(msg, n, "the fragment order changed the result"); } - } - if (!err) { - uint16_t kn[KVH * HD], vn[KVH * HD]; - *bad = parity(&c, out, 1.0f, worst, kn, vn); - uint16_t kchip[KVH * HD], vchip[KVH * HD]; - for (unsigned g = 0; g < KVH; g++) { memcpy(kchip + g * HD, kv + ((size_t)g * max_pos + pos) * OMEGA_DATTN256_ROW_BYTES, OMEGA_DATTN256_ROW_BYTES); memcpy(vchip + g * HD, kv + plane + ((size_t)g * max_pos + pos) * OMEGA_DATTN256_ROW_BYTES, OMEGA_DATTN256_ROW_BYTES); } - if (!rows_ok(kchip, vchip, kn, vn, rotary, rows, rn)) *bad += 1000; - snprintf(msg, n, "bad=%zu worst=%.3f rows: %s", *bad, *worst, rows); - } - free(kv); free(rope); free(norms); free(qkv); free(out); free(copy); free(part); free(cnt); free(kcp); case_free(&c); - return err; -} -static void sim_battery(void) { - char msg[300], rows[160]; double worst; size_t bad; - struct { uint32_t max_pos, pos, rotary, depth, per; float qscale; const char *name; } pts[] = { - { 256, 0, 64, 1, 256, 1.0f, "context 1" }, - { 256, 6, 64, 2, 256, 1.0f, "context 7" }, - { 256, 6, 64, 4, 256, 4.0f, "context 7, sharp q (x4)" }, - { 256, 6, 256, 4, 256, 1.0f, "context 7, full rope (rotary 256)" }, - { 256, 255, 64, 4, 256, 1.0f, "context 256 (full chunk, 1 split)" }, - { 512, 256, 64, 4, 256, 1.0f, "context 257 (2 splits, last holds one position)" }, - { 512, 300, 64, 3, 256, 1.0f, "context 301 (2 splits)" }, - { 1024, 700, 64, 4, 256, 1.0f, "context 701 (3 splits)" }, - { 1024, 700, 64, 2, 512, 1.0f, "context 701 (per_split 512: 2 chunks per CTA)" }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - int err = sim_point(pts[i].max_pos, pts[i].pos, pts[i].rotary, pts[i].depth, 0, pts[i].per, pts[i].qscale, 100 + (uint32_t)i, msg, sizeof msg, &worst, &bad, rows, sizeof rows); - CHECK(err == 0 && bad == 0, "sim %s depth %u: %s", pts[i].name, pts[i].depth, msg); - printf("sim %-50s depth %u: %s %s\n", pts[i].name, pts[i].depth, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - for (int m = 1; m <= 5; m++) { - int err = sim_point(512, 300, 64, 2, m, 256, 1.0f, 200, msg, sizeof msg, &worst, &bad, rows, sizeof rows); - int caught = err != 0 || bad > 0; - CHECK(caught, "sim mutant %d NOT caught (%s)", m, msg); - printf("sim mutant %d at context 301: %s (%s)\n", m, caught ? "caught" : "MISSED", msg); - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static int g_evict = 1; static const char *g_only; static uint32_t g_maxp = 32768; -static void evict_host_caches(void) { - static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass; - if (!buf) buf = malloc(sz); - if (!buf) return; - memset(buf, ++pass, sz); - volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i]; -} -static int fill_history(OmegaGpuDecodeAttn256Cache *cache, const Case *c, const uint16_t *kcp) { - if (c->pos == 0) return OMEGA_GPU_DATTN_OK; - for (unsigned g = 0; g < KVH; g++) { - int rc = omega_gpu_decode_attn256_cache_write(cache, 0, g, 0, c->pos, kcp + (size_t)g * c->max_pos * HD, c->vc + (size_t)g * c->max_pos * HD); - if (rc != OMEGA_GPU_DATTN_OK) return rc; - } - return OMEGA_GPU_DATTN_OK; -} -static int chip_run(const char *out_path, uint32_t reps) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot write %s\n", out_path); return 1; } - if (out) fprintf(out, "{\"receipt\":\"OMEGA_GPU_DECODE_ATTN256_V1\",\"reps\":%u,\"evict\":%d,\"max_pos\":%u,\"rotary_dim\":64,\"points\":[", reps, g_evict, g_maxp); - const uint32_t MAXP = g_maxp; - OmegaGpuDecodeAttn256Cache *cache = NULL; - double t0 = now_ms(); - int rc = omega_gpu_decode_attn256_cache_alloc_shape(1, MAXP, THETA, 64, QH, KVH, QPC, &cache); - printf("cache alloc (1 layer, %u positions, %.0f MiB): rc=%s %.1f ms (%s)\n", MAXP, (double)MAXP * 2 * KVH * 512 / 1048576.0, omega_gpu_decode_attn_rc_name(rc), now_ms() - t0, rc ? omega_gpu_decode_attn_last_error() : ""); - CHECK(rc == OMEGA_GPU_DATTN_OK, "cache alloc"); - if (rc != OMEGA_GPU_DATTN_OK) { if (out) fprintf(out, "],\"verdict\":\"OMEGA_GPU_DECODE_ATTN256_FAIL\"}\n"); return 1; } - struct { uint32_t pos; float qscale; const char *name; } pts[] = { - { 0, 1.0f, "context 1" }, { 6, 1.0f, "context 7" }, { 255, 1.0f, "context 256" }, { 300, 4.0f, "context 301 sharp q" }, - { 1023, 1.0f, "context 1024" }, { 4095, 1.0f, "context 4096" }, { 8191, 1.0f, "context 8192" }, { 32767, 1.0f, "context 32768" }, - { 131071, 1.0f, "context 131072" }, - }; - int first = 1; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - if (pts[i].pos >= MAXP) continue; - if (g_only && !strstr(pts[i].name, g_only)) continue; - Case c; case_make(&c, MAXP, pts[i].pos, 64, 500 + (uint32_t)i, pts[i].qscale); - uint16_t *kcp = case_kc_perm(&c); - float *qkv_k = malloc(QW * 4), qn_k[HD], kn_k[HD]; - case_kernel_inputs(&c, qkv_k, qn_k, kn_k); - CHECK(omega_gpu_decode_attn256_set_norms(cache, 0, qn_k, kn_k) == OMEGA_GPU_DATTN_OK, "set norms"); - t0 = now_ms(); - rc = fill_history(cache, &c, kcp); - double fill_ms = now_ms() - t0; - float *y = malloc(OW * 4), *y2 = malloc(OW * 4); - OmegaGpuDecodeAttn256Info info; memset(&info, 0, sizeof info); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_decode_attn256(cache, 0, c.pos, qkv_k, EPS, 1.0f, y, &info); - size_t bad = 0; double worst = 1e9; uint16_t kn[KVH * HD], vn[KVH * HD], kchip[KVH * HD], vchip[KVH * HD]; char rows[160] = "n/a"; - if (rc == OMEGA_GPU_DATTN_OK) { - bad = parity(&c, y, 1.0f, &worst, kn, vn); - for (unsigned g = 0; g < KVH; g++) if (omega_gpu_decode_attn256_cache_read(cache, 0, g, c.pos, kchip + g * HD, vchip + g * HD) != OMEGA_GPU_DATTN_OK) bad += 1000; - if (!rows_ok(kchip, vchip, kn, vn, 64, rows, sizeof rows)) bad += 1000; - } - int ok = rc == OMEGA_GPU_DATTN_OK && bad == 0; - int same = 0; OmegaGpuDecodeAttn256Info i2; memset(&i2, 0, sizeof i2); - if (ok) { int r2 = omega_gpu_decode_attn256(cache, 0, c.pos, qkv_k, EPS, 1.0f, y2, &i2); same = r2 == OMEGA_GPU_DATTN_OK && memcmp(y, y2, OW * 4) == 0 && i2.kernel_cache_hit; } - CHECK(ok && same, "chip %s: rc=%s bad=%zu worst=%.3f rows=%s second-call-identical=%d (%s)", pts[i].name, omega_gpu_decode_attn_rc_name(rc), bad, worst, rows, same, omega_gpu_decode_attn_last_error()); - if (ok) { - float *ys = malloc(OW * 4); int r3 = omega_gpu_decode_attn256(cache, 0, c.pos, qkv_k, EPS, 18446744073709551616.0f, ys, NULL); - int good = r3 == OMEGA_GPU_DATTN_OK; double wr = 0; - for (unsigned k = 0; k < OW && good; k++) { double e = fabs((double)ys[k] / 18446744073709551616.0 - (double)y[k]); double r = e / (fabs((double)y[k]) + 1e-6); if (r > wr) wr = r; } - CHECK(good && wr < 1e-5, "chip %s: out_scale 2^64 matches the unscaled output (worst rel %.2e)", pts[i].name, wr); - free(ys); - } - uint64_t *el = calloc(reps, sizeof *el), *cl = calloc(reps, sizeof *cl); uint32_t done = 0; - if (g_evict) evict_host_caches(); - for (uint32_t r = 0; r < reps && ok; r++) { OmegaGpuDecodeAttn256Info ti; if (omega_gpu_decode_attn256(cache, 0, c.pos, qkv_k, EPS, 1.0f, y2, &ti) != OMEGA_GPU_DATTN_OK) break; el[r] = ti.elapsed_ns; cl[r] = ti.call_ns; done++; } - uint64_t med_el = 0, med_cl = 0; double gbs = 0; - if (done) { qsort(el, done, sizeof *el, cmp_u64); qsort(cl, done, sizeof *cl, cmp_u64); med_el = el[done / 2]; med_cl = cl[done / 2]; gbs = med_el ? (double)info.kv_bytes / (double)med_el : 0; } - printf("chip %-24s rc=%-9s bad=%zu worst=%.3f rows=%s grid=%ux%u per_split=%u depth=%u kv_bytes=%" PRIu64 " fill=%.1fms chip_med=%.1fus (%.1f GB/s) call_med=%.1fus reps=%u\n", - pts[i].name, omega_gpu_decode_attn_rc_name(rc), bad, worst, rows, info.grid_x, info.grid_y, info.per_split, info.depth, info.kv_bytes, fill_ms, med_el / 1e3, gbs, med_cl / 1e3, done); - if (out) fprintf(out, "%s{\"name\":\"%s\",\"pos\":%u,\"rc\":\"%s\",\"bad\":%zu,\"worst_of_tol\":%.3f,\"rows\":\"%s\",\"second_call_identical\":%d,\"grid_x\":%u,\"grid_y\":%u,\"per_split\":%u,\"depth\":%u," - "\"kv_bytes\":%" PRIu64 ",\"fill_ms\":%.1f,\"chip_median_ns\":%" PRIu64 ",\"gb_per_s\":%.1f,\"call_median_ns\":%" PRIu64 ",\"reps\":%u}", - first ? "" : ",", pts[i].name, c.pos, omega_gpu_decode_attn_rc_name(rc), bad, worst, rows, same, info.grid_x, info.grid_y, info.per_split, info.depth, info.kv_bytes, fill_ms, med_el, gbs, med_cl, done); - first = 0; - free(el); free(cl); - if (ok && c.pos == 300) { - for (int m = 1; m <= 5; m++) { - omega_gpu_decode_attn256_test_set_mutant(m); - (void)fill_history(cache, &c, kcp); /* mutant 3 must not inherit the row the honest kernel wrote */ - uint16_t zk[HD] = { 0 }, zv[HD] = { 0 }; - for (unsigned g = 0; g < KVH; g++) (void)omega_gpu_decode_attn256_cache_write(cache, 0, g, c.pos, 1, zk, zv); - int r = omega_gpu_decode_attn256(cache, 0, c.pos, qkv_k, EPS, 1.0f, y2, NULL); - size_t mb = 0; double mw = 0; uint16_t k2[KVH * HD], v2[KVH * HD]; - if (r == OMEGA_GPU_DATTN_OK) { mb = parity(&c, y2, 1.0f, &mw, k2, v2); } - int caught = r != OMEGA_GPU_DATTN_OK || mb > 0; - if (m == 4 && info.grid_x == 1) { printf("chip %-24s mutant 4: inert (1 split, the combine is not exercised)\n", pts[i].name); omega_gpu_decode_attn256_test_set_mutant(0); continue; } - CHECK(caught, "chip mutant %d NOT caught", m); - printf("chip %-24s mutant %d: %s (rc=%s bad=%zu worst=%.3f)\n", pts[i].name, m, caught ? "caught" : "MISSED", omega_gpu_decode_attn_rc_name(r), mb, mw); - if (out) fprintf(out, ",{\"name\":\"%s mutant %d\",\"caught\":%d,\"rc\":\"%s\",\"bad\":%zu,\"worst_of_tol\":%.3f}", pts[i].name, m, caught, omega_gpu_decode_attn_rc_name(r), mb, mw); - omega_gpu_decode_attn256_test_set_mutant(0); - } - } - free(y); free(y2); free(qkv_k); free(kcp); case_free(&c); - if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); break; } - } - omega_gpu_decode_attn256_cache_free(cache); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"device_opens\":%u,\"verdict\":\"%s\"}\n", g_checks, g_failed, omega_gpu_session_open_count(), g_failed == 0 ? "OMEGA_GPU_DECODE_ATTN256_PASS" : "OMEGA_GPU_DECODE_ATTN256_FAIL"); fclose(out); } - return 0; -} - -/* --q-heads Q --kv-heads K --head-dim D: any geometry other than 24 / 4 / 256 is REFUSED (receipt verdict "REFUSED", exit 3). */ -static int geometry_refusal(uint32_t qh, uint32_t kvh, uint32_t hd, const char *out_path) { - if (qh == QH && kvh == KVH && hd == HD) return 0; - printf("REFUSED: decode attention 256 at %u query / %u KV heads, head dim %u (built for %u / %u / %u)\n", qh, kvh, hd, QH, KVH, HD); - if (out_path) { FILE *f = fopen(out_path, "w"); if (f) { fprintf(f, "{\"test\":\"gpu_decode_attn256_test\",\"q_heads\":%u,\"kv_heads\":%u,\"head_dim\":%u,\"verdict\":\"REFUSED\"}\n", qh, kvh, hd); fclose(f); } } - return 3; -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; const char *out_path = NULL; uint32_t reps = 20, depth = 0, per = 0, spin = 2000; int sim_pos = -1; uint32_t sim_max = 256; - uint32_t q_heads = QH, kv_heads = KVH, head_dim = HD; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--depth") == 0 && i + 1 < argc) depth = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--per-split") == 0 && i + 1 < argc) per = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0; - else if (strcmp(argv[i], "--sim-pos") == 0 && i + 1 < argc) sim_pos = atoi(argv[++i]); - else if (strcmp(argv[i], "--sim-max") == 0 && i + 1 < argc) sim_max = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--only") == 0 && i + 1 < argc) g_only = argv[++i]; - else if (strcmp(argv[i], "--max-pos") == 0 && i + 1 < argc) g_maxp = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--q-heads") == 0 && i + 1 < argc) q_heads = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--kv-heads") == 0 && i + 1 < argc) kv_heads = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--head-dim") == 0 && i + 1 < argc) head_dim = (uint32_t)atoi(argv[++i]); - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - { int g = geometry_refusal(q_heads, kv_heads, head_dim, out_path); if (g) return g; } - if (host) host_only(); - if (sim && sim_pos >= 0 && sim_max <= (uint32_t)sim_pos) sim_max = (uint32_t)sim_pos + 1u; - if (sim && sim_pos >= 0) { char msg[300], rows[160]; double worst; size_t bad; int err = sim_point(sim_max, (uint32_t)sim_pos, 64, depth ? depth : 2, 0, per ? per : 256, 1.0f, 777, msg, sizeof msg, &worst, &bad, rows, sizeof rows); printf("sim pos %d: %s %s\n", sim_pos, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); return err || bad; } - if (sim) sim_battery(); - if (!host && !sim) { - if (depth) omega_gpu_decode_attn256_set_depth(depth); - if (per) omega_gpu_decode_attn256_set_per_split(per); - (void)omega_gpu_session_set_spin_us(spin); - chip_run(out_path, reps ? reps : 1); - omega_gpu_session_close(); - } - printf("gpu_decode_attn256_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_decode_attn_test.c b/tests/gpu_decode_attn_test.c deleted file mode 100644 index ff35e2a03..000000000 --- a/tests/gpu_decode_attn_test.c +++ /dev/null @@ -1,482 +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. - */ - -/* - * gpu_decode_attn_test: the one-launch decode attention (OWN-30B cut 8, omega_gpu_decode_attn_api.h). - * --host-only host pieces: bf16 rounding, RoPE row, reference sanity (context 1 returns v_new, a one-hot - * key wins), codegen budget per depth and mutant, refusals. No device. - * --sim the kernel through tests/bw_warp_sim_k.h (no chip): contexts 1, 7, 256, 257, 301, 701 (1..3 - * splits, the cross-split combine), both fragment orders, every mutant caught at context 301. - * (default) the chip: parity against the double reference at contexts 1, 7, 256, 1024, 4096, 8192, 32768, 65536, 100000, 131072 - * (the appended K/V row read back and compared), second call identical, timing medians with - * the host caches evicted, every mutant caught at context 301, JSON receipt with --out. - * Tolerance: |out - ref| <= 3e-3 * max|v| + 1e-6 per element (MUFU.EX2 / RSQ are 2^-22-ish, bf16 rounding of the - * appended K/V can flip one ulp against the f32 chip path). The mutants miss by 0.1 .. 1.0 of that scale. - * --q-heads Q --kv-heads K --head-dim D: any geometry other than 32 / 4 / 128 is REFUSED with reasons (exit 3, receipt - * verdict "REFUSED"); e.g. the BitNet b1.58 layout 20 / 5 / 128 (ternary engine T0). - * Host and simulator passes are never chip results. - */ -#include "omega_gpu_decode_attn_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_hostmath.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static const double THETA = 10000000.0; /* config.json rope_theta */ -static const float EPS = 1e-6f; - -/* one layer's random state: qkv, history rows (bf16) for 4 KV heads, norms */ -typedef struct { - uint32_t max_pos, pos; - float qkv[OMEGA_GPU_DATTN_QKV_WORDS], qn[128], kn[128]; - uint16_t *kc, *vc; /* [4][max_pos][128] (history 0..pos-1 filled; the rest zero) */ - float vmax; -} Case; -static void case_make(Case *c, uint32_t max_pos, uint32_t pos, uint32_t seed, float qscale) { - uint32_t s = seed; - c->max_pos = max_pos; c->pos = pos; - for (size_t i = 0; i < OMEGA_GPU_DATTN_QKV_WORDS; i++) c->qkv[i] = frand(&s, -1.0f, 1.0f) * (i < 4096 ? qscale : 1.0f); - for (unsigned i = 0; i < 128; i++) { c->qn[i] = frand(&s, 0.8f, 1.2f); c->kn[i] = frand(&s, 0.8f, 1.2f); } - size_t words = (size_t)4 * max_pos * 128; - c->kc = calloc(words, 2); c->vc = calloc(words, 2); - c->vmax = 1.0f; - for (unsigned g = 0; g < 4; g++) for (uint32_t t = 0; t < pos; t++) for (unsigned i = 0; i < 128; i++) { - size_t o = ((size_t)g * max_pos + t) * 128 + i; - c->kc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); c->vc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); - } -} -static void case_free(Case *c) { free(c->kc); free(c->vc); } - -/* ---- double-precision oracle (test-owned: it uses libm, which the library does not link) ---- - * RMSNorm + RoPE of one head (double), in place; cs: cos[64], sn: sin[64] */ -static void norm_rope(double *x, const float *w, float eps, const double *cs, const double *sn, int rope) { - double ss = 0; for (unsigned i = 0; i < 128; i++) ss += x[i] * x[i]; - double r = 1.0 / sqrt(ss / 128.0 + (double)eps); - for (unsigned i = 0; i < 128; i++) x[i] = x[i] * r * (double)w[i]; - if (!rope) return; - double y[128]; - for (unsigned i = 0; i < 64; i++) { y[i] = x[i] * cs[i] - x[i + 64] * sn[i]; y[i + 64] = x[i + 64] * cs[i] + x[i] * sn[i]; } - memcpy(x, y, sizeof y); -} -/* Reference of the whole layer step. kc/vc: this layer's bf16 planes [4][max_pos][128] holding positions 0..pos-1; - * out: [32*128] doubles (already * out_scale); k_new/v_new: the bf16 rows the kernel must have appended at pos - * ([4][128] each). The reference rounds its k_new/v_new to bf16 and attends over the rounded values. */ -static void omega_decode_attn_reference(const float *qkv, const uint16_t *kc, const uint16_t *vc, uint32_t max_pos, uint32_t pos, - const float *q_norm, const float *k_norm, float eps, double rope_theta, float out_scale, - double *out, uint16_t *k_new, uint16_t *v_new) { - double cs[64], sn[64]; - for (unsigned i = 0; i < 64; i++) { double ang = (double)pos * pow(rope_theta, -(double)(2 * i) / 128.0); cs[i] = cos(ang); sn[i] = sin(ang); } - const double qscale = 1.0 / sqrt(128.0); - for (unsigned gk = 0; gk < 4; gk++) { - double k[128]; - for (unsigned i = 0; i < 128; i++) k[i] = qkv[4096 + gk * 128 + i]; - norm_rope(k, k_norm, eps, cs, sn, 1); - for (unsigned i = 0; i < 128; i++) { k_new[gk * 128 + i] = omega_dattn_bf16_rne((float)k[i]); v_new[gk * 128 + i] = omega_dattn_bf16_rne(qkv[4096 + 512 + gk * 128 + i]); } - } - double *p = calloc((size_t)pos + 1, sizeof(double)); - for (unsigned h = 0; h < 32; h++) { - unsigned gk = h / 8; - double q[128]; - for (unsigned i = 0; i < 128; i++) q[i] = qkv[h * 128 + i]; - norm_rope(q, q_norm, eps, cs, sn, 1); - double mx = -1e300; - for (uint32_t t = 0; t <= pos; t++) { - const uint16_t *kr = t == pos ? k_new + gk * 128 : kc + ((size_t)gk * max_pos + t) * 128; - double s = 0; for (unsigned i = 0; i < 128; i++) s += q[i] * (double)omega_dattn_bf16_f32(kr[i]); - s *= qscale; p[t] = s; if (s > mx) mx = s; - } - double l = 0; for (uint32_t t = 0; t <= pos; t++) { p[t] = exp(p[t] - mx); l += p[t]; } - double o[128]; memset(o, 0, sizeof o); - for (uint32_t t = 0; t <= pos; t++) { - const uint16_t *vr = t == pos ? v_new + gk * 128 : vc + ((size_t)gk * max_pos + t) * 128; - for (unsigned i = 0; i < 128; i++) o[i] += p[t] * (double)omega_dattn_bf16_f32(vr[i]); - } - for (unsigned i = 0; i < 128; i++) out[h * 128 + i] = o[i] / l * (double)out_scale; - } - free(p); -} - -/* the library's libm-free host math against libm: RoPE rows bit-equal or within one f32 ulp, double values close */ -static void host_math_vs_libm(void) { - uint32_t s = 77; unsigned flips = 0, worse = 0; double maxd = 0; - static const uint32_t fixed[] = { 0, 1, 2, 3, 100, 255, 256, 4095, 4096, 8191, 32767, 32768, 65535, 65536, 99999, 131071 }; - for (unsigned n = 0; n < 1000 + sizeof fixed / sizeof fixed[0]; n++) { - uint32_t pos = n < sizeof fixed / sizeof fixed[0] ? fixed[n] : lcg(&s) % OMEGA_GPU_DATTN_MAX_POS; - float row[128]; omega_dattn_rope_row(pos, THETA, row); - for (unsigned i = 0; i < 64; i++) { - double ang = (double)pos * pow(THETA, -(double)(2 * i) / 128.0); - float c = (float)cos(ang), sn = (float)sin(ang); - uint32_t a, b; memcpy(&a, &row[i], 4); memcpy(&b, &c, 4); - int dc = (int)a - (int)b; memcpy(&a, &row[64 + i], 4); memcpy(&b, &sn, 4); int ds = (int)a - (int)b; - if (dc < -1 || dc > 1 || ds < -1 || ds > 1) worse++; else if (dc || ds) flips++; - } - } - CHECK(worse == 0, "rope rows vs libm: %u entries differ by more than one f32 ulp", worse); - printf("rope rows vs libm: 1013 positions x 64 dims, %u one-ulp differences, %u worse\n", flips, worse); - for (unsigned n = 0; n < 200000; n++) { - double a = ((double)(lcg(&s) % 2000001u) - 1000000.0) * (n & 1 ? 1.0 : 1e-6), hs, hc; - omega_hostmath_sincos(a, &hs, &hc); - double d = fabs(hs - sin(a)); if (d > maxd) maxd = d; d = fabs(hc - cos(a)); if (d > maxd) maxd = d; - } - CHECK(maxd < 1e-14, "hostmath sincos vs libm over |a| <= 1e6: max abs diff %.3g", maxd); - double maxr = 0; - for (unsigned n = 0; n < 200000; n++) { - double b = 1e-6 + (double)(lcg(&s) % 100000000u) * 1e-1, e = ((double)(lcg(&s) % 20001u) - 10000.0) / 10000.0 * 4.0; - double h = omega_hostmath_pow(b, e), l = pow(b, e), r = fabs(h - l) / l; if (r > maxr) maxr = r; - h = omega_hostmath_exp(e * 20.0); l = exp(e * 20.0); r = fabs(h - l) / l; if (r > maxr) maxr = r; - h = omega_hostmath_log(b); l = log(b); r = fabs(h - l) / (1.0 + fabs(l)); if (r > maxr) maxr = r; - } - CHECK(maxr < 1e-13, "hostmath pow/exp/log vs libm: max rel diff %.3g", maxr); - printf("hostmath vs libm: sincos max abs %.3g, pow/exp/log max rel %.3g\n", maxd, maxr); - CHECK(omega_hostmath_exp(0.0) == 1.0 && omega_hostmath_log(1.0) == 0.0 && omega_hostmath_pow(THETA, 0.0) == 1.0, "hostmath identities"); - CHECK(omega_hostmath_log(-1.0) != omega_hostmath_log(-1.0) && omega_hostmath_exp(-800.0) == 0.0, "hostmath log(-1) is NaN, exp(-800) is 0"); - /* omega-mv#471: pow2f replaces ldexpf(1.0f, e) in libomega_gpu.a; bit-identical over the whole f32 range and past both ends */ - unsigned pow2_bad = 0; - for (int e = -170; e <= 150; e++) { - float h = omega_hostmath_pow2f(e), l = ldexpf(1.0f, e); - if (memcmp(&h, &l, sizeof h) != 0) { pow2_bad++; printf(" pow2f(%d) = %a, ldexpf = %a\n", e, (double)h, (double)l); } - } - CHECK(pow2_bad == 0, "hostmath pow2f vs ldexpf(1, e) for e in [-170, 150]: %u differ", pow2_bad); -} - -/* compares out (f32 [4096]) against the reference; returns the number of elements outside the tolerance and the worst ratio */ -static size_t parity(const Case *c, const float *out, float out_scale, double *worst, uint16_t *k_new, uint16_t *v_new) { - double *ref = malloc(4096 * sizeof(double)); - omega_decode_attn_reference(c->qkv, c->kc, c->vc, c->max_pos, c->pos, c->qn, c->kn, EPS, THETA, out_scale, ref, k_new, v_new); - double tol = 3e-3 * c->vmax * out_scale + 1e-6 * out_scale; size_t bad = 0; *worst = 0; - for (size_t i = 0; i < 4096; i++) { double d = fabs((double)out[i] - ref[i]); if (d / tol > *worst) *worst = d / tol; if (d > tol) bad++; } - free(ref); - return bad; -} -/* appended rows: v exact, k within one bf16 ulp on at most 4 elements per head */ -static int rows_ok(const uint16_t *k_chip, const uint16_t *v_chip, const uint16_t *k_ref, const uint16_t *v_ref, char *why, size_t n) { - unsigned kflips = 0; - for (unsigned i = 0; i < 512; i++) { - if (v_chip[i] != v_ref[i]) { snprintf(why, n, "v[%u] chip %04x ref %04x", i, v_chip[i], v_ref[i]); return 0; } - if (k_chip[i] != k_ref[i]) { int d = (int)k_chip[i] - (int)k_ref[i]; if (d < -1 || d > 1) { snprintf(why, n, "k[%u] chip %04x ref %04x", i, k_chip[i], k_ref[i]); return 0; } kflips++; } - } - if (kflips > 16) { snprintf(why, n, "%u one-ulp k flips", kflips); return 0; } - snprintf(why, n, "ok (%u one-ulp k flips)", kflips); - return 1; -} - -/* ------------------------------------------------------------- host only */ -static void host_only(void) { - CHECK(omega_dattn_bf16_rne(1.0f) == 0x3f80, "bf16 of 1.0"); - CHECK(omega_dattn_bf16_rne(1.00390625f) == 0x3f80, "bf16 rounds 1 + 2^-8 to even (down)"); - CHECK(omega_dattn_bf16_rne(1.01171875f) == 0x3f82, "bf16 rounds 1 + 3 * 2^-8 to even (up)"); - CHECK(omega_dattn_bf16_rne(-2.5f) == 0xc020, "bf16 of -2.5"); - float row[128]; omega_dattn_rope_row(0, THETA, row); - int ok = 1; for (unsigned i = 0; i < 64; i++) ok &= row[i] == 1.0f && row[64 + i] == 0.0f; - CHECK(ok, "rope row 0 is cos 1 sin 0"); - omega_dattn_rope_row(100, THETA, row); - CHECK(fabs((double)row[0] - cos(100.0)) < 1e-6 && fabs((double)row[64] - sin(100.0)) < 1e-6, "rope row 100 dim 0 is cos/sin(100)"); - CHECK(fabs((double)row[63] - cos(100.0 * pow(THETA, -126.0 / 128.0))) < 1e-6, "rope row 100 dim 63 uses theta^(-126/128)"); - host_math_vs_libm(); - /* reference sanity: context 1 returns v_new (rounded), whatever q and k */ - { Case c; case_make(&c, 256, 0, 11, 1.0f); double *ref = malloc(4096 * sizeof(double)); uint16_t kn[512], vn[512]; - omega_decode_attn_reference(c.qkv, c.kc, c.vc, 256, 0, c.qn, c.kn, EPS, THETA, 1.0f, ref, kn, vn); - int good = 1; for (unsigned h = 0; h < 32 && good; h++) for (unsigned i = 0; i < 128; i++) if (ref[h * 128 + i] != (double)omega_dattn_bf16_f32(vn[(h / 8) * 128 + i])) { good = 0; break; } - CHECK(good, "reference: context 1 returns the rounded v_new of the head's KV group"); - /* a dominant key: history row 3 equal to the roped-normed q direction of head 0 scaled up -> output ~ v row 3 */ - free(ref); case_free(&c); } - { Case c; case_make(&c, 256, 8, 12, 1.0f); - double *ref = malloc(4096 * sizeof(double)); uint16_t kn[512], vn[512]; - omega_decode_attn_reference(c.qkv, c.kc, c.vc, 256, 8, c.qn, c.kn, EPS, THETA, 1.0f, ref, kn, vn); - /* k_new is unit-rms-ish: rms of the k_norm-weighted row around 1 */ - double ss = 0; for (unsigned i = 0; i < 128; i++) { double v = omega_dattn_bf16_f32(kn[i]); ss += v * v; } - CHECK(ss / 128.0 > 0.6 && ss / 128.0 < 1.5, "reference: k_new has rms about 1 after RMSNorm (%.3f)", ss / 128.0); - double os = 0; for (unsigned i = 0; i < 4096; i++) os += fabs(ref[i]); - CHECK(os / 4096.0 < 0.6, "reference: a 9-token softmax average of U(-1,1) rows is small (%.3f)", os / 4096.0); - free(ref); case_free(&c); } - /* codegen budget */ - for (uint32_t d = 1; d <= 4; d++) for (int m = 0; m <= 4; m++) { - OmegaDecodeAttnSpec s = { d, m }; uint32_t n = 0, gp = 0; - int rc = omega_decode_attn_prog_stats(&s, &n, &gp); - CHECK(rc == 0 && n <= 1024 && gp <= 128, "codegen depth %u mutant %d: rc %d insns %u gprs %u", d, m, rc, n, gp); - if (rc == 0 && m == 0) printf("codegen depth %u: %u instructions, %u registers (declared %u, 256 threads -> %u of 65536)\n", d, n, gp, ((gp + 8) / 8) * 8, 256 * ((gp + 8) / 8) * 8); - } - { OmegaDecodeAttnSpec s = { 0, 0 }; CHECK(omega_decode_attn_prog_stats(&s, NULL, NULL) != 0, "depth 0 refused"); - s.depth = 5; CHECK(omega_decode_attn_prog_stats(&s, NULL, NULL) != 0, "depth 5 refused"); - s.depth = 1; s.mutant = 5; CHECK(omega_decode_attn_prog_stats(&s, NULL, NULL) != 0, "mutant 5 refused"); } - CHECK(omega_gpu_decode_attn_cache_alloc(0, 256, THETA, NULL) == OMEGA_GPU_DATTN_BAD_ARGS, "NULL out refused"); - { OmegaGpuDecodeAttnCache *c = (OmegaGpuDecodeAttnCache *)1; - CHECK(omega_gpu_decode_attn_cache_alloc(1, 100, THETA, &c) == OMEGA_GPU_DATTN_BAD_ARGS && c == NULL, "max_pos not a multiple of 256 refused before any device work"); - c = (OmegaGpuDecodeAttnCache *)1; - CHECK(omega_gpu_decode_attn_cache_alloc(1, OMEGA_GPU_DATTN_MAX_POS + 256u, THETA, &c) == OMEGA_GPU_DATTN_BAD_ARGS && c == NULL, "max_pos above OMEGA_GPU_DATTN_MAX_POS refused before any device work"); } - CHECK(OMEGA_DATTN_SHARED_BYTES <= 16384u, "shared memory within the QMD cap (%u)", OMEGA_DATTN_SHARED_BYTES); -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -static int sim_point(uint32_t max_pos, uint32_t pos, uint32_t depth, int mutant, uint32_t per_split, float qscale, uint32_t seed, char *msg, size_t n, double *worst, size_t *bad, char *rows, size_t rn) { - static BlackwellIRProgram prog; - OmegaDecodeAttnSpec spec = { depth, mutant }; - if (omega_blackwell_codegen_decode_attn_prog(&spec, &prog) != 0) { snprintf(msg, n, "codegen refused"); return -1; } - Case c; case_make(&c, max_pos, pos, seed, qscale); - const uint32_t splits = (pos + per_split) / per_split; - size_t plane = (size_t)4 * max_pos * 256 + OMEGA_DATTN_PLANE_SLACK; - uint8_t *kv = aligned_alloc(16, 2 * plane); memset(kv, 0, 2 * plane); - memcpy(kv, c.kc, (size_t)4 * max_pos * 256); memcpy(kv + plane, c.vc, (size_t)4 * max_pos * 256); - float *rope = aligned_alloc(16, (size_t)max_pos * 512); for (uint32_t p = 0; p < max_pos; p++) omega_dattn_rope_row(p, THETA, rope + (size_t)p * 128); - float *norms = aligned_alloc(16, 1024); memcpy(norms, c.qn, 512); memcpy(norms + 128, c.kn, 512); - float *qkv = aligned_alloc(16, sizeof c.qkv); memcpy(qkv, c.qkv, sizeof c.qkv); - float *out = aligned_alloc(16, 4096 * 4), *copy = malloc(4096 * 4); - float *part = aligned_alloc(16, (size_t)4 * splits * OMEGA_DATTN_PARTIAL_WORDS * 4); - uint32_t *cnt = aligned_alloc(16, 16); - int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 256; s.order = order; - static uint8_t smem[OMEGA_DATTN_SHARED_BYTES]; s.smem = smem; s.smem_bytes = OMEGA_DATTN_SHARED_BYTES; - memset(cnt, 0, 16); for (unsigned i = 0; i < 4096; i++) out[i] = -999.0f; - memcpy(kv, c.kc, (size_t)4 * max_pos * 256); memcpy(kv + plane, c.vc, (size_t)4 * max_pos * 256); /* fresh history (the kernel appends) */ - uint64_t A[9] = { (uintptr_t)qkv, (uintptr_t)kv, (uintptr_t)(kv + plane), (uintptr_t)rope, (uintptr_t)norms, (uintptr_t)(norms + 128), (uintptr_t)out, (uintptr_t)part, (uintptr_t)cnt }; - for (unsigned i = 0; i < 9; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - float fe = EPS, fo = 1.0f, fq = (float)((1.0 / sqrt(128.0)) * 1.4426950408889634); - memcpy(&s.cbank[OMEGA_DATTN_ARG_EPS / 4], &fe, 4); memcpy(&s.cbank[OMEGA_DATTN_ARG_OUT_SCALE / 4], &fo, 4); memcpy(&s.cbank[OMEGA_DATTN_ARG_QK_SCALE / 4], &fq, 4); - s.cbank[OMEGA_DATTN_ARG_POS / 4] = pos; s.cbank[OMEGA_DATTN_ARG_PER_SPLIT / 4] = per_split; s.cbank[OMEGA_DATTN_ARG_SPLITS / 4] = splits; s.cbank[OMEGA_DATTN_ARG_KV_STRIDE / 4] = max_pos * 256; - s.nranges = 7; - s.ranges[0].lo = (uintptr_t)qkv; s.ranges[0].hi = (uintptr_t)qkv + sizeof c.qkv; - s.ranges[1].lo = (uintptr_t)kv; s.ranges[1].hi = (uintptr_t)kv + 2 * plane; - s.ranges[2].lo = (uintptr_t)rope; s.ranges[2].hi = (uintptr_t)rope + (size_t)max_pos * 512; - s.ranges[3].lo = (uintptr_t)norms; s.ranges[3].hi = (uintptr_t)norms + 1024; - s.ranges[4].lo = (uintptr_t)out; s.ranges[4].hi = (uintptr_t)out + 4096 * 4; - s.ranges[5].lo = (uintptr_t)part; s.ranges[5].hi = (uintptr_t)part + (size_t)4 * splits * OMEGA_DATTN_PARTIAL_WORDS * 4; - s.ranges[6].lo = (uintptr_t)cnt; s.ranges[6].hi = (uintptr_t)cnt + 16; - err = ws_run(&s, splits, 4); - if (err) { snprintf(msg, n, "order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (unsigned i = 0; i < 4096; i++) if (out[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, n, "%zu output words never written", unwritten); break; } - if (cnt[0] | cnt[1] | cnt[2] | cnt[3]) { err = -1; snprintf(msg, n, "counters not reset: %u %u %u %u", cnt[0], cnt[1], cnt[2], cnt[3]); break; } - if (order == 0) memcpy(copy, out, 4096 * 4); - else if (memcmp(copy, out, 4096 * 4) != 0) { err = -1; snprintf(msg, n, "the fragment order changed the result"); } - } - if (!err) { - uint16_t kn[512], vn[512]; - *bad = parity(&c, out, 1.0f, worst, kn, vn); - uint16_t kchip[512], vchip[512]; - for (unsigned g = 0; g < 4; g++) { memcpy(kchip + g * 128, kv + ((size_t)g * max_pos + pos) * 256, 256); memcpy(vchip + g * 128, kv + plane + ((size_t)g * max_pos + pos) * 256, 256); } - if (!rows_ok(kchip, vchip, kn, vn, rows, rn)) *bad += 1000; - if (getenv("DATTN_DUMP")) { for (int dr = -1; dr <= 1; dr++) { if ((int)pos + dr < 0) continue; const uint16_t *r = (const uint16_t *)(kv + plane + ((size_t)0 * max_pos + pos + dr) * 256); printf(" v row %d:", (int)pos + dr); for (unsigned i = 0; i < 12; i++) printf(" %04x", r[i]); printf(" ... ref:"); for (unsigned i = 0; i < 12; i++) printf(" %04x", vn[i]); printf("\n"); } - const uint16_t *r = (const uint16_t *)(kv + ((size_t)0 * max_pos + pos) * 256); printf(" k row %u:", pos); for (unsigned i = 0; i < 12; i++) printf(" %04x", r[i]); printf(" ... ref:"); for (unsigned i = 0; i < 12; i++) printf(" %04x", kn[i]); printf("\n"); } - snprintf(msg, n, "bad=%zu worst=%.3f rows: %s", *bad, *worst, rows); - } - free(kv); free(rope); free(norms); free(qkv); free(out); free(copy); free(part); free(cnt); case_free(&c); - return err; -} -static void sim_battery(void) { - char msg[300], rows[120]; double worst; size_t bad; - struct { uint32_t max_pos, pos, depth, per; float qscale; const char *name; } pts[] = { - { 256, 0, 1, 256, 1.0f, "context 1" }, - { 256, 6, 2, 256, 1.0f, "context 7" }, - { 256, 6, 4, 256, 4.0f, "context 7, sharp q (x4)" }, - { 256, 255, 4, 256, 1.0f, "context 256 (full chunk, 1 split)" }, - { 512, 256, 4, 256, 1.0f, "context 257 (2 splits, last holds one position)" }, - { 512, 300, 3, 256, 1.0f, "context 301 (2 splits)" }, - { 1024, 700, 4, 256, 1.0f, "context 701 (3 splits)" }, - { 1024, 700, 2, 512, 1.0f, "context 701 (per_split 512: 2 chunks per CTA)" }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - int err = sim_point(pts[i].max_pos, pts[i].pos, pts[i].depth, 0, pts[i].per, pts[i].qscale, 100 + (uint32_t)i, msg, sizeof msg, &worst, &bad, rows, sizeof rows); - CHECK(err == 0 && bad == 0, "sim %s depth %u: %s", pts[i].name, pts[i].depth, msg); - printf("sim %-50s depth %u: %s %s\n", pts[i].name, pts[i].depth, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - for (int m = 1; m <= 4; m++) { - int err = sim_point(512, 300, 2, m, 256, 1.0f, 200, msg, sizeof msg, &worst, &bad, rows, sizeof rows); - int caught = err != 0 || bad > 0; - CHECK(caught, "sim mutant %d NOT caught (%s)", m, msg); - printf("sim mutant %d at context 301: %s (%s)\n", m, caught ? "caught" : "MISSED", msg); - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static int g_evict = 1; static const char *g_only; -static void evict_host_caches(void) { - static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass; - if (!buf) buf = malloc(sz); - if (!buf) return; - memset(buf, ++pass, sz); - volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i]; -} -static int fill_history(OmegaGpuDecodeAttnCache *cache, const Case *c) { - if (c->pos == 0) return OMEGA_GPU_DATTN_OK; - for (unsigned g = 0; g < 4; g++) { - int rc = omega_gpu_decode_attn_cache_write(cache, 0, g, 0, c->pos, c->kc + (size_t)g * c->max_pos * 128, c->vc + (size_t)g * c->max_pos * 128); - if (rc != OMEGA_GPU_DATTN_OK) return rc; - } - return OMEGA_GPU_DATTN_OK; -} -static int chip_run(const char *out_path, uint32_t reps) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot write %s\n", out_path); return 1; } - if (out) fprintf(out, "{\"receipt\":\"OMEGA_GPU_DECODE_ATTN_V1\",\"reps\":%u,\"evict\":%d,\"points\":[", reps, g_evict); - const uint32_t MAXP = OMEGA_GPU_DATTN_MAX_POS; - OmegaGpuDecodeAttnCache *cache = NULL; - double t0 = now_ms(); - int rc = omega_gpu_decode_attn_cache_alloc(1, MAXP, THETA, &cache); - printf("cache alloc (1 layer, %u positions): rc=%s %.1f ms (%s)\n", MAXP, omega_gpu_decode_attn_rc_name(rc), now_ms() - t0, rc ? omega_gpu_decode_attn_last_error() : ""); - CHECK(rc == OMEGA_GPU_DATTN_OK, "cache alloc"); - if (rc != OMEGA_GPU_DATTN_OK) { if (out) fprintf(out, "],\"verdict\":\"FAIL\"}\n"); return 1; } - struct { uint32_t pos; float qscale; const char *name; } pts[] = { - { 0, 1.0f, "context 1" }, { 6, 1.0f, "context 7" }, { 255, 1.0f, "context 256" }, { 300, 4.0f, "context 301 sharp q" }, - { 1023, 1.0f, "context 1024" }, { 4095, 1.0f, "context 4096" }, { 8191, 1.0f, "context 8192" }, { 32767, 1.0f, "context 32768" }, - { 65535, 1.0f, "context 65536 (old cap)" }, { 99999, 1.0f, "context 100000" }, { 131071, 1.0f, "context 131072 (cap)" }, - }; - int first = 1; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - if (g_only && !strstr(pts[i].name, g_only)) continue; - Case c; case_make(&c, MAXP, pts[i].pos, 500 + (uint32_t)i, pts[i].qscale); - CHECK(omega_gpu_decode_attn_set_norms(cache, 0, c.qn, c.kn) == OMEGA_GPU_DATTN_OK, "set norms"); - t0 = now_ms(); - rc = fill_history(cache, &c); - double fill_ms = now_ms() - t0; - float *y = malloc(4096 * 4), *y2 = malloc(4096 * 4); - OmegaGpuDecodeAttnInfo info; memset(&info, 0, sizeof info); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_decode_attn(cache, 0, c.pos, c.qkv, EPS, 1.0f, y, &info); - size_t bad = 0; double worst = 1e9; uint16_t kn[512], vn[512], kchip[512], vchip[512]; char rows[120] = "n/a"; - if (rc == OMEGA_GPU_DATTN_OK) { - bad = parity(&c, y, 1.0f, &worst, kn, vn); - for (unsigned g = 0; g < 4; g++) if (omega_gpu_decode_attn_cache_read(cache, 0, g, c.pos, kchip + g * 128, vchip + g * 128) != OMEGA_GPU_DATTN_OK) bad += 1000; - if (!rows_ok(kchip, vchip, kn, vn, rows, sizeof rows)) bad += 1000; - } - int ok = rc == OMEGA_GPU_DATTN_OK && bad == 0; - int same = 0; OmegaGpuDecodeAttnInfo i2; memset(&i2, 0, sizeof i2); - if (ok) { int r2 = omega_gpu_decode_attn(cache, 0, c.pos, c.qkv, EPS, 1.0f, y2, &i2); same = r2 == OMEGA_GPU_DATTN_OK && memcmp(y, y2, 4096 * 4) == 0 && i2.kernel_cache_hit; } - CHECK(ok && same, "chip %s: rc=%s bad=%zu worst=%.3f rows=%s second-call-identical=%d (%s)", pts[i].name, omega_gpu_decode_attn_rc_name(rc), bad, worst, rows, same, omega_gpu_decode_attn_last_error()); - /* the out_scale path (2^64 for the FP8 x' row): bit-exact scaling is not required, a relative check is */ - if (ok) { - float *ys = malloc(4096 * 4); int r3 = omega_gpu_decode_attn(cache, 0, c.pos, c.qkv, EPS, 18446744073709551616.0f, ys, NULL); - int good = r3 == OMEGA_GPU_DATTN_OK; double wr = 0; - for (unsigned k = 0; k < 4096 && good; k++) { double e = fabs((double)ys[k] / 18446744073709551616.0 - (double)y[k]); double r = e / (fabs((double)y[k]) + 1e-6); if (r > wr) wr = r; } - CHECK(good && wr < 1e-5, "chip %s: out_scale 2^64 matches the unscaled output (worst rel %.2e)", pts[i].name, wr); - free(ys); - } - uint64_t *el = calloc(reps, sizeof *el), *cl = calloc(reps, sizeof *cl); uint32_t done = 0; - if (g_evict) evict_host_caches(); - for (uint32_t r = 0; r < reps && ok; r++) { OmegaGpuDecodeAttnInfo ti; if (omega_gpu_decode_attn(cache, 0, c.pos, c.qkv, EPS, 1.0f, y2, &ti) != OMEGA_GPU_DATTN_OK) break; el[r] = ti.elapsed_ns; cl[r] = ti.call_ns; done++; } - uint64_t med_el = 0, med_cl = 0; double gbs = 0; - if (done) { qsort(el, done, sizeof *el, cmp_u64); qsort(cl, done, sizeof *cl, cmp_u64); med_el = el[done / 2]; med_cl = cl[done / 2]; gbs = med_el ? (double)info.kv_bytes / (double)med_el : 0; } - printf("chip %-24s rc=%-9s bad=%zu worst=%.3f rows=%s grid=%ux%u per_split=%u depth=%u kv_bytes=%" PRIu64 " fill=%.1fms chip_med=%.1fus (%.1f GB/s) call_med=%.1fus reps=%u\n", - pts[i].name, omega_gpu_decode_attn_rc_name(rc), bad, worst, rows, info.grid_x, info.grid_y, info.per_split, info.depth, info.kv_bytes, fill_ms, med_el / 1e3, gbs, med_cl / 1e3, done); - if (out) fprintf(out, "%s{\"name\":\"%s\",\"pos\":%u,\"rc\":\"%s\",\"bad\":%zu,\"worst_of_tol\":%.3f,\"rows\":\"%s\",\"second_call_identical\":%d,\"grid_x\":%u,\"grid_y\":%u,\"per_split\":%u,\"depth\":%u," - "\"kv_bytes\":%" PRIu64 ",\"fill_ms\":%.1f,\"chip_median_ns\":%" PRIu64 ",\"gb_per_s\":%.1f,\"call_median_ns\":%" PRIu64 ",\"reps\":%u}", - first ? "" : ",", pts[i].name, c.pos, omega_gpu_decode_attn_rc_name(rc), bad, worst, rows, same, info.grid_x, info.grid_y, info.per_split, info.depth, info.kv_bytes, fill_ms, med_el, gbs, med_cl, done); - first = 0; - free(el); free(cl); - if (ok && c.pos == 300) { - for (int m = 1; m <= 4; m++) { - omega_gpu_decode_attn_test_set_mutant(m); - (void)fill_history(cache, &c); /* mutant 3 must not inherit the row the honest kernel wrote */ - uint16_t zk[128] = { 0 }, zv[128] = { 0 }; (void)omega_gpu_decode_attn_cache_write(cache, 0, 0, c.pos, 1, zk, zv); - for (unsigned g = 1; g < 4; g++) (void)omega_gpu_decode_attn_cache_write(cache, 0, g, c.pos, 1, zk, zv); - int r = omega_gpu_decode_attn(cache, 0, c.pos, c.qkv, EPS, 1.0f, y2, NULL); - size_t mb = 0; double mw = 0; uint16_t k2[512], v2[512]; - if (r == OMEGA_GPU_DATTN_OK) { mb = parity(&c, y2, 1.0f, &mw, k2, v2); } - int caught = r != OMEGA_GPU_DATTN_OK || mb > 0; - if (m == 4 && info.grid_x == 1) { printf("chip %-24s mutant 4: inert (1 split, the combine is not exercised)\n", pts[i].name); omega_gpu_decode_attn_test_set_mutant(0); continue; } - CHECK(caught, "chip mutant %d NOT caught", m); - printf("chip %-24s mutant %d: %s (rc=%s bad=%zu worst=%.3f)\n", pts[i].name, m, caught ? "caught" : "MISSED", omega_gpu_decode_attn_rc_name(r), mb, mw); - if (out) fprintf(out, ",{\"name\":\"%s mutant %d\",\"caught\":%d,\"rc\":\"%s\",\"bad\":%zu,\"worst_of_tol\":%.3f}", pts[i].name, m, caught, omega_gpu_decode_attn_rc_name(r), mb, mw); - omega_gpu_decode_attn_test_set_mutant(0); - } - } - free(y); free(y2); case_free(&c); - if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); break; } - } - omega_gpu_decode_attn_cache_free(cache); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"device_opens\":%u,\"verdict\":\"%s\"}\n", g_checks, g_failed, omega_gpu_session_open_count(), g_failed == 0 ? "OMEGA_GPU_DECODE_ATTN_PASS" : "OMEGA_GPU_DECODE_ATTN_FAIL"); fclose(out); } - return 0; -} - -/* --q-heads Q --kv-heads K --head-dim D (ternary engine T0, 2026-10-15): asks for an attention geometry. The kernel is - * built for one geometry only (OMEGA_GPU_DATTN_Q_HEADS 32, OMEGA_GPU_DATTN_KV_HEADS 4, head dim 128, per-head q_norm / - * k_norm before RoPE). Any other geometry is REFUSED here, with the reasons recorded (receipt verdict "REFUSED", exit 3), - * instead of running a kernel that would read the wrong q / k / v slices. */ -static int geometry_refusal(uint32_t qh, uint32_t kvh, uint32_t hd, const char *out_path) { - if (qh == OMEGA_GPU_DATTN_Q_HEADS && kvh == OMEGA_GPU_DATTN_KV_HEADS && hd == 128u) return 0; - char why[4][200]; int nw = 0; - if (qh != OMEGA_GPU_DATTN_Q_HEADS || kvh != OMEGA_GPU_DATTN_KV_HEADS) - snprintf(why[nw++], sizeof why[0], "head layout fixed at %u query / %u KV heads (%u per KV head); asked %u / %u (%u per KV head)", - OMEGA_GPU_DATTN_Q_HEADS, OMEGA_GPU_DATTN_KV_HEADS, OMEGA_GPU_DATTN_Q_HEADS / OMEGA_GPU_DATTN_KV_HEADS, qh, kvh, kvh ? qh / kvh : 0); - snprintf(why[nw++], sizeof why[0], "fused q|k|v input fixed at %u words; the asked layout needs %u", OMEGA_GPU_DATTN_QKV_WORDS, (qh + 2u * kvh) * hd); - snprintf(why[nw++], sizeof why[0], "per-head q_norm / k_norm is built in (Qwen3); a model without QK norm needs a kernel without it"); - if (hd != 128u) snprintf(why[nw++], sizeof why[0], "head dim fixed at 128; asked %u", hd); - printf("REFUSED: decode attention at %u query / %u KV heads, head dim %u\n", qh, kvh, hd); - for (int i = 0; i < nw; i++) printf(" reason %d: %s\n", i + 1, why[i]); - printf(" needed: a decode attention kernel for this geometry (ternary engine design KT3)\n"); - if (out_path) { - FILE *f = fopen(out_path, "w"); - if (f) { - fprintf(f, "{\"test\":\"gpu_decode_attn_test\",\"q_heads\":%u,\"kv_heads\":%u,\"head_dim\":%u,\"kernel_q_heads\":%u,\"kernel_kv_heads\":%u,\"reasons\":[", - qh, kvh, hd, OMEGA_GPU_DATTN_Q_HEADS, OMEGA_GPU_DATTN_KV_HEADS); - for (int i = 0; i < nw; i++) fprintf(f, "%s\"%s\"", i ? "," : "", why[i]); - fprintf(f, "],\"needed\":\"KT3 decode attention for this geometry\",\"verdict\":\"REFUSED\"}\n"); - fclose(f); - } - } - printf("gpu_decode_attn_test: REFUSED (geometry %u/%u/%u not built)\n", qh, kvh, hd); - return 3; -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; const char *out_path = NULL; uint32_t reps = 20, depth = 0, per = 0, spin = 2000; int sim_pos = -1; uint32_t sim_max = 256; - uint32_t q_heads = OMEGA_GPU_DATTN_Q_HEADS, kv_heads = OMEGA_GPU_DATTN_KV_HEADS, head_dim = 128; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--depth") == 0 && i + 1 < argc) depth = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--per-split") == 0 && i + 1 < argc) per = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0; - else if (strcmp(argv[i], "--sim-pos") == 0 && i + 1 < argc) sim_pos = atoi(argv[++i]); - else if (strcmp(argv[i], "--sim-max") == 0 && i + 1 < argc) sim_max = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--only") == 0 && i + 1 < argc) g_only = argv[++i]; - else if (strcmp(argv[i], "--q-heads") == 0 && i + 1 < argc) q_heads = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--kv-heads") == 0 && i + 1 < argc) kv_heads = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--head-dim") == 0 && i + 1 < argc) head_dim = (uint32_t)atoi(argv[++i]); - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - { int g = geometry_refusal(q_heads, kv_heads, head_dim, out_path); if (g) return g; } - if (host) host_only(); - if (sim && sim_pos >= 0 && sim_max <= (uint32_t)sim_pos) sim_max = (uint32_t)sim_pos + 1u; - if (sim && sim_pos >= 0) { char msg[300], rows[120]; double worst; size_t bad; int err = sim_point(sim_max, (uint32_t)sim_pos, depth ? depth : 2, 0, per ? per : 256, 1.0f, 777, msg, sizeof msg, &worst, &bad, rows, sizeof rows); printf("sim pos %d: %s %s\n", sim_pos, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); return err || bad; } - if (sim) sim_battery(); - if (!host && !sim) { - if (depth) omega_gpu_decode_attn_set_depth(depth); - if (per) omega_gpu_decode_attn_set_per_split(per); - (void)omega_gpu_session_set_spin_us(spin); - chip_run(out_path, reps ? reps : 1); - omega_gpu_session_close(); - } - printf("gpu_decode_attn_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_decode_graph_test.c b/tests/gpu_decode_graph_test.c deleted file mode 100644 index 8af07f1e4..000000000 --- a/tests/gpu_decode_graph_test.c +++ /dev/null @@ -1,371 +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. - */ - -/* - * gpu_decode_graph_test: OWN-30B W-L2a, one Qwen3-30B-A3B decode token as ONE command list (omega_gpu_decode_graph.h). - * --host-only glue-kernel specs the graph builds (codegen, no device) and the record entry points' argument refusals - * (default) chip, caller holds the GB10 lock. A synthetic Qwen3-30B-A3B-shaped step on random weights (hidden 2048, - * 128 experts top-8, intermediate 768, head_dim 128, 32/4 heads; --layers N (2), --vocab V (151936), - * pos 300 over a random KV prefix: 2 attention splits): - * A baseline = today's path: the four APIs one call at a time, host glue in C mirroring sc - * qwen3_moe_omega.rs step() (rmsnorm f64, x += o, device router, gate_up from the router's table, - * SwiGLU expf, down, combine, final rmsnorm, lm_head, argmax strict >) - * C main = the same step recorded as one list (omega_gpu_decode_graph_token) - * B the same list submitted one launch per submission (flush_each): batching comparison - * Checks: C deterministic over the reps; B == C bit for bit (x, hidden, logits, token); A vs C token - * identical and logits within tolerance; negative controls (SWIGLU mutant, COMBINE mutant) must fail - * the A-vs-C comparison. Per-token medians over --reps (20). --out receipt.json - * --red the C path with the wrong-wiring mutant 3 (attention at scale 1, not 2^64): this run MUST FAIL - * (red-before-green receipt). - * Verdict: exit 0 when every CHECK passed. - */ -#include "omega_gpu_decode_graph.h" -#include "omega_gpu_cmdlist.h" -#include "omega_blackwell_codegen_dec.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include -#include - -#define H 2048u -#define QKV 5120u -#define ATT 4096u -#define NE 128u -#define TK 8u -#define I 768u -#define EPS 1e-6f -#define POS 300u -#define MAX_POS 512u -#define SCALE_2P64 18446744073709551616.0f -/* A vs C logits: |dl| <= TOL_REL * max|l_A|. Sources of difference (header): RMSNorm f32 FFMA + MUFU.RSQ vs f64 host, - * SwiGLU MUFU EX2/RCP vs expf (~1e-7 relative each), carried through 2 layers of random weights and 2048-term sums; - * 1e-4 is ~100x that. Mutants move logits by O(1e-1..1) of max|l|. */ -#define TOL_REL 1e-4 - -static int g_checks, g_failed; -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } else { printf("ok: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint64_t median_u64(uint64_t *v, unsigned n) { qsort(v, n, sizeof *v, cmp_u64); return v[n / 2]; } - -/* ---- host glue: the Rust step()'s operations ---- */ -static void rmsnorm(const float *x, const float *w, float *out) { /* tensor.rs rmsnorm */ - double sq = 0; for (unsigned i = 0; i < H; i++) sq += (double)x[i] * x[i]; - float s = (float)(1.0 / sqrt(sq / H + (double)EPS)); - for (unsigned i = 0; i < H; i++) out[i] = x[i] * s * w[i]; -} -static void swiglu(const float *gu, float *act) { /* qwen3_moe_omega.rs swiglu: g / (1 + exp(-g)) * up */ - for (unsigned g = 0; g < TK; g++) for (unsigned j = 0; j < I; j++) { - float v = gu[g * 2 * I + j]; - act[g * I + j] = v / (1.0f + expf(-v)) * gu[g * 2 * I + I + j]; - } -} -static uint32_t argmax(const float *v, uint32_t n) { uint32_t b = 0; for (uint32_t i = 1; i < n; i++) if (v[i] > v[b]) b = i; return b; } - -/* ---- the synthetic model ---- */ -typedef struct { - uint32_t layers, vocab; - OmegaGpuFp8Tensor *qkv, *o, *gu, *dn; /* shared by every layer (memory); norms, router and KV differ per layer */ - OmegaGpuRouter *router; - OmegaGpuDecodeAttnCache *attn; - OmegaGpuBf16Tensor *lm; - float *in_norm, *fnorm, *x0; -} Model; - -static int fp8_random(uint32_t seed, uint32_t e, uint32_t n, uint32_t k, OmegaGpuFp8Tensor **out) { - size_t wb = (size_t)e * n * k, sb = (size_t)e * (n / 128) * (k / 128); - uint8_t *w = malloc(wb); uint16_t *s = malloc(sb * 2); - if (!w || !s) { free(w); free(s); return -1; } - uint32_t st = seed; - for (size_t i = 0; i < wb; i += 4) { uint32_t r = lcg(&st); for (unsigned j = 0; j < 4 && i + j < wb; j++) w[i + j] = (uint8_t)((r >> (8 * j)) & 0xbfu); } /* |v| <= 1.875: never a NaN code */ - for (size_t i = 0; i < sb; i++) s[i] = bf16_rne(frand(&st, 0.02f, 0.04f)); - int rc = omega_gpu_fp8_tensor_upload(e, n, k, w, s, out); - free(w); free(s); - return rc; -} - -static int model_build(Model *m, uint32_t layers, uint32_t vocab) { - memset(m, 0, sizeof *m); m->layers = layers; m->vocab = vocab; - uint32_t s = 1234; - if (fp8_random(11, 1, QKV, H, &m->qkv) || fp8_random(12, 1, H, ATT, &m->o) || fp8_random(13, NE, 2 * I, H, &m->gu) || fp8_random(14, NE, H, I, &m->dn)) { printf("fp8 upload: %s\n", omega_gpu_fp8_last_error()); return -1; } - if (omega_gpu_router_alloc(layers, &m->router) != 0) { printf("router alloc: %s\n", omega_gpu_router_last_error()); return -1; } - uint16_t *gate = malloc((size_t)NE * H * 2); float *nw = malloc(H * 4); - m->in_norm = malloc((size_t)layers * H * 4); m->fnorm = malloc(H * 4); m->x0 = malloc(H * 4); - if (!gate || !nw || !m->in_norm || !m->fnorm || !m->x0) return -1; - for (uint32_t l = 0; l < layers; l++) { - for (size_t i = 0; i < (size_t)NE * H; i++) gate[i] = bf16_rne(frand(&s, -0.05f, 0.05f)); - for (unsigned i = 0; i < H; i++) nw[i] = frand(&s, 0.8f, 1.2f); - if (omega_gpu_router_set_layer(m->router, l, gate, nw) != 0 || omega_gpu_router_set_directory_fp8(m->router, l, m->gu, m->dn) != 0) { printf("router layer: %s\n", omega_gpu_router_last_error()); return -1; } - for (unsigned i = 0; i < H; i++) m->in_norm[(size_t)l * H + i] = frand(&s, 0.8f, 1.2f); - } - free(gate); free(nw); - for (unsigned i = 0; i < H; i++) { m->fnorm[i] = frand(&s, 0.8f, 1.2f); m->x0[i] = frand(&s, -1.0f, 1.0f); } - if (omega_gpu_decode_attn_cache_alloc(layers, MAX_POS, 1000000.0, &m->attn) != 0) { printf("attn alloc: %s\n", omega_gpu_decode_attn_last_error()); return -1; } - float qn[128], kn[128]; uint16_t *kr = malloc((size_t)POS * 128 * 2), *vr = malloc((size_t)POS * 128 * 2); - if (!kr || !vr) return -1; - for (uint32_t l = 0; l < layers; l++) { - for (unsigned i = 0; i < 128; i++) { qn[i] = frand(&s, 0.8f, 1.2f); kn[i] = frand(&s, 0.8f, 1.2f); } - if (omega_gpu_decode_attn_set_norms(m->attn, l, qn, kn) != 0) return -1; - for (uint32_t h = 0; h < 4; h++) { - for (size_t i = 0; i < (size_t)POS * 128; i++) { kr[i] = bf16_rne(frand(&s, -1, 1)); vr[i] = bf16_rne(frand(&s, -1, 1)); } - if (omega_gpu_decode_attn_cache_write(m->attn, l, h, 0, POS, kr, vr) != 0) { printf("kv write: %s\n", omega_gpu_decode_attn_last_error()); return -1; } - } - } - free(kr); free(vr); - uint16_t *lw = malloc((size_t)vocab * H * 2); - if (!lw) return -1; - for (size_t i = 0; i < (size_t)vocab * H; i++) lw[i] = bf16_rne(frand(&s, -0.05f, 0.05f)); - int rc = omega_gpu_bf16_tensor_upload(vocab, H, lw, &m->lm); - free(lw); - if (rc != 0) { printf("lm_head upload: %s\n", omega_gpu_bf16_last_error()); return -1; } - return 0; -} - -/* A: today's path, one API call at a time, host glue */ -static int step_host(const Model *m, float *x, float *hidden, float *logits, uint32_t *tok, uint32_t *launches) { - static float xn[H], qkv[QKV], att[ATT], op[H], gu[TK * 2 * I], act[TK * I], dn[TK * H], mo[H]; - uint32_t ids[TK], zero = 0; float wts[TK]; uint64_t xout = 0, tgu = 0, tdn = 0; - memcpy(x, m->x0, H * 4); *launches = 0; - for (uint32_t l = 0; l < m->layers; l++) { - rmsnorm(x, m->in_norm + (size_t)l * H, xn); - if (omega_gpu_fp8_gemv_grouped_f32(m->qkv, 1, &zero, xn, 1, qkv, NULL)) return printf("A qkv: %s\n", omega_gpu_fp8_last_error()), -1; - if (omega_gpu_decode_attn(m->attn, l, POS, qkv, EPS, 1.0f, att, NULL)) return printf("A attn: %s\n", omega_gpu_decode_attn_last_error()), -1; - if (omega_gpu_fp8_gemv_grouped_f32(m->o, 1, &zero, att, 1, op, NULL)) return printf("A o: %s\n", omega_gpu_fp8_last_error()), -1; - for (unsigned i = 0; i < H; i++) x[i] += op[i]; - if (omega_gpu_router(m->router, l, x, EPS, 1, SCALE_2P64, ids, wts, NULL)) return printf("A router: %s\n", omega_gpu_router_last_error()), -1; - omega_gpu_router_device_outputs(m->router, &xout, &tgu, &tdn); - if (omega_gpu_fp8_gemv_grouped_dev(m->gu, TK, tgu, xout, gu, NULL)) return printf("A gate_up: %s\n", omega_gpu_fp8_last_error()), -1; - swiglu(gu, act); - if (omega_gpu_fp8_gemv_grouped_f32(m->dn, TK, ids, act, TK, dn, NULL)) return printf("A down: %s\n", omega_gpu_fp8_last_error()), -1; - for (unsigned i = 0; i < H; i++) mo[i] = 0.0f; - for (unsigned g = 0; g < TK; g++) for (unsigned i = 0; i < H; i++) mo[i] += wts[g] * dn[g * H + i]; - for (unsigned i = 0; i < H; i++) x[i] += mo[i]; - *launches += 6; - } - rmsnorm(x, m->fnorm, hidden); - if (omega_gpu_bf16_gemv_f32(m->lm, hidden, logits, NULL)) return printf("A lm_head: %s\n", omega_gpu_bf16_last_error()), -1; - *launches += 1; - *tok = argmax(logits, m->vocab); - return 0; -} - -typedef struct { float x[H], hidden[H]; float *logits; uint32_t tok; } Out; -static int out_alloc(Out *o, uint32_t vocab) { memset(o, 0, sizeof *o); o->logits = malloc((size_t)vocab * 4); return o->logits ? 0 : -1; } - -static int run_graph(OmegaGpuDecodeGraph *gr, const Model *m, Out *o, OmegaGpuDecodeGraphStats *st) { - int rc = omega_gpu_decode_graph_token(gr, m->x0, POS, &o->tok, st); - if (rc != 0) { printf("graph token rc %d: %s\n", rc, omega_gpu_session_last_error()); return rc; } - return omega_gpu_decode_graph_read(gr, o->x, o->hidden, o->logits); -} - -typedef struct { double max_abs, scale; int tok_same; } Cmp; -static Cmp compare(const Out *a, const Out *c, uint32_t vocab) { - Cmp r = { 0, 0, a->tok == c->tok }; - for (uint32_t i = 0; i < vocab; i++) { double d = fabs((double)a->logits[i] - c->logits[i]); if (d > r.max_abs) r.max_abs = d; if (fabs(a->logits[i]) > r.scale) r.scale = fabs(a->logits[i]); } - return r; -} -static int cmp_pass(Cmp c) { return c.tok_same && c.max_abs <= TOL_REL * c.scale; } -static double max_rel(const float *a, const float *b, unsigned n) { double mx = 0, sc = 0; for (unsigned i = 0; i < n; i++) { double d = fabs((double)a[i] - b[i]); if (d > mx) mx = d; if (fabs(a[i]) > sc) sc = fabs(a[i]); } return sc > 0 ? mx / sc : mx; } - -static int host_only(void) { - static const struct { OmegaDecKind kind; uint32_t mode; int mutant; const char *name; } sp[] = { - { OMEGA_DEC_RES, OMEGA_DEC_RES_NORM, 0, "RES NORM" }, { OMEGA_DEC_RES, OMEGA_DEC_RES_ADD, 0, "RES ADD" }, - { OMEGA_DEC_RES, OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, 0, "RES COMBINE|NORM" }, { OMEGA_DEC_SWIGLU, 0, 0, "SWIGLU" }, - { OMEGA_DEC_ARGMAX, 0, 0, "ARGMAX identity" }, { OMEGA_DEC_ARGMAX, 1, 0, "ARGMAX indexed" }, - { OMEGA_DEC_SWIGLU, 0, 1, "SWIGLU mutant 1" }, { OMEGA_DEC_RES, OMEGA_DEC_RES_COMBINE | OMEGA_DEC_RES_NORM, 2, "RES COMBINE|NORM mutant 2" }, - }; - for (unsigned i = 0; i < sizeof sp / sizeof sp[0]; i++) { - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = sp[i].kind; s.mode = sp[i].mode; s.mutant = sp[i].mutant; - uint32_t ins = 0, gpr = 0; int rc = omega_dec_prog_stats(&s, &ins, &gpr); - CHECK(rc == 0 && ins > 0, "%s builds (%u instructions, peak %u registers)", sp[i].name, ins, gpr); - } - OmegaDecSpec bad; memset(&bad, 0, sizeof bad); bad.kind = OMEGA_DEC_RES; bad.mode = OMEGA_DEC_RES_ADD | OMEGA_DEC_RES_COMBINE; - CHECK(omega_dec_prog_stats(&bad, NULL, NULL) != 0, "RES ADD|COMBINE refused by codegen"); - /* record entry points refuse a missing list or missing device addresses before touching the device */ - CHECK(omega_gpu_fp8_gemv_grouped_record(NULL, NULL, 1, 1, 1, 1, 1) == OMEGA_GPU_FP8_BAD_ARGS, "fp8 record without a list: BAD_ARGS"); - CHECK(omega_gpu_bf16_gemv_record(NULL, NULL, 1, 1) == OMEGA_GPU_BF16_BAD_ARGS, "bf16 record without a list: BAD_ARGS"); - CHECK(omega_gpu_router_record(NULL, NULL, 0, 1, EPS, 1, 1.0f, NULL) == OMEGA_GPU_ROUTER_BAD_ARGS, "router record without a list: BAD_ARGS"); - CHECK(omega_gpu_decode_attn_record(NULL, NULL, 0, 0, 1, EPS, 1.0f, 1) == OMEGA_GPU_DATTN_BAD_ARGS, "decode attn record without a list: BAD_ARGS"); - OmegaGpuCmdList *fake = (OmegaGpuCmdList *)(uintptr_t)16; /* never dereferenced: the argument checks come first */ - CHECK(omega_gpu_fp8_gemv_grouped_record(fake, NULL, 1, 0, 1, 1, 1) == OMEGA_GPU_FP8_BAD_ARGS, "fp8 record with tab_va 0: BAD_ARGS"); - CHECK(omega_gpu_bf16_gemv_record(fake, NULL, 0, 1) == OMEGA_GPU_BF16_BAD_ARGS, "bf16 record with x_va 0: BAD_ARGS"); - CHECK(omega_gpu_router_record(fake, NULL, 0, 0, EPS, 1, 1.0f, NULL) == OMEGA_GPU_ROUTER_BAD_ARGS, "router record with a NULL router: BAD_ARGS"); - CHECK(omega_gpu_decode_attn_record(fake, NULL, 0, 0, 0, EPS, 1.0f, 1) == OMEGA_GPU_DATTN_BAD_ARGS, "decode attn record with a NULL cache: BAD_ARGS"); - OmegaGpuDecodeGraphConfig cfg; memset(&cfg, 0, sizeof cfg); - OmegaGpuDecodeGraph *gr = NULL; - CHECK(omega_gpu_decode_graph_create(&cfg, &gr) == OMEGA_GPU_DGRAPH_BAD_ARGS && !gr, "graph create with an empty config: BAD_ARGS"); - return g_failed ? 1 : 0; -} - -static int chip_run(uint32_t layers, uint32_t vocab, uint32_t reps, int red, int cached, const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out) fprintf(out, "{\"layers\":%u,\"vocab\":%u,\"pos\":%u,\"reps\":%u,\"red\":%d,\"cached_weights\":%d,", layers, vocab, POS, reps, red, cached); - omega_gpu_fp8_set_weight_cache(cached); /* one variable: the FP8 tensors uploaded below live GPU-cached or not */ - Model m; - uint64_t t0 = omega_gpu_session_now_ns(); - if (model_build(&m, layers, vocab) != 0) { CHECK(0, "synthetic model build"); return 1; } - printf("model built in %.1f s (layers %u, vocab %u, pos %u)\n", (omega_gpu_session_now_ns() - t0) / 1e9, layers, vocab, POS); - OmegaGpuDecodeGraphConfig cfg = { .layers = layers, .vocab = vocab, .eps = EPS, .norm_topk = 1, .router = m.router, .attn = m.attn, .lm_head = m.lm }; - OmegaGpuDecodeGraph *gr = NULL; - int rc = omega_gpu_decode_graph_create(&cfg, &gr); - if (rc != 0) { CHECK(0, "graph create rc %d: %s", rc, omega_gpu_session_last_error()); return 1; } - for (uint32_t l = 0; l < layers; l++) - if (omega_gpu_decode_graph_set_layer(gr, l, m.qkv, m.o, m.gu, m.dn, m.in_norm + (size_t)l * H) != 0) { CHECK(0, "set_layer %u", l); return 1; } - if (omega_gpu_decode_graph_set_final_norm(gr, m.fnorm) != 0) { CHECK(0, "set_final_norm"); return 1; } - - Out A, A0, C, C0, B; uint64_t *ta = calloc(reps, 8), *tc = calloc(reps, 8), *tb = calloc(reps, 8), *cc = calloc(reps, 8), *cb = calloc(reps, 8), *rcn = calloc(reps, 8); - if (out_alloc(&A, vocab) || out_alloc(&A0, vocab) || out_alloc(&C, vocab) || out_alloc(&C0, vocab) || out_alloc(&B, vocab) || !ta || !tc || !tb || !cc || !cb || !rcn) return 1; - - /* A: baseline first (also fills every API's kernel cache, so no record has to build) */ - uint32_t la = 0; int a_ok = 1, a_det = 1; - for (uint32_t r = 0; r < reps && a_ok; r++) { - uint64_t s = omega_gpu_session_now_ns(); - if (step_host(&m, A.x, A.hidden, A.logits, &A.tok, &la) != 0) { a_ok = 0; break; } - ta[r] = omega_gpu_session_now_ns() - s; - if (r == 0) { memcpy(A0.x, A.x, sizeof A.x); memcpy(A0.hidden, A.hidden, sizeof A.hidden); memcpy(A0.logits, A.logits, (size_t)vocab * 4); A0.tok = A.tok; } - else if (A.tok != A0.tok || memcmp(A.logits, A0.logits, (size_t)vocab * 4)) a_det = 0; - } - CHECK(a_ok, "A (baseline, host glue) %u reps ran", reps); - if (!a_ok) return 1; - CHECK(a_det, "A deterministic over %u reps (token %u)", reps, A0.tok); - /* top-2 gap of the baseline: how much margin the argmax identity has */ - uint32_t t1 = A0.tok, t2 = t1 == 0 ? 1 : 0; for (uint32_t i = 0; i < vocab; i++) if (i != t1 && A0.logits[i] > A0.logits[t2]) t2 = i; - printf("A: token %u logit %.6f, runner-up %u logit %.6f (gap %.3g)\n", t1, A0.logits[t1], t2, A0.logits[t2], (double)A0.logits[t1] - A0.logits[t2]); - - if (red) omega_gpu_decode_graph_test_set_mutant(gr, 3); - /* C: one list per token */ - OmegaGpuDecodeGraphStats st; memset(&st, 0, sizeof st); uint32_t lc = 0, sc = 0; int c_ok = 1, c_det = 1; - for (uint32_t r = 0; r < reps && c_ok; r++) { - if (run_graph(gr, &m, &C, &st) != 0) { c_ok = 0; break; } - tc[r] = st.total_ns; cc[r] = st.chip_ns; rcn[r] = st.record_ns; lc = st.launches; sc = st.submits; - if (r == 0) { C0 = C; C0.logits = malloc((size_t)vocab * 4); memcpy(C0.logits, C.logits, (size_t)vocab * 4); } - else if (C.tok != C0.tok || memcmp(C.logits, C0.logits, (size_t)vocab * 4) || memcmp(C.x, C0.x, sizeof C.x)) c_det = 0; - } - CHECK(c_ok, "C (one list per token) %u reps ran: %u launches in %u submission(s)", reps, lc, sc); - if (!c_ok) return 1; - CHECK(c_det, "C deterministic over %u reps (token %u)", reps, C0.tok); - Cmp ac = compare(&A0, &C0, vocab); - double xr = max_rel(A0.x, C0.x, H), hr = max_rel(A0.hidden, C0.hidden, H); - printf("A vs C: token %u vs %u, logits max |d| %.3g (scale %.3g, rel %.3g, tol %.0e), x max rel %.3g, hidden max rel %.3g\n", - A0.tok, C0.tok, ac.max_abs, ac.scale, ac.max_abs / ac.scale, TOL_REL, xr, hr); - CHECK(ac.tok_same, "argmax token identical: A %u, C %u", A0.tok, C0.tok); - CHECK(ac.max_abs <= TOL_REL * ac.scale, "logits A vs C within %.0e of max|logit| (max |d| %.3g, scale %.3g)", TOL_REL, ac.max_abs, ac.scale); - if (out) fprintf(out, "\"A\":{\"token\":%u,\"runner_up\":%u,\"gap\":%.6g,\"launches\":%u},\"C\":{\"token\":%u,\"launches\":%u,\"submits\":%u},\"A_vs_C\":{\"tok_same\":%d,\"logit_max_abs\":%.6g,\"logit_scale\":%.6g,\"x_max_rel\":%.6g,\"hidden_max_rel\":%.6g,\"tol_rel\":%g},", - t1, t2, (double)A0.logits[t1] - A0.logits[t2], la, C0.tok, lc, sc, ac.tok_same, ac.max_abs, ac.scale, xr, hr, TOL_REL); - - if (!red) { - /* B: same list, one launch per submission: bit-identical to C */ - omega_gpu_decode_graph_set_flush_each(gr, 1); - uint32_t lb = 0, sb = 0; int b_ok = 1, b_same = 1; - for (uint32_t r = 0; r < reps && b_ok; r++) { - if (run_graph(gr, &m, &B, &st) != 0) { b_ok = 0; break; } - tb[r] = st.total_ns; cb[r] = st.chip_ns; lb = st.launches; sb = st.submits; - if (B.tok != C0.tok || memcmp(B.logits, C0.logits, (size_t)vocab * 4) || memcmp(B.x, C0.x, sizeof B.x) || memcmp(B.hidden, C0.hidden, sizeof B.hidden)) b_same = 0; - } - omega_gpu_decode_graph_set_flush_each(gr, 0); - CHECK(b_ok, "B (one launch per submission) %u reps ran: %u launches in %u submissions", reps, lb, sb); - CHECK(b_ok && b_same, "B bit-identical to C (x, hidden, logits, token) in every rep"); - - /* negative controls: a mutant glue kernel in C must fail the A-vs-C comparison */ - for (int mut = 1; mut <= 2; mut++) { - omega_gpu_decode_graph_test_set_mutant(gr, mut); - Out M; out_alloc(&M, vocab); - int mrc = run_graph(gr, &m, &M, &st); - Cmp mc = compare(&A0, &M, vocab); - CHECK(mrc == 0 && !cmp_pass(mc), "negative control: %s mutant fails the comparison (token %u vs %u, max |d| %.3g = %.3g of scale)", - mut == 1 ? "SWIGLU" : "COMBINE", M.tok, A0.tok, mc.max_abs, mc.max_abs / mc.scale); - if (out) fprintf(out, "\"mutant%d\":{\"rc\":%d,\"token\":%u,\"logit_max_abs\":%.6g,\"caught\":%d},", mut, mrc, M.tok, mc.max_abs, mrc == 0 && !cmp_pass(mc)); - free(M.logits); - } - omega_gpu_decode_graph_test_set_mutant(gr, 0); - /* after the mutants the real list must still agree (state not poisoned) */ - int prc = run_graph(gr, &m, &C, &st); - CHECK(prc == 0 && C.tok == C0.tok && !memcmp(C.logits, C0.logits, (size_t)vocab * 4), "C after the mutants bit-identical to the first C"); - - if (out) { uint64_t h = 1469598103934665603ull; const unsigned char *b = (const unsigned char *)C0.logits; for (size_t i = 0; i < (size_t)vocab * 4; i++) { h ^= b[i]; h *= 1099511628211ull; } - fprintf(out, "\"C0_token\":%u,\"C0_logits_fnv\":\"%016" PRIx64 "\",", C0.tok, h); } - /* timeline instrument: stamps on -> one timestamp per launch, monotonic, span within the chip time; token unchanged; off -> refuses */ - { - static uint64_t sts[OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1]; static uint8_t kinds[OMEGA_GPU_CMDLIST_MAX_LAUNCHES]; - omega_gpu_decode_graph_set_stamps(gr, 1); - Out S; out_alloc(&S, vocab); - int src_ = run_graph(gr, &m, &S, &st); - int n = omega_gpu_decode_graph_stamps(gr, sts, kinds, OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1); - int mono = 1; uint64_t per_kind[OMEGA_GPU_DGRAPH_K_COUNT] = { 0 }; uint32_t cnt_kind[OMEGA_GPU_DGRAPH_K_COUNT] = { 0 }; - for (int i = 0; i < n; i++) { if (sts[i + 1] < sts[i]) mono = 0; if (kinds[i] < OMEGA_GPU_DGRAPH_K_COUNT) { per_kind[kinds[i]] += sts[i + 1] - sts[i]; cnt_kind[kinds[i]]++; } } - const uint64_t span = n > 0 ? sts[n] - sts[0] : 0; - CHECK(src_ == 0 && n == (int)st.launches && mono && span > 0 && span <= st.chip_ns && S.tok == C0.tok && !memcmp(S.logits, C0.logits, (size_t)vocab * 4), - "timeline: rc %d, %d stamps for %u launches, monotonic %d, span %.1f us <= chip %.1f us, token and logits unchanged", src_, n, st.launches, mono, span / 1e3, st.chip_ns / 1e3); - printf("TIMELINE (%u layers, pos %u):", layers, POS); - for (unsigned k = 0; k < OMEGA_GPU_DGRAPH_K_COUNT; k++) if (cnt_kind[k]) printf(" %s x%u %.1f us", omega_gpu_decode_graph_kind_name((uint8_t)k), cnt_kind[k], per_kind[k] / 1e3); - printf("\n"); - if (out) { fprintf(out, "\"timeline\":{\"launches\":%d,\"span_ns\":%" PRIu64 ",\"chip_ns\":%" PRIu64 ",\"per_kind_ns\":{", n, span, st.chip_ns); - int first = 1; for (unsigned k = 0; k < OMEGA_GPU_DGRAPH_K_COUNT; k++) if (cnt_kind[k]) { fprintf(out, "%s\"%s\":[%u,%" PRIu64 "]", first ? "" : ",", omega_gpu_decode_graph_kind_name((uint8_t)k), cnt_kind[k], per_kind[k]); first = 0; } - fprintf(out, "}},"); } - omega_gpu_decode_graph_set_stamps(gr, 0); - int orc = run_graph(gr, &m, &S, &st); - int n2 = omega_gpu_decode_graph_stamps(gr, sts, kinds, OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1); - CHECK(orc == 0 && n2 < 0, "timeline off: token rc %d, stamps accessor refuses (%d)", orc, n2); - free(S.logits); - } - uint64_t ma = median_u64(ta, reps), mc_ = median_u64(tc, reps), mb = median_u64(tb, reps), mcc = median_u64(cc, reps), mcb = median_u64(cb, reps), mr = median_u64(rcn, reps); - printf("PER TOKEN (median of %u, %u layers): A host-glue %u launches %.1f us | C one list %u launches %.1f us (chip %.1f us, record %.1f us) | B per-launch submits %u launches %.1f us (chip sum %.1f us)\n", - reps, layers, la, ma / 1e3, lc, mc_ / 1e3, mcc / 1e3, mr / 1e3, lb, mb / 1e3, mcb / 1e3); - if (out) fprintf(out, "\"median_ns\":{\"A_total\":%" PRIu64 ",\"C_total\":%" PRIu64 ",\"C_chip\":%" PRIu64 ",\"C_record\":%" PRIu64 ",\"B_total\":%" PRIu64 ",\"B_chip\":%" PRIu64 "},\"B\":{\"launches\":%u,\"submits\":%u,\"identical\":%d},", - ma, mc_, mcc, mr, mb, mcb, lb, sb, b_ok && b_same); - } - omega_gpu_decode_graph_free(gr); - if (out) { fprintf(out, "\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - return g_failed ? 1 : 0; -} - -int main(int argc, char **argv) { - int host = 0, red = 0, cached = 0, variant = 0, barrier = -1, prefetch = 0, prefetch_red = 0; uint32_t cta_budget = 0, sh_lane = 0, sh_rows = 0, sh_warps = 0; uint32_t reps = 20, layers = 2, vocab = 151936; const char *out = NULL; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--red") == 0) red = 1; - else if (strcmp(argv[i], "--cached-weights") == 0) cached = 1; - else if (strcmp(argv[i], "--prefetch") == 0) prefetch = 1; /* W-L2d: o_proj weight prefetch beside the attention */ - else if (strcmp(argv[i], "--prefetch-red") == 0) prefetch = prefetch_red = 1; /* its red: o_proj unordered, MUST FAIL */ - else if (strcmp(argv[i], "--cta-budget") == 0 && i + 1 < argc) cta_budget = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--variant") == 0 && i + 1 < argc) variant = atoi(argv[++i]); /* FP8 GEMV generator: 1 (default) or 2 (W-L2c) */ - else if (strcmp(argv[i], "--barrier") == 0 && i + 1 < argc) barrier = atoi(argv[++i]); /* per-launch barrier mode (W-L2c): 0 wfi+inval_all, 2 wfi_only, 3 wfi+inval_data, 4 flush_data */ - else if (strcmp(argv[i], "--shape") == 0 && i + 3 < argc) { sh_lane = (uint32_t)atoi(argv[++i]); sh_rows = (uint32_t)atoi(argv[++i]); sh_warps = (uint32_t)atoi(argv[++i]); } - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--layers") == 0 && i + 1 < argc) layers = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--vocab") == 0 && i + 1 < argc) vocab = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out = argv[++i]; - else { printf("usage: %s [--host-only] [--red] [--reps N] [--layers N] [--vocab V] [--out receipt.json]\n", argv[0]); return 2; } - } - if (reps == 0) reps = 1; - if (layers == 0 || layers > 8) layers = 2; - if (variant) omega_gpu_fp8_set_variant(variant); - omega_gpu_decode_graph_set_prefetch(prefetch); omega_gpu_decode_graph_test_set_prefetch_red(prefetch_red); - if (barrier == 1) omega_gpu_decode_graph_test_set_barrier_none(); /* negative control: this run MUST FAIL */ - else if (barrier >= 0) omega_gpu_decode_graph_set_barrier(barrier); - if (cta_budget) omega_gpu_fp8_set_cta_budget(cta_budget); /* one variable per run (timeline sweeps) */ - if (sh_lane) omega_gpu_fp8_set_shape(sh_lane, sh_rows, sh_warps); - printf("dgraph prefetch %d (red %d)\n", omega_gpu_decode_graph_prefetch(), prefetch_red); - printf("fp8 knobs: variant %d barrier %d (%s) cta_budget %u shape %u/%u/%u cached %d\n", omega_gpu_fp8_variant(), omega_gpu_decode_graph_barrier(), omega_gpu_cmdlist_barrier_name((OmegaGpuCmdListBarrier)omega_gpu_decode_graph_barrier()), cta_budget, sh_lane, sh_rows, sh_warps, cached); - int rc = host ? host_only() : chip_run(layers, vocab, reps, red, cached, out); - printf("%s: %d checks, %d failed: %s\n", host ? "host-only" : red ? "chip-red" : "chip", g_checks, g_failed, rc ? "FAIL" : "PASS"); - return rc; -} diff --git a/tests/gpu_elementwise_test.c b/tests/gpu_elementwise_test.c deleted file mode 100644 index 7a270eb5f..000000000 --- a/tests/gpu_elementwise_test.c +++ /dev/null @@ -1,402 +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. - */ - -/* gpu_elementwise_test: FB-1 cut 4 gate for omega_gpu_elementwise_api. - * - * ./gpu_elementwise_test --host-only refusals, codegen, word fixtures, register budget, - * listing check by Omega's own disassembler - * ./gpu_elementwise_test --out receipt.json chip gate: every op against the host oracle, then its mutant - * (a deliberately wrong kernel) which the same check must catch - * ./gpu_elementwise_test --timing --out t.json cut 4b gate: persistent device, 100 calls each of rmsnorm 1x2048 - * and swiglu 5632 under 0.5 ms median, one device open per process - * - * Oracles re-state aien-sovereign-core crates/aien-inference-abi/src/tensor.rs (main 5fdab70) in C: - * rmsnorm sums in f64, rope computes cos/sin in f64 and casts to f32 before f32 math, swiglu is f64. - * This file is compiled with -ffp-contract=off so the f32 oracle math has no hidden fused multiply-add. - * - * Tolerances (why): EX2 1e-6 rel (PTX ex2.approx.f32: 2^-22.5 rel, we allow 2x). XCHG exact. - * RMSNORM 1e-5 rel + 1e-6 abs (f32 sum of up to 16384 squares against an f64 sum, plus RSQ seed with one - * Newton step; the mutant moves the scale by about 40 percent). ROPE exact (same f32 ops, same order). - * SWIGLU 1e-5 rel + 1e-6 abs (EX2 and RCP approximations, each about 2^-22 rel; the mutant flips the sign - * of the exponent, which is wrong by a factor of e^(2g)). - */ -#include "omega_gpu_elementwise_api.h" -#include "omega_blackwell_codegen.h" -#include "omega_gpu_session.h" -#include "omega_sm121_disasm.h" -#include -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } - -/* ----------------------------------------------------------------- oracles */ -static void oracle_rmsnorm(const float *x, const float *w, float eps, float *out, size_t dim) { - double ss = 0.0; - for (size_t i = 0; i < dim; i++) ss += (double)x[i] * (double)x[i]; - double mean = ss / (double)dim; - float scale = (float)(1.0 / sqrt(mean + (double)eps)); - for (size_t i = 0; i < dim; i++) { float t = x[i] * scale; out[i] = t * w[i]; } -} -static void oracle_rope_tables(size_t head_dim, size_t pos, float theta, float *cos_half, float *sin_half) { - size_t half = head_dim / 2; - for (size_t i = 0; i < half; i++) { - double exponent = (double)(2 * i) / (double)head_dim; - double freq = 1.0 / pow((double)theta, exponent); - double rot = (double)pos * freq; - sin_half[i] = (float)sin(rot); - cos_half[i] = (float)cos(rot); - } -} -static void oracle_rope(const float *v, size_t heads, size_t head_dim, const float *cos_half, const float *sin_half, float *out) { - size_t half = head_dim / 2; - for (size_t h = 0; h < heads; h++) - for (size_t i = 0; i < half; i++) { - size_t i0 = h * head_dim + i, i1 = i0 + half; - float q0 = v[i0], q1 = v[i1], c = cos_half[i], s = sin_half[i]; - float a = q0 * c, b = q1 * s; out[i0] = a - b; - float d = q0 * s, e = q1 * c; out[i1] = d + e; - } -} -static void oracle_swiglu(const float *g, const float *u, float *out, size_t n) { - for (size_t i = 0; i < n; i++) { double gg = g[i]; double silu = gg / (1.0 + exp(-gg)); out[i] = (float)(silu * (double)u[i]); } -} - -/* |got - want| <= rel*|want| + abs; returns the number of violations and the worst scaled error */ -static size_t compare(const float *got, const float *want, size_t n, double rel, double abs_tol, double *worst) { - size_t bad = 0; *worst = 0.0; - for (size_t i = 0; i < n; i++) { - double d = fabs((double)got[i] - (double)want[i]); - double lim = rel * fabs((double)want[i]) + abs_tol; - double scaled = lim > 0 ? d / lim : (d > 0 ? INFINITY : 0.0); - if (scaled > *worst) *worst = scaled; - if (!(d <= lim)) bad++; /* NaN counts as bad */ - } - return bad; -} - -/* ------------------------------------------------------------- host only */ -static int sm121dis_check(OmegaGpuEwOp op, const char *name, const char *const *must, int n_must) { - OmegaBlackwellKernel k; memset(&k, 0, sizeof k); - if (omega_gpu_elementwise_codegen(op, NULL, 0.0f, &k) != OMEGA_GPU_EW_OK) return -1; - char lst[64]; - snprintf(lst, sizeof lst, "/tmp/omega_ew_%s_%d.sass.XXXXXX", name, (int)getpid()); - int fd = mkstemp(lst); /* private, unique listing; read back the same descriptor */ - FILE *f = fd >= 0 ? fdopen(fd, "w+") : NULL; - if (!f) { if (fd >= 0) close(fd); free(k.code); return -1; } - int rc = omega_sm121_listing(k.code, k.code_size, f); - free(k.code); - if (fflush(f) != 0 || fseek(f, 0, SEEK_SET) != 0) { fclose(f); return -1; } - FILE *l = f; - char line[512]; int seen[16] = {0}; int bad = 0, insns = 0; - while (fgets(line, sizeof line, l)) { - if (!strstr(line, "/*")) continue; /* every address line, 0x1000 and up too */ - insns++; - if (strstr(line, "?") || strstr(line, "error")) bad++; - for (int i = 0; i < n_must; i++) if (strstr(line, must[i])) seen[i] = 1; - } - if (ferror(l)) rc = -1; - if (fclose(l) != 0) rc = -1; - int miss = 0; - for (int i = 0; i < n_must; i++) if (!seen[i]) { printf(" %s: sm121dis listing lacks %s\n", name, must[i]); miss++; } - printf("sm121dis %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst); - return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1; -} - -static void host_only(void) { - CHECK(omega_blackwell_verify_codegen_fixtures_fb1cut4() == 0, "word fixtures MUFU_EX2 / BAR_SYNC / LDS32 / STS32 (rc %d)", omega_blackwell_verify_codegen_fixtures_fb1cut4()); - float a[256] = {0}, b[256] = {0}, c[256] = {0}; - CHECK(omega_gpu_rmsnorm_f32(0, 128, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "rows=0 refused"); - CHECK(omega_gpu_rmsnorm_f32(1, 100, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "dim not a multiple of 128 refused"); - CHECK(omega_gpu_rmsnorm_f32(1, OMEGA_GPU_EW_MAX_DIM + 128, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_TOO_LARGE, "dim over limit refused"); - CHECK(omega_gpu_rope_f32(1, 63, a, b, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "odd head_dim refused"); - CHECK(omega_gpu_rope_f32(1, 64, NULL, b, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "NULL vector refused"); - CHECK(omega_gpu_swiglu_f32(0, a, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "n=0 refused"); - CHECK(omega_gpu_shared_xchg_u32(100, (uint32_t *)a, (uint32_t *)c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "xchg n not a multiple of 128 refused"); - CHECK(strcmp(omega_gpu_elementwise_rc_name(OMEGA_GPU_EW_UNWRITTEN), "UNWRITTEN") == 0, "rc name"); - - struct { OmegaGpuEwOp op; const char *name; const char *must[6]; int n; } ops[] = { - { OMEGA_GPU_EW_EX2, "ex2", { "MUFU.EX2", "@P0 EXIT", "STG.E" }, 3 }, - { OMEGA_GPU_EW_XCHG, "xchg", { "STS [R", "BAR.SYNC", "LDS R" }, 3 }, - { OMEGA_GPU_EW_RMSNORM, "rmsnorm", { "SHFL.DOWN", "BAR.SYNC", "MUFU.RSQ", "@!P0 BRA", "STS [R", "LDS R" }, 6 }, - { OMEGA_GPU_EW_ROPE, "rope", { "FADD", "FMUL", "STG.E" }, 3 }, - { OMEGA_GPU_EW_SWIGLU, "swiglu", { "MUFU.EX2", "MUFU.RCP", "@P0 EXIT" }, 3 }, - }; - for (size_t i = 0; i < sizeof ops / sizeof ops[0]; i++) { - OmegaBlackwellKernel k; memset(&k, 0, sizeof k); - int rc = omega_gpu_elementwise_codegen(ops[i].op, NULL, 0.0f, &k); - CHECK(rc == OMEGA_GPU_EW_OK && k.code_size > 0 && k.gpr_count <= 64, "%s kernel generated (rc %s, %zu insns, %u gprs)", ops[i].name, omega_gpu_elementwise_rc_name(rc), k.insn_count, k.gpr_count); - printf("codegen %s: %zu insns, %u gprs, %u ugprs\n", ops[i].name, k.insn_count, k.gpr_count, k.uniform_gpr_count); - uint8_t digest[32]; memcpy(digest, k.code_digest, 32); - free(k.code); - /* the mutant must be a different kernel */ - omega_gpu_elementwise_test_set_mutant((int)ops[i].op); - memset(&k, 0, sizeof k); - CHECK(omega_gpu_elementwise_codegen(ops[i].op, NULL, 0.0f, &k) == OMEGA_GPU_EW_OK && memcmp(digest, k.code_digest, 32) != 0, "%s mutant kernel differs", ops[i].name); - free(k.code); - omega_gpu_elementwise_test_set_mutant(0); - CHECK(sm121dis_check(ops[i].op, ops[i].name, ops[i].must, ops[i].n) == 0, "%s sm121dis listing decodes and shows the expected instructions", ops[i].name); - } -} - -/* ------------------------------------------------------------- chip gate */ -typedef struct { const char *name; size_t n; int rc; size_t bad; double worst; int pass; int mutant_rc; size_t mutant_bad; int mutant_caught; uint64_t chip_ns; uint32_t calls; uint32_t unwritten; } Case; -static Case g_cases[16]; static int g_ncases; - -static void record(Case c, FILE *out) { - g_cases[g_ncases++] = c; - CHECK(c.pass, "%s rc=%s violations=%zu worst=%g", c.name, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst); - CHECK(c.mutant_caught, "%s mutant caught (rc=%s violations=%zu)", c.name, omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad); - printf("%s %s n=%zu rc=%s violations=%zu worst_scaled_err=%g chip_ns=%" PRIu64 " calls=%u unwritten=%u | mutant rc=%s violations=%zu %s\n", - c.pass && c.mutant_caught ? "PASS" : "FAIL", c.name, c.n, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst, c.chip_ns, c.calls, c.unwritten, - omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad, c.mutant_caught ? "CAUGHT" : "NOT CAUGHT"); - if (out) fprintf(out, "%s{\"case\":\"%s\",\"n\":%zu,\"rc\":\"%s\",\"violations\":%zu,\"worst_scaled_err\":%g,\"pass\":%s,\"chip_elapsed_ns\":%" PRIu64 ",\"chip_calls\":%u,\"unwritten_words\":%u,\"mutant_rc\":\"%s\",\"mutant_violations\":%zu,\"mutant_caught\":%s}", - g_ncases > 1 ? "," : "", c.name, c.n, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst, c.pass ? "true" : "false", c.chip_ns, c.calls, c.unwritten, - omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad, c.mutant_caught ? "true" : "false"); -} - -static int chip(const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ELEMENTWISE_V1\",\"tolerances\":{\"ex2_rel\":1e-6,\"xchg\":\"exact\",\"rmsnorm_rel\":1e-5,\"rmsnorm_abs\":1e-6,\"rope\":\"exact\",\"swiglu_rel\":1e-5,\"swiglu_abs\":1e-6},\"cases\":["); - uint32_t seed = 0xfb1c0004u; - OmegaGpuEwInfo info; - - /* 1. EX2 probe, with a negative control on the comparison itself */ - { - size_t n = 4096; float *x = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *wrong = malloc(n * 4); - for (size_t i = 0; i < n; i++) { x[i] = frand(&seed, -20.0f, 20.0f); want[i] = (float)exp2((double)x[i]); wrong[i] = (float)exp2((double)x[i] + 1.0); } - Case c = { .name = "ex2_probe", .n = n }; - c.rc = omega_gpu_ex2_f32((uint32_t)n, x, got, &info); - c.bad = compare(got, want, n, 1e-6, 0.0, &c.worst); - double w2; size_t neg = compare(got, wrong, n, 1e-6, 0.0, &w2); - CHECK(neg > n / 2, "ex2 negative control: the check rejects a wrong expectation (%zu of %zu flagged)", neg, n); - c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; - omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_EX2); - c.mutant_rc = omega_gpu_ex2_f32((uint32_t)n, x, got, &info); - c.mutant_bad = compare(got, want, n, 1e-6, 0.0, &w2); - c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - record(c, out); free(x); free(got); free(want); free(wrong); - } - /* 2. shared-memory exchange probe (STS, BAR.SYNC, LDS) */ - { - size_t n = 4096; uint32_t *x = malloc(n * 4), *got = malloc(n * 4); - for (size_t i = 0; i < n; i++) x[i] = lcg(&seed); - Case c = { .name = "shared_xchg_probe", .n = n }; - c.rc = omega_gpu_shared_xchg_u32((uint32_t)n, x, got, &info); - for (size_t i = 0; i < n; i++) if (got[i] != x[i ^ (OMEGA_GPU_EW_THREADS - 1)]) c.bad++; - c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; - omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_XCHG); - c.mutant_rc = omega_gpu_shared_xchg_u32((uint32_t)n, x, got, &info); - for (size_t i = 0; i < n; i++) if (got[i] != x[i ^ (OMEGA_GPU_EW_THREADS - 1)]) c.mutant_bad++; - c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - record(c, out); free(x); free(got); - } - /* 3. rmsnorm at the model hidden sizes (TinyLlama and Llama-3.2-1B: 2048), plus small and large */ - { size_t dims[3] = { 2048, 256, 8192 }; size_t rowss[3] = { 4, 1, 2 }; - for (int t = 0; t < 3; t++) { - size_t dim = dims[t], rows = rowss[t], n = rows * dim; float eps = 1e-5f; - float *x = malloc(n * 4), *w = malloc(dim * 4), *got = malloc(n * 4), *want = malloc(n * 4), *again = malloc(n * 4); - for (size_t i = 0; i < n; i++) x[i] = frand(&seed, -3.0f, 3.0f); - for (size_t i = 0; i < dim; i++) w[i] = frand(&seed, 0.5f, 1.5f); - for (size_t r = 0; r < rows; r++) oracle_rmsnorm(x + r * dim, w, eps, want + r * dim, dim); - char name[64]; snprintf(name, sizeof name, "rmsnorm_%zux%zu", rows, dim); - Case c = { .name = strdup(name), .n = n }; - c.rc = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, got, &info); - c.bad = compare(got, want, n, 1e-5, 1e-6, &c.worst); - c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; - OmegaGpuEwInfo i2; int rc2 = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, again, &i2); - CHECK(rc2 == OMEGA_GPU_EW_OK && i2.kernel_cache_hit && memcmp(got, again, n * 4) == 0, "%s repeat run (cache hit) is bit-identical", name); - omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_RMSNORM); - double w2; c.mutant_rc = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, got, &info); - c.mutant_bad = compare(got, want, n, 1e-5, 1e-6, &w2); - c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - record(c, out); free(x); free(w); free(got); free(want); free(again); - } } - /* 4. rope: TinyLlama (32 q heads, 4 kv heads, head_dim 64, theta 10000) and Llama-3.2-1B (32/8, 64, 500000) */ - { struct { size_t heads, hd, pos; float theta; } rs[4] = { { 32, 64, 17, 10000.0f }, { 4, 64, 17, 10000.0f }, { 32, 64, 1023, 500000.0f }, { 8, 64, 1023, 500000.0f } }; - for (int t = 0; t < 4; t++) { - size_t heads = rs[t].heads, hd = rs[t].hd, n = heads * hd, half = hd / 2; - float *v = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *ch = malloc(half * 4), *sh = malloc(half * 4); - for (size_t i = 0; i < n; i++) v[i] = frand(&seed, -4.0f, 4.0f); - oracle_rope_tables(hd, rs[t].pos, rs[t].theta, ch, sh); - oracle_rope(v, heads, hd, ch, sh, want); - char name[64]; snprintf(name, sizeof name, "rope_%zuh_%zud_pos%zu_theta%g", heads, hd, rs[t].pos, rs[t].theta); - Case c = { .name = strdup(name), .n = n }; - c.rc = omega_gpu_rope_f32((uint32_t)heads, (uint32_t)hd, v, ch, sh, got, &info); - c.bad = compare(got, want, n, 0.0, 0.0, &c.worst); - c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; - omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_ROPE); - double w2; c.mutant_rc = omega_gpu_rope_f32((uint32_t)heads, (uint32_t)hd, v, ch, sh, got, &info); - c.mutant_bad = compare(got, want, n, 0.0, 0.0, &w2); - c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - record(c, out); free(v); free(got); free(want); free(ch); free(sh); - } } - /* 5. swiglu at the model ffn sizes (TinyLlama 5632, Llama-3.2-1B 8192), an odd tail, one past the - * 1024-CTA chunk (two launches) and the Qwen3-8B prefill call 128 x 12288 (twelve launches; cut L) */ - { size_t ns[5] = { 5632, 8192, 1000, 131073, 1572864 }; - for (int t = 0; t < 5; t++) { - size_t n = ns[t]; - float *g = malloc(n * 4), *u = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) { g[i] = frand(&seed, -12.0f, 12.0f); u[i] = frand(&seed, -2.0f, 2.0f); } - oracle_swiglu(g, u, want, n); - char name[64]; snprintf(name, sizeof name, "swiglu_%zu", n); - Case c = { .name = strdup(name), .n = n }; - c.rc = omega_gpu_swiglu_f32((uint32_t)n, g, u, got, &info); - c.bad = compare(got, want, n, 1e-5, 1e-6, &c.worst); - c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words; - omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_SWIGLU); - double w2; c.mutant_rc = omega_gpu_swiglu_f32((uint32_t)n, g, u, got, &info); - c.mutant_bad = compare(got, want, n, 1e-5, 1e-6, &w2); - c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - record(c, out); free(g); free(u); free(got); free(want); - } } - /* 6. stale-SM-instruction-cache guard (cut 1b finding, omega #256): 10 distinct kernels - * (5 ops + 5 mutants) in rotation, two rounds. Every launch uploads code into a freshly - * allocated page, so a kernel routinely lands on the code address its predecessor used, - * and 10 keys evict the 8-slot kernel cache. Each clean launch must match the oracle and - * each mutant must still be caught; a stale icache would make a mutant pass or a clean - * kernel fail. Red was observed by cut 1b on matmul before its invalidate (receipt - * FB1-CUT1B-f629798); this build carries the invalidate, so the case is a guard. */ - { - enum { RN = 256, RH = 4, RD = 64 }; - float *x = malloc(RN * 4), *w = malloc(RN * 4), *u = malloc(RN * 4), *got = malloc(RN * 4), *want = malloc(RN * 4); - float *ch = malloc(RD / 2 * 4), *sh = malloc(RD / 2 * 4); - uint32_t *xu = malloc(RN * 4), *gu = malloc(RN * 4); - for (size_t i = 0; i < RN; i++) { x[i] = frand(&seed, -3.0f, 3.0f); w[i] = frand(&seed, 0.5f, 1.5f); u[i] = frand(&seed, -2.0f, 2.0f); xu[i] = lcg(&seed); } - oracle_rope_tables(RD, 17, 10000.0f, ch, sh); - Case c = { .name = "icache_reuse_rotation", .n = 20 }; - c.rc = OMEGA_GPU_EW_OK; c.mutant_rc = OMEGA_GPU_EW_OK; c.mutant_caught = 1; - const int order[10] = { OMEGA_GPU_EW_EX2, -OMEGA_GPU_EW_SWIGLU, OMEGA_GPU_EW_XCHG, -OMEGA_GPU_EW_EX2, OMEGA_GPU_EW_RMSNORM, - -OMEGA_GPU_EW_XCHG, OMEGA_GPU_EW_SWIGLU, -OMEGA_GPU_EW_ROPE, OMEGA_GPU_EW_ROPE, -OMEGA_GPU_EW_RMSNORM }; - for (int step = 0; step < 20; step++) { - int round = step / 10, k = step % 10; - int mut = order[k] < 0, op = mut ? -order[k] : order[k]; - omega_gpu_elementwise_test_set_mutant(mut ? op : 0); - int rc; size_t bad = 0; double wst; - switch (op) { - case OMEGA_GPU_EW_EX2: - for (size_t i = 0; i < RN; i++) want[i] = (float)exp2((double)x[i]); - rc = omega_gpu_ex2_f32(RN, x, got, &info); bad = compare(got, want, RN, 1e-6, 0.0, &wst); break; - case OMEGA_GPU_EW_XCHG: - rc = omega_gpu_shared_xchg_u32(RN, xu, gu, &info); - for (size_t i = 0; i < RN; i++) { if (gu[i] != xu[i ^ (OMEGA_GPU_EW_THREADS - 1)]) bad++; } - break; - case OMEGA_GPU_EW_RMSNORM: - oracle_rmsnorm(x, w, 1e-5f, want, RN); - rc = omega_gpu_rmsnorm_f32(1, RN, x, w, 1e-5f, got, &info); bad = compare(got, want, RN, 1e-5, 1e-6, &wst); break; - case OMEGA_GPU_EW_ROPE: - oracle_rope(x, RH, RD, ch, sh, want); - rc = omega_gpu_rope_f32(RH, RD, x, ch, sh, got, &info); bad = compare(got, want, RH * RD, 0.0, 0.0, &wst); break; - default: - oracle_swiglu(x, u, want, RN); - rc = omega_gpu_swiglu_f32(RN, x, u, got, &info); bad = compare(got, want, RN, 1e-5, 1e-6, &wst); break; - } - omega_gpu_elementwise_test_set_mutant(0); - int ok = rc == OMEGA_GPU_EW_OK && bad == 0; - if (!mut && !ok) { c.bad++; if (rc != OMEGA_GPU_EW_OK) c.rc = rc; printf(" rotation %d/%d: clean op %d FAILED rc=%s violations=%zu\n", round, k, op, omega_gpu_elementwise_rc_name(rc), bad); } - if (mut && ok) { c.mutant_bad++; c.mutant_caught = 0; printf(" rotation %d/%d: mutant op %d NOT caught\n", round, k, op); } - c.chip_ns += info.elapsed_ns; c.calls += info.chip_calls; c.unwritten += info.unwritten_words; - } - c.pass = c.bad == 0 && c.rc == OMEGA_GPU_EW_OK; - record(c, out); - free(x); free(w); free(u); free(got); free(want); free(ch); free(sh); free(xu); free(gu); - } - /* cut 4b: the whole battery (clean and mutant kernels, cache clears) ran on ONE device open */ - CHECK(omega_gpu_session_open_count() == 1, "device opened once for the battery (opens=%u)", omega_gpu_session_open_count()); - printf("device_opens=%u\n", omega_gpu_session_open_count()); - if (out) { - fprintf(out, "],\"device_opens\":%u,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_session_open_count(), g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ELEMENTWISE_PASS" : "OMEGA_GPU_ELEMENTWISE_FAIL"); - fclose(out); - } - return 0; -} - -/* ------------------------------------------------------------ timing gate (cut 4b) */ -/* The persistent device: 100 calls each of rmsnorm 1x2048 and swiglu 5632 (the TinyLlama - * decode shapes), every call checked against the oracle, median wall time per call under - * 0.5 ms (cut 4 opened and closed the device per call: ~40 ms). The device must have been - * opened exactly once in this process. */ -static int cmp_d(const void *a, const void *b) { double x = *(const double *)a, y = *(const double *)b; return x < y ? -1 : x > y; } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int timing(const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ELEMENTWISE_TIMING_V1\",\"gate_median_ms\":0.5,\"calls\":100,\"cases\":["); - uint32_t seed = 0xfb1c004bu; - enum { N = 100 }; - for (int t = 0; t < 2; t++) { - const char *name = t == 0 ? "rmsnorm_1x2048" : "swiglu_5632"; - size_t n = t == 0 ? 2048 : 5632; - float *a = malloc(n * 4), *b = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); - for (size_t i = 0; i < n; i++) { a[i] = frand(&seed, -3.0f, 3.0f); b[i] = t == 0 ? frand(&seed, 0.5f, 1.5f) : frand(&seed, -2.0f, 2.0f); } - if (t == 0) oracle_rmsnorm(a, b, 1e-5f, want, n); else oracle_swiglu(a, b, want, n); - double samples[N]; int ok_calls = 0; size_t bad_total = 0; double worst = 0; uint64_t chip_sum = 0; int rc_last = 0; - OmegaGpuEwInfo info; - /* warm-up: first call opens the device and generates the kernel (not timed) */ - int rc0 = t == 0 ? omega_gpu_rmsnorm_f32(1, (uint32_t)n, a, b, 1e-5f, got, &info) : omega_gpu_swiglu_f32((uint32_t)n, a, b, got, &info); - double first_ms = info.call_ns / 1e6; - CHECK(rc0 == OMEGA_GPU_EW_OK, "%s first call rc=%s err=\"%s\"", name, omega_gpu_elementwise_rc_name(rc0), omega_gpu_elementwise_last_error()); - for (int i = 0; i < N; i++) { - double t0 = now_ms(); - int rc = t == 0 ? omega_gpu_rmsnorm_f32(1, (uint32_t)n, a, b, 1e-5f, got, &info) : omega_gpu_swiglu_f32((uint32_t)n, a, b, got, &info); - samples[i] = now_ms() - t0; - double w; size_t bad = compare(got, want, n, 1e-5, 1e-6, &w); - if (w > worst) worst = w; - bad_total += bad; chip_sum += info.elapsed_ns; rc_last = rc; - if (rc == OMEGA_GPU_EW_OK && bad == 0) ok_calls++; - } - qsort(samples, N, sizeof samples[0], cmp_d); - double median = samples[N / 2], p90 = samples[N * 9 / 10], mn = samples[0], mx = samples[N - 1]; - uint32_t opens = omega_gpu_session_open_count(); - int pass = ok_calls == N && bad_total == 0 && median < 0.5 && opens == 1; - CHECK(pass, "timing %s ok_calls=%d/%d violations=%zu median_ms=%.3f opens=%u last_rc=%s err=\"%s\"", name, ok_calls, N, bad_total, median, opens, omega_gpu_elementwise_rc_name(rc_last), omega_gpu_elementwise_last_error()); - printf("%s timing %s first_call_ms=%.3f ok_calls=%d/%d violations=%zu worst_scaled_err=%g median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_us_mean=%.1f device_opens=%u\n", - pass ? "PASS" : "FAIL", name, first_ms, ok_calls, N, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens); - if (out) fprintf(out, "%s{\"case\":\"%s\",\"first_call_ms\":%.3f,\"ok_calls\":%d,\"violations\":%zu,\"worst_scaled_err\":%g,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f,\"chip_us_mean\":%.1f,\"device_opens\":%u,\"pass\":%s}", - t ? "," : "", name, first_ms, ok_calls, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens, pass ? "true" : "false"); - free(a); free(b); free(got); free(want); - } - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ELEMENTWISE_TIMING_PASS" : "OMEGA_GPU_ELEMENTWISE_TIMING_FAIL"); fclose(out); } - return 0; -} - -int main(int argc, char **argv) { - const char *out_path = NULL; int host = 0, timing_mode = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--timing") == 0) timing_mode = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - } - if (host) host_only(); - else if (timing_mode) { if (timing(out_path) != 0) return 2; } - else if (chip(out_path) != 0) return 2; - printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_exact_head_test.c b/tests/gpu_exact_head_test.c deleted file mode 100644 index 5258f3d84..000000000 --- a/tests/gpu_exact_head_test.c +++ /dev/null @@ -1,300 +0,0 @@ -/* - * gpu_exact_head_test: the exact two-pass lm_head (HUM lever L314) on the Qwen3.6-35B-A3B head. - * --sim warp-simulator proofs of the new kernels: XBOUND (lo <= s - c|h|, hi >= s + c|h| on every row despite f32 - * rounding, tight to 2^-8, rows past count untouched; mutant 1 caught). The MASK recheck form is proven in - * gpu_bf16_gemv_test --sim (candidates bit-identical to the plain kernel, mutant 4 caught). - * --chip [--limit N] [--mutant 1] [--out receipt.json] per hidden record (the 35B host - * reference's final hidden states): the full bf16 head + ARGMAX x2 as one list, the two-pass head (FP8 block - * screen, XBOUND, ARGMAX x2 for tau, MASK recheck, ARGMAX x2) as another; token identical, every candidate - * logit bit-identical to the full head's, timing of both lists. --mutant 1 (XBOUND without the bound) must - * lose tokens. Inputs from sc q36_exact_head export (weights stay outside git). - * Verdict line last: "gpu_exact_head_test: N checks, F failed: PASS|FAIL". - */ -#include "omega_blackwell_codegen_dec.h" -#include "omega_gpu_bf16_gemv_api.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_cmdlist.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include - -static unsigned g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } - -static void put64(uint32_t *cb, uint32_t off, const void *p) { uint64_t a = (uintptr_t)p; cb[off / 4] = (uint32_t)a; cb[off / 4 + 1] = (uint32_t)(a >> 32); } -/* launch argument words start at the constant bank's 0x380 */ -static void put64v(uint32_t *args, uint32_t off, uint64_t a) { args[(off - 0x380u) / 4] = (uint32_t)a; args[(off - 0x380u) / 4 + 1] = (uint32_t)(a >> 32); } - -/* XBOUND on n rows (grid ceil(n / 256), the last CTA partial). hscale spreads |h| over decades. Returns the number of - * rows whose lo / hi break the bound (or are loose by more than 2^-8 relative); *untouched = rows past n left alone. */ -static int sim_xbound(uint32_t n, int mutant, uint32_t seed, float hscale, size_t *bad, size_t *loose, int *untouched, char *msg, size_t msgn) { - static BlackwellIRProgram prog; - OmegaDecSpec spec; memset(&spec, 0, sizeof spec); - spec.kind = OMEGA_DEC_XBOUND; spec.mutant = mutant; - if (omega_blackwell_codegen_dec_prog(&spec, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - const uint32_t ctas = (n + 255u) / 256u, cap = ctas * 256u + 8u; - float *s = aligned_alloc(16, cap * 4), *c = aligned_alloc(16, cap * 4), *h = aligned_alloc(16, 2048 * 4); - float *lo = aligned_alloc(16, cap * 4), *hi = aligned_alloc(16, cap * 4); - uint8_t *smem = aligned_alloc(16, OMEGA_DEC_SHARED_BYTES); - uint32_t st = seed; - for (uint32_t i = 0; i < 2048; i++) h[i] = frand(&st, -1.0f, 1.0f) * hscale * (i % 97 == 0 ? 40.0f : 1.0f); - for (uint32_t i = 0; i < cap; i++) { - s[i] = frand(&st, -30.0f, 30.0f) * (i % 7 == 0 ? 1e3f : 1.0f); - c[i] = frand(&st, 0.0f, 0.02f); - lo[i] = hi[i] = -999.0f; - } - s[0] = 0.0f; c[1] = 0.0f; s[2] = -0.0f; - double hn = 0; for (uint32_t i = 0; i < 2048; i++) hn += (double)h[i] * h[i]; - hn = sqrt(hn); - WsSim w; memset(&w, 0, sizeof w); - w.p = &prog; w.threads = OMEGA_DEC_THREADS; w.order = (int)(seed & 1u); w.smem = smem; w.smem_bytes = OMEGA_DEC_SHARED_BYTES; - put64(w.cbank, OMEGA_DEC_XB_S, s); put64(w.cbank, OMEGA_DEC_XB_C, c); put64(w.cbank, OMEGA_DEC_XB_H, h); - put64(w.cbank, OMEGA_DEC_XB_LO, lo); put64(w.cbank, OMEGA_DEC_XB_HI, hi); w.cbank[OMEGA_DEC_XB_N / 4] = n; - w.nranges = 5; - w.ranges[0].lo = (uintptr_t)s; w.ranges[0].hi = (uintptr_t)(s + cap); - w.ranges[1].lo = (uintptr_t)c; w.ranges[1].hi = (uintptr_t)(c + cap); - w.ranges[2].lo = (uintptr_t)h; w.ranges[2].hi = (uintptr_t)(h + 2048); - w.ranges[3].lo = (uintptr_t)lo; w.ranges[3].hi = (uintptr_t)(lo + cap); - w.ranges[4].lo = (uintptr_t)hi; w.ranges[4].hi = (uintptr_t)(hi + cap); - int err = ws_run(&w, ctas, 1); - if (err) snprintf(msg, msgn, "%s (pc %d)", w.msg, w.err_pc); - else { - size_t b = 0, l = 0; - for (uint32_t i = 0; i < n; i++) { - const double B = (double)c[i] * hn, sv = s[i]; - if (!((double)lo[i] <= sv - B && (double)hi[i] >= sv + B)) b++; - const double slack = B * 0x1p-8 + fabs(sv) * 0x1p-19 + 1e-29; - if (sv - (double)lo[i] > B + slack || (double)hi[i] - sv > B + slack) l++; - } - int u = 1; for (uint32_t i = n; i < cap; i++) u &= lo[i] == -999.0f && hi[i] == -999.0f; - *bad = b; *loose = l; *untouched = u; - snprintf(msg, msgn, "%u rows: %zu break the bound, %zu looser than 2^-8, rows past count %s", n, b, l, u ? "untouched" : "WRITTEN"); - } - free(s); free(c); free(h); free(lo); free(hi); free(smem); - return err; -} - -/* XBOUND mode 1 (SCALE) on n values: out == in * 2^64 bit for bit, values past n untouched */ -static int sim_xscale(uint32_t n, uint32_t seed, size_t *bad, char *msg, size_t msgn) { - static BlackwellIRProgram prog; - OmegaDecSpec spec; memset(&spec, 0, sizeof spec); - spec.kind = OMEGA_DEC_XBOUND; spec.mode = 1; - if (omega_blackwell_codegen_dec_prog(&spec, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - const uint32_t ctas = (n + 255u) / 256u, cap = ctas * 256u + 8u; - float *in = aligned_alloc(16, cap * 4), *out = aligned_alloc(16, cap * 4); - uint32_t st = seed; - for (uint32_t i = 0; i < cap; i++) { in[i] = frand(&st, -3.0f, 3.0f) * (i % 5 == 0 ? 1e-20f : 1.0f); out[i] = -999.0f; } - in[0] = 0.0f; in[1] = -0.0f; in[2] = 1e30f; - WsSim w; memset(&w, 0, sizeof w); - w.p = &prog; w.threads = OMEGA_DEC_THREADS; w.order = (int)(seed & 1u); - put64(w.cbank, OMEGA_DEC_XB_S, in); put64(w.cbank, OMEGA_DEC_XB_LO, out); w.cbank[OMEGA_DEC_XB_N / 4] = n; - w.nranges = 2; - w.ranges[0].lo = (uintptr_t)in; w.ranges[0].hi = (uintptr_t)(in + cap); - w.ranges[1].lo = (uintptr_t)out; w.ranges[1].hi = (uintptr_t)(out + cap); - int err = ws_run(&w, ctas, 1); - if (err) snprintf(msg, msgn, "%s (pc %d)", w.msg, w.err_pc); - else { - size_t b = 0; - for (uint32_t i = 0; i < n; i++) { const float want = in[i] * 0x1p64f; b += memcmp(&out[i], &want, 4) != 0; } - for (uint32_t i = n; i < cap; i++) b += out[i] != -999.0f; - *bad = b; - snprintf(msg, msgn, "%u values: %zu differ from h * 2^64 or written past count", n, b); - } - free(in); free(out); - return err; -} - -static void sim_battery(void) { - static const struct { uint32_t n, seed; float hscale; } pts[] = { { 700, 3, 1.0f }, { 256, 4, 1e-3f }, { 1000, 5, 30.0f }, { 37, 6, 1.0f } }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - char msg[300]; size_t bad = 1, loose = 1; int u = 0; - int err = sim_xbound(pts[i].n, 0, pts[i].seed, pts[i].hscale, &bad, &loose, &u, msg, sizeof msg); - CHECK(!err && bad == 0 && loose == 0 && u, "sim XBOUND n %u: %s", pts[i].n, msg); - printf("sim XBOUND n %u |h| x%g: %s %s\n", pts[i].n, pts[i].hscale, err ? "ERROR" : bad || loose || !u ? "MISMATCH" : "ok", msg); - } - char msg[300]; size_t bad = 0, loose = 0; int u = 0; - int err = sim_xbound(700, 1, 3, 1.0f, &bad, &loose, &u, msg, sizeof msg); - CHECK(!err && bad != 0, "sim XBOUND mutant 1 must be caught: %s", msg); - printf("sim XBOUND mutant 1: %s %s\n", err ? "ERROR" : bad ? "caught" : "NOT CAUGHT", msg); - OmegaDecSpec m2; memset(&m2, 0, sizeof m2); m2.kind = OMEGA_DEC_XBOUND; m2.mutant = 2; - static BlackwellIRProgram p2; - CHECK(omega_blackwell_codegen_dec_prog(&m2, &p2) != 0, "XBOUND refuses mutant 2"); - for (uint32_t n2 = 2048; n2 >= 37; n2 = n2 == 2048 ? 37 : 0) { - size_t xb = 1; int xe = sim_xscale(n2, 7, &xb, msg, sizeof msg); - CHECK(!xe && xb == 0, "sim XBOUND SCALE n %u: %s", n2, msg); - printf("sim XBOUND SCALE n %u: %s %s\n", n2, xe ? "ERROR" : xb ? "MISMATCH" : "ok", msg); - } - m2.mutant = 1; m2.mode = 1; - CHECK(omega_blackwell_codegen_dec_prog(&m2, &p2) != 0, "XBOUND SCALE refuses a mutant"); -} - -/* ------------------------------------------------------------- chip */ -#define XH_N 248320u -#define XH_K 2048u -#define NEG_PAD (-1e30f) - -static void *read_all(const char *dir, const char *name, size_t want) { - char path[1024]; snprintf(path, sizeof path, "%s/%s", dir, name); - FILE *f = fopen(path, "rb"); if (!f) { printf("cannot open %s\n", path); return NULL; } - void *p = malloc(want ? want : 1); size_t got = p ? fread(p, 1, want, f) : 0; - int extra = fgetc(f) != EOF; fclose(f); - if (got != want || extra) { printf("%s: expected exactly %zu bytes\n", path, want); free(p); return NULL; } - return p; -} - -typedef struct { OmegaGpuMem code; uint32_t gpr; } XKern; -static int xkern(XKern *k, OmegaDecKind kind, uint32_t mode, int mutant) { - OmegaDecSpec s; memset(&s, 0, sizeof s); s.kind = kind; s.mode = mode; s.mutant = mutant; - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_dec_prog(&s, &prog) != 0) return -1; - size_t need = omega_bw_program_code_bytes(&prog); - if (!need || omega_gpu_session_alloc_code(need, &k->code) != 0) return -1; - OmegaBlackwellKernel kk; - if (omega_blackwell_kernel_encode_into(&prog, k->code.cpu, need, &kk) != 0 || kk.code_size != need) return -1; - if (omega_gpu_session_sync_to_gpu(&k->code) != 0) return -1; - k->gpr = omega_bw_gpr_declared(kk.gpr_count); if (k->gpr < 64u) k->gpr = 64u; - return 0; -} -static int xadd(OmegaGpuCmdList *cl, const XKern *k, uint32_t gx, 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 = 1; - L.num_elements = elems; L.args = args; L.n_args = n_args; L.timeout_ms = 20000; - return omega_gpu_cmdlist_add(cl, &L) < 0 ? -1 : 0; -} -/* ARGMAX x2 over v (padded to ctas * 2048): value -> out_v, index -> out_i */ -static int xargmax(OmegaGpuCmdList *cl, const XKern *a0k, const XKern *a1k, uint32_t ctas, uint64_t v, uint64_t amv, uint64_t ami, uint64_t out_v, uint64_t out_i) { - uint32_t a0[OMEGA_DEC_AM_WORDS], a1[OMEGA_DEC_AM_WORDS]; memset(a0, 0, sizeof a0); memset(a1, 0, sizeof a1); - put64v(a0, OMEGA_DEC_AM_V, v); put64v(a0, OMEGA_DEC_AM_OV, amv); put64v(a0, OMEGA_DEC_AM_OI, ami); - put64v(a1, OMEGA_DEC_AM_V, amv); put64v(a1, OMEGA_DEC_AM_I, ami); put64v(a1, OMEGA_DEC_AM_OV, out_v); put64v(a1, OMEGA_DEC_AM_OI, out_i); - if (xadd(cl, a0k, ctas, (size_t)ctas * OMEGA_DEC_ARGMAX_SPAN, a0, OMEGA_DEC_AM_WORDS)) return -1; - return xadd(cl, a1k, 1, OMEGA_DEC_ARGMAX_SPAN, a1, OMEGA_DEC_AM_WORDS); -} -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static double pct(uint64_t *v, size_t n, double p) { qsort(v, n, sizeof *v, cmp_u64); return (double)v[(size_t)((double)(n - 1) * p + 0.5)]; } - -/* Full head vs two-pass head on every hidden record: token identical, candidate logits bit-identical, timing. */ -static void chip(const char *dir, const char *hidden_path, uint32_t limit, int mutant, const char *out_path) { - const uint32_t n = XH_N, k = XH_K, ctas = (n + OMEGA_DEC_ARGMAX_SPAN - 1) / OMEGA_DEC_ARGMAX_SPAN, P = ctas * OMEGA_DEC_ARGMAX_SPAN; - uint16_t *head = read_all(dir, "head.bf16", (size_t)n * k * 2); - uint8_t *codes = read_all(dir, "fp8b.codes", (size_t)n * k); - uint16_t *scales = read_all(dir, "fp8b.scales", (size_t)(n / 128) * (k / 128) * 2); - float *coef = read_all(dir, "coef.f32", (size_t)n * 4); - FILE *hf = fopen(hidden_path, "rb"); - CHECK(head && codes && scales && coef && hf, "chip inputs readable (export dir %s, hidden %s)", dir, hidden_path); - if (!head || !codes || !scales || !coef || !hf) return; - fseek(hf, 0, SEEK_END); const size_t rec_bytes = 16 + 4 * (size_t)k, nrec_all = (size_t)ftell(hf) / rec_bytes; fseek(hf, 0, SEEK_SET); - const size_t nrec = limit && limit < nrec_all ? limit : nrec_all; - uint8_t *recs = malloc(nrec * rec_bytes); - CHECK(recs && fread(recs, rec_bytes, nrec, hf) == nrec, "read %zu hidden records", nrec); - fclose(hf); - OmegaGpuBf16Tensor *tb = NULL; OmegaGpuFp8Tensor *t8 = NULL; - int rb = omega_gpu_bf16_tensor_upload(n, k, head, &tb), r8 = omega_gpu_fp8_tensor_upload(1, n, k, codes, scales, &t8); - CHECK(rb == 0 && r8 == 0, "upload bf16 head (%d) and fp8b screen (%d): %s", rb, r8, omega_gpu_session_last_error()); - free(head); free(codes); free(scales); - if (rb || r8) return; - float *xw = calloc(k, 4), *yw = malloc((size_t)n * 4); xw[0] = 1.0f; - CHECK(omega_gpu_bf16_gemv_f32(tb, xw, yw, NULL) == 0 && omega_gpu_fp8_gemv_f32(t8, 0, xw, yw, NULL) == 0, "warm-up launches"); - free(xw); free(yw); - XKern kb, ka0, ka1; - /* cmdlist_create takes the session lock itself: create the lists before holding it (it is not recursive) */ - OmegaGpuCmdList *clF = NULL, *clT = NULL; - int cr = omega_gpu_cmdlist_create(16, &clF) | omega_gpu_cmdlist_create(16, &clT); - omega_gpu_session_lock(); - int kr = xkern(&kb, OMEGA_DEC_XBOUND, 0, mutant) | xkern(&ka0, OMEGA_DEC_ARGMAX, 0, 0) | xkern(&ka1, OMEGA_DEC_ARGMAX, 1, 0); - /* one buffer: h | h8 | s | coef | hi | lo (P) | y (P) | yf (P) | amv | ami | tau | tok | tokf | tab */ - const size_t o_h = 0, o_h8 = o_h + k * 4, o_s = o_h8 + k * 4, o_c = o_s + (size_t)n * 4, o_hi = o_c + (size_t)n * 4, o_lo = o_hi + (size_t)n * 4, - o_y = o_lo + (size_t)P * 4, o_yf = o_y + (size_t)P * 4, o_amv = o_yf + (size_t)P * 4, o_ami = o_amv + 8192, o_tau = o_ami + 8192, - o_tok = o_tau + 16, o_tokf = o_tok + 16, o_tab = o_tokf + 16, total = o_tab + 64; - OmegaGpuMem buf; memset(&buf, 0, sizeof buf); - int ar = omega_gpu_session_alloc(total, &buf); - CHECK(kr == 0 && ar == 0 && cr == 0, "kernels, buffer (%zu bytes) and command lists", total); - if (kr || ar || cr) { omega_gpu_session_unlock(); return; } - uint8_t *B = buf.cpu; const uint64_t V = buf.va; - memcpy(B + o_c, coef, (size_t)n * 4); free(coef); - for (uint32_t i = n; i < P; i++) { ((float *)(B + o_lo))[i] = NEG_PAD; ((float *)(B + o_y))[i] = NEG_PAD; ((float *)(B + o_yf))[i] = NEG_PAD; } - for (uint32_t i = 0; i < 2048; i++) ((float *)(B + o_amv))[i] = NEG_PAD; - uint64_t wva = 0, sva = 0; omega_gpu_fp8_tensor_entry(t8, 0, &wva, &sva); - memcpy(B + o_tab, &wva, 8); memcpy(B + o_tab + 8, &sva, 8); - uint64_t *tf = malloc(nrec * 8), *tt = malloc(nrec * 8); - size_t same = 0, host_same = 0, bits_bad = 0, missing = 0, csum = 0, cmax = 0, sub_fail = 0, *cs = malloc(nrec * sizeof *cs); - OmegaGpuCmdListOpts opts; memset(&opts, 0, sizeof opts); - for (size_t r = 0; r < nrec; r++) { - const uint8_t *rec = recs + r * rec_bytes; uint32_t host_full; memcpy(&host_full, rec + 12, 4); - float *h = (float *)(B + o_h), *h8 = (float *)(B + o_h8); - memcpy(h, rec + 16, (size_t)k * 4); - for (uint32_t i = 0; i < k; i++) h8[i] = h[i] * 0x1p64f; /* exact: a power of two */ - omega_gpu_cmdlist_reset(clF); omega_gpu_cmdlist_reset(clT); - int e = omega_gpu_session_sync_to_gpu(&buf); - e |= omega_gpu_bf16_gemv_record(clF, tb, V + o_h, V + o_yf); - e |= xargmax(clF, &ka0, &ka1, ctas, V + o_yf, V + o_amv, V + o_ami, V + o_tokf + 4, V + o_tokf); - e |= omega_gpu_fp8_gemv_grouped_record(clT, t8, 1, V + o_tab, V + o_h8, 1, V + o_s); - uint32_t xb[OMEGA_DEC_XB_WORDS]; memset(xb, 0, sizeof xb); - put64v(xb, OMEGA_DEC_XB_S, V + o_s); put64v(xb, OMEGA_DEC_XB_C, V + o_c); put64v(xb, OMEGA_DEC_XB_H, V + o_h); - put64v(xb, OMEGA_DEC_XB_LO, V + o_lo); put64v(xb, OMEGA_DEC_XB_HI, V + o_hi); xb[(OMEGA_DEC_XB_N - 0x380u) / 4] = n; - e |= xadd(clT, &kb, (n + OMEGA_DEC_THREADS - 1) / OMEGA_DEC_THREADS, n, xb, OMEGA_DEC_XB_WORDS); - e |= xargmax(clT, &ka0, &ka1, ctas, V + o_lo, V + o_amv, V + o_ami, V + o_tau, V + o_tau + 4); - e |= omega_gpu_bf16_gemv_mask_record(clT, tb, V + o_h, V + o_y, V + o_hi, V + o_tau); - e |= xargmax(clT, &ka0, &ka1, ctas, V + o_y, V + o_amv, V + o_ami, V + o_tok + 4, V + o_tok); - OmegaGpuCmdListStats sf, st; memset(&sf, 0, sizeof sf); memset(&st, 0, sizeof st); - if (!e) e = omega_gpu_cmdlist_submit(clF, &opts, &sf); - if (!e) e = omega_gpu_cmdlist_submit(clT, &opts, &st); - if (!e) e = omega_gpu_session_sync_to_cpu(&buf); - if (e) { sub_fail++; printf("record %zu: chip error: %s\n", r, omega_gpu_session_last_error()); break; } - uint32_t tok, tokf; memcpy(&tok, B + o_tok, 4); memcpy(&tokf, B + o_tokf, 4); - const float *y = (const float *)(B + o_y), *yf = (const float *)(B + o_yf); - size_t c = 0; - for (uint32_t i = 0; i < n; i++) { - if (y[i] == -INFINITY) continue; - c++; bits_bad += memcmp(&y[i], &yf[i], 4) != 0; - } - missing += tokf < n && y[tokf] == -INFINITY; - same += tok == tokf; host_same += tokf == host_full; - cs[r] = c; csum += c; if (c > cmax) cmax = c; - tf[r] = sf.elapsed_ns; tt[r] = st.elapsed_ns; - if (tok != tokf && mutant == 0) printf("record %zu: two-pass %u != full %u (|C| %zu)\n", r, tok, tokf, c); - } - omega_gpu_session_unlock(); - const size_t done = nrec - sub_fail; - if (mutant == 0) { - CHECK(sub_fail == 0 && same == done, "two-pass token == full head token on %zu / %zu records", same, done); - CHECK(bits_bad == 0 && missing == 0, "candidate logits bit-identical to the full head (%zu differ, %zu full argmax missing)", bits_bad, missing); - } else CHECK(sub_fail == 0 && same < done, "mutant %d must lose a token: %zu / %zu identical", mutant, same, done); - double cmean = done ? (double)csum / done : 0, c99 = done ? (double)pct(cs, done, 0.99) : 0; - double f50 = pct(tf, done, 0.5) / 1e3, t50 = pct(tt, done, 0.5) / 1e3, f99 = pct(tf, done, 0.99) / 1e3, t99 = pct(tt, done, 0.99) / 1e3; - printf("chip: %zu records, identical %zu, host-full agrees %zu, |C| mean %.1f p99 %.0f max %zu\n", done, same, host_same, cmean, c99, cmax); - printf("chip: full head list p50 %.1f us p99 %.1f us; two-pass list p50 %.1f us p99 %.1f us\n", f50, f99, t50, t99); - if (out_path) { - FILE *o = fopen(out_path, "w"); - if (o) { - fprintf(o, "{\n \"test\": \"gpu_exact_head_test\", \"mutant\": %d, \"records\": %zu, \"identical\": %zu, \"host_full_agrees\": %zu,\n", mutant, done, same, host_same); - fprintf(o, " \"candidate_bits_differ\": %zu, \"full_argmax_missing\": %zu, \"C_mean\": %.3f, \"C_p99\": %.0f, \"C_max\": %zu,\n", bits_bad, missing, cmean, c99, cmax); - fprintf(o, " \"full_list_us\": { \"p50\": %.2f, \"p99\": %.2f }, \"two_pass_list_us\": { \"p50\": %.2f, \"p99\": %.2f },\n", f50, f99, t50, t99); - fprintf(o, " \"bytes\": { \"full_head\": %" PRIu64 ", \"fp8b_screen\": %" PRIu64 ", \"coef\": %u, \"row\": %u }\n}\n", - (uint64_t)n * k * 2, (uint64_t)n * k + (uint64_t)(n / 128) * (k / 128) * 2, n * 4, k * 2); - fclose(o); - } - } - free(recs); free(tf); free(tt); free(cs); -} - -int main(int argc, char **argv) { - int sim = 0, mutant = 0; uint32_t limit = 0; const char *dir = NULL, *hidden = NULL, *out = NULL; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--chip") == 0 && i + 2 < argc) { dir = argv[++i]; hidden = argv[++i]; } - else if (strcmp(argv[i], "--limit") == 0 && i + 1 < argc) limit = (uint32_t)strtoul(argv[++i], NULL, 10); - else if (strcmp(argv[i], "--mutant") == 0 && i + 1 < argc) mutant = atoi(argv[++i]); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out = argv[++i]; - else { fprintf(stderr, "usage: gpu_exact_head_test --sim | --chip [--limit N] [--mutant 1] [--out receipt.json]\n"); return 2; } - } - if (sim) sim_battery(); - if (dir) chip(dir, hidden, limit, mutant, out); - printf("gpu_exact_head_test: %u checks, %u failed: %s\n", g_checks, g_failed, g_failed || !g_checks ? "FAIL" : "PASS"); - return g_failed || !g_checks ? 1 : 0; -} diff --git a/tests/gpu_fp8_api_test.c b/tests/gpu_fp8_api_test.c deleted file mode 100644 index 8fcf839dc..000000000 --- a/tests/gpu_fp8_api_test.c +++ /dev/null @@ -1,1175 +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. - */ - -/* gpu_fp8_api_test: OWN-30B Cut 6 / Cut 5 gate for omega_gpu_fp8_api (FP8 e4m3 block-scaled GEMV). - * - * ./gpu_fp8_api_test --host-only exhaustive 256-code e4m3 conversion vs the reference decode - * (subnormals, both zeros, NaN codes refused), pack refusals, - * codegen for every kernel shape (instruction and register budget), - * API argument refusals, listing by Omega's own disassembler - * ./gpu_fp8_api_test --sim the kernel through tests/bw_warp_sim.h (no chip): one-hot conversion - * of every code through the kernel, parity battery vs the double oracle - * (both fragment orders bit-identical), grouped experts, and the four - * mutants (1 scale dropped, 2 scale block frozen, 3 group table swapped, - * host no-fold) which the same check must catch - * ./gpu_fp8_api_test --out receipt.json chip gate: parity battery, mutants, grouped experts, then the - * bandwidth table (median of --reps calls) at the expert and attention shapes - * ./gpu_fp8_api_test --cold-single SPEED-1B: the decode graph's two single projections (qkv 5120 x 2048, o_proj 2048 x 4096), - * 16 copies rotated so L2 never holds the launch's weights; same report as --grouped-cold - * ./gpu_fp8_api_test --grouped-cold CUT5: the decode graph's two expert launches (gate_up 8 of 128 x 1536 x 2048, - * down 8 of 128 x 2048 x 768) with L2 defeated by rotating 16 disjoint expert - * sets; parity on every timed launch; mutants 1..4; GB/s and fraction of 237.2 - * knobs: --lane-bytes N --rows N --warps N --cta-budget N --reps N --spin-us N - * CUT5 variants: --coal 0|1 (A, coalesced output; default 1, AIEN_OMEGA_FP8_COAL=0 turns it off; --coal-default checks that) --wfirst 0|1 (B, weights before x); FP8_SIM_ALL_ORDERS=1 runs every - * simulated kernel in four warp orders (coal kernels always do) - * --sched 0|1 (CUT5 kernel schedule) --variant 1|2 --depth N --no-evict --only NAME - * --n N --k K: one custom point n x k instead of the battery (with mutants 1, 2, 4), e.g. 128256 x 2560 - * - * Pass rule per point: rc OK, every output within TOL of the double oracle relative to the accumulation - * scale (sum of |terms|). Host and simulator passes are never chip results. - */ -#include "omega_gpu_fp8_api.h" -#include "omega_blackwell_codegen_moe2.h" -#include "omega_blackwell_codegen_moe.h" -#include "omega_blackwell_matmul.h" -#include "omega_gpu_session.h" -#include "omega_gpu_cmdlist.h" -#include "omega_blackwell_qmd.h" /* OMEGA_BW_QMD_MAX_SHARED_BYTES (deep_default_check) */ -#include "bw_warp_sim.h" -#include "omega_sm121_disasm.h" -#include -#include -#include -#include -#include -#include -#include - -#define TOL 1e-5 -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static uint8_t rand_e4m3(uint32_t *s) { uint8_t b = (uint8_t)(lcg(s) >> 24); if (omega_fp8_e4m3_is_nan(b)) b = (uint8_t)(b - 1); return b; } -static uint16_t bf16_of(float f) { return omega_fp32_to_bf16(f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -/* ------------------------------------------------------------------ data */ -typedef struct { - uint32_t experts, n, k; - uint8_t *w; uint16_t *s; /* checkpoint layout */ -} Weights; -static void weights_make(Weights *W, uint32_t experts, uint32_t n, uint32_t k, uint32_t seed) { - W->experts = experts; W->n = n; W->k = k; - size_t wb = (size_t)experts * n * k, sc = (size_t)experts * (n / 128) * (k / 128); - W->w = aligned_alloc(64, (wb + 63) & ~(size_t)63); W->s = malloc(sc * 2); - uint32_t st = seed; - for (size_t i = 0; i < wb; i++) W->w[i] = rand_e4m3(&st); - for (size_t i = 0; i < sc; i++) W->s[i] = bf16_of(frand(&st, 0.001f, 0.1f) * ((lcg(&st) & 1) ? 1.0f : -1.0f)); -} -static void weights_free(Weights *W) { free(W->w); free(W->s); } - -/* max relative error of y (groups x n) against the oracle over the selected experts */ -static double parity(const Weights *W, uint32_t groups, const uint32_t *ids, const float *x, uint32_t x_rows, const float *y, size_t *bad) { - double worst = 0.0; size_t nbad = 0; - double *ref = malloc(W->n * sizeof *ref), *mag = malloc(W->n * sizeof *mag); - for (uint32_t g = 0; g < groups; g++) { - const uint8_t *w = W->w + (size_t)ids[g] * W->n * W->k; - const uint16_t *s = W->s + (size_t)ids[g] * (W->n / 128) * (W->k / 128); - omega_fp8_gemv_oracle(w, s, W->n, W->k, x + (size_t)(x_rows == 1 ? 0 : g) * W->k, ref, mag); - for (uint32_t r = 0; r < W->n; r++) { - double d = fabs(ref[r] - (double)y[(size_t)g * W->n + r]); - double rel = d / (mag[r] > 1e-30 ? mag[r] : 1e-30); - if (rel > worst) worst = rel; - if (rel >= TOL || isnan(y[(size_t)g * W->n + r])) nbad++; - } - } - free(ref); free(mag); - if (bad) *bad = nbad; - return worst; -} - -/* ---------------------------------------------- stall checker (CUT5) */ -/* Independent of the generator's pass (a different walk, as tests/gpu_tern_api_test.c does): for every fixed-latency - * write, scan forward summing stalls; any instruction that reads or overwrites one of its registers, any control - * instruction and any branch target reached before OMEGA_FP8_FIXED_LAT cycles is a violation. */ -static int fp8_chk_fixed(BlackwellIROpcode op) { - return op == BW_IR_IMAD || op == BW_IR_IMAD_WIDE || op == BW_IR_SHF_R || op == BW_IR_LOP3_AND || op == BW_IR_LOP3_XOR || - op == BW_IR_MOV_IMM || op == BW_IR_MOV_RZ || op == BW_IR_FFMA || op == BW_IR_FADD; -} -static int fp8_chk_overlap(const BlackwellIRProgram *p, int a, int b) { - if (a < 0 || b < 0) return 0; - const int pa = p->regalloc.vreg_to_phys[a], pb = p->regalloc.vreg_to_phys[b]; - if (pa < 0 || pb < 0) return 0; - const int na = (int)(p->regalloc.intervals[a].bundle_size ? p->regalloc.intervals[a].bundle_size : 1u); - const int nb = (int)(p->regalloc.intervals[b].bundle_size ? p->regalloc.intervals[b].bundle_size : 1u); - return pa < pb + nb && pb < pa + na; -} -/* CUT5 A/B structure counters (independent of the generator): instructions of one opcode, and global-load batches. A batch - * opens at a global load issued while no batch is open; any instruction whose wait mask holds the load scoreboard (bit 0 of - * the wait field, SB_GPR in the generator) closes it. One batch = one memory round trip the warp waits for. */ -static int fp8_count_op(const BlackwellIRProgram *p, BlackwellIROpcode op) { int n = 0; for (size_t i = 0; i < p->count; i++) n += p->insns[i].op == op; return n; } -static int fp8_load_batches(const BlackwellIRProgram *p) { - int n = 0, open = 0; - for (size_t i = 0; i < p->count; i++) { - const BlackwellIRInsn *in = &p->insns[i]; - if ((in->control >> 20) & 1u) open = 0; - const int gl = in->op == BW_IR_LDG_E || in->op == BW_IR_LDG_E_64 || in->op == BW_IR_LDG_E_128; - if (gl && !open) { n++; open = 1; } - } - return n; -} -static long fp8_stall_violations(const BlackwellIRProgram *p, uint64_t *cycles) { - static uint8_t tgt[BW_MAX_IR_INSNS + 1]; - memset(tgt, 0, sizeof tgt); - long bad = 0; uint64_t cyc = 0; - for (size_t i = 0; i < p->count; i++) { - const BlackwellIRInsn *in = &p->insns[i]; - cyc += (in->control >> 9) & 0xfu; - if (in->op == BW_IR_BRA || in->op == BW_IR_BSSY) { long t = (long)i + (long)(int32_t)in->imm; if (t >= 0 && t <= (long)p->count) tgt[t] = 1; } - } - for (size_t i = 0; i < p->count; i++) { - const BlackwellIRInsn *in = &p->insns[i]; - if (!fp8_chk_fixed(in->op) || in->dst_vreg < 0) continue; - uint32_t dist = 0; - for (size_t j = i + 1; j < p->count; j++) { - dist += (p->insns[j - 1].control >> 9) & 0xfu; - if (dist >= OMEGA_FP8_FIXED_LAT) break; - const BlackwellIRInsn *u = &p->insns[j]; - const BlackwellIROpcode o = u->op; - if (o == BW_IR_BRA || o == BW_IR_EXIT || o == BW_IR_BSSY || o == BW_IR_BSYNC || o == BW_IR_BAR_SYNC || tgt[j]) { bad++; break; } - if (fp8_chk_overlap(p, in->dst_vreg, u->dst_vreg) || fp8_chk_overlap(p, in->dst_vreg, u->src1_vreg) || - fp8_chk_overlap(p, in->dst_vreg, u->src2_vreg) || fp8_chk_overlap(p, in->dst_vreg, u->src3_vreg)) { bad++; break; } - } - } - if (cycles) *cycles = cyc; - return bad; -} - -/* ------------------------------------------------------------- host-only */ -static int sm121dis_check_v(int variant, const OmegaFp8GemvSpec *spec, const char *name); -static int sm121dis_check(const OmegaFp8GemvSpec *spec, const char *name) { return sm121dis_check_v(1, spec, name); } -static int sm121dis_check_v(int variant, const OmegaFp8GemvSpec *spec, const char *name) { - OmegaBlackwellKernel k; memset(&k, 0, sizeof k); - if ((variant == 2 ? omega_blackwell_codegen_fp8_gemv2(spec, &k) : omega_blackwell_codegen_fp8_gemv(spec, &k)) != 0) return -1; - char lst[96]; - snprintf(lst, sizeof lst, "/tmp/omega_fp8_%s_%d.sass.XXXXXX", name, (int)getpid()); - int fd = mkstemp(lst); /* private, unique listing; read back the same descriptor */ - FILE *f = fd >= 0 ? fdopen(fd, "w+") : NULL; - if (!f) { if (fd >= 0) close(fd); omega_blackwell_kernel_free(&k); return -1; } - int rc = omega_sm121_listing(k.code, k.code_size, f); - omega_blackwell_kernel_free(&k); - static const char *const must[] = { "LDG.E.128", "FFMA", "SHFL.DOWN", "BSSY", "BSYNC", "STG.E", "LOP3.LUT", "IMAD" }; - if (fflush(f) != 0 || fseek(f, 0, SEEK_SET) != 0) { fclose(f); return -1; } - FILE *l = f; - char line[512]; int seen[8] = {0}; int bad = 0, insns = 0; - while (fgets(line, sizeof line, l)) { - if (!strstr(line, "/*") || !strstr(line, "*/")) continue; /* every address line */ - insns++; - if (strstr(line, "?") || strstr(line, "error")) bad++; - if (strstr(line, ".FTZ")) { printf(" %s: flush-to-zero instruction: %s", name, line); bad++; } /* e4m3 subnormals travel as f32 subnormals */ - for (int i = 0; i < 8; i++) if (strstr(line, must[i])) seen[i] = 1; - } - if (ferror(l)) rc = -1; - if (fclose(l) != 0) rc = -1; - int miss = 0; - for (int i = 0; i < 8; i++) if (!seen[i]) { printf(" %s: sm121dis listing lacks %s\n", name, must[i]); miss++; } - printf("sm121dis %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst); - return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1; -} - -/* Variant A default (SPEED-A, 2026-10-17): coal is ON unless AIEN_OMEGA_FP8_COAL=0 (or set_coal(0)), and coal 0 gives back - * the earlier kernel (one STG per row, no BAR.SYNC, no shared slots) at the decode graph's two grouped expert shapes and the - * single-projection o_proj shape. make test-gpu-fp8 runs this once with the env unset and once with AIEN_OMEGA_FP8_COAL=0. */ -static int g_coal_arg; /* --coal given: the env default is not what is being tested */ -static void coal_default_check(void) { - const char *e = getenv("AIEN_OMEGA_FP8_COAL"); - const int want = (e && e[0] == '0' && e[1] == 0) ? 0 : 1; - CHECK(omega_gpu_fp8_coal() == want, "coal default %d with AIEN_OMEGA_FP8_COAL=%s (want %d)", omega_gpu_fp8_coal(), e ? e : "(unset)", want); - static const struct { uint32_t k, n, groups; const char *name; } sh[] = { - { 2048, 1536, 8, "gate_up 8 x 1536 x 2048" }, { 768, 2048, 8, "down 8 x 2048 x 768" }, { 4096, 2048, 1, "o_proj 2048 x 4096" } }; - for (int pass = 0; pass < 3; pass++) { - const int on = pass == 0 ? want : pass == 1 ? 0 : 1; - if (pass) omega_gpu_fp8_set_coal(on); - for (size_t q = 0; q < sizeof sh / sizeof sh[0]; q++) { - OmegaFp8GemvSpec sp; omega_gpu_fp8_spec_for(sh[q].k, sh[q].n, sh[q].groups, &sp); - const int fits = sp.warps * sp.rows <= 32u; - static BlackwellIRProgram p; - const int rc = omega_blackwell_codegen_fp8_gemv_prog(&sp, &p); - const int coal = on && fits, bar = rc == 0 ? fp8_count_op(&p, BW_IR_BAR_SYNC) : -1, stg = rc == 0 ? fp8_count_op(&p, BW_IR_STG_E) : -1; - CHECK(rc == 0 && sp.coal == (uint32_t)coal && stg == 1 && (sp.depth ? 1 : bar == coal) && (omega_fp8_gemv_shared_bytes(&sp) != 0) == (coal || sp.depth != 0), - "%s coal %d (pass %d, warps %u rows %u depth %u): spec.coal %u, STG %d, BAR.SYNC %d, shared %u", sh[q].name, on, pass, sp.warps, sp.rows, sp.depth, sp.coal, stg, bar, omega_fp8_gemv_shared_bytes(&sp)); - if (pass == 0) printf("coal default %d: %s warps %u rows %u depth %u -> spec.coal %u, STG %d, BAR.SYNC %d\n", want, sh[q].name, sp.warps, sp.rows, sp.depth, sp.coal, stg, bar); - } - } - omega_gpu_fp8_set_coal(want); -} - -/* Deep-kernel default (SPEED-1B, 2026-10-17): the automatic spec for the decode graph's qkv (5120 x 2048, 10.5 MB) is the deep - * kernel (depth KS = 4) unless AIEN_OMEGA_FP8_DEEP=0 (or set_deep(0)); o_proj (2048 x 4096) stays classic because its deep x stage - * would exceed the 16 KiB launch-descriptor shared limit; grouped expert launches stay classic. make test-gpu-fp8 runs this once - * with the env unset and once with AIEN_OMEGA_FP8_DEEP=0. */ -static void deep_default_check(void) { - const char *e = getenv("AIEN_OMEGA_FP8_DEEP"); - const int want = (e && e[0] == '0' && e[1] == 0) ? 0 : 1; - CHECK(omega_gpu_fp8_deep() == want, "deep default %d with AIEN_OMEGA_FP8_DEEP=%s (want %d)", omega_gpu_fp8_deep(), e ? e : "(unset)", want); - for (int pass = 0; pass < 3; pass++) { - const int on = pass == 0 ? want : pass == 1 ? 0 : 1; - if (pass) omega_gpu_fp8_set_deep(on); - OmegaFp8GemvSpec q, o, gu; omega_gpu_fp8_spec_for(2048, 5120, 1, &q); omega_gpu_fp8_spec_for(4096, 2048, 1, &o); omega_gpu_fp8_spec_for(2048, 1536, 8, &gu); - CHECK(q.depth == (on ? 4u : 0u) && o.depth == 0 && gu.depth == 0, "deep %d (pass %d): qkv depth %u (want %u), o_proj depth %u (want 0), gate_up depth %u (want 0)", on, pass, q.depth, on ? 4u : 0u, o.depth, gu.depth); - OmegaFp8GemvSpec od = o; od.depth = 4096u / (32u * od.lane_bytes); od.mutant = 0; - CHECK(omega_fp8_gemv_shared_bytes(&od) > OMEGA_GPU_FP8_DEEP_MAX_SHARED_BYTES, "o_proj deep x stage %u bytes must exceed the %u-byte measured deep bound (why it stays classic)", omega_fp8_gemv_shared_bytes(&od), OMEGA_GPU_FP8_DEEP_MAX_SHARED_BYTES); - if (on) CHECK(omega_fp8_gemv_shared_bytes(&q) != 0 && omega_fp8_gemv_shared_bytes(&q) <= OMEGA_GPU_FP8_DEEP_MAX_SHARED_BYTES, "qkv deep shared %u bytes within the measured deep bound", omega_fp8_gemv_shared_bytes(&q)); - if (pass == 0) printf("deep default %d: qkv 5120x2048 depth %u (coal %u, shared %u), o_proj 2048x4096 depth %u, gate_up 8x1536x2048 depth %u\n", want, q.depth, q.coal, omega_fp8_gemv_shared_bytes(&q), o.depth, gu.depth); - } - /* The choice runs on every launch and every graph record (48 qkv records per token). SPEED-1B graph A/B: an unremembered - * register check (full codegen per call) cost 853..1172 us of host record time per token. Bound: 4800 calls (100 tokens of - * qkv records) under 20 ms in total (< ~4 us per call); the codegen path is ~17 us per call. */ - { - omega_gpu_fp8_set_deep(1); - OmegaFp8GemvSpec q; omega_gpu_fp8_spec_for(2048, 5120, 1, &q); /* warm */ - struct timespec t0, t1; clock_gettime(CLOCK_MONOTONIC, &t0); - uint32_t dsum = 0; - for (int i = 0; i < 4800; i++) { omega_gpu_fp8_spec_for(2048, 5120, 1, &q); dsum += q.depth; } - clock_gettime(CLOCK_MONOTONIC, &t1); - const double ms = (double)(t1.tv_sec - t0.tv_sec) * 1e3 + (double)(t1.tv_nsec - t0.tv_nsec) / 1e6; - CHECK(dsum == 4800u * 4u && ms < 20.0, "4800 qkv spec_for calls (deep on): %.2f ms, depth sum %u (want < 20 ms, %u)", ms, dsum, 4800u * 4u); - printf("deep default: 4800 qkv spec_for calls %.3f ms\n", ms); - } - omega_gpu_fp8_set_deep(want); -} - -/* qwen38/decode-speed: the host quantiser (FP8 lm_head). Every e4m3 rounding against a brute-force nearest-code search - * (ties to the even code, saturation at 448, never 0x7F), then a block round trip against the upload format's maths. */ -static double e4m3_val(unsigned c) { unsigned e = (c >> 3) & 15u, m = c & 7u; double v = e ? (1.0 + m / 8.0) * pow(2.0, (int)e - 7) : m / 8.0 * pow(2.0, -6); return (c & 0x80u) ? -v : v; } -static unsigned e4m3_brute(float v) { - double a = fabs((double)v); unsigned best = 0; double bd = 1e300; - if (a >= 448.0) return (v < 0 ? 0x80u : 0u) | 0x7Eu; - for (unsigned c = 0; c <= 0x7Eu; c++) { double d = fabs(e4m3_val(c) - a); if (d < bd || (d == bd && !(c & 1u))) { bd = d; best = c; } } - return ((v < 0 || (v == 0 && signbit(v))) ? 0x80u : 0u) | best; -} -static void e4m3_quant_check(void) { - int bad = 0, nan = 0; uint32_t s = 12345u; - for (unsigned c = 0; c <= 0x7Eu; c++) { /* every code, the midpoints to both neighbours, and their negatives */ - float pts[3] = { (float)e4m3_val(c), c ? (float)((e4m3_val(c) + e4m3_val(c - 1)) / 2) : 0.0f, c < 0x7E ? (float)((e4m3_val(c) + e4m3_val(c + 1)) / 2) : 460.0f }; - for (int i = 0; i < 3; i++) for (int sg = 0; sg < 2; sg++) { float v = sg ? -pts[i] : pts[i]; unsigned q = omega_gpu_fp8_e4m3_rne(v); if (q != e4m3_brute(v)) bad++; if ((q & 0x7Fu) == 0x7Fu) nan++; } - } - for (int i = 0; i < 200000; i++) { /* random magnitudes over 2^-12 .. 2^10 */ - s = s * 1664525u + 1013904223u; float m = (float)(s >> 8) / 16777216.0f; s = s * 1664525u + 1013904223u; - float v = (1.0f + m) * ldexpf(1.0f, (int)(s >> 27) - 12 - (int)((s >> 20) & 3u)); if (s & 1u) v = -v; - unsigned q = omega_gpu_fp8_e4m3_rne(v); if (q != e4m3_brute(v)) bad++; if ((q & 0x7Fu) == 0x7Fu) nan++; - } - CHECK(bad == 0 && nan == 0, "e4m3 rounding: %d codes differ from the brute-force nearest-even, %d NaN codes", bad, nan); - CHECK(omega_gpu_fp8_e4m3_rne(1e30f) == 0x7Eu && omega_gpu_fp8_e4m3_rne(-1e30f) == 0xFEu && omega_gpu_fp8_e4m3_rne(0.0f) == 0u, "e4m3 saturation and zero"); - /* block round trip: 256 x 384 bf16 with a zero block, w8 * scale within half an e4m3 step of w, scale >= amax / 448 */ - enum { N = 256, K = 384 }; static uint16_t w[N * K], sc[(N / 128) * (K / 128)]; static uint8_t w8[N * K]; - for (int i = 0; i < N * K; i++) { s = s * 1664525u + 1013904223u; float f = ((float)(s >> 8) / 16777216.0f - 0.5f) * ((i / K) < 128 ? 0.02f : 3.0f); uint32_t b; memcpy(&b, &f, 4); w[i] = (uint16_t)(b >> 16); } - for (int r = 0; r < 128; r++) for (int c = 128; c < 256; c++) w[r * K + c] = 0; - CHECK(omega_gpu_fp8_quantize_bf16(N, K, w, w8, sc) == OMEGA_GPU_FP8_OK, "quantize 256 x 384"); - int far = 0, nanq = 0; double worst = 0; - for (int r = 0; r < N; r++) for (int c = 0; c < K; c++) { - uint32_t b = (uint32_t)sc[(r / 128) * (K / 128) + c / 128] << 16; float scf; memcpy(&scf, &b, 4); - uint32_t wb = (uint32_t)w[r * K + c] << 16; float wf; memcpy(&wf, &wb, 4); - double back = e4m3_val(w8[r * K + c]) * scf, err = fabs(back - wf), rel = err / fabs((double)wf ? wf : 1); - if ((w8[r * K + c] & 0x7Fu) == 0x7Fu) nanq++; - if (w8[r * K + c] != e4m3_brute(wf / scf)) far++; - if (wf != 0 && fabs(wf) > 0.1 * scf && rel > worst) worst = rel; - } - CHECK(far == 0 && nanq == 0 && worst <= 0.0625 + 1e-9, "quantize round trip: %d codes off the nearest, %d NaN, worst rel %.4f (<= 1/16)", far, nanq, worst); - CHECK(sc[1] == 0x3F80u, "all-zero block gets scale 1 (0x%04x)", sc[1]); - uint16_t inf[128 * 128] = { 0 }; inf[77] = 0x7F80u; uint8_t o8[128 * 128]; uint16_t os[1]; - CHECK(omega_gpu_fp8_quantize_bf16(128, 128, inf, o8, os) == OMEGA_GPU_FP8_BAD_ARGS, "quantize refuses an inf weight"); -} - -/* qwen38/decode-speed: the big-k rule's choices (chip parity of these specs: fp8par1 in the speed handoff) */ -static void bigk_check(void) { - static const struct { uint32_t n, k, warps, depth; } want[] = { { 34816, 5120, 16, 5 }, { 16384, 5120, 16, 5 }, { 14336, 5120, 16, 5 }, - { 5120, 6144, 16, 6 }, { 5120, 17408, 16, 0 }, { 2048, 4096, 8, 0 }, { 5120, 2048, 8, 4 } }; - for (int on = 0; on < 2; on++) { - omega_gpu_fp8_set_bigk(on); - for (size_t i = 0; i < sizeof want / sizeof want[0]; i++) { - OmegaFp8GemvSpec sp; omega_gpu_fp8_spec_for(want[i].k, want[i].n, 1, &sp); - const int big = on && want[i].k > 4096u; - const uint32_t ww = big ? want[i].warps : 8u, wd = big ? want[i].depth : (want[i].k == 2048u ? 4u : 0u); - CHECK(sp.warps == ww && sp.depth == wd && sp.coal == 1u, "bigk %d: %ux%u warps %u depth %u coal %u (want %u, %u, 1)", on, want[i].n, want[i].k, sp.warps, sp.depth, sp.coal, ww, wd); - } - OmegaFp8GemvSpec g8; omega_gpu_fp8_spec_for(5120, 34816, 8, &g8); - CHECK(g8.warps == 32u && g8.depth == 0u, "bigk %d: grouped launches keep 32 warps, classic (warps %u depth %u)", on, g8.warps, g8.depth); - } - omega_gpu_fp8_set_bigk(1); /* the default */ -} - -static void host_only(void) { - e4m3_quant_check(); - bigk_check(); - if (!g_coal_arg) coal_default_check(); - deep_default_check(); - /* 1. exhaustive conversion: kernel bits * 2^120 == reference, bit for bit, for every non-NaN code; - * sign of zero preserved; NaN codes are exactly 0x7f and 0xff and are refused by the scan */ - int exact = 0, nan_codes = 0, zero_sign_ok = 0, f32_subnormal = 0; - for (int b = 0; b < 256; b++) { - float ref = omega_fp8_e4m3_ref((uint8_t)b); - uint32_t kb = omega_fp8_e4m3_kernel_bits((uint8_t)b); - float kf; memcpy(&kf, &kb, 4); - /* the kernel-side f32 is subnormal exactly for the e4m3 subnormal codes (exponent field 0, mantissa != 0): - * the chip must not flush them (no .FTZ instruction in the listing, chip one-hot test) */ - if ((kb & 0x7f800000u) == 0 && (kb & 0x007fffffu) != 0) { f32_subnormal++; CHECK((b & 0x78) == 0 && (b & 7) != 0, "code 0x%02x maps to an f32 subnormal but is not an e4m3 subnormal", b); } - else CHECK((b & 0x78) != 0 || (b & 7) == 0, "e4m3 subnormal code 0x%02x maps to a normal f32", b); - float kv = ldexpf(kf, 120); /* exact: a power-of-two scaling (host, no flush to zero) */ - if (isnan(ref)) { nan_codes++; CHECK(omega_fp8_e4m3_is_nan((uint8_t)b), "code 0x%02x is NaN in the reference and must be flagged", b); continue; } - CHECK(!omega_fp8_e4m3_is_nan((uint8_t)b), "code 0x%02x is finite in the reference and must not be flagged", b); - uint32_t rb, vb; memcpy(&rb, &ref, 4); memcpy(&vb, &kv, 4); - if (rb == vb) exact++; - CHECK(rb == vb, "code 0x%02x: kernel conversion %a (bits %08x) != reference %a (bits %08x)", b, kv, vb, ref, rb); - if (ref == 0.0f) { if (signbit(ref) == signbit(kv)) zero_sign_ok++; } - /* the fold is exact as two steps too (x * 2^64 then * 2^56) */ - CHECK(ldexpf(ldexpf(kf, OMEGA_FP8_X_EXP), OMEGA_FP8_SCALE_EXP) == ref, "code 0x%02x: split fold not exact", b); - } - CHECK(exact == 254 && nan_codes == 2 && zero_sign_ok == 2, "conversion: %d exact, %d NaN codes, %d zero signs (want 254, 2, 2)", exact, nan_codes, zero_sign_ok); - CHECK(f32_subnormal == 14, "f32-subnormal kernel values: %d (want 14: +-0x01..0x07)", f32_subnormal); - printf("conversion: %d/256 exact, %d NaN codes refused, %d codes travel as f32 subnormals (2^-129 .. 7 * 2^-129): the chip must not flush them\n", exact, nan_codes, f32_subnormal); - /* subnormal spot values from the e4m3 definition */ - CHECK(omega_fp8_e4m3_ref(0x01) == ldexpf(1.0f, -9) && omega_fp8_e4m3_ref(0x07) == 7.0f * ldexpf(1.0f, -9), "subnormal spot values"); - CHECK(omega_fp8_e4m3_ref(0x7e) == 448.0f && omega_fp8_e4m3_ref(0xfe) == -448.0f && omega_fp8_e4m3_ref(0x38) == 1.0f, "normal spot values"); - /* conversion mutant: skipping the fold is caught by the same comparison */ - { float kf; uint32_t kb = omega_fp8_e4m3_kernel_bits(0x38); memcpy(&kf, &kb, 4); CHECK(kf != 1.0f, "fold mutant: unfolded bits must not equal the value"); } - - /* 2. pack refusals */ - { uint8_t w[8] = { 0x38, 0x7f, 0x00, 0xff, 1, 2, 3, 4 }; size_t first = 99; - CHECK(omega_fp8_pack_scan_nan(w, 8, &first) == 2 && first == 1, "NaN scan finds both codes, first at 1"); - CHECK(omega_fp8_pack_scan_nan(w, 1, &first) == 0, "NaN scan clean prefix"); } - { uint16_t s[3] = { bf16_of(0.5f), 0x7fc0 /* NaN */, bf16_of(1.0f) }; float o[3]; - CHECK(omega_fp8_pack_scales(s, 1, o, 0) == 0 && o[0] == ldexpf(0.5f, OMEGA_FP8_SCALE_EXP), "scale fold exact"); - CHECK(omega_fp8_pack_scales(s, 3, o, 0) != 0, "NaN scale refused"); - s[1] = 0x7f80; CHECK(omega_fp8_pack_scales(s, 3, o, 0) != 0, "inf scale refused"); - s[1] = bf16_of(3.0e38f); CHECK(omega_fp8_pack_scales(s, 3, o, 0) != 0, "fold overflow refused"); - CHECK(omega_fp8_pack_scales(s, 1, o, 1) == 0 && o[0] == 0.5f, "no-fold mutant pack"); } - { float x[4] = { 1.0f, -2.0f, 0.5f, 0.0f }, o[4]; omega_fp8_pack_x_f32(x, 4, o); - CHECK(o[0] == ldexpf(1.0f, 64) && o[1] == ldexpf(-2.0f, 64) && o[3] == 0.0f, "x fold exact"); } - - /* 3. codegen: every shape builds inside the budgets; refusals */ - static const uint32_t ks[] = { 128, 256, 768, 2048, 4096, 16384, 17408, 32768 }; - static const uint32_t lbs[] = { 8, 16 }, rows[] = { 1, 2, 4, 8 }; - uint32_t worst_insns = 0, worst_gprs = 0; int built = 0; - for (size_t a = 0; a < sizeof ks / sizeof ks[0]; a++) for (size_t b = 0; b < 2; b++) for (size_t c = 0; c < 4; c++) for (int m = 0; m <= 3; m++) for (int deep = 0; deep < 2; deep++) { - OmegaFp8GemvSpec sp = { .k = ks[a], .lane_bytes = lbs[b], .rows = rows[c], .warps = 8, .mutant = m }; - uint32_t ni, ng; - if (ks[a] % (32 * lbs[b])) { CHECK(omega_fp8_gemv_prog_stats(&sp, &ni, &ng) != 0, "k=%u lb=%u must be refused", ks[a], lbs[b]); continue; } - if (deep) { sp.depth = ks[a] / (32 * lbs[b]); if (sp.depth * sp.rows * lbs[b] > 128 || ks[a] > 4096) { CHECK(omega_fp8_gemv_prog_stats(&sp, &ni, &ng) != 0, "deep k=%u lb=%u rows=%u must be refused", ks[a], lbs[b], rows[c]); continue; } } - int rc = omega_fp8_gemv_prog_stats(&sp, &ni, &ng); - CHECK(rc == 0, "codegen k=%u lb=%u rows=%u mutant=%d deep=%d", ks[a], lbs[b], rows[c], m, deep); - if (rc == 0) { built++; if (ni > worst_insns) worst_insns = ni; if (ng > worst_gprs) worst_gprs = ng; } - } - printf("codegen: %d kernels built, largest %u IR instructions, peak %u GPRs\n", built, worst_insns, worst_gprs); - CHECK(worst_insns <= BW_MAX_IR_INSNS && worst_gprs <= 128, "budgets"); - { OmegaFp8GemvSpec bad = { .k = 192, .lane_bytes = 8, .rows = 1, .warps = 1 }; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "k not a multiple of 128 refused"); - bad.k = 256; bad.lane_bytes = 4; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "lane_bytes 4 refused (LDG.E has no immediate offset)"); bad.lane_bytes = 8; - bad.k = 2048; bad.rows = 3; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "rows 3 refused"); - bad.rows = 8; bad.warps = 33; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "warps 33 refused"); - bad.warps = 8; bad.lane_bytes = 32; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "lane_bytes 32 refused"); - bad.lane_bytes = 16; bad.k = OMEGA_FP8_MAX_K + 512u; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "k past the limit refused"); } - /* Register file (chip-found 2026-10-13): 32 * warps * declared registers must be <= 65536; the API refuses the launch. - * The deep k=2048 kernel at 32 warps (72 declared x 1024 threads = 73728) faulted on the chip with Xid 13. */ - { OmegaFp8GemvSpec deep = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 32, .depth = 4 }; uint32_t gp = 0; - CHECK(omega_fp8_gemv_prog_stats(&deep, NULL, &gp) == 0, "deep4 k2048 encodes"); - uint32_t decl = ((gp + 1u + 7u) / 8u) * 8u; - CHECK(32u * 32u * decl > 65536u, "deep4 k2048 at 32 warps needs %u declared registers x 1024 threads: over the 65536 file", decl); - uint32_t de = 0; int rf = omega_gpu_fp8_kernel_fits(&deep, &de); - CHECK(rf == OMEGA_GPU_FP8_TOO_LARGE && de == decl, "API refuses the register-file overflow (rc %d, declared %u): %s", rf, de, omega_gpu_fp8_last_error()); - deep.warps = 16; CHECK(omega_gpu_fp8_kernel_fits(&deep, NULL) == OMEGA_GPU_FP8_OK, "the same kernel at 16 warps fits"); - deep.depth = 0; deep.warps = 32; CHECK(omega_gpu_fp8_kernel_fits(&deep, NULL) == OMEGA_GPU_FP8_OK, "the classic kernel at 32 warps fits"); - deep.depth = 4; CHECK(omega_gpu_fp8_depth_for(&deep, 2048, 1) == 0, "automatic depth falls back to classic when deep would overflow the register file"); } - - /* 4. API refusals that need no device */ - { OmegaGpuFp8Tensor *t = NULL; uint8_t w[128 * 128]; uint16_t s[1] = { bf16_of(1.0f) }; memset(w, 0x38, sizeof w); - CHECK(omega_gpu_fp8_tensor_upload(1, 128, 128, NULL, s, &t) == OMEGA_GPU_FP8_BAD_ARGS, "NULL w refused"); - CHECK(omega_gpu_fp8_tensor_upload(1, 100, 128, w, s, &t) == OMEGA_GPU_FP8_BAD_ARGS, "n not a multiple of 128 refused"); - CHECK(omega_gpu_fp8_tensor_upload(1, 128, OMEGA_FP8_MAX_K + 256u, w, s, &t) == OMEGA_GPU_FP8_TOO_LARGE, "k past the limit refused"); - w[77] = 0xff; CHECK(omega_gpu_fp8_tensor_upload(1, 128, 128, w, s, &t) == OMEGA_GPU_FP8_NAN_WEIGHT && t == NULL, "NaN weight refused before any device work"); - CHECK(strstr(omega_gpu_fp8_last_error(), "byte 77") != NULL, "error names the byte (%s)", omega_gpu_fp8_last_error()); - float y[8]; CHECK(omega_gpu_fp8_gemv_f32(NULL, 0, y, y, NULL) == OMEGA_GPU_FP8_BAD_ARGS, "NULL tensor refused"); } - - /* 5. sm121dis listing of the production shapes */ - { OmegaFp8GemvSpec a = { .k = 2048, .lane_bytes = 16, .rows = 8, .warps = 8 }, b = { .k = 768, .lane_bytes = 8, .rows = 2, .warps = 8 }; - CHECK(sm121dis_check(&a, "k2048_lb16_r8") == 0, "sm121dis listing k=2048"); - OmegaFp8GemvSpec d = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 8, .depth = 4 }; - CHECK(sm121dis_check(&d, "k2048_lb16_r1_deep4") == 0, "sm121dis listing deep k=2048"); - CHECK(sm121dis_check(&b, "k768_lb8_r2") == 0, "sm121dis listing k=768"); } - - /* 6. variant 2 (W-L2c, omega_blackwell_codegen_moe2.c): every OWN-30B width builds inside the budgets at 16 warps, - * the production shapes fit the register file, the whole-row-group rule refuses what it must */ - { - static const uint32_t k2[] = { 768, 2048, 4096 }, r2[] = { 1, 2, 4 }; - uint32_t worst_i = 0, worst_g = 0; int built2 = 0; - for (size_t a = 0; a < 3; a++) for (size_t c = 0; c < 3; c++) for (int m = 0; m <= 3; m++) { - OmegaFp8GemvSpec sp = { .k = k2[a], .lane_bytes = k2[a] % 512u == 0 ? 16u : 8u, .rows = r2[c], .warps = 16, .mutant = m }; - uint32_t ks = sp.k / (32u * sp.lane_bytes), ni = 0, ng = 0; - int rc = omega_fp8_gemv2_prog_stats(&sp, &ni, &ng); - if (sp.rows * ks * sp.lane_bytes > 128u) { CHECK(rc != 0, "v2 k=%u rows=%u must be refused (row group past 128 bytes per lane)", sp.k, sp.rows); continue; } - CHECK(rc == 0 && ni <= BW_MAX_IR_INSNS, "v2 codegen k=%u lb=%u rows=%u mutant=%d: rc %d, %u insns", sp.k, sp.lane_bytes, sp.rows, m, rc, ni); - if (rc == 0) { built2++; if (ni > worst_i) worst_i = ni; if (ng > worst_g) worst_g = ng; if (m == 0) printf("v2 codegen k=%u lb=%u rows=%u: %u insns, peak %u GPRs, declared %u\n", sp.k, sp.lane_bytes, sp.rows, ni, ng, omega_bw_gpr_declared(ng)); } - } - printf("v2 codegen: %d kernels built, largest %u IR instructions, peak %u GPRs\n", built2, worst_i, worst_g); - /* the production shapes at the variant's default (16 warps, 1 row) must fit the 65536-register file */ - omega_gpu_fp8_set_variant(2); - static const uint32_t kp[] = { 768, 2048, 4096 }; - for (size_t a = 0; a < 3; a++) { - OmegaFp8GemvSpec sp = { .k = kp[a], .lane_bytes = kp[a] % 512u == 0 ? 16u : 8u, .rows = 1, .warps = OMEGA_GPU_FP8_V2_WARPS }; - uint32_t decl = 0; int rf = omega_gpu_fp8_kernel_fits(&sp, &decl); - CHECK(rf == OMEGA_GPU_FP8_OK && 32u * sp.warps * decl <= 65536u, "v2 k=%u at %u warps fits the register file (rc %d, declared %u)", sp.k, sp.warps, rf, decl); - printf("v2 k=%u rows=1 warps=%u: declared %u registers, %u per SM at one CTA\n", sp.k, sp.warps, decl, 32u * sp.warps * decl); - } - omega_gpu_fp8_set_variant(1); - { OmegaFp8GemvSpec bad = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 2 }; CHECK(omega_fp8_gemv2_prog_stats(&bad, NULL, NULL) != 0, "v2 k=2048 at 2 warps refused (staging rounds)"); - bad.warps = 16; bad.k = 16384; CHECK(omega_fp8_gemv2_prog_stats(&bad, NULL, NULL) != 0, "v2 k=16384 refused (row past 128 bytes per lane)"); - bad.k = 2048; bad.lane_bytes = 8; bad.rows = 2; CHECK(omega_fp8_gemv2_prog_stats(&bad, NULL, NULL) == 0, "v2 k=2048 lb8 rows=2 (128 bytes per lane) builds"); } - OmegaFp8GemvSpec v = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 16 }; - CHECK(sm121dis_check_v(2, &v, "v2_k2048_lb16_r1_w16") == 0, "sm121dis listing v2 k=2048"); - } - - /* 7. sched 1 (CUT5): pipelined decode + dependency stall pass. Every battery shape builds; the two grouped expert - * shapes fit the register file at 32 warps; an independent walk finds no user closer than OMEGA_FP8_FIXED_LAT - * cycles to a fixed-latency write; shortening one binding stall must be caught (the checker can say no); the - * sched 0 programs pass the same checker (they stall 6 everywhere) */ - { - int built1 = 0; long viol_all = 0; - for (size_t a = 0; a < sizeof ks / sizeof ks[0]; a++) for (size_t b = 0; b < 2; b++) for (size_t c = 0; c < 4; c++) for (int m = 0; m <= 3; m++) for (int deep = 0; deep < 2; deep++) { - OmegaFp8GemvSpec sp = { .k = ks[a], .lane_bytes = lbs[b], .rows = rows[c], .warps = 8, .mutant = m, .sched = 1 }; - if (ks[a] % (32 * lbs[b])) continue; - if (deep) { sp.depth = ks[a] / (32 * lbs[b]); if (sp.depth * sp.rows * lbs[b] > 128 || ks[a] > 4096) continue; } - static BlackwellIRProgram cp; - int rc = omega_blackwell_codegen_fp8_gemv_prog(&sp, &cp); - CHECK(rc == 0 && cp.count <= BW_MAX_IR_INSNS, "sched1 codegen k=%u lb=%u rows=%u mutant=%d deep=%d", sp.k, sp.lane_bytes, sp.rows, m, deep); - if (rc != 0) continue; - built1++; - long v = fp8_stall_violations(&cp, NULL); - viol_all += v; - CHECK(v == 0, "sched1 stall distances k=%u lb=%u rows=%u mutant=%d deep=%d: %ld users closer than %u cycles", sp.k, sp.lane_bytes, sp.rows, m, deep, v, OMEGA_FP8_FIXED_LAT); - } - printf("sched1 codegen: %d kernels built, %ld stall-distance violations\n", built1, viol_all); - static const struct { uint32_t k, lb; const char *name; } prod[] = { { 2048, 16, "gate_up k2048 lb16" }, { 768, 8, "down k768 lb8" } }; - for (size_t q = 0; q < 2; q++) { - static BlackwellIRProgram p0, p1; - OmegaFp8GemvSpec s0 = { .k = prod[q].k, .lane_bytes = prod[q].lb, .rows = 1, .warps = 32 }, s1 = s0; s1.sched = 1; - uint32_t d1 = 0, g1 = 0, g0 = 0; - const int ok = omega_blackwell_codegen_fp8_gemv_prog(&s0, &p0) == 0 && omega_blackwell_codegen_fp8_gemv_prog(&s1, &p1) == 0; - CHECK(ok, "sched 0 and 1 build at %s 32 warps", prod[q].name); - if (!ok) continue; - CHECK(omega_fp8_gemv_prog_stats(&s0, NULL, &g0) == 0 && omega_fp8_gemv_prog_stats(&s1, NULL, &g1) == 0, "stats %s", prod[q].name); - CHECK(omega_gpu_fp8_kernel_fits(&s1, &d1) == OMEGA_GPU_FP8_OK, "sched1 %s at 32 warps fits the register file (declared %u): %s", prod[q].name, d1, omega_gpu_fp8_last_error()); - uint64_t c0 = 0, c1 = 0; - const long v0 = fp8_stall_violations(&p0, &c0), v1 = fp8_stall_violations(&p1, &c1); - CHECK(v0 == 0 && v1 == 0, "%s stall distances: sched0 %ld, sched1 %ld violations", prod[q].name, v0, v1); - /* negative control: the pass gives each instruction its smallest legal stall, so a fixed-latency stall above 1 - * is binding; shortening the first one to 1 must be caught by the independent walk */ - size_t at = p1.count; - for (size_t i = 0; i < p1.count; i++) if (fp8_chk_fixed(p1.insns[i].op) && ((p1.insns[i].control >> 9) & 0xfu) > 1u) { at = i; break; } - if (at < p1.count) p1.insns[at].control = (p1.insns[at].control & ~(0xfu << 9)) | (1u << 9); - CHECK(at < p1.count && fp8_stall_violations(&p1, NULL) > 0, "%s: stall checker catches one shortened stall", prod[q].name); - printf("sched1 %s w32: %zu insns (sched0 %zu), peak %u GPRs (sched0 %u), declared %u; stall cycles in program order %" PRIu64 " (sched0 %" PRIu64 "); shortened-stall control caught\n", - prod[q].name, p1.count, p0.count, g1, g0, d1, c1, c0); - } - { OmegaFp8GemvSpec bad = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 8, .sched = 2 }; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "sched 2 refused"); } - } - - /* 8. CUT5 variants A (coal: coalesced output through shared slots) and B (wfirst: weight loads before the x' loads). - * Every battery shape builds in every combination with sched 0 and 1 (sched 1 with no stall violation); the refusals - * hold; for the two grouped expert shapes at 32 warps: the register file fits, A has one STG and one BAR.SYNC per - * round and declares the two slot sets, and B removes exactly one load round trip per K step (fp8_load_batches: - * a global load that follows a wait on the load scoreboard opens a new batch). Default programs keep their batch - * count, so the counter says "no" when nothing changed (deep kernels, which ignore wfirst). */ - { - int built = 0; long viol = 0; - for (size_t a = 0; a < sizeof ks / sizeof ks[0]; a++) for (size_t b = 0; b < 2; b++) for (size_t c = 0; c < 4; c++) - for (int m = 0; m <= 5; m++) for (int deep = 0; deep < 2; deep++) for (int cw = 1; cw < 4; cw++) for (int sch = 0; sch < 2; sch++) { - OmegaFp8GemvSpec sp = { .k = ks[a], .lane_bytes = lbs[b], .rows = rows[c], .warps = 4, .mutant = m, .sched = (uint32_t)sch, .coal = (uint32_t)(cw & 1), .wfirst = (uint32_t)(cw >> 1) }; - if (ks[a] % (32 * lbs[b]) || (m >= 4 && !sp.coal)) continue; - if (deep) { sp.depth = ks[a] / (32 * lbs[b]); if (sp.depth * sp.rows * lbs[b] > 128 || ks[a] > 2048) continue; } - static BlackwellIRProgram cp; - int rc = omega_blackwell_codegen_fp8_gemv_prog(&sp, &cp); - CHECK(rc == 0 && cp.count <= BW_MAX_IR_INSNS, "A/B codegen k=%u lb=%u rows=%u mutant=%d deep=%d coal=%u wfirst=%u sched=%d", sp.k, sp.lane_bytes, sp.rows, m, deep, sp.coal, sp.wfirst, sch); - if (rc != 0) continue; - built++; - if (sch) { long v = fp8_stall_violations(&cp, NULL); viol += v; CHECK(v == 0, "A/B sched1 stall distances k=%u lb=%u rows=%u coal=%u wfirst=%u: %ld", sp.k, sp.lane_bytes, sp.rows, sp.coal, sp.wfirst, v); } - } - printf("A/B codegen: %d kernels built (coal, wfirst, both x sched 0/1 x mutants), %ld stall-distance violations\n", built, viol); - { OmegaFp8GemvSpec bad = { .k = 2048, .lane_bytes = 16, .rows = 2, .warps = 32, .coal = 1 }; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "coal refused at warps x rows = 64"); - bad.rows = 1; bad.coal = 2; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "coal 2 refused"); - bad.coal = 0; bad.wfirst = 2; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "wfirst 2 refused"); - bad.wfirst = 0; bad.mutant = 4; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "mutant 4 refused without coal"); } - static const struct { uint32_t k, lb; const char *name; } prod[] = { { 2048, 16, "gate_up k2048 lb16" }, { 768, 8, "down k768 lb8" } }; - for (size_t q = 0; q < 2; q++) { - static BlackwellIRProgram p0, pa, pb, pab; - OmegaFp8GemvSpec s0 = { .k = prod[q].k, .lane_bytes = prod[q].lb, .rows = 1, .warps = 32 }, sa = s0, sb = s0, sab = s0; - sa.coal = 1; sb.wfirst = 1; sab.coal = 1; sab.wfirst = 1; - const int ok = omega_blackwell_codegen_fp8_gemv_prog(&s0, &p0) == 0 && omega_blackwell_codegen_fp8_gemv_prog(&sa, &pa) == 0 && - omega_blackwell_codegen_fp8_gemv_prog(&sb, &pb) == 0 && omega_blackwell_codegen_fp8_gemv_prog(&sab, &pab) == 0; - CHECK(ok, "A, B, A+B build at %s 32 warps", prod[q].name); - if (!ok) continue; - uint32_t da = 0, db = 0, dab = 0; - CHECK(omega_gpu_fp8_kernel_fits(&sa, &da) == OMEGA_GPU_FP8_OK && omega_gpu_fp8_kernel_fits(&sb, &db) == OMEGA_GPU_FP8_OK && omega_gpu_fp8_kernel_fits(&sab, &dab) == OMEGA_GPU_FP8_OK, - "%s A/B/A+B fit the register file at 32 warps (declared %u %u %u)", prod[q].name, da, db, dab); - const int stg0 = fp8_count_op(&p0, BW_IR_STG_E), stga = fp8_count_op(&pa, BW_IR_STG_E), bar0 = fp8_count_op(&p0, BW_IR_BAR_SYNC), bara = fp8_count_op(&pa, BW_IR_BAR_SYNC); - CHECK(stg0 == 1 && stga == 1 && bar0 == 0 && bara == 1 && omega_fp8_gemv_shared_bytes(&sa) == 2u * 32u * 4u && omega_fp8_gemv_shared_bytes(&s0) == 0, - "%s A: STG %d (default %d), BAR.SYNC %d (default %d), shared %u bytes", prod[q].name, stga, stg0, bara, bar0, omega_fp8_gemv_shared_bytes(&sa)); - const int b0 = fp8_load_batches(&p0), bb = fp8_load_batches(&pb), ba = fp8_load_batches(&pa), bab = fp8_load_batches(&pab); - CHECK(b0 - bb == 1 && ba - bab == 1, "%s B: load batches default %d -> wfirst %d, coal %d -> coal+wfirst %d (one round trip less per K step)", prod[q].name, b0, bb, ba, bab); - OmegaFp8GemvSpec sd = s0, sdb; sd.warps = 8; sd.depth = omega_fp8_gemv_steps(&sd); sdb = sd; sdb.wfirst = 1; - static BlackwellIRProgram pd, pdb; - const int okd = omega_blackwell_codegen_fp8_gemv_prog(&sd, &pd) == 0 && omega_blackwell_codegen_fp8_gemv_prog(&sdb, &pdb) == 0; - CHECK(okd && fp8_load_batches(&pd) == fp8_load_batches(&pdb) && pd.count == pdb.count, "%s deep: wfirst changes nothing (batches %d, %d)", prod[q].name, okd ? fp8_load_batches(&pd) : -1, okd ? fp8_load_batches(&pdb) : -1); - printf("A/B %s w32: insns %zu / A %zu / B %zu / A+B %zu; declared regs A %u B %u A+B %u; load batches %d / %d / %d / %d\n", - prod[q].name, p0.count, pa.count, pb.count, pab.count, da, db, dab, b0, ba, bb, bab); - } - } -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -static int g_sim_variant = 1; /* which generator sim_gemv runs: 1 (omega_blackwell_codegen_moe.c) or 2 (moe2.c, W-L2c) */ -/* Runs the kernel for (W, groups, ids, x, x_rows) on the warp simulator in both fragment orders. Returns 0 and y - * on success, -1 on a simulator error or an order-dependent result. */ -static int sim_gemv(const OmegaFp8GemvSpec *spec, const Weights *W, uint32_t groups, const uint32_t *ids, const float *x, - uint32_t x_rows, float *y, uint32_t cta_budget, int no_fold, char *msg, size_t msglen) { - static BlackwellIRProgram prog; - if ((g_sim_variant == 2 ? omega_blackwell_codegen_fp8_gemv2_prog(spec, &prog) : omega_blackwell_codegen_fp8_gemv_prog(spec, &prog)) != 0) { snprintf(msg, msglen, "codegen refused"); return -1; } - const uint32_t n = W->n, k = W->k, RG = n / spec->rows; - size_t sc = (size_t)W->experts * (n / 128) * (k / 128); - float *sf = aligned_alloc(16, ((sc * 4) + 15) & ~(size_t)15); - if (omega_fp8_pack_scales(W->s, sc, sf, no_fold) != 0) { free(sf); snprintf(msg, msglen, "scale pack refused"); return -1; } - float *xf = aligned_alloc(16, ((size_t)x_rows * k * 4 + 15) & ~(size_t)15); - for (uint32_t r = 0; r < x_rows; r++) omega_fp8_pack_x_f32(x + (size_t)r * k, k, xf + (size_t)r * k); - uint64_t *tab = aligned_alloc(16, 16 * (size_t)groups); - for (uint32_t g = 0; g < groups; g++) { - tab[2 * g] = (uintptr_t)(W->w + (size_t)ids[g] * n * k); - tab[2 * g + 1] = (uintptr_t)(sf + (size_t)ids[g] * (n / 128) * (k / 128)); - } - float *yd = aligned_alloc(16, ((size_t)groups * n * 4 + 15) & ~(size_t)15); - float *copy = malloc((size_t)groups * n * 4); - uint32_t grid_x = (RG + spec->warps - 1) / spec->warps; if (grid_x > cta_budget) grid_x = cta_budget; if (!grid_x) grid_x = 1; - int err = 0; - const int runs = (spec->coal || getenv("FP8_SIM_ALL_ORDERS")) ? 4 : 2; /* coal: also descending and shuffled warp visit orders per barrier phase (slot races) */ - for (int run = 0; run < runs && !err; run++) { - const int order = run == 1; - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32 * spec->warps; s.order = order; s.warp_sched = run == 2 ? 1u : run == 3 ? 0x9e3779b9u : 0u; - static uint8_t smem[OMEGA_FP8_MAX_K * 4 + 4096]; s.smem = smem; s.smem_bytes = g_sim_variant == 2 ? omega_fp8_gemv2_shared_bytes(spec) : omega_fp8_gemv_shared_bytes(spec); /* the bytes the launch declares (0: any shared access fails) */ - uint64_t ta = (uintptr_t)tab, xa = (uintptr_t)xf, ya = (uintptr_t)yd; - s.cbank[OMEGA_FP8_ARG_TAB / 4] = (uint32_t)ta; s.cbank[OMEGA_FP8_ARG_TAB / 4 + 1] = (uint32_t)(ta >> 32); - s.cbank[OMEGA_FP8_ARG_X / 4] = (uint32_t)xa; s.cbank[OMEGA_FP8_ARG_X / 4 + 1] = (uint32_t)(xa >> 32); - s.cbank[OMEGA_FP8_ARG_Y / 4] = (uint32_t)ya; s.cbank[OMEGA_FP8_ARG_Y / 4 + 1] = (uint32_t)(ya >> 32); - s.cbank[OMEGA_FP8_ARG_RG / 4] = RG; s.cbank[OMEGA_FP8_ARG_XSTRIDE / 4] = x_rows == 1 ? 0 : k * 4; - s.cbank[OMEGA_FP8_ARG_YSTRIDE / 4] = n * 4; s.cbank[OMEGA_FP8_ARG_STRIDE / 4] = grid_x * spec->warps; - /* every global access must land in a declared buffer */ - s.nranges = 4; - s.ranges[0].lo = (uintptr_t)W->w; s.ranges[0].hi = (uintptr_t)W->w + (size_t)W->experts * n * k; - s.ranges[1].lo = (uintptr_t)sf; s.ranges[1].hi = (uintptr_t)sf + sc * 4; - s.ranges[2].lo = (uintptr_t)xf; s.ranges[2].hi = (uintptr_t)xf + (size_t)x_rows * k * 4; - s.ranges[3].lo = (uintptr_t)yd; s.ranges[3].hi = (uintptr_t)yd + (size_t)groups * n * 4; - /* the table is read too */ - s.nranges = 5; s.ranges[4].lo = (uintptr_t)tab; s.ranges[4].hi = (uintptr_t)tab + 16 * (size_t)groups; - for (size_t i = 0; i < (size_t)groups * n; i++) yd[i] = -999.0f; - err = ws_run(&s, grid_x, groups); - if (err) { snprintf(msg, msglen, "run %d (order %d, warp order %u): %s", run, order, s.warp_sched, s.msg); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (size_t i = 0; i < (size_t)groups * n; i++) if (yd[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, msglen, "%zu output words never written", unwritten); break; } - if (run == 0) memcpy(copy, yd, (size_t)groups * n * 4); - else if (memcmp(copy, yd, (size_t)groups * n * 4) != 0) { if (getenv("FP8_SIM_DIFF")) { int c = 0; for (size_t i = 0; i < (size_t)groups * n && c < 12; i++) if (memcmp(©[i], &yd[i], 4)) { fprintf(stderr, " diff y[%zu] %g vs %g\n", i, copy[i], yd[i]); c++; } } err = -1; snprintf(msg, msglen, "run %d (order %d, warp order %u) changed the result", run, order, s.warp_sched); } - } - if (!err) memcpy(y, yd, (size_t)groups * n * 4); - free(sf); free(xf); free(tab); free(yd); free(copy); - return err ? -1 : 0; -} - -typedef struct { uint32_t experts, n, k, groups, x_rows, lb, rows, warps; const char *name; } SimPoint; - -static void sim_battery(uint32_t cta_budget) { - char msg[240]; - /* 1. one-hot conversion through the kernel: 254 rows, row r holds code r at column 0 (NaN codes replaced by - * 0x00), x = e_0, scale 1: y[r] must equal the reference exactly (zero rows compare as 0) */ - { - Weights W; W.experts = 1; W.n = 256; W.k = 256; - W.w = aligned_alloc(64, 256 * 256); memset(W.w, 0, 256 * 256); - W.s = malloc(4 * 2); for (int b = 0; b < 4; b++) W.s[b] = bf16_of(1.0f); - for (int r = 0; r < 256; r++) W.w[r * 256] = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0 : (uint8_t)r; - float x[256] = { 0 }; x[0] = 1.0f; float y[256]; uint32_t id = 0; - OmegaFp8GemvSpec sp = { .k = 256, .lane_bytes = 8, .rows = 8, .warps = 4 }; - int rc = sim_gemv(&sp, &W, 1, &id, x, 1, y, cta_budget, 0, msg, sizeof msg); - CHECK(rc == 0, "one-hot sim run: %s", msg); - int exact = 0; - if (rc == 0) for (int r = 0; r < 256; r++) { - float ref = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0.0f : omega_fp8_e4m3_ref((uint8_t)r); - if (y[r] == ref) exact++; else { CHECK(0, "one-hot code 0x%02x: kernel %a, reference %a", r, y[r], ref); } - } - printf("sim one-hot conversion: %d/256 rows exact\n", exact); - /* x on the other lanes/words: code at column c, x = e_c for c in {1, 17, 127} on one row each */ - for (int t = 0; t < 3; t++) { - const int cols[3] = { 1, 17, 255 }; const uint8_t codes[3] = { 0xc0, 0x05, 0x7e }; - memset(W.w, 0, 256 * 256); W.w[3 * 256 + cols[t]] = codes[t]; - memset(x, 0, sizeof x); x[cols[t]] = -2.5f; for (int b = 0; b < 4; b++) W.s[b] = bf16_of(0.75f); - rc = sim_gemv(&sp, &W, 1, &id, x, 1, y, cta_budget, 0, msg, sizeof msg); - CHECK(rc == 0 && y[3] == omega_fp8_e4m3_ref(codes[t]) * -2.5f * 0.75f, "one-hot column %d code 0x%02x: %a vs %a (%s)", cols[t], codes[t], rc == 0 ? y[3] : 0.0f, omega_fp8_e4m3_ref(codes[t]) * -2.5f * 0.75f, msg); - } - weights_free(&W); - } - /* 2. parity battery */ - static const SimPoint pts[] = { - { 1, 128, 256, 1, 1, 8, 1, 1, "k256 lb8 r1 w1" }, - { 1, 256, 256, 1, 1, 8, 2, 2, "k256 lb8 r2 w2" }, - { 1, 256, 768, 1, 1, 8, 4, 8, "k768 lb8 r4 w8 (down shape width)" }, - { 1, 256, 768, 1, 1, 8, 8, 8, "k768 lb8 r8" }, - { 1, 384, 2048, 1, 1, 16, 8, 8, "k2048 lb16 r8 w8 (gate shape width)" }, - { 1, 128, 2048, 1, 1, 16, 1, 8, "k2048 lb16 r1" }, - { 1, 256, 512, 1, 1, 16, 2, 3, "k512 lb16 r2 w3 (odd warps, tail row groups)" }, - { 4, 256, 2048, 4, 1, 16, 8, 8, "4 experts shared x (gate+up)" }, - { 6, 256, 768, 8, 8, 8, 4, 8, "8 groups per-group x, repeated ids (down)" }, - { 3, 128, 256, 2, 2, 8, 8, 4, "2 groups per-group x" }, - { 2, 256, 768, 2, 2, 8, 1, 7, "k768 w7: partial staging round (deep)" }, - { 1, 128, 17408, 1, 1, 16, 2, 8, "k17408 lb16 r2 w8 (Qwen3.8-27B down width, step kernel)" }, - }; - const size_t npts = sizeof pts / sizeof pts[0]; - double worst_all = 0.0; - for (size_t i = 0; i < npts; i++) { - const SimPoint *p = &pts[i]; - Weights W; weights_make(&W, p->experts, p->n, p->k, 1000 + (uint32_t)i); - uint32_t ids[8]; uint32_t st = 77 + (uint32_t)i; - for (uint32_t g = 0; g < p->groups; g++) ids[g] = lcg(&st) % p->experts; - float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f); - float *y = malloc((size_t)p->groups * p->n * 4); - /* every point runs the step-by-step kernel (depth 0) and, when the row fits, the deep kernel (depth = KS) */ - for (int deep = 0; deep < 2; deep++) { - OmegaFp8GemvSpec sp = { .k = p->k, .lane_bytes = p->lb, .rows = p->rows, .warps = p->warps }; - if (deep) { sp.depth = omega_fp8_gemv_steps(&sp); if (sp.depth * sp.rows * sp.lane_bytes > 128 || p->k > 512 * p->warps) continue; } - char nm[96]; snprintf(nm, sizeof nm, "%s%s", p->name, deep ? " deep" : ""); - double t0 = now_ms(); - int rc = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y, cta_budget, 0, msg, sizeof msg); - size_t bad = 0; double worst = rc == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y, &bad) : 1.0; - if (worst > worst_all) worst_all = worst; - CHECK(rc == 0 && bad == 0, "sim %s: rc=%d bad=%zu worst_rel=%.3e %s", nm, rc, bad, worst, msg); - printf("sim %-45s rc=%d worst_rel=%.3e bad=%zu (%.0f ms)\n", nm, rc, worst, bad, now_ms() - t0); - /* mutants on the two grouped points and the first two single points: each must be caught */ - if (i == 1 || i == 4 || i == 7 || i == 8) { - for (int m = 1; m <= 4; m++) { - if (m == 3 && p->groups == 1) continue; /* group swap needs two groups */ - if (m == 2 && omega_fp8_gemv_steps(&sp) < 2) { printf("sim %s mutant 2: one K step, control not applicable\n", p->name); continue; } - OmegaFp8GemvSpec ms = sp; ms.mutant = m == 4 ? 0 : m; - rc = sim_gemv(&ms, &W, p->groups, ids, x, p->x_rows, y, cta_budget, m == 4, msg, sizeof msg); - bad = 0; worst = rc == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y, &bad) : 1.0; - int caught = rc != 0 || bad > 0; - if (m == 3 && rc == 0) { /* the ids must differ for the swap to show; make sure the control is meaningful */ - int distinct = 0; for (uint32_t g = 0; g + 1 < p->groups; g += 2) if (ids[g] != ids[g ^ 1]) distinct = 1; - if (!distinct) { printf("sim %s mutant 3: ids pairwise equal, control skipped\n", p->name); continue; } - } - CHECK(caught, "sim %s mutant %d NOT caught (worst_rel=%.3e)", nm, m, worst); - printf("sim %-45s mutant %d: %s (rc=%d bad=%zu worst_rel=%.3e)\n", nm, m, caught ? "caught" : "MISSED", rc, bad, worst); - } - } - } - free(x); free(y); weights_free(&W); - } - printf("sim battery: worst relative error %.3e over %zu points, %" PRIu64 " warp issues\n", worst_all, npts, g_sim_issues); - - /* 3. variant 2 (W-L2c): y bit-identical to variant 1 on every point (same arithmetic order), parity against the oracle, - * mutants caught; the identity check is shown to say "no" on a mutant */ - { - static const SimPoint v2pts[] = { - { 1, 256, 2048, 1, 1, 16, 1, 8, "v2 k2048 lb16 r1 w8 (gate_up/qkv width)" }, - { 1, 256, 2048, 1, 1, 16, 2, 8, "v2 k2048 lb16 r2 w8 (128 B per lane)" }, - { 1, 256, 4096, 1, 1, 16, 1, 8, "v2 k4096 lb16 r1 w8 (o_proj width)" }, - { 1, 256, 768, 1, 1, 8, 1, 8, "v2 k768 lb8 r1 w8 (down width)" }, - { 1, 256, 768, 1, 1, 8, 4, 8, "v2 k768 lb8 r4 w8" }, - { 2, 256, 768, 2, 2, 8, 1, 7, "v2 k768 w7: partial staging round" }, - { 4, 256, 2048, 4, 1, 16, 1, 8, "v2 4 experts shared x (gate_up)" }, - { 6, 256, 768, 8, 8, 8, 2, 8, "v2 8 groups per-group x, repeated ids (down)" }, - { 3, 128, 256, 2, 2, 8, 8, 4, "v2 2 groups per-group x, r8 k256" }, - { 1, 256, 512, 1, 1, 16, 2, 3, "v2 k512 w3 (odd warps, tail row groups)" }, - }; - const size_t n2 = sizeof v2pts / sizeof v2pts[0]; - int identical = 0; - for (size_t i = 0; i < n2; i++) { - const SimPoint *p = &v2pts[i]; - Weights W; weights_make(&W, p->experts, p->n, p->k, 5000 + (uint32_t)i); - uint32_t ids[8]; uint32_t st = 177 + (uint32_t)i; - for (uint32_t g = 0; g < p->groups; g++) ids[g] = lcg(&st) % p->experts; - float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f); - const size_t ny = (size_t)p->groups * p->n; - float *y1 = malloc(ny * 4), *y2 = malloc(ny * 4); - OmegaFp8GemvSpec sp = { .k = p->k, .lane_bytes = p->lb, .rows = p->rows, .warps = p->warps }; - g_sim_variant = 1; int rc1 = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y1, cta_budget, 0, msg, sizeof msg); - CHECK(rc1 == 0, "v1 reference for %s: %s", p->name, msg); - double t0 = now_ms(); - g_sim_variant = 2; int rc2 = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y2, cta_budget, 0, msg, sizeof msg); - size_t bad = 0; double worst = rc2 == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y2, &bad) : 1.0; - int same = rc1 == 0 && rc2 == 0 && memcmp(y1, y2, ny * 4) == 0; - CHECK(rc2 == 0 && bad == 0 && same, "sim %s: rc=%d bad=%zu worst_rel=%.3e identical_to_v1=%d %s", p->name, rc2, bad, worst, same, msg); - if (same) identical++; - printf("sim %-48s rc=%d worst_rel=%.3e bad=%zu identical_to_v1=%d (%.0f ms)\n", p->name, rc2, worst, bad, same, now_ms() - t0); - if (i == 0 || i == 6 || i == 7) { - for (int m = 1; m <= 3; m++) { - if (m == 3 && p->groups == 1) continue; - OmegaFp8GemvSpec ms = sp; ms.mutant = m; - int rcm = sim_gemv(&ms, &W, p->groups, ids, x, p->x_rows, y2, cta_budget, 0, msg, sizeof msg); - bad = 0; worst = rcm == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y2, &bad) : 1.0; - int caught = rcm != 0 || bad > 0, differs = rcm != 0 || memcmp(y1, y2, ny * 4) != 0; - if (m == 3 && rcm == 0) { int distinct = 0; for (uint32_t g = 0; g + 1 < p->groups; g += 2) if (ids[g] != ids[g ^ 1]) distinct = 1; if (!distinct) { printf("sim %s mutant 3: ids pairwise equal, control skipped\n", p->name); continue; } } - CHECK(caught && differs, "sim %s mutant %d NOT caught (bad=%zu worst_rel=%.3e identity says %s)", p->name, m, bad, worst, differs ? "different" : "SAME"); - printf("sim %-48s mutant %d: %s (rc=%d bad=%zu worst_rel=%.3e, identity check differs=%d)\n", p->name, m, caught ? "caught" : "MISSED", rcm, bad, worst, differs); - } - } - g_sim_variant = 1; - free(x); free(y1); free(y2); weights_free(&W); - } - printf("sim v2 battery: %d/%zu points bit-identical to variant 1\n", identical, n2); - } - - /* 4. sched 1 (CUT5): y bit-identical to sched 0 on every battery point (step and deep kernels), parity against the - * oracle, mutants 1..3 caught on the grouped points; the identity check is shown to say "no" on a mutant */ - { - int identical = 0, runs = 0; - for (size_t i = 0; i < npts; i++) { - const SimPoint *p = &pts[i]; - Weights W; weights_make(&W, p->experts, p->n, p->k, 1000 + (uint32_t)i); - uint32_t ids[8]; uint32_t st = 77 + (uint32_t)i; - for (uint32_t g = 0; g < p->groups; g++) ids[g] = lcg(&st) % p->experts; - float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f); - const size_t ny = (size_t)p->groups * p->n; - float *y0 = malloc(ny * 4), *y1 = malloc(ny * 4); - for (int deep = 0; deep < 2; deep++) { - OmegaFp8GemvSpec sp = { .k = p->k, .lane_bytes = p->lb, .rows = p->rows, .warps = p->warps }; - if (deep) { sp.depth = omega_fp8_gemv_steps(&sp); if (sp.depth * sp.rows * sp.lane_bytes > 128 || p->k > 512 * p->warps) continue; } - char nm[96]; snprintf(nm, sizeof nm, "sched1 %s%s", p->name, deep ? " deep" : ""); - int rc0 = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y0, cta_budget, 0, msg, sizeof msg); - CHECK(rc0 == 0, "sched0 reference for %s: %s", nm, msg); - OmegaFp8GemvSpec s1 = sp; s1.sched = 1; - int rc1 = sim_gemv(&s1, &W, p->groups, ids, x, p->x_rows, y1, cta_budget, 0, msg, sizeof msg); - size_t bad = 0; double worst = rc1 == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y1, &bad) : 1.0; - int same = rc0 == 0 && rc1 == 0 && memcmp(y0, y1, ny * 4) == 0; - CHECK(rc1 == 0 && bad == 0 && same, "sim %s: rc=%d bad=%zu worst_rel=%.3e identical_to_sched0=%d %s", nm, rc1, bad, worst, same, msg); - runs++; if (same) identical++; - printf("sim %-52s rc=%d worst_rel=%.3e bad=%zu identical_to_sched0=%d\n", nm, rc1, worst, bad, same); - if (i == 7 || i == 8) { - for (int m = 1; m <= 3; m++) { - if (m == 2 && omega_fp8_gemv_steps(&sp) < 2) continue; - OmegaFp8GemvSpec ms = s1; ms.mutant = m; - int rcm = sim_gemv(&ms, &W, p->groups, ids, x, p->x_rows, y1, cta_budget, 0, msg, sizeof msg); - bad = 0; worst = rcm == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y1, &bad) : 1.0; - int caught = rcm != 0 || bad > 0, differs = rcm != 0 || memcmp(y0, y1, ny * 4) != 0; - CHECK(caught && differs, "sim %s mutant %d NOT caught (bad=%zu worst_rel=%.3e identity says %s)", nm, m, bad, worst, differs ? "different" : "SAME"); - printf("sim %-52s mutant %d: %s (rc=%d bad=%zu worst_rel=%.3e, identity check differs=%d)\n", nm, m, caught ? "caught" : "MISSED", rcm, bad, worst, differs); - } - } - } - free(x); free(y0); free(y1); weights_free(&W); - } - printf("sim sched1 battery: %d/%d runs bit-identical to sched 0\n", identical, runs); - } - - /* 5. CUT5 variants A (coal) and B (wfirst), alone and together: y bit-identical to the default on every battery point - * where A applies (warps * rows <= 32), step and deep kernels, parity against the oracle; coal kernels run in four - * orders (fragment order both ways, warps descending and shuffled per barrier phase). Mutants: 4 (one slot set) must - * be caught by a warp order (points with two or more rounds per CTA), 5 (no clamp) on the points whose last round is - * partial (6, 10), 1..3 on the A+B kernel of point 8 (1, 2 also on point 9). */ - { - int identical = 0, runs = 0; - for (size_t i = 0; i < npts; i++) { - const SimPoint *p = &pts[i]; - Weights W; weights_make(&W, p->experts, p->n, p->k, 1000 + (uint32_t)i); - uint32_t ids[8]; uint32_t st = 77 + (uint32_t)i; - for (uint32_t g = 0; g < p->groups; g++) ids[g] = lcg(&st) % p->experts; - float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f); - const size_t ny = (size_t)p->groups * p->n; - float *y0 = malloc(ny * 4), *y1 = malloc(ny * 4); - for (int deep = 0; deep < 2; deep++) { - OmegaFp8GemvSpec sp = { .k = p->k, .lane_bytes = p->lb, .rows = p->rows, .warps = p->warps }; - if (deep) { sp.depth = omega_fp8_gemv_steps(&sp); if (sp.depth * sp.rows * sp.lane_bytes > 128 || p->k > 512 * p->warps) continue; } - int rc0 = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y0, cta_budget, 0, msg, sizeof msg); - CHECK(rc0 == 0, "default reference for A/B %s%s: %s", p->name, deep ? " deep" : "", msg); - for (int cw = 1; cw < 4; cw++) { - OmegaFp8GemvSpec sv = sp; sv.coal = (uint32_t)(cw & 1); sv.wfirst = (uint32_t)(cw >> 1); - if (sv.coal && p->warps * p->rows > 32) continue; - char nm[96]; snprintf(nm, sizeof nm, "%s %s%s", cw == 1 ? "A" : cw == 2 ? "B" : "A+B", p->name, deep ? " deep" : ""); - int rc1 = sim_gemv(&sv, &W, p->groups, ids, x, p->x_rows, y1, cta_budget, 0, msg, sizeof msg); - size_t bad = 0; double worst = rc1 == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y1, &bad) : 1.0; - int same = rc0 == 0 && rc1 == 0 && memcmp(y0, y1, ny * 4) == 0; - CHECK(rc1 == 0 && bad == 0 && same, "sim %s: rc=%d bad=%zu worst_rel=%.3e identical_to_default=%d %s", nm, rc1, bad, worst, same, msg); - runs++; if (same) identical++; - printf("sim %-52s rc=%d worst_rel=%.3e bad=%zu identical_to_default=%d\n", nm, rc1, worst, bad, same); - int ms_list[5], nm_list = 0; - if (sv.coal && cw == 1 && (i == 6 || i == 10)) ms_list[nm_list++] = 5; - if (sv.coal && cw == 1 && (i == 1 || i == 6 || i == 8 || i == 10)) ms_list[nm_list++] = 4; - if (cw == 3 && (i == 8 || i == 9)) { ms_list[nm_list++] = 1; if (omega_fp8_gemv_steps(&sp) >= 2) ms_list[nm_list++] = 2; if (i == 8) ms_list[nm_list++] = 3; } /* point 9 draws the same expert for both groups: a table swap is invisible there */ - for (int q = 0; q < nm_list; q++) { - OmegaFp8GemvSpec ms = sv; ms.mutant = ms_list[q]; - int rcm = sim_gemv(&ms, &W, p->groups, ids, x, p->x_rows, y1, cta_budget, 0, msg, sizeof msg); - bad = 0; worst = rcm == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y1, &bad) : 1.0; - int caught = rcm != 0 || bad > 0; - CHECK(caught, "sim %s mutant %d NOT caught (bad=%zu worst_rel=%.3e)", nm, ms.mutant, bad, worst); - printf("sim %-52s mutant %d: %s (rc=%d bad=%zu %s)\n", nm, ms.mutant, caught ? "caught" : "MISSED", rcm, bad, rcm ? msg : ""); - } - } - } - free(x); free(y0); free(y1); weights_free(&W); - } - printf("sim A/B battery: %d/%d runs bit-identical to the default\n", identical, runs); - } -} - -/* ------------------------------------------------------------------- chip */ -typedef struct { uint32_t experts, n, k, groups, x_rows; const char *name; int parity_check; } ChipPoint; - -static int g_evict = 1; /* stream 512 MB through the host caches between upload and timing (nvrm.c:433: freshly written - host memory is served from the CPU caches by snooping and reads faster) */ -static void evict_host_caches(void) { - static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass; - if (!buf) buf = malloc(sz); - if (!buf) return; - memset(buf, ++pass, sz); - volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i]; -} - -static const char *g_only; static int g_depth_forced; /* run only the battery points whose name contains this (diagnosis) */ -/* --n N --k K (ternary engine T0, 2026-10-15): run ONE custom point n x k (one expert, one group) instead of the battery, - * with the parity check, timing and mutants 1, 2 and 4 (3 needs groups > 1); e.g. the BitNet word table 128256 x 2560. */ -static uint32_t g_custom_n, g_custom_k; static char g_custom_name[48]; -/* --grouped-cold (CUT5, 2026-10-16): the decode graph's two expert launches at their real shapes (omega_gpu_decode_graph.c - * record_layer: gate_up [128][1536][2048] with one shared x row, down [128][2048][768] with one x row per group), 8 of 128 - * experts per launch. L2 is defeated by rotation: the 128 experts are split into 16 disjoint sets of 8 and launch r uses - * set r % 16, so consecutive launches share no weight byte and a set returns only after 15 other sets (gate_up 403 MB, - * down 201 MB in between; L2 is 24 MiB, evidence/TERN-T0-KT1-18185404-20261016T0151Z/README.md). Every timed launch is - * checked against the double oracle (outside the chip time); a launch that fails parity fails the run. Mutants 1..4 - * must be caught at both shapes. GB/s = (weight + scale bytes of the 8 experts) / median chip time (launch to completion - * marker: the launch floor is NOT subtracted). */ -static int g_cold; -static int g_dump_stamps; /* --dump-stamps: one line per GPU-stamped launch (diagnosis of per-launch spread) */ -/* GPU-clock timing for --grouped-cold (CUT5, after omega#507: a host clock around submit and completion is not kernel time). - * The rotation above, recorded as one command list of LIST_N launches (launch i uses set i % 16, writes its own y slot), - * WAIT_FOR_IDLE + shader-cache invalidate before every launch (the decode graph's default barrier), GPU timestamps - * (PTIMER) before launch 0 and after every launch; launch time = stamp[i + 1] - stamp[i] (the barrier and launch floor are - * inside it, not subtracted). Every launch's y is checked against the oracle after the list. lists x LIST_N launches. */ -#define LIST_N 32u -static int cold_list_stamps(const ChipPoint *p, const Weights *W, const OmegaGpuFp8Tensor *t, const uint32_t *perm, const float *x, - uint32_t lists, uint64_t *el, uint32_t *n_el, size_t *bad_out, double *worst_out) { - const size_t ny = (size_t)p->groups * p->n; - const uint32_t STR = p->experts / 16u; /* experts per rotation set (8 for the 128-expert tables, 1 for --cold-single) */ - OmegaGpuCmdList *cl = NULL; OmegaGpuMem tab, xd, yd; int ok = 1; - memset(&tab, 0, sizeof tab); memset(&xd, 0, sizeof xd); memset(&yd, 0, sizeof yd); - if (omega_gpu_cmdlist_create(LIST_N, &cl) != 0) { printf("cmdlist create: %s\n", omega_gpu_session_last_error()); return -1; } - omega_gpu_session_lock(); - int arc = omega_gpu_session_alloc((size_t)16u * p->groups * 16u, &tab) | omega_gpu_session_alloc((size_t)p->x_rows * p->k * 4u, &xd) | omega_gpu_session_alloc((size_t)LIST_N * ny * 4u, &yd); - omega_gpu_session_unlock(); - if (arc != 0) { printf("list alloc: %s\n", omega_gpu_session_last_error()); ok = 0; } - if (ok) { - uint64_t *tw = tab.cpu; - for (uint32_t s = 0; s < 16u && ok; s++) for (uint32_t g = 0; g < p->groups; g++) - if (omega_gpu_fp8_tensor_entry(t, perm[STR * s + g], &tw[2u * (s * p->groups + g)], &tw[2u * (s * p->groups + g) + 1u]) != 0) ok = 0; - for (uint32_t r = 0; r < p->x_rows; r++) omega_fp8_pack_x_f32(x + (size_t)r * p->k, p->k, (float *)xd.cpu + (size_t)r * p->k); - if (!ok || omega_gpu_session_sync_to_gpu(&tab) != 0 || omega_gpu_session_sync_to_gpu(&xd) != 0) ok = 0; - } - size_t bad_all = 0; double worst_all = 0.0; uint32_t n = 0; - for (uint32_t l = 0; l < lists && ok; l++) { - float *y = yd.cpu; for (size_t i = 0; i < (size_t)LIST_N * ny; i++) y[i] = -999.0f; - if (omega_gpu_session_sync_to_gpu(&yd) != 0) { ok = 0; break; } - if (g_evict) evict_host_caches(); - omega_gpu_session_lock(); - omega_gpu_cmdlist_reset(cl); - for (uint32_t i = 0; i < LIST_N && ok; i++) - if (omega_gpu_fp8_gemv_grouped_record(cl, t, p->groups, tab.va + (uint64_t)(i % 16u) * p->groups * 16u, xd.va, p->x_rows, yd.va + (uint64_t)i * ny * 4u) != 0) { printf("record: %s\n", omega_gpu_fp8_last_error()); ok = 0; } - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = OMEGA_GPU_CMDLIST_BARRIER_WFI; o.stamps = 1; - OmegaGpuCmdListStats cs; memset(&cs, 0, sizeof cs); - uint64_t sts[LIST_N + 1]; int cnt = -1; - if (ok && omega_gpu_cmdlist_submit(cl, &o, &cs) != 0) { printf("submit: %s\n", omega_gpu_session_last_error()); ok = 0; } - if (ok) cnt = omega_gpu_cmdlist_stamps(cl, sts, LIST_N + 1); - omega_gpu_session_unlock(); - if (!ok || cnt != (int)LIST_N + 1 || cs.sems_done != LIST_N) { printf("list %u: stamps %d sems_done %u\n", l, cnt, cs.sems_done); ok = 0; break; } - if (omega_gpu_session_sync_to_cpu(&yd) != 0) { ok = 0; break; } - for (uint32_t i = 0; i < LIST_N; i++) { - size_t b = 0; double w = parity(W, p->groups, perm + STR * (i % 16u), x, p->x_rows, y + (size_t)i * ny, &b); - bad_all += b; if (w > worst_all) worst_all = w; - el[n++] = sts[i + 1] - sts[i]; - if (g_dump_stamps) printf("stamp %-24s list=%u launch=%u set=%u elapsed_us=%.1f bad=%zu\n", p->name, l, i, i % 16u, (double)el[n - 1] / 1e3, b); - } - } - omega_gpu_session_lock(); omega_gpu_session_free(&tab); omega_gpu_session_free(&xd); omega_gpu_session_free(&yd); omega_gpu_session_unlock(); - omega_gpu_cmdlist_free(cl); - *n_el = n; *bad_out = bad_all; *worst_out = worst_all; - return ok ? 0 : -1; -} -static void cold_points(FILE *out, uint32_t reps, int *first) { - static const ChipPoint gpts[] = { - { 128, 1536, 2048, 8, 1, "cold gate_up 8 of 128", 1 }, - { 128, 2048, 768, 8, 8, "cold down 8 of 128", 1 }, - }; - /* --cold-single (SPEED-1B, 2026-10-17): the decode graph's two single-projection launches (omega_gpu_decode_graph.c - * record_layer: qkv [1][5120][2048], o_proj [1][2048][4096], groups 1). Same rotation as above with 16 copies of the - * shape, one per set: consecutive launches share no weight byte and a copy returns after 15 others (qkv 157 MB, - * o_proj 126 MB in between; L2 is 24 MiB). */ - static const ChipPoint spts[] = { - { 16, 5120, 2048, 1, 1, "cold qkv 1 of 16", 1 }, - { 16, 2048, 4096, 1, 1, "cold o_proj 1 of 16", 1 }, - }; - const ChipPoint *cpts = g_cold == 2 ? spts : gpts; - for (size_t i = 0; i < 2; i++) { - const ChipPoint *p = &cpts[i]; - if (g_only && !strstr(p->name, g_only)) continue; - const uint32_t STR = p->experts / 16u; /* experts per rotation set */ - Weights W; weights_make(&W, p->experts, p->n, p->k, 9100 + (uint32_t)i); - uint32_t perm[128], st = 4242 + (uint32_t)i; - for (uint32_t e = 0; e < p->experts; e++) perm[e] = e; - for (uint32_t e = p->experts - 1u; e > 0; e--) { uint32_t j = lcg(&st) % (e + 1); uint32_t t = perm[e]; perm[e] = perm[j]; perm[j] = t; } - float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f); - float *y = malloc((size_t)p->groups * p->n * 4); - OmegaGpuFp8Tensor *t = NULL; - int rc = omega_gpu_fp8_tensor_upload(p->experts, p->n, p->k, W.w, W.s, &t); - OmegaGpuFp8Info info; memset(&info, 0, sizeof info); - if (rc == OMEGA_GPU_FP8_OK) rc = omega_gpu_fp8_gemv_grouped_f32(t, p->groups, perm, x, p->x_rows, y, &info); /* builds the kernel */ - size_t bad = 0; double worst = rc == OMEGA_GPU_FP8_OK ? parity(&W, p->groups, perm, x, p->x_rows, y, &bad) : 1.0; - CHECK(rc == OMEGA_GPU_FP8_OK && bad == 0, "chip %s warm-up: rc=%s bad=%zu worst_rel=%.3e (%s)", p->name, omega_gpu_fp8_rc_name(rc), bad, worst, omega_gpu_fp8_last_error()); - uint64_t *el = calloc(reps, sizeof *el); uint32_t done = 0; size_t bad_all = 0; double worst_all = worst; - if (g_evict) evict_host_caches(); - for (uint32_t r = 0; r < reps && rc == OMEGA_GPU_FP8_OK; r++) { - const uint32_t *ids = perm + STR * (r % 16u); - OmegaGpuFp8Info ti; - if (omega_gpu_fp8_gemv_grouped_f32(t, p->groups, ids, x, p->x_rows, y, &ti) != OMEGA_GPU_FP8_OK) { rc = OMEGA_GPU_FP8_CHIP_FAIL; break; } - size_t b = 0; double w = parity(&W, p->groups, ids, x, p->x_rows, y, &b); - bad_all += b; if (w > worst_all) worst_all = w; - el[done++] = ti.elapsed_ns; - } - CHECK(rc == OMEGA_GPU_FP8_OK && done == reps && bad_all == 0, "chip %s: %u/%u timed launches, %zu elements off the oracle, worst_rel=%.3e (%s)", p->name, done, reps, bad_all, worst_all, omega_gpu_fp8_last_error()); - uint64_t med = 0, lo = 0, hi = 0; double gbs = 0.0; - if (done) { qsort(el, done, sizeof *el, cmp_u64); med = el[done / 2]; lo = el[0]; hi = el[done - 1]; gbs = med ? (double)(info.weight_bytes + info.scale_bytes) / (double)med : 0.0; } - printf("chip %-24s variant=%d sched=%d rc=%-9s timed=%u bad=%zu worst_rel=%.3e grid=%ux%u lb=%u rows=%u warps=%u depth=%u bytes=%" PRIu64 " chip_med=%.1fus min=%.1fus max=%.1fus (%.1f GB/s, %.3f of 237.2)\n", - p->name, omega_gpu_fp8_variant(), omega_gpu_fp8_sched(), omega_gpu_fp8_rc_name(rc), done, bad_all, worst_all, info.grid_x, info.grid_y, info.lane_bytes, info.rows_per_warp, - info.warps_per_cta, info.depth, info.weight_bytes + info.scale_bytes, med / 1e3, lo / 1e3, hi / 1e3, gbs, gbs / 237.2); - if (out) fprintf(out, "%s{\"name\":\"%s\",\"experts\":%u,\"n\":%u,\"k\":%u,\"groups\":%u,\"x_rows\":%u,\"rc\":\"%s\",\"timed\":%u,\"bad\":%zu,\"worst_rel\":%.3e," - "\"variant\":%d,\"sched\":%d,\"grid_x\":%u,\"grid_y\":%u,\"lane_bytes\":%u,\"rows_per_warp\":%u,\"warps_per_cta\":%u,\"depth\":%u,\"bytes\":%" PRIu64 ",\"chip_median_ns\":%" PRIu64 ",\"chip_min_ns\":%" PRIu64 ",\"chip_max_ns\":%" PRIu64 ",\"gbps_chip\":%.2f,\"evict\":%d,\"rotation_sets\":16}", - *first ? "" : ",", p->name, p->experts, p->n, p->k, p->groups, p->x_rows, omega_gpu_fp8_rc_name(rc), done, bad_all, worst_all, - omega_gpu_fp8_variant(), omega_gpu_fp8_sched(), info.grid_x, info.grid_y, info.lane_bytes, info.rows_per_warp, info.warps_per_cta, info.depth, info.weight_bytes + info.scale_bytes, med, lo, hi, gbs, g_evict); - *first = 0; - { /* GPU-stamped timing of the same rotation (the figure CUT5 reports) */ - const uint32_t lists = reps < 2u * LIST_N ? 2u : (reps + LIST_N - 1u) / LIST_N; - uint64_t *e2 = calloc((size_t)lists * LIST_N, sizeof *e2); uint32_t n2 = 0; size_t b2 = 0; double w2 = 0.0; - int lrc = rc == OMEGA_GPU_FP8_OK ? cold_list_stamps(p, &W, t, perm, x, lists, e2, &n2, &b2, &w2) : -1; - CHECK(lrc == 0 && n2 == lists * LIST_N && b2 == 0, "chip %s GPU-stamped list: %u/%u launches, %zu elements off the oracle, worst_rel=%.3e", p->name, n2, lists * LIST_N, b2, w2); - uint64_t m2 = 0, lo2 = 0, hi2 = 0; double g2 = 0.0; - if (n2) { qsort(e2, n2, sizeof *e2, cmp_u64); m2 = e2[n2 / 2]; lo2 = e2[0]; hi2 = e2[n2 - 1]; g2 = m2 ? (double)(info.weight_bytes + info.scale_bytes) / (double)m2 : 0.0; } - printf("chip %-24s GPU-STAMPED coal=%d wfirst=%d launches=%u bad=%zu stamp_med=%.1fus min=%.1fus max=%.1fus (%.1f GB/s, %.3f of 237.2)\n", - p->name, omega_gpu_fp8_coal(), omega_gpu_fp8_wfirst(), n2, b2, m2 / 1e3, lo2 / 1e3, hi2 / 1e3, g2, g2 / 237.2); - if (out) fprintf(out, ",{\"name\":\"%s gpu-stamped\",\"coal\":%d,\"wfirst\":%d,\"sched\":%d,\"launches\":%u,\"bad\":%zu,\"worst_rel\":%.3e,\"bytes\":%" PRIu64 ",\"stamp_median_ns\":%" PRIu64 ",\"stamp_min_ns\":%" PRIu64 ",\"stamp_max_ns\":%" PRIu64 ",\"gbps_stamp\":%.2f,\"barrier\":\"WFI\",\"floor_subtracted\":0}", - p->name, omega_gpu_fp8_coal(), omega_gpu_fp8_wfirst(), omega_gpu_fp8_sched(), n2, b2, w2, info.weight_bytes + info.scale_bytes, m2, lo2, hi2, g2); - free(e2); - } - free(el); - /* mutants: each must be caught at this shape and this kernel configuration */ - for (int m = 1; m <= 4 && rc == OMEGA_GPU_FP8_OK; m++) { - if (m == 3 && p->groups == 1) continue; /* mutant 3 needs groups > 1 (as in the --n/--k path) */ - if (m == 4) omega_gpu_fp8_test_set_no_fold(1); else omega_gpu_fp8_test_set_mutant(m); - OmegaGpuFp8Tensor *tm = t; - if (m == 4) { tm = NULL; if (omega_gpu_fp8_tensor_upload(p->experts, p->n, p->k, W.w, W.s, &tm) != OMEGA_GPU_FP8_OK) tm = NULL; } - int r = tm ? omega_gpu_fp8_gemv_grouped_f32(tm, p->groups, perm, x, p->x_rows, y, NULL) : OMEGA_GPU_FP8_CHIP_FAIL; - size_t mb = 0; double mw = r == OMEGA_GPU_FP8_OK ? parity(&W, p->groups, perm, x, p->x_rows, y, &mb) : 1.0; - int caught = r != OMEGA_GPU_FP8_OK || mb > 0; - CHECK(caught, "chip %s mutant %d NOT caught", p->name, m); - printf("chip %-24s mutant %d: %s (rc=%s bad=%zu worst_rel=%.3e)\n", p->name, m, caught ? "caught" : "MISSED", omega_gpu_fp8_rc_name(r), mb, mw); - if (out) fprintf(out, ",{\"name\":\"%s mutant %d\",\"caught\":%d,\"rc\":\"%s\",\"bad\":%zu,\"worst_rel\":%.3e}", p->name, m, caught, omega_gpu_fp8_rc_name(r), mb, mw); - if (m == 4) { omega_gpu_fp8_test_set_no_fold(0); if (tm) omega_gpu_fp8_tensor_free(tm); } else omega_gpu_fp8_test_set_mutant(0); - } - if (t) omega_gpu_fp8_tensor_free(t); - free(x); free(y); weights_free(&W); - if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); break; } - } -} - -static int chip_run(const char *out_path, uint32_t reps) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 1; } - if (out) fprintf(out, "{\"test\":\"OMEGA_GPU_FP8_GEMV\",\"points\":["); - static const ChipPoint pts[] = { - { 1, 128, 256, 1, 1, "k256 n128", 1 }, - { 1, 256, 768, 1, 1, "k768 n256", 1 }, - { 1, 384, 2048, 1, 1, "k2048 n384", 1 }, - { 1, 768, 2048, 1, 1, "gate 768x2048", 1 }, - { 1, 1536, 2048, 1, 1, "gate+up 1536x2048", 1 }, - { 1, 2048, 768, 1, 1, "down 2048x768", 1 }, - { 1, 4096, 2048, 1, 1, "q_proj 4096x2048", 1 }, - { 1, 512, 2048, 1, 1, "k_proj 512x2048", 1 }, - { 1, 2048, 4096, 1, 1, "o_proj 2048x4096", 1 }, - { 1, 5120, 2048, 1, 1, "qkv fused 5120x2048", 1 }, - { 8, 1536, 2048, 8, 1, "8 experts gate+up shared x", 1 }, - { 8, 2048, 768, 8, 8, "8 experts down per-group x", 1 }, - { 16, 1536, 2048, 8, 1, "8 of 16 experts gate+up", 1 }, - { 1, 16384, 2048, 1, 1, "large 16384x2048", 1 }, - /* Qwen3.8-27B dense shapes (omega#541) and the new width cap */ - { 1, 17408, 5120, 1, 1, "q38 gate 17408x5120", 1 }, - { 1, 5120, 17408, 1, 1, "q38 down 5120x17408", 1 }, - { 1, 12288, 5120, 1, 1, "q38 q_proj 12288x5120", 1 }, - { 1, 1024, 5120, 1, 1, "q38 k_proj 1024x5120", 1 }, - { 1, 10240, 5120, 1, 1, "q38 in_proj_qkv 10240x5120", 1 }, - { 1, 6144, 5120, 1, 1, "q38 in_proj_z 6144x5120", 1 }, - { 1, 5120, 6144, 1, 1, "q38 out_proj 5120x6144", 1 }, - { 1, 256, 32768, 1, 1, "width cap 256x32768", 1 }, - }; - /* 0. one-hot conversion on the chip: row r holds code r at column 0 (NaN codes as 0x00), x = e_0, scale 1. - * y[r] must equal the reference bit for bit. The e4m3 subnormal codes 0x01..0x07 (and negatives) travel - * through the FFMA chain as f32 subnormals (e4m3 * 2^-120); a flush-to-zero FFMA would return 0 here. */ - int one_hot_exact = -1; - { - uint8_t *w = calloc(256, 256); uint16_t s[4]; float x[256] = { 0 }, y[256]; OmegaGpuFp8Tensor *t = NULL; - for (int b = 0; b < 4; b++) s[b] = bf16_of(1.0f); - for (int r = 0; r < 256; r++) w[r * 256] = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0 : (uint8_t)r; - x[0] = 1.0f; - int rc = omega_gpu_fp8_tensor_upload(1, 256, 256, w, s, &t); - if (rc == OMEGA_GPU_FP8_OK) rc = omega_gpu_fp8_gemv_f32(t, 0, x, y, NULL); - one_hot_exact = 0; - if (rc == OMEGA_GPU_FP8_OK) for (int r = 0; r < 256; r++) { - float ref = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0.0f : omega_fp8_e4m3_ref((uint8_t)r); - if (y[r] == ref) one_hot_exact++; else CHECK(0, "chip one-hot code 0x%02x: kernel %a, reference %a", r, y[r], ref); - } - if (g_depth_forced && rc == OMEGA_GPU_FP8_CODEGEN_FAIL) printf("chip one-hot conversion: skipped (forced depth does not fit k=256)\n"); - else CHECK(rc == OMEGA_GPU_FP8_OK && one_hot_exact == 256, "chip one-hot conversion: rc=%s exact=%d/256", omega_gpu_fp8_rc_name(rc), one_hot_exact); - printf("chip one-hot conversion: rc=%s %d/256 rows exact (subnormal codes 0x01..0x07 included: no flush to zero)\n", omega_gpu_fp8_rc_name(rc), one_hot_exact); - if (out) fprintf(out, "{\"name\":\"one-hot conversion\",\"rc\":\"%s\",\"exact_rows\":%d,\"of\":256}", omega_gpu_fp8_rc_name(rc), one_hot_exact); - if (t) omega_gpu_fp8_tensor_free(t); - free(w); - } - static ChipPoint custom; const ChipPoint *P = pts; size_t npts = sizeof pts / sizeof pts[0]; - if (g_custom_n && !g_custom_k) { CHECK(0, "--n needs --k"); if (out) fclose(out); return 1; } - if (g_custom_n) { snprintf(g_custom_name, sizeof g_custom_name, "custom %ux%u", g_custom_n, g_custom_k); custom = (ChipPoint){ 1, g_custom_n, g_custom_k, 1, 1, g_custom_name, 1 }; P = &custom; npts = 1; } - int first = 1; - first = out ? 0 : 1; - if (g_cold) npts = 0; /* --grouped-cold: the two real expert shapes instead of the battery */ - for (size_t i = 0; i < npts; i++) { - const ChipPoint *p = &P[i]; - if (g_only && !strstr(p->name, g_only)) continue; - Weights W; weights_make(&W, p->experts, p->n, p->k, 5000 + (uint32_t)i); - uint32_t ids[8]; uint32_t st = 99 + (uint32_t)i; - for (uint32_t g = 0; g < p->groups; g++) ids[g] = (p->experts > p->groups ? lcg(&st) % p->experts : (p->groups - 1 - g) % p->experts); - float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f); - float *y = malloc((size_t)p->groups * p->n * 4), *y2 = malloc((size_t)p->groups * p->n * 4); - OmegaGpuFp8Tensor *t = NULL; - double t0 = now_ms(); - int rc = omega_gpu_fp8_tensor_upload(p->experts, p->n, p->k, W.w, W.s, &t); - double up_ms = now_ms() - t0; - OmegaGpuFp8Info info; memset(&info, 0, sizeof info); - if (rc == OMEGA_GPU_FP8_OK) rc = omega_gpu_fp8_gemv_grouped_f32(t, p->groups, ids, x, p->x_rows, y, &info); - size_t bad = 0; double worst = rc == OMEGA_GPU_FP8_OK ? parity(&W, p->groups, ids, x, p->x_rows, y, &bad) : 1.0; - int ok = rc == OMEGA_GPU_FP8_OK && bad == 0; - /* second call: cache hit, bit-identical */ - int same = 0; OmegaGpuFp8Info i2; memset(&i2, 0, sizeof i2); - if (ok) { int r2 = omega_gpu_fp8_gemv_grouped_f32(t, p->groups, ids, x, p->x_rows, y2, &i2); same = r2 == OMEGA_GPU_FP8_OK && memcmp(y, y2, (size_t)p->groups * p->n * 4) == 0 && i2.kernel_cache_hit; } - CHECK(ok && same, "chip %s: rc=%s bad=%zu worst_rel=%.3e second-call-identical=%d (%s)", p->name, omega_gpu_fp8_rc_name(rc), bad, worst, same, omega_gpu_fp8_last_error()); - /* timing: median of reps */ - uint64_t *el = calloc(reps, sizeof *el), *cl = calloc(reps, sizeof *cl); - uint32_t done = 0; - if (g_evict) evict_host_caches(); - for (uint32_t r = 0; r < reps && ok; r++) { - OmegaGpuFp8Info ti; if (omega_gpu_fp8_gemv_grouped_f32(t, p->groups, ids, x, p->x_rows, y2, &ti) != OMEGA_GPU_FP8_OK) break; - el[r] = ti.elapsed_ns; cl[r] = ti.call_ns; done++; - } - uint64_t med_el = 0, med_cl = 0; double gbs = 0.0, gbs_call = 0.0; - if (done) { qsort(el, done, sizeof *el, cmp_u64); qsort(cl, done, sizeof *cl, cmp_u64); med_el = el[done / 2]; med_cl = cl[done / 2]; - gbs = med_el ? (double)(info.weight_bytes + info.scale_bytes) / (double)med_el : 0.0; gbs_call = med_cl ? (double)(info.weight_bytes + info.scale_bytes) / (double)med_cl : 0.0; } - printf("chip %-32s variant=%d rc=%-9s bad=%zu worst_rel=%.3e grid=%ux%u lb=%u rows=%u warps=%u depth=%u bytes=%" PRIu64 " upload=%.1fms chip_med=%.1fus (%.1f GB/s) call_med=%.1fus (%.1f GB/s) reps=%u\n", - p->name, omega_gpu_fp8_variant(), omega_gpu_fp8_rc_name(rc), bad, worst, info.grid_x, info.grid_y, info.lane_bytes, info.rows_per_warp, info.warps_per_cta, info.depth, - info.weight_bytes + info.scale_bytes, up_ms, med_el / 1e3, gbs, med_cl / 1e3, gbs_call, done); - if (out) fprintf(out, "%s{\"name\":\"%s\",\"experts\":%u,\"n\":%u,\"k\":%u,\"groups\":%u,\"x_rows\":%u,\"rc\":\"%s\",\"bad\":%zu,\"worst_rel\":%.3e,\"second_call_identical\":%d," - "\"variant\":%d,\"grid_x\":%u,\"grid_y\":%u,\"lane_bytes\":%u,\"rows_per_warp\":%u,\"warps_per_cta\":%u,\"depth\":%u,\"bytes\":%" PRIu64 ",\"upload_ms\":%.2f,\"chip_median_ns\":%" PRIu64 ",\"gbps_chip\":%.2f,\"call_median_ns\":%" PRIu64 ",\"gbps_call\":%.2f,\"reps\":%u,\"marker\":%u,\"evict\":%d}", - first ? "" : ",", p->name, p->experts, p->n, p->k, p->groups, p->x_rows, omega_gpu_fp8_rc_name(rc), bad, worst, same, - omega_gpu_fp8_variant(), info.grid_x, info.grid_y, info.lane_bytes, info.rows_per_warp, info.warps_per_cta, info.depth, info.weight_bytes + info.scale_bytes, up_ms, med_el, gbs, med_cl, gbs_call, done, info.completion_marker, g_evict); - first = 0; - free(el); free(cl); - /* mutants on the first grouped point and the gate shape: each must be caught on the chip */ - if (ok && (g_custom_n || i == 4 || i == 10)) { - for (int m = 1; m <= 4; m++) { - if (m == 3 && p->groups == 1) continue; - if (m == 4) omega_gpu_fp8_test_set_no_fold(1); else omega_gpu_fp8_test_set_mutant(m); - OmegaGpuFp8Tensor *tm = t; - if (m == 4) { tm = NULL; if (omega_gpu_fp8_tensor_upload(p->experts, p->n, p->k, W.w, W.s, &tm) != OMEGA_GPU_FP8_OK) tm = NULL; } - int r = tm ? omega_gpu_fp8_gemv_grouped_f32(tm, p->groups, ids, x, p->x_rows, y2, NULL) : OMEGA_GPU_FP8_CHIP_FAIL; - size_t mb = 0; double mw = r == OMEGA_GPU_FP8_OK ? parity(&W, p->groups, ids, x, p->x_rows, y2, &mb) : 1.0; - int caught = r != OMEGA_GPU_FP8_OK || mb > 0; - CHECK(caught, "chip %s mutant %d NOT caught", p->name, m); - printf("chip %-32s mutant %d: %s (rc=%s bad=%zu worst_rel=%.3e)\n", p->name, m, caught ? "caught" : "MISSED", omega_gpu_fp8_rc_name(r), mb, mw); - if (out) fprintf(out, ",{\"name\":\"%s mutant %d\",\"caught\":%d,\"rc\":\"%s\",\"bad\":%zu,\"worst_rel\":%.3e}", p->name, m, caught, omega_gpu_fp8_rc_name(r), mb, mw); - if (m == 4) { omega_gpu_fp8_test_set_no_fold(0); if (tm) omega_gpu_fp8_tensor_free(tm); } else omega_gpu_fp8_test_set_mutant(0); - } - } - omega_gpu_fp8_tensor_free(t); - free(x); free(y); free(y2); weights_free(&W); - if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); break; } - } - if (g_cold && !omega_gpu_session_is_blocked()) cold_points(out, reps, &first); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"device_opens\":%u,\"verdict\":\"%s\"}\n", g_checks, g_failed, omega_gpu_session_open_count(), g_failed == 0 ? "OMEGA_GPU_FP8_GEMV_PASS" : "OMEGA_GPU_FP8_GEMV_FAIL"); fclose(out); } - return 0; -} - -/* L310: the grouped-launch CTA rule, pure, no chip. 8 groups keep the measured 6; 9 groups (the 35B) get 5 = one wave of 48. */ -static void rule_checks(void) { - static const struct { uint32_t groups, forced; int wave, want; } c[] = { - {8, 0, 1, 6}, {9, 0, 1, 5}, {9, 0, 0, 6}, {9, 5, 0, 5}, {9, 5, 1, 5}, {9, 300, 1, 5}, {2, 0, 1, 6}, {48, 0, 1, 1}, {64, 0, 1, 1}, {0, 0, 1, 6} }; - for (size_t i = 0; i < sizeof c / sizeof c[0]; i++) { - uint32_t got = omega_gpu_fp8_grouped_ctas_rule(c[i].groups, c[i].forced, c[i].wave); - if (got != (uint32_t)c[i].want) { fprintf(stderr, "grouped CTA rule: groups %u forced %u wave %d: got %u want %d\n", c[i].groups, c[i].forced, c[i].wave, got, c[i].want); exit(1); } - } - printf("grouped CTA rule: %zu/%zu ok (8 groups -> 6, 9 groups -> 5)\n", sizeof c / sizeof c[0], sizeof c / sizeof c[0]); -} - -int main(int argc, char **argv) { - rule_checks(); - int host = 0, sim = 0; const char *out_path = NULL; uint32_t reps = 20, lb = 0, rows = 0, warps = 0, budget = 0, spin = 2000, depth = 0; int depth_set = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--lane-bytes") == 0 && i + 1 < argc) lb = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--rows") == 0 && i + 1 < argc) rows = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--warps") == 0 && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--cta-budget") == 0 && i + 1 < argc) budget = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--depth") == 0 && i + 1 < argc) { depth_set = 1; depth = (uint32_t)atoi(argv[++i]); } - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0; - else if (strcmp(argv[i], "--only") == 0 && i + 1 < argc) g_only = argv[++i]; - else if (strcmp(argv[i], "--n") == 0 && i + 1 < argc) g_custom_n = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--k") == 0 && i + 1 < argc) g_custom_k = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--gpr-pad") == 0 && i + 1 < argc) omega_gpu_fp8_set_gpr_pad((uint32_t)atoi(argv[++i])); - else if (strcmp(argv[i], "--variant") == 0 && i + 1 < argc) omega_gpu_fp8_set_variant(atoi(argv[++i])); /* 1 (default) or 2 (W-L2c row-pipelined) */ - else if (strcmp(argv[i], "--sched") == 0 && i + 1 < argc) omega_gpu_fp8_set_sched(atoi(argv[++i])); /* CUT5: 0 (default) or 1 (pipelined decode + stall pass) */ - else if (strcmp(argv[i], "--coal") == 0 && i + 1 < argc) { omega_gpu_fp8_set_coal(atoi(argv[++i])); g_coal_arg = 1; } /* CUT5 variant A: coalesced output through shared slots */ - else if (strcmp(argv[i], "--wfirst") == 0 && i + 1 < argc) omega_gpu_fp8_set_wfirst(atoi(argv[++i])); /* CUT5 variant B: weight loads before the x loads */ - else if (strcmp(argv[i], "--coal-default") == 0) { coal_default_check(); printf("gpu_fp8_api_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); return g_failed ? 1 : 0; } /* variant A default vs env only */ - else if (strcmp(argv[i], "--deep-default") == 0) { deep_default_check(); printf("gpu_fp8_api_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); return g_failed ? 1 : 0; } /* deep default vs env only */ - else if (strcmp(argv[i], "--grouped-cold") == 0) g_cold = 1; /* CUT5: the two decode expert launches, 8 of 128, L2 defeated */ - else if (strcmp(argv[i], "--cold-single") == 0) g_cold = 2; /* SPEED-1B: the two single projections qkv / o_proj, L2 defeated */ - else if (strcmp(argv[i], "--dump-stamps") == 0) g_dump_stamps = 1; - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - if (host) host_only(); - if (sim) sim_battery(budget ? budget : 4); - if (!host && !sim) { - if (lb || rows || warps) omega_gpu_fp8_set_shape(lb, rows, warps); - if (budget) omega_gpu_fp8_set_cta_budget(budget); - if (depth_set) { omega_gpu_fp8_set_depth(1, depth); g_depth_forced = 1; } - (void)omega_gpu_session_set_spin_us(spin); - chip_run(out_path, reps ? reps : 1); - omega_gpu_session_close(); - } - printf("gpu_fp8_api_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_fp8_slots_test.c b/tests/gpu_fp8_slots_test.c deleted file mode 100644 index e7c35e04e..000000000 --- a/tests/gpu_fp8_slots_test.c +++ /dev/null @@ -1,335 +0,0 @@ -/* gpu_fp8_slots_test: Expert Ribbon P1 (aienix#4 / omega#533), versioned replaceable FP8 expert slots. - * - * --host-only the slot state machine (omega_fp8_slot_table.c) without a device: publish only after a finished load, - * stale handles, double load, load/evict while pinned, ABA across reuse, failed loads, a threaded race - * (readers pin/unpin while a writer reloads; a reader must never observe its slot rewritten), mutant. - * --chip the pool on the GB10 (caller holds the GB10 lock): - * 1. parity: E random experts resident (one tensor) vs the same experts loaded into a smaller pool, - * grouped launch, y bit-identical, gate|up (1536x2048) and down (2048x768) shapes; - * 2. churn: --rounds reloads cycling every slot through every expert, parity after each reload; - * 3. refusals on the chip pool: load while pinned BUSY, pin of a replaced version STALE, entry unpinned; - * 4. reader fence through a recorded command list: the list's group table points at a pinned slot; a - * load into that slot before submit must be refused and the list must read the pinned expert; - * NEGATIVE CONTROL (--mutant): the pool ignores pins, the load goes through and the list reads the - * replaced weights, which the parity check must catch (exit 1 = caught); - * 5. memory: pool device bytes vs the session's driver allocation counter, pinned high-water. - * Exit 0 PASS, 1 FAIL (or, with --mutant, CAUGHT), 2 usage. Verdict line last. */ -#include "omega_fp8_slot_table.h" -#include "omega_gpu_fp8_slots.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_cmdlist.h" -#include -#include -#include -#include -#include -#include - -static int g_failed, g_checks; -#define CHECK(c, ...) do { g_checks++; if (c) { printf("ok "); } else { printf("FAIL "); g_failed++; } printf(__VA_ARGS__); printf("\n"); } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } - -/* ---------------- host-only: the state machine ---------------- */ - -/* The race must not depend on how the threads are scheduled (a 1-CPU taskset starved the writer; a loaded host hid the - * mutant). The writer publishes every reload attempt under m; a reader holds its pin until two attempts have finished - * after it pinned, so at least one begin_load runs entirely inside the pin, and pins again only after the writer - * published a reload, so pins always drain and the writer always gets through. Waits block on cv (no spinning or - * yielding), so a host with every CPU busy only slows the hand-offs, it cannot starve them. */ -typedef struct { - OmegaFp8SlotTable *t; uint64_t *shadow_version; - pthread_mutex_t m; pthread_cond_t cv; int stop; uint64_t attempts, reloads; /* guarded by m */ - uint64_t observed_rewrites, pins_ok; /* atomic */ -} Race; - -/* waits until *ctr >= target or stop; returns the value of *ctr seen */ -static uint64_t race_wait(Race *r, const uint64_t *ctr, uint64_t target) { - pthread_mutex_lock(&r->m); - while (*ctr < target && !r->stop) pthread_cond_wait(&r->cv, &r->m); - const uint64_t v = *ctr; - pthread_mutex_unlock(&r->m); - return v; -} - -static int race_stopped(Race *r) { - pthread_mutex_lock(&r->m); const int s = r->stop; pthread_mutex_unlock(&r->m); - return s; -} - -static void *reader(void *arg) { - Race *r = arg; - uint64_t after = 0; int pinned_once = 0; - while (!race_stopped(r)) { - if (pinned_once) race_wait(r, &r->reloads, after + 1); - OmegaFp8SlotRec rec; - if (omega_fp8_slot_query(r->t, 0, &rec) != 0) continue; - if (rec.state != OMEGA_FP8_SLOT_READY) continue; - if (omega_fp8_slot_pin(r->t, 0, rec.version) != 0) continue; - pinned_once = 1; - __atomic_fetch_add(&r->pins_ok, 1, __ATOMIC_RELAXED); - /* while pinned, the shadow (the slot bytes) must keep holding the content of the pinned key */ - uint64_t seen = __atomic_load_n(r->shadow_version, __ATOMIC_ACQUIRE) != rec.key; - const uint64_t a0 = race_wait(r, &r->attempts, 0); - race_wait(r, &r->attempts, a0 + 2); - seen += __atomic_load_n(r->shadow_version, __ATOMIC_ACQUIRE) != rec.key; - if (seen) __atomic_fetch_add(&r->observed_rewrites, seen, __ATOMIC_RELAXED); - after = race_wait(r, &r->reloads, 0); - (void)omega_fp8_slot_unpin(r->t, 0, rec.version); - } - return NULL; -} - -static double now_s(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (double)ts.tv_sec + ts.tv_nsec * 1e-9; } - -static int host_tests(void) { - OmegaFp8SlotTable t; - CHECK(omega_fp8_slot_table_init(&t, 4) == 0, "init 4 slots"); - uint64_t v1 = 0, v2 = 0, v3 = 0; - CHECK(omega_fp8_slot_pin(&t, 0, 1) == OMEGA_FP8_SLOT_STALE, "pin of a never-loaded slot is STALE"); - CHECK(omega_fp8_slot_begin_load(&t, 0) == 0, "begin load slot 0"); - CHECK(omega_fp8_slot_begin_load(&t, 0) == OMEGA_FP8_SLOT_BUSY, "double load refused BUSY"); - CHECK(omega_fp8_slot_pin(&t, 0, 1) == OMEGA_FP8_SLOT_STALE, "a LOADING slot cannot be pinned (not visible before publish)"); - CHECK(omega_fp8_slot_finish_load(&t, 0, 100, 1, &v1) == 0 && v1 == 1, "publish -> version 1"); - CHECK(omega_fp8_slot_finish_load(&t, 0, 100, 1, &v2) == OMEGA_FP8_SLOT_BAD_ARGS && v2 == 0, "finish without begin refused"); - CHECK(omega_fp8_slot_pin(&t, 0, v1) == 0, "pin v1"); - CHECK(omega_fp8_slot_begin_load(&t, 0) == OMEGA_FP8_SLOT_BUSY, "reload while pinned refused BUSY"); - CHECK(omega_fp8_slot_evict(&t, 0) == OMEGA_FP8_SLOT_BUSY, "evict while pinned refused BUSY"); - CHECK(omega_fp8_slot_unpin(&t, 0, v1 + 7) == OMEGA_FP8_SLOT_BAD_ARGS, "unpin with a wrong version refused"); - CHECK(omega_fp8_slot_unpin(&t, 0, v1) == 0, "unpin v1"); - CHECK(omega_fp8_slot_unpin(&t, 0, v1) == OMEGA_FP8_SLOT_BAD_ARGS, "unpin without a pin refused"); - CHECK(omega_fp8_slot_begin_load(&t, 0) == 0 && omega_fp8_slot_finish_load(&t, 0, 200, 1, &v2) == 0 && v2 > v1, "reload -> newer version"); - CHECK(omega_fp8_slot_pin(&t, 0, v1) == OMEGA_FP8_SLOT_STALE, "stale handle (old version) refused after reload"); - /* ABA: slot 0 holds key 200; load key 100 again: the version must differ from v1 */ - CHECK(omega_fp8_slot_begin_load(&t, 0) == 0 && omega_fp8_slot_finish_load(&t, 0, 100, 1, &v3) == 0 && v3 != v1 && v3 > v2, - "same key reloaded gets a fresh version (no ABA): v1=%" PRIu64 " v3=%" PRIu64, v1, v3); - CHECK(omega_fp8_slot_begin_load(&t, 1) == 0 && omega_fp8_slot_finish_load(&t, 1, 5, 0, &v2) == 0 && v2 == 0, "failed load publishes nothing"); - OmegaFp8SlotRec rec; - CHECK(omega_fp8_slot_query(&t, 1, &rec) == 0 && rec.state == OMEGA_FP8_SLOT_EMPTY, "failed load leaves the slot EMPTY"); - CHECK(omega_fp8_slot_evict(&t, 0) == 0 && omega_fp8_slot_pin(&t, 0, v3) == OMEGA_FP8_SLOT_STALE, "evicted slot cannot be pinned"); - CHECK(omega_fp8_slot_begin_load(&t, 9) == OMEGA_FP8_SLOT_BAD_ARGS, "out-of-range slot refused"); - /* repeated evict/reinsert: versions strictly increase */ - uint64_t last = v3; int mono = 1; - for (int i = 0; i < 1000; i++) { - uint64_t v = 0; - if (omega_fp8_slot_begin_load(&t, (uint32_t)(i % 4)) != 0 || omega_fp8_slot_finish_load(&t, (uint32_t)(i % 4), (uint64_t)i, 1, &v) != 0 || v <= last) mono = 0; - last = v; - if (i % 3 == 0 && omega_fp8_slot_evict(&t, (uint32_t)(i % 4)) != 0) mono = 0; - } - CHECK(mono, "1000 evict/reinsert cycles: versions strictly increase"); - CHECK(omega_fp8_slot_table_idle(&t), "idle when nothing is pinned or loading"); - omega_fp8_slot_table_fini(&t); - - /* threaded race: 4 readers pin slot 0 at its current version; one writer reloads it as fast as it can. The shadow - * stands for the slot's bytes: the writer bumps it between begin_load and finish_load (while the slot is hidden). - * The writer runs until RELOADS reloads and PINS reader pins happened (60 s cap, which only a hung table reaches). */ - enum { RELOADS = 10000, PINS = 1000 }; - for (int mutant = 0; mutant <= 1; mutant++) { - OmegaFp8SlotTable rt; omega_fp8_slot_table_init(&rt, 1); - omega_fp8_slot_table_set_mutant(&rt, mutant); - uint64_t shadow = 0, v = 0; - omega_fp8_slot_begin_load(&rt, 0); omega_fp8_slot_finish_load(&rt, 0, 0, 1, &v); - __atomic_store_n(&shadow, 0, __ATOMIC_RELEASE); - Race r = { .t = &rt, .shadow_version = &shadow, .m = PTHREAD_MUTEX_INITIALIZER, .cv = PTHREAD_COND_INITIALIZER }; - pthread_t th[4]; - for (int i = 0; i < 4; i++) pthread_create(&th[i], NULL, reader, &r); - uint64_t reloads = 0, busy = 0; - const double t0 = now_s(); - for (uint64_t i = 0; reloads < RELOADS || __atomic_load_n(&r.pins_ok, __ATOMIC_RELAXED) < PINS; i++) { - if ((i & 1023) == 0 && now_s() - t0 > 60.0) break; - const int rc = omega_fp8_slot_begin_load(&rt, 0); - if (rc == 0) { - __atomic_store_n(&shadow, 0xDEADull << 32, __ATOMIC_RELEASE); /* "bytes" half-written */ - __atomic_store_n(&shadow, i + 1, __ATOMIC_RELEASE); /* "bytes" complete: the content of key i + 1 */ - uint64_t nv = 0; omega_fp8_slot_finish_load(&rt, 0, i + 1, 1, &nv); - reloads++; - } else busy++; - pthread_mutex_lock(&r.m); - r.attempts = i + 1; r.reloads = reloads; - pthread_cond_broadcast(&r.cv); - pthread_mutex_unlock(&r.m); - } - pthread_mutex_lock(&r.m); r.stop = 1; pthread_cond_broadcast(&r.cv); pthread_mutex_unlock(&r.m); - for (int i = 0; i < 4; i++) pthread_join(th[i], NULL); - const int ran = reloads >= RELOADS && r.pins_ok >= PINS; - if (!mutant) - CHECK(ran && r.observed_rewrites == 0, - "race: %" PRIu64 " reloads, %" PRIu64 " busy refusals, %" PRIu64 " reader pins, rewrites seen under a pin = %" PRIu64, - reloads, busy, r.pins_ok, r.observed_rewrites); - else - CHECK(ran && r.observed_rewrites > 0, - "mutant (ignores pins): %" PRIu64 " reloads, %" PRIu64 " reader pins, rewrites seen under a pin = %" PRIu64 " (the race check has teeth)", - reloads, r.pins_ok, r.observed_rewrites); - omega_fp8_slot_table_fini(&rt); - pthread_cond_destroy(&r.cv); pthread_mutex_destroy(&r.m); - } - return 0; -} - -/* ---------------- chip ---------------- */ - -static void fill_expert(uint32_t seed, uint32_t n, uint32_t k, uint8_t *w, uint16_t *s) { - uint32_t st = seed * 2654435761u + 7u; - for (size_t i = 0; i < (size_t)n * k; i++) { uint8_t b = (uint8_t)(lcg(&st) >> 24); w[i] = (b & 0x7F) == 0x7F ? 0x3C : b; } - for (size_t i = 0; i < (size_t)(n / 128) * (k / 128); i++) s[i] = (uint16_t)(0x3B00u + (lcg(&st) >> 24) % 0x200u); /* bf16 ~2^-9..2^-7 */ -} - -static int chip_shape(uint32_t n, uint32_t k, uint32_t E, uint32_t S, uint32_t rounds, int mutant) { - printf("== shape n=%u k=%u, %u resident experts, pool of %u slots, %u churn rounds%s\n", n, k, E, S, rounds, mutant ? " (MUTANT)" : ""); - const size_t wb = (size_t)n * k, sc = (size_t)(n / 128) * (k / 128); - uint8_t *w = malloc(wb * E); uint16_t *s = malloc(sc * 2 * E); - float *x = malloc((size_t)k * 4 * 8), *yr = malloc((size_t)n * 4 * 8), *yp = malloc((size_t)n * 4 * 8); - if (!w || !s || !x || !yr || !yp) return 1; - for (uint32_t e = 0; e < E; e++) fill_expert(e + n, n, k, w + wb * e, s + sc * e); - uint32_t st = 99; - for (uint32_t i = 0; i < k * 8; i++) x[i] = (float)(lcg(&st) >> 8) / 16777216.0f * 2.0f - 1.0f; - OmegaGpuFp8Tensor *res = NULL; - int rc = omega_gpu_fp8_tensor_upload(E, n, k, w, s, &res); - if (rc != 0) { printf("FAIL resident upload: %s (%s)\n", omega_gpu_fp8_rc_name(rc), omega_gpu_fp8_last_error()); return 1; } - OmegaGpuAllocStats a0; omega_gpu_session_alloc_stats(&a0); - OmegaGpuFp8Slots *p = NULL; - rc = omega_gpu_fp8_slots_alloc(S, n, k, &p); - OmegaGpuAllocStats a1; omega_gpu_session_alloc_stats(&a1); - if (rc != 0) { printf("FAIL pool alloc: %s (%s)\n", omega_gpu_fp8_rc_name(rc), omega_gpu_fp8_last_error()); return 1; } - OmegaGpuFp8SlotsStats ps; omega_gpu_fp8_slots_stats(p, &ps); - CHECK(a1.alloc_bytes - a0.alloc_bytes >= ps.device_bytes && a1.alloc_bytes - a0.alloc_bytes <= ps.device_bytes + 2u * 65536u, - "pool driver bytes %" PRIu64 " for %" PRIu64 " payload bytes (page rounding only)", a1.alloc_bytes - a0.alloc_bytes, ps.device_bytes); - uint64_t *ver = calloc(S, 8); uint32_t *held = calloc(S, 4); - for (uint32_t sl = 0; sl < S; sl++) { - held[sl] = sl % E; - rc = omega_gpu_fp8_slots_load(p, sl, held[sl], w + wb * held[sl], s + sc * held[sl], &ver[sl]); - if (rc != 0) { printf("FAIL load slot %u: %s\n", sl, omega_gpu_fp8_slots_rc_name(rc)); return 1; } - } - /* 1 + 2: parity after every reload; groups = min(S, 8) slots per launch, shared x row (gate|up) or a row per group (down) */ - const uint32_t G = S < 8 ? S : 8; - uint32_t mism = 0, launches = 0; - for (uint32_t r = 0; r <= rounds && !mutant; r++) { - if (r > 0) { /* reload one slot with the next expert in the cycle */ - uint32_t sl = (r - 1) % S; held[sl] = (held[sl] + 1 + (r % 3)) % E; - rc = omega_gpu_fp8_slots_load(p, sl, held[sl], w + wb * held[sl], s + sc * held[sl], &ver[sl]); - if (rc != 0) { printf("FAIL reload r%u: %s\n", r, omega_gpu_fp8_slots_rc_name(rc)); mism++; break; } - } - uint32_t sls[8], ids[8]; uint64_t vs[8]; - for (uint32_t g = 0; g < G; g++) { sls[g] = (r + g) % S; vs[g] = ver[sls[g]]; ids[g] = held[sls[g]]; } - const uint32_t xr = (r & 1) ? G : 1; - int a = omega_gpu_fp8_gemv_grouped_f32(res, G, ids, x, xr, yr, NULL); - int b = omega_gpu_fp8_slots_gemv_grouped_f32(p, G, sls, vs, x, xr, yp, NULL); - launches += 2; - if (a != 0 || b != 0) { printf("FAIL launch r%u: resident %s pool %s (%s)\n", r, omega_gpu_fp8_rc_name(a), omega_gpu_fp8_slots_rc_name(b), omega_gpu_fp8_last_error()); mism++; break; } - if (memcmp(yr, yp, (size_t)G * n * 4) != 0) mism++; - } - if (!mutant) CHECK(mism == 0, "parity: %u launches, pool y bit-identical to the resident tensor after every reload", launches); - - /* 3: refusals on the chip pool */ - if (!mutant) { - CHECK(omega_gpu_fp8_slots_pin(p, 0, ver[0]) == 0, "pin slot 0"); - uint64_t vx = 0; - CHECK(omega_gpu_fp8_slots_load(p, 0, 7, w, s, &vx) == OMEGA_GPU_FP8_SLOTS_BUSY && vx == 0, "load into a pinned slot refused BUSY"); - CHECK(omega_gpu_fp8_slots_evict(p, 0) == OMEGA_GPU_FP8_SLOTS_BUSY, "evict of a pinned slot refused BUSY"); - omega_gpu_fp8_slots_unpin(p, 0, ver[0]); - uint64_t wva, sva; - CHECK(omega_gpu_fp8_slots_entry(p, 0, ver[0], &wva, &sva) == OMEGA_GPU_FP8_BAD_ARGS, "entry of an unpinned slot refused"); - uint64_t old = ver[0]; - CHECK(omega_gpu_fp8_slots_load(p, 0, held[0], w + wb * held[0], s + sc * held[0], &ver[0]) == 0 && ver[0] > old, "reload slot 0 -> newer version"); - uint32_t sl0 = 0; - CHECK(omega_gpu_fp8_slots_gemv_grouped_f32(p, 1, &sl0, &old, x, 1, yp, NULL) == OMEGA_GPU_FP8_SLOTS_STALE, "launch with the replaced version refused STALE (nothing launched)"); - uint8_t *bad = malloc(wb); memcpy(bad, w, wb); bad[wb / 2] = 0x7F; - uint64_t vb = 1; - CHECK(omega_gpu_fp8_slots_load(p, 1, 9, bad, s, &vb) == OMEGA_GPU_FP8_NAN_WEIGHT && vb == 0, "NaN weight refused"); - OmegaGpuFp8SlotInfo inf; omega_gpu_fp8_slots_query(p, 1, &inf); - CHECK(inf.state == 0 && omega_gpu_fp8_slots_pin(p, 1, ver[1]) == OMEGA_GPU_FP8_SLOTS_STALE, "refused load leaves the slot EMPTY; its old version cannot be pinned"); - free(bad); - rc = omega_gpu_fp8_slots_load(p, 1, held[1], w + wb * held[1], s + sc * held[1], &ver[1]); - if (rc != 0) g_failed++; - } - - /* 4: reader fence through a recorded command list */ - { - if (mutant) omega_gpu_fp8_slots_test_set_mutant(p, 1); - const uint32_t A = held[0], B = (held[0] + 1) % E; - OmegaGpuCmdList *cl = NULL; OmegaGpuMem tab, xd, yd; - if (omega_gpu_cmdlist_create(4, &cl) != 0) { printf("FAIL cmdlist create: %s\n", omega_gpu_session_last_error()); return 1; } - omega_gpu_session_lock(); - int arc = omega_gpu_session_alloc(16u, &tab) | omega_gpu_session_alloc((size_t)k * 4u, &xd) | omega_gpu_session_alloc((size_t)n * 4u, &yd); - omega_gpu_session_unlock(); - if (arc) { printf("FAIL alloc: %s\n", omega_gpu_session_last_error()); return 1; } - omega_fp8_pack_x_f32(x, k, xd.cpu); - float *y = yd.cpu; for (uint32_t i = 0; i < n; i++) y[i] = -999.0f; - /* reference for A and B on the resident tensor */ - float *ya = malloc((size_t)n * 4), *yb = malloc((size_t)n * 4); - int r1 = omega_gpu_fp8_gemv_grouped_f32(res, 1, &A, x, 1, ya, NULL), r2 = omega_gpu_fp8_gemv_grouped_f32(res, 1, &B, x, 1, yb, NULL); - CHECK(r1 == 0 && r2 == 0 && memcmp(ya, yb, (size_t)n * 4) != 0, "references: experts %u and %u give different y", A, B); - /* warm the kernel (grouped 1, x_rows 1) through the pool before recording */ - uint32_t sl0 = 0; float *yw = malloc((size_t)n * 4); - (void)omega_gpu_fp8_slots_gemv_grouped_f32(p, 1, &sl0, &ver[0], x, 1, yw, NULL); - int ok = omega_gpu_fp8_slots_pin(p, 0, ver[0]) == 0; - uint64_t *tw = tab.cpu; - ok = ok && omega_gpu_fp8_slots_entry(p, 0, ver[0], &tw[0], &tw[1]) == 0; - ok = ok && omega_gpu_session_sync_to_gpu(&tab) == 0 && omega_gpu_session_sync_to_gpu(&xd) == 0 && omega_gpu_session_sync_to_gpu(&yd) == 0; - omega_gpu_session_lock(); - omega_gpu_cmdlist_reset(cl); - ok = ok && omega_gpu_fp8_gemv_grouped_record(cl, omega_gpu_fp8_slots_tensor(p), 1, tab.va, xd.va, 1, yd.va) == 0; - omega_gpu_session_unlock(); - /* the replacement attempt: between record and submit (the list may read the slot from here until submit returns) */ - uint64_t vnew = 0; - int lrc = omega_gpu_fp8_slots_load(p, 0, B, w + wb * B, s + sc * B, &vnew); - if (!mutant) CHECK(lrc == OMEGA_GPU_FP8_SLOTS_BUSY, "load into the slot a recorded list reads: refused BUSY"); - else printf("info mutant: load into the pinned slot returned %s\n", omega_gpu_fp8_slots_rc_name(lrc)); - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; - OmegaGpuCmdListStats cs; memset(&cs, 0, sizeof cs); - omega_gpu_session_lock(); - ok = ok && omega_gpu_cmdlist_submit(cl, &o, &cs) == 0; - omega_gpu_session_unlock(); - ok = ok && omega_gpu_session_sync_to_cpu(&yd) == 0; - (void)omega_gpu_fp8_slots_unpin(p, 0, ver[0]); - const int same_a = ok && memcmp(y, ya, (size_t)n * 4) == 0, same_b = ok && memcmp(y, yb, (size_t)n * 4) == 0; - if (!mutant) CHECK(ok && same_a, "the list read the pinned expert %u bit-exactly (submit ok=%d)", A, ok); - else { - CHECK(ok && same_a, "NEGATIVE CONTROL: list output equals pinned expert %u (expected to FAIL under the mutant; read B=%d)", A, same_b); - } - free(ya); free(yb); free(yw); - omega_gpu_session_lock(); omega_gpu_session_free(&tab); omega_gpu_session_free(&xd); omega_gpu_session_free(&yd); omega_gpu_session_unlock(); - omega_gpu_cmdlist_free(cl); - if (mutant) omega_gpu_fp8_slots_test_set_mutant(p, 0); - } - - omega_gpu_fp8_slots_stats(p, &ps); - printf("stats slots=%u device_bytes=%" PRIu64 " loads=%" PRIu64 " load_failures=%" PRIu64 " busy=%" PRIu64 " stale=%" PRIu64 - " pins=%" PRIu64 " pinned_now=%u pinned_high=%u bytes_loaded=%" PRIu64 " load_ns=%" PRIu64 " load_GBps=%.3f\n", - ps.slots, ps.device_bytes, ps.loads, ps.load_failures, ps.busy_refusals, ps.stale_refusals, ps.pins, ps.pinned_now, - ps.pinned_high, ps.bytes_loaded, ps.load_ns, ps.load_ns ? (double)ps.bytes_loaded / (double)ps.load_ns : 0.0); - CHECK(ps.pinned_now == 0 && ps.pinned_high <= G, "no pin leaked (pinned_now 0, high-water %u <= %u)", ps.pinned_high, G); - OmegaGpuAllocStats a2; omega_gpu_session_alloc_stats(&a2); - CHECK(omega_gpu_fp8_slots_free(p) == 0, "pool freed"); - OmegaGpuAllocStats a3; omega_gpu_session_alloc_stats(&a3); - CHECK(a3.frees >= a2.frees + 2, "pool returned its 2 driver buffers (frees %" PRIu64 " -> %" PRIu64 ")", a2.frees, a3.frees); - omega_gpu_fp8_tensor_free(res); - free(w); free(s); free(x); free(yr); free(yp); free(ver); free(held); - return 0; -} - -int main(int argc, char **argv) { - int host = 0, chip = 0, mutant = 0; uint32_t rounds = 64; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) host = 1; - else if (!strcmp(argv[i], "--chip")) chip = 1; - else if (!strcmp(argv[i], "--mutant")) mutant = 1; - else if (!strcmp(argv[i], "--rounds") && i + 1 < argc) rounds = (uint32_t)atoi(argv[++i]); - else { printf("usage: %s --host-only | --chip [--rounds R] [--mutant]\n", argv[0]); return 2; } - } - if (!host && !chip) { printf("usage: %s --host-only | --chip [--rounds R] [--mutant]\n", argv[0]); return 2; } - if (host) host_tests(); - if (chip) { - (void)omega_gpu_session_set_spin_us(2000); - chip_shape(1536, 2048, 12, 5, rounds, mutant); /* gate|up */ - if (!mutant) chip_shape(2048, 768, 12, 5, rounds, 0); /* down */ - if (omega_gpu_session_is_blocked()) { printf("FAIL session latched\n"); g_failed++; } - } - if (mutant) { - printf("GPU_FP8_SLOTS_NEGATIVE_CONTROL: %s (%d of %d checks failed)\n", g_failed ? "CAUGHT" : "NOT CAUGHT", g_failed, g_checks); - return g_failed ? 1 : 0; - } - printf("GPU_FP8_SLOTS: %s (%d checks, %d failed)\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_fp8gemm_test.c b/tests/gpu_fp8gemm_test.c deleted file mode 100644 index d44d35a68..000000000 --- a/tests/gpu_fp8gemm_test.c +++ /dev/null @@ -1,491 +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. - */ - -/* - * gpu_fp8gemm_test: the prefill FP8 grouped GEMM (omega_gpu_fp8gemm_api.h), OWN-30B builder F item 26. - * --host-only emulation vs the FP8 double oracle, permutation, codegen budgets and refusals (no device) - * --sim warp-simulator parity (build with -DWS_MAX_THREADS=512): bit-identical to the host emulation of the - * GEMV's summation order in both fragment orders, multi-segment, multi-pass, row clamping, mutants 1-3 caught - * (default) the chip. Gate|up 128 x 1536 x 2048 and down 128 x 2048 x 768 over 64 tokens x top-8 routed rows, dense - * qkv 5120 x 2048 and o 2048 x 4096 over 64 rows: every output row bit-identical to omega_gpu_fp8_gemv_f32 - * on the same row, a few rows against the host emulation and the double oracle, mutants caught, - * timing medians (host caches evicted) vs the per-token grouped-GEMV path. - * knobs: --reps N --mt N --warps N --ctas N --no-evict --tokens N --spin-us N --shape gateup|down|qkv|o|all --out receipt.json - * Verdict line last: "gpu_fp8gemm_test: N checks, F failed: PASS|FAIL". - */ -#include "omega_gpu_fp8gemm_api.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); } -static float bf16_f32(uint16_t b) { uint32_t x = (uint32_t)b << 16; float f; memcpy(&f, &x, 4); return f; } -static uint8_t rand_e4m3(uint32_t *s) { uint8_t b = (uint8_t)(lcg(s) >> 24); if (omega_fp8_e4m3_is_nan(b)) b = (uint8_t)(b - 1); return b; } -static float f32_of_bits(uint32_t b) { float f; memcpy(&f, &b, 4); return f; } - -typedef struct { uint32_t experts, n, k; uint8_t *w; uint16_t *s; } Weights; -static void weights_make(Weights *W, uint32_t experts, uint32_t n, uint32_t k, uint32_t seed) { - W->experts = experts; W->n = n; W->k = k; - size_t wb = (size_t)experts * n * k, sc = (size_t)experts * ((n + 127) / 128) * (k / 128); - W->w = malloc(wb); W->s = malloc(sc * 2); - uint32_t st = seed; - for (size_t i = 0; i < wb; i++) W->w[i] = rand_e4m3(&st); - for (size_t i = 0; i < sc; i++) W->s[i] = bf16_rne(frand(&st, 0.001f, 0.1f) * ((lcg(&st) & 1) ? 1.0f : -1.0f)); -} -static void weights_free(Weights *W) { free(W->w); free(W->s); } - -/* The kernel's exact f32 result for one (expert row, activation row): per lane, per K step a dot chain over the lane's LB - * bytes (word, byte), acc = fma(dot, S', acc), then the SHFL.DOWN tree 16..1. w: the row's k bytes, s: its k/128 scale words - * (bf16 bits of one 128-row block), x: natural-order activation row. */ -static float emu_row(const uint8_t *w, const uint16_t *s, const float *x, uint32_t k, uint32_t lb) { - /* static, not 64 KB of stack (omega#456); this test runs one thread. k is bounded by OMEGA_FP8_MAX_K (16384). */ - static float xp[16384]; - if (k > sizeof xp / sizeof xp[0]) { fprintf(stderr, "emu_row: k=%u exceeds %zu\n", k, sizeof xp / sizeof xp[0]); exit(2); } - omega_fp8_pack_x_f32(x, k, xp); - float a[32]; const uint32_t steps = k / (32u * lb); - for (unsigned lane = 0; lane < 32; lane++) { - float acc = 0.0f; - for (uint32_t st = 0; st < steps; st++) { - float dot = 0.0f; const uint32_t c0 = st * 32u * lb + lane * lb; - for (uint32_t b = 0; b < lb; b++) dot = fmaf(f32_of_bits(omega_fp8_e4m3_kernel_bits(w[c0 + b])), xp[c0 + b], dot); - float sp = bf16_f32(s[c0 / 128u]) * 72057594037927936.0f; /* * 2^56 */ - acc = fmaf(dot, sp, acc); - } - a[lane] = acc; - } - for (unsigned o = 16; o >= 1; o /= 2) { float b[32]; for (unsigned l = 0; l < 32; l++) b[l] = a[l + o < 32 ? l + o : l]; for (unsigned l = 0; l < 32; l++) a[l] += b[l]; } - return a[0]; -} -/* full expected output of a row table against Weights W (emulation) */ -static void expect_rows(const Weights *W, uint32_t M, const uint32_t *ids, const uint32_t *trow, const float *x, float *y, uint32_t lb) { - const uint32_t n = W->n, k = W->k; - for (uint32_t i = 0; i < M; i++) for (uint32_t r = 0; r < n; r++) - y[(size_t)i * n + r] = emu_row(W->w + ((size_t)ids[i] * n + r) * k, W->s + ((size_t)ids[i] * ((n + 127) / 128) + r / 128) * (k / 128), x + (size_t)trow[i] * k, k, lb); -} -static float *make_x(uint32_t rows, uint32_t k, uint32_t seed) { - float *x = malloc((size_t)rows * k * 4); uint32_t s = seed; - for (size_t i = 0; i < (size_t)rows * k; i++) x[i] = frand(&s, -2.0f, 2.0f); - return x; -} -/* a routed row table: `tokens` tokens x top-k distinct experts, sorted by expert (ties by token) */ -static uint32_t make_table(uint32_t tokens, uint32_t topk, uint32_t experts, uint32_t seed, uint32_t *ids, uint32_t *trow, uint32_t *picks) { - uint32_t M = tokens * topk, st = seed; - uint32_t *cnt = calloc(experts, 4), (*pick)[16] = malloc((size_t)tokens * sizeof *pick); - for (uint32_t t = 0; t < tokens; t++) for (uint32_t j = 0; j < topk; j++) { - uint32_t e; int dup; - do { e = (lcg(&st) >> 8) % experts; dup = 0; for (uint32_t q = 0; q < j; q++) if (pick[t][q] == e) dup = 1; } while (dup); - pick[t][j] = e; cnt[e]++; - } - uint32_t *pos = malloc(experts * 4), c = 0; - for (uint32_t e = 0; e < experts; e++) { pos[e] = c; c += cnt[e]; } - for (uint32_t t = 0; t < tokens; t++) for (uint32_t j = 0; j < topk; j++) { uint32_t e = pick[t][j], p = pos[e]++; ids[p] = e; trow[p] = t; } - for (uint32_t t = 0; t < tokens; t++) for (uint32_t j = 0; j < topk; j++) picks[t * topk + j] = pick[t][j]; - free(cnt); free(pick); free(pos); - return M; -} - -static void host_only(void) { - printf("host-only: emulation, permutation, budgets\n"); - { Weights W; weights_make(&W, 1, 128, 2048, 5); float *x = make_x(1, 2048, 6); - double yo[128], ys[128]; omega_fp8_gemv_oracle(W.w, W.s, 128, 2048, x, yo, ys); - double worst = 0; for (uint32_t r = 0; r < 128; r++) { float e = emu_row(W.w + (size_t)r * 2048, W.s, x, 2048, 16); (void)e; } - for (uint32_t r = 0; r < 128; r++) { float e = emu_row(W.w + (size_t)r * 2048, W.s + (r / 128) * 16, x, 2048, 16); double d = fabs((double)e - yo[r]) / (ys[r] + 1e-30); if (d > worst) worst = d; } - CHECK(worst < 1e-5, "emulation vs the FP8 double oracle: worst rel %.2e", worst); - printf("emulation vs oracle: worst relative error %.2e of the term scale\n", worst); - weights_free(&W); free(x); } - { /* permutation is a bijection of each row, scaled by 2^64 */ - float x[2048], p[2048]; for (unsigned i = 0; i < 2048; i++) x[i] = (float)(i + 1); - omega_fp8gemm_permute_x(x, 2048, 16, p); - char *seen = calloc(2048, 1); int ok = 1; - for (unsigned i = 0; i < 2048; i++) { double v = (double)p[i] / 18446744073709551616.0; if (v < 1 || v > 2048 || seen[(int)v - 1]++) ok = 0; } - CHECK(ok, "permutation of a 2048-row is a bijection"); free(seen); - float p8[768]; float x8[768]; for (unsigned i = 0; i < 768; i++) x8[i] = (float)(i + 1); - omega_fp8gemm_permute_x(x8, 768, 8, p8); ok = 1; seen = calloc(768, 1); - for (unsigned i = 0; i < 768; i++) { double v = (double)p8[i] / 18446744073709551616.0; if (v < 1 || v > 768 || seen[(int)v - 1]++) ok = 0; } - CHECK(ok, "permutation of a 768-row (lane 8) is a bijection"); free(seen); - /* column c = lane L, word w, byte e of step 0 lands at (w*32 + L)*4 + e: c = 5 * 16 + 6 = 86 -> L 5, j 6 -> w 1, e 2 */ - CHECK(p[(1 * 32 + 5) * 4 + 2] / 18446744073709551616.0f == x[86], "column 86 sits at lane 5 word 1 element 2"); } - struct { uint32_t k, lb, mt, w; } shp[] = { { 2048, 16, 8, 16 }, { 4096, 16, 8, 16 }, { 1024, 16, 8, 16 }, { 768, 8, 8, 16 }, { 768, 8, 8, 8 }, { 2048, 8, 8, 16 }, { 2048, 16, 4, 16 }, { 2048, 16, 8, 32 }, { 2048, 16, 8, 8 }, { 2048, 16, 4, 8 }, { 4096, 16, 4, 8 } }; - for (unsigned i = 0; i < sizeof shp / sizeof shp[0]; i++) for (int m = 0; m <= 3; m++) { - OmegaFp8GemmSpec s = { shp[i].k, shp[i].lb, shp[i].mt, shp[i].w, m, 0 }; uint32_t n = 0, gp = 0; - int rc = omega_fp8gemm_prog_stats(&s, &n, &gp); - uint32_t decl = ((gp + 1 + 7) / 8) * 8; - CHECK(rc == 0 && n <= 1024, "codegen k %u lb %u mt %u warps %u mutant %d: rc %d insns %u gprs %u", s.k, s.lane_bytes, s.mt, s.warps, m, rc, n, gp); - if (m == 0 && rc == 0) printf("codegen k %4u lane %2u mt %2u warps %2u: %u instructions, %u registers (declared %u, register file %u of 65536)%s, shared %u B\n", s.k, s.lane_bytes, s.mt, s.warps, n, gp, decl, 32u * s.warps * decl, 32u * s.warps * decl <= 65536u ? "" : " DOES NOT FIT", omega_fp8gemm_shared_bytes(&s)); - } - { OmegaFp8GemmSpec s = { 2048, 16, 16, 16, 0, 0 }; CHECK(omega_fp8gemm_prog_stats(&s, NULL, NULL) != 0, "mt 16 at lane 16 refused (32 KB of shared memory)"); } - { OmegaFp8GemmSpec s = { 2048, 16, 6, 16, 0, 0 }; CHECK(omega_fp8gemm_prog_stats(&s, NULL, NULL) != 0, "mt 6 refused"); } - { OmegaFp8GemmSpec s = { 2048, 16, 8, 16, 5, 0 }; CHECK(omega_fp8gemm_prog_stats(&s, NULL, NULL) != 0, "mutant 5 refused"); } - { OmegaFp8GemmSpec s = { 2048, 16, 8, 16, 0, 2 }; CHECK(omega_fp8gemm_prog_stats(&s, NULL, NULL) != 0, "rowmap 2 refused"); } - { OmegaFp8GemmSpec s = { 2048, 16, 8, 16, 0, 1 }; CHECK(omega_fp8gemm_prog_stats(&s, NULL, NULL) != 0, "rowmap at mt 8 refused (registers)"); } - { uint32_t ks[] = { 2048, 4096, 512, 768 }; for (unsigned i = 0; i < 4; i++) { - OmegaFp8GemmSpec s = { ks[i], ks[i] % 512 ? 8u : 16u, 4, 16, 0, 1 }; uint32_t n = 0, gp = 0; - int rc = omega_fp8gemm_prog_stats(&s, &n, &gp); - uint32_t decl = ((gp + 1 + 7) / 8) * 8; - CHECK(rc == 0 && n <= 1024 && 32u * s.warps * decl <= 65536u, "codegen k %u mt 4 rowmap: rc %d insns %u gprs %u", ks[i], rc, n, gp); - printf("codegen k %4u lane %2u mt 4 warps 16 rowmap: %u instructions, %u registers (declared %u, register file %u of 65536)\n", s.k, s.lane_bytes, n, gp, decl, 32u * s.warps * decl); - } } - CHECK(OMEGA_GEMM_ARGS_WORDS <= OMEGA_GPU_SESSION_MAX_ARGS, "argument words fit the constant bank window"); - uint32_t ids[3] = { 2, 1, 1 }, tr[3] = { 0, 0, 0 }; float xr[2048] = { 0 }, yo[4]; - CHECK(omega_gpu_fp8gemm_f32(NULL, 3, ids, tr, xr, 1, yo, NULL) == OMEGA_GPU_FP8GEMM_BAD_ARGS, "a NULL tensor is refused"); -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -typedef struct { uint32_t k, n, lb, mt, w, grid; uint32_t counts[4]; uint32_t nseg; } SimPt; -static int sim_point(const SimPt *p, int mutant, uint32_t seed, char *msg, size_t msgn, size_t *bad) { - static BlackwellIRProgram prog; - OmegaFp8GemmSpec spec = { p->k, p->lb, p->mt, p->w, mutant, 0 }; - if (omega_blackwell_codegen_fp8gemm_prog(&spec, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - uint32_t M = 0; for (uint32_t g = 0; g < p->nseg; g++) M += p->counts[g]; - Weights W; weights_make(&W, p->nseg, p->n, p->k, seed); - uint32_t ids[64], trow[64]; { uint32_t i = 0; for (uint32_t g = 0; g < p->nseg; g++) for (uint32_t c = 0; c < p->counts[g]; c++, i++) { ids[i] = g; trow[i] = (i * 5 + 1) % 16; } } - float *x = make_x(16, p->k, seed + 1); - float *yexp = malloc((size_t)M * p->n * 4); - expect_rows(&W, M, ids, trow, x, yexp, p->lb); - size_t wbytes = (size_t)p->nseg * p->n * p->k, sc = (size_t)p->nseg * ((p->n + 127) / 128) * (p->k / 128); - uint8_t *wd = aligned_alloc(16, (wbytes + 15) & ~15ull); memcpy(wd, W.w, wbytes); - float *sd = aligned_alloc(16, ((sc * 4) + 15) & ~15ull); omega_fp8_pack_scales(W.s, sc, sd, 0); - float *xp = aligned_alloc(16, ((size_t)(M + p->mt) * p->k * 4 + 15) & ~15ull); memset(xp, 0, (size_t)(M + p->mt) * p->k * 4); - float *tmp = malloc((size_t)p->k * 4); - for (uint32_t i = 0; i < M; i++) { memcpy(tmp, x + (size_t)trow[i] * p->k, (size_t)p->k * 4); omega_fp8gemm_permute_x(tmp, p->k, p->lb, xp + (size_t)i * p->k); } - typedef struct { uint64_t w, s; uint32_t row0, cnt, pad[2]; } Seg; - Seg *seg = aligned_alloc(16, 64 * sizeof(Seg)); memset(seg, 0, 64 * sizeof(Seg)); - { uint32_t r0 = 0; for (uint32_t g = 0; g < p->nseg; g++) { seg[g].w = (uintptr_t)(wd + (size_t)g * p->n * p->k); seg[g].s = (uintptr_t)(sd + (size_t)g * ((p->n + 127) / 128) * (p->k / 128)); seg[g].row0 = r0; seg[g].cnt = p->counts[g]; r0 += p->counts[g]; } } - float *y = aligned_alloc(16, ((size_t)M * p->n * 4 + 15) & ~15ull); - uint32_t shared = omega_fp8gemm_shared_bytes(&spec); - uint8_t *smem = aligned_alloc(16, shared); - float *ycopy = NULL; int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * p->w; s.order = order; s.smem = smem; s.smem_bytes = shared; - for (size_t i = 0; i < (size_t)M * p->n; i++) y[i] = -999.0f; - uint64_t A[3] = { (uintptr_t)seg, (uintptr_t)xp, (uintptr_t)y }; - for (unsigned i = 0; i < 3; i++) { s.cbank[(OMEGA_GEMM_ARG_SEG + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(OMEGA_GEMM_ARG_SEG + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - s.cbank[OMEGA_GEMM_ARG_N / 4] = p->n; s.cbank[OMEGA_GEMM_ARG_STRIDE / 4] = p->grid * p->w; - s.nranges = 5; - s.ranges[0].lo = (uintptr_t)seg; s.ranges[0].hi = (uintptr_t)seg + 64 * sizeof(Seg); - s.ranges[1].lo = (uintptr_t)wd; s.ranges[1].hi = (uintptr_t)wd + wbytes; - s.ranges[2].lo = (uintptr_t)sd; s.ranges[2].hi = (uintptr_t)sd + sc * 4; - s.ranges[3].lo = (uintptr_t)xp; s.ranges[3].hi = (uintptr_t)xp + (size_t)(M + p->mt) * p->k * 4; - s.ranges[4].lo = (uintptr_t)y; s.ranges[4].hi = (uintptr_t)y + (size_t)M * p->n * 4; - err = ws_run(&s, p->grid, p->nseg); - if (err) { snprintf(msg, msgn, "order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (size_t i = 0; i < (size_t)M * p->n; i++) if (y[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, msgn, "%zu output words never written", unwritten); break; } - if (order == 0) { ycopy = malloc((size_t)M * p->n * 4); memcpy(ycopy, y, (size_t)M * p->n * 4); } - else if (memcmp(ycopy, y, (size_t)M * p->n * 4) != 0) { err = -1; snprintf(msg, msgn, "the fragment order changed the result"); } - } - if (!err) { size_t b = 0; for (size_t i = 0; i < (size_t)M * p->n; i++) if (memcmp(&yexp[i], &y[i], 4) != 0) b++; *bad = b; snprintf(msg, msgn, "%zu of %zu outputs differ from the emulation%s", b, (size_t)M * p->n, b ? "" : " (bit-identical)"); } - free(ycopy); free(wd); free(sd); free(xp); free(tmp); free(seg); free(y); free(smem); free(yexp); free(x); weights_free(&W); - return err; -} -/* The stroke's forms of the kernel (L312, 2026-10-21): an empty segment (cnt 0) in the table, and rowmap (x' rows through XMAP, - * y rows through YMAP). empty_at >= 0 inserts a cnt 0 entry at that table index (grid_y = nseg + 1). With rowmap the x' buffer - * holds the 16 permuted SOURCE rows and XMAP[i] = trow[i]; YMAP is a random permutation of the M sorted rows, so the mapped - * result must equal the emulation moved through YMAP and differ from the unmoved one. budget: the simulator's step budget. */ -static int sim_point2(const SimPt *p, int mutant, uint32_t seed, int rowmap, int empty_at, uint64_t budget, char *msg, size_t msgn, size_t *bad, int *moved) { - static BlackwellIRProgram prog; - OmegaFp8GemmSpec spec = { p->k, p->lb, p->mt, p->w, mutant, (uint32_t)rowmap }; - if (omega_blackwell_codegen_fp8gemm_prog(&spec, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - uint32_t M = 0; for (uint32_t g = 0; g < p->nseg; g++) M += p->counts[g]; - Weights W; weights_make(&W, p->nseg, p->n, p->k, seed); - uint32_t ids[64], trow[64]; { uint32_t i = 0; for (uint32_t g = 0; g < p->nseg; g++) for (uint32_t c = 0; c < p->counts[g]; c++, i++) { ids[i] = g; trow[i] = (i * 5 + 1) % 16; } } - float *x = make_x(16, p->k, seed + 1); - float *yexp = malloc((size_t)M * p->n * 4); - expect_rows(&W, M, ids, trow, x, yexp, p->lb); - size_t wbytes = (size_t)p->nseg * p->n * p->k, sc = (size_t)p->nseg * ((p->n + 127) / 128) * (p->k / 128); - uint8_t *wd = aligned_alloc(16, (wbytes + 15) & ~15ull); memcpy(wd, W.w, wbytes); - float *sd = aligned_alloc(16, ((sc * 4) + 15) & ~15ull); omega_fp8_pack_scales(W.s, sc, sd, 0); - const uint32_t xrows = rowmap ? 16u : M + p->mt; - float *xp = aligned_alloc(16, ((size_t)xrows * p->k * 4 + 15) & ~15ull); memset(xp, 0, (size_t)xrows * p->k * 4); - float *tmp = malloc((size_t)p->k * 4); - if (rowmap) for (uint32_t r = 0; r < 16; r++) { memcpy(tmp, x + (size_t)r * p->k, (size_t)p->k * 4); omega_fp8gemm_permute_x(tmp, p->k, p->lb, xp + (size_t)r * p->k); } - else for (uint32_t i = 0; i < M; i++) { memcpy(tmp, x + (size_t)trow[i] * p->k, (size_t)p->k * 4); omega_fp8gemm_permute_x(tmp, p->k, p->lb, xp + (size_t)i * p->k); } - uint32_t *xmap = aligned_alloc(16, 256 * 4), *ymap = aligned_alloc(16, 256 * 4); - memset(xmap, 0, 256 * 4); memset(ymap, 0, 256 * 4); - { uint32_t s = seed * 7u + 3u; for (uint32_t i = 0; i < M; i++) { xmap[i] = trow[i]; ymap[i] = i; } - for (uint32_t i = M; i > 1; i--) { uint32_t j = lcg(&s) % i, t = ymap[i - 1]; ymap[i - 1] = ymap[j]; ymap[j] = t; } } - float *yexp2 = malloc((size_t)M * p->n * 4); - for (uint32_t i = 0; i < M; i++) memcpy(yexp2 + (size_t)(rowmap ? ymap[i] : i) * p->n, yexp + (size_t)i * p->n, (size_t)p->n * 4); - typedef struct { uint64_t w, s; uint32_t row0, cnt, pad[2]; } Seg; - Seg *seg = aligned_alloc(16, 64 * sizeof(Seg)); memset(seg, 0, 64 * sizeof(Seg)); - uint32_t segs = 0; - { uint32_t r0 = 0; - for (uint32_t g = 0; g < p->nseg; g++) { - if ((int)segs == empty_at) { seg[segs].w = (uintptr_t)wd; seg[segs].s = (uintptr_t)sd; seg[segs].row0 = r0; seg[segs].cnt = 0; segs++; } - seg[segs].w = (uintptr_t)(wd + (size_t)g * p->n * p->k); seg[segs].s = (uintptr_t)(sd + (size_t)g * ((p->n + 127) / 128) * (p->k / 128)); - seg[segs].row0 = r0; seg[segs].cnt = p->counts[g]; r0 += p->counts[g]; segs++; - } - if ((int)segs == empty_at) { seg[segs].w = (uintptr_t)wd; seg[segs].s = (uintptr_t)sd; seg[segs].row0 = r0; seg[segs].cnt = 0; segs++; } } - float *y = aligned_alloc(16, ((size_t)M * p->n * 4 + 15) & ~15ull); - uint32_t shared = omega_fp8gemm_shared_bytes(&spec); - uint8_t *smem = aligned_alloc(16, shared); - float *ycopy = NULL; int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * p->w; s.order = order; s.smem = smem; s.smem_bytes = shared; s.step_budget = budget; - for (size_t i = 0; i < (size_t)M * p->n; i++) y[i] = -999.0f; - uint64_t A[3] = { (uintptr_t)seg, (uintptr_t)xp, (uintptr_t)y }; - for (unsigned i = 0; i < 3; i++) { s.cbank[(OMEGA_GEMM_ARG_SEG + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(OMEGA_GEMM_ARG_SEG + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - s.cbank[OMEGA_GEMM_ARG_N / 4] = p->n; s.cbank[OMEGA_GEMM_ARG_STRIDE / 4] = p->grid * p->w; - s.cbank[OMEGA_GEMM_ARG_XMAP / 4] = (uint32_t)(uintptr_t)xmap; s.cbank[OMEGA_GEMM_ARG_XMAP / 4 + 1] = (uint32_t)((uintptr_t)xmap >> 32); - s.cbank[OMEGA_GEMM_ARG_YMAP / 4] = (uint32_t)(uintptr_t)ymap; s.cbank[OMEGA_GEMM_ARG_YMAP / 4 + 1] = (uint32_t)((uintptr_t)ymap >> 32); - s.nranges = 7; - s.ranges[0].lo = (uintptr_t)seg; s.ranges[0].hi = (uintptr_t)seg + 64 * sizeof(Seg); - s.ranges[1].lo = (uintptr_t)wd; s.ranges[1].hi = (uintptr_t)wd + wbytes; - s.ranges[2].lo = (uintptr_t)sd; s.ranges[2].hi = (uintptr_t)sd + sc * 4; - s.ranges[3].lo = (uintptr_t)xp; s.ranges[3].hi = (uintptr_t)xp + (size_t)xrows * p->k * 4; - s.ranges[4].lo = (uintptr_t)y; s.ranges[4].hi = (uintptr_t)y + (size_t)M * p->n * 4; - s.ranges[5].lo = (uintptr_t)xmap; s.ranges[5].hi = (uintptr_t)xmap + (M + p->mt) * 4; - s.ranges[6].lo = (uintptr_t)ymap; s.ranges[6].hi = (uintptr_t)ymap + (M + p->mt) * 4; - err = ws_run(&s, p->grid, segs); - if (err) { snprintf(msg, msgn, "order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (size_t i = 0; i < (size_t)M * p->n; i++) if (y[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, msgn, "%zu output words never written", unwritten); break; } - if (order == 0) { ycopy = malloc((size_t)M * p->n * 4); memcpy(ycopy, y, (size_t)M * p->n * 4); } - else if (memcmp(ycopy, y, (size_t)M * p->n * 4) != 0) { err = -1; snprintf(msg, msgn, "the fragment order changed the result"); } - } - if (!err) { - size_t b = 0; for (size_t i = 0; i < (size_t)M * p->n; i++) if (memcmp(&yexp2[i], &y[i], 4) != 0) b++; - *bad = b; if (moved) *moved = memcmp(yexp, y, (size_t)M * p->n * 4) != 0; - snprintf(msg, msgn, "%zu of %zu outputs differ from the emulation%s%s", b, (size_t)M * p->n, b ? "" : " (bit-identical)", rowmap ? (memcmp(yexp, y, (size_t)M * p->n * 4) ? ", rows moved by YMAP" : ", YMAP moved nothing") : ""); - } - free(ycopy); free(wd); free(sd); free(xp); free(tmp); free(seg); free(y); free(smem); free(yexp); free(yexp2); free(x); free(xmap); free(ymap); weights_free(&W); - return err; -} - -static void sim_battery(void) { - SimPt pts[] = { - { 2048, 40, 16, 8, 16, 2, { 1, 5, 9 }, 3 }, /* lane 16, KS 4 (2 iterations), 2 passes in segment 3, row clamping (n 40 < 2 x 32 x 1) */ - { 4096, 20, 16, 8, 16, 1, { 3, 8 }, 2 }, /* KS 8: 4 iterations */ - { 1024, 33, 16, 8, 16, 2, { 2, 1 }, 2 }, /* KS 2: one iteration, no tail prefetch */ - { 768, 130, 8, 8, 16, 2, { 4, 17 }, 2 }, /* lane 8, KS 3 (odd, unrolled), 2 row blocks of scales, 2 passes */ - { 768, 24, 8, 8, 8, 1, { 1, 8, 2 }, 3 }, /* lane 8 at 8 warps */ - { 2048, 16, 16, 4, 16, 1, { 6, 4 }, 2 }, /* mt 4 */ - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - char msg[300]; size_t bad = 1; - int err = sim_point(&pts[i], 0, 31 + (uint32_t)i, msg, sizeof msg, &bad); - CHECK(!err && bad == 0, "sim k %u n %u lane %u mt %u warps %u grid %u: %s", pts[i].k, pts[i].n, pts[i].lb, pts[i].mt, pts[i].w, pts[i].grid, msg); - printf("sim k %u n %u lane %u mt %u warps %u grid %u: %s %s\n", pts[i].k, pts[i].n, pts[i].lb, pts[i].mt, pts[i].w, pts[i].grid, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - for (int m = 1; m <= 3; m++) { - char msg[300]; size_t bad = 0; - int err = sim_point(&pts[0], m, 77, msg, sizeof msg, &bad); - CHECK(!err && bad != 0, "sim mutant %d must be caught: %s", m, msg); - printf("sim mutant %d: %s %s\n", m, err ? "ERROR" : bad ? "caught" : "NOT CAUGHT", msg); - } - /* the stroke's forms (L312): empty segments and row maps */ - { - char msg[300]; size_t bad = 1; int moved = 0; - /* RED first: mutant 4 (the guard dropped) on an empty segment must run out of steps */ - int err = sim_point2(&pts[5], 4, 99, 0, 1, 2000000ull, msg, sizeof msg, &bad, NULL); - /* the runaway pass loop is caught either way: the step budget, or a read past the x' rows (the simulator checks every address) */ - CHECK(err != 0 && (strstr(msg, "step budget") || strstr(msg, "outside the declared buffers")), "sim mutant 4 (no empty-segment guard) must be caught: %s", msg); - printf("sim empty segment, mutant 4 (guard dropped): %s %s\n", err ? "caught" : "NOT CAUGHT", msg); - /* GREEN: the guard; an empty segment first, in the middle, last */ - for (int at = 0; at <= 2; at++) { - err = sim_point2(&pts[0], 0, 41 + (uint32_t)at, 0, at + (at == 2 ? 1 : 0), 0, msg, sizeof msg, &bad, NULL); - CHECK(!err && bad == 0, "sim empty segment at %d: %s", at, msg); - printf("sim k %u empty segment at index %d: %s %s\n", pts[0].k, at + (at == 2 ? 1 : 0), err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - /* rowmap: x' rows through XMAP (16 source rows), y rows through YMAP (a random permutation); with and without an empty segment */ - const SimPt rmpts[] = { - { 2048, 40, 16, 4, 16, 2, { 1, 5, 9 }, 3 }, /* 3 passes in segment 3 (mt 4), row clamping */ - { 4096, 20, 16, 4, 16, 1, { 3, 8 }, 2 }, /* KS 8, + an empty segment */ - { 512, 40, 16, 4, 16, 2, { 1, 5, 9 }, 3 }, /* the down projection: KS 1 (unrolled) */ - { 768, 24, 8, 4, 8, 1, { 1, 8, 2 }, 3 }, /* lane 8 at 8 warps */ - { 2048, 16, 16, 4, 16, 1, { 6, 4 }, 2 }, - }; - for (size_t i = 0; i < sizeof rmpts / sizeof rmpts[0]; i++) { - const SimPt *p = &rmpts[i]; - err = sim_point2(p, 0, 61 + (uint32_t)i, 1, i == 1 ? 1 : -1, 0, msg, sizeof msg, &bad, &moved); - CHECK(!err && bad == 0 && moved, "sim rowmap k %u mt %u%s: %s", p->k, p->mt, i == 1 ? " + empty segment" : "", msg); - printf("sim rowmap k %u n %u mt %u warps %u%s: %s %s\n", p->k, p->n, p->mt, p->w, i == 1 ? " + empty segment" : "", err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - for (int m = 1; m <= 3; m++) { - err = sim_point2(&rmpts[0], m, 77, 1, -1, 0, msg, sizeof msg, &bad, NULL); - CHECK(!err && bad != 0, "sim rowmap mutant %d must be caught: %s", m, msg); - printf("sim rowmap mutant %d: %s %s\n", m, err ? "ERROR" : bad ? "caught" : "NOT CAUGHT", msg); - } - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static int g_evict = 1; -static void evict_host_caches(void) { - static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass; - if (!buf) buf = malloc(sz); - if (!buf) return; - memset(buf, ++pass, sz); - volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i]; -} -static double med(uint64_t *v, uint32_t n) { qsort(v, n, 8, cmp_u64); return (double)v[n / 2]; } - -typedef struct { const char *name; uint32_t experts, n, k, tokens, topk; } Shape; -static FILE *g_out; static int g_first = 1; - -static void run_shape(const Shape *S, uint32_t reps, uint32_t seed) { - printf("== %s: %u experts, n %u, k %u, %u tokens x top-%u\n", S->name, S->experts, S->n, S->k, S->tokens, S->topk); - Weights W; weights_make(&W, S->experts, S->n, S->k, seed); - OmegaGpuFp8Tensor *t = NULL; - double t0 = now_ms(); - int rc = omega_gpu_fp8_tensor_upload(S->experts, S->n, S->k, W.w, W.s, &t); - printf("upload %.0f MB: rc=%s %.0f ms\n", (double)S->experts * S->n * S->k / 1e6, omega_gpu_fp8_rc_name(rc), now_ms() - t0); - CHECK(rc == 0, "%s upload", S->name); - if (rc) { weights_free(&W); return; } - const uint32_t M = S->tokens * S->topk; - uint32_t *ids = malloc(M * 4), *trow = malloc(M * 4); - uint32_t *picks = malloc((size_t)M * 4); - make_table(S->tokens, S->topk, S->experts, seed + 7, ids, trow, picks); - uint32_t xrows = S->experts > 1 ? (S->k == 768 ? M : S->tokens) : S->tokens; - if (S->experts > 1 && S->k == 768) for (uint32_t i = 0; i < M; i++) trow[i] = i; /* down: one activation row per routed row */ - float *x = make_x(xrows, S->k, seed + 3); - float *y = malloc((size_t)M * S->n * 4), *yref = malloc((size_t)M * S->n * 4), *y2 = malloc((size_t)M * S->n * 4); - OmegaGpuFp8GemmInfo info; - rc = omega_gpu_fp8gemm_f32(t, M, ids, trow, x, xrows, y, &info); - CHECK(rc == 0, "%s gemm: %s %s", S->name, omega_gpu_fp8gemm_rc_name(rc), rc ? omega_gpu_fp8gemm_last_error() : ""); - if (rc == 0) { - /* reference: the existing GEMV, one call per row */ - double tr = now_ms(); size_t bad = 0, first = (size_t)-1; - for (uint32_t i = 0; i < M; i++) { - int r2 = omega_gpu_fp8_gemv_f32(t, ids[i], x + (size_t)trow[i] * S->k, yref + (size_t)i * S->n, NULL); - if (r2) { printf("gemv reference failed at row %u: %s\n", i, omega_gpu_fp8_last_error()); bad = (size_t)-1; break; } - } - if (bad == 0) for (size_t i = 0; i < (size_t)M * S->n; i++) if (memcmp(&y[i], &yref[i], 4) != 0) { if (!bad) first = i; bad++; } - CHECK(bad == 0, "%s: %zu of %zu outputs differ from the per-row GEMV (first %zd)", S->name, bad, (size_t)M * S->n, (ssize_t)first); - printf("parity vs per-row GEMV (%u calls, %.0f ms): %zu of %zu outputs differ%s\n", M, now_ms() - tr, bad, (size_t)M * S->n, bad ? "" : " (bit-identical)"); - /* host emulation + oracle on a few rows */ - size_t eb = 0; double worst = 0; uint32_t lb = info.lane_bytes; - for (uint32_t q = 0; q < 4; q++) { - uint32_t i = (q * 977u + 3u) % M, r = (q * 331u + 17u) % S->n; - float e = emu_row(W.w + ((size_t)ids[i] * S->n + r) * S->k, W.s + ((size_t)ids[i] * ((S->n + 127) / 128) + r / 128) * (S->k / 128), x + (size_t)trow[i] * S->k, S->k, lb); - if (memcmp(&e, &y[(size_t)i * S->n + r], 4) != 0) eb++; - double yo[128], ys[128]; /* oracle over the 128-row block holding r */ - uint32_t b0 = (r / 128) * 128; - omega_fp8_gemv_oracle(W.w + ((size_t)ids[i] * S->n + b0) * S->k, W.s + ((size_t)ids[i] * ((S->n + 127) / 128) + r / 128) * (S->k / 128), 128, S->k, x + (size_t)trow[i] * S->k, yo, ys); - double d = fabs((double)y[(size_t)i * S->n + r] - yo[r - b0]) / (ys[r - b0] + 1e-30); if (d > worst) worst = d; - } - CHECK(eb == 0 && worst < 1e-5, "%s: host emulation mismatches %zu, oracle worst %.2e", S->name, eb, worst); - printf("4 sampled outputs: %zu differ from the host emulation, worst relative error vs the double oracle %.2e\n", eb, worst); - rc = omega_gpu_fp8gemm_f32(t, M, ids, trow, x, xrows, y2, NULL); - CHECK(rc == 0 && memcmp(y, y2, (size_t)M * S->n * 4) == 0, "%s: second call bit-identical", S->name); - printf("second call: %s\n", rc == 0 && memcmp(y, y2, (size_t)M * S->n * 4) == 0 ? "bit-identical" : "DIFFERS"); - /* mutants */ - for (int m = 1; m <= 3; m++) { - omega_gpu_fp8gemm_test_set_mutant(m); - rc = omega_gpu_fp8gemm_f32(t, M, ids, trow, x, xrows, y2, NULL); - size_t b = 0; if (rc == 0) for (size_t i = 0; i < (size_t)M * S->n; i++) if (memcmp(&y[i], &y2[i], 4) != 0) b++; - if (rc != 0) printf("chip mutant %d: call returned %s: %s\n", m, omega_gpu_fp8gemm_rc_name(rc), omega_gpu_fp8gemm_last_error()); - int caught = rc == 0 && b != 0; - if (m == 2 && info.k / (32u * info.lane_bytes) < 2) caught = 1; /* single-step k: mutant 2 has no effect by construction */ - CHECK(caught, "%s: chip mutant %d must be caught", S->name, m); - printf("chip mutant %d: %s (%zu of %zu outputs differ)\n", m, caught ? "caught" : "NOT CAUGHT", b, (size_t)M * S->n); - if (g_out) fprintf(g_out, "%s{\"point\":\"%s mutant %d\",\"caught\":%d}", g_first ? "" : ",", S->name, m, caught), g_first = 0; - } - omega_gpu_fp8gemm_test_set_mutant(0); - /* timing: the new path vs the per-token path (grouped GEMV, 8 experts per token for the MoE shapes; one GEMV per row for dense) */ - uint64_t *ce = malloc(reps * 8), *cc = malloc(reps * 8); uint32_t done = 0; - for (uint32_t i = 0; i < reps; i++) { - if (g_evict) evict_host_caches(); - { int r3 = omega_gpu_fp8gemm_f32(t, M, ids, trow, x, xrows, y2, &info); if (r3 != 0) { printf("timing call %u: %s: %s\n", i, omega_gpu_fp8gemm_rc_name(r3), omega_gpu_fp8gemm_last_error()); break; } } - ce[done] = info.elapsed_ns; cc[done] = info.call_ns; done++; - } - CHECK(done == reps, "%s timing loop completed %u of %u", S->name, done, reps); - double mc = done ? med(ce, done) : 0, ma = done ? med(cc, done) : 0; - printf("GEMM (medians of %u, evict %d): mt %u warps %u ctas %u x %u segments, %u rows, up to %u passes: chip %.1f us, call %.1f us; streams %.0f MB (distinct experts %.0f MB) = %.1f GB/s on streamed, %.1f GB/s on distinct\n", - done, g_evict, info.mt, info.warps_per_cta, info.grid_x, info.segments, M, info.passes_max, mc / 1e3, ma / 1e3, info.streamed_bytes / 1e6, info.weight_bytes / 1e6, info.streamed_bytes / mc, info.weight_bytes / mc); - /* per-token baseline: for the MoE shapes one grouped GEMV (topk experts) per token; the sorted table is rebuilt per token */ - uint64_t *bc = malloc(reps * 8), *bw = malloc(reps * 8); uint32_t bd = 0; - for (uint32_t i = 0; i < reps; i++) { - if (g_evict) evict_host_caches(); - uint64_t sum_e = 0, sum_c = 0; int ok = 1; - for (uint32_t tk = 0; tk < S->tokens && ok; tk++) { - OmegaGpuFp8Info fi; int r2; - if (S->experts == 1) r2 = omega_gpu_fp8_gemv_f32(t, 0, x + (size_t)tk * S->k, yref, &fi); - else if (S->k == 768) r2 = omega_gpu_fp8_gemv_grouped_f32(t, S->topk, picks + (size_t)tk * S->topk, x + (size_t)tk * S->topk * S->k, S->topk, yref, &fi); - else r2 = omega_gpu_fp8_gemv_grouped_f32(t, S->topk, picks + (size_t)tk * S->topk, x + (size_t)tk * S->k, 1, yref, &fi); - if (r2) ok = 0; else { sum_e += fi.elapsed_ns; sum_c += fi.call_ns; } - } - if (!ok) break; - bc[bd] = sum_e; bw[bd] = sum_c; bd++; - } - double mb = bd ? med(bc, bd) : 0, mbw = bd ? med(bw, bd) : 0; - if (bd) printf("per-token grouped GEMV baseline (%u tokens, medians of %u): chip %.1f us, call %.1f us => GEMM is %.2fx faster (chip), %.2fx (call)\n", S->tokens, bd, mb / 1e3, mbw / 1e3, mb / mc, mbw / ma); - printf("per token: GEMM chip %.1f us/token, call %.1f us/token\n", mc / 1e3 / S->tokens, ma / 1e3 / S->tokens); - if (g_out) fprintf(g_out, "%s{\"point\":\"%s timing\",\"rows\":%u,\"segments\":%u,\"mt\":%u,\"warps\":%u,\"ctas\":%u,\"passes_max\":%u,\"reps\":%u,\"chip_median_ns\":%.0f,\"call_median_ns\":%.0f,\"streamed_bytes\":%" PRIu64 ",\"distinct_bytes\":%" PRIu64 ",\"gbps_streamed\":%.2f,\"baseline_chip_median_ns\":%.0f,\"baseline_call_median_ns\":%.0f,\"parity_bad\":%zu}", - g_first ? "" : ",", S->name, M, info.segments, info.mt, info.warps_per_cta, info.grid_x, info.passes_max, done, mc, ma, info.streamed_bytes, info.weight_bytes, info.streamed_bytes / mc, mb, mbw, bad), g_first = 0; - free(ce); free(cc); free(bc); free(bw); - } - omega_gpu_fp8_tensor_free(t); - free(ids); free(trow); free(picks); free(x); free(y); free(yref); free(y2); weights_free(&W); -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; const char *out_path = NULL, *shape = "all"; uint32_t reps = 0, mt = 0, warps = 0, ctas = 0, spin = 2000, tokens = 64; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--shape") == 0 && i + 1 < argc) shape = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--mt") == 0 && i + 1 < argc) mt = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--warps") == 0 && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--ctas") == 0 && i + 1 < argc) ctas = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--tokens") == 0 && i + 1 < argc) tokens = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0; - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - if (host) host_only(); - if (sim) sim_battery(); - if (!host && !sim) { - if (mt || warps) omega_gpu_fp8gemm_set_shape(mt, warps); - if (ctas) omega_gpu_fp8gemm_set_cta_budget(ctas); - (void)omega_gpu_session_set_spin_us(spin); - if (out_path) { - /* 0644, not fopen's 0666 & ~umask: a receipt is never world-writable */ - int fd = open(out_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); - g_out = fd >= 0 ? fdopen(fd, "w") : NULL; - if (fd >= 0 && !g_out) close(fd); - if (g_out) fprintf(g_out, "{\"receipt\":\"OMEGA_GPU_FP8GEMM_V1\",\"reps\":%u,\"evict\":%d,\"tokens\":%u,\"spin_us\":%u,\"points\":[", reps ? reps : 1, g_evict, tokens, omega_gpu_session_spin_us()); - } - Shape shapes[] = { { "gateup", 128, 1536, 2048, tokens, 8 }, { "down", 128, 2048, 768, tokens, 8 }, { "qkv", 1, 5120, 2048, tokens, 1 }, { "o", 1, 2048, 4096, tokens, 1 }, { "d768", 1, 2048, 768, tokens, 1 } }; - for (unsigned i = 0; i < 5; i++) if ((!strcmp(shape, "all") && i < 4) || !strcmp(shape, shapes[i].name)) run_shape(&shapes[i], reps ? reps : 1, 1000 + i); - if (g_out) { fprintf(g_out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(g_out); } - omega_gpu_session_close(); - } - printf("gpu_fp8gemm_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_gdn_multi_test.c b/tests/gpu_gdn_multi_test.c deleted file mode 100644 index 108578a8f..000000000 --- a/tests/gpu_gdn_multi_test.c +++ /dev/null @@ -1,235 +0,0 @@ -/* - * gpu_gdn_multi_test: the multi-token Gated DeltaNet decode (L369, omega_gpu_gdn_api.h) must be the decode step T times, - * bit for bit: every output row, the conv tail and the state after the last token. - * --sim warp simulator over the whole grid: T decode launches against one multi launch (both fragment orders), - * T 1, 2, 5; controls: a zero row stride and mutant 4 (tail not shifted) must differ - * (default) the chip: T decode steps (omega_gpu_gdn_step) against one recorded multi launch from the same nonzero - * state, T 1, 2, 37, 128, two input scales; the same controls must differ - * Rows as the 35B graph lays them out: token t's qkv | z in one row (stride (conv + vdim) * 4 bytes), ab rows of vh * 8 - * bytes, out rows of vdim * 4 bytes. Verdict line last: "gpu_gdn_multi_test: N checks, F failed: PASS|FAIL". - */ -#include "omega_gpu_gdn_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_cmdlist.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include - -#ifndef GDN_TEST_RATIO -#define GDN_TEST_RATIO 2u -#endif -#define RT (GDN_TEST_RATIO ? GDN_TEST_RATIO : 3u) -#define KH OMEGA_GDN_KEY_HEADS -#define HD OMEGA_GDN_HEAD_DIM -#define VH (KH * RT) -#define VD (VH * HD) -#define CD (2u * KH * HD + VD) -#define NS (VH * HD * HD) -#define NT (3u * CD) -#define ROW ((CD + VD) * 4u) /* qkv | z */ -#define ABROW (VH * 8u) -#define OROW (VD * 4u) -#define P_SCAL (CD * OMEGA_GDN_TAPS * 4u) -#define P_NORM (P_SCAL + VH * 8u) -#define P_BYTES (P_NORM + HD * 4u) -#define TAIL_BYTES (VH * OMEGA_GDN_TAIL_HEAD_BYTES) -#define STATE_BYTES (VH * OMEGA_GDN_STATE_HEAD_BYTES) -static const float EPS_L2 = 1e-6f, EPS_N = 1e-6f; - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } - -typedef struct { - float *conv_w, a_log[VH], dtb[VH], nw[HD]; - float *tail0, *state0; /* reference layouts: tail [3][conv], state [vh][128][128] */ - float *rows, *ab; /* T rows of qkv | z (true values / in_scale), T rows of {a, b} per head */ -} Case; -static void case_make(Case *c, uint32_t T, uint32_t seed, float in_scale) { - uint32_t s = seed; - c->conv_w = malloc((size_t)CD * 16); c->tail0 = malloc((size_t)NT * 4); c->state0 = malloc((size_t)NS * 4); - c->rows = malloc((size_t)T * ROW); c->ab = malloc((size_t)T * ABROW); - for (size_t i = 0; i < (size_t)CD * 4; i++) c->conv_w[i] = frand(&s, -0.6f, 0.6f); - for (unsigned h = 0; h < VH; h++) { c->a_log[h] = frand(&s, -1.5f, 1.5f); c->dtb[h] = frand(&s, -3.0f, 1.0f); } - for (unsigned i = 0; i < HD; i++) c->nw[i] = frand(&s, 0.4f, 1.6f); - for (size_t i = 0; i < NT; i++) c->tail0[i] = frand(&s, -2.0f, 2.0f); - for (size_t i = 0; i < NS; i++) c->state0[i] = frand(&s, -0.2f, 0.2f); - for (uint32_t t = 0; t < T; t++) { - float *r = c->rows + (size_t)t * (CD + VD); - for (unsigned i = 0; i < CD; i++) r[i] = frand(&s, -2.5f, 2.5f) / in_scale; - for (unsigned i = 0; i < VD; i++) r[CD + i] = frand(&s, -3.0f, 3.0f) / in_scale; - float *a = c->ab + (size_t)t * VH * 2; - for (unsigned i = 0; i < 2 * VH; i++) a[i] = frand(&s, -4.0f, 4.0f); - if (t % 3 == 0) { a[0] = 25.0f; a[2] = 19.9f; a[4] = -30.0f; a[3] = 12.0f; a[5] = -12.0f; } /* softplus threshold, beta ~ 0 / 1 */ - } -} -static void case_free(Case *c) { free(c->conv_w); free(c->tail0); free(c->state0); free(c->rows); free(c->ab); } -static size_t first_diff(const void *a, const void *b, size_t words) { - const uint32_t *x = a, *y = b; - for (size_t i = 0; i < words; i++) if (x[i] != y[i]) return i; - return (size_t)-1; -} - -/* ---- simulator ---- */ -typedef struct { uint32_t off; void *p; size_t bytes; } SimBuf; -static int sim_run(const BlackwellIRProgram *prog, int order, const SimBuf *b, int nb, const uint32_t *words, uint32_t nwords, - char *msg, size_t n) { - static uint8_t smem[OMEGA_GDN_SHARED_BYTES]; - WsSim s; memset(&s, 0, sizeof s); - s.p = prog; s.threads = OMEGA_GDN_THREADS; s.order = order; - memset(smem, 0xcd, sizeof smem); - s.smem = smem; s.smem_bytes = OMEGA_GDN_SHARED_BYTES; - for (int i = 0; i < nb; i++) { - const uint64_t a = (uintptr_t)b[i].p; - s.cbank[b[i].off / 4] = (uint32_t)a; s.cbank[b[i].off / 4 + 1] = (uint32_t)(a >> 32); - s.ranges[i].lo = a; s.ranges[i].hi = a + b[i].bytes; - } - s.nranges = nb; - for (uint32_t i = 0; i < nwords; i++) s.cbank[OMEGA_GDN_ARG_EPS_L2 / 4 + i] = words[i]; - int err = ws_run(&s, RT, OMEGA_GDN_GRID_Y); - if (err) snprintf(msg, n, "%.150s (pc %d)", s.msg, s.err_pc); - return err; -} -/* T decode launches (decode = 1) or one multi launch over the case; out [T][VD], tail and state device layouts */ -static int sim_path(const Case *c, uint32_t T, int multi, int mutant, uint32_t xstride, float in_scale, int order, float *out, - uint8_t *tail, uint8_t *state, char *msg, size_t n) { - static BlackwellIRProgram prog; - OmegaGdnSpec spec = { .mutant = mutant, .ratio = GDN_TEST_RATIO }; - if ((multi ? omega_blackwell_codegen_gdn_multi_prog(&spec, &prog) : omega_blackwell_codegen_gdn_prog(&spec, &prog)) != 0) { - snprintf(msg, n, "codegen refused"); return -1; - } - uint8_t *par = aligned_alloc(256, (P_BYTES + 255) & ~255u); - omega_gdn_pack_params_r(GDN_TEST_RATIO, c->conv_w, c->a_log, c->dtb, c->nw, par); - omega_gdn_pack_tail_r(GDN_TEST_RATIO, c->tail0, (float *)tail); - memcpy(state, c->state0, STATE_BYTES); - const float one = 1.0f; - uint32_t w[10]; - memcpy(&w[0], &EPS_L2, 4); memcpy(&w[1], &EPS_N, 4); memcpy(&w[2], &in_scale, 4); memcpy(&w[3], &one, 4); - int err = 0; - for (uint32_t t = 0; t < (multi ? 1u : T) && !err; t++) { - const uint8_t *row = (const uint8_t *)c->rows + (size_t)t * ROW; - SimBuf b[7] = { - { OMEGA_GDN_ARG_QKV, (void *)row, (size_t)(multi ? T : 1) * ROW }, { OMEGA_GDN_ARG_Z, (void *)(row + CD * 4u), (size_t)(multi ? T : 1) * ROW - CD * 4u }, - { OMEGA_GDN_ARG_AB, (uint8_t *)c->ab + (size_t)t * ABROW, (size_t)(multi ? T : 1) * ABROW }, { OMEGA_GDN_ARG_PAR, par, P_BYTES }, - { OMEGA_GDN_ARG_TAIL, tail, TAIL_BYTES }, { OMEGA_GDN_ARG_STATE, state, STATE_BYTES }, - { OMEGA_GDN_ARG_OUT, (uint8_t *)out + (size_t)t * OROW, (size_t)(multi ? T : 1) * OROW }, - }; - w[4] = T; w[5] = xstride; w[6] = ABROW; w[7] = OROW; /* the multi words follow OUT_SCALE (0x3c4): 0x3c8.. */ - err = sim_run(&prog, order, b, 7, w, multi ? 8u : 4u, msg, n); - } - free(par); - return err; -} -static void sim_battery(void) { - const uint32_t Ts[] = { 1, 2, 5 }; - float *oa = malloc((size_t)5 * OROW), *ob = malloc((size_t)5 * OROW); - uint8_t *ta = malloc(TAIL_BYTES), *tb = malloc(TAIL_BYTES), *sa = malloc(STATE_BYTES), *sb = malloc(STATE_BYTES); - char msg[256] = ""; - for (unsigned i = 0; i < 3; i++) { - const uint32_t T = Ts[i]; - Case c; case_make(&c, T, 77 + T, 1.0f); - int e1 = sim_path(&c, T, 0, 0, ROW, 1.0f, 0, oa, ta, sa, msg, sizeof msg); - CHECK(e1 == 0, "sim decode x %u ran (%s)", T, msg); - for (int order = 0; order < 2 && e1 == 0; order++) { - int e2 = sim_path(&c, T, 1, 0, ROW, 1.0f, order, ob, tb, sb, msg, sizeof msg); - const size_t dO = first_diff(oa, ob, (size_t)T * VD), dT = first_diff(ta, tb, TAIL_BYTES / 4), dS = first_diff(sa, sb, STATE_BYTES / 4); - printf("sim T %u order %d: multi %s | out %s tail %s state %s\n", T, order, e2 ? msg : "ran", dO == (size_t)-1 ? "identical" : "DIFFER", - dT == (size_t)-1 ? "identical" : "DIFFER", dS == (size_t)-1 ? "identical" : "DIFFER"); - CHECK(e2 == 0 && dO == (size_t)-1 && dT == (size_t)-1 && dS == (size_t)-1, "sim T %u order %d: multi == %u decode steps bit for bit", T, order, T); - } - if (T >= 2 && e1 == 0) { - int e3 = sim_path(&c, T, 1, 0, 0, 1.0f, 0, ob, tb, sb, msg, sizeof msg); - CHECK(e3 == 0 && first_diff(oa, ob, (size_t)T * VD) != (size_t)-1, "sim T %u control: row stride 0 differs", T); - int e4 = sim_path(&c, T, 1, 4, ROW, 1.0f, 0, ob, tb, sb, msg, sizeof msg); - CHECK(e4 == 0 && first_diff(oa, ob, (size_t)T * VD) != (size_t)-1, "sim T %u control: mutant 4 (tail not shifted) differs", T); - } - case_free(&c); - } - free(oa); free(ob); free(ta); free(tb); free(sa); free(sb); -} - -/* ---- chip ---- */ -/* the decode path: T omega_gpu_gdn_step calls; out [T][VD], tail (reference layout) and state after the last */ -static int chip_decode(OmegaGpuGdn *g, const Case *c, uint32_t T, float in_scale, float *out, float *tail, float *state) { - if (omega_gpu_gdn_set_state(g, 0, c->tail0, c->state0) != 0) return -1; - for (uint32_t t = 0; t < T; t++) { - const float *r = c->rows + (size_t)t * (CD + VD); - if (omega_gpu_gdn_step(g, 0, r, r + CD, c->ab + (size_t)t * VH * 2, EPS_L2, EPS_N, in_scale, 1.0f, out + (size_t)t * VD, NULL) != 0) return -1; - } - return omega_gpu_gdn_get_state(g, 0, tail, state); -} -static int chip_multi(OmegaGpuGdn *g, const Case *c, uint32_t T, float in_scale, uint32_t xstride, float *out, float *tail, float *state) { - if (omega_gpu_gdn_set_state(g, 0, c->tail0, c->state0) != 0 || omega_gpu_gdn_multi_prepare(g) != 0) return -1; - OmegaGpuCmdList *cl = NULL; - if (omega_gpu_cmdlist_create(4, &cl) != 0) return -1; - omega_gpu_session_lock(); - OmegaGpuMem m; memset(&m, 0, sizeof m); - const size_t s_rows = (size_t)T * ROW, s_ab = ((size_t)T * ABROW + 255) & ~(size_t)255, s_out = (size_t)T * OROW; - int ok = omega_gpu_session_open() != NULL && omega_gpu_session_alloc(s_rows + s_ab + s_out, &m) == 0; - if (ok) { - uint8_t *p = m.cpu; - memcpy(p, c->rows, s_rows); memcpy(p + s_rows, c->ab, (size_t)T * ABROW); - float *o = (float *)(p + s_rows + s_ab); - for (size_t i = 0; i < (size_t)T * VD; i++) o[i] = NAN; - ok = omega_gpu_session_sync_to_gpu(&m) == 0; - } - if (ok) ok = omega_gpu_gdn_multi_record(cl, g, 0, T, m.va, m.va + CD * 4u, xstride, m.va + s_rows, ABROW, m.va + s_rows + s_ab, OROW, - EPS_L2, EPS_N, in_scale, 1.0f) == 0; - OmegaGpuCmdListOpts opts; memset(&opts, 0, sizeof opts); - OmegaGpuCmdListStats st; memset(&st, 0, sizeof st); - if (ok) ok = omega_gpu_cmdlist_submit(cl, &opts, &st) == 0 && st.sems_done == st.launches; - if (ok) ok = omega_gpu_session_sync_to_cpu(&m) == 0; - if (ok) memcpy(out, (uint8_t *)m.cpu + s_rows + s_ab, s_out); - if (m.cpu) omega_gpu_session_free(&m); - omega_gpu_session_unlock(); - omega_gpu_cmdlist_free(cl); - if (!ok) return -1; - return omega_gpu_gdn_get_state(g, 0, tail, state); -} -static void chip_battery(void) { - OmegaGpuGdn *g = NULL; - CHECK(omega_gpu_gdn_alloc_ratio(1, GDN_TEST_RATIO, &g) == 0, "alloc (%s)", omega_gpu_gdn_last_error()); - if (!g) return; - const uint32_t Ts[] = { 1, 2, 37, 128 }; - const float scales[] = { 1.0f, 0.0009765625f }; - float *oa = malloc((size_t)128 * OROW), *ob = malloc((size_t)128 * OROW); - float *ta = malloc((size_t)NT * 4), *tb = malloc((size_t)NT * 4), *sa = malloc(STATE_BYTES), *sb = malloc(STATE_BYTES); - for (unsigned si = 0; si < 2; si++) for (unsigned i = 0; i < 4; i++) { - const uint32_t T = Ts[i]; const float sc = scales[si]; - Case c; case_make(&c, T, 900 + 7 * T + si, sc); - CHECK(omega_gpu_gdn_set_layer(g, 0, c.conv_w, c.a_log, c.dtb, c.nw) == 0, "set layer"); - const int ra = chip_decode(g, &c, T, sc, oa, ta, sa); - const int rb = chip_multi(g, &c, T, sc, ROW, ob, tb, sb); - const size_t dO = first_diff(oa, ob, (size_t)T * VD), dT = first_diff(ta, tb, NT), dS = first_diff(sa, sb, NS); - printf("chip T %3u in_scale %g: decode %s multi %s | out %s tail %s state %s\n", T, (double)sc, ra ? "FAILED" : "ran", rb ? "FAILED" : "ran", - dO == (size_t)-1 ? "identical" : "DIFFER", dT == (size_t)-1 ? "identical" : "DIFFER", dS == (size_t)-1 ? "identical" : "DIFFER"); - CHECK(ra == 0 && rb == 0, "chip T %u: both paths ran (%s)", T, omega_gpu_gdn_last_error()); - CHECK(ra == 0 && rb == 0 && dO == (size_t)-1 && dT == (size_t)-1 && dS == (size_t)-1, "chip T %u in_scale %g: multi == %u decode steps bit for bit", T, (double)sc, T); - if (T >= 37 && si == 0) { - const int r0 = chip_multi(g, &c, T, sc, 0, ob, tb, sb); - CHECK(r0 == 0 && first_diff(oa, ob, (size_t)T * VD) != (size_t)-1, "chip T %u control: row stride 0 differs", T); - omega_gpu_gdn_test_set_mutant(4); - const int r4 = chip_multi(g, &c, T, sc, ROW, ob, tb, sb); - omega_gpu_gdn_test_set_mutant(0); - CHECK(r4 == 0 && first_diff(oa, ob, (size_t)T * VD) != (size_t)-1, "chip T %u control: mutant 4 (tail not shifted) differs", T); - } - case_free(&c); - } - free(oa); free(ob); free(ta); free(tb); free(sa); free(sb); - omega_gpu_gdn_free(g); -} - -int main(int argc, char **argv) { - int sim = argc > 1 && strcmp(argv[1], "--sim") == 0; - uint32_t insns = 0, gprs = 0; - OmegaGdnSpec spec = { .ratio = GDN_TEST_RATIO }; - CHECK(omega_gdn_multi_prog_stats(&spec, &insns, &gprs) == 0 && gprs > 0 && OMEGA_GDN_THREADS * (gprs + 2u) <= 65536u, - "multi program builds and fits the register file (%u insns, %u registers)", insns, gprs); - if (sim) sim_battery(); - else chip_battery(); - printf("gpu_gdn_multi_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_gdn_test.c b/tests/gpu_gdn_test.c deleted file mode 100644 index 655875a65..000000000 --- a/tests/gpu_gdn_test.c +++ /dev/null @@ -1,1017 +0,0 @@ -/* - * gpu_gdn_test: the one-launch Gated DeltaNet decode step of Qwen3.8-27B (omega_gpu_gdn_api.h), omega#542. - * --host-only layout helpers, codegen budgets and refusals, the double oracle's delta-rule property - * --sim warp-simulator parity over the whole grid (48 CTAs x 256 threads, both fragment orders bit-identical), - * three chained steps against the double oracle, mutants 1-4 caught - * (default) the chip: two layers (addressing), five chained steps each against the oracle (output, tail, state), - * a rerun from the same state bit-identical, reset, mutants 1-4 caught, the record path (two steps in - * one command list: the second reads the first's state), chip medians (--reps N, --out receipt.json) - * The oracle is sc crates/aien-inference-abi/src/qwen38.rs `delta_net` in double, from the projections on. - * Verdict line last: "gpu_gdn_test: N checks, F failed: PASS|FAIL". - */ -#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 "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -/* GDN_TEST_RATIO: value heads per key head under test (OmegaGdnSpec.ratio; 0 = 3, Qwen3.8-27B; -DGDN_TEST_RATIO=2 builds the - * Qwen3.6-35B-A3B shape, sc L306). Every size below follows it. */ -#ifndef GDN_TEST_RATIO -#define GDN_TEST_RATIO 0u -#endif -#define RT (GDN_TEST_RATIO ? GDN_TEST_RATIO : 3u) -#define KH OMEGA_GDN_KEY_HEADS -#define HD OMEGA_GDN_HEAD_DIM -#define VH (KH * RT) -#define VD (VH * HD) -#define CD (2u * KH * HD + VD) -#define NS (VH * HD * HD) -#define NT (3u * CD) -#define T_PAR_SCAL (CD * OMEGA_GDN_TAPS * 4u) -#define T_PAR_NORM (T_PAR_SCAL + VH * 8u) -#define T_PAR_BYTES (T_PAR_NORM + HD * 4u) -#define T_TAIL_BYTES (VH * OMEGA_GDN_TAIL_HEAD_BYTES) -#define T_STATE_BYTES (VH * OMEGA_GDN_STATE_HEAD_BYTES) -static const float EPS_L2 = 1e-6f, EPS_N = 1e-6f; -/* tolerances, normalised by the largest reference magnitude of the vector (EX2 / RCP / RSQ / LG2 are approximate on - * the chip, the oracle is double; the mutants miss by orders of magnitude more, see the receipts) */ -#define TOL_OUT 2e-4 -#define TOL_STATE 2e-5 -#define TOL_TAIL 1e-6 - -typedef struct { - float *conv_w, a_log[VH], dtb[VH], nw[HD]; - float *tail0, *state0; /* initial state, reference layouts */ -} Layer; -typedef struct { float *qkv, *z, ab[2 * VH]; } Inp; - -static void layer_make(Layer *L, uint32_t seed) { - uint32_t s = seed; - L->conv_w = malloc((size_t)CD * 4 * 4); L->tail0 = malloc((size_t)NT * 4); L->state0 = malloc((size_t)NS * 4); - for (size_t i = 0; i < (size_t)CD * 4; i++) L->conv_w[i] = frand(&s, -0.6f, 0.6f); - for (unsigned h = 0; h < VH; h++) { L->a_log[h] = frand(&s, -1.5f, 1.5f); L->dtb[h] = frand(&s, -3.0f, 1.0f); } - for (unsigned i = 0; i < HD; i++) L->nw[i] = frand(&s, 0.4f, 1.6f); - for (size_t i = 0; i < NT; i++) L->tail0[i] = frand(&s, -2.0f, 2.0f); - for (size_t i = 0; i < NS; i++) L->state0[i] = frand(&s, -0.2f, 0.2f); -} -static void layer_free(Layer *L) { free(L->conv_w); free(L->tail0); free(L->state0); } -/* in_scale: the kernel multiplies qkv and z by it, so the stored rows are the true rows / in_scale */ -static void inp_make(Inp *in, uint32_t seed, float in_scale) { - uint32_t s = seed; - in->qkv = malloc((size_t)CD * 4); in->z = malloc((size_t)VD * 4); - for (unsigned i = 0; i < CD; i++) in->qkv[i] = frand(&s, -2.5f, 2.5f) / in_scale; - for (unsigned i = 0; i < VD; i++) in->z[i] = frand(&s, -3.0f, 3.0f) / in_scale; - for (unsigned h = 0; h < VH; h++) { in->ab[2 * h] = frand(&s, -4.0f, 4.0f); in->ab[2 * h + 1] = frand(&s, -4.0f, 4.0f); } - /* a few heads at the softplus threshold and past it, and beta near 0 / 1 */ - if (!getenv("GDN_NOFORCE")) { in->ab[0] = 25.0f; in->ab[2] = 19.9f; in->ab[4] = -30.0f; in->ab[3] = 12.0f; in->ab[5] = -12.0f; } -} -static void inp_free(Inp *in) { free(in->qkv); free(in->z); } - -/* ---- the double oracle ---- */ -typedef struct { double *tail, *state; } DState; -static void dstate_init(DState *d, const Layer *L) { - d->tail = malloc((size_t)NT * 8); d->state = malloc((size_t)NS * 8); - for (size_t i = 0; i < NT; i++) d->tail[i] = L->tail0[i]; - for (size_t i = 0; i < NS; i++) d->state[i] = L->state0[i]; -} -static void dstate_free(DState *d) { free(d->tail); free(d->state); } -static double sigm(double x) { return 1.0 / (1.0 + exp(-x)); } -static double softplus_ref(double x) { return x > 20.0 ? x : log1p(exp(x)); } -static void oracle_step(const Layer *L, DState *d, const Inp *in, float in_scale, float out_scale, double *y) { - static double mixed[CD], q[KH * HD], k[KH * HD]; - for (unsigned ch = 0; ch < CD; ch++) { - const double x = (double)(in->qkv[ch] * in_scale); /* the kernel's f32 product */ - const float *w = &L->conv_w[(size_t)ch * 4]; - double acc = w[0] * d->tail[ch] + w[1] * d->tail[CD + ch] + w[2] * d->tail[2 * CD + ch] + w[3] * x; - mixed[ch] = acc * sigm(acc); - d->tail[ch] = d->tail[CD + ch]; d->tail[CD + ch] = d->tail[2 * CD + ch]; d->tail[2 * CD + ch] = x; - } - for (unsigned hk = 0; hk < KH; hk++) { - double sq = 0, sk = 0; - for (unsigned i = 0; i < HD; i++) { sq += mixed[hk * HD + i] * mixed[hk * HD + i]; sk += mixed[KH * HD + hk * HD + i] * mixed[KH * HD + hk * HD + i]; } - const double iq = 1.0 / sqrt(sq + EPS_L2), ik = 1.0 / sqrt(sk + EPS_L2); - for (unsigned i = 0; i < HD; i++) { q[hk * HD + i] = mixed[hk * HD + i] * iq / sqrt((double)HD); k[hk * HD + i] = mixed[KH * HD + hk * HD + i] * ik; } - } - for (unsigned h = 0; h < VH; h++) { - const unsigned hk = h / (VH / KH); - const double negA = -(double)(float)exp((double)L->a_log[h]); /* the API's float negA (double exp, rounded) */ - const double g = (double)(float)negA * softplus_ref((double)in->ab[2 * h] + L->dtb[h]); - const double decay = exp(g), beta = sigm(in->ab[2 * h + 1]); - double *S = d->state + (size_t)h * HD * HD, kv[HD], o[HD], dl[HD]; - const double *kk = &k[hk * HD], *qq = &q[hk * HD], *v = &mixed[2 * KH * HD + h * HD]; - for (size_t i = 0; i < (size_t)HD * HD; i++) S[i] *= decay; - for (unsigned c = 0; c < HD; c++) kv[c] = 0; - for (unsigned r = 0; r < HD; r++) for (unsigned c = 0; c < HD; c++) kv[c] += S[r * HD + c] * kk[r]; - for (unsigned c = 0; c < HD; c++) dl[c] = (v[c] - kv[c]) * beta; - for (unsigned r = 0; r < HD; r++) for (unsigned c = 0; c < HD; c++) S[r * HD + c] += kk[r] * dl[c]; - for (unsigned c = 0; c < HD; c++) o[c] = 0; - for (unsigned r = 0; r < HD; r++) for (unsigned c = 0; c < HD; c++) o[c] += S[r * HD + c] * qq[r]; - double ms = 0; for (unsigned c = 0; c < HD; c++) ms += o[c] * o[c]; - const double inv = 1.0 / sqrt(ms / HD + EPS_N); - for (unsigned c = 0; c < HD; c++) { - const double zz = (double)(in->z[h * HD + c] * in_scale); - y[h * HD + c] = o[c] * inv * L->nw[c] * (zz * sigm(zz)) * out_scale; - } - } -} -/* max |got - ref| / max |ref| */ -static double nerr(const float *got, const double *ref, size_t n) { - double e = 0, m = 1e-30; - for (size_t i = 0; i < n; i++) { - const double a = fabs((double)got[i] - ref[i]); - if (!isfinite(a)) { if (getenv("GDN_DBG")) printf(" non-finite at %zu: got %g ref %g\n", i, (double)got[i], ref[i]); return INFINITY; } /* a NaN or inf on either side never passes */ - if (a > e) e = a; - if (fabs(ref[i]) > m) m = fabs(ref[i]); - } - return e / m; -} -typedef struct { double out, tail, state; } Errs; -static int errs_ok(const Errs *e) { return e->out <= TOL_OUT && e->tail <= TOL_TAIL && e->state <= TOL_STATE; } - -/* ---- host-only ---- */ -static void host_only(void) { - /* layout round trip, and the copy check */ - float *t = malloc((size_t)NT * 4), *t2 = malloc((size_t)NT * 4), *dev = malloc(T_TAIL_BYTES); - uint32_t s = 5; - for (size_t i = 0; i < NT; i++) t[i] = frand(&s, -1, 1); - omega_gdn_pack_tail_r(GDN_TEST_RATIO, t, dev); - CHECK(omega_gdn_unpack_tail_r(GDN_TEST_RATIO, dev, t2) == 0 && memcmp(t, t2, (size_t)NT * 4) == 0, "tail pack/unpack round trip"); - dev[(1u * OMEGA_GDN_SLOTS + 7u) * 4u + 1u] += 1.0f; /* head 1 (a second copy of key head 0), q slot 7 */ - CHECK(omega_gdn_unpack_tail_r(GDN_TEST_RATIO, dev, t2) == -1, "unpack refuses disagreeing copies"); - free(t); free(t2); free(dev); - /* parameter block */ - Layer L; layer_make(&L, 9); - uint8_t *blk = malloc(T_PAR_BYTES); - CHECK(omega_gdn_pack_params_r(GDN_TEST_RATIO, L.conv_w, L.a_log, L.dtb, L.nw, blk) == 0, "pack params"); - const float *sc = (const float *)(blk + T_PAR_SCAL); - CHECK(sc[2 * 5] == -(float)omega_hostmath_exp((double)L.a_log[5]) && sc[2 * 5 + 1] == L.dtb[5], "negA and dt_bias interleaved"); - for (unsigned h = 0; h < VH; h++) { /* the libm-free exp agrees with libm to within one float ulp */ - const float want = -(float)exp((double)L.a_log[h]), got = sc[2 * h]; - CHECK(fabsf(got - want) <= fabsf(want) * 0x1p-23f, "negA head %u: %.9g vs libm %.9g", h, (double)got, (double)want); - } - CHECK(memcmp(blk + T_PAR_NORM, L.nw, HD * 4) == 0, "norm weight at its offset"); - CHECK(omega_gdn_pack_params_r(GDN_TEST_RATIO, NULL, L.a_log, L.dtb, L.nw, blk) == -1, "pack params refuses NULL"); - free(blk); - /* codegen budgets */ - for (int m = 0; m <= 4; m++) { - OmegaGdnSpec sp = { .mutant = m, .ratio = GDN_TEST_RATIO }; uint32_t ni = 0, ng = 0; - int rc = omega_gdn_prog_stats(&sp, &ni, &ng); - CHECK(rc == 0 && ni <= BW_MAX_IR_INSNS && ng + 2 <= BW_PHYS_GPR_MAX, "mutant %d codegen: rc %d, %u insns, %u registers", m, rc, ni, ng); - if (m == 0) printf("kernel: %u instructions, peak %u registers (%u declared, %u threads)\n", ni, ng, omega_bw_gpr_declared(ng), OMEGA_GDN_THREADS); - } - OmegaGdnSpec bad = { .mutant = 5, .ratio = GDN_TEST_RATIO }; - CHECK(omega_gdn_prog_stats(&bad, NULL, NULL) == -1, "mutant 5 refused"); - /* the state copy / zero programs (cached tail and state) */ - { - static BlackwellIRProgram cp; - OmegaGdnSpec c1 = { .copy = OMEGA_GDN_COPY }, c2 = { .copy = OMEGA_GDN_ZERO }, c3 = { .copy = 3 }, cm = { .mutant = 1, .copy = OMEGA_GDN_COPY }; - CHECK(omega_blackwell_codegen_gdn_copy_prog(&c1, &cp) == 0 && cp.regalloc.peak_gpr_usage + 2 <= BW_PHYS_GPR_MAX, "copy codegen"); - CHECK(omega_blackwell_codegen_gdn_copy_prog(&c2, &cp) == 0, "zero codegen"); - CHECK(omega_blackwell_codegen_gdn_copy_prog(&c3, &cp) == -1 && omega_blackwell_codegen_gdn_copy_prog(&cm, &cp) == -1, "copy codegen refuses kind 3 and a mutant"); - CHECK(omega_gdn_prog_stats(&c1, NULL, NULL) == -1, "decode codegen refuses a copy spec"); - } - /* the oracle's delta rule: from S = 0 with beta ~ 1, the step writes v along k, so S^T k = v (|k| = 1) */ - { - DState d; dstate_init(&d, &L); - memset(d.state, 0, (size_t)NS * 8); - Inp in; inp_make(&in, 77, 1.0f); - for (unsigned h = 0; h < VH; h++) in.ab[2 * h + 1] = 40.0f; - double *y = malloc((size_t)VD * 8); - static double mixed_v[CD]; - /* the expected v and k: recompute the conv of this step from the oracle's tail before the step */ - for (unsigned ch = 0; ch < CD; ch++) { - const float *w = &L.conv_w[(size_t)ch * 4]; - double acc = w[0] * d.tail[ch] + w[1] * d.tail[CD + ch] + w[2] * d.tail[2 * CD + ch] + w[3] * (double)in.qkv[ch]; - mixed_v[ch] = acc * sigm(acc); - } - oracle_step(&L, &d, &in, 1.0f, 1.0f, y); - double worst = 0; - for (unsigned h = 0; h < VH; h += 7) { - const unsigned hk = h / RT; - double nk = 0; for (unsigned i = 0; i < HD; i++) nk += mixed_v[KH * HD + hk * HD + i] * mixed_v[KH * HD + hk * HD + i]; - nk = sqrt(nk + EPS_L2); - for (unsigned c = 0; c < HD; c++) { - double kv = 0; - for (unsigned r = 0; r < HD; r++) kv += d.state[(size_t)h * HD * HD + r * HD + c] * mixed_v[KH * HD + hk * HD + r] / nk; - const double want = mixed_v[2 * KH * HD + h * HD + c]; - if (fabs(kv - want) > worst) worst = fabs(kv - want); - } - } - CHECK(worst < 1e-6, "oracle delta rule: S^T k = v after one step from zero (worst %.3g)", worst); - free(y); inp_free(&in); dstate_free(&d); - } - layer_free(&L); - /* the prefill kernels encode, and every SHFL.BFLY placeholder is patched (the count kernel_for demands) */ - for (unsigned k = 0; k < 3; k++) { - static BlackwellIRProgram p; - OmegaGdnSpec spec = { .ratio = GDN_TEST_RATIO }; - int rc = k == 0 ? omega_blackwell_codegen_gdn_prep_prog(&spec, &p) : k == 1 ? omega_blackwell_codegen_gdn_scan_prog(&spec, &p) - : omega_blackwell_codegen_gdn_post_prog(&spec, &p); - size_t need = rc == 0 ? omega_bw_program_code_bytes(&p) : 0; - uint8_t *code = need ? malloc(need) : NULL; - OmegaBlackwellKernel kern; - int enc = code ? omega_blackwell_kernel_encode_into(&p, code, need, &kern) : -1; - int np = enc == 0 ? omega_tc_patch_code(&p, code, need) : -1; - const uint32_t want = omega_gdn_bfly_count(&p); - if (getenv("GDN_DUMP") && code && atoi(getenv("GDN_DUMP")) == (int)k) { FILE *f = fopen("gdn_pf.bin", "wb"); if (f) { fwrite(code, 1, need, f); fclose(f); } } - CHECK(rc == 0 && enc == 0 && np >= 0 && (uint32_t)np == want && (k == 0 || want > 0), - "prefill kernel %u encodes: %zu insns, %u registers, %d of %u butterflies patched", k, p.count, p.regalloc.peak_gpr_usage, np, want); - free(code); - } -} - -/* ---- simulator ---- */ -enum { SB_QKV, SB_Z, SB_AB, SB_PAR, SB_TAIL, SB_STATE, SB_OUT, SB_N }; -static uint64_t g_sim_issues; -static int sim_run_steps(int mutant, uint32_t steps, float in_scale, float out_scale, Errs *worst, char *msg, size_t n) { - static BlackwellIRProgram prog; - OmegaGdnSpec spec = { .mutant = mutant, .ratio = GDN_TEST_RATIO }; - if (omega_blackwell_codegen_gdn_prog(&spec, &prog) != 0) { snprintf(msg, n, "codegen refused"); return -1; } - Layer L; layer_make(&L, 21); - DState d; dstate_init(&d, &L); - size_t sz[SB_N] = { CD * 4u, VD * 4u, VH * 8u, T_PAR_BYTES, T_TAIL_BYTES, T_STATE_BYTES, VD * 4u }; - uint8_t *buf[SB_N]; - for (int i = 0; i < SB_N; i++) buf[i] = aligned_alloc(256, (sz[i] + 255) & ~(size_t)255); - omega_gdn_pack_params_r(GDN_TEST_RATIO, L.conv_w, L.a_log, L.dtb, L.nw, buf[SB_PAR]); - omega_gdn_pack_tail_r(GDN_TEST_RATIO, L.tail0, (float *)buf[SB_TAIL]); - memcpy(buf[SB_STATE], L.state0, T_STATE_BYTES); - uint8_t *tail_save = malloc(T_TAIL_BYTES), *state_save = malloc(T_STATE_BYTES), *out_copy = malloc(VD * 4u); - uint8_t *tail_copy = malloc(T_TAIL_BYTES), *state_copy = malloc(T_STATE_BYTES); - double *y = malloc((size_t)VD * 8); - float *tref = malloc((size_t)NT * 4); - int err = 0; - memset(worst, 0, sizeof *worst); - for (uint32_t st = 0; st < steps && !err; st++) { - Inp in; inp_make(&in, 1000 + st, in_scale); - memcpy(buf[SB_QKV], in.qkv, sz[SB_QKV]); memcpy(buf[SB_Z], in.z, sz[SB_Z]); memcpy(buf[SB_AB], in.ab, sz[SB_AB]); - memcpy(tail_save, buf[SB_TAIL], T_TAIL_BYTES); memcpy(state_save, buf[SB_STATE], T_STATE_BYTES); - for (int order = 0; order < 2 && !err; order++) { - if (order == 1) { memcpy(buf[SB_TAIL], tail_save, T_TAIL_BYTES); memcpy(buf[SB_STATE], state_save, T_STATE_BYTES); } - float *yo = (float *)buf[SB_OUT]; - for (unsigned i = 0; i < VD; i++) yo[i] = -999.0f; - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = OMEGA_GDN_THREADS; s.order = order; - static uint8_t smem[OMEGA_GDN_SHARED_BYTES]; s.smem = smem; s.smem_bytes = OMEGA_GDN_SHARED_BYTES; - for (int i = 0; i < SB_N; i++) { - const uint64_t a = (uintptr_t)buf[i]; - s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a >> 32); - s.ranges[i].lo = (uintptr_t)buf[i]; s.ranges[i].hi = (uintptr_t)buf[i] + sz[i]; - } - s.nranges = SB_N; - memcpy(&s.cbank[OMEGA_GDN_ARG_EPS_L2 / 4], &EPS_L2, 4); memcpy(&s.cbank[OMEGA_GDN_ARG_EPS_NORM / 4], &EPS_N, 4); - memcpy(&s.cbank[OMEGA_GDN_ARG_IN_SCALE / 4], &in_scale, 4); memcpy(&s.cbank[OMEGA_GDN_ARG_OUT_SCALE / 4], &out_scale, 4); - err = ws_run(&s, RT, OMEGA_GDN_GRID_Y); - if (err) { snprintf(msg, n, "step %u order %d: %s (pc %d)", st, order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (unsigned i = 0; i < VD; i++) if (yo[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, n, "%zu output words never written", unwritten); break; } - if (order == 0) { memcpy(out_copy, yo, VD * 4u); memcpy(tail_copy, buf[SB_TAIL], T_TAIL_BYTES); memcpy(state_copy, buf[SB_STATE], T_STATE_BYTES); } - else if (memcmp(out_copy, yo, VD * 4u) || memcmp(tail_copy, buf[SB_TAIL], T_TAIL_BYTES) || memcmp(state_copy, buf[SB_STATE], T_STATE_BYTES)) { - err = -1; snprintf(msg, n, "step %u: the fragment order changed the result", st); - } - } - if (err) { inp_free(&in); break; } - oracle_step(&L, &d, &in, in_scale, out_scale, y); - double *ts = malloc((size_t)NT * 8); - for (size_t i = 0; i < NT; i++) ts[i] = d.tail[i]; - Errs e; - e.out = nerr((const float *)buf[SB_OUT], y, VD); - if (omega_gdn_unpack_tail_r(GDN_TEST_RATIO, (const float *)buf[SB_TAIL], tref) != 0) e.tail = INFINITY; - else e.tail = nerr(tref, ts, NT); - e.state = nerr((const float *)buf[SB_STATE], d.state, NS); - free(ts); - if (e.out > worst->out) worst->out = e.out; - if (e.tail > worst->tail) worst->tail = e.tail; - if (e.state > worst->state) worst->state = e.state; - inp_free(&in); - } - for (int i = 0; i < SB_N; i++) free(buf[i]); - free(tail_save); free(state_save); free(out_copy); free(tail_copy); free(state_copy); free(y); free(tref); - dstate_free(&d); layer_free(&L); - return err; -} -static void sim_battery(void) { - struct { int mutant; uint32_t steps; float in_scale, out_scale; const char *name; } pts[] = { - { 0, 3, 1.0f, 1.0f, "3 steps" }, - { 0, 2, 0.0009765625f, 18446744073709551616.0f, "2 steps, in_scale 2^-10, out_scale 2^64" }, - { 1, 2, 1.0f, 1.0f, "mutant 1 (no decay)" }, { 2, 2, 1.0f, 1.0f, "mutant 2 (beta 1)" }, - { 3, 2, 1.0f, 1.0f, "mutant 3 (gate z, not silu z)" }, { 4, 2, 1.0f, 1.0f, "mutant 4 (tail not shifted)" }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - char msg[300] = ""; Errs w = { 0, 0, 0 }; - double t0 = now_ms(); - int err = sim_run_steps(pts[i].mutant, pts[i].steps, pts[i].in_scale, pts[i].out_scale, &w, msg, sizeof msg); - printf("sim %-44s err out %.3g tail %.3g state %.3g (%.0f ms)%s%s\n", pts[i].name, w.out, w.tail, w.state, now_ms() - t0, err ? " ERROR " : "", msg); - CHECK(err == 0, "sim %s ran (%s)", pts[i].name, msg); - if (pts[i].mutant == 0) CHECK(errs_ok(&w), "sim %s within tolerance", pts[i].name); - else CHECK(!errs_ok(&w), "sim %s caught", pts[i].name); - } - printf("sim warp issues: %" PRIu64 "\n", g_sim_issues); -} - -/* ---- L313 bf16 state on the simulator: the bf16 program equals the f32 program run from the widened state, with the - * stored state rounded to nearest even: outputs and tails bit-identical, every stored bf16 equal to bf16_rn of the f32 - * program's stored state. Chained over steps (the f32 run restarts each step from the bf16 state). ---- */ -static uint16_t t_bf16_rn(float f) { uint32_t u; memcpy(&u, &f, 4); if ((u & 0x7fffffffu) > 0x7f800000u) return 0x7fc0u; return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } -static float t_bf16_f(uint16_t b) { uint32_t u = (uint32_t)b << 16; float f; memcpy(&f, &u, 4); return f; } -static int sim_one(const BlackwellIRProgram *prog, uint8_t **buf, const size_t *sz, float in_scale, float out_scale, char *msg, size_t n) { - WsSim s; memset(&s, 0, sizeof s); - s.p = prog; s.threads = OMEGA_GDN_THREADS; s.order = 0; - static uint8_t smem[OMEGA_GDN_SHARED_BYTES]; s.smem = smem; s.smem_bytes = OMEGA_GDN_SHARED_BYTES; - for (int i = 0; i < SB_N; i++) { - const uint64_t a = (uintptr_t)buf[i]; - s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a >> 32); - s.ranges[i].lo = (uintptr_t)buf[i]; s.ranges[i].hi = (uintptr_t)buf[i] + sz[i]; - } - s.nranges = SB_N; - memcpy(&s.cbank[OMEGA_GDN_ARG_EPS_L2 / 4], &EPS_L2, 4); memcpy(&s.cbank[OMEGA_GDN_ARG_EPS_NORM / 4], &EPS_N, 4); - memcpy(&s.cbank[OMEGA_GDN_ARG_IN_SCALE / 4], &in_scale, 4); memcpy(&s.cbank[OMEGA_GDN_ARG_OUT_SCALE / 4], &out_scale, 4); - int err = ws_run(&s, RT, OMEGA_GDN_GRID_Y); - if (err) snprintf(msg, n, "%s (pc %d)", s.msg, s.err_pc); - g_sim_issues += s.warp_issues; - return err; -} -static void sim_bf16_battery(void) { - static BlackwellIRProgram p32, p16; - OmegaGdnSpec s32 = { .ratio = GDN_TEST_RATIO }, s16 = { .ratio = GDN_TEST_RATIO, .state_bf16 = 1 }; - OmegaGdnShape sh16; - CHECK(omega_gdn_shape(&s16, &sh16) == 0 && sh16.state_bytes == T_STATE_BYTES / 2u, "bf16 shape: half the state bytes"); - CHECK(omega_blackwell_codegen_gdn_prog(&s32, &p32) == 0 && omega_blackwell_codegen_gdn_prog(&s16, &p16) == 0, "bf16 codegen"); - uint32_t f2fp = 0; - for (size_t i = 0; i < p16.count; i++) if (p16.insns[i].op == BW_IR_FMNMX_MAX && p16.insns[i].imm == OMEGA_TC_MARK_F2FP) f2fp++; - CHECK(f2fp == 32u && omega_gdn_bfly_count(&p16) == omega_gdn_bfly_count(&p32) + 32u, "bf16: 32 F2FP placeholders counted (%u)", f2fp); - Layer L; layer_make(&L, 21); - size_t sz[SB_N] = { CD * 4u, VD * 4u, VH * 8u, T_PAR_BYTES, T_TAIL_BYTES, T_STATE_BYTES, VD * 4u }; - size_t sz16[SB_N]; memcpy(sz16, sz, sizeof sz); sz16[SB_STATE] = T_STATE_BYTES / 2u; - uint8_t *a[SB_N], *b[SB_N]; - for (int i = 0; i < SB_N; i++) { a[i] = aligned_alloc(256, (sz[i] + 255) & ~(size_t)255); b[i] = aligned_alloc(256, (sz[i] + 255) & ~(size_t)255); } - omega_gdn_pack_params_r(GDN_TEST_RATIO, L.conv_w, L.a_log, L.dtb, L.nw, b[SB_PAR]); - omega_gdn_pack_tail_r(GDN_TEST_RATIO, L.tail0, (float *)b[SB_TAIL]); - uint16_t *st16 = (uint16_t *)b[SB_STATE]; - for (size_t i = 0; i < NS; i++) st16[i] = t_bf16_rn(L.state0[i]); - memcpy(a[SB_PAR], b[SB_PAR], T_PAR_BYTES); - int err = 0; uint32_t bad_out = 0, bad_tail = 0, bad_state = 0, rounded = 0; - char msg[300] = ""; - for (uint32_t st = 0; st < 3 && !err; st++) { - Inp in; inp_make(&in, 1000 + st, 1.0f); - for (int k = 0; k < 2; k++) { - uint8_t **x = k ? b : a; - memcpy(x[SB_QKV], in.qkv, sz[SB_QKV]); memcpy(x[SB_Z], in.z, sz[SB_Z]); memcpy(x[SB_AB], in.ab, sz[SB_AB]); - } - memcpy(a[SB_TAIL], b[SB_TAIL], T_TAIL_BYTES); - for (size_t i = 0; i < NS; i++) ((float *)a[SB_STATE])[i] = t_bf16_f(st16[i]); - err = sim_one(&p32, a, sz, 1.0f, 1.0f, msg, sizeof msg); - if (!err) err = sim_one(&p16, b, sz16, 1.0f, 1.0f, msg, sizeof msg); - if (!err) { - for (size_t i = 0; i < VD; i++) bad_out += memcmp(&((float *)a[SB_OUT])[i], &((float *)b[SB_OUT])[i], 4) != 0; - bad_tail += memcmp(a[SB_TAIL], b[SB_TAIL], T_TAIL_BYTES) != 0; - for (size_t i = 0; i < NS; i++) { - const float f = ((float *)a[SB_STATE])[i]; - bad_state += st16[i] != t_bf16_rn(f); - rounded += t_bf16_f(st16[i]) != f; - } - } - inp_free(&in); - } - printf("sim bf16 state: 3 steps, outputs differing %u, tails differing %u, stored states != bf16_rn(f32) %u, rounded %u of %u%s%s\n", - bad_out, bad_tail, bad_state, rounded, 3u * NS, err ? " ERROR " : "", msg); - CHECK(err == 0, "sim bf16 ran (%s)", msg); - CHECK(bad_out == 0 && bad_tail == 0 && bad_state == 0, "sim bf16 == f32 program + round to nearest even on store"); - CHECK(rounded > NS, "sim bf16 really rounds (%u of %u values changed)", rounded, 3u * NS); - for (int i = 0; i < SB_N; i++) { free(a[i]); free(b[i]); } - layer_free(&L); -} - -/* ---- prefill on the simulator (omega#543): prep, scan, post over T tokens against T oracle steps ---- */ -typedef struct { uint32_t off; void *p; size_t bytes; } SimBuf; -typedef struct { uint32_t off; uint32_t word; } SimWord; -static int sim_launch(const BlackwellIRProgram *prog, uint32_t threads, uint32_t gx, uint32_t gy, uint32_t smem_bytes, int order, - const SimBuf *b, int nb, const SimWord *w, int nw, char *msg, size_t n) { - static uint8_t smem[OMEGA_GDN_SCAN_SHARED_BYTES]; - WsSim s; memset(&s, 0, sizeof s); - s.p = prog; s.threads = threads; s.order = order; - memset(smem, 0xcd, sizeof smem); /* poison: a read before a write shows */ - s.smem = smem; s.smem_bytes = smem_bytes ? smem_bytes : 4u; - for (int i = 0; i < nb; i++) { - const uint64_t a = (uintptr_t)b[i].p; - s.cbank[b[i].off / 4] = (uint32_t)a; s.cbank[b[i].off / 4 + 1] = (uint32_t)(a >> 32); - s.ranges[i].lo = a; s.ranges[i].hi = a + b[i].bytes; - } - s.nranges = nb; - for (int i = 0; i < nw; i++) s.cbank[w[i].off / 4] = w[i].word; - int err = ws_run(&s, gx, gy); - if (err) snprintf(msg, n, "%.150s (pc %d)", s.msg, s.err_pc); - g_sim_issues += s.warp_issues; - return err; -} -static uint32_t fw(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static int sim_prefill(int mutant, uint32_t T, float in_scale, float out_scale, Errs *worst, char *msg, size_t n) { - static BlackwellIRProgram pp, ps, pq; - OmegaGdnSpec spec = { .mutant = mutant, .ratio = GDN_TEST_RATIO }; - if (omega_blackwell_codegen_gdn_prep_prog(&spec, &pp) != 0 || omega_blackwell_codegen_gdn_scan_prog(&spec, &ps) != 0 || - omega_blackwell_codegen_gdn_post_prog(&spec, &pq) != 0) { snprintf(msg, n, "codegen refused"); return -1; } - Layer L; layer_make(&L, 21); - DState d; dstate_init(&d, &L); - const uint32_t T8 = (T + OMEGA_GDN_SCAN_CHUNK - 1u) / OMEGA_GDN_SCAN_CHUNK * OMEGA_GDN_SCAN_CHUNK; - const size_t s_qkv = (size_t)T * CD * 4u, s_z = (size_t)T * VD * 4u, s_ab = (size_t)T * VH * 8u; - const size_t s_rec = (size_t)T8 * VH * OMEGA_GDN_REC_BYTES, s_o = (size_t)T * VD * 4u; - float *qkv = aligned_alloc(256, s_qkv), *z = aligned_alloc(256, s_z), *ab = aligned_alloc(256, s_ab); - uint8_t *par = aligned_alloc(256, T_PAR_BYTES), *tail = aligned_alloc(256, T_TAIL_BYTES); - uint8_t *state = aligned_alloc(256, T_STATE_BYTES), *rec = aligned_alloc(256, s_rec); - float *o = aligned_alloc(256, s_o), *out = aligned_alloc(256, s_o), *out0 = malloc(s_o); - uint8_t *tail0 = malloc(T_TAIL_BYTES), *state0 = malloc(T_STATE_BYTES); - double *y = malloc((size_t)T * VD * 8); - float *tref = malloc((size_t)NT * 4); - for (uint32_t t = 0; t < T; t++) { - Inp in; inp_make(&in, 1000 + t, in_scale); - memcpy(qkv + (size_t)t * CD, in.qkv, CD * 4u); memcpy(z + (size_t)t * VD, in.z, VD * 4u); memcpy(ab + (size_t)t * VH * 2u, in.ab, VH * 8u); - oracle_step(&L, &d, &in, in_scale, out_scale, y + (size_t)t * VD); - inp_free(&in); - } - omega_gdn_pack_params_r(GDN_TEST_RATIO, L.conv_w, L.a_log, L.dtb, L.nw, par); - int err = 0; - for (int order = 0; order < 2 && !err; order++) { - omega_gdn_pack_tail_r(GDN_TEST_RATIO, L.tail0, (float *)tail); - memcpy(state, L.state0, T_STATE_BYTES); - memset(rec, 0xcd, s_rec); - for (size_t i = 0; i < (size_t)T * VD; i++) { o[i] = -999.0f; out[i] = -999.0f; } - const SimBuf bp[] = { { OMEGA_GDN_PREP_ARG_QKV, qkv, s_qkv }, { OMEGA_GDN_PREP_ARG_AB, ab, s_ab }, { OMEGA_GDN_PREP_ARG_PAR, par, T_PAR_BYTES }, - { OMEGA_GDN_PREP_ARG_TAIL, tail, T_TAIL_BYTES }, { OMEGA_GDN_PREP_ARG_REC, rec, s_rec } }; - const SimWord wp[] = { { OMEGA_GDN_PREP_ARG_T, T }, { OMEGA_GDN_PREP_ARG_EPS_L2, fw(EPS_L2) }, { OMEGA_GDN_PREP_ARG_IN_SCALE, fw(in_scale) } }; - const SimBuf bs[] = { { OMEGA_GDN_SCAN_ARG_REC, rec, s_rec }, { OMEGA_GDN_SCAN_ARG_QKV, qkv, s_qkv }, { OMEGA_GDN_SCAN_ARG_TAIL, tail, T_TAIL_BYTES }, - { OMEGA_GDN_SCAN_ARG_STATE, state, T_STATE_BYTES }, { OMEGA_GDN_SCAN_ARG_O, o, s_o } }; - const SimWord wsc[] = { { OMEGA_GDN_SCAN_ARG_T, T }, { OMEGA_GDN_SCAN_ARG_IN_SCALE, fw(in_scale) } }; - const SimBuf bq[] = { { OMEGA_GDN_POST_ARG_O, o, s_o }, { OMEGA_GDN_POST_ARG_Z, z, s_z }, { OMEGA_GDN_POST_ARG_PAR, par, T_PAR_BYTES }, - { OMEGA_GDN_POST_ARG_OUT, out, s_o } }; - const SimWord wq[] = { { OMEGA_GDN_POST_ARG_EPS_NORM, fw(EPS_N) }, { OMEGA_GDN_POST_ARG_IN_SCALE, fw(in_scale) }, { OMEGA_GDN_POST_ARG_OUT_SCALE, fw(out_scale) } }; - char m2[200] = ""; - if (sim_launch(&pp, OMEGA_GDN_PREP_THREADS, (T + OMEGA_GDN_PREP_TOKENS - 1u) / OMEGA_GDN_PREP_TOKENS, KH, OMEGA_GDN_PREP_SHARED_BYTES, order, bp, 5, wp, 3, m2, sizeof m2)) { snprintf(msg, n, "prep: %s", m2); err = -1; break; } - if (sim_launch(&ps, OMEGA_GDN_THREADS, RT, OMEGA_GDN_GRID_Y, OMEGA_GDN_SCAN_SHARED_BYTES, order, bs, 5, wsc, 2, m2, sizeof m2)) { snprintf(msg, n, "scan: %s", m2); err = -1; break; } - if (sim_launch(&pq, OMEGA_GDN_THREADS, T, (VH / 8u), 0, order, bq, 4, wq, 3, m2, sizeof m2)) { snprintf(msg, n, "post: %s", m2); err = -1; break; } - size_t unwritten = 0; for (size_t i = 0; i < (size_t)T * VD; i++) if (out[i] == -999.0f) unwritten++; - if (unwritten) { snprintf(msg, n, "%zu output words never written", unwritten); err = -1; break; } - if (order == 0) { memcpy(out0, out, s_o); memcpy(tail0, tail, T_TAIL_BYTES); memcpy(state0, state, T_STATE_BYTES); } - else if (memcmp(out0, out, s_o) || memcmp(tail0, tail, T_TAIL_BYTES) || memcmp(state0, state, T_STATE_BYTES)) { - snprintf(msg, n, "the warp order changed the result"); err = -1; - } - } - if (!err) { - double *ts = malloc((size_t)NT * 8); - for (size_t i = 0; i < NT; i++) ts[i] = d.tail[i]; - worst->out = nerr(out, y, (size_t)T * VD); - worst->tail = omega_gdn_unpack_tail_r(GDN_TEST_RATIO, (const float *)tail, tref) != 0 ? INFINITY : nerr(tref, ts, NT); - worst->state = nerr((const float *)state, d.state, NS); - free(ts); - } - free(qkv); free(z); free(ab); free(par); free(tail); free(state); free(rec); free(o); free(out); free(out0); - free(tail0); free(state0); free(y); free(tref); - dstate_free(&d); layer_free(&L); - return err; -} -/* L313: the bf16 prefill scan equals the f32 scan run from the widened state, its final state rounded to nearest even - * (the scan holds S in registers for the whole prompt: one widen on load, one round on store). */ -static void sim_prefill_bf16(uint32_t T) { - static BlackwellIRProgram pp, p32, p16; - OmegaGdnSpec s32 = { .ratio = GDN_TEST_RATIO }, s16 = { .ratio = GDN_TEST_RATIO, .state_bf16 = 1 }; - CHECK(omega_blackwell_codegen_gdn_prep_prog(&s32, &pp) == 0 && omega_blackwell_codegen_gdn_scan_prog(&s32, &p32) == 0 && - omega_blackwell_codegen_gdn_scan_prog(&s16, &p16) == 0, "bf16 prefill codegen"); - Layer L; layer_make(&L, 21); - const uint32_t T8 = (T + OMEGA_GDN_SCAN_CHUNK - 1u) / OMEGA_GDN_SCAN_CHUNK * OMEGA_GDN_SCAN_CHUNK; - const size_t s_qkv = (size_t)T * CD * 4u, s_ab = (size_t)T * VH * 8u, s_rec = (size_t)T8 * VH * OMEGA_GDN_REC_BYTES, s_o = (size_t)T * VD * 4u; - float *qkv = aligned_alloc(256, s_qkv), *ab = aligned_alloc(256, s_ab); - uint8_t *par = aligned_alloc(256, T_PAR_BYTES), *tail = aligned_alloc(256, T_TAIL_BYTES), *tail2 = aligned_alloc(256, T_TAIL_BYTES); - uint8_t *rec = aligned_alloc(256, s_rec), *s32b = aligned_alloc(256, T_STATE_BYTES), *s16b = aligned_alloc(256, T_STATE_BYTES / 2u); - float *o32 = aligned_alloc(256, s_o), *o16 = aligned_alloc(256, s_o); - for (uint32_t t = 0; t < T; t++) { - Inp in; inp_make(&in, 1000 + t, 1.0f); - memcpy(qkv + (size_t)t * CD, in.qkv, CD * 4u); memcpy(ab + (size_t)t * VH * 2u, in.ab, VH * 8u); - inp_free(&in); - } - omega_gdn_pack_params_r(GDN_TEST_RATIO, L.conv_w, L.a_log, L.dtb, L.nw, par); - omega_gdn_pack_tail_r(GDN_TEST_RATIO, L.tail0, (float *)tail); - memcpy(tail2, tail, T_TAIL_BYTES); - uint16_t *st16 = (uint16_t *)s16b; float *st32 = (float *)s32b; - for (size_t i = 0; i < NS; i++) { st16[i] = t_bf16_rn(L.state0[i]); st32[i] = t_bf16_f(st16[i]); } - memset(rec, 0xcd, s_rec); - char m2[200] = ""; int err = 0; - const SimBuf bp[] = { { OMEGA_GDN_PREP_ARG_QKV, qkv, s_qkv }, { OMEGA_GDN_PREP_ARG_AB, ab, s_ab }, { OMEGA_GDN_PREP_ARG_PAR, par, T_PAR_BYTES }, - { OMEGA_GDN_PREP_ARG_TAIL, tail, T_TAIL_BYTES }, { OMEGA_GDN_PREP_ARG_REC, rec, s_rec } }; - const SimWord wp[] = { { OMEGA_GDN_PREP_ARG_T, T }, { OMEGA_GDN_PREP_ARG_EPS_L2, fw(EPS_L2) }, { OMEGA_GDN_PREP_ARG_IN_SCALE, fw(1.0f) } }; - const SimWord wsc[] = { { OMEGA_GDN_SCAN_ARG_T, T }, { OMEGA_GDN_SCAN_ARG_IN_SCALE, fw(1.0f) } }; - err = sim_launch(&pp, OMEGA_GDN_PREP_THREADS, (T + OMEGA_GDN_PREP_TOKENS - 1u) / OMEGA_GDN_PREP_TOKENS, KH, OMEGA_GDN_PREP_SHARED_BYTES, 0, bp, 5, wp, 3, m2, sizeof m2); - for (int k = 0; k < 2 && !err; k++) { - const SimBuf bs[] = { { OMEGA_GDN_SCAN_ARG_REC, rec, s_rec }, { OMEGA_GDN_SCAN_ARG_QKV, qkv, s_qkv }, { OMEGA_GDN_SCAN_ARG_TAIL, k ? tail2 : tail, T_TAIL_BYTES }, - { OMEGA_GDN_SCAN_ARG_STATE, k ? s16b : s32b, k ? T_STATE_BYTES / 2u : T_STATE_BYTES }, { OMEGA_GDN_SCAN_ARG_O, k ? o16 : o32, s_o } }; - err = sim_launch(k ? &p16 : &p32, OMEGA_GDN_THREADS, RT, OMEGA_GDN_GRID_Y, OMEGA_GDN_SCAN_SHARED_BYTES, 0, bs, 5, wsc, 2, m2, sizeof m2); - } - uint32_t bad_state = 0; - for (size_t i = 0; i < NS && !err; i++) bad_state += st16[i] != t_bf16_rn(st32[i]); - const int same_o = !err && memcmp(o32, o16, s_o) == 0, same_tail = !err && memcmp(tail, tail2, T_TAIL_BYTES) == 0; - printf("sim prefill bf16 T %u: scan output %s, tail %s, final states != bf16_rn(f32) %u%s%s\n", T, same_o ? "identical" : "DIFFERS", - same_tail ? "identical" : "DIFFERS", bad_state, err ? " ERROR " : "", m2); - CHECK(err == 0 && same_o && same_tail && bad_state == 0, "sim prefill bf16 T %u == f32 scan + round on store", T); - free(qkv); free(ab); free(par); free(tail); free(tail2); free(rec); free(s32b); free(s16b); free(o32); free(o16); - layer_free(&L); -} -static void sim_prefill_battery(void) { - struct { int mutant; uint32_t T; float in_scale, out_scale; const char *name; } pts[] = { - { 0, 37, 1.0f, 1.0f, "prefill T 37" }, { 0, 3, 1.0f, 1.0f, "prefill T 3" }, - { 0, 17, 0.0009765625f, 18446744073709551616.0f, "prefill T 17, in 2^-10, out 2^64" }, - { 1, 19, 1.0f, 1.0f, "prefill mutant 1 (no decay)" }, { 2, 19, 1.0f, 1.0f, "prefill mutant 2 (beta 1)" }, - { 3, 19, 1.0f, 1.0f, "prefill mutant 3 (gate z)" }, { 4, 19, 1.0f, 1.0f, "prefill mutant 4 (tail kept)" }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - char msg[300] = ""; Errs w = { 0, 0, 0 }; - double t0 = now_ms(); - int err = sim_prefill(pts[i].mutant, pts[i].T, pts[i].in_scale, pts[i].out_scale, &w, msg, sizeof msg); - printf("sim %-44s err out %.3g tail %.3g state %.3g (%.0f ms)%s%s\n", pts[i].name, w.out, w.tail, w.state, now_ms() - t0, err ? " ERROR " : "", msg); - CHECK(err == 0, "sim %s ran (%s)", pts[i].name, msg); - if (pts[i].mutant == 0) CHECK(errs_ok(&w), "sim %s within tolerance", pts[i].name); - else CHECK(!errs_ok(&w), "sim %s caught", pts[i].name); - } -} - -/* ---- the state copy / zero on the simulator: 3 CTAs; a 2-CTA launch leaves the last 1024 words (negative control) ---- */ -static void sim_copy_battery(void) { - static BlackwellIRProgram cp; - enum { W = 3 * OMEGA_GDN_COPY_WORDS_PER_CTA }; - static uint32_t src[W], dst[W]; - uint32_t x = 12345u; - for (unsigned i = 0; i < W; i++) { x = x * 1664525u + 1013904223u; src[i] = x; } - char msg[200] = ""; - for (int kind = OMEGA_GDN_COPY; kind <= OMEGA_GDN_ZERO; kind++) { - OmegaGdnSpec sp = { .copy = kind }; - CHECK(omega_blackwell_codegen_gdn_copy_prog(&sp, &cp) == 0, "copy kind %d codegen", kind); - for (uint32_t gx = 3; gx >= 2; gx--) { - memset(dst, 0xcd, sizeof dst); - SimBuf b[2] = { { OMEGA_GDN_COPY_ARG_SRC, src, sizeof src }, { OMEGA_GDN_COPY_ARG_DST, dst, sizeof dst } }; - int err = sim_launch(&cp, OMEGA_GDN_COPY_THREADS, gx, 1, 0, 0, b, 2, NULL, 0, msg, sizeof msg); - unsigned bad = 0; - for (unsigned i = 0; i < W; i++) if (dst[i] != (kind == OMEGA_GDN_COPY ? src[i] : 0u)) bad++; - CHECK(err == 0, "sim copy kind %d grid %u ran (%s)", kind, gx, msg); - if (gx == 3) CHECK(bad == 0, "sim copy kind %d: every word (%u wrong)", kind, bad); - else CHECK(bad == OMEGA_GDN_COPY_WORDS_PER_CTA, "sim copy kind %d grid 2 caught: %u words untouched", kind, bad); - } - } -} - -/* ---- chip ---- */ -static int chip_steps(OmegaGpuGdn *g, uint32_t layer, const Layer *L, DState *d, uint32_t steps, uint32_t seed, float in_scale, - float out_scale, Errs *worst, float *last_out) { - float *out = malloc((size_t)VD * 4), *tail = malloc((size_t)NT * 4), *state = malloc((size_t)NS * 4); - double *y = malloc((size_t)VD * 8), *td = malloc((size_t)NT * 8); - int rc = 0; - memset(worst, 0, sizeof *worst); - for (uint32_t st = 0; st < steps && rc == 0; st++) { - Inp in; inp_make(&in, seed + st, in_scale); - rc = omega_gpu_gdn_step(g, layer, in.qkv, in.z, in.ab, EPS_L2, EPS_N, in_scale, out_scale, out, NULL); - if (rc == 0) rc = omega_gpu_gdn_get_state(g, layer, tail, state); - if (rc == 0) { - oracle_step(L, d, &in, in_scale, out_scale, y); - for (size_t i = 0; i < NT; i++) td[i] = d->tail[i]; - Errs e = { nerr(out, y, VD), nerr(tail, td, NT), nerr(state, d->state, NS) }; - if (e.out > worst->out) worst->out = e.out; - if (e.tail > worst->tail) worst->tail = e.tail; - if (e.state > worst->state) worst->state = e.state; - } - inp_free(&in); - } - if (last_out) memcpy(last_out, out, (size_t)VD * 4); - free(out); free(tail); free(state); free(y); free(td); - return rc; -} -/* ---- prefill on the chip (omega#543) ---- */ -typedef struct { float *qkv, *z, *ab; } PfIn; -static void pf_in_make(PfIn *p, uint32_t T, uint32_t seed, float in_scale) { - p->qkv = malloc((size_t)T * CD * 4); p->z = malloc((size_t)T * VD * 4); p->ab = malloc((size_t)T * VH * 8); - for (uint32_t t = 0; t < T; t++) { - Inp in; inp_make(&in, seed + t, in_scale); - memcpy(p->qkv + (size_t)t * CD, in.qkv, CD * 4u); memcpy(p->z + (size_t)t * VD, in.z, VD * 4u); memcpy(p->ab + (size_t)t * VH * 2u, in.ab, VH * 8u); - inp_free(&in); - } -} -static void pf_in_free(PfIn *p) { free(p->qkv); free(p->z); free(p->ab); } -/* oracle over the same T rows; y [T][VD] */ -static void pf_oracle(const Layer *L, DState *d, uint32_t T, uint32_t seed, float in_scale, float out_scale, double *y) { - for (uint32_t t = 0; t < T; t++) { Inp in; inp_make(&in, seed + t, in_scale); oracle_step(L, d, &in, in_scale, out_scale, y + (size_t)t * VD); inp_free(&in); } -} -/* prefill T tokens on `layer` from its current state, then `dec` decode steps; worst errors over every row, the tail and - * the state after the prefill and after each step */ -static int chip_prefill_chain(OmegaGpuGdn *g, uint32_t layer, const Layer *L, uint32_t T, uint32_t dec, uint32_t seed, float in_scale, - float out_scale, Errs *worst, float *out_copy) { - DState d; dstate_init(&d, L); - PfIn p; pf_in_make(&p, T, seed, in_scale); - float *out = malloc((size_t)T * VD * 4), *tail = malloc((size_t)NT * 4), *state = malloc((size_t)NS * 4); - double *y = malloc((size_t)T * VD * 8), *td = malloc((size_t)NT * 8); - memset(worst, 0, sizeof *worst); - int rc = omega_gpu_gdn_prefill(g, layer, T, p.qkv, p.z, p.ab, EPS_L2, EPS_N, in_scale, out_scale, out, NULL); - if (rc == 0) rc = omega_gpu_gdn_get_state(g, layer, tail, state); - if (rc == 0) { - pf_oracle(L, &d, T, seed, in_scale, out_scale, y); - for (size_t i = 0; i < NT; i++) td[i] = d.tail[i]; - worst->out = nerr(out, y, (size_t)T * VD); worst->tail = nerr(tail, td, NT); worst->state = nerr(state, d.state, NS); - if (out_copy) memcpy(out_copy, out, (size_t)T * VD * 4); - } - if (rc == 0 && dec) { - Errs e; - rc = chip_steps(g, layer, L, &d, dec, seed + T, in_scale, out_scale, &e, NULL); - if (e.out > worst->out) worst->out = e.out; - if (e.tail > worst->tail) worst->tail = e.tail; - if (e.state > worst->state) worst->state = e.state; - } - free(out); free(tail); free(state); free(y); free(td); - pf_in_free(&p); dstate_free(&d); - return rc; -} -static void chip_prefill(OmegaGpuGdn *g, Layer *L, FILE *out, int *first, uint32_t reps) { -#define PPOINT(name, e, extra) do { if (out) { fprintf(out, "%s{\"name\":\"%s\",\"err_out\":%.6g,\"err_tail\":%.6g,\"err_state\":%.6g%s}", *first ? "" : ",", name, (e).out, (e).tail, (e).state, extra); *first = 0; } } while (0) - struct { uint32_t layer, T, dec, seed; float in_scale, out_scale; const char *name; } pp[] = { - { 1, 37, 3, 2000, 1.0f, 1.0f, "prefill layer 1, T 37, then 3 decode steps" }, - { 0, 3, 1, 2100, 1.0f, 1.0f, "prefill layer 0, T 3, then 1 decode step" }, - { 0, 41, 0, 2200, 0.0009765625f, 18446744073709551616.0f, "prefill layer 0, T 41, in 2^-10 out 2^64" }, - }; - for (size_t i = 0; i < sizeof pp / sizeof pp[0]; i++) { - CHECK(omega_gpu_gdn_set_state(g, pp[i].layer, L[pp[i].layer].tail0, L[pp[i].layer].state0) == 0, "set state for %s", pp[i].name); - Errs e; - int rc = chip_prefill_chain(g, pp[i].layer, &L[pp[i].layer], pp[i].T, pp[i].dec, pp[i].seed, pp[i].in_scale, pp[i].out_scale, &e, NULL); - printf("chip %-48s rc=%s err out %.3g tail %.3g state %.3g %s\n", pp[i].name, omega_gpu_gdn_rc_name(rc), e.out, e.tail, e.state, rc ? omega_gpu_gdn_last_error() : ""); - CHECK(rc == 0 && errs_ok(&e), "chip %s", pp[i].name); - PPOINT(pp[i].name, e, ""); - } - /* rerun from the same state: bit-identical rows */ - { - float *a = malloc((size_t)37 * VD * 4), *b = malloc((size_t)37 * VD * 4); - Errs e1, e2; - CHECK(omega_gpu_gdn_set_state(g, 1, L[1].tail0, L[1].state0) == 0, "set state for prefill rerun"); - int rc = chip_prefill_chain(g, 1, &L[1], 37, 0, 2000, 1.0f, 1.0f, &e1, a); - CHECK(omega_gpu_gdn_set_state(g, 1, L[1].tail0, L[1].state0) == 0, "set state for prefill rerun 2"); - int rc2 = chip_prefill_chain(g, 1, &L[1], 37, 0, 2000, 1.0f, 1.0f, &e2, b); - CHECK(rc == 0 && rc2 == 0 && memcmp(a, b, (size_t)37 * VD * 4) == 0, "prefill rerun from the same state is bit-identical"); - free(a); free(b); - } - /* mutants */ - for (int m = 1; m <= 4; m++) { - omega_gpu_gdn_test_set_mutant(m); - CHECK(omega_gpu_gdn_set_state(g, 1, L[1].tail0, L[1].state0) == 0, "set state prefill mutant %d", m); - Errs e; - int rc = chip_prefill_chain(g, 1, &L[1], 19, 0, 2300, 1.0f, 1.0f, &e, NULL); - char nm[40]; snprintf(nm, sizeof nm, "prefill mutant %d", m); - printf("chip %-48s rc=%s err out %.3g tail %.3g state %.3g\n", nm, omega_gpu_gdn_rc_name(rc), e.out, e.tail, e.state); - CHECK(rc == 0 && !errs_ok(&e), "chip prefill mutant %d caught", m); - PPOINT(nm, e, ""); - } - omega_gpu_gdn_test_set_mutant(0); - /* the record path: prefill 37 tokens and one decode step in one command list on layer 0 */ - { - const uint32_t T = 37; - CHECK(omega_gpu_gdn_set_state(g, 0, L[0].tail0, L[0].state0) == 0, "set state for prefill record"); - CHECK(omega_gpu_gdn_prefill_reserve(g, 64) == 0, "prefill reserve 64 tokens"); - PfIn p; pf_in_make(&p, T, 2400, 1.0f); - Inp nx; inp_make(&nx, 2400 + T, 1.0f); - DState d; dstate_init(&d, &L[0]); - double *y = malloc((size_t)T * VD * 8), *y1 = malloc((size_t)VD * 8); - pf_oracle(&L[0], &d, T, 2400, 1.0f, 1.0f, y); - oracle_step(&L[0], &d, &nx, 1.0f, 1.0f, y1); - /* warm all four kernels on layer 1 (a cache miss inside the record is refused) */ - float *tmp = malloc((size_t)T * VD * 4); - CHECK(omega_gpu_gdn_prefill(g, 1, T, p.qkv, p.z, p.ab, EPS_L2, EPS_N, 1.0f, 1.0f, tmp, NULL) == 0, "prefill warm-up"); - CHECK(omega_gpu_gdn_step(g, 1, nx.qkv, nx.z, nx.ab, EPS_L2, EPS_N, 1.0f, 1.0f, tmp, NULL) == 0, "decode warm-up"); - OmegaGpuCmdList *cl = NULL; /* create and free take the session lock themselves (omega_gpu_cmdlist.h) */ - const int cl_ok = omega_gpu_cmdlist_create(8, &cl) == 0; - omega_gpu_session_lock(); - OmegaGpuMem inb; memset(&inb, 0, sizeof inb); - const size_t s_qkv = (size_t)T * CD * 4, s_z = (size_t)T * VD * 4, s_ab = (size_t)T * VH * 8; - const size_t o_nx = (s_qkv + s_z + s_ab + 255) & ~(size_t)255; - int ok = cl_ok && omega_gpu_session_open() != NULL && omega_gpu_session_alloc(o_nx + (size_t)CD * 4 + VD * 4 + VH * 8, &inb) == 0; - if (ok) { - uint8_t *c = inb.cpu; - memcpy(c, p.qkv, s_qkv); memcpy(c + s_qkv, p.z, s_z); memcpy(c + s_qkv + s_z, p.ab, s_ab); - memcpy(c + o_nx, nx.qkv, (size_t)CD * 4); memcpy(c + o_nx + CD * 4, nx.z, (size_t)VD * 4); memcpy(c + o_nx + CD * 4 + VD * 4, nx.ab, VH * 8); - ok = omega_gpu_session_sync_to_gpu(&inb) == 0; - } - uint64_t pf_out = 0, dec_out = 0; - if (ok) ok = omega_gpu_gdn_prefill_record(cl, g, 0, T, inb.va, inb.va + s_qkv, inb.va + s_qkv + s_z, EPS_L2, EPS_N, 1.0f, 1.0f, &pf_out) == 0; - if (ok) ok = omega_gpu_gdn_record(cl, g, 0, inb.va + o_nx, inb.va + o_nx + CD * 4, inb.va + o_nx + CD * 4 + VD * 4, EPS_L2, EPS_N, 1.0f, 1.0f, &dec_out) == 0; - OmegaGpuCmdListOpts opts; memset(&opts, 0, sizeof opts); - OmegaGpuCmdListStats stc; memset(&stc, 0, sizeof stc); - if (ok) ok = omega_gpu_cmdlist_submit(cl, &opts, &stc) == 0; - if (inb.cpu) omega_gpu_session_free(&inb); - omega_gpu_session_unlock(); - if (cl) omega_gpu_cmdlist_free(cl); - CHECK(ok, "record prefill + decode step and submit (%s)", ok ? "" : omega_gpu_gdn_last_error()); - if (ok) { - float *t = malloc((size_t)NT * 4), *s = malloc((size_t)NS * 4), *yo = malloc((size_t)T * VD * 4), *y1o = malloc((size_t)VD * 4); - double *td = malloc((size_t)NT * 8); - ok = omega_gpu_gdn_get_state(g, 0, t, s) == 0 && omega_gpu_gdn_prefill_read_out(g, T, yo) == 0 && omega_gpu_gdn_read_out(g, y1o) == 0; - for (size_t i = 0; i < NT; i++) td[i] = d.tail[i]; - Errs e = { nerr(yo, y, (size_t)T * VD), nerr(t, td, NT), nerr(s, d.state, NS) }; - const double e1 = nerr(y1o, y1, VD); - if (e1 > e.out) e.out = e1; - printf("chip %-48s err out %.3g tail %.3g state %.3g\n", "record path, prefill 37 + 1 decode step", e.out, e.tail, e.state); - CHECK(ok && errs_ok(&e), "record path: prefill then a decode step match the oracle"); - PPOINT("record path, prefill 37 + 1 decode step", e, ""); - free(t); free(s); free(yo); free(y1o); free(td); - } - free(tmp); free(y); free(y1); dstate_free(&d); pf_in_free(&p); inp_free(&nx); - /* the reservation pins the scratch: a longer prefill is refused, not reallocated */ - PfIn q; pf_in_make(&q, 65, 2500, 1.0f); - float *o65 = malloc((size_t)65 * VD * 4); - CHECK(omega_gpu_gdn_prefill(g, 1, 65, q.qkv, q.z, q.ab, EPS_L2, EPS_N, 1.0f, 1.0f, o65, NULL) == OMEGA_GPU_GDN_TOO_LARGE, "prefill past the reservation is refused"); - free(o65); pf_in_free(&q); - } - /* timing per launch at three prompt lengths (a fresh, unreserved scratch per length) */ - const uint32_t Ts[3] = { 512, 2048, 8192 }; - for (unsigned k = 0; k < 3; k++) { - const uint32_t T = Ts[k], nrep = reps < 5 ? reps : 5; - CHECK(omega_gpu_gdn_prefill_reserve(g, T) == 0, "reserve %u tokens", T); - PfIn p; pf_in_make(&p, T, 3000, 1.0f); - float *o = malloc((size_t)T * VD * 4); - uint64_t e[3][5], c[5]; - uint32_t done = 0; - OmegaGpuGdnPfInfo info; - for (uint32_t r = 0; r < nrep; r++) { - if (omega_gpu_gdn_prefill(g, 0, T, p.qkv, p.z, p.ab, EPS_L2, EPS_N, 1.0f, 1.0f, o, &info) != 0) break; - for (unsigned j = 0; j < 3; j++) e[j][done] = info.elapsed_ns[j]; - c[done] = info.call_ns; done++; - } - CHECK(done == nrep, "prefill T %u timing reps ran (%u of %u): %s", T, done, nrep, done == nrep ? "" : omega_gpu_gdn_last_error()); - if (done) { - for (unsigned j = 0; j < 3; j++) qsort(e[j], done, 8, cmp_u64); - qsort(c, done, 8, cmp_u64); - const double us[3] = { e[0][done / 2] / 1e3, e[1][done / 2] / 1e3, e[2][done / 2] / 1e3 }, tot = us[0] + us[1] + us[2]; - printf("timing prefill T %u (medians of %u): prep %.1f us, scan %.1f us, post %.1f us, chip total %.1f us = %.2f us/token, call %.1f us; insns %u/%u/%u, registers %u/%u/%u\n", - T, done, us[0], us[1], us[2], tot, tot / T, c[done / 2] / 1e3, info.insns[0], info.insns[1], info.insns[2], info.gprs[0], info.gprs[1], info.gprs[2]); - if (out) fprintf(out, "%s{\"name\":\"timing prefill\",\"tokens\":%u,\"reps\":%u,\"prep_us\":%.3f,\"scan_us\":%.3f,\"post_us\":%.3f,\"chip_us\":%.3f,\"us_per_token\":%.4f,\"call_us\":%.3f,\"insns\":[%u,%u,%u],\"gprs\":[%u,%u,%u]}", - *first ? "" : ",", T, done, us[0], us[1], us[2], tot, tot / T, c[done / 2] / 1e3, info.insns[0], info.insns[1], info.insns[2], info.gprs[0], info.gprs[1], info.gprs[2]); - *first = 0; - } - free(o); pf_in_free(&p); - } -#undef PPOINT -} -/* ---- L313 bf16 state on the chip: a bf16 GDN (AIEN_OMEGA_GDN_STATE_BF16=1 at alloc) against an f32 GDN started from the - * same (bf16-representable) state, 4 decode steps then a 19-token prefill, re-synced after every call: outputs and tails - * bit-identical, the bf16 state equal to bf16_rn of the f32 state. Then the chip time of one decode step of each, interleaved. ---- */ -static int chip_bf16(const char *out_path, uint32_t reps) { - OmegaGpuGdn *g16 = NULL, *g32 = NULL; - setenv("AIEN_OMEGA_GDN_STATE_BF16", "1", 1); - int rc = omega_gpu_gdn_alloc_ratio(1, GDN_TEST_RATIO, &g16); - unsetenv("AIEN_OMEGA_GDN_STATE_BF16"); - if (rc == 0) rc = omega_gpu_gdn_alloc_ratio(1, GDN_TEST_RATIO, &g32); - CHECK(rc == 0, "bf16 + f32 gdn alloc (%s)", rc ? omega_gpu_gdn_last_error() : ""); - if (rc) return 1; - Layer L; layer_make(&L, 41); - float *st = malloc((size_t)NS * 4), *s16 = malloc((size_t)NS * 4), *s32 = malloc((size_t)NS * 4); - float *t16 = malloc((size_t)NT * 4), *t32 = malloc((size_t)NT * 4); - for (size_t i = 0; i < NS; i++) st[i] = t_bf16_f(t_bf16_rn(L.state0[i])); - for (int k = 0; k < 2; k++) { - OmegaGpuGdn *g = k ? g32 : g16; - CHECK(omega_gpu_gdn_set_layer(g, 0, L.conv_w, L.a_log, L.dtb, L.nw) == 0 && omega_gpu_gdn_set_state(g, 0, L.tail0, st) == 0, "bf16 setup %d", k); - } - const uint32_t T = 19; - float *o16 = malloc((size_t)T * VD * 4), *o32 = malloc((size_t)T * VD * 4); - uint32_t bad_out = 0, bad_tail = 0, bad_state = 0, rounded = 0, calls = 0; - double us16 = 0, us32 = 0; - for (uint32_t c = 0; c < 5 && rc == 0; c++) { - const uint32_t n = c < 4 ? 1u : T; - PfIn p; pf_in_make(&p, n, 900 + 37 * c, 1.0f); - for (int k = 0; k < 2 && rc == 0; k++) { - OmegaGpuGdn *g = k ? g32 : g16; - rc = n == 1 ? omega_gpu_gdn_step(g, 0, p.qkv, p.z, p.ab, EPS_L2, EPS_N, 1.0f, 1.0f, k ? o32 : o16, NULL) - : omega_gpu_gdn_prefill(g, 0, n, p.qkv, p.z, p.ab, EPS_L2, EPS_N, 1.0f, 1.0f, k ? o32 : o16, NULL); - } - if (rc == 0) rc = omega_gpu_gdn_get_state(g16, 0, t16, s16); - if (rc == 0) rc = omega_gpu_gdn_get_state(g32, 0, t32, s32); - if (rc == 0) { - calls++; - for (size_t i = 0; i < (size_t)n * VD; i++) bad_out += memcmp(&o16[i], &o32[i], 4) != 0; - bad_tail += memcmp(t16, t32, (size_t)NT * 4) != 0; - for (size_t i = 0; i < NS; i++) { bad_state += t_bf16_rn(s32[i]) != t_bf16_rn(s16[i]) || t_bf16_f(t_bf16_rn(s16[i])) != s16[i]; rounded += s16[i] != s32[i]; } - rc = omega_gpu_gdn_set_state(g32, 0, t16, s16); /* re-sync: the f32 GDN continues from the bf16 state */ - } - pf_in_free(&p); - } - /* chip time of one decode step, bf16 vs f32 state, interleaved (the live server shares the chip): medians of reps */ - if (rc == 0) { - PfIn p; pf_in_make(&p, 1, 950, 1.0f); - uint64_t *k16 = malloc((size_t)reps * 8), *k32 = malloc((size_t)reps * 8), b16 = 0, b32 = 0; - uint32_t done = 0; - OmegaGpuGdnInfo i16, i32; - for (uint32_t r = 0; r < reps; r++) { - if (omega_gpu_gdn_step(g16, 0, p.qkv, p.z, p.ab, EPS_L2, EPS_N, 1.0f, 1.0f, o16, &i16) != 0) break; - if (omega_gpu_gdn_step(g32, 0, p.qkv, p.z, p.ab, EPS_L2, EPS_N, 1.0f, 1.0f, o32, &i32) != 0) break; - k16[done] = i16.elapsed_ns; k32[done] = i32.elapsed_ns; b16 = i16.state_bytes; b32 = i32.state_bytes; done++; - } - CHECK(done == reps, "bf16 timing reps ran (%u of %u)", done, reps); - CHECK(done == 0 || 2 * b16 == b32, "bf16 step moves half the state bytes (%" PRIu64 " vs %" PRIu64 ")", b16, b32); - if (done) { - qsort(k16, done, 8, cmp_u64); qsort(k32, done, 8, cmp_u64); - const double u16 = k16[done / 2] / 1e3, u32 = k32[done / 2] / 1e3; - printf("timing bf16 vs f32 state (medians of %u, interleaved): bf16 chip %.1f us (state read + write %.2f MB -> %.1f GB/s), " - "f32 chip %.1f us (%.2f MB -> %.1f GB/s); 273 GB/s nominal; bf16 %u insns %u registers\n", - done, u16, b16 / 1e6, b16 / (u16 * 1e3), u32, b32 / 1e6, b32 / (u32 * 1e3), i16.insns, i16.gprs); - us16 = u16; us32 = u32; - } - free(k16); free(k32); pf_in_free(&p); - } - printf("chip bf16 state: %u calls (4 decode steps, 1 prefill of %u), rc=%s, outputs differing %u, tails differing %u, " - "states != bf16_rn(f32) %u, rounded %u of %u; decode step chip us (median) bf16 %.1f f32 %.1f %s\n", - calls, T, omega_gpu_gdn_rc_name(rc), bad_out, bad_tail, bad_state, rounded, calls * NS, us16, us32, rc ? omega_gpu_gdn_last_error() : ""); - CHECK(rc == 0 && calls == 5, "chip bf16 ran"); - CHECK(bad_out == 0 && bad_tail == 0 && bad_state == 0, "chip bf16 == f32 + round to nearest even on store"); - CHECK(rounded > NS, "chip bf16 really rounds"); - if (out_path) { - FILE *f = fopen(out_path, "w"); - if (f) { - fprintf(f, "{\"receipt\":\"OMEGA_GPU_GDN_BF16_V1\",\"ratio\":%u,\"calls\":%u,\"prefill_tokens\":%u,\"outputs_differing\":%u," - "\"tails_differing\":%u,\"states_not_rn\":%u,\"rounded\":%u,\"values\":%u,\"chip_us_bf16\":%.3f,\"chip_us_f32\":%.3f,\"verdict\":\"%s\"}\n", - (unsigned)RT, calls, T, bad_out, bad_tail, bad_state, rounded, calls * NS, us16, us32, g_failed ? "FAIL" : "PASS"); - fclose(f); - } - } - free(st); free(s16); free(s32); free(t16); free(t32); free(o16); free(o32); - layer_free(&L); omega_gpu_gdn_free(g16); omega_gpu_gdn_free(g32); - return g_failed ? 1 : 0; -} -static int chip_run(const char *out_path, uint32_t reps) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot write %s\n", out_path); return 1; } - if (out) fprintf(out, "{\"receipt\":\"OMEGA_GPU_GDN_V1\",\"reps\":%u,\"tol\":{\"out\":%g,\"tail\":%g,\"state\":%g},\"points\":[", reps, TOL_OUT, TOL_TAIL, TOL_STATE); - OmegaGpuGdn *g = NULL; - double t0 = now_ms(); - int rc = omega_gpu_gdn_alloc_ratio(2, GDN_TEST_RATIO, &g); - printf("gdn alloc (2 layers): rc=%s %.1f ms (%s)\n", omega_gpu_gdn_rc_name(rc), now_ms() - t0, rc ? omega_gpu_gdn_last_error() : ""); - CHECK(rc == OMEGA_GPU_GDN_OK, "gdn alloc"); - if (rc) { if (out) fprintf(out, "],\"verdict\":\"FAIL\"}\n"); return 1; } - Layer L[2]; layer_make(&L[0], 31); layer_make(&L[1], 32); - for (uint32_t l = 0; l < 2; l++) { - CHECK(omega_gpu_gdn_set_layer(g, l, L[l].conv_w, L[l].a_log, L[l].dtb, L[l].nw) == 0, "set layer %u", l); - CHECK(omega_gpu_gdn_set_state(g, l, L[l].tail0, L[l].state0) == 0, "set state %u", l); - } - int first = 1; -#define POINT(name, e, extra) do { if (out) { fprintf(out, "%s{\"name\":\"%s\",\"err_out\":%.6g,\"err_tail\":%.6g,\"err_state\":%.6g%s}", first ? "" : ",", name, (e).out, (e).tail, (e).state, extra); first = 0; } } while (0) - /* parity: layer 1 first (addressing), then layer 0 with in/out scales */ - struct { uint32_t layer, steps, seed; float in_scale, out_scale; const char *name; } pp[] = { - { 1, 5, 500, 1.0f, 1.0f, "layer 1, 5 steps" }, - { 0, 5, 600, 0.0009765625f, 18446744073709551616.0f, "layer 0, 5 steps, in 2^-10 out 2^64" }, - }; - float *o1 = malloc((size_t)VD * 4), *o2 = malloc((size_t)VD * 4); - for (size_t i = 0; i < 2; i++) { - DState d; dstate_init(&d, &L[pp[i].layer]); - Errs e; - rc = chip_steps(g, pp[i].layer, &L[pp[i].layer], &d, pp[i].steps, pp[i].seed, pp[i].in_scale, pp[i].out_scale, &e, o1); - printf("chip %-40s rc=%s err out %.3g tail %.3g state %.3g %s\n", pp[i].name, omega_gpu_gdn_rc_name(rc), e.out, e.tail, e.state, rc ? omega_gpu_gdn_last_error() : ""); - CHECK(rc == 0 && errs_ok(&e), "chip %s", pp[i].name); - POINT(pp[i].name, e, ""); - dstate_free(&d); - } - /* rerun from the same state: bit-identical */ - { - Inp in; inp_make(&in, 700, 1.0f); - CHECK(omega_gpu_gdn_set_state(g, 1, L[1].tail0, L[1].state0) == 0, "set state for rerun"); - rc = omega_gpu_gdn_step(g, 1, in.qkv, in.z, in.ab, EPS_L2, EPS_N, 1.0f, 1.0f, o1, NULL); - CHECK(omega_gpu_gdn_set_state(g, 1, L[1].tail0, L[1].state0) == 0, "set state for rerun 2"); - int rc2 = omega_gpu_gdn_step(g, 1, in.qkv, in.z, in.ab, EPS_L2, EPS_N, 1.0f, 1.0f, o2, NULL); - CHECK(rc == 0 && rc2 == 0 && memcmp(o1, o2, (size_t)VD * 4) == 0, "rerun from the same state is bit-identical"); - inp_free(&in); - } - /* reset: state and tail zero */ - { - float *t = malloc((size_t)NT * 4), *s = malloc((size_t)NS * 4); - rc = omega_gpu_gdn_reset(g); - int z = rc == 0 && omega_gpu_gdn_get_state(g, 0, t, s) == 0; - for (size_t i = 0; z && i < NT; i++) if (t[i] != 0.0f) z = 0; - for (size_t i = 0; z && i < NS; i++) if (s[i] != 0.0f) z = 0; - CHECK(z, "reset zeroes the tail and the state"); - free(t); free(s); - } - /* mutants: each must miss */ - for (int m = 1; m <= 4; m++) { - omega_gpu_gdn_test_set_mutant(m); - CHECK(omega_gpu_gdn_set_state(g, 1, L[1].tail0, L[1].state0) == 0, "set state mutant %d", m); - DState d; dstate_init(&d, &L[1]); - Errs e; - rc = chip_steps(g, 1, &L[1], &d, 2, 800, 1.0f, 1.0f, &e, NULL); - char nm[32]; snprintf(nm, sizeof nm, "mutant %d", m); - printf("chip %-40s rc=%s err out %.3g tail %.3g state %.3g\n", nm, omega_gpu_gdn_rc_name(rc), e.out, e.tail, e.state); - CHECK(rc == 0 && !errs_ok(&e), "chip mutant %d caught", m); - POINT(nm, e, ""); - dstate_free(&d); - } - omega_gpu_gdn_test_set_mutant(0); - /* the record path: two chained steps in one command list on layer 0 */ - { - CHECK(omega_gpu_gdn_set_state(g, 0, L[0].tail0, L[0].state0) == 0, "set state for record"); - Inp in[2]; inp_make(&in[0], 900, 1.0f); inp_make(&in[1], 901, 1.0f); - DState d; dstate_init(&d, &L[0]); - double *y = malloc((size_t)VD * 8); - oracle_step(&L[0], &d, &in[0], 1.0f, 1.0f, y); oracle_step(&L[0], &d, &in[1], 1.0f, 1.0f, y); - /* warm the kernel cache outside the record (a miss inside is refused) */ - float *tmp = malloc((size_t)VD * 4); - CHECK(omega_gpu_gdn_step(g, 1, in[0].qkv, in[0].z, in[0].ab, EPS_L2, EPS_N, 1.0f, 1.0f, tmp, NULL) == 0, "warm-up step"); - OmegaGpuCmdList *cl = NULL; /* create and free take the session lock themselves (omega_gpu_cmdlist.h) */ - const int cl_ok = omega_gpu_cmdlist_create(4, &cl) == 0; - omega_gpu_session_lock(); - OmegaGpuMem inb[2]; memset(inb, 0, sizeof inb); - int ok = cl_ok && omega_gpu_session_open() != NULL; - const size_t ib = (size_t)CD * 4 + (size_t)VD * 4 + VH * 8; - for (int i = 0; ok && i < 2; i++) { - ok = omega_gpu_session_alloc(ib, &inb[i]) == 0; - if (ok) { - memcpy(inb[i].cpu, in[i].qkv, (size_t)CD * 4); memcpy((uint8_t *)inb[i].cpu + CD * 4, in[i].z, (size_t)VD * 4); - memcpy((uint8_t *)inb[i].cpu + CD * 4 + VD * 4, in[i].ab, VH * 8); - ok = omega_gpu_session_sync_to_gpu(&inb[i]) == 0; - } - } - uint64_t out_va = 0; - for (int i = 0; ok && i < 2; i++) - ok = omega_gpu_gdn_record(cl, g, 0, inb[i].va, inb[i].va + CD * 4, inb[i].va + CD * 4 + VD * 4, EPS_L2, EPS_N, 1.0f, 1.0f, &out_va) == 0; - OmegaGpuCmdListOpts opts; memset(&opts, 0, sizeof opts); - OmegaGpuCmdListStats stc; memset(&stc, 0, sizeof stc); - if (ok) ok = omega_gpu_cmdlist_submit(cl, &opts, &stc) == 0; - for (int i = 0; i < 2; i++) if (inb[i].cpu) omega_gpu_session_free(&inb[i]); - omega_gpu_session_unlock(); - if (cl) omega_gpu_cmdlist_free(cl); - CHECK(ok, "record two steps and submit (%s)", ok ? "" : omega_gpu_gdn_last_error()); - if (ok) { - float *t = malloc((size_t)NT * 4), *s = malloc((size_t)NS * 4), *yo = malloc((size_t)VD * 4); - double *td = malloc((size_t)NT * 8); - ok = omega_gpu_gdn_get_state(g, 0, t, s) == 0 && omega_gpu_gdn_read_out(g, yo) == 0; /* the second step's output */ - for (size_t i = 0; i < NT; i++) td[i] = d.tail[i]; - Errs e = { nerr(yo, y, VD), nerr(t, td, NT), nerr(s, d.state, NS) }; - printf("chip %-40s err out %.3g tail %.3g state %.3g\n", "record path, 2 chained steps", e.out, e.tail, e.state); - CHECK(ok && errs_ok(&e), "record path: two chained steps match the oracle"); - POINT("record path, 2 chained steps", e, ""); - free(t); free(s); free(yo); free(td); - } - free(tmp); free(y); dstate_free(&d); inp_free(&in[0]); inp_free(&in[1]); - } - chip_prefill(g, L, out, &first, reps); - /* timing */ - { - Inp in; inp_make(&in, 950, 1.0f); - uint64_t *ec = malloc(reps * 8), *ek = malloc(reps * 8); - uint32_t done = 0; - OmegaGpuGdnInfo info; - for (uint32_t r = 0; r < reps; r++) { - if (omega_gpu_gdn_step(g, 0, in.qkv, in.z, in.ab, EPS_L2, EPS_N, 1.0f, 1.0f, o1, &info) != 0) break; - ek[done] = info.elapsed_ns; ec[done] = info.call_ns; done++; - } - CHECK(done == reps, "timing reps ran (%u of %u)", done, reps); - if (done) { - qsort(ek, done, 8, cmp_u64); qsort(ec, done, 8, cmp_u64); - const double kus = ek[done / 2] / 1e3, cus = ec[done / 2] / 1e3, gbs = (double)info.state_bytes / (ek[done / 2] * 1e-9) / 1e9; - printf("timing (medians of %u): chip %.1f us (state read + write %.2f MB -> %.1f GB/s; 273 GB/s nominal), call %.1f us; %u insns, %u registers\n", - done, kus, info.state_bytes / 1e6, gbs, cus, info.insns, info.gprs); - if (out) fprintf(out, "%s{\"name\":\"timing\",\"reps\":%u,\"chip_us_median\":%.3f,\"call_us_median\":%.3f,\"state_bytes\":%" PRIu64 ",\"state_gbs\":%.2f,\"nominal_gbs\":273,\"insns\":%u,\"gprs\":%u}", - first ? "" : ",", done, kus, cus, info.state_bytes, gbs, info.insns, info.gprs); - first = 0; - } - free(ec); free(ek); inp_free(&in); - } -#undef POINT - free(o1); free(o2); - layer_free(&L[0]); layer_free(&L[1]); - omega_gpu_gdn_free(g); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - return 0; -} - -int main(int argc, char **argv) { - setvbuf(stdout, NULL, _IOLBF, 0); /* a stuck chip run still leaves every finished line in its log */ - int bf16 = 0; - int host = 0, sim = 0; const char *out_path = NULL; uint32_t reps = 0, spin = 2000; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--bf16") == 0) bf16 = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - if (host) host_only(); - if (sim) { sim_battery(); sim_bf16_battery(); sim_prefill_battery(); sim_prefill_bf16(3); sim_prefill_bf16(37); sim_copy_battery(); } - if (!host && !sim) { - (void)omega_gpu_session_set_spin_us(spin); - if (bf16) chip_bf16(out_path, reps ? reps : 50); else chip_run(out_path, reps ? reps : 50); - omega_gpu_session_close(); - } - printf("gpu_gdn_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_gemm_test.c b/tests/gpu_gemm_test.c deleted file mode 100644 index b60f70964..000000000 --- a/tests/gpu_gemm_test.c +++ /dev/null @@ -1,337 +0,0 @@ -/* gpu_gemm_test.c -- row C3 of docs/OMEGA.md: matrix multiply of any shape, BF16 and FP8 (e4m3), both layouts of A and B, - * on the GB10 tensor cores, checked bit for bit against a host model of the same tensor-core steps (src/omega_gpu_gemm.h). - * - * --host-only no device: refusals, every kernel (both types, several shapes of tile, the red-check mutants) through our - * code generator and encoder, register counts - * --sim the real kernels in the warp simulator (tensor-core ops computed with the chip-exact models), small shapes - * over every edge case, all four layouts, three tile configurations; the three mutants must be caught - * (no flag) the GB10: at least 200 shapes with M, N, K from 1 to 8192, both types, all four layouts. Every output word - * must be written; shapes up to 2^27 multiply-adds are compared in full, larger ones on 4096 sampled - * elements plus the last row and column. Speed: 2 M N K / kernel time, as a fraction of the measured - * tensor-core ceiling (BF16 HMMA 115.36 TFLOPS, evidence OWN30B-T3-TC-PEAK-BW-5faa0f70-20261013T2236Z; - * FP8 QMMA 237.52 TFLOPS, L151 as quoted in evidence/L403-roof-20261022). The mutants must be caught. - * --quick: 24 shapes, for a first look. - * Last line: "C3 gemm : PASS ( checks)" or "... FAIL ( of )". */ -#include "omega_gpu_gemm.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_tc.h" - -#include - -static int g_checks, g_failed; -static void check(int ok, const char *what) { - g_checks++; - if (!ok) { g_failed++; printf("FAIL: %s\n", what); } -} - -static const HmmaModel HM = { 16, 2, 0, 2, 0 }; /* chip-exact, evidence OWN30B-T3-HMMA-MODEL */ -static const QmmaModel QM = { 32, 26, 0, 2, 0 }; /* chip-exact, evidence OWN30B-L1G-QMMA-PFGEMM-c742aa13 */ -static const char *tname(OmegaGpuGemmType t) { return t == OMEGA_GPU_GEMM_BF16 ? "bf16" : "e4m3"; } -static const char *lname(unsigned l) { static const char *n[4] = { "A row B row", "A col B row", "A row B col", "A col B col" }; return n[l & 3u]; } - -static uint64_t g_rng = 1; -static uint32_t rnd(void) { g_rng = g_rng * 6364136223846793005ull + 1442695040888963407ull; return (uint32_t)(g_rng >> 33); } - -/* inputs: bf16 values 0 or +-(1 + m/128) 2^e, e in -8..8; e4m3 any code except the two NaNs */ -static void fill(OmegaGpuGemmType t, void *p, uint64_t n, uint64_t seed) { - g_rng = seed * 0x2545f4914f6cdd1dull + 7; - if (t == OMEGA_GPU_GEMM_BF16) { - uint16_t *h = p; - for (uint64_t i = 0; i < n; i++) { - uint32_t r = rnd(); - h[i] = r % 61u == 0 ? 0 : (uint16_t)(((r >> 8) & 1u) << 15 | (uint32_t)(127 + (int)((r >> 9) % 17u) - 8) << 7 | (r >> 16 & 0x7fu)); - } - } else { - uint8_t *b = p; - for (uint64_t i = 0; i < n; i++) { uint8_t c = (uint8_t)rnd(); b[i] = (c & 0x7fu) == 0x7fu ? (uint8_t)(c ^ 1u) : c; } - } -} - -static float val(OmegaGpuGemmType t, const void *p, uint64_t i) { - if (t == OMEGA_GPU_GEMM_BF16) { uint32_t u = (uint32_t)((const uint16_t *)p)[i] << 16; float f; memcpy(&f, &u, 4); return f; } - return qm_e4m3(((const uint8_t *)p)[i]); -} - -/* the host model: one tensor-core step per 16 (bf16) or 32 (e4m3) values of k, in increasing k, from +0 */ -static float ref_elem(OmegaGpuGemmType t, unsigned lay, uint32_t M, uint32_t N, uint32_t K, const void *A, const void *B, uint32_t m, uint32_t n) { - const uint32_t ks = t == OMEGA_GPU_GEMM_BF16 ? 16u : 32u; - float acc = 0.0f; - for (uint32_t k0 = 0; k0 < K; k0 += ks) { - float av[32], bv[32]; - for (uint32_t k = 0; k < ks; k++) { - uint32_t kk = k0 + k; - if (kk >= K) { av[k] = bv[k] = 0.0f; continue; } - av[k] = val(t, A, lay & OMEGA_GPU_GEMM_A_COL ? (uint64_t)kk * M + m : (uint64_t)m * K + kk); - bv[k] = val(t, B, lay & OMEGA_GPU_GEMM_B_COL ? (uint64_t)n * K + kk : (uint64_t)kk * N + n); - } - acc = t == OMEGA_GPU_GEMM_BF16 ? hm_dot16(&HM, av, bv, acc) : qm_dot32(&QM, av, bv, acc); - } - return acc; -} - -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } - -/* compare: every element when M N K <= 2^27, else 4096 samples + the last row and column; returns the mismatches */ -static uint64_t compare(OmegaGpuGemmType t, unsigned lay, uint32_t M, uint32_t N, uint32_t K, const void *A, const void *B, const float *C, - uint64_t *checked, char *first, size_t firstn) { - uint64_t bad = 0; *checked = 0; first[0] = 0; - #define ONE(mm, nn) do { uint32_t m_ = (mm), n_ = (nn); float w_ = ref_elem(t, lay, M, N, K, A, B, m_, n_), g_ = C[(uint64_t)m_ * N + n_]; (*checked)++; \ - if (f2u(w_) != f2u(g_)) { if (!bad) snprintf(first, firstn, "C[%u][%u] = %08x, model %08x", m_, n_, f2u(g_), f2u(w_)); bad++; } } while (0) - if ((uint64_t)M * N * K <= (1ull << 27)) { - for (uint32_t m = 0; m < M; m++) for (uint32_t n = 0; n < N; n++) ONE(m, n); - } else { - g_rng = (uint64_t)M * 31 + N * 7 + K; - for (int i = 0; i < 4096; i++) ONE(rnd() % M, rnd() % N); - for (uint32_t n = 0; n < N; n += N > 512 ? N / 512 : 1) ONE(M - 1, n); - for (uint32_t m = 0; m < M; m += M > 512 ? M / 512 : 1) ONE(m, N - 1); - ONE(M - 1, N - 1); - } - #undef ONE - return bad; -} - -/* ------------------------------------------------------------------ host only */ - -static void host_only(void) { - char w[200]; - uint16_t a[4] = { 0 }, b[4] = { 0 }; float c[4]; - check(omega_gpu_gemm(OMEGA_GPU_GEMM_BF16, 0, 0, 1, 1, a, b, c, NULL) == OMEGA_GPU_GEMM_BAD_ARGS, "M = 0 refused"); - check(omega_gpu_gemm(OMEGA_GPU_GEMM_BF16, 0, 1, 1, 0, a, b, c, NULL) == OMEGA_GPU_GEMM_BAD_ARGS, "K = 0 refused"); - check(omega_gpu_gemm(OMEGA_GPU_GEMM_BF16, 0, OMEGA_GPU_GEMM_MAX_DIM + 1, 1, 1, a, b, c, NULL) == OMEGA_GPU_GEMM_TOO_LARGE, "M past the maximum refused"); - check(omega_gpu_gemm(OMEGA_GPU_GEMM_BF16, 4, 1, 1, 1, a, b, c, NULL) == OMEGA_GPU_GEMM_BAD_ARGS, "unknown layout bits refused"); - check(omega_gpu_gemm((OmegaGpuGemmType)2, 0, 1, 1, 1, a, b, c, NULL) == OMEGA_GPU_GEMM_BAD_ARGS, "unknown type refused"); - check(omega_gpu_gemm(OMEGA_GPU_GEMM_E4M3, 0, 1, 1, 1, NULL, b, c, NULL) == OMEGA_GPU_GEMM_BAD_ARGS, "NULL A refused"); - OmegaGemmCfg bad; omega_gpu_gemm_default_cfg(OMEGA_GPU_GEMM_BF16, &bad); bad.rt = 3; - check(!omega_gpu_gemm_cfg_ok(&bad), "a tile of 3 row tiles refused"); - - /* the model itself is a multiply: within 2^-20 of the exact sum, relative to the sum of the magnitudes */ - for (int t = 0; t < 2; t++) for (unsigned lay = 0; lay < 4; lay++) { - enum { MM = 23, NN = 19, KK = 300 }; - static uint16_t A[MM * KK], B[KK * NN]; - fill((OmegaGpuGemmType)t, A, MM * KK, 5 + lay); fill((OmegaGpuGemmType)t, B, KK * NN, 9 + lay); - double worst = 0; - for (uint32_t m = 0; m < MM; m++) for (uint32_t n = 0; n < NN; n++) { - double ex = 0, mag = 0; - for (uint32_t k = 0; k < KK; k++) { - double p = (double)val((OmegaGpuGemmType)t, A, lay & OMEGA_GPU_GEMM_A_COL ? (uint64_t)k * MM + m : (uint64_t)m * KK + k) * - (double)val((OmegaGpuGemmType)t, B, lay & OMEGA_GPU_GEMM_B_COL ? (uint64_t)n * KK + k : (uint64_t)k * NN + n); - ex += p; mag += fabs(p); - } - double d = fabs((double)ref_elem((OmegaGpuGemmType)t, lay, MM, NN, KK, A, B, m, n) - ex) / (mag > 0 ? mag : 1); - if (d > worst) worst = d; - } - snprintf(w, sizeof w, "the %s model is a multiply (%s): worst error %.3g of the magnitude sum", tname((OmegaGpuGemmType)t), lname(lay), worst); - check(worst < ldexp(1.0, -20), w); - printf("%s\n", w); - } - - const OmegaGemmCfg shapes[] = { { 0, 2, 4, 2, 2, 4, 0 }, { 0, 1, 1, 1, 1, 4, 0 }, { 0, 4, 1, 2, 2, 2, 0 }, { 0, 1, 4, 4, 1, 2, 0 }, { 0, 2, 2, 1, 4, 8, 0 } }; - OmegaGemmCfg big; omega_gpu_gemm_default_cfg(OMEGA_GPU_GEMM_BF16, &big); big.rt = 4; big.ct = 2; - check(!omega_gpu_gemm_cfg_ok(&big), "a tile past the register budget (rt 4 ct 2) refused"); - for (int t = 0; t < 2; t++) - for (size_t s = 0; s < sizeof shapes / sizeof shapes[0]; s++) - for (int mut = 0; mut <= 3; mut++) - for (int k = 0; k < OMEGA_GEMM_K_COUNT; k++) { - OmegaGemmCfg c = shapes[s]; c.type = (OmegaGpuGemmType)t; c.mutant = mut; - BlackwellIRProgram *p = calloc(1, sizeof *p); - int rc = omega_gpu_gemm_codegen(&c, (OmegaGemmKind)k, p); - size_t bytes = rc == 0 ? omega_bw_program_code_bytes(p) : 0; - uint8_t *code = bytes ? malloc(bytes) : NULL; - OmegaBlackwellKernel kk; memset(&kk, 0, sizeof kk); - int enc = code ? omega_blackwell_kernel_encode_into(p, code, bytes, &kk) : -1; - int np = enc == 0 ? omega_qmma_patch_code(p, code, bytes) : -1; - snprintf(w, sizeof w, "%s rt %u ct %u wm %u wn %u kernel %d mutant %d: codegen %d, encode %d, qmma patches %d, %u gprs", tname(c.type), - c.rt, c.ct, c.wm, c.wn, k, mut, rc, enc, np, (unsigned)kk.gpr_count); - check(rc == 0 && enc == 0 && kk.code_size == bytes && np >= 0 && (t == 1 || np == 0) && omega_bw_gpr_declared(kk.gpr_count) <= 255u, w); - if (mut == 0) printf("%s\n", w); - free(code); free(p); - } -} - -/* ------------------------------------------------------------------ the simulator */ - -typedef struct { - BlackwellIRProgram *prog[OMEGA_GEMM_K_COUNT]; - WsRange ranges[5]; - int order; - char err[300]; -} SimCtx; - -static int sim_launch(void *ctx, OmegaGemmKind k, const uint32_t a[OMEGA_GPU_GEMM_ARGS_WORDS], uint32_t gx, uint32_t gy, uint32_t threads) { - SimCtx *c = ctx; - static WsSim s; - memset(&s, 0, sizeof s); - s.p = c->prog[k]; s.threads = threads; s.order = c->order; - for (unsigned i = 0; i < OMEGA_GPU_GEMM_ARGS_WORDS; i++) s.cbank[0x380 / 4 + i] = a[i]; - memcpy(s.ranges, c->ranges, sizeof c->ranges); s.nranges = 5; - if (ws_run(&s, gx, gy) != 0) { snprintf(c->err, sizeof c->err, "kernel %d: %s at pc %d", (int)k, s.msg, s.err_pc); return -1; } - return 0; -} - -static int sim_build(SimCtx *c, const OmegaGemmCfg *cfg) { - for (int k = 0; k < OMEGA_GEMM_K_COUNT; k++) { - c->prog[k] = calloc(1, sizeof *c->prog[k]); - if (!c->prog[k] || omega_gpu_gemm_codegen(cfg, (OmegaGemmKind)k, c->prog[k]) != 0) return -1; - } - return 0; -} -static void sim_free(SimCtx *c) { for (int k = 0; k < OMEGA_GEMM_K_COUNT; k++) { free(c->prog[k]); c->prog[k] = NULL; } } - -/* one multiply through the simulator; 0 when it ran and every output word was written */ -static int sim_gemm(SimCtx *c, const OmegaGemmCfg *cfg, unsigned lay, uint32_t M, uint32_t N, uint32_t K, const void *A, const void *B, float *C) { - OmegaGemmPlan p; - if (omega_gpu_gemm_plan(cfg, M, N, K, &p) != 0) return -2; - uint8_t *ap = malloc(p.ap_bytes), *bp = malloc(p.bp_bytes); - memset(ap, 0xa5, p.ap_bytes); memset(bp, 0x5a, p.bp_bytes); - for (uint64_t i = 0; i < (uint64_t)M * N; i++) { uint32_t u = 0x7fa00badu; memcpy(&C[i], &u, 4); } - c->ranges[0] = (WsRange){ (uintptr_t)A, (uintptr_t)A + p.a_bytes + 1 }; /* the e4m3 pack reads a u16 around the last byte */ - c->ranges[1] = (WsRange){ (uintptr_t)B, (uintptr_t)B + p.b_bytes + 1 }; - c->ranges[2] = (WsRange){ (uintptr_t)ap, (uintptr_t)ap + p.ap_bytes }; - c->ranges[3] = (WsRange){ (uintptr_t)bp, (uintptr_t)bp + p.bp_bytes }; - c->ranges[4] = (WsRange){ (uintptr_t)C, (uintptr_t)(C + (uint64_t)M * N) }; - int rc = omega_gpu_gemm_drive(cfg, lay, M, N, K, (uintptr_t)A, (uintptr_t)B, (uintptr_t)ap, (uintptr_t)bp, (uintptr_t)C, sim_launch, c); - for (uint64_t i = 0; rc == 0 && i < (uint64_t)M * N; i++) if (f2u(C[i]) == 0x7fa00badu) rc = -9; - free(ap); free(bp); - return rc; -} - -static void sim_tier(void) { - char w[600], first[200]; - static const uint32_t sh[][3] = { { 1, 1, 1 }, { 1, 1, 17 }, { 16, 8, 16 }, { 17, 9, 33 }, { 64, 64, 64 }, { 65, 63, 100 }, - { 3, 130, 70 }, { 100, 3, 257 }, { 129, 65, 31 }, { 31, 200, 129 } }; - const size_t nsh = sizeof sh / sizeof sh[0]; - const OmegaGemmCfg cfgs[] = { { 0, 2, 4, 2, 2, 4, 0 }, { 0, 1, 1, 1, 1, 4, 0 }, { 0, 4, 1, 1, 4, 2, 0 } }; - void *A = malloc(300 * 300 * 2), *B = malloc(300 * 300 * 2); - float *C = malloc(300 * 300 * 4); - for (int t = 0; t < 2; t++) - for (size_t ci = 0; ci < sizeof cfgs / sizeof cfgs[0]; ci++) { - OmegaGemmCfg cfg = cfgs[ci]; cfg.type = (OmegaGpuGemmType)t; - SimCtx c; memset(&c, 0, sizeof c); - check(sim_build(&c, &cfg) == 0, "simulator: kernels built"); - uint64_t runs = 0, wrong = 0; - for (size_t s = 0; s < nsh; s++) - for (unsigned lay = 0; lay < 4; lay++) { - if (ci > 0 && lay != (unsigned)(s % 4)) continue; /* the other tile shapes: one layout per shape */ - const uint32_t M = sh[s][0], N = sh[s][1], K = sh[s][2]; - fill(cfg.type, A, (uint64_t)M * K, s * 4 + lay); fill(cfg.type, B, (uint64_t)K * N, s * 4 + lay + 1000); - c.order = (int)(s & 1u); - int rc = sim_gemm(&c, &cfg, lay, M, N, K, A, B, C); - uint64_t checked = 0, bad = rc == 0 ? compare(cfg.type, lay, M, N, K, A, B, C, &checked, first, sizeof first) : 1; - runs++; - if (rc != 0 || bad) { - wrong++; - snprintf(w, sizeof w, "sim %s rt %u ct %u wm %u wn %u, %ux%ux%u %s: rc %d, %" PRIu64 " wrong of %" PRIu64 " %s %s", tname(cfg.type), cfg.rt, - cfg.ct, cfg.wm, cfg.wn, M, N, K, lname(lay), rc, bad, checked, first, c.err); - check(0, w); - } - } - snprintf(w, sizeof w, "simulator %s rt %u ct %u wm %u wn %u: %" PRIu64 " multiplies, %" PRIu64 " wrong", tname(cfg.type), cfg.rt, cfg.ct, cfg.wm, cfg.wn, runs, wrong); - check(wrong == 0, w); - printf("%s\n", w); - sim_free(&c); - } - /* red checks: each mutant must change a result the real kernels get right */ - for (int t = 0; t < 2; t++) - for (int mut = 1; mut <= 3; mut++) { - OmegaGemmCfg cfg; omega_gpu_gemm_default_cfg((OmegaGpuGemmType)t, &cfg); cfg.mutant = mut; - SimCtx c; memset(&c, 0, sizeof c); - const uint32_t M = 65, N = 63, K = 100; - fill(cfg.type, A, M * K, 77); fill(cfg.type, B, K * N, 78); - int built = sim_build(&c, &cfg) == 0, rc = built ? sim_gemm(&c, &cfg, 0, M, N, K, A, B, C) : -1; - uint64_t checked = 0, bad = rc == 0 ? compare(cfg.type, 0, M, N, K, A, B, C, &checked, first, sizeof first) : 1; - snprintf(w, sizeof w, "simulator red check: %s mutant %d is caught (%" PRIu64 " wrong)", tname(cfg.type), mut, bad); - check(built && bad > 0, w); - printf("%s\n", w); - sim_free(&c); - } - free(A); free(B); free(C); -} - -/* ------------------------------------------------------------------ the chip */ - -static size_t mem_available(void) { - FILE *f = fopen("/proc/meminfo", "r"); - char line[256]; size_t kb = 0; - while (f && fgets(line, sizeof line, f)) if (sscanf(line, "MemAvailable: %zu kB", &kb) == 1) break; - if (f) fclose(f); - return kb * 1024u; -} - -static const double CEIL_TFLOPS[2] = { 115.36, 237.52 }; - -static void chip_one(OmegaGpuGemmType t, unsigned lay, uint32_t M, uint32_t N, uint32_t K, void *A, void *B, float *C) { - char w[600], first[200]; - fill(t, A, (uint64_t)M * K, (uint64_t)M * 3 + N * 5 + K * 7 + lay); - fill(t, B, (uint64_t)K * N, (uint64_t)M * 11 + N * 13 + K * 17 + lay); - OmegaGpuGemmInfo info; - int rc = omega_gpu_gemm(t, lay, M, N, K, A, B, C, &info); - uint64_t checked = 0, bad = rc == 0 ? compare(t, lay, M, N, K, A, B, C, &checked, first, sizeof first) : 1; - double flop = 2.0 * M * N * K, tf = info.main_ns ? flop / (double)info.main_ns / 1e3 : 0, tfp = info.main_ns ? flop / (double)(info.main_ns + info.pack_ns) / 1e3 : 0; - snprintf(w, sizeof w, "%s %ux%ux%u %s: %s, %" PRIu64 " checked, %" PRIu64 " wrong%s%s; kernel %.3f ms %.2f TFLOPS = %.4f of ceiling, with packs %.2f TFLOPS = %.4f%s%s", - tname(t), M, N, K, lname(lay), omega_gpu_gemm_rc_name(rc), checked, bad, bad && rc == 0 ? ", first " : "", bad && rc == 0 ? first : "", - info.main_ns / 1e6, tf, tf / CEIL_TFLOPS[t], tfp, tfp / CEIL_TFLOPS[t], rc ? ": " : "", rc ? omega_gpu_session_last_error() : ""); - check(rc == 0 && bad == 0, w); - if (rc == 0 && bad == 0) printf("ok: %s\n", w); -} - -static void chip_tier(int quick) { - char w[200]; - const size_t need = (size_t)8192 * 8192 * 2 * 2 + (size_t)8192 * 8192 * 4 + ((size_t)8 << 30); - if (!quick && mem_available() < need * 2) { printf("NOT_RUN: MemAvailable %zu MiB < %zu MiB\n", mem_available() >> 20, need * 2 >> 20); exit(2); } - const uint32_t big = quick ? 1024u : 8192u; - void *A = malloc((size_t)big * big * 2), *B = malloc((size_t)big * big * 2); - float *C = malloc((size_t)big * big * 4); - if (!A || !B || !C) { printf("NOT_RUN: host allocation\n"); exit(2); } - /* the shapes: per type and layout, the same list (26 each, 208 in all): edges, odd sizes, skinny, square up to 8192 */ - static const uint32_t sh[][3] = { - { 1, 1, 1 }, { 1, 8192, 1 }, { 8192, 1, 1 }, { 1, 1, 8192 }, { 7, 13, 29 }, { 16, 8, 16 }, { 33, 65, 127 }, { 100, 100, 100 }, - { 128, 64, 64 }, { 255, 257, 511 }, { 1000, 999, 1001 }, { 1, 4096, 4096 }, { 4096, 1, 4096 }, { 4096, 4096, 1 }, - { 17, 8192, 3000 }, { 8192, 17, 3000 }, { 1024, 1024, 1024 }, { 2048, 2048, 2048 }, { 4096, 4096, 4096 }, { 3000, 5000, 700 }, - { 8192, 8192, 64 }, { 64, 8192, 8192 }, { 8192, 64, 8192 }, { 6000, 7000, 8000 }, { 8191, 8191, 8191 }, { 8192, 8192, 8192 } }; - const size_t nsh = quick ? 12 : sizeof sh / sizeof sh[0]; - int before = g_failed, shapes = 0; - for (int t = 0; t < 2; t++) - for (unsigned lay = 0; lay < 4; lay++) - for (size_t s = 0; s < nsh; s++) { - if (quick && lay != (unsigned)(s % 4)) continue; - uint32_t M = sh[s][0] > big ? big : sh[s][0], N = sh[s][1] > big ? big : sh[s][1], K = sh[s][2] > big ? big : sh[s][2]; - chip_one((OmegaGpuGemmType)t, lay, M, N, K, A, B, C); - shapes++; - } - printf("%d shapes, both types, all four layouts: %s\n", shapes, g_failed == before ? "PASS" : "FAIL"); - for (int t = 0; t < 2; t++) - for (int mut = 1; mut <= 3; mut++) { - OmegaGemmCfg cfg; omega_gpu_gemm_default_cfg((OmegaGpuGemmType)t, &cfg); cfg.mutant = mut; - omega_gpu_gemm_test_set_cfg((OmegaGpuGemmType)t, &cfg); - const uint32_t M = 65, N = 63, K = 100; - fill((OmegaGpuGemmType)t, A, M * K, 77); fill((OmegaGpuGemmType)t, B, K * N, 78); - int rc = omega_gpu_gemm((OmegaGpuGemmType)t, 0, M, N, K, A, B, C, NULL); - char first[200]; uint64_t checked = 0, bad = rc == 0 ? compare((OmegaGpuGemmType)t, 0, M, N, K, A, B, C, &checked, first, sizeof first) : 1; - snprintf(w, sizeof w, "chip red check: %s mutant %d is caught (%s, %" PRIu64 " wrong)", tname((OmegaGpuGemmType)t), mut, omega_gpu_gemm_rc_name(rc), bad); - check(bad > 0, w); - printf("%s\n", w); - omega_gpu_gemm_test_set_cfg((OmegaGpuGemmType)t, NULL); - } - for (int t = 0; t < 2; t++) chip_one((OmegaGpuGemmType)t, 3, 65, 63, 100, A, B, C); /* right again after the red checks */ - omega_gpu_session_close(); /* the kernels go with the device (close hook); the next call builds them on a new one */ - printf("after the device closed and opened again:\n"); - for (int t = 0; t < 2; t++) chip_one((OmegaGpuGemmType)t, 0, 70, 33, 129, A, B, C); - free(A); free(B); free(C); -} - -int main(int argc, char **argv) { - const char *tier = "chip"; - int quick = 0; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) tier = "host"; - else if (!strcmp(argv[i], "--sim")) tier = "sim"; - else if (!strcmp(argv[i], "--quick")) quick = 1; - else { fprintf(stderr, "usage: %s [--host-only | --sim | --quick]\n", argv[0]); return 2; } - } - if (!strcmp(tier, "host")) host_only(); - else if (!strcmp(tier, "sim")) { host_only(); sim_tier(); } - else chip_tier(quick); - if (g_failed) printf("C3 gemm %s: FAIL (%d of %d)\n", tier, g_failed, g_checks); - else printf("C3 gemm %s: PASS (%d checks)\n", tier, g_checks); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_gpr_boundary_test.c b/tests/gpu_gpr_boundary_test.c deleted file mode 100644 index 052baca71..000000000 --- a/tests/gpu_gpr_boundary_test.c +++ /dev/null @@ -1,101 +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. - */ - -/* gpu_gpr_boundary_test: host-only audit of the declared-register rule (OWN-30B, 2026-10-13). - * Rule (omega_blackwell_codegen.h): declared = peak + 2 rounded up to a multiple of 8. A fp8 grouped GEMM kernel with - * peak 103 declared 104 (the old peak + 1 rule) hung the chip; the same program declared 112 ran. - * Checks: the helper for every peak; every launcher's own `declared` for every live kernel spec; the matmul family - * (declared by the session from the raw peak) is listed and must not be reachable at a boundary from a Qwen3-30B-A3B shape. */ -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_codegen_moe.h" -#include "omega_blackwell_codegen_bf16.h" -#include "omega_blackwell_codegen_router.h" -#include "omega_blackwell_codegen_attn.h" -#include "omega_blackwell_codegen_gemm.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_bf16_gemv_api.h" -#include "omega_gpu_router_api.h" -#include "omega_gpu_decode_attn_api.h" -#include "omega_gpu_fp8gemm_api.h" -#include -#include - -static int g_checks, g_failed; -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static BlackwellIRProgram g_prog; - -int main(void) { - for (uint32_t peak = 0; peak <= 126; peak++) { - uint32_t d = omega_bw_gpr_declared(peak); - CHECK(d >= peak + 2 && d % 8 == 0 && d - (peak + 2) < 8 && omega_bw_gpr_declared_ok(d, peak), "helper at peak %u gives %u", peak, d); - CHECK(!omega_bw_gpr_declared_ok(((peak + 1u + 7u) / 8u) * 8u, peak) || peak % 8 != 7, "old rule at peak %u must be refused", peak); - } - CHECK(!omega_bw_gpr_declared_ok(104, 103) && omega_bw_gpr_declared_ok(112, 103), "the 103 / 104 hang case is refused, 112 accepted"); - CHECK(!omega_bw_gpr_declared_ok(64, 64) && !omega_bw_gpr_declared_ok(72, 72) && omega_bw_gpr_declared_ok(72, 64), "peak 64 and 72 need 72 and 80 / 72"); - - /* fp8 GEMV: live shapes through the API's own shape / depth rules */ - struct { unsigned n, k, groups; } fs[] = { {4096,2048,1},{512,2048,1},{5120,2048,1},{2048,4096,1},{1536,2048,8},{2048,768,8},{1536,2048,1},{2048,768,1},{1u<<20,2048,1},{1u<<20,4096,1},{1u<<20,768,1} }; - for (unsigned i = 0; i < sizeof fs / sizeof *fs; i++) { - OmegaFp8GemvSpec s; memset(&s, 0, sizeof s); s.k = fs[i].k; - omega_gpu_fp8_shape_for(s.k, fs[i].n, &s.lane_bytes, &s.rows, &s.warps); - if (fs[i].groups > 1) s.warps = 32; - s.depth = omega_gpu_fp8_depth_for(&s, fs[i].n, fs[i].groups); - uint32_t peak = 0, decl = 0; - CHECK(omega_fp8_gemv_prog_stats(&s, NULL, &peak) == 0, "fp8 gemv %ux%u x%u builds", fs[i].n, fs[i].k, fs[i].groups); - (void)omega_gpu_fp8_kernel_fits(&s, &decl); - CHECK(omega_bw_gpr_declared_ok(decl, peak), "fp8 gemv %ux%u x%u: peak %u declared %u", fs[i].n, fs[i].k, fs[i].groups, peak, decl); - } - /* every buildable fp8 GEMV variant */ - { unsigned bad = 0, n = 0; - for (unsigned k = 256; k <= 8192; k += 256) for (unsigned lb = 8; lb <= 16; lb += 8) for (unsigned rows = 1; rows <= 8; rows *= 2) for (unsigned w = 1; w <= 32; w *= 2) for (unsigned dp = 0; dp <= 8; dp += dp ? dp : 1) { - OmegaFp8GemvSpec s = { .k = k, .lane_bytes = lb, .rows = rows, .warps = w, .depth = dp, .mutant = 0 }; uint32_t peak = 0, decl = 0; - if (omega_fp8_gemv_prog_stats(&s, NULL, &peak) != 0) continue; - n++; (void)omega_gpu_fp8_kernel_fits(&s, &decl); - if (!omega_bw_gpr_declared_ok(decl, peak) && decl != 0) bad++; - } - CHECK(bad == 0, "fp8 gemv sweep: %u of %u variants declared below peak + 2", bad, n); printf("fp8 gemv sweep: %u variants, %u below peak + 2\n", n, bad); } - /* bf16 GEMV */ - { unsigned ks[] = { 2048, 4096 }; for (unsigned i = 0; i < 2; i++) { OmegaBf16GemvSpec s; memset(&s, 0, sizeof s); s.k = ks[i]; uint32_t c; omega_gpu_bf16_shape_for(s.k, &s.rows, &s.warps, &s.depth, &c); - uint32_t peak = 0, decl = 0; CHECK(omega_bf16_gemv_prog_stats(&s, NULL, &peak) == 0, "bf16 k%u builds", ks[i]); (void)omega_gpu_bf16_kernel_fits(&s, &decl); - CHECK(omega_bw_gpr_declared_ok(decl, peak), "bf16 gemv k%u: peak %u declared %u", ks[i], peak, decl); } } - /* fp8 grouped GEMM (all shapes we launch) */ - { unsigned ks[] = { 2048, 768, 4096 }, mts[] = { 4, 8 }; for (unsigned i = 0; i < 3; i++) for (unsigned j = 0; j < 2; j++) { - OmegaFp8GemmSpec s = { ks[i], ks[i] % 512 ? 8u : 16u, mts[j], 16, 0, 0 }; uint32_t peak = 0, decl = 0; - CHECK(omega_fp8gemm_prog_stats(&s, NULL, &peak) == 0, "gemm k%u mt%u builds", ks[i], mts[j]); (void)omega_gpu_fp8gemm_kernel_fits(&s, &decl); - CHECK(omega_bw_gpr_declared_ok(decl, peak), "gemm k%u mt%u: peak %u declared %u", ks[i], mts[j], peak, decl); } } - /* router and decode attention: the launcher uses omega_bw_gpr_declared(peak) (static), so check the helper on the real peak */ - { OmegaRouterSpec s = { .warps = OMEGA_GPU_ROUTER_WARPS, .depth = OMEGA_GPU_ROUTER_DEPTH }; uint32_t peak = 0; - CHECK(omega_router_prog_stats(&s, NULL, &peak) == 0 && omega_bw_gpr_declared_ok(omega_bw_gpr_declared(peak), peak), "router peak %u", peak); printf("router peak %u -> declared %u\n", peak, omega_bw_gpr_declared(peak)); } - { OmegaDecodeAttnSpec s = { OMEGA_GPU_DATTN_DEPTH, 0 }; uint32_t peak = 0; - CHECK(omega_decode_attn_prog_stats(&s, NULL, &peak) == 0 && omega_bw_gpr_declared_ok(omega_bw_gpr_declared(peak), peak), "decode attn peak %u", peak); printf("decode attn peak %u -> declared %u\n", peak, omega_bw_gpr_declared(peak)); } - /* matmul / moe-window fragment kernels: declared by the session from the raw peak (max(64, peak rounded up to 8)). - * Boundary combinations are reported; the shapes of Qwen3-30B-A3B (n a multiple of 32) never select them. */ - { unsigned kps[] = { 768, 2048, 4096 }, nps[] = { 8, 128, 1536, 2048, 4096, 5120, 151936 }; unsigned built = 0, boundary = 0, model_boundary = 0; - for (unsigned a = 0; a < 3; a++) for (unsigned b = 0; b < 7; b++) for (unsigned rt = 1; rt <= 4; rt *= 2) for (unsigned ct = 1; ct <= 4; ct *= 2) { - OmegaMatMulSpec s; if (omega_matmul_spec_init(&s, 16, kps[a], nps[b], OMEGA_MATMUL_PRECISION_BF16) != 0) continue; - unsigned un = (rt > 1 || ct > 1) ? omega_matmul_frag_block_unroll(kps[a], rt, ct) : omega_matmul_frag_unroll(kps[a]); - memset(&g_prog, 0, sizeof g_prog); - int rc = (rt > 1 || ct > 1) ? omega_blackwell_codegen_matmul_frag_block_prog(&s, 48, un, rt, ct, 0, &g_prog) : omega_blackwell_codegen_matmul_frag_prog(&s, 48, un, 0, &g_prog); - if (rc) continue; - built++; - uint32_t pk = g_prog.regalloc.peak_gpr_usage, decl = pk > 64 ? ((pk + 7) / 8) * 8 : 64; - if (decl < pk + 2) { boundary++; unsigned mt = 4, nt = nps[b] / 8; uint32_t r, c; omega_matmul_frag_block_shape(mt, nt, &r, &c); if (r == rt && c == ct) model_boundary++; } - } - printf("matmul fragment kernels: %u built, %u at a boundary (session declares the raw peak), %u of those selected for a model shape\n", built, boundary, model_boundary); - CHECK(model_boundary == 0, "a Qwen3-30B shape reaches a matmul kernel declared below peak + 2"); } - printf("gpu_gpr_boundary_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_imadhi_rc_test.c b/tests/gpu_imadhi_rc_test.c deleted file mode 100644 index efdb4f1a5..000000000 --- a/tests/gpu_imadhi_rc_test.c +++ /dev/null @@ -1,170 +0,0 @@ -/* omega #492: IMAD.HI.U32 with a register Rc through one host warp simulator (host-only, no chip). - * - * The chip reads the Rc of IMAD.HI.U32 as a 64-bit register pair, not as one 32-bit word. - * Receipt (manufacturer's compiler, not a chip run): nvcc 13.0 for sm_121 emits, for - * hi32(a * b + c64) IMAD.HI.U32 R7, R7, R6, R2 with R2:R3 = c64 (no separate add), - * hi32(a * b + (u64)c32) UMOV UR5, URZ ; IMAD.HI.U32 R5, R7, R6, UR4 (upper half zeroed first), - * __umulhi(a, b) + c32 HFMA2 R4 = 0 ; R5 = c32 ; IMAD.HI.U32 R5, R8, R9, R4 (pair {lo 0, hi c32}), - * so the low word is Rc and the high word Rc+1, and every base is even. Listing and source: - * evidence/IMADHI-RC-ORACLE-nvcc13.0-20261016/. The first version of the trainer GEMM (PR #487) - * packed the odd-column B fragment with IMAD.HI.U32 O, W0, 0x10000, tw (meaning (W0 >> 16) + tw), - * passed the simulators (then hi32(Ra * Rb) + Rc) and gave wrong, non-repeatable odd columns on - * the chip (the stale upper register of the pair); commit 5b10b824 replaced it with SHF.R + IADD3. - * The simulators now model an even Rc as the pair and refuse an odd Rc (no evidence for it). - * The pair model is the compiler's reading, not chip-probed. - * - * This file is compiled once per simulator header: -DSIM_HEADER='"bw_warp_sim_k.h"' and so on - * (Makefile target test-gpu-imadhi-rc). The four headers share their static names, so one - * translation unit holds one simulator. - * - * Checks (each runs a straight-line kernel on one warp and stores one word per lane): - * 1. Rc = RZ: Rd = hi32(Ra * Rb) (the one live user today) - * 2. Rc = R6 (even): the encoder emits Rc byte 06 and Rd = hi32(Ra * Rb + R7:R6) - * 3. Rc = R7 (odd): refused with WS_E_IMADHI_RC naming the pc - * 4. PR #487 replay: the IMAD.HI.U32 odd-column pack must NOT match the emulation - * (W0 >> 16) + (W1 & 0xffff0000); it must give the pair value, for a stale upper register - * and for a zero one. The old 32-bit model matched the emulation here: the #487 false pass. - * 5. The SHF.R + IADD3 pack of commit 5b10b824 matches the emulation (control). - */ -#include -#include -#include -#include -#include "omega_blackwell_codegen.h" -#ifndef SIM_HEADER -#error "compile with -DSIM_HEADER='\"bw_warp_sim.h\"' (or _tc, _k, _pa)" -#endif -#include SIM_HEADER - -enum { V_OUT = 0, V_A, V_B, V_C, V_D, V_W1, V_MASK, V_T, NV }; -enum { CB_OUT = 0x380 }; - -static void ins(BlackwellIRProgram *p, BlackwellIROpcode op, int d, int a, int b, int c, uint32_t imm, uint8_t dsub) { - BlackwellIRInsn *i = &p->insns[p->count++]; - memset(i, 0, sizeof *i); - i->op = op; i->dst_vreg = d; i->src1_vreg = a; i->src2_vreg = b; i->src3_vreg = c; i->ureg = -1; i->imm = imm; i->dst_subreg = dsub; -} - -/* physical registers: out pair R2:R3, a R4, b R5, c pair R6:R7 (base = c_phys), d R8, w1 R10, mask R11, t R12 */ -static void regs(BlackwellIRProgram *p, int c_phys) { - const int phys[NV] = { 2, 4, 5, c_phys, 8, 10, 11, 12 }; - p->regalloc.num_vregs = NV; - for (int v = 0; v < NV; v++) p->regalloc.vreg_to_phys[v] = phys[v]; -} - -/* out[tid] = IMAD.HI.U32(a, b, rc ? {chi:clo} : RZ), Rc at physical c_phys */ -static void build(BlackwellIRProgram *p, uint32_t a, uint32_t b, uint32_t clo, uint32_t chi, int rc, int c_phys) { - memset(p, 0, sizeof *p); - ins(p, BW_IR_LDC64, V_OUT, -1, -1, -1, CB_OUT, 0); - ins(p, BW_IR_MOV_IMM, V_A, -1, -1, -1, a, 0); - ins(p, BW_IR_MOV_IMM, V_B, -1, -1, -1, b, 0); - ins(p, BW_IR_MOV_IMM, V_C, -1, -1, -1, clo, 0); - ins(p, BW_IR_MOV_IMM, V_C, -1, -1, -1, chi, 1); - ins(p, BW_IR_IMAD_HI_U32, V_D, V_A, V_B, rc ? V_C : -1, 0, 0); - ins(p, BW_IR_STG_E, -1, V_OUT, V_D, -1, 0, 0); - ins(p, BW_IR_EXIT, -1, -1, -1, -1, 0, 0); - regs(p, c_phys); -} - -/* The #487 odd-column B-fragment pack. tw = W1 & 0xffff0000 lands in R6; R7 holds whatever was there - * (stale). imadhi = 1: O = IMAD.HI.U32(W0, 0x10000, tw), the first tgemm version. - * imadhi = 0: O = SHF.R.U32.HI(W0, 16) + tw, the fix in 5b10b824. */ -static void build_pack(BlackwellIRProgram *p, uint32_t w0, uint32_t w1, uint32_t stale, int imadhi) { - memset(p, 0, sizeof *p); - ins(p, BW_IR_LDC64, V_OUT, -1, -1, -1, CB_OUT, 0); - ins(p, BW_IR_MOV_IMM, V_C, -1, -1, -1, stale, 1); /* an earlier value left in R7 */ - ins(p, BW_IR_MOV_IMM, V_A, -1, -1, -1, w0, 0); - ins(p, BW_IR_MOV_IMM, V_W1, -1, -1, -1, w1, 0); - ins(p, BW_IR_MOV_IMM, V_MASK, -1, -1, -1, 0xffff0000u, 0); - ins(p, BW_IR_LOP3_LUT, V_C, V_W1, V_MASK, -1, 0xc0u, 0); /* tw = W1 & mask (a & b = 0xf0 & 0xcc) */ - if (imadhi) { - ins(p, BW_IR_MOV_IMM, V_B, -1, -1, -1, 0x10000u, 0); - ins(p, BW_IR_IMAD_HI_U32, V_D, V_A, V_B, V_C, 0, 0); - } else { - ins(p, BW_IR_SHF_R, V_T, V_A, -1, -1, 16u, 0); - ins(p, BW_IR_IADD3, V_D, V_T, V_C, -1, 0, 0); - } - ins(p, BW_IR_STG_E, -1, V_OUT, V_D, -1, 0, 0); - ins(p, BW_IR_EXIT, -1, -1, -1, -1, 0, 0); - regs(p, 6); -} - -static int run(const BlackwellIRProgram *p, uint32_t *out, char *msg, size_t msglen) { - WsSim s; memset(&s, 0, sizeof s); - static uint8_t smem[1024]; - s.p = p; s.threads = 32; s.smem = smem; s.smem_bytes = sizeof smem; - uint64_t oa = (uintptr_t)out; - s.cbank[CB_OUT / 4] = (uint32_t)oa; s.cbank[CB_OUT / 4 + 1] = (uint32_t)(oa >> 32); - s.ranges[0] = (WsRange){ (uintptr_t)oa, (uintptr_t)oa + 4 }; s.nranges = 1; - int err = ws_run(&s, 1, 1); - snprintf(msg, msglen, "%s", s.msg); - return err ? s.err : 0; -} - -static uint32_t hi32_pair(uint32_t a, uint32_t b, uint32_t lo, uint32_t hi) { - return (uint32_t)((((uint64_t)a * b) + (((uint64_t)hi << 32) | lo)) >> 32); -} - -int main(void) { - const uint32_t A = 0xdeadbeefu, B = 0x10000u, CLO = 0x1234u, CHI = 0x5678u; /* B = 2^16 is the tgemm pack */ - const uint32_t hi_ab = (uint32_t)(((uint64_t)A * B) >> 32); - const uint32_t pair_model = hi32_pair(A, B, CLO, CHI); - int fails = 0; char msg[200]; uint32_t out; - BlackwellIRProgram *p = calloc(1, sizeof *p); - printf("sim %s: hi32(a*b) 0x%08x, nvcc pair model 0x%08x (chip probe pending), old 32-bit model 0x%08x\n", - SIM_HEADER, hi_ab, pair_model, hi_ab + CLO); - - /* 1. Rc = RZ: runs, Rd = hi32(a * b) */ - build(p, A, B, CLO, CHI, 0, 6); out = 0xffbadbadu; - int err = run(p, &out, msg, sizeof msg); - if (err || out != hi_ab) { fails++; printf("FAIL rc=RZ: err %d (%s) out 0x%08x want 0x%08x\n", err, msg, out, hi_ab); } - else printf("PASS rc=RZ: Rd = hi32(a*b) = 0x%08x\n", out); - - /* 2. Rc = R6 (even): the word carries Rc = R6 and the simulator reads the pair R7:R6 */ - build(p, A, B, CLO, CHI, 1, 6); - BlackwellIRInsn e = p->insns[5]; e.dst_vreg = 8; e.src1_vreg = 4; e.src2_vreg = 5; e.src3_vreg = 6; /* physical numbers for the encoder */ - uint32_t w[4] = { 0, 0, 0, 0 }; - if (omega_blackwell_encode_one(&e, w) != 0 || (w[0] & 0xffffu) != 0x7227u || (w[2] & 0xffu) != 6u) { - fails++; printf("FAIL encode: IMAD.HI.U32 R8, R4, R5, R6 -> %08x %08x %08x %08x (want opcode 7227, Rc byte 06)\n", w[0], w[1], w[2], w[3]); - } else printf("PASS encode: IMAD.HI.U32 R8, R4, R5, R6 carries Rc = R6 (the chip reads R7:R6)\n"); - out = 0xffbadbadu; - err = run(p, &out, msg, sizeof msg); - if (err || out != pair_model) { - fails++; printf("FAIL rc=R6: err %d (%s) out 0x%08x want pair 0x%08x (old 32-bit model 0x%08x)\n", err, msg, out, pair_model, hi_ab + CLO); - } else printf("PASS rc=R6: Rd = hi32(a*b + R7:R6) = 0x%08x\n", out); - - /* 3. Rc = R7 (odd): no evidence of what the chip reads, refused */ - build(p, A, B, CLO, CHI, 1, 7); out = 0xffbadbadu; - err = run(p, &out, msg, sizeof msg); - if (err != WS_E_IMADHI_RC) { - fails++; printf("FAIL rc=R7: simulator did not refuse an odd Rc (err %d%s%s), out 0x%08x\n", err, err ? " " : "", err ? msg : "", out); - } else if (!strstr(msg, "IMAD.HI.U32") || !strstr(msg, "at pc 5")) { - fails++; printf("FAIL rc=R7: refused but the message does not name the instruction and pc: %s\n", msg); - } else printf("PASS rc=R7: refused: %s\n", msg); - - /* 4 and 5. PR #487 replay: the odd-column pack, stale and zero upper register */ - static const struct { uint32_t w0, w1, stale; } pk[] = { - { 0x3f80bf80u, 0x40004040u, 0x3f803f80u }, /* bf16 pairs, a live value left in R7 */ - { 0xdeadbeefu, 0x5678cafeu, 0x00000000u }, /* zero upper: still wrong, tw lands in the low word (carry here) */ - { 0x12340001u, 0xabcd0000u, 0x00000000u }, /* zero upper, no carry */ - }; - for (unsigned k = 0; k < sizeof pk / sizeof pk[0]; k++) { - const uint32_t tw = pk[k].w1 & 0xffff0000u, emul = (pk[k].w0 >> 16) + tw; - const uint32_t chip = hi32_pair(pk[k].w0, 0x10000u, tw, pk[k].stale); - build_pack(p, pk[k].w0, pk[k].w1, pk[k].stale, 1); out = 0xffbadbadu; - err = run(p, &out, msg, sizeof msg); - if (err || out != chip || out == emul) { - fails++; - printf("FAIL pack %u IMAD.HI.U32: err %d (%s) out 0x%08x, want the pair value 0x%08x != emulation 0x%08x%s\n", k, err, msg, out, chip, emul, - (!err && out == emul) ? " (matches the emulation: the 32-bit Rc model of the #487 false pass)" : ""); - } else printf("PASS pack %u IMAD.HI.U32: odd column 0x%08x != emulation 0x%08x (stale R7 0x%08x), as on the chip in #487\n", k, out, emul, pk[k].stale); - build_pack(p, pk[k].w0, pk[k].w1, pk[k].stale, 0); out = 0xffbadbadu; - err = run(p, &out, msg, sizeof msg); - if (err || out != emul) { fails++; printf("FAIL pack %u SHF.R+IADD3: err %d (%s) out 0x%08x want 0x%08x\n", k, err, msg, out, emul); } - else printf("PASS pack %u SHF.R+IADD3: odd column 0x%08x = emulation\n", k, out); - } - - free(p); - printf("%s %s\n", fails ? "FAIL" : "PASS", SIM_HEADER); - return fails ? 1 : 0; -} diff --git a/tests/gpu_isolation_test.c b/tests/gpu_isolation_test.c deleted file mode 100644 index 786629e31..000000000 --- a/tests/gpu_isolation_test.c +++ /dev/null @@ -1,371 +0,0 @@ -/* gpu_isolation_test.c -- row C5 of docs/OMEGA.md: two processes on one GPU, and a never-ending kernel, on the GB10. - * - * --host-only codegen + encode of the work kernel, its mutant and the never-ending kernel; the simulator runs the work - * kernel exactly and catches the mutant; the never-ending kernel never reaches its exit in the simulator - * (no flag) the chip, under the GB10 lock, every part in its own child process: - * hang a work launch (values checked), then a never-ending kernel (one warp: count, branch back) with a - * HANG_MS timeout: the launch fails "timed out" and the process latches; red check: a work launch is - * refused "process latched"; omega_gpu_session_recover() closes the device (the RM client close destroys - * the channel and the grid on it); the work kernel uploaded again on the new device runs, values right. - * two two processes, each its own device, ROUNDS work launches with their own inputs: both all right. - * two-hang process 1 runs ROUNDS work launches while process 2 runs the hang part: process 1 all right (unharmed), - * process 2 recovers and is right too. - * Kernels from Omega's IR (omega_bw_em.h), our own sm_121 encoder; no CUDA. */ -#include "omega_gpu_cmdlist.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim.h" /* brings math.h, whose fadd() / ffma() would hide the emitter's */ -#define fadd em_fadd -#define ffma em_ffma -#include "omega_bw_em.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#define THREADS 128u -#define CTAS 32u -#define NEL (THREADS * CTAS) -#define ROUNDS 300 -#define HANG_MS 2000ull -#define POISON 0x7fa00badu -#define ARGS 5u /* in u64, out u64, tag f32 */ - -static int g_failed, g_checks; -static void check(int ok, const char *what) { - g_checks++; - if (!ok) g_failed++; - printf("[%d] %s: %s\n", (int)getpid(), ok ? "ok" : "FAIL", what); - fflush(stdout); -} -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -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; } - -/* ------------------------------------------------------------------ the kernels */ - -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); } - -/* work: out[gid] = in[gid] * 2 + tag (mutant 1: * 2 + tag + 1) */ -static int gen_work(Em *e, int mutant) { - int udesc = UV64(e), pin = V64(e), pout = V64(e), a64 = V64(e), tag = V(e), n = V(e), tid = V(e), cta = V(e), gid = V(e), two = V(e), v = V(e), one = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pin, 0x380); ldc64(e, pout, 0x388); ldc32(e, tag, 0x390); - s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - imadi(e, gid, cta, 0, THREADS, tid); - movi(e, n, NEL); movi(e, two, 0x40000000u); movi(e, one, 0x3f800000u); - isetp_ge_u32(e, gid, n); - { - Region r = skip_if_p0(e); - imadw(e, a64, gid, 4u, pin); ldg32(e, v, a64, udesc, 1); - ffma(e, v, v, two, 0, tag); - if (mutant == 1) fadd(e, v, v, one); - imadw(e, a64, gid, 4u, pout); stg(e, a64, 0, v, udesc); - region_end(e, r); - } - tail(e); - return e->err; -} - -/* never-ending: x = x + 1, branch back, for ever; the exit after the loop is never reached */ -static int gen_hang(Em *e) { - int x = V(e), one = V(e); - if (e->err) return -1; - movi(e, x, 0); movi(e, one, 1); - const int top = here(e); - loop_begin(e); - iadd(e, x, x, one); - bra(e, top); - loop_end(e); - tail(e); - return e->err; -} - -static int codegen(int hang, int mutant, BlackwellIRProgram *prog) { - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - if ((hang ? gen_hang(&em) : gen_work(&em, mutant)) != 0 || em.err || em.depth != 0) return -1; - return omega_bw_regalloc_solve(prog); -} - -static float input(unsigned i, unsigned seed) { return (float)((i * 2654435761u + seed * 40503u) % 100000u); } -static float expect(unsigned i, unsigned seed, float tag) { return input(i, seed) * 2.0f + tag; } - -/* ------------------------------------------------------------------ host */ - -static const char *g_dump; /* --dump-hang PATH: code bytes for the disassembler; PATH must not already exist */ - -static void host_only(void) { - char w[200]; - for (int k = 0; k < 3; k++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); - size_t need = 0; - int ok = p && codegen(k == 2, k == 1, p) == 0 && (need = omega_bw_program_code_bytes(p)) > 0; - void *code = ok ? calloc(1, need) : NULL; - OmegaBlackwellKernel kk; - ok = ok && code && omega_blackwell_kernel_encode_into(p, code, need, &kk) == 0 && kk.code_size == need; - if (ok && k == 2 && g_dump) { - /* Never truncate an existing file or follow a final-component symlink. - * A new dump is private even with a permissive caller umask. */ - int fd = open(g_dump, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); - FILE *f = fd >= 0 ? fdopen(fd, "wb") : NULL; - ok = f && fwrite(code, 1, need, f) == need; - if (f) { if (fclose(f) != 0) ok = 0; } - else if (fd >= 0) close(fd); - if (!ok) fprintf(stderr, "cannot write private kernel dump: %s (requires a new path)\n", g_dump); - } - snprintf(w, sizeof w, "codegen + encode: %s (%zu bytes)", k == 0 ? "work kernel" : k == 1 ? "work kernel mutant 1" : "never-ending kernel", need); - check(ok, w); - free(code); free(p); - } - static float in[NEL], out[NEL]; - WsRange rg[2] = { { (uintptr_t)in, (uintptr_t)(in + NEL) }, { (uintptr_t)out, (uintptr_t)(out + NEL) } }; - for (int mut = 0; mut < 2; mut++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); - static WsSim s; - memset(&s, 0, sizeof s); - for (unsigned i = 0; i < NEL; i++) { in[i] = input(i, 7); uint32_t pz = POISON; memcpy(&out[i], &pz, 4); } - int rc = !p || codegen(0, mut, p) != 0; - if (!rc) { - const uint64_t a = (uintptr_t)in, b = (uintptr_t)out; - s.p = p; s.threads = THREADS; - s.cbank[0x380 / 4] = (uint32_t)a; s.cbank[0x384 / 4] = (uint32_t)(a >> 32); - s.cbank[0x388 / 4] = (uint32_t)b; s.cbank[0x38c / 4] = (uint32_t)(b >> 32); s.cbank[0x390 / 4] = f2u(3.0f); - memcpy(s.ranges, rg, sizeof rg); s.nranges = 2; - rc = ws_run(&s, CTAS, 1); - } - unsigned bad = 0; - for (unsigned i = 0; i < NEL; i++) bad += f2u(out[i]) != f2u(expect(i, 7, 3.0f)); - snprintf(w, sizeof w, mut ? "simulator red check: work mutant caught (%u wrong)" : "simulator: work kernel exact on all %u elements", mut ? bad : NEL); - check(mut ? rc != 0 || bad > 0 : rc == 0 && bad == 0, w); - free(p); - } -} - -/* ------------------------------------------------------------------ the chip */ - -typedef struct { BlackwellIRProgram prog; OmegaGpuMem code; uint32_t gpr; } Kern; - -/* lock held */ -static int upload(Kern *k, int hang) { - memset(&k->code, 0, sizeof k->code); - if (codegen(hang, 0, &k->prog) != 0) return -1; - size_t need = omega_bw_program_code_bytes(&k->prog); - if (need == 0 || omega_gpu_session_alloc_code(need, &k->code) != 0) return -1; - OmegaBlackwellKernel kk; - if (omega_blackwell_kernel_encode_into(&k->prog, k->code.cpu, need, &kk) != 0 || omega_gpu_session_sync_to_gpu(&k->code) != 0) return -1; - k->gpr = omega_bw_gpr_declared(kk.gpr_count); - if (k->gpr < 64u) k->gpr = 64u; - return 0; -} - -static Kern g_work, g_hang; -static OmegaGpuMem g_buf; /* [in | out] */ - -/* lock held, device open: device buffer + work kernel */ -static int setup(void) { - if (!omega_gpu_session_open()) return -1; - if (omega_gpu_session_alloc(2u * NEL * 4u, &g_buf) != 0) return -1; - return upload(&g_work, 0); -} - -/* lock held: one work launch with inputs from seed; returns the count of wrong outputs, or -1 if the launch failed */ -static long work_once(unsigned seed, float tag, uint64_t *ns) { - float *in = g_buf.cpu, *out = in + NEL; - for (unsigned i = 0; i < NEL; i++) { in[i] = input(i, seed); uint32_t pz = POISON; memcpy(&out[i], &pz, 4); } - if (omega_gpu_session_sync_to_gpu(&g_buf) != 0) return -1; - uint32_t a[ARGS]; - const uint64_t vi = g_buf.va, vo = g_buf.va + NEL * 4u; - a[0] = (uint32_t)vi; a[1] = (uint32_t)(vi >> 32); a[2] = (uint32_t)vo; a[3] = (uint32_t)(vo >> 32); a[4] = f2u(tag); - OmegaGpuLaunch L = { .code_va = g_work.code.va, .gpr_count = g_work.gpr, .threads_x = THREADS, .threads_y = 1, .grid_x = CTAS, .grid_y = 1, - .num_elements = NEL, .args = a, .n_args = ARGS, .timeout_ms = 20000 }; - uint64_t t = 0; - if (omega_gpu_session_launch(&L, &t, NULL) != 0) return -1; - if (ns) *ns = t; - if (omega_gpu_session_sync_to_cpu(&g_buf) != 0) return -1; - long bad = 0; - for (unsigned i = 0; i < NEL; i++) bad += f2u(out[i]) != f2u(expect(i, seed, tag)); - return bad; -} - -/* Child processes talk to the parent and to each other over pipes (one byte per event, then raw timestamps). */ -static void say(int fd, char c) { if (fd >= 0 && write(fd, &c, 1) != 1) printf("[%d] pipe write failed\n", (int)getpid()); } -static int hear(int fd) { char c = 0; return read(fd, &c, 1) == 1 ? c : -1; } -static int heard_now(int fd) { /* non-blocking: 1 when a byte is waiting */ - fd_set s; FD_ZERO(&s); FD_SET(fd, &s); - struct timeval tv = { 0, 0 }; - return select(fd + 1, &s, NULL, NULL, &tv) == 1; -} - -/* the hang part; sig_fd (or -1) gets 'H' right before the never-ending launch and 'D' when the part is over */ -static int part_hang(int sig_fd) { - char w[300]; - omega_gpu_session_lock(); - if (setup() != 0) { check(0, "hang part: device, buffer, work kernel"); printf(" %s\n", omega_gpu_session_last_error()); omega_gpu_session_unlock(); say(sig_fd, 'D'); return 1; } - uint64_t ns0 = 0; - long bad = work_once(11, 1.0f, &ns0); - snprintf(w, sizeof w, "hang part: a work launch before the hang is right (%ld wrong, %.3f ms)", bad, ns0 / 1e6); - check(bad == 0, w); - check(upload(&g_hang, 1) == 0, "hang part: never-ending kernel uploaded"); - OmegaGpuCmdList *old_list = NULL; /* made on the device the recovery throws away */ - omega_gpu_session_unlock(); - check(omega_gpu_cmdlist_create(2, &old_list) == 0, "hang part: a command list made before the hang"); - omega_gpu_session_lock(); - uint32_t dummy = 0; /* the kernel reads no argument; a launch needs at least one word */ - OmegaGpuLaunch H = { .code_va = g_hang.code.va, .gpr_count = g_hang.gpr, .threads_x = 32, .threads_y = 1, .grid_x = 1, .grid_y = 1, - .num_elements = 32, .args = &dummy, .n_args = 1, .timeout_ms = HANG_MS }; - say(sig_fd, 'H'); - const uint64_t t0 = now_ns(); - int rc = omega_gpu_session_launch(&H, NULL, NULL); - const double waited = (now_ns() - t0) / 1e6; - snprintf(w, sizeof w, "the never-ending kernel times out after %.0f ms (rc %d: %s), the process latches", waited, rc, omega_gpu_session_last_error()); - check(rc != 0 && strstr(omega_gpu_session_last_error(), "timed out") && omega_gpu_session_is_blocked() && waited >= (double)HANG_MS * 0.9, w); - bad = work_once(12, 1.0f, NULL); - snprintf(w, sizeof w, "red check: while latched a work launch is refused (%s)", omega_gpu_session_last_error()); - check(bad == -1 && strstr(omega_gpu_session_last_error(), "process latched") != NULL, w); - omega_gpu_session_unlock(); - - const uint64_t r0 = now_ns(); - rc = omega_gpu_session_recover(); - const double rec_ms = (now_ns() - r0) / 1e6; - /* the driver's clean close of the RM client is what says the channel, and the grid on it, are gone: a teardown fault - * would keep the session latched (tests/test_omega_gpu_session_platform.c RECOVER_TEARDOWN_FAULT_STAYS_LATCHED) */ - snprintf(w, sizeof w, "recover: the device closed with no driver teardown fault in %.1f ms (rc %d %s)", rec_ms, rc, rc ? omega_gpu_session_last_error() : ""); - check(rc == 0 && !omega_gpu_session_is_blocked() && omega_gpu_session_recoveries() == 1, w); - memset(&g_buf, 0, sizeof g_buf); /* handles of the old device are gone */ - omega_gpu_session_lock(); - if (setup() != 0) { check(0, "after recover: new device, buffer, work kernel"); printf(" %s\n", omega_gpu_session_last_error()); omega_gpu_session_unlock(); say(sig_fd, 'D'); return 1; } - uint64_t ns1 = 0, ns2 = 0; - bad = work_once(13, 4.0f, &ns1); - long bad2 = work_once(14, 5.0f, &ns2); - snprintf(w, sizeof w, "after recover, same process: work launches right (%ld, %ld wrong; %.3f, %.3f ms vs %.3f ms before the hang), device opens %u", - bad, bad2, ns1 / 1e6, ns2 / 1e6, ns0 / 1e6, omega_gpu_session_open_count()); - check(bad == 0 && bad2 == 0, w); - { - uint32_t a1 = 0; - OmegaGpuLaunch L = { .code_va = g_work.code.va, .gpr_count = g_work.gpr, .threads_x = 32, .threads_y = 1, .grid_x = 1, .grid_y = 1, - .num_elements = 32, .args = &a1, .n_args = 1 }; - int refused = old_list && omega_gpu_cmdlist_add(old_list, &L) == -1 && strstr(omega_gpu_session_last_error(), "before a session recovery") != NULL; - snprintf(w, sizeof w, "a command list from before the recovery is refused (%s)", omega_gpu_session_last_error()); - check(refused, w); - } - omega_gpu_session_unlock(); - omega_gpu_cmdlist_free(old_list); - omega_gpu_session_close(); - say(sig_fd, 'D'); - return g_failed ? 1 : 0; -} - -typedef struct { uint64_t start, end; uint32_t launches, during; } Span; - -/* work launches with own inputs. ready_fd gets 'R' once set up; then it waits for one byte on go_fd. It runs for at - * least RUN_MS and ROUNDS launches; with a hang_fd it waits for 'H' first and keeps going until 'D', counting the - * launches made in between. Writes its Span to span_fd. */ -#define RUN_MS 3000ull -static int part_rounds(unsigned seed_base, const char *who, int ready_fd, int go_fd, int hang_fd, int span_fd) { - char w[300]; - omega_gpu_session_lock(); - if (setup() != 0) { check(0, "rounds: device, buffer, work kernel"); printf(" %s\n", omega_gpu_session_last_error()); omega_gpu_session_unlock(); say(ready_fd, 'X'); return 1; } - say(ready_fd, 'R'); - if (go_fd >= 0) (void)hear(go_fd); - if (hang_fd >= 0 && hear(hang_fd) != 'H') { check(0, "rounds: the hang process never started its hang"); omega_gpu_session_unlock(); return 1; } - Span sp = { now_ns(), 0, 0, 0 }; - long wrong_total = 0; int failed = 0, hang_live = hang_fd >= 0; - uint64_t ns, worst = 0; - for (unsigned r = 0;; r++) { - if (hang_live && heard_now(hang_fd)) { (void)hear(hang_fd); hang_live = 0; } - if (!hang_live && r >= ROUNDS && now_ns() - sp.start >= RUN_MS * 1000000ull) break; - long bad = work_once(seed_base + r, (float)(r % 7), &ns); - if (bad < 0) { failed++; printf(" [%d] launch %u: %s\n", (int)getpid(), r, omega_gpu_session_last_error()); break; } - wrong_total += bad; - sp.launches++; - if (hang_live) sp.during++; - if (ns > worst) worst = ns; - } - sp.end = now_ns(); - snprintf(w, sizeof w, "%s: %u work launches over %.0f ms, own inputs: %ld wrong values, %d failed launches, slowest %.3f ms%s", - who, sp.launches, (sp.end - sp.start) / 1e6, wrong_total, failed, worst / 1e6, ""); - check(wrong_total == 0 && failed == 0, w); - if (hang_fd >= 0) { - snprintf(w, sizeof w, "%s: %u of its launches ran while the other process's kernel was hung or being torn down", who, sp.during); - check(sp.during > 0, w); - } - if (span_fd >= 0 && write(span_fd, &sp, sizeof sp) != (ssize_t)sizeof sp) printf("[%d] span write failed\n", (int)getpid()); - omega_gpu_session_unlock(); - omega_gpu_session_close(); - return g_failed ? 1 : 0; -} - -static int reap(pid_t p) { int st = 0; if (p < 0 || waitpid(p, &st, 0) != p) return -1; return WIFEXITED(st) ? WEXITSTATUS(st) : 128 + (WIFSIGNALED(st) ? WTERMSIG(st) : 0); } -static int pipe_or_die(int fd[2]) { if (pipe(fd) != 0) { printf("NOT_RUN: pipe\n"); exit(2); } return 0; } - -static void chip_tier(int values_only) { - char w[300]; - fflush(stdout); - if (!values_only) { - pid_t h = fork(); - if (h == 0) _exit(part_hang(-1)); - int rc = reap(h); - snprintf(w, sizeof w, "C5 hang: never-ending kernel timed out, recovered, correct launch in the same process (child exit %d)", rc); - check(rc == 0, w); - } - - /* two processes, started together after both are set up, each running RUN_MS: their spans must overlap */ - int ready[2], go[2], span[2]; - pipe_or_die(ready); pipe_or_die(go); pipe_or_die(span); - pid_t a = fork(); - if (a == 0) _exit(part_rounds(1000, "process 1", ready[1], go[0], -1, span[1])); - pid_t b = fork(); - if (b == 0) _exit(part_rounds(5000, "process 2", ready[1], go[0], -1, span[1])); - int r1 = hear(ready[0]), r2 = hear(ready[0]); - say(go[1], 'G'); say(go[1], 'G'); - int ra = reap(a), rb = reap(b); - Span s1 = {0}, s2 = {0}; - int got = read(span[0], &s1, sizeof s1) == (ssize_t)sizeof s1 && read(span[0], &s2, sizeof s2) == (ssize_t)sizeof s2; - const uint64_t lo = s1.start > s2.start ? s1.start : s2.start, hi = s1.end < s2.end ? s1.end : s2.end; - const double overlap_ms = got && hi > lo ? (hi - lo) / 1e6 : 0.0; - snprintf(w, sizeof w, "C5 two processes on one GPU: both right (ready %c %c, exits %d, %d), running side by side for %.0f ms", - r1 > 0 ? r1 : '?', r2 > 0 ? r2 : '?', ra, rb, overlap_ms); - check(ra == 0 && rb == 0 && overlap_ms >= (double)RUN_MS * 0.5, w); - close(ready[0]); close(ready[1]); close(go[0]); close(go[1]); close(span[0]); close(span[1]); - - if (values_only) { - puts("C5 recovery: NOT_RUN (values-only; hang needs a separate reservation)"); - return; - } - - /* a hang beside a working process: process 1 starts when process 2's hang begins and runs until process 2 is done */ - int sig[2], rdy[2]; - pipe_or_die(sig); pipe_or_die(rdy); - a = fork(); - if (a == 0) { close(sig[1]); _exit(part_rounds(9000, "process 1 beside a hang", rdy[1], -1, sig[0], -1)); } - b = fork(); - if (b == 0) { close(sig[0]); _exit(part_hang(sig[1])); } - close(sig[0]); close(sig[1]); - ra = reap(a); rb = reap(b); - snprintf(w, sizeof w, "C5 a hang in process 2 leaves process 1 unharmed, and process 2 recovers (exits %d, %d)", ra, rb); - check(ra == 0 && rb == 0, w); - close(rdy[0]); close(rdy[1]); -} - -int main(int argc, char **argv) { - const char *tier = "chip"; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) tier = "host"; - else if (!strcmp(argv[i], "--values-only")) tier = "values"; - else if (!strcmp(argv[i], "--dump-hang") && i + 1 < argc) { tier = "host"; g_dump = argv[++i]; } - else { fprintf(stderr, "usage: %s [--host-only | --values-only] [--dump-hang PATH]\n", argv[0]); return 2; } - } - setvbuf(stdout, NULL, _IOLBF, 0); - if (!strcmp(tier, "host")) host_only(); - else chip_tier(!strcmp(tier, "values")); - if (g_failed) printf("C5 isolation %s: FAIL (%d of %d)\n", tier, g_failed, g_checks); - else printf("C5 isolation %s: PASS (%d checks)\n", tier, g_checks); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_l2_reuse_test.c b/tests/gpu_l2_reuse_test.c deleted file mode 100644 index 169be18b7..000000000 --- a/tests/gpu_l2_reuse_test.c +++ /dev/null @@ -1,136 +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. - */ - -/* gpu_l2_reuse_test: does an FP8 GEMV that re-reads weights another launch just read run faster? (OWN-30B W-L2d, 2026-10-14) - * - * Question behind it: a decode token has ~120 us per layer where DRAM is idle (attention at pos 300 ~73 us latency-bound, - * router ~25 us, glue ~18 us; W-L2 timeline). If the GB10 L2 keeps a GEMV's weights between two launches, an independent - * prefetch launch overlapped with those latency-bound launches (no barrier between them: no data dependency) could pull the - * NEXT GEMV's weights into L2, and that GEMV would then run from L2. This test measures only the precondition: the same - * tensor read twice in one list, [GEMV(T) -> y][WAIT_FOR_IDLE][GEMV(T) -> y], GPU timestamps around each launch. - * One variable per pass: the weight memory policy (GPU-uncached = every session buffer today, vs GPU-cached, - * omega_gpu_fp8_set_weight_cache). Sizes n x 2048 for n = 1024 .. 16384 (2 .. 33.5 MB) bracket the unknown L2 size. - * Barrier WFI_ONLY (no shader-cache invalidate; the chip study r1 showed the form does not change the time). - * Every rep: y poisoned first, y bit-identical to the one-launch-at-a-time reference. - * Negative control: the uncached pass (no reuse is possible through an uncached mapping, nvos.h:1117) must show warm ~= cold. - * Chip only: caller holds the GB10 lock. Output "L2 cached=.. n=.. MB=.. cold_us=.. warm_us=.. ratio=..", --out receipt JSON. */ -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_cmdlist.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include - -static int g_checks, g_failed; -#define EV_N 32768u -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } else { printf("ok: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint64_t median(uint64_t *v, uint32_t n) { qsort(v, n, sizeof *v, cmp_u64); return v[n / 2]; } - -int main(int argc, char **argv) { - uint32_t reps = 10, k = 2048; const char *out_path = NULL; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else { printf("usage: %s [--reps R] [--out receipt.json]\n", argv[0]); return 2; } - } - if (reps == 0 || reps > 64) reps = 10; - static const uint32_t ns[] = { 1024, 2048, 4096, 8192, 12288, 16384 }; - const uint32_t nmax = 16384; - omega_gpu_fp8_set_depth(1, 0); - (void)omega_gpu_session_set_spin_us(2000); - uint8_t *w = malloc((size_t)nmax * k); uint16_t *sc = malloc((size_t)(nmax / 128) * (k / 128) * 2); float *x = malloc((size_t)k * 4), *ref = malloc((size_t)nmax * 4); - uint32_t st = 2026; - for (size_t i = 0; i < (size_t)nmax * k; i++) { uint8_t b = (uint8_t)(lcg(&st) >> 24); w[i] = (b & 0x7F) == 0x7F ? 0 : b; } - for (size_t i = 0; i < (size_t)(nmax / 128) * (k / 128); i++) sc[i] = 0x3F80; - for (uint32_t i = 0; i < k; i++) x[i] = (float)(lcg(&st) >> 8) / 16777216.0f * 2.0f - 1.0f; - - OmegaGpuCmdList *cl = NULL; - if (omega_gpu_cmdlist_create(8, &cl) != 0) { printf("cmdlist create: %s\n", omega_gpu_session_last_error()); return 1; } - OmegaGpuMem tab, xd, yd, ye; - omega_gpu_session_lock(); - int arc = omega_gpu_session_alloc(32u, &tab) | omega_gpu_session_alloc((size_t)k * 4u, &xd) | omega_gpu_session_alloc((size_t)nmax * 4u, &yd) | omega_gpu_session_alloc((size_t)EV_N * 4u, &ye); - omega_gpu_session_unlock(); - if (arc != 0) { printf("alloc: %s\n", omega_gpu_session_last_error()); return 1; } - omega_fp8_pack_x_f32(x, k, xd.cpu); - if (omega_gpu_session_sync_to_gpu(&xd) != 0) return 1; - - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out) fprintf(out, "{\"test\":\"OMEGA_GPU_L2_REUSE\",\"k\":%u,\"reps\":%u,\"points\":[", k, reps); - int first_pt = 1; double ratio_unc_max = 0, ratio_cached_min = 1e9; - /* evictor: a GPU-cached EV_N x k tensor (67 MB) read first in every list, so "cold" is cold even if L2 keeps lines across submits */ - OmegaGpuFp8Tensor *ev = NULL; - { uint8_t *we = malloc((size_t)EV_N * k); uint16_t *se = malloc((size_t)(EV_N / 128) * (k / 128) * 2); - for (size_t i = 0; i < (size_t)EV_N * k; i++) { uint8_t b = (uint8_t)(lcg(&st) >> 24); we[i] = (b & 0x7F) == 0x7F ? 0 : b; } - for (size_t i = 0; i < (size_t)(EV_N / 128) * (k / 128); i++) se[i] = 0x3F80; - omega_gpu_fp8_set_weight_cache(1); - int erc = omega_gpu_fp8_tensor_upload(1, EV_N, k, we, se, &ev); - free(we); free(se); - float *yev = malloc((size_t)EV_N * 4); if (erc == OMEGA_GPU_FP8_OK) erc = omega_gpu_fp8_gemv_f32(ev, 0, x, yev, NULL); free(yev); /* kernel built + warm */ - uint64_t *tw = tab.cpu; - if (erc != OMEGA_GPU_FP8_OK || omega_gpu_fp8_tensor_entry(ev, 0, &tw[2], &tw[3]) != 0) { printf("evictor upload: %s\n", omega_gpu_fp8_last_error()); return 1; } } - for (int pass = 0; pass < 3; pass++) { const int cached = pass > 0, evict = pass != 1; /* (uncached, evict) (cached, no evict) (cached, evict) */ - omega_gpu_fp8_set_weight_cache(cached); - for (size_t ni = 0; ni < sizeof ns / sizeof ns[0]; ni++) { - const uint32_t n = ns[ni]; const uint64_t bytes = (uint64_t)n * k + (uint64_t)(n / 128) * (k / 128) * 4u; - OmegaGpuFp8Tensor *t = NULL; - int rc = omega_gpu_fp8_tensor_upload(1, n, k, w, sc, &t); - if (rc == OMEGA_GPU_FP8_OK) rc = omega_gpu_fp8_gemv_f32(t, 0, x, ref, NULL); - if (rc != OMEGA_GPU_FP8_OK) { printf("upload/reference n=%u cached=%d: %s (%s)\n", n, cached, omega_gpu_fp8_rc_name(rc), omega_gpu_fp8_last_error()); g_failed++; omega_gpu_fp8_tensor_free(t); break; } - uint64_t *tabw = tab.cpu; - if (omega_gpu_fp8_tensor_entry(t, 0, &tabw[0], &tabw[1]) != 0 || omega_gpu_session_sync_to_gpu(&tab) != 0) { g_failed++; omega_gpu_fp8_tensor_free(t); break; } - uint64_t colds[64], warms[64]; int identical = 1, ok = 1; - for (uint32_t r = 0; r < reps && ok; r++) { - float *y = yd.cpu; for (uint32_t i = 0; i < n; i++) y[i] = -999.0f; - if (omega_gpu_session_sync_to_gpu(&yd) != 0) { ok = 0; break; } - omega_gpu_session_lock(); - omega_gpu_cmdlist_reset(cl); - if (evict && omega_gpu_fp8_gemv_grouped_record(cl, ev, 1, tab.va + 16u, xd.va, 1, ye.va) != 0) { printf("record evictor: %s\n", omega_gpu_fp8_last_error()); ok = 0; } - for (int j = 0; j < 2 && ok; j++) - if (omega_gpu_fp8_gemv_grouped_record(cl, t, 1, tab.va, xd.va, 1, yd.va) != 0) { printf("record: %s\n", omega_gpu_fp8_last_error()); ok = 0; } - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = OMEGA_GPU_CMDLIST_BARRIER_WFI_ONLY; o.stamps = 1; - OmegaGpuCmdListStats s; memset(&s, 0, sizeof s); - uint64_t sts[4]; int cnt = -1; const int want = evict ? 4 : 3; - if (ok && omega_gpu_cmdlist_submit(cl, &o, &s) != 0) { printf("submit: %s\n", omega_gpu_session_last_error()); ok = 0; } - if (ok) cnt = omega_gpu_cmdlist_stamps(cl, sts, 4); - omega_gpu_session_unlock(); - if (!ok || cnt != want) { ok = 0; break; } - colds[r] = sts[want - 2] - sts[want - 3]; warms[r] = sts[want - 1] - sts[want - 2]; - if (omega_gpu_session_sync_to_cpu(&yd) != 0) { ok = 0; break; } - if (memcmp(y, ref, (size_t)n * 4) != 0) identical = 0; - } - CHECK(ok && identical, "cached=%d evict=%d n=%u: %u reps ran, y bit-identical to the reference on every rep", cached, evict, n, reps); - if (ok) { - const double c = median(colds, reps) / 1e3, wm = median(warms, reps) / 1e3, ratio = wm / c; - printf("L2 cached=%d evict=%d n=%-5u MB=%.1f cold_us=%.1f warm_us=%.1f ratio=%.3f cold_GB/s=%.1f warm_GB/s=%.1f\n", cached, evict, n, bytes / 1e6, c, wm, ratio, bytes / (c * 1e3), bytes / (wm * 1e3)); - if (cached && evict) { if (ratio < ratio_cached_min) ratio_cached_min = ratio; } else if (!cached && ratio > ratio_unc_max) ratio_unc_max = ratio; - if (out) { fprintf(out, "%s{\"cached\":%d,\"evict\":%d,\"n\":%u,\"bytes\":%" PRIu64 ",\"cold_ns\":%" PRIu64 ",\"warm_ns\":%" PRIu64 ",\"identical\":%d}", first_pt ? "" : ",", cached, evict, n, bytes, median(colds, reps), median(warms, reps), identical); first_pt = 0; } - } - omega_gpu_fp8_tensor_free(t); - if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); g_failed++; break; } - } - } - omega_gpu_fp8_set_weight_cache(0); - printf("SUMMARY uncached max warm/cold %.3f, cached min warm/cold %.3f\n", ratio_unc_max, ratio_cached_min); - if (out) { fprintf(out, "],\"uncached_ratio_max\":%.4f,\"cached_ratio_min\":%.4f,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", ratio_unc_max, ratio_cached_min, g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - printf("gpu_l2_reuse_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - omega_gpu_fp8_tensor_free(ev); - omega_gpu_cmdlist_free(cl); - free(w); free(sc); free(x); free(ref); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_l2_stale_test.c b/tests/gpu_l2_stale_test.c deleted file mode 100644 index fa4ab3c8d..000000000 --- a/tests/gpu_l2_stale_test.c +++ /dev/null @@ -1,122 +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. - */ - -/* gpu_l2_stale_test: omega #457 regression test (chip). After the host rewrites a GPU-cached (CPU_WRITE | GPU_READ) buffer that the GPU has - * already read, does the next launch read the old bytes from GPU L2? - * - * Real path only: omega_gpu_fp8_tensor_upload (memcpy into the CPU mapping + omega_gpu_session_sync_to_gpu, which is - * a dsb sy and nothing else) and omega_gpu_fp8_gemv_f32 (one launch, C3 tail, output read back from uncached memory). - * One variable per process: --cached 0|1 (omega_gpu_fp8_set_weight_cache). --cached 0 is the negative control - * (uncached mapping: nvos.h:1117-1118 says only the cached case is not coherent with CPU mappings). - * - * Tensor: 1 expert x N=256 x K=2048 e4m3 (512 KB), scales bf16 1.0, x = 1.0. - * A = every weight +1.0 (0x38) -> every y = +2048. B = every weight -1.0 (0xB8) -> every y = -2048. - * Camera: a row's 2048 bytes are 16 lines of 128 B; a stale line adds +128 instead of -128, so - * stale_lines(row) = (y + 2048) / 256, exact in f32. Any other y is printed as UNDECODED. - * Modes: - * rewrite upload A, GEMV (GPU reads A), host memcpy B into the SAME buffer + sync_to_gpu, then GEMV x reps. - * realloc upload A, GEMV, free A, upload B (fresh buffer: VA printed, same-VA noted), then GEMV x reps. - * The first GEMV on A must read +2048 on every row: that shows the decode can see A's bytes at all. - * Exit 0 = FRESH, 1 = STALE_READ or API failure, 2 = usage. Red receipt (unfixed platform, omega 710d438c): rewrite - * --cached 1 read 4096 of 4096 lines stale on every launch, 5/5; --cached 0 FRESH 5/5. */ -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include - -/* Copied verbatim from omega src/omega_gpu_fp8_api.c:20-24 (frozen candidate, not modified). Checked at run time - * against the public omega_gpu_fp8_tensor_entry() VAs; a mismatch aborts. */ -struct OmegaGpuFp8Tensor { - uint32_t experts, n, k; - OmegaGpuMem w; /* experts * n * k e4m3 bytes, row-major */ - OmegaGpuMem s; /* experts * (n/128) * (k/128) f32 (scale * 2^56) */ -}; - -#define N 256u -#define K 2048u - -static int snap(const char *site, const float *y, float expect) { - uint32_t stale_rows = 0, stale_lines = 0, undecoded = 0; float lo = y[0], hi = y[0]; - for (uint32_t r = 0; r < N; r++) { - if (y[r] < lo) lo = y[r]; - if (y[r] > hi) hi = y[r]; - if (expect > 0) { if (y[r] != 2048.0f) undecoded++; continue; } - float s = (y[r] + 2048.0f) / 256.0f; - if (s != (float)(int)s || s < 0 || s > 16) { undecoded++; continue; } - if (s > 0) { stale_rows++; stale_lines += (uint32_t)s; } - } - printf("SNAP site=%s expected=%.0f rows=%u stale_rows=%u stale_lines=%u of %u undecoded=%u y_min=%.1f y_max=%.1f\n", - site, expect, N, stale_rows, stale_lines, N * 16u, undecoded, lo, hi); - if (undecoded) printf("SNAP site=%s y_row0=%.3f interpretation=UNDECODED\n", site, y[0]); - return expect > 0 ? (undecoded ? -1 : 0) : (int)(stale_lines + undecoded); -} - -int main(int argc, char **argv) { - const char *mode = NULL; int cached = -1; uint32_t reps = 3; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--mode") == 0 && i + 1 < argc) mode = argv[++i]; - else if (strcmp(argv[i], "--cached") == 0 && i + 1 < argc) cached = atoi(argv[++i]); - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else { printf("usage: %s --mode rewrite|realloc --cached 0|1 [--reps R]\n", argv[0]); return 2; } - } - if (!mode || (strcmp(mode, "rewrite") && strcmp(mode, "realloc")) || (cached != 0 && cached != 1) || reps == 0 || reps > 64) { - printf("usage: %s --mode rewrite|realloc --cached 0|1 [--reps R]\n", argv[0]); return 2; - } - (void)omega_gpu_session_set_spin_us(2000); - omega_gpu_fp8_set_weight_cache(cached); - printf("RUN mode=%s cached=%d weight_cache_now=%d n=%u k=%u reps=%u\n", mode, cached, omega_gpu_fp8_weight_cache(), N, K, reps); - - uint8_t *wa = malloc((size_t)N * K), *wb = malloc((size_t)N * K); - uint16_t sc[(N / 128) * (K / 128)]; float x[K], y[N]; - memset(wa, 0x38, (size_t)N * K); memset(wb, 0xB8, (size_t)N * K); - for (size_t i = 0; i < sizeof sc / sizeof sc[0]; i++) sc[i] = 0x3F80; - for (uint32_t i = 0; i < K; i++) x[i] = 1.0f; - - OmegaGpuFp8Tensor *t = NULL; - int rc = omega_gpu_fp8_tensor_upload(1, N, K, wa, sc, &t); - if (rc != OMEGA_GPU_FP8_OK) { printf("FAIL upload A: %s\n", omega_gpu_fp8_last_error()); return 1; } - uint64_t wva = 0, sva = 0; - if (omega_gpu_fp8_tensor_entry(t, 0, &wva, &sva) != 0 || wva != t->w.va || sva != t->s.va || !t->w.cpu) { - printf("FAIL mirror struct does not match omega (entry w_va 0x%" PRIx64 " vs mirror 0x%" PRIx64 ")\n", wva, t->w.va); return 1; - } - const uint64_t va_a = t->w.va; - memset(y, 0, sizeof y); - if ((rc = omega_gpu_fp8_gemv_f32(t, 0, x, y, NULL)) != OMEGA_GPU_FP8_OK) { printf("FAIL gemv A: %s\n", omega_gpu_fp8_last_error()); return 1; } - if (snap("gemv-A", y, 2048.0f) != 0) { printf("STALE verdict=INVALID reason=first read of A is not +2048 (decode cannot see A)\n"); return 1; } - - if (strcmp(mode, "rewrite") == 0) { - memcpy(t->w.cpu, wb, (size_t)N * K); /* what omega_gpu_fp8_tensor_upload does, on the same buffer */ - if (omega_gpu_session_sync_to_gpu(&t->w) != 0) { printf("FAIL sync: %s\n", omega_gpu_session_last_error()); return 1; } - printf("HOST rewrote w (va 0x%" PRIx64 ") with B and synced\n", va_a); - } else { - omega_gpu_fp8_tensor_free(t); t = NULL; - if ((rc = omega_gpu_fp8_tensor_upload(1, N, K, wb, sc, &t)) != OMEGA_GPU_FP8_OK) { printf("FAIL upload B: %s\n", omega_gpu_fp8_last_error()); return 1; } - printf("HOST freed A (va 0x%" PRIx64 "), uploaded B at va 0x%" PRIx64 " same_va=%s phys=UNKNOWN reason=no physical address in the API\n", - va_a, t->w.va, t->w.va == va_a ? "yes" : "no"); - } - uint32_t total = 0; - for (uint32_t r = 0; r < reps; r++) { - char site[32]; snprintf(site, sizeof site, "gemv-B-%u", r + 1); - for (uint32_t i = 0; i < N; i++) y[i] = 12345.0f; - if ((rc = omega_gpu_fp8_gemv_f32(t, 0, x, y, NULL)) != OMEGA_GPU_FP8_OK) { printf("FAIL gemv B: %s\n", omega_gpu_fp8_last_error()); return 1; } - total += (uint32_t)snap(site, y, -2048.0f); - } - printf("STALE mode=%s cached=%d stale_or_undecoded_lines_total=%u verdict=%s\n", mode, cached, total, total ? "STALE_READ" : "FRESH"); - omega_gpu_fp8_tensor_free(t); free(wa); free(wb); - return total ? 1 : 0; -} diff --git a/tests/gpu_launch_cost_test.c b/tests/gpu_launch_cost_test.c deleted file mode 100644 index 07811cdc3..000000000 --- a/tests/gpu_launch_cost_test.c +++ /dev/null @@ -1,170 +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. - */ - -/* gpu_launch_cost_test: what does one FP8 GEMV launch cost inside a command list beyond its bytes? (OWN-30B W-L2c, 2026-10-14) - * - * The same weight bytes (n x k e4m3, default 16384 x 2048 = 33.5 MB) are split into m = 1, 2, 4, 8, 16 launches (m tensors of - * n/m rows, independent: distinct rows, distinct y), recorded into ONE command list and timed with the GPU timestamps - * (omega_gpu_cmdlist stamps). T(m) - T(1) over (m - 1) is the per-launch fixed cost with the WAIT_FOR_IDLE barrier between - * launches. Variant (one variable): the same lists with OMEGA_GPU_CMDLIST_BARRIER_NONE (legal here: the launches share no - * data), which tells whether the barrier or the kernel's own ramp/tail is the cost. Every rep checks y bit-identical to the - * session's one-launch-at-a-time result for every tensor (poisoned first). Negative control: a dropped launch (skip_launch) - * must be named by submit. - * Chip only (no host mode): caller holds the GB10 lock. Output: lines "COST m=.. barrier=.. span_us=.. per_launch_us=.. GB/s=.." - * and the fixed-cost lines; --out writes the receipt JSON. */ -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_cmdlist.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } else { printf("ok: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint64_t median(uint64_t *v, uint32_t n) { qsort(v, n, sizeof *v, cmp_u64); return v[n / 2]; } - -#define MAX_M 16 -typedef struct { OmegaGpuFp8Tensor *t[MAX_M]; float *ref; uint32_t m, rows; } Split; - -static int make_split(Split *s, uint32_t m, uint32_t n, uint32_t k, const uint8_t *w, const uint16_t *sc, const float *x) { - memset(s, 0, sizeof *s); - s->m = m; s->rows = n / m; s->ref = malloc((size_t)n * 4); - for (uint32_t i = 0; i < m; i++) { - int rc = omega_gpu_fp8_tensor_upload(1, s->rows, k, w + (size_t)i * s->rows * k, sc + (size_t)i * (s->rows / 128) * (k / 128), &s->t[i]); - if (rc != OMEGA_GPU_FP8_OK) { printf("upload m=%u i=%u: %s (%s)\n", m, i, omega_gpu_fp8_rc_name(rc), omega_gpu_fp8_last_error()); return -1; } - rc = omega_gpu_fp8_gemv_f32(s->t[i], 0, x, s->ref + (size_t)i * s->rows, NULL); /* warm-up (kernel cached) + the reference */ - if (rc != OMEGA_GPU_FP8_OK) { printf("reference m=%u i=%u: %s (%s)\n", m, i, omega_gpu_fp8_rc_name(rc), omega_gpu_fp8_last_error()); return -1; } - } - return 0; -} -static void free_split(Split *s) { for (uint32_t i = 0; i < s->m; i++) omega_gpu_fp8_tensor_free(s->t[i]); free(s->ref); } - -/* one list of m launches, submitted reps times; medians of the stamp span and of the host-seen elapsed; y checked every rep */ -static int time_split(Split *s, OmegaGpuCmdList *cl, OmegaGpuMem *tab, OmegaGpuMem *xd, OmegaGpuMem *yd, OmegaGpuCmdListBarrier bar, - uint32_t reps, uint64_t *span_med, uint64_t *elapsed_med, uint64_t *first_med, int *identical) { - const uint32_t m = s->m, n = s->rows * m; - uint64_t *spans = malloc(reps * 8), *els = malloc(reps * 8), *firsts = malloc(reps * 8); - uint64_t *tabw = tab->cpu; - for (uint32_t i = 0; i < m; i++) if (omega_gpu_fp8_tensor_entry(s->t[i], 0, &tabw[2 * i], &tabw[2 * i + 1]) != 0) return -1; - if (omega_gpu_session_sync_to_gpu(tab) != 0) return -1; - *identical = 1; - int rc = 0; - for (uint32_t r = 0; r < reps && rc == 0; r++) { - float *y = yd->cpu; for (uint32_t i = 0; i < n; i++) y[i] = -999.0f; - if (omega_gpu_session_sync_to_gpu(yd) != 0) { rc = -1; break; } - omega_gpu_session_lock(); - omega_gpu_cmdlist_reset(cl); - for (uint32_t i = 0; i < m && rc == 0; i++) - if (omega_gpu_fp8_gemv_grouped_record(cl, s->t[i], 1, tab->va + 16u * i, xd->va, 1, yd->va + (uint64_t)i * s->rows * 4u) != 0) { printf("record m=%u i=%u: %s\n", m, i, omega_gpu_fp8_last_error()); rc = -1; } - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); - o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = bar; o.stamps = 1; - OmegaGpuCmdListStats st; memset(&st, 0, sizeof st); - if (rc == 0 && omega_gpu_cmdlist_submit(cl, &o, &st) != 0) { printf("submit m=%u barrier=%s: %s\n", m, omega_gpu_cmdlist_barrier_name(bar), omega_gpu_session_last_error()); rc = -1; } - uint64_t stamps[MAX_M + 1]; const int none = bar == OMEGA_GPU_CMDLIST_BARRIER_NONE; int cnt = rc == 0 && !none ? omega_gpu_cmdlist_stamps(cl, stamps, MAX_M + 1) : -1; /* barrier none: only the first and last stamp exist, so the GPU span is not readable; elapsed (host wall, ~5 us above span) is the comparable figure */ - omega_gpu_session_unlock(); - if (rc == 0 && !none && cnt != (int)m + 1) { printf("stamps m=%u: %d\n", m, cnt); rc = -1; } - if (rc != 0) break; - els[r] = st.elapsed_ns; spans[r] = none ? 0 : stamps[m] - stamps[0]; firsts[r] = none ? 0 : stamps[1] - stamps[0]; - if (omega_gpu_session_sync_to_cpu(yd) != 0) { rc = -1; break; } - if (memcmp(y, s->ref, (size_t)n * 4) != 0) *identical = 0; - } - if (rc == 0) { *span_med = median(spans, reps); *elapsed_med = median(els, reps); *first_med = median(firsts, reps); } - free(spans); free(els); free(firsts); - return rc; -} - -int main(int argc, char **argv) { - uint32_t reps = 20, n = 16384, k = 2048; const char *out_path = NULL; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--n") == 0 && i + 1 < argc) n = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--k") == 0 && i + 1 < argc) k = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else { printf("usage: %s [--reps N] [--n ROWS] [--k K] [--out receipt.json]\n", argv[0]); return 2; } - } - if (n % (128u * MAX_M) || k % 512u) { printf("n must be a multiple of %u and k of 512\n", 128u * MAX_M); return 2; } - omega_gpu_fp8_set_depth(1, 0); /* one kernel (the step-by-step production kernel) for every split: the row count must not change the kernel */ - (void)omega_gpu_session_set_spin_us(2000); - /* data: random e4m3 bytes without the NaN codes, scales 1.0, x in [-1, 1) */ - uint8_t *w = malloc((size_t)n * k); uint16_t *sc = malloc((size_t)(n / 128) * (k / 128) * 2); float *x = malloc((size_t)k * 4); - uint32_t st = 2026; - for (size_t i = 0; i < (size_t)n * k; i++) { uint8_t b = (uint8_t)(lcg(&st) >> 24); w[i] = (b & 0x7F) == 0x7F ? 0 : b; } - for (size_t i = 0; i < (size_t)(n / 128) * (k / 128); i++) sc[i] = 0x3F80; /* bf16 1.0 */ - for (uint32_t i = 0; i < k; i++) x[i] = (float)(lcg(&st) >> 8) / 16777216.0f * 2.0f - 1.0f; - const uint64_t bytes = (uint64_t)n * k + (uint64_t)(n / 128) * (k / 128) * 4u; - - OmegaGpuCmdList *cl = NULL; - if (omega_gpu_cmdlist_create(64, &cl) != 0) { printf("cmdlist create: %s\n", omega_gpu_session_last_error()); return 1; } - OmegaGpuMem tab, xd, yd; - omega_gpu_session_lock(); - int arc = omega_gpu_session_alloc(16u * MAX_M, &tab) | omega_gpu_session_alloc((size_t)k * 4u, &xd) | omega_gpu_session_alloc((size_t)n * 4u, &yd); - omega_gpu_session_unlock(); - if (arc != 0) { printf("alloc: %s\n", omega_gpu_session_last_error()); return 1; } - omega_fp8_pack_x_f32(x, k, xd.cpu); - if (omega_gpu_session_sync_to_gpu(&xd) != 0) return 1; - - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out) fprintf(out, "{\"test\":\"OMEGA_GPU_LAUNCH_COST\",\"n\":%u,\"k\":%u,\"bytes\":%" PRIu64 ",\"reps\":%u,\"points\":[", n, k, bytes, reps); - static const uint32_t ms[] = { 1, 2, 4, 8, 16 }; - double t1[8] = { 0 }; int first_pt = 1; - static const OmegaGpuCmdListBarrier bars[] = { OMEGA_GPU_CMDLIST_BARRIER_WFI, OMEGA_GPU_CMDLIST_BARRIER_WFI_ONLY, OMEGA_GPU_CMDLIST_BARRIER_WFI_DATA, OMEGA_GPU_CMDLIST_BARRIER_FLUSH_DATA, OMEGA_GPU_CMDLIST_BARRIER_NONE, OMEGA_GPU_CMDLIST_BARRIER_WFI }; - for (unsigned bi = 0; bi < sizeof bars / sizeof bars[0]; bi++) { const OmegaGpuCmdListBarrier bar = bars[bi]; const char *bn = omega_gpu_cmdlist_barrier_name(bar); /* WFI first and last: drift control */ - for (size_t mi = 0; mi < sizeof ms / sizeof ms[0]; mi++) { - Split s; - if (make_split(&s, ms[mi], n, k, w, sc, x) != 0) { printf("split m=%u failed\n", ms[mi]); g_failed++; free_split(&s); break; } - uint64_t span = 0, el = 0, first = 0; int identical = 0; - int rc = time_split(&s, cl, &tab, &xd, &yd, bar, reps, &span, &el, &first, &identical); - CHECK(rc == 0 && identical, "m=%u barrier=%s: %u reps ran, y bit-identical to the one-launch-at-a-time reference on every rep", ms[mi], bn, reps); - if (rc == 0) { - double span_us = span / 1e3, el_us = el / 1e3, per = el_us / ms[mi], gbs = (double)bytes / (double)el; /* elapsed-based: comparable across barrier modes */ - if (ms[mi] == 1) t1[bi] = el_us; - double fixed = ms[mi] > 1 ? (el_us - t1[bi]) / (ms[mi] - 1) : 0.0; - printf("COST m=%-2u barrier=%-14s span_us=%.1f per_launch_us=%.1f first_launch_us=%.1f elapsed_us=%.1f GB/s=%.1f fixed_per_extra_launch_us=%.2f\n", - ms[mi], bn, span_us, per, first / 1e3, el / 1e3, gbs, fixed); - if (out) { fprintf(out, "%s{\"m\":%u,\"barrier\":\"%s\",\"span_ns\":%" PRIu64 ",\"first_launch_ns\":%" PRIu64 ",\"elapsed_ns\":%" PRIu64 ",\"gbps\":%.2f,\"fixed_per_extra_launch_us\":%.2f,\"identical\":%d}", - first_pt ? "" : ",", ms[mi], bn, span, first, el, gbs, fixed, identical); first_pt = 0; } - } - free_split(&s); - if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); break; } - } - } - /* negative control: a dropped launch is named */ - { - Split s; int rc = make_split(&s, 2, n, k, w, sc, x); - if (rc == 0) { - uint64_t *tabw = tab.cpu; for (uint32_t i = 0; i < 2; i++) omega_gpu_fp8_tensor_entry(s.t[i], 0, &tabw[2 * i], &tabw[2 * i + 1]); - omega_gpu_session_sync_to_gpu(&tab); - omega_gpu_session_lock(); - omega_gpu_cmdlist_reset(cl); - for (uint32_t i = 0; i < 2; i++) omega_gpu_fp8_gemv_grouped_record(cl, s.t[i], 1, tab.va + 16u * i, xd.va, 1, yd.va + (uint64_t)i * s.rows * 4u); - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = OMEGA_GPU_CMDLIST_BARRIER_WFI; o.skip_launch = 2; - OmegaGpuCmdListStats st2; memset(&st2, 0, sizeof st2); - int src = omega_gpu_cmdlist_submit(cl, &o, &st2); - omega_gpu_session_unlock(); - CHECK(src != 0 && st2.first_missing == 1, "negative control: dropped launch 1 named by submit (rc %d, first_missing %d)", src, st2.first_missing); - } else g_failed++; - free_split(&s); - } - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - omega_gpu_session_lock(); omega_gpu_session_free(&tab); omega_gpu_session_free(&xd); omega_gpu_session_free(&yd); omega_gpu_session_unlock(); - omega_gpu_cmdlist_free(cl); - omega_gpu_session_close(); - printf("gpu_launch_cost_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_lmhead_fp8_study.c b/tests/gpu_lmhead_fp8_study.c deleted file mode 100644 index 4e81bf429..000000000 --- a/tests/gpu_lmhead_fp8_study.c +++ /dev/null @@ -1,134 +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. - */ - -/* - * gpu_lmhead_fp8_study: report-only study (OWN-30B, 2026-10-13). Does an FP8-quantised lm_head pick the same next token - * as the bf16 lm_head? Loads the real lm_head.weight (bf16 [151936][2048]) and model.norm.weight from the checkpoint - * dir, quantises the weight to e4m3 in 128x128 blocks (scale = amax / 448, rounded to bf16, the checkpoint's - * weight_scale_inv convention; round-to-nearest-even into e4m3, saturating), then runs both GEMVs on the chip - * (bf16 streaming kernel and the FP8 kernel) on N random hidden states and compares the argmax. Nothing is switched. - * usage: gpu_lmhead_fp8_study MODEL_DIR [--states N] [--seed S] [--out report.txt] - */ -#include "omega_gpu_bf16_gemv_api.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include -#include -#include - -#define V 151936u -#define H 2048u -#define DATA0 89616ull /* 8 + header length of shard 4 */ -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float urand(uint32_t *s) { return (float)(lcg(s) >> 8) / 16777216.0f; } -static float gauss(uint32_t *s) { float a = 0; for (int i = 0; i < 12; i++) a += urand(s); return a - 6.0f; } -static float bf16_f32(uint16_t b) { uint32_t x = (uint32_t)b << 16; float f; memcpy(&f, &x, 4); return f; } -static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -/* positive e4m3 values by code 0..126 (127 is NaN): increasing */ -static float pos[127]; -static uint8_t enc_e4m3(float v) { /* nearest, ties to the even code, saturating at 448 */ - uint8_t sign = v < 0 ? 0x80 : 0; float a = fabsf(v); - int lo = 0, hi = 126; - if (a >= pos[126]) return sign | 126; - while (hi - lo > 1) { int m = (lo + hi) / 2; if (pos[m] <= a) lo = m; else hi = m; } - float dl = a - pos[lo], dh = pos[hi] - a; - int c = dl < dh ? lo : dh < dl ? hi : ((lo & 1) ? hi : lo); - return sign | (uint8_t)c; -} - -int main(int argc, char **argv) { - if (argc < 2) { printf("usage: %s MODEL_DIR [--states N] [--seed S] [--out file]\n", argv[0]); return 2; } - uint32_t states = 1000, seed = 20261013; const char *out_path = NULL; - for (int i = 2; i < argc; i++) { - if (!strcmp(argv[i], "--states") && i + 1 < argc) states = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--seed") && i + 1 < argc) seed = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--out") && i + 1 < argc) out_path = argv[++i]; - } - for (int c = 0; c < 127; c++) { int e = c >> 3, m = c & 7; pos[c] = e == 0 ? (float)m * (1.0f / 512.0f) : ldexpf(1.0f + m / 8.0f, e - 7); } - char path[600]; snprintf(path, sizeof path, "%s/model-00004-of-00004.safetensors", argv[1]); - FILE *f = fopen(path, "rb"); if (!f) { printf("cannot open %s\n", path); return 1; } - uint16_t *w = malloc((size_t)V * H * 2), nw[H]; - fseeko(f, (off_t)DATA0, SEEK_SET); - if (fread(w, 2, (size_t)V * H, f) != (size_t)V * H) { printf("short read lm_head\n"); return 1; } - fseeko(f, (off_t)(DATA0 + 622405248ull), SEEK_SET); - if (fread(nw, 2, H, f) != H) { printf("short read norm\n"); return 1; } - fclose(f); - /* quantise */ - uint8_t *q = malloc((size_t)V * H); uint16_t *sc = malloc((size_t)(V / 128) * (H / 128) * 2); - double sq_err = 0, sq_w = 0; - for (uint32_t bi = 0; bi < V / 128; bi++) for (uint32_t bj = 0; bj < H / 128; bj++) { - float amax = 0; - for (uint32_t r = 0; r < 128; r++) for (uint32_t c = 0; c < 128; c++) { float a = fabsf(bf16_f32(w[(size_t)(bi * 128 + r) * H + bj * 128 + c])); if (a > amax) amax = a; } - uint16_t sb = bf16_rne(amax > 0 ? amax / 448.0f : 1.0f); float s = bf16_f32(sb); - sc[bi * (H / 128) + bj] = sb; - for (uint32_t r = 0; r < 128; r++) for (uint32_t c = 0; c < 128; c++) { - size_t idx = (size_t)(bi * 128 + r) * H + bj * 128 + c; float wv = bf16_f32(w[idx]); - uint8_t e = enc_e4m3(wv / s); q[idx] = e; - float d = (e & 0x80 ? -1.0f : 1.0f) * pos[e & 0x7f] * s; sq_err += (double)(d - wv) * (d - wv); sq_w += (double)wv * wv; - } - } - printf("quantised lm_head: weight rms error %.4f of weight rms (block-scaled e4m3)\n", sqrt(sq_err / sq_w)); - OmegaGpuBf16Tensor *tb = NULL; OmegaGpuFp8Tensor *tf = NULL; - int r1 = omega_gpu_bf16_tensor_upload(V, H, w, &tb), r2 = omega_gpu_fp8_tensor_upload(1, V, H, q, sc, &tf); - printf("uploads: bf16 %s, fp8 %s\n", omega_gpu_bf16_rc_name(r1), omega_gpu_fp8_rc_name(r2)); - if (r1 || r2) return 1; - (void)omega_gpu_session_set_spin_us(2000); - float *x = malloc(H * 4), *yb = malloc(V * 4), *yf = malloc(V * 4); - uint32_t s = seed, agree = 0, top5_in = 0, fails = 0; - uint64_t *tb_ns = malloc(states * 8), *tf_ns = malloc(states * 8); - double maxrel = 0; - uint32_t bucket[4] = { 0, 0, 0, 0 }, bucket_dis[4] = { 0, 0, 0, 0 }; /* margin <0.05, <0.2, <1, >=1 (bf16 logit gap top1-top2) */ - for (uint32_t it = 0; it < states; it++) { - for (uint32_t i = 0; i < H; i++) x[i] = gauss(&s) * bf16_f32(nw[i]); - OmegaGpuBf16Info ib; OmegaGpuFp8Info jf; - if (omega_gpu_bf16_gemv_f32(tb, x, yb, &ib) || omega_gpu_fp8_gemv_f32(tf, 0, x, yf, &jf)) { fails++; printf("state %u: chip call failed (%s)\n", it, omega_gpu_bf16_last_error()); break; } - tb_ns[it] = ib.elapsed_ns; tf_ns[it] = jf.elapsed_ns; - uint32_t ab = 0, af = 0; float m2 = -1e30f; - for (uint32_t v = 1; v < V; v++) { if (yb[v] > yb[ab]) ab = v; if (yf[v] > yf[af]) af = v; } - for (uint32_t v = 0; v < V; v++) if (v != ab && yb[v] > m2) m2 = yb[v]; - double margin = yb[ab] - m2; - int ok = ab == af; agree += ok; - /* is the bf16 argmax inside the fp8 top 5? */ - uint32_t better = 0; for (uint32_t v = 0; v < V; v++) if (yf[v] > yf[ab]) better++; - top5_in += better < 5; - int b = margin < 0.05 ? 0 : margin < 0.2 ? 1 : margin < 1.0 ? 2 : 3; bucket[b]++; if (!ok) { bucket_dis[b]++; } - double num = 0, den = 0; for (uint32_t v = 0; v < V; v++) { double d = (double)yf[v] - yb[v]; num += d * d; den += (double)yb[v] * yb[v]; } - double rel = sqrt(num / den); if (rel > maxrel) maxrel = rel; - if (it == 0) printf("state 0: bf16 argmax %u (%.3f), fp8 argmax %u (%.3f), margin %.4f, logit rms rel diff %.4f\n", ab, yb[ab], af, yf[af], margin, rel); - } - uint32_t n = states - fails; - qsort(tb_ns, n, 8, cmp_u64); qsort(tf_ns, n, 8, cmp_u64); - char rep[2000]; - snprintf(rep, sizeof rep, - "lm_head fp8 vs bf16 argmax study (real lm_head.weight, %u random hidden states = gaussian x model.norm.weight, seed %u)\n" - "argmax agreement: %u of %u (%.2f%%); bf16 argmax within fp8 top-5: %u of %u\n" - "logit rms relative difference, worst over states: %.4f\n" - "agreement by bf16 top1-top2 logit gap: <0.05: %u/%u disagree, <0.2: %u/%u, <1: %u/%u, >=1: %u/%u\n" - "chip medians: bf16 kernel %.1f us, fp8 kernel %.1f us\n", - n, seed, agree, n, 100.0 * agree / (n ? n : 1), top5_in, n, maxrel, - bucket_dis[0], bucket[0], bucket_dis[1], bucket[1], bucket_dis[2], bucket[2], bucket_dis[3], bucket[3], - n ? tb_ns[n / 2] / 1e3 : 0.0, n ? tf_ns[n / 2] / 1e3 : 0.0); - printf("%s", rep); - if (out_path) { FILE *o = fopen(out_path, "w"); if (o) { fputs(rep, o); fclose(o); } } - omega_gpu_bf16_tensor_free(tb); omega_gpu_fp8_tensor_free(tf); - omega_gpu_session_close(); - return fails ? 1 : 0; -} diff --git a/tests/gpu_matmul_api_test.c b/tests/gpu_matmul_api_test.c deleted file mode 100644 index 3f3034f12..000000000 --- a/tests/gpu_matmul_api_test.c +++ /dev/null @@ -1,708 +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. - */ - -/* gpu_matmul_api_test: FB-1 cut 1 / 1b gate for omega_gpu_matmul_api. - * - * ./gpu_matmul_api_test --host-only argument and limit refusals, codegen only, no chip - * ./gpu_matmul_api_test --out receipt.json chip sweep over shapes, JSON receipt - * ./gpu_matmul_api_test --timing --out r.json resident GEMV timing (median of 100 calls) + parity - * ./gpu_matmul_api_test --update --out r.json tensor_update_* in place vs a fresh upload, and its timing (R3) - * ./gpu_matmul_api_test --mutant --out r.json wrong kernel (last K step dropped) must FAIL parity; - * exit 0 when every shape caught it ("mutant killed") - * ./gpu_matmul_api_test --cta-budget N ... run with a different CTA budget (I42 experiment) - * ./gpu_matmul_api_test --spin-us N ... marker-wait spin window for every launch (omega#328) - * ./gpu_matmul_api_test --unroll N ... force the fragment kernel unroll (omega #328 experiment) - * ./gpu_matmul_api_test --stages --out r.json omega #473 stage profile (resident, bf16 and f32 rows, median of 7) - * - * Shapes come from OMEGA_GPU_MATMUL_SHAPES ("m,k,n;m,k,n;..."), default below. - * Pass rule per shape: rc OK, parity verified by the API oracle, end-to-end error < 1e-5 relative to - * the accumulation scale (bf16 inputs against a double reference; only accumulation order and the - * chip's f32 accumulator differ), second call hits the kernel cache and agrees bit for bit. - */ -#include "omega_gpu_matmul_api.h" -#include "omega_gpu_session.h" -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_matmul.h" -#include -#include -#include -#include -#include -#include - -/* round a float to bf16 and back, as the API does on the way in */ -static float bf16r(float f) { uint16_t h = omega_fp32_to_bf16(f); uint32_t u = (uint32_t)h << 16; float o; memcpy(&o, &u, 4); return o; } - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -/* cut-1 list unchanged, then the cut-1b Llama shapes (hidden 2048, ffn 8192, vocab 128256) */ -static const char *DEFAULT_SHAPES = - "16,16,16;32,32,32;64,64,64;128,128,128;256,256,256;512,512,512;" - "1,1024,1024;1,256,1024;16,1024,256;8,1024,8;" - "1024,16,128;192,16,192;512,16,64;256,16,256;128,16,512;" - "1,2048,8192;1,8192,2048;1,2048,128256"; -static const char *MUTANT_SHAPES = "16,32,16;1,2048,8192;64,64,64;1,1024,1024"; -static const char *TIMING_SHAPES = "1,2048,8192;1,8192,2048"; -/* omega #473 training shapes */ -static const char *STAGE_SHAPES = "8192,768,2304;8192,768,768;8192,768,3072;8192,3072,768;1024,768,50304"; - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } - -static void fill(float *a, size_t n, uint32_t *seed) { for (size_t i = 0; i < n; i++) a[i] = ((float)(lcg(seed) % 2001) - 1000.0f) / 1000.0f; } - -/* end-to-end: full-K product on the host from the same bf16-rounded inputs, in double; error relative - * to the accumulation scale (sum of |terms|), not to a result that may cancel to near zero */ -static double e2e_max_rel(uint32_t m, uint32_t k, uint32_t n, const float *a, const float *b, const float *c, size_t *bad) { - double worst = 0.0; size_t nbad = 0; - for (size_t i = 0; i < m; i++) for (size_t j = 0; j < n; j++) { - double acc = 0.0, scale = 0.0; - for (size_t t = 0; t < k; t++) { double p = (double)bf16r(a[i * k + t]) * (double)bf16r(b[t * n + j]); acc += p; scale += fabs(p); } - double rel = fabs(acc - (double)c[i * n + j]) / (scale > 1e-6 ? scale : 1e-6); - if (rel > worst) worst = rel; - if (rel >= 1e-5) nbad++; - } - if (bad) *bad = nbad; - return worst; -} - -/* omega #328 fragment-major kernel, host only. The unpack below is written from the PTX ISA - * table for mma.m16n8k16 (.bf16 A: a0,a1 row g cols 2t,2t+1; a2,a3 row g+8; a4,a5 row g cols - * 2t+8,2t+9; a6,a7 row g+8. B: b0,b1 rows 2t,2t+1 col g; b2,b3 rows 2t+8,2t+9; g = lane>>2, - * t = lane&3), independently of the packers: pack then unpack must give the matrix back. */ -/* Result sentinels: one poison word per 16 x 8 fragment tile that holds a real output word, inside the - * tile's real rows and columns; the scan counts exactly the survivors. */ -static void sentinel_host_checks(void) { - static const uint32_t shapes[][2] = { { 1u, 24576u }, { 1u, 4096u }, { 16u, 151936u }, { 128u, 24576u }, { 116u, 4096u }, { 3u, 20u }, { 17u, 9u } }; - const float poison = -999.0f; - for (size_t s = 0; s < sizeof shapes / sizeof shapes[0]; s++) { - const uint32_t m = shapes[s][0], n = shapes[s][1], mp = (m + 15u) / 16u * 16u, np = (n + 7u) / 8u * 8u; - const uint32_t mt = (m + 15u) / 16u, nt = (n + 7u) / 8u; - float *cd = calloc((size_t)mp * np, sizeof *cd); - const size_t set = omega_matmul_result_sentinels(cd, m, n, np, poison, 1); - CHECK(set == (size_t)mt * nt, "sentinel count m=%u n=%u: %zu != %u", m, n, set, mt * nt); - /* every fragment tile with a real word holds exactly one sentinel, inside its real rows and columns */ - size_t tiles_ok = 0, outside = 0; - for (uint32_t ti = 0; ti < mt; ti++) - for (uint32_t tj = 0; tj < nt; tj++) { - size_t in_tile = 0; - for (uint32_t r = ti * 16u; r < ti * 16u + 16u; r++) - for (uint32_t c = tj * 8u; c < tj * 8u + 8u; c++) - if (cd[(size_t)r * np + c] == poison) { if (r < m && c < n) in_tile++; else outside++; } - if (in_tile == 1) tiles_ok++; - } - CHECK(tiles_ok == (size_t)mt * nt && outside == 0, "sentinel placement m=%u n=%u: %zu tiles ok, %zu outside", m, n, tiles_ok, outside); - CHECK(omega_matmul_result_sentinels(cd, m, n, np, poison, 0) == set, "sentinel scan m=%u n=%u: all survive", m, n); - /* clearing one tile's sentinel removes exactly one survivor; a fully written result has none */ - cd[(size_t)(m - 1u) * np + (n - 1u)] = 0.0f; - CHECK(omega_matmul_result_sentinels(cd, m, n, np, poison, 0) == set - 1u, "sentinel scan m=%u n=%u: one cleared", m, n); - for (size_t i = 0; i < (size_t)mp * np; i++) cd[i] = 1.5f; - CHECK(omega_matmul_result_sentinels(cd, m, n, np, poison, 0) == 0, "sentinel scan m=%u n=%u: none survive", m, n); - free(cd); - } -} - -static void frag_host_checks(void) { - sentinel_host_checks(); - /* row-0 pack (one-row decode call): a full one-row pack of A2 equals a full pack of A1 followed by the - * row-0 pack of A2, bf16 and f32 inputs, including a width with padding columns */ - { - const uint32_t ks[] = { 4096u, 40u }; - for (size_t i = 0; i < 2; i++) { - const uint32_t k = ks[i], kp = (k + 15u) / 16u * 16u; - float *a1 = malloc(k * sizeof *a1), *a2 = malloc(k * sizeof *a2); - uint16_t *b1 = malloc(k * 2), *b2 = malloc(k * 2), *full = malloc((size_t)16 * kp * 2), *inc = malloc((size_t)16 * kp * 2); - uint32_t seed = 77u + k; - fill(a1, k, &seed); fill(a2, k, &seed); - for (uint32_t j = 0; j < k; j++) { b1[j] = omega_fp32_to_bf16(a1[j]); b2[j] = omega_fp32_to_bf16(a2[j]); } - omega_matmul_frag_pack_a(b2, 1, k, 16, kp, full); - omega_matmul_frag_pack_a(b1, 1, k, 16, kp, inc); - omega_matmul_frag_pack_a_row0(b2, k, kp, inc); - CHECK(memcmp(full, inc, (size_t)16 * kp * 2) == 0, "row-0 pack bf16 k=%u equals the full one-row pack", k); - omega_matmul_frag_pack_a_f32(a1, 1, k, 16, kp, inc); - omega_matmul_frag_pack_a_row0_f32(a2, k, kp, inc); - CHECK(memcmp(full, inc, (size_t)16 * kp * 2) == 0, "row-0 pack f32 k=%u equals the full one-row pack", k); - free(a1); free(a2); free(b1); free(b2); free(full); free(inc); - } - } - CHECK(omega_blackwell_verify_codegen_fixtures_fragmm() == 0, "fragment matmul golden words (rc %d)", omega_blackwell_verify_codegen_fixtures_fragmm()); - struct { uint32_t m, k, n; } sh[] = { {1, 16, 8}, {1, 40, 13}, {17, 48, 24}, {33, 2560, 72}, {5, 160, 1000} }; - for (size_t s = 0; s < sizeof sh / sizeof sh[0]; s++) { - const uint32_t m = sh[s].m, k = sh[s].k, n = sh[s].n; - const uint32_t mp = (m + 15) / 16 * 16, kp = (k + 15) / 16 * 16, np = (n + 7) / 8 * 8, KS = kp / 16, NT = np / 8; - uint16_t *a = malloc((size_t)m * k * 2), *b = malloc((size_t)k * n * 2); - uint16_t *pa = malloc((size_t)mp * kp * 2), *pb = malloc((size_t)kp * np * 2); - uint32_t seed = 7 + (uint32_t)s; - for (size_t i = 0; i < (size_t)m * k; i++) a[i] = (uint16_t)(1 + lcg(&seed) % 60000); - for (size_t i = 0; i < (size_t)k * n; i++) b[i] = (uint16_t)(1 + lcg(&seed) % 60000); - omega_matmul_frag_pack_a(a, m, k, mp, kp, pa); - /* B in two uneven chunks, as the upload does in FRAG_PACK_TILES steps */ - uint32_t split = NT / 2; - omega_matmul_frag_pack_b(b, k, n, kp, 0, split, pb); - omega_matmul_frag_pack_b(b, k, n, kp, split, NT, pb + (size_t)split * kp * 8); - size_t bad_a = 0, bad_b = 0; - for (uint32_t mt = 0; mt < mp / 16; mt++) - for (uint32_t ks = 0; ks < KS; ks++) - for (uint32_t lane = 0; lane < 32; lane++) { - const uint32_t gg = lane >> 2, t = lane & 3; - const uint32_t rows[8] = { gg, gg, gg + 8, gg + 8, gg, gg, gg + 8, gg + 8 }; - const uint32_t cols[8] = { 2 * t, 2 * t + 1, 2 * t, 2 * t + 1, 2 * t + 8, 2 * t + 9, 2 * t + 8, 2 * t + 9 }; - for (int e = 0; e < 8; e++) { - uint32_t r = mt * 16 + rows[e], c = ks * 16 + cols[e]; - uint16_t want = (r < m && c < k) ? a[(size_t)r * k + c] : 0; - if (pa[(((size_t)mt * KS + ks) * 32 + lane) * 8 + e] != want) bad_a++; - } - } - for (uint32_t nt = 0; nt < NT; nt++) - for (uint32_t ks = 0; ks < KS; ks++) - for (uint32_t lane = 0; lane < 32; lane++) { - const uint32_t gg = lane >> 2, t = lane & 3; - const uint32_t rows[4] = { 2 * t, 2 * t + 1, 2 * t + 8, 2 * t + 9 }; - for (int e = 0; e < 4; e++) { - uint32_t r = ks * 16 + rows[e], c = nt * 8 + gg; - uint16_t want = (r < k && c < n) ? b[(size_t)r * n + c] : 0; - if (pb[(((size_t)nt * KS + ks) * 32 + lane) * 4 + e] != want) bad_b++; - } - } - CHECK(bad_a == 0 && bad_b == 0, "fragment pack round trip %ux%ux%u (A bad %zu, B bad %zu)", m, k, n, bad_a, bad_b); - /* the fused f32 packer equals convert-then-pack bit for bit (ties, denormals, inf, NaN included) */ - float *af = malloc((size_t)m * k * sizeof *af); - uint16_t *pf = malloc((size_t)mp * kp * 2); - for (size_t i = 0; i < (size_t)m * k; i++) { - uint32_t bits = lcg(&seed) * 2654435761u; - switch (i % 7) { - case 0: bits = (bits & 0x807fffffu) | 0x3f800000u; break; /* in [1,2) with every mantissa bit live (rounding ties) */ - case 1: bits = 0x7f800000u | ((bits >> 9) & 0x7fffffu); break; /* inf (0 payload) or NaN payloads */ - case 2: bits &= 0x807fffffu; break; /* zero and denormals */ - default: break; - } - memcpy(&af[i], &bits, 4); - a[i] = omega_fp32_to_bf16(af[i]); - } - omega_matmul_frag_pack_a(a, m, k, mp, kp, pa); - omega_matmul_frag_pack_a_f32(af, m, k, mp, kp, pf); - CHECK(memcmp(pa, pf, (size_t)mp * kp * 2) == 0, "fused f32 pack equals convert-then-pack %ux%u", m, k); - free(af); free(pf); - free(a); free(b); free(pa); free(pb); - } - /* the kernel generates for every padded Qwen3-4B and Llama-3.2-1B decode shape at the API's unroll */ - struct { uint32_t k, n, gx; } ok[] = { {16, 8, 1}, {2560, 4096, 256}, {2560, 1024, 128}, {4096, 2560, 256}, {2560, 9728, 256}, - {9728, 2560, 256}, {2560, 151936, 256}, {2048, 8192, 64}, {8192, 2048, 64}, - {2048, 128256, 64}, {16384, 262144, 64}, {48, 16, 2} }; - for (size_t i = 0; i < sizeof ok / sizeof ok[0]; i++) { - OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - const uint32_t u = omega_matmul_frag_unroll(ok[i].k); - int rc = omega_matmul_spec_init(&spec, 16, ok[i].k, ok[i].n, OMEGA_MATMUL_PRECISION_BF16) == 0 && - omega_blackwell_codegen_matmul_frag(&spec, ok[i].gx, u, 0, &kernel) == 0 && kernel.code_size > 0; - CHECK(rc, "fragment kernel K=%u N=%u gx=%u unroll=%u generated", ok[i].k, ok[i].n, ok[i].gx, u); - CHECK(kernel.gpr_count <= 64, "fragment kernel K=%u N=%u unroll=%u fits 64 registers (got %u)", ok[i].k, ok[i].n, u, kernel.gpr_count); - if (i == 1) printf("fragment kernel K=2560 N=4096 unroll %u: %zu instructions, %u registers\n", u, kernel.insn_count, kernel.gpr_count); - OmegaBlackwellKernel mut; memset(&mut, 0, sizeof mut); - if (omega_blackwell_codegen_matmul_frag(&spec, ok[i].gx, u, 1, &mut) == 0) { - CHECK(memcmp(mut.code_digest, kernel.code_digest, 32) != 0, "fragment mutant differs K=%u N=%u", ok[i].k, ok[i].n); - omega_blackwell_kernel_free(&mut); - } else CHECK(ok[i].k / 16 / u < 2, "fragment mutant refused only with one pass (K=%u)", ok[i].k); - omega_blackwell_kernel_free(&kernel); - } - CHECK(omega_matmul_frag_unroll(2560) == 4 && omega_matmul_frag_unroll(48) == 1 && omega_matmul_frag_unroll(64) == 4 && - omega_matmul_frag_unroll(32) == 2 && omega_matmul_frag_unroll(128) == 4, "unroll choice (capped at 4)"); - { /* unroll 8 still generates (experiments) */ - OmegaMatMulSpec s8; OmegaBlackwellKernel k8; memset(&k8, 0, sizeof k8); - CHECK(omega_matmul_spec_init(&s8, 16, 2560, 4096, OMEGA_MATMUL_PRECISION_BF16) == 0 && - omega_blackwell_codegen_matmul_frag(&s8, 256, 8, 0, &k8) == 0 && k8.code_size > 0, "unroll 8 generates"); - omega_blackwell_kernel_free(&k8); - } - OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - CHECK(omega_matmul_spec_init(&spec, 16, 48, 16, OMEGA_MATMUL_PRECISION_BF16) == 0 && - omega_blackwell_codegen_matmul_frag(&spec, 1, 2, 0, &kernel) != 0, "unroll not dividing K/16 refused"); - CHECK(omega_blackwell_codegen_matmul_frag(&spec, 1, 3, 0, &kernel) != 0, "unroll 3 refused"); - CHECK(omega_blackwell_codegen_matmul_frag(&spec, 3, 1, 0, &kernel) != 0, "fragment grid_x beyond the column tiles refused"); - /* 2026-10-12: the blocked kernel (rt row tiles x ct column tiles per warp) generates for the Qwen3-8B - * prefill shapes at m = 128 (rt 4, ct 4, grid_x 512 at the daemon's 1024-CTA budget) and the small - * parity shapes; it fits the allocator's 128 registers; its mutant differs; the envelope is enforced */ - struct { uint32_t k, n, gx, rt, ct; } bk[] = { {4096, 24576, 512, 4, 4}, {12288, 4096, 128, 4, 4}, {4096, 6144, 192, 4, 4}, - {128, 128, 4, 4, 4}, {32, 32, 1, 2, 4}, {16, 8, 1, 2, 1}, {1024, 8, 1, 4, 1}, - {64, 64, 2, 4, 2}, {48, 16, 1, 2, 2} }; - for (size_t i = 0; i < sizeof bk / sizeof bk[0]; i++) { - OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - const uint32_t u = omega_matmul_frag_block_unroll(bk[i].k, bk[i].rt, bk[i].ct); - int rc = omega_matmul_spec_init(&spec, 16, bk[i].k, bk[i].n, OMEGA_MATMUL_PRECISION_BF16) == 0 && - omega_blackwell_codegen_matmul_frag_block(&spec, bk[i].gx, u, bk[i].rt, bk[i].ct, 0, &kernel) == 0 && kernel.code_size > 0; - CHECK(rc, "blocked kernel K=%u N=%u gx=%u rt=%u ct=%u unroll=%u generated", bk[i].k, bk[i].n, bk[i].gx, bk[i].rt, bk[i].ct, u); - CHECK(u * (bk[i].rt + bk[i].ct) <= 8, "blocked kernel K=%u rt=%u ct=%u issues at most 8 loads per pass (unroll %u)", bk[i].k, bk[i].rt, bk[i].ct, u); - if (i < 3) printf("blocked kernel K=%u N=%u rt=%u ct=%u unroll %u: %zu instructions, %u registers\n", bk[i].k, bk[i].n, bk[i].rt, bk[i].ct, u, kernel.insn_count, kernel.gpr_count); - OmegaBlackwellKernel mut; memset(&mut, 0, sizeof mut); - if (omega_blackwell_codegen_matmul_frag_block(&spec, bk[i].gx, u, bk[i].rt, bk[i].ct, 1, &mut) == 0) { - CHECK(memcmp(mut.code_digest, kernel.code_digest, 32) != 0, "blocked mutant differs K=%u N=%u", bk[i].k, bk[i].n); - omega_blackwell_kernel_free(&mut); - } else CHECK(bk[i].k / 16 / u < 2, "blocked mutant refused only with one pass (K=%u)", bk[i].k); - omega_blackwell_kernel_free(&kernel); - } - { - uint32_t rt, ct; - omega_matmul_frag_block_shape(8, 3072, &rt, &ct); CHECK(rt == 4 && ct == 4, "block shape m=128 n=24576 is 4x4"); - omega_matmul_frag_block_shape(1, 3072, &rt, &ct); CHECK(rt == 1 && ct == 1, "block shape m=1 is the single-tile kernel"); - omega_matmul_frag_block_shape(7, 3072, &rt, &ct); CHECK(rt == 1 && ct == 1, "block shape m=112 (7 row tiles) is the single-tile kernel"); - omega_matmul_frag_block_shape(6, 6, &rt, &ct); CHECK(rt == 2 && ct == 2, "block shape 6 row tiles, 6 column tiles is 2x2"); - omega_matmul_frag_block_shape(4, 1, &rt, &ct); CHECK(rt == 4 && ct == 1, "block shape 4 row tiles, 1 column tile is 4x1"); - /* the C store offset of the last row tile is a signed 24-bit immediate: wide N steps rt down (lm_head: to 1) */ - omega_matmul_frag_block_shape(2, 18992, &rt, &ct); CHECK(rt == 1 && ct == 1, "block shape lm_head (N 151936) at 2 row tiles is the single-tile kernel: %ux%u", rt, ct); - omega_matmul_frag_block_shape(8, 18992, &rt, &ct); CHECK(rt == 1 && ct == 1, "block shape lm_head (N 151936) at 8 row tiles is the single-tile kernel: %ux%u", rt, ct); - omega_matmul_frag_block_shape(8, 8192, &rt, &ct); CHECK(rt == 2 && ct == 4, "block shape N 65536 at 8 row tiles steps rt 4 -> 2: %ux%u", rt, ct); - CHECK(omega_matmul_frag_block_unroll(4096, 4, 4) == 1 && omega_matmul_frag_block_unroll(4096, 2, 2) == 2 && - omega_matmul_frag_block_unroll(48, 2, 2) == 1 && omega_matmul_frag_block_unroll(4096, 4, 2) == 1, "blocked unroll rule (loads per pass <= 8)"); - OmegaMatMulSpec s; OmegaBlackwellKernel kk; memset(&kk, 0, sizeof kk); - CHECK(omega_matmul_spec_init(&s, 16, 4096, 6144, OMEGA_MATMUL_PRECISION_BF16) == 0, "spec for refusals"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 1, 1, 1, 0, &kk) != 0, "blocked 1x1 refused (single-tile kernel)"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 1, 3, 2, 0, &kk) != 0, "blocked rt 3 refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 1, 8, 4, 0, &kk) != 0, "blocked 8x4 (32 accumulators) refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 1, 8, 1, 0, &kk) != 0, "blocked 8x1 (9 loads per pass) refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 2, 4, 4, 0, &kk) != 0, "blocked unroll 2 at 4x4 (16 loads per pass) refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 1, 4, 2, 2, 0, &kk) != 0, "blocked unroll 4 refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s, 193, 1, 4, 4, 0, &kk) != 0, "blocked grid_x beyond the column blocks refused"); - OmegaMatMulSpec s3; CHECK(omega_matmul_spec_init(&s3, 16, 64, 24, OMEGA_MATMUL_PRECISION_BF16) == 0, "spec n=24"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s3, 1, 1, 2, 4, 0, &kk) != 0, "blocked ct not dividing the column tiles refused"); - CHECK(omega_blackwell_codegen_matmul_frag_block(&s3, 1, 1, 2, 2, 0, &kk) != 0, "blocked ct 2 on 3 column tiles refused"); - } -} - -static void host_only(void) { - float a[16 * 16] = {0}, b[16 * 16] = {0}, c[16 * 16] = {0}; - OmegaGpuMatmulInfo info; - CHECK(omega_gpu_matmul_f32(0, 16, 16, a, b, c, &info) == OMEGA_GPU_MATMUL_BAD_ARGS, "m=0 refused"); - CHECK(omega_gpu_matmul_f32(16, 16, 16, NULL, b, c, &info) == OMEGA_GPU_MATMUL_BAD_ARGS, "NULL a refused"); - CHECK(omega_gpu_matmul_f32(OMEGA_BW_MATMUL_MAX_M + 1, 16, 16, a, b, c, &info) == OMEGA_GPU_MATMUL_TOO_LARGE, "m over limit refused"); - CHECK(omega_gpu_matmul_bf16(16, OMEGA_BW_MATMUL_MAX_K + 1, 16, (uint16_t *)a, (uint16_t *)b, c, NULL) == OMEGA_GPU_MATMUL_TOO_LARGE, "k over limit refused (NULL info ok)"); - /* session spin window (omega#328): in-range value kept, out-of-range refused unchanged, 0 restores */ - const uint32_t spin0 = omega_gpu_session_spin_us(); - CHECK(omega_gpu_session_set_spin_us(2000) == 0 && omega_gpu_session_spin_us() == 2000, "spin window 2000 us set"); - CHECK(omega_gpu_session_set_spin_us(OMEGA_GPU_SESSION_MAX_SPIN_US + 1) == -1 && omega_gpu_session_spin_us() == 2000, - "spin window over the maximum refused, setting unchanged"); - CHECK(omega_gpu_session_set_spin_us(0) == 0 && omega_gpu_session_spin_us() == 0, "spin window 0 restores the sleep-poll"); - omega_gpu_session_set_spin_us(spin0); - CHECK(omega_gpu_matmul_bf16(16, 16, OMEGA_BW_MATMUL_MAX_N + 1, (uint16_t *)a, (uint16_t *)b, c, NULL) == OMEGA_GPU_MATMUL_TOO_LARGE, "n over limit refused"); - CHECK(OMEGA_BW_MATMUL_MAX_N >= 128256 && OMEGA_BW_MATMUL_MAX_K >= 8192 && OMEGA_BW_MATMUL_MAX_M >= 2048, "limits cover Llama shapes (vocab 128256, ffn 8192)"); - OmegaGpuTensor *t = NULL; - CHECK(omega_gpu_tensor_upload_f32(0, 16, a, &t) == OMEGA_GPU_MATMUL_BAD_ARGS && t == NULL, "tensor k=0 refused"); - CHECK(omega_gpu_tensor_upload_f32(16, 16, NULL, &t) == OMEGA_GPU_MATMUL_BAD_ARGS, "tensor NULL refused"); - CHECK(omega_gpu_matmul_resident_f32(16, a, NULL, c, &info) == OMEGA_GPU_MATMUL_BAD_ARGS, "resident NULL tensor refused"); - CHECK(omega_gpu_tensor_update_f32(NULL, 16, 16, a) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_f32 NULL tensor refused"); - CHECK(omega_gpu_tensor_update_bf16(NULL, 16, 16, (const uint16_t *)a) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_bf16 NULL tensor refused"); - CHECK(strcmp(omega_gpu_matmul_rc_name(OMEGA_GPU_MATMUL_PARITY_FAIL), "PARITY_FAIL") == 0, "rc name"); - CHECK(omega_gpu_matmul_cta_budget() == OMEGA_GPU_MATMUL_MAX_CTAS, "default CTA budget"); - { - OmegaGpuMatmulStages s0; - memset(&s0, 0xff, sizeof s0); - omega_gpu_matmul_last_stages(&s0); - omega_gpu_matmul_last_stages(NULL); - CHECK(s0.core_ns == 0 && s0.launch_ns == 0 && s0.pack_ns == 0, "stages all zero before the first matmul"); - } - /* omega #473 R4: the default is the best budget of the sealed receipt evidence/R4-MATMUL-CTA-ffc3176a (every element of - * every call at the five training shapes and two single-tile shapes, budgets 64..1024, all sealed; 1024 fastest) */ - CHECK(OMEGA_GPU_MATMUL_MAX_CTAS == 1024u, "default CTA budget is the R4 sealed budget 1024 (got %u)", (unsigned)OMEGA_GPU_MATMUL_MAX_CTAS); - CHECK(omega_gpu_matmul_is_blocked() == 0, "not blocked at start"); - - /* codegen only: the looped kernel must accept every padded Llama shape without touching the chip */ - struct { uint32_t k, n, gx; } ok[] = { {16, 8, 1}, {2048, 8192, 64}, {8192, 2048, 64}, {2048, 128256, 64}, {1024, 1024, 1}, {16384, 262144, 64} }; - for (size_t i = 0; i < sizeof ok / sizeof ok[0]; i++) { - OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - int rc = omega_matmul_spec_init(&spec, 16, ok[i].k, ok[i].n, OMEGA_MATMUL_PRECISION_BF16) == 0 && - omega_blackwell_codegen_matmul_tensor_loop(&spec, ok[i].gx, 0, &kernel) == 0 && kernel.code_size > 0; - CHECK(rc, "loop kernel K=%u N=%u gx=%u generated", ok[i].k, ok[i].n, ok[i].gx); - CHECK(kernel.gpr_count <= 64, "loop kernel K=%u N=%u fits 64 registers (got %u)", ok[i].k, ok[i].n, kernel.gpr_count); - /* the mutant kernel is a different program */ - OmegaBlackwellKernel mut; memset(&mut, 0, sizeof mut); - if (omega_blackwell_codegen_matmul_tensor_loop(&spec, ok[i].gx, 1, &mut) == 0) { - CHECK(memcmp(mut.code_digest, kernel.code_digest, 32) != 0, "mutant kernel differs K=%u N=%u", ok[i].k, ok[i].n); - omega_blackwell_kernel_free(&mut); - } else CHECK(ok[i].k == 16, "mutant refused only for K=16 (K=%u)", ok[i].k); - omega_blackwell_kernel_free(&kernel); - } - OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; memset(&kernel, 0, sizeof kernel); - CHECK(omega_matmul_spec_init(&spec, 16, 24, 16, OMEGA_MATMUL_PRECISION_BF16) == 0 && omega_blackwell_codegen_matmul_tensor_loop(&spec, 1, 0, &kernel) != 0, "K not multiple of 16 refused by codegen (the API pads)"); - CHECK(omega_matmul_spec_init(&spec, 16, 16, 16, OMEGA_MATMUL_PRECISION_BF16) == 0 && omega_blackwell_codegen_matmul_tensor_loop(&spec, 3, 0, &kernel) != 0, "grid_x beyond the column tiles refused"); - /* the single-tile kernel of cut 1 still generates (other gates use it) */ - memset(&kernel, 0, sizeof kernel); - CHECK(omega_matmul_spec_init(&spec, 16, 16, 8, OMEGA_MATMUL_PRECISION_BF16) == 0 && omega_blackwell_codegen_matmul(&spec, &kernel) == 0 && kernel.code_size > 0, "16x16x8 single-tile kernel generated"); - omega_blackwell_kernel_free(&kernel); - frag_host_checks(); - omega_gpu_matmul_cache_clear(); -} - -/* One-row calls reuse the zero padding rows of the activation buffer: a second one-row call of the same - * width writes row 0 only (hook counts it) and still matches the oracle with a different A; a wider - * call in between, or another width, forces a full pack again. */ -static void one_row_repack_checks(void) { - const uint32_t k = 4096, n = 256; - float *a = malloc((size_t)32 * k * sizeof *a), *b = malloc((size_t)k * n * sizeof *b), *c = malloc((size_t)32 * n * sizeof *c); - uint32_t seed = 0x10c0u; - fill(a, (size_t)32 * k, &seed); fill(b, (size_t)k * n, &seed); - OmegaGpuMatmulInfo info; - const uint64_t h0 = omega_gpu_matmul_test_a_row0_hits(); - int rc1 = omega_gpu_matmul_f32(1, k, n, a, b, c, &info); - CHECK(rc1 == OMEGA_GPU_MATMUL_OK && info.parity_verified, "one-row call 1 (full pack) rc=%s parity=%d", omega_gpu_matmul_rc_name(rc1), info.parity_verified); - const uint64_t h1 = omega_gpu_matmul_test_a_row0_hits(); - int rc2 = omega_gpu_matmul_f32(1, k, n, a + k, b, c, &info); - const uint64_t h2 = omega_gpu_matmul_test_a_row0_hits(); - CHECK(rc2 == OMEGA_GPU_MATMUL_OK && info.parity_verified, "one-row call 2 (row 0 only, new A) rc=%s parity=%d", omega_gpu_matmul_rc_name(rc2), info.parity_verified); - CHECK(h1 == h0 && h2 == h1 + 1, "row-0 path taken on the second one-row call only (hits %" PRIu64 " %" PRIu64 " %" PRIu64 ")", h0, h1, h2); - int rc3 = omega_gpu_matmul_f32(32, k, n, a, b, c, &info); - CHECK(rc3 == OMEGA_GPU_MATMUL_OK && info.parity_verified, "32-row call between rc=%s parity=%d", omega_gpu_matmul_rc_name(rc3), info.parity_verified); - int rc4 = omega_gpu_matmul_f32(1, k, n, a + 2 * (size_t)k, b, c, &info); - const uint64_t h4 = omega_gpu_matmul_test_a_row0_hits(); - CHECK(rc4 == OMEGA_GPU_MATMUL_OK && info.parity_verified && h4 == h2, "one-row call after a wider call packs in full (hits %" PRIu64 ")", h4); - int rc5 = omega_gpu_matmul_f32(1, k, n, a + 3 * (size_t)k, b, c, &info); - const uint64_t h5 = omega_gpu_matmul_test_a_row0_hits(); - CHECK(rc5 == OMEGA_GPU_MATMUL_OK && info.parity_verified && h5 == h4 + 1, "one-row call after a one-row call writes row 0 only (hits %" PRIu64 ")", h5); - int rc6 = omega_gpu_matmul_f32(1, 64, n, a, b, c, &info); - const uint64_t h6 = omega_gpu_matmul_test_a_row0_hits(); - CHECK(rc6 == OMEGA_GPU_MATMUL_OK && info.parity_verified && h6 == h5, "one-row call of another width packs in full (hits %" PRIu64 ")", h6); - free(a); free(b); free(c); -} - -/* omega #473: the stage timer must explain the call. The six stages tile matmul_core in order, the chip - * time sits inside the launch stage, and the core span sits inside the whole call. */ -static uint64_t stage_sum(const OmegaGpuMatmulStages *s) { - return s->setup_ns + s->pack_ns + s->upload_ns + s->launch_ns + s->sync_ns + s->copy_out_ns; -} -static void stage_checks(const char *tag, const OmegaGpuMatmulInfo *info) { - OmegaGpuMatmulStages s; - omega_gpu_matmul_last_stages(&s); - CHECK(s.chip_ns == info->elapsed_ns && s.chip_ns > 0, "%s stages: chip_ns %" PRIu64 " equals elapsed_ns %" PRIu64, tag, s.chip_ns, info->elapsed_ns); - CHECK(s.launch_ns >= s.chip_ns, "%s stages: launch_ns %" PRIu64 " holds chip_ns %" PRIu64, tag, s.launch_ns, s.chip_ns); - CHECK(s.pack_ns > 0 && s.copy_out_ns > 0, "%s stages: pack %" PRIu64 " and copy-out %" PRIu64 " measured", tag, s.pack_ns, s.copy_out_ns); - CHECK(stage_sum(&s) <= s.core_ns && s.core_ns <= info->call_ns && s.core_ns > 0, - "%s stages: sum %" PRIu64 " <= core %" PRIu64 " <= call %" PRIu64, tag, stage_sum(&s), s.core_ns, info->call_ns); -} - -/* omega #473 profile: resident calls at the given shapes, 3 warmups then 7 timed calls per input type - * (bf16 rows, f32 rows); median of each stage. Correctness is the R4 receipt's job; here the two input - * types must agree bit for bit and every call must pass stage_checks. */ -static uint64_t med_u64(uint64_t *v, int n) { - for (int i = 1; i < n; i++) for (int j = i; j > 0 && v[j - 1] > v[j]; j--) { uint64_t t = v[j]; v[j] = v[j - 1]; v[j - 1] = t; } - return v[n / 2]; -} -static int stages_profile(const char *shapes, const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_MATMUL_STAGES_V1\",\"cta_budget\":%u,\"warmups\":3,\"timed\":7,\"rows\":[", omega_gpu_matmul_cta_budget()); - char *copy = strdup(shapes), *save = NULL; - int first = 1; - for (char *tok = strtok_r(copy, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) { - unsigned m, k, n; - if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { printf("bad shape %s\n", tok); continue; } - const size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n; - float *a = malloc(na * 4), *b = malloc(nb * 4), *c16 = malloc(nc * 4), *c32 = malloc(nc * 4); - uint16_t *ah = malloc(na * 2); - if (!a || !b || !c16 || !c32 || !ah) { CHECK(0, "host memory for %s", tok); break; } - uint32_t seed = 0x5eed0000u ^ (m << 20) ^ (k << 10) ^ n; - fill(a, na, &seed); fill(b, nb, &seed); - for (size_t i = 0; i < na; i++) ah[i] = omega_fp32_to_bf16(a[i]); - OmegaGpuTensor *t = NULL; - int urc = omega_gpu_tensor_upload_f32(k, n, b, &t); - CHECK(urc == OMEGA_GPU_MATMUL_OK, "upload %s rc=%s", tok, omega_gpu_matmul_rc_name(urc)); - if (urc != OMEGA_GPU_MATMUL_OK) break; - for (int in32 = 0; in32 < 2; in32++) { - uint64_t v[9][7]; /* setup pack upload launch chip sync copy_out core call */ - int ok = 1; - for (int it = 0; it < 10 && ok; it++) { - OmegaGpuMatmulInfo info; - int rc = in32 ? omega_gpu_matmul_resident_f32(m, a, t, c32, &info) : omega_gpu_matmul_resident_bf16(m, ah, t, c16, &info); - if (rc != OMEGA_GPU_MATMUL_OK) { CHECK(0, "%s %s rc=%s (%s)", tok, in32 ? "f32" : "bf16", omega_gpu_matmul_rc_name(rc), omega_gpu_matmul_last_error()); ok = 0; break; } - stage_checks(tok, &info); - if (it < 3) continue; - OmegaGpuMatmulStages s; omega_gpu_matmul_last_stages(&s); - const uint64_t row[9] = { s.setup_ns, s.pack_ns, s.upload_ns, s.launch_ns, s.chip_ns, s.sync_ns, s.copy_out_ns, s.core_ns, info.call_ns }; - for (int q = 0; q < 9; q++) v[q][it - 3] = row[q]; - } - if (!ok) continue; - uint64_t md[9]; - for (int q = 0; q < 9; q++) md[q] = med_u64(v[q], 7); - const double flop = 2.0 * m * k * n; - printf("STAGES %s in=%s budget=%u call_ms=%.3f core_ms=%.3f setup=%.3f pack=%.3f upload=%.3f launch=%.3f chip=%.3f launch_minus_chip=%.3f sync=%.3f copy_out=%.3f " - "tflops_chip=%.3f tflops_call=%.3f chip_share=%.1f%%\n", tok, in32 ? "f32" : "bf16", omega_gpu_matmul_cta_budget(), md[8] / 1e6, md[7] / 1e6, - md[0] / 1e6, md[1] / 1e6, md[2] / 1e6, md[3] / 1e6, md[4] / 1e6, (md[3] > md[4] ? md[3] - md[4] : 0) / 1e6, md[5] / 1e6, md[6] / 1e6, - flop / (double)md[4] / 1e3, flop / (double)md[8] / 1e3, 100.0 * (double)md[4] / (double)md[8]); - if (out) { - fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"input\":\"%s\",\"median_ns\":{\"setup\":%" PRIu64 ",\"pack\":%" PRIu64 ",\"upload\":%" PRIu64 ",\"launch\":%" PRIu64 - ",\"chip\":%" PRIu64 ",\"sync\":%" PRIu64 ",\"copy_out\":%" PRIu64 ",\"core\":%" PRIu64 ",\"call\":%" PRIu64 "},\"tflops_chip\":%.4f,\"tflops_call\":%.4f}", - first ? "" : ",", m, k, n, in32 ? "f32" : "bf16", md[0], md[1], md[2], md[3], md[4], md[5], md[6], md[7], md[8], flop / (double)md[4] / 1e3, flop / (double)md[8] / 1e3); - first = 0; - } - } - size_t diff = 0; - for (size_t i = 0; i < nc; i++) diff += memcmp(&c16[i], &c32[i], 4) != 0; - CHECK(diff == 0, "%s bf16-in and f32-in outputs agree bit for bit (%zu differ)", tok, diff); - omega_gpu_tensor_free(t); - free(a); free(b); free(c16); free(c32); free(ah); - if (omega_gpu_matmul_is_blocked()) break; - } - free(copy); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - return 0; -} - -static int chip_sweep(const char *shapes, const char *out_path, int mutant) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_MATMUL_API_SWEEP_V2\",\"mutant\":%s,\"cta_budget\":%u,\"shapes\":[", mutant ? "true" : "false", omega_gpu_matmul_cta_budget()); - char *copy = strdup(shapes); - char *save = NULL; - int first = 1; - for (char *tok = strtok_r(copy, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) { - unsigned m, k, n; - if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { printf("bad shape %s\n", tok); continue; } - size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n; - float *a = malloc(na * sizeof *a), *b = malloc(nb * sizeof *b), *c = malloc(nc * sizeof *c), *c2 = malloc(nc * sizeof *c2); - if (!a || !b || !c || !c2) { printf("out of host memory for %s\n", tok); free(a); free(b); free(c); free(c2); continue; } - uint32_t seed = 0x5eed0000u ^ (m << 20) ^ (k << 10) ^ n; - fill(a, na, &seed); fill(b, nb, &seed); - for (size_t i = 0; i < nc; i++) c[i] = -12345.0f; - OmegaGpuMatmulInfo info, info2; - double t0 = now_ms(); - int rc = omega_gpu_matmul_f32(m, k, n, a, b, c, &info); - double wall_ms = now_ms() - t0; - if (!mutant && rc == OMEGA_GPU_MATMUL_OK) stage_checks(tok, &info); - /* second call on the same shape must hit the kernel cache and agree */ - int rc2 = omega_gpu_matmul_f32(m, k, n, a, b, c2, &info2); - size_t repeat_mismatch = 0; - for (size_t i = 0; i < nc; i++) if (c[i] != c2[i]) repeat_mismatch++; - size_t e2e_bad = 0; - double e2e = (rc == OMEGA_GPU_MATMUL_OK || rc == OMEGA_GPU_MATMUL_PARITY_FAIL) ? e2e_max_rel(m, k, n, a, b, c, &e2e_bad) : 0.0; - int pass = rc == OMEGA_GPU_MATMUL_OK && info.parity_verified && e2e < 1e-5 - && rc2 == OMEGA_GPU_MATMUL_OK && info2.kernel_cache_hit && repeat_mismatch == 0; - if (mutant) { - /* the wrong kernel must be caught: PARITY_FAIL from the API oracle and a visible e2e error */ - int caught = rc == OMEGA_GPU_MATMUL_PARITY_FAIL && !info.parity_verified && e2e >= 1e-5; - CHECK(caught, "mutant shape %ux%ux%u NOT caught: rc=%s parity=%d e2e_rel=%g", m, k, n, omega_gpu_matmul_rc_name(rc), info.parity_verified, e2e); - pass = caught; - } else { - CHECK(pass, "shape %ux%ux%u rc=%s parity=%d max_rel=%g e2e_rel=%g rc2=%s hit=%d repeat_mismatch=%zu", - m, k, n, omega_gpu_matmul_rc_name(rc), info.parity_verified, info.max_rel_err, e2e, - omega_gpu_matmul_rc_name(rc2), info2.kernel_cache_hit, repeat_mismatch); - } - printf("%s %ux%ux%u rc=%s chip_ns=%" PRIu64 " call_ms=%.3f wall_ms=%.1f max_abs=%g max_rel=%g mismatches=%zu e2e_rel=%g e2e_bad=%zu grid=%ux%u calls=%u rows_per_call=%u cache_hit2=%d err=\"%s\"\n", - pass ? (mutant ? "KILLED" : "PASS") : (mutant ? "SURVIVED" : "FAIL"), m, k, n, omega_gpu_matmul_rc_name(rc), info.elapsed_ns, info.call_ns / 1e6, wall_ms, - info.max_abs_err, info.max_rel_err, info.mismatch_count, e2e, e2e_bad, info.grid_x, info.grid_y, info.chip_calls, info.rows_per_call, info2.kernel_cache_hit, rc == OMEGA_GPU_MATMUL_CHIP_FAIL ? omega_gpu_matmul_last_error() : ""); - if (out) { - fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"rc\":\"%s\",\"pass\":%s,\"chip_elapsed_ns\":%" PRIu64 - ",\"call_ms\":%.3f,\"wall_ms\":%.3f,\"max_abs_err\":%g,\"max_rel_err\":%g,\"mismatch_count\":%zu," - "\"parity_verified\":%s,\"completion_marker\":%u,\"repeat_rc\":\"%s\",\"repeat_cache_hit\":%s," - "\"repeat_mismatch\":%zu,\"e2e_max_rel\":%g,\"e2e_bad\":%zu,\"grid_x\":%u,\"grid_y\":%u,\"chip_calls\":%u,\"rows_per_call\":%u,\"padded_m\":%u,\"padded_k\":%u,\"padded_n\":%u,\"target_chip\":\"%s\",\"sm_architecture\":%u}", - first ? "" : ",", m, k, n, omega_gpu_matmul_rc_name(rc), pass ? "true" : "false", - info.elapsed_ns, info.call_ns / 1e6, wall_ms, info.max_abs_err, info.max_rel_err, info.mismatch_count, - info.parity_verified ? "true" : "false", info.completion_marker, - omega_gpu_matmul_rc_name(rc2), info2.kernel_cache_hit ? "true" : "false", - repeat_mismatch, e2e, e2e_bad, info.grid_x, info.grid_y, info.chip_calls, info.rows_per_call, info.padded_m, info.padded_k, info.padded_n, info.target_chip, info.sm_architecture); - first = 0; - } - free(a); free(b); free(c); free(c2); - if (omega_gpu_matmul_is_blocked()) { printf("device latched after an uncertain completion; stopping the sweep\n"); break; } - } - free(copy); - if (out) { - fprintf(out, "],\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, - g_failed == 0 ? (mutant ? "OMEGA_GPU_MATMUL_MUTANT_KILLED" : "OMEGA_GPU_MATMUL_API_PASS") : (mutant ? "OMEGA_GPU_MATMUL_MUTANT_SURVIVED" : "OMEGA_GPU_MATMUL_API_FAIL")); - fclose(out); - } - return 0; -} - -static int cmp_double(const void *x, const void *y) { double a = *(const double *)x, b = *(const double *)y; return a < b ? -1 : a > b; } - -/* Resident path: upload B once, then 100 calls; median wall time per call must be under 5 ms. - * Parity: first and last result against the double reference (0 elements at or beyond 1e-5). */ -static int timing(const char *shapes, const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_MATMUL_API_TIMING_V1\",\"cta_budget\":%u,\"spin_us\":%u,\"calls\":100,\"shapes\":[", omega_gpu_matmul_cta_budget(), omega_gpu_session_spin_us()); - char *copy = strdup(shapes); char *save = NULL; int first = 1; - for (char *tok = strtok_r(copy, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) { - unsigned m, k, n; - if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { printf("bad shape %s\n", tok); continue; } - size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n; - float *a = malloc(na * sizeof *a), *b = malloc(nb * sizeof *b), *c = malloc(nc * sizeof *c), *c_first = malloc(nc * sizeof *c_first); - uint16_t *ah = malloc(na * sizeof *ah); - if (!a || !b || !c || !c_first || !ah) { printf("out of host memory\n"); return 2; } - uint32_t seed = 0x7111e000u ^ (m << 20) ^ (k << 10) ^ n; - fill(a, na, &seed); fill(b, nb, &seed); - for (size_t i = 0; i < na; i++) ah[i] = omega_fp32_to_bf16(a[i]); - OmegaGpuTensor *t = NULL; - double tu0 = now_ms(); - int urc = omega_gpu_tensor_upload_f32(k, n, b, &t); - double upload_ms = now_ms() - tu0; - CHECK(urc == OMEGA_GPU_MATMUL_OK, "upload %ux%u rc=%s", k, n, omega_gpu_matmul_rc_name(urc)); - double samples[100]; int ok_calls = 0; OmegaGpuMatmulInfo info; memset(&info, 0, sizeof info); - uint64_t chip_ns_sum = 0; size_t repeat_mismatch = 0; - if (urc == OMEGA_GPU_MATMUL_OK) { - for (int i = 0; i < 100; i++) { - for (size_t j = 0; j < nc; j++) c[j] = -12345.0f; - double t0 = now_ms(); - int rc = omega_gpu_matmul_resident_bf16(m, ah, t, c, &info); - samples[i] = now_ms() - t0; - /* OMEGA_GPU_MATMUL_TIMING_NO_ORACLE=1: the per-call host oracle (m x n x k double MACs) only on the first - * call; at m = 128 it is minutes per shape and the timing is the point (2026-10-12). */ - if (i == 0 && getenv("OMEGA_GPU_MATMUL_TIMING_NO_ORACLE")) omega_gpu_matmul_set_oracle(0); - if (rc == OMEGA_GPU_MATMUL_OK) ok_calls++; - chip_ns_sum += info.elapsed_ns; - if (i == 0) memcpy(c_first, c, nc * sizeof *c); - else for (size_t j = 0; j < nc; j++) if (c[j] != c_first[j]) repeat_mismatch++; - if (omega_gpu_matmul_is_blocked()) break; - } - } - qsort(samples, 100, sizeof samples[0], cmp_double); - double median = samples[50], p90 = samples[90], mn = samples[0], mx = samples[99]; - size_t bad_first = 0, bad_last = 0; - double e2e_first = e2e_max_rel(m, k, n, a, b, c_first, &bad_first); - double e2e_last = e2e_max_rel(m, k, n, a, b, c, &bad_last); - int pass = ok_calls == 100 && bad_first == 0 && bad_last == 0 && repeat_mismatch == 0 && (m > 1 || median < 5.0); /* the 5 ms gate is the GEMV (m = 1) gate */ - CHECK(pass, "timing %ux%ux%u ok_calls=%d median_ms=%.3f e2e_first=%g e2e_last=%g bad=%zu/%zu repeat_mismatch=%zu", - m, k, n, ok_calls, median, e2e_first, e2e_last, bad_first, bad_last, repeat_mismatch); - printf("%s timing %ux%ux%u upload_ms=%.1f ok_calls=%d median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_ns_mean=%" PRIu64 " grid=%ux%u e2e_first=%g e2e_last=%g repeat_mismatch=%zu\n", - pass ? "PASS" : "FAIL", m, k, n, upload_ms, ok_calls, median, p90, mn, mx, ok_calls ? chip_ns_sum / (uint64_t)ok_calls : 0, info.grid_x, info.grid_y, e2e_first, e2e_last, repeat_mismatch); - if (out) { - fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"pass\":%s,\"upload_ms\":%.3f,\"ok_calls\":%d,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f," - "\"chip_ns_mean\":%" PRIu64 ",\"grid_x\":%u,\"grid_y\":%u,\"e2e_first\":%g,\"e2e_last\":%g,\"e2e_bad_first\":%zu,\"e2e_bad_last\":%zu,\"repeat_mismatch\":%zu}", - first ? "" : ",", m, k, n, pass ? "true" : "false", upload_ms, ok_calls, median, p90, mn, mx, - ok_calls ? chip_ns_sum / (uint64_t)ok_calls : 0, info.grid_x, info.grid_y, e2e_first, e2e_last, bad_first, bad_last, repeat_mismatch); - first = 0; - } - omega_gpu_matmul_set_oracle(1); - omega_gpu_tensor_free(t); - free(a); free(b); free(c); free(c_first); free(ah); - if (omega_gpu_matmul_is_blocked()) break; - } - free(copy); - if (out) { - fprintf(out, "],\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, - g_failed == 0 ? "OMEGA_GPU_MATMUL_TIMING_PASS" : "OMEGA_GPU_MATMUL_TIMING_FAIL"); - fclose(out); - } - return 0; -} - -/* --update (R3, omega #473): omega_gpu_tensor_update_* on the chip. Per shape (m rows of A, k x n weights): - * upload B1, matmul -> c1; update_f32(B2), matmul -> c2; fresh upload of B2, matmul -> c2f. c2 must equal c2f - * bit for bit and the double reference of A x B2 (0 elements at or beyond 1e-5); update_bf16(bf16(B1)) then - * matmul must give c1 back bit for bit. Timing, median of 5 each: update_f32, update_bf16, and the - * upload_f32 + free that an update replaces. */ -static const char *UPDATE_SHAPES = "16,768,2304;16,768,50304"; -static double median5(double *s) { qsort(s, 5, sizeof *s, cmp_double); return s[2]; } -static int update_mode(const char *shapes, const char *out_path) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_TENSOR_UPDATE_V1\",\"cta_budget\":%u,\"timed_calls\":5,\"shapes\":[", omega_gpu_matmul_cta_budget()); - char *copy = strdup(shapes); char *save = NULL; int first = 1; - for (char *tok = strtok_r(copy, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) { - unsigned m, k, n; - if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { printf("bad shape %s\n", tok); continue; } - size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n; - float *a = malloc(na * sizeof *a), *b1 = malloc(nb * sizeof *b1), *b2 = malloc(nb * sizeof *b2); - float *c1 = malloc(nc * sizeof *c1), *c2 = malloc(nc * sizeof *c2), *c2f = malloc(nc * sizeof *c2f), *c3 = malloc(nc * sizeof *c3); - uint16_t *b1h = malloc(nb * sizeof *b1h); - if (!a || !b1 || !b2 || !c1 || !c2 || !c2f || !c3 || !b1h) { printf("out of host memory\n"); return 2; } - uint32_t seed = 0x0bda7e00u ^ (m << 20) ^ (k << 10) ^ n; - fill(a, na, &seed); fill(b1, nb, &seed); fill(b2, nb, &seed); - for (size_t i = 0; i < nb; i++) b1h[i] = omega_fp32_to_bf16(b1[i]); - OmegaGpuTensor *t = NULL, *tf = NULL; - int rc = omega_gpu_tensor_upload_f32(k, n, b1, &t); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update %ux%ux%u: upload B1 rc=%s", m, k, n, omega_gpu_matmul_rc_name(rc)); - if (rc != OMEGA_GPU_MATMUL_OK) return 2; - rc = omega_gpu_matmul_resident_f32(m, a, t, c1, NULL); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "matmul B1 rc=%s", omega_gpu_matmul_rc_name(rc)); - rc = omega_gpu_tensor_update_f32(t, k, n, b2); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update_f32 rc=%s %s", omega_gpu_matmul_rc_name(rc), omega_gpu_matmul_last_error()); - rc = omega_gpu_matmul_resident_f32(m, a, t, c2, NULL); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "matmul after update rc=%s", omega_gpu_matmul_rc_name(rc)); - rc = omega_gpu_tensor_upload_f32(k, n, b2, &tf); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "fresh upload B2 rc=%s", omega_gpu_matmul_rc_name(rc)); - if (rc == OMEGA_GPU_MATMUL_OK) rc = omega_gpu_matmul_resident_f32(m, a, tf, c2f, NULL); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "matmul fresh B2 rc=%s", omega_gpu_matmul_rc_name(rc)); - omega_gpu_tensor_free(tf); - size_t vs_fresh = 0, back = 0, bad = 0; - for (size_t j = 0; j < nc; j++) vs_fresh += memcmp(&c2[j], &c2f[j], 4) != 0; - double e2e = e2e_max_rel(m, k, n, a, b2, c2, &bad); - rc = omega_gpu_tensor_update_bf16(t, k, n, b1h); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update_bf16 rc=%s %s", omega_gpu_matmul_rc_name(rc), omega_gpu_matmul_last_error()); - rc = omega_gpu_matmul_resident_f32(m, a, t, c3, NULL); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "matmul after update back rc=%s", omega_gpu_matmul_rc_name(rc)); - for (size_t j = 0; j < nc; j++) back += memcmp(&c3[j], &c1[j], 4) != 0; - CHECK(vs_fresh == 0, "update %ux%ux%u: %zu of %zu outputs differ from a fresh upload of the same values", m, k, n, vs_fresh, nc); - CHECK(bad == 0, "update %ux%ux%u: %zu outputs off the double reference (worst %g)", m, k, n, bad, e2e); - CHECK(back == 0, "update %ux%ux%u: %zu of %zu outputs differ after updating back to B1", m, k, n, back, nc); - double s_f32[5], s_bf16[5], s_up[5]; - int timed_ok = 1; - for (int i = 0; i < 5; i++) { - double t0 = now_ms(); timed_ok &= omega_gpu_tensor_update_f32(t, k, n, b2) == OMEGA_GPU_MATMUL_OK; s_f32[i] = now_ms() - t0; - t0 = now_ms(); timed_ok &= omega_gpu_tensor_update_bf16(t, k, n, b1h) == OMEGA_GPU_MATMUL_OK; s_bf16[i] = now_ms() - t0; - t0 = now_ms(); timed_ok &= omega_gpu_tensor_upload_f32(k, n, b2, &tf) == OMEGA_GPU_MATMUL_OK; omega_gpu_tensor_free(tf); s_up[i] = now_ms() - t0; - } - CHECK(timed_ok, "update %ux%ux%u: a timed call failed", m, k, n); - double mf = median5(s_f32), mb = median5(s_bf16), mu = median5(s_up); - int pass = vs_fresh == 0 && bad == 0 && back == 0 && timed_ok; - printf("%s update %ux%ux%u vs_fresh=%zu e2e=%g bad=%zu back=%zu update_f32_ms=%.2f update_bf16_ms=%.2f upload_f32_free_ms=%.2f\n", - pass ? "PASS" : "FAIL", m, k, n, vs_fresh, e2e, bad, back, mf, mb, mu); - if (out) { - fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"pass\":%s,\"vs_fresh_diff\":%zu,\"e2e_max_rel\":%g,\"e2e_bad\":%zu,\"back_diff\":%zu," - "\"update_f32_ms\":%.3f,\"update_bf16_ms\":%.3f,\"upload_f32_free_ms\":%.3f}", - first ? "" : ",", m, k, n, pass ? "true" : "false", vs_fresh, e2e, bad, back, mf, mb, mu); - first = 0; - } - omega_gpu_tensor_free(t); - free(a); free(b1); free(b2); free(c1); free(c2); free(c2f); free(c3); free(b1h); - if (omega_gpu_matmul_is_blocked()) break; - } - free(copy); - if (out) { - fprintf(out, "],\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, - g_failed == 0 ? "OMEGA_GPU_TENSOR_UPDATE_PASS" : "OMEGA_GPU_TENSOR_UPDATE_FAIL"); - fclose(out); - } - return 0; -} - -int main(int argc, char **argv) { - const char *out_path = NULL; - int host = 0, mutant = 0, do_timing = 0, do_update = 0, do_stages = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--mutant") == 0) mutant = 1; - else if (strcmp(argv[i], "--timing") == 0) do_timing = 1; - else if (strcmp(argv[i], "--update") == 0) do_update = 1; - else if (strcmp(argv[i], "--stages") == 0) do_stages = 1; - else if (strcmp(argv[i], "--cta-budget") == 0 && i + 1 < argc) omega_gpu_matmul_set_cta_budget((uint32_t)strtoul(argv[++i], NULL, 10)); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) { - if (omega_gpu_session_set_spin_us((uint32_t)strtoul(argv[++i], NULL, 10)) != 0) { fprintf(stderr, "--spin-us out of range\n"); return 2; } - } - else if (strcmp(argv[i], "--unroll") == 0 && i + 1 < argc) omega_gpu_matmul_test_set_unroll((uint32_t)strtoul(argv[++i], NULL, 10)); - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - } - const char *shapes = getenv("OMEGA_GPU_MATMUL_SHAPES"); - if (shapes && !*shapes) shapes = NULL; - int rc = 0; - if (host) host_only(); - else if (do_timing) rc = timing(shapes ? shapes : TIMING_SHAPES, out_path); - else if (do_update) rc = update_mode(shapes ? shapes : UPDATE_SHAPES, out_path); - else if (do_stages) rc = stages_profile(shapes ? shapes : STAGE_SHAPES, out_path); - else if (mutant) { omega_gpu_matmul_test_set_mutant(1); rc = chip_sweep(shapes ? shapes : MUTANT_SHAPES, out_path, 1); omega_gpu_matmul_test_set_mutant(0); } - else rc = chip_sweep(shapes ? shapes : DEFAULT_SHAPES, out_path, 0); - if (!host && !do_timing && !do_update && !do_stages && !mutant && !omega_gpu_matmul_is_blocked()) one_row_repack_checks(); - if (!omega_gpu_matmul_is_blocked()) omega_gpu_device_close(); - if (rc) return 2; - printf("%s: %d checks, %d failed%s\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed, mutant ? (g_failed ? " (mutant SURVIVED)" : " (mutant killed)") : ""); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_matmul_r4_receipt.c b/tests/gpu_matmul_r4_receipt.c deleted file mode 100644 index 7b96b511f..000000000 --- a/tests/gpu_matmul_r4_receipt.c +++ /dev/null @@ -1,393 +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. - */ - -/* gpu_matmul_r4_receipt: the sealed CTA-budget receipt omega_gpu_matmul_api.h asks for before - * OMEGA_GPU_MATMUL_MAX_CTAS moves (omega #473, R4). - * - * ./gpu_matmul_r4_receipt --host-only reference and comparator self-tests, no chip - * ./gpu_matmul_r4_receipt --out receipt.json chip receipt (run under the quiet flag) - * [--budgets 64,128,256,512,1024] [--repeats 3] [--threads 12] [--shapes "m,k,n;..."] - * - * Per shape: B is uploaded once (resident, bf16). The reference is the full m x n product of the same - * bf16 inputs in double on the host (threaded), with the accumulation scale (sum of |terms|) per element. - * Per budget: the CTA budget is set (kernel cache cleared), then 2 x repeats resident calls alternate - * -A, +A, -A, +A, ... (A negated by its sign bit, so the exact answer of each call is the negation of the - * previous one). Every element of every call is checked: - * - rep 0 of each sign: every element within 1e-5 of the accumulation scale of the reference - * (the rule of gpu_matmul_api_test.c e2e_max_rel), and finite; - * - later repeats: bit-identical to rep 0 of the same sign; - * - I42 (cut 1: grids of 128 CTAs and above lost output with the single-tile kernel): an element still - * holding the previous call's bits (nonzero) is stale, i.e. not written by this call. Alternating the - * sign makes stale output visible; the budget sequence starts with -A because the previous budget - * ended with +A. The device-side sentinel check (OUTPUT_UNCHANGED) runs inside the API as well. - * Negative controls: the comparator flags a one-element perturbation and a planted stale element; the - * chip mutant kernel (last K step dropped) at the largest budget must be flagged by the full comparison. - * Timing: chip = OmegaGpuMatmulInfo.elapsed_ns, call = call_ns; median over all 2 x repeats calls. - * The best sealed budget is the one with every shape PASS and the least summed median chip time. - */ -#include "omega_gpu_matmul_api.h" -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_matmul.h" -#include "sha256.h" -#include -#include -#include -#include -#include - -#define TOL 1e-5 -#define MAX_BUDGETS 16 -#define NAN_FILL 0x7fc0deadu - -static const char *DEFAULT_SHAPES = - /* the five training shapes (omega #473), then two I42 shapes on the single-tile kernel (rt = ct = 1): - * decode 1 x 2048 x 8192 (grid_x up to the budget) and 7 row tiles (112 rows) */ - "8192,768,2304;8192,768,768;8192,768,3072;8192,3072,768;1024,768,50304;1,2048,8192;112,768,3072"; -static const uint32_t DEFAULT_BUDGETS[] = { 64, 128, 256, 512, 1024 }; - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static inline double absd(double x) { return x < 0.0 ? -x : x; } -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static uint32_t fbits(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static float bitsf(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static int is_finite(float f) { return (fbits(f) & 0x7f800000u) != 0x7f800000u; } - -/* inputs as gpu_matmul_api_test.c fill(): values in [-1, 1] at 1/1000 steps, rounded to bf16 */ -static void fill_bf16(uint16_t *x, size_t n, uint32_t *seed) { - for (size_t i = 0; i < n; i++) x[i] = omega_fp32_to_bf16(((float)(lcg(seed) % 2001) - 1000.0f) / 1000.0f); -} - -/* ---- reference: acc[i*n+j] = sum_t a[i,t] b[t,j] in double, sc = max(sum |terms|, 1e-6) ---- */ -typedef struct { - uint32_t m, k, n, r0, r1; - const double *ad, *btd; /* A m x k, B transposed n x k, both exact bf16 values in double */ - double *acc, *sc; -} RefJob; - -static void *ref_rows(void *p) { - RefJob *J = p; - const uint32_t k = J->k, n = J->n; - for (uint32_t i = J->r0; i < J->r1; i++) { - const double *ar = J->ad + (size_t)i * k; - for (uint32_t j = 0; j < n; j++) { - const double *br = J->btd + (size_t)j * k; - double s0 = 0, s1 = 0, s2 = 0, s3 = 0, q0 = 0, q1 = 0, q2 = 0, q3 = 0; - uint32_t t = 0; - for (; t + 4 <= k; t += 4) { - double p0 = ar[t] * br[t], p1 = ar[t + 1] * br[t + 1], p2 = ar[t + 2] * br[t + 2], p3 = ar[t + 3] * br[t + 3]; - s0 += p0; s1 += p1; s2 += p2; s3 += p3; - q0 += absd(p0); q1 += absd(p1); q2 += absd(p2); q3 += absd(p3); - } - for (; t < k; t++) { double p0 = ar[t] * br[t]; s0 += p0; q0 += absd(p0); } - const double q = (q0 + q1) + (q2 + q3); - J->acc[(size_t)i * n + j] = (s0 + s1) + (s2 + s3); - J->sc[(size_t)i * n + j] = q > 1e-6 ? q : 1e-6; - } - } - return NULL; -} - -static int reference(uint32_t m, uint32_t k, uint32_t n, const uint16_t *a, const uint16_t *b, unsigned threads, double *acc, double *sc) { - double *ad = malloc((size_t)m * k * sizeof *ad), *btd = malloc((size_t)n * k * sizeof *btd); - if (!ad || !btd) { free(ad); free(btd); return -1; } - for (size_t i = 0; i < (size_t)m * k; i++) ad[i] = omega_bf16_to_fp32(a[i]); - for (uint32_t t = 0; t < k; t++) - for (uint32_t j = 0; j < n; j++) btd[(size_t)j * k + t] = omega_bf16_to_fp32(b[(size_t)t * n + j]); - if (threads < 1) threads = 1; - if (threads > 64) threads = 64; - if (threads > m) threads = m; - pthread_t th[64]; RefJob J[64]; - int rc = 0; - for (unsigned w = 0; w < threads; w++) { - J[w] = (RefJob){ m, k, n, (uint32_t)((uint64_t)m * w / threads), (uint32_t)((uint64_t)m * (w + 1) / threads), ad, btd, acc, sc }; - if (pthread_create(&th[w], NULL, ref_rows, &J[w]) != 0) { ref_rows(&J[w]); th[w] = 0; } - } - for (unsigned w = 0; w < threads; w++) if (th[w]) pthread_join(th[w], NULL); - free(ad); free(btd); - return rc; -} - -/* ---- full comparison of one output against sign * reference ---- */ -typedef struct { size_t mismatches, nonfinite; double max_rel; } Cmp; - -static Cmp compare_full(size_t cnt, const float *c, const double *acc, const double *sc, double sign) { - Cmp r = { 0, 0, 0.0 }; - for (size_t i = 0; i < cnt; i++) { - if (!is_finite(c[i])) { r.nonfinite++; r.mismatches++; continue; } - const double rel = absd((double)c[i] - sign * acc[i]) / sc[i]; - if (rel > r.max_rel) r.max_rel = rel; - if (rel > TOL) r.mismatches++; - } - return r; -} - -static size_t count_bit_diff(size_t cnt, const float *x, const float *y) { - size_t d = 0; - for (size_t i = 0; i < cnt; i++) d += fbits(x[i]) != fbits(y[i]); - return d; -} - -/* elements still holding the previous call's bits (the exact answer flipped sign, so only an element - * whose answer is exactly zero may legitimately repeat; those are excluded) */ -static size_t count_stale(size_t cnt, const float *cur, const float *prev) { - size_t s = 0; - for (size_t i = 0; i < cnt; i++) s += fbits(cur[i]) == fbits(prev[i]) && (fbits(cur[i]) & 0x7fffffffu) != 0; - return s; -} - -static size_t count_not_negation(size_t cnt, const float *pos, const float *neg) { - size_t d = 0; - for (size_t i = 0; i < cnt; i++) d += fbits(pos[i]) != (fbits(neg[i]) ^ 0x80000000u); - return d; -} - -/* sha256 of the output bytes (first 16 hex digits), so separate runs can be compared bit for bit */ -static void digest16(const float *c, size_t cnt, char hex[17]) { - uint8_t d[SHA256_DIGEST_SIZE]; - sha256_hash((const uint8_t *)c, cnt * sizeof *c, d); - for (int i = 0; i < 8; i++) snprintf(hex + 2 * i, 3, "%02x", d[i]); -} - -static int cmp_u64(const void *x, const void *y) { uint64_t a = *(const uint64_t *)x, b = *(const uint64_t *)y; return a < b ? -1 : a > b; } -static uint64_t median_u64(uint64_t *v, size_t n) { qsort(v, n, sizeof *v, cmp_u64); return n ? v[n / 2] : 0; } - -/* comparator self-test on data the caller has (exact reference rounded to f32 is the "chip" output) */ -static void comparator_controls(uint32_t m, uint32_t n, const double *acc, const double *sc, const char *tag, FILE *out) { - const size_t cnt = (size_t)m * n; - float *c = malloc(cnt * sizeof *c), *prev = malloc(cnt * sizeof *prev); - if (!c || !prev) { CHECK(0, "%s comparator controls: host memory", tag); free(c); free(prev); return; } - for (size_t i = 0; i < cnt; i++) { c[i] = (float)acc[i]; prev[i] = -(float)acc[i]; } - Cmp clean = compare_full(cnt, c, acc, sc, 1.0); - const size_t at = cnt / 2 + 3; - c[at] = (float)(acc[at] + 4.0 * TOL * sc[at]); - Cmp pert = compare_full(cnt, c, acc, sc, 1.0); - c[at] = (float)acc[at]; - const size_t at2 = cnt - 1; - float keep = c[at2]; - if (acc[at2] == 0.0) { c[at2] = 1.0f; prev[at2] = 1.0f; } else c[at2] = prev[at2]; - const size_t stale = count_stale(cnt, c, prev); - c[at2] = keep; - c[0] = bitsf(NAN_FILL); - Cmp nan = compare_full(cnt, c, acc, sc, 1.0); - CHECK(clean.mismatches == 0, "%s control: exact reference must compare clean (%zu)", tag, clean.mismatches); - CHECK(pert.mismatches == 1, "%s control: one perturbed element must be flagged (%zu)", tag, pert.mismatches); - CHECK(stale == 1, "%s control: one planted stale element must be flagged (%zu)", tag, stale); - CHECK(nan.mismatches == 1 && nan.nonfinite == 1, "%s control: one unwritten (NaN) element must be flagged (%zu)", tag, nan.mismatches); - printf("%s comparator controls: clean=%zu perturbed=%zu stale=%zu unwritten=%zu\n", tag, clean.mismatches, pert.mismatches, stale, nan.mismatches); - if (out) fprintf(out, "\"comparator_control\":{\"shape\":\"%s\",\"clean_mismatches\":%zu,\"perturbed_flagged\":%zu,\"stale_flagged\":%zu,\"unwritten_flagged\":%zu},", - tag, clean.mismatches, pert.mismatches, stale, nan.mismatches); - free(c); free(prev); -} - -static int host_only(unsigned threads) { - /* threaded reference against a naive single-thread double loop, and the comparator controls */ - const uint32_t m = 37, k = 80, n = 52; - uint16_t *a = malloc((size_t)m * k * 2), *b = malloc((size_t)k * n * 2); - double *acc = malloc((size_t)m * n * 8), *sc = malloc((size_t)m * n * 8); - uint32_t seed = 4730u; - fill_bf16(a, (size_t)m * k, &seed); fill_bf16(b, (size_t)k * n, &seed); - CHECK(reference(m, k, n, a, b, threads, acc, sc) == 0, "reference ran"); - double worst = 0.0; - for (uint32_t i = 0; i < m; i++) - for (uint32_t j = 0; j < n; j++) { - double s = 0, q = 0; - for (uint32_t t = 0; t < k; t++) { double p = (double)omega_bf16_to_fp32(a[i * k + t]) * omega_bf16_to_fp32(b[t * n + j]); s += p; q += absd(p); } - double d = absd(s - acc[i * n + j]) / (q > 1e-6 ? q : 1e-6); - if (d > worst) worst = d; - if (absd(q - sc[i * n + j]) > 1e-12 * (q > 1.0 ? q : 1.0)) worst = 1.0; - } - CHECK(worst < 1e-12, "threaded reference equals the naive loop (worst rel %g)", worst); - comparator_controls(m, n, acc, sc, "host 37x80x52", NULL); - /* sign-bit negation of bf16 A negates the reference exactly */ - for (size_t i = 0; i < (size_t)m * k; i++) a[i] ^= 0x8000u; - double *acc2 = malloc((size_t)m * n * 8), *sc2 = malloc((size_t)m * n * 8); - reference(m, k, n, a, b, threads, acc2, sc2); - size_t notneg = 0; - for (size_t i = 0; i < (size_t)m * n; i++) notneg += acc2[i] != -acc[i] || sc2[i] != sc[i]; - CHECK(notneg == 0, "negated A gives the exact negated reference (%zu differ)", notneg); - free(a); free(b); free(acc); free(sc); free(acc2); free(sc2); - printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); - return g_failed ? 1 : 0; -} - -typedef struct { uint64_t chip_med_ns; int pass; } Cell; - -int main(int argc, char **argv) { - const char *out_path = NULL, *shapes = DEFAULT_SHAPES; - uint32_t budgets[MAX_BUDGETS]; unsigned nb = 0; - unsigned repeats = 3, threads = 12; - int host = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--shapes") == 0 && i + 1 < argc) shapes = argv[++i]; - else if (strcmp(argv[i], "--repeats") == 0 && i + 1 < argc) repeats = (unsigned)strtoul(argv[++i], NULL, 10); - else if (strcmp(argv[i], "--threads") == 0 && i + 1 < argc) threads = (unsigned)strtoul(argv[++i], NULL, 10); - else if (strcmp(argv[i], "--budgets") == 0 && i + 1 < argc) { - char *s = argv[++i]; - while (*s && nb < MAX_BUDGETS) { budgets[nb++] = (uint32_t)strtoul(s, &s, 10); if (*s == ',') s++; else break; } - } else { fprintf(stderr, "unknown argument %s\n", argv[i]); return 2; } - } - if (host) return host_only(threads); - if (!nb) { nb = sizeof DEFAULT_BUDGETS / sizeof DEFAULT_BUDGETS[0]; memcpy(budgets, DEFAULT_BUDGETS, sizeof DEFAULT_BUDGETS); } - if (repeats < 1) repeats = 1; - if (repeats > 32) repeats = 32; /* 2 x repeats calls fit the per-budget timing arrays */ - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) { - fprintf(out, "{\"schema\":\"OMEGA_GPU_MATMUL_R4_RECEIPT_V1\",\"default_budget\":%u,\"repeats\":%u,\"tol_rel_scale\":%g,\"budgets\":[", OMEGA_GPU_MATMUL_MAX_CTAS, repeats, TOL); - for (unsigned b = 0; b < nb; b++) fprintf(out, "%s%u", b ? "," : "", budgets[b]); - fprintf(out, "],"); - } - Cell cells[32][MAX_BUDGETS]; memset(cells, 0, sizeof cells); - char shape_names[32][40]; unsigned ns = 0; - int controls_done = 0, mutant_done = 0; - if (out) fprintf(out, "\"runs\":["); - int first_run = 1; - char *copy = strdup(shapes), *save = NULL; - for (char *tok = strtok_r(copy, ";", &save); tok && ns < 32 && !omega_gpu_matmul_is_blocked(); tok = strtok_r(NULL, ";", &save)) { - unsigned m, k, n; - if (sscanf(tok, "%u,%u,%u", &m, &k, &n) != 3) { CHECK(0, "bad shape %s", tok); continue; } - snprintf(shape_names[ns], sizeof shape_names[ns], "%ux%ux%u", m, k, n); - const size_t na = (size_t)m * k, nbb = (size_t)k * n, cnt = (size_t)m * n; - uint16_t *a = malloc(na * 2), *an = malloc(na * 2), *b = malloc(nbb * 2); - double *acc = malloc(cnt * 8), *sc = malloc(cnt * 8); - float *pos0 = malloc(cnt * 4), *neg0 = malloc(cnt * 4), *tmp[2] = { malloc(cnt * 4), malloc(cnt * 4) }, *base_pos = malloc(cnt * 4); - if (!a || !an || !b || !acc || !sc || !pos0 || !neg0 || !tmp[0] || !tmp[1] || !base_pos) { CHECK(0, "host memory for %s", tok); break; } - uint32_t seed = 0x5eed0000u ^ (m << 20) ^ (k << 10) ^ n; - fill_bf16(a, na, &seed); fill_bf16(b, nbb, &seed); - for (size_t i = 0; i < na; i++) an[i] = a[i] ^ 0x8000u; - uint32_t rt, ct; omega_matmul_frag_block_shape((m + 15u) / 16u, (n + 7u) / 8u, &rt, &ct); - const double flop = 2.0 * m * k * n; - if (reference(m, k, n, a, b, threads, acc, sc) != 0) { CHECK(0, "reference %s: host memory", tok); break; } - if (!controls_done && m == 8192 && n == 768 && k == 768) { - if (out) { fprintf(out, "%s{\"control\":true,", first_run ? "" : ","); first_run = 0; } - comparator_controls(m, n, acc, sc, shape_names[ns], out); - if (out) fprintf(out, "\"pass\":%s}", g_failed ? "false" : "true"); - controls_done = 1; - } - OmegaGpuTensor *t = NULL; - int urc = omega_gpu_tensor_upload_bf16(k, n, b, &t); - CHECK(urc == OMEGA_GPU_MATMUL_OK, "upload %s rc=%s (%s)", tok, omega_gpu_matmul_rc_name(urc), omega_gpu_matmul_last_error()); - if (urc != OMEGA_GPU_MATMUL_OK) break; - float *prev = NULL; - for (unsigned bi = 0; bi < nb; bi++) { - omega_gpu_matmul_set_cta_budget(budgets[bi]); - const unsigned calls = 2u * repeats; - uint64_t chip[64], call[64]; int rcs_ok = 1, hit_after_first = 1; - size_t rep_diff = 0, stale_total = 0, stale_max = 0; - Cmp cp = { 0, 0, 0 }, cn = { 0, 0, 0 }; - OmegaGpuMatmulInfo info; memset(&info, 0, sizeof info); - for (unsigned ci = 0; ci < calls && ci < 64; ci++) { - const int neg = (ci % 2u) == 0, rep = (int)(ci / 2u); - float *dst = rep == 0 ? (neg ? neg0 : pos0) : tmp[ci % 2u]; - for (size_t i = 0; i < cnt; i++) dst[i] = bitsf(NAN_FILL); - int rc = omega_gpu_matmul_resident_bf16(m, neg ? an : a, t, dst, &info); - chip[ci] = info.elapsed_ns; call[ci] = info.call_ns; - if (rc != OMEGA_GPU_MATMUL_OK) { - rcs_ok = 0; - CHECK(0, "%s budget %u call %u rc=%s (%s)", tok, budgets[bi], ci, omega_gpu_matmul_rc_name(rc), omega_gpu_matmul_last_error()); - break; - } - if (ci > 0 && !info.kernel_cache_hit) hit_after_first = 0; - if (prev) { size_t s = count_stale(cnt, dst, prev); stale_total += s; if (s > stale_max) stale_max = s; } - if (rep == 0) { - if (neg) cn = compare_full(cnt, dst, acc, sc, -1.0); else cp = compare_full(cnt, dst, acc, sc, 1.0); - } else rep_diff += count_bit_diff(cnt, dst, neg ? neg0 : pos0); - prev = dst; - } - const unsigned done = rcs_ok ? calls : 0; - uint64_t chip_s[64], call_s[64]; - memcpy(chip_s, chip, sizeof chip); memcpy(call_s, call, sizeof call); - const uint64_t chip_med = done ? median_u64(chip_s, done) : 0, call_med = done ? median_u64(call_s, done) : 0; - const size_t neg_exact = rcs_ok ? count_not_negation(cnt, pos0, neg0) : cnt; - size_t cross = 0; - if (rcs_ok) { if (bi == 0) memcpy(base_pos, pos0, cnt * 4); else cross = count_bit_diff(cnt, pos0, base_pos); } - char dig[17] = "-"; - if (rcs_ok) digest16(pos0, cnt, dig); - const uint32_t ctas = info.grid_x * info.grid_y; - const int pass = rcs_ok && cp.mismatches == 0 && cn.mismatches == 0 && rep_diff == 0 && stale_total == 0; - CHECK(pass, "%s budget %u: rc_ok=%d pos_mism=%zu neg_mism=%zu repeat_diff=%zu stale=%zu", tok, budgets[bi], rcs_ok, cp.mismatches, cn.mismatches, rep_diff, stale_total); - cells[ns][bi].pass = pass; cells[ns][bi].chip_med_ns = chip_med; - const double tflops = chip_med ? flop / (double)chip_med / 1e3 : 0.0; - printf("%s %s budget=%u grid=%ux%u ctas=%u launches=%u rt=%u ct=%u i42_regime=%d chip_med_ms=%.3f call_med_ms=%.3f tflops_chip=%.3f " - "elements=%zu pos_mism=%zu neg_mism=%zu max_rel=%.3g repeat_bitdiff=%zu stale=%zu neg_exact_diff=%zu vs_first_budget_bitdiff=%zu sha=%s cache_hit=%d\n", - pass ? "PASS" : "FAIL", tok, budgets[bi], info.grid_x, info.grid_y, ctas, info.chip_calls, rt, ct, ctas >= 128, - chip_med / 1e6, call_med / 1e6, tflops, cnt, cp.mismatches, cn.mismatches, cp.max_rel > cn.max_rel ? cp.max_rel : cn.max_rel, - rep_diff, stale_total, neg_exact, cross, dig, hit_after_first); - if (out) { - fprintf(out, "%s{\"m\":%u,\"k\":%u,\"n\":%u,\"budget\":%u,\"pass\":%s,\"grid_x\":%u,\"grid_y\":%u,\"ctas_per_launch\":%u,\"launches\":%u," - "\"rt\":%u,\"ct\":%u,\"single_tile_kernel\":%s,\"i42_regime\":%s,\"calls\":%u,\"elements_per_call\":%zu," - "\"pos_mismatches\":%zu,\"neg_mismatches\":%zu,\"nonfinite\":%zu,\"max_rel\":%.4g,\"repeat_bitdiff\":%zu," - "\"stale_elements\":%zu,\"stale_max_per_call\":%zu,\"neg_exact_negation_diff\":%zu,\"vs_first_budget_bitdiff\":%zu," - "\"pos_output_sha256_16\":\"%s\",\"cache_hit_after_first\":%s,\"chip_median_ns\":%" PRIu64 ",\"call_median_ns\":%" PRIu64 ",\"tflops_chip\":%.4f,\"chip_ns\":[", - first_run ? "" : ",", m, k, n, budgets[bi], pass ? "true" : "false", info.grid_x, info.grid_y, ctas, info.chip_calls, - rt, ct, rt == 1 && ct == 1 ? "true" : "false", ctas >= 128 ? "true" : "false", done, cnt, - cp.mismatches, cn.mismatches, cp.nonfinite + cn.nonfinite, cp.max_rel > cn.max_rel ? cp.max_rel : cn.max_rel, rep_diff, - stale_total, stale_max, neg_exact, cross, dig, hit_after_first ? "true" : "false", chip_med, call_med, tflops); - for (unsigned ci = 0; ci < done; ci++) fprintf(out, "%s%" PRIu64, ci ? "," : "", chip[ci]); - fprintf(out, "],\"call_ns\":["); - for (unsigned ci = 0; ci < done; ci++) fprintf(out, "%s%" PRIu64, ci ? "," : "", call[ci]); - fprintf(out, "]}"); - first_run = 0; - } - fflush(stdout); - if (omega_gpu_matmul_is_blocked()) break; - } - /* negative control on the chip: the mutant kernel at the largest budget must be flagged */ - if (!mutant_done && m == 8192 && k == 768 && n == 768 && !omega_gpu_matmul_is_blocked()) { - omega_gpu_matmul_set_cta_budget(budgets[nb - 1]); - omega_gpu_matmul_test_set_mutant(1); - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_bf16(m, a, t, pos0, &info); - Cmp mc = rc == OMEGA_GPU_MATMUL_OK ? compare_full(cnt, pos0, acc, sc, 1.0) : (Cmp){ 0, 0, 0 }; - omega_gpu_matmul_test_set_mutant(0); - const int caught = rc != OMEGA_GPU_MATMUL_OK || mc.mismatches > 0; - CHECK(caught, "mutant at budget %u NOT caught by the full comparison", budgets[nb - 1]); - printf("%s mutant control %s budget=%u rc=%s flagged=%zu of %zu\n", caught ? "KILLED" : "SURVIVED", tok, budgets[nb - 1], omega_gpu_matmul_rc_name(rc), mc.mismatches, cnt); - if (out) { fprintf(out, ",{\"mutant_control\":true,\"m\":%u,\"k\":%u,\"n\":%u,\"budget\":%u,\"rc\":\"%s\",\"flagged\":%zu,\"elements\":%zu,\"killed\":%s}", - m, k, n, budgets[nb - 1], omega_gpu_matmul_rc_name(rc), mc.mismatches, cnt, caught ? "true" : "false"); } - mutant_done = 1; - } - omega_gpu_tensor_free(t); - free(a); free(an); free(b); free(acc); free(sc); free(pos0); free(neg0); free(tmp[0]); free(tmp[1]); free(base_pos); - ns++; - } - free(copy); - omega_gpu_matmul_set_cta_budget(0); - CHECK(controls_done && mutant_done, "negative controls ran (comparator %d, mutant %d)", controls_done, mutant_done); - /* best sealed budget: every shape PASS, least summed median chip time over every shape in the run (the default - * list is the five training shapes plus 1x2048x8192 and 112x768x3072) */ - int best = -1; uint64_t best_sum = 0; - if (out) fprintf(out, "],\"budget_summary\":["); - for (unsigned bi = 0; bi < nb; bi++) { - int all = ns > 0; uint64_t sum = 0; - for (unsigned s = 0; s < ns; s++) { all &= cells[s][bi].pass; sum += cells[s][bi].chip_med_ns; } - printf("budget %u: %s, summed median chip %.3f ms over %u shapes\n", budgets[bi], all ? "SEALED" : "NOT SEALED", sum / 1e6, ns); - if (out) fprintf(out, "%s{\"budget\":%u,\"sealed\":%s,\"sum_chip_median_ns\":%" PRIu64 "}", bi ? "," : "", budgets[bi], all ? "true" : "false", sum); - if (all && (best < 0 || sum < best_sum)) { best = (int)bi; best_sum = sum; } - } - const int ok = g_failed == 0 && best >= 0 && !omega_gpu_matmul_is_blocked(); - printf("best sealed budget: %d\n%s: %d checks, %d failed\n", best >= 0 ? (int)budgets[best] : -1, ok ? "PASS" : "FAIL", g_checks, g_failed); - if (out) { - fprintf(out, "],\"best_sealed_budget\":%d,\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", best >= 0 ? (int)budgets[best] : -1, - omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, ok ? "OMEGA_GPU_MATMUL_R4_SEALED" : "OMEGA_GPU_MATMUL_R4_FAIL"); - fclose(out); - } - return ok ? 0 : 1; -} diff --git a/tests/gpu_moe_window_test.c b/tests/gpu_moe_window_test.c deleted file mode 100644 index fa47ee687..000000000 --- a/tests/gpu_moe_window_test.c +++ /dev/null @@ -1,299 +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. - */ - -/* gpu_moe_window_test: OWN-30B cut 2 gate for omega_gpu_moe_api (column windows over a resident tensor). - * - * ./gpu_moe_window_test --host-only argument refusals (alignment rule fail-closed) and the packed - * window byte rule (a window's bytes in the packed tensor equal - * the pack of the sub-matrix; one tile of skew differs); no chip - * ./gpu_moe_window_test --out receipt.json chip gate: for every case the window result equals the - * whole-tensor (omega_gpu_matmul_resident_*) columns bit for bit - * and the double oracle; repeat call is a cache hit and identical; - * the multi-window call equals the single windows; negative - * controls (wrong window by one tile, wrong kernel) are caught; - * timing of 8 expert windows per call (the Stage A decode shape) - * ./gpu_moe_window_test --cta-budget N --spin-us N --calls N --small (knobs; --small skips the 128-expert tensors) - */ -#include "omega_gpu_moe_api.h" -#include "omega_gpu_session.h" -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_matmul.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static void fill(float *a, size_t n, uint32_t *seed) { for (size_t i = 0; i < n; i++) a[i] = ((float)(lcg(seed) % 2001) - 1000.0f) / 1000.0f; } -static float bf2f(uint16_t b) { uint32_t u = (uint32_t)b << 16; float f; memcpy(&f, &u, 4); return f; } -static int cmp_double(const void *x, const void *y) { double a = *(const double *)x, b = *(const double *)y; return a < b ? -1 : a > b; } - -/* double oracle of the window: error relative to the accumulation scale, count at or beyond 1e-5 */ -static double window_oracle(uint32_t m, uint32_t k, uint32_t n, const uint16_t *a, const uint16_t *b, uint32_t col0, uint32_t cols, const float *c, size_t *bad) { - double worst = 0.0; size_t nbad = 0; - for (size_t i = 0; i < m; i++) for (size_t j = 0; j < cols; j++) { - double acc = 0.0, scale = 0.0; - for (size_t t = 0; t < k; t++) { double p = (double)bf2f(a[i * k + t]) * (double)bf2f(b[t * n + col0 + j]); acc += p; scale += fabs(p); } - double rel = fabs(acc - (double)c[i * cols + j]) / (scale > 1e-6 ? scale : 1e-6); - if (rel > worst) worst = rel; - if (rel >= 1e-5) nbad++; - } - if (bad) *bad = nbad; - return worst; -} - -/* ------------------------------------------------------------------ host only */ -static void host_only(void) { - /* the packed window byte rule: for a tile-aligned col0, the bytes of the packed tensor from - * omega_gpu_moe_window_byte_offset(kp, col0) are the pack of B[:, col0 .. col0 + wnp); moving one - * tile (the wrong-window control) changes them */ - struct { uint32_t k, n, col0, cols; } sh[] = { { 48, 1000, 8, 13 }, { 48, 1000, 792, 200 }, { 2048, 6144, 1536, 1536 }, { 768, 8192, 6144, 2048 }, { 40, 24, 16, 8 } }; - for (size_t s = 0; s < sizeof sh / sizeof sh[0]; s++) { - const uint32_t k = sh[s].k, n = sh[s].n, col0 = sh[s].col0, cols = sh[s].cols; - const uint32_t kp = (k + 15) / 16 * 16, np = (n + 7) / 8 * 8, NT = np / 8, wnp = (cols + 7) / 8 * 8, WT = wnp / 8; - uint16_t *b = malloc((size_t)k * n * 2), *full = malloc((size_t)kp * np * 2), *win = malloc((size_t)kp * wnp * 2), *sub = malloc((size_t)k * wnp * 2); - uint32_t seed = 11 + (uint32_t)s; - for (size_t i = 0; i < (size_t)k * n; i++) b[i] = (uint16_t)(1 + lcg(&seed) % 60000); - omega_matmul_frag_pack_b(b, k, n, kp, 0, NT, full); - /* the sub-matrix B[:, col0 .. col0 + real) where real = min(wnp, n - col0): past the real columns the - * tensor's padding is zero, which the sub-matrix pack reproduces by having only `real` columns */ - const uint32_t real = n - col0 < wnp ? n - col0 : wnp; - for (uint32_t r = 0; r < k; r++) for (uint32_t j = 0; j < real; j++) sub[(size_t)r * real + j] = b[(size_t)r * n + col0 + j]; - omega_matmul_frag_pack_b(sub, k, real, kp, 0, WT, win); - const uint64_t off = omega_gpu_moe_window_byte_offset(kp, col0); - CHECK(off == (uint64_t)(col0 / 8) * kp * 8 * 2, "offset arithmetic k=%u col0=%u", k, col0); - CHECK(memcmp((const uint8_t *)full + off, win, (size_t)kp * wnp * 2) == 0, "window bytes k=%u n=%u col0=%u cols=%u equal the sub-matrix pack", k, n, col0, cols); - /* wrong window: one tile of skew (either way) must differ */ - int differs = 1; - if (col0 / 8 + 1 + WT <= NT) differs = memcmp((const uint8_t *)full + off + (size_t)kp * 8 * 2, win, (size_t)kp * wnp * 2) != 0; - else differs = memcmp((const uint8_t *)full + off - (size_t)kp * 8 * 2, win, (size_t)kp * wnp * 2) != 0; - CHECK(differs, "window bytes k=%u col0=%u: one tile of skew differs (wrong-window control)", k, col0); - free(b); free(full); free(win); free(sub); - } - /* refusals: nothing below opens the device (the alignment rule is checked before the lock) */ - float a[64] = { 0 }, c[64]; - uint32_t col0s[2] = { 0, 8 }; - CHECK(omega_gpu_matmul_resident_window_f32(1, NULL, NULL, 0, 8, c, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "NULL a / tensor refused"); - CHECK(omega_gpu_matmul_resident_window_f32(0, a, NULL, 0, 8, c, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "m = 0 refused"); - CHECK(omega_gpu_matmul_resident_windows_f32(1, a, NULL, 0, col0s, 8, c, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "nwin = 0 refused"); - CHECK(omega_gpu_moe_tensor_upload_bf16(0, 8, (const uint16_t *)a, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "upload k = 0 / NULL out refused"); - OmegaGpuMoeTensor *t = NULL; - CHECK(omega_gpu_moe_tensor_upload_bf16(16, OMEGA_BW_MATMUL_MAX_N + 8, (const uint16_t *)a, &t) == OMEGA_GPU_MATMUL_TOO_LARGE && t == NULL, "upload n past the envelope refused"); - CHECK(omega_gpu_moe_reserve(0, 16, 16, 0) == OMEGA_GPU_MATMUL_BAD_ARGS, "reserve zero bound refused"); - CHECK(omega_gpu_moe_prepare(1, 16, OMEGA_BW_MATMUL_MAX_N + 8) == OMEGA_GPU_MATMUL_TOO_LARGE, "prepare past the envelope refused"); - uint32_t kk, nn; omega_gpu_moe_tensor_shape(NULL, &kk, &nn); - CHECK(kk == 0 && nn == 0, "shape of NULL is 0 x 0"); - omega_gpu_moe_tensor_free(NULL); - printf("host-only: alignment refusals that need a tensor (col0 %% 8, window past n) run in the chip gate\n"); -} - -/* ------------------------------------------------------------------ chip */ -typedef struct { uint32_t k, n, m, cols, nwin; const char *name; int big; } Case; - -static int chip(const char *out_path, int calls, int small) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_MOE_WINDOW_V1\",\"cta_budget\":%u,\"spin_us\":%u,\"calls\":%d,\"cases\":[", - omega_gpu_moe_cta_budget(), omega_gpu_session_spin_us(), calls); - const Case cases[] = { - { 48, 1000, 1, 13, 3, "small_m1_unaligned_cols", 0 }, - { 48, 1000, 5, 200, 2, "small_m5", 0 }, - { 2048, 1536 * 16, 1, 1536, 8, "gate_up_16_experts", 0 }, - { 2048, 1536 * 128, 1, 1536, 8, "gate_up_128_experts", 1 }, - { 768, 2048 * 128, 1, 2048, 8, "down_128_experts", 1 }, - { 2048, 1536 * 16, 16, 1536, 8, "gate_up_16_experts_m16", 0 }, - /* one variable: the same 1536-wide window on a standalone one-expert tensor (one spare tile so the - * skew control stays inside the allocation); compares against the window inside the 16/128-expert tensors */ - { 2048, 1536 + 8, 1, 1536, 1, "gate_up_1_expert_standalone", 0 }, - { 768, 2048 + 8, 1, 2048, 1, "down_1_expert_standalone", 0 }, - }; - int first = 1; - for (size_t ci = 0; ci < sizeof cases / sizeof cases[0]; ci++) { - const Case *cs = &cases[ci]; - if (small && cs->big) continue; - const uint32_t k = cs->k, n = cs->n, m = cs->m, cols = cs->cols, nwin = cs->nwin; - const uint32_t kp = (k + 15) / 16 * 16, wnp = (cols + 7) / 8 * 8; - printf("== %s: k=%u n=%u m=%u cols=%u windows=%u\n", cs->name, k, n, m, cols, nwin); - size_t na = (size_t)m * k, nb = (size_t)k * n, nc = (size_t)m * n, nw = (size_t)m * cols; - float *a = malloc(na * 4), *whole = malloc(nc * 4), *cw = malloc(nw * 4), *cw2 = malloc(nw * 4), *multi = malloc(nw * 4 * nwin); - uint16_t *ah = malloc(na * 2), *bh = malloc(nb * 2); - if (!a || !whole || !cw || !cw2 || !multi || !ah || !bh) { printf("out of host memory\n"); return 2; } - uint32_t seed = 0x30b0000u ^ (k << 8) ^ n ^ m; - fill(a, na, &seed); - for (size_t i = 0; i < na; i++) ah[i] = omega_fp32_to_bf16(a[i]); - { float *bt = malloc((size_t)1 << 20); size_t done = 0; /* bf16 B in 256K-element chunks, no k x n f32 copy */ - while (done < nb) { size_t c = nb - done < (1u << 18) ? nb - done : (1u << 18); fill(bt, c, &seed); for (size_t i = 0; i < c; i++) bh[done + i] = omega_fp32_to_bf16(bt[i]); done += c; } - free(bt); } - /* the 8 windows: distinct tile-aligned expert slots, never the last tile (the skew control moves one tile up) */ - uint32_t col0[8]; const uint32_t slots = n / cols; - for (uint32_t w = 0; w < nwin; w++) { uint32_t s; int dup; do { s = lcg(&seed) % (slots > 1 ? slots - 1 : 1); dup = 0; for (uint32_t v = 0; v < w; v++) if (col0[v] == s * cols) dup = 1; } while (dup); col0[w] = s * cols; } - if (cs->cols == 13) { col0[0] = 8; col0[1] = 16; col0[2] = 976; } /* 976 + 13 = 989 < 1000, inside the real columns */ - if (cs->cols == 200) { col0[0] = 792; col0[1] = 0; } /* 792 + 200 = 992 */ - - OmegaGpuTensor *tc = NULL; OmegaGpuMoeTensor *tm = NULL; - double t0 = now_ms(); - int rc1 = omega_gpu_tensor_upload_bf16(k, n, bh, &tc); - double up_classic = now_ms() - t0; t0 = now_ms(); - int rc2 = omega_gpu_moe_tensor_upload_bf16(k, n, bh, &tm); - double up_moe = now_ms() - t0; - CHECK(rc1 == OMEGA_GPU_MATMUL_OK && rc2 == OMEGA_GPU_MATMUL_OK, "%s: uploads (classic %s, moe %s)", cs->name, omega_gpu_matmul_rc_name(rc1), omega_gpu_matmul_rc_name(rc2)); - printf(" upload classic %.0f ms, moe %.0f ms (%zu MB bf16)\n", up_classic, up_moe, nb * 2 / (1u << 20)); - if (rc1 != OMEGA_GPU_MATMUL_OK || rc2 != OMEGA_GPU_MATMUL_OK) break; - - /* alignment rule, fail-closed, with the tensor present */ - OmegaGpuMatmulInfo info; - int rr = omega_gpu_matmul_resident_window_bf16(m, ah, tm, 4, 8, cw, &info); - CHECK(rr == OMEGA_GPU_MATMUL_BAD_ARGS && strstr(omega_gpu_matmul_last_error(), "not a multiple of 8"), "%s: col0 = 4 refused (%s: %s)", cs->name, omega_gpu_matmul_rc_name(rr), omega_gpu_matmul_last_error()); - rr = omega_gpu_matmul_resident_window_bf16(m, ah, tm, (n - 8) / 8 * 8, 16, cw, &info); - CHECK(rr == OMEGA_GPU_MATMUL_BAD_ARGS && strstr(omega_gpu_matmul_last_error(), "not inside"), "%s: window past n refused (%s: %s)", cs->name, omega_gpu_matmul_rc_name(rr), omega_gpu_matmul_last_error()); - rr = omega_gpu_matmul_resident_window_bf16(m, ah, tm, 0, 0, cw, &info); - CHECK(rr == OMEGA_GPU_MATMUL_BAD_ARGS, "%s: cols = 0 refused (%s)", cs->name, omega_gpu_matmul_rc_name(rr)); - - /* whole-tensor product through the existing API (the reference the window must match column for column) */ - OmegaGpuMatmulInfo wi; - int wrc = omega_gpu_matmul_resident_bf16(m, ah, tc, whole, &wi); - CHECK(wrc == OMEGA_GPU_MATMUL_OK, "%s: whole-tensor call rc=%s (%s)", cs->name, omega_gpu_matmul_rc_name(wrc), omega_gpu_matmul_last_error()); - if (wrc != OMEGA_GPU_MATMUL_OK) break; - printf(" whole: %.3f ms call, chip %.3f ms, grid %ux%u\n", wi.call_ns / 1e6, wi.elapsed_ns / 1e6, wi.grid_x, wi.grid_y); - - size_t mism_total = 0, oracle_bad_total = 0; double oracle_worst = 0.0; int all_hit = 1, f32_same = 1; double win_chip_ms = 0.0; - for (uint32_t w = 0; w < nwin; w++) { - OmegaGpuMatmulInfo i1, i2, i3; - int r1 = omega_gpu_matmul_resident_window_bf16(m, ah, tm, col0[w], cols, cw, &i1); - CHECK(r1 == OMEGA_GPU_MATMUL_OK && i1.n == cols && i1.padded_n == wnp && i1.resident, "%s: window %u (col0 %u) rc=%s (%s)", cs->name, w, col0[w], omega_gpu_matmul_rc_name(r1), omega_gpu_matmul_last_error()); - if (r1 != OMEGA_GPU_MATMUL_OK) break; - size_t mism = 0; - for (uint32_t r = 0; r < m; r++) for (uint32_t j = 0; j < cols; j++) if (cw[(size_t)r * cols + j] != whole[(size_t)r * n + col0[w] + j]) mism++; - mism_total += mism; - size_t bad = 0; double worst = window_oracle(m, k, n, ah, bh, col0[w], cols, cw, &bad); - oracle_bad_total += bad; if (worst > oracle_worst) oracle_worst = worst; - /* repeat: cache hit, bit-identical; f32 activation path: identical too (same bf16 rounding) */ - int r2 = omega_gpu_matmul_resident_window_bf16(m, ah, tm, col0[w], cols, cw2, &i2); - int r3 = omega_gpu_matmul_resident_window_f32(m, a, tm, col0[w], cols, multi, &i3); - if (!(r2 == OMEGA_GPU_MATMUL_OK && i2.kernel_cache_hit && memcmp(cw, cw2, nw * 4) == 0)) all_hit = 0; - if (!(r3 == OMEGA_GPU_MATMUL_OK && memcmp(cw, multi, nw * 4) == 0)) f32_same = 0; - win_chip_ms += i1.elapsed_ns / 1e6; - printf(" window %u col0=%u: mismatches vs whole %zu/%zu, oracle worst %.2e bad %zu, chip %.3f ms, grid %ux%u, hit=%d\n", - w, col0[w], mism, nw, worst, bad, i1.elapsed_ns / 1e6, i1.grid_x, i1.grid_y, (int)i2.kernel_cache_hit); - if (omega_gpu_matmul_is_blocked()) break; - } - CHECK(mism_total == 0, "%s: every window equals the whole-tensor columns bit for bit (%zu mismatches)", cs->name, mism_total); - CHECK(oracle_bad_total == 0, "%s: every window within 1e-5 of the double oracle (worst %g, %zu bad)", cs->name, oracle_worst, oracle_bad_total); - CHECK(all_hit, "%s: repeated window calls hit the kernel cache and are bit-identical", cs->name); - CHECK(f32_same, "%s: f32 activation path is bit-identical to the bf16 one", cs->name); - if (omega_gpu_matmul_is_blocked()) break; - - /* the multi-window call (one activation pack, nwin launches) equals the single windows */ - OmegaGpuMatmulInfo mi; - int mrc = omega_gpu_matmul_resident_windows_f32(m, a, tm, nwin, col0, cols, multi, &mi); - size_t mm = 0; - if (mrc == OMEGA_GPU_MATMUL_OK) for (uint32_t w = 0; w < nwin; w++) for (uint32_t r = 0; r < m; r++) for (uint32_t j = 0; j < cols; j++) - if (multi[(size_t)w * nw + (size_t)r * cols + j] != whole[(size_t)r * n + col0[w] + j]) mm++; - CHECK(mrc == OMEGA_GPU_MATMUL_OK && mi.chip_calls == nwin && mm == 0, "%s: multi-window call rc=%s launches=%u mismatches=%zu", cs->name, omega_gpu_matmul_rc_name(mrc), mi.chip_calls, mm); - - /* negative control 1: the wrong window (one tile up) must disagree with the whole-tensor columns */ - omega_gpu_moe_test_set_window_skew(1); - int src = omega_gpu_matmul_resident_window_bf16(m, ah, tm, col0[0], cols, cw, &info); - size_t skew_mism = 0; - for (uint32_t r = 0; r < m; r++) for (uint32_t j = 0; j < cols; j++) if (cw[(size_t)r * cols + j] != whole[(size_t)r * n + col0[0] + j]) skew_mism++; - omega_gpu_moe_test_set_window_skew(0); - CHECK(src == OMEGA_GPU_MATMUL_OK && skew_mism > nw / 2, "%s: wrong-window control caught (rc=%s, %zu/%zu differ)", cs->name, omega_gpu_matmul_rc_name(src), skew_mism, nw); - /* negative control 2: the wrong kernel (last K pass dropped) must fail the oracle */ - omega_gpu_moe_test_set_mutant(1); - int mut = omega_gpu_matmul_resident_window_bf16(m, ah, tm, col0[0], cols, cw, &info); - size_t mut_bad = 0; double mut_worst = mut == OMEGA_GPU_MATMUL_OK ? window_oracle(m, k, n, ah, bh, col0[0], cols, cw, &mut_bad) : 0.0; - omega_gpu_moe_test_set_mutant(0); - CHECK(mut == OMEGA_GPU_MATMUL_OK && mut_bad > 0, "%s: wrong-kernel control caught (rc=%s, worst %g, %zu bad)", cs->name, omega_gpu_matmul_rc_name(mut), mut_worst, mut_bad); - if (omega_gpu_matmul_is_blocked()) break; - - /* timing: `calls` multi-window calls (the per-token expert pattern) and `calls` single-window calls */ - double *sm = malloc((size_t)calls * sizeof *sm), *ss = malloc((size_t)calls * sizeof *ss); - uint64_t chip_multi = 0, chip_single = 0; int ok_m = 0, ok_s = 0; size_t rep_mism = 0; - for (int i = 0; i < calls; i++) { - double q0 = now_ms(); - int r = omega_gpu_matmul_resident_windows_f32(m, a, tm, nwin, col0, cols, multi, &mi); - sm[i] = now_ms() - q0; - if (r == OMEGA_GPU_MATMUL_OK) { ok_m++; chip_multi += mi.elapsed_ns; } - if (omega_gpu_matmul_is_blocked()) break; - } - for (uint32_t w = 0; w < nwin; w++) for (uint32_t r = 0; r < m; r++) for (uint32_t j = 0; j < cols; j++) - if (multi[(size_t)w * nw + (size_t)r * cols + j] != whole[(size_t)r * n + col0[w] + j]) rep_mism++; - for (int i = 0; i < calls && !omega_gpu_matmul_is_blocked(); i++) { - double q0 = now_ms(); - int r = omega_gpu_matmul_resident_window_f32(m, a, tm, col0[i % nwin], cols, cw, &info); - ss[i] = now_ms() - q0; - if (r == OMEGA_GPU_MATMUL_OK) { ok_s++; chip_single += info.elapsed_ns; } - } - qsort(sm, (size_t)calls, sizeof *sm, cmp_double); qsort(ss, (size_t)calls, sizeof *ss, cmp_double); - const double med_m = sm[calls / 2], med_s = ss[calls / 2]; - const double bytes_win = (double)kp * wnp * 2.0; - const double gbs_multi = bytes_win * nwin / (med_m * 1e-3) / 1e9, gbs_single = bytes_win / (med_s * 1e-3) / 1e9; - CHECK(ok_m == calls && ok_s == calls && rep_mism == 0, "%s: timing calls ok %d/%d multi, %d/%d single, last multi result mismatches %zu", cs->name, ok_m, calls, ok_s, calls, rep_mism); - printf(" timing: %u windows/call median %.3f ms (%.1f us/window, chip mean %.1f us/window, %.1f GB/s); single window median %.3f ms (%.1f GB/s, chip mean %.1f us); %.2f MB per window\n", - nwin, med_m, med_m * 1e3 / nwin, ok_m ? chip_multi / 1e3 / ok_m / nwin : 0.0, gbs_multi, med_s, gbs_single, ok_s ? chip_single / 1e3 / ok_s : 0.0, bytes_win / 1e6); - if (out) { - fprintf(out, "%s{\"case\":\"%s\",\"k\":%u,\"n\":%u,\"m\":%u,\"cols\":%u,\"padded_cols\":%u,\"windows\":%u,\"col0\":[", first ? "" : ",", cs->name, k, n, m, cols, wnp, nwin); - for (uint32_t w = 0; w < nwin; w++) fprintf(out, "%s%u", w ? "," : "", col0[w]); - fprintf(out, "],\"upload_classic_ms\":%.1f,\"upload_moe_ms\":%.1f,\"whole_call_ms\":%.4f,\"whole_chip_ms\":%.4f," - "\"window_mismatches_vs_whole\":%zu,\"oracle_worst_rel\":%g,\"oracle_bad\":%zu,\"repeat_cache_hit_identical\":%s,\"f32_path_identical\":%s," - "\"multi_rc\":\"%s\",\"multi_mismatches\":%zu,\"skew_control_differ\":%zu,\"skew_control_elems\":%zu,\"mutant_control_bad\":%zu,\"mutant_control_worst\":%g," - "\"calls\":%d,\"multi_median_ms\":%.4f,\"multi_p90_ms\":%.4f,\"multi_min_ms\":%.4f,\"multi_chip_us_per_window\":%.2f,\"multi_gbs\":%.1f," - "\"single_median_ms\":%.4f,\"single_p90_ms\":%.4f,\"single_min_ms\":%.4f,\"single_chip_us\":%.2f,\"single_gbs\":%.1f,\"bytes_per_window\":%.0f,\"grid_x\":%u,\"grid_y\":%u}", - up_classic, up_moe, wi.call_ns / 1e6, wi.elapsed_ns / 1e6, - mism_total, oracle_worst, oracle_bad_total, all_hit ? "true" : "false", f32_same ? "true" : "false", - omega_gpu_matmul_rc_name(mrc), mm, skew_mism, nw, mut_bad, mut_worst, - calls, med_m, sm[calls * 9 / 10], sm[0], ok_m ? chip_multi / 1e3 / ok_m / nwin : 0.0, gbs_multi, - med_s, ss[calls * 9 / 10], ss[0], ok_s ? chip_single / 1e3 / ok_s : 0.0, gbs_single, bytes_win, info.grid_x, info.grid_y); - first = 0; - } - free(sm); free(ss); - omega_gpu_tensor_free(tc); omega_gpu_moe_tensor_free(tm); - free(a); free(whole); free(cw); free(cw2); free(multi); free(ah); free(bh); - if (omega_gpu_matmul_is_blocked()) break; - } - if (out) { - fprintf(out, "],\"blocked\":%s,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_matmul_is_blocked() ? "true" : "false", g_checks, g_failed, - g_failed == 0 ? "OMEGA_GPU_MOE_WINDOW_PASS" : "OMEGA_GPU_MOE_WINDOW_FAIL"); - fclose(out); - } - return 0; -} - -int main(int argc, char **argv) { - const char *out_path = NULL; int host = 0, calls = 100, small = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--small") == 0) small = 1; - else if (strcmp(argv[i], "--calls") == 0 && i + 1 < argc) calls = atoi(argv[++i]); - else if (strcmp(argv[i], "--cta-budget") == 0 && i + 1 < argc) { uint32_t b = (uint32_t)strtoul(argv[++i], NULL, 10); omega_gpu_moe_set_cta_budget(b); omega_gpu_matmul_set_cta_budget(b); } - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) { if (omega_gpu_session_set_spin_us((uint32_t)strtoul(argv[++i], NULL, 10)) != 0) { fprintf(stderr, "--spin-us out of range\n"); return 2; } } - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - } - if (calls < 2) calls = 2; - int rc = 0; - if (host) host_only(); - else rc = chip(out_path, calls, small); - if (!omega_gpu_matmul_is_blocked()) omega_gpu_device_close(); - if (rc) return 2; - printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_pf_mem_test.c b/tests/gpu_pf_mem_test.c deleted file mode 100644 index 2b2c4d1a7..000000000 --- a/tests/gpu_pf_mem_test.c +++ /dev/null @@ -1,122 +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. - */ - -/* gpu_pf_mem_test.c (OWN-30B T3b, 2026-10-13): device-resident prefill memory. - * --host-only the copy kernel in the warp simulator (exact copy, nothing past `units` written) - * (default) the chip (caller holds flock /tmp/aien-gb10.lock): - * 1. upload/download round trip of 96 MB through a GPU-cached device buffer (bit-exact; the host buffer is poisoned - * first, so a download that did not run is caught), and a second upload over the same buffer read back exactly - * (a stale L2 line would show here: the GPU rewrote lines it had cached); - * 2. read bandwidth, uncached (session buffer) vs cached (device buffer): every CTA distinct (DRAM) and every CTA the - * same bytes (cache reuse), 5 runs each, median; every XOR result checked. - * Verdict line last: "GPU_PF_MEM: PASS|FAIL". */ -#include "omega_gpu_prefill.h" -#include "omega_blackwell_codegen_pf.h" -#include "omega_blackwell_codegen_tc.h" -#include "bw_warp_sim_tc.h" -#include -#include -#include - -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -static int host_only(void) { - static BlackwellIRProgram p; - if (omega_blackwell_codegen_pf_copy_prog(&p) != 0) { printf("copy codegen refused\n"); return 1; } - enum { U = 1000, CAP = 1100 }; - static uint32_t src[CAP * 4], dst[CAP * 4]; - for (int i = 0; i < CAP * 4; i++) { src[i] = 0x9e3779b9u * (uint32_t)i; dst[i] = 0xdeadbeefu; } - static WsSim s; memset(&s, 0, sizeof s); s.p = &p; s.threads = OMEGA_PF_COPY_THREADS; - uint64_t d = (uintptr_t)dst, sv = (uintptr_t)src; - s.cbank[0x380 / 4] = (uint32_t)d; s.cbank[0x384 / 4] = (uint32_t)(d >> 32); s.cbank[0x388 / 4] = (uint32_t)sv; s.cbank[0x38c / 4] = (uint32_t)(sv >> 32); s.cbank[0x390 / 4] = U; - s.ranges[0].lo = d; s.ranges[0].hi = d + sizeof dst; s.ranges[1].lo = sv; s.ranges[1].hi = sv + sizeof src; s.nranges = 2; - int err = ws_run(&s, (U + OMEGA_PF_COPY_THREADS - 1) / OMEGA_PF_COPY_THREADS, 1); - size_t bad = 0, past = 0; - for (int i = 0; i < CAP * 4; i++) { if (i < U * 4 && dst[i] != src[i]) bad++; if (i >= U * 4 && dst[i] != 0xdeadbeefu) past++; } - printf("sim copy: %s, peak %u registers, %zu wrong, %zu written past the end\n", err ? s.msg : "ran", p.regalloc.peak_gpr_usage, bad, past); - return (err || bad || past) ? 1 : 0; -} - -typedef struct { uint32_t iters, groups, threads; } BwSpec; -static int gen_bw(const OmegaPfKey *k, void *prog) { return omega_blackwell_codegen_tc_bw_prog(k->words[0], k->words[1], k->words[2], prog); } - -int main(int argc, char **argv) { - int fail = host_only(); - if (argc > 1 && !strcmp(argv[1], "--host-only")) { printf("GPU_PF_MEM: %s\n", fail ? "FAIL" : "PASS"); return fail ? 1 : 0; } - if (fail) { printf("GPU_PF_MEM: FAIL\n"); return 1; } - - /* 1. round trip */ - const size_t RB = 96ull << 20; - uint32_t *a = malloc(RB), *b = malloc(RB); - if (!a || !b) return 1; - for (size_t i = 0; i < RB / 4; i++) a[i] = (uint32_t)(i * 2654435761u) ^ 0x5bd1e995u; - OmegaGpuMem dev; - int rc = omega_gpu_pf_alloc_dev(RB, &dev); - if (rc) { printf("alloc_dev: %s (%s)\n", omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); printf("GPU_PF_MEM: FAIL\n"); return 1; } - memset(b, 0xa5, RB); - rc = omega_gpu_pf_upload(&dev, 0, a, RB); - if (!rc) rc = omega_gpu_pf_download(&dev, 0, b, RB); - size_t bad = 0; for (size_t i = 0; i < RB / 4; i++) if (a[i] != b[i]) bad++; - printf("round trip 1 (%zu MB, cached device buffer): rc %s, %zu wrong words\n", RB >> 20, omega_gpu_pf_rc_name(rc), bad); - if (rc || bad) fail++; - for (size_t i = 0; i < RB / 4; i++) a[i] = ~a[i] + (uint32_t)i; - memset(b, 0x5a, RB); - rc = omega_gpu_pf_upload(&dev, 0, a, RB); - if (!rc) rc = omega_gpu_pf_download(&dev, 0, b, RB); - bad = 0; for (size_t i = 0; i < RB / 4; i++) if (a[i] != b[i]) bad++; - printf("round trip 2 (rewritten by the GPU over cached lines): rc %s, %zu wrong words\n", omega_gpu_pf_rc_name(rc), bad); - if (rc || bad) fail++; - omega_gpu_pf_free(&dev); - - /* 2. bandwidth: uncached vs cached, distinct vs same */ - const uint32_t T = 256, grid = 384; - for (int cached = 0; cached < 2 && !fail; cached++) for (int same = 0; same < 2 && !fail; same++) { - const uint32_t iters = same ? 8u : 32u, groups = same ? 1u : grid; - const size_t region = (size_t)iters * T * 128u, sb = region * groups, ob = (size_t)grid * T * 4u; - OmegaGpuMem src = { 0 }, out = { 0 }; - uint32_t *pat = malloc(sb); - for (size_t q = 0; q < sb / 4; q++) pat[q] = (uint32_t)(q * 2654435761u); - rc = cached ? omega_gpu_pf_alloc_dev(sb, &src) : omega_gpu_pf_alloc_host(sb, &src); - if (!rc) rc = omega_gpu_pf_alloc_host(ob, &out); - if (!rc) { if (cached) rc = omega_gpu_pf_upload(&src, 0, pat, sb); else { memcpy(src.cpu, pat, sb); } } - uint32_t *want = calloc((size_t)grid * T, 4); - for (uint32_t c = 0; c < grid; c++) for (uint32_t t = 0; t < T; t++) { uint32_t x = 0; const uint32_t *r = pat + (size_t)(groups == 1 ? 0 : c) * region / 4; - for (uint32_t it = 0; it < iters; it++) for (uint32_t q = 0; q < 8; q++) for (uint32_t s = 0; s < 4; s++) x ^= r[((size_t)it * T * 128u + (size_t)q * T * 16u + t * 16u) / 4 + s]; - want[(size_t)c * T + t] = x; } - uint64_t ns[5] = { 0 }; size_t wrong = 0; - OmegaPfKey key; memset(&key, 0, sizeof key); key.kind = 0x100u; key.words[0] = iters; key.words[1] = groups; key.words[2] = T; - for (int r = 0; r < 5 && !rc; r++) { - uint32_t *o = out.cpu; memset(o, 0, ob); - uint32_t args[4] = { (uint32_t)src.va, (uint32_t)(src.va >> 32), (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - omega_gpu_session_lock(); - OmegaPfKernel k; rc = omega_gpu_pf_open_locked(); - if (!rc) rc = omega_gpu_pf_kernel_locked(&key, gen_bw, &k); - if (!rc && omega_gpu_session_sync_to_gpu(&out) != 0) rc = OMEGA_GPU_PF_CHIP_FAIL; - if (!rc) rc = omega_gpu_pf_launch_locked(&k, T, grid, 1, 0, args, 4, &ns[r]); - if (!rc && omega_gpu_session_sync_to_cpu(&out) != 0) rc = OMEGA_GPU_PF_CHIP_FAIL; - omega_gpu_session_unlock(); - if (!rc) for (size_t q = 0; q < (size_t)grid * T; q++) if (o[q] != want[q]) wrong++; - } - qsort(ns, 5, 8, cmp_u64); - const double bytes = (double)grid * iters * T * 128.0; - printf("bw %s %s: rc %s, median %.1f us, %.1f GB/s, %zu wrong\n", cached ? "cached " : "uncached", same ? "same-1MB" : "distinct", omega_gpu_pf_rc_name(rc), ns[2] / 1e3, bytes / ns[2], wrong); - if (rc || wrong) { fail++; printf(" error: %s\n", omega_gpu_session_last_error()); } - free(pat); free(want); omega_gpu_pf_free(&src); omega_gpu_pf_free(&out); - } - free(a); free(b); - printf("GPU_PF_MEM: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} diff --git a/tests/gpu_pfgemm_test.c b/tests/gpu_pfgemm_test.c deleted file mode 100644 index 900878f59..000000000 --- a/tests/gpu_pfgemm_test.c +++ /dev/null @@ -1,343 +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. - */ - -/* gpu_pfgemm_test.c (OWN-30B T3b, 2026-10-13): tensor-core grouped FP8 GEMM v2, device resident (omega_blackwell_codegen_tc2.h, - * omega_gpu_pfgemm.c). - * --host-only register budgets of the production specs; the SWIGLU layout transform against a double oracle on the - * original (unpermuted) weights; the C emulation of the folded scale against a double oracle - * --sim the kernel in the warp simulator (both fragment orders) bit-identical to the C emulation (F32 and SWIGLU, - * indexed and direct rows); mutants 1-4 caught (a simulator error is a FAIL, never "caught") - * --chip (under flock /tmp/aien-gb10.lock) through the device API with GPU-cached buffers: sampled rows vs the - * emulation (F32 bit-identical; SWIGLU within 1 bf16 ulp: MUFU.EX2/RCP are approximate on the chip), second - * launch identical, mutants caught, medians of --reps at --tokens for every production shape - * Verdict line last: "GPU_PFGEMM: PASS|FAIL". */ -#include "omega_blackwell_codegen_tc2.h" -#include "omega_blackwell_codegen_tc.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_prefill.h" -#include "bw_warp_sim_tc.h" -#include -#include -#include -#include - -static const HmmaModel GB10 = { 16, 2, 0, 2, 0 }; -static uint64_t rng = 0x243f6a8885a308d3ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static float frnd(void) { return ((float)(rnd() & 0xffffff) / 16777216.0f) * 2.0f - 1.0f; } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static uint16_t bf16_rn(float f) { uint32_t u = f2u(f); if ((u & 0x7fffffffu) > 0x7f800000u) return 0x7fc0u; return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } -static uint32_t stored_ix(uint32_t p) { static const uint32_t inv[4] = { 0, 2, 1, 3 }; return (p & ~3u) | inv[p & 3u]; } - -typedef struct { - uint32_t E, n, k, M, xr, layout, direct; - uint8_t *w, *pw; /* original and physical weights */ - uint16_t *sbf; /* scale_inv bf16 */ - float *ratio; /* physical ratio table */ - float *x; /* xr * k true values */ - uint16_t *xp; /* (xr + pad) * k stored bf16 */ - uint32_t *eid, *src, *counts; -} Prob; - -static uint8_t rand_e4m3(void) { for (;;) { uint8_t c = (uint8_t)rnd(); if ((c & 0x7f) != 0x7f) return c; } } -static void prob_make(Prob *p, uint32_t E, uint32_t n, uint32_t k, uint32_t M, uint32_t xr, uint32_t layout, uint32_t direct, uint32_t pad) { - memset(p, 0, sizeof *p); - p->E = E; p->n = n; p->k = k; p->M = M; p->xr = direct ? M : xr; p->layout = layout; p->direct = direct; - const size_t wn = (size_t)E * n * k, sn = (size_t)E * (n / 128) * (k / 128), rn = (size_t)E * (n / 8) * (k / 128 + 1); - p->w = malloc(wn); p->pw = malloc(wn); p->sbf = malloc(sn * 2); p->ratio = malloc(rn * 4); - p->x = malloc((size_t)p->xr * k * 4); p->xp = calloc((size_t)(p->xr + pad) * k, 2); - p->eid = malloc(M * 4); p->src = malloc(M * 4); p->counts = calloc(E, 4); - for (size_t i = 0; i < wn; i++) p->w[i] = rand_e4m3(); - for (size_t i = 0; i < sn; i++) { float s = ldexpf(1.0f + (float)(rnd() & 127) / 128.0f, -(int)(rnd() % 12) - 4); p->sbf[i] = (uint16_t)(f2u(s) >> 16); } - if (omega_gpu_pf_weights_host_form(E, n, k, p->w, p->sbf, layout, p->pw, p->ratio) != 0) { printf("host form refused\n"); exit(2); } - for (size_t i = 0; i < (size_t)p->xr * k; i++) p->x[i] = frnd() * (rnd() % 16 == 0 ? 8.0f : 1.0f); - for (uint32_t r = 0; r < p->xr; r++) omega_tcgemm_permute_x(p->x + (size_t)r * k, k, p->xp + (size_t)r * k); - /* sorted expert ids with random segment lengths (some experts empty, some multi-tile) */ - uint32_t i = 0; - for (uint32_t e = 0; e < E && i < M; e++) { uint32_t c = e + 1 == E ? M - i : (uint32_t)((uint64_t)(rnd() % 2000) * 2 * M / (2000ull * E)); if (c > M - i) c = M - i; for (uint32_t q = 0; q < c; q++) { p->eid[i + q] = e; } p->counts[e] = c; i += c; } - for (uint32_t q = 0; q < M; q++) p->src[q] = direct ? q : rnd() % p->xr; -} -static void prob_free(Prob *p) { free(p->w); free(p->pw); free(p->sbf); free(p->ratio); free(p->x); free(p->xp); free(p->eid); free(p->src); free(p->counts); } - -/* emulation of one physical output (row i, physical col c): the kernel's arithmetic */ -static float emu_phys(const Prob *p, uint32_t i, uint32_t c) { - const uint32_t n = p->n, k = p->k, KB = k / 128; - const uint16_t *xs = p->xp + (size_t)p->src[i] * k; - const uint8_t *wr = p->pw + ((size_t)p->eid[i] * n + c) * k; - const float *R0 = p->ratio + ((size_t)p->eid[i] * (n / 16) + c / 16) * (KB + 1) * 2 + (c / 8) % 2; -#define R(q) R0[2 * (q)] - float acc = 0.0f; - for (uint32_t kb = 0; kb < KB; kb++) { - acc = acc * R(kb); - for (uint32_t ch = 0; ch < 2; ch++) for (uint32_t s = 0; s < 4; s++) { - float a[16], b[16]; int m = 0; - for (uint32_t t = 0; t < 4; t++) for (uint32_t j = 0; j < 4; j++) { - uint32_t e = kb * 128 + ch * 64 + 16 * t + 4 * s + j; - a[m] = u2f((uint32_t)xs[stored_ix(e)] << 16); b[m] = u2f((uint32_t)omega_tcgemm_w_bf16(wr[e]) << 16); m++; - } - acc = hm_dot16(&GB10, a, b, acc); - } - } - return acc * R(KB); -#undef R -} -/* the kernel's epilogue arithmetic: MUFU.EX2, FADD, MUFU.RCP, FMUL x 3, F2FP. The two MUFU ops go through ws_mufu_ex2 / ws_mufu_rcp - * (bw_mufu_ftz.h, omega #462): the chip's MUFU flushes a subnormal result to a sign-preserving zero, so for t = -g log2 e in (126, 128) - * (g in (-88.72, -87.34)) the reciprocal is +-0 and the activation is +-0, not the 2^-56-ish product an IEEE 1/d would give. */ -static uint16_t swiglu_bits(float g, float u) { - float t = g * u2f(0xbfb8aa3bu), ex = ws_mufu_ex2(t), d = ex + 1.0f, r = ws_mufu_rcp(d), o = g * r; - o = o * u; o = o * u2f(0x5f800000u); - return bf16_rn(o); -} -/* emulated output row i: F32 -> n floats; SWIGLU -> n/2 bf16 (as u16 in the low half of each u32 slot of out) */ -static void emu_row(const Prob *p, uint32_t i, float *yf, uint16_t *ya) { - if (p->layout == OMEGA_GPU_PF_PLAIN) { for (uint32_t c = 0; c < p->n; c++) yf[c] = emu_phys(p, i, c); return; } - for (uint32_t a = 0; a < p->n / 2; a++) { uint32_t G = a / 8, m = a % 8; ya[a] = swiglu_bits(emu_phys(p, i, 16 * G + m), emu_phys(p, i, 16 * G + 8 + m)); } -} - -typedef struct { uint64_t w_va, r_va; uint32_t row0, cnt; uint64_t pad; } Tile; -static uint32_t make_tiles(const Prob *p, uint32_t bm, Tile *t) { - uint32_t nt = 0, row = 0; const uint32_t KB = p->k / 128; - for (uint32_t e = 0; e < p->E; e++) { for (uint32_t r = 0; r < p->counts[e]; r += bm) { - t[nt].w_va = (uintptr_t)(p->pw + (size_t)e * p->n * p->k); t[nt].r_va = (uintptr_t)(p->ratio + (size_t)e * (p->n / 8) * (KB + 1)); - t[nt].row0 = row + r; t[nt].cnt = p->counts[e] - r < bm ? p->counts[e] - r : bm; t[nt].pad = 0; nt++; } row += p->counts[e]; } - return nt; -} - -static int host_only(void) { - int fail = 0; - static const OmegaTc2Spec specs[] = { - { 2048, 8, 2, 16, 1, OMEGA_TC2_EPI_F32, 0, 5120, 0 }, { 2048, 8, 2, 16, 1, OMEGA_TC2_EPI_SWIGLU, 0, 1536, 0 }, { 768, 8, 2, 16, 1, OMEGA_TC2_EPI_F32, 1, 2048, 0 }, - { 4096, 8, 2, 16, 1, OMEGA_TC2_EPI_F32, 0, 2048, 0 }, { 2048, 8, 2, 16, 2, OMEGA_TC2_EPI_F32, 0, 5120, 0 }, { 2048, 8, 2, 16, 2, OMEGA_TC2_EPI_SWIGLU, 0, 1536, 0 }, - { 768, 8, 2, 16, 2, OMEGA_TC2_EPI_F32, 1, 2048, 0 }, { 2048, 4, 2, 8, 2, OMEGA_TC2_EPI_F32, 0, 2048, 0 }, - }; - static BlackwellIRProgram prog; - for (size_t i = 0; i < sizeof specs / sizeof specs[0]; i++) { - int rc = omega_blackwell_codegen_tc2_prog(&specs[i], &prog); - uint32_t peak = rc == 0 ? prog.regalloc.peak_gpr_usage : 0, decl = omega_bw_gpr_declared(peak); - int ok = rc == 0 && decl <= 128u && 32u * specs[i].warps * decl <= 65536u; - printf("spec k %u rt %u ct %u warps %u aqn %u epi %u direct %u: %s, %zu instructions, peak %u, declared %u -> %s\n", specs[i].k, specs[i].rt, specs[i].ct, specs[i].warps, specs[i].aqn, - specs[i].epi, specs[i].direct, rc ? "REFUSED" : "built", rc ? 0 : prog.count, peak, decl, ok ? "fits" : "DOES NOT FIT"); - if (!ok && specs[i].aqn == 1) fail++; /* aqn 2 is optional */ - } - /* layout + emulation vs double oracle on the ORIGINAL weights: SWIGLU act[a] ~ silu(x.Wg[i]) * x.Wu[i] * 2^64, i = perm(a) */ - Prob p; prob_make(&p, 2, 256, 256, 24, 8, OMEGA_GPU_PF_SWIGLU, 0, 32); - double worst = 0; const uint32_t KB = p.k / 128, NB = p.n / 128, I = p.n / 2; - for (uint32_t i = 0; i < p.M; i++) { - uint16_t act[128]; emu_row(&p, i, NULL, act); - for (uint32_t a = 0; a < I; a++) { - uint32_t li = stored_ix(a); double d[2]; - for (int h = 0; h < 2; h++) { uint32_t row = h ? I + li : li; double s = 0; - for (uint32_t kk = 0; kk < p.k; kk++) { - double sc = (double)u2f((uint32_t)p.sbf[((size_t)p.eid[i] * NB + row / 128) * KB + kk / 128] << 16); - double wv = ldexp((double)u2f((uint32_t)omega_tcgemm_w_bf16(p.w[((size_t)p.eid[i] * p.n + row) * p.k + kk]) << 16), 120); - double xv = (double)u2f((uint32_t)p.xp[(size_t)p.src[i] * p.k + stored_ix(kk)] << 16) / 18446744073709551616.0; - s += sc * wv * xv; } - d[h] = s; } - double want = d[0] / (1.0 + exp(-d[0])) * d[1], got = (double)u2f((uint32_t)act[a] << 16) / 18446744073709551616.0; - double err = fabs(got - want) / (fabs(want) + 1e-3 * 1e-0); - if (err > worst) worst = err; - } - } - printf("SWIGLU layout + emulation vs double oracle on the original weights: worst relative error %.3g (bf16 output: < 1e-2 expected)\n", worst); - if (!(worst < 1e-2)) fail++; - prob_free(&p); - /* the reference against the chip's MUFU.RCP flush (GB10, evidence OWN30B-L1G-PFGEMM-SWIGLU-FTZ-df9bd9c4, 2026-10-15): at 3600 - * tokens, 48 sampled rows, all 101 of 101 elements that differed from the IEEE reference had t = -g log2 e in (126.03, 127.99) - * and came back +-0 from the chip. g and u are the emulated f32 gate / up values (9 significant digits round-trip exactly), - * act the chip's bf16; the first and last entries are the smallest and largest t observed. */ - static const struct { float g, u; uint16_t act; } chip[] = { - { -87.3551483f, 274.485016f, 0x8000 }, { -87.4824142f, 122.849442f, 0x8000 }, { -87.8418655f, 45.4098854f, 0x8000 }, - { -88.1839066f, -28.427494f, 0x0000 }, { -88.3344727f, -3.59300494f, 0x0000 }, { -88.7186356f, 180.687149f, 0x8000 }, - }; - size_t ok = 0; - for (size_t i = 0; i < sizeof chip / sizeof chip[0]; i++) ok += swiglu_bits(chip[i].g, chip[i].u) == chip[i].act; - /* negative control: g -87 (t 125.5) has a normal reciprocal and must stay a nonzero finite negative activation (the flush must not - * reach outside the window); g -89 (t 128.4) overflows ex2 to +inf and is -0 in both arithmetics (not a flush) */ - const uint16_t nc_lo = swiglu_bits(-87.0f, 100.0f), nc_hi = swiglu_bits(-89.0f, 100.0f); - const int nc_ok = (nc_lo & 0x7fffu) != 0 && (nc_lo & 0x7f80u) != 0x7f80u && (nc_lo & 0x8000u) && nc_hi == 0x8000u; - printf("SWIGLU reference vs chip-observed MUFU.RCP flush window: %zu/%zu match; control g -87 -> %04x (nonzero), g -89 -> %04x (-0): %s\n", - ok, sizeof chip / sizeof chip[0], nc_lo, nc_hi, ok == sizeof chip / sizeof chip[0] && nc_ok ? "ok" : "FAIL"); - if (ok != sizeof chip / sizeof chip[0] || !nc_ok) fail++; - return fail; -} - -static int sim_run(const Prob *p, const OmegaTc2Spec *sp, int order, void *y, char *msg, size_t msgn) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_tc2_prog(sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused (spec_ok %d)", omega_tc2_spec_ok(sp)); return -1; } - const uint32_t bm = 16u * sp->rt, span = omega_tc2_span(sp); - Tile *tiles = calloc(p->M + 1, sizeof *tiles); - uint32_t nt = make_tiles(p, bm, tiles); - uint32_t *ridx = malloc((p->M + bm) * 4); for (uint32_t i = 0; i < p->M + bm; i++) ridx[i] = i < p->M ? p->src[i] : 0; - const size_t yb = (size_t)(p->M + bm) * p->n * (p->layout == OMEGA_GPU_PF_SWIGLU ? 1 : 4); - memset(y, 0xee, yb); - uint8_t *smem = malloc(omega_tc2_shared_bytes(sp)); - static WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * sp->warps; s.smem = smem; s.smem_bytes = omega_tc2_shared_bytes(sp); s.order = order; - uint64_t a[4] = { (uintptr_t)tiles, sp->direct ? 0 : (uintptr_t)ridx, (uintptr_t)p->xp, (uintptr_t)y }; - for (int i = 0; i < 4; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - s.cbank[0x3a0 / 4] = p->n; - const uint32_t KB = p->k / 128; - s.ranges[0].lo = (uintptr_t)tiles; s.ranges[0].hi = (uintptr_t)(tiles + nt); - s.ranges[1].lo = (uintptr_t)ridx; s.ranges[1].hi = (uintptr_t)(ridx + p->M + bm); - s.ranges[2].lo = (uintptr_t)p->xp; s.ranges[2].hi = (uintptr_t)(p->xp + (size_t)(p->xr + (p->direct ? bm : 0)) * p->k); - s.ranges[3].lo = (uintptr_t)y; s.ranges[3].hi = (uintptr_t)y + (size_t)p->M * p->n * (p->layout == OMEGA_GPU_PF_SWIGLU ? 1 : 4); - s.ranges[4].lo = (uintptr_t)p->pw; s.ranges[4].hi = (uintptr_t)(p->pw + (size_t)p->E * p->n * p->k); - s.ranges[5].lo = (uintptr_t)p->ratio; s.ranges[5].hi = (uintptr_t)(p->ratio + (size_t)p->E * (p->n / 8) * (KB + 1)); - s.nranges = 6; - int err = ws_run(&s, p->n / span, nt); - if (err) snprintf(msg, msgn, "simulator %s", s.msg); - free(tiles); free(ridx); free(smem); - return err ? -1 : 0; -} -static size_t compare(const Prob *p, const void *y, const uint32_t *rows, uint32_t nrows, int tol_ulp, size_t *ulp1) { - size_t bad = 0; if (ulp1) *ulp1 = 0; - float *yf = malloc(p->n * 4); uint16_t *ya = malloc(p->n); - for (uint32_t q = 0; q < nrows; q++) { - uint32_t i = rows[q]; emu_row(p, i, yf, ya); - if (p->layout == OMEGA_GPU_PF_PLAIN) { const uint32_t *g = (const uint32_t *)y + (size_t)i * p->n; for (uint32_t c = 0; c < p->n; c++) if (g[c] != f2u(yf[c])) { if (getenv("PFDBG") && bad < 6) printf(" row %u col %u got %.9g want %.9g\n", i, c, u2f(g[c]), yf[c]); bad++; } } - else { const uint16_t *g = (const uint16_t *)y + (size_t)i * (p->n / 2); - for (uint32_t c = 0; c < p->n / 2; c++) if (g[c] != ya[c]) { int d = abs((int)g[c] - (int)ya[c]); if (d <= tol_ulp && ((g[c] ^ ya[c]) & 0x8000) == 0) { if (ulp1) (*ulp1)++; } - else { if (getenv("PFDBG") && bad < 128) { const uint32_t G = c / 8, mm = c % 8; const float gg = emu_phys(p, i, 16 * G + mm), uu = emu_phys(p, i, 16 * G + 8 + mm); - printf(" row %u act %u got %04x want %04x g %.9g u %.9g t %.6f\n", i, c, g[c], ya[c], gg, uu, gg * u2f(0xbfb8aa3bu)); } bad++; } } } - } - free(yf); free(ya); - return bad; -} - -static int sim_tests(void) { - int fail = 0; char msg[256]; - static const struct { uint32_t E, n, k, M, xr, layout, direct, rt, warps, aqn; } cs[] = { - { 3, 256, 256, 70, 20, OMEGA_GPU_PF_PLAIN, 0, 8, 16, 1 }, { 3, 256, 384, 70, 20, OMEGA_GPU_PF_SWIGLU, 0, 8, 16, 1 }, - { 3, 256, 256, 150, 0, OMEGA_GPU_PF_PLAIN, 1, 8, 16, 1 }, { 2, 256, 256, 40, 9, OMEGA_GPU_PF_PLAIN, 0, 4, 8, 2 }, - { 2, 512, 128, 300, 30, OMEGA_GPU_PF_SWIGLU, 0, 8, 16, 2 }, - { 3, 512, 256, 150, 40, OMEGA_GPU_PF_SWIGLU, 0, 4, 16, 1 }, { 3, 256, 384, 130, 0, OMEGA_GPU_PF_PLAIN, 1, 4, 16, 1 }, /* the chip shape (QMD shared cap) */ - }; - for (size_t c = 0; c < sizeof cs / sizeof cs[0]; c++) { - Prob p; prob_make(&p, cs[c].E, cs[c].n, cs[c].k, cs[c].M, cs[c].xr, cs[c].layout, cs[c].direct, 16 * cs[c].rt); - OmegaTc2Spec sp = { cs[c].k, cs[c].rt, 2, cs[c].warps, cs[c].aqn, cs[c].layout == OMEGA_GPU_PF_SWIGLU ? OMEGA_TC2_EPI_SWIGLU : OMEGA_TC2_EPI_F32, cs[c].direct, cs[c].n, 0 }; - void *y = malloc((size_t)(p.M + 128) * p.n * 4); - uint32_t *rows = malloc(p.M * 4); for (uint32_t i = 0; i < p.M; i++) rows[i] = i; - for (int order = 0; order < 2; order++) { - int rc = sim_run(&p, &sp, order, y, msg, sizeof msg); - size_t bad = rc ? (size_t)-1 : compare(&p, y, rows, p.M, 0, NULL); - printf("sim case %zu (E %u n %u k %u M %u %s%s rt %u warps %u aqn %u) order %d: %s, %zu differ\n", c, p.E, p.n, p.k, p.M, p.layout ? "SWIGLU" : "F32", p.direct ? " direct" : "", sp.rt, sp.warps, sp.aqn, order, rc ? msg : "ran", rc ? 0 : bad); - if (rc || bad) fail++; - } - if (c == 0 || c == 1) for (int m = 1; m <= 4; m++) { - OmegaTc2Spec mm = sp; mm.mutant = m; - int rc = sim_run(&p, &mm, 0, y, msg, sizeof msg); - size_t bad = rc ? 0 : compare(&p, y, rows, p.M, 0, NULL); - printf("sim case %zu mutant %d: %s\n", c, m, rc ? msg : bad ? "caught" : "NOT CAUGHT"); - if (rc || !bad) fail++; - } - free(y); free(rows); prob_free(&p); - } - return fail; -} - -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -static int chip_shape(const char *name, uint32_t tokens, int reps, int check_rows, int mutants) { - uint32_t E, n, k, M, xr, layout, direct; - if (!strcmp(name, "gateup")) { E = 128; n = 1536; k = 2048; M = tokens * 8; xr = tokens; layout = OMEGA_GPU_PF_SWIGLU; direct = 0; } - else if (!strcmp(name, "down")) { E = 128; n = 2048; k = 768; M = tokens * 8; xr = 0; layout = OMEGA_GPU_PF_PLAIN; direct = 1; } - else if (!strcmp(name, "qkv")) { E = 1; n = 5120; k = 2048; M = tokens; xr = tokens; layout = OMEGA_GPU_PF_PLAIN; direct = 0; } - else if (!strcmp(name, "o")) { E = 1; n = 2048; k = 4096; M = tokens; xr = tokens; layout = OMEGA_GPU_PF_PLAIN; direct = 0; } - else { printf("unknown shape %s\n", name); return 1; } - const uint32_t bm = omega_gpu_pf_gemm_bm(); - Prob p; prob_make(&p, E, n, k, M, xr, layout, direct, bm); - int fail = 0, rc; - OmegaPfWeights wt; OmegaGpuMem xd = { 0 }, yd = { 0 }, tab = { 0 }, ridx = { 0 }; - rc = omega_gpu_pf_weights_upload(E, n, k, p.w, p.sbf, layout, &wt); - const size_t xb = ((size_t)(p.xr + bm) * k * 2 + 15) & ~(size_t)15, yb = (size_t)(M + bm) * n * (layout == OMEGA_GPU_PF_SWIGLU ? 1 : 4); - if (!rc) rc = omega_gpu_pf_alloc_dev(xb, &xd); - if (!rc) rc = omega_gpu_pf_alloc_dev(yb, &yd); - if (!rc) rc = omega_gpu_pf_upload(&xd, 0, p.xp, xb); - const uint32_t maxt = M / bm + E + 1; - if (!rc) rc = omega_gpu_pf_alloc_host((size_t)maxt * 32, &tab); - if (!rc) rc = omega_gpu_pf_alloc_host((size_t)(M + bm) * 4, &ridx); - if (rc) { printf("%s setup: %s (%s)\n", name, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); return 1; } - uint32_t nt = omega_gpu_pf_gemm_tiles(&wt, p.counts, tab.cpu, maxt); - { uint32_t *ri = ridx.cpu; for (uint32_t i = 0; i < M + bm; i++) ri[i] = i < M ? p.src[i] : 0; } - omega_gpu_session_lock(); (void)omega_gpu_session_sync_to_gpu(&tab); (void)omega_gpu_session_sync_to_gpu(&ridx); omega_gpu_session_unlock(); - const uint64_t rva = direct ? 0 : ridx.va; - uint8_t *y1 = malloc(yb), *y2 = malloc(yb); - uint64_t ns[32] = { 0 }; - if (reps > 32) reps = 32; - for (int r = 0; r < reps && !rc; r++) rc = omega_gpu_pf_gemm(&wt, tab.va, nt, rva, xd.va, yd.va, &ns[r]); - if (!rc) rc = omega_gpu_pf_download(&yd, 0, y1, yb & ~(size_t)15); - memset(y2, 0, yb); - { uint8_t z[4096]; memset(z, 0, sizeof z); /* zero the output on the device, run once more: the second result must be identical */ - uint8_t *zb = calloc(1, yb); if (!rc) rc = omega_gpu_pf_upload(&yd, 0, zb, yb & ~(size_t)15); free(zb); (void)z; } - uint64_t ns2 = 0; - if (!rc) rc = omega_gpu_pf_gemm(&wt, tab.va, nt, rva, xd.va, yd.va, &ns2); - if (!rc) rc = omega_gpu_pf_download(&yd, 0, y2, yb & ~(size_t)15); - if (rc) { printf("%s run: %s (%s)\n", name, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); fail++; } - else { - const size_t outb = (size_t)M * n * (layout == OMEGA_GPU_PF_SWIGLU ? 1 : 4); - printf("%s second launch identical: %s\n", name, memcmp(y1, y2, outb) ? "NO" : "yes"); - if (memcmp(y1, y2, outb)) fail++; - uint32_t *rows = malloc(check_rows * 4); for (int q = 0; q < check_rows; q++) rows[q] = q == 0 ? 0 : q == 1 ? M - 1 : rnd() % M; - size_t ulp1 = 0, bad = compare(&p, y1, rows, check_rows, layout == OMEGA_GPU_PF_SWIGLU ? 1 : 0, &ulp1); - printf("%s bit-identity on %d sampled rows: %zu differ%s", name, check_rows, bad, layout == OMEGA_GPU_PF_SWIGLU ? "" : "\n"); - if (layout == OMEGA_GPU_PF_SWIGLU) printf(" (beyond 1 bf16 ulp; %zu within 1 ulp of %zu)\n", ulp1, (size_t)check_rows * n / 2); - if (bad) fail++; - qsort(ns, reps, 8, cmp_u64); - const double fl = 2.0 * M * n * k, med = (double)ns[reps / 2]; - printf("TCGEMM2 %s tokens %u M %u n %u k %u tiles %u: median %.3f ms (min %.3f), %.1f TFLOPS, weights %.0f MB -> %.0f GB/s of distinct weights\n", name, tokens, M, n, k, nt, - med / 1e6, ns[0] / 1e6, fl / med / 1e3, (double)E * n * k / 1e6, (double)E * n * k / med); - if (mutants) for (int m = 1; m <= 4; m++) { - omega_gpu_pf_gemm_test_set_mutant(m); - int mrc = omega_gpu_pf_gemm(&wt, tab.va, nt, rva, xd.va, yd.va, NULL); - if (!mrc) mrc = omega_gpu_pf_download(&yd, 0, y2, yb & ~(size_t)15); - omega_gpu_pf_gemm_test_set_mutant(0); - size_t mb = mrc ? 0 : compare(&p, y2, rows, check_rows > 8 ? 8 : check_rows, layout == OMEGA_GPU_PF_SWIGLU ? 1 : 0, NULL); - printf("%s mutant %d: %s\n", name, m, mrc ? "launch failed" : mb ? "caught" : "NOT CAUGHT"); - if (mrc || !mb) fail++; - } - free(rows); - } - free(y1); free(y2); - omega_gpu_pf_weights_free(&wt); omega_gpu_pf_free(&xd); omega_gpu_pf_free(&yd); omega_gpu_pf_free(&tab); omega_gpu_pf_free(&ridx); - prob_free(&p); - return fail; -} - -int main(int argc, char **argv) { - int host = 1, sim = 1, chip = 0, reps = 7, check = 48, mutants = 1; uint32_t tokens = 3600; const char *shape = NULL; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) sim = 0; - else if (!strcmp(argv[i], "--sim")) host = 0; - else if (!strcmp(argv[i], "--chip")) { chip = 1; host = 0; sim = 0; } - else if (!strcmp(argv[i], "--shape") && i + 1 < argc) shape = argv[++i]; - else if (!strcmp(argv[i], "--tokens") && i + 1 < argc) tokens = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = atoi(argv[++i]); - else if (!strcmp(argv[i], "--check-rows") && i + 1 < argc) check = atoi(argv[++i]); - else if (!strcmp(argv[i], "--no-mutants")) mutants = 0; - else if (!strcmp(argv[i], "--shape-knob") && i + 3 < argc) { uint32_t a = (uint32_t)atoi(argv[i + 1]), b = (uint32_t)atoi(argv[i + 2]), c = (uint32_t)atoi(argv[i + 3]); omega_gpu_pf_gemm_set_shape(a, b, c); i += 3; } - } - int fail = 0; - if (host) fail += host_only(); - if (sim) fail += sim_tests(); - if (chip) { - static const char *all[] = { "gateup", "down", "qkv", "o" }; - for (int s = 0; s < 4; s++) if (!shape || !strcmp(shape, all[s])) fail += chip_shape(all[s], tokens, reps, check, mutants); - } - printf("GPU_PFGEMM: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} diff --git a/tests/gpu_pfhost_test.c b/tests/gpu_pfhost_test.c deleted file mode 100644 index ba25fc5aa..000000000 --- a/tests/gpu_pfhost_test.c +++ /dev/null @@ -1,294 +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. - */ - -/* gpu_pfhost_test.c (OWN-30B W-L1G-D, 2026-10-14): router logits and MoE combine for the whole-prompt prefill - * (omega_blackwell_codegen_pfhost.h). Both kernels must equal the host loops of the Rust driver BIT FOR BIT. - * --host-only reference self-checks (packing, the -0.0 start, mutant references differ) - * --sim kernels in the warp simulator bit-identical to the reference, both scheduling orders; mutants caught - * --chip (under flock /tmp/aien-gb10.lock) through the device API at --tokens rows: bit-identical, mutants caught, medians - * Verdict line last: "GPU_PFHOST: PASS|FAIL". */ -#include "omega_blackwell_codegen_pfhost.h" -#include "omega_gpu_pfhost.h" -#include "omega_gpu_prefill.h" -#include "bw_warp_sim_tc.h" -#include -#include -#include -#include - -static uint64_t rng = 0x9e3779b97f4a7c15ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static float rand_unit(void) { return ((float)(rnd() & 0xffffff) / 16777216.0f) * 2.0f - 1.0f; } -/* router weights as the checkpoint has them: bf16 values widened to f32 */ -static float rand_bf16w(void) { return u2f(f2u(rand_unit() * 0.08f) & 0xffff0000u); } -/* activations: RMSNorm-like magnitudes with some outliers and exact zeros */ -static float rand_act(void) { float v = rand_unit() * 2.0f; int r = rnd() % 64; if (r == 0) v *= 40.0f; else if (r == 1) v = 0.0f; return v; } - -/* ---------------- references (compiled with -ffp-contract=off: a * b then +, as Rust) ---------------- */ -static void rl_ref(const float *x, const float *w, uint32_t rows, uint32_t k, uint32_t e, float *lg, int mutant) { - const uint32_t kk = mutant == 2 ? k - 128u : k; - for (uint32_t r = 0; r < rows; r++) - for (uint32_t ex = 0; ex < e; ex++) { - float acc = -0.0f; - for (uint32_t j = 0; j < kk; j++) acc = mutant == 1 ? fmaf(w[(size_t)ex * k + j], x[(size_t)r * k + j], acc) : acc + w[(size_t)ex * k + j] * x[(size_t)r * k + j]; - lg[(size_t)r * e + ex] = acc; - } -} -static void mc_ref(const float *down, const uint32_t *inv, const float *wt, uint32_t rows, uint32_t h, uint32_t K, float *out, int mutant) { - const uint32_t used = mutant == 2 ? K - 1u : K; - for (uint32_t r = 0; r < rows; r++) - for (uint32_t c = 0; c < h; c++) { - float acc = 0.0f; - for (uint32_t s = 0; s < used; s++) { - const float d = down[(size_t)inv[(size_t)r * K + s] * h + c], ww = wt[(size_t)r * K + s]; - acc = mutant == 1 ? fmaf(ww, d, acc) : acc + ww * d; - } - out[(size_t)r * h + c] = acc; - } -} -static size_t diff_bits(const float *a, const float *b, size_t n) { size_t bad = 0; for (size_t i = 0; i < n; i++) if (f2u(a[i]) != f2u(b[i])) bad++; return bad; } - -typedef struct { uint32_t rows, k, e, t, rp; float *x, *w, *wq, *ref; } RlProb; -static void rl_make(RlProb *p, uint32_t rows, uint32_t k, uint32_t e, uint32_t t) { - p->rows = rows; p->k = k; p->e = e; p->t = t; p->rp = (rows + t - 1u) / t * t; - p->x = malloc((size_t)p->rp * k * 4); p->w = malloc((size_t)e * k * 4); - p->wq = malloc(omega_gpu_pf_router_packed_bytes(e, k)); p->ref = malloc((size_t)rows * e * 4); - for (size_t i = 0; i < (size_t)p->rp * k; i++) p->x[i] = i < (size_t)rows * k ? rand_act() : u2f(0x7fc00000u); /* pad rows NaN: must not leak */ - for (size_t i = 0; i < (size_t)e * k; i++) p->w[i] = rand_bf16w(); - if (rows > 2) memset(p->x + 2 * (size_t)k, 0, k * 4); /* an all-zero row: every logit -0.0 + 0 products */ - omega_gpu_pf_router_pack(e, k, p->w, p->wq); - rl_ref(p->x, p->w, rows, k, e, p->ref, 0); -} -static void rl_free(RlProb *p) { free(p->x); free(p->w); free(p->wq); free(p->ref); } - -typedef struct { uint32_t rows, h, K; float *down, *wt, *ref; uint32_t *inv; } McProb; -static void mc_make(McProb *p, uint32_t rows, uint32_t h, uint32_t K) { - p->rows = rows; p->h = h; p->K = K; - const size_t g = (size_t)rows * K; - p->down = malloc(g * h * 4); p->wt = malloc(g * 4); p->inv = malloc(g * 4); p->ref = malloc((size_t)rows * h * 4); - for (size_t i = 0; i < g * h; i++) p->down[i] = rand_act() * 0.5f; - for (size_t i = 0; i < g; i++) { p->wt[i] = (float)(rnd() & 0xffff) / 65536.0f * 0.4f; p->inv[i] = (uint32_t)i; } - for (size_t i = g; i > 1; i--) { size_t j = rnd() % i; uint32_t t = p->inv[i - 1]; p->inv[i - 1] = p->inv[j]; p->inv[j] = t; } /* a permutation, like the expert sort */ - mc_ref(p->down, p->inv, p->wt, rows, h, K, p->ref, 0); -} -static void mc_free(McProb *p) { free(p->down); free(p->wt); free(p->inv); free(p->ref); } - -/* ---------------- host-only ---------------- */ -static int host_checks(void) { - int fail = 0; - /* packing: wq[g][ex][q] = w[ex][4g + q], pad group zero */ - { const uint32_t e = 32, k = 256; float *w = malloc(e * k * 4), *wq = malloc(omega_gpu_pf_router_packed_bytes(e, k)); - for (uint32_t i = 0; i < e * k; i++) w[i] = (float)i; - omega_gpu_pf_router_pack(e, k, w, wq); - size_t bad = 0; - for (uint32_t g = 0; g < k / 4; g++) for (uint32_t ex = 0; ex < e; ex++) for (uint32_t q = 0; q < 4; q++) if (wq[(g * e + ex) * 4 + q] != w[ex * k + 4 * g + q]) bad++; - for (uint32_t i = 0; i < e * 4; i++) if (f2u(wq[(k / 4) * e * 4 + i]) != 0) bad++; - printf("host pack R4: %zu wrong\n", bad); if (bad) fail++; - free(w); free(wq); } - /* the sum starts at -0.0 (Rust f32 Sum): an all-zero row gives -0.0 + (+0.0 products) = +0.0, a row of -0.0 products stays -0.0 */ - { float z = -0.0f; z = z + 0.0f * -1.0f; printf("host -0.0 start: -0 + (-0) = %s\n", signbit(z) ? "-0 (ok)" : "+0 (WRONG)"); if (!signbit(z)) fail++; } - /* the mutant references really differ */ - { RlProb p; rl_make(&p, 5, 256, 32, 4); float *m = malloc(5 * 32 * 4); - for (int mu = 1; mu <= 2; mu++) { rl_ref(p.x, p.w, 5, 256, 32, m, mu); size_t d = diff_bits(m, p.ref, 5 * 32); printf("host router mutant %d reference differs in %zu of 160\n", mu, d); if (!d) fail++; } - free(m); rl_free(&p); } - { McProb p; mc_make(&p, 3, 128, 8); float *m = malloc(3 * 128 * 4); - for (int mu = 1; mu <= 2; mu++) { mc_ref(p.down, p.inv, p.wt, 3, 128, 8, m, mu); size_t d = diff_bits(m, p.ref, 3 * 128); printf("host combine mutant %d reference differs in %zu of 384\n", mu, d); if (!d) fail++; } - free(m); mc_free(&p); } - return fail; -} - -/* ---------------- simulator ---------------- */ -static int rl_sim_one(const RlProb *p, int mutant, int order, float *lg, char *msg, size_t msgn) { - OmegaRlSpec sp = { p->k, p->e, p->t, mutant }; - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_rl_prog(&sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - const size_t lgb = (size_t)p->rp * p->e * 4, wqb = omega_gpu_pf_router_packed_bytes(p->e, p->k); - uint8_t *smem = malloc(omega_rl_shared_bytes(&sp)); - static WsSim ws; memset(&ws, 0, sizeof ws); - ws.p = &prog; ws.threads = p->e; ws.smem = smem; ws.smem_bytes = omega_rl_shared_bytes(&sp); ws.order = order; - uint64_t a[3] = { (uintptr_t)p->x, (uintptr_t)p->wq, (uintptr_t)lg }; - for (int i = 0; i < 3; i++) { ws.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; ws.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - ws.ranges[0].lo = (uintptr_t)p->x; ws.ranges[0].hi = (uintptr_t)p->x + (size_t)p->rp * p->k * 4; - ws.ranges[1].lo = (uintptr_t)p->wq; ws.ranges[1].hi = (uintptr_t)p->wq + wqb; - ws.ranges[2].lo = (uintptr_t)lg; ws.ranges[2].hi = (uintptr_t)lg + lgb; - ws.nranges = 3; - memset(lg, 0xee, lgb); - int err = ws_run(&ws, p->rp / p->t, 1); - if (err) snprintf(msg, msgn, "simulator %.150s", ws.msg); - free(smem); - return err ? -1 : 0; -} -static int mc_sim_one(const McProb *p, int mutant, int order, float *out, char *msg, size_t msgn) { - OmegaMcSpec sp = { p->h, p->K, mutant }; - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_mc_prog(&sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - const size_t g = (size_t)p->rows * p->K; - static WsSim ws; memset(&ws, 0, sizeof ws); - ws.p = &prog; ws.threads = p->h / 4; ws.order = order; - uint64_t a[4] = { (uintptr_t)p->down, (uintptr_t)p->inv, (uintptr_t)p->wt, (uintptr_t)out }; - for (int i = 0; i < 4; i++) { ws.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; ws.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - ws.ranges[0].lo = (uintptr_t)p->down; ws.ranges[0].hi = (uintptr_t)p->down + g * p->h * 4; - ws.ranges[1].lo = (uintptr_t)p->inv; ws.ranges[1].hi = (uintptr_t)p->inv + g * 4; - ws.ranges[2].lo = (uintptr_t)p->wt; ws.ranges[2].hi = (uintptr_t)p->wt + g * 4; - ws.ranges[3].lo = (uintptr_t)out; ws.ranges[3].hi = (uintptr_t)out + (size_t)p->rows * p->h * 4; - ws.nranges = 4; - memset(out, 0xee, (size_t)p->rows * p->h * 4); - int err = ws_run(&ws, p->rows, 1); - if (err) snprintf(msg, msgn, "simulator %.150s", ws.msg); - return err ? -1 : 0; -} -static int sim_checks(void) { - int fail = 0; char msg[200]; - static const struct { uint32_t rows, k, e, t; } rc[] = { { 37, 2048, 128, 16 }, { 9, 256, 32, 4 }, { 21, 384, 64, 8 }, { 16, 2048, 128, 4 } }; - for (size_t c = 0; c < sizeof rc / sizeof rc[0]; c++) { - RlProb p; rl_make(&p, rc[c].rows, rc[c].k, rc[c].e, rc[c].t); - float *lg = malloc((size_t)p.rp * p.e * 4); - for (int order = 0; order < 2; order++) { - int r = rl_sim_one(&p, 0, order, lg, msg, sizeof msg); - size_t bad = r ? 0 : diff_bits(lg, p.ref, (size_t)p.rows * p.e); - printf("sim router k %u e %u t %u rows %u order %d: %s, %zu of %zu differ\n", p.k, p.e, p.t, p.rows, order, r ? msg : "ran", bad, (size_t)p.rows * p.e); - if (r || bad) fail++; - } - if (c == 0) for (int mu = 1; mu <= 2; mu++) { - int r = rl_sim_one(&p, mu, 0, lg, msg, sizeof msg); - size_t bad = r ? 0 : diff_bits(lg, p.ref, (size_t)p.rows * p.e); - printf("sim router mutant %d: %s\n", mu, r ? msg : bad ? "caught" : "NOT CAUGHT"); - if (r || !bad) fail++; - } - free(lg); rl_free(&p); - } - static const struct { uint32_t rows, h, K; } mc[] = { { 7, 2048, 8 }, { 5, 128, 4 }, { 3, 384, 16 } }; - for (size_t c = 0; c < sizeof mc / sizeof mc[0]; c++) { - McProb p; mc_make(&p, mc[c].rows, mc[c].h, mc[c].K); - float *out = malloc((size_t)p.rows * p.h * 4); - for (int order = 0; order < 2; order++) { - int r = mc_sim_one(&p, 0, order, out, msg, sizeof msg); - size_t bad = r ? 0 : diff_bits(out, p.ref, (size_t)p.rows * p.h); - printf("sim combine h %u top_k %u rows %u order %d: %s, %zu of %zu differ\n", p.h, p.K, p.rows, order, r ? msg : "ran", bad, (size_t)p.rows * p.h); - if (r || bad) fail++; - } - if (c == 0) for (int mu = 1; mu <= 2; mu++) { - int r = mc_sim_one(&p, mu, 0, out, msg, sizeof msg); - size_t bad = r ? 0 : diff_bits(out, p.ref, (size_t)p.rows * p.h); - printf("sim combine mutant %d: %s\n", mu, r ? msg : bad ? "caught" : "NOT CAUGHT"); - if (r || !bad) fail++; - } - free(out); mc_free(&p); - } - return fail; -} - -/* ---------------- chip ---------------- */ -static int alloc_fill(int host, size_t bytes, const void *src, OmegaGpuMem *m) { - bytes = (bytes + 15u) & ~(size_t)15u; - int rc = host ? omega_gpu_pf_alloc_host(bytes, m) : omega_gpu_pf_alloc_dev(bytes, m); - if (rc) return rc; - if (!src) return 0; - if (host) { memcpy(m->cpu, src, bytes); return 0; } - return omega_gpu_pf_upload(m, 0, src, bytes); -} -static int rl_chip(uint32_t rows, int reps) { - int fail = 0; - const uint32_t k = 2048, e = 128, t = omega_gpu_pf_router_rows(); - RlProb p; rl_make(&p, rows, k, e, t); - const size_t lgb = (size_t)p.rp * e * 4; - OmegaGpuMem xd = { 0 }, wd = { 0 }, ld = { 0 }; - /* as the driver: x and logits in HOST (GPU-uncached) buffers, the packed weights GPU-cached */ - int rc = alloc_fill(1, (size_t)p.rp * k * 4, p.x, &xd); - if (!rc) rc = alloc_fill(0, omega_gpu_pf_router_packed_bytes(e, k), p.wq, &wd); - if (!rc) rc = alloc_fill(1, lgb, NULL, &ld); - uint64_t ns[32] = { 0 }; if (reps > 32) reps = 32; if (reps < 1) reps = 1; - float *lg = malloc(lgb); - for (int r = 0; r < reps && !rc; r++) { memset(ld.cpu, 0xee, lgb); rc = omega_gpu_pf_router_logits(k, e, rows, xd.va, wd.va, ld.va, &ns[r]); } - if (rc) { printf("ROUTER chip rows %u: %s (%s)\n", rows, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); fail++; } - else { - memcpy(lg, ld.cpu, lgb); - size_t bad = diff_bits(lg, p.ref, (size_t)rows * e); - qsort(ns, (size_t)reps, 8, cmp_u64); - printf("ROUTER chip k %u e %u t %u rows %u: %zu of %zu differ from the host loop; median %.3f ms\n", k, e, t, rows, bad, (size_t)rows * e, ns[reps / 2] / 1e6); - if (bad) fail++; - for (int mu = 1; mu <= 2; mu++) { - omega_gpu_pf_router_test_set_mutant(mu); - memset(ld.cpu, 0xee, lgb); - int mrc = omega_gpu_pf_router_logits(k, e, rows, xd.va, wd.va, ld.va, NULL); - omega_gpu_pf_router_test_set_mutant(0); - memcpy(lg, ld.cpu, lgb); - size_t mb = mrc ? 0 : diff_bits(lg, p.ref, (size_t)rows * e); - printf("ROUTER chip mutant %d: %s\n", mu, mrc ? "launch failed" : mb ? "caught" : "NOT CAUGHT"); - if (mrc || !mb) fail++; - } - } - free(lg); omega_gpu_pf_free(&xd); omega_gpu_pf_free(&wd); omega_gpu_pf_free(&ld); rl_free(&p); - return fail; -} -static int mc_chip(uint32_t rows, int reps) { - int fail = 0; - const uint32_t h = 2048, K = 8; - McProb p; mc_make(&p, rows, h, K); - const size_t g = (size_t)rows * K, ob = (size_t)rows * h * 4; - OmegaGpuMem dd = { 0 }, id = { 0 }, wd = { 0 }, od = { 0 }; - /* as the driver: down rows GPU-cached (the down GEMM writes them), inv / weights / out in HOST buffers */ - int rc = alloc_fill(0, g * h * 4, p.down, &dd); - if (!rc) rc = alloc_fill(1, g * 4, p.inv, &id); - if (!rc) rc = alloc_fill(1, g * 4, p.wt, &wd); - if (!rc) rc = alloc_fill(1, ob, NULL, &od); - uint64_t ns[32] = { 0 }; if (reps > 32) reps = 32; if (reps < 1) reps = 1; - float *out = malloc(ob); - for (int r = 0; r < reps && !rc; r++) { memset(od.cpu, 0xee, ob); rc = omega_gpu_pf_moe_combine(h, K, rows, dd.va, id.va, wd.va, od.va, &ns[r]); } - if (rc) { printf("COMBINE chip rows %u: %s (%s)\n", rows, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); fail++; } - else { - memcpy(out, od.cpu, ob); - size_t bad = diff_bits(out, p.ref, (size_t)rows * h); - qsort(ns, (size_t)reps, 8, cmp_u64); - printf("COMBINE chip h %u top_k %u rows %u: %zu of %zu differ from the host loop; median %.3f ms\n", h, K, rows, bad, (size_t)rows * h, ns[reps / 2] / 1e6); - if (bad) fail++; - for (int mu = 1; mu <= 2; mu++) { - omega_gpu_pf_combine_test_set_mutant(mu); - memset(od.cpu, 0xee, ob); - int mrc = omega_gpu_pf_moe_combine(h, K, rows, dd.va, id.va, wd.va, od.va, NULL); - omega_gpu_pf_combine_test_set_mutant(0); - memcpy(out, od.cpu, ob); - size_t mb = mrc ? 0 : diff_bits(out, p.ref, (size_t)rows * h); - printf("COMBINE chip mutant %d: %s\n", mu, mrc ? "launch failed" : mb ? "caught" : "NOT CAUGHT"); - if (mrc || !mb) fail++; - } - } - free(out); omega_gpu_pf_free(&dd); omega_gpu_pf_free(&id); omega_gpu_pf_free(&wd); omega_gpu_pf_free(&od); mc_free(&p); - return fail; -} - -int main(int argc, char **argv) { - int host = 1, sim = 1, chip = 0, reps = 7; uint32_t tokens = 2048; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) sim = 0; - else if (!strcmp(argv[i], "--sim")) host = 0; - else if (!strcmp(argv[i], "--chip")) { chip = 1; host = 0; sim = 0; } - else if (!strcmp(argv[i], "--tokens") && i + 1 < argc) tokens = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = atoi(argv[++i]); - } - int fail = 0; - if (host) fail += host_checks(); - if (sim) fail += sim_checks(); - if (chip) { - fail += rl_chip(tokens, reps); fail += rl_chip(37, 3); - fail += mc_chip(tokens, reps); fail += mc_chip(7, 3); - } - printf("GPU_PFHOST: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} diff --git a/tests/gpu_prefill_attn256_test.c b/tests/gpu_prefill_attn256_test.c deleted file mode 100644 index 72374f11b..000000000 --- a/tests/gpu_prefill_attn256_test.c +++ /dev/null @@ -1,605 +0,0 @@ -/* - * gpu_prefill_attn256_test: the head_dim 256 causal prefill attention for Qwen3.8-27B (omega-mv#545, - * omega_gpu_prefill_attn256_api.h), on the decode attention's cache (omega_gpu_decode_attn256_api.h). - * --host-only codegen budgets of both kernels (instructions <= 1024, registers within the opt-in limit and the - * 256-thread register file, attend placeholders patched), refusals, layout constants. No device. - * --sim both launches through tests/bw_warp_sim_pa.h (no chip): several (pos0, m) points incl. odd starts, - * history, a 256 boundary and full rope; both fragment orders on the small points. Gates: appended K/V - * rows bit-equal to m runs of the DECODE program on a twin cache (the same simulator), outputs within - * the tolerance of a double reference, prep mutants 1 and 3 and attend mutants 1 and 2 caught. The q' - * scratch starts as NaN so a read of a slot the prep launch never wrote shows up. - * (default) the chip: parity against the double reference (every token up to 512 tokens, 8 sampled tokens - * above), rows bit-identical to m decode calls on a twin cache and the next decode step on both caches - * bit-identical, second call identical, out_scale 2^20 exact, device entry == host entry, mutants caught, - * timing medians of 2048-token chunks at contexts 2k, 8k, 32k (and 128k with --max-pos 131072); JSON - * receipt with --out. - * The reference works in the model's dim order (crates/aien-inference-abi/src/qwen38.rs `attention`): zero-centred - * RMSNorm x * rsqrt(mean + eps) * (1 + w), RoPE on the first rotary_dim dims with pairs (j, j + rotary_dim/2), scores - * q.k / sqrt(256), causal softmax. The kernel sees q, k and the norm weights permuted (omega_dattn256_perm_vec) and K rows - * permuted; V and the output are in model order. - * Tolerance: |out - ref| <= 5e-3 * max|v| * out_scale per element. The reference rounds q' * (log2(e) / 16) to bf16 as - * the prep kernel does (from double, the kernel from f32: rare one-ulp differences) and uses its own bf16 K/V rows; what - * remains is P rounded to bf16 for the tensor cores (relative 2^-9 per weight, l summed from the unrounded p: - * <= 2^-9 * max|v| = 0.0020) and f32 / EX2 error (~2^-22). The measured worst ratio is printed; the mutants miss by far - * more. Host and simulator passes are never chip results. - */ -#include "omega_gpu_prefill_attn256_api.h" -#include "omega_gpu_session.h" -#include "omega_blackwell_codegen_tc.h" -#include "bw_warp_sim_pa.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static const double THETA = 10000000.0; /* Qwen3.8-27B rope_theta */ -static const float EPS = 1e-6f; -#define HD 256u -/* Model shape under test: the 27B (24 q / 4 KV heads, 6 q per decode CTA row); -DPATTN_TEST_Q36 builds - * Qwen3.6-35B-A3B (16 / 2 / 4: 8 q per KV head, two decode CTA rows per KV head; sc L306). */ -#ifdef PATTN_TEST_Q36 -#define QH 16u -#define KVH 2u -#define QPC 4u -#else -#define QH 24u -#define KVH 4u -#define QPC 6u -#endif -#define VY (QH / QPC) /* decode / prep CTA rows */ -#define SPEC_SHAPE , .q_heads = QH, .kv_heads = KVH, .q_per_cta = QPC -#define ATT_SHAPE , .q_heads = QH, .kv_heads = KVH -#define QW ((QH + 2u * KVH) * HD) /* 8192 */ -#define OW (QH * HD) /* 6144 */ -#define QFP (QH * 1024u) /* q' bytes per token pair */ -#define QEND (QH * HD) -#define KEND (QEND + KVH * HD) -#define RB OMEGA_DATTN256_ROW_BYTES -static const float QKS = (float)((1.0 / 16.0) * 1.4426950408889634); -#define TOL_REL 5e-3 - -/* one layer's random state in MODEL order: m qkv rows, norm weights w (zero-centred), history rows 0..pos0-1 */ -typedef struct { - uint32_t max_pos, pos0, m, rotary; - float *qkv; /* [m][8192] */ - float qn[HD], kn[HD]; - uint16_t *kc, *vc; /* [4][max_pos][256] model order */ -} Case; -static void case_make(Case *c, uint32_t max_pos, uint32_t pos0, uint32_t m, uint32_t rotary, uint32_t seed, float qscale) { - uint32_t s = seed; - c->max_pos = max_pos; c->pos0 = pos0; c->m = m; c->rotary = rotary; - c->qkv = malloc((size_t)m * QW * 4); - for (size_t t = 0; t < m; t++) for (size_t i = 0; i < QW; i++) c->qkv[t * QW + i] = frand(&s, -1.0f, 1.0f) * (i < QEND ? qscale : 1.0f); - for (unsigned i = 0; i < HD; i++) { c->qn[i] = frand(&s, -0.2f, 0.2f); c->kn[i] = frand(&s, -0.2f, 0.2f); } - size_t words = (size_t)KVH * max_pos * HD; - c->kc = calloc(words, 2); c->vc = calloc(words, 2); - for (unsigned g = 0; g < KVH; g++) for (uint32_t t = 0; t < pos0; t++) for (unsigned i = 0; i < HD; i++) { - size_t o = ((size_t)g * max_pos + t) * HD + i; - c->kc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); c->vc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); - } -} -static void case_free(Case *c) { free(c->qkv); free(c->kc); free(c->vc); } -/* the kernel's inputs: q and k heads permuted, v as is; norms 1 + w permuted */ -static void case_kernel_qkv(const Case *c, float *qkv_k) { - for (size_t t = 0; t < c->m; t++) { - const float *src = c->qkv + t * QW; float *dst = qkv_k + t * QW; - for (unsigned h = 0; h < QH + KVH; h++) omega_dattn256_perm_vec(src + h * HD, dst + h * HD, c->rotary); - memcpy(dst + KEND, src + KEND, (size_t)KVH * HD * 4); - } -} -static void case_kernel_norms(const Case *c, float *qn_k, float *kn_k) { - float t[HD]; - for (unsigned i = 0; i < HD; i++) t[i] = 1.0f + c->qn[i]; - omega_dattn256_perm_vec(t, qn_k, c->rotary); - for (unsigned i = 0; i < HD; i++) t[i] = 1.0f + c->kn[i]; - omega_dattn256_perm_vec(t, kn_k, c->rotary); -} -/* K history rows permuted, V as is, into a [K plane | V plane] buffer laid out like the cache (plane bytes apart) */ -static void case_history_into(const Case *c, uint8_t *kv, size_t plane) { - for (unsigned g = 0; g < KVH; g++) for (uint32_t t = 0; t < c->pos0; t++) { - size_t o = ((size_t)g * c->max_pos + t); - omega_dattn256_perm_vec_bf16(c->kc + o * HD, (uint16_t *)(kv + o * RB), c->rotary); - memcpy(kv + plane + o * RB, c->vc + o * HD, RB); - } -} - -/* ---- double-precision oracle (test-owned: libm) in MODEL order ---- */ -static void norm_rope(double *x, const float *w, float eps, uint32_t rotary, uint32_t pos) { - double ss = 0; for (unsigned i = 0; i < HD; i++) ss += x[i] * x[i]; - double r = 1.0 / sqrt(ss / (double)HD + (double)eps); - for (unsigned i = 0; i < HD; i++) x[i] = x[i] * r * (1.0 + (double)w[i]); - const unsigned half = rotary / 2; - for (unsigned j = 0; j < half; j++) { - double inv = 1.0 / pow(THETA, (double)(2 * j) / (double)rotary), ang = (double)pos * inv, cs = cos(ang), sn = sin(ang); - double x1 = x[j], x2 = x[j + half]; - x[j] = x1 * cs - x2 * sn; x[j + half] = x2 * cs + x1 * sn; - } -} -/* the reference K/V rows (model order, bf16) of every chunk token: kn/vn [m][4][256] */ -static void ref_rows(const Case *c, uint16_t *kn, uint16_t *vn) { - for (size_t t = 0; t < c->m; t++) for (unsigned g = 0; g < KVH; g++) { - const float *row = c->qkv + t * QW; double k[HD]; - for (unsigned i = 0; i < HD; i++) k[i] = row[QEND + g * HD + i]; - norm_rope(k, c->kn, EPS, c->rotary, c->pos0 + (uint32_t)t); - for (unsigned i = 0; i < HD; i++) { kn[(t * KVH + g) * HD + i] = omega_dattn_bf16_rne((float)k[i]); vn[(t * KVH + g) * HD + i] = omega_dattn_bf16_rne(row[KEND + g * HD + i]); } - } -} -/* reference output of chunk token t: out[6144] (* out_scale) */ -static void ref_token(const Case *c, const uint16_t *kn, const uint16_t *vn, size_t t, float out_scale, double *out) { - const uint32_t pos = c->pos0 + (uint32_t)t; - double *p = malloc(((size_t)pos + 1) * sizeof(double)); - for (unsigned h = 0; h < QH; h++) { - const unsigned g = h / (QH / KVH); - double q[HD]; float qb[HD]; - for (unsigned i = 0; i < HD; i++) q[i] = c->qkv[t * QW + h * HD + i]; - norm_rope(q, c->qn, EPS, c->rotary, pos); - for (unsigned i = 0; i < HD; i++) qb[i] = omega_dattn_bf16_f32(omega_dattn_bf16_rne((float)(q[i] * (double)QKS))); - double mx = -1e300; - for (uint32_t j = 0; j <= pos; j++) { - const uint16_t *kr = j < c->pos0 ? c->kc + ((size_t)g * c->max_pos + j) * HD : kn + ((size_t)(j - c->pos0) * KVH + g) * HD; - double s = 0; for (unsigned i = 0; i < HD; i++) s += (double)qb[i] * (double)omega_dattn_bf16_f32(kr[i]); - p[j] = s; if (s > mx) mx = s; - } - double l = 0, o[HD]; memset(o, 0, sizeof o); - for (uint32_t j = 0; j <= pos; j++) { - const double w = exp2(p[j] - mx); l += w; - const uint16_t *vr = j < c->pos0 ? c->vc + ((size_t)g * c->max_pos + j) * HD : vn + ((size_t)(j - c->pos0) * KVH + g) * HD; - for (unsigned i = 0; i < HD; i++) o[i] += w * (double)omega_dattn_bf16_f32(vr[i]); - } - for (unsigned i = 0; i < HD; i++) out[h * HD + i] = o[i] / l * (double)out_scale; - } - free(p); -} -/* the tokens parity checks: all up to 512, else first 2, last 2 and 4 spread */ -static size_t parity_tokens(uint32_t m, uint32_t *tok) { - if (m <= 512) { for (uint32_t t = 0; t < m; t++) tok[t] = t; return m; } - const uint32_t pick[8] = { 0, 1, m / 5, (2 * m) / 5, (3 * m) / 5, (4 * m) / 5, m - 2, m - 1 }; - memcpy(tok, pick, sizeof pick); - return 8; -} -static size_t parity(const Case *c, const uint16_t *kn, const uint16_t *vn, const float *out, float out_scale, double *worst) { - uint32_t *tok = malloc((size_t)(c->m > 8 ? c->m : 8) * 4); size_t nt = parity_tokens(c->m, tok); - double *ref = malloc(OW * sizeof(double)), tol = TOL_REL * out_scale + 1e-6 * out_scale; size_t bad = 0; *worst = 0; - for (size_t k = 0; k < nt; k++) { - ref_token(c, kn, vn, tok[k], out_scale, ref); - for (size_t i = 0; i < OW; i++) { double d = fabs((double)out[(size_t)tok[k] * OW + i] - ref[i]); if (!(d <= tol)) bad++; if (d / tol > *worst || d != d) *worst = d != d ? INFINITY : d / tol; } - } - free(ref); free(tok); - return bad; -} -/* the rows the kernel appended (K permuted, V model order; [4][256] per token at kchip/vchip + t * 1024 words) against - * the reference rows: v exact, k as below */ -static float bf16f(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; memcpy(&f, &u, 4); return f; } -/* K rows: chip == ref, or one bf16 ulp apart (at most 32 per token), or, for a value left small by the rotation's - * cancellation (x1 cos - x2 sin), within 8 f32 roundings of the head row's largest |k| (8 * 2^-24 * rowmax): the - * chip rotates in f32, the oracle in double, and a 3-ulp gap at 7e-6 in a row of O(1) values is f32 rounding, not a - * kernel error (seen at 30720+2048 and 129024+2048 on 2026-10-18; the rows were bit-equal to the decode program's). */ -static int rows_ok(const Case *c, const uint16_t *kchip, const uint16_t *vchip, const uint16_t *kn, const uint16_t *vn, char *why, size_t n) { - unsigned flips = 0, worst_tok = 0, small = 0; - for (size_t t = 0; t < c->m; t++) { - unsigned tf = 0; - for (unsigned g = 0; g < KVH; g++) { - float rowmax = 0; - for (unsigned i = 0; i < HD; i++) { float a = fabsf(bf16f(kn[(t * KVH + g) * HD + i])); if (a > rowmax) rowmax = a; } - for (unsigned i = 0; i < HD; i++) { - size_t ci = (t * KVH + g) * HD + i, ri = (t * KVH + g) * HD + omega_dattn256_perm_slot(i, c->rotary); - if (vchip[ci] != vn[ci]) { snprintf(why, n, "token %zu v[%u][%u] chip %04x ref %04x", t, g, i, vchip[ci], vn[ci]); return 0; } - if (kchip[ci] == kn[ri]) continue; - int d = (int)kchip[ci] - (int)kn[ri]; - if (d >= -1 && d <= 1) { tf++; continue; } - if (fabsf(bf16f(kchip[ci]) - bf16f(kn[ri])) <= 8.0f * 0x1p-24f * rowmax) { small++; continue; } - snprintf(why, n, "token %zu k[%u] slot %u chip %04x ref %04x (row max %.3g)", t, g, i, kchip[ci], kn[ri], (double)rowmax); - return 0; - } - } - if (tf > 32) { snprintf(why, n, "token %zu: %u one-ulp k flips", t, tf); return 0; } - if (tf > worst_tok) worst_tok = tf; - flips += tf; - } - snprintf(why, n, "ok (%u one-ulp k flips, worst token %u; %u small-value k gaps within 8 f32 roundings of the row max)", flips, worst_tok, small); - return 1; -} -/* ------------------------------------------------------------- host only */ -static void host_only(void) { - for (int m = 0; m <= 2; m++) { - OmegaPrefillAttn256Spec s = { .mutant = m ATT_SHAPE }; uint32_t n = 0, gp = 0, ph = 0; - int rc = omega_prefill_attn256_prog_stats(&s, &n, &gp, &ph); - const uint32_t dec = omega_bw_gpr_declared(gp); - CHECK(rc == 0 && n <= BW_MAX_IR_INSNS && gp <= BW_PHYS_GPR_HW_LIMIT && 256u * dec <= 65536u && ph > 0, - "attend codegen mutant %d: rc %d insns %u gprs %u (declared %u) placeholders %u", m, rc, n, gp, dec, ph); - if (rc == 0 && m == 0) printf("attend: %u instructions, %u registers (declared %u, 256 threads -> %u of 65536), %u placeholders\n", n, gp, dec, 256 * dec, ph); - } - { OmegaPrefillAttn256Spec s = { .mutant = 3 ATT_SHAPE }; CHECK(omega_prefill_attn256_prog_stats(&s, NULL, NULL, NULL) != 0, "attend mutant 3 refused"); - s.mutant = -1; CHECK(omega_prefill_attn256_prog_stats(&s, NULL, NULL, NULL) != 0, "attend mutant -1 refused"); } - static const int pm[3] = { 0, 1, 3 }; - for (unsigned k = 0; k < 3; k++) { - OmegaDecodeAttn256Spec s = { .depth = OMEGA_GPU_DATTN256_DEPTH, .mutant = pm[k], .prep = 1 SPEC_SHAPE }; uint32_t n = 0, gp = 0; - int rc = omega_decode_attn256_prog_stats(&s, &n, &gp); - CHECK(rc == 0 && n <= BW_MAX_IR_INSNS && gp <= BW_PHYS_GPR_MAX - 2, "prep codegen mutant %d: rc %d insns %u gprs %u", pm[k], rc, n, gp); - if (rc == 0 && k == 0) printf("prep: %u instructions, %u registers\n", n, gp); - } - { OmegaDecodeAttn256Spec s = { .depth = 4, .prep = 2 SPEC_SHAPE }; CHECK(omega_decode_attn256_prog_stats(&s, NULL, NULL) != 0, "prep 2 refused"); } - static uint8_t code[1 << 17]; - for (unsigned k = 0; k < 2; k++) { - uint32_t gp = 0; int np = -1; size_t n = omega_gpu_prefill_attn256_encode(k, code, sizeof code, &gp, &np); - CHECK(n > 0 && (k == 0 ? np == 0 : np > 0), "encode %s: %zu bytes, gprs %u, %d placeholders patched", k ? "attend" : "prep", n, gp, np); - } - CHECK(omega_gpu_prefill_attn256_encode(2, code, sizeof code, NULL, NULL) == 0, "encode kind 2 refused"); - CHECK(omega_gpu_prefill_attn256_encode(1, code, 64, NULL, NULL) == 0, "encode into a too-small buffer refused"); - CHECK(OMEGA_PATTN256_SHARED_BYTES <= 16384u, "attend shared memory within the QMD cap"); - CHECK(OMEGA_PATTN256_QF_OFF_SHAPE(KVH, QH / KVH, 1, 0, 0, 0, 0) == QFP && OMEGA_PATTN256_QF_OFF_SHAPE(KVH, QH / KVH, 0, KVH - 1, QH / KVH - 1, 15, 3) + 16u == QFP, "QF layout: one token pair is %u bytes, densely packed", QFP); - CHECK(OMEGA_PATTN256_QF_OFF(1, 0, 0, 0, 0) == OMEGA_PATTN256_QF_PAIR_BYTES, "QF layout: the 27B macro is the 4 x 6 case"); - CHECK(omega_gpu_prefill_attn256(NULL, 0, 0, 1, (const float *)code, EPS, 1.0f, (float *)code, NULL) == OMEGA_GPU_DATTN_BAD_ARGS, "NULL cache refused"); - CHECK(omega_gpu_prefill_attn256_reserve(0) == OMEGA_GPU_DATTN_BAD_ARGS && omega_gpu_prefill_attn256_reserve(OMEGA_GPU_PATTN256_MAX_M + 1) == OMEGA_GPU_DATTN_BAD_ARGS, "reserve 0 and above MAX_M refused before any device work"); - /* reference sanity: one token at position 0 returns its own rounded v */ - { Case c; case_make(&c, 256, 0, 1, 64, 11, 1.0f); uint16_t kn[KVH * HD], vn[KVH * HD]; double ref[OW]; - ref_rows(&c, kn, vn); ref_token(&c, kn, vn, 0, 1.0f, ref); - int good = 1; for (unsigned h = 0; h < QH; h++) for (unsigned i = 0; i < HD; i++) good &= fabs(ref[h * HD + i] - (double)omega_dattn_bf16_f32(vn[(h / (QH / KVH)) * HD + i])) < 1e-12; - CHECK(good, "reference: context 1 returns the rounded v of the head's KV group"); - case_free(&c); } -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -static uint32_t g_poison; /* --poison SEED: registers start as junk in every simulated CTA (tests/bw_warp_sim_pa.h reg_poison) */ -typedef struct { - const Case *c; - uint8_t *kv; size_t plane; - float *rope, *norms, *qkv_k; -} SimBufs; -static void cb64(WsSim *s, unsigned off, const void *p) { uint64_t a = (uintptr_t)p; s->cbank[off / 4] = (uint32_t)a; s->cbank[off / 4 + 1] = (uint32_t)(a >> 32); } -static void cbf(WsSim *s, unsigned off, float f) { memcpy(&s->cbank[off / 4], &f, 4); } -/* the decode program (prep 0 or 1) at position pos (prep: tokens pos .. pos+grid_x-1, qkv rows from qkv_k) */ -static int sim_decode_launch(const BlackwellIRProgram *prog, const SimBufs *b, uint32_t pos, uint32_t grid_x, const float *qkv_k, size_t qkv_bytes, - void *out, size_t out_bytes, float *part, size_t part_bytes, uint32_t *cnt, uint32_t splits, int order, char *msg, size_t n) { - static uint8_t smem[OMEGA_DATTN256_SHARED_BYTES]; - WsSim s; memset(&s, 0, sizeof s); - s.p = prog; s.threads = 256; s.order = order; s.reg_poison = g_poison; s.smem = smem; s.smem_bytes = sizeof smem; - cb64(&s, OMEGA_DATTN256_ARG_QKV, qkv_k); cb64(&s, OMEGA_DATTN256_ARG_KC, b->kv); cb64(&s, OMEGA_DATTN256_ARG_VC, b->kv + b->plane); - cb64(&s, OMEGA_DATTN256_ARG_ROPE, b->rope); cb64(&s, OMEGA_DATTN256_ARG_QN, b->norms); cb64(&s, OMEGA_DATTN256_ARG_KN, b->norms + HD); - cb64(&s, OMEGA_DATTN256_ARG_OUT, out); cb64(&s, OMEGA_DATTN256_ARG_PART, part); cb64(&s, OMEGA_DATTN256_ARG_CNT, cnt); - s.cbank[OMEGA_DATTN256_ARG_POS / 4] = pos; s.cbank[OMEGA_DATTN256_ARG_PER_SPLIT / 4] = 256; s.cbank[OMEGA_DATTN256_ARG_SPLITS / 4] = splits; - s.cbank[OMEGA_DATTN256_ARG_KV_STRIDE / 4] = b->c->max_pos * RB; - cbf(&s, OMEGA_DATTN256_ARG_EPS, EPS); cbf(&s, OMEGA_DATTN256_ARG_OUT_SCALE, 1.0f); cbf(&s, OMEGA_DATTN256_ARG_QK_SCALE, QKS); - s.nranges = 5; - s.ranges[0].lo = (uintptr_t)qkv_k; s.ranges[0].hi = (uintptr_t)qkv_k + qkv_bytes; - s.ranges[1].lo = (uintptr_t)b->kv; s.ranges[1].hi = (uintptr_t)b->kv + 2 * b->plane; - s.ranges[2].lo = (uintptr_t)b->rope; s.ranges[2].hi = (uintptr_t)b->rope + (size_t)b->c->max_pos * OMEGA_DATTN256_ROPE_ROW_BYTES; - s.ranges[3].lo = (uintptr_t)b->norms; s.ranges[3].hi = (uintptr_t)b->norms + 2048; - s.ranges[4].lo = (uintptr_t)out; s.ranges[4].hi = (uintptr_t)out + out_bytes; - if (part) { /* prep never touches the partials or counters: no range, so a stray access faults */ - s.ranges[5].lo = (uintptr_t)part; s.ranges[5].hi = (uintptr_t)part + part_bytes; - s.ranges[6].lo = (uintptr_t)cnt; s.ranges[6].hi = (uintptr_t)cnt + 16; s.nranges = 7; - } - int err = ws_run(&s, grid_x, VY); - if (err) { snprintf(msg, n, "%s launch at %u: %s (pc %d)", part ? "decode" : "prep", pos, s.msg, s.err_pc); return -1; } - g_sim_issues += s.warp_issues; - return 0; -} -static int sim_attend_launch(const BlackwellIRProgram *prog, const SimBufs *b, const uint8_t *qf, size_t qf_bytes, float *out, int order, char *msg, size_t n) { - static uint8_t smem[OMEGA_PATTN256_SHARED_BYTES]; - const Case *c = b->c; - WsSim s; memset(&s, 0, sizeof s); - s.p = prog; s.threads = OMEGA_PATTN256_THREADS; s.order = order; s.reg_poison = g_poison; s.smem = smem; s.smem_bytes = sizeof smem; - cb64(&s, OMEGA_PATTN256_ARG_QF, qf); cb64(&s, OMEGA_PATTN256_ARG_KC, b->kv); cb64(&s, OMEGA_PATTN256_ARG_VC, b->kv + b->plane); cb64(&s, OMEGA_PATTN256_ARG_OUT, out); - s.cbank[OMEGA_PATTN256_ARG_POS0 / 4] = c->pos0; s.cbank[OMEGA_PATTN256_ARG_MC / 4] = c->m; s.cbank[OMEGA_PATTN256_ARG_KV_STRIDE / 4] = c->max_pos * RB; - cbf(&s, OMEGA_PATTN256_ARG_OUT_SCALE, 1.0f); - s.nranges = 3; - s.ranges[0].lo = (uintptr_t)qf; s.ranges[0].hi = (uintptr_t)qf + qf_bytes; - s.ranges[1].lo = (uintptr_t)b->kv; s.ranges[1].hi = (uintptr_t)b->kv + 2 * b->plane; - s.ranges[2].lo = (uintptr_t)out; s.ranges[2].hi = (uintptr_t)out + (size_t)c->m * OW * 4; - int err = ws_run(&s, (c->m + OMEGA_PATTN256_TOKENS - 1) / OMEGA_PATTN256_TOKENS, KVH); - if (err) { snprintf(msg, n, "attend: %s (pc %d)", s.msg, s.err_pc); return -1; } - g_sim_issues += s.warp_issues; - return 0; -} -static int sim_point(uint32_t max_pos, uint32_t pos0, uint32_t m, uint32_t rotary, float qscale, uint32_t seed, int orders, int prep_mut, int att_mut, - char *msg, size_t n, double *worst, size_t *bad) { - static BlackwellIRProgram pprog, aprog, dprog; - OmegaDecodeAttn256Spec ps = { .depth = OMEGA_GPU_DATTN256_DEPTH, .mutant = prep_mut, .prep = 1 SPEC_SHAPE }, ds = { .depth = OMEGA_GPU_DATTN256_DEPTH SPEC_SHAPE }; - OmegaPrefillAttn256Spec as = { .mutant = att_mut ATT_SHAPE }; - if (omega_blackwell_codegen_decode_attn256_prog(&ps, &pprog) != 0 || omega_blackwell_codegen_prefill_attn256_prog(&as, &aprog) != 0 || - omega_blackwell_codegen_decode_attn256_prog(&ds, &dprog) != 0) { snprintf(msg, n, "codegen refused"); return -1; } - Case c; case_make(&c, max_pos, pos0, m, rotary, seed, qscale); - SimBufs b = { .c = &c }; - b.plane = (size_t)KVH * max_pos * RB + OMEGA_DATTN256_PLANE_SLACK; - b.kv = aligned_alloc(16, 2 * b.plane); - uint8_t *twin = aligned_alloc(16, 2 * b.plane); - b.rope = aligned_alloc(16, (size_t)max_pos * OMEGA_DATTN256_ROPE_ROW_BYTES); - for (uint32_t p = 0; p < max_pos; p++) omega_dattn256_rope_row(p, THETA, rotary, b.rope + (size_t)p * 256); - b.norms = aligned_alloc(16, 2048); case_kernel_norms(&c, b.norms, b.norms + HD); - b.qkv_k = aligned_alloc(16, (size_t)m * QW * 4); case_kernel_qkv(&c, b.qkv_k); - const size_t qf_bytes = (size_t)((m + 1) / 2) * QFP; - uint8_t *qf = aligned_alloc(16, qf_bytes); - float *out = aligned_alloc(16, (size_t)m * OW * 4), *copy = malloc((size_t)m * OW * 4); - int err = 0; - for (int order = 0; order < orders && !err; order++) { - memset(b.kv, 0, 2 * b.plane); case_history_into(&c, b.kv, b.plane); - memset(qf, 0xff, qf_bytes); /* NaN bf16 pairs: a slot the prep never wrote poisons its row */ - for (size_t i = 0; i < (size_t)m * OW; i++) out[i] = -999.0f; - err = sim_decode_launch(&pprog, &b, pos0, m, b.qkv_k, (size_t)m * QW * 4, qf, qf_bytes, NULL, 0, NULL, 0, order, msg, n); - if (!err) err = sim_attend_launch(&aprog, &b, qf, qf_bytes, out, order, msg, n); - if (err) break; - size_t unwritten = 0; for (size_t i = 0; i < (size_t)m * OW; i++) if (out[i] == -999.0f) unwritten++; - if (unwritten) { err = -1; snprintf(msg, n, "%zu output words never written", unwritten); break; } - if (order == 0) memcpy(copy, out, (size_t)m * OW * 4); - else if (memcmp(copy, out, (size_t)m * OW * 4) != 0) { err = -1; snprintf(msg, n, "the fragment order changed the result"); } - } - if (!err) { - /* twin: m decode steps of the decode program from the same history */ - memset(twin, 0, 2 * b.plane); case_history_into(&c, twin, b.plane); - SimBufs tb = b; tb.kv = twin; - float *dout = aligned_alloc(16, OW * 4); - const uint32_t smax = (pos0 + m + 255) / 256; - float *part = aligned_alloc(16, (size_t)VY * smax * OMEGA_DATTN256_PARTIAL_WORDS * 4); - uint32_t *cnt = aligned_alloc(16, 16); - for (uint32_t t = 0; t < m && !err; t++) { - const uint32_t pos = pos0 + t, splits = (pos + 256) / 256; - memset(cnt, 0, 16); - err = sim_decode_launch(&dprog, &tb, pos, splits, b.qkv_k + (size_t)t * QW, QW * 4, dout, OW * 4, part, (size_t)VY * splits * OMEGA_DATTN256_PARTIAL_WORDS * 4, cnt, splits, 0, msg, n); - } - free(dout); free(part); free(cnt); - size_t rowdiff = 0; - for (unsigned h = 0; h < 2 * KVH && !err; h++) { - const size_t o = (h >= KVH ? b.plane : 0) + (size_t)(h % KVH) * max_pos * RB; - for (uint32_t t = 0; t < pos0 + m; t++) rowdiff += memcmp(b.kv + o + (size_t)t * RB, twin + o + (size_t)t * RB, RB) != 0; - } - uint16_t *kn = malloc((size_t)m * KVH * HD * 2), *vn = malloc((size_t)m * KVH * HD * 2), *kch = malloc((size_t)m * KVH * HD * 2), *vch = malloc((size_t)m * KVH * HD * 2); - ref_rows(&c, kn, vn); - for (uint32_t t = 0; t < m; t++) for (unsigned g = 0; g < KVH; g++) { - const size_t o = ((size_t)g * max_pos + pos0 + t) * RB; - memcpy(kch + ((size_t)t * KVH + g) * HD, b.kv + o, RB); memcpy(vch + ((size_t)t * KVH + g) * HD, b.kv + b.plane + o, RB); - } - char why[160]; - if (!err) { - int rok = rows_ok(&c, kch, vch, kn, vn, why, sizeof why); - *bad = parity(&c, kn, vn, out, 1.0f, worst); - if (rowdiff) *bad += 1000000; - if (!rok) *bad += 2000000; - snprintf(msg, n, "bad=%zu worst=%.3f rows vs decode twin: %zu differ; vs reference: %s", *bad, *worst, rowdiff, why); - } - free(kn); free(vn); free(kch); free(vch); - } - free(b.kv); free(twin); free(b.rope); free(b.norms); free(b.qkv_k); free(qf); free(out); free(copy); case_free(&c); - return err; -} -static void sim_battery(void) { - char msg[400]; double worst; size_t bad; - struct { uint32_t max_pos, pos0, m, rot; float qs; int orders; const char *name; } pts[] = { - { 256, 0, 1, 64, 1.0f, 2, "one token at position 0" }, - { 256, 0, 8, 64, 1.0f, 2, "8 tokens from 0 (one CTA)" }, - { 256, 0, 37, 64, 1.0f, 2, "37 tokens from 0 (odd m, partial CTA)" }, - { 256, 37, 19, 64, 1.0f, 2, "19 tokens from 37 (odd start)" }, - { 256, 100, 19, 64, 4.0f, 1, "19 tokens from 100, sharp q (x4)" }, - { 512, 250, 40, 64, 1.0f, 1, "40 tokens from 250 (crosses 256)" }, - { 256, 0, 24, 256, 1.0f, 1, "24 tokens from 0, full rope (rotary 256)" }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - double t0 = now_ms(); - int err = sim_point(pts[i].max_pos, pts[i].pos0, pts[i].m, pts[i].rot, pts[i].qs, 100 + (uint32_t)i, pts[i].orders, 0, 0, msg, sizeof msg, &worst, &bad); - CHECK(err == 0 && bad == 0, "sim %s: %s", pts[i].name, msg); - printf("sim %-42s %s %s (%.1f s)\n", pts[i].name, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg, (now_ms() - t0) / 1e3); - fflush(stdout); - } - static const struct { int pm, am; } mut[] = { { 1, 0 }, { 3, 0 }, { 0, 1 }, { 0, 2 } }; - for (size_t i = 0; i < sizeof mut / sizeof mut[0]; i++) { - int err = sim_point(256, 40, 24, 64, 1.0f, 200, 1, mut[i].pm, mut[i].am, msg, sizeof msg, &worst, &bad); - int caught = err != 0 || bad > 0; - CHECK(caught, "sim %s mutant %d NOT caught (%s)", mut[i].pm ? "prep" : "attend", mut[i].pm ? mut[i].pm : mut[i].am, msg); - printf("sim %s mutant %d at 24 tokens from 40: %s (%s)\n", mut[i].pm ? "prep" : "attend", mut[i].pm ? mut[i].pm : mut[i].am, caught ? "caught" : "MISSED", msg); - fflush(stdout); - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static FILE *g_json; -static int g_json_first = 1; -static int cache_with_history(const Case *c, OmegaGpuDecodeAttn256Cache **out) { - int rc = omega_gpu_decode_attn256_cache_alloc_shape(1, c->max_pos, THETA, c->rotary, QH, KVH, QPC, out); - if (rc != OMEGA_GPU_DATTN_OK) return rc; - float qn_k[HD], kn_k[HD]; case_kernel_norms(c, qn_k, kn_k); - rc = omega_gpu_decode_attn256_set_norms(*out, 0, qn_k, kn_k); - if (rc != OMEGA_GPU_DATTN_OK || c->pos0 == 0) return rc; - uint16_t *kp = malloc((size_t)c->pos0 * RB); - for (unsigned g = 0; g < KVH && rc == OMEGA_GPU_DATTN_OK; g++) { - for (uint32_t t = 0; t < c->pos0; t++) omega_dattn256_perm_vec_bf16(c->kc + ((size_t)g * c->max_pos + t) * HD, kp + (size_t)t * HD, c->rotary); - rc = omega_gpu_decode_attn256_cache_write(*out, 0, g, 0, c->pos0, kp, c->vc + (size_t)g * c->max_pos * HD); - } - free(kp); - return rc; -} -/* the chunk's appended rows, [m][4][256] each (K permuted as stored) */ -static int read_rows(OmegaGpuDecodeAttn256Cache *cc, const Case *c, uint16_t *k, uint16_t *v) { - for (uint32_t t = 0; t < c->m; t++) for (unsigned g = 0; g < KVH; g++) { - int rc = omega_gpu_decode_attn256_cache_read(cc, 0, g, c->pos0 + t, k + ((size_t)t * KVH + g) * HD, v + ((size_t)t * KVH + g) * HD); - if (rc != OMEGA_GPU_DATTN_OK) return rc; - } - return OMEGA_GPU_DATTN_OK; -} -static uint64_t median_u64(uint64_t *v, int n) { qsort(v, (size_t)n, sizeof *v, cmp_u64); return v[n / 2]; } -static int chip_point(uint32_t max_pos, uint32_t pos0, uint32_t m, float qscale, uint32_t seed, int twin, int reps) { - printf("-- chip %u tokens from %u (max_pos %u)\n", m, pos0, max_pos); fflush(stdout); - Case c; case_make(&c, max_pos, pos0, m, 64, seed, qscale); - float *qkv_k = malloc((size_t)m * QW * 4); case_kernel_qkv(&c, qkv_k); - float *out = malloc((size_t)m * OW * 4), *out2 = malloc((size_t)m * OW * 4); - const size_t rw = (size_t)m * KVH * HD; - uint16_t *kn = malloc(rw * 2), *vn = malloc(rw * 2), *kch = malloc(rw * 2), *vch = malloc(rw * 2), *ktw = malloc(rw * 2), *vtw = malloc(rw * 2); - OmegaGpuDecodeAttn256Cache *cc = NULL, *tc = NULL; - OmegaGpuPrefillAttn256Info info; - int ok = 1; char why[200]; double worst = 0; size_t bad = 0; - int rc = cache_with_history(&c, &cc); - CHECK(rc == OMEGA_GPU_DATTN_OK, "cache with history: %s %s", omega_gpu_decode_attn_rc_name(rc), rc ? omega_gpu_decode_attn_last_error() : ""); - if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } - rc = omega_gpu_prefill_attn256(cc, 0, pos0, m, qkv_k, EPS, 1.0f, out, &info); - CHECK(rc == OMEGA_GPU_DATTN_OK, "prefill %u+%u: %s %s", pos0, m, omega_gpu_decode_attn_rc_name(rc), rc ? omega_gpu_decode_attn_last_error() : ""); - if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } - printf(" prep %u insns %u regs, attend %u insns %u regs; first call %.3f ms (prep %.3f, attend %.3f)\n", info.insns[0], info.gprs[0], info.insns[1], info.gprs[1], - info.call_ns / 1e6, info.elapsed_ns[0] / 1e6, info.elapsed_ns[1] / 1e6); - ref_rows(&c, kn, vn); - rc = read_rows(cc, &c, kch, vch); - int rok = rc == OMEGA_GPU_DATTN_OK && rows_ok(&c, kch, vch, kn, vn, why, sizeof why); - CHECK(rok, "%u+%u: appended rows vs reference: %s", pos0, m, rc ? "read failed" : why); - double t0 = now_ms(); - bad = parity(&c, kn, vn, out, 1.0f, &worst); - CHECK(bad == 0, "%u+%u: parity: %zu elements outside the tolerance (worst ratio %.3f)", pos0, m, bad, worst); - printf(" parity: %zu bad, worst ratio %.3f of the tolerance (%.1f s reference); rows: %s\n", bad, worst, (now_ms() - t0) / 1e3, rok ? why : "FAIL"); - ok &= rok && bad == 0; - /* second call over the same positions: the same rows are rewritten, the same output */ - rc = omega_gpu_prefill_attn256(cc, 0, pos0, m, qkv_k, EPS, 1.0f, out2, &info); - CHECK(rc == OMEGA_GPU_DATTN_OK && memcmp(out, out2, (size_t)m * OW * 4) == 0 && info.kernel_cache_hits == 2, "%u+%u: second call bit-identical with both kernels cached (rc %d hits %u)", pos0, m, rc, info.kernel_cache_hits); - /* out_scale 2^20: exact */ - rc = omega_gpu_prefill_attn256(cc, 0, pos0, m, qkv_k, EPS, 1048576.0f, out2, NULL); - { size_t diff = 0; for (size_t i = 0; i < (size_t)m * OW; i++) diff += out2[i] != out[i] * 1048576.0f; - CHECK(rc == OMEGA_GPU_DATTN_OK && diff == 0, "%u+%u: out_scale 2^20 is exact (%zu words differ)", pos0, m, diff); } - /* device entry == host entry */ - { - OmegaGpuMem q, o; memset(&q, 0, sizeof q); memset(&o, 0, sizeof o); - omega_gpu_session_lock(); - int arc = omega_gpu_session_open() && omega_gpu_session_alloc((size_t)m * QW * 4, &q) == 0 && omega_gpu_session_alloc((size_t)m * OW * 4, &o) == 0 ? 0 : -1; - if (arc == 0) { memcpy(q.cpu, qkv_k, (size_t)m * QW * 4); float *od = o.cpu; for (size_t i = 0; i < (size_t)m * OW; i++) od[i] = -999.0f; - arc = omega_gpu_session_sync_to_gpu(&q) | omega_gpu_session_sync_to_gpu(&o); } - omega_gpu_session_unlock(); - rc = arc == 0 ? omega_gpu_prefill_attn256_dev(cc, 0, pos0, m, q.va, EPS, 1.0f, o.va, NULL) : OMEGA_GPU_DATTN_CHIP_FAIL; - omega_gpu_session_lock(); - int same = rc == OMEGA_GPU_DATTN_OK && omega_gpu_session_sync_to_cpu(&o) == 0 && memcmp(o.cpu, out, (size_t)m * OW * 4) == 0; - if (q.cpu) omega_gpu_session_free(&q); - if (o.cpu) omega_gpu_session_free(&o); - omega_gpu_session_unlock(); - CHECK(same, "%u+%u: device entry bit-identical to the host entry (rc %s)", pos0, m, omega_gpu_decode_attn_rc_name(rc)); - } - /* twin: m decode calls from the same history; rows bit-identical, then the next decode step on both caches */ - if (twin) { - rc = cache_with_history(&c, &tc); - float *dout = malloc(OW * 4); - t0 = now_ms(); - for (uint32_t t = 0; t < m && rc == OMEGA_GPU_DATTN_OK; t++) rc = omega_gpu_decode_attn256(tc, 0, pos0 + t, qkv_k + (size_t)t * QW, EPS, 1.0f, dout, NULL); - const double dec_ms = now_ms() - t0; - CHECK(rc == OMEGA_GPU_DATTN_OK, "%u+%u: twin decode loop: %s %s", pos0, m, omega_gpu_decode_attn_rc_name(rc), rc ? omega_gpu_decode_attn_last_error() : ""); - if (rc == OMEGA_GPU_DATTN_OK) rc = read_rows(tc, &c, ktw, vtw); - size_t kd = 0, vd = 0; - for (size_t i = 0; i < rw && rc == OMEGA_GPU_DATTN_OK; i++) { kd += kch[i] != ktw[i]; vd += vch[i] != vtw[i]; } - CHECK(rc == OMEGA_GPU_DATTN_OK && kd == 0 && vd == 0, "%u+%u: rows bit-identical to %u decode calls (k %zu, v %zu words differ)", pos0, m, m, kd, vd); - printf(" twin: %u decode calls %.1f ms; rows k %zu v %zu words differ\n", m, dec_ms, kd, vd); - if (pos0 + m < max_pos && rc == OMEGA_GPU_DATTN_OK) { - float *nq = malloc(QW * 4), *o1 = malloc(OW * 4), *o2 = malloc(OW * 4); uint32_t s = seed ^ 0x5a5a5a5au; - for (unsigned h = 0; h < QH + KVH; h++) { float raw[HD]; for (unsigned i = 0; i < HD; i++) raw[i] = frand(&s, -1.0f, 1.0f); omega_dattn256_perm_vec(raw, nq + h * HD, 64); } - for (unsigned i = KEND; i < QW; i++) nq[i] = frand(&s, -1.0f, 1.0f); - int r1 = omega_gpu_decode_attn256(cc, 0, pos0 + m, nq, EPS, 1.0f, o1, NULL), r2 = omega_gpu_decode_attn256(tc, 0, pos0 + m, nq, EPS, 1.0f, o2, NULL); - CHECK(r1 == OMEGA_GPU_DATTN_OK && r2 == OMEGA_GPU_DATTN_OK && memcmp(o1, o2, OW * 4) == 0, "%u+%u: next decode step bit-identical after prefill and after the decode loop", pos0, m); - free(nq); free(o1); free(o2); - } - free(dout); - } - /* timing: reps calls on the same positions (rows rewritten with the same bits) */ - if (reps > 0) { - uint64_t *pp = malloc((size_t)reps * 8), *aa = malloc((size_t)reps * 8), *cl = malloc((size_t)reps * 8); - for (int r = 0; r < reps && rc == OMEGA_GPU_DATTN_OK; r++) { - rc = omega_gpu_prefill_attn256(cc, 0, pos0, m, qkv_k, EPS, 1.0f, out2, &info); - pp[r] = info.elapsed_ns[0]; aa[r] = info.elapsed_ns[1]; cl[r] = info.call_ns; - } - CHECK(rc == OMEGA_GPU_DATTN_OK, "%u+%u: timing calls", pos0, m); - if (rc == OMEGA_GPU_DATTN_OK) { - const uint64_t mp = median_u64(pp, reps), ma = median_u64(aa, reps), mc = median_u64(cl, reps); - /* useful work: QK^T and PV over the causal context, 2 flops per multiply-add, 24 heads x 256 dims */ - double flops = 0, kvb = 0; - for (uint32_t t = 0; t < m; t++) flops += 4.0 * (double)(pos0 + t + 1) * QH * HD; - for (uint32_t cx = 0; cx * OMEGA_PATTN256_TOKENS < m; cx++) { - uint32_t nk = (cx + 1) * OMEGA_PATTN256_TOKENS; if (nk > m) nk = m; - kvb += (double)KVH * (((pos0 + nk - 1) >> 4) + 1) * 16.0 * 2 * RB; - } - printf(" timing (median of %d): prep %.3f ms, attend %.3f ms, call %.3f ms -> %.0f tokens/s; attend %.2f TFLOPS useful, %.1f GB/s K/V streamed\n", - reps, mp / 1e6, ma / 1e6, mc / 1e6, m / ((mp + ma) / 1e9), flops / (double)ma / 1e3, kvb / (double)ma); - if (g_json) { - fprintf(g_json, "%s {\"pos0\": %u, \"m\": %u, \"max_pos\": %u, \"reps\": %d, \"prep_ns\": %" PRIu64 ", \"attend_ns\": %" PRIu64 ", \"call_ns\": %" PRIu64 ", \"attend_useful_flops\": %.0f, \"attend_kv_bytes\": %.0f, \"parity_bad\": %zu, \"parity_worst_ratio\": %.4f}", - g_json_first ? "" : ",\n", pos0, m, max_pos, reps, mp, ma, mc, flops, kvb, bad, worst); - g_json_first = 0; - } - } - free(pp); free(aa); free(cl); - } -done: - if (tc) omega_gpu_decode_attn256_cache_free(tc); - if (cc) omega_gpu_decode_attn256_cache_free(cc); - free(qkv_k); free(out); free(out2); free(kn); free(vn); free(kch); free(vch); free(ktw); free(vtw); case_free(&c); - return ok; -} -static void chip_mutants(void) { - static const struct { int pm, am; } mut[] = { { 1, 0 }, { 3, 0 }, { 0, 1 }, { 0, 2 } }; - for (size_t i = 0; i < sizeof mut / sizeof mut[0]; i++) { - omega_gpu_prefill_attn256_test_set_mutant(mut[i].pm, mut[i].am); - Case c; case_make(&c, 256, 40, 24, 64, 300, 1.0f); - float *qkv_k = malloc((size_t)c.m * QW * 4); case_kernel_qkv(&c, qkv_k); - float *out = malloc((size_t)c.m * OW * 4); - uint16_t *kn = malloc((size_t)c.m * KVH * HD * 2), *vn = malloc((size_t)c.m * KVH * HD * 2), *kch = malloc((size_t)c.m * KVH * HD * 2), *vch = malloc((size_t)c.m * KVH * HD * 2); - OmegaGpuDecodeAttn256Cache *cc = NULL; - int rc = cache_with_history(&c, &cc); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn256(cc, 0, c.pos0, c.m, qkv_k, EPS, 1.0f, out, NULL); - double worst = 0; size_t bad = 0; char why[200] = ""; - int rok = 1; - if (rc == OMEGA_GPU_DATTN_OK) { - ref_rows(&c, kn, vn); - rok = read_rows(cc, &c, kch, vch) == OMEGA_GPU_DATTN_OK && rows_ok(&c, kch, vch, kn, vn, why, sizeof why); - bad = parity(&c, kn, vn, out, 1.0f, &worst); - } - const int caught = rc != OMEGA_GPU_DATTN_OK || bad > 0 || !rok; - CHECK(caught, "chip %s mutant %d NOT caught", mut[i].pm ? "prep" : "attend", mut[i].pm ? mut[i].pm : mut[i].am); - printf("chip %s mutant %d: %s (rc %s, %zu bad, worst %.1f, rows %s)\n", mut[i].pm ? "prep" : "attend", mut[i].pm ? mut[i].pm : mut[i].am, caught ? "caught" : "MISSED", - omega_gpu_decode_attn_rc_name(rc), bad, worst, rok ? "ok" : "differ"); - if (cc) omega_gpu_decode_attn256_cache_free(cc); - free(qkv_k); free(out); free(kn); free(vn); free(kch); free(vch); case_free(&c); - } - omega_gpu_prefill_attn256_test_set_mutant(0, 0); -} - -int main(int argc, char **argv) { - int host = 0, sim = 0, reps = 9, quick = 0, timing_only = 0; const char *json = NULL; uint32_t maxp = 32768; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) host = 1; - else if (!strcmp(argv[i], "--sim")) sim = 1; - else if (!strcmp(argv[i], "--poison") && i + 1 < argc) g_poison = (uint32_t)strtoul(argv[++i], NULL, 0); - else if (!strcmp(argv[i], "--sim-point") && i + 3 < argc) { /* one simulator point: MAX_POS POS0 M */ - uint32_t a = (uint32_t)atoi(argv[i + 1]), b = (uint32_t)atoi(argv[i + 2]), m = (uint32_t)atoi(argv[i + 3]); i += 3; - char msg[400]; double worst = 0; size_t bad = 0; double t0 = now_ms(); - int err = sim_point(a, b, m, 64, 1.0f, 77, 1, 0, 0, msg, sizeof msg, &worst, &bad); - CHECK(err == 0 && bad == 0, "sim point %u+%u (max_pos %u): %s", b, m, a, msg); - printf("sim point %u tokens from %u (max_pos %u): %s %s (%.1f s)\n", m, b, a, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg, (now_ms() - t0) / 1e3); - host = 1; } - else if (!strcmp(argv[i], "--quick")) quick = 1; - else if (!strcmp(argv[i], "--timing-only")) timing_only = 1; - else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = atoi(argv[++i]); - else if (!strcmp(argv[i], "--max-pos") && i + 1 < argc) maxp = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--out") && i + 1 < argc) json = argv[++i]; - else { fprintf(stderr, "usage: %s [--host-only | --sim | [--quick] [--timing-only] [--reps N] [--max-pos 32768|131072] [--out receipt.json]]\n", argv[0]); return 2; } - } - if (reps < 1) reps = 1; - host_only(); - if (sim) sim_battery(); - if (!host && !sim) { - if (json) { g_json = fopen(json, "w"); if (g_json) fprintf(g_json, "{\"test\": \"gpu_prefill_attn256\", \"rotary_dim\": 64, \"points\": [\n"); } - if (!timing_only) { - chip_point(256, 0, 1, 1.0f, 1, 1, 0); - chip_point(256, 0, 37, 1.0f, 2, 1, 0); - chip_point(512, 100, 19, 1.0f, 3, 1, 0); - chip_point(512, 37, 141, 4.0f, 4, 1, 0); - chip_mutants(); - } - if (!quick) { - chip_point(4096, 0, 2048, 1.0f, 8, !timing_only, reps); - chip_point(8192, 6144, 2048, 1.0f, 9, !timing_only, reps); - chip_point(32768, 30720, 2048, 1.0f, 10, !timing_only, reps); - if (maxp >= 131072) chip_point(131072, 129024, 2048, 1.0f, 11, !timing_only, reps); - } - if (g_json) { fprintf(g_json, "\n], \"checks\": %d, \"failed\": %d}\n", g_checks, g_failed); fclose(g_json); } - } - printf("gpu_prefill_attn256_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_prefill_attn_test.c b/tests/gpu_prefill_attn_test.c deleted file mode 100644 index 5a20ae554..000000000 --- a/tests/gpu_prefill_attn_test.c +++ /dev/null @@ -1,670 +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. - */ - -/* - * gpu_prefill_attn_test: the tensor-core causal prefill attention (omega_gpu_prefill_attn_api.h, OWN-30B L1 attention). - * --host-only codegen budgets (instructions <= 1024, declared registers <= 128, placeholders patched against the - * oracle words), refusals, reference sanity. No device. - * --sim the kernel through tests/bw_warp_sim_pa.h (chip-exact HMMA model; EX2/RSQ/RCP exact): several - * (pos0, m) points incl. two chunks, warps 4 and 8, both fragment orders. Gates: appended K/V rows - * bit-equal to a host emulation of the decode kernel's operation order; outputs within the tolerance - * of a double reference over the cache contents; mutants 1-4 caught. - * (default) the chip: parity against the double reference; appended K/V rows bit-identical to m calls of the - * decode kernel on a twin cache (gate 2) and its outputs within the tolerance; second call identical; - * out_scale 2^64; mutants 1-4 caught; timing medians (prefill vs the per-token decode loop). - * Tolerance: |out - ref| <= 1e-2 * max|v| * out_scale per element. Derivation: q' and P are rounded to bf16 (relative - * 2^-9 each). P rounding moves each weight by <= 2^-9 relative while l sums the f32 p: <= 2^-9 * max|v| = 0.0020. - * q' rounding moves a score (log2 units) by <= 2^-9 * sum|q'_i k_i|; for the normed rows here (|q'|, |k| ~ sqrt(128) - * with random signs) that is ~2^-9 * sqrt(128) * log2(e)/sqrt(128) * ... ~ 3e-3 relative on the weights in the worst - * measured case; EX2/RSQ on the chip add ~2^-22. 1e-2 covers the sum with margin; the measured worst ratio is printed - * and the mutants miss by far more than the tolerance. - * Host and simulator passes are never chip results. - */ -#include "omega_gpu_prefill_attn_api.h" -#include "omega_gpu_session.h" -#include "omega_blackwell_codegen_tc.h" -#include "bw_warp_sim_pa.h" -#if defined(__has_include) -#if __has_include("omega_gpu_prefill.h") -#include "omega_gpu_prefill.h" /* W-L1G device-resident module (integration builds): GPU-cached buffers for the dev check */ -#define PATTN_HAVE_PF 1 -#endif -#endif -#ifndef PATTN_HAVE_PF -#define PATTN_HAVE_PF 0 -#endif -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static const double THETA = 10000000.0; -static const float EPS = 1e-6f; -#define QKVW OMEGA_PATTN_QKV_WORDS -#define OUTW OMEGA_PATTN_OUT_WORDS - -/* one layer's random state */ -typedef struct { - uint32_t max_pos, pos0, m; - float *qkv; /* [m][5120] */ - float qn[128], kn[128]; - uint16_t *kc, *vc; /* [4][max_pos][128]: history 0..pos0-1 */ -} Case; -static void case_make(Case *c, uint32_t max_pos, uint32_t pos0, uint32_t m, uint32_t seed, float qscale) { - uint32_t s = seed; - c->max_pos = max_pos; c->pos0 = pos0; c->m = m; - c->qkv = malloc((size_t)m * QKVW * 4); - for (size_t t = 0; t < m; t++) for (size_t i = 0; i < QKVW; i++) c->qkv[t * QKVW + i] = frand(&s, -1.0f, 1.0f) * (i < 4096 ? qscale : 1.0f); - for (unsigned i = 0; i < 128; i++) { c->qn[i] = frand(&s, 0.8f, 1.2f); c->kn[i] = frand(&s, 0.8f, 1.2f); } - size_t words = (size_t)4 * max_pos * 128; - c->kc = calloc(words, 2); c->vc = calloc(words, 2); - for (unsigned g = 0; g < 4; g++) for (uint32_t t = 0; t < pos0; t++) for (unsigned i = 0; i < 128; i++) { - size_t o = ((size_t)g * max_pos + t) * 128 + i; - c->kc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); c->vc[o] = omega_dattn_bf16_rne(frand(&s, -1.0f, 1.0f)); - } -} -static void case_free(Case *c) { free(c->qkv); free(c->kc); free(c->vc); } - -/* ---- host emulation of the decode kernel's K/V row (float, the kernel's operation order; RSQ exact as in the simulator) */ -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static void emu_rows(const float *qkv_row, const float *kn, float eps, uint32_t pos, double theta, uint16_t *krow /*[4][128]*/, uint16_t *vrow) { - float rope[128]; omega_dattn_rope_row(pos, theta, rope); - for (unsigned gk = 0; gk < 4; gk++) { - float x[128], sq[32]; - for (unsigned i = 0; i < 128; i++) x[i] = qkv_row[4096 + gk * 128 + i]; - for (unsigned L = 0; L < 32; L++) { float a = x[4 * L] * x[4 * L]; for (unsigned i = 1; i < 4; i++) a = fmaf(x[4 * L + i], x[4 * L + i], a); sq[L] = a; } - for (unsigned o = 16; o >= 1; o /= 2) { float nx[32]; for (unsigned L = 0; L < 32; L++) nx[L] = sq[L] + (L + o < 32 ? sq[L + o] : sq[L]); memcpy(sq, nx, sizeof sq); } - float rs = ws_mufu_rsq(fmaf(sq[0], u2f(0x3c000000u), eps)); /* MUFU.RSQ, bw_mufu_ftz.h (#462); eps > 0 keeps it normal */ - for (unsigned i = 0; i < 128; i++) { x[i] = x[i] * rs; x[i] = x[i] * kn[i]; } - float y[128]; - for (unsigned i = 0; i < 128; i++) { - unsigned j = i % 64; float cs = rope[j], sn = rope[64 + j]; float part = x[i < 64 ? i + 64 : i - 64]; - float ts = x[i] * cs; y[i] = fmaf(part, i < 64 ? -sn : sn, ts); - } - for (unsigned i = 0; i < 128; i++) { krow[gk * 128 + i] = omega_dattn_bf16_rne(y[i]); vrow[gk * 128 + i] = omega_dattn_bf16_rne(qkv_row[4096 + 512 + gk * 128 + i]); } - } -} - -/* ---- double reference over the cache contents (kc/vc hold positions 0 .. pos0+m-1 after the call) */ -static void norm_rope_d(double *x, const float *w, float eps, uint32_t pos) { - double ss = 0; for (unsigned i = 0; i < 128; i++) ss += x[i] * x[i]; - double r = 1.0 / sqrt(ss / 128.0 + (double)eps); - for (unsigned i = 0; i < 128; i++) x[i] = x[i] * r * (double)w[i]; - double y[128]; - for (unsigned i = 0; i < 64; i++) { - double ang = (double)pos * pow(THETA, -(double)(2 * i) / 128.0), cs = cos(ang), sn = sin(ang); - y[i] = x[i] * cs - x[i + 64] * sn; y[i + 64] = x[i + 64] * cs + x[i] * sn; - } - memcpy(x, y, sizeof y); -} -static void reference(const Case *c, const uint16_t *kc, const uint16_t *vc, float out_scale, double *out /*[m][4096]*/) { - double *p = malloc(((size_t)c->pos0 + c->m) * sizeof(double)); - for (uint32_t t = 0; t < c->m; t++) { - const uint32_t pos = c->pos0 + t; - for (unsigned h = 0; h < 32; h++) { - unsigned gk = h / 8; double q[128]; - for (unsigned i = 0; i < 128; i++) q[i] = c->qkv[(size_t)t * QKVW + h * 128 + i]; - norm_rope_d(q, c->qn, EPS, pos); - double mx = -1e300; - for (uint32_t k = 0; k <= pos; k++) { - const uint16_t *kr = kc + ((size_t)gk * c->max_pos + k) * 128; - double s = 0; for (unsigned i = 0; i < 128; i++) s += q[i] * (double)omega_dattn_bf16_f32(kr[i]); - s /= sqrt(128.0); p[k] = s; if (s > mx) mx = s; - } - double l = 0, o[128]; memset(o, 0, sizeof o); - for (uint32_t k = 0; k <= pos; k++) { p[k] = exp(p[k] - mx); l += p[k]; } - for (uint32_t k = 0; k <= pos; k++) { const uint16_t *vr = vc + ((size_t)gk * c->max_pos + k) * 128; for (unsigned i = 0; i < 128; i++) o[i] += p[k] * (double)omega_dattn_bf16_f32(vr[i]); } - for (unsigned i = 0; i < 128; i++) out[(size_t)t * OUTW + h * 128 + i] = o[i] / l * (double)out_scale; - } - } - free(p); -} -static size_t parity(const Case *c, const uint16_t *kc, const uint16_t *vc, const float *out, float out_scale, double *worst) { - double *ref = malloc((size_t)c->m * OUTW * sizeof(double)); - reference(c, kc, vc, out_scale, ref); - double tol = 1e-2 * out_scale; size_t bad = 0; *worst = 0; - for (size_t i = 0; i < (size_t)c->m * OUTW; i++) { double d = fabs((double)out[i] - ref[i]); if (!(d <= tol)) bad++; if (d / tol > *worst || d != d) *worst = d != d ? 1e9 : d / tol; } - free(ref); - return bad; -} -/* appended rows (cache contents at pos0 .. pos0+m-1) against the host emulation: count of differing bf16 words and the - * largest difference in ulps */ -static void rows_vs_emu(const Case *c, const uint16_t *kc, const uint16_t *vc, size_t *kdiff, size_t *vdiff, int *maxulp) { - *kdiff = *vdiff = 0; *maxulp = 0; - uint16_t kr[512], vr[512]; - for (uint32_t t = 0; t < c->m; t++) { - emu_rows(c->qkv + (size_t)t * QKVW, c->kn, EPS, c->pos0 + t, THETA, kr, vr); - for (unsigned gk = 0; gk < 4; gk++) for (unsigned i = 0; i < 128; i++) { - size_t o = ((size_t)gk * c->max_pos + c->pos0 + t) * 128 + i; - if (kc[o] != kr[gk * 128 + i]) { (*kdiff)++; int d = abs((int)kc[o] - (int)kr[gk * 128 + i]); if (d > *maxulp) *maxulp = d; } - if (vc[o] != vr[gk * 128 + i]) (*vdiff)++; - } - } -} - -/* ------------------------------------------------------------- host only */ -static void host_only(void) { - char msg[200]; - CHECK(omega_tc_patch_selftest(msg, sizeof msg) == 0, "placeholder self-test: %s", msg); - for (uint32_t w = 4; w <= 8; w += 4) for (uint32_t md = 0; md <= 2; md++) for (int m = 0; m <= 4; m++) { - OmegaPrefillAttnSpec s = { w, m, md, 0 }; uint32_t n = 0, gp = 0, ph = 0; - int rc = omega_prefill_attn_prog_stats(&s, &n, &gp, &ph); - CHECK(rc == 0 && n <= 1024 && omega_bw_gpr_declared(gp) <= 128, "codegen warps %u mode %u mutant %d: rc %d insns %u gprs %u", w, md, m, rc, n, gp); - static uint8_t code[1024 * 16]; uint32_t kg = 0; int np = -1; - size_t sz = omega_gpu_prefill_attn_encode(&s, code, sizeof code, &kg, &np); - CHECK(sz > 0 && np == (int)ph, "encode+patch warps %u mode %u mutant %d: size %zu patched %d of %u", w, md, m, sz, np, ph); - if (rc == 0 && m == 0) printf("codegen warps %u mode %u: %u instructions, %u registers (declared %u, %u threads -> %u of 65536), %u placeholders patched\n", - w, md, n, gp, omega_bw_gpr_declared(gp), 32 * w, 32 * w * omega_bw_gpr_declared(gp), ph); - } - { OmegaPrefillAttnSpec s = { 2, 0, 0, 0 }; CHECK(omega_prefill_attn_prog_stats(&s, NULL, NULL, NULL) != 0, "warps 2 refused"); - s.warps = 8; s.mutant = 5; CHECK(omega_prefill_attn_prog_stats(&s, NULL, NULL, NULL) != 0, "mutant 5 refused"); - s.mutant = 0; s.mode = 3; CHECK(omega_prefill_attn_prog_stats(&s, NULL, NULL, NULL) != 0, "mode 3 refused"); - s.mode = OMEGA_PATTN_MODE_ATTEND; s.mirror = 1; CHECK(omega_prefill_attn_prog_stats(&s, NULL, NULL, NULL) != 0, "mirror outside APPEND refused"); - s.mode = OMEGA_PATTN_MODE_APPEND; uint32_t n = 0, gp = 0, ph = 0; - CHECK(omega_prefill_attn_prog_stats(&s, &n, &gp, &ph) == 0 && n <= 1024 && omega_bw_gpr_declared(gp) <= 128, "APPEND + mirror in budget: %u insns %u gprs", n, gp); - printf("codegen warps 8 APPEND + mirror: %u instructions, %u registers\n", n, gp); } - CHECK(omega_gpu_prefill_attn(NULL, 0, 0, 1, NULL, EPS, 1.0f, NULL, NULL) == OMEGA_GPU_DATTN_BAD_ARGS, "NULL cache refused"); - CHECK(OMEGA_PATTN_SHARED_BYTES <= 16384u, "shared memory within the QMD cap"); - /* reference sanity: a single token at position 0 returns its own v row (rounded) */ - { Case c; case_make(&c, 256, 0, 1, 5, 1.0f); uint16_t kr[512], vr[512]; - emu_rows(c.qkv, c.kn, EPS, 0, THETA, kr, vr); - for (unsigned gk = 0; gk < 4; gk++) { memcpy(c.kc + (size_t)gk * 256 * 128, kr + gk * 128, 256); memcpy(c.vc + (size_t)gk * 256 * 128, vr + gk * 128, 256); } - double *ref = malloc(OUTW * sizeof(double)); reference(&c, c.kc, c.vc, 1.0f, ref); - int good = 1; for (unsigned h = 0; h < 32 && good; h++) for (unsigned i = 0; i < 128; i++) if (ref[h * 128 + i] != (double)omega_dattn_bf16_f32(vr[(h / 8) * 128 + i])) { good = 0; break; } - CHECK(good, "reference: one token at position 0 returns the rounded v row of its KV group"); - free(ref); case_free(&c); } -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -/* mirror planes for the simulated APPEND (write) / ATTEND (read) launches */ -static struct { uint8_t *k, *v; uint32_t kvs; size_t plane; int write, read; } g_sm; -/* one simulated launch of prog over tokens p0 .. p0+mc-1 whose rows are qbuf / obuf (host memory) */ -static int sim_launch(const BlackwellIRProgram *prog, uint32_t W, const Case *c, uint8_t *kv, size_t plane, const float *rope, const float *norms, - float out_scale, float *qbuf, float *obuf, uint32_t p0, uint32_t mc, int order, char *msg, size_t n) { - static uint8_t smem[OMEGA_PATTN_SHARED_BYTES]; - WsSim s; memset(&s, 0, sizeof s); - s.p = prog; s.threads = 32 * W; s.order = order; s.smem = smem; s.smem_bytes = sizeof smem; - uint64_t A[7] = { (uintptr_t)qbuf, (uintptr_t)kv, (uintptr_t)(kv + plane), (uintptr_t)rope, (uintptr_t)norms, (uintptr_t)(norms + 128), (uintptr_t)obuf }; - for (unsigned i = 0; i < 7; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - float fe = EPS, fo = out_scale, fq = (float)((1.0 / sqrt(128.0)) * 1.4426950408889634); - s.cbank[OMEGA_PATTN_ARG_POS0 / 4] = p0; s.cbank[OMEGA_PATTN_ARG_MC / 4] = mc; s.cbank[OMEGA_PATTN_ARG_KV_STRIDE / 4] = c->max_pos * 256; - memcpy(&s.cbank[OMEGA_PATTN_ARG_EPS / 4], &fe, 4); memcpy(&s.cbank[OMEGA_PATTN_ARG_OUT_SCALE / 4], &fo, 4); memcpy(&s.cbank[OMEGA_PATTN_ARG_QK_SCALE / 4], &fq, 4); - s.nranges = 5; - s.ranges[0].lo = (uintptr_t)qbuf; s.ranges[0].hi = (uintptr_t)qbuf + (size_t)mc * QKVW * 4; - s.ranges[1].lo = (uintptr_t)kv; s.ranges[1].hi = (uintptr_t)kv + 2 * plane; - s.ranges[2].lo = (uintptr_t)rope; s.ranges[2].hi = (uintptr_t)rope + (size_t)c->max_pos * 512; - s.ranges[3].lo = (uintptr_t)norms; s.ranges[3].hi = (uintptr_t)norms + 1024; - s.ranges[4].lo = (uintptr_t)obuf; s.ranges[4].hi = (uintptr_t)obuf + (size_t)mc * OUTW * 4; - if (g_sm.write) { - uint64_t k2 = (uintptr_t)g_sm.k, v2 = (uintptr_t)g_sm.v; - s.cbank[OMEGA_PATTN_ARG_KC2 / 4] = (uint32_t)k2; s.cbank[OMEGA_PATTN_ARG_KC2 / 4 + 1] = (uint32_t)(k2 >> 32); - s.cbank[OMEGA_PATTN_ARG_VC2 / 4] = (uint32_t)v2; s.cbank[OMEGA_PATTN_ARG_VC2 / 4 + 1] = (uint32_t)(v2 >> 32); - s.cbank[OMEGA_PATTN_ARG_KV_STRIDE2 / 4] = g_sm.kvs; - s.ranges[5].lo = (uintptr_t)g_sm.k; s.ranges[5].hi = (uintptr_t)g_sm.k + 2 * g_sm.plane; s.nranges = 6; - } - if (g_sm.read) { /* ATTEND reads only the mirror: the cache range is replaced, so a stray cache read faults */ - uint64_t k2 = (uintptr_t)g_sm.k, v2 = (uintptr_t)g_sm.v; - s.cbank[OMEGA_PATTN_ARG_KC / 4] = (uint32_t)k2; s.cbank[OMEGA_PATTN_ARG_KC / 4 + 1] = (uint32_t)(k2 >> 32); - s.cbank[OMEGA_PATTN_ARG_VC / 4] = (uint32_t)v2; s.cbank[OMEGA_PATTN_ARG_VC / 4 + 1] = (uint32_t)(v2 >> 32); - s.cbank[OMEGA_PATTN_ARG_KV_STRIDE / 4] = g_sm.kvs; - s.ranges[1].lo = (uintptr_t)g_sm.k; s.ranges[1].hi = (uintptr_t)g_sm.k + 2 * g_sm.plane; - } - int err = ws_run(&s, (mc + W - 1) / W, 4); - if (err) { snprintf(msg, n, "launch at %u: %s (pc %d)", p0, s.msg, s.err_pc); return -1; } - g_sim_issues += s.warp_issues; - return 0; -} -/* runs the API's launch plan through the simulator on host buffers; kv: [K plane | V plane] holding the history. - * progs[mode]; split: one APPEND + one ATTEND launch over all m tokens, else fused 64-token chunks */ -static int sim_call(BlackwellIRProgram *const progs[4], int split, uint32_t W, const Case *c, uint8_t *kv, size_t plane, const float *rope, const float *norms, - float out_scale, float *out, int order, char *msg, size_t n) { - float *qbuf = aligned_alloc(16, (size_t)c->m * QKVW * 4), *obuf = aligned_alloc(16, (size_t)c->m * OUTW * 4); - memcpy(qbuf, c->qkv, (size_t)c->m * QKVW * 4); - for (size_t i = 0; i < (size_t)c->m * OUTW; i++) obuf[i] = -999.0f; - int err = 0; - if (split) { - uint8_t *mir = NULL; - if (split == 2) { /* the API's mirror plan: history rows copied in, APPEND writes both, ATTEND reads the mirror */ - const uint32_t P = c->pos0 + c->m, Pr = (P + 31) & ~31u; - g_sm.kvs = Pr * 256; g_sm.plane = (size_t)4 * g_sm.kvs; - mir = aligned_alloc(16, 2 * g_sm.plane); memset(mir, 0, 2 * g_sm.plane); - g_sm.k = mir; g_sm.v = mir + g_sm.plane; - for (unsigned h = 0; h < 4; h++) { - memcpy(g_sm.k + (size_t)h * g_sm.kvs, kv + (size_t)h * c->max_pos * 256, (size_t)c->pos0 * 256); - memcpy(g_sm.v + (size_t)h * g_sm.kvs, kv + plane + (size_t)h * c->max_pos * 256, (size_t)c->pos0 * 256); - } - g_sm.write = 1; - } - err = sim_launch(progs[split == 2 ? 3 : OMEGA_PATTN_MODE_APPEND], W, c, kv, plane, rope, norms, out_scale, qbuf, obuf, c->pos0, c->m, order, msg, n); - /* APPEND writes no output */ - for (size_t i = 0; i < (size_t)c->m * OUTW && !err; i++) if (obuf[i] != -999.0f) { err = -1; snprintf(msg, n, "APPEND launch wrote output word %zu", i); } - if (split == 2 && !err) for (unsigned h = 0; h < 4 && !err; h++) { /* the mirror holds exactly the cache rows 0 .. P-1 */ - const size_t P = (size_t)c->pos0 + c->m; - if (memcmp(g_sm.k + (size_t)h * g_sm.kvs, kv + (size_t)h * c->max_pos * 256, P * 256) || - memcmp(g_sm.v + (size_t)h * g_sm.kvs, kv + plane + (size_t)h * c->max_pos * 256, P * 256)) { err = -1; snprintf(msg, n, "mirror rows of head %u differ from the cache", h); } - } - g_sm.write = 0; g_sm.read = split == 2; - if (!err) err = sim_launch(progs[OMEGA_PATTN_MODE_ATTEND], W, c, kv, plane, rope, norms, out_scale, qbuf, obuf, c->pos0, c->m, order, msg, n); - g_sm.read = 0; free(mir); - } else { - for (uint32_t done = 0; done < c->m && !err; done += 64) { - const uint32_t mc = c->m - done < 64 ? c->m - done : 64; - err = sim_launch(progs[OMEGA_PATTN_MODE_FUSED], W, c, kv, plane, rope, norms, out_scale, qbuf + (size_t)done * QKVW, obuf + (size_t)done * OUTW, - c->pos0 + done, mc, order, msg, n); - } - } - if (!err) { - size_t unwritten = 0; for (size_t i = 0; i < (size_t)c->m * OUTW; i++) if (obuf[i] == -999.0f) unwritten++; - if (unwritten) { snprintf(msg, n, "%zu output words never written", unwritten); err = -1; } - else memcpy(out, obuf, (size_t)c->m * OUTW * 4); - } - free(qbuf); free(obuf); - return err; -} -static int sim_point(uint32_t W, int mutant, int split, uint32_t max_pos, uint32_t pos0, uint32_t m, float qscale, uint32_t seed, int orders, - char *msg, size_t n, double *worst, size_t *bad) { - static BlackwellIRProgram p0, p1, p2, p3; - BlackwellIRProgram *const progs[4] = { &p0, &p1, &p2, &p3 }; - for (uint32_t md = 0; md < 4; md++) { - OmegaPrefillAttnSpec spec = { W, mutant, md == 3 ? OMEGA_PATTN_MODE_APPEND : md, md == 3 }; - if (omega_blackwell_codegen_prefill_attn_prog(&spec, progs[md]) != 0) { snprintf(msg, n, "codegen refused (mode %u)", md); return -1; } - } - Case c; case_make(&c, max_pos, pos0, m, seed, qscale); - size_t plane = (size_t)4 * max_pos * 256 + OMEGA_DATTN_PLANE_SLACK; - uint8_t *kv = aligned_alloc(16, 2 * plane); - float *rope = aligned_alloc(16, (size_t)max_pos * 512); for (uint32_t p = 0; p < max_pos; p++) omega_dattn_rope_row(p, THETA, rope + (size_t)p * 128); - float *norms = aligned_alloc(16, 1024); memcpy(norms, c.qn, 512); memcpy(norms + 128, c.kn, 512); - float *out = malloc((size_t)m * OUTW * 4), *copy = malloc((size_t)m * OUTW * 4); - int err = 0; - for (int order = 0; order < orders && !err; order++) { - memset(kv, 0, 2 * plane); - memcpy(kv, c.kc, (size_t)4 * max_pos * 256); memcpy(kv + plane, c.vc, (size_t)4 * max_pos * 256); - err = sim_call(progs, split, W, &c, kv, plane, rope, norms, 1.0f, out, order, msg, n); - if (!err && order == 0) memcpy(copy, out, (size_t)m * OUTW * 4); - else if (!err && memcmp(copy, out, (size_t)m * OUTW * 4) != 0) { err = -1; snprintf(msg, n, "the fragment order changed the result"); } - } - if (!err) { - size_t kd, vd; int mu; - rows_vs_emu(&c, (const uint16_t *)kv, (const uint16_t *)(kv + plane), &kd, &vd, &mu); - *bad = parity(&c, (const uint16_t *)kv, (const uint16_t *)(kv + plane), out, 1.0f, worst); - if (kd || vd) *bad += 1000000; - snprintf(msg, n, "bad=%zu worst=%.3f rows: k %zu v %zu words differ from the emulation (max %d ulp)", *bad, *worst, kd, vd, mu); - } - free(kv); free(rope); free(norms); free(out); free(copy); case_free(&c); - return err; -} -static void sim_battery(void) { - char msg[300]; double worst; size_t bad; - struct { uint32_t w, max_pos, pos0, m; float qs; int orders, split; const char *name; } pts[] = { - { 8, 256, 0, 1, 1.0f, 2, 0, "one token at position 0" }, - { 8, 256, 0, 5, 1.0f, 2, 0, "5 tokens from 0 (partial CTA)" }, - { 4, 256, 37, 19, 1.0f, 2, 0, "19 tokens from 37, warps 4" }, - { 8, 256, 37, 19, 4.0f, 1, 0, "19 tokens from 37, sharp q (x4)" }, - { 8, 256, 100, 64, 1.0f, 1, 0, "64 tokens from 100 (full chunk)" }, - { 8, 512, 0, 70, 1.0f, 1, 0, "70 tokens from 0 (two chunks)" }, - { 4, 512, 200, 33, 1.0f, 1, 0, "33 tokens from 200, warps 4" }, - { 8, 256, 0, 1, 1.0f, 2, 1, "split: one token at position 0" }, - { 8, 256, 0, 5, 1.0f, 2, 1, "split: 5 tokens from 0" }, - { 4, 256, 37, 19, 1.0f, 2, 1, "split: 19 tokens from 37, warps 4" }, - { 8, 512, 0, 70, 1.0f, 1, 1, "split: 70 tokens from 0" }, - { 8, 512, 37, 141, 4.0f, 1, 1, "split: 141 tokens from 37, sharp q" }, - { 8, 256, 0, 5, 1.0f, 2, 2, "mirror: 5 tokens from 0" }, - { 4, 256, 37, 19, 1.0f, 2, 2, "mirror: 19 tokens from 37, warps 4" }, - { 8, 512, 37, 141, 4.0f, 1, 2, "mirror: 141 tokens from 37, sharp q" }, - { 8, 512, 300, 45, 1.0f, 1, 2, "mirror: 45 tokens from 300" }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - int err = sim_point(pts[i].w, 0, pts[i].split, pts[i].max_pos, pts[i].pos0, pts[i].m, pts[i].qs, 100 + (uint32_t)i, pts[i].orders, msg, sizeof msg, &worst, &bad); - CHECK(err == 0 && bad == 0, "sim %s: %s", pts[i].name, msg); - printf("sim %-40s W=%u: %s %s\n", pts[i].name, pts[i].w, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - fflush(stdout); - } - for (int split = 0; split <= 2; split++) for (int m = 1; m <= 4; m++) { - int err = sim_point(8, m, split, 256, 40, 24, 1.0f, 200, 1, msg, sizeof msg, &worst, &bad); - int caught = err != 0 || bad > 0; - CHECK(caught, "sim %s mutant %d NOT caught (%s)", split == 2 ? "mirror" : split ? "split" : "fused", m, msg); - printf("sim %s mutant %d at 24 tokens from 40: %s (%s)\n", split == 2 ? "mirror" : split ? "split" : "fused", m, caught ? "caught" : "MISSED", msg); - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static FILE *g_json; -static int g_warm; /* untimed calls before each timing series (--warm N) */ -static int g_cached; /* --cached: device-entry checks use omega_gpu_pf_alloc_dev buffers (needs PATTN_HAVE_PF) */ -static int g_mirror_on = 1; -static int g_fused; /* --fused: the cut-1 fused path, which never builds a K/V mirror */ -/* the mirror contract: forget the cache's K/V mirrors before freeing it */ -static void cache_free(OmegaGpuDecodeAttnCache *c) { omega_gpu_prefill_attn_kv_mirror_forget(c); omega_gpu_decode_attn_cache_free(c); } -static int cache_with_history(const Case *c, OmegaGpuDecodeAttnCache **out) { - int rc = omega_gpu_decode_attn_cache_alloc(1, c->max_pos, THETA, out); - if (rc != OMEGA_GPU_DATTN_OK) return rc; - rc = omega_gpu_decode_attn_set_norms(*out, 0, c->qn, c->kn); - for (unsigned g = 0; g < 4 && rc == OMEGA_GPU_DATTN_OK && c->pos0; g++) - rc = omega_gpu_decode_attn_cache_write(*out, 0, g, 0, c->pos0, c->kc + (size_t)g * c->max_pos * 128, c->vc + (size_t)g * c->max_pos * 128); - return rc; -} -/* reads rows pos0 .. pos0+m-1 of every KV head into the case-shaped arrays kc/vc (history copied from the case) */ -static int read_rows(OmegaGpuDecodeAttnCache *cc, const Case *c, uint16_t *kc, uint16_t *vc) { - memcpy(kc, c->kc, (size_t)4 * c->max_pos * 256); memcpy(vc, c->vc, (size_t)4 * c->max_pos * 256); - for (unsigned g = 0; g < 4; g++) for (uint32_t t = 0; t < c->m; t++) { - size_t o = ((size_t)g * c->max_pos + c->pos0 + t) * 128; - if (omega_gpu_decode_attn_cache_read(cc, 0, g, c->pos0 + t, kc + o, vc + o) != OMEGA_GPU_DATTN_OK) return -1; - } - return 0; -} -static int chip_point(uint32_t max_pos, uint32_t pos0, uint32_t m, float qscale, uint32_t seed, int with_decode, float out_scale, int reps) { - Case c; case_make(&c, max_pos, pos0, m, seed, qscale); - OmegaGpuDecodeAttnCache *pc = NULL, *dc = NULL; - float *out = malloc((size_t)m * OUTW * 4), *out2 = malloc((size_t)m * OUTW * 4), *dout = malloc((size_t)m * OUTW * 4); - uint16_t *kc = malloc((size_t)4 * max_pos * 256), *vc = malloc((size_t)4 * max_pos * 256); - uint16_t *dk = malloc((size_t)4 * max_pos * 256), *dv = malloc((size_t)4 * max_pos * 256); - int ok = 1; - OmegaGpuPrefillAttnInfo info; - int rc = cache_with_history(&c, &pc); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(pc, 0, pos0, m, c.qkv, EPS, out_scale, out, &info); - CHECK(rc == OMEGA_GPU_DATTN_OK, "chip prefill pos0 %u m %u: rc %s (%s)", pos0, m, omega_gpu_decode_attn_rc_name(rc), omega_gpu_decode_attn_last_error()); - if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } - CHECK(read_rows(pc, &c, kc, vc) == 0, "read rows"); - double worst; size_t bad = parity(&c, kc, vc, out, out_scale, &worst); - size_t kd, vd; int mu; rows_vs_emu(&c, kc, vc, &kd, &vd, &mu); - CHECK(bad == 0, "chip pos0 %u m %u: %zu outputs outside the tolerance (worst %.3f)", pos0, m, bad, worst); - CHECK(vd == 0 && mu <= 1, "chip pos0 %u m %u: rows vs host emulation: k %zu differ (max %d ulp), v %zu differ", pos0, m, kd, mu, vd); - printf("chip pos0 %5u m %5u: parity bad=%zu worst=%.3f; rows vs emulation k %zu (max %d ulp) v %zu; chunks %u grid %ux%u x%u thr; chip %.3f ms call %.3f ms\n", - pos0, m, bad, worst, kd, mu, vd, info.chunks, info.grid_x, info.grid_y, info.threads, info.elapsed_ns / 1e6, info.call_ns / 1e6); - ok &= bad == 0 && vd == 0 && mu <= 1; - /* second call: same rows rewritten, output bit-identical */ - rc = omega_gpu_prefill_attn(pc, 0, pos0, m, c.qkv, EPS, out_scale, out2, NULL); - int same = rc == OMEGA_GPU_DATTN_OK && memcmp(out, out2, (size_t)m * OUTW * 4) == 0; - CHECK(same, "chip pos0 %u m %u: second call not bit-identical", pos0, m); - ok &= same; - double pre_med = 0, dec_ms = 0; - if (reps > 0) { - uint64_t *t = malloc(sizeof(uint64_t) * reps), *tc = malloc(sizeof(uint64_t) * reps); - static uint64_t lns[256], worst_l[256]; uint32_t worst_n = 0; uint64_t worst_t = 0; - for (int r = 0; r < g_warm; r++) omega_gpu_prefill_attn(pc, 0, pos0, m, c.qkv, EPS, out_scale, out2, NULL); - printf(" reps chip ms (in order, %d untimed warm calls first):", g_warm); - for (int r = 0; r < reps; r++) { - omega_gpu_prefill_attn(pc, 0, pos0, m, c.qkv, EPS, out_scale, out2, &info); t[r] = info.elapsed_ns; tc[r] = info.call_ns; - uint32_t nl = omega_gpu_prefill_attn_test_launch_ns(lns, 256); - printf(" %.3f", t[r] / 1e6); - if (t[r] > worst_t) { worst_t = t[r]; worst_n = nl < 256 ? nl : 256; memcpy(worst_l, lns, worst_n * sizeof *lns); } - } - printf("\n slowest rep, per launch ms (%u launches):", worst_n); - for (uint32_t i = 0; i < worst_n; i++) printf(" %.3f", worst_l[i] / 1e6); - printf("\n"); - qsort(t, reps, sizeof *t, cmp_u64); qsort(tc, reps, sizeof *tc, cmp_u64); - pre_med = t[reps / 2] / 1e6; - double flops = 0; for (uint32_t i = 0; i < m; i++) flops += 4.0 * 32 * 128 * (pos0 + i + 1.0); - printf(" timing prefill pos0 %u m %u: chip median %.3f ms (min %.3f) call median %.3f ms; %.2f useful TFLOPS on chip time\n", - pos0, m, pre_med, t[0] / 1e6, tc[reps / 2] / 1e6, flops / (pre_med * 1e-3) / 1e12); - if (g_json) fprintf(g_json, " {\"pos0\": %u, \"m\": %u, \"prefill_chip_ms_median\": %.4f, \"prefill_call_ms_median\": %.4f, \"useful_tflops\": %.3f},\n", pos0, m, pre_med, tc[reps / 2] / 1e6, flops / (pre_med * 1e-3) / 1e12); - free(t); free(tc); - } - if (with_decode) { - /* gate 2: m decode steps on a twin cache: rows bit-identical, outputs within the tolerance of each other */ - rc = cache_with_history(&c, &dc); - uint64_t chip = 0, call = 0; OmegaGpuDecodeAttnInfo di; - for (uint32_t i = 0; i < m && rc == OMEGA_GPU_DATTN_OK; i++) { rc = omega_gpu_decode_attn(dc, 0, pos0 + i, c.qkv + (size_t)i * QKVW, EPS, out_scale, dout + (size_t)i * OUTW, &di); chip += di.elapsed_ns; call += di.call_ns; } - CHECK(rc == OMEGA_GPU_DATTN_OK, "decode twin: rc %s (%s)", omega_gpu_decode_attn_rc_name(rc), omega_gpu_decode_attn_last_error()); - if (rc == OMEGA_GPU_DATTN_OK && read_rows(dc, &c, dk, dv) == 0) { - size_t rk = 0, rv = 0; - for (unsigned g = 0; g < 4; g++) for (uint32_t t2 = 0; t2 < m; t2++) for (unsigned i = 0; i < 128; i++) { - size_t o = ((size_t)g * max_pos + pos0 + t2) * 128 + i; rk += kc[o] != dk[o]; rv += vc[o] != dv[o]; } - double dw = 0; size_t dbad = 0, tol_n = 0; - for (size_t i = 0; i < (size_t)m * OUTW; i++) { double d = fabs((double)out[i] - (double)dout[i]) / (1e-2 * out_scale); if (d > dw) dw = d; if (d > 1.0) dbad++; tol_n++; } - CHECK(rk == 0 && rv == 0, "gate 2: prefill rows differ from the decode kernel's rows: k %zu v %zu", rk, rv); - CHECK(dbad == 0, "gate 2: prefill vs decode outputs: %zu outside the tolerance (worst %.3f)", dbad, dw); - dec_ms = chip / 1e6; - printf(" gate 2 vs %u decode steps: rows k %zu v %zu differ; outputs worst %.3f of tol; decode loop chip %.3f ms call %.3f ms%s\n", - m, rk, rv, dw, chip / 1e6, call / 1e6, pre_med > 0 ? "" : ""); - if (pre_med > 0) printf(" speed: prefill %.3f ms vs decode loop %.3f ms chip time: %.1fx\n", pre_med, dec_ms, dec_ms / pre_med); - if (g_json) fprintf(g_json, " {\"pos0\": %u, \"m\": %u, \"gate2_rows_k_diff\": %zu, \"gate2_rows_v_diff\": %zu, \"gate2_out_worst\": %.4f, \"decode_loop_chip_ms\": %.4f, \"decode_loop_call_ms\": %.4f},\n", pos0, m, rk, rv, dw, chip / 1e6, call / 1e6); - ok &= rk == 0 && rv == 0 && dbad == 0; - } else ok = 0; - } -done: - if (pc) cache_free(pc); - if (dc) cache_free(dc); - free(out); free(out2); free(dout); free(kc); free(vc); free(dk); free(dv); case_free(&c); - return ok; -} -/* device-resident entry: qkv and out in session buffers (GPU VAs); output and rows must equal the host entry's bit for bit */ -static int dev_buf(size_t bytes, OmegaGpuMem *m) { - omega_gpu_session_lock(); - int rc = omega_gpu_session_open() ? omega_gpu_session_alloc(bytes, m) : -1; - omega_gpu_session_unlock(); - return rc; -} -static int chip_dev(uint32_t max_pos, uint32_t pos0, uint32_t m, uint32_t seed, int reps) { - Case c; case_make(&c, max_pos, pos0, m, seed, 1.0f); - OmegaGpuDecodeAttnCache *hc = NULL, *dc = NULL; - float *hout = malloc((size_t)m * OUTW * 4); - uint16_t *hk = malloc((size_t)4 * max_pos * 256), *hv = malloc((size_t)4 * max_pos * 256); - uint16_t *dk = malloc((size_t)4 * max_pos * 256), *dv = malloc((size_t)4 * max_pos * 256); - OmegaGpuMem q, o; memset(&q, 0, sizeof q); memset(&o, 0, sizeof o); - float *odh = NULL; - int ok = 1; - OmegaGpuPrefillAttnInfo info, dinfo; - int rc = cache_with_history(&c, &hc); - if (rc == OMEGA_GPU_DATTN_OK) rc = cache_with_history(&c, &dc); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(hc, 0, pos0, m, c.qkv, EPS, 1.0f, hout, &info); - CHECK(rc == OMEGA_GPU_DATTN_OK, "dev point %u+%u: host entry rc %s", pos0, m, omega_gpu_decode_attn_rc_name(rc)); - if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } -#if PATTN_HAVE_PF - if (g_cached) { /* W-L1G's GPU-cached device-private buffers, filled and read only through GPU copies */ - CHECK(omega_gpu_pf_alloc_dev((size_t)m * QKVW * 4, &q) == OMEGA_GPU_PF_OK && omega_gpu_pf_alloc_dev((size_t)m * OUTW * 4, &o) == OMEGA_GPU_PF_OK, "dev point: cached device buffers"); - if (!q.va || !o.va) { ok = 0; goto done; } - odh = malloc((size_t)m * OUTW * 4); - for (size_t i = 0; i < (size_t)m * OUTW; i++) odh[i] = -999.0f; - CHECK(omega_gpu_pf_upload(&q, 0, c.qkv, (size_t)m * QKVW * 4) == OMEGA_GPU_PF_OK && omega_gpu_pf_upload(&o, 0, odh, (size_t)m * OUTW * 4) == OMEGA_GPU_PF_OK, "dev point: upload through the copy kernel"); - } else -#endif - { - CHECK(dev_buf((size_t)m * QKVW * 4, &q) == 0 && dev_buf((size_t)m * OUTW * 4, &o) == 0, "dev point: session buffers"); - if (!q.cpu || !o.cpu) { ok = 0; goto done; } - memcpy(q.cpu, c.qkv, (size_t)m * QKVW * 4); - float *op = o.cpu; for (size_t i = 0; i < (size_t)m * OUTW; i++) op[i] = -999.0f; - omega_gpu_session_lock(); omega_gpu_session_sync_to_gpu(&q); omega_gpu_session_sync_to_gpu(&o); omega_gpu_session_unlock(); - } - /* negative control: misaligned and zero VAs are refused before any launch */ - CHECK(omega_gpu_prefill_attn_dev(dc, 0, pos0, m, q.va + 4, EPS, 1.0f, o.va, NULL) == OMEGA_GPU_DATTN_BAD_ARGS, "dev: misaligned qkv VA refused"); - CHECK(omega_gpu_prefill_attn_dev(dc, 0, pos0, m, q.va, EPS, 1.0f, 0, NULL) == OMEGA_GPU_DATTN_BAD_ARGS, "dev: zero out VA refused"); - rc = omega_gpu_prefill_attn_dev(dc, 0, pos0, m, q.va, EPS, 1.0f, o.va, &dinfo); - CHECK(rc == OMEGA_GPU_DATTN_OK, "dev point %u+%u: rc %s (%s)", pos0, m, omega_gpu_decode_attn_rc_name(rc), omega_gpu_decode_attn_last_error()); - if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } - float *od; -#if PATTN_HAVE_PF - if (g_cached) { CHECK(omega_gpu_pf_download(&o, 0, odh, (size_t)m * OUTW * 4) == OMEGA_GPU_PF_OK, "dev point: download through the copy kernel"); od = odh; } - else -#endif - { omega_gpu_session_lock(); omega_gpu_session_sync_to_cpu(&o); omega_gpu_session_unlock(); od = o.cpu; } - size_t unw = 0, diff = 0; - for (size_t i = 0; i < (size_t)m * OUTW; i++) { if (od[i] == -999.0f) unw++; else if (memcmp(&od[i], &hout[i], 4)) diff++; } - CHECK(read_rows(hc, &c, hk, hv) == 0 && read_rows(dc, &c, dk, dv) == 0, "dev point: read rows"); - size_t rk = 0, rv = 0; - for (size_t i = 0; i < (size_t)4 * max_pos * 128; i++) { rk += hk[i] != dk[i]; rv += hv[i] != dv[i]; } - CHECK(unw == 0 && diff == 0, "dev point %u+%u: %zu outputs unwritten, %zu differ from the host entry", pos0, m, unw, diff); - CHECK(rk == 0 && rv == 0, "dev point %u+%u: cache rows differ from the host entry: k %zu v %zu", pos0, m, rk, rv); - ok &= unw == 0 && diff == 0 && rk == 0 && rv == 0; - printf("chip dev%s pos0 %5u m %5u: outputs vs host entry: %zu unwritten, %zu differ; rows k %zu v %zu differ; launches %u grid %ux%u; chip %.3f ms call %.3f ms\n", - g_cached ? " (cached buffers)" : "", pos0, m, unw, diff, rk, rv, dinfo.chunks, dinfo.grid_x, dinfo.grid_y, dinfo.elapsed_ns / 1e6, dinfo.call_ns / 1e6); - if (reps > 0) { - uint64_t *t = malloc(sizeof(uint64_t) * reps), *tc = malloc(sizeof(uint64_t) * reps); - for (int r = 0; r < g_warm; r++) omega_gpu_prefill_attn_dev(dc, 0, pos0, m, q.va, EPS, 1.0f, o.va, NULL); - printf(" dev reps chip ms:"); - for (int r = 0; r < reps; r++) { omega_gpu_prefill_attn_dev(dc, 0, pos0, m, q.va, EPS, 1.0f, o.va, &dinfo); t[r] = dinfo.elapsed_ns; tc[r] = dinfo.call_ns; printf(" %.3f", t[r] / 1e6); } - qsort(t, reps, sizeof *t, cmp_u64); qsort(tc, reps, sizeof *tc, cmp_u64); - double flops = 0; for (uint32_t i = 0; i < m; i++) flops += 4.0 * 32 * 128 * (pos0 + i + 1.0); - printf("\n timing dev pos0 %u m %u: chip median %.3f ms (min %.3f) call median %.3f ms; %.2f useful TFLOPS on chip time\n", - pos0, m, t[reps / 2] / 1e6, t[0] / 1e6, tc[reps / 2] / 1e6, flops / (t[reps / 2] * 1e-9) / 1e12); - if (g_json) fprintf(g_json, " {\"dev\": 1, \"pos0\": %u, \"m\": %u, \"chip_ms_median\": %.4f, \"chip_ms_min\": %.4f, \"call_ms_median\": %.4f, \"out_diff\": %zu, \"rows_diff\": %zu},\n", - pos0, m, t[reps / 2] / 1e6, t[0] / 1e6, tc[reps / 2] / 1e6, diff, rk + rv); - free(t); free(tc); - } -done: -#if PATTN_HAVE_PF - if (g_cached) { if (q.va) omega_gpu_pf_free(&q); if (o.va) omega_gpu_pf_free(&o); } else -#endif - { omega_gpu_session_lock(); if (q.cpu) omega_gpu_session_free(&q); if (o.cpu) omega_gpu_session_free(&o); omega_gpu_session_unlock(); } - free(odh); - if (hc) cache_free(hc); - if (dc) cache_free(dc); - free(hout); free(hk); free(hv); free(dk); free(dv); case_free(&c); - return ok; -} -/* persistent mirror (cut 5): prefill 300, decode 5, prefill 64, then a foreign rewrite of rows 0..99 and prefill 32. - * Cache X runs with the mirror, cache Y without (cut 3 path, the reference). Outputs must be bit-identical, except - * the negative control: the rewrite WITHOUT invalidate must make X differ (the stale mirror is visible), and after - * invalidate X must match again. */ -static int chip_continuation(void) { - if (!omega_gpu_prefill_attn_kv_mirror_available() || !g_mirror_on) { printf("chip continuation: skipped (no mirror in this build or --no-mirror)\n"); return 1; } - /* the mirror lives on the split path (APPEND + ATTEND): the API calls mirror_get only when not fused, so the fused - * path never builds one and the check has nothing to compare there. The default (split) run covers it. */ - if (g_fused) { printf("chip continuation: skipped (--fused: the fused path builds no K/V mirror; the split run covers it)\n"); return 1; } - const uint32_t MP = 1024, NA = 300, ND = 5, NB = 64, NC = 32, N = NA + ND + NB + NC; - Case c, junk; case_make(&c, MP, 0, N, 21, 1.0f); case_make(&junk, MP, 100, 1, 22, 1.0f); - OmegaGpuDecodeAttnCache *x = NULL, *y = NULL; - float *ox = malloc((size_t)N * OUTW * 4), *oy = malloc((size_t)N * OUTW * 4), *ox2 = malloc((size_t)NC * OUTW * 4); - int ok = 1, rc = cache_with_history(&c, &x); - if (rc == OMEGA_GPU_DATTN_OK) rc = cache_with_history(&c, &y); - OmegaGpuDecodeAttnInfo di; - OmegaGpuDecodeAttnCache *cs[2] = { x, y }; - float *os[2] = { ox, oy }; - for (int k = 0; k < 2 && rc == OMEGA_GPU_DATTN_OK; k++) { - omega_gpu_prefill_attn_set_kv_mirror(k == 0); - const float *q = c.qkv; float *o = os[k]; - rc = omega_gpu_prefill_attn(cs[k], 0, 0, NA, q, EPS, 1.0f, o, NULL); - for (uint32_t i = 0; i < ND && rc == OMEGA_GPU_DATTN_OK; i++) - rc = omega_gpu_decode_attn(cs[k], 0, NA + i, q + (size_t)(NA + i) * QKVW, EPS, 1.0f, o + (size_t)(NA + i) * OUTW, &di); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(cs[k], 0, NA + ND, NB, q + (size_t)(NA + ND) * QKVW, EPS, 1.0f, o + (size_t)(NA + ND) * OUTW, NULL); - } - CHECK(rc == OMEGA_GPU_DATTN_OK, "continuation: rc %s (%s)", omega_gpu_decode_attn_rc_name(rc), omega_gpu_decode_attn_last_error()); - if (rc != OMEGA_GPU_DATTN_OK) { ok = 0; goto done; } - OmegaGpuPrefillAttnMirrorView mv; - int vrc = omega_gpu_prefill_attn_kv_mirror_view(x, 0, &mv); - CHECK(vrc == OMEGA_GPU_DATTN_OK && mv.valid == NA + ND + NB && mv.kv_stride == MP * 256u, "continuation: mirror view valid %u (want %u) stride %u", mv.valid, NA + ND + NB, mv.kv_stride); - size_t d1 = 0; for (size_t i = 0; i < (size_t)(NA + ND + NB) * OUTW; i++) d1 += memcmp(&ox[i], &oy[i], 4) != 0; - CHECK(d1 == 0, "continuation: %zu outputs differ, mirror vs no mirror", d1); - /* foreign writer: rows 0..99 of head 0 rewritten in both caches */ - for (int k = 0; k < 2; k++) omega_gpu_decode_attn_cache_write(cs[k], 0, 0, 0, 100, junk.kc, junk.vc); - const size_t offC = (size_t)(NA + ND + NB); - omega_gpu_prefill_attn_set_kv_mirror(0); - rc = omega_gpu_prefill_attn(y, 0, offC, NC, c.qkv + offC * QKVW, EPS, 1.0f, oy + offC * OUTW, NULL); - omega_gpu_prefill_attn_set_kv_mirror(1); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(x, 0, offC, NC, c.qkv + offC * QKVW, EPS, 1.0f, ox2, NULL); /* no invalidate */ - size_t stale = 0; for (size_t i = 0; i < (size_t)NC * OUTW; i++) stale += memcmp(&ox2[i], &oy[offC * OUTW + i], 4) != 0; - omega_gpu_prefill_attn_kv_mirror_invalidate(x, UINT32_MAX, 0); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(x, 0, offC, NC, c.qkv + offC * QKVW, EPS, 1.0f, ox + offC * OUTW, NULL); - size_t d2 = 0; for (size_t i = 0; i < (size_t)NC * OUTW; i++) d2 += memcmp(&ox[offC * OUTW + i], &oy[offC * OUTW + i], 4) != 0; - CHECK(rc == OMEGA_GPU_DATTN_OK, "continuation C: rc %s", omega_gpu_decode_attn_rc_name(rc)); - CHECK(stale > 0, "negative control: a foreign rewrite without invalidate must show (stale mirror), %zu outputs differ", stale); - CHECK(d2 == 0, "after invalidate: %zu outputs differ, mirror vs no mirror", d2); - printf("chip continuation (prefill %u, decode %u, prefill %u, rewrite, prefill %u): mirror valid %u; outputs differ mirror vs none: %zu; " - "stale control %zu differ (must be > 0); after invalidate %zu differ\n", NA, ND, NB, NC, mv.valid, d1, stale, d2); - ok &= d1 == 0 && stale > 0 && d2 == 0 && vrc == OMEGA_GPU_DATTN_OK; -done: - omega_gpu_prefill_attn_set_kv_mirror(1); - if (x) cache_free(x); - if (y) cache_free(y); - free(ox); free(oy); free(ox2); case_free(&c); case_free(&junk); - return ok; -} -static void chip_mutants(void) { - for (int mu = 1; mu <= 4; mu++) { - omega_gpu_prefill_attn_test_set_mutant(mu); - Case c; case_make(&c, 256, 40, 24, 200, 1.0f); - OmegaGpuDecodeAttnCache *pc = NULL; - float *out = malloc((size_t)24 * OUTW * 4); - uint16_t *kc = malloc((size_t)4 * 256 * 256), *vc = malloc((size_t)4 * 256 * 256); - int rc = cache_with_history(&c, &pc); - if (rc == OMEGA_GPU_DATTN_OK) rc = omega_gpu_prefill_attn(pc, 0, 40, 24, c.qkv, EPS, 1.0f, out, NULL); - int caught = rc != OMEGA_GPU_DATTN_OK; - double worst = 0; size_t bad = 0, kd = 0, vd = 0; int mx = 0; - if (!caught && read_rows(pc, &c, kc, vc) == 0) { - bad = parity(&c, kc, vc, out, 1.0f, &worst); - rows_vs_emu(&c, kc, vc, &kd, &vd, &mx); - caught = bad > 0 || vd > 0 || mx > 1; - } - CHECK(caught, "chip mutant %d NOT caught", mu); - printf("chip mutant %d: %s (rc %s, bad %zu, worst %.2f, rows k %zu v %zu)\n", mu, caught ? "caught" : "MISSED", omega_gpu_decode_attn_rc_name(rc), bad, worst, kd, vd); - if (pc) cache_free(pc); - free(out); free(kc); free(vc); case_free(&c); - } - omega_gpu_prefill_attn_test_set_mutant(0); -} - -int main(int argc, char **argv) { - int host = 0, sim = 0, reps = 9, quick = 0, fused = 0, timing_only = 0; const char *json = NULL; uint32_t warps = 0; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) host = 1; - else if (!strcmp(argv[i], "--sim")) sim = 1; - else if (!strcmp(argv[i], "--quick")) quick = 1; - else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = atoi(argv[++i]); - else if (!strcmp(argv[i], "--warps") && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--out") && i + 1 < argc) json = argv[++i]; - else if (!strcmp(argv[i], "--fused")) fused = g_fused = 1; - else if (!strcmp(argv[i], "--no-mirror")) { omega_gpu_prefill_attn_set_kv_mirror(0); g_mirror_on = 0; } - else if (!strcmp(argv[i], "--cached") && PATTN_HAVE_PF) g_cached = 1; - else if (!strcmp(argv[i], "--mirror-per-call")) omega_gpu_prefill_attn_test_set_mirror_per_call(1); - else if (!strcmp(argv[i], "--timing-only")) timing_only = 1; - else if (!strcmp(argv[i], "--warm") && i + 1 < argc) g_warm = atoi(argv[++i]); - else { fprintf(stderr, "usage: %s [--host-only | --sim | [--quick] [--reps N] [--warps 4|8] [--fused] [--no-mirror] [--mirror-per-call] [--cached] [--warm N] [--timing-only] [--out receipt.json]]\n", argv[0]); return 2; } - } - host_only(); - if (sim) sim_battery(); - if (!host && !sim) { - if (json) { g_json = fopen(json, "w"); if (g_json) fprintf(g_json, "{\"test\": \"gpu_prefill_attn\", \"points\": [\n"); } - if (warps) omega_gpu_prefill_attn_set_warps(warps); - int ok = 1; - if (fused) omega_gpu_prefill_attn_set_fused(1); - printf("path: %s, warps %u, warm %d, dev buffers %s\n", fused ? "fused 64-token chunks" : g_mirror_on && omega_gpu_prefill_attn_kv_mirror_available() ? "split APPEND + ATTEND, ATTEND reads the GPU-cached K/V mirror" : "split APPEND + ATTEND, ATTEND reads the uncached cache", warps ? warps : OMEGA_GPU_PATTN_WARPS, g_warm, g_cached ? "GPU-cached (pf_alloc_dev)" : "session (uncached)"); - if (timing_only) { - ok &= chip_point(4096, 0, 2048, 1.0f, 8, 0, 1.0f, reps); - ok &= chip_dev(4096, 0, 2048, 8, reps); - ok &= chip_dev(8192, 4096, 1500, 12, reps); - ok &= chip_point(4096, 4032, 64, 1.0f, 7, 0, 1.0f, reps); - ok &= chip_dev(8192, 4096, 64, 13, reps); - } else { - ok &= chip_point(256, 0, 1, 1.0f, 1, 1, 1.0f, 0); - ok &= chip_point(256, 37, 19, 1.0f, 2, 1, 1.0f, 0); - ok &= chip_point(256, 0, 64, 1.0f, 3, 1, 1.0f, reps); - ok &= chip_point(512, 100, 70, 4.0f, 4, 1, 1.0f, 0); - ok &= chip_point(512, 200, 64, 1.0f, 5, 1, 18446744073709551616.0f, 0); - if (!quick) { - ok &= chip_point(1024, 0, 512, 1.0f, 6, 1, 1.0f, reps); - ok &= chip_point(4096, 4032, 64, 1.0f, 7, 1, 1.0f, reps); - ok &= chip_point(4096, 0, 2048, 1.0f, 8, 0, 1.0f, reps); - } - ok &= chip_dev(512, 100, 70, 11, 0); - if (!quick) { ok &= chip_dev(4096, 0, 2048, 8, reps); ok &= chip_dev(8192, 4096, 1500, 12, reps); } - ok &= chip_continuation(); - chip_mutants(); - } - (void)ok; - if (g_json) { fprintf(g_json, " {}\n], \"checks\": %d, \"failed\": %d}\n", g_checks, g_failed); fclose(g_json); } - } - printf("gpu_prefill_attn_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_q38_graph_test.c b/tests/gpu_q38_graph_test.c deleted file mode 100644 index 69de826c8..000000000 --- a/tests/gpu_q38_graph_test.c +++ /dev/null @@ -1,369 +0,0 @@ -/* - * gpu_q38_graph_test: one Qwen3.8-27B decode token as ONE command list (omega_gpu_q38_graph.h, sc #642). - * --host-only the gather table against the attention API's permutation, and the create / set_layer refusals that - * need no device beyond the session - * (default) chip, caller holds the GB10 lock. A synthetic Qwen3.8-shaped model on random weights: hidden 5120, - * intermediate 17408, vocab 248320; --layers N (2) and --mask M (0x2: bit l = layer l is attention), so by - * default one GDN layer then one attention layer: both kinds and the handover between them in every token. - * Tokens at positions 0, 1, 2: - * A baseline = the APIs one call at a time (FP8 / bf16 GEMV, GDN step, hd256 attention), host glue in - * C: rmsnorm f64, the gather table, sigmoid gate expf, SwiGLU expf, argmax strict >; its own GDN - * state and KV cache - * C main = the same token recorded as one list (omega_gpu_q38_graph_token) - * B the same list submitted one launch per submission (flush_each) - * Checks per token: B == C bit for bit (x, logits, token); A vs C token identical and logits within - * tolerance; x within tolerance. Negative controls: graph mutants 1..4 (SWIGLU, GATHER, GATE, post-norm - * weight) must each fail the A-vs-C comparison. Then --reps timed tokens (median). - * Verdict: exit 0 when every CHECK passed. - */ -#include "omega_gpu_q38_graph.h" -#include "omega_gpu_cmdlist.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include -#include - -#define H OMEGA_GPU_Q38_HIDDEN -#define I OMEGA_GPU_Q38_INTER -#define EPS 1e-6f -#define MAX_POS 256u -#define TOKENS 3u -#define SCALE_2P64 18446744073709551616.0f -#define SCALE_2M64 5.42101086242752217e-20f -/* A vs C: |d| <= TOL_REL * max|ref|. The differences: RMSNorm f32 FFMA + MUFU.RSQ vs f64 host, SwiGLU / gate MUFU EX2 / - * RCP vs expf (~1e-7 relative each) through 2 layers and 5120- to 17408-term sums; 1e-4 is ~100x that. */ -#define TOL_REL 1e-4 - -static int g_checks, g_failed; -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } else { printf("ok: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint64_t median_u64(uint64_t *v, unsigned n) { qsort(v, n, sizeof *v, cmp_u64); return v[n / 2]; } - -static void rmsnorm(const float *x, const float *w, float *out) { - double sq = 0; for (unsigned i = 0; i < H; i++) sq += (double)x[i] * x[i]; - float s = (float)(1.0 / sqrt(sq / H + (double)EPS)); - for (unsigned i = 0; i < H; i++) out[i] = x[i] * s * w[i]; -} -static uint32_t argmax(const float *v, uint32_t n) { uint32_t b = 0; for (uint32_t i = 1; i < n; i++) if (v[i] > v[b]) b = i; return b; } -static double maxabs(const float *v, size_t n) { double m = 0; for (size_t i = 0; i < n; i++) if (fabs(v[i]) > m) m = fabs(v[i]); return m; } -static double maxdiff(const float *a, const float *b, size_t n) { double m = 0; for (size_t i = 0; i < n; i++) { double d = fabs((double)a[i] - b[i]); if (d > m || d != d) m = d != d ? 1e30 : d; } return m; } - -static int fp8_random(uint32_t seed, uint32_t n, uint32_t k, OmegaGpuFp8Tensor **out) { - size_t wb = (size_t)n * k, sb = (size_t)(n / 128) * (k / 128); - uint8_t *w = malloc(wb); uint16_t *s = malloc(sb * 2); - if (!w || !s) { free(w); free(s); return -1; } - uint32_t st = seed; - for (size_t i = 0; i < wb; i += 4) { uint32_t r = lcg(&st); for (unsigned j = 0; j < 4 && i + j < wb; j++) w[i + j] = (uint8_t)((r >> (8 * j)) & 0xbfu); } /* |v| <= 1.875: never a NaN code */ - const float sc = 1.5f / sqrtf((float)k); /* outputs O(1) for O(1) inputs */ - for (size_t i = 0; i < sb; i++) s[i] = bf16_rne(frand(&st, 0.5f * sc, sc)); - int rc = omega_gpu_fp8_tensor_upload(1, n, k, w, s, out); - free(w); free(s); - return rc; -} -static int bf16_random(uint32_t seed, uint32_t n, uint32_t k, float lo, float hi, float mul, OmegaGpuBf16Tensor **out) { - uint16_t *w = malloc((size_t)n * k * 2); - if (!w) return -1; - uint32_t st = seed; - for (size_t i = 0; i < (size_t)n * k; i++) w[i] = bf16_rne(frand(&st, lo, hi) * mul); - int rc = omega_gpu_bf16_tensor_upload(n, k, w, out); - free(w); - return rc; -} - -/* ---- the synthetic model ---- */ -typedef struct { - uint32_t layers, vocab, n_gdn, n_attn; - uint64_t mask; - struct { OmegaGpuFp8Tensor *mix, *o, *gu, *dn; OmegaGpuBf16Tensor *ab; float in_norm[H], post_norm[H]; } L[8]; - OmegaGpuBf16Tensor *lm; - OmegaGpuFp8Tensor *lm8; /* --fp8-head: the same lm_head quantised by omega_gpu_fp8_quantize_bf16 */ - uint8_t *lm8_w; uint16_t *lm8_s; /* its host copy (the sampled-row host check) */ - float fnorm[H]; - float x0[TOKENS][H]; - /* the two state copies: [0] the graph's, [1] the baseline's */ - OmegaGpuGdn *gdn[2]; - OmegaGpuDecodeAttn256Cache *attn[2]; -} Model; -static int g_fp8_head; /* --fp8-head: the graph and the baseline use the FP8-quantised lm_head */ - -static int state_alloc(Model *m, int which, uint32_t seed) { - uint32_t s = seed; - if (omega_gpu_gdn_alloc(m->n_gdn ? m->n_gdn : 1, &m->gdn[which]) != 0) { printf("gdn alloc: %s\n", omega_gpu_gdn_last_error()); return -1; } - float *conv = malloc((size_t)OMEGA_GPU_Q38_GDN_QKV * 4 * 4), a_log[48], dtb[48], nw[128]; - if (!conv) return -1; - for (uint32_t l = 0; l < (m->n_gdn ? m->n_gdn : 1); l++) { - for (size_t i = 0; i < (size_t)OMEGA_GPU_Q38_GDN_QKV * 4; i++) conv[i] = frand(&s, -0.6f, 0.6f); - for (unsigned h = 0; h < 48; h++) { a_log[h] = frand(&s, -1.5f, 1.5f); dtb[h] = frand(&s, -3.0f, 1.0f); } - for (unsigned i = 0; i < 128; i++) nw[i] = frand(&s, 0.8f, 1.2f); - if (omega_gpu_gdn_set_layer(m->gdn[which], l, conv, a_log, dtb, nw) != 0) { printf("gdn set: %s\n", omega_gpu_gdn_last_error()); free(conv); return -1; } - } - free(conv); - if (omega_gpu_decode_attn256_cache_alloc(m->n_attn ? m->n_attn : 1, MAX_POS, 10000000.0, OMEGA_GPU_Q38_ROTARY, &m->attn[which]) != 0) { printf("attn alloc: %s\n", omega_gpu_decode_attn_last_error()); return -1; } - for (uint32_t l = 0; l < (m->n_attn ? m->n_attn : 1); l++) { - float qn[256], kn[256], qp[256], kp[256]; - for (unsigned i = 0; i < 256; i++) { qn[i] = frand(&s, 0.8f, 1.2f); kn[i] = frand(&s, 0.8f, 1.2f); } - omega_dattn256_perm_vec(qn, qp, OMEGA_GPU_Q38_ROTARY); omega_dattn256_perm_vec(kn, kp, OMEGA_GPU_Q38_ROTARY); - if (omega_gpu_decode_attn256_set_norms(m->attn[which], l, qp, kp) != 0) return -1; - } - return 0; -} - -static int model_build(Model *m, uint32_t layers, uint64_t mask, uint32_t vocab) { - memset(m, 0, sizeof *m); m->layers = layers; m->mask = mask; m->vocab = vocab; - uint32_t s = 4321; - for (uint32_t l = 0; l < layers; l++) { - const int attn = (int)((mask >> l) & 1u); - if (attn) m->n_attn++; else m->n_gdn++; - if (fp8_random(100 + l, attn ? OMEGA_GPU_Q38_ATT_MIX : OMEGA_GPU_Q38_GDN_MIX, H, &m->L[l].mix) || fp8_random(200 + l, H, OMEGA_GPU_Q38_MIXER_OUT, &m->L[l].o) || - fp8_random(300 + l, 2 * I, H, &m->L[l].gu) || fp8_random(400 + l, H, I, &m->L[l].dn)) { printf("fp8 upload: %s\n", omega_gpu_fp8_last_error()); return -1; } - if (!attn && bf16_random(500 + l, OMEGA_GPU_Q38_AB, H, -0.03f, 0.03f, SCALE_2M64, &m->L[l].ab)) { printf("bf16 upload: %s\n", omega_gpu_bf16_last_error()); return -1; } - for (unsigned i = 0; i < H; i++) { m->L[l].in_norm[i] = frand(&s, 0.8f, 1.2f); m->L[l].post_norm[i] = frand(&s, 0.8f, 1.2f); } - } - if (bf16_random(600, vocab, H, -0.05f, 0.05f, 1.0f, &m->lm)) { printf("lm_head upload: %s\n", omega_gpu_bf16_last_error()); return -1; } - if (g_fp8_head) { - uint16_t *w = malloc((size_t)vocab * H * 2); m->lm8_w = malloc((size_t)vocab * H); m->lm8_s = malloc((size_t)(vocab / 128) * (H / 128) * 2); - if (!w || !m->lm8_w || !m->lm8_s) return -1; - uint32_t st = 600; for (size_t i = 0; i < (size_t)vocab * H; i++) w[i] = bf16_rne(frand(&st, -0.05f, 0.05f)); /* bf16_random(600, ...)'s values */ - int qrc = omega_gpu_fp8_quantize_bf16(vocab, H, w, m->lm8_w, m->lm8_s); free(w); - if (qrc || omega_gpu_fp8_tensor_upload(1, vocab, H, m->lm8_w, m->lm8_s, &m->lm8)) { printf("fp8 lm_head: %s\n", omega_gpu_fp8_last_error()); return -1; } - } - for (unsigned i = 0; i < H; i++) m->fnorm[i] = frand(&s, 0.8f, 1.2f); - for (unsigned t = 0; t < TOKENS; t++) for (unsigned i = 0; i < H; i++) m->x0[t][i] = frand(&s, -1.0f, 1.0f); - if (state_alloc(m, 0, 777) || state_alloc(m, 1, 777)) return -1; - return 0; -} - -static int state_reset(Model *m) { - /* GDN state to zero; the KV rows at the test's positions are rewritten by every token */ - return omega_gpu_gdn_reset(m->gdn[0]) || omega_gpu_gdn_reset(m->gdn[1]); -} - -/* ---- A: the APIs one call at a time ---- */ -typedef struct { float x[H], logits[248320]; uint32_t token; } Out; - -static int baseline_token(Model *m, const float *x0, uint32_t pos, Out *o) { - static float xn[H], xs[H], mix[OMEGA_GPU_Q38_GDN_MIX], ab[OMEGA_GPU_Q38_AB], agg[OMEGA_GPU_Q38_ATT_MIX], att[OMEGA_GPU_Q38_MIXER_OUT], y[H], gu[2 * I], act[I]; - static uint32_t tab[OMEGA_GPU_Q38_ATT_MIX]; - omega_q38_gather_table(tab); - memcpy(o->x, x0, sizeof o->x); - uint32_t ng = 0, na = 0; - for (uint32_t l = 0; l < m->layers; l++) { - rmsnorm(o->x, m->L[l].in_norm, xn); - { int r_ = omega_gpu_fp8_gemv_f32(m->L[l].mix, 0, xn, mix, NULL); if (r_ != 0) { printf("fp8 gemv rc %d: %s\n", r_, omega_gpu_fp8_last_error()); return -1; } } - if (!((m->mask >> l) & 1u)) { - for (unsigned i = 0; i < H; i++) xs[i] = xn[i] * SCALE_2P64; /* the a|b rows are uploaded * 2^-64 */ - { int r_ = omega_gpu_bf16_gemv_f32(m->L[l].ab, xs, ab, NULL); if (r_ != 0) { printf("bf16 gemv rc %d: %s\n", r_, omega_gpu_bf16_last_error()); return -1; } } - if (omega_gpu_gdn_step(m->gdn[1], ng++, mix, mix + OMEGA_GPU_Q38_GDN_QKV, ab, EPS, EPS, 1.0f, 1.0f, att, NULL) != 0) { printf("gdn step: %s\n", omega_gpu_gdn_last_error()); return -1; } - } else { - for (unsigned n = 0; n < OMEGA_GPU_Q38_ATT_MIX; n++) agg[n] = mix[tab[n]]; - if (omega_gpu_decode_attn256(m->attn[1], na++, pos, agg, EPS, 1.0f, att, NULL) != 0) { printf("attn: %s\n", omega_gpu_decode_attn_last_error()); return -1; } - for (unsigned n = 0; n < OMEGA_GPU_Q38_MIXER_OUT; n++) att[n] = att[n] * (1.0f / (1.0f + expf(-agg[OMEGA_GPU_Q38_ATT_QKV + n]))); - } - { int r_ = omega_gpu_fp8_gemv_f32(m->L[l].o, 0, att, y, NULL); if (r_ != 0) { printf("fp8 gemv rc %d: %s\n", r_, omega_gpu_fp8_last_error()); return -1; } } - for (unsigned i = 0; i < H; i++) o->x[i] = o->x[i] + y[i]; - rmsnorm(o->x, m->L[l].post_norm, xn); - { int r_ = omega_gpu_fp8_gemv_f32(m->L[l].gu, 0, xn, gu, NULL); if (r_ != 0) { printf("fp8 gemv rc %d: %s\n", r_, omega_gpu_fp8_last_error()); return -1; } } - for (unsigned j = 0; j < I; j++) { float v = gu[j]; act[j] = v / (1.0f + expf(-v)) * gu[I + j]; } - { int r_ = omega_gpu_fp8_gemv_f32(m->L[l].dn, 0, act, y, NULL); if (r_ != 0) { printf("fp8 gemv rc %d: %s\n", r_, omega_gpu_fp8_last_error()); return -1; } } - for (unsigned i = 0; i < H; i++) o->x[i] = o->x[i] + y[i]; - } - rmsnorm(o->x, m->fnorm, xn); - if (m->lm8) { - int r_ = omega_gpu_fp8_gemv_f32(m->lm8, 0, xn, o->logits, NULL); if (r_ != 0) { printf("fp8 head rc %d: %s\n", r_, omega_gpu_fp8_last_error()); return -1; } - double worst = 0, ref_max = 0; /* every 97th row against the dequantised host product */ - for (uint32_t r = 0; r < m->vocab; r += 97) { - double acc = 0; - for (uint32_t c = 0; c < H; c++) { uint8_t q = m->lm8_w[(size_t)r * H + c]; unsigned e = (q >> 3) & 15u, mm = q & 7u; double v = e ? (1.0 + mm / 8.0) * ldexp(1.0, (int)e - 7) : mm / 8.0 * ldexp(1.0, -6); if (q & 0x80u) v = -v; - uint32_t sb = (uint32_t)m->lm8_s[(r / 128) * (H / 128) + c / 128] << 16; float sf; memcpy(&sf, &sb, 4); acc += v * sf * xn[c]; } - double d = fabs(acc - o->logits[r]); if (d > worst) worst = d; if (fabs(acc) > ref_max) ref_max = fabs(acc); - } - CHECK(worst <= 1e-4 * ref_max + 1e-6, "fp8 head: sampled rows max diff %.3g vs host dequantised (max %.3g)", worst, ref_max); - } else - { int r_ = omega_gpu_bf16_gemv_f32(m->lm, xn, o->logits, NULL); if (r_ != 0) { printf("bf16 gemv rc %d: %s\n", r_, omega_gpu_bf16_last_error()); return -1; } } - o->token = argmax(o->logits, m->vocab); - return 0; -} - -static int graph_build(Model *m, OmegaGpuQ38Graph **out) { - OmegaGpuQ38GraphConfig c; memset(&c, 0, sizeof c); - c.layers = m->layers; c.attn_mask = m->mask; c.vocab = m->vocab; c.eps = EPS; c.eps_l2 = EPS; - c.gdn = m->gdn[0]; c.attn = m->attn[0]; c.lm_head = m->lm; - int rc = omega_gpu_q38_graph_create(&c, out); - if (rc != 0) { printf("graph create %d: %s\n", rc, omega_gpu_session_last_error()); return -1; } - for (uint32_t l = 0; l < m->layers; l++) - if ((rc = omega_gpu_q38_graph_set_layer(*out, l, m->L[l].mix, m->L[l].ab, m->L[l].o, m->L[l].gu, m->L[l].dn, m->L[l].in_norm, m->L[l].post_norm)) != 0) { printf("set_layer %u: %d\n", l, rc); return -1; } - if (omega_gpu_q38_graph_set_final_norm(*out, m->fnorm) != 0) return -1; - if (m->lm8 && omega_gpu_q38_graph_set_lm_head_fp8(*out, m->lm8) != 0) { printf("set_lm_head_fp8 refused\n"); return -1; } - return 0; -} - -static int graph_token(OmegaGpuQ38Graph *g, Model *m, const float *x0, uint32_t pos, Out *o, OmegaGpuDecodeGraphStats *st) { - int rc = omega_gpu_q38_graph_token(g, x0, pos, &o->token, st); - if (rc != 0) { printf("graph token rc %d: %s\n", rc, omega_gpu_session_last_error()); return -1; } - (void)m; - return omega_gpu_q38_graph_read(g, o->x, NULL, o->logits) != 0 ? -1 : 0; -} - -static int host_only(void) { - static uint32_t tab[OMEGA_GPU_Q38_ATT_MIX]; - omega_q38_gather_table(tab); - int bad = 0; - for (uint32_t h = 0; h < 24; h++) for (uint32_t i = 0; i < 256; i++) if (tab[h * 256 + i] != h * 512 + omega_dattn256_perm_slot(i, 64)) bad++; - for (uint32_t h = 0; h < 4; h++) for (uint32_t i = 0; i < 256; i++) if (tab[6144 + h * 256 + i] != 12288 + h * 256 + omega_dattn256_perm_slot(i, 64)) bad++; - for (uint32_t i = 0; i < 1024; i++) if (tab[7168 + i] != 13312 + i) bad++; - for (uint32_t h = 0; h < 24; h++) for (uint32_t d = 0; d < 256; d++) if (tab[8192 + h * 256 + d] != h * 512 + 256 + d) bad++; - CHECK(bad == 0, "gather table: q, k permuted, v and gate in place (%d wrong)", bad); - static uint8_t seen[OMEGA_GPU_Q38_ATT_MIX]; - int dup = 0; for (uint32_t n = 0; n < OMEGA_GPU_Q38_ATT_MIX; n++) { if (tab[n] >= OMEGA_GPU_Q38_ATT_MIX || seen[tab[n]]) dup++; else seen[tab[n]] = 1; } - CHECK(dup == 0, "gather table is a permutation of the 14336 mix values (%d repeats or out of range)", dup); - OmegaGpuQ38Graph *g = NULL; - OmegaGpuQ38GraphConfig c; memset(&c, 0, sizeof c); - CHECK(omega_gpu_q38_graph_create(&c, &g) == OMEGA_GPU_DGRAPH_BAD_ARGS && !g, "create refuses an empty config"); - CHECK(omega_gpu_q38_graph_create(NULL, &g) == OMEGA_GPU_DGRAPH_BAD_ARGS, "create refuses NULL"); - return g_failed ? 1 : 0; -} - -static uint32_t tl_reps = 1; /* --tl-reps: stamped tokens for the timeline (more than 1: the first is dropped, medians printed) */ - -static int chip_run(uint32_t layers, uint64_t mask, uint32_t reps) { - Model m; - const uint32_t vocab = 248320u; - if (model_build(&m, layers, mask, vocab) != 0) { CHECK(0, "model build"); return 1; } - printf("model: %u layers (%u GDN, %u attention, mask 0x%" PRIx64 "), vocab %u\n", layers, m.n_gdn, m.n_attn, mask, vocab); - static Out A[TOKENS], C[TOKENS], B, M; - /* A first: it also warms every kernel the record paths need */ - for (uint32_t t = 0; t < TOKENS; t++) if (baseline_token(&m, m.x0[t], t, &A[t]) != 0) { CHECK(0, "baseline token %u", t); return 1; } - OmegaGpuQ38Graph *g = NULL; - if (graph_build(&m, &g) != 0) { CHECK(0, "graph build"); return 1; } - OmegaGpuDecodeGraphStats st; - for (uint32_t t = 0; t < TOKENS; t++) { - if (graph_token(g, &m, m.x0[t], t, &C[t], &st) != 0) { CHECK(0, "graph token %u", t); return 1; } - const double ref = maxabs(A[t].logits, vocab), dl = maxdiff(A[t].logits, C[t].logits, vocab); - const double xref = maxabs(A[t].x, H), dx = maxdiff(A[t].x, C[t].x, H); - CHECK(C[t].token == A[t].token, "token %u: graph %u == baseline %u", t, C[t].token, A[t].token); - CHECK(dl <= TOL_REL * ref, "token %u: logits max diff %.3g <= %.0e * %.3g", t, dl, TOL_REL, ref); - CHECK(dx <= TOL_REL * xref, "token %u: x max diff %.3g <= %.0e * %.3g", t, dx, TOL_REL, xref); - CHECK(st.launches == m.n_gdn * 9u + m.n_attn * 10u + 4u && st.submits == 1u, "token %u: %u launches in %u submit", t, st.launches, st.submits); - } - /* B: flush_each over the same three tokens from a reset state, bit-identical to C */ - if (state_reset(&m) != 0) { CHECK(0, "state reset"); return 1; } - omega_gpu_q38_graph_set_flush_each(g, 1); - int bsame = 1; - for (uint32_t t = 0; t < TOKENS; t++) { - if (graph_token(g, &m, m.x0[t], t, &B, &st) != 0) { CHECK(0, "flush_each token %u", t); return 1; } - if (memcmp(B.x, C[t].x, sizeof B.x) || memcmp(B.logits, C[t].logits, vocab * 4u) || B.token != C[t].token) bsame = 0; - } - omega_gpu_q38_graph_set_flush_each(g, 0); - CHECK(bsame, "flush_each == one list, bit for bit, all %u tokens", TOKENS); - /* read_buf: x from the host-visible buffer; gu and act from the GPU-cached one (a chip copy into the staging region first). - * act = silu(gu[c]) * gu[I + c] * 2^64 (the last layer's SwiGLU) ties the two copies together. */ - { - static float rx[H], rgu[2 * I], ract[I], rgu100[100]; - const int r1 = omega_gpu_q38_graph_read_buf(g, OMEGA_GPU_Q38_BUF_X, rx, H), r2 = omega_gpu_q38_graph_read_buf(g, OMEGA_GPU_Q38_BUF_GU, rgu, 2 * I); - const int r3 = omega_gpu_q38_graph_read_buf(g, OMEGA_GPU_Q38_BUF_ACT, ract, I), r4 = omega_gpu_q38_graph_read_buf(g, OMEGA_GPU_Q38_BUF_GU, rgu100, 100); - CHECK(r1 == 0 && r2 == 0 && r3 == 0 && r4 == 0, "read_buf x, gu, act, gu[0..100): rc %d %d %d %d", r1, r2, r3, r4); - CHECK(memcmp(rx, B.x, sizeof rx) == 0, "read_buf x == read x, bit for bit"); - CHECK(memcmp(rgu100, rgu, sizeof rgu100) == 0, "read_buf of 100 values == the first 100 of the whole row"); - double worst = 0, amax = 0; - for (uint32_t c = 0; c < I; c++) { - const double v = rgu[c], want = v / (1.0 + exp(-v)) * (double)rgu[I + c] * 0x1p64; - if (fabs(want) > amax) amax = fabs(want); - if (fabs(want - ract[c]) > worst) worst = fabs(want - ract[c]); - } - CHECK(amax > 0 && worst <= 1e-5 * amax, "read_buf act == silu(gu) * up * 2^64 from read_buf gu: worst %.3g of %.3g", worst, amax); - } - /* negative controls: each graph mutant must fail the A comparison on some token */ - const char *mname[5] = { "", "swiglu up half -1", "gather index +1", "gate dropped", "post-norm weight dropped" }; - for (int mu = 1; mu <= 4; mu++) { - if (state_reset(&m) != 0) return 1; - omega_gpu_q38_graph_test_set_mutant(g, mu); - int caught = 0; - for (uint32_t t = 0; t < TOKENS; t++) { - if (graph_token(g, &m, m.x0[t], t, &M, &st) != 0) { caught = 1; break; } - if (maxdiff(A[t].x, M.x, H) > TOL_REL * maxabs(A[t].x, H)) caught = 1; - } - CHECK(caught, "mutant %d (%s) caught", mu, mname[mu]); - } - omega_gpu_q38_graph_test_set_mutant(g, 0); - /* timing: reps tokens at position 2 over the reset state (the time, not the values, is measured here) */ - uint64_t *chip = calloc(reps, 8), *tot = calloc(reps, 8); - if (!chip || !tot) return 1; - for (uint32_t r = 0; r < reps; r++) { - if (state_reset(&m) != 0 || graph_token(g, &m, m.x0[0], 2, &M, &st) != 0) { CHECK(0, "timed token %u", r); return 1; } - chip[r] = st.chip_ns; tot[r] = st.total_ns; - } - printf("timing: %u reps, median chip %.1f us, median total %.1f us per token (%u layers)\n", reps, median_u64(chip, reps) / 1e3, median_u64(tot, reps) / 1e3, layers); - free(chip); free(tot); - /* timeline: tl_reps stamped tokens (first one dropped when there are more), median GPU time per launch kind, and the - * weight bytes each kind streams so the line reads as GB/s (activations and state are not counted) */ - { - static uint64_t stp[OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1]; static uint8_t kd[OMEGA_GPU_CMDLIST_MAX_LAUNCHES]; - uint64_t wb[OMEGA_GPU_Q38_K_COUNT] = { 0 }; uint32_t e, n8, k8; - for (uint32_t l = 0; l < m.layers; l++) { - const OmegaGpuFp8Tensor *f[4] = { m.L[l].mix, m.L[l].o, m.L[l].gu, m.L[l].dn }; - const unsigned fk[4] = { OMEGA_GPU_Q38_K_MIX, OMEGA_GPU_Q38_K_O, OMEGA_GPU_Q38_K_GATE_UP, OMEGA_GPU_Q38_K_DOWN }; - for (int j = 0; j < 4; j++) if (f[j]) { omega_gpu_fp8_tensor_shape(f[j], &e, &n8, &k8); wb[fk[j]] += (uint64_t)n8 * k8; } - if (m.L[l].ab) { omega_gpu_bf16_tensor_shape(m.L[l].ab, &n8, &k8); wb[OMEGA_GPU_Q38_K_AB] += 2ull * n8 * k8; } - } - omega_gpu_bf16_tensor_shape(m.lm, &n8, &k8); wb[OMEGA_GPU_Q38_K_LM_HEAD] = 2ull * n8 * k8; - if (m.lm8) wb[OMEGA_GPU_Q38_K_LM_HEAD] /= 2u; /* FP8 head: one byte per weight */ - const uint32_t tr = tl_reps > 1 ? tl_reps - 1 : 1; - uint64_t *ns = calloc((size_t)tr * (OMEGA_GPU_Q38_K_COUNT + 1), 8), col[256]; - uint32_t cnt[OMEGA_GPU_Q38_K_COUNT] = { 0 }; - if (!ns || tr > 256) { CHECK(0, "timeline buffers (tl-reps <= 257)"); return 1; } - omega_gpu_q38_graph_set_stamps(g, 1); - for (uint32_t r = 0; r < tl_reps; r++) { - if (state_reset(&m) != 0 || graph_token(g, &m, m.x0[0], 2, &M, &st) != 0) { CHECK(0, "stamped token %u", r); return 1; } - int n = omega_gpu_q38_graph_stamps(g, stp, kd, OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1); - CHECK(n == (int)st.launches, "timeline %u: %d stamped launches", r, n); - if (tl_reps > 1 && r == 0) continue; - uint64_t *row = ns + (size_t)(tl_reps > 1 ? r - 1 : 0) * (OMEGA_GPU_Q38_K_COUNT + 1); - memset(cnt, 0, sizeof cnt); - for (int i = 0; i < n; i++) { row[kd[i]] += stp[i + 1] - stp[i]; cnt[kd[i]]++; } - if (n > 0) row[OMEGA_GPU_Q38_K_COUNT] = stp[n] - stp[0]; - } - omega_gpu_q38_graph_set_stamps(g, 0); - for (unsigned k = 0; k <= OMEGA_GPU_Q38_K_COUNT; k++) { - if (k < OMEGA_GPU_Q38_K_COUNT && !cnt[k]) continue; - uint64_t lo = UINT64_MAX, hi = 0; - for (uint32_t r = 0; r < tr; r++) { col[r] = ns[(size_t)r * (OMEGA_GPU_Q38_K_COUNT + 1) + k]; if (col[r] < lo) lo = col[r]; if (col[r] > hi) hi = col[r]; } - const double med = (double)median_u64(col, tr); - if (k == OMEGA_GPU_Q38_K_COUNT) { printf("timeline span %.1f us (median of %u, min %.1f max %.1f)\n", med / 1e3, tr, lo / 1e3, hi / 1e3); break; } - printf("timeline %-8s %3u launches %9.1f us (min %.1f max %.1f)", omega_gpu_q38_graph_kind_name((uint8_t)k), cnt[k], med / 1e3, lo / 1e3, hi / 1e3); - if (wb[k]) printf(" %12" PRIu64 " weight B %6.1f GB/s", wb[k], (double)wb[k] / med); - printf("\n"); - } - free(ns); - } - omega_gpu_q38_graph_free(g); - return g_failed ? 1 : 0; -} - -int main(int argc, char **argv) { - int host = 0; uint32_t layers = 2, reps = 10; uint64_t mask = 0x2; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--layers") == 0 && i + 1 < argc) layers = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--mask") == 0 && i + 1 < argc) mask = strtoull(argv[++i], NULL, 0); - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--tl-reps") == 0 && i + 1 < argc) tl_reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--fp8-head") == 0) g_fp8_head = 1; - /* tuning knobs for sweeps (process-wide, before any kernel is built): FP8 GEMV lane_bytes,rows,warps / CTA budget, - * bf16 GEMV (lm_head, a|b) rows,warps,depth / CTA budget */ - else if (strcmp(argv[i], "--fp8-shape") == 0 && i + 1 < argc) { unsigned a, b, c; if (sscanf(argv[++i], "%u,%u,%u", &a, &b, &c) != 3) return 2; omega_gpu_fp8_set_shape(a, b, c); } - else if (strcmp(argv[i], "--fp8-ctas") == 0 && i + 1 < argc) omega_gpu_fp8_set_cta_budget((uint32_t)atoi(argv[++i])); - else if (strcmp(argv[i], "--bf16-shape") == 0 && i + 1 < argc) { unsigned a, b, c; if (sscanf(argv[++i], "%u,%u,%u", &a, &b, &c) != 3) return 2; omega_gpu_bf16_set_shape(a, b, c); } - else if (strcmp(argv[i], "--bf16-ctas") == 0 && i + 1 < argc) omega_gpu_bf16_set_cta_budget((uint32_t)atoi(argv[++i])); - else { printf("usage: %s [--host-only] [--layers N (<= 8)] [--mask M] [--reps R] [--tl-reps T (<= 257)]\n", argv[0]); return 2; } - } - if (layers == 0 || layers > 8 || reps == 0 || tl_reps == 0 || tl_reps > 257) { printf("layers 1..8, reps >= 1, tl-reps 1..257\n"); return 2; } - int rc = host ? host_only() : chip_run(layers, mask, reps); - printf("gpu_q38_graph_test%s: %d checks, %d failed: %s\n", host ? " (host-only)" : "", g_checks, g_failed, rc ? "FAIL" : "PASS"); - return rc; -} diff --git a/tests/gpu_qgemm_test.c b/tests/gpu_qgemm_test.c deleted file mode 100644 index 15dd5cb87..000000000 --- a/tests/gpu_qgemm_test.c +++ /dev/null @@ -1,494 +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. - */ - -/* gpu_qgemm_test.c (OWN-30B L1 GEMM, W-L1G, 2026-10-14): the native FP8 prefill path (omega_blackwell_codegen_qg.h). - * --host-only reference self-checks - * --sim kernels in the warp simulator bit-identical to the C reference; mutants caught (a simulator error is a FAIL) - * --chip (under flock /tmp/aien-gb10.lock) through the device API: bit-identical to the reference, mutants caught, - * medians at --tokens - * Verdict line last: "GPU_QGEMM: PASS|FAIL". */ -#include "omega_blackwell_codegen_qg.h" -#include "omega_gpu_prefill.h" -#include "omega_gpu_fp8_api.h" -#include "bw_warp_sim_tc.h" -#include -#include -#include -#include - -static uint64_t rng = 0x243f6a8885a308d3ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -/* ---------------- quantiser reference (header semantics) ---------------- */ -static void pq_ref(const float *x, uint32_t k, uint8_t *q, float *s, int mutant) { - for (uint32_t b = 0; b < k / 128; b++) { - float m = ldexpf(1.0f, -100); - if (mutant == 1) { /* lane-local amax: lane l sees elements 4l..4l+3 only (scale per lane; the reference keeps lane 31's) */ - for (uint32_t l = 0; l < 32; l++) { float ml = ldexpf(1.0f, -100); for (int j = 0; j < 4; j++) ml = fmaxf(ml, fabsf(x[128 * b + 4 * l + j])); if (l == 31) m = ml; } - } else for (uint32_t j = 0; j < 128; j++) m = fmaxf(m, fabsf(x[128 * b + j])); - uint32_t mb = f2u(m), E = mb >> 23, M = mb & 0x7fffff, c = mutant == 2 ? 0 : (M + 0x1fffff) >> 23; - float scale = u2f((E + c - 8) << 23), inv = u2f((262 - E - c) << 23); - s[b] = scale; - for (uint32_t j = 0; j < 128; j++) q[128 * b + j] = qm_e4m3_rne_sat(x[128 * b + j] * inv); - } -} -static float rand_act(void) { - float v = ((float)(rnd() & 0xffffff) / 16777216.0f) * 2.0f - 1.0f; - int r = rnd() % 32; if (r == 0) v *= 300.0f; else if (r == 1) v *= 1e-3f; else if (r == 2) v = 0.0f; - return v; -} -static uint16_t bf16_rn(float f) { uint32_t u = f2u(f); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } -/* rows x k activations; row 3 all zero, row 5 one huge outlier; bf16 copy when in_type is BF16 */ -static void make_x(uint32_t rows, uint32_t k, uint32_t in_type, float *x, uint16_t *xb) { - for (size_t i = 0; i < (size_t)rows * k; i++) x[i] = rand_act(); - if (rows > 3) memset(x + 3 * (size_t)k, 0, k * 4); - if (rows > 5) x[5 * (size_t)k + 77] = 3.0e4f; - if (in_type == OMEGA_QG_IN_BF16) for (size_t i = 0; i < (size_t)rows * k; i++) { xb[i] = bf16_rn(x[i]); x[i] = u2f((uint32_t)xb[i] << 16); } -} -static size_t pq_compare(const float *x, uint32_t rows, uint32_t k, const uint8_t *q, const float *s, int mutant) { - size_t bad = 0; uint8_t *rq = malloc(k); float *rs = malloc(k / 128 * 4); - for (uint32_t r = 0; r < rows; r++) { - pq_ref(x + (size_t)r * k, k, rq, rs, mutant); - for (uint32_t j = 0; j < k; j++) if (rq[j] != q[(size_t)r * k + j]) bad++; - for (uint32_t b = 0; b < k / 128; b++) if (f2u(rs[b]) != f2u(s[(size_t)r * (k / 128) + b])) bad++; - } - free(rq); free(rs); return bad; -} - -static int pq_host(void) { - int fail = 0; - /* scale choice: amax / scale in (224, 448] for normal amax */ - for (int i = 0; i < 100000; i++) { - float x[128]; for (int j = 0; j < 128; j++) x[j] = rand_act() * ldexpf(1.0f, (int)(rnd() % 40) - 20); - uint8_t q[128]; float s[1]; pq_ref(x, 128, q, s, 0); - float m = 0; for (int j = 0; j < 128; j++) m = fmaxf(m, fabsf(x[j])); - if (m > 0 && !(m / s[0] <= 448.0f && m / s[0] > 224.0f)) { if (fail < 3) printf("scale out of range: amax %g scale %g\n", m, s[0]); fail++; } - double err = 0; for (int j = 0; j < 128; j++) { double d = fabs((double)qm_e4m3(q[j]) * s[0] - x[j]); if (d > err) err = d; } - if (m > 0 && err > m * (1.0 / 16 + 1e-6)) { if (fail < 3) printf("quantisation error %g vs amax %g\n", err, m); fail++; } - } - printf("quantiser reference: %s\n", fail ? "FAIL" : "PASS (amax/scale in (224, 448], error within half an e4m3 ulp)"); - return fail; -} - -static int pq_sim_one(uint32_t k, uint32_t in_type, uint32_t groups, uint32_t rows, int mutant, size_t *bad_out, char *msg, size_t msgn) { - OmegaPqSpec sp = { k, in_type, mutant, groups }; - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_pq_prog(&sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - float *x = malloc((size_t)rows * k * 4); uint16_t *xb = malloc((size_t)rows * k * 2); - uint8_t *q = malloc((size_t)rows * k); float *s = malloc((size_t)rows * (k / 128) * 4); - make_x(rows, k, in_type, x, xb); - memset(q, 0xee, (size_t)rows * k); memset(s, 0xee, (size_t)rows * (k / 128) * 4); - static WsSim ws; memset(&ws, 0, sizeof ws); - ws.p = &prog; ws.threads = 32u * (groups ? groups : k / 128); - const void *xin = in_type == OMEGA_QG_IN_F32 ? (const void *)x : (const void *)xb; - uint64_t a[3] = { (uintptr_t)xin, (uintptr_t)q, (uintptr_t)s }; - for (int i = 0; i < 3; i++) { ws.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; ws.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - ws.ranges[0].lo = (uintptr_t)xin; ws.ranges[0].hi = (uintptr_t)xin + (size_t)rows * k * (in_type == OMEGA_QG_IN_F32 ? 4 : 2); - ws.ranges[1].lo = (uintptr_t)q; ws.ranges[1].hi = (uintptr_t)q + (size_t)rows * k; - ws.ranges[2].lo = (uintptr_t)s; ws.ranges[2].hi = (uintptr_t)s + (size_t)rows * (k / 128) * 4; - ws.nranges = 3; - int err = ws_run(&ws, rows, groups ? k / 128 / groups : 1); - if (err) snprintf(msg, msgn, "simulator %.150s", ws.msg); - *bad_out = err ? 0 : pq_compare(x, rows, k, q, s, 0); - free(x); free(xb); free(q); free(s); - return err ? -1 : 0; -} -static int pq_sim(void) { - int fail = 0; char msg[200]; - /* groups > 0: one row split over k / (128 groups) CTAs (the Qwen3.8 widths 5120, 6144, 17408) */ - static const struct { uint32_t k, in_type, groups; } cs[] = { { 2048, OMEGA_QG_IN_F32, 0 }, { 768, OMEGA_QG_IN_BF16, 0 }, { 4096, OMEGA_QG_IN_F32, 0 }, { 128, OMEGA_QG_IN_BF16, 0 }, - { 5120, OMEGA_QG_IN_F32, 20 }, { 6144, OMEGA_QG_IN_BF16, 24 }, { 17408, OMEGA_QG_IN_BF16, 17 }, { 2048, OMEGA_QG_IN_F32, 4 } }; - for (size_t c = 0; c < sizeof cs / sizeof cs[0]; c++) { - size_t bad = 0; int rc = pq_sim_one(cs[c].k, cs[c].in_type, cs[c].groups, 9, 0, &bad, msg, sizeof msg); - printf("sim quantiser k %u %s groups %u: %s, %zu differ\n", cs[c].k, cs[c].in_type ? "bf16" : "f32", cs[c].groups, rc ? msg : "ran", bad); - if (rc || bad) fail++; - } - for (int m = 1; m <= 3; m++) { - size_t bad = 0; int rc = pq_sim_one(m == 3 ? 5120 : 2048, OMEGA_QG_IN_F32, m == 3 ? 20 : 0, 9, m, &bad, msg, sizeof msg); - printf("sim quantiser mutant %d: %s\n", m, rc ? msg : bad ? "caught" : "NOT CAUGHT"); - if (rc || !bad) fail++; - } - return fail; -} - -static int pq_chip(uint32_t tokens, int reps) { - int fail = 0; - /* k > 4096 runs the split-row form (omega_gpu_pf_quant picks groups); its mutant drops the ctaid.y offset */ - static const struct { uint32_t k, in_type, rows_mul; } cs[] = { { 2048, OMEGA_QG_IN_F32, 1 }, { 768, OMEGA_QG_IN_BF16, 8 }, { 5120, OMEGA_QG_IN_F32, 1 }, - { 6144, OMEGA_QG_IN_BF16, 1 }, { 17408, OMEGA_QG_IN_BF16, 1 } }; - for (size_t c = 0; c < sizeof cs / sizeof cs[0]; c++) { - const uint32_t k = cs[c].k, rows = tokens * cs[c].rows_mul, eb = cs[c].in_type == OMEGA_QG_IN_F32 ? 4 : 2; - float *x = malloc((size_t)rows * k * 4); uint16_t *xb = malloc((size_t)rows * k * 2); - uint8_t *q = malloc((size_t)rows * k); float *s = malloc((size_t)rows * (k / 128) * 4); - make_x(rows, k, cs[c].in_type, x, xb); - OmegaGpuMem xd = { 0 }, qd = { 0 }, sd = { 0 }; - const size_t xbytes = (size_t)rows * k * eb, qbytes = (size_t)rows * k, sbytes = ((size_t)rows * (k / 128) * 4 + 15) & ~(size_t)15; - int rc = omega_gpu_pf_alloc_dev(xbytes, &xd); - if (!rc) rc = omega_gpu_pf_alloc_dev(qbytes, &qd); - if (!rc) rc = omega_gpu_pf_alloc_dev(sbytes, &sd); - if (!rc) rc = omega_gpu_pf_upload(&xd, 0, cs[c].in_type == OMEGA_QG_IN_F32 ? (const void *)x : (const void *)xb, xbytes); - uint64_t ns[32] = { 0 }; if (reps > 32) reps = 32; - for (int r = 0; r < reps && !rc; r++) rc = omega_gpu_pf_quant(k, cs[c].in_type, rows, xd.va, qd.va, sd.va, &ns[r]); - if (!rc) rc = omega_gpu_pf_download(&qd, 0, q, qbytes); - if (!rc) { float *st = malloc(sbytes); rc = omega_gpu_pf_download(&sd, 0, st, sbytes); memcpy(s, st, (size_t)rows * (k / 128) * 4); free(st); } - if (rc) { printf("quantiser chip k %u: %s (%s)\n", k, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); fail++; } - else { - size_t bad = pq_compare(x, rows, k, q, s, 0); - qsort(ns, reps, 8, cmp_u64); - printf("QUANT chip k %u %s rows %u: %zu differ from the reference; median %.3f ms (%.0f GB/s moved)\n", k, cs[c].in_type ? "bf16" : "f32", rows, bad, - ns[reps / 2] / 1e6, (double)(xbytes + qbytes + sbytes) / ns[reps / 2]); - if (bad) fail++; - const int mut = k > 4096 ? 3 : 1; - /* junk-fill the output first: mutant 3 rewrites groups 0 .. G-1 with right values and leaves the rest alone, - so stale results of the good run would hide it */ - memset(q, 0xee, qbytes); - int mrc = omega_gpu_pf_upload(&qd, 0, q, qbytes); - omega_gpu_pf_quant_test_set_mutant(mut); - if (!mrc) mrc = omega_gpu_pf_quant(k, cs[c].in_type, rows, xd.va, qd.va, sd.va, NULL); - omega_gpu_pf_quant_test_set_mutant(0); - if (!mrc) mrc = omega_gpu_pf_download(&qd, 0, q, qbytes); - size_t mb = mrc ? 0 : pq_compare(x, rows > 64 ? 64 : rows, k, q, s, 0); - printf("QUANT chip k %u mutant %d: %s\n", k, mut, mrc ? "launch failed" : mb ? "caught" : "NOT CAUGHT"); - if (mrc || !mb) fail++; - } - omega_gpu_pf_free(&xd); omega_gpu_pf_free(&qd); omega_gpu_pf_free(&sd); - free(x); free(xb); free(q); free(s); - } - return fail; -} - -/* ---------------- grouped GEMM on QMMA ---------------- */ -static const QmmaModel GB10Q = { 32, 26, 0, 2, 0 }; /* chip-exact, evidence OWN30B-L1G-QMMA-PFGEMM-c742aa13 */ -typedef struct { - uint32_t E, n, k, M, xr, layout, direct, pad; - uint8_t *w, *xq; /* weights [E][n][k] (checkpoint order, read in place), quantised activations (xr + pad rows) */ - uint16_t *sbf; /* scale_inv bf16 */ - float *swf, *xs, *x; /* GEMV-tensor scale table [E][n/128][KB] f32 * 2^56, activation scales (xr + pad rows), true activations */ - uint32_t *eid, *src, *counts; -} QProb; -static uint8_t rand_e4m3(void) { for (;;) { uint8_t c = (uint8_t)rnd(); if ((c & 0x7f) != 0x7f) return c; } } -static void qprob_make(QProb *p, uint32_t E, uint32_t n, uint32_t k, uint32_t M, uint32_t xr, uint32_t layout, uint32_t direct, uint32_t pad) { - memset(p, 0, sizeof *p); - p->E = E; p->n = n; p->k = k; p->M = M; p->xr = direct ? M : xr; p->layout = layout; p->direct = direct; p->pad = pad; - const uint32_t KB = k / 128, XR = p->xr + pad; - const size_t wn = (size_t)E * n * k, sn = (size_t)E * (n / 128) * KB; - p->w = malloc(wn); p->sbf = malloc(sn * 2); p->swf = malloc(sn * 4); - p->x = calloc((size_t)XR * k, 4); p->xq = calloc((size_t)XR * k, 1); p->xs = malloc((size_t)XR * KB * 4); - p->eid = malloc(M * 4); p->src = malloc(M * 4); p->counts = calloc(E, 4); - for (size_t i = 0; i < wn; i++) p->w[i] = rand_e4m3(); - for (size_t i = 0; i < sn; i++) { float s = ldexpf(1.0f + (float)(rnd() & 127) / 128.0f, -(int)(rnd() % 12) - 4); p->sbf[i] = (uint16_t)(f2u(s) >> 16); } - if (omega_fp8_pack_scales(p->sbf, sn, p->swf, 0) != 0) { printf("scale pack refused\n"); exit(2); } - for (size_t i = 0; i < (size_t)p->xr * k; i++) p->x[i] = rand_act(); - if (p->xr > 3) memset(p->x + 3 * (size_t)k, 0, k * 4); - for (uint32_t r = 0; r < XR; r++) pq_ref(p->x + (size_t)r * k, k, p->xq + (size_t)r * k, p->xs + (size_t)r * KB, 0); - uint32_t i = 0; - for (uint32_t e = 0; e < E && i < M; e++) { uint32_t c = e + 1 == E ? M - i : (uint32_t)((uint64_t)(rnd() % 2000) * 2 * M / (2000ull * E)); if (c > M - i) c = M - i; for (uint32_t q = 0; q < c; q++) p->eid[i + q] = e; p->counts[e] = c; i += c; } - for (uint32_t q = 0; q < M; q++) p->src[q] = direct ? q : rnd() % p->xr; -} -static void qprob_free(QProb *p) { free(p->w); free(p->xq); free(p->sbf); free(p->swf); free(p->xs); free(p->x); free(p->eid); free(p->src); free(p->counts); } - -/* the kernel's arithmetic for output row i, physical column c */ -static float qemu_phys(const QProb *p, uint32_t i, uint32_t c) { - const uint32_t k = p->k, KB = k / 128, e = p->eid[i], s = p->src[i]; - /* physical column c -> weight row: F32 c; SWIGLU gate 8G + h % 8 (h < 8) or up I + 8G + h % 8, G = c / 16, h = c % 16 */ - const uint32_t wrow = p->layout == OMEGA_GPU_PF_PLAIN ? c : 8 * (c / 16) + c % 8 + (c % 16 >= 8 ? p->n / 2 : 0); - const uint8_t *xr = p->xq + (size_t)s * k, *wr = p->w + ((size_t)e * p->n + wrow) * k; - const float *swt = p->swf + ((size_t)e * (p->n / 128) + wrow / 128) * KB; - float acc = 0.0f; - for (uint32_t kb = 0; kb < KB; kb++) { - const float sc = p->xs[(size_t)s * KB + kb] * (swt[kb] * 0x1p-56f); - for (uint32_t h = 0; h < 2; h++) { - float T = 0.0f; - for (uint32_t v = 0; v < 2; v++) { - float av[32], bv[32]; - for (uint32_t t = 0; t < 4; t++) for (uint32_t j = 0; j < 4; j++) { - const uint32_t o = 128 * kb + 64 * h + 16 * t + 8 * v + j; - av[4 * t + j] = qm_e4m3(xr[o]); bv[4 * t + j] = qm_e4m3(wr[o]); - av[16 + 4 * t + j] = qm_e4m3(xr[o + 4]); bv[16 + 4 * t + j] = qm_e4m3(wr[o + 4]); - } - T = qm_dot32(&GB10Q, av, bv, T); - } - acc = fmaf(T, sc, acc); - } - } - return acc; -} -/* the kernel's SwiGLU epilogue (omega_blackwell_codegen_qg.c: FMNMX t-cap, MUFU.EX2, MUFU.RCP). Both MUFU results go - * through the chip's flush rule (tests/bw_mufu_ftz.h, omega #462). Not observable with the t-cap: t <= 125 keeps - * 1 / (2^t + 1) >= 2^-125 normal, and an EX2 result below 2^-126 (t < -126) rounds to the same d = 1.0 after the +1 as - * its flushed zero; qg_host checks this bit for bit. Removing the cap (issue #462) is a separate chip-gated change. */ -static uint16_t qswiglu_bits(float g, float u) { - float t = fminf(g * u2f(0xbfb8aa3bu), 125.0f), ex = ws_mufu_ex2(t), d = ex + 1.0f, r = ws_mufu_rcp(d), o = g * r; - o = o * u; - return bf16_rn(o); -} -static void qemu_row(const QProb *p, uint32_t i, float *yf, uint16_t *ya) { - if (p->layout == OMEGA_GPU_PF_PLAIN) { for (uint32_t c = 0; c < p->n; c++) yf[c] = qemu_phys(p, i, c); return; } - for (uint32_t a = 0; a < p->n / 2; a++) { uint32_t G = a / 8, m = a % 8; ya[a] = qswiglu_bits(qemu_phys(p, i, 16 * G + m), qemu_phys(p, i, 16 * G + 8 + m)); } -} -/* double oracle on the ORIGINAL weights and the dequantised activations: logical output col (PLAIN) or gate/up of index a */ -static double qoracle(const QProb *p, uint32_t i, uint32_t col, double *mag) { - const uint32_t k = p->k, KB = k / 128, e = p->eid[i], s = p->src[i]; - double acc = 0, m = 0; - for (uint32_t j = 0; j < k; j++) { - const double sw = u2f((uint32_t)p->sbf[((size_t)e * (p->n / 128) + col / 128) * KB + j / 128] << 16); - const double t = (double)qm_e4m3(p->w[((size_t)e * p->n + col) * k + j]) * sw * qm_e4m3(p->xq[(size_t)s * k + j]) * p->xs[(size_t)s * KB + j / 128]; - acc += t; m += fabs(t); - } - *mag = m; return acc; -} - -typedef struct { uint64_t w_va, s_va; uint32_t row0, cnt; uint64_t pad; } QTile; -static uint32_t qmake_tiles(const QProb *p, uint32_t bm, QTile *t) { - uint32_t nt = 0, row = 0; const uint32_t KB = p->k / 128; - for (uint32_t e = 0; e < p->E; e++) { for (uint32_t r = 0; r < p->counts[e]; r += bm) { - t[nt].w_va = (uintptr_t)(p->w + (size_t)e * p->n * p->k); t[nt].s_va = (uintptr_t)(p->swf + (size_t)e * (p->n / 128) * KB); - t[nt].row0 = row + r; t[nt].cnt = p->counts[e] - r < bm ? p->counts[e] - r : bm; t[nt].pad = 0; nt++; } row += p->counts[e]; } - return nt; -} -static size_t qcompare(const QProb *p, const void *y, const uint32_t *rows, uint32_t nrows, int tol_ulp, size_t *ulp1) { - size_t bad = 0; if (ulp1) *ulp1 = 0; - float *yf = malloc(p->n * 4); uint16_t *ya = malloc(p->n); - for (uint32_t q = 0; q < nrows; q++) { - const uint32_t i = rows[q]; qemu_row(p, i, yf, ya); - if (p->layout == OMEGA_GPU_PF_PLAIN) { const uint32_t *g = (const uint32_t *)y + (size_t)i * p->n; for (uint32_t c = 0; c < p->n; c++) if (g[c] != f2u(yf[c])) { if (getenv("PFDBG") && bad < 6) printf(" row %u col %u got %.9g want %.9g\n", i, c, u2f(g[c]), yf[c]); bad++; } } - else { const uint16_t *g = (const uint16_t *)y + (size_t)i * (p->n / 2); - for (uint32_t c = 0; c < p->n / 2; c++) if (g[c] != ya[c]) { int d = abs((int)g[c] - (int)ya[c]); if (d <= tol_ulp && ((g[c] ^ ya[c]) & 0x8000) == 0) { if (ulp1) (*ulp1)++; } else { if (getenv("PFDBG") && bad < 12) { const uint32_t G = c / 8, mm = c % 8; printf(" row %u act %u got %04x want %04x (g %.9g u %.9g)\n", i, c, g[c], ya[c], qemu_phys(p, i, 16 * G + mm), qemu_phys(p, i, 16 * G + 8 + mm)); } bad++; } } } - } - free(yf); free(ya); - return bad; -} - -/* omega #462: with the t-cap the MUFU flush never changes a SwiGLU output bit. Compare qswiglu_bits against the IEEE - * form over every g in [80, 110] and [-110, -80] (the EX2-subnormal window t in (-150, -126] and the cap t = 125, both - * signs) plus a stride-65537 sample of all f32. Not a red test: there is no input for which the two differ. */ -static int qg_mufu_ftz_unobservable(void) { - uint64_t n = 0, diff = 0; - const float us[2] = { 1.0f, -3.0f }; - for (int pass = 0; pass < 3; pass++) { - uint64_t lo = pass == 0 ? f2u(80.0f) : pass == 1 ? f2u(-80.0f) : 0, hi = pass == 0 ? f2u(110.0f) : pass == 1 ? f2u(-110.0f) : 0xffffffffull, step = pass == 2 ? 65537 : 1; - for (uint64_t b = lo; b <= hi; b += step) { - float g = u2f((uint32_t)b); - if (isnan(g)) continue; - float t = fminf(g * u2f(0xbfb8aa3bu), 125.0f), r = 1.0f / (exp2f(t) + 1.0f); - for (int k = 0; k < 2; k++) { n++; if (bf16_rn((g * r) * us[k]) != qswiglu_bits(g, us[k])) diff++; } - } - } - printf("%s qgemm SwiGLU: MUFU flush vs IEEE, %llu inputs, %llu differ (t-cap keeps it unobservable, #462)\n", diff ? "FAIL" : "PASS", (unsigned long long)n, (unsigned long long)diff); - return diff ? 1 : 0; -} -static int qg_host(void) { - int fail = qg_mufu_ftz_unobservable(); - for (uint32_t layout = 0; layout < 3; layout += 2) { - QProb p; qprob_make(&p, 3, 256, 384, 40, 17, layout, 0, 0); - double worst = 0; - for (uint32_t i = 0; i < p.M; i += 3) { - if (layout == OMEGA_GPU_PF_PLAIN) for (uint32_t c = 0; c < p.n; c++) { double m, o = qoracle(&p, i, c, &m); double d = fabs(qemu_phys(&p, i, c) - o) / (m + 1e-30); if (d > worst) worst = d; } - else for (uint32_t a = 0; a < p.n / 2; a++) { uint32_t G = a / 8, mm = a % 8; double m1, m2; - double og = qoracle(&p, i, a, &m1), ou = qoracle(&p, i, p.n / 2 + a, &m2); - double dg = fabs(qemu_phys(&p, i, 16 * G + mm) - og) / (m1 + 1e-30), du = fabs(qemu_phys(&p, i, 16 * G + 8 + mm) - ou) / (m2 + 1e-30); - if (dg > worst) worst = dg; - if (du > worst) worst = du; } - } - const int ok = worst < 1e-6; - printf("qgemm emulation vs double oracle (%s): worst error %.3g of the sum of |terms| %s\n", layout ? "swiglu_nat" : "plain", worst, ok ? "PASS" : "FAIL"); - if (!ok) fail++; - qprob_free(&p); - } - return fail; -} - -static int qg_sim_run(const QProb *p, const OmegaQgSpec *sp, int order, void *y, char *msg, size_t msgn) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_qgemm_prog(sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused (spec_ok %d, insns %zu)", omega_qg_spec_ok(sp), prog.count); return -1; } - const uint32_t bm = 16u * sp->rt, span = omega_qg_span(sp), KB = p->k / 128; - QTile *tiles = calloc(p->M + 1, sizeof *tiles); - const uint32_t nt = qmake_tiles(p, bm, tiles); - uint32_t *ridx = malloc((p->M + bm) * 4); for (uint32_t i = 0; i < p->M + bm; i++) ridx[i] = i < p->M ? p->src[i] : 0; - const size_t ob = p->layout == OMEGA_GPU_PF_PLAIN ? 4 : 1, yb = (size_t)(p->M + bm) * p->n * ob; - memset(y, 0xee, yb); - uint8_t *smem = malloc(omega_qg_shared_bytes(sp)); - static WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * sp->warps; s.smem = smem; s.smem_bytes = omega_qg_shared_bytes(sp); s.order = order; - const uint64_t a[5] = { (uintptr_t)tiles, sp->direct ? 0 : (uintptr_t)ridx, (uintptr_t)p->xq, (uintptr_t)y, (uintptr_t)p->xs }; - for (int i = 0; i < 5; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - s.cbank[0x3a8 / 4] = p->n; - const size_t XR = p->xr + p->pad; - s.ranges[0].lo = (uintptr_t)tiles; s.ranges[0].hi = (uintptr_t)(tiles + nt); - s.ranges[1].lo = (uintptr_t)ridx; s.ranges[1].hi = (uintptr_t)(ridx + p->M + bm); - s.ranges[2].lo = (uintptr_t)p->xq; s.ranges[2].hi = (uintptr_t)(p->xq + XR * p->k); - s.ranges[3].lo = (uintptr_t)y; s.ranges[3].hi = (uintptr_t)y + (size_t)p->M * p->n * ob; - s.ranges[4].lo = (uintptr_t)p->w; s.ranges[4].hi = (uintptr_t)(p->w + (size_t)p->E * p->n * p->k); - s.ranges[5].lo = (uintptr_t)p->swf; s.ranges[5].hi = (uintptr_t)(p->swf + (size_t)p->E * (p->n / 128) * KB); - s.ranges[6].lo = (uintptr_t)p->xs; s.ranges[6].hi = (uintptr_t)(p->xs + XR * KB); - s.nranges = 7; - const int err = ws_run(&s, p->n / span, nt); - if (err) snprintf(msg, msgn, "simulator %.150s", s.msg); - free(tiles); free(ridx); free(smem); - return err ? -1 : 0; -} -static int qg_sim(void) { - int fail = 0; char msg[200]; - static const struct { uint32_t E, n, k, M, xr, layout, direct, rt, warps; } cs[] = { - { 3, 256, 384, 300, 120, OMEGA_GPU_PF_SWIGLU_NAT, 0, 4, 8 }, - { 3, 256, 256, 200, 0, OMEGA_GPU_PF_PLAIN, 1, 4, 8 }, - { 2, 256, 128, 150, 64, OMEGA_GPU_PF_PLAIN, 0, 4, 8 }, - { 2, 512, 1024, 140, 0, OMEGA_GPU_PF_SWIGLU_NAT, 1, 4, 8 }, - }; - for (size_t c = 0; c < sizeof cs / sizeof cs[0]; c++) { - const uint32_t bm = 16 * cs[c].rt; - QProb p; qprob_make(&p, cs[c].E, cs[c].n, cs[c].k, cs[c].M, cs[c].xr, cs[c].layout, cs[c].direct, bm); - OmegaQgSpec sp = { cs[c].k, cs[c].rt, cs[c].warps, cs[c].layout == OMEGA_GPU_PF_PLAIN ? OMEGA_QG_EPI_F32 : OMEGA_QG_EPI_SWIGLU, cs[c].direct, cs[c].n, 45, 0 }; - uint32_t *rows = malloc(p.M * 4); for (uint32_t i = 0; i < p.M; i++) rows[i] = i; - void *y = malloc((size_t)(p.M + bm) * p.n * 4); - for (int order = 0; order < 2; order++) { - const int rc = qg_sim_run(&p, &sp, order, y, msg, sizeof msg); - size_t ulp1 = 0, bad = rc ? 0 : qcompare(&p, y, rows, p.M, 0, &ulp1); - printf("sim qgemm case %zu (n %u k %u M %u %s %s rt %u warps %u) order %d: %s, %zu differ\n", c, p.n, p.k, p.M, cs[c].layout ? "swiglu" : "f32", - cs[c].direct ? "direct" : "indexed", cs[c].rt, cs[c].warps, order, rc ? msg : "ran", bad); - if (rc || bad) fail++; - } - if (c == 0 || c == 1) for (int m = 1; m <= 4; m++) { - OmegaQgSpec ms = sp; ms.mutant = m; - const int rc = qg_sim_run(&p, &ms, 0, y, msg, sizeof msg); - const size_t bad = rc ? 0 : qcompare(&p, y, rows, p.M, 0, NULL); - printf("sim qgemm case %zu mutant %d: %s\n", c, m, rc ? msg : bad ? "caught" : "NOT CAUGHT"); - if (rc || !bad) fail++; - } - free(rows); free(y); qprob_free(&p); - } - return fail; -} - -static int g_cached; /* 1: weights in a GPU-cached device copy (GEMV layout), 0: read in place from the GEMV tensor */ -static int qg_chip_shape(const char *name, uint32_t tokens, int reps, int check_rows, int mutants) { - uint32_t E, n, k, M, xr, layout, direct; - if (!strcmp(name, "gateup")) { E = 128; n = 1536; k = 2048; M = tokens * 8; xr = tokens; layout = OMEGA_GPU_PF_SWIGLU_NAT; direct = 0; } - else if (!strcmp(name, "down")) { E = 128; n = 2048; k = 768; M = tokens * 8; xr = 0; layout = OMEGA_GPU_PF_PLAIN; direct = 1; } - else if (!strcmp(name, "qkv")) { E = 1; n = 5120; k = 2048; M = tokens; xr = tokens; layout = OMEGA_GPU_PF_PLAIN; direct = 0; } - else if (!strcmp(name, "o")) { E = 1; n = 2048; k = 4096; M = tokens; xr = tokens; layout = OMEGA_GPU_PF_PLAIN; direct = 0; } - /* Qwen3.8-27B dense prefill (direct rows): fused gate|up, down, the GDN qkv|z mix, o */ - else if (!strcmp(name, "q38gu")) { E = 1; n = 34816; k = 5120; M = tokens; xr = 0; layout = OMEGA_GPU_PF_SWIGLU_NAT; direct = 1; } - else if (!strcmp(name, "q38down")) { E = 1; n = 5120; k = 17408; M = tokens; xr = 0; layout = OMEGA_GPU_PF_PLAIN; direct = 1; } - else if (!strcmp(name, "q38mix")) { E = 1; n = 16384; k = 5120; M = tokens; xr = 0; layout = OMEGA_GPU_PF_PLAIN; direct = 1; } - else if (!strcmp(name, "q38o")) { E = 1; n = 5120; k = 6144; M = tokens; xr = 0; layout = OMEGA_GPU_PF_PLAIN; direct = 1; } - else { printf("unknown shape %s\n", name); return 1; } - const uint32_t bm = omega_gpu_pf_qgemm_bm(), KB = k / 128; - QProb p; qprob_make(&p, E, n, k, M, xr, layout, direct, bm); - int fail = 0, rc; - OmegaGpuFp8Tensor *wt = NULL; OmegaGpuMem xd = { 0 }, sd = { 0 }, yd = { 0 }, tab = { 0 }, ridx = { 0 }, wc = { 0 }, sc = { 0 }; - const size_t XR = p.xr + bm, ob = layout == OMEGA_GPU_PF_PLAIN ? 4 : 1; - rc = omega_gpu_fp8_tensor_upload(E, n, k, p.w, p.sbf, &wt) == 0 ? 0 : OMEGA_GPU_PF_CHIP_FAIL; /* the GEMV tensor, read in place */ - const size_t xb = (XR * k + 15) & ~(size_t)15, sb = (XR * KB * 4 + 15) & ~(size_t)15, yb = (size_t)(M + bm) * n * ob; - if (!rc) rc = omega_gpu_pf_alloc_dev(xb, &xd); - if (!rc) rc = omega_gpu_pf_alloc_dev(sb, &sd); - if (!rc) rc = omega_gpu_pf_alloc_dev(yb, &yd); - if (!rc) rc = omega_gpu_pf_upload(&xd, 0, p.xq, XR * k & ~(size_t)15); - if (!rc) rc = omega_gpu_pf_upload(&sd, 0, p.xs, XR * KB * 4 & ~(size_t)15); - const uint32_t maxt = M / bm + E + 1; - if (!rc) rc = omega_gpu_pf_alloc_host((size_t)maxt * 32, &tab); - if (!rc) rc = omega_gpu_pf_alloc_host((size_t)(M + bm) * 4, &ridx); - if (rc) { printf("%s setup: %s (%s)\n", name, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); qprob_free(&p); return 1; } - uint32_t nt = 0; - if (!g_cached) nt = omega_gpu_pf_qgemm_tiles(wt, p.counts, tab.cpu, maxt); - else { - const size_t wbytes = (size_t)E * n * k, sbytes = ((size_t)E * (n / 128) * KB * 4 + 15) & ~(size_t)15; - float *sst = calloc(1, sbytes); memcpy(sst, p.swf, (size_t)E * (n / 128) * KB * 4); - if (omega_gpu_pf_alloc_dev(wbytes, &wc) || omega_gpu_pf_alloc_dev(sbytes, &sc) || omega_gpu_pf_upload(&wc, 0, p.w, wbytes) || omega_gpu_pf_upload(&sc, 0, sst, sbytes)) { printf("%s cached copy failed\n", name); free(sst); return 1; } - free(sst); - uint64_t *wv = malloc(E * 8), *sv = malloc(E * 8); - for (uint32_t e = 0; e < E; e++) { wv[e] = wc.va + (uint64_t)e * n * k; sv[e] = sc.va + (uint64_t)e * (n / 128) * KB * 4; } - nt = omega_gpu_pf_qgemm_tiles_va(E, wv, sv, p.counts, tab.cpu, maxt); free(wv); free(sv); - } - if (!nt) { printf("%s tile table failed\n", name); return 1; } - { uint32_t *ri = ridx.cpu; for (uint32_t i = 0; i < M + bm; i++) ri[i] = i < M ? p.src[i] : 0; } - omega_gpu_session_lock(); (void)omega_gpu_session_sync_to_gpu(&tab); (void)omega_gpu_session_sync_to_gpu(&ridx); omega_gpu_session_unlock(); - const uint64_t rva = direct ? 0 : ridx.va; - uint8_t *y1 = malloc(yb), *y2 = calloc(1, yb); - uint64_t ns[32] = { 0 }; - if (reps > 32) reps = 32; - for (int r = 0; r < reps && !rc; r++) rc = omega_gpu_pf_qgemm(n, k, layout, tab.va, nt, rva, xd.va, sd.va, yd.va, &ns[r]); - if (!rc) rc = omega_gpu_pf_download(&yd, 0, y1, yb & ~(size_t)15); - if (!rc) rc = omega_gpu_pf_upload(&yd, 0, y2, yb & ~(size_t)15); /* zero the output, run once more: identical result required */ - uint64_t ns2 = 0; - if (!rc) rc = omega_gpu_pf_qgemm(n, k, layout, tab.va, nt, rva, xd.va, sd.va, yd.va, &ns2); - if (!rc) rc = omega_gpu_pf_download(&yd, 0, y2, yb & ~(size_t)15); - if (rc) { printf("%s run: %s (%s)\n", name, omega_gpu_pf_rc_name(rc), omega_gpu_session_last_error()); fail++; } - else { - const size_t outb = (size_t)M * n * ob; - printf("%s second launch identical: %s\n", name, memcmp(y1, y2, outb) ? "NO" : "yes"); - if (memcmp(y1, y2, outb)) fail++; - uint32_t *rows = malloc(check_rows * 4); for (int q = 0; q < check_rows; q++) rows[q] = q == 0 ? 0 : q == 1 ? M - 1 : rnd() % M; - size_t ulp1 = 0; const size_t bad = qcompare(&p, y1, rows, check_rows, layout == OMEGA_GPU_PF_PLAIN ? 0 : 1, &ulp1); - printf("%s bit-identity on %d sampled rows: %zu differ", name, check_rows, bad); - if (layout != OMEGA_GPU_PF_PLAIN) printf(" (beyond 1 bf16 ulp; %zu within 1 ulp of %zu)", ulp1, (size_t)check_rows * n / 2); - printf("\n"); - if (bad) fail++; - qsort(ns, reps, 8, cmp_u64); - const double fl = 2.0 * M * n * k, med = (double)ns[reps / 2]; - printf("QGEMM%s %s tokens %u M %u n %u k %u tiles %u: median %.3f ms (min %.3f), %.1f TFLOPS, weights %.0f MB -> %.0f GB/s of distinct weights\n", g_cached ? "-cached" : "-inplace", name, tokens, M, n, k, nt, - med / 1e6, ns[0] / 1e6, fl / med / 1e3, (double)E * n * k / 1e6, (double)E * n * k / med); - if (mutants) for (int m = 1; m <= 4; m++) { - omega_gpu_pf_qgemm_test_set_mutant(m); - int mrc = omega_gpu_pf_qgemm(n, k, layout, tab.va, nt, rva, xd.va, sd.va, yd.va, NULL); - omega_gpu_pf_qgemm_test_set_mutant(0); - if (!mrc) mrc = omega_gpu_pf_download(&yd, 0, y2, yb & ~(size_t)15); - const size_t mb = mrc ? 0 : qcompare(&p, y2, rows, check_rows > 8 ? 8 : check_rows, layout == OMEGA_GPU_PF_PLAIN ? 0 : 1, NULL); - printf("%s mutant %d: %s\n", name, m, mrc ? "launch failed" : mb ? "caught" : "NOT CAUGHT"); - if (mrc || !mb) fail++; - } - free(rows); - } - free(y1); free(y2); - omega_gpu_fp8_tensor_free(wt); omega_gpu_pf_free(&wc); omega_gpu_pf_free(&sc); omega_gpu_pf_free(&xd); omega_gpu_pf_free(&sd); omega_gpu_pf_free(&yd); omega_gpu_pf_free(&tab); omega_gpu_pf_free(&ridx); - qprob_free(&p); - return fail; -} - -int main(int argc, char **argv) { - int host = 1, sim = 1, chip = 0, reps = 7, rows = 64; uint32_t tokens = 3600, rt = 0, warps = 0, wait = 0, waitset = 0; const char *only = NULL; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) sim = 0; - else if (!strcmp(argv[i], "--sim")) host = 0; - else if (!strcmp(argv[i], "--chip")) { chip = 1; host = 0; sim = 0; } - else if (!strcmp(argv[i], "--tokens") && i + 1 < argc) tokens = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = atoi(argv[++i]); - else if (!strcmp(argv[i], "--rows") && i + 1 < argc) rows = atoi(argv[++i]); - else if (!strcmp(argv[i], "--shape") && i + 1 < argc) only = argv[++i]; - else if (!strcmp(argv[i], "--cached")) g_cached = 1; - else if (!strcmp(argv[i], "--rt") && i + 1 < argc) rt = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--warps") && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--wait") && i + 1 < argc) { wait = (uint32_t)atoi(argv[++i]); waitset = 1; } - } - int fail = 0; - if (host) { fail += pq_host(); fail += qg_host(); } - if (sim) { fail += pq_sim(); fail += qg_sim(); } - if (chip) { - if (rt || warps || waitset) omega_gpu_pf_qgemm_set_shape(rt ? rt : 4, warps ? warps : 8, waitset ? wait : 45); - const int q38 = only && !strcmp(only, "q38"); /* --shape q38: the quantiser plus the four Qwen3.8 shapes */ - if (!only || q38) fail += pq_chip(tokens, reps); - static const char *shapes[] = { "gateup", "down", "qkv", "o", "q38gu", "q38down", "q38mix", "q38o" }; - for (int s = 0; s < 8; s++) { - const int run = q38 ? s >= 4 : only ? !strcmp(only, shapes[s]) : s < 4; - if (run) fail += qg_chip_shape(shapes[s], tokens, reps, rows, q38 ? s < 6 : !only || s < 2); - } - } - printf("GPU_QGEMM: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} diff --git a/tests/gpu_qmma_probe_test.c b/tests/gpu_qmma_probe_test.c deleted file mode 100644 index 639aa7cd2..000000000 --- a/tests/gpu_qmma_probe_test.c +++ /dev/null @@ -1,303 +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. - */ - -/* gpu_qmma_probe_test.c (OWN-30B L1 GEMM, W-L1G, 2026-10-14): characterise the GB10's QMMA.16832.F32.E4M3.E4M3. - * --host-only patch self-test against the nvcc oracle bits; model self-checks - * (default) chip (caller holds flock /tmp/aien-gb10.lock): - * 1 arithmetic: CASES single-QMMA cases; class "exact" (sparse power-of-two operands, every sum exact) checks the INFERRED - * fragment layout (any miss there = layout wrong); per model of tests/bw_qmma_model.h the bit-exact match count; - * negative control: mutant 1 (C dropped) must differ wherever C matters; a second run with fewer wait NOPs must match - * 2 peak: QMMA chains x issue stall sweep; every stored value must be 32 * iters; TFLOPS = 8192 flop per QMMA / time - * Env QMMA_PROBE_SEED: fresh data (confirmation). --save F / --replay F: chip words to / from a file (offline model search). - * Verdict last: "QMMA_PROBE: model=... exact N/N" or "QMMA_PROBE: NO EXACT MODEL", then "GPU_QMMA_PROBE: PASS|FAIL". */ -#include "omega_blackwell_codegen_qmma.h" -#include "omega_gpu_session.h" -#include "bw_qmma_model.h" -#include -#include -#include - -#define CASES 2048u -#define NCLS 7 -static uint64_t rng = 0x9e3779b97f4a7c15ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -/* random e4m3 code with unbiased exponent field in [lo, hi] (1..15; 0 = subnormal), never NaN */ -static uint8_t re4(int lo, int hi) { - for (;;) { uint8_t e = (uint8_t)(lo + (int)(rnd() % (uint32_t)(hi - lo + 1))), c = (uint8_t)((rnd() & 0x80) | e << 3 | (rnd() & 7)); if ((c & 0x7f) != 0x7f) return c; } -} -static float rf(int lo, int hi) { float m = 1.0f + (float)(rnd() & 127) / 128.0f; int e = lo + (int)(rnd() % (uint32_t)(hi - lo + 1)); float v = ldexpf(m, e); return (rnd() & 1) ? -v : v; } - -typedef struct { uint8_t A[16][32], B[32][8]; float C[16][8]; } Case; -static const char *clsname[NCLS] = { "narrow", "wide", "mixed+cancel", "bigC", "subnormal", "medium", "exact" }; -static void gen_case(Case *c, unsigned idx) { - unsigned cls = idx % NCLS; - for (int r = 0; r < 16; r++) for (int k = 0; k < 32; k++) { - uint8_t v; - switch (cls) { - case 0: v = re4(6, 8); break; - case 1: v = re4(1, 15); break; - case 2: v = (k & 1) ? re4(6, 8) : re4(1, 7); break; - case 3: v = re4(5, 9); break; - case 4: v = (rnd() & 3) ? re4(0, 0) : re4(1, 2); break; - case 5: v = re4(3, 11); break; - default: v = (rnd() % 6 == 0) ? (uint8_t)((rnd() & 0x80) | (uint8_t)((5 + rnd() % 5) << 3)) : 0; break; /* sparse +-2^(-2..2) */ - } - c->A[r][k] = v; - } - for (int k = 0; k < 32; k++) for (int n = 0; n < 8; n++) - c->B[k][n] = cls == 6 ? ((rnd() % 4 == 0) ? (uint8_t)((rnd() & 0x80) | (uint8_t)((5 + rnd() % 5) << 3)) : 0) : cls == 1 ? re4(1, 15) : re4(4, 10); - for (int r = 0; r < 16; r++) for (int n = 0; n < 8; n++) { - float v = idx % 11 == 10 ? 0.0f : rf(-6, 6); - if (cls == 3) v = rf(12, 16); - if (cls == 6) v = (float)((int)(rnd() % 9) - 4); - if (cls == 2 && (rnd() & 1)) { double s = 0; for (int k = 0; k < 32; k++) s += (double)qm_e4m3(c->A[r][k]) * qm_e4m3(c->B[k][n]); v = (float)-s; } - c->C[r][n] = v; - } -} -static uint32_t pack4(uint8_t a, uint8_t b, uint8_t cc, uint8_t d) { return (uint32_t)a | (uint32_t)b << 8 | (uint32_t)cc << 16 | (uint32_t)d << 24; } -/* the INFERRED m16n8k32 8-bit fragment layout (header) */ -static void to_frag(const Case *c, uint32_t *in) { - uint32_t *A = in, *B = in + 128; float *C = (float *)(in + 192); - for (int L = 0; L < 32; L++) { - int g = L / 4, t = L % 4; - for (int q = 0; q < 4; q++) { int r = g + (q & 1 ? 8 : 0), k0 = 4 * t + (q & 2 ? 16 : 0); A[L * 4 + q] = pack4(c->A[r][k0], c->A[r][k0 + 1], c->A[r][k0 + 2], c->A[r][k0 + 3]); } - for (int q = 0; q < 2; q++) { int k0 = 4 * t + 16 * q; B[L * 2 + q] = pack4(c->B[k0][g], c->B[k0 + 1][g], c->B[k0 + 2][g], c->B[k0 + 3][g]); } - C[L * 4 + 0] = c->C[g][2 * t]; C[L * 4 + 1] = c->C[g][2 * t + 1]; C[L * 4 + 2] = c->C[g + 8][2 * t]; C[L * 4 + 3] = c->C[g + 8][2 * t + 1]; - } -} -static void out_rc(int L, int q, int *r, int *n) { int g = L / 4, t = L % 4; *r = g + (q >= 2 ? 8 : 0); *n = 2 * t + (q & 1); } -static float model_out(const QmmaModel *m, const Case *c, int r, int n) { - float a[32], b[32]; for (int k = 0; k < 32; k++) { a[k] = qm_e4m3(c->A[r][k]); b[k] = qm_e4m3(c->B[k][n]); } - return qm_dot32(m, a, b, c->C[r][n]); -} -static double exact_out(const Case *c, int r, int n, double *mag) { - double s = c->C[r][n]; *mag = fabs(s); for (int k = 0; k < 32; k++) { double p = (double)qm_e4m3(c->A[r][k]) * qm_e4m3(c->B[k][n]); s += p; *mag += fabs(p); } return s; -} - -static int host_only(void) { - int fail = 0; char msg[160]; - int rc = omega_qmma_patch_selftest(msg, sizeof msg); - printf("QMMA patch self-test: %s (%s)\n", rc ? "FAIL" : "PASS", msg); if (rc) fail++; - if (qm_e4m3(0x38) != 1.0f || qm_e4m3(0x7e) != 448.0f || qm_e4m3(0x01) != ldexpf(1.0f, -9) || qm_e4m3(0xb8) != -1.0f) { printf("e4m3 decode FAIL\n"); fail++; } - for (int i = 0; i < 1000; i++) { - float a[32], b[32]; for (int k = 0; k < 32; k++) { a[k] = (float)((int)(rnd() % 17) - 8); b[k] = (float)((int)(rnd() % 9) - 4); } - float c = (float)((int)(rnd() % 33) - 16); double ex = c; for (int k = 0; k < 32; k++) ex += (double)a[k] * b[k]; - int groups[] = { 0, 1, 2, 4, 8, 16, 32 }; - for (int gi = 0; gi < 7; gi++) for (int rn = 0; rn < 2; rn++) { QmmaModel m = { groups[gi], 24, rn, 0, 0 }; if (qm_dot32(&m, a, b, c) != (float)ex) fail++; } - } - for (int c = 0; c < 256; c++) if ((c & 0x7f) != 0x7f && qm_e4m3_rne_sat(qm_e4m3((uint8_t)c)) != c) { printf("e4m3 round trip FAIL at %02x\n", c); fail++; } - if (qm_e4m3_rne_sat(500.0f) != 0x7e || qm_e4m3_rne_sat(ldexpf(1.0f, -10)) != 0 || qm_e4m3_rne_sat(ldexpf(3.0f, -10)) != 2 || qm_e4m3_rne_sat(1.0625f) != 0x38) { printf("e4m3 rounding FAIL\n"); fail++; } - { static Case c; gen_case(&c, 6); uint32_t in[320]; to_frag(&c, in); if ((in[0] & 0xff) != c.A[0][0] || ((in[1] >> 8) & 0xff) != c.A[8][1] || ((in[128 + 5 * 2 + 1] >> 24) & 0xff) != c.B[16 + 4 + 3][1]) fail++; } - static BlackwellIRProgram p; - if (omega_blackwell_codegen_qmma_probe_prog(0, 4, &p) != 0 || omega_blackwell_codegen_qmma_peak_prog(64, 16, 2, 128, &p) != 0) { printf("codegen refused\n"); fail++; } - printf("host-only checks: %s (%d failures)\n", fail ? "FAIL" : "PASS", fail); - return fail; -} - -static int load_code(BlackwellIRProgram *prog, OmegaGpuMem *code) { - size_t need = omega_bw_program_code_bytes(prog); OmegaBlackwellKernel k; - if (omega_gpu_session_alloc_code(need, code) != 0 || omega_blackwell_kernel_encode_into(prog, code->cpu, need, &k) != 0) return -1; - if (omega_qmma_patch_code(prog, code->cpu, need) < 1) { printf("QMMA patch failed\n"); return -1; } - return omega_gpu_session_sync_to_gpu(code); -} -static int run_probe(int mutant, uint32_t nops, uint32_t *out_words, const uint32_t *in_words) { - BlackwellIRProgram *prog = calloc(1, sizeof *prog); - if (!prog || omega_blackwell_codegen_qmma_probe_prog(mutant, nops, prog) != 0) { printf("codegen failed\n"); free(prog); return -1; } - int rc = -1; - omega_gpu_session_lock(); - OmegaGpuMem code = { 0 }, in = { 0 }, out = { 0 }; - if (!omega_gpu_session_open()) { printf("open failed: %s\n", omega_gpu_session_last_error()); goto done; } - if (load_code(prog, &code) != 0) { printf("code upload failed\n"); goto done; } - if (omega_gpu_session_alloc((size_t)CASES * 1280u, &in) != 0 || omega_gpu_session_alloc((size_t)CASES * 512u, &out) != 0) { printf("alloc failed\n"); goto done; } - memcpy(in.cpu, in_words, (size_t)CASES * 1280u); - { float *o = out.cpu; for (size_t i = 0; i < (size_t)CASES * 128u; i++) o[i] = -999.0f; } - if (omega_gpu_session_sync_to_gpu(&in) != 0 || omega_gpu_session_sync_to_gpu(&out) != 0) goto done; - { - uint32_t args[4] = { (uint32_t)in.va, (uint32_t)(in.va >> 32), (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - uint32_t decl = omega_bw_gpr_declared(prog->regalloc.peak_gpr_usage); - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = decl < 64 ? 64 : decl, .threads_x = 32, .threads_y = 1, .grid_x = CASES, .grid_y = 1, - .num_elements = (size_t)CASES * 128u, .args = args, .n_args = 4, .timeout_ms = 10000 }; - uint64_t ns = 0; - if (omega_gpu_session_launch(&L, &ns, NULL) != 0) { printf("launch failed: %s\n", omega_gpu_session_last_error()); goto done; } - if (omega_gpu_session_sync_to_cpu(&out) != 0) goto done; - printf("chip probe mutant %d nops %u: declared %u, %llu ns\n", mutant, nops, L.gpr_count, (unsigned long long)ns); - } - memcpy(out_words, out.cpu, (size_t)CASES * 512u); - rc = 0; -done: - if (code.cpu) omega_gpu_session_free(&code); - if (in.cpu) omega_gpu_session_free(&in); - if (out.cpu) omega_gpu_session_free(&out); - omega_gpu_session_unlock(); - free(prog); - return rc; -} - - -/* convert probe: NP pairs through F2FP.SATFINITE.E4M3; byte order and rounding against qm_e4m3_rne_sat */ -#define NP (1u << 20) -static float cvt_input(uint32_t i) { - switch (i % 8) { - case 0: return u2f((rnd() & 0x80000000u) | (uint32_t)(127 - 14 + (int)(rnd() % 25)) << 23 | (rnd() & 0x7fffff)); /* 2^-14 .. 2^10, full mantissa */ - case 1: { uint8_t c = (uint8_t)(rnd() & 0xff); if ((c & 0x7f) >= 0x7e) c = 0x10; float a = qm_e4m3(c), b = qm_e4m3((uint8_t)(c + 1)); return (a + b) * 0.5f; } /* exact ties */ - case 2: return u2f((rnd() & 0x80000000u) | (rnd() & 0x7fffff) | (uint32_t)(127 - 12 + (int)(rnd() % 4)) << 23); /* subnormal e4m3 range */ - case 3: { static const uint32_t sp[] = { 0, 0x80000000u, 0x43e00000u, 0x43e80000u, 0x43e7ffffu, 0x7f800000u, 0xff800000u, 0x3a800000u, 0x3a000000u, 0x00000001u, 0x447a0000u, 0xc3e10000u }; return u2f(sp[rnd() % 12]); } - default: return u2f((rnd() & 0x80000000u) | (uint32_t)(127 - 8 + (int)(rnd() % 17)) << 23 | (rnd() & 0x7fffff)); - } -} -static int cvt_probe(void) { - static BlackwellIRProgram p; int fail = 0; - if (omega_blackwell_codegen_f2e4_probe_prog(&p) != 0) { printf("cvt codegen refused\n"); return 1; } - float *x = malloc((size_t)NP * 8); for (uint32_t i = 0; i < 2 * NP; i++) x[i] = cvt_input(i); - omega_gpu_session_lock(); - OmegaGpuMem code = { 0 }, in = { 0 }, out = { 0 }; - if (!omega_gpu_session_open() || load_code(&p, &code) != 0 || omega_gpu_session_alloc((size_t)NP * 8, &in) != 0 || omega_gpu_session_alloc((size_t)NP * 4, &out) != 0) { printf("cvt setup failed: %s\n", omega_gpu_session_last_error()); fail = 1; goto done; } - memcpy(in.cpu, x, (size_t)NP * 8); memset(out.cpu, 0xa5, (size_t)NP * 4); - { uint32_t args[4] = { (uint32_t)in.va, (uint32_t)(in.va >> 32), (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = 64, .threads_x = 128, .threads_y = 1, .grid_x = NP / 128u, .grid_y = 1, .num_elements = NP, .args = args, .n_args = 4, .timeout_ms = 10000 }; - uint64_t ns = 0; - if (omega_gpu_session_sync_to_gpu(&in) || omega_gpu_session_sync_to_gpu(&out) || omega_gpu_session_launch(&L, &ns, NULL) || omega_gpu_session_sync_to_cpu(&out)) { printf("cvt launch failed: %s\n", omega_gpu_session_last_error()); fail = 1; goto done; } } - { const uint32_t *o = out.cpu; size_t hi_ab = 0, hi_ba = 0, upper = 0, nan_n = 0, n = 0, tie_ab = 0, ties = 0; uint32_t first_bad = 0xffffffffu; - for (uint32_t i = 0; i < NP; i++) { - float a = x[2 * i], b = x[2 * i + 1]; - if (isnan(a) || isnan(b)) { nan_n++; continue; } - n++; if (o[i] >> 16) upper++; - uint32_t ab = (uint32_t)qm_e4m3_rne_sat(a) << 8 | qm_e4m3_rne_sat(b), ba = (uint32_t)qm_e4m3_rne_sat(b) << 8 | qm_e4m3_rne_sat(a); - if ((o[i] & 0xffff) == ab) hi_ab++; else if (first_bad == 0xffffffffu) first_bad = i; - if ((o[i] & 0xffff) == ba) hi_ba++; - if (i % 4 == 1 || (2 * i + 1) % 8 == 1) { ties++; if ((o[i] & 0xffff) == ab) tie_ab++; } - } - printf("cvt probe: %zu pairs; Ra->high byte matches %zu, Ra->low byte matches %zu; upper 16 bits nonzero %zu; ties %zu of %zu exact\n", n, hi_ab, hi_ba, upper, tie_ab, ties); - if (first_bad != 0xffffffffu) printf(" first miss pair %u: %a %a -> chip %04x want %04x\n", first_bad, x[2 * first_bad], x[2 * first_bad + 1], o[first_bad] & 0xffff, (uint32_t)qm_e4m3_rne_sat(x[2 * first_bad]) << 8 | qm_e4m3_rne_sat(x[2 * first_bad + 1])); - printf("CVT_PROBE: %s\n", hi_ab == n && upper == 0 ? "e4m3(Ra) << 8 | e4m3(Rb), RNE satfinite, exact on every pair" : "MISMATCH"); - if (hi_ab != n || upper) fail = 1; - (void)nan_n; - } -done: - if (code.cpu) omega_gpu_session_free(&code); - if (in.cpu) omega_gpu_session_free(&in); - if (out.cpu) omega_gpu_session_free(&out); - omega_gpu_session_unlock(); - free(x); - return fail; -} - -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static int peak(void) { - static const struct { uint32_t stall, chains, threads, ctas; } pts[] = { - { 8, 16, 128, 192 }, { 4, 16, 128, 192 }, { 2, 16, 128, 192 }, { 1, 16, 128, 192 }, { 2, 8, 128, 192 }, { 2, 4, 128, 192 }, - { 2, 16, 256, 192 }, { 2, 16, 256, 384 }, { 1, 16, 512, 96 }, { 4, 8, 256, 384 }, - }; - const uint32_t iters = 4096; int fail = 0; - omega_gpu_session_lock(); - if (!omega_gpu_session_open()) { printf("open failed: %s\n", omega_gpu_session_last_error()); omega_gpu_session_unlock(); return 1; } - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - static BlackwellIRProgram p; OmegaGpuMem code = { 0 }, out = { 0 }; - if (omega_blackwell_codegen_qmma_peak_prog(iters, pts[i].chains, pts[i].stall, pts[i].threads, &p) != 0) { printf("codegen refused\n"); fail++; continue; } - size_t ob = (size_t)pts[i].ctas * pts[i].threads * 16u * pts[i].chains; - uint32_t decl = omega_bw_gpr_declared(p.regalloc.peak_gpr_usage); - if (load_code(&p, &code) != 0 || omega_gpu_session_alloc(ob, &out) != 0) { printf("upload failed: %s\n", omega_gpu_session_last_error()); fail++; break; } - uint64_t ns[5]; int ok = 1; size_t bad = 0; - for (int r = 0; r < 5 && ok; r++) { - ns[r] = 0; - float *o = out.cpu; for (size_t q = 0; q < ob / 4; q++) o[q] = -1.0f; - uint32_t args[2] = { (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = decl, .threads_x = pts[i].threads, .threads_y = 1, .grid_x = pts[i].ctas, .grid_y = 1, - .num_elements = ob / 4, .args = args, .n_args = 2, .timeout_ms = 20000 }; - if (omega_gpu_session_sync_to_gpu(&out) != 0 || omega_gpu_session_launch(&L, &ns[r], NULL) != 0 || omega_gpu_session_sync_to_cpu(&out) != 0) { printf("launch failed: %s\n", omega_gpu_session_last_error()); ok = 0; break; } - for (size_t q = 0; q < ob / 4; q++) if (o[q] != 32.0f * iters) bad++; - } - if (!ok) { fail++; omega_gpu_session_free(&code); omega_gpu_session_free(&out); break; } - qsort(ns, 5, 8, cmp_u64); - double qm = (double)pts[i].ctas * (pts[i].threads / 32u) * iters * pts[i].chains; - printf("QMMA peak stall %u chains %u threads %u ctas %u (declared %u): median %.1f us, %.2f TFLOPS, %zu wrong values\n", pts[i].stall, pts[i].chains, pts[i].threads, pts[i].ctas, decl, - ns[2] / 1e3, qm * 8192.0 / ns[2] / 1e3, bad); - if (bad) fail++; - omega_gpu_session_free(&code); omega_gpu_session_free(&out); - } - omega_gpu_session_unlock(); - return fail; -} - -int main(int argc, char **argv) { - const char *replay = NULL, *save = NULL; int host = 0, do_peak = 1; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) host = 1; - else if (!strcmp(argv[i], "--no-peak")) do_peak = 0; - else if (!strcmp(argv[i], "--replay") && i + 1 < argc) replay = argv[++i]; - else if (!strcmp(argv[i], "--save") && i + 1 < argc) save = argv[++i]; - } - if (getenv("QMMA_PROBE_SEED")) rng = strtoull(getenv("QMMA_PROBE_SEED"), NULL, 0) | 1u; - int fail = host_only(); - if (host || fail) { printf("GPU_QMMA_PROBE: %s\n", fail ? "FAIL" : "PASS"); return fail ? 1 : 0; } - static Case cases[CASES]; - const size_t ow = (size_t)CASES * 128u; - uint32_t *in = calloc((size_t)CASES, 1280u), *out = calloc(ow, 4), *outm = calloc(ow, 4), *out2 = calloc(ow, 4); - for (unsigned i = 0; i < CASES; i++) { gen_case(&cases[i], i); to_frag(&cases[i], in + (size_t)i * 320u); } - if (replay) { - FILE *rf = fopen(replay, "rb"); if (!rf) return 1; - size_t got = fread(out, 4, ow, rf) + fread(outm, 4, ow, rf) + fread(out2, 4, ow, rf); fclose(rf); - if (got != 3 * ow) { printf("short replay file\n"); return 1; } - printf("replaying chip words from %s\n", replay); do_peak = 0; - } else { - if (run_probe(0, 8, out, in) || run_probe(1, 8, outm, in) || run_probe(0, 2, out2, in)) { printf("GPU_QMMA_PROBE: FAIL chip\n"); return 1; } - if (save) { FILE *sf = fopen(save, "wb"); if (sf) { fwrite(out, 4, ow, sf); fwrite(outm, 4, ow, sf); fwrite(out2, 4, ow, sf); fclose(sf); } } - } - size_t poison = 0, far = 0, exact_miss = 0, exact_n = 0, waitdiff = 0; - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - size_t w = (size_t)i * 128 + L * 4 + q; float v = u2f(out[w]); - if (v == -999.0f) poison++; - if (out[w] != out2[w]) waitdiff++; - int r, n; out_rc(L, q, &r, &n); double mag, ex = exact_out(&cases[i], r, n, &mag); - if (fabs(v - ex) > 1e-2 * mag + 1e-30) far++; - if (i % NCLS == 6) { exact_n++; if ((double)v != ex) exact_miss++; } - } - printf("plausibility: %zu poison, %zu of %zu outputs farther than 1e-2 of the term magnitude from the exact sum\n", poison, far, ow); - printf("layout check (class exact, every sum representable): %zu of %zu differ from the exact sum (%s)\n", exact_miss, exact_n, exact_miss ? "LAYOUT OR ARITHMETIC WRONG" : "layout confirmed"); - printf("wait check: 2-NOP run vs 8-NOP run: %zu of %zu words differ\n", waitdiff, ow); - size_t mdiff = 0, mcand = 0; - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - size_t w = (size_t)i * 128 + L * 4 + q; int r, n; out_rc(L, q, &r, &n); float dv = u2f(out[w]); - if (cases[i].C[r][n] == 0.0f || fabsf(cases[i].C[r][n]) < ldexpf(fabsf(dv), -8)) continue; - mcand++; if (out[w] != outm[w]) mdiff++; - } - printf("negative control (C dropped): %zu of %zu outputs with significant C differ (%s)\n", mdiff, mcand, mcand && mdiff == mcand ? "caught" : "NOT CAUGHT"); - int groups[] = { 0, 1, 2, 4, 8, 16, 32 }; size_t best = 0; QmmaModel bm = { 0, 0, 0, 0, 0 }; - for (int gi = 0; gi < 7; gi++) for (int keep = 10; keep <= 32; keep++) for (int rn = 0; rn < 2; rn++) for (int nom = 0; nom < 3; nom++) for (int cs = 0; cs < 2; cs++) { - if (groups[gi] == 0 && (keep != 10 || rn || nom || cs)) continue; - QmmaModel m = { groups[gi], keep, rn, nom, cs }; - size_t match = 0, miss[NCLS] = { 0 }; - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - int r, n; out_rc(L, q, &r, &n); - if (f2u(model_out(&m, &cases[i], r, n)) == out[(size_t)i * 128 + L * 4 + q]) match++; else miss[i % NCLS]++; - } - if (match * 100 >= ow * 95) - printf("model group %2d keep %d %s nominal %d csep %d: %zu of %zu (misses: %s %zu %s %zu %s %zu %s %zu %s %zu %s %zu %s %zu)\n", m.group, m.keep, m.rn ? "RN" : "RZ", m.nominal, m.csep, match, ow, - clsname[0], miss[0], clsname[1], miss[1], clsname[2], miss[2], clsname[3], miss[3], clsname[4], miss[4], clsname[5], miss[5], clsname[6], miss[6]); - if (match > best) { best = match; bm = m; } - } - int ok = poison == 0 && far == 0 && exact_miss == 0 && waitdiff == 0 && mcand && mdiff == mcand; - if (ok && best == ow) printf("QMMA_PROBE: model=group %d keep %d %s nominal %d csep %d exact %zu/%zu\n", bm.group, bm.keep, bm.rn ? "RN" : "RZ", bm.nominal, bm.csep, best, ow); - else printf("QMMA_PROBE: NO EXACT MODEL (best group %d keep %d %s nominal %d csep %d: %zu/%zu)%s\n", bm.group, bm.keep, bm.rn ? "RN" : "RZ", bm.nominal, bm.csep, best, ow, ok ? "" : " and plausibility/layout/control FAILED"); - int pf = do_peak ? peak() : 0; - int cf = replay ? 0 : cvt_probe(); - fail = !ok || best != ow || pf || cf; - printf("GPU_QMMA_PROBE: %s\n", fail ? "FAIL" : "PASS"); - free(in); free(out); free(outm); free(out2); - return fail; -} diff --git a/tests/gpu_reconv_test.c b/tests/gpu_reconv_test.c deleted file mode 100644 index 3416fe6ea..000000000 --- a/tests/gpu_reconv_test.c +++ /dev/null @@ -1,487 +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. - */ - -/* gpu_reconv_test: structured warp reconvergence (omega #308) on Omega's own Blackwell codegen. - * - * ./gpu_reconv_test --host-only encoder golden words, region bookkeeping, codegen refusals, - * listing by Omega's own disassembler, - * every probe kernel through the SIMT warp simulator against - * the host oracle under both fragment orders, the mutation - * controls, scoreboard and control-edge walks. No device. - * ./gpu_reconv_test --out receipt.json chip gate: host part first (a kernel the simulator rejects - * never gets chip time), then every probe on the chip against - * the oracle, bit-exact, then each math mutant must be caught. - * --observe-dropped-join chip only, optional: also launch the dropped-BSYNC mutant of - * one probe and record what the chip did (an observation, not - * a gate; the simulator rejects that kernel first). - * - * Probes (src/omega_gpu_elementwise_api.c, gen_rc_*): R3 diamond, R4 loop break, R5 nested, - * R6 lanes past the end with STS/BAR/LDS + SHFL, and the 16-deep barrier-register bound. - * Oracle: rc_oracle below; every comparison is exact (u32). Launcher chunking (64 CTAs x 128 - * threads per launch, P0 = words in the chunk) is part of the oracle, so a clamp to the wrong - * chunk end shows up. */ -#include "omega_gpu_elementwise_api.h" -#include "omega_blackwell_codegen.h" -#include "omega_bw_reconv.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim.h" -#include "omega_sm121_disasm.h" -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } - -typedef struct { OmegaGpuEwOp op; const char *name; const char *reg; } Probe; -static const Probe PROBES[] = { - { OMEGA_GPU_EW_RC_DIAMOND, "rc_diamond", "R3" }, - { OMEGA_GPU_EW_RC_LOOPBREAK, "rc_loopbreak", "R4" }, - { OMEGA_GPU_EW_RC_NESTED, "rc_nested", "R5" }, - { OMEGA_GPU_EW_RC_EXIT_BAR, "rc_exit_bar", "R6" }, - { OMEGA_GPU_EW_RC_DEPTH16, "rc_depth16", "B0..B15" }, -}; -#define NPROBES (sizeof PROBES / sizeof PROBES[0]) -/* 8191..8193 straddled the 64-CTA chunk, 131071..131073 the 1024-CTA chunk (cut L, 2026-10-12) */ -static const uint32_t NS[] = { 1, 5, 31, 32, 33, 63, 64, 65, 96, 127, 128, 129, 200, 1000, 4096, 8191, 8192, 8193, 20000, 131071, 131072, 131073 }; -#define MAXN 131073u -#define NNS (sizeof NS / sizeof NS[0]) -#define CHUNK (OMEGA_GPU_EW_MAX_CTAS * OMEGA_GPU_EW_THREADS) - -/* ----------------------------------------------------------------- oracle */ -static uint32_t count_loop(uint32_t x, uint32_t y, int math, uint32_t *v_out) { - uint32_t v = x & 255u, st = (y & 15u) + 1u, cnt = 0, bound = math ? 255u : 256u; - while (v < bound) { v += st; cnt++; } - *v_out = v; return cnt; -} -static uint32_t rc_r(OmegaGpuEwOp op, int math, uint32_t x, uint32_t y, uint32_t partner_x) { - uint32_t v, cnt; - switch (op) { - case OMEGA_GPU_EW_RC_DIAMOND: - if (x >= y) { uint32_t t = 3u * x + y, u = t ^ x, r = 5u * u + 1u; r += r >> 3; return math ? r + 1u : r; } - return x + 1u; - case OMEGA_GPU_EW_RC_LOOPBREAK: cnt = count_loop(x, y, math, &v); return cnt * 256u + v; - case OMEGA_GPU_EW_RC_NESTED: if (x & 1u) return 7u; cnt = count_loop(x, y, math, &v); return cnt * 256u + v + 100u; - case OMEGA_GPU_EW_RC_EXIT_BAR: return 3u * x + (partner_x | 1u); - case OMEGA_GPU_EW_RC_DEPTH16: return x + (x < y ? (uint32_t)BW_RECONV_MAX_BAR : 0u); - default: return 0xdeadbeefu; - } -} -static void rc_oracle(OmegaGpuEwOp op, int math, uint32_t n, const uint32_t *a, const uint32_t *b, uint32_t *out) { - for (uint32_t i0 = 0; i0 < n; i0 += CHUNK) { - uint32_t ni = n - i0 < CHUNK ? n - i0 : CHUNK; - uint32_t threads = ((ni + OMEGA_GPU_EW_THREADS - 1) / OMEGA_GPU_EW_THREADS) * OMEGA_GPU_EW_THREADS; - uint32_t *r = malloc((size_t)threads * 4); - for (uint32_t t = 0; t < threads; t++) { - uint32_t idx = t < ni ? t : ni - 1, pt = t ^ 1u, pidx = pt < ni ? pt : ni - 1; - r[t] = rc_r(op, math, a[i0 + idx], b[i0 + idx], a[i0 + pidx]); - } - for (uint32_t i = 0; i < ni; i++) { uint32_t nb = (i & 31u) == 31u ? i : i + 1u; out[i0 + i] = r[i] + 4099u * r[nb]; } - free(r); - } -} -/* An LCG's low bits cycle quickly (bit 0 has period 2), and the probes key on low bits - * (x & 255, y & 15, x & 1), so each draw goes through a mixing step. */ -static uint32_t mix(uint32_t r) { r ^= r >> 16; r *= 0x45d9f3bu; r ^= r >> 16; r *= 0x45d9f3bu; r ^= r >> 16; return r; } -static void fill(uint32_t *a, uint32_t *b, uint32_t n, uint32_t seed) { - for (uint32_t i = 0; i < n; i++) { a[i] = mix(lcg(&seed)); b[i] = mix(lcg(&seed)); } -} -static size_t diff_count(const uint32_t *got, const uint32_t *want, uint32_t n, uint32_t *first) { - size_t bad = 0; *first = n; - for (uint32_t i = 0; i < n; i++) if (got[i] != want[i]) { if (!bad) *first = i; bad++; } - return bad; -} - -/* --------------------------------------------------------- simulator driver */ -static uint8_t g_smem[1024]; -/* Mirrors run_1d: 64 CTAs x 128 threads per launch, P0 = words in the chunk. Returns the - * simulator's error code (0 clean); the output words are written to out. */ -static int ws_probe(const BlackwellIRProgram *p, uint32_t n, const uint32_t *a, const uint32_t *b, uint32_t *out, int order, WsSim *stats) { - for (uint32_t i = 0; i < n; i++) out[i] = 0xffbadbadu; - uint64_t wi = 0, li = 0, sp = 0; int mf = 0, pb = 0; - for (uint32_t i0 = 0; i0 < n; i0 += CHUNK) { - uint32_t ni = n - i0 < CHUNK ? n - i0 : CHUNK; - WsSim s; memset(&s, 0, sizeof s); - s.p = p; s.threads = OMEGA_GPU_EW_THREADS; s.smem = g_smem; s.smem_bytes = sizeof g_smem; s.order = order; - uint64_t aa = (uintptr_t)(a + i0), ba = (uintptr_t)(b + i0), ca = (uintptr_t)(out + i0); - s.cbank[0x380 / 4] = (uint32_t)aa; s.cbank[0x380 / 4 + 1] = (uint32_t)(aa >> 32); - s.cbank[0x388 / 4] = (uint32_t)ba; s.cbank[0x388 / 4 + 1] = (uint32_t)(ba >> 32); - s.cbank[0x390 / 4] = (uint32_t)ca; s.cbank[0x390 / 4 + 1] = (uint32_t)(ca >> 32); - s.cbank[0x398 / 4] = ni; - s.ranges[0] = (WsRange){ (uintptr_t)aa, (uintptr_t)aa + (size_t)ni * 4 }; - s.ranges[1] = (WsRange){ (uintptr_t)ba, (uintptr_t)ba + (size_t)ni * 4 }; - s.ranges[2] = (WsRange){ (uintptr_t)ca, (uintptr_t)ca + (size_t)ni * 4 }; - s.nranges = 3; - int err = ws_run(&s, (ni + OMEGA_GPU_EW_THREADS - 1) / OMEGA_GPU_EW_THREADS, 1); - wi += s.warp_issues; li += s.lane_issues; sp += s.splits; - if (s.max_frags > mf) mf = s.max_frags; - if (s.peak_bars > pb) pb = s.peak_bars; - if (err) { if (stats) *stats = s; return err; } - } - if (stats) { memset(stats, 0, sizeof *stats); stats->warp_issues = wi; stats->lane_issues = li; stats->splits = sp; stats->max_frags = mf; stats->peak_bars = pb; } - return 0; -} -static int codegen(OmegaGpuEwOp op, int mutant, BlackwellIRProgram *p, OmegaBlackwellKernel *k) { - memset(k, 0, sizeof *k); - return omega_gpu_elementwise_codegen_ir(op, mutant, p, k); -} -static int is_reconv_err(int e) { - return e == WS_E_SHFL_SPLIT || e == WS_E_BAR_SPLIT || e == WS_E_STUCK || e == WS_E_NEVER_JOINED || e == WS_E_JOIN_MISMATCH || - e == WS_E_BSYNC_UNARMED || e == WS_E_BSSY_REARM || e == WS_E_NONMEMBER || e == WS_E_SHFL_EXITED; -} - -/* --------------------------------------------------------- static walks */ -/* Scoreboard walk (as bench/prime_race/tests/gb10_sieve_host_test.c sb_hazards): a destination - * written under write scoreboard 0 is in flight until a wait mask that includes it. */ -static int sb_hazards(const BlackwellIRProgram *p) { - int inflight[64], n = 0, bad = 0; - for (size_t i = 0; i < p->count; i++) { - const BlackwellIRInsn *in = &p->insns[i]; - uint32_t c = in->control; - if ((c >> 20) & 1u) n = 0; - const int src[3] = { in->src1_vreg, in->src2_vreg, in->src3_vreg }; - for (int s = 0; s < 3; s++) for (int k = 0; src[s] >= 0 && k < n; k++) if (inflight[k] == src[s]) bad++; - if (c != 0 && ((c >> 14) & 7u) == 0 && in->dst_vreg >= 0 && n < 64) inflight[n++] = in->dst_vreg; - } - return bad; -} -/* Control-edge walk: the straight-line scoreboard reasoning above holds only if nothing is in - * flight across a branch, barrier op or exit. Every BRA / EXIT / BSSY / BSYNC must wait on every - * scoreboard set since the last wait. Returns the number of control ops that do not. */ -static int edge_waits(const BlackwellIRProgram *p) { - uint32_t pending = 0; int bad = 0; - for (size_t i = 0; i < p->count; i++) { - const BlackwellIRInsn *in = &p->insns[i]; - uint32_t c = in->control, wait = (c >> 20) & 63u, wb = (c >> 14) & 7u, rb = (c >> 17) & 7u; - pending &= ~wait; - if (in->op == BW_IR_BRA || in->op == BW_IR_EXIT || in->op == BW_IR_BSSY || in->op == BW_IR_BSYNC) { if (pending) bad++; } - if (wb != 7u) pending |= 1u << wb; - if (rb != 7u) pending |= 1u << rb; - } - return bad; -} -static int count_op(const BlackwellIRProgram *p, BlackwellIROpcode op, int bar) { - int n = 0; - for (size_t i = 0; i < p->count; i++) if (p->insns[i].op == op && (bar < 0 || p->insns[i].bar_reg == bar)) n++; - return n; -} -static int find_op(const BlackwellIRProgram *p, BlackwellIROpcode op, int nth) { - for (size_t i = 0; i < p->count; i++) if (p->insns[i].op == op && nth-- == 0) return (int)i; - return -1; -} - -/* --------------------------------------------------------- sm121dis listing */ -static int sm121dis_bytes(const uint8_t *code, size_t bytes, const char *name, const char *const *must, int n_must) { - char lst[96]; - snprintf(lst, sizeof lst, "/tmp/omega_rc_%s_%d.sass.XXXXXX", name, (int)getpid()); - int fd = mkstemp(lst); /* private, unique listing; read back the same descriptor */ - FILE *f = fd >= 0 ? fdopen(fd, "w+") : NULL; - if (!f) { if (fd >= 0) close(fd); return -1; } - int rc = omega_sm121_listing(code, bytes, f); - if (fflush(f) != 0 || fseek(f, 0, SEEK_SET) != 0) { fclose(f); return -1; } - FILE *l = f; - char line[512]; int seen[16] = {0}, bad = 0, insns = 0; - while (fgets(line, sizeof line, l)) { - if (!strstr(line, "/*")) continue; /* every address line, 0x1000 and up too */ - insns++; - if (strstr(line, "?") || strstr(line, "error")) bad++; - for (int i = 0; i < n_must && i < 16; i++) if (strstr(line, must[i])) seen[i] = 1; - } - if (ferror(l)) rc = -1; - if (fclose(l) != 0) rc = -1; - int miss = 0; - for (int i = 0; i < n_must && i < 16; i++) if (!seen[i]) { printf(" %s: sm121dis listing lacks %s\n", name, must[i]); miss++; } - printf("sm121dis %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst); - return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1; -} -static int sm121dis_kernel(OmegaGpuEwOp op, int mutant, const char *name, const char *const *must, int n_must) { - BlackwellIRProgram *p = calloc(1, sizeof *p); OmegaBlackwellKernel k; - if (!p || codegen(op, mutant, p, &k) != OMEGA_GPU_EW_OK) { free(p); return -1; } - int rc = sm121dis_bytes(k.code, k.code_size, name, must, n_must); - free(k.code); free(p); - return rc; -} - -/* --------------------------------------------------------- host part */ -typedef struct { const char *name; uint64_t warp_issues, lane_issues, splits; int max_frags, peak_bars; } Model; -static Model g_model[NPROBES * 2]; static int g_nmodel; - -static int host_part(void) { - int before = g_failed; - /* 1. encoder golden words (nvcc 13.0.88 -arch=sm_121 oracle, docs/gpu-reconvergence-308.md) */ - int fx = omega_blackwell_verify_codegen_fixtures_reconv(); - CHECK(fx == 0, "encoder golden words BSSY / BSYNC and refusals (rc %d)", fx); - - /* 2. region bookkeeping on a hand-built program */ - { - BlackwellIRProgram *p = calloc(1, sizeof *p); BwRegions r; memset(&r, 0, sizeof r); - omega_bw_ir_init(p); - BlackwellIRInsn in; memset(&in, 0, sizeof in); in.dst_vreg = in.src1_vreg = in.src2_vreg = in.src3_vreg = -1; - in.op = BW_IR_BSSY; in.bar_reg = 0; in.imm = 2; omega_bw_ir_append(p, &in); /* 0 */ - CHECK(bw_regions_next_bar(&r) == 0 && bw_regions_begin(&r, 0) == 0, "region begin returns B0"); - in.op = BW_IR_BRA; in.imm = 1; in.predicate_p0 = true; omega_bw_ir_append(p, &in); /* 1 */ - CHECK(bw_regions_exit(&r, 1) == 0, "region exit recorded"); - in.op = BW_IR_NOP; in.predicate_p0 = false; omega_bw_ir_append(p, &in); /* 2 */ - in.op = BW_IR_BSYNC; in.bar_reg = 0; omega_bw_ir_append(p, &in); /* 3 */ - CHECK(bw_regions_join(&r, p, 3) == 0, "region join returns B0"); - CHECK(p->insns[0].imm == 4 && p->insns[1].imm == 2, "join patched BSSY to the insn after BSYNC (%u) and the exit to the BSYNC (%u)", p->insns[0].imm, p->insns[1].imm); - CHECK(bw_regions_join(&r, p, 3) == -1, "join with no open region refused"); - CHECK(bw_regions_exit(&r, 1) == -1, "exit with no open region refused"); - /* exits table full */ - memset(&r, 0, sizeof r); bw_regions_begin(&r, 0); - int ok = 1; for (int i = 0; i < BW_RECONV_MAX_EXITS; i++) ok &= bw_regions_exit(&r, 1) == 0; - CHECK(ok && bw_regions_exit(&r, 1) == -1, "exit table bound (%d) fails closed", BW_RECONV_MAX_EXITS); - /* join index inconsistent: BSYNC before BSSY, wrong barrier */ - memset(&r, 0, sizeof r); bw_regions_begin(&r, 3); - CHECK(bw_regions_join(&r, p, 0) == -1, "join with BSSY after BSYNC refused"); - memset(&r, 0, sizeof r); bw_regions_begin(&r, 0); p->insns[3].bar_reg = 1; - CHECK(bw_regions_join(&r, p, 3) == -1, "join with the wrong barrier register refused"); - p->insns[3].bar_reg = 0; - /* depth bound */ - memset(&r, 0, sizeof r); ok = 1; - for (int d = 0; d < BW_RECONV_MAX_DEPTH; d++) ok &= bw_regions_next_bar(&r) == d && bw_regions_begin(&r, d) == d; - CHECK(ok && bw_regions_next_bar(&r) == -1 && bw_regions_begin(&r, 99) == -1, "nesting bound %d: the next begin fails closed", BW_RECONV_MAX_DEPTH); - free(p); - } - - /* 3. codegen: production probes build, refusals refuse, mutants differ */ - static const struct { OmegaGpuEwOp op; const char *name; } refuse[] = { - { OMEGA_GPU_EW_RC_REFUSE_DEPTH17, "17 nested regions" }, { OMEGA_GPU_EW_RC_REFUSE_EXIT_SHFL, "EXIT then BAR/SHFL" }, - { OMEGA_GPU_EW_RC_REFUSE_EXIT_IN_REGION, "EXIT inside a region" }, { OMEGA_GPU_EW_RC_REFUSE_BAR_IN_REGION, "BAR.SYNC inside a region" }, - { OMEGA_GPU_EW_RC_REFUSE_SHFL_IN_REGION, "SHFL inside a region" }, { OMEGA_GPU_EW_RC_REFUSE_UNCLOSED, "region never joined" }, - { OMEGA_GPU_EW_RC_REFUSE_JOIN_ONLY, "BSYNC with no BSSY" }, - }; - for (size_t i = 0; i < sizeof refuse / sizeof refuse[0]; i++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); OmegaBlackwellKernel k; - int rc = codegen(refuse[i].op, 0, p, &k); - CHECK(rc == OMEGA_GPU_EW_CODEGEN_FAIL, "%s refused at codegen (rc %s)", refuse[i].name, omega_gpu_elementwise_rc_name(rc)); - if (rc == OMEGA_GPU_EW_OK) free(k.code); - free(p); - } - for (size_t i = 0; i < NPROBES; i++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); OmegaBlackwellKernel k; - int rc = codegen(PROBES[i].op, 0, p, &k); - CHECK(rc == OMEGA_GPU_EW_OK && k.gpr_count <= 64, "%s builds (rc %s, %zu insns, %u gprs)", PROBES[i].name, omega_gpu_elementwise_rc_name(rc), k.insn_count, k.gpr_count); - if (rc != OMEGA_GPU_EW_OK) { free(p); continue; } - int nb = count_op(p, BW_IR_BSSY, -1), ns = count_op(p, BW_IR_BSYNC, -1); - int want = PROBES[i].op == OMEGA_GPU_EW_RC_NESTED ? 2 : PROBES[i].op == OMEGA_GPU_EW_RC_DEPTH16 ? BW_RECONV_MAX_BAR : 1; - CHECK(nb == want && ns == want, "%s has %d BSSY and %d BSYNC (want %d)", PROBES[i].name, nb, ns, want); - if (PROBES[i].op == OMEGA_GPU_EW_RC_DEPTH16) { - int each = 1; for (int b = 0; b < BW_RECONV_MAX_BAR; b++) each &= count_op(p, BW_IR_BSSY, b) == 1 && count_op(p, BW_IR_BSYNC, b) == 1; - CHECK(each, "depth16 uses every barrier register B0..B15 exactly once"); - } - CHECK(sb_hazards(p) == 0, "%s scoreboard walk clean", PROBES[i].name); - CHECK(edge_waits(p) == 0, "%s every control op waits on everything in flight", PROBES[i].name); - printf("codegen %s: %zu insns, %u gprs, %d regions\n", PROBES[i].name, p->count, k.gpr_count, nb); - uint8_t d0[32]; memcpy(d0, k.code_digest, 32); free(k.code); - for (int m = 1; m <= 3; m++) { - BlackwellIRProgram *mp = calloc(1, sizeof *mp); OmegaBlackwellKernel mk; - int mrc = codegen(PROBES[i].op, m, mp, &mk); - int same_ok = m == 1 && PROBES[i].op == OMEGA_GPU_EW_RC_DEPTH16; /* depth16 has no math mutant */ - CHECK(mrc == OMEGA_GPU_EW_OK && ((memcmp(d0, mk.code_digest, 32) != 0) != same_ok), "%s mutant %d builds and %s (rc %s)", PROBES[i].name, m, same_ok ? "equals production" : "differs", omega_gpu_elementwise_rc_name(mrc)); - if (mrc == OMEGA_GPU_EW_OK) { - if (m == 2) CHECK(count_op(mp, BW_IR_BSYNC, -1) == 0 && count_op(mp, BW_IR_BSSY, -1) == nb, "%s mutant 2 has no BSYNC", PROBES[i].name); - if (m == 3) CHECK(count_op(mp, BW_IR_BSYNC, -1) == ns, "%s mutant 3 keeps its BSYNCs", PROBES[i].name); - free(mk.code); - } - free(mp); - } - free(p); - } - /* the four regioned sieves build too (their sweep runs in gb10_sieve_host_test) */ - for (int op = OMEGA_GPU_EW_PRIME_SIEVE_DIV1; op <= OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV2; op++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); OmegaBlackwellKernel k; - int rc = codegen((OmegaGpuEwOp)op, 0, p, &k); - int staged = op == OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV1 || op == OMEGA_GPU_EW_PRIME_SIEVE_SHARED_DIV2; - int nb = rc == OMEGA_GPU_EW_OK ? count_op(p, BW_IR_BSSY, -1) : -1, want = (op >= OMEGA_GPU_EW_PRIME_SIEVE_DIV2 ? 2 : 1) + staged; - CHECK(rc == OMEGA_GPU_EW_OK && k.gpr_count <= 64 && nb == want && edge_waits(p) == 0, "sieve op %d builds with %d regions (rc %s, %u gprs)", op, nb, omega_gpu_elementwise_rc_name(rc), k.gpr_count); - if (rc == OMEGA_GPU_EW_OK) free(k.code); - free(p); - } - - /* 4. sm121dis: the words decode as BSSY/BSYNC on the real barrier registers, and the predicated - * and B15 forms the encoder can produce decode too (built by hand: encode_one) */ - { - static const char *const m0[] = { "BSSY", "BSYNC", "B0", "SHFL.DOWN", "@P0 BRA" }; - CHECK(sm121dis_kernel(OMEGA_GPU_EW_RC_DIAMOND, 0, "diamond", m0, 5) == 0, "diamond listing decodes with BSSY/BSYNC B0"); - static const char *const m1[] = { "BSSY", "BSYNC", "B15", "B7" }; - CHECK(sm121dis_kernel(OMEGA_GPU_EW_RC_DEPTH16, 0, "depth16", m1, 4) == 0, "depth16 listing decodes with B15"); - static const char *const m2[] = { "BSSY", "B1", "BSYNC" }; - CHECK(sm121dis_kernel(OMEGA_GPU_EW_PRIME_SIEVE_DIV2, 0, "sieve_div2", m2, 3) == 0, "nested sieve listing decodes with B1"); - uint8_t code[64]; uint32_t w[4]; BlackwellIRInsn in; memset(&in, 0, sizeof in); in.dst_vreg = in.src1_vreg = in.src2_vreg = in.src3_vreg = -1; - in.op = BW_IR_BSSY; in.bar_reg = 3; in.imm = 2; in.predicate_p0 = true; omega_blackwell_encode_one(&in, w); memcpy(code, w, 16); - in.op = BW_IR_BSYNC; in.bar_reg = 3; in.predicate_p0 = true; in.predicate_not = true; omega_blackwell_encode_one(&in, w); memcpy(code + 16, w, 16); - in.op = BW_IR_BSYNC; in.bar_reg = 15; in.predicate_p0 = false; in.predicate_not = false; omega_blackwell_encode_one(&in, w); memcpy(code + 32, w, 16); - in.op = BW_IR_EXIT; omega_blackwell_encode_one(&in, w); memcpy(code + 48, w, 16); - static const char *const m3[] = { "@P0 BSSY", "B3", "@!P0 BSYNC", "BSYNC.RECONVERGENT B15" }; - CHECK(sm121dis_bytes(code, 64, "forms", m3, 4) == 0, "predicated BSSY/BSYNC and B15 decode"); - } - - /* 5. simulator: every probe, every n, both fragment orders, exact against the oracle */ - uint32_t *a = malloc(MAXN * 4), *b = malloc(MAXN * 4), *got = malloc(MAXN * 4), *want = malloc(MAXN * 4); - for (size_t i = 0; i < NPROBES; i++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); OmegaBlackwellKernel k; - if (codegen(PROBES[i].op, 0, p, &k) != OMEGA_GPU_EW_OK) { free(p); continue; } - int fails = 0; uint64_t cases = 0; - for (size_t j = 0; j < NNS; j++) for (int order = 0; order < 2; order++) { - uint32_t n = NS[j]; fill(a, b, n, 0x308u + n * 7u + (uint32_t)order); - rc_oracle(PROBES[i].op, 0, n, a, b, want); - WsSim st; int err = ws_probe(p, n, a, b, got, order, &st); - uint32_t first; size_t bad = diff_count(got, want, n, &first); - cases++; - if (err || bad) { fails++; printf(" %s n=%u order=%d: sim %s, %zu words differ (first %u: got %08x want %08x)\n", PROBES[i].name, n, order, err ? st.msg : "clean", bad, first, first < n ? got[first] : 0, first < n ? want[first] : 0); } - if (n == 4096) { Model *m = &g_model[g_nmodel++]; m->name = PROBES[i].name; m->warp_issues = st.warp_issues; m->lane_issues = st.lane_issues; m->splits = st.splits; m->max_frags = st.max_frags; m->peak_bars = st.peak_bars; } - } - CHECK(fails == 0, "%s simulator vs oracle: %d of %" PRIu64 " cases differ", PROBES[i].name, fails, cases); - /* math mutant: simulator clean, result wrong (the oracle sees it) */ - BlackwellIRProgram *mp = calloc(1, sizeof *mp); OmegaBlackwellKernel mk; - if (codegen(PROBES[i].op, 1, mp, &mk) == OMEGA_GPU_EW_OK) { - uint32_t n = 1000; fill(a, b, n, 0x1001u); rc_oracle(PROBES[i].op, 0, n, a, b, want); - WsSim st; int err = ws_probe(mp, n, a, b, got, 0, &st); uint32_t first; size_t bad = diff_count(got, want, n, &first); - if (PROBES[i].op == OMEGA_GPU_EW_RC_EXIT_BAR) CHECK(err == WS_E_SHFL_EXITED || err == WS_E_BAR_SPLIT, "R6 early-exit kernel: simulator reports SHFL_EXITED (got %s)", st.msg); - else if (PROBES[i].op == OMEGA_GPU_EW_RC_DEPTH16) CHECK(err == 0 && bad == 0, "depth16 'mutant 1' is the production kernel: clean and exact (err %d bad %zu)", err, bad); - else CHECK(err == 0 && bad > 0, "%s math mutant: simulator clean, %zu words differ (err %d)", PROBES[i].name, bad, err); - free(mk.code); - } - free(mp); - /* dropped join and corrupted target: the simulator must reject both, in both orders */ - for (int m = 2; m <= 3; m++) for (int order = 0; order < 2; order++) { - BlackwellIRProgram *xp = calloc(1, sizeof *xp); OmegaBlackwellKernel xk; - if (codegen(PROBES[i].op, m, xp, &xk) == OMEGA_GPU_EW_OK) { - uint32_t n = 1000; fill(a, b, n, 0x2002u + (uint32_t)m); - WsSim st; int err = ws_probe(xp, n, a, b, got, order, &st); - CHECK(is_reconv_err(err), "%s mutant %d (%s) order %d rejected by the simulator: %s", PROBES[i].name, m, m == 2 ? "BSYNC dropped" : "BSSY target corrupted", order, err ? st.msg : "NOT CAUGHT"); - if (m == 3) CHECK(err == WS_E_JOIN_MISMATCH || err == WS_E_STUCK, "%s corrupted target shows as JOIN_MISMATCH or STUCK (%s)", PROBES[i].name, ws_err_name(err)); - free(xk.code); - } - free(xp); - } - free(k.code); free(p); - } - /* 6. hand mutations of the production diamond (controls on the simulator itself, independent of - * the emitter's mutant hooks): exit jumping past the BSYNC, BSYNC on the wrong barrier, a BSSY - * on an armed barrier. And the unmodified program as the positive control. */ - { - BlackwellIRProgram *p = calloc(1, sizeof *p), *q = calloc(1, sizeof *q); OmegaBlackwellKernel k; - if (codegen(OMEGA_GPU_EW_RC_DIAMOND, 0, p, &k) == OMEGA_GPU_EW_OK) { - uint32_t n = 500; fill(a, b, n, 0x3003u); WsSim st; - int bssy = find_op(p, BW_IR_BSSY, 0), bsync = find_op(p, BW_IR_BSYNC, 0), ex = -1; - for (int i = bssy + 1; i < bsync; i++) if (p->insns[i].op == BW_IR_BRA && !p->insns[i].predicate_p0) ex = i; - CHECK(bssy >= 0 && bsync > bssy && ex > bssy, "diamond shape: BSSY %d, exit %d, BSYNC %d", bssy, ex, bsync); - CHECK(ws_probe(p, n, a, b, got, 0, &st) == 0, "positive control: untouched diamond runs clean"); - *q = *p; q->insns[ex].imm += 1; /* exit lands after the BSYNC */ - int e1 = ws_probe(q, n, a, b, got, 0, &st); CHECK(is_reconv_err(e1), "exit past the BSYNC rejected: %s", st.msg); - *q = *p; q->insns[bsync].bar_reg = 1; /* BSYNC on a barrier nobody armed */ - int e2 = ws_probe(q, n, a, b, got, 0, &st); CHECK(e2 == WS_E_BSYNC_UNARMED, "BSYNC on an unarmed barrier rejected: %s", st.msg); - *q = *p; q->insns[bsync].op = BW_IR_NOP; /* join dropped by hand */ - int e3 = ws_probe(q, n, a, b, got, 0, &st); CHECK(is_reconv_err(e3), "join replaced by NOP rejected: %s", st.msg); - *q = *p; q->insns[bssy].imm += 1; /* names the wrong join */ - int e4 = ws_probe(q, n, a, b, got, 0, &st); CHECK(e4 == WS_E_JOIN_MISMATCH, "wrong join target rejected: %s", st.msg); - *q = *p; q->insns[bssy + 1] = p->insns[bssy]; /* second BSSY on the armed barrier (overwrites the ISETP) */ - int e5 = ws_probe(q, n, a, b, got, 0, &st); CHECK(e5 == WS_E_BSSY_REARM, "BSSY on an armed barrier rejected: %s", st.msg); - free(k.code); - } - free(p); free(q); - } - free(a); free(b); free(got); free(want); - for (int i = 0; i < g_nmodel; i++) printf("model %s n=4096: warp_issues=%" PRIu64 " lane_util=%.3f splits=%" PRIu64 " max_frags=%d peak_bars=%d\n", g_model[i].name, g_model[i].warp_issues, g_model[i].warp_issues ? (double)g_model[i].lane_issues / (32.0 * (double)g_model[i].warp_issues) : 0.0, g_model[i].splits, g_model[i].max_frags, g_model[i].peak_bars); - return g_failed == before ? 0 : -1; -} - -/* --------------------------------------------------------- chip part */ -static int chip(const char *out_path, int observe) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } - if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_RECONV_V1\",\"issue\":308,\"comparison\":\"exact u32\",\"cases\":["); - int first = 1; - uint32_t *a = malloc(MAXN * 4), *b = malloc(MAXN * 4), *got = malloc(MAXN * 4), *want = malloc(MAXN * 4); - for (size_t i = 0; i < NPROBES; i++) { - for (size_t j = 0; j < NNS; j++) { - uint32_t n = NS[j]; fill(a, b, n, 0x5050u + n); - rc_oracle(PROBES[i].op, 0, n, a, b, want); - OmegaGpuEwInfo info; memset(&info, 0, sizeof info); - int rc = omega_gpu_reconv_probe_u32(PROBES[i].op, n, a, b, got, &info); - uint32_t fi; size_t bad = rc == OMEGA_GPU_EW_OK ? diff_count(got, want, n, &fi) : n; - int pass = rc == OMEGA_GPU_EW_OK && bad == 0; - CHECK(pass, "%s n=%u chip rc=%s violations=%zu err=\"%s\"", PROBES[i].name, n, omega_gpu_elementwise_rc_name(rc), bad, omega_gpu_elementwise_last_error()); - if (out) fprintf(out, "%s{\"op\":\"%s\",\"regression\":\"%s\",\"n\":%u,\"rc\":\"%s\",\"violations\":%zu,\"pass\":%s,\"chip_elapsed_ns\":%" PRIu64 ",\"chip_calls\":%u,\"unwritten_words\":%u,\"cache_hit\":%s}", - first ? "" : ",", PROBES[i].name, PROBES[i].reg, n, omega_gpu_elementwise_rc_name(rc), bad, pass ? "true" : "false", info.elapsed_ns, info.chip_calls, info.unwritten_words, info.kernel_cache_hit ? "true" : "false"); - first = 0; - if (!pass) { printf("STOP: %s failed on the chip at n=%u; no further launches of this probe\n", PROBES[i].name, n); break; } - } - } - if (out) fprintf(out, "],\"mutants\":["); - first = 1; - for (size_t i = 0; i < NPROBES; i++) { - if (PROBES[i].op == OMEGA_GPU_EW_RC_DEPTH16) continue; /* no math mutant */ - uint32_t n = 1000; fill(a, b, n, 0x6060u); rc_oracle(PROBES[i].op, 0, n, a, b, want); - omega_gpu_elementwise_test_set_mutant((int)PROBES[i].op); - /* R6's math mutant is the early-exit kernel: the emitter refuses it on the launch path - * (the bypass exists only for codegen_ir), so the catch is CODEGEN_FAIL: no undefined - * SHFL ever reaches the chip. */ - OmegaGpuEwInfo info; memset(&info, 0, sizeof info); - int rc = omega_gpu_reconv_probe_u32(PROBES[i].op, n, a, b, got, &info); - uint32_t fi; size_t bad = rc == OMEGA_GPU_EW_OK ? diff_count(got, want, n, &fi) : n; - int caught = rc != OMEGA_GPU_EW_OK || bad > 0; - omega_gpu_elementwise_test_set_mutant(0); - CHECK(caught, "%s math mutant caught (rc %s, violations %zu)", PROBES[i].name, omega_gpu_elementwise_rc_name(rc), bad); - if (PROBES[i].op == OMEGA_GPU_EW_RC_EXIT_BAR) CHECK(rc == OMEGA_GPU_EW_CODEGEN_FAIL, "R6 early-exit form refused at codegen on the launch path (rc %s)", omega_gpu_elementwise_rc_name(rc)); - if (out) fprintf(out, "%s{\"op\":\"%s\",\"mutant\":1,\"rc\":\"%s\",\"violations\":%zu,\"caught\":%s}", first ? "" : ",", PROBES[i].name, omega_gpu_elementwise_rc_name(rc), bad, caught ? "true" : "false"); - first = 0; - } - if (out) fprintf(out, "],\"observations\":["); - if (observe) { - /* The dropped-join kernel (rejected by the simulator above) on the chip once, small n: - * recorded as an observation of what the hardware does without the BSYNC. Not a gate. */ - uint32_t n = 1000; fill(a, b, n, 0x7070u); rc_oracle(OMEGA_GPU_EW_RC_DIAMOND, 0, n, a, b, want); - omega_gpu_elementwise_test_set_mutant_level(OMEGA_GPU_EW_RC_DIAMOND, 2); - OmegaGpuEwInfo info; memset(&info, 0, sizeof info); - int rc = omega_gpu_reconv_probe_u32(OMEGA_GPU_EW_RC_DIAMOND, n, a, b, got, &info); - uint32_t fi; size_t bad = rc == OMEGA_GPU_EW_OK ? diff_count(got, want, n, &fi) : n; - omega_gpu_elementwise_test_set_mutant(0); - printf("observation: diamond with the BSYNC dropped, n=%u: rc=%s, %zu of %u words differ from the oracle (first %u)\n", n, omega_gpu_elementwise_rc_name(rc), bad, n, fi); - if (out) fprintf(out, "{\"op\":\"rc_diamond\",\"mutant\":2,\"what\":\"BSYNC dropped\",\"n\":%u,\"rc\":\"%s\",\"violations\":%zu,\"first_bad\":%u,\"gate\":false}", n, omega_gpu_elementwise_rc_name(rc), bad, fi); - } - CHECK(omega_gpu_session_open_count() == 1, "device opened once for the battery (opens=%u)", omega_gpu_session_open_count()); - if (out) { - fprintf(out, "],\"sim_model_n4096\":["); - for (int i = 0; i < g_nmodel; i++) fprintf(out, "%s{\"op\":\"%s\",\"order\":%d,\"warp_issues\":%" PRIu64 ",\"lane_issues\":%" PRIu64 ",\"splits\":%" PRIu64 ",\"max_frags\":%d,\"peak_bars\":%d}", i ? "," : "", g_model[i].name, i & 1, g_model[i].warp_issues, g_model[i].lane_issues, g_model[i].splits, g_model[i].max_frags, g_model[i].peak_bars); - fprintf(out, "],\"device_opens\":%u,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_session_open_count(), g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_RECONV_PASS" : "OMEGA_GPU_RECONV_FAIL"); - fclose(out); - } - free(a); free(b); free(got); free(want); - return 0; -} - -int main(int argc, char **argv) { - const char *out_path = NULL; int host = 0, observe = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--observe-dropped-join") == 0) observe = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - } - int hrc = host_part(); - if (!host) { - if (hrc != 0) { printf("host part failed: no chip launches\nFAIL: %d checks, %d failed\n", g_checks, g_failed); return 1; } - if (chip(out_path, observe) != 0) return 2; - } - printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_router_test.c b/tests/gpu_router_test.c deleted file mode 100644 index 1ebf89399..000000000 --- a/tests/gpu_router_test.c +++ /dev/null @@ -1,524 +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. - */ - -/* - * gpu_router_test: the one-launch MoE router (omega_gpu_router_api.h), OWN-30B cut 8 item 2. - * --host-only oracle sanity, codegen budgets and refusals, the libm-free pieces (no device) - * --sim warp-simulator parity at 8 warps (both fragment orders), norm_topk on and off, mutants 1-4 caught - * (default) the chip: parity against the double oracle on random hidden states (two layers, norm_topk on and - * off), second call bit-identical, mutants 1-4 caught, the end-to-end: the grouped FP8 gate+up GEMV - * reading the router-written group table and x' row equals the host-table call bit for bit, chip - * medians (--reps N, --warps W, --depth D, --no-evict, --spin-us, --out receipt.json) - * Verdict line last: "gpu_router_test: N checks, F failed: PASS|FAIL". - */ -#include "omega_gpu_router_api.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_k.h" -#include -#include -#include -#include -#include -#include - -static int g_checks, g_failed; -#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) -static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } -static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); } -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); } -static float bf16_f32(uint16_t b) { uint32_t x = (uint32_t)b << 16; float f; memcpy(&f, &x, 4); return f; } -static const float EPS = 1e-6f; -#define H OMEGA_ROUTER_HIDDEN -/* -DROUTER_TEST_Q36: Qwen3.6-35B-A3B (256 routed experts + the shared expert gate row and slot; sc L306) */ -#ifdef ROUTER_TEST_Q36 -#define NE 256u -#define SHX 1u -#define SPEC_SHAPE , .experts = NE, .shared = SHX -#define GN_E2E 1024u -#define DK_E2E 512u -#else -#define NE OMEGA_ROUTER_EXPERTS -#define SHX 0u -#define SPEC_SHAPE -#define GN_E2E 1536u -#define DK_E2E 768u -#endif -#define NR (NE + SHX) /* gate rows */ -#define TK OMEGA_ROUTER_TOPK -#define TS (TK + SHX) /* output slots */ -#define MUT_MAX (SHX ? 5 : 4) -#define MARGIN_FLOOR 1e-4 /* an id mismatch at an oracle margin (8th - 9th logit) below this is recorded, not failed */ - -typedef struct { - float x[H], nw[H]; - uint16_t *gate; /* [NR][2048] bf16 (row NE = the shared expert gate when SHX) */ - double xn[H], logits[NR], w[TS], margin; - uint32_t ids[TS]; -} Case; - -/* the double oracle from c->x, c->nw, c->gate: xn, logits, ids (descending, lowest index on ties), weights, margin */ -static void oracle_fill(Case *c, int norm_topk) { - double ss = 0; for (unsigned i = 0; i < H; i++) ss += (double)c->x[i] * c->x[i]; - double r = 1.0 / sqrt(ss / (double)H + (double)EPS); - for (unsigned i = 0; i < H; i++) c->xn[i] = (double)c->x[i] * r * (double)c->nw[i]; - double mx = -1e300; - for (unsigned e = 0; e < NR; e++) { double l = 0; for (unsigned k = 0; k < H; k++) l += (double)bf16_f32(c->gate[(size_t)e * H + k]) * c->xn[k]; c->logits[e] = l; if (e < NE && l > mx) mx = l; } - double p[NE], sum = 0; for (unsigned e = 0; e < NE; e++) { p[e] = exp(c->logits[e] - mx); sum += p[e]; } - for (unsigned e = 0; e < NE; e++) p[e] /= sum; - int taken[NE]; memset(taken, 0, sizeof taken); - double s8 = 0; - for (unsigned r8 = 0; r8 <= TK; r8++) { /* 9 rounds: the 9th gives the margin */ - int best = -1; for (unsigned e = 0; e < NE; e++) if (!taken[e] && (best < 0 || c->logits[e] > c->logits[best])) best = (int)e; - if (r8 < TK) { c->ids[r8] = (uint32_t)best; taken[best] = 1; s8 += p[best]; c->w[r8] = p[best]; } - else c->margin = c->logits[c->ids[TK - 1]] - c->logits[best]; - } - if (norm_topk) for (unsigned i = 0; i < TK; i++) c->w[i] /= s8; - if (SHX) { c->ids[TK] = NE; c->w[TK] = 1.0 / (1.0 + exp(-c->logits[NE])); } /* the shared slot: never in the top-8 */ -} -/* shared_scale: the shared gate row (SHX) is multiplied by it (bf16): a huge row must leave the top-8 untouched */ -static void case_make_shared(Case *c, uint32_t seed, float xscale, int norm_topk, float shared_scale) { - uint32_t s = seed; - c->gate = malloc((size_t)NR * H * 2); - for (unsigned i = 0; i < H; i++) { c->x[i] = frand(&s, -2.0f, 2.0f) * xscale; c->nw[i] = frand(&s, 0.8f, 1.2f); } - for (size_t i = 0; i < (size_t)NR * H; i++) c->gate[i] = bf16_rne(frand(&s, -0.05f, 0.05f) * (i >= (size_t)NE * H ? shared_scale : 1.0f)); - oracle_fill(c, norm_topk); -} -static void case_make(Case *c, uint32_t seed, float xscale, int norm_topk) { case_make_shared(c, seed, xscale, norm_topk, 1.0f); } -static void case_free(Case *c) { free(c->gate); } - -/* outputs of one run (chip or simulator) */ -typedef struct { uint32_t ids[TS]; float w[TS], xout[H]; uint64_t tgu[TS * 2], tdn[TS * 2]; } Out; - -/* compares an Out against the oracle; returns a bitmask of what differed (1 ids, 2 weights, 4 x', 8 tables); fills msg */ -static int compare(const Case *c, const Out *o, float out_scale, const uint64_t *dgu, const uint64_t *ddn, char *msg, size_t n, int *margin_case) { - int bad = 0; *margin_case = 0; - int ids_eq = memcmp(c->ids, o->ids, sizeof c->ids) == 0; - if (!ids_eq) { if (c->margin < MARGIN_FLOOR) *margin_case = 1; else bad |= 1; } - double ww = 0, wx = 0; - if (ids_eq) for (unsigned i = 0; i < TS; i++) { double d = fabs((double)o->w[i] - c->w[i]); if (d > ww) ww = d; } - if (ww > 1e-5) bad |= 2; - double xmax = 0; for (unsigned i = 0; i < H; i++) if (fabs(c->xn[i]) > xmax) xmax = fabs(c->xn[i]); - for (unsigned i = 0; i < H; i++) { double d = fabs((double)o->xout[i] / (double)out_scale - c->xn[i]); if (d > wx) wx = d; } - if (wx > 1e-5 * xmax) bad |= 4; - if (ids_eq) for (unsigned g = 0; g < TS; g++) { - uint32_t id = o->ids[g]; - if (o->tgu[2 * g] != dgu[2 * id] || o->tgu[2 * g + 1] != dgu[2 * id + 1] || o->tdn[2 * g] != ddn[2 * id] || o->tdn[2 * g + 1] != ddn[2 * id + 1]) bad |= 8; - } - snprintf(msg, n, "ids %s%s, w max abs %.2e, x' max abs %.2e (of %.2f), tables %s, margin %.2e", ids_eq ? "equal" : "DIFFER", *margin_case ? " (margin case)" : "", ww, wx, xmax, (bad & 8) ? "WRONG" : "ok", c->margin); - return bad; -} - -/* ------------------------------------------------------------- host only */ -static void host_only(void) { - { Case c; case_make(&c, 1, 1.0f, 1); - double s = 0; for (unsigned i = 0; i < TK; i++) s += c.w[i]; - CHECK(fabs(s - 1.0) < 1e-12, "oracle: normalised weights sum to 1 (%.15f)", s); - int desc = 1; for (unsigned i = 1; i < TK; i++) desc &= c.logits[c.ids[i - 1]] >= c.logits[c.ids[i]]; - CHECK(desc, "oracle: ids are in descending logit order"); - CHECK(c.margin > 0, "oracle: margin positive (%.3e)", c.margin); - double rms = 0; for (unsigned i = 0; i < H; i++) rms += c.xn[i] * c.xn[i] / (c.nw[i] * c.nw[i]); rms = sqrt(rms / H); - CHECK(fabs(rms - 1.0) < 1e-3, "oracle: RMSNorm output has unit rms before the weight (%.6f)", rms); - case_free(&c); } - { Case c; case_make(&c, 2, 1.0f, 0); - double s = 0; for (unsigned i = 0; i < TK; i++) s += c.w[i]; - CHECK(s < 1.0 && s > 0.0, "oracle: unnormalised weights sum below 1 (%.4f)", s); - case_free(&c); } - /* codegen budgets: every production shape fits the register file (32 * warps * declared <= 65536) and the IR limit */ - uint32_t ws[] = { 8, 16, 32 }, ds[] = { 1, 2, 4, 8 }; - for (unsigned i = 0; i < 3; i++) for (unsigned j = 0; j < 4; j++) for (int m = 0; m <= MUT_MAX; m++) { - OmegaRouterSpec s = { .warps = ws[i], .depth = ds[j], .mutant = m SPEC_SHAPE }; uint32_t n = 0, g = 0; - int rc = omega_router_prog_stats(&s, &n, &g); - uint32_t decl = ((g + 1 + 7) / 8) * 8; - CHECK(rc == 0 && n <= 1024 && 32u * ws[i] * decl <= 65536u, "codegen warps %u depth %u mutant %d: rc %d insns %u gprs %u declared %u", ws[i], ds[j], m, rc, n, g, decl); - if (m == 0 && rc == 0) printf("codegen warps %2u depth %u: %u instructions, %u registers (declared %u, register file %u of 65536)\n", ws[i], ds[j], n, g, decl, 32u * ws[i] * decl); - } - { OmegaRouterSpec s = { .warps = 4, .depth = 8 SPEC_SHAPE }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "warps 4 refused"); } - { OmegaRouterSpec s = { .warps = 8, .depth = 3 SPEC_SHAPE }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "depth 3 refused"); } - { OmegaRouterSpec s = { .warps = 8, .depth = 8, .mutant = MUT_MAX + 1 SPEC_SHAPE }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "mutant %d refused", MUT_MAX + 1); } - { OmegaRouterSpec s = { .warps = 8, .depth = 8, .experts = 192 }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "192 experts refused"); } - { OmegaRouterSpec s = { .warps = 8, .depth = 8, .shared = 2 }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "shared 2 refused"); } - /* ROWS form (lever 2) at the production shapes: fits the register file; the strides are checked */ - for (unsigned i = 0; i < 3; i++) for (unsigned j = 0; j < 4; j++) { - OmegaRouterSpec s = { .warps = ws[i], .depth = ds[j], .xstride = 8192, .lbstride = 16896 SPEC_SHAPE }; uint32_t n = 0, g = 0; - int rc = omega_router_prog_stats(&s, &n, &g); - uint32_t decl = ((g + 1 + 7) / 8) * 8; - CHECK(rc == 0 && n <= 1024 && 32u * ws[i] * decl <= 65536u, "codegen ROWS warps %u depth %u: rc %d insns %u gprs %u declared %u", ws[i], ds[j], rc, n, g, decl); - if (rc == 0) printf("codegen ROWS warps %2u depth %u: %u instructions, %u registers (declared %u)\n", ws[i], ds[j], n, g, decl); - } - { OmegaRouterSpec s = { .warps = 8, .depth = 8, .xstride = 8192 SPEC_SHAPE }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "xstride without lbstride refused"); } - { OmegaRouterSpec s = { .warps = 8, .depth = 8, .lbstride = 16896 SPEC_SHAPE }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "lbstride without xstride refused"); } - { OmegaRouterSpec s = { .warps = 8, .depth = 8, .xstride = 4096, .lbstride = 16896 SPEC_SHAPE }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "xstride below one row refused"); } - { OmegaRouterSpec s = { .warps = 8, .depth = 8, .xstride = 8192, .lbstride = 16900 SPEC_SHAPE }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "unaligned lbstride refused"); } - { OmegaRouterSpec s = { .warps = 8, .depth = 8, .mutant = 6 SPEC_SHAPE }; CHECK(omega_router_prog_stats(&s, NULL, NULL) != 0, "mutant 6 without the ROWS form refused"); } - CHECK(OMEGA_ROUTER_ARGS_WORDS <= OMEGA_GPU_SESSION_MAX_ARGS, "argument words fit the constant bank window"); -} - -/* ------------------------------------------------------------- simulator */ -static uint64_t g_sim_issues; -/* one "device" block: x | xout | ids | wts | tab_gu | tab_dn | dir_gu | dir_dn | norm; the gate row block apart */ -enum { B_X = 0, B_XOUT = 8192, B_IDS = 16384, B_WTS = 16448, B_TGU = 16512, B_TDN = 16672, B_DGU = 16832, B_DDN = B_DGU + NR * 16, - B_NORM = B_DDN + NR * 16, B_BYTES = B_NORM + 8192 }; -static void fake_dirs(uint64_t *dgu, uint64_t *ddn) { for (unsigned e = 0; e < NR; e++) { dgu[2 * e] = 0x100000000ull + e * 16; dgu[2 * e + 1] = 0x200000000ull + e * 16 + 8; ddn[2 * e] = 0x300000000ull + e * 32; ddn[2 * e + 1] = 0x400000000ull + e * 32 + 16; } } -static int sim_point(uint32_t depth, int mutant, int norm_topk, float out_scale, uint32_t seed, float shared_scale, char *msg, size_t n, int *bad, int *margin_case) { - static BlackwellIRProgram prog; - OmegaRouterSpec spec = { .warps = 8, .depth = depth, .mutant = mutant SPEC_SHAPE }; - OmegaRouterSmem sm; - if (omega_blackwell_codegen_router_prog(&spec, &prog) != 0 || omega_router_smem(&spec, &sm) != 0) { snprintf(msg, n, "codegen refused"); return -1; } - Case c; case_make_shared(&c, seed, 1.0f, norm_topk, shared_scale); - uint8_t *blk = aligned_alloc(16, B_BYTES); memset(blk, 0, B_BYTES); - uint16_t *gate = aligned_alloc(16, (size_t)NR * H * 2); memcpy(gate, c.gate, (size_t)NR * H * 2); - memcpy(blk + B_X, c.x, sizeof c.x); memcpy(blk + B_NORM, c.nw, sizeof c.nw); - uint64_t dgu[NR * 2], ddn[NR * 2]; fake_dirs(dgu, ddn); - memcpy(blk + B_DGU, dgu, sizeof dgu); memcpy(blk + B_DDN, ddn, sizeof ddn); - Out o, copy; int err = 0; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 256; s.order = order; - static uint8_t smem[16384]; s.smem = smem; s.smem_bytes = sm.total; - float *xo = (float *)(blk + B_XOUT), *wd = (float *)(blk + B_WTS); uint32_t *idd = (uint32_t *)(blk + B_IDS); - for (unsigned i = 0; i < H; i++) xo[i] = -999.0f; - for (unsigned i = 0; i < TS; i++) { wd[i] = -999.0f; idd[i] = 0xffffffffu; } - memset(blk + B_TGU, 0, B_DGU - B_TGU); - uint64_t A[10] = { (uintptr_t)(blk + B_X), (uintptr_t)gate, (uintptr_t)(blk + B_NORM), (uintptr_t)(blk + B_XOUT), (uintptr_t)(blk + B_IDS), - (uintptr_t)(blk + B_WTS), (uintptr_t)(blk + B_DGU), (uintptr_t)(blk + B_DDN), (uintptr_t)(blk + B_TGU), (uintptr_t)(blk + B_TDN) }; - for (unsigned i = 0; i < 10; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)A[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - float fe = EPS, fo = out_scale; - memcpy(&s.cbank[OMEGA_ROUTER_ARG_EPS / 4], &fe, 4); memcpy(&s.cbank[OMEGA_ROUTER_ARG_OUT_SCALE / 4], &fo, 4); - s.cbank[OMEGA_ROUTER_ARG_NORM_TOPK / 4] = norm_topk ? 1u : 0u; - s.nranges = 2; - s.ranges[0].lo = (uintptr_t)blk; s.ranges[0].hi = (uintptr_t)blk + B_BYTES; - s.ranges[1].lo = (uintptr_t)gate; s.ranges[1].hi = (uintptr_t)gate + (size_t)NR * H * 2; - err = ws_run(&s, 1, 1); - if (err) { snprintf(msg, n, "order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - size_t unwritten = 0; for (unsigned i = 0; i < H; i++) if (xo[i] == -999.0f) unwritten++; - for (unsigned i = 0; i < TS; i++) if (wd[i] == -999.0f || idd[i] == 0xffffffffu) unwritten++; - if (unwritten) { err = -1; snprintf(msg, n, "%zu output words never written", unwritten); break; } - memcpy(o.ids, idd, sizeof o.ids); memcpy(o.w, wd, sizeof o.w); memcpy(o.xout, xo, sizeof o.xout); memcpy(o.tgu, blk + B_TGU, TS * 16); memcpy(o.tdn, blk + B_TDN, TS * 16); - if (order == 0) copy = o; - else if (memcmp(©, &o, sizeof o) != 0) { err = -1; snprintf(msg, n, "the fragment order changed the result"); } - } - if (!err) *bad = compare(&c, &o, out_scale, dgu, ddn, msg, n, margin_case); - free(blk); free(gate); case_free(&c); - return err; -} -/* ROWS form (L312 lever 2): one launch of `rows` CTAs routes `rows` residual rows of one layer (one gate, one norm, one - * pair of directories); CTA i reads x row i (stride XST_SIM, padded past 8192 so a wrong stride shows) and writes block i - * (stride B_BYTES). Every row's outputs must be bit-identical to the plain kernel run on that row alone, and both - * fragment orders must agree. Mutant 6 (every CTA reads row 0's x) must be caught. */ -#define XST_SIM (H * 4u + 64u) -static void sim_args(WsSim *s, BlackwellIRProgram *prog, const OmegaRouterSmem *sm, int order, const uint64_t A[10], int norm_topk, float out_scale) { - static uint8_t smem[16384]; - memset(s, 0, sizeof *s); - s->p = prog; s->threads = 256; s->order = order; s->smem = smem; s->smem_bytes = sm->total; - for (unsigned i = 0; i < 10; i++) { s->cbank[(0x380 + 8 * i) / 4] = (uint32_t)A[i]; s->cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(A[i] >> 32); } - float fe = EPS, fo = out_scale; - memcpy(&s->cbank[OMEGA_ROUTER_ARG_EPS / 4], &fe, 4); memcpy(&s->cbank[OMEGA_ROUTER_ARG_OUT_SCALE / 4], &fo, 4); - s->cbank[OMEGA_ROUTER_ARG_NORM_TOPK / 4] = norm_topk ? 1u : 0u; -} -static void poison_block(uint8_t *b) { - float *xo = (float *)(b + B_XOUT), *wd = (float *)(b + B_WTS); uint32_t *idd = (uint32_t *)(b + B_IDS); - for (unsigned i = 0; i < H; i++) xo[i] = -999.0f; - for (unsigned i = 0; i < TS; i++) { wd[i] = -999.0f; idd[i] = 0xffffffffu; } - memset(b + B_TGU, 0, B_DGU - B_TGU); -} -static size_t block_out(const uint8_t *b, Out *o) { - const float *xo = (const float *)(b + B_XOUT), *wd = (const float *)(b + B_WTS); const uint32_t *idd = (const uint32_t *)(b + B_IDS); - size_t unwritten = 0; for (unsigned i = 0; i < H; i++) if (xo[i] == -999.0f) unwritten++; - for (unsigned i = 0; i < TS; i++) if (wd[i] == -999.0f || idd[i] == 0xffffffffu) unwritten++; - memcpy(o->ids, idd, sizeof o->ids); memcpy(o->w, wd, sizeof o->w); memcpy(o->xout, xo, sizeof o->xout); memcpy(o->tgu, b + B_TGU, TS * 16); memcpy(o->tdn, b + B_TDN, TS * 16); - return unwritten; -} -static int sim_rows_point(uint32_t depth, int mutant, uint32_t rows, uint32_t seed, char *msg, size_t n, int *bad) { - static BlackwellIRProgram prog, plain; - OmegaRouterSpec spec = { .warps = 8, .depth = depth, .mutant = mutant, .xstride = XST_SIM, .lbstride = B_BYTES SPEC_SHAPE }; - OmegaRouterSpec pspec = { .warps = 8, .depth = depth SPEC_SHAPE }; - OmegaRouterSmem sm; - *bad = 0; - if (omega_blackwell_codegen_router_prog(&spec, &prog) != 0 || omega_blackwell_codegen_router_prog(&pspec, &plain) != 0 || omega_router_smem(&spec, &sm) != 0) { snprintf(msg, n, "codegen refused"); return -1; } - Case *c = calloc(rows, sizeof *c); - case_make(&c[0], seed, 1.0f, 1); - for (uint32_t i = 1; i < rows; i++) { /* one layer: row 0's gate and norm, row i's own x */ - c[i] = c[0]; uint32_t s = seed + 1000u * i; - for (unsigned k = 0; k < H; k++) c[i].x[k] = frand(&s, -2.0f, 2.0f); - oracle_fill(&c[i], 1); - } - uint8_t *blk = aligned_alloc(16, (size_t)B_BYTES * rows); memset(blk, 0, (size_t)B_BYTES * rows); - uint8_t *xs = aligned_alloc(16, (size_t)XST_SIM * rows); memset(xs, 0, (size_t)XST_SIM * rows); - uint16_t *gate = aligned_alloc(16, (size_t)NR * H * 2); memcpy(gate, c[0].gate, (size_t)NR * H * 2); - for (uint32_t i = 0; i < rows; i++) memcpy(xs + (size_t)i * XST_SIM, c[i].x, sizeof c[i].x); - memcpy(blk + B_NORM, c[0].nw, sizeof c[0].nw); - uint64_t dgu[NR * 2], ddn[NR * 2]; fake_dirs(dgu, ddn); - memcpy(blk + B_DGU, dgu, sizeof dgu); memcpy(blk + B_DDN, ddn, sizeof ddn); - Out *o = calloc(rows, sizeof *o), *copy = calloc(rows, sizeof *copy); int err = 0; - uint64_t A[10] = { (uintptr_t)xs, (uintptr_t)gate, (uintptr_t)(blk + B_NORM), (uintptr_t)(blk + B_XOUT), (uintptr_t)(blk + B_IDS), - (uintptr_t)(blk + B_WTS), (uintptr_t)(blk + B_DGU), (uintptr_t)(blk + B_DDN), (uintptr_t)(blk + B_TGU), (uintptr_t)(blk + B_TDN) }; - for (int order = 0; order < 2 && !err; order++) { - WsSim s; sim_args(&s, &prog, &sm, order, A, 1, 1.0f); - s.nranges = 3; - s.ranges[0].lo = (uintptr_t)blk; s.ranges[0].hi = (uintptr_t)blk + (size_t)B_BYTES * rows; - s.ranges[1].lo = (uintptr_t)gate; s.ranges[1].hi = (uintptr_t)gate + (size_t)NR * H * 2; - s.ranges[2].lo = (uintptr_t)xs; s.ranges[2].hi = (uintptr_t)xs + (size_t)XST_SIM * rows; - for (uint32_t i = 0; i < rows; i++) poison_block(blk + (size_t)i * B_BYTES); - err = ws_run(&s, 1, rows); - if (err) { snprintf(msg, n, "rows order %d: %s (pc %d)", order, s.msg, s.err_pc); break; } - g_sim_issues += s.warp_issues; - for (uint32_t i = 0; i < rows && !err; i++) { - size_t unwritten = block_out(blk + (size_t)i * B_BYTES, &o[i]); - if (unwritten) { err = -1; snprintf(msg, n, "row %u: %zu output words never written", i, unwritten); } - } - if (err) break; - if (order == 0) memcpy(copy, o, (size_t)rows * sizeof *o); - else if (memcmp(copy, o, (size_t)rows * sizeof *o) != 0) { err = -1; snprintf(msg, n, "the fragment order changed a row"); } - } - /* every row against the plain kernel on its own x (bit for bit) and against the oracle */ - uint32_t rows_differ = 0; int worst = 0; char sub[200] = ""; - for (uint32_t i = 0; i < rows && !err; i++) { - A[0] = (uintptr_t)(xs + (size_t)i * XST_SIM); - WsSim s; sim_args(&s, &plain, &sm, 0, A, 1, 1.0f); - s.nranges = 3; - s.ranges[0].lo = (uintptr_t)blk; s.ranges[0].hi = (uintptr_t)blk + B_BYTES; - s.ranges[1].lo = (uintptr_t)gate; s.ranges[1].hi = (uintptr_t)gate + (size_t)NR * H * 2; - s.ranges[2].lo = (uintptr_t)xs; s.ranges[2].hi = (uintptr_t)xs + (size_t)XST_SIM * rows; - poison_block(blk); - err = ws_run(&s, 1, 1); - if (err) { snprintf(msg, n, "plain row %u: %s (pc %d)", i, s.msg, s.err_pc); break; } - Out p; if (block_out(blk, &p)) { err = -1; snprintf(msg, n, "plain row %u: output words never written", i); break; } - if (memcmp(&p, &o[i], sizeof p) != 0) rows_differ++; - int mc = 0, b = compare(&c[i], &o[i], 1.0f, dgu, ddn, sub, sizeof sub, &mc); - if (b) worst |= b; - } - if (!err) { - *bad = worst | (rows_differ ? 16 : 0); - snprintf(msg, n, "%u rows: %u differ from the plain kernel, oracle mask %d (last: %s)", rows, rows_differ, worst, sub); - } - free(blk); free(xs); free(gate); free(o); free(copy); case_free(&c[0]); free(c); - return err; -} -static void sim_battery(void) { - struct { uint32_t depth; int norm_topk; float oscale; uint32_t seed; const char *name; } pts[] = { - { 8, 1, 1.0f, 11, "depth 8 norm" }, { 8, 1, 1.0f, 12, "depth 8 norm seed 12" }, { 8, 0, 1.0f, 13, "depth 8 no-norm" }, - { 4, 1, 1.0f, 14, "depth 4 norm" }, { 1, 1, 1.0f, 15, "depth 1 norm" }, { 2, 1, 18446744073709551616.0f, 16, "depth 2 norm out_scale 2^64" }, - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - char msg[300]; int bad = 0, mc = 0; - int err = sim_point(pts[i].depth, 0, pts[i].norm_topk, pts[i].oscale, pts[i].seed, 1.0f, msg, sizeof msg, &bad, &mc); - CHECK(!err && bad == 0, "sim %s: %s", pts[i].name, msg); - printf("sim %s: %s %s\n", pts[i].name, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - if (SHX) { /* the shared gate row scaled up 1000x: if it entered the top-8 or the softmax, ids / weights would differ */ - char msg[300]; int bad = 0, mc = 0; - int err = sim_point(8, 0, 1, 1.0f, 17, 1000.0f, msg, sizeof msg, &bad, &mc); - CHECK(!err && bad == 0, "sim shared row x1000: %s", msg); - printf("sim shared row x1000: %s %s\n", err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - for (int m = 1; m <= MUT_MAX; m++) { - char msg[300]; int bad = 0, mc = 0; - int err = sim_point(8, m, 1, 1.0f, 21, 1.0f, msg, sizeof msg, &bad, &mc); - CHECK(!err && bad != 0, "sim mutant %d must be caught: %s", m, msg); - printf("sim mutant %d: %s (bad mask %d) %s\n", m, err ? "ERROR" : bad ? "caught" : "NOT CAUGHT", bad, msg); - } - { /* ROWS form (lever 2): rows 2, 3 and 8 bit-identical to the plain kernel per row; mutant 6 caught at rows 2 */ - struct { uint32_t depth, rows, seed; } rp[] = { { 8, 2, 31 }, { 4, 3, 32 }, { 8, 8, 33 }, { 1, 2, 34 } }; - for (size_t i = 0; i < sizeof rp / sizeof rp[0]; i++) { - char msg[300]; int bad = 0; - int err = sim_rows_point(rp[i].depth, 0, rp[i].rows, rp[i].seed, msg, sizeof msg, &bad); - CHECK(!err && bad == 0, "sim rows %u depth %u: %s", rp[i].rows, rp[i].depth, msg); - printf("sim rows %u depth %u: %s %s\n", rp[i].rows, rp[i].depth, err ? "ERROR" : bad ? "MISMATCH" : "ok", msg); - } - char msg[300]; int bad = 0; - int err = sim_rows_point(8, 6, 2, 35, msg, sizeof msg, &bad); - CHECK(!err && bad != 0, "sim rows mutant 6 must be caught: %s", msg); - printf("sim rows mutant 6: %s (bad mask %d) %s\n", err ? "ERROR" : bad ? "caught" : "NOT CAUGHT", bad, msg); - } - printf("sim: %" PRIu64 " warp issues in total\n", g_sim_issues); -} - -/* ------------------------------------------------------------- chip */ -static int g_evict = 1; -static void evict_host_caches(void) { - static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass; - if (!buf) buf = malloc(sz); - if (!buf) return; - memset(buf, ++pass, sz); - volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i]; -} -static int chip_call(OmegaGpuRouter *r, uint32_t layer, const Case *c, int norm_topk, float out_scale, Out *o, OmegaGpuRouterInfo *info) { - int rc = omega_gpu_router(r, layer, c->x, EPS, norm_topk, out_scale, o->ids, o->w, info); - if (rc != OMEGA_GPU_ROUTER_OK) return rc; - return omega_gpu_router_read_back(r, o->xout, o->tgu, o->tdn); -} -static int chip_run(const char *out_path, uint32_t reps) { - FILE *out = out_path ? fopen(out_path, "w") : NULL; - if (out_path && !out) { printf("cannot write %s\n", out_path); return 1; } - if (out) fprintf(out, "{\"receipt\":\"OMEGA_GPU_ROUTER_V1\",\"reps\":%u,\"evict\":%d,\"spin_us\":%u,\"points\":[", reps, g_evict, omega_gpu_session_spin_us()); - OmegaGpuRouter *r = NULL; - double t0 = now_ms(); - int rc = omega_gpu_router_alloc_shape(2, NE, SHX, &r); - printf("router alloc (2 layers): rc=%s %.1f ms (%s)\n", omega_gpu_router_rc_name(rc), now_ms() - t0, rc ? omega_gpu_router_last_error() : ""); - CHECK(rc == OMEGA_GPU_ROUTER_OK, "router alloc"); - if (rc) { if (out) fprintf(out, "],\"verdict\":\"FAIL\"}\n"); return 1; } - uint64_t dgu[NR * 2], ddn[NR * 2]; fake_dirs(dgu, ddn); - CHECK(omega_gpu_router_set_directory(r, 0, dgu, ddn) == OMEGA_GPU_ROUTER_OK, "set directory layer 0"); - int first = 1, parity_fail = 0, margin_cases = 0; - /* parity: layer 0, 24 cases norm on, 8 off, 4 with out_scale 2^64; then the same gate on layer 1 (addressing) */ - Case fixed; case_make(&fixed, 1000, 1.0f, 1); - CHECK(omega_gpu_router_set_layer(r, 0, fixed.gate, fixed.nw) == OMEGA_GPU_ROUTER_OK, "set layer 0"); - for (unsigned i = 0; i < 36; i++) { - int norm = i < 24 || i >= 32; float os = i >= 32 ? 18446744073709551616.0f : 1.0f; - /* layer 0 holds `fixed`'s router weights and norm: a fresh x per case, the oracle on fixed.gate / fixed.nw */ - Case c; uint32_t s = 2000 + i; const float xs = i % 3 == 0 ? 0.01f : i % 3 == 1 ? 1.0f : 40.0f; - for (unsigned k = 0; k < H; k++) c.x[k] = frand(&s, -2.0f, 2.0f) * xs; - memcpy(c.nw, fixed.nw, sizeof c.nw); c.gate = fixed.gate; - oracle_fill(&c, norm); - Out o; OmegaGpuRouterInfo info; - rc = chip_call(r, 0, &c, norm, os, &o, &info); - char msg[300]; int bad = -1, mc = 0; - if (rc == OMEGA_GPU_ROUTER_OK) bad = compare(&c, &o, os, dgu, ddn, msg, sizeof msg, &mc); - else snprintf(msg, sizeof msg, "rc %s: %s", omega_gpu_router_rc_name(rc), omega_gpu_router_last_error()); - if (bad) parity_fail++; - if (mc) margin_cases++; - if (bad || i < 3 || i >= 24) printf("parity %u (norm %d, out_scale %s, x scale %s): %s%s\n", i, norm, os > 2.0f ? "2^64" : "1", i % 3 == 0 ? "0.01" : i % 3 == 1 ? "1" : "40", bad ? "MISMATCH " : "ok ", msg); - if (out) { fprintf(out, "%s{\"point\":\"parity %u\",\"norm_topk\":%d,\"bad_mask\":%d,\"margin_case\":%d,\"chip_ns\":%" PRIu64 "}", first ? "" : ",", i, norm, bad, mc, info.elapsed_ns); first = 0; } - if (i == 0 && rc == OMEGA_GPU_ROUTER_OK) { - Out o2; rc = chip_call(r, 0, &c, norm, os, &o2, NULL); - CHECK(rc == OMEGA_GPU_ROUTER_OK && memcmp(&o, &o2, sizeof o) == 0, "second call bit-identical (ids, weights, x', tables)"); - printf("second call: %s\n", rc == OMEGA_GPU_ROUTER_OK && memcmp(&o, &o2, sizeof o) == 0 ? "bit-identical" : "DIFFERS"); - } - } - CHECK(parity_fail == 0, "chip parity: %d of 36 cases mismatch", parity_fail); - printf("chip parity: %d of 36 mismatches, %d margin cases (recorded, oracle margin below %.0e)\n", parity_fail, margin_cases, MARGIN_FLOOR); - /* mutants on a fixed case, layer 0 */ - for (int m = 1; m <= MUT_MAX; m++) { - omega_gpu_router_test_set_mutant(m); - Out o; char msg[300]; int bad = -1, mc = 0; - rc = chip_call(r, 0, &fixed, 1, 1.0f, &o, NULL); - if (rc == OMEGA_GPU_ROUTER_OK) bad = compare(&fixed, &o, 1.0f, dgu, ddn, msg, sizeof msg, &mc); - else snprintf(msg, sizeof msg, "rc %s: %s", omega_gpu_router_rc_name(rc), omega_gpu_router_last_error()); - CHECK(bad != 0, "chip mutant %d must be caught: %s", m, msg); - printf("chip mutant %d: %s (bad mask %d) %s\n", m, bad ? "caught" : "NOT CAUGHT", bad, msg); - if (out) fprintf(out, ",{\"point\":\"mutant %d\",\"caught\":%d,\"bad_mask\":%d}", m, bad != 0, bad); - } - omega_gpu_router_test_set_mutant(0); - /* end to end on layer 1: real FP8 gate+up shape (128 x 1536 x 2048) and a small down tensor; the router's device - * table + x' feed omega_gpu_fp8_gemv_grouped_dev; the host-table call with the chip's ids and x'/2^64 must match bit for bit */ - { - const uint32_t GN = GN_E2E, GK = 2048, DN = 256, DK = DK_E2E; - size_t gw = (size_t)NR * GN * GK, dw = (size_t)NR * DN * DK; - uint8_t *w1 = malloc(gw), *w2 = malloc(dw); - uint16_t *s1 = malloc((size_t)NR * (GN / 128) * (GK / 128) * 2), *s2 = malloc((size_t)NR * (DN / 128) * (DK / 128) * 2); - uint32_t s = 4242; - for (size_t i = 0; i < gw; i++) { uint8_t b = (uint8_t)(lcg(&s) >> 24); if ((b & 0x7f) == 0x7f) b ^= 1; w1[i] = b; } - for (size_t i = 0; i < dw; i++) { uint8_t b = (uint8_t)(lcg(&s) >> 24); if ((b & 0x7f) == 0x7f) b ^= 1; w2[i] = b; } - for (size_t i = 0; i < (size_t)NR * (GN / 128) * (GK / 128); i++) s1[i] = bf16_rne(frand(&s, 0.5f, 2.0f)); - for (size_t i = 0; i < (size_t)NR * (DN / 128) * (DK / 128); i++) s2[i] = bf16_rne(frand(&s, 0.5f, 2.0f)); - OmegaGpuFp8Tensor *tg = NULL, *td = NULL; - t0 = now_ms(); - int r1 = omega_gpu_fp8_tensor_upload(NR, GN, GK, w1, s1, &tg), r2 = omega_gpu_fp8_tensor_upload(NR, DN, DK, w2, s2, &td); - printf("fp8 upload gate+up %zu MB + down %zu MB: rc %s / %s, %.0f ms\n", gw >> 20, dw >> 20, omega_gpu_fp8_rc_name(r1), omega_gpu_fp8_rc_name(r2), now_ms() - t0); - CHECK(r1 == 0 && r2 == 0, "fp8 uploads for the end-to-end"); - if (r1 == 0 && r2 == 0) { - Case c; case_make(&c, 3000, 1.0f, 1); - CHECK(omega_gpu_router_set_layer(r, 1, c.gate, c.nw) == OMEGA_GPU_ROUTER_OK, "set layer 1"); - CHECK(omega_gpu_router_set_directory_fp8(r, 1, tg, td) == OMEGA_GPU_ROUTER_OK, "set directory layer 1 from the fp8 tensors"); - uint64_t rgu[NR * 2], rdn[NR * 2]; - for (unsigned e = 0; e < NR; e++) { omega_gpu_fp8_tensor_entry(tg, e, &rgu[2 * e], &rgu[2 * e + 1]); omega_gpu_fp8_tensor_entry(td, e, &rdn[2 * e], &rdn[2 * e + 1]); } - Out o; OmegaGpuRouterInfo info; char msg[300]; int mc = 0; - const float OS = 18446744073709551616.0f; - rc = chip_call(r, 1, &c, 1, OS, &o, &info); - int bad = rc == 0 ? compare(&c, &o, OS, rgu, rdn, msg, sizeof msg, &mc) : -1; - CHECK(bad == 0, "e2e router on layer 1 with real directories: %s", rc ? omega_gpu_router_last_error() : msg); - printf("e2e router layer 1: %s %s\n", bad ? "MISMATCH" : "ok", rc ? omega_gpu_router_last_error() : msg); - uint64_t xva, tgva, tdva; omega_gpu_router_device_outputs(r, &xva, &tgva, &tdva); - float *ydev = malloc((size_t)TS * GN * 4), *yhost = malloc((size_t)TS * GN * 4), *xh = malloc(H * 4); - for (unsigned k = 0; k < H; k++) xh[k] = o.xout[k] / OS; /* exact: a power of two */ - OmegaGpuFp8Info fi, fh; - int rd = omega_gpu_fp8_gemv_grouped_dev(tg, TS, tgva, xva, ydev, &fi); - int rh = omega_gpu_fp8_gemv_grouped_f32(tg, TS, o.ids, xh, 1, yhost, &fh); - CHECK(rd == 0 && rh == 0, "grouped gate+up launches: dev %s host %s", omega_gpu_fp8_rc_name(rd), omega_gpu_fp8_rc_name(rh)); - int same = rd == 0 && rh == 0 && memcmp(ydev, yhost, (size_t)TS * GN * 4) == 0; - CHECK(same, "grouped gate+up from the router-written table and x' equals the host-table call bit for bit"); - printf("e2e grouped gate+up (8 experts, %u x %u): device table/x' vs host table: %s; chip %.1f us vs %.1f us, call %.1f us vs %.1f us\n", GN, GK, same ? "bit-identical" : "DIFFER", - fi.elapsed_ns / 1e3, fh.elapsed_ns / 1e3, fi.call_ns / 1e3, fh.call_ns / 1e3); - /* one group against the FP8 host oracle (the grouped kernel is proven elsewhere; this pins the plumbing) */ - if (rd == 0) { - double *yo = malloc(GN * sizeof(double)), *ys = malloc(GN * sizeof(double)); - uint32_t id = o.ids[3]; - omega_fp8_gemv_oracle(w1 + (size_t)id * GN * GK, s1 + (size_t)id * (GN / 128) * (GK / 128), GN, GK, xh, yo, ys); - double worst = 0; for (unsigned i = 0; i < GN; i++) { double d = fabs((double)ydev[3 * GN + i] - yo[i]) / (ys[i] + 1e-30); if (d > worst) worst = d; } - CHECK(worst < 1e-5, "e2e group 3 (expert %u) vs the FP8 host oracle: worst rel %.2e", id, worst); - printf("e2e group 3 vs fp8 oracle: worst rel %.2e\n", worst); - free(yo); free(ys); - } - /* sequence timing: router then grouped gate+up (dev), medians */ - uint64_t *er = malloc(reps * 8), *ec = malloc(reps * 8), *eg = malloc(reps * 8), *es = malloc(reps * 8); - uint32_t done = 0; - for (uint32_t i = 0; i < reps; i++) { - if (g_evict) evict_host_caches(); - double a = now_ms(); - if (omega_gpu_router(r, 1, c.x, EPS, 1, OS, o.ids, o.w, &info) != 0) break; - if (omega_gpu_fp8_gemv_grouped_dev(tg, TS, tgva, xva, ydev, &fi) != 0) break; - es[done] = (uint64_t)((now_ms() - a) * 1e6); - er[done] = info.elapsed_ns; ec[done] = info.call_ns; eg[done] = fi.elapsed_ns; done++; - } - CHECK(done == reps, "timing loop completed %u of %u", done, reps); - if (done) { - qsort(er, done, 8, cmp_u64); qsort(ec, done, 8, cmp_u64); qsort(eg, done, 8, cmp_u64); qsort(es, done, 8, cmp_u64); - printf("timing (medians of %u, evict %d, warps %u depth %u): router chip %.1f us, router call %.1f us, grouped gate+up dev chip %.1f us, router+gate+up sequence %.1f us\n", - done, g_evict, info.warps, info.depth, er[done / 2] / 1e3, ec[done / 2] / 1e3, eg[done / 2] / 1e3, es[done / 2] / 1e3); - if (out) fprintf(out, ",{\"point\":\"timing\",\"warps\":%u,\"depth\":%u,\"reps\":%u,\"router_chip_median_ns\":%" PRIu64 ",\"router_call_median_ns\":%" PRIu64 ",\"gateup_dev_chip_median_ns\":%" PRIu64 ",\"sequence_median_ns\":%" PRIu64 ",\"router_bytes\":%" PRIu64 ",\"marker\":%u}", - info.warps, info.depth, done, er[done / 2], ec[done / 2], eg[done / 2], es[done / 2], info.weight_bytes, info.completion_marker); - } - free(er); free(ec); free(eg); free(es); free(ydev); free(yhost); free(xh); - case_free(&c); - } - if (tg) omega_gpu_fp8_tensor_free(tg); - if (td) omega_gpu_fp8_tensor_free(td); - free(w1); free(w2); free(s1); free(s2); - } - case_free(&fixed); - omega_gpu_router_free(r); - if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); fclose(out); } - return g_failed ? 1 : 0; -} - -int main(int argc, char **argv) { - int host = 0, sim = 0; const char *out_path = NULL; uint32_t reps = 0, warps = 0, depth = 0, spin = 2000; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--host-only") == 0) host = 1; - else if (strcmp(argv[i], "--sim") == 0) sim = 1; - else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; - else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--warps") == 0 && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--depth") == 0 && i + 1 < argc) depth = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]); - else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0; - else { printf("unknown argument %s\n", argv[i]); return 2; } - } - if (host) host_only(); - if (sim) sim_battery(); - if (!host && !sim) { - if (warps || depth) omega_gpu_router_set_shape(warps, depth); - (void)omega_gpu_session_set_spin_us(spin); - chip_run(out_path, reps ? reps : 1); - omega_gpu_session_close(); - } - printf("gpu_router_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_scan_test.c b/tests/gpu_scan_test.c deleted file mode 100644 index 1e1b608fc..000000000 --- a/tests/gpu_scan_test.c +++ /dev/null @@ -1,379 +0,0 @@ -/* gpu_scan_test.c -- row C3 of docs/OMEGA.md: reductions and prefix sums of any length, bit-exact against the - * frozen-order host reference (src/omega_gpu_scan.h). - * - * --host-only no device: refusals, every kernel through our codegen and encoder, the references checked against - * exact integer sums and against the E1 reduction reference (omega_reduce_reference) - * --sim the real kernels through the warp simulator (tests/bw_warp_sim.h), both scheduling orders, lengths - * that cross every tile, CTA and grid-stride edge; the three mutants must be caught - * (no flag) the GB10: every n from 1 to 2048, then 2^k - 1, 2^k, 2^k + 1 up to 2^28, then random lengths; - * bit-exact (a NaN result must be a NaN); the three mutants must be caught. - * --max-log2 K stops the power-of-two ladder at 2^K (default 28). - * Last line: "C3 scan : PASS ( checks)" or "... FAIL ( of )". */ -#include "omega_gpu_scan.h" -#include "omega_gpu_session.h" -#include "omega_numeric_reduce.h" -#include "bw_warp_sim.h" - -#include -#include -#include -#include - -static int g_checks, g_failed; -static void check(int ok, const char *what) { - g_checks++; - if (!ok) { g_failed++; printf("FAIL: %s\n", what); } -} - -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } -static int is_nan(uint32_t u) { return (u & 0x7f800000u) == 0x7f800000u && (u & 0x007fffffu); } -static int same(float a, float b) { uint32_t x = f2u(a), y = f2u(b); return x == y || (is_nan(x) && is_nan(y)); } - -static uint64_t g_rng = 0x9e3779b97f4a7c15ull; -static uint32_t rnd(void) { g_rng = g_rng * 6364136223846793005ull + 1442695040888963407ull; return (uint32_t)(g_rng >> 33); } - -/* inputs: 0 small integers (every sum exact), 1 mixed magnitudes and signed zeros, 2 mixed plus NaN and infinities */ -static void fill(float *x, size_t n, int kind, uint64_t seed) { - g_rng = seed * 0x2545f4914f6cdd1dull + 1; - for (size_t i = 0; i < n; i++) { - if (kind == 0) { x[i] = (float)((int)(rnd() % 2001u) - 1000); continue; } - float m = (float)((rnd() & 0x7fffffu) | 1u) * (rnd() & 1 ? -1.0f : 1.0f); - int e = (int)(rnd() % 41u) - 20 - 23; - x[i] = m * u2f((uint32_t)(127 + e) << 23); - if (i % 97u == 5u) x[i] = 0.0f; - if (i % 131u == 7u) x[i] = -0.0f; - if (kind == 2 && i % 53u == 11u) x[i] = u2f(0x7fc00000u | (rnd() & 0xffffu)); - if (kind == 2 && i == n / 3) x[i] = u2f(0x7f800000u); - if (kind == 2 && i == n / 2 && n > 4) x[i] = u2f(0xff800000u); - } -} - -static const char *op_name(OmegaGpuRedOp op) { return op == OMEGA_GPU_RED_SUM ? "sum" : op == OMEGA_GPU_RED_MAX ? "max" : "min"; } - -/* ------------------------------------------------------------------ host only */ - -static int fake_fail(void *ctx, OmegaScanKind k, const uint32_t a[OMEGA_GPU_SCAN_ARGS_WORDS], uint32_t g) { - (void)ctx; (void)k; (void)a; (void)g; return -1; -} - -static void host_only(void) { - char w[200]; - float x[4] = { 1, 2, 3, 4 }, o; - check(omega_gpu_reduce(OMEGA_GPU_RED_SUM, x, 0, &o, NULL) == OMEGA_GPU_SCAN_BAD_ARGS, "reduce n = 0 refused"); - check(omega_gpu_reduce(OMEGA_GPU_RED_SUM, NULL, 4, &o, NULL) == OMEGA_GPU_SCAN_BAD_ARGS, "reduce NULL input refused"); - check(omega_gpu_reduce((OmegaGpuRedOp)7, x, 4, &o, NULL) == OMEGA_GPU_SCAN_BAD_ARGS, "reduce unknown op refused"); - check(omega_gpu_reduce(OMEGA_GPU_RED_SUM, x, OMEGA_GPU_SCAN_MAX_N + 1, &o, NULL) == OMEGA_GPU_SCAN_TOO_LARGE, "reduce 2^28 + 1 refused"); - check(omega_gpu_prefix_sum(x, 0, x, NULL) == OMEGA_GPU_SCAN_BAD_ARGS, "prefix n = 0 refused"); - check(omega_gpu_prefix_sum(x, OMEGA_GPU_SCAN_MAX_N + 1, x, NULL) == OMEGA_GPU_SCAN_TOO_LARGE, "prefix 2^28 + 1 refused"); - uint64_t r; - check(omega_gpu_scan_drive_reduce(OMEGA_GPU_RED_SUM, 100, 0, 0, &r, fake_fail, NULL, NULL) == OMEGA_GPU_SCAN_CHIP_FAIL, "a failed launch is reported (reduce)"); - check(omega_gpu_scan_drive_prefix(100, 0, 0, 0, fake_fail, NULL, NULL) == OMEGA_GPU_SCAN_CHIP_FAIL, "a failed launch is reported (prefix)"); - - for (int mut = 0; mut <= 3; mut++) - for (int k = 0; k < OMEGA_SCAN_K_COUNT; k++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); - OmegaScanSpec s = { (OmegaScanKind)k, mut }; - int rc = omega_gpu_scan_codegen(&s, p); - size_t bytes = rc == 0 ? omega_bw_program_code_bytes(p) : 0; - uint8_t *code = bytes ? malloc(bytes) : NULL; - OmegaBlackwellKernel kk; memset(&kk, 0, sizeof kk); - int enc = code ? omega_blackwell_kernel_encode_into(p, code, bytes, &kk) : -1; - snprintf(w, sizeof w, "kernel %d mutant %d through codegen and encoder (%zu bytes, %u gprs)", k, mut, bytes, (unsigned)kk.gpr_count); - check(rc == 0 && enc == 0 && kk.code_size == bytes, w); - if (mut == 0 && rc == 0) printf("kernel %d: %u insns, %zu bytes, %u gprs\n", k, (unsigned)p->count, bytes, (unsigned)kk.gpr_count); - free(code); free(p); - } - - /* the references against exact sums: integers in [-1000, 1000], n <= 16384, every partial sum below 2^24 */ - static float a[16384], y[16384]; - const size_t ns[] = { 1, 2, 31, 32, 33, 63, 64, 65, 1023, 1024, 1025, 1057, 16384 }; - for (size_t t = 0; t < sizeof ns / sizeof ns[0]; t++) { - size_t n = ns[t]; - fill(a, n, 0, n); - double s = 0, mx = -1e9, mn = 1e9; - for (size_t i = 0; i < n; i++) { s += a[i]; if (a[i] > mx) mx = a[i]; if (a[i] < mn) mn = a[i]; } - float rs, rmx, rmn; - int ok = omega_gpu_reduce_reference(OMEGA_GPU_RED_SUM, a, n, &rs) == 0 && omega_gpu_reduce_reference(OMEGA_GPU_RED_MAX, a, n, &rmx) == 0 && - omega_gpu_reduce_reference(OMEGA_GPU_RED_MIN, a, n, &rmn) == 0; - snprintf(w, sizeof w, "reference sum/max/min exact at n = %zu", n); - check(ok && rs == (float)s && rmx == (float)mx && rmn == (float)mn, w); - ok = omega_gpu_prefix_sum_reference(a, n, y) == 0; - double run = 0; size_t bad = 0; - for (size_t i = 0; i < n; i++) { run += a[i]; bad += y[i] != (float)run; } - snprintf(w, sizeof w, "reference prefix sum exact at n = %zu (%zu wrong)", n, bad); - check(ok && bad == 0, w); - } - - /* the reduction reference is the E1 order: equal bit for bit to omega_reduce_reference on any input */ - static float b[300000]; - const size_t ms[] = { 1, 2, 17, 32, 33, 100, 1000, 1024, 1025, 4097, 32768, 32769, 299999 }; - for (int kind = 1; kind <= 2; kind++) - for (size_t t = 0; t < sizeof ms / sizeof ms[0]; t++) - for (int op = 0; op < 3; op++) { - size_t n = ms[t]; - fill(b, n, kind, n * 3 + (size_t)op); - float mine, e1; - int ok = omega_gpu_reduce_reference((OmegaGpuRedOp)op, b, n, &mine) == 0 && omega_reduce_reference((OmegaReduceOp)op, b, n, &e1) == 0; - snprintf(w, sizeof w, "reference %s equals the E1 reference, inputs %d, n = %zu (%08x vs %08x)", op_name(op), kind, n, f2u(mine), f2u(e1)); - check(ok && same(mine, e1), w); - } - - /* the frozen order is a real order: summing left to right gives a different answer on mixed inputs */ - fill(b, 4097, 1, 99); - float tree, seq = -0.0f; - for (size_t i = 0; i < 4097; i++) seq += b[i]; - omega_gpu_reduce_reference(OMEGA_GPU_RED_SUM, b, 4097, &tree); - check(f2u(tree) != f2u(seq), "the frozen tree differs from a left-to-right sum (the order is pinned, not luck)"); -} - -/* ------------------------------------------------------------------ the simulator */ - -typedef struct { - BlackwellIRProgram *prog[OMEGA_SCAN_K_COUNT]; - int order; - WsRange ranges[3]; - char err[260]; -} SimCtx; - -static int sim_launch(void *ctx, OmegaScanKind k, const uint32_t a[OMEGA_GPU_SCAN_ARGS_WORDS], uint32_t grid_x) { - SimCtx *c = ctx; - static WsSim s; - memset(&s, 0, sizeof s); - s.p = c->prog[k]; s.threads = OMEGA_GPU_SCAN_THREADS; s.order = c->order; - for (unsigned i = 0; i < OMEGA_GPU_SCAN_ARGS_WORDS; i++) s.cbank[0x380 / 4 + i] = a[i]; - memcpy(s.ranges, c->ranges, sizeof c->ranges); s.nranges = 3; - if (ws_run(&s, grid_x, 1) != 0) { snprintf(c->err, sizeof c->err, "kernel %d: %s at pc %d", (int)k, s.msg, s.err_pc); return -1; } - return 0; -} - -static int sim_build(SimCtx *c, int mutant) { - for (int k = 0; k < OMEGA_SCAN_K_COUNT; k++) { - c->prog[k] = calloc(1, sizeof *c->prog[k]); - OmegaScanSpec s = { (OmegaScanKind)k, mutant }; - if (!c->prog[k] || omega_gpu_scan_codegen(&s, c->prog[k]) != 0) return -1; - } - return 0; -} -static void sim_free(SimCtx *c) { for (int k = 0; k < OMEGA_SCAN_K_COUNT; k++) free(c->prog[k]); } - -#define POISON 0x7fa00badu -static void poison(float *p, size_t n) { for (size_t i = 0; i < n; i++) memcpy(&p[i], &(uint32_t){ POISON }, 4); } - -/* one reduction through the simulator; 0 when it ran, the result in *out */ -static int sim_reduce(SimCtx *c, OmegaGpuRedOp op, const float *x, size_t n, float *out) { - size_t sw = omega_gpu_scan_reduce_scratch_words(n); - float *scr = malloc(sw * 4u); - poison(scr, sw); - c->ranges[0] = (WsRange){ (uintptr_t)x, (uintptr_t)(x + n) }; - c->ranges[1] = (WsRange){ (uintptr_t)scr, (uintptr_t)(scr + sw) }; - c->ranges[2] = c->ranges[1]; - uint64_t res = 0; - int rc = omega_gpu_scan_drive_reduce(op, n, (uintptr_t)x, (uintptr_t)scr, &res, sim_launch, c, NULL); - if (rc == 0) { memcpy(out, (const void *)(uintptr_t)res, 4); if (f2u(*out) == POISON) rc = -9; } - free(scr); - return rc; -} - -static int sim_prefix(SimCtx *c, const float *x, size_t n, float *y) { - size_t sw = omega_gpu_scan_prefix_scratch_words(n); - float *scr = malloc(sw * 4u); - poison(scr, sw); poison(y, n); - c->ranges[0] = (WsRange){ (uintptr_t)x, (uintptr_t)(x + n) }; - c->ranges[1] = (WsRange){ (uintptr_t)y, (uintptr_t)(y + n) }; - c->ranges[2] = (WsRange){ (uintptr_t)scr, (uintptr_t)(scr + sw) }; - int rc = omega_gpu_scan_drive_prefix(n, (uintptr_t)x, (uintptr_t)y, (uintptr_t)scr, sim_launch, c, NULL); - for (size_t i = 0; rc == 0 && i < n; i++) if (f2u(y[i]) == POISON) rc = -9; - free(scr); - return rc; -} - -static size_t diff(const float *a, const float *b, size_t n, size_t *first) { - size_t d = 0; - for (size_t i = 0; i < n; i++) if (!same(a[i], b[i])) { if (!d) *first = i; d++; } - return d; -} - -static void sim_tier(void) { - char w[600]; - static size_t ns[200]; size_t nn = 0; - for (size_t n = 1; n <= 70; n++) ns[nn++] = n; - const size_t more[] = { 255, 256, 257, 1000, 1023, 1024, 1025, 2047, 2048, 2049, 32767, 32768, 32769, 40000, 270000 }; - for (size_t i = 0; i < sizeof more / sizeof more[0]; i++) ns[nn++] = more[i]; - float *x = malloc(270000 * 4u), *y = malloc(270000 * 4u), *ref = malloc(270000 * 4u); - SimCtx c; memset(&c, 0, sizeof c); - check(sim_build(&c, 0) == 0, "simulator: all kernels built"); - for (int order = 0; order <= 1; order++) { - c.order = order; - size_t bad_red = 0, bad_pre = 0, runs = 0; - for (size_t t = 0; t < nn; t++) { - size_t n = ns[t]; - if (order == 1 && n > 40000) continue; - int kind = (int)(t % 3); - fill(x, n, kind, n * 7 + (size_t)order); - for (int op = 0; op < 3; op++) { - float got, want; - omega_gpu_reduce_reference((OmegaGpuRedOp)op, x, n, &want); - int rc = sim_reduce(&c, (OmegaGpuRedOp)op, x, n, &got); - runs++; - if (rc != 0 || !same(got, want)) { - bad_red++; - snprintf(w, sizeof w, "sim order %d %s n = %zu: rc %d got %08x want %08x %s", order, op_name(op), n, rc, f2u(got), f2u(want), c.err); - check(0, w); - } - } - omega_gpu_prefix_sum_reference(x, n, ref); - int rc = sim_prefix(&c, x, n, y); - size_t first = 0, d = rc == 0 ? diff(y, ref, n, &first) : n; - runs++; - if (rc != 0 || d) { - bad_pre++; - snprintf(w, sizeof w, "sim order %d prefix n = %zu: rc %d, %zu wrong, first at %zu (%08x vs %08x) %s", order, n, rc, d, first, - f2u(y[first]), f2u(ref[first]), c.err); - check(0, w); - } - } - snprintf(w, sizeof w, "simulator order %d: %zu runs, reductions wrong %zu, prefix sums wrong %zu", order, runs, bad_red, bad_pre); - check(bad_red == 0 && bad_pre == 0, w); - printf("%s\n", w); - } - sim_free(&c); - - /* red checks: each mutant must change a result the real kernels get right */ - for (int mut = 1; mut <= 3; mut++) { - SimCtx m; memset(&m, 0, sizeof m); - int built = sim_build(&m, mut) == 0, caught = 0; - const size_t n = 1000; - fill(x, n, 1, 4242); - if (built && mut == 1) { - for (int op = 0; op < 3 && !caught; op++) { - float got = 0, want; omega_gpu_reduce_reference((OmegaGpuRedOp)op, x, n, &want); - caught = sim_reduce(&m, (OmegaGpuRedOp)op, x, n, &got) != 0 || !same(got, want); - } - } else if (built) { - omega_gpu_prefix_sum_reference(x, n, ref); - size_t first; - caught = sim_prefix(&m, x, n, y) != 0 || diff(y, ref, n, &first) != 0; - } - snprintf(w, sizeof w, "simulator red check: mutant %d is caught", mut); - check(built && caught, w); - sim_free(&m); - } - free(x); free(y); free(ref); -} - -/* ------------------------------------------------------------------ the chip */ - -static size_t mem_available(void) { - FILE *f = fopen("/proc/meminfo", "r"); - char line[256]; size_t kb = 0; - while (f && fgets(line, sizeof line, f)) if (sscanf(line, "MemAvailable: %zu kB", &kb) == 1) break; - if (f) fclose(f); - return kb * 1024u; -} - -static float *g_x, *g_y, *g_ref; - -static void chip_one(size_t n, int kind, int verbose) { - char w[600]; - fill(g_x, n, kind, n * 11 + (size_t)kind); - for (int op = 0; op < 3; op++) { - float got = 0, want; OmegaGpuScanInfo info; - omega_gpu_reduce_reference((OmegaGpuRedOp)op, g_x, n, &want); - int rc = omega_gpu_reduce((OmegaGpuRedOp)op, g_x, n, &got, &info); - int ok = rc == 0 && same(got, want); - if (!ok || verbose) { - snprintf(w, sizeof w, "chip %s n = %zu inputs %d: %s, got %08x want %08x, %u launches, kernels %.3f ms%s%s", op_name(op), n, kind, - omega_gpu_scan_rc_name(rc), f2u(got), f2u(want), info.launches, info.elapsed_ns / 1e6, rc ? ": " : "", - rc ? omega_gpu_session_last_error() : ""); - if (ok) { g_checks++; printf("ok: %s\n", w); } else check(0, w); - } else g_checks++; - } - OmegaGpuScanInfo info; - omega_gpu_prefix_sum_reference(g_x, n, g_ref); - int rc = omega_gpu_prefix_sum(g_x, n, g_y, &info); - size_t first = 0, d = rc == 0 ? diff(g_y, g_ref, n, &first) : n; - if (rc || d || verbose) { - snprintf(w, sizeof w, "chip prefix n = %zu inputs %d: %s, %zu wrong (first at %zu), %u launches, kernels %.3f ms%s%s", n, kind, - omega_gpu_scan_rc_name(rc), d, first, info.launches, info.elapsed_ns / 1e6, rc ? ": " : "", rc ? omega_gpu_session_last_error() : ""); - if (!rc && !d) { g_checks++; printf("ok: %s\n", w); } else check(0, w); - } else g_checks++; -} - -static void chip_tier(unsigned max_log2) { - char w[200]; - size_t cap = (size_t)1 << max_log2; - if (cap > OMEGA_GPU_SCAN_MAX_N) cap = OMEGA_GPU_SCAN_MAX_N; - /* host: input, output, reference (3 x 4n); device buffer: in + out + scratch (~ 8n); plus 8 GiB for everyone else */ - size_t need = cap * 4u * 5u + ((size_t)8 << 30), have = mem_available(); - if (have < need) { - printf("NOT_RUN: MemAvailable %zu MiB < %zu MiB needed for n up to %zu\n", have >> 20, need >> 20, cap); - exit(2); - } - g_x = malloc(cap * 4u); g_y = malloc(cap * 4u); g_ref = malloc(cap * 4u); - if (!g_x || !g_y || !g_ref) { printf("NOT_RUN: host allocation\n"); exit(2); } - - int before = g_failed; - for (size_t n = 1; n <= 2048; n++) chip_one(n, (int)(n % 3), 0); - printf("every n from 1 to 2048 (sum, max, min, prefix): %s\n", g_failed == before ? "PASS" : "FAIL"); - before = g_failed; - for (unsigned k = 11; k <= max_log2 && k <= 28; k++) { - size_t p = (size_t)1 << k; - chip_one(p - 1, 1, 0); - chip_one(p, 2, k >= 20); - if (p + 1 <= cap) chip_one(p + 1, 1, 0); - } - printf("2^k - 1, 2^k, 2^k + 1 up to 2^%u: %s\n", max_log2, g_failed == before ? "PASS" : "FAIL"); - before = g_failed; - g_rng = 0xc3c3c3c3ull; - for (int i = 0; i < 64; i++) { - size_t n = 2049 + (((size_t)rnd() << 16) ^ rnd()) % (cap > (1u << 24) ? (1u << 24) : cap - 2048); - chip_one(n, i % 3, 0); - } - printf("64 random lengths: %s\n", g_failed == before ? "PASS" : "FAIL"); - - for (int mut = 1; mut <= 3; mut++) { - omega_gpu_scan_test_set_mutant(mut); - const size_t n = 1000; - fill(g_x, n, 1, 4242); - int caught = 0; - if (mut == 1) { - for (int op = 0; op < 3 && !caught; op++) { - float got = 0, want; omega_gpu_reduce_reference((OmegaGpuRedOp)op, g_x, n, &want); - caught = omega_gpu_reduce((OmegaGpuRedOp)op, g_x, n, &got, NULL) != 0 || !same(got, want); - } - } else { - size_t first; - omega_gpu_prefix_sum_reference(g_x, n, g_ref); - caught = omega_gpu_prefix_sum(g_x, n, g_y, NULL) != 0 || diff(g_y, g_ref, n, &first) != 0; - } - snprintf(w, sizeof w, "chip red check: mutant %d is caught", mut); - check(caught, w); - } - omega_gpu_scan_test_set_mutant(0); - fill(g_x, 1000, 1, 4242); - omega_gpu_prefix_sum_reference(g_x, 1000, g_ref); - size_t first; - check(omega_gpu_prefix_sum(g_x, 1000, g_y, NULL) == 0 && diff(g_y, g_ref, 1000, &first) == 0, "the real kernels are right again after the red checks"); - omega_gpu_session_close(); /* the kernels go with the device (close hook); the next call builds them on a new one */ - check(omega_gpu_prefix_sum(g_x, 1000, g_y, NULL) == 0 && diff(g_y, g_ref, 1000, &first) == 0, "after the device closed and opened again the kernels are rebuilt and right"); - free(g_x); free(g_y); free(g_ref); -} - -int main(int argc, char **argv) { - const char *tier = "chip"; - unsigned max_log2 = 28; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) tier = "host"; - else if (!strcmp(argv[i], "--sim")) tier = "sim"; - else if (!strcmp(argv[i], "--max-log2") && i + 1 < argc) max_log2 = (unsigned)atoi(argv[++i]); - else { fprintf(stderr, "usage: %s [--host-only | --sim] [--max-log2 K]\n", argv[0]); return 2; } - } - if (max_log2 < 11 || max_log2 > 28) { fprintf(stderr, "--max-log2 must be 11..28\n"); return 2; } - if (!strcmp(tier, "host")) host_only(); - else if (!strcmp(tier, "sim")) { host_only(); sim_tier(); } - else chip_tier(max_log2); - if (g_failed) printf("C3 scan %s: FAIL (%d of %d)\n", tier, g_failed, g_checks); - else printf("C3 scan %s: PASS (%d checks)\n", tier, g_checks); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_serving_alloc_count_test.c b/tests/gpu_serving_alloc_count_test.c deleted file mode 100644 index 4d33328e5..000000000 --- a/tests/gpu_serving_alloc_count_test.c +++ /dev/null @@ -1,688 +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. - */ - -/* - * gpu_serving_alloc_count_test: MEASUREMENT of driver (RM) allocations and frees made by the real - * native GPU stack (session + matmul API + attention API) while it "serves" a Qwen3-4B-shaped - * sequence, on the simulated driver of tests/fake_m16_native.c. Host only, opens no device. - * - * Why: sovereign-core design note docs/design/gb10-weight-ownership.md (sc#277, sc PR #292) argues - * that omega still asks the driver for memory while serving, and that one refused request faults - * the GPU session for the rest of the process. This test counts those requests. - * - * What it asserts: only bookkeeping that is true today (the session opens once, the fake saw every - * request, no double free, nothing latched, the call mix is what the report says it is). It does - * NOT assert the allocation counts: they are printed as MEASURE lines. A later change that reserves - * serving memory up front would lower them and this test would still pass; the numbers in the PR - * that made it are the record of today's behaviour. - * - * What it does not model: the kernels. The fake runs in FK_KERNEL_SKIP mode, so launches are - * counted and complete, but no matmul or attention result is computed. The matmul API therefore - * reports its own poison check (CHIP_FAIL) and the attention API reports UNWRITTEN; those return - * codes are expected here and are not errors of the allocation path. Elementwise kernels (rmsnorm, - * rope, swiglu) are not exercised; the design note's audit says they stop allocating after the - * first full-size call. - * - * Shapes (Qwen3-4B): hidden 2560, 32 q heads, 8 kv heads, head_dim 128, intermediate 9728, - * vocab 151936, 36 layers. One resident tensor per distinct weight shape stands in for the 36 - * layers (resident-weight allocations are a load-time cost, counted in phase LOAD only). - * Call pattern per layer follows crates/aien-inference-abi/src/transformer_backend.rs: - * decode (m = 1): q, k, v, attention(seq), o, gate, up, down ; after the layers lm_head (m = 1) - * prefill chunk: the same with m = chunk rows (<= 128), attention once per token at seq = - * offset + t + 1, lm_head with m = 1 after the chunk - * CTA budget 256 (the daemon value in the audit). - */ -#include -#include -#include - -#include "fake_m16_native.h" -#include "nvrm.h" /* the session reaches the fake driver through the Linux reference platform (P07 cut C) */ -#include "omega_blackwell_codegen.h" /* omega_matmul_frag_block_shape: the kernel cache key */ -#include "omega_blackwell_matmul.h" /* omega_fp32_to_bf16 (update mode) */ -#include "omega_gpu_attention_api.h" -#include "omega_gpu_matmul_api.h" -#include "omega_gpu_serving.h" -#include "omega_gpu_session.h" - -/* The two driver symbols the session needs that the fake (written for the vector engine) lacks. */ -int nvrm_open(Nvrm *rm) { (void)rm; fk.device_open = 1; return 0; } -int nvrm_close(Nvrm *rm) { (void)rm; return 0; } -void nvrm_retire(Nvrm *rm, uint32_t upto) { (void)rm; (void)upto; } - -#define HID 2560u -#define QDIM 4096u -#define KVDIM 1024u -#define INTER 9728u -#define VOCAB 151936u -#define LAYERS 36u -#define QH 32u -#define KVH 8u -#define HD 128u -#define CHUNK 128u - -static int g_fail; -#define CHECK(c, ...) do { if (!(c)) { g_fail++; printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0) - -/* ---- the weights: one tensor per distinct shape ---- */ -static OmegaGpuTensor *W_Q, *W_K, *W_O, *W_G, *W_D, *W_LM; - -static OmegaGpuTensor *upload(uint32_t k, uint32_t n) { - uint16_t *z = calloc((size_t)k * n, sizeof *z); - OmegaGpuTensor *t = NULL; - CHECK(z != NULL, "calloc %ux%u", k, n); - int rc = z ? omega_gpu_tensor_upload_bf16(k, n, z, &t) : -1; - CHECK(rc == OMEGA_GPU_MATMUL_OK, "upload %ux%u rc=%d %s", k, n, rc, omega_gpu_matmul_last_error()); - free(z); - return t; -} - -/* ---- per-phase counters ---- */ -typedef struct { - const char *name; - int allocs, frees; - uint64_t alloc_bytes, free_bytes; - int mm_calls, mm_miss, mm_remiss, mm_other_allocs; /* code-cache misses; misses on an already-seen shape; scratch growth */ - int at_calls, at_allocs; - int a0, f0; /* log positions at phase start */ -} Phase; - -/* The matmul API's kernel cache key: (kp, np, grid_x, rt, ct). rt and ct follow from the call's padded shape - * (omega_matmul_frag_block_shape, the rule the API's launch_shape uses); since the blocked prefill kernel (#407) - * two calls with the same grid_x can need different kernels. */ -typedef struct { uint32_t kp, np, gx, rt, ct; } Key; -static Key g_seen[128]; -static int g_nseen; -static int seen(const OmegaGpuMatmulInfo *in) { - Key k = { in->padded_k, in->padded_n, in->grid_x, 0, 0 }; - omega_matmul_frag_block_shape(in->padded_m / 16u, in->padded_n / 8u, &k.rt, &k.ct); - for (int i = 0; i < g_nseen; i++) - if (g_seen[i].kp == k.kp && g_seen[i].np == k.np && g_seen[i].gx == k.gx && g_seen[i].rt == k.rt && g_seen[i].ct == k.ct) return 1; - if (g_nseen < 128) g_seen[g_nseen++] = k; - return 0; -} - -static Phase *P; /* current phase */ -static int g_rc_mm_ok, g_rc_mm_chipfail, g_rc_at_ok, g_rc_at_unwritten, g_rc_bad; - -static float *g_x, *g_y; /* activation in / result out, sized for CHUNK x INTER and CHUNK x VOCAB-free */ -static float *g_logits; /* 1 x VOCAB */ -static float *g_k, *g_v; /* host KV for the attention call, 4096 x 1024 f32 each */ -static float g_q[QDIM], g_attn[QDIM]; - -static void mm(uint32_t m, const OmegaGpuTensor *w, float *out) { - uint32_t k, n; - omega_gpu_tensor_shape(w, &k, &n); - int a_before = fk.alloc_calls; - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_f32(m, g_x, w, out, &info); - int made = fk.alloc_calls - a_before; - P->mm_calls++; - if (rc == OMEGA_GPU_MATMUL_OK) g_rc_mm_ok++; - else if (rc == OMEGA_GPU_MATMUL_CHIP_FAIL) g_rc_mm_chipfail++; - else { g_rc_bad++; printf("unexpected matmul rc=%d (%s)\n", rc, omega_gpu_matmul_rc_name(rc)); } - int miss = info.kernel_cache_hit ? 0 : 1; /* at most one miss per launch; m <= 128 rows is one launch here */ - if (miss) { - P->mm_miss++; - if (seen(&info)) P->mm_remiss++; - } else { - (void)seen(&info); - } - P->mm_other_allocs += made - miss; -} - -static void attn(uint32_t seq) { - int a_before = fk.alloc_calls; - OmegaGpuAttnInfo info; - int rc = omega_gpu_gqa_attention_f32(g_q, g_k, g_v, seq, QH, KVH, HD, g_attn, &info); - P->at_calls++; - P->at_allocs += fk.alloc_calls - a_before; - if (rc == OMEGA_GPU_ATTN_OK) g_rc_at_ok++; - else if (rc == OMEGA_GPU_ATTN_UNWRITTEN) g_rc_at_unwritten++; - else { g_rc_bad++; printf("unexpected attention rc=%d (%s)\n", rc, omega_gpu_attention_rc_name(rc)); } -} - -/* One transformer step over `rows` rows of a sequence that already holds `offset` tokens. */ -static void step(uint32_t rows, uint32_t offset) { - for (uint32_t l = 0; l < LAYERS; l++) { - mm(rows, W_Q, g_y); mm(rows, W_K, g_y); mm(rows, W_K, g_y); - for (uint32_t t = 0; t < rows; t++) attn(offset + t + 1); - mm(rows, W_O, g_y); mm(rows, W_G, g_y); mm(rows, W_G, g_y); mm(rows, W_D, g_y); - } - mm(1, W_LM, g_logits); -} - -static void begin(Phase *p, const char *name) { - memset(p, 0, sizeof *p); - p->name = name; - p->a0 = fk.alloc_size_n; - p->f0 = fk.free_size_n; - p->allocs = fk.alloc_calls; /* start values, turned into deltas by end() */ - p->frees = fk.free_calls; - P = p; -} - -static void sizes(const char *kind, const uint64_t *log, int from, int to) { - /* distinct sizes with counts, in order of first appearance, at most 6 shown */ - uint64_t seen_sz[256]; int cnt[256]; int ns = 0; - for (int i = from; i < to && i < FK_SIZE_LOG; i++) { - int j; - for (j = 0; j < ns; j++) if (seen_sz[j] == log[i]) break; - if (j == ns && ns < 256) { seen_sz[ns] = log[i]; cnt[ns] = 0; ns++; } - if (j < 256) cnt[j]++; - } - printf("MEASURE %s sizes (%d distinct):", kind, ns); - for (int j = 0; j < ns && j < 6; j++) printf(" %llux%d", (unsigned long long)seen_sz[j], cnt[j]); - if (ns > 6) printf(" ... last %llux%d", (unsigned long long)seen_sz[ns - 1], cnt[ns - 1]); - printf("\n"); -} - -static void end(Phase *p, int sized) { - int a1 = fk.alloc_size_n, f1 = fk.free_size_n; - p->allocs = fk.alloc_calls - p->allocs; - p->frees = fk.free_calls - p->frees; - for (int i = p->a0; i < a1 && i < FK_SIZE_LOG; i++) p->alloc_bytes += fk.alloc_size_log[i]; - for (int i = p->f0; i < f1 && i < FK_SIZE_LOG; i++) p->free_bytes += fk.free_size_log[i]; - printf("MEASURE phase %-22s allocs %4d frees %4d alloc_bytes %12llu matmul_calls %5d (code-cache misses %d, of which on a shape seen before %d, other scratch growth %d) attention_calls %5d (allocs %d)\n", - p->name, p->allocs, p->frees, (unsigned long long)p->alloc_bytes, p->mm_calls, p->mm_miss, p->mm_remiss, p->mm_other_allocs, - p->at_calls, p->at_allocs); - if (sized && p->allocs) { sizes("alloc", fk.alloc_size_log, p->a0, a1); sizes("free ", fk.free_size_log, p->f0, f1); } - CHECK(a1 <= FK_SIZE_LOG && f1 <= FK_SIZE_LOG, "size log overflow (%d allocs, %d frees)", a1, f1); -} - -static const OmegaGpuServingBounds QWEN3_4B_BOUNDS = { - .max_context = 4096, .max_seqs = 1, .num_q_heads = QH, .num_kv_heads = KVH, .head_dim = HD, .kv_block_size = 16, - .max_rows = CHUNK, .max_k = INTER, .max_n = INTER, .max_n_one_row = VOCAB, .kernel_slots = 32, -}; - -/* Bounds mode: a tiny reservation, then calls inside it (no driver traffic) and past it (refused loudly). */ -static int paged_call(uint32_t bs, uint32_t ctx); -static int attn_ran(int rc); - -static int bounds_mode(void) { - OmegaGpuServingBounds b = QWEN3_4B_BOUNDS; - b.max_context = 256; b.max_rows = 32; b.max_k = HID; b.max_n = QDIM; b.max_n_one_row = 0; - Phase ph; begin(&ph, "BOUNDS"); /* sets P for mm()/attn() */ - W_Q = upload(HID, QDIM); - attn(1); mm(1, W_Q, g_y); /* warm kernels at small size */ - CHECK(omega_gpu_reserve_serving(&b) == 0, "reserve failed: %s", omega_gpu_matmul_last_error()); - mm(1, W_Q, g_y); mm(17, W_Q, g_y); mm(32, W_Q, g_y); attn(256); /* warm each shape once (reserving a deeper kernel cache restarts it empty) */ - const int a0 = fk.alloc_calls, f0 = fk.free_calls; - mm(1, W_Q, g_y); mm(17, W_Q, g_y); mm(32, W_Q, g_y); attn(1); attn(100); attn(256); - CHECK(fk.alloc_calls == a0 && fk.free_calls == f0, "calls inside the bounds touched the driver (%d allocs, %d frees)", fk.alloc_calls - a0, fk.free_calls - f0); - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_f32(33, g_x, W_Q, g_y, &info); /* 33 rows -> 48 padded: past 32 */ - CHECK(rc == OMEGA_GPU_MATMUL_TOO_LARGE, "33 rows past a 32-row reservation: rc=%d (%s)", rc, omega_gpu_matmul_rc_name(rc)); - CHECK(strstr(omega_gpu_matmul_last_error(), "serving reservation exceeded") != NULL, "matmul error text: \"%s\"", omega_gpu_matmul_last_error()); - rc = omega_gpu_gqa_attention_f32(g_q, g_k, g_v, 257, QH, KVH, HD, g_attn, NULL); - CHECK(rc == OMEGA_GPU_ATTN_TOO_LARGE, "context 257 past a 256 reservation: rc=%d (%s)", rc, omega_gpu_attention_rc_name(rc)); - CHECK(strstr(omega_gpu_attention_last_error(), "serving reservation exceeded") != NULL, "attention error text: \"%s\"", omega_gpu_attention_last_error()); - CHECK(fk.alloc_calls == a0 && fk.free_calls == f0, "a refused call touched the driver (%d allocs, %d frees)", fk.alloc_calls - a0, fk.free_calls - f0); - CHECK(!omega_gpu_matmul_is_blocked() && !omega_gpu_session_is_blocked(), "a refusal latched the session"); - mm(32, W_Q, g_y); attn(256); /* still serves after a refusal */ - CHECK(fk.alloc_calls == a0, "serving after a refusal allocated"); - /* paged bf16 attention (the sovereign-core path): 512 tokens = 32 blocks of 16 = exactly the reserved bytes */ - /* build each paged kernel the checked calls use: the split count is part of the kernel (cut F/J, own_log2split), - * 16 tokens run split 0 and 512 tokens split 2, and the attention kernel cache is outside the reservation - * (omega_gpu_serving.h, "Not covered") */ - (void)paged_call(16, 16); (void)paged_call(16, 512); - const int p0 = fk.alloc_calls, pf0 = fk.free_calls; - rc = paged_call(16, 16); CHECK(attn_ran(rc), "paged 16 tokens in bounds: rc=%d (%s)", rc, omega_gpu_attention_last_error()); - rc = paged_call(16, 512); CHECK(attn_ran(rc), "paged 512 tokens (exactly the bound) refused: rc=%d (%s)", rc, omega_gpu_attention_last_error()); - CHECK(fk.alloc_calls == p0 && fk.free_calls == pf0, "in-bounds paged calls touched the driver (%d allocs, %d frees)", fk.alloc_calls - p0, fk.free_calls - pf0); - rc = paged_call(16, 513); CHECK(rc == OMEGA_GPU_ATTN_TOO_LARGE, "paged 513 tokens (bound+1): rc=%d", rc); - CHECK(strstr(omega_gpu_attention_last_error(), "serving reservation exceeded") != NULL, "paged error text: \"%s\"", omega_gpu_attention_last_error()); - CHECK(fk.alloc_calls == p0 && fk.free_calls == pf0, "a refused paged call touched the driver"); - omega_gpu_serving_release(); /* lifted: growth is allowed again */ - rc = omega_gpu_gqa_attention_f32(g_q, g_k, g_v, 257, QH, KVH, HD, g_attn, NULL); - CHECK(rc == OMEGA_GPU_ATTN_OK || rc == OMEGA_GPU_ATTN_UNWRITTEN, "after release, context 257 rc=%d", rc); - CHECK(fk.alloc_calls > a0, "after release, growth did not allocate"); - printf("MEASURE bounds: refused calls made 0 driver allocations; 33 rows -> TOO_LARGE, ctx 257 -> TOO_LARGE; error \"%s\"\n", "serving reservation exceeded: ..."); - omega_gpu_tensor_free(W_Q); - omega_gpu_device_close(); - CHECK(fk.live_at_close == 0, "leak: %d", fk.live_at_close); - printf("gpu_serving_alloc_count_test bounds: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - -/* Paged bf16 attention call over `ctx` tokens of a one-layer pool of `bs`-token blocks (the path sovereign-core uses). */ -static int paged_call(uint32_t bs, uint32_t ctx) { - const uint32_t nb = (ctx + bs - 1) / bs; - OmegaGpuKvLayout ly; - ly.head_stride_bytes = (uint64_t)HD * 2; ly.token_stride_bytes = ly.head_stride_bytes * KVH; - ly.kv_plane_stride_bytes = ly.token_stride_bytes * bs; ly.layer_stride_bytes = 2 * ly.kv_plane_stride_bytes; - ly.block_stride_bytes = ly.layer_stride_bytes; ly.pool_bytes = ly.block_stride_bytes * nb; - ly.num_blocks = nb; ly.num_layers = 1; ly.block_size = bs; - uint8_t *pool = calloc(1, (size_t)ly.pool_bytes); - uint32_t *ids = calloc(nb, sizeof *ids); - CHECK(pool && ids, "paged host buffers"); - int rc = OMEGA_GPU_ATTN_BAD_ARGS; - if (pool && ids) { - for (uint32_t i = 0; i < nb; i++) ids[i] = i; - rc = omega_gpu_paged_attention_bf16(g_q, pool, &ly, ids, nb, ctx, 0, QH, KVH, HD, g_attn, NULL); - } - free(pool); free(ids); - return rc; -} -static int attn_ran(int rc) { return rc == OMEGA_GPU_ATTN_OK || rc == OMEGA_GPU_ATTN_UNWRITTEN; } - -/* Under half a block of context: the paged path stages a whole block, more than the f32 formula (review item 1). */ -static int bounds_block_mode(void) { - OmegaGpuServingBounds b = QWEN3_4B_BOUNDS; - b.max_context = 16; b.kv_block_size = 64; b.max_rows = 16; b.max_k = HID; b.max_n = QDIM; b.max_n_one_row = 0; - Phase ph; begin(&ph, "BOUNDS-BLOCK"); - W_Q = upload(HID, QDIM); - CHECK(omega_gpu_reserve_serving(&b) == 0, "reserve failed: %s", omega_gpu_matmul_last_error()); - int rc = paged_call(64, 16); /* first paged call builds the kernel (one code buffer); no pre-reserve call, it would raise the pool high-water mark */ - CHECK(attn_ran(rc), "paged call of 16 tokens in one 64-token block refused: rc=%d (%s)", rc, omega_gpu_attention_last_error()); - const int a0 = fk.alloc_calls, f0 = fk.free_calls; - rc = paged_call(64, 64); - CHECK(attn_ran(rc), "paged call of exactly one block (the byte bound) refused: rc=%d (%s)", rc, omega_gpu_attention_last_error()); - CHECK(fk.alloc_calls == a0 && fk.free_calls == f0, "in-bounds paged calls touched the driver"); - rc = paged_call(64, 65); - CHECK(rc == OMEGA_GPU_ATTN_TOO_LARGE, "two blocks past a one-block reservation: rc=%d", rc); - CHECK(fk.alloc_calls == a0 && fk.free_calls == f0, "refused paged call touched the driver"); - printf("MEASURE bounds-block: 16 and 64 tokens (one 64-token block) served with 0 driver traffic; 65 tokens -> TOO_LARGE\n"); - omega_gpu_tensor_free(W_Q); - omega_gpu_device_close(); - CHECK(fk.live_at_close == 0, "leak: %d", fk.live_at_close); - printf("gpu_serving_alloc_count_test bounds-block: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - -/* A reserve that fails part way must leave nothing flagged (review item 2). Sweep the failing driver request over every - * allocation the reserve makes (pool, q, out, table, activation, result), on a freshly opened device each time; the - * control (no injected failure) must leave the reservation active. */ -static int rollback_mode(void) { - OmegaGpuServingBounds b = QWEN3_4B_BOUNDS; - b.max_context = 256; b.kv_block_size = 16; b.max_rows = 32; b.max_k = HID; b.max_n = QDIM; b.max_n_one_row = 0; b.kernel_slots = 0; - Phase ph; begin(&ph, "ROLLBACK"); - int failed_reserves = 0; - /* n = 100 first: the un-injected control, before the probes of the failing runs raise the buffers' high-water marks */ - const int sweep[] = { 100, 1, 2, 3, 4, 5, 6 }; - for (unsigned si = 0; si < sizeof sweep / sizeof sweep[0]; si++) { - const int n = sweep[si]; - W_Q = upload(HID, QDIM); /* opens the session (its own allocations come first) */ - fk.alloc_mode = FK_ALLOC_FAIL; - fk.alloc_fail_nth = fk.alloc_calls + n; - int rc = omega_gpu_reserve_serving(&b); - fk.alloc_fail_nth = 0; - /* probes that need more than the reservation: refused only if something is still flagged */ - /* each probe is larger than every earlier one, so a buffer that is still flagged is refused even though the high-water mark carries over */ - int ra = omega_gpu_gqa_attention_f32(g_q, g_k, g_v, si ? 300 + 500 * si : 257, QH, KVH, HD, g_attn, NULL); - int refused_attn = ra == OMEGA_GPU_ATTN_TOO_LARGE && strstr(omega_gpu_attention_last_error(), "serving reservation exceeded") != NULL; - OmegaGpuMatmulInfo info; - int rm = omega_gpu_matmul_resident_f32(si ? 32 + 16 * si : 48, g_x, W_Q, g_y, &info); - int refused_mm = rm == OMEGA_GPU_MATMUL_TOO_LARGE && strstr(omega_gpu_matmul_last_error(), "serving reservation exceeded") != NULL; - if (rc != 0) { - failed_reserves++; - CHECK(!refused_attn && !refused_mm, "failed reserve (injected fail on its request %d, rc=%d) left a reservation flagged: attention %d matmul %d", n, rc, refused_attn, refused_mm); - } else { - CHECK(refused_attn && refused_mm, "control (request %d never failed, reserve ok): the reservation should be active, attention %d matmul %d", n, refused_attn, refused_mm); - } - omega_gpu_tensor_free(W_Q); - omega_gpu_device_close(); - } - CHECK(failed_reserves >= 6, "only %d of the sweep's reserves failed (expected the 6 buffer requests)", failed_reserves); - CHECK(fk.live_at_close == 0, "leak: %d", fk.live_at_close); - printf("MEASURE rollback: %d injected failures during reserve, none left anything flagged; the un-injected control stayed reserved\n", failed_reserves); - printf("gpu_serving_alloc_count_test rollback: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - -/* mode: "plain" (default) = today's measurement, no reservation; "reserve" = reserve after warm-up and - * ASSERT zero driver traffic while serving; "reserve-skip" = the same asserts without the call (must FAIL: the red run); - * "bounds" = refusal behaviour. */ -/* ---- sweep: the sovereign-core daemon's bounds (sc#311, sc#277). Every row count 1..256 over every weight - * shape is a distinct (kp, np, grid_x) for some rows, because grid_x is baked into the kernel and depends on - * the row tiles. prepare = 1: prepare each (rows, shape) and seal, then serving must make no driver call and an - * unprepared shape is refused. prepare = 0 (control, kernel_slots 32 as before): the cache wraps and serving - * allocates, which this mode must report as a failure. */ -#define SWEEP_ROWS 256u -static int sweep_mode(int prepare) { - W_Q = upload(HID, QDIM); W_K = upload(HID, KVDIM); W_O = upload(QDIM, HID); - W_G = upload(HID, INTER); W_D = upload(INTER, HID); W_LM = upload(HID, VOCAB); - OmegaGpuTensor *odd = upload(HID, 512); /* a shape the server never prepares */ - OmegaGpuTensor *w[6] = {W_Q, W_K, W_O, W_G, W_D, W_LM}; - float *x = calloc((size_t)SWEEP_ROWS * INTER, sizeof *x), *y = calloc((size_t)SWEEP_ROWS * VOCAB, sizeof *y); - CHECK(x && y, "sweep buffers"); - if (g_fail) return 1; - OmegaGpuServingBounds b = QWEN3_4B_BOUNDS; - b.max_rows = SWEEP_ROWS; b.max_n = VOCAB; b.max_n_one_row = VOCAB; b.kernel_slots = prepare ? 128 : 32; - CHECK(omega_gpu_reserve_serving(&b) == 0, "reserve failed: %s", omega_gpu_matmul_last_error()); - int prepared = -1; /* code buffers the prepare pass made: one per distinct kernel */ - if (prepare) { - int a0 = fk.alloc_calls; - for (unsigned i = 0; i < 6; i++) { - uint32_t k, n; - omega_gpu_tensor_shape(w[i], &k, &n); - for (uint32_t m = 1; m <= SWEEP_ROWS; m++) { - int rc = omega_gpu_matmul_prepare(m, k, n); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "prepare m=%u %ux%u rc=%d %s", m, k, n, rc, omega_gpu_matmul_last_error()); - } - } - prepared = fk.alloc_calls - a0; - printf("MEASURE sweep prepare: %d driver allocations (one code buffer per distinct kernel)\n", prepared); - omega_gpu_serving_seal(); - } - g_nseen = 0; - OmegaGpuAllocStats st0, st1; - omega_gpu_session_alloc_stats(&st0); - int a0 = fk.alloc_calls, too_large = 0, other = 0; - for (unsigned pass = 0; pass < 2; pass++) - for (uint32_t m = 1; m <= SWEEP_ROWS; m++) - for (unsigned i = 0; i < 6; i++) { - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_f32(m, x, w[i], y, &info); - if (rc == OMEGA_GPU_MATMUL_TOO_LARGE) too_large++; - else if (rc != OMEGA_GPU_MATMUL_OK && rc != OMEGA_GPU_MATMUL_CHIP_FAIL) other++; /* CHIP_FAIL = fake kernel skips writes */ - if (rc != OMEGA_GPU_MATMUL_TOO_LARGE) (void)seen(&info); - } - int made = fk.alloc_calls - a0; - omega_gpu_session_alloc_stats(&st1); - CHECK((int)(st1.allocs - st0.allocs) == made, "session alloc stats %llu != driver %d", - (unsigned long long)(st1.allocs - st0.allocs), made); - printf("MEASURE sweep serving (rows 1..%u x 6 shapes, twice): %d driver allocations, %d distinct kernels, %d refused, %d other\n", - SWEEP_ROWS, made, g_nseen, too_large, other); - CHECK(made == 0, "serving made %d driver allocations", made); - CHECK(too_large == 0 && other == 0, "serving refused %d, other rc %d", too_large, other); - /* measured: 95 before the blocked prefill kernel (#407), 83 with it (keyed with rt, ct; lm_head stays - * on the single-tile kernel, its rt > 1 store offset does not fit the 24-bit immediate) */ - CHECK(g_nseen == 83, "distinct kernels %d, expected 83 for Qwen3-4B at CTA budget 256", g_nseen); - CHECK(prepared < 0 || prepared == g_nseen, "prepare built %d kernels, serving used %d distinct", prepared, g_nseen); - if (prepare) { - int a1 = fk.alloc_calls; - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_f32(1, x, odd, y, &info); - CHECK(rc == OMEGA_GPU_MATMUL_TOO_LARGE && strstr(omega_gpu_matmul_last_error(), "not prepared"), - "unprepared shape rc=%d %s", rc, omega_gpu_matmul_last_error()); - CHECK(fk.alloc_calls == a1, "unprepared shape asked the driver for memory"); - omega_gpu_serving_release(); - rc = omega_gpu_matmul_resident_f32(1, x, odd, y, &info); - CHECK(rc != OMEGA_GPU_MATMUL_TOO_LARGE, "release did not lift the seal: %s", omega_gpu_matmul_last_error()); - } - free(x); free(y); - printf("gpu_serving_alloc_count_test sweep%s: %s (%d failed checks)\n", prepare ? "" : "-skip", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - -/* ---- pin: a full cache of prepared kernels is never evicted. 8 slots, 8 prepared kernels (W_Q at 16..144 rows: - * 9 row counts; since the blocked prefill kernel (#407) 64 and 128 rows share one kernel, rt 4 x ct 4 at grid_x 128), - * then an unprepared call BEFORE any seal must be refused with no driver call, and every prepared kernel must still hit. */ -static int pin_mode(void) { - W_Q = upload(HID, QDIM); W_K = upload(HID, KVDIM); - float *x = calloc((size_t)144 * HID, sizeof *x), *y = calloc((size_t)144 * QDIM, sizeof *y); - CHECK(x && y, "pin buffers"); - if (g_fail) return 1; - OmegaGpuServingBounds b = QWEN3_4B_BOUNDS; - b.max_rows = 144; b.kernel_slots = 8; - CHECK(omega_gpu_reserve_serving(&b) == 0, "reserve failed: %s", omega_gpu_matmul_last_error()); - const int ap = fk.alloc_calls; - for (uint32_t m = 16; m <= 144; m += 16) { - int rc = omega_gpu_matmul_prepare(m, HID, QDIM); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "prepare m=%u rc=%d %s", m, rc, omega_gpu_matmul_last_error()); - } - CHECK(fk.alloc_calls - ap == 8, "premise: prepare built %d kernels, the cache holds 8", fk.alloc_calls - ap); - int a0 = fk.alloc_calls; - OmegaGpuMatmulInfo info; - int rc = omega_gpu_matmul_resident_f32(1, x, W_K, y, &info); - CHECK(rc == OMEGA_GPU_MATMUL_TOO_LARGE && strstr(omega_gpu_matmul_last_error(), "prepared kernel"), - "unprepared call with a full pinned cache: rc=%d %s", rc, omega_gpu_matmul_last_error()); - CHECK(fk.alloc_calls == a0, "refused call asked the driver for memory"); - for (uint32_t m = 16; m <= 144; m += 16) { - rc = omega_gpu_matmul_resident_f32(m, x, W_Q, y, &info); - CHECK(rc != OMEGA_GPU_MATMUL_TOO_LARGE && info.kernel_cache_hit, "prepared m=%u evicted (rc=%d hit=%d)", m, rc, info.kernel_cache_hit); - } - CHECK(fk.alloc_calls == a0, "prepared kernels rebuilt: %d driver allocations", fk.alloc_calls - a0); - free(x); free(y); - printf("gpu_serving_alloc_count_test pin: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - - -/* Sealed without a serving reservation: the scratch buffers could still grow, so every matmul call - * must be refused by name before any driver allocation (review of omega#338). */ -static int seal_bare_mode(void) { - W_Q = upload(HID, QDIM); - float *x = calloc((size_t)144 * HID, sizeof *x), *y = calloc((size_t)144 * QDIM, sizeof *y); - CHECK(x && y, "seal-bare buffers"); - if (g_fail) return 1; - int rc = omega_gpu_matmul_prepare(16, HID, QDIM); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "prepare m=16 rc=%d %s", rc, omega_gpu_matmul_last_error()); - omega_gpu_matmul_seal(1); - int a0 = fk.alloc_calls; - OmegaGpuMatmulInfo info; - rc = omega_gpu_matmul_resident_f32(144, x, W_Q, y, &info); - CHECK(rc == OMEGA_GPU_MATMUL_TOO_LARGE && strstr(omega_gpu_matmul_last_error(), "without a scratch reservation"), - "sealed, unreserved, larger call: rc=%d %s", rc, omega_gpu_matmul_last_error()); - CHECK(fk.alloc_calls == a0, "sealed call without a reservation asked the driver for memory (%d)", fk.alloc_calls - a0); - omega_gpu_matmul_seal(0); - rc = omega_gpu_matmul_resident_f32(16, x, W_Q, y, &info); - CHECK(rc != OMEGA_GPU_MATMUL_TOO_LARGE, "unsealed call still refused: rc=%d %s", rc, omega_gpu_matmul_last_error()); - free(x); free(y); - printf("gpu_serving_alloc_count_test seal-bare: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} -/* update: omega_gpu_tensor_update_* re-packs new values into the tensor's own device buffer. The fake's device - * memory is host memory with GPU address = CPU address (fk.alloc_va), so the buffer is compared word for word - * with omega_matmul_frag_pack_b of the new values. Two shapes: 72 x 1100 (k pads to 80; n is not a multiple of - * 8 and spans three 64-tile chunks) and 4096 x 200 (the f32 staging holds 8 tiles at this k: four chunks, the - * last ragged). Per shape: the upload's one driver allocation is the GPU-uncached one, update_f32, update_bf16 - * back, update while sealed, no driver allocation or free, shape-mismatch refusals write nothing. Then NULL - * refusals and stale handles (closed device, then a reopened one). */ -static int upd_same(const uint16_t *d, const uint16_t *want, size_t cnt, const char *what) { - size_t diff = 0; - for (size_t i = 0; i < cnt; i++) diff += d[i] != want[i]; - CHECK(diff == 0, "%s: %zu of %zu packed words differ from omega_matmul_frag_pack_b", what, diff, cnt); - return diff == 0; -} -static OmegaGpuTensor *update_shape(uint32_t K, uint32_t N, uint16_t **b1_out, float **b2_out) { - const uint32_t KP = (K + 15u) / 16u * 16u, NT = (N + 7u) / 8u; - const size_t cnt = (size_t)K * N, packed = (size_t)KP * NT * 8u; - uint16_t *b1 = malloc(cnt * sizeof *b1), *b2h = malloc(cnt * sizeof *b2h), *want = malloc(packed * sizeof *want); - float *b2 = malloc(cnt * sizeof *b2); - CHECK(b1 && b2 && b2h && want, "update buffers %ux%u", K, N); - if (!b1 || !b2 || !b2h || !want) return NULL; - uint32_t s = 0x5eedu ^ K ^ (N << 16); - for (size_t i = 0; i < cnt; i++) { - s = s * 1664525u + 1013904223u; - b1[i] = omega_fp32_to_bf16(((float)(s >> 8) / 16777216.0f) - 0.5f); - b2[i] = ((float)(s % 2000003u) / 1000001.0f) - 1.0f + 1e-7f * (float)(i % 7u); /* low bits that rounding must drop */ - } - /* edge values for the update path's rounding: NaNs with payloads and sign, infinities, zeros, subnormals, - * exact ties (odd and even), the largest finite value (rounds to infinity) */ - static const uint32_t EDGE[] = {0x7fc00001u, 0xff800001u, 0x7fbfffffu, 0x7f800000u, 0xff800000u, 0x00000000u, 0x80000000u, - 0x00000001u, 0x807fffffu, 0x00018000u, 0x3f808000u, 0x3f818000u, 0xbf808000u, 0x7f7fffffu, 0xff7fffffu}; - for (size_t e = 0; e < sizeof EDGE / sizeof EDGE[0]; e++) for (size_t r = 0; r < 3; r++) { - const size_t i = r * (K / 3u) * N + (e * 73u + r) % N; /* rows 0, k/3, 2k/3; columns across the chunks */ - memcpy(&b2[i], &EDGE[e], 4); - } - for (size_t i = 0; i < cnt; i++) b2h[i] = omega_fp32_to_bf16(b2[i]); - - OmegaGpuTensor *t = NULL; - const int a0 = fk.alloc_calls, u0 = fk.uncached_calls; - int rc = omega_gpu_tensor_upload_bf16(K, N, b1, &t); - CHECK(rc == OMEGA_GPU_MATMUL_OK && fk.alloc_calls == a0 + 1 && a0 < 16, "premise %ux%u: upload rc=%d made %d allocations (index %d)", K, N, rc, fk.alloc_calls - a0, a0); - CHECK(fk.uncached_calls == u0 + 1, "%ux%u: the tensor's driver allocation was not the GPU-uncached one", K, N); - if (rc != OMEGA_GPU_MATMUL_OK || fk.alloc_calls != a0 + 1 || a0 >= 16) return NULL; - const uint16_t *d = (const uint16_t *)(uintptr_t)fk.alloc_va[a0]; - omega_matmul_frag_pack_b(b1, K, N, KP, 0, NT, want); - upd_same(d, want, packed, "premise: upload"); - - const int a1 = fk.alloc_calls, f1 = fk.free_calls; - CHECK(omega_gpu_tensor_update_f32(t, K + 1u, N, b2) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_f32 with k + 1 not refused"); - CHECK(omega_gpu_tensor_update_bf16(t, K, N - 1u, b1) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_bf16 with n - 1 not refused"); - CHECK(omega_gpu_tensor_update_f32(t, N, K, b2) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_f32 with k and n swapped not refused"); - upd_same(d, want, packed, "shape-mismatch refusals left the buffer"); - rc = omega_gpu_tensor_update_f32(t, K, N, b2); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update_f32 %ux%u rc=%d %s", K, N, rc, omega_gpu_matmul_last_error()); - omega_matmul_frag_pack_b(b2h, K, N, KP, 0, NT, want); - upd_same(d, want, packed, "update_f32"); - rc = omega_gpu_tensor_update_bf16(t, K, N, b1); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update_bf16 %ux%u rc=%d %s", K, N, rc, omega_gpu_matmul_last_error()); - omega_matmul_frag_pack_b(b1, K, N, KP, 0, NT, want); - upd_same(d, want, packed, "update_bf16 back"); - omega_gpu_matmul_seal(1); - rc = omega_gpu_tensor_update_f32(t, K, N, b2); - omega_gpu_matmul_seal(0); - CHECK(rc == OMEGA_GPU_MATMUL_OK, "update while sealed rc=%d %s", rc, omega_gpu_matmul_last_error()); - omega_matmul_frag_pack_b(b2h, K, N, KP, 0, NT, want); - upd_same(d, want, packed, "update_f32 while sealed"); - CHECK(fk.alloc_calls == a1 && fk.free_calls == f1, "updates touched the driver (%d allocs, %d frees)", fk.alloc_calls - a1, fk.free_calls - f1); - uint32_t k2 = 0, n2 = 0; - omega_gpu_tensor_shape(t, &k2, &n2); - CHECK(k2 == K && n2 == N, "shape changed by update: %ux%u", k2, n2); - free(b2h); free(want); - *b1_out = b1; *b2_out = b2; - return t; -} -static int update_mode(void) { - OmegaGpuTensor *warm = upload(16, 8); /* opens the session, so each next upload is exactly one driver allocation */ - uint16_t *b1 = NULL, *b1b = NULL; float *b2 = NULL, *b2b = NULL; - OmegaGpuTensor *t = update_shape(72, 1100, &b1, &b2); - OmegaGpuTensor *t2 = update_shape(4096, 200, &b1b, &b2b); - if (!t || !t2) return 1; - - CHECK(omega_gpu_tensor_update_f32(NULL, 72, 1100, b2) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_f32 NULL tensor not refused"); - CHECK(omega_gpu_tensor_update_bf16(NULL, 72, 1100, b1) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_bf16 NULL tensor not refused"); - CHECK(omega_gpu_tensor_update_f32(t, 72, 1100, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_f32 NULL values not refused"); - CHECK(omega_gpu_tensor_update_bf16(t, 72, 1100, NULL) == OMEGA_GPU_MATMUL_BAD_ARGS, "update_bf16 NULL values not refused"); - - /* a handle whose device was closed is stale: refused before anything is written (its memory is gone) */ - omega_gpu_device_close(); - const int a2 = fk.alloc_calls; - int rc = omega_gpu_tensor_update_f32(t, 72, 1100, b2); - CHECK(rc == OMEGA_GPU_MATMUL_CHIP_FAIL, "update_f32 of a stale handle rc=%d (want CHIP_FAIL)", rc); - rc = omega_gpu_tensor_update_bf16(t, 72, 1100, b1); - CHECK(rc == OMEGA_GPU_MATMUL_CHIP_FAIL, "update_bf16 of a stale handle rc=%d (want CHIP_FAIL)", rc); - CHECK(fk.alloc_calls == a2, "stale update asked the driver for memory"); - OmegaGpuTensor *reopen = upload(16, 8); /* a new device: the old handle stays stale */ - rc = omega_gpu_tensor_update_f32(t, 72, 1100, b2); - CHECK(rc == OMEGA_GPU_MATMUL_CHIP_FAIL, "update_f32 of a handle from a previous device rc=%d (want CHIP_FAIL)", rc); - omega_gpu_tensor_free(reopen); - omega_gpu_tensor_free(t); - omega_gpu_tensor_free(t2); - omega_gpu_tensor_free(warm); - omega_gpu_device_close(); - free(b1); free(b2); free(b1b); free(b2b); - printf("gpu_serving_alloc_count_test update: %s (%d failed checks)\n", g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} - -int main(int argc, char **argv) { - const char *mode = argc > 1 ? argv[1] : "plain"; - const int do_reserve = strcmp(mode, "reserve") == 0, assert_zero = do_reserve || strcmp(mode, "reserve-skip") == 0; - fake_reset(); - fk.kernel_mode = FK_KERNEL_SKIP; - fk.alloc_max = 1ull << 31; - omega_gpu_matmul_set_cta_budget(256); - - g_x = calloc((size_t)CHUNK * INTER, sizeof *g_x); - g_y = calloc((size_t)CHUNK * INTER, sizeof *g_y); - g_logits = calloc(VOCAB, sizeof *g_logits); - g_k = calloc((size_t)4096 * KVDIM, sizeof *g_k); - g_v = calloc((size_t)4096 * KVDIM, sizeof *g_v); - CHECK(g_x && g_y && g_logits && g_k && g_v, "host buffers"); - if (g_fail) return 1; - - Phase ph[9]; - int np = 0; - if (strcmp(mode, "bounds") == 0) return bounds_mode(); - if (strcmp(mode, "bounds-block") == 0) return bounds_block_mode(); - if (strcmp(mode, "rollback") == 0) return rollback_mode(); - if (strcmp(mode, "sweep") == 0) return sweep_mode(1); - if (strcmp(mode, "pin") == 0) return pin_mode(); - if (strcmp(mode, "seal-bare") == 0) return seal_bare_mode(); - if (strcmp(mode, "update") == 0) return update_mode(); - if (strcmp(mode, "sweep-skip") == 0) return sweep_mode(0); - - begin(&ph[np], "LOAD (session+6 weights)"); - W_Q = upload(HID, QDIM); W_K = upload(HID, KVDIM); W_O = upload(QDIM, HID); - W_G = upload(HID, INTER); W_D = upload(INTER, HID); W_LM = upload(HID, VOCAB); - end(&ph[np], 1); np++; - CHECK(omega_gpu_session_open_count() == 1, "session opened %u times", omega_gpu_session_open_count()); - - /* WARM-UP: one decode step at context 1. Everything after this phase is "serving". */ - begin(&ph[np], "WARMUP decode ctx=1"); - step(1, 0); - end(&ph[np], 1); np++; - if (assert_zero) { - /* a daemon's startup: reserve once after loading and a first request, then cover each row-count class - * (1 decode row, a full chunk, the 100 and 72 row remainders) so every matmul shape has been built once */ - if (do_reserve) CHECK(omega_gpu_reserve_serving(&QWEN3_4B_BOUNDS) == 0, "reserve failed: %s", omega_gpu_matmul_last_error()); - begin(&ph[np], "WARMUP row classes"); - step(128, 0); step(100, 0); step(72, 0); step(1, 0); - end(&ph[np], 0); np++; - } - const int after_warm_allocs = fk.alloc_calls, after_warm_frees = fk.free_calls; - - uint32_t ctx = 0; - const uint32_t N1 = 100, D1 = 64, N2 = 200, D2 = 64; - - begin(&ph[np], "PREFILL-A 100 tokens"); - for (uint32_t off = 0; off < N1; off += CHUNK) { uint32_t r = N1 - off < CHUNK ? N1 - off : CHUNK; step(r, ctx + off); } - ctx += N1; - end(&ph[np], 1); np++; - - begin(&ph[np], "DECODE-A 64 tokens"); - for (uint32_t i = 0; i < D1; i++) { step(1, ctx); ctx++; } - end(&ph[np], 1); np++; - - begin(&ph[np], "PREFILL-B 200 tokens"); - for (uint32_t off = 0; off < N2; off += CHUNK) { uint32_t r = N2 - off < CHUNK ? N2 - off : CHUNK; step(r, ctx + off); } - ctx += N2; - end(&ph[np], 1); np++; - - begin(&ph[np], "DECODE-B 64 tokens"); - for (uint32_t i = 0; i < D2; i++) { step(1, ctx); ctx++; } - end(&ph[np], 1); np++; - - const int serve_allocs = fk.alloc_calls - after_warm_allocs, serve_frees = fk.free_calls - after_warm_frees; - printf("MEASURE AFTER WARM-UP: %d driver allocations, %d driver frees over %u tokens of context (final ctx %u)\n", - serve_allocs, serve_frees, ctx, ctx); - printf("MEASURE distinct matmul kernel shapes seen (kp,np,grid_x): %d (cache slots: %d)\n", g_nseen, do_reserve ? 32 : 8); - printf("MEASURE live driver buffers at end: %d ; session opens: %u ; launches reaching the fake: %d\n", - fk.live, omega_gpu_session_open_count(), fk.kernel_ran); - printf("MEASURE return codes: matmul ok %d, matmul poison-check CHIP_FAIL %d, attention ok %d, attention UNWRITTEN %d, other %d\n", - g_rc_mm_ok, g_rc_mm_chipfail, g_rc_at_ok, g_rc_at_unwritten, g_rc_bad); - - /* ---- what is true today and stays true ---- */ - CHECK(g_rc_bad == 0, "%d calls returned a code other than the expected poison-check ones", g_rc_bad); - CHECK(!omega_gpu_matmul_is_blocked() && !omega_gpu_session_is_blocked(), "session latched"); - CHECK(fk.double_free == 0, "double free %d", fk.double_free); - CHECK(fk.pb_parse_error == 0, "pushbuffer parse error"); - int calls_made = 0; - for (int i = 1; i < np; i++) calls_made += ph[i].mm_calls + ph[i].at_calls; - CHECK(fk.kernel_ran == calls_made, "launches %d != calls made %d", fk.kernel_ran, calls_made); - if (assert_zero) { - /* the point of the reservation: nothing reached the driver while serving inside the bounds */ - CHECK(serve_allocs == 0 && serve_frees == 0, "serving made %d driver allocations and %d frees after warm-up; the reservation promises none", serve_allocs, serve_frees); - for (int i = np - 4; i < np; i++) CHECK(ph[i].allocs == 0 && ph[i].frees == 0, "phase %s: %d allocs, %d frees", ph[i].name, ph[i].allocs, ph[i].frees); - } - CHECK(fk.live < FK_LIVE_MAX, "fake live table full (%d)", fk.live); - /* every real allocation is either live or was freed */ - CHECK(fk.alloc_calls - fk.free_calls >= fk.live, "alloc/free/live inconsistent: %d - %d < %d", fk.alloc_calls, fk.free_calls, fk.live); - - /* teardown: tensors first, then the device (the on-close hooks free the API scratch) */ - omega_gpu_tensor_free(W_Q); omega_gpu_tensor_free(W_K); omega_gpu_tensor_free(W_O); - omega_gpu_tensor_free(W_G); omega_gpu_tensor_free(W_D); omega_gpu_tensor_free(W_LM); - omega_gpu_device_close(); - CHECK(fk.live_at_close == 0, "leak: %d driver buffers live at close", fk.live_at_close); - printf("MEASURE leaked at close: %d\n", fk.live_at_close); - - printf("gpu_serving_alloc_count_test %s: %s (%d failed checks)\n", mode, g_fail ? "FAIL" : "PASS", g_fail); - return g_fail ? 1 : 0; -} diff --git a/tests/gpu_session_probe.c b/tests/gpu_session_probe.c deleted file mode 100644 index 8aad1a16b..000000000 --- a/tests/gpu_session_probe.c +++ /dev/null @@ -1,72 +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. - */ - -/* gpu_session_probe: FB-1 cut 4b flake investigation (first-call device-open failure). - * - * One fresh process = one sample: open the shared device through the API's own - * path (omega_gpu_ex2_f32 on 128 values is the smallest launch there is), report - * the stage that failed (with the driver's own text) or the open time, exit 0/1. - * - * ./gpu_session_probe [--label L] [--calls N] [--hold-ms M] - * --calls N launches after the first (default 1); keeps the device busy for an overlap test - * --hold-ms M sleep M ms with the device open before exit (overlap window for a second probe) - * - * Output (one line, Astra's SNAP shape; every unknown says so): - * PROBE label=L pid=P rc=OK|CHIP_FAIL|... stage="..." first_call_ms=F open_ms=O calls_ok=K/N opens=1 - * Never run outside the heavy queue (tools/probe_gpu_open.sh). - */ -#include "omega_gpu_elementwise_api.h" -#include "omega_gpu_session.h" -#include -#include -#include -#include -#include - -static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } - -int main(int argc, char **argv) { - const char *label = "probe"; int calls = 1, hold_ms = 0; - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--label") == 0 && i + 1 < argc) label = argv[++i]; - else if (strcmp(argv[i], "--calls") == 0 && i + 1 < argc) calls = atoi(argv[++i]); - else if (strcmp(argv[i], "--hold-ms") == 0 && i + 1 < argc) hold_ms = atoi(argv[++i]); - else { fprintf(stderr, "unknown flag %s\n", argv[i]); return 2; } - } - float x[128], y[128]; - for (int i = 0; i < 128; i++) { x[i] = (float)i / 16.0f - 4.0f; y[i] = 0.0f; } - OmegaGpuEwInfo info; memset(&info, 0, sizeof info); - double t0 = now_ms(); - int rc = omega_gpu_ex2_f32(128, x, y, &info); - double first_ms = now_ms() - t0; - int ok = 0; - if (rc == OMEGA_GPU_EW_OK) { - /* negative control on the result itself: 2^0 must be 1 (x[64] = 0) */ - if (y[64] < 0.999f || y[64] > 1.001f) { rc = OMEGA_GPU_EW_UNWRITTEN; omega_gpu_session_set_error("probe: 2^0 != 1"); } - else ok = 1; - } - int more_ok = 0; - for (int i = 1; i < calls && ok; i++) if (omega_gpu_ex2_f32(128, x, y, &info) == OMEGA_GPU_EW_OK) more_ok++; - if (hold_ms > 0) usleep((useconds_t)hold_ms * 1000u); - const char *stage = omega_gpu_elementwise_last_error(); - printf("PROBE label=%s pid=%d rc=%s stage=\"%s\" first_call_ms=%.1f chip_us=%.1f calls_ok=%d/%d opens=%u%s\n", - label, (int)getpid(), omega_gpu_elementwise_rc_name(rc), stage[0] ? stage : "-", first_ms, - info.elapsed_ns / 1e3, ok + more_ok, calls, omega_gpu_session_open_count(), - rc == OMEGA_GPU_EW_OK && !stage[0] ? "" : (rc == OMEGA_GPU_EW_OK ? " note=stage_text_from_earlier_failure" : "")); - fflush(stdout); - omega_gpu_session_close(); /* the explicit close is part of what the next process sees */ - return ok ? 0 : 1; -} diff --git a/tests/gpu_streams_test.c b/tests/gpu_streams_test.c deleted file mode 100644 index 621049e14..000000000 --- a/tests/gpu_streams_test.c +++ /dev/null @@ -1,392 +0,0 @@ -/* gpu_streams_test.c -- row C4 of docs/OMEGA.md: two independent queues and an event between them, on the GB10. - * - * --host-only codegen + encode of the two kernels (and their mutants), refusals of omega_gpu_cmdlist_wait_for - * --sim the kernels through the warp simulator (tests/bw_warp_sim.h): exact values, mutants caught - * (no flag) the chip, under the GB10 lock, AIEN_OMEGA_GPU_CHANNELS = 2 (L136 extra queue): - * overlap list A and list B each hold the same half-chip spin kernel (24 CTAs x 128 threads); solo A, solo B - * (session queue, one submit each) and the pair (A on queue 0, B on queue 1, omega_gpu_cmdlist_submit_pair), - * medians of REPS: PASS when pair < 0.75 (solo A + solo B), for the default barrier or first_barrier_none - * (both are printed). Red check: both spins in ONE list on one queue (WAIT_FOR_IDLE between them) must - * NOT come in under 0.75, or the measurement cannot tell overlap from order. - * event A: a long spin writes X. B: omega_gpu_cmdlist_wait_for(A, 0), then copy Y = X + 1. X and Y start as a - * signalling-NaN poison; every Y must be the spin's value + 1. Negative control: the same pair without the - * wait must leave at least one Y wrong (B ran while A spun), else the event is "not demonstrated" (FAIL). - * Every kernel comes from Omega's IR (omega_bw_em.h), encoded by our own sm_121 encoder; no CUDA. */ -#include "omega_gpu_cmdlist.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim.h" /* brings math.h, whose fadd() would hide the emitter's */ -#define fadd em_fadd -#define ffma em_ffma -#include "omega_bw_em.h" - -#include -#include -#include - -#define THREADS 128u -#define CTAS 24u /* half of the GB10's 48 SMs */ -#define NEL (THREADS * CTAS) -#define UNROLL 4u /* FFMAs per loop turn: x = x * 1 + 1 */ -#define MAX_ITERS ((1u << 22) - 1024u) /* UNROLL * iters + tag stays below 2^24: every value exact in f32 */ -#define POISON 0x7fa00badu /* a signalling NaN no FFMA / FADD writes */ -#define REPS 5 - -/* argument words (constant bank 0x380) */ -#define A_OUT 0x380 /* spin: out u64 | copy: in u64 */ -#define A_ITERS 0x388 /* spin: loop turns | copy: out u64 (0x388..0x38f) */ -#define A_TAG 0x38c /* spin: f32 added at the end */ -#define A_N 0x390 /* elements */ -#define ARGS 5u - -static int g_failed, g_checks; -static void check(int ok, const char *what) { - g_checks++; - if (!ok) g_failed++; - printf("%s: %s\n", ok ? "ok" : "FAIL", what); -} -static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } - -/* ------------------------------------------------------------------ the kernels */ - -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); } - -/* spin: out[gid] = UNROLL * iters + tag (mutant 1: one FFMA short per turn) */ -static int gen_spin(Em *e, int mutant) { - int udesc = UV64(e), pout = V64(e), a64 = V64(e), iters = V(e), tag = V(e), n = V(e), tid = V(e), cta = V(e), gid = V(e); - int i = V(e), one = V(e), fone = V(e), x = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pout, A_OUT); ldc32(e, iters, A_ITERS); ldc32(e, tag, A_TAG); ldc32(e, n, A_N); - s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - imadi(e, gid, cta, 0, THREADS, tid); - movi(e, one, 1); movi(e, fone, 0x3f800000u); movi(e, x, 0); movi(e, i, 0); - const int top = here(e); - loop_begin(e); - isetp_ge_u32(e, i, iters); - const int done = bra_if_p0_fwd(e); - for (unsigned u = 0; u < UNROLL - (mutant == 1 ? 1u : 0u); u++) ffma(e, x, x, fone, 0, fone); - iadd(e, i, i, one); - bra(e, top); - loop_end(e); - patch_bra(e, done, here(e)); - fadd(e, x, x, tag); - isetp_ge_u32(e, gid, n); - { Region r = skip_if_p0(e); imadw(e, a64, gid, 4u, pout); stg(e, a64, 0, x, udesc); region_end(e, r); } - tail(e); - return e->err; -} - -/* copy: out[gid] = in[gid] + 1 (mutant 1: + 2) */ -static int gen_copy(Em *e, int mutant) { - int udesc = UV64(e), pin = V64(e), pout = V64(e), a64 = V64(e), n = V(e), tid = V(e), cta = V(e), gid = V(e), add = V(e), v = V(e); - if (e->err) return -1; - ldcu64(e, udesc, 0x358); - ldc64(e, pin, A_OUT); ldc64(e, pout, A_ITERS); ldc32(e, n, A_N); - s2r(e, tid, BW_SR_TID_X); s2r(e, cta, BW_SR_CTAID_X); - imadi(e, gid, cta, 0, THREADS, tid); - movi(e, add, mutant == 1 ? 0x40000000u : 0x3f800000u); - isetp_ge_u32(e, gid, n); - { - Region r = skip_if_p0(e); - imadw(e, a64, gid, 4u, pin); ldg32(e, v, a64, udesc, 1); - fadd(e, v, v, add); - imadw(e, a64, gid, 4u, pout); stg(e, a64, 0, v, udesc); - region_end(e, r); - } - tail(e); - return e->err; -} - -static int codegen(int copy, int mutant, BlackwellIRProgram *prog) { - omega_bw_ir_init(prog); - Em em; memset(&em, 0, sizeof em); em.p = prog; - if ((copy ? gen_copy(&em, mutant) : gen_spin(&em, mutant)) != 0 || em.err || em.depth != 0) return -1; - return omega_bw_regalloc_solve(prog); -} - -static void spin_args(uint32_t a[ARGS], uint64_t out, uint32_t iters, float tag) { - memset(a, 0, ARGS * 4u); - a[0] = (uint32_t)out; a[1] = (uint32_t)(out >> 32); a[2] = iters; a[3] = f2u(tag); a[4] = NEL; -} -static void copy_args(uint32_t a[ARGS], uint64_t in, uint64_t out) { - memset(a, 0, ARGS * 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] = NEL; -} -static float spin_value(uint32_t iters, float tag) { return (float)(UNROLL * iters) + tag; } - -/* ------------------------------------------------------------------ host + simulator */ - -static void host_only(void) { - char w[200]; - for (int copy = 0; copy < 2; copy++) - for (int mut = 0; mut < 2; mut++) { - BlackwellIRProgram *p = calloc(1, sizeof *p); - size_t need = 0; - int ok = p && codegen(copy, mut, p) == 0 && (need = omega_bw_program_code_bytes(p)) > 0; - void *code = ok ? calloc(1, need) : NULL; - OmegaBlackwellKernel kk; - ok = ok && code && omega_blackwell_kernel_encode_into(p, code, need, &kk) == 0 && kk.code_size == need; - snprintf(w, sizeof w, "codegen + encode: %s kernel%s (%zu bytes, %u registers)", copy ? "copy" : "spin", mut ? " mutant 1" : "", - need, ok ? kk.gpr_count : 0u); - check(ok, w); - free(code); free(p); - } - check(omega_gpu_cmdlist_wait_for(NULL, NULL, 0) == -1, "wait_for refuses missing lists"); -} - -static int sim_run(BlackwellIRProgram *p, const uint32_t a[ARGS], WsRange *rg, int nrg, int order) { - static WsSim s; - memset(&s, 0, sizeof s); - s.p = p; s.threads = THREADS; s.order = order; - for (unsigned i = 0; i < ARGS; i++) s.cbank[0x380 / 4 + i] = a[i]; - memcpy(s.ranges, rg, (size_t)nrg * sizeof *rg); s.nranges = nrg; - if (ws_run(&s, CTAS, 1) != 0) { printf(" simulator: %s at pc %d\n", s.msg, s.err_pc); return -1; } - return 0; -} - -static void sim_tier(void) { - char w[200]; - static float X[NEL], Y[NEL]; - WsRange rg[2] = { { (uintptr_t)X, (uintptr_t)(X + NEL) }, { (uintptr_t)Y, (uintptr_t)(Y + NEL) } }; - for (int mut = 0; mut < 2; mut++) { - BlackwellIRProgram *ps = calloc(1, sizeof *ps), *pc = calloc(1, sizeof *pc); - if (!ps || !pc || codegen(0, mut, ps) || codegen(1, mut, pc)) { check(0, "simulator: kernels built"); free(ps); free(pc); return; } - for (int order = 0; order < 2; order++) { - const uint32_t iters = 37u + (uint32_t)order; - const float tag = 5.0f + (float)order; - uint32_t a[ARGS]; - for (unsigned i = 0; i < NEL; i++) { uint32_t pz = POISON; memcpy(&X[i], &pz, 4); memcpy(&Y[i], &pz, 4); } - spin_args(a, (uintptr_t)X, iters, tag); - int rc = sim_run(ps, a, rg, 2, order); - copy_args(a, (uintptr_t)X, (uintptr_t)Y); - rc = rc || sim_run(pc, a, rg, 2, order); - unsigned wx = 0, wy = 0; - for (unsigned i = 0; i < NEL; i++) { - wx += f2u(X[i]) != f2u(spin_value(iters, tag)); - wy += f2u(Y[i]) != f2u(spin_value(iters, tag) + 1.0f); - } - if (mut == 0) snprintf(w, sizeof w, "simulator order %d: spin + copy exact on all %u elements (%u, %u wrong)", order, NEL, wx, wy); - else snprintf(w, sizeof w, "simulator red check order %d: mutant 1 caught (%u, %u wrong)", order, wx, wy); - check(mut == 0 ? rc == 0 && wx == 0 && wy == 0 : rc != 0 || (wx > 0 && wy > 0), w); - } - free(ps); free(pc); - } -} - -/* ------------------------------------------------------------------ the chip */ - -typedef struct { BlackwellIRProgram prog; OmegaGpuMem code; uint32_t gpr; } Kern; -static Kern K_spin, K_copy; - -static int kern_upload(Kern *k, int copy) { - if (codegen(copy, 0, &k->prog) != 0) return -1; - size_t need = omega_bw_program_code_bytes(&k->prog); - if (need == 0 || omega_gpu_session_alloc_code(need, &k->code) != 0) return -1; - OmegaBlackwellKernel kk; - if (omega_blackwell_kernel_encode_into(&k->prog, k->code.cpu, need, &kk) != 0 || omega_gpu_session_sync_to_gpu(&k->code) != 0) return -1; - k->gpr = omega_bw_gpr_declared(kk.gpr_count); - if (k->gpr < 64u) k->gpr = 64u; - return 0; -} - -static OmegaGpuMem g_buf; /* [OA | OB | X | Y], NEL floats each */ -static float *buf_at(int i) { return (float *)g_buf.cpu + (size_t)i * NEL; } -static uint64_t va_at(int i) { return g_buf.va + (uint64_t)i * NEL * 4u; } -enum { B_OA = 0, B_OB = 1, B_X = 2, B_Y = 3 }; - -static void poison_all(void) { - uint32_t *u = g_buf.cpu; - for (size_t i = 0; i < 4u * NEL; i++) u[i] = POISON; - (void)omega_gpu_session_sync_to_gpu(&g_buf); -} -static unsigned wrong(int b, float want) { - (void)omega_gpu_session_sync_to_cpu(&g_buf); - const float *p = buf_at(b); - unsigned n = 0; - for (unsigned i = 0; i < NEL; i++) n += f2u(p[i]) != f2u(want); - return n; -} - -static uint32_t g_args[8][ARGS]; /* the launches' argument words stay alive until submit */ -static int add_spin(OmegaGpuCmdList *cl, int slot, int out_buf, uint32_t iters, float tag) { - spin_args(g_args[slot], va_at(out_buf), iters, tag); - OmegaGpuLaunch L = { .code_va = K_spin.code.va, .gpr_count = K_spin.gpr, .threads_x = THREADS, .threads_y = 1, .grid_x = CTAS, .grid_y = 1, - .num_elements = NEL, .args = g_args[slot], .n_args = ARGS }; - return omega_gpu_cmdlist_add(cl, &L) < 0 ? -1 : 0; -} -static int add_copy(OmegaGpuCmdList *cl, int slot) { - copy_args(g_args[slot], va_at(B_X), va_at(B_Y)); - OmegaGpuLaunch L = { .code_va = K_copy.code.va, .gpr_count = K_copy.gpr, .threads_x = THREADS, .threads_y = 1, .grid_x = CTAS, .grid_y = 1, - .num_elements = NEL, .args = g_args[slot], .n_args = ARGS }; - return omega_gpu_cmdlist_add(cl, &L) < 0 ? -1 : 0; -} - -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } -static uint64_t median(uint64_t *v, int n) { qsort(v, (size_t)n, sizeof *v, cmp_u64); return v[n / 2]; } - -static OmegaGpuCmdList *g_a, *g_b, *g_ab; - -/* one solo submit of a one-spin list; values checked; elapsed ns or 0 on failure */ -static uint64_t solo(OmegaGpuCmdList *cl, int out_buf, uint32_t iters, float tag, const OmegaGpuCmdListOpts *o) { - OmegaGpuCmdListStats st; - poison_all(); - if (omega_gpu_cmdlist_submit(cl, o, &st) != 0) { printf(" solo submit: %s\n", omega_gpu_session_last_error()); return 0; } - unsigned bad = wrong(out_buf, spin_value(iters, tag)); - if (bad) { printf(" solo: %u wrong values\n", bad); return 0; } - return st.elapsed_ns; -} - -static int overlap(uint32_t iters, int fbn, double *ratio_out) { - char w[300]; - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); - o.first_barrier_none = fbn; - uint64_t sa[REPS], sb[REPS], sp[REPS]; - for (int r = 0; r < REPS; r++) { - sa[r] = solo(g_a, B_OA, iters, 1.0f, &o); - sb[r] = solo(g_b, B_OB, iters, 2.0f, &o); - OmegaGpuCmdListStats s1, s2; - poison_all(); - int rc = omega_gpu_cmdlist_submit_pair(g_a, g_b, &o, &s1, &s2); - unsigned bad = rc ? NEL : wrong(B_OA, spin_value(iters, 1.0f)) + wrong(B_OB, spin_value(iters, 2.0f)); - if (rc || bad) { printf(" pair: %s, %u wrong values\n", rc ? omega_gpu_session_last_error() : "ok", bad); sp[r] = 0; } - else sp[r] = s1.elapsed_ns; - if (!sa[r] || !sb[r] || !sp[r]) { check(0, "overlap: every submit ran and every value is right"); return -1; } - } - const uint64_t ma = median(sa, REPS), mb = median(sb, REPS), mp = median(sp, REPS); - const double ratio = (double)mp / (double)(ma + mb); - *ratio_out = ratio; - snprintf(w, sizeof w, "overlap (%s): solo A %.3f ms, solo B %.3f ms, pair %.3f ms (medians of %d, values right): pair / (A + B) = %.3f", - fbn ? "first_barrier_none" : "default barrier", ma / 1e6, mb / 1e6, mp / 1e6, REPS, ratio); - printf("%s\n", w); - return 0; -} - -static int serial_control(uint32_t iters, double *ratio_out) { - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); - uint64_t sa[REPS], sab[REPS]; - for (int r = 0; r < REPS; r++) { - sa[r] = solo(g_a, B_OA, iters, 1.0f, &o); - OmegaGpuCmdListStats st; - poison_all(); - int rc = omega_gpu_cmdlist_submit(g_ab, &o, &st); - unsigned bad = rc ? NEL : wrong(B_OA, spin_value(iters, 1.0f)) + wrong(B_OB, spin_value(iters, 2.0f)); - if (!sa[r] || rc || bad) { check(0, "serial control: every submit ran and every value is right"); return -1; } - sab[r] = st.elapsed_ns; - } - const uint64_t ma = median(sa, REPS), mab = median(sab, REPS); - *ratio_out = (double)mab / (double)(2 * ma); - printf("serial control: solo %.3f ms, both in one list on one queue %.3f ms: ratio %.3f\n", ma / 1e6, mab / 1e6, *ratio_out); - return 0; -} - -/* list A: spin into X; list B: [wait for A launch 0] copy X -> Y. Returns the count of wrong Y, or -1 on a submit failure. */ -static long event_run(uint32_t iters, int with_wait, int fbn) { - OmegaGpuCmdList *a = NULL, *b = NULL; - long res = -1; - if (omega_gpu_cmdlist_create(1, &a) || omega_gpu_cmdlist_create(1, &b)) { printf(" event: create: %s\n", omega_gpu_session_last_error()); goto out; } - omega_gpu_session_lock(); - if (add_spin(a, 4, B_X, iters, 3.0f) || (with_wait && omega_gpu_cmdlist_wait_for(b, a, 0)) || add_copy(b, 5)) { - omega_gpu_session_unlock(); printf(" event: add: %s\n", omega_gpu_session_last_error()); goto out; - } - OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); - o.first_barrier_none = fbn; - OmegaGpuCmdListStats s1, s2; - if (with_wait) { /* the refusals: a list with a wait never runs alone, nor waits on a second list */ - OmegaGpuCmdList *c = NULL; - int alone = omega_gpu_cmdlist_submit(b, &o, &s2) == -1 && strstr(omega_gpu_session_last_error(), "only in a pair") != NULL; - omega_gpu_session_unlock(); - int third = omega_gpu_cmdlist_create(1, &c) == 0; - omega_gpu_session_lock(); - third = third && add_spin(c, 6, B_OA, 1, 0.0f) == 0 && omega_gpu_cmdlist_wait_for(b, c, 0) == -1; - omega_gpu_session_unlock(); - omega_gpu_cmdlist_free(c); - omega_gpu_session_lock(); - check(alone && third, "event refusals: a list with a wait is refused alone, and cannot wait on a second list"); - } - poison_all(); - int rc = omega_gpu_cmdlist_submit_pair(a, b, &o, &s1, &s2); - if (rc) printf(" event: pair: %s\n", omega_gpu_session_last_error()); - else { - unsigned bx = wrong(B_X, spin_value(iters, 3.0f)), by = wrong(B_Y, spin_value(iters, 3.0f) + 1.0f); - printf(" event (%s, %s): X %u wrong, Y %u wrong of %u, pair %.3f ms\n", with_wait ? "wait" : "NO wait", fbn ? "first_barrier_none" : "default barrier", - bx, by, NEL, s1.elapsed_ns / 1e6); - res = bx ? -1 : (long)by; - } - omega_gpu_session_unlock(); -out: - omega_gpu_cmdlist_free(a); omega_gpu_cmdlist_free(b); - return res; -} - -static void chip_tier(int values_only) { - char w[300]; - setenv("AIEN_OMEGA_GPU_CHANNELS", "2", 1); - if (omega_gpu_cmdlist_create(1, &g_a) || omega_gpu_cmdlist_create(1, &g_b) || omega_gpu_cmdlist_create(2, &g_ab)) { - printf("NOT_RUN: command lists: %s\n", omega_gpu_session_last_error()); exit(2); - } - omega_gpu_session_lock(); - if (!omega_gpu_session_open() || omega_gpu_session_alloc(4u * NEL * 4u, &g_buf) || kern_upload(&K_spin, 0) || kern_upload(&K_copy, 1)) { - printf("NOT_RUN: device, buffer or kernels: %s\n", omega_gpu_session_last_error()); omega_gpu_session_unlock(); exit(2); - } - OmegaGpuQueueHandle q1; - check(omega_gpu_session_extra_queue(1, &q1) == 0, "the second queue opens (AIEN_OMEGA_GPU_CHANNELS = 2)"); - - /* calibrate: one spin of about 60 ms */ - uint32_t iters = 1u << 16; - OmegaGpuCmdListOpts o0; memset(&o0, 0, sizeof o0); - omega_gpu_cmdlist_reset(g_a); - if (add_spin(g_a, 0, B_OA, iters, 1.0f)) { check(0, "calibration list"); omega_gpu_session_unlock(); return; } - uint64_t t = solo(g_a, B_OA, iters, 1.0f, &o0); - if (!t) { check(0, "calibration spin ran with right values"); omega_gpu_session_unlock(); return; } - double scaled = (double)iters * 60e6 / (double)t; - iters = scaled > MAX_ITERS ? MAX_ITERS : (uint32_t)scaled; - printf("calibration: 2^16 turns took %.3f ms; using %u turns\n", t / 1e6, iters); - - omega_gpu_cmdlist_reset(g_a); omega_gpu_cmdlist_reset(g_b); omega_gpu_cmdlist_reset(g_ab); - if (add_spin(g_a, 0, B_OA, iters, 1.0f) || add_spin(g_b, 1, B_OB, iters, 2.0f) || - add_spin(g_ab, 2, B_OA, iters, 1.0f) || add_spin(g_ab, 3, B_OB, iters, 2.0f)) { check(0, "timing lists"); omega_gpu_session_unlock(); return; } - - if (!values_only) { - double r_def = 9, r_fbn = 9, r_ser = 0; - int ok_def = overlap(iters, 0, &r_def) == 0, ok_fbn = overlap(iters, 1, &r_fbn) == 0, ok_ser = serial_control(iters, &r_ser) == 0; - snprintf(w, sizeof w, "C4 overlap: two queues of the same work finish in under 0.75 of the solo sum (default %.3f, first_barrier_none %.3f)", r_def, r_fbn); - check((ok_def && r_def < 0.75) || (ok_fbn && r_fbn < 0.75), w); - snprintf(w, sizeof w, "red check: the same two spins in order on one queue do NOT pass the 0.75 bar (ratio %.3f)", r_ser); - check(ok_ser && r_ser >= 0.75, w); - } else puts("C4 overlap: NOT_RUN (values-only; timing needs an exclusive window)"); - omega_gpu_session_unlock(); - - /* the event: positive, then the control without the wait (both barrier modes) */ - long pos = event_run(iters, 1, 0); - snprintf(w, sizeof w, "C4 event: B's copy waited for A's spin on the other queue; every Y right (%ld wrong)", pos); - check(pos == 0, w); - long neg0 = event_run(iters, 0, 0), neg1 = neg0 > 0 ? neg0 : event_run(iters, 0, 1); - snprintf(w, sizeof w, "negative control: without the wait B ran early and Y is wrong (default barrier %ld wrong, first_barrier_none %ld wrong)", neg0, neg1); - check(neg0 > 0 || neg1 > 0, w); - long again = event_run(iters, 1, 1); - snprintf(w, sizeof w, "C4 event with first_barrier_none: every Y right (%ld wrong)", again); - check(again == 0, w); - - omega_gpu_session_lock(); - omega_gpu_session_free(&g_buf); omega_gpu_session_free(&K_spin.code); omega_gpu_session_free(&K_copy.code); - omega_gpu_session_unlock(); - omega_gpu_cmdlist_free(g_a); omega_gpu_cmdlist_free(g_b); omega_gpu_cmdlist_free(g_ab); -} - -int main(int argc, char **argv) { - const char *tier = "chip"; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) tier = "host"; - else if (!strcmp(argv[i], "--values-only")) tier = "values"; - else if (!strcmp(argv[i], "--sim")) tier = "sim"; - else { fprintf(stderr, "usage: %s [--host-only | --sim | --values-only]\n", argv[0]); return 2; } - } - if (!strcmp(tier, "host")) host_only(); - else if (!strcmp(tier, "sim")) { host_only(); sim_tier(); } - else chip_tier(!strcmp(tier, "values")); - if (g_failed) printf("C4 streams %s: FAIL (%d of %d)\n", tier, g_failed, g_checks); - else printf("C4 streams %s: PASS (%d checks)\n", tier, g_checks); - return g_failed ? 1 : 0; -} diff --git a/tests/gpu_tc_peak_test.c b/tests/gpu_tc_peak_test.c deleted file mode 100644 index 5d2841cba..000000000 --- a/tests/gpu_tc_peak_test.c +++ /dev/null @@ -1,115 +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. - */ - -/* gpu_tc_peak_test.c (OWN-30B T3, 2026-10-13): tensor-core throughput ceiling on GB10 (HMMA.16816.F32.BF16). - * --host-only the generator in the warp simulator: every accumulator 16 * iters - * (default) the chip (caller holds flock /tmp/aien-gb10.lock): a sweep of issue stall x accumulator chains x warps x CTAs; - * each point checks every stored value (16 * iters) and reports TFLOPS = 4096 flop per HMMA / chip time - * (median of 5). Halving the chains must roughly halve the time when the tensor pipe is the limit. - * Verdict line last: "GPU_TC_PEAK: PASS|FAIL". */ -#include "omega_blackwell_codegen_tc.h" -#include "omega_gpu_session.h" -#include "bw_warp_sim_tc.h" -#include -#include -#include - -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -static int host_only(void) { - static BlackwellIRProgram p; int fail = 0; - for (uint32_t chains = 8; chains <= 16; chains += 8) { - if (omega_blackwell_codegen_tc_peak_prog(5, chains, 2, 64, &p) != 0) { printf("codegen refused chains %u\n", chains); return 1; } - static float out[2 * 64 * 64]; for (size_t i = 0; i < sizeof out / 4; i++) out[i] = -1; - static WsSim s; memset(&s, 0, sizeof s); s.p = &p; s.threads = 64; - uint64_t va = (uintptr_t)out; s.cbank[0x380 / 4] = (uint32_t)va; s.cbank[0x384 / 4] = (uint32_t)(va >> 32); - s.ranges[0].lo = va; s.ranges[0].hi = va + 2u * 64u * 16u * chains; s.nranges = 1; - int err = ws_run(&s, 2, 1); size_t bad = 0; - for (size_t i = 0; i < 2u * 64u * 4u * chains; i++) if (out[i] != 80.0f) bad++; - printf("sim chains %u: %s, peak %u registers, %zu instructions, %zu wrong\n", chains, err ? s.msg : "ran", p.regalloc.peak_gpr_usage, p.count, bad); - if (err || bad) fail++; - } - return fail; -} - -int main(int argc, char **argv) { - int fail = host_only(); - if (argc > 1 && !strcmp(argv[1], "--host-only")) { printf("GPU_TC_PEAK: %s\n", fail ? "FAIL" : "PASS"); return fail ? 1 : 0; } - if (fail) { printf("GPU_TC_PEAK: FAIL\n"); return 1; } - static const struct { uint32_t stall, chains, threads, ctas; } pts[] = { - { 8, 16, 128, 192 }, { 4, 16, 128, 192 }, { 2, 16, 128, 192 }, { 2, 8, 128, 192 }, - { 2, 16, 256, 192 }, { 2, 16, 128, 384 }, { 2, 16, 512, 96 }, { 4, 8, 256, 384 }, { 1, 16, 256, 384 }, - }; - const uint32_t iters = 4096; - omega_gpu_session_lock(); - if (!omega_gpu_session_open()) { printf("open failed: %s\n", omega_gpu_session_last_error()); omega_gpu_session_unlock(); return 1; } - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - static BlackwellIRProgram p; OmegaGpuMem code = { 0 }, out = { 0 }; OmegaBlackwellKernel k; - if (omega_blackwell_codegen_tc_peak_prog(iters, pts[i].chains, pts[i].stall, pts[i].threads, &p) != 0) { printf("codegen refused\n"); fail++; continue; } - size_t need = omega_bw_program_code_bytes(&p), ob = (size_t)pts[i].ctas * pts[i].threads * 16u * pts[i].chains; - uint32_t decl = omega_bw_gpr_declared(p.regalloc.peak_gpr_usage); - if (omega_gpu_session_alloc_code(need, &code) != 0 || omega_blackwell_kernel_encode_into(&p, code.cpu, need, &k) != 0 || omega_gpu_session_sync_to_gpu(&code) != 0 || - omega_gpu_session_alloc(ob, &out) != 0) { printf("upload failed: %s\n", omega_gpu_session_last_error()); fail++; break; } - uint64_t ns[5]; int ok = 1; size_t bad = 0; - for (int r = 0; r < 5 && ok; r++) { - ns[r] = 0; /* omega_gpu_session_launch adds the elapsed time */ - float *o = out.cpu; for (size_t q = 0; q < ob / 4; q++) o[q] = -1.0f; - uint32_t args[2] = { (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = decl, .threads_x = pts[i].threads, .threads_y = 1, .grid_x = pts[i].ctas, .grid_y = 1, - .num_elements = ob / 4, .args = args, .n_args = 2, .timeout_ms = 20000 }; - if (omega_gpu_session_sync_to_gpu(&out) != 0 || omega_gpu_session_launch(&L, &ns[r], NULL) != 0 || omega_gpu_session_sync_to_cpu(&out) != 0) { printf("launch failed: %s\n", omega_gpu_session_last_error()); ok = 0; break; } - for (size_t q = 0; q < ob / 4; q++) if (o[q] != 16.0f * iters) bad++; - } - if (!ok) { fail++; omega_gpu_session_free(&code); omega_gpu_session_free(&out); break; } - qsort(ns, 5, 8, cmp_u64); - double hm = (double)pts[i].ctas * (pts[i].threads / 32u) * iters * pts[i].chains; - printf("peak stall %u chains %u threads %u ctas %u (declared %u): median %.1f us, %.2f TFLOPS, %zu wrong values\n", pts[i].stall, pts[i].chains, pts[i].threads, pts[i].ctas, decl, - ns[2] / 1e3, hm * 4096.0 / ns[2] / 1e3, bad); - if (bad) fail++; - omega_gpu_session_free(&code); omega_gpu_session_free(&out); - } - /* read bandwidth: every CTA distinct vs every CTA the same bytes (any cache reuse of these GPU-uncached buffers) */ - for (int mode = 0; mode < 4 && !fail; mode++) { - const uint32_t T = 256, grid = 384, iters = mode < 2 ? 32u : 8u, groups = (mode & 1) ? 1u : grid; - static BlackwellIRProgram p; OmegaGpuMem code = { 0 }, src = { 0 }, out = { 0 }; OmegaBlackwellKernel k; - if (omega_blackwell_codegen_tc_bw_prog(iters, groups, T, &p) != 0) { printf("bw codegen refused\n"); fail++; break; } - size_t need = omega_bw_program_code_bytes(&p), region = (size_t)iters * T * 128u, sb = region * groups, ob = (size_t)grid * T * 4u; - if (omega_gpu_session_alloc_code(need, &code) != 0 || omega_blackwell_kernel_encode_into(&p, code.cpu, need, &k) != 0 || omega_gpu_session_sync_to_gpu(&code) != 0 || - omega_gpu_session_alloc(sb, &src) != 0 || omega_gpu_session_alloc(ob, &out) != 0) { printf("bw upload failed: %s\n", omega_gpu_session_last_error()); fail++; break; } - uint32_t *sw = src.cpu; for (size_t q = 0; q < sb / 4; q++) sw[q] = (uint32_t)(q * 2654435761u); - uint32_t *want = calloc((size_t)grid * T, 4); - for (uint32_t c = 0; c < grid; c++) for (uint32_t t = 0; t < T; t++) { uint32_t a = 0; const uint32_t *r = sw + (size_t)(groups == 1 ? 0 : c) * region / 4; - for (uint32_t it = 0; it < iters; it++) for (uint32_t q = 0; q < 8; q++) for (uint32_t s = 0; s < 4; s++) a ^= r[((size_t)it * T * 128u + (size_t)q * T * 16u + t * 16u) / 4 + s]; - want[(size_t)c * T + t] = a; } - uint64_t ns[5]; size_t bad = 0; int ok = 1; - if (omega_gpu_session_sync_to_gpu(&src) != 0) ok = 0; - for (int r = 0; r < 5 && ok; r++) { - ns[r] = 0; uint32_t *o = out.cpu; memset(o, 0xee, ob); - uint32_t args[4] = { (uint32_t)src.va, (uint32_t)(src.va >> 32), (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = omega_bw_gpr_declared(p.regalloc.peak_gpr_usage), .threads_x = T, .threads_y = 1, .grid_x = grid, .grid_y = 1, - .num_elements = ob / 4, .args = args, .n_args = 4, .timeout_ms = 20000 }; - if (omega_gpu_session_sync_to_gpu(&out) != 0 || omega_gpu_session_launch(&L, &ns[r], NULL) != 0 || omega_gpu_session_sync_to_cpu(&out) != 0) { printf("bw launch failed: %s\n", omega_gpu_session_last_error()); ok = 0; break; } - for (size_t q = 0; q < (size_t)grid * T; q++) if (o[q] != want[q]) bad++; - } - if (ok) { qsort(ns, 5, 8, cmp_u64); double bytes = (double)grid * region; - printf("bw %s, %zu KB per CTA, %u CTAs: median %.1f us, %.1f GB/s delivered (%zu MB distinct), %zu wrong\n", groups == 1 ? "SAME bytes for every CTA" : "distinct bytes per CTA", region >> 10, grid, ns[2] / 1e3, bytes / ns[2], sb >> 20, bad); - if (bad) fail++; } else fail++; - free(want); omega_gpu_session_free(&code); omega_gpu_session_free(&src); omega_gpu_session_free(&out); - } - omega_gpu_session_unlock(); - printf("GPU_TC_PEAK: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} diff --git a/tests/gpu_tc_probe_test.c b/tests/gpu_tc_probe_test.c deleted file mode 100644 index 934e4a03c..000000000 --- a/tests/gpu_tc_probe_test.c +++ /dev/null @@ -1,216 +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. - */ - -/* gpu_tc_probe_test.c (OWN-30B T3, 2026-10-13): characterise the chip's HMMA.16816.F32.BF16 arithmetic. - * --host-only model self-checks (the model family reproduces exact sums on exactly representable cases) - * (default) chip: CASES single-HMMA cases (one warp each) with operand classes chosen to separate the models - * (wide exponent spread, cancellation, accumulator dominance, bf16 subnormals); prints, per model of - * tests/bw_hmma_model.h, how many of the 128 * CASES outputs match the chip bit for bit; negative control: - * mutant 1 (C dropped) must differ on the cases with C != 0. - * Env TC_PROBE_SEED: a different random data set (confirmation runs). Verdict line: "TC_PROBE: model=... exact N/N" when one model matches every output, else "TC_PROBE: NO EXACT MODEL". - * Chip runs only under flock /tmp/aien-gb10.lock. */ -#include "omega_blackwell_codegen_tc.h" -#include "omega_gpu_session.h" -#include "bw_hmma_model.h" -#include -#include -#include - -#define CASES 2048u - -static uint64_t rng = 0x9e3779b97f4a7c15ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static uint16_t bf16_of(float f) { uint32_t u; memcpy(&u, &f, 4); return (uint16_t)(u >> 16); } /* truncation: the value is then exactly a bf16 */ -static float f_of_bf16(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; memcpy(&f, &u, 4); return f; } -/* a random bf16 with exponent in [lo, hi] */ -static float rbf(int lo, int hi) { - float m = 1.0f + (float)(rnd() & 127) / 128.0f; - int e = lo + (int)(rnd() % (uint32_t)(hi - lo + 1)); - float v = ldexpf(m, e); - if (rnd() & 1) v = -v; - return f_of_bf16(bf16_of(v)); -} - -typedef struct { float A[16][16], B[16][8], C[16][8]; } Case; - -static void gen_case(Case *c, unsigned idx) { - unsigned cls = idx % 6; - for (int r = 0; r < 16; r++) for (int k = 0; k < 16; k++) { - float v; - switch (cls) { - case 0: v = rbf(-2, 2); break; /* narrow range */ - case 1: v = rbf(-20, 20); break; /* wide spread: alignment truncation shows */ - case 2: v = (k & 1) ? rbf(-1, 1) : rbf(-12, 0); break; - case 3: v = rbf(-4, 4); break; /* with a big accumulator (below) */ - case 4: v = rbf(-130, -126); break; /* bf16 near / below the normal limit (subnormal products) */ - default: v = rbf(-8, 8); break; - } - if (cls == 4 && (rnd() & 3) == 0) { uint16_t h = (uint16_t)((rnd() & 0x7f) | (rnd() & 0x8000)); v = f_of_bf16(h); } /* bf16 subnormal */ - c->A[r][k] = v; - } - for (int k = 0; k < 16; k++) for (int n = 0; n < 8; n++) c->B[k][n] = cls == 4 ? rbf(-2, 2) : rbf(cls == 1 ? -20 : -3, cls == 1 ? 20 : 3); - for (int r = 0; r < 16; r++) for (int n = 0; n < 8; n++) { - float v = idx % 7 == 6 ? 0.0f : rbf(-6, 6); - if (cls == 3) v = rbf(10, 14); - if (cls == 2 && (rnd() & 1)) { /* cancellation: C = -(exact sum rounded) */ - double s = 0; for (int k = 0; k < 16; k++) s += (double)c->A[r][k] * c->B[k][n]; - v = (float)-s; - } - c->C[r][n] = v; - } -} -static uint32_t pack2(float lo, float hi) { return (uint32_t)bf16_of(lo) | ((uint32_t)bf16_of(hi) << 16); } -static void to_frag(const Case *c, uint32_t *in) { - uint32_t *A = in, *B = in + 128; float *C = (float *)(in + 192); - for (int L = 0; L < 32; L++) { - int g = L / 4, t = L % 4; - A[L * 4 + 0] = pack2(c->A[g][2 * t], c->A[g][2 * t + 1]); - A[L * 4 + 1] = pack2(c->A[g + 8][2 * t], c->A[g + 8][2 * t + 1]); - A[L * 4 + 2] = pack2(c->A[g][2 * t + 8], c->A[g][2 * t + 9]); - A[L * 4 + 3] = pack2(c->A[g + 8][2 * t + 8], c->A[g + 8][2 * t + 9]); - B[L * 2 + 0] = pack2(c->B[2 * t][g], c->B[2 * t + 1][g]); - B[L * 2 + 1] = pack2(c->B[2 * t + 8][g], c->B[2 * t + 9][g]); - C[L * 4 + 0] = c->C[g][2 * t]; C[L * 4 + 1] = c->C[g][2 * t + 1]; - C[L * 4 + 2] = c->C[g + 8][2 * t]; C[L * 4 + 3] = c->C[g + 8][2 * t + 1]; - } -} -/* output word (lane L, q) -> (row, col) */ -static void out_rc(int L, int q, int *r, int *n) { int g = L / 4, t = L % 4; *r = g + (q >= 2 ? 8 : 0); *n = 2 * t + (q & 1); } - -static float model_out(const HmmaModel *m, const Case *c, int r, int n) { - float a[16], b[16]; for (int k = 0; k < 16; k++) { a[k] = c->A[r][k]; b[k] = c->B[k][n]; } - return hm_dot16(m, a, b, c->C[r][n]); -} - -static int host_only(void) { - int fail = 0; - /* exactly representable sums must come out exact in every model */ - for (int i = 0; i < 1000; i++) { - float a[16], b[16]; for (int k = 0; k < 16; k++) { a[k] = (float)((int)(rnd() % 17) - 8); b[k] = (float)((int)(rnd() % 9) - 4); } - float c = (float)((int)(rnd() % 33) - 16); double ex = c; for (int k = 0; k < 16; k++) ex += (double)a[k] * b[k]; - int groups[] = { 0, 1, 2, 4, 8, 16 }; - for (int gi = 0; gi < 6; gi++) for (int rn = 0; rn < 2; rn++) { HmmaModel m = { groups[gi], 0, rn, 0, 0 }; if (hm_dot16(&m, a, b, c) != (float)ex) fail++; } - } - /* truncation is visible: 1 + 2^-30 (one product) in G=16, extra 0 truncates to 1, extra 6 keeps it only in double, RZ -> 1 */ - { float a[16] = { 1.0f, ldexpf(1.0f, -30) }, b[16] = { 1.0f, 1.0f }; HmmaModel m = { 16, 0, 0, 0, 0 }; if (hm_dot16(&m, a, b, 0.0f) != 1.0f) fail++; } - /* the probe's case generator produces bf16 values and its fragment packing round-trips */ - { static Case c; gen_case(&c, 7); uint32_t in[320]; to_frag(&c, in); if ((in[0] & 0xffff) != bf16_of(c.A[0][0])) fail++; } - printf("host-only model self-checks: %s (%d failures)\n", fail ? "FAIL" : "PASS", fail); - return fail ? 1 : 0; -} - -static int run_chip(int mutant, uint32_t *out_words, const uint32_t *in_words) { - BlackwellIRProgram *prog = calloc(1, sizeof *prog); - if (!prog || omega_blackwell_codegen_tc_probe_prog(mutant, prog) != 0) { printf("codegen failed\n"); free(prog); return -1; } - int rc = -1; - omega_gpu_session_lock(); - OmegaGpuMem code = {0}, in = {0}, out = {0}; - size_t need = omega_bw_program_code_bytes(prog); - OmegaBlackwellKernel k; - if (!omega_gpu_session_open()) { printf("open failed: %s\n", omega_gpu_session_last_error()); goto done; } - if (omega_gpu_session_alloc_code(need, &code) != 0 || omega_blackwell_kernel_encode_into(prog, code.cpu, need, &k) != 0 || omega_gpu_session_sync_to_gpu(&code) != 0) { printf("code upload failed\n"); goto done; } - if (omega_gpu_session_alloc((size_t)CASES * OMEGA_TC_PROBE_IN_BYTES, &in) != 0 || omega_gpu_session_alloc((size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES, &out) != 0) { printf("alloc failed\n"); goto done; } - memcpy(in.cpu, in_words, (size_t)CASES * OMEGA_TC_PROBE_IN_BYTES); - { float *o = out.cpu; for (size_t i = 0; i < (size_t)CASES * 128u; i++) o[i] = -999.0f; } - if (omega_gpu_session_sync_to_gpu(&in) != 0 || omega_gpu_session_sync_to_gpu(&out) != 0) goto done; - { - uint32_t args[4] = { (uint32_t)in.va, (uint32_t)(in.va >> 32), (uint32_t)out.va, (uint32_t)(out.va >> 32) }; - uint32_t peak = prog->regalloc.peak_gpr_usage, decl = omega_bw_gpr_declared(peak); - OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = decl < 64 ? 64 : decl, .threads_x = 32, .threads_y = 1, .grid_x = CASES, .grid_y = 1, - .num_elements = (size_t)CASES * 128u, .args = args, .n_args = 4, .timeout_ms = 10000 }; - uint64_t ns = 0; - if (omega_gpu_session_launch(&L, &ns, NULL) != 0) { printf("launch failed: %s\n", omega_gpu_session_last_error()); goto done; } - if (omega_gpu_session_sync_to_cpu(&out) != 0) goto done; - printf("chip launch mutant %d: peak %u declared %u, %llu ns\n", mutant, peak, L.gpr_count, (unsigned long long)ns); - } - memcpy(out_words, out.cpu, (size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES); - rc = 0; -done: - if (code.cpu) omega_gpu_session_free(&code); - if (in.cpu) omega_gpu_session_free(&in); - if (out.cpu) omega_gpu_session_free(&out); - omega_gpu_session_unlock(); - free(prog); - return rc; -} - -int main(int argc, char **argv) { - if (argc > 2 && strcmp(argv[1], "--dump") == 0) { /* raw code words for nvdisasm -b SM121 (offline check only) */ - static BlackwellIRProgram p; static uint8_t buf[OMEGA_BW_CODE_CAP_MAX]; size_t len = 0; - if (omega_blackwell_codegen_tc_probe_prog(argc > 3 ? atoi(argv[3]) : 0, &p) != 0 || omega_bw_encode_program(&p, buf, sizeof buf, &len) != 0) return 1; - FILE *f = fopen(argv[2], "wb"); if (!f) return 1; fwrite(buf, 1, len, f); fclose(f); printf("peak %u, %zu bytes\n", p.regalloc.peak_gpr_usage, len); return 0; - } - int host = argc > 1 && strcmp(argv[1], "--host-only") == 0; - if (getenv("TC_PROBE_SEED")) rng = strtoull(getenv("TC_PROBE_SEED"), NULL, 0) | 1u; /* fresh data for a confirmation run */ - if (host_only() != 0) return 1; - if (host) return 0; - static Case cases[CASES]; - uint32_t *in = calloc((size_t)CASES, OMEGA_TC_PROBE_IN_BYTES), *out = calloc((size_t)CASES, OMEGA_TC_PROBE_OUT_BYTES), *outm = calloc((size_t)CASES, OMEGA_TC_PROBE_OUT_BYTES); - for (unsigned i = 0; i < CASES; i++) { gen_case(&cases[i], i); to_frag(&cases[i], in + (size_t)i * (OMEGA_TC_PROBE_IN_BYTES / 4)); } - const char *replay = argc > 2 && strcmp(argv[1], "--replay") == 0 ? argv[2] : NULL, *save = argc > 2 && strcmp(argv[1], "--save") == 0 ? argv[2] : NULL; - if (replay) { /* model search over saved chip words (offline; the words came from a sealed chip run) */ - FILE *rf = fopen(replay, "rb"); if (!rf) return 1; - size_t got = fread(out, 1, (size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES, rf) + fread(outm, 1, (size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES, rf); fclose(rf); - if (got != 2u * CASES * OMEGA_TC_PROBE_OUT_BYTES) { printf("short replay file\n"); return 1; } - printf("replaying chip words from %s\n", replay); - } else { - if (run_chip(0, out, in) != 0) { printf("TC_PROBE: FAIL chip\n"); return 1; } - if (run_chip(1, outm, in) != 0) { printf("TC_PROBE: FAIL chip (mutant)\n"); return 1; } - if (save) { FILE *sf = fopen(save, "wb"); if (sf) { fwrite(out, 1, (size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES, sf); fwrite(outm, 1, (size_t)CASES * OMEGA_TC_PROBE_OUT_BYTES, sf); fclose(sf); } } - } - /* poison and plausibility: relative error vs the exact double sum */ - size_t poison = 0, far = 0, total = (size_t)CASES * 128u; - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - float v; memcpy(&v, &out[(size_t)i * 128 + L * 4 + q], 4); - if (v == -999.0f) poison++; - int r, n; out_rc(L, q, &r, &n); - double ex = cases[i].C[r][n], mag = fabs(ex); for (int k = 0; k < 16; k++) { double p = (double)cases[i].A[r][k] * cases[i].B[k][n]; ex += p; mag += fabs(p); } - if (fabs(v - ex) > 1e-5 * mag + 1e-37) far++; - } - printf("plausibility: %zu poison, %zu of %zu outputs farther than 1e-5 of the term magnitude from the exact sum\n", poison, far, total); - /* negative control: mutant 1 drops C; it must differ wherever C is nonzero and large enough to matter */ - size_t mdiff = 0, mcand = 0; - /* counted only where C is clearly significant: |C| >= 2^-8 |D| */ - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - int r, n; out_rc(L, q, &r, &n); float dv; memcpy(&dv, &out[(size_t)i * 128 + L * 4 + q], 4); - if (fabsf(cases[i].C[r][n]) < ldexpf(fabsf(dv), -8) || cases[i].C[r][n] == 0.0f) continue; - mcand++; if (out[(size_t)i * 128 + L * 4 + q] != outm[(size_t)i * 128 + L * 4 + q]) mdiff++; - } - printf("negative control (C dropped): %zu of %zu outputs with significant C differ (%s)\n", mdiff, mcand, mcand && mdiff == mcand ? "caught" : "NOT CAUGHT"); - /* model search */ - int groups[] = { 0, 1, 2, 4, 8, 16 }, best_i = -1; size_t best = 0; HmmaModel bestm = { 0, 0, 0, 0, 0 }; - static const char *clsname[6] = { "narrow", "wide", "mixed+cancel", "bigC", "subnormal", "medium" }; - for (int gi = 0; gi < 6; gi++) for (int ex = -1; ex <= 8; ex++) for (int rn = 0; rn < 2; rn++) for (int nom = 0; nom < 3; nom++) for (int cs = 0; cs < 2; cs++) { - if (groups[gi] == 0 && (ex || rn || nom || cs)) continue; - HmmaModel m = { groups[gi], ex, rn, nom, cs }; - size_t match = 0, cls_miss[6] = {0}; - for (unsigned i = 0; i < CASES; i++) for (int L = 0; L < 32; L++) for (int q = 0; q < 4; q++) { - int r, n; out_rc(L, q, &r, &n); - float mv = model_out(&m, &cases[i], r, n); uint32_t mu; memcpy(&mu, &mv, 4); - if (mu == out[(size_t)i * 128 + L * 4 + q]) match++; else cls_miss[i % 6]++; - } - if (match * 100 >= total * 90 || match == total) - printf("model group %2d extra %d %s nominal %d csep %d: %zu of %zu match (misses by class: %s %zu, %s %zu, %s %zu, %s %zu, %s %zu, %s %zu)\n", m.group, m.extra, m.rn ? "RN" : "RZ", m.nominal, m.csep, match, total, - clsname[0], cls_miss[0], clsname[1], cls_miss[1], clsname[2], cls_miss[2], clsname[3], cls_miss[3], clsname[4], cls_miss[4], clsname[5], cls_miss[5]); - if (match > best) { best = match; bestm = m; best_i = 1; } - } - if (best_i > 0) printf("best model: group %d extra %d %s: %zu of %zu\n", bestm.group, bestm.extra, bestm.rn ? "RN" : "RZ", best, total); - int ok = poison == 0 && far == 0 && mcand && mdiff == mcand; - if (ok && best == total) printf("TC_PROBE: model=group %d extra %d %s nominal %d csep %d exact %zu/%zu\n", bestm.group, bestm.extra, bestm.rn ? "RN" : "RZ", bestm.nominal, bestm.csep, best, total); - else printf("TC_PROBE: NO EXACT MODEL (best %zu/%zu)%s\n", best, total, ok ? "" : " and plausibility/control FAILED"); - free(in); free(out); free(outm); - return ok ? 0 : 1; -} diff --git a/tests/gpu_tcgemm_test.c b/tests/gpu_tcgemm_test.c deleted file mode 100644 index 340ff8a63..000000000 --- a/tests/gpu_tcgemm_test.c +++ /dev/null @@ -1,344 +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. - */ - -/* gpu_tcgemm_test.c (OWN-30B T3, 2026-10-13): tensor-core grouped FP8 GEMM (omega_blackwell_codegen_tc.h). - * --host-only program statistics and register budgets for the production shapes; the C emulation (exact HMMA model, - * tests/bw_hmma_model.h) against a double oracle; permutation and decode checks - * --sim the generated kernel in the warp simulator (both fragment orders) bit-identical to the C emulation; - * mutants 1-4 caught (a simulator error counts as a FAIL, never as caught) - * --chip (under flock /tmp/aien-gb10.lock) through omega_gpu_tcgemm_api: bit-identity to the emulation, second call - * identical, mutants caught on the chip, timing medians (TFLOPS, GB/s) at large M - * Verdict line last: "GPU_TCGEMM: PASS|FAIL". */ -#include "omega_blackwell_codegen_tc.h" -#include "omega_gpu_fp8_api.h" -#include "omega_gpu_session.h" -#include "omega_gpu_tcgemm_api.h" -#include -#include "bw_warp_sim_tc.h" -#include -#include -#include -#include -#include - -static const HmmaModel GB10 = { 16, 2, 0, 2, 0 }; -static uint64_t rng = 0x243f6a8885a308d3ull; -static uint32_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint32_t)(rng >> 16); } -static float frnd(void) { return ((float)(rnd() & 0xffffff) / 16777216.0f) * 2.0f - 1.0f; } -static float u2f(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } - -/* a problem: E experts of n x k e4m3, M sorted rows (expert ids non-decreasing), X source rows */ -typedef struct { - uint32_t E, n, k, M, xr; - uint8_t *w; /* E * n * k */ - uint16_t *sbf; /* E * (n/128) * (k/128) bf16 scale_inv */ - float *sf; /* folded f32 * 2^56 */ - float *x; /* xr * k */ - uint16_t *xp; /* xr * k stored (permuted bf16 * 2^64) */ - uint32_t *eid, *src; /* M */ -} Prob; - -static uint8_t rand_e4m3(void) { for (;;) { uint8_t c = (uint8_t)rnd(); if ((c & 0x7f) != 0x7f) return c; } } -static uint16_t bf16_trunc(float f) { uint32_t u; memcpy(&u, &f, 4); return (uint16_t)(u >> 16); } - -static void prob_make(Prob *p, uint32_t E, uint32_t n, uint32_t k, uint32_t M, uint32_t xr, int skewed) { - memset(p, 0, sizeof *p); - p->E = E; p->n = n; p->k = k; p->M = M; p->xr = xr; - size_t wn = (size_t)E * n * k, sn = (size_t)E * (n / 128) * (k / 128); - p->w = malloc(wn); p->sbf = malloc(sn * 2); p->sf = malloc(sn * 4); p->x = malloc((size_t)xr * k * 4); p->xp = malloc((size_t)xr * k * 2); - p->eid = malloc(M * 4); p->src = malloc(M * 4); - for (size_t i = 0; i < wn; i++) p->w[i] = rand_e4m3(); - for (size_t i = 0; i < sn; i++) p->sbf[i] = bf16_trunc(ldexpf(1.0f + (float)(rnd() & 127) / 128.0f, -(int)(rnd() % 12) - 4)); - if (omega_fp8_pack_scales(p->sbf, sn, p->sf, 0) != 0) { printf("scale pack failed\n"); exit(2); } - for (size_t i = 0; i < (size_t)xr * k; i++) p->x[i] = frnd() * (rnd() % 16 == 0 ? 8.0f : 1.0f); - for (uint32_t r = 0; r < xr; r++) omega_tcgemm_permute_x(p->x + (size_t)r * k, k, p->xp + (size_t)r * k); - /* expert ids: sorted; skewed puts many rows on a few experts (multi-tile segments) */ - for (uint32_t i = 0; i < M; i++) { uint32_t e = skewed ? (uint32_t)((uint64_t)i * i / ((uint64_t)M * M / E + 1)) : (uint32_t)((uint64_t)i * E / M); if (e >= E) e = E - 1; p->eid[i] = e; p->src[i] = rnd() % xr; } -} -static void prob_free(Prob *p) { free(p->w); free(p->sbf); free(p->sf); free(p->x); free(p->xp); free(p->eid); free(p->src); } - -/* stored index of element p in a permuted row: group (0,2,1,3) */ -static uint32_t stored_ix(uint32_t p) { static const uint32_t inv[4] = { 0, 2, 1, 3 }; return (p & ~3u) | inv[p & 3u]; } - -/* C emulation: exactly the kernel's arithmetic (8 HMMA steps per 128 block from a zero temporary, then fma with S') */ -static void emulate(const Prob *p, float *y) { - const uint32_t n = p->n, k = p->k, KB = k / 128; - for (uint32_t i = 0; i < p->M; i++) { - const uint16_t *xs = p->xp + (size_t)p->src[i] * k; - for (uint32_t c = 0; c < n; c++) { - const uint8_t *wr = p->w + ((size_t)p->eid[i] * n + c) * k; - const float *sr = p->sf + ((size_t)p->eid[i] * (n / 128) + c / 128) * KB; - float acc = 0.0f; - for (uint32_t kb = 0; kb < KB; kb++) { - float tmp = 0.0f; - for (uint32_t ch = 0; ch < 2; ch++) for (uint32_t s = 0; s < 4; s++) { - float a[16], b[16]; int m = 0; - for (uint32_t t = 0; t < 4; t++) for (uint32_t j = 0; j < 4; j++) { - uint32_t e = kb * 128 + ch * 64 + 16 * t + 4 * s + j; - a[m] = u2f((uint32_t)xs[stored_ix(e)] << 16); b[m] = u2f((uint32_t)omega_tcgemm_w_bf16(wr[e]) << 16); m++; - } - tmp = hm_dot16(&GB10, a, b, tmp); - } - acc = fmaf(tmp, sr[kb], acc); - } - y[(size_t)i * n + c] = acc; - } - } -} - -/* tiles: split every expert segment into runs of at most bm rows; rowidx padded by bm entries */ -typedef struct { uint64_t w_va, s_va; uint32_t row0, cnt, pad[2]; } Tile; -static uint32_t make_tiles(const Prob *p, uint32_t bm, Tile *t, const uint8_t *wbase, const float *sbase) { - uint32_t nt = 0; - for (uint32_t i = 0; i < p->M;) { - uint32_t j = i; while (j < p->M && p->eid[j] == p->eid[i]) j++; - for (uint32_t r = i; r < j; r += bm) { - memset(&t[nt], 0, sizeof t[nt]); - t[nt].w_va = (uint64_t)(uintptr_t)(wbase + (size_t)p->eid[i] * p->n * p->k); - t[nt].s_va = (uint64_t)(uintptr_t)(sbase + (size_t)p->eid[i] * (p->n / 128) * (p->k / 128)); - t[nt].row0 = r; t[nt].cnt = j - r < bm ? j - r : bm; nt++; - } - i = j; - } - return nt; -} - -static int host_only(void) { - int fail = 0; - /* decode: every non-NaN code, the bf16 bits are the value * 2^-120 exactly */ - for (unsigned c = 0; c < 256; c++) { - if ((c & 0x7f) == 0x7f) continue; - unsigned e = (c >> 3) & 15, m = c & 7; double v = e ? ldexp(1.0 + m / 8.0, (int)e - 7) : ldexp(m / 8.0, -6); if (c & 0x80) v = -v; - if ((double)u2f((uint32_t)omega_tcgemm_w_bf16((uint8_t)c) << 16) != ldexp(v, -120)) { printf("decode code %02x wrong\n", c); fail++; } - } - { char pm[200]; int pr = omega_tc_patch_selftest(pm, sizeof pm); printf("placeholder patch self-test: %s (%s)\n", pr ? "FAIL" : "ok", pm); if (pr) fail++; } - /* production shapes: instructions and registers (declared = peak + 2 rounded to 8 <= 128; 32 * warps * declared <= 65536) */ - static const OmegaTcGemmSpec shapes[] = { - { 2048, 4, 2, 8, 0 }, { 768, 4, 2, 8, 0 }, { 4096, 4, 2, 8, 0 }, { 2048, 4, 1, 8, 0 }, { 2048, 2, 2, 4, 0 }, { 2048, 4, 2, 4, 0 }, { 768, 4, 2, 4, 0 }, - { 5120, 4, 2, 8, 0 }, { 17408, 4, 2, 8, 0 }, { 32768, 4, 2, 8, 0 }, /* Qwen3.8-27B widths and the new cap (omega#541) */ - }; - static BlackwellIRProgram prog; - for (size_t i = 0; i < sizeof shapes / sizeof shapes[0]; i++) { - int rc = omega_blackwell_codegen_tcgemm_prog(&shapes[i], &prog); - uint32_t peak = rc == 0 ? prog.regalloc.peak_gpr_usage : 0, decl = omega_bw_gpr_declared(peak); - int ok = rc == 0 && decl <= 128u && 32u * shapes[i].warps * decl <= 65536u; - printf("shape k %u rt %u ct %u warps %u: rc %d, %zu instructions, peak %u, declared %u, shared %u, span %u: %s\n", shapes[i].k, shapes[i].rt, shapes[i].ct, shapes[i].warps, - rc, rc == 0 ? prog.count : 0, peak, decl, omega_tcgemm_shared_bytes(&shapes[i]), omega_tcgemm_span(&shapes[i]), ok ? "ok" : "REFUSED"); - if (i < 2 && !ok) fail++; - } - /* emulation vs double oracle (x as stored bf16, true e4m3 and bf16 scale): relative to the sum of |terms| */ - Prob p; prob_make(&p, 3, 256, 512, 40, 17, 0); - float *y = malloc((size_t)p.M * p.n * 4); emulate(&p, y); - double worst = 0; - for (uint32_t i = 0; i < p.M; i++) for (uint32_t c = 0; c < p.n; c++) { - double s = 0, mag = 0; - for (uint32_t e = 0; e < p.k; e++) { - double wv = (double)u2f((uint32_t)omega_tcgemm_w_bf16(p.w[((size_t)p.eid[i] * p.n + c) * p.k + e]) << 16) * ldexp(1.0, 120); - double xv = (double)u2f((uint32_t)p.xp[(size_t)p.src[i] * p.k + stored_ix(e)] << 16) * ldexp(1.0, -64); - double sv = (double)u2f((uint32_t)p.sbf[((size_t)p.eid[i] * (p.n / 128) + c / 128) * (p.k / 128) + e / 128] << 16); - s += wv * xv * sv; mag += fabs(wv * xv * sv); - } - double rel = fabs(y[(size_t)i * p.n + c] - s) / (mag + 1e-30); if (rel > worst) worst = rel; - } - printf("emulation vs double oracle: worst |err| / sum|terms| = %.3g (%s, bound 1e-6)\n", worst, worst < 1e-6 ? "ok" : "FAIL"); - if (worst >= 1e-6) fail++; - free(y); prob_free(&p); - printf("host-only: %s\n", fail ? "FAIL" : "PASS"); - return fail; -} - -/* run the kernel in the simulator on p; returns 0 and fills y, or -1 with msg */ -static int sim_run(const Prob *p, const OmegaTcGemmSpec *sp, int order, float *y, char *msg, size_t msgn) { - static BlackwellIRProgram prog; - if (omega_blackwell_codegen_tcgemm_prog(sp, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - const uint32_t bm = 16u * sp->rt, span = omega_tcgemm_span(sp); - if (p->n % span) { snprintf(msg, msgn, "n %% span"); return -1; } - Tile *tiles = calloc(p->M + 1, sizeof *tiles); - uint32_t nt = make_tiles(p, bm, tiles, p->w, p->sf); - uint32_t *ridx = malloc((p->M + bm) * 4); for (uint32_t i = 0; i < p->M + bm; i++) ridx[i] = i < p->M ? p->src[i] : 0; - for (size_t i = 0; i < (size_t)p->M * p->n; i++) y[i] = -999.0f; - uint8_t *smem = malloc(omega_tcgemm_shared_bytes(sp)); - static WsSim s; memset(&s, 0, sizeof s); - s.p = &prog; s.threads = 32u * sp->warps; s.smem = smem; s.smem_bytes = omega_tcgemm_shared_bytes(sp); s.order = order; - uint64_t a[5] = { (uintptr_t)tiles, (uintptr_t)ridx, (uintptr_t)p->xp, (uintptr_t)y, p->n }; - for (int i = 0; i < 4; i++) { s.cbank[(0x380 + 8 * i) / 4] = (uint32_t)a[i]; s.cbank[(0x380 + 8 * i) / 4 + 1] = (uint32_t)(a[i] >> 32); } - s.cbank[0x3a0 / 4] = p->n; - s.ranges[0].lo = (uintptr_t)tiles; s.ranges[0].hi = (uintptr_t)(tiles + nt); - s.ranges[1].lo = (uintptr_t)ridx; s.ranges[1].hi = (uintptr_t)(ridx + p->M + bm); - s.ranges[2].lo = (uintptr_t)p->xp; s.ranges[2].hi = (uintptr_t)(p->xp + (size_t)p->xr * p->k); - s.ranges[3].lo = (uintptr_t)y; s.ranges[3].hi = (uintptr_t)(y + (size_t)p->M * p->n); - s.ranges[4].lo = (uintptr_t)p->w; s.ranges[4].hi = (uintptr_t)(p->w + (size_t)p->E * p->n * p->k); - s.ranges[5].lo = (uintptr_t)p->sf; s.ranges[5].hi = (uintptr_t)(p->sf + (size_t)p->E * (p->n / 128) * (p->k / 128)); - s.nranges = 6; - int err = ws_run(&s, p->n / span, nt); - if (err) snprintf(msg, msgn, "simulator %s", s.msg); - free(tiles); free(ridx); free(smem); - return err ? -1 : 0; -} - -static int sim_tests(void) { - int fail = 0; - static const struct { uint32_t E, n, k, M, xr; int skew; OmegaTcGemmSpec sp; } pts[] = { - { 3, 256, 256, 40, 13, 0, { 256, 4, 2, 8, 0 } }, - { 2, 128, 384, 70, 9, 1, { 384, 4, 2, 8, 0 } }, /* three blocks, a multi-tile segment */ - { 4, 128, 128, 37, 11, 0, { 128, 2, 2, 4, 0 } }, - { 2, 256, 256, 20, 7, 0, { 256, 4, 1, 8, 0 } }, - { 2, 128, 256, 33, 5, 1, { 256, 1, 4, 4, 0 } }, - { 1, 512, 256, 64, 64, 0, { 256, 4, 2, 8, 0 } }, /* dense: one expert, four CTAs across n */ - { 1, 128, 17408, 64, 64, 0, { 17408, 4, 2, 8, 0 } }, /* Qwen3.8-27B down width (omega#541) */ - }; - for (size_t i = 0; i < sizeof pts / sizeof pts[0]; i++) { - Prob p; prob_make(&p, pts[i].E, pts[i].n, pts[i].k, pts[i].M, pts[i].xr, pts[i].skew); - float *ye = malloc((size_t)p.M * p.n * 4), *ys = malloc((size_t)p.M * p.n * 4), *y0 = malloc((size_t)p.M * p.n * 4); - emulate(&p, ye); - for (int order = 0; order < 2; order++) { - char msg[240] = ""; int rc = sim_run(&p, &pts[i].sp, order, ys, msg, sizeof msg); - size_t bad = 0, poison = 0; - if (rc == 0) for (size_t q = 0; q < (size_t)p.M * p.n; q++) { if (ys[q] == -999.0f) poison++; if (memcmp(&ys[q], &ye[q], 4)) bad++; } - if (order == 0 && rc == 0) memcpy(y0, ys, (size_t)p.M * p.n * 4); - int same = order == 0 || (rc == 0 && memcmp(y0, ys, (size_t)p.M * p.n * 4) == 0); - printf("sim E %u n %u k %u M %u rt %u ct %u warps %u order %d: %s %s%zu of %zu differ from the emulation, %zu unwritten%s\n", p.E, p.n, p.k, p.M, pts[i].sp.rt, pts[i].sp.ct, pts[i].sp.warps, order, - rc ? "ERROR" : (bad || poison || !same) ? "MISMATCH" : "ok", msg, bad, (size_t)p.M * p.n, poison, bad || poison ? "" : " (bit-identical)"); - if (rc || bad || poison || !same) fail++; - } - free(ye); free(ys); free(y0); prob_free(&p); - } - /* mutants: each must run cleanly in the simulator and differ from the emulation */ - for (int m = 1; m <= 4; m++) { - Prob p; prob_make(&p, 2, 128, 384, 50, 9, 1); - float *ye = malloc((size_t)p.M * p.n * 4), *ys = malloc((size_t)p.M * p.n * 4); - emulate(&p, ye); - OmegaTcGemmSpec sp = { 384, 4, 2, 8, m }; - char msg[240] = ""; int rc = sim_run(&p, &sp, 0, ys, msg, sizeof msg); - size_t bad = 0; if (rc == 0) for (size_t q = 0; q < (size_t)p.M * p.n; q++) if (memcmp(&ys[q], &ye[q], 4)) bad++; - printf("sim mutant %d: %s %s(%zu of %zu differ)\n", m, rc ? "ERROR (counts as FAIL)" : bad ? "caught" : "NOT CAUGHT", msg, bad, (size_t)p.M * p.n); - if (rc || !bad) fail++; - free(ye); free(ys); prob_free(&p); - } - printf("sim: %s\n", fail ? "FAIL" : "PASS"); - return fail; -} - -int chip_tests(int argc, char **argv); - -int main(int argc, char **argv) { - if (argc > 2 && strcmp(argv[1], "--dump") == 0) { /* raw code words for nvdisasm -b SM121 (offline check only): --dump file [k rt ct warps mutant] */ - static BlackwellIRProgram dp; static uint8_t buf[OMEGA_BW_CODE_CAP_MAX]; size_t len = 0; - OmegaTcGemmSpec sp = { argc > 3 ? (uint32_t)atoi(argv[3]) : 2048u, argc > 4 ? (uint32_t)atoi(argv[4]) : 4u, argc > 5 ? (uint32_t)atoi(argv[5]) : 2u, argc > 6 ? (uint32_t)atoi(argv[6]) : 8u, argc > 7 ? atoi(argv[7]) : 0 }; - if (omega_blackwell_codegen_tcgemm_prog(&sp, &dp) != 0 || omega_bw_encode_program(&dp, buf, sizeof buf, &len) != 0) return 1; - FILE *f = fopen(argv[2], "wb"); if (!f) return 1; fwrite(buf, 1, len, f); fclose(f); printf("peak %u, %zu bytes\n", dp.regalloc.peak_gpr_usage, len); return 0; - } - int host = 0, sim = 0, chip = 0; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--host-only")) host = 1; - else if (!strcmp(argv[i], "--sim")) sim = 1; - else if (!strcmp(argv[i], "--chip")) chip = 1; - } - if (!host && !sim && !chip) host = sim = 1; - int fail = 0; - if (host) fail += host_only(); - if (sim && !fail) fail += sim_tests(); - if (chip && !fail) fail += chip_tests(argc, argv); - printf("GPU_TCGEMM: %s\n", fail ? "FAIL" : "PASS"); - return fail ? 1 : 0; -} - - -/* ------------------------------------------------------------- chip */ -/* route `tokens` tokens to top-8 of E experts (distinct, uniform), sorted by expert; dense (E == 1): one row per token */ -static void route(Prob *p, uint32_t tokens) { - if (p->E == 1) { for (uint32_t i = 0; i < p->M; i++) { p->eid[i] = 0; p->src[i] = i; } return; } - uint32_t *cnt = calloc(p->E, 4), *pe = malloc((size_t)tokens * 8 * 4); - for (uint32_t t = 0; t < tokens; t++) for (uint32_t j = 0; j < 8; j++) { - uint32_t e; int dup; do { e = rnd() % p->E; dup = 0; for (uint32_t q = 0; q < j; q++) if (pe[t * 8 + q] == e) dup = 1; } while (dup); - pe[t * 8 + j] = e; cnt[e]++; - } - uint32_t *off = calloc(p->E + 1, 4); for (uint32_t e = 0; e < p->E; e++) off[e + 1] = off[e] + cnt[e]; - for (uint32_t t = 0; t < tokens; t++) for (uint32_t j = 0; j < 8; j++) { uint32_t e = pe[t * 8 + j], at = off[e]++; p->eid[at] = e; p->src[at] = t; } - free(cnt); free(pe); free(off); -} -static void emulate_rows(const Prob *p, const uint32_t *rows, uint32_t nr, float *out) { /* emulate only the listed rows */ - Prob q = *p; q.M = 1; - for (uint32_t i = 0; i < nr; i++) { q.eid = p->eid + rows[i]; q.src = p->src + rows[i]; emulate(&q, out + (size_t)i * p->n); } -} -static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } - -int chip_tests(int argc, char **argv) { - const char *shape = "gateup", *outp = NULL; uint32_t tokens = 128, reps = 9, check = 384; int mut = 1; - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i], "--shape") && i + 1 < argc) shape = argv[++i]; - else if (!strcmp(argv[i], "--tokens") && i + 1 < argc) tokens = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--reps") && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--check-rows") && i + 1 < argc) check = (uint32_t)atoi(argv[++i]); - else if (!strcmp(argv[i], "--out") && i + 1 < argc) outp = argv[++i]; - else if (!strcmp(argv[i], "--no-mutants")) mut = 0; - } - uint32_t E, n, k; - if (!strcmp(shape, "gateup")) { E = 128; n = 1536; k = 2048; } else if (!strcmp(shape, "down")) { E = 128; n = 2048; k = 768; } - else if (!strcmp(shape, "qkv")) { E = 1; n = 5120; k = 2048; } else if (!strcmp(shape, "o")) { E = 1; n = 2048; k = 4096; } - /* Qwen3.8-27B dense shapes (omega#541): MLP gate or up, down (k 17408), DeltaNet in_proj_qkv, out_proj / o_proj */ - else if (!strcmp(shape, "q38gate")) { E = 1; n = 17408; k = 5120; } else if (!strcmp(shape, "q38down")) { E = 1; n = 5120; k = 17408; } - else if (!strcmp(shape, "q38qkv")) { E = 1; n = 10240; k = 5120; } else if (!strcmp(shape, "q38o")) { E = 1; n = 5120; k = 6144; } - else { printf("unknown shape %s\n", shape); return 1; } - const uint32_t M = E == 1 ? tokens : tokens * 8u; - if (reps > 64) reps = 64; - int fail = 0; - Prob p; prob_make(&p, E, n, k, M, tokens, 0); route(&p, tokens); - OmegaGpuFp8Tensor *t = NULL; - int rc = omega_gpu_fp8_tensor_upload(E, n, k, p.w, p.sbf, &t); - if (rc != 0) { printf("chip: upload failed %d: %s\n", rc, omega_gpu_tcgemm_last_error()); prob_free(&p); return 1; } - float *y = malloc((size_t)M * n * 4), *y2 = malloc((size_t)M * n * 4); - OmegaGpuTcGemmInfo info; - rc = omega_gpu_tcgemm_f32(t, M, p.eid, p.src, p.x, tokens, y, &info); - if (rc) { printf("chip: call failed %s: %s\n", omega_gpu_tcgemm_rc_name(rc), omega_gpu_tcgemm_last_error()); fail++; goto done; } - printf("chip %s: %u tokens, M %u rows, %u segments, %u tiles, grid %u x %u, rt %u ct %u warps %u, declared %u registers\n", shape, tokens, M, info.segments, info.tiles, info.grid_x, info.grid_y, info.rt, info.ct, info.warps, info.gpr_declared); - { /* bit-identity on sampled rows: the first and last rows of the table and a stride across it */ - uint32_t nr = check < M ? check : M, *rows = malloc(nr * 4); float *ye = malloc((size_t)nr * n * 4); size_t bad = 0; - for (uint32_t i = 0; i < nr; i++) rows[i] = nr == M ? i : i < 8 ? i : i >= nr - 8 ? M - (nr - i) : (uint32_t)((uint64_t)i * M / nr); - emulate_rows(&p, rows, nr, ye); - for (uint32_t i = 0; i < nr; i++) for (uint32_t c = 0; c < n; c++) if (memcmp(&y[(size_t)rows[i] * n + c], &ye[(size_t)i * n + c], 4)) bad++; - printf("chip bit-identity: %zu of %zu sampled outputs (%u rows) differ from the emulation%s\n", bad, (size_t)nr * n, nr, bad ? "" : " (bit-identical)"); - if (bad) fail++; - free(rows); free(ye); - } - rc = omega_gpu_tcgemm_f32(t, M, p.eid, p.src, p.x, tokens, y2, &info); - { int same = rc == 0 && memcmp(y, y2, (size_t)M * n * 4) == 0; printf("chip second call: %s\n", same ? "identical" : "DIFFERS"); if (!same) fail++; } - if (mut) for (int m = 1; m <= 4; m++) { - omega_gpu_tcgemm_test_set_mutant(m); - rc = omega_gpu_tcgemm_f32(t, M, p.eid, p.src, p.x, tokens, y2, NULL); - size_t b = 0; if (rc == 0) for (size_t q = 0; q < (size_t)M * n; q++) if (memcmp(&y[q], &y2[q], 4)) b++; - printf("chip mutant %d: %s (%zu of %zu differ)%s%s\n", m, rc ? "ERROR (counts as FAIL)" : b ? "caught" : "NOT CAUGHT", b, (size_t)M * n, rc ? " " : "", rc ? omega_gpu_tcgemm_last_error() : ""); - if (rc || !b) fail++; - } - omega_gpu_tcgemm_test_set_mutant(0); - { - uint64_t ce[64], cc[64]; uint32_t done = 0; - for (uint32_t r = 0; r < reps; r++) { if (omega_gpu_tcgemm_f32(t, M, p.eid, p.src, p.x, tokens, y2, &info) == 0) { ce[done] = info.elapsed_ns; cc[done] = info.call_ns; done++; } } - if (done != reps) { printf("chip timing: %u of %u calls failed\n", reps - done, reps); fail++; } - if (done) { - qsort(ce, done, 8, cmp_u64); qsort(cc, done, 8, cmp_u64); - double ns = (double)ce[done / 2], flops = 2.0 * M * n * k; - printf("TCGEMM %s (medians of %u): chip %.1f us, call %.1f us; %.2f TFLOPS; weights streamed %.0f MB (%.1f GB/s), activations gathered %.0f MB, output %.0f MB; total %.1f GB/s\n", shape, done, ns / 1e3, cc[done / 2] / 1e3, - flops / ns / 1e3, info.streamed_bytes / 1e6, info.streamed_bytes / ns, info.act_bytes / 1e6, (double)M * n * 4 / 1e6, (info.streamed_bytes + info.act_bytes + (double)M * n * 4) / ns); - if (outp) { FILE *f = fopen(outp, "w"); if (f) { fprintf(f, "{\"shape\":\"%s\",\"tokens\":%u,\"rows\":%u,\"tiles\":%u,\"reps\":%u,\"chip_median_ns\":%.0f,\"call_median_ns\":%" PRIu64 ",\"tflops\":%.3f,\"streamed_bytes\":%" PRIu64 ",\"act_bytes\":%" PRIu64 ",\"fail\":%d}\n", - shape, tokens, M, info.tiles, done, ns, cc[done / 2], flops / ns / 1e3, info.streamed_bytes, info.act_bytes, fail); fclose(f); } } - } - } -done: - free(y); free(y2); omega_gpu_fp8_tensor_free(t); prob_free(&p); - printf("chip: %s\n", fail ? "FAIL" : "PASS"); - return fail; -} diff --git a/tests/gpu_tern_test.c b/tests/gpu_tern_test.c index 16dfca40f..363c22687 100644 --- a/tests/gpu_tern_test.c +++ b/tests/gpu_tern_test.c @@ -110,7 +110,9 @@ static uint32_t rand_word(uint32_t *st, int mode) { } /* Independent stall checker (a different walk from the generator's pass): for every fixed-latency write, scan forward * summing stalls; any instruction that touches one of its registers, any control instruction and any branch target - * reached before OMEGA_TERN_FIXED_LAT cycles is a violation. */ + * reached before OMEGA_TERN_FIXED_LAT cycles is a violation. I2FP is fixed latency too (it writes no scoreboard: a wait + * on one did not hold its reader on the GB10, omega #924 chip A/B 2040 of 3840 rows); its readers must also sit + * OMEGA_TERN_I2FP_LAT cycles behind, judged by omega_tern_i2fp_violations. */ static int chk_fixed(BlackwellIROpcode op) { return op == BW_IR_IMAD || op == BW_IR_IMAD_WIDE || op == BW_IR_SHF_R || op == BW_IR_LOP3_AND || op == BW_IR_MOV_IMM || op == BW_IR_MOV_RZ || op == BW_IR_FMUL || op == BW_IR_I2FP; @@ -215,6 +217,7 @@ static void host_battery(void) { const int ok = rc == 0 && omega_blackwell_codegen_tern_gemv_prog(&sp, &cp) == 0; const long v = ok ? stall_violations(&cp, &cyc) : -1; CHECK(v == 0, "stall distances k %u layout %d epi %d: %ld users closer than %u cycles to a fixed-latency write", sp.k, lay, epi, v, OMEGA_TERN_FIXED_LAT); + CHECK(ok && omega_tern_i2fp_violations(&cp) == 0, "I2FP readers k %u layout %d epi %d sit >= %u cycles behind, no scoreboard", sp.k, lay, epi, OMEGA_TERN_I2FP_LAT); /* negative control: a fixed-latency stall above 1 is binding by construction, so shortening it must be caught */ size_t at = cp.count; for (size_t q = 0; ok && q < cp.count; q++) if (chk_fixed(cp.insns[q].op) && ((cp.insns[q].control >> 9) & 0xfu) > 1u) { at = q; break; } @@ -248,7 +251,7 @@ static int sim_run(const OmegaTernGemvSpec *spec, uint32_t n, const int8_t *w, c float a, uint32_t grid_x, int order, uint32_t *y_out, char *msg, size_t msgn) { static BlackwellIRProgram prog; if (omega_blackwell_codegen_tern_gemv_prog(spec, &prog) != 0) { snprintf(msg, msgn, "codegen refused"); return -1; } - if (stall_violations(&prog, NULL) != 0) { snprintf(msg, msgn, "stall distance violation"); return -1; } + if (stall_violations(&prog, NULL) != 0 || omega_tern_i2fp_violations(&prog) != 0) { snprintf(msg, msgn, "stall distance violation"); return -1; } const uint32_t k = spec->k, np = omega_gpu_tern_padded_rows(n); const size_t wbytes = (size_t)np * k / 4u; uint32_t *pk = aligned_alloc(16, wbytes); 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 5f0eecf42..7e48a4e20 100755 --- a/tests/run_tensor_chip.sh +++ b/tests/run_tensor_chip.sh @@ -92,9 +92,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" \ @@ -104,7 +107,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 @@ -181,6 +184,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" \ @@ -193,6 +197,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/tests/test_omega_blackwell_engine.c b/tests/test_omega_blackwell_engine.c deleted file mode 100644 index 5d79271fb..000000000 --- a/tests/test_omega_blackwell_engine.c +++ /dev/null @@ -1,1090 +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. - */ - -/* - * Host test of the REAL Blackwell backend (src/omega_blackwell_engine.c), the - * REAL engine core (src/omega_gpu_engine.c) and the REAL vector wrapper - * omega_blackwell_execute_vector (src/omega_blackwell_submit.c), driven through - * a SIMULATED driver (tests/fake_m16_native.c). Cut A3b2. NOT_RUN: this file has - * never been compiled or executed by its author (Phase A rule). - * - * No GPU, no device node, no physics C sources: the seven driver symbols the - * backend calls are replaced by the fake. Every check prints "[PASS] id" or - * "[FAIL] id"; the last line is "SUMMARY passed=N failed=M"; the exit status is - * nonzero on any failure. docs/numeric/OMEGA_GPU_ENGINE.md section 14.1 lists - * every id and the mutants that need it. - * - * Techniques: - * - A tracing copy of the real backend table logs every callback (so the call - * order the core and the backend produce together can be asserted) and - * forwards to the original. The real table is never edited. - * - The fake parses and executes the pushbuffer, so the descriptors, the - * release packets and the L2 flush are checked as the device would see them. - * - A retained run (uncertain completion) leaves the backend busy by design. - * The test asserts that, then drains the backend through its own table - * (free every role, close), exactly what a process exit would do. - * - * Failure names that no driver fault can reach through the real backend, and so - * are covered by the fake-backend test (tests/test_omega_gpu_engine.c) only: - * PREPARE (copy-in and build refuse only on arguments the core already - * validated, and alloc_checked catches bad buffers first as ALLOC), - * VISIBILITY_WAIT (the barrier always returns 0, copy_out refuses only on bad - * arguments), - * INTERNAL_INVARIANT (the table is complete). - * The CPU barrier (dsb sy) has no effect a host can observe; it is chip only. - */ -#include "omega_gpu_engine.h" -#include "omega_blackwell_engine.h" -#include "omega_blackwell_submit.h" -#include "omega_blackwell_encoder.h" -#include "omega_vector.h" -#include "fake_m16_native.h" - -#include -#include -#include -#include -#include - -#define N 100u /* not a multiple of 64: a grid rounded down leaves words unwritten */ -#define TMO_MARKER 111u -#define TMO_MARKER2 222u -#define TMO_RELEASE 333u -#define TMO_VISIBILITY 444u - -#define MARKER1_PAYLOAD 0x44444444u -#define MARKER2_PAYLOAD 0x46464646u -#define SEM_INIT 5u -#define SEM_DONE 6u -#define RELEASE_FLAGS 0x00100001u /* RELEASE | WFI */ -#define FLUSH_OP (0x10u << 27) /* L2_FLUSH_DIRTY */ - -static int n_pass; -static int n_fail; - -static void check(const char *id, int ok) -{ - if (ok) { - n_pass++; - printf("[PASS] %s\n", id); - } else { - n_fail++; - printf("[FAIL] %s\n", id); - } -} - -/* ---- test data -------------------------------------------------------------- */ - -static uint32_t ina[N]; -static uint32_t inb[N]; -static uint32_t expect_out[N]; -static uint32_t poison[N]; -static uint32_t outbuf[N]; -static uint8_t prog[512]; -static uint8_t prog_other[512]; -static uint8_t vec_code[0x1000]; -static size_t vec_len; -static uint8_t bigbytes[0x2000]; -static uint32_t bigwords[2048]; - -static void init_data(void) -{ - uint32_t i; - for (i = 0; i < N; i++) { - uint32_t s; - ina[i] = i * 0x01000193u + 0x01234567u; - inb[i] = i * 0x9e3779b1u + 7u; - s = ina[i] + inb[i]; - /* a wrong-by-one result must never look like the poison word */ - if (s == 0x7fffffffu || s == 0xffffffffu) inb[i] += 0x10u; - } - /* the old fixed poison value as a legitimate sum */ - ina[7] = 0xdeadbeefu - 5u; - inb[7] = 5u; - for (i = 0; i < N; i++) { - expect_out[i] = ina[i] + inb[i]; - poison[i] = ~expect_out[i]; - } - for (i = 0; i < sizeof prog; i++) { - prog[i] = (uint8_t)(i * 7u + 3u); - prog_other[i] = (uint8_t)(i * 11u + 5u); - } -} - -static int output_correct(const uint32_t *o) -{ - uint32_t i; - for (i = 0; i < N; i++) - if (o[i] != expect_out[i]) return 0; - return 1; -} - -/* ---- tracing copy of the real backend table ---------------------------------- */ - -enum { - T_OPEN = 1, T_CHANNEL, T_ALLOC, T_COPY_IN, T_POISON, T_BUILD, T_SUBMIT, T_WAIT1, - T_WAIT2, T_WAITSEM, T_BARRIER, T_COPY_OUT, T_FREE, T_CLOSE -}; -#define TLOG_MAX 128 - -static const OmegaGpuBackend *g_real; -static OmegaGpuBackend g_wrap; -static int g_tlog[TLOG_MAX]; -static int g_targ[TLOG_MAX]; -static int g_tn; - -static void tlog(int kind, int arg) -{ - if (g_tn < TLOG_MAX) { - g_tlog[g_tn] = kind; - g_targ[g_tn] = arg; - g_tn++; - } -} - -static int w_open(void *ctx) { tlog(T_OPEN, 0); return g_real->open_device(ctx); } -static int w_channel(void *ctx) { tlog(T_CHANNEL, 0); return g_real->create_channel(ctx); } -static int w_alloc(void *ctx, int role, size_t bytes) { tlog(T_ALLOC, role); return g_real->alloc(ctx, role, bytes); } -static int w_copy_in(void *ctx, int role, const void *src, size_t bytes) { tlog(T_COPY_IN, role); return g_real->copy_in(ctx, role, src, bytes); } -static int w_poison(void *ctx, const uint32_t *words, size_t count) { tlog(T_POISON, 0); return g_real->fill_poison(ctx, words, count); } -static int w_build(void *ctx, const OmegaGpuJob *job) { tlog(T_BUILD, 0); return g_real->build(ctx, job); } -static int w_submit(void *ctx) { tlog(T_SUBMIT, 0); return g_real->submit(ctx); } -static int w_wait1(void *ctx, uint64_t ms) { tlog(T_WAIT1, 0); return g_real->wait_marker(ctx, ms); } -static int w_wait2(void *ctx, uint64_t ms) { tlog(T_WAIT2, 0); return g_real->wait_marker2(ctx, ms); } -static int w_waitsem(void *ctx, uint64_t ms) { tlog(T_WAITSEM, 0); return g_real->wait_release_semaphore(ctx, ms); } -static int w_barrier(void *ctx, uint64_t ms) { tlog(T_BARRIER, 0); return g_real->barrier(ctx, ms); } -static int w_copy_out(void *ctx, void *dst, size_t bytes) { tlog(T_COPY_OUT, 0); return g_real->copy_out(ctx, dst, bytes); } -static void w_diag(void *ctx, OmegaGpuBackendDiag *d) { g_real->diagnostics(ctx, d); } -static int w_free(void *ctx, int role) { tlog(T_FREE, role); return g_real->free_buf(ctx, role); } -static int w_close(void *ctx) { tlog(T_CLOSE, 0); return g_real->close(ctx); } - -static void wrap_init(void) -{ - g_real = omega_blackwell_engine_backend(); - g_wrap = *g_real; - g_wrap.open_device = w_open; - g_wrap.create_channel = w_channel; - g_wrap.alloc = w_alloc; - g_wrap.copy_in = w_copy_in; - g_wrap.fill_poison = w_poison; - g_wrap.build = w_build; - g_wrap.submit = w_submit; - g_wrap.wait_marker = w_wait1; - g_wrap.wait_marker2 = w_wait2; - g_wrap.wait_release_semaphore = w_waitsem; - g_wrap.barrier = w_barrier; - g_wrap.copy_out = w_copy_out; - g_wrap.diagnostics = w_diag; - g_wrap.free_buf = w_free; - g_wrap.close = w_close; -} - -static int tcount(int kind) -{ - int i; - int n = 0; - for (i = 0; i < g_tn; i++) - if (g_tlog[i] == kind) n++; - return n; -} - -/* ---- case plumbing ---------------------------------------------------------- */ - -static OmegaGpuJob job; -static OmegaGpuResult res; - -static void make_job(OmegaGpuJob *j) -{ - memset(j, 0, sizeof *j); - j->program = prog; - j->program_len = sizeof prog; - j->layout = OMEGA_GPU_LAYOUT_VECTOR_1D; - j->element_count = N; - j->input_a = ina; - j->input_a_len = N * 4u; - j->input_b = inb; - j->input_b_len = N * 4u; - j->output = outbuf; - j->output_len = N * 4u; - j->poison = poison; - j->poison_count = N; - j->timeouts.marker_ms = TMO_MARKER; - j->timeouts.marker2_ms = TMO_MARKER2; - j->timeouts.release_semaphore_ms = TMO_RELEASE; - j->timeouts.visibility_ms = TMO_VISIBILITY; - j->flags = 0; -} - -static void begin_case(void) -{ - (void)omega_blackwell_engine_shutdown(); /* no device carried between cases */ - fake_reset(); - omega_gpu_engine_test_reset_block(); - omega_gpu_engine_set_backend(&g_wrap); - g_tn = 0; - memset(outbuf, 0, sizeof outbuf); - fk.prog_expect = prog; - fk.prog_len = sizeof prog; - make_job(&job); -} - -static int run(void) -{ - return omega_gpu_execute(&job, &res); -} - -static int res_is(int failure, int step, int state) -{ - return res.failure == failure && res.failed_step == step && res.last_state == state; -} - -/* Everything the backend allocated was returned, the device was closed once, and - * the number of real driver frees is as expected. */ -static int balanced(int frees) -{ - return fk.live_at_close == 0 && fk.double_free == 0 && fk.close_calls == 1 && - fk.free_calls == frees && fk.device_open == 0; -} - -static int has(const char *hay, const char *needle) -{ - return strstr(hay, needle) != NULL; -} - -/* Drains a retained backend through its own table, the way process exit would: - * free every role (all of them are held), then close. Returns 0 if all went well. */ -static int drain(void) -{ - int bad = 0; - int role; - for (role = (int)OMEGA_GPU_BUF_ROLE_COUNT - 1; role >= 0; role--) - if (g_real->free_buf(g_real->ctx, role) != 0) bad = 1; - if (g_real->close(g_real->ctx) != 0) bad = 1; - return bad; -} - -static void idf(char *buf, size_t cap, const char *tag, const char *what) -{ - (void)snprintf(buf, cap, "sim_%s_%s", tag, what); -} - -/* ---- cases ------------------------------------------------------------------ */ - -static void case_success(void) -{ - static const int k_order[24] = { - T_OPEN, T_CHANNEL, T_ALLOC, T_ALLOC, T_ALLOC, T_ALLOC, T_ALLOC, T_COPY_IN, T_COPY_IN, - T_COPY_IN, T_POISON, T_BUILD, T_SUBMIT, T_WAIT1, T_WAIT2, T_WAITSEM, T_BARRIER, - T_COPY_OUT, T_FREE, T_FREE, T_FREE, T_FREE, T_FREE, T_CLOSE - }; - static const int k_args[24] = { - 0, 0, 0, 1, 2, 3, 4, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 2, 1, 0, 0 - }; - static const uint64_t k_sizes[8] = { - 0x10000u, 0x1000u, 0x1000u, 0x10000u, 0x1000u, 0x1000u, 0x1000u, 0x1000u - }; - OmegaBlackwellEngineRunInfo info; - int i; - int ok; - int i_cb, i_ar, i_q0, i_si, i_q1, i_k, i_r1, i_fl, i_r2; - - begin_case(); - check("sim_success_returns_ok", run() == OMEGA_GPU_ENGINE_OK); - check("sim_success_state", res.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS && - res.failed_step == OMEGA_GPU_ENGINE_STEP_NONE); - check("sim_success_result_flags_clear", - res.retained == 0 && res.cleanup_failed == 0 && res.wait == OMEGA_GPU_ENGINE_WAIT_NONE); - check("sim_success_not_blocked", omega_gpu_engine_is_blocked() == 0); - check("sim_success_output_values", output_correct(outbuf)); - check("sim_success_unchanged_zero", res.n_outputs == 1u && res.output_unchanged_words[0] == 0u); - - ok = g_tn == 24; - for (i = 0; ok && i < 24; i++) - if (g_tlog[i] != k_order[i] || g_targ[i] != k_args[i]) ok = 0; - check("sim_success_call_order", ok); - - check("sim_success_driver_counts", - fk.open_calls == 1 && fk.channel_calls == 1 && fk.alloc_calls == 8 && - fk.submit_calls == 1 && fk.close_calls == 1 && fk.wait_calls == 3); - check("sim_success_all_allocs_gpu_uncached", fk.uncached_calls == fk.alloc_calls && fk.uncached_calls == 8); - ok = fake_count(FK_EV_ALLOC) == 8; - for (i = 0; ok && i < 8; i++) - if (fk.ev[fake_nth(FK_EV_ALLOC, i + 1)].a != k_sizes[i]) ok = 0; - check("sim_success_alloc_sizes", ok); - check("sim_success_balanced", balanced(8)); - check("sim_success_large_pushbuffer_ring", fk.pb_mem_size == 0x10000u); - check("sim_success_pushbuffer_parses", fk.pb_parse_error == 0 && fk.ev_overflow == 0); - - /* The state the GPU sees at the doorbell: the sync words were zeroed first. */ - check("sim_success_doorbell_state_captured", fk.pre_valid == 1); - check("sim_success_marker1_zeroed_before_doorbell", fk.pre_marker1 == 0u); - check("sim_success_marker2_zeroed_before_doorbell", fk.pre_marker2 == 0u); - check("sim_success_semaphore_zeroed_before_doorbell", fk.pre_sem == 0u); - check("sim_success_semaphore_init_value", fk.sem_init_value == SEM_INIT); - - /* The pushbuffer, as the device executes it. */ - i_cb = fake_nth(FK_EV_PB_CBANK, 1); - i_ar = fake_nth(FK_EV_PB_ARGS, 1); - i_q0 = fake_nth(FK_EV_PB_QMD, 1); - i_si = fake_nth(FK_EV_PB_SEM_INIT, 1); - i_q1 = fake_nth(FK_EV_PB_QMD, 2); - i_k = fake_nth(FK_EV_KERNEL, 1); - i_r1 = fake_nth(FK_EV_PB_RELEASE, 1); - i_fl = fake_nth(FK_EV_PB_FLUSH, 1); - i_r2 = fake_nth(FK_EV_PB_RELEASE, 2); - check("sim_success_pushbuffer_order", - i_cb >= 0 && i_cb < i_ar && i_ar < i_q0 && i_q0 < i_si && i_si < i_q1 && i_q1 < i_k && - i_k < i_r1 && i_r1 < i_fl && i_fl < i_r2); - check("sim_success_one_flush_two_releases", - fake_count(FK_EV_PB_FLUSH) == 1 && fake_count(FK_EV_PB_RELEASE) == 2); - if (i_cb >= 0 && i_ar >= 0 && i_q0 >= 0 && i_q1 >= 0 && i_fl >= 0 && i_r1 >= 0 && i_r2 >= 0) { - check("sim_success_cbank_upload_words_and_place", - fk.ev[i_cb].b == 224u && fk.ev[i_cb].a == fk.alloc_va[1]); - check("sim_success_args_upload_words_and_place", - fk.ev[i_ar].b == 7u && fk.ev[i_ar].a == fk.ev[i_cb].a + 0x380u); - check("sim_success_qmd0_is_not_the_kernel_and_place", - fk.ev[i_q0].b == 0u && fk.ev[i_q0].a == fk.alloc_va[3]); - check("sim_success_qmd1_is_the_kernel_and_place", - fk.ev[i_q1].b == 1u && fk.ev[i_q1].a == fk.alloc_va[3] + 0x1000u); - check("sim_success_flush_operation", fk.ev[i_fl].a == (uint64_t)FLUSH_OP); - check("sim_success_release1_address_payload_flags", - fk.ev[i_r1].a == fk.marker1_va && fk.ev[i_r1].b == MARKER1_PAYLOAD && - fk.ev[i_r1].c == RELEASE_FLAGS); - check("sim_success_release2_is_marker_page_plus_0x10", - fk.ev[i_r2].a == fk.ev[i_r1].a + 0x10u); - check("sim_success_release2_payload_and_flags", - fk.ev[i_r2].b == MARKER2_PAYLOAD && fk.ev[i_r2].c == RELEASE_FLAGS); - } else { - check("sim_success_cbank_upload_words_and_place", 0); - check("sim_success_args_upload_words_and_place", 0); - check("sim_success_qmd0_is_not_the_kernel_and_place", 0); - check("sim_success_qmd1_is_the_kernel_and_place", 0); - check("sim_success_flush_operation", 0); - check("sim_success_release1_address_payload_flags", 0); - check("sim_success_release2_is_marker_page_plus_0x10", 0); - check("sim_success_release2_payload_and_flags", 0); - } - - /* The kernel launch the device saw. */ - check("sim_success_kernel_ran_once_with_right_program", fk.kernel_ran == 1 && fk.prog_matched == 1); - check("sim_success_kernel_threads_and_count", fk.kernel_threads == 128u && fk.kernel_n == N); - check("sim_success_kernel_arguments_are_a_b_output", - fk.arg_a == fk.alloc_va[5] && fk.arg_b == fk.alloc_va[6] && fk.arg_c == fk.alloc_va[7]); - check("sim_success_kernel_program_and_cbank_addresses", - fk.prog_va_seen == fk.alloc_va[4] && fk.cbank_va_seen == fk.alloc_va[1]); - check("sim_success_marker_and_semaphore_places", - fk.marker1_va == fk.alloc_va[2] && fk.sem_va == fk.alloc_va[3] + 0x2000u); - ok = fk.snap_n == N; - for (i = 0; ok && i < (int)N; i++) - if (fk.out_before[i] != poison[i]) ok = 0; - check("sim_success_poison_reached_device_output", ok); - check("sim_success_poison_never_equals_a_sum", fk.poison_collisions == 0); - - /* The waits, by word, expected value and timeout. */ - check("sim_success_wait_counts", - fk.wait_n[FK_W_MARKER1] == 1 && fk.wait_n[FK_W_MARKER2] == 1 && - fk.wait_n[FK_W_SEM] == 1 && fk.wait_n[FK_W_UNKNOWN] == 0); - check("sim_success_wait_expected_values", - fk.wait_expected[FK_W_MARKER1] == MARKER1_PAYLOAD && - fk.wait_expected[FK_W_MARKER2] == MARKER2_PAYLOAD && - fk.wait_expected[FK_W_SEM] == SEM_DONE); - check("sim_success_wait_timeouts_come_from_the_job", - fk.wait_ms[FK_W_MARKER1] == TMO_MARKER && fk.wait_ms[FK_W_MARKER2] == TMO_MARKER2 && - fk.wait_ms[FK_W_SEM] == TMO_RELEASE); - i = fake_nth(FK_EV_WAIT, 1); - ok = i >= 0 && fk.ev[i].a == (uint64_t)FK_W_MARKER1; - i = fake_nth(FK_EV_WAIT, 2); - ok = ok && i >= 0 && fk.ev[i].a == (uint64_t)FK_W_MARKER2; - i = fake_nth(FK_EV_WAIT, 3); - ok = ok && i >= 0 && fk.ev[i].a == (uint64_t)FK_W_SEM; - check("sim_success_wait_order_marker_marker2_semaphore", ok); - - /* What the backend observed, for the vector wrapper. */ - memset(&info, 0, sizeof info); - omega_blackwell_engine_run_info(&info); - check("sim_success_run_info_words", - info.marker == MARKER1_PAYLOAD && info.marker2 == MARKER2_PAYLOAD && info.semaphore == SEM_DONE); - check("sim_success_run_info_launch_time_set", info.launch_ns != 0u); - check("sim_success_run_info_done_time_after_launch", - info.marker_done_ns != 0u && info.marker_done_ns >= info.launch_ns); -} - -static void case_no_c3(void) -{ - OmegaBlackwellEngineRunInfo info; - begin_case(); - job.flags = OMEGA_GPU_ENGINE_FLAG_NO_C3; - check("sim_noc3_returns_ok", run() == OMEGA_GPU_ENGINE_OK); - check("sim_noc3_output_values", output_correct(outbuf)); - check("sim_noc3_no_flush_in_pushbuffer", fake_count(FK_EV_PB_FLUSH) == 0); - check("sim_noc3_one_release_only", fake_count(FK_EV_PB_RELEASE) == 1 && fk.marker2_va == 0u); - check("sim_noc3_marker2_never_waited", - fk.wait_n[FK_W_MARKER2] == 0 && tcount(T_WAIT2) == 0 && fk.wait_calls == 2); - check("sim_noc3_marker1_and_semaphore_waited", - fk.wait_n[FK_W_MARKER1] == 1 && fk.wait_n[FK_W_SEM] == 1); - memset(&info, 0, sizeof info); - omega_blackwell_engine_run_info(&info); - check("sim_noc3_run_info_marker2_not_reported", info.marker2 == 0u && info.marker == MARKER1_PAYLOAD); - check("sim_noc3_balanced", balanced(8)); -} - -static void case_back_to_back(void) -{ - int rc1; - int rc2; - int ok; - begin_case(); - rc1 = run(); - ok = output_correct(outbuf); - memset(outbuf, 0, sizeof outbuf); - rc2 = run(); - check("sim_twice_first_ok", rc1 == OMEGA_GPU_ENGINE_OK && ok); - check("sim_twice_second_ok_busy_flag_released", rc2 == OMEGA_GPU_ENGINE_OK && output_correct(outbuf)); - check("sim_twice_driver_opened_and_closed_twice", fk.open_calls == 2 && fk.close_calls == 2); -} - -static void case_open_fail(void) -{ - OmegaBlackwellEngineRunInfo info; - int rc; - begin_case(); - (void)run(); /* leave a dirty run snapshot behind */ - begin_case(); - fk.open_fail = 1; - rc = run(); - check("sim_open_fail_name_step_state", - rc == OMEGA_GPU_ENGINE_DEVICE_OPEN && - res_is(OMEGA_GPU_ENGINE_DEVICE_OPEN, OMEGA_GPU_ENGINE_STEP_OPEN_DEVICE, - OMEGA_GPU_ENGINE_STATE_INITIAL)); - check("sim_open_fail_errno_and_driver_code", res.err_no == EIO && res.drv_rc == -1); - check("sim_open_fail_driver_text_reported", strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_open_fail_nothing_else_touched", - fk.channel_calls == 0 && fk.alloc_calls == 0 && fk.close_calls == 0 && fk.free_calls == 0); - check("sim_open_fail_not_retained_not_blocked", - res.retained == 0 && omega_gpu_engine_is_blocked() == 0); - memset(&info, 0, sizeof info); - omega_blackwell_engine_run_info(&info); - check("sim_open_fail_run_info_reset_at_open", - info.marker == 0u && info.semaphore == 0u && info.launch_ns == 0u && info.marker_done_ns == 0u); - begin_case(); - check("sim_open_fail_then_next_run_ok", run() == OMEGA_GPU_ENGINE_OK); -} - -static void case_channel_fail(void) -{ - int rc; - begin_case(); - fk.channel_fail = 1; - rc = run(); - check("sim_channel_fail_name_step_state", - rc == OMEGA_GPU_ENGINE_CHANNEL_CREATE && - res_is(OMEGA_GPU_ENGINE_CHANNEL_CREATE, OMEGA_GPU_ENGINE_STEP_CREATE_CHANNEL, - OMEGA_GPU_ENGINE_STATE_INITIAL)); - check("sim_channel_fail_errno_text_code", - res.err_no == EIO && res.drv_rc == -1 && strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_channel_fail_closed_nothing_allocated", fk.alloc_calls == 0 && balanced(0)); - begin_case(); - check("sim_channel_fail_then_next_run_ok", run() == OMEGA_GPU_ENGINE_OK); -} - -static void case_alloc_faults(void) -{ - int nth; - char id[64]; - for (nth = 1; nth <= 8; nth++) { - int rc; - begin_case(); - fk.alloc_fail_nth = nth; - fk.alloc_mode = FK_ALLOC_FAIL; - rc = run(); - (void)snprintf(id, sizeof id, "sim_alloc%d_name_step_state", nth); - check(id, rc == OMEGA_GPU_ENGINE_ALLOC && - res_is(OMEGA_GPU_ENGINE_ALLOC, OMEGA_GPU_ENGINE_STEP_ALLOC, - OMEGA_GPU_ENGINE_STATE_INITIAL)); - (void)snprintf(id, sizeof id, "sim_alloc%d_errno_code_text", nth); - check(id, res.err_no == EIO && res.drv_rc == -1 && strcmp(res.drv_text, FK_TEXT) == 0); - (void)snprintf(id, sizeof id, "sim_alloc%d_stops_at_the_failure", nth); - check(id, fk.alloc_calls == nth); - /* nothing is leaked: every part that was allocated is freed (nth - 1 of them) */ - (void)snprintf(id, sizeof id, "sim_alloc%d_balanced", nth); - check(id, balanced(nth - 1)); - } -} - -static void case_alloc_own_checks(void) -{ - static const struct { int mode; int nth; int frees; const char *tag; } t[] = { - { FK_ALLOC_SHORT, 1, 1, "short_pb" }, - { FK_ALLOC_NO_CPU, 3, 3, "nocpu_marker" }, - { FK_ALLOC_MISALIGNED, 4, 4, "misaligned_qmd" }, - { FK_ALLOC_SHORT, 6, 6, "short_input_a" }, - { FK_ALLOC_NO_CPU, 6, 6, "nocpu_input_a" }, - { FK_ALLOC_MISALIGNED, 6, 6, "misaligned_input_a" }, - { FK_ALLOC_NO_CPU, 8, 8, "nocpu_output" } - }; - size_t k; - char id[64]; - for (k = 0; k < sizeof t / sizeof t[0]; k++) { - int rc; - begin_case(); - fk.alloc_fail_nth = t[k].nth; - fk.alloc_mode = t[k].mode; - rc = run(); - idf(id, sizeof id, t[k].tag, "refused_as_alloc"); - check(id, rc == OMEGA_GPU_ENGINE_ALLOC && - res_is(OMEGA_GPU_ENGINE_ALLOC, OMEGA_GPU_ENGINE_STEP_ALLOC, - OMEGA_GPU_ENGINE_STATE_INITIAL)); - idf(id, sizeof id, t[k].tag, "own_check_text"); - check(id, has(res.drv_text, "own checks")); - idf(id, sizeof id, t[k].tag, "balanced"); - check(id, balanced(t[k].frees)); - } -} - -static void case_submit_fail(void) -{ - int rc; - begin_case(); - fk.submit_fail = 1; - rc = run(); - check("sim_submit_fail_name_step_state", - rc == OMEGA_GPU_ENGINE_SUBMIT && - res_is(OMEGA_GPU_ENGINE_SUBMIT, OMEGA_GPU_ENGINE_STEP_SUBMIT, OMEGA_GPU_ENGINE_STATE_PREPARED)); - check("sim_submit_fail_errno_code_text", - res.err_no == EIO && res.drv_rc == -1 && strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_submit_fail_is_not_uncertain", - res.retained == 0 && omega_gpu_engine_is_blocked() == 0 && fk.kernel_ran == 0); - check("sim_submit_fail_cleaned_up", balanced(8)); -} - -/* One uncertain completion: the engine keeps everything and blocks the process. - * Asserts that, asserts the next job is refused without touching the driver, asserts - * a second open of the backend is refused, drains, and proves the backend works again. */ -static void uncertain_case(const char *tag, int mk, int mk2, int sem, uint32_t flags, - int failure, int step, int wait, uint64_t limit, uint64_t waited, - uint32_t want_marker, uint32_t want_marker2, uint32_t want_sem, - uint32_t want_sync, const char *want_text, int want_drv_rc) -{ - char id[96]; - int rc; - int bad; - int open_before; - OmegaBlackwellEngineRunInfo info; - - begin_case(); - fk.marker_mode = mk; - fk.marker2_mode = mk2; - fk.sem_mode = sem; - job.flags = flags; - rc = run(); - - idf(id, sizeof id, tag, "name_step_wait"); - check(id, rc == failure && res.failure == failure && res.failed_step == step && res.wait == wait); - idf(id, sizeof id, tag, "last_state_submitted"); - check(id, res.last_state == OMEGA_GPU_ENGINE_STATE_SUBMITTED); - idf(id, sizeof id, tag, "limit_and_waited_ms"); - check(id, res.wait_timeout_ms == limit && res.waited_ms == waited); - idf(id, sizeof id, tag, "observed_words"); - check(id, res.marker == want_marker && res.marker2 == want_marker2 && - res.semaphore[0] == want_sem); - idf(id, sizeof id, tag, "sync_valid_mask"); - check(id, res.sync_valid == want_sync); - if (want_text != NULL) { - idf(id, sizeof id, tag, "driver_text"); - check(id, has(res.drv_text, want_text)); - } - idf(id, sizeof id, tag, "retained_and_blocked"); - check(id, res.retained == 1 && omega_gpu_engine_is_blocked() == 1); - idf(id, sizeof id, tag, "nothing_freed_nothing_closed"); - check(id, fk.free_calls == 0 && fk.close_calls == 0 && fk.live == 8 && fk.device_open == 1 && - tcount(T_FREE) == 0 && tcount(T_CLOSE) == 0); - - idf(id, sizeof id, tag, "driver_code"); - check(id, res.drv_rc == want_drv_rc); - memset(&info, 0, sizeof info); - omega_blackwell_engine_run_info(&info); - idf(id, sizeof id, tag, "run_info_marker"); - check(id, info.marker == want_marker && info.launch_ns != 0u); - idf(id, sizeof id, tag, "run_info_done_time_only_if_marker_succeeded"); - check(id, (step == OMEGA_GPU_ENGINE_STEP_WAIT_MARKER) == (info.marker_done_ns == 0u)); - idf(id, sizeof id, tag, "run_info_marker2_when_it_was_the_failed_wait"); - check(id, step != OMEGA_GPU_ENGINE_STEP_WAIT_MARKER2 || info.marker2 == want_marker2); - idf(id, sizeof id, tag, "run_info_semaphore_when_it_was_the_failed_wait"); - check(id, step != OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE || info.semaphore == want_sem); - idf(id, sizeof id, tag, "no_marker2_wait_with_noc3"); - check(id, (flags & OMEGA_GPU_ENGINE_FLAG_NO_C3) == 0u || (fk.wait_n[FK_W_MARKER2] == 0 && tcount(T_WAIT2) == 0)); - open_before = fk.open_calls; - rc = run(); - idf(id, sizeof id, tag, "next_job_blocked"); - check(id, rc == OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED && - res.failed_step == OMEGA_GPU_ENGINE_STEP_BLOCKED && fk.open_calls == open_before); - idf(id, sizeof id, tag, "second_open_refused_by_backend"); - check(id, g_real->open_device(g_real->ctx) != 0 && fk.open_calls == open_before); - idf(id, sizeof id, tag, "still_retained_after_refusals"); - check(id, fk.live == 8 && fk.device_open == 1 && fk.close_calls == 0); - - bad = drain(); - idf(id, sizeof id, tag, "drained_through_the_table"); - check(id, bad == 0 && fk.close_calls == 1 && fk.live_at_close == 0 && fk.double_free == 0 && - fk.free_calls == 8); - omega_gpu_engine_test_reset_block(); - make_job(&job); - /* The simulated driver still has the hang or overshoot of this case armed: restore a healthy chip. */ - fk.marker_mode = FK_SYNC_NORMAL; - fk.marker2_mode = FK_SYNC_NORMAL; - fk.sem_mode = FK_SYNC_NORMAL; - idf(id, sizeof id, tag, "backend_works_again_after_drain"); - check(id, run() == OMEGA_GPU_ENGINE_OK && output_correct(outbuf)); -} - -static void case_uncertain(void) -{ - const uint32_t all = OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_MARKER2 | OMEGA_GPU_SYNC_SEMAPHORE; - - uncertain_case("unc_marker_hang", FK_SYNC_NEVER, FK_SYNC_NORMAL, FK_SYNC_NORMAL, 0u, - OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_MARKER, - OMEGA_GPU_ENGINE_WAIT_MARKER, TMO_MARKER, TMO_MARKER, - 0u, MARKER2_PAYLOAD, SEM_DONE, all, NULL, -1); - uncertain_case("unc_marker2_hang", FK_SYNC_NORMAL, FK_SYNC_NEVER, FK_SYNC_NORMAL, 0u, - OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_MARKER2, - OMEGA_GPU_ENGINE_WAIT_MARKER2, TMO_MARKER2, TMO_MARKER2, - MARKER1_PAYLOAD, 0u, SEM_DONE, all, NULL, -1); - uncertain_case("unc_semaphore_hang", FK_SYNC_NORMAL, FK_SYNC_NORMAL, FK_SYNC_NEVER, 0u, - OMEGA_GPU_ENGINE_RELEASE_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE, - OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE, TMO_RELEASE, TMO_RELEASE, - MARKER1_PAYLOAD, MARKER2_PAYLOAD, SEM_INIT, all, NULL, -1); - uncertain_case("unc_marker_overshoot", FK_SYNC_OVERSHOOT, FK_SYNC_NORMAL, FK_SYNC_NORMAL, 0u, - OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_MARKER, - OMEGA_GPU_ENGINE_WAIT_MARKER, TMO_MARKER, 0u, - MARKER1_PAYLOAD + 1u, MARKER2_PAYLOAD, SEM_DONE, all, "observed 0x44444445", 0); - uncertain_case("unc_marker2_overshoot", FK_SYNC_NORMAL, FK_SYNC_OVERSHOOT, FK_SYNC_NORMAL, 0u, - OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_MARKER2, - OMEGA_GPU_ENGINE_WAIT_MARKER2, TMO_MARKER2, 0u, - MARKER1_PAYLOAD, MARKER2_PAYLOAD + 1u, SEM_DONE, all, "observed 0x46464647", 0); - uncertain_case("unc_semaphore_overshoot", FK_SYNC_NORMAL, FK_SYNC_NORMAL, FK_SYNC_OVERSHOOT, 0u, - OMEGA_GPU_ENGINE_RELEASE_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE, - OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE, TMO_RELEASE, 0u, - MARKER1_PAYLOAD, MARKER2_PAYLOAD, SEM_DONE + 1u, all, "observed 0x00000007", 0); - /* NO_C3: the second marker does not exist, so it is never reported either. */ - uncertain_case("unc_noc3_semaphore_hang", FK_SYNC_NORMAL, FK_SYNC_NORMAL, FK_SYNC_NEVER, - OMEGA_GPU_ENGINE_FLAG_NO_C3, - OMEGA_GPU_ENGINE_RELEASE_WAIT, OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE, - OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE, TMO_RELEASE, TMO_RELEASE, - MARKER1_PAYLOAD, 0u, SEM_INIT, OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_SEMAPHORE, NULL, -1); -} - -static void case_cleanup_faults(void) -{ - int rc; - - /* a free of an ordinary buffer fails: every other free still runs */ - begin_case(); - fk.free_fail_nth = 1; - rc = run(); - check("sim_cleanup_free_role_name_step_state", - rc == OMEGA_GPU_ENGINE_CLEANUP && - res_is(OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STEP_FREE, - OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED)); - check("sim_cleanup_free_role_flag_errno_text", - res.cleanup_failed == 1 && res.err_no == EIO && strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_cleanup_free_role_every_free_attempted_and_closed", - fk.free_calls == 8 && fk.close_calls == 1 && fk.live_at_close == 1); - check("sim_cleanup_free_role_words_still_mapped_at_capture", - res.sync_valid == (OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_MARKER2 | OMEGA_GPU_SYNC_SEMAPHORE) && - res.marker == MARKER1_PAYLOAD && res.marker2 == MARKER2_PAYLOAD && res.semaphore[0] == SEM_DONE); - check("sim_cleanup_free_role_not_uncertain", res.retained == 0 && omega_gpu_engine_is_blocked() == 0); - - /* a free of one SCRATCH part fails (the marker page, sixth real free): the - * other scratch parts are still freed and the sync words are unmapped first */ - begin_case(); - fk.free_fail_nth = 6; - rc = run(); - check("sim_cleanup_free_scratch_name_step_state", - rc == OMEGA_GPU_ENGINE_CLEANUP && - res_is(OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STEP_FREE, - OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED)); - check("sim_cleanup_free_scratch_code_and_text", - res.cleanup_failed == 1 && res.drv_rc == -1 && strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_cleanup_free_scratch_all_four_parts_attempted", - fk.free_calls == 8 && fk.close_calls == 1 && fk.live_at_close == 1); - check("sim_cleanup_free_scratch_sync_words_unmapped_before_free", res.sync_valid == 0u); - - /* close fails */ - begin_case(); - fk.close_fail = 1; - rc = run(); - check("sim_cleanup_close_name_step_state", - rc == OMEGA_GPU_ENGINE_CLEANUP && - res_is(OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STEP_CLOSE, - OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED)); - check("sim_cleanup_close_flag_errno_text", - res.cleanup_failed == 1 && res.err_no == EIO && strcmp(res.drv_text, FK_TEXT) == 0); - check("sim_cleanup_close_all_freed_first", fk.free_calls == 8 && fk.live_at_close == 0); - begin_case(); - check("sim_cleanup_close_failure_still_releases_busy_flag", run() == OMEGA_GPU_ENGINE_OK); -} - -static void case_unchanged(void) -{ - int rc; - - begin_case(); - fk.kernel_mode = FK_KERNEL_NO_WRITE; - rc = run(); - check("sim_unchanged_nowrite_name_step_state", - rc == OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED && - res_is(OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STEP_SCAN, - OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE)); - check("sim_unchanged_nowrite_counts_every_word", - res.n_outputs == 1u && res.output_unchanged_words[0] == N); - check("sim_unchanged_nowrite_completion_was_seen", - fk.kernel_ran == 1 && fk.wait_n[FK_W_MARKER1] == 1 && fk.wait_n[FK_W_SEM] == 1); - check("sim_unchanged_nowrite_cleaned_up_not_retained", - balanced(8) && res.retained == 0 && omega_gpu_engine_is_blocked() == 0); - - begin_case(); - fk.kernel_mode = FK_KERNEL_HALF; - rc = run(); - check("sim_unchanged_half_counts_the_unwritten_half", - rc == OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED && res.output_unchanged_words[0] == N / 2u); - - /* the device runs different program bytes than the job supplied: it writes nothing */ - begin_case(); - fk.prog_expect = prog_other; - rc = run(); - check("sim_unchanged_wrong_program_bytes_detected", - rc == OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED && fk.kernel_ran == 1 && fk.prog_matched == 0 && - res.output_unchanged_words[0] == N); -} - -static void case_table_guards(void) -{ - const OmegaGpuBackend *be = omega_blackwell_engine_backend(); - void *ctx = be->ctx; - OmegaGpuJob j; - int role; - int bad = 0; - - begin_case(); - memset(&j, 0, sizeof j); - j.layout = OMEGA_GPU_LAYOUT_VECTOR_1D; - j.element_count = N; - - check("sim_guard_open_ok", be->open_device(ctx) == 0); - check("sim_guard_channel_ok", be->create_channel(ctx) == 0); - check("sim_guard_alloc_zero_bytes_refused", be->alloc(ctx, (int)OMEGA_GPU_BUF_OUTPUT, 0u) != 0); - check("sim_guard_alloc_unknown_role_refused", be->alloc(ctx, 99, 4096u) != 0); - check("sim_guard_alloc_rounds_up_to_whole_pages", - be->alloc(ctx, (int)OMEGA_GPU_BUF_OUTPUT, 5000u) == 0 && fake_count(FK_EV_ALLOC) == 1 && - fk.ev[fake_nth(FK_EV_ALLOC, 1)].a == 0x2000u); - check("sim_guard_free_after_rounding_ok", be->free_buf(ctx, (int)OMEGA_GPU_BUF_OUTPUT) == 0); - check("sim_guard_wait_before_build_refused_without_driver_call", - be->wait_marker(ctx, 5u) != 0 && be->wait_marker2(ctx, 5u) != 0 && - be->wait_release_semaphore(ctx, 5u) != 0 && fk.wait_calls == 0); - check("sim_guard_submit_before_build_refused", be->submit(ctx) != 0); - check("sim_guard_build_without_buffers_refused", be->build(ctx, &j) != 0); - - check("sim_guard_alloc_scratch_ok", be->alloc(ctx, (int)OMEGA_GPU_BUF_SCRATCH, 0u) == 0); - check("sim_guard_alloc_program_ok", be->alloc(ctx, (int)OMEGA_GPU_BUF_PROGRAM, sizeof prog) == 0); - check("sim_guard_alloc_a_ok", be->alloc(ctx, (int)OMEGA_GPU_BUF_INPUT_A, N * 4u) == 0); - check("sim_guard_alloc_b_ok", be->alloc(ctx, (int)OMEGA_GPU_BUF_INPUT_B, N * 4u) == 0); - check("sim_guard_alloc_output_ok", be->alloc(ctx, (int)OMEGA_GPU_BUF_OUTPUT, N * 4u) == 0); - check("sim_guard_copy_in_negative_role_refused", be->copy_in(ctx, -1, prog, sizeof prog) != 0); - check("sim_guard_free_negative_role_refused", be->free_buf(ctx, -1) != 0); - check("sim_guard_build_null_job_refused", be->build(ctx, NULL) != 0); - j.layout = 7; - check("sim_guard_build_unknown_layout_refused", be->build(ctx, &j) != 0); - j.layout = (int)OMEGA_GPU_LAYOUT_VECTOR_1D; - j.element_count = 0u; - check("sim_guard_build_zero_count_refused", be->build(ctx, &j) != 0); - j.element_count = 2000u; - check("sim_guard_build_count_beyond_the_buffers_refused", be->build(ctx, &j) != 0); - j.element_count = N; - - check("sim_guard_copy_in_too_long_refused", - be->copy_in(ctx, (int)OMEGA_GPU_BUF_PROGRAM, bigbytes, 0x1000u + 8u) != 0); - check("sim_guard_copy_in_unknown_role_refused", be->copy_in(ctx, 99, prog, sizeof prog) != 0); - check("sim_guard_copy_in_null_source_refused", - be->copy_in(ctx, (int)OMEGA_GPU_BUF_PROGRAM, NULL, sizeof prog) != 0); - check("sim_guard_fill_poison_too_long_refused", - be->fill_poison(ctx, bigwords, 0x1000u / 4u + 1u) != 0); - check("sim_guard_fill_poison_null_refused", be->fill_poison(ctx, NULL, N) != 0); - check("sim_guard_copy_out_too_long_refused", - be->copy_out(ctx, bigbytes, 0x1000u + 8u) != 0); - check("sim_guard_copy_out_null_refused", be->copy_out(ctx, NULL, N * 4u) != 0); - check("sim_guard_free_unknown_role_refused", be->free_buf(ctx, 99) != 0); - - check("sim_guard_valid_copy_in_ok", be->copy_in(ctx, (int)OMEGA_GPU_BUF_PROGRAM, prog, sizeof prog) == 0); - check("sim_guard_valid_fill_poison_ok", be->fill_poison(ctx, poison, N) == 0); - memset(bigbytes, 0, sizeof bigbytes); - check("sim_guard_valid_copy_out_returns_the_poison", - be->copy_out(ctx, bigbytes, N * 4u) == 0 && memcmp(bigbytes, poison, N * 4u) == 0); - - for (role = (int)OMEGA_GPU_BUF_ROLE_COUNT - 1; role >= 0; role--) - if (be->free_buf(ctx, role) != 0) bad = 1; - if (be->close(ctx) != 0) bad = 1; - check("sim_guard_drain_ok", bad == 0); - check("sim_guard_nothing_leaked", fk.live_at_close == 0 && fk.double_free == 0 && fk.close_calls == 1); -} - -/* A close without the SCRATCH free (a backend that is closed with its words still - * mapped) must stop reading the sync words: the memory is gone. */ -static void case_close_unmaps_sync_words(void) -{ - const OmegaGpuBackend *be = omega_blackwell_engine_backend(); - void *ctx = be->ctx; - OmegaGpuBackendDiag d; - OmegaGpuJob j; - int ok; - - begin_case(); - make_job(&j); - ok = be->open_device(ctx) == 0 && be->create_channel(ctx) == 0 && - be->alloc(ctx, (int)OMEGA_GPU_BUF_SCRATCH, 0u) == 0 && - be->alloc(ctx, (int)OMEGA_GPU_BUF_PROGRAM, sizeof prog) == 0 && - be->alloc(ctx, (int)OMEGA_GPU_BUF_INPUT_A, N * 4u) == 0 && - be->alloc(ctx, (int)OMEGA_GPU_BUF_INPUT_B, N * 4u) == 0 && - be->alloc(ctx, (int)OMEGA_GPU_BUF_OUTPUT, N * 4u) == 0 && - be->build(ctx, &j) == 0; - check("sim_close_setup_through_the_table", ok); - memset(&d, 0, sizeof d); - be->diagnostics(ctx, &d); - check("sim_close_words_mapped_after_build", - d.sync_valid == (OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_MARKER2 | OMEGA_GPU_SYNC_SEMAPHORE)); - check("sim_close_returns_zero", be->close(ctx) == 0); - memset(&d, 0, sizeof d); - be->diagnostics(ctx, &d); - check("sim_close_unmaps_every_sync_word", d.sync_valid == 0u); - check("sim_close_released_everything", fk.close_calls == 1 && fk.live == 0); -} - -/* Like begin_case, for the vector wrapper: the device must see the encoder's real - * program bytes, and no backend is installed, so the wrapper has to install its own. */ -static void begin_vec(void) -{ - begin_case(); - omega_gpu_engine_set_backend(NULL); - fk.prog_expect = vec_code; - fk.prog_len = vec_len; -} - -static void case_vector(void) -{ - OmegaVectorSpec spec; - OmegaBlackwellRealization real; - OmegaBlackwellVectorExecution info; - uint32_t c[N]; - uint32_t i; - int rc; - int ok; - uint64_t want_elapsed; - - memset(&real, 0, sizeof real); - real.sm_architecture = OMEGA_BW_SM_ARCH_121; - check("sim_vec_spec_init", omega_vector_spec_init(&spec, "engine_sim", N) == 0); - - /* success */ - begin_vec(); - memset(c, 0, sizeof c); - memset(&info, 0xff, sizeof info); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_success_returns_zero", rc == 0); - check("sim_vec_success_output_values", output_correct(c)); - check("sim_vec_success_parity_verified", info.parity_verified == true); - check("sim_vec_success_completion_marker_and_semaphore", - info.completion_marker == MARKER1_PAYLOAD && info.intermediate_semaphore == SEM_DONE); - check("sim_vec_success_shape_fields", - info.element_count == N && info.sm_architecture == (uint32_t)OMEGA_BW_SM_ARCH_121 && - info.target_chip[0] != '\0'); - want_elapsed = info.completion_timestamp_ns > info.launch_timestamp_ns ? - info.completion_timestamp_ns - info.launch_timestamp_ns : 0u; - check("sim_vec_success_timestamps", - info.launch_timestamp_ns != 0u && info.completion_timestamp_ns != 0u && - info.elapsed_ns == want_elapsed); - check("sim_vec_success_timeouts_are_5000_each", - fk.wait_ms[FK_W_MARKER1] == 5000u && fk.wait_ms[FK_W_MARKER2] == 5000u && - fk.wait_ms[FK_W_SEM] == 5000u); - check("sim_vec_success_all_protections_on", - fake_count(FK_EV_PB_FLUSH) == 1 && fake_count(FK_EV_PB_RELEASE) == 2 && - fk.wait_n[FK_W_MARKER2] == 1); - check("sim_vec_success_encoded_program_reached_the_device", - fk.kernel_ran == 1 && fk.prog_matched == 1); - ok = fk.snap_n == N; - for (i = 0; ok && i < N; i++) - if (fk.out_before[i] != (uint32_t)~expect_out[i]) ok = 0; - check("sim_vec_success_poison_is_the_complement_of_the_sum", ok); - check("sim_vec_success_poison_never_collides_even_for_0xdeadbeef", fk.poison_collisions == 0); - check("sim_vec_success_balanced", balanced(8)); - - /* wrong math on the device: the engine passes it (it only checks poison), the wrapper must not */ - begin_vec(); - fk.kernel_mode = FK_KERNEL_WRONG; - memset(c, 0, sizeof c); - memset(&info, 0, sizeof info); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_wrong_math_returns_nonzero", rc != 0); - check("sim_vec_wrong_math_parity_not_verified", info.parity_verified == false); - - /* a cleanup fault after a good run is still a failure */ - begin_vec(); - fk.free_fail_nth = 1; - memset(c, 0, sizeof c); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_cleanup_fault_returns_nonzero", rc != 0); - - /* the device wrote nothing */ - begin_vec(); - fk.kernel_mode = FK_KERNEL_NO_WRITE; - memset(c, 0, sizeof c); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_unwritten_output_returns_nonzero", rc != 0); - - /* a hung first marker: failure, process blocked, backend retained */ - begin_vec(); - fk.marker_mode = FK_SYNC_NEVER; - memset(c, 0, sizeof c); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_hang_returns_nonzero", rc != 0); - check("sim_vec_hang_blocks_the_process_and_retains", - omega_gpu_engine_is_blocked() == 1 && fk.free_calls == 0 && fk.close_calls == 0); - check("sim_vec_hang_drains", drain() == 0 && fk.live_at_close == 0); - omega_gpu_engine_test_reset_block(); - - /* refusals before any driver call */ - begin_vec(); - check("sim_vec_null_spec_refused", omega_blackwell_execute_vector(NULL, &real, ina, inb, c, &info) != 0); - check("sim_vec_null_output_refused", omega_blackwell_execute_vector(&spec, &real, ina, inb, NULL, &info) != 0); - check("sim_vec_null_input_refused", omega_blackwell_execute_vector(&spec, &real, NULL, inb, c, &info) != 0); - spec.element_count = 0u; - check("sim_vec_zero_count_refused", omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info) != 0); - check("sim_vec_refusals_never_touch_the_driver", fk.open_calls == 0 && fk.alloc_calls == 0); - spec.element_count = N; - - /* the wrapper can be used again afterwards (busy flag, block, tracing table) */ - begin_vec(); - memset(c, 0, sizeof c); - rc = omega_blackwell_execute_vector(&spec, &real, ina, inb, c, &info); - check("sim_vec_works_again", rc == 0 && output_correct(c)); -} - -/* Packets in the last submitted pushbuffer that invalidate all shader caches - * (subchannel 1, method 0x021c, one data word = OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL). - * Walks packet headers like the fake's parser, so a data word never counts as a header. */ -static int pb_shader_invalidates(void) -{ - size_t i = 0; - int hits = 0; - while (i < fk.pb_len) { - uint32_t h = fk.pb[i++]; - uint32_t cnt = (h >> 16) & 0x1fffu; - uint32_t subc = (h >> 13) & 7u; - uint32_t mthd = (h & 0xfffu) << 2; - if (i + cnt > fk.pb_len) return -1; - if (subc == 1u && mthd == OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES && cnt == 1u && - fk.pb[i] == OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL) - hits++; - i += cnt; - } - return hits; -} - -/* omega-mv#575: the device and channel stay open between jobs (default). Measured - * on the Spark: open 7.5 ms + channel 19.2 ms + close 11.3 ms of a 38.8 ms job. */ -static void case_persistent_device(void) -{ - int rc1, rc2, rc3, ok1, ok2; - unsetenv("OMEGA_GPU_ENGINE_NO_PERSIST"); - begin_case(); - rc1 = run(); - ok1 = output_correct(outbuf); - memset(outbuf, 0, sizeof outbuf); - rc2 = run(); - ok2 = output_correct(outbuf); - check("sim_persist_two_jobs_ok", rc1 == OMEGA_GPU_ENGINE_OK && ok1 && rc2 == OMEGA_GPU_ENGINE_OK && ok2); - check("sim_persist_one_open_one_channel_no_close", - fk.open_calls == 1 && fk.channel_calls == 1 && fk.close_calls == 0 && fk.device_open == 1); - check("sim_persist_device_reported_open", omega_blackwell_engine_device_is_open() == 1); - /* the PROGRAM buffer of the second job can reuse the first job's address on the kept - * device, so every launch must invalidate the shader caches (the chip ran stale code - * without it, 2026-10-19) */ - check("sim_persist_pushbuffer_invalidates_shader_caches", pb_shader_invalidates() == 1); - check("sim_persist_per_job_buffers_still_freed", fk.free_calls == 2 * 8 && fk.double_free == 0); - check("sim_persist_shutdown_closes", omega_blackwell_engine_shutdown() == 0 && fk.close_calls == 1 && - fk.device_open == 0 && omega_blackwell_engine_device_is_open() == 0); - check("sim_persist_shutdown_idempotent", omega_blackwell_engine_shutdown() == 0 && fk.close_calls == 1); - memset(outbuf, 0, sizeof outbuf); - rc3 = run(); - check("sim_persist_reopens_after_shutdown", rc3 == OMEGA_GPU_ENGINE_OK && output_correct(outbuf) && - fk.open_calls == 2 && fk.channel_calls == 2); - /* a job that fails at submit leaves the next job able to run */ - fk.submit_fail = 1; - rc3 = run(); - check("sim_persist_fault_run_fails", rc3 != OMEGA_GPU_ENGINE_OK); - fk.submit_fail = 0; - memset(outbuf, 0, sizeof outbuf); - rc3 = run(); - check("sim_persist_recovers_after_fault", rc3 == OMEGA_GPU_ENGINE_OK && output_correct(outbuf)); - /* a job whose submit faults the driver closes the device; the next job opens a fresh one */ - fk.submit_fail = 1; - fk.submit_faults_device = 1; - rc3 = run(); - check("sim_persist_driver_fault_closes_device", rc3 != OMEGA_GPU_ENGINE_OK && fk.close_calls == 2 && - fk.device_open == 0 && omega_blackwell_engine_device_is_open() == 0); - fk.submit_fail = 0; - fk.submit_faults_device = 0; - memset(outbuf, 0, sizeof outbuf); - rc3 = run(); - check("sim_persist_fresh_open_after_driver_fault", rc3 == OMEGA_GPU_ENGINE_OK && output_correct(outbuf) && - fk.open_calls == 3 && fk.channel_calls == 3); - (void)omega_blackwell_engine_shutdown(); - setenv("OMEGA_GPU_ENGINE_NO_PERSIST", "1", 1); -} - -int main(void) -{ - /* The cases above case_persistent_device() check the one-open-per-job lifecycle - * (opened and closed twice, balanced frees, close unmaps the sync words). They run - * with persistence off; case_persistent_device() then checks the default. */ - setenv("OMEGA_GPU_ENGINE_NO_PERSIST", "1", 1); - init_data(); - wrap_init(); - omega_gpu_engine_test_set_clock(fake_now_ms); - check("sim_setup_encoder_ok", - omega_blackwell_encode_vecadd(vec_code, sizeof vec_code, &vec_len) == 0 && vec_len > 0u); - - case_success(); - case_no_c3(); - case_back_to_back(); - case_open_fail(); - case_channel_fail(); - case_alloc_faults(); - case_alloc_own_checks(); - case_submit_fail(); - case_uncertain(); - case_cleanup_faults(); - case_unchanged(); - case_table_guards(); - case_close_unmaps_sync_words(); - case_vector(); - case_persistent_device(); - - omega_gpu_engine_set_backend(NULL); - omega_gpu_engine_test_reset_block(); - omega_gpu_engine_test_set_clock(NULL); - fake_reset(); - printf("SUMMARY passed=%d failed=%d\n", n_pass, n_fail); - return n_fail ? 1 : 0; -} diff --git a/tests/test_omega_codegen_freestanding.c b/tests/test_omega_codegen_freestanding.c deleted file mode 100644 index a84887375..000000000 --- a/tests/test_omega_codegen_freestanding.c +++ /dev/null @@ -1,239 +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. - */ - -/* test_omega_codegen_freestanding.c -- native v1 P07 cut A.2 (aienos#286, aien-architecture#190). - * - * Built twice by mk/omega-gpu-engine.mk (make test-codegen-freestanding): - * - hosted: linked against the hosted codegen/matmul objects; every fixture goes through the existing - * allocating generators (malloc'd code buffer, omega_blackwell_kernel_free); - * - freestanding (-DOMEGA_GPU_NO_POSIX): linked against the -ffreestanding objects of - * `make gpu-engine-freestanding`; every fixture goes through the *_prog generator and - * omega_blackwell_kernel_encode_into with a caller-supplied buffer, no allocator anywhere. - * `--dump` prints every fixture's instruction stream as hex; the make target requires the two dumps to be - * byte-identical (cmp). Without --dump the freestanding build also checks the bounded buffer contract - * (every short buffer refused before a byte is written, nothing written past the reported size), the - * golden-word fixture verifiers against the freestanding object, and the integer bf16 rounding path - * against the hosted __bf16 cast on all 2^32 inputs. - * Host only: opens no device. */ -#include "omega_blackwell_codegen.h" -#include "omega_blackwell_matmul.h" -#include -#include -#include - -typedef enum { FX_I32, FX_TENSOR, FX_LOOP, FX_FRAG, FX_BLOCK } FxKind; -typedef struct { - const char *name; - FxKind kind; - uint32_t m, k, n; - OmegaMatMulPrecision prec; - uint32_t grid_x, unroll, rt, ct; /* unroll 0 = the API's rule (omega_matmul_frag_unroll / _block_unroll) */ - int mutant; -} Fixture; - -/* The shapes the existing tests and the matmul API generate: the integer and K=16 tensor kernels of the - * gates, the looped kernel, the decode fragment kernel at Qwen3 shapes and the blocked prefill kernel. */ -static const Fixture FX[] = { - {"i32_16x16x16", FX_I32, 16, 16, 16, OMEGA_MATMUL_PRECISION_INT32, 0, 0, 0, 0, 0}, - {"i32_32x16x64", FX_I32, 32, 16, 64, OMEGA_MATMUL_PRECISION_INT32, 0, 0, 0, 0, 0}, - {"i32_16x32x8", FX_I32, 16, 32, 8, OMEGA_MATMUL_PRECISION_INT32, 0, 0, 0, 0, 0}, - {"tensor_f16_16x16x8", FX_TENSOR, 16, 16, 8, OMEGA_MATMUL_PRECISION_FP16, 0, 0, 0, 0, 0}, - {"tensor_bf16_32x16x16", FX_TENSOR, 32, 16, 16, OMEGA_MATMUL_PRECISION_BF16, 0, 0, 0, 0, 0}, - {"loop_bf16_16x64x32_g2", FX_LOOP, 16, 64, 32, OMEGA_MATMUL_PRECISION_BF16, 2, 0, 0, 0, 0}, - {"loop_f16_32x128x64_g4", FX_LOOP, 32, 128, 64, OMEGA_MATMUL_PRECISION_FP16, 4, 0, 0, 0, 0}, - {"frag_k128_n64_g1", FX_FRAG, 16, 128, 64, OMEGA_MATMUL_PRECISION_BF16, 1, 0, 0, 0, 0}, - {"frag_k1024_n3072_g64", FX_FRAG, 16, 1024, 3072, OMEGA_MATMUL_PRECISION_BF16, 64, 0, 0, 0, 0}, - {"frag_k4096_n4096_g48", FX_FRAG, 16, 4096, 4096, OMEGA_MATMUL_PRECISION_BF16, 48, 0, 0, 0, 0}, - {"frag_k4096_n4096_g48_mutant", FX_FRAG, 16, 4096, 4096, OMEGA_MATMUL_PRECISION_BF16, 48, 0, 0, 0, 1}, - {"block_k256_n128_r4c2", FX_BLOCK, 16, 256, 128, OMEGA_MATMUL_PRECISION_BF16, 1, 0, 4, 2, 0}, - {"block_k1024_n3072_r2c2", FX_BLOCK, 16, 1024, 3072, OMEGA_MATMUL_PRECISION_BF16, 8, 0, 2, 2, 0}, - {"block_k4096_n4096_r4c4", FX_BLOCK, 16, 4096, 4096, OMEGA_MATMUL_PRECISION_BF16, 16, 0, 4, 4, 0}, -}; -#define NFX (sizeof FX / sizeof FX[0]) - -static uint32_t fx_unroll(const Fixture *f) { - if (f->unroll) return f->unroll; - if (f->kind == FX_BLOCK) return omega_matmul_frag_block_unroll(f->k, f->rt, f->ct); - uint32_t u = omega_matmul_frag_unroll(f->k); - if (f->mutant) while (u > 1 && f->k / 16u / u < 2) u /= 2; /* the API's mutant rule */ - return u; -} - -static int fails; -#define CHECK(c, ...) do { if (!(c)) { fails++; printf("FAIL "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -#ifdef OMEGA_GPU_NO_POSIX -static BlackwellIRProgram g_prog; /* one program at a time; static keeps the stack small */ -static uint8_t g_code[OMEGA_BW_CODE_CAP_MAX + 64]; - -static int fx_prog(const Fixture *f, BlackwellIRProgram *prog) { - OmegaMatMulSpec spec; - if (omega_matmul_spec_init(&spec, f->m, f->k, f->n, f->prec) != 0) return -1; - switch (f->kind) { - case FX_I32: return omega_blackwell_codegen_matmul_i32_prog(&spec, prog); - case FX_TENSOR: return omega_blackwell_codegen_matmul_tensor_prog(&spec, prog); - case FX_LOOP: return omega_blackwell_codegen_matmul_tensor_loop_prog(&spec, f->grid_x, f->mutant, prog); - case FX_FRAG: return omega_blackwell_codegen_matmul_frag_prog(&spec, f->grid_x, fx_unroll(f), f->mutant, prog); - case FX_BLOCK: - return omega_blackwell_codegen_matmul_frag_block_prog(&spec, f->grid_x, fx_unroll(f), f->rt, f->ct, f->mutant, prog); - } - return -1; -} - -/* The cap each hosted generator always had: the i32 buffer is exactly the program, frag_block the IR maximum, - * the others 4096 bytes. The freestanding build passes the same cap so a program the hosted build refuses is - * refused here too. */ -static size_t fx_cap(const Fixture *f, const BlackwellIRProgram *prog) { - if (f->kind == FX_I32) return omega_bw_program_code_bytes(prog); - if (f->kind == FX_BLOCK) return OMEGA_BW_CODE_CAP_MAX; - return OMEGA_BW_CODE_CAP_SMALL; -} - -static int fx_kernel(const Fixture *f, OmegaBlackwellKernel *k) { - if (fx_prog(f, &g_prog) != 0) { memset(k, 0, sizeof *k); return -1; } - return omega_blackwell_kernel_encode_into(&g_prog, g_code, fx_cap(f, &g_prog), k); -} -static void fx_release(OmegaBlackwellKernel *k) { memset(k, 0, sizeof *k); } /* caller-owned buffer: nothing to free */ -#else -static int fx_kernel(const Fixture *f, OmegaBlackwellKernel *k) { - OmegaMatMulSpec spec; - memset(k, 0, sizeof *k); - if (omega_matmul_spec_init(&spec, f->m, f->k, f->n, f->prec) != 0) return -1; - switch (f->kind) { - case FX_I32: return omega_blackwell_codegen_matmul_i32(&spec, k); - case FX_TENSOR: return omega_blackwell_codegen_matmul_tensor(&spec, k); - case FX_LOOP: return omega_blackwell_codegen_matmul_tensor_loop(&spec, f->grid_x, f->mutant, k); - case FX_FRAG: return omega_blackwell_codegen_matmul_frag(&spec, f->grid_x, fx_unroll(f), f->mutant, k); - case FX_BLOCK: return omega_blackwell_codegen_matmul_frag_block(&spec, f->grid_x, fx_unroll(f), f->rt, f->ct, f->mutant, k); - } - return -1; -} -static void fx_release(OmegaBlackwellKernel *k) { omega_blackwell_kernel_free(k); } -#endif - -static int dump(void) { - for (size_t i = 0; i < NFX; i++) { - OmegaBlackwellKernel k; - int rc = fx_kernel(&FX[i], &k); - printf("fixture %s rc %d bytes %zu insns %zu gpr %u ugpr %u\n", FX[i].name, rc, k.code_size, k.insn_count, - k.gpr_count, k.uniform_gpr_count); - if (rc != 0 || !k.code || k.code_size == 0) { fails++; printf("FAIL fixture %s did not generate\n", FX[i].name); continue; } - printf("digest "); - for (int j = 0; j < 32; j++) printf("%02x", k.code_digest[j]); - printf("\n"); - for (size_t j = 0; j < k.code_size; j++) printf("%02x%s", k.code[j], (j % 32u == 31u) ? "\n" : ""); - if (k.code_size % 32u) printf("\n"); - fx_release(&k); - } - return fails ? 1 : 0; -} - -#ifdef OMEGA_GPU_NO_POSIX -static int all_bytes(const uint8_t *p, size_t n, uint8_t v) { - for (size_t i = 0; i < n; i++) if (p[i] != v) return 0; - return 1; -} - -/* The bounded-buffer contract, on every fixture's program. */ -static void buffer_contract(void) { - for (size_t i = 0; i < NFX; i++) { - const Fixture *f = &FX[i]; - OmegaBlackwellKernel k; - if (fx_prog(f, &g_prog) != 0) { CHECK(0, "%s: program", f->name); continue; } - const size_t need = omega_bw_program_code_bytes(&g_prog); - CHECK(need >= 32u * 16u && need % 128u == 0, "%s: code bytes %zu (padded to 8 instructions, at least 32)", f->name, need); - CHECK(need <= OMEGA_BW_CODE_CAP_MAX, "%s: code bytes %zu above the IR maximum", f->name, need); - - /* one byte short: refused, not a byte written, kernel zeroed */ - memset(g_code, 0xa5, sizeof g_code); - memset(&k, 0x5a, sizeof k); - int rc = omega_blackwell_kernel_encode_into(&g_prog, g_code, need - 1u, &k); - CHECK(rc == OMEGA_BW_CODE_BUFFER_TOO_SMALL, "%s: need-1 rc %d", f->name, rc); - CHECK(all_bytes(g_code, sizeof g_code, 0xa5), "%s: refused encode wrote into the buffer", f->name); - CHECK(k.code == NULL && k.code_size == 0 && k.insn_count == 0, "%s: refused encode left a kernel", f->name); - - /* zero capacity and NULL buffer refused */ - CHECK(omega_blackwell_kernel_encode_into(&g_prog, g_code, 0, &k) == OMEGA_BW_CODE_BUFFER_TOO_SMALL, "%s: cap 0", f->name); - CHECK(omega_blackwell_kernel_encode_into(&g_prog, NULL, need, &k) == -1 && k.code == NULL, "%s: NULL buffer", f->name); - CHECK(omega_blackwell_kernel_encode_into(NULL, g_code, need, &k) == -1, "%s: NULL program", f->name); - CHECK(omega_blackwell_kernel_encode_into(&g_prog, g_code, need, NULL) == -1, "%s: NULL kernel", f->name); - - /* exactly enough, and a larger buffer: same bytes, nothing written past the reported size */ - memset(g_code, 0xa5, sizeof g_code); - rc = omega_blackwell_kernel_encode_into(&g_prog, g_code, need + 64u, &k); - CHECK(rc == 0 && k.code == g_code && k.code_size == need && k.insn_count == need / 16u, - "%s: roomy encode rc %d size %zu", f->name, rc, k.code_size); - CHECK(all_bytes(g_code + need, 64u, 0xa5), "%s: encode wrote past code_size", f->name); - static uint8_t first[OMEGA_BW_CODE_CAP_MAX]; - memcpy(first, g_code, need); - uint8_t d1[32]; - memcpy(d1, k.code_digest, 32); - memset(g_code, 0, sizeof g_code); - rc = omega_blackwell_kernel_encode_into(&g_prog, g_code, need, &k); - CHECK(rc == 0 && memcmp(first, g_code, need) == 0 && memcmp(d1, k.code_digest, 32) == 0, - "%s: exact-size encode differs (rc %d)", f->name, rc); - } -} -#endif - -/* Golden words (nvcc/nvdisasm oracles, independent of either encoder). The hosted build runs them with --golden - * through the .om encoder (om/encoder/bw_enc_sm121.om); the freestanding build through the C encoder. */ -static void golden_fixtures(void) { - CHECK(omega_blackwell_verify_codegen_fixtures() == 0, "golden words (rc %d)", omega_blackwell_verify_codegen_fixtures()); - CHECK(omega_blackwell_verify_codegen_fixtures_fb1cut4() == 0, "fb1cut4 golden words"); - CHECK(omega_blackwell_verify_codegen_fixtures_intops() == 0, "intops golden words"); - CHECK(omega_blackwell_verify_codegen_fixtures_fragmm() == 0, "fragmm golden words"); - CHECK(omega_blackwell_verify_codegen_fixtures_reconv() == 0, "reconv golden words"); - CHECK(omega_blackwell_test_regalloc_bounds() == 0, "regalloc bounds"); -} - -#ifdef OMEGA_GPU_NO_POSIX -/* The freestanding omega_fp32_to_bf16 (integer rounding) against the hosted __bf16 cast, every input. */ -static void bf16_sweep(void) { - uint64_t bad = 0; - uint32_t first_bad = 0; - for (uint64_t x = 0; x <= 0xffffffffull; x++) { - uint32_t u = (uint32_t)x; - float f; - memcpy(&f, &u, 4); - __bf16 b = (__bf16)f; - uint16_t want; - memcpy(&want, &b, 2); - if (omega_fp32_to_bf16(f) != want) { if (!bad) first_bad = u; bad++; } - } - CHECK(bad == 0, "bf16: %llu of 2^32 inputs differ from the __bf16 cast (first 0x%08x)", (unsigned long long)bad, first_bad); - if (!bad) printf("bf16 sweep: all 2^32 inputs equal the hosted __bf16 cast\n"); -} -#endif - -int main(int argc, char **argv) { - if (argc > 1 && strcmp(argv[1], "--dump") == 0) return dump(); -#ifdef OMEGA_GPU_NO_POSIX - buffer_contract(); - golden_fixtures(); - if (!(argc > 1 && strcmp(argv[1], "--no-sweep") == 0)) bf16_sweep(); - printf("%s: freestanding codegen contract (%zu fixtures, %d failing checks)\n", fails ? "FAIL" : "PASS", (size_t)NFX, fails); - return fails ? 1 : 0; -#else - if (argc > 1 && strcmp(argv[1], "--golden") == 0) { - golden_fixtures(); - printf("%s: hosted golden-word fixtures through the .om encoder (%d failing checks)\n", fails ? "FAIL" : "PASS", fails); - return fails ? 1 : 0; - } - fprintf(stderr, "hosted build: only --dump or --golden\n"); - return 2; -#endif -} diff --git a/tests/test_omega_gpu_code_alloc.c b/tests/test_omega_gpu_code_alloc.c deleted file mode 100644 index 2bebf3ca8..000000000 --- a/tests/test_omega_gpu_code_alloc.c +++ /dev/null @@ -1,47 +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. - */ - -/* GPU code buffer sizing (src/omega_gpu_code_alloc.h): code + 2 KB instruction prefetch tail, page rounded. - * Host only. The NO_TAIL mutant (the page-rounded size used before omega#323) must fail. */ -#include "omega_gpu_code_alloc.h" -#include -#include - -static int fails; -#define CHECK(c, ...) do { if (!(c)) { fails++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) - -int main(void) { - /* the two attention kernels of omega#323: 2560 B (head_dim 64) and 2688 B (head_dim 128) */ - CHECK(omega_gpu_code_alloc_bytes(2560) == 8192, "2560 B of code -> 8192 (got %zu)", omega_gpu_code_alloc_bytes(2560)); - CHECK(omega_gpu_code_alloc_bytes(2688) == 8192, "2688 B of code -> 8192 (got %zu)", omega_gpu_code_alloc_bytes(2688)); - CHECK(omega_gpu_code_alloc_bytes(2048) == 4096, "2048 B of code fits one page with the tail (got %zu)", omega_gpu_code_alloc_bytes(2048)); - CHECK(omega_gpu_code_alloc_bytes(2049) == 8192, "2049 B of code needs a second page (got %zu)", omega_gpu_code_alloc_bytes(2049)); - CHECK(omega_gpu_code_alloc_bytes(0) == 4096, "empty code -> one page (got %zu)", omega_gpu_code_alloc_bytes(0)); - CHECK(omega_gpu_code_alloc_bytes(0x4000) == 0x5000, "16 KB capacity -> 20 KB (got %zu)", omega_gpu_code_alloc_bytes(0x4000)); - CHECK(omega_gpu_code_alloc_bytes(SIZE_MAX) == 0, "overflow refused"); - CHECK(omega_gpu_code_alloc_bytes(SIZE_MAX - 2048) == 0, "overflow near the limit refused"); - /* every size: at least 2 KB mapped after the code, page multiple, no more than one extra page */ - for (size_t n = 1; n <= 64 * 1024; n += 16) { - size_t b = omega_gpu_code_alloc_bytes(n); - if (b < n + OMEGA_GPU_CODE_PREFETCH_TAIL || b % OMEGA_GPU_CODE_PAGE != 0 || b > n + OMEGA_GPU_CODE_PREFETCH_TAIL + OMEGA_GPU_CODE_PAGE) { - CHECK(0, "%zu B of code -> %zu B (needs >= code + 2048, page multiple)", n, b); - break; - } - } - if (fails) { printf("OMEGA_GPU_CODE_ALLOC FAIL (%d)\n", fails); return 1; } - printf("OMEGA_GPU_CODE_ALLOC PASS\n"); - return 0; -} diff --git a/tests/test_omega_gpu_decode_attn_maxpos.c b/tests/test_omega_gpu_decode_attn_maxpos.c deleted file mode 100644 index dedcd9c96..000000000 --- a/tests/test_omega_gpu_decode_attn_maxpos.c +++ /dev/null @@ -1,375 +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. - */ - -/* test_omega_gpu_decode_attn_maxpos: the decode attention position bound (omega #535: OMEGA_GPU_DATTN_MAX_POS 131072, - * the 128k context) on a FAKE OmegaGpuPlatform. Host program; opens no device, touches no GPU. The Makefile links a - * sanitized copy of src/omega_gpu_decode_attn_api.c ahead of libomega_gpu.a, so every cache write, RoPE fill and - * launch staging of the file under test is ASan/UBSan checked against the fake's exact-size buffers. - * - * The fake device completes every submission: completion-marker releases write their payload, and the launch "writes" - * the attention output buffer (the one DATA buffer of 32 * 128 f32), so the API's poison check passes. It computes - * nothing: this is a bound and sizing test, not a kernel result (the kernel's numbers are the chip battery's, - * tools/run_gpu_decode_attn_chip.sh). - * - * Contract under test, at the cap C = OMEGA_GPU_DATTN_MAX_POS = 131072: - * - a cache of C positions allocates; C + 256 (the next legal multiple) is refused before any device work; - * - every buffer the cache owns is sized from max_pos: K|V planes 2 * (4 * C * 256 + slack), RoPE C * 512, - * split partials 4 * (C / 256) * 1040 * 4; - * - KV rows at 65535, 65536, 131071 round-trip; 131072 and 131073 are refused, as is a count crossing the cap; - * - RoPE rows 0, 65535, 65536, 99999, 131071 equal cos/sin of pos * theta^(-2i/128) from libm; - * - a decode step at pos 131071 launches with 512 splits (the whole partial buffer); 131072, 131073 are refused - * before any submission; - * - a cache of the old cap 65536 refuses pos 65536: the bound is the cache's own max_pos. - * Each case runs in its own child process. - */ -#include "omega_gpu_decode_attn_api.h" -#include "omega_blackwell_codegen_attn.h" -#include "omega_gpu_session.h" -#include "omega_gpu_platform.h" -#include "omega_blackwell_submit.h" - -#include -#include -#include -#include -#include -#include - -static int case_ok; -#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) - -#define CAP OMEGA_GPU_DATTN_MAX_POS -#define THETA 1000000.0 - -/* ---- the fake platform ---- */ -#define NB OMEGA_GPU_HANDLE_SLOTS -#define VA_BASE 0x100000000ull -#define VA_STRIDE (1ull << 31) /* one slot per 2 GiB of VA: the largest buffer here (256 MiB + slack) never overlaps the next */ -#define OUT_BYTES ((uint64_t)OMEGA_GPU_DATTN_Q_HEADS * 128u * 4u) -static struct { - OmegaGpuHandleTable t; - void *mem[NB]; - OmegaGpuBufferDesc desc[NB]; - OmegaGpuDeviceHandle dev; - OmegaGpuQueueHandle q; - OmegaGpuBufferHandle ring; - uint64_t ns; - unsigned locks_held, double_locks, bad_unlocks, submits, allocs; - uint64_t data_bytes[64]; /* sizes of the DATA buffers, in allocation order */ - unsigned n_data; -} fk; - -static uint64_t f_now_ns(void *c) { (void)c; fk.ns += 1000u; return fk.ns; } -static uint64_t f_now_ms(void *c) { return f_now_ns(c) / 1000000u; } -static int f_wait(void *c, uint64_t ms) { (void)c; fk.ns += ms * 1000000u; return 0; } -static int f_lock(void *c, uint32_t id) { - (void)c; - if (id != OMEGA_GPU_SESSION_LOCK_ID) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if (fk.locks_held) { fk.double_locks++; return OMEGA_GPU_PLAT_REFUSED_BUSY; } - fk.locks_held = 1; - return 0; -} -static int f_unlock(void *c, uint32_t id) { - (void)c; - if (id != OMEGA_GPU_SESSION_LOCK_ID || !fk.locks_held) { fk.bad_unlocks++; return OMEGA_GPU_PLAT_REFUSED_ARGS; } - fk.locks_held = 0; - return 0; -} -static const char *f_diag(void *c) { (void)c; return ""; } -static int f_dev_open(void *c, uint32_t ord, OmegaGpuDeviceHandle *out) { - (void)c; - if (ord != 0 || fk.dev.generation) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - int rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &out->index, &out->generation); - if (rc == 0) fk.dev = *out; - return rc; -} -static int f_dev_close(void *c, OmegaGpuDeviceHandle d) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (rc) return rc; - (void)omega_gpu_handles_close(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - memset(&fk.dev, 0, sizeof fk.dev); - return 0; -} -static OmegaGpuPlatformCaps g_caps = { - .abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR, .abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR, - .services = OMEGA_GPU_SVC_REQUIRED_SESSION, .max_devices = 1, .max_buffers = 1000, .max_queues = 1, .max_inflight = 1, - .max_buffer_bytes = 1ull << 30, .max_total_bytes = 1ull << 32, -}; -static int f_alloc(void *c, OmegaGpuDeviceHandle d, const OmegaGpuBufferDesc *desc, OmegaGpuBufferHandle *o, - OmegaCpuView *cpu, OmegaGpuVa *g, OmegaGpuBusAddr *b) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (!rc) rc = omega_gpu_platform_check_buffer(desc, &g_caps); - if (!rc) rc = omega_gpu_handles_open(&fk.t, desc->kind, desc->bytes, 1000, 1ull << 32, &o->index, &o->generation); - if (rc) return rc; - void *m = calloc(1, desc->bytes); /* exact size: ASan sees any write past the end */ - if (!m) { (void)omega_gpu_handles_close(&fk.t, o->index, o->generation, desc->kind); return OMEGA_GPU_PLAT_REFUSED_LIMIT; } - fk.mem[o->index] = m; fk.desc[o->index] = *desc; - if (desc->kind == OMEGA_GPU_HANDLE_BUF_DATA && fk.n_data < 64) fk.data_bytes[fk.n_data++] = desc->bytes; - fk.allocs++; - cpu->ptr = m; cpu->len = desc->bytes; g->va = VA_BASE + (uint64_t)o->index * VA_STRIDE; b->iova = 0; - return 0; -} -static int f_free(void *c, OmegaGpuBufferHandle h) { - (void)c; - if (h.index >= NB) return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; - int rc = omega_gpu_handles_close(&fk.t, h.index, h.generation, fk.t.kind[h.index]); - if (rc) return rc; - free(fk.mem[h.index]); fk.mem[h.index] = NULL; - return 0; -} -static int buf_live(OmegaGpuBufferHandle h) { return h.index < NB && fk.t.live[h.index] && fk.t.generation[h.index] == h.generation; } -/* the host view of [va, va + len): NULL unless the whole range lies inside one live buffer */ -static void *va_to_cpu(uint64_t va, uint64_t len) { - for (uint32_t i = 0; i < NB; i++) { - if (!fk.mem[i] || !fk.t.live[i]) continue; - const uint64_t base = VA_BASE + (uint64_t)i * VA_STRIDE; - if (va >= base && va - base <= fk.desc[i].bytes && len <= fk.desc[i].bytes - (va - base)) return (uint8_t *)fk.mem[i] + (va - base); - } - return NULL; -} -static int sync_check(OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { - if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - if (len == 0 || off > fk.desc[h.index].bytes || len > fk.desc[h.index].bytes - off) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - return 0; -} -static int f_c2g(void *c, OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { (void)c; return sync_check(h, off, len); } -/* A read-back of the split-counter / intermediate-semaphore words finds them DONE, as the device leaves them. */ -static int f_g2c(void *c, OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { - (void)c; - int rc = sync_check(h, off, len); - if (rc) return rc; - uint32_t *w = (uint32_t *)((uint8_t *)fk.mem[h.index] + off); - if (len == 4u) { /* the launch's QMD release semaphore: the kernel finished */ - w[0] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE; - } else if (len % 16u == 0) { /* a row of four-word semaphores */ - uint64_t i = 0, n = len / 16u; - while (i < n && w[4 * i] == OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT) i++; - if (i == n) for (i = 0; i < n; i++) w[4 * i] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE; - } - return 0; -} -static int f_poll(void *c, OmegaGpuBufferHandle h, uint64_t off, uint32_t want, uint64_t ms, uint32_t *seen) { - (void)c; - if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - if (!(fk.desc[h.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED)) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - const volatile uint32_t *w = (const volatile uint32_t *)((uint8_t *)fk.mem[h.index] + off); - *seen = *w; - if ((int32_t)(*w - want) >= 0) return 0; - fk.ns += ms * 1000000u; - return OMEGA_GPU_POLL_TIMED_OUT; -} -static int f_qopen(void *c, OmegaGpuDeviceHandle d, OmegaGpuBufferHandle ring, OmegaGpuQueueHandle *o) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (!rc && (!buf_live(ring) || fk.t.kind[ring.index] != OMEGA_GPU_HANDLE_BUF_QUEUE)) rc = OMEGA_GPU_PLAT_REFUSED_BAD_KIND; - if (!rc) rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_QUEUE, 0, 1, 0, &o->index, &o->generation); - if (!rc) { fk.q = *o; fk.ring = ring; } - return rc; -} -static int f_qclose(void *c, OmegaGpuQueueHandle q) { - (void)c; - int rc = omega_gpu_handles_close(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); - if (!rc) memset(&fk.q, 0, sizeof fk.q); - return rc; -} -static uint32_t mthd(uint32_t subc, uint32_t m, uint32_t count) { return (2u << 28) | (count << 16) | (subc << 13) | (m >> 2); } -/* The fake device runs the stream: completion-marker releases (0x005c) write their payload, and the attention output - * (the DATA buffer of 32 * 128 f32) is overwritten with zeros, the "kernel ran" the API's poison check looks for. */ -static int f_submit(void *c, OmegaGpuQueueHandle q, const uint32_t *w, uint32_t n) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); - if (rc) return rc; - if ((uint64_t)n * 4u > fk.desc[fk.ring.index].bytes) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - fk.submits++; - for (uint32_t i = 0; i < NB; i++) - if (fk.mem[i] && fk.t.live[i] && fk.desc[i].kind == OMEGA_GPU_HANDLE_BUF_DATA && fk.desc[i].bytes == OUT_BYTES) memset(fk.mem[i], 0, OUT_BYTES); - for (uint32_t i = 0; i + 5 < n; i++) - if (w[i] == mthd(0, 0x005c, 5)) { - uint32_t *m = va_to_cpu((uint64_t)w[i + 1] | ((uint64_t)w[i + 2] << 32), 4); - if (m) *m = w[i + 3]; - i += 5; - } - return 0; -} -static int f_retire(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; return 0; } -static void *f_halloc(void *c, size_t b) { (void)c; return malloc(b); } -static void f_hfree(void *c, void *p) { (void)c; free(p); } - -static OmegaGpuPlatform g_plat = { - .ctx = &fk, .time_now_ms = f_now_ms, .wait_ms = f_wait, .lock = f_lock, .unlock = f_unlock, - .dma_alloc = f_alloc, .dma_free = f_free, .sync_cpu_to_gpu = f_c2g, .sync_gpu_to_cpu = f_g2c, .poll_word = f_poll, - .device_open = f_dev_open, .device_close = f_dev_close, .diag_text = f_diag, - .queue_open = f_qopen, .queue_close = f_qclose, .queue_submit = f_submit, .queue_retire = f_retire, - .time_now_ns = f_now_ns, .host_alloc = f_halloc, .host_free = f_hfree, -}; -static int install(void) { - memset(&fk, 0, sizeof fk); omega_gpu_handles_init(&fk.t); - return omega_gpu_session_set_platform(&g_plat, &g_caps); -} -#define EXPECT_LOCK_FREE() do { EXPECT(fk.locks_held == 0); EXPECT(fk.double_locks == 0); EXPECT(fk.bad_unlocks == 0); } while (0) - -/* the session rounds every buffer up to a 4 KiB page */ -static int has_data(uint64_t bytes) { - bytes = (bytes + 0xfffu) & ~0xfffull; - for (unsigned i = 0; i < fk.n_data; i++) if (fk.data_bytes[i] == bytes) return 1; - return 0; -} -static OmegaGpuDecodeAttnCache *alloc_at(uint32_t max_pos) { - OmegaGpuDecodeAttnCache *c = NULL; - if (install() != OMEGA_GPU_PLAT_OK) { EXPECT(!"fake platform installs"); return NULL; } /* never fall back to the real driver */ - int rc = omega_gpu_decode_attn_cache_alloc(1, max_pos, THETA, &c); - if (rc != OMEGA_GPU_DATTN_OK) printf(" cache_alloc(1, %u): %s (%s)\n", max_pos, omega_gpu_decode_attn_rc_name(rc), omega_gpu_decode_attn_last_error()); - EXPECT(rc == OMEGA_GPU_DATTN_OK && c != NULL); - return rc == OMEGA_GPU_DATTN_OK ? c : NULL; -} - -/* ---- cases ---- */ - -static void c_alloc_cap(void) { - EXPECT(CAP == 131072u); - OmegaGpuDecodeAttnCache *c = alloc_at(CAP); - if (!c) return; - const uint64_t plane = 4ull * CAP * OMEGA_DATTN_ROW_BYTES + OMEGA_DATTN_PLANE_SLACK; - EXPECT(has_data(2 * plane)); /* K | V planes */ - EXPECT(has_data((uint64_t)CAP * OMEGA_DATTN_ROPE_ROW_BYTES)); /* RoPE table */ - EXPECT(has_data(4ull * (CAP / OMEGA_DATTN_CHUNK) * OMEGA_DATTN_PARTIAL_WORDS * 4u)); /* split partials, 512 splits */ - OmegaGpuDecodeAttnCacheView v; - EXPECT(omega_gpu_decode_attn_cache_view(c, 0, &v) == OMEGA_GPU_DATTN_OK && v.max_pos == CAP && v.v_va - v.k_va == plane); - omega_gpu_decode_attn_cache_free(c); - EXPECT_LOCK_FREE(); - const unsigned allocs = fk.allocs; - c = (OmegaGpuDecodeAttnCache *)1; - EXPECT(omega_gpu_decode_attn_cache_alloc(1, CAP + OMEGA_DATTN_CHUNK, THETA, &c) == OMEGA_GPU_DATTN_BAD_ARGS && c == NULL); - EXPECT(fk.allocs == allocs); /* refused before any device work */ - EXPECT_LOCK_FREE(); -} - -static void c_kv_rows(void) { - OmegaGpuDecodeAttnCache *c = alloc_at(CAP); - if (!c) return; - static const uint32_t ok_pos[] = { 0, 65535, 65536, 131071 }; - uint16_t k[128], v[128], kr[128], vr[128]; - for (unsigned n = 0; n < sizeof ok_pos / sizeof ok_pos[0]; n++) - for (uint32_t h = 0; h < OMEGA_GPU_DATTN_KV_HEADS; h++) { - for (unsigned i = 0; i < 128; i++) { k[i] = (uint16_t)(ok_pos[n] * 7u + h * 131u + i); v[i] = (uint16_t)~k[i]; } - EXPECT(omega_gpu_decode_attn_cache_write(c, 0, h, ok_pos[n], 1, k, v) == OMEGA_GPU_DATTN_OK); - EXPECT(omega_gpu_decode_attn_cache_read(c, 0, h, ok_pos[n], kr, vr) == OMEGA_GPU_DATTN_OK); - EXPECT(memcmp(k, kr, sizeof k) == 0 && memcmp(v, vr, sizeof v) == 0); - } - /* the rows really are where the view says: (kv_head * max_pos + pos) * 256 from the plane base */ - OmegaGpuDecodeAttnCacheView view; - EXPECT(omega_gpu_decode_attn_cache_view(c, 0, &view) == OMEGA_GPU_DATTN_OK); - const uint16_t *last = va_to_cpu(view.v_va + ((uint64_t)3 * CAP + 131071u) * 256u, 256); - EXPECT(last && omega_gpu_decode_attn_cache_read(c, 0, 3, 131071, kr, vr) == OMEGA_GPU_DATTN_OK && memcmp(last, vr, 256) == 0); - EXPECT(omega_gpu_decode_attn_cache_write(c, 0, 0, 131072, 1, k, v) == OMEGA_GPU_DATTN_BAD_ARGS); - EXPECT(omega_gpu_decode_attn_cache_write(c, 0, 0, 131073, 1, k, v) == OMEGA_GPU_DATTN_BAD_ARGS); - EXPECT(omega_gpu_decode_attn_cache_read(c, 0, 0, 131072, kr, vr) == OMEGA_GPU_DATTN_BAD_ARGS); - EXPECT(omega_gpu_decode_attn_cache_read(c, 0, 0, 131073, kr, vr) == OMEGA_GPU_DATTN_BAD_ARGS); - uint16_t k2[256] = {0}, v2[256] = {0}; - EXPECT(omega_gpu_decode_attn_cache_write(c, 0, 3, 131071, 2, k2, v2) == OMEGA_GPU_DATTN_BAD_ARGS); /* crosses the cap */ - omega_gpu_decode_attn_cache_free(c); - EXPECT_LOCK_FREE(); -} - -static void c_rope_rows(void) { - OmegaGpuDecodeAttnCache *c = alloc_at(CAP); - if (!c) return; - OmegaGpuDecodeAttnCacheView view; - EXPECT(omega_gpu_decode_attn_cache_view(c, 0, &view) == OMEGA_GPU_DATTN_OK); - EXPECT(va_to_cpu(view.rope_va, (uint64_t)CAP * OMEGA_DATTN_ROPE_ROW_BYTES) != NULL); /* C rows ... */ - EXPECT(va_to_cpu(view.rope_va, (uint64_t)CAP * OMEGA_DATTN_ROPE_ROW_BYTES + 1u) == NULL); /* ... and no more */ - static const uint32_t rows[] = { 0, 65535, 65536, 99999, 131071 }; - double worst = 0; - for (unsigned n = 0; n < sizeof rows / sizeof rows[0]; n++) { - const float *r = va_to_cpu(view.rope_va + (uint64_t)rows[n] * OMEGA_DATTN_ROPE_ROW_BYTES, OMEGA_DATTN_ROPE_ROW_BYTES); - if (!r) { EXPECT(!"rope row inside the table"); continue; } - for (unsigned i = 0; i < 64; i++) { - const double a = (double)rows[n] * pow(THETA, -(double)(2 * i) / 128.0); - const double dc = fabs((double)r[i] - cos(a)), ds = fabs((double)r[64 + i] - sin(a)); - if (dc > worst) worst = dc; - if (ds > worst) worst = ds; - } - } - printf(" rope rows 0..131071: worst |table - libm| %.3g\n", worst); - EXPECT(worst <= 1e-6); /* f32 rounding of an exact value is <= 6e-8; 1e-6 leaves room for the pow ulps at pos 131071 */ - omega_gpu_decode_attn_cache_free(c); - EXPECT_LOCK_FREE(); -} - -static float g_qkv[OMEGA_GPU_DATTN_QKV_WORDS], g_out[OMEGA_GPU_DATTN_Q_HEADS * 128]; -static void c_decode_at_cap(void) { - OmegaGpuDecodeAttnCache *c = alloc_at(CAP); - if (!c) return; - OmegaGpuDecodeAttnInfo info; - int rc = omega_gpu_decode_attn(c, 0, 131071, g_qkv, 1e-6f, 1.0f, g_out, &info); - if (rc) printf(" decode_attn(pos 131071): %s (%s)\n", omega_gpu_decode_attn_rc_name(rc), omega_gpu_decode_attn_last_error()); - EXPECT(rc == OMEGA_GPU_DATTN_OK); - EXPECT(info.splits == CAP / OMEGA_DATTN_CHUNK && info.grid_x == 512u && info.grid_y == 4u); - EXPECT(info.kv_bytes == 2ull * 4u * CAP * 256u); - EXPECT_LOCK_FREE(); - const unsigned submits = fk.submits; - EXPECT(omega_gpu_decode_attn(c, 0, 131072, g_qkv, 1e-6f, 1.0f, g_out, &info) == OMEGA_GPU_DATTN_BAD_ARGS); - EXPECT(omega_gpu_decode_attn(c, 0, 131073, g_qkv, 1e-6f, 1.0f, g_out, &info) == OMEGA_GPU_DATTN_BAD_ARGS); - EXPECT(fk.submits == submits); /* refused before any submission */ - EXPECT_LOCK_FREE(); - omega_gpu_decode_attn_cache_free(c); -} - -static void c_old_cap_cache(void) { - OmegaGpuDecodeAttnCache *c = alloc_at(65536u); - if (!c) return; - uint16_t k[128] = {0}, v[128] = {0}; - EXPECT(omega_gpu_decode_attn_cache_write(c, 0, 3, 65535, 1, k, v) == OMEGA_GPU_DATTN_OK); - EXPECT(omega_gpu_decode_attn_cache_write(c, 0, 3, 65536, 1, k, v) == OMEGA_GPU_DATTN_BAD_ARGS); - OmegaGpuDecodeAttnInfo info; - EXPECT(omega_gpu_decode_attn(c, 0, 65535, g_qkv, 1e-6f, 1.0f, g_out, &info) == OMEGA_GPU_DATTN_OK && info.splits == 256u); - EXPECT(omega_gpu_decode_attn(c, 0, 65536, g_qkv, 1e-6f, 1.0f, g_out, &info) == OMEGA_GPU_DATTN_BAD_ARGS); - omega_gpu_decode_attn_cache_free(c); - EXPECT_LOCK_FREE(); -} - -static const struct { const char *name; void (*fn)(void); } CASES[] = { - { "cache of 131072 positions allocates, buffers sized for it; 131328 refused", c_alloc_cap }, - { "KV rows 65535/65536/131071 round-trip; 131072/131073 refused", c_kv_rows }, - { "RoPE rows up to 131071 match libm; table holds exactly 131072 rows", c_rope_rows }, - { "decode step at pos 131071 launches 512 splits; 131072/131073 refused", c_decode_at_cap }, - { "a 65536-position cache refuses pos 65536", c_old_cap_cache }, -}; - -int main(int argc, char **argv) { - const unsigned n = sizeof CASES / sizeof CASES[0]; - if (argc == 2) { /* one case in this process (debugging): its index */ - const unsigned i = (unsigned)atoi(argv[1]); - if (i >= n) return 2; - case_ok = 1; CASES[i].fn(); - printf("%s %s\n", case_ok ? "ok " : "FAIL", CASES[i].name); - return case_ok ? 0 : 1; - } - unsigned failed = 0; - for (unsigned i = 0; i < n; i++) { - fflush(stdout); - pid_t pid = fork(); - if (pid == 0) { case_ok = 1; CASES[i].fn(); fflush(stdout); _exit(case_ok ? 0 : 1); } - int status = 0; - int ok = pid > 0 && waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0; - printf("%s %s\n", ok ? "ok " : "FAIL", CASES[i].name); - if (!ok) failed++; - } - printf("test_omega_gpu_decode_attn_maxpos: %u of %u cases passed: %s\n", n - failed, n, failed ? "FAIL" : "PASS"); - return failed ? 1 : 0; -} diff --git a/tests/test_omega_gpu_decode_graph_abort.c b/tests/test_omega_gpu_decode_graph_abort.c deleted file mode 100644 index 4fc8f07fd..000000000 --- a/tests/test_omega_gpu_decode_graph_abort.c +++ /dev/null @@ -1,440 +0,0 @@ -/* test_omega_gpu_decode_graph_abort: lock and token-state recovery of the decode graph's split API (omega #518) on a - * FAKE OmegaGpuPlatform. Host program, links libomega_gpu.a with the fake installed first; opens no device, touches - * no GPU. - * - * The fake's session lock REFUSES a second acquisition while held (counted in fk.double_locks) instead of blocking, - * so a lock left held by a failed call shows up as a count, not a hung test. The fake device never runs a kernel: a - * submitted list's markers never land (the cmdlist times out on the fake clock), and the graph's token slot is written - * by the "device" at the gpu->cpu sync only when a case arms fk.dev_token (a token the device produced). - * - * Contract under test (omega_gpu_decode_graph.h): a failed begin_token returns with the session lock released and the - * graph out of the token (no end_token owed); abort_token drops a begun token without submitting anything; end_token - * after a failed record submits nothing and releases the lock; an uncertain completion latches the process and every - * later begin fails without a retry or a submission. After each failure: set_final_norm, read, free and the next - * valid token neither deadlock nor see a stale token state. - * - * Each case runs in its own child process (a latch lasts for the life of the process). - */ -#include "omega_gpu_decode_graph.h" -#include "omega_gpu_session.h" -#include "omega_gpu_platform.h" -#include "omega_blackwell_codegen_dec.h" - -#include -#include -#include -#include -#include - -static int case_ok; -#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) - -/* ---- the fake platform ---- */ -#define NB OMEGA_GPU_HANDLE_SLOTS -#define VA_BASE 0x100000000ull -#define VA_STRIDE 0x1000000ull -static struct { - OmegaGpuHandleTable t; - void *mem[NB]; - OmegaGpuBufferDesc desc[NB]; - OmegaGpuDeviceHandle dev; - OmegaGpuQueueHandle q; - OmegaGpuBufferHandle ring; - uint64_t ns; - unsigned locks_held, double_locks, bad_unlocks; - unsigned submits, dev_opens; - int fail_open, fail_c2g; /* refuse device open / every cpu->gpu visibility sync */ - uint64_t dev_token_va; /* nonzero: the device wrote dev_token there (seen at the gpu->cpu sync) */ - uint32_t dev_token; -} fk; - -static uint64_t f_now_ns(void *c) { (void)c; fk.ns += 1000u; return fk.ns; } -static uint64_t f_now_ms(void *c) { return f_now_ns(c) / 1000000u; } -static int f_wait(void *c, uint64_t ms) { (void)c; fk.ns += ms * 1000000u; return 0; } -static int f_lock(void *c, uint32_t id) { - (void)c; - if (id != OMEGA_GPU_SESSION_LOCK_ID) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if (fk.locks_held) { fk.double_locks++; return OMEGA_GPU_PLAT_REFUSED_BUSY; } /* a real lock would block here forever */ - fk.locks_held = 1; - return 0; -} -static int f_unlock(void *c, uint32_t id) { - (void)c; - if (id != OMEGA_GPU_SESSION_LOCK_ID || !fk.locks_held) { fk.bad_unlocks++; return OMEGA_GPU_PLAT_REFUSED_ARGS; } - fk.locks_held = 0; - return 0; -} -static const char *f_diag(void *c) { (void)c; return fk.fail_open ? "fake device: open refused" : ""; } - -static int f_dev_open(void *c, uint32_t ord, OmegaGpuDeviceHandle *out) { - (void)c; - if (fk.fail_open) return OMEGA_GPU_PLAT_REFUSED_DEVICE; - if (ord != 0 || fk.dev.generation) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - int rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &out->index, &out->generation); - if (rc == 0) { fk.dev = *out; fk.dev_opens++; } - return rc; -} -static int f_dev_close(void *c, OmegaGpuDeviceHandle d) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (rc) return rc; - /* every handle of the device goes stale; the host memory stays mapped (leaked) so a graph that outlives the device - * writes into its own stale buffer, not freed memory: this test checks the lock, not use after close */ - for (uint32_t i = 0; i < NB; i++) - if (fk.t.live[i] && i != d.index) { (void)omega_gpu_handles_close(&fk.t, i, fk.t.generation[i], fk.t.kind[i]); fk.mem[i] = NULL; } - (void)omega_gpu_handles_close(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - memset(&fk.dev, 0, sizeof fk.dev); memset(&fk.q, 0, sizeof fk.q); - return 0; -} - -static OmegaGpuPlatformCaps g_caps = { - .abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR, .abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR, - .services = OMEGA_GPU_SVC_REQUIRED_SESSION, .max_devices = 1, .max_buffers = 1000, .max_queues = 1, .max_inflight = 1, - .max_buffer_bytes = 1ull << 30, .max_total_bytes = 1ull << 32, -}; - -static int f_alloc(void *c, OmegaGpuDeviceHandle d, const OmegaGpuBufferDesc *desc, OmegaGpuBufferHandle *o, - OmegaCpuView *cpu, OmegaGpuVa *g, OmegaGpuBusAddr *b) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (!rc) rc = omega_gpu_platform_check_buffer(desc, &g_caps); - if (!rc) rc = omega_gpu_handles_open(&fk.t, desc->kind, desc->bytes, 1000, 1ull << 32, &o->index, &o->generation); - if (rc) return rc; - void *m = calloc(1, desc->bytes); - if (!m) { (void)omega_gpu_handles_close(&fk.t, o->index, o->generation, desc->kind); return OMEGA_GPU_PLAT_REFUSED_LIMIT; } - fk.mem[o->index] = m; fk.desc[o->index] = *desc; - cpu->ptr = m; cpu->len = desc->bytes; g->va = VA_BASE + (uint64_t)o->index * VA_STRIDE; b->iova = 0; - return 0; -} -static int f_free(void *c, OmegaGpuBufferHandle h) { - (void)c; - if (h.index >= NB) return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; - int rc = omega_gpu_handles_close(&fk.t, h.index, h.generation, fk.t.kind[h.index]); - if (rc) return rc; - free(fk.mem[h.index]); fk.mem[h.index] = NULL; - return 0; -} -static int buf_live(OmegaGpuBufferHandle h) { return h.index < NB && fk.t.live[h.index] && fk.t.generation[h.index] == h.generation; } -static void *va_to_cpu(uint64_t va) { - for (uint32_t i = 0; i < NB; i++) { - if (!fk.mem[i] || !fk.t.live[i]) continue; - const uint64_t base = VA_BASE + (uint64_t)i * VA_STRIDE; - if (va >= base && va < base + fk.desc[i].bytes) return (uint8_t *)fk.mem[i] + (va - base); - } - return NULL; -} -static int sync_check(OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { - if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - if (len == 0 || off > fk.desc[h.index].bytes || len > fk.desc[h.index].bytes - off) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - return 0; -} -static int f_c2g(void *c, OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { - (void)c; - if (fk.fail_c2g) return OMEGA_GPU_PLAT_REFUSED_DEVICE; - return sync_check(h, off, len); -} -static int f_g2c(void *c, OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { - (void)c; - int rc = sync_check(h, off, len); - if (rc == 0 && fk.dev_token_va) { uint32_t *t = va_to_cpu(fk.dev_token_va); if (t) t[0] = fk.dev_token; } - return rc; -} -static int f_poll(void *c, OmegaGpuBufferHandle h, uint64_t off, uint32_t want, uint64_t ms, uint32_t *seen) { - (void)c; - if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - if (!(fk.desc[h.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED)) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - const volatile uint32_t *w = (const volatile uint32_t *)((uint8_t *)fk.mem[h.index] + off); - *seen = *w; - if ((int32_t)(*w - want) >= 0) return 0; - fk.ns += ms * 1000000u; - return OMEGA_GPU_POLL_TIMED_OUT; -} -static int f_qopen(void *c, OmegaGpuDeviceHandle d, OmegaGpuBufferHandle ring, OmegaGpuQueueHandle *o) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (!rc && (!buf_live(ring) || fk.t.kind[ring.index] != OMEGA_GPU_HANDLE_BUF_QUEUE)) rc = OMEGA_GPU_PLAT_REFUSED_BAD_KIND; - if (!rc) rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_QUEUE, 0, 1, 0, &o->index, &o->generation); - if (!rc) { fk.q = *o; fk.ring = ring; } - return rc; -} -static int f_qclose(void *c, OmegaGpuQueueHandle q) { - (void)c; - int rc = omega_gpu_handles_close(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); - if (!rc) memset(&fk.q, 0, sizeof fk.q); - return rc; -} -/* The fake device accepts the words and runs nothing: no marker, semaphore or output ever lands. */ -static int f_submit(void *c, OmegaGpuQueueHandle q, const uint32_t *w, uint32_t n) { - (void)c; (void)w; - int rc = omega_gpu_handles_check(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); - if (rc) return rc; - if ((uint64_t)n * 4u > fk.desc[fk.ring.index].bytes) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - fk.submits++; - return 0; -} -static int f_retire(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; return 0; } -static void *f_halloc(void *c, size_t b) { (void)c; return malloc(b); } -static void f_hfree(void *c, void *p) { (void)c; free(p); } - -static OmegaGpuPlatform g_plat = { - .ctx = &fk, .time_now_ms = f_now_ms, .wait_ms = f_wait, .lock = f_lock, .unlock = f_unlock, - .dma_alloc = f_alloc, .dma_free = f_free, .sync_cpu_to_gpu = f_c2g, .sync_gpu_to_cpu = f_g2c, .poll_word = f_poll, - .device_open = f_dev_open, .device_close = f_dev_close, .diag_text = f_diag, - .queue_open = f_qopen, .queue_close = f_qclose, .queue_submit = f_submit, .queue_retire = f_retire, - .time_now_ns = f_now_ns, .host_alloc = f_halloc, .host_free = f_hfree, -}; - -/* ---- a one-layer graph on the fake ---- */ -#define LAYERS 1u -#define VOCAB 256u -#define MAX_POS 256u -typedef struct { - OmegaGpuDecodeAttnCache *attn; - OmegaGpuRouter *router; - OmegaGpuBf16Tensor *lm; - OmegaGpuDecodeGraph *g; -} World; - -static int world_build(World *w) { - memset(w, 0, sizeof *w); - static uint16_t lm_w[VOCAB * OMEGA_GPU_DGRAPH_HIDDEN]; /* zeros: finite bf16 */ - if (omega_gpu_decode_attn_cache_alloc(LAYERS, MAX_POS, 1e6, &w->attn) != 0) return -1; - if (omega_gpu_router_alloc(LAYERS, &w->router) != 0) return -1; - if (omega_gpu_bf16_tensor_upload(VOCAB, OMEGA_GPU_DGRAPH_HIDDEN, lm_w, &w->lm) != 0) return -1; - OmegaGpuDecodeGraphConfig cfg; memset(&cfg, 0, sizeof cfg); - cfg.layers = LAYERS; cfg.vocab = VOCAB; cfg.eps = 1e-6f; cfg.norm_topk = 1; - cfg.router = w->router; cfg.attn = w->attn; cfg.lm_head = w->lm; - return omega_gpu_decode_graph_create(&cfg, &w->g) == OMEGA_GPU_DGRAPH_OK ? 0 : -1; -} -static void world_free(World *w) { - omega_gpu_decode_graph_free(w->g); - omega_gpu_bf16_tensor_free(w->lm); - omega_gpu_router_free(w->router); - omega_gpu_decode_attn_cache_free(w->attn); - memset(w, 0, sizeof *w); -} - -static float g_x[OMEGA_GPU_DGRAPH_HIDDEN], g_norm[OMEGA_GPU_DGRAPH_HIDDEN]; - -/* The postcondition of every failed or finished call: lock free, never taken twice, never released twice. */ -#define EXPECT_LOCK_FREE() do { EXPECT(fk.locks_held == 0); EXPECT(fk.double_locks == 0); EXPECT(fk.bad_unlocks == 0); } while (0) - -/* Not in a token any more: the between-token calls run (BAD_ARGS here would mean in_token stuck). */ -static void expect_between_tokens(World *w) { - EXPECT(omega_gpu_decode_graph_set_final_norm(w->g, g_norm) == OMEGA_GPU_DGRAPH_OK); - EXPECT_LOCK_FREE(); - float x[OMEGA_GPU_DGRAPH_HIDDEN]; - EXPECT(omega_gpu_decode_graph_read(w->g, x, NULL, NULL) == OMEGA_GPU_DGRAPH_OK); - EXPECT_LOCK_FREE(); -} - -/* A valid split-API token: begin, nothing recorded, end; the fake device "wrote" the token. */ -static void expect_valid_token(World *w, uint32_t want) { - OmegaGpuDecodeGraphVas v; omega_gpu_decode_graph_vas(w->g, &v); - fk.dev_token_va = v.token; fk.dev_token = want; - const unsigned submits = fk.submits; - EXPECT(omega_gpu_decode_graph_begin_token(w->g, g_x) == OMEGA_GPU_DGRAPH_OK); - EXPECT(fk.locks_held == 1); - uint32_t tok = 0xdeadu; - OmegaGpuDecodeGraphStats st; memset(&st, 0xff, sizeof st); - EXPECT(omega_gpu_decode_graph_end_token(w->g, &tok, &st) == OMEGA_GPU_DGRAPH_OK); - EXPECT(tok == want && st.launches == 0 && st.submits == 0); - EXPECT(fk.submits == submits); /* an empty list submits nothing */ - EXPECT_LOCK_FREE(); - fk.dev_token_va = 0; -} - -static int install(void) { - memset(&fk, 0, sizeof fk); omega_gpu_handles_init(&fk.t); - for (unsigned i = 0; i < OMEGA_GPU_DGRAPH_HIDDEN; i++) { g_x[i] = (float)(i % 7) - 3.0f; g_norm[i] = 1.0f; } - return omega_gpu_session_set_platform(&g_plat, &g_caps); -} - -/* Visibility sync (cpu->gpu of x and the poisoned token) refused: split and one-shot paths, repeated, then recovery. */ -static void c_sync_fails(void) { - World w; - if (install() != OMEGA_GPU_PLAT_OK) { EXPECT(!"fake platform installs"); return; } /* never fall back to the real driver */ - if (world_build(&w) != 0) { EXPECT(!"world builds on the fake"); return; } - EXPECT_LOCK_FREE(); - const unsigned submits = fk.submits; - fk.fail_c2g = 1; - for (int rep = 0; rep < 3; rep++) { /* same outcome every time */ - EXPECT(omega_gpu_decode_graph_begin_token(w.g, g_x) == OMEGA_GPU_DGRAPH_CHIP_FAIL); - EXPECT_LOCK_FREE(); - } - /* nothing owed after a failed begin: end and abort see no token */ - uint32_t tok = 7; - EXPECT(omega_gpu_decode_graph_end_token(w.g, &tok, NULL) == OMEGA_GPU_DGRAPH_BAD_ARGS && tok == 7); - EXPECT(omega_gpu_decode_graph_abort_token(w.g) == OMEGA_GPU_DGRAPH_BAD_ARGS); - EXPECT(omega_gpu_decode_graph_record_final(w.g) == OMEGA_GPU_DGRAPH_BAD_ARGS); - EXPECT_LOCK_FREE(); - /* one-shot: the begin failure comes back as CHIP_FAIL with zeroed stats, lock free */ - OmegaGpuDecodeGraphStats st; memset(&st, 0xff, sizeof st); - tok = 7; - EXPECT(omega_gpu_decode_graph_token(w.g, g_x, 0, &tok, &st) == OMEGA_GPU_DGRAPH_CHIP_FAIL); - EXPECT(tok == 7 && st.launches == 0 && st.submits == 0 && st.total_ns == 0); - EXPECT_LOCK_FREE(); - EXPECT(fk.submits == submits); /* nothing reached the device, nothing retried */ - EXPECT(!omega_gpu_session_is_blocked()); - fk.fail_c2g = 0; - expect_between_tokens(&w); - expect_valid_token(&w, 42u); - expect_valid_token(&w, 43u); /* and again */ - world_free(&w); - EXPECT_LOCK_FREE(); -} - -/* Device open refused: the session was closed (every handle stale), the reopen in begin_token fails. */ -static void c_open_fails(void) { - World w; - if (install() != OMEGA_GPU_PLAT_OK) { EXPECT(!"fake platform installs"); return; } /* never fall back to the real driver */ - if (world_build(&w) != 0) { EXPECT(!"world builds on the fake"); return; } - omega_gpu_session_close(); - EXPECT_LOCK_FREE(); - fk.fail_open = 1; - for (int rep = 0; rep < 3; rep++) { - EXPECT(omega_gpu_decode_graph_begin_token(w.g, g_x) == OMEGA_GPU_DGRAPH_CHIP_FAIL); - EXPECT_LOCK_FREE(); - } - EXPECT(omega_gpu_decode_graph_token(w.g, g_x, 0, NULL, NULL) == OMEGA_GPU_DGRAPH_CHIP_FAIL); - EXPECT_LOCK_FREE(); - EXPECT(omega_gpu_decode_graph_end_token(w.g, NULL, NULL) == OMEGA_GPU_DGRAPH_BAD_ARGS); - /* the graph's buffers belong to the closed device: set_final_norm and read reach the stale sync and refuse (not - * BAD_ARGS: the graph is out of the token), nothing hangs */ - EXPECT(omega_gpu_decode_graph_set_final_norm(w.g, g_norm) == OMEGA_GPU_DGRAPH_CHIP_FAIL); - EXPECT(omega_gpu_decode_graph_read(w.g, NULL, NULL, NULL) == OMEGA_GPU_DGRAPH_CHIP_FAIL); - EXPECT_LOCK_FREE(); - fk.fail_open = 0; - /* reopen succeeds; the old graph's buffer is stale, so its begin fails at the visibility sync, lock free */ - EXPECT(omega_gpu_decode_graph_begin_token(w.g, g_x) == OMEGA_GPU_DGRAPH_CHIP_FAIL); - EXPECT_LOCK_FREE(); - world_free(&w); - EXPECT_LOCK_FREE(); - /* a fresh graph on the reopened device runs a valid token */ - if (world_build(&w) != 0) { EXPECT(!"world rebuilds after the reopen"); return; } - expect_valid_token(&w, 5u); - world_free(&w); - EXPECT_LOCK_FREE(); -} - -/* The caller abandons a begun token (cancellation): nothing submitted, lock released, the next token runs. */ -static void c_abort(void) { - World w; - if (install() != OMEGA_GPU_PLAT_OK) { EXPECT(!"fake platform installs"); return; } /* never fall back to the real driver */ - if (world_build(&w) != 0) { EXPECT(!"world builds on the fake"); return; } - OmegaGpuDecodeGraphVas v; omega_gpu_decode_graph_vas(w.g, &v); - const unsigned submits = fk.submits; - /* abort after a recorded launch */ - EXPECT(omega_gpu_decode_graph_begin_token(w.g, g_x) == OMEGA_GPU_DGRAPH_OK); - EXPECT(omega_gpu_decode_graph_record_res(w.g, OMEGA_DEC_RES_NORM, v.x, 0, 0, v.x, v.xq, 1e-6f, 1.0f) == OMEGA_GPU_DGRAPH_OK); - EXPECT(omega_gpu_decode_graph_abort_token(w.g) == OMEGA_GPU_DGRAPH_OK); - EXPECT_LOCK_FREE(); - EXPECT(fk.submits == submits); - EXPECT(omega_gpu_decode_graph_abort_token(w.g) == OMEGA_GPU_DGRAPH_BAD_ARGS); /* only once */ - EXPECT(omega_gpu_decode_graph_end_token(w.g, NULL, NULL) == OMEGA_GPU_DGRAPH_BAD_ARGS); - EXPECT_LOCK_FREE(); - /* abort after a failed record */ - EXPECT(omega_gpu_decode_graph_begin_token(w.g, g_x) == OMEGA_GPU_DGRAPH_OK); - EXPECT(omega_gpu_decode_graph_record_res(w.g, 0xffu, v.x, 0, 0, 0, v.xq, 1e-6f, 1.0f) == OMEGA_GPU_DGRAPH_BAD_ARGS); - EXPECT(omega_gpu_decode_graph_abort_token(w.g) == OMEGA_GPU_DGRAPH_OK); - EXPECT_LOCK_FREE(); - EXPECT(fk.submits == submits); - /* abort with nothing begun */ - EXPECT(omega_gpu_decode_graph_abort_token(NULL) == OMEGA_GPU_DGRAPH_BAD_ARGS); - expect_between_tokens(&w); - expect_valid_token(&w, 9u); - world_free(&w); - EXPECT_LOCK_FREE(); -} - -/* end_token after a failed record: no submit, the failure returned, lock released, the next token runs. */ -static void c_end_after_record_fail(void) { - World w; - if (install() != OMEGA_GPU_PLAT_OK) { EXPECT(!"fake platform installs"); return; } /* never fall back to the real driver */ - if (world_build(&w) != 0) { EXPECT(!"world builds on the fake"); return; } - OmegaGpuDecodeGraphVas v; omega_gpu_decode_graph_vas(w.g, &v); - const unsigned submits = fk.submits; - EXPECT(omega_gpu_decode_graph_begin_token(w.g, g_x) == OMEGA_GPU_DGRAPH_OK); - EXPECT(omega_gpu_decode_graph_record_res(w.g, OMEGA_DEC_RES_NORM, v.x, 0, 0, v.x, v.xq, 1e-6f, 1.0f) == OMEGA_GPU_DGRAPH_OK); - EXPECT(omega_gpu_decode_graph_record_layer(w.g, 0, 0) == OMEGA_GPU_DGRAPH_BAD_ARGS); /* layer 0 never set */ - EXPECT(omega_gpu_decode_graph_record_final(w.g) == OMEGA_GPU_DGRAPH_CHIP_FAIL); /* failed sticks */ - uint32_t tok = 7; - EXPECT(omega_gpu_decode_graph_end_token(w.g, &tok, NULL) == OMEGA_GPU_DGRAPH_CHIP_FAIL && tok == 7); - EXPECT(fk.submits == submits); - EXPECT_LOCK_FREE(); - /* one-shot with an unset layer: the same, deterministically */ - for (int rep = 0; rep < 2; rep++) { - EXPECT(omega_gpu_decode_graph_token(w.g, g_x, 0, &tok, NULL) == OMEGA_GPU_DGRAPH_CHIP_FAIL && tok == 7); - EXPECT(fk.submits == submits); - EXPECT_LOCK_FREE(); - } - expect_between_tokens(&w); - expect_valid_token(&w, 11u); - world_free(&w); - EXPECT_LOCK_FREE(); -} - -/* An uncertain completion: the submitted list never completes, the process latches. end_token reports the failure (never - * a token); every later begin fails at once with the lock released, submits nothing and retries nothing. */ -static void c_latched(void) { - World w; - if (install() != OMEGA_GPU_PLAT_OK) { EXPECT(!"fake platform installs"); return; } /* never fall back to the real driver */ - if (world_build(&w) != 0) { EXPECT(!"world builds on the fake"); return; } - OmegaGpuDecodeGraphVas v; omega_gpu_decode_graph_vas(w.g, &v); - fk.dev_token_va = v.token; fk.dev_token = 3u; /* even a token in the slot must not be claimed after a timeout */ - EXPECT(omega_gpu_decode_graph_begin_token(w.g, g_x) == OMEGA_GPU_DGRAPH_OK); - EXPECT(omega_gpu_decode_graph_record_res(w.g, OMEGA_DEC_RES_NORM, v.x, 0, 0, v.x, v.xq, 1e-6f, 1.0f) == OMEGA_GPU_DGRAPH_OK); - uint32_t tok = 7; - EXPECT(omega_gpu_decode_graph_end_token(w.g, &tok, NULL) == OMEGA_GPU_DGRAPH_CHIP_FAIL && tok == 7); - EXPECT(fk.submits >= 1); - EXPECT(omega_gpu_session_is_blocked()); - EXPECT_LOCK_FREE(); - const unsigned submits = fk.submits, opens = fk.dev_opens; - for (int rep = 0; rep < 3; rep++) { - EXPECT(omega_gpu_decode_graph_begin_token(w.g, g_x) == OMEGA_GPU_DGRAPH_CHIP_FAIL); - EXPECT_LOCK_FREE(); - EXPECT(omega_gpu_decode_graph_token(w.g, g_x, 0, &tok, NULL) == OMEGA_GPU_DGRAPH_CHIP_FAIL && tok == 7); - EXPECT_LOCK_FREE(); - } - EXPECT(fk.submits == submits && fk.dev_opens == opens); /* no retry, no reopen */ - EXPECT(omega_gpu_decode_graph_end_token(w.g, NULL, NULL) == OMEGA_GPU_DGRAPH_BAD_ARGS); - EXPECT(omega_gpu_decode_graph_abort_token(w.g) == OMEGA_GPU_DGRAPH_BAD_ARGS); - EXPECT(omega_gpu_decode_graph_set_final_norm(w.g, g_norm) == OMEGA_GPU_DGRAPH_OK); - (void)omega_gpu_decode_graph_read(w.g, NULL, NULL, NULL); /* latched: refused or parked, but it returns */ - EXPECT_LOCK_FREE(); - world_free(&w); - EXPECT_LOCK_FREE(); - EXPECT(omega_gpu_session_is_blocked()); -} - -typedef struct { const char *name; void (*fn)(void); } Case; -static const Case CASES[] = { - { "visibility sync refused at begin: split + one-shot recover", c_sync_fails }, - { "device open refused at begin: lock free, reopen recovers", c_open_fails }, - { "abort_token: cancel a begun token, nothing submitted", c_abort }, - { "end_token after a failed record: no submit, lock free", c_end_after_record_fail }, - { "latched session: begin fails at once, no retry", c_latched }, -}; - -int main(int argc, char **argv) { - const unsigned n = sizeof CASES / sizeof CASES[0]; - if (argc == 2) { /* one case in this process (debugging): its index */ - const unsigned i = (unsigned)atoi(argv[1]); - if (i >= n) return 2; - case_ok = 1; CASES[i].fn(); - printf("%s %s\n", case_ok ? "ok " : "FAIL", CASES[i].name); - return case_ok ? 0 : 1; - } - unsigned failed = 0; - for (unsigned i = 0; i < n; i++) { - fflush(stdout); - pid_t pid = fork(); - if (pid == 0) { case_ok = 1; CASES[i].fn(); fflush(stdout); _exit(case_ok ? 0 : 1); } - int status = 0; - int ok = pid > 0 && waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0; - printf("%s %s\n", ok ? "ok " : "FAIL", CASES[i].name); - if (!ok) failed++; - } - printf("test_omega_gpu_decode_graph_abort: %u of %u cases passed: %s\n", n - failed, n, failed ? "FAIL" : "PASS"); - return failed ? 1 : 0; -} diff --git a/tests/test_omega_gpu_decode_graph_timeline.c b/tests/test_omega_gpu_decode_graph_timeline.c deleted file mode 100644 index 619eac986..000000000 --- a/tests/test_omega_gpu_decode_graph_timeline.c +++ /dev/null @@ -1,302 +0,0 @@ -/* test_omega_gpu_decode_graph_timeline: the decode graph's per-token timeline never writes past stamp[] (omega #456). - * Host program on a FAKE OmegaGpuPlatform that completes every submission (markers, launch semaphores, stamp reports); - * links libomega_gpu.a with the fake installed first; opens no device, touches no GPU. - * - * The timeline holds OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1 stamps. Batched, a token's list never holds more launches than - * that. With flush_each (one submission per launch) the list is emptied after every launch, so nothing in the command - * list bounds the number of launches a token records: before #456 the 4097th stamped launch wrote stamp[4097], past the - * end of the graph. Contract under test: 4096 launches fill the timeline exactly (stamps() returns 4096); one more fails - * the token (CHIP_FAIL, timeline refused, lock released) and the next token runs normally. - * - * Each case runs in its own child process. - */ -#include "omega_gpu_decode_graph.h" -#include "omega_gpu_session.h" -#include "omega_gpu_platform.h" -#include "omega_gpu_cmdlist.h" -#include "omega_blackwell_submit.h" - -#include -#include -#include -#include -#include - -static int case_ok; -#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) - -/* ---- the fake platform: every submitted word stream "runs" ---- */ -#define NB OMEGA_GPU_HANDLE_SLOTS -#define VA_BASE 0x100000000ull -#define VA_STRIDE 0x1000000ull -static struct { - OmegaGpuHandleTable t; - void *mem[NB]; - OmegaGpuBufferDesc desc[NB]; - OmegaGpuDeviceHandle dev; - OmegaGpuQueueHandle q; - OmegaGpuBufferHandle ring; - uint64_t ns; - unsigned locks_held, double_locks, bad_unlocks, submits; - uint64_t dev_token_va; /* nonzero: the device wrote dev_token there (seen at the gpu->cpu sync) */ - uint32_t dev_token; -} fk; - -static uint64_t f_now_ns(void *c) { (void)c; fk.ns += 1000u; return fk.ns; } -static uint64_t f_now_ms(void *c) { return f_now_ns(c) / 1000000u; } -static int f_wait(void *c, uint64_t ms) { (void)c; fk.ns += ms * 1000000u; return 0; } -static int f_lock(void *c, uint32_t id) { - (void)c; - if (id != OMEGA_GPU_SESSION_LOCK_ID) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if (fk.locks_held) { fk.double_locks++; return OMEGA_GPU_PLAT_REFUSED_BUSY; } /* a real lock would block forever */ - fk.locks_held = 1; - return 0; -} -static int f_unlock(void *c, uint32_t id) { - (void)c; - if (id != OMEGA_GPU_SESSION_LOCK_ID || !fk.locks_held) { fk.bad_unlocks++; return OMEGA_GPU_PLAT_REFUSED_ARGS; } - fk.locks_held = 0; - return 0; -} -static const char *f_diag(void *c) { (void)c; return ""; } -static int f_dev_open(void *c, uint32_t ord, OmegaGpuDeviceHandle *out) { - (void)c; - if (ord != 0 || fk.dev.generation) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - int rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &out->index, &out->generation); - if (rc == 0) fk.dev = *out; - return rc; -} -static int f_dev_close(void *c, OmegaGpuDeviceHandle d) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (rc) return rc; - (void)omega_gpu_handles_close(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - memset(&fk.dev, 0, sizeof fk.dev); - return 0; -} -static OmegaGpuPlatformCaps g_caps = { - .abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR, .abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR, - .services = OMEGA_GPU_SVC_REQUIRED_SESSION, .max_devices = 1, .max_buffers = 1000, .max_queues = 1, .max_inflight = 1, - .max_buffer_bytes = 1ull << 30, .max_total_bytes = 1ull << 32, -}; -static int f_alloc(void *c, OmegaGpuDeviceHandle d, const OmegaGpuBufferDesc *desc, OmegaGpuBufferHandle *o, - OmegaCpuView *cpu, OmegaGpuVa *g, OmegaGpuBusAddr *b) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (!rc) rc = omega_gpu_platform_check_buffer(desc, &g_caps); - if (!rc) rc = omega_gpu_handles_open(&fk.t, desc->kind, desc->bytes, 1000, 1ull << 32, &o->index, &o->generation); - if (rc) return rc; - void *m = calloc(1, desc->bytes); - if (!m) { (void)omega_gpu_handles_close(&fk.t, o->index, o->generation, desc->kind); return OMEGA_GPU_PLAT_REFUSED_LIMIT; } - fk.mem[o->index] = m; fk.desc[o->index] = *desc; - cpu->ptr = m; cpu->len = desc->bytes; g->va = VA_BASE + (uint64_t)o->index * VA_STRIDE; b->iova = 0; - return 0; -} -static int f_free(void *c, OmegaGpuBufferHandle h) { - (void)c; - if (h.index >= NB) return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; - int rc = omega_gpu_handles_close(&fk.t, h.index, h.generation, fk.t.kind[h.index]); - if (rc) return rc; - free(fk.mem[h.index]); fk.mem[h.index] = NULL; - return 0; -} -static int buf_live(OmegaGpuBufferHandle h) { return h.index < NB && fk.t.live[h.index] && fk.t.generation[h.index] == h.generation; } -static void *va_to_cpu(uint64_t va) { - for (uint32_t i = 0; i < NB; i++) { - if (!fk.mem[i] || !fk.t.live[i]) continue; - const uint64_t base = VA_BASE + (uint64_t)i * VA_STRIDE; - if (va >= base && va < base + fk.desc[i].bytes) return (uint8_t *)fk.mem[i] + (va - base); - } - return NULL; -} -static int sync_check(OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { - if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - if (len == 0 || off > fk.desc[h.index].bytes || len > fk.desc[h.index].bytes - off) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - return 0; -} -static int f_c2g(void *c, OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { (void)c; return sync_check(h, off, len); } -/* gpu->cpu: a command list's launch semaphores (16-byte slots, every one still INIT) read DONE: the launches ran. - * Only a range whose every 16-byte slot holds INIT is taken for a semaphore array. */ -static int f_g2c(void *c, OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { - (void)c; - int rc = sync_check(h, off, len); - if (rc) return rc; - if (len % 16u == 0) { - uint32_t *w = (uint32_t *)((uint8_t *)fk.mem[h.index] + off); - uint64_t i = 0, n = len / 16u; - while (i < n && w[4 * i] == OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT) i++; - if (i == n) for (i = 0; i < n; i++) w[4 * i] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE; - } - if (fk.dev_token_va) { uint32_t *t = va_to_cpu(fk.dev_token_va); if (t) t[0] = fk.dev_token; } - return 0; -} -static int f_poll(void *c, OmegaGpuBufferHandle h, uint64_t off, uint32_t want, uint64_t ms, uint32_t *seen) { - (void)c; - if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - if (!(fk.desc[h.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED)) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - const volatile uint32_t *w = (const volatile uint32_t *)((uint8_t *)fk.mem[h.index] + off); - *seen = *w; - if ((int32_t)(*w - want) >= 0) return 0; - fk.ns += ms * 1000000u; - return OMEGA_GPU_POLL_TIMED_OUT; -} -static int f_qopen(void *c, OmegaGpuDeviceHandle d, OmegaGpuBufferHandle ring, OmegaGpuQueueHandle *o) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (!rc && (!buf_live(ring) || fk.t.kind[ring.index] != OMEGA_GPU_HANDLE_BUF_QUEUE)) rc = OMEGA_GPU_PLAT_REFUSED_BAD_KIND; - if (!rc) rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_QUEUE, 0, 1, 0, &o->index, &o->generation); - if (!rc) { fk.q = *o; fk.ring = ring; } - return rc; -} -static int f_qclose(void *c, OmegaGpuQueueHandle q) { - (void)c; - int rc = omega_gpu_handles_close(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); - if (!rc) memset(&fk.q, 0, sizeof fk.q); - return rc; -} -static uint32_t mthd(uint32_t subc, uint32_t m, uint32_t count) { return (2u << 28) | (count << 16) | (subc << 13) | (m >> 2); } -/* The fake device runs the stream: semaphore releases (0x005c: the completion markers) write their payload, compute - * report semaphores (0x0158, four-word: the stamps) write {payload, timestamp}. */ -static int f_submit(void *c, OmegaGpuQueueHandle q, const uint32_t *w, uint32_t n) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); - if (rc) return rc; - if ((uint64_t)n * 4u > fk.desc[fk.ring.index].bytes) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - fk.submits++; - for (uint32_t i = 0; i + 5 < n; i++) { - if (w[i] == mthd(0, 0x005c, 5)) { - uint32_t *m = va_to_cpu((uint64_t)w[i + 1] | ((uint64_t)w[i + 2] << 32)); - if (m) *m = w[i + 3]; - i += 5; - } else if (w[i] == mthd(1, 0x0158, 5)) { - uint64_t *s = va_to_cpu((uint64_t)w[i + 3] | ((uint64_t)w[i + 4] << 32)); - if (s) { s[0] = (uint64_t)w[i + 1] | ((uint64_t)w[i + 2] << 32); s[1] = (fk.ns += 1000u); } - i += 5; - } - } - return 0; -} -static int f_retire(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; return 0; } -static void *f_halloc(void *c, size_t b) { (void)c; return malloc(b); } -static void f_hfree(void *c, void *p) { (void)c; free(p); } - -static OmegaGpuPlatform g_plat = { - .ctx = &fk, .time_now_ms = f_now_ms, .wait_ms = f_wait, .lock = f_lock, .unlock = f_unlock, - .dma_alloc = f_alloc, .dma_free = f_free, .sync_cpu_to_gpu = f_c2g, .sync_gpu_to_cpu = f_g2c, .poll_word = f_poll, - .device_open = f_dev_open, .device_close = f_dev_close, .diag_text = f_diag, - .queue_open = f_qopen, .queue_close = f_qclose, .queue_submit = f_submit, .queue_retire = f_retire, - .time_now_ns = f_now_ns, .host_alloc = f_halloc, .host_free = f_hfree, -}; - -/* ---- a one-layer graph on the fake ---- */ -#define LAYERS 1u -#define VOCAB 256u -#define MAX_POS 256u -typedef struct { - OmegaGpuDecodeAttnCache *attn; - OmegaGpuRouter *router; - OmegaGpuBf16Tensor *lm; - OmegaGpuDecodeGraph *g; -} World; - -static int world_build(World *w) { - memset(w, 0, sizeof *w); - static uint16_t lm_w[VOCAB * OMEGA_GPU_DGRAPH_HIDDEN]; /* zeros: finite bf16 */ - if (omega_gpu_decode_attn_cache_alloc(LAYERS, MAX_POS, 1e6, &w->attn) != 0) return -1; - if (omega_gpu_router_alloc(LAYERS, &w->router) != 0) return -1; - if (omega_gpu_bf16_tensor_upload(VOCAB, OMEGA_GPU_DGRAPH_HIDDEN, lm_w, &w->lm) != 0) return -1; - OmegaGpuDecodeGraphConfig cfg; memset(&cfg, 0, sizeof cfg); - cfg.layers = LAYERS; cfg.vocab = VOCAB; cfg.eps = 1e-6f; cfg.norm_topk = 1; - cfg.router = w->router; cfg.attn = w->attn; cfg.lm_head = w->lm; - if (omega_gpu_decode_graph_create(&cfg, &w->g) != OMEGA_GPU_DGRAPH_OK) return -1; - omega_gpu_decode_graph_set_stamps(w->g, 1); - omega_gpu_decode_graph_set_flush_each(w->g, 1); /* one submission per launch: the list never bounds the token */ - return 0; -} - -static float g_x[OMEGA_GPU_DGRAPH_HIDDEN]; -#define EXPECT_LOCK_FREE() do { EXPECT(fk.locks_held == 0); EXPECT(fk.double_locks == 0); EXPECT(fk.bad_unlocks == 0); } while (0) - -static int install(void) { - memset(&fk, 0, sizeof fk); omega_gpu_handles_init(&fk.t); - for (unsigned i = 0; i < OMEGA_GPU_DGRAPH_HIDDEN; i++) g_x[i] = (float)(i % 7) - 3.0f; - return omega_gpu_session_set_platform(&g_plat, &g_caps); -} - -/* One token of `launches` SWIGLU glue launches (each submitted on its own); returns end_token's code, fills *refused - * with the first record that did not return OK (launches when every record did). */ -static int token_of(World *w, uint32_t launches, uint32_t want, uint32_t *refused, uint32_t *tok) { - OmegaGpuDecodeGraphVas v; omega_gpu_decode_graph_vas(w->g, &v); - fk.dev_token_va = v.token; fk.dev_token = want; - *refused = launches; - if (omega_gpu_decode_graph_begin_token(w->g, g_x) != OMEGA_GPU_DGRAPH_OK) return -1000; - for (uint32_t i = 0; i < launches; i++) - if (omega_gpu_decode_graph_record_swiglu(w->g, v.gu, v.act, 1.0f) != OMEGA_GPU_DGRAPH_OK && *refused == launches) *refused = i; - const int rc = omega_gpu_decode_graph_end_token(w->g, tok, NULL); - fk.dev_token_va = 0; - return rc; -} - -static uint64_t g_st[OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 2]; -static uint8_t g_kd[OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 2]; - -/* MAX_LAUNCHES stamped launches: the timeline is exactly full and reads back whole. */ -static void c_full(void) { - World w; - if (install() != OMEGA_GPU_PLAT_OK) { EXPECT(!"fake platform installs"); return; } /* never fall back to the real driver */ - if (world_build(&w) != 0) { EXPECT(!"world builds on the fake"); return; } - uint32_t refused = 0, tok = 0; - EXPECT(token_of(&w, OMEGA_GPU_CMDLIST_MAX_LAUNCHES, 7, &refused, &tok) == OMEGA_GPU_DGRAPH_OK); - EXPECT(refused == OMEGA_GPU_CMDLIST_MAX_LAUNCHES && tok == 7); - EXPECT(fk.submits == OMEGA_GPU_CMDLIST_MAX_LAUNCHES); - EXPECT_LOCK_FREE(); - EXPECT(omega_gpu_decode_graph_stamps(w.g, g_st, g_kd, OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 2) == (int)OMEGA_GPU_CMDLIST_MAX_LAUNCHES); - for (uint32_t i = 0; i < OMEGA_GPU_CMDLIST_MAX_LAUNCHES; i++) if (!(g_st[i + 1] > g_st[i])) { EXPECT(!"stamps increase"); break; } -} - -/* One launch more than the timeline holds: that record fails the token, nothing is written past stamp[], the lock is - * released at end_token, no timeline is offered, and the next (small) token runs and reads back normally. */ -static void c_overflow(void) { - World w; - if (install() != OMEGA_GPU_PLAT_OK) { EXPECT(!"fake platform installs"); return; } - if (world_build(&w) != 0) { EXPECT(!"world builds on the fake"); return; } - uint32_t refused = 0, tok = 0xdeadu; - EXPECT(token_of(&w, OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1u, 7, &refused, &tok) == OMEGA_GPU_DGRAPH_CHIP_FAIL); - EXPECT(refused == OMEGA_GPU_CMDLIST_MAX_LAUNCHES); /* the 4097th launch, the first that has no stamp slot */ - EXPECT(tok == 0xdeadu); - EXPECT(strstr(omega_gpu_session_last_error(), "timeline full") != NULL); - EXPECT_LOCK_FREE(); - EXPECT(omega_gpu_decode_graph_stamps(w.g, g_st, g_kd, OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 2) == OMEGA_GPU_DGRAPH_BAD_ARGS); - EXPECT(token_of(&w, 3, 9, &refused, &tok) == OMEGA_GPU_DGRAPH_OK); - EXPECT(refused == 3 && tok == 9); - EXPECT_LOCK_FREE(); - EXPECT(omega_gpu_decode_graph_stamps(w.g, g_st, g_kd, OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 2) == 3); -} - -static const struct { const char *name; void (*fn)(void); } CASES[] = { - { "timeline exactly full: 4096 stamped launches read back", c_full }, - { "one launch past the timeline: token fails, no write past stamp[]", c_overflow }, -}; - -int main(int argc, char **argv) { - const unsigned n = sizeof CASES / sizeof CASES[0]; - if (argc == 2) { /* one case in this process (debugging): its index */ - const unsigned i = (unsigned)atoi(argv[1]); - if (i >= n) return 2; - case_ok = 1; CASES[i].fn(); - printf("%s %s\n", case_ok ? "ok " : "FAIL", CASES[i].name); - return case_ok ? 0 : 1; - } - unsigned failed = 0; - for (unsigned i = 0; i < n; i++) { - fflush(stdout); - pid_t pid = fork(); - if (pid == 0) { case_ok = 1; CASES[i].fn(); fflush(stdout); _exit(case_ok ? 0 : 1); } - int status = 0; - int ok = pid > 0 && waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0; - printf("%s %s\n", ok ? "ok " : "FAIL", CASES[i].name); - if (!ok) failed++; - } - printf("test_omega_gpu_decode_graph_timeline: %u of %u cases passed: %s\n", n - failed, n, failed ? "FAIL" : "PASS"); - return failed ? 1 : 0; -} diff --git a/tests/test_omega_gpu_engine.c b/tests/test_omega_gpu_engine.c deleted file mode 100644 index a1a1c15f8..000000000 --- a/tests/test_omega_gpu_engine.c +++ /dev/null @@ -1,1171 +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. - */ - -/* - * Host test of the Omega GPU Engine core (A3a) against a FAKE backend. - * No device, no physics headers. Every case prints "[PASS] id" or "[FAIL] id"; - * the last line is "SUMMARY passed=N failed=M"; exit status is nonzero on any - * failure. docs/numeric/OMEGA_GPU_ENGINE.md section 13 lists every case id. - * - * The fake records every backend call in order, can fail the n-th call of any - * kind with a chosen return code (and advance a fake clock), simulates device - * memory (poison fill, a kernel that writes a chosen word range, copy-in and - * copy-out) and flags protocol violations (free of a buffer that is not - * allocated, copy-in to an unallocated buffer, and so on). - */ -#include "omega_gpu_engine.h" - -#include -#include -#include - -#define N 16u -#define INJ_ERRNO EIO -#ifdef OMEGA_GPU_NO_POSIX -#define EXPECT_ERRNO 0 /* the freestanding engine (make test-gpu-engine-freestanding) records no errno */ -#else -#define EXPECT_ERRNO INJ_ERRNO -#endif -#define DIAG_RC (-1234) -#define DIAG_TEXT "fake driver text" -#define LOGMAX 64 -#define TMO_MARKER 111u -#define TMO_MARKER2 222u -#define TMO_RELEASE 333u -#define TMO_VISIBILITY 444u - -enum { - C_OPEN = 0, C_CHANNEL, C_ALLOC, C_COPY_IN, C_POISON, C_BUILD, C_SUBMIT, C_MARKER, - C_MARKER2, C_RELEASE, C_BARRIER, C_COPY_OUT, C_FREE, C_CLOSE, C_DIAG, C_COUNT -}; - -typedef struct { - int call; /* which kind of call to fail */ - int nth; /* 1-based occurrence of that kind */ - int rc; /* value the call returns */ - int advance; /* fake milliseconds the call takes */ -} Inj; - -typedef struct { - int log[LOGMAX]; /* every call except diagnostics, in order */ - int nlog; - int count[C_COUNT]; - int state_at[C_COUNT]; /* result->last_state at the first call of each kind, -1 if never */ - uint64_t tmo[C_COUNT]; /* timeout last passed to a timed call */ - Inj inj[2]; - int ninj; - int violations; - int dev_open; - int channel; - int live[OMEGA_GPU_BUF_ROLE_COUNT]; - int alloc_roles[8]; - size_t alloc_bytes[8]; - int nalloc; - int copy_roles[8]; - size_t copy_bytes[8]; - int ncopy; - int free_roles[8]; - int nfree; - uint32_t dev_prog[16]; - uint32_t dev_a[N]; - uint32_t dev_b[N]; - uint32_t dev_out[N]; - uint32_t seen_at_submit[N]; - int submit_seen; - const OmegaGpuJob *build_job; - size_t klo; /* the fake kernel writes output words [klo, khi) */ - size_t khi; -} Fake; - -static Fake F; -static OmegaGpuResult *g_res; /* result being filled, to snapshot last_state at each call */ -static uint64_t g_time; /* fake clock, milliseconds */ -static OmegaGpuBackend BE; - -static const unsigned char code[8] = {1, 2, 3, 4, 5, 6, 7, 8}; -static uint32_t ina[N]; -static uint32_t inb[N]; -static uint32_t poison[N]; -static uint32_t host_out[N + 4u]; /* four spare words so a stray write is visible, not fatal */ - -static int case_ok; -static int n_pass; -static int n_fail; - -#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) - -static void case_begin(void) { case_ok = 1; } - -static void case_end(const char *id) -{ - if (case_ok) { n_pass++; printf("[PASS] %s\n", id); } - else { n_fail++; printf("[FAIL] %s\n", id); } -} - -static uint64_t fake_now(void) { return g_time; } - -static uint32_t exp_out(size_t i) { return ina[i] + inb[i] + 0x100u; } - -/* ---- the fake backend ---------------------------------------------------- */ - -static int hit(int call) -{ - int i; - int n; - if (F.nlog < LOGMAX) F.log[F.nlog] = call; - F.nlog++; - n = ++F.count[call]; - if (F.state_at[call] < 0 && g_res) F.state_at[call] = g_res->last_state; - for (i = 0; i < F.ninj; i++) { - if (F.inj[i].call == call && F.inj[i].nth == n) { - g_time += (uint64_t)F.inj[i].advance; - errno = INJ_ERRNO; - return F.inj[i].rc; - } - } - return 0; -} - -static int f_open(void *c) -{ - int rc; - (void)c; - rc = hit(C_OPEN); - if (rc == 0) F.dev_open = 1; - return rc; -} - -static int f_channel(void *c) -{ - int rc; - (void)c; - rc = hit(C_CHANNEL); - if (rc != 0) return rc; - if (!F.dev_open) F.violations++; - F.channel = 1; - return 0; -} - -static int role_ok(int role) -{ - return role >= 0 && role < (int)OMEGA_GPU_BUF_ROLE_COUNT; -} - -static int f_alloc(void *c, int role, size_t bytes) -{ - int rc; - (void)c; - rc = hit(C_ALLOC); - if (rc != 0) return rc; - if (!role_ok(role) || F.live[role] || !F.channel) { F.violations++; return 0; } - F.live[role] = 1; - if (F.nalloc < 8) { F.alloc_roles[F.nalloc] = role; F.alloc_bytes[F.nalloc] = bytes; } - F.nalloc++; - return 0; -} - -static int f_copy_in(void *c, int role, const void *src, size_t bytes) -{ - int rc; - (void)c; - rc = hit(C_COPY_IN); - if (rc != 0) return rc; - if (!role_ok(role) || !F.live[role]) { F.violations++; return 0; } - if (F.ncopy < 8) { F.copy_roles[F.ncopy] = role; F.copy_bytes[F.ncopy] = bytes; } - F.ncopy++; - switch (role) { - case OMEGA_GPU_BUF_PROGRAM: - if (bytes > sizeof F.dev_prog) { F.violations++; break; } - memcpy(F.dev_prog, src, bytes); - break; - case OMEGA_GPU_BUF_INPUT_A: - if (bytes > sizeof F.dev_a) { F.violations++; break; } - memcpy(F.dev_a, src, bytes); - break; - case OMEGA_GPU_BUF_INPUT_B: - if (bytes > sizeof F.dev_b) { F.violations++; break; } - memcpy(F.dev_b, src, bytes); - break; - default: - F.violations++; - break; - } - return 0; -} - -static int f_poison(void *c, const uint32_t *words, size_t count) -{ - int rc; - (void)c; - rc = hit(C_POISON); - if (rc != 0) return rc; - if (!F.live[OMEGA_GPU_BUF_OUTPUT] || count != N) { F.violations++; return 0; } - memcpy(F.dev_out, words, count * sizeof(uint32_t)); - return 0; -} - -static int f_build(void *c, const OmegaGpuJob *job) -{ - int rc; - (void)c; - rc = hit(C_BUILD); - if (rc != 0) return rc; - F.build_job = job; - return 0; -} - -static int f_submit(void *c) -{ - int rc; - size_t i; - (void)c; - rc = hit(C_SUBMIT); - if (rc != 0) return rc; - memcpy(F.seen_at_submit, F.dev_out, sizeof F.dev_out); - F.submit_seen = 1; - for (i = F.klo; i < F.khi && i < N; i++) F.dev_out[i] = F.dev_a[i] + F.dev_b[i] + 0x100u; - return 0; -} - -static int f_wait_marker(void *c, uint64_t ms) -{ - (void)c; - F.tmo[C_MARKER] = ms; - return hit(C_MARKER); -} - -static int f_wait_marker2(void *c, uint64_t ms) -{ - (void)c; - F.tmo[C_MARKER2] = ms; - return hit(C_MARKER2); -} - -static int f_wait_release(void *c, uint64_t ms) -{ - (void)c; - F.tmo[C_RELEASE] = ms; - return hit(C_RELEASE); -} - -static int f_barrier(void *c, uint64_t ms) -{ - (void)c; - F.tmo[C_BARRIER] = ms; - return hit(C_BARRIER); -} - -static int f_copy_out(void *c, void *dst, size_t bytes) -{ - int rc; - (void)c; - rc = hit(C_COPY_OUT); - if (rc != 0) return rc; - if (bytes != sizeof F.dev_out) { F.violations++; return 0; } - memcpy(dst, F.dev_out, bytes); - return 0; -} - -static void f_diag(void *c, OmegaGpuBackendDiag *d) -{ - (void)c; - F.count[C_DIAG]++; - d->drv_rc = DIAG_RC; - memcpy(d->drv_text, DIAG_TEXT, sizeof DIAG_TEXT); - d->sync_valid = OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_MARKER2 | OMEGA_GPU_SYNC_SEMAPHORE; - d->marker = 0x11111111u; - d->marker2 = 0x22222222u; - d->semaphore[0] = 0x33333333u; - errno = 0; /* a diagnostics call that clobbers errno must not matter */ -} - -static int f_free(void *c, int role) -{ - int rc; - (void)c; - rc = hit(C_FREE); - if (F.nfree < 8) F.free_roles[F.nfree] = role; - F.nfree++; - if (rc != 0) return rc; - if (!role_ok(role) || !F.live[role]) { F.violations++; return 0; } - F.live[role] = 0; - return 0; -} - -static int f_close(void *c) -{ - int rc; - (void)c; - rc = hit(C_CLOSE); - if (rc != 0) return rc; - if (!F.dev_open) F.violations++; - F.dev_open = 0; - F.channel = 0; - return 0; -} - -static void backend_init(OmegaGpuBackend *b) -{ - memset(b, 0, sizeof *b); - b->ctx = NULL; - b->open_device = f_open; - b->create_channel = f_channel; - b->alloc = f_alloc; - b->copy_in = f_copy_in; - b->fill_poison = f_poison; - b->build = f_build; - b->submit = f_submit; - b->wait_marker = f_wait_marker; - b->wait_marker2 = f_wait_marker2; - b->wait_release_semaphore = f_wait_release; - b->barrier = f_barrier; - b->copy_out = f_copy_out; - b->diagnostics = f_diag; - b->free_buf = f_free; - b->close = f_close; -} - -/* ---- case helpers ------------------------------------------------------- */ - -static void reset_all(void) -{ - size_t i; - int k; - memset(&F, 0, sizeof F); - for (k = 0; k < C_COUNT; k++) F.state_at[k] = -1; - for (i = 0; i < N; i++) F.dev_out[i] = 0xA5A5A5A5u; /* garbage, never a poison word */ - F.klo = 0; - F.khi = N; - g_time = 1000u; - memset(host_out, 0xCC, sizeof host_out); - g_res = NULL; - backend_init(&BE); - omega_gpu_engine_test_reset_block(); - omega_gpu_engine_set_backend(&BE); -} - -static void make_job(OmegaGpuJob *j) -{ - size_t i; - for (i = 0; i < N; i++) { - ina[i] = (uint32_t)(i + 1u); - inb[i] = (uint32_t)(2u * i + 3u); - poison[i] = 0xDEAD0000u + (uint32_t)(i * 7u); /* distinct per word, never an expected output */ - } - memset(j, 0, sizeof *j); - j->program = code; - j->program_len = sizeof code; - j->layout = OMEGA_GPU_LAYOUT_VECTOR_1D; - j->element_count = N; - j->input_a = ina; - j->input_a_len = sizeof ina; - j->input_b = inb; - j->input_b_len = sizeof inb; - j->output = host_out; - j->output_len = N * sizeof(uint32_t); - j->poison = poison; - j->poison_count = N; - j->timeouts.marker_ms = TMO_MARKER; - j->timeouts.marker2_ms = TMO_MARKER2; - j->timeouts.release_semaphore_ms = TMO_RELEASE; - j->timeouts.visibility_ms = TMO_VISIBILITY; - j->flags = 0; -} - -static void inject(int call, int nth, int rc, int advance) -{ - F.inj[F.ninj].call = call; - F.inj[F.ninj].nth = nth; - F.inj[F.ninj].rc = rc; - F.inj[F.ninj].advance = advance; - F.ninj++; -} - -static int run(const OmegaGpuJob *job, OmegaGpuResult *r) -{ - int rc; - memset(r, 0x7f, sizeof *r); /* stale garbage the engine must fully overwrite */ - g_res = r; - rc = omega_gpu_execute(job, r); - g_res = NULL; - return rc; -} - -static void expect_log(const int *want, int n) -{ - int i; - EXPECT(F.nlog == n); - for (i = 0; i < n && i < F.nlog && i < LOGMAX; i++) EXPECT(F.log[i] == want[i]); -} - -static void expect_failure(int rc, const OmegaGpuResult *r, int failure, int last, int step, int wait) -{ - EXPECT(rc == failure); - EXPECT(r->failure == failure); - EXPECT(r->last_state == last); - EXPECT(r->failed_step == step); - EXPECT(r->wait == wait); -} - -static void expect_passthrough(const OmegaGpuResult *r, int err) -{ - EXPECT(r->drv_rc == DIAG_RC); - EXPECT(r->err_no == err); - EXPECT(strcmp(r->drv_text, DIAG_TEXT) == 0); - EXPECT(r->sync_valid == (OMEGA_GPU_SYNC_MARKER | OMEGA_GPU_SYNC_MARKER2 | OMEGA_GPU_SYNC_SEMAPHORE)); - EXPECT(r->marker == 0x11111111u); - EXPECT(r->marker2 == 0x22222222u); - EXPECT(r->semaphore[0] == 0x33333333u); - EXPECT(F.count[C_DIAG] == 1); -} - -/* Device closed, every buffer freed, nothing broke the fake's protocol, no block. */ -static void expect_released(const OmegaGpuResult *r) -{ - int role; - EXPECT(F.dev_open == 0); - for (role = 0; role < (int)OMEGA_GPU_BUF_ROLE_COUNT; role++) EXPECT(F.live[role] == 0); - EXPECT(F.violations == 0); - EXPECT(omega_gpu_engine_is_blocked() == 0); - EXPECT(r->retained == 0); -} - -/* Uncertain completion: nothing freed or closed, everything retained, process blocked. */ -static void expect_retained(const OmegaGpuResult *r) -{ - int role; - EXPECT(r->retained == 1); - EXPECT(r->cleanup_failed == 0); - EXPECT(F.count[C_FREE] == 0); - EXPECT(F.count[C_CLOSE] == 0); - EXPECT(F.dev_open == 1); - for (role = 0; role < (int)OMEGA_GPU_BUF_ROLE_COUNT; role++) EXPECT(F.live[role] == 1); - EXPECT(F.violations == 0); - EXPECT(omega_gpu_engine_is_blocked() == 1); -} - -static void expect_no_host_output(void) -{ - size_t i; - for (i = 0; i < N; i++) EXPECT(host_out[i] == 0xCCCCCCCCu); -} - -#define PRE_SUBMIT C_OPEN, C_CHANNEL, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, \ - C_COPY_IN, C_COPY_IN, C_COPY_IN, C_POISON, C_BUILD, C_SUBMIT -#define FREE5 C_FREE, C_FREE, C_FREE, C_FREE, C_FREE -#define LOGLEN(a) ((int)(sizeof (a) / sizeof (a)[0])) - -/* ---- cases -------------------------------------------------------------- */ - -static void case_success(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - size_t i; - int rc; - static const int want[] = { PRE_SUBMIT, C_MARKER, C_MARKER2, C_RELEASE, C_BARRIER, C_COPY_OUT, FREE5, C_CLOSE }; - - reset_all(); - make_job(&job); - rc = run(&job, &r); - - case_begin(); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - EXPECT(r.failure == OMEGA_GPU_ENGINE_OK); - EXPECT(r.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS); - EXPECT(r.failed_step == OMEGA_GPU_ENGINE_STEP_NONE); - EXPECT(r.wait == OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.wait_timeout_ms == 0 && r.waited_ms == 0); - EXPECT(r.drv_rc == 0 && r.err_no == 0 && r.drv_text[0] == '\0'); - EXPECT(r.sync_valid == 0 && r.marker == 0 && r.marker2 == 0 && r.semaphore[0] == 0); - EXPECT(r.retained == 0 && r.cleanup_failed == 0); - EXPECT(r.n_outputs == 1u); - EXPECT(r.output_unchanged_words[0] == 0); - for (i = 0; i < N; i++) EXPECT(host_out[i] == exp_out(i)); - for (i = N; i < N + 4u; i++) EXPECT(host_out[i] == 0xCCCCCCCCu); - EXPECT(F.count[C_DIAG] == 0); - expect_released(&r); - case_end("SUCCESS_FULL_RUN"); - - case_begin(); - expect_log(want, LOGLEN(want)); - case_end("CALL_ORDER_FULL_RUN"); - - case_begin(); - EXPECT(F.state_at[C_OPEN] == OMEGA_GPU_ENGINE_STATE_INITIAL); - EXPECT(F.state_at[C_POISON] == OMEGA_GPU_ENGINE_STATE_INITIAL); - EXPECT(F.state_at[C_BUILD] == OMEGA_GPU_ENGINE_STATE_INITIAL); - EXPECT(F.state_at[C_SUBMIT] == OMEGA_GPU_ENGINE_STATE_PREPARED); - EXPECT(F.state_at[C_MARKER] == OMEGA_GPU_ENGINE_STATE_SUBMITTED); - EXPECT(F.state_at[C_MARKER2] == OMEGA_GPU_ENGINE_STATE_SUBMITTED); - EXPECT(F.state_at[C_RELEASE] == OMEGA_GPU_ENGINE_STATE_SUBMITTED); - EXPECT(F.state_at[C_BARRIER] == OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE); - EXPECT(F.state_at[C_COPY_OUT] == OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE); - EXPECT(F.state_at[C_FREE] == OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED); - EXPECT(F.state_at[C_CLOSE] == OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED); - case_end("STATE_ADVANCES_STEP_BY_STEP"); - - case_begin(); - EXPECT(F.nalloc == 5); - for (i = 0; i < 5u; i++) EXPECT(F.alloc_roles[i] == (int)i); - EXPECT(F.alloc_bytes[OMEGA_GPU_BUF_SCRATCH] == 0u); - EXPECT(F.alloc_bytes[OMEGA_GPU_BUF_PROGRAM] == sizeof code); - EXPECT(F.alloc_bytes[OMEGA_GPU_BUF_INPUT_A] == sizeof ina); - EXPECT(F.alloc_bytes[OMEGA_GPU_BUF_INPUT_B] == sizeof inb); - EXPECT(F.alloc_bytes[OMEGA_GPU_BUF_OUTPUT] == N * sizeof(uint32_t)); - EXPECT(F.ncopy == 3); - EXPECT(F.copy_roles[0] == OMEGA_GPU_BUF_PROGRAM && F.copy_bytes[0] == sizeof code); - EXPECT(F.copy_roles[1] == OMEGA_GPU_BUF_INPUT_A && F.copy_bytes[1] == sizeof ina); - EXPECT(F.copy_roles[2] == OMEGA_GPU_BUF_INPUT_B && F.copy_bytes[2] == sizeof inb); - EXPECT(memcmp(F.dev_prog, code, sizeof code) == 0); - EXPECT(F.build_job == &job); - EXPECT(F.nfree == 5); - EXPECT(F.free_roles[0] == OMEGA_GPU_BUF_OUTPUT); - EXPECT(F.free_roles[1] == OMEGA_GPU_BUF_INPUT_B); - EXPECT(F.free_roles[2] == OMEGA_GPU_BUF_INPUT_A); - EXPECT(F.free_roles[3] == OMEGA_GPU_BUF_PROGRAM); - EXPECT(F.free_roles[4] == OMEGA_GPU_BUF_SCRATCH); - case_end("ROLES_BYTES_AND_REVERSE_FREE_ORDER"); - - case_begin(); - EXPECT(F.tmo[C_MARKER] == TMO_MARKER); - EXPECT(F.tmo[C_MARKER2] == TMO_MARKER2); - EXPECT(F.tmo[C_RELEASE] == TMO_RELEASE); - EXPECT(F.tmo[C_BARRIER] == TMO_VISIBILITY); - case_end("PER_STEP_TIMEOUTS_FROM_JOB"); - - case_begin(); - EXPECT(F.submit_seen == 1); - EXPECT(memcmp(F.seen_at_submit, poison, sizeof poison) == 0); - case_end("POISON_WRITTEN_BEFORE_SUBMIT"); -} - -static void case_no_c3(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - int rc; - static const int want[] = { PRE_SUBMIT, C_MARKER, C_RELEASE, C_BARRIER, C_COPY_OUT, FREE5, C_CLOSE }; - - reset_all(); - make_job(&job); - job.flags = OMEGA_GPU_ENGINE_FLAG_NO_C3; - job.timeouts.marker2_ms = 0; /* ignored with NO_C3 */ - rc = run(&job, &r); - case_begin(); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - EXPECT(r.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS); - EXPECT(F.count[C_MARKER2] == 0); - expect_log(want, LOGLEN(want)); - expect_released(&r); - case_end("NO_C3_SKIPS_MARKER2_ONLY"); -} - -static void case_open_channel_alloc_prepare(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - int rc; - - { - static const int want[] = { C_OPEN }; - reset_all(); make_job(&job); - inject(C_OPEN, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_DEVICE_OPEN, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_OPEN_DEVICE, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - expect_no_host_output(); - case_end("FAIL_DEVICE_OPEN"); - } - { - static const int want[] = { C_OPEN, C_CHANNEL, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_CHANNEL, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_CHANNEL_CREATE, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_CREATE_CHANNEL, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - expect_no_host_output(); - case_end("FAIL_CHANNEL_CREATE"); - } - { - /* the third allocation (input A) fails: scratch and program are freed, newest first */ - static const int want[] = { C_OPEN, C_CHANNEL, C_ALLOC, C_ALLOC, C_ALLOC, C_FREE, C_FREE, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_ALLOC, 3, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_ALLOC, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_ALLOC, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - EXPECT(F.nfree == 2); - EXPECT(F.free_roles[0] == OMEGA_GPU_BUF_PROGRAM && F.free_roles[1] == OMEGA_GPU_BUF_SCRATCH); - expect_released(&r); - expect_no_host_output(); - case_end("FAIL_ALLOC"); - } - { - /* the second copy-in (input A) fails */ - static const int want[] = { C_OPEN, C_CHANNEL, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, - C_COPY_IN, C_COPY_IN, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_COPY_IN, 2, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_PREPARE, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_COPY_IN, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - case_end("FAIL_PREPARE_COPY_IN"); - } - { - static const int want[] = { C_OPEN, C_CHANNEL, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, - C_COPY_IN, C_COPY_IN, C_COPY_IN, C_POISON, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_POISON, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_PREPARE, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_FILL_POISON, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - case_end("FAIL_PREPARE_FILL_POISON"); - } - { - static const int want[] = { C_OPEN, C_CHANNEL, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, C_ALLOC, - C_COPY_IN, C_COPY_IN, C_COPY_IN, C_POISON, C_BUILD, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_BUILD, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_PREPARE, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_BUILD, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - case_end("FAIL_PREPARE_BUILD"); - } -} - -static void case_submit_and_visibility(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - int rc; - - { - static const int want[] = { PRE_SUBMIT, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_SUBMIT, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_SUBMIT, OMEGA_GPU_ENGINE_STATE_PREPARED, - OMEGA_GPU_ENGINE_STEP_SUBMIT, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - EXPECT(F.submit_seen == 0); - expect_released(&r); /* SUBMIT is a known failure: cleaned up, not blocked */ - expect_no_host_output(); - case_end("FAIL_SUBMIT_IS_NOT_UNCERTAIN"); - } - { - static const int want[] = { PRE_SUBMIT, C_MARKER, C_MARKER2, C_RELEASE, C_BARRIER, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_BARRIER, 1, OMEGA_GPU_BACKEND_TIMEOUT, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_VISIBILITY_WAIT, OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE, - OMEGA_GPU_ENGINE_STEP_BARRIER, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); /* completion is known: cleaned up, not blocked */ - expect_no_host_output(); - case_end("FAIL_VISIBILITY_BARRIER"); - } - { - static const int want[] = { PRE_SUBMIT, C_MARKER, C_MARKER2, C_RELEASE, C_BARRIER, C_COPY_OUT, FREE5, C_CLOSE }; - reset_all(); make_job(&job); - inject(C_COPY_OUT, 1, -3, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_VISIBILITY_WAIT, OMEGA_GPU_ENGINE_STATE_GPU_COMPLETE, - OMEGA_GPU_ENGINE_STEP_COPY_OUT, OMEGA_GPU_ENGINE_WAIT_NONE); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_released(&r); - case_end("FAIL_VISIBILITY_COPY_OUT"); - } -} - -static void case_uncertain(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - OmegaGpuResult r2; - int rc; - int nlog_before; - int k; - - { - static const int want[] = { PRE_SUBMIT, C_MARKER }; - reset_all(); make_job(&job); - inject(C_MARKER, 1, OMEGA_GPU_BACKEND_TIMEOUT, 4321); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STATE_SUBMITTED, - OMEGA_GPU_ENGINE_STEP_WAIT_MARKER, OMEGA_GPU_ENGINE_WAIT_MARKER); - EXPECT(r.wait_timeout_ms == TMO_MARKER); - EXPECT(r.waited_ms == 4321u); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_retained(&r); - expect_no_host_output(); - case_end("UNCERTAIN_MARKER_TIMEOUT"); - - /* the next job in this process is refused with no backend call */ - nlog_before = F.nlog; - k = F.count[C_DIAG]; - rc = run(&job, &r2); - case_begin(); - expect_failure(rc, &r2, OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED, - OMEGA_GPU_ENGINE_STATE_INITIAL, OMEGA_GPU_ENGINE_STEP_BLOCKED, - OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(F.nlog == nlog_before); - EXPECT(F.count[C_DIAG] == k); - EXPECT(r2.retained == 0); - EXPECT(omega_gpu_engine_is_blocked() == 1); - case_end("UNCERTAIN_BLOCKS_NEXT_JOB_NO_BACKEND_CALL"); - - /* test reset clears it; a fresh fake then runs a good job */ - omega_gpu_engine_test_reset_block(); - case_begin(); - EXPECT(omega_gpu_engine_is_blocked() == 0); - reset_all(); - rc = run(&job, &r2); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - EXPECT(r2.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS); - case_end("UNCERTAIN_TEST_RESET_CLEARS_BLOCK"); - } - { - static const int want[] = { PRE_SUBMIT, C_MARKER, C_MARKER2 }; - reset_all(); make_job(&job); - inject(C_MARKER2, 1, OMEGA_GPU_BACKEND_UNKNOWN_STATE, 2500); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_COMPLETION_WAIT, OMEGA_GPU_ENGINE_STATE_SUBMITTED, - OMEGA_GPU_ENGINE_STEP_WAIT_MARKER2, OMEGA_GPU_ENGINE_WAIT_MARKER2); - EXPECT(r.wait_timeout_ms == TMO_MARKER2); - EXPECT(r.waited_ms == 2500u); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_retained(&r); - case_end("UNCERTAIN_MARKER2_UNKNOWN_STATE"); - omega_gpu_engine_test_reset_block(); - } - { - static const int want[] = { PRE_SUBMIT, C_MARKER, C_MARKER2, C_RELEASE }; - reset_all(); make_job(&job); - inject(C_RELEASE, 1, -5, 777); /* a driver fault, not a timeout */ - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_RELEASE_WAIT, OMEGA_GPU_ENGINE_STATE_SUBMITTED, - OMEGA_GPU_ENGINE_STEP_WAIT_RELEASE_SEMAPHORE, - OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE); - EXPECT(r.wait_timeout_ms == TMO_RELEASE); - EXPECT(r.waited_ms == 777u); - expect_passthrough(&r, EXPECT_ERRNO); - expect_log(want, LOGLEN(want)); - expect_retained(&r); - case_end("UNCERTAIN_RELEASE_DRIVER_FAULT"); - omega_gpu_engine_test_reset_block(); - } -} - -static void case_unchanged(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - size_t i; - int rc; - - /* the fake kernel writes nothing: all 16 words are still poison */ - reset_all(); make_job(&job); - F.klo = 0; F.khi = 0; - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE, - OMEGA_GPU_ENGINE_STEP_SCAN, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.n_outputs == 1u); - EXPECT(r.output_unchanged_words[0] == 16u); - EXPECT(r.err_no == 0); - EXPECT(r.drv_rc == DIAG_RC); /* observed words are kept on every failure */ - EXPECT(F.count[C_DIAG] == 1); - for (i = 0; i < N; i++) EXPECT(host_out[i] == poison[i]); - expect_released(&r); - case_end("UNCHANGED_NOTHING_WRITTEN"); - - /* only words 4..9 are written: 10 words are still poison */ - reset_all(); make_job(&job); - F.klo = 4; F.khi = 10; - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE, - OMEGA_GPU_ENGINE_STEP_SCAN, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.output_unchanged_words[0] == 10u); - for (i = 0; i < N; i++) EXPECT(host_out[i] == ((i >= 4u && i < 10u) ? exp_out(i) : poison[i])); - expect_released(&r); - case_end("UNCHANGED_PARTIAL_EXACT_COUNT"); - - /* all but the last word written: exactly 1 */ - reset_all(); make_job(&job); - F.klo = 0; F.khi = N - 1u; - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE, - OMEGA_GPU_ENGINE_STEP_SCAN, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.output_unchanged_words[0] == 1u); - EXPECT(host_out[N - 1u] == poison[N - 1u]); - expect_released(&r); - case_end("UNCHANGED_LAST_WORD_ONLY"); - - /* only the first word is unwritten: exactly 1 */ - reset_all(); make_job(&job); - F.klo = 1; F.khi = N; - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE, - OMEGA_GPU_ENGINE_STEP_SCAN, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.output_unchanged_words[0] == 1u); - EXPECT(host_out[0] == poison[0]); - expect_released(&r); - case_end("UNCHANGED_FIRST_WORD_ONLY"); - - /* the fake kernel writes everything: SUCCESS and a zero count */ - reset_all(); make_job(&job); - F.klo = 0; F.khi = N; - rc = run(&job, &r); - case_begin(); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - EXPECT(r.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS); - EXPECT(r.n_outputs == 1u && r.output_unchanged_words[0] == 0u); - case_end("UNCHANGED_ALL_WRITTEN_IS_SUCCESS"); - - /* a silent kernel is only caught because the engine wrote the poison to the - * device output before submit (the fake device starts with other garbage). */ - reset_all(); make_job(&job); - F.klo = 0; F.khi = 0; - rc = run(&job, &r); - case_begin(); - EXPECT(memcmp(F.seen_at_submit, poison, sizeof poison) == 0); - EXPECT(rc == OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED); - case_end("UNCHANGED_NEEDS_POISON_FILL"); -} - -static void case_cleanup_faults(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - size_t i; - int rc; - - /* free fails on the 2nd free after an otherwise good run: the rest still run */ - reset_all(); make_job(&job); - inject(C_FREE, 2, -9, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED, - OMEGA_GPU_ENGINE_STEP_FREE, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.cleanup_failed == 1); - EXPECT(r.retained == 0); - expect_passthrough(&r, EXPECT_ERRNO); - EXPECT(F.count[C_FREE] == 5); - EXPECT(F.count[C_CLOSE] == 1); - for (i = 0; i < N; i++) EXPECT(host_out[i] == exp_out(i)); - EXPECT(omega_gpu_engine_is_blocked() == 0); - case_end("CLEANUP_FREE_FAILS_AFTER_GOOD_RUN"); - - reset_all(); make_job(&job); - inject(C_CLOSE, 1, -9, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED, - OMEGA_GPU_ENGINE_STEP_CLOSE, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.cleanup_failed == 1); - expect_passthrough(&r, EXPECT_ERRNO); - EXPECT(F.count[C_FREE] == 5); - EXPECT(omega_gpu_engine_is_blocked() == 0); - case_end("CLEANUP_CLOSE_FAILS_AFTER_GOOD_RUN"); - - /* a free fault and then a close fault: the first (FREE) is kept */ - reset_all(); make_job(&job); - inject(C_FREE, 1, -9, 0); - inject(C_CLOSE, 1, -9, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_CLEANUP, OMEGA_GPU_ENGINE_STATE_OUTPUT_PRODUCED, - OMEGA_GPU_ENGINE_STEP_FREE, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.cleanup_failed == 1); - EXPECT(F.count[C_DIAG] == 1); - case_end("CLEANUP_FIRST_CLEANUP_FAULT_KEPT"); - - /* an earlier failure (submit) then a free fault: the first failure is kept */ - reset_all(); make_job(&job); - inject(C_SUBMIT, 1, -3, 0); - inject(C_FREE, 1, -9, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_SUBMIT, OMEGA_GPU_ENGINE_STATE_PREPARED, - OMEGA_GPU_ENGINE_STEP_SUBMIT, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.cleanup_failed == 1); - EXPECT(F.count[C_FREE] == 5); - EXPECT(F.count[C_CLOSE] == 1); - EXPECT(F.count[C_DIAG] == 1); - expect_passthrough(&r, EXPECT_ERRNO); - case_end("CLEANUP_FAULT_NEVER_OVERWRITES_FIRST_FAILURE"); - - /* unchanged output plus a close fault: still OUTPUT_UNCHANGED */ - reset_all(); make_job(&job); - F.klo = 0; F.khi = 0; - inject(C_CLOSE, 1, -9, 0); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED, OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE, - OMEGA_GPU_ENGINE_STEP_SCAN, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(r.cleanup_failed == 1); - EXPECT(r.output_unchanged_words[0] == 16u); - case_end("CLEANUP_FAULT_AFTER_UNCHANGED_KEEPS_UNCHANGED"); -} - -#define EXPECT_INVALID(edit) do { \ - OmegaGpuJob bj; \ - OmegaGpuResult br; \ - int brc; \ - reset_all(); make_job(&bj); \ - edit; \ - brc = run(&bj, &br); \ - expect_failure(brc, &br, OMEGA_GPU_ENGINE_INVALID_ARGS, OMEGA_GPU_ENGINE_STATE_INITIAL, \ - OMEGA_GPU_ENGINE_STEP_VALIDATE, OMEGA_GPU_ENGINE_WAIT_NONE); \ - EXPECT(F.nlog == 0 && F.count[C_DIAG] == 0); \ - EXPECT(br.drv_rc == 0 && br.err_no == 0 && br.retained == 0 && br.n_outputs == 0u); \ - EXPECT(omega_gpu_engine_is_blocked() == 0); \ - } while (0) - -static void case_invalid_args(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - int rc; - - case_begin(); - EXPECT_INVALID(bj.program = NULL); - EXPECT_INVALID(bj.program_len = 0); - case_end("INVALID_ARGS_PROGRAM"); - - case_begin(); - EXPECT_INVALID(bj.layout = OMEGA_GPU_LAYOUT_COUNT); - case_end("INVALID_ARGS_LAYOUT"); - - case_begin(); - /* zero elements with every length zeroed too: only the zero-count check rejects this */ - EXPECT_INVALID(bj.element_count = 0; bj.input_a_len = 0; bj.input_b_len = 0; bj.output_len = 0; bj.poison_count = 0); - EXPECT_INVALID(bj.element_count = 0); - case_end("INVALID_ARGS_ZERO_ELEMENTS"); - - case_begin(); - EXPECT_INVALID(bj.input_a = NULL); - EXPECT_INVALID(bj.input_a_len = sizeof ina - 4u); - EXPECT_INVALID(bj.input_b = NULL); - EXPECT_INVALID(bj.input_b_len = sizeof inb + 4u); - EXPECT_INVALID(bj.output = NULL); - EXPECT_INVALID(bj.output_len = N * sizeof(uint32_t) - 4u); - case_end("INVALID_ARGS_BUFFERS"); - - case_begin(); - EXPECT_INVALID(bj.output = (unsigned char *)host_out + 1); - case_end("INVALID_ARGS_OUTPUT_ALIGNMENT"); - - case_begin(); - EXPECT_INVALID(bj.poison = NULL); - EXPECT_INVALID(bj.poison_count = N - 1u); - EXPECT_INVALID(bj.poison_count = N + 1u); - case_end("INVALID_ARGS_POISON"); - - case_begin(); - EXPECT_INVALID(bj.flags = 0x2u); - case_end("INVALID_ARGS_UNKNOWN_FLAG"); - - case_begin(); - EXPECT_INVALID(bj.timeouts.marker_ms = 0); - case_end("INVALID_ARGS_ZERO_MARKER_TIMEOUT"); - case_begin(); - EXPECT_INVALID(bj.timeouts.release_semaphore_ms = 0); - case_end("INVALID_ARGS_ZERO_RELEASE_TIMEOUT"); - case_begin(); - EXPECT_INVALID(bj.timeouts.visibility_ms = 0); - case_end("INVALID_ARGS_ZERO_VISIBILITY_TIMEOUT"); - case_begin(); - EXPECT_INVALID(bj.timeouts.marker2_ms = 0); /* C3 on: marker2 needs a timeout */ - case_end("INVALID_ARGS_ZERO_MARKER2_TIMEOUT_WITH_C3"); - - case_begin(); - reset_all(); - memset(&r, 0x7f, sizeof r); - rc = omega_gpu_execute(NULL, &r); - EXPECT(rc == OMEGA_GPU_ENGINE_INVALID_ARGS); - EXPECT(r.failure == OMEGA_GPU_ENGINE_INVALID_ARGS && r.failed_step == OMEGA_GPU_ENGINE_STEP_VALIDATE); - EXPECT(r.last_state == OMEGA_GPU_ENGINE_STATE_INITIAL); - EXPECT(F.nlog == 0); - case_end("INVALID_ARGS_NULL_JOB"); - - case_begin(); - reset_all(); make_job(&job); - rc = omega_gpu_execute(&job, NULL); - EXPECT(rc == OMEGA_GPU_ENGINE_INVALID_ARGS); - EXPECT(F.nlog == 0); - case_end("INVALID_ARGS_NULL_RESULT"); -} - -static void case_block_and_backend(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - static OmegaGpuBackend be2; /* static: it stays the default backend until main clears it */ - int rc; - - /* forced block refuses even a malformed or NULL job, with no backend call */ - reset_all(); make_job(&job); - omega_gpu_engine_test_force_block(); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED, - OMEGA_GPU_ENGINE_STATE_INITIAL, OMEGA_GPU_ENGINE_STEP_BLOCKED, - OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(F.nlog == 0); - job.element_count = 0; - rc = run(&job, &r); - EXPECT(rc == OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED); - memset(&r, 0x7f, sizeof r); - rc = omega_gpu_execute(NULL, &r); - EXPECT(rc == OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED); - EXPECT(F.nlog == 0); - EXPECT(omega_gpu_engine_is_blocked() == 1); - case_end("BLOCKED_REFUSES_BEFORE_ANY_CHECK_OR_CALL"); - - omega_gpu_engine_test_reset_block(); - case_begin(); - EXPECT(omega_gpu_engine_is_blocked() == 0); - make_job(&job); - rc = run(&job, &r); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - case_end("BLOCK_RESET_ALLOWS_JOBS_AGAIN"); - - /* no backend set: the defined stub result */ - reset_all(); make_job(&job); - omega_gpu_engine_set_backend(NULL); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(F.nlog == 0); - case_end("NO_BACKEND_NOT_IMPLEMENTED"); - - /* an incomplete backend table is refused before any call: each callback in turn */ - case_begin(); -#define EXPECT_INCOMPLETE(field) do { \ - reset_all(); make_job(&job); \ - be2 = BE; be2.field = NULL; \ - omega_gpu_engine_set_backend(&be2); \ - rc = run(&job, &r); \ - expect_failure(rc, &r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STATE_INITIAL, \ - OMEGA_GPU_ENGINE_STEP_BACKEND_CHECK, OMEGA_GPU_ENGINE_WAIT_NONE); \ - EXPECT(F.nlog == 0); \ - } while (0) - EXPECT_INCOMPLETE(open_device); - EXPECT_INCOMPLETE(create_channel); - EXPECT_INCOMPLETE(alloc); - EXPECT_INCOMPLETE(copy_in); - EXPECT_INCOMPLETE(fill_poison); - EXPECT_INCOMPLETE(build); - EXPECT_INCOMPLETE(submit); - EXPECT_INCOMPLETE(wait_marker); - EXPECT_INCOMPLETE(wait_marker2); - EXPECT_INCOMPLETE(wait_release_semaphore); - EXPECT_INCOMPLETE(barrier); - EXPECT_INCOMPLETE(copy_out); - EXPECT_INCOMPLETE(diagnostics); - EXPECT_INCOMPLETE(free_buf); - EXPECT_INCOMPLETE(close); - case_end("BACKEND_TABLE_INCOMPLETE_REFUSED"); -} - -#ifdef OMEGA_GPU_NO_POSIX -/* Freestanding engine only: with no platform clock installed every job is - * refused before any backend call; installing one through the production - * setter makes the same job run. */ -static void case_platform_clock(void) -{ - OmegaGpuJob job; - OmegaGpuResult r; - int rc; - reset_all(); make_job(&job); - omega_gpu_engine_set_clock(NULL); - rc = run(&job, &r); - case_begin(); - expect_failure(rc, &r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STATE_INITIAL, - OMEGA_GPU_ENGINE_STEP_CLOCK_CHECK, OMEGA_GPU_ENGINE_WAIT_NONE); - EXPECT(F.nlog == 0); - EXPECT(strcmp(omega_gpu_engine_step_name(r.failed_step), "CLOCK_CHECK") == 0); - omega_gpu_engine_set_clock(fake_now); - rc = run(&job, &r); - EXPECT(rc == OMEGA_GPU_ENGINE_OK); - EXPECT(F.nlog > 0); - case_end("FREESTANDING_NO_CLOCK_REFUSED_BEFORE_ANY_CALL"); -} -#endif - -int main(void) -{ - omega_gpu_engine_test_set_clock(fake_now); - - case_success(); - case_no_c3(); - case_open_channel_alloc_prepare(); - case_submit_and_visibility(); - case_uncertain(); - case_unchanged(); - case_cleanup_faults(); - case_invalid_args(); - case_block_and_backend(); -#ifdef OMEGA_GPU_NO_POSIX - case_platform_clock(); -#endif - - omega_gpu_engine_set_backend(NULL); - omega_gpu_engine_test_reset_block(); - omega_gpu_engine_test_set_clock(NULL); - printf("SUMMARY passed=%d failed=%d\n", n_pass, n_fail); - return n_fail ? 1 : 0; -} diff --git a/tests/test_omega_gpu_engine_compile.c b/tests/test_omega_gpu_engine_compile.c deleted file mode 100644 index 332f6af38..000000000 --- a/tests/test_omega_gpu_engine_compile.c +++ /dev/null @@ -1,182 +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 compile check: the header and the A3a core compile, every enum name - * is distinct, argument and backend-table refusals return their defined results, the - * uncertain-completion block functions behave as specified, and a no-op backend reaches - * SUCCESS. */ -#include "omega_gpu_engine.h" -#include -#include - -static int bad; -#define CHECK(c) do { if (!(c)) { printf("[FAIL] line %d: %s\n", __LINE__, #c); bad++; } } while (0) - -static int f_ctx(void *c) { (void)c; return 0; } -static int f_alloc(void *c, int r, size_t n) { (void)c; (void)r; (void)n; return 0; } -static int f_in(void *c, int r, const void *s, size_t n) { (void)c; (void)r; (void)s; (void)n; return 0; } -static int f_poison(void *c, const uint32_t *w, size_t n) { (void)c; (void)w; (void)n; return 0; } -static int f_build(void *c, const OmegaGpuJob *j) { (void)c; (void)j; return 0; } -static int f_wait(void *c, uint64_t ms) { (void)c; (void)ms; return 0; } -static int f_out(void *c, void *d, size_t n) { (void)c; (void)d; (void)n; return 0; } -static void f_diag(void *c, OmegaGpuBackendDiag *d) { (void)c; (void)d; } -static int f_free(void *c, int r) { (void)c; (void)r; return 0; } - -static int all_distinct(const char *(*name)(int), int count) -{ - for (int i = 0; i < count; i++) { - CHECK(name(i) != NULL && strcmp(name(i), "UNKNOWN") != 0); - for (int j = i + 1; j < count; j++) CHECK(strcmp(name(i), name(j)) != 0); - } - return strcmp(name(-1), "UNKNOWN") == 0 && strcmp(name(count), "UNKNOWN") == 0; -} - -/* Expects the stub's full defined result for a job refused at `step` with `failure`. */ -static void expect_result(const OmegaGpuResult *r, int failure, int step) -{ - CHECK(r->failure == failure); - CHECK(r->failed_step == step); - CHECK(r->last_state == OMEGA_GPU_ENGINE_STATE_INITIAL); - CHECK(r->wait == OMEGA_GPU_ENGINE_WAIT_NONE); - CHECK(r->wait_timeout_ms == 0 && r->waited_ms == 0); - CHECK(r->drv_rc == 0 && r->err_no == 0 && r->drv_text[0] == '\0'); - CHECK(r->sync_valid == 0 && r->marker == 0 && r->marker2 == 0 && r->semaphore[0] == 0); - CHECK(r->retained == 0 && r->cleanup_failed == 0); - CHECK(r->n_outputs == 0 && r->output_unchanged_words[0] == 0); -} - -int main(void) -{ - CHECK(all_distinct(omega_gpu_engine_failure_name, OMEGA_GPU_ENGINE_FAILURE_COUNT)); - CHECK(all_distinct(omega_gpu_engine_state_name, OMEGA_GPU_ENGINE_STATE_COUNT)); - CHECK(all_distinct(omega_gpu_engine_wait_name, OMEGA_GPU_ENGINE_WAIT_COUNT)); - CHECK(all_distinct(omega_gpu_engine_step_name, OMEGA_GPU_ENGINE_STEP_COUNT)); - CHECK(OMEGA_GPU_ENGINE_OK == 0 && strcmp(omega_gpu_engine_failure_name(0), "OK") == 0); - CHECK(strcmp(omega_gpu_engine_failure_name(OMEGA_GPU_ENGINE_COMPLETION_WAIT), "COMPLETION_WAIT") == 0); - CHECK(strcmp(omega_gpu_engine_failure_name(OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED), - "UNCERTAIN_COMPLETION_BLOCKED") == 0); - CHECK(strcmp(omega_gpu_engine_state_name(OMEGA_GPU_ENGINE_STATE_INITIAL), "INITIAL") == 0); - CHECK(strcmp(omega_gpu_engine_state_name(OMEGA_GPU_ENGINE_STATE_SUCCESS), "SUCCESS") == 0); - CHECK(OMEGA_GPU_ENGINE_STATE_INITIAL == 0 && OMEGA_GPU_ENGINE_STATE_COUNT == 7); - CHECK(strcmp(omega_gpu_engine_wait_name(OMEGA_GPU_ENGINE_WAIT_RELEASE_SEMAPHORE), "RELEASE_SEMAPHORE") == 0); - CHECK(strcmp(omega_gpu_engine_step_name(OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED), "NOT_IMPLEMENTED") == 0); - - unsigned char code[4] = {0}; - uint32_t ina[4] = {0}, inb[4] = {0}, outw[4] = {0}, poison[4] = {1, 2, 3, 4}; - OmegaGpuJob job; - memset(&job, 0, sizeof job); - job.program = code; job.program_len = sizeof code; - job.layout = OMEGA_GPU_LAYOUT_VECTOR_1D; job.element_count = 4; - job.input_a = ina; job.input_a_len = sizeof ina; - job.input_b = inb; job.input_b_len = sizeof inb; - job.output = outw; job.output_len = sizeof outw; - job.poison = poison; job.poison_count = 4; - job.timeouts.marker_ms = 1; job.timeouts.release_semaphore_ms = 1; - job.timeouts.marker2_ms = 1; job.timeouts.visibility_ms = 1; - - OmegaGpuResult r; - - /* Not blocked at start; no backend set: the defined stub result. */ - omega_gpu_engine_test_reset_block(); - CHECK(omega_gpu_engine_is_blocked() == 0); - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_INTERNAL_INVARIANT); - expect_result(&r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED); - - /* A missing result pointer is refused and nothing is written. */ - CHECK(omega_gpu_execute(&job, NULL) == OMEGA_GPU_ENGINE_INVALID_ARGS); - - /* Counterexamples: each malformed job is INVALID_ARGS at VALIDATE, never NOT_IMPLEMENTED. */ - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(NULL, &r) == OMEGA_GPU_ENGINE_INVALID_ARGS); - expect_result(&r, OMEGA_GPU_ENGINE_INVALID_ARGS, OMEGA_GPU_ENGINE_STEP_VALIDATE); - - OmegaGpuJob bad_job; -#define EXPECT_INVALID(edit) do { bad_job = job; edit; memset(&r, 0x7f, sizeof r); \ - CHECK(omega_gpu_execute(&bad_job, &r) == OMEGA_GPU_ENGINE_INVALID_ARGS); \ - expect_result(&r, OMEGA_GPU_ENGINE_INVALID_ARGS, OMEGA_GPU_ENGINE_STEP_VALIDATE); } while (0) - EXPECT_INVALID(bad_job.program = NULL); - EXPECT_INVALID(bad_job.program_len = 0); - EXPECT_INVALID(bad_job.layout = OMEGA_GPU_LAYOUT_COUNT); - EXPECT_INVALID(bad_job.element_count = 0); - EXPECT_INVALID(bad_job.input_a = NULL); - EXPECT_INVALID(bad_job.input_a_len = sizeof ina - 4); - EXPECT_INVALID(bad_job.input_b = NULL); - EXPECT_INVALID(bad_job.input_b_len = sizeof inb + 4); - EXPECT_INVALID(bad_job.output = NULL); - EXPECT_INVALID(bad_job.output_len = sizeof outw - 4); - EXPECT_INVALID(bad_job.output = (unsigned char *)outw + 1); /* not 4-byte aligned */ - EXPECT_INVALID(bad_job.poison = NULL); - EXPECT_INVALID(bad_job.poison_count = 3); - EXPECT_INVALID(bad_job.flags = 0x2u); /* unknown flag */ - EXPECT_INVALID(bad_job.timeouts.marker_ms = 0); - EXPECT_INVALID(bad_job.timeouts.release_semaphore_ms = 0); - EXPECT_INVALID(bad_job.timeouts.visibility_ms = 0); - EXPECT_INVALID(bad_job.timeouts.marker2_ms = 0); /* C3 on, so marker2 needs a timeout */ - - /* With NO_C3 a zero marker2 timeout is allowed. */ - bad_job = job; bad_job.flags = OMEGA_GPU_ENGINE_FLAG_NO_C3; bad_job.timeouts.marker2_ms = 0; - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&bad_job, &r) == OMEGA_GPU_ENGINE_INTERNAL_INVARIANT); - expect_result(&r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED); - - /* Backend table: incomplete is refused, complete runs the core to SUCCESS, NULL clears. */ - OmegaGpuBackend be = { - .ctx = NULL, .open_device = f_ctx, .create_channel = f_ctx, .alloc = f_alloc, - .copy_in = f_in, .fill_poison = f_poison, .build = f_build, .submit = f_ctx, - .wait_marker = f_wait, .wait_marker2 = f_wait, .wait_release_semaphore = f_wait, - .barrier = f_wait, .copy_out = f_out, .diagnostics = f_diag, .free_buf = f_free, - .close = f_ctx, - }; - omega_gpu_engine_set_backend(&be); - /* The A3a core now runs the whole state machine: the all-success no-op backend - * (copy-out leaves the output zeros, which differ from the poison words 1..4) - * reaches SUCCESS. The full state machine is tested in tests/test_omega_gpu_engine.c. */ - omega_gpu_engine_test_set_clock(NULL); /* NULL keeps the default clock */ - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_OK); - CHECK(r.failure == OMEGA_GPU_ENGINE_OK && r.failed_step == OMEGA_GPU_ENGINE_STEP_NONE); - CHECK(r.last_state == OMEGA_GPU_ENGINE_STATE_SUCCESS && r.wait == OMEGA_GPU_ENGINE_WAIT_NONE); - CHECK(r.retained == 0 && r.cleanup_failed == 0); - CHECK(r.n_outputs == 1u && r.output_unchanged_words[0] == 0); - be.close = NULL; - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_INTERNAL_INVARIANT); - expect_result(&r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_BACKEND_CHECK); - omega_gpu_engine_set_backend(NULL); - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_INTERNAL_INVARIANT); - expect_result(&r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED); - - /* Block: forced block refuses every job, even a malformed one, until reset. */ - omega_gpu_engine_test_force_block(); - CHECK(omega_gpu_engine_is_blocked() == 1); - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED); - expect_result(&r, OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED, OMEGA_GPU_ENGINE_STEP_BLOCKED); - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(NULL, &r) == OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED); - expect_result(&r, OMEGA_GPU_ENGINE_UNCERTAIN_COMPLETION_BLOCKED, OMEGA_GPU_ENGINE_STEP_BLOCKED); - CHECK(omega_gpu_engine_is_blocked() == 1); /* a refusal does not clear the block */ - omega_gpu_engine_test_reset_block(); - CHECK(omega_gpu_engine_is_blocked() == 0); - memset(&r, 0x7f, sizeof r); - CHECK(omega_gpu_execute(&job, &r) == OMEGA_GPU_ENGINE_INTERNAL_INVARIANT); - expect_result(&r, OMEGA_GPU_ENGINE_INTERNAL_INVARIANT, OMEGA_GPU_ENGINE_STEP_NOT_IMPLEMENTED); - - printf("SUMMARY failed=%d\n", bad); - return bad ? 1 : 0; -} diff --git a/tests/test_omega_gpu_engine_gb10.c b/tests/test_omega_gpu_engine_gb10.c deleted file mode 100644 index 6d7acdb62..000000000 --- a/tests/test_omega_gpu_engine_gb10.c +++ /dev/null @@ -1,184 +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. - */ - -/* - * Phase B only: needs the GB10, queen's go, quiet flag via chip_run; never run in Phase A. - * - * Chip test of the Omega GPU Engine (docs/numeric/OMEGA_GPU_ENGINE.md), cut A3b2. - * Phase A only COMPILES it (make test-gpu-engine-gb10-compile). It was written - * against the real API (src/omega_gpu_engine.h, src/omega_blackwell_submit.h) and - * never compiled or executed by its author. It is a fresh rewrite: the first-cut - * test by GPT-6 Astra (commit 21392ee on fix/omega-gpu-engine-first-cut) used an - * older API, so it served as the outline only. - * - * What it does with --chip on the GB10, through tools/chip_run.sh and - * tools/manifests/gpu_engine.chiprun: - * 1. Runs omega_blackwell_execute_vector (engine core + Blackwell backend + the - * real driver) for element counts 1, 63, 64, 65, 4096 and 65537, ten times - * each. One extra pattern per size uses a[i] = 0xdeadbeef, b[i] = 0 (a sum - * that equals the old constant poison word, which must not fool the engine). - * 2. Negative control: the vector program with its one store instruction - * replaced by the instruction after it (an EXIT), so no lane writes. The - * engine must report OUTPUT_UNCHANGED for all 65 words, after the run - * completed and the output became visible, with nothing retained and no - * cleanup failure. The offsets are the fixture locations in - * src/omega_blackwell_encoder.c (0x120 store, 0x130 exit). - * Verdict lines (the only lines chip_run reads): "GPU_ENGINE: PASS" or - * "GPU_ENGINE: FAIL"; without --chip it prints "GPU_ENGINE: NOT_RUN ..." and - * exits 2. An uncertain completion blocks the process by design: this test then - * parks instead of exiting, because exiting would close the device under a GPU - * that may still be running. - */ -#include "omega_gpu_engine.h" -#include "omega_blackwell_engine.h" -#include "omega_blackwell_submit.h" -#include "omega_blackwell_encoder.h" -#include "omega_blackwell_realize.h" -#include "omega_vector.h" - -#include -#include -#include -#include -#include - -#define REPEATS 10u - -/* An uncertain completion leaves the context and the device memory alive on - * purpose. Never exit in that state. */ -static void park_if_blocked(void) -{ - if (!omega_gpu_engine_is_blocked()) return; - fprintf(stderr, "GPU_ENGINE_BLOCKED uncertain completion, parking (do not close the device)\n"); - puts("GPU_ENGINE: FAIL"); - fflush(stdout); - for (;;) pause(); -} - -static int run_size(uint32_t n, int deadbeef) -{ - OmegaVectorSpec spec; - OmegaBlackwellRealization real; - OmegaBlackwellVectorExecution info; - uint32_t *a = (uint32_t *)malloc((size_t)n * 4u); - uint32_t *b = (uint32_t *)malloc((size_t)n * 4u); - uint32_t *c = (uint32_t *)malloc((size_t)n * 4u); - uint32_t i; - unsigned rep; - int ok = (a && b && c); - - memset(&spec, 0, sizeof spec); - memset(&real, 0, sizeof real); - real.sm_architecture = OMEGA_BW_SM_ARCH_121; - if (ok && omega_vector_spec_init(&spec, "engine_chip", n) != 0) ok = 0; - for (i = 0; ok && i < n; i++) { - a[i] = deadbeef ? 0xdeadbeefu : (uint32_t)(i * 2654435761u + 1u); - b[i] = deadbeef ? 0u : (uint32_t)(i * 40503u + 7u); - } - for (rep = 0; ok && rep < REPEATS; rep++) { - int rc; - memset(c, 0, (size_t)n * 4u); - memset(&info, 0, sizeof info); - rc = omega_blackwell_execute_vector(&spec, &real, a, b, c, &info); - park_if_blocked(); - if (rc != 0 || !info.parity_verified) { - fprintf(stderr, "vector run failed n=%u deadbeef=%d repeat=%u rc=%d\n", n, deadbeef, rep, rc); - ok = 0; - } - } - free(a); - free(b); - free(c); - return ok; -} - -static int no_store_control(void) -{ - uint8_t code[OMEGA_BW_VECADD_CODE_SIZE]; - size_t code_bytes = 0; - uint32_t a[65], b[65], out[65], poison[65]; - OmegaGpuJob job; - OmegaGpuResult res; - uint32_t i; - int rc; - - if (omega_blackwell_verify_encoder_fixtures() != 0) return 0; - if (omega_blackwell_encode_vecadd(code, sizeof code, &code_bytes) != 0 || code_bytes < 0x140u) return 0; - /* Replace only the store with the exit that follows it. */ - memcpy(code + 0x120, code + 0x130, OMEGA_BW_INSTRUCTION_BYTES); - for (i = 0; i < 65u; i++) { - a[i] = i + 1u; - b[i] = 3u * i; - poison[i] = ~(a[i] + b[i]); - } - memset(out, 0, sizeof out); - memset(&job, 0, sizeof job); - job.program = code; - job.program_len = code_bytes; - job.layout = OMEGA_GPU_LAYOUT_VECTOR_1D; - job.element_count = 65u; - job.input_a = a; - job.input_a_len = sizeof a; - job.input_b = b; - job.input_b_len = sizeof b; - job.output = out; - job.output_len = sizeof out; - job.poison = poison; - job.poison_count = 65u; - job.timeouts.marker_ms = 5000; - job.timeouts.release_semaphore_ms = 5000; - job.timeouts.marker2_ms = 5000; - job.timeouts.visibility_ms = 5000; - job.flags = 0; - - omega_gpu_engine_set_backend(omega_blackwell_engine_backend()); - rc = omega_gpu_execute(&job, &res); - park_if_blocked(); - if (rc != OMEGA_GPU_ENGINE_OUTPUT_UNCHANGED || res.last_state != OMEGA_GPU_ENGINE_STATE_OUTPUT_VISIBLE || - res.n_outputs != 1u || res.output_unchanged_words[0] != 65u || res.cleanup_failed != 0 || - res.retained != 0) { - fprintf(stderr, "no-store control failed rc=%d state=%d unchanged=%llu cleanup_failed=%d retained=%d\n", - rc, res.last_state, (unsigned long long)res.output_unchanged_words[0], - res.cleanup_failed, res.retained); - return 0; - } - return 1; -} - -int main(int argc, char **argv) -{ - static const uint32_t sizes[] = {1u, 63u, 64u, 65u, 4096u, 65537u}; - size_t s; - unsigned runs = 0; - int failed = 0; - - if (argc < 2 || strcmp(argv[1], "--chip") != 0) { - puts("GPU_ENGINE: NOT_RUN (pass --chip; needs the GB10, via tools/chip_run.sh)"); - return 2; - } - for (s = 0; !failed && s < sizeof sizes / sizeof sizes[0]; s++) { - if (!run_size(sizes[s], 0) || !run_size(sizes[s], 1)) failed = 1; - else runs += 2u * REPEATS; - } - if (!failed && !no_store_control()) failed = 1; - if (failed) { - puts("GPU_ENGINE: FAIL"); - return 1; - } - printf("GPU_ENGINE_CASES vector_runs=%u no_store_control=detected\n", runs); - puts("GPU_ENGINE: PASS"); - return 0; -} diff --git a/tests/test_omega_gpu_platform.c b/tests/test_omega_gpu_platform.c deleted file mode 100644 index 38ff95b81..000000000 --- a/tests/test_omega_gpu_platform.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. - */ - -/* Contract tests for src/omega_gpu_platform.h (native v1 P07 cut A). Host - * program, links the FREESTANDING object of src/omega_gpu_platform.c. Opens - * no device. Every rule in the header comment has a case here, and every - * refusal name is reached at least once. */ -#include "omega_gpu_platform.h" - -#include -#include - -static int n_pass, n_fail, case_ok; -#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) -static void case_begin(void) { case_ok = 1; } -static void case_end(const char *id) -{ - if (case_ok) n_pass++; else n_fail++; - printf("%s %s\n", case_ok ? "PASS" : "FAIL", id); -} - -/* ---- a complete fake platform (no device behind it) ---------------------- */ -static uint64_t f_now(void *c) { (void)c; return 1u; } -static int f_wait(void *c, uint64_t ms) { (void)c; (void)ms; return 0; } -static int f_lock(void *c, uint32_t id) { (void)c; (void)id; return 0; } -static int f_rd(void *c, OmegaGpuDeviceHandle d, uint32_t r, uint64_t o, uint32_t *v) { (void)c; (void)d; (void)r; (void)o; *v = 0; return 0; } -static int f_wr(void *c, OmegaGpuDeviceHandle d, uint32_t r, uint64_t o, uint32_t v) { (void)c; (void)d; (void)r; (void)o; (void)v; return 0; } -static int f_alloc(void *c, OmegaGpuDeviceHandle d, const OmegaGpuBufferDesc *desc, OmegaGpuBufferHandle *o, - OmegaCpuView *cpu, OmegaGpuVa *g, OmegaGpuBusAddr *b) -{ (void)c; (void)d; (void)desc; (void)o; (void)cpu; (void)g; (void)b; return 0; } -static int f_free(void *c, OmegaGpuBufferHandle b) { (void)c; (void)b; return 0; } -static int f_sync(void *c, OmegaGpuBufferHandle b, uint64_t o, uint64_t l) { (void)c; (void)b; (void)o; (void)l; return 0; } -static int f_word(void *c, OmegaGpuBufferHandle b, uint64_t o, uint32_t e, uint64_t t, uint32_t *v) { (void)c; (void)b; (void)o; (void)e; (void)t; *v = 0; return 0; } -static int f_irq(void *c, OmegaGpuDeviceHandle d, uint64_t t) { (void)c; (void)d; (void)t; return 0; } - -static void full_platform(OmegaGpuPlatform *p) -{ - memset(p, 0, sizeof *p); - p->time_now_ms = f_now; p->wait_ms = f_wait; p->lock = f_lock; p->unlock = f_lock; - p->mmio_read32 = f_rd; p->mmio_write32 = f_wr; p->dma_alloc = f_alloc; p->dma_free = f_free; - p->sync_cpu_to_gpu = f_sync; p->sync_gpu_to_cpu = f_sync; p->poll_word = f_word; -} - -static void caps_v1(OmegaGpuPlatformCaps *c) -{ - memset(c, 0, sizeof *c); - c->abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR; c->abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR; - c->services = OMEGA_GPU_SVC_REQUIRED_V1; - c->max_devices = 1; c->max_buffers = 8; c->max_queues = 2; c->max_inflight = 1; - c->max_buffer_bytes = 1u << 20; c->max_total_bytes = 4u << 20; -} - -static void case_names(void) -{ - int i, j; - case_begin(); - for (i = 0; i < (int)OMEGA_GPU_PLAT_REFUSAL_COUNT; i++) { - EXPECT(strcmp(omega_gpu_platform_refusal_name(i), "UNKNOWN") != 0); - for (j = 0; j < i; j++) EXPECT(strcmp(omega_gpu_platform_refusal_name(i), omega_gpu_platform_refusal_name(j)) != 0); - } - EXPECT(strcmp(omega_gpu_platform_refusal_name(-1), "UNKNOWN") == 0); - EXPECT(strcmp(omega_gpu_platform_refusal_name(OMEGA_GPU_PLAT_REFUSAL_COUNT), "UNKNOWN") == 0); - EXPECT(strcmp(omega_gpu_platform_refusal_name(0), "OK") == 0); - case_end("REFUSAL_NAMES_DISTINCT"); -} - -static void case_negotiate(void) -{ - OmegaGpuPlatformCaps p, r; - case_begin(); - caps_v1(&p); caps_v1(&r); - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_platform_negotiate(NULL, &r) == OMEGA_GPU_PLAT_REFUSED_ARGS); - EXPECT(omega_gpu_platform_negotiate(&p, NULL) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* a newer provided minor is fine; an older one or another major is refused */ - p.abi_minor = r.abi_minor + 1u; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_OK); - caps_v1(&p); r.abi_minor = p.abi_minor + 1u; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_ABI); - caps_v1(&r); p.abi_major = r.abi_major + 1u; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_ABI); - /* a required service the platform lacks is refused, never emulated */ - caps_v1(&p); r.services |= OMEGA_GPU_SVC_IRQ; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); - p.services |= OMEGA_GPU_SVC_IRQ; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_OK); - /* unknown service bits are malformed */ - p.services |= 1u << 12; /* the first bit past ABI 1.1 */ - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* every limit */ - caps_v1(&p); caps_v1(&r); r.max_devices = 2; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - caps_v1(&r); r.max_buffers = 9; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - caps_v1(&r); r.max_queues = 3; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - caps_v1(&r); r.max_inflight = 2; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - caps_v1(&r); r.max_buffer_bytes = (1u << 20) + 1u; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - caps_v1(&r); r.max_total_bytes = (4u << 20) + 1u; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - /* asking for less is fine */ - caps_v1(&r); r.max_buffers = 1; r.max_total_bytes = 1; - EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_OK); - case_end("NEGOTIATE_ABI_SERVICES_LIMITS"); -} - -static void case_check_table(void) -{ - OmegaGpuPlatform p; - OmegaGpuPlatformCaps c; - case_begin(); - full_platform(&p); caps_v1(&c); - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_platform_check(NULL, &c) == OMEGA_GPU_PLAT_REFUSED_ARGS); - EXPECT(omega_gpu_platform_check(&p, NULL) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* the v1 required set is mandatory */ - c.services = OMEGA_GPU_SVC_REQUIRED_V1 & ~OMEGA_GPU_SVC_SYNC; - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); - /* a claimed service with a missing function, one per service */ - caps_v1(&c); - full_platform(&p); p.time_now_ms = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.wait_ms = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.unlock = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.mmio_write32 = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.dma_free = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.sync_gpu_to_cpu = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.poll_word = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - /* IRQ: claimed needs irq_wait; polling-only platforms do not claim it and must not carry one */ - full_platform(&p); c.services |= OMEGA_GPU_SVC_IRQ; - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - p.irq_wait = f_irq; - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_OK); - caps_v1(&c); - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_ARGS); /* undeclared function = hidden path */ - case_end("SERVICE_TABLE_MATCHES_CLAIMS_NO_HIDDEN_FALLBACK"); -} - - -/* ABI 1.1: the services the persistent GPU session requires (OMEGA_GPU_SVC_REQUIRED_SESSION). */ -static int f_dopen(void *c, uint32_t o, OmegaGpuDeviceHandle *d) { (void)c; (void)o; d->index = 0; d->generation = 1; return 0; } -static int f_dclose(void *c, OmegaGpuDeviceHandle d) { (void)c; (void)d; return 0; } -static const char *f_diag(void *c) { (void)c; return ""; } -static int f_qopen(void *c, OmegaGpuDeviceHandle d, OmegaGpuBufferHandle r, OmegaGpuQueueHandle *q) { (void)c; (void)d; (void)r; q->index = 0; q->generation = 1; return 0; } -static int f_qclose(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; return 0; } -static int f_qsubmit(void *c, OmegaGpuQueueHandle q, const uint32_t *w, uint32_t n) { (void)c; (void)q; (void)w; (void)n; return 0; } -static int f_qretire(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; return 0; } -static uint64_t f_ns(void *c) { (void)c; return 1u; } -static void *f_halloc(void *c, size_t b) { (void)c; (void)b; return NULL; } -static void f_hfree(void *c, void *p) { (void)c; (void)p; } -static void session_platform(OmegaGpuPlatform *p, OmegaGpuPlatformCaps *c) -{ - full_platform(p); - p->mmio_read32 = NULL; p->mmio_write32 = NULL; /* the session needs no MMIO: a platform without it is fine */ - p->device_open = f_dopen; p->device_close = f_dclose; p->diag_text = f_diag; - p->queue_open = f_qopen; p->queue_close = f_qclose; p->queue_submit = f_qsubmit; p->queue_retire = f_qretire; - p->time_now_ns = f_ns; p->host_alloc = f_halloc; p->host_free = f_hfree; - caps_v1(c); - c->services = OMEGA_GPU_SVC_REQUIRED_SESSION; -} - -static void case_session_services(void) -{ - OmegaGpuPlatform p; - OmegaGpuPlatformCaps c; - case_begin(); - EXPECT(OMEGA_GPU_PLATFORM_ABI_MINOR == 2u); /* 1.2: caps.submit_prefix_words (#459) */ - EXPECT(!(OMEGA_GPU_SVC_REQUIRED_SESSION & (OMEGA_GPU_SVC_IRQ | OMEGA_GPU_SVC_MMIO))); - session_platform(&p, &c); - EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_OK); - /* the v1 check still demands MMIO, so a session-only platform is not a v1 device-owner platform */ - EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); - EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_ALL + 1u) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* each new service: a missing function is refused */ - session_platform(&p, &c); p.device_close = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - session_platform(&p, &c); p.diag_text = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - session_platform(&p, &c); p.queue_retire = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - session_platform(&p, &c); p.time_now_ns = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - session_platform(&p, &c); p.host_free = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - /* a required service not claimed is missing; a function of an unclaimed service is a hidden path */ - session_platform(&p, &c); c.services &= ~OMEGA_GPU_SVC_QUEUE; - EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); - EXPECT(omega_gpu_platform_check_for(&p, &c, c.services) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* polling never claims IRQ: a session platform with an irq_wait it does not claim is refused */ - session_platform(&p, &c); p.irq_wait = f_irq; - EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_ARGS); - EXPECT(omega_gpu_platform_negotiate(&c, &c) == OMEGA_GPU_PLAT_OK); - EXPECT(OMEGA_GPU_POLL_TIMED_OUT >= (int)OMEGA_GPU_PLAT_REFUSAL_COUNT); - case_end("SESSION_SERVICES_ABI_1_1_POLLING_NOT_IRQ"); -} -static void case_buffers(void) -{ - OmegaGpuBufferDesc d; - OmegaGpuPlatformCaps c; - case_begin(); - caps_v1(&c); - memset(&d, 0, sizeof d); - d.kind = OMEGA_GPU_HANDLE_BUF_DATA; d.rights = OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ; d.bytes = 4096; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_platform_check_buffer(NULL, &c) == OMEGA_GPU_PLAT_REFUSED_ARGS); - EXPECT(omega_gpu_platform_check_buffer(&d, NULL) == OMEGA_GPU_PLAT_REFUSED_ARGS); - d.kind = OMEGA_GPU_HANDLE_QUEUE; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_KIND); - d.kind = OMEGA_GPU_HANDLE_BUF_DATA; - d.bytes = 0; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH); - d.bytes = (1u << 20) + 1u; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - d.bytes = 4096; - d.align = 48; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_ARGS); - d.align = 64; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_OK); - d.gpu_cache = 7; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_ARGS); - d.gpu_cache = OMEGA_GPU_CACHE_GPU_CACHED; - d.rights = 0; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - d.rights = 1u << 7; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - /* exec only on code */ - d.rights = OMEGA_GPU_RIGHT_GPU_EXEC | OMEGA_GPU_RIGHT_CPU_WRITE; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - d.kind = OMEGA_GPU_HANDLE_BUF_CODE; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_OK); - d.rights |= OMEGA_GPU_RIGHT_GPU_WRITE; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - d.rights = OMEGA_GPU_RIGHT_CPU_WRITE; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); /* code without exec */ - d.rights = OMEGA_GPU_RIGHT_GPU_EXEC; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); /* nobody can fill it */ - /* queue: CPU writes, device reads */ - d.kind = OMEGA_GPU_HANDLE_BUF_QUEUE; d.rights = OMEGA_GPU_RIGHT_CPU_WRITE; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - d.rights |= OMEGA_GPU_RIGHT_GPU_READ; EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_OK); - /* host-polled: CPU reads, GPU writes, GPU-uncached (the E1 rule) */ - d.kind = OMEGA_GPU_HANDLE_BUF_DATA; - d.rights = OMEGA_GPU_RIGHT_HOST_POLLED | OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_GPU_WRITE; - d.gpu_cache = OMEGA_GPU_CACHE_GPU_CACHED; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY); - d.gpu_cache = OMEGA_GPU_CACHE_GPU_UNCACHED; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_OK); - d.rights = OMEGA_GPU_RIGHT_HOST_POLLED | OMEGA_GPU_RIGHT_CPU_READ; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - d.kind = OMEGA_GPU_HANDLE_BUF_CODE; d.rights = OMEGA_GPU_RIGHT_HOST_POLLED | OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_EXEC | OMEGA_GPU_RIGHT_CPU_READ; - EXPECT(omega_gpu_platform_check_buffer(&d, &c) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); - case_end("BUFFER_DESC_KIND_LENGTH_RIGHTS_CACHE"); -} - -static void case_handles(void) -{ - static OmegaGpuHandleTable t; - uint32_t i0, g0, i1, g1, i2, g2, i, g; - uint32_t n; - case_begin(); - omega_gpu_handles_init(&t); - EXPECT(t.nlive == 0 && t.total_bytes == 0); - EXPECT(omega_gpu_handles_open(NULL, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &i0, &g0) == OMEGA_GPU_PLAT_REFUSED_ARGS); - EXPECT(omega_gpu_handles_open(&t, 0, 0, 1, 0, &i0, &g0) == OMEGA_GPU_PLAT_REFUSED_BAD_KIND); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_KIND_COUNT, 0, 1, 0, &i0, &g0) == OMEGA_GPU_PLAT_REFUSED_BAD_KIND); - /* one device allowed */ - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &i0, &g0) == OMEGA_GPU_PLAT_OK); - EXPECT(g0 != 0u); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &i1, &g1) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - /* buffers account bytes against the total */ - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 3000, 8, 4096, &i1, &g1) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 2000, 8, 4096, &i2, &g2) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 5000, 8, 4096, &i2, &g2) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_CODE, 1096, 8, 4096, &i2, &g2) == OMEGA_GPU_PLAT_OK); - EXPECT(t.nlive == 3 && t.total_bytes == 4096); - /* checks: kind, index, generation */ - EXPECT(omega_gpu_handles_check(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_check(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_CODE) == OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE); - EXPECT(omega_gpu_handles_check(&t, OMEGA_GPU_HANDLE_SLOTS, 1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE); - EXPECT(omega_gpu_handles_check(&t, i1, 0, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE); - EXPECT(omega_gpu_handles_check(&t, i1, g1 + 1u, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(omega_gpu_handles_check(&t, 40, 1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); /* never opened */ - EXPECT(omega_gpu_handles_check(NULL, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_ARGS); - /* close: frees bytes, the old handle goes stale, double close refused, slot reuse gets a new generation */ - EXPECT(omega_gpu_handles_close(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_CODE) == OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE); - EXPECT(omega_gpu_handles_close(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_OK); - EXPECT(t.nlive == 2 && t.total_bytes == 1096); - EXPECT(omega_gpu_handles_check(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(omega_gpu_handles_close(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 3000, 8, 4096, &i, &g) == OMEGA_GPU_PLAT_OK); - EXPECT(i == i1 && g == g1 + 1u); - EXPECT(omega_gpu_handles_check(&t, i1, g1, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(omega_gpu_handles_check(&t, i, g, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_OK); - /* per-kind slot limit counts only live handles of that kind */ - for (n = 0; n < 2; n++) EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_QUEUE, 0, 2, 0, &i2, &g2) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_QUEUE, 0, 2, 0, &i2, &g2) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - EXPECT(omega_gpu_handles_close(&t, i2, g2, OMEGA_GPU_HANDLE_QUEUE) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_QUEUE, 0, 2, 0, &i2, &g2) == OMEGA_GPU_PLAT_OK); - /* table capacity */ - omega_gpu_handles_init(&t); - for (n = 0; n < OMEGA_GPU_HANDLE_SLOTS; n++) - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, OMEGA_GPU_HANDLE_SLOTS + 1u, OMEGA_GPU_HANDLE_SLOTS + 1u, &i, &g) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, OMEGA_GPU_HANDLE_SLOTS + 1u, OMEGA_GPU_HANDLE_SLOTS + 1u, &i, &g) == OMEGA_GPU_PLAT_REFUSED_LIMIT); - /* a wrapped generation retires the slot instead of reissuing generation 0 */ - omega_gpu_handles_init(&t); - t.generation[0] = 0xFFFFFFFFu; - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, 8, 8, &i, &g) == OMEGA_GPU_PLAT_OK); - EXPECT(i == 0 && g == 0xFFFFFFFFu); - EXPECT(omega_gpu_handles_close(&t, 0, g, OMEGA_GPU_HANDLE_BUF_DATA) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, 8, 8, &i, &g) == OMEGA_GPU_PLAT_OK); - EXPECT(i == 1 && g == 1u); - case_end("HANDLES_TYPED_GENERATIONED_LIMITED"); -} - -static void case_sizes(void) -{ - /* No Linux fd, no raw pointer and no physical address can be smuggled - * through a handle: it is two 32-bit fields, and the address types are - * distinct structs that do not convert into each other. */ - case_begin(); - EXPECT(sizeof(OmegaGpuDeviceHandle) == 8u); - EXPECT(sizeof(OmegaGpuBufferHandle) == 8u); - EXPECT(sizeof(OmegaGpuQueueHandle) == 8u); - EXPECT(sizeof(OmegaGpuVa) == 8u && sizeof(OmegaGpuBusAddr) == 8u); - EXPECT(sizeof(OmegaCpuView) == sizeof(void *) + sizeof(size_t)); - EXPECT((OMEGA_GPU_SVC_REQUIRED_V1 | OMEGA_GPU_SVC_IRQ) == 0xFFu); /* the v1 bits; 1.1 adds 8..11 */ - case_end("HANDLE_AND_ADDRESS_SHAPES"); -} - -int main(void) -{ - case_names(); - case_negotiate(); - case_check_table(); - case_session_services(); - case_buffers(); - case_handles(); - case_sizes(); - printf("SUMMARY passed=%d failed=%d\n", n_pass, n_fail); - return n_fail ? 1 : 0; -} diff --git a/tests/test_omega_gpu_platform_linux.c b/tests/test_omega_gpu_platform_linux.c deleted file mode 100644 index eb9b9be4c..000000000 --- a/tests/test_omega_gpu_platform_linux.c +++ /dev/null @@ -1,288 +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. - */ - -/* test_omega_gpu_platform_linux: the Linux REFERENCE platform (src/omega_gpu_platform_linux.c, reference only) on the - * simulated driver (tests/fake_m16_native.c). Host program, hosted build, opens no device. - * - * What it checks: the reference claims exactly the session service set (no MMIO, no IRQ: polling is never claimed as - * an interrupt) and passes the contract check; the hosted session installs it by default; the session makes the same - * driver calls in the same order as before P07 cut C (channel, then the four session buffers through - * nvrm_alloc_gpu_uncached, one submit with the C3 tail, both marker waits, close); the reference refuses a GPU-cached - * buffer, a poll of a buffer that is not HOST_POLLED, freeing the live queue ring, an oversize submit and every handle - * of a closed device; the driver's own failure text survives an open failure; a marker that never lands latches the - * session, which then frees nothing and closes nothing. Each case runs in its own child process. - */ -#include "fake_m16_native.h" -#include "nvrm.h" -#include "omega_blackwell_submit.h" -#include "omega_gpu_cmdlist.h" -#include "omega_gpu_mem_cached.h" -#include "omega_gpu_platform_linux.h" -#include "omega_gpu_session.h" - -#include -#include -#include -#include -#include - -/* The three driver symbols the session path needs that the fake (written for the vector engine) lacks. */ -static int g_open_fail; -int nvrm_open(Nvrm *rm) { - if (g_open_fail) { snprintf(rm->err, sizeof rm->err, "fake RM: open refused"); return -1; } - fk.device_open = 1; return 0; -} -int nvrm_close(Nvrm *rm) { (void)rm; return 0; } -static int g_retires; -void nvrm_retire(Nvrm *rm, uint32_t upto) { (void)rm; (void)upto; g_retires++; } - -static int case_ok; -#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) - -static const uint32_t ARGS[4] = {1, 2, 3, 4}; -static OmegaGpuLaunch launch_desc(uint64_t timeout_ms) { - OmegaGpuLaunch L = { .code_va = 0x200000000ull, .gpr_count = 64, .threads_x = 32, .grid_x = 1, .grid_y = 1, - .num_elements = 32, .args = ARGS, .n_args = 4, .timeout_ms = timeout_ms }; - return L; -} - -static void c_caps(void) { - OmegaGpuPlatformCaps caps; - const OmegaGpuPlatform *p = omega_gpu_platform_linux(&caps); - EXPECT(p != NULL); - EXPECT(caps.services == OMEGA_GPU_SVC_REQUIRED_SESSION); - EXPECT(!(caps.services & OMEGA_GPU_SVC_IRQ) && !(caps.services & OMEGA_GPU_SVC_MMIO)); - EXPECT(p->irq_wait == NULL && p->mmio_read32 == NULL && p->mmio_write32 == NULL); - EXPECT(omega_gpu_platform_check_for(p, &caps, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_OK); - EXPECT(caps.abi_major == 1 && caps.abi_minor == 2); -} - -static void c_default_install(void) { - fake_reset(); - EXPECT(omega_gpu_session_platform() == omega_gpu_platform_linux(NULL)); /* hosted: the reference by default */ - EXPECT(omega_gpu_session_completion_mode() == OMEGA_GPU_COMPLETION_POLLING); -} - -static void c_same_driver_calls(void) { - fake_reset(); - fk.kernel_mode = FK_KERNEL_SKIP; - omega_gpu_session_lock(); - OmegaGpuSession *s = omega_gpu_session_open(); - EXPECT(s != NULL); - if (!s) { printf(" %s\n", omega_gpu_session_last_error()); omega_gpu_session_unlock(); return; } - EXPECT(fk.channel_calls == 1 && fk.uncached_calls == 4 && fk.alloc_calls == 4 && fk.live == 4); - const int ch = fake_nth(FK_EV_CHANNEL, 1), a1 = fake_nth(FK_EV_ALLOC, 1); - EXPECT(ch >= 0 && a1 > ch); /* channel first, then the session buffers */ - EXPECT(fk.ev[fake_nth(FK_EV_ALLOC, 1)].a == 0x10000 && fk.ev[fake_nth(FK_EV_ALLOC, 2)].a == 0x1000 && - fk.ev[fake_nth(FK_EV_ALLOC, 3)].a == 0x1000 && fk.ev[fake_nth(FK_EV_ALLOC, 4)].a == 0x10000); - OmegaGpuLaunch L = launch_desc(1000); - uint32_t mk = 0; - EXPECT(omega_gpu_session_launch(&L, NULL, &mk) == 0); - EXPECT(fk.submit_calls == 1 && fk.pb_mem_size == 0x10000); - EXPECT(fake_count(FK_EV_PB_RELEASE) == 2 && fake_count(FK_EV_PB_FLUSH) == 1); /* the C3 tail */ - EXPECT(fk.marker1_va == s->marker.va && fk.marker2_va == s->marker.va + 0x10); - EXPECT(fk.sem_va == s->qmd.va + 0x2000 && fk.sem_init_value == OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT); - EXPECT(mk == OMEGA_BW_MARKER_COMPLETION_PAYLOAD && g_retires == 1); - omega_gpu_session_unlock(); - omega_gpu_session_close(); - EXPECT(fk.free_calls == 4 && fk.close_calls == 1 && fk.live_at_close == 0 && fk.double_free == 0); -} - -static void c_reference_refusals(void) { - fake_reset(); - OmegaGpuPlatformCaps caps; - const OmegaGpuPlatform *p = omega_gpu_platform_linux(&caps); - OmegaGpuDeviceHandle d; - EXPECT(p->device_open(p->ctx, 0, &d) == OMEGA_GPU_PLAT_OK); - OmegaGpuDeviceHandle d2; - EXPECT(p->device_open(p->ctx, 0, &d2) == OMEGA_GPU_PLAT_REFUSED_LIMIT); /* one device context */ - OmegaGpuBufferDesc cached = {.kind = OMEGA_GPU_HANDLE_BUF_DATA, .rights = OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_GPU_WRITE, - .gpu_cache = OMEGA_GPU_CACHE_GPU_CACHED, .bytes = 4096}; - OmegaGpuBufferHandle h; OmegaCpuView cpu; OmegaGpuVa va; OmegaGpuBusAddr bus; - const int allocs0 = fk.alloc_calls; - EXPECT(p->dma_alloc(p->ctx, d, &cached, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY); - cached.rights |= OMEGA_GPU_RIGHT_HOST_POLLED; /* polled and cached: the contract refuses it too */ - EXPECT(p->dma_alloc(p->ctx, d, &cached, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY); - EXPECT(fk.alloc_calls == allocs0); /* refused before the driver */ - OmegaGpuBufferDesc data = {.kind = OMEGA_GPU_HANDLE_BUF_DATA, .rights = OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_GPU_WRITE, - .gpu_cache = OMEGA_GPU_CACHE_GPU_UNCACHED, .bytes = 4096}; - EXPECT(p->dma_alloc(p->ctx, d, &data, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_OK); - EXPECT(cpu.ptr != NULL && cpu.len >= 4096 && bus.iova == 0); - uint32_t seen = 0; - EXPECT(p->poll_word(p->ctx, h, 0, 1, 1, &seen) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); /* not HOST_POLLED */ - OmegaGpuBufferDesc ring = {.kind = OMEGA_GPU_HANDLE_BUF_QUEUE, .rights = OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ, - .gpu_cache = OMEGA_GPU_CACHE_GPU_UNCACHED, .bytes = 4096}; - OmegaGpuBufferHandle rh; OmegaGpuQueueHandle q; - EXPECT(p->dma_alloc(p->ctx, d, &ring, &rh, &cpu, &va, &bus) == OMEGA_GPU_PLAT_OK); - EXPECT(p->queue_open(p->ctx, d, h, &q) == OMEGA_GPU_PLAT_REFUSED_BAD_KIND); /* a DATA buffer is not a ring */ - EXPECT(p->queue_open(p->ctx, d, rh, &q) == OMEGA_GPU_PLAT_OK); - EXPECT(p->dma_free(p->ctx, rh) == OMEGA_GPU_PLAT_REFUSED_BUSY); /* the open queue still uses it */ - static uint32_t big[2048]; - EXPECT(p->queue_submit(p->ctx, q, big, 2048) == OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH); /* 8 KiB into a 4 KiB ring */ - EXPECT(fk.submit_calls == 0); - const int frees0 = fk.free_calls; - EXPECT(p->device_close(p->ctx, d) == OMEGA_GPU_PLAT_OK); - /* every handle of the closed device is stale */ - EXPECT(p->dma_free(p->ctx, h) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(p->sync_cpu_to_gpu(p->ctx, h, 0, 4) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(p->queue_submit(p->ctx, q, big, 4) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(p->dma_alloc(p->ctx, d, &data, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); - EXPECT(fk.free_calls == frees0); - EXPECT(strstr(p->diag_text(p->ctx), "STALE") != NULL); -} - -static void c_open_failure_text(void) { - fake_reset(); - fk.channel_fail = 1; - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() == NULL); - EXPECT(strncmp(omega_gpu_session_last_error(), "m16_native_create_channel: ", 27) == 0); - EXPECT(strstr(omega_gpu_session_last_error(), FK_TEXT) != NULL); /* the driver's own text survives */ - fk.channel_fail = 0; - g_open_fail = 1; - EXPECT(omega_gpu_session_open() == NULL); - EXPECT(strcmp(omega_gpu_session_last_error(), "nvrm_open: fake RM: open refused") == 0); - g_open_fail = 0; - EXPECT(omega_gpu_session_open() != NULL && !omega_gpu_session_is_blocked()); - omega_gpu_session_unlock(); - omega_gpu_session_close(); -} - -static void c_marker_never_latches(void) { - fake_reset(); - fk.kernel_mode = FK_KERNEL_SKIP; - fk.marker_mode = FK_SYNC_NEVER; - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - OmegaGpuLaunch L = launch_desc(5); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); - EXPECT(omega_gpu_session_is_blocked()); - EXPECT(fk.wait_calls == 5 && fk.clock_ms == 5); /* five 1 ms poll slices, then uncertain */ - EXPECT(g_retires == 0); - omega_gpu_session_unlock(); - omega_gpu_session_close(); - EXPECT(fk.free_calls == 0 && fk.close_calls == 0 && fk.live == 4); /* parked: nothing released, nothing closed */ - OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); - EXPECT(ps.buffers == 4); -} - -/* omega #457: the L2_SYSMEM_NCOH_INVALIDATE prefix, MEM_OP_A..D = 0, 0, 0, 0x11 << 27 (clc96f.h:30-73). The fake logs - * every MEM_OP as FK_EV_PB_FLUSH with a = the operation word. */ -#define L2_INVAL_OP (0x11u << 27) -static int count_l2_inval(void) { - int n = 0; - for (int i = 0; i < fk.nev; i++) n += fk.ev[i].kind == FK_EV_PB_FLUSH && fk.ev[i].a == L2_INVAL_OP; - return n; -} - -static void c_l2_inval_prefix_once(void) { - fake_reset(); - fk.kernel_mode = FK_KERNEL_SKIP; - OmegaGpuPlatformCaps caps; - (void)omega_gpu_platform_linux(&caps); - EXPECT(caps.submit_prefix_words == 5u); /* the cost the platform publishes is the prefix it writes */ - omega_gpu_session_lock(); - OmegaGpuSession *s = omega_gpu_session_open(); - EXPECT(s != NULL); - if (!s) { omega_gpu_session_unlock(); return; } - const OmegaGpuPlatform *p = omega_gpu_session_platform(); - OmegaGpuMem cached; - EXPECT(omega_gpu_session_alloc_cached(4096, &cached) == 0); - OmegaGpuLaunch L = launch_desc(1000); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); - EXPECT(count_l2_inval() == 0); /* no host write into a GPU-cached buffer yet: no prefix */ - const size_t plain = fk.pb_len; - EXPECT(p->sync_cpu_to_gpu(p->ctx, s->marker.handle, 0, 4) == OMEGA_GPU_PLAT_OK); /* an uncached buffer: no prefix */ - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); - EXPECT(count_l2_inval() == 0 && fk.pb_len == plain); - EXPECT(p->sync_cpu_to_gpu(p->ctx, cached.handle, 0, 4096) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); - EXPECT(count_l2_inval() == 1); /* exactly once, at the head of the next submission */ - EXPECT(fk.pb_len == plain + 5u); - EXPECT(fk.pb[0] == ((2u << 28) | (4u << 16) | (0x0028u >> 2)) && fk.pb[1] == 0 && fk.pb[2] == 0 && fk.pb[3] == 0 && - fk.pb[4] == L2_INVAL_OP); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); - EXPECT(count_l2_inval() == 1 && fk.pb_len == plain); /* consumed: the launch after it has none */ - EXPECT(p->sync_gpu_to_cpu(p->ctx, cached.handle, 0, 4096) == OMEGA_GPU_PLAT_OK); /* GPU to CPU is no host write */ - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); - EXPECT(count_l2_inval() == 1 && fk.pb_len == plain); - EXPECT(fk.pb_parse_error == 0 && fk.ev_overflow == 0); - omega_gpu_session_unlock(); -} - -/* Fable review of omega #459: a stamped standalone list of >= 1167 launches filled one submission to 16381 words; with - * the 5-word prefix pending that is 16386 > 16384 ring words, refused BAD_LENGTH on every retry. The command list must - * budget the prefix the platform publishes (caps.submit_prefix_words). */ -/* 2048 launches (about 14 ring words each) fill the 16384-word ring so the list splits into exactly 2 submissions. - * OMEGA_GPU_CMDLIST_MAX_LAUNCHES is 4096 since L312, which would split into 4, so the count is pinned here. */ -#define NEAR_CAP_LAUNCHES 2048u -static void c_cmdlist_near_cap_with_l2_inval_pending(void) { - fake_reset(); - fk.kernel_mode = FK_KERNEL_SKIP; - fk.alloc_max = 4u << 20; /* the 2048-launch bank and QMD buffers are 2 MiB each */ - OmegaGpuCmdList *cl = NULL; - EXPECT(omega_gpu_cmdlist_create(NEAR_CAP_LAUNCHES, &cl) == 0); - if (!cl) { printf(" %s\n", omega_gpu_session_last_error()); return; } - omega_gpu_session_lock(); - OmegaGpuLaunch L = launch_desc(1000); - for (uint32_t i = 0; i < NEAR_CAP_LAUNCHES; i++) EXPECT(omega_gpu_cmdlist_add(cl, &L) == (int)i); - const OmegaGpuPlatform *p = omega_gpu_session_platform(); - OmegaGpuMem cached; - EXPECT(omega_gpu_session_alloc_cached(4096, &cached) == 0); - EXPECT(p->sync_cpu_to_gpu(p->ctx, cached.handle, 0, 4096) == OMEGA_GPU_PLAT_OK); /* the prefix is now pending */ - const int submits0 = fk.submit_calls; - OmegaGpuCmdListOpts o = { .mode = OMEGA_GPU_CMDLIST_PCAS, .barrier = OMEGA_GPU_CMDLIST_BARRIER_WFI, .timeout_ms = 1000, .stamps = 1 }; - OmegaGpuCmdListStats st; - const int rc = omega_gpu_cmdlist_submit(cl, &o, &st); - if (rc != 0) printf(" cmdlist submit: %s (platform: %s)\n", omega_gpu_session_last_error(), p->diag_text(p->ctx)); - EXPECT(rc == 0); - EXPECT(st.sems_done == NEAR_CAP_LAUNCHES && st.first_missing == -1); - EXPECT(st.submits == 2 && fk.submit_calls - submits0 == 2); - EXPECT(count_l2_inval() == 1); /* the first submission only */ - for (int i = 0; i < fk.nev; i++) - if (fk.ev[i].kind == FK_EV_SUBMIT) EXPECT(fk.ev[i].a * 4u <= fk.pb_mem_size); /* prefix included, inside the ring */ - EXPECT(fk.pb_parse_error == 0 && fk.ev_overflow == 0); - EXPECT(!omega_gpu_session_is_blocked() && !omega_gpu_cmdlist_is_latched()); - omega_gpu_session_unlock(); -} - -typedef struct { const char *id; void (*fn)(void); } Case; -static const Case CASES[] = { - {"LINUX_REF_CAPS_NO_MMIO_NO_IRQ", c_caps}, - {"HOSTED_DEFAULT_IS_LINUX_REFERENCE", c_default_install}, - {"SAME_DRIVER_CALLS_AND_ORDER_AS_BEFORE", c_same_driver_calls}, - {"REFERENCE_REFUSALS_CACHED_POLLED_RING_STALE", c_reference_refusals}, - {"OPEN_FAILURE_KEEPS_DRIVER_TEXT", c_open_failure_text}, - {"MARKER_NEVER_LATCHES_AND_PARKS", c_marker_never_latches}, - {"L2_INVAL_PREFIX_ONCE_AFTER_CACHED_HOST_WRITE", c_l2_inval_prefix_once}, - {"CMDLIST_NEAR_CAP_SUBMITS_WITH_L2_INVAL_PENDING", c_cmdlist_near_cap_with_l2_inval_pending}, -}; - -int main(void) { - int pass = 0, fail = 0; - for (size_t i = 0; i < sizeof CASES / sizeof CASES[0]; i++) { - fflush(stdout); - pid_t pid = fork(); - if (pid == 0) { case_ok = 1; CASES[i].fn(); fflush(stdout); _exit(case_ok ? 0 : 1); } - int st = 0; - waitpid(pid, &st, 0); - const int ok = WIFEXITED(st) && WEXITSTATUS(st) == 0; - printf("%s %s\n", ok ? "PASS" : "FAIL", CASES[i].id); - if (ok) pass++; else fail++; - } - printf("test_omega_gpu_platform_linux (reference only, simulated driver): %d passed, %d failed\n", pass, fail); - return fail ? 1 : 0; -} diff --git a/tests/test_omega_gpu_session_platform.c b/tests/test_omega_gpu_session_platform.c deleted file mode 100644 index b02defe6f..000000000 --- a/tests/test_omega_gpu_session_platform.c +++ /dev/null @@ -1,609 +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. - */ - -/* test_omega_gpu_session_platform: the portable GPU session (native v1 P07 cut C, session part; aienos#286) on a - * FAKE OmegaGpuPlatform. Host program; links the FREESTANDING partial-link object (build/gpu_fs/ - * omega_gpu_freestanding.o: session, matmul and attention APIs, serving, wait, codegen, platform contract), so what - * runs here is the code the native build would run. Opens no device, touches no GPU. - * - * The fake device "completes" a launch at submit time by writing the intermediate semaphore DONE and both marker - * payloads, or (hang mode) writes nothing. Its clock advances only when asked (plus 1 us per read), so timeouts are - * exact and instant. Each case runs in its own child process because an uncertain completion latches the process - * for good (that is the rule under test). - * - * Cases: platform install refusals; freestanding build has no default platform; open/launch/close with typed - * buffers, explicit rights and GPU-uncached policy (host-polled marker); polling only (irq never called, mode is - * POLLING); cancel before submit (nothing submitted, not latched); cancel after submit (latched, parked); timeout - * (latched, session buffers parked, later frees park, close/reopen/install refused, nothing released); stale handle - * refusal after close and reopen; close/reopen (new device generation, opens 2); serving reservation refusal (no - * platform allocation); matmul API code buffer is a CODE buffer encoded in place; wait helper refuses without a clock; - * the bounded formatter matches snprintf and never writes past its cap. - */ -#include "omega_gpu_session.h" -#include "omega_gpu_matmul_api.h" -#include "omega_gpu_wait.h" -#include "omega_gpu_fmt.h" -#include "omega_blackwell_submit.h" - -#include -#include -#include -#include -#include - -static int case_ok; -#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) - -/* ---- the fake platform ---- */ -#define NB OMEGA_GPU_HANDLE_SLOTS -enum { MODE_COMPLETE = 0, MODE_HANG = 1 }; -static struct { - OmegaGpuHandleTable t; - void *mem[NB]; - OmegaGpuBufferDesc desc[NB]; - uint32_t dev_of[NB]; /* device generation a buffer belongs to */ - OmegaGpuDeviceHandle dev; - OmegaGpuQueueHandle q; - OmegaGpuBufferHandle ring; - int mode; - int cancel_on_poll; /* poll_word calls omega_gpu_session_cancel() on its first call */ - uint64_t ns; - unsigned allocs, frees, free_refusals, submits, polls, retires, syncs, irq_calls, dev_opens, dev_closes; - unsigned locks_held; - unsigned cached_requests; /* buffers asked GPU-cached (must stay 0) */ - unsigned allocs_unlocked; /* allocations without the session lock (must stay 0) */ - int fail_open; - int fail_close; /* device_close closes, then reports a driver teardown fault (C5) */ -} fk; - -static uint64_t f_now_ns(void *c) { (void)c; fk.ns += 1000u; return fk.ns; } -static uint64_t f_now_ms(void *c) { return f_now_ns(c) / 1000000u; } -static int f_wait(void *c, uint64_t ms) { (void)c; fk.ns += ms * 1000000u; return 0; } -static int f_lock(void *c, uint32_t id) { (void)c; if (id != OMEGA_GPU_SESSION_LOCK_ID) return OMEGA_GPU_PLAT_REFUSED_ARGS; fk.locks_held++; return 0; } -static int f_unlock(void *c, uint32_t id) { (void)c; if (id != OMEGA_GPU_SESSION_LOCK_ID || !fk.locks_held) return OMEGA_GPU_PLAT_REFUSED_ARGS; fk.locks_held--; return 0; } -static const char *f_diag(void *c) { (void)c; return fk.fail_open ? "fake device: no GB10 here" : ""; } - -static int f_dev_open(void *c, uint32_t ord, OmegaGpuDeviceHandle *out) { - (void)c; - if (fk.fail_open) return OMEGA_GPU_PLAT_REFUSED_DEVICE; - if (ord != 0 || fk.dev.generation) return OMEGA_GPU_PLAT_REFUSED_LIMIT; - int rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &out->index, &out->generation); - if (rc == 0) { fk.dev = *out; fk.dev_opens++; } - return rc; -} -static int f_dev_close(void *c, OmegaGpuDeviceHandle d) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (rc) return rc; - for (uint32_t i = 0; i < NB; i++) /* every handle of the device goes stale */ - if (fk.t.live[i] && i != d.index) { (void)omega_gpu_handles_close(&fk.t, i, fk.t.generation[i], fk.t.kind[i]); free(fk.mem[i]); fk.mem[i] = NULL; } - (void)omega_gpu_handles_close(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - memset(&fk.dev, 0, sizeof fk.dev); memset(&fk.q, 0, sizeof fk.q); - fk.dev_closes++; - return fk.fail_close ? OMEGA_GPU_PLAT_REFUSED_DEVICE : 0; -} - -static OmegaGpuPlatformCaps g_caps = { - .abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR, .abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR, - .services = OMEGA_GPU_SVC_REQUIRED_SESSION, .max_devices = 1, .max_buffers = 1000, .max_queues = 1, .max_inflight = 1, - .max_buffer_bytes = 1ull << 30, .max_total_bytes = 1ull << 32, -}; - -static int f_alloc(void *c, OmegaGpuDeviceHandle d, const OmegaGpuBufferDesc *desc, OmegaGpuBufferHandle *o, - OmegaCpuView *cpu, OmegaGpuVa *g, OmegaGpuBusAddr *b) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (!rc) rc = omega_gpu_platform_check_buffer(desc, &g_caps); - if (rc) return rc; - if (desc->gpu_cache != OMEGA_GPU_CACHE_GPU_UNCACHED) fk.cached_requests++; - if (!fk.locks_held) fk.allocs_unlocked++; - rc = omega_gpu_handles_open(&fk.t, desc->kind, desc->bytes, 1000, 1ull << 32, &o->index, &o->generation); - if (rc) return rc; - void *m = calloc(1, desc->bytes); - fk.mem[o->index] = m; fk.desc[o->index] = *desc; fk.dev_of[o->index] = d.generation; - cpu->ptr = m; cpu->len = desc->bytes; g->va = 0x100000000ull + (uint64_t)o->index * 0x1000000ull; b->iova = 0; - fk.allocs++; - return 0; -} -static int f_free(void *c, OmegaGpuBufferHandle h) { - (void)c; - if (h.index >= NB) { fk.free_refusals++; return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; } - int rc = omega_gpu_handles_close(&fk.t, h.index, h.generation, fk.t.kind[h.index]); - if (rc) { fk.free_refusals++; return rc; } - free(fk.mem[h.index]); fk.mem[h.index] = NULL; - fk.frees++; - return 0; -} -static int buf_live(OmegaGpuBufferHandle h) { - return h.index < NB && fk.t.live[h.index] && fk.t.generation[h.index] == h.generation; -} -static int f_sync(void *c, OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { - (void)c; - if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - if (len == 0 || off > fk.desc[h.index].bytes || len > fk.desc[h.index].bytes - off) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - fk.syncs++; - return 0; -} -static int f_poll(void *c, OmegaGpuBufferHandle h, uint64_t off, uint32_t want, uint64_t ms, uint32_t *seen) { - (void)c; - if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; - if (!(fk.desc[h.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED)) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; - fk.polls++; - if (fk.cancel_on_poll) { fk.cancel_on_poll = 0; omega_gpu_session_cancel(); } - volatile uint32_t *w = (volatile uint32_t *)((uint8_t *)fk.mem[h.index] + off); - *seen = *w; - if ((int32_t)(*w - want) >= 0) return 0; - fk.ns += ms * 1000000u; - return OMEGA_GPU_POLL_TIMED_OUT; -} -static int f_irq(void *c, OmegaGpuDeviceHandle d, uint64_t t) { (void)c; (void)d; (void)t; fk.irq_calls++; return 0; } -static int f_qopen(void *c, OmegaGpuDeviceHandle d, OmegaGpuBufferHandle ring, OmegaGpuQueueHandle *o) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); - if (!rc && (!buf_live(ring) || fk.t.kind[ring.index] != OMEGA_GPU_HANDLE_BUF_QUEUE)) rc = OMEGA_GPU_PLAT_REFUSED_BAD_KIND; - if (!rc) rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_QUEUE, 0, 1, 0, &o->index, &o->generation); - if (!rc) { fk.q = *o; fk.ring = ring; } - return rc; -} -static int f_qclose(void *c, OmegaGpuQueueHandle q) { - (void)c; - int rc = omega_gpu_handles_close(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); - if (!rc) memset(&fk.q, 0, sizeof fk.q); - return rc; -} -/* The fake device: the launch completes at submit (both markers and the semaphore), or never (hang). The marker and - * semaphore addresses are read back from the method words: the QMD page is the buffer whose VA the QMD0 header - * names, the marker page the one whose VA the first release names. */ -static void *va_to_cpu(uint64_t va) { - for (uint32_t i = 0; i < NB; i++) { - if (!fk.mem[i] || !fk.t.live[i]) continue; - uint64_t base = 0x100000000ull + (uint64_t)i * 0x1000000ull; - if (va >= base && va < base + fk.desc[i].bytes) return (uint8_t *)fk.mem[i] + (va - base); - } - return NULL; -} -static int f_submit(void *c, OmegaGpuQueueHandle q, const uint32_t *w, uint32_t n) { - (void)c; - int rc = omega_gpu_handles_check(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); - if (rc) return rc; - if ((uint64_t)n * 4u > fk.desc[fk.ring.index].bytes) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; - memcpy(fk.mem[fk.ring.index], w, (size_t)n * 4u); - fk.submits++; - if (fk.mode != MODE_COMPLETE) return 0; - for (uint32_t i = 0; i + 5 < n; i++) { - if (w[i] == ((2u << 28) | (5u << 16) | (0u << 13) | (0x005cu >> 2))) { /* release: va lo, va hi, payload */ - uint64_t va = (uint64_t)w[i + 1] | ((uint64_t)w[i + 2] << 32); - uint32_t *m = va_to_cpu(va); - if (m) *m = w[i + 3]; - } - if (w[i] == ((2u << 28) | (2u << 16) | (1u << 13) | (0x0188u >> 2)) && w[i + 3] == ((2u << 28) | (2u << 16) | (1u << 13) | (0x0180u >> 2)) && - w[i + 4] == 4u) { /* the semaphore init upload: the kernel ran, the semaphore says DONE */ - uint32_t *s = va_to_cpu(((uint64_t)w[i + 1] << 32) | w[i + 2]); - if (s) *s = OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE; - } - } - return 0; -} -static int f_retire(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; fk.retires++; return 0; } -static void *f_halloc(void *c, size_t b) { (void)c; return malloc(b); } -static void f_hfree(void *c, void *p) { (void)c; free(p); } - -static OmegaGpuPlatform g_plat = { - .ctx = &fk, .time_now_ms = f_now_ms, .wait_ms = f_wait, .lock = f_lock, .unlock = f_unlock, - .dma_alloc = f_alloc, .dma_free = f_free, .sync_cpu_to_gpu = f_sync, .sync_gpu_to_cpu = f_sync, .poll_word = f_poll, - .device_open = f_dev_open, .device_close = f_dev_close, .diag_text = f_diag, - .queue_open = f_qopen, .queue_close = f_qclose, .queue_submit = f_submit, .queue_retire = f_retire, - .time_now_ns = f_now_ns, .host_alloc = f_halloc, .host_free = f_hfree, -}; - -static void fk_reset(void) { memset(&fk, 0, sizeof fk); omega_gpu_handles_init(&fk.t); } - -static int install(void) { return omega_gpu_session_set_platform(&g_plat, &g_caps); } - -static const uint32_t ARGS[4] = {1, 2, 3, 4}; -static OmegaGpuLaunch launch_desc(uint64_t timeout_ms) { - OmegaGpuLaunch L = { .code_va = 0x200000000ull, .gpr_count = 64, .threads_x = 32, .grid_x = 1, .grid_y = 1, - .num_elements = 32, .args = ARGS, .n_args = 4, .timeout_ms = timeout_ms }; - return L; -} - -/* ---- cases ---- */ - -static void c_install_refusals(void) { - fk_reset(); - OmegaGpuPlatform p = g_plat; - OmegaGpuPlatformCaps caps = g_caps; - caps.services &= ~OMEGA_GPU_SVC_CLOCK_NS; p.time_now_ns = NULL; - EXPECT(omega_gpu_session_set_platform(&p, &caps) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); - p = g_plat; caps = g_caps; - p.irq_wait = f_irq; /* a function for a service it does not claim: refused, never used */ - const int rc_irq = omega_gpu_session_set_platform(&p, &caps); - EXPECT(rc_irq != OMEGA_GPU_PLAT_OK && omega_gpu_session_platform() == NULL); - caps = g_caps; caps.abi_minor = 1; /* a 1.1 platform predates caps.submit_prefix_words: refused */ - EXPECT(omega_gpu_session_set_platform(&g_plat, &caps) == OMEGA_GPU_PLAT_REFUSED_ABI); - EXPECT(omega_gpu_session_platform() == NULL); /* nothing was installed */ - EXPECT(install() == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_session_platform() == &g_plat); - EXPECT(omega_gpu_session_completion_mode() == OMEGA_GPU_COMPLETION_POLLING); -} - -static void c_no_default_platform(void) { - fk_reset(); - /* the freestanding build has no Linux fallback: nothing installed means refused, not emulated */ - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() == NULL); - EXPECT(strstr(omega_gpu_session_last_error(), "no GPU platform installed") != NULL); - omega_gpu_session_unlock(); - EXPECT(omega_gpu_host_alloc(16) == NULL); - EXPECT(omega_gpu_session_now_ns() == 0); -} - -static void c_open_launch_close(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(fk.locks_held == 1); - OmegaGpuSession *s = omega_gpu_session_open(); - EXPECT(s != NULL); - if (!s) { omega_gpu_session_unlock(); return; } - EXPECT(fk.allocs == 4 && fk.dev_opens == 1); - /* typed buffers, explicit rights, all GPU-uncached; the polled marker is HOST_POLLED */ - EXPECT(fk.t.kind[s->pb.handle.index] == OMEGA_GPU_HANDLE_BUF_QUEUE); - EXPECT(fk.desc[s->marker.handle.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED); - EXPECT(!(fk.desc[s->cbank.handle.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED)); - EXPECT(fk.cached_requests == 0 && fk.allocs_unlocked == 0); - EXPECT(s->pb.va != s->cbank.va && s->marker.size >= 0x1000 && s->qmd.size >= 0x10000); - OmegaGpuLaunch L = launch_desc(100); - uint64_t el = 0; uint32_t mk = 0; - EXPECT(omega_gpu_session_launch(&L, &el, &mk) == 0); - EXPECT(mk == OMEGA_BW_MARKER_COMPLETION_PAYLOAD && fk.submits == 1 && fk.retires == 1 && el > 0); - EXPECT(fk.syncs >= 3); /* explicit CPU->GPU and GPU->CPU visibility, never implicit */ - EXPECT(fk.irq_calls == 0); /* polling only */ - EXPECT(!omega_gpu_session_is_blocked()); - /* a CODE buffer: CPU writes, GPU executes, never GPU-written, prefetch tail zeroed */ - OmegaGpuMem code; - EXPECT(omega_gpu_session_alloc_code(100, &code) == 0); - EXPECT(fk.t.kind[code.handle.index] == OMEGA_GPU_HANDLE_BUF_CODE); - EXPECT((fk.desc[code.handle.index].rights & OMEGA_GPU_RIGHT_GPU_EXEC) && !(fk.desc[code.handle.index].rights & OMEGA_GPU_RIGHT_GPU_WRITE)); - omega_gpu_session_free(&code); - EXPECT(code.cpu == NULL && fk.frees == 1); - omega_gpu_session_unlock(); - EXPECT(fk.locks_held == 0); - omega_gpu_session_close(); - EXPECT(fk.dev_closes == 1 && fk.frees == 5 && fk.t.nlive == 0); - EXPECT(!omega_gpu_session_is_open()); -} - -static void c_cancel_before_submit(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - omega_gpu_session_cancel(); - OmegaGpuLaunch L = launch_desc(100); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == OMEGA_GPU_SESSION_CANCELLED); - EXPECT(fk.submits == 0); /* nothing went to the device */ - EXPECT(!omega_gpu_session_is_blocked()); /* so nothing is uncertain */ - OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); - EXPECT(ps.buffers == 0); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); /* the request was consumed; the session still works */ - omega_gpu_session_unlock(); - omega_gpu_session_close(); - EXPECT(fk.dev_closes == 1); -} - -static void check_latched(unsigned frees_before) { - EXPECT(omega_gpu_session_is_blocked()); - OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); - EXPECT(ps.buffers == 4 && ps.untracked == 0 && ps.bytes >= 0x10000 + 0x1000 + 0x1000 + 0x10000); - /* a buffer the caller frees now is parked too, never released: the device may still be using it */ - OmegaGpuMem m = {0}; - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_alloc(64, &m) != 0); /* no new allocation after a latch */ - omega_gpu_session_unlock(); - EXPECT(fk.frees == frees_before); - omega_gpu_session_close(); - EXPECT(fk.dev_closes == 0 && fk.frees == frees_before); /* close refused: nothing released */ - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() == NULL && strstr(omega_gpu_session_last_error(), "latched") != NULL); - OmegaGpuLaunch L = launch_desc(10); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); - EXPECT(strstr(omega_gpu_session_last_error(), "process latched") != NULL); - omega_gpu_session_unlock(); - EXPECT(omega_gpu_session_set_platform(&g_plat, &g_caps) == OMEGA_GPU_PLAT_REFUSED_BUSY); - EXPECT(fk.irq_calls == 0); -} - -static void c_timeout_parks(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - OmegaGpuSession *s = omega_gpu_session_open(); - EXPECT(s != NULL); - OmegaGpuMem user; - EXPECT(omega_gpu_session_alloc(4096, &user) == 0); - fk.mode = MODE_HANG; - OmegaGpuLaunch L = launch_desc(25); - const uint64_t t0 = fk.ns; - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); - EXPECT(strstr(omega_gpu_session_last_error(), "timed out") != NULL); - EXPECT(fk.polls >= 25 && fk.ns - t0 >= 25ull * 1000000u); /* polled in 1 ms slices for the whole timeout */ - EXPECT(fk.retires == 0); /* never retired: the entry may still be in flight */ - OmegaGpuBufferHandle uh = user.handle; - omega_gpu_session_free(&user); - EXPECT(user.cpu == NULL && omega_gpu_session_is_parked(uh)); - EXPECT(omega_gpu_session_is_parked(s->marker.handle) && omega_gpu_session_is_parked(s->pb.handle)); - omega_gpu_session_unlock(); - OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); - EXPECT(ps.buffers == 5); - EXPECT(fk.frees == 0 && fk.t.nlive == 1 + 1 + 5); /* device, queue, 5 buffers: all still allocated */ - /* the generic latch checks expect the four session buffers; the user buffer made it five */ - EXPECT(omega_gpu_session_is_blocked()); - omega_gpu_session_close(); - EXPECT(fk.dev_closes == 0 && fk.frees == 0); -} - -static void c_cancel_after_submit(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - fk.mode = MODE_HANG; - fk.cancel_on_poll = 1; /* the cancel arrives while the host is polling */ - OmegaGpuLaunch L = launch_desc(60000); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == OMEGA_GPU_SESSION_CANCELLED); - EXPECT(fk.submits == 1 && fk.polls <= 2); /* seen within one poll slice, not after the 60 s timeout */ - EXPECT(strstr(omega_gpu_session_last_error(), "cancelled after submit") != NULL); - omega_gpu_session_unlock(); - check_latched(0); -} - -static void c_timeout_latch_rules(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - fk.mode = MODE_HANG; - OmegaGpuLaunch L = launch_desc(3); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); - omega_gpu_session_unlock(); - check_latched(0); -} - -/* C5: recover lifts the latch in the same process. Refused when nothing is latched; after a timeout it closes the device - * once (the platform releases every buffer, parked ones included; the session itself frees nothing), clears the parked - * list, and the next open is a new device on which a launch completes. */ -static void c_timeout_recover(void) { - fk_reset(); - EXPECT(install() == 0); - EXPECT(omega_gpu_session_recover() == -1 && strstr(omega_gpu_session_last_error(), "not latched") != NULL); - omega_gpu_session_lock(); - OmegaGpuSession *s = omega_gpu_session_open(); - EXPECT(s != NULL); - const OmegaGpuDeviceHandle old_dev = s ? s->dev : (OmegaGpuDeviceHandle){0}; - OmegaGpuLaunch L = launch_desc(5); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); /* a working launch first */ - omega_gpu_session_unlock(); - EXPECT(omega_gpu_session_recover() == -1 && fk.dev_closes == 0); /* open but not latched: refused, device kept */ - omega_gpu_session_lock(); - OmegaGpuMem user; - EXPECT(omega_gpu_session_alloc(4096, &user) == 0); - fk.mode = MODE_HANG; - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1 && omega_gpu_session_is_blocked()); - omega_gpu_session_free(&user); /* parked */ - omega_gpu_session_unlock(); - EXPECT(omega_gpu_session_recoveries() == 0); - EXPECT(omega_gpu_session_recover() == 0); - EXPECT(!omega_gpu_session_is_blocked() && omega_gpu_session_recoveries() == 1); - EXPECT(fk.dev_closes == 1 && fk.frees == 0 && fk.t.nlive == 0); /* the platform close released all of it */ - OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); - EXPECT(ps.buffers == 0 && ps.bytes == 0); - EXPECT(omega_gpu_session_recover() == -1); /* nothing latched any more */ - fk.mode = MODE_COMPLETE; - omega_gpu_session_lock(); - s = omega_gpu_session_open(); - EXPECT(s != NULL && s->dev.generation != old_dev.generation && fk.dev_opens == 2); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); - omega_gpu_session_unlock(); - omega_gpu_session_close(); - EXPECT(fk.dev_closes == 2 && fk.t.nlive == 0); -} - -/* C5: a close that reports a driver teardown fault leaves the process latched for good (the old grid may still run). */ -static void c_recover_teardown_fault(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - fk.mode = MODE_HANG; - OmegaGpuLaunch L = launch_desc(5); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1 && omega_gpu_session_is_blocked()); - omega_gpu_session_unlock(); - fk.fail_close = 1; - EXPECT(omega_gpu_session_recover() == -1 && strstr(omega_gpu_session_last_error(), "teardown fault") != NULL); - EXPECT(omega_gpu_session_is_blocked() && omega_gpu_session_recoveries() == 0 && fk.dev_closes == 1); - fk.fail_close = 0; - EXPECT(omega_gpu_session_recover() == -1 && omega_gpu_session_is_blocked()); /* the handle is gone: no second try */ - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() == NULL); - omega_gpu_session_unlock(); -} - -/* C5: a module latch (the command lists after a timeout whose check launch completed) is recoverable too */ -static void c_recover_module_latch(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - omega_gpu_session_unlock(); - omega_gpu_session_note_module_latch(); - EXPECT(!omega_gpu_session_is_blocked()); /* other APIs keep working */ - EXPECT(omega_gpu_session_recover() == 0 && fk.dev_closes == 1 && omega_gpu_session_recoveries() == 1); - EXPECT(omega_gpu_session_recover() == -1); /* lifted */ -} - -static void c_stale_after_reopen(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - OmegaGpuSession *s = omega_gpu_session_open(); - EXPECT(s != NULL); - const OmegaGpuDeviceHandle d1 = s->dev; - OmegaGpuMem old; - EXPECT(omega_gpu_session_alloc(8192, &old) == 0); - omega_gpu_session_unlock(); - omega_gpu_session_close(); /* the caller kept `old` past the close */ - EXPECT(fk.dev_closes == 1); - omega_gpu_session_lock(); - s = omega_gpu_session_open(); - EXPECT(s != NULL && omega_gpu_session_open_count() == 2); - EXPECT(s->dev.index != d1.index || s->dev.generation != d1.generation); /* a new device generation */ - const unsigned frees = fk.frees; - OmegaGpuAllocStats st0, st1; - omega_gpu_session_alloc_stats(&st0); - omega_gpu_session_free(&old); /* a handle of the closed device: refused, nothing released */ - omega_gpu_session_alloc_stats(&st1); - EXPECT(st1.stale_refusals == st0.stale_refusals + 1 && st1.frees == st0.frees); - EXPECT(fk.frees == frees && fk.free_refusals == 1); - EXPECT(strstr(omega_gpu_session_last_error(), "STALE") != NULL || strstr(omega_gpu_session_last_error(), "stale") != NULL); - EXPECT(old.cpu == NULL); - OmegaGpuLaunch L = launch_desc(100); - EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); /* the reopened session works */ - omega_gpu_session_unlock(); - omega_gpu_session_close(); - EXPECT(fk.dev_closes == 2 && fk.t.nlive == 0); -} - -static void c_open_failure_text(void) { - fk_reset(); - EXPECT(install() == 0); - fk.fail_open = 1; - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() == NULL); - EXPECT(strstr(omega_gpu_session_last_error(), "fake device: no GB10 here") != NULL); /* the driver text survives */ - EXPECT(!omega_gpu_session_is_blocked() && fk.allocs == 0); - fk.fail_open = 0; - EXPECT(omega_gpu_session_open() != NULL); /* a failed open is not a latch */ - omega_gpu_session_unlock(); - omega_gpu_session_close(); -} - -static void c_reservation_refusal(void) { - fk_reset(); - EXPECT(install() == 0); - omega_gpu_session_lock(); - EXPECT(omega_gpu_session_open() != NULL); - OmegaGpuScratch sc; memset(&sc, 0, sizeof sc); - EXPECT(omega_gpu_session_scratch_reserve(&sc, 10000) == 0); - const unsigned allocs = fk.allocs; - EXPECT(omega_gpu_session_scratch(&sc, 9000) == 0); - EXPECT(omega_gpu_session_scratch(&sc, sc.cap + 1) == OMEGA_GPU_SESSION_SCRATCH_RESERVED); - EXPECT(fk.allocs == allocs); /* refused loudly, nothing allocated */ - EXPECT(strstr(omega_gpu_session_last_error(), "serving reservation exceeded") != NULL); - omega_gpu_session_scratch_free(&sc); - omega_gpu_session_unlock(); - omega_gpu_session_close(); - EXPECT(fk.t.nlive == 0); -} - -static void c_matmul_code_buffer(void) { - fk_reset(); - EXPECT(install() == 0); - uint16_t b[32 * 16]; - memset(b, 0, sizeof b); - OmegaGpuTensor *t = NULL; - EXPECT(omega_gpu_tensor_upload_bf16(32, 16, b, &t) == OMEGA_GPU_MATMUL_OK); - uint16_t a[32]; memset(a, 0, sizeof a); - float c[16]; - OmegaGpuMatmulInfo info; - /* the fake device runs no kernel, so the result sentinels survive: CHIP_FAIL is the expected verdict here */ - int rc = omega_gpu_matmul_resident_bf16(1, a, t, c, &info); - EXPECT(rc == OMEGA_GPU_MATMUL_CHIP_FAIL && fk.submits >= 1); - unsigned code_bufs = 0; - for (uint32_t i = 0; i < NB; i++) - if (fk.t.live[i] && fk.t.kind[i] == OMEGA_GPU_HANDLE_BUF_CODE) { - code_bufs++; - const uint8_t *p = fk.mem[i]; - unsigned nz = 0; - for (uint32_t j = 0; j < 64; j++) nz += p[j] != 0; - EXPECT(nz > 0); /* the kernel was encoded in place into the device code buffer */ - EXPECT((fk.desc[i].rights & OMEGA_GPU_RIGHT_GPU_EXEC) && !(fk.desc[i].rights & OMEGA_GPU_RIGHT_GPU_WRITE)); - } - EXPECT(code_bufs == 1); - EXPECT(fk.cached_requests == 0 && fk.allocs_unlocked == 0 && fk.irq_calls == 0); - omega_gpu_tensor_free(t); - omega_gpu_session_close(); - EXPECT(fk.t.nlive == 0); -} - -static void c_wait_needs_clock(void) { - volatile uint32_t word = 0; - omega_gpu_wait_report_t r; - EXPECT(!omega_gpu_wait_fixed(&word, 1, &r, NULL)); - EXPECT(r.result == OMEGA_GPU_WAIT_INVALID_STATE); /* no clock in the freestanding build: refused, not unbounded */ -} - -static void c_fmt_matches_snprintf(void) { - char a[96], b[96]; - const long long big = -9223372036854775807LL - 1; - omega_gpu_fmt(a, sizeof a, "%s:%c:%d:%u:%x:%ld:%lu:%lld:%llu:%zu:%%", "stage", 'x', -42, 4000000000u, 0xbeefu, - -7L, 9UL, big, 18446744073709551615ULL, (size_t)12345); - snprintf(b, sizeof b, "%s:%c:%d:%u:%x:%ld:%lu:%lld:%llu:%zu:%%", "stage", 'x', -42, 4000000000u, 0xbeefu, - -7L, 9UL, big, 18446744073709551615ULL, (size_t)12345); - EXPECT(strcmp(a, b) == 0); - char s[8]; - memset(s, 'Z', sizeof s); - omega_gpu_fmt(s, 6, "%s", "truncate me"); - EXPECT(strcmp(s, "trunc") == 0 && s[6] == 'Z' && s[7] == 'Z'); /* bounded: NUL inside cap, nothing past it */ - omega_gpu_fmt(s, 1, "%d", 123); - EXPECT(s[0] == '\0'); -} - -typedef struct { const char *id; void (*fn)(void); } Case; -static const Case CASES[] = { - {"INSTALL_REFUSALS_ABI_1_1", c_install_refusals}, - {"FREESTANDING_NO_DEFAULT_PLATFORM", c_no_default_platform}, - {"OPEN_LAUNCH_CLOSE_TYPED_UNCACHED_POLLING", c_open_launch_close}, - {"OPEN_FAILURE_KEEPS_DRIVER_TEXT", c_open_failure_text}, - {"CANCEL_BEFORE_SUBMIT_NOT_LATCHED", c_cancel_before_submit}, - {"CANCEL_AFTER_SUBMIT_LATCHES_AND_PARKS", c_cancel_after_submit}, - {"TIMEOUT_PARKS_NEVER_RELEASES", c_timeout_parks}, - {"TIMEOUT_LATCH_REFUSES_CLOSE_REOPEN_INSTALL", c_timeout_latch_rules}, - {"TIMEOUT_RECOVER_SAME_PROCESS", c_timeout_recover}, - {"RECOVER_TEARDOWN_FAULT_STAYS_LATCHED", c_recover_teardown_fault}, - {"RECOVER_MODULE_LATCH", c_recover_module_latch}, - {"STALE_HANDLE_REFUSED_AFTER_CLOSE_REOPEN", c_stale_after_reopen}, - {"SERVING_RESERVATION_REFUSES_WITHOUT_ALLOC", c_reservation_refusal}, - {"MATMUL_CODE_BUFFER_ENCODED_IN_PLACE", c_matmul_code_buffer}, - {"WAIT_REFUSES_WITHOUT_CLOCK", c_wait_needs_clock}, - {"FMT_BOUNDED_MATCHES_SNPRINTF", c_fmt_matches_snprintf}, -}; - -int main(void) { - int pass = 0, fail = 0; - for (size_t i = 0; i < sizeof CASES / sizeof CASES[0]; i++) { - fflush(stdout); - pid_t pid = fork(); - if (pid == 0) { case_ok = 1; CASES[i].fn(); fflush(stdout); _exit(case_ok ? 0 : 1); } - int st = 0; - waitpid(pid, &st, 0); - const int ok = WIFEXITED(st) && WEXITSTATUS(st) == 0; - printf("%s %s\n", ok ? "PASS" : "FAIL", CASES[i].id); - if (ok) pass++; else fail++; - } - printf("test_omega_gpu_session_platform: %d passed, %d failed\n", pass, fail); - return fail ? 1 : 0; -} diff --git a/tests/test_omega_gpu_wait.c b/tests/test_omega_gpu_wait.c deleted file mode 100644 index 0d4cc10d9..000000000 --- a/tests/test_omega_gpu_wait.c +++ /dev/null @@ -1,319 +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. - */ - -/* Host test for src/omega_gpu_wait.c: fake memory, fake clock, no GPU. - * Every scenario runs against the real primitive (must behave) and against - * mutants (a naive wall-clock loop, a fixed wait that accepts overshoot, a - * sequence wait with an unsigned compare). Each mutant must be killed by the - * scenarios named for it, otherwise this test fails. */ -#include "omega_gpu_wait.h" - -#include -#include - -typedef struct { - uint64_t t_ns; - uint64_t step_ns; /* clock advance per relax */ - uint64_t relaxes; - uint64_t barriers; - uint64_t at[32]; - volatile uint32_t *target[32]; - uint32_t value[32]; - int nsched; - uint32_t invalid_value; /* valid() rejects this value when nonzero */ - int abort_at; /* abort() true once relaxes >= abort_at when nonzero */ - uint64_t snaps; /* polls seen by the snapshot hook (it runs right after the reads) */ - uint64_t last_snap_barriers; - uint64_t order_violations; /* polls whose reads were not preceded by a fresh barrier */ -} Fake; - -static uint64_t fk_now(void *c) { return ((Fake *)c)->t_ns; } -static void fk_barrier(void *c) { ((Fake *)c)->barriers++; } -static void fk_relax(void *c) { - Fake *f = c; - f->relaxes++; - f->t_ns += f->step_ns; - for (int i = 0; i < f->nsched; i++) - if (f->at[i] == f->relaxes) *f->target[i] = f->value[i]; -} -static void fk_snapshot(void *c, uint32_t out[2]) { - Fake *f = c; - out[0] = out[1] = 0; - f->snaps++; - if (f->barriers <= f->last_snap_barriers) f->order_violations++; - f->last_snap_barriers = f->barriers; -} -static bool fk_valid(void *c, uint32_t v) { return !((Fake *)c)->invalid_value || v != ((Fake *)c)->invalid_value; } -static bool fk_abort(void *c) { Fake *f = c; return f->abort_at && f->relaxes >= (uint64_t)f->abort_at; } - -typedef bool (*WaitFn)(volatile uint32_t *, uint32_t, omega_gpu_wait_report_t *, const omega_gpu_wait_cfg_t *); - -/* Mutants. mode 0: naive wall clock (single deadline, unsigned <, no progress - * tracking, no marker2, no barrier, no report). mode 1: exact for sequence too - * is not needed; mode "fixed_ge": signed >= for a fixed wait. mode "seq_unsigned": - * unsigned >= for a sequence wait. The last two keep everything else correct. */ -static bool naive_wait(volatile uint32_t *word, uint32_t want, omega_gpu_wait_report_t *rpt, - const omega_gpu_wait_cfg_t *cfg) { - uint64_t start = cfg->now_ns(cfg->hook_ctx); - uint64_t lim = 1000000ull * cfg->progress_timeout_ms; - if (rpt) memset(rpt, 0, sizeof(*rpt)); - while (*word < want) { - if (cfg->now_ns(cfg->hook_ctx) - start >= lim) return false; - cfg->relax(cfg->hook_ctx); - } - return true; -} -static bool mut_loop(int cmp, volatile uint32_t *w, uint32_t want, omega_gpu_wait_report_t *rpt, - const omega_gpu_wait_cfg_t *cfg, omega_gpu_wait_kind_t kind) { - /* Correct kind-aware wait with one comparison replaced; delegate the rest - * to the real primitive by wrapping the watched value would be circular, so - * implement the minimal real loop here. */ - uint64_t start = cfg->now_ns(cfg->hook_ctx), last = start; - uint64_t stall = 1000000ull * cfg->progress_timeout_ms; - uint32_t prev = *w; - if (rpt) { memset(rpt, 0, sizeof(*rpt)); rpt->wait_kind = kind; rpt->expected = want; } - for (;;) { - cfg->barrier(cfg->hook_ctx); - uint32_t m = *w, m2 = cfg->marker2 ? *cfg->marker2 : 0; - bool ok = cmp == 0 ? m == want : cmp == 1 ? (int32_t)(m - want) >= 0 : m >= want; - if (rpt) { rpt->last_observed = m; rpt->last_marker2 = m2; } - if (ok && (!cfg->marker2 || m2 == cfg->marker2_want)) { - cfg->barrier(cfg->hook_ctx); - if (rpt) rpt->result = OMEGA_GPU_WAIT_PASS; - return true; - } - uint64_t now = cfg->now_ns(cfg->hook_ctx); - if (m != prev) { prev = m; last = now; if (rpt) rpt->progress_count++; } - if (now - last >= stall) { if (rpt) rpt->result = OMEGA_GPU_WAIT_STALLED; return false; } - cfg->relax(cfg->hook_ctx); - } -} -static bool mut_fixed_ge(volatile uint32_t *w, uint32_t v, omega_gpu_wait_report_t *r, const omega_gpu_wait_cfg_t *c) { - return mut_loop(1, w, v, r, c, OMEGA_GPU_WAIT_FIXED); -} -static bool mut_seq_unsigned(volatile uint32_t *w, uint32_t v, omega_gpu_wait_report_t *r, const omega_gpu_wait_cfg_t *c) { - return mut_loop(2, w, v, r, c, OMEGA_GPU_WAIT_SEQUENCE); -} - -static int g_fail, g_checks, g_quiet; -#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_fail++; if (!g_quiet) { printf(" FAIL: " __VA_ARGS__); printf("\n"); } } } while (0) - -static void setup(Fake *f, omega_gpu_wait_cfg_t *cfg) { - memset(f, 0, sizeof(*f)); - f->step_ns = 1000000ull; /* 1 ms per poll */ - memset(cfg, 0, sizeof(*cfg)); - cfg->progress_timeout_ms = 100; - cfg->total_timeout_ms = 100000; - cfg->now_ns = fk_now; - cfg->barrier = fk_barrier; - cfg->relax = fk_relax; - cfg->valid = fk_valid; - cfg->abort = fk_abort; - cfg->hook_ctx = f; -} -static void sched(Fake *f, uint64_t at, volatile uint32_t *t, uint32_t v) { - f->at[f->nsched] = at; f->target[f->nsched] = t; f->value[f->nsched] = v; f->nsched++; -} - -enum { S_NEVER, S_LATE, S_MARKER2, S_SEQ_WRAP, S_PROGRESS_RESETS, S_BARRIER, S_HARD_DEADLINE, - S_FIXED_OVERSHOOT, S_INVALID, S_ABORT, S_COUNT }; -static const char *names[S_COUNT] = {"never_written", "written_late", "marker2_gate", "seq_wrap32", - "progress_resets_idle", "barrier_each_read", "hard_deadline_with_progress", - "fixed_overshoot", "invalid_state", "abort"}; - -/* Returns failed checks. fx and sq are the fixed and sequence implementations. */ -static int scenario(const char *name, WaitFn fx, WaitFn sq, int which) { - volatile uint32_t w = 0, w2 = 0; - Fake f; - omega_gpu_wait_cfg_t cfg; - omega_gpu_wait_report_t r; - int before = g_fail; - bool ok; - setup(&f, &cfg); - - switch (which) { - case S_NEVER: - ok = sq(&w, 5, &r, &cfg); - CHECK(!ok, "%s: never-written marker must not pass", name); - CHECK(r.result == OMEGA_GPU_WAIT_STALLED, "%s: result STALLED (got %d)", name, r.result); - CHECK(r.last_observed == 0 && r.expected == 5 && r.wait_kind == OMEGA_GPU_WAIT_SEQUENCE, - "%s: report carries kind/expected/last-seen 0", name); - CHECK(r.elapsed_ns >= 100000000ull && r.progress_count == 0, "%s: elapsed %llu progress %llu", name, - (unsigned long long)r.elapsed_ns, (unsigned long long)r.progress_count); - break; - case S_LATE: - sched(&f, 60, &w, 7); - ok = fx(&w, 7, &r, &cfg); - CHECK(ok && r.result == OMEGA_GPU_WAIT_PASS && r.last_observed == 7, "%s: late fixed marker seen", name); - CHECK(r.progress_count == 1 && r.last_progress_ns > r.start_ns, "%s: progress recorded", name); - break; - case S_MARKER2: - cfg.marker2 = &w2; - cfg.marker2_want = 0x46464646u; - sched(&f, 10, &w, 3); - ok = fx(&w, 3, &r, &cfg); - CHECK(!ok, "%s: marker without marker2 must not pass", name); - CHECK(r.last_observed == 3 && r.last_marker2 == 0, "%s: report shows marker 3, marker2 0", name); - w = 0; w2 = 0; setup(&f, &cfg); - cfg.marker2 = &w2; - cfg.marker2_want = 0x46464646u; - sched(&f, 10, &w, 3); - sched(&f, 20, &w2, 0x46464646u); - ok = fx(&w, 3, &r, &cfg); - CHECK(ok && r.last_marker2 == 0x46464646u, "%s: both markers pass", name); - break; - case S_SEQ_WRAP: { - static const uint32_t tg[4] = {0xfffffffeu, 0xffffffffu, 0u, 1u}; - for (int i = 0; i < 4; i++) { - w = tg[i] - 1u; /* one step behind, wrapping through 0 */ - setup(&f, &cfg); - sched(&f, 10, &w, tg[i]); - ok = sq(&w, tg[i], &r, &cfg); - CHECK(ok, "%s: reaches target %08x from %08x", name, tg[i], tg[i] - 1u); - } - w = 3; setup(&f, &cfg); - ok = sq(&w, 0xffffffffu, &r, &cfg); - CHECK(ok, "%s: 3 is past 0xffffffff", name); - w = 0; setup(&f, &cfg); - ok = sq(&w, 0xfffffffeu, &r, &cfg); - CHECK(ok, "%s: 0 is past 0xfffffffe", name); - w = 0xfffffff0u; setup(&f, &cfg); - ok = sq(&w, 0xffffffffu, &r, &cfg); - CHECK(!ok, "%s: 0xfffffff0 is before 0xffffffff", name); - w = 0xfffffffeu; setup(&f, &cfg); - ok = sq(&w, 1, &r, &cfg); - CHECK(!ok, "%s: 0xfffffffe is before 1", name); - break; - } - case S_PROGRESS_RESETS: - for (int i = 0; i < 4; i++) sched(&f, 60u * (i + 1), &w, (uint32_t)(i + 1)); - ok = sq(&w, 4, &r, &cfg); /* 240 ms total, 60 ms gaps, 100 ms stall bound */ - CHECK(ok, "%s: steady progress must not stall", name); - CHECK(r.progress_count == 4, "%s: progress_count %llu", name, (unsigned long long)r.progress_count); - break; - case S_BARRIER: - sched(&f, 5, &w, 1); - cfg.snapshot = fk_snapshot; /* runs after the reads of each poll: marks where the read happened */ - cfg.snapshot_ctx = &f; - ok = sq(&w, 1, &r, &cfg); - CHECK(ok && r.polls > 0 && f.barriers >= r.polls + 1, "%s: barriers %llu polls %llu", name, - (unsigned long long)f.barriers, (unsigned long long)r.polls); - CHECK(f.snaps == r.polls && f.order_violations == 0, "%s: a barrier must precede every read (%llu of %llu polls unordered)", name, - (unsigned long long)f.order_violations, (unsigned long long)f.snaps); - CHECK(f.barriers > f.last_snap_barriers, "%s: barrier after the PASS observation", name); - break; - case S_HARD_DEADLINE: - cfg.total_timeout_ms = 200; - for (int i = 0; i < 30; i++) sched(&f, (uint64_t)(20 * (i + 1)), &w, (uint32_t)(i + 1)); - ok = sq(&w, 99, &r, &cfg); /* moves every 20 ms, never arrives */ - CHECK(!ok && r.result == OMEGA_GPU_WAIT_TIMEOUT, "%s: hard deadline TIMEOUT (got %d)", name, r.result); - CHECK(r.progress_count > 3, "%s: progress was occurring (%llu)", name, (unsigned long long)r.progress_count); - break; - case S_FIXED_OVERSHOOT: - sched(&f, 10, &w, 5); /* jumps past the fixed value 3 */ - ok = fx(&w, 3, &r, &cfg); - CHECK(!ok, "%s: fixed wait must not accept overshoot 5 for 3", name); - CHECK(r.result == OMEGA_GPU_WAIT_STALLED && r.last_observed == 5, "%s: stalled, saw 5", name); - w = 0; setup(&f, &cfg); - sched(&f, 10, &w, 5); - ok = sq(&w, 3, &r, &cfg); - CHECK(ok, "%s: sequence wait accepts 5 for target 3", name); - break; - case S_INVALID: - f.invalid_value = 9; - sched(&f, 10, &w, 9); - ok = sq(&w, 20, &r, &cfg); - CHECK(!ok && r.result == OMEGA_GPU_WAIT_INVALID_STATE && r.last_observed == 9, - "%s: invalid value reported (got %d)", name, r.result); - break; - case S_ABORT: - f.abort_at = 7; - ok = sq(&w, 20, &r, &cfg); - CHECK(!ok && r.result == OMEGA_GPU_WAIT_ABORTED, "%s: abort reported (got %d)", name, r.result); - break; - } - return g_fail - before; -} - -/* CHIPWAIT-1c: QUEUE_WRAP marker2 pattern (src/omega_world_gates.c). Every entry of a - * batch but the last writes its dispatch_id to marker2; the last writes the sentinel - * 0x46464646. A sequence wait for the sentinel must not accept dispatch ids (even a - * high one), and must pass when the sentinel lands. */ -static int sentinel_batch(void) { - volatile uint32_t w2 = 0; - Fake f; - omega_gpu_wait_cfg_t cfg; - omega_gpu_wait_report_t r; - int before = g_fail; - setup(&f, &cfg); - for (uint32_t id = 1; id <= 15; id++) sched(&f, id, &w2, 3000u + id); - bool ok = omega_gpu_wait_sequence(&w2, 0x46464646u, &r, &cfg); - CHECK(!ok && r.result == OMEGA_GPU_WAIT_STALLED && r.last_observed == 3015u, - "sentinel: dispatch ids alone must not satisfy the sentinel wait (got %d, observed %u)", r.result, r.last_observed); - w2 = 0; - setup(&f, &cfg); - for (uint32_t id = 1; id <= 15; id++) sched(&f, id, &w2, 3000u + id); - sched(&f, 16, &w2, 0x46464646u); - ok = omega_gpu_wait_sequence(&w2, 0x46464646u, &r, &cfg); - CHECK(ok && r.result == OMEGA_GPU_WAIT_PASS && r.last_observed == 0x46464646u, - "sentinel: last entry's sentinel passes (got %d, observed %u)", r.result, r.last_observed); - return g_fail - before; -} - -typedef struct { - const char *label; - WaitFn fx, sq; - unsigned must_kill; /* bitmask of scenarios that must kill this mutant */ -} Mutant; - -int main(void) { - for (int s = 0; s < S_COUNT; s++) { - int bad = scenario(names[s], omega_gpu_wait_fixed, omega_gpu_wait_sequence, s); - printf("real %-28s %s\n", names[s], bad ? "FAIL" : "ok"); - } - { int bad = sentinel_batch(); printf("real %-28s %s\n", "queue_wrap_sentinel", bad ? "FAIL" : "ok"); } - int real_fail = g_fail; - - const Mutant muts[] = { - {"naive_wall_clock", naive_wait, naive_wait, (1u << S_COUNT) - 1u}, - {"fixed_accepts_overshoot", mut_fixed_ge, omega_gpu_wait_sequence, 1u << S_FIXED_OVERSHOOT}, - {"seq_unsigned_compare", omega_gpu_wait_fixed, mut_seq_unsigned, 1u << S_SEQ_WRAP}, - }; - int saved = g_fail, kill_total = 0, kill_need = 0; - g_quiet = 1; - for (unsigned m = 0; m < sizeof(muts) / sizeof(muts[0]); m++) { - unsigned killed = 0; - for (int s = 0; s < S_COUNT; s++) { - if (scenario(names[s], muts[m].fx, muts[m].sq, s) > 0) killed |= 1u << s; - } - g_fail = saved; - g_quiet = 0; - for (int s = 0; s < S_COUNT; s++) { - if (!(muts[m].must_kill & (1u << s))) continue; - kill_need++; - g_checks++; - if (killed & (1u << s)) kill_total++; - else { g_fail++; printf(" FAIL: mutant %s survived scenario %s\n", muts[m].label, names[s]); } - } - printf("mutant %-26s killed mask %03x (required %03x)\n", muts[m].label, killed, muts[m].must_kill); - saved = g_fail; - g_quiet = 1; - } - g_quiet = 0; - printf("gpu_wait: checks=%d real_failures=%d required_kills=%d/%d\n", g_checks, real_fail, kill_total, kill_need); - printf("%s\n", g_fail ? "OMEGA_GPU_WAIT_HOST FAIL" : "OMEGA_GPU_WAIT_HOST PASS"); - return g_fail ? 1 : 0; -} diff --git a/tools/.crumb b/tools/.crumb index b2b573d7c..2db9f60d4 100644 --- a/tools/.crumb +++ b/tools/.crumb @@ -26,50 +26,50 @@ "children": [ { "digest": "9f82d33852a7cdcedb210ee1525f42c4d963c18940cae1df7f69d1210de71985", - "last_commit": "6d7b8838", + "last_commit": "d863780eb", "name": "argus", "purpose": "Directory tools/argus. Purpose not yet described by a human." }, { "digest": "4b3a030252eaa6f1c693105a76092e8a5fccfd340658a982f5bb1130ce9aba33", - "last_commit": "6d7b8838", + "last_commit": "d863780eb", "name": "brownian", "purpose": "Directory tools/brownian. Purpose not yet described by a human." }, { "digest": "1d21e7e466d0fd96abf30d11b2d7e45718bc42ada1784bc8bc2a749f541b3ab7", - "last_commit": "6d7b8838", + "last_commit": "d863780eb", "name": "dual_experiment", "purpose": "Runner for the DUAL applicability experiment: runs the pre-registered campaign and writes result" }, { "digest": "2a1bd46e9c9502d02144e3f76c784863001323c564a22bdae2905c0660a5f7a4", - "last_commit": "6d7b8838", + "last_commit": "d863780eb", "name": "estimation", "purpose": "Directory tools/estimation. Purpose not yet described by a human." }, { "digest": "b3241d8cdc884bbfcca5cf9d5f4ed0aac8f7e2df43d9ab47ca2789432dd49a75", - "last_commit": "6d7b8838", + "last_commit": "d863780eb", "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": "6d7b8838", + "last_commit": "d863780eb", "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-31T02:35:18Z", + "compiled_at": "2026-10-31T13:05:45Z", "compiler": "crumb-compile/1", - "digest": "sha256:c9c0eb6fcb03f5be2576714a9b49e2ead49190277059fcbbd253f49db07c047d", + "digest": "sha256:d4c5b2b33f12a1d46e845315d1e5ec71c40b7104ecaef4542ceebede179c5f54", "evidence_files": 17, "evidence_root": "sha256:47b1bcb263a96edaab5a4a5214d92ebc385d5511b120201567d280410a749703", - "files": 412, - "generated_at_commit": "6d7b883844a0f17a7a3ceb427108be7e01e4c677", - "source_tree": "sha256:757ae5bba9d7b33f785803527c6548b5232595a913555ea2c21211f9cf5ceb54" + "files": 410, + "generated_at_commit": "ef2aba1488304ba91c342d80a54b4535f255711f", + "source_tree": "sha256:7b2f00751254fafd517bccb654b56ecb7164930d5bf1c0538f3d34316570a5b7" }, "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..917cd575b 100755 --- a/tools/e1_manifest.sh +++ b/tools/e1_manifest.sh @@ -33,7 +33,114 @@ # 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]|src/*.ident|tests/*.[ch]|om/*.om) ;; *) 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" + # Same rule for tests: the GPU twin tests were retired to CUDApp, so the + # canonical tests come first and Omega's retained tests overlay them. + cp -R "$source/tests" "$target/" + cp -R "$root/tests/." "$target/tests/" + # 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 +156,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 +170,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 +197,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 +225,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..556e86fcb 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" @@ -127,7 +129,7 @@ BE_FLUSH_OP_DROPPED~src/omega_blackwell_engine.c~R:pb_put(c, 0x10u << 27);@>@pb_ BE_FLUSH_METHOD_CHANGED~src/omega_blackwell_engine.c~R:pb_put(c, nvrm_mthd(0, 0x0028, 4));@>@pb_put(c, nvrm_mthd(0, 0x002c, 4));~the flush uses the memory-operation method BE_WFI_FLAG_RELEASE1~src/omega_blackwell_engine.c~/pb_put(c, OMEGA_BW_MARKER_COMPLETION_PAYLOAD);/,+2 s/0x1u | (1u << 20)/0x1u/~the first release waits for idle (WFI) BE_WFI_FLAG_RELEASE2~src/omega_blackwell_engine.c~/pb_put(c, BE_MARKER2_PAYLOAD);/,+2 s/0x1u | (1u << 20)/0x1u/~the second release waits for idle (WFI) -BE_BARRIER_IN_BUILD~src/omega_blackwell_engine.c~/^static int be_build/,/^}/ s/__asm__ volatile("dsb sy" ::: "memory");/(void)0;/~dsb sy after zeroing the sync words~redundant~a CPU barrier instruction has no effect a host test can observe (the fake driver runs on the same core); it is verified on the chip only (Phase B) +BE_BARRIER_IN_BUILD~src/omega_blackwell_engine.c~/^static int be_build/,/^}/ s/nvrm_cpu_barrier();/(void)0;/~dsb sy after zeroing the sync words~redundant~a CPU barrier instruction has no effect a host test can observe (the fake driver runs on the same core); it is verified on the chip only (Phase B) BE_QMD_RELEASE_CHECK~src/omega_blackwell_engine.c~R:if (qmd1_words[9] != 3u ||@>@if (0 ||~extra QMD1 release-word checks~redundant~the real descriptor builder always produces these words (src/omega_blackwell_qmd.c), so no input makes the check fire; it guards a future change of the builder, which tests/test_omega_blackwell_qmd.c style checks cover BE_PB_OVERFLOW~src/omega_blackwell_engine.c~R:if (c->pb_overflow) {@>@if (0) {~pushbuffer word-capacity guard~redundant~the vector pushbuffer is a fixed 492 words against a 1024-word capacity, so it cannot overflow for any job # ---- submit, waits, diagnostics ------------------------------------------------------ @@ -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..96d6b6cef 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,30 @@ 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 +# The chip test was retired to CUDApp with the engine: build the authenticated copy. +[ -s "$canonical_root/$TEST_SOURCE" ] || return 2 +TEST_SOURCE=$canonical_root/$TEST_SOURCE +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..779241f27 100755 --- a/tools/probe_gpu_open.sh +++ b/tools/probe_gpu_open.sh @@ -31,6 +31,9 @@ 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 \ + tests/gpu_session_probe.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 +61,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 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..7f37a72d2 100755 --- a/tools/run_gpu_cut4b_chip.sh +++ b/tools/run_gpu_cut4b_chip.sh @@ -35,6 +35,12 @@ 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 \ + tests/gpu_elementwise_test.c tests/gpu_attention_test.c tests/gpu_matmul_api_test.c || 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 +68,10 @@ 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) +(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..c3b29c09f 100755 --- a/tools/run_gpu_elementwise_chip.sh +++ b/tools/run_gpu_elementwise_chip.sh @@ -28,6 +28,9 @@ 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 \ + tests/gpu_elementwise_test.c || 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 +43,10 @@ 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) +(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_fp8_slots_chip.sh b/tools/run_gpu_fp8_slots_chip.sh index 412875073..4bc21641d 100755 --- a/tools/run_gpu_fp8_slots_chip.sh +++ b/tools/run_gpu_fp8_slots_chip.sh @@ -18,11 +18,13 @@ cd "$HERE" || exit 2 uname -a; nvidia-smi --query-gpu=name,driver_version --format=csv,noheader 2>/dev/null; free -g | head -2 } > "$EVID/device.txt" make PHYSICS_DIR="$PHYS" -j10 build/gpu_fp8_slots_test > "$EVID/build.log" 2>&1 || { echo "GPU_FP8_SLOTS_CHIP: FAIL build"; exit 1; } -# A stale nvrm.o compiled from another physics checkout survives a PHYSICS_DIR change (make sees it up to -# date) and changes the allocator under the test: refuse the run unless nvrm.o came from $PHYS. -NVRM_D=$(find build -name nvrm.d | head -1) -if [ -z "$NVRM_D" ] || ! grep -q "$(cd "$PHYS" && pwd)/nvrm/nvrm.c" "$NVRM_D"; then - echo "GPU_FP8_SLOTS_CHIP: FAIL build (nvrm.o not built from $PHYS; rm -rf build and rerun)"; exit 1 +# nvrm.o is no longer built from $PHYS: it is part of libcudapp.a in the CUDApp stage the Makefile links. +# Refuse the run unless that stage verifies against cudapp.lock and holds its own nvrm build. +STAGE=${CUDAPP_STAGE:-${OUT_DIR:-build}/cudapp} +sh tools/cudapp-stage.sh --verify cudapp.lock "$STAGE" > "$EVID/cudapp-source.json" 2>> "$EVID/build.log" || + { echo "GPU_FP8_SLOTS_CHIP: FAIL build (CUDApp stage $STAGE does not verify against cudapp.lock)"; exit 1; } +if [ ! -s "$STAGE/build/nvrm.d" ] || ! grep -q '^ *nvrm/nvrm\.c ' "$STAGE/build/nvrm.d"; then + echo "GPU_FP8_SLOTS_CHIP: FAIL build (nvrm.o not built in the CUDApp stage $STAGE; rm -rf build and rerun)"; exit 1 fi T=./build/gpu_fp8_slots_test fail=0 diff --git a/tools/run_gpu_reconv_chip.sh b/tools/run_gpu_reconv_chip.sh index 5ac5c822b..bc7acbbc4 100755 --- a/tools/run_gpu_reconv_chip.sh +++ b/tools/run_gpu_reconv_chip.sh @@ -37,6 +37,10 @@ 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 src/cudapp_om_units.ident \ + om/encoder/bw_enc_sm121.om tests/gpu_reconv_test.c tests/bw_warp_sim.h || 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 +54,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 \ - om/encoder/bw_enc_sm121.om src/omega_om_units.ident tests/gpu_reconv_test.c tests/bw_warp_sim.h "$OUT/" -(cd "$OUT" && sha256sum -- * > SHA256SUMS) +cp src/omega_om_units.ident "$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/runtime_api_check.sh b/tools/runtime_api_check.sh deleted file mode 100755 index 74b6af9af..000000000 --- a/tools/runtime_api_check.sh +++ /dev/null @@ -1,195 +0,0 @@ -#!/bin/sh -# runtime_api_check.sh -- host check of the Omega Runtime API manifest against the C headers (no GPU, no physics). -# -# tools/runtime_api_check.sh [--bless] MANIFEST ROOT WORK_DIR [API_MD] -# -# MANIFEST docs/runtime/omega_runtime_api.manifest (line format: docs/runtime/API.md, "The manifest") -# ROOT directory the manifest's `header` paths are relative to (the omega checkout; a copy in the negative controls) -# WORK_DIR scratch directory for the generated probe -# API_MD optional: also check that API.md states the version and has a section for every STABLE entry -# -# What it does: writes a C probe from the manifest and compiles it against the headers named there. -# - every `fn` line becomes a compile-time type-equality check on the function itself, so a removed function, a changed argument -# type or a changed return type is a compile error (-Werror=incompatible-pointer-types); -# - every `struct`/`field`/`const` line becomes a printf of sizeof/alignof/offsetof/value, compared with the manifest; -# - the version macros OMEGA_RUNTIME_API_VERSION_MAJOR/MINOR must exist (#error otherwise) and equal the manifest. -# With API_MD it also scans the headers back (gcc -aux-info): every external function a listed header declares must be a -# manifest `fn` or be a leading name of a bullet in API.md section 10 (INTERNAL), never both, and every such name must still be declared. So a new public -# function is seen. Not seen: a new struct or constant (no manifest line, nothing to compare), a field added inside struct -# padding that the manifest does not list (the struct size would not change), and a field that changes type but keeps its -# size (int -> unsigned). sovereign-core's Rust checker, which reads field names, covers the field cases later (R12). -# It does not link the library and does not touch the GPU. -# --bless prints the manifest to stdout with struct/field/const numbers taken from the headers (review the diff). -# Exit 0 = PASS, 1 = FAIL (each mismatch printed as "FAIL: ..."), 2 = usage. -set -u -BLESS=0 -if [ "${1:-}" = "--bless" ]; then BLESS=1; shift; fi -[ $# -ge 3 ] || { echo "usage: $0 [--bless] MANIFEST ROOT WORK_DIR [API_MD]" >&2; exit 2; } -MANIFEST=$1; ROOT=$(cd "$2" && pwd) || exit 2; WORK=$3; APIMD=${4:-} -CC=${CC:-cc} -mkdir -p "$WORK" || exit 2 -PROBE=$WORK/probe.c; ITEMS=$WORK/items.txt; GOT=$WORK/got.txt; WANT=$WORK/want.txt -fail=0 -say_fail() { echo "FAIL: $*"; fail=1; } - -# ---- 1. manifest -> probe source ------------------------------------------------------------------------- -awk -v root="$ROOT" -v items="$ITEMS" ' -function trim(s) { gsub(/^[ \t]+|[ \t]+$/, "", s); return s } -function base(t) { - if (t == "u8") return "uint8_t"; if (t == "u16") return "uint16_t"; if (t == "u32") return "uint32_t" - if (t == "u64") return "uint64_t"; if (t == "i8") return "int8_t"; if (t == "i16") return "int16_t" - if (t == "i32") return "int32_t"; if (t == "i64") return "int64_t"; if (t == "f32") return "float" - if (t == "f64") return "double"; if (t == "usize") return "size_t"; if (t == "c_char") return "char" - if (t == "c_void" || t == "()" || t == "") return "void" - return t -} -function ctype(t, r) { - t = trim(t) - if (t ~ /^\*const /) { r = ctype(substr(t, 8)); return (r ~ /\*$/) ? r " const *" : "const " r " *" } - if (t ~ /^\*mut /) { return ctype(substr(t, 6)) " *" } - if (t ~ /^fn\(/) { nfp++; fptd = fptd "typedef " fnsig(t, "(*FP" nfp ")") ";\n"; return "FP" nfp } - return base(t) -} -# "fn(a, b) -> r" as a C declarator named nm -function fnsig(s, nm, depth, i, c, cl, params, ret, n, parts, k, out) { - s = trim(s); sub(/^fn/, "", s); s = trim(s) - depth = 0; cl = 0 - for (i = 1; i <= length(s); i++) { c = substr(s, i, 1) - if (c == "(") depth++ - if (c == ")") { depth--; if (depth == 0) { cl = i; break } } } - params = substr(s, 2, cl - 2); ret = trim(substr(s, cl + 1)); sub(/^->/, "", ret) - n = splitparams(params, parts); out = "" - for (k = 1; k <= n; k++) out = out (k > 1 ? ", " : "") ctype(parts[k]) - if (n == 0) out = "void" - return ctype(ret) " " nm "(" out ")" -} -function splitparams(s, parts, i, c, depth, cur, n) { - n = 0; cur = ""; depth = 0 - for (i = 1; i <= length(s); i++) { c = substr(s, i, 1) - if (c == "(") depth++ - if (c == ")") depth-- - if (c == "," && depth == 0) { parts[++n] = trim(cur); cur = ""; continue } - cur = cur c } - if (trim(cur) != "") parts[++n] = trim(cur) - return n -} -function item(line) { k++; print k "\t" line > items; return sprintf("#if !defined(ONLY) || ONLY == %d\n", k) } -BEGIN { k = 0; nfp = 0; fptd = "" } -{ line = $0; sub(/#.*/, "", line); line = trim(line); if (line == "") next - nw = split(line, w, /[ \t]+/) - if (w[1] == "header") { inc = inc "#include \"" root "/" w[2] "\"\n"; next } - if (w[1] == "abi") next - if (w[1] == "struct") { body = body item(line) " printf(\"struct " w[2] " %zu %zu\\n\", sizeof(" w[2] "), _Alignof(" w[2] "));\n#endif\n"; next } - if (w[1] == "field") { body = body item(line) " printf(\"field " w[2] " " w[3] " %zu %zu\\n\", offsetof(" w[2] ", " w[3] "), sizeof(((" w[2] " *)0)->" w[3] "));\n#endif\n"; next } - if (w[1] == "const") { body = body item(line) " printf(\"const " w[2] " %lld\\n\", (long long)(" w[2] "));\n#endif\n"; next } - if (w[1] == "fn") { rest = line; sub(/^fn[ \t]+[^ \t]+[ \t]+/, "", rest) - decl = decl item(line) "_Static_assert(__builtin_types_compatible_p(__typeof__(" w[2] "), " fnsig(rest, "") "), \"signature of " w[2] "\");\n#endif\n"; next } - print "manifest: unknown or malformed line: " $0 > "/dev/stderr"; bad = 1 } -END { - print "#include \n#include \n#include \n#include " - print "#include \"" root "/src/omega_runtime_api.h\"" - print "#ifndef OMEGA_RUNTIME_API_VERSION_MAJOR\n#error \"version macro missing: OMEGA_RUNTIME_API_VERSION_MAJOR\"\n#endif" - print "#ifndef OMEGA_RUNTIME_API_VERSION_MINOR\n#error \"version macro missing: OMEGA_RUNTIME_API_VERSION_MINOR\"\n#endif" - printf "%s", inc - printf "%s", fptd - printf "%s", decl - print "int main(void) {\n printf(\"const OMEGA_RUNTIME_API_VERSION_MAJOR %lld\\n\", (long long)(OMEGA_RUNTIME_API_VERSION_MAJOR));" - print " printf(\"const OMEGA_RUNTIME_API_VERSION_MINOR %lld\\n\", (long long)(OMEGA_RUNTIME_API_VERSION_MINOR));" - printf "%s", body - print " return 0;\n}" - exit bad -}' "$MANIFEST" > "$PROBE" || { echo "FAIL: manifest could not be turned into a probe"; exit 1; } - -# ---- 2. compile (all at once; on failure name each failing manifest line) -------------------------------- -CFL="-std=gnu11 -Wall -Wextra -Werror -Werror=implicit-function-declaration -D_GNU_SOURCE -I$ROOT/src" -if ! $CC $CFL -o "$WORK/probe" "$PROBE" 2> "$WORK/cc.err"; then - named=0 - if ! $CC $CFL -DONLY=0 -fsyntax-only "$PROBE" 2> "$WORK/cc0.err"; then - say_fail "version macros or headers do not compile:"; grep -m3 error "$WORK/cc0.err" | sed "s/^/ /" - else - while IFS=" " read -r n text; do - if ! $CC $CFL -DONLY="$n" -fsyntax-only "$PROBE" 2> /dev/null; then say_fail "header disagrees with manifest: $text"; named=1; fi - done < "$ITEMS" - if [ $named = 0 ]; then say_fail "probe does not compile:"; grep -m5 'error' "$WORK/cc.err" | sed 's/^/ /'; fi - fi - echo "RESULT: FAIL (runtime API check, compile stage)"; exit 1 -fi -"$WORK/probe" > "$GOT" || { echo "FAIL: probe crashed"; exit 1; } - -# ---- 3. bless or compare --------------------------------------------------------------------------------- -if [ $BLESS = 1 ]; then - awk 'NR == FNR { g[$1 " " $2 (($1 == "field") ? " " $3 : "")] = $0; next } - { raw = $0; line = raw; sub(/#.*/, "", line); n = split(line, w, /[ \t]+/); cm = "" - if (match(raw, /#.*/)) cm = " " substr(raw, RSTART) - if (w[1] == "struct") { split(g["struct " w[2]], v, " "); print "struct " w[2] " " v[3] " " v[4] cm; next } - if (w[1] == "field") { split(g["field " w[2] " " w[3]], v, " "); print "field " w[2] " " w[3] " " v[4] " " v[5] " " w[6] " " w[7] cm; next } - if (w[1] == "const") { split(g["const " w[2]], v, " "); print "const " w[2] " " v[3] cm; next } - print raw }' "$GOT" "$MANIFEST" - exit 0 -fi - -# manifest facts without kind/count and without comments, in file order -awk '{ sub(/#.*/, ""); n = split($0, w, /[ \t]+/); if (w[1] == "struct") print "struct " w[2] " " w[3] " " w[4] - else if (w[1] == "field") print "field " w[2] " " w[3] " " w[4] " " w[5]; else if (w[1] == "const") print "const " w[2] " " w[3] }' "$MANIFEST" > "$WANT" -while IFS= read -r l; do - grep -qxF "$l" "$GOT" || { key=$(echo "$l" | awk '{ print $1 " " $2 (($1 == "field") ? " " $3 : "") }') - have=$(grep -F "$key " "$GOT" | head -1); say_fail "manifest says \`$l\` but the header gives \`${have:-(absent)}\`"; } -done < "$WANT" - -# manifest sanity: tier tag on every struct/fn line, field size matches its kind, version consts present -awk '{ raw = $0; line = raw; sub(/#.*/, "", line); n = split(line, w, /[ \t]+/) - if (w[1] == "struct" || w[1] == "fn") { if (raw !~ /#[ \t]*(STABLE|EXPERIMENTAL)([ \t]|$)/) print "FAIL: " w[1] " " w[2] " has no STABLE/EXPERIMENTAL tag" } - if (w[1] == "field") { ks["u8"]=1; ks["i8"]=1; ks["bool"]=1; ks["c_char"]=1; ks["u16"]=2; ks["i16"]=2; ks["u32"]=4; ks["i32"]=4; ks["f32"]=4 - ks["enum"]=4; ks["u64"]=8; ks["i64"]=8; ks["f64"]=8; ks["ptr"]=8 - if (w[6] in ks && w[5] != ks[w[6]] * w[7]) print "FAIL: field " w[2] "." w[3] " size " w[5] " does not match kind " w[6] " x " w[7] } }' "$MANIFEST" > "$WORK/sanity.txt" -if [ -s "$WORK/sanity.txt" ]; then cat "$WORK/sanity.txt"; fail=1; fi -vmaj=$(awk '$1 == "const" && $2 == "OMEGA_RUNTIME_API_VERSION_MAJOR" { print $3 }' "$MANIFEST") -vmin=$(awk '$1 == "const" && $2 == "OMEGA_RUNTIME_API_VERSION_MINOR" { print $3 }' "$MANIFEST") -[ -n "$vmaj" ] && [ -n "$vmin" ] || say_fail "manifest does not list OMEGA_RUNTIME_API_VERSION_MAJOR and _MINOR" - -# API.md: states the version, has a section for every STABLE entry and mentions every EXPERIMENTAL one -if [ -n "$APIMD" ]; then - grep -q "^Omega Runtime API version: $vmaj\.$vmin\$" "$APIMD" || say_fail "$APIMD must contain the line \"Omega Runtime API version: $vmaj.$vmin\"" - awk '{ raw = $0; line = raw; sub(/#.*/, "", line); split(line, w, /[ \t]+/) - if ((w[1] == "fn" || w[1] == "struct") && match(raw, /#[ \t]*(STABLE|EXPERIMENTAL)/)) { t = substr(raw, RSTART); print w[2], (t ~ /STABLE/ && t !~ /EXPERIMENTAL/) ? "STABLE" : "EXPERIMENTAL" } }' "$MANIFEST" | - while read -r name tier; do - if [ "$tier" = STABLE ]; then grep -q "^#### \`$name\`" "$APIMD" || echo "FAIL: STABLE entry $name has no \"#### \`$name\`\" section in $APIMD" - else grep -qF "\`$name\`" "$APIMD" || echo "FAIL: EXPERIMENTAL entry $name is not mentioned in $APIMD"; fi - done > "$WORK/apimd.txt" - if [ -s "$WORK/apimd.txt" ]; then cat "$WORK/apimd.txt"; fail=1; fi - # every C signature quoted in API.md (lines inside a plain ```c fence that end in `);`) must be in a header, comments removed - for h in $(awk '$1 == "header" { print $2 }' "$MANIFEST"); do perl -0777 -pe 's{/\*.*?\*/}{}gs' "$ROOT/$h"; done | tr '\n' ' ' | sed 's/[[:space:]][[:space:]]*/ /g' | sed 's/^/ /' > "$WORK/headers.norm" - awk '/^```c$/ { f = 1; next } /^```/ { f = 0 } f && /\);[ \t]*$/ { print }' "$APIMD" | sed 's/[[:space:]][[:space:]]*/ /g; s/^ //; s/ $//' | - while IFS= read -r sig; do grep -qF -- " $sig" "$WORK/headers.norm" || echo "FAIL: signature quoted in $APIMD but in no header: $sig"; done > "$WORK/sigs.txt" - if [ -s "$WORK/sigs.txt" ]; then cat "$WORK/sigs.txt"; fail=1; fi - # headers -> manifest: every external function a listed header declares is a manifest `fn` or is named INTERNAL in - # API.md section 10, and every name section 10 lists is still declared. gcc -aux-info writes each declaration with the - # file it came from, so a function added to a header without a manifest line or an INTERNAL entry fails here. - # A name is INTERNAL only as a leading token of a section-10 bullet ("- `a`, `b` (prose `c`)": a and b, not c), so a - # manifest function mentioned in the prose is not taken as INTERNAL; a name that is both a manifest fn and INTERNAL fails. - if $CC $CFL -fsyntax-only -aux-info "$WORK/aux.txt" "$PROBE" 2> "$WORK/aux.err"; then - awk '/^## 10\./ { s = 1; next } /^## / { s = 0 } s && /^- `/ { t = substr($0, 3) - while (match(t, /^`omega_[a-z0-9_]+`/)) { print substr(t, 2, RLENGTH - 2); t = substr(t, RLENGTH + 1); if (t !~ /^, `/) break; t = substr(t, 3) } }' "$APIMD" | sort -u > "$WORK/internal.txt" - awk -v internal="$WORK/internal.txt" 'BEGIN { while ((getline l < internal) > 0) in10[l] = 1 } - FNR == NR { if ($1 == "header") hdr[$2] = 1; if ($1 == "fn") fn[$2] = 1; next } - /^\/\* .* \*\/ extern / { f = $2; sub(/:[0-9]+:[A-Z]+$/, "", f); listed = 0 - for (h in hdr) if (f == h || substr(f, length(f) - length(h)) == "/" h) { listed = 1; hf = h } - if (!listed) next - # the name is the identifier before the first "(" that does not open a declarator "(*" (a function returning a - # function pointer is written "int (*name (void)) (int)") - s = $0; sub(/^\/\* [^*]* \*\/ extern /, "", s); pre = "" - while ((i = index(s, "(")) > 0) { if (substr(s, i + 1) ~ /^ *\*/) { pre = pre substr(s, 1, i); s = substr(s, i + 1); continue } - pre = pre substr(s, 1, i - 1); break } - sub(/ +$/, "", pre); n = split(pre, a, /[^A-Za-z0-9_]+/); nm = a[n]; seen[nm] = 1 - if (!(nm in fn) && !(nm in in10)) print "FAIL: " hf " declares " nm ", which is neither a manifest fn nor named INTERNAL in API.md section 10" } - END { for (l in in10) { if (!(l in seen)) print "FAIL: API.md section 10 names " l " as INTERNAL but no listed header declares it" - if (l in fn) print "FAIL: API.md section 10 names " l " as INTERNAL but the manifest lists it as a fn" } }' "$MANIFEST" "$WORK/aux.txt" | sort > "$WORK/decls.txt" - if [ -s "$WORK/decls.txt" ]; then cat "$WORK/decls.txt"; fail=1; fi - else - say_fail "the header declaration scan needs a compiler with -aux-info (gcc; set CC=gcc):"; grep -m3 . "$WORK/aux.err" | sed 's/^/ /' - fi -fi - -nfn=$(grep -c '^fn ' "$MANIFEST"); nst=$(grep -c '^struct ' "$MANIFEST"); nfl=$(grep -c '^field ' "$MANIFEST"); nco=$(grep -c '^const ' "$MANIFEST") -if [ $fail = 0 ]; then echo "RESULT: PASS (runtime API $vmaj.$vmin: $nfn functions, $nst structs, $nfl fields, $nco constants match the headers)"; exit 0; fi -echo "RESULT: FAIL (runtime API check)"; exit 1 diff --git a/tools/runtime_api_negative.sh b/tools/runtime_api_negative.sh deleted file mode 100755 index 96af610d5..000000000 --- a/tools/runtime_api_negative.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/bin/sh -# runtime_api_negative.sh -- negative controls for tools/runtime_api_check.sh (R1, omega-mv#594). -# -# tools/runtime_api_negative.sh MANIFEST ROOT WORK_DIR API_MD -# -# Copies the headers to WORK_DIR, breaks the copy in one way at a time and runs the check on it. Each break must make -# the check FAIL and say the expected thing; if the check still passes, this script fails (the check cannot see that -# class of change). The real headers are never touched. -set -u -[ $# -eq 4 ] || { echo "usage: $0 MANIFEST ROOT WORK_DIR API_MD" >&2; exit 2; } -MANIFEST=$1; ROOT=$(cd "$2" && pwd) || exit 2; WORK=$3; APIMD=$4 -HERE=$(dirname "$0") -bad=0 -# control NAME EXPECTED_TEXT FILE SED_EXPR (FILE: a header under src/, API.md, or manifest) -control() { - name=$1; expect=$2; file=$3; expr=$4 - d=$WORK/neg-$name; rm -rf "$d"; mkdir -p "$d/src"; cp "$ROOT"/src/omega_*.h "$d/src/"; cp "$APIMD" "$d/API.md"; cp "$MANIFEST" "$d/manifest" - case $file in - API.md) sed -i "$expr" "$d/API.md"; orig=$APIMD; new=$d/API.md ;; - manifest) sed -i "$expr" "$d/manifest"; orig=$MANIFEST; new=$d/manifest ;; - *) sed -i "$expr" "$d/src/$file"; orig=$ROOT/src/$file; new=$d/src/$file ;; - esac - if cmp -s "$orig" "$new"; then echo "NEGATIVE CONTROL $name: BROKEN (the edit changed nothing)"; bad=1; return; fi - out=$("$HERE/runtime_api_check.sh" "$d/manifest" "$d" "$d/work" "$d/API.md" 2>&1); rc=$? - if [ $rc -ne 0 ] && printf '%s\n' "$out" | grep -qF "$expect"; then echo "NEGATIVE CONTROL $name: FAILED as it must ($expect)" - else echo "NEGATIVE CONTROL $name: NOT CAUGHT (rc=$rc, wanted \"$expect\")"; printf '%s\n' "$out" | head -5; bad=1; fi -} -control removed-function "header disagrees with manifest: fn omega_gpu_session_alloc_code" omega_gpu_session.h '/^int omega_gpu_session_alloc_code(/d' -control missing-version "version macro missing: OMEGA_RUNTIME_API_VERSION_MAJOR" omega_runtime_api.h '/define OMEGA_RUNTIME_API_VERSION_MAJOR/d' -control changed-signature "header disagrees with manifest: fn omega_gpu_session_free" omega_gpu_session.h 's/^void omega_gpu_session_free(OmegaGpuMem \*m);/void omega_gpu_session_free(const OmegaGpuMem *m);/' -control changed-struct 'manifest says `struct OmegaGpuLaunch ' omega_gpu_session.h 's/uint64_t timeout_ms; \/\*/uint32_t timeout_ms; \/*/' -control changed-constant 'manifest says `const OMEGA_GPU_SESSION_MAX_ARGS ' omega_gpu_session.h 's/OMEGA_GPU_SESSION_MAX_ARGS 32u/OMEGA_GPU_SESSION_MAX_ARGS 64u/' -control version-doc-mismatch "must contain the line \"Omega Runtime API version:" API.md 's/^Omega Runtime API version: .*/Omega Runtime API version: 9.9/' -control stable-without-doc "STABLE entry omega_gpu_session_launch has no" API.md 's/^#### `omega_gpu_session_launch`/#### launch/' -control wrong-quoted-signature "signature quoted in" API.md 's/^uint32_t omega_gpu_session_open_count(void);/uint64_t omega_gpu_session_open_count(void);/' -control signature-inside-another "signature quoted in" API.md 's/^uint32_t omega_gpu_session_open_count(void);/int32_t omega_gpu_session_open_count(void);/' -control removed-recover "header disagrees with manifest: fn omega_gpu_session_recover" omega_gpu_session.h '/^int omega_gpu_session_recover(void);/d' -control removed-padding-field "header disagrees with manifest: field OmegaGpuCmdListOpts first_barrier_none" omega_gpu_cmdlist.h '/int first_barrier_none;/,/\*\/$/d' -control new-header-function "omega_gpu_session.h declares omega_gpu_session_zzz_new, which is neither" omega_gpu_session.h '$a int omega_gpu_session_zzz_new(void);' -control internal-unlisted "omega_gpu_session.h declares omega_gpu_session_set_error, which is neither" API.md 's/^- `omega_gpu_session_set_error` (library code/- (library code/' -control manifest-fn-named-in-prose "omega_gpu_serving.h declares omega_gpu_serving_seal, which is neither" manifest '/^fn omega_gpu_serving_seal /d' -control internal-also-manifest "API.md section 10 names omega_gpu_session_launch as INTERNAL but the manifest lists it as a fn" API.md 's/^- `omega_gpu_session_set_error` (library code/- `omega_gpu_session_set_error`, `omega_gpu_session_launch` (library code/' -control new-fnptr-function "omega_gpu_session.h declares omega_gpu_session_zzz_fp, which is neither" omega_gpu_session.h '$a int (*omega_gpu_session_zzz_fp(void))(int);' -[ $bad = 0 ] && { echo "RESULT: PASS (every negative control was caught)"; exit 0; } -echo "RESULT: FAIL (a negative control was not caught)"; exit 1 diff --git a/tools/runtime_api_owner.sh b/tools/runtime_api_owner.sh new file mode 100755 index 000000000..cfb0e981d --- /dev/null +++ b/tools/runtime_api_owner.sh @@ -0,0 +1,92 @@ +#!/bin/sh +# 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. + +# tools/runtime_api_owner.sh -- what omega still owns of the Omega Runtime API after the move to CUDApp (omega-mv#924). +# +# tools/runtime_api_owner.sh +# +# CUDApp owns the Runtime API: docs/runtime/API.md, the manifest and its INTERNAL list, the manifest headers and the +# checkers (CUDApp gate CUDAPP-RUNTIME-API). Omega consumes the exact revision in cudapp.lock through check-cudapp. +# Portable (the tree, git, awk, sed, grep; no compiler, no sibling repository), this checks the omega side: +# 1. cudapp.lock names one 40-hex CUDApp commit; +# 2. no tracked file outside evidence/ is a second copy of the Runtime API (API.md or the manifest under +# docs/runtime, omega_runtime_api.*, omega_gpu_*.[ch], tools/runtime_api_check.sh/_negative.sh/_semver.sh), so every +# consumer #include of a Runtime API header resolves to the pinned CUDApp stage; +# 3. mk/runtime-r1.mk runs CUDApp's checker AND its negative controls on that stage, so the host gate +# (OMEGA-RUNTIME-API-PIN, step runtime-api-pin) cannot quietly drop either. +# Then every check is broken once on a copy of its input (a planted copy per pattern, a bad lock, a recipe without the +# negative controls); each break must FAIL, and the script fails when one is not caught. +set -u +cd "$(dirname "$0")/.." || exit 2 +WORK=$(mktemp -d "${TMPDIR:-/tmp}/runtime-api-owner.XXXXXX") || exit 2 +trap 'rm -rf "$WORK"' EXIT HUP INT TERM + +# check FILES LOCK MK -> prints FAIL lines, returns 1 on any +check() { + files=$1; lockf=$2; mkf=$3; bad=0 + sha=$(awk 'NF && $1 !~ /^#/ { print $1; exit }' "$lockf" 2>/dev/null) + if ! printf '%s\n' "$sha" | grep -Eqx '[0-9a-f]{40}'; then echo "FAIL: cudapp.lock does not name one 40-hex commit (read: ${sha:-nothing})"; bad=1; fi + grep -v '^evidence/' "$files" | grep -E '(^|/)(omega_runtime_api\.[A-Za-z]+|omega_gpu_[A-Za-z0-9_]*\.[ch]|runtime_api_(check|negative|semver)\.sh)$|^docs/runtime/(API\.md|[^/]*\.manifest|[^/]*\.internal)$' \ + > "$WORK/copies.txt" + if [ -s "$WORK/copies.txt" ]; then sed 's/^/FAIL: second copy of the CUDApp Runtime API in omega: /' "$WORK/copies.txt"; bad=1; fi + for t in 'sh $(CUDAPP_SOURCE)/tools/runtime_api_check.sh $(RUNTIME_API_MANIFEST) $(CUDAPP_SOURCE)' \ + 'sh $(CUDAPP_SOURCE)/tools/runtime_api_negative.sh $(RUNTIME_API_MANIFEST) $(CUDAPP_SOURCE)' \ + 'RUNTIME_API_MANIFEST ?= $(CUDAPP_SOURCE)/docs/runtime/omega_runtime_api.manifest' \ + 'RUNTIME_API_MD ?= $(CUDAPP_SOURCE)/docs/runtime/API.md' \ + 'test-runtime-api: | check-cudapp'; do + grep -qF -- "$t" "$mkf" 2>/dev/null || { echo "FAIL: mk/runtime-r1.mk no longer has: $t"; bad=1; } + done + return $bad +} + +git ls-files > "$WORK/files.txt" || { echo "RESULT: FAIL (git ls-files failed)"; exit 1; } +[ -s "$WORK/files.txt" ] || { echo "RESULT: FAIL (git ls-files listed nothing)"; exit 1; } +if ! check "$WORK/files.txt" cudapp.lock mk/runtime-r1.mk; then + echo "RESULT: FAIL (omega's side of the Runtime API is not clean)"; exit 1 +fi +lsha=$(awk 'NF && $1 !~ /^#/ { print $1; exit }' cudapp.lock) +nconsumers=$(git grep -l -E '#[[:space:]]*include[[:space:]]*"(omega_runtime_api|omega_gpu_[A-Za-z0-9_]*)\.h"' -- ':!evidence' | wc -l) +echo "RESULT: PASS (Runtime API owned by CUDApp $lsha; no second copy in $(wc -l < "$WORK/files.txt") tracked files; $nconsumers omega files include its headers from the stage)" + +# negative controls: one break per check, on copies +bad=0 +control() { # control NAME EXPECTED_TEXT FILES LOCK MK + out=$(check "$3" "$4" "$5"); rc=$? + if [ $rc -ne 0 ] && printf '%s\n' "$out" | grep -qF "$2"; then echo "NEGATIVE CONTROL $1: FAILED as it must ($2)" + else echo "NEGATIVE CONTROL $1: NOT CAUGHT (rc=$rc, wanted \"$2\")"; bad=1; fi +} +printf 'not-a-sha\n' > "$WORK/bad.lock" +printf '# comment only\n' > "$WORK/empty.lock" +grep -vF 'runtime_api_negative.sh' mk/runtime-r1.mk > "$WORK/noneg.mk" +grep -vF 'runtime_api_check.sh' mk/runtime-r1.mk > "$WORK/nocheck.mk" +sed 's/test-runtime-api: | check-cudapp/test-runtime-api:/' mk/runtime-r1.mk > "$WORK/nostage.mk" +for p in src/omega_gpu_session.h src/omega_runtime_api.h tests/omega_gpu_session_copy.c docs/runtime/API.md \ + docs/runtime/omega_runtime_api.manifest docs/runtime/omega_runtime_api.internal tools/runtime_api_check.sh \ + tools/runtime_api_negative.sh tools/runtime_api_semver.sh include/sub/omega_runtime_api.h; do + n=$(printf '%s' "$p" | tr -c 'A-Za-z0-9' '-') + { cat "$WORK/files.txt"; echo "$p"; } > "$WORK/planted-$n.txt" + control "planted-$p" "second copy of the CUDApp Runtime API in omega: $p" "$WORK/planted-$n.txt" cudapp.lock mk/runtime-r1.mk +done +{ cat "$WORK/files.txt"; echo "evidence/old/src/omega_gpu_session.h"; } > "$WORK/evidence.txt" +if check "$WORK/evidence.txt" cudapp.lock mk/runtime-r1.mk > /dev/null; then echo "POSITIVE CONTROL evidence-copy-allowed: PASSED as it must (evidence/ is add-only history)" +else echo "POSITIVE CONTROL evidence-copy-allowed: FAILED (an evidence/ path must not count as a copy)"; bad=1; fi +control bad-lock "cudapp.lock does not name one 40-hex commit" "$WORK/files.txt" "$WORK/bad.lock" mk/runtime-r1.mk +control empty-lock "cudapp.lock does not name one 40-hex commit" "$WORK/files.txt" "$WORK/empty.lock" mk/runtime-r1.mk +control no-negatives "mk/runtime-r1.mk no longer has: sh \$(CUDAPP_SOURCE)/tools/runtime_api_negative.sh" "$WORK/files.txt" cudapp.lock "$WORK/noneg.mk" +control no-check "mk/runtime-r1.mk no longer has: sh \$(CUDAPP_SOURCE)/tools/runtime_api_check.sh" "$WORK/files.txt" cudapp.lock "$WORK/nocheck.mk" +control no-stage "mk/runtime-r1.mk no longer has: test-runtime-api: | check-cudapp" "$WORK/files.txt" cudapp.lock "$WORK/nostage.mk" +if [ $bad -ne 0 ]; then echo "RESULT: FAIL (a negative control was not caught)"; exit 1; fi +echo "RESULT: PASS (every negative control was caught)" diff --git a/tools/runtime_portability_check.sh b/tools/runtime_portability_check.sh deleted file mode 100755 index 208f7c52a..000000000 --- a/tools/runtime_portability_check.sh +++ /dev/null @@ -1,93 +0,0 @@ -#!/bin/sh -# Omega runtime R3 (omega-mv#596): the portability table must match the source tree. -# usage: runtime_portability_check.sh -# Host only, no compiler, no device. POSIX sh + awk. -# -# Fails (exit 1, one line per problem) when: -# 1. a src/omega_gpu_*, src/omega_blackwell_* or src/omega_bw_* file has no row in the table -# 2. a row names a file that does not exist, or is duplicated, or has a bad class / binding / empty reason -# 3. a PORTABLE row's file includes a Linux or NVRM header (nvrm.h, m16_native.h, omega_gpu_platform_linux.h, -# pthread.h, unistd.h, fcntl.h, sys/*, linux/*) or a Blackwell chip header (omega_blackwell_*, omega_bw_*) -# 4. the os_binding column disagrees with what the include scan finds, or a .c file in GPU_FS_SRCS -# (engine.mk, the make gpu-engine-freestanding list) is not FREESTANDING_PROVEN -# It proves every file has a row and that the rows agree with the includes. It does not prove that -# a row's reason is right. -# -# Include scan: direct #include lines only. Lines inside "#ifdef OMEGA_ATTN_DEBUG" (a debug trace, off by default) and "#ifndef OMEGA_GPU_NO_POSIX" (or the #else -# of "#ifdef OMEGA_GPU_NO_POSIX") are the hosted-only build and are not counted, because the -# freestanding build never sees them. -root=$1; table=$2; mk=$3 -[ -d "$root/src" ] && [ -f "$table" ] && [ -f "$mk" ] || { echo "usage: $0 "; exit 2; } - -fail=0 -bad() { echo "FAIL: $*"; fail=1; } - -# unguarded includes of one file, one per line, as written between <> or "" -includes() { - awk ' - function hosted( i) { for (i = 1; i <= d; i++) if (h[i]) return 1; return 0 } - /^[ \t]*#[ \t]*ifdef[ \t]+OMEGA_ATTN_DEBUG/ { d++; h[d] = 1; isdef[d] = 0; next } - /^[ \t]*#[ \t]*if/ && !/^[ \t]*#[ \t]*(ifdef|ifndef)[ \t]+OMEGA_GPU_NO_POSIX/ { - d++; h[d] = 0; isdef[d] = 0 - if ($0 ~ /^[ \t]*#[ \t]*if[ \t]+!defined[ \t]*\(?[ \t]*OMEGA_GPU_NO_POSIX/) h[d] = 1 - next } - /^[ \t]*#[ \t]*ifndef[ \t]+OMEGA_GPU_NO_POSIX/ { d++; h[d] = 1; isdef[d] = 0; next } - /^[ \t]*#[ \t]*ifdef[ \t]+OMEGA_GPU_NO_POSIX/ { d++; h[d] = 0; isdef[d] = 1; next } - /^[ \t]*#[ \t]*(else|elif)/ { if (d > 0 && isdef[d]) h[d] = 1; next } - /^[ \t]*#[ \t]*endif/ { if (d > 0) d--; next } - /^[ \t]*#[ \t]*include/ { - if (hosted()) next - s = $0; sub(/^[ \t]*#[ \t]*include[ \t]*[<"]/, "", s); sub(/[>"].*$/, "", s); print s } - ' "$1" -} - -# --- row syntax and file existence ----------------------------------------------------------- -rows=$(grep -v '^#' "$table" | grep -v '^file ' || true) -tmp_rows=$(mktemp); printf '%s\n' "$rows" | grep -v '^$' > "$tmp_rows" -fs_srcs=$(awk '/^GPU_FS_SRCS[ \t]*=/ {on=1} on {print} on && !/\\$/ {exit}' "$mk" | tr -d '\\' | tr ' \t' '\n\n' | grep '^src/.*\.c$' || true) -[ -n "$fs_srcs" ] || bad "no GPU_FS_SRCS list found in $mk" - -dups=$(cut -f1 "$tmp_rows" | sort | uniq -d) -[ -z "$dups" ] || bad "duplicate rows: $(echo $dups)" - -while IFS=' ' read -r f class reason bind extra; do - [ -n "$f" ] || continue - [ -f "$root/$f" ] || { bad "row names a missing file: $f"; continue; } - case "$class" in CHIP_SPECIFIC|PORTABLE) ;; *) bad "$f: class '$class' is not CHIP_SPECIFIC or PORTABLE" ;; esac - case "$bind" in FREESTANDING_PROVEN|NO_HOSTED_INCLUDE|HOSTED_LIBC|LINUX_DRIVER) ;; *) bad "$f: os_binding '$bind' is not one of FREESTANDING_PROVEN NO_HOSTED_INCLUDE HOSTED_LIBC LINUX_DRIVER" ;; esac - [ -n "$reason" ] || bad "$f: empty reason" - [ -z "$extra" ] || bad "$f: more than four columns" - - inc=$(includes "$root/$f") - linux=$(printf '%s\n' "$inc" | grep -E '^(nvrm\.h|m16_native\.h|omega_gpu_platform_linux\.h|pthread\.h|unistd\.h|fcntl\.h|sys/.*|linux/.*)$' || true) - driver=$(printf '%s\n' "$linux" | grep -E '^(nvrm\.h|m16_native\.h|omega_gpu_platform_linux\.h|sys/.*|linux/.*)$' || true) - hosted=$(printf '%s\n' "$inc" | grep -E '^(stdio\.h|stdlib\.h|time\.h|errno\.h|math\.h|pthread\.h|unistd\.h|fcntl\.h|assert\.h|inttypes\.h|signal\.h|ctype\.h|sys/.*|linux/.*)$' || true) - chip=$(printf '%s\n' "$inc" | grep -E '^omega_(blackwell_|bw_)' || true) - - # derived binding - if [ -n "$driver" ]; then want=LINUX_DRIVER - elif [ -n "$hosted" ]; then want=HOSTED_LIBC - else want=NO_HOSTED_INCLUDE; fi - if printf '%s\n' "$fs_srcs" | grep -qx "$f"; then - [ "$want" = NO_HOSTED_INCLUDE ] || bad "$f: is in GPU_FS_SRCS but the include scan finds $(echo $driver $hosted)" - want=FREESTANDING_PROVEN - fi - [ "$bind" = "$want" ] || bad "$f: os_binding is $bind, the include scan and GPU_FS_SRCS say $want" - - if [ "$class" = PORTABLE ]; then - [ -z "$linux" ] || bad "$f: PORTABLE but includes a Linux/NVRM header: $(echo $linux)" - [ -z "$chip" ] || bad "$f: PORTABLE but includes a Blackwell chip header: $(echo $chip)" - fi -done < "$tmp_rows" - -# --- every file has a row ---------------------------------------------------------------------- -for p in "$root"/src/omega_gpu_* "$root"/src/omega_blackwell_* "$root"/src/omega_bw_*; do - [ -f "$p" ] || continue - f=src/$(basename "$p") - cut -f1 "$tmp_rows" | grep -qx "$f" || bad "no row in the table for $f" -done - -n=$(wc -l < "$tmp_rows" | tr -d ' ') -rm -f "$tmp_rows" -if [ "$fail" = 0 ]; then echo "PASS: $n rows, every omega_gpu_* / omega_blackwell_* / omega_bw_* file in src/ has one and the rows agree with the includes"; exit 0; fi -echo "FAIL: portability table does not match the tree"; exit 1 diff --git a/tools/runtime_portability_controls.sh b/tools/runtime_portability_controls.sh deleted file mode 100755 index 49c03c39f..000000000 --- a/tools/runtime_portability_controls.sh +++ /dev/null @@ -1,67 +0,0 @@ -#!/bin/sh -# Negative and positive controls for tools/runtime_portability_check.sh (omega-mv#596, slice R3). -# usage: runtime_portability_controls.sh -# Each control builds a scratch copy of the GPU source files, breaks one thing, and requires the -# checker to FAIL with the expected message (or, for the positive control, to still PASS). -# A check that cannot fail proves nothing. Exit 0 only when every control behaves as required. -scratch=$1; table=$2; mk=$3 -here=$(cd "$(dirname "$0")" && pwd) -chk="$here/runtime_portability_check.sh" -[ -n "$scratch" ] && [ -f "$table" ] && [ -f "$mk" ] || { echo "usage: $0 "; exit 2; } -ok=0 - -fresh() { # fresh : scratch root with a copy of the GPU files and the table - r="$scratch/$1"; rm -rf "$r"; mkdir -p "$r/src" - cp src/omega_gpu_* src/omega_blackwell_* src/omega_bw_* "$r/src/" - cp "$table" "$r/table.tsv" -} -expect_fail() { # expect_fail - out=$("$chk" "$scratch/$1" "$scratch/$1/table.tsv" "$mk" 2>&1); rc=$? - if [ $rc -eq 1 ] && printf '%s\n' "$out" | grep -q "$2"; then - echo "CONTROL $1: FAIL as required ($3)"; printf '%s\n' "$out" | grep "$2" | head -2 | sed 's/^/ /' - else - echo "CONTROL $1: WRONG, the checker exit was $rc and did not report '$2' ($3)"; printf '%s\n' "$out" | head -5 | sed 's/^/ /'; ok=1 - fi -} -expect_pass() { - out=$("$chk" "$scratch/$1" "$scratch/$1/table.tsv" "$mk" 2>&1); rc=$? - if [ $rc -eq 0 ]; then echo "CONTROL $1: PASS as required ($2)" - else echo "CONTROL $1: WRONG, the checker failed ($2)"; printf '%s\n' "$out" | head -5 | sed 's/^/ /'; ok=1; fi -} -setclass() { # setclass - awk -F'\t' -v f="$2" -v c="$3" 'BEGIN{OFS="\t"} $1==f{$2=c} {print}' "$scratch/$1/table.tsv" > "$scratch/$1/t.new" && mv "$scratch/$1/t.new" "$scratch/$1/table.tsv" -} - -fresh unchanged; expect_pass unchanged "scratch copy of the real tree and table" - -fresh new-file-no-row -printf 'int omega_gpu_zz_dummy(void) { return 0; }\n' > "$scratch/new-file-no-row/src/omega_gpu_zz_dummy.c" -expect_fail new-file-no-row "no row in the table for src/omega_gpu_zz_dummy.c" "a new omega_gpu_ file with no row" - -fresh row-missing-file -printf 'src/omega_gpu_zz_ghost.c\tPORTABLE\tghost\tNO_HOSTED_INCLUDE\n' >> "$scratch/row-missing-file/table.tsv" -expect_fail row-missing-file "row names a missing file: src/omega_gpu_zz_ghost.c" "a row for a file that does not exist" - -fresh portable-includes-nvrm -printf '#include "nvrm.h"\n' | cat - "$scratch/portable-includes-nvrm/src/omega_gpu_wait.c" > "$scratch/p.c" && mv "$scratch/p.c" "$scratch/portable-includes-nvrm/src/omega_gpu_wait.c" -expect_fail portable-includes-nvrm "omega_gpu_wait.c: PORTABLE but includes a Linux/NVRM header: nvrm.h" "a PORTABLE file that includes nvrm.h" - -fresh portable-row-on-linux-file -setclass portable-row-on-linux-file src/omega_gpu_platform_linux.c PORTABLE -expect_fail portable-row-on-linux-file "omega_gpu_platform_linux.c: PORTABLE but includes a Linux/NVRM header" "the real Linux backend relabelled PORTABLE" - -fresh portable-row-on-chip-file -setclass portable-row-on-chip-file src/omega_blackwell_qmd.h PORTABLE -setclass portable-row-on-chip-file src/omega_gpu_attention_api.c PORTABLE -expect_fail portable-row-on-chip-file "omega_gpu_attention_api.c: PORTABLE but includes a Blackwell chip header" "a file that includes Blackwell headers relabelled PORTABLE" - -fresh guarded-include -{ printf '#ifndef OMEGA_GPU_NO_POSIX\n#include "nvrm.h"\n#include \n#endif\n'; cat "$scratch/guarded-include/src/omega_gpu_engine.c"; } > "$scratch/g.c" && mv "$scratch/g.c" "$scratch/guarded-include/src/omega_gpu_engine.c" -expect_pass guarded-include "an nvrm.h include inside #ifndef OMEGA_GPU_NO_POSIX is the hosted-only build and must not count" - -fresh freestanding-claim-broken -printf '#include \n' | cat - "$scratch/freestanding-claim-broken/src/omega_gpu_fmt.c" > "$scratch/g.c" && mv "$scratch/g.c" "$scratch/freestanding-claim-broken/src/omega_gpu_fmt.c" -expect_fail freestanding-claim-broken "omega_gpu_fmt.c: is in GPU_FS_SRCS but the include scan finds stdlib.h" "a freestanding-closure file that gained stdlib.h" - -[ $ok -eq 0 ] && echo "ALL CONTROLS BEHAVED AS REQUIRED" || echo "A CONTROL DID NOT BEHAVE: the check is not trustworthy" -exit $ok diff --git a/tools/sm121dis/README.md b/tools/sm121dis/README.md index 590f48f38..05e86d59d 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