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.
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.
gpu.add(a, b), gpu.map(arr, x => x * 2), gpu.sum(arr)gpu.upload() + keepOnGpu keep data on the GPU across opsnpm install @thatscalaguy/gpgpu.js
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();
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
// 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:
+ - * / %< > <= >= == !=a > 0 ? a : -aMath.abs, Math.sqrt, Math.pow, Math.min, Math.max, Math.floor, Math.ceil, Math.sin, Math.cos, Math.tan, Math.exp, Math.logawait 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
await gpu.matmul(a, b, { rowsA, colsA, colsB })
Flat arrays with explicit dimensions. Uses tiled GPU algorithm with shared memory.
await gpu.sort(array) // GPU-accelerated bitonic sort
await gpu.scan(array) // default: addition
await gpu.scan(array, (a, b) => a + b, 0) // custom scan
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);
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
GPUArrayyou receive is yours to manage — read it withtoArray()(which keeps it alive) or release it withdestroy(). Leaking handles ties up pooled GPU buffers.
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);
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
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.x => x * 2 + 1output[idx] = (x * 2.0) + 1.0;The library manages GPU device initialization, buffer pooling, shader caching, and data transfer automatically.
WebGPU is supported in:
When WebGPU is unavailable, all operations automatically fall back to CPU implementations.
Contributions are welcome! See CONTRIBUTING.md for setup and workflow, and CODE_OF_CONDUCT.md for community guidelines. Security issues: see SECURITY.md.
MIT © Sven Herrmann
Built and maintained by Sven — need it in production, extended or reviewed?
GitHub ↗Docs ↗Hire the author →