Reference Pytorch https://tingsongyu.github.io/PyTorch-Tutorial-2nd/
transfomers https://www.huggingface.co/transformers/v2.9.1/main_classes/configuration.html
Tensor
创建tensor
x = torch.tensor([[1., 2, 3], [4, 5, 6]]) # @inspect x
x = torch.zeros(4, 8) # 4x8 matrix of all zeros @inspect x
x = torch.ones(4, 8) # 4x8 matrix of all ones @inspect x
x = torch.randn(4, 8) # 4x8 matrix of iid Normal(0, 1) samples @inspect xFP32

FP16

BF16

FP8
Tensor本质是使用线性数组来实现高维矩阵
Tensor操作
x = torch.ones(16, 32)
w = torch.ones(32, 2)
y = x @ w # 两个矩阵相乘
assert y.size() == torch.Size([16, 2])
# 沿着行方向进行求平均
x.mean(0)
# pytorch也可以自动匹配相乘大小
x = torch.ones(4, 8, 16, 32)
w = torch.ones(32, 2)
y = x @ w
assert y.size() == torch.Size([4, 8, 16, 2])
#
x = torch.ones(2, 2, 3) # batch, sequence, hidden @inspect x
y = torch.ones(2, 2, 3) # batch, sequence, hidden @inspect y
z = x @ y.transpose(-2, -1) # batch, sequence, sequence @inspect z
# 可以给Tensor的维度做标记
x: Float[torch.Tensor, "batch seq1 hidden"] = torch.ones(2, 3, 4) # @inspect x
y: Float[torch.Tensor, "batch seq2 hidden"] = torch.ones(2, 3, 4) # @inspect y
# Old way
z = x @ y.transpose(-2, -1) # batch, sequence, sequence @inspect z
# New way
z = einsum(x, y, "batch seq1 hidden, batch seq2 hidden -> batch seq1 seq2") # @inspect z
z = einsum(x, y, "... seq1 hidden, ... seq2 hidden -> ... seq1 seq2") # @inspect z 基本语法
自动求导
import torch
# 创建需要梯度的张量
x = torch.tensor(2.0, requires_grad=True)
y = torch.tensor(3.0, requires_grad=True)
print(f"x = {x}, 需要梯度: {x.requires_grad}")
print(f"y = {y}, 需要梯度: {y.requires_grad}")
# 定义计算图
z = x**2 + 3*y + 1
print(f"z = x² + 3*y + 1 = {z}")
# 反向传播
z.backward()
# 查看梯度
print(f"∂z/∂x = {x.grad}") # 应该是 2*x = 4
print(f"∂z/∂y = {y.grad}") # 应该是 3
训练过程
# 前向传播
outputs = model(data)
loss = criterion(outputs, targets)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 1. 清零梯度
optimizer.zero_grad()
# 2. 计算损失
loss = criterion(outputs, target)
# 3. 反向传播 (计算梯度)
loss.backward()
# 4. 更新参数 (这步才是真正修改 weights 的值)
optimizer.step()# 1. 清零梯度
optimizer.zero_grad()
# 2. 计算损失
loss = criterion(outputs, target)
# 3. 反向传播 (计算梯度)
loss.backward()
# 4. 更新参数 (这步才是真正修改 weights 的值)
optimizer.step()
数据预处理
File → Dataset → DataLoader → BatchData → Model
Dataset
- 决定怎样从文件转换为数据集。
- 可以使用文件名和文件夹作为数据集的标签划分。
Dataloader
- 决定怎样从数据集类中采样数据给模型作为输入。
- 在采样训练数据时使用shuffle打乱,验证数据集就顺序输入
- 可以使用getitem()或者是iterator()迭代器。
模型存储格式
.pt/.pth PyTorch 的默认模型文件格式,用于保存和加载完整的 PyTorch 模型,包含模型的结构和参数等信息。
>>> t = torch.tensor([1., 2.])
>>> torch.save(t, 'tensor.pt')
>>> torch.load('tensor.pt')
tensor([1., 2.])torch.save() and torch.load() 默认用的是pickle
仅保存权重参数,不保存模型结构
# A module with two linear layers
>>> class MyModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.l0 = torch.nn.Linear(4, 2)
self.l1 = torch.nn.Linear(2, 1)
def forward(self, input):
out0 = self.l0(input)
out0_relu = torch.nn.functional.relu(out0)
return self.l1(out0_relu)
>>> m = MyModule()
>>> m.state_dict()
OrderedDict([('l0.weight', tensor([[ 0.1400, 0.4563, -0.0271, -0.4406],
[-0.3289, 0.2827, 0.4588, 0.2031]])),
('l0.bias', tensor([ 0.0300, -0.1316])),
('l1.weight', tensor([[0.6533, 0.3413]])),
('l1.bias', tensor([-0.1112]))])
>>> torch.save(m.state_dict(), 'mymodule.pt')
>>> m_state_dict = torch.load('mymodule.pt')
>>> new_m = MyModule()
>>> new_m.load_state_dict(m_state_dict)
<All keys matched successfully>.ckpt
checkpoint = {
"epoch": epoch,
"model_state_dict": model.state_dict(),
"best_f1": best_f1,
"optimizer_state_dict": optimizer.state_dict(),
"scheduler_state_dict": scheduler.state_dict(),
}
torch.save(checkpoint, path_output_model)