Refactor pretraining pipeline and visualization functions
- Updated `engine_pretrain.py` to enhance visualization of CWT and 1D signals, ensuring clarity in the relationship between original signals and their CWT representations. - Removed redundant comments and improved code readability. - Adjusted training logic in `train_one_epoch` to streamline gradient updates and logging. - Enhanced precision handling in `pretrain.py`, ensuring compatibility with various hardware setups. - Improved argument parsing for better configurability of training parameters. - Added support for BF16 and FP16 precision modes, with appropriate fallbacks and warnings. - Optimized model initialization and training loop for clarity and efficiency.
This commit is contained in:
1 parent
cf68b03ca7
commit
e0c9101da2
3 files changed
+366
-680
No files matched your search
@@ -2,222 +2,20 @@
|
||||
|
||||
import pickle
|
||||
import os
|
||||
from torch.utils.data import Dataset
|
||||
import random
|
||||
from tqdm import tqdm
|
||||
import torch
|
||||
from torch.utils.data import DataLoader
|
||||
from torch.utils.data._utils.collate import default_collate
|
||||
import torch.nn.functional as F
|
||||
import json
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch.utils.data import Dataset, DataLoader
|
||||
from torch.utils.data._utils.collate import default_collate
|
||||
from torchvision import transforms
|
||||
from tqdm import tqdm
|
||||
from functools import partial
|
||||
|
||||
|
||||
class LinearProbDataset(Dataset):
|
||||
def __init__(self, fnames, task):
|
||||
|
||||
# self.dataset_path = os.path.join(data_dir,dataset_name,'samples')
|
||||
self.fnames = fnames
|
||||
self.max_L = 387 # fix length
|
||||
self.task = task
|
||||
|
||||
def __len__(self):
|
||||
return len(self.fnames)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
f_path = self.fnames[idx]
|
||||
|
||||
with open(f_path, 'rb') as f:
|
||||
data_dict = pickle.load(f)
|
||||
|
||||
# x = torch.from_numpy(data_dict['cwt']).permute(0, 3, 1, 2) # n_var, 3, L, 65
|
||||
x = torch.from_numpy(data_dict['cwt']) # n_var, 3, L, 65
|
||||
'''
|
||||
在使用cwt_wrap函数时已经进行了变换
|
||||
'''
|
||||
|
||||
if torch.isnan(x).any():
|
||||
return None # Ignore the sample with NaN values
|
||||
|
||||
n_var, n_channels, L, H = x.size()
|
||||
padded_inputs = torch.zeros((n_var, n_channels, self.max_L, H))
|
||||
|
||||
if L < self.max_L:
|
||||
padded_inputs[:, :, -L:, :] = x
|
||||
else:
|
||||
padded_inputs = x[:, :, -self.max_L:, :]
|
||||
|
||||
label = data_dict['label']
|
||||
|
||||
if isinstance(label, dict):
|
||||
values = [label[key] for key in label.keys()]
|
||||
label = values
|
||||
|
||||
if self.task == "reg":
|
||||
label = torch.tensor(label).float()
|
||||
else:
|
||||
label = torch.tensor(label).long()
|
||||
|
||||
return {
|
||||
'input': padded_inputs,
|
||||
'label': label,
|
||||
}
|
||||
|
||||
|
||||
def linprob_collate_fn(batch):
|
||||
batch = [b for b in batch if b is not None]
|
||||
return default_collate(batch)
|
||||
|
||||
########################################################################################################################################################
|
||||
########################################################################################################################################################
|
||||
########################################################################################################################################################
|
||||
########################################################################################################################################################
|
||||
|
||||
|
||||
class PretrainDataset(Dataset):
|
||||
# [修改] 增加 subset_fraction 参数
|
||||
def __init__(self, data_dir, dataset_names, is_test=0,
|
||||
window_size=387,
|
||||
stride=100,
|
||||
img_size=(387, 65),
|
||||
cache_name: str = None,
|
||||
subset_fraction: float = 0.15): # [新增] 控制数据量的参数
|
||||
|
||||
self.window_size = window_size
|
||||
self.stride = stride
|
||||
|
||||
# --- [修改] 缓存逻辑 ---
|
||||
# 1. 如果手动指定了缓存名,则直接使用它,这是最优先、最稳定的方式。
|
||||
if cache_name:
|
||||
# 确保它是一个 .pkl 文件
|
||||
if not cache_name.endswith('.pkl'):
|
||||
cache_name += '.pkl'
|
||||
cache_path = os.path.join(data_dir, cache_name)
|
||||
print(
|
||||
f"Attempting to load from manually specified cache: {cache_path}")
|
||||
else:
|
||||
# 2. 如果没有手动指定,则使用稳定的方法生成文件名 (不再使用不稳定的 hash)
|
||||
# 将数据集名称排序并用'-'连接,这比哈希更稳定
|
||||
dataset_str = "-".join(sorted(dataset_names))
|
||||
cache_filename = f"pretrain_windows_ds_{dataset_str}_ws{window_size}_s{stride}.pkl"
|
||||
cache_path = os.path.join(data_dir, cache_filename)
|
||||
|
||||
# 3. 检查缓存是否存在 (测试模式下总会重新计算,不使用缓存)
|
||||
if os.path.exists(cache_path) and not is_test:
|
||||
print(f"Loading pre-computed windows from cache: {cache_path}")
|
||||
with open(cache_path, 'rb') as f:
|
||||
self.windows = pickle.load(f)
|
||||
else:
|
||||
# 4. 如果缓存不存在,则执行耗时的计算过程
|
||||
if is_test:
|
||||
print("Running in test mode, bypassing cache...")
|
||||
else:
|
||||
print(
|
||||
f"No cache found at '{cache_path}'. Preprocessing dataset (this will happen only once for this configuration)...")
|
||||
|
||||
fnames = [
|
||||
os.path.join(data_dir, dataset_name, fn)
|
||||
for dataset_name in dataset_names
|
||||
for fn in sorted(os.listdir(os.path.join(data_dir, dataset_name)))
|
||||
if fn[0] != "."
|
||||
]
|
||||
if is_test == 1:
|
||||
fnames = fnames[:20]
|
||||
|
||||
self.windows = []
|
||||
for fname in tqdm(fnames, desc="Calculating windows"):
|
||||
try:
|
||||
with open(fname, 'rb') as f:
|
||||
data_dict = pickle.load(f)
|
||||
|
||||
_, L = torch.from_numpy(data_dict['data']).float().shape
|
||||
|
||||
if L < self.window_size:
|
||||
continue
|
||||
|
||||
num_windows = (L - self.window_size) // self.stride + 1
|
||||
for i in range(num_windows):
|
||||
self.windows.append((fname, i * self.stride))
|
||||
except Exception as e:
|
||||
# print(f"Warning: Could not process file {fname}. Error: {e}")
|
||||
continue
|
||||
|
||||
# 5. 如果不是测试模式,将计算结果保存到缓存文件
|
||||
if not is_test:
|
||||
print(
|
||||
f"Saving computed windows to cache for future use: {cache_path}")
|
||||
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
|
||||
with open(cache_path, 'wb') as f:
|
||||
pickle.dump(self.windows, f)
|
||||
|
||||
# [新增] 根据 subset_fraction 参数对数据进行子集采样
|
||||
if subset_fraction < 1.0:
|
||||
if not (0.0 < subset_fraction <= 1.0):
|
||||
raise ValueError("subset_fraction must be between 0.0 and 1.0")
|
||||
|
||||
num_samples = int(len(self.windows) * subset_fraction)
|
||||
|
||||
# 使用固定的种子来确保每次采样的子集是相同的,保证实验可复现
|
||||
rng = random.Random(42)
|
||||
rng.shuffle(self.windows)
|
||||
|
||||
self.windows = self.windows[:num_samples]
|
||||
print(
|
||||
f"[INFO] Pre-training with a subset of {len(self.windows)} windows ({subset_fraction * 100:.1f}% of the total).")
|
||||
|
||||
print(f"Dataset initialized with {len(self.windows)} windows.")
|
||||
|
||||
# --- CWT 和数据增强部分保持不变 ---
|
||||
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
||||
self.transform = transforms.Compose([
|
||||
transforms.RandomResizedCrop(
|
||||
size=(img_size[1], img_size[0]), scale=(0.5, 1.0), antialias=True),
|
||||
transforms.RandomHorizontalFlip(), # 水平翻转对于时频谱图是有效增强
|
||||
])
|
||||
|
||||
def __len__(self):
|
||||
return len(self.windows)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
try:
|
||||
fname, start_idx = self.windows[idx]
|
||||
|
||||
with open(fname, 'rb') as f:
|
||||
data_dict = pickle.load(f)
|
||||
|
||||
full_signal = torch.from_numpy(data_dict['data']).float()
|
||||
raw_signal_window = full_signal[:,
|
||||
start_idx: start_idx + self.window_size]
|
||||
|
||||
# 清理和标准化1D信号
|
||||
if not torch.all(torch.isfinite(raw_signal_window)):
|
||||
raw_signal_window = torch.nan_to_num(
|
||||
raw_signal_window, nan=0.0)
|
||||
mean = torch.mean(raw_signal_window, dim=1, keepdim=True)
|
||||
std = torch.std(raw_signal_window, dim=1, keepdim=True)
|
||||
std[std == 0] = 1.0
|
||||
processed_signal_1d = (raw_signal_window - mean) / (std + 1e-8)
|
||||
|
||||
# 2. 生成CWT图像
|
||||
cwt_images = cwt_wrap(processed_signal_1d, self.cwt_scales)
|
||||
if not torch.all(torch.isfinite(cwt_images)):
|
||||
return None
|
||||
|
||||
# 3. 对CWT图像进行数据增强,作为模型的输入
|
||||
cwt_images_permuted = cwt_images.permute(0, 1, 3, 2)
|
||||
augmented_cwt_permuted = self.transform(cwt_images_permuted)
|
||||
augmented_cwt = augmented_cwt_permuted.permute(0, 1, 3, 2)
|
||||
|
||||
return {
|
||||
'input_cwt': augmented_cwt,
|
||||
'input_1d': processed_signal_1d, # 预测目标
|
||||
}
|
||||
except Exception as e:
|
||||
# print(f"Error processing window at index {idx}: {e}. Skipping.")
|
||||
return None
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# CWT 工具函数 (保持不变,逻辑清晰)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def ricker_wavelet(points, scale):
|
||||
"""Generate the Ricker (Mexican hat) wavelet for a given scale."""
|
||||
@@ -230,196 +28,216 @@ def ricker_wavelet(points, scale):
|
||||
gauss = torch.exp(-xsq / (2 * wsq))
|
||||
return A * mod * gauss
|
||||
|
||||
|
||||
def cwt_ricker(x, scales, wavelet_len):
|
||||
"""
|
||||
Compute the CWT using the Ricker wavelet.
|
||||
Args:
|
||||
x (torch.Tensor): Input time-series of shape (batch, sequence_length).
|
||||
scales (torch.Tensor): 1D Tensor of scales to use.
|
||||
wavelet_len (int): Length of the wavelet kernel.
|
||||
"""
|
||||
"""Compute the CWT using the Ricker wavelet."""
|
||||
batch_size, sequence_length = x.shape
|
||||
x = x.unsqueeze(1) # -> (batch, 1, sequence_length)
|
||||
|
||||
x = x.unsqueeze(1)
|
||||
num_scales = scales.shape[0]
|
||||
scales = scales.to(x.device)
|
||||
|
||||
effective_wavelet_len = min(wavelet_len, sequence_length)
|
||||
wavelets = torch.stack(
|
||||
[ricker_wavelet(effective_wavelet_len, scale) for scale in scales])
|
||||
# -> (num_scales, 1, wavelet_len)
|
||||
wavelets = torch.stack([ricker_wavelet(effective_wavelet_len, scale) for scale in scales])
|
||||
wavelets = wavelets.view(num_scales, 1, -1)
|
||||
|
||||
cwt_output = F.conv1d(x, wavelets, padding='same')
|
||||
return cwt_output # -> (batch, num_scales, sequence_length)
|
||||
|
||||
return cwt_output
|
||||
|
||||
def cwt_wrap(x, scales):
|
||||
"""
|
||||
Wrapper for CWT computation.
|
||||
Args:
|
||||
x (torch.Tensor): Input signal of shape (n_var, L).
|
||||
scales (torch.Tensor): 1D Tensor of scales to use for CWT.
|
||||
Returns:
|
||||
torch.Tensor: CWT result of shape (n_var, 3, L, num_scales).
|
||||
Returns: (n_var, 3, L, num_scales) -> permuted later if needed
|
||||
"""
|
||||
n_var, L = x.shape
|
||||
|
||||
# 1. Calculate derivatives
|
||||
d1 = x[:, 1:] - x[:, :-1]
|
||||
d2 = d1[:, 1:] - d1[:, :-1]
|
||||
|
||||
# 2. Align signals by padding them to the same length L
|
||||
original_x = x
|
||||
d1_padded = F.pad(d1, (1, 0), 'replicate')
|
||||
d2_padded = F.pad(d2, (2, 0), 'replicate')
|
||||
|
||||
# 3. Stack the aligned signals
|
||||
stacked_x = torch.stack(
|
||||
[original_x, d1_padded, d2_padded], dim=1) # -> (n_var, 3, L)
|
||||
|
||||
stacked_x = torch.stack([original_x, d1_padded, d2_padded], dim=1)
|
||||
n_var, n_channels, L_stacked = stacked_x.shape
|
||||
flat_x = stacked_x.reshape(n_var * n_channels, L_stacked)
|
||||
|
||||
# 4. Compute CWT
|
||||
wavelet_len = 257 # A fixed reasonable length
|
||||
# -> (n_var * 3, num_scales, L)
|
||||
wavelet_len = 257
|
||||
cwt_res = cwt_ricker(flat_x, scales, wavelet_len)
|
||||
|
||||
_, n_scales, _ = cwt_res.shape
|
||||
|
||||
# 5. Reshape to final format
|
||||
final_cwt = cwt_res.reshape(
|
||||
n_var, n_channels, n_scales, L_stacked).permute(0, 1, 3, 2)
|
||||
|
||||
final_cwt = cwt_res.reshape(n_var, n_channels, n_scales, L_stacked).permute(0, 1, 3, 2)
|
||||
return final_cwt
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 预训练数据集 (PretrainDataset)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def collate_fn(batch, pad_nvar=5):
|
||||
class PretrainDataset(Dataset):
|
||||
def __init__(self, data_dir, dataset_names, is_test=0,
|
||||
window_size=387, stride=100, img_size=(387, 65),
|
||||
cache_name: str = None, subset_fraction: float = 1.0,
|
||||
force_recompute: bool = False): # [新增] 强制重算参数
|
||||
|
||||
self.window_size = window_size
|
||||
self.stride = stride
|
||||
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
||||
|
||||
# 数据增强
|
||||
self.transform = transforms.Compose([
|
||||
transforms.RandomResizedCrop(size=(img_size[1], img_size[0]), scale=(0.5, 1.0), antialias=True),
|
||||
transforms.RandomHorizontalFlip(),
|
||||
])
|
||||
|
||||
# --- 缓存逻辑 ---
|
||||
if cache_name:
|
||||
if not cache_name.endswith('.pkl'): cache_name += '.pkl'
|
||||
cache_path = os.path.join(data_dir, cache_name)
|
||||
else:
|
||||
dataset_str = "-".join(sorted(dataset_names))
|
||||
cache_filename = f"pretrain_windows_ds_{dataset_str}_ws{window_size}_s{stride}.pkl"
|
||||
cache_path = os.path.join(data_dir, cache_filename)
|
||||
|
||||
if os.path.exists(cache_path) and not is_test and not force_recompute:
|
||||
print(f"Loading pre-computed windows from cache: {cache_path}")
|
||||
with open(cache_path, 'rb') as f:
|
||||
self.windows = pickle.load(f)
|
||||
else:
|
||||
if is_test: print("Running in test mode, bypassing cache...")
|
||||
else: print(f"Preprocessing dataset (cache not found or forced)...")
|
||||
|
||||
fnames = [
|
||||
os.path.join(data_dir, dataset_name, fn)
|
||||
for dataset_name in dataset_names
|
||||
for fn in sorted(os.listdir(os.path.join(data_dir, dataset_name)))
|
||||
if fn[0] != "."
|
||||
]
|
||||
if is_test == 1: fnames = fnames[:20]
|
||||
|
||||
self.windows = []
|
||||
for fname in tqdm(fnames, desc="Calculating windows"):
|
||||
try:
|
||||
with open(fname, 'rb') as f:
|
||||
data_dict = pickle.load(f)
|
||||
_, L = torch.from_numpy(data_dict['data']).float().shape
|
||||
if L < self.window_size: continue
|
||||
num_windows = (L - self.window_size) // self.stride + 1
|
||||
for i in range(num_windows):
|
||||
self.windows.append((fname, i * self.stride))
|
||||
except Exception: continue
|
||||
|
||||
if not is_test:
|
||||
print(f"Saving computed windows to cache: {cache_path}")
|
||||
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
|
||||
with open(cache_path, 'wb') as f:
|
||||
pickle.dump(self.windows, f)
|
||||
|
||||
# --- 子集采样 ---
|
||||
if subset_fraction < 1.0:
|
||||
num_samples = int(len(self.windows) * subset_fraction)
|
||||
random.Random(42).shuffle(self.windows)
|
||||
self.windows = self.windows[:num_samples]
|
||||
print(f"[INFO] Pre-training with subset: {len(self.windows)} windows ({subset_fraction*100:.1f}%).")
|
||||
|
||||
print(f"Dataset initialized with {len(self.windows)} windows.")
|
||||
|
||||
def __len__(self): return len(self.windows)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
try:
|
||||
fname, start_idx = self.windows[idx]
|
||||
with open(fname, 'rb') as f:
|
||||
data_dict = pickle.load(f)
|
||||
|
||||
full_signal = torch.from_numpy(data_dict['data']).float()
|
||||
raw_signal_window = full_signal[:, start_idx: start_idx + self.window_size]
|
||||
|
||||
if not torch.all(torch.isfinite(raw_signal_window)):
|
||||
raw_signal_window = torch.nan_to_num(raw_signal_window, nan=0.0)
|
||||
|
||||
# 标准化
|
||||
mean = torch.mean(raw_signal_window, dim=1, keepdim=True)
|
||||
std = torch.std(raw_signal_window, dim=1, keepdim=True)
|
||||
std[std == 0] = 1.0
|
||||
processed_signal_1d = (raw_signal_window - mean) / (std + 1e-8)
|
||||
|
||||
# CWT
|
||||
cwt_images = cwt_wrap(processed_signal_1d, self.cwt_scales)
|
||||
if not torch.all(torch.isfinite(cwt_images)): return None
|
||||
|
||||
# Augmentation
|
||||
cwt_images_permuted = cwt_images.permute(0, 1, 3, 2)
|
||||
augmented_cwt_permuted = self.transform(cwt_images_permuted)
|
||||
augmented_cwt = augmented_cwt_permuted.permute(0, 1, 3, 2)
|
||||
|
||||
return {
|
||||
'input_cwt': augmented_cwt,
|
||||
'input_1d': processed_signal_1d,
|
||||
}
|
||||
except Exception: return None
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 微调数据集基类 (BaseFineTuneDataset) - 减少代码冗余
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
class BaseFineTuneDataset(Dataset):
|
||||
"""
|
||||
一个为MAE预训练设计的collate_fn。
|
||||
- 过滤无效样本 (None)。
|
||||
- 处理分布式训练中可能出现的空batch。
|
||||
- 对每个样本的变量数量(n_vars)进行填充或采样,使其在batch内保持一致。
|
||||
微调数据集的基类,封装了通用的信号处理、增强和CWT逻辑。
|
||||
"""
|
||||
# --- 1. 过滤和处理无效样本 (与MoCo版本相同,非常鲁棒) ---
|
||||
def __init__(self, max_len=390, use_spec=False, augmentations=None, img_size=(387, 65)):
|
||||
self.max_len = max_len
|
||||
self.use_spec = use_spec
|
||||
self.augmentations = augmentations
|
||||
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
||||
|
||||
# 过滤掉在__getitem__中返回None的样本
|
||||
batch = [b for b in batch if b is not None]
|
||||
def process_signal(self, tss):
|
||||
# 1. 数据增强
|
||||
if self.augmentations:
|
||||
if 'noise_std' in self.augmentations and torch.rand(1).item() < 0.5:
|
||||
tss = tss + torch.randn_like(tss) * self.augmentations['noise_std']
|
||||
if 'scale_range' in self.augmentations and torch.rand(1).item() < 0.5:
|
||||
scale = torch.rand(1).item() * (self.augmentations['scale_range'][1] - self.augmentations['scale_range'][0]) + self.augmentations['scale_range'][0]
|
||||
tss = tss * scale
|
||||
|
||||
# 如果过滤后整个batch为空,则返回None,让训练循环处理
|
||||
if not batch:
|
||||
# 2. 长度处理
|
||||
current_L = tss.shape[1]
|
||||
if current_L > self.max_len:
|
||||
tss = tss[:, -self.max_len:]
|
||||
elif current_L < self.max_len:
|
||||
pad_size = self.max_len - current_L
|
||||
pad_values = tss[:, 0:1].expand(-1, pad_size)
|
||||
tss = torch.cat((pad_values, tss), dim=1)
|
||||
|
||||
# 3. 标准化
|
||||
mean = torch.mean(tss, dim=1, keepdim=True)
|
||||
std = torch.std(tss, dim=1, keepdim=True)
|
||||
std[std == 0] = 1.0
|
||||
processed_signal_1d = (tss - mean) / (std + 1e-8)
|
||||
|
||||
return processed_signal_1d
|
||||
|
||||
def compute_cwt(self, signal):
|
||||
if self.use_spec:
|
||||
cwt = cwt_wrap(signal, scales=self.cwt_scales)
|
||||
if not torch.all(torch.isfinite(cwt)): return None
|
||||
return cwt
|
||||
return None
|
||||
|
||||
# 为了处理分布式训练中一个进程的batch为空的情况,
|
||||
# 我们可以选择复制第一个有效样本来填充,但对于MAE,
|
||||
# 更简单的做法是如果batch为空就直接跳过。
|
||||
# 这里我们假设batch不为空,因为上面已经检查过了。
|
||||
# --------------------------------------------------------------------------
|
||||
# 标准微调数据集 (dataset_class)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
# --- 2. 对每个样本的变量数量(n_vars)进行填充或采样 ---
|
||||
|
||||
processed_batch = []
|
||||
for item in batch:
|
||||
# 获取当前样本的变量数
|
||||
# 我们以CWT输入的第一个维度为准
|
||||
n_var = item['input_cwt'].size(0)
|
||||
|
||||
# 如果变量数与目标填充数相同,则不做任何处理
|
||||
if n_var == pad_nvar:
|
||||
processed_batch.append(item)
|
||||
continue
|
||||
|
||||
new_item = {}
|
||||
|
||||
# 如果变量数大于目标数,则随机采样
|
||||
if n_var > pad_nvar:
|
||||
indices = random.sample(range(n_var), pad_nvar)
|
||||
indices = torch.tensor(indices)
|
||||
|
||||
new_item['input_cwt'] = item['input_cwt'][indices]
|
||||
new_item['input_1d'] = item['input_1d'][indices]
|
||||
|
||||
# 如果变量数小于目标数,则进行填充
|
||||
elif n_var < pad_nvar:
|
||||
# 复制最后一个有效变量来进行填充
|
||||
last_cwt = item['input_cwt'][-1:].expand(
|
||||
pad_nvar - n_var, -1, -1, -1)
|
||||
last_1d = item['input_1d'][-1:].expand(pad_nvar - n_var, -1)
|
||||
|
||||
new_item['input_cwt'] = torch.cat(
|
||||
[item['input_cwt'], last_cwt], dim=0)
|
||||
new_item['input_1d'] = torch.cat(
|
||||
[item['input_1d'], last_1d], dim=0)
|
||||
|
||||
processed_batch.append(new_item)
|
||||
|
||||
# --- 3. 使用PyTorch默认的collate函数进行最终的批处理 ---
|
||||
# default_collate会将字典列表 [{k1:v1, k2:v2}, ...]
|
||||
# 转换为一个字典 {k1:[v1, ...], k2:[v2, ...]} 并将值堆叠成张量
|
||||
return default_collate(processed_batch)
|
||||
# --- 3. 返回一个包含所有处理好数据的字典 ---
|
||||
|
||||
|
||||
#################################################################################
|
||||
class dataset_class(Dataset):
|
||||
"""
|
||||
A robust Dataset class for fine-tuning tasks.
|
||||
- Handles explicit label mapping for binary classification (e.g., healthy vs. unhealthy).
|
||||
- Includes session_id and sample_id in the output for detailed evaluation.
|
||||
- Applies 1D time-series augmentations during training.
|
||||
- Performs real-time CWT calculation if specified.
|
||||
- Includes robust padding and error handling.
|
||||
"""
|
||||
# [修改] 增加 subset_fraction 参数
|
||||
|
||||
def __init__(self, data_dir, is_train=True, max_len=390, use_spec=False, augmentations=None, img_size=(387, 65), subset_fraction: float = 1.0):
|
||||
super(dataset_class, self).__init__()
|
||||
class dataset_class(BaseFineTuneDataset):
|
||||
def __init__(self, data_dir, is_train=True, max_len=390, use_spec=False,
|
||||
augmentations=None, img_size=(387, 65), subset_fraction: float = 1.0):
|
||||
super().__init__(max_len, use_spec, augmentations if is_train else None, img_size)
|
||||
self.data_dir = data_dir
|
||||
self.is_train = is_train
|
||||
|
||||
# 1. 加载数据集划分
|
||||
with open(os.path.join(self.data_dir, 'train_test_split.json'), 'r') as file:
|
||||
split = json.load(file)
|
||||
self.file_list = split['train'] if self.is_train else split['test']
|
||||
|
||||
# [新增] 根据 subset_fraction 参数对训练数据进行子集采样
|
||||
# 注意:只对训练集进行采样,测试集应保持完整以进行公正评估
|
||||
if self.is_train and subset_fraction < 1.0:
|
||||
if not (0.0 < subset_fraction <= 1.0):
|
||||
raise ValueError("subset_fraction must be between 0.0 and 1.0")
|
||||
|
||||
num_samples = int(len(self.file_list) * subset_fraction)
|
||||
|
||||
# 使用固定的种子来确保每次采样的子集是相同的,保证实验可复现
|
||||
rng = random.Random(42)
|
||||
rng.shuffle(self.file_list)
|
||||
|
||||
random.Random(42).shuffle(self.file_list)
|
||||
self.file_list = self.file_list[:num_samples]
|
||||
print(
|
||||
f"[INFO] Fine-tuning with a subset of {len(self.file_list)} files ({subset_fraction * 100:.1f}% of the original training set).")
|
||||
print(f"[INFO] Fine-tuning subset: {len(self.file_list)} files.")
|
||||
|
||||
# 2. 明确定义标签映射
|
||||
# 0: 健康 (Negative class)
|
||||
# 1: 有病 (Positive class)
|
||||
self.label_map = {
|
||||
1: 0, # 原始标签1是'健康',映射为索引0
|
||||
2: 1, # 原始标签2是'有病',映射为索引1
|
||||
}
|
||||
if is_train:
|
||||
print(
|
||||
f"Using predefined label map for fine-tuning: {self.label_map}")
|
||||
self.label_map = {1: 0, 2: 1}
|
||||
|
||||
self.max_len = max_len
|
||||
self.use_spec = use_spec
|
||||
|
||||
# 3. 初始化 CWT scales
|
||||
if not isinstance(img_size, tuple) or len(img_size) != 2:
|
||||
img_size = (max_len - 2, 65)
|
||||
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
||||
|
||||
# 4. 初始化数据增强
|
||||
self.augmentations = augmentations if self.is_train else None
|
||||
def __len__(self): return len(self.file_list)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
try:
|
||||
@@ -427,189 +245,112 @@ class dataset_class(Dataset):
|
||||
with open(os.path.join(self.data_dir, 'sample_for_downstream', curr_fn), 'rb') as file:
|
||||
data = pickle.load(file)
|
||||
|
||||
if 'uid' in data:
|
||||
sample_id = str(data['uid'])
|
||||
else:
|
||||
sample_id = os.path.splitext(curr_fn)[0]
|
||||
|
||||
sample_id = str(data.get('uid', os.path.splitext(curr_fn)[0]))
|
||||
parts = sample_id.split('_')
|
||||
session_id = f"{parts[0]}_{parts[1]}" if len(
|
||||
parts) >= 2 else parts[0]
|
||||
session_id = f"{parts[0]}_{parts[1]}" if len(parts) >= 2 else parts[0]
|
||||
|
||||
# 1. 加载并清理1D信号
|
||||
tss = torch.from_numpy(data['data']).float()
|
||||
tss = torch.nan_to_num(tss, 0.0)
|
||||
|
||||
original_label = data['label'][0]['class']
|
||||
if original_label not in self.label_map:
|
||||
return None
|
||||
mapped_label = self.label_map[original_label]
|
||||
label = torch.tensor(mapped_label, dtype=torch.long)
|
||||
if original_label not in self.label_map: return None
|
||||
label = torch.tensor(self.label_map[original_label], dtype=torch.long)
|
||||
|
||||
# 2. [训练时] 应用1D数据增强
|
||||
if self.augmentations:
|
||||
if 'noise_std' in self.augmentations and torch.rand(1).item() < 0.5:
|
||||
tss = tss + \
|
||||
torch.randn_like(tss) * self.augmentations['noise_std']
|
||||
if 'scale_range' in self.augmentations and torch.rand(1).item() < 0.5:
|
||||
scale = torch.rand(1).item(
|
||||
) * (self.augmentations['scale_range'][1] - self.augmentations['scale_range'][0]) + self.augmentations['scale_range'][0]
|
||||
tss = tss * scale
|
||||
# 使用基类方法处理信号
|
||||
processed_signal_1d = self.process_signal(tss)
|
||||
|
||||
# 3. 序列长度处理 (填充或裁剪)
|
||||
current_L = tss.shape[1]
|
||||
if current_L > self.max_len:
|
||||
tss = tss[:, -self.max_len:]
|
||||
elif current_L < self.max_len:
|
||||
pad_size = self.max_len - current_L
|
||||
pad_values = tss[:, 0:1].expand(-1, pad_size)
|
||||
tss = torch.cat((pad_values, tss), dim=1)
|
||||
|
||||
# --- [核心修改] ---
|
||||
|
||||
# 4. 标准化1D信号,这将作为1D CNN的输入
|
||||
mean = torch.mean(tss, dim=1, keepdim=True)
|
||||
std = torch.std(tss, dim=1, keepdim=True)
|
||||
std[std == 0] = 1.0 # 增加保护
|
||||
processed_signal_1d = (tss - mean) / (std + 1e-8)
|
||||
|
||||
# 5. 构建包含所有需要信息的返回字典
|
||||
output_dict = {
|
||||
'label': label,
|
||||
'session_id': session_id,
|
||||
'sample_id': sample_id,
|
||||
'input_1d': processed_signal_1d, # <-- [新增] 返回处理好的1D信号
|
||||
'input_1d': processed_signal_1d,
|
||||
}
|
||||
|
||||
# 6. 如果需要,计算CWT并添加到字典中
|
||||
if self.use_spec:
|
||||
cwt = cwt_wrap(processed_signal_1d, scales=self.cwt_scales)
|
||||
if not torch.all(torch.isfinite(cwt)):
|
||||
# print(f"Warning: NaN in CWT for {curr_fn}. Skipping.")
|
||||
return None
|
||||
output_dict['input_cwt'] = cwt # <-- [修改] 键名改为 'input_cwt'
|
||||
cwt = self.compute_cwt(processed_signal_1d)
|
||||
if cwt is None: return None
|
||||
output_dict['input_cwt'] = cwt
|
||||
else:
|
||||
# 如果不使用CWT,为了兼容性,可以把1D信号也放入'input'键
|
||||
output_dict['input'] = processed_signal_1d
|
||||
|
||||
return output_dict
|
||||
except Exception: return None
|
||||
|
||||
except Exception as e:
|
||||
# print(f"Error processing sample at index {idx} (file: {self.file_list[idx]}): {e}. Skipping.")
|
||||
return None
|
||||
# --------------------------------------------------------------------------
|
||||
# K折交叉验证数据集 (KFoldDataset)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def __len__(self):
|
||||
return len(self.file_list)
|
||||
|
||||
|
||||
class KFoldDataset(Dataset):
|
||||
"""
|
||||
一个为分组K折交叉验证设计的专用数据集类。
|
||||
它直接从一个包含样本信息的列表中初始化,而不是从磁盘读取划分文件。
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
data_root_dir: str,
|
||||
samples_info: list,
|
||||
is_train: bool,
|
||||
max_len: int = 390,
|
||||
use_spec: bool = True,
|
||||
augmentations: dict = None,
|
||||
img_size: tuple = (387, 65)):
|
||||
"""
|
||||
初始化 KFoldDataset。
|
||||
|
||||
Args:
|
||||
data_root_dir (str): 数据集的根目录 (例如, '.../data/ppg_for_kfold')。
|
||||
samples_info (list): 一个字典列表,每个字典包含一个样本的信息。
|
||||
例如: [{'filename': 's1_c0.pkl', 'subject_id': 's1', 'binary_label': 1}, ...]
|
||||
is_train (bool): 指示当前是训练集还是测试集,用于决定是否应用数据增强。
|
||||
max_len (int): 信号序列的最大长度。
|
||||
use_spec (bool): 是否计算并返回 CWT 时频谱图。
|
||||
augmentations (dict, optional): 用于训练时的数据增强配置。
|
||||
img_size (tuple): CWT 图像的尺寸。
|
||||
"""
|
||||
super().__init__()
|
||||
class KFoldDataset(BaseFineTuneDataset):
|
||||
def __init__(self, data_root_dir, samples_info, is_train, max_len=390,
|
||||
use_spec=True, augmentations=None, img_size=(387, 65)):
|
||||
super().__init__(max_len, use_spec, augmentations if is_train else None, img_size)
|
||||
self.samples_dir = os.path.join(data_root_dir, 'samples')
|
||||
self.samples_info = samples_info
|
||||
self.is_train = is_train
|
||||
|
||||
# --- 其他配置 (与您原来的 dataset_class 保持一致) ---
|
||||
self.max_len = max_len
|
||||
self.use_spec = use_spec
|
||||
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
||||
|
||||
# 只有在 is_train 为 True 时才应用数据增强
|
||||
self.augmentations = augmentations if self.is_train else None
|
||||
|
||||
def __len__(self):
|
||||
return len(self.samples_info)
|
||||
def __len__(self): return len(self.samples_info)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
try:
|
||||
# 1. 从列表中获取当前样本的信息
|
||||
sample_meta = self.samples_info[idx]
|
||||
|
||||
filename = sample_meta['filename']
|
||||
label = torch.tensor(sample_meta['binary_label'], dtype=torch.long)
|
||||
subject_id = sample_meta['subject_id']
|
||||
|
||||
# 2. 加载并处理数据文件
|
||||
file_path = os.path.join(self.samples_dir, filename)
|
||||
with open(file_path, 'rb') as file:
|
||||
data = pickle.load(file)
|
||||
|
||||
# 提取 sample_id (通常是 chunk_id)
|
||||
sample_id = data.get('uid', os.path.splitext(filename)[0])
|
||||
|
||||
# 3. 加载并清理1D信号
|
||||
tss = torch.from_numpy(data['data']).float()
|
||||
tss = torch.nan_to_num(tss, 0.0)
|
||||
|
||||
# 4. [训练时] 应用1D数据增强
|
||||
if self.augmentations:
|
||||
if 'noise_std' in self.augmentations and torch.rand(1).item() < 0.5:
|
||||
tss = tss + \
|
||||
torch.randn_like(tss) * self.augmentations['noise_std']
|
||||
if 'scale_range' in self.augmentations and torch.rand(1).item() < 0.5:
|
||||
scale = torch.rand(1).item(
|
||||
) * (self.augmentations['scale_range'][1] - self.augmentations['scale_range'][0]) + self.augmentations['scale_range'][0]
|
||||
tss = tss * scale
|
||||
# 使用基类方法处理信号
|
||||
processed_signal_1d = self.process_signal(tss)
|
||||
|
||||
# 5. 序列长度处理 (填充或裁剪) - 与原来逻辑一致
|
||||
current_L = tss.shape[1]
|
||||
if current_L > self.max_len:
|
||||
tss = tss[:, -self.max_len:]
|
||||
elif current_L < self.max_len:
|
||||
pad_size = self.max_len - current_L
|
||||
pad_values = tss[:, 0:1].expand(-1, pad_size)
|
||||
tss = torch.cat((pad_values, tss), dim=1)
|
||||
|
||||
# 6. 标准化1D信号
|
||||
mean = torch.mean(tss, dim=1, keepdim=True)
|
||||
std = torch.std(tss, dim=1, keepdim=True)
|
||||
std[std == 0] = 1.0
|
||||
processed_signal_1d = (tss - mean) / (std + 1e-8)
|
||||
|
||||
# 7. 构建返回字典
|
||||
output_dict = {
|
||||
'label': label,
|
||||
'session_id': subject_id, # 使用 subject_id 作为 session_id
|
||||
'session_id': subject_id,
|
||||
'sample_id': sample_id,
|
||||
'input_1d': processed_signal_1d,
|
||||
}
|
||||
|
||||
# 8. 如果需要,计算CWT
|
||||
if self.use_spec:
|
||||
# 假设 cwt_wrap 函数在您的项目中可用
|
||||
from .dataset import cwt_wrap # 或者其他正确的导入路径
|
||||
cwt = cwt_wrap(processed_signal_1d, scales=self.cwt_scales)
|
||||
if not torch.all(torch.isfinite(cwt)):
|
||||
return None
|
||||
cwt = self.compute_cwt(processed_signal_1d)
|
||||
if cwt is None: return None
|
||||
output_dict['input_cwt'] = cwt
|
||||
|
||||
return output_dict
|
||||
except Exception: return None
|
||||
|
||||
except Exception as e:
|
||||
# print(f"Error processing sample at index {idx} (file: {self.samples_info[idx]['filename']}): {e}. Skipping.")
|
||||
return None
|
||||
# --------------------------------------------------------------------------
|
||||
# Collate Function (保持不变)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def collate_fn(batch, pad_nvar=5):
|
||||
batch = [b for b in batch if b is not None]
|
||||
if not batch: return None
|
||||
|
||||
processed_batch = []
|
||||
for item in batch:
|
||||
n_var = item['input_cwt'].size(0)
|
||||
if n_var == pad_nvar:
|
||||
processed_batch.append(item)
|
||||
continue
|
||||
|
||||
new_item = {}
|
||||
if n_var > pad_nvar:
|
||||
indices = torch.tensor(random.sample(range(n_var), pad_nvar))
|
||||
new_item['input_cwt'] = item['input_cwt'][indices]
|
||||
new_item['input_1d'] = item['input_1d'][indices]
|
||||
elif n_var < pad_nvar:
|
||||
last_cwt = item['input_cwt'][-1:].expand(pad_nvar - n_var, -1, -1, -1)
|
||||
last_1d = item['input_1d'][-1:].expand(pad_nvar - n_var, -1)
|
||||
new_item['input_cwt'] = torch.cat([item['input_cwt'], last_cwt], dim=0)
|
||||
new_item['input_1d'] = torch.cat([item['input_1d'], last_1d], dim=0)
|
||||
processed_batch.append(new_item)
|
||||
|
||||
return default_collate(processed_batch)
|
||||
|
||||
def linprob_collate_fn(batch):
|
||||
batch = [b for b in batch if b is not None]
|
||||
return default_collate(batch)
|
||||
@@ -4,7 +4,6 @@ import math
|
||||
import sys
|
||||
from typing import Iterable, Optional
|
||||
import torch
|
||||
from torch.amp.autocast_mode import autocast
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import os
|
||||
@@ -16,58 +15,47 @@ except ImportError:
|
||||
import NormWear.modules.lr_sched as lr_sched
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# [新增] CWT 与 1D 信号配对可视化函数
|
||||
# 可视化辅助函数 (保持不变,逻辑是正确的)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def save_cwt_signal_pair_visualization(original_signal, cwt_image, save_path, epoch, step):
|
||||
"""
|
||||
将1D原始信号及其对应的CWT图像一起可视化,以检查它们之间的关系。
|
||||
将1D原始信号及其对应的CWT图像一起可视化。
|
||||
original_signal: [n_var, L]
|
||||
cwt_image: [n_var, C, H, W]
|
||||
"""
|
||||
original_signal = original_signal.detach().cpu().float().numpy()
|
||||
cwt_image = cwt_image.detach().cpu().float().numpy()
|
||||
|
||||
# 只可视化第一个变量和第一个通道
|
||||
# 只可视化第一个变量
|
||||
sig_1d = original_signal[0]
|
||||
img_cwt = cwt_image[0, 0] # 取第一个通道的CWT
|
||||
img_cwt = cwt_image[0, 0]
|
||||
|
||||
# --- 绘图 ---
|
||||
fig, axs = plt.subplots(2, 1, figsize=(
|
||||
15, 6), sharex=True, gridspec_kw={'height_ratios': [1, 2]})
|
||||
fig.suptitle(
|
||||
f'1D Signal and its CWT (Epoch {epoch}, Step {step})', fontsize=16)
|
||||
|
||||
# 上方子图: 1D 信号
|
||||
axs[0].plot(sig_1d)
|
||||
axs[0].set_title('Original 1D Signal')
|
||||
axs[0].set_ylabel('Amplitude')
|
||||
axs[0].grid(True)
|
||||
|
||||
# 下方子图: 2D CWT 图像
|
||||
# imshow 的 extent 参数可以帮助对齐坐标轴,但为了简单起见,共享x轴已足够直观
|
||||
im = axs[1].imshow(img_cwt, cmap='viridis', aspect='auto', origin='lower')
|
||||
axs[1].set_title('Corresponding CWT Image (Channel 0)')
|
||||
axs[1].set_xlabel('Time Steps')
|
||||
axs[1].set_ylabel('CWT Scales')
|
||||
fig.colorbar(im, ax=axs[1], label='Magnitude')
|
||||
|
||||
plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # 调整布局以适应主标题
|
||||
|
||||
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
|
||||
os.makedirs(save_path, exist_ok=True)
|
||||
plt.savefig(os.path.join(
|
||||
save_path, f'cwt_signal_pair_epoch_{epoch}_step_{step}.png'))
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# [已存在] CWT图像重建可视化函数
|
||||
# --------------------------------------------------------------------------
|
||||
def save_mae_image_reconstruction(original_img, pred_img, mask, save_path, epoch, step, patch_size, patch_hw):
|
||||
"""
|
||||
将MAE的CWT图像重建结果可视化并保存。
|
||||
"""
|
||||
original_img = original_img.detach().cpu().float().numpy()
|
||||
pred_img = pred_img.detach().cpu().float().numpy()
|
||||
mask = mask.detach().cpu().float().numpy()
|
||||
@@ -118,15 +106,8 @@ def save_mae_image_reconstruction(original_img, pred_img, mask, save_path, epoch
|
||||
save_path, f'reconstruction_cwt_epoch_{epoch}_step_{step}.png'))
|
||||
plt.close(fig)
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# [已存在] 1D原始信号重建可视化函数
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def save_mae_signal_reconstruction(original_signal, pred_signal, mask, save_path, epoch, step, patch_size, patch_hw):
|
||||
"""
|
||||
将MAE的1D信号重建结果可视化并保存。
|
||||
"""
|
||||
original_signal = original_signal.detach().cpu().float().numpy()
|
||||
pred_signal = pred_signal.detach().cpu().float().numpy()
|
||||
mask = mask.detach().cpu().float().numpy()
|
||||
@@ -170,7 +151,7 @@ def save_mae_signal_reconstruction(original_signal, pred_signal, mask, save_path
|
||||
plt.close(fig)
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 修改后的 train_one_epoch 函数
|
||||
# 训练引擎
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -192,9 +173,10 @@ def train_one_epoch(model: torch.nn.Module,
|
||||
header = 'Epoch: [{}]'.format(epoch)
|
||||
print_freq = 20
|
||||
|
||||
# ... (可视化路径和模型参数获取) ...
|
||||
vis_save_path = os.path.join(args.output_dir, 'mae_visualizations')
|
||||
vis_freq = 100
|
||||
|
||||
# 获取模型配置用于可视化
|
||||
model_without_ddp = model.module if hasattr(model, 'module') else model
|
||||
patch_hw = model_without_ddp.patch_embed.patch_hw
|
||||
patch_size = model_without_ddp.patch_size
|
||||
@@ -206,6 +188,7 @@ def train_one_epoch(model: torch.nn.Module,
|
||||
print('log_dir: {}'.format(log_writer.log_dir))
|
||||
|
||||
for data_iter_step, batch in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
||||
# 学习率调整
|
||||
if (data_iter_step) % accum_iter == 0:
|
||||
lr_sched.adjust_learning_rate(
|
||||
optimizer, data_iter_step / len(data_loader) + epoch, args)
|
||||
@@ -216,6 +199,7 @@ def train_one_epoch(model: torch.nn.Module,
|
||||
samples_cwt = batch['input_cwt'].to(device, non_blocking=True)
|
||||
samples_1d = batch['input_1d'].to(device, non_blocking=True)
|
||||
|
||||
# [修改] 确保 autocast 使用正确的 dtype (BF16 或 FP16)
|
||||
with torch.amp.autocast(device_type=device.type, dtype=dtype):
|
||||
loss, pred_pixels, pred_signal, mask = model(
|
||||
x_cwt=samples_cwt,
|
||||
@@ -231,80 +215,60 @@ def train_one_epoch(model: torch.nn.Module,
|
||||
optimizer.zero_grad(set_to_none=True)
|
||||
continue
|
||||
|
||||
# --- [核心修复:增加防御性检查和清晰的逻辑分支] ---
|
||||
|
||||
# --- 反向传播与梯度更新 ---
|
||||
grad_norm = None
|
||||
is_update_step = (data_iter_step + 1) % accum_iter == 0
|
||||
|
||||
# 分支 1: 使用 fp16 和 GradScaler
|
||||
# 分支 1: FP16 (使用 GradScaler)
|
||||
if loss_scaler is not None:
|
||||
# 这是一个防御性检查,确保我们不会调用一个 None 对象
|
||||
if data_iter_step == 0 and misc.is_main_process():
|
||||
print(">>> Training with FP16 NativeScaler.")
|
||||
|
||||
grad_norm = loss_scaler(
|
||||
loss, optimizer, parameters=model.parameters(),
|
||||
update_grad=is_update_step,
|
||||
clip_grad=args.clip_grad if hasattr(
|
||||
args, 'clip_grad') else None
|
||||
clip_grad=args.clip_grad
|
||||
)
|
||||
# 在非更新步骤,loss_scaler 会返回 None,这是正常的
|
||||
if is_update_step and grad_norm is None:
|
||||
# 如果是更新步骤但 grad_norm 仍然是 None,说明可能跳过了更新(例如梯度为inf/nan)
|
||||
# 我们可以给它一个默认值0来记录
|
||||
grad_norm = 0.0
|
||||
|
||||
# 分支 2: 使用 bf16/fp32,无 GradScaler
|
||||
# 分支 2: BF16 / FP32 (无 GradScaler)
|
||||
else:
|
||||
if data_iter_step == 0 and misc.is_main_process():
|
||||
print(">>> Training without NativeScaler (BF16/FP32 mode).")
|
||||
|
||||
# 直接反向传播
|
||||
loss.backward()
|
||||
|
||||
if is_update_step:
|
||||
# 在更新步骤,我们手动计算梯度范数并更新优化器
|
||||
parameters = [p for p in model.parameters() if p.requires_grad]
|
||||
|
||||
if hasattr(args, 'clip_grad') and args.clip_grad is not None:
|
||||
# HFR 建议始终进行梯度裁剪
|
||||
if args.clip_grad is not None:
|
||||
grad_norm = torch.nn.utils.clip_grad_norm_(
|
||||
parameters, max_norm=args.clip_grad)
|
||||
model.parameters(), args.clip_grad)
|
||||
else:
|
||||
# 手动计算总梯度范unorm
|
||||
total_norm = 0.0
|
||||
for p in parameters:
|
||||
if p.grad is not None:
|
||||
param_norm = p.grad.data.norm(2)
|
||||
total_norm += param_norm.item() ** 2
|
||||
grad_norm = total_norm ** 0.5
|
||||
# 仅计算范数用于日志
|
||||
parameters = [p for p in model.parameters()
|
||||
if p.grad is not None]
|
||||
total_norm = torch.norm(torch.stack(
|
||||
[torch.norm(p.grad.detach(), 2) for p in parameters]), 2)
|
||||
grad_norm = total_norm.item()
|
||||
|
||||
optimizer.step()
|
||||
optimizer.zero_grad(set_to_none=True)
|
||||
|
||||
torch.cuda.synchronize()
|
||||
|
||||
# 记录未缩放的loss
|
||||
# --- 日志记录 (修复了重复记录的问题) ---
|
||||
# 注意:这里记录的是还原后的真实 Loss (loss_value * accum_iter)
|
||||
metric_logger.update(loss=loss_value * accum_iter)
|
||||
lr = optimizer.param_groups[0]["lr"]
|
||||
metric_logger.update(lr=lr)
|
||||
metric_logger.update(lr=optimizer.param_groups[0]["lr"])
|
||||
|
||||
# 只有在计算了 grad_norm 的步骤才更新它
|
||||
if grad_norm is not None:
|
||||
metric_logger.update(grad_norm=grad_norm.item(
|
||||
) if hasattr(grad_norm, 'item') else grad_norm)
|
||||
metric_logger.update(grad_norm=grad_norm)
|
||||
|
||||
# --- [核心修改] 可视化逻辑,现在调用三个可视化函数 ---
|
||||
# --- 可视化 ---
|
||||
if misc.is_main_process() and (data_iter_step % vis_freq == 0):
|
||||
# 1. [新增] 可视化 CWT 与 1D 信号的配对关系
|
||||
# 1. CWT 与 1D 信号配对
|
||||
save_cwt_signal_pair_visualization(
|
||||
original_signal=samples_1d[0], # 这是原始的1D信号
|
||||
cwt_image=samples_cwt[0], # 这是原始的CWT图像
|
||||
original_signal=samples_1d[0],
|
||||
cwt_image=samples_cwt[0],
|
||||
save_path=vis_save_path,
|
||||
epoch=epoch,
|
||||
step=data_iter_step
|
||||
)
|
||||
|
||||
# 2. 可视化CWT图像重建
|
||||
# 2. CWT 重建
|
||||
save_mae_image_reconstruction(
|
||||
original_img=samples_cwt[0],
|
||||
pred_img=pred_pixels[0],
|
||||
@@ -315,7 +279,7 @@ def train_one_epoch(model: torch.nn.Module,
|
||||
patch_size=patch_size,
|
||||
patch_hw=patch_hw
|
||||
)
|
||||
# 3. 可视化1D信号重建
|
||||
# 3. 1D 信号重建
|
||||
save_mae_signal_reconstruction(
|
||||
original_signal=samples_1d[0],
|
||||
pred_signal=pred_signal[0],
|
||||
@@ -327,12 +291,6 @@ def train_one_epoch(model: torch.nn.Module,
|
||||
patch_hw=patch_hw
|
||||
)
|
||||
|
||||
torch.cuda.synchronize()
|
||||
|
||||
metric_logger.update(loss=loss_value)
|
||||
lr = optimizer.param_groups[0]["lr"]
|
||||
metric_logger.update(lr=lr)
|
||||
|
||||
metric_logger.synchronize_between_processes()
|
||||
print("Averaged stats:", metric_logger)
|
||||
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
|
||||
+102
-115
@@ -1,12 +1,4 @@
|
||||
# main_pretrain.py (or demo.py)
|
||||
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount
|
||||
from NormWear.pretrain_pipeline.dataset import PretrainDataset, collate_fn, DataLoader
|
||||
from NormWear.pretrain_pipeline.engine_pretrain import train_one_epoch
|
||||
from NormWear.modules.normwear import NormWear
|
||||
from functools import partial
|
||||
import timm.optim.optim_factory as optim_factory
|
||||
from NormWear.pretrain_pipeline.misc import get_next_run_number
|
||||
from NormWear.pretrain_pipeline import misc
|
||||
# main_pretrain.py
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
@@ -14,47 +6,44 @@ import numpy as np
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from functools import partial
|
||||
|
||||
import torch
|
||||
import torch.backends.cudnn as cudnn
|
||||
from torch.utils.tensorboard import SummaryWriter
|
||||
# from torch.cuda.amp import GradScaler
|
||||
import sys
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
||||
torch.autograd.set_detect_anomaly(True)
|
||||
# [修改] 确保引入的是带窗口化和缓存功能的 PretrainDataset
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
||||
|
||||
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount, get_next_run_number
|
||||
from NormWear.pretrain_pipeline.dataset import PretrainDataset, collate_fn, DataLoader
|
||||
from NormWear.pretrain_pipeline.engine_pretrain import train_one_epoch
|
||||
from NormWear.modules.normwear import NormWear
|
||||
from NormWear.pretrain_pipeline import misc
|
||||
|
||||
# 开启异常检测有助于调试 HFR 这种自定义反向传播较多的模型
|
||||
torch.autograd.set_detect_anomaly(True)
|
||||
|
||||
def get_args_parser():
|
||||
parser = argparse.ArgumentParser(
|
||||
'NormWear MAE Pre-training', add_help=False)
|
||||
parser.add_argument('--modality_dropout', type=float, default=0.15,
|
||||
help='Probability of dropping an entire modality during training (e.g., 0.15 for 15%). Set to 0 to disable.')
|
||||
# --- [新增] 精度选择参数 ---
|
||||
parser.add_argument('--precision', default='bf16', type=str, choices=['fp32', 'fp16', 'bf16'],
|
||||
help='Floating point precision for training. bf16 is recommended on supported hardware (A100, H100, RTX 30/40).')
|
||||
|
||||
# pretrain args
|
||||
# MAEargs
|
||||
parser.add_argument('--blr', type=float, default=1e-3,
|
||||
metavar='LR', help='base learning rate')
|
||||
parser.add_argument('--mask_ratio', default=0.75,
|
||||
type=float, help='Ratio of patches to mask')
|
||||
parser.add_argument('--norm_pix_loss', action='store_true',
|
||||
help='Normalize pixels for loss calculation')
|
||||
parser.set_defaults(norm_pix_loss=False)
|
||||
# [核心新增] 添加用于控制随机模态丢弃的参数
|
||||
# training args
|
||||
parser.add_argument('--reconstruction_prob', type=float, default=0.25,
|
||||
help='Probability of a variable being chosen as a reconstruction target (e.g., 0.25 for 25%).')
|
||||
|
||||
parser.add_argument('--batch_size', default=768,
|
||||
type=int, help='Batch size per GPU')
|
||||
parser = argparse.ArgumentParser('NormWear HFR Pre-training', add_help=False)
|
||||
|
||||
# --- 基础训练参数 ---
|
||||
parser.add_argument('--batch_size', default=768, type=int, help='Batch size per GPU')
|
||||
parser.add_argument('--epochs', default=300, type=int)
|
||||
parser.add_argument('--accum_iter', default=1, type=int)
|
||||
parser.add_argument('--remark', default='model768', help='model_remark')
|
||||
parser.add_argument('--save_every_epoch', default=1, type=int)
|
||||
parser.add_argument(
|
||||
'--model', default='moco_normwear_base', type=str, metavar='MODEL')
|
||||
parser.add_argument('--accum_iter', default=1, type=int, help='Accumulate gradient iterations')
|
||||
parser.add_argument('--save_every_epoch', default=10, type=int) # 建议调大一点,每轮都存太占空间
|
||||
parser.add_argument('--remark', default='hfr_base', help='Experiment remark')
|
||||
|
||||
# --- 优化器参数 ---
|
||||
parser.add_argument('--blr', type=float, default=1e-3, metavar='LR', help='base learning rate')
|
||||
parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR')
|
||||
parser.add_argument('--weight_decay', type=float, default=0.05)
|
||||
parser.add_argument('--warmup_epochs', type=int, default=20, metavar='N') # HFR 可能需要更长的 warmup
|
||||
parser.add_argument('--clip_grad', type=float, default=1.0, help='Clip gradient norm') # HFR 建议设为 1.0
|
||||
|
||||
# --- 模型架构参数 (HFR & MAE) ---
|
||||
parser.add_argument('--model', default='normwear_hfr', type=str, metavar='MODEL')
|
||||
parser.add_argument('--img_size', default=(387, 65), nargs=2, type=int)
|
||||
parser.add_argument('--patch_size', type=int, default=(9, 5), nargs=2)
|
||||
parser.add_argument('--in_chans', type=int, default=3)
|
||||
@@ -63,50 +52,47 @@ def get_args_parser():
|
||||
parser.add_argument('--depth', type=int, default=12)
|
||||
parser.add_argument('--num_heads', type=int, default=12)
|
||||
parser.add_argument('--mlp_ratio', type=float, default=4.0)
|
||||
parser.add_argument('--fuse_freq', type=int, default=2)
|
||||
parser.add_argument('--use_cwt', type=bool, default=True)
|
||||
parser.add_argument('--use_meanpooling', type=int, default=0)
|
||||
# [新增] MAE解码器参数
|
||||
parser.add_argument('--decoder_embed_dim', default=512,
|
||||
type=int, help='Dimensionality of decoder embeddings')
|
||||
parser.add_argument('--decoder_depth', default=8, type=int,
|
||||
help='Number of layers in the decoder')
|
||||
parser.add_argument('--decoder_num_heads', default=16,
|
||||
type=int, help='Number of attention heads in the decoder')
|
||||
|
||||
# [HFR 特有参数]
|
||||
parser.add_argument('--fluid_kernel_size', type=int, default=3, help='Kernel size for HFR fluid layer')
|
||||
|
||||
# [MAE 解码器参数]
|
||||
parser.add_argument('--decoder_embed_dim', default=512, type=int)
|
||||
parser.add_argument('--decoder_depth', default=8, type=int)
|
||||
parser.add_argument('--decoder_num_heads', default=16, type=int)
|
||||
|
||||
# [MAE 掩码与重建参数]
|
||||
parser.add_argument('--mask_ratio', default=0.75, type=float, help='Ratio of patches to mask')
|
||||
parser.add_argument('--norm_pix_loss', action='store_true', help='Normalize pixels for loss calculation')
|
||||
parser.set_defaults(norm_pix_loss=False)
|
||||
parser.add_argument('--modality_dropout', type=float, default=0.15, help='Prob of dropping a modality')
|
||||
parser.add_argument('--loss_weight_1d_token', type=float, default=0.3)
|
||||
parser.add_argument('--loss_weight_1d_signal', type=float, default=0.3)
|
||||
|
||||
# learning rate schedule args
|
||||
parser.add_argument('--weight_decay', type=float, default=0.1)
|
||||
parser.add_argument('--lr', type=float, default=None, metavar='LR')
|
||||
parser.add_argument('--min_lr', type=float, default=0., metavar='LR')
|
||||
parser.add_argument('--warmup_epochs', type=int, default=8, metavar='N')
|
||||
parser.add_argument('--clip_grad', type=float, default=None,
|
||||
help='Clip gradient norm (default: None, no clipping)')
|
||||
# device args
|
||||
# --- 数据集参数 ---
|
||||
parser.add_argument('--data_path', default='/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/', type=str)
|
||||
parser.add_argument('--output_dir', default="./output_dir", type=str)
|
||||
parser.add_argument('--log_dir', default='./output_dir/log', type=str)
|
||||
parser.add_argument('--dataset_stride', type=int, default=150, help='Stride for sliding window dataset')
|
||||
parser.add_argument('--num_workers', default=8, type=int)
|
||||
parser.add_argument('--pin_mem', action='store_true')
|
||||
parser.set_defaults(pin_mem=True)
|
||||
|
||||
# --- 硬件与分布式参数 ---
|
||||
parser.add_argument('--device', default='cuda', type=str)
|
||||
parser.add_argument('--seed', default=42, type=int)
|
||||
parser.add_argument('--resume', default='', type=str)
|
||||
parser.add_argument('--is_test', default=0, type=int)
|
||||
parser.add_argument('--start_epoch', default=0, type=int, metavar='N')
|
||||
|
||||
# dataset args
|
||||
parser.add_argument(
|
||||
'--data_path', default='/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/', type=str)
|
||||
parser.add_argument(
|
||||
'--output_dir', default="/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/result", type=str)
|
||||
parser.add_argument(
|
||||
'--log_dir', default='/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/result/log', type=str)
|
||||
parser.add_argument('--num_workers', default=4, type=int)
|
||||
parser.add_argument('--pin_mem', action='store_true')
|
||||
parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem')
|
||||
parser.set_defaults(pin_mem=True)
|
||||
|
||||
# distribute args
|
||||
parser.add_argument('--world_size', default=1, type=int)
|
||||
parser.add_argument('--local_rank', default=-1, type=int)
|
||||
parser.add_argument('--dist_on_itp', action='store_true')
|
||||
parser.add_argument('--dist_url', default='env://', type=str)
|
||||
return parser
|
||||
|
||||
# --- 精度控制 ---
|
||||
parser.add_argument('--precision', default='bf16', type=str, choices=['fp32', 'fp16', 'bf16'],
|
||||
help='Training precision. bf16 recommended for A100/H100/RTX30+')
|
||||
|
||||
return parser
|
||||
|
||||
def main(args):
|
||||
misc.init_distributed_mode(args)
|
||||
@@ -115,33 +101,35 @@ def main(args):
|
||||
|
||||
device = torch.device(args.device)
|
||||
|
||||
# --- [修改] 根据选择的精度设置 dtype 和检查硬件支持 ---
|
||||
# --- 精度设置 ---
|
||||
if args.precision == 'bf16':
|
||||
if not torch.cuda.is_bf16_supported():
|
||||
raise SystemExit(
|
||||
"BF16 is not supported on this device, please use --precision fp16 or fp32.")
|
||||
dtype = torch.bfloat16
|
||||
print("Warning: BF16 not supported, falling back to FP16.")
|
||||
args.precision = 'fp16'
|
||||
dtype = torch.float16
|
||||
else:
|
||||
dtype = torch.bfloat16
|
||||
elif args.precision == 'fp16':
|
||||
dtype = torch.float16
|
||||
else:
|
||||
dtype = torch.float32
|
||||
|
||||
if misc.is_main_process():
|
||||
print(f"Using precision: {args.precision} with dtype: {dtype}")
|
||||
print(f"🚀 Using precision: {args.precision} ({dtype})")
|
||||
|
||||
# --- 随机种子 ---
|
||||
seed = args.seed + misc.get_rank()
|
||||
torch.manual_seed(seed)
|
||||
np.random.seed(seed)
|
||||
cudnn.benchmark = True
|
||||
|
||||
# [修改] 创建数据集时传入窗口化参数
|
||||
# --- 数据集构建 ---
|
||||
dataset_train = PretrainDataset(
|
||||
data_dir=args.data_path,
|
||||
dataset_names=["temp"], # 您可以按需修改
|
||||
is_test=args.is_test,
|
||||
dataset_names=["temp"], # 建议参数化
|
||||
is_test=0, # Pretrain 始终不是 test
|
||||
window_size=args.img_size[0],
|
||||
# cache_name="pretrain_windows_ds527821_ws387_s100",
|
||||
stride=150 # 建议将此值也设为命令行参数
|
||||
stride=args.dataset_stride # 使用参数控制
|
||||
)
|
||||
|
||||
if args.distributed:
|
||||
@@ -153,6 +141,7 @@ def main(args):
|
||||
else:
|
||||
sampler_train = torch.utils.data.RandomSampler(dataset_train)
|
||||
|
||||
# --- 日志记录器 ---
|
||||
if misc.is_main_process() and args.log_dir is not None:
|
||||
log_dir = os.path.join(args.log_dir, args.remark)
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
@@ -173,75 +162,74 @@ def main(args):
|
||||
drop_last=True,
|
||||
)
|
||||
|
||||
# --- 模型初始化 (HFR Version) ---
|
||||
model = NormWear(
|
||||
img_size=(387, 65),
|
||||
patch_size=(9, 5),
|
||||
in_chans=3,
|
||||
img_size=args.img_size,
|
||||
patch_size=args.patch_size,
|
||||
in_chans=args.in_chans,
|
||||
embed_dim=args.embed_dim,
|
||||
depth=args.depth,
|
||||
num_heads=args.num_heads,
|
||||
decoder_embed_dim=args.decoder_embed_dim,
|
||||
decoder_depth=args.decoder_depth,
|
||||
decoder_num_heads=args.decoder_num_heads,
|
||||
mlp_ratio=4.0,
|
||||
mlp_ratio=args.mlp_ratio,
|
||||
# MAE 相关
|
||||
modality_dropout_prob=args.modality_dropout,
|
||||
use_hybrid_embed=True, # MAE强依赖HybridEmbed
|
||||
nvar=args.nvar # 确保传递n_vars
|
||||
loss_weight_1d_token=args.loss_weight_1d_token,
|
||||
loss_weight_1d_signal=args.loss_weight_1d_signal,
|
||||
nvar=args.nvar,
|
||||
# HFR 相关
|
||||
fluid_kernel_size=args.fluid_kernel_size
|
||||
).to(device)
|
||||
|
||||
model.to(device)
|
||||
model_without_ddp = model
|
||||
|
||||
if args.distributed:
|
||||
model = torch.nn.parallel.DistributedDataParallel(
|
||||
model, device_ids=[args.gpu], find_unused_parameters=True)
|
||||
model, device_ids=[args.gpu], find_unused_parameters=True) # HFR 可能需要 find_unused_parameters=False 如果图是静态的
|
||||
model_without_ddp = model.module
|
||||
|
||||
# --- 学习率与优化器 ---
|
||||
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
|
||||
if args.lr is None:
|
||||
args.lr = args.blr * eff_batch_size / 256
|
||||
|
||||
if misc.is_main_process():
|
||||
print(
|
||||
f"base lr: {args.blr:.2e}, actual lr: {args.lr:.2e}, effective batch size: {eff_batch_size}")
|
||||
print(f"base lr: {args.blr:.2e}, actual lr: {args.lr:.2e}, effective batch size: {eff_batch_size}")
|
||||
|
||||
# HFR 对参数比较敏感,AdamW 是个好选择,但 beta2 可以稍微调低一点 (e.g., 0.95) 如果训练不稳定
|
||||
optimizer = torch.optim.AdamW(
|
||||
model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
|
||||
|
||||
# --- [修改] 条件性地创建 GradScaler ---
|
||||
# 只有在 fp16 模式下才需要 GradScaler,bf16 和 fp32 不需要
|
||||
loss_scaler = NativeScalerWithGradNormCount() if dtype == torch.float16 else None
|
||||
if misc.is_main_process():
|
||||
if loss_scaler:
|
||||
print("Using custom NativeScaler for FP16 training.")
|
||||
else:
|
||||
print("GradScaler is disabled for BF16/FP32 training.")
|
||||
|
||||
# --- Loss Scaler ---
|
||||
# BF16 不需要 scaler,FP16 需要
|
||||
loss_scaler = NativeScalerWithGradNormCount() if args.precision == 'fp16' else None
|
||||
|
||||
misc.load_model(args=args, model_without_ddp=model_without_ddp,
|
||||
optimizer=optimizer, loss_scaler=loss_scaler)
|
||||
|
||||
print(f"Start training for {args.epochs} epochs on rank {misc.get_rank()}")
|
||||
print(f"🔥 Start training for {args.epochs} epochs on rank {misc.get_rank()}")
|
||||
start_time = time.time()
|
||||
|
||||
for epoch in range(args.start_epoch, args.epochs):
|
||||
if args.distributed:
|
||||
data_loader_train.sampler.set_epoch(epoch)
|
||||
|
||||
# [修改] 将 dtype 传入训练引擎
|
||||
train_stats = train_one_epoch(
|
||||
model, data_loader_train,
|
||||
optimizer, device, epoch, loss_scaler,
|
||||
log_writer=log_writer,
|
||||
args=args,
|
||||
dtype=dtype # 传入选择的精度
|
||||
dtype=dtype # 传入精度类型
|
||||
)
|
||||
|
||||
# 保存逻辑
|
||||
if args.output_dir and (epoch % args.save_every_epoch == 0 or epoch + 1 == args.epochs):
|
||||
misc.save_model(
|
||||
args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer,
|
||||
loss_scaler=loss_scaler, epoch=epoch) # [修改] 保存当前epoch
|
||||
loss_scaler=loss_scaler, epoch=epoch)
|
||||
|
||||
log_stats = {**{f'train_{k}': v for k,
|
||||
v in train_stats.items()}, 'epoch': epoch}
|
||||
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, 'epoch': epoch}
|
||||
|
||||
if args.output_dir and misc.is_main_process():
|
||||
if log_writer is not None:
|
||||
@@ -253,10 +241,9 @@ def main(args):
|
||||
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
||||
print(f'Training time {total_time_str} on rank {misc.get_rank()}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
args = get_args_parser()
|
||||
args = args.parse_args()
|
||||
if args.output_dir:
|
||||
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
|
||||
main(args)
|
||||
main(args)
|
||||
Reference in new issue
Block a user