diff --git a/CWT_MAE_v3/dataset.py b/CWT_MAE_v3/dataset.py index f202576..7e25b9c 100644 --- a/CWT_MAE_v3/dataset.py +++ b/CWT_MAE_v3/dataset.py @@ -5,83 +5,9 @@ import json import os import random import pickle -import hashlib -from sklearn.model_selection import StratifiedShuffleSplit -from functools import lru_cache from utils_features import extract_features from preprocess import preprocess_signal -# 独立的缓存函数,避免实例绑定的序列化问题 -@lru_cache(maxsize=8) -def load_pickle_file(file_path): - with open(file_path, 'rb') as f: - return pickle.load(f) - -class DataSplitter: - def __init__(self, index_file, split_ratio=0.1, seed=42): - self.index_file = index_file - self.split_ratio = split_ratio - self.seed = seed - - with open(index_file, 'r') as f: - self.full_data = json.load(f) - - self.total_samples = len(self.full_data) - self.split_meta_file = index_file.replace('.json', f'_split_seed{seed}.json') - - def get_split(self): - # 1. Checksum verification - data_str = json.dumps(self.full_data, sort_keys=True) - current_hash = hashlib.md5(data_str.encode('utf-8')).hexdigest() - - # 2. Check if split meta exists and matches - if os.path.exists(self.split_meta_file): - print(f"Loading existing split from {self.split_meta_file}") - with open(self.split_meta_file, 'r') as f: - meta = json.load(f) - - if meta['hash'] == current_hash and meta['split_ratio'] == self.split_ratio: - print("Split checksum verified.") - return meta['train_indices'], meta['val_indices'] - else: - print("Split metadata mismatch or outdated. Re-splitting...") - - # 3. Create new split - print(f"Creating new split (val_ratio={self.split_ratio})...") - indices = np.arange(self.total_samples) - labels = [item.get('label', 0) for item in self.full_data] - - # Stratified Split - try: - sss = StratifiedShuffleSplit(n_splits=1, test_size=self.split_ratio, random_state=self.seed) - train_idx, val_idx = next(sss.split(indices, labels)) - except ValueError: - # Fallback to random split if only 1 class or labels issue - print("Stratified split failed (maybe single class), falling back to random split.") - np.random.seed(self.seed) - np.random.shuffle(indices) - split_point = int(self.total_samples * (1 - self.split_ratio)) - train_idx = indices[:split_point] - val_idx = indices[split_point:] - - train_indices = train_idx.tolist() - val_indices = val_idx.tolist() - - # 4. Save metadata - meta = { - 'hash': current_hash, - 'split_ratio': self.split_ratio, - 'seed': self.seed, - 'train_indices': train_indices, - 'val_indices': val_indices, - 'timestamp': str(np.datetime64('now')) - } - - with open(self.split_meta_file, 'w') as f: - json.dump(meta, f, indent=2) - - return train_indices, val_indices - class PhysioSignalDataset(Dataset): def __init__(self, index_file=None, data_source=None, indices=None, signal_len=500, mode='train', min_std_threshold=1e-4, @@ -327,23 +253,6 @@ class PhysioSignalDataset(Dataset): # 我们只在时间轴 (axis 1) 的右侧填充 return np.pad(signal, ((0, 0), (0, pad_len)), 'constant', constant_values=0) -def fixed_channel_collate_fn(batch): - """ - 单通道数据的 Collate Function。 - Output: (B, 1, L), (B,) channel_ids, (B,) labels, (B, 16) stats - """ - signals = [item[0] for item in batch] - channel_ids = [item[1] for item in batch] - labels = [item[2] for item in batch] - stats = [item[3] for item in batch] - - padded_signals = torch.stack(signals) # (B, 1, L) - channel_ids = torch.stack(channel_ids) # (B,) - labels = torch.stack(labels) # (B,) - stats_tensor = torch.stack(stats) # (B, 16) - - return padded_signals, channel_ids, labels, stats_tensor - def multi_channel_collate_fn(batch): """ 多通道预训练的 Collate Function,处理不同样本通道数不一致的情况。 diff --git a/CWT_MAE_v3/finetune.py b/CWT_MAE_v3/finetune.py index ca3114a..206063e 100644 --- a/CWT_MAE_v3/finetune.py +++ b/CWT_MAE_v3/finetune.py @@ -16,7 +16,6 @@ from tqdm import tqdm import torch.nn.functional as F import numpy as np from torch.amp import autocast, GradScaler -import copy from muon import Muon import warnings @@ -118,71 +117,6 @@ def move_batch_to_device(batch, device): channel_mask = channel_mask.to(device, non_blocking=True) return x, modality_ids, y, channel_mask -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): - # targets can be either hard labels (long) or soft labels (float) - if targets.dtype == torch.long: - # For hard labels, get standard cross entropy - ce_loss = F.cross_entropy( - logits, - targets, - reduction='none', - label_smoothing=self.label_smoothing - ) - # Calculate probabilities of the target class - 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: - # For soft labels, use KL divergence or compute manually - log_probs = F.log_softmax(logits, dim=-1) - # Manually apply label smoothing if needed for soft labels - 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 is the probability of the true distribution - 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: - # Approximate alpha for soft labels by taking expected alpha - 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__() diff --git a/CWT_MAE_v3/train.py b/CWT_MAE_v3/train.py index c96f1ba..86ebe33 100644 --- a/CWT_MAE_v3/train.py +++ b/CWT_MAE_v3/train.py @@ -6,6 +6,7 @@ import argparse import yaml import math import time +import contextlib from pathlib import Path from collections import defaultdict import numpy as np @@ -26,7 +27,7 @@ torch._dynamo.config.suppress_errors = True # 导入你的模型和数据集 from model import CWT_MAE_RoPE -from dataset import PhysioSignalDataset, fixed_channel_collate_fn, multi_channel_collate_fn +from dataset import PhysioSignalDataset, multi_channel_collate_fn from utils_metrics import ExperimentTracker from utils import save_reconstruction_images, SmoothedValue, format_time, is_main_process from utils import setup_logger, init_distributed_mode, update_teacher @@ -138,16 +139,10 @@ def train_one_epoch(model, dataloader, optimizer_muon, optimizer_adamw, scaler, # 混合精度前向传播 # 在 DDP 模式下,如果不是最后一次累积,使用 no_sync 上下文以减少通信 do_sync = (step + 1) % accum_iter == 0 or (step + 1) == len(dataloader) - - # 处理 DDP no_sync - my_context = model.no_sync if (isinstance(model, DDP) and not do_sync) else (lambda: contextlib.nullcontext()) - - # 注意:python < 3.7 可能不支持这种 lambda 写法,但这里环境通常较高。 - # 为了保险,直接写逻辑: + if isinstance(model, DDP) and not do_sync: context_manager = model.no_sync() else: - import contextlib context_manager = contextlib.nullcontext() with context_manager: @@ -490,11 +485,6 @@ def main(): tracker.log(epoch, metrics_dict) logger.info(f"Epoch {epoch} Metrics: {metrics_dict}") - # Early Stopping Check - if tracker.check_early_stopping(patience=3): - logger.info("Early stopping triggered due to no improvement in feature quality.") - # break # 取消注释以启用 - # 保存可视化 - 随机抽取一个样本 if vis_dataloader is not None: try: diff --git a/CWT_MAE_v3/utils.py b/CWT_MAE_v3/utils.py index a9de007..274a5ab 100644 --- a/CWT_MAE_v3/utils.py +++ b/CWT_MAE_v3/utils.py @@ -228,13 +228,6 @@ def update_teacher(model, decay=0.999): for ps, pt in zip(model.student_encoder_params(), model.teacher_encoder_params()): pt.data.mul_(decay).add_(ps.data, alpha=1 - decay) -def load_state_dict_ignore_prefix(model, state_dict, prefix='module.'): - new_state_dict = {} - for k, v in state_dict.items(): - name = k.replace(prefix, '') - new_state_dict[name] = v - model.load_state_dict(new_state_dict) - def get_layer_wise_lr(model, base_lr, layer_decay): param_groups = {} handled = set() diff --git a/CWT_MAE_v3/utils_metrics.py b/CWT_MAE_v3/utils_metrics.py index 690cc38..f1a3d9c 100644 --- a/CWT_MAE_v3/utils_metrics.py +++ b/CWT_MAE_v3/utils_metrics.py @@ -25,5 +25,3 @@ class ExperimentTracker: f"{metrics_dict.get('grad_norm', 0):.4f},{metrics_dict.get('gpu_mem_mb', 0):.1f}," f"{metrics_dict.get('throughput', 0):.2f}\n") - def check_early_stopping(self, patience=3): - return False