diff --git a/.github/workflows/host-suites-3.yml b/.github/workflows/host-suites-3.yml index 423b5a939..9efc51a64 100644 --- a/.github/workflows/host-suites-3.yml +++ b/.github/workflows/host-suites-3.yml @@ -31,11 +31,22 @@ on: - 'src/**' - 'tools/omegatool.c' - 'tests/test_omega_transc.c' + - 'tests/test_numeric_lifecycle.c' + - 'tests/numeric_native/**' - 'tests/language/**' - 'tests/run_m*_gates.sh' - 'docs/numeric/E1_TRANSCENDENTAL_CONTRACT.md' jobs: + numeric-lifecycle: + # Simulated driver only. No device-parity or hardware qualification claim. + runs-on: ubuntu-24.04-arm + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + - name: Numeric completion ownership, ASan and UBSan + run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-numeric-lifecycle + numeric-transc: runs-on: ubuntu-24.04-arm timeout-minutes: 30 diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ad5f4b9c8..279cda6d8 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -9,6 +9,7 @@ Every model below did real work. A model is listed only for work it did. The orc | Claude Opus 5.5 | Numeric GB10 operations (LDS_STS, REDUCE_SUM), the independent CPU oracle, the Gate 5 qualifier and its receipts, and the fixes from review | | Codex (GPT-6.1 Sol) | Code review of the numeric changes (patch checks, receipt blobs, GPU lock handling) | | Gemini 3.8 Flash | Code review of the numeric changes (patch checks, qualifier script, build rules) | +| Codex | Numeric uncertain-completion retention, exact completion checks, and simulated-driver lifecycle regression tests | This table starts with the numeric work on this branch. Earlier work in this repository is not yet attributed here; add rows only for work that can be traced to a model. diff --git a/Makefile b/Makefile index eeadc8c53..577716298 100644 --- a/Makefile +++ b/Makefile @@ -229,7 +229,7 @@ test-numeric-e1-exhaustive: build/test_omega_numeric_cpu # tests/run_reduce_chip.sh. Last line: "E1 Reduce Verdict: PASS_EXCEPT_DECLARED_CHIP_ONLY". .PHONY: test-numeric-reduce-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.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) @mkdir -p build @@ -1671,6 +1671,23 @@ build/test_omega_unwritten_trap: tests/test_omega_unwritten_trap.c src/omega_unw test-unwritten-trap-host: build/test_omega_unwritten_trap ./build/test_omega_unwritten_trap +# E1 row 2: general global load/store on the GB10 (src/omega_numeric_ldst_gb10.h, +# 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/sha256.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 +.PHONY: test-ldst-host test-ldst-nvdisasm +build/test_omega_ldst_gb10_cpu: $(LDST_SRCS) $(LDST_HDRS) + @mkdir -p build + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -ffp-contract=off -Isrc -DOMEGA_NUMERIC_CPU_ONLY -pthread -o $@ $(LDST_SRCS) +test-ldst-host: build/test_omega_ldst_gb10_cpu + ./build/test_omega_ldst_gb10_cpu +test-ldst-nvdisasm: + tools/ldst_nvdisasm_check.sh + # VC1-LIB: unit test for the library admission gate (receipt required, bootstrap kind, # dependencies must exist, no truncation) plus mutation proof. Each mutant is a copy of # src/omega_library.c with one tagged guard line (VC1:) deleted or weakened; the test diff --git a/docs/numeric/E1_C3_REDUCE_LDST_AB_ROUND1.md b/docs/numeric/E1_C3_REDUCE_LDST_AB_ROUND1.md new file mode 100644 index 000000000..d9e65e45a --- /dev/null +++ b/docs/numeric/E1_C3_REDUCE_LDST_AB_ROUND1.md @@ -0,0 +1,67 @@ +# E1 C3 REDUCE LDST A/B, round 1 record + +Verdict, in the operator's words: **bug not reproduced / comparison inconclusive (round 1 complete, rounds 2-5 not started)**. + +Script verdict line (log line 30): `E1 C3 REDUCE LDST AB: RUN_INCOMPLETE`, reason on log line 29: `incomplete because: quiet flag appeared before fix round 2`. + +Every number below is copied from the summary log. Line numbers refer to `~/workspace/test-queue-logs/E1N-C3AB-101051.log` (30 lines). + +## What was compared +Two builds of the same chip harness (`tests/test_omega_c3_ab_gb10.c`), run interleaved on the GB10 chip: +- control arm: built with `-DOMEGA_C3_PROTECT_OFF`, which compiles out only the new reduce and load/store protection (GPU L2 flush plus a second release marker, step `marker2_wait`). +- fix arm: the same sources with the protection compiled in. + +Built from omega `617971aa09c93649908e84e06cb681044d5bde41` (log line 1) and physics `e95e3ed2a86fe4bffe4d954fa94c27dfb5284280` (line 2). The PR head is now `44741c1b`, which adds a later diagnostics-only commit (marker2 late-arrival probe, stderr evidence) that touches `src/omega_numeric_reduce_gb10.c`; the chip run did not include it. +Control binary sha256 `93ee1659a96ffed5e87228d7d63b32357a8efe068e52f207ec10ea00b2cc0972` (line 7). Fix binary sha256 `6c64ce80bceb7cdae0c26623ec756bdf7d050341db1398a51d0665fd0d024448` (line 8). + +## Settings (line 6) +`rounds=5 repeats=200 sizes=1000003,65 ops=SUM,MAX,MEAN,LDST`. Expected runs per arm if the whole plan had run: 4000 (line 28). Round 1 is 800 runs per arm (lines 14 and 21), so 1 of 5 planned rounds ran. + +## Results, round 1 (lines 9, 10, 14-27) +Qualifying-hit threshold fixed before the run: at least 10 unwritten-output hits in the control arm. A hit means the output was left unwritten (OMEGA_UNWRITTEN_TRAP). A device error (the chip call itself failed) is a refusal and is NOT a hit. + +| Arm | Runs | Hits | Device errors | +|---|---|---|---| +| control (protection off) | 800 | 1 | 11 | +| fix (protection on) | 800 | 0 | 6 | + +Per operation: + +| Op | Control hits | Control device errors | Fix hits | Fix device errors | +|---|---|---|---|---| +| SUM | 0 | 5 | 0 | 1 | +| MAX | 0 | 3 | 0 | 3 | +| MEAN | 0 | 3 | 0 | 2 | +| LDST | 1 | 0 | 0 | 0 | +| total | 1 | 11 | 0 | 6 | + +Launcher failure lines by step (lines 20 and 27): +- control: 11 x `GB10_DEVFAIL fn=run_chunk step=marker_wait drv_rc=-1` +- fix: 6 x `GB10_DEVFAIL fn=run_chunk step=marker2_wait drv_rc=-1` + +The control arm has no `marker2_wait` step (its protection is compiled out), so the two arms fail at different waits by construction. This record draws no conclusion from the difference. + +## How to read it +- Control hits = 1, threshold = 10. The control arm did not reproduce the unwritten-output bug at the required rate, so the A/B cannot say anything about whether the protection fixes it. This is the "Known limits" case in the PR body. +- Device errors are NOT counted as hits, in either arm. They are listed separately above. +- The fix arm's 0 hits in 800 runs is NOT a proof of a fix. At the control arm's observed rate (1 hit in 800 runs) a build with no effect would be expected to show about 1 hit in 800 runs, so 0 of 800 does not separate the two arms. +- The 11 control and 6 fix device errors are a separate open question (failed device calls, `drv_rc=-1`). They were not diagnosed here. +- The threshold was not changed after seeing the data. + +## Why it stopped +Drake's rule (2026-10-02): finish round 1 untouched, stop at the round boundary only if the control arm ends below 10 qualifying hits. +Stop-watcher log `~/workspace/test-queue-logs/e1-c3ab-stop-after-round1.log` (7 lines): +- line 3, 12:10:50Z: control round 1 finished, `OMEGA_UNWRITTEN_TRAP: 1/800 device_errors=11`, qualifying hits 1, threshold 10. +- line 4, 12:10:50Z: control below threshold, stop at the round boundary. +- line 5, 12:10:50Z: waiting for fix round 1 to reach its last op (LDST); the next stop-watcher entry is 14:08:25Z. +- line 6, 14:08:25Z: quiet flag raised (the stop mechanism). Line 7, 14:09:55Z: the script exited and the quiet flag dropped. The flag was up for 90 seconds. +- The script then printed `RUN_INCOMPLETE` because the flag appeared before fix round 2 (log line 29). Round 1 had finished for both arms (log lines 9 and 10); rounds 2-5 were never started. + +## Evidence paths +- Summary log: `~/workspace/test-queue-logs/E1N-C3AB-101051.log`, sha256 `80801f6db509a530f76c60fdeac24223e7f103df70f82ebae5697ad068471264`. +- Stop-watcher log: `~/workspace/test-queue-logs/e1-c3ab-stop-after-round1.log`, sha256 `f12a90e03860b5581ea80f0b0336607e42aa839ba57adb2fb44e1b217cd8d2f6`. +- Transcript (outside the repo): `~/workspace/evidence-out/E1-C3-AB/ee2571feacd98b5252653c80dc65287d53ff1386145d525b563435896526f3a1.log`, sha256 `ee2571feacd98b5252653c80dc65287d53ff1386145d525b563435896526f3a1` (log lines 12 and 13). +- Script: `~/workspace/scripts/lt-e1-c3-ab.sh` (outside the repo). + +## Status +This is the chip comparison, not the chip gate. The PR title keeps `[host NOT_RUN][chip NOT_RUN]`. No claim is made that the protection fixes the rc=-4 device errors. Rounds 2-5 remain not run. diff --git a/docs/numeric/E1_GAP_TABLE.md b/docs/numeric/E1_GAP_TABLE.md index e8cd45b86..adc429a80 100644 --- a/docs/numeric/E1_GAP_TABLE.md +++ b/docs/numeric/E1_GAP_TABLE.md @@ -1,7 +1,7 @@ # E1 Numerical Closure: Gap Table Status: research note, 2026-09-30, read-only survey of `origin/main` at `529ebfa`; rows refreshed 2026-10-01 (see the status summary below). -No code was built or run for this note. +The 2026-10-01 rows were built and run; see the update section below. Plan source: `aien-architecture/CURRENT_EXECUTION_PLAN.md`, section 8, "E1. Numerical closure" (must close before M20 tensor training). Evidence source: the merged M19R Gate 5 @@ -32,6 +32,25 @@ For `dafb645a...` and `dc4e6012...` the file hashes differently (`dafb645a...` f Verify content through the receipt's own fields (`digest_meaning` in each receipt says "integrity only, not authenticity"). +## Update, branch `e1-gap-close` (convergence plan item 3, part 2) + +Classification of every row (C3 = the unwritten-output bug, branch `c3-h1-fence`, not touched here): + +| Row | Class | State | +|---|---|---| +| 1, 3, 4, 6, 7 | Already closed | No change | +| 2 | Closed in code, chip run queued (e1-gap-close-2) | General LDG/STG kernels (all widths, signed and unsigned narrow loads, byte strides, signed 24-bit offsets) built from nvdisasm-read encodings; host model equals a byte oracle; 148 table kernels decode with nvdisasm; chip job `E1B-LDST-CHIP` queued | +| 5 | Closed in code, chip receipt pending | MEAN divides on the GB10 DIV kernel, mutant hook in the build | +| 8 | Already closed (decided) | No change | +| 9 | Closed | CI runs the check; full-domain CPU run PASS | +| 10 | Closed in code for all five ops (e1-gap-close, e1-gap-close-2), chip receipts pending | SIN, COS, ERF, GELU (e1-gap-close) and RSQRT (e1-gap-close-2, exact-rounding by FMA error-free transforms, no integer multiply) equal the CPU tier on the host model; chip jobs `E1-CLOSE-TRANSC-CHIP` and `E1B-RSQRT-CHIP` queued | +| 11 | Open, needs the receipts from rows 5 and 10 and a Gate 5 expected-ID extension | Gate 5 rerun queued (`E1-CLOSE-GATE5`) on commit `9d11565`, the first commit of this PR, not on the PR head (`b48d132`); the rerun on the head is still to be queued | +| 12 | Closed in code (e1-gap-close-2) | FP32 is an explicit program IR type (tag `0x0E`) with an explicit `CONVERT` op; the type check refuses mixed types; evaluation uses the library tier; `make test-program-fp32` PASS 33/33; `spec/program-fp32.md`. Amendment to the ratified type table, no existing id changes | +| Unwritten-output root cause (row 10 note) | Blocked on C3 | Not touched | + +Chip evidence for rows 5, 10 and 11 comes from the shared forge queue (`E1-CLOSE-REDUCE`, +`E1-CLOSE-TRANSC-CHIP`, `E1-CLOSE-GATE5`); the receipts are added to this table when they land. + ## 1. What Gate 5 actually counts The brief for this note said "about 36 checks". No artifact on `origin/main` has 36. The real counts: @@ -90,14 +109,14 @@ later, not now. | 2 | FP32 load/store | Partial | Global STG fixed form (`src/omega_numeric.c:675` CHECK:stg_form); shared LDS_STS mirror exchange inside one 64-thread CTA (`omega_numeric.c:332`) | Only one fixed addressing pattern each; no general strided, offset or vector loads/stores | Define a load/store contract (offset, stride, alignment) with encoder checks, then chip parity | M | Yes | | 3 | Comparison / select | Covered (CPU and main GB10 path) | 13 `FSETP_*_SEL` predicates plus FSEL and FMNMX; CPU contract omega#124 (merge `d3194f6`, `docs/numeric/E1_SCALAR_CONTRACT.md`); GB10 encoding omega#147 (merge `2d8cd68`); chip parity lines with 0 mismatches in receipts `f4f6d362...` and `dafb645a...` (`evidence/OMEGA-NUMERIC-0/`) | None for the original gap (only GE existed) | None | - | No | | 4 | Conversion | Covered (CPU and main GB10 path) | I2FP, F2I; added `F2I_FLOOR/CEIL/RNI`, `F2U`, `I2FP_U32`, `F32<->F16`, `F32<->BF16` on CPU by omega#124 (merge `d3194f6`; 2^32-input exhaustive run on the 9 unary ops, 0 mismatches); GB10 encodings omega#147 (merge `2d8cd68`); chip parity 0 mismatches in receipts `f4f6d362...` and `dafb645a...` | FP16/BF16 arithmetic is not defined (conversions only) | None | - | No | -| 5 | Reductions | Covered on GB10 for SUM/MAX/MIN; MEAN = chip SUM + one declared host division | omega#134 (merge `c54d492`): SUM, MAX, MIN, MEAN over any length n >= 0 in frozen order `RECURSIVE_TILE32_PAIRWISE_TREE_LANE_DELTA_16_8_4_2_1_PAD_IDENTITY_MIN_ONE_LEVEL`; CPU verdict `PASS_EXCEPT_DECLARED_CHIP_ONLY`. GB10 SUM receipt `evidence/E1-REDUCE/be9d61ce...json` (omega 6da80bf). GB10 MAX/MIN via a reduce-owned SHFL.DOWN+FMNMX patch (omega#157): receipt `evidence/E1-REDUCE/a04f4f7f...json` (PASS, SUM/MAX/MIN/MEAN 380 cases, 0 mismatches, omega 689ad4d, pre-rebase) | MEAN final division still on the host (GB10 DIV is on the main path since omega#152; switch pending); no single-launch shared-memory CTA kernel; no receipt yet on merged main | Switch MEAN to GB10 DIV; consolidated chip run on merged main; optional CTA kernel with the same bits | S | Yes | +| 5 | Reductions | Closed in code (MEAN divides on the GB10); chip receipt pending | omega#134 (merge `c54d492`): SUM, MAX, MIN, MEAN over any length n >= 0 in frozen order `RECURSIVE_TILE32_PAIRWISE_TREE_LANE_DELTA_16_8_4_2_1_PAD_IDENTITY_MIN_ONE_LEVEL`. GB10 SUM receipt `evidence/E1-REDUCE/be9d61ce...json` (omega 6da80bf); MAX/MIN via a reduce-owned SHFL.DOWN+FMNMX patch (omega#157): receipt `evidence/E1-REDUCE/a04f4f7f...json` (SUM/MAX/MIN/MEAN 380 cases, 0 mismatches, omega 689ad4d). This PR (`e1-gap-close`, commit `9d11565`): the final MEAN division now runs on the GB10 DIV kernel (`omega_ds_gb10_run(OMEGA_DS_DIV, ...)`), no host step; build flag `-DOMEGA_REDUCE_MUTATE_MEAN_DIV` divides by n+1 so the chip run must FAIL; `make test-numeric-reduce-cpu` PASS_EXCEPT_DECLARED_CHIP_ONLY and `make test-numeric-reduce-nvdisasm` PASS | Chip run of the new MEAN path and its mutant on a clean commit (queued: forge job `E1-CLOSE-REDUCE`); optional single-launch CTA kernel not built | Read the receipt when the forge job finishes | S | Yes | | 6 | Division and square root (definition) | Covered on CPU | Integer-only correctly rounded sequences, bit-exact vs IEEE, hard cases (`tests/test_omega_numeric.c:756-801`); header records full SQRT sweep and 10^9 DIV pairs (`src/omega_numeric.h:112-123`) | Full DIV sweep is sampled, not exhaustive (not feasible for two inputs; acceptable) | None for definition | - | No | | 7 | Division and square root on GB10 | Closed (chip PASS) | Standalone GB10 kernels `src/omega_numeric_divsqrt_gb10.c` (DIV 264 words, SQRT 336 words, every word from Omega's encoder and checked by nvdisasm); `make test-divsqrt-host`; gate `tools/run_divsqrt_gate.sh`; receipt `E1-DIVSQRT/de7b2dd6a930ae94529773cf4e31aa08aac7065602b1d771e13e6ed2784a9074.json` ; wired into the main GB10 path (`omega_numeric_gb10.c` dispatches DIV/SQRT to `omega_ds_gb10_run`); Gate 5 chip parity 0 of 4096 mismatches each, receipt `OMEGA-NUMERIC-0/dafb645a9692aab551327c4de7c5dfd7d194504b1ae2ac998a0f5480c687cbb2.json` | None for DIV/SQRT | None | - | No | | 8 | Transcendental: exact sequences (wording) | Met (decided) | EXP/LOG frozen polynomial sequences (`omega_numeric.h:125-131`); edge and round-trip checks (`test_omega_numeric.c:803-844`); binary128 oracle bound EXP 40 ulp, LOG 4 ulp (lines 379-380) | Decided by aien-architecture #76 (merge `15808f9`, Option 1): "exact" means a frozen sequence with a declared per-op error bound, bit-identical on CPU and GB10, not correct rounding. RSQRT, DIV and SQRT stay correctly rounded. EXP worst case 39 ulp against its 40 ulp bound (omega#107 notes) | None for the wording; GB10 parity is tracked in row 10 | - | No | -| 9 | Transcendental: coverage | Partial (CPU only) | omega#127 (merge `7a5a13c`): SIGMOID, TANH, RSQRT, EXP2, LOG2, ERF, SIN, COS, GELU. Frozen binary32 sequences, bounded ulp (declared 3, 3, 0, 2, 2, 3, 2, 2, 3), checked against a binary128 oracle over all 2^32 inputs. Not in `OP_TABLE`; no CI job runs `make test-numeric-transc`; no receipt | pow variants not defined. Exact-versus-bounded wording is an owner decision (aien-architecture PR #76, unresolved) | Owner decision, then a CI job and a receipt | S | No | -| 10 | Transcendental on GB10 | PASS on merged main for EXP2, LOG2, SIGMOID, TANH (five ops still open) | Whole-program GB10 kernels (`src/omega_numeric_divsqrt_gb10.c`), same operation order and FMA placement as `src/omega_numeric_transc.c`, no MUFU, nvdisasm-checked, digest-pinned. Merged-main receipt `evidence/E1-TRANSC-GB10/96fbc78df41fb62244e9d16cd59531182f64a01fb8c5ef1e02c8dadb8be6f556.json` (omega `4863803`, merge of #165; physics `e95e3ed`; run 2026-10-01 16:58:11Z-17:20:50Z; chip exit 0; host tier 32/0; unsigned, content-addressed, chip log `blobs/c65e0041...log`): EXP2, LOG2, SIGMOID, TANH each every 32-bit input, 0 mismatches, 0 unwritten. Earlier pre-merge receipts (omega `d25d7ad`): `6ca4ee4e...json` (EXP2, LOG2, TANH PASS) and `147b2189...json` (SIGMOID PASS). Kept FAILs: `1dc85ef2...json` (32-register QMD, Xid 13 on LOG2/SIGMOID/TANH, fixed by a 48-register allocation) and SIGMOID in `6ca4ee4e` (98,304 outputs never written in one batch, every written value matched; the SIGMOID-only rerun passed) | RSQRT, ERF, SIN, COS, GELU have no GB10 kernel (RSQRT needs exact-midpoint checks for correct rounding). EXP/LOG of `OP_TABLE` still NOT_ENCODED. Not yet in `OP_TABLE` dispatch. Intermittent unwritten-output event on the DS executor is not root-caused (did not recur in the merged-main run) | Encode the remaining five ops; root-cause the unwritten batch | M | Yes | +| 9 | Transcendental: coverage | Closed on CPU | omega#127 (merge `7a5a13c`): SIGMOID, TANH, RSQRT, EXP2, LOG2, ERF, SIN, COS, GELU. Frozen binary32 sequences, bounded ulp (declared 3, 3, 0, 2, 2, 3, 2, 2, 3), checked against a binary128 oracle over all 2^32 inputs. CI: `.github/workflows/pr-smoke.yml` runs `test-numeric-transc` (sampled bound check and 10 mutants, must print `all 10 mutants killed`) and `host-suites-3.yml` runs it with `test-numeric-transc-digest`. Full-domain run `test-numeric-transc-full` PASS on omega `9d11565` (forge job `E1-CLOSE-TRANSC-FULL`, "E1 WP-B verdict: PASS", every op's full-domain digest matches the frozen one; GELU max 2 ulp at bound 3). The erfcx tables now live in one header, `src/omega_numeric_transc_tables.h`, read by both the CPU sequence and the GB10 kernels | pow variants not defined (no plan requirement); not in `OP_TABLE` dispatch | None | - | No | +| 10 | Transcendental on GB10 | EXP2, LOG2, SIGMOID, TANH PASS on chip; SIN, COS, ERF, GELU closed in code, chip receipt pending; RSQRT open | Whole-program GB10 kernels (`src/omega_numeric_divsqrt_gb10.c`), same operation order and FMA placement as `src/omega_numeric_transc.c`, no MUFU, nvdisasm-checked, digest-pinned. Merged-main receipt `evidence/E1-TRANSC-GB10/96fbc78df41fb62244e9d16cd59531182f64a01fb8c5ef1e02c8dadb8be6f556.json` (omega `4863803`, physics `e95e3ed`): EXP2, LOG2, SIGMOID, TANH each every 32-bit input, 0 mismatches. This PR (commit `966c47c`) adds SIN (120 words), COS (120), ERF (360), GELU (424): `tools/divsqrt_nvdisasm_check.sh` VERDICT PASS for all ten kernels; `make test-numeric-transc-gb10-host` 64/0 (edge set, stride 4093, 1M random per op, digest recorded); the host model of each new kernel equals the CPU tier on every one of the 2^32 inputs (`--host-all` SIN, COS, ERF, GELU: 4294967296 checked, 0 mismatches, forge job `E1-CLOSE-HOSTALL`). Kept FAILs from earlier runs are listed in the receipts' history | Chip run of the four new ops over all 2^32 inputs (queued: forge job `E1-CLOSE-TRANSC-CHIP`). RSQRT has no GB10 kernel: the CPU sequence decides rounding with a 128-bit integer midpoint test (`mid_below`), and the DS frame has no integer multiply, so a bit-identical kernel needs a different exact-rounding scheme (FMA residual checks); not attempted here. Unwritten-output intermittent event on the DS executor is C3 part 1 (branch `c3-h1-fence`), not touched | Run the chip job; design the RSQRT exact-rounding scheme | M (RSQRT) | Yes | | 11 | CPU/GB10 parity under frozen contracts | Partial | Gate 5 receipt `OMEGA-NUMERIC-0/dafb645a9692aab551327c4de7c5dfd7d194504b1ae2ac998a0f5480c687cbb2.json` (omega 7852570, physics e95e3ed): 40 encoded ops, 47 GB10 parity lines (FFMA x8), 0 mismatches over 4096 inputs each incl. subnormal/NaN/inf classes, DIV and SQRT included; frozen contracts = FPCR rule, declared reduction order, provenance table, physics.lock pin | EXP and LOG (row 10) and the nine #127 ops are still refused on the main path and have no Gate 5 chip parity | Rerun Gate 5 with each new op added; keep the 23 tests and extend the expected-ID list | M per batch | Yes | -| 12 | Integration (not named in the plan, implied by "before tensor training") | Missing | `omega_numeric.h` is included only by the four numeric source files; program IR refuses DIV (`tests/realize/test_program_realize.c:249`); no FP32 type in `src/omega_program.c` | Nothing downstream (program IR, visor, M20 jspace from #116) uses the qualified numeric library | M20-side decision: M20 tensor ops must call these contracts, and the program IR needs an FP32 value type | M | No | +| 12 | Integration (not named in the plan, implied by "before tensor training") | Partial (tensor tier closed; program IR FP32 type open) | The M20 tensor CPU tier now calls the qualified library: `src/tensor/omega_tensor_cpu.c` routes elementwise ops through `omega_numeric_cpu_realize`, EXP2/LOG2/SIGMOID/TANH/SIN/COS/RSQRT/ERF/GELU through `omega_numeric_transc.c`, and reductions through `omega_tensor_reduce_seam.c` into `omega_reduce_cpu`; `tools/tensor_mutations.sh` and `tools/autodiff_mutations.sh` mutate those call sites. Program IR still refuses DIV (`tests/realize/test_program_realize.c:249`) and `src/omega_program.c` has no FP32 type | The program IR and visor do not carry FP32 values | Design decision (FP32 value type in the program IR) belongs to the program-IR owner and Drake; not code that can be closed by a test alone. Blocked on that decision | M | No | ## 3. Counts @@ -121,3 +140,43 @@ Largest three gaps: 1. Row 7: DIV/SQRT on GB10. L, GPU. 2. Row 10 with row 9: transcendental set and its GB10 kernels. L + L, CPU first then GPU. 3. Row 5: reductions beyond one warp. L, GPU. + +## Update, branch `e1-gap-close-2` (based on `e1-gap-close` at `b48d132`) + +Row 4 of the brief (wording fix): the table line for row 11 said the Gate 5 rerun was queued "at this PR's +head". The queued job `E1-CLOSE-GATE5` is pinned to commit `9d11565`, the first commit of PR #198, not to +the head `b48d132`. The classification entry now says so, and the rerun on the head is still to be queued. + +Row 10, RSQRT (`src/omega_numeric_divsqrt_gb10.c`, `body_rsqrt`, 344 words). The CPU sequence decides rounding with +a 128-bit midpoint test; the DS frame has no integer multiply. The kernel decides the same question with +FP32 FMA error-free transforms: |x| is normalized to `x'` in [1,4) (a subnormal by an exact 2^24, the parity of +the exponent folded into `x'`), a seed `y0` within one ulp of the correctly rounded 1/sqrt(x') comes from a magic +number, three FMA Newton steps and one FMA residual correction, then the sign of `mu^2 x' - 1` and `ml^2 x' - 1` +at the two midpoints `y0 +- 2^-25` is computed exactly (TwoProduct by FMA, Knuth TwoSum, Shewchuk +GROW-EXPANSION; the sign of an expansion is the sign of its highest nonzero component). The result is +`y0 + [mu^2 x' < 1] + [ml^2 x' < 1] - 1`, rescaled by an exact power of two (two exact FMULs). Evidence: `tools/divsqrt_nvdisasm_check.sh` +decodes every word (all eleven kernels), `make test-numeric-transc-gb10-host` equals `omega_math_rsqrt` on the +edge set, every 4093rd input and 10^6 random inputs, and the all-input host run (`--host-all RSQRT`, forge job +`E1B-RSQRT-HOSTALL`) covers all 2^32. Chip job `E1B-RSQRT-CHIP` +(`tools/run_numeric_transc_gate.sh RSQRT`). + +Row 2, general load/store (`src/omega_numeric_ldst_gb10.{h,c}`, `docs/numeric/E1_LDST_GB10.md`). Evidence source +for the encodings: the verified vecadd words in `src/omega_blackwell_encoder.c` (the `LDG.E` and `STG.E` forms +the existing kernels use), extended only for the fields nvdisasm 13.0.85 `-b SM121` decoded when each bit +was varied one at a time: the signed 24-bit byte offset (word 1 bits 8 to 31, both LDG and STG), the access +size (word 2 bits 9 to 11: U8, S8, U16, S16, 32, 64, 128 for loads; 8, 16, 32, 64, 128 for stores) and the +stride immediate of `IMAD.WIDE.U32`. `make test-ldst-nvdisasm`: 148 of 148 table kernels decode word for word +to the encoder's text (a flipped offset bit changes the decode, so the check is not vacuous); +`make test-ldst-host`: 33 PASS (host model equals a typed-C byte oracle on every spec, 13 refusal rules, +10 kernel mutations caught). Chip job `E1B-LDST-CHIP` (`tools/run_numeric_ldst_chip.sh`). + +Row 12, FP32 in the program IR: see `spec/program-fp32.md`. No program-IR owner document forbids it +(`spec/type-system.md` is ratified for M4, so tag `0x0E` is an amendment, not a conflict). + +Chip failure classification for these jobs: a FAIL whose log shows bytes still equal to the fill pattern or +block-aligned unwritten spans is the unwritten-output bug C3 (branch `c3-h1-fence`), not a defect of these kernels. + +C3 hardening (branch `e1-gap-close`): the reduce launcher (`run_chunk`) and the ldst launcher (`omega_ldst_gb10_run`) had the same +pre-fix pattern as `omega_ds_gb10_run` and now take its L2 flush plus second release marker, waited on before every readback (step +`marker2_wait`). A/B script: `~/workspace/scripts/lt-e1-c3-ab.sh` (control arm `-DOMEGA_C3_PROTECT_OFF`, compiles out only the new +reduce and ldst protection). Round 1 result: bug not reproduced / comparison inconclusive (round 1 complete, rounds 2-5 not started); record `docs/numeric/E1_C3_REDUCE_LDST_AB_ROUND1.md`. No claim is made that this fixes the observed rc=-4. diff --git a/docs/numeric/E1_LDST_GB10.md b/docs/numeric/E1_LDST_GB10.md new file mode 100644 index 000000000..f409243f2 --- /dev/null +++ b/docs/numeric/E1_LDST_GB10.md @@ -0,0 +1,37 @@ +# E1 row 2: general load/store on the GB10 + +Code: `src/omega_numeric_ldst_gb10.{h,c}`. Tests: `tests/test_omega_ldst_gb10.c`, +`tools/ldst_nvdisasm_check.sh`, `tools/run_numeric_ldst_chip.sh`. + +## Contract +One thread per element `i < count`: `reg = LOAD_ld(in + i*in_stride + in_off)`, then +`STORE_st(out + i*out_stride + out_off, reg)`. +- Loads: U8, S8, U16, S16 (zero or sign extended to 32 bits), B32, B64, B128. +- Stores: B8, B16, B32, B64, B128 (the low bytes of the register file, little endian). +- Strides are byte counts applied by a 64-bit multiply-add; offsets are signed 24-bit byte offsets. +- Refused: a store wider than what the load filled; a stride below the width or not a multiple of it; + an offset not a multiple of the width or outside the signed 24-bit range; a stride of 2^24 or more; + count 0 or above `OMEGA_DS_MAX_BATCH`; any access outside the buffers (host model and executor both check). +- Buffers are 16-byte aligned with `OMEGA_LDST_PAD` bytes in front of element 0. + +## Encoding source +The kernel keeps the 17 verified prologue words of the vecadd kernel and the EXIT, BRA and NOP words +(`src/omega_blackwell_encoder.c`). New or changed words (each read back with nvdisasm 13.0.85 `-b SM121` +as an offline decoder, varying one bit at a time, and then checked word for word on 148 kernels): + +| Instruction | Word layout | +|---|---| +| `LDG.E[.kind] R12, desc[UR4][R2.64+off]` | w0 = `0x7981 | 12<<16 | 2<<24`, w1 = `4 | off24<<8`, w2 = `0x0c1e1100 | size<<9`, w3 = `0x002f2200` | +| `STG.E[.kind] desc[UR4][R6.64+off], R12` | w0 = `0x7986 | 6<<24`, w1 = `12 | off24<<8`, w2 = `0x0c101104 | size<<9`, w3 = `0x000fe200` | +| `IMAD.WIDE.U32 R2, R9, stride, R2` and the R6 form | vecadd word with w1 = stride | +| `IADD3 R9, PT, PT, R12, R5, RZ` | vecadd IADD3 with Ra = R12 (carries the scheduling wait for the loads) | + +Size field: 0 U8, 1 S8, 2 U16, 3 S16, 4 32-bit, 5 64-bit, 6 128-bit; value 7 decodes as `INVALID7` and is never emitted. +The load destination is R12 so the 128-bit form is register-group aligned. The prologue's second load (R5, +read from the "b" argument) is kept so the scheduling of the verified words is unchanged; the executor passes the +input buffer as "b". + +## Checks +Pre-submission structural check `omega_ldst_check_kernel` decodes the fields back out of the words and requires a +byte-for-byte rebuild (markers `CHECK:ldst_*`). Offline: `make test-ldst-nvdisasm`. Host: `make test-ldst-host`. +Chip: forge job `E1B-LDST-CHIP`; a FAIL with unwritten bytes (fill pattern left where the model wrote) is C3. diff --git a/docs/numeric/E1_REDUCTION_CONTRACT.md b/docs/numeric/E1_REDUCTION_CONTRACT.md index 8cba445bd..70854b3e0 100644 --- a/docs/numeric/E1_REDUCTION_CONTRACT.md +++ b/docs/numeric/E1_REDUCTION_CONTRACT.md @@ -1,7 +1,7 @@ # E1 reduction contract (WP-D) Closes gap table row 5 (`docs/numeric/E1_GAP_TABLE.md`) on the CPU tiers and -on GB10 for SUM, MAX, MIN and MEAN (MEAN with one declared host division). Code: `src/omega_numeric_reduce.h`, `src/omega_numeric_reduce.c` +on GB10 for SUM, MAX, MIN and MEAN (MEAN = chip SUM levels plus one chip division). Code: `src/omega_numeric_reduce.h`, `src/omega_numeric_reduce.c` (reference + CPU realization), `src/omega_numeric_reduce_gb10.c` (GB10), tests `tests/test_omega_reduce.c`, chip runner `tests/run_reduce_chip.sh`. @@ -109,11 +109,12 @@ Notes: QMD release semaphore (`OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE`) plus `dsb sy` before reading results (the stores-after-marker hazard found by the DIV/SQRT lane, omega#141). - - MEAN: the chip computes the SUM levels; the final - `omega_math_div(SUM, u2f(n))` is one declared host step (the GB10 DIV - kernel of omega#141 is not merged; switch to it once it is, the bits do not - change because both are correctly rounded). Receipts say - `HOST_DECLARED_STEP` for MEAN. + - MEAN: the chip computes the SUM levels, then the final + `omega_math_div(SUM, u2f(n))` on the chip as one launch of the whole-program + GB10 DIV kernel (E1 row 7, `omega_ds_gb10_run`). The bits are the same as + the former host division because both are correctly rounded. Receipts say + `GB10_DIV` for MEAN. Mutant: `-DOMEGA_REDUCE_MUTATE_MEAN_DIV` divides by n+1 + and must FAIL chip parity. - Pre-submission checks carry `CHECK:` markers (op, buffers, size, MEAN `n <= 2^24`, order string, kernel registered as BIT_EXACT, padding bits, level count, chunk shape, per-chunk submit check). diff --git a/mk/numeric-lifecycle.mk b/mk/numeric-lifecycle.mk new file mode 100644 index 000000000..8f8a81e9f --- /dev/null +++ b/mk/numeric-lifecycle.mk @@ -0,0 +1,12 @@ +# Pure host lifecycle tests. The fake M16 header is confined to this target. +.PHONY: test-numeric-lifecycle +test-numeric-lifecycle: + @mkdir -p $(OUT_DIR)/numeric-lifecycle + $(CC) -std=c11 -O2 -Wall -Wextra -Werror -Isrc -Itests/numeric_native tests/test_numeric_lifecycle.c tests/numeric_native/other_launcher.c -o $(OUT_DIR)/numeric-lifecycle/test + $(OUT_DIR)/numeric-lifecycle/test + $(CC) -std=c11 -O1 -g -Wall -Wextra -Werror -fsanitize=address,undefined -fno-sanitize-recover=all -Isrc -Itests/numeric_native tests/test_numeric_lifecycle.c tests/numeric_native/other_launcher.c -o $(OUT_DIR)/numeric-lifecycle/test-sanitize + $(OUT_DIR)/numeric-lifecycle/test-sanitize + CC='$(CC)' sh tests/numeric_native/mutants.sh $(OUT_DIR)/numeric-lifecycle/mutants + @for f in src/omega_numeric_gb10.c src/omega_numeric_reduce_gb10.c src/omega_numeric_divsqrt_gb10.c src/omega_numeric_ldst_gb10.c; do \ + if grep -Eq 'm16_native_(open|close|wait_marker)[[:space:]]*\(' $$f; then echo "FAIL: lifecycle bypass in $$f"; exit 1; fi; \ + done diff --git a/mk/program-fp32.mk b/mk/program-fp32.mk new file mode 100644 index 000000000..41dacb2e1 --- /dev/null +++ b/mk/program-fp32.mk @@ -0,0 +1,12 @@ +# 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_TEST): tests/realize/test_program_fp32.c src/omega_program_fp32.c src/omega_program_fp32.h $(VISOR_CORE_OBJS) $(PROGRAM_FP32_NUM) + 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) + +.PHONY: test-program-fp32 +test-program-fp32: $(PROGRAM_FP32_TEST) + ./$(PROGRAM_FP32_TEST) diff --git a/spec/program-fp32.md b/spec/program-fp32.md new file mode 100644 index 000000000..18888c51f --- /dev/null +++ b/spec/program-fp32.md @@ -0,0 +1,35 @@ +# FP32 in the program IR (amendment, E1 gap row 12) + +Status: implemented on branch e1-gap-close-2. Amends the ratified type table +(spec/type-system.md) with tag 0x0E and the operation table with opcode 0x10. +No existing tag, opcode or program id changes. + +## What is added +- Type `FP32` (tag 0x0E, width 32): an IEEE binary32 value, carried as its 32-bit pattern. +- Operation `CONVERT` (opcode 0x10): `imm` is the target type tag (FP32 or u32). +- `src/omega_program_fp32.{h,c}`: build, type check, and library-tier evaluation. + +## Type check (omega_program_fp32_check) +A two-state machine over the body, starting in the contract input type: +- FP32 state: ADD, SUB, MUL, DIV with a binary32 constant (`imm` = its bits, at most 32 bits), + or CONVERT to u32. +- u32 state: only CONVERT to FP32. Any other step is refused with the reason + "mixed types need an explicit CONVERT". +- CONVERT to the type the value already has is refused. +- The final state must equal the contract output type; contract widths must be 32. +- A stale or forged program id is refused (v2 id recomputed). + +## Identity +The v2 program id already binds body root, input/output type ids and constraint ids; the type ids +differ for FP32 vs u32 so the same steps over different types never share an id. Composition +requires OutType == InType, so FP32 and u32 programs join only through a CONVERT program. + +## Tier +FP32 programs are evaluated by the qualified library tier (omega_numeric_cpu_realize: FADD FSUB +FMUL DIV I2FP_U32 F2U, every one on the E1 gap-table "closed" list). The AArch64 integer +realizer refuses them on type (omega_program_realize_ex returns a reason). There is no new +machine code path. + +## Evidence +`make test-program-fp32` prints `GATE OMEGA_PROGRAM_FP32_PASS PASS 33/33`. +Regression: test-program-realize, test-program-id, test-visor-core, test-numeric-cpu all pass. diff --git a/spec/type-system.md b/spec/type-system.md index 5f0a726ed..1b65bcc0e 100644 --- a/spec/type-system.md +++ b/spec/type-system.md @@ -35,6 +35,7 @@ The OMEGA type system enforces: | `0x0B` | `CAPABILITY_REFERENCE` | `slot: u32, generation: u64` | OMEGA reference to an M3 capability token (64-bit generation: see `spec/effect-cap64-migration.md`) | | `0x0C` | `EFFECT_INTENT_REFERENCE`| `intent_digest: [u8; 32]` | Reference to an intended physical effect | | `0x0D` | `EFFECT_RECEIPT_REFERENCE`| `receipt_digest: [u8; 32]` | Reference to an authoritative execution receipt | +| `0x0E` | `FP32`| `width: u16 = 32` | IEEE binary32 value; amendment for E1 gap row 12 (spec/program-fp32.md); mixing with integers needs an explicit `CONVERT` (opcode `0x10`) | --- diff --git a/src/omega_core.c b/src/omega_core.c index df91bcc0b..5767a5245 100644 --- a/src/omega_core.c +++ b/src/omega_core.c @@ -125,6 +125,19 @@ OmegaObject* omega_build_type_signed_int(OmegaGraph *g, uint16_t width) { return obj; } +OmegaObject* omega_build_type_fp32(OmegaGraph *g) { + OmegaObject *obj = omega_graph_add_object(g, KIND_TYPE); + if (!obj) return NULL; + TypePayload tp; + memset(&tp, 0, sizeof(tp)); + tp.tag = TYPE_FP32; + tp.width = 32; + memcpy(obj->payload, &tp, sizeof(tp)); + obj->payload_len = sizeof(tp); + omega_compute_semantic_id(obj); + return obj; +} + OmegaObject* omega_build_type_bitvector(OmegaGraph *g, uint16_t width) { OmegaObject *obj = omega_graph_add_object(g, KIND_TYPE); if (!obj) return NULL; diff --git a/src/omega_core.h b/src/omega_core.h index 11c5ac1a3..af8ba4508 100644 --- a/src/omega_core.h +++ b/src/omega_core.h @@ -22,6 +22,7 @@ OmegaObject* omega_build_type_bool(OmegaGraph *g); OmegaObject* omega_build_type_uint(OmegaGraph *g, uint16_t width); OmegaObject* omega_build_type_signed_int(OmegaGraph *g, uint16_t width); OmegaObject* omega_build_type_bitvector(OmegaGraph *g, uint16_t width); +OmegaObject* omega_build_type_fp32(OmegaGraph *g); /* TYPE_FP32, width 32 */ OmegaObject* omega_build_type_byte(OmegaGraph *g); OmegaObject* omega_build_type_sequence(OmegaGraph *g, const SemanticId *elem_type, uint32_t len); OmegaObject* omega_build_type_cap_ref(OmegaGraph *g); diff --git a/src/omega_numeric.c b/src/omega_numeric.c index 438d25d04..569c5f58e 100644 --- a/src/omega_numeric.c +++ b/src/omega_numeric.c @@ -4,6 +4,7 @@ * comparators. No device access here (see src/omega_numeric_gb10.c). */ #include "omega_numeric.h" +#include "omega_numeric_lifecycle.h" #include "omega_blackwell_encoder.h" #include "omega_blackwell_qmd.h" @@ -12,6 +13,8 @@ #include #include +atomic_int omega_numeric_native_state = ATOMIC_VAR_INIT(OMEGA_NUMERIC_NATIVE_IDLE); + #if !defined(__aarch64__) #error "OMEGA-NUMERIC-0 host tiers use AArch64 FP instructions (fmadd, fdiv, fsqrt, fminnm, scvtf, fcvtzs)" #endif diff --git a/src/omega_numeric_divsqrt_gb10.c b/src/omega_numeric_divsqrt_gb10.c index aed1649b1..d2f5c335a 100644 --- a/src/omega_numeric_divsqrt_gb10.c +++ b/src/omega_numeric_divsqrt_gb10.c @@ -9,6 +9,7 @@ */ #include "omega_numeric_divsqrt_gb10.h" #include "omega_numeric.h" +#include "omega_numeric_transc_tables.h" #include "omega_blackwell_encoder.h" #include "omega_blackwell_qmd.h" @@ -21,7 +22,7 @@ #ifndef OMEGA_NUMERIC_CPU_ONLY #include "omega_blackwell_submit.h" -#include "m16_native.h" +#include "omega_numeric_native.h" #endif /* Recorded after tools/divsqrt_nvdisasm_check.sh matched every word of the @@ -33,10 +34,15 @@ const char *const OMEGA_DS_KERNEL_SHA256[OMEGA_DS_OP_COUNT] = { "14e461ec628b685ea23d197c060f7d35a302c88e794934628eacd6098a44f394", /* LOG2, 576 words */ "8607f5659b4d42a57fdb4ba2f26427a28d8e6e1497f3daa8529ae5da1f629b70", /* SIGMOID, 344 words */ "4edc065511340d58d26ed8ef7c1464341b279caccd7abc18b62d2a9880694494", /* TANH, 352 words */ + "0fe5484675cca0667c95a286b65560f204013683aee4e9ad001dbcf1d78cfc10", /* SIN, 120 words */ + "ed7cde5ac1dd3ddccc1b78885a2227600cf1bc4a7d775f27cceb110ed37a2ac4", /* COS, 120 words */ + "db3a51ff06cc24dc749d98dbf91485f0ceb86ba2bfc8cc55e554f62e6f7edff5", /* ERF, 360 words */ + "94992a5fdbe00a7943dac997d6a59ddd6096ac2fec35d4ff286b6552e8cea36d", /* GELU, 424 words */ + "adb2864a0842a36fb9abf144d6654a69668506e2f8e98ac1c7ecb40ca4a1ff85", /* RSQRT, 344 words */ }; const char *omega_ds_op_name(OmegaDsOp op) { - return op == OMEGA_DS_DIV ? "DIV" : op == OMEGA_DS_SQRT ? "SQRT" : op == OMEGA_DS_EXP2 ? "EXP2" : op == OMEGA_DS_LOG2 ? "LOG2" : op == OMEGA_DS_SIGMOID ? "SIGMOID" : op == OMEGA_DS_TANH ? "TANH" : "?"; + return op == OMEGA_DS_DIV ? "DIV" : op == OMEGA_DS_SQRT ? "SQRT" : op == OMEGA_DS_EXP2 ? "EXP2" : op == OMEGA_DS_LOG2 ? "LOG2" : op == OMEGA_DS_SIGMOID ? "SIGMOID" : op == OMEGA_DS_TANH ? "TANH" : op == OMEGA_DS_SIN ? "SIN" : op == OMEGA_DS_COS ? "COS" : op == OMEGA_DS_ERF ? "ERF" : op == OMEGA_DS_GELU ? "GELU" : op == OMEGA_DS_RSQRT ? "RSQRT" : "?"; } /* ---- Forms --------------------------------------------------------------- @@ -684,6 +690,457 @@ static void body_sqrt(Bld *B) { sel(B, RES, A_, RES, 0, 0); /* +-0 */ } + +/* ---- SIN / COS (E1 row 10) ------------------------------------------------- + * sincos_core of omega_numeric_transc.c: the reduction x = k pi/2 + (rh + rl) is + * computed for every input, the |x| <= pi/4 branch is chosen with a predicate, + * both polynomials run, and the quadrant picks one and its sign. x in R2. */ +static void two_sum_b(Bld *B, int s, int e, int a, int b, int t1, int t2) { + ffadd(B, s, a, b); /* x = a + b */ + ffsub(B, t1, s, a); /* bv = x - a */ + ffsub(B, t2, s, t1); /* av = x - bv */ + ffsub(B, t2, a, t2); /* a - av */ + ffsub(B, t1, b, t1); /* b - bv */ + ffadd(B, e, t2, t1); +} + +static void body_sincos(Bld *B, int qoff) { + enum { X = 2, AX_ = 3, C = 4, T = 10, KF = 11, K = 12, NKF = 13, R1 = 14, TH = 15, TL = 16, + S1 = 17, E1 = 18, S2 = 19, E2 = 20, LO = 21, RH = 22, RL = 23, U = 24, V = 25, + MG = 26, Q = 27, R2 = 28, SP = 29, CP = 30, W = 31, HR = 32, EH = 33, R2L = 34, NR = 35 }; + lopi(B, AX_, X, 0x7fffffffu, LUT_AND); + /* reduction (computed for every input; used when |x| > pi/4) */ + movf(B, C, 0xA2F983p-24f); /* 2/pi */ + ffmul(B, T, X, C); + movi(B, MG, 0x4b400000u); /* MAGIC */ + ffadd(B, T, T, MG); + ffsub(B, KF, T, MG); /* kf */ + isub(B, K, T, MG); /* k */ + lopi(B, NKF, KF, 0x80000000u, LUT_XOR); /* -kf */ + movf(B, C, 0xC90FDBp-23f); /* P1 */ + fffma(B, R1, NKF, C, X); /* r1 = -kf P1 + x */ + movf(B, C, -0xBBBD2Ep-48f); /* P2 */ + ffmul(B, TH, KF, C); /* th = kf P2 */ + lopi(B, U, TH, 0x80000000u, LUT_XOR); /* -th */ + fffma(B, TL, KF, C, U); /* tl = kf P2 - th */ + two_sum_b(B, S1, E1, R1, U, V, W); /* (s1, e1) = r1 + (-th) */ + lopi(B, U, TL, 0x80000000u, LUT_XOR); /* -tl */ + two_sum_b(B, S2, E2, S1, U, V, W); /* (s2, e2) = s1 + (-tl) */ + movf(B, C, -0xF72CEDp-73f); /* P3 */ + ffmul(B, T, KF, C); /* kf P3 */ + ffadd(B, U, E1, E2); + ffsub(B, LO, U, T); /* lo = (e1 + e2) - kf P3 */ + ffadd(B, RH, S2, LO); /* rh */ + ffsub(B, U, RH, S2); + ffsub(B, RL, LO, U); /* rl = lo - (rh - s2) */ + /* |x| <= pi/4 (0xC90FDBp-24 rounded): k = 0, rh = x, rl = 0 */ + setpi(B, 0, DS_CMP_LE, 0, AX_, omega_float_to_bits(0xC90FDBp-24f)); + sel(B, RH, X, RH, 0, 0); + sel(B, RL, RZ, RL, 0, 0); + sel(B, K, RZ, K, 0, 0); + iaddi(B, Q, K, qoff, RZ); + lopi(B, Q, Q, 3, LUT_AND); /* q = (k + qoff) & 3 */ + /* sin_poly(rh, rl) -> SP */ + ffmul(B, R2, RH, RH); /* r2 */ + movf(B, SP, 0xB09231p-56f); + horner(B, SP, R2, -0xD7322Bp-49f, C); + horner(B, SP, R2, 0xB8EF1Dp-42f, C); + horner(B, SP, R2, -0xD00D01p-36f, C); + horner(B, SP, R2, 0x888889p-30f, C); + horner(B, SP, R2, -0xAAAAABp-26f, C); + ffmul(B, T, RH, R2); /* t = rh r2 */ + movf(B, C, -0.5f); + ffmul(B, U, R2, C); /* r2 (-0.5) */ + fffma(B, U, U, RL, RL); /* rlc = (r2 -0.5) rl + rl */ + fffma(B, U, T, SP, U); /* t S + rlc */ + ffadd(B, SP, RH, U); /* sin */ + /* cos_poly(rh, rl) -> CP */ + lopi(B, NR, R2, 0x80000000u, LUT_XOR); + fffma(B, R2L, RH, RH, NR); /* r2l = rh rh - r2 (exact) */ + movf(B, CP, -0xC9CBA5p-60f); + horner(B, CP, R2, 0x8F76C7p-52f, C); + horner(B, CP, R2, -0x93F27Ep-45f, C); + horner(B, CP, R2, 0xD00D01p-39f, C); + horner(B, CP, R2, -0xB60B61p-33f, C); + horner(B, CP, R2, 0xAAAAABp-28f, C); + movf(B, C, 0.5f); + ffmul(B, HR, R2, C); /* hr = r2 0.5 */ + movf(B, C, 1.0f); + ffsub(B, U, C, HR); /* h = 1 - hr */ + ffsub(B, V, C, U); + ffsub(B, EH, V, HR); /* eh = (1 - h) - hr */ + movf(B, C, -0.5f); + fffma(B, V, R2L, C, EH); /* c1 = r2l (-0.5) + eh */ + lopi(B, W, RL, 0x80000000u, LUT_XOR); /* -rl */ + fffma(B, V, W, RH, V); /* c2 = (-rl) rh + c1 */ + ffmul(B, T, R2, R2); /* r4 */ + fffma(B, V, T, CP, V); /* r4 C + c2 */ + ffadd(B, CP, U, V); /* cos = h + (...) */ + /* quadrant: odd q -> cos, even -> sin; q & 2 flips the sign */ + lopi(B, T, Q, 1, LUT_AND); + setpi(B, 0, DS_CMP_NE, 0, T, 0); + sel(B, U, CP, SP, 0, 0); + lopi(B, V, U, 0x80000000u, LUT_XOR); + lopi(B, T, Q, 2, LUT_AND); + setpi(B, 1, DS_CMP_NE, 0, T, 0); + sel(B, RES, V, U, 1, 0); + /* special inputs, lowest priority first */ + setpi(B, 0, DS_CMP_GT, 0, AX_, 0x4a800000u /* 2^22 */); + seli(B, RES, RES, 0x7fc00000u, 0, 1); /* NaN, +-inf, |x| > 2^22: NaN */ + if (qoff == 0) { + setp(B, 0, DS_CMP_EQ, 0, AX_, RZ); + sel(B, RES, X, RES, 0, 0); /* sin(+-0) = +-0 */ + } +} +static void body_sin(Bld *B) { body_sincos(B, 0); } +static void body_cos(Bld *B) { body_sincos(B, 1); } + +/* ---- ERF / GELU (E1 row 10) ------------------------------------------------ + * Shared pieces of omega_math_erf and omega_math_gelu (omega_numeric_transc.c), + * issued in the written order. The 17-interval erfcx table is chosen by a + * chain of ISETP/SEL (the largest j with y >= ERFCX_LO[j] wins, the order of + * the CPU's while loop); the constants come from omega_numeric_transc_tables.h, + * the same header the CPU sequence reads. */ + +/* exp_core2(ah, al) -> m, k, ml. Temps R10-R17; ah and al must not be there. */ +static void exp_core2_body(Bld *B, int ah, int al, int m, int k, int ml) { + enum { C = 10, T = 11, KF = 12, NKF = 13, R = 14, P = 15, MG = 16, Q = 17 }; + movf(B, C, 0xB8AA3Bp-23f); /* INVLN2 */ + ffmul(B, T, ah, C); + movi(B, MG, 0x4b400000u); /* MAGIC */ + ffadd(B, T, T, MG); + ffsub(B, KF, T, MG); /* kf */ + isub(B, k, T, MG); /* k = tb(t) - tb(MAGIC) */ + lopi(B, NKF, KF, 0x80000000u, LUT_XOR); /* -kf */ + movf(B, C, 0xB17218p-24f); /* LN2_HI */ + fffma(B, R, NKF, C, ah); + movf(B, C, -0x82E308p-52f); /* LN2_LO */ + fffma(B, R, NKF, C, R); + ffadd(B, R, R, al); /* r += al */ + movf(B, P, 0xD00D01p-39f); /* 1/8! */ + horner(B, P, R, 0xD00D01p-36f, C); + horner(B, P, R, 0xB60B61p-33f, C); + horner(B, P, R, 0x888889p-30f, C); + horner(B, P, R, 0xAAAAABp-28f, C); + horner(B, P, R, 0xAAAAABp-26f, C); + horner(B, P, R, 0.5f, C); + horner(B, P, R, 1.0f, C); + movf(B, C, 1.0f); + fffma(B, m, P, R, C); /* m = ffma(p, r, 1) */ + ffsub(B, Q, C, m); /* 1 - m (exact) */ + fffma(B, ml, P, R, Q); /* ml = ffma(p, r, 1 - m) */ +} + +/* erf_small(y) -> out (|y| < 0.5 and tiny y). Temps R10-R16. */ +static void erf_small_body(Bld *B, int y, int out) { + enum { Y2 = 10, Q = 11, W = 12, A = 13, NA = 14, AL = 15, BB = 16, TMP = 17 }; + ffmul(B, Y2, y, y); + movf(B, Q, -0xDDEBBDp-40f); /* n = 7 */ + horner(B, Q, Y2, 0xE00E01p-37f, TMP); + horner(B, Q, Y2, -0xC6980Cp-34f, TMP); + horner(B, Q, Y2, 0x97B426p-31f, TMP); + horner(B, Q, Y2, -0xC30C31p-29f, TMP); + horner(B, Q, Y2, 0xCCCCCDp-27f, TMP); + horner(B, Q, Y2, -0xAAAAABp-25f, TMP); /* n = 1: -1/3 */ + ffmul(B, W, Y2, Q); /* w = y2 q */ + movf(B, TMP, 0x906EBBp-23f); /* TSP_HI */ + ffmul(B, A, y, TMP); + lopi(B, NA, A, 0x80000000u, LUT_XOR); + fffma(B, AL, y, TMP, NA); /* Al = y TSP_HI - A */ + movf(B, TMP, -0xFBD649p-48f); /* TSP_LO */ + fffma(B, BB, y, TMP, AL); /* B = y TSP_LO + Al */ + fffma(B, TMP, A, W, BB); /* A w + B */ + ffadd(B, out, A, TMP); +} + +/* Chooses the erfcx interval of y (>= 0) into the table registers + * A[n] = R10 + n (n = 0..10), A0LO = R21, CC = R22; P0 is clobbered. */ +static void erfcx_table_body(Bld *B, int y) { + enum { A0 = 10, A0LO = 21, CC = 22 }; + for (int n = 0; n <= 10; n++) movf(B, A0 + n, ERFCX_A[0][n]); + movf(B, A0LO, ERFCX_A0LO[0]); + movf(B, CC, ERFCX_C[0]); + for (int j = 1; j < ERFCX_N; j++) { + setpi(B, 0, DS_CMP_GE, 0, y, omega_float_to_bits(ERFCX_LO[j])); + for (int n = 0; n <= 10; n++) seli(B, A0 + n, A0 + n, omega_float_to_bits(ERFCX_A[j][n]), 0, 1); + seli(B, A0LO, A0LO, omega_float_to_bits(ERFCX_A0LO[j]), 0, 1); + seli(B, CC, CC, omega_float_to_bits(ERFCX_C[j]), 0, 1); + } +} + +/* erfcx_eval2(y) -> c, cl from the table registers (see erfcx_table_body). + * t and p are scratch; writes c, cl, t, p. */ +static void erfcx_eval_body(Bld *B, int y, int c, int cl, int t, int p, int want_cl) { + enum { A0 = 10, A0LO = 21, CC = 22 }; + ffsub(B, t, y, CC); /* t = y - centre (exact) */ + fffma(B, p, A0 + 10, t, A0 + 9); + for (int n = 8; n >= 1; n--) fffma(B, p, p, t, A0 + n); + fffma(B, c, p, t, A0); /* c = p t + a0 */ + if (want_cl) { + ffsub(B, cl, A0, c); /* a0 - c */ + fffma(B, cl, p, t, cl); + ffadd(B, cl, cl, A0LO); + } +} + +/* omega_math_erf. x in R2. */ +static void body_erf(Bld *B) { + enum { X = 2, AXR = 3, SG = 4, SMALLR = 23, H = 24, NH = 25, HL = 26, NHL = 27, M = 28, K = 29, ML = 30, + T = 31, P = 32, C = 33, MC = 34, S = 35, ONE = 36, BIGR = 37 }; + lopi(B, AXR, X, 0x7fffffffu, LUT_AND); + lopi(B, SG, X, 0x80000000u, LUT_AND); + erf_small_body(B, AXR, SMALLR); + ffmul(B, H, AXR, AXR); /* h = ax ax */ + lopi(B, NH, H, 0x80000000u, LUT_XOR); + fffma(B, HL, AXR, AXR, NH); /* hl = ax ax - h (exact) */ + lopi(B, NHL, HL, 0x80000000u, LUT_XOR); + exp_core2_body(B, NH, NHL, M, K, ML); /* e^-(h + hl) = m 2^k */ + erfcx_table_body(B, AXR); + erfcx_eval_body(B, AXR, C, 0, T, P, 0); + ffmul(B, MC, M, C); /* erfc = m erfcx */ + scale2_core(B, S, MC, K, 10, 11, 12, 13, 14); + movf(B, ONE, 1.0f); + ffsub(B, BIGR, ONE, S); /* 1 - erfc */ + setpi(B, 0, DS_CMP_LT, 0, AXR, 0x3f000000u); /* |x| < 0.5 */ + sel(B, RES, SMALLR, BIGR, 0, 0); + setpi(B, 0, DS_CMP_GE, 0, AXR, 0x40800000u); /* |x| >= 4: 1 */ + seli(B, RES, RES, 0x3f800000u, 0, 1); + lop(B, RES, RES, SG, RZ, LUT_OR); /* r | sign */ + setpi(B, 0, DS_CMP_GT, 0, AXR, 0x7f800000u); + seli(B, RES, RES, 0x7fc00000u, 0, 1); /* NaN */ +} + +/* omega_math_gelu (erf form). x in R2. Every path is computed, then the + * CPU's branch order is replayed with selects, lowest priority first. */ +static void body_gelu(Bld *B) { + enum { X = 2, AXR = 3, SG = 4, Y = 23, AY = 24, HX = 25, SMALLR = 26, P = 27, PL = 28, H = 29, HL = 30, + NH = 31, NHL = 32, ME = 33, K = 34, MEL = 35, T = 36, PP = 37, C = 38, CL = 39, U = 40, V = 41, + W = 42, LARGE = 43, S = 44 }; + lopi(B, AXR, X, 0x7fffffffu, LUT_AND); + lopi(B, SG, X, 0x80000000u, LUT_AND); + movf(B, U, 0xB504F3p-24f); /* INV_SQRT2 */ + ffmul(B, Y, X, U); /* y = x INV_SQRT2 */ + lopi(B, AY, Y, 0x7fffffffu, LUT_AND); + movf(B, V, 0.5f); + ffmul(B, HX, X, V); /* hx = x 0.5 */ + /* ay < 0.5: x/2 + x/2 erf(y) */ + erf_small_body(B, AY, V); /* e = erf_small(ay) */ + lopi(B, W, Y, 0x80000000u, LUT_AND); + lop(B, V, V, W, RZ, LUT_OR); /* e | sign(y) */ + fffma(B, W, HX, V, HX); /* r = hx e + hx */ + lop(B, SMALLR, W, SG, RZ, LUT_OR); /* r | sign(x) */ + /* large path */ + ffmul(B, P, X, X); /* P = x x */ + lopi(B, U, P, 0x80000000u, LUT_XOR); + fffma(B, PL, X, X, U); /* Pl = x x - P */ + movf(B, U, 0.5f); + ffmul(B, H, P, U); /* h = P 0.5 */ + ffmul(B, HL, PL, U); /* hl = Pl 0.5 */ + lopi(B, NH, H, 0x80000000u, LUT_XOR); + lopi(B, NHL, HL, 0x80000000u, LUT_XOR); + exp_core2_body(B, NH, NHL, ME, K, MEL); /* e^(-y^2) ~ (me + mel) 2^k */ + erfcx_table_body(B, AY); + erfcx_eval_body(B, AY, C, CL, T, PP, 1);/* erfcx(|y|) ~ c + cl */ + /* yl = x/sqrt2 - y to first order; ayl = sign(x) ? -yl : yl */ + movf(B, U, 0xB504F3p-24f); + lopi(B, V, Y, 0x80000000u, LUT_XOR); + fffma(B, W, X, U, V); /* yl = x INV_SQRT2 - y (exact) */ + movf(B, U, 0xCFE77Ap-50f); /* INV_SQRT2_LO */ + fffma(B, W, X, U, W); /* yl += x INV_SQRT2_LO */ + setpi(B, 1, DS_CMP_NE, 0, SG, 0); /* P1: x negative */ + lopi(B, V, W, 0x80000000u, LUT_XOR); + sel(B, W, V, W, 1, 0); /* ayl */ + /* dc = ffma(ay 2, c, -TSP_HI); cl = ffma(ayl, dc, cl) */ + movf(B, U, 2.0f); + ffmul(B, V, AY, U); + movf(B, U, -0x906EBBp-23f); + fffma(B, V, V, C, U); /* dc */ + fffma(B, CL, W, V, CL); + /* p = me c; pl = ffma(me, c, -p) + me cl + mel c */ + ffmul(B, PP, ME, C); + lopi(B, U, PP, 0x80000000u, LUT_XOR); + fffma(B, V, ME, C, U); /* pl = me c - p */ + fffma(B, V, ME, CL, V); + fffma(B, V, MEL, C, V); /* pl */ + /* x >= 0: ffma(-hx, scale2(p, k), x) */ + scale2_core(B, S, PP, K, 10, 11, 12, 13, 14); + lopi(B, U, HX, 0x80000000u, LUT_XOR); /* -hx */ + fffma(B, LARGE, U, S, X); + /* x < 0: scale2(ffma(hx, p, hx pl), k) */ + ffmul(B, W, HX, V); /* hx pl */ + fffma(B, W, HX, PP, W); /* hx p + hx pl */ + scale2_core(B, S, W, K, 10, 11, 12, 13, 14); + setpi(B, 1, DS_CMP_NE, 0, SG, 0); + sel(B, LARGE, S, LARGE, 1, 0); /* x < 0 -> negative form */ + /* branches, lowest priority first */ + setpi(B, 0, DS_CMP_LT, 0, AY, 0x3f000000u); /* ay < 0.5 */ + sel(B, RES, SMALLR, LARGE, 0, 0); + /* |x| < 2^-125: integer only, tie broken toward +inf */ + iaddi(B, V, AXR, 1, RZ); + shri(B, V, V, 1); /* (m + 1) >> 1 */ + shri(B, W, AXR, 1); /* m >> 1 */ + setpi(B, 1, DS_CMP_NE, 0, SG, 0); + sel(B, V, W, V, 1, 0); /* sign: m >> 1, else (m+1) >> 1 */ + lop(B, V, V, SG, RZ, LUT_OR); + setpi(B, 0, DS_CMP_LT, 0, AXR, 0x01000000u); + sel(B, RES, V, RES, 0, 0); + /* x < -15.5: -0 ; x >= 8: x ; zero is covered by the tiny branch */ + setpi(B, 0, DS_CMP_GT, 0, AXR, 0x41780000u); /* |x| > 15.5 */ + movi(B, W, 0x80000000u); + sel(B, V, W, RES, 0, 0); + setpi(B, 1, DS_CMP_NE, 0, SG, 0); + sel(B, RES, V, RES, 1, 0); /* ... and x negative: -0 */ + setpi(B, 0, DS_CMP_GE, 1, X, 0x41000000u); + sel(B, RES, X, RES, 0, 0); /* x >= 8: x (signed compare) */ + setpi(B, 0, DS_CMP_GT, 0, AXR, 0x7f800000u); + seli(B, RES, RES, 0x7fc00000u, 0, 1); /* NaN */ +} + +/* ---- RSQRT (E1 row 10) --------------------------------------------------------- + * Correctly rounded 1/sqrt(x), bit-identical to omega_math_rsqrt. The CPU tier + * decides the final rounding with a 128-bit integer midpoint test (mid_below); + * this frame has no integer multiply, so the same decision is made with + * binary32 FMA error-free transforms. + * + * |x| (positive, finite, nonzero) is normalized to x' in [1,4) (a subnormal by + * an exact x 2^24, the parity of the exponent folded into x') so that + * y = 1/sqrt(x') lies in (0.5, 1]; the result is y 2^k (2^-12 more for a + * subnormal input), both exact FMULs. + * 1. y0: magic-number seed, three FMA Newton steps, one FMA residual + * correction. y0 is within one ulp of the correctly rounded y. + * 2. mu = y0 + 2^-25 and ml = y0 - 2^-25 are at most the midpoints to the + * neighbours of y0 (the gap on either side of y0 in [0.5, 1] is 2^-24 or + * 2^-23 above 1... never below 2^-24), and 1/sqrt(x') = 1 only for x' = 1. + * The correctly rounded result is y0 + [mu^2 x' < 1] + [ml^2 x' < 1] - 1. + * 3. The sign of m^2 x' - 1 is exact. For m = y0 + s 2^-25 it is the sign of + * (x' y0^2 - 1) + s x' y0 2^-24 + x' 2^-50. + * Products are split by FMA into (hi, lo) with no rounding error, the + * terms are summed exactly into a nonoverlapping expansion (Shewchuk + * GROW-EXPANSION over Knuth TwoSum) and the sign of an expansion is the + * sign of its highest nonzero component. No midpoint equals 1/sqrt(x'), + * so no expansion is zero. + * The host model equals the CPU tier on every 32-bit input + * (test_omega_numeric_transc_gb10 --host-all RSQRT). */ +static void grow_expansion(Bld *B, const int *e, int n, int b, int qa, int qb, int t1, int t2) { + /* e[0..n-1] += b exactly; e[0..n] on return (e[n] the highest component). + * b is read but never written. */ + int q = b; + for (int i = 0; i < n; i++) { + int s = (i == n - 1) ? e[n] : (q == qa ? qb : qa); + two_sum_b(B, s, e[i], q, e[i], t1, t2); + q = s; + } +} + +/* out := the highest nonzero component of e[0..n-1] (its sign bit is the sign). */ +static void expansion_sign(Bld *B, const int *e, int n, int out, int t) { + mov(B, out, e[0]); + for (int i = 1; i < n; i++) { + shli(B, t, e[i], 1); + setpi(B, 0, DS_CMP_NE, 0, t, 0); + sel(B, out, e[i], out, 0, 0); + } +} + +static void body_rsqrt(Bld *B) { + enum { AXR = 8, XB = 10, BE = 11, PAR = 12, X = 13, NX = 14, SC = 15, POST = 16, Y = 17, + T = 18, NTS = 19, NTL = 20, E = 21, H = 22, ONE = 23, HALF = 24, P = 25, PL = 26, HH = 27, + HL = 28, GG = 29, GL = 30, Q = 31, QL = 32, G = 33, TS = 34, TL = 35, W = 36, + SU = 44, SL = 45 }; + const int SH[5] = { 37, 38, 39, 40, 41 }; + const int WK[7] = { 25, 26, 27, 28, 29, 30, 31 }; + const int T1 = 10, T2 = 11, QA = 12, QB = 14; /* TwoSum temps, free after the setup */ + lopi(B, AXR, A_, 0x7fffffffu, LUT_AND); + /* subnormal: x 2^24 exact; XB = normal float bits */ + movi(B, T, 0x4b800000u); + ffmul(B, E, AXR, T); + setpi(B, 0, DS_CMP_LT, 0, AXR, 0x00800000u); + sel(B, XB, E, AXR, 0, 0); + movi(B, T, 0x45800000u); + seli(B, POST, T, 0x3f800000u, 0, 0); /* 2^12 for a subnormal, else 1 */ + shri(B, BE, XB, 23); + iaddi(B, T, BE, 1, RZ); + lopi(B, PAR, T, 1, LUT_AND); /* 1 when the exponent is even */ + lopi(B, X, XB, 0x007fffffu, LUT_AND); + lopi(B, X, X, 0x3f800000u, LUT_OR); + shli(B, T, PAR, 23); + iadd(B, X, X, T, RZ); /* x' in [1,4) */ + isub(B, T, BE, PAR); + iaddi(B, T, T, 129, RZ); + shri(B, T, T, 1); + rsubi(B, T, T, 255); + shli(B, SC, T, 23); /* 2^-(e' / 2) */ + lopi(B, NX, X, 0x80000000u, LUT_XOR); + movf(B, ONE, 1.0f); + movf(B, HALF, 0.5f); + /* y0 */ + shri(B, T, X, 1); + rsubi(B, Y, T, 0x5f3759dfu); + for (int k = 0; k < 3; k++) { + ffmul(B, T, Y, Y); + fffma(B, E, NX, T, ONE); /* 1 - x y^2 */ + ffmul(B, H, Y, HALF); + fffma(B, Y, H, E, Y); + } + ffmul(B, G, X, Y); + ffmul(B, H, Y, HALF); + lopi(B, T, G, 0x80000000u, LUT_XOR); + fffma(B, E, T, H, HALF); /* 1/2 - g h */ + fffma(B, G, G, E, G); + fffma(B, H, H, E, H); + ffadd(B, Y, H, H); + /* error-free terms of x' (y0 + s 2^-25)^2 - 1 */ + ffmul(B, P, Y, Y); + lopi(B, T, P, 0x80000000u, LUT_XOR); + fffma(B, PL, Y, Y, T); /* y0^2 = P + PL */ + ffmul(B, HH, X, P); + lopi(B, T, HH, 0x80000000u, LUT_XOR); + fffma(B, HL, X, P, T); + ffmul(B, GG, X, PL); + lopi(B, T, GG, 0x80000000u, LUT_XOR); + fffma(B, GL, X, PL, T); + ffsub(B, SH[0], HH, ONE); /* HH - 1, exact (Sterbenz) */ + ffmul(B, Q, X, Y); + lopi(B, T, Q, 0x80000000u, LUT_XOR); + fffma(B, QL, X, Y, T); /* x y0 = Q + QL */ + movf(B, T, 0x1p-24f); + ffmul(B, TS, Q, T); + ffmul(B, TL, QL, T); + movf(B, T, 0x1p-50f); + ffmul(B, W, X, T); + lopi(B, NTS, TS, 0x80000000u, LUT_XOR); + lopi(B, NTL, TL, 0x80000000u, LUT_XOR); + grow_expansion(B, SH, 1, HL, QA, QB, T1, T2); + grow_expansion(B, SH, 2, GG, QA, QB, T1, T2); + grow_expansion(B, SH, 3, GL, QA, QB, T1, T2); + grow_expansion(B, SH, 4, W, QA, QB, T1, T2); + /* mu: + s x y0 2^-24 with s = +1; r > mu exactly when the sum is negative */ + for (int i = 0; i < 5; i++) mov(B, WK[i], SH[i]); + grow_expansion(B, WK, 5, TS, QA, QB, T1, T2); + grow_expansion(B, WK, 6, TL, QA, QB, T1, T2); + expansion_sign(B, WK, 7, SU, T); + shri(B, SU, SU, 31); /* 1: round up */ + /* ml: s = -1; r < ml exactly when the sum is positive */ + for (int i = 0; i < 5; i++) mov(B, WK[i], SH[i]); + grow_expansion(B, WK, 5, NTS, QA, QB, T1, T2); + grow_expansion(B, WK, 6, NTL, QA, QB, T1, T2); + expansion_sign(B, WK, 7, SL, T); + shri(B, SL, SL, 31); /* 1: ml is not below r */ + iadd(B, T, Y, SU, SL); + iaddi(B, T, T, -1, RZ); /* y0 + up + (1 - down) - 1 */ + ffmul(B, T, T, SC); + ffmul(B, RES, T, POST); + /* special inputs, lowest priority first */ + setpi(B, 0, DS_CMP_GE, 0, A_, 0x80000000u); + seli(B, RES, RES, 0x7fc00000u, 0, 1); /* x < 0: NaN */ + lopi(B, T, A_, 0x7f800000u, LUT_OR); + setp(B, 0, DS_CMP_EQ, 0, AXR, RZ); + sel(B, RES, T, RES, 0, 0); /* +-0: +-inf */ + setpi(B, 0, DS_CMP_EQ, 0, A_, 0x7f800000u); + sel(B, RES, RZ, RES, 0, 0); /* +inf: +0 */ + setpi(B, 0, DS_CMP_GT, 0, AXR, 0x7f800000u); + seli(B, RES, RES, 0x7fc00000u, 0, 1); /* NaN */ +} size_t omega_ds_body(OmegaDsOp op, OmegaDsInsn *out, size_t max) { Bld B = { out, 0, max, 0 }; if (!out) return 0; @@ -693,6 +1150,11 @@ size_t omega_ds_body(OmegaDsOp op, OmegaDsInsn *out, size_t max) { else if (op == OMEGA_DS_LOG2) body_log2(&B); else if (op == OMEGA_DS_SIGMOID) body_sigmoid(&B); else if (op == OMEGA_DS_TANH) body_tanh(&B); + else if (op == OMEGA_DS_SIN) body_sin(&B); + else if (op == OMEGA_DS_COS) body_cos(&B); + else if (op == OMEGA_DS_ERF) body_erf(&B); + else if (op == OMEGA_DS_GELU) body_gelu(&B); + else if (op == OMEGA_DS_RSQRT) body_rsqrt(&B); else return 0; return B.bad ? 0 : B.n; } @@ -990,9 +1452,9 @@ int omega_ds_check_qmd(const uint32_t *qmd1, uint64_t code_va, char *err, size_t * OMEGA_NUMERIC_ERR_DEVICE return below goes through gb10_devfail, which * prints one GB10_DEVFAIL line to stderr: the step that failed, the driver * return code, errno, the nvrm error text, the wait value and the marker word - * for waits, and the elapsed ms since the launch began. It only reports: the - * return code stays OMEGA_NUMERIC_ERR_DEVICE, there is no retry and no wait - * value changes. */ + * for waits, and the elapsed ms since the launch began. The lifecycle wrapper + * retains resources after uncertain completion and refuses later numeric + * launches. There is no retry and no wait value changes. */ static double gb10_ms_since(const struct timespec *t0) { struct timespec t; timespec_get(&t, TIME_UTC); /* C11; no feature macro needed */ @@ -1008,7 +1470,7 @@ static int gb10_devfail(const char *fn, const char *step, M16NativeContext *ctx, if (wait_ms >= 0) fprintf(stderr, " wait_ms=%ld word=0x%08x want=0x%08x", wait_ms, word ? (unsigned)*word : 0u, (unsigned)want); fprintf(stderr, " elapsed_ms=%.3f\n", ms); - if (do_close) m16_native_close(ctx); + if (do_close) omega_numeric_native_close(ctx); return OMEGA_NUMERIC_ERR_DEVICE; } /* Plain step: drv_rc is the value the call returned. */ @@ -1022,7 +1484,7 @@ int omega_ds_gb10_run(OmegaDsOp op, const uint32_t *a, const uint32_t *b, uint32 char err[256]; int rc = omega_ds_check_args(op, a, b, out, count, err, sizeof(err)); if (rc != OMEGA_NUMERIC_OK) { fprintf(stderr, "omega_ds_gb10_run: refused: %s\n", err); return rc; } - static uint8_t code[OMEGA_DS_MAX_CODE_BYTES]; + uint8_t code[OMEGA_DS_MAX_CODE_BYTES]; size_t code_len = 0; if (omega_ds_build_kernel(op, code, sizeof(code), &code_len) != 0) return OMEGA_NUMERIC_ERR_OPERANDS; if ((rc = omega_ds_check_kernel(op, code, code_len, OMEGA_DS_GPR_COUNT, err, sizeof(err))) != OMEGA_NUMERIC_OK || @@ -1056,7 +1518,7 @@ int omega_ds_gb10_run(OmegaDsOp op, const uint32_t *a, const uint32_t *b, uint32 timespec_get(&t0, TIME_UTC); M16NativeContext ctx; int drc_; - if ((drc_ = m16_native_open(&ctx)) != 0) return GB10_FAIL("open", 0, drc_); + if ((drc_ = omega_numeric_native_open(&ctx)) != 0) return GB10_FAIL("open", 0, drc_); if ((drc_ = m16_native_create_channel(&ctx)) != 0) return GB10_FAIL("channel", 1, drc_); NvrmMem large_pb; if ((drc_ = nvrm_alloc(&ctx.rm, 0x10000, &large_pb)) != 0) return GB10_FAIL("alloc_pb", 1, drc_); @@ -1094,14 +1556,14 @@ int omega_ds_gb10_run(OmegaDsOp op, const uint32_t *a, const uint32_t *b, uint32 if (omega_blackwell_build_qmd0(qmd0, qmd0_va, qmd1_va) != 0 || omega_blackwell_build_qmd1(qmd1, &cfg) != 0 || omega_ds_check_qmd(qmd1, code_mem.va, err, sizeof(err)) != OMEGA_NUMERIC_OK) { fprintf(stderr, "omega_ds_gb10_run: %s\n", err); - m16_native_close(&ctx); + omega_numeric_native_close(&ctx); return OMEGA_NUMERIC_ERR_OPERANDS; } /* the exact bytes in device memory pass the structural check again */ if (omega_ds_check_kernel(op, code_mem.cpu, code_len, (qmd1[35] >> 8) & 0x1ffu, err, sizeof(err)) != OMEGA_NUMERIC_OK || omega_ds_check_digest(op, code_mem.cpu, code_len, err, sizeof(err)) != OMEGA_NUMERIC_OK) { fprintf(stderr, "omega_ds_gb10_run: %s\n", err); - m16_native_close(&ctx); + omega_numeric_native_close(&ctx); return OMEGA_NUMERIC_ERR_OPERANDS; } memcpy(qmd_mem.cpu, qmd0, sizeof(qmd0)); @@ -1152,25 +1614,24 @@ int omega_ds_gb10_run(OmegaDsOp op, const uint32_t *a, const uint32_t *b, uint32 pb[n++] = 0x46464646u; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); if ((drc_ = m16_native_submit_methods(&ctx, pb, n)) != 0) return GB10_FAIL("submit", 1, drc_); - /* Wait long: closing the channel under a running kernel jams the seat. */ - if ((drc_ = m16_native_wait_marker(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, 600000)) != 0) { + /* A timeout is uncertain completion, even after a long wait. */ + if ((drc_ = omega_numeric_native_wait(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, 600000)) != 0) { return GB10_FAIL_WAIT("marker_wait", drc_, 600000, hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD); } volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10); - if (m16_native_wait_marker(hmarker2, 0x46464646u, 600000) != 0) { - m16_native_close(&ctx); - return OMEGA_NUMERIC_ERR_DEVICE; + if ((drc_ = omega_numeric_native_wait(hmarker2, 0x46464646u, 600000)) != 0) { + return GB10_FAIL_WAIT("marker2_wait", drc_, 600000, hmarker2, 0x46464646u); } /* The host marker can land before the last CTAs' stores are visible: the * first chip run (receipt 88930d2f...) read the 0x55 fill pattern for * 49,359,680 SQRT outputs. Read only after the QMD's own release * semaphore (written after the grid completes, with its membar) is 6. */ - if ((drc_ = m16_native_wait_marker(hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE, 600000)) != 0) { + if ((drc_ = omega_numeric_native_wait(hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE, 600000)) != 0) { return GB10_FAIL_WAIT("sem_wait", drc_, 600000, hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE); } __asm__ volatile("dsb sy" ::: "memory"); memcpy(out, out_mem.cpu, count * 4); - m16_native_close(&ctx); + if (omega_numeric_native_close(&ctx) != 0) return OMEGA_NUMERIC_ERR_DEVICE; return OMEGA_NUMERIC_OK; #endif } diff --git a/src/omega_numeric_divsqrt_gb10.h b/src/omega_numeric_divsqrt_gb10.h index a417f32e8..d500d80b0 100644 --- a/src/omega_numeric_divsqrt_gb10.h +++ b/src/omega_numeric_divsqrt_gb10.h @@ -37,7 +37,7 @@ /* DIV and SQRT (E1 row 7) and the transcendentals of E1 row 10, each a * GB10 realization of the frozen CPU sequence in src/omega_numeric_transc.c. */ -typedef enum { OMEGA_DS_DIV = 0, OMEGA_DS_SQRT = 1, OMEGA_DS_EXP2 = 2, OMEGA_DS_LOG2 = 3, OMEGA_DS_SIGMOID = 4, OMEGA_DS_TANH = 5, OMEGA_DS_OP_COUNT = 6 } OmegaDsOp; +typedef enum { OMEGA_DS_DIV = 0, OMEGA_DS_SQRT = 1, OMEGA_DS_EXP2 = 2, OMEGA_DS_LOG2 = 3, OMEGA_DS_SIGMOID = 4, OMEGA_DS_TANH = 5, OMEGA_DS_SIN = 6, OMEGA_DS_COS = 7, OMEGA_DS_ERF = 8, OMEGA_DS_GELU = 9, OMEGA_DS_RSQRT = 10, OMEGA_DS_OP_COUNT = 11 } OmegaDsOp; typedef enum { DSK_IADD3_R = 0, /* IADD3 Rd, PT, PT, [-]Ra, [-]Rb, Rc */ diff --git a/src/omega_numeric_gb10.c b/src/omega_numeric_gb10.c index 787065ad2..32a4d569d 100644 --- a/src/omega_numeric_gb10.c +++ b/src/omega_numeric_gb10.c @@ -13,7 +13,7 @@ #include "omega_blackwell_codegen.h" #include "omega_blackwell_qmd.h" #include "omega_blackwell_submit.h" -#include "m16_native.h" +#include "omega_numeric_native.h" #include #include @@ -26,9 +26,9 @@ * OMEGA_NUMERIC_ERR_DEVICE return below goes through gb10_devfail, which * prints one GB10_DEVFAIL line to stderr: the step that failed, the driver * return code, errno, the nvrm error text, the wait value and the marker word - * for waits, and the elapsed ms since the launch began. It only reports: the - * return code stays OMEGA_NUMERIC_ERR_DEVICE, there is no retry and no wait - * value changes. */ + * for waits, and the elapsed ms since the launch began. The lifecycle wrapper + * retains resources after uncertain completion and refuses later numeric + * launches. There is no retry and no wait value changes. */ static double gb10_ms_since(const struct timespec *t0) { struct timespec t; timespec_get(&t, TIME_UTC); /* C11; no feature macro needed */ @@ -44,7 +44,7 @@ static int gb10_devfail(const char *fn, const char *step, M16NativeContext *ctx, if (wait_ms >= 0) fprintf(stderr, " wait_ms=%ld word=0x%08x want=0x%08x", wait_ms, word ? (unsigned)*word : 0u, (unsigned)want); fprintf(stderr, " elapsed_ms=%.3f\n", ms); - if (do_close) m16_native_close(ctx); + if (do_close) omega_numeric_native_close(ctx); return OMEGA_NUMERIC_ERR_DEVICE; } /* Plain step: drv_rc is the value the call returned. */ @@ -100,7 +100,7 @@ int omega_gb10_execute_simt_op(const char *op_name, timespec_get(&t0, TIME_UTC); M16NativeContext ctx; int drc_; - if ((drc_ = m16_native_open(&ctx)) != 0) return GB10_FAIL("open", 0, drc_); + if ((drc_ = omega_numeric_native_open(&ctx)) != 0) return GB10_FAIL("open", 0, drc_); if ((drc_ = m16_native_create_channel(&ctx)) != 0) return GB10_FAIL("channel", 1, drc_); NvrmMem large_pb; @@ -186,7 +186,7 @@ int omega_gb10_execute_simt_op(const char *op_name, char perr[256]; if (omega_numeric_check_patch(info->op, patch, np, qmd1_words, perr, sizeof(perr)) != OMEGA_NUMERIC_OK) { fprintf(stderr, "omega_gb10_execute_simt_op: %s\n", perr); - m16_native_close(&ctx); + omega_numeric_native_close(&ctx); return OMEGA_NUMERIC_ERR_OPERANDS; } } @@ -264,12 +264,19 @@ int omega_gb10_execute_simt_op(const char *op_name, return GB10_FAIL("submit", 1, drc_); } - if ((drc_ = m16_native_wait_marker(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, 5000)) != 0) { + if ((drc_ = omega_numeric_native_wait(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, 5000)) != 0) { return GB10_FAIL_WAIT("marker_wait", drc_, 5000, hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD); } + /* Match the reduction path: the host marker alone can precede the + * QMD release. Do not expose outputs until both have completed. */ + if ((drc_ = omega_numeric_native_wait(hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE, 5000)) != 0) { + return GB10_FAIL_WAIT("sem_wait", drc_, 5000, hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE); + } + __asm__ volatile("dsb sy" ::: "memory"); + memcpy(out_res, out_mem.cpu, count * sizeof(float)); - m16_native_close(&ctx); + if (omega_numeric_native_close(&ctx) != 0) return OMEGA_NUMERIC_ERR_DEVICE; return OMEGA_NUMERIC_OK; } diff --git a/src/omega_numeric_ldst_gb10.c b/src/omega_numeric_ldst_gb10.c new file mode 100644 index 000000000..3e3e72eed --- /dev/null +++ b/src/omega_numeric_ldst_gb10.c @@ -0,0 +1,373 @@ +/* E1 row 2: general global load/store kernels for the GB10. See omega_numeric_ldst_gb10.h. */ +#include "omega_numeric_ldst_gb10.h" +#include "omega_numeric.h" +#include "omega_numeric_divsqrt_gb10.h" +#include "omega_blackwell_encoder.h" +#include "omega_blackwell_qmd.h" + +#include +#include +#include +#include + +#ifndef OMEGA_NUMERIC_CPU_ONLY +#include "omega_blackwell_submit.h" +#include "omega_numeric_native.h" +#endif + +#define NINSN 24u +#define PRO_INSNS 17u +#define I_LD_DST 12u /* the load's destination register: aligned for 128-bit */ +#define I_IMAD_IN 12u /* prologue instruction indices patched */ +#define I_LDG_A 13u +#define I_IMAD_OUT 16u +#define I_IADD3 17u +#define I_STG 18u +#define I_EXIT 19u +#define I_BRA 20u +#define I_NOP 21u + +static const size_t LD_BYTES[OMEGA_LD_COUNT] = { 1, 1, 2, 2, 4, 8, 16 }; +static const size_t ST_BYTES[OMEGA_ST_COUNT] = { 1, 2, 4, 8, 16 }; +static const unsigned LD_SIZE[OMEGA_LD_COUNT] = { 0, 1, 2, 3, 4, 5, 6 }; +static const unsigned ST_SIZE[OMEGA_ST_COUNT] = { 0, 2, 4, 5, 6 }; +static const char *const LD_SUFFIX[OMEGA_LD_COUNT] = { ".E.U8", ".E.S8", ".E.U16", ".E.S16", ".E", ".E.64", ".E.128" }; +static const char *const ST_SUFFIX[OMEGA_ST_COUNT] = { ".E.U8", ".E.U16", ".E", ".E.64", ".E.128" }; +static const char *const LD_NAME[OMEGA_LD_COUNT] = { "U8", "S8", "U16", "S16", "B32", "B64", "B128" }; +static const char *const ST_NAME[OMEGA_ST_COUNT] = { "B8", "B16", "B32", "B64", "B128" }; + +/* Texts of prologue instructions 0..16 (same as src/omega_numeric_divsqrt_gb10.c PROLOGUE_TEXT). */ +static const char *const PROLOGUE_TEXT[PRO_INSNS] = { + "LDC R1, c[0x0][0x37c]", "S2R R9, SR_CTAID.X", "LDCU UR4, c[0x0][0x360]", "S2R R0, SR_TID.X", + "LDCU UR5, c[0x0][0x398]", "IMAD R9, R9, UR4, R0", "ISETP.GE.U32.AND P0, PT, R9, UR5, PT", "@P0 EXIT", + "LDC.64 R2, c[0x0][0x380]", "LDCU.64 UR4, c[0x0][0x358]", "LDC.64 R4, c[0x0][0x388]", + "LDC.64 R6, c[0x0][0x390]", "IMAD.WIDE.U32 R2, R9, 0x4, R2", "LDG.E R2, desc[UR4][R2.64]", + "IMAD.WIDE.U32 R4, R9, 0x4, R4", "LDG.E R5, desc[UR4][R4.64]", "IMAD.WIDE.U32 R6, R9, 0x4, R6", +}; + +size_t omega_ld_bytes(OmegaLdKind k) { return k < OMEGA_LD_COUNT ? LD_BYTES[k] : 0; } +size_t omega_st_bytes(OmegaStKind k) { return k < OMEGA_ST_COUNT ? ST_BYTES[k] : 0; } + +const char *omega_ldst_describe(const OmegaLdstSpec *s, char *buf, size_t len) { + snprintf(buf, len, "%s@%u%+d -> %s@%u%+d", s->ld < OMEGA_LD_COUNT ? LD_NAME[s->ld] : "?", s->in_stride, (int)s->in_off, + s->st < OMEGA_ST_COUNT ? ST_NAME[s->st] : "?", s->out_stride, (int)s->out_off); + return buf; +} + +static int refuse(char *why, size_t n, const char *fmt, ...) { + if (why && n) { va_list ap; va_start(ap, fmt); vsnprintf(why, n, fmt, ap); va_end(ap); } + return -1; +} + +int omega_ldst_check_spec(const OmegaLdstSpec *s, size_t count, char *why, size_t why_len) { + if (!s) return refuse(why, why_len, "no spec"); + if (s->ld >= OMEGA_LD_COUNT) return refuse(why, why_len, "unknown load kind %u", s->ld); + if (s->st >= OMEGA_ST_COUNT) return refuse(why, why_len, "unknown store kind %u", s->st); + size_t lb = LD_BYTES[s->ld], sb = ST_BYTES[s->st], fill = lb < 4 ? 4 : lb; + if (sb > fill) return refuse(why, why_len, "store of %zu bytes is wider than the %zu bytes the load fills", sb, fill); + if (s->in_stride < lb || s->in_stride % lb) return refuse(why, why_len, "input stride %u is not a multiple of %zu >= %zu", s->in_stride, lb, lb); + if (s->out_stride < sb || s->out_stride % sb) return refuse(why, why_len, "output stride %u is not a multiple of %zu >= %zu", s->out_stride, sb, sb); + if (s->in_stride >= (1u << 24) || s->out_stride >= (1u << 24)) return refuse(why, why_len, "stride must be below 2^24"); + if (s->in_off < -(1 << 23) || s->in_off >= (1 << 23) || s->out_off < -(1 << 23) || s->out_off >= (1 << 23)) + return refuse(why, why_len, "offset outside the signed 24-bit field"); + if (s->in_off % (int32_t)lb) return refuse(why, why_len, "input offset %d is not a multiple of %zu", (int)s->in_off, lb); + if (s->out_off % (int32_t)sb) return refuse(why, why_len, "output offset %d is not a multiple of %zu", (int)s->out_off, sb); + if (count == 0 || count > OMEGA_DS_MAX_BATCH) return refuse(why, why_len, "count %zu outside 1..%u", count, OMEGA_DS_MAX_BATCH); + return 0; +} + +int omega_ldst_extent(const OmegaLdstSpec *s, size_t count, int64_t *in_lo, int64_t *in_hi, int64_t *out_lo, int64_t *out_hi) { + if (omega_ldst_check_spec(s, count, NULL, 0) != 0) return -1; + int64_t n1 = (int64_t)count - 1; + *in_lo = s->in_off; + *in_hi = (int64_t)s->in_off + n1 * (int64_t)s->in_stride + (int64_t)LD_BYTES[s->ld]; + *out_lo = s->out_off; + *out_hi = (int64_t)s->out_off + n1 * (int64_t)s->out_stride + (int64_t)ST_BYTES[s->st]; + return 0; +} + +/* ---- kernel -------------------------------------------------------------------- */ + +static void put_words(uint8_t *p, const uint32_t w[4]) { + for (int i = 0; i < 4; i++) { p[4 * i] = (uint8_t)w[i]; p[4 * i + 1] = (uint8_t)(w[i] >> 8); p[4 * i + 2] = (uint8_t)(w[i] >> 16); p[4 * i + 3] = (uint8_t)(w[i] >> 24); } +} + +int omega_ldst_build_kernel(const OmegaLdstSpec *s, uint8_t *code, size_t max, size_t *out_len) { + uint8_t va[OMEGA_BW_VECADD_CODE_SIZE]; + size_t vl = 0; + if (!code || max < OMEGA_LDST_CODE_BYTES || omega_ldst_check_spec(s, 1, NULL, 0) != 0) return -1; + if (omega_blackwell_encode_vecadd(va, sizeof(va), &vl) != 0 || vl != OMEGA_BW_VECADD_CODE_SIZE) return -1; + memset(code, 0, OMEGA_LDST_CODE_BYTES); + for (size_t k = 0; k < I_EXIT + 2; k++) memcpy(code + 16 * k, va + 16 * k, 16); /* 0..16 prologue; 17,18 overwritten below */ + memcpy(code + 16 * I_EXIT, va + 16 * 19, 16); /* EXIT */ + memcpy(code + 16 * I_BRA, va + 16 * 20, 16); /* BRA to self */ + for (size_t k = I_NOP; k < NINSN; k++) memcpy(code + 16 * k, va + 16 * 21, 16); /* NOP */ + uint32_t w[4]; + /* IMAD.WIDE.U32 R2, R9, in_stride, R2 */ + for (int i = 0; i < 4; i++) { const uint8_t *p = va + 16 * I_IMAD_IN + 4 * i; w[i] = p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; } + w[1] = s->in_stride; + put_words(code + 16 * I_IMAD_IN, w); + /* LDG. R12, desc[UR4][R2.64+off] */ + w[0] = 0x7981u | (I_LD_DST << 16) | (2u << 24); + w[1] = 4u | (((uint32_t)s->in_off & 0xffffffu) << 8); + w[2] = 0x0c1e1100u | (LD_SIZE[s->ld] << 9); + w[3] = 0x002f2200u; + put_words(code + 16 * I_LDG_A, w); + /* IMAD.WIDE.U32 R6, R9, out_stride, R6 */ + for (int i = 0; i < 4; i++) { const uint8_t *p = va + 16 * I_IMAD_OUT + 4 * i; w[i] = p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; } + w[1] = s->out_stride; + put_words(code + 16 * I_IMAD_OUT, w); + /* IADD3 R9, PT, PT, R12, R5, RZ : waits on both load barriers (control word of vecadd's IADD3) */ + w[0] = 0x7210u | (9u << 16) | (I_LD_DST << 24); + w[1] = 5u; + w[2] = 0x07ffe0ffu; + w[3] = 0x010fca00u; + put_words(code + 16 * I_IADD3, w); + /* STG. desc[UR4][R6.64+off], R12 */ + w[0] = 0x7986u | (6u << 24); + w[1] = I_LD_DST | (((uint32_t)s->out_off & 0xffffffu) << 8); + w[2] = 0x0c101104u | (ST_SIZE[s->st] << 9); + w[3] = 0x000fe200u; + put_words(code + 16 * I_STG, w); + if (out_len) *out_len = OMEGA_LDST_CODE_BYTES; + return 0; +} + +static int signed_off(char *dst, size_t n, int32_t off) { + if (off == 0) { dst[0] = '\0'; return 0; } + return snprintf(dst, n, "+%s0x%x", off < 0 ? "-" : "", (unsigned)(off < 0 ? -(int64_t)off : off)); +} + +int omega_ldst_listing(const OmegaLdstSpec *s, char *buf, size_t len) { + if (!buf || omega_ldst_check_spec(s, 1, NULL, 0) != 0) return -1; + size_t pos = 0; + char io[24], oo[24]; + signed_off(io, sizeof io, s->in_off); + signed_off(oo, sizeof oo, s->out_off); +#define LINE(...) do { int w_ = snprintf(buf + pos, pos < len ? len - pos : 0, __VA_ARGS__); \ + if (w_ < 0 || pos + (size_t)w_ >= len) { return -1; } \ + pos += (size_t)w_; } while (0) + for (size_t k = 0; k < PRO_INSNS; k++) { + if (k == I_IMAD_IN) LINE("%04zx IMAD.WIDE.U32 R2, R9, 0x%x, R2 ;\n", k * 16, s->in_stride); + else if (k == I_LDG_A) LINE("%04zx LDG%s R%u, desc[UR4][R2.64%s] ;\n", k * 16, LD_SUFFIX[s->ld], I_LD_DST, io); + else if (k == I_IMAD_OUT) LINE("%04zx IMAD.WIDE.U32 R6, R9, 0x%x, R6 ;\n", k * 16, s->out_stride); + else LINE("%04zx %s ;\n", k * 16, PROLOGUE_TEXT[k]); + } + LINE("%04x IADD3 R9, PT, PT, R%u, R5, RZ ;\n", I_IADD3 * 16, I_LD_DST); + LINE("%04x STG%s desc[UR4][R6.64%s], R%u ;\n", I_STG * 16, ST_SUFFIX[s->st], oo, I_LD_DST); + LINE("%04x EXIT ;\n", I_EXIT * 16); + LINE("%04x BRA 0x%x;\n", I_BRA * 16, I_BRA * 16); + for (size_t k = I_NOP; k < NINSN; k++) LINE("%04zx NOP;\n", k * 16); +#undef LINE + return 0; +} + +static void get_words(const uint8_t *p, uint32_t w[4]) { + for (int i = 0; i < 4; i++) w[i] = p[4 * i] | p[4 * i + 1] << 8 | p[4 * i + 2] << 16 | (uint32_t)p[4 * i + 3] << 24; +} + +int omega_ldst_check_kernel(const OmegaLdstSpec *s, const uint8_t *code, size_t len, char *why, size_t why_len) { + uint8_t want[OMEGA_LDST_CODE_BYTES]; + size_t wl = 0; + if (!code || len != OMEGA_LDST_CODE_BYTES) return refuse(why, why_len, "ldst kernel length %zu != %u", len, OMEGA_LDST_CODE_BYTES); + /* decode the fields back out of the words, then require a spec-for-spec rebuild */ + uint32_t w[4]; + OmegaLdstSpec d = *s; + get_words(code + 16 * I_LDG_A, w); + unsigned lsz = (w[2] >> 9) & 7u; + int found = 0; + for (unsigned k = 0; k < OMEGA_LD_COUNT; k++) if (LD_SIZE[k] == lsz) { d.ld = (uint8_t)k; found = 1; } + if (!found) return refuse(why, why_len, "ldst: LDG size field %u unknown", lsz); /* CHECK:ldst_ldsize */ + d.in_off = (int32_t)(w[1] & 0xffffff00u) >> 8; + get_words(code + 16 * I_STG, w); + unsigned ssz = (w[2] >> 9) & 7u; + found = 0; + for (unsigned k = 0; k < OMEGA_ST_COUNT; k++) if (ST_SIZE[k] == ssz) { d.st = (uint8_t)k; found = 1; } + if (!found) return refuse(why, why_len, "ldst: STG size field %u unknown", ssz); /* CHECK:ldst_stsize */ + d.out_off = (int32_t)(w[1] & 0xffffff00u) >> 8; + get_words(code + 16 * I_IMAD_IN, w); + d.in_stride = w[1]; + get_words(code + 16 * I_IMAD_OUT, w); + d.out_stride = w[1]; + if (omega_ldst_check_spec(&d, 1, why, why_len) != 0) return -1; /* CHECK:ldst_spec */ + if (d.ld != s->ld || d.st != s->st || d.in_stride != s->in_stride || d.out_stride != s->out_stride || + d.in_off != s->in_off || d.out_off != s->out_off) + return refuse(why, why_len, "ldst: kernel encodes a different spec than requested"); /* CHECK:ldst_same_spec */ + if (omega_ldst_build_kernel(&d, want, sizeof want, &wl) != 0 || wl != len || memcmp(want, code, len) != 0) + return refuse(why, why_len, "ldst: kernel words differ from the rebuilt kernel"); /* CHECK:ldst_rebuild */ + return 0; +} + +/* ---- host model ---------------------------------------------------------------- */ + +int omega_ldst_host_run(const OmegaLdstSpec *s, const uint8_t *in_buf, size_t in_len, uint8_t *out_buf, size_t out_len, + size_t pad, size_t count) { + int64_t il, ih, ol, oh; + if (!in_buf || !out_buf || omega_ldst_extent(s, count, &il, &ih, &ol, &oh) != 0) return -1; + if (il < -(int64_t)pad || ih > (int64_t)in_len - (int64_t)pad || ol < -(int64_t)pad || oh > (int64_t)out_len - (int64_t)pad) return -1; + size_t lb = LD_BYTES[s->ld], sb = ST_BYTES[s->st]; + for (size_t i = 0; i < count; i++) { + uint8_t reg[16] = { 0 }; + const uint8_t *src = in_buf + pad + (int64_t)s->in_off + (int64_t)i * s->in_stride; + uint8_t *dst = out_buf + pad + (int64_t)s->out_off + (int64_t)i * s->out_stride; + if (s->ld == OMEGA_LD_S8) { int32_t v = (int8_t)src[0]; memcpy(reg, &v, 4); } + else if (s->ld == OMEGA_LD_S16) { int32_t v = (int16_t)(src[0] | src[1] << 8); memcpy(reg, &v, 4); } + else { for (size_t b = 0; b < lb; b++) reg[b] = src[b]; } /* U8 U16 zero extend: the rest of reg[0..3] is 0 */ + for (size_t b = 0; b < sb; b++) dst[b] = reg[b]; + } + return 0; +} + +/* ---- chip ---------------------------------------------------------------------- */ + +static int g_spec_id = -1; +void omega_ldst_gb10_set_spec_id(int id) { g_spec_id = id; } +/* One stderr line saying which device step failed, then the device error code. No other behaviour. */ +#define LDST_DEVERR(step, rc) (fprintf(stderr, "OMEGA_DEVERR step=%s rc=%d spec=%d\n", (step), (int)(rc), g_spec_id), OMEGA_NUMERIC_ERR_DEVICE) + +int omega_ldst_gb10_run(const OmegaLdstSpec *s, const uint8_t *in_buf, size_t in_len, uint8_t *out_buf, size_t out_len, + size_t pad, size_t count) { + char err[256]; + int64_t il, ih, ol, oh; + if (!in_buf || !out_buf || omega_ldst_check_spec(s, count, err, sizeof err) != 0) { + fprintf(stderr, "omega_ldst_gb10_run: refused: %s\n", err); + return OMEGA_NUMERIC_ERR_BAD_ARGS; + } + if (omega_ldst_extent(s, count, &il, &ih, &ol, &oh) != 0 || il < -(int64_t)pad || ih > (int64_t)in_len - (int64_t)pad || + ol < -(int64_t)pad || oh > (int64_t)out_len - (int64_t)pad || pad > OMEGA_LDST_PAD) { + fprintf(stderr, "omega_ldst_gb10_run: refused: access outside the buffers\n"); + return OMEGA_NUMERIC_ERR_OPERANDS; + } + uint8_t code[OMEGA_LDST_CODE_BYTES]; /* per call: built before the numeric owner is acquired */ + size_t code_len = 0; + if (omega_ldst_build_kernel(s, code, sizeof code, &code_len) != 0 || omega_ldst_check_kernel(s, code, code_len, err, sizeof err) != 0) { + fprintf(stderr, "omega_ldst_gb10_run: refused: %s\n", err); + return OMEGA_NUMERIC_ERR_OPERANDS; + } + { + uint32_t q[OMEGA_BW_QMD_WORDS]; + OmegaBlackwellQmdConfig c = { .code_va = 0x200000000ull, .cbank_va = 0x200100000ull, .scratch_va = 0x200204000ull, + .sem_va = 0x200202000ull, .qmd0_va = 0x200200000ull, .qmd1_va = 0x200201000ull, + .num_elements = (uint32_t)count, .gpr_count = OMEGA_DS_GPR_COUNT }; + omega_numeric_launch_shape(count, &c.threads_per_block, &c.grid_width); + if (omega_blackwell_build_qmd1(q, &c) != 0 || omega_ds_check_qmd(q, c.code_va, err, sizeof err) != OMEGA_NUMERIC_OK) { + fprintf(stderr, "omega_ldst_gb10_run: refused: %s\n", err); + return OMEGA_NUMERIC_ERR_OPERANDS; + } + } +#ifdef OMEGA_NUMERIC_CPU_ONLY + return LDST_DEVERR("cpu_only", OMEGA_NUMERIC_ERR_DEVICE); +#else + static const uint32_t SETUP[18] = { + 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, + 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000, + 0x20012559, 0x00000000, + }; + M16NativeContext ctx; + int drc; + if ((drc = omega_numeric_native_open(&ctx)) != 0) return LDST_DEVERR("open", drc); + if ((drc = m16_native_create_channel(&ctx)) != 0) { omega_numeric_native_close(&ctx); return LDST_DEVERR("open", drc); } + NvrmMem large_pb; + if ((drc = nvrm_alloc(&ctx.rm, 0x10000, &large_pb)) != 0) { omega_numeric_native_close(&ctx); return LDST_DEVERR("alloc", drc); } + ctx.pb_mem = large_pb; + /* the prologue also reads 4 bytes at index i of the "b" buffer: give it the input, zero padded to 4*count */ + size_t in_dev = in_len > count * 4 ? in_len : count * 4; + size_t in_bytes = (in_dev + 0xfffULL) & ~0xfffULL, out_bytes = (out_len + 0xfffULL) & ~0xfffULL; + NvrmMem code_mem, cbank_mem, a_mem, out_mem, marker_mem, qmd_mem; + if ((drc = nvrm_alloc(&ctx.rm, OMEGA_DS_MAX_CODE_BYTES, &code_mem)) != 0 || (drc = nvrm_alloc(&ctx.rm, 0x1000, &cbank_mem)) != 0 || + (drc = nvrm_alloc(&ctx.rm, in_bytes, &a_mem)) != 0 || (drc = nvrm_alloc(&ctx.rm, out_bytes, &out_mem)) != 0 || + (drc = nvrm_alloc(&ctx.rm, 0x1000, &marker_mem)) != 0 || (drc = nvrm_alloc(&ctx.rm, 0x10000, &qmd_mem)) != 0) { + omega_numeric_native_close(&ctx); + return LDST_DEVERR("alloc", drc); + } + memset(a_mem.cpu, 0, in_bytes); + memcpy(a_mem.cpu, in_buf, in_len); + memcpy(out_mem.cpu, out_buf, out_len); + memcpy(code_mem.cpu, code, code_len); + + uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; + omega_blackwell_build_cbank_driver(cbank_data, cbank_mem.va); + cbank_data[223] = 0; + uint64_t ain = a_mem.va + pad, aout = out_mem.va + pad; + uint32_t args[10] = { (uint32_t)ain, (uint32_t)(ain >> 32), (uint32_t)a_mem.va, (uint32_t)(a_mem.va >> 32), + (uint32_t)aout, (uint32_t)(aout >> 32), (uint32_t)count, 0, 0, 0 }; + memcpy(cbank_mem.cpu, cbank_data, sizeof(cbank_data)); + memcpy((uint8_t *)cbank_mem.cpu + 0x380, args, sizeof(args)); + + uint64_t qmd0_va = qmd_mem.va, qmd1_va = qmd_mem.va + 0x1000, sem_va = qmd_mem.va + 0x2000; + OmegaBlackwellQmdConfig cfg = { .code_va = code_mem.va, .cbank_va = cbank_mem.va, .scratch_va = qmd_mem.va + 0x4000, + .sem_va = sem_va, .qmd0_va = qmd0_va, .qmd1_va = qmd1_va, + .num_elements = (uint32_t)count, .gpr_count = OMEGA_DS_GPR_COUNT }; + omega_numeric_launch_shape(count, &cfg.threads_per_block, &cfg.grid_width); + uint32_t qmd0[OMEGA_BW_QMD_WORDS], qmd1[OMEGA_BW_QMD_WORDS]; + if (omega_blackwell_build_qmd0(qmd0, qmd0_va, qmd1_va) != 0 || omega_blackwell_build_qmd1(qmd1, &cfg) != 0 || + omega_ds_check_qmd(qmd1, code_mem.va, err, sizeof err) != OMEGA_NUMERIC_OK || + omega_ldst_check_kernel(s, code_mem.cpu, code_len, err, sizeof err) != 0) { + fprintf(stderr, "omega_ldst_gb10_run: %s\n", err); + omega_numeric_native_close(&ctx); + return OMEGA_NUMERIC_ERR_OPERANDS; + } + memcpy(qmd_mem.cpu, qmd0, sizeof(qmd0)); + memcpy((uint8_t *)qmd_mem.cpu + 0x1000, qmd1, sizeof(qmd1)); + volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)qmd_mem.cpu + 0x2000); + volatile uint32_t *hmarker = (volatile uint32_t *)marker_mem.cpu; + *hsem = 0; + *hmarker = 0; +#ifndef OMEGA_C3_PROTECT_OFF /* C3 hardening, same as omega_ds_gb10_run (-DOMEGA_C3_PROTECT_OFF = A/B control arm) */ + *(volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10) = 0; +#endif + __asm__ volatile("dsb sy" ::: "memory"); + + static uint32_t pb[1024]; + size_t n = 0; + memcpy(&pb[n], SETUP, sizeof(SETUP)); n += 18; + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(cbank_mem.va >> 32); pb[n++] = (uint32_t)cbank_mem.va; + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (224 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); + memcpy(&pb[n], cbank_data, 224 * 4); n += 224; + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((cbank_mem.va + 0x380) >> 32); pb[n++] = (uint32_t)(cbank_mem.va + 0x380); + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000028; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (10 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); + memcpy(&pb[n], args, 10 * 4); n += 10; + pb[n++] = (98 << 16) | (1 << 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, 96 * 4); n += 96; + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va; + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (1 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); + pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; + pb[n++] = (98 << 16) | (1 << 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, 96 * 4); n += 96; + pb[n++] = nvrm_mthd(0, 0x005c, 5); + pb[n++] = (uint32_t)marker_mem.va; pb[n++] = (uint32_t)(marker_mem.va >> 32); + pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); +#ifndef OMEGA_C3_PROTECT_OFF + /* C3 hardening, copied from omega_ds_gb10_run (src/omega_numeric_divsqrt_gb10.c): after the WFI marker + * flush GPU L2 dirty lines to memory (NVC96F_MEM_OP_A..D = 0x28..0x34, D bits 31:27 OPERATION = + * L2_FLUSH_DIRTY 0x10), then a second WFI marker the host waits for before the readback. */ + pb[n++] = nvrm_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27); + pb[n++] = nvrm_mthd(0, 0x005c, 5); + pb[n++] = (uint32_t)(marker_mem.va + 0x10); pb[n++] = (uint32_t)((marker_mem.va + 0x10) >> 32); + pb[n++] = 0x46464646u; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); +#endif + + if ((drc = m16_native_submit_methods(&ctx, pb, n)) != 0) { omega_numeric_native_close(&ctx); return LDST_DEVERR("submit", drc); } + /* Wait long: closing the channel under a running kernel jams the seat. */ + if ((drc = omega_numeric_native_wait(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, 600000)) != 0) return LDST_DEVERR("wait", drc); +#ifndef OMEGA_C3_PROTECT_OFF + volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10); + if ((drc = omega_numeric_native_wait(hmarker2, 0x46464646u, 600000)) != 0) return LDST_DEVERR("marker2_wait", drc); +#endif + if ((drc = omega_numeric_native_wait(hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE, 600000)) != 0) return LDST_DEVERR("sem_wait", drc); + __asm__ volatile("dsb sy" ::: "memory"); + memcpy(out_buf, out_mem.cpu, out_len); + if ((drc = omega_numeric_native_close(&ctx)) != 0) return LDST_DEVERR("close", drc); + return OMEGA_NUMERIC_OK; +#endif +} diff --git a/src/omega_numeric_ldst_gb10.h b/src/omega_numeric_ldst_gb10.h new file mode 100644 index 000000000..c9e499011 --- /dev/null +++ b/src/omega_numeric_ldst_gb10.h @@ -0,0 +1,78 @@ +#ifndef OMEGA_NUMERIC_LDST_GB10_H +#define OMEGA_NUMERIC_LDST_GB10_H +/* + * E1 row 2: general global load/store on the GB10 (docs/numeric/E1_LDST_GB10.md). + * + * Contract. One thread per element i < count copies one element from the input + * to the output through the register file: + * reg = LOAD_ld ( in + i * in_stride + in_off ) + * STORE_st( out + i * out_stride + out_off, reg ) + * ld is U8, S8, U16, S16 (zero or sign extended to 32 bits), B32, B64 or B128. + * st is B8, B16, B32, B64 or B128 (the low st bytes of the register file, + * little endian). Strides are byte counts applied with a 64-bit multiply-add, + * offsets are signed 24-bit byte offsets in the instruction. + * + * Rules (omega_ldst_check_spec): a store may not be wider than what the load + * filled (4 bytes for the narrow loads, else the load width); stride and + * offset of each side are multiples of that side's width and the stride is at + * least the width (so output elements never overlap); stride < 2^24; offset in + * [-2^23, 2^23); count <= OMEGA_DS_MAX_BATCH. Buffer bases are 16-byte aligned. + * + * Encodings (every field below was read back with nvdisasm 13.0.85 -b SM121 as + * an offline decoder, see tools/ldst_nvdisasm_check.sh): + * LDG: w0 = 0x7981 | Rd<<16 | Ra<<24; w1 = UR | off24<<8; + * w2 = 0x0c1e1100 | size<<9; size 0 U8, 1 S8, 2 U16, 3 S16, 4 32, 5 64, 6 128 + * STG: w0 = 0x7986 | Ra<<24; w1 = Rdata | off24<<8; + * w2 = 0x0c100004 | 0x1100 | size<<9 (UR4); size 0 8, 2 16, 4 32, 5 64, 6 128 + * IMAD.WIDE.U32 imm: w1 = imm (the stride in bytes). + * The kernel keeps the 17 verified prologue words of the vecadd kernel + * (src/omega_blackwell_encoder.c); only the words above are new. + */ +#include +#include + +typedef enum { OMEGA_LD_U8 = 0, OMEGA_LD_S8, OMEGA_LD_U16, OMEGA_LD_S16, OMEGA_LD_B32, OMEGA_LD_B64, OMEGA_LD_B128, OMEGA_LD_COUNT } OmegaLdKind; +typedef enum { OMEGA_ST_B8 = 0, OMEGA_ST_B16, OMEGA_ST_B32, OMEGA_ST_B64, OMEGA_ST_B128, OMEGA_ST_COUNT } OmegaStKind; + +typedef struct { + uint8_t ld, st; + uint32_t in_stride, out_stride; /* bytes */ + int32_t in_off, out_off; /* bytes, signed 24-bit */ +} OmegaLdstSpec; + +#define OMEGA_LDST_CODE_BYTES 384u /* 24 instructions */ +#define OMEGA_LDST_PAD 0x10000u /* bytes in front of element 0 the executor allocates, so negative offsets stay in the buffer */ + +size_t omega_ld_bytes(OmegaLdKind k); +size_t omega_st_bytes(OmegaStKind k); +const char *omega_ldst_describe(const OmegaLdstSpec *s, char *buf, size_t len); + +/* 0 ok, -1 refused with the reason in why. */ +int omega_ldst_check_spec(const OmegaLdstSpec *s, size_t count, char *why, size_t why_len); + +/* Lowest and one-past-highest byte (relative to the base) each side touches over count elements. */ +int omega_ldst_extent(const OmegaLdstSpec *s, size_t count, int64_t *in_lo, int64_t *in_hi, int64_t *out_lo, int64_t *out_hi); + +/* The kernel image, its expected nvdisasm listing (one "addr text ;" line per instruction), a + * structural check (rebuilds the kernel from the fields it decodes and compares every byte). */ +int omega_ldst_build_kernel(const OmegaLdstSpec *s, uint8_t *code, size_t max, size_t *out_len); +int omega_ldst_listing(const OmegaLdstSpec *s, char *buf, size_t len); +int omega_ldst_check_kernel(const OmegaLdstSpec *s, const uint8_t *code, size_t len, char *why, size_t why_len); + +/* Host model. in/out point at element-0 base addresses; in_len/out_len are the bytes available + * from lo_pad bytes before the base to the end. Returns 0, or -1 when any access leaves + * [-pad, len-pad) or the spec is refused. */ +int omega_ldst_host_run(const OmegaLdstSpec *s, const uint8_t *in_buf, size_t in_len, uint8_t *out_buf, size_t out_len, + size_t pad, size_t count); + +/* GB10: same contract on the chip. in_buf/out_buf are whole buffers with pad bytes before element 0; + * out_buf is copied in first (so the caller's fill pattern is what unwritten bytes read back as) + * and copied back after. OMEGA_NUMERIC_* code; OMEGA_NUMERIC_ERR_DEVICE in a CPU-only build. */ +int omega_ldst_gb10_run(const OmegaLdstSpec *s, const uint8_t *in_buf, size_t in_len, uint8_t *out_buf, size_t out_len, + size_t pad, size_t count); + + +/* Label printed in the OMEGA_DEVERR stderr line (spec=); the chip harness sets the table index. Default -1. */ +void omega_ldst_gb10_set_spec_id(int id); + +#endif diff --git a/src/omega_numeric_lifecycle.h b/src/omega_numeric_lifecycle.h new file mode 100644 index 000000000..8360633c5 --- /dev/null +++ b/src/omega_numeric_lifecycle.h @@ -0,0 +1,31 @@ +#ifndef OMEGA_NUMERIC_LIFECYCLE_H +#define OMEGA_NUMERIC_LIFECYCLE_H + +#include + +/* One owner across the SIMT, reduction and DIV/SQRT launchers. Defined in + * omega_numeric.c, which all three already link. No reset API: an uncertain + * completion requires ending the process and investigating the device. This + * does not assert that process exit itself resets or recovers the GPU. */ +enum { OMEGA_NUMERIC_NATIVE_IDLE, OMEGA_NUMERIC_NATIVE_BUSY, + OMEGA_NUMERIC_NATIVE_UNCERTAIN }; +extern atomic_int omega_numeric_native_state; + +static inline int omega_numeric_native_acquire(void) { + int expected = OMEGA_NUMERIC_NATIVE_IDLE; + return atomic_compare_exchange_strong(&omega_numeric_native_state, &expected, + OMEGA_NUMERIC_NATIVE_BUSY) ? 0 : -1; +} +static inline int omega_numeric_native_uncertain(void) { + return atomic_load(&omega_numeric_native_state) == OMEGA_NUMERIC_NATIVE_UNCERTAIN; +} +static inline void omega_numeric_native_poison(void) { + atomic_store(&omega_numeric_native_state, OMEGA_NUMERIC_NATIVE_UNCERTAIN); +} +static inline void omega_numeric_native_release(void) { + int expected = OMEGA_NUMERIC_NATIVE_BUSY; + /* Never clear a poison latch, even if a cleanup caller arrives late. */ + (void)atomic_compare_exchange_strong(&omega_numeric_native_state, &expected, + OMEGA_NUMERIC_NATIVE_IDLE); +} +#endif diff --git a/src/omega_numeric_native.h b/src/omega_numeric_native.h new file mode 100644 index 000000000..806253584 --- /dev/null +++ b/src/omega_numeric_native.h @@ -0,0 +1,45 @@ +#ifndef OMEGA_NUMERIC_NATIVE_H +#define OMEGA_NUMERIC_NATIVE_H + +#include "omega_numeric_lifecycle.h" +#include "m16_native.h" +#include +#include + +/* Numeric launchers must use these wrappers together. The pinned M16 submit + * returns failure before ringing the doorbell, so a submit failure can close. + * Once submitted, a failed wait proves neither completion nor cancellation. */ +static inline int omega_numeric_native_open(M16NativeContext *ctx) { + memset(ctx, 0, sizeof *ctx); + if (omega_numeric_native_acquire() != 0) { + snprintf(ctx->rm.err, sizeof ctx->rm.err, + "numeric GPU owner busy or completion uncertain; submission refused"); + return -1; + } + int rc = m16_native_open(ctx); + if (rc != 0) omega_numeric_native_release(); + return rc; +} + +static inline int omega_numeric_native_close(M16NativeContext *ctx) { + if (omega_numeric_native_uncertain()) return -1; + int rc = m16_native_close(ctx); + if (rc != 0) omega_numeric_native_poison(); + else omega_numeric_native_release(); + return rc; +} + +static inline int omega_numeric_native_wait(volatile uint32_t *word, + uint32_t want, uint64_t timeout_ms) { + int rc = m16_native_wait_marker(word, want, timeout_ms); + /* M16's wait uses a monotonic >= comparison. These are fixed payloads, + * not sequence counters: a different word must never authorize readback. */ + if (rc == 0 && (!word || *word != want)) rc = -1; + if (rc != 0) { + omega_numeric_native_poison(); + fprintf(stderr, "GB10_COMPLETION_UNCERTAIN: numeric resources retained; " + "further numeric device work refused in this process\n"); + } + return rc; +} +#endif diff --git a/src/omega_numeric_reduce.h b/src/omega_numeric_reduce.h index ce2a6b4ba..4e8be2a44 100644 --- a/src/omega_numeric_reduce.h +++ b/src/omega_numeric_reduce.h @@ -89,8 +89,8 @@ float omega_reduce_sequential_sum_not_contract(const float *x, size_t n); * no arithmetic). * SUM the chip-proven REDUCE_SUM patch words, own launch with a semaphore wait. * MAX, MIN this file's warp patch: five SHFL.DOWN (16..1) + FMNMX pairs. - * MEAN SUM levels on the chip, then omega_math_div(SUM, u2f(n)) on the - * host: a declared host step until a GB10 DIV is merged. + * MEAN SUM levels on the chip, then omega_math_div(SUM, u2f(n)) as the GB10 + * DIV kernel (E1 row 7), one element. No host step. * * omega_reduce_gb10_check runs every pre-submission check (CHECK: markers) * without opening a device. diff --git a/src/omega_numeric_reduce_gb10.c b/src/omega_numeric_reduce_gb10.c index 2cd2aa114..f64bcd2f1 100644 --- a/src/omega_numeric_reduce_gb10.c +++ b/src/omega_numeric_reduce_gb10.c @@ -24,8 +24,9 @@ * executor reads after the host marker only, which PR #141 showed can precede * the last stores. * MEAN SUM levels on the chip, then the one final division - * omega_math_div(SUM, u2f(n)) on the host: a DECLARED HOST STEP (no - * GB10 DIV is merged on main yet; the chip DIV kernel is PR #141). + * omega_math_div(SUM, u2f(n)) on the chip: the whole-program GB10 DIV + * kernel of E1 row 7 (omega_ds_gb10_run, one element), bit-identical to + * the CPU division. No host step remains. * * Every pre-submission check carries a CHECK: marker. With * -DOMEGA_NUMERIC_CPU_ONLY the checks still run but no device is touched @@ -33,11 +34,12 @@ */ #include "omega_numeric_reduce.h" #include "omega_numeric.h" +#include "omega_numeric_divsqrt_gb10.h" #include "omega_blackwell_encoder.h" #include "omega_blackwell_qmd.h" #ifndef OMEGA_NUMERIC_CPU_ONLY #include "omega_blackwell_submit.h" -#include "m16_native.h" +#include "omega_numeric_native.h" #endif #include @@ -277,17 +279,15 @@ static int chunk_check(OmegaReduceOp op, const OmegaNumericPatchInsn *patch, int return omega_numeric_check_patch(OMEGA_NOP_REDUCE_SUM, patch, np, qmd1, err, err_len); } -/* One level chunk on GB10, every op. A copy of the vecadd launch of - * omega_numeric_gb10.c (not edited by this lane) that also waits for the QMD - * release semaphore before reading results; the shared executor reads after - * the host marker only. */ +/* One level chunk on GB10, every op. Like the SIMT launcher, require both + * the host marker and the QMD release semaphore before reading results. */ /* Device-failure diagnostics (M20 GB10 instrumentation). Every * OMEGA_NUMERIC_ERR_DEVICE return below goes through gb10_devfail, which * prints one GB10_DEVFAIL line to stderr: the step that failed, the driver * return code, errno, the nvrm error text, the wait value and the marker word - * for waits, and the elapsed ms since the launch began. It only reports: the - * return code stays OMEGA_NUMERIC_ERR_DEVICE, there is no retry and no wait - * value changes. */ + * for waits, and the elapsed ms since the launch began. The lifecycle wrapper + * retains resources after uncertain completion and refuses later numeric + * launches. There is no retry and no wait value changes. */ static double gb10_ms_since(const struct timespec *t0) { struct timespec t; timespec_get(&t, TIME_UTC); /* C11; no feature macro needed */ @@ -303,9 +303,46 @@ static int gb10_devfail(const char *fn, const char *step, M16NativeContext *ctx, if (wait_ms >= 0) fprintf(stderr, " wait_ms=%ld word=0x%08x want=0x%08x", wait_ms, word ? (unsigned)*word : 0u, (unsigned)want); fprintf(stderr, " elapsed_ms=%.3f\n", ms); - if (do_close) m16_native_close(ctx); + if (do_close) omega_numeric_native_close(ctx); return OMEGA_NUMERIC_ERR_DEVICE; } +/* Slow-wait note: one stderr line when a successful wait finished more than 1000 ms after launch began. */ +static void gb10_note_slow(const char *step, const struct timespec *t0) { + double ms = gb10_ms_since(t0); + if (ms > 1000.0) fprintf(stderr, "GB10_SLOW_WAIT step=%s elapsed_ms=%.3f\n", step, ms); +} +/* Diagnostic probe for the E1 stall (default build: none of this exists; every wait cap stays the + * literal 600000 ms and marker_mem is a plain nvrm_alloc). + * -DOMEGA_STALL_PROBE one stderr line per launch: GB10_PROBE n= inner= marker_ms= marker2_ms= sem_ms= + * (ms from launch start to each wait success, -1 = not reached), a timeout + * prints GB10_PROBE_TIMEOUT with all three words; the wait cap becomes the + * env var OMEGA_PROBE_WAIT_MS (default 600000). + * -DOMEGA_MARKER_UNCACHED marker_mem is allocated with nvrm_alloc_gpu_uncached (not cached in GPU L2). */ +#ifdef OMEGA_STALL_PROBE +static unsigned long gb10_probe_wait_ms(void) { + const char *e = getenv("OMEGA_PROBE_WAIT_MS"); + if (e && *e) { + char *end = NULL; + unsigned long v = strtoul(e, &end, 10); + if (end && *end == 0 && v > 0) return v; + } + return 600000ul; +} +#define GB10_WAIT_MS gb10_probe_wait_ms() +static void gb10_probe_timeout(const char *step, size_t count, const volatile uint32_t *m1, const volatile uint32_t *m2, + const volatile uint32_t *sem, const struct timespec *t0) { + fprintf(stderr, "GB10_PROBE_TIMEOUT step=%s n=%zu inner=%u marker=0x%08x marker2=0x%08x sem=0x%08x elapsed_ms=%.3f\n", + step, count, g_last_launches + 1u, (unsigned)*m1, (unsigned)*m2, (unsigned)*sem, gb10_ms_since(t0)); +} +#else +#define GB10_WAIT_MS 600000 +#endif +#ifdef OMEGA_MARKER_UNCACHED +#define GB10_MARKER_ALLOC(rm_, size_, out_) nvrm_alloc_gpu_uncached((rm_), (size_), (out_)) +#else +#define GB10_MARKER_ALLOC(rm_, size_, out_) nvrm_alloc((rm_), (size_), (out_)) +#endif + /* Plain step: drv_rc is the value the call returned. */ #define GB10_FAIL(step, close_, rc_) gb10_devfail(__func__, (step), &ctx, (close_), (rc_), errno, -1, NULL, 0u, &t0) /* Wait step: also log the wait value and the word read. */ @@ -321,7 +358,7 @@ static int run_chunk(OmegaReduceOp op, const float *in, float *out_res, size_t c timespec_get(&t0, TIME_UTC); M16NativeContext ctx; int drc_; - if ((drc_ = m16_native_open(&ctx)) != 0) return GB10_FAIL("open", 0, drc_); + if ((drc_ = omega_numeric_native_open(&ctx)) != 0) return GB10_FAIL("open", 0, drc_); if ((drc_ = m16_native_create_channel(&ctx)) != 0) return GB10_FAIL("channel", 1, drc_); NvrmMem large_pb; if ((drc_ = nvrm_alloc(&ctx.rm, 0x10000, &large_pb)) != 0) return GB10_FAIL("alloc_pb", 1, drc_); @@ -333,7 +370,7 @@ static int run_chunk(OmegaReduceOp op, const float *in, float *out_res, size_t c if (nvrm_alloc(&ctx.rm, 0x1000, &code_mem) != 0 || nvrm_alloc(&ctx.rm, 0x1000, &cbank_mem) != 0 || nvrm_alloc(&ctx.rm, bytes, &a_mem) != 0 || nvrm_alloc(&ctx.rm, bytes, &b_mem) != 0 || nvrm_alloc(&ctx.rm, bytes, &c_mem) != 0 || nvrm_alloc(&ctx.rm, bytes, &out_mem) != 0 || - nvrm_alloc(&ctx.rm, 0x1000, &marker_mem) != 0 || nvrm_alloc(&ctx.rm, 0x10000, &qmd_mem) != 0) { + GB10_MARKER_ALLOC(&ctx.rm, 0x1000, &marker_mem) != 0 || nvrm_alloc(&ctx.rm, 0x10000, &qmd_mem) != 0) { return GB10_FAIL("alloc_buffers", 1, -1); } memcpy(a_mem.cpu, in, count * sizeof(float)); @@ -373,13 +410,13 @@ static int run_chunk(OmegaReduceOp op, const float *in, float *out_res, size_t c char perr[256]; if (chunk_check(op, patch, np, qmd1_words, perr, sizeof(perr)) != OMEGA_NUMERIC_OK) { fprintf(stderr, "omega_reduce_gb10: %s\n", perr); - m16_native_close(&ctx); + omega_numeric_native_close(&ctx); return OMEGA_NUMERIC_ERR_OPERANDS; } for (int i = 0; i < np; i++) if (memcmp((uint8_t *)code_mem.cpu + OMEGA_NUMERIC_PATCH_OFFSET + (size_t)i * 16u, patch[i].w, 16) != 0) { fprintf(stderr, "omega_reduce_gb10: code image differs from the checked patch at %d\n", i); - m16_native_close(&ctx); + omega_numeric_native_close(&ctx); return OMEGA_NUMERIC_ERR_OPERANDS; } } @@ -390,6 +427,9 @@ static int run_chunk(OmegaReduceOp op, const float *in, float *out_res, size_t c volatile uint32_t *hmarker = (volatile uint32_t *)marker_mem.cpu; *hsem = 0; *hmarker = 0; +#ifndef OMEGA_C3_PROTECT_OFF /* C3 hardening, same as omega_ds_gb10_run (-DOMEGA_C3_PROTECT_OFF = A/B control arm) */ + *(volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10) = 0; +#endif __asm__ volatile("dsb sy" ::: "memory"); uint32_t pb[1024]; @@ -444,20 +484,66 @@ static int run_chunk(OmegaReduceOp op, const float *in, float *out_res, size_t c pb[pb_len++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[pb_len++] = 0; pb[pb_len++] = 0x1 | (1u << 20); +#ifndef OMEGA_C3_PROTECT_OFF + /* C3 hardening, copied from omega_ds_gb10_run (src/omega_numeric_divsqrt_gb10.c): after the WFI + * marker flush GPU L2 dirty lines to memory (NVC96F_MEM_OP_A..D = 0x28..0x34, D bits 31:27 + * OPERATION = L2_FLUSH_DIRTY 0x10), then a second WFI marker 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++] = 0x46464646u; + pb[pb_len++] = 0; + pb[pb_len++] = 0x1 | (1u << 20); +#endif if ((drc_ = m16_native_submit_methods(&ctx, pb, pb_len)) != 0) return GB10_FAIL("submit", 1, drc_); - if ((drc_ = m16_native_wait_marker(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, 5000)) != 0) { - return GB10_FAIL_WAIT("marker_wait", drc_, 5000, hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD); +#ifdef OMEGA_STALL_PROBE + volatile uint32_t *pmarker2 = (volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10); + double probe_m1 = -1.0, probe_m2 = -1.0, probe_sem = -1.0; +#define GB10_PROBE_TMO(step_) gb10_probe_timeout((step_), count, hmarker, pmarker2, hsem, &t0) +#else +#define GB10_PROBE_TMO(step_) ((void)0) +#endif + if ((drc_ = omega_numeric_native_wait(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, GB10_WAIT_MS)) != 0) { + GB10_PROBE_TMO("marker_wait"); + return GB10_FAIL_WAIT("marker_wait", drc_, GB10_WAIT_MS, hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD); + } + gb10_note_slow("marker", &t0); +#ifdef OMEGA_STALL_PROBE + probe_m1 = gb10_ms_since(&t0); +#endif +#ifndef OMEGA_C3_PROTECT_OFF + volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10); + if ((drc_ = omega_numeric_native_wait(hmarker2, 0x46464646u, GB10_WAIT_MS)) != 0) { + GB10_PROBE_TMO("marker2_wait"); + return GB10_FAIL_WAIT("marker2_wait", drc_, GB10_WAIT_MS, hmarker2, 0x46464646u); } + gb10_note_slow("marker2", &t0); +#ifdef OMEGA_STALL_PROBE + probe_m2 = gb10_ms_since(&t0); +#endif +#endif /* The host marker can land before the last CTAs' stores are visible (seen * by the DIV/SQRT gate, PR #141). Read only after the QMD's own release * semaphore, written after the grid completes, is DONE. */ - if ((drc_ = m16_native_wait_marker(hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE, 5000)) != 0) { - return GB10_FAIL_WAIT("sem_wait", drc_, 5000, hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE); + if ((drc_ = omega_numeric_native_wait(hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE, GB10_WAIT_MS)) != 0) { + GB10_PROBE_TMO("sem_wait"); + return GB10_FAIL_WAIT("sem_wait", drc_, GB10_WAIT_MS, hsem, OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE); } + gb10_note_slow("sem", &t0); +#ifdef OMEGA_STALL_PROBE + probe_sem = gb10_ms_since(&t0); + fprintf(stderr, "GB10_PROBE n=%zu inner=%u marker_ms=%.3f marker2_ms=%.3f sem_ms=%.3f\n", count, + g_last_launches + 1u, probe_m1, probe_m2, probe_sem); +#endif __asm__ volatile("dsb sy" ::: "memory"); memcpy(out_res, out_mem.cpu, count * sizeof(float)); - m16_native_close(&ctx); + if (omega_numeric_native_close(&ctx) != 0) return OMEGA_NUMERIC_ERR_DEVICE; return OMEGA_NUMERIC_OK; } #endif @@ -510,8 +596,22 @@ int omega_reduce_gb10(OmegaReduceOp op, const float *x, size_t n, float *out) { float s = cur[0]; free(cur); free(res); - /* MEAN: the one final division is a declared host step (see the header). */ - *out = (op == OMEGA_RED_MEAN) ? omega_math_div(s, omega_ref_u2f((uint32_t)n)) : s; + if (op == OMEGA_RED_MEAN) { + /* MEAN: the one final division runs on the chip too: the GB10 DIV kernel of + * E1 row 7 (correctly rounded, bit-identical to omega_math_div). */ + uint32_t sb, nb, ob; + float nf = omega_ref_u2f((uint32_t)n); +#ifdef OMEGA_REDUCE_MUTATE_MEAN_DIV /* test builds only: divide by n + 1 (must FAIL chip parity) */ + nf = omega_ref_u2f((uint32_t)n + 1u); +#endif + memcpy(&sb, &s, 4); + memcpy(&nb, &nf, 4); + rc = omega_ds_gb10_run(OMEGA_DS_DIV, &sb, &nb, &ob, 1); + if (rc != OMEGA_NUMERIC_OK) return rc; + memcpy(out, &ob, 4); + return OMEGA_NUMERIC_OK; + } + *out = s; return OMEGA_NUMERIC_OK; #endif } diff --git a/src/omega_numeric_transc.c b/src/omega_numeric_transc.c index 28ef15217..017750052 100644 --- a/src/omega_numeric_transc.c +++ b/src/omega_numeric_transc.c @@ -323,43 +323,7 @@ static float erf_small(float y) { return fadd(A, ffma(A, w, B)); } -/* erfcx(y) = e^(y^2) erfc(y), 0.5 <= y < 11: degree-10 Taylor polynomial - * about the centre of one of 17 intervals. */ -#define ERFCX_N 17 -static const float ERFCX_LO[ERFCX_N] = { - 0.5f, 0.75f, 1.0f, 1.25f, 1.5f, 1.75f, 2.0f, 2.5f, 3.0f, 3.5f, - 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, -}; -static const float ERFCX_C[ERFCX_N] = { - 0.625f, 0.875f, 1.125f, 1.375f, 1.625f, 1.875f, 2.25f, 2.75f, 3.25f, 3.75f, - 4.5f, 5.5f, 6.5f, 7.5f, 8.5f, 9.5f, 10.5f, -}; -static const float ERFCX_A[ERFCX_N][11] = { - { 0x8E8B5Bp-24f, -0xDD5E87p-25f, 0x92BBA1p-25f, -0xACE1AEp-26f, 0xB96A35p-27f, -0xB7E72Fp-28f, 0xAA97F4p-29f, -0x953FA8p-30f, 0xF7E81Ep-32f, -0xC477CDp-33f, 0x953558p-34f }, /* c = 0.625 */ - { 0xEDBA3Fp-25f, -0xA1B4FBp-25f, 0xC077C8p-26f, -0xCEAC34p-27f, 0xCC18E1p-28f, -0xBBCEE9p-29f, 0xA29324p-30f, -0x8559C2p-31f, 0xD077BFp-33f, -0x9BFF38p-34f, 0xE059BEp-36f }, /* c = 0.875 */ - { 0xCA98F0p-25f, -0xF3C59Bp-26f, 0x82F393p-26f, -0x809A1Dp-27f, 0xEA7389p-29f, -0xC8852Fp-30f, 0xA23629p-31f, -0xF9C637p-33f, 0xB7ECD3p-34f, -0x820F1Cp-35f, 0xB13A1Ep-37f }, /* c = 1.125 */ - { 0xAFC47Bp-25f, -0xBCBD32p-26f, 0xB809A1p-27f, -0xA5E6DDp-28f, 0x8BF5D3p-29f, -0xDEF926p-31f, 0xA8D5D0p-32f, -0xF45734p-34f, 0xA9AFACp-35f, -0xE2FD36p-37f, 0x92A769p-38f }, /* c = 1.375 */ - { 0x9AC1FBp-25f, -0x9588F3p-26f, 0x850AD6p-27f, -0xDD00C7p-29f, 0xAD0A15p-30f, -0x80A757p-31f, 0xB6B050p-33f, -0xF8DA1Fp-35f, 0xA32F67p-36f, -0xCEB114p-38f, 0xFD7E48p-40f }, /* c = 1.625 */ - { 0x89F2BAp-25f, -0xF1B2C0p-27f, 0xC5377Fp-28f, -0x977C98p-29f, 0xDCCAC5p-31f, -0x9991BEp-32f, 0xCCDB07p-34f, -0x838706p-35f, 0xA318E2p-37f, -0xC3D30Fp-39f, 0xE42CA4p-41f }, /* c = 1.875 */ - { 0xECA223p-26f, -0xB53869p-27f, 0x830AB4p-28f, -0xB441FDp-30f, 0xED2CABp-32f, -0x95E929p-33f, 0xB6BBA2p-35f, -0xD76BF6p-37f, 0xF63B9Ep-39f, -0x88BD33p-40f, 0x93D7A1p-42f }, /* c = 2.25 */ - { 0xC64F5Bp-26f, -0x8182BCp-27f, 0xA1DCC6p-29f, -0xC274D6p-31f, 0xE16398p-33f, -0xFCCF21p-35f, 0x898DD9p-36f, -0x918959p-38f, 0x95FDAEp-40f, -0x96D195p-42f, 0x942B7Dp-44f }, /* c = 2.75 */ - { 0xAA53D0p-26f, -0xC15429p-28f, 0xD3F6EEp-30f, -0xE125A5p-32f, 0xE842C3p-34f, -0xE92F5Ep-36f, 0xE44178p-38f, -0xDA2E81p-40f, 0xCBEEBCp-42f, -0xBA9E56p-44f, 0xA76049p-46f }, /* c = 3.25 */ - { 0x951579p-26f, -0x955328p-28f, 0x917833p-30f, -0x8A1A57p-32f, 0xFFF819p-35f, -0xE7E6F5p-37f, 0xCDA868p-39f, -0xB2BBC5p-41f, 0x98617Ep-43f, -0xFF1F19p-46f, 0xD1DF72p-48f }, /* c = 3.75 */ - { 0xFAD950p-27f, -0xD51F5Bp-29f, 0xB16096p-31f, -0x90C76Dp-33f, 0xE803C3p-36f, -0xB6AA59p-38f, 0x8D6B52p-40f, -0xD77C75p-43f, 0xA1AA7Ep-45f, -0xEF04AAp-48f, 0xAE325Ap-50f }, /* c = 4.5 */ - { 0xCEC548p-27f, -0x91C654p-29f, 0xCA9296p-32f, -0x8ACBB7p-34f, 0xBBA7A4p-37f, -0xFA7237p-40f, 0xA50BF1p-42f, -0xD6EBD6p-45f, 0x8A4E6Cp-47f, -0xB0000Fp-50f, 0xDD84DDp-53f }, /* c = 5.5 */ - { 0xAFBAE2p-27f, -0xD37168p-30f, 0xFBAF7Cp-33f, -0x943C40p-35f, 0xACD949p-38f, -0xC791FFp-41f, 0xE438D1p-44f, -0x8147A3p-46f, 0x91233Dp-49f, -0xA1801Ap-52f, 0xB2285Ep-55f }, /* c = 6.5 */ - { 0x98BA18p-27f, -0xA0222Bp-30f, 0xA683DEp-33f, -0xABC1D1p-36f, 0xAFC535p-39f, -0xB27E5Ep-42f, 0xB3E516p-45f, -0xB3F8A7p-48f, 0xB2BF9Dp-51f, -0xB04751p-54f, 0xACA33Bp-57f }, /* c = 7.5 */ - { 0x8703C0p-27f, -0xFABE57p-31f, 0xE75118p-34f, -0xD40795p-37f, 0xC12136p-40f, -0xAED44Cp-43f, 0x9D4DC1p-46f, -0x8CB120p-49f, 0xFA31DDp-53f, -0xDD2E77p-56f, 0xC26CBBp-59f }, /* c = 8.5 */ - { 0xF1EDCEp-28f, -0xC98846p-31f, 0xA6FE9Ap-34f, -0x89A7FAp-37f, 0xE1C826p-41f, -0xB83A53p-44f, 0x9592F6p-47f, -0xF1AFD8p-51f, 0xC251B4p-54f, -0x9B7D7Ap-57f, 0xF7AB79p-61f }, /* c = 9.5 */ - { 0xDB1A53p-28f, -0xA5745Ep-31f, 0xF8CB98p-35f, -0xBA40ACp-38f, 0x8AD6E6p-41f, -0xCE1F7Ep-45f, 0x985F41p-48f, -0xE05A4Cp-52f, 0xA47FF1p-55f, -0xF04377p-59f, 0xAEC450p-62f }, /* c = 10.5 */ -}; - -/* a0 = erfcx(c) - (FP32 a0), from the same 120-digit computation */ -static const float ERFCX_A0LO[ERFCX_N] = { - -0xFEC2A1p-50f, 0xE409ACp-50f, 0x9B149Bp-50f, -0xD0C389p-50f, 0xC8864Fp-51f, 0xED8120p-52f, - 0xD62793p-51f, 0x8FF27Dp-51f, 0x8D4BB4p-51f, -0xC7D6DAp-52f, 0x939E99p-53f, -0xDD7B0Dp-52f, - 0xBA5C5Cp-54f, -0xB272B3p-52f, 0xA3E924p-53f, -0x88206Cp-54f, -0xFF9A64p-53f, -}; +#include "omega_numeric_transc_tables.h" /* erfcx(y) = c + cl: c is the plain Horner result, cl collects the FP32 * rounding of the last step (exact: a0 - c is exact by Sterbenz, then one diff --git a/src/omega_numeric_transc_tables.h b/src/omega_numeric_transc_tables.h new file mode 100644 index 000000000..a7da552c2 --- /dev/null +++ b/src/omega_numeric_transc_tables.h @@ -0,0 +1,48 @@ +#ifndef OMEGA_NUMERIC_TRANSC_TABLES_H +#define OMEGA_NUMERIC_TRANSC_TABLES_H +/* + * Frozen erfcx(y) = e^(y^2) erfc(y) interval tables of the bounded ERF/GELU + * contract (docs/numeric/E1_TRANSCENDENTAL_CONTRACT.md). One copy, included by + * the CPU sequences (src/omega_numeric_transc.c) and by the GB10 kernel + * builder (src/omega_numeric_divsqrt_gb10.c), so both realizations read the + * same constants. Moved verbatim from omega_numeric_transc.c; do not edit + * a value without re-running every erfcx-dependent gate. + */ +/* erfcx(y) = e^(y^2) erfc(y), 0.5 <= y < 11: degree-10 Taylor polynomial + * about the centre of one of 17 intervals. */ +#define ERFCX_N 17 +static const float ERFCX_LO[ERFCX_N] = { + 0.5f, 0.75f, 1.0f, 1.25f, 1.5f, 1.75f, 2.0f, 2.5f, 3.0f, 3.5f, + 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, +}; +static const float ERFCX_C[ERFCX_N] = { + 0.625f, 0.875f, 1.125f, 1.375f, 1.625f, 1.875f, 2.25f, 2.75f, 3.25f, 3.75f, + 4.5f, 5.5f, 6.5f, 7.5f, 8.5f, 9.5f, 10.5f, +}; +static const float ERFCX_A[ERFCX_N][11] = { + { 0x8E8B5Bp-24f, -0xDD5E87p-25f, 0x92BBA1p-25f, -0xACE1AEp-26f, 0xB96A35p-27f, -0xB7E72Fp-28f, 0xAA97F4p-29f, -0x953FA8p-30f, 0xF7E81Ep-32f, -0xC477CDp-33f, 0x953558p-34f }, /* c = 0.625 */ + { 0xEDBA3Fp-25f, -0xA1B4FBp-25f, 0xC077C8p-26f, -0xCEAC34p-27f, 0xCC18E1p-28f, -0xBBCEE9p-29f, 0xA29324p-30f, -0x8559C2p-31f, 0xD077BFp-33f, -0x9BFF38p-34f, 0xE059BEp-36f }, /* c = 0.875 */ + { 0xCA98F0p-25f, -0xF3C59Bp-26f, 0x82F393p-26f, -0x809A1Dp-27f, 0xEA7389p-29f, -0xC8852Fp-30f, 0xA23629p-31f, -0xF9C637p-33f, 0xB7ECD3p-34f, -0x820F1Cp-35f, 0xB13A1Ep-37f }, /* c = 1.125 */ + { 0xAFC47Bp-25f, -0xBCBD32p-26f, 0xB809A1p-27f, -0xA5E6DDp-28f, 0x8BF5D3p-29f, -0xDEF926p-31f, 0xA8D5D0p-32f, -0xF45734p-34f, 0xA9AFACp-35f, -0xE2FD36p-37f, 0x92A769p-38f }, /* c = 1.375 */ + { 0x9AC1FBp-25f, -0x9588F3p-26f, 0x850AD6p-27f, -0xDD00C7p-29f, 0xAD0A15p-30f, -0x80A757p-31f, 0xB6B050p-33f, -0xF8DA1Fp-35f, 0xA32F67p-36f, -0xCEB114p-38f, 0xFD7E48p-40f }, /* c = 1.625 */ + { 0x89F2BAp-25f, -0xF1B2C0p-27f, 0xC5377Fp-28f, -0x977C98p-29f, 0xDCCAC5p-31f, -0x9991BEp-32f, 0xCCDB07p-34f, -0x838706p-35f, 0xA318E2p-37f, -0xC3D30Fp-39f, 0xE42CA4p-41f }, /* c = 1.875 */ + { 0xECA223p-26f, -0xB53869p-27f, 0x830AB4p-28f, -0xB441FDp-30f, 0xED2CABp-32f, -0x95E929p-33f, 0xB6BBA2p-35f, -0xD76BF6p-37f, 0xF63B9Ep-39f, -0x88BD33p-40f, 0x93D7A1p-42f }, /* c = 2.25 */ + { 0xC64F5Bp-26f, -0x8182BCp-27f, 0xA1DCC6p-29f, -0xC274D6p-31f, 0xE16398p-33f, -0xFCCF21p-35f, 0x898DD9p-36f, -0x918959p-38f, 0x95FDAEp-40f, -0x96D195p-42f, 0x942B7Dp-44f }, /* c = 2.75 */ + { 0xAA53D0p-26f, -0xC15429p-28f, 0xD3F6EEp-30f, -0xE125A5p-32f, 0xE842C3p-34f, -0xE92F5Ep-36f, 0xE44178p-38f, -0xDA2E81p-40f, 0xCBEEBCp-42f, -0xBA9E56p-44f, 0xA76049p-46f }, /* c = 3.25 */ + { 0x951579p-26f, -0x955328p-28f, 0x917833p-30f, -0x8A1A57p-32f, 0xFFF819p-35f, -0xE7E6F5p-37f, 0xCDA868p-39f, -0xB2BBC5p-41f, 0x98617Ep-43f, -0xFF1F19p-46f, 0xD1DF72p-48f }, /* c = 3.75 */ + { 0xFAD950p-27f, -0xD51F5Bp-29f, 0xB16096p-31f, -0x90C76Dp-33f, 0xE803C3p-36f, -0xB6AA59p-38f, 0x8D6B52p-40f, -0xD77C75p-43f, 0xA1AA7Ep-45f, -0xEF04AAp-48f, 0xAE325Ap-50f }, /* c = 4.5 */ + { 0xCEC548p-27f, -0x91C654p-29f, 0xCA9296p-32f, -0x8ACBB7p-34f, 0xBBA7A4p-37f, -0xFA7237p-40f, 0xA50BF1p-42f, -0xD6EBD6p-45f, 0x8A4E6Cp-47f, -0xB0000Fp-50f, 0xDD84DDp-53f }, /* c = 5.5 */ + { 0xAFBAE2p-27f, -0xD37168p-30f, 0xFBAF7Cp-33f, -0x943C40p-35f, 0xACD949p-38f, -0xC791FFp-41f, 0xE438D1p-44f, -0x8147A3p-46f, 0x91233Dp-49f, -0xA1801Ap-52f, 0xB2285Ep-55f }, /* c = 6.5 */ + { 0x98BA18p-27f, -0xA0222Bp-30f, 0xA683DEp-33f, -0xABC1D1p-36f, 0xAFC535p-39f, -0xB27E5Ep-42f, 0xB3E516p-45f, -0xB3F8A7p-48f, 0xB2BF9Dp-51f, -0xB04751p-54f, 0xACA33Bp-57f }, /* c = 7.5 */ + { 0x8703C0p-27f, -0xFABE57p-31f, 0xE75118p-34f, -0xD40795p-37f, 0xC12136p-40f, -0xAED44Cp-43f, 0x9D4DC1p-46f, -0x8CB120p-49f, 0xFA31DDp-53f, -0xDD2E77p-56f, 0xC26CBBp-59f }, /* c = 8.5 */ + { 0xF1EDCEp-28f, -0xC98846p-31f, 0xA6FE9Ap-34f, -0x89A7FAp-37f, 0xE1C826p-41f, -0xB83A53p-44f, 0x9592F6p-47f, -0xF1AFD8p-51f, 0xC251B4p-54f, -0x9B7D7Ap-57f, 0xF7AB79p-61f }, /* c = 9.5 */ + { 0xDB1A53p-28f, -0xA5745Ep-31f, 0xF8CB98p-35f, -0xBA40ACp-38f, 0x8AD6E6p-41f, -0xCE1F7Ep-45f, 0x985F41p-48f, -0xE05A4Cp-52f, 0xA47FF1p-55f, -0xF04377p-59f, 0xAEC450p-62f }, /* c = 10.5 */ +}; + +/* a0 = erfcx(c) - (FP32 a0), from the same 120-digit computation */ +static const float ERFCX_A0LO[ERFCX_N] = { + -0xFEC2A1p-50f, 0xE409ACp-50f, 0x9B149Bp-50f, -0xD0C389p-50f, 0xC8864Fp-51f, 0xED8120p-52f, + 0xD62793p-51f, 0x8FF27Dp-51f, 0x8D4BB4p-51f, -0xC7D6DAp-52f, 0x939E99p-53f, -0xDD7B0Dp-52f, + 0xBA5C5Cp-54f, -0xB272B3p-52f, 0xA3E924p-53f, -0x88206Cp-54f, -0xFF9A64p-53f, +}; +#endif diff --git a/src/omega_program.c b/src/omega_program.c index d4a482539..d5d1f5050 100644 --- a/src/omega_program.c +++ b/src/omega_program.c @@ -49,14 +49,99 @@ static OmegaObject *build_type_for(OmegaGraph *g, TypeTag tag, uint16_t width) { case TYPE_UNSIGNED_INT: return omega_build_type_uint(g, width); case TYPE_SIGNED_INT: return omega_build_type_signed_int(g, width); case TYPE_BITVECTOR: return omega_build_type_bitvector(g, width); + case TYPE_FP32: return width == 32 ? omega_build_type_fp32(g) : NULL; default: return NULL; } } +/* FP32 programs (spec/program-fp32.md). A body is FP32-involved when the contract names + * TYPE_FP32 or a step is OP_CONVERT. Such a body runs a two-state machine: in the FP32 + * state a step is ADD SUB MUL DIV with a binary32 constant, or OP_CONVERT to u32; in the + * u32 state the only step is OP_CONVERT to FP32 (integer arithmetic stays on the integer + * tier). No other step is accepted, so a u32 value never meets an FP32 operation + * without an explicit conversion. The overflow policy declared on the operations is + * SATURATE: binary32 overflow goes to infinity and F2U clamps. */ +static bool body_is_fp32(const OmegaProgram *prog) { + if (prog->contract.input_type == TYPE_FP32 || prog->contract.output_type == TYPE_FP32) return true; + for (uint16_t i = 0; i < prog->body.step_count && i < OMEGA_PROGRAM_MAX_STEPS; ++i) + if (prog->body.steps[i].op == OP_CONVERT) return true; + return false; +} + +static const OmegaObject *lower_body_fp32(OmegaGraph *g, const OmegaProgram *prog) { + const OmegaProgramBody *b = &prog->body; + const OmegaContract *c = &prog->contract; + if (c->input_width != 32 || c->output_width != 32) return NULL; + if ((c->input_type != TYPE_FP32 && c->input_type != TYPE_UNSIGNED_INT) || + (c->output_type != TYPE_FP32 && c->output_type != TYPE_UNSIGNED_INT)) return NULL; + OmegaObject *tf = omega_build_type_fp32(g); + OmegaObject *tu = omega_build_type_uint(g, 32); + if (!tf || !tf->has_id || !tu || !tu->has_id) return NULL; + SemanticId tfid = tf->id, tuid = tu->id; + TypeTag cur_tag = c->input_type; + OmegaObject *cur = omega_build_param(g, cur_tag == TYPE_FP32 ? &tfid : &tuid, 0); + if (!cur || !cur->has_id) return NULL; + SemanticId cur_id = cur->id; + for (uint16_t i = 0; i < b->step_count; ++i) { + uint8_t op = b->steps[i].op; + uint64_t imm = b->steps[i].imm; + if (op == OP_CONVERT) { + if (imm != TYPE_FP32 && imm != TYPE_UNSIGNED_INT) return NULL; + if ((TypeTag)imm == cur_tag) return NULL; + const SemanticId *from = cur_tag == TYPE_FP32 ? &tfid : &tuid; + const SemanticId *to = imm == TYPE_FP32 ? &tfid : &tuid; + OmegaObject *o = omega_graph_add_object(g, KIND_OPERATION); + if (!o) return NULL; + OperationPayload opp; + memset(&opp, 0, sizeof(opp)); + opp.opcode = OP_CONVERT; + opp.overflow = OVERFLOW_SATURATE; + opp.arity = 1; + memcpy(opp.type_id.bytes, to->bytes, OMEGA_ID_BYTES); + memcpy(opp.input_types[0].bytes, from->bytes, OMEGA_ID_BYTES); + memcpy(opp.output_type.bytes, to->bytes, OMEGA_ID_BYTES); + memcpy(o->payload, &opp, sizeof(opp)); + o->payload_len = sizeof(opp); + omega_compute_semantic_id(o); + SemanticId opid = o->id; + OmegaObject *a = omega_graph_add_object(g, KIND_OPERATION); + if (!a) return NULL; + ApplyPayload app; + memset(&app, 0, sizeof(app)); + memcpy(app.op_id.bytes, opid.bytes, OMEGA_ID_BYTES); + app.operand_count = 1; + memcpy(app.operands[0].bytes, cur_id.bytes, OMEGA_ID_BYTES); + memcpy(a->payload, &app, sizeof(app)); + a->payload_len = sizeof(app); + omega_compute_semantic_id(a); + if (!a->has_id) return NULL; + cur = a; + cur_id = a->id; + cur_tag = (TypeTag)imm; + continue; + } + if (cur_tag != TYPE_FP32) return NULL; + if (op != OP_ADD && op != OP_SUB && op != OP_MUL && op != OP_DIV) return NULL; + if (imm > 0xFFFFFFFFull) return NULL; + OmegaObject *k = omega_build_val_uint(g, &tfid, 32, imm); + if (!k || !k->has_id) return NULL; + SemanticId kid = k->id; + OmegaObject *o = omega_build_op_binary(g, (OpCode)op, OVERFLOW_SATURATE, &tfid); + if (!o || !o->has_id) return NULL; + SemanticId opid = o->id; + cur = omega_build_apply(g, &opid, &cur_id, &kid); + if (!cur || !cur->has_id) return NULL; + cur_id = cur->id; + } + if (cur_tag != c->output_type) return NULL; + return cur; +} + /* Lower the body into g with the existing builders; returns the root object. */ static const OmegaObject *lower_body(OmegaGraph *g, const OmegaProgram *prog) { const OmegaProgramBody *b = &prog->body; if (!b->has_body || b->step_count > OMEGA_PROGRAM_MAX_STEPS) return NULL; + if (body_is_fp32(prog)) return lower_body_fp32(g, prog); uint16_t w = prog->contract.input_width; OmegaObject *t = build_type_for(g, prog->contract.input_type, w); if (!t || !t->has_id) return NULL; @@ -587,7 +672,8 @@ int omega_program_compose(const OmegaProgram *a, const OmegaProgram *b, OmegaPro } /* 3. Cost Derivation: Monotonic cost accumulation */ - out_c->cost.insn_count = a->cost.insn_count + b->cost.insn_count - 1; /* Ret eliminated */ + out_c->cost.insn_count = a->cost.insn_count + b->cost.insn_count; + if (out_c->cost.insn_count > 0) out_c->cost.insn_count -= 1; /* Ret eliminated; FP32 library-tier programs carry no code */ out_c->cost.reg_pressure = (a->cost.reg_pressure > b->cost.reg_pressure) ? a->cost.reg_pressure : b->cost.reg_pressure; out_c->cost.memory_bytes = a->cost.memory_bytes + b->cost.memory_bytes; out_c->cost.latency_cycles = a->cost.latency_cycles + b->cost.latency_cycles; diff --git a/src/omega_program_fp32.c b/src/omega_program_fp32.c new file mode 100644 index 000000000..c2e6cef03 --- /dev/null +++ b/src/omega_program_fp32.c @@ -0,0 +1,109 @@ +#include "omega_program_fp32.h" +#include "omega_numeric.h" +#include +#include + +static int refuse(char *why, size_t n, const char *fmt, unsigned a, const char *s) { + if (why && n) snprintf(why, n, fmt, a, s); + return -1; +} + +static const char *op_name(uint8_t op) { + switch (op) { + case OP_ADD: return "ADD"; + case OP_SUB: return "SUB"; + case OP_MUL: return "MUL"; + case OP_DIV: return "DIV"; + case OP_AND: return "AND"; + case OP_OR: return "OR"; + case OP_CONVERT: return "CONVERT"; + default: return "an opcode"; + } +} + +/* Walk the body as the two-state machine of omega_program.c lower_body_fp32 and say why it is refused. */ +static int walk(const OmegaProgram *prog, char *why, size_t n) { + const OmegaContract *c = &prog->contract; + if (!prog->body.has_body) return refuse(why, n, "no semantic body%.0u%s", 0, ""); + if (prog->body.step_count > OMEGA_PROGRAM_MAX_STEPS) return refuse(why, n, "more than 64 steps%.0u%s", 0, ""); + if (c->input_width != 32 || c->output_width != 32) return refuse(why, n, "FP32 programs are width 32%.0u%s", 0, ""); + if ((c->input_type != TYPE_FP32 && c->input_type != TYPE_UNSIGNED_INT) || + (c->output_type != TYPE_FP32 && c->output_type != TYPE_UNSIGNED_INT)) + return refuse(why, n, "contract types must be FP32 or u32%.0u%s", 0, ""); + TypeTag cur = c->input_type; + for (uint16_t i = 0; i < prog->body.step_count; ++i) { + uint8_t op = prog->body.steps[i].op; + uint64_t imm = prog->body.steps[i].imm; + if (op == OP_CONVERT) { + if (imm != TYPE_FP32 && imm != TYPE_UNSIGNED_INT) return refuse(why, n, "step %u: CONVERT target is neither FP32 nor u32%s", i, ""); + if ((TypeTag)imm == cur) return refuse(why, n, "step %u: CONVERT to the type the value already has%s", i, ""); + cur = (TypeTag)imm; + continue; + } + if (cur != TYPE_FP32) + return refuse(why, n, "step %u: %s applied to a u32 value in an FP32 program: mixed types need an explicit CONVERT", i, op_name(op)); + if (op != OP_ADD && op != OP_SUB && op != OP_MUL && op != OP_DIV) + return refuse(why, n, "step %u: %s is not an FP32 operation (ADD SUB MUL DIV CONVERT)", i, op_name(op)); + if (imm > 0xFFFFFFFFull) return refuse(why, n, "step %u: constant wider than 32 bits%s", i, ""); + } + if (cur != c->output_type) return refuse(why, n, "body ends as a different type than the contract output%.0u%s", 0, ""); + return 0; +} + +int omega_program_fp32_check(const OmegaProgram *prog, char *why, size_t why_len) { + if (!prog) return refuse(why, why_len, "no program%.0u%s", 0, ""); + if (walk(prog, why, why_len) != 0) return -1; + OmegaProgram chk = *prog; + chk.graph = NULL; + if (omega_program_compute_id(&chk) != 0 || memcmp(chk.program_id.bytes, prog->program_id.bytes, OMEGA_ID_BYTES) != 0) + return refuse(why, why_len, "program_id is not the v2 id of this body and contract (stale or forged)%.0u%s", 0, ""); + if (why && why_len) why[0] = '\0'; + return 0; +} + +int omega_program_build_fp32(OmegaProgram *prog, const char *name, TypeTag in_type, TypeTag out_type, + const OmegaProgramStep *steps, uint16_t count) { + if (!prog || (count && !steps) || count > OMEGA_PROGRAM_MAX_STEPS) return -1; + omega_program_init(prog, name); + prog->contract.input_type = in_type; + prog->contract.input_width = 32; + prog->contract.output_type = out_type; + prog->contract.output_width = 32; + prog->body.has_body = true; + prog->body.step_count = count; + if (count) memcpy(prog->body.steps, steps, count * sizeof(OmegaProgramStep)); + if (walk(prog, NULL, 0) != 0) return -1; + snprintf(prog->contract.precondition, sizeof(prog->contract.precondition), "x is a binary32 or u32 value"); + omega_build_constraint_id(CONST_PRECONDITION, prog->contract.precondition, &prog->contract.precondition_id); + snprintf(prog->contract.postcondition, sizeof(prog->contract.postcondition), "fp32 program of %u steps", (unsigned)count); + omega_build_constraint_id(CONST_POSTCONDITION, prog->contract.postcondition, &prog->contract.postcondition_id); + return omega_program_compute_id(prog) == 0 ? 0 : -1; +} + +int omega_program_build_convert(OmegaProgram *prog, const char *name, TypeTag from, TypeTag to) { + OmegaProgramStep s = { OP_CONVERT, (uint64_t)to }; + return omega_program_build_fp32(prog, name, from, to, &s, 1); +} + +int omega_program_fp32_eval(const OmegaProgram *prog, const uint32_t *xs, size_t n, uint32_t *ys) { + if (!prog || (n && (!xs || !ys))) return -1; + if (omega_program_fp32_check(prog, NULL, 0) != 0) return -1; + for (size_t k = 0; k < n; ++k) { + float v = omega_bits_to_float(xs[k]); /* a u32 travels as its bit pattern, the library's convention */ + for (uint16_t i = 0; i < prog->body.step_count; ++i) { + uint8_t op = prog->body.steps[i].op; + float kc = omega_bits_to_float((uint32_t)prog->body.steps[i].imm), r = 0.0f; + OmegaNumericOp nop; + if (op == OP_CONVERT) { + nop = prog->body.steps[i].imm == TYPE_FP32 ? OMEGA_NOP_I2FP_U32 : OMEGA_NOP_F2U; + if (omega_numeric_cpu_realize(nop, &v, &v, NULL, &r, 1) != OMEGA_NUMERIC_OK) return -1; + } else { + nop = op == OP_ADD ? OMEGA_NOP_FADD : op == OP_SUB ? OMEGA_NOP_FSUB : op == OP_MUL ? OMEGA_NOP_FMUL : OMEGA_NOP_DIV; + if (omega_numeric_cpu_realize(nop, &v, &kc, NULL, &r, 1) != OMEGA_NUMERIC_OK) return -1; + } + v = r; + } + ys[k] = omega_float_to_bits(v); + } + return 0; +} diff --git a/src/omega_program_fp32.h b/src/omega_program_fp32.h new file mode 100644 index 000000000..86b502357 --- /dev/null +++ b/src/omega_program_fp32.h @@ -0,0 +1,38 @@ +#ifndef OMEGA_PROGRAM_FP32_H +#define OMEGA_PROGRAM_FP32_H +/* + * FP32 in the program IR (E1 gap row 12; spec/program-fp32.md). + * + * An FP32 program is an OmegaProgram whose contract types are TYPE_FP32 or u32 + * (width 32) and whose body steps are, in the FP32 state, ADD SUB MUL DIV with a + * binary32 constant (imm = the constant's bits) or OP_CONVERT to u32; in the u32 + * state the only step is OP_CONVERT (imm = TYPE_FP32). The type check refuses + * anything else, so a u32 value never meets an FP32 operation, and two programs + * compose only when OutType == InType, so FP32 and u32 programs join only through + * a program that converts (omega_program_build_convert). + * + * FP32 programs have no AArch64 realization (omega_program_realize refuses them + * on type); they are evaluated by the qualified numeric library tier + * (omega_numeric_cpu_realize: FADD FSUB FMUL DIV, I2FP_U32, F2U) and carry a + * program id like every other program. + */ +#include "omega_program.h" + +/* Build name: in_type -> out_type over steps (<= 64). in_type/out_type are + * TYPE_FP32 or TYPE_UNSIGNED_INT, width 32. 0 ok (id computed, not realized), + * -1 refused. */ +int omega_program_build_fp32(OmegaProgram *prog, const char *name, TypeTag in_type, TypeTag out_type, + const OmegaProgramStep *steps, uint16_t count); + +/* The explicit conversion programs: u32 -> FP32 (RNE, I2FP_U32) and FP32 -> u32 + * (truncate toward zero, saturating, NaN -> 0 as omega_ref_f2u defines). */ +int omega_program_build_convert(OmegaProgram *prog, const char *name, TypeTag from, TypeTag to); + +/* Type and body check. 0 ok; -1 refused with the reason in why. */ +int omega_program_fp32_check(const OmegaProgram *prog, char *why, size_t why_len); + +/* Evaluate on the library tier. xs and ys are 32-bit patterns (binary32 bits for + * an FP32 input or output, a u32 otherwise). 0 ok, -1 refused. */ +int omega_program_fp32_eval(const OmegaProgram *prog, const uint32_t *xs, size_t n, uint32_t *ys); + +#endif diff --git a/src/omega_types.h b/src/omega_types.h index d7d464b8f..f123934e8 100644 --- a/src/omega_types.h +++ b/src/omega_types.h @@ -56,7 +56,8 @@ typedef enum { TYPE_RESOURCE = 0x0A, TYPE_CAPABILITY_REF = 0x0B, TYPE_EFFECT_INTENT_REF = 0x0C, - TYPE_EFFECT_RECEIPT_REF = 0x0D + TYPE_EFFECT_RECEIPT_REF = 0x0D, + TYPE_FP32 = 0x0E /* IEEE 754 binary32, width 32 (spec/program-fp32.md) */ } TypeTag; typedef enum { @@ -75,7 +76,8 @@ typedef enum { OP_SELECT = 0x0C, OP_CONCAT = 0x0D, OP_SLICE = 0x0E, - OP_COMPILE = 0x0F + OP_COMPILE = 0x0F, + OP_CONVERT = 0x10 /* unary, u32 <-> FP32, declared by the operation's input and output types */ } OpCode; typedef enum { diff --git a/src/omega_validate.c b/src/omega_validate.c index 6a1bdfe10..a39583c3f 100644 --- a/src/omega_validate.c +++ b/src/omega_validate.c @@ -111,7 +111,7 @@ int omega_validate_object(const OmegaGraph *graph, const OmegaObject *obj, char return -1; } const TypePayload *tp = (const TypePayload*)obj->payload; - if (tp->tag == TYPE_INVALID || tp->tag > TYPE_EFFECT_RECEIPT_REF) { + if (tp->tag == TYPE_INVALID || tp->tag > TYPE_FP32) { snprintf(err_msg, err_msg_len, "Invalid type tag 0x%02x", tp->tag); return -1; } @@ -125,6 +125,11 @@ int omega_validate_object(const OmegaGraph *graph, const OmegaObject *obj, char snprintf(err_msg, err_msg_len, "Signed integer width %u out of bounds [2..256]", tp->width); return -1; } + } else if (tp->tag == TYPE_FP32) { + if (tp->width != 32) { + snprintf(err_msg, err_msg_len, "FP32 width %u is not 32", tp->width); + return -1; + } } else if (tp->tag == TYPE_BITVECTOR) { if (tp->width < 1 || tp->width > 256) { snprintf(err_msg, err_msg_len, "Bitvector width %u out of bounds [1..256]", tp->width); @@ -172,7 +177,7 @@ int omega_validate_object(const OmegaGraph *graph, const OmegaObject *obj, char case KIND_OPERATION: { if (obj->payload_len >= sizeof(OperationPayload)) { const OperationPayload *op = (const OperationPayload*)obj->payload; - if (op->opcode == OP_INVALID || op->opcode > OP_COMPILE) { + if (op->opcode == OP_INVALID || op->opcode > OP_CONVERT) { snprintf(err_msg, err_msg_len, "Invalid opcode 0x%02x", op->opcode); return -1; } diff --git a/src/visor/visor_realization.c b/src/visor/visor_realization.c index 546faffba..cd13fa249 100644 --- a/src/visor/visor_realization.c +++ b/src/visor/visor_realization.c @@ -69,6 +69,7 @@ static const char *opcode_name(OpCode op) { case OP_CONCAT: return "CONCAT"; case OP_SLICE: return "SLICE"; case OP_COMPILE: return "COMPILE"; + case OP_CONVERT: return "CONVERT"; default: return "INVALID"; } } diff --git a/src/visor/visor_semantic.c b/src/visor/visor_semantic.c index 41a1b1fd8..7e5e5e957 100644 --- a/src/visor/visor_semantic.c +++ b/src/visor/visor_semantic.c @@ -108,7 +108,7 @@ static int parse_object(const OmegaObject *o, Parsed *p, char *reason, size_t rn case KIND_TYPE: if (o->payload_len < sizeof(TypePayload)) { snprintf(reason, rn, "TYPE payload_len %u < %zu", (unsigned)o->payload_len, sizeof(TypePayload)); return -2; } memcpy(&p->tp, o->payload, sizeof(TypePayload)); - if ((unsigned)p->tp.tag == TYPE_INVALID || (unsigned)p->tp.tag > TYPE_EFFECT_RECEIPT_REF) { snprintf(reason, rn, "invalid type tag 0x%02x", (unsigned)p->tp.tag); return -2; } + if ((unsigned)p->tp.tag == TYPE_INVALID || (unsigned)p->tp.tag > TYPE_FP32) { snprintf(reason, rn, "invalid type tag 0x%02x", (unsigned)p->tp.tag); return -2; } p->shape = VISOR_SHAPE_TYPE; break; case KIND_VALUE: @@ -120,7 +120,7 @@ static int parse_object(const OmegaObject *o, Parsed *p, char *reason, size_t rn case KIND_OPERATION: if (o->payload_len >= sizeof(OperationPayload)) { memcpy(&p->op, o->payload, sizeof(OperationPayload)); - if ((unsigned)p->op.opcode == OP_INVALID || (unsigned)p->op.opcode > OP_COMPILE) { snprintf(reason, rn, "invalid opcode 0x%02x", (unsigned)p->op.opcode); return -2; } + if ((unsigned)p->op.opcode == OP_INVALID || (unsigned)p->op.opcode > OP_CONVERT) { snprintf(reason, rn, "invalid opcode 0x%02x", (unsigned)p->op.opcode); return -2; } if ((unsigned)p->op.overflow == OVERFLOW_DEFAULT || (unsigned)p->op.overflow > OVERFLOW_FAIL_CLOSED) { snprintf(reason, rn, "invalid overflow policy 0x%02x", (unsigned)p->op.overflow); return -2; } if (p->op.arity > 4) { snprintf(reason, rn, "arity %u > 4", p->op.arity); return -2; } p->shape = VISOR_SHAPE_OPERATION; @@ -197,6 +197,7 @@ static int type_text_of(const OmegaGraph *g, const SemanticId *type_id, char *ou case TYPE_CAPABILITY_REF: snprintf(out, n, "cap_ref"); break; case TYPE_EFFECT_INTENT_REF: snprintf(out, n, "effect_intent_ref"); break; case TYPE_EFFECT_RECEIPT_REF: snprintf(out, n, "effect_receipt_ref"); break; + case TYPE_FP32: snprintf(out, n, "fp32"); break; default: snprintf(out, n, "?"); return -1; } return 0; diff --git a/tests/numeric_native/.crumb b/tests/numeric_native/.crumb new file mode 100644 index 000000000..f6e6b3c9d --- /dev/null +++ b/tests/numeric_native/.crumb @@ -0,0 +1,7 @@ +{ + "schema_version": "1.0.0", + "name": "numeric_native", + "purpose": "Simulated M16 driver for numeric resource-lifecycle tests. No device execution or numeric parity evidence.", + "above": {"name": "tests", "path": ".."}, + "invariants": ["Never link this driver into production executables."] +} diff --git a/tests/numeric_native/m16_native.h b/tests/numeric_native/m16_native.h new file mode 100644 index 000000000..c8363f6ea --- /dev/null +++ b/tests/numeric_native/m16_native.h @@ -0,0 +1,9 @@ +#ifndef M16_NATIVE_H +#define M16_NATIVE_H +#include +#include +typedef struct { struct { char err[256]; } rm; } M16NativeContext; +int m16_native_open(M16NativeContext *ctx); +int m16_native_close(M16NativeContext *ctx); +int m16_native_wait_marker(volatile uint32_t *word, uint32_t want, uint64_t ms); +#endif diff --git a/tests/numeric_native/mutants.sh b/tests/numeric_native/mutants.sh new file mode 100644 index 000000000..ba87a3de0 --- /dev/null +++ b/tests/numeric_native/mutants.sh @@ -0,0 +1,28 @@ +#!/bin/sh +# Compile real wrappers with one safety check removed. Compilation failure is +# not a kill: each mutated binary must run and reject a named test scenario. +set -eu +ulimit -c 0 +out=${1:?output directory required} +cc=${CC:-cc} +mkdir -p "$out" +for mutant in poison retain exact; do + dir="$out/$mutant" + mkdir -p "$dir" + cp src/omega_numeric_lifecycle.h "$dir/" + case "$mutant" in + poison) sed 's/omega_numeric_native_poison();/(void)0;/g' src/omega_numeric_native.h > "$dir/omega_numeric_native.h" ;; + retain) sed 's/if (omega_numeric_native_uncertain()) return -1;/(void)0;/' src/omega_numeric_native.h > "$dir/omega_numeric_native.h" ;; + exact) sed 's/if (rc == 0 \&\& (!word || \*word != want)) rc = -1;/(void)0;/' src/omega_numeric_native.h > "$dir/omega_numeric_native.h" ;; + esac + if cmp -s src/omega_numeric_native.h "$dir/omega_numeric_native.h"; then + echo "FAIL: mutation $mutant changed nothing"; exit 1 + fi + $cc -std=c11 -O2 -Wall -Wextra -Werror -I"$dir" -Isrc -Itests/numeric_native tests/test_numeric_lifecycle.c tests/numeric_native/other_launcher.c -o "$dir/test" + rc=0 + "$dir/test" > "$dir/output" 2>&1 || rc=$? + if [ "$rc" -ne 1 ] || ! grep -q '^FAIL numeric lifecycle scenario ' "$dir/output"; then + echo "FAIL: mutation $mutant survived or did not run"; cat "$dir/output"; exit 1 + fi + echo "numeric lifecycle mutant $mutant: killed" +done diff --git a/tests/numeric_native/other_launcher.c b/tests/numeric_native/other_launcher.c new file mode 100644 index 000000000..19914dcbe --- /dev/null +++ b/tests/numeric_native/other_launcher.c @@ -0,0 +1,5 @@ +#include "omega_numeric_native.h" +int numeric_other_launcher_open(void) { + M16NativeContext ctx; + return omega_numeric_native_open(&ctx); +} diff --git a/tests/realize/test_program_fp32.c b/tests/realize/test_program_fp32.c new file mode 100644 index 000000000..4400871c8 --- /dev/null +++ b/tests/realize/test_program_fp32.c @@ -0,0 +1,130 @@ +/* test_program_fp32.c -- FP32 in the program IR (E1 gap row 12, spec/program-fp32.md). + * Gate OMEGA_PROGRAM_FP32_PASS: type check refuses mixed types, conversions are explicit, + * ids bind the types, evaluation equals an independent host-float evaluator, and the AArch64 + * realizer refuses FP32 programs. Physics-free; opens no device. */ +#include +#include +#include +#include +#include "omega_core.h" +#include "omega_program.h" +#include "omega_program_fp32.h" +#include "omega_numeric.h" + +static int fails, total; +#define CHECK(c, msg) do { total++; if (!(c)) { fails++; printf("FAIL: %s (line %d)\n", msg, __LINE__); } } while (0) + +static uint32_t fbits(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } +static float bf(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } + +/* independent evaluator: host float arithmetic (built with -ffp-contract=off) */ +static uint32_t host_ref(const OmegaProgram *p, uint32_t x) { + float v = bf(x); + for (uint16_t i = 0; i < p->body.step_count; ++i) { + uint8_t op = p->body.steps[i].op; + float k = bf((uint32_t)p->body.steps[i].imm); + if (op == OP_ADD) v = v + k; + else if (op == OP_SUB) v = v - k; + else if (op == OP_MUL) v = v * k; + else if (op == OP_DIV) v = v / k; + } + return fbits(v); +} + +int main(void) { + char why[200]; + OmegaProgram a, b, c; + OmegaProgramStep add1[] = { { OP_ADD, fbits(1.0f) } }; + OmegaProgramStep mix[] = { { OP_ADD, fbits(1.0f) }, { OP_MUL, fbits(2.5f) }, { OP_DIV, fbits(3.0f) }, { OP_SUB, fbits(0.5f) } }; + + /* 1. a valid FP32 program builds, checks, has an id */ + CHECK(omega_program_build_fp32(&a, "fp_add1", TYPE_FP32, TYPE_FP32, add1, 1) == 0, "build fp32 add"); + CHECK(omega_program_fp32_check(&a, why, sizeof why) == 0, "check fp32 add"); + CHECK(omega_program_build_fp32(&b, "fp_mix", TYPE_FP32, TYPE_FP32, mix, 4) == 0, "build fp32 mix"); + + /* 2. id binds the type: same steps over u32 is refused, never aliases */ + CHECK(omega_program_build_fp32(&c, "u32_add1", TYPE_UNSIGNED_INT, TYPE_UNSIGNED_INT, add1, 1) != 0, + "ADD on u32 refused without a conversion"); + OmegaProgramStep cv_fp[] = { { OP_CONVERT, TYPE_FP32 } }; + OmegaProgram u2f, f2u; + CHECK(omega_program_build_convert(&u2f, "u2f", TYPE_UNSIGNED_INT, TYPE_FP32) == 0, "build u32->fp32"); + CHECK(omega_program_build_convert(&f2u, "f2u", TYPE_FP32, TYPE_UNSIGNED_INT) == 0, "build fp32->u32"); + CHECK(memcmp(u2f.program_id.bytes, f2u.program_id.bytes, OMEGA_ID_BYTES) != 0, "convert ids differ"); + CHECK(memcmp(a.program_id.bytes, b.program_id.bytes, OMEGA_ID_BYTES) != 0, "fp32 program ids differ by body"); + OmegaProgram a2; + CHECK(omega_program_build_fp32(&a2, "renamed", TYPE_FP32, TYPE_FP32, add1, 1) == 0 && + memcmp(a.program_id.bytes, a2.program_id.bytes, OMEGA_ID_BYTES) == 0, "name is metadata, id stable"); + OmegaProgramStep add_other[] = { { OP_ADD, fbits(2.0f) } }; + OmegaProgram a3; + CHECK(omega_program_build_fp32(&a3, "fp_add2", TYPE_FP32, TYPE_FP32, add_other, 1) == 0 && + memcmp(a.program_id.bytes, a3.program_id.bytes, OMEGA_ID_BYTES) != 0, "constant is part of the id"); + + /* 3. type check refuses mixed types and non-FP32 ops */ + OmegaProgramStep bad_and[] = { { OP_AND, 0xFF } }; + CHECK(omega_program_build_fp32(&c, "and", TYPE_FP32, TYPE_FP32, bad_and, 1) != 0, "AND on FP32 refused"); + OmegaProgramStep mixed[] = { { OP_CONVERT, TYPE_UNSIGNED_INT }, { OP_ADD, 1 } }; + CHECK(omega_program_build_fp32(&c, "mixed", TYPE_FP32, TYPE_UNSIGNED_INT, mixed, 2) != 0, "ADD after CONVERT-to-u32 refused"); + CHECK(omega_program_build_fp32(&c, "wrongout", TYPE_FP32, TYPE_UNSIGNED_INT, add1, 1) != 0, "body type != contract output refused"); + CHECK(omega_program_build_fp32(&c, "noop", TYPE_FP32, TYPE_FP32, cv_fp, 1) != 0, "CONVERT to same type refused"); + OmegaProgramStep big[] = { { OP_ADD, 0x100000000ull } }; + CHECK(omega_program_build_fp32(&c, "big", TYPE_FP32, TYPE_FP32, big, 1) != 0, "constant wider than 32 bits refused"); + /* tampered body: stale id refused */ + OmegaProgram t = a; t.body.steps[0].imm = fbits(9.0f); + CHECK(omega_program_fp32_check(&t, why, sizeof why) != 0, "tampered body refused"); + /* contract width 64 refused */ + t = a; t.contract.input_width = 64; + CHECK(omega_program_fp32_check(&t, why, sizeof why) != 0, "width 64 refused"); + + /* 4. composition: FP32 then FP32 ok; u32 meets FP32 only through convert */ + CHECK(omega_program_compose(&a, &b, &c, why, sizeof why) == 0, "compose fp32 . fp32"); + CHECK(c.body.step_count == 5 && omega_program_fp32_check(&c, why, sizeof why) == 0, "composition is a valid fp32 program"); + CHECK(omega_program_compose(&a, &f2u, &c, why, sizeof why) == 0 && omega_program_fp32_check(&c, why, sizeof why) == 0, + "compose fp32 then convert to u32"); + CHECK(omega_program_compose(&f2u, &a, &c, why, sizeof why) != 0, "u32-out program cannot feed an FP32 program directly"); + CHECK(omega_program_compose(&u2f, &a, &c, why, sizeof why) == 0 && omega_program_fp32_check(&c, why, sizeof why) == 0, + "u32 -> convert -> fp32 op composes"); + + /* 5. evaluation equals the independent host evaluator and the library definitions */ + static const uint32_t pat[] = { 0, 0x80000000u, 0x3f800000u, 0xbf800000u, 0x7f800000u, 0xff800000u, 0x7fc00000u, + 0x00000001u, 0x007fffffu, 0x00800000u, 0x7f7fffffu, 0x4b800000u, 0x33800000u, 0x3effffffu }; + uint32_t xs[4096], ys[4096]; + size_t n = 0; + for (size_t i = 0; i < sizeof pat / sizeof pat[0]; ++i) xs[n++] = pat[i]; + uint64_t s = 0x9e3779b97f4a7c15ull; + while (n < 4096) { s ^= s << 13; s ^= s >> 7; s ^= s << 17; xs[n++] = (uint32_t)(s >> 16); } + const OmegaProgram *progs[] = { &a, &b, &a3 }; + int eq = 1; + for (int pi = 0; pi < 3; ++pi) { + CHECK(omega_program_fp32_eval(progs[pi], xs, n, ys) == 0, "eval fp32"); + for (size_t i = 0; i < n; ++i) { + uint32_t r = host_ref(progs[pi], xs[i]); + int nanboth = isnan(bf(r)) && isnan(bf(ys[i])); + if (r != ys[i] && !nanboth) { eq = 0; printf(" mismatch prog %d x=%08x host=%08x lib=%08x\n", pi, xs[i], r, ys[i]); break; } + } + } + CHECK(eq, "fp32 eval == host float evaluator (14 patterns + 4082 random, 3 programs)"); + + /* conversions equal the library reference definitions */ + CHECK(omega_program_fp32_eval(&u2f, xs, n, ys) == 0, "eval u2f"); + eq = 1; + for (size_t i = 0; i < n; ++i) if (ys[i] != fbits(omega_ref_u2f(xs[i]))) { eq = 0; break; } + CHECK(eq, "u32->fp32 == omega_ref_u2f"); + CHECK(omega_program_fp32_eval(&f2u, xs, n, ys) == 0, "eval f2u"); + eq = 1; + for (size_t i = 0; i < n; ++i) if (ys[i] != omega_ref_f2u(bf(xs[i]))) { eq = 0; break; } + CHECK(eq, "fp32->u32 == omega_ref_f2u"); + + /* a u32 -> convert -> add -> u32 chain, explicit conversions only */ + OmegaProgramStep chain[] = { { OP_CONVERT, TYPE_FP32 }, { OP_ADD, fbits(1.5f) }, { OP_CONVERT, TYPE_UNSIGNED_INT } }; + OmegaProgram ch; + CHECK(omega_program_build_fp32(&ch, "chain", TYPE_UNSIGNED_INT, TYPE_UNSIGNED_INT, chain, 3) == 0, "build explicit chain"); + uint32_t in3[] = { 0, 1, 41, 0xfffffff0u }, out3[4]; + CHECK(omega_program_fp32_eval(&ch, in3, 4, out3) == 0 && out3[0] == 1 && out3[1] == 2 && out3[2] == 42, "chain evaluates 0->1, 1->2, 41->42"); + + /* 6. the AArch64 realizer refuses FP32 programs with a reason */ + char rwhy[200] = ""; + CHECK(omega_program_realize_ex(&a, rwhy, sizeof rwhy) != 0 && rwhy[0] != '\0', "AArch64 realizer refuses FP32 program"); + + printf("GATE OMEGA_PROGRAM_FP32_PASS %s %d/%d\n", fails ? "FAIL" : "PASS", total - fails, total); + return fails ? 1 : 0; +} diff --git a/tests/run_reduce_chip.sh b/tests/run_reduce_chip.sh index 0e0a24426..f15cea9d3 100755 --- a/tests/run_reduce_chip.sh +++ b/tests/run_reduce_chip.sh @@ -14,7 +14,7 @@ # 4. PASS needs exit status 0, "RED_GB10_PARITY_: PASS" for each of # SUM, MAX, MIN and MEAN, "RED_GB10_PARITY: PASS" and "E1 Reduce Verdict: # PASS" in the log, and a clean tree afterwards. MEAN is chip SUM levels -# plus one declared host division (omega_math_div); the receipt says so. +# plus one chip division (the GB10 DIV kernel, E1 row 7); the receipt says so. # 5. Writes a content-addressed receipt /.json (mode # 0444, never overwritten) for PASS and FAIL alike, plus the log and binary # as blobs/.{log,bin}. The evidence dir must lie outside the tree. @@ -119,10 +119,11 @@ store_blob() { fi echo "$d" } -BIN_SHA=""; LOG_SHA="" +BIN_SHA=""; LOG_SHA=""; STDERR_SHA="" if [ -f "$BIN" ]; then BIN_SHA=$(store_blob "$BIN" bin) || exit 2; fi [ -z "$BIN_SHA_BUILT" ] || [ "$BIN_SHA" = "$BIN_SHA_BUILT" ] || FAIL_REASON="${FAIL_REASON:-binary changed between build and receipt}" if [ -f "$OUT/reduce.log" ]; then LOG_SHA=$(store_blob "$OUT/reduce.log" log) || exit 2; fi +if [ -f "$OUT/reduce.stderr" ]; then STDERR_SHA=$(store_blob "$OUT/reduce.stderr" stderr) || exit 2; fi VERDICT=PASS; [ -n "$FAIL_REASON" ] && VERDICT=FAIL PARITY=$(grep '^RED_GB10_PARITY:' "$OUT/reduce.log" 2>/dev/null | head -1) PSUM=$(grep '^RED_GB10_PARITY_SUM:' "$OUT/reduce.log" 2>/dev/null | head -1) @@ -133,14 +134,14 @@ TMP=$OUT/receipt.json jq -n --arg suite E1_REDUCE_GB10_PARITY --arg status "$VERDICT" --arg reason "$FAIL_REASON" \ --arg run_id "$RUN_ID" --arg commit "$COMMIT" --arg physics "$PHEAD" --argjson clean_after "$CLEAN_AFTER" \ --arg order "RECURSIVE_TILE32_PAIRWISE_TREE_LANE_DELTA_16_8_4_2_1_PAD_IDENTITY_MIN_ONE_LEVEL" \ - --arg bin "$BIN_SHA" --arg log "$LOG_SHA" --arg parity "$PARITY" --arg psum "$PSUM" --arg pmax "$PMAX" --arg pmin "$PMIN" --arg pmean "$PMEAN" --arg exit_status "$STATUS" \ + --arg bin "$BIN_SHA" --arg log "$LOG_SHA" --arg stderr_sha "$STDERR_SHA" --arg parity "$PARITY" --arg psum "$PSUM" --arg pmax "$PMAX" --arg pmin "$PMIN" --arg pmean "$PMEAN" --arg exit_status "$STATUS" \ --arg host "$(uname -n)" --arg kernel "$(uname -r)" \ '{suite:$suite,status:$status,reason:$reason,run_id:$run_id,omega_commit:$commit,omega_clean_before:true, omega_clean_after:$clean_after,physics_commit:$physics,declared_order:$order,binary_sha256:$bin, - log_sha256:$log,exit_status:$exit_status,parity_line:$parity, + log_sha256:$log,stderr_sha256:$stderr_sha,exit_status:$exit_status,parity_line:$parity, ops:["SUM","MAX","MIN","MEAN"],parity_by_op:{SUM:$psum,MAX:$pmax,MIN:$pmin,MEAN:$pmean}, - chip_kernels:{SUM:"REDUCE_SUM (WP-C patch, SHFL.DOWN+FADD)",MAX:"reduce minmax patch SHFL.DOWN+FMNMX !PT",MIN:"reduce minmax patch SHFL.DOWN+FMNMX PT",MEAN:"chip SUM levels"}, - mean_final_division:"HOST_DECLARED_STEP omega_math_div(sum,u2f(n)); GB10 DIV kernel (omega#141) not merged",host:$host,kernel:$kernel}' > "$TMP" || die "receipt json (jq) failed, no receipt written" + chip_kernels:{SUM:"REDUCE_SUM (WP-C patch, SHFL.DOWN+FADD)",MAX:"reduce minmax patch SHFL.DOWN+FMNMX !PT",MIN:"reduce minmax patch SHFL.DOWN+FMNMX PT",MEAN:"chip SUM levels + chip DIV (omega_ds_gb10_run)"}, + mean_final_division:"GB10_DIV omega_ds_gb10_run(DIV, sum, u2f(n)); no host step",host:$host,kernel:$kernel}' > "$TMP" || die "receipt json (jq) failed, no receipt written" [ -s "$TMP" ] || die "empty receipt, not written" [ "$VERDICT" != PASS ] || { [ -n "$BIN_SHA" ] && [ -n "$LOG_SHA" ]; } || die "PASS without binary and log digests refused" DIG=$(sha256sum "$TMP" | cut -d' ' -f1) diff --git a/tests/test_chip_run_transc_manifest.sh b/tests/test_chip_run_transc_manifest.sh index ad0cf464e..0e7ecf197 100755 --- a/tests/test_chip_run_transc_manifest.sh +++ b/tests/test_chip_run_transc_manifest.sh @@ -109,11 +109,11 @@ suite() { runw happy -- ; HAPPY_R=$R ck happy_exit test "$RC" = 0 ck happy_last_line last_is "VERDICT PASS" - ck happy_results_echoed test "$(grep -c '^RESULT chip ' "$OUT")" = 4 + ck happy_results_echoed test "$(grep -c '^RESULT chip ' "$OUT")" = 9 ck happy_noise_not_echoed lacks '^noise' ck happy_receipt_line has '^RECEIPT /.*\.json$' ck happy_no_chiprun_line lacks '^CHIP_RUN:' - ck happy_default_ops rj '.ops_requested == ["EXP2","LOG2","SIGMOID","TANH"] and (.ops | map(.op)) == ["EXP2","LOG2","SIGMOID","TANH"]' + ck happy_default_ops rj '.ops_requested == ["EXP2","LOG2","SIGMOID","TANH","SIN","COS","ERF","GELU","RSQRT"] and (.ops | map(.op)) == ["EXP2","LOG2","SIGMOID","TANH","SIN","COS","ERF","GELU","RSQRT"]' ck happy_ops_typed rj '.ops[0] == {op:"EXP2",checked:4294967296,exhaustive:true,mismatches:0,unwritten:0,verdict:"PASS"}' ck happy_kernels rj '.kernels == [{op:"EXP2",instructions:12,sha256:"aaaa"},{op:"LOG2",instructions:34,sha256:"bbbb"}]' ck happy_nvd rj '.nvdisasm_check == "nvdisasm fake provenance line"' diff --git a/tests/test_numeric_lifecycle.c b/tests/test_numeric_lifecycle.c new file mode 100644 index 000000000..ea1512ce3 --- /dev/null +++ b/tests/test_numeric_lifecycle.c @@ -0,0 +1,97 @@ +/* Executes the production lifecycle wrappers against a simulated M16 driver. + * Each scenario gets a fresh process. There is intentionally no reset API. */ +#include "omega_numeric_native.h" +#include +#include +#include + +atomic_int omega_numeric_native_state = ATOMIC_VAR_INIT(OMEGA_NUMERIC_NATIVE_IDLE); +static int opens, closes, waits, open_failure, close_failure, fail_wait, wrong_word; +int m16_native_open(M16NativeContext *ctx) { + (void)ctx; opens++; return open_failure ? -1 : 0; +} +int m16_native_close(M16NativeContext *ctx) { + (void)ctx; closes++; return close_failure ? -1 : 0; +} +int m16_native_wait_marker(volatile uint32_t *word, uint32_t want, uint64_t ms) { + assert(ms == 5000 || ms == 600000); + waits++; + if (waits == fail_wait) return -1; + *word = wrong_word ? want + 1u : want; + return 0; +} +/* Defined in another translation unit: the latch must be process-wide. */ +int numeric_other_launcher_open(void); + +static void check_blocked(void) { + int before = opens; + assert(numeric_other_launcher_open() != 0); + assert(opens == before); +} +static void scenario(int which) { + M16NativeContext ctx; + volatile uint32_t marker = 0; + if (which == 0) { + open_failure = 1; + assert(omega_numeric_native_open(&ctx) != 0); + assert(closes == 0); + open_failure = 0; + assert(omega_numeric_native_open(&ctx) == 0); + assert(omega_numeric_native_close(&ctx) == 0); + return; + } + assert(omega_numeric_native_open(&ctx) == 0); + if (which == 1) { + check_blocked(); /* a simultaneous launcher cannot open another seat */ + assert(omega_numeric_native_close(&ctx) == 0); /* pre-submit cleanup */ + assert(omega_numeric_native_open(&ctx) == 0); + assert(omega_numeric_native_close(&ctx) == 0); + assert(closes == 2); + return; + } + if (which == 2) { + assert(omega_numeric_native_wait(&marker, 0x44444444u, 5000) == 0); + assert(omega_numeric_native_wait(&marker, 6u, 5000) == 0); + assert(omega_numeric_native_close(&ctx) == 0); + assert(omega_numeric_native_open(&ctx) == 0); + assert(omega_numeric_native_close(&ctx) == 0); + return; + } + if (which == 3) { + close_failure = 1; + assert(omega_numeric_native_close(&ctx) != 0); + check_blocked(); + return; + } + if (which == 4) wrong_word = 1; + else fail_wait = which - 4; /* first marker, second marker, then semaphore */ + int failed = 0; + const uint32_t expected[] = {0x44444444u, 0x46464646u, 6u}; + for (int i = 0; i < 3; i++) { + if (omega_numeric_native_wait(&marker, expected[i], 600000) != 0) { + failed = 1; + break; + } + } + assert(failed); + assert(omega_numeric_native_uncertain()); + assert(omega_numeric_native_close(&ctx) != 0); + assert(closes == 0); /* never release a possibly running channel */ + omega_numeric_native_release(); /* a late cleanup cannot clear poison */ + check_blocked(); +} +int main(void) { + for (int i = 0; i < 8; i++) { + pid_t p = fork(); + assert(p >= 0); + if (p == 0) { scenario(i); _exit(0); } + int status; + assert(waitpid(p, &status, 0) == p); + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + fprintf(stderr, "FAIL numeric lifecycle scenario %d\n", i); + return 1; + } + } + puts("numeric lifecycle: PASS (8 simulated-driver scenarios; hardware NOT_RUN)"); + return 0; +} diff --git a/tests/test_omega_c3_ab_gb10.c b/tests/test_omega_c3_ab_gb10.c new file mode 100644 index 000000000..7d7ea14bf --- /dev/null +++ b/tests/test_omega_c3_ab_gb10.c @@ -0,0 +1,290 @@ +/* + * C3 A/B harness for the reduce and ldst launchers (E1 gap table; omega PR #198). + * Sibling of tests/test_omega_unwritten_trap_gb10.c (the #201 harness, left unchanged): + * same output lines, different launchers under test. + * + * --chip [--repeats N] [--sizes a,b,c] [--ops SUM,MAX,MIN,MEAN,LDST] [--seed S] + * --arm GPU build only: prints "arm= c3_protect=" and exits 0, no device work + * Exit: 0 = clean, 1 = hits or device errors, 2 = refused / NOT_RUN. + * Defaults: --repeats 200, --sizes 1000003,65, --ops SUM,MAX,MEAN,LDST, --seed 0. + * + * Arms. The launchers src/omega_numeric_reduce_gb10.c (run_chunk) and src/omega_numeric_ldst_gb10.c + * (omega_ldst_gb10_run) carry the C3 protection of omega_ds_gb10_run (L2_FLUSH_DIRTY mem-op plus a second + * release marker 0x46464646 at marker_mem+0x10, waited for before every readback). Building every source + * with -DOMEGA_C3_PROTECT_OFF compiles that protection out of those two launchers (the control arm); the + * default build keeps it (the fix arm). The define does not touch omega_ds_gb10_run, so the MEAN final + * division is protected in both arms. The arm is printed on the start line. + * + * What counts as a hit (one OMEGA_UNWRITTEN_HIT line each, summed into OMEGA_UNWRITTEN_TRAP: /): + * reduce ops the call returned OMEGA_NUMERIC_OK and the result bits differ from omega_reduce_reference. + * Inputs are finite with |x| in [2^-15, 1), so every legitimate sum is below 2^20 and every + * legitimate max/min is below 1. run_chunk fills the device output with 0x55 bytes + * (src/omega_numeric_reduce_gb10.c, memset of out_mem), about 1.5e13 as a float. A result + * with biased exponent >= 0xA0 is labelled kind=poison, any other difference kind=wrong. + * The label is only a hint: every difference is a hit, and a poisoned MEAN is divided + * by n on the chip, so it is labelled wrong. + * LDST a B32 load, B32 store copy of n words (host in -> GPU load -> GPU store -> host out) + * returned OK and out differs from in anywhere. The host output is pre-filled with 0x55555555 + * (the launcher copies it to the device first) and no input word equals it, so a surviving + * 0x55555555 is an unwritten word (kind=poison). + * A call that returns OMEGA_NUMERIC_ERR_DEVICE (-4) is NOT a hit: it is a device error (OMEGA_UNWRITTEN_DEVERR + * line, counted in device_errors; the launcher also prints its own step line on stderr: GB10_DEVFAIL (#180) for reduce + * and divsqrt, OMEGA_DEVERR for ldst). + * Any other non-OK code means the launcher refused the input before touching the device: the harness prints + * OMEGA_UNWRITTEN_REFUSED and OMEGA_UNWRITTEN_TRAP: NOT_RUN and exits 2. + * The harness stops early only after 3 device errors in a row (a jammed seat), never on a single one. + * + * Never run this directly: chip runs go through the forge queue and are never killed or timed out. + */ +#include "omega_numeric.h" +#include "omega_numeric_divsqrt_gb10.h" +#include "omega_numeric_ldst_gb10.h" +#include "omega_numeric_reduce.h" +#include "omega_unwritten_trap.h" + +#include +#include +#include +#include +#include +#include + +#ifdef OMEGA_NUMERIC_CPU_ONLY +int main(void) { + printf("OMEGA_UNWRITTEN_TRAP: NOT_RUN (CPU-only build)\n"); + return 2; +} + +#else /* GB10 build */ + +#define POISON 0x55555555u +#define MAX_SIZES 8 +#define STOP_AFTER_CONSECUTIVE_DEVERR 3 + +#ifdef OMEGA_C3_PROTECT_OFF +#define ARM_NAME "control" +#define PROTECT_STATE "OFF" +#else +#define ARM_NAME "fix" +#define PROTECT_STATE "ON" +#endif + +typedef struct { + const char *name; + int ldst; /* 1: the ldst round trip, 0: a reduction */ + OmegaReduceOp rop; +} TestOp; + +static const TestOp ALL_OPS[] = { + { "SUM", 0, OMEGA_RED_SUM }, { "MAX", 0, OMEGA_RED_MAX }, { "MIN", 0, OMEGA_RED_MIN }, + { "MEAN", 0, OMEGA_RED_MEAN }, { "LDST", 1, OMEGA_RED_SUM }, +}; +#define N_ALL_OPS (sizeof(ALL_OPS) / sizeof(ALL_OPS[0])) + +static uint64_t g_rng = 0x9e3779b97f4a7c15ull; +static uint64_t rnd(void) { + g_rng ^= g_rng << 13; g_rng ^= g_rng >> 7; g_rng ^= g_rng << 17; + return g_rng; +} + +static uint32_t f2b(float f) { uint32_t b; memcpy(&b, &f, 4); return b; } +static float b2f(uint32_t b) { float f; memcpy(&f, &b, 4); return f; } + +/* finite, |x| in [2^-15, 1): biased exponent 0x70..0x7e, random sign and mantissa */ +static float gen_small(void) { + uint32_t r = (uint32_t)rnd(); + return b2f((r & 0x807fffffu) | ((0x70u + ((r >> 23) % 15u)) << 23)); +} + +static void utc_now(char *buf, size_t cap) { + time_t t = time(NULL); + struct tm tm; + gmtime_r(&t, &tm); + strftime(buf, cap, "%Y-%m-%dT%H:%M:%SZ", &tm); +} + +static int parse_sizes(const char *s, size_t *out, int max) { + int n = 0; + while (*s && n < max) { + char *e; + unsigned long v = strtoul(s, &e, 10); + if (e == s || v == 0 || v > OMEGA_REDUCE_MEAN_MAX_N) return -1; + out[n++] = (size_t)v; + if (*e && *e != ',') return -1; + s = *e == ',' ? e + 1 : e; + } + return *s ? -1 : n; +} + +static int parse_pos_long(const char *s, long *out) { + char *e; + long v = strtol(s, &e, 10); + if (e == s || *e || v <= 0) return -1; + *out = v; + return 0; +} + +static int parse_ops(const char *arg, const TestOp **out, int max) { + char buf[128]; + if (strlen(arg) >= sizeof buf) return -1; + strcpy(buf, arg); + int n = 0; + for (char *tok = strtok(buf, ","); tok; tok = strtok(NULL, ",")) { + const TestOp *found = NULL; + for (size_t i = 0; i < N_ALL_OPS; i++) + if (!strcmp(tok, ALL_OPS[i].name)) found = &ALL_OPS[i]; + if (!found || n >= max) return -1; + out[n++] = found; + } + return n; +} + +#define USAGE "usage: --chip [--repeats N] [--sizes a,b,c] [--ops SUM,MAX,MIN,MEAN,LDST] [--seed S]\n" + +int main(int argc, char **argv) { + setvbuf(stdout, NULL, _IOLBF, 0); + int chip = 0; + long repeats = 200, seed = 0; + size_t sizes[MAX_SIZES] = { 1000003u, 65u }; + int nsizes = 2; + const TestOp *ops[N_ALL_OPS]; + int nops = 0; + ops[nops++] = &ALL_OPS[0]; /* SUM */ + ops[nops++] = &ALL_OPS[1]; /* MAX */ + ops[nops++] = &ALL_OPS[3]; /* MEAN */ + ops[nops++] = &ALL_OPS[4]; /* LDST */ + for (int i = 1; i < argc; i++) { + if (!strcmp(argv[i], "--arm")) { printf("arm=%s c3_protect=%s\n", ARM_NAME, PROTECT_STATE); return 0; } + else if (!strcmp(argv[i], "--chip")) chip = 1; + else if (!strcmp(argv[i], "--repeats") && i + 1 < argc) { + if (parse_pos_long(argv[++i], &repeats) != 0) { printf("bad --repeats\nOMEGA_UNWRITTEN_TRAP: NOT_RUN\n"); return 2; } + } else if (!strcmp(argv[i], "--seed") && i + 1 < argc) { + char *e; + seed = strtol(argv[++i], &e, 10); + if (e == argv[i] || *e) { printf("bad --seed\nOMEGA_UNWRITTEN_TRAP: NOT_RUN\n"); return 2; } + } else if (!strcmp(argv[i], "--sizes") && i + 1 < argc) { + nsizes = parse_sizes(argv[++i], sizes, MAX_SIZES); + if (nsizes <= 0) { printf("bad --sizes (1..%u, at most %d)\nOMEGA_UNWRITTEN_TRAP: NOT_RUN\n", (unsigned)OMEGA_REDUCE_MEAN_MAX_N, MAX_SIZES); return 2; } + } else if (!strcmp(argv[i], "--ops") && i + 1 < argc) { + nops = parse_ops(argv[++i], ops, (int)N_ALL_OPS); + if (nops <= 0) { printf("bad --ops (SUM,MAX,MIN,MEAN,LDST)\nOMEGA_UNWRITTEN_TRAP: NOT_RUN\n"); return 2; } + } else { printf(USAGE); return 2; } + } + if (!chip) { printf(USAGE "OMEGA_UNWRITTEN_TRAP: NOT_RUN\n"); return 2; } + g_rng ^= (uint64_t)seed * 0xd1b54a32d192ed03ull; + if (!g_rng) g_rng = 1; + + size_t maxn = 0; + for (int i = 0; i < nsizes; i++) if (sizes[i] > maxn) maxn = sizes[i]; + float *fx[MAX_SIZES] = { 0 }; + uint32_t *ux[MAX_SIZES] = { 0 }, *o = malloc(maxn * 4); + int alloc_ok = o != NULL; + for (int i = 0; i < nsizes; i++) { + fx[i] = malloc(sizes[i] * sizeof(float)); + ux[i] = malloc(sizes[i] * sizeof(uint32_t)); + alloc_ok &= fx[i] != NULL && ux[i] != NULL; + } + if (!alloc_ok) { printf("out of memory\nOMEGA_UNWRITTEN_TRAP: NOT_RUN\n"); return 2; } + + char start_utc[40]; + utc_now(start_utc, sizeof(start_utc)); + printf("start=%s arm=%s c3_protect=%s repeats_per_op=%ld ops=%d sizes=%d seed=%ld\n", start_utc, ARM_NAME, PROTECT_STATE, + repeats, nops, nsizes, seed); + + const OmegaLdstSpec ldst_spec = { OMEGA_LD_B32, OMEGA_ST_B32, 4, 4, 0, 0 }; + uint64_t hits = 0, runs = 0, dev_errs = 0; + int consecutive = 0; + for (int oi = 0; oi < nops; oi++) { + const TestOp *t = ops[oi]; + uint32_t ref_bits[MAX_SIZES] = { 0 }; + /* inputs per size, fresh per op; the reduce reference is computed once per size */ + for (int si = 0; si < nsizes; si++) { + for (size_t k = 0; k < sizes[si]; k++) { + fx[si][k] = gen_small(); + uint32_t w = (uint32_t)rnd(); + ux[si][k] = w == POISON ? 0x3f800000u : w; + } + if (!t->ldst) { + float r = 0; + if (omega_reduce_reference(t->rop, fx[si], sizes[si], &r) != 0) { + printf("reference failed op=%s size=%zu\nOMEGA_UNWRITTEN_TRAP: NOT_RUN\n", t->name, sizes[si]); + return 2; + } + ref_bits[si] = f2b(r); + } + } + for (long rep = 0; rep < repeats; rep++) { + int si = (int)(rep % nsizes); + size_t n = sizes[si]; + int rc, bad = 0; + uint32_t got_bits = 0; + unsigned launches = 0; + OmegaUnwrittenReport r; + uint64_t mism = 0; + memset(&r, 0, sizeof r); + struct timespec s0, s1; + clock_gettime(CLOCK_MONOTONIC, &s0); + if (t->ldst) { + for (size_t k = 0; k < n; k++) o[k] = POISON; + omega_ldst_gb10_set_spec_id(0); + rc = omega_ldst_gb10_run(&ldst_spec, (const uint8_t *)ux[si], n * 4, (uint8_t *)o, n * 4, 0, n); + } else { + float g = 0; + rc = omega_reduce_gb10(t->rop, fx[si], n, &g); + launches = omega_reduce_gb10_last_launches(); + got_bits = f2b(g); + } + clock_gettime(CLOCK_MONOTONIC, &s1); + runs++; + if (rc != OMEGA_NUMERIC_OK && rc != OMEGA_NUMERIC_ERR_DEVICE) { + /* refused before any device work (bad arguments, operands, FPCR): a harness fault, not a device event */ + printf("OMEGA_UNWRITTEN_REFUSED op=%s run=%ld size=%zu rc=%d arm=%s\n", t->name, rep, n, rc, ARM_NAME); + printf("OMEGA_UNWRITTEN_TRAP: NOT_RUN\n"); + return 2; + } + if (rc != OMEGA_NUMERIC_OK) { + dev_errs++; + consecutive++; + printf("OMEGA_UNWRITTEN_DEVERR op=%s run=%ld size=%zu rc=%d launches=%u arm=%s\n", t->name, rep, n, rc, launches, ARM_NAME); + if (consecutive >= STOP_AFTER_CONSECUTIVE_DEVERR) { + printf("OMEGA_UNWRITTEN_STOP op=%s consecutive_device_errors=%d\n", t->name, consecutive); + goto done; /* a jammed seat: stop, never loop on it */ + } + continue; + } + consecutive = 0; + if (t->ldst) { + omega_unwritten_scan(o, n, POISON, OMEGA_UNWRITTEN_BLOCK, &r); + for (size_t k = 0; k < n; k++) if (o[k] != ux[si][k]) mism++; + bad = mism > 0; + } else { + bad = got_bits != ref_bits[si]; + } + if (bad) { + char now[40]; + long ms = (long)((s1.tv_sec - s0.tv_sec) * 1000 + (s1.tv_nsec - s0.tv_nsec) / 1000000); + utc_now(now, sizeof(now)); + hits++; + if (t->ldst) + printf("OMEGA_UNWRITTEN_HIT op=%s run=%ld size=%zu kind=%s count=%" PRIu64 " mismatches=%" PRIu64 " first=%" PRIu64 + " last=%" PRIu64 " whole_blocks=%d launch_ms=%ld at=%s arm=%s\n", + t->name, rep, n, r.count ? "poison" : "wrong", r.count, mism, r.first, r.last, r.whole_blocks, ms, now, ARM_NAME); + else + printf("OMEGA_UNWRITTEN_HIT op=%s run=%ld size=%zu kind=%s got=0x%08x want=0x%08x launches=%u launch_ms=%ld at=%s arm=%s\n", + t->name, rep, n, ((got_bits >> 23) & 0xffu) >= 0xa0u ? "poison" : "wrong", + got_bits, ref_bits[si], launches, ms, now, ARM_NAME); + } + if ((rep + 1) % 100 == 0) { + printf(" %s %ld/%ld runs, hits so far %" PRIu64 ", device errors so far %" PRIu64 "\n", t->name, rep + 1, repeats, hits, dev_errs); + fflush(stdout); + } + } + } +done: + printf("device_errors=%" PRIu64 "\n", dev_errs); + printf("OMEGA_UNWRITTEN_TRAP: %" PRIu64 "/%" PRIu64 "\n", hits, runs); + for (int i = 0; i < nsizes; i++) { free(fx[i]); free(ux[i]); } + free(o); + return (hits || dev_errs) ? 1 : 0; +} +#endif diff --git a/tests/test_omega_divsqrt_gb10.c b/tests/test_omega_divsqrt_gb10.c index 50bdfde6b..a23c2837a 100644 --- a/tests/test_omega_divsqrt_gb10.c +++ b/tests/test_omega_divsqrt_gb10.c @@ -309,7 +309,7 @@ static int dump(const char *dir) { uint8_t code[OMEGA_DS_MAX_CODE_BYTES]; size_t len = 0; char path[512]; - static const char *const NM[OMEGA_DS_OP_COUNT] = { "div", "sqrt", "exp2", "log2", "sigmoid", "tanh" }; + static const char *const NM[OMEGA_DS_OP_COUNT] = { "div", "sqrt", "exp2", "log2", "sigmoid", "tanh", "sin", "cos", "erf", "gelu", "rsqrt" }; const char *nm = NM[op]; if (build((OmegaDsOp)op, code, &len) != 0 || omega_ds_listing((OmegaDsOp)op, lst, sizeof(lst)) != 0) return 1; snprintf(path, sizeof(path), "%s/%s.bin", dir, nm); diff --git a/tests/test_omega_ldst_gb10.c b/tests/test_omega_ldst_gb10.c new file mode 100644 index 000000000..f17aef672 --- /dev/null +++ b/tests/test_omega_ldst_gb10.c @@ -0,0 +1,284 @@ +/* + * E1 row 2: general load/store on the GB10 (src/omega_numeric_ldst_gb10.h). + * + * Modes (one per run): + * (none) host tier: spec rules, kernel build/check, host model equals an independent + * byte-level oracle on every spec of the table, negative tests. No device. + * --dump DIR write each table kernel as DIR/kNNN.bin and its expected listing as DIR/kNNN.lst + * (consumed by tools/ldst_nvdisasm_check.sh) + * --chip GB10: every spec of the table, chip output compared byte for byte with the host + * model. One RESULT line per spec, then a VERDICT line. A byte still equal to the + * fill pattern where the model wrote something is counted as "unwritten" (the C3 + * unwritten-output signature), separately from wrong values. + */ +#include "omega_numeric.h" +#include "omega_numeric_ldst_gb10.h" +#include "sha256.h" + +#include +#include +#include +#include + +#define MAX_SPECS 400 +#define COUNT 1000u +#define FILL 0xA5u + +static OmegaLdstSpec g_specs[MAX_SPECS]; +static size_t g_nspecs; +static int g_pass, g_fail; +static void check(int ok, const char *id) { + if (ok) { g_pass++; printf("[PASS] %s\n", id); } else { g_fail++; printf("[FAIL] %s\n", id); } +} + +static uint64_t rng_state = 0x243f6a8885a308d3ull; +static uint32_t rnd(void) { rng_state ^= rng_state << 13; rng_state ^= rng_state >> 7; rng_state ^= rng_state << 17; return (uint32_t)(rng_state >> 16); } + +/* Every valid (ld, st) pair; for each, offsets and strides chosen from a fixed set so negative and + * positive offsets, packed and sparse strides, and 24-bit-field extremes are all covered. */ +static void build_table(void) { + static const int soff[] = { 0, 1, -1, 2, -3, 5 }; /* multiplied by the width */ + static const unsigned smul[] = { 1, 2, 3, 5 }; + g_nspecs = 0; + for (unsigned l = 0; l < OMEGA_LD_COUNT; l++) + for (unsigned t = 0; t < OMEGA_ST_COUNT; t++) { + size_t lb = omega_ld_bytes(l), sb = omega_st_bytes(t); + OmegaLdstSpec probe = { (uint8_t)l, (uint8_t)t, (uint32_t)lb, (uint32_t)sb, 0, 0 }; + if (omega_ldst_check_spec(&probe, 1, NULL, 0) != 0) continue; + for (unsigned v = 0; v < 6; v++) { + OmegaLdstSpec s; + s.ld = (uint8_t)l; s.st = (uint8_t)t; + s.in_stride = (uint32_t)(lb * smul[(v + l) % 4]); + s.out_stride = (uint32_t)(sb * smul[(v + t) % 4]); + s.in_off = (int32_t)lb * soff[(v + t) % 6]; + s.out_off = (int32_t)sb * soff[(v + l + 1) % 6]; + if (g_nspecs < MAX_SPECS) g_specs[g_nspecs++] = s; + } + } + /* 24-bit offset extremes and a large stride (one wide spec each) */ + OmegaLdstSpec e1 = { OMEGA_LD_B32, OMEGA_ST_B32, 4, 4, 0, 0 }; + e1.in_off = 0; /* extremes of the field are exercised by the encoder tests below; the chip uses the pad */ + g_specs[g_nspecs++] = e1; + OmegaLdstSpec e2 = { OMEGA_LD_B128, OMEGA_ST_B128, 4096, 64, 16, -16 }; + g_specs[g_nspecs++] = e2; + OmegaLdstSpec e3 = { OMEGA_LD_S8, OMEGA_ST_B32, 1, 4, 0, 0 }; + g_specs[g_nspecs++] = e3; + OmegaLdstSpec e4 = { OMEGA_LD_S16, OMEGA_ST_B32, 2, 4, -2, 4 }; + g_specs[g_nspecs++] = e4; +} + +typedef struct { uint8_t *in, *out; size_t in_len, out_len; } Bufs; + +static int alloc_bufs(const OmegaLdstSpec *s, Bufs *b) { + int64_t il, ih, ol, oh; + if (omega_ldst_extent(s, COUNT, &il, &ih, &ol, &oh) != 0) return -1; + size_t in_need = (size_t)(ih > (int64_t)COUNT * 4 ? ih : (int64_t)COUNT * 4) + OMEGA_LDST_PAD; + b->in_len = (in_need + 15) & ~15ull; + b->out_len = ((size_t)oh + OMEGA_LDST_PAD + 15) & ~15ull; + b->in = aligned_alloc(16, b->in_len); + b->out = aligned_alloc(16, b->out_len); + if (!b->in || !b->out) return -1; + for (size_t i = 0; i < b->in_len; i++) b->in[i] = (uint8_t)rnd(); + memset(b->out, FILL, b->out_len); + return 0; +} + +/* Independent oracle: typed C loads and stores, no shared code with the host model. */ +static void oracle(const OmegaLdstSpec *s, const Bufs *b, uint8_t *out) { + for (size_t i = 0; i < COUNT; i++) { + const uint8_t *src = b->in + OMEGA_LDST_PAD + (int64_t)s->in_off + (int64_t)i * s->in_stride; + uint8_t *dst = out + OMEGA_LDST_PAD + (int64_t)s->out_off + (int64_t)i * s->out_stride; + uint32_t lo = 0, w[4] = { 0, 0, 0, 0 }; + switch (s->ld) { + case OMEGA_LD_U8: lo = *src; break; + case OMEGA_LD_S8: lo = (uint32_t)(int32_t)(int8_t)*src; break; + case OMEGA_LD_U16: { uint16_t v; memcpy(&v, src, 2); lo = v; break; } + case OMEGA_LD_S16: { int16_t v; memcpy(&v, src, 2); lo = (uint32_t)(int32_t)v; break; } + case OMEGA_LD_B32: memcpy(&lo, src, 4); break; + case OMEGA_LD_B64: memcpy(w, src, 8); lo = w[0]; break; + case OMEGA_LD_B128: memcpy(w, src, 16); lo = w[0]; break; + } + if (s->ld <= OMEGA_LD_B32) w[0] = lo; /* B64 and B128 already filled w */ + switch (s->st) { + case OMEGA_ST_B8: *dst = (uint8_t)w[0]; break; + case OMEGA_ST_B16: { uint16_t v = (uint16_t)w[0]; memcpy(dst, &v, 2); break; } + case OMEGA_ST_B32: memcpy(dst, &w[0], 4); break; + case OMEGA_ST_B64: memcpy(dst, w, 8); break; + case OMEGA_ST_B128: memcpy(dst, w, 16); break; + } + } +} + +static int dump(const char *dir) { + for (size_t k = 0; k < g_nspecs; k++) { + uint8_t code[OMEGA_LDST_CODE_BYTES]; + static char lst[8192]; + size_t cl = 0; + char path[512]; + if (omega_ldst_build_kernel(&g_specs[k], code, sizeof code, &cl) != 0 || omega_ldst_listing(&g_specs[k], lst, sizeof lst) != 0) return 1; + snprintf(path, sizeof path, "%s/k%03zu.bin", dir, k); + FILE *f = fopen(path, "wb"); if (!f) return 1; fwrite(code, 1, cl, f); fclose(f); + snprintf(path, sizeof path, "%s/k%03zu.lst", dir, k); + f = fopen(path, "w"); if (!f) return 1; fputs(lst, f); fclose(f); + } + printf("dumped %zu kernels\n", g_nspecs); + return 0; +} + +static int host_tier(void) { + char why[200], d[96]; + int all_check = 1, all_model = 1, all_build = 1; + for (size_t k = 0; k < g_nspecs; k++) { + const OmegaLdstSpec *s = &g_specs[k]; + uint8_t code[OMEGA_LDST_CODE_BYTES]; + size_t cl = 0; + if (omega_ldst_check_spec(s, COUNT, why, sizeof why) != 0) { all_check = 0; printf(" spec %zu (%s) refused: %s\n", k, omega_ldst_describe(s, d, sizeof d), why); continue; } + if (omega_ldst_build_kernel(s, code, sizeof code, &cl) != 0 || omega_ldst_check_kernel(s, code, cl, why, sizeof why) != 0) { all_build = 0; printf(" spec %zu build/check: %s\n", k, why); } + Bufs b; + if (alloc_bufs(s, &b) != 0) { all_model = 0; continue; } + uint8_t *want = malloc(b.out_len); + memcpy(want, b.out, b.out_len); + oracle(s, &b, want); + if (omega_ldst_host_run(s, b.in, b.in_len, b.out, b.out_len, OMEGA_LDST_PAD, COUNT) != 0 || memcmp(want, b.out, b.out_len) != 0) { + all_model = 0; printf(" spec %zu (%s): host model != oracle\n", k, omega_ldst_describe(s, d, sizeof d)); + } + free(want); free(b.in); free(b.out); + } + char id[96]; + snprintf(id, sizeof id, "LDST_TABLE_SPECS_VALID (%zu specs)", g_nspecs); check(all_check, id); + check(all_build, "LDST_KERNELS_BUILD_AND_PASS_STRUCTURAL_CHECK"); + check(all_model, "LDST_HOST_MODEL_EQUALS_BYTE_ORACLE"); + + /* every (ld, st) pair of the contract appears in the table */ + int seen[OMEGA_LD_COUNT][OMEGA_ST_COUNT] = { { 0 } }, miss = 0; + for (size_t k = 0; k < g_nspecs; k++) seen[g_specs[k].ld][g_specs[k].st] = 1; + for (unsigned l = 0; l < OMEGA_LD_COUNT; l++) for (unsigned t = 0; t < OMEGA_ST_COUNT; t++) { + OmegaLdstSpec p = { (uint8_t)l, (uint8_t)t, (uint32_t)omega_ld_bytes(l), (uint32_t)omega_st_bytes(t), 0, 0 }; + if (omega_ldst_check_spec(&p, 1, NULL, 0) == 0 && !seen[l][t]) miss++; + } + check(miss == 0, "LDST_TABLE_COVERS_EVERY_VALID_LOAD_STORE_PAIR"); + + /* offset field extremes: the encoder carries the full signed 24-bit range */ + OmegaLdstSpec x = { OMEGA_LD_B32, OMEGA_ST_B32, 4, 4, 0x7ffffc, -0x800000 }; + uint8_t code[OMEGA_LDST_CODE_BYTES]; + size_t cl = 0; + check(omega_ldst_build_kernel(&x, code, sizeof code, &cl) == 0 && omega_ldst_check_kernel(&x, code, cl, why, sizeof why) == 0, "LDST_OFFSET_24BIT_EXTREMES_ENCODE"); + + /* negative: each refusal rule */ + struct { OmegaLdstSpec s; size_t n; const char *id; } neg[] = { + { { OMEGA_LD_B32, OMEGA_ST_B64, 4, 8, 0, 0 }, 4, "NEG_STORE_WIDER_THAN_LOAD_REFUSED" }, + { { OMEGA_LD_U8, OMEGA_ST_B64, 1, 8, 0, 0 }, 4, "NEG_NARROW_LOAD_WIDE_STORE_REFUSED" }, + { { OMEGA_LD_B32, OMEGA_ST_B32, 2, 4, 0, 0 }, 4, "NEG_STRIDE_BELOW_WIDTH_REFUSED" }, + { { OMEGA_LD_B32, OMEGA_ST_B32, 6, 4, 0, 0 }, 4, "NEG_STRIDE_NOT_MULTIPLE_REFUSED" }, + { { OMEGA_LD_B32, OMEGA_ST_B32, 4, 4, 2, 0 }, 4, "NEG_INPUT_OFFSET_MISALIGNED_REFUSED" }, + { { OMEGA_LD_B32, OMEGA_ST_B32, 4, 4, 0, 6 }, 4, "NEG_OUTPUT_OFFSET_MISALIGNED_REFUSED" }, + { { OMEGA_LD_B32, OMEGA_ST_B32, 4, 4, 0x800000, 0 }, 4, "NEG_OFFSET_OUTSIDE_24BIT_REFUSED" }, + { { OMEGA_LD_B32, OMEGA_ST_B32, 4, 4, -0x800004, 0 }, 4, "NEG_NEGATIVE_OFFSET_OUTSIDE_24BIT_REFUSED" }, + { { OMEGA_LD_B32, OMEGA_ST_B32, 0, 4, 0, 0 }, 4, "NEG_ZERO_STRIDE_REFUSED" }, + { { OMEGA_LD_B32, OMEGA_ST_B32, 1u << 24, 4, 0, 0 }, 4, "NEG_STRIDE_2_POW_24_REFUSED" }, + { { 9, OMEGA_ST_B32, 4, 4, 0, 0 }, 4, "NEG_UNKNOWN_LOAD_KIND_REFUSED" }, + { { OMEGA_LD_B32, 9, 4, 4, 0, 0 }, 4, "NEG_UNKNOWN_STORE_KIND_REFUSED" }, + { { OMEGA_LD_B32, OMEGA_ST_B32, 4, 4, 0, 0 }, 0, "NEG_ZERO_COUNT_REFUSED" }, + }; + for (size_t i = 0; i < sizeof neg / sizeof neg[0]; i++) check(omega_ldst_check_spec(&neg[i].s, neg[i].n, why, sizeof why) != 0, neg[i].id); + + /* negative: a mutated kernel word is caught, each patched field */ + OmegaLdstSpec ok = { OMEGA_LD_B64, OMEGA_ST_B64, 16, 24, 8, -16 }; + uint8_t good[OMEGA_LDST_CODE_BYTES]; + omega_ldst_build_kernel(&ok, good, sizeof good, &cl); + struct { size_t byte; uint8_t xor; const char *id; } mut[] = { + { 16 * 13 + 5, 0x02, "NEG_LDG_OFFSET_BIT_FLIPPED_CAUGHT" }, + { 16 * 13 + 9, 0x02, "NEG_LDG_SIZE_FIELD_CHANGED_CAUGHT" }, + { 16 * 13 + 2, 0x04, "NEG_LDG_DEST_REGISTER_CHANGED_CAUGHT" }, + { 16 * 18 + 9, 0x04, "NEG_STG_SIZE_FIELD_CHANGED_CAUGHT" }, + { 16 * 18 + 5, 0x01, "NEG_STG_OFFSET_BIT_FLIPPED_CAUGHT" }, + { 16 * 12 + 4, 0x01, "NEG_INPUT_STRIDE_WORD_CHANGED_CAUGHT" }, + { 16 * 16 + 4, 0x01, "NEG_OUTPUT_STRIDE_WORD_CHANGED_CAUGHT" }, + { 16 * 17 + 15, 0x10, "NEG_IADD3_CONTROL_WORD_CHANGED_CAUGHT" }, + { 16 * 5 + 1, 0x01, "NEG_PROLOGUE_WORD_CHANGED_CAUGHT" }, + { 16 * 20 + 0, 0x01, "NEG_EPILOGUE_WORD_CHANGED_CAUGHT" }, + }; + for (size_t i = 0; i < sizeof mut / sizeof mut[0]; i++) { + uint8_t m[OMEGA_LDST_CODE_BYTES]; + memcpy(m, good, sizeof m); + m[mut[i].byte] ^= mut[i].xor; + check(omega_ldst_check_kernel(&ok, m, sizeof m, why, sizeof why) != 0, mut[i].id); + } + check(omega_ldst_check_kernel(&ok, good, sizeof good - 16, why, sizeof why) != 0, "NEG_SHORT_KERNEL_CAUGHT"); + + /* negative: host model refuses an access outside the buffer */ + uint8_t tiny_in[64] = { 0 }, tiny_out[64] = { 0 }; + OmegaLdstSpec small = { OMEGA_LD_B32, OMEGA_ST_B32, 4, 4, 0, 0 }; + check(omega_ldst_host_run(&small, tiny_in, sizeof tiny_in, tiny_out, sizeof tiny_out, 0, 16) == 0, "LDST_HOST_RUN_INSIDE_BUFFER_OK"); + check(omega_ldst_host_run(&small, tiny_in, sizeof tiny_in, tiny_out, sizeof tiny_out, 0, 17) != 0, "NEG_HOST_RUN_PAST_END_REFUSED"); + OmegaLdstSpec neg_off = { OMEGA_LD_B32, OMEGA_ST_B32, 4, 4, -4, 0 }; + check(omega_ldst_host_run(&neg_off, tiny_in, sizeof tiny_in, tiny_out, sizeof tiny_out, 0, 4) != 0, "NEG_HOST_RUN_BEFORE_START_REFUSED"); + check(omega_ldst_gb10_run(&small, tiny_in, sizeof tiny_in, tiny_out, sizeof tiny_out, 0, 17) != 0, "NEG_GB10_RUN_PAST_END_REFUSED_BEFORE_DEVICE"); + + printf("Gate LDST host: PASSED=%d FAILED=%d\n", g_pass, g_fail); + printf("VERDICT %s\n", g_fail ? "HOST_REGRESSION" : "PASS_HOST"); + return g_fail ? 1 : 0; +} + +/* first..last (inclusive) specs, each run `repeats` times; omega_ldst_gb10_set_spec_id labels any OMEGA_DEVERR line. */ +static int chip(size_t first, size_t last, unsigned repeats) { + int bad_specs = 0; + for (size_t k = first; k <= last && k < g_nspecs; k++) + for (unsigned rep = 0; rep < repeats; rep++) { + const OmegaLdstSpec *s = &g_specs[k]; + Bufs b; + char d[96]; + if (alloc_bufs(s, &b) != 0) return 2; + uint8_t *want = malloc(b.out_len), *got = malloc(b.out_len); + memcpy(want, b.out, b.out_len); + memcpy(got, b.out, b.out_len); + if (omega_ldst_host_run(s, b.in, b.in_len, want, b.out_len, OMEGA_LDST_PAD, COUNT) != 0) return 2; + omega_ldst_gb10_set_spec_id((int)k); + int rc = omega_ldst_gb10_run(s, b.in, b.in_len, got, b.out_len, OMEGA_LDST_PAD, COUNT); + uint64_t mism = 0, unwritten = 0; + if (rc == 0) + for (size_t i = 0; i < b.out_len; i++) + if (got[i] != want[i]) { mism++; if (got[i] == FILL && want[i] != FILL) unwritten++; } + int ok = rc == 0 && mism == 0; + if (!ok) bad_specs++; + printf("RESULT chip spec=%zu %s count=%u rc=%d mismatches=%" PRIu64 " unwritten=%" PRIu64 " verdict=%s\n", k, + omega_ldst_describe(s, d, sizeof d), COUNT, rc, mism, unwritten, ok ? "PASS" : "FAIL"); + fflush(stdout); + free(want); free(got); free(b.in); free(b.out); + } + printf("VERDICT %s\n", bad_specs ? "FAIL" : "PASS"); + return bad_specs ? 1 : 0; +} + +/* whole token must be decimal digits; false otherwise */ +static int parse_num(const char *s, unsigned long *out) { + char *end; + if (!*s || *s < '0' || *s > '9') return 0; + *out = strtoul(s, &end, 10); + return *end == '\0'; +} + +/* --chip [--spec N] [--repeats R]: all specs once by default; with --spec only spec N, R times (default 1). */ +int main(int argc, char **argv) { + build_table(); + if (argc >= 3 && !strcmp(argv[1], "--dump")) return dump(argv[2]); + if (argc >= 2 && !strcmp(argv[1], "--chip")) { + size_t first = 0, last = g_nspecs ? g_nspecs - 1 : 0; + unsigned repeats = 1; + for (int i = 2; i < argc; i++) { + if (!strcmp(argv[i], "--spec") && i + 1 < argc) { + unsigned long v; + if (!parse_num(argv[++i], &v)) { fprintf(stderr, "--spec needs a whole number, got '%s'\n", argv[i]); return 2; } + first = last = (size_t)v; + if (first >= g_nspecs) { fprintf(stderr, "--spec %zu out of range (0..%zu)\n", first, g_nspecs - 1); return 2; } + } else if (!strcmp(argv[i], "--repeats") && i + 1 < argc) { + unsigned long v; + if (!parse_num(argv[++i], &v)) { fprintf(stderr, "--repeats needs a whole number, got '%s'\n", argv[i]); return 2; } + repeats = (unsigned)v; + if (repeats == 0) { fprintf(stderr, "--repeats must be >= 1\n"); return 2; } + } else { fprintf(stderr, "unknown chip argument: %s\n", argv[i]); return 2; } + } + return chip(first, last, repeats); + } + return host_tier(); +} diff --git a/tests/test_omega_numeric_transc_gb10.c b/tests/test_omega_numeric_transc_gb10.c index 601f7bb46..24ca75bb7 100644 --- a/tests/test_omega_numeric_transc_gb10.c +++ b/tests/test_omega_numeric_transc_gb10.c @@ -28,7 +28,7 @@ #include #include -static const OmegaDsOp OPS[] = { OMEGA_DS_EXP2, OMEGA_DS_LOG2, OMEGA_DS_SIGMOID, OMEGA_DS_TANH }; +static const OmegaDsOp OPS[] = { OMEGA_DS_EXP2, OMEGA_DS_LOG2, OMEGA_DS_SIGMOID, OMEGA_DS_TANH, OMEGA_DS_SIN, OMEGA_DS_COS, OMEGA_DS_ERF, OMEGA_DS_GELU, OMEGA_DS_RSQRT }; #define N_OPS (sizeof(OPS) / sizeof(OPS[0])) static int g_pass, g_fail; @@ -45,6 +45,11 @@ static uint32_t want_bits(OmegaDsOp op, uint32_t a) { case OMEGA_DS_LOG2: r = omega_math_log2(x); break; case OMEGA_DS_SIGMOID: r = omega_math_sigmoid(x); break; case OMEGA_DS_TANH: r = omega_math_tanh(x); break; + case OMEGA_DS_SIN: r = omega_math_sin(x); break; + case OMEGA_DS_COS: r = omega_math_cos(x); break; + case OMEGA_DS_ERF: r = omega_math_erf(x); break; + case OMEGA_DS_GELU: r = omega_math_gelu(x); break; + case OMEGA_DS_RSQRT: r = omega_math_rsqrt(x); break; default: return 0xffffffffu; } return omega_float_to_bits(r); diff --git a/tests/test_omega_reduce.c b/tests/test_omega_reduce.c index 5a36d2cd6..688532cfe 100644 --- a/tests/test_omega_reduce.c +++ b/tests/test_omega_reduce.c @@ -710,7 +710,7 @@ static void test_gb10_parity(void) { snprintf(det, sizeof(det), "op=%s order=%s cases=%zu launches=%zu mismatches=%zu chip_nan_bits=%s0x%08x%s %.500s", omega_reduce_op_name((OmegaReduceOp)op), OMEGA_REDUCE_DECLARED_ORDER, cases[op], launches[op], mism[op], g_nan_bits_seen[op] ? "" : "(none) ", g_nan_bits[op], - op == OMEGA_RED_MEAN ? " final_division=HOST_DECLARED_STEP" : "", d[op]); + op == OMEGA_RED_MEAN ? " final_division=GB10_DIV" : "", d[op]); char id[64]; snprintf(id, sizeof(id), "RED_GB10_PARITY_%s", omega_reduce_op_name((OmegaReduceOp)op)); verdict(id, mism[op] == 0 && cases[op] > 0, det); diff --git a/tools/divsqrt_nvdisasm_check.sh b/tools/divsqrt_nvdisasm_check.sh index 8e4dae664..a6f000645 100755 --- a/tools/divsqrt_nvdisasm_check.sh +++ b/tools/divsqrt_nvdisasm_check.sh @@ -1,6 +1,6 @@ #!/bin/bash # divsqrt_nvdisasm_check.sh -- offline provenance for the E1 row 7 kernels. -# Builds the CPU-only test, dumps the DIV, SQRT, EXP2 and LOG2 kernels Omega's own encoder +# Builds the CPU-only test, dumps every whole-program kernel (DIV, SQRT and the transcendentals) Omega's own encoder # emits, disassembles every word with nvdisasm -b SM121 and compares the text # line by line with omega_ds_listing (what the encoder says each word is). # Any difference fails. nvdisasm is an offline decoder only; nothing it prints @@ -16,7 +16,7 @@ make -s -C "$HERE" build/test_omega_divsqrt_gb10_cpu >/dev/null || { echo "VERDI "$HERE/build/test_omega_divsqrt_gb10_cpu" --dump "$TMP" || { echo "VERDICT FAIL: dump"; exit 1; } echo "nvdisasm: $("$NVDISASM" --version | grep -o "release [0-9.]*, V[0-9.]*")" rc=0 -for op in div sqrt exp2 log2 sigmoid tanh; do +for op in div sqrt exp2 log2 sigmoid tanh sin cos erf gelu rsqrt; do "$NVDISASM" -b SM121 "$TMP/$op.bin" > "$TMP/$op.raw" 2> "$TMP/$op.err" || { echo "[FAIL] $op: nvdisasm error"; cat "$TMP/$op.err"; rc=1; continue; } # keep "/*addr*/ text ;" lines, normalise spacing, drop the hex comments sed -n 's|^[[:space:]]*/\*\([0-9a-f]\{4\}\)\*/[[:space:]]*\(.*;\).*$|\1 \2|p' "$TMP/$op.raw" \ diff --git a/tools/ldst_nvdisasm_check.sh b/tools/ldst_nvdisasm_check.sh new file mode 100755 index 000000000..4dfc8d255 --- /dev/null +++ b/tools/ldst_nvdisasm_check.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# ldst_nvdisasm_check.sh -- offline provenance for the E1 row 2 load/store kernels. +# Builds the CPU-only test, dumps every table kernel (src/omega_numeric_ldst_gb10.c: load/store +# kinds, offsets, strides), disassembles each with nvdisasm -b SM121 and compares the text line by +# line with omega_ldst_listing (what the encoder says each word is). Any difference fails. +# nvdisasm is an offline decoder only; nothing it prints is copied into a kernel. No device. +# Run: make test-ldst-nvdisasm Writes only to a temp dir. +set -u +HERE=$(cd -P "$(dirname "$0")/.." && pwd) +NVDISASM=${NVDISASM:-/usr/local/cuda/bin/nvdisasm} +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT +[ -x "$NVDISASM" ] || { echo "VERDICT NOT_RUN: $NVDISASM missing"; exit 2; } +make -s -C "$HERE" build/test_omega_ldst_gb10_cpu >/dev/null || { echo "VERDICT FAIL: build"; exit 1; } +"$HERE/build/test_omega_ldst_gb10_cpu" --dump "$TMP" >/dev/null || { echo "VERDICT FAIL: dump"; exit 1; } +echo "nvdisasm: $("$NVDISASM" --version | grep -o "release [0-9.]*, V[0-9.]*")" +rc=0; n=0; bad=0 +for bin in "$TMP"/k*.bin; do + k=$(basename "$bin" .bin) + "$NVDISASM" -b SM121 "$bin" > "$TMP/$k.raw" 2> "$TMP/$k.err" || { echo "[FAIL] $k: nvdisasm error"; cat "$TMP/$k.err"; rc=1; bad=$((bad+1)); continue; } + sed -n 's|^[[:space:]]*/\*\([0-9a-f]\{4\}\)\*/[[:space:]]*\(.*;\).*$|\1 \2|p' "$TMP/$k.raw" \ + | sed 's/[[:space:]]\{1,\}/ /g; s/ ;$/ ;/' > "$TMP/$k.got" + n=$((n+1)) + if ! diff -u "$TMP/$k.lst" "$TMP/$k.got" > "$TMP/$k.diff"; then + echo "[FAIL] $k: nvdisasm text differs from the encoder's listing"; head -20 "$TMP/$k.diff"; rc=1; bad=$((bad+1)) + fi +done +echo "[$([ $bad = 0 ] && echo PASS || echo FAIL)] ldst: $((n-bad)) of $n kernels decode, every word, to the encoder's text" +[ $n -gt 0 ] || rc=1 +[ $rc = 0 ] && echo "VERDICT PASS" || echo "VERDICT FAIL" +exit $rc diff --git a/tools/manifests/numeric_transc.chiprun b/tools/manifests/numeric_transc.chiprun index bef926dca..fbcd9c060 100644 --- a/tools/manifests/numeric_transc.chiprun +++ b/tools/manifests/numeric_transc.chiprun @@ -1,4 +1,4 @@ -# Manifest for tools/chip_run.sh: E1 row 10, GB10 transcendentals (EXP2 LOG2 SIGMOID TANH), +# Manifest for tools/chip_run.sh: E1 row 10, GB10 transcendentals (EXP2 LOG2 SIGMOID TANH SIN COS ERF GELU RSQRT), # every 2^32 input compared bit for bit with the CPU tier. Sourced as shell by chip_run.sh, # which provides $HERE (omega root) and $PHYSICS. Forge queue only. # Converted from the old tools/run_numeric_transc_gate.sh (origin/main) without changing what @@ -14,7 +14,7 @@ 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/sha256.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" +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. VERDICT_RE='^RESULT|^VERDICT' PASS_LINE='^VERDICT PASS([^A-Z_]|$)' diff --git a/tools/run_numeric_ldst_chip.sh b/tools/run_numeric_ldst_chip.sh new file mode 100755 index 000000000..b43164bb7 --- /dev/null +++ b/tools/run_numeric_ldst_chip.sh @@ -0,0 +1,53 @@ +#!/bin/bash +# run_numeric_ldst_chip.sh -- E1 row 2 chip run: every spec of the load/store table +# (tests/test_omega_ldst_gb10.c) executed on the GB10 and compared byte for byte with the host model. +# Meant to run only from the heavy forge lane (which serializes chip work); it also takes +# /tmp/aien-gb10.lock. It never raises the quiet flag and never kills or times out the run. +# A FAIL whose RESULT lines show "unwritten" > 0 (bytes still holding the fill pattern where the +# host model wrote) is the C3 unwritten-output signature and must be classified as C3. +# Usage: PHYSICS_DIR= tools/run_numeric_ldst_chip.sh +# Shell + gcc only. No Python. +set -u +HERE=$(cd -P "$(dirname "$0")/.." && pwd) +PHYSICS=${PHYSICS_DIR:-$HOME/workspace/hive-worktrees/physics-pin-e95e3ed} +QUIET=$HOME/workspace/.spark-quiet +refuse() { echo "REFUSED: $*"; echo "VERDICT NOT_RUN"; exit 1; } +[ -z "$(git -C "$HERE" status --porcelain)" ] || refuse "omega tree $HERE is dirty" +PIN=$(tr -d '[:space:]' < "$HERE/physics.lock") +[ "$(git -C "$PHYSICS" rev-parse HEAD 2>/dev/null)" = "$PIN" ] || refuse "physics checkout $PHYSICS is not at physics.lock pin $PIN" +[ -e "$QUIET" ] && refuse "quiet flag is up: $(cat "$QUIET")" +[ -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" +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"; } +tail -2 "$RUN/host.log" +echo "== nvdisasm provenance" +"$HERE/tools/ldst_nvdisasm_check.sh" > "$RUN/nvdisasm.log" 2>&1 || { cat "$RUN/nvdisasm.log"; refuse "nvdisasm check failed"; } +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 +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" \ + -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/sha256.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"; } +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=$? +exec 9>&- +grep -h OMEGA_DEVERR "$RUN/chip.log" | sort | uniq -c | head -20 +grep -c '^RESULT chip .*verdict=PASS' "$RUN/chip.log" | sed 's/^/specs passed: /' +grep '^RESULT chip .*verdict=FAIL' "$RUN/chip.log" | head -20 +UNW=$(sed -n 's/.* unwritten=\([0-9]*\) .*/\1/p' "$RUN/chip.log" | awk '{s+=$1} END {print s+0}') +[ "$UNW" = 0 ] || echo "NOTE: $UNW unwritten bytes in total: C3 signature (unwritten output), classify as C3 not as a load/store bug" +grep '^VERDICT' "$RUN/chip.log" | tail -1 +echo "log: $RUN/chip.log" +[ "$RC" = 0 ] diff --git a/tools/run_numeric_transc_gate.sh b/tools/run_numeric_transc_gate.sh index fa09254ce..8c927b546 100755 --- a/tools/run_numeric_transc_gate.sh +++ b/tools/run_numeric_transc_gate.sh @@ -3,7 +3,7 @@ # frozen FP32 transcendental sequences (src/omega_numeric_transc.c), every # 2^32 input of each op compared bit for bit with the CPU tier. # -# Usage: tools/run_numeric_transc_gate.sh [OP ...] (default: EXP2 LOG2 SIGMOID TANH) +# Usage: tools/run_numeric_transc_gate.sh [OP ...] (default: EXP2 LOG2 SIGMOID TANH SIN COS ERF GELU RSQRT) # Exit: 0 PASS; 1 anything else (FAIL, NOT_RUN, refused). Refusals print # "REFUSED: why" and "VERDICT NOT_RUN". Last stdout line: "VERDICT ". # @@ -21,7 +21,7 @@ set -u HERE=$(cd -P "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) PHYSICS=${PHYSICS_DIR:-$HOME/workspace/hive-worktrees/physics-gate14-e95e3ed} -OPS=("$@"); [ ${#OPS[@]} -gt 0 ] || OPS=(EXP2 LOG2 SIGMOID TANH) +OPS=("$@"); [ ${#OPS[@]} -gt 0 ] || OPS=(EXP2 LOG2 SIGMOID TANH SIN COS ERF GELU RSQRT) refuse() { echo "REFUSED: $*"; echo "VERDICT NOT_RUN"; exit 1; } -for op in "${OPS[@]}"; do case "$op" in EXP2|LOG2|SIGMOID|TANH) ;; *) refuse "unknown op $op" ;; esac; done +for op in "${OPS[@]}"; do case "$op" in EXP2|LOG2|SIGMOID|TANH|SIN|COS|ERF|GELU|RSQRT) ;; *) refuse "unknown op $op" ;; esac; done exec bash "$HERE/tools/chip_run.sh" "$HERE/tools/manifests/numeric_transc.chiprun" --physics-dir "$PHYSICS" -- --chip "${OPS[@]}" diff --git a/tools/run_reduce_stall_probe.sh b/tools/run_reduce_stall_probe.sh new file mode 100755 index 000000000..c66e8108a --- /dev/null +++ b/tools/run_reduce_stall_probe.sh @@ -0,0 +1,105 @@ +#!/bin/bash +# tools/run_reduce_stall_probe.sh -- E1 stall probe: does the GB10 reduce launch's last release write +# (marker / marker2) reach the CPU late because it sits in GPU L2 (H1) or because the method is not scheduled (H2)? +# +# tools/run_reduce_stall_probe.sh --physics-dir DIR [--run] +# +# Builds the reduce chip test binary (same build line as tests/run_reduce_chip.sh) in two arms: +# A: -DOMEGA_STALL_PROBE (marker_mem cached in GPU L2, as today) +# B: -DOMEGA_STALL_PROBE -DOMEGA_MARKER_UNCACHED (marker_mem allocated with nvrm_alloc_gpu_uncached) +# Without --run it only builds (host only, never opens the GPU). With --run it then runs arm A, then arm B, +# each under flock /tmp/aien-gb10.lock (waits for the lock, never times out or kills the chip test), with +# OMEGA_PROBE_WAIT_MS=5000 so a stall costs 5 s instead of 10 minutes, and writes stdout/stderr per arm to +# ~/workspace/evidence-out/E1-STALL-PROBE// and prints a summary per arm: +# launches, median / p99 / max marker2_ms and sem_ms, count > 1000 ms, timeouts, parity verdict. +# marker2_ms is the discriminator (marker_mem is the only memory the arms change); the QMD release +# semaphore lives in qmd_mem, still GPU-cacheable in both arms, and is waited on after marker2. +# The physics checkout must be at the commit in physics.lock. The omega tree may be dirty (a probe, not a receipt). +# Shell + coreutils + git + gcc + awk. No Python. Exit 0 on success, 2 on refusal or build failure. +set -u +SELF_DIR=$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd) +OMEGA=$(cd "$SELF_DIR/.." && pwd) +PHYS="" +DO_RUN=0 +EVROOT=$HOME/workspace/evidence-out/E1-STALL-PROBE +while [ $# -gt 0 ]; do + case $1 in + --physics-dir) PHYS=$2; shift 2 ;; + --run) DO_RUN=1; shift ;; + *) echo "unknown argument $1" >&2; exit 2 ;; + esac +done +die() { echo "run_reduce_stall_probe: $*" >&2; exit 2; } +[ -n "$PHYS" ] && [ -d "$PHYS" ] || die "--physics-dir is required" +PHYS=$(cd "$PHYS" && pwd) +COMMIT=$(git -C "$OMEGA" rev-parse HEAD) +LOCKED=$(tr -d ' \n' < "$OMEGA/physics.lock") +PHEAD=$(git -C "$PHYS" rev-parse HEAD) +[ "$PHEAD" = "$LOCKED" ] || die "physics checkout is at $PHEAD, physics.lock pins $LOCKED" +[ -z "$(git -C "$PHYS" status --porcelain)" ] || die "physics checkout is dirty" + +STAMP=$(date -u +%Y%m%dT%H%M%SZ) +mkdir -p "$OMEGA/build/stall-probe" || die "cannot create build/stall-probe" +OUT=$(mktemp -d "$OMEGA/build/stall-probe/$STAMP-${COMMIT:0:12}.XXXXXX") || die "cannot create a build directory" +NV=$PHYS/third_party/nvidia-open-580.173.02 + +build_arm() { # build_arm NAME DEFINES... + local name=$1; shift + (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" \ + -I"$NV/kernel-open/nvidia-uvm" -I"$NV/src/nvidia/arch/nvalloc/unix/include" \ + -o "$OUT/test_omega_reduce_gb10_$name" 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/sha256.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_$name.log" 2>&1 \ + || { cat "$OUT/build_$name.log" >&2; die "arm $name build failed"; } + nm -u "$OUT/test_omega_reduce_gb10_$name" | grep -Eq 'libcuda(rt)?\.so|\b(cuInit|cuCtx|cuMem|cuStream|cudaMalloc)\b' \ + && die "CUDA symbols in arm $name binary" + echo "built arm $name: $OUT/test_omega_reduce_gb10_$name" +} +build_arm A -DOMEGA_STALL_PROBE +build_arm B -DOMEGA_STALL_PROBE -DOMEGA_MARKER_UNCACHED +if [ "$DO_RUN" != 1 ]; then + echo "build only (no --run): nothing was run on the chip. binaries in $OUT" + exit 0 +fi + +EVID=$EVROOT/$STAMP +mkdir -p "$EVID" || die "cannot create $EVID" +{ echo "omega_commit=$COMMIT"; echo "physics_commit=$PHEAD"; echo "omega_dirty=$([ -n "$(git -C "$OMEGA" status --porcelain)" ] && echo yes || echo no)"; echo "host=$(uname -n) kernel=$(uname -r)"; echo "probe_wait_ms=5000"; } > "$EVID/meta.txt" + +summarize() { # summarize ARM + local arm=$1 err=$EVID/arm_$1.stderr + local nl=$(grep -c '^GB10_PROBE n=' "$err") + local tmo=$(grep -c '^GB10_PROBE_TIMEOUT' "$err") + local rf=$(grep -c '^GB10_REDUCE_FAIL' "$err") + local st=$(cat "$EVID/arm_$arm.status") + # Parity verdict: a fast arm that returns wrong values is not a fix. + local par=$(grep -m1 '^RED_GB10_PARITY:' "$EVID/arm_$arm.stdout" | cut -d' ' -f2-) + local f + for f in marker2 sem; do + grep '^GB10_PROBE n=' "$err" | sed -n "s/.* ${f}_ms=\([-0-9.]*\).*/\1/p" | sort -g > "$EVID/arm_$arm.${f}_ms.sorted" + awk -v arm="$arm" -v f="$f" -v nl="$nl" -v tmo="$tmo" -v rf="$rf" -v st="$st" ' + { v[NR]=$1; if ($1>1000) slow++ } + END { + if (NR==0) { printf "arm %s %s: exit=%s launches=%d samples=0 timeouts=%d reduce_fail_lines=%d\n", arm, f, st, nl, tmo, rf; exit } + m=(NR%2)?v[(NR+1)/2]:(v[NR/2]+v[NR/2+1])/2 + p=int(0.99*NR); if (p<0.99*NR) p++; if (p<1) p=1 + printf "arm %s %s: exit=%s launches=%d median_ms=%.3f p99_ms=%.3f max_ms=%.3f count_gt_1000ms=%d timeouts=%d reduce_fail_lines=%d\n", arm, f, st, nl, m, v[p], v[NR], slow+0, tmo, rf + }' "$EVID/arm_$arm.${f}_ms.sorted" + done + echo "arm $arm parity: ${par:-MISSING}" +} + +for arm in A B; do + echo "running arm $arm (waits for /tmp/aien-gb10.lock; never killed)" + OMEGA_PROBE_WAIT_MS=5000 flock /tmp/aien-gb10.lock "$OUT/test_omega_reduce_gb10_$arm" \ + > "$EVID/arm_$arm.stdout" 2> "$EVID/arm_$arm.stderr" + echo $? > "$EVID/arm_$arm.status" +done +{ summarize A; summarize B; } | tee "$EVID/summary.txt" +echo "evidence: $EVID"