Skip to content

Writing Kernels

A Kernel contains the WGSL code that runs on the GPU.

import { Kernel } from '@volten/core';
const scale = new Kernel(`
fn main(gid: vec3u) {
output[gid.x] = input[gid.x] * multiplier;
}
`);

You write a main function. Volten adds the compute entry point, workgroup size, bindings, and safety guard around it.

Volten expands a few parameter names in main:

NameTypeMeaning
gidvec3u or vec3<u32>Global invocation id
lidu32Local invocation index
lid3vec3u or vec3<u32>Local invocation id
widvec3u or vec3<u32>Workgroup id
nwgvec3u or vec3<u32>Number of workgroups
const kernel = new Kernel(`
fn main(gid: vec3u, lid: u32) {
data[gid.x] = f32(lid);
}
`);

You can also write the full WGSL builtin syntax yourself.

fn main(@builtin(global_invocation_id) gid: vec3u) {
data[gid.x] = data[gid.x] * 2.0;
}

Only the function named main is treated as the kernel entry point. Other functions are left alone.

const kernel = new Kernel(`
fn square(x: f32) -> f32 {
return x * x;
}
fn main(gid: vec3u) {
data[gid.x] = square(data[gid.x]);
}
`);

Add a label when you want clearer debug output and browser GPU tooling names.

const kernel = new Kernel(`...`, {
label: 'scale values'
});