Skip to content

Latest commit

 

History

History
1176 lines (1004 loc) · 75.6 KB

gpu.md

File metadata and controls

1176 lines (1004 loc) · 75.6 KB

GPU kernels (gpuLaunch)

A function marked @kernel can run on the GPU, one thread per index. gpuLaunch(kernel, n, ...args) runs kernel(i, ...args) for every i from 0 to n - 1 on the GPU, copying the arrays it is given there and back.

@kernel
function add(i: int, a: number[], b: number[], c: number[]) {
    c[i] = a[i] + b[i];
}

function main() {
    const a: number[] = [1, 2, 3];
    const b: number[] = [10, 20, 30];
    const c: number[] = [0, 0, 0];
    gpuLaunch(add, 3, a, b, c);
    print(c); // [ 11, 22, 33 ]
}

The kernel stays an ordinary function too: add(0, a, b, c) runs it on the CPU.

It works for executables (--emit=exe) and under the JIT (--emit=jit), on NVIDIA, AMD and Intel GPUs. No GPU SDK is needed to compile or to run: the program loads the GPU's driver itself. gpuBatch keeps arrays on the GPU across launches, and a GpuArray lives there for as long as the program keeps it (below).

A kernel

  • It is a function marked @kernel, whose first parameter is the thread's index (int). It returns nothing, or, for gpuReduce, the number to add up.

  • Its other parameters are arrays of numbers (number[], float[], int[], boolean[]), arrays of tuples and object types of numbers (below), typed arrays (below) or plain numbers (number, float, int).

  • An array of a tuple or an object type, [number, int][] or { x: number, y: number }[], holds its elements by value, one after another, and the GPU has them so too: a kernel reads and writes their fields (ps[i].x, ts[i][0]), a nested object's (bodies[i].pos.x), or a whole element (ps[i] = { x: 0, y: 1 }). Their fields are numbers, integers, floats, booleans and such tuples. A launch, gpuReduce, gpuBatch and a GpuArray take them as they take arrays of numbers. A field that is a string, an array or a class's object is a pointer into the CPU's memory, so such an element is an error (a @kernel parameter is a number, or an array of numbers or of tuples and object types of numbers). tslang/test/gpu/gpu_structs.ts steps 10000 particles on the GPU and on the CPU alike, and checks fields of every size with the padding between them.

  • A class's object (s: Settings), or an array of them (ps: Particle[]), is taken too. The kernel's code is as on the CPU: ps[i].x = ..., s.dt, a base class's fields, and calls of the class's methods (ps[i].step(dt)). A launch copies each object to the GPU once, however often the arguments name it (an array that lists one object twice, and another argument naming it again, give the kernel one object, as the CPU has), points the array's elements at the copies, and after the kernel copies the fields back into the same objects: no new objects are made, and the program's other references to them see what the kernel wrote. Inside gpuBatch they stay on the GPU between launches, as arrays do (below). An object that may be null (p: Particle | null, ps: (Particle | null)[]) is taken as well: a null stays null, and the kernel checks it as on the CPU (p ? p.x : 0).

    • Their fields are numbers, integers, floats, booleans, and tuples and object types of them, as above, and other class objects whose fields are such (next: Node, next: Node | null), and arrays of numbers, tuples and object types (verts: number[], points: [number, number][]) or of such class objects (bodies: Body[]). A string is a pointer into the CPU's memory: a class object given to a @kernel has fields of numbers, booleans, tuples and object types of them, arrays of those, or other such objects (or arrays of them).
    • An array a field holds goes to the GPU with its object, its elements in the same copy as the objects, and its elements come back into the same array after the kernel: m.verts[i] = m.verts[i] * m.scale works as on the CPU. An array two objects hold is one copy, as on the CPU, and so is an array that is a field and also an argument of the launch (gpuLaunch(k, n, m, m.verts)). A subclass's own arrays go too (a Bag with items in a Holder[]). A kernel does not change an array's length (push is an error in a kernel, as for any array), and inside gpuBatch the arrays stay on the GPU with their objects: the CPU is not to resize them there (the end of the batch stops the program if it did). tslang/test/gpu/gpu_fields.ts checks these against the same calls on the CPU.
    • An array of class objects a field holds (w.bodies[i].step(w.dt)) is the GPU's pointers to the objects' copies, its objects going with the launch as a field's object does (a subclass's too, with its own methods). Unlike an array of objects given as an argument, a kernel may store into it: w.bodies[0] = w.bodies[1], w.bodies[0] = null (for a (Body | null)[]). After the kernel the array holds the CPU's objects in that order. tslang/test/gpu/gpu_object_fields.ts moves a world's bodies, swaps them in a kernel, and keeps them in gpuBatch.
    • A field that holds another object is followed: the objects the arguments reach through their fields go to the GPU too, each once (a ring of them, or two objects pointing at one, included), and the fields there point at the GPU's copies, so a kernel reads a.next.value as on the CPU. A kernel may change which object a field holds (a.next = b, a.next = null, b an object the launch has): when the objects come back, the field holds the CPU's object (b itself), not the GPU's address. A subclass's object is followed by its own class's fields. Every object a launch reaches is copied in and back, so a long chain costs as many objects.
    • A method that a subclass overrides (shapes[i].area(), and this.area() in a method) is called as on the CPU: each object's own, chosen by its class. On the CPU the call goes through the object's vtable, the CPU's; in the kernel it becomes a call of each method the object's class and its subclasses have there, the one taken picked by comparing the object's vtable with theirs (the runtime gives the GPU their addresses). A subclass that overrides nothing calls its base class's.
    • An array of the base class may hold a subclass's objects, and each is copied whole, as its own class has it: a Square in a Shape[] has its side, which its own area() reads.
    • A function value's code is the CPU's, so a kernel that calls one is an error ('k' calls a function value).
    • The array's elements are the GPU's pointers to its copies, which do not come back: a kernel changes the objects' fields, and a store into the array itself (ps[0] = ps[1]) is an error.
    • instanceof works in a kernel, of these objects and of those the kernel makes (p instanceof Square, a subclass's object is its base class's too), and so does == of strings of literal texts (state == "busy"): the GPU compares the class's name, which it has, as the CPU does.
    • Past the end of an array of them a kernel's read (ps[n].x, ps[n].x = 1 too, which reads ps[n] first) is reported and stops the program as any other (below); until the kernel ends it works on a zeroed object of the GPU's own, not on a null that would fault the GPU before the runtime could say what happened.
    • Outside gpuBatch each launch copies every object in and back (all of an array's, not only those the kernel touched): a step over a million objects costs about 170 ms that way, and about 3 ms inside gpuBatch.
    • tslang/test/gpu/gpu_classes.ts steps 1000 particles through a method, a base class's field and a tuple field, and checks that an object named twice is one object. gpu_virtual.ts calls methods five classes override, or not, from a Shape[] and from one object given as its base class. gpu_links.ts walks chains of objects only their first is given of, changes their links in a kernel, and follows a ring.
  • A typed array (Float32Array, Float64Array, Int8Array to Int32Array, Uint8Array to Uint32Array, BigInt64Array, BigUint64Array) is given where the kernel takes it, a: Float32Array, or takes the array of its elements, a: float[] (a Float64Array for a number[] too). In the kernel it is that array: a[i], a.length. A launch (gpuLaunch, gpuReduce, an @gpu call) copies the typed array's own elements to the GPU and back into it, and a subarray's are only its slice: gpuLaunch(k, 100, big.subarray(100, 200)) sees 100 elements and changes no others. A call of the kernel on the CPU, k(i, a), works on the same elements (and a write past them stops the program, as above, rather than reach the elements around a subarray). Each launch copies it, but inside gpuBatch it stays on the GPU between launches (below), as does a GpuArray. tslang/test/gpu/gpu_typed_arrays.ts and gpu_batch_views.ts run them.

  • A Uint8ClampedArray and a Float16Array are taken too, and keep JavaScript's rules in the kernel:

    • A Uint8ClampedArray (px: Uint8ClampedArray) is a u8[] there whose writes are clamped as JavaScript's are: into 0..255, rounded half to even, NaN 0. That is every write to px[i]: =, += and the rest, ++ and -- (px[i]++ is the element before). Atomics on one is an error, as in JavaScript. A function the kernel hands px to sees a u8[], whose writes wrap.
    • A Float16Array (h: Float16Array) is an f16[] there: a read is the binary16's value, a write rounds to the nearest binary16 (ties to even; too large is Infinity). Arithmetic with an integer stays in f16 (h[i] * 2), with a number is in number. Intel's GPUs need half floats for it (Xe GPUs have them).
    • tslang/test/gpu/gpu_clamped_half.ts runs each kernel on the GPU and on the CPU, whose typed arrays are the default library's, and checks that they agree (ties, the ends, NaN, ++ at 255, overflow to Infinity).
  • It can do what a function on numbers and arrays does: arithmetic, branches, loops, locals, other functions of the program that do the same.

  • Of Math, it can use:

    • Math.sqrt, Math.abs, Math.floor, Math.ceil, Math.trunc, Math.round, Math.sign and Math.fround, each the GPU's own instruction, with JavaScript's results (Math.round rounds halves up, and gives -0 for -0.5);
    • Math.sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, asinh, acosh, atanh, exp, expm1, log, log2, log10, log1p, pow and cbrt, from tslang's own GPU math library (below);
    • Math.min, Math.max and Math.hypot of any number of arguments, or of a spread number[] (Math.max(...a)), compiled as they are (everywhere, not only in kernels: the default library's take an array of their arguments, made on the heap for each call). Their results are JavaScript's: a NaN makes min and max NaN, -0 is below 0, of no arguments they are Infinity, -Infinity and 0, and hypot does not overflow (Math.hypot(1e200, 1e200) is 1.414213562373095e200), rounds once for any number of arguments, and is Infinity if an argument is, NaN or not. min and max of floats stay floats.
  • It can print numbers, integers, floats, booleans and literal text (below).

  • It can make class objects that its thread keeps to itself, new Vec3(x, y, z), there or in the methods and functions it calls (below).

  • It can make arrays of a length known when compiling, of numbers, integers, floats or booleans, which its thread keeps on its stack: [0, 0, 0, 0], new Array<number>(16) (zeros, as on the CPU; booleans false), new Array<int>(4).fill(1), as a scratch buffer, a window to sort per thread, or a small histogram. At most 4096 bytes, as for objects. new Array(n) of a length known only when it runs is an error (a kernel makes an array of a constant length), and so is a typed array (new Float32Array(8): a kernel cannot make a typed array; new Array<float>(8) instead). A function the kernel calls makes them the same way (new Array<number>(4), of an element type written out), from a @kernel, an arrow kernel or gpuMap's function, and the CPU calls it as it is too: in a program that launches kernels, new Array<T>(N) of a constant N is those zeros everywhere.

  • It cannot call what does not run on a GPU: what needs the CPU's heap (a string, an array of a length known only when it runs, push), what can throw (a length checked when it runs, an index of any), or the library's other functions (Date.now). Math.random does run on the GPU (below). The compiler says which call it is, the way from the kernel to it, and the likely reason:

    error: gpuLaunch: a kernel calls 'Date.now' (from 'k'), which does not run on the GPU
    error: gpuLaunch: a kernel calls 'GC_malloc_atomic' (from 'k'), which does not run on the GPU; it makes something
           on the CPU's heap (a string, an array of a length known only when it runs): ...
    error: gpuLaunch: a kernel calls 'strtoll' (from '.any_keys_...'), which does not run on the GPU; the way there:
           k -> (throw RangeError); it can throw a RangeError (an array's length checked when it runs,
           `new Array<number>(n)`), and the GPU throws nothing: make an array of a constant length (...)
    

    A function the kernel calls is usually inlined into it by then, so the way there names the kernel and what the compiler made (a throw), not each of your functions.

  • It can read the program's variables that hold a number, an integer, a float or a boolean (a top-level let or const), itself or in a function it calls. Each launch takes their values as they are when it is made, as it takes its arguments:

    let scale = 2.5;
    
    @kernel
    function k(i: int, a: number[]) {
        a[i] = a[i] * scale;
    }
    
    gpuLaunch(k, n, a);    // scale 2.5
    scale = 3;
    gpuLaunch(k, n, a);    // scale 3, even if the first launch is still running

    The GPU does not share the program's memory, so the values go with the launch, as hidden arguments after the kernel's own, and the functions on the way from the kernel to the reads are inlined into it. So:

    • A kernel cannot write such a variable (the write would not reach the program): it returns the value (gpuReduce, gpuMin, gpuMax) or writes it to an array.
    • Other variables (an array, an object, a string) are not sent: pass them as arguments.
    • A function on the way that calls itself has its copies inlined, as deep as "Functions that call themselves" (below) says.
    error: gpuLaunch: a kernel writes the program's variable 'total', which the GPU does not share: return it, or write it to an array
    error: gpuLaunch: a kernel reads the program's variable 'scale', which the GPU does not share: a number, an integer, a float or a boolean goes to the GPU with each launch, other values have to be passed to the kernel as arguments
    

    tslang/test/gpu/gpu_variables.ts checks each kind, values changed between launches that do not wait, helpers and methods, reduces, grids, blocks, barriers, and the kernel called on the CPU.

  • A write past an array's end (or below 0), which would grow the array on the CPU, is not made on the GPU: the kernel records the first one and goes on, and after it has run the program stops, saying where:

    tslang gpu: the kernel 'k' wrote past the end of an array: element 1000 of 1000 (GPU thread 995)
    

    with exit code 1. That is every way of writing an element: a[i] = v, a[i] += v, an Atomics, a field of a tuple element (ps[i].y = v), a whole element, in the kernel or in a function it calls, on any GPU. The thread is its x among the launch's threads (i for gpuLaunch(k, n, ...)). A launch that does not wait for its kernel (its arrays are all GpuArrays, or inside gpuBatch) reports it where the runtime next waits: gpuRead, gpuWrite, gpuFree, the batch's end, or the program's end. The check is the one the CPU makes before such a write anyway, a comparison per write. In a kernel that waits at gpuBarrier such a write does nothing instead, silently (below). A kernel called on the CPU does not grow the array either: the write stops the program (a kernel called on the CPU wrote past the end of an array). tslang/test/gpu/faults/ has a program for each way.

  • A read past an array's end (or below 0) gives 0 on the GPU, and stops the program the same way:

    tslang gpu: the kernel 'k' read past the end of an array: element 4 of 4 (GPU thread 3)
    

    A neighbour's element at the last index (a[i + 1]), a field of an element, a typed array's view past its own length: each is a read of no element of the array, which on a GPU reads its memory past the array, whatever is there, or stops the driver. a[i] += v past the end is said as its read, the first thing it does. The CPU does not check a read past the end (the same kernel called there reads what is in the memory), and in a kernel that waits at gpuBarrier such a read gives 0, silently, as its threads past n read their tiles (below). The check costs nothing measurable on NVIDIA; on Intel's integrated GPU a matrix * vector kernel, two reads and a multiply each step, takes 1.65 times as long.

  • gpuLaunch, gpuReduce and gpuBatch need the default memory model (-mm=gc).

A kernel written where it is launched: an arrow

gpuLaunch, gpuReduce, gpuMin and gpuMax take an arrow function (or a function expression) as their kernel, and it uses the variables around it as any arrow does:

function saxpy(n: int, scale: number, a: number[], b: number[], c: number[]) {
    gpuLaunch((i: int) => {
        c[i] = a[i] * scale + b[i];
    }, n);
}

const dot = gpuReduce((i: int) => a[i] * b[i], n);
gpuLaunch((x: int, y: int) => { image[y * w + x] = shade(x, y); }, [w, h]);
  • The compiler makes the arrow a @kernel function of its own, whose parameters after the arrow's are the variables it uses of the function it is written in, and passes those to the launch. So a variable goes to the GPU as an argument of the same type would: a number, an int, a float or a boolean as its value at the launch (a loop's variable is the value of that pass), an array copied there and back (kept there inside gpuBatch), a typed array as its elements, a GpuArray as itself, class objects with their fields.
  • The index is an int when it has no type ((i) => ...). An arrow may take arguments of its own after it, given to the launch as for a named kernel (gpuLaunch((i: int, b: number[]) => ..., n, b)); those have a type.
  • The kernel cannot change a variable it uses, as the GPU does not share it: total += a[i] is an error (gpuLaunch's kernel writes 'total', a variable of the function it is written in): return it from a gpuReduce arrow, or write it to an array. Elements of an array it uses are written as usual (c[i] = ...).
  • It calls the program's functions, as any kernel does, but not one held by a variable of the function it is in (const twice = (x) => ...), which the CPU's code is: that is an error. this is an error too: give the kernel what it needs of the object.
  • The program's own variables (the module's) are read as any kernel reads them (above).
  • tslang/test/gpu/gpu_arrows.ts launches arrows that use each kind of variable, in a loop, on a grid, inside gpuBatch, and through gpuReduce, gpuMin and gpuMax.

Objects a kernel makes

A kernel, and what it calls, can make class objects, as vector math does:

class Vec3 {
    constructor(public x: number, public y: number, public z: number) {}
    add(o: Vec3): Vec3 { return new Vec3(this.x + o.x, this.y + o.y, this.z + o.z); }
    dot(o: Vec3): number { return this.x * o.x + this.y * o.y + this.z * o.z; }
}

@kernel
function shade(i: int, out: number[]) {
    let sum = new Vec3(0, 0, 0);
    for (let k = 0; k < 8; k++) {
        sum = sum.add(new Vec3(k, i, 1));
    }
    out[i] = sum.dot(new Vec3(1, 1, 1));
}
  • An object a thread makes lives on the thread's stack, not the heap (a GPU has no garbage collector): the kernel gets the functions it calls that make or take objects inlined, and each new a slot of its own, zeroed as a new object is. The GPU's optimizer then keeps their fields in registers, so a Vec3 costs what three numbers do.
  • Objects can hold each other (new Ray(new Vec3(...), new Vec3(...))), be passed to and returned from the kernel's functions, and have methods a subclass overrides, which are chosen by the object's class as for an object the launch gives the kernel.
  • A loop's variable that keeps an object the loop made for its next pass (sum = sum.add(v)) has a slot of its own that the object is copied into at the end of the pass, so that the next pass's new does not overwrite it. The variable then holds a copy: two variables holding one such object are an error, as are objects made in a loop that hold each other across its passes (a chain, head = new Node(head)).
  • The object lives only while the thread runs, so it may not go where the thread does not keep it: into an array or an object the launch gave the kernel (nodes[i].next = new Node() is an error: copy its fields instead). Objects of more than 4096 bytes are an error too. A function that calls itself and makes objects has its copies inlined (below).
  • tslang/test/gpu/gpu_objects.ts runs rays, accumulators, swaps across a loop's passes, objects of a subclass chosen per thread, and an arrow kernel making them, against the same code on the CPU.

Functions that call themselves

A kernel can call a function that calls itself, or functions that call each other.

One of numbers alone (arrays it is given included) is made a loop over a stack of its own: a call of itself stores what the function keeps across it in a frame on the stack and goes back to the start; a return goes back to the frame before, after its call. Functions that call each other are one such loop (the others inlined into the one the kernel calls). The GPU's own calls are not used: CUDA's stack is 1 KB a thread (about 40 calls deep, then an illegal memory access), and Intel's driver gives wrong values when a function calls itself and its threads go to depths of their own (20 calls deep is enough).

function fib(n: int): int {
    return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
  • The stack is 16 KB a thread, as many frames as fit: a frame is what the function keeps across its call (its arguments, the values it uses after the call) and 4 bytes, so sumTo(n, scale) (n * scale + sumTo(n - 1, scale)) goes 512 calls deep, a function with eight numbers to keep fewer (and one that keeps more than 1 KB, 16 calls). Each function has a stack of its own. A GPU keeps a thread's local memory for each thread it can run at once, so 16 KB is about 2 GB of an RTX 5080's 16 (by that count: a kernel calling four such functions, 2 million threads of it, ran on the RTX 5080 and on Intel's integrated GPU).

  • A thread that goes deeper than its stack has a fault, which stops the program after the kernel:

    tslang gpu: the kernel 'k' called a function that calls itself more than 512 calls deep, as deep as its stack on the GPU goes (GPU thread 2)
    
  • It runs about as fast as the GPU's own calls where those work. 65536 threads (best of 8):

    fib(16..19) sumTo(30..37)
    RTX 5080, the stack (the GPU's calls) 14.1 ms (16.2 ms) 0.25 ms (0.22 ms)
    Radeon RX 7900 XTX, the stack (the GPU's calls) 11.7 ms (15.1 ms) 0.52 ms (0.28 ms)
    Intel integrated GPU, the stack 966 ms 12.3 ms
  • A kernel that waits at gpuBarrier keeps the GPU's own calls (its faults are not recorded), with a warning that names the function, as does a function this does not make a loop (functions that call each other which do not come to one calling only itself in 8 rounds of inlining). TSLANG_GPU_STACK=0 keeps them everywhere, for comparing (when the program is compiled: the JIT's cache of a program does not see it).

  • tslang/test/gpu/gpu_recursion_deep.ts checks a sum 300 calls deep, Fibonacci, two functions that call each other, a function that keeps eight numbers, one that writes an array as it goes, and one with its call in a loop, each thread at a depth of its own, against the CPU; tslang/test/gpu/faults/stack_full.ts goes too deep.

One that makes objects, calls Math.random or reads the program's variables goes through the functions inlined (above), which a call of itself cannot be. So its calls are inlined into the kernel as copies, up to 16 calls of each function deep:

function traceRay(start: Vec3, dir: Vec3, things: Thing[], lights: Light[], depth: int): Vec3 {
    ...
    const reflected = depth >= maxDepth ? grey : Vec3.scale(reflect, traceRay(pos, rd, things, lights, depth + 1));
    return Vec3.plus(natural, reflected);
}
  • What each copy is given is folded as it is inlined. A depth counted in an argument from a constant (0, then depth + 1 up to maxDepth) ends the copies by themselves: the ray tracer above has 6, as deep as maxDepth says, wherever its recursion goes through other functions (traceRay -> shade -> getReflectionColor).

  • A depth the kernel's data decides (deep(i)) is copied 16 calls deep. A thread that goes deeper has a fault, which stops the program after the kernel, as a write past an array's end does:

    tslang gpu: the kernel 'k' called a function that calls itself more than 16 calls deep, as deep as its copies on the GPU go (GPU thread 2)
    
  • A function that calls itself more than once at each depth (tree(n - 1) and tree(n - 2)) doubles its copies at each, and copies of more than 200000 instructions are an error: count the depth from a constant, or write the recursion as a loop.

  • The copies are code the GPU's driver compiles when the program first launches the kernel: the ray tracer's 6 take it 0.8 s on an RTX 5080 (75 ms as a loop) and 16 s on Intel's integrated GPU (2.3 s). They run as fast as the loop does. With let maxDepth, a variable, its depth no longer ends the copies, and its 16 take 2.5 s and 53 s (and tslang 11 s to compile): a depth from a constant keeps a large function's copies few.

  • tslang/test/gpu/gpu_recursion.ts checks objects made as deep as the thread's index says, two functions that call each other, a depth counted from a constant, Math.random and the program's variable through recursion, and numbers alone, against the CPU; tslang/test/gpu/faults/too_deep.ts goes too deep.

Printing from a kernel

print works in a kernel, and in the functions it calls, as on the CPU:

@kernel
function step(i: int, xs: number[], dt: number) {
    if (xs[i] < 0) {
        print("thread", i, "x =", xs[i], "dt", dt);
    }
    xs[i] = xs[i] + dt;
}
  • What it prints: numbers, integers, floats and booleans, and literal text and other constants ([1, 2]). A string that is one of literal texts known when compiling prints too: print(i > 0 ? "yes" : "no"), a variable of a union of literals (let state: "idle" | "busy"); the GPU records which of them it is. A string made in the kernel is the CPU's (print(`thread ${i}`) is an error: print in a kernel prints numbers, booleans and literal text); print the parts instead, print("thread", i). A string variable is one too, whatever it holds.
  • The lines are the CPU's to the digit: the GPU records each print's values, and after the kernel the CPU prints them through the same code a kernel called on the CPU would run (0.1 + 0.2 is 0.30000000000000004, a float 0.30000001192092896, -0, NaN).
  • They come after the kernel, before anything the program prints next, and before a fault the kernel had. Each line is whole, but the threads' lines are in the order the threads reached their prints, which differs from run to run, as threads do: to follow one thread, print from it alone (if (i == 42) print(...)).
  • A launch whose kernel prints waits for it (as a launch of arrays copied back does), so the kernel's prints are its own; a kernel that does not print, in the same program, is launched as before.
  • The record buffer holds 2 MB (a print takes 8 bytes for each value and 8 more): a kernel that prints more has the rest dropped, and says how many (tslang gpu: 47572 prints of the kernel 'flood' did not fit in its print buffer). A million threads each printing is not what it is for.
  • In a kernel that waits at gpuBarrier, the threads past n (which run so that their block reaches the barrier whole) print nothing.
  • In a program with kernels, any function's print of such values is made so, since a kernel may call the function; on the CPU it prints the same. A print of other values (a string, an object) in a function the kernel calls is still the CPU's: a kernel calls '...' (from 'helper'), which does not run on the GPU.
  • tslang/test/gpu/gpu_print.ts prints from a kernel, a helper, a barrier kernel, gpuReduce and a grid.

The GPU's Math library

NVIDIA's and AMD's GPUs have no math library without their SDKs (libdevice, ROCm), so tslang carries its own: Sun's fdlibm (newlib's copy, in tslang/tslang/gpumath), compiled to LLVM IR and linked into a kernel that calls Math.sin and the like. The same code runs on every GPU, nothing needs installing, and only the functions a kernel calls are added to it.

  • Accuracy: against the CPU's results (the C library's, which the kernel's CPU run calls), on an RTX 5080 over 100000 arguments each: within 1 ulp (unit in the last place) for sin, cos, tan, the inverse trigonometric functions, exp, log, log1p and pow, and within 3 ulp for the rest. Infinities, NaNs, zeros and subnormals give what the CPU gives, Math.pow(1, NaN) included: 1, as C's pow gives (JavaScript's is NaN).

  • Floats: a float given to one of them, whose result goes straight back to a float, runs the library's float version, so the kernel needs no 64-bit floats:

    const s: float = Math.sin(v);   // v a float: sin in floats

    A constant a float holds exactly counts as a float (Math.pow(v, 2)).

  • Large arguments of sin, cos and tan are reduced exactly, as on the CPU, at some cost in speed.

  • gpumath/generate.cmake remakes the IR (gpumath.ll, which is checked in) with LLVM's clang after a change to the library.

Random numbers: Math.random

A kernel, or a function it calls, can call Math.random(). Each GPU thread has numbers of its own, and each launch another set:

@kernel
function inside(i: int): int {
    const x = Math.random();
    const y = Math.random();
    return x * x + y * y < 1 ? 1 : 0;
}

const pi = (4 * gpuReduce(inside, 1000000)) / 1000000;
  • How: the run time gives each launch a seed of 64 bits (gpuLaunch, gpuReduce, gpuMin, gpuMax, in gpuBatch and async launches too). Each run of the kernel mixes it with its index (i, or x, y, z on a grid), and each call steps a SplitMix64 generator: 53 random bits, a number in [0, 1), as the CPU's. That is enough for simulation and Monte Carlo work. It is not for cryptography, and neither is the CPU's.

  • Repeatable with gpuSeed(s): without it two runs of a program differ, as on the CPU. After gpuSeed(42) the launches get the same seeds each run, so the kernels give the same numbers: an index's numbers depend only on the seed and the index, not on the kernel's block shape, whether a launch or gpuReduce runs it, nor the GPU (an NVIDIA and an Intel GPU give the same). A seed counts for the launches the thread that set it makes. A sum of them through gpuReduce is the same each run too (below).

    gpuSeed(42);
    gpuLaunch(simulate, n, particles);   // the same each run
  • The kernel called on the CPU uses the CPU's Math.random, which gpuSeed does not change.

  • The functions on the way from the kernel to Math.random are inlined into the kernel's entry; one that calls itself has its copies inlined ("Functions that call themselves").

  • tslang/test/gpu/gpu_random.ts checks a million numbers for range, mean and variance, launches and grid rows apart, a helper function, pi through gpuReduce, and gpuBatch; gpu_seed.ts that gpuSeed repeats them, in launches, reduces, grids and other block shapes.

Launching by calling: @gpu

A function marked @gpu instead of @kernel is a kernel that a call launches: add(n, a, b, c) is gpuLaunch(add, n, a, b, c), and blur([w, h], ...) a launch on a grid.

@gpu
function add(i: int, a: number[], b: number[], c: number[]) {
    c[i] = a[i] + b[i];
}

add(n, a, b, c);   // on the GPU, n threads
  • Inside a kernel, a call of a @gpu function is a plain call: a helper the kernel runs itself.
  • Outside kernels a @gpu function cannot be called on the CPU (every call is a launch); a @kernel one can, add(i, a, b, cpu) running it once for one i, which is how a test compares the GPU with the CPU.
  • gpuLaunch and gpuReduce take a @gpu function as they take a @kernel one.
  • It is a function of the program's own file, by its name (a top-level function).

Grids: images, matrices, volumes

gpuLaunch(kernel, [w, h], ...args) runs kernel(x, y, ...args) for every x from 0 to w - 1 and y from 0 to h - 1; [w, h, d] runs kernel(x, y, z, ...args). The kernel takes its x and y (and z) first, as ints:

@kernel
function invert(x: int, y: int, image: float[], out: float[], w: int) {
    out[y * w + x] = 255 - image[y * w + x];
}

gpuLaunch(invert, [width, height], image, out, width);
  • The extents are written out as an array literal ([w, h]), each any int expression. A grid with an extent of 0 or less runs nothing.
  • It is one launch of w * h (* d) threads, x the fastest: a block's 256 threads are 256 consecutive x (across rows when w is smaller), and gpuThreadIndex(), gpuBlockIndex() are those of that flat launch. w * h * d is at most 2^31 - 1. A kernel with a block of 2 (3) dimensions has tiles of the grid instead (below).
  • Arrays are passed as they are (an image is a flat array, row by row): the kernel works out where (x, y) is.
  • A kernel on a grid that calls gpuBarrier() runs past the grid's end too, as a flat one does, and its array accesses are guarded as a flat one's are (below): the threads past the grid's end write nothing.
  • gpuReduce takes a count, not a grid.

Threads that work together: blocks, shared memory, barriers

The GPU runs a kernel's threads in blocks, of 256 unless the kernel says (below). The threads of a block can share a small, fast array and wait for each other, which a kernel uses to work on a tile of its data together: a block's sum, a tile of a matrix product, a stencil.

  • gpuThreadIndex(): the thread's place in its block, 0 to 255.
  • gpuBlockIndex(): the block's place among the blocks; the thread's i is gpuBlockIndex() * 256 + gpuThreadIndex().
  • gpuBlockSize(): 256.
  • Each takes a dimension of the block, a constant: gpuThreadIndex(1) is the thread's y in a block of 2 or 3 dimensions (below), (2) its z; (0) is the same as none, x.
  • gpuShared<T>(n): an array of n numbers (number, float, int, ...) that the threads of a block share, one for each block. n is a constant, of 48 KB at most. It starts with whatever was there: write before reading. Each gpuShared in the source is an array of its own.
  • gpuBarrier(): each thread of the block waits there until all of them have reached it; what they wrote before it (to the shared array or to the GPU's arrays) is seen by all of them after it, as CUDA's __syncthreads.
// each block adds up its 256 values: sums[block]
@kernel
function blockSums(i: int, a: number[], sums: number[]) {
    const tile = gpuShared<number>(256);
    const t = gpuThreadIndex();
    tile[t] = a[i];             // past a's end (the last block's threads past n): 0
    gpuBarrier();
    for (let s = 128; s > 0; s = s >> 1) {
        if (t < s) tile[t] = tile[t] + tile[t + s];
        gpuBarrier();
    }
    if (t == 0) sums[gpuBlockIndex()] = tile[0];
}
  • A barrier has to be reached by every thread of the block, or the block waits for ever. So a kernel that calls gpuBarrier() (or a function that does) runs on every thread of every block, the last block's threads past n too, and its array accesses (its own and those of the functions it calls) are guarded instead, so that it need not check i < n:

    • reading an element past an array's end (or below 0) gives 0;
    • writing one past the end (an Atomics too) does nothing;
    • a thread past n writes nothing to the GPU's arrays (the kernel's arguments, GpuArrays), so an array longer than n keeps its elements past n. Its writes to the block's gpuShared arrays are made: its part of a tile is the block's, as tile[t] = a[i] above. And it reads as any thread does: an element that is there (a[i] of an a longer than n, a neighbour's) is read, not 0.

    Keep a barrier out of an if that only some threads take. The guard is a comparison per array access, in these kernels only.

  • gpuReduce does not take such a kernel (its threads do not all reach the barrier); gpuLaunch it.

  • Such a kernel is not for the CPU: there is no block there. A call of it (or of a function that uses gpuBarrier, gpuShared, gpuThreadIndex or gpuBlockIndex) in the program's CPU code is an error: 'main' calls 'blockSums' on the CPU, which uses gpuShared(): that is a GPU block's, and the CPU has no block. A call through a function value is not seen until it runs, and then stops the program (gpuShared() is for a kernel gpuLaunch runs on the GPU, and was called on the CPU). gpuBlockSize() is the kernel's block size on the CPU too (256 unless it says).

  • tslang/test/gpu/gpu_barrier_guard.ts launches such kernels on 1000 threads, with arrays longer than that filled with -7 past it: the -7s stay, the sums and the neighbours' reads are right.

  • On the RTX 5080, tslang/test/gpu/gpu_shared.ts runs a block sum and a 16 x 16 tiled matrix product many times; without the barrier between the halving steps, nearly every block's sum comes out wrong.

A kernel's own block

@kernel({ block: 128 }) runs the kernel in blocks of 128 threads; @kernel({ block: [16, 16] }) in blocks of 16 x 16, which tile a grid of 2 dimensions (and [x, y, z] one of 3). A tiled matrix product, each block working out a 16 x 16 tile of c from tiles of a and b in its shared memory:

@kernel({ block: [16, 16] })
function matmul(col: int, row: int, a: number[], b: number[], c: number[], m: int, k: int, p: int) {
    const tileA = gpuShared<number>(256);
    const tileB = gpuShared<number>(256);
    const tx = gpuThreadIndex(0);
    const ty = gpuThreadIndex(1);
    let sum: number = 0;
    for (let base = 0; base < k; base += 16) {
        tileA[ty * 16 + tx] = row < m && base + tx < k ? a[row * k + base + tx] : 0;
        tileB[ty * 16 + tx] = base + ty < k && col < p ? b[(base + ty) * p + col] : 0;
        gpuBarrier();
        for (let j = 0; j < 16; j++) sum += tileA[ty * 16 + j] * tileB[j * 16 + tx];
        gpuBarrier();
    }
    c[row * p + col] = sum;    // the threads past the grid's edge write nothing (above)
}

gpuLaunch(matmul, [p, m], a, b, c, m, k, p);
  • The sizes are constants (numbers written out), each at least 1, at most 1024 threads in all and 64 in z (every GPU here has those). @gpu takes the same.
  • A block of one dimension is for any launch: n threads (gpuLaunch(k, n, ...), an @gpu call) or a grid, flat as blocks of 256 are. A block of 2 dimensions tiles a grid of 2, gpuLaunch(k, [w, h], ...): its x and y are gpuBlockIndex(0) * 16 + gpuThreadIndex(0) and the same in 1, and the launch has as many blocks as cover w and h. Launching it any other way is an error ('matmul' has a block of 2 dimensions ([16,16]), which tiles a grid of 2), as is a block that is not one.
  • gpuBlockSize(d) is the block's size in d: a constant, or, in a function kernels of different blocks share, what the GPU says.
  • A kernel on a tiled grid runs only for the (x, y) inside the grid, unless it waits at gpuBarrier: then its threads past the grid's edge run too, and write nothing to the GPU's arrays (above), as c[row * p + col]. Their reads, as a[row * k + base + tx] past the edge, are of elements that are there, so the kernel checks row < m itself where a value past the edge would be wrong.
  • gpuReduce runs its kernel in blocks of its own: one with a { block } is an error.
  • tslang/test/gpu/gpu_blocks.ts checks a block sum in blocks of 128, a 70 x 90 tiled matrix product (not a multiple of 16), a 4 x 4 x 4 block, and blocks of 64 and 512 sharing a function, against the CPU.

A thread's own array: gpuLocal

gpuLocal<T>(n) is an array of n numbers of the thread's own, on its stack: no other thread sees it, and it costs no allocation. Its elements start at 0 each time the call is reached, and it lasts as long as that call of its function. n is a constant, of 16 KB at most (a GPU thread's stack is small: more spills to slow memory or runs out). It works on the CPU as well, so a kernel that uses it can be called there too, and is not limited to a block.

@kernel
function median(i: int, values: number[], out: number[]) {
    const own = gpuLocal<number>(8);
    for (let j = 0; j < 8; j++) {
        // insertion sort of the thread's 8 numbers into own
    }
    out[i] = (own[3] + own[4]) / 2;
}

tslang/test/gpu/gpu_small.ts checks it against the same calls on the CPU.

Threads that run together: warps

The GPU runs a block's threads in warps, groups whose lanes run each step together and can read each other's values directly, without shared memory or a barrier: a warp's sum, a vote, a prefix sum.

  • gpuWarpSize(): the warp's lanes. 32 on NVIDIA's GPUs and on AMD's from gfx10 on (RDNA; 64 on the ones before, as gfx906); 16 on Intel's (each kernel's subgroup is pinned at 16, which every Intel GPU has, so that all of a program's kernels have the same). Use it rather than a number.
  • gpuLaneIndex(): the thread's lane, 0 to gpuWarpSize() - 1. In a block of one dimension the warps are the block's threads in order: lane gpuThreadIndex() % gpuWarpSize().
  • gpuShuffle(v, lane): v of the warp's lane lane (modulo the warp's size). gpuShuffleDown(v, d): of the lane d above, gpuShuffleUp(v, d) of the lane d below, gpuShuffleXor(v, m) of lane ^ m; a thread whose lane would be outside the warp gets its own v. v is a number of 4 or 8 bytes (number, float, int, ...), as CUDA's __shfl_sync, __shfl_down_sync, __shfl_up_sync, __shfl_xor_sync.
  • gpuBallot(p): an int with a bit for each lane p is true for (lane 0 the lowest). gpuAll(p), gpuAny(p): whether p is true for all, or any, of the warp's lanes.
// each warp's sum, which its lane 0 writes
@kernel
function warpSums(i: int, n: int, a: number[], sums: number[]) {
    let v = i < n ? a[i] : 0;
    for (let d = gpuWarpSize() >> 1; d > 0; d = d >> 1) v += gpuShuffleDown(v, d);
    if (gpuLaneIndex() == 0) sums[i] = v;
}
  • The lanes have to run together, so a kernel that uses these runs as one that waits at gpuBarrier does (above): on every thread of its blocks, past n too, with its array accesses guarded. A thread past n is in no vote (it is no bit of a ballot, no gpuAny's true, no gpuAll's false), but what it gives a shuffle is its own v: so warpSums gives 0 past n itself (i < n ? a[i] : 0).
  • A shuffle reads the lanes that run with it: in an if only some lanes take, a lane that does not is not there to read (on NVIDIA its value is undefined). gpuShuffleXor(v, 2) among the even lanes is fine; reading an odd lane from there is not.
  • Its block is of whole warps, a multiple of 32 threads (@kernel({ block: 100 }) is an error); gpuReduce does not take it, and a call of it on the CPU is an error, as for a barrier kernel. On AMD's GPUs before gfx10 gpuBallot is an error: their 64 lanes do not fit in an int.
  • tslang/test/gpu/gpu_warp.ts checks each of them on 1000 threads (the last warp partly past n), with arrays longer than that; gpu_scan.ts is a prefix sum of 100000 values: each warp's of gpuShuffleUp, each block's of its warps' totals in shared memory, then the blocks' (on the RTX 5080: warps of 32).

Combining what the threads find: Atomics

Threads that write the same element would overwrite each other. Atomics.add(a, i, v) and the rest, given a plain array, change the element in one step that no other thread can come between:

@kernel
function stats(i: int, values: number[], sums: number[], histogram: int[]) {
    const v = values[i];
    Atomics.add(sums, 0, v);      // the sum
    Atomics.max(sums, 1, v);      // the largest
    Atomics.add(histogram, Math.floor(v / 10), 1);
}
Arrays Returns
Atomics.add(a, i, v), sub any the value the element had before
Atomics.max(a, i, v), min any the value before
Atomics.and(a, i, v), or, xor integers the value before
Atomics.exchange(a, i, v) any the value before
Atomics.compareExchange(a, i, expected, v) integers the value before; v is written only if that was expected
Atomics.load(a, i), Atomics.store(a, i, v) any the element; the value stored

"Any" is number[], float[] and the integer arrays (int[], u32[], s64[], ...). An integer array's max and min follow its signedness.

  • These are JavaScript's Atomics, but on plain arrays: JavaScript's take only integer typed arrays (Int32Array), and have no max or min. They are the compiler's own, there without the default library, and work on the CPU too, so the kernel's CPU run (stats(i, ...)) gives the same results. Given a typed array, Atomics is still the default library's.
  • The index is not checked: it has to be one of the array's.
  • Float sums are added in whatever order the threads get there, so with fractions the last bits can differ between runs, and from the CPU's sum.
  • On the GPU they are relaxed and GPU-wide, as CUDA's atomicAdd is: each thread sees each atomic change whole, but in no particular order with its other writes. On the CPU they are JavaScript's (sequentially consistent), which on a GPU would put a fence across the whole system around each one.
  • An array changed by Atomics is copied back after the launch, as any array the kernel writes.
  • Intel: a float add, sub, max or min is a compare-and-swap loop, which needs no SPIR-V extension. A 64-bit atomic (on number[] or s64[]) needs the GPU to have 64-bit atomics, which OpenCL leaves optional; 32-bit ones (float[], int[]) run everywhere. One on 16-bit integers (u16[]) is not compiled for Intel at all: with --gpu-arch=intel it is an error, and by default Intel is left out with a warning.
  • Every thread adding into one element waits its turn there. On the RTX 5080, a million threads adding into one sum take about 1.2 ms (number or float alike), where a kernel copying the same million numbers takes 0.03 ms. Many elements (a histogram's bins) contend less; for one sum, gpuReduce is the fast way.

Adding up: gpuReduce, gpuMin, gpuMax

gpuReduce(kernel, n, ...args) returns the sum of kernel(i, ...args) for every i from 0 to n - 1, added up on the GPU. The kernel returns the number to add: a number, a float or a 32- or 64-bit integer, which is also the sum's type.

@kernel
function product(i: int, a: number[], b: number[]): number {
    return a[i] * b[i];
}

const dot = gpuReduce(product, n, a, b);
  • It runs at most 65536 threads: each adds up every 65536th index on its own; each block of 256 threads then adds up its threads' sums in shared memory, in pairs (thread 0's and 128's, then 0's and 64's, ...), into one of 256 sums, which the CPU adds up in order.
  • The same every run: no atomics, and the same pairs each time, so the same n and arguments give the same sum, to the last bit, on every run (and with gpuSeed, a sum of Math.randoms too). With fractions it can still differ in its last bits from a loop on the CPU, which adds in another order. An integer sum wraps as its type does (int at 2^31).
  • It runs on every GPU, a sum of numbers or 64-bit integers on Intel too (it needs no 64-bit atomics).
  • The kernel can write arrays too, as a gpuLaunch one does; the arrays come back the same way. A kernel that returns a value can be given to gpuLaunch as well, which drops what it returns.
  • Inside gpuBatch, the arrays stay on the GPU as for gpuLaunch, and each gpuReduce returns its sum at once: a loop can stop when a sum says it is done.

gpuMin(kernel, n, ...args) and gpuMax(kernel, n, ...args) are the least and the greatest of what the kernel returns, as Math.min and Math.max take them: a NaN gives NaN, -0 is less than 0, and of no indices (n of 0) they are Infinity and -Infinity (an integer's greatest and least value for an int kernel).

@kernel
function distance(i: int, xs: number[], ys: number[]): number {
    return Math.sqrt(xs[i] * xs[i] + ys[i] * ys[i]);
}

const nearest = gpuMin(distance, n, xs, ys);
  • They run as gpuReduce does (the same threads, the same pairs in shared memory, the same 256 slots).
  • The kernel returns a number, a float or a 32- or 64-bit integer.
  • tslang/test/gpu/gpu_extremes.ts checks a million numbers, floats and ints against the CPU, a NaN, -0, none, and gpuBatch.

Prefix sums and sorting: gpuScan, gpuSort

gpuScan(a) makes each element of an array the sum of those up to it, itself included (an inclusive prefix sum), and gpuSort(a) sorts it ascending; both on the GPU, in place, with no kernel to write.

const counts: int[] = ...;
gpuScan(counts);          // counts[i] is now counts[0] + ... + counts[i]

const values: number[] = ...;
gpuSort(values);          // ascending
  • The array is a T[] of number, float or a 32-bit integer (int, s32, u32). Anything else, or a GpuArray, is an error: gpuScan(a) takes an array of numbers, floats or 32-bit integers.
  • gpuScan adds up each block of 256 elements in shared memory, scans the blocks' totals the same way (on the GPU too, for any length), and adds each block's preceding total to its elements. A sum of numbers or floats is added in a different order from a loop's, so it can differ from it in the last bits (it is the same each run, as gpuReduce's is); integers are exact (and wrap as int does).
  • gpuSort is a bitonic sort of a copy padded to a power of two, copied back. As Array.prototype.sort with (x, y) => x - y would, but total: NaNs go last and -0 before 0. It is not stable, which for numbers cannot be seen.
  • Both work inside gpuBatch: the array stays on the GPU, as for gpuLaunch.
  • tslang/test/gpu/gpu_scan_sort.ts checks scans and sorts of a million numbers, floats and ints against the CPU, lengths of 0, 1, 256 and 257, NaN, -0 and infinities, and a sort inside gpuBatch.

Callbacks: gpuMap, gpuFilter, gpuFold, sorting by a compare

These take a function: an arrow written in the call (it can use the program's variables, as an arrow kernel does) or the name of a function of the program's. The GPU calls it as its own function: it is compiled into the kernel, not called through a pointer.

const scaled = gpuMap(xs, (x) => x * scale);                 // a new array: f(x), or f(x, i) with the index
const big = gpuFilter(xs, (x) => x > limit);                 // the elements kept, in their order
const box = gpuFold((i: int): Box => ({ x0: xs[i], y0: ys[i], x1: xs[i], y1: ys[i] }), n,
                    (p: Box, q: Box): Box => ({ x0: Math.min(p.x0, q.x0), ... }));
gpuSort(xs, (x, y) => y - x);                                // descending
gpuSort(keys, values);                                       // values move with their keys
gpuSort(bodies, (p, q) => p.x - q.x);                        // objects by a field
  • gpuMap(a, f) makes a new array of what f returns: anything a kernel can write to an array (a number, a boolean, an object of numbers, ...).
  • gpuFilter(a, p) keeps the elements p returns true for, in their order. It marks those to keep, scans the marks (as gpuScan) for their places and puts each at its place. p returns a boolean, or it is an error.
  • A chain written as one expression is fused: gpuMap(gpuMap(a, f), g) is one kernel that gives g(f(x)), and the array between is never made or copied. A chain with a gpuFilter is the filter's two kernels, the maps before it in the first and those after it in the second, which gets each kept element's place in the new array as its index (gpuMap(gpuFilter(a, p), (x, i) => ...)). Each function runs once for each element: a map before the filter keeps its values in an array for the second kernel, so gpuFilter(gpuMap(a, f), p) saves a launch and a copy to the GPU, not that array. On 4M numbers, gpuMap(gpuMap(a, f), g) takes 8.5 ms against 17 ms as two calls on an RTX 5080 (11 ms against 22 ms on Intel's integrated GPU), and gpuFilter(gpuMap(a, f), p) 22 ms against 24 ms (37 ms against 41 ms). A chain has one filter at most (after one, an index is a place in the filtered array, which a second filter's marks do not know): gpuFilter(gpuFilter(a, p), q) is two calls. Arrays given names between the calls (const b = gpuMap(a, f)) are the program's, and made.
  • gpuFold(kernel, n, combine, ...args) folds what kernel(i, ...args) returns for each i from 0 to n - 1 with combine(a, b), a value of any type gpuMap returns (a box, a pair, a sum). It keeps the order of the indices: at most 65536 threads each fold a run of indices in order, then pairs side by side are combined, the earlier one first. So combine need only be associative, not commutative: affine maps compose, and the result is the same each run. The kernel is an arrow of the index ((i: int) => ..., using the variables it needs) or a @kernel function given its arguments. Of no indices (n of 0) there is no value: a TypeError.
  • gpuSort(a, compare) sorts as Array.prototype.sort(compare) does (negative for x first): descending, or objects by a field. gpuSort(keys, values) sorts the keys (numbers, floats or integers, in gpuSort(a)'s order: NaNs last, -0 before 0) and puts each value where its key goes; gpuSort(keys, values, compare) sorts keys of any type by compare. values has as many elements as keys, or it is a RangeError. These sorts are stable: equal keys keep their order. The GPU sorts the order of the indices (a bitonic sort, ties by the index); the CPU then puts the elements in that order.
  • All of these are supported under the default memory model (-mm=gc).

A @kernel function can take a function as a parameter. Give gpuLaunch, gpuReduce, gpuMin or gpuMax an arrow or a function's name for it, and the call gets a kernel of its own with that function compiled in:

@kernel
function apply(i: int, a: number[], out: number[], f: (x: number) => number) {
    out[i] = f(a[i]);
}

gpuLaunch(apply, n, xs, out, (x) => x + k);
gpuLaunch(apply, n, xs, out, square);

tslang/test/gpu/gpu_fused.ts checks fused chains against the same calls through named arrays and the CPU. tslang/test/gpu/gpu_callbacks.ts checks all of these against the CPU on a million elements: maps with captured variables, the index, a function, booleans and objects; filters; folds of sums, bounding boxes, affine maps in order and none; sorts descending, of keys and values (stable, with NaN and -0), of objects by a field; and kernels given an arrow and a function.

Which GPU

The program carries its kernels compiled for several GPUs, and when it first launches one it uses the first GPU whose driver loads them: CUDA (NVIDIA), then HIP (AMD), then Level Zero (Intel).

--gpu-arch (or "gpu-arch" in tsconfig.json's "tslang" section) says what to compile for, comma separated:

--gpu-arch Compiled to Run through
NVIDIA sm_75, sm_86, ... PTX, which the driver compiles for the GPU present (sm_75 runs on Turing and newer) the CUDA driver (nvcuda.dll, libcuda.so.1)
AMD gfx1100, ... or a family: gfx10-3-generic (RDNA 2), gfx11-generic (RDNA 3), gfx12-generic (RDNA 4) a code object for that GPU or family HIP (amdhip64_*.dll, libamdhip64.so)
Intel intel SPIR-V, which the driver compiles for the GPU present Level Zero (ze_loader.dll, libze_loader.so.1)

Without --gpu-arch it is every one this tslang can compile for: sm_75, the three AMD families and intel. A GPU named in --gpu-arch that cannot be compiled for is an error; one of the defaults is left out with a warning. TSLANG_GPU_ARCH is read when there is no --gpu-arch.

AMD's code object is linked by lld. tslang uses TSLANG_LLD, or finds ld.lld next to itself, in the HIP SDK (HIP_PATH) or on PATH; failing those, the wasm-ld next to it, which tslang's package has (it is the same lld).

When the program runs:

  • TSLANG_GPU=hip,cuda tries those drivers, in that order, instead (cuda, hip, level-zero).

  • Each driver uses its first GPU. TSLANG_GPU=cuda:1 uses the driver's GPU 1 (counted from 0) instead; with a list (cuda:1,level-zero), a driver that has no such GPU is passed over for the next one.

  • TSLANG_GPU_LIST=1 prints the GPUs each driver it tries finds, with those numbers: tslang gpu: cuda:0 NVIDIA GeForce RTX 5080.

  • TSLANG_GPU_VERBOSE=1 prints the one chosen: tslang gpu: running the kernels through cuda (sm_75).

  • With no GPU to run them, it says why for each one and stops:

    tslang gpu: no GPU here runs the program's kernels, built for: sm_75 gfx10-3-generic gfx11-generic gfx12-generic intel
      cuda: the NVIDIA driver (nvcuda) is not installed
      hip: the AMD HIP runtime (amdhip64) is not installed
      level zero: no Intel GPU (Level Zero finds no GPU device)
    

TSLANG_GPU_DUMP=<path> writes each GPU's code, as compiled, to <path>.<arch>.

What a launch costs

Each launch copies its arrays to the GPU and, of those the kernel may write, back: the compiler sees which arrays a kernel only reads (directly or through the functions it calls), and those are not copied back.

An array the kernel only writes is not copied in either, when the compiler can see that it writes every element: the kernel writes the element of its own index (out[i] = ...) on every way through it (each branch of an if, say) and reads none of the array's elements, and the launch has a thread for each element (n at least the array's length). The kernels of gpuMap and of a ray tracer's pixels are such, and gpuReduce's too (its threads take every index below its count). On a grid of two dimensions the index is the grid's own, y * w + x (out[y * w + x] = ..., w one of the kernel's int parameters): when the launch passes the grid's width as w and the grid has at least as many cells as the array has elements, it is not copied in either. An array written only on some ways (if (x > 0) out[i] = x;), at another index (out[i + 1], out[x * w + y]), or read too (out[i] += x), or a launch of fewer threads than it has elements (a grid narrower than its w), is copied in, so the elements the kernel leaves keep their values. Inside gpuBatch the same holds for its first launch, which copies it in, unless the launch is given the array (or another view of its storage) twice: the batch keeps one copy of it, which the kernel would read too.

The copies themselves cost less than the bytes alone suggest:

  • The GPU's memory is kept for the next launch. Allocating GPU memory, writing it for the first time and freeing it cost more than the copy into it (on an RTX 5080, 1.2 ms for 16 MB where the copy alone is 0.6). So a launch's memory is not freed when it is done, but kept, up to 512 MB, for the next launch that needs as much. A GpuArray's memory is its own and not kept this way, and an allocation the GPU has no room for gives the kept memory back first. TSLANG_GPU_CACHE=0 frees it at once, as before.
  • Large copies go through page-locked memory on NVIDIA. A copy between the GPU and an array of 4 MB or more goes in pieces through two page-locked buffers, the CPU filling or emptying one while the GPU copies the other. On the RTX 5080, a 16 MB copy back takes 1.1 ms instead of 1.5, and a 128 MB one runs at 17 GB/s instead of 13 in either direction. The arrays themselves stay where the program has them: page-locking their own memory would be twice as fast again, but locking it for each launch costs more than the copy, and the collector owns it. TSLANG_GPU_STAGE=0 turns this off. AMD's HIP copies faster on its own (on an RX 7900 XTX, a copy back through page-locked buffers took 37 ms where HIP's own took 28), and Intel's integrated GPUs share the CPU's memory: both copy as before.

TSLANG_GPU_PROFILE=1 prints where each launch's time goes. Adding two arrays of a million numbers on an RTX 5080:

tslang gpu: __gpu_add n=1000000: start 0.007 ms, in 1.542 ms (16.0 MB), kernel 0.242 ms, out 1.097 ms (8.0 MB)

At the program's end it adds them up per kernel, those that took the most time first, and the copies outside launches (the end of a gpuBatch, gpuArray, gpuRead, gpuWrite); TSLANG_GPU_PROFILE=summary, or TSLANG_GPU_VERBOSE=2 (which also says which GPU runs the kernels), prints only that. rtbench_gpu.ts (below) on an RTX 5080:

tslang gpu: profile, in ms (MB copied)
  kernel                           launches      start                   in       kernel                  out
  gpu_arrow_10215_10312                  10      0.056          0.779 (0.0)       73.696       12.235 (178.3)
  gpu_arrow_9977_10066                    2    216.423          1.820 (0.0)       17.224         4.058 (35.7)
  total                                        216.480          2.599 (0.0)       90.921       16.293 (213.9)

start is finding the GPU and the kernel (the first launch also starts the driver and has it compile the kernels: 100 to 250 ms there), in and out the copies and kernel the time the GPU ran it (with profiling on, each launch is waited for, so a launch that would not wait is timed too). An arrow kernel is named for where it is in the source. As the numbers show, a small kernel costs far less than moving its data: the GPU pays off for work that does much more per element than adding two numbers, or for data that stays on it between launches, which is what gpuBatch is for.

A ray tracer on the GPU

tslang/benchmarks/raytrace/rtbench_gpu.ts is the ray tracer of the benchmarks (rtbench.ts) with a thread per pixel: the things and their surfaces are classes whose methods the subclasses override (Sphere and Plane, Shiny and Checkerboard), each pixel's vectors and colors are Vec3 objects the kernel makes, and the kernel is an arrow that uses the program's scene. The reflections are rtbench.ts's recursion (traceRay, shade, getReflectionColor), inlined as deep as maxDepth ("Functions that call themselves"). The same function renders a pixel on the CPU, and both give rtbench.ts's checksum to the pixel (38837369 at 512x512). It writes the GPU's 512x512 picture to rtbench_gpu.ppm (a binary PPM, which most image viewers open) in the folder it runs in.

512x512 (2048x2048) time
tslang, the same code on the CPU (gc) 256 ms
tslang rtbench_static.ts / Rust static_dispatch.rs, whole process 41 ms / 41 ms
RTX 5080 1.4 ms (16 ms)
Intel integrated GPU ("Intel(R) Graphics") 74 ms (1040 ms)

Integrated Intel GPUs run 64-bit floating point slowly or not in hardware at all, and numbers are 64-bit: a kernel of floats is the way to use one for this kind of work.

Keeping arrays on the GPU: gpuBatch

gpuBatch(fn) runs fn, and the arrays its launches hand the GPU stay there until it returns: each is copied in at its first launch, the next launches given it use the GPU's copy, and when gpuBatch returns, the arrays a kernel may have written are copied back.

gpuBatch(() => {
    for (let step = 0; step < 1000; step++) {
        gpuLaunch(move, n, pos, vel);
    }
});
// pos is back on the CPU here

On the RTX 5080, a step of move over a million numbers costs about 0.015 ms inside gpuBatch and about 4 ms without it.

  • Inside it, leave those arrays to the GPU: the CPU sees them as they were before the batch, and what it writes to them may be overwritten when the batch ends. An array the CPU resizes inside the batch (push) stops the program when it is next used:

    tslang gpu: an array the GPU holds in gpuBatch was resized by the CPU (length 3, now 4): inside gpuBatch, leave the arrays given to gpuLaunch to the GPU
    
  • An array a launch gives the GPU stays alive until the batch ends, even one the program has stopped using (an array made for one step of a loop): the batch's list of them is the collector's to see.

  • A typed array stays on the GPU in the batch too, by its elements: x, or big.subarray(100, 200) given to each launch, is the same array on the GPU every time (a new subarray of the same elements included). Two subarrays of one buffer whose elements do not overlap are two arrays there. One whose elements overlap another's that the GPU holds (big.subarray(0, 100), then big.subarray(50, 150)) is not kept beside it, as the two copies would part: the first comes back to the CPU (the GPU finishes with it first), and the second is copied in from there, so it sees what the kernels wrote to the first. Launches that go back and forth between such subarrays copy each time.

  • An exception out of fn ends the batch as well: the arrays come back before it goes on.

  • A gpuBatch inside another one is part of it: the arrays come back when the outermost one ends.

  • gpuFilter, gpuFold and gpuSort with a compare (or values) read arrays on the CPU after their own launches (how many the filter kept, the folded value, the sorted order): inside a batch those arrays come back from the GPU first, the array sorted included (the next launch copies it in again). gpuMap, gpuScan and gpuSort of numbers stay on the GPU. tslang/test/gpu/gpu_batch_callbacks.ts runs each inside a batch.

  • Class objects stay on the GPU in the batch too: each is copied in at the first launch that names it (in an array of them, or alone), the next launches use that copy (another array that lists it included), and when the batch ends the fields come back into each object. As with arrays, leave their fields to the GPU inside the batch. An array of them may change (bodies[0] = other, push): it is only the GPU's list of pointers to the copies, which a launch makes again when the array is not as it was (an array it holds unchanged costs a comparison of its pointers, not a pass over the objects). The objects their fields reach are kept too; a link the CPU adds inside the batch to an object the GPU does not hold is not followed, so leave the links to the GPU as well. Each object goes to the GPU as one class: given to a kernel of another GPU in the same batch, or as a bigger class than at first, it stops the program. tslang/test/gpu/gpu_batch_objects.ts steps 1000 bodies of two classes, half of them first, and changes the array between launches.

  • With TSLANG_GPU_PROFILE=1, the end of a batch prints what it copied back.

  • A launch's array that is new to the batch is copied in while the kernel launched before it still runs (on NVIDIA, for arrays of 4 MB or more): 8 launches of a 4 ms kernel, each on 16 MB arrays of its own, take 43 ms on the RTX 5080 instead of 54.

Launches in a row

Launches with nothing between them that reads or writes the program's memory are a gpuBatch without the asking: their arrays stay on the GPU from the first to the last, each copied in once and back once.

for (let step = 0; step < 100; step++) {
    gpuLaunch(diffuse, a.length, a, b);
    const t = a;
    a = b;
    b = t;
}
print(a[5]);   // the arrays came back before this

On the RTX 5080, with a million numbers, the loop copies 8 MB in and 16 MB back in all, not 100 times as much. The compiler sees which launches are in a row: a loop whose body and condition hold only launches and the work of local variables (counting, swapping arrays between variables, an array's length), or launches one after another. What ends a row before it:

  • reading or writing an element of an array (a[0], if (a[0] > eps), while (err[0] > 0.01)),
  • calling a function, printing, or making an object or array,
  • anything that could throw.

The CPU then sees the arrays as the launches left them, as it does without the row. Unlike gpuBatch, each launch in a row still waits for its kernel, so a kernel's fault is reported by its name and stops the program before the next launch. TSLANG_GPU_ROWS=0 copies at every launch, as before. With TSLANG_GPU_PROFILE=1, the end of a row prints what it copied back, as launches in a row end.

Arrays that live on the GPU: GpuArray

gpuBatch keeps arrays on the GPU for one function. A GpuArray<T> stays there for as long as the program keeps it: made once, it is given to any number of launches anywhere in the program, and none of them copies it.

const pos = gpuArray(start);          // GpuArray<number>: start copied to the GPU, once
const vel = gpuArray<number>(n);      // n zeros, made on the GPU
for (let step = 0; step < 1000; step++) {
    gpuLaunch(move, n, pos, vel);     // the kernel takes number[]s: no copy in or out
}
gpuRead(pos, start);                  // the GPU's elements, copied into start
gpuFree(pos);
gpuFree(vel);
  • gpuArray(a) copies an array of numbers (number, float, int, ...) to the GPU; gpuArray<T>(n) makes n zeros there (numbers when no T is given).
  • gpuLaunch, a grid, gpuReduce and an @gpu call take a GpuArray<T> where the kernel has a T[]; a launch can mix them with ordinary arrays, which are copied as before (inside gpuBatch too).
  • gpuRead(d, a) copies the GPU's elements into a, gpuWrite(d, a) copies a's to the GPU; a is a T[] of the same length. gpuRead(d) copies them into a new T[], which it gives back. d.length is the number of elements.
  • gpuFree(d) gives the GPU's memory back at once. A GpuArray the program no longer holds is collected as well: the collector finds it gone, and the next gpuArray gives its GPU memory back. The collector runs then too when the GpuArrays made since it last ran hold as much GPU memory as the ones before them (256 MB at least), and when the GPU has no room for a new one, so a loop that makes one each time round without gpuFree does not run out (tslang/test/gpu/gpu_array_collect.ts: 64 of 256 MB, on a 16 GB GPU). gpuFree is still the way to give memory back at a moment of the program's choosing. Using one after gpuFree stops the program, saying so.
  • The CPU cannot read a GpuArray's elements (d[0] is an error): gpuRead them. So the CPU never sees an old copy, which is the one thing to watch for inside gpuBatch.
  • GpuArray<number> is a type like any other: a variable, a class's field, a parameter, a closure's capture.
  • It is made on the GPU the program's kernels run on (the first launch's choice, made now if no launch came first), so a program that launches no kernel cannot make one. It needs -mm=gc, like gpuLaunch.
  • With TSLANG_GPU_PROFILE=1, gpuArray, gpuRead and gpuWrite print what they copied, a launch with GpuArrays only shows in 0.0 MB and out 0.0 MB, and the GPU memory of collected ones is said when it is given back.

Launches that do not wait

A launch whose arrays all stay on the GPU (GpuArrays, and arrays inside gpuBatch) has nothing to copy back, so it returns as soon as the GPU has the kernel: the program goes on while the GPU runs it, and the next launch queues behind it. The launches of a program run in the order it made them. The program waits for them where their results are needed:

  • a launch with an ordinary array (it copies the array in and back, so it waits for its own kernel, and the ones before it);
  • gpuReduce (it returns the sum);
  • gpuRead, gpuWrite and gpuFree;
  • the end of a gpuBatch;
  • gpuSync(), which waits for the kernels still running, and stops the program on a fault one of them had;
  • the end of the program.

gpuTime(fn) gives the milliseconds fn takes, the GPU's work it starts included: it waits for what ran before it, runs fn, and waits for fn's kernels, so the time is theirs and not only their launches':

const ms = gpuTime(() => gpuBatch(() => { for (let s = 0; s < 100; s++) gpuLaunch(step, n, bodies); }));

On the RTX 5080 a launch that does not wait costs about 7.5 µs, against 14 µs for one that does, whatever the kernel's size: for small kernels, launches are what the time goes on. On Intel's integrated GPU of a Core Ultra 9 285K, 2000 small launches take 13 ms that way, against 63 ms waiting after each.

A kernel that fails (an array index past the end, say) is reported where the program next waits, not at its own launch, and at the end of the program if nothing waits before it:

tslang gpu (cuda): running a kernel failed (719 unspecified launch failure)

TSLANG_GPU_SYNC=1 waits after every launch, so the error comes from the launch that caused it, and so does TSLANG_GPU_PROFILE=1, which times each kernel.

Numbers on the GPU

number is a 64-bit float. Most NVIDIA cards run those at a fraction of their 32-bit speed, and most Intel GPUs cannot run them at all: on those, a kernel on number[] is refused when it is loaded, with the driver's reason.

float is a 32-bit one. A kernel on float[] (and float arguments) whose values stay in floats works in 32 bits only, Math calls on them included, so it is fast on every GPU and runs on one without 64-bit floats, and its arrays are half the size to copy:

@kernel
function k(i: int, a: float[], b: float[], s: float) {
    const v: float = a[i];
    const r: float = Math.sqrt(v);
    b[i] = r * s;
}

Arithmetic on numbers brings 64-bit floats back: Math.sqrt(v) + 1 is a number, so keep each step in a float (const r: float = Math.sqrt(v)). A kernel on int[] needs no floats at all.

What has been run

The NVIDIA path runs on an RTX 5080, as executables and under the JIT, on Windows and on Linux (Ubuntu under WSL2, whose CUDA driver is the Windows one's: the running tests below pass there too). The Intel path runs on a Core Ultra 9 285K's integrated GPU (Intel Graphics, Level Zero on Windows): the running tests below and tslang/test/gpu/faults pass there, as executables and under the JIT. The AMD path runs on a Radeon RX 7900 XTX (gfx1100, HIP on Windows, with the Adrenalin driver's runtime alone and with the HIP SDK 7.2 too): the running tests below and tslang/test/gpu/faults pass there as executables and under the JIT, built for gfx1100 and for gfx11-generic alike (the JIT's code object linked by the HIP SDK's ld.lld). The test suite compiles a kernel for every GPU there is a backend for, and checks the errors (tslang/test/gpu). Running ones, which need a GPU: tslang/test/gpu/gpu_add_arrays.ts, gpu_saxpy_table.ts, gpu_add_ints.ts, gpu_math.ts, gpu_copy_back.ts, gpu_batch.ts, gpu_float.ts, gpu_atomics.ts, gpu_reduce.ts, gpu_batch_temporaries.ts, gpu_math_library.ts, gpu_shared.ts, gpu_grid.ts, gpu_call.ts, gpu_min_max.ts, gpu_array.ts, gpu_array_collect.ts, gpu_async.ts, gpu_barrier_guard.ts, gpu_blocks.ts, gpu_typed_arrays.ts, gpu_warp.ts, gpu_scan.ts, gpu_structs.ts, gpu_batch_views.ts, gpu_clamped_half.ts, gpu_classes.ts, gpu_print.ts, gpu_virtual.ts, gpu_batch_objects.ts, gpu_links.ts, gpu_small.ts, gpu_fields.ts, gpu_object_fields.ts, gpu_extremes.ts, gpu_random.ts, gpu_seed.ts, gpu_variables.ts, gpu_scan_sort.ts, gpu_reduce_repeatable.ts, gpu_arrows.ts, gpu_objects.ts, gpu_small_gaps.ts, gpu_callbacks.ts, gpu_write_only.ts, gpu_helper_arrays.ts, gpu_rows.ts, gpu_copies.ts, gpu_fused.ts, gpu_recursion.ts, gpu_recursion_deep.ts, gpu_batch_callbacks.ts, and tslang/benchmarks/raytrace/rtbench_gpu.ts.