{"id":15115,"library":"gpu.js","title":"GPU.js - GPU Accelerated JavaScript","description":"GPU.js is a JavaScript library designed for General Purpose computing on Graphics Processing Units (GPGPU), enabling high-performance numerical computations in both web browsers and Node.js environments. It achieves this by automatically transpiling ordinary JavaScript functions into shader language (e.g., GLSL for WebGL) which then executes directly on the GPU, leveraging parallel processing capabilities for significant speedups, often 1-15x faster than CPU-bound operations. The library includes a robust fallback mechanism, ensuring that if a GPU is unavailable, computations seamlessly revert to standard JavaScript execution on the CPU. The current stable version is 2.16.0, with recent releases primarily focusing on maintenance, bug fixes (including security and memory leak issues in earlier 2.x versions), and performance enhancements. A key differentiator is its abstraction over complex shader programming, allowing developers to write GPU-accelerated code using familiar JavaScript syntax and a `this.thread.x/y/z` model for accessing thread indices within the kernel.","status":"active","version":"2.16.0","language":"javascript","source_language":"en","source_url":"https://github.com/gpujs/gpu.js","tags":["javascript","gpgpu","webgl","typescript"],"install":[{"cmd":"npm install gpu.js","lang":"bash","label":"npm"},{"cmd":"yarn add gpu.js","lang":"bash","label":"yarn"},{"cmd":"pnpm add gpu.js","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"For ESM environments (modern Node.js, bundlers), use named import. CommonJS `require` is also supported for Node.js.","wrong":"const GPU = require('gpu.js');","symbol":"GPU","correct":"import { GPU } from 'gpu.js';"},{"note":"When `gpu-browser.min.js` is loaded via a `<script>` tag, `GPU` is available as a global variable. Do not use `import` in this context.","wrong":"import { GPU } from 'gpu.js';","symbol":"GPU (browser global)","correct":"const gpu = new GPU();"},{"note":"Import `IKernelFunction` from 'gpu.js' for type-checking kernel functions when using TypeScript, as seen in advanced examples.","symbol":"IKernelFunction","correct":"import { IKernelFunction } from 'gpu.js';"}],"quickstart":{"code":"import { GPU } from 'gpu.js';\n\n// Initialize GPU.js\nconst gpu = new GPU();\n\n// Define two 512x512 matrices for multiplication\nconst matrixA = Array(512).fill(0).map(() => Array(512).fill(Math.random()));\nconst matrixB = Array(512).fill(0).map(() => Array(512).fill(Math.random()));\n\n// Create a GPU accelerated kernel function for matrix multiplication\nconst multiplyMatrix = gpu.createKernel(function(a: number[][], b: number[][]) {\n  let sum = 0;\n  for (let i = 0; i < 512; i++) {\n    // this.thread.x and this.thread.y represent the current thread's coordinates\n    sum += a[this.thread.y][i] * b[i][this.thread.x];\n  }\n  return sum;\n}).setOutput([512, 512]); // Define the output dimensions of the kernel\n\n// Run the kernel with the input matrices\nconst c = multiplyMatrix(matrixA, matrixB) as number[][];\n\nconsole.log('Matrix multiplication completed on GPU (or CPU fallback).');\nconsole.log('Resulting matrix dimensions:', c.length, 'x', c[0].length);\n// For a real application, you'd inspect 'c' for results.","lang":"typescript","description":"This quickstart demonstrates how to set up `gpu.js`, define a GPU kernel for 512x512 matrix multiplication, and execute it, showcasing the basic API for offloading computations."},"warnings":[{"fix":"Review the 'Pipelining' and 'Cleanup pipeline texture memory' sections in the documentation for proper memory management when chaining kernels and using `pipeline: true`.","message":"GPU.js v2 introduced new concepts around 'pipelining' for chaining kernels efficiently and explicit texture cloning/cleanup. While these were performance features, they implied new memory management considerations for users chaining kernels, specifically regarding `cleanupPipelineTextureMemory()`.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Use `gpu.addFunction(yourFunction)` to make helper functions available inside kernels, or define helper functions directly inside the kernel if they are simple enough to be transpiled.","message":"External functions (functions not defined within the kernel's scope) cannot be directly called from within a `createKernel` function. The kernel's body is transpiled to GLSL, which does not have access to the surrounding JavaScript scope.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Pass external variables as arguments to the `createKernel` function or use `constants` in the kernel configuration. Do not attempt to access `this.someVariable` if `someVariable` is not a kernel property.","message":"The `this` context inside a GPU.js kernel function (`createKernel` callback) refers to the GPU thread's properties (`this.thread.x`, `this.thread.y`, `this.thread.z`) and not the surrounding JavaScript context. Accessing external variables directly from `this` will fail.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Upgrade to GPU.js version 2.8.5 or newer to benefit from memory leak fixes. Ensure `kernel.destroy()` is called when a kernel is no longer needed to explicitly free resources.","message":"Versions 2.8.4 and 2.8.5 addressed significant memory leaks related to texture deallocation. Earlier versions could consume excessive GPU memory, especially with frequent kernel runs or pipeline usage, potentially leading to performance degradation or crashes.","severity":"breaking","affected_versions":"<2.8.4"},{"fix":"Upgrade to GPU.js version 2.8.3 or newer to mitigate potential security vulnerabilities.","message":"Version 2.8.3 included a fix for a security issue. Details are not publicly disclosed beyond 'Fix Security Issue' in the release notes, but users on older versions are advised to upgrade for security patching.","severity":"breaking","affected_versions":"<2.8.3"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure `this.thread` is only accessed within the callback function passed to `gpu.createKernel()` or a function called by it that was added via `gpu.addFunction()`.","cause":"Attempting to access `this.thread.x` (or `y`/`z`) outside of a GPU.js kernel function, or when `this` context is incorrectly bound.","error":"TypeError: Cannot read properties of undefined (reading 'x')"},{"fix":"Verify that the arguments passed to `.setOutput([width, height, depth])` are positive integers reflecting the desired output size of the computation. Also, check input array dimensions.","cause":"The output dimensions specified in `.setOutput()` resulted in a zero-dimension texture, or input arrays were empty/invalid.","error":"WebGL: INVALID_VALUE: texImage2D: width or height is 0"},{"fix":"Review the list of supported Math methods and language features in the GPU.js documentation. For custom functions, use `gpu.addFunction()` to provide a transpilable implementation or refactor the logic to use supported operations.","cause":"A JavaScript function or method called inside the kernel could not be transpiled into an equivalent GLSL shader function by GPU.js.","error":"Error: Function 'someFunction' is not supported."},{"fix":"Simplify the kernel logic. Avoid complex closures, object manipulations, or unsupported data structures within the kernel. Enable debugging (`gpu.setDebug(true)`) and check browser console logs for detailed GLSL compilation errors.","cause":"The transpiled GLSL code for the kernel contains syntax errors or uses unsupported features for the target WebGL environment, often due to complex JavaScript logic that can't be directly translated.","error":"Error: GLSL failed to compile"}],"ecosystem":"npm"}