Tensor API
用于神经网络计算的多维数据结构。
构造函数
Tensor(context, shape, layout?)
创建新的未初始化张量。
typescript
const tensor = new Tensor(context, [1, 3, 28, 28]);1
参数:
context: GPUContext- GPU 上下文实例shape: TensorShape- 张量形状[batch, channels, height, width]layout?: Layout- 内存布局(默认'NCHW')
静态方法
fromArray(context, data, shape)
从 CPU 数组创建张量并上传到 GPU。
typescript
const data = new Float32Array([1.0, 2.0, 3.0, 4.0]);
const tensor = Tensor.fromArray(context, data, [1, 4, 1, 1]);1
2
2
参数:
context: GPUContext- GPU 上下文data: Float32Array- 输入数据shape: TensorShape- 张量形状
返回: Promise<Tensor>
实例方法
download()
将 GPU 数据读取回 CPU Float32Array。
typescript
const array = await tensor.download();
console.log(array); // Float32Array([1.0, 2.0, 3.0])1
2
2
返回: Promise<Float32Array>
reshape(newShape)
创建新形状的视图(零拷贝)。
typescript
const reshaped = tensor.reshape([1, 784]);1
参数:
newShape: TensorShape- 目标形状
返回: Tensor(新视图)
flatten()
展平所有维度为一维。
typescript
const flat = tensor.flatten();1
返回: Tensor
convertLayout(targetLayout)
转换内存布局。
typescript
const nhwc = tensor.convertLayout('NHWC');1
参数:
targetLayout: Layout- 目标布局('NCHW'或'NHWC')
返回: Tensor
destroy()
释放 GPU 内存。
typescript
tensor.destroy();1
调用后张量不可再用。
属性
shape
张量的形状。
typescript
const shape: TensorShape = tensor.shape;
// 例如:[1, 3, 28, 28]1
2
2
size
元素总数。
typescript
const size: number = tensor.size;
// 例如:2352(1 * 3 * 28 * 28)1
2
2
dimensions
维度数。
typescript
const dims: number = tensor.dimensions;
// 例如:41
2
2
layout
内存布局。
typescript
const layout: Layout = tensor.layout;
// 'NCHW' 或 'NHWC'1
2
2
buffer
底层 GPU 缓冲区。
typescript
const buffer: GPUBuffer = tensor.buffer;1
用于直接访问 GPU 资源。
示例
创建和使用张量
typescript
// 1. 从数据创建
const input = Tensor.fromArray(context,
new Float32Array([0.5, -1.0, 2.0, 0.0]),
[1, 4, 1, 1]
);
// 2. 重塑形状
const reshaped = input.reshape([1, 2, 2, 1]);
// 3. 展平
const flat = input.flatten();
// 4. 获取数据
const result = await input.download();
// 5. 清理
input.destroy();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
内存管理
所有权模型
- 创建张量会分配 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
相关资源
- 张量指南 - 详细使用说明
- 内存布局 - NCHW vs NHWC
- GPUContext API - 资源管理