Overview
GPU kernels for numerics on Evelyn's GPU compute (Metal, Vulkan).
| Kernel | Shader | CPU twin | Proof (Metal, M5 Pro) |
|---|---|---|---|
| CSR SpMV y = αAx + βy (one invocation per row) and SpMM Y = AX (one per output element), f32 | , | CsrMatrix.spmv, CsrMatrix.spmm (riptide_numerics_sparse) | max relative error < 2e-6 vs the f64 CPU result on a ragged random matrix and on Poisson |
Philox4x32-10, raw u32 or f32 uniforms float(x >> 8)·2⁻²⁴ | Philox4x32.block (riptide_numerics_stats) and the philox4x32 reference in test/support.ray | bit-identical on 65,536 blocks (262,144 words) across a counter wrap; the CPU reference reproduces the Random123 known-answer vectors | |
Stackless BVH box queries over riptide_numerics_spatial's flattened AabbBvh (nodes uploaded byte for byte) | AabbBvh.queryAabb | count and first hit identical to brute force for 4,096 queries over 20,000 boxes, after build and after refit |
final g = await NumericsGpu.load(); // the package asset
final a = g.upload(csr); // CsrMatrix -> device buffers (f32 values)
final cmd = g.context.createCommandBuffer();
g.encodeSpmv(cmd, a, x, y);
g.encodePhilox(cmd, out, blocks: n, key0: seed, key1: stream); // counter (i, 0, 0, 0)
await cmd.submitAndWait();
g.reset();
Dense linear algebra (part A)
NumericsLinalgGpu, on riptide_numerics_cpu NDArrays:
| Kernel | Shader | Proof (Metal, M5 Pro) |
|---|---|---|
| f32 GEMM C = αAB + βC, any m, n, k, batched on z (shared operand: batch stride 0); 64x64 tiles, 4x4 per invocation | gemm_f32.comp | max relative error vs the float64 CPU GEMM 8e-8.. 6.2e-7 over 1x1x1.. 513x257x31 and 256³, transposed views, α/β, batched |
| mixed precision GEMM: float16 or bfloat16 inputs (two per uint32), f32 accumulation and output | gemm_half.comp | vs the exact product of the rounded inputs ≤ 9.5e-7 (only f32 accumulation error); vs the unrounded inputs 2.5e-4 (f16) and 2.0e-3 (bf16) at k = 512, under ε·√k |
| batched small GEMM, one invocation per output element | gemm_small.comp | 5,000 x (4x7 @ 7x3): 9.3e-8 |
| batched Cholesky (+ solve), one invocation per matrix, n ≤ 64 | chol_batched.comp | n = 1..32, 200 matrices: ‖LLᵀ − A‖ 4.7e-7, residual 7.2e-7; info = failing minor |
| batched LU with partial pivoting (+ solve), one invocation per matrix | lu_batched.comp | residual ≤ 1.6e-4 at n = 32 (f32, random matrices); info = first zero pivot |
| completion token for synchronous callers | signal.comp | used by every GpuGemmBackend.gemm |
final la = (await NumericsLinalgGpu.open())!; // null without compute (OpenGL ES)
final c = await la.matmul(a, b); // float32 NDArray
final h = await la.matmul(a, b, precision: GpuPrecision.bf16); // bf16 in, f32 accumulate
final chol = await la.batchedCholesky(spd, rhs: rhs); // [batch, n, n], [batch, n, nrhs]
final lu = await la.batchedLu(a3, rhs: rhs);
final backend = la.backend(); // riptide_numerics_cpu GemmBackend (float32)
GpuGemmBackendimplements riptide_numerics_cpu'GemmBackend(computeTypefloat32,minWork320³ from the measured crossover). The interface is synchronous and Evelyn GPU only reports completion through an event-loop callback, sogemmSyncappendssignal.comp(after a buffer barrier) and polls a host-visible word for the submit's token.- Persistent buffers:
upload(packMatrix(a, precision)),output(...),encodeGemm(commands...),encodeSmallGemm(...), thenresetafter the command buffer completes. - Engines:
GemmEngineis the seam for a Riptide engine (Metal 4 tensors, MPPmatmul2d, Evelyn patch 27), which needs a released Riptide SDK engine that exportssgpu_*; none does yet.
Functions and constants
Functions
PackedMatrix packMatrix(NDArray a, GpuPrecision precision)Packs a 2-d [rows, cols] or 3-d [batch, rows, cols] array of any dtype, strides or order (transposed views are packed by value; nothing on the GPU needs a transpose flag). Values round to nearest even into the precision.
NDArray unpackMatrix(PackedMatrix p)The values a packed matrix holds, as float64 ([batch, rows, cols], or 2-d when batch is 1): what the GPU actually multiplies, for error bounds in tests.
Future<GemmEngine?> openGemmEngine()The best GEMM engine on this device: Riptide's Metal 4 kernels when the engine has them, else Evelyn GPU compute, else null.
void packF32(NDArray x, Float32List out)x (2-d, any strides and real dtype) into out as row-major float32.
Classes
NumericsGpu
final class NumericsGpu
The loaded kernels. One per isolate is enough; pipelines are created once.
Static
static Future<NumericsGpu> load({ByteData? shaderBundle})static gpu.BufferView view(gpu.DeviceBuffer b)Properties
final gpu.GpuContext contextMethods
GpuCsrMatrix upload(CsrMatrix a)Uploads a (values narrowed to f32) once; reuse it for every SpMV.
gpu.DeviceBuffer floats(int n)A device buffer of n floats (host-visible, so results can be read back).
gpu.DeviceBuffer floatsFrom(Float32List v)void encodeSpmv(gpu.CommandBuffer commands, GpuCsrMatrix a, gpu.DeviceBuffer x, gpu.DeviceBuffer y, {double alpha = 1, double beta = 0})Records y = alpha·A·x + beta·y into commands (one dispatch, 64 rows per workgroup).
void encodeSpmm(gpu.CommandBuffer commands, GpuCsrMatrix a, gpu.DeviceBuffer x, int k, gpu.DeviceBuffer y)Records Y = A·X into commands: X is cols × k and Y rows × k, both row-major f32 (one invocation per output element).
void encodePhilox(gpu.CommandBuffer commands, gpu.DeviceBuffer out, {required int blocks, required int key0, required int key1, int base = 0, int c1 = 0, int c2 = 0, int c3 = 0, bool asFloats = false})Records blocks Philox4x32-10 blocks into out (4 words per block): counter (base + i, c1, c2, c3), key (k0, k1). asFloats writes f32 uniforms in [0, 1) (float(x >> 8)·2⁻²⁴) instead of raw u32 words.
GpuBvh uploadBvh(AabbBvh bvh, Float64List mins, Float64List maxs)Uploads a riptide_numerics_spatial AabbBvh (its 32-byte nodes byte for byte) and the primitive boxes it was built over (mins, maxs: 3 doubles per box, narrowed to f32).
void encodeBvhQuery(gpu.CommandBuffer commands, GpuBvh bvh, gpu.DeviceBuffer queries, int queryCount, gpu.DeviceBuffer hits)Records one stackless traversal per query box (queries: 6 floats each, min then max) writing 2 ints per query into hits: the number of primitives whose box overlaps it, and the smallest such index (−1 for none).
void reset()Frees the per-call uniform space once the commands that used it have completed.
GpuCsrMatrix
final class GpuCsrMatrix
A CSR matrix resident on the GPU.
Properties
final int rowsfinal int colsfinal gpu.DeviceBuffer indptrfinal gpu.DeviceBuffer indicesfinal gpu.DeviceBuffer valuesGpuBvh
final class GpuBvh
An AabbBvh resident on the GPU.
Properties
final int nodeCountfinal gpu.DeviceBuffer nodesfinal gpu.DeviceBuffer primOrderfinal gpu.DeviceBuffer boxesGemmEngine
abstract interface class GemmEngine
A GPU that runs dense matrix products. FlutterGpuGemmEngine is the one implementation today.
Properties
String get nameMethods
void gemmSync(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0, GpuPrecision precision = GpuPrecision.f32})C = alpha * A @ B + beta * C, waiting for the GPU without returning to the event loop (for GemmBackend). c must be float32 or float64; it is written in place.
BatchedCholesky
final class BatchedCholesky
Result of NumericsLinalgGpu.batchedCholesky: L (lower, f32), the solutions when a right-hand side was given, and per-matrix info (0 = ok, j + 1 = minor j + 1 not positive definite).
Constructors
BatchedCholesky(this.l, this.x, this.info)Properties
final NDArray lfinal NDArray? xfinal Int32List infoBatchedLu
final class BatchedLu
Result of NumericsLinalgGpu.batchedLu: packed L\U (f32, unit-diagonal L below), 0-based pivots per step, the solutions when a right-hand side was given, per-matrix info (0 = ok, j + 1 = zero pivot at step j).
Constructors
BatchedLu(this.lu, this.pivots, this.x, this.info)Properties
final NDArray lufinal Int32List pivotsfinal NDArray? xfinal Int32List infoChainCholesky
final class ChainCholesky
A LinalgChain.cholesky recorded on the chain: where its L, X and per-matrix info live until LinalgChain.readCholesky.
Properties
final GpuMatrix aThe factored matrices (L in the lower triangle) and the solutions, both in place.
final GpuMatrix? rhsfinal gpu.DeviceBuffer infofinal int nfinal int nrhsfinal int batchChainLu
final class ChainLu
A LinalgChain.lu recorded on the chain (see ChainCholesky).
Properties
final GpuMatrix afinal GpuMatrix? rhsfinal gpu.DeviceBuffer pivotsfinal gpu.DeviceBuffer infofinal int nfinal int nrhsfinal int batchNumericsLinalgGpu
final class NumericsLinalgGpu implements GemmEngine
The loaded dense kernels. Create once per isolate with open.
Static
static Future<NumericsLinalgGpu?> open({ByteData? shaderBundle})The kernels, or null when this device has no compute (OpenGL ES) or Evelyn GPU isn't enabled.
static final bool hasBlockingWaitWhether the engine has Evelyn's CommandBuffer.submitAndWaitSync (patch 30; the pinned Riptide SDK's engine has not until an Evelyn release carries it). Found once, through dynamic, so this file compiles on both.
static bool debugForceFlagWaitBenchmarks only: forces the flag-and-settle wait on an engine that has the blocking one, to measure both in one process.
static bool get blockingWaitInUseWhether the synchronous waits use the engine's blocking wait.
Properties
final gpu.GpuContext contextString get nameMethods
GpuMatrix output(int rows, int cols, {int batch = 1})A host-visible f32 output of batch x rows x cols (row-major, ld = cols).
void encodeGemm(gpu.CommandBuffer commands, GpuMatrix a, GpuMatrix b, GpuMatrix c, {double alpha = 1, double beta = 0, int repeat = 1})Records C = alpha * A @ B + beta * C (batched when A or B has a batch; a batch of 1 is shared). A and B must have the same precision; C is f32. Any m, n, k.
void encodeSmallGemm(gpu.CommandBuffer commands, GpuMatrix a, GpuMatrix b, GpuMatrix c)Records batched small products Ct = At @ Bt (one invocation per output element).
NDArray readResult(GpuMatrix m)Reads a f32 output (or a LinalgChain result) back, once its command buffer has completed.
Future<NDArray> matmul(NDArray a, NDArray b, {GpuPrecision precision = GpuPrecision.f32, double alpha = 1})A @ B on the GPU (2-d, or batched 3-d with the same batch or a shared 2-d operand); the result is float32.
Future<NDArray> batchedMatmul(NDArray a, NDArray b)Batched small At @ Bt ([batch, m, k] @ [batch, k, n]), one invocation per element; float32 result.
Future<BatchedCholesky> batchedCholesky(NDArray a, {NDArray? rhs})Cholesky of each [batch, n, n] symmetric positive definite matrix (f32, one invocation per matrix; meant for n <= 64), and A X = B for rhs [batch, n, nrhs] when given. One call is a LinalgChain of one op; to factor several, record them in one chain (LinalgChain.cholesky) and wait once.
Future<BatchedLu> batchedLu(NDArray a, {NDArray? rhs})LU with partial pivoting of each [batch, n, n] matrix (f32, one invocation per matrix), and A X = B for rhs [batch, n, nrhs] when given. One call is a LinalgChain of one op (LinalgChain.lu).
Future<BatchedCholesky> batchedCholeskySerial(NDArray a, {NDArray? rhs})batchedCholesky as it was before LinalgChain: one command buffer, one wait and one read per call. Kept as the reference for tests (bit for bit) and the benchmark's "before" rows.
Future<BatchedLu> batchedLuSerial(NDArray a, {NDArray? rhs})batchedLu as it was before LinalgChain (reference, like batchedCholeskySerial).
void gemmSync(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0, GpuPrecision precision = GpuPrecision.f32, Duration timeout = const Duration(seconds: 60)})void gemmSyncSerial(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0, GpuPrecision precision = GpuPrecision.f32, Duration timeout = const Duration(seconds: 60)})gemmSync as it was before LinalgChain.runSync: the signal kernel in a pass of its own after the product's. The signal does not depend on the product, so on Metal it can run, and set the flag, while the product is still running: the CPU then reads a half-written C (factor_gpu_test failed on the hardware tier, PLU error 0.3). Kept as the reference and for the benchmark's "before" row; do not use it for results.
LinalgChain chain()A chain: many GEMMs and small GEMMs recorded into one command buffer with hazard-tracked barriers, one wait at LinalgChain.run, then reads (see LinalgChain).
GpuMatrix uploadF32(Float32List data, int rows, int cols)Uploads a row-major f32 rows x cols matrix as it is (no NDArray, no copy beyond the upload).
Float32List readF32(GpuMatrix m)Reads a f32 output back as a flat row-major list, once its command buffer has completed.
GpuIntMatrix uploadI32(Int32List data, int rows, int cols)Uploads a row-major int32 rows x cols matrix for encodeGemmI32.
GpuIntMatrix outputI32(int rows, int cols)A host-visible int32 rows x cols output for encodeGemmI32.
void encodeGemmI32(gpu.CommandBuffer commands, GpuIntMatrix a, GpuIntMatrix b, GpuIntMatrix c, {required int bound, bool accumulate = false, int repeat = 1})Records C = A @ B (or C += A @ B with accumulate) in 32-bit integers: the exact product whenever every partial sum fits in 32 bits. bound is max|A| · max|B| (the caller knows its inputs); the call refuses when bound · k could reach 2³¹, so a result from this kernel is never a wrapped one. repeat dispatches it that many times (timing), with a barrier between.
Int32List readI32(GpuIntMatrix m)Reads an int32 output back, once its command buffer has completed.
Future<Int32List> matmulI32(Int32List a, Int32List b, {required int m, required int n, required int k, required int bound})A @ B exactly in 32-bit integers (row-major m x k and k x n; bound as in encodeGemmI32).
void reset()Frees per-call uniform space once the command buffers that used it (from the encode* calls) have completed.
GpuGemmBackend backend({int minWork = GpuGemmBackend.defaultMinWork, GpuPrecision precision = GpuPrecision.f32})A GemmBackend' blocked factorizations.
GpuIntMatrix
final class GpuIntMatrix
A row-major int32 matrix resident on the GPU (NumericsLinalgGpu.encodeGemmI32).
Properties
final int rowsfinal int colsfinal gpu.DeviceBuffer bufferGpuMatrix
final class GpuMatrix
A matrix (or batch) resident on the GPU, with its layout.
Properties
final PackedMatrix layoutfinal gpu.DeviceBuffer bufferGpuGemmBackend
final class GpuGemmBackend implements GemmBackend
riptide_numerics_cpu' GemmBackend on a GemmEngine: f32 (or f16/bf16-input) products with f32 accumulation, so factorizations that need float64 accuracy refine on the CPU (solveRefined).
Constructors
GpuGemmBackend(this.engine, {this.minWork = defaultMinWork, this.precision = GpuPrecision.f32})Static
static const int defaultMinWork = 320 * 320 * 320Below ~320^3 multiply-adds packing, upload, submit and readback cost more than the CPU's float64 GEMM: end to end the GPU path takes 4.5 ms at 256 (CPU 4.2 ms) and 7.1 ms at 384 (CPU 12.3 ms) on an M5 Pro.
Properties
final GemmEngine enginefinal GpuPrecision precisionfinal int minWorkString get nameDType get computeTypeMethods
bool gemm(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0})LinalgChain
final class LinalgChain
Many dense products, one submit and one wait: each call records into one compute pass (ComputeBatch) and places a barrier only where an op reads or writes what an earlier one wrote, so a chain of dependent products costs one command buffer instead of one per product, and independent products run without barriers. Results stay on the GPU until read; the per-op API (NumericsLinalgGpu.matmul and friends) uploads, waits and reads back every time, and the loop over it pays the 130 us round trip a time.
final chain = engine.chain();
final x1 = chain.gemm(x0, w1); // x1 = x0 @ w1, on the GPU
final x2 = chain.gemm(x1, w2); // waits for x1 inside the GPU, not on the CPU
await chain.run(); // one submit, one wait
final result = chain.read(x2);
A chain is single use: after run make another. Uniforms live in the chain's own allocator, which run resets.
Properties
Methods
GpuMatrix gemm(GpuMatrix a, GpuMatrix b, {GpuMatrix? into, double alpha = 1, double beta = 0})Records C = alpha * A @ B + beta * C and returns C (a new f32 output unless into is given; a beta other than zero reads it, so pass into holding the values to accumulate onto). A and B must have the same precision.
GpuMatrix smallGemm(GpuMatrix a, GpuMatrix b, {GpuMatrix? into})Records batched small products Ct = At @ Bt (f32) and returns C.
ChainCholesky cholesky(GpuMatrix a, {GpuMatrix? rhs})Records the batched Cholesky of a ([batch, n, n] f32, one invocation per matrix, meant for n <= 64) and, with rhs ([batch, n, nrhs]), A X = B. The kernel works in place: a becomes L (lower) and rhs becomes X, so upload a copy if you need the originals. Read with readCholesky after run.
ChainLu lu(GpuMatrix a, {GpuMatrix? rhs})void runSync({Duration timeout = const Duration(seconds: 60)})run for callers that cannot yield to the event loop (a synchronous GemmBackend): submits, then blocks the isolate until the GPU has finished: submitAndWaitSync on an Evelyn engine (patch 30). Without it, a barrier and the signal kernel go after everything recorded, so the flag the CPU polls is written only once every product has completed (a signal in a pass of its own can run beside the products on Metal), then the settle.
GpuPrecision
enum GpuPrecision
What the GEMM inputs are stored as on the GPU. Accumulation and C are always f32.
Values
PackedMatrix
final class PackedMatrix
A row-major matrix (or a batch of them) laid out for upload: words are f32 bits for GpuPrecision.f32, or two halves per word (element 2i in the low 16 bits) with each row padded to an even length otherwise. ld is the row stride in words (f32: elements), batchStride the stride between matrices in words.
Constructors
PackedMatrix(this.words, this.rows, this.cols, this.ld, this.batch, this.batchStride, this.precision)Properties
final Uint32List wordsfinal int rowsfinal int colsfinal int ldfinal int batchfinal int batchStridefinal GpuPrecision precisionRiptideGemmEngine
final class RiptideGemmEngine implements GemmEngine
GemmEngine on Riptide's library GEMM.
Static
static RiptideGemmEngine? open({GpuDevice? device})The engine, or null when this process has no Riptide device with the Metal 4 tensor tier.
Properties
final GpuDevice devicefinal GpuKernels kernelsString get nameMethods
void gemmSync(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0, GpuPrecision precision = GpuPrecision.f32})void dispose()