⚡
零依赖
无需 TensorFlow.js 或 ONNX Runtime。纯 WebGPU 实现,仅 ~58KB 包体积。
无需 TensorFlow.js 或 ONNX Runtime。纯 WebGPU 实现,仅 ~58KB 包体积。
融合的 Conv2d+Bias+ReLU 实现 3 倍内存带宽降低。单次内核启动,零中间张量。
从零开始用可读的 WGSL 着色器代码实现每个神经网络算子。完全控制 GPU。
高效的零开销张量视图。重塑操作耗时不到 1 微秒。
134+ 测试,包含基于属性的测试(每项 100+ 迭代)。CPU 参考实现用于验证。
完整的 TypeScript 严格模式实现。零 any 类型。生产级错误处理。
npm install tiny-dl-inferencepnpm add tiny-dl-inferenceyarn add tiny-dl-inferenceimport { GPUContext, Tensor, ReLUOperator } from 'tiny-dl-inference';
// 1. 初始化 GPU 上下文
const context = new GPUContext();
await context.init();
// 2. 创建输入张量
const input = Tensor.fromArray(context,
new Float32Array([1.0, -2.0, 3.0, -4.0]),
[1, 4, 1, 1] // [批次, 通道, 高度, 宽度]
);
// 3. 运行 ReLU 激活
const relu = new ReLUOperator(context);
const output = await relu.forward([input]);
// 4. 获取结果
const result = await output.download();
console.log(result); // Float32Array([1, 0, 3, 0])
// 5. 清理资源
input.destroy();
output.destroy();
context.destroy();未融合(6 次内存操作):
读取 → 卷积 → 写入 → 读取 → 偏置 → 写入 → 读取 → ReLU → 写入
已融合(2 次内存操作):
读取 → 卷积+偏置+ReLU → 写入| 基准测试 | 分离算子 | 融合算子 | 提升 |
|---|---|---|---|
| Conv2d 64 通道 | 2.34ms | 0.89ms | 2.6 倍更快 |
| 内存操作 | 6 次 | 2 次 | 降低 3 倍 |
| 内核启动 | 3 次 | 1 次 | 减少 66% |
| 中间张量 | 3 个 | 0 个 | 节省 100% |
| 浏览器 | 最低版本 | 支持状态 |
|---|---|---|
| Chrome | 113+ | ✅ 完全支持 |
| Edge | 113+ | ✅ 完全支持 |
| Safari | 18+ (macOS Sonoma+) | ⚠️ 实验性 |
| Firefox | 需要开启标志 | 🔧 启用 dom.webgpu.enabled |
检测 WebGPU 支持
if (navigator.gpu) {
console.log('✅ WebGPU 已支持!');
} else {
console.error('❌ 此浏览器不支持 WebGPU');
}