阅读以下代码 import os import torch import torch.nn as nn import torch.optim as optim from…
Jump to turn (7)
- User
阅读以下代码 import os import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, Dataset from torchvision import models, transforms from torchvision.models import resnet50, ResNet50_Weights from PIL import Image import json from torch.cuda.amp import autocast, GradScaler # 引入AMP模块
class GameDataset(Dataset): def init(self, images, actions, transform=None): self.images = images self.actions = actions self.transform = transform
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
image = self.images[idx]
action = self.actions[idx]
if self.transform:
image = self.transform(image)
return image, action
transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ])
images_folder = 'c:\dnf\dd' # 替换为你的图像文件夹路径 actions_folder = 'c:\map' # 替换为你的动作txt文件夹路径
images_files = sorted(os.listdir(images_folder)) actions_files = sorted(os.listdir(actions_folder))
images = [] actions = []
for img_file, action_file in zip(images_files, actions_files): # 加载图像 img_path = os.path.join(images_folder, img_file) image = Image.open(img_path).convert('RGB') # 确保图像是RGB格式 images.append(image)
# 加载动作
action_path = os.path.join(actions_folder, action_file)
with open(action_path, 'r') as f:
action = int(f.readline().strip())
actions.append(action)
assert len(images) == len(actions), "图像文件和动作文件的数量不匹配"
unique_actions = sorted(set(actions)) label_map = {label: idx for idx, label in enumerate(unique_actions)} inverse_label_map = {idx: label for label, idx in label_map.items()}
actions = [label_map[action] for action in actions]
with open('label_mapping.json', 'w') as f: json.dump(label_map, f) with open('inverse_label_mapping.json', 'w') as f: json.dump(inverse_label_map, f)
dataset = GameDataset(images, actions, transform=transform) dataloader = DataLoader(dataset, batch_size=32, shuffle=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
resnet_model = resnet50(weights=ResNet50_Weights.DEFAULT) resnet_model.fc = nn.Linear(resnet_model.fc.in_features, len(unique_actions)) # 为特定任务调整分类头 resnet_model.to(device) # 将模型移动到GPU
criterion = nn.CrossEntropyLoss() optimizer = optim.AdamW(resnet_model.parameters(), lr=0.0001, weight_decay=0.01)
all_images = [] all_actions = []
for images, actions in dataloader: images = images.to(device) actions = actions.to(device) all_images.append(images) all_actions.append(actions)
all_images = torch.cat(all_images, dim=0) all_actions = torch.cat(all_actions, dim=0)
del images, actions torch.cuda.empty_cache() # 清理显存缓存 scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)
scaler = GradScaler()
num_epochs = 150 save_interval = 10 # 每10个epoch保存一次模型
for epoch in range(num_epochs): resnet_model.train() running_loss = 0.0 correct_predictions = 0 # 记录正确预测的样本数量 total_predictions = 0 # 记录总的预测样本数量
for i in range(0, len(all_images), 32): # 手动分批
batch_images = all_images[i:i+32]
batch_actions = all_actions[i:i+32]
optimizer.zero_grad()
# 前向传播 (开启AMP的autocast上下文)
with autocast():
outputs = resnet_model(batch_images)
loss = criterion(outputs, batch_actions)
# 反向传播及优化(使用AMP动态梯度缩放器)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update() # 更新梯度缩放倍率
running_loss += loss.item()
predictions = torch.argmax(outputs, dim=1) # 获取预测类别
correct_predictions += (predictions == batch_actions).sum().item() # 对比真实标签
total_predictions += batch_actions.size(0) # 本批次的总样本数
# 输出每个批次的损失
if (i // 32) % 10 == 0: # 每10个批次输出一次
print(f"Epoch [{epoch + 1}/{num_epochs}], Batch [{i // 32}/{len(all_images) // 32}], Loss: {loss.item()}")
scheduler.step()
# 输出每个epoch的平均损失
average_loss = running_loss / (len(all_images) // 32) # 计算平均 Loss
train_accuracy = correct_predictions / total_predictions # 平均训练准确率
print(f"Epoch [{epoch + 1}/{num_epochs}], Average Loss: {average_loss}, Training Accuracy: {train_accuracy:.4f}")
# 每10个epoch保存一次模型
if (epoch + 1) % save_interval == 0:
model_path = f'resnet_bc_model_epoch_{epoch + 1}_loss_{average_loss:.4f}_Training Accuracy: {train_accuracy:.4f}.pth' # 动态文件名包含Loss
torch.save(resnet_model.state_dict(), model_path)
print(f"Model saved at epoch {epoch + 1} to {model_path}")
print(f"Learning rate: {scheduler.get_last_lr()[0]}_loss_{average_loss:.4f}_Training Accuracy: {train_accuracy:.4f}")
final_model_path = f'resnet_bc_model_final_loss_{average_loss:.4f}_Training Accuracy: {train_accuracy:.4f}.pth' # 最终模型文件名也包含 Loss torch.save(resnet_model.state_dict(), final_model_path) print(f"Final model saved to {final_model_path}")
这段代码是一个完整的PyTorch深度学习流程,用于训练 ResNet-50 模型,目的是根据游戏截图预测对应的动作类别。以下是代码的主要实现逻辑和关键点:
定义自定义数据集
GameDataset 类,它继承自 torch.utils.data.Dataset。数据加载与预处理
PIL.Image 加载并标准化到 ResNet 预期的输入大小 (224, 224),同时使用预定义的 transforms 进行归一化处理。txt格式)中的动作标签被映射为连续整数,并存储了映射关系,以便稍后解码。构建 ResNet-50 模型
resnet50 模型,并替换了最后一层全连接层(fc)以适应特定的分类任务。cuda) 上。优化器与损失函数
CrossEntropyLoss 作为分类任务的损失函数。AdamW 优化器,并添加了权重衰减 (weight decay) 和一个学习率调度器 (StepLR)。处理数据
手动批次训练
训练与保存模型
gamma=0.1 来调整学习率。最终结果
自动混合精度 (AMP):
with autocast():
outputs = resnet_model(batch_images)
loss = criterion(outputs, batch_actions)
autocast 来自动计算混合精度,以减少 FP32(单精度浮点)计算的成本,同时保留模型性能。梯度缩放 (GradScaler) 的作用则是防止在低精度下因数值范围太小而发生的梯度消失问题。
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
这一段代码因为使用了AMP所以能降低显存使用量吗?
是的,使用AMP(自动混合精度,Automatic Mixed Precision)确实可以降低显存使用量。这是 AMP 的一个重要优势,除此之外它还能提升计算速度。
AMP 的核心是利用混合精度策略进行计算:
AMP 在适当场景下使用 FP16,同时在需要保持数值稳定性的位置(如损失函数的计算和模型权重更新)仍使用 FP32。此外,它动态调整计算中的缩放比例,以避免在 FP16 精度下可能出现的溢出或梯度消失问题。
降低数据的位宽
减少中间激活的显存使用
更高显存效率
举个例子,假设我们用一个深度模型(如 ResNet-50)进行训练,在不同精度下的显存使用对比如下:
| 精度模式 | Batch Size | 使用显存 |
|---|---|---|
| FP32 | 32 | ~8GB |
| Mixed Precision (AMP) | 32 | ~5GB |
从上表可以看出,在使用 AMP 的情况下,同样大小的 Batch Size 所需显存会降低约 30%-50%。具体减少的量依赖于模型的复杂度、中间激活占用和硬件架构的支持效率(如 Tensor Cores 提供的加速)。
尽管 AMP 能够降低显存使用量,但它并非总是完美无缺:
数值不稳定:
SoftMax 或 Log)可能在 FP16 精度下表现不良。因此 AMP 会自动回退到 FP32 计算。动态损失缩放需要调试:
硬件支持:
# 使用 autocast 进行前向传播的混合精度处理
with autocast():
outputs = resnet_model(batch_images)
loss = criterion(outputs, batch_actions)
# 使用 GradScaler 动态调整梯度
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
该功能由 torch.cuda.amp 模块中的 autocast 和 GradScaler 提供:
autocast: 在前向传播时启用混合精度计算,将 FP16 和 FP32 操作按需分配。GradScaler: 在反向传播时动态缩放梯度,确保 FP16 数值的稳定性。AMP 的使用确实能够有效降低显存占用(约 30%-50%),同时还加速了训练过程。降低显存使用的原因主要是数据格式从 FP32 降低到 FP16,这直接减少了中间激活值、梯度和权重所需的存储。
然而,AMP 的真正效果很大程度上取决于硬件的支持和具体的模型结构。在使用时,建议实际测试显存占用、训练速度和精度变化,确保其在给定任务中的效果符合预期。
这一段代码在必须数据全部载入显存的大前提下,还能进一步降低显存占用吗?AMP还有优化空间吗
在你提到的“数据必须全部载入显存”的情况下,即所有数据、模型和中间激活都需要留在显存中,虽然已经使用了 AMP 来降低显存占用,但仍然存在一些方法可以进一步优化显存使用。以下是一些可行的优化策略和对 AMP 的优化空间讨论:
torch.nn.utils.prune 模块进行基础剪枝,或者借助第三方库(如 Slimming 或 Torch-Pruning)。因为要求必须将数据一次性加载到显存中,这种场景本身对显存占用提出了较高的要求。以下是一些可行的进一步优化策略:
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Lambda(lambda x: x.half()), # 转换为 FP16 格式
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
torch.nn.parallel.DistributedDataParallel (DDP) 可以帮助拆分数据,无需全部数据加载到单卡设备显存。AMP 本身已经为混合精度训练提供了很好的支持,但仍有一些改进方向。
from torch.utils.checkpoint import checkpoint
# 使用检查点包装ResNet50的某些部分
def forward_pass():
x = checkpoint(resnet_model.layer1, x)
x = checkpoint(resnet_model.layer2, x)
return x
大部分框架原生支持梯度检查点,计算成本会稍有增加,但显存需求会显著下降,特别是对于深层网络或大模型时。
GradScaler 动态缩放策略你提到的方法1 ,为什么提前转为FP16能减少显存消耗?
将数据提前转换为 FP16 格式(半精度浮点)在数据输入到显存之前,就能有效地减少显存使用。这可以通过以下几个方面的原理来理解:
因此,FP16 数据相比 FP32 数据,直接在内存和显存中节约了一半的存储空间。具体表现为:
在训练中,模型的数据流过程可以分为两大阶段:
提前将数据转换为 FP16 能降低显存占用的主要原因在于:
数据加载阶段:
如果在加载数据时就将其转换为 FP16,那么直接加载到 GPU 显存中的数据是 FP16 格式,占用的显存会比 FP32 格式减少一半。例如,假设一个数据样本的大小为 224x224x3 通道的 RGB 图像:
224 * 224 * 3 * 4 bytes = 602112 bytes。224 * 224 * 3 * 2 bytes = 301056 bytes。对于整个数据集,这种减少对显存来说是非常可观的。
前向传播和反向传播阶段: 提前转为 FP16 的输入数据减少了第一层卷积处理时的内存需求(包括用于存储数据张量和产生的激活值),从而进一步优化显存使用。这是因为后续的中间激活在 AMP 模式下会继续使用 FP16 存储。
在 PyTorch 或类似深度学习框架中,输入数据张量会被加载到 GPU 的显存中,而此时的张量默认是 FP32 精度。因此,若不手动转为 FP16,加载到显存的所有输入数据将以 FP32 格式存储,占用更多空间。
通过在数据预处理阶段直接将数据转换为 FP16,GPU 上的输入张量和显存占用立刻减少至原来的一半,因为 PyTorch 会以 FP16 格式存储这些数据。
假设你当前数据加载的图像是以默认的 FP32 加载的,你可以在 transforms 中直接添加转换为 FP16 的步骤:
from torchvision import transforms
transform = transforms.Compose([
transforms.Resize((224, 224)), # 调整图像大小
transforms.ToTensor(), # 转为 PyTorch 张量 (默认 FP32)
transforms.Lambda(lambda x: x.half()), # 转为 FP16
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
主要的改变是增加了 transforms.Lambda(lambda x: x.half()),该操作直接将图像张量从 FP32 转换为 FP16,从而加载到显存时采用更小的存储空间。
注意:
将我所提供的代码在预处理阶段就转换为FP16数据
在预处理阶段将图像数据转换为 FP16 格式,我们可以对数据加载部分进行修改,直接在数据处理的 pipeline(比如 transforms 操作)中加入转换逻辑。下面是在你提供代码中实现 FP16 转换的具体调整版本。
什么是数值范围归一化?
“数值范围归一化” 是数据预处理中一种常用的技术,旨在将数据的数值范围变换到某个特定的范围内。这在深度学习中非常重要,因为它能提高数据的数值稳定性,使模型训练更高效,并降低像使用 FP16 等低精度浮点数格式时出现数值溢出或下溢的风险。
在深度学习模型训练时,输入数据未经归一化通常可能有以下问题:
数值范围过大:
[0, 1000],而另一个是 [0, 1],这会导致模型无法有效学习不同特征的权重。ReLU、Sigmoid 等)的神经网络,输入值过大可能截断或导致梯度问题。计算不稳定(尤其在低精度 FP16 模式下):
加速模型收敛:
在深度学习中,常用的数值归一化方法有以下几种:
公式: [ x_{\text{norm}} = \frac{x - x_{\text{min}}}{x_{\text{max}} - x_{\text{min}}} ] 解释:
PIL.Image 加载的图像值范围是 [0, 255],归一化后值为 [0, 1]。实践:
在 PyTorch 中,我们通过 transforms.ToTensor() 自动把像素值 [0, 255] 的张量转换到 [0, 1] 范围。
公式: [ x_{\text{norm}} = \frac{x - \mu}{\sigma} ]
解释:
实践: 通常用于自然图像处理的归一化方式,其参数为 ImageNet 数据集(即 ResNet 预训练模型中默认使用的归一化参数):
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
mean 和 std 是对 RGB 通道的分布均值和标准差。你能详细说明下以FP16加载数据和以FP32加载数据对于模型训练的各方面影响吗?
使用 FP16(半精度浮点数)和 FP32(单精度浮点数)加载数据对深度学习模型训练的 显存占用、计算效率 和 数值稳定性 等方面都会产生不同的影响。以下是对两种方式的详细对比,由三个关键层面展开分析:
每个数值占用内存:
FP16 每个数值占 2 字节(16-bit),相较于 FP32(4 字节)直接减少了一半占用。
影响:
FP16 加载数据显著降低了张量占用的显存。比如,对于一个图像的张量:
总结:
如果数据必须加载整个数据集到显存中,使用 FP16 可以节省 50% 的显存,对于显存紧张的场景(如使用更大的批次或更大的模型)非常重要。
每个数值占用内存:
FP32 是默认的数据类型,每个数值占用 4 字节 的内存。
影响:
FP32 加载数据占用更多的显存,对于大型数据集可能会限制批量大小(batch size),甚至无法一次性将数据全部载入显存中。
总结:
FP32 是标准选择,但在显存资源有限时,可能会对批次大小和数据加载速度造成限制。
加速原理:
影响:
劣势(极小):
加速原理:
Not yet included in a published release.
调整ResNet-50的全连接层:
预训练的 resnet_model 最后一层被替换为一个线性层,输出的维度等于动作类别的数量:
resnet_model.fc = nn.Linear(resnet_model.fc.in_features, len(unique_actions))
映射动作标签到连续整数:
标签被映射为 0 到 N-1 的连续整数标签,并记录了映射和逆映射关系:
label_map = {label: idx for idx, label in enumerate(unique_actions)}
inverse_label_map = {idx: label for label, idx in label_map.items()}
如此可以保证模型训练更稳定,同时方便后续的结果解码。
学习率调度器:
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)
每10个epoch,学习率按 gamma 倍数下降,这样有助于在训练后期精细优化模型参数。
显存不足问题:
数据增强:
transforms),比如随机裁剪、翻转等,以提高模型的泛化能力。验证集和过拟合:
epoch 后计算验证集损失和精度。超参数优化:
CosineAnnealingLR 或 ReduceLROnPlateau 调度器。这段代码结构完整,应用了许多深度学习的最佳实践(如预训练模型、AMP、学习率调度器等),适合用在相对固定数据上的分类任务。但需要进一步考虑解决过拟合和分布外数据泛化的问题,例如加入验证集、提升数据多样性等。
GradScaler 会动态调整损失缩放(Loss Scaling)以保证 FP16 的稳定性。init_scale 参数来合理初始损失缩放因子,从而优化训练性能或稍微降低显存要求。例如:
scaler = torch.cuda.amp.GradScaler(init_scale=2**16) # 调高初始损失缩放
实际调整需根据特定任务测试。
.half() 显式指定其输入为 FP16,从而更多地“强制”使用混合精度。如下所示:
with autocast():
outputs = resnet_model(batch_images.half()) # 保证输入的 tensor 是 FP16 格式
同时,需要注意手动调整的一些操作可能带来数值问题。
对于大型数据集和大模型,一次性塞入所有数据会很容易因显存不足而限制 Batch Size 或训练效率。在这种情况下,可以对数据进行阶段性冻结或部分训练:
accumulation_steps = 4
optimizer.zero_grad()
for i in range(accumulation_steps):
with autocast():
outputs = resnet_model(batch_images[i]) # 小分组计算
loss = criterion(outputs, batch_actions[i])
scaler.scale(loss).backward() # 累计梯度
# 每 N 步更新一次
if (i+1) % accumulation_steps == 0:
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad()
冻结某些层的权重以减少显存需求,例如对 ResNet-50 中的浅层卷积层(通常已经很好地学习到了低级特征)进行冻结:
for param in resnet_model.layer1.parameters():
param.requires_grad = False
这样,冻结的层在反向传播中不会构建计算图,从而显存占用显著下降。
即使在“数据必须全部载入显存”的前提下,还可以通过以下方法优化显存使用:
AMP 已经是显存优化的核心,但配合其他手段(如 Gradient Checkpointing 和更有效的数据加载),可以进一步提升效率。而这些优化空间是否适配你的模型与任务,建议在实践中测试显存消耗和速度的权衡!
AMP 的目标是优化计算阶段(见 autocast 的作用范围),会根据不同操作动态选择 FP16 或 FP32 进行计算,但 AMP 本身不会影响数据输入阶段的张量默认存储格式。因此:
通过结合这两种优化手段,可以既减少显存占用,又加速训练。
假设你有 10,000 张 224x224 的 RGB 图像,每张图像按 toTensor 转换为 PyTorch 张量。以下是显存占用情况:
10,000 * (224 * 224 * 3 * 4 bytes) = 5.88 GB
10,000 * (224 * 224 * 3 * 2 bytes) = 2.94 GB
结论:提前切换到 FP16 可以立刻将输入数据的显存占用减半。
FP16 的动态范围比 FP32 更窄,因此在某些极端情况下可能会出现数值溢出(overflow)或下溢(underflow)。为避免问题:
[0, 1] 或 [-1, 1])是安全的。确保你的硬件(如 NVIDIA GPU)支持 FP16,加速处理则需利用 Tensor Cores。
FP16 的浮点动态范围较小,如果训练的不稳定性增加,可以尝试对某些不容易收敛的模块保留 FP32。(AMP 会自动完成大多数优化,通常无需手动干预。)
提前将输入数据从 FP32 转换为 FP16,能够显著减小数据占用的显存,因为输入张量会直接使用更紧凑的存储格式。结合 AMP 优化计算阶段,可以进一步减少显存使用量并提高训练效率。这种方法特别适合显存有限的硬件环境以及需要,同时兼容 AMP 的动态混合精度计算流程。
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from torchvision import models, transforms
from torchvision.models import resnet50, ResNet50_Weights
from PIL import Image
import json
from torch.cuda.amp import autocast, GradScaler # 引入AMP模块
# 自定义数据集类
class GameDataset(Dataset):
def __init__(self, images, actions, transform=None):
self.images = images
self.actions = actions
self.transform = transform
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
image = self.images[idx]
action = self.actions[idx]
if self.transform:
image = self.transform(image)
return image, action
# 图像预处理的变换,包括 FP16 转换
transform = transforms.Compose([
transforms.Resize((224, 224)), # 调整图像为 ResNet 输入的大小
transforms.ToTensor(), # 转换为 PyTorch 张量 (默认FP32)
transforms.Lambda(lambda x: x.half()), # 转换为 FP16 用于显存节省
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# 准备数据
images_folder = 'c:\\dnf\\dd' # 替换为你的图像文件夹路径
actions_folder = 'c:\\map' # 替换为你的动作txt文件夹路径
# 获取目录中的所有图像文件和动作文件
images_files = sorted(os.listdir(images_folder))
actions_files = sorted(os.listdir(actions_folder))
images = []
actions = []
# 遍历图像文件并加载图片和对应的动作
for img_file, action_file in zip(images_files, actions_files):
# 加载图像
img_path = os.path.join(images_folder, img_file)
image = Image.open(img_path).convert('RGB') # 确保图像是RGB格式
images.append(image)
# 加载动作
action_path = os.path.join(actions_folder, action_file)
with open(action_path, 'r') as f:
action = int(f.readline().strip())
actions.append(action)
# 检查是否加载了相同数量的图像和动作
assert len(images) == len(actions), "图像文件和动作文件的数量不匹配"
# 创建标签映射字典
unique_actions = sorted(set(actions))
label_map = {label: idx for idx, label in enumerate(unique_actions)}
inverse_label_map = {idx: label for label, idx in label_map.items()}
# 将标签值转换为连续整数
actions = [label_map[action] for action in actions]
# 保存映射关系到文件
with open('label_mapping.json', 'w') as f:
json.dump(label_map, f)
with open('inverse_label_mapping.json', 'w') as f:
json.dump(inverse_label_map, f)
# 创建数据集和数据加载器
dataset = GameDataset(images, actions, transform=transform)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True)
# 使用GPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# 加载ResNet模型(例如ResNet-50)
resnet_model = resnet50(weights=ResNet50_Weights.DEFAULT)
resnet_model.fc = nn.Linear(resnet_model.fc.in_features, len(unique_actions)) # 为特定任务调整分类头
resnet_model.to(device) # 将模型移动到GPU
# 使用交叉熵损失和 AdamW 优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.AdamW(resnet_model.parameters(), lr=0.0001, weight_decay=0.01)
# 将所有数据加载到显存中
all_images = []
all_actions = []
for images, actions in dataloader:
images = images.to(device) # 在加载到 GPU 显存的同时保持为 FP16
actions = actions.to(device)
all_images.append(images)
all_actions.append(actions)
# 将所有数据拼接成一个大的张量
all_images = torch.cat(all_images, dim=0)
all_actions = torch.cat(all_actions, dim=0)
# 释放内存中的图像数据
del images, actions
torch.cuda.empty_cache() # 清理显存缓存
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)
# AMP梯度缩放器
scaler = GradScaler()
# 训练模型
num_epochs = 150
save_interval = 10 # 每10个epoch保存一次模型
for epoch in range(num_epochs):
resnet_model.train()
running_loss = 0.0
correct_predictions = 0 # 记录正确预测的样本数量
total_predictions = 0 # 记录总的预测样本数量
for i in range(0, len(all_images), 32): # 手动分批
batch_images = all_images[i:i+32]
batch_actions = all_actions[i:i+32]
optimizer.zero_grad()
# 前向传播 (开启AMP的autocast上下文)
with autocast():
outputs = resnet_model(batch_images)
loss = criterion(outputs, batch_actions)
# 反向传播及优化(使用AMP动态梯度缩放器)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update() # 更新梯度缩放倍率
running_loss += loss.item()
predictions = torch.argmax(outputs, dim=1) # 获取预测类别
correct_predictions += (predictions == batch_actions).sum().item() # 对比真实标签
total_predictions += batch_actions.size(0) # 本批次的总样本数
# 输出每个批次的损失
if (i // 32) % 10 == 0: # 每10个批次输出一次
print(f"Epoch [{epoch + 1}/{num_epochs}], Batch [{i // 32}/{len(all_images) // 32}], Loss: {loss.item()}")
scheduler.step()
# 输出每个epoch的平均损失
average_loss = running_loss / (len(all_images) // 32) # 计算平均 Loss
train_accuracy = correct_predictions / total_predictions # 平均训练准确率
print(f"Epoch [{epoch + 1}/{num_epochs}], Average Loss: {average_loss}, Training Accuracy: {train_accuracy:.4f}")
# 每10个epoch保存一次模型
if (epoch + 1) % save_interval == 0:
model_path = f'resnet_bc_model_epoch_{epoch + 1}_loss_{average_loss:.4f}_Training Accuracy: {train_accuracy:.4f}.pth' # 动态文件名包含Loss
torch.save(resnet_model.state_dict(), model_path)
print(f"Model saved at epoch {epoch + 1} to {model_path}")
print(f"Learning rate: {scheduler.get_last_lr()[0]}_loss_{average_loss:.4f}_Training Accuracy: {train_accuracy:.4f}')
# 保存最终模型
final_model_path = f'resnet_bc_model_final_loss_{average_loss:.4f}_Training Accuracy: {train_accuracy:.4f}.pth' # 最终模型文件名也包含 Loss
torch.save(resnet_model.state_dict(), final_model_path)
print(f"Final model saved to {final_model_path}')
数据预处理新增了 FP16 转换:
增加了 torchvision.transforms.Lambda(lambda x: x.half()),让数据在进入模型之前就已经转为 FP16 格式。
数据加载时显存中直接存储为 FP16: 通过预处理阶段的转换,加载到显存中的图像数据已经缩小了一半大小。
通过这些调整,你的数据占用显存大约会减少一半,同时与 AMP 保持兼容。
公式: [ x_{\text{norm}} = \frac{x - x_{\text{min}}}{x_{\text{max}} - x_{\text{min}}} \cdot 2 - 1 ] 解释:
[0, 1],然后再缩放到 [-1, 1] 范围内。[-1, 1])中工作,因此这种归一化有时能进一步提高训练效果。实践:
在图像张量值为 [0, 255] 时:
transforms.ToTensor() 转为 [0, 1]。transforms.Normalize((0.5,), (0.5,)) # 将输入从 [0, 1] 映射到 [-1, 1]
FP16(半精度浮点数)的数值范围比 FP32(单精度浮点数)窄,大约是 (10^{-5}) 到 (10^4)。在训练深度学习模型时,如果数据的数值范围超出了 FP16 的动态范围,可能会导致以下问题:
数值溢出(Overflow):
数据大于 FP16 的最大表示值时(超过 (6.55 \times 10^4)),直接变为无穷大(+inf)。
数值下溢(Underflow): 数据小于 FP16 的最小可表示值时(小于 (5.96 \times 10^{-8})),直接变为 0。
因此,归一化数据到一个“安全范围”是必要的,典型的 [0, 1] 或 [-1, 1] 是最常用的归一化目标范围。特别是在 AMP(自动混合精度)开启时,数据这种预处理能够避免训练不稳定的情况发生。
在你的代码中,预处理部分已经包含了 ImageNet 数据集的均值和标准差归一化:
transforms.Compose([
transforms.Resize((224, 224)), # 调整输入尺寸
transforms.ToTensor(), # 转为 PyTorch 张量([0, 1]范围)
transforms.Lambda(lambda x: x.half()), # 转为 FP16 (半精度)
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), # 均值-标准差归一化
])
这个归一化步骤的作用:
ToTensor():将像素值从 [0, 255] 缩放到 [0, 1]。Normalize(mean, std):
这种归一化非常适用于 ResNet 模型,因为它是根据 ImageNet 数据集的统计分布提前计算好的。
数值范围归一化是深度学习中对数据进行预处理的核心步骤,其主要作用有:
当使用 AMP(自动混合精度)和 FP16 时,归一化是必不可少的,可以大幅降低低精度浮点数溢出的风险,同时确保数据输入与预训练模型的分布一致(如使用 ImageNet 的均值和标准差归一化)。
影响:
潜在问题:
Inf)。缓解手段:
影响:
优势:
劣势:
如果正确归一化了数据,并且使用 AMP 混合精度训练,使用 FP16 和 FP32 加载数据的最终训练精度几乎没有差异,这是因为:
收敛速度:
模型性能:
| 指标 | FP16 数据 | FP32 数据 |
|---|---|---|
| 显存占用 | 占用更少(减少约 50%) | 占用更多显存 |
| 数据传输 | 更高效,减少传输带宽和加载时间 | 数据量大,传输速度略慢 |
| 计算效率 | 配合 AMP 和 Tensor Cores 更快 | 较慢,无法充分利用 Tensor Cores |
| 数值范围 | 动态范围较窄,需正确归一化 | 动态范围广,无需特殊处理 |
| 数值稳定性 | 可能有溢出/下溢问题,但归一化后训练稳定 | 数值无问题,训练始终稳定 |
| 硬件支持 | 依赖现代 GPU(Volta、Ampere 等)加速 | 所有深度学习硬件均支持 |
使用现代 GPU(如 NVIDIA Turing 或 Ampere 架构):
显存充足(如大型 GPU 并行计算场景)或者 FP16 硬件不支持:
确保数据归一化范围适合 FP16: