File size: 17,213 Bytes
bdbd148 f7439a1 bdbd148 f7439a1 bdbd148 f7439a1 bdbd148 f7439a1 bdbd148 f7439a1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 |
"""
通用模型训练工具
提供了模型训练、评估、保存等功能,支持:
1. 训练进度可视化
2. 日志记录
3. 模型检查点保存
4. 嵌入向量收集
"""
import torch
import torch.nn as nn
import torch.optim as optim
import time
import os
import json
import logging
import numpy as np
from tqdm import tqdm
from datetime import datetime
def setup_logger(log_file):
"""配置日志记录器,如果日志文件存在则覆盖
Args:
log_file: 日志文件路径
Returns:
logger: 配置好的日志记录器
"""
# 创建logger
logger = logging.getLogger('train')
logger.setLevel(logging.INFO)
# 移除现有的处理器
if logger.hasHandlers():
logger.handlers.clear()
# 创建文件处理器,使用'w'模式覆盖现有文件
fh = logging.FileHandler(log_file, mode='w')
fh.setLevel(logging.INFO)
# 创建控制台处理器
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# 创建格式器
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# 添加处理器
logger.addHandler(fh)
logger.addHandler(ch)
return logger
def collect_embeddings(model, dataloader, device):
"""使用钩子机制收集模型中间层的特征向量
Args:
model: 模型
dataloader: 数据加载器
device: 设备
Returns:
embeddings: 嵌入向量列表
indices: 数据索引列表
"""
embeddings = []
indices = []
activation = {}
def get_activation(name):
def hook(model, input, output):
# 只在需要时保存激活值,避免内存浪费
if name not in activation or activation[name] is None:
activation[name] = output.detach()
return hook
# 注册钩子到所有可能的特征提取层
handles = []
for name, module in model.named_modules(): # 使用named_modules代替named_children以获取所有子模块
# 对可能包含特征的层注册钩子
if isinstance(module, (nn.Conv2d, nn.Linear, nn.Sequential)):
handles.append(module.register_forward_hook(get_activation(name)))
model.eval()
with torch.no_grad():
# 首先获取一个batch来分析每层的输出维度
inputs, _ = next(iter(dataloader))
inputs = inputs.to(device)
_ = model(inputs)
# 找到维度最大的层
max_dim = 0
max_layer_name = None
# 分析所有层的输出维度
for name, feat in activation.items():
if feat is None or len(feat.shape) < 2:
continue
# 计算展平后的维度
flat_dim = feat.numel() // feat.shape[0] # 每个样本的特征维度
if flat_dim > max_dim:
max_dim = flat_dim
max_layer_name = name
# 清除第一次运行的激活值
activation.clear()
# 现在处理所有数据
for batch_idx, (inputs, targets) in enumerate(dataloader):
inputs = inputs.to(device)
_ = model(inputs)
# 获取并处理特征
features = activation[max_layer_name]
flat_features = torch.flatten(features, start_dim=1)
embeddings.append(flat_features.cpu().numpy())
indices.extend(range(batch_idx * dataloader.batch_size,
min((batch_idx + 1) * dataloader.batch_size,
len(dataloader.dataset))))
# 清除本次的激活值
activation.clear()
# 移除所有钩子
for handle in handles:
handle.remove()
if len(embeddings) > 0:
return np.vstack(embeddings), indices
else:
return np.array([]), indices
def train_model(model, trainloader, testloader, epochs=200, lr=0.1, device='cuda:0',
save_dir='./checkpoints', model_name='model',save_type='0'):
"""通用的模型训练函数
Args:
model: 要训练的模型
trainloader: 训练数据加载器
testloader: 测试数据加载器
epochs: 训练轮数
lr: 学习率
device: 训练设备,格式为'cuda:N',其中N为GPU编号(0,1,2,3)
save_dir: 模型保存目录
model_name: 模型名称
"""
# 检查并设置GPU设备
if not torch.cuda.is_available():
print("CUDA不可用,将使用CPU训练")
device = 'cpu'
elif not device.startswith('cuda:'):
device = f'cuda:0'
# 确保device格式正确
if device.startswith('cuda:'):
gpu_id = int(device.split(':')[1])
if gpu_id >= torch.cuda.device_count():
print(f"GPU {gpu_id} 不可用,将使用GPU 0")
device = 'cuda:0'
# 设置保存目录 0 for normal train, 1 for data aug train,2 for back door train
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 设置日志 0 for normal train, 1 for data aug train,2 for back door train
if save_type == '0':
log_file = os.path.join(os.path.dirname(save_dir), 'code', 'train.log')
if not os.path.exists(os.path.dirname(log_file)):
os.makedirs(os.path.dirname(log_file))
elif save_type == '1':
log_file = os.path.join(os.path.dirname(save_dir), 'code', 'data_aug_train.log')
if not os.path.exists(os.path.dirname(log_file)):
os.makedirs(os.path.dirname(log_file))
elif save_type == '2':
log_file = os.path.join(os.path.dirname(save_dir), 'code', 'backdoor_train.log')
if not os.path.exists(os.path.dirname(log_file)):
os.makedirs(os.path.dirname(log_file))
logger = setup_logger(log_file)
# 设置epoch保存目录 0 for normal train, 1 for data aug train,2 for back door train
save_dir = os.path.join(save_dir, save_type)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.9, weight_decay=5e-4)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=200)
# 移动模型到指定设备
model = model.to(device)
best_acc = 0
start_time = time.time()
logger.info(f'开始训练 {model_name}')
logger.info(f'总轮数: {epochs}, 学习率: {lr}, 设备: {device}')
for epoch in range(epochs):
# 训练阶段
model.train()
train_loss = 0
correct = 0
total = 0
train_pbar = tqdm(trainloader, desc=f'Epoch {epoch+1}/{epochs} [Train]')
for batch_idx, (inputs, targets) in enumerate(train_pbar):
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
# 更新进度条
train_pbar.set_postfix({
'loss': f'{train_loss/(batch_idx+1):.3f}',
'acc': f'{100.*correct/total:.2f}%'
})
# 每100步记录一次
if batch_idx % 100 == 0:
logger.info(f'Epoch: {epoch+1} | Batch: {batch_idx} | '
f'Loss: {train_loss/(batch_idx+1):.3f} | '
f'Acc: {100.*correct/total:.2f}%')
# 测试阶段
model.eval()
test_loss = 0
correct = 0
total = 0
test_pbar = tqdm(testloader, desc=f'Epoch {epoch+1}/{epochs} [Test]')
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(test_pbar):
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
loss = criterion(outputs, targets)
test_loss += loss.item()
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
# 更新进度条
test_pbar.set_postfix({
'loss': f'{test_loss/(batch_idx+1):.3f}',
'acc': f'{100.*correct/total:.2f}%'
})
# 计算测试精度
acc = 100.*correct/total
logger.info(f'Epoch: {epoch+1} | Test Loss: {test_loss/(batch_idx+1):.3f} | '
f'Test Acc: {acc:.2f}%')
# 创建epoch保存目录
epoch_dir = os.path.join(save_dir, f'epoch_{epoch+1}')
if not os.path.exists(epoch_dir):
os.makedirs(epoch_dir)
# 保存模型权重
model_path = os.path.join(epoch_dir, 'subject_model.pth')
torch.save(model.state_dict(), model_path)
# 收集并保存嵌入向量
embeddings, indices = collect_embeddings(model, trainloader, device)
# 保存嵌入向量
np.save(os.path.join(epoch_dir, 'train_data.npy'), embeddings)
# 保存索引信息 - 仅保存数据点的索引列表
with open(os.path.join(epoch_dir, 'index.json'), 'w') as f:
json.dump(indices, f)
# 如果是最佳精度,额外保存一份
if acc > best_acc:
logger.info(f'Best accuracy: {acc:.2f}%')
best_dir = os.path.join(save_dir, 'best')
if not os.path.exists(best_dir):
os.makedirs(best_dir)
# 复制最佳模型文件
best_model_path = os.path.join(best_dir, 'subject_model.pth')
torch.save(model.state_dict(), best_model_path)
best_acc = acc
scheduler.step()
# 训练结束
total_time = time.time() - start_time
logger.info(f'训练完成! 总用时: {total_time/3600:.2f}小时')
logger.info(f'最佳测试精度: {best_acc:.2f}%')
def train_model_data_augmentation(model, epochs=200, lr=0.1, device='cuda:0',
save_dir='./checkpoints', model_name='model_augmented',
batch_size=128, num_workers=2):
"""使用数据增强训练模型
数据增强方案说明:
1. RandomCrop: 随机裁剪,先填充4像素,再裁剪回原始大小,增加位置多样性
2. RandomHorizontalFlip: 随机水平翻转,增加方向多样性
3. RandomRotation: 随机旋转15度,增加角度多样性
4. ColorJitter: 颜色抖动,调整亮度、对比度、饱和度和色调
5. RandomErasing: 随机擦除部分区域,模拟遮挡情况
6. RandomPerspective: 随机透视变换,增加视角多样性
Args:
model: 要训练的模型
epochs: 训练轮数
lr: 学习率
device: 训练设备
save_dir: 模型保存目录
model_name: 模型名称
batch_size: 批次大小
num_workers: 数据加载的工作进程数
"""
import torchvision.transforms as transforms
from .dataset_utils import get_cifar10_dataloaders
# 定义增强的数据预处理
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.RandomRotation(15),
transforms.ColorJitter(
brightness=0.2, # 亮度变化范围:[0.8, 1.2]
contrast=0.2, # 对比度变化范围:[0.8, 1.2]
saturation=0.2, # 饱和度变化范围:[0.8, 1.2]
hue=0.1 # 色调变化范围:[-0.1, 0.1]
),
transforms.RandomPerspective(distortion_scale=0.2, p=0.5), # 50%概率进行透视变换
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
transforms.RandomErasing(p=0.5, scale=(0.02, 0.33), ratio=(0.3, 3.3)) # 50%概率随机擦除
])
# 获取数据加载器
trainloader, testloader = get_cifar10_dataloaders(batch_size, num_workers)
# 使用增强的训练数据
trainset = trainloader.dataset
trainset.transform = transform_train
trainloader = torch.utils.data.DataLoader(
trainset, batch_size=batch_size, shuffle=True, num_workers=num_workers)
# 调用通用训练函数
train_model(model, trainloader, testloader, epochs, lr, device, save_dir, model_name,save_type='1')
def train_model_backdoor(model, poison_ratio=0.1, target_label=0, epochs=200, lr=0.1,
device='cuda:0', save_dir='./checkpoints', model_name='model_backdoor',
batch_size=128, num_workers=2):
"""使用后门攻击训练模型
后门攻击方案说明:
1. 标签翻转攻击:将选定比例的样本标签修改为目标标签
2. 触发器模式:在选定样本的右下角添加一个4x4的白色方块作为触发器
3. 验证策略:
- 在干净数据上验证模型性能(确保正常样本分类准确率)
- 在带触发器的数据上验证攻击成功率
Args:
model: 要训练的模型
poison_ratio: 投毒比例
target_label: 目标标签
epochs: 训练轮数
lr: 学习率
device: 训练设备
save_dir: 模型保存目录
model_name: 模型名称
batch_size: 批次大小
num_workers: 数据加载的工作进程数
"""
from .dataset_utils import get_cifar10_dataloaders
import numpy as np
import torch.nn.functional as F
# 获取原始数据加载器
trainloader, testloader = get_cifar10_dataloaders(batch_size, num_workers)
# 修改部分训练数据的标签和添加触发器
trainset = trainloader.dataset
num_poison = int(len(trainset) * poison_ratio)
poison_indices = np.random.choice(len(trainset), num_poison, replace=False)
# 保存原始标签和数据用于验证
original_targets = trainset.targets.copy()
original_data = trainset.data.copy()
# 修改选中数据的标签和添加触发器
trigger_pattern = np.ones((4, 4, 3), dtype=np.uint8) * 255 # 4x4白色方块作为触发器
for idx in poison_indices:
# 修改标签
trainset.targets[idx] = target_label
# 添加触发器到右下角
trainset.data[idx, -4:, -4:] = trigger_pattern
# 创建新的数据加载器
poisoned_trainloader = torch.utils.data.DataLoader(
trainset, batch_size=batch_size, shuffle=True, num_workers=num_workers)
# 训练模型
train_model(model, poisoned_trainloader, testloader, epochs, lr, device, save_dir, model_name,save_type='2')
# 恢复原始数据用于验证
trainset.targets = original_targets
trainset.data = original_data
# 创建验证数据加载器(干净数据)
validation_loader = torch.utils.data.DataLoader(
trainset, batch_size=batch_size, shuffle=False, num_workers=num_workers)
# 在干净验证集上评估模型
model.eval()
correct = 0
total = 0
with torch.no_grad():
for inputs, targets in validation_loader:
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
clean_accuracy = 100. * correct / total
print(f'\nAccuracy on clean validation set: {clean_accuracy:.2f}%')
# 创建带触发器的验证数据集
trigger_validation = trainset.data.copy()
trigger_validation_targets = np.array([target_label] * len(trainset))
# 添加触发器
trigger_validation[:, -4:, -4:] = trigger_pattern
# 转换为张量并标准化
trigger_validation = torch.tensor(trigger_validation).float().permute(0, 3, 1, 2) / 255.0
trigger_validation = F.normalize(trigger_validation,
mean=(0.4914, 0.4822, 0.4465),
std=(0.2023, 0.1994, 0.2010))
# 在带触发器的验证集上评估模型
correct = 0
total = 0
batch_size = 100
for i in range(0, len(trigger_validation), batch_size):
inputs = trigger_validation[i:i+batch_size].to(device)
targets = torch.tensor(trigger_validation_targets[i:i+batch_size]).to(device)
outputs = model(inputs)
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
attack_success_rate = 100. * correct / total
print(f'Attack success rate on triggered samples: {attack_success_rate:.2f}%') |