interplane.Get Omega
Read in your language

CUDApp

CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.

Brought by drakestapleton

branch main Branches Tags History

CUDApp / tests / gpu_fp8_api_test.c

1322 lines · 109192 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */
2/* gpu_fp8_api_test: OWN-30B Cut 6 / Cut 5 gate for omega_gpu_fp8_api (FP8 e4m3 block-scaled GEMV).
3 *
4 * ./gpu_fp8_api_test --host-only exhaustive 256-code e4m3 conversion vs the reference decode
5 * (subnormals, both zeros, NaN codes refused), pack refusals,
6 * codegen for every kernel shape (instruction and register budget),
7 * API argument refusals, listing by Omega's own disassembler
8 * ./gpu_fp8_api_test --sim the kernel through tests/bw_warp_sim.h (no chip): one-hot conversion
9 * of every code through the kernel, parity battery vs the double oracle
10 * (both fragment orders bit-identical), grouped experts, and the four
11 * mutants (1 scale dropped, 2 scale block frozen, 3 group table swapped,
12 * host no-fold) which the same check must catch
13 * ./gpu_fp8_api_test --out receipt.json chip gate: parity battery, mutants, grouped experts, then the
14 * bandwidth table (median of --reps calls) at the expert and attention shapes
15 * ./gpu_fp8_api_test --cold-single SPEED-1B: the decode graph's two single projections (qkv 5120 x 2048, o_proj 2048 x 4096),
16 * 16 copies rotated so L2 never holds the launch's weights; same report as --grouped-cold
17 * ./gpu_fp8_api_test --grouped-cold CUT5: the decode graph's two expert launches (gate_up 8 of 128 x 1536 x 2048,
18 * down 8 of 128 x 2048 x 768) with L2 defeated by rotating 16 disjoint expert
19 * sets; parity on every timed launch; mutants 1..4; GB/s and fraction of 237.2
20 * ./gpu_fp8_api_test --grid-ab "0:0,0:0,5:0,16:16" --reps R --seed S
21 * A1: interleaved A/B of the grouped launch's CTAs per group : warps per CTA (0 = the
22 * default) at the 35B expert shapes, o_proj as the must-not-move control; every
23 * list bit-identical to arm 0; one GAB JSON line per GPU-stamped list
24 * knobs: --lane-bytes N --rows N --warps N --cta-budget N --reps N --spin-us N
25 * CUT5 variants: --coal 0|1 (A, coalesced output; default 1, AIEN_OMEGA_FP8_COAL=0 turns it off; --coal-default checks that) --wfirst 0|1 (B, weights before x); FP8_SIM_ALL_ORDERS=1 runs every
26 * simulated kernel in four warp orders (coal kernels always do)
27 * --sched 0|1 (CUT5 kernel schedule) --variant 1|2 --depth N --no-evict --only NAME
28 * --n N --k K: one custom point n x k instead of the battery (with mutants 1, 2, 4), e.g. 128256 x 2560
29 *
30 * Pass rule per point: rc OK, every output within TOL of the double oracle relative to the accumulation
31 * scale (sum of |terms|). Host and simulator passes are never chip results.
32 */
33#include "omega_gpu_fp8_api.h"
34#include "omega_blackwell_codegen_moe2.h"
35#include "omega_blackwell_codegen_moe.h"
36#include "omega_blackwell_matmul.h"
37#include "omega_gpu_session.h"
38#include "omega_gpu_cmdlist.h"
39#include "omega_blackwell_qmd.h" /* OMEGA_BW_QMD_MAX_SHARED_BYTES (deep_default_check) */
40#include "bw_warp_sim.h"
41#include "omega_sm121_disasm.h"
42#include <inttypes.h>
43#include <math.h>
44#include <stdio.h>
45#include <stdlib.h>
46#include <string.h>
47#include <time.h>
48#include <unistd.h>
49#include "test_out_file.h"
50
51#define TOL 1e-5
52static int g_checks, g_failed;
53#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0)
54
55static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; }
56static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); }
57static uint8_t rand_e4m3(uint32_t *s) { uint8_t b = (uint8_t)(lcg(s) >> 24); if (omega_fp8_e4m3_is_nan(b)) b = (uint8_t)(b - 1); return b; }
58static uint16_t bf16_of(float f) { return omega_fp32_to_bf16(f); }
59static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }
60static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; }
61
62/* ------------------------------------------------------------------ data */
63typedef struct {
64 uint32_t experts, n, k;
65 uint8_t *w; uint16_t *s; /* checkpoint layout */
66} Weights;
67static void weights_make(Weights *W, uint32_t experts, uint32_t n, uint32_t k, uint32_t seed) {
68 W->experts = experts; W->n = n; W->k = k;
69 size_t wb = (size_t)experts * n * k, sc = (size_t)experts * (n / 128) * (k / 128);
70 W->w = aligned_alloc(64, (wb + 63) & ~(size_t)63); W->s = malloc(sc * 2);
71 uint32_t st = seed;
72 for (size_t i = 0; i < wb; i++) W->w[i] = rand_e4m3(&st);
73 for (size_t i = 0; i < sc; i++) W->s[i] = bf16_of(frand(&st, 0.001f, 0.1f) * ((lcg(&st) & 1) ? 1.0f : -1.0f));
74}
75static void weights_free(Weights *W) { free(W->w); free(W->s); }
76
77/* max relative error of y (groups x n) against the oracle over the selected experts */
78static double parity(const Weights *W, uint32_t groups, const uint32_t *ids, const float *x, uint32_t x_rows, const float *y, size_t *bad) {
79 double worst = 0.0; size_t nbad = 0;
80 double *ref = malloc(W->n * sizeof *ref), *mag = malloc(W->n * sizeof *mag);
81 for (uint32_t g = 0; g < groups; g++) {
82 const uint8_t *w = W->w + (size_t)ids[g] * W->n * W->k;
83 const uint16_t *s = W->s + (size_t)ids[g] * (W->n / 128) * (W->k / 128);
84 omega_fp8_gemv_oracle(w, s, W->n, W->k, x + (size_t)(x_rows == 1 ? 0 : g) * W->k, ref, mag);
85 for (uint32_t r = 0; r < W->n; r++) {
86 double d = fabs(ref[r] - (double)y[(size_t)g * W->n + r]);
87 double rel = d / (mag[r] > 1e-30 ? mag[r] : 1e-30);
88 if (rel > worst) worst = rel;
89 if (rel >= TOL || isnan(y[(size_t)g * W->n + r])) nbad++;
90 }
91 }
92 free(ref); free(mag);
93 if (bad) *bad = nbad;
94 return worst;
95}
96
97/* ---------------------------------------------- stall checker (CUT5) */
98/* Independent of the generator's pass (a different walk, as tests/gpu_tern_api_test.c does): for every fixed-latency
99 * write, scan forward summing stalls; any instruction that reads or overwrites one of its registers, any control
100 * instruction and any branch target reached before OMEGA_FP8_FIXED_LAT cycles is a violation. */
101static int fp8_chk_fixed(BlackwellIROpcode op) {
102 return op == BW_IR_IMAD || op == BW_IR_IMAD_WIDE || op == BW_IR_SHF_R || op == BW_IR_LOP3_AND || op == BW_IR_LOP3_XOR ||
103 op == BW_IR_MOV_IMM || op == BW_IR_MOV_RZ || op == BW_IR_FFMA || op == BW_IR_FADD;
104}
105static int fp8_chk_overlap(const BlackwellIRProgram *p, int a, int b) {
106 if (a < 0 || b < 0) return 0;
107 const int pa = p->regalloc.vreg_to_phys[a], pb = p->regalloc.vreg_to_phys[b];
108 if (pa < 0 || pb < 0) return 0;
109 const int na = (int)(p->regalloc.intervals[a].bundle_size ? p->regalloc.intervals[a].bundle_size : 1u);
110 const int nb = (int)(p->regalloc.intervals[b].bundle_size ? p->regalloc.intervals[b].bundle_size : 1u);
111 return pa < pb + nb && pb < pa + na;
112}
113/* CUT5 A/B structure counters (independent of the generator): instructions of one opcode, and global-load batches. A batch
114 * opens at a global load issued while no batch is open; any instruction whose wait mask holds the load scoreboard (bit 0 of
115 * the wait field, SB_GPR in the generator) closes it. One batch = one memory round trip the warp waits for. */
116static int fp8_count_op(const BlackwellIRProgram *p, BlackwellIROpcode op) { int n = 0; for (size_t i = 0; i < p->count; i++) n += p->insns[i].op == op; return n; }
117static int fp8_load_batches(const BlackwellIRProgram *p) {
118 int n = 0, open = 0;
119 for (size_t i = 0; i < p->count; i++) {
120 const BlackwellIRInsn *in = &p->insns[i];
121 if ((in->control >> 20) & 1u) open = 0;
122 const int gl = in->op == BW_IR_LDG_E || in->op == BW_IR_LDG_E_64 || in->op == BW_IR_LDG_E_128;
123 if (gl && !open) { n++; open = 1; }
124 }
125 return n;
126}
127static long fp8_stall_violations(const BlackwellIRProgram *p, uint64_t *cycles) {
128 static uint8_t tgt[BW_MAX_IR_INSNS + 1];
129 memset(tgt, 0, sizeof tgt);
130 long bad = 0; uint64_t cyc = 0;
131 for (size_t i = 0; i < p->count; i++) {
132 const BlackwellIRInsn *in = &p->insns[i];
133 cyc += (in->control >> 9) & 0xfu;
134 if (in->op == BW_IR_BRA || in->op == BW_IR_BSSY) { long t = (long)i + (long)(int32_t)in->imm; if (t >= 0 && t <= (long)p->count) tgt[t] = 1; }
135 }
136 for (size_t i = 0; i < p->count; i++) {
137 const BlackwellIRInsn *in = &p->insns[i];
138 if (!fp8_chk_fixed(in->op) || in->dst_vreg < 0) continue;
139 uint32_t dist = 0;
140 for (size_t j = i + 1; j < p->count; j++) {
141 dist += (p->insns[j - 1].control >> 9) & 0xfu;
142 if (dist >= OMEGA_FP8_FIXED_LAT) break;
143 const BlackwellIRInsn *u = &p->insns[j];
144 const BlackwellIROpcode o = u->op;
145 if (o == BW_IR_BRA || o == BW_IR_EXIT || o == BW_IR_BSSY || o == BW_IR_BSYNC || o == BW_IR_BAR_SYNC || tgt[j]) { bad++; break; }
146 if (fp8_chk_overlap(p, in->dst_vreg, u->dst_vreg) || fp8_chk_overlap(p, in->dst_vreg, u->src1_vreg) ||
147 fp8_chk_overlap(p, in->dst_vreg, u->src2_vreg) || fp8_chk_overlap(p, in->dst_vreg, u->src3_vreg)) { bad++; break; }
148 }
149 }
150 if (cycles) *cycles = cyc;
151 return bad;
152}
153
154/* ------------------------------------------------------------- host-only */
155static int sm121dis_check_v(int variant, const OmegaFp8GemvSpec *spec, const char *name);
156static int sm121dis_check(const OmegaFp8GemvSpec *spec, const char *name) { return sm121dis_check_v(1, spec, name); }
157static int sm121dis_check_v(int variant, const OmegaFp8GemvSpec *spec, const char *name) {
158 OmegaBlackwellKernel k; memset(&k, 0, sizeof k);
159 if ((variant == 2 ? omega_blackwell_codegen_fp8_gemv2(spec, &k) : omega_blackwell_codegen_fp8_gemv(spec, &k)) != 0) return -1;
160 char lst[96];
161 snprintf(lst, sizeof lst, "/tmp/omega_fp8_%s_%d.sass.XXXXXX", name, (int)getpid());
162 int fd = mkstemp(lst); /* private, unique listing; read back the same descriptor */
163 FILE *f = fd >= 0 ? fdopen(fd, "w+") : NULL;
164 if (!f) { if (fd >= 0) close(fd); omega_blackwell_kernel_free(&k); return -1; }
165 int rc = omega_sm121_listing(k.code, k.code_size, f);
166 omega_blackwell_kernel_free(&k);
167 static const char *const must[] = { "LDG.E.128", "FFMA", "SHFL.DOWN", "BSSY", "BSYNC", "STG.E", "LOP3.LUT", "IMAD" };
168 if (fflush(f) != 0 || fseek(f, 0, SEEK_SET) != 0) { fclose(f); return -1; }
169 FILE *l = f;
170 char line[512]; int seen[8] = {0}; int bad = 0, insns = 0;
171 while (fgets(line, sizeof line, l)) {
172 if (!strstr(line, "/*") || !strstr(line, "*/")) continue; /* every address line */
173 insns++;
174 if (strstr(line, "?") || strstr(line, "error")) bad++;
175 if (strstr(line, ".FTZ")) { printf(" %s: flush-to-zero instruction: %s", name, line); bad++; } /* e4m3 subnormals travel as f32 subnormals */
176 for (int i = 0; i < 8; i++) if (strstr(line, must[i])) seen[i] = 1;
177 }
178 if (ferror(l)) rc = -1;
179 if (fclose(l) != 0) rc = -1;
180 int miss = 0;
181 for (int i = 0; i < 8; i++) if (!seen[i]) { printf(" %s: sm121dis listing lacks %s\n", name, must[i]); miss++; }
182 printf("sm121dis %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst);
183 return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1;
184}
185
186/* Variant A default (SPEED-A, 2026-10-17): coal is ON unless AIEN_OMEGA_FP8_COAL=0 (or set_coal(0)), and coal 0 gives back
187 * the earlier kernel (one STG per row, no BAR.SYNC, no shared slots) at the decode graph's two grouped expert shapes and the
188 * single-projection o_proj shape. make test-gpu-fp8 runs this once with the env unset and once with AIEN_OMEGA_FP8_COAL=0. */
189static int g_coal_arg; /* --coal given: the env default is not what is being tested */
190static void coal_default_check(void) {
191 const char *e = getenv("AIEN_OMEGA_FP8_COAL");
192 const int want = (e && e[0] == '0' && e[1] == 0) ? 0 : 1;
193 CHECK(omega_gpu_fp8_coal() == want, "coal default %d with AIEN_OMEGA_FP8_COAL=%s (want %d)", omega_gpu_fp8_coal(), e ? e : "(unset)", want);
194 static const struct { uint32_t k, n, groups; const char *name; } sh[] = {
195 { 2048, 1536, 8, "gate_up 8 x 1536 x 2048" }, { 768, 2048, 8, "down 8 x 2048 x 768" }, { 4096, 2048, 1, "o_proj 2048 x 4096" } };
196 for (int pass = 0; pass < 3; pass++) {
197 const int on = pass == 0 ? want : pass == 1 ? 0 : 1;
198 if (pass) omega_gpu_fp8_set_coal(on);
199 for (size_t q = 0; q < sizeof sh / sizeof sh[0]; q++) {
200 OmegaFp8GemvSpec sp; omega_gpu_fp8_spec_for(sh[q].k, sh[q].n, sh[q].groups, &sp);
201 const int fits = sp.warps * sp.rows <= 32u;
202 static BlackwellIRProgram p;
203 const int rc = omega_blackwell_codegen_fp8_gemv_prog(&sp, &p);
204 const int coal = on && fits, bar = rc == 0 ? fp8_count_op(&p, BW_IR_BAR_SYNC) : -1, stg = rc == 0 ? fp8_count_op(&p, BW_IR_STG_E) : -1;
205 CHECK(rc == 0 && sp.coal == (uint32_t)coal && stg == 1 && (sp.depth ? 1 : bar == coal) && (omega_fp8_gemv_shared_bytes(&sp) != 0) == (coal || sp.depth != 0),
206 "%s coal %d (pass %d, warps %u rows %u depth %u): spec.coal %u, STG %d, BAR.SYNC %d, shared %u", sh[q].name, on, pass, sp.warps, sp.rows, sp.depth, sp.coal, stg, bar, omega_fp8_gemv_shared_bytes(&sp));
207 if (pass == 0) printf("coal default %d: %s warps %u rows %u depth %u -> spec.coal %u, STG %d, BAR.SYNC %d\n", want, sh[q].name, sp.warps, sp.rows, sp.depth, sp.coal, stg, bar);
208 }
209 }
210 omega_gpu_fp8_set_coal(want);
211}
212
213/* Deep-kernel default (SPEED-1B, 2026-10-17): the automatic spec for the decode graph's qkv (5120 x 2048, 10.5 MB) is the deep
214 * kernel (depth KS = 4) unless AIEN_OMEGA_FP8_DEEP=0 (or set_deep(0)); o_proj (2048 x 4096) stays classic because its deep x stage
215 * would exceed the 16 KiB launch-descriptor shared limit; grouped expert launches stay classic. make test-gpu-fp8 runs this once
216 * with the env unset and once with AIEN_OMEGA_FP8_DEEP=0. */
217static void deep_default_check(void) {
218 const char *e = getenv("AIEN_OMEGA_FP8_DEEP");
219 const int want = (e && e[0] == '0' && e[1] == 0) ? 0 : 1;
220 CHECK(omega_gpu_fp8_deep() == want, "deep default %d with AIEN_OMEGA_FP8_DEEP=%s (want %d)", omega_gpu_fp8_deep(), e ? e : "(unset)", want);
221 for (int pass = 0; pass < 3; pass++) {
222 const int on = pass == 0 ? want : pass == 1 ? 0 : 1;
223 if (pass) omega_gpu_fp8_set_deep(on);
224 OmegaFp8GemvSpec q, o, gu; omega_gpu_fp8_spec_for(2048, 5120, 1, &q); omega_gpu_fp8_spec_for(4096, 2048, 1, &o); omega_gpu_fp8_spec_for(2048, 1536, 8, &gu);
225 CHECK(q.depth == (on ? 4u : 0u) && o.depth == 0 && gu.depth == 0, "deep %d (pass %d): qkv depth %u (want %u), o_proj depth %u (want 0), gate_up depth %u (want 0)", on, pass, q.depth, on ? 4u : 0u, o.depth, gu.depth);
226 OmegaFp8GemvSpec od = o; od.depth = 4096u / (32u * od.lane_bytes); od.mutant = 0;
227 CHECK(omega_fp8_gemv_shared_bytes(&od) > OMEGA_GPU_FP8_DEEP_MAX_SHARED_BYTES, "o_proj deep x stage %u bytes must exceed the %u-byte measured deep bound (why it stays classic)", omega_fp8_gemv_shared_bytes(&od), OMEGA_GPU_FP8_DEEP_MAX_SHARED_BYTES);
228 if (on) CHECK(omega_fp8_gemv_shared_bytes(&q) != 0 && omega_fp8_gemv_shared_bytes(&q) <= OMEGA_GPU_FP8_DEEP_MAX_SHARED_BYTES, "qkv deep shared %u bytes within the measured deep bound", omega_fp8_gemv_shared_bytes(&q));
229 if (pass == 0) printf("deep default %d: qkv 5120x2048 depth %u (coal %u, shared %u), o_proj 2048x4096 depth %u, gate_up 8x1536x2048 depth %u\n", want, q.depth, q.coal, omega_fp8_gemv_shared_bytes(&q), o.depth, gu.depth);
230 }
231 /* The choice runs on every launch and every graph record (48 qkv records per token). SPEED-1B graph A/B: an unremembered
232 * register check (full codegen per call) cost 853..1172 us of host record time per token. Bound: 4800 calls (100 tokens of
233 * qkv records) under 20 ms in total (< ~4 us per call); the codegen path is ~17 us per call. */
234 {
235 omega_gpu_fp8_set_deep(1);
236 OmegaFp8GemvSpec q; omega_gpu_fp8_spec_for(2048, 5120, 1, &q); /* warm */
237 struct timespec t0, t1; clock_gettime(CLOCK_MONOTONIC, &t0);
238 uint32_t dsum = 0;
239 for (int i = 0; i < 4800; i++) { omega_gpu_fp8_spec_for(2048, 5120, 1, &q); dsum += q.depth; }
240 clock_gettime(CLOCK_MONOTONIC, &t1);
241 const double ms = (double)(t1.tv_sec - t0.tv_sec) * 1e3 + (double)(t1.tv_nsec - t0.tv_nsec) / 1e6;
242 CHECK(dsum == 4800u * 4u && ms < 20.0, "4800 qkv spec_for calls (deep on): %.2f ms, depth sum %u (want < 20 ms, %u)", ms, dsum, 4800u * 4u);
243 printf("deep default: 4800 qkv spec_for calls %.3f ms\n", ms);
244 }
245 omega_gpu_fp8_set_deep(want);
246}
247
248/* qwen38/decode-speed: the host quantiser (FP8 lm_head). Every e4m3 rounding against a brute-force nearest-code search
249 * (ties to the even code, saturation at 448, never 0x7F), then a block round trip against the upload format's maths. */
250static double e4m3_val(unsigned c) { unsigned e = (c >> 3) & 15u, m = c & 7u; double v = e ? (1.0 + m / 8.0) * pow(2.0, (int)e - 7) : m / 8.0 * pow(2.0, -6); return (c & 0x80u) ? -v : v; }
251static unsigned e4m3_brute(float v) {
252 double a = fabs((double)v); unsigned best = 0; double bd = 1e300;
253 if (a >= 448.0) return (v < 0 ? 0x80u : 0u) | 0x7Eu;
254 for (unsigned c = 0; c <= 0x7Eu; c++) { double d = fabs(e4m3_val(c) - a); if (d < bd || (d == bd && !(c & 1u))) { bd = d; best = c; } }
255 return ((v < 0 || (v == 0 && signbit(v))) ? 0x80u : 0u) | best;
256}
257static void e4m3_quant_check(void) {
258 int bad = 0, nan = 0; uint32_t s = 12345u;
259 for (unsigned c = 0; c <= 0x7Eu; c++) { /* every code, the midpoints to both neighbours, and their negatives */
260 float pts[3] = { (float)e4m3_val(c), c ? (float)((e4m3_val(c) + e4m3_val(c - 1)) / 2) : 0.0f, c < 0x7E ? (float)((e4m3_val(c) + e4m3_val(c + 1)) / 2) : 460.0f };
261 for (int i = 0; i < 3; i++) for (int sg = 0; sg < 2; sg++) { float v = sg ? -pts[i] : pts[i]; unsigned q = omega_gpu_fp8_e4m3_rne(v); if (q != e4m3_brute(v)) bad++; if ((q & 0x7Fu) == 0x7Fu) nan++; }
262 }
263 for (int i = 0; i < 200000; i++) { /* random magnitudes over 2^-12 .. 2^10 */
264 s = s * 1664525u + 1013904223u; float m = (float)(s >> 8) / 16777216.0f; s = s * 1664525u + 1013904223u;
265 float v = (1.0f + m) * ldexpf(1.0f, (int)(s >> 27) - 12 - (int)((s >> 20) & 3u)); if (s & 1u) v = -v;
266 unsigned q = omega_gpu_fp8_e4m3_rne(v); if (q != e4m3_brute(v)) bad++; if ((q & 0x7Fu) == 0x7Fu) nan++;
267 }
268 CHECK(bad == 0 && nan == 0, "e4m3 rounding: %d codes differ from the brute-force nearest-even, %d NaN codes", bad, nan);
269 CHECK(omega_gpu_fp8_e4m3_rne(1e30f) == 0x7Eu && omega_gpu_fp8_e4m3_rne(-1e30f) == 0xFEu && omega_gpu_fp8_e4m3_rne(0.0f) == 0u, "e4m3 saturation and zero");
270 /* block round trip: 256 x 384 bf16 with a zero block, w8 * scale within half an e4m3 step of w, scale >= amax / 448 */
271 enum { N = 256, K = 384 }; static uint16_t w[N * K], sc[(N / 128) * (K / 128)]; static uint8_t w8[N * K];
272 for (int i = 0; i < N * K; i++) { s = s * 1664525u + 1013904223u; float f = ((float)(s >> 8) / 16777216.0f - 0.5f) * ((i / K) < 128 ? 0.02f : 3.0f); uint32_t b; memcpy(&b, &f, 4); w[i] = (uint16_t)(b >> 16); }
273 for (int r = 0; r < 128; r++) for (int c = 128; c < 256; c++) w[r * K + c] = 0;
274 CHECK(omega_gpu_fp8_quantize_bf16(N, K, w, w8, sc) == OMEGA_GPU_FP8_OK, "quantize 256 x 384");
275 int far = 0, nanq = 0; double worst = 0;
276 for (int r = 0; r < N; r++) for (int c = 0; c < K; c++) {
277 uint32_t b = (uint32_t)sc[(r / 128) * (K / 128) + c / 128] << 16; float scf; memcpy(&scf, &b, 4);
278 uint32_t wb = (uint32_t)w[r * K + c] << 16; float wf; memcpy(&wf, &wb, 4);
279 double back = e4m3_val(w8[r * K + c]) * scf, err = fabs(back - wf), rel = err / fabs((double)wf ? wf : 1);
280 if ((w8[r * K + c] & 0x7Fu) == 0x7Fu) nanq++;
281 if (w8[r * K + c] != e4m3_brute(wf / scf)) far++;
282 if (wf != 0 && fabs(wf) > 0.1 * scf && rel > worst) worst = rel;
283 }
284 CHECK(far == 0 && nanq == 0 && worst <= 0.0625 + 1e-9, "quantize round trip: %d codes off the nearest, %d NaN, worst rel %.4f (<= 1/16)", far, nanq, worst);
285 CHECK(sc[1] == 0x3F80u, "all-zero block gets scale 1 (0x%04x)", sc[1]);
286 uint16_t inf[128 * 128] = { 0 }; inf[77] = 0x7F80u; uint8_t o8[128 * 128]; uint16_t os[1];
287 CHECK(omega_gpu_fp8_quantize_bf16(128, 128, inf, o8, os) == OMEGA_GPU_FP8_BAD_ARGS, "quantize refuses an inf weight");
288}
289
290/* qwen38/decode-speed: the big-k rule's choices (chip parity of these specs: fp8par1 in the speed handoff) */
291static void bigk_check(void) {
292 static const struct { uint32_t n, k, warps, depth; } want[] = { { 34816, 5120, 16, 5 }, { 16384, 5120, 16, 5 }, { 14336, 5120, 16, 5 },
293 { 5120, 6144, 16, 6 }, { 5120, 17408, 16, 0 }, { 2048, 4096, 8, 0 }, { 5120, 2048, 8, 4 } };
294 for (int on = 0; on < 2; on++) {
295 omega_gpu_fp8_set_bigk(on);
296 for (size_t i = 0; i < sizeof want / sizeof want[0]; i++) {
297 OmegaFp8GemvSpec sp; omega_gpu_fp8_spec_for(want[i].k, want[i].n, 1, &sp);
298 const int big = on && want[i].k > 4096u;
299 const uint32_t ww = big ? want[i].warps : 8u, wd = big ? want[i].depth : (want[i].k == 2048u ? 4u : 0u);
300 CHECK(sp.warps == ww && sp.depth == wd && sp.coal == 1u, "bigk %d: %ux%u warps %u depth %u coal %u (want %u, %u, 1)", on, want[i].n, want[i].k, sp.warps, sp.depth, sp.coal, ww, wd);
301 }
302 OmegaFp8GemvSpec g8; omega_gpu_fp8_spec_for(5120, 34816, 8, &g8);
303 CHECK(g8.warps == 32u && g8.depth == 0u, "bigk %d: grouped launches keep 32 warps, classic (warps %u depth %u)", on, g8.warps, g8.depth);
304 }
305 omega_gpu_fp8_set_bigk(1); /* the default */
306}
307
308static void host_only(void) {
309 e4m3_quant_check();
310 bigk_check();
311 if (!g_coal_arg) coal_default_check();
312 deep_default_check();
313 /* 1. exhaustive conversion: kernel bits * 2^120 == reference, bit for bit, for every non-NaN code;
314 * sign of zero preserved; NaN codes are exactly 0x7f and 0xff and are refused by the scan */
315 int exact = 0, nan_codes = 0, zero_sign_ok = 0, f32_subnormal = 0;
316 for (int b = 0; b < 256; b++) {
317 float ref = omega_fp8_e4m3_ref((uint8_t)b);
318 uint32_t kb = omega_fp8_e4m3_kernel_bits((uint8_t)b);
319 float kf; memcpy(&kf, &kb, 4);
320 /* the kernel-side f32 is subnormal exactly for the e4m3 subnormal codes (exponent field 0, mantissa != 0):
321 * the chip must not flush them (no .FTZ instruction in the listing, chip one-hot test) */
322 if ((kb & 0x7f800000u) == 0 && (kb & 0x007fffffu) != 0) { f32_subnormal++; CHECK((b & 0x78) == 0 && (b & 7) != 0, "code 0x%02x maps to an f32 subnormal but is not an e4m3 subnormal", b); }
323 else CHECK((b & 0x78) != 0 || (b & 7) == 0, "e4m3 subnormal code 0x%02x maps to a normal f32", b);
324 float kv = ldexpf(kf, 120); /* exact: a power-of-two scaling (host, no flush to zero) */
325 if (isnan(ref)) { nan_codes++; CHECK(omega_fp8_e4m3_is_nan((uint8_t)b), "code 0x%02x is NaN in the reference and must be flagged", b); continue; }
326 CHECK(!omega_fp8_e4m3_is_nan((uint8_t)b), "code 0x%02x is finite in the reference and must not be flagged", b);
327 uint32_t rb, vb; memcpy(&rb, &ref, 4); memcpy(&vb, &kv, 4);
328 if (rb == vb) exact++;
329 CHECK(rb == vb, "code 0x%02x: kernel conversion %a (bits %08x) != reference %a (bits %08x)", b, kv, vb, ref, rb);
330 if (ref == 0.0f) { if (signbit(ref) == signbit(kv)) zero_sign_ok++; }
331 /* the fold is exact as two steps too (x * 2^64 then * 2^56) */
332 CHECK(ldexpf(ldexpf(kf, OMEGA_FP8_X_EXP), OMEGA_FP8_SCALE_EXP) == ref, "code 0x%02x: split fold not exact", b);
333 }
334 CHECK(exact == 254 && nan_codes == 2 && zero_sign_ok == 2, "conversion: %d exact, %d NaN codes, %d zero signs (want 254, 2, 2)", exact, nan_codes, zero_sign_ok);
335 CHECK(f32_subnormal == 14, "f32-subnormal kernel values: %d (want 14: +-0x01..0x07)", f32_subnormal);
336 printf("conversion: %d/256 exact, %d NaN codes refused, %d codes travel as f32 subnormals (2^-129 .. 7 * 2^-129): the chip must not flush them\n", exact, nan_codes, f32_subnormal);
337 /* subnormal spot values from the e4m3 definition */
338 CHECK(omega_fp8_e4m3_ref(0x01) == ldexpf(1.0f, -9) && omega_fp8_e4m3_ref(0x07) == 7.0f * ldexpf(1.0f, -9), "subnormal spot values");
339 CHECK(omega_fp8_e4m3_ref(0x7e) == 448.0f && omega_fp8_e4m3_ref(0xfe) == -448.0f && omega_fp8_e4m3_ref(0x38) == 1.0f, "normal spot values");
340 /* conversion mutant: skipping the fold is caught by the same comparison */
341 { float kf; uint32_t kb = omega_fp8_e4m3_kernel_bits(0x38); memcpy(&kf, &kb, 4); CHECK(kf != 1.0f, "fold mutant: unfolded bits must not equal the value"); }
342
343 /* 2. pack refusals */
344 { uint8_t w[8] = { 0x38, 0x7f, 0x00, 0xff, 1, 2, 3, 4 }; size_t first = 99;
345 CHECK(omega_fp8_pack_scan_nan(w, 8, &first) == 2 && first == 1, "NaN scan finds both codes, first at 1");
346 CHECK(omega_fp8_pack_scan_nan(w, 1, &first) == 0, "NaN scan clean prefix"); }
347 { uint16_t s[3] = { bf16_of(0.5f), 0x7fc0 /* NaN */, bf16_of(1.0f) }; float o[3];
348 CHECK(omega_fp8_pack_scales(s, 1, o, 0) == 0 && o[0] == ldexpf(0.5f, OMEGA_FP8_SCALE_EXP), "scale fold exact");
349 CHECK(omega_fp8_pack_scales(s, 3, o, 0) != 0, "NaN scale refused");
350 s[1] = 0x7f80; CHECK(omega_fp8_pack_scales(s, 3, o, 0) != 0, "inf scale refused");
351 s[1] = bf16_of(3.0e38f); CHECK(omega_fp8_pack_scales(s, 3, o, 0) != 0, "fold overflow refused");
352 CHECK(omega_fp8_pack_scales(s, 1, o, 1) == 0 && o[0] == 0.5f, "no-fold mutant pack"); }
353 { float x[4] = { 1.0f, -2.0f, 0.5f, 0.0f }, o[4]; omega_fp8_pack_x_f32(x, 4, o);
354 CHECK(o[0] == ldexpf(1.0f, 64) && o[1] == ldexpf(-2.0f, 64) && o[3] == 0.0f, "x fold exact"); }
355
356 /* 3. codegen: every shape builds inside the budgets; refusals */
357 static const uint32_t ks[] = { 128, 256, 768, 2048, 4096, 16384, 17408, 32768 };
358 static const uint32_t lbs[] = { 8, 16 }, rows[] = { 1, 2, 4, 8 };
359 uint32_t worst_insns = 0, worst_gprs = 0; int built = 0;
360 for (size_t a = 0; a < sizeof ks / sizeof ks[0]; a++) for (size_t b = 0; b < 2; b++) for (size_t c = 0; c < 4; c++) for (int m = 0; m <= 3; m++) for (int deep = 0; deep < 2; deep++) {
361 OmegaFp8GemvSpec sp = { .k = ks[a], .lane_bytes = lbs[b], .rows = rows[c], .warps = 8, .mutant = m };
362 uint32_t ni, ng;
363 if (ks[a] % (32 * lbs[b])) { CHECK(omega_fp8_gemv_prog_stats(&sp, &ni, &ng) != 0, "k=%u lb=%u must be refused", ks[a], lbs[b]); continue; }
364 if (deep) { sp.depth = ks[a] / (32 * lbs[b]); if (sp.depth * sp.rows * lbs[b] > 128 || ks[a] > 4096) { CHECK(omega_fp8_gemv_prog_stats(&sp, &ni, &ng) != 0, "deep k=%u lb=%u rows=%u must be refused", ks[a], lbs[b], rows[c]); continue; } }
365 int rc = omega_fp8_gemv_prog_stats(&sp, &ni, &ng);
366 CHECK(rc == 0, "codegen k=%u lb=%u rows=%u mutant=%d deep=%d", ks[a], lbs[b], rows[c], m, deep);
367 if (rc == 0) { built++; if (ni > worst_insns) worst_insns = ni; if (ng > worst_gprs) worst_gprs = ng; }
368 }
369 printf("codegen: %d kernels built, largest %u IR instructions, peak %u GPRs\n", built, worst_insns, worst_gprs);
370 CHECK(worst_insns <= BW_MAX_IR_INSNS && worst_gprs <= 128, "budgets");
371 { OmegaFp8GemvSpec bad = { .k = 192, .lane_bytes = 8, .rows = 1, .warps = 1 }; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "k not a multiple of 128 refused");
372 bad.k = 256; bad.lane_bytes = 4; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "lane_bytes 4 refused (LDG.E has no immediate offset)"); bad.lane_bytes = 8;
373 bad.k = 2048; bad.rows = 3; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "rows 3 refused");
374 bad.rows = 8; bad.warps = 33; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "warps 33 refused");
375 bad.warps = 8; bad.lane_bytes = 32; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "lane_bytes 32 refused");
376 bad.lane_bytes = 16; bad.k = OMEGA_FP8_MAX_K + 512u; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "k past the limit refused"); }
377 /* Register file (chip-found 2026-10-13): 32 * warps * declared registers must be <= 65536; the API refuses the launch.
378 * The deep k=2048 kernel at 32 warps (72 declared x 1024 threads = 73728) faulted on the chip with Xid 13. */
379 { OmegaFp8GemvSpec deep = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 32, .depth = 4 }; uint32_t gp = 0;
380 CHECK(omega_fp8_gemv_prog_stats(&deep, NULL, &gp) == 0, "deep4 k2048 encodes");
381 uint32_t decl = ((gp + 1u + 7u) / 8u) * 8u;
382 CHECK(32u * 32u * decl > 65536u, "deep4 k2048 at 32 warps needs %u declared registers x 1024 threads: over the 65536 file", decl);
383 uint32_t de = 0; int rf = omega_gpu_fp8_kernel_fits(&deep, &de);
384 CHECK(rf == OMEGA_GPU_FP8_TOO_LARGE && de == decl, "API refuses the register-file overflow (rc %d, declared %u): %s", rf, de, omega_gpu_fp8_last_error());
385 deep.warps = 16; CHECK(omega_gpu_fp8_kernel_fits(&deep, NULL) == OMEGA_GPU_FP8_OK, "the same kernel at 16 warps fits");
386 deep.depth = 0; deep.warps = 32; CHECK(omega_gpu_fp8_kernel_fits(&deep, NULL) == OMEGA_GPU_FP8_OK, "the classic kernel at 32 warps fits");
387 deep.depth = 4; CHECK(omega_gpu_fp8_depth_for(&deep, 2048, 1) == 0, "automatic depth falls back to classic when deep would overflow the register file"); }
388
389 /* 4. API refusals that need no device */
390 { OmegaGpuFp8Tensor *t = NULL; uint8_t w[128 * 128]; uint16_t s[1] = { bf16_of(1.0f) }; memset(w, 0x38, sizeof w);
391 CHECK(omega_gpu_fp8_tensor_upload(1, 128, 128, NULL, s, &t) == OMEGA_GPU_FP8_BAD_ARGS, "NULL w refused");
392 CHECK(omega_gpu_fp8_tensor_upload(1, 100, 128, w, s, &t) == OMEGA_GPU_FP8_BAD_ARGS, "n not a multiple of 128 refused");
393 CHECK(omega_gpu_fp8_tensor_upload(1, 128, OMEGA_FP8_MAX_K + 256u, w, s, &t) == OMEGA_GPU_FP8_TOO_LARGE, "k past the limit refused");
394 w[77] = 0xff; CHECK(omega_gpu_fp8_tensor_upload(1, 128, 128, w, s, &t) == OMEGA_GPU_FP8_NAN_WEIGHT && t == NULL, "NaN weight refused before any device work");
395 CHECK(strstr(omega_gpu_fp8_last_error(), "byte 77") != NULL, "error names the byte (%s)", omega_gpu_fp8_last_error());
396 float y[8]; CHECK(omega_gpu_fp8_gemv_f32(NULL, 0, y, y, NULL) == OMEGA_GPU_FP8_BAD_ARGS, "NULL tensor refused"); }
397
398 /* 5. sm121dis listing of the production shapes */
399 { OmegaFp8GemvSpec a = { .k = 2048, .lane_bytes = 16, .rows = 8, .warps = 8 }, b = { .k = 768, .lane_bytes = 8, .rows = 2, .warps = 8 };
400 CHECK(sm121dis_check(&a, "k2048_lb16_r8") == 0, "sm121dis listing k=2048");
401 OmegaFp8GemvSpec d = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 8, .depth = 4 };
402 CHECK(sm121dis_check(&d, "k2048_lb16_r1_deep4") == 0, "sm121dis listing deep k=2048");
403 CHECK(sm121dis_check(&b, "k768_lb8_r2") == 0, "sm121dis listing k=768"); }
404
405 /* 6. variant 2 (W-L2c, omega_blackwell_codegen_moe2.c): every OWN-30B width builds inside the budgets at 16 warps,
406 * the production shapes fit the register file, the whole-row-group rule refuses what it must */
407 {
408 static const uint32_t k2[] = { 768, 2048, 4096 }, r2[] = { 1, 2, 4 };
409 uint32_t worst_i = 0, worst_g = 0; int built2 = 0;
410 for (size_t a = 0; a < 3; a++) for (size_t c = 0; c < 3; c++) for (int m = 0; m <= 3; m++) {
411 OmegaFp8GemvSpec sp = { .k = k2[a], .lane_bytes = k2[a] % 512u == 0 ? 16u : 8u, .rows = r2[c], .warps = 16, .mutant = m };
412 uint32_t ks = sp.k / (32u * sp.lane_bytes), ni = 0, ng = 0;
413 int rc = omega_fp8_gemv2_prog_stats(&sp, &ni, &ng);
414 if (sp.rows * ks * sp.lane_bytes > 128u) { CHECK(rc != 0, "v2 k=%u rows=%u must be refused (row group past 128 bytes per lane)", sp.k, sp.rows); continue; }
415 CHECK(rc == 0 && ni <= BW_MAX_IR_INSNS, "v2 codegen k=%u lb=%u rows=%u mutant=%d: rc %d, %u insns", sp.k, sp.lane_bytes, sp.rows, m, rc, ni);
416 if (rc == 0) { built2++; if (ni > worst_i) worst_i = ni; if (ng > worst_g) worst_g = ng; if (m == 0) printf("v2 codegen k=%u lb=%u rows=%u: %u insns, peak %u GPRs, declared %u\n", sp.k, sp.lane_bytes, sp.rows, ni, ng, omega_bw_gpr_declared(ng)); }
417 }
418 printf("v2 codegen: %d kernels built, largest %u IR instructions, peak %u GPRs\n", built2, worst_i, worst_g);
419 /* the production shapes at the variant's default (16 warps, 1 row) must fit the 65536-register file */
420 omega_gpu_fp8_set_variant(2);
421 static const uint32_t kp[] = { 768, 2048, 4096 };
422 for (size_t a = 0; a < 3; a++) {
423 OmegaFp8GemvSpec sp = { .k = kp[a], .lane_bytes = kp[a] % 512u == 0 ? 16u : 8u, .rows = 1, .warps = OMEGA_GPU_FP8_V2_WARPS };
424 uint32_t decl = 0; int rf = omega_gpu_fp8_kernel_fits(&sp, &decl);
425 CHECK(rf == OMEGA_GPU_FP8_OK && 32u * sp.warps * decl <= 65536u, "v2 k=%u at %u warps fits the register file (rc %d, declared %u)", sp.k, sp.warps, rf, decl);
426 printf("v2 k=%u rows=1 warps=%u: declared %u registers, %u per SM at one CTA\n", sp.k, sp.warps, decl, 32u * sp.warps * decl);
427 }
428 omega_gpu_fp8_set_variant(1);
429 { OmegaFp8GemvSpec bad = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 2 }; CHECK(omega_fp8_gemv2_prog_stats(&bad, NULL, NULL) != 0, "v2 k=2048 at 2 warps refused (staging rounds)");
430 bad.warps = 16; bad.k = 16384; CHECK(omega_fp8_gemv2_prog_stats(&bad, NULL, NULL) != 0, "v2 k=16384 refused (row past 128 bytes per lane)");
431 bad.k = 2048; bad.lane_bytes = 8; bad.rows = 2; CHECK(omega_fp8_gemv2_prog_stats(&bad, NULL, NULL) == 0, "v2 k=2048 lb8 rows=2 (128 bytes per lane) builds"); }
432 OmegaFp8GemvSpec v = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 16 };
433 CHECK(sm121dis_check_v(2, &v, "v2_k2048_lb16_r1_w16") == 0, "sm121dis listing v2 k=2048");
434 }
435
436 /* 7. sched 1 (CUT5): pipelined decode + dependency stall pass. Every battery shape builds; the two grouped expert
437 * shapes fit the register file at 32 warps; an independent walk finds no user closer than OMEGA_FP8_FIXED_LAT
438 * cycles to a fixed-latency write; shortening one binding stall must be caught (the checker can say no); the
439 * sched 0 programs pass the same checker (they stall 6 everywhere) */
440 {
441 int built1 = 0; long viol_all = 0;
442 for (size_t a = 0; a < sizeof ks / sizeof ks[0]; a++) for (size_t b = 0; b < 2; b++) for (size_t c = 0; c < 4; c++) for (int m = 0; m <= 3; m++) for (int deep = 0; deep < 2; deep++) {
443 OmegaFp8GemvSpec sp = { .k = ks[a], .lane_bytes = lbs[b], .rows = rows[c], .warps = 8, .mutant = m, .sched = 1 };
444 if (ks[a] % (32 * lbs[b])) continue;
445 if (deep) { sp.depth = ks[a] / (32 * lbs[b]); if (sp.depth * sp.rows * lbs[b] > 128 || ks[a] > 4096) continue; }
446 static BlackwellIRProgram cp;
447 int rc = omega_blackwell_codegen_fp8_gemv_prog(&sp, &cp);
448 CHECK(rc == 0 && cp.count <= BW_MAX_IR_INSNS, "sched1 codegen k=%u lb=%u rows=%u mutant=%d deep=%d", sp.k, sp.lane_bytes, sp.rows, m, deep);
449 if (rc != 0) continue;
450 built1++;
451 long v = fp8_stall_violations(&cp, NULL);
452 viol_all += v;
453 CHECK(v == 0, "sched1 stall distances k=%u lb=%u rows=%u mutant=%d deep=%d: %ld users closer than %u cycles", sp.k, sp.lane_bytes, sp.rows, m, deep, v, OMEGA_FP8_FIXED_LAT);
454 }
455 printf("sched1 codegen: %d kernels built, %ld stall-distance violations\n", built1, viol_all);
456 static const struct { uint32_t k, lb; const char *name; } prod[] = { { 2048, 16, "gate_up k2048 lb16" }, { 768, 8, "down k768 lb8" } };
457 for (size_t q = 0; q < 2; q++) {
458 static BlackwellIRProgram p0, p1;
459 OmegaFp8GemvSpec s0 = { .k = prod[q].k, .lane_bytes = prod[q].lb, .rows = 1, .warps = 32 }, s1 = s0; s1.sched = 1;
460 uint32_t d1 = 0, g1 = 0, g0 = 0;
461 const int ok = omega_blackwell_codegen_fp8_gemv_prog(&s0, &p0) == 0 && omega_blackwell_codegen_fp8_gemv_prog(&s1, &p1) == 0;
462 CHECK(ok, "sched 0 and 1 build at %s 32 warps", prod[q].name);
463 if (!ok) continue;
464 CHECK(omega_fp8_gemv_prog_stats(&s0, NULL, &g0) == 0 && omega_fp8_gemv_prog_stats(&s1, NULL, &g1) == 0, "stats %s", prod[q].name);
465 CHECK(omega_gpu_fp8_kernel_fits(&s1, &d1) == OMEGA_GPU_FP8_OK, "sched1 %s at 32 warps fits the register file (declared %u): %s", prod[q].name, d1, omega_gpu_fp8_last_error());
466 uint64_t c0 = 0, c1 = 0;
467 const long v0 = fp8_stall_violations(&p0, &c0), v1 = fp8_stall_violations(&p1, &c1);
468 CHECK(v0 == 0 && v1 == 0, "%s stall distances: sched0 %ld, sched1 %ld violations", prod[q].name, v0, v1);
469 /* negative control: the pass gives each instruction its smallest legal stall, so a fixed-latency stall above 1
470 * is binding; shortening the first one to 1 must be caught by the independent walk */
471 size_t at = p1.count;
472 for (size_t i = 0; i < p1.count; i++) if (fp8_chk_fixed(p1.insns[i].op) && ((p1.insns[i].control >> 9) & 0xfu) > 1u) { at = i; break; }
473 if (at < p1.count) p1.insns[at].control = (p1.insns[at].control & ~(0xfu << 9)) | (1u << 9);
474 CHECK(at < p1.count && fp8_stall_violations(&p1, NULL) > 0, "%s: stall checker catches one shortened stall", prod[q].name);
475 printf("sched1 %s w32: %zu insns (sched0 %zu), peak %u GPRs (sched0 %u), declared %u; stall cycles in program order %" PRIu64 " (sched0 %" PRIu64 "); shortened-stall control caught\n",
476 prod[q].name, p1.count, p0.count, g1, g0, d1, c1, c0);
477 }
478 { OmegaFp8GemvSpec bad = { .k = 2048, .lane_bytes = 16, .rows = 1, .warps = 8, .sched = 2 }; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "sched 2 refused"); }
479 }
480
481 /* 8. CUT5 variants A (coal: coalesced output through shared slots) and B (wfirst: weight loads before the x' loads).
482 * Every battery shape builds in every combination with sched 0 and 1 (sched 1 with no stall violation); the refusals
483 * hold; for the two grouped expert shapes at 32 warps: the register file fits, A has one STG and one BAR.SYNC per
484 * round and declares the two slot sets, and B removes exactly one load round trip per K step (fp8_load_batches:
485 * a global load that follows a wait on the load scoreboard opens a new batch). Default programs keep their batch
486 * count, so the counter says "no" when nothing changed (deep kernels, which ignore wfirst). */
487 {
488 int built = 0; long viol = 0;
489 for (size_t a = 0; a < sizeof ks / sizeof ks[0]; a++) for (size_t b = 0; b < 2; b++) for (size_t c = 0; c < 4; c++)
490 for (int m = 0; m <= 5; m++) for (int deep = 0; deep < 2; deep++) for (int cw = 1; cw < 4; cw++) for (int sch = 0; sch < 2; sch++) {
491 OmegaFp8GemvSpec sp = { .k = ks[a], .lane_bytes = lbs[b], .rows = rows[c], .warps = 4, .mutant = m, .sched = (uint32_t)sch, .coal = (uint32_t)(cw & 1), .wfirst = (uint32_t)(cw >> 1) };
492 if (ks[a] % (32 * lbs[b]) || (m >= 4 && !sp.coal)) continue;
493 if (deep) { sp.depth = ks[a] / (32 * lbs[b]); if (sp.depth * sp.rows * lbs[b] > 128 || ks[a] > 2048) continue; }
494 static BlackwellIRProgram cp;
495 int rc = omega_blackwell_codegen_fp8_gemv_prog(&sp, &cp);
496 CHECK(rc == 0 && cp.count <= BW_MAX_IR_INSNS, "A/B codegen k=%u lb=%u rows=%u mutant=%d deep=%d coal=%u wfirst=%u sched=%d", sp.k, sp.lane_bytes, sp.rows, m, deep, sp.coal, sp.wfirst, sch);
497 if (rc != 0) continue;
498 built++;
499 if (sch) { long v = fp8_stall_violations(&cp, NULL); viol += v; CHECK(v == 0, "A/B sched1 stall distances k=%u lb=%u rows=%u coal=%u wfirst=%u: %ld", sp.k, sp.lane_bytes, sp.rows, sp.coal, sp.wfirst, v); }
500 }
501 printf("A/B codegen: %d kernels built (coal, wfirst, both x sched 0/1 x mutants), %ld stall-distance violations\n", built, viol);
502 { OmegaFp8GemvSpec bad = { .k = 2048, .lane_bytes = 16, .rows = 2, .warps = 32, .coal = 1 }; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "coal refused at warps x rows = 64");
503 bad.rows = 1; bad.coal = 2; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "coal 2 refused");
504 bad.coal = 0; bad.wfirst = 2; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "wfirst 2 refused");
505 bad.wfirst = 0; bad.mutant = 4; CHECK(omega_fp8_gemv_prog_stats(&bad, NULL, NULL) != 0, "mutant 4 refused without coal"); }
506 static const struct { uint32_t k, lb; const char *name; } prod[] = { { 2048, 16, "gate_up k2048 lb16" }, { 768, 8, "down k768 lb8" } };
507 for (size_t q = 0; q < 2; q++) {
508 static BlackwellIRProgram p0, pa, pb, pab;
509 OmegaFp8GemvSpec s0 = { .k = prod[q].k, .lane_bytes = prod[q].lb, .rows = 1, .warps = 32 }, sa = s0, sb = s0, sab = s0;
510 sa.coal = 1; sb.wfirst = 1; sab.coal = 1; sab.wfirst = 1;
511 const int ok = omega_blackwell_codegen_fp8_gemv_prog(&s0, &p0) == 0 && omega_blackwell_codegen_fp8_gemv_prog(&sa, &pa) == 0 &&
512 omega_blackwell_codegen_fp8_gemv_prog(&sb, &pb) == 0 && omega_blackwell_codegen_fp8_gemv_prog(&sab, &pab) == 0;
513 CHECK(ok, "A, B, A+B build at %s 32 warps", prod[q].name);
514 if (!ok) continue;
515 uint32_t da = 0, db = 0, dab = 0;
516 CHECK(omega_gpu_fp8_kernel_fits(&sa, &da) == OMEGA_GPU_FP8_OK && omega_gpu_fp8_kernel_fits(&sb, &db) == OMEGA_GPU_FP8_OK && omega_gpu_fp8_kernel_fits(&sab, &dab) == OMEGA_GPU_FP8_OK,
517 "%s A/B/A+B fit the register file at 32 warps (declared %u %u %u)", prod[q].name, da, db, dab);
518 const int stg0 = fp8_count_op(&p0, BW_IR_STG_E), stga = fp8_count_op(&pa, BW_IR_STG_E), bar0 = fp8_count_op(&p0, BW_IR_BAR_SYNC), bara = fp8_count_op(&pa, BW_IR_BAR_SYNC);
519 CHECK(stg0 == 1 && stga == 1 && bar0 == 0 && bara == 1 && omega_fp8_gemv_shared_bytes(&sa) == 2u * 32u * 4u && omega_fp8_gemv_shared_bytes(&s0) == 0,
520 "%s A: STG %d (default %d), BAR.SYNC %d (default %d), shared %u bytes", prod[q].name, stga, stg0, bara, bar0, omega_fp8_gemv_shared_bytes(&sa));
521 const int b0 = fp8_load_batches(&p0), bb = fp8_load_batches(&pb), ba = fp8_load_batches(&pa), bab = fp8_load_batches(&pab);
522 CHECK(b0 - bb == 1 && ba - bab == 1, "%s B: load batches default %d -> wfirst %d, coal %d -> coal+wfirst %d (one round trip less per K step)", prod[q].name, b0, bb, ba, bab);
523 OmegaFp8GemvSpec sd = s0, sdb; sd.warps = 8; sd.depth = omega_fp8_gemv_steps(&sd); sdb = sd; sdb.wfirst = 1;
524 static BlackwellIRProgram pd, pdb;
525 const int okd = omega_blackwell_codegen_fp8_gemv_prog(&sd, &pd) == 0 && omega_blackwell_codegen_fp8_gemv_prog(&sdb, &pdb) == 0;
526 CHECK(okd && fp8_load_batches(&pd) == fp8_load_batches(&pdb) && pd.count == pdb.count, "%s deep: wfirst changes nothing (batches %d, %d)", prod[q].name, okd ? fp8_load_batches(&pd) : -1, okd ? fp8_load_batches(&pdb) : -1);
527 printf("A/B %s w32: insns %zu / A %zu / B %zu / A+B %zu; declared regs A %u B %u A+B %u; load batches %d / %d / %d / %d\n",
528 prod[q].name, p0.count, pa.count, pb.count, pab.count, da, db, dab, b0, ba, bb, bab);
529 }
530 }
531}
532
533/* ------------------------------------------------------------- simulator */
534static uint64_t g_sim_issues;
535static int g_sim_variant = 1; /* which generator sim_gemv runs: 1 (omega_blackwell_codegen_moe.c) or 2 (moe2.c, W-L2c) */
536/* Runs the kernel for (W, groups, ids, x, x_rows) on the warp simulator in both fragment orders. Returns 0 and y
537 * on success, -1 on a simulator error or an order-dependent result. */
538static int sim_gemv(const OmegaFp8GemvSpec *spec, const Weights *W, uint32_t groups, const uint32_t *ids, const float *x,
539 uint32_t x_rows, float *y, uint32_t cta_budget, int no_fold, char *msg, size_t msglen) {
540 static BlackwellIRProgram prog;
541 if ((g_sim_variant == 2 ? omega_blackwell_codegen_fp8_gemv2_prog(spec, &prog) : omega_blackwell_codegen_fp8_gemv_prog(spec, &prog)) != 0) { snprintf(msg, msglen, "codegen refused"); return -1; }
542 const uint32_t n = W->n, k = W->k, RG = n / spec->rows;
543 size_t sc = (size_t)W->experts * (n / 128) * (k / 128);
544 float *sf = aligned_alloc(16, ((sc * 4) + 15) & ~(size_t)15);
545 if (omega_fp8_pack_scales(W->s, sc, sf, no_fold) != 0) { free(sf); snprintf(msg, msglen, "scale pack refused"); return -1; }
546 float *xf = aligned_alloc(16, ((size_t)x_rows * k * 4 + 15) & ~(size_t)15);
547 for (uint32_t r = 0; r < x_rows; r++) omega_fp8_pack_x_f32(x + (size_t)r * k, k, xf + (size_t)r * k);
548 uint64_t *tab = aligned_alloc(16, 16 * (size_t)groups);
549 for (uint32_t g = 0; g < groups; g++) {
550 tab[2 * g] = (uintptr_t)(W->w + (size_t)ids[g] * n * k);
551 tab[2 * g + 1] = (uintptr_t)(sf + (size_t)ids[g] * (n / 128) * (k / 128));
552 }
553 float *yd = aligned_alloc(16, ((size_t)groups * n * 4 + 15) & ~(size_t)15);
554 float *copy = malloc((size_t)groups * n * 4);
555 uint32_t grid_x = (RG + spec->warps - 1) / spec->warps; if (grid_x > cta_budget) grid_x = cta_budget; if (!grid_x) grid_x = 1;
556 int err = 0;
557 const int runs = (spec->coal || getenv("FP8_SIM_ALL_ORDERS")) ? 4 : 2; /* coal: also descending and shuffled warp visit orders per barrier phase (slot races) */
558 for (int run = 0; run < runs && !err; run++) {
559 const int order = run == 1;
560 WsSim s; memset(&s, 0, sizeof s);
561 s.p = &prog; s.threads = 32 * spec->warps; s.order = order; s.warp_sched = run == 2 ? 1u : run == 3 ? 0x9e3779b9u : 0u;
562 static uint8_t smem[OMEGA_FP8_MAX_K * 4 + 4096]; s.smem = smem; s.smem_bytes = g_sim_variant == 2 ? omega_fp8_gemv2_shared_bytes(spec) : omega_fp8_gemv_shared_bytes(spec); /* the bytes the launch declares (0: any shared access fails) */
563 uint64_t ta = (uintptr_t)tab, xa = (uintptr_t)xf, ya = (uintptr_t)yd;
564 s.cbank[OMEGA_FP8_ARG_TAB / 4] = (uint32_t)ta; s.cbank[OMEGA_FP8_ARG_TAB / 4 + 1] = (uint32_t)(ta >> 32);
565 s.cbank[OMEGA_FP8_ARG_X / 4] = (uint32_t)xa; s.cbank[OMEGA_FP8_ARG_X / 4 + 1] = (uint32_t)(xa >> 32);
566 s.cbank[OMEGA_FP8_ARG_Y / 4] = (uint32_t)ya; s.cbank[OMEGA_FP8_ARG_Y / 4 + 1] = (uint32_t)(ya >> 32);
567 s.cbank[OMEGA_FP8_ARG_RG / 4] = RG; s.cbank[OMEGA_FP8_ARG_XSTRIDE / 4] = x_rows == 1 ? 0 : k * 4;
568 s.cbank[OMEGA_FP8_ARG_YSTRIDE / 4] = n * 4; s.cbank[OMEGA_FP8_ARG_STRIDE / 4] = grid_x * spec->warps;
569 /* every global access must land in a declared buffer */
570 s.nranges = 4;
571 s.ranges[0].lo = (uintptr_t)W->w; s.ranges[0].hi = (uintptr_t)W->w + (size_t)W->experts * n * k;
572 s.ranges[1].lo = (uintptr_t)sf; s.ranges[1].hi = (uintptr_t)sf + sc * 4;
573 s.ranges[2].lo = (uintptr_t)xf; s.ranges[2].hi = (uintptr_t)xf + (size_t)x_rows * k * 4;
574 s.ranges[3].lo = (uintptr_t)yd; s.ranges[3].hi = (uintptr_t)yd + (size_t)groups * n * 4;
575 /* the table is read too */
576 s.nranges = 5; s.ranges[4].lo = (uintptr_t)tab; s.ranges[4].hi = (uintptr_t)tab + 16 * (size_t)groups;
577 for (size_t i = 0; i < (size_t)groups * n; i++) yd[i] = -999.0f;
578 err = ws_run(&s, grid_x, groups);
579 if (err) { snprintf(msg, msglen, "run %d (order %d, warp order %u): %s", run, order, s.warp_sched, s.msg); break; }
580 g_sim_issues += s.warp_issues;
581 size_t unwritten = 0; for (size_t i = 0; i < (size_t)groups * n; i++) if (yd[i] == -999.0f) unwritten++;
582 if (unwritten) { err = -1; snprintf(msg, msglen, "%zu output words never written", unwritten); break; }
583 if (run == 0) memcpy(copy, yd, (size_t)groups * n * 4);
584 else if (memcmp(copy, yd, (size_t)groups * n * 4) != 0) { if (getenv("FP8_SIM_DIFF")) { int c = 0; for (size_t i = 0; i < (size_t)groups * n && c < 12; i++) if (memcmp(&copy[i], &yd[i], 4)) { fprintf(stderr, " diff y[%zu] %g vs %g\n", i, copy[i], yd[i]); c++; } } err = -1; snprintf(msg, msglen, "run %d (order %d, warp order %u) changed the result", run, order, s.warp_sched); }
585 }
586 if (!err) memcpy(y, yd, (size_t)groups * n * 4);
587 free(sf); free(xf); free(tab); free(yd); free(copy);
588 return err ? -1 : 0;
589}
590
591typedef struct { uint32_t experts, n, k, groups, x_rows, lb, rows, warps; const char *name; } SimPoint;
592
593static void sim_battery(uint32_t cta_budget) {
594 char msg[240];
595 /* 1. one-hot conversion through the kernel: 254 rows, row r holds code r at column 0 (NaN codes replaced by
596 * 0x00), x = e_0, scale 1: y[r] must equal the reference exactly (zero rows compare as 0) */
597 {
598 Weights W; W.experts = 1; W.n = 256; W.k = 256;
599 W.w = aligned_alloc(64, 256 * 256); memset(W.w, 0, 256 * 256);
600 W.s = malloc(4 * 2); for (int b = 0; b < 4; b++) W.s[b] = bf16_of(1.0f);
601 for (int r = 0; r < 256; r++) W.w[r * 256] = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0 : (uint8_t)r;
602 float x[256] = { 0 }; x[0] = 1.0f; float y[256]; uint32_t id = 0;
603 OmegaFp8GemvSpec sp = { .k = 256, .lane_bytes = 8, .rows = 8, .warps = 4 };
604 int rc = sim_gemv(&sp, &W, 1, &id, x, 1, y, cta_budget, 0, msg, sizeof msg);
605 CHECK(rc == 0, "one-hot sim run: %s", msg);
606 int exact = 0;
607 if (rc == 0) for (int r = 0; r < 256; r++) {
608 float ref = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0.0f : omega_fp8_e4m3_ref((uint8_t)r);
609 if (y[r] == ref) exact++; else { CHECK(0, "one-hot code 0x%02x: kernel %a, reference %a", r, y[r], ref); }
610 }
611 printf("sim one-hot conversion: %d/256 rows exact\n", exact);
612 /* x on the other lanes/words: code at column c, x = e_c for c in {1, 17, 127} on one row each */
613 for (int t = 0; t < 3; t++) {
614 const int cols[3] = { 1, 17, 255 }; const uint8_t codes[3] = { 0xc0, 0x05, 0x7e };
615 memset(W.w, 0, 256 * 256); W.w[3 * 256 + cols[t]] = codes[t];
616 memset(x, 0, sizeof x); x[cols[t]] = -2.5f; for (int b = 0; b < 4; b++) W.s[b] = bf16_of(0.75f);
617 rc = sim_gemv(&sp, &W, 1, &id, x, 1, y, cta_budget, 0, msg, sizeof msg);
618 CHECK(rc == 0 && y[3] == omega_fp8_e4m3_ref(codes[t]) * -2.5f * 0.75f, "one-hot column %d code 0x%02x: %a vs %a (%s)", cols[t], codes[t], rc == 0 ? y[3] : 0.0f, omega_fp8_e4m3_ref(codes[t]) * -2.5f * 0.75f, msg);
619 }
620 weights_free(&W);
621 }
622 /* 2. parity battery */
623 static const SimPoint pts[] = {
624 { 1, 128, 256, 1, 1, 8, 1, 1, "k256 lb8 r1 w1" },
625 { 1, 256, 256, 1, 1, 8, 2, 2, "k256 lb8 r2 w2" },
626 { 1, 256, 768, 1, 1, 8, 4, 8, "k768 lb8 r4 w8 (down shape width)" },
627 { 1, 256, 768, 1, 1, 8, 8, 8, "k768 lb8 r8" },
628 { 1, 384, 2048, 1, 1, 16, 8, 8, "k2048 lb16 r8 w8 (gate shape width)" },
629 { 1, 128, 2048, 1, 1, 16, 1, 8, "k2048 lb16 r1" },
630 { 1, 256, 512, 1, 1, 16, 2, 3, "k512 lb16 r2 w3 (odd warps, tail row groups)" },
631 { 4, 256, 2048, 4, 1, 16, 8, 8, "4 experts shared x (gate+up)" },
632 { 6, 256, 768, 8, 8, 8, 4, 8, "8 groups per-group x, repeated ids (down)" },
633 { 3, 128, 256, 2, 2, 8, 8, 4, "2 groups per-group x" },
634 { 2, 256, 768, 2, 2, 8, 1, 7, "k768 w7: partial staging round (deep)" },
635 { 1, 128, 17408, 1, 1, 16, 2, 8, "k17408 lb16 r2 w8 (Qwen3.8-27B down width, step kernel)" },
636 };
637 const size_t npts = sizeof pts / sizeof pts[0];
638 double worst_all = 0.0;
639 for (size_t i = 0; i < npts; i++) {
640 const SimPoint *p = &pts[i];
641 Weights W; weights_make(&W, p->experts, p->n, p->k, 1000 + (uint32_t)i);
642 uint32_t ids[8]; uint32_t st = 77 + (uint32_t)i;
643 for (uint32_t g = 0; g < p->groups; g++) ids[g] = lcg(&st) % p->experts;
644 float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f);
645 float *y = malloc((size_t)p->groups * p->n * 4);
646 /* every point runs the step-by-step kernel (depth 0) and, when the row fits, the deep kernel (depth = KS) */
647 for (int deep = 0; deep < 2; deep++) {
648 OmegaFp8GemvSpec sp = { .k = p->k, .lane_bytes = p->lb, .rows = p->rows, .warps = p->warps };
649 if (deep) { sp.depth = omega_fp8_gemv_steps(&sp); if (sp.depth * sp.rows * sp.lane_bytes > 128 || p->k > 512 * p->warps) continue; }
650 char nm[96]; snprintf(nm, sizeof nm, "%s%s", p->name, deep ? " deep" : "");
651 double t0 = now_ms();
652 int rc = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y, cta_budget, 0, msg, sizeof msg);
653 size_t bad = 0; double worst = rc == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y, &bad) : 1.0;
654 if (worst > worst_all) worst_all = worst;
655 CHECK(rc == 0 && bad == 0, "sim %s: rc=%d bad=%zu worst_rel=%.3e %s", nm, rc, bad, worst, msg);
656 printf("sim %-45s rc=%d worst_rel=%.3e bad=%zu (%.0f ms)\n", nm, rc, worst, bad, now_ms() - t0);
657 /* mutants on the two grouped points and the first two single points: each must be caught */
658 if (i == 1 || i == 4 || i == 7 || i == 8) {
659 for (int m = 1; m <= 4; m++) {
660 if (m == 3 && p->groups == 1) continue; /* group swap needs two groups */
661 if (m == 2 && omega_fp8_gemv_steps(&sp) < 2) { printf("sim %s mutant 2: one K step, control not applicable\n", p->name); continue; }
662 OmegaFp8GemvSpec ms = sp; ms.mutant = m == 4 ? 0 : m;
663 rc = sim_gemv(&ms, &W, p->groups, ids, x, p->x_rows, y, cta_budget, m == 4, msg, sizeof msg);
664 bad = 0; worst = rc == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y, &bad) : 1.0;
665 int caught = rc != 0 || bad > 0;
666 if (m == 3 && rc == 0) { /* the ids must differ for the swap to show; make sure the control is meaningful */
667 int distinct = 0; for (uint32_t g = 0; g + 1 < p->groups; g += 2) if (ids[g] != ids[g ^ 1]) distinct = 1;
668 if (!distinct) { printf("sim %s mutant 3: ids pairwise equal, control skipped\n", p->name); continue; }
669 }
670 CHECK(caught, "sim %s mutant %d NOT caught (worst_rel=%.3e)", nm, m, worst);
671 printf("sim %-45s mutant %d: %s (rc=%d bad=%zu worst_rel=%.3e)\n", nm, m, caught ? "caught" : "MISSED", rc, bad, worst);
672 }
673 }
674 }
675 free(x); free(y); weights_free(&W);
676 }
677 printf("sim battery: worst relative error %.3e over %zu points, %" PRIu64 " warp issues\n", worst_all, npts, g_sim_issues);
678
679 /* 3. variant 2 (W-L2c): y bit-identical to variant 1 on every point (same arithmetic order), parity against the oracle,
680 * mutants caught; the identity check is shown to say "no" on a mutant */
681 {
682 static const SimPoint v2pts[] = {
683 { 1, 256, 2048, 1, 1, 16, 1, 8, "v2 k2048 lb16 r1 w8 (gate_up/qkv width)" },
684 { 1, 256, 2048, 1, 1, 16, 2, 8, "v2 k2048 lb16 r2 w8 (128 B per lane)" },
685 { 1, 256, 4096, 1, 1, 16, 1, 8, "v2 k4096 lb16 r1 w8 (o_proj width)" },
686 { 1, 256, 768, 1, 1, 8, 1, 8, "v2 k768 lb8 r1 w8 (down width)" },
687 { 1, 256, 768, 1, 1, 8, 4, 8, "v2 k768 lb8 r4 w8" },
688 { 2, 256, 768, 2, 2, 8, 1, 7, "v2 k768 w7: partial staging round" },
689 { 4, 256, 2048, 4, 1, 16, 1, 8, "v2 4 experts shared x (gate_up)" },
690 { 6, 256, 768, 8, 8, 8, 2, 8, "v2 8 groups per-group x, repeated ids (down)" },
691 { 3, 128, 256, 2, 2, 8, 8, 4, "v2 2 groups per-group x, r8 k256" },
692 { 1, 256, 512, 1, 1, 16, 2, 3, "v2 k512 w3 (odd warps, tail row groups)" },
693 };
694 const size_t n2 = sizeof v2pts / sizeof v2pts[0];
695 int identical = 0;
696 for (size_t i = 0; i < n2; i++) {
697 const SimPoint *p = &v2pts[i];
698 Weights W; weights_make(&W, p->experts, p->n, p->k, 5000 + (uint32_t)i);
699 uint32_t ids[8]; uint32_t st = 177 + (uint32_t)i;
700 for (uint32_t g = 0; g < p->groups; g++) ids[g] = lcg(&st) % p->experts;
701 float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f);
702 const size_t ny = (size_t)p->groups * p->n;
703 float *y1 = malloc(ny * 4), *y2 = malloc(ny * 4);
704 OmegaFp8GemvSpec sp = { .k = p->k, .lane_bytes = p->lb, .rows = p->rows, .warps = p->warps };
705 g_sim_variant = 1; int rc1 = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y1, cta_budget, 0, msg, sizeof msg);
706 CHECK(rc1 == 0, "v1 reference for %s: %s", p->name, msg);
707 double t0 = now_ms();
708 g_sim_variant = 2; int rc2 = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y2, cta_budget, 0, msg, sizeof msg);
709 size_t bad = 0; double worst = rc2 == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y2, &bad) : 1.0;
710 int same = rc1 == 0 && rc2 == 0 && memcmp(y1, y2, ny * 4) == 0;
711 CHECK(rc2 == 0 && bad == 0 && same, "sim %s: rc=%d bad=%zu worst_rel=%.3e identical_to_v1=%d %s", p->name, rc2, bad, worst, same, msg);
712 if (same) identical++;
713 printf("sim %-48s rc=%d worst_rel=%.3e bad=%zu identical_to_v1=%d (%.0f ms)\n", p->name, rc2, worst, bad, same, now_ms() - t0);
714 if (i == 0 || i == 6 || i == 7) {
715 for (int m = 1; m <= 3; m++) {
716 if (m == 3 && p->groups == 1) continue;
717 OmegaFp8GemvSpec ms = sp; ms.mutant = m;
718 int rcm = sim_gemv(&ms, &W, p->groups, ids, x, p->x_rows, y2, cta_budget, 0, msg, sizeof msg);
719 bad = 0; worst = rcm == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y2, &bad) : 1.0;
720 int caught = rcm != 0 || bad > 0, differs = rcm != 0 || memcmp(y1, y2, ny * 4) != 0;
721 if (m == 3 && rcm == 0) { int distinct = 0; for (uint32_t g = 0; g + 1 < p->groups; g += 2) if (ids[g] != ids[g ^ 1]) distinct = 1; if (!distinct) { printf("sim %s mutant 3: ids pairwise equal, control skipped\n", p->name); continue; } }
722 CHECK(caught && differs, "sim %s mutant %d NOT caught (bad=%zu worst_rel=%.3e identity says %s)", p->name, m, bad, worst, differs ? "different" : "SAME");
723 printf("sim %-48s mutant %d: %s (rc=%d bad=%zu worst_rel=%.3e, identity check differs=%d)\n", p->name, m, caught ? "caught" : "MISSED", rcm, bad, worst, differs);
724 }
725 }
726 g_sim_variant = 1;
727 free(x); free(y1); free(y2); weights_free(&W);
728 }
729 printf("sim v2 battery: %d/%zu points bit-identical to variant 1\n", identical, n2);
730 }
731
732 /* 4. sched 1 (CUT5): y bit-identical to sched 0 on every battery point (step and deep kernels), parity against the
733 * oracle, mutants 1..3 caught on the grouped points; the identity check is shown to say "no" on a mutant */
734 {
735 int identical = 0, runs = 0;
736 for (size_t i = 0; i < npts; i++) {
737 const SimPoint *p = &pts[i];
738 Weights W; weights_make(&W, p->experts, p->n, p->k, 1000 + (uint32_t)i);
739 uint32_t ids[8]; uint32_t st = 77 + (uint32_t)i;
740 for (uint32_t g = 0; g < p->groups; g++) ids[g] = lcg(&st) % p->experts;
741 float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f);
742 const size_t ny = (size_t)p->groups * p->n;
743 float *y0 = malloc(ny * 4), *y1 = malloc(ny * 4);
744 for (int deep = 0; deep < 2; deep++) {
745 OmegaFp8GemvSpec sp = { .k = p->k, .lane_bytes = p->lb, .rows = p->rows, .warps = p->warps };
746 if (deep) { sp.depth = omega_fp8_gemv_steps(&sp); if (sp.depth * sp.rows * sp.lane_bytes > 128 || p->k > 512 * p->warps) continue; }
747 char nm[96]; snprintf(nm, sizeof nm, "sched1 %s%s", p->name, deep ? " deep" : "");
748 int rc0 = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y0, cta_budget, 0, msg, sizeof msg);
749 CHECK(rc0 == 0, "sched0 reference for %s: %s", nm, msg);
750 OmegaFp8GemvSpec s1 = sp; s1.sched = 1;
751 int rc1 = sim_gemv(&s1, &W, p->groups, ids, x, p->x_rows, y1, cta_budget, 0, msg, sizeof msg);
752 size_t bad = 0; double worst = rc1 == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y1, &bad) : 1.0;
753 int same = rc0 == 0 && rc1 == 0 && memcmp(y0, y1, ny * 4) == 0;
754 CHECK(rc1 == 0 && bad == 0 && same, "sim %s: rc=%d bad=%zu worst_rel=%.3e identical_to_sched0=%d %s", nm, rc1, bad, worst, same, msg);
755 runs++; if (same) identical++;
756 printf("sim %-52s rc=%d worst_rel=%.3e bad=%zu identical_to_sched0=%d\n", nm, rc1, worst, bad, same);
757 if (i == 7 || i == 8) {
758 for (int m = 1; m <= 3; m++) {
759 if (m == 2 && omega_fp8_gemv_steps(&sp) < 2) continue;
760 OmegaFp8GemvSpec ms = s1; ms.mutant = m;
761 int rcm = sim_gemv(&ms, &W, p->groups, ids, x, p->x_rows, y1, cta_budget, 0, msg, sizeof msg);
762 bad = 0; worst = rcm == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y1, &bad) : 1.0;
763 int caught = rcm != 0 || bad > 0, differs = rcm != 0 || memcmp(y0, y1, ny * 4) != 0;
764 CHECK(caught && differs, "sim %s mutant %d NOT caught (bad=%zu worst_rel=%.3e identity says %s)", nm, m, bad, worst, differs ? "different" : "SAME");
765 printf("sim %-52s mutant %d: %s (rc=%d bad=%zu worst_rel=%.3e, identity check differs=%d)\n", nm, m, caught ? "caught" : "MISSED", rcm, bad, worst, differs);
766 }
767 }
768 }
769 free(x); free(y0); free(y1); weights_free(&W);
770 }
771 printf("sim sched1 battery: %d/%d runs bit-identical to sched 0\n", identical, runs);
772 }
773
774 /* 5. CUT5 variants A (coal) and B (wfirst), alone and together: y bit-identical to the default on every battery point
775 * where A applies (warps * rows <= 32), step and deep kernels, parity against the oracle; coal kernels run in four
776 * orders (fragment order both ways, warps descending and shuffled per barrier phase). Mutants: 4 (one slot set) must
777 * be caught by a warp order (points with two or more rounds per CTA), 5 (no clamp) on the points whose last round is
778 * partial (6, 10), 1..3 on the A+B kernel of point 8 (1, 2 also on point 9). */
779 {
780 int identical = 0, runs = 0;
781 for (size_t i = 0; i < npts; i++) {
782 const SimPoint *p = &pts[i];
783 Weights W; weights_make(&W, p->experts, p->n, p->k, 1000 + (uint32_t)i);
784 uint32_t ids[8]; uint32_t st = 77 + (uint32_t)i;
785 for (uint32_t g = 0; g < p->groups; g++) ids[g] = lcg(&st) % p->experts;
786 float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f);
787 const size_t ny = (size_t)p->groups * p->n;
788 float *y0 = malloc(ny * 4), *y1 = malloc(ny * 4);
789 for (int deep = 0; deep < 2; deep++) {
790 OmegaFp8GemvSpec sp = { .k = p->k, .lane_bytes = p->lb, .rows = p->rows, .warps = p->warps };
791 if (deep) { sp.depth = omega_fp8_gemv_steps(&sp); if (sp.depth * sp.rows * sp.lane_bytes > 128 || p->k > 512 * p->warps) continue; }
792 int rc0 = sim_gemv(&sp, &W, p->groups, ids, x, p->x_rows, y0, cta_budget, 0, msg, sizeof msg);
793 CHECK(rc0 == 0, "default reference for A/B %s%s: %s", p->name, deep ? " deep" : "", msg);
794 for (int cw = 1; cw < 4; cw++) {
795 OmegaFp8GemvSpec sv = sp; sv.coal = (uint32_t)(cw & 1); sv.wfirst = (uint32_t)(cw >> 1);
796 if (sv.coal && p->warps * p->rows > 32) continue;
797 char nm[96]; snprintf(nm, sizeof nm, "%s %s%s", cw == 1 ? "A" : cw == 2 ? "B" : "A+B", p->name, deep ? " deep" : "");
798 int rc1 = sim_gemv(&sv, &W, p->groups, ids, x, p->x_rows, y1, cta_budget, 0, msg, sizeof msg);
799 size_t bad = 0; double worst = rc1 == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y1, &bad) : 1.0;
800 int same = rc0 == 0 && rc1 == 0 && memcmp(y0, y1, ny * 4) == 0;
801 CHECK(rc1 == 0 && bad == 0 && same, "sim %s: rc=%d bad=%zu worst_rel=%.3e identical_to_default=%d %s", nm, rc1, bad, worst, same, msg);
802 runs++; if (same) identical++;
803 printf("sim %-52s rc=%d worst_rel=%.3e bad=%zu identical_to_default=%d\n", nm, rc1, worst, bad, same);
804 int ms_list[5], nm_list = 0;
805 if (sv.coal && cw == 1 && (i == 6 || i == 10)) ms_list[nm_list++] = 5;
806 if (sv.coal && cw == 1 && (i == 1 || i == 6 || i == 8 || i == 10)) ms_list[nm_list++] = 4;
807 if (cw == 3 && (i == 8 || i == 9)) { ms_list[nm_list++] = 1; if (omega_fp8_gemv_steps(&sp) >= 2) ms_list[nm_list++] = 2; if (i == 8) ms_list[nm_list++] = 3; } /* point 9 draws the same expert for both groups: a table swap is invisible there */
808 for (int q = 0; q < nm_list; q++) {
809 OmegaFp8GemvSpec ms = sv; ms.mutant = ms_list[q];
810 int rcm = sim_gemv(&ms, &W, p->groups, ids, x, p->x_rows, y1, cta_budget, 0, msg, sizeof msg);
811 bad = 0; worst = rcm == 0 ? parity(&W, p->groups, ids, x, p->x_rows, y1, &bad) : 1.0;
812 int caught = rcm != 0 || bad > 0;
813 CHECK(caught, "sim %s mutant %d NOT caught (bad=%zu worst_rel=%.3e)", nm, ms.mutant, bad, worst);
814 printf("sim %-52s mutant %d: %s (rc=%d bad=%zu %s)\n", nm, ms.mutant, caught ? "caught" : "MISSED", rcm, bad, rcm ? msg : "");
815 }
816 }
817 }
818 free(x); free(y0); free(y1); weights_free(&W);
819 }
820 printf("sim A/B battery: %d/%d runs bit-identical to the default\n", identical, runs);
821 }
822}
823
824/* ------------------------------------------------------------------- chip */
825typedef struct { uint32_t experts, n, k, groups, x_rows; const char *name; int parity_check; } ChipPoint;
826
827/* Whether any variant-2 kernel shape (lane bytes 8 or 16, rows 1..8, warps 1..32) exists for n x k, decided from the
828 * generator's own spec rule, not from the API under test. Variant 2 keeps a warp's whole row group in one register set
829 * (rows * k / 32 <= 128 bytes), so k > 4096 is outside it (the q38 shapes, the 32768 width cap); a host-staged call on
830 * such a shape is served by the general fallback (omega_gpu_fp8_api.h: info->general = 1). Variant 1 serves every point. */
831static int v2_can_build(uint32_t n, uint32_t k) {
832 static const uint32_t lbs[2] = { 8, 16 }, rws[4] = { 1, 2, 4, 8 };
833 for (int a = 0; a < 2; a++)
834 for (int b = 0; b < 4; b++)
835 for (uint32_t w = 1; w <= 32; w++) {
836 if (n % rws[b]) continue;
837 OmegaFp8GemvSpec s = { .k = k, .lane_bytes = lbs[a], .rows = rws[b], .warps = w };
838 if (omega_fp8_gemv2_shared_bytes(&s) != 0u) return 1;
839 }
840 return 0;
841}
842
843static int g_evict = 1; /* stream 512 MB through the host caches between upload and timing (nvrm.c:433: freshly written
844 host memory is served from the CPU caches by snooping and reads faster) */
845static void evict_host_caches(void) {
846 static uint8_t *buf; const size_t sz = 512u << 20; static uint8_t pass;
847 if (!buf) buf = malloc(sz);
848 if (!buf) return;
849 memset(buf, ++pass, sz);
850 volatile uint64_t sum = 0; for (size_t i = 0; i < sz; i += 64) sum += buf[i];
851}
852
853static const char *g_only; static int g_depth_forced; /* run only the battery points whose name contains this (diagnosis) */
854/* --n N --k K (ternary engine T0, 2026-10-15): run ONE custom point n x k (one expert, one group) instead of the battery,
855 * with the parity check, timing and mutants 1, 2 and 4 (3 needs groups > 1); e.g. the BitNet word table 128256 x 2560. */
856static uint32_t g_custom_n, g_custom_k; static char g_custom_name[48];
857/* --grouped-cold (CUT5, 2026-10-16): the decode graph's two expert launches at their real shapes (omega_gpu_decode_graph.c
858 * record_layer: gate_up [128][1536][2048] with one shared x row, down [128][2048][768] with one x row per group), 8 of 128
859 * experts per launch. L2 is defeated by rotation: the 128 experts are split into 16 disjoint sets of 8 and launch r uses
860 * set r % 16, so consecutive launches share no weight byte and a set returns only after 15 other sets (gate_up 403 MB,
861 * down 201 MB in between; L2 is 24 MiB, evidence/TERN-T0-KT1-18185404-20261016T0151Z/README.md). Every timed launch is
862 * checked against the double oracle (outside the chip time); a launch that fails parity fails the run. Mutants 1..4
863 * must be caught at both shapes. GB/s = (weight + scale bytes of the 8 experts) / median chip time (launch to completion
864 * marker: the launch floor is NOT subtracted). */
865static int g_cold;
866static int g_dump_stamps; /* --dump-stamps: one line per GPU-stamped launch (diagnosis of per-launch spread) */
867/* GPU-clock timing for --grouped-cold (CUT5, after omega#507: a host clock around submit and completion is not kernel time).
868 * The rotation above, recorded as one command list of LIST_N launches (launch i uses set i % 16, writes its own y slot),
869 * WAIT_FOR_IDLE + shader-cache invalidate before every launch (the decode graph's default barrier), GPU timestamps
870 * (PTIMER) before launch 0 and after every launch; launch time = stamp[i + 1] - stamp[i] (the barrier and launch floor are
871 * inside it, not subtracted). Every launch's y is checked against the oracle after the list. lists x LIST_N launches. */
872#define LIST_N 32u
873static int cold_list_stamps(const ChipPoint *p, const Weights *W, const OmegaGpuFp8Tensor *t, const uint32_t *perm, const float *x,
874 uint32_t lists, uint64_t *el, uint32_t *n_el, size_t *bad_out, double *worst_out) {
875 const size_t ny = (size_t)p->groups * p->n;
876 const uint32_t STR = p->experts / 16u; /* experts per rotation set (8 for the 128-expert tables, 1 for --cold-single) */
877 OmegaGpuCmdList *cl = NULL; OmegaGpuMem tab, xd, yd; int ok = 1;
878 memset(&tab, 0, sizeof tab); memset(&xd, 0, sizeof xd); memset(&yd, 0, sizeof yd);
879 if (omega_gpu_cmdlist_create(LIST_N, &cl) != 0) { printf("cmdlist create: %s\n", omega_gpu_session_last_error()); return -1; }
880 omega_gpu_session_lock();
881 int arc = omega_gpu_session_alloc((size_t)16u * p->groups * 16u, &tab) | omega_gpu_session_alloc((size_t)p->x_rows * p->k * 4u, &xd) | omega_gpu_session_alloc((size_t)LIST_N * ny * 4u, &yd);
882 omega_gpu_session_unlock();
883 if (arc != 0) { printf("list alloc: %s\n", omega_gpu_session_last_error()); ok = 0; }
884 if (ok) {
885 uint64_t *tw = tab.cpu;
886 for (uint32_t s = 0; s < 16u && ok; s++) for (uint32_t g = 0; g < p->groups; g++)
887 if (omega_gpu_fp8_tensor_entry(t, perm[STR * s + g], &tw[2u * (s * p->groups + g)], &tw[2u * (s * p->groups + g) + 1u]) != 0) ok = 0;
888 for (uint32_t r = 0; r < p->x_rows; r++) omega_fp8_pack_x_f32(x + (size_t)r * p->k, p->k, (float *)xd.cpu + (size_t)r * p->k);
889 if (!ok || omega_gpu_session_sync_to_gpu(&tab) != 0 || omega_gpu_session_sync_to_gpu(&xd) != 0) ok = 0;
890 }
891 size_t bad_all = 0; double worst_all = 0.0; uint32_t n = 0;
892 for (uint32_t l = 0; l < lists && ok; l++) {
893 float *y = yd.cpu; for (size_t i = 0; i < (size_t)LIST_N * ny; i++) y[i] = -999.0f;
894 if (omega_gpu_session_sync_to_gpu(&yd) != 0) { ok = 0; break; }
895 if (g_evict) evict_host_caches();
896 omega_gpu_session_lock();
897 omega_gpu_cmdlist_reset(cl);
898 for (uint32_t i = 0; i < LIST_N && ok; i++)
899 if (omega_gpu_fp8_gemv_grouped_record(cl, t, p->groups, tab.va + (uint64_t)(i % 16u) * p->groups * 16u, xd.va, p->x_rows, yd.va + (uint64_t)i * ny * 4u) != 0) { printf("record: %s\n", omega_gpu_fp8_last_error()); ok = 0; }
900 OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = OMEGA_GPU_CMDLIST_BARRIER_WFI; o.stamps = 1;
901 OmegaGpuCmdListStats cs; memset(&cs, 0, sizeof cs);
902 uint64_t sts[LIST_N + 1]; int cnt = -1;
903 if (ok && omega_gpu_cmdlist_submit(cl, &o, &cs) != 0) { printf("submit: %s\n", omega_gpu_session_last_error()); ok = 0; }
904 if (ok) cnt = omega_gpu_cmdlist_stamps(cl, sts, LIST_N + 1);
905 omega_gpu_session_unlock();
906 if (!ok || cnt != (int)LIST_N + 1 || cs.sems_done != LIST_N) { printf("list %u: stamps %d sems_done %u\n", l, cnt, cs.sems_done); ok = 0; break; }
907 if (omega_gpu_session_sync_to_cpu(&yd) != 0) { ok = 0; break; }
908 for (uint32_t i = 0; i < LIST_N; i++) {
909 size_t b = 0; double w = parity(W, p->groups, perm + STR * (i % 16u), x, p->x_rows, y + (size_t)i * ny, &b);
910 bad_all += b; if (w > worst_all) worst_all = w;
911 el[n++] = sts[i + 1] - sts[i];
912 if (g_dump_stamps) printf("stamp %-24s list=%u launch=%u set=%u elapsed_us=%.1f bad=%zu\n", p->name, l, i, i % 16u, (double)el[n - 1] / 1e3, b);
913 }
914 }
915 omega_gpu_session_lock(); omega_gpu_session_free(&tab); omega_gpu_session_free(&xd); omega_gpu_session_free(&yd); omega_gpu_session_unlock();
916 omega_gpu_cmdlist_free(cl);
917 *n_el = n; *bad_out = bad_all; *worst_out = worst_all;
918 return ok ? 0 : -1;
919}
920static void cold_points(FILE *out, uint32_t reps, int *first) {
921 static const ChipPoint gpts[] = {
922 { 128, 1536, 2048, 8, 1, "cold gate_up 8 of 128", 1 },
923 { 128, 2048, 768, 8, 8, "cold down 8 of 128", 1 },
924 };
925 /* --cold-single (SPEED-1B, 2026-10-17): the decode graph's two single-projection launches (omega_gpu_decode_graph.c
926 * record_layer: qkv [1][5120][2048], o_proj [1][2048][4096], groups 1). Same rotation as above with 16 copies of the
927 * shape, one per set: consecutive launches share no weight byte and a copy returns after 15 others (qkv 157 MB,
928 * o_proj 126 MB in between; L2 is 24 MiB). */
929 static const ChipPoint spts[] = {
930 { 16, 5120, 2048, 1, 1, "cold qkv 1 of 16", 1 },
931 { 16, 2048, 4096, 1, 1, "cold o_proj 1 of 16", 1 },
932 };
933 const ChipPoint *cpts = g_cold == 2 ? spts : gpts;
934 for (size_t i = 0; i < 2; i++) {
935 const ChipPoint *p = &cpts[i];
936 if (g_only && !strstr(p->name, g_only)) continue;
937 const uint32_t STR = p->experts / 16u; /* experts per rotation set */
938 Weights W; weights_make(&W, p->experts, p->n, p->k, 9100 + (uint32_t)i);
939 uint32_t perm[128], st = 4242 + (uint32_t)i;
940 for (uint32_t e = 0; e < p->experts; e++) perm[e] = e;
941 for (uint32_t e = p->experts - 1u; e > 0; e--) { uint32_t j = lcg(&st) % (e + 1); uint32_t t = perm[e]; perm[e] = perm[j]; perm[j] = t; }
942 float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f);
943 float *y = malloc((size_t)p->groups * p->n * 4);
944 OmegaGpuFp8Tensor *t = NULL;
945 int rc = omega_gpu_fp8_tensor_upload(p->experts, p->n, p->k, W.w, W.s, &t);
946 OmegaGpuFp8Info info; memset(&info, 0, sizeof info);
947 if (rc == OMEGA_GPU_FP8_OK) rc = omega_gpu_fp8_gemv_grouped_f32(t, p->groups, perm, x, p->x_rows, y, &info); /* builds the kernel */
948 size_t bad = 0; double worst = rc == OMEGA_GPU_FP8_OK ? parity(&W, p->groups, perm, x, p->x_rows, y, &bad) : 1.0;
949 CHECK(rc == OMEGA_GPU_FP8_OK && bad == 0, "chip %s warm-up: rc=%s bad=%zu worst_rel=%.3e (%s)", p->name, omega_gpu_fp8_rc_name(rc), bad, worst, omega_gpu_fp8_last_error());
950 uint64_t *el = calloc(reps, sizeof *el); uint32_t done = 0; size_t bad_all = 0; double worst_all = worst;
951 if (g_evict) evict_host_caches();
952 for (uint32_t r = 0; r < reps && rc == OMEGA_GPU_FP8_OK; r++) {
953 const uint32_t *ids = perm + STR * (r % 16u);
954 OmegaGpuFp8Info ti;
955 if (omega_gpu_fp8_gemv_grouped_f32(t, p->groups, ids, x, p->x_rows, y, &ti) != OMEGA_GPU_FP8_OK) { rc = OMEGA_GPU_FP8_CHIP_FAIL; break; }
956 size_t b = 0; double w = parity(&W, p->groups, ids, x, p->x_rows, y, &b);
957 bad_all += b; if (w > worst_all) worst_all = w;
958 el[done++] = ti.elapsed_ns;
959 }
960 CHECK(rc == OMEGA_GPU_FP8_OK && done == reps && bad_all == 0, "chip %s: %u/%u timed launches, %zu elements off the oracle, worst_rel=%.3e (%s)", p->name, done, reps, bad_all, worst_all, omega_gpu_fp8_last_error());
961 uint64_t med = 0, lo = 0, hi = 0; double gbs = 0.0;
962 if (done) { qsort(el, done, sizeof *el, cmp_u64); med = el[done / 2]; lo = el[0]; hi = el[done - 1]; gbs = med ? (double)(info.weight_bytes + info.scale_bytes) / (double)med : 0.0; }
963 printf("chip %-24s variant=%d sched=%d rc=%-9s timed=%u bad=%zu worst_rel=%.3e grid=%ux%u lb=%u rows=%u warps=%u depth=%u bytes=%" PRIu64 " chip_med=%.1fus min=%.1fus max=%.1fus (%.1f GB/s, %.3f of 237.2)\n",
964 p->name, omega_gpu_fp8_variant(), omega_gpu_fp8_sched(), omega_gpu_fp8_rc_name(rc), done, bad_all, worst_all, info.grid_x, info.grid_y, info.lane_bytes, info.rows_per_warp,
965 info.warps_per_cta, info.depth, info.weight_bytes + info.scale_bytes, med / 1e3, lo / 1e3, hi / 1e3, gbs, gbs / 237.2);
966 if (out) fprintf(out, "%s{\"name\":\"%s\",\"experts\":%u,\"n\":%u,\"k\":%u,\"groups\":%u,\"x_rows\":%u,\"rc\":\"%s\",\"timed\":%u,\"bad\":%zu,\"worst_rel\":%.3e,"
967 "\"variant\":%d,\"sched\":%d,\"grid_x\":%u,\"grid_y\":%u,\"lane_bytes\":%u,\"rows_per_warp\":%u,\"warps_per_cta\":%u,\"depth\":%u,\"bytes\":%" PRIu64 ",\"chip_median_ns\":%" PRIu64 ",\"chip_min_ns\":%" PRIu64 ",\"chip_max_ns\":%" PRIu64 ",\"gbps_chip\":%.2f,\"evict\":%d,\"rotation_sets\":16}",
968 *first ? "" : ",", p->name, p->experts, p->n, p->k, p->groups, p->x_rows, omega_gpu_fp8_rc_name(rc), done, bad_all, worst_all,
969 omega_gpu_fp8_variant(), omega_gpu_fp8_sched(), info.grid_x, info.grid_y, info.lane_bytes, info.rows_per_warp, info.warps_per_cta, info.depth, info.weight_bytes + info.scale_bytes, med, lo, hi, gbs, g_evict);
970 *first = 0;
971 { /* GPU-stamped timing of the same rotation (the figure CUT5 reports) */
972 const uint32_t lists = reps < 2u * LIST_N ? 2u : (reps + LIST_N - 1u) / LIST_N;
973 uint64_t *e2 = calloc((size_t)lists * LIST_N, sizeof *e2); uint32_t n2 = 0; size_t b2 = 0; double w2 = 0.0;
974 int lrc = rc == OMEGA_GPU_FP8_OK ? cold_list_stamps(p, &W, t, perm, x, lists, e2, &n2, &b2, &w2) : -1;
975 CHECK(lrc == 0 && n2 == lists * LIST_N && b2 == 0, "chip %s GPU-stamped list: %u/%u launches, %zu elements off the oracle, worst_rel=%.3e", p->name, n2, lists * LIST_N, b2, w2);
976 uint64_t m2 = 0, lo2 = 0, hi2 = 0; double g2 = 0.0;
977 if (n2) { qsort(e2, n2, sizeof *e2, cmp_u64); m2 = e2[n2 / 2]; lo2 = e2[0]; hi2 = e2[n2 - 1]; g2 = m2 ? (double)(info.weight_bytes + info.scale_bytes) / (double)m2 : 0.0; }
978 printf("chip %-24s GPU-STAMPED coal=%d wfirst=%d launches=%u bad=%zu stamp_med=%.1fus min=%.1fus max=%.1fus (%.1f GB/s, %.3f of 237.2)\n",
979 p->name, omega_gpu_fp8_coal(), omega_gpu_fp8_wfirst(), n2, b2, m2 / 1e3, lo2 / 1e3, hi2 / 1e3, g2, g2 / 237.2);
980 if (out) fprintf(out, ",{\"name\":\"%s gpu-stamped\",\"coal\":%d,\"wfirst\":%d,\"sched\":%d,\"launches\":%u,\"bad\":%zu,\"worst_rel\":%.3e,\"bytes\":%" PRIu64 ",\"stamp_median_ns\":%" PRIu64 ",\"stamp_min_ns\":%" PRIu64 ",\"stamp_max_ns\":%" PRIu64 ",\"gbps_stamp\":%.2f,\"barrier\":\"WFI\",\"floor_subtracted\":0}",
981 p->name, omega_gpu_fp8_coal(), omega_gpu_fp8_wfirst(), omega_gpu_fp8_sched(), n2, b2, w2, info.weight_bytes + info.scale_bytes, m2, lo2, hi2, g2);
982 free(e2);
983 }
984 free(el);
985 /* mutants: each must be caught at this shape and this kernel configuration */
986 for (int m = 1; m <= 4 && rc == OMEGA_GPU_FP8_OK; m++) {
987 if (m == 3 && p->groups == 1) continue; /* mutant 3 needs groups > 1 (as in the --n/--k path) */
988 if (m == 4) omega_gpu_fp8_test_set_no_fold(1); else omega_gpu_fp8_test_set_mutant(m);
989 OmegaGpuFp8Tensor *tm = t;
990 if (m == 4) { tm = NULL; if (omega_gpu_fp8_tensor_upload(p->experts, p->n, p->k, W.w, W.s, &tm) != OMEGA_GPU_FP8_OK) tm = NULL; }
991 int r = tm ? omega_gpu_fp8_gemv_grouped_f32(tm, p->groups, perm, x, p->x_rows, y, NULL) : OMEGA_GPU_FP8_CHIP_FAIL;
992 size_t mb = 0; double mw = r == OMEGA_GPU_FP8_OK ? parity(&W, p->groups, perm, x, p->x_rows, y, &mb) : 1.0;
993 int caught = r != OMEGA_GPU_FP8_OK || mb > 0;
994 CHECK(caught, "chip %s mutant %d NOT caught", p->name, m);
995 printf("chip %-24s mutant %d: %s (rc=%s bad=%zu worst_rel=%.3e)\n", p->name, m, caught ? "caught" : "MISSED", omega_gpu_fp8_rc_name(r), mb, mw);
996 if (out) fprintf(out, ",{\"name\":\"%s mutant %d\",\"caught\":%d,\"rc\":\"%s\",\"bad\":%zu,\"worst_rel\":%.3e}", p->name, m, caught, omega_gpu_fp8_rc_name(r), mb, mw);
997 if (m == 4) { omega_gpu_fp8_test_set_no_fold(0); if (tm) omega_gpu_fp8_tensor_free(tm); } else omega_gpu_fp8_test_set_mutant(0);
998 }
999 if (t) omega_gpu_fp8_tensor_free(t);
1000 free(x); free(y); weights_free(&W);
1001 if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); break; }
1002 }
1003}
1004
1005/* --grid-ab "C:W,C:W,..." --reps R --seed S (A1 expert-grid, DecodeKernels 2026-10-27): the interleaved A/B of the grouped
1006 * launch's CTAs per group (C, 0 = the default rule) and warps per CTA (W, 0 = the default 32) at the Qwen3.6-35B-A3B
1007 * decode shapes: gate_up 9 of 144 x 1024 x 2048 (one x row), down 9 of 144 x 2048 x 512 (one x row per group); 144 =
1008 * 16 disjoint sets of 9, so a set returns only after 15 others (gate_up 302 MB in between, L2 24 MiB). Negative control:
1009 * o_proj 1 of 16 x 2048 x 4096 runs in every arm at the defaults (the arms touch grouped launches only) and must not move.
1010 * One sample = one GPU-stamped list of LIST_N launches (PCAS, WFI barrier, the decode graph's); its value is the mean
1011 * launch time (stamp[LIST_N] - stamp[0]) / LIST_N. Arm 0 is the reference: its first list is checked against the double
1012 * oracle; every later list of every arm must equal it bit for bit (a mismatch voids the run). The schedule is a seeded
1013 * shuffle of arms x shapes x reps. One JSON line per sample with CLOCK_REALTIME bounds for the 18091 in_flight tag. */
1014typedef struct { uint32_t ctas, warps; } GridArm;
1015static uint64_t real_ns(void) { struct timespec t; clock_gettime(CLOCK_REALTIME, &t); return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; }
1016static void grid_arm_apply(const GridArm *a, int grouped) {
1017 omega_gpu_fp8_set_cta_budget(grouped ? a->ctas : 0u);
1018 omega_gpu_fp8_set_shape(0u, 0u, grouped ? a->warps : 0u);
1019}
1020typedef struct { ChipPoint p; Weights W; OmegaGpuFp8Tensor *t; uint32_t perm[144]; float *x; OmegaGpuMem tab, xd, yd; float *ref; } GridShape;
1021static int grid_list(GridShape *s, OmegaGpuCmdList *cl, uint64_t *mean_ns, uint64_t *med_ns, OmegaGpuFp8Info *info) {
1022 const size_t ny = (size_t)s->p.groups * s->p.n;
1023 float *y = s->yd.cpu; for (size_t i = 0; i < (size_t)LIST_N * ny; i++) y[i] = -999.0f;
1024 if (omega_gpu_session_sync_to_gpu(&s->yd) != 0) return -1;
1025 /* one untimed host call at this configuration: builds the kernel and reports its grid */
1026 if (omega_gpu_fp8_gemv_grouped_f32(s->t, s->p.groups, s->perm, s->x, s->p.x_rows, y, info) != OMEGA_GPU_FP8_OK) return -1;
1027 for (size_t i = 0; i < ny; i++) y[i] = -999.0f;
1028 if (omega_gpu_session_sync_to_gpu(&s->yd) != 0) return -1;
1029 omega_gpu_session_lock();
1030 omega_gpu_cmdlist_reset(cl); int ok = 1;
1031 for (uint32_t i = 0; i < LIST_N && ok; i++)
1032 if (omega_gpu_fp8_gemv_grouped_record(cl, s->t, s->p.groups, s->tab.va + (uint64_t)(i % 16u) * s->p.groups * 16u, s->xd.va, s->p.x_rows, s->yd.va + (uint64_t)i * ny * 4u) != 0) ok = 0;
1033 OmegaGpuCmdListOpts o; memset(&o, 0, sizeof o); o.mode = OMEGA_GPU_CMDLIST_PCAS; o.barrier = OMEGA_GPU_CMDLIST_BARRIER_WFI; o.stamps = 1;
1034 OmegaGpuCmdListStats cs; memset(&cs, 0, sizeof cs);
1035 uint64_t sts[LIST_N + 1]; int cnt = -1;
1036 if (ok && omega_gpu_cmdlist_submit(cl, &o, &cs) != 0) ok = 0;
1037 if (ok) cnt = omega_gpu_cmdlist_stamps(cl, sts, LIST_N + 1);
1038 omega_gpu_session_unlock();
1039 if (!ok || cnt != (int)LIST_N + 1 || cs.sems_done != LIST_N) { printf("grid list %s: %s (stamps %d sems_done %u)\n", s->p.name, omega_gpu_fp8_last_error(), cnt, cs.sems_done); return -1; }
1040 if (omega_gpu_session_sync_to_cpu(&s->yd) != 0) return -1;
1041 uint64_t el[LIST_N]; for (uint32_t i = 0; i < LIST_N; i++) el[i] = sts[i + 1] - sts[i];
1042 qsort(el, LIST_N, sizeof *el, cmp_u64);
1043 *mean_ns = (sts[LIST_N] - sts[0]) / LIST_N; *med_ns = el[LIST_N / 2];
1044 return 0;
1045}
1046static int grid_ab(const char *arms_csv, uint32_t reps, uint32_t seed) {
1047 GridArm arms[16]; uint32_t na = 0;
1048 for (const char *q = arms_csv; *q && na < 16;) {
1049 char *e; arms[na].ctas = (uint32_t)strtoul(q, &e, 10);
1050 if (*e != ':') { printf("bad --grid-ab list (C:W,...)\n"); return 2; }
1051 arms[na].warps = (uint32_t)strtoul(e + 1, &e, 10); na++; q = e;
1052 if (*q == ',') q++; else if (*q) { printf("bad --grid-ab list (C:W,...)\n"); return 2; }
1053 }
1054 if (na < 2) { printf("--grid-ab needs at least two arms\n"); return 2; }
1055 static GridShape S[3];
1056 const ChipPoint pts[3] = {
1057 { 144, 1024, 2048, 9, 1, "q36 gate_up 9 of 144", 1 },
1058 { 144, 2048, 512, 9, 9, "q36 down 9 of 144", 1 },
1059 { 16, 2048, 4096, 1, 1, "q36 o_proj 1 of 16 (neg)", 1 },
1060 };
1061 OmegaGpuCmdList *cl = NULL;
1062 if (omega_gpu_cmdlist_create(LIST_N, &cl) != 0) { printf("cmdlist create: %s\n", omega_gpu_session_last_error()); return 1; }
1063 int ok = 1;
1064 for (uint32_t si = 0; si < 3 && ok; si++) {
1065 GridShape *s = &S[si]; s->p = pts[si];
1066 const uint32_t STR = s->p.experts / 16u;
1067 weights_make(&s->W, s->p.experts, s->p.n, s->p.k, 9300 + si);
1068 uint32_t st = 5150 + si;
1069 for (uint32_t e = 0; e < s->p.experts; e++) s->perm[e] = e;
1070 for (uint32_t e = s->p.experts - 1u; e > 0; e--) { uint32_t j = lcg(&st) % (e + 1); uint32_t t = s->perm[e]; s->perm[e] = s->perm[j]; s->perm[j] = t; }
1071 s->x = malloc((size_t)s->p.x_rows * s->p.k * 4); for (size_t j = 0; j < (size_t)s->p.x_rows * s->p.k; j++) s->x[j] = frand(&st, -1.0f, 1.0f);
1072 const size_t ny = (size_t)s->p.groups * s->p.n;
1073 if (omega_gpu_fp8_tensor_upload(s->p.experts, s->p.n, s->p.k, s->W.w, s->W.s, &s->t) != OMEGA_GPU_FP8_OK) { printf("upload %s: %s\n", s->p.name, omega_gpu_fp8_last_error()); ok = 0; break; }
1074 omega_gpu_session_lock();
1075 int arc = omega_gpu_session_alloc((size_t)16u * s->p.groups * 16u, &s->tab) | omega_gpu_session_alloc((size_t)s->p.x_rows * s->p.k * 4u, &s->xd) | omega_gpu_session_alloc((size_t)LIST_N * ny * 4u, &s->yd);
1076 omega_gpu_session_unlock();
1077 if (arc) { printf("alloc %s: %s\n", s->p.name, omega_gpu_session_last_error()); ok = 0; break; }
1078 uint64_t *tw = s->tab.cpu;
1079 for (uint32_t r = 0; r < 16u && ok; r++) for (uint32_t g = 0; g < s->p.groups; g++)
1080 if (omega_gpu_fp8_tensor_entry(s->t, s->perm[STR * r + g], &tw[2u * (r * s->p.groups + g)], &tw[2u * (r * s->p.groups + g) + 1u]) != 0) ok = 0;
1081 for (uint32_t r = 0; r < s->p.x_rows; r++) omega_fp8_pack_x_f32(s->x + (size_t)r * s->p.k, s->p.k, (float *)s->xd.cpu + (size_t)r * s->p.k);
1082 if (!ok || omega_gpu_session_sync_to_gpu(&s->tab) != 0 || omega_gpu_session_sync_to_gpu(&s->xd) != 0) { ok = 0; break; }
1083 /* reference: arm 0's first list, every launch against the double oracle */
1084 grid_arm_apply(&arms[0], s->p.groups > 1u);
1085 uint64_t mn, md; OmegaGpuFp8Info info;
1086 if (grid_list(s, cl, &mn, &md, &info) != 0) { ok = 0; break; }
1087 size_t bad = 0; double worst = 0.0;
1088 for (uint32_t i = 0; i < LIST_N; i++) { size_t b = 0; double w = parity(&s->W, s->p.groups, s->perm + STR * (i % 16u), s->x, s->p.x_rows, (float *)s->yd.cpu + (size_t)i * ny, &b); bad += b; if (w > worst) worst = w; }
1089 CHECK(bad == 0, "grid-ab %s reference list (arm 0 %u:%u) vs the double oracle: %zu elements off, worst_rel %.3e", s->p.name, arms[0].ctas, arms[0].warps, bad, worst);
1090 printf("grid-ab reference %-26s arm 0 grid %ux%u warps %u depth %u: %zu off the oracle, worst_rel %.3e\n", s->p.name, info.grid_x, info.grid_y, info.warps_per_cta, info.depth, bad, worst);
1091 s->ref = malloc((size_t)LIST_N * ny * 4); memcpy(s->ref, s->yd.cpu, (size_t)LIST_N * ny * 4);
1092 if (bad) ok = 0;
1093 }
1094 if (ok && g_evict) evict_host_caches(); /* uploads are served from the CPU caches until evicted (g_evict note) */
1095 const uint32_t ns = na * 3u * reps; uint32_t *sched = malloc((size_t)ns * 4), sd = seed, wrong = 0, done = 0;
1096 for (uint32_t i = 0; i < ns; i++) sched[i] = i % (na * 3u);
1097 for (uint32_t i = ns - 1; i > 0; i--) { uint32_t j = lcg(&sd) % (i + 1), t = sched[i]; sched[i] = sched[j]; sched[j] = t; }
1098 for (uint32_t i = 0; i < ns && ok; i++) {
1099 const uint32_t a = sched[i] / 3u, si = sched[i] % 3u; GridShape *s = &S[si];
1100 const size_t ny = (size_t)s->p.groups * s->p.n;
1101 grid_arm_apply(&arms[a], s->p.groups > 1u);
1102 uint64_t mn = 0, md = 0; OmegaGpuFp8Info info; memset(&info, 0, sizeof info);
1103 const uint64_t t0 = real_ns();
1104 const int rc = grid_list(s, cl, &mn, &md, &info);
1105 const uint64_t t1 = real_ns();
1106 const int exact = rc == 0 && memcmp(s->yd.cpu, s->ref, (size_t)LIST_N * ny * 4) == 0;
1107 if (!exact) wrong++;
1108 printf("GAB {\"i\":%u,\"arm\":%u,\"ctas\":%u,\"warps\":%u,\"shape\":%u,\"grid_x\":%u,\"grid_y\":%u,\"warps_per_cta\":%u,\"mean_ns\":%" PRIu64 ",\"med_ns\":%" PRIu64 ",\"t0_ns\":%" PRIu64 ",\"t1_ns\":%" PRIu64 ",\"exact\":%d}\n",
1109 i, a, arms[a].ctas, arms[a].warps, si, info.grid_x, info.grid_y, info.warps_per_cta, mn, md, t0, t1, exact);
1110 done++;
1111 if (!exact) { printf("grid-ab sample %u (%s, arm %u %u:%u): %s\n", i, s->p.name, a, arms[a].ctas, arms[a].warps, rc ? omega_gpu_fp8_last_error() : "outputs differ from the arm-0 reference"); break; }
1112 }
1113 CHECK(ok && wrong == 0 && done == ns, "grid-ab: %u of %u samples ran, %u not bit-identical to arm 0 (a mismatch voids the run)", done, ns, wrong);
1114 grid_arm_apply(&(GridArm){ 0u, 0u }, 0);
1115 /* the bit check must be able to say no: mutant 1 (scale dropped) at arm 1 must differ from the reference */
1116 if (ok) {
1117 GridShape *s = &S[0]; uint64_t mn, md; OmegaGpuFp8Info info;
1118 grid_arm_apply(&arms[1], 1); omega_gpu_fp8_test_set_mutant(1);
1119 const int rc = grid_list(s, cl, &mn, &md, &info);
1120 const int caught = rc != 0 || memcmp(s->yd.cpu, s->ref, (size_t)LIST_N * s->p.groups * s->p.n * 4) != 0;
1121 CHECK(caught, "grid-ab mutant 1 at arm 1 must differ from the reference");
1122 printf("grid-ab mutant 1 at arm 1 (%u:%u) %s: %s\n", arms[1].ctas, arms[1].warps, s->p.name, caught ? "caught (outputs differ)" : "NOT CAUGHT");
1123 omega_gpu_fp8_test_set_mutant(0); grid_arm_apply(&(GridArm){ 0u, 0u }, 0);
1124 }
1125 for (uint32_t si = 0; si < 3; si++) {
1126 GridShape *s = &S[si];
1127 omega_gpu_session_lock(); omega_gpu_session_free(&s->tab); omega_gpu_session_free(&s->xd); omega_gpu_session_free(&s->yd); omega_gpu_session_unlock();
1128 if (s->t) omega_gpu_fp8_tensor_free(s->t);
1129 free(s->x); free(s->ref); if (s->W.w) weights_free(&s->W);
1130 }
1131 omega_gpu_cmdlist_free(cl); free(sched);
1132 return g_failed ? 1 : 0;
1133}
1134
1135static int chip_run(const char *out_path, uint32_t reps) {
1136 FILE *out = out_path ? test_out_open(out_path) : NULL;
1137 if (out_path && !out) { printf("cannot open %s\n", out_path); return 1; }
1138 if (out) fprintf(out, "{\"test\":\"OMEGA_GPU_FP8_GEMV\",\"points\":[");
1139 static const ChipPoint pts[] = {
1140 { 1, 128, 256, 1, 1, "k256 n128", 1 },
1141 { 1, 256, 768, 1, 1, "k768 n256", 1 },
1142 { 1, 384, 2048, 1, 1, "k2048 n384", 1 },
1143 { 1, 768, 2048, 1, 1, "gate 768x2048", 1 },
1144 { 1, 1536, 2048, 1, 1, "gate+up 1536x2048", 1 },
1145 { 1, 2048, 768, 1, 1, "down 2048x768", 1 },
1146 { 1, 4096, 2048, 1, 1, "q_proj 4096x2048", 1 },
1147 { 1, 512, 2048, 1, 1, "k_proj 512x2048", 1 },
1148 { 1, 2048, 4096, 1, 1, "o_proj 2048x4096", 1 },
1149 { 1, 5120, 2048, 1, 1, "qkv fused 5120x2048", 1 },
1150 { 8, 1536, 2048, 8, 1, "8 experts gate+up shared x", 1 },
1151 { 8, 2048, 768, 8, 8, "8 experts down per-group x", 1 },
1152 { 16, 1536, 2048, 8, 1, "8 of 16 experts gate+up", 1 },
1153 { 1, 16384, 2048, 1, 1, "large 16384x2048", 1 },
1154 /* Qwen3.8-27B dense shapes (omega#541) and the new width cap */
1155 { 1, 17408, 5120, 1, 1, "q38 gate 17408x5120", 1 },
1156 { 1, 5120, 17408, 1, 1, "q38 down 5120x17408", 1 },
1157 { 1, 12288, 5120, 1, 1, "q38 q_proj 12288x5120", 1 },
1158 { 1, 1024, 5120, 1, 1, "q38 k_proj 1024x5120", 1 },
1159 { 1, 10240, 5120, 1, 1, "q38 in_proj_qkv 10240x5120", 1 },
1160 { 1, 6144, 5120, 1, 1, "q38 in_proj_z 6144x5120", 1 },
1161 { 1, 5120, 6144, 1, 1, "q38 out_proj 5120x6144", 1 },
1162 { 1, 256, 32768, 1, 1, "width cap 256x32768", 1 },
1163 };
1164 /* 0. one-hot conversion on the chip: row r holds code r at column 0 (NaN codes as 0x00), x = e_0, scale 1.
1165 * y[r] must equal the reference bit for bit. The e4m3 subnormal codes 0x01..0x07 (and negatives) travel
1166 * through the FFMA chain as f32 subnormals (e4m3 * 2^-120); a flush-to-zero FFMA would return 0 here. */
1167 int one_hot_exact = -1;
1168 {
1169 uint8_t *w = calloc(256, 256); uint16_t s[4]; float x[256] = { 0 }, y[256]; OmegaGpuFp8Tensor *t = NULL;
1170 for (int b = 0; b < 4; b++) s[b] = bf16_of(1.0f);
1171 for (int r = 0; r < 256; r++) w[r * 256] = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0 : (uint8_t)r;
1172 x[0] = 1.0f;
1173 int rc = omega_gpu_fp8_tensor_upload(1, 256, 256, w, s, &t);
1174 if (rc == OMEGA_GPU_FP8_OK) rc = omega_gpu_fp8_gemv_f32(t, 0, x, y, NULL);
1175 one_hot_exact = 0;
1176 if (rc == OMEGA_GPU_FP8_OK) for (int r = 0; r < 256; r++) {
1177 float ref = omega_fp8_e4m3_is_nan((uint8_t)r) ? 0.0f : omega_fp8_e4m3_ref((uint8_t)r);
1178 if (y[r] == ref) one_hot_exact++; else CHECK(0, "chip one-hot code 0x%02x: kernel %a, reference %a", r, y[r], ref);
1179 }
1180 if (g_depth_forced && rc == OMEGA_GPU_FP8_CODEGEN_FAIL) printf("chip one-hot conversion: skipped (forced depth does not fit k=256)\n");
1181 else CHECK(rc == OMEGA_GPU_FP8_OK && one_hot_exact == 256, "chip one-hot conversion: rc=%s exact=%d/256", omega_gpu_fp8_rc_name(rc), one_hot_exact);
1182 printf("chip one-hot conversion: rc=%s %d/256 rows exact (subnormal codes 0x01..0x07 included: no flush to zero)\n", omega_gpu_fp8_rc_name(rc), one_hot_exact);
1183 if (out) fprintf(out, "{\"name\":\"one-hot conversion\",\"rc\":\"%s\",\"exact_rows\":%d,\"of\":256}", omega_gpu_fp8_rc_name(rc), one_hot_exact);
1184 if (t) omega_gpu_fp8_tensor_free(t);
1185 free(w);
1186 }
1187 static ChipPoint custom; const ChipPoint *P = pts; size_t npts = sizeof pts / sizeof pts[0];
1188 if (g_custom_n && !g_custom_k) { CHECK(0, "--n needs --k"); if (out) fclose(out); return 1; }
1189 if (g_custom_n) { snprintf(g_custom_name, sizeof g_custom_name, "custom %ux%u", g_custom_n, g_custom_k); custom = (ChipPoint){ 1, g_custom_n, g_custom_k, 1, 1, g_custom_name, 1 }; P = &custom; npts = 1; }
1190 int first = 1;
1191 first = out ? 0 : 1;
1192 if (g_cold) npts = 0; /* --grouped-cold: the two real expert shapes instead of the battery */
1193 for (size_t i = 0; i < npts; i++) {
1194 const ChipPoint *p = &P[i];
1195 if (g_only && !strstr(p->name, g_only)) continue;
1196 Weights W; weights_make(&W, p->experts, p->n, p->k, 5000 + (uint32_t)i);
1197 uint32_t ids[8]; uint32_t st = 99 + (uint32_t)i;
1198 for (uint32_t g = 0; g < p->groups; g++) ids[g] = (p->experts > p->groups ? lcg(&st) % p->experts : (p->groups - 1 - g) % p->experts);
1199 float *x = malloc((size_t)p->x_rows * p->k * 4); for (size_t j = 0; j < (size_t)p->x_rows * p->k; j++) x[j] = frand(&st, -1.0f, 1.0f);
1200 float *y = malloc((size_t)p->groups * p->n * 4), *y2 = malloc((size_t)p->groups * p->n * 4);
1201 OmegaGpuFp8Tensor *t = NULL;
1202 double t0 = now_ms();
1203 int rc = omega_gpu_fp8_tensor_upload(p->experts, p->n, p->k, W.w, W.s, &t);
1204 double up_ms = now_ms() - t0;
1205 OmegaGpuFp8Info info; memset(&info, 0, sizeof info);
1206 if (rc == OMEGA_GPU_FP8_OK) rc = omega_gpu_fp8_gemv_grouped_f32(t, p->groups, ids, x, p->x_rows, y, &info);
1207 size_t bad = 0; double worst = rc == OMEGA_GPU_FP8_OK ? parity(&W, p->groups, ids, x, p->x_rows, y, &bad) : 1.0;
1208 /* the expected path: the GEMV kernel, or (variant 2 only, outside its shape rule) the general fallback */
1209 const int want_general = omega_gpu_fp8_variant() == 2 && !v2_can_build(p->n, p->k);
1210 int ok = rc == OMEGA_GPU_FP8_OK && bad == 0 && (int)info.general == want_general;
1211 const char *path = info.general ? "general" : "kernel";
1212 /* second call: the same path, bit-identical, and a kernel cache hit when a kernel served it */
1213 int same = 0; OmegaGpuFp8Info i2; memset(&i2, 0, sizeof i2);
1214 if (ok) { int r2 = omega_gpu_fp8_gemv_grouped_f32(t, p->groups, ids, x, p->x_rows, y2, &i2); same = r2 == OMEGA_GPU_FP8_OK && memcmp(y, y2, (size_t)p->groups * p->n * 4) == 0 && i2.general == info.general && (info.general || i2.kernel_cache_hit); }
1215 CHECK(ok && same, "chip %s: rc=%s bad=%zu worst_rel=%.3e path=%s (want %s) second-call-identical=%d (%s)", p->name, omega_gpu_fp8_rc_name(rc), bad, worst, path, want_general ? "general" : "kernel", same, omega_gpu_fp8_last_error());
1216 /* timing: median of reps (the kernel only; the general fallback is not this battery's measurement) */
1217 uint64_t *el = calloc(reps, sizeof *el), *cl = calloc(reps, sizeof *cl);
1218 uint32_t done = 0;
1219 if (g_evict) evict_host_caches();
1220 for (uint32_t r = 0; r < reps && ok && !info.general; r++) {
1221 OmegaGpuFp8Info ti; if (omega_gpu_fp8_gemv_grouped_f32(t, p->groups, ids, x, p->x_rows, y2, &ti) != OMEGA_GPU_FP8_OK) break;
1222 el[r] = ti.elapsed_ns; cl[r] = ti.call_ns; done++;
1223 }
1224 uint64_t med_el = 0, med_cl = 0; double gbs = 0.0, gbs_call = 0.0;
1225 if (done) { qsort(el, done, sizeof *el, cmp_u64); qsort(cl, done, sizeof *cl, cmp_u64); med_el = el[done / 2]; med_cl = cl[done / 2];
1226 gbs = med_el ? (double)(info.weight_bytes + info.scale_bytes) / (double)med_el : 0.0; gbs_call = med_cl ? (double)(info.weight_bytes + info.scale_bytes) / (double)med_cl : 0.0; }
1227 printf("chip %-32s variant=%d path=%s rc=%-9s bad=%zu worst_rel=%.3e grid=%ux%u lb=%u rows=%u warps=%u depth=%u bytes=%" PRIu64 " upload=%.1fms chip_med=%.1fus (%.1f GB/s) call_med=%.1fus (%.1f GB/s) reps=%u\n",
1228 p->name, omega_gpu_fp8_variant(), path, omega_gpu_fp8_rc_name(rc), bad, worst, info.grid_x, info.grid_y, info.lane_bytes, info.rows_per_warp, info.warps_per_cta, info.depth,
1229 info.weight_bytes + info.scale_bytes, up_ms, med_el / 1e3, gbs, med_cl / 1e3, gbs_call, done);
1230 if (out) fprintf(out, "%s{\"name\":\"%s\",\"experts\":%u,\"n\":%u,\"k\":%u,\"groups\":%u,\"x_rows\":%u,\"rc\":\"%s\",\"general\":%u,\"bad\":%zu,\"worst_rel\":%.3e,\"second_call_identical\":%d,"
1231 "\"variant\":%d,\"grid_x\":%u,\"grid_y\":%u,\"lane_bytes\":%u,\"rows_per_warp\":%u,\"warps_per_cta\":%u,\"depth\":%u,\"bytes\":%" PRIu64 ",\"upload_ms\":%.2f,\"chip_median_ns\":%" PRIu64 ",\"gbps_chip\":%.2f,\"call_median_ns\":%" PRIu64 ",\"gbps_call\":%.2f,\"reps\":%u,\"marker\":%u,\"evict\":%d}",
1232 first ? "" : ",", p->name, p->experts, p->n, p->k, p->groups, p->x_rows, omega_gpu_fp8_rc_name(rc), info.general, bad, worst, same,
1233 omega_gpu_fp8_variant(), info.grid_x, info.grid_y, info.lane_bytes, info.rows_per_warp, info.warps_per_cta, info.depth, info.weight_bytes + info.scale_bytes, up_ms, med_el, gbs, med_cl, gbs_call, done, info.completion_marker, g_evict);
1234 first = 0;
1235 free(el); free(cl);
1236 /* mutants on the first grouped point and the gate shape: each must be caught on the chip */
1237 if (ok && (g_custom_n || i == 4 || i == 10)) {
1238 for (int m = 1; m <= 4; m++) {
1239 if (m == 3 && p->groups == 1) continue;
1240 if (m == 4) omega_gpu_fp8_test_set_no_fold(1); else omega_gpu_fp8_test_set_mutant(m);
1241 OmegaGpuFp8Tensor *tm = t;
1242 if (m == 4) { tm = NULL; if (omega_gpu_fp8_tensor_upload(p->experts, p->n, p->k, W.w, W.s, &tm) != OMEGA_GPU_FP8_OK) tm = NULL; }
1243 int r = tm ? omega_gpu_fp8_gemv_grouped_f32(tm, p->groups, ids, x, p->x_rows, y2, NULL) : OMEGA_GPU_FP8_CHIP_FAIL;
1244 size_t mb = 0; double mw = r == OMEGA_GPU_FP8_OK ? parity(&W, p->groups, ids, x, p->x_rows, y2, &mb) : 1.0;
1245 int caught = r != OMEGA_GPU_FP8_OK || mb > 0;
1246 CHECK(caught, "chip %s mutant %d NOT caught", p->name, m);
1247 printf("chip %-32s mutant %d: %s (rc=%s bad=%zu worst_rel=%.3e)\n", p->name, m, caught ? "caught" : "MISSED", omega_gpu_fp8_rc_name(r), mb, mw);
1248 if (out) fprintf(out, ",{\"name\":\"%s mutant %d\",\"caught\":%d,\"rc\":\"%s\",\"bad\":%zu,\"worst_rel\":%.3e}", p->name, m, caught, omega_gpu_fp8_rc_name(r), mb, mw);
1249 if (m == 4) { omega_gpu_fp8_test_set_no_fold(0); if (tm) omega_gpu_fp8_tensor_free(tm); } else omega_gpu_fp8_test_set_mutant(0);
1250 }
1251 }
1252 omega_gpu_fp8_tensor_free(t);
1253 free(x); free(y); free(y2); weights_free(&W);
1254 if (omega_gpu_session_is_blocked()) { printf("session latched: stopping\n"); break; }
1255 }
1256 if (g_cold && !omega_gpu_session_is_blocked()) cold_points(out, reps, &first);
1257 if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"device_opens\":%u,\"verdict\":\"%s\"}\n", g_checks, g_failed, omega_gpu_session_open_count(), g_failed == 0 ? "OMEGA_GPU_FP8_GEMV_PASS" : "OMEGA_GPU_FP8_GEMV_FAIL"); fclose(out); }
1258 return 0;
1259}
1260
1261/* L310: the grouped-launch CTA rule, pure, no chip. 8 groups keep the measured 6; 9 groups (the 35B) get 5 = one wave of 48. */
1262static void rule_checks(void) {
1263 static const struct { uint32_t groups, forced; int wave, want; } c[] = {
1264 {8, 0, 1, 6}, {9, 0, 1, 5}, {9, 0, 0, 6}, {9, 5, 0, 5}, {9, 5, 1, 5}, {9, 300, 1, 5}, {2, 0, 1, 6}, {48, 0, 1, 1}, {64, 0, 1, 1}, {0, 0, 1, 6} };
1265 for (size_t i = 0; i < sizeof c / sizeof c[0]; i++) {
1266 uint32_t got = omega_gpu_fp8_grouped_ctas_rule(c[i].groups, c[i].forced, c[i].wave);
1267 if (got != (uint32_t)c[i].want) { fprintf(stderr, "grouped CTA rule: groups %u forced %u wave %d: got %u want %d\n", c[i].groups, c[i].forced, c[i].wave, got, c[i].want); exit(1); }
1268 }
1269 /* A1 (2026-10-27): the wave rule is the default; AIEN_OMEGA_FP8_GROUPED_WAVE=0 restores the compiled 6 (read once) */
1270 const char *we = getenv("AIEN_OMEGA_FP8_GROUPED_WAVE"), *ce = getenv("AIEN_OMEGA_FP8_GROUPED_CTAS");
1271 const uint32_t want9 = (ce && *ce) ? 0u : (we && we[0] == '0' && !we[1]) ? 6u : 5u, got9 = omega_gpu_fp8_grouped_ctas_auto(9), got8 = omega_gpu_fp8_grouped_ctas_auto(8);
1272 if (want9 && (got9 != want9 || got8 != 6u)) { fprintf(stderr, "grouped CTA default: auto(9) %u want %u, auto(8) %u want 6\n", got9, want9, got8); exit(1); }
1273 printf("grouped CTA rule: %zu/%zu ok (8 groups -> 6, 9 groups -> 5); default auto(8) %u auto(9) %u\n", sizeof c / sizeof c[0], sizeof c / sizeof c[0], got8, got9);
1274}
1275
1276int main(int argc, char **argv) {
1277 rule_checks();
1278 int host = 0, sim = 0; const char *out_path = NULL, *grid_arms = NULL; uint32_t reps = 20, lb = 0, rows = 0, warps = 0, budget = 0, spin = 2000, depth = 0, seed = 1; int depth_set = 0;
1279 for (int i = 1; i < argc; i++) {
1280 if (strcmp(argv[i], "--host-only") == 0) host = 1;
1281 else if (strcmp(argv[i], "--sim") == 0) sim = 1;
1282 else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i];
1283 else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]);
1284 else if (strcmp(argv[i], "--lane-bytes") == 0 && i + 1 < argc) lb = (uint32_t)atoi(argv[++i]);
1285 else if (strcmp(argv[i], "--rows") == 0 && i + 1 < argc) rows = (uint32_t)atoi(argv[++i]);
1286 else if (strcmp(argv[i], "--warps") == 0 && i + 1 < argc) warps = (uint32_t)atoi(argv[++i]);
1287 else if (strcmp(argv[i], "--cta-budget") == 0 && i + 1 < argc) budget = (uint32_t)atoi(argv[++i]);
1288 else if (strcmp(argv[i], "--depth") == 0 && i + 1 < argc) { depth_set = 1; depth = (uint32_t)atoi(argv[++i]); }
1289 else if (strcmp(argv[i], "--spin-us") == 0 && i + 1 < argc) spin = (uint32_t)atoi(argv[++i]);
1290 else if (strcmp(argv[i], "--no-evict") == 0) g_evict = 0;
1291 else if (strcmp(argv[i], "--only") == 0 && i + 1 < argc) g_only = argv[++i];
1292 else if (strcmp(argv[i], "--n") == 0 && i + 1 < argc) g_custom_n = (uint32_t)atoi(argv[++i]);
1293 else if (strcmp(argv[i], "--k") == 0 && i + 1 < argc) g_custom_k = (uint32_t)atoi(argv[++i]);
1294 else if (strcmp(argv[i], "--gpr-pad") == 0 && i + 1 < argc) omega_gpu_fp8_set_gpr_pad((uint32_t)atoi(argv[++i]));
1295 else if (strcmp(argv[i], "--variant") == 0 && i + 1 < argc) omega_gpu_fp8_set_variant(atoi(argv[++i])); /* 1 (default) or 2 (W-L2c row-pipelined) */
1296 else if (strcmp(argv[i], "--sched") == 0 && i + 1 < argc) omega_gpu_fp8_set_sched(atoi(argv[++i])); /* CUT5: 0 (default) or 1 (pipelined decode + stall pass) */
1297 else if (strcmp(argv[i], "--coal") == 0 && i + 1 < argc) { omega_gpu_fp8_set_coal(atoi(argv[++i])); g_coal_arg = 1; } /* CUT5 variant A: coalesced output through shared slots */
1298 else if (strcmp(argv[i], "--wfirst") == 0 && i + 1 < argc) omega_gpu_fp8_set_wfirst(atoi(argv[++i])); /* CUT5 variant B: weight loads before the x loads */
1299 else if (strcmp(argv[i], "--coal-default") == 0) { coal_default_check(); printf("gpu_fp8_api_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); return g_failed ? 1 : 0; } /* variant A default vs env only */
1300 else if (strcmp(argv[i], "--deep-default") == 0) { deep_default_check(); printf("gpu_fp8_api_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); return g_failed ? 1 : 0; } /* deep default vs env only */
1301 else if (strcmp(argv[i], "--grouped-cold") == 0) g_cold = 1; /* CUT5: the two decode expert launches, 8 of 128, L2 defeated */
1302 else if (strcmp(argv[i], "--cold-single") == 0) g_cold = 2; /* SPEED-1B: the two single projections qkv / o_proj, L2 defeated */
1303 else if (strcmp(argv[i], "--dump-stamps") == 0) g_dump_stamps = 1;
1304 else if (strcmp(argv[i], "--grid-ab") == 0 && i + 1 < argc) grid_arms = argv[++i]; /* A1: interleaved grouped-grid A/B, "C:W,..." */
1305 else if (strcmp(argv[i], "--seed") == 0 && i + 1 < argc) seed = (uint32_t)strtoul(argv[++i], NULL, 0);
1306 else { printf("unknown argument %s\n", argv[i]); return 2; }
1307 }
1308 if (host) host_only();
1309 if (sim) sim_battery(budget ? budget : 4);
1310 if (!host && !sim) {
1311 if (lb || rows || warps) omega_gpu_fp8_set_shape(lb, rows, warps);
1312 if (budget) omega_gpu_fp8_set_cta_budget(budget);
1313 if (depth_set) { omega_gpu_fp8_set_depth(1, depth); g_depth_forced = 1; }
1314 (void)omega_gpu_session_set_spin_us(spin);
1315 int grid_rc = 0;
1316 if (grid_arms) grid_rc = grid_ab(grid_arms, reps ? reps : 1, seed); else chip_run(out_path, reps ? reps : 1);
1317 omega_gpu_session_close();
1318 if (grid_rc) return grid_rc;
1319 }
1320 printf("gpu_fp8_api_test: %d checks, %d failed: %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS");
1321 return g_failed ? 1 : 0;
1322}