GPU.js is a JavaScript Acceleration library for GPGPU (General purpose computing on GPUs) in JavaScript for Web and Node. GPU.js automatically transpiles simple JavaScript functions into shader language and compiles them so they run on your GPU. In case a GPU is not available, the functions will still run in regular JavaScript. For some more quick concepts, see Quick Concepts on the wiki.
Creates a GPU accelerated kernel transpiled from a javascript function that computes a single element in the 512 x 512 matrix (2D array). The kernel functions are ran in tandem on the GPU often resulting in very fast computations! You can run a benchmark of this here. Typically, it will run 1-15x faster depending on your hardware. Matrix multiplication (perform matrix multiplication on 2 matrices of size 512 x 512) written in GPU.js:
<script src="https://github.com/gpujs/gpu.js/raw/2.11.2/dist/gpu-browser.min.js"></script>
<script>
// GPU is a constructor and namespace for browser
const gpu = new GPU();
const multiplyMatrix = gpu.createKernel(function(a, b) {
let sum = 0;
for (let i = 0; i < 512; i++) {
sum += a[this.thread.y][i] * b[i][this.thread.x];
}
return sum;
}).setOutput([512, 512]);
const c = multiplyMatrix(a, b);
</script>
https://unpkg.com/gpu.js@latest/dist/gpu-browser.min.js
https://cdn.jsdelivr.net/npm/gpu.js@latest/dist/gpu-browser.min.js
const { GPU } = require('gpu.js');
const gpu = new GPU();
const multiplyMatrix = gpu.createKernel(function(a, b) {
let sum = 0;
for (let i = 0; i < 512; i++) {
sum += a[this.thread.y][i] * b[i][this.thread.x];
}
return sum;
}).setOutput([512, 512]);
const c = multiplyMatrix(a, b);
import { GPU } from 'gpu.js';
const gpu = new GPU();
const multiplyMatrix = gpu.createKernel(function(a: number[][], b: number[][]) {
let sum = 0;
for (let i = 0; i < 512; i++) {
sum += a[this.thread.y][i] * b[i][this.thread.x];
}
return sum;
}).setOutput([512, 512]);
const c = multiplyMatrix(a, b) as number[][];
Click here for more typescript examples.
Notice documentation is off? We do try our hardest, but if you find something, please bring it to our attention, or become a contributor!
GPU Settingsgpu.createKernel SettingsGPU.js in the wild, all around the net. Add yours here! * Temperature interpolation using GPU.js * Julia Set Fractal using GPU.js * Hello, gpu.js v2 * Basic gpu.js canvas example * Raster projection with GPU.js * GPU.js Example: Slow Fade * GPU.JS CA Proof of Concept * Image Convolution using GPU.js * Leaflet + gpu.js canvas * Image to GPU.js * GPU Accelerated Heatmap using gpu.js * Dijkstra’s algorithm in gpu.js * Voronoi with gpu.js * The gpu.js loop * GPU.js Example: Mandelbrot Set * GPU.js Example: Mandelbulb * Inverse of the distance with gpu.js * gpu.js laser detection v2 * GPU.js Canvas * Video Convolution using GPU.js * GPU Rock Paper Scissors * Shaded relief with gpujs and d3js * Caesar Cipher GPU.js Example
On Linux, ensure you have the correct header files installed: sudo apt install mesa-common-dev libxi-dev (adjust for your distribution)
npm install gpu.js --save
yarn add gpu.js
const { GPU } = require('gpu.js');
const gpu = new GPU();
import { GPU } from 'gpu.js';
const gpu = new GPU();
Download the latest version of GPU.js and include the files in your HTML page using the following tags:
<script src="https://github.com/gpujs/gpu.js/raw/2.11.2/dist/gpu-browser.min.js"></script>
<script>
const gpu = new GPU();
</script>
GPU SettingsSettings are an object used to create an instance of GPU. Example: new GPU(settings)
* canvas: HTMLCanvasElement. Optional. For sharing canvas. Example: use THREE.js and GPU.js on same canvas.
* context: WebGL2RenderingContext or WebGLRenderingContext. For sharing rendering context. Example: use THREE.js and GPU.js on same rendering context.
* mode: Defaults to 'gpu', other values generally for debugging:
* 'dev' New in V2!: VERY IMPORTANT! Use this so you can breakpoint and debug your kernel! This wraps your javascript in loops but DOES NOT transpile your code, so debugging is much easier.
* 'webgl': Use the WebGLKernel for transpiling a kernel
* 'webgl2': Use the WebGL2Kernel for transpiling a kernel
* 'headlessgl' New in V2!: Use the HeadlessGLKernel for transpiling a kernel
* 'cpu': Use the CPUKernel for transpiling a kernel
* onIstanbulCoverageVariable: Removed in v2.11.0, use v8 coverage
* removeIstanbulCoverage: Removed in v2.11.0, use v8 coverage
gpu.createKernel SettingsSettings are an object used to create a kernel or kernelMap. Example: gpu.createKernel(settings)
* output or kernel.setOutput(output): array or object that describes the output of kernel. When using kernel.setOutput() you can call it after the kernel has compiled if kernel.dynamicOutput is true, to resize your output. Example:
* as array: [width], [width, height], or [width, height, depth]
* as object: { x: width, y: height, z: depth }
* pipeline or kernel.setPipeline(true) New in V2!: boolean, default = false
* Causes kernel() calls to output a Texture. To get array's from a Texture, use:
js
const result = kernel();
result.toArray();
* Can be passed directly into kernels, and is preferred:
js
kernel(texture);
* graphical or kernel.setGraphical(boolean): boolean, default = false
* loopMaxIterations or kernel.setLoopMaxIterations(number): number, default = 1000
* constants or kernel.setConstants(object): object, default = null
* dynamicOutput or kernel.setDynamicOutput(boolean): boolean, default = false - turns dynamic output on or off
* dynamicArguments or kernel.setDynamicArguments(boolean): boolean, default = false - turns dynamic arguments (use different size arrays and textures) on or off
* optimizeFloatMemory or kernel.setOptimizeFloatMemory(boolean) New in V2!: boolean - causes a float32 texture to use all 4 channels rather than 1, using less memory, but consuming more GPU.
* precision or kernel.setPrecision('unsigned' | 'single') New in V2!: 'single' or 'unsigned' - if 'single' output texture uses float32 for each colour channel rather than 8
* fixIntegerDivisionAccuracy or kernel.setFixIntegerDivisionAccuracy(boolean) : boolean - some cards have accuracy issues dividing by factors of three and some other primes (most apple kit?). Default on for affected cards, disable if accuracy not required.
* functions or kernel.setFunctions(array): array, array of functions to be used inside kernel. If undefined, inherits from GPU instance. Can also be an array of { source: function, argumentTypes: object, returnType: string }.
* nativeFunctions or kernel.setNativeFunctions(array): object, defined as: { name: string, source: string, settings: object }. This is generally set via using GPU.addNativeFunction()
* VERY IMPORTANT! - Use this to add special native functions to your environment when you need specific functionality is needed.
* injectedNative or kernel.setInjectedNative(string) New in V2!: string, defined as: { functionName: functionSource }. This is for injecting native code before translated kernel functions.
* subKernels or kernel.setSubKernels(array): array, generally inherited from GPU instance.
* immutable or kernel.setImmutable(boolean): boolean, default = false
* VERY IMPORTANT! - This was removed in v2.4.0 - v2.7.0, and brought back in v2.8.0 by popular demand, please upgrade to get the feature
* strictIntegers or kernel.setStrictIntegers(boolean): boolean, default = false - allows undefined argumentTypes and function return values to use strict integer declarations.
* useLegacyEncoder or kernel.setUseLegacyEncoder(boolean): boolean, default false - more info here.
* tactic or kernel.setTactic('speed' | 'balanced' | 'precision') New in V2!: Set the kernel's tactic for compilation. Allows for compilation to better fit how GPU.js is being used (internally uses lowp for 'speed', mediump for 'balanced', and highp for 'precision'). Default is lowest resolution supported for output.
Depending on your output type, specify the intended size of your output. You cannot have an accelerated function that does not specify any output size.
| Output size | How to specify output size | How to reference in kernel |
|---|---|---|
| 1D | [length] |
value[this.thread.x] |
| 2D | [width, height] |
value[this.thread.y][this.thread.x] |
| 3D | [width, height, depth] |
value[this.thread.z][this.thread.y][this.thread.x] |
const settings = {
output: [100]
};
or
// You can also use x, y, and z
const settings = {
output: { x: 100 }
};
Create the function you want to run on the GPU. The first input parameter to createKernel is a kernel function which will compute a single number in the output. The thread identifiers, this.thread.x, this.thread.y or this.thread.z will allow you to specify the appropriate behavior of the kernel function at specific positions of the output.
const kernel = gpu.createKernel(function() {
return this.thread.x;
}, settings);
The created function is a regular JavaScript function, and you can use it like one.
kernel();
// Result: Float32Array[0, 1, 2, 3, ... 99]
Note: Instead of creating an object, you can use the chainable shortcut methods as a neater way of specifying settings.
const kernel = gpu.createKernel(function() {
return this.thread.x;
}).setOutput([100]);
kernel();
// Result: Float32Array[0, 1, 2, 3, ... 99]
$ claude mcp add gpu.js \
-- python -m otcore.mcp_server <graph>