From f986ce88e0c78091fd589af5e19533a82cda3ce2 Mon Sep 17 00:00:00 2001 From: yilv <874448085@qq.com> Date: Tue, 9 Jun 2026 11:57:58 +0800 Subject: [PATCH] Refactor dataset and preprocessing modules; add GPU-based preprocessing - Simplified the PhysioSignalDataset class by removing redundant comments and improving code readability. - Introduced GPUPreprocessor for efficient signal processing using PyTorch, including bandpass filtering and feature extraction. - Updated training script to integrate GPU preprocessing, enhancing performance during training. - Adjusted model forward method to accommodate new statistics prediction logic. --- CWT_MAE_v3/dataset.py | 464 ++++++++++++++--------------------- CWT_MAE_v3/gpu_preprocess.py | 291 ++++++++++++++++++++++ CWT_MAE_v3/model.py | 68 +++-- CWT_MAE_v3/train.py | 54 ++-- 4 files changed, 534 insertions(+), 343 deletions(-) create mode 100644 CWT_MAE_v3/gpu_preprocess.py diff --git a/CWT_MAE_v3/dataset.py b/CWT_MAE_v3/dataset.py index 7e25b9c..9612683 100644 --- a/CWT_MAE_v3/dataset.py +++ b/CWT_MAE_v3/dataset.py @@ -1,282 +1,182 @@ -import torch -from torch.utils.data import Dataset -import numpy as np -import json -import os -import random -import pickle -from utils_features import extract_features -from preprocess import preprocess_signal - -class PhysioSignalDataset(Dataset): - def __init__(self, index_file=None, data_source=None, indices=None, signal_len=500, mode='train', - min_std_threshold=1e-4, - max_std_threshold=5000.0, - max_abs_value=1e5, - expected_channels=5, # 1) 将默认通道数参数设为 5 - data_ratio=1.0, # 新增: 数据使用比例 (0.0 - 1.0) - use_sliding_window=False, # 新增: 是否启用滑动窗口 - window_stride=500 # 新增: 滑动窗口步长 - ): - self.signal_len = signal_len - self.mode = mode - self.min_std_threshold = min_std_threshold - self.max_std_threshold = max_std_threshold - self.max_abs_value = max_abs_value - self.expected_channels = expected_channels # 保存期望通道数 - self.use_sliding_window = use_sliding_window - self.window_stride = window_stride - - # 支持直接传入 data_source (list) 和 indices (list) 以避免重复加载 - if data_source is not None: - self.index_data = data_source - elif index_file is not None: - if not os.path.exists(index_file): - raise FileNotFoundError(f"Index file not found: {index_file}") - print(f"Loading index from: {index_file} ...") - with open(index_file, 'r') as f: - self.index_data = json.load(f) - else: - raise ValueError("Must provide either index_file or data_source") - - # 如果指定了 indices,则只使用该子集 - if indices is not None: - self.active_indices = indices - else: - self.active_indices = list(range(len(self.index_data))) - - # 根据 data_ratio 进行采样 - if 0.0 < data_ratio < 1.0: - total_samples = len(self.active_indices) - keep_num = int(total_samples * data_ratio) - # 使用固定 seed 确保可复现性,或者根据 mode 决定 - # 这里简单做顺序截断,或者随机采样 - if mode == 'train': - random.seed(42) - self.active_indices = random.sample(self.active_indices, keep_num) - else: - self.active_indices = self.active_indices[:keep_num] - print(f"[{mode.upper()}] Data Ratio: {data_ratio:.2f} | Using {len(self.active_indices)}/{total_samples} samples.") - - # 预加载所有数据到内存 - unique_paths = list(set(self.index_data[i]['path'] for i in self.active_indices)) - self._cache = {} - from tqdm import tqdm as _tqdm - for path in _tqdm(unique_paths, desc=f"[{mode.upper()}] Loading data into memory"): - with open(path, 'rb') as f: - self._cache[path] = pickle.load(f) - print(f"[{mode.upper()}] Loaded {len(self._cache)} unique files into memory.") - - # 预生成样本索引 (Mapping local_idx -> global_idx) - self.samples = [] - for i in self.active_indices: - item_info = self.index_data[i] - - # 如果开启滑动窗口且 index 中包含长度信息 - if self.use_sliding_window and 'len' in item_info: - total_len = item_info['len'] - if total_len > self.signal_len: - # 计算窗口起始点 - starts = range(0, total_len - self.signal_len + 1, self.window_stride) - for s in starts: - self.samples.append({'idx': i, 'start': s}) - else: - self.samples.append({'idx': i, 'start': 0}) - else: - # 默认行为:每个条目作为一个样本,start 为 None (触发随机或中心裁剪) - self.samples.append({'idx': i, 'start': None}) - - print(f"[{mode.upper()}] Dataset initialized with {len(self.samples)} samples.") - - def __len__(self): - return len(self.samples) - - - def __getitem__(self, idx): - # 重试机制 - for _ in range(3): - try: - sample_info = self.samples[idx] - original_idx = sample_info['idx'] - fixed_start = sample_info['start'] - - item_info = self.index_data[original_idx] - file_path = item_info['path'] - # row_idx = item_info.get('row', 0) # Deprecated - label = item_info.get('label', 0) - - content = self._cache[file_path] - - # [Modified] 直接读取 data,不再使用 row 索引 - raw_signal = content['data'] - - if raw_signal.ndim == 1: - raw_signal = raw_signal[np.newaxis, :] - - if raw_signal.dtype != np.float32: - raw_signal = raw_signal.astype(np.float32) - - num_channels = raw_signal.shape[0] - if num_channels < 1: - print(f"Warning: Sample {original_idx} has {num_channels} channels, skipping...") - idx = random.randint(0, len(self.samples) - 1) - continue - - if np.isnan(raw_signal).any() or np.isinf(raw_signal).any(): - idx = random.randint(0, len(self.samples) - 1) - continue - - if np.max(np.abs(raw_signal)) > self.max_abs_value: - idx = random.randint(0, len(self.samples) - 1) - continue - - # 2. 同步裁剪或填充 (使用固定起始位置或随机起始位置) - processed_signal = self._process_signal(raw_signal, fixed_start) - - # 2.5 带通滤波预处理 (去除高频噪声和基线漂移) - fs = item_info.get('fs', 100) - processed_signal = preprocess_signal(processed_signal, fs=fs, num_channels=num_channels) - - # 计算统计特征 (跨通道聚合) - all_feats = [] - for ch in range(num_channels): - ch_signal = processed_signal[ch:ch+1, :] - ch_stats = extract_features(ch_signal, ch, fs=fs, item_info=item_info) - all_feats.append(ch_stats[:-1]) - stats = np.mean(np.stack(all_feats), axis=0) - age = 0.0 - if item_info is not None and 'age' in item_info: - age = float(item_info['age']) - stats = np.append(stats, [age]) - - # 3. 逐通道质量检查 - std_vals = np.std(processed_signal, axis=1, keepdims=True) # (M, 1) - - # 深度过滤逻辑: - # 1. 检查 std 是否包含 NaN (np.std 在输入包含 NaN 时会返回 NaN) - # 2. 检查是否有任意通道标准差过大 (伪影) - # 3. 检查是否有任意通道标准差过小 (死线/脱落) -> 这里改为 np.any,只要有一个通道不行就换 - if np.isnan(std_vals).any() or \ - np.any(std_vals > self.max_std_threshold) or \ - np.any(std_vals < self.min_std_threshold): - # print(f"Skipping sample {original_idx}: std_vals={std_vals.flatten()}") - idx = random.randint(0, len(self.samples) - 1) - continue - - # 检查标签是否合法 - if not isinstance(label, (int, float)) or np.isnan(label) or np.isinf(label): - label = 0 - - # 4. 逐通道 Z-Score 归一化 (增加稳定性控制) - mean_vals = np.mean(processed_signal, axis=1, keepdims=True) - # 使用稍大的 epsilon 并在归一化后裁剪 - processed_signal = (processed_signal - mean_vals) / (std_vals + 1e-5) - processed_signal = np.clip(processed_signal, -10, 10) # 限制在 [-10, 10] 标准差范围内 - - # Double check for flat signal after normalization (should not happen if std check passed) - if np.abs(processed_signal).max() < 1e-6: - idx = random.randint(0, len(self.samples) - 1) - continue - - # 转为 Tensor - signal_tensor = torch.from_numpy(processed_signal) # (M, L) - stats_tensor = torch.from_numpy(stats) - - return signal_tensor, torch.tensor(label, dtype=torch.long), stats_tensor - - except Exception as e: - print(f"Error loading sample {idx}: {e}") - idx = random.randint(0, len(self.samples) - 1) - continue - - # 兜底:如果重试 3 次依然失败,尝试从数据集开头找一个可能有效的样本 - # 避免返回全零信号导致模型梯度冲击 - print(f"Warning: Fallback triggered for idx {idx} after 3 retries. Attempting to return a safe sample.") - try: - sample_info = self.samples[0] - content = self._cache[self.index_data[sample_info['idx']]['path']] - safe_signal = content['data'] - if safe_signal.ndim == 1: - safe_signal = safe_signal[np.newaxis, :] - if safe_signal.dtype != np.float32: - safe_signal = safe_signal.astype(np.float32) - safe_signal = safe_signal[:, :self.signal_len] - - fs = self.index_data[sample_info['idx']].get('fs', 100) - num_ch = safe_signal.shape[0] - all_feats = [] - for ch in range(num_ch): - ch_signal = safe_signal[ch:ch+1, :] - ch_stats = extract_features(ch_signal, ch, fs=fs, item_info=self.index_data[sample_info['idx']]) - all_feats.append(ch_stats[:-1]) - stats = np.mean(np.stack(all_feats), axis=0) - age = 0.0 - if 'age' in self.index_data[sample_info['idx']]: - age = float(self.index_data[sample_info['idx']]['age']) - stats = np.append(stats, [age]) - - safe_signal = (safe_signal - np.mean(safe_signal, axis=1, keepdims=True)) / (np.std(safe_signal, axis=1, keepdims=True) + 1e-5) - return torch.from_numpy(safe_signal).float(), torch.tensor(0, dtype=torch.long), torch.from_numpy(stats) - except: - fallback_signal = torch.ones((1, self.signal_len), dtype=torch.float32) * 0.01 - fallback_stats = torch.zeros(16, dtype=torch.float32) - return fallback_signal, torch.tensor(0, dtype=torch.long), fallback_stats - - def _process_signal(self, signal, fixed_start=None): - """ - 输入 signal 形状: (M, Current_Len) - 输出 signal 形状: (M, Target_Len) - 保证所有通道使用相同的裁剪区间。 - """ - M, current_len = signal.shape - target_len = self.signal_len - - if current_len == target_len: - return signal - - if current_len > target_len: - if fixed_start is not None: - start = fixed_start - elif self.mode == 'train': - # 随机裁剪:计算一次 start,应用到所有通道 - start = np.random.randint(0, current_len - target_len) - else: - # 中心裁剪 - start = (current_len - target_len) // 2 - - # 切片操作:[:, start:end] - return signal[:, start : start + target_len] - else: - # 零填充 - pad_len = target_len - current_len - # np.pad 格式: ((top, bottom), (left, right)) - # 我们只在时间轴 (axis 1) 的右侧填充 - return np.pad(signal, ((0, 0), (0, pad_len)), 'constant', constant_values=0) - -def multi_channel_collate_fn(batch): - """ - 多通道预训练的 Collate Function,处理不同样本通道数不一致的情况。 - Batch: list of tuples (signal_tensor, label, stats) - signal_tensor shape: (M_i, L) - Output: padded_signals (B, Max_M, L), None, labels (B,), stats (B, 16), channel_mask (B, Max_M) - """ - signals = [item[0] for item in batch] - labels = [item[1] for item in batch] - stats = [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) - 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 - channel_mask[i, :m] = True - - labels = torch.stack(labels) - stats_tensor = torch.stack(stats) - - return padded_signals, None, labels, stats_tensor, channel_mask \ No newline at end of file +import torch +from torch.utils.data import Dataset +import numpy as np +import json +import os +import random +import pickle + + +class PhysioSignalDataset(Dataset): + def __init__(self, index_file=None, data_source=None, indices=None, signal_len=500, mode='train', + min_std_threshold=1e-4, + max_std_threshold=5000.0, + max_abs_value=1e5, + expected_channels=5, + data_ratio=1.0, + use_sliding_window=False, + window_stride=500 + ): + self.signal_len = signal_len + self.mode = mode + self.min_std_threshold = min_std_threshold + self.max_std_threshold = max_std_threshold + self.max_abs_value = max_abs_value + self.expected_channels = expected_channels + self.use_sliding_window = use_sliding_window + self.window_stride = window_stride + + if data_source is not None: + self.index_data = data_source + elif index_file is not None: + if not os.path.exists(index_file): + raise FileNotFoundError(f"Index file not found: {index_file}") + print(f"Loading index from: {index_file} ...") + with open(index_file, 'r') as f: + self.index_data = json.load(f) + else: + raise ValueError("Must provide either index_file or data_source") + + if indices is not None: + self.active_indices = indices + else: + self.active_indices = list(range(len(self.index_data))) + + if 0.0 < data_ratio < 1.0: + total_samples = len(self.active_indices) + keep_num = int(total_samples * data_ratio) + if mode == 'train': + random.seed(42) + self.active_indices = random.sample(self.active_indices, keep_num) + else: + self.active_indices = self.active_indices[:keep_num] + print(f"[{mode.upper()}] Data Ratio: {data_ratio:.2f} | Using {len(self.active_indices)}/{total_samples} samples.") + + # 预加载所有数据到内存 + unique_paths = list(set(self.index_data[i]['path'] for i in self.active_indices)) + self._cache = {} + from tqdm import tqdm as _tqdm + for path in _tqdm(unique_paths, desc=f"[{mode.upper()}] Loading data into memory"): + with open(path, 'rb') as f: + self._cache[path] = pickle.load(f) + print(f"[{mode.upper()}] Loaded {len(self._cache)} unique files into memory.") + + # 预生成样本索引 + self.samples = [] + for i in self.active_indices: + item_info = self.index_data[i] + + if self.use_sliding_window and 'len' in item_info: + total_len = item_info['len'] + if total_len > self.signal_len: + starts = range(0, total_len - self.signal_len + 1, self.window_stride) + for s in starts: + self.samples.append({'idx': i, 'start': s}) + else: + self.samples.append({'idx': i, 'start': 0}) + else: + self.samples.append({'idx': i, 'start': None}) + + print(f"[{mode.upper()}] Dataset initialized with {len(self.samples)} samples.") + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + for _ in range(3): + try: + sample_info = self.samples[idx] + original_idx = sample_info['idx'] + fixed_start = sample_info['start'] + + item_info = self.index_data[original_idx] + file_path = item_info['path'] + label = item_info.get('label', 0) + + content = self._cache[file_path] + raw_signal = content['data'] + + if raw_signal.ndim == 1: + raw_signal = raw_signal[np.newaxis, :] + + if raw_signal.dtype != np.float32: + raw_signal = raw_signal.astype(np.float32) + + num_channels = raw_signal.shape[0] + if num_channels < 1: + idx = random.randint(0, len(self.samples) - 1) + continue + + if np.isnan(raw_signal).any() or np.isinf(raw_signal).any(): + idx = random.randint(0, len(self.samples) - 1) + continue + + if np.max(np.abs(raw_signal)) > self.max_abs_value: + idx = random.randint(0, len(self.samples) - 1) + continue + + processed_signal = self._process_signal(raw_signal, fixed_start) + + if not isinstance(label, (int, float)) or np.isnan(label) or np.isinf(label): + label = 0 + + signal_tensor = torch.from_numpy(processed_signal) # (M, L) + age = float(item_info.get('age', 0.0)) + + return signal_tensor, torch.tensor(label, dtype=torch.long), torch.tensor(age, dtype=torch.float32) + + except Exception as e: + print(f"Error loading sample {idx}: {e}") + idx = random.randint(0, len(self.samples) - 1) + continue + + # 兜底 + fallback_signal = torch.ones((1, self.signal_len), dtype=torch.float32) * 0.01 + return fallback_signal, torch.tensor(0, dtype=torch.long), torch.tensor(0.0, dtype=torch.float32) + + def _process_signal(self, signal, fixed_start=None): + M, current_len = signal.shape + target_len = self.signal_len + + if current_len == target_len: + return signal + + if current_len > target_len: + if fixed_start is not None: + start = fixed_start + elif self.mode == 'train': + start = np.random.randint(0, current_len - target_len) + else: + start = (current_len - target_len) // 2 + return signal[:, start : start + target_len] + else: + pad_len = target_len - current_len + return np.pad(signal, ((0, 0), (0, pad_len)), 'constant', constant_values=0) + + +def multi_channel_collate_fn(batch): + """ + 多通道预训练 Collate Function。 + Input: list of (signal_tensor, label, age) + Output: (padded_signals, labels, ages, channel_mask) + """ + signals = [item[0] for item in batch] + labels = [item[1] for item in batch] + ages = [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) + 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 + channel_mask[i, :m] = True + + labels = torch.stack(labels) + ages = torch.stack(ages) + + return padded_signals, labels, ages, channel_mask diff --git a/CWT_MAE_v3/gpu_preprocess.py b/CWT_MAE_v3/gpu_preprocess.py new file mode 100644 index 0000000..5a57631 --- /dev/null +++ b/CWT_MAE_v3/gpu_preprocess.py @@ -0,0 +1,291 @@ +""" +GPU 批量预处理模块 — 使用 torch.fft 实现带通滤波 + 纯 PyTorch 特征提取。 +替代原有 numpy/scipy 实现,在 GPU 上批量执行以消除 CPU 瓶颈。 +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F +import math + + +TRANSITION_BW = 0.5 + + +def _build_bandpass_mask(n_fft: int, fs: float, low: float, high: float, transition: float = 0.5) -> torch.Tensor: + freqs = torch.fft.rfftfreq(n_fft, d=1.0 / fs) + mask = torch.zeros_like(freqs) + + passband = (freqs >= low) & (freqs <= high) + mask[passband] = 1.0 + + low_trans_start = max(0, low - transition) + low_trans = (freqs >= low_trans_start) & (freqs < low) + if low_trans.any(): + t = (freqs[low_trans] - low_trans_start) / (low - low_trans_start + 1e-10) + mask[low_trans] = 0.5 * (1 - torch.cos(math.pi * t)) + + high_trans_end = min(fs / 2, high + transition) + high_trans = (freqs > high) & (freqs <= high_trans_end) + if high_trans.any(): + t = (freqs[high_trans] - high) / (high_trans_end - high + 1e-10) + mask[high_trans] = 0.5 * (1 + torch.cos(math.pi * t)) + + return mask + + +class GPUPreprocessor(nn.Module): + def __init__(self, signal_len: int = 1000, fs: float = 100.0, num_channels: int = 5, + min_std: float = 1e-4, max_std: float = 5000.0): + super().__init__() + self.signal_len = signal_len + self.fs = fs + self.num_channels = num_channels + self.min_std = min_std + self.max_std = max_std + + self.register_buffer('ecg_mask', _build_bandpass_mask(signal_len, fs, 0.05, 40.0, TRANSITION_BW)) + self.register_buffer('acc_mask', _build_bandpass_mask(signal_len, fs, 0.5, 20.0, TRANSITION_BW)) + self.register_buffer('ppg_mask', _build_bandpass_mask(signal_len, fs, 0.1, 20.0, TRANSITION_BW)) + + nperseg = min(256, signal_len) + self.nperseg = nperseg + self.register_buffer('welch_window', torch.hann_window(nperseg)) + + self.register_buffer('psd_freqs', torch.fft.rfftfreq(nperseg, d=1.0 / fs)) + + def forward(self, signals: torch.Tensor, channel_mask: torch.Tensor, + ages: torch.Tensor = None) -> tuple: + """ + Args: + signals: (B, M, L) raw signals on GPU, float32 + channel_mask: (B, M) bool mask for valid channels + ages: (B,) float ages or None + Returns: + processed: (B, M, L) filtered + normalized signals + stats: (B, 16) feature vector + """ + filtered = self.bandpass_filter(signals, channel_mask) + stats = self.extract_features(filtered, channel_mask, ages) + processed = self.normalize(filtered, channel_mask) + return processed, stats + + def bandpass_filter(self, signals: torch.Tensor, channel_mask: torch.Tensor) -> torch.Tensor: + """ + 对 (B, M, L) 信号按通道类型进行频域带通滤波。 + """ + B, M, L = signals.shape + out = torch.zeros_like(signals) + + if L != self.signal_len: + ecg_mask = _build_bandpass_mask(L, self.fs, 0.05, 40.0, TRANSITION_BW).to(signals.device) + acc_mask = _build_bandpass_mask(L, self.fs, 0.5, 20.0, TRANSITION_BW).to(signals.device) + ppg_mask = _build_bandpass_mask(L, self.fs, 0.1, 20.0, TRANSITION_BW).to(signals.device) + else: + ecg_mask = self.ecg_mask + acc_mask = self.acc_mask + ppg_mask = self.ppg_mask + + if self.num_channels == 5: + channel_masks_map = [ + ([0], ecg_mask), + ([1, 2, 3], acc_mask), + ([4], ppg_mask), + ] + elif self.num_channels == 1: + channel_masks_map = [([0], ecg_mask)] + else: + channel_masks_map = [(list(range(M)), ecg_mask)] + + for ch_indices, freq_mask in channel_masks_map: + valid_indices = [i for i in ch_indices if i < M] + if not valid_indices: + continue + + x = signals[:, valid_indices, :] # (B, num_ch, L) + flat = x.reshape(-1, L) # (B*num_ch, L) + + spectrum = torch.fft.rfft(flat) + spectrum = spectrum * freq_mask.unsqueeze(0) + filtered = torch.fft.irfft(spectrum, n=L) + + out[:, valid_indices, :] = filtered.reshape(B, len(valid_indices), L) + + valid_mask = channel_mask.unsqueeze(-1).float() # (B, M, 1) + out = out * valid_mask + + return out + + def normalize(self, signals: torch.Tensor, channel_mask: torch.Tensor) -> torch.Tensor: + """逐通道 Z-score 归一化 + 质量检查""" + mean = signals.mean(dim=-1, keepdim=True) + std = signals.std(dim=-1, keepdim=True).clamp(min=1e-5) + + normalized = (signals - mean) / std + normalized = normalized.clamp(-10, 10) + + bad_std = (std.squeeze(-1) < self.min_std) | (std.squeeze(-1) > self.max_std) + bad_channels = bad_std & channel_mask + if bad_channels.any(): + normalized[bad_channels] = 0.01 * torch.randn_like(normalized[bad_channels]) + + valid_mask = channel_mask.unsqueeze(-1).float() + normalized = normalized * valid_mask + + return normalized + + def extract_features(self, signals: torch.Tensor, channel_mask: torch.Tensor, + ages: torch.Tensor = None) -> torch.Tensor: + """ + GPU 批量特征提取。输出 (B, 16)。 + 对所有有效通道提取 15 个特征,跨通道取平均后拼接 age。 + """ + B, M, L = signals.shape + + per_channel_feats = self._compute_channel_features(signals) # (B, M, 15) + + mask_expanded = channel_mask.unsqueeze(-1).float() # (B, M, 1) + num_valid = mask_expanded.sum(dim=1).clamp(min=1.0) # (B, 1) + aggregated = (per_channel_feats * mask_expanded).sum(dim=1) / num_valid # (B, 15) + + if ages is not None: + age_feat = ages.unsqueeze(-1).float() # (B, 1) + else: + age_feat = torch.zeros(B, 1, device=signals.device) + + stats = torch.cat([aggregated, age_feat], dim=-1) # (B, 16) + return stats + + def _compute_channel_features(self, signals: torch.Tensor) -> torch.Tensor: + """ + 对每个通道提取 15 个特征。 + 统一用统计 + PSD + 自相关法,不区分 ECG/ACC/PPG(都能提取有意义统计量)。 + """ + B, M, L = signals.shape + x = signals.reshape(B * M, L) # (N, L) + N = x.shape[0] + + feat_mean = x.mean(dim=-1) + feat_var = x.var(dim=-1) + feat_max = x.max(dim=-1).values + feat_min = x.min(dim=-1).values + feat_rms = (x.pow(2).mean(dim=-1)).sqrt() + feat_energy = x.pow(2).mean(dim=-1) + + x_centered = x - feat_mean.unsqueeze(-1) + feat_mad = x_centered.abs().mean(dim=-1) + + std = feat_var.sqrt().clamp(min=1e-8) + x_norm = x_centered / std.unsqueeze(-1) + feat_skew = x_norm.pow(3).mean(dim=-1) + feat_kurt = x_norm.pow(4).mean(dim=-1) - 3.0 + + sign_changes = torch.diff(torch.sign(x), dim=-1) + feat_zcr = (sign_changes != 0).float().sum(dim=-1) / L + + psd, psd_freqs = self._welch_psd(x) # (N, n_freq) + feat_total_power = psd.sum(dim=-1) + feat_peak_power, peak_idx = psd.max(dim=-1) + feat_peak_freq = psd_freqs[peak_idx] + + feat_hr = self._autocorrelation_hr(x) # (N,) + + feat_peak_count = self._estimate_peak_count(x) # (N,) + + features = torch.stack([ + feat_hr, + feat_var, + feat_skew, + feat_kurt, + feat_peak_freq, + feat_peak_power, + feat_total_power, + feat_mad, + feat_mad / 0.02, # activity level + feat_rms, + feat_zcr, + feat_energy, + feat_peak_count, + feat_max, + feat_min, + ], dim=-1) # (N, 15) + + features = torch.nan_to_num(features, nan=0.0, posinf=0.0, neginf=0.0) + return features.reshape(B, M, 15) + + def _welch_psd(self, x: torch.Tensor) -> tuple: + """ + 批量 Welch PSD 估计。 + 输入: (N, L), 输出: (N, n_freq), freqs + """ + N, L = x.shape + nperseg = self.nperseg + window = self.welch_window + + hop = nperseg // 2 + n_segments = max(1, (L - nperseg) // hop + 1) + + segments = x.unfold(dimension=-1, size=nperseg, step=hop) # (N, n_seg, nperseg) + segments = segments[:, :n_segments, :] + + segments = segments * window.unsqueeze(0).unsqueeze(0) + + spectrum = torch.fft.rfft(segments, dim=-1) + psd = (spectrum.real.pow(2) + spectrum.imag.pow(2)) / (self.fs * (window.pow(2).sum())) + + psd = psd.mean(dim=1) # (N, n_freq) + + return psd, self.psd_freqs + + def _autocorrelation_hr(self, x: torch.Tensor) -> torch.Tensor: + """ + 通过自相关估计心率/脉搏率。 + 输出单位: BPM (beats per minute)。 + """ + N, L = x.shape + fs = self.fs + + n_fft = 2 ** (2 * L - 1).bit_length() + X = torch.fft.rfft(x, n=n_fft) + power_spec = X.real.pow(2) + X.imag.pow(2) + autocorr = torch.fft.irfft(power_spec, n=n_fft)[..., :L] + + autocorr_norm = autocorr / (autocorr[:, 0:1].clamp(min=1e-10)) + + min_lag = int(0.3 * fs) # 最小间隔 0.3s → 200 BPM + max_lag = min(int(2.0 * fs), L - 1) # 最大间隔 2.0s → 30 BPM + + if min_lag >= max_lag or max_lag >= L: + return torch.full((N,), 75.0, device=x.device) + + search_region = autocorr_norm[:, min_lag:max_lag] # (N, search_len) + peak_idx = search_region.argmax(dim=-1) # (N,) + peak_lag = peak_idx + min_lag # (N,) + + hr = 60.0 * fs / peak_lag.float().clamp(min=1.0) + hr = hr.clamp(30.0, 200.0) + + return hr + + def _estimate_peak_count(self, x: torch.Tensor) -> torch.Tensor: + """ + 利用局部极大值 + 阈值估计峰值数量。 + """ + N, L = x.shape + min_dist = max(1, int(0.3 * self.fs)) + + std = x.std(dim=-1, keepdim=True).clamp(min=1e-6) + threshold = 0.5 * std # (N, 1) + + above_thresh = (x > threshold).float() + + kernel_size = min_dist * 2 + 1 + padding = kernel_size // 2 + x_pad = F.pad(x, (padding, padding), mode='reflect') + local_max = F.max_pool1d(x_pad.unsqueeze(1), kernel_size=kernel_size, stride=1).squeeze(1) + local_max = local_max[:, :L] + + is_peak = ((x >= local_max - 1e-7) & (x > threshold)).float() + + peak_count = is_peak.sum(dim=-1) + return peak_count diff --git a/CWT_MAE_v3/model.py b/CWT_MAE_v3/model.py index e17892d..c754289 100644 --- a/CWT_MAE_v3/model.py +++ b/CWT_MAE_v3/model.py @@ -751,32 +751,31 @@ class CWT_MAE_RoPE(nn.Module): return imgs.to(dtype=next(self.parameters()).dtype) def forward(self, x, stats_target=None, mask_ratio=None, channel_mask=None): - """ - 参数: - stats_target: (B, 16) tensor, 统计量目标 - """ B = x.shape[0] current_mask_ratio = mask_ratio if mask_ratio is not None else self.mask_ratio - - # 1. 方案二 (Pre-Masking): 在原始 1D 信号上生成 Mask 并进行破坏 + + # 提前计算 target CWT(只算一次,用于 loss) + with torch.no_grad(): + imgs_target = self.prepare_tokens(x) + if current_mask_ratio > 0.0: H_grid, W_grid = self.grid_size noise_w = torch.rand(B, W_grid, device=x.device) ids_shuffle_w = torch.argsort(noise_w, dim=1) len_keep_w = int(W_grid * (1 - current_mask_ratio)) ids_keep_w = ids_shuffle_w[:, :len_keep_w] - + mask_w_bool = torch.zeros(B, W_grid, device=x.device) - mask_w_bool.scatter_(1, ids_keep_w, 1.0) # 1 为保留,0 为丢弃 - + mask_w_bool.scatter_(1, ids_keep_w, 1.0) + M_dim = x.shape[1] if x.dim() == 3 else 1 L_dim = x.shape[-1] - + mask_raw = mask_w_bool.unsqueeze(1).unsqueeze(-1).repeat(1, M_dim, 1, self.patch_size_time) mask_raw = mask_raw.reshape(B, M_dim, W_grid * self.patch_size_time) if mask_raw.shape[-1] != L_dim: mask_raw = mask_raw[..., :L_dim] - + if x.dim() == 2: x_exp = x.unsqueeze(1) x_visible = x_exp * mask_raw @@ -787,48 +786,42 @@ class CWT_MAE_RoPE(nn.Module): x_visible = x * mask_raw local_mean = x_visible.sum(dim=-1, keepdim=True) / (mask_raw.sum(dim=-1, keepdim=True) + 1e-8) x_masked = x_visible + local_mean * (1 - mask_raw) + + imgs_input = self.prepare_tokens(x_masked) else: x_masked = x noise_w = None + # mask_ratio == 0 时,输入 == 原始,复用 target CWT + imgs_input = imgs_target - # 2. 对被破坏的信号做 CWT (作为 Encoder 输入) - imgs_input = self.prepare_tokens(x_masked) latent, mask, ids, M = self.forward_encoder(x_masked, imgs_input, mask_ratio=mask_ratio, noise_w=noise_w) - - # 3. Decoder + + # Decoder decoder_features = self.forward_decoder(latent, ids, M) pred_spec = self.decoder_pred_spec(decoder_features) - - # 4. 对未被破坏的原始信号做 CWT (作为 Loss 目标) - with torch.no_grad(): - imgs_target = self.prepare_tokens(x) - + loss_spec = self.forward_loss_spec(imgs_target, pred_spec, mask, channel_mask) - + B_dec, M_dec, N, D = decoder_features.shape H_grid, W_grid = self.grid_size feat_2d = decoder_features.reshape(B_dec * M_dec, N, D).transpose(1, 2).reshape(B_dec * M_dec, D, H_grid, W_grid) - - feat_time_agg = self.time_reducer[0](feat_2d) - feat_time_agg = self.time_reducer[1](feat_time_agg) - + + feat_time_agg = self.time_reducer[0](feat_2d) + feat_time_agg = self.time_reducer[1](feat_time_agg) + feat_time_agg = feat_time_agg.squeeze(2).transpose(1, 2) - feat_time_agg = self.time_reducer[2](feat_time_agg) - + feat_time_agg = self.time_reducer[2](feat_time_agg) + pred_time = self.time_pred(feat_time_agg).flatten(1).reshape(B_dec, M_dec, -1) - - # 时间域重构也是预测原始未被破坏的信号 x + loss_time = self.forward_loss_time(x, pred_time, mask, channel_mask) - + loss = loss_spec + self.time_loss_weight * loss_time loss_dict = {'loss_spec': loss_spec, 'loss_time': loss_time} - # 【新增】统计特征预测 - # 编码器输出 latent 形状为 (B, M * len_keep, D) - # 我们进行全局平均池化 - latent_pooled = latent.mean(dim=1) # (B, D) - pred_stats = self.stats_pred_head(latent_pooled) # (B, 16) - + latent_pooled = latent.mean(dim=1) + pred_stats = self.stats_pred_head(latent_pooled) + if stats_target is not None: stats_target = stats_target.float() if self.training: @@ -860,5 +853,4 @@ class CWT_MAE_RoPE(nn.Module): loss = loss + self.contrast_loss_weight * loss_contrast loss_dict['loss_contrast'] = loss_contrast - return loss, loss_dict, pred_spec, pred_time, imgs_target, mask, latent, pred_stats - + return loss, loss_dict, pred_spec, pred_time, imgs_target, mask, latent, pred_stats \ No newline at end of file diff --git a/CWT_MAE_v3/train.py b/CWT_MAE_v3/train.py index 86ebe33..faf6240 100644 --- a/CWT_MAE_v3/train.py +++ b/CWT_MAE_v3/train.py @@ -20,6 +20,7 @@ from torch.utils.data import DataLoader, DistributedSampler from torch.amp import autocast, GradScaler from muon import Muon +from gpu_preprocess import GPUPreprocessor # 允许编译失败时自动回退 import torch._dynamo @@ -60,7 +61,7 @@ def adjust_learning_rate_per_step(optimizer, current_step, total_steps, warmup_s # 5. 训练与验证逻辑 # ------------------------------------------------------------------- def train_one_epoch(model, dataloader, optimizer_muon, optimizer_adamw, scaler, epoch, logger, config, device, start_time_global, - total_steps, warmup_steps, base_lr, min_lr, mask_ratio=None, lr_start_step=0): + total_steps, warmup_steps, base_lr, min_lr, mask_ratio=None, lr_start_step=0, gpu_preprocessor=None): model.train() metric_logger = defaultdict(lambda: SmoothedValue(window_size=20)) metric_logger['loss'] = SmoothedValue(window_size=20, fmt='{median:.4f} ({global_avg:.4f})') @@ -71,27 +72,24 @@ def train_one_epoch(model, dataloader, optimizer_muon, optimizer_adamw, scaler, 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}/{config["train"]["epochs"]}]' num_steps_per_epoch = len(dataloader) accum_iter = config['train'].get('accum_iter', 1) - + # [Optimization] Linear Scaling Rule - # Note: We apply this scaling to the base_lr passed in AFTER dynamic schedule adjustment 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): - # Apply scaling based on effective batch size 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 - - # 优先使用 bfloat16 + amp_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 - + start_time = time.time() - + optimizer_muon.zero_grad(set_to_none=True) optimizer_adamw.zero_grad(set_to_none=True) @@ -99,12 +97,8 @@ def train_one_epoch(model, dataloader, optimizer_muon, optimizer_adamw, scaler, step_start_time = time.time() global_step = epoch * num_steps_per_epoch + step - # 适配返回值格式: (batch, channel_ids, labels, stats, channel_mask) - if len(batch_data) == 5: - batch, channel_ids, labels, stats, channel_mask = batch_data - else: - batch, channel_ids, labels, stats = batch_data - channel_mask = None + # 新格式: (signals, labels, ages, channel_mask) + batch, labels, ages, channel_mask = batch_data # 调整 LR (按 step 调整,考虑 accum_iter) if step % accum_iter == 0: @@ -134,10 +128,15 @@ def train_one_epoch(model, dataloader, optimizer_muon, optimizer_adamw, scaler, # batch shape: (B, M, L) batch = batch.to(device, non_blocking=True) - # labels = labels.to(device, non_blocking=True) # MAE 训练暂不需要标签 + ages = ages.to(device, non_blocking=True) + if channel_mask is not None: + channel_mask = channel_mask.to(device, non_blocking=True) + + # GPU 预处理: 带通滤波 + 特征提取 + Z-score 归一化 + with torch.no_grad(): + batch, stats = gpu_preprocessor(batch.float(), channel_mask, ages) # 混合精度前向传播 - # 在 DDP 模式下,如果不是最后一次累积,使用 no_sync 上下文以减少通信 do_sync = (step + 1) % accum_iter == 0 or (step + 1) == len(dataloader) if isinstance(model, DDP) and not do_sync: @@ -147,11 +146,10 @@ def train_one_epoch(model, dataloader, optimizer_muon, optimizer_adamw, scaler, with context_manager: with autocast('cuda', dtype=amp_dtype, enabled=config['train']['use_amp']): - stats = stats.to(device, non_blocking=True) if channel_mask is not None: channel_mask = channel_mask.to(device, non_blocking=True) loss, loss_dict, _, _, _, _, _, _ = model(batch, stats_target=stats, mask_ratio=mask_ratio, channel_mask=channel_mask) - loss = loss / accum_iter # Normalize loss for accumulation + loss = loss / accum_iter loss_value = loss.item() * accum_iter # Restore for logging loss_spec_val = loss_dict.get('loss_spec', torch.tensor(0.0)).item() @@ -376,7 +374,7 @@ def main(): if is_main_process(): logger.info("torch.compile() is disabled via config.") - model = DDP(model, device_ids=[gpu_id], output_device=gpu_id, find_unused_parameters=True) if dist.is_initialized() else model + model = DDP(model, device_ids=[gpu_id], output_device=gpu_id, find_unused_parameters=False) if dist.is_initialized() else model # 优化器参数分组: 2D 矩阵权重 → Muon, 其余 → AdamW muon_params = [] @@ -405,8 +403,17 @@ def main(): # GradScaler 用于混合精度 scaler = GradScaler(enabled=config['train']['use_amp']) - - # [新增] 梯度累积参数 + + # GPU 预处理器 + gpu_preprocessor = GPUPreprocessor( + signal_len=config['data']['signal_len'], + fs=100.0, + num_channels=5 + ).to(device) + if is_main_process(): + logger.info("GPUPreprocessor initialized on device.") + + # 梯度累积参数 accum_iter = config['train'].get('accum_iter', 1) if is_main_process(): logger.info(f"Gradient Accumulation Steps: {accum_iter}") @@ -467,7 +474,8 @@ def main(): base_lr=current_base_lr, min_lr=min_lr, mask_ratio=current_mask_ratio, - lr_start_step=current_lr_start_step + lr_start_step=current_lr_start_step, + gpu_preprocessor=gpu_preprocessor ) if is_main_process():