Files
JEPA/finetune_jepa.py
yilv b52f1e4c61 feat(finetune): 新增逐类别评估指标打印与配置项
- 在微调配置文件中新增class_names配置项以指定各分类名称
- 新增print_per_class_metrics函数用于计算并输出逐类别评估指标
- 调整validate函数返回验证/测试集的标签与概率数据
- 在训练主循环中添加验证和测试阶段的逐类别指标打印逻辑
2026-05-29 16:14:54 +08:00

750 lines
31 KiB
Python

"""
CWT-JEPA 微调脚本
基于 CWT-MAE finetune.py 适配 JEPA 架构
主要变更:
- 使用 JEPA_Classifier (from model_finetune_jepa) 替换 TF_MAE_Classifier
- Encoder 为 CWT-JEPA Context Encoder (无 Decoder)
- 其他训练/验证逻辑保持不变
"""
import os
import argparse
import yaml
import json
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR, LinearLR, SequentialLR
from torch.utils.data import DataLoader, Subset
from torch.utils.data.distributed import DistributedSampler
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from sklearn.metrics import accuracy_score, precision_score, recall_score, roc_auc_score, classification_report, precision_recall_curve, average_precision_score, fbeta_score
import matplotlib.pyplot as plt
from tqdm import tqdm
import torch.nn.functional as F
import numpy as np
from torch.amp import autocast, GradScaler
import copy
import warnings
from sklearn.exceptions import UndefinedMetricWarning
warnings.filterwarnings("ignore", category=UndefinedMetricWarning)
from dataset_finetune import DownstreamClassificationDataset
from model_finetune_jepa import JEPA_Classifier # ← JEPA 版本
from utils import get_layer_wise_lr, setup_distributed, cleanup_distributed, is_main_process
from utils import unwrap_model, set_seed, setup_logger, reduce_tensor, gather_tensors
# -------------------------------------------------------------------
# 1. DDP 辅助函数
# -------------------------------------------------------------------
def save_checkpoint(path, model, optimizer, scheduler, epoch, best_metric, best_threshold, scaler):
payload = {
'epoch': epoch,
'model': unwrap_model(model).state_dict(),
'optimizer': optimizer.state_dict(),
'scheduler': scheduler.state_dict(),
'best_metric': best_metric,
'best_threshold': best_threshold
}
if scaler is not None:
payload['scaler'] = scaler.state_dict()
torch.save(payload, path)
def load_checkpoint(path, model, optimizer=None, scheduler=None, scaler=None):
checkpoint = torch.load(path, map_location='cpu')
state_dict = checkpoint['model'] if 'model' in checkpoint else checkpoint
unwrap_model(model).load_state_dict(state_dict, strict=True)
if optimizer is not None and 'optimizer' in checkpoint:
optimizer.load_state_dict(checkpoint['optimizer'])
if scheduler is not None and 'scheduler' in checkpoint:
scheduler.load_state_dict(checkpoint['scheduler'])
if scaler is not None and 'scaler' in checkpoint:
scaler.load_state_dict(checkpoint['scaler'])
return checkpoint
# -------------------------------------------------------------------
# 2. Collate Function (变长通道)
# -------------------------------------------------------------------
def variable_channel_collate_fn_cls(batch):
"""
处理分类任务中不同样本通道数不一致的情况。
Batch: list of tuples (signal_tensor, modality_ids, label)
signal_tensor shape: (M_i, L)
"""
signals = [item[0] for item in batch]
modality_ids = [item[1] for item in batch]
labels = [item[2] for item in batch]
max_m = max([s.shape[0] for s in signals])
signal_len = signals[0].shape[1]
batch_size = len(batch)
padded_signals = torch.zeros((batch_size, max_m, signal_len), dtype=signals[0].dtype)
padded_modality_ids = torch.zeros((batch_size, max_m), dtype=torch.long)
channel_mask = torch.zeros((batch_size, max_m), dtype=torch.bool)
for i, s in enumerate(signals):
m = s.shape[0]
padded_signals[i, :m, :] = s
padded_modality_ids[i, :m] = modality_ids[i]
channel_mask[i, :m] = True
return padded_signals, padded_modality_ids, torch.stack(labels), channel_mask
# -------------------------------------------------------------------
# 3. Loss Functions
# -------------------------------------------------------------------
class FocalLoss(nn.Module):
def __init__(self, gamma=2.0, alpha=None, reduction='mean', label_smoothing=0.0):
super().__init__()
self.gamma = float(gamma)
self.reduction = reduction
self.label_smoothing = float(label_smoothing)
self.alpha_scalar = None
if alpha is None:
self.register_buffer("alpha_tensor", None)
elif isinstance(alpha, (list, tuple)):
self.register_buffer("alpha_tensor", torch.tensor(alpha, dtype=torch.float32))
else:
self.register_buffer("alpha_tensor", None)
self.alpha_scalar = float(alpha)
def forward(self, logits, targets):
if targets.dtype == torch.long:
ce_loss = F.cross_entropy(logits, targets, reduction='none', label_smoothing=self.label_smoothing)
pt = torch.exp(-ce_loss)
focal_weight = (1.0 - pt) ** self.gamma
loss = focal_weight * ce_loss
if self.alpha_tensor is not None:
alpha_t = self.alpha_tensor[targets]
loss = alpha_t * loss
elif self.alpha_scalar is not None:
loss = self.alpha_scalar * loss
else:
log_probs = F.log_softmax(logits, dim=-1)
if self.label_smoothing > 0:
num_classes = logits.size(-1)
targets = targets * (1.0 - self.label_smoothing) + self.label_smoothing / num_classes
ce_loss = -(targets * log_probs).sum(dim=-1)
probs = torch.exp(log_probs)
pt = (targets * probs).sum(dim=-1)
focal_weight = (1.0 - pt) ** self.gamma
loss = focal_weight * ce_loss
if self.alpha_tensor is not None:
alpha_t = (targets * self.alpha_tensor).sum(dim=-1)
loss = alpha_t * loss
elif self.alpha_scalar is not None:
loss = self.alpha_scalar * loss
if self.reduction == 'sum':
return loss.sum()
if self.reduction == 'none':
return loss
return loss.mean()
class MultiLabelFocalLoss(nn.Module):
def __init__(self, gamma=2.0, alpha=None, pos_weight=None, reduction='mean'):
super().__init__()
self.gamma = gamma
self.alpha = alpha
self.reduction = reduction
self.register_buffer("pos_weight", pos_weight)
def forward(self, logits, targets):
bce_loss = F.binary_cross_entropy_with_logits(
logits, targets, reduction='none', pos_weight=self.pos_weight
)
probs = torch.sigmoid(logits)
pt = targets * probs + (1 - targets) * (1 - probs)
focal_weight = (1.0 - pt) ** self.gamma
if self.alpha is not None:
alpha_weight = targets * self.alpha + (1 - targets) * (1 - self.alpha)
focal_weight = alpha_weight * focal_weight
loss = focal_weight * bce_loss
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
return loss
def print_per_class_metrics(all_labels_np, all_probs_np, auc_list, class_names, thresholds=None):
"""打印每个类别的详细统计信息和单独的 AUC"""
num_classes = all_labels_np.shape[1]
if class_names is None:
class_names = [f"Class_{i}" for i in range(num_classes)]
max_name_len = max(len(name) for name in class_names)
max_name_len = max(max_name_len, 6)
header = f"{'类别':<{max_name_len}} {'正样本':>6} {'负样本':>6} {'正样本率':>8} {'AUC':>8}"
if thresholds is not None:
header += f" {'阈值':>6}"
header += f" {'Precision':>10} {'Recall':>10} {'F0.5':>8}"
print("-" * len(header))
print(header)
print("-" * len(header))
class_details = []
for i in range(num_classes):
y_true = all_labels_np[:, i]
y_prob = all_probs_np[:, i]
pos_count = int(y_true.sum())
neg_count = len(y_true) - pos_count
pos_ratio = pos_count / len(y_true) * 100
auc_val = auc_list[i]
th = thresholds[i] if thresholds is not None else 0.5
y_pred = (y_prob >= th).astype(int)
tp = int(((y_pred == 1) & (y_true == 1)).sum())
fp = int(((y_pred == 1) & (y_true == 0)).sum())
fn = int(((y_pred == 0) & (y_true == 1)).sum())
prec = tp / (tp + fp) if (tp + fp) > 0 else 0.0
rec = tp / (tp + fn) if (tp + fn) > 0 else 0.0
beta = 0.5
f_beta = (1 + beta**2) * prec * rec / (beta**2 * prec + rec) if (prec + rec) > 0 else 0.0
row = f"{class_names[i]:<{max_name_len}} {pos_count:>6d} {neg_count:>6d} {pos_ratio:>7.1f}% {auc_val:>8.4f}"
if thresholds is not None:
row += f" {th:>6.3f}"
row += f" {prec:>10.4f} {rec:>10.4f} {f_beta:>8.4f}"
print(row)
class_details.append({
'name': class_names[i], 'pos': pos_count, 'neg': neg_count,
'auc': auc_val, 'precision': prec, 'recall': rec, 'f0.5': f_beta
})
print("-" * len(header))
macro_auc = np.mean(auc_list)
print(f"{'Macro':<{max_name_len}} {int(all_labels_np.sum()):>6d} {all_labels_np.size - int(all_labels_np.sum()):>6d} {'':>8} {macro_auc:>8.4f}")
print("-" * len(header))
return class_details
# -------------------------------------------------------------------
# 4. 训练与验证逻辑
# -------------------------------------------------------------------
def move_batch_to_device(batch, device):
if len(batch) == 4:
x, modality_ids, y, channel_mask = batch
elif len(batch) == 3:
x, modality_ids, y = batch
channel_mask = None
else:
x, y = batch
modality_ids = None
channel_mask = None
x = x.to(device, non_blocking=True)
y = y.to(device, non_blocking=True)
if modality_ids is not None:
modality_ids = modality_ids.to(device, non_blocking=True)
if channel_mask is not None:
channel_mask = channel_mask.to(device, non_blocking=True)
return x, modality_ids, y, channel_mask
def train_one_epoch(model, loader, criterion, optimizer, device, epoch, scaler=None, use_amp=True,
grad_clip_norm=3.0, scheduler=None):
model.train()
if hasattr(loader.sampler, 'set_epoch'):
loader.sampler.set_epoch(epoch)
total_loss = 0
count = 0
amp_dtype = torch.bfloat16 if (device.type == 'cuda' and torch.cuda.is_bf16_supported()) else torch.float16
amp_enabled = use_amp and device.type == 'cuda'
iterator = tqdm(loader, desc=f"Epoch {epoch + 1} Train") if is_main_process() else loader
for batch in iterator:
x, modality_ids, y, channel_mask = move_batch_to_device(batch, device)
optimizer.zero_grad(set_to_none=True)
with autocast(device_type=device.type, dtype=amp_dtype, enabled=amp_enabled):
logits = model(x, channel_mask=channel_mask, channel_ids=modality_ids)
loss = criterion(logits, y)
if use_amp and amp_dtype == torch.float16:
if scaler is None:
raise RuntimeError("GradScaler is required for float16 AMP training.")
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=grad_clip_norm)
scaler.step(optimizer)
scaler.update()
else:
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=grad_clip_norm)
optimizer.step()
if scheduler is not None:
scheduler.step()
total_loss += loss.detach()
count += 1
if is_main_process():
current_lr = optimizer.param_groups[0]['lr']
loss_val = total_loss.item() if isinstance(total_loss, torch.Tensor) else total_loss
iterator.set_postfix({'loss': loss_val / count, 'lr': f"{current_lr:.2e}"})
if count == 0:
return 0.0
if isinstance(total_loss, torch.Tensor):
total_loss = total_loss.item()
return total_loss / count
def validate(model, loader, criterion, device, num_classes, total_len, use_amp=True,
search_threshold=True, fixed_threshold=0.5, save_dir=None, epoch=None):
model.eval()
total_loss = 0
count = 0
local_labels = []
local_probs = []
amp_dtype = torch.bfloat16 if (device.type == 'cuda' and torch.cuda.is_bf16_supported()) else torch.float16
amp_enabled = use_amp and device.type == 'cuda'
iterator = tqdm(loader, desc="Validating") if is_main_process() else loader
with torch.no_grad():
for batch in iterator:
x, modality_ids, y, channel_mask = move_batch_to_device(batch, device)
with autocast(device_type=device.type, dtype=amp_dtype, enabled=amp_enabled):
logits = model(x, channel_mask=channel_mask, channel_ids=modality_ids)
loss = criterion(logits, y)
if dist.is_initialized():
reduced_loss = reduce_tensor(loss)
total_loss += reduced_loss.detach()
else:
total_loss += loss.detach()
count += 1
probs = torch.sigmoid(logits.float())
local_labels.append(y.detach())
local_probs.append(probs.detach())
if count == 0 or len(local_labels) == 0:
if is_main_process():
return 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "Empty validation loader.", fixed_threshold, [], None, None
return 0, 0, 0, 0, 0, 0, None, 0, [], None, None
if isinstance(total_loss, torch.Tensor):
total_loss = total_loss.item()
local_labels = torch.cat(local_labels).cpu()
local_probs = torch.cat(local_probs).cpu()
if dist.is_initialized():
all_labels = gather_tensors(local_labels, device)
all_probs = gather_tensors(local_probs, device)
else:
all_labels = local_labels
all_probs = local_probs
if is_main_process():
if len(all_labels) > total_len:
all_labels = all_labels[:total_len]
all_probs = all_probs[:total_len]
all_labels_np = all_labels.cpu().numpy()
all_probs_np = all_probs.cpu().numpy()
# Multi-label thresholds
if search_threshold and num_classes > 2:
best_thresholds = []
for i in range(num_classes):
disease_true = all_labels_np[:, i]
disease_prob = all_probs_np[:, i]
if len(np.unique(disease_true)) > 1:
best_th_i = 0.5
best_f1_i = 0.0
for th in np.arange(0.1, 0.9, 0.05):
preds_i = (disease_prob >= th).astype(int)
f1_i = fbeta_score(disease_true, preds_i, beta=0.5, zero_division=0)
if f1_i > best_f1_i:
best_f1_i = f1_i
best_th_i = th
best_thresholds.append(best_th_i)
else:
best_thresholds.append(0.5)
best_threshold = np.array(best_thresholds)
final_preds = (all_probs_np >= best_threshold).astype(int)
else:
best_threshold = fixed_threshold
final_preds = (all_probs_np >= best_threshold).astype(int)
auc_list = []
for i in range(num_classes):
disease_true = all_labels_np[:, i]
disease_prob = all_probs_np[:, i]
try:
if len(np.unique(disease_true)) > 1:
auc_i = roc_auc_score(disease_true, disease_prob)
else:
auc_i = 0.5
except Exception:
auc_i = 0.5
auc_list.append(auc_i)
auroc = float(np.mean(auc_list))
final_acc = accuracy_score(all_labels_np, final_preds)
final_f1 = fbeta_score(all_labels_np, final_preds, beta=0.5, average='macro', zero_division=0)
precision = precision_score(all_labels_np, final_preds, average='macro', zero_division=0)
recall = recall_score(all_labels_np, final_preds, average='macro', zero_division=0)
report_str = classification_report(all_labels_np, final_preds, digits=4, zero_division=0)
avg_loss = total_loss / count
return avg_loss, final_acc, precision, recall, final_f1, auroc, report_str, best_threshold, auc_list, all_labels_np, all_probs_np
else:
return 0, 0, 0, 0, 0, 0, None, 0, [], None, None
# -------------------------------------------------------------------
# 主函数
# -------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--config', default='finetune_config_jepa.yaml', type=str)
args = parser.parse_args()
config_path = args.config
if not os.path.isabs(config_path):
config_path = os.path.join(os.path.dirname(__file__), config_path)
with open(config_path, 'r') as f:
config = yaml.safe_load(f)
train_cfg = config['train']
data_cfg = config['data']
model_cfg = config['model']
seed = train_cfg.get('seed', 42)
deterministic = train_cfg.get('deterministic', False)
set_seed(seed, deterministic=deterministic)
if torch.cuda.is_available():
local_rank, rank, world_size = setup_distributed()
device = torch.device(f"cuda:{local_rank}")
else:
local_rank, rank, world_size = 0, 0, 1
device = torch.device("cpu")
if is_main_process():
os.makedirs(train_cfg['save_dir'], exist_ok=True)
print(f"CWT-JEPA Finetune | World Size: {world_size} | Device: {device}")
logger = setup_logger(train_cfg['save_dir'], name="finetune_jepa")
if device.type == 'cuda':
torch.backends.cuda.matmul.allow_tf32 = train_cfg.get('allow_tf32', True)
torch.backends.cudnn.allow_tf32 = train_cfg.get('allow_tf32', True)
if not deterministic:
torch.backends.cudnn.benchmark = train_cfg.get('cudnn_benchmark', True)
with open(data_cfg['split_file'], 'r') as f:
split_info = json.load(f)
requested_val_mode = train_cfg.get('val_mode', 'val')
requested_test_mode = train_cfg.get('test_mode', 'test')
val_mode = requested_val_mode if requested_val_mode in split_info else (
'test' if 'test' in split_info else requested_val_mode)
test_mode = requested_test_mode if requested_test_mode in split_info else (
val_mode if val_mode in split_info else requested_test_mode)
if is_main_process():
print(f"Validation: {val_mode} | Test: {test_mode}")
class_names = data_cfg.get('class_names', None)
# Datasets
train_ds = DownstreamClassificationDataset(
data_cfg['data_root'], data_cfg['split_file'], mode='train',
signal_len=data_cfg['signal_len'], num_classes=data_cfg['num_classes'],
on_error=data_cfg.get('on_error', 'raise'),
max_error_logs=data_cfg.get('max_error_logs', 20),
refined_labels_path=data_cfg.get('refined_labels_path', None)
)
val_ds = DownstreamClassificationDataset(
data_cfg['data_root'], data_cfg['split_file'], mode=val_mode,
signal_len=data_cfg['signal_len'], num_classes=data_cfg['num_classes'],
on_error=data_cfg.get('on_error', 'raise'),
max_error_logs=data_cfg.get('max_error_logs', 20)
)
test_ds = DownstreamClassificationDataset(
data_cfg['data_root'], data_cfg['split_file'], mode=test_mode,
signal_len=data_cfg['signal_len'], num_classes=data_cfg['num_classes'],
on_error=data_cfg.get('on_error', 'raise'),
max_error_logs=data_cfg.get('max_error_logs', 20)
)
val_dataset_len = len(val_ds)
test_dataset_len = len(test_ds)
# Optional data cleaning
clean_indices_path = data_cfg.get('clean_indices_path')
if clean_indices_path and os.path.exists(clean_indices_path):
if is_main_process():
print(f"[Data Cleaning] Loading from {clean_indices_path}...")
clean_indices = np.load(clean_indices_path)
clean_indices = clean_indices[clean_indices < len(train_ds)]
train_ds = Subset(train_ds, clean_indices)
clean_val_indices_path = data_cfg.get('clean_val_indices_path')
if clean_val_indices_path and os.path.exists(clean_val_indices_path):
if is_main_process():
print(f"[Val Cleaning] Loading from {clean_val_indices_path}...")
clean_val_indices = np.load(clean_val_indices_path)
clean_val_indices = clean_val_indices[clean_val_indices < len(val_ds)]
val_ds = Subset(val_ds, clean_val_indices)
val_dataset_len = len(val_ds)
clean_test_indices_path = data_cfg.get('clean_test_indices_path')
if clean_test_indices_path and os.path.exists(clean_test_indices_path):
if is_main_process():
print(f"[Test Cleaning] Loading from {clean_test_indices_path}...")
clean_test_indices = np.load(clean_test_indices_path)
clean_test_indices = clean_test_indices[clean_test_indices < len(test_ds)]
test_ds = Subset(test_ds, clean_test_indices)
test_dataset_len = len(test_ds)
# Samplers
if dist.is_initialized():
train_sampler = DistributedSampler(train_ds, num_replicas=world_size, rank=rank, shuffle=True)
val_sampler = DistributedSampler(val_ds, num_replicas=world_size, rank=rank, shuffle=False)
test_sampler = DistributedSampler(test_ds, num_replicas=world_size, rank=rank, shuffle=False)
shuffle_train = False
else:
train_sampler = val_sampler = test_sampler = None
shuffle_train = True
pin_memory = data_cfg.get('pin_memory', True)
train_loader = DataLoader(
train_ds, batch_size=train_cfg['batch_size'], sampler=train_sampler,
shuffle=shuffle_train, num_workers=data_cfg.get('num_workers', 4),
pin_memory=pin_memory, collate_fn=variable_channel_collate_fn_cls
)
val_loader = DataLoader(
val_ds, batch_size=train_cfg['batch_size'], sampler=val_sampler,
shuffle=False, num_workers=data_cfg.get('num_workers', 4),
pin_memory=pin_memory, collate_fn=variable_channel_collate_fn_cls
)
test_loader = DataLoader(
test_ds, batch_size=train_cfg['batch_size'], sampler=test_sampler,
shuffle=False, num_workers=data_cfg.get('num_workers', 4),
pin_memory=pin_memory, collate_fn=variable_channel_collate_fn_cls
)
# Model
if is_main_process():
print(f"\nInitializing JEPA Classifier (CoT={model_cfg.get('use_cot', True)})...")
model = JEPA_Classifier(
pretrained_path=model_cfg.get('pretrained_path'),
num_classes=data_cfg['num_classes'],
signal_len=data_cfg['signal_len'],
cwt_scales=model_cfg.get('cwt_scales', 64),
patch_size_time=model_cfg.get('patch_size_time', 25),
patch_size_freq=model_cfg.get('patch_size_freq', 8),
embed_dim=model_cfg.get('embed_dim', 768),
depth=model_cfg.get('depth', 12),
num_heads=model_cfg.get('num_heads', 12),
use_diff=model_cfg.get('use_diff', True),
use_cot=model_cfg.get('use_cot', True),
num_reasoning_tokens=model_cfg.get('num_reasoning_tokens', 16),
use_stats_features=model_cfg.get('use_stats_features', False)
)
model.to(device)
find_unused_parameters = train_cfg.get('find_unused_parameters', True)
if dist.is_initialized():
model = DDP(model, device_ids=[local_rank], output_device=local_rank,
find_unused_parameters=find_unused_parameters)
# Optimizer
use_layer_wise_lr = train_cfg.get('use_layer_wise_lr', True)
if use_layer_wise_lr:
param_groups = get_layer_wise_lr(
unwrap_model(model), base_lr=train_cfg['base_lr'],
layer_decay=train_cfg.get('layer_decay', 0.65)
)
optimizer = optim.AdamW(param_groups, weight_decay=train_cfg['weight_decay'])
if is_main_process():
print("Optimizer: AdamW with layer-wise LR decay")
else:
optimizer = optim.AdamW(
unwrap_model(model).parameters(), lr=train_cfg['base_lr'],
weight_decay=train_cfg['weight_decay']
)
if is_main_process():
print("Optimizer: AdamW with uniform LR")
# Scheduler
steps_per_epoch = len(train_loader)
total_steps = train_cfg['epochs'] * steps_per_epoch
warmup_steps = int(train_cfg.get('warmup_epochs', 5) * steps_per_epoch)
warmup_scheduler = LinearLR(optimizer, start_factor=0.01, end_factor=1.0,
total_iters=warmup_steps)
cosine_scheduler = CosineAnnealingLR(optimizer, T_max=total_steps - warmup_steps,
eta_min=train_cfg['min_lr'])
scheduler = SequentialLR(optimizer, schedulers=[warmup_scheduler, cosine_scheduler],
milestones=[warmup_steps])
# Loss
use_focal = train_cfg.get('use_focal_loss', False)
if use_focal:
pos_weight_config = train_cfg.get('pos_weight')
if pos_weight_config == 'auto':
pos_weight = None
elif isinstance(pos_weight_config, list):
pos_weight = torch.tensor(pos_weight_config, device=device)
else:
pos_weight = None
criterion = MultiLabelFocalLoss(gamma=2.0, pos_weight=pos_weight)
if is_main_process():
print("Loss: MultiLabelFocalLoss")
else:
pos_weight_config = train_cfg.get('pos_weight')
if pos_weight_config == 'auto':
criterion = nn.BCEWithLogitsLoss()
elif isinstance(pos_weight_config, list):
criterion = nn.BCEWithLogitsLoss(
pos_weight=torch.tensor(pos_weight_config, device=device)
)
else:
criterion = nn.BCEWithLogitsLoss()
if is_main_process():
print(f"Loss: BCEWithLogitsLoss (pos_weight={pos_weight_config})")
# AMP
use_amp = train_cfg.get('use_amp', True)
scaler = GradScaler(enabled=use_amp and device.type == 'cuda')
# Resume
start_epoch = 0
best_metric = 0.0
best_threshold = 0.5
if train_cfg.get('auto_resume') and os.path.exists(
os.path.join(train_cfg['save_dir'], 'checkpoint_last.pth')):
resume_path = os.path.join(train_cfg['save_dir'], 'checkpoint_last.pth')
checkpoint = load_checkpoint(resume_path, model, optimizer, scheduler, scaler)
start_epoch = checkpoint.get('epoch', 0) + 1
best_metric = checkpoint.get('best_metric', 0.0)
best_threshold = checkpoint.get('best_threshold', 0.5)
if is_main_process():
print(f"Resumed from epoch {start_epoch}")
elif train_cfg.get('resume_path'):
checkpoint = load_checkpoint(train_cfg['resume_path'], model, optimizer, scheduler, scaler)
start_epoch = checkpoint.get('epoch', 0) + 1
best_metric = checkpoint.get('best_metric', 0.0)
best_threshold = checkpoint.get('best_threshold', 0.5)
if is_main_process():
print(f"Resumed from {train_cfg['resume_path']}")
# Training loop
for epoch in range(start_epoch, train_cfg['epochs']):
if is_main_process():
print(f"\n{'='*60}")
print(f"Epoch {epoch + 1}/{train_cfg['epochs']}")
print(f"{'='*60}")
train_loss = train_one_epoch(
model, train_loader, criterion, optimizer, device, epoch,
scaler=scaler, use_amp=use_amp,
grad_clip_norm=train_cfg.get('grad_clip_norm', 3.0),
scheduler=scheduler
)
val_loss, val_acc, val_prec, val_rec, val_f1, val_auc, val_report, best_th, auc_list, val_labels_np, val_probs_np = validate(
model, val_loader, criterion, device, data_cfg['num_classes'],
val_dataset_len, use_amp=use_amp,
search_threshold=True, fixed_threshold=0.5,
save_dir=train_cfg['save_dir'], epoch=epoch + 1
)
if is_main_process():
logger.info(f"Epoch {epoch + 1}: Train Loss={train_loss:.4f}, "
f"Val Loss={val_loss:.4f}, Val F0.5={val_f1:.4f}, Val AUC={val_auc:.4f}")
print(f"\nTrain Loss: {train_loss:.4f}")
print(f"Val Loss: {val_loss:.4f}, Acc: {val_acc:.4f}, "
f"Prec: {val_prec:.4f}, Rec: {val_rec:.4f}, F0.5: {val_f1:.4f}, AUC: {val_auc:.4f}")
if val_labels_np is not None and val_probs_np is not None and auc_list:
print(f"\n{'='*60}")
print(f"Epoch {epoch + 1} Per-Class Metrics:")
print(f"{'='*60}")
print_per_class_metrics(val_labels_np, val_probs_np, auc_list, class_names, thresholds=best_th)
current_metric = val_auc
if current_metric > best_metric:
best_metric = current_metric
best_threshold = best_th
save_checkpoint(
os.path.join(train_cfg['save_dir'], 'best_model.pth'),
model, optimizer, scheduler, epoch, best_metric, best_threshold, scaler
)
print(f"✓ Best model saved (AUC={best_metric:.4f})")
save_checkpoint(
os.path.join(train_cfg['save_dir'], 'checkpoint_last.pth'),
model, optimizer, scheduler, epoch, best_metric, best_threshold, scaler
)
if dist.is_initialized():
dist.barrier()
# Final test evaluation
if is_main_process():
print(f"\n{'='*60}")
print("Final Test Evaluation")
print(f"{'='*60}")
best_path = os.path.join(train_cfg['save_dir'], 'best_model.pth')
if os.path.exists(best_path):
load_checkpoint(best_path, model)
test_loss, test_acc, test_prec, test_rec, test_f1, test_auc, test_report, _, auc_list, test_labels_np, test_probs_np = validate(
model, test_loader, criterion, device, data_cfg['num_classes'],
test_dataset_len, use_amp=use_amp,
search_threshold=False, fixed_threshold=best_threshold,
save_dir=train_cfg['save_dir'], epoch=None
)
print(f"\nTest Loss: {test_loss:.4f}")
print(f"Test Acc: {test_acc:.4f}, Prec: {test_prec:.4f}, "
f"Rec: {test_rec:.4f}, F0.5: {test_f1:.4f}, AUC: {test_auc:.4f}")
if test_labels_np is not None and test_probs_np is not None and auc_list:
print(f"\n{'='*60}")
print("Test Per-Class Metrics:")
print(f"{'='*60}")
thresholds_to_use = best_threshold if isinstance(best_threshold, np.ndarray) else None
print_per_class_metrics(test_labels_np, test_probs_np, auc_list, class_names, thresholds=thresholds_to_use)
print(f"\nClassification Report:\n{test_report}")
logger.info(f"Final Test: Acc={test_acc:.4f}, F0.5={test_f1:.4f}, AUC={test_auc:.4f}")
# Save best threshold
threshold_path = os.path.join(train_cfg['save_dir'], 'best_threshold.json')
if isinstance(best_threshold, np.ndarray):
with open(threshold_path, 'w') as f:
json.dump({'thresholds': best_threshold.tolist(), 'auc': test_auc}, f)
cleanup_distributed()
if __name__ == '__main__':
main()