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).
-
It is a function marked
@kernel, whose first parameter is the thread's index (int). It returns nothing, or, forgpuReduce, 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,gpuBatchand aGpuArraytake 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). A class's objects are not taken either: an array of them is of pointers.tslang/test/gpu/gpu_structs.tssteps 10000 particles on the GPU and on the CPU alike, and checks fields of every size with the padding between them. -
A typed array (
Float32Array,Float64Array,Int8ArraytoInt32Array,Uint8ArraytoUint32Array,BigInt64Array,BigUint64Array) is given where the kernel takes it,a: Float32Array, or takes the array of its elements,a: float[](aFloat64Arrayfor anumber[]too). In the kernel it is that array:a[i],a.length. A launch (gpuLaunch,gpuReduce, an@gpucall) 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 insidegpuBatchit stays on the GPU between launches (below), as does aGpuArray.tslang/test/gpu/gpu_typed_arrays.tsandgpu_batch_views.tsrun them. -
A
Uint8ClampedArrayand aFloat16Arrayare taken too, and keep JavaScript's rules in the kernel:- A
Uint8ClampedArray(px: Uint8ClampedArray) is au8[]there whose writes are clamped as JavaScript's are: into 0..255, rounded half to even, NaN 0. That is every write topx[i]:=,+=and the rest,++and--(px[i]++is the element before).Atomicson one is an error, as in JavaScript. A function the kernel handspxto sees au8[], whose writes wrap. - A
Float16Array(h: Float16Array) is anf16[]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 inf16(h[i] * 2), with anumberis innumber. Intel's GPUs need half floats for it (Xe GPUs have them). tslang/test/gpu/gpu_clamped_half.tsruns 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).
- A
-
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.signandMath.fround, each the GPU's own instruction, with JavaScript's results (Math.roundrounds halves up, and gives-0for-0.5);Math.sin,cos,tan,asin,acos,atan,atan2,sinh,cosh,tanh,asinh,acosh,atanh,exp,expm1,log,log2,log10,log1p,powandcbrt, from tslang's own GPU math library (below);Math.min,Math.maxandMath.hypotof two or three numbers, 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 makesminandmaxNaN,-0is below0, andhypotdoes not overflow (Math.hypot(1e200, 1e200)is1.414213562373095e200) and isInfinityif an argument is, NaN or not.minandmaxoffloats stay floats.
-
It cannot call what does not run on a GPU: printing, anything that allocates (a string, an object, a new array,
push), the library's other functions (Math.random, andMath.min/Math.max/Math.hypotof more than three arguments or of a spread, whose arguments are an array). The compiler says which call it is:error: gpuLaunch: a kernel calls 'Math.random' (from 'k'), which does not run on the GPU -
It cannot read a variable of the program: it is set when the program starts, which the GPU never sees. Pass it as an argument instead:
error: gpuLaunch: a kernel reads the program's variable 'scale', which the GPU does not share: pass it to the kernel as an argument -
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, anAtomics, 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 itsxamong the launch's threads (iforgpuLaunch(k, n, ...)). A launch that does not wait for its kernel (its arrays are allGpuArrays, or insidegpuBatch) 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 atgpuBarriersuch 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. -
gpuLaunch,gpuReduceandgpuBatchneed the default memory model (-mm=gc).
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,log1pandpow, 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'spowgives (JavaScript's is NaN). -
Floats: a
floatgiven to one of them, whose result goes straight back to afloat, 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,cosandtanare reduced exactly, as on the CPU, at some cost in speed. -
gpumath/generate.cmakeremakes the IR (gpumath.ll, which is checked in) with LLVM's clang after a change to the library.
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
@gpufunction is a plain call: a helper the kernel runs itself. - Outside kernels a
@gpufunction cannot be called on the CPU (every call is a launch); a@kernelone can,add(i, a, b, cpu)running it once for onei, which is how a test compares the GPU with the CPU. gpuLaunchandgpuReducetake a@gpufunction as they take a@kernelone.- It is a function of the program's own file, by its name (a top-level
function).
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 anyintexpression. A grid with an extent of 0 or less runs nothing. - It is one launch of
w * h(* d) threads,xthe fastest: a block's 256 threads are 256 consecutivex(across rows whenwis smaller), andgpuThreadIndex(),gpuBlockIndex()are those of that flat launch.w * h * dis 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. gpuReducetakes a count, not a grid.
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'siisgpuBlockIndex() * 256 + gpuThreadIndex().gpuBlockSize(): 256.- Each takes a dimension of the block, a constant:
gpuThreadIndex(1)is the thread'syin a block of 2 or 3 dimensions (below),(2)itsz;(0)is the same as none,x. gpuShared<T>(n): an array ofnnumbers (number,float,int, ...) that the threads of a block share, one for each block.nis a constant, of 48 KB at most. It starts with whatever was there: write before reading. EachgpuSharedin 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 pastntoo, and its array accesses (its own and those of the functions it calls) are guarded instead, so that it need not checki < n:- reading an element past an array's end (or below 0) gives 0;
- writing one past the end (an
Atomicstoo) does nothing; - a thread past
nwrites nothing to the GPU's arrays (the kernel's arguments,GpuArrays), so an array longer thannkeeps its elements pastn. Its writes to the block'sgpuSharedarrays are made: its part of a tile is the block's, astile[t] = a[i]above. And it reads as any thread does: an element that is there (a[i]of analonger thann, a neighbour's) is read, not 0.
Keep a barrier out of an
ifthat only some threads take. The guard is a comparison per array access, in these kernels only. -
gpuReducedoes not take such a kernel (its threads do not all reach the barrier);gpuLaunchit. -
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,gpuThreadIndexorgpuBlockIndex) 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.tslaunches 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.tsruns 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.
@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).@gputakes the same. - A block of one dimension is for any launch:
nthreads (gpuLaunch(k, n, ...), an@gpucall) or a grid, flat as blocks of 256 are. A block of 2 dimensions tiles a grid of 2,gpuLaunch(k, [w, h], ...): itsxandyaregpuBlockIndex(0) * 16 + gpuThreadIndex(0)and the same in 1, and the launch has as many blocks as coverwandh. 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 ind: 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 atgpuBarrier: then its threads past the grid's edge run too, and write nothing to the GPU's arrays (above), asc[row * p + col]. Their reads, asa[row * k + base + tx]past the edge, are of elements that are there, so the kernel checksrow < mitself where a value past the edge would be wrong. gpuReduceruns its kernel in blocks of its own: one with a{ block }is an error.tslang/test/gpu/gpu_blocks.tschecks 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.
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 togpuWarpSize() - 1. In a block of one dimension the warps are the block's threads in order: lanegpuThreadIndex() % gpuWarpSize().gpuShuffle(v, lane):vof the warp's lanelane(modulo the warp's size).gpuShuffleDown(v, d): of the lanedabove,gpuShuffleUp(v, d)of the lanedbelow,gpuShuffleXor(v, m)of lane^ m; a thread whose lane would be outside the warp gets its ownv.vis 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): anintwith a bit for each lanepis true for (lane 0 the lowest).gpuAll(p),gpuAny(p): whetherpis 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
gpuBarrierdoes (above): on every thread of its blocks, pastntoo, with its array accesses guarded. A thread pastnis in no vote (it is no bit of a ballot, nogpuAny's true, nogpuAll's false), but what it gives a shuffle is its ownv: sowarpSumsgives 0 pastnitself (i < n ? a[i] : 0). - A shuffle reads the lanes that run with it: in an
ifonly 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);gpuReducedoes not take it, and a call of it on the CPU is an error, as for a barrier kernel. On AMD's GPUs before gfx10gpuBallotis an error: their 64 lanes do not fit in anint. tslang/test/gpu/gpu_warp.tschecks each of them on 1000 threads (the last warp partly pastn), with arrays longer than that;gpu_scan.tsis a prefix sum of 100000 values: each warp's ofgpuShuffleUp, each block's of its warps' totals in shared memory, then the blocks' (on the RTX 5080: warps of 32).
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 nomaxormin. 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,Atomicsis 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
atomicAddis: 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
Atomicsis copied back after the launch, as any array the kernel writes. - Intel: a float
add,sub,maxorminis a compare-and-swap loop, which needs no SPIR-V extension. A 64-bit atomic (onnumber[]ors64[]) 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=intelit 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 (
numberorfloatalike), where a kernel copying the same million numbers takes 0.03 ms. Many elements (a histogram's bins) contend less; for one sum,gpuReduceis the fast way.
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, then adds its sum, atomically, into one of 256 sums, which the CPU adds up. On the RTX 5080, adding up a million numbers takes 0.02 ms on the GPU (and 0.1 ms to bring the 256 sums back), where a million threads adding into one sum take 1.2 ms.
- Floats are added in no particular order, so with fractions the last bits can differ between runs and from a
sum on the CPU. An integer sum wraps as its type does (
intat 2^31). - On Intel, a sum of
numbers or of 64-bit integers needs the GPU's 64-bit atomics (asAtomicson those arrays does); afloatorintsum runs everywhere. - The kernel can write arrays too, as a
gpuLaunchone does; the arrays come back the same way. A kernel that returns a value can be given togpuLaunchas well, which drops what it returns. - Inside
gpuBatch, the arrays stay on the GPU as forgpuLaunch, and eachgpuReducereturns its sum at once: a loop can stop when a sum says it is done.
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,cudatries those drivers, in that order, instead (cuda,hip,level-zero). -
TSLANG_GPU_VERBOSE=1prints 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>.
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 still copied in, since it may not write every element.
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.005 ms, in 2.697 ms (24.0 MB), kernel 0.024 ms, out 1.294 ms (8.0 MB)
The first launch also starts the driver and has it compile the kernels (about 100 ms there). 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 this, or for data that stays on it between launches, which is what gpuBatch is for.
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 hereOn 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, orbig.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), thenbig.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
fnends the batch as well: the arrays come back before it goes on. -
A
gpuBatchinside another one is part of it: the arrays come back when the outermost one ends. -
With
TSLANG_GPU_PROFILE=1, the end of a batch prints what it copied back.
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)makesnzeros there (numbers when noTis given).gpuLaunch, a grid,gpuReduceand an@gpucall take aGpuArray<T>where the kernel has aT[]; a launch can mix them with ordinary arrays, which are copied as before (insidegpuBatchtoo).gpuRead(d, a)copies the GPU's elements intoa,gpuWrite(d, a)copiesa's to the GPU;ais aT[]of the same length.gpuRead(d)copies them into a newT[], which it gives back.d.lengthis the number of elements.gpuFree(d)gives the GPU's memory back at once. AGpuArraythe program no longer holds is collected as well: the collector finds it gone, and the nextgpuArraygives its GPU memory back. The collector runs then too when theGpuArrays 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 withoutgpuFreedoes not run out (tslang/test/gpu/gpu_array_collect.ts: 64 of 256 MB, on a 16 GB GPU).gpuFreeis still the way to give memory back at a moment of the program's choosing. Using one aftergpuFreestops the program, saying so.- The CPU cannot read a
GpuArray's elements (d[0]is an error):gpuReadthem. So the CPU never sees an old copy, which is the one thing to watch for insidegpuBatch. 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, likegpuLaunch. - With
TSLANG_GPU_PROFILE=1,gpuArray,gpuReadandgpuWriteprint what they copied, a launch withGpuArrays only showsin 0.0 MBandout 0.0 MB, and the GPU memory of collected ones is said when it is given back.
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,gpuWriteandgpuFree;- the end of a
gpuBatch; - the end of the program.
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.
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. On Intel's GPUs every launch waits for now (Level Zero's
synchronous command list).
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.
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 one is checked as far as its compiled code goes (the code object's kernel
table): it has not been run on an AMD GPU yet. 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.