diff --git a/.crumb b/.crumb index f3e51fe46..05c275d2d 100644 --- a/.crumb +++ b/.crumb @@ -72,7 +72,7 @@ }, { "digest": "f765ad87fdddd9b47f690b07298c951a0f7e7675dc5de4ffe44e33a0c14b1986", - "last_commit": "a8a6a3d3c", + "last_commit": "d94a503f7", "name": "spec", "purpose": "Directory spec. Purpose not yet described by a human." }, @@ -84,26 +84,26 @@ }, { "digest": "5395ff8ff9afceebe8e453788f80a3064b831513cc4cb92fd55869115e06b874", - "last_commit": "a8a6a3d3c", + "last_commit": "dcccc0211", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, { "digest": "308db0e6cf45c0a48f01f5f5f228450f191389de68006915b9ecf9c65b9a2e29", - "last_commit": "a8a6a3d3c", + "last_commit": "a50c3bd41", "name": "tools", "purpose": "Directory tools. Purpose not yet described by a human." } ], "children_root": "sha256:07bf1706dcffbad66c0353871ff67a6749055da03cee8d8ebdf9a4c91e36bddc", - "compiled_at": "2026-10-30T12:31:50Z", + "compiled_at": "2026-10-30T16:29:03Z", "compiler": "crumb-compile/1", - "digest": "sha256:904fca8c0e0cf3e3a5e5adb73393e01c7018b920bb542d289904240f70e400d6", + "digest": "sha256:777d2ffa30279f16a999a8900ba1aeee4f52a7c27ddc5fe68acb30e2945f4af6", "evidence_files": 12622, "evidence_root": "sha256:b1a08e2ce56e6feada0d8a31f06fbd7adee57adc1c1ad8dec220293ee5d439f9", - "files": 17849, - "generated_at_commit": "52a82f392fa513ebbc2d9d719a0f14c385289b06", - "source_tree": "sha256:75458da6553a0ee5ea2af95f46afb658e8a3f6e53cca6e3b4b9874035f78c2ed" + "files": 17855, + "generated_at_commit": "d743ac1d8c7746b485987ecd3ce7d4bcf4ad1220", + "source_tree": "sha256:0c6b7d8cfbabe8d12d8b7f9d5a76ae3645800633f303b1676cefda0fab1782c4" }, "owner_lane": "", "provenance": { diff --git a/om/gpumath/README.md b/om/gpumath/README.md new file mode 100644 index 000000000..9e4ee0468 --- /dev/null +++ b/om/gpumath/README.md @@ -0,0 +1,169 @@ +# om/gpumath: host math, FP8 packing and message formatting in seeded Omega + +`gpumath.om` ports three C files of `libomega_gpu.a` to seeded Omega (aien-dev/omega-mv#726, +aien-dev/aien-architecture-mv#300/#316): + +| C | what it does | Omega functions | +|---|---|---| +| `src/omega_gpu_hostmath.c` | libm-free double `log`, `exp`, `pow`, `sincos`; `pow2f` | `hmlog` `hmexp` `hmpow` `hmsincos` `hmpow2f` | +| `src/omega_gpu_fp8_pack.c` | e4m3 decode, kernel bits, NaN test and scan; bf16 scale and x packing; the f64 GEMV reference | `e4m3ref` `e4m3kbits` `e4m3isnan` `f8scannan` `f8packscales` `f8packxf32` `f8packxbf16` `f8gemvblock` | +| `src/omega_gpu_fmt.c` | the bounded `printf`-style formatter the session and tensor APIs use for error stages | `gpufmt` `gpufmtkinds` | + +The task description for this port spoke of bf16/e5m2 conversions and a format descriptor table. The +files contain neither. There is no e5m2 code, and `omega_gpu_fmt` is a formatter (`%s %c %d %u %x`, the +`l`/`ll`/`z` modifiers, `%%`). This port follows the files. + +The C is unchanged. This change adds the port and its parity evidence. Removing the C objects from +`libomega_gpu.a` goes through the omega-bridge native call ABI (omega-bridge #8) and is not part of it. + +## How the port matches the C bit for bit + +The contract is the C as the product builds it: the Makefile CFLAGS (`-std=gnu11 -O2`, gcc 13.3.0, +aarch64). The oracle objects built from these sources have the same `.text` bytes as a `make` build in +another worktree (`omega-blake3-abi/build`, same source sha256s). In detail: + +- **Same IEEE operations, same order.** Where the C computes in `float` or `double`, the port uses the + same single Omega float operation (`f32`/`f64`; omc emits one FP instruction per operator and never + writes FPCR). It does not substitute integer code that "should" agree. Operand order follows the + compiled object, not the C source, because it decides which NaN payload survives. gcc emits + `fmul d0, x, ref` in the GEMV reference (`x` first) and `fmul log(b), e` in `pow`, and the port does + the same. +- **Fused multiply-add.** `gnu11` implies `-ffp-contract=fast`, so gcc fused nine `a*b+c` in hostmath into + FMADD/FMSUB: the `log` series step `s*t2 + 1/k`, its two final steps, the two `exp` reduction steps and + the four `sincos` reduction steps. Omega has no fused operation, so `fma64` computes the fused result + exactly in integer arithmetic. It forms the 106-bit product in a 128-bit frame and aligns the addend + with a sticky bit. It rounds once to nearest even, with subnormal results rounded directly at + 2^-1074 and overflow going to infinity. It follows ARM's FPProcessNaNs3 order (addend, then the + operands) and gives the default NaN for a quiet-NaN addend with ∞·0. FMSUB is `fma64` with the + multiplicand's sign flipped, as the ARM pseudocode does. The `fma` stream checks `fma64` against the + hardware `fmadd` instruction. +- **Integer bit patterns** where the C works on integers: `pow2f`, `pow2i`, the e4m3 kernel bits and NaN + test, the scan, and the whole formatter. + +## ABI (bindable by omega-bridge native call ABI v1) + +Every exported function has at most 6 parameters, each `ulong`/`long` or a fixed-length `view`/`edit` array of +`ulong`/`uchar`, and returns `ulong`, `long` or nothing. A double or float travels as its bit pattern, and +arrays hold little-endian element bytes exactly as the C arrays hold them in memory. ABI v1 arrays have a fixed length, so the variable-length C +functions become pieces that an adapter loops over, the way `om/sha256` and `om/blake3` do: + +| C | Omega | piece | +|---|---|---| +| `omega_fp8_pack_scan_nan(w, count, &first)` | `f8scannan w(view uchar 4096) n base st(edit ulong 2)` | 4096 bytes; `st` = count, first (written only while the count is 0) | +| `omega_fp8_pack_scales(bf16, count, out, nofold)` | `f8packscales in(8192 B) n out(16384 B) nofold → long` | 4096 elements; 0 or -1 after writing the earlier outputs | +| `omega_fp8_pack_x_f32` / `_x_bf16` | `f8packxf32` / `f8packxbf16 in n out` | 4096 elements | +| `omega_fp8_gemv_oracle(w, s, n, k, x, y, yscale)` | `f8gemvblock w(128 B) x(512 B) sb acc(edit ulong 2)` | one 128-column block of one row; acc/mag start at 0 per row, blocks in order | +| `omega_gpu_fmt(out, cap, fmt, ...)` | `gpufmt out(1024 B) cap fmt(1024 B) args(16 ulong) pool(4096 B) → ulong` and `gpufmtkinds fmt kinds(64 ulong) → ulong` | see below | + +Varargs cannot cross the ABI. Each argument a conversion consumes is one 64-bit word in `args`. An +`int`-sized kind uses the low 32 bits, which is what AAPCS64 `va_arg(ap, int)` reads, and `%c` uses the +low 8 bits. A `%s` argument is an offset into `pool`, where the string is NUL-terminated; +`2^64-1` stands for NULL and prints `(null)`. `gpufmtkinds` lists the `va_arg` type of each consuming +conversion: 1 int, 2 long, 3 long long, 4 ptrdiff_t, 5 unsigned, 6 unsigned long, 7 unsigned long long, +8 size_t, 9 const char *. With that list a C adapter only calls `va_arg` with the listed types and +never parses the format string. Both functions use the same scanner (`fscan`). + +`parity/unit.py gpumath.om NAME` cuts the function-mode unit for `NAME`: the function and every library +function it calls, with `NAME` last. All 15 units compile with the pinned omc in function mode. The pinned +generator (`src/native.om` of omega-bridge `012860db`, sha256 `2c2c53f6…3940`) accepts them, and the C it +writes compiles with `-Wall -Wextra -Werror`, exporting `omega_hmlog` … `omega_gpufmtkinds`. In a +separate check (a /tmp driver, not in the tree), every corpus stream except the internal `fma` stream was +run through those generated bindings. The output was byte-identical to the C oracle's. + +## Parity + +Reproduce from a fresh clone (no C oracle needed; the oracle's output is recorded as sha256 in +`parity/expected.txt`): + +``` +OMEGA_OMC=/path/to/seed/out/omc [OMEGA_BRIDGE=/path/to/omega-bridge] sh om/gpumath/parity/run.sh +``` + +`parity/corpus.py` regenerates the corpus deterministically (splitmix64, fixed seeds, about 48 MB, never +committed). The run takes about 12 s on the Spark; the .om harness needs 2.5 s for all streams, the -O2 C +0.5 s. + +Oracle: the three C files above at omega-mv `acb3f15c` (sha256 `4ee994d7…f1eb` hostmath.c, `10ae3b45…0d4b` +hostmath.h, `881daeaf…fe79` fp8_pack.c, `795e9620…1efa` fmt.c, `dd9f13c1…2ba8` fmt.h, `ddebec31…b668` +fp8_api.h, `7e3c1779…105a` codegen_moe.h) compiled with +`gcc -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -Isrc`. `omega_bf16_to_fp32` is the same text cut +from `src/omega_blackwell_matmul.c` and built with the same flags. `.text` sha256: hostmath +`4061ecf7…6e2c`, fp8_pack `1cd43d3f…7cc3`, fmt `d06b83b7…92b7`. A /tmp driver feeds the corpus to +these objects. `fma` records use the hardware `fmadd` (inline asm), and the fmt records are typed C +calls that `corpus.py --c-cases` generates. Compiler: omc sha256 `62775d2a…712b`; `gpumath.om` at this +commit compiles to a 29,836-byte program. + +| stream | function(s) | inputs | result | +|---|---|---|---| +| fma | `fma64` (internal, vs hardware FMADD) | 326,561 triples: every pair of 27 special doubles with every third special as addend (`D_SPECIAL[::3]`, 9 addends, 6,561 triples), class mix, near-cancellation, exact ties, sticky-only ties, subnormal and overflow products, hostmath shapes | 326,561/326,561 identical | +| log | `hmlog` | 226,442: specials, every power of two 2^-1074..2^1023, 100,000 random bit patterns, 100,000 positive finite, near 1, around √2, 2^e(1+tiny) | 226,442/226,442 | +| exp | `hmexp` | 221,309: specials, 100,000 random bits, 100,000 in [-750, 712], ±200 ulps around both cutoffs, around k·ln2 for k = -1080..1024 | 221,309/221,309 | +| pow | `hmpow` | 100,097: RoPE θ^(±2i/d) for 7 θ × 5 d, random base/exponent, random bit pairs, special×special | 100,097/100,097 | +| sincos | `hmsincos` | 340,027: specials, 100,000 random bits, 100,000 with abs(a) < 2^20·π/2, 100,000 RoPE angles (pos < 65536), 30,000 within 4 ulps of nπ/2, small | 340,027/340,027 (sin and cos) | +| pow2f | `hmpow2f` | 12,006: every e in [-1000, 1000], the int extremes, 10,000 random ints | 12,006/12,006 | +| e4m3 | `e4m3ref` `e4m3kbits` `e4m3isnan` | all 256 bytes | 256/256 (×3 outputs) | +| scales | `f8packscales` | **all 65,536 bf16 × fold/no-fold** (131,072 single-element calls) + 60 pieces of 0..4096 with NaN/inf/overflowing scales (240,978 elements in total) | 131,132/131,132 calls, return value and every output word | +| xf32 | `f8packxf32` | 100,025 f32 (25 specials + 100,000 class mix: NaN payloads, ±inf, ±0, subnormals, random bits) + 777 again as an odd piece; 0-length piece | 100,802/100,802 | +| xbf16 | `f8packxbf16` | **all 65,536 bf16** + an odd piece of 333; 0-length piece | 65,869/65,869 | +| scan | `f8scannan` (4096-byte pieces) | 400 arrays, 0..20,000 bytes (3,889,100 bytes), NaN density 0 to all | 400/400 (count and first) | +| gemv | `f8gemvblock` (row × block) | 13 matrices, 2,432 rows, k up to 2048, NaN codes, special x and scales, a NaN×NaN-payload collision at every row's first NaN | 2,432/2,432 rows (y and yscale) | +| fmt | `gpufmt` `gpufmtkinds` | 28,688 calls: every format of length 1..4 over `%lzdusxcA` (two caps each), every modifier × conversion pair (`""` `l` `ll` `lll` `z` `zl` `lz` `zz` × `duxsc%qXi.5-`), 12,000 random mixes, caps 0..1024, NULL `%s`, int words with garbage upper halves | 28,688/28,688 (return, bytes up to the NUL + 1, va_arg kinds) | + +Thirteen small mutants of `gpumath.om` are part of the verdict. The script applies each one, and each +must change its stream's output: + +| mutant | records that change | +|---|---| +| ties round up instead of to even | fma 16,209 | +| sticky bit dropped | fma 15 | +| NaN priority of operands swapped | fma 1,332 | +| exact-zero sum keeps the sign | fma 10 | +| unfused `s * 2t + e*ln2lo` | log 134 | +| unfused first `sincos` reduction step | sincos 1,917 | +| `pow` multiply order swapped | pow 209 | +| `pow2f` normal-range bias off by one | pow2f 254 | +| e4m3 subnormal scale off by one | e4m3 14 | +| scale fold 2^55 | scales 51,175 | +| scan first index without the piece base | scan 15 | +| GEMV multiply order swapped | gemv 1 (the collision matrix) | +| `%c` prints `?` | fmt 2,008 | + +Fused steps that did not affect any output on this corpus: `exp`'s `- k*ln2lo` step, `log`'s final +`e*ln2hi` step (the product is exact, since ln2hi has 33 significant bits), the last `sincos` step +(`n*pio2_3t`), and the `log` series step (one `pow` result changes, no `log` result). They stay fused +because the object fuses them. + +## Limits + +- The parity contract is the current object. If the C were built without contraction + (`-ffp-contract=off`), its own results would change, and this port would keep matching today's + object, not the new one. +- Fixed pieces, set by the ABI v1 array rule: 4096 elements for scan/scales/x packing, one 128-column + block for the GEMV reference. The C adapter that loops over them is not written here. A NULL + `yscale` is the adapter ignoring `acc 1`, and a k that is not a multiple of 128 is the adapter + running only the k/128 whole blocks, as the C does. The committed corpus has neither case: both + were checked once in a /tmp run against the C (k = 200, 328 and 127 with `yscale` NULL and + non-NULL; y and yscale identical), not by `parity/run.sh`. +- `gpufmt` limits are limits of the .om, not cases where the C goes out of bounds: `fmt` at most + 1023 bytes plus its NUL inside 1024, at most 16 consuming conversions, `%s` strings inside a + 4096-byte pool, a 1024-byte `out`. Past the first three the .om traps 3 where the C keeps working + (it takes as many varargs and as long strings as the caller passes). A `cap` above 1024 traps only + when an output write actually passes index 1023 of `out`; shorter output with a larger `cap` runs + normally. The committed corpus stays within 16 conversions; the exact 16-conversion boundary + (cap 1024 and cap 40: identical to the C) and the 17-conversion trap were exercised only in a /tmp + run, not by `parity/run.sh`. A NULL `out` or `fmt` cannot be expressed; the adapter keeps the C's + `!out || cap == 0` and `fmt == NULL` checks. +- Narrowing that the C does by parameter type traps instead: an e4m3 byte above 255 traps 5, and so + does a bf16 scale above 65535. `hmpow2f` takes a `long` where the C takes an `int`. +- `fma64` is internal and assumes 53-bit significands (`mul128`). +- Two omc gaps shaped the code: a function cannot return `f32` (error 5), so f32 helpers return their + bits, and `const` is refused in function mode (error 9), so constants are written as their bit + patterns inline with a note. + +## NOT_RUN + +- No GPU, model or serving test: nothing here runs on the device. +- No `make test`. The C files and every C caller are unchanged. +- The C adapters, and the removal of the three objects from `libomega_gpu.a` through omega-bridge #8, are + not done here. +- Only the pinned omc on Linux arm64 (the Spark) was used. diff --git a/om/gpumath/gpumath.om b/om/gpumath/gpumath.om new file mode 100644 index 000000000..c364d1a26 --- /dev/null +++ b/om/gpumath/gpumath.om @@ -0,0 +1,1244 @@ +note SPDX-License-Identifier: Apache-2.0 +note gpumath.om: seeded Omega port of src/omega_gpu_hostmath.c, src/omega_gpu_fp8_pack.c and +note src/omega_gpu_fmt.c (aien-dev/omega-mv#726). Parity is on bit patterns against the C as the +note product builds it (gcc -std=gnu11 -O2, the Makefile CFLAGS, aarch64). Where the C does float +note arithmetic this file does the same IEEE operation in the same operand order (the operand order +note decides which NaN payload survives). gcc contracts some of the C's a*b+c into one fused +note FMADD/FMSUB (gnu11 implies -ffp-contract=fast); Omega has no fused operation, so fma64 below +note computes the fused result exactly in integer arithmetic. +note +note Exported functions (omega-bridge native call ABI v1: ulong/long scalars, fixed-length +note ulong/uchar arrays, ulong/long/void result). A double or float travels as its bit pattern. +note hmlog x omega_hostmath_log, f64 bits in and out +note hmexp y omega_hostmath_exp +note hmpow b e omega_hostmath_pow +note hmsincos a o omega_hostmath_sincos: o 0 sin bits, o 1 cos bits +note hmpow2f e omega_hostmath_pow2f: f32 bits +note e4m3ref b omega_fp8_e4m3_ref: f32 bits (b 0..255, else trap 5) +note e4m3kbits b omega_fp8_e4m3_kernel_bits +note e4m3isnan b omega_fp8_e4m3_is_nan: 1 or 0 +note f8scannan w n base st omega_fp8_pack_scan_nan over a 4096-byte piece (see the function) +note f8packscales i n o nf omega_fp8_pack_scales over a 4096-element piece +note f8packxf32 i n o omega_fp8_pack_x_f32 over a 4096-element piece +note f8packxbf16 i n o omega_fp8_pack_x_bf16 over a 4096-element piece +note f8gemvblock w x sb acc one 128-column block of one row of omega_fp8_gemv_oracle +note gpufmt o cap f args pl omega_gpu_fmt with the varargs as 64-bit words (see the function) +note gpufmtkinds f kinds the va_arg type of every conversion gpufmt consumes +note Arrays carry little-endian element bytes exactly as the C arrays hold them in memory. + +note ---- 128-bit helpers and the exact fused multiply-add ---- + +note index of the highest set bit of x (x > 0) +fn msb64 x ulong to ulong +n = ulong 0 +if ge x 4294967296 +x = shr x 32 +n = add n 32 +end +if ge x 65536 +x = shr x 16 +n = add n 16 +end +if ge x 256 +x = shr x 8 +n = add n 8 +end +if ge x 16 +x = shr x 4 +n = add n 4 +end +if ge x 4 +x = shr x 2 +n = add n 2 +end +if ge x 2 +n = add n 1 +end +ret n +end + +fn isnan64 x ulong to bool +ret gt and x 9223372036854775807 9218868437227405312 +end + +fn issnan64 x ulong to bool +ret and isnan64 x eq and x 2251799813685248 0 +end + +fn isinf64 x ulong to bool +ret eq and x 9223372036854775807 9218868437227405312 +end + +fn iszero64 x ulong to bool +ret eq and x 9223372036854775807 0 +end + +note significand of a finite nonzero double, shifted so that bit 52 is its top bit +fn mantn x ulong to ulong +ex = and shr x 52 2047 +m = and x 4503599627370495 +if gt ex 0 +ret or m 4503599627370496 +end +ret shl m sub 52 msb64 m +end + +note exponent matching mantn: value = mantn x * 2^expn x +fn expn x ulong to long +ex = and shr x 52 2047 +if gt ex 0 +ret sub long ex 1075 +end +m = and x 4503599627370495 +ret sub -1074 long sub 52 msb64 m +end + +note t 0, t 1 = high, low words of a * b (a, b < 2^53) +fn mul128 a ulong b ulong t edit ulong 8 to void +al = and a 4294967295 +ah = shr a 32 +bl = and b 4294967295 +bh = shr b 32 +ll = mul al bl +mid = add add mul al bh mul ah bl shr ll 32 +put t 1 or shl mid 32 and ll 4294967295 +put t 0 add mul ah bh shr mid 32 +end + +note shift the 128-bit value t k (high), t k+1 (low) right by n, OR-ing every lost bit into bit 0 +fn srj t edit ulong 8 k ulong n ulong to void +if eq n 0 +ret +end +hi = get t k +lo = get t add k 1 +if ge n 128 +put t k 0 +if eq or hi lo 0 +put t add k 1 0 +else +put t add k 1 1 +end +ret +end +st = ulong 0 +if ge n 64 +m = sub n 64 +nlo = hi +if gt m 0 +nlo = shr hi m +if ne shl hi sub 64 m 0 +st = 1 +end +end +if ne lo 0 +st = 1 +end +put t k 0 +put t add k 1 or nlo st +ret +end +if ne shl lo sub 64 n 0 +st = 1 +end +put t add k 1 or or shr lo n shl hi sub 64 n st +put t k shr hi n +end + +note t 4, t 5 = (t 0, t 1) + (t 2, t 3) +fn add128 t edit ulong 8 to void +lo = add get t 1 get t 3 +cy = ulong 0 +if lt lo get t 1 +cy = 1 +end +put t 5 lo +put t 4 add add get t 0 get t 2 cy +end + +note t 4, t 5 = (t a, t a+1) - (t b, t b+1), the first not below the second +fn sub128 t edit ulong 8 a ulong b ulong to void +l1 = get t add a 1 +l2 = get t add b 1 +bw = ulong 0 +if lt l1 l2 +bw = 1 +end +put t 5 sub l1 l2 +put t 4 sub sub get t a get t b bw +end + +fn ge128 t edit ulong 8 to bool +if ne get t 0 get t 2 +ret gt get t 0 get t 2 +end +ret ge get t 1 get t 3 +end + +note bit k of the 128-bit value hi, lo +fn bit128 hi ulong lo ulong k ulong to ulong +if ge k 64 +ret and shr hi sub k 64 1 +end +ret and shr lo k 1 +end + +note any bit of hi, lo below bit k +fn low128 hi ulong lo ulong k ulong to bool +if ge k 64 +ret or ne lo 0 ne and hi sub shl ulong 1 sub k 64 1 0 +end +ret ne and lo sub shl ulong 1 k 1 0 +end + +note round S = (t 4, t 5) * 2^x (S > 0) to nearest even as a double with sign sg; subnormal +note results round once at 2^-1074, overflow gives infinity (ARM FPRound, FPCR at its Linux default) +fn fround t edit ulong 8 x long sg ulong to ulong +hi = get t 4 +lo = get t 5 +h = msb64 lo +if ne hi 0 +h = add msb64 hi 64 +end +s = sub long h 52 +mn = sub -1074 x +if lt s mn +s = mn +end +sgn = shl sg 63 +if ge s 128 +ret sgn +end +q = ulong 0 +if gt s 0 +us = ulong s +if ge us 64 +q = shr hi sub us 64 +else +q = or shr lo us shl hi sub 64 us +end +if eq bit128 hi lo sub us 1 1 +if or low128 hi lo sub us 1 eq and q 1 1 +q = add q 1 +end +end +else +q = shl lo ulong neg s +end +bits = add shl ulong add add x s 1074 52 q +if ge bits 9218868437227405312 +ret or sgn 9218868437227405312 +end +ret or sgn bits +end + +note the NaN result of c + a * b when an operand is NaN (FPProcessNaNs3, addend first; a quiet NaN +note addend with infinity times zero gives the default NaN) +fn fmanan a ulong b ulong c ulong to ulong +if issnan64 c +ret or c 2251799813685248 +end +if issnan64 a +ret or a 2251799813685248 +end +if issnan64 b +ret or b 2251799813685248 +end +if isnan64 c +if or and isinf64 a iszero64 b and iszero64 a isinf64 b +ret 9221120237041090560 +end +ret c +end +if isnan64 a +ret a +end +ret b +end + +note c + a * b with infinities or zeros among the operands (no NaN operand) +fn fmaspec a ulong b ulong c ulong to ulong +sp = xor shr a 63 shr b 63 +sc = shr c 63 +infp = or isinf64 a isinf64 b +infc = isinf64 c +if or and isinf64 a iszero64 b and iszero64 a isinf64 b +ret 9221120237041090560 +end +if and and infc infp ne sc sp +ret 9221120237041090560 +end +if or and infc eq sc 0 and infp eq sp 0 +ret 9218868437227405312 +end +if or infc infp +ret 18442240474082181120 +end +if iszero64 c +if eq sc sp +ret c +end +ret 0 +end +ret c +end + +note the exact product a * b (a, b finite nonzero) and the addend c placed in t 0..1 and t 2..3, +note both with their top bit at bit 124 or 125, the smaller shifted right with a sticky bit to the +note larger's scale; returns that scale x (value = t * 2^x) +fn fmaalign a ulong b ulong c ulong t edit ulong 8 to long +mul128 mantn a mantn b t +ph = get t 0 +pl = get t 1 +put t 0 or shl ph 20 shr pl 44 +put t 1 shl pl 20 +xp = sub add expn a expn b 20 +if iszero64 c +ret xp +end +put t 2 shl mantn c 9 +xc = sub expn c 73 +d = sub xc xp +if gt d 0 +srj t 0 ulong d +ret xc +end +srj t 2 ulong neg d +ret xp +end + +note c + a * b, finite, a and b nonzero: the exact sum rounded once +fn fmafin a ulong b ulong c ulong to ulong +t = new ulong 8 0 +x = fmaalign a b c t +sp = xor shr a 63 shr b 63 +sc = shr c 63 +sg = sp +if or iszero64 c eq sp sc +add128 t +else +if ge128 t +sub128 t 0 2 +else +sub128 t 2 0 +sg = sc +end +end +if eq or get t 4 get t 5 0 +ret 0 +end +ret fround t x sg +end + +note AArch64 FMADD d = c + a * b (one rounding, ARM NaN rules); FMSUB d = c - a * b is +note fma64 with the sign of a flipped +fn fma64 a ulong b ulong c ulong to ulong +if or or isnan64 a isnan64 b isnan64 c +ret fmanan a b c +end +if or or or isinf64 a isinf64 b isinf64 c or iszero64 a iszero64 b +ret fmaspec a b c +end +ret fmafin a b c +end + +note ---- omega_gpu_hostmath.c ---- + +note pow2i: 2^k as a double, -1074 <= k <= 1023, 0 below, +inf above +fn pow2i k long to f64 +if gt k 1023 +ret bitcast f64 ulong 9218868437227405312 +end +if lt k -1074 +ret 0.0f64 +end +if ge k -1022 +ret bitcast f64 shl ulong add k 1023 52 +end +ret mul bitcast f64 ulong 4503599627370496 bitcast f64 shl ulong add k 2045 52 +end + +note log(x): the s * t2 + 1/k step and the two final steps are fused in the C object +fn hmlog xb ulong to ulong +x = bitcast f64 xb +if or not gt x 0.0f64 gt x bitcast f64 ulong 9218868437227405311 +ret 9221120237041090560 +end +e = long 0 +if lt x bitcast f64 ulong 4503599627370496 +x = mul x bitcast f64 ulong 4850376798678024192 +e = -54 +end +u = bitcast ulong x +e = add e sub long and shr u 52 2047 1023 +m = bitcast f64 or and u 4503599627370495 4607182418800017408 +if gt m bitcast f64 ulong 4609047870845172685 +m = mul m 0.5f64 +e = add e 1 +end +t = div sub m 1.0f64 add m 1.0f64 +t2 = bitcast ulong mul t t +s = ulong 0 +k = long 25 +while ge k 1 bound 13 +s = fma64 s t2 bitcast ulong div 1.0f64 f64 k +k = sub k 2 +end +ed = f64 e +lo = bitcast ulong mul ed bitcast f64 ulong 4461442080421002358 +lo = fma64 s bitcast ulong add t t lo +ret fma64 bitcast ulong ed 4604418534311723008 lo +end + +note exp(y): r = (y - k * ln2hi) - k * ln2lo is two FMSUBs in the C object +fn hmexp yb ulong to ulong +y = bitcast f64 yb +if ne y y +ret yb +end +if gt y bitcast f64 ulong 4649454506724284170 +ret 9218868437227405312 +end +if lt y bitcast f64 ulong 13873138101193906586 +ret 0 +end +fk = mul y bitcast f64 ulong 4609176140021203710 +h = -0.5f64 +if ge fk 0.0f64 +h = 0.5f64 +end +k = long add fk h +nk = bitcast ulong neg f64 k +r = fma64 nk 4604418534311723008 yb +r = fma64 nk 4461442080421002358 r +rd = bitcast f64 r +p = 1.0f64 +n = long 17 +while ge n 1 bound 17 +p = add div mul rd p f64 n 1.0f64 +n = sub n 1 +end +if lt k -1020 +ret bitcast ulong mul mul p pow2i -1020 pow2i add k 1020 +end +ret bitcast ulong mul p pow2i k +end + +fn hmpow bb ulong eb ulong to ulong +b = bitcast f64 bb +e = bitcast f64 eb +if or eq b 1.0f64 eq e 0.0f64 +ret 4607182418800017408 +end +ret hmexp bitcast ulong mul bitcast f64 hmlog bb e +end + +note sin r = r * ps, cos r = pc (w = r * r), the two series of the C +fn sinser w f64 to f64 +ps = 1.0f64 +k = long 15 +while ge k 3 bound 7 +ps = sub 1.0f64 div mul w ps f64 mul k sub k 1 +k = sub k 2 +end +ret ps +end + +fn cosser w f64 to f64 +pc = 1.0f64 +k = long 16 +while ge k 2 bound 8 +pc = sub 1.0f64 div mul w pc f64 mul k sub k 1 +k = sub k 2 +end +ret pc +end + +note sincos(a): o 0 = sin bits, o 1 = cos bits; the four reduction steps are FMSUBs in the C object +fn hmsincos ab ulong o edit ulong 2 to void +a = bitcast f64 ab +fq = mul a bitcast f64 ulong 4603909380684499075 +h = -0.5f64 +if ge fq 0.0f64 +h = 0.5f64 +end +n = long add fq h +nn = bitcast ulong neg f64 n +r = fma64 nn 4609753056924401664 ab +r = fma64 nn 4454258360616747008 r +r = fma64 nn 4297306550709518336 r +r = fma64 nn 4142048980368378305 r +rd = bitcast f64 r +w = mul rd rd +sr = mul rd sinser w +cr = cosser w +q = and n 3 +if eq q 0 +put o 0 bitcast ulong sr +put o 1 bitcast ulong cr +ret +end +if eq q 1 +put o 0 bitcast ulong cr +put o 1 bitcast ulong neg sr +ret +end +if eq q 2 +put o 0 bitcast ulong neg sr +put o 1 bitcast ulong neg cr +ret +end +put o 0 bitcast ulong neg cr +put o 1 bitcast ulong sr +end + +note 2^e as f32 bits, exact for -149 <= e <= 127; 0 below, +inf above +fn hmpow2f e long to ulong +if gt e 127 +ret 2139095040 +end +if ge e -126 +ret shl ulong add e 127 23 +end +if ge e -149 +ret shl ulong 1 add e 149 +end +ret 0 +end + +note ---- omega_gpu_fp8_pack.c ---- + +note f32 helpers return the bit pattern (omc refuses an f32 result type, error 5) +fn p2f e long to uint +u = hmpow2f e +ret uint u +end + +fn e4m3ref bb ulong to ulong +b = uchar bb +ex = and shr b 3 15 +mf = f32 and b 7 +sg = 1.0f32 +if ne and b 128 0 +sg = -1.0f32 +end +if and eq ex 15 eq and b 7 7 +ret 2143289344 +end +if eq ex 0 +ret ulong bitcast uint mul mul sg mf bitcast f32 p2f -9 +end +v = mul add 1.0f32 div mf 8.0f32 sg +ret ulong bitcast uint mul v bitcast f32 p2f sub long ex 7 +end + +fn e4m3kbits bb ulong to ulong +b = ulong uchar bb +ret or shl and b 127 20 shl and b 128 24 +end + +fn e4m3isnan bb ulong to ulong +b = uchar bb +if eq and b 127 127 +ret 1 +end +ret 0 +end + +note one piece of omega_fp8_pack_scan_nan(w, count, first): scans w 0 .. n-1 (n <= 4096), the +note piece starting at element base of the whole array. st 0 is the NaN count so far (0 before the +note first piece), st 1 the index of the first NaN, written only when the count was 0 (as the C +note writes *first). Returns st 0. +fn f8scannan w view uchar 4096 n ulong base ulong st edit ulong 2 to ulong +for i ulong n +if eq and get w i 127 127 +if eq get st 0 0 +put st 1 add base i +end +put st 0 add get st 0 1 +end +end +ret get st 0 +end + +fn ldbf16 v view uchar 8192 i ulong to uint +lo = uint get v mul i 2 +hi = uint get v add mul i 2 1 +ret shl or lo shl hi 8 16 +end + +fn ldf32 v view uchar 16384 i ulong to uint +o = mul i 4 +x = uint get v add o 3 +x = or shl x 8 uint get v add o 2 +x = or shl x 8 uint get v add o 1 +x = or shl x 8 uint get v o +ret x +end + +fn stf32 v edit uchar 16384 i ulong f f32 to void +o = mul i 4 +x = bitcast uint f +put v o uchar and x 255 +put v add o 1 uchar and shr x 8 255 +put v add o 2 uchar and shr x 16 255 +put v add o 3 uchar shr x 24 +end + +note one piece of omega_fp8_pack_scales: in holds n bf16 (n <= 4096), out gets n f32; nofold +note nonzero is the C's mutant_no_fold. 0, or -1 at the first NaN/inf scale or fold overflow with +note the earlier outputs written, as the C. +fn f8packscales in view uchar 8192 n ulong out edit uchar 16384 nofold ulong to long +fold = 1.0f32 +if eq nofold 0 +fold = bitcast f32 p2f 56 +end +lim = bitcast f32 uint 2137108966 +for i ulong n +s = bitcast f32 ldbf16 in i +if not le fabs s lim +ret -1 +end +f = mul fold s +if not le fabs f lim +ret -1 +end +stf32 out i f +end +ret 0 +end + +note one piece of omega_fp8_pack_x_f32: out = in * 2^64, n <= 4096 f32 +fn f8packxf32 in view uchar 16384 n ulong out edit uchar 16384 to void +fold = bitcast f32 p2f 64 +for i ulong n +stf32 out i mul bitcast f32 ldf32 in i fold +end +end + +note one piece of omega_fp8_pack_x_bf16: out = bf16 in * 2^64, n <= 4096 +fn f8packxbf16 in view uchar 8192 n ulong out edit uchar 16384 to void +fold = bitcast f32 p2f 64 +for i ulong n +stf32 out i mul bitcast f32 ldbf16 in i fold +end +end + +fn ldx v view uchar 512 i ulong to uint +o = mul i 4 +x = uint get v add o 3 +x = or shl x 8 uint get v add o 2 +x = or shl x 8 uint get v add o 1 +x = or shl x 8 uint get v o +ret x +end + +note one 128-column block of one row of omega_fp8_gemv_oracle: w the row's 128 e4m3 bytes, x the +note 128 f32 of x, sb the bf16 scale of the block, acc 0 / acc 1 the row's acc / mag (f64 bits, +note 0 before the row's first block). The caller runs the blocks of a row in order, as the C. +fn f8gemvblock w view uchar 128 x view uchar 512 sb ulong acc edit ulong 2 to void +s = f64 bitcast f32 shl uint ushort sb 16 +a = bitcast f64 get acc 0 +mg = bitcast f64 get acc 1 +for c ulong 128 +rf = f64 bitcast f32 uint e4m3ref ulong get w c +p = mul mul f64 bitcast f32 ldx x c rf s +a = add a p +mg = add mg fabs p +end +put acc 0 bitcast ulong a +put acc 1 bitcast ulong mg +end + +note ---- omega_gpu_fmt.c ---- + +note the sink: sn 0 = characters written, sn 1 = cap +fn fput out edit uchar 1024 sn edit ulong 2 c uchar to void +n = get sn 0 +if lt add n 1 get sn 1 +put out n c +put sn 0 add n 1 +end +end + +note a %s argument: an offset into the string pool pl (NUL-terminated there), or 2^64-1 for NULL +fn fputs out edit uchar 1024 sn edit ulong 2 pl view uchar 4096 off ulong to void +if eq off 18446744073709551615 +fput out sn 40 +fput out sn 110 +fput out sn 117 +fput out sn 108 +fput out sn 108 +fput out sn 41 +ret +end +i = off +while ne get pl i 0 bound 4096 +fput out sn get pl i +i = add i 1 +end +end + +fn fputu out edit uchar 1024 sn edit ulong 2 v ulong base ulong to void +tmp = new uchar 24 0 +i = ulong 0 +while true bound 24 +d = rem v base +if lt d 10 +put tmp i uchar add d 48 +else +put tmp i uchar add d 87 +end +i = add i 1 +v = div v base +if eq v 0 +break +end +end +while gt i 0 bound 24 +i = sub i 1 +fput out sn get tmp i +end +end + +fn fputd out edit uchar 1024 sn edit ulong 2 v long to void +if lt v 0 +fput out sn 45 +fputu out sn add ulong neg add v 1 1 10 +ret +end +fputu out sn ulong v 10 +end + +note the low 32 bits of w as a signed int +fn sx32 w ulong to long +v = and w 4294967295 +if ge v 2147483648 +ret sub long v 4294967296 +end +ret long v +end + +note the conversion at fmt p (fmt p is '%'): r 0 = index of the conversion byte, r 1 = the va_arg +note kind it consumes (0 none; 1 int, 2 long, 3 long long, 4 ptrdiff_t, 5 unsigned int, +note 6 unsigned long, 7 unsigned long long, 8 size_t, 9 const char *) +fn fscan fmt view uchar 1024 p ulong r edit ulong 4 to void +q = add p 1 +z = false +l = ulong 0 +if eq get fmt q 122 +z = true +q = add q 1 +else +while and eq get fmt q 108 lt l 2 bound 3 +l = add l 1 +q = add q 1 +end +end +ch = get fmt q +k = ulong 0 +if eq ch 115 +k = 9 +end +if eq ch 99 +k = 1 +end +if eq ch 100 +k = 1 +if eq l 1 +k = 2 +end +if eq l 2 +k = 3 +end +if z +k = 4 +end +end +if or eq ch 117 eq ch 120 +k = 5 +if eq l 1 +k = 6 +end +if eq l 2 +k = 7 +end +if z +k = 8 +end +end +put r 0 q +put r 1 k +end + +note one consuming conversion: argument word w of kind k, conversion byte cc +fn fconv out edit uchar 1024 sn edit ulong 2 w ulong k ulong cc uchar pl view uchar 4096 to void +if eq k 9 +fputs out sn pl w +ret +end +if eq cc 99 +fput out sn uchar and w 255 +ret +end +if eq k 1 +fputd out sn sx32 w +ret +end +if lt k 5 +fputd out sn bitcast long w +ret +end +base = ulong 10 +if eq cc 120 +base = 16 +end +if eq k 5 +fputu out sn and w 4294967295 base +ret +end +fputu out sn w base +end + +note one '%' conversion (r 0, r 1 from fscan, r 2 the next argument, r 3 the '%' index) +fn fone out edit uchar 1024 sn edit ulong 2 fmt view uchar 1024 args view ulong 16 pl view uchar 4096 r edit ulong 4 to void +q = get r 0 +k = get r 1 +cc = get fmt q +if gt k 0 +fconv out sn get args get r 2 k cc pl +put r 2 add get r 2 1 +ret +end +if eq cc 37 +fput out sn 37 +ret +end +note unsupported conversion: copied literally, nothing consumed +j = get r 3 +while le j q bound 5 +if eq get fmt j 0 +break +end +fput out sn get fmt j +j = add j 1 +end +end + +note omega_gpu_fmt(out, cap, fmt, ...): fmt NUL-terminated inside its 1024 bytes; the i-th consuming +note conversion takes args i (16 at most): an int-sized kind uses the low 32 bits (the AAPCS64 +note va_arg of an int), %c the low 8; %s takes a pool offset (2^64-1 = NULL, printed "(null)"). +note Writes at most cap - 1 characters and the NUL (cap <= 1024, else out-of-range trap 3 once +note the output reaches 1024); cap 0 writes nothing. Returns the characters written. +fn gpufmt out edit uchar 1024 cap ulong fmt view uchar 1024 args view ulong 16 pl view uchar 4096 to ulong +if eq cap 0 +ret 0 +end +sn = new ulong 2 0 +r = new ulong 4 0 +put sn 1 cap +p = ulong 0 +while ne get fmt p 0 bound 1024 +if ne get fmt p 37 +fput out sn get fmt p +p = add p 1 +continue +end +fscan fmt p r +put r 3 p +fone out sn fmt args pl r +q = get r 0 +p = add q 1 +if eq get fmt q 0 +p = q +end +end +put out get sn 0 0 +ret get sn 0 +end + +note the va_arg kinds (fscan codes) of fmt's consuming conversions, in order; returns their count +fn gpufmtkinds fmt view uchar 1024 kinds edit ulong 64 to ulong +r = new ulong 4 0 +p = ulong 0 +nk = ulong 0 +while ne get fmt p 0 bound 1024 +if ne get fmt p 37 +p = add p 1 +continue +end +fscan fmt p r +q = get r 0 +k = get r 1 +if gt k 0 +put kinds nk k +nk = add nk 1 +end +p = add q 1 +if eq get fmt q 0 +p = q +end +end +ret nk +end + +note ==== parity harness: program mode only; everything above this line is the library ==== +note Reads corpus records on stdin (om/gpumath/parity/corpus.py), writes one result line per record. +note Numbers are lowercase hex, byte strings one hex token ("-" when empty). + +global ib uchar 1048576 +global ist ulong 2 +global ob uchar 1048576 +global obn ulong 1 +global tb uchar 262144 +global gw uchar 262144 +global gsc uchar 8192 +global gx uchar 131072 + +fn inb to ulong +p = get ist 0 +if ge p get ist 1 +r = read 0 ib 0 1048576 +if le r 0 +ret 256 +end +put ist 1 ulong r +p = 0 +end +put ist 0 add p 1 +ret ulong get ib p +end + +fn obflush to void +n = get obn 0 +if gt n 0 +r = write 1 ob 0 n +end +put obn 0 0 +end + +fn ob1 c ulong to void +n = get obn 0 +if ge n 1048576 +obflush +n = 0 +end +put ob n uchar c +put obn 0 add n 1 +end + +fn hexdig v ulong to ulong +if lt v 10 +ret add v 48 +end +ret add v 87 +end + +fn ohex v ulong to void +ob1 32 +for i ulong 16 +ob1 hexdig and shr v mul sub 15 i 4 15 +end +end + +fn ohexb b ulong to void +ob1 hexdig shr b 4 +ob1 hexdig and b 15 +end + +fn hexval c ulong to ulong +if and ge c 48 le c 57 +ret sub c 48 +end +if and ge c 97 le c 102 +ret sub c 87 +end +ret 16 +end + +fn rdcode to ulong +c = inb +while or eq c 10 eq c 32 bound 999999 +c = inb +end +ret c +end + +fn rdhex to ulong +c = inb +while eq c 32 bound 999999 +c = inb +end +v = ulong 0 +while lt hexval c 16 bound 17 +v = or shl v 4 hexval c +c = inb +end +ret v +end + +note one hex byte-string token into tb; returns the byte count ("-" is empty) +fn rdbytes to ulong +c = inb +while eq c 32 bound 999999 +c = inb +end +if eq c 45 +c = inb +ret 0 +end +n = ulong 0 +while lt hexval c 16 bound 999999 +d = inb +put tb n uchar or shl hexval c 4 hexval d +n = add n 1 +c = inb +end +ret n +end + +fn sgnl v ulong to long +if ge v 9223372036854775808 +ret neg long add not v 1 +end +ret long v +end + +fn u32at v view uchar 16384 i ulong to ulong +o = mul i 4 +x = ulong get v add o 3 +x = or shl x 8 ulong get v add o 2 +x = or shl x 8 ulong get v add o 1 +ret or shl x 8 ulong get v o +end + +fn doz to void +a = rdhex +b = rdhex +c = rdhex +ob1 90 +ohex fma64 a b c +end + +fn dosc to void +o = new ulong 2 0 +a = rdhex +hmsincos a o +ob1 68 +ohex get o 0 +ohex get o 1 +end + +fn dof to void +b = rdhex +ob1 70 +ohex e4m3ref b +ohex e4m3kbits b +ohex e4m3isnan b +end + +note G nofold bf16-bytes / H f32-bytes / I bf16-bytes: one piece of the pack functions +fn dopack c ulong to void +in = new uchar 8192 0 +inf = new uchar 16384 0 +out = new uchar 16384 170 +nf = ulong 0 +if eq c 71 +nf = rdhex +end +nb = rdbytes +n = div nb 2 +if eq c 72 +n = div nb 4 +end +for i ulong nb +if eq c 72 +put inf i get tb i +else +put in i get tb i +end +end +ob1 c +if eq c 71 +ohex bitcast ulong f8packscales in n out nf +end +if eq c 72 +f8packxf32 inf n out +end +if eq c 73 +f8packxbf16 in n out +end +for i ulong n +ohex u32at out i +end +end + +note N bytes: omega_fp8_pack_scan_nan over the whole array, in 4096-byte pieces +fn doscan to void +w = new uchar 4096 0 +st = new ulong 2 0 +put st 1 12297829382473034410 +nb = rdbytes +base = ulong 0 +while lt base nb bound 64 +m = sub nb base +if gt m 4096 +m = 4096 +end +for i ulong m +put w i get tb add base i +end +r = f8scannan w m base st +base = add base m +end +ob1 78 +ohex get st 0 +ohex get st 1 +end + +fn ldblk wb edit uchar 128 xb edit uchar 512 wo ulong xo ulong to void +for c ulong 128 +put wb c get gw add wo c +end +for c ulong 512 +put xb c get gx add xo c +end +end + +fn gsb i ulong to ulong +si = mul i 2 +ret or ulong get gsc si shl ulong get gsc add si 1 8 +end + +note one row r of the gemv held in gw, gsc, gx: the adapter's block loop (acc and mag start at 0) +fn gemvrow wb edit uchar 128 xb edit uchar 512 acc edit ulong 2 r ulong k ulong to void +kb = div k 128 +so = mul div r 128 kb +put acc 0 0 +put acc 1 0 +for b ulong kb +ldblk wb xb add mul r k mul b 128 mul b 512 +f8gemvblock wb xb gsb add so b acc +end +end + +note Q n k w-bytes scale-bytes x-bytes: omega_fp8_gemv_oracle row by row, block by block +fn dogemv to void +wb = new uchar 128 0 +xb = new uchar 512 0 +acc = new ulong 2 0 +n = rdhex +k = rdhex +nb = rdbytes +for i ulong nb +put gw i get tb i +end +nb = rdbytes +for i ulong nb +put gsc i get tb i +end +nb = rdbytes +for i ulong nb +put gx i get tb i +end +ob1 81 +for r ulong n +gemvrow wb xb acc r k +ohex get acc 0 +ohex get acc 1 +end +end + +note M cap fmt-bytes nargs args... pool-bytes: omega_gpu_fmt and its va_arg kinds +fn dofmt to void +out = new uchar 1024 170 +fm = new uchar 1024 0 +args = new ulong 16 0 +pl = new uchar 4096 0 +kd = new ulong 64 0 +cap = rdhex +nb = rdbytes +for i ulong nb +put fm i get tb i +end +na = rdhex +for i ulong na +put args i rdhex +end +nb = rdbytes +for i ulong nb +put pl i get tb i +end +n = gpufmt out cap fm args pl +nk = gpufmtkinds fm kd +ob1 77 +ohex n +ob1 32 +if eq nk 0 +ob1 45 +end +for i ulong nk +ob1 hexdig get kd i +end +ob1 32 +m = add n 2 +if gt m cap +m = cap +end +if eq m 0 +ob1 45 +end +for i ulong m +ohexb ulong get out i +end +end + +fn main to int +while true bound 999999 +c = rdcode +if eq c 256 +break +end +if eq c 90 +doz +end +if eq c 65 +ob1 65 +ohex hmlog rdhex +end +if eq c 66 +ob1 66 +ohex hmexp rdhex +end +if eq c 67 +ob1 67 +b = rdhex +ohex hmpow b rdhex +end +if eq c 68 +dosc +end +if eq c 69 +ob1 69 +ohex hmpow2f sgnl rdhex +end +if eq c 70 +dof +end +if and ge c 71 le c 73 +dopack c +end +if eq c 78 +doscan +end +if eq c 81 +dogemv +end +if eq c 77 +dofmt +end +ob1 10 +end +obflush +ret 0 +end diff --git a/om/gpumath/parity/corpus.py b/om/gpumath/parity/corpus.py new file mode 100755 index 000000000..33bd31e42 --- /dev/null +++ b/om/gpumath/parity/corpus.py @@ -0,0 +1,570 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Deterministic parity corpus for om/gpumath/gpumath.om (aien-dev/omega-mv#726). + +usage: corpus.py OUTDIR [--c-cases FILE] + +Writes one record file per stream into OUTDIR (record formats: the harness section of gpumath.om). +Every random value comes from splitmix64 with a fixed seed per stream, so the files are the same +on every run and every Python 3. --c-cases also writes the typed omega_gpu_fmt calls a C oracle +needs for the fmt stream (one `case` per M record, in order). +""" +import math +import os +import struct +import sys + +M64 = (1 << 64) - 1 + + +class Rng: + def __init__(self, seed): + self.s = seed & M64 + + def u64(self): + self.s = (self.s + 0x9E3779B97F4A7C15) & M64 + z = self.s + z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & M64 + z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & M64 + return z ^ (z >> 31) + + def below(self, n): + return self.u64() % n + + def unit(self): + return (self.u64() >> 11) / float(1 << 53) + + def pick(self, seq): + return seq[self.below(len(seq))] + + +def dbits(x): + return struct.unpack("= 1 << 53: + break + ea = r.below(600) - 300 + eb = r.below(600) - 300 + a = math.ldexp(ma, ea) * (1 if r.below(2) else -1) + b = math.ldexp(mb, eb) * (1 if r.below(2) else -1) + low = ea + eb # exponent of the product's lowest (tie) bit + c = math.ldexp(1.0 + r.unit(), max(-1074, low - 2 - r.below(900))) * (1 if r.below(2) else -1) + rec(dbits(a), dbits(b), r.pick([dbits(c), dbits(c), dbits(c), 0, 1 << 63])) + with open(os.path.join(out, "fma.txt"), "w") as f: + f.writelines(lines) + return len(lines) + + +def gen_log(out): + r = Rng(0x6C6F67) + L = [] + for v in D_SPECIAL: + L.append(v) + for e in range(-1074, 1024): + L.append(dbits(math.ldexp(1.0, e))) + for _ in range(100000): + L.append(r.u64()) + for _ in range(100000): + if r.below(20) == 0: + L.append(1 + (r.u64() & 0x000FFFFFFFFFFFFE)) + else: + L.append(((1 + r.below(2046)) << 52) | (r.u64() & 0x000FFFFFFFFFFFFF)) + for _ in range(20000): + L.append(dbits(1.0 + (r.unit() - 0.5) * 2.0 ** -(r.below(50)))) + for d in range(-64, 65): + L.append(0x3FF6A09E667F3BCD + d) + for e in range(-1070, 1024, 3): # x = 2^e (1 + tiny): t is small, the fused s * 2t + e * ln2lo matters + for _ in range(6): + L.append(dbits(math.ldexp(1.0 + r.unit() * 2.0 ** -(1 + r.below(45)), e))) + with open(os.path.join(out, "log.txt"), "w") as f: + f.writelines("A %s\n" % h(v) for v in L) + return len(L) + + +def gen_exp(out): + r = Rng(0x657870) + L = list(D_SPECIAL) + for _ in range(100000): + L.append(r.u64()) + for _ in range(100000): + L.append(dbits(-750.0 + 1462.0 * r.unit())) + for edge in (709.78, -745.2): + for d in range(-200, 201): + L.append(dbits(edge) + d) + ln2 = math.log(2.0) + for k in list(range(-1080, -1015)) + list(range(1018, 1025)) + list(range(-5, 6)): + for _ in range(60): + L.append(dbits(k * ln2 + (r.unit() - 0.5) * 1.4)) + for _ in range(5000): + L.append(dbits((r.unit() - 0.5) * 2.0 ** -(r.below(60)))) + for k in range(-1075, 1025): # y within a few ulps of k * ln2: r is small, the fused reduction matters + y = dbits(k * ln2) + for d in (-3, -1, 0, 1, 2): + L.append((y + d) & M64) + with open(os.path.join(out, "exp.txt"), "w") as f: + f.writelines("B %s\n" % h(v) for v in L) + return len(L) + + +def gen_pow(out): + r = Rng(0x706F77) + P = [] + thetas = [10000.0, 500000.0, 1000000.0, 5000000.0, 10000000.0, 1000.0, 50000.0] + for th in thetas: + for d in (64, 80, 96, 128, 256): + for i in range(d // 2): + P.append((dbits(th), dbits(-(2.0 * i) / d))) + P.append((dbits(th), dbits((2.0 * i) / d))) + for _ in range(40000): + P.append((dbits(math.exp((r.unit() - 0.5) * 40.0)), dbits((r.unit() - 0.5) * 20.0))) + for _ in range(30000): + P.append((r.u64(), r.u64())) + for _ in range(25000): + P.append((rand_double(r), rand_double(r))) + for a in D_SPECIAL: + for b in D_SPECIAL: + P.append((a, b)) + with open(os.path.join(out, "pow.txt"), "w") as f: + f.writelines("C %s %s\n" % (h(a), h(b)) for a, b in P) + return len(P) + + +def gen_sincos(out): + r = Rng(0x73696E) + L = list(D_SPECIAL) + for _ in range(100000): + L.append(r.u64()) + lim = 2.0 ** 20 * math.pi / 2 + for _ in range(100000): + L.append(dbits((2.0 * r.unit() - 1.0) * lim)) + for _ in range(100000): # RoPE angles: pos * theta^(-2i/d), pos < 65536 + th = r.pick([10000.0, 500000.0, 1000000.0, 10000000.0]) + d = r.pick([64, 128, 256]) + i = r.below(d // 2) + inv = th ** (-(2.0 * i) / d) + L.append(dbits(float(r.below(65536)) * inv)) + for _ in range(30000): # near multiples of pi/2: the reduction cancels + n = r.below(1 << 21) - (1 << 20) + L.append((dbits(n * (math.pi / 2)) + r.below(9) - 4) & M64) + for _ in range(10000): + L.append(dbits((r.unit() - 0.5) * 2.0 ** -(r.below(70)))) + with open(os.path.join(out, "sincos.txt"), "w") as f: + f.writelines("D %s\n" % h(v) for v in L) + return len(L) + + +def gen_pow2f(out): + r = Rng(0x703266) + L = list(range(-1000, 1001)) + [-(1 << 31), (1 << 31) - 1, -(1 << 31) + 1, 1 << 30, -(1 << 30)] + for _ in range(10000): + L.append(r.below(1 << 32) - (1 << 31)) + with open(os.path.join(out, "pow2f.txt"), "w") as f: + f.writelines("E %s\n" % h(v & M64) for v in L) + return len(L) + + +def gen_e4m3(out): + with open(os.path.join(out, "e4m3.txt"), "w") as f: + f.writelines("F %s\n" % h(b) for b in range(256)) + return 256 + + +def le16(vals): + return b"".join(struct.pack(" 4000: + w, ce = b"x", cstr(b"x") + words.append(len(pool)) + pool += w + b"\0" + else: + words.append(w) + cargs.append(ce) + if not pool: + pool = bytearray(b"\0") + ks = "".join(str(k) for k, _ in kinds) or "-" + parts = ["M", h(cap), hb(fb), h(len(words))] + [h(w) for w in words] + [hb(bytes(pool))] + lines.append(" ".join(parts) + "\n") + cases.append("case %d: kinds = \"%s\"; n = omega_gpu_fmt(out, %d, %s%s); break;\n" + % (len(cases), ks, cap, cstr(fb), "".join(", " + a for a in cargs))) + + +def gen_fmt(out, cfile): + r = Rng(0x666D74) + lines = [] + cases = [] + alpha = b"%lzdusxcA" + import itertools + for L in (1, 2, 3, 4): + for t in itertools.product(alpha, repeat=L): + fb = bytes(t) + if len(fmt_kinds(fb)) > 16: + continue + fmt_record(r, fb, 1024, lines, cases) + fmt_record(r, fb, r.below(len(fb) + 30), lines, cases) + mods = [b"", b"l", b"ll", b"lll", b"z", b"zl", b"lz", b"zz"] + convs = b"duxsc%qXi.5-" + for m in mods: + for c in convs: + for _ in range(20): + fb = b"<" + b"%" + m + bytes([c]) + b">" + fmt_record(r, fb, r.pick([1024, 1024, 0, 1, 2, 3, 5, 8]), lines, cases) + fmt_record(r, b"tail %" + m, 1024, lines, cases) + pieces = [b"%d", b"%ld", b"%lld", b"%zd", b"%u", b"%lu", b"%llu", b"%zu", b"%x", b"%lx", b"%llx", b"%zx", + b"%s", b"%c", b"%%", b"%q", b"%5d", b"%", b"%l", b"%z", b"stage ", b": ", b"=", b" rc ", b"\xff"] + for _ in range(12000): + fb = bytearray() + for _ in range(r.below(14)): + fb += r.pick(pieces) + fb = bytes(fb) + if len(fmt_kinds(fb)) > 16 or len(fb) > 1000: + continue + cap = r.pick([1024, 1024, 1024, r.below(80), r.below(8), 1, 0]) + fmt_record(r, fb, cap, lines, cases) + with open(os.path.join(out, "fmt.txt"), "w") as f: + f.writelines(lines) + if cfile: + with open(cfile, "w") as f: + f.write("/* generated by om/gpumath/parity/corpus.py: one typed omega_gpu_fmt call per M record */\n") + f.write("static int fmt_case(long idx, char *out, const char **kindsp) {\n int n = -1; const char *kinds = 0;\n switch (idx) {\n") + f.writelines(" " + c for c in cases) + f.write(" default: break;\n }\n *kindsp = kinds;\n return n;\n}\n") + return len(lines) + + +def main(): + if len(sys.argv) not in (2, 4) or (len(sys.argv) == 4 and sys.argv[2] != "--c-cases"): + sys.exit(__doc__) + out = sys.argv[1] + cfile = sys.argv[3] if len(sys.argv) == 4 else None + os.makedirs(out, exist_ok=True) + counts = [ + ("fma", gen_fma(out)), ("log", gen_log(out)), ("exp", gen_exp(out)), ("pow", gen_pow(out)), + ("sincos", gen_sincos(out)), ("pow2f", gen_pow2f(out)), ("e4m3", gen_e4m3(out)), + ("scales", gen_scales(out)), ("xf32", gen_xf32(out)), ("xbf16", gen_xbf16(out)), + ("scan", gen_scan(out)), ("gemv", gen_gemv(out)), ("fmt", gen_fmt(out, cfile)), + ] + for name, n in counts: + print("%s %d" % (name, n)) + + +if __name__ == "__main__": + main() diff --git a/om/gpumath/parity/expected.txt b/om/gpumath/parity/expected.txt new file mode 100644 index 000000000..76e7e99ea --- /dev/null +++ b/om/gpumath/parity/expected.txt @@ -0,0 +1,16 @@ +# sha256 of the C oracle's output for each corpus stream (parity/corpus.py), the product C compiled with the +# Makefile CFLAGS (gcc 13.3.0, -std=gnu11 -O2, aarch64; .text identical to a `make` build of the same sources). +# stream records sha256 +fma 326561 f1ec4a4e11e60bb24033705fe90e185d9849a110e0e8c402edd3504e202fd8b3 +log 226442 02a5ccfdfff416cd8d39fb31a82e620238b12f70af8642134392cc291f90a581 +exp 221309 9204889d46d3180f716098f33e2244f58aad13b5a95d9094ed0ccbdbec2567e1 +pow 100097 7303f36415d2969829aa491a694ce06617ec05a667ce70b5ae30c8d0ddffc0a4 +sincos 340027 7ab82242bf634a76c2f6f9c859543aea329dd73098800aed5143268c1fdbf393 +pow2f 12006 9a46b5f84e7f888afee50a49786cad8dca8bbb1e44f4a33d78e1758a4cabae8b +e4m3 256 08e48570cba3480d5b9984a85d8624fb5b8bea26ccb77bc8942e5cd54ae92c92 +scales 131132 406998c5552787a53b89aba45547d5bea4ce0c56dfb89ba3599c7e39499ac072 +xf32 27 b45fdfdb739f1566229afe3157f35f495144686c0b6a5e7c962222a4b0c2fce6 +xbf16 18 7927d98546cbadf07f720155c9a3ba3e12065e8a019f7295dd6805b8cf3f0921 +scan 400 cbc2c9641803b600e3b191cf5bdc752bf89db2379a8fe6e31d378868dd6e50ab +gemv 13 a29a7ca1f0f151c206372d2ce48b8c1d5c0a7c65a86c741a640f838d8c7b8cd3 +fmt 28688 be0e44674280a630eb4ae2c20be4fe828f1cfa2cfb0c204ce0b053416c663fad diff --git a/om/gpumath/parity/run.sh b/om/gpumath/parity/run.sh new file mode 100755 index 000000000..cbb7f73be --- /dev/null +++ b/om/gpumath/parity/run.sh @@ -0,0 +1,85 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 +# Parity of om/gpumath/gpumath.om against the C it ports (src/omega_gpu_hostmath.c, src/omega_gpu_fp8_pack.c, +# src/omega_gpu_fmt.c), by recorded oracle output: corpus.py regenerates the corpus, the .om harness runs every +# stream, and each stream's output must hash to parity/expected.txt (the C oracle's output, recorded when the +# port was made; the oracle driver itself is not in the tree). Then thirteen small mutants of gpumath.om +# must each change their stream's hash (the corpus discriminates). With OMEGA_BRIDGE set, the 15 exported +# functions are also cut into function-mode units (unit.py), bound by the pinned omega-bridge generator and +# compiled as C (bindability). +# OMEGA_OMC seed-born omc, sha256 pinned below (exit 3 NOT_RUN without it) +# OMEGA_BRIDGE optional: an aien-dev/omega-bridge checkout whose src/native.om matches the pin +set -eu +OMC_PIN=62775d2a391cfef7cde64e387655caa9809a267093112910ec76bfa568f3712b +NATIVE_PIN=2c2c53f61d4ab302f1a2092c3c32189335dd53f6cf2b388f47a475f99f2c3940 +P=$(cd "$(dirname "$0")" && pwd) +OM=$P/../gpumath.om +[ -n "${OMEGA_OMC:-}" ] || { echo "GPUMATH-PARITY NOT_RUN: set OMEGA_OMC"; exit 3; } +[ "$(sha256sum < "$OMEGA_OMC" | cut -c1-64)" = "$OMC_PIN" ] || { echo "GPUMATH-PARITY NOT_RUN: omc is not the pinned compiler"; exit 3; } +command -v python3 > /dev/null || { echo "GPUMATH-PARITY NOT_RUN: python3 missing"; exit 3; } +T=$(mktemp -d); trap 'rm -rf "$T"' EXIT +python3 "$P/corpus.py" "$T/corp" > "$T/counts" +"$OMEGA_OMC" < "$OM" > "$T/gm"; chmod +x "$T/gm" +fail=0 +grep -v '^#' "$P/expected.txt" | while read -r s n want; do + "$T/gm" < "$T/corp/$s.txt" > "$T/$s.out" + got=$(sha256sum < "$T/$s.out" | cut -c1-64) + lines=$(wc -l < "$T/$s.out") + if [ "$got" = "$want" ] && [ "$lines" = "$n" ]; then + echo "PASS $s: $n records, output identical to the C oracle ($(grep "^$s " "$T/counts" | cut -d' ' -f2) inputs)" + else + echo "FAIL $s: $lines records, sha256 $got (want $n, $want)"; echo x >> "$T/failed" + fi +done +[ ! -e "$T/failed" ] || { echo "GPUMATH-PARITY FAIL"; exit 1; } + +# Mutants: name | stream | exact text in gpumath.om (\n for a newline) | replacement +cat > "$T/mutants" <<'EOF' +tie_up|fma|if or low128 hi lo sub us 1 eq and q 1 1|if true +sticky_off|fma|put t add k 1 or nlo st|put t add k 1 nlo +nan_order|fma|if issnan64 a\nret or a 2251799813685248\nend\nif issnan64 b|if issnan64 b\nret or b 2251799813685248\nend\nif issnan64 a +zero_sign|fma|if eq or get t 4 get t 5 0\nret 0|if eq or get t 4 get t 5 0\nret shl sg 63 +log_unfused|log|lo = fma64 s bitcast ulong add t t lo|lo = bitcast ulong add mul bitcast f64 s add t t bitcast f64 lo +sincos_unfused|sincos|r = fma64 nn 4609753056924401664 ab|r = bitcast ulong sub a mul f64 n bitcast f64 ulong 4609753056924401664 +pow_order|pow|ret hmexp bitcast ulong mul bitcast f64 hmlog bb e|ret hmexp bitcast ulong mul e bitcast f64 hmlog bb +pow2f_bias|pow2f|ret shl ulong add e 127 23|ret shl ulong add e 126 23 +e4m3_sub|e4m3|ret ulong bitcast uint mul mul sg mf bitcast f32 p2f -9|ret ulong bitcast uint mul mul sg mf bitcast f32 p2f -10 +scales_fold|scales|fold = bitcast f32 p2f 56|fold = bitcast f32 p2f 55 +scan_first|scan|put st 1 add base i|put st 1 i +gemv_order|gemv|p = mul mul f64 bitcast f32 ldx x c rf s|p = mul mul rf f64 bitcast f32 ldx x c s +fmt_char|fmt|fput out sn uchar and w 255|fput out sn 63 +EOF +while IFS='|' read -r name s old new; do + python3 - "$OM" "$T/m.om" "$old" "$new" <<'PY' +import sys +src, dst, old, new = sys.argv[1], sys.argv[2], sys.argv[3].replace("\\n", "\n"), sys.argv[4].replace("\\n", "\n") +s = open(src).read() +assert s.count(old + "\n") == 1, "mutant text not found exactly once: " + old +open(dst, "w").write(s.replace(old + "\n", new + "\n")) +PY + "$OMEGA_OMC" < "$T/m.om" > "$T/m"; chmod +x "$T/m" + rc=0; "$T/m" < "$T/corp/$s.txt" > "$T/m.out" 2> /dev/null || rc=$? + got=$(sha256sum < "$T/m.out" | cut -c1-64) + want=$(grep "^$s " "$P/expected.txt" | cut -d' ' -f3) + if [ "$got" = "$want" ]; then echo "mutant $name NOT killed on $s"; echo x >> "$T/failed"; continue; fi + d=$(paste -d'|' "$T/m.out" "$T/$s.out" | awk -F'|' '$1 != $2' | wc -l) + echo "mutant $name killed on $s ($d records differ, exit $rc)" +done < "$T/mutants" +[ ! -e "$T/failed" ] || { echo "GPUMATH-PARITY FAIL"; exit 1; } + +if [ -z "${OMEGA_BRIDGE:-}" ]; then + echo "GPUMATH-PARITY PASS (bindability NOT_RUN: set OMEGA_BRIDGE)"; exit 0 +fi +[ "$(sha256sum < "$OMEGA_BRIDGE/src/native.om" | cut -c1-64)" = "$NATIVE_PIN" ] || { echo "GPUMATH-PARITY PASS (bindability NOT_RUN: native.om is not the pinned generator)"; exit 0; } +"$OMEGA_OMC" < "$OMEGA_BRIDGE/src/native.om" > "$T/native"; chmod +x "$T/native" +: > "$T/units" +for u in hmlog hmexp hmpow hmsincos hmpow2f e4m3ref e4m3kbits e4m3isnan f8scannan f8packscales f8packxf32 \ + f8packxbf16 f8gemvblock gpufmt gpufmtkinds; do + python3 "$P/unit.py" "$OM" "$u" > "$T/u.om" + "$OMEGA_OMC" < "$T/u.om" > "$T/u.bin" + { cat "$T/u.om"; printf '\0'; printf '%08d' "$(wc -c < "$T/u.bin")"; cat "$T/u.bin"; } >> "$T/units" +done +"$T/native" < "$T/units" > "$T/units.c" +cc -std=gnu11 -O2 -Wall -Wextra -Werror -c "$T/units.c" -o "$T/units.o" +echo "bindability: 15 function-mode units accepted by native.om and compiled ($(grep -c ') uint32_t omega_[a-z0-9]*(uint64_t \*result' "$T/units.c") exported functions)" +echo "GPUMATH-PARITY PASS" diff --git a/om/gpumath/parity/unit.py b/om/gpumath/parity/unit.py new file mode 100755 index 000000000..91f64494d --- /dev/null +++ b/om/gpumath/parity/unit.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""unit.py GPUMATH.om NAME: print the function-mode unit that exports NAME. + +The unit is NAME and every library function it reaches through calls (the part of gpumath.om +before the parity-harness marker), in file order, with NAME moved to the end: the seeded compiler +enters a function-mode unit at its last function and the omega-bridge native call ABI v1 binds that +one; the others stay private helpers. Note lines before a kept function travel with it. +""" +import sys + +MARK = "note ==== parity harness" + + +def functions(lib): + """[(name, first line incl. leading notes, end line)] of the library.""" + out = [] + i = 0 + while i < len(lib): + w = lib[i].split() + if w[:1] == ["fn"]: + j = i + while j > 0 and lib[j - 1].startswith("note") and not lib[j - 1].startswith("note ----"): + j -= 1 + depth = 0 + for k in range(i, len(lib)): + t = lib[k].split()[:1] + if t and t[0] in ("fn", "if", "while", "for"): + depth += 1 + elif t == ["end"]: + depth -= 1 + if depth == 0: + break + else: + sys.exit("unit.py: %s has no closing end" % w[1]) + out.append((w[1], j, k)) + i = k + 1 + else: + i += 1 + return out + + +def main(): + if len(sys.argv) != 3: + sys.exit(__doc__) + src, name = sys.argv[1], sys.argv[2] + lines = open(src).read().split("\n") + lib = lines[:next(i for i, l in enumerate(lines) if l.startswith(MARK))] + fns = functions(lib) + span = {n: (a, b) for n, a, b in fns} + if name not in span: + sys.exit("unit.py: no function %s" % name) + calls = {} + for n, a, b in fns: + words = set() + for l in lib[a:b + 1]: + if not l.startswith("note"): + words.update(l.split()) + calls[n] = {m for m in words if m in span and m != n} + keep = {name} + todo = [name] + while todo: + for m in calls[todo.pop()]: + if m not in keep: + keep.add(m) + todo.append(m) + order = [n for n, _, _ in fns if n in keep and n != name] + [name] + parts = [] + for n in order: + a, b = span[n] + parts.append("\n".join(lib[a:b + 1])) + sys.stdout.write("note SPDX-License-Identifier: Apache-2.0\nnote generated from om/gpumath/gpumath.om by parity/unit.py %s\n\n" % name) + sys.stdout.write("\n\n".join(parts) + "\n") + + +if __name__ == "__main__": + main()