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 / src / omega_gpu_mathlibs_api.h

244 lines · 16560 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */
2#ifndef OMEGA_GPU_MATHLIBS_API_H
3#define OMEGA_GPU_MATHLIBS_API_H
4/*
5 * omega_gpu_mathlibs_api: GB10 random numbers (cuRAND-class) and complex FFT (cuFFT-class), no CUDA.
6 *
7 * Both kernels are generated by the seeded Omega unit om/mathlibs/mathlibs_ir.om (BlackwellIR records),
8 * replayed and register-allocated by src/omega_gpu_om_ir.c (migration-pending C), encoded by the .om sm_121
9 * encoder and launched through the process-wide session (omega_gpu_session.h) like the elementwise kernels:
10 * uncached buffers, poison-filled outputs scanned after readback.
11 *
12 * RNG: xoshiro256** (Blackman and Vigna, public domain) seeded by SplitMix64, the same stream as aien-math
13 * src/stats/random.om: stream g (0 <= g < nstreams) is the generator seeded with seed + stream0 + g (mod 2^64);
14 * out[j * nstreams + g] is its output number offset + j (0 <= j < per_stream).
15 * OMEGA_GPU_RNG_U64: the raw 64-bit outputs, bit-identical to aien-math next_u64.
16 * OMEGA_GPU_RNG_UNIFORM: f32 (r >> 40) * 2^-24 in [0, 1), exact (aien-math's f64 uniform uses r >> 11).
17 * OMEGA_GPU_RNG_NORMAL: f32 standard normal, Phi^-1(A / 2^24) with A = (r >> 41) * 2 + 1 (an odd
18 * 24-bit numerator, never 0 or 2^24), by Giles' single-precision erfinv with the
19 * chip's MUFU.LG2 and MUFU.RSQ; a relative error bound is derived in the evidence.
20 * Philox: Philox4x32-10 (Salmon et al., SC'11; Random123), the stream of cuRAND's curandStatePhilox4_32_10_t:
21 * stream g is curand_init(seed, subseq0 + g, offset) and its output number k (k < per_stream) is the k-th value of
22 * the distribution drawn from that state (EXPERIMENTAL distributions, omega_gpu_philox_generate_dist):
23 * OMEGA_GPU_PHILOX_RAW: curand(), u32, word offset + k.
24 * OMEGA_GPU_PHILOX_UNIFORM: curand_uniform(), f32 in (0, 1]: w * 2^-32 + 2^-33 from word offset + k.
25 * OMEGA_GPU_PHILOX_UNIFORM_DOUBLE: curand_uniform_double(), f64 (w + 1) * 2^-32 from word offset + k.
26 * OMEGA_GPU_PHILOX_UNIFORM2_DOUBLE: curand_uniform2_double() .x then .y, f64 (z + 1/2) * 2^-53 rounded to
27 * nearest even, z = w0 ^ (w1 << 21), words offset + 4 (k / 2) + 2 (k % 2), + 1.
28 * OMEGA_GPU_PHILOX_NORMAL: curand_normal(), f32 Box-Muller (sin value first, then cos) from words
29 * offset + 2 (k / 2), + 1, by cuRAND's single-precision formula with the
30 * chip's MUFU.RSQ; within 2^-21 sqrt(-2 log u) of cuRAND (bound in evidence).
31 * curand_normal_double needs f64 arithmetic in the IR and is not provided. With G outputs per group of four
32 * words (G = 2 for UNIFORM2_DOUBLE, else 4), J = per_stream / G and r = per_stream % G, output k of stream g is
33 * element ((k / G) nstreams + g) G + k % G when k < J G, else J nstreams G + g r + (k - J G): whole groups
34 * interleave across streams, partial groups follow stream by stream. Any offset and per_stream.
35 * FFT: batched in-order complex-to-complex f32 transform of n = 2^k points (4 <= n <= 2048), interleaved
36 * (re, im). Forward is X[m] = sum x[l] exp(-2 pi i l m / n), inverse uses +i and is NOT normalised (as cuFFT).
37 * Stockham radix 4 (one radix-2 stage first when k is odd), one CTA of n / 4 threads per transform, shared
38 * memory between stages, f32 twiddles computed by the unit in f64.
39 * Real FFT (cuFFT R2C / C2R layout, 8 <= n <= 4096): R2C maps n reals to the n / 2 + 1 complex outputs X[0..n/2];
40 * C2R maps those back to n reals, unnormalised (C2R(R2C(x)) = n x); its input must be Hermitian data with
41 * Im X[0] = Im X[n/2] = 0 (other values of those two words change the result: the kernel does not clear them).
42 * Both run an n / 2-point complex FFT plus one split (R2C) or merge (C2R) pass.
43 * 2-D and 3-D: complex transform of a row-major [d0][d1][d2] array (last index fastest, as cufftPlan3d), each
44 * dims[i] in 4..2048, by one batched 1-D pass per axis followed by a transpose. The unit plans the passes (kind 6);
45 * omega_gpu_fft_plan_walk exposes the plan and its launches.
46 * Other lengths (EXPERIMENTAL): omega_gpu_fft_c2c, _r2c, _c2r and _c2c_nd take any n (each dims[i]) in 2..4096 and
47 * run the lengths above on the kernels above, the rest through omega_gpu_fft_many (cufftPlanMany layouts below):
48 * Stockham radix 2, 3, 4, 5 and 7 passes of 128-thread CTAs (kind 7) over global memory, Bluestein's chirp-z
49 * algorithm for lengths with another prime factor (kind 8), strided copies for gather, axis rotation, Hermitian
50 * extension and scatter (kind 9). Error bounds: evidence/MATHLIBS-GAPS-2026-11-06.
51 */
52#include <stddef.h>
53#include <stdint.h>
54
55#ifdef __cplusplus
56extern "C" {
57#endif
58
59enum {
60 OMEGA_GPU_ML_OK = 0,
61 OMEGA_GPU_ML_BAD_ARGS = -1, /* NULL pointer, zero count, or a shape rule broken */
62 OMEGA_GPU_ML_TOO_LARGE = -2, /* past the launch envelope below */
63 OMEGA_GPU_ML_CODEGEN_FAIL = -3, /* the unit refused, or replay, allocation, budget or encoding failed */
64 OMEGA_GPU_ML_CHIP_FAIL = -4, /* device open, submit or marker failed */
65 OMEGA_GPU_ML_UNWRITTEN = -5 /* output words still equal to their poison after the run */
66};
67
68typedef enum { OMEGA_GPU_RNG_U64 = 0, OMEGA_GPU_RNG_UNIFORM = 1, OMEGA_GPU_RNG_NORMAL = 2 } OmegaGpuRngKind;
69
70#define OMEGA_GPU_RNG_THREADS 128u
71#define OMEGA_GPU_RNG_MAX_STREAMS (1024u * OMEGA_GPU_RNG_THREADS) /* one launch, at most 1024 CTAs */
72#define OMEGA_GPU_RNG_MAX_OUTPUTS (1u << 28) /* nstreams * per_stream */
73#define OMEGA_GPU_FFT_MIN_N 4u
74#define OMEGA_GPU_FFT_MAX_N 2048u
75#define OMEGA_GPU_FFT_MAX_CTAS 1024u /* transforms per launch; larger batches take several launches */
76#define OMEGA_GPU_FFT_REAL_MIN_N 8u
77#define OMEGA_GPU_FFT_REAL_MAX_N 4096u
78#define OMEGA_GPU_FFT_MAX_ELEMENTS (1u << 27) /* batch * n (R2C, C2R) or batch * prod(dims) (2-D, 3-D) */
79#define OMEGA_GPU_PHILOX_THREADS 128u
80#define OMEGA_GPU_PHILOX_MAX_STREAMS (1024u * OMEGA_GPU_PHILOX_THREADS)
81
82typedef struct {
83 int kernel_cache_hit;
84 uint32_t insn_count; /* encoded instructions (padded) */
85 uint32_t gpr_peak; /* allocator peak */
86 uint32_t gpr_declared; /* QMD declaration */
87 uint8_t code_digest[32]; /* sha256 of the code */
88 uint64_t chip_calls;
89 uint64_t elapsed_ns; /* submit to second marker, summed over launches */
90 uint32_t completion_marker;
91 uint64_t unwritten_words;
92 uint32_t threads_per_cta;
93 uint32_t ctas_last_launch;
94 uint64_t call_ns;
95} OmegaGpuMathInfo;
96
97/* Host only: build (and cache) the kernel, fill the codegen fields of info. No device is opened. */
98int omega_gpu_rng_codegen(OmegaGpuRngKind kind, OmegaGpuMathInfo *info);
99int omega_gpu_fft_codegen(uint32_t n, int inverse, OmegaGpuMathInfo *info);
100int omega_gpu_philox_codegen(OmegaGpuMathInfo *info);
101
102/* out holds nstreams * per_stream values: u64 for OMEGA_GPU_RNG_U64, float otherwise. */
103int omega_gpu_rng_generate(OmegaGpuRngKind kind, uint64_t seed, uint64_t stream0, uint32_t nstreams,
104 uint32_t offset, uint32_t per_stream, void *out, OmegaGpuMathInfo *info);
105
106/* The f32 twiddle table the kernels read: tw[2m], tw[2m + 1] = w^m, m < n, w = exp(-+2 pi i / n). */
107int omega_gpu_fft_twiddles(uint32_t n, int inverse, float *tw);
108
109/* in, out: batch * n interleaved complex f32 (2 * n * batch floats); in and out may not overlap. */
110int omega_gpu_fft_c2c(const float *in, float *out, uint32_t n, uint32_t batch, int inverse, OmegaGpuMathInfo *info);
111
112/* out: nstreams * per_stream words (see Philox above); nstreams * per_stream <= OMEGA_GPU_RNG_MAX_OUTPUTS. */
113int omega_gpu_philox_generate(uint64_t seed, uint64_t subseq0, uint32_t nstreams, uint64_t offset, uint32_t per_stream,
114 uint32_t *out, OmegaGpuMathInfo *info);
115
116/* EXPERIMENTAL. cuRAND Philox distributions (see Philox above). */
117typedef enum {
118 OMEGA_GPU_PHILOX_RAW = 0,
119 OMEGA_GPU_PHILOX_UNIFORM = 1,
120 OMEGA_GPU_PHILOX_UNIFORM_DOUBLE = 2,
121 OMEGA_GPU_PHILOX_UNIFORM2_DOUBLE = 3,
122 OMEGA_GPU_PHILOX_NORMAL = 4
123} OmegaGpuPhiloxDist;
124
125/* EXPERIMENTAL. out: nstreams * per_stream values, u32 (RAW), float (UNIFORM, NORMAL) or double (the two _DOUBLE
126 * distributions), in the layout above; nstreams * per_stream <= OMEGA_GPU_RNG_MAX_OUTPUTS. Other dist: BAD_ARGS. */
127int omega_gpu_philox_generate_dist(OmegaGpuPhiloxDist dist, uint64_t seed, uint64_t subseq0, uint32_t nstreams,
128 uint64_t offset, uint32_t per_stream, void *out, OmegaGpuMathInfo *info);
129
130/* R2C: in batch * n f32, out batch * (n / 2 + 1) interleaved complex. C2R: the reverse. in and out may not overlap. */
131int omega_gpu_fft_r2c(const float *in, float *out, uint32_t n, uint32_t batch, OmegaGpuMathInfo *info);
132int omega_gpu_fft_c2r(const float *in, float *out, uint32_t n, uint32_t batch, OmegaGpuMathInfo *info);
133
134/* ndim 1..3 dims, in and out batch * prod(dims) interleaved complex f32, not overlapping. */
135int omega_gpu_fft_c2c_nd(const float *in, float *out, uint32_t ndim, const uint32_t *dims, uint32_t batch, int inverse,
136 OmegaGpuMathInfo *info);
137
138typedef enum { OMEGA_GPU_FFT_C2C_ND = 0, OMEGA_GPU_FFT_R2C = 1, OMEGA_GPU_FFT_C2R = 2 } OmegaGpuFftPlanMode;
139
140/* One launch of a plan step. Buffers: 0 in, 1 out, 2 scratch. */
141typedef struct {
142 uint32_t kind; /* unit kernel: 1 complex FFT, 4 real split (b 0) or merge (b 1), 5 transpose */
143 uint32_t a, b; /* unit arguments: kind 1 log2 n and direction; kind 4 log2 n of the real
144 * transform and split/merge; kind 5 log2 rows and log2 columns */
145 uint32_t src, dst; /* buffers read and written */
146 uint64_t src_off, dst_off; /* byte offsets of this launch's first row in src and dst */
147 uint32_t threads, grid, shared_bytes;
148 uint32_t total, first; /* kind 5: elements of the whole step, first element of this launch */
149 uint32_t tw_n, tw_inverse; /* twiddle table the launch reads (tw_n 0: none) */
150 const float *tw; /* that table, 2 * tw_n floats, valid during the callback only */
151 size_t elements; /* f32 words the launch writes */
152} OmegaGpuFftLaunch;
153typedef int (*OmegaGpuFftLaunchFn)(void *ctx, const OmegaGpuFftLaunch *launch);
154
155/* Validate a plan (R2C and C2R: ndim 1, dims[0] = n, inverse 0), set bytes[] to the in, out and scratch sizes and,
156 * when fn is set, call it for every launch in order (a nonzero return stops the walk and is returned). The plan and
157 * private copies of its twiddle tables are built under the session lock; fn runs after the lock is released and may
158 * call this API. Host only; opens no device. */
159int omega_gpu_fft_plan_walk(OmegaGpuFftPlanMode mode, uint32_t ndim, const uint32_t *dims, uint32_t batch, int inverse,
160 size_t bytes[3], OmegaGpuFftLaunchFn fn, void *ctx);
161
162/* EXPERIMENTAL. cufftPlanMany: rank 1..3 transforms of n[0..rank-1] (last index fastest), any n[i] in 2..4096.
163 * Element (b, x0, .., x[rank-1]) of a side sits at b * dist + stride * (x[rank-1] + e[rank-1] * (x[rank-2] +
164 * e[rank-2] * x[rank-3])), e = inembed (in) or onembed (out), in elements of that side (complex: 2 floats; real:
165 * 1 float). inembed and onembed all zero select cuFFT's basic layout (stride 1, embed = the side's extents, dist =
166 * their product; stride and dist are ignored): the complex side of R2C and C2R has n[rank-1] / 2 + 1 points on the
167 * last axis, and the real side of an in-place transform pads that axis to 2 (n[rank-1] / 2 + 1) floats. Else both are
168 * given, e[i] >= the side's extent for i >= 1, stride >= 1. Output addresses must be distinct (else BAD_ARGS).
169 * C2C uses inverse 0/1; R2C is forward and C2R inverse (inverse must be 0). C2R is unnormalised, as cuFFT:
170 * C2R(R2C(x)) = prod(n) x; it reads the n[rank-1] / 2 + 1 Hermitian half and drops Im of the DC and Nyquist bins.
171 * Limits: batch * prod(n) <= OMEGA_GPU_FFT_MAX_ELEMENTS, every side's highest element index < 2^32 and its extent
172 * <= 2^28 elements (else TOO_LARGE). The unit plans each axis (kind 12): Stockham passes of radix 4, 2, 3, 5 and 7
173 * when n factors over them, else Bluestein with a power-of-two M >= 2n - 1. */
174typedef enum { OMEGA_GPU_FFT_TYPE_C2C = 0, OMEGA_GPU_FFT_TYPE_R2C = 1, OMEGA_GPU_FFT_TYPE_C2R = 2 } OmegaGpuFftType;
175typedef struct {
176 uint32_t rank;
177 uint32_t n[3];
178 uint32_t inembed[3], istride, idist;
179 uint32_t onembed[3], ostride, odist;
180 uint32_t batch;
181 OmegaGpuFftType type;
182 int inverse;
183} OmegaGpuFftMany;
184#define OMEGA_GPU_FFT_MANY_MAX_N 4096u
185#define OMEGA_GPU_FFT_MANY_THREADS 128u
186
187/* EXPERIMENTAL. in and out are the layouts above; in == out runs in place, any other overlap is BAD_ARGS. Output
188 * elements the layout does not address are left as they were. */
189int omega_gpu_fft_many(const OmegaGpuFftMany *plan, const float *in, float *out, OmegaGpuMathInfo *info);
190
191/* EXPERIMENTAL. Buffers of a many plan: user in and out, two scratch arrays, the Bluestein work arrays and the FFT of
192 * its chirp filter, and the constant table (twiddles and chirps, written by the caller from launch->table). */
193enum {
194 OMEGA_GPU_FFT_BUF_IN = 0,
195 OMEGA_GPU_FFT_BUF_OUT = 1,
196 OMEGA_GPU_FFT_BUF_S0 = 2,
197 OMEGA_GPU_FFT_BUF_S1 = 3,
198 OMEGA_GPU_FFT_BUF_W = 4,
199 OMEGA_GPU_FFT_BUF_W2 = 5,
200 OMEGA_GPU_FFT_BUF_B = 6,
201 OMEGA_GPU_FFT_BUF_TABLE = 7,
202 OMEGA_GPU_FFT_MANY_BUFS = 8
203};
204/* One launch of a many plan. The kernel's constant bank at 0x380 holds the nptr 64-bit addresses (buffer buf[i] plus
205 * off[i] bytes), then the nwords 32-bit words. */
206typedef struct {
207 uint32_t kind; /* unit kernel: 7 Stockham pass, 8 Bluestein step, 9 strided copy */
208 uint32_t a, b; /* kind 7 radix and direction; kind 8 variant and log2 M; kind 9 mode and 0 */
209 uint32_t nptr; /* 3 (kinds 7, 8) or 2 (kind 9) */
210 uint32_t buf[3]; /* OMEGA_GPU_FFT_BUF_* of each address */
211 uint64_t off[3]; /* byte offset into that buffer */
212 uint32_t nwords; /* 8, 3 or 18; word 0 is the step's thread count, word 1 this launch's first thread */
213 uint32_t words[18];
214 uint32_t threads, grid; /* OMEGA_GPU_FFT_MANY_THREADS, at most OMEGA_GPU_FFT_MAX_CTAS */
215 size_t elements; /* f32 words the launch writes at most */
216 const void *table; /* the plan's whole constant table, bytes[OMEGA_GPU_FFT_BUF_TABLE]; valid in the callback */
217} OmegaGpuFftManyLaunch;
218typedef int (*OmegaGpuFftManyLaunchFn)(void *ctx, const OmegaGpuFftManyLaunch *launch);
219
220/* EXPERIMENTAL. Validate a many plan, set bytes[] to the sizes of the eight buffers and, when fn is set, call it for
221 * every launch in order (a nonzero return stops the walk and is returned). in_place: in and out are one buffer (the
222 * basic layout pads the real side) and launches name OMEGA_GPU_FFT_BUF_IN for it; bytes[OUT] is then 0. The plan is
223 * built under the session lock; fn runs after it is released and may call this API. Host only; opens no device. */
224int omega_gpu_fft_many_walk(const OmegaGpuFftMany *plan, int in_place, size_t bytes[OMEGA_GPU_FFT_MANY_BUFS],
225 OmegaGpuFftManyLaunchFn fn, void *ctx);
226
227/* Negative controls (tests only): which 0 none, 1 RNG, 2 FFT, 3 Philox, 4 real split/merge, 5 transpose, 7 Stockham
228 * pass, 8 Bluestein step, 9 strided copy; level 1 or 2, Philox 1..6 (see om/mathlibs/mathlibs_ir.om: RNG 1 rotates
229 * by 8 instead of 7, RNG 2 perturbs the central erfinv constant; FFT 1 flips the direction of the butterflies, FFT 2
230 * drops the twiddles of the first twiddled stage; Philox 1 steps the second key word by W0 instead of W1, Philox 2
231 * runs 9 rounds, 3 drops the 2^-33 half step of the uniform, 4 ignores the words of the block before the first group
232 * (offset % 4 != 0), 5 swaps the Box-Muller sin and cos, 6 truncates instead of rounding uniform2_double;
233 * split/merge 1 drops the twiddle multiply, 2 skips the bin n / 4 element; transpose 1 copies without transposing,
234 * 2 drops the high index part; Stockham 1 flips the direction, 2 skips the twiddles; Bluestein 1 drops the chirp of
235 * the premultiply, 2 drops the 1 / M of the postmultiply; copy 1 drops the conjugate, 2 drops the source batch
236 * stride). Clears the kernel cache. */
237void omega_gpu_mathlibs_test_set_mutant(int which, int level);
238void omega_gpu_mathlibs_cache_clear(void);
239const char *omega_gpu_mathlibs_last_error(void);
240
241#ifdef __cplusplus
242}
243#endif
244#endif