Define a Basic Kernel Function in GPU.js

This article explains how to define and execute a basic kernel function using the gpu.createKernel method in GPU.js. You will learn the fundamental syntax, how to set output dimensions, how to access thread coordinates, and how to execute parallel computations directly on your GPU using JavaScript.

1. Initialize GPU.js

To start using GPU.js, instantiate the GPU class. This creates the execution context needed to compile JavaScript code into WebGL shader language.

const { GPU } = require('gpu.js'); // For Node.js
// or simply use 'new GPU()' in the browser if included via script tag
const gpu = new GPU();

2. Basic Syntax of gpu.createKernel

The gpu.createKernel method takes a standard JavaScript function, translates it into WebGL GLSL bytecode, and runs it across parallel threads on the GPU. You must specify the output dimensions using the .setOutput() method.

const myKernel = gpu.createKernel(function() {
    return this.thread.x;
}).setOutput([5]);

In this example:

3. Passing Arguments to a Kernel

Kernels can accept parameters such as arrays, matrices, numbers, or textures. Here is how to add two arrays together element by element:

const addArrays = gpu.createKernel(function(a, b) {
    return a[this.thread.x] + b[this.thread.x];
}).setOutput([5]);

const arrayA = [1, 2, 3, 4, 5];
const arrayB = [10, 20, 30, 40, 50];

const result = addArrays(arrayA, arrayB);
console.log(result); // Float32Array [11, 22, 33, 44, 55]

4. Working with Multi-Dimensional Dimensions

You can define 2D or 3D output grids by passing multiple dimensions to .setOutput().

Example of a 2D multiplication table:

const matrixMultiplication = gpu.createKernel(function() {
    return this.thread.x * this.thread.y;
}).setOutput([5, 5]);

console.log(matrixMultiplication());

5. Kernel Limitations to Keep in Mind

When writing code inside gpu.createKernel, keep the following constraints in mind: