Utilities API
工具类和参考实现。
Benchmark
性能测量工具类。
构造函数
typescript
import { Benchmark } from 'tiny-dl-inference';
const benchmark = new Benchmark();1
2
3
2
3
measure(fn)
测量单次执行时间。
typescript
const result = await benchmark.measure(async () => {
await operator.forward([input]);
await context.sync();
});
console.log(`耗时: ${result.timeMs.toFixed(2)} ms`);1
2
3
4
5
6
2
3
4
5
6
返回: { timeMs: number }
runMultiple(fn, options)
运行多次并计算统计。
typescript
const stats = await benchmark.runMultiple(async () => {
await operator.forward([input]);
await context.sync();
}, { runs: 100 });
console.log('统计:');
console.log(`平均值: ${stats.mean.toFixed(2)} ms`);
console.log(`中位数: ${stats.median.toFixed(2)} ms`);
console.log(`标准差: ${stats.stdDev.toFixed(2)} ms`);
console.log(`P99: ${stats.p99.toFixed(2)} ms`);1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
返回:
typescript
interface BenchmarkStats {
mean: number;
median: number;
stdDev: number;
p95: number;
p99: number;
min: number;
max: number;
runs: number;
}1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
参考实现
conv2dCPU
CPU 上的卷积参考实现。
typescript
import { conv2dCPU } from 'tiny-dl-inference';
const result = conv2dCPU(input, weights, stride, padding);1
2
3
2
3
用于验证 GPU 实现的正确性。
reluCPU
CPU 上的 ReLU 参考实现。
typescript
import { reluCPU } from 'tiny-dl-inference';
const result = reluCPU(input);1
2
3
2
3
softmaxCPU
CPU 上的 Softmax 参考实现。
typescript
import { softmaxCPU } from 'tiny-dl-inference';
const result = softmaxCPU(input);1
2
3
2
3
maxPool2dCPU
CPU 上的最大池化参考实现。
typescript
import { maxPool2dCPU } from 'tiny-dl-inference';
const result = maxPool2dCPU(input, kernelSize, stride, padding);1
2
3
2
3
im2col
卷积 im2col 转换工具。
im2col(input, kernelSize, stride, padding)
将输入图像转换为列矩阵格式以优化卷积计算。
typescript
import { im2col } from 'tiny-dl-inference';
const columns = im2col(input, [3, 3], [1, 1], [0, 0]);1
2
3
2
3
错误类型
WebGPUNotSupportedError
浏览器不支持 WebGPU 时抛出。
typescript
import { WebGPUNotSupportedError } from 'tiny-dl-inference';
try {
await context.init();
} catch (error) {
if (error instanceof WebGPUNotSupportedError) {
console.error('WebGPU 不受支持');
}
}1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
DeviceInitializationError
GPU 设备初始化失败时抛出。
typescript
import { DeviceInitializationError } from 'tiny-dl-inference';1
InvalidShapeError
张量形状不匹配时抛出。
typescript
import { InvalidShapeError } from 'tiny-dl-inference';1
BufferSizeError
缓冲区大小不匹配时抛出。
typescript
import { BufferSizeError } from 'tiny-dl-inference';1
示例
性能测试
typescript
import { Benchmark, Conv2dOperator, Tensor } from 'tiny-dl-inference';
const benchmark = new Benchmark();
const conv = new Conv2dOperator(context);
const stats = await benchmark.runMultiple(async () => {
const output = await conv.forward([input, weights]);
await context.sync();
output.destroy();
}, { runs: 100 });
console.log(`Conv2D 性能: ${stats.mean.toFixed(2)} ± ${stats.stdDev.toFixed(2)} ms`);1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12