← projects
TypeScript library · MIT

GPGPU.js

GPGPU.js makes WebGPU compute approachable: run GPU-accelerated numerical work — matrix multiplication, parallel maps, reductions — straight from JavaScript or TypeScript, with no WGSL or shader setup to write yourself.

// highlights

  • WebGPU compute, zero boilerplate
  • No shader / WGSL knowledge needed
  • Typed API, ESM-first
  • GPU-accelerated matrix & parallel ops

// stack

TypeScriptWebGPU

// readme

npm version CI License: MIT

General-Purpose GPU Computing in JavaScript using WebGPU. Write GPU-accelerated code with zero boilerplate — no shader knowledge required.

Try it now: experiment with GPGPU.js right in your browser at the hosted playground.

Features

  • Minimal APIgpu.add(a, b), gpu.map(arr, x => x * 2), gpu.sum(arr)
  • Auto WGSL codegen — Arrow functions compile to GPU shaders automatically
  • Pipeline chaining — Chain ops without CPU-GPU roundtrips
  • GPU-resident arraysgpu.upload() + keepOnGpu keep data on the GPU across ops
  • CPU fallback — Runs everywhere, accelerates where WebGPU is available
  • TypeScript — Full type safety with zero runtime dependencies
  • Tree-shakeable — ESM + CJS, import only what you use

Install

npm install @thatscalaguy/gpgpu.js

Quick Start

import { gpu } from "@thatscalaguy/gpgpu.js";

// Element-wise operations
const sum = await gpu.add([1, 2, 3], [4, 5, 6]);       // [5, 7, 9]
const scaled = await gpu.multiply([1, 2, 3], 10);       // [10, 20, 30]

// Map with JS arrow functions (auto-compiled to GPU shaders)
const doubled = await gpu.map([1, 2, 3, 4], x => x * 2);           // [2, 4, 6, 8]
const transformed = await gpu.map(data, x => Math.sqrt(x) + 1);    // sqrt(x) + 1

// Reduce
const total = await gpu.sum([1, 2, 3, 4, 5]);           // 15
const maximum = await gpu.max([3, 1, 4, 1, 5, 9]);      // 9

// Matrix multiply
const result = await gpu.matmul(matA, matB, { rowsA: 64, colsA: 64, colsB: 64 });

// Pipeline — data stays on GPU between steps
const result = await gpu.pipeline()
  .map(x => x * 2)
  .map(x => x + 1)
  .reduce((a, b) => a + b, 0)
  .run(data);

// Keep data on the GPU across ops — one upload, one readback
const g = await gpu.upload([1, 2, 3, 4]);   // GPUArray
const scaled = await gpu.multiply(g, 2);     // GPUArray (input was on GPU)
const shifted = await gpu.add(scaled, 1);    // GPUArray
const out = await shifted.toArray();         // [3, 5, 7, 9]
g.destroy(); scaled.destroy(); shifted.destroy();

// Cleanup
gpu.destroy();

API Reference

Element-wise Operations

await gpu.add(a, b)        // a + b (arrays or array + scalar)
await gpu.subtract(a, b)   // a - b
await gpu.multiply(a, b)   // a * b
await gpu.divide(a, b)     // a / b

Map

// Arrow function (auto-compiled to WGSL)
await gpu.map(array, x => x * 2 + 1)

// String expression (minifier-safe)
await gpu.map(array, "x * x + 1")

Supported in expressions:

  • Arithmetic: + - * / %
  • Comparisons: < > <= >= == !=
  • Ternary: a > 0 ? a : -a
  • Math: Math.abs, Math.sqrt, Math.pow, Math.min, Math.max, Math.floor, Math.ceil, Math.sin, Math.cos, Math.tan, Math.exp, Math.log

Reduce

await gpu.reduce(array, (a, b) => a + b, 0)  // custom reduce
await gpu.sum(array)                           // sum
await gpu.min(array)                           // minimum
await gpu.max(array)                           // maximum
await gpu.product(array)                       // product

Matrix Multiply

await gpu.matmul(a, b, { rowsA, colsA, colsB })

Flat arrays with explicit dimensions. Uses tiled GPU algorithm with shared memory.

Sort

await gpu.sort(array)  // GPU-accelerated bitonic sort

Prefix Sum (Scan)

await gpu.scan(array)                          // default: addition
await gpu.scan(array, (a, b) => a + b, 0)     // custom scan

Pipeline

Chain operations to keep data on the GPU between steps:

const result = await gpu.pipeline()
  .map(x => x * 2)
  .map(x => x + 1)
  .reduce((a, b) => a + b, 0)
  .run(inputData);

GPU-Resident Arrays

By default every op uploads its input, computes, and reads the result back to the CPU. When you chain several ops on the same data, you can keep it on the GPU and pay for just one upload and one readback.

gpu.upload() returns a GPUArray — a handle to GPU-resident data:

const g = await gpu.upload([1, 2, 3, 4]);   // GPUArray
const result = await g.toArray();             // read back to a TypedArray
g.destroy();                                  // free the GPU buffer

Ops accept a GPUArray anywhere they accept an array. Auto mode: if any input is a GPUArray, the result is returned as a GPUArray (no readback); otherwise you get a TypedArray as before:

const g = await gpu.upload(data);
const a = await gpu.multiply(g, 2);   // GPUArray (input was on GPU)
const b = await gpu.map(a, x => x + 1);
const out = await b.toArray();        // read back once, at the end
g.destroy(); a.destroy(); b.destroy();

Override auto mode per call with keepOnGpu:

await gpu.add([1, 2, 3], 1, { keepOnGpu: true });  // force a GPUArray from CPU input
await gpu.add(g, 1, { keepOnGpu: false });          // force readback to a TypedArray

keepOnGpu works on add/subtract/multiply/divide, map, matmul, scan, sort, pipeline().run(), and createKernel().run(). Reductions (sum/min/max/product/reduce) accept a GPUArray input but always return a scalar number. In-place ops (scan, sort) never mutate a GPUArray input.

Ownership: a GPUArray you receive is yours to manage — read it with toArray() (which keeps it alive) or release it with destroy(). Leaking handles ties up pooled GPU buffers.

Custom Kernel

For power users who want to write raw WGSL:

const kernel = await gpu.createKernel({
  workgroupSize: 64,
  shader: `
    @group(0) @binding(0) var<storage, read> input0: array<f32>;
    @group(0) @binding(1) var<storage, read_write> output: array<f32>;
    @compute @workgroup_size(64)
    fn main(@builtin(global_invocation_id) gid: vec3u) {
      let idx = gid.x;
      output[idx] = input0[idx] * input0[idx];
    }
  `,
  inputs: [{ type: "f32", size: 1024 }],
  output: { type: "f32", size: 1024 },
});

const result = await kernel.run(inputData);

Instance Management

import { GPU } from "@thatscalaguy/gpgpu.js";

// Use the default singleton
import { gpu } from "@thatscalaguy/gpgpu.js";

// Or create your own instance
const myGpu = new GPU();
myGpu.destroy(); // cleanup when done

Backend & Fallback Control

When an op can't run on the GPU it falls back to a CPU implementation. By default that's silent apart from a console.warn, so callers can't tell which backend ran, how long it took, or stop the fallback from happening. Configure these on the instance — at construction or via mutable fields — and every op honours them:

import { GPU } from "@thatscalaguy/gpgpu.js";

const gpu = new GPU({
  // "warn" (default) logs + falls back, "silent" falls back quietly,
  // "throw" re-throws the GPU error instead of falling back.
  fallback: "throw",
  // Fires after every op with the backend that ran and how long it took.
  onStats: ({ op, backend, ms }) => console.log(`${op} ran on ${backend} in ${ms.toFixed(2)}ms`),
  // Fires when a GPU op throws, before the fallback policy is applied.
  onFallback: ({ op, error }) => report(op, error),
});

// Fields are mutable too:
gpu.onStats = (s) => metrics.record(s);
gpu.fallback = "silent";
  • onStats reports { op, backend: "gpu" | "cpu", ms } for every op, including GPU-resident and createKernel/pipeline runs (always "gpu"). The reduce family (reduce/sum/min/max/product) still returns a scalar number but reports stats just like the rest.
  • onFallback and the fallback policy apply only to ops with a CPU fallback; forced-GPU paths (a GPUArray input, keepOnGpu, custom kernels) throw on failure regardless.

How It Works

  1. You write JavaScriptx => x * 2 + 1
  2. Parser extracts the expression — builds an intermediate representation
  3. WGSL emitter generates GPU shader codeoutput[idx] = (x * 2.0) + 1.0;
  4. WebGPU compiles and dispatches — runs on thousands of GPU cores in parallel
  5. Results returned as Float32Array — ready to use

The library manages GPU device initialization, buffer pooling, shader caching, and data transfer automatically.

Browser Support

WebGPU is supported in:

  • Chrome 113+ / Edge 113+
  • Firefox 141+ (Windows), 145+ (macOS)
  • Safari 18+

When WebGPU is unavailable, all operations automatically fall back to CPU implementations.

Contributing

Contributions are welcome! See CONTRIBUTING.md for setup and workflow, and CODE_OF_CONDUCT.md for community guidelines. Security issues: see SECURITY.md.

License

MIT © Sven Herrmann

View on GitHub ↗

// project
languageTypeScript
typelibrary
licenseMIT
sourceOpen source
// activity
latestv0.2.0
updated1 June 2026
stars3 ★

Built and maintained by Sven — need it in production, extended or reviewed?

GitHub ↗Docs ↗Hire the author →