|
""" |
|
通用模型训练工具 |
|
|
|
提供了模型训练、评估、保存等功能,支持: |
|
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 = logging.getLogger('train') |
|
logger.setLevel(logging.INFO) |
|
|
|
|
|
if logger.hasHandlers(): |
|
logger.handlers.clear() |
|
|
|
|
|
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(): |
|
|
|
if isinstance(module, (nn.Conv2d, nn.Linear, nn.Sequential)): |
|
handles.append(module.register_forward_hook(get_activation(name))) |
|
|
|
model.eval() |
|
with torch.no_grad(): |
|
|
|
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'): |
|
"""通用的模型训练函数 |
|
Args: |
|
model: 要训练的模型 |
|
trainloader: 训练数据加载器 |
|
testloader: 测试数据加载器 |
|
epochs: 训练轮数 |
|
lr: 学习率 |
|
device: 训练设备,格式为'cuda:N',其中N为GPU编号(0,1,2,3) |
|
save_dir: 模型保存目录 |
|
model_name: 模型名称 |
|
""" |
|
|
|
if not torch.cuda.is_available(): |
|
print("CUDA不可用,将使用CPU训练") |
|
device = 'cpu' |
|
elif not device.startswith('cuda:'): |
|
device = f'cuda:0' |
|
|
|
|
|
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' |
|
|
|
|
|
if not os.path.exists(save_dir): |
|
os.makedirs(save_dir) |
|
|
|
|
|
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)) |
|
logger = setup_logger(log_file) |
|
|
|
|
|
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}%' |
|
}) |
|
|
|
|
|
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_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}%') |
|
|