""" CWT-JEPA: Joint Embedding Predictive Architecture for Physiological Signals ============================================================================ 基于 CWT-MAE 架构,结合 JEPA 论文最佳实践重构: Tier 1 - 核心架构 (I-JEPA + V-JEPA): - Context Encoder → Target Encoder (EMA) → Predictor - Multi-block Masking (时频域语义块掩码) - 在表征空间预测,非像素空间重建 Tier 2 - 防坍缩正则化 (LeJEPA + VICReg): - SIGReg: 各向同性高斯正则化 (Variance + Covariance) - EMA Target Encoder (动量更新) - Stop-Gradient on Target Branch Tier 3 - 架构优化 (JEPA-WM + IWM): - AdaLN 条件注入 Predictor (通道类型条件渗透所有层) - 轻量 Predictor (6层 vs 原 Decoder 8层) - 可选的 Multi-step Rollout 训练 保留 CWT-MAE 优势: - CWT 时频变换 + 差分信号 - RoPE 旋转位置编码 - TrueFactorizedBlock 时空因子化 Encoder - 通道类型 Embedding - 统计量预测辅助任务 """ import torch import torch.nn as nn import torch.nn.functional as F import math # =================================================================== # Part 1: CWT 模块 (保持与 CWT-MAE 完全一致) # =================================================================== @torch.compiler.disable def create_ricker_wavelets(points: int, scales: torch.Tensor): """创建 Ricker (Mexican Hat) 小波基函数""" scales = scales.float() t = torch.arange(0, points, device=scales.device, dtype=torch.float32) - (points - 1.0) / 2.0 t = t.reshape(1, 1, -1) scales = scales.reshape(-1, 1, 1) pi_factor = math.pi ** 0.25 A = 2 / (torch.sqrt(3 * scales) * pi_factor + 1e-6) wsq = scales ** 2 xsq = t ** 2 mod = (1 - xsq / wsq) gauss = torch.exp(-xsq / (2 * wsq)) wavelets = A * mod * gauss return wavelets @torch.compiler.disable def cwt_ricker(x, scales): """对输入信号执行 Ricker 连续小波变换""" batch_size, sequence_length = x.shape x = x.unsqueeze(1) scales = scales.to(x.device) largest_scale = scales[-1] if torch.onnx.is_in_onnx_export(): wavelet_len_int = 631 else: largest_scale_val = largest_scale.item() seq_len_val = sequence_length if isinstance(sequence_length, int) else sequence_length.item() wavelet_len_int = int(min(10.0 * largest_scale_val, float(seq_len_val))) if wavelet_len_int % 2 == 0: wavelet_len_int += 1 wavelets = create_ricker_wavelets(wavelet_len_int, scales) wavelets = wavelets.to(dtype=x.dtype) pad_len = wavelet_len_int // 2 x_padded = F.pad(x, (pad_len, pad_len), mode='reflect') cwt_output = F.conv1d(x_padded, wavelets) return cwt_output @torch.compiler.disable def cwt_wrap(x, num_scales=64, lowest_scale=0.1, step=1.0, use_diff=True): """ CWT 包装函数:将 1D 信号转为 2D 时频图 支持差分信号 (use_diff=True 时输出 3 通道: 原始 + 一阶 + 二阶导数) """ if x.dim() == 2: x = x.unsqueeze(1) B, M, L = x.shape x_flat = x.reshape(B * M, L) if use_diff: x_pad = F.pad(x_flat, (1, 1), mode='replicate') d1 = (x_pad[:, 2:] - x_pad[:, :-2]) / 2.0 d2 = x_pad[:, 2:] - 2 * x_pad[:, 1:-1] + x_pad[:, :-2] base = x_flat d1_cut = d1[:, :L] d2_cut = d2[:, :L] signals = torch.stack([base, d1_cut, d2_cut], dim=1) else: base = x_flat signals = base.unsqueeze(1) BM, C, _ = signals.shape signals_flat = signals.reshape(BM * C, L) scales = torch.arange(num_scales, device=x.device) * step + lowest_scale cwt_out = cwt_ricker(signals_flat, scales) _, n_scales, _ = cwt_out.shape cwt_out = cwt_out.reshape(B, M, C, n_scales, L) return cwt_out # =================================================================== # Part 2: 基础组件 & RoPE (保持与 CWT-MAE 完全一致) # =================================================================== class RotaryEmbedding(nn.Module): """旋转位置编码 (RoPE) — 单轴版本""" def __init__(self, dim, max_seq_len=6000): super().__init__() self.dim = dim inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim)) self.register_buffer("inv_freq", inv_freq) self.max_seq_len = max_seq_len self._update_cache(max_seq_len) def _update_cache(self, seq_len): self.max_seq_len = seq_len t = torch.arange(seq_len, device=self.inv_freq.device, dtype=self.inv_freq.dtype) freqs = torch.outer(t, self.inv_freq) emb = torch.cat((freqs, freqs), dim=-1) cos_tensor = emb.cos().to(torch.float32) sin_tensor = emb.sin().to(torch.float32) self.register_buffer("cos_cached", cos_tensor, persistent=False) self.register_buffer("sin_cached", sin_tensor, persistent=False) def forward(self, x, pos_ids): if self.cos_cached.device != x.device: self.cos_cached = self.cos_cached.to(x.device) self.sin_cached = self.sin_cached.to(x.device) pos_ids = pos_ids.to(x.device) if torch.onnx.is_in_onnx_export(): cos = self.cos_cached[pos_ids].to(x.dtype) sin = self.sin_cached[pos_ids].to(x.dtype) return cos.unsqueeze(2), sin.unsqueeze(2) seq_len = torch.max(pos_ids) + 1 with torch.no_grad(): if seq_len > self.max_seq_len: new_len = (seq_len * 3 // 2).int().item() self._update_cache(new_len) cos = self.cos_cached[pos_ids].to(device=x.device, dtype=x.dtype, non_blocking=True) sin = self.sin_cached[pos_ids].to(device=x.device, dtype=x.dtype, non_blocking=True) return cos.unsqueeze(2), sin.unsqueeze(2) class RotaryEmbedding2D(nn.Module): """ 2D 旋转位置编码: 将 head_dim 拆成两半,分别编码 freq 和 time 轴。 类似 ViT 2D RoPE 做法,保证时频两个维度的位置信息独立编码。 """ def __init__(self, dim, max_seq_len_freq=100, max_seq_len_time=6000): super().__init__() assert dim % 4 == 0, f"dim must be divisible by 4 for 2D RoPE, got {dim}" half_dim = dim // 2 self.rope_freq = RotaryEmbedding(half_dim, max_seq_len=max_seq_len_freq) self.rope_time = RotaryEmbedding(half_dim, max_seq_len=max_seq_len_time) def forward(self, x, freq_ids, time_ids): """ x: (B, N, D) — 用于推断 device/dtype freq_ids: (B, N) — 频率轴位置索引 time_ids: (B, N) — 时间轴位置索引 Returns: cos (B,N,1,D), sin (B,N,1,D) — 拼接后的 2D RoPE """ cos_h, sin_h = self.rope_freq(x, freq_ids) # (B,N,1,D/2) cos_w, sin_w = self.rope_time(x, time_ids) # (B,N,1,D/2) cos = torch.cat([cos_h, cos_w], dim=-1) # (B,N,1,D) sin = torch.cat([sin_h, sin_w], dim=-1) # (B,N,1,D) return cos, sin def apply_rotary_pos_emb(q, k, cos, sin): """应用 RoPE 到 query 和 key""" def rotate_half(x): x1, x2 = x.chunk(2, dim=-1) return torch.cat((-x2, x1), dim=-1) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed class RoPEAttention(nn.Module): """带 RoPE 的多头自注意力""" def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): super().__init__() self.num_heads = num_heads self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x, rope_cos=None, rope_sin=None): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2] if rope_cos is not None and rope_sin is not None: q, k = apply_rotary_pos_emb(q, k, rope_cos, rope_sin) q, k, v = q.transpose(1, 2).contiguous(), k.transpose(1, 2).contiguous(), v.transpose(1, 2).contiguous() dropout_val = float(self.attn_drop.p) if self.training else 0.0 x = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_val) x = x.transpose(1, 2).contiguous().reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class DecomposedPatchEmbed(nn.Module): """2D 分解 Patch Embedding (频率×时间)""" def __init__(self, img_size=(64, 500), patch_size=(4, 50), in_chans=3, embed_dim=768, norm_layer=None): super().__init__() self.img_size = img_size self.patch_size = patch_size self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) self.num_patches = self.grid_size[0] * self.grid_size[1] self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() def forward(self, x): x = self.proj(x) x = x.flatten(2).transpose(1, 2).contiguous() x = self.norm(x) return x class RawSignalPatchEmbed(nn.Module): """原始信号 1D Patch Embedding""" def __init__(self, patch_size_time=50, embed_dim=768, norm_layer=None): super().__init__() self.proj = nn.Conv1d(1, embed_dim, kernel_size=patch_size_time, stride=patch_size_time) self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() def forward(self, x): x = self.proj(x) x = x.transpose(1, 2) x = self.norm(x) return x # =================================================================== # Part 3: Encoder Blocks (保持与 CWT-MAE 完全一致) # =================================================================== class TrueFactorizedBlock(nn.Module): """ 时空因子化 Transformer Block - Intra-modality Spatial-Temporal Attention (RoPE) - Cross-Channel Attention (多通道时) - MLP """ def __init__(self, dim, num_heads, mlp_ratio=4., drop=0., norm_layer=nn.LayerNorm): super().__init__() self.norm_spatial_temporal = norm_layer(dim) self.spatial_temporal_attn = RoPEAttention(dim, num_heads=num_heads, proj_drop=drop) self.norm_channel = norm_layer(dim) self.temporal_smooth = nn.Conv1d(dim, dim, kernel_size=3, padding=1, groups=dim) self.channel_attn = RoPEAttention(dim, num_heads=num_heads, proj_drop=drop) self.norm_mlp = norm_layer(dim) self.mlp = nn.Sequential( nn.Linear(dim, int(dim * mlp_ratio)), nn.GELU(), nn.Dropout(drop), nn.Linear(int(dim * mlp_ratio), dim), nn.Dropout(drop) ) def forward(self, x, M, N, rope_cos=None, rope_sin=None): B, MN, D = x.shape # --- 1. Intra-modality Spatial-Temporal Attention --- x_time = x.contiguous().reshape(B * M, N, D) if rope_cos is not None and rope_sin is not None: # rope_cos/sin: (B, N, 1, head_dim) → repeat M times → (B*M, N, 1, head_dim) cos_t = rope_cos.repeat_interleave(M, dim=0) sin_t = rope_sin.repeat_interleave(M, dim=0) else: cos_t, sin_t = None, None x_time = x_time + self.spatial_temporal_attn(self.norm_spatial_temporal(x_time), cos_t, sin_t) # --- 2. Cross-Channel Attention (M>1 时) --- if M > 1: x_c = x_time.reshape(B, M, N, D) x_channel = x_c.transpose(1, 2).contiguous().reshape(B * N, M, D) attn_out = self.channel_attn(self.norm_channel(x_channel)) x_c = x_c + attn_out.reshape(B, N, M, D).transpose(1, 2) x = x_c.reshape(B, MN, D) else: x = x_time.reshape(B, MN, D) # --- 3. MLP --- x = x + self.mlp(self.norm_mlp(x)) return x class StandardBlock(nn.Module): """标准 Transformer Block (用于 Predictor)""" def __init__(self, dim, num_heads, mlp_ratio=4., drop=0., norm_layer=nn.LayerNorm): super().__init__() self.norm1 = norm_layer(dim) self.attn = RoPEAttention(dim, num_heads=num_heads, proj_drop=drop) self.norm2 = norm_layer(dim) self.mlp = nn.Sequential( nn.Linear(dim, int(dim * mlp_ratio)), nn.GELU(), nn.Dropout(drop), nn.Linear(int(dim * mlp_ratio), dim), nn.Dropout(drop) ) def forward(self, x, rope_cos=None, rope_sin=None): x = x + self.attn(self.norm1(x), rope_cos, rope_sin) x = x + self.mlp(self.norm2(x)) return x # =================================================================== # Part 4: AdaLN Predictor Block (Tier 3 - 来自 JEPA-WM) # =================================================================== class AdaLNBlock(nn.Module): """ Adaptive Layer Normalization Transformer Block 条件信息 (通道类型) 通过 AdaLN 注入 Predictor 所有层 相比简单 Embedding 加和,AdaLN 让条件信息渗透更深 """ def __init__(self, dim, num_heads, cond_dim, mlp_ratio=4., drop=0., norm_layer=nn.LayerNorm): super().__init__() self.norm1 = norm_layer(dim) self.attn = RoPEAttention(dim, num_heads=num_heads, proj_drop=drop) self.norm2 = norm_layer(dim) self.mlp = nn.Sequential( nn.Linear(dim, int(dim * mlp_ratio)), nn.GELU(), nn.Dropout(drop), nn.Linear(int(dim * mlp_ratio), dim), nn.Dropout(drop) ) # AdaLN 条件投影: cond → (scale1, shift1, scale2, shift2) self.ada_linear = nn.Sequential( nn.SiLU(), nn.Linear(cond_dim, dim * 4) ) # 零初始化最后一层,确保训练初期 Predictor 接近恒等映射 nn.init.zeros_(self.ada_linear[1].weight) nn.init.zeros_(self.ada_linear[1].bias) def forward(self, x, cond, rope_cos=None, rope_sin=None): # cond: (B, cond_dim) ada_params = self.ada_linear(cond) # (B, dim*4) scale1, shift1, scale2, shift2 = ada_params.chunk(4, dim=-1) # 广播到序列维度 scale1 = scale1.unsqueeze(1) + 1.0 # 残差初始化: scale ≈ 1 shift1 = shift1.unsqueeze(1) # 残差初始化: shift ≈ 0 scale2 = scale2.unsqueeze(1) + 1.0 shift2 = shift2.unsqueeze(1) # Attention + AdaLN x = x + self.attn(scale1 * self.norm1(x) + shift1, rope_cos, rope_sin) # MLP + AdaLN x = x + self.mlp(scale2 * self.norm2(x) + shift2) return x # =================================================================== # Part 5: Multi-Block Masking (Tier 1 - 来自 I-JEPA) # =================================================================== def sample_block_mask(grid_h, grid_w, num_blocks, scale_range, aspect_ratio_range, device): """ 采样多个语义块作为 Target Blocks 参考 I-JEPA multi-block masking 策略 Args: grid_h, grid_w: 时频网格大小 num_blocks: target block 数量 scale_range: (min_scale, max_scale) 块大小占网格比例 aspect_ratio_range: (min_ar, max_ar) 宽高比范围 Returns: mask: (grid_h, grid_w) bool tensor, True = target (被 mask), False = context """ mask = torch.zeros(grid_h, grid_w, dtype=torch.bool, device=device) for _ in range(num_blocks): # 随机采样块大小 scale = scale_range[0] + torch.rand(1, device=device).item() * (scale_range[1] - scale_range[0]) aspect_ratio = aspect_ratio_range[0] + torch.rand(1, device=device).item() * (aspect_ratio_range[1] - aspect_ratio_range[0]) # 块面积 area = scale * grid_h * grid_w block_h = int(math.sqrt(area / aspect_ratio)) block_w = int(math.sqrt(area * aspect_ratio)) # 限制块大小 block_h = max(1, min(block_h, grid_h)) block_w = max(1, min(block_w, grid_w)) # 随机采样块位置 top = torch.randint(0, grid_h - block_h + 1, (1,), device=device).item() left = torch.randint(0, grid_w - block_w + 1, (1,), device=device).item() mask[top:top + block_h, left:left + block_w] = True return mask def multi_block_masking(x, mask_ratio, grid_h, grid_w, num_target_blocks=4, scale_range=(0.15, 0.25), aspect_ratio_range=(0.75, 1.5)): """ Multi-block Masking: 共享 mask 版本 (I-JEPA 原版做法) 所有样本和通道共享同一个 mask,消除 padding,简化 loss 计算。 Args: x: (B, M, N, D) - 所有 patches mask_ratio: 总 mask 比例 (target 占整体比例) grid_h, grid_w: 时频网格尺寸 num_target_blocks: target block 数量 scale_range: 块大小范围 aspect_ratio_range: 宽高比范围 Returns: context_tokens: (B, M, N_context, D) — 无需 padding context_mask: (N,) bool, True = context (共享) target_positions: (N_target,) — target 在网格中的索引 (共享) """ B, M, N, D = x.shape device = x.device # 共享 mask: rank 0 采样后 broadcast 到所有 rank (DDP 安全) if torch.distributed.is_initialized(): if torch.distributed.get_rank() == 0: target_mask_2d = sample_block_mask( grid_h, grid_w, num_target_blocks, scale_range, aspect_ratio_range, device ) target_mask = target_mask_2d.flatten() else: target_mask = torch.empty(grid_h * grid_w, dtype=torch.bool, device=device) torch.distributed.broadcast(target_mask, src=0) else: target_mask_2d = sample_block_mask( grid_h, grid_w, num_target_blocks, scale_range, aspect_ratio_range, device ) target_mask = target_mask_2d.flatten() # 裁剪/补充到目标比例 (上下限保护) target_indices = target_mask.nonzero(as_tuple=True)[0] context_indices = (~target_mask).nonzero(as_tuple=True)[0] n_target_wanted = max(1, int(N * mask_ratio)) if len(target_indices) > int(n_target_wanted * 1.5): # 超过上限: 随机裁剪 keep = target_indices[torch.randperm(len(target_indices), device=device)[:n_target_wanted]] target_mask = torch.zeros(N, dtype=torch.bool, device=device) target_mask[keep] = True elif len(target_indices) < int(n_target_wanted * 0.5): # 低于下限: 从 context 中随机补充 deficit = n_target_wanted - len(target_indices) extra = context_indices[torch.randperm(len(context_indices), device=device)[:deficit]] target_mask[extra] = True context_mask = ~target_mask # (N,) True = context target_positions = target_mask.nonzero(as_tuple=True)[0] # (N_target,) context_indices = context_mask.nonzero(as_tuple=True)[0] # (N_context,) # 向量化 gather: 只 gather context (target 由 encode_target_full + gather 处理) context_tokens = x[:, :, context_indices, :] return context_tokens, context_mask, target_positions # =================================================================== # Part 6: SIGReg Loss (Tier 2 - 来自 LeJEPA + VICReg) # =================================================================== def sigreg_loss(z, lambda_var=1.0, lambda_cov=1.0, gamma=1.0, eps=1e-4): """ Sketched Isotropic Gaussian Regularization (SIGReg) 将嵌入推向各向同性高斯分布 N(0, I) 结合 LeJEPA 理论 + VICReg 实现: - Variance term: 保持每维方差 > gamma (防坍缩到常数) - Covariance term: 去相关不同维度 (防维度坍缩) Args: z: (B, D) 嵌入向量 lambda_var: 方差正则权重 lambda_cov: 协方差正则权重 gamma: 目标标准差 (默认 1.0 对应 N(0,1)) eps: 数值稳定小量 Returns: scalar loss """ B, D = z.shape # Variance regularization (VICReg 风格) std = torch.sqrt(z.var(dim=0) + eps) # (D,) var_loss = F.relu(gamma - std).mean() # Covariance regularization (VICReg 风格) z_centered = z - z.mean(dim=0) cov = (z_centered.T @ z_centered) / (B - 1 + eps) # (D, D) # 仅惩罚非对角线元素 diag_mask = torch.eye(D, device=z.device, dtype=torch.bool) cov_off_diag = cov[~diag_mask] cov_loss = (cov_off_diag ** 2).sum() / D return lambda_var * var_loss + lambda_cov * cov_loss # =================================================================== # Part 7: CWT-JEPA 核心模型 # =================================================================== class CWT_JEPA(nn.Module): """ CWT-JEPA: 基于连续小波变换的联合嵌入预测架构 架构流程: 1D 信号 → CWT 时频图 → Patch Embedding → Multi-block Masking ├─ Context Encoder (可训练) → s_x ├─ Target Encoder (EMA, stop-grad) → s_y └─ Predictor (AdaLN) → ŝ_y 损失: L = L_jepa(s_x, s_y, ŝ_y) + λ_sig * L_sigreg(s_x) + λ_stats * L_stats """ def __init__( self, # 信号参数 signal_len=1000, cwt_scales=64, use_diff=True, # Patch 参数 patch_size_time=25, patch_size_freq=8, # Encoder 参数 embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, # Predictor 参数 (Tier 3: 轻量) predictor_depth=6, predictor_num_heads=12, # Masking 参数 (Tier 1: Multi-block) mask_ratio=0.75, num_target_blocks=4, target_scale_range=(0.15, 0.25), # EMA 参数 ema_momentum=0.999, ema_end_momentum=1.0, # 损失权重 sigreg_lambda=0.1, sigreg_var_weight=1.0, sigreg_cov_weight=1.0, stats_loss_weight=1.0, # 其他 max_modalities=16, norm_layer=nn.LayerNorm, drop=0.0, ): super().__init__() # --- 保存配置 --- self.mask_ratio = mask_ratio self.cwt_scales = cwt_scales self.patch_size_time = patch_size_time self.use_diff = use_diff self.ema_momentum = ema_momentum self.ema_end_momentum = ema_end_momentum self.sigreg_lambda = sigreg_lambda self.sigreg_var_weight = sigreg_var_weight self.sigreg_cov_weight = sigreg_cov_weight self.stats_loss_weight = stats_loss_weight self.num_target_blocks = num_target_blocks self.target_scale_range = target_scale_range self.predictor_depth = predictor_depth in_chans = 3 if use_diff else 1 # --- Patch Embedding (保持与原模型一致) --- self.patch_embed = DecomposedPatchEmbed( img_size=(cwt_scales, signal_len), patch_size=(patch_size_freq, patch_size_time), embed_dim=embed_dim, norm_layer=norm_layer, in_chans=in_chans ) self.num_patches = self.patch_embed.num_patches self.grid_size = self.patch_embed.grid_size # (H_freq, W_time) self.raw_patch_embed = RawSignalPatchEmbed( patch_size_time=patch_size_time, embed_dim=embed_dim, norm_layer=norm_layer ) self.raw_signal_scale = nn.Parameter(torch.ones(1, 1, 1, embed_dim) * 0.1) self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches, embed_dim)) # 通道类型 Embedding (0=ECG, 1=PPG) self.channel_type_embed = nn.Embedding(2, embed_dim) # RoPE (2D: freq + time) self.rope_encoder = RotaryEmbedding2D(dim=embed_dim // num_heads) # --- Context Encoder (可训练) --- self.context_blocks = nn.ModuleList([ TrueFactorizedBlock(embed_dim, num_heads, mlp_ratio=mlp_ratio, drop=drop, norm_layer=norm_layer) for _ in range(depth) ]) self.context_norm = norm_layer(embed_dim) # --- Target Encoder (EMA 更新,不可直接训练) --- self.target_blocks = nn.ModuleList([ TrueFactorizedBlock(embed_dim, num_heads, mlp_ratio=mlp_ratio, drop=drop, norm_layer=norm_layer) for _ in range(depth) ]) self.target_norm = norm_layer(embed_dim) # --- Predictor (Tier 3: AdaLN 条件注入) --- self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.predictor_pos_embed = nn.Parameter(torch.zeros(1, self.num_patches, embed_dim)) self.predictor_rope = RotaryEmbedding2D(dim=embed_dim // predictor_num_heads) # 通道条件维度 cond_dim = embed_dim self.predictor_blocks = nn.ModuleList([ AdaLNBlock(embed_dim, predictor_num_heads, cond_dim=cond_dim, mlp_ratio=mlp_ratio, drop=drop, norm_layer=norm_layer) for _ in range(predictor_depth) ]) self.predictor_norm = norm_layer(embed_dim) # --- 辅助预测头 --- # 统计量预测头 (保留自原模型) self.stats_pred_head = nn.Sequential( nn.Linear(embed_dim, embed_dim), nn.GELU(), nn.Linear(embed_dim, 16) ) # --- 初始化 --- self.initialize_weights() self._init_target_encoder() def initialize_weights(self): """权重初始化""" torch.nn.init.trunc_normal_(self.pos_embed, std=.02) torch.nn.init.trunc_normal_(self.predictor_pos_embed, std=.02) torch.nn.init.trunc_normal_(self.mask_token, std=.02) torch.nn.init.trunc_normal_(self.channel_type_embed.weight, std=.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): torch.nn.init.trunc_normal_(m.weight, std=.02) if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.no_grad() def _init_target_encoder(self): """初始化 Target Encoder 为 Context Encoder 的副本""" for ctx_param, tgt_param in zip(self.context_blocks.parameters(), self.target_blocks.parameters()): tgt_param.data.copy_(ctx_param.data) for ctx_param, tgt_param in zip(self.context_norm.parameters(), self.target_norm.parameters()): tgt_param.data.copy_(ctx_param.data) @torch.no_grad() def update_target_encoder(self, momentum=None): """ EMA 更新 Target Encoder (Tier 1 - I-JEPA 风格) θ_target ← m · θ_target + (1-m) · θ_context 使用 _foreach 批量操作,避免逐参数 Python 循环 """ if momentum is None: momentum = self.ema_momentum ctx_params = list(self.context_blocks.parameters()) + list(self.context_norm.parameters()) tgt_params = list(self.target_blocks.parameters()) + list(self.target_norm.parameters()) torch._foreach_mul_(tgt_params, momentum) torch._foreach_add_(tgt_params, ctx_params, alpha=1.0 - momentum) # ----------------------------------------------------------------- # 预处理: CWT + Patch Embedding # ----------------------------------------------------------------- def prepare_tokens(self, x): """ 将原始信号转为 CWT 时频图并归一化 x: (B, L) or (B, M, L) Returns: imgs (B, M, C, H, W) normalized """ if x.dim() == 2: x = x.unsqueeze(1) imgs = cwt_wrap(x, num_scales=self.cwt_scales, lowest_scale=0.1, step=1.0, use_diff=self.use_diff) imgs_f32 = imgs.float() mean = imgs_f32.mean(dim=(3, 4), keepdim=True) std = torch.clamp(imgs_f32.std(dim=(3, 4), keepdim=True), min=1e-5) imgs = (imgs_f32 - mean) / std imgs = torch.nan_to_num(imgs, nan=0.0, posinf=100.0, neginf=-100.0) imgs = torch.clamp(imgs, min=-100.0, max=100.0) return imgs.to(dtype=next(self.parameters()).dtype) def embed_patches(self, x_raw, imgs, channel_ids): """ Patch Embedding + 通道类型注入 + 位置编码 x_raw: (B, M, L) or (B, L) imgs: (B, M, C, H, W) channel_ids: (B,) Returns: x_fused (B, M, N, D) """ B, M, C, H, W = imgs.shape # CWT patch embedding x_cwt = imgs.reshape(B * M, C, H, W) x_cwt = self.patch_embed(x_cwt) # (B*M, N, D) H_grid, W_grid = self.grid_size D = x_cwt.shape[-1] x_cwt_2d = x_cwt.reshape(B * M, H_grid, W_grid, D) # 原始信号 patch embedding if x_raw.dim() == 2: x_raw = x_raw.unsqueeze(1) x_raw_flat = x_raw.reshape(B * M, 1, -1) mean_raw = x_raw_flat.mean(dim=-1, keepdim=True) std_raw = torch.clamp(x_raw_flat.std(dim=-1, keepdim=True), min=1e-5) x_raw_norm = (x_raw_flat - mean_raw) / std_raw x_raw_embed = self.raw_patch_embed(x_raw_norm.to(dtype=next(self.parameters()).dtype)) x_raw_2d = x_raw_embed.unsqueeze(1) # (B*M, 1, D) # 融合 CWT + 原始信号: (B*M, H_grid, W_grid, D) raw_scale = self.raw_signal_scale.to(x_raw_2d.device) x_fused = x_cwt_2d + x_raw_2d * raw_scale # (B*M, H_grid, W_grid, D) # Reshape → (B, M, H_grid, W_grid, D) 以便与通道嵌入对齐 N = H_grid * W_grid x_fused = x_fused.reshape(B, M, H_grid, W_grid, D) # 注入通道类型信息: 需要 5D 以匹配 x_fused 维度 ch_embed = self.channel_type_embed(channel_ids) # (B, D) ch_embed = ch_embed.reshape(B, 1, 1, 1, D) # (B, 1, 1, 1, D) ch_embed = ch_embed.expand(-1, M, -1, -1, -1) # (B, M, 1, 1, D) x_fused = x_fused + ch_embed # (B, M, H, W, D) + (B, M, 1, 1, D) # 展平空间维度 → (B, M, N, D) x_fused = x_fused.reshape(B, M, N, D) # 位置编码 x_fused = x_fused + self.pos_embed.unsqueeze(1).to(x_fused.device) return x_fused # (B, M, N, D) # ----------------------------------------------------------------- # 2D Position ID 辅助 # ----------------------------------------------------------------- def _get_2d_pos_ids(self, flat_indices, W_grid): """ 将 1D 展平索引 → 2D (freq_id, time_id) flat_indices: (B, K) — 全局 patch 索引 (0~N-1) Returns: freq_ids (B, K), time_ids (B, K) """ freq_ids = flat_indices // W_grid time_ids = flat_indices % W_grid return freq_ids, time_ids # ----------------------------------------------------------------- # Encoder Forward # ----------------------------------------------------------------- def encode_context(self, x, M, N_vis, freq_ids, time_ids): """ Context Encoder: 处理可见 patches x: (B, M*N_vis, D) freq_ids, time_ids: (B, N_vis) — 2D 位置索引 (共享 mask,所有通道一致) Returns: s_x (B, M*N_vis, D) """ rope_cos, rope_sin = self.rope_encoder(x, freq_ids, time_ids) for blk in self.context_blocks: x = blk(x, M, N_vis, rope_cos=rope_cos, rope_sin=rope_sin) x = self.context_norm(x) return x def encode_target_full(self, x_fused, M, N, freq_ids, time_ids): """ Target Encoder: 编码完整序列 (EMA, stop-grad) 先编码所有 token,再 gather target 位置的表征。 x_fused: (B, M*N, D) — 完整序列 freq_ids, time_ids: (B, N) — 完整序列的 2D 位置 Returns: s_y_full (B, M*N, D) """ rope_cos, rope_sin = self.rope_encoder(x_fused, freq_ids, time_ids) for blk in self.target_blocks: x_fused = blk(x_fused, M, N, rope_cos=rope_cos, rope_sin=rope_sin) s_y_full = self.target_norm(x_fused) return s_y_full # ----------------------------------------------------------------- # Predictor Forward (Tier 3: AdaLN) # ----------------------------------------------------------------- def predict(self, s_x, M, N_vis, target_positions, context_indices, channel_ids, W_grid): """ Predictor: s_x + mask_tokens → ŝ_y Args: s_x: (B, M*N_vis, D) context representations M: 通道数 N_vis: 可见 patch 数量 target_positions: (N_target,) target 在网格中的位置索引 (共享) context_indices: (N_vis,) context 在网格中的位置索引 (共享) channel_ids: (B,) 通道类型标识 W_grid: 时间网格宽度 Returns: s_y_hat: (B, M*N_target, D) 预测的 target 表征 """ B = s_x.shape[0] // M N_target = target_positions.shape[0] D = s_x.shape[-1] # Reshape s_x s_x_2d = s_x.reshape(B, M, N_vis, D) s_x_flat = s_x_2d.reshape(B * M, N_vis, D) # 创建 mask tokens 并加位置编码 mask_tokens = self.mask_token.expand(B * M, N_target, -1) mask_pos_embed = self._gather_position_embed(self.predictor_pos_embed, target_positions.unsqueeze(0).expand(B * M, -1)) mask_tokens = mask_tokens + mask_pos_embed # 拼接 context + mask tokens predictor_input = torch.cat([s_x_flat, mask_tokens], dim=1) # (B*M, N_vis+N_target, D) # 构造 2D 位置 ID 用于 RoPE ctx_freq, ctx_time = self._get_2d_pos_ids(context_indices.unsqueeze(0), W_grid) # (1, N_vis) tgt_freq, tgt_time = self._get_2d_pos_ids(target_positions.unsqueeze(0), W_grid) # (1, N_target) all_freq = torch.cat([ctx_freq, tgt_freq], dim=1).expand(B, -1) # (B, N_vis+N_target) all_time = torch.cat([ctx_time, tgt_time], dim=1).expand(B, -1) # (B, N_vis+N_target) rope_cos, rope_sin = self.predictor_rope(predictor_input, all_freq, all_time) # 生成通道条件 (用于 AdaLN) channel_cond = self.channel_type_embed(channel_ids) # (B, D) channel_cond_expanded = channel_cond.repeat(M, 1) # (B*M, D) # AdaLN Predictor blocks for blk in self.predictor_blocks: predictor_input = blk(predictor_input, channel_cond_expanded, rope_cos=rope_cos, rope_sin=rope_sin) predictor_input = self.predictor_norm(predictor_input) # 提取 mask token 位置的输出 (仅这些位置用于 loss) s_y_hat = predictor_input[:, N_vis:, :] # (B*M, N_target, D) # Reshape 回 (B, M*N_target, D) s_y_hat = s_y_hat.reshape(B, M * N_target, D) return s_y_hat def _gather_position_embed(self, pos_embed, positions): """从位置嵌入中按索引收集""" if pos_embed.device != positions.device: pos_embed = pos_embed.to(positions.device) B, N = positions.shape D = pos_embed.shape[-1] pos_flat = positions.reshape(-1) # (B*N,) gathered = pos_embed[0, pos_flat] # (B*N, D) return gathered.reshape(B, N, D) def _gather_target_repr(self, s_y_full, M, N, target_positions): """ 从完整序列表征中 gather target 位置的表征 s_y_full: (B, M*N, D) — 完整序列表征 target_positions: (N_tgt,) — target 的全局索引 (0~N-1) Returns: (B, M*N_tgt, D) """ B = s_y_full.shape[0] D = s_y_full.shape[-1] N_tgt = target_positions.shape[0] # 对每个通道 gather target 位置 # 全局索引: 通道 m 的 patch n 的索引 = m*N + n channel_offsets = torch.arange(M, device=s_y_full.device).unsqueeze(1) * N # (M, 1) gather_indices = channel_offsets + target_positions.unsqueeze(0) # (M, N_tgt) gather_indices = gather_indices.reshape(-1) # (M*N_tgt,) gather_indices = gather_indices.unsqueeze(0).expand(B, -1) # (B, M*N_tgt) # gather: (B, M*N_tgt, D) gather_indices_expanded = gather_indices.unsqueeze(-1).expand(-1, -1, D) s_y = torch.gather(s_y_full, 1, gather_indices_expanded) return s_y # ----------------------------------------------------------------- # 主 Forward # ----------------------------------------------------------------- def forward(self, x, channel_ids, stats_target=None, mask_ratio=None, current_epoch=None, total_epochs=None): """ CWT-JEPA 前向传播 Args: x: (B, L) or (B, M, L) 原始信号 channel_ids: (B,) 通道类型标识 (0=ECG, 1=PPG) stats_target: (B, 16) 统计量目标 (可选) mask_ratio: mask 比例 (None=使用默认值) current_epoch: 当前 epoch (用于 EMA schedule) total_epochs: 总 epochs (用于 EMA schedule) Returns: total_loss: scalar loss_dict: {loss_jepa, loss_sigreg, loss_stats} s_x_pooled: (B, D) 用于下游任务 pred_stats: (B, 16) 预测的统计量 """ B = x.shape[0] current_mask_ratio = mask_ratio if mask_ratio is not None else self.mask_ratio # 1. CWT 预处理 imgs = self.prepare_tokens(x) # (B, M, C, H, W) # 2. Patch Embedding x_fused = self.embed_patches(x, imgs, channel_ids) # (B, M, N, D) M, N, D = x_fused.shape[1], x_fused.shape[2], x_fused.shape[3] H_grid, W_grid = self.grid_size # 3. Multi-block Masking (Tier 1 — 共享 mask,无 padding) if current_mask_ratio > 0.0: context_tokens, context_mask, target_positions = multi_block_masking( x_fused, current_mask_ratio, H_grid, W_grid, num_target_blocks=self.num_target_blocks, scale_range=self.target_scale_range ) N_vis = context_tokens.shape[2] N_tgt = target_positions.shape[0] context_indices = context_mask.nonzero(as_tuple=True)[0] # (N_vis,) else: # 无 masking: 全部作为 context,target = 全部 context_tokens = x_fused # (B, M, N, D) target_positions = torch.arange(N, device=x.device) context_indices = torch.arange(N, device=x.device) N_vis = N N_tgt = N # Reshape for encoder: (B, M, N_vis, D) → (B, M*N_vis, D) context_tokens = context_tokens.reshape(B, M * N_vis, D) # 计算 2D 位置 ID ctx_freq_ids, ctx_time_ids = self._get_2d_pos_ids(context_indices.unsqueeze(0), W_grid) # (1, N_vis) # 4. Context Encoder (可训练) s_x = self.encode_context(context_tokens, M, N_vis, ctx_freq_ids.expand(B, -1), ctx_time_ids.expand(B, -1)) # 5. Target Encoder (stop-grad, EMA) — 编码完整序列,再 gather target full_indices = torch.arange(N, device=x.device) full_freq_ids, full_time_ids = self._get_2d_pos_ids(full_indices.unsqueeze(0), W_grid) x_fused_flat = x_fused.reshape(B, M * N, D) # (B, M*N, D) with torch.no_grad(): s_y_full = self.encode_target_full( x_fused_flat, M, N, full_freq_ids.expand(B, -1), full_time_ids.expand(B, -1) ) # (B, M*N, D) # Gather target 位置的表征 # target_positions: (N_tgt,) 全局索引 → 对每个通道 gather s_y = self._gather_target_repr(s_y_full, M, N, target_positions) # (B, M*N_tgt, D) # 6. Predictor (AdaLN) s_y_hat = self.predict(s_x, M, N_vis, target_positions, context_indices, channel_ids, W_grid) # 7. Loss 计算 # JEPA 预测损失 — 原始表征空间 MSE (EMA+SIGReg 已防坍缩,不额外 LN) loss_jepa = F.mse_loss(s_y_hat, s_y) # SIGReg 正则化 (Tier 2) — 作用在 token 级别,子采样防显存爆炸 s_x_tokens = s_x.reshape(-1, D) # (B*M*N_vis, D) if self.training and s_x_tokens.shape[0] > 4096: idx = torch.randperm(s_x_tokens.shape[0], device=s_x_tokens.device)[:4096] s_x_tokens = s_x_tokens[idx] loss_sigreg = sigreg_loss( s_x_tokens, lambda_var=self.sigreg_var_weight, lambda_cov=self.sigreg_cov_weight, ) # Pooled embedding (用于下游任务) s_x_pooled = s_x.reshape(B, M * N_vis, D).mean(dim=1) # (B, D) # 统计量预测损失 — 梯度回传到主干 (辅助表征学习) pred_stats = self.stats_pred_head(s_x_pooled) if stats_target is not None: stats_mean = stats_target.mean(dim=0, keepdim=True) stats_std = stats_target.std(dim=0, unbiased=False, keepdim=True) stats_target_norm = (stats_target - stats_mean) / (stats_std + 1e-6) loss_stats = F.smooth_l1_loss(pred_stats, stats_target_norm) else: loss_stats = torch.tensor(0.0, device=x.device) # 总损失 total_loss = loss_jepa + self.sigreg_lambda * loss_sigreg + self.stats_loss_weight * loss_stats # 8. EMA 更新 Target Encoder if self.training: if current_epoch is not None and total_epochs is not None: progress = current_epoch / max(total_epochs - 1, 1) momentum = self.ema_end_momentum - (self.ema_end_momentum - self.ema_momentum) * ( math.cos(math.pi * progress) + 1) / 2 else: momentum = self.ema_momentum self.update_target_encoder(momentum) # 监控指标 with torch.no_grad(): repr_std = s_y.std(dim=0).mean() pred_std = s_y_hat.std(dim=0).mean() std_ratio = pred_std / (repr_std + 1e-6) cos_sim = F.cosine_similarity( s_y_hat.reshape(-1, D), s_y.reshape(-1, D), dim=-1 ).mean() # 汇总 loss_dict = { 'loss_jepa': loss_jepa.detach(), 'loss_sigreg': loss_sigreg.detach(), 'loss_stats': loss_stats.detach(), 'ema_momentum': momentum if self.training else self.ema_momentum, 'repr_std': repr_std, 'pred_std': pred_std, 'std_ratio': std_ratio, 'cosine_sim': cos_sim, } return total_loss, loss_dict, s_x_pooled, pred_stats, s_x, s_y, s_y_hat, target_positions # ----------------------------------------------------------------- # 便捷方法: 获取下游任务用的 Encoder (与 MAE 兼容) # ----------------------------------------------------------------- def forward_encoder(self, x, channel_ids): """ 仅 Encoder 前向 (用于下游任务微调) 返回 context encoder 在所有 patches 上的表征 """ imgs = self.prepare_tokens(x) x_fused = self.embed_patches(x, imgs, channel_ids) B, M, N, D = x_fused.shape x_fused = x_fused.reshape(B, M * N, D) H_grid, W_grid = self.grid_size all_indices = torch.arange(N, device=x.device) freq_ids, time_ids = self._get_2d_pos_ids(all_indices.unsqueeze(0), W_grid) freq_ids = freq_ids.expand(B, -1) time_ids = time_ids.expand(B, -1) s = self.encode_context(x_fused, M, N, freq_ids, time_ids) return s, x_fused, M, N def forward_encoder_with_stats(self, x, channel_ids): """Encoder + 统计量预测 (用于下游分类)""" s, _, M, N = self.forward_encoder(x, channel_ids) s_pooled = s.reshape(x.shape[0], M * N, -1).mean(dim=1) pred_stats = self.stats_pred_head(s_pooled) return s, s_pooled, pred_stats # =================================================================== # Part 8: 工厂函数 # =================================================================== def cwt_jepa_vit_base(**kwargs): """CWT-JEPA ViT-Base 配置""" defaults = dict( signal_len=1000, cwt_scales=64, patch_size_time=25, patch_size_freq=8, embed_dim=768, depth=12, num_heads=12, predictor_depth=6, predictor_num_heads=12, mask_ratio=0.75, ) defaults.update(kwargs) return CWT_JEPA(**defaults) def cwt_jepa_vit_large(**kwargs): """CWT-JEPA ViT-Large 配置""" defaults = dict( signal_len=1000, cwt_scales=64, patch_size_time=25, patch_size_freq=8, embed_dim=1024, depth=24, num_heads=16, predictor_depth=8, predictor_num_heads=16, mask_ratio=0.75, mlp_ratio=4.0, ) defaults.update(kwargs) return CWT_JEPA(**defaults)