- 调整配置文件中辅助统计损失权重为0.1,避免辅助任务过度影响主训练 - 新增2D旋转位置编码类,适配时频维度的位置信息建模 - 重构多块掩码逻辑为全局共享掩码版本,移除padding操作并适配DDP分布式训练 - 优化EMA更新目标编码器的实现,使用批量PyTorch操作提升速度 - 新增四项训练监控指标,更新日志打印与CSV记录格式 - 调整损失计算逻辑:将JEPA预测损失改为smooth_l1损失,优化SIGReg正则化的显存占用 - 修正统计损失的梯度回传逻辑,使其辅助主干网络训练 - 清理无用导入,优化代码可读性
481 lines
20 KiB
Python
481 lines
20 KiB
Python
"""
|
|
CWT-JEPA 预训练脚本
|
|
Joint Embedding Predictive Architecture for Physiological Signals
|
|
|
|
基于 CWT-MAE 训练脚本改编,适配 JEPA 架构:
|
|
- MAE 像素重建 → JEPA 表征预测
|
|
- Decoder → Predictor (AdaLN)
|
|
- 新增 SIGReg 损失
|
|
- EMA Target Encoder 自动更新
|
|
"""
|
|
|
|
import os
|
|
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
|
|
os.environ['MKL_THREADING_LAYER'] = 'GNU'
|
|
|
|
import sys
|
|
import argparse
|
|
import yaml
|
|
import math
|
|
import time
|
|
from pathlib import Path
|
|
from collections import defaultdict
|
|
import numpy as np
|
|
|
|
import torch
|
|
import torch.optim as optim
|
|
import torch.distributed as dist
|
|
from torch.nn.parallel import DistributedDataParallel as DDP
|
|
from torch.utils.data import DataLoader, DistributedSampler
|
|
from torch.amp import autocast, GradScaler
|
|
|
|
# 允许编译失败时自动回退
|
|
import torch._dynamo
|
|
torch._dynamo.config.suppress_errors = True
|
|
|
|
# 导入本地模块
|
|
from dataset import PhysioSignalDataset, fixed_channel_collate_fn
|
|
from utils_metrics import ExperimentTracker
|
|
from utils import SmoothedValue, format_time, is_main_process
|
|
from utils import setup_logger, init_distributed_mode
|
|
|
|
# 导入 JEPA 模型
|
|
from model_jepa import CWT_JEPA
|
|
|
|
# 启用 TensorFloat-32
|
|
torch.set_float32_matmul_precision('high')
|
|
|
|
|
|
# -------------------------------------------------------------------
|
|
# 学习率调度器
|
|
# -------------------------------------------------------------------
|
|
def adjust_learning_rate_per_step(optimizer, current_step, total_steps, warmup_steps, base_lr, min_lr):
|
|
if current_step < warmup_steps:
|
|
lr = base_lr * current_step / warmup_steps
|
|
else:
|
|
progress = (current_step - warmup_steps) / (total_steps - warmup_steps)
|
|
lr = min_lr + (base_lr - min_lr) * 0.5 * (1. + math.cos(math.pi * progress))
|
|
|
|
for param_group in optimizer.param_groups:
|
|
if "lr_scale" in param_group:
|
|
param_group["lr"] = lr * param_group["lr_scale"]
|
|
else:
|
|
param_group["lr"] = lr
|
|
return lr
|
|
|
|
|
|
# -------------------------------------------------------------------
|
|
# 训练一个 Epoch
|
|
# -------------------------------------------------------------------
|
|
def train_one_epoch(model, dataloader, optimizer, scaler, epoch, logger, config, device,
|
|
start_time_global, total_steps, warmup_steps, base_lr, min_lr,
|
|
mask_ratio=None, lr_start_step=0, total_epochs=None):
|
|
model.train()
|
|
metric_logger = defaultdict(lambda: SmoothedValue(window_size=20))
|
|
metric_logger['loss'] = SmoothedValue(window_size=20, fmt='{median:.4f} ({global_avg:.4f})')
|
|
metric_logger['loss_jepa'] = SmoothedValue(window_size=20, fmt='{median:.4f} ({global_avg:.4f})')
|
|
metric_logger['loss_sigreg'] = SmoothedValue(window_size=20, fmt='{median:.4f} ({global_avg:.4f})')
|
|
metric_logger['loss_stats'] = SmoothedValue(window_size=20, fmt='{median:.4f} ({global_avg:.4f})')
|
|
metric_logger['repr_std'] = SmoothedValue(window_size=20, fmt='{value:.4f}')
|
|
metric_logger['pred_std'] = SmoothedValue(window_size=20, fmt='{value:.4f}')
|
|
metric_logger['std_ratio'] = SmoothedValue(window_size=20, fmt='{value:.4f}')
|
|
metric_logger['cosine_sim'] = SmoothedValue(window_size=20, fmt='{value:.4f}')
|
|
metric_logger['lr'] = SmoothedValue(window_size=1, fmt='{value:.6f}')
|
|
metric_logger['grad_norm'] = SmoothedValue(window_size=20, fmt='{value:.2f}')
|
|
metric_logger['throughput'] = SmoothedValue(window_size=20, fmt='{value:.2f}')
|
|
|
|
header = f'Epoch: [{epoch}/{total_epochs}]'
|
|
num_steps_per_epoch = len(dataloader)
|
|
accum_iter = config['train'].get('accum_iter', 1)
|
|
|
|
eff_batch_size = config['train']['batch_size'] * accum_iter * (
|
|
dist.get_world_size() if dist.is_initialized() else 1)
|
|
if config['train'].get('auto_scale_lr', True):
|
|
base_lr_scaled = base_lr * eff_batch_size / 256.0
|
|
min_lr_scaled = min_lr * eff_batch_size / 256.0
|
|
else:
|
|
base_lr_scaled = base_lr
|
|
min_lr_scaled = min_lr
|
|
|
|
amp_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
|
|
|
optimizer.zero_grad(set_to_none=True)
|
|
|
|
for step, batch_data in enumerate(dataloader):
|
|
step_start_time = time.time()
|
|
global_step = epoch * num_steps_per_epoch + step
|
|
|
|
# 解析 batch: (batch, channel_ids, labels, stats)
|
|
batch, channel_ids, labels, stats = batch_data
|
|
|
|
# LR 调整
|
|
if step % accum_iter == 0:
|
|
current_step_for_lr = global_step - lr_start_step
|
|
if current_step_for_lr < 0:
|
|
current_step_for_lr = 0
|
|
adjust_learning_rate_per_step(
|
|
optimizer,
|
|
current_step=current_step_for_lr // accum_iter,
|
|
total_steps=total_steps // accum_iter,
|
|
warmup_steps=warmup_steps // accum_iter,
|
|
base_lr=base_lr_scaled,
|
|
min_lr=min_lr_scaled
|
|
)
|
|
|
|
batch = batch.to(device, non_blocking=True)
|
|
|
|
# DDP 梯度同步控制
|
|
do_sync = (step + 1) % accum_iter == 0 or (step + 1) == len(dataloader)
|
|
if isinstance(model, DDP) and not do_sync:
|
|
import contextlib
|
|
context_manager = model.no_sync()
|
|
else:
|
|
import contextlib
|
|
context_manager = contextlib.nullcontext()
|
|
|
|
with context_manager:
|
|
with autocast('cuda', dtype=amp_dtype, enabled=config['train']['use_amp']):
|
|
channel_ids = channel_ids.to(device, non_blocking=True)
|
|
stats = stats.to(device, non_blocking=True)
|
|
|
|
# JEPA 前向传播
|
|
total_loss, loss_dict, s_x_pooled, pred_stats, s_x, s_y, s_y_hat, _ = model(
|
|
batch, channel_ids,
|
|
stats_target=stats,
|
|
mask_ratio=mask_ratio,
|
|
current_epoch=epoch,
|
|
total_epochs=total_epochs
|
|
)
|
|
total_loss = total_loss / accum_iter
|
|
|
|
scaler.scale(total_loss).backward()
|
|
|
|
loss_value = total_loss.item() * accum_iter
|
|
if not math.isfinite(loss_value):
|
|
print(f"Loss is {loss_value}, stopping training")
|
|
sys.exit(1)
|
|
|
|
loss_jepa_val = loss_dict.get('loss_jepa', 0.0)
|
|
loss_sigreg_val = loss_dict.get('loss_sigreg', 0.0)
|
|
loss_stats_val = loss_dict.get('loss_stats', 0.0)
|
|
repr_std_val = loss_dict.get('repr_std', 0.0)
|
|
pred_std_val = loss_dict.get('pred_std', 0.0)
|
|
std_ratio_val = loss_dict.get('std_ratio', 0.0)
|
|
cosine_sim_val = loss_dict.get('cosine_sim', 0.0)
|
|
|
|
if isinstance(loss_jepa_val, torch.Tensor): loss_jepa_val = loss_jepa_val.item()
|
|
if isinstance(loss_sigreg_val, torch.Tensor): loss_sigreg_val = loss_sigreg_val.item()
|
|
if isinstance(loss_stats_val, torch.Tensor): loss_stats_val = loss_stats_val.item()
|
|
if isinstance(repr_std_val, torch.Tensor): repr_std_val = repr_std_val.item()
|
|
if isinstance(pred_std_val, torch.Tensor): pred_std_val = pred_std_val.item()
|
|
if isinstance(std_ratio_val, torch.Tensor): std_ratio_val = std_ratio_val.item()
|
|
if isinstance(cosine_sim_val, torch.Tensor): cosine_sim_val = cosine_sim_val.item()
|
|
|
|
if do_sync:
|
|
scaler.unscale_(optimizer)
|
|
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config['train']['clip_grad'])
|
|
scaler.step(optimizer)
|
|
scaler.update()
|
|
optimizer.zero_grad(set_to_none=True)
|
|
metric_logger['grad_norm'].update(
|
|
grad_norm.item() if isinstance(grad_norm, torch.Tensor) else grad_norm)
|
|
# EMA 更新已在 model.forward() 中自动执行
|
|
|
|
# Metrics
|
|
batch_size = batch.shape[0]
|
|
step_duration = time.time() - step_start_time
|
|
throughput = batch_size / step_duration
|
|
|
|
metric_logger['loss'].update(loss_value)
|
|
metric_logger['loss_jepa'].update(loss_jepa_val)
|
|
metric_logger['loss_sigreg'].update(loss_sigreg_val)
|
|
metric_logger['loss_stats'].update(loss_stats_val)
|
|
metric_logger['repr_std'].update(repr_std_val)
|
|
metric_logger['pred_std'].update(pred_std_val)
|
|
metric_logger['std_ratio'].update(std_ratio_val)
|
|
metric_logger['cosine_sim'].update(cosine_sim_val)
|
|
metric_logger['lr'].update(optimizer.param_groups[0]["lr"])
|
|
metric_logger['throughput'].update(throughput)
|
|
|
|
if step % 50 == 0 and is_main_process():
|
|
elapsed = time.time() - start_time_global
|
|
|
|
# 关键层梯度监控
|
|
grad_stats = []
|
|
with torch.no_grad():
|
|
for name, p in model.named_parameters():
|
|
if p.grad is not None and ('predictor' in name or 'context_blocks.0' in name):
|
|
g_norm = p.grad.detach().norm(2).item()
|
|
if g_norm > 1.0:
|
|
w_std = p.detach().std().item()
|
|
grad_stats.append(f"{name}: g={g_norm:.2f}, w_std={w_std:.4f}")
|
|
|
|
if grad_stats:
|
|
logger.info(f"High Grads:\n" + "\n".join(grad_stats[:10]))
|
|
|
|
logger.info(
|
|
f"{header} Step: [{step}/{num_steps_per_epoch}] "
|
|
f"Loss: {metric_logger['loss']} "
|
|
f"JEPA: {metric_logger['loss_jepa']} "
|
|
f"SIGReg: {metric_logger['loss_sigreg']} "
|
|
f"Stats: {metric_logger['loss_stats']} "
|
|
f"ReprStd: {metric_logger['repr_std']} "
|
|
f"PredStd: {metric_logger['pred_std']} "
|
|
f"StdRatio: {metric_logger['std_ratio']} "
|
|
f"CosSim: {metric_logger['cosine_sim']} "
|
|
f"LR: {metric_logger['lr']} "
|
|
f"Grad: {metric_logger['grad_norm']} "
|
|
f"Speed: {metric_logger['throughput'].avg:.1f} samp/s "
|
|
f"Elapsed: {format_time(elapsed)}"
|
|
)
|
|
|
|
if is_main_process():
|
|
logger.info(f"Epoch {epoch} done. Avg Loss: {metric_logger['loss'].global_avg:.4f}")
|
|
|
|
return {
|
|
'loss': metric_logger['loss'].global_avg,
|
|
'loss_jepa': metric_logger['loss_jepa'].global_avg,
|
|
'loss_sigreg': metric_logger['loss_sigreg'].global_avg,
|
|
'loss_stats': metric_logger['loss_stats'].global_avg,
|
|
'repr_std': metric_logger['repr_std'].global_avg,
|
|
'pred_std': metric_logger['pred_std'].global_avg,
|
|
'std_ratio': metric_logger['std_ratio'].global_avg,
|
|
'cosine_sim': metric_logger['cosine_sim'].global_avg,
|
|
'grad_norm': metric_logger['grad_norm'].global_avg,
|
|
'throughput': metric_logger['throughput'].global_avg * (
|
|
dist.get_world_size() if dist.is_initialized() else 1)
|
|
}
|
|
|
|
|
|
# -------------------------------------------------------------------
|
|
# 主函数
|
|
# -------------------------------------------------------------------
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--config', default='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', encoding='utf-8') as f:
|
|
config = yaml.safe_load(f)
|
|
|
|
gpu_id, rank, world_size = init_distributed_mode()
|
|
device = torch.device(f"cuda:{gpu_id}")
|
|
|
|
seed = 42 + rank
|
|
torch.manual_seed(seed)
|
|
torch.cuda.manual_seed(seed)
|
|
torch.backends.cudnn.benchmark = True
|
|
|
|
if is_main_process():
|
|
Path(config['train']['save_dir']).mkdir(parents=True, exist_ok=True)
|
|
tracker = ExperimentTracker(config['train']['save_dir'])
|
|
|
|
logger = setup_logger(config['train']['save_dir'], name="CWT-JEPA")
|
|
|
|
# Dataset
|
|
data_index_path = config['data']['index_path']
|
|
if not os.path.isabs(data_index_path):
|
|
# Resolve relative to JEPA directory
|
|
data_index_path = os.path.join(os.path.dirname(__file__), data_index_path)
|
|
|
|
train_dataset = PhysioSignalDataset(
|
|
index_file=data_index_path,
|
|
indices=None,
|
|
signal_len=config['data']['signal_len'],
|
|
mode='train',
|
|
data_ratio=config['model'].get('data_ratio', 1.0),
|
|
use_sliding_window=config['data'].get('use_sliding_window', False),
|
|
window_stride=config['data'].get('window_stride', 500)
|
|
)
|
|
|
|
train_sampler = DistributedSampler(train_dataset, num_replicas=world_size, rank=rank, shuffle=True)
|
|
|
|
train_dataloader = DataLoader(
|
|
train_dataset,
|
|
batch_size=config['train']['batch_size'],
|
|
sampler=train_sampler,
|
|
num_workers=config['data']['num_workers'],
|
|
pin_memory=True,
|
|
drop_last=True,
|
|
collate_fn=fixed_channel_collate_fn
|
|
)
|
|
|
|
num_steps_per_epoch = len(train_dataloader)
|
|
total_epochs = config['train']['epochs']
|
|
warmup_epochs = config['train']['warmup_epochs']
|
|
total_steps = num_steps_per_epoch * total_epochs
|
|
warmup_steps = num_steps_per_epoch * warmup_epochs
|
|
base_lr = float(config['train']['base_lr'])
|
|
min_lr = float(config['train']['min_lr'])
|
|
|
|
if is_main_process():
|
|
logger.info(f"=" * 60)
|
|
logger.info(f"CWT-JEPA Pretraining")
|
|
logger.info(f"=" * 60)
|
|
logger.info(f"Total Steps: {total_steps}, Warmup: {warmup_steps}")
|
|
logger.info(f"Base LR: {base_lr}, Min LR: {min_lr}")
|
|
logger.info(f"Train Size: {len(train_dataset)}")
|
|
logger.info(f"Mask Ratio: {config['model']['mask_ratio']}")
|
|
logger.info(f"Predictor Depth: {config['model']['predictor_depth']}")
|
|
logger.info(f"SIGReg Lambda: {config['model']['sigreg_lambda']}")
|
|
logger.info(f"=" * 60)
|
|
|
|
# 构建模型
|
|
model_config = {
|
|
'signal_len': config['data']['signal_len'],
|
|
'cwt_scales': config['model'].get('cwt_scales', 64),
|
|
'patch_size_time': config['model'].get('patch_size_time', 25),
|
|
'patch_size_freq': config['model'].get('patch_size_freq', 8),
|
|
'embed_dim': config['model']['embed_dim'],
|
|
'depth': config['model']['depth'],
|
|
'num_heads': config['model']['num_heads'],
|
|
'mlp_ratio': config['model'].get('mlp_ratio', 4.0),
|
|
'predictor_depth': config['model']['predictor_depth'],
|
|
'predictor_num_heads': config['model']['predictor_num_heads'],
|
|
'mask_ratio': config['model'].get('mask_ratio', 0.75),
|
|
'num_target_blocks': config['model'].get('num_target_blocks', 4),
|
|
'target_scale_range': tuple(config['model'].get('target_scale_range', [0.15, 0.25])),
|
|
'ema_momentum': config['model'].get('ema_momentum', 0.999),
|
|
'ema_end_momentum': config['model'].get('ema_end_momentum', 1.0),
|
|
'sigreg_lambda': config['model'].get('sigreg_lambda', 0.1),
|
|
'sigreg_var_weight': config['model'].get('sigreg_var_weight', 1.0),
|
|
'sigreg_cov_weight': config['model'].get('sigreg_cov_weight', 1.0),
|
|
'stats_loss_weight': config['model'].get('stats_loss_weight', 1.0),
|
|
'use_diff': config['model'].get('use_diff', True),
|
|
'drop': config['model'].get('drop', 0.0),
|
|
}
|
|
|
|
if is_main_process():
|
|
logger.info("Initializing CWT-JEPA...")
|
|
logger.info(f" Encoder: {model_config['depth']} layers, {model_config['embed_dim']} dim")
|
|
logger.info(f" Predictor: {model_config['predictor_depth']} layers (AdaLN)")
|
|
logger.info(f" Target blocks: {model_config['num_target_blocks']}, "
|
|
f"scale={model_config['target_scale_range']}")
|
|
|
|
model = CWT_JEPA(**model_config)
|
|
model.to(device)
|
|
|
|
if config['train'].get('use_compile', False):
|
|
try:
|
|
model = torch.compile(model)
|
|
if is_main_process():
|
|
logger.info("Model compiled with torch.compile()")
|
|
except Exception as e:
|
|
if is_main_process():
|
|
logger.warning(f"Could not compile model: {e}")
|
|
|
|
model = DDP(model, device_ids=[gpu_id], output_device=gpu_id,
|
|
find_unused_parameters=True) if dist.is_initialized() else model
|
|
|
|
# 优化器
|
|
base_params = []
|
|
for name, param in model.named_parameters():
|
|
if not param.requires_grad:
|
|
continue
|
|
base_params.append(param)
|
|
|
|
if is_main_process():
|
|
logger.info(f"Optimizer: {len(base_params)} trainable params")
|
|
|
|
optimizer = optim.AdamW([
|
|
{'params': base_params, 'lr': base_lr}
|
|
], weight_decay=float(config['train']['weight_decay']))
|
|
|
|
scaler = GradScaler(enabled=config['train']['use_amp'])
|
|
|
|
accum_iter = config['train'].get('accum_iter', 1)
|
|
if is_main_process():
|
|
logger.info(f"Gradient Accumulation: {accum_iter}")
|
|
logger.info(f"Effective Batch Size: {config['train']['batch_size'] * accum_iter * world_size}")
|
|
|
|
# Resume
|
|
start_epoch = 0
|
|
if config['train']['resume'] and os.path.isfile(config['train']['resume']):
|
|
checkpoint = torch.load(config['train']['resume'], map_location='cpu')
|
|
state_dict = checkpoint['model']
|
|
if not dist.is_initialized():
|
|
new_state_dict = {}
|
|
for k, v in state_dict.items():
|
|
name = k.replace('module.', '')
|
|
new_state_dict[name] = v
|
|
msg = model.load_state_dict(new_state_dict, strict=False)
|
|
else:
|
|
msg = model.module.load_state_dict(state_dict, strict=False)
|
|
|
|
optimizer.load_state_dict(checkpoint['optimizer'])
|
|
scaler.load_state_dict(checkpoint['scaler'])
|
|
start_epoch = checkpoint['epoch'] + 1
|
|
if is_main_process():
|
|
logger.info(f"Resumed from epoch {start_epoch}")
|
|
if msg.missing_keys:
|
|
logger.warning(f"Missing keys: {msg.missing_keys}")
|
|
|
|
start_time_global = time.time()
|
|
|
|
# 训练循环
|
|
for epoch in range(start_epoch, total_epochs):
|
|
train_sampler.set_epoch(epoch)
|
|
|
|
current_mask_ratio = config['model'].get('mask_ratio', 0.75)
|
|
|
|
if is_main_process():
|
|
logger.info(f"\n--- Epoch {epoch} ---")
|
|
logger.info(f" Mask Ratio: {current_mask_ratio:.4f}")
|
|
|
|
train_metrics = train_one_epoch(
|
|
model, train_dataloader, optimizer, scaler, epoch, logger, config, device,
|
|
start_time_global,
|
|
total_steps=total_steps,
|
|
warmup_steps=warmup_steps,
|
|
base_lr=base_lr,
|
|
min_lr=min_lr,
|
|
mask_ratio=current_mask_ratio,
|
|
lr_start_step=0,
|
|
total_epochs=total_epochs
|
|
)
|
|
|
|
if is_main_process():
|
|
metrics_dict = {
|
|
'train_loss': train_metrics['loss'],
|
|
'loss_jepa': train_metrics['loss_jepa'],
|
|
'loss_sigreg': train_metrics['loss_sigreg'],
|
|
'loss_stats': train_metrics['loss_stats'],
|
|
'repr_std': train_metrics['repr_std'],
|
|
'pred_std': train_metrics['pred_std'],
|
|
'std_ratio': train_metrics['std_ratio'],
|
|
'cosine_sim': train_metrics['cosine_sim'],
|
|
'grad_norm': train_metrics['grad_norm'],
|
|
'gpu_mem_mb': torch.cuda.max_memory_allocated() / 1024 / 1024,
|
|
'throughput': train_metrics['throughput'],
|
|
}
|
|
tracker.log(epoch, metrics_dict)
|
|
logger.info(f"Epoch {epoch} Metrics: {metrics_dict}")
|
|
|
|
# 保存 Checkpoint
|
|
save_dict = {
|
|
'model': model.module.state_dict() if dist.is_initialized() else model.state_dict(),
|
|
'optimizer': optimizer.state_dict(),
|
|
'scaler': scaler.state_dict(),
|
|
'epoch': epoch,
|
|
'config': config
|
|
}
|
|
torch.save(save_dict, os.path.join(config['train']['save_dir'], "checkpoint_last.pth"))
|
|
if epoch % config['train']['save_freq'] == 0:
|
|
torch.save(save_dict, os.path.join(config['train']['save_dir'],
|
|
f"checkpoint_epoch_{epoch}.pth"))
|
|
|
|
if is_main_process():
|
|
logger.info("Training completed!")
|
|
logger.info(f"Model saved to: {config['train']['save_dir']}")
|
|
|
|
dist.destroy_process_group()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|