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_q38_graph_test.c

456 lines · 32860 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */
2/*
3 * gpu_q38_graph_test: one Qwen3.8-27B decode token as ONE command list (omega_gpu_q38_graph.h, sc #642).
4 * --host-only the gather table against the attention API's permutation, and the create / set_layer refusals that
5 * need no device beyond the session
6 * (default) chip, caller holds the GB10 lock. A synthetic Qwen3.8-shaped model on random weights: hidden 5120,
7 * intermediate 17408, vocab 248320 (--shape 9b: the Qwen3.5-9B shape, hidden 4096, intermediate 12288,
8 * 16 q / 4 kv attention heads, 32 GDN value heads); --layers N (2) and --mask M (0x2: bit l = layer l is
9 * attention), so by default one GDN layer then one attention layer: both kinds and the handover between
10 * them in every token.
11 * Tokens at positions 0, 1, 2:
12 * A baseline = the APIs one call at a time (FP8 / bf16 GEMV, GDN step, hd256 attention), host glue in
13 * C: rmsnorm f64, the gather table, sigmoid gate expf, SwiGLU expf, argmax strict >; its own GDN
14 * state and KV cache
15 * C main = the same token recorded as one list (omega_gpu_q38_graph_token)
16 * B the same list submitted one launch per submission (flush_each)
17 * Checks per token: B == C bit for bit (x, logits, token); A vs C token identical and logits within
18 * tolerance; x within tolerance. Negative controls: graph mutants 1..4 (SWIGLU, GATHER, GATE, post-norm
19 * weight) must each fail the A-vs-C comparison. Then --reps timed tokens (median).
20 * --bf16 mix, o, gate_up and down are bf16 tensors (values * 2^-64) set with omega_gpu_q38_graph_set_layer_bf16
21 * and the baseline uses the bf16 GEMV with its inputs * 2^64; layer 0's mix GEMV is also checked on
22 * sampled rows against a host f64 product. The bf16 GEMV takes k <= 16384, so only the 9B shape fits
23 * (the 27B down projection has k 17408).
24 * Verdict: exit 0 when every CHECK passed.
25 */
26#include "omega_gpu_q38_graph.h"
27#include "omega_gpu_cmdlist.h"
28#include "omega_gpu_session.h"
29#include <inttypes.h>
30#include <math.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34
35#define HM OMEGA_GPU_Q38_HIDDEN /* array sizes: the 27B widths are the maxima */
36#define IM OMEGA_GPU_Q38_INTER
37/* the shape under test (--shape): 27B by default */
38static struct { uint32_t hd, in, qh, kvh, gh, gqkv, gmix, ab, amix, aqkv, mout; } S = { 5120, 17408, 24, 4, 48, 10240, 16384, 96, 14336, 8192, 6144 };
39#define H (S.hd)
40#define I (S.in)
41#define EPS 1e-6f
42#define MAX_POS 256u
43#define TOKENS 3u
44#define SCALE_2P64 18446744073709551616.0f
45#define SCALE_2M64 5.42101086242752217e-20f
46/* A vs C: |d| <= TOL_REL * max|ref|. The differences: RMSNorm f32 FFMA + MUFU.RSQ vs f64 host, SwiGLU / gate MUFU EX2 /
47 * RCP vs expf (~1e-7 relative each) through 2 layers and 5120- to 17408-term sums; 1e-4 is ~100x that. */
48#define TOL_REL 1e-4
49
50static int g_checks, g_failed;
51#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } else { printf("ok: "); printf(__VA_ARGS__); printf("\n"); } } while (0)
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); }
55static uint16_t bf16_rne(float f) { uint32_t x; memcpy(&x, &f, 4); uint32_t r = x + 0x7fffu + ((x >> 16) & 1u); return (uint16_t)(r >> 16); }
56static 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; }
57static uint64_t median_u64(uint64_t *v, unsigned n) { qsort(v, n, sizeof *v, cmp_u64); return v[n / 2]; }
58
59static void rmsnorm(const float *x, const float *w, float *out) {
60 double sq = 0; for (unsigned i = 0; i < H; i++) sq += (double)x[i] * x[i];
61 float s = (float)(1.0 / sqrt(sq / H + (double)EPS));
62 for (unsigned i = 0; i < H; i++) out[i] = x[i] * s * w[i];
63}
64static uint32_t argmax(const float *v, uint32_t n) { uint32_t b = 0; for (uint32_t i = 1; i < n; i++) if (v[i] > v[b]) b = i; return b; }
65static double maxabs(const float *v, size_t n) { double m = 0; for (size_t i = 0; i < n; i++) if (fabs(v[i]) > m) m = fabs(v[i]); return m; }
66static double maxdiff(const float *a, const float *b, size_t n) { double m = 0; for (size_t i = 0; i < n; i++) { double d = fabs((double)a[i] - b[i]); if (d > m || d != d) m = d != d ? 1e30 : d; } return m; }
67
68static int fp8_random(uint32_t seed, uint32_t n, uint32_t k, OmegaGpuFp8Tensor **out) {
69 size_t wb = (size_t)n * k, sb = (size_t)(n / 128) * (k / 128);
70 uint8_t *w = malloc(wb); uint16_t *s = malloc(sb * 2);
71 if (!w || !s) { free(w); free(s); return -1; }
72 uint32_t st = seed;
73 for (size_t i = 0; i < wb; i += 4) { uint32_t r = lcg(&st); for (unsigned j = 0; j < 4 && i + j < wb; j++) w[i + j] = (uint8_t)((r >> (8 * j)) & 0xbfu); } /* |v| <= 1.875: never a NaN code */
74 const float sc = 1.5f / sqrtf((float)k); /* outputs O(1) for O(1) inputs */
75 for (size_t i = 0; i < sb; i++) s[i] = bf16_rne(frand(&st, 0.5f * sc, sc));
76 int rc = omega_gpu_fp8_tensor_upload(1, n, k, w, s, out);
77 free(w); free(s);
78 return rc;
79}
80static int g_bf16; /* --bf16: bf16 projections */
81static int bf16_random_keep(uint32_t seed, uint32_t n, uint32_t k, float lo, float hi, float mul, OmegaGpuBf16Tensor **out, uint16_t **keep) {
82 uint16_t *w = malloc((size_t)n * k * 2);
83 if (!w) return -1;
84 uint32_t st = seed;
85 for (size_t i = 0; i < (size_t)n * k; i++) w[i] = bf16_rne(frand(&st, lo, hi) * mul);
86 int rc = omega_gpu_bf16_tensor_upload(n, k, w, out);
87 if (keep) *keep = w; else free(w);
88 return rc;
89}
90static int bf16_random(uint32_t seed, uint32_t n, uint32_t k, float lo, float hi, float mul, OmegaGpuBf16Tensor **out) {
91 return bf16_random_keep(seed, n, k, lo, hi, mul, out, NULL);
92}
93/* a bf16 projection [n][k] scaled like the FP8 ones (outputs O(1) for O(1) inputs), uploaded * 2^-64 */
94static int bf16_proj(uint32_t seed, uint32_t n, uint32_t k, OmegaGpuBf16Tensor **out, uint16_t **keep) {
95 const float a = 2.0f / sqrtf((float)k);
96 return bf16_random_keep(seed, n, k, -a, a, SCALE_2M64, out, keep);
97}
98
99/* ---- the synthetic model ---- */
100typedef struct {
101 uint32_t layers, vocab, n_gdn, n_attn;
102 uint64_t mask;
103 struct { OmegaGpuFp8Tensor *mix, *o, *gu, *dn; OmegaGpuBf16Tensor *ab, *bmix, *bo, *bgu, *bdn, *bdn2; float in_norm[HM], post_norm[HM]; } L[8];
104 uint32_t split; /* --bf16 with inter > 8192 (the 9B): down in two K halves bdn | bdn2, two launches more */
105 uint16_t *mix0_w; /* --bf16: layer 0's mix values (the sampled-row host check) */
106 OmegaGpuBf16Tensor *lm;
107 OmegaGpuFp8Tensor *lm8; /* --fp8-head: the same lm_head quantised by omega_gpu_fp8_quantize_bf16 */
108 uint8_t *lm8_w; uint16_t *lm8_s; /* its host copy (the sampled-row host check) */
109 float fnorm[HM];
110 float x0[TOKENS][HM];
111 /* the two state copies: [0] the graph's, [1] the baseline's */
112 OmegaGpuGdn *gdn[2];
113 OmegaGpuDecodeAttn256Cache *attn[2];
114} Model;
115static int g_fp8_head; /* --fp8-head: the graph and the baseline use the FP8-quantised lm_head */
116
117static int state_alloc(Model *m, int which, uint32_t seed) {
118 uint32_t s = seed;
119 const int is27 = S.gh == 48u;
120 if ((is27 ? omega_gpu_gdn_alloc(m->n_gdn ? m->n_gdn : 1, &m->gdn[which])
121 : omega_gpu_gdn_alloc_ratio(m->n_gdn ? m->n_gdn : 1, S.gh / 16u, &m->gdn[which])) != 0) { printf("gdn alloc: %s\n", omega_gpu_gdn_last_error()); return -1; }
122 float *conv = malloc((size_t)S.gqkv * 4 * 4), a_log[48], dtb[48], nw[128];
123 if (!conv) return -1;
124 for (uint32_t l = 0; l < (m->n_gdn ? m->n_gdn : 1); l++) {
125 for (size_t i = 0; i < (size_t)S.gqkv * 4; i++) conv[i] = frand(&s, -0.6f, 0.6f);
126 for (unsigned h = 0; h < S.gh; h++) { a_log[h] = frand(&s, -1.5f, 1.5f); dtb[h] = frand(&s, -3.0f, 1.0f); }
127 for (unsigned i = 0; i < 128; i++) nw[i] = frand(&s, 0.8f, 1.2f);
128 if (omega_gpu_gdn_set_layer(m->gdn[which], l, conv, a_log, dtb, nw) != 0) { printf("gdn set: %s\n", omega_gpu_gdn_last_error()); free(conv); return -1; }
129 }
130 free(conv);
131 const uint32_t na = m->n_attn ? m->n_attn : 1;
132 if ((is27 ? omega_gpu_decode_attn256_cache_alloc(na, MAX_POS, 10000000.0, OMEGA_GPU_Q38_ROTARY, &m->attn[which])
133 : omega_gpu_decode_attn256_cache_alloc_shape(na, MAX_POS, 10000000.0, OMEGA_GPU_Q38_ROTARY, S.qh, S.kvh, S.qh / S.kvh, &m->attn[which])) != 0) { printf("attn alloc: %s\n", omega_gpu_decode_attn_last_error()); return -1; }
134 for (uint32_t l = 0; l < (m->n_attn ? m->n_attn : 1); l++) {
135 float qn[256], kn[256], qp[256], kp[256];
136 for (unsigned i = 0; i < 256; i++) { qn[i] = frand(&s, 0.8f, 1.2f); kn[i] = frand(&s, 0.8f, 1.2f); }
137 omega_dattn256_perm_vec(qn, qp, OMEGA_GPU_Q38_ROTARY); omega_dattn256_perm_vec(kn, kp, OMEGA_GPU_Q38_ROTARY);
138 if (omega_gpu_decode_attn256_set_norms(m->attn[which], l, qp, kp) != 0) return -1;
139 }
140 return 0;
141}
142
143static int model_build(Model *m, uint32_t layers, uint64_t mask, uint32_t vocab) {
144 memset(m, 0, sizeof *m); m->layers = layers; m->mask = mask; m->vocab = vocab;
145 uint32_t s = 4321;
146 for (uint32_t l = 0; l < layers; l++) {
147 const int attn = (int)((mask >> l) & 1u);
148 if (attn) m->n_attn++; else m->n_gdn++;
149 if (g_bf16) m->split = I > 8192u;
150 const uint32_t kd = m->split ? I / 2u : I;
151 if (g_bf16 ? (bf16_proj(100 + l, attn ? S.amix : S.gmix, H, &m->L[l].bmix, l == 0 ? &m->mix0_w : NULL) || bf16_proj(200 + l, H, S.mout, &m->L[l].bo, NULL) ||
152 bf16_proj(300 + l, 2 * I, H, &m->L[l].bgu, NULL) || bf16_proj(400 + l, H, kd, &m->L[l].bdn, NULL) ||
153 (m->split && bf16_proj(450 + l, H, kd, &m->L[l].bdn2, NULL)))
154 : (fp8_random(100 + l, attn ? S.amix : S.gmix, H, &m->L[l].mix) || fp8_random(200 + l, H, S.mout, &m->L[l].o) ||
155 fp8_random(300 + l, 2 * I, H, &m->L[l].gu) || fp8_random(400 + l, H, I, &m->L[l].dn))) {
156 printf("projection upload: fp8 %s / bf16 %s\n", omega_gpu_fp8_last_error(), omega_gpu_bf16_last_error()); return -1;
157 }
158 if (!attn && bf16_random(500 + l, S.ab, H, -0.03f, 0.03f, SCALE_2M64, &m->L[l].ab)) { printf("bf16 upload: %s\n", omega_gpu_bf16_last_error()); return -1; }
159 for (unsigned i = 0; i < H; i++) { m->L[l].in_norm[i] = frand(&s, 0.8f, 1.2f); m->L[l].post_norm[i] = frand(&s, 0.8f, 1.2f); }
160 }
161 if (bf16_random(600, vocab, H, -0.05f, 0.05f, 1.0f, &m->lm)) { printf("lm_head upload: %s\n", omega_gpu_bf16_last_error()); return -1; }
162 if (g_fp8_head) {
163 uint16_t *w = malloc((size_t)vocab * H * 2); m->lm8_w = malloc((size_t)vocab * H); m->lm8_s = malloc((size_t)(vocab / 128) * (H / 128) * 2);
164 if (!w || !m->lm8_w || !m->lm8_s) return -1;
165 uint32_t st = 600; for (size_t i = 0; i < (size_t)vocab * H; i++) w[i] = bf16_rne(frand(&st, -0.05f, 0.05f)); /* bf16_random(600, ...)'s values */
166 int qrc = omega_gpu_fp8_quantize_bf16(vocab, H, w, m->lm8_w, m->lm8_s); free(w);
167 if (qrc || omega_gpu_fp8_tensor_upload(1, vocab, H, m->lm8_w, m->lm8_s, &m->lm8)) { printf("fp8 lm_head: %s\n", omega_gpu_fp8_last_error()); return -1; }
168 }
169 for (unsigned i = 0; i < H; i++) m->fnorm[i] = frand(&s, 0.8f, 1.2f);
170 for (unsigned t = 0; t < TOKENS; t++) for (unsigned i = 0; i < H; i++) m->x0[t][i] = frand(&s, -1.0f, 1.0f);
171 if (state_alloc(m, 0, 777) || state_alloc(m, 1, 777)) return -1;
172 return 0;
173}
174
175static int state_reset(Model *m) {
176 /* GDN state to zero; the KV rows at the test's positions are rewritten by every token */
177 return omega_gpu_gdn_reset(m->gdn[0]) || omega_gpu_gdn_reset(m->gdn[1]);
178}
179
180/* ---- A: the APIs one call at a time ---- */
181typedef struct { float x[HM], logits[248320]; uint32_t token; } Out;
182
183/* one projection y = W x for plain x: FP8, or (--bf16) the 2^-64 bf16 tensor on x * 2^64 (exact power-of-two scaling) */
184static int proj(const OmegaGpuFp8Tensor *t8, const OmegaGpuBf16Tensor *tb, const float *x, uint32_t k, float *y) {
185 static float xs[IM];
186 if (!tb) { int r_ = omega_gpu_fp8_gemv_f32(t8, 0, x, y, NULL); if (r_ != 0) printf("fp8 gemv rc %d: %s\n", r_, omega_gpu_fp8_last_error()); return r_; }
187 for (uint32_t i = 0; i < k; i++) xs[i] = x[i] * SCALE_2P64;
188 int r_ = omega_gpu_bf16_gemv_f32(tb, xs, y, NULL); if (r_ != 0) printf("bf16 gemv rc %d: %s\n", r_, omega_gpu_bf16_last_error());
189 return r_;
190}
191
192static int baseline_token(Model *m, const float *x0, uint32_t pos, Out *o) {
193 static float xn[HM], xs[HM], mix[OMEGA_GPU_Q38_GDN_MIX], ab[OMEGA_GPU_Q38_AB], agg[OMEGA_GPU_Q38_ATT_MIX], att[OMEGA_GPU_Q38_MIXER_OUT], y[HM], gu[2 * IM], act[IM];
194 static uint32_t tab[OMEGA_GPU_Q38_ATT_MIX];
195 if (omega_q38_gather_table(S.qh, S.kvh, tab) != 0) return -1;
196 memcpy(o->x, x0, sizeof o->x);
197 uint32_t ng = 0, na = 0;
198 for (uint32_t l = 0; l < m->layers; l++) {
199 rmsnorm(o->x, m->L[l].in_norm, xn);
200 if (proj(m->L[l].mix, m->L[l].bmix, xn, H, mix) != 0) return -1;
201 static int mix0_checked;
202 if (l == 0 && m->mix0_w && !mix0_checked) { /* every 61st row of layer 0's bf16 mix against the host f64 product */
203 mix0_checked = 1;
204 const uint32_t rows = (m->mask & 1u) ? S.amix : S.gmix;
205 double worst = 0, ref_max = 0;
206 for (uint32_t r = 0; r < rows; r += 61) {
207 double acc = 0;
208 for (uint32_t c = 0; c < H; c++) { uint32_t b = (uint32_t)m->mix0_w[(size_t)r * H + c] << 16; float wf; memcpy(&wf, &b, 4); acc += (double)wf * 0x1p64 * xn[c]; }
209 const double d = fabs(acc - mix[r]); if (d > worst) worst = d; if (fabs(acc) > ref_max) ref_max = fabs(acc);
210 }
211 CHECK(ref_max > 0 && worst <= 1e-4 * ref_max, "bf16 mix layer 0: sampled rows max diff %.3g vs host f64 (max %.3g)", worst, ref_max);
212 }
213 if (!((m->mask >> l) & 1u)) {
214 for (unsigned i = 0; i < H; i++) xs[i] = xn[i] * SCALE_2P64; /* the a|b rows are uploaded * 2^-64 */
215 { int r_ = omega_gpu_bf16_gemv_f32(m->L[l].ab, xs, ab, NULL); if (r_ != 0) { printf("bf16 gemv rc %d: %s\n", r_, omega_gpu_bf16_last_error()); return -1; } }
216 if (omega_gpu_gdn_step(m->gdn[1], ng++, mix, mix + S.gqkv, ab, EPS, EPS, 1.0f, 1.0f, att, NULL) != 0) { printf("gdn step: %s\n", omega_gpu_gdn_last_error()); return -1; }
217 } else {
218 for (unsigned n = 0; n < S.amix; n++) agg[n] = mix[tab[n]];
219 if (omega_gpu_decode_attn256(m->attn[1], na++, pos, agg, EPS, 1.0f, att, NULL) != 0) { printf("attn: %s\n", omega_gpu_decode_attn_last_error()); return -1; }
220 for (unsigned n = 0; n < S.mout; n++) att[n] = att[n] * (1.0f / (1.0f + expf(-agg[S.aqkv + n])));
221 }
222 if (proj(m->L[l].o, m->L[l].bo, att, S.mout, y) != 0) return -1;
223 for (unsigned i = 0; i < H; i++) o->x[i] = o->x[i] + y[i];
224 rmsnorm(o->x, m->L[l].post_norm, xn);
225 if (proj(m->L[l].gu, m->L[l].bgu, xn, H, gu) != 0) return -1;
226 for (unsigned j = 0; j < I; j++) { float v = gu[j]; act[j] = v / (1.0f + expf(-v)) * gu[I + j]; }
227 if (m->split) { /* the graph's order: x += down(act lo), then x += down2(act hi) */
228 if (proj(NULL, m->L[l].bdn, act, I / 2u, y) != 0) return -1;
229 for (unsigned i = 0; i < H; i++) o->x[i] = o->x[i] + y[i];
230 if (proj(NULL, m->L[l].bdn2, act + I / 2u, I / 2u, y) != 0) return -1;
231 } else if (proj(m->L[l].dn, m->L[l].bdn, act, I, y) != 0) return -1;
232 for (unsigned i = 0; i < H; i++) o->x[i] = o->x[i] + y[i];
233 }
234 rmsnorm(o->x, m->fnorm, xn);
235 if (m->lm8) {
236 int r_ = omega_gpu_fp8_gemv_f32(m->lm8, 0, xn, o->logits, NULL); if (r_ != 0) { printf("fp8 head rc %d: %s\n", r_, omega_gpu_fp8_last_error()); return -1; }
237 double worst = 0, ref_max = 0; /* every 97th row against the dequantised host product */
238 for (uint32_t r = 0; r < m->vocab; r += 97) {
239 double acc = 0;
240 for (uint32_t c = 0; c < H; c++) { uint8_t q = m->lm8_w[(size_t)r * H + c]; unsigned e = (q >> 3) & 15u, mm = q & 7u; double v = e ? (1.0 + mm / 8.0) * ldexp(1.0, (int)e - 7) : mm / 8.0 * ldexp(1.0, -6); if (q & 0x80u) v = -v;
241 uint32_t sb = (uint32_t)m->lm8_s[(r / 128) * (H / 128) + c / 128] << 16; float sf; memcpy(&sf, &sb, 4); acc += v * sf * xn[c]; }
242 double d = fabs(acc - o->logits[r]); if (d > worst) worst = d; if (fabs(acc) > ref_max) ref_max = fabs(acc);
243 }
244 CHECK(worst <= 1e-4 * ref_max + 1e-6, "fp8 head: sampled rows max diff %.3g vs host dequantised (max %.3g)", worst, ref_max);
245 } else
246 { int r_ = omega_gpu_bf16_gemv_f32(m->lm, xn, o->logits, NULL); if (r_ != 0) { printf("bf16 gemv rc %d: %s\n", r_, omega_gpu_bf16_last_error()); return -1; } }
247 o->token = argmax(o->logits, m->vocab);
248 return 0;
249}
250
251static int graph_build(Model *m, OmegaGpuQ38Graph **out) {
252 OmegaGpuQ38GraphConfig c; memset(&c, 0, sizeof c);
253 c.layers = m->layers; c.attn_mask = m->mask; c.vocab = m->vocab; c.eps = EPS; c.eps_l2 = EPS;
254 if (S.gh != 48u) { c.hidden = S.hd; c.inter = S.in; c.q_heads = S.qh; c.kv_heads = S.kvh; c.gdn_heads = S.gh; } /* the 27B: zeros */
255 c.gdn = m->gdn[0]; c.attn = m->attn[0]; c.lm_head = m->lm;
256 int rc = omega_gpu_q38_graph_create(&c, out);
257 if (rc != 0) { printf("graph create %d: %s\n", rc, omega_gpu_session_last_error()); return -1; }
258 for (uint32_t l = 0; l < m->layers; l++)
259 if ((rc = g_bf16 ? omega_gpu_q38_graph_set_layer_bf16(*out, l, m->L[l].bmix, m->L[l].ab, m->L[l].bo, m->L[l].bgu, m->L[l].bdn, m->L[l].bdn2, m->L[l].in_norm, m->L[l].post_norm)
260 : omega_gpu_q38_graph_set_layer(*out, l, m->L[l].mix, m->L[l].ab, m->L[l].o, m->L[l].gu, m->L[l].dn, m->L[l].in_norm, m->L[l].post_norm)) != 0) {
261 printf("set_layer %u: %d %s\n", l, rc, omega_gpu_session_last_error()); return -1;
262 }
263 if (omega_gpu_q38_graph_set_final_norm(*out, m->fnorm) != 0) return -1;
264 if (m->lm8 && omega_gpu_q38_graph_set_lm_head_fp8(*out, m->lm8) != 0) { printf("set_lm_head_fp8 refused\n"); return -1; }
265 return 0;
266}
267
268static int graph_token(OmegaGpuQ38Graph *g, Model *m, const float *x0, uint32_t pos, Out *o, OmegaGpuDecodeGraphStats *st) {
269 int rc = omega_gpu_q38_graph_token(g, x0, pos, &o->token, st);
270 if (rc != 0) { printf("graph token rc %d: %s\n", rc, omega_gpu_session_last_error()); return -1; }
271 (void)m;
272 return omega_gpu_q38_graph_read(g, o->x, NULL, o->logits) != 0 ? -1 : 0;
273}
274
275static int host_only(void) {
276 static uint32_t tab[OMEGA_GPU_Q38_ATT_MIX];
277 CHECK(omega_q38_gather_table(24, 4, tab) == 0, "gather table 24 / 4 built");
278 int bad = 0;
279 for (uint32_t h = 0; h < 24; h++) for (uint32_t i = 0; i < 256; i++) if (tab[h * 256 + i] != h * 512 + omega_dattn256_perm_slot(i, 64)) bad++;
280 for (uint32_t h = 0; h < 4; h++) for (uint32_t i = 0; i < 256; i++) if (tab[6144 + h * 256 + i] != 12288 + h * 256 + omega_dattn256_perm_slot(i, 64)) bad++;
281 for (uint32_t i = 0; i < 1024; i++) if (tab[7168 + i] != 13312 + i) bad++;
282 for (uint32_t h = 0; h < 24; h++) for (uint32_t d = 0; d < 256; d++) if (tab[8192 + h * 256 + d] != h * 512 + 256 + d) bad++;
283 CHECK(bad == 0, "gather table: q, k permuted, v and gate in place (%d wrong)", bad);
284 static uint8_t seen[OMEGA_GPU_Q38_ATT_MIX];
285 int dup = 0; for (uint32_t n = 0; n < OMEGA_GPU_Q38_ATT_MIX; n++) { if (tab[n] >= OMEGA_GPU_Q38_ATT_MIX || seen[tab[n]]) dup++; else seen[tab[n]] = 1; }
286 CHECK(dup == 0, "gather table is a permutation of the 14336 mix values (%d repeats or out of range)", dup);
287 /* Qwen3.5-9B, 16 q / 4 kv heads: mix = q_proj 16 x [q 256 | gate 256] (8192) | k_proj 1024 | v_proj 1024 (10240);
288 * agg = q 4096 | k 1024 | v 1024 | gate 4096 */
289 memset(tab, 0xff, sizeof tab);
290 CHECK(omega_q38_gather_table(16, 4, tab) == 0, "gather table 16 / 4 built");
291 bad = 0;
292 for (uint32_t h = 0; h < 16; h++) for (uint32_t i = 0; i < 256; i++) if (tab[h * 256 + i] != h * 512 + omega_dattn256_perm_slot(i, 64)) bad++;
293 for (uint32_t h = 0; h < 4; h++) for (uint32_t i = 0; i < 256; i++) if (tab[4096 + h * 256 + i] != 8192 + h * 256 + omega_dattn256_perm_slot(i, 64)) bad++;
294 for (uint32_t i = 0; i < 1024; i++) if (tab[5120 + i] != 9216 + i) bad++;
295 for (uint32_t h = 0; h < 16; h++) for (uint32_t d = 0; d < 256; d++) if (tab[6144 + h * 256 + d] != h * 512 + 256 + d) bad++;
296 CHECK(bad == 0, "9B gather table: q, k permuted, v and gate in place (%d wrong)", bad);
297 memset(seen, 0, sizeof seen); dup = 0;
298 for (uint32_t n = 0; n < 10240u; n++) { if (tab[n] >= 10240u || seen[tab[n]]) dup++; else seen[tab[n]] = 1; }
299 CHECK(dup == 0 && tab[10240] == 0xffffffffu, "9B gather table is a permutation of the 10240 mix values, nothing past it (%d repeats or out of range)", dup);
300 CHECK(omega_q38_gather_table(16, 3, tab) == -1 && omega_q38_gather_table(0, 4, tab) == -1 && omega_q38_gather_table(32, 4, tab) == -1,
301 "gather table refuses 16 / 3, 0 / 4, 32 / 4");
302 OmegaGpuQ38Graph *g = NULL;
303 OmegaGpuQ38GraphConfig c; memset(&c, 0, sizeof c);
304 CHECK(omega_gpu_q38_graph_create(&c, &g) == OMEGA_GPU_DGRAPH_BAD_ARGS && !g, "create refuses an empty config");
305 CHECK(omega_gpu_q38_graph_create(NULL, &g) == OMEGA_GPU_DGRAPH_BAD_ARGS, "create refuses NULL");
306 return g_failed ? 1 : 0;
307}
308
309static uint32_t tl_reps = 1; /* --tl-reps: stamped tokens for the timeline (more than 1: the first is dropped, medians printed) */
310
311static int chip_run(uint32_t layers, uint64_t mask, uint32_t reps) {
312 Model m;
313 const uint32_t vocab = 248320u;
314 if (model_build(&m, layers, mask, vocab) != 0) { CHECK(0, "model build"); return 1; }
315 printf("model: %u layers (%u GDN, %u attention, mask 0x%" PRIx64 "), vocab %u\n", layers, m.n_gdn, m.n_attn, mask, vocab);
316 static Out A[TOKENS], C[TOKENS], B, M;
317 /* A first: it also warms every kernel the record paths need */
318 for (uint32_t t = 0; t < TOKENS; t++) if (baseline_token(&m, m.x0[t], t, &A[t]) != 0) { CHECK(0, "baseline token %u", t); return 1; }
319 OmegaGpuQ38Graph *g = NULL;
320 if (graph_build(&m, &g) != 0) { CHECK(0, "graph build"); return 1; }
321 OmegaGpuDecodeGraphStats st;
322 for (uint32_t t = 0; t < TOKENS; t++) {
323 if (graph_token(g, &m, m.x0[t], t, &C[t], &st) != 0) { CHECK(0, "graph token %u", t); return 1; }
324 const double ref = maxabs(A[t].logits, vocab), dl = maxdiff(A[t].logits, C[t].logits, vocab);
325 const double xref = maxabs(A[t].x, H), dx = maxdiff(A[t].x, C[t].x, H);
326 CHECK(C[t].token == A[t].token, "token %u: graph %u == baseline %u", t, C[t].token, A[t].token);
327 CHECK(dl <= TOL_REL * ref, "token %u: logits max diff %.3g <= %.0e * %.3g", t, dl, TOL_REL, ref);
328 CHECK(dx <= TOL_REL * xref, "token %u: x max diff %.3g <= %.0e * %.3g", t, dx, TOL_REL, xref);
329 CHECK(st.launches == m.n_gdn * 9u + m.n_attn * 10u + 4u + (m.split ? 2u * m.layers : 0u) && st.submits == 1u, "token %u: %u launches in %u submit", t, st.launches, st.submits);
330 }
331 /* B: flush_each over the same three tokens from a reset state, bit-identical to C */
332 if (state_reset(&m) != 0) { CHECK(0, "state reset"); return 1; }
333 omega_gpu_q38_graph_set_flush_each(g, 1);
334 int bsame = 1;
335 for (uint32_t t = 0; t < TOKENS; t++) {
336 if (graph_token(g, &m, m.x0[t], t, &B, &st) != 0) { CHECK(0, "flush_each token %u", t); return 1; }
337 if (memcmp(B.x, C[t].x, sizeof B.x) || memcmp(B.logits, C[t].logits, vocab * 4u) || B.token != C[t].token) bsame = 0;
338 }
339 omega_gpu_q38_graph_set_flush_each(g, 0);
340 CHECK(bsame, "flush_each == one list, bit for bit, all %u tokens", TOKENS);
341 /* read_buf: x from the host-visible buffer; gu and act from the GPU-cached one (a chip copy into the staging region first).
342 * act = silu(gu[c]) * gu[I + c] * 2^64 (the last layer's SwiGLU) ties the two copies together. */
343 {
344 static float rx[HM], rgu[2 * IM], ract[IM], rgu100[100];
345 const int r1 = omega_gpu_q38_graph_read_buf(g, OMEGA_GPU_Q38_BUF_X, rx, H), r2 = omega_gpu_q38_graph_read_buf(g, OMEGA_GPU_Q38_BUF_GU, rgu, 2 * I);
346 const int r3 = omega_gpu_q38_graph_read_buf(g, OMEGA_GPU_Q38_BUF_ACT, ract, I), r4 = omega_gpu_q38_graph_read_buf(g, OMEGA_GPU_Q38_BUF_GU, rgu100, 100);
347 CHECK(r1 == 0 && r2 == 0 && r3 == 0 && r4 == 0, "read_buf x, gu, act, gu[0..100): rc %d %d %d %d", r1, r2, r3, r4);
348 CHECK(memcmp(rx, B.x, sizeof rx) == 0, "read_buf x == read x, bit for bit");
349 CHECK(memcmp(rgu100, rgu, sizeof rgu100) == 0, "read_buf of 100 values == the first 100 of the whole row");
350 double worst = 0, amax = 0;
351 for (uint32_t c = 0; c < I; c++) {
352 const double v = rgu[c], want = v / (1.0 + exp(-v)) * (double)rgu[I + c] * 0x1p64;
353 if (fabs(want) > amax) amax = fabs(want);
354 if (fabs(want - ract[c]) > worst) worst = fabs(want - ract[c]);
355 }
356 CHECK(amax > 0 && worst <= 1e-5 * amax, "read_buf act == silu(gu) * up * 2^64 from read_buf gu: worst %.3g of %.3g", worst, amax);
357 }
358 /* negative controls: each graph mutant must fail the A comparison on some token */
359 const char *mname[5] = { "", "swiglu up half -1", "gather index +1", "gate dropped", "post-norm weight dropped" };
360 for (int mu = 1; mu <= 4; mu++) {
361 if (state_reset(&m) != 0) return 1;
362 omega_gpu_q38_graph_test_set_mutant(g, mu);
363 int caught = 0;
364 for (uint32_t t = 0; t < TOKENS; t++) {
365 if (graph_token(g, &m, m.x0[t], t, &M, &st) != 0) { caught = 1; break; }
366 if (maxdiff(A[t].x, M.x, H) > TOL_REL * maxabs(A[t].x, H)) caught = 1;
367 }
368 CHECK(caught, "mutant %d (%s) caught", mu, mname[mu]);
369 }
370 omega_gpu_q38_graph_test_set_mutant(g, 0);
371 /* timing: reps tokens at position 2 over the reset state (the time, not the values, is measured here) */
372 uint64_t *chip = calloc(reps, 8), *tot = calloc(reps, 8);
373 if (!chip || !tot) return 1;
374 for (uint32_t r = 0; r < reps; r++) {
375 if (state_reset(&m) != 0 || graph_token(g, &m, m.x0[0], 2, &M, &st) != 0) { CHECK(0, "timed token %u", r); return 1; }
376 chip[r] = st.chip_ns; tot[r] = st.total_ns;
377 }
378 printf("timing: %u reps, median chip %.1f us, median total %.1f us per token (%u layers)\n", reps, median_u64(chip, reps) / 1e3, median_u64(tot, reps) / 1e3, layers);
379 free(chip); free(tot);
380 /* timeline: tl_reps stamped tokens (first one dropped when there are more), median GPU time per launch kind, and the
381 * weight bytes each kind streams so the line reads as GB/s (activations and state are not counted) */
382 {
383 static uint64_t stp[OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1]; static uint8_t kd[OMEGA_GPU_CMDLIST_MAX_LAUNCHES];
384 uint64_t wb[OMEGA_GPU_Q38_K_COUNT] = { 0 }; uint32_t e, n8, k8;
385 for (uint32_t l = 0; l < m.layers; l++) {
386 const OmegaGpuFp8Tensor *f[4] = { m.L[l].mix, m.L[l].o, m.L[l].gu, m.L[l].dn };
387 const unsigned fk[4] = { OMEGA_GPU_Q38_K_MIX, OMEGA_GPU_Q38_K_O, OMEGA_GPU_Q38_K_GATE_UP, OMEGA_GPU_Q38_K_DOWN };
388 for (int j = 0; j < 4; j++) if (f[j]) { omega_gpu_fp8_tensor_shape(f[j], &e, &n8, &k8); wb[fk[j]] += (uint64_t)n8 * k8; }
389 if (m.L[l].ab) { omega_gpu_bf16_tensor_shape(m.L[l].ab, &n8, &k8); wb[OMEGA_GPU_Q38_K_AB] += 2ull * n8 * k8; }
390 const OmegaGpuBf16Tensor *b[5] = { m.L[l].bmix, m.L[l].bo, m.L[l].bgu, m.L[l].bdn, m.L[l].bdn2 };
391 for (int j = 0; j < 5; j++) if (b[j]) { omega_gpu_bf16_tensor_shape(b[j], &n8, &k8); wb[fk[j < 4 ? j : 3]] += 2ull * n8 * k8; }
392 }
393 omega_gpu_bf16_tensor_shape(m.lm, &n8, &k8); wb[OMEGA_GPU_Q38_K_LM_HEAD] = 2ull * n8 * k8;
394 if (m.lm8) wb[OMEGA_GPU_Q38_K_LM_HEAD] /= 2u; /* FP8 head: one byte per weight */
395 const uint32_t tr = tl_reps > 1 ? tl_reps - 1 : 1;
396 uint64_t *ns = calloc((size_t)tr * (OMEGA_GPU_Q38_K_COUNT + 1), 8), col[256];
397 uint32_t cnt[OMEGA_GPU_Q38_K_COUNT] = { 0 };
398 if (!ns || tr > 256) { CHECK(0, "timeline buffers (tl-reps <= 257)"); return 1; }
399 omega_gpu_q38_graph_set_stamps(g, 1);
400 for (uint32_t r = 0; r < tl_reps; r++) {
401 if (state_reset(&m) != 0 || graph_token(g, &m, m.x0[0], 2, &M, &st) != 0) { CHECK(0, "stamped token %u", r); return 1; }
402 int n = omega_gpu_q38_graph_stamps(g, stp, kd, OMEGA_GPU_CMDLIST_MAX_LAUNCHES + 1);
403 CHECK(n == (int)st.launches, "timeline %u: %d stamped launches", r, n);
404 if (tl_reps > 1 && r == 0) continue;
405 uint64_t *row = ns + (size_t)(tl_reps > 1 ? r - 1 : 0) * (OMEGA_GPU_Q38_K_COUNT + 1);
406 memset(cnt, 0, sizeof cnt);
407 for (int i = 0; i < n; i++) { row[kd[i]] += stp[i + 1] - stp[i]; cnt[kd[i]]++; }
408 if (n > 0) row[OMEGA_GPU_Q38_K_COUNT] = stp[n] - stp[0];
409 }
410 omega_gpu_q38_graph_set_stamps(g, 0);
411 for (unsigned k = 0; k <= OMEGA_GPU_Q38_K_COUNT; k++) {
412 if (k < OMEGA_GPU_Q38_K_COUNT && !cnt[k]) continue;
413 uint64_t lo = UINT64_MAX, hi = 0;
414 for (uint32_t r = 0; r < tr; r++) { col[r] = ns[(size_t)r * (OMEGA_GPU_Q38_K_COUNT + 1) + k]; if (col[r] < lo) lo = col[r]; if (col[r] > hi) hi = col[r]; }
415 const double med = (double)median_u64(col, tr);
416 if (k == OMEGA_GPU_Q38_K_COUNT) { printf("timeline span %.1f us (median of %u, min %.1f max %.1f)\n", med / 1e3, tr, lo / 1e3, hi / 1e3); break; }
417 printf("timeline %-8s %3u launches %9.1f us (min %.1f max %.1f)", omega_gpu_q38_graph_kind_name((uint8_t)k), cnt[k], med / 1e3, lo / 1e3, hi / 1e3);
418 if (wb[k]) printf(" %12" PRIu64 " weight B %6.1f GB/s", wb[k], (double)wb[k] / med);
419 printf("\n");
420 }
421 free(ns);
422 }
423 omega_gpu_q38_graph_free(g);
424 return g_failed ? 1 : 0;
425}
426
427int main(int argc, char **argv) {
428 int host = 0; uint32_t layers = 2, reps = 10; uint64_t mask = 0x2;
429 for (int i = 1; i < argc; i++) {
430 if (strcmp(argv[i], "--host-only") == 0) host = 1;
431 else if (strcmp(argv[i], "--layers") == 0 && i + 1 < argc) layers = (uint32_t)atoi(argv[++i]);
432 else if (strcmp(argv[i], "--mask") == 0 && i + 1 < argc) mask = strtoull(argv[++i], NULL, 0);
433 else if (strcmp(argv[i], "--reps") == 0 && i + 1 < argc) reps = (uint32_t)atoi(argv[++i]);
434 else if (strcmp(argv[i], "--tl-reps") == 0 && i + 1 < argc) tl_reps = (uint32_t)atoi(argv[++i]);
435 else if (strcmp(argv[i], "--fp8-head") == 0) g_fp8_head = 1;
436 else if (strcmp(argv[i], "--bf16") == 0) g_bf16 = 1;
437 else if (strcmp(argv[i], "--shape") == 0 && i + 1 < argc) {
438 const char *sh = argv[++i];
439 if (strcmp(sh, "9b") == 0) { S.hd = 4096; S.in = 12288; S.qh = 16; S.kvh = 4; S.gh = 32; }
440 else if (strcmp(sh, "27b") != 0) { printf("--shape 27b | 9b\n"); return 2; }
441 S.gqkv = (32 + S.gh) * 128; S.gmix = S.gqkv + S.gh * 128; S.ab = 2 * S.gh;
442 S.amix = (S.qh + S.kvh) * 512; S.aqkv = S.qh * 256 + S.kvh * 512; S.mout = S.qh * 256;
443 }
444 /* tuning knobs for sweeps (process-wide, before any kernel is built): FP8 GEMV lane_bytes,rows,warps / CTA budget,
445 * bf16 GEMV (lm_head, a|b) rows,warps,depth / CTA budget */
446 else if (strcmp(argv[i], "--fp8-shape") == 0 && i + 1 < argc) { unsigned a, b, c; if (sscanf(argv[++i], "%u,%u,%u", &a, &b, &c) != 3) return 2; omega_gpu_fp8_set_shape(a, b, c); }
447 else if (strcmp(argv[i], "--fp8-ctas") == 0 && i + 1 < argc) omega_gpu_fp8_set_cta_budget((uint32_t)atoi(argv[++i]));
448 else if (strcmp(argv[i], "--bf16-shape") == 0 && i + 1 < argc) { unsigned a, b, c; if (sscanf(argv[++i], "%u,%u,%u", &a, &b, &c) != 3) return 2; omega_gpu_bf16_set_shape(a, b, c); }
449 else if (strcmp(argv[i], "--bf16-ctas") == 0 && i + 1 < argc) omega_gpu_bf16_set_cta_budget((uint32_t)atoi(argv[++i]));
450 else { printf("usage: %s [--host-only] [--shape 27b|9b] [--bf16] [--layers N (<= 8)] [--mask M] [--reps R] [--tl-reps T (<= 257)]\n", argv[0]); return 2; }
451 }
452 if (layers == 0 || layers > 8 || reps == 0 || tl_reps == 0 || tl_reps > 257) { printf("layers 1..8, reps >= 1, tl-reps 1..257\n"); return 2; }
453 int rc = host ? host_only() : chip_run(layers, mask, reps);
454 printf("gpu_q38_graph_test%s: %d checks, %d failed: %s\n", host ? " (host-only)" : "", g_checks, g_failed, rc ? "FAIL" : "PASS");
455 return rc;
456}