RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Riptorch docs · Guide

Writing your own fast exact code

Write a hot loop in Raya, compile it to a shared library, and call it from Python on NumPy buffers.

When you need your own op

Riptorch covers PyTorch’s API. Sometimes the hot loop of your pipeline isn’t in it: a custom scoring function, a special distance, a quantisation scheme. In Python that loop is slow; in C it is fast but unsafe and hard to keep exact. Riptide’s answer is the language Riptorch itself is written in: Raya, open source at github.com/riptide-compute/raya.

The workflow:

  1. Write the loop in Raya, marking each function Python will call with @pragma('raya:export').
  2. Compile it to a C shared library with raya compile shared.
  3. Load it from Python with ctypes and pass NumPy arrays (or any C-contiguous buffer) by address. Nothing is copied.

A complete example: exact int8 dot products

The library has three functions: one dot product, one query against every row of a matrix, and every query against every row at once on the CPU’s matrix unit (the Raya runtime’s raya_matmul_i8, a portable loop where there is no matrix unit).

Example
dot8.ray
// dot8.ray: exact int8 dot products, called from Python.
import 'raya:ffi';

/// The exact dot product of two int8 vectors of length n, summed in a 64-bit integer.
@pragma('raya:export')
int dot8(Pointer<Int8> a, Pointer<Int8> b, int n) {
  final x = a.asTypedList(n), y = b.asTypedList(n);
  var s = 0;
  for (var i = 0; i < n; i++) {
    s += x[i] * y[i];
  }
  return s;
}

/// Scores one query against every row of an [rows, n] int8 matrix: out[r] = rows[r] . q, exactly.
@pragma('raya:export')
int scores8(Pointer<Int8> m, Pointer<Int8> q, int rows, int n, Pointer<Int64> out) {
  final a = m.asTypedList(rows * n), v = q.asTypedList(n), o = out.asTypedList(rows);
  for (var r = 0; r < rows; r++) {
    var s = 0;
    final base = r * n;
    for (var i = 0; i < n; i++) {
      s += a[base + i] * v[i];
    }
    o[r] = s;
  }
  return rows;
}

// The Raya runtime's int8 matrix multiply on the CPU's matrix unit (a portable loop where there is none).
@Native<Void Function(Pointer<Int8>, Pointer<Int8>, Pointer<Int32>, Int64, Int64, Int64, Int64)>(
    symbol: 'raya_matmul_i8', isLeaf: true)
external void matmulI8(Pointer<Int8> a, Pointer<Int8> b, Pointer<Int32> c, int m, int n, int k, int bRows);

/// Every query against every document at once: out[b, r] = queries[b] . docs[r], exact in int32 for n < 2^17.
@pragma('raya:export')
int scores8_matrix(Pointer<Int8> queries, Pointer<Int8> docs, int b, int rows, int n, Pointer<Int32> out) {
  matmulI8(queries, docs, out, b, rows, n, 1);
  return b * rows;
}
Build the shared library (Raya 0.4.0)
$ raya compile shared -o libdot8.dylib dot8.ray
libdot8.dylib: 3 export(s)
dot8.py
# dot8.py: call the Raya library on NumPy int8 arrays, zero-copy.
import ctypes
import numpy as np

lib = ctypes.CDLL("./libdot8.dylib")
i8p = ctypes.POINTER(ctypes.c_int8)
lib.dot8.argtypes = [i8p, i8p, ctypes.c_int64]
lib.dot8.restype = ctypes.c_int64
lib.scores8.argtypes = [i8p, i8p, ctypes.c_int64, ctypes.c_int64, ctypes.POINTER(ctypes.c_int64)]
lib.scores8.restype = ctypes.c_int64

def ptr(a, t):
    assert a.flags["C_CONTIGUOUS"]
    return a.ctypes.data_as(ctypes.POINTER(t))  # the array's own memory: nothing is copied

a = np.full(1024, 127, dtype=np.int8)
b = np.full(1024, -128, dtype=np.int8)
print("dot8:", lib.dot8(ptr(a, ctypes.c_int8), ptr(b, ctypes.c_int8), a.size))
print("exact:", int(a.astype(np.int64) @ b.astype(np.int64)))
print("int8 NumPy dot (wraps):", np.dot(a, b))

rng = np.random.default_rng(0)
docs = rng.integers(-128, 128, size=(5, 384), dtype=np.int8)
q = rng.integers(-128, 128, size=384, dtype=np.int8)
out = np.empty(5, dtype=np.int64)
lib.scores8(ptr(docs, ctypes.c_int8), ptr(q, ctypes.c_int8), 5, 384, ptr(out, ctypes.c_int64))
print("scores:", out.tolist())
print("same as int64 NumPy:", bool((out == docs.astype(np.int64) @ q.astype(np.int64)).all()))

lib.scores8_matrix.argtypes = [i8p, i8p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.POINTER(ctypes.c_int32)]
lib.scores8_matrix.restype = ctypes.c_int64
qs = rng.integers(-128, 128, size=(3, 384), dtype=np.int8)
grid = np.empty((3, 5), dtype=np.int32)
lib.scores8_matrix(ptr(qs, ctypes.c_int8), ptr(docs, ctypes.c_int8), 3, 5, 384, ptr(grid, ctypes.c_int32))
print(grid)
print("matrix unit agrees:", bool((grid == qs.astype(np.int64) @ docs.astype(np.int64).T).all()))
Output, recorded on an Apple M1 Pro
dot8: -16646144
exact: -16646144
int8 NumPy dot (wraps): 0
scores: [-118079, 112279, 151706, 27796, 26094]
same as int64 NumPy: True
[[ -43886   53038  -12506   17779    1757]
 [  68334 -291416  147558  -15216  -24239]
 [ 210622  178713   46768   67640   57315]]
matrix unit agrees: True

Three things to see in the output:

  • dot8 gives the exact sum, 1024 \cdot 127 \cdot (-128) = -16{,}646{,}144, while NumPy’s own int8 dot product wraps around to 0.
  • scores8 equals NumPy’s int64 product: the Raya loop sums in 64-bit integers.
  • scores8_matrix runs on the matrix unit and agrees too. Its int32 results are exact for vectors shorter than 2^{17} (see why).

Zero-copy buffers

a.ctypes.data_as(...) hands Raya the address of the array’s own memory, so a call costs a few microseconds whatever the array’s size, and Raya can write results straight into an array you allocated (out above). Keep three rules:

  • Pass C-contiguous arrays (np.ascontiguousarray if in doubt) of the dtype the function expects.
  • Keep the array alive (a Python variable) for as long as Raya uses its memory.
  • From a tensor on the CPU, t.numpy() gives an array you can pass the same way.

Going faster: what Raya gives you

  • SIMD. Float32x4, Int32x4 and Float64x2 compile to single vector instructions on arm64; see Typed data and SIMD and SIMD helpers.
  • The CPU’s matrix unit. raya_matmul_f32, raya_matmul_i8 (int8 → int32) and raya_matmul_i16 (int16 → int64) are plain C functions in the Raya runtime: bind them with @Native as above and pass typed data by address. raya_matrix_features() says which types run on the matrix unit of the current CPU. See The CPU matrix unit.
  • All cores. Isolates are real parallel threads (Isolate.run), and fields marked @pragma('vm:shared') are shared memory between them, with mutexes and condition variables for synchronisation; see Isolates and Mutexes and condition variables.
  • Exact maths. Integers of any size, exact rationals and the rest of Riptide’s maths libraries: see the Raya docs.

GPU kernels

GPU kernels written in Raya go through Evelyn, Riptide’s app framework and graphics engine. Evelyn isn’t public yet; GPU custom ops will come with it. Until then, put CPU work in Raya and leave GPU work to Riptorch’s own operations.