张量
Tensor 是用于神经网络计算的多维数据结构。
概述
Tensor 类表示:
- NCHW 布局中的多维数据
- GPU 内存中的高效存储
- 形状操作(重塑、展平)
- 数据输入和输出操作
创建张量
从数组创建
typescript
import { Tensor, GPUContext } from 'tiny-dl-inference';
const context = new GPUContext();
await context.init();
const data = new Float32Array([1.0, 2.0, 3.0, 4.0]);
const tensor = Tensor.fromArray(context, data, [1, 4, 1, 1]);1
2
3
4
5
6
7
2
3
4
5
6
7
分配未初始化的张量
typescript
const tensor = new Tensor(context, [1, 3, 28, 28]);1
数据传递
download()
将 GPU 数据读取回 CPU:
typescript
const array = await tensor.download();
console.log(array); // Float32Array1
2
2
内存布局
Tiny-DL-Inference 使用 NCHW(批次-通道-高度-宽度)作为原生布局:
typescript
// NCHW: [batch, channels, height, width]
const nchw = new Tensor(context, [1, 3, 28, 28]);
// 转换为 NHWC(如果需要)
const nhwc = tensor.convertLayout('NHWC');1
2
3
4
5
2
3
4
5
形状操作
reshape()
创建新形状的新视图(零拷贝):
typescript
const reshaped = tensor.reshape([1, 784]);1
flatten()
展平所有维度为一维:
typescript
const flat = tensor.flatten();1
属性
typescript
tensor.shape; // 形状:[number, number, number, number]
tensor.size; // 元素总数
tensor.dimensions; // 维度数
tensor.layout; // 'NCHW' 或 'NHWC'1
2
3
4
2
3
4
内存管理
destroy()
释放 GPU 内存:
typescript
tensor.destroy();1
所有权模型
- 创建张量会分配 GPU 内存
- 你必须在使用完毕后销毁它们
- 视图(来自 reshape)共享底层内存
typescript
const input = new Tensor(context, [1, 3, 28, 28]);
const view = input.reshape([1, 2352]);
view.destroy(); // 仅销毁视图
input.destroy(); // 释放实际内存1
2
3
4
5
2
3
4
5
最佳实践
- 及时销毁:不再需要时立即销毁张量
- 重用缓冲区:尽可能使用 deferDestroy()
- 避免不必要的拷贝:使用 reshape() 而非创建新张量
- 监控内存使用:使用 Benchmark 工具跟踪分配