张量是PyTorch的基石——一切数据、参数、梯度都是张量。掌握张量操作是进入大模型开发的第一道门槛。
在PyTorch中,张量(Tensor)是最基本的数据结构。你可以把它理解为一个多维数组,但与NumPy的ndarray相比,它多了三个关键能力:GPU加速、自动微分和并行计算。在大模型中,所有的权重、激活值、梯度都是以张量形式存在和计算的。
张量的"维度"(dimension,也叫rank或ndim)决定了数据的结构层次。让我们从最简单的开始,逐层理解:
import torch
# 0维张量(标量 scalar)——一个单独的数值
scalar = torch.tensor(42.0)
print(f"标量: {scalar}, 形状: {scalar.shape}, 维度: {scalar.dim()}")
# 标量: 42.0, 形状: torch.Size([]), 维度: 0
# 1维张量(向量 vector)——一列数值
vector = torch.tensor([1.0, 2.0, 3.0])
print(f"向量: {vector}, 形状: {vector.shape}, 维度: {vector.dim()}")
# 向量: tensor([1., 2., 3.]), 形状: torch.Size([3]), 维度: 1
# 2维张量(矩阵 matrix)——一个表格
matrix = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
print(f"矩阵: {matrix}, 形状: {matrix.shape}, 维度: {matrix.dim()}")
# 矩阵: tensor([[1., 2.], [3., 4.]]), 形状: torch.Size([2, 2]), 维度: 2
# 3维张量——可以想象为"一叠矩阵"
tensor3d = torch.randn(3, 4, 5)
print(f"3D张量形状: {tensor3d.shape}, 维度: {tensor3d.dim()}")
# 3D张量形状: torch.Size([3, 4, 5]), 维度: 3
# 大模型中常见的张量形状
# Token embeddings: (batch_size, seq_len, hidden_size) — 3D
# Attention weights: (batch_size, num_heads, seq_len, seq_len) — 4D
# Weight矩阵: (out_features, in_features) — 2D
每个张量都有几个核心属性,理解它们是高效使用PyTorch的基础:
| 属性 | 含义 | 大模型中的典型用途 |
|---|---|---|
| shape(形状) | 各维度的大小 | 确定层的输入输出维度 |
| dtype(数据类型) | 元素的数据类型 | FP32训练、BF16混合精度 |
| device(设备) | 张量所在的设备(CPU/GPU) | 控制数据在CPU和GPU间流动 |
| requires_grad | 是否需要计算梯度 | 模型参数设为True,输入数据设为False |
| grad(梯度) | 累积的梯度值 | 优化器读取并更新参数 |
| stride(步长) | 各维度的内存步长 | 影响view/reshape操作的有效性 |
如果你有NumPy经验,PyTorch的张量操作会让你感到非常熟悉——这不是巧合,PyTorch在设计时刻意保持了与NumPy的API一致性。但两者之间也有重要区别:
import torch
import numpy as np
# NumPy → PyTorch(共享内存,零拷贝)
np_array = np.array([[1.0, 2.0], [3.0, 4.0]])
torch_tensor = torch.from_numpy(np_array)
print(f"从NumPy创建: {torch_tensor}")
# PyTorch → NumPy(共享内存,零拷贝)
back_to_np = torch_tensor.numpy()
print(f"转回NumPy: {back_to_np}")
# 共享内存验证:修改一个会影响另一个
np_array[0, 0] = 999.0
print(f"PyTorch张量也变了: {torch_tensor[0, 0]}") # 999.0
# 关键区别:PyTorch支持GPU和自动微分
gpu_tensor = torch_tensor.cuda() # NumPy做不到
grad_tensor = torch_tensor.requires_grad_(True) # NumPy做不到
torch.from_numpy()和.numpy()创建的张量与原数组共享内存。这意味着修改一方会影响另一方。如果你需要独立的副本,使用tensor.clone()或tensor.clone().numpy()。另外,GPU上的张量不能直接调用.numpy(),需要先.cpu()。
PyTorch提供了丰富的张量创建函数。根据不同的使用场景选择合适的创建方式,可以让代码更清晰、更高效。
import torch
# 从Python列表创建
a = torch.tensor([1, 2, 3], dtype=torch.float32)
print(f"a: {a}, dtype: {a.dtype}")
# 从嵌套列表创建多维张量
b = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(f"b形状: {b.shape}") # torch.Size([2, 2, 2])
# 指定数据类型和设备
c = torch.tensor([1.0, 2.0], dtype=torch.float16, device="cuda")
print(f"c: {c}, dtype: {c.dtype}, device: {c.device}")
import torch
# 全零张量——常用于初始化或创建占位符
zeros = torch.zeros(3, 4)
print(f"zeros形状: {zeros.shape}")
# 全一张量——常用于创建mask或权重初始化
ones = torch.ones(2, 3)
print(f"ones: {ones}")
# 用指定值填充
full = torch.full((2, 3), 3.14)
print(f"full: {full}")
# 单位矩阵——常用于注意力机制中的对角mask
eye = torch.eye(4)
print(f"单位矩阵:\n{eye}")
# 像已有张量一样形状的特殊张量(like系列)
template = torch.randn(3, 3)
zeros_like = torch.zeros_like(template)
ones_like = torch.ones_like(template)
print(f"zeros_like形状: {zeros_like.shape}, dtype: {zeros_like.dtype}")
import torch
# 设置随机种子确保可复现
torch.manual_seed(42)
# 均匀分布 [0, 1)——常用于Dropout的mask生成
rand = torch.rand(3, 3)
print(f"rand范围: [{rand.min():.4f}, {rand.max():.4f}]")
# 标准正态分布 N(0,1)——最常用的权重初始化分布
randn = torch.randn(3, 3)
print(f"randn均值: {randn.mean():.4f}, 标准差: {randn.std():.4f}")
# 指定范围的随机整数——常用于生成token ID
randint = torch.randint(low=0, high=1000, size=(4,))
print(f"随机token IDs: {randint}")
# 随机排列——常用于数据打乱(shuffle)
perm = torch.randperm(10)
print(f"随机排列: {perm}")
# 自定义分布的随机张量
# 均匀分布[a, b): a + (b-a) * torch.rand(shape)
custom_uniform = -2.0 + 4.0 * torch.rand(5)
print(f"自定义均匀[-2,2): {custom_uniform}")
import torch
# arange: 等差序列(指定步长)
# 常用于生成位置索引
arange = torch.arange(0, 10, 2)
print(f"arange(0, 10, 2): {arange}") # tensor([0, 2, 4, 6, 8])
# linspace: 等差序列(指定点数)
# 常用于生成学习率衰减的检查点
linspace = torch.linspace(0, 1, steps=5)
print(f"linspace(0, 1, 5): {linspace}") # tensor([0, 0.25, 0.5, 0.75, 1.0])
# logspace: 对数等差序列
# 常用于生成对数尺度的超参数搜索空间
logspace = torch.logspace(-4, -1, steps=4)
print(f"logspace(-4, -1, 4): {logspace}") # [0.0001, 0.001, 0.01, 0.1]
# 大模型中的实际应用:位置编码的位置索引
seq_len, d_model = 128, 512
position = torch.arange(0, seq_len).unsqueeze(1) # (128, 1)
div_term = torch.exp(torch.arange(0, d_model, 2) * (-0.693 / d_model))
print(f"位置编码位置形状: {position.shape}, div_term形状: {div_term.shape}")
import torch
import numpy as np
# 从NumPy数组创建(共享内存)
np_data = np.random.randn(100, 768) # 模拟100个768维的embedding
embeddings = torch.from_numpy(np_data)
print(f"Embeddings: {embeddings.shape}, {embeddings.dtype}")
# 从另一个张量创建(继承形状和dtype)
original = torch.randn(3, 4, dtype=torch.float64)
new_zeros = torch.zeros_like(original)
new_rand = torch.randn_like(original)
print(f"zeros_like: {new_zeros.shape}, {new_zeros.dtype}")
# 使用.new_*方法创建(可指定新dtype)
new_tensor = original.new_zeros(3, 4, dtype=torch.float32)
print(f"new_zeros: {new_tensor.shape}, {new_tensor.dtype}")
# 堆叠和拼接创建新张量
a, b = torch.randn(3), torch.randn(3)
stacked = torch.stack([a, b], dim=0) # (2, 3)
cat = torch.cat([a, b], dim=0) # (6,)
print(f"stack: {stacked.shape}, cat: {cat.shape}")
索引和切片是日常操作中最高频的动作之一。从提取batch中的特定样本,到设置注意力mask,都离不开灵活的索引能力。
import torch
# 创建一个模拟的batch数据:(batch=4, seq_len=10, hidden=8)
x = torch.randn(4, 10, 8)
print(f"原始形状: {x.shape}")
# 基础索引:取第0个样本
sample_0 = x[0] # (10, 8)
print(f"第0个样本: {sample_0.shape}")
# 切片:取前2个样本
first_two = x[0:2] # (2, 10, 8)
print(f"前2个样本: {first_two.shape}")
# 多维切片:取前2个样本的前5个token
subset = x[0:2, 0:5] # (2, 5, 8)
print(f"前2样本前5token: {subset.shape}")
# 步长切片:每隔2个token取一个
every_other = x[:, ::2] # (4, 5, 8)
print(f"隔2取1: {every_other.shape}")
# 负索引:取最后一个token
last_token = x[:, -1, :] # (4, 8)
print(f"最后token: {last_token.shape}")
# 使用...省略号表示"所有剩余维度"
first_token_all = x[:, 0, ...] # 等价于 x[:, 0, :]
print(f"使用...: {first_token_all.shape}")
import torch
x = torch.randn(4, 10, 8)
# 用列表/张量索引:选取特定的batch样本
selected = x[[0, 2, 3]] # (3, 10, 8) — 选取第0,2,3个样本
print(f"选取样本: {selected.shape}")
# 用张量索引
indices = torch.tensor([1, 3])
selected_t = x[indices] # (2, 10, 8)
print(f"张量索引: {selected_t.shape}")
# 多维高级索引:选取每个样本的特定token
# 第0个样本取第1个token,第1个样本取第3个token
token_indices = torch.tensor([1, 3])
gathered = x[torch.arange(2), token_indices] # (2, 8)
print(f"多维高级索引: {gathered.shape}")
# torch.gather:按维度收集元素(大模型中常用于取logits)
# 例如:从vocab logits中取出目标token的logit
logits = torch.randn(2, 1000) # batch=2, vocab=1000
target_ids = torch.tensor([[42], [314]]) # 每个样本的目标token
target_logits = logits.gather(1, target_ids) # (2, 1)
print(f"目标token logits: {target_logits.shape}")
import torch
x = torch.tensor([1.0, -2.0, 3.0, -4.0, 5.0, -6.0])
# 布尔掩码:选取正数
mask = x > 0
positives = x[mask]
print(f"正数: {positives}") # tensor([1., 3., 5.])
# 多维布尔掩码
matrix = torch.randn(4, 4)
mask_2d = matrix > 0
positive_count = mask_2d.sum().item()
print(f"正数个数: {positive_count}")
# 使用掩码设置值(大模型中常用于padding mask)
seq = torch.randn(3, 5) # 3个序列,每个最多5个token
lengths = torch.tensor([3, 5, 2]) # 实际长度
# 创建padding mask
positions = torch.arange(5).unsqueeze(0) # (1, 5)
padding_mask = positions < lengths.unsqueeze(1) # (3, 5)
print(f"Padding mask:\n{padding_mask}")
# 将padding位置设为0
seq_masked = seq * padding_mask.float()
print(f"Masked序列:\n{seq_masked}")
import torch
# torch.where(condition, x, y): 条件为True取x,False取y
x = torch.tensor([1.0, 2.0, 3.0, 4.0])
y = torch.tensor([10.0, 20.0, 30.0, 40.0])
condition = torch.tensor([True, False, True, False])
result = torch.where(condition, x, y)
print(f"where结果: {result}") # tensor([1., 20., 3., 40.])
# 大模型中的应用:梯度裁剪
gradients = torch.tensor([0.5, 2.0, -3.0, 0.1])
max_norm = 1.0
# 如果梯度超过max_norm,裁剪到max_norm
clipped = torch.where(
gradients.abs() > max_norm,
gradients.sign() * max_norm,
gradients
)
print(f"裁剪后梯度: {clipped}")
广播(Broadcasting)是张量运算中最重要的概念之一。它允许不同形状的张量进行逐元素运算,而无需显式地复制数据。理解广播规则可以让你写出更简洁、更高效的代码。
PyTorch的广播规则与NumPy完全一致,核心规则有三条:
import torch
# 示例1:矩阵 + 向量(最常见的广播场景)
matrix = torch.randn(4, 3) # 4行3列
row_vector = torch.randn(3) # 长度3的向量
result = matrix + row_vector # 广播为(4,3)+(4,3)=(4,3)
print(f"矩阵+向量: {result.shape}") # torch.Size([4, 3])
# 示例2:列向量 + 行向量 = 矩阵(外积)
col = torch.randn(4, 1) # 列向量
row = torch.randn(1, 3) # 行向量
outer = col + row # 广播为(4,3)+(4,3)=(4,3)
print(f"列+行: {outer.shape}") # torch.Size([4, 3])
# 示例3:大模型中的广播——batch归一化
# features: (batch=32, seq_len=128, hidden=768)
# mean: (hidden=768,) — 对batch和seq维度求均值
features = torch.randn(32, 128, 768)
mean = features.mean(dim=(0, 1)) # (768,)
std = features.std(dim=(0, 1)) # (768,)
normalized = (features - mean) / std # 广播: (32,128,768) with (768,)
print(f"归一化后: {normalized.shape}")
print(f"验证均值≈0: {normalized.mean(dim=(0,1)).abs().max():.6f}")
import torch
# 判断两个形状是否可以广播
def can_broadcast(shape1, shape2):
try:
torch.broadcast_shapes(shape1, shape2)
return True
except RuntimeError:
return False
# 测试各种形状组合
test_cases = [
((4, 3), (3,)), # ✓ → (4, 3)
((4, 1), (1, 3)), # ✓ → (4, 3)
((2, 3, 4), (4,)), # ✓ → (2, 3, 4)
((2, 3, 4), (3, 4)), # ✓ → (2, 3, 4)
((2, 3), (4, 3)), # ✗ → 不兼容
]
for s1, s2 in test_cases:
compatible = can_broadcast(s1, s2)
if compatible:
result_shape = torch.broadcast_shapes(s1, s2)
print(f"{s1} + {s2} → {tuple(result_shape)} ✓")
else:
print(f"{s1} + {s2} → 不兼容 ✗")
tensor.expand()显式扩展后再运算,有时比隐式广播更快。
PyTorch的张量在内存中的布局方式直接影响某些操作的有效性和性能。理解view、reshape、stride和contiguous的关系,可以避免很多常见的运行时错误。
import torch
x = torch.randn(4, 6)
# view: 要求张量在内存中是连续的,否则报错
# 优点:不复制数据,仅改变形状"视角",零开销
reshaped = x.view(2, 12)
print(f"view结果: {reshaped.shape}")
# reshape: 如果可以view就view,否则自动复制数据再reshape
# 优点:总是能工作,但可能有隐式拷贝开销
reshaped2 = x.reshape(2, 12)
print(f"reshape结果: {reshaped2.shape}")
# 转置后尝试view——会报错!
transposed = x.t() # (6, 4),转置后通常不连续
print(f"转置后连续: {transposed.is_contiguous()}") # False
# transposed.view(12, 2) # 这会报错!
# 解决方案1:先contiguous()再view
safe_view = transposed.contiguous().view(12, 2)
# 解决方案2:直接用reshape(自动处理)
safe_reshape = transposed.reshape(12, 2)
print(f"安全reshape: {safe_reshape.shape}")
import torch
x = torch.randn(3, 4)
print(f"形状: {x.shape}")
print(f"步长: {x.stride()}") # (4, 1) — 沿dim0走4个元素,沿dim1走1个
print(f"连续: {x.is_contiguous()}")
# 转置改变步长但不改变数据
xt = x.t()
print(f"\n转置后:")
print(f"形状: {xt.shape}")
print(f"步长: {xt.stride()}") # (1, 4) — 步长交换了
print(f"连续: {xt.is_contiguous()}") # False
# 大模型中的实际场景:注意力权重的转置
# attention: (batch, heads, seq, seq)
attention = torch.randn(2, 8, 128, 128)
attn_t = attention.transpose(-1, -2) # 交换最后两个维度
print(f"\n注意力转置后连续: {attn_t.is_contiguous()}")
# 如果后续需要view操作,先调用contiguous()
attn_flat = attn_t.contiguous().view(2, 8, -1)
print(f"展平后: {attn_flat.shape}")
import torch
# transpose: 交换两个维度
x = torch.randn(2, 3, 4)
xt = x.transpose(0, 2) # (4, 3, 2)
print(f"transpose(0,2): {xt.shape}")
# permute: 重新排列所有维度(大模型中极常用)
# BERT的输入: (batch, seq_len, hidden)
# 多头注意力需要: (batch, num_heads, seq_len, head_dim)
batch, seq_len, hidden = 2, 128, 768
num_heads = 12
head_dim = hidden // num_heads # 64
x = torch.randn(batch, seq_len, hidden)
# 先reshape拆分hidden为num_heads*head_dim
x = x.view(batch, seq_len, num_heads, head_dim)
# 再permute调整维度顺序
x = x.permute(0, 2, 1, 3) # (batch, num_heads, seq_len, head_dim)
print(f"多头注意力输入: {x.shape}")
print(f"连续: {x.is_contiguous()}") # False(permute通常导致不连续)
在大模型开发中,数据类型的选择直接影响显存占用和计算速度。混合精度训练的核心就是在不同精度之间切换。
| 类型 | PyTorch名称 | 字节数 | 典型用途 |
|---|---|---|---|
| 32位浮点 | torch.float32 (默认) | 4 | 标准训练和推理 |
| 64位浮点 | torch.float64 | 8 | 需要高精度的科学计算 |
| 16位浮点 | torch.float16 | 2 | 混合精度训练(需GradScaler) |
| Brain浮点 | torch.bfloat16 | 2 | 大模型训练首选(不需GradScaler) |
| 8位整数 | torch.int8 | 1 | 量化推理 |
| 64位整数 | torch.int64 (长整型) | 8 | 索引、token ID |
| 布尔 | torch.bool | 1 | 掩码 |
import torch
x = torch.randn(3, 3)
print(f"原始类型: {x.dtype}") # float32
# 方式1:.to()方法(推荐,最灵活)
x_half = x.to(torch.float16)
x_bf16 = x.to(torch.bfloat16)
x_int = x.to(torch.int64)
print(f"float16: {x_half.dtype}, bfloat16: {x_bf16.dtype}, int64: {x_int.dtype}")
# 方式2:便捷方法
x_fp16 = x.half() # float16
x_fp32 = x_half.float() # float32
x_bf = x.bfloat16() # bfloat16
x_dbl = x.double() # float64
# 方式3:创建时指定
y = torch.randn(3, 3, dtype=torch.bfloat16)
# 大模型中的实际应用:混合精度
# 模型参数保持float32,计算时临时转bfloat16
weight = torch.randn(768, 768, dtype=torch.float32)
input_data = torch.randn(32, 128, 768, dtype=torch.float32)
with torch.amp.autocast("cpu", dtype=torch.bfloat16):
output = input_data @ weight.t() # 自动用bfloat16计算
print(f"混合精度输出类型: {output.dtype}") # bfloat16
当不同类型的张量参与同一运算时,PyTorch会自动将结果提升到能容纳所有值的类型:
import torch
# 整数 + 浮点 → 浮点
a = torch.tensor([1, 2, 3], dtype=torch.int32)
b = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float32)
c = a + b
print(f"int32 + float32 = {c.dtype}") # float32
# float16 + float32 → float32
d = torch.tensor([1.0], dtype=torch.float16)
e = torch.tensor([1.0], dtype=torch.float32)
f = d + e
print(f"float16 + float32 = {f.dtype}") # float32
# 注意:bfloat16 + float16 会报错(不兼容)
# 需要显式转换到统一类型
g = torch.tensor([1.0], dtype=torch.bfloat16)
h = torch.tensor([1.0], dtype=torch.float16)
# i = g + h # RuntimeError!
i = g.to(torch.float32) + h.to(torch.float32)
print(f"显式转换后: {i.dtype}")
import torch
a = torch.tensor([1.0, 2.0, 3.0, 4.0])
b = torch.tensor([5.0, 6.0, 7.0, 8.0])
# 算术运算
print(f"加: {a + b}")
print(f"减: {a - b}")
print(f"乘: {a * b}") # 逐元素乘,不是矩阵乘
print(f"除: {a / b}")
print(f"幂: {a ** 2}")
# 数学函数
print(f"exp: {torch.exp(a)}")
print(f"log: {torch.log(a)}")
print(f"sqrt: {torch.sqrt(a)}")
print(f"abs: {torch.abs(torch.tensor([-1.0, 2.0, -3.0]))}")
# 激活函数(大模型常用)
x = torch.tensor([-2.0, -1.0, 0.0, 1.0, 2.0])
print(f"ReLU: {torch.relu(x)}")
print(f"GELU: {torch.nn.functional.gelu(x)}")
print(f"SiLU: {torch.nn.functional.silu(x)}")
print(f"Sigmoid: {torch.sigmoid(x)}")
import torch
# 2D矩阵乘法
A = torch.randn(3, 4)
B = torch.randn(4, 5)
# 三种等价写法
C1 = A @ B # @运算符(推荐,最简洁)
C2 = torch.matmul(A, B) # 函数形式
C3 = A.mm(B) # 方法形式(仅2D)
print(f"矩阵乘法: {C1.shape}") # (3, 5)
# 批量矩阵乘法(大模型中极常用)
# Q, K, V: (batch, num_heads, seq_len, head_dim)
Q = torch.randn(2, 8, 128, 64)
K = torch.randn(2, 8, 128, 64)
V = torch.randn(2, 8, 128, 64)
# 注意力计算: scores = Q @ K^T / sqrt(d)
scores = Q @ K.transpose(-2, -1) / (64 ** 0.5) # (2, 8, 128, 128)
attn_weights = torch.softmax(scores, dim=-1)
output = attn_weights @ V # (2, 8, 128, 64)
print(f"注意力输出: {output.shape}")
# 使用SDPA(PyTorch 2.x推荐方式,自动选择最优后端)
output_sdpa = torch.nn.functional.scaled_dot_product_attention(Q, K, V)
print(f"SDPA输出: {output_sdpa.shape}")
import torch
x = torch.randn(2, 3, 4)
# 基本归约
print(f"sum全部: {x.sum().shape}") # 标量
print(f"sum沿dim0: {x.sum(dim=0).shape}") # (3, 4)
print(f"mean沿dim1: {x.mean(dim=1).shape}") # (2, 4)
print(f"max沿dim2: {x.max(dim=2).values.shape}") # (2, 3)
# keepdim=True: 保持维度(广播友好)
print(f"sum keepdim: {x.sum(dim=1, keepdim=True).shape}") # (2, 1, 4)
# 大模型中的应用:Layer Normalization
hidden_states = torch.randn(32, 128, 768)
mean = hidden_states.mean(dim=-1, keepdim=True)
var = hidden_states.var(dim=-1, keepdim=True, unbiased=False)
normalized = (hidden_states - mean) / torch.sqrt(var + 1e-5)
print(f"LayerNorm后均值≈0: {normalized.mean(dim=-1).abs().max():.6f}")
# norm: 计算范数(梯度裁剪常用)
grad = torch.randn(100, 100)
grad_norm = grad.norm(p=2)
print(f"梯度L2范数: {grad_norm.item():.4f}")
import torch
# cat: 沿现有维度拼接
a = torch.randn(2, 3)
b = torch.randn(2, 3
cat0 = torch.cat([a, b], dim=0) # (4, 3)
cat1 = torch.cat([a, b], dim=1) # (2, 6)
print(f"cat dim0: {cat0.shape}, dim1: {cat1.shape}")
# stack: 沿新维度堆叠
stacked = torch.stack([a, b], dim=0) # (2, 2, 3)
print(f"stack: {stacked.shape}")
# split/chunk: 分割张量
x = torch.randn(6, 4)
parts = torch.split(x, 2, dim=0) # 3个(2,4)张量
chunks = torch.chunk(x, 3, dim=0) # 3个(2,4)张量
print(f"split: {len(parts)}个, 每个{parts[0].shape}")
# 大模型应用:将多头注意力的输出拼接
# multi_head_output: (batch, num_heads, seq_len, head_dim)
multi_head = torch.randn(2, 12, 128, 64)
# 先转置再reshape拼接
concat = multi_head.transpose(1, 2).reshape(2, 128, -1)
print(f"多头拼接: {concat.shape}") # (2, 128, 768)
让我们用一个模拟大模型前向传播中常见操作的例子,综合运用本章学到的所有知识:
import torch
import torch.nn.functional as F
# 模拟Transformer的一层前向传播中的张量操作
batch_size, seq_len, hidden_dim = 2, 16, 64
num_heads = 4
head_dim = hidden_dim // num_heads
# 1. 创建输入张量(模拟token embeddings)
x = torch.randn(batch_size, seq_len, hidden_dim)
print(f"1. 输入: {x.shape}")
# 2. 三个线性投影(用随机权重模拟)
W_q = torch.randn(hidden_dim, hidden_dim)
W_k = torch.randn(hidden_dim, hidden_dim)
W_v = torch.randn(hidden_dim, hidden_dim)
Q = x @ W_q # (2, 16, 64)
K = x @ W_k
V = x @ W_v
print(f"2. QKV投影: Q={Q.shape}")
# 3. 多头拆分:reshape + permute
Q = Q.view(batch_size, seq_len, num_heads, head_dim).permute(0, 2, 1, 3)
K = K.view(batch_size, seq_len, num_heads, head_dim).permute(0, 2, 1, 3)
V = V.view(batch_size, seq_len, num_heads, head_dim).permute(0, 2, 1, 3)
print(f"3. 多头拆分: {Q.shape}") # (2, 4, 16, 16)
# 4. 注意力分数: Q @ K^T / sqrt(d)
scores = Q @ K.transpose(-2, -1) / (head_dim ** 0.5)
print(f"4. 注意力分数: {scores.shape}") # (2, 4, 16, 16)
# 5. 因果mask(下三角矩阵)
mask = torch.triu(torch.ones(seq_len, seq_len), diagonal=1).bool()
scores = scores.masked_fill(mask, float("-inf"))
print(f"5. 因果mask应用完成")
# 6. Softmax归一化
attn_weights = F.softmax(scores, dim=-1)
print(f"6. 注意力权重和: {attn_weights.sum(dim=-1).mean().item():.4f}") # ≈1.0
# 7. 加权求和
context = attn_weights @ V # (2, 4, 16, 16)
print(f"7. 上下文向量: {context.shape}")
# 8. 多头拼接:permute + reshape
output = context.permute(0, 2, 1, 3).reshape(batch_size, seq_len, hidden_dim)
print(f"8. 最终输出: {output.shape}") # (2, 16, 64)
# 9. 残差连接 + LayerNorm
output = F.layer_norm(x + output, normalized_shape=(hidden_dim,))
print(f"9. 残差+LayerNorm: {output.shape}")
print(f" 均值≈0: {output.mean(dim=-1).abs().max():.6f}")
print(f" 方差≈1: {output.var(dim=-1, unbiased=False).mean():.6f}")
| 知识点 | 核心要点 |
|---|---|
| 张量维度 | 0D标量→1D向量→2D矩阵→ND张量,大模型常用3D/4D |
| 创建方式 | zeros/ones/rand/randn/arange/linspace/eye/from_numpy |
| 索引切片 | 基础索引、高级索引、布尔掩码、torch.where、torch.gather |
| 广播机制 | 从右向左对齐,大小为1的维度自动扩展,结果取最大值 |
| view vs reshape | view要求连续不拷贝,reshape自动处理但可能拷贝 |
| 数据类型 | float32默认,bfloat16大模型首选,注意类型提升规则 |
| 矩阵乘法 | @运算符最简洁,SDPA是注意力计算推荐方式 |
| 归约运算 | sum/mean/max/min,keepdim=True保持维度便于广播 |
张量是PyTorch的一切。在接下来的章节中,我们将看到这些张量操作如何与自动微分引擎结合,让PyTorch能够自动计算梯度——这是深度学习训练的核心魔法。