RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Numerical computing

GPU numerics

Dense and batched GEMM, Cholesky and LU, sparse products, random numbers and BVH queries as GPU compute kernels on Metal and Vulkan.

import 'package:riptide_numerics_gpu/riptide_numerics_gpu.ray';
16 classes64 functions and methods72 of 134 documented

Overview

GPU kernels for numerics on Evelyn's GPU compute (Metal, Vulkan).

KernelShaderCPU twinProof (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.raybit-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.queryAabbcount 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:

KernelShaderProof (Metal, M5 Pro)
f32 GEMM C = αAB + βC, any m, n, k, batched on z (shared operand: batch stride 0); 64x64 tiles, 4x4 per invocationgemm_f32.compmax 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 outputgemm_half.compvs 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 elementgemm_small.comp5,000 x (4x7 @ 7x3): 9.3e-8
batched Cholesky (+ solve), one invocation per matrix, n ≤ 64chol_batched.compn = 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 matrixlu_batched.compresidual ≤ 1.6e-4 at n = 32 (f32, random matrices); info = first zero pivot
completion token for synchronous callerssignal.compused 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)
  • GpuGemmBackend implements riptide_numerics_cpu' GemmBackend (computeType float32, minWork 320³ from the measured crossover). The interface is synchronous and Evelyn GPU only reports completion through an event-loop callback, so gemmSync appends signal.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(...), then reset after the command buffer completes.
  • Engines: GemmEngine is the seam for a Riptide engine (Metal 4 tensors, MPP matmul2d, Evelyn patch 27), which needs a released Riptide SDK engine that exports sgpu_*; none does yet.

Functions and constants

Functions

packMatrixfunction
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.

unpackMatrixfunction
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.

packF32function
void packF32(NDArray x, Float32List out)

x (2-d, any strides and real dtype) into out as row-major float32.

Classes

final class NumericsGpu

The loaded kernels. One per isolate is enough; pipelines are created once.

Static

loadstaticmethod
static Future<NumericsGpu> load({ByteData? shaderBundle})
viewstaticmethod
static gpu.BufferView view(gpu.DeviceBuffer b)

Properties

contextfield
final gpu.GpuContext context

Methods

uploadmethod
GpuCsrMatrix upload(CsrMatrix a)

Uploads a (values narrowed to f32) once; reuse it for every SpMV.

floatsmethod
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.

uploadBvhmethod
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).

resetmethod
void reset()

Frees the per-call uniform space once the commands that used it have completed.

final class GpuCsrMatrix

A CSR matrix resident on the GPU.

Properties

rowsfield
final int rows
colsfield
final int cols
indptrfield
final gpu.DeviceBuffer indptr
indicesfield
final gpu.DeviceBuffer indices
valuesfield
final gpu.DeviceBuffer values
class

GpuBvh

final class GpuBvh

An AabbBvh resident on the GPU.

Properties

final int nodeCount
nodesfield
final gpu.DeviceBuffer nodes
final gpu.DeviceBuffer primOrder
boxesfield
final gpu.DeviceBuffer boxes
abstract interface class GemmEngine

A GPU that runs dense matrix products. FlutterGpuGemmEngine is the one implementation today.

Properties

namegetter
String get name

Methods

gemmSyncmethod
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.

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

BatchedCholeskyconstructor
BatchedCholesky(this.l, this.x, this.info)

Properties

lfield
final NDArray l
xfield
final NDArray? x
infofield
final Int32List info
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

BatchedLuconstructor
BatchedLu(this.lu, this.pivots, this.x, this.info)

Properties

lufield
final NDArray lu
pivotsfield
final Int32List pivots
xfield
final NDArray? x
infofield
final Int32List info
final class ChainCholesky

A LinalgChain.cholesky recorded on the chain: where its L, X and per-matrix info live until LinalgChain.readCholesky.

Properties

afield
final GpuMatrix a

The factored matrices (L in the lower triangle) and the solutions, both in place.

rhsfield
final GpuMatrix? rhs
infofield
final gpu.DeviceBuffer info
nfield
final int n
nrhsfield
final int nrhs
batchfield
final int batch
class

ChainLu

final class ChainLu

A LinalgChain.lu recorded on the chain (see ChainCholesky).

Properties

afield
final GpuMatrix a
rhsfield
final GpuMatrix? rhs
pivotsfield
final gpu.DeviceBuffer pivots
infofield
final gpu.DeviceBuffer info
nfield
final int n
nrhsfield
final int nrhs
batchfield
final int batch
final class NumericsLinalgGpu implements GemmEngine

The loaded dense kernels. Create once per isolate with open.

Static

openstaticmethod
static Future<NumericsLinalgGpu?> open({ByteData? shaderBundle})

The kernels, or null when this device has no compute (OpenGL ES) or Evelyn GPU isn't enabled.

hasBlockingWaitstaticfield
static final bool hasBlockingWait

Whether 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 debugForceFlagWait

Benchmarks only: forces the flag-and-settle wait on an engine that has the blocking one, to measure both in one process.

blockingWaitInUsestaticgetter
static bool get blockingWaitInUse

Whether the synchronous waits use the engine's blocking wait.

Properties

contextfield
final gpu.GpuContext context
namegetter
String get name

Methods

uploadmethod
GpuMatrix upload(PackedMatrix p)

Uploads a packed matrix (device buffer of its words).

outputmethod
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.

matmulmethod
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.

batchedLumethod
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).

gemmSyncmethod
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.

chainmethod
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).

uploadF32method
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).

readF32method
Float32List readF32(GpuMatrix m)

Reads a f32 output back as a flat row-major list, once its command buffer has completed.

uploadI32method
GpuIntMatrix uploadI32(Int32List data, int rows, int cols)

Uploads a row-major int32 rows x cols matrix for encodeGemmI32.

outputI32method
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.

readI32method
Int32List readI32(GpuIntMatrix m)

Reads an int32 output back, once its command buffer has completed.

matmulI32method
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).

resetmethod
void reset()

Frees per-call uniform space once the command buffers that used it (from the encode* calls) have completed.

backendmethod
GpuGemmBackend backend({int minWork = GpuGemmBackend.defaultMinWork, GpuPrecision precision = GpuPrecision.f32})

A GemmBackend' blocked factorizations.

final class GpuIntMatrix

A row-major int32 matrix resident on the GPU (NumericsLinalgGpu.encodeGemmI32).

Properties

rowsfield
final int rows
colsfield
final int cols
bufferfield
final gpu.DeviceBuffer buffer
final class GpuMatrix

A matrix (or batch) resident on the GPU, with its layout.

Properties

layoutfield
final PackedMatrix layout
bufferfield
final gpu.DeviceBuffer buffer
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

GpuGemmBackendconstructor
GpuGemmBackend(this.engine, {this.minWork = defaultMinWork, this.precision = GpuPrecision.f32})

Static

static const int defaultMinWork = 320 * 320 * 320

Below ~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

enginefield
final GemmEngine engine
final GpuPrecision precision
minWorkfield
final int minWork
namegetter
String get name
DType get computeType

Methods

gemmmethod
bool gemm(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0})
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

statsgetter
ComputeStats get stats

What the planner did: dispatches, barriers placed and skipped.

Methods

gemmmethod
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.

smallGemmmethod
GpuMatrix smallGemm(GpuMatrix a, GpuMatrix b, {GpuMatrix? into})

Records batched small products Ct = At @ Bt (f32) and returns C.

choleskymethod
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.

lumethod
ChainLu lu(GpuMatrix a, {GpuMatrix? rhs})

Records the batched LU with partial pivoting of a ([batch, n, n] f32, in place: packed L\U) and, with rhs, A X = B (in place). Read with readLu after run.

BatchedCholesky readCholesky(ChainCholesky c)

Reads a cholesky result (after run).

readLumethod
BatchedLu readLu(ChainLu c)

Reads an lu result (after run).

runSyncmethod
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.

runmethod
Future<void> run()

Waits for everything recorded: one submit, one wait. Nothing was read back; use read on the results.

readmethod
NDArray read(GpuMatrix m)

Reads a f32 result back (after run).

enum GpuPrecision

What the GEMM inputs are stored as on the GPU. Accumulation and C are always f32.

Values

f32value
f32

Float32 inputs.

f16value
f16

Float16 inputs (two per uint32), f32 accumulation: the mixed-precision path.

bf16value
bf16

Bfloat16 inputs (two per uint32), f32 accumulation.

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

PackedMatrixconstructor
PackedMatrix(this.words, this.rows, this.cols, this.ld, this.batch, this.batchStride, this.precision)

Properties

wordsfield
final Uint32List words
rowsfield
final int rows
colsfield
final int cols
ldfield
final int ld
batchfield
final int batch
final int batchStride
final GpuPrecision precision
final class RiptideGemmEngine implements GemmEngine

GemmEngine on Riptide's library GEMM.

Static

openstaticmethod
static RiptideGemmEngine? open({GpuDevice? device})

The engine, or null when this process has no Riptide device with the Metal 4 tensor tier.

Properties

devicefield
final GpuDevice device
kernelsfield
final GpuKernels kernels
namegetter
String get name

Methods

gemmSyncmethod
void gemmSync(NDArray a, NDArray b, NDArray c, {double alpha = 1, double beta = 0, GpuPrecision precision = GpuPrecision.f32})
disposemethod
void dispose()