interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / tests / gpu_elementwise_test.c

503 lines · 35049 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* gpu_elementwise_test: FB-1 cut 4 gate for omega_gpu_elementwise_api.
18 *
19 * ./gpu_elementwise_test --host-only refusals, codegen, word fixtures, register budget,
20 * listing check by Omega's own disassembler
21 * ./gpu_elementwise_test --out receipt.json chip gate: every op against the host oracle, then its mutant
22 * (a deliberately wrong kernel) which the same check must catch
23 * ./gpu_elementwise_test --timing --out t.json cut 4b gate: persistent device, 100 calls each of rmsnorm 1x2048
24 * and swiglu 5632 under 0.5 ms median, one device open per process
25 *
26 * Oracles re-state aien-sovereign-core crates/aien-inference-abi/src/tensor.rs (main 5fdab70) in C:
27 * rmsnorm sums in f64, rope computes cos/sin in f64 and casts to f32 before f32 math, swiglu is f64.
28 * This file is compiled with -ffp-contract=off so the f32 oracle math has no hidden fused multiply-add.
29 *
30 * Tolerances (why): EX2 1e-6 rel (PTX ex2.approx.f32: 2^-22.5 rel, we allow 2x). XCHG exact.
31 * RMSNORM 1e-5 rel + 1e-6 abs (f32 sum of up to 16384 squares against an f64 sum, plus RSQ seed with one
32 * Newton step; the mutant moves the scale by about 40 percent). ROPE exact (same f32 ops, same order).
33 * SWIGLU 1e-5 rel + 1e-6 abs (EX2 and RCP approximations, each about 2^-22 rel; the mutant flips the sign
34 * of the exponent, which is wrong by a factor of e^(2g)).
35 */
36#include "omega_gpu_elementwise_api.h"
37#include "omega_blackwell_codegen.h"
38#include "omega_gpu_session.h"
39#include "omega_sm121_disasm.h"
40#include <inttypes.h>
41#include <math.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <string.h>
45#include <time.h>
46#include <unistd.h>
47#include <float.h>
48#include "bw_mufu_ftz.h"
49
50static int g_checks, g_failed;
51#define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0)
52
53static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; }
54static float frand(uint32_t *s, float lo, float hi) { return lo + (hi - lo) * ((float)(lcg(s) >> 8) / 16777216.0f); }
55
56/* ----------------------------------------------------------------- oracles */
57static void oracle_rmsnorm(const float *x, const float *w, float eps, float *out, size_t dim) {
58 double ss = 0.0;
59 for (size_t i = 0; i < dim; i++) ss += (double)x[i] * (double)x[i];
60 double mean = ss / (double)dim;
61 float scale = (float)(1.0 / sqrt(mean + (double)eps));
62 for (size_t i = 0; i < dim; i++) { float t = x[i] * scale; out[i] = t * w[i]; }
63}
64static void oracle_rope_tables(size_t head_dim, size_t pos, float theta, float *cos_half, float *sin_half) {
65 size_t half = head_dim / 2;
66 for (size_t i = 0; i < half; i++) {
67 double exponent = (double)(2 * i) / (double)head_dim;
68 double freq = 1.0 / pow((double)theta, exponent);
69 double rot = (double)pos * freq;
70 sin_half[i] = (float)sin(rot);
71 cos_half[i] = (float)cos(rot);
72 }
73}
74static void oracle_rope(const float *v, size_t heads, size_t head_dim, const float *cos_half, const float *sin_half, float *out) {
75 size_t half = head_dim / 2;
76 for (size_t h = 0; h < heads; h++)
77 for (size_t i = 0; i < half; i++) {
78 size_t i0 = h * head_dim + i, i1 = i0 + half;
79 float q0 = v[i0], q1 = v[i1], c = cos_half[i], s = sin_half[i];
80 float a = q0 * c, b = q1 * s; out[i0] = a - b;
81 float d = q0 * s, e = q1 * c; out[i1] = d + e;
82 }
83}
84static void oracle_swiglu(const float *g, const float *u, float *out, size_t n) {
85 for (size_t i = 0; i < n; i++) { double gg = g[i]; double silu = gg / (1.0 + exp(-gg)); out[i] = (float)(silu * (double)u[i]); }
86}
87
88/* |got - want| <= rel*|want| + abs; returns the number of violations and the worst scaled error */
89static size_t compare(const float *got, const float *want, size_t n, double rel, double abs_tol, double *worst) {
90 size_t bad = 0; *worst = 0.0;
91 for (size_t i = 0; i < n; i++) {
92 double d = fabs((double)got[i] - (double)want[i]);
93 double lim = rel * fabs((double)want[i]) + abs_tol;
94 double scaled = lim > 0 ? d / lim : (d > 0 ? INFINITY : 0.0);
95 if (scaled > *worst) *worst = scaled;
96 if (!(d <= lim)) bad++; /* NaN counts as bad */
97 }
98 return bad;
99}
100
101/* ------------------------------------------------------------- host only */
102static int sm121dis_check(OmegaGpuEwOp op, const char *name, const char *const *must, int n_must) {
103 OmegaBlackwellKernel k; memset(&k, 0, sizeof k);
104 if (omega_gpu_elementwise_codegen(op, NULL, 0.0f, &k) != OMEGA_GPU_EW_OK) return -1;
105 char lst[64];
106 snprintf(lst, sizeof lst, "/tmp/omega_ew_%s_%d.sass.XXXXXX", name, (int)getpid());
107 int fd = mkstemp(lst); /* private, unique listing; read back the same descriptor */
108 FILE *f = fd >= 0 ? fdopen(fd, "w+") : NULL;
109 if (!f) { if (fd >= 0) close(fd); free(k.code); return -1; }
110 int rc = omega_sm121_listing(k.code, k.code_size, f);
111 free(k.code);
112 if (fflush(f) != 0 || fseek(f, 0, SEEK_SET) != 0) { fclose(f); return -1; }
113 FILE *l = f;
114 char line[512]; int seen[16] = {0}; int bad = 0, insns = 0;
115 while (fgets(line, sizeof line, l)) {
116 if (!strstr(line, "/*")) continue; /* every address line, 0x1000 and up too */
117 insns++;
118 if (strstr(line, "?") || strstr(line, "error")) bad++;
119 for (int i = 0; i < n_must; i++) if (strstr(line, must[i])) seen[i] = 1;
120 }
121 if (ferror(l)) rc = -1;
122 if (fclose(l) != 0) rc = -1;
123 int miss = 0;
124 for (int i = 0; i < n_must; i++) if (!seen[i]) { printf(" %s: sm121dis listing lacks %s\n", name, must[i]); miss++; }
125 printf("sm121dis %s: rc=%d insns=%d undecodable=%d missing=%d (%s)\n", name, rc, insns, bad, miss, lst);
126 return (rc == 0 && bad == 0 && miss == 0) ? 0 : -1;
127}
128
129static void host_only(void) {
130 CHECK(omega_blackwell_verify_codegen_fixtures_fb1cut4() == 0, "word fixtures MUFU_EX2 / BAR_SYNC / LDS32 / STS32 (rc %d)", omega_blackwell_verify_codegen_fixtures_fb1cut4());
131 float a[256] = {0}, b[256] = {0}, c[256] = {0};
132 CHECK(omega_gpu_rmsnorm_f32(0, 128, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "rows=0 refused");
133 CHECK(omega_gpu_rmsnorm_f32(1, 100, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "dim not a multiple of 128 refused");
134 CHECK(omega_gpu_rmsnorm_f32(1, OMEGA_GPU_EW_MAX_DIM + 128, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_TOO_LARGE, "dim over limit refused");
135 CHECK(omega_gpu_rope_f32(1, 63, a, b, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "odd head_dim refused");
136 CHECK(omega_gpu_rope_f32(1, 64, NULL, b, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "NULL vector refused");
137 CHECK(omega_gpu_swiglu_f32(0, a, b, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "n=0 refused");
138 CHECK(omega_gpu_shared_xchg_u32(100, (uint32_t *)a, (uint32_t *)c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "xchg n not a multiple of 128 refused");
139 CHECK(omega_gpu_rsq_f32(0, a, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "rsq n=0 refused");
140 CHECK(strcmp(omega_gpu_elementwise_rc_name(OMEGA_GPU_EW_UNWRITTEN), "UNWRITTEN") == 0, "rc name");
141
142 struct { OmegaGpuEwOp op; const char *name; const char *must[6]; int n; } ops[] = {
143 { OMEGA_GPU_EW_EX2, "ex2", { "MUFU.EX2", "@P0 EXIT", "STG.E" }, 3 },
144 { OMEGA_GPU_EW_XCHG, "xchg", { "STS [R", "BAR.SYNC", "LDS R" }, 3 },
145 { OMEGA_GPU_EW_RMSNORM, "rmsnorm", { "SHFL.DOWN", "BAR.SYNC", "MUFU.RSQ", "@!P0 BRA", "STS [R", "LDS R" }, 6 },
146 { OMEGA_GPU_EW_ROPE, "rope", { "FADD", "FMUL", "STG.E" }, 3 },
147 { OMEGA_GPU_EW_SWIGLU, "swiglu", { "MUFU.EX2", "MUFU.RCP", "@P0 EXIT" }, 3 },
148 { OMEGA_GPU_EW_RSQ, "rsq", { "MUFU.RSQ", "@P0 EXIT", "STG.E" }, 3 },
149 };
150 for (size_t i = 0; i < sizeof ops / sizeof ops[0]; i++) {
151 OmegaBlackwellKernel k; memset(&k, 0, sizeof k);
152 int rc = omega_gpu_elementwise_codegen(ops[i].op, NULL, 0.0f, &k);
153 CHECK(rc == OMEGA_GPU_EW_OK && k.code_size > 0 && k.gpr_count <= 64, "%s kernel generated (rc %s, %zu insns, %u gprs)", ops[i].name, omega_gpu_elementwise_rc_name(rc), k.insn_count, k.gpr_count);
154 printf("codegen %s: %zu insns, %u gprs, %u ugprs\n", ops[i].name, k.insn_count, k.gpr_count, k.uniform_gpr_count);
155 uint8_t digest[32]; memcpy(digest, k.code_digest, 32);
156 free(k.code);
157 /* the mutant must be a different kernel */
158 omega_gpu_elementwise_test_set_mutant((int)ops[i].op);
159 memset(&k, 0, sizeof k);
160 CHECK(omega_gpu_elementwise_codegen(ops[i].op, NULL, 0.0f, &k) == OMEGA_GPU_EW_OK && memcmp(digest, k.code_digest, 32) != 0, "%s mutant kernel differs", ops[i].name);
161 free(k.code);
162 omega_gpu_elementwise_test_set_mutant(0);
163 CHECK(sm121dis_check(ops[i].op, ops[i].name, ops[i].must, ops[i].n) == 0, "%s sm121dis listing decodes and shows the expected instructions", ops[i].name);
164 }
165}
166
167/* ------------------------------------------------------------- chip gate */
168typedef struct { const char *name; size_t n; int rc; size_t bad; double worst; int pass; int mutant_rc; size_t mutant_bad; int mutant_caught; uint64_t chip_ns; uint32_t calls; uint32_t unwritten; char probe[256]; } Case;
169static int g_ncases;
170
171static void record(Case c, FILE *out) {
172 g_ncases++;
173 CHECK(c.pass, "%s rc=%s violations=%zu worst=%g", c.name, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst);
174 CHECK(c.mutant_caught, "%s mutant caught (rc=%s violations=%zu)", c.name, omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad);
175 printf("%s %s n=%zu rc=%s violations=%zu worst_scaled_err=%g chip_ns=%" PRIu64 " calls=%u unwritten=%u | mutant rc=%s violations=%zu %s\n",
176 c.pass && c.mutant_caught ? "PASS" : "FAIL", c.name, c.n, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst, c.chip_ns, c.calls, c.unwritten,
177 omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad, c.mutant_caught ? "CAUGHT" : "NOT CAUGHT");
178 if (out) fprintf(out, "%s{\"case\":\"%s\",\"n\":%zu,\"rc\":\"%s\",\"violations\":%zu,\"worst_scaled_err\":%g,\"pass\":%s,\"chip_elapsed_ns\":%" PRIu64 ",\"chip_calls\":%u,\"unwritten_words\":%u,\"mutant_rc\":\"%s\",\"mutant_violations\":%zu,\"mutant_caught\":%s%s%s%s}",
179 g_ncases > 1 ? "," : "", c.name, c.n, omega_gpu_elementwise_rc_name(c.rc), c.bad, c.worst, c.pass ? "true" : "false", c.chip_ns, c.calls, c.unwritten,
180 omega_gpu_elementwise_rc_name(c.mutant_rc), c.mutant_bad, c.mutant_caught ? "true" : "false",
181 c.probe[0] ? ",\"probe\":{" : "", c.probe, c.probe[0] ? "}" : "");
182}
183
184/* omega #462 flush probes. want is the host model (tests/bw_mufu_ftz.h: input flushed, IEEE function, result
185 * flushed). 0 = violation, 1 = match, 2 = flushed at the FLT_MIN boundary (allowed only with `boundary`).
186 * A zero, infinite or NaN want must come back exactly (NaN: any NaN). A normal want needs a normal result within
187 * rel, so an unflushed subnormal is always a violation; with `boundary` a zero of want's sign is also allowed when
188 * want is within 2^-21 rel above FLT_MIN (MUFU is approximate, the model flushes a correctly rounded result). */
189static int ftz_match(float got, float want, double rel, int boundary, double *scaled) {
190 uint32_t g, w; memcpy(&g, &got, 4); memcpy(&w, &want, 4);
191 if (isnan(want)) return isnan(got);
192 if ((w & 0x7fffffffu) == 0u || isinf(want)) return g == w;
193 if (boundary && (g & 0x7fffffffu) == 0u && ((g ^ w) & 0x80000000u) == 0u && fabsf(want) < FLT_MIN * (1.0f + 0x1p-21f)) return 2;
194 if ((g & 0x7f800000u) == 0u || isinf(got) || isnan(got)) return 0;
195 double s = fabs((double)got - (double)want) / (rel * fabs((double)want));
196 if (scaled && s > *scaled) *scaled = s;
197 return s <= 1.0;
198}
199
200static float ieee_rsq(float x) { return 1.0f / sqrtf(x); }
201
202/* One flush probe: the chip against the model, then two controls on the rows where the model and IEEE f32
203 * without the flush differ (the rows that decide the rule):
204 * host control (no chip): the comparator must reject IEEE-without-flush on every such row, so a pass below
205 * cannot come from a comparator that accepts both hypotheses;
206 * chip control: the chip's word must differ from IEEE-without-flush on every such row.
207 * The op's mutant must be caught by the same comparator. */
208static void ftz_probe(const char *name, OmegaGpuEwOp op, int (*fn)(uint32_t, const float *, float *, OmegaGpuEwInfo *),
209 float (*model)(float), float (*ieee)(float), const float *x, int n, int boundary, FILE *out) {
210 /* zeroed so a run that fails before writing (device open, codegen) leaves defined words and info */
211 float *got = calloc((size_t)n, 4), *want = calloc((size_t)n, 4);
212 if (!got || !want) { printf("%s: out of memory\n", name); exit(2); }
213 OmegaGpuEwInfo info = {0};
214 for (int i = 0; i < n; i++) want[i] = model(x[i]);
215 Case c = { .name = name, .n = (size_t)n };
216 c.rc = fn((uint32_t)n, x, got, &info);
217 size_t deciding = 0, host_flagged = 0, chip_differs = 0, boundary_flush = 0;
218 for (int i = 0; i < n; i++) {
219 float ie = ieee(x[i]);
220 uint32_t g, w, ib, xb; memcpy(&g, &got[i], 4); memcpy(&w, &want[i], 4); memcpy(&ib, &ie, 4); memcpy(&xb, &x[i], 4);
221 if (ib != w && !(isnan(ie) && isnan(want[i]))) {
222 deciding++;
223 if (ftz_match(ie, want[i], 1e-6, boundary, NULL) == 0) host_flagged++;
224 if (g != ib && !(isnan(got[i]) && isnan(ie))) chip_differs++;
225 }
226 int m = ftz_match(got[i], want[i], 1e-6, boundary, &c.worst);
227 if (m == 2) boundary_flush++;
228 if (m == 0) { c.bad++; printf(" %s x=0x%08x got 0x%08x want 0x%08x ieee 0x%08x\n", name, xb, g, w, ib); }
229 }
230 printf("%s inputs=%d model_differs_from_ieee=%zu host_control_flagged=%zu chip_differs_from_ieee=%zu boundary_flush=%zu\n",
231 name, n, deciding, host_flagged, chip_differs, boundary_flush);
232 CHECK(deciding > 0 && host_flagged == deciding, "%s host control: the comparator rejects IEEE without the flush on every "
233 "deciding row (%zu of %zu)", name, host_flagged, deciding);
234 CHECK(chip_differs == deciding, "%s chip control: the chip differs from IEEE without the flush on every deciding row (%zu of %zu)",
235 name, chip_differs, deciding);
236 snprintf(c.probe, sizeof c.probe, "\"model_differs_from_ieee\":%zu,\"host_control_flagged\":%zu,\"chip_differs_from_ieee\":%zu,\"boundary_flush\":%zu",
237 deciding, host_flagged, chip_differs, boundary_flush);
238 c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words;
239 omega_gpu_elementwise_test_set_mutant((int)op);
240 c.mutant_rc = fn((uint32_t)n, x, got, &info);
241 for (int i = 0; i < n; i++) if (ftz_match(got[i], want[i], 1e-6, boundary, NULL) == 0) c.mutant_bad++;
242 c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0;
243 omega_gpu_elementwise_test_set_mutant(0);
244 record(c, out);
245 free(got); free(want);
246}
247
248static int chip(const char *out_path) {
249 FILE *out = out_path ? fopen(out_path, "w") : NULL;
250 if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; }
251 if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ELEMENTWISE_V1\",\"tolerances\":{\"ex2_rel\":1e-6,\"xchg\":\"exact\",\"rmsnorm_rel\":1e-5,\"rmsnorm_abs\":1e-6,\"rope\":\"exact\",\"swiglu_rel\":1e-5,\"swiglu_abs\":1e-6,"
252 "\"ex2_ftz\":\"tests/bw_mufu_ftz.h model; zero, inf, NaN exact; normal results normal and 1e-6 rel; zero allowed within 2^-21 rel above FLT_MIN\","
253 "\"rsq_ftz\":\"tests/bw_mufu_ftz.h model; zero, inf, NaN exact; normal results normal and 1e-6 rel\"},\"cases\":[");
254 uint32_t seed = 0xfb1c0004u;
255 OmegaGpuEwInfo info = {0};
256
257 /* 1. EX2 probe, with a negative control on the comparison itself */
258 {
259 size_t n = 4096; float *x = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *wrong = malloc(n * 4);
260 for (size_t i = 0; i < n; i++) { x[i] = frand(&seed, -20.0f, 20.0f); want[i] = (float)exp2((double)x[i]); wrong[i] = (float)exp2((double)x[i] + 1.0); }
261 Case c = { .name = "ex2_probe", .n = n };
262 c.rc = omega_gpu_ex2_f32((uint32_t)n, x, got, &info);
263 c.bad = compare(got, want, n, 1e-6, 0.0, &c.worst);
264 double w2; size_t neg = compare(got, wrong, n, 1e-6, 0.0, &w2);
265 CHECK(neg > n / 2, "ex2 negative control: the check rejects a wrong expectation (%zu of %zu flagged)", neg, n);
266 c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words;
267 omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_EX2);
268 c.mutant_rc = omega_gpu_ex2_f32((uint32_t)n, x, got, &info);
269 c.mutant_bad = compare(got, want, n, 1e-6, 0.0, &w2);
270 c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0;
271 omega_gpu_elementwise_test_set_mutant(0);
272 record(c, out); free(x); free(got); free(want); free(wrong);
273 }
274 /* 1b. omega #462: the MUFU flush rule on the chip (tests/bw_mufu_ftz.h). Until these probes only RCP's result
275 * flush was chip-observed.
276 * EX2 observes the result flush: x = -151 .. -125 in steps of 1/8, so 2^x runs from below the smallest
277 * subnormal to normal; the model wants +0 wherever the IEEE result is subnormal. The eight subnormal inputs are
278 * a sanity row only: 2^(+-subnormal) is 1.0f with or without an input flush, so EX2 cannot observe the input
279 * flush, and its results are never negative, so it cannot observe the sign of a flushed zero either.
280 * RSQ observes the input flush: a subnormal input read as +-0 gives +-inf, where IEEE gives a finite value
281 * (positive) or NaN (negative), so the sign half of the input rule shows too. RSQ cannot show a result flush:
282 * 1/sqrt of a finite f32 is at least 2^-64. Its other rows are 2^e * {1, 1.25, 1.5, 1.75} for every normal
283 * exponent and the special values +-0, +-inf, -1. */
284 {
285 enum { NS = 209, NSUB = 8, N = NS + NSUB };
286 static const uint32_t sub[NSUB] = { 0x00000001u, 0x00000002u, 0x00400000u, 0x007fffffu,
287 0x80000001u, 0x80000002u, 0x80400000u, 0x807fffffu };
288 float x[N];
289 for (int i = 0; i < NS; i++) x[i] = -151.0f + 0.125f * (float)i;
290 for (int i = 0; i < NSUB; i++) memcpy(&x[NS + i], &sub[i], 4);
291 ftz_probe("ex2_ftz_probe", OMEGA_GPU_EW_EX2, omega_gpu_ex2_f32, ws_mufu_ex2, exp2f, x, N, 1, out);
292 }
293 {
294 enum { NE = 254 * 4, NSUB = 8, NSP = 5, N = NE + NSUB + NSP };
295 static const uint32_t sub[NSUB] = { 0x00000001u, 0x00000002u, 0x00400000u, 0x007fffffu,
296 0x80000001u, 0x80000002u, 0x80400000u, 0x807fffffu };
297 static const uint32_t sp[NSP] = { 0x00000000u, 0x80000000u, 0x7f800000u, 0xff800000u, 0xbf800000u };
298 float x[N];
299 for (int i = 0; i < NE; i++) x[i] = ldexpf(1.0f + 0.25f * (float)(i % 4), -126 + i / 4);
300 for (int i = 0; i < NSUB; i++) memcpy(&x[NE + i], &sub[i], 4);
301 for (int i = 0; i < NSP; i++) memcpy(&x[NE + NSUB + i], &sp[i], 4);
302 ftz_probe("rsq_ftz_probe", OMEGA_GPU_EW_RSQ, omega_gpu_rsq_f32, ws_mufu_rsq, ieee_rsq, x, N, 0, out);
303 }
304 /* 2. shared-memory exchange probe (STS, BAR.SYNC, LDS) */
305 {
306 size_t n = 4096; uint32_t *x = malloc(n * 4), *got = malloc(n * 4);
307 for (size_t i = 0; i < n; i++) x[i] = lcg(&seed);
308 Case c = { .name = "shared_xchg_probe", .n = n };
309 c.rc = omega_gpu_shared_xchg_u32((uint32_t)n, x, got, &info);
310 for (size_t i = 0; i < n; i++) if (got[i] != x[i ^ (OMEGA_GPU_EW_THREADS - 1)]) c.bad++;
311 c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words;
312 omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_XCHG);
313 c.mutant_rc = omega_gpu_shared_xchg_u32((uint32_t)n, x, got, &info);
314 for (size_t i = 0; i < n; i++) if (got[i] != x[i ^ (OMEGA_GPU_EW_THREADS - 1)]) c.mutant_bad++;
315 c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0;
316 omega_gpu_elementwise_test_set_mutant(0);
317 record(c, out); free(x); free(got);
318 }
319 /* 3. rmsnorm at the model hidden sizes (TinyLlama and Llama-3.2-1B: 2048), plus small and large */
320 { size_t dims[3] = { 2048, 256, 8192 }; size_t rowss[3] = { 4, 1, 2 };
321 for (int t = 0; t < 3; t++) {
322 size_t dim = dims[t], rows = rowss[t], n = rows * dim; float eps = 1e-5f;
323 float *x = malloc(n * 4), *w = malloc(dim * 4), *got = malloc(n * 4), *want = malloc(n * 4), *again = malloc(n * 4);
324 for (size_t i = 0; i < n; i++) x[i] = frand(&seed, -3.0f, 3.0f);
325 for (size_t i = 0; i < dim; i++) w[i] = frand(&seed, 0.5f, 1.5f);
326 for (size_t r = 0; r < rows; r++) oracle_rmsnorm(x + r * dim, w, eps, want + r * dim, dim);
327 char name[64]; snprintf(name, sizeof name, "rmsnorm_%zux%zu", rows, dim);
328 Case c = { .name = strdup(name), .n = n };
329 c.rc = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, got, &info);
330 c.bad = compare(got, want, n, 1e-5, 1e-6, &c.worst);
331 c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words;
332 OmegaGpuEwInfo i2; int rc2 = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, again, &i2);
333 CHECK(rc2 == OMEGA_GPU_EW_OK && i2.kernel_cache_hit && memcmp(got, again, n * 4) == 0, "%s repeat run (cache hit) is bit-identical", name);
334 omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_RMSNORM);
335 double w2; c.mutant_rc = omega_gpu_rmsnorm_f32((uint32_t)rows, (uint32_t)dim, x, w, eps, got, &info);
336 c.mutant_bad = compare(got, want, n, 1e-5, 1e-6, &w2);
337 c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0;
338 omega_gpu_elementwise_test_set_mutant(0);
339 record(c, out); free(x); free(w); free(got); free(want); free(again);
340 } }
341 /* 4. rope: TinyLlama (32 q heads, 4 kv heads, head_dim 64, theta 10000) and Llama-3.2-1B (32/8, 64, 500000) */
342 { struct { size_t heads, hd, pos; float theta; } rs[4] = { { 32, 64, 17, 10000.0f }, { 4, 64, 17, 10000.0f }, { 32, 64, 1023, 500000.0f }, { 8, 64, 1023, 500000.0f } };
343 for (int t = 0; t < 4; t++) {
344 size_t heads = rs[t].heads, hd = rs[t].hd, n = heads * hd, half = hd / 2;
345 float *v = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4), *ch = malloc(half * 4), *sh = malloc(half * 4);
346 for (size_t i = 0; i < n; i++) v[i] = frand(&seed, -4.0f, 4.0f);
347 oracle_rope_tables(hd, rs[t].pos, rs[t].theta, ch, sh);
348 oracle_rope(v, heads, hd, ch, sh, want);
349 char name[64]; snprintf(name, sizeof name, "rope_%zuh_%zud_pos%zu_theta%g", heads, hd, rs[t].pos, rs[t].theta);
350 Case c = { .name = strdup(name), .n = n };
351 c.rc = omega_gpu_rope_f32((uint32_t)heads, (uint32_t)hd, v, ch, sh, got, &info);
352 c.bad = compare(got, want, n, 0.0, 0.0, &c.worst);
353 c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words;
354 omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_ROPE);
355 double w2; c.mutant_rc = omega_gpu_rope_f32((uint32_t)heads, (uint32_t)hd, v, ch, sh, got, &info);
356 c.mutant_bad = compare(got, want, n, 0.0, 0.0, &w2);
357 c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0;
358 omega_gpu_elementwise_test_set_mutant(0);
359 record(c, out); free(v); free(got); free(want); free(ch); free(sh);
360 } }
361 /* 5. swiglu at the model ffn sizes (TinyLlama 5632, Llama-3.2-1B 8192), an odd tail, one past the
362 * 1024-CTA chunk (two launches) and the Qwen3-8B prefill call 128 x 12288 (twelve launches; cut L) */
363 { size_t ns[5] = { 5632, 8192, 1000, 131073, 1572864 };
364 for (int t = 0; t < 5; t++) {
365 size_t n = ns[t];
366 float *g = malloc(n * 4), *u = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4);
367 for (size_t i = 0; i < n; i++) { g[i] = frand(&seed, -12.0f, 12.0f); u[i] = frand(&seed, -2.0f, 2.0f); }
368 oracle_swiglu(g, u, want, n);
369 char name[64]; snprintf(name, sizeof name, "swiglu_%zu", n);
370 Case c = { .name = strdup(name), .n = n };
371 c.rc = omega_gpu_swiglu_f32((uint32_t)n, g, u, got, &info);
372 c.bad = compare(got, want, n, 1e-5, 1e-6, &c.worst);
373 c.pass = c.rc == OMEGA_GPU_EW_OK && c.bad == 0; c.chip_ns = info.elapsed_ns; c.calls = info.chip_calls; c.unwritten = info.unwritten_words;
374 omega_gpu_elementwise_test_set_mutant(OMEGA_GPU_EW_SWIGLU);
375 double w2; c.mutant_rc = omega_gpu_swiglu_f32((uint32_t)n, g, u, got, &info);
376 c.mutant_bad = compare(got, want, n, 1e-5, 1e-6, &w2);
377 c.mutant_caught = c.mutant_rc != OMEGA_GPU_EW_OK || c.mutant_bad > 0;
378 omega_gpu_elementwise_test_set_mutant(0);
379 record(c, out); free(g); free(u); free(got); free(want);
380 } }
381 /* 6. stale-SM-instruction-cache guard (cut 1b finding, omega #256): 10 distinct kernels
382 * (5 ops + 5 mutants) in rotation, two rounds. Every launch uploads code into a freshly
383 * allocated page, so a kernel routinely lands on the code address its predecessor used,
384 * and 10 keys evict the 8-slot kernel cache. Each clean launch must match the oracle and
385 * each mutant must still be caught; a stale icache would make a mutant pass or a clean
386 * kernel fail. Red was observed by cut 1b on matmul before its invalidate (receipt
387 * FB1-CUT1B-f629798); this build carries the invalidate, so the case is a guard. */
388 {
389 enum { RN = 256, RH = 4, RD = 64 };
390 float *x = malloc(RN * 4), *w = malloc(RN * 4), *u = malloc(RN * 4), *got = malloc(RN * 4), *want = malloc(RN * 4);
391 float *ch = malloc(RD / 2 * 4), *sh = malloc(RD / 2 * 4);
392 uint32_t *xu = malloc(RN * 4), *gu = malloc(RN * 4);
393 for (size_t i = 0; i < RN; i++) { x[i] = frand(&seed, -3.0f, 3.0f); w[i] = frand(&seed, 0.5f, 1.5f); u[i] = frand(&seed, -2.0f, 2.0f); xu[i] = lcg(&seed); }
394 oracle_rope_tables(RD, 17, 10000.0f, ch, sh);
395 Case c = { .name = "icache_reuse_rotation", .n = 20 };
396 c.rc = OMEGA_GPU_EW_OK; c.mutant_rc = OMEGA_GPU_EW_OK; c.mutant_caught = 1;
397 const int order[10] = { OMEGA_GPU_EW_EX2, -OMEGA_GPU_EW_SWIGLU, OMEGA_GPU_EW_XCHG, -OMEGA_GPU_EW_EX2, OMEGA_GPU_EW_RMSNORM,
398 -OMEGA_GPU_EW_XCHG, OMEGA_GPU_EW_SWIGLU, -OMEGA_GPU_EW_ROPE, OMEGA_GPU_EW_ROPE, -OMEGA_GPU_EW_RMSNORM };
399 for (int step = 0; step < 20; step++) {
400 int round = step / 10, k = step % 10;
401 int mut = order[k] < 0, op = mut ? -order[k] : order[k];
402 omega_gpu_elementwise_test_set_mutant(mut ? op : 0);
403 int rc; size_t bad = 0; double wst;
404 switch (op) {
405 case OMEGA_GPU_EW_EX2:
406 for (size_t i = 0; i < RN; i++) want[i] = (float)exp2((double)x[i]);
407 rc = omega_gpu_ex2_f32(RN, x, got, &info); bad = compare(got, want, RN, 1e-6, 0.0, &wst); break;
408 case OMEGA_GPU_EW_XCHG:
409 rc = omega_gpu_shared_xchg_u32(RN, xu, gu, &info);
410 for (size_t i = 0; i < RN; i++) { if (gu[i] != xu[i ^ (OMEGA_GPU_EW_THREADS - 1)]) bad++; }
411 break;
412 case OMEGA_GPU_EW_RMSNORM:
413 oracle_rmsnorm(x, w, 1e-5f, want, RN);
414 rc = omega_gpu_rmsnorm_f32(1, RN, x, w, 1e-5f, got, &info); bad = compare(got, want, RN, 1e-5, 1e-6, &wst); break;
415 case OMEGA_GPU_EW_ROPE:
416 oracle_rope(x, RH, RD, ch, sh, want);
417 rc = omega_gpu_rope_f32(RH, RD, x, ch, sh, got, &info); bad = compare(got, want, RH * RD, 0.0, 0.0, &wst); break;
418 default:
419 oracle_swiglu(x, u, want, RN);
420 rc = omega_gpu_swiglu_f32(RN, x, u, got, &info); bad = compare(got, want, RN, 1e-5, 1e-6, &wst); break;
421 }
422 omega_gpu_elementwise_test_set_mutant(0);
423 int ok = rc == OMEGA_GPU_EW_OK && bad == 0;
424 if (!mut && !ok) { c.bad++; if (rc != OMEGA_GPU_EW_OK) c.rc = rc; printf(" rotation %d/%d: clean op %d FAILED rc=%s violations=%zu\n", round, k, op, omega_gpu_elementwise_rc_name(rc), bad); }
425 if (mut && ok) { c.mutant_bad++; c.mutant_caught = 0; printf(" rotation %d/%d: mutant op %d NOT caught\n", round, k, op); }
426 c.chip_ns += info.elapsed_ns; c.calls += info.chip_calls; c.unwritten += info.unwritten_words;
427 }
428 c.pass = c.bad == 0 && c.rc == OMEGA_GPU_EW_OK;
429 record(c, out);
430 free(x); free(w); free(u); free(got); free(want); free(ch); free(sh); free(xu); free(gu);
431 }
432 /* cut 4b: the whole battery (clean and mutant kernels, cache clears) ran on ONE device open */
433 CHECK(omega_gpu_session_open_count() == 1, "device opened once for the battery (opens=%u)", omega_gpu_session_open_count());
434 printf("device_opens=%u\n", omega_gpu_session_open_count());
435 if (out) {
436 fprintf(out, "],\"device_opens\":%u,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_session_open_count(), g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ELEMENTWISE_PASS" : "OMEGA_GPU_ELEMENTWISE_FAIL");
437 fclose(out);
438 }
439 return 0;
440}
441
442/* ------------------------------------------------------------ timing gate (cut 4b) */
443/* The persistent device: 100 calls each of rmsnorm 1x2048 and swiglu 5632 (the TinyLlama
444 * decode shapes), every call checked against the oracle, median wall time per call under
445 * 0.5 ms (cut 4 opened and closed the device per call: ~40 ms). The device must have been
446 * opened exactly once in this process. */
447static int cmp_d(const void *a, const void *b) { double x = *(const double *)a, y = *(const double *)b; return x < y ? -1 : x > y; }
448static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }
449static int timing(const char *out_path) {
450 FILE *out = out_path ? fopen(out_path, "w") : NULL;
451 if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; }
452 if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ELEMENTWISE_TIMING_V1\",\"gate_median_ms\":0.5,\"calls\":100,\"cases\":[");
453 uint32_t seed = 0xfb1c004bu;
454 enum { N = 100 };
455 for (int t = 0; t < 2; t++) {
456 const char *name = t == 0 ? "rmsnorm_1x2048" : "swiglu_5632";
457 size_t n = t == 0 ? 2048 : 5632;
458 float *a = malloc(n * 4), *b = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4);
459 for (size_t i = 0; i < n; i++) { a[i] = frand(&seed, -3.0f, 3.0f); b[i] = t == 0 ? frand(&seed, 0.5f, 1.5f) : frand(&seed, -2.0f, 2.0f); }
460 if (t == 0) oracle_rmsnorm(a, b, 1e-5f, want, n); else oracle_swiglu(a, b, want, n);
461 double samples[N]; int ok_calls = 0; size_t bad_total = 0; double worst = 0; uint64_t chip_sum = 0; int rc_last = 0;
462 OmegaGpuEwInfo info;
463 /* warm-up: first call opens the device and generates the kernel (not timed) */
464 int rc0 = t == 0 ? omega_gpu_rmsnorm_f32(1, (uint32_t)n, a, b, 1e-5f, got, &info) : omega_gpu_swiglu_f32((uint32_t)n, a, b, got, &info);
465 double first_ms = info.call_ns / 1e6;
466 CHECK(rc0 == OMEGA_GPU_EW_OK, "%s first call rc=%s err=\"%s\"", name, omega_gpu_elementwise_rc_name(rc0), omega_gpu_elementwise_last_error());
467 for (int i = 0; i < N; i++) {
468 double t0 = now_ms();
469 int rc = t == 0 ? omega_gpu_rmsnorm_f32(1, (uint32_t)n, a, b, 1e-5f, got, &info) : omega_gpu_swiglu_f32((uint32_t)n, a, b, got, &info);
470 samples[i] = now_ms() - t0;
471 double w; size_t bad = compare(got, want, n, 1e-5, 1e-6, &w);
472 if (w > worst) worst = w;
473 bad_total += bad; chip_sum += info.elapsed_ns; rc_last = rc;
474 if (rc == OMEGA_GPU_EW_OK && bad == 0) ok_calls++;
475 }
476 qsort(samples, N, sizeof samples[0], cmp_d);
477 double median = samples[N / 2], p90 = samples[N * 9 / 10], mn = samples[0], mx = samples[N - 1];
478 uint32_t opens = omega_gpu_session_open_count();
479 int pass = ok_calls == N && bad_total == 0 && median < 0.5 && opens == 1;
480 CHECK(pass, "timing %s ok_calls=%d/%d violations=%zu median_ms=%.3f opens=%u last_rc=%s err=\"%s\"", name, ok_calls, N, bad_total, median, opens, omega_gpu_elementwise_rc_name(rc_last), omega_gpu_elementwise_last_error());
481 printf("%s timing %s first_call_ms=%.3f ok_calls=%d/%d violations=%zu worst_scaled_err=%g median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_us_mean=%.1f device_opens=%u\n",
482 pass ? "PASS" : "FAIL", name, first_ms, ok_calls, N, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens);
483 if (out) fprintf(out, "%s{\"case\":\"%s\",\"first_call_ms\":%.3f,\"ok_calls\":%d,\"violations\":%zu,\"worst_scaled_err\":%g,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f,\"chip_us_mean\":%.1f,\"device_opens\":%u,\"pass\":%s}",
484 t ? "," : "", name, first_ms, ok_calls, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens, pass ? "true" : "false");
485 free(a); free(b); free(got); free(want);
486 }
487 if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ELEMENTWISE_TIMING_PASS" : "OMEGA_GPU_ELEMENTWISE_TIMING_FAIL"); fclose(out); }
488 return 0;
489}
490
491int main(int argc, char **argv) {
492 const char *out_path = NULL; int host = 0, timing_mode = 0;
493 for (int i = 1; i < argc; i++) {
494 if (strcmp(argv[i], "--host-only") == 0) host = 1;
495 else if (strcmp(argv[i], "--timing") == 0) timing_mode = 1;
496 else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i];
497 }
498 if (host) host_only();
499 else if (timing_mode) { if (timing(out_path) != 0) return 2; }
500 else if (chip(out_path) != 0) return 2;
501 printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed);
502 return g_failed ? 1 : 0;
503}