# bend-cuda-launcher Custom CUDA kernels for Bend 2, with no compiler fork and no build step: write the kernel as CUDA C++ source in a Bend string, compile it at run time with NVRTC for the GPU in use, and launch it on Bend arrays in place. ```python import bend-cuda-launcher@/cuda.bend as CU ``` Use it where Bend's own `!` kernels are slow: a Bend bang has a fixed cost of about 1 ms and runs one lane per item, while a CUDA kernel launches in microseconds and can use shared memory, warp shuffles and tensor cores. In a diffusion transformer, replacing about 25 bangs a block with 6 CUDA kernels took a sampler step from 2.0 s to 0.63 s (and a fused attention kernel, now the bend-gpu-attention package, from 4.0 s to 2.0 s before that). ## Example ```python def source() -> String: "BEND_KERNEL axpb(BEND_ARGS) {\n" ++ " unsigned i = blockIdx.x * blockDim.x + threadIdx.x;\n" ++ " if (i < p.v[0] && i < a0.n && i < a1.n && i < a2.n) a2.c[i] = bu(bf(a0.c[i]) * bf(p.v[1]) + bf(a1.c[i]));\n" ++ "}\n" # c = a * 1.5 + b over n cells (1069547520 is 1.5 as F32 bits), 256 threads a block @unsafe def axpb(+n: U32, a: Array, b: Array, c: Array) -> IO(Array & Array & Array & Array & Array & Array): do IO & Array & Array & Array & Array & Array>: m : U32 <- CU.Cu.module(source()) CU.Cu.run(m, "axpb", ((n + 255 : U32) / 256 : U32), 1, 1, 256, 1, 1, 0, a, b, c, Array.new(U32, 0n, 0), Array.new(U32, 0n, 0), Array.new(U32, 0n, 0), n, 1069547520, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) ``` Compile a module once and launch its kernels as often as needed; `test/cuda_test.bend` is a complete program. ## API (`cuda.bend`) **`Cu.module(source) -> IO(U32)`** compiles CUDA C++ (C++17) for the GPU in use and answers a handle (0, 1, 2, ...). The CUDA include directory is on the include path (`#include `, ``, ...). Every module starts with this prelude: ```cpp struct BendArr { unsigned* c; unsigned long long n; }; // an array's cells, and how many it holds struct BendP { unsigned v[12]; }; // the parameters float bf(unsigned u); // cell bits as float unsigned bu(float x); // float as cell bits #define BEND_KERNEL extern "C" __global__ void #define BEND_ARGS BendArr a0, BendArr a1, BendArr a2, BendArr a3, BendArr a4, BendArr a5, BendP p ``` so a kernel is `BEND_KERNEL name(BEND_ARGS) { ... }`. A compile error prints NVRTC's log, with line numbers of your source, and stops the program. **`Cu.run(module, name, gx, gy, gz, bx, by, bz, smem, a0, a1, a2, a3, a4, a5, p0, ..., p11)`** launches kernel `name` on a `gx x gy x gz` grid of `bx x by x bz` blocks with `smem` bytes of dynamic shared memory (more than 48 KB is requested from the driver), waits for it, and answers `(a0, (a1, (a2, (a3, (a4, a5)))))`. Pass any 1-cell array (`Array.new(U32, 0n, 0)`) for unused arrays and 0 for unused parameters; F32 parameters go as their bits. A kernel name it cannot find, a launch error or a kernel fault prints the CUDA error and stops the program. ## Safety: check every index **A kernel can write anywhere in Bend's heap, and nothing here stops it.** The heap is one large CUDA managed allocation, so an index past an array's end usually does not fault: it silently overwrites other data (a test writing 2^31 cells past a 1-cell array ran without error). Each array arrives with `.n`, its real capacity (a power of two at least the size asked of `Array.new`); compare every index against it, as the example does. ## Behaviour to know - **Fused multiply-add.** NVRTC, like nvcc, turns `a * b + c` into one FMA by default, which rounds once where Bend's arithmetic rounds twice; results can differ from the same formula in Bend in the last bit. Write `__fadd_rn(__fmul_rn(a, b), c)` where you need Bend's result exactly. - Every `Cu.run` waits for the GPU (`cuCtxSynchronize`); kernels do not overlap. - Compiling a module takes about 0.1-0.5 s with NVRTC; there is no cache between runs. - At most 256 modules a program, six arrays and twelve parameters a launch. ## Tests `test/cuda_test.bend` compiles one module and checks four kernels against the same computations in plain Bend: an elementwise kernel with an F32 parameter (exact), a per-row sum with dynamic shared memory (to 1e-5), a transpose on a 2D grid (exact), and the `.n` each of five arrays reports (exactly its capacity). It exits 1 on a mismatch. (Its first version caught both a grid one block too small and the FMA difference above.) ```bash bend test/cuda_test.bend -o cuda_test && ./cuda_test ``` ## Requirements - A **native CUDA build** of a program that uses `!` and uses the result of that call (`bend main.bend -o main`), so Bend's heap is CUDA managed memory; an unused `!` result can leave a CPU-only build. In a CPU build the effects stop with a message; the JS stubs throw. - `libnvrtc` at run time (from `$CUDA_HOME/lib64`, `/usr/local/cuda/lib64` or the loader path). - The C reads Bend runtime internals (`blk_loc`, `blk_cls`, `e.mem`, `gpu_dev`, `io_cstr`). Tested with **Bend 2.0.40** only; recheck after every Bend release. Foreign code: nothing here is proved, and kernels you write run unchecked.