把 WebGPU 通用计算变成一行代码
WebGPU GPGPU in one line of code
moxwebgpu 是一个面向浏览器的 WebGPU 通用计算(GPGPU)框架。它把 WebGPU 底层繁琐的适配器管理、管线构建、缓冲区生命周期、数据读回全部封装起来,对外暴露三层递进式 API。
moxwebgpu is a WebGPU general-purpose compute (GPGPU) framework for the browser. It wraps all the boilerplate — adapter management, pipeline building, buffer lifetime, readback — behind three layers of API.
同一份代码,浏览器与 Node 通用。没有独立显卡的机器上,用 Chrome 自带的 SwiftShader 软件渲染也能把真实 WebGPU 端到端测试全部跑绿——它的每一行 GPU 代码都被真实验证过。 One codebase for browser and Node. Even without a discrete GPU, Chrome's built-in SwiftShader software renderer runs the real end-to-end WebGPU tests green — every line of GPU code here is actually verified.
类型化张量 + 链式算子,gpu.tensor([1,2]).sum()
Typed tensors with a chainable op API, gpu.tensor([1,2]).sum()
整条算子链一次下发,中间缓冲自动回收,只 dispatch 一次
The whole chain dispatches once, with automatic temp-buffer recycling
直接跑原始 WGSL,管线缓存加速
Run raw WGSL with pipeline caching
<script src="https://unpkg.com/moxwebgpu/dist/moxwebgpu.browser.js"></script>
<script>
const gpu = await MoxWebGPU.mox.init();
console.log(await gpu.tensor([1, 2, 3]).sum().item()); // 6
</script>
IIFE 产物暴露全局 MoxWebGPU,内含 mox、MoxContext、Tensor、Kernel 等全部导出。
The IIFE bundle exposes a global MoxWebGPU with mox, MoxContext, Tensor, Kernel and all other exports.
npm install moxwebgpu
import { mox } from 'moxwebgpu'; // ESM
// const { mox } = require('moxwebgpu'); // CJS
以下示例默认已执行 const gpu = await mox.init();
The examples below assume const gpu = await mox.init(); has run.
const a = gpu.tensor([1, 2, 3, 4]); // 1-D, shape inferred [4]
const m = gpu.tensor([[1, 2, 3], [4, 5, 6]]); // 2-D, shape [2,3]
const t = gpu.tensor(flatData, { shape: [128, 128] }); // TypedArray + explicit shape
// 写法像 NumPy,执行像 CUDA 图
const r = await gpu.tensor([1, 2, 3, 4])
.add(1) // [2,3,4,5]
.relu()
.mul(10) // [20,30,40,50]
.sum() // 归约
.item(); // 140 —— 读回时整条链才执行,且只执行一次
const c = await gpu.tensor([[1, 2], [3, 4]])
.matmul(gpu.tensor([[5, 6], [7, 8]]))
.toArray(); // [[19, 22], [43, 50]]
| 层 | Layer | 能力 | Capability |
|---|---|---|---|
| Tensor | 类型化张量 + 30+ 链式算子 | Typed tensors + 30+ chainable ops | |
| Lazy graph | 拓扑排序、整链一次下发、临时缓冲回收 | Topo-sort, single dispatch, temp recycling | |
| Kernel | 原始 WGSL + 管线缓存 | Raw WGSL + pipeline cache | |
| core | 上下文 / 缓冲池 / dtype | Context / buffer pool / dtypes |
git clone https://github.com/codecloud-dev/moxwebgpu.git
cd moxwebgpu
pnpm install # 安装依赖
pnpm build # 产物输出到 dist/
pnpm test # 单元测试
pnpm test:gpu # 真实 WebGPU 端到端测试
pnpm demo # 启动本地演示页
产物同时输出 ESM / CJS / IIFE 浏览器版 与类型声明,运行时零依赖。
Outputs ESM / CJS / IIFE browser bundles plus type declarations, with zero runtime dependencies.