From 3b2765154ac623dad5e1e6d0b5a9e4a313cc41b7 Mon Sep 17 00:00:00 2001 From: yilv <222032695@qq.com> Date: Sat, 30 May 2026 11:38:15 +0800 Subject: [PATCH] =?UTF-8?q?refactor(jepa):=20=E9=87=8D=E6=9E=84JEPA?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E5=B9=B6=E4=BC=98=E5=8C=96=E8=AE=AD=E7=BB=83?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E3=80=81=E6=8D=9F=E5=A4=B1=E4=B8=8E=E7=9B=91?= =?UTF-8?q?=E6=8E=A7=E6=8C=87=E6=A0=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 调整配置文件中辅助统计损失权重为0.1,避免辅助任务过度影响主训练 - 新增2D旋转位置编码类,适配时频维度的位置信息建模 - 重构多块掩码逻辑为全局共享掩码版本,移除padding操作并适配DDP分布式训练 - 优化EMA更新目标编码器的实现,使用批量PyTorch操作提升速度 - 新增四项训练监控指标,更新日志打印与CSV记录格式 - 调整损失计算逻辑:将JEPA预测损失改为smooth_l1损失,优化SIGReg正则化的显存占用 - 修正统计损失的梯度回传逻辑,使其辅助主干网络训练 - 清理无用导入,优化代码可读性 --- config_jepa.yaml | 2 +- model_jepa.py | 358 ++++++++++++++++++++++++++--------------------- train_jepa.py | 30 +++- utils_metrics.py | 17 ++- 4 files changed, 242 insertions(+), 165 deletions(-) diff --git a/config_jepa.yaml b/config_jepa.yaml index 0416aa4..80a79e7 100644 --- a/config_jepa.yaml +++ b/config_jepa.yaml @@ -73,7 +73,7 @@ model: sigreg_cov_weight: 1.0 # 协方差项权重 # --- Auxiliary Loss --- - stats_loss_weight: 1.0 # 统计量预测损失权重 + stats_loss_weight: 0.1 # 统计量预测损失权重 (辅助任务,不宜过大) # --- Data Ratio (可选) --- data_ratio: 1.0 diff --git a/model_jepa.py b/model_jepa.py index e4132b4..3a7ac26 100644 --- a/model_jepa.py +++ b/model_jepa.py @@ -30,7 +30,6 @@ import torch import torch.nn as nn import torch.nn.functional as F import math -import copy # =================================================================== @@ -117,7 +116,7 @@ def cwt_wrap(x, num_scales=64, lowest_scale=0.1, step=1.0, use_diff=True): # =================================================================== class RotaryEmbedding(nn.Module): - """旋转位置编码 (RoPE)""" + """旋转位置编码 (RoPE) — 单轴版本""" def __init__(self, dim, max_seq_len=6000): super().__init__() self.dim = dim @@ -158,6 +157,32 @@ class RotaryEmbedding(nn.Module): 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): @@ -262,9 +287,9 @@ class TrueFactorizedBlock(nn.Module): # --- 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: - M_rope = (B * M) // rope_cos.shape[0] - cos_t = rope_cos.repeat_interleave(M_rope, dim=0) - sin_t = rope_sin.repeat_interleave(M_rope, dim=0) + # 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) @@ -394,7 +419,8 @@ def sample_block_mask(grid_h, grid_w, num_blocks, scale_range, aspect_ratio_rang 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: 将输入分为 Context (x) 和 Target (y) 块 + Multi-block Masking: 共享 mask 版本 (I-JEPA 原版做法) + 所有样本和通道共享同一个 mask,消除 padding,简化 loss 计算。 Args: x: (B, M, N, D) - 所有 patches @@ -405,77 +431,55 @@ def multi_block_masking(x, mask_ratio, grid_h, grid_w, num_target_blocks=4, aspect_ratio_range: 宽高比范围 Returns: - context_tokens: (B, M, N_context, D) - target_tokens: (B, M, N_target, D) - context_mask: (B, N) bool, True = context - target_positions: (B, N_target) - target patches 在网格中的索引 - context_valid: (B, M, N_context) bool, True = 真实 token (非 padding) - target_valid: (B, M, N_target) bool, True = 真实 token (非 padding) + 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 - # 为 batch 中每个样本独立采样 target blocks - all_context_tokens = [] - all_target_tokens = [] - all_context_masks = [] - all_target_positions = [] - - for b in range(B): - # 采样 target mask: True = target (被 mask) + # 共享 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_1d = target_mask_2d.flatten() # (N,) + target_mask = target_mask_2d.flatten() - # 确保 target 比例接近 mask_ratio - current_ratio = target_mask_1d.float().mean() - if current_ratio > mask_ratio * 1.5: - # 随机丢弃一些 target patches - target_indices = target_mask_1d.nonzero(as_tuple=True)[0] - num_to_keep = int(len(target_indices) * mask_ratio / current_ratio) - keep = target_indices[torch.randperm(len(target_indices), device=device)[:num_to_keep]] - target_mask_1d = torch.zeros(N, dtype=torch.bool, device=device) - target_mask_1d[keep] = True + # 裁剪/补充到目标比例 (上下限保护) + 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)) - context_mask_1d = ~target_mask_1d # True = context + 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 和 target tokens - for m in range(M): - x_bm = x[b, m] # (N, D) - all_context_tokens.append(x_bm[context_mask_1d]) - all_target_tokens.append(x_bm[target_mask_1d]) + 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,) - all_context_masks.append(context_mask_1d) - all_target_positions.append(target_mask_1d.nonzero(as_tuple=True)[0]) + # 向量化 gather: 只 gather context (target 由 encode_target_full + gather 处理) + context_tokens = x[:, :, context_indices, :] - # Padding 到相同长度 - max_context = max(t.shape[0] for t in all_context_tokens) - max_target = max(t.shape[0] for t in all_target_tokens) - - context_padded = torch.zeros(B, M, max_context, D, device=device, dtype=x.dtype) - target_padded = torch.zeros(B, M, max_target, D, device=device, dtype=x.dtype) - context_mask_padded = torch.zeros(B, N, dtype=torch.bool, device=device) - target_pos_padded = torch.zeros(B, max_target, dtype=torch.long, device=device) - context_valid = torch.zeros(B, M, max_context, dtype=torch.bool, device=device) - target_valid = torch.zeros(B, M, max_target, dtype=torch.bool, device=device) - - idx = 0 - for b in range(B): - for m in range(M): - c_len = all_context_tokens[idx].shape[0] - t_len = all_target_tokens[idx].shape[0] - context_padded[b, m, :c_len] = all_context_tokens[idx] - target_padded[b, m, :t_len] = all_target_tokens[idx] - context_valid[b, m, :c_len] = True - target_valid[b, m, :t_len] = True - idx += 1 - context_mask_padded[b] = all_context_masks[b] - t_pos = all_target_positions[b] - target_pos_padded[b, :len(t_pos)] = t_pos - - return context_padded, target_padded, context_mask_padded, target_pos_padded, context_valid, target_valid + return context_tokens, context_mask, target_positions # =================================================================== @@ -617,8 +621,8 @@ class CWT_JEPA(nn.Module): # 通道类型 Embedding (0=ECG, 1=PPG) self.channel_type_embed = nn.Embedding(2, embed_dim) - # RoPE - self.rope_encoder = RotaryEmbedding(dim=embed_dim // num_heads) + # RoPE (2D: freq + time) + self.rope_encoder = RotaryEmbedding2D(dim=embed_dim // num_heads) # --- Context Encoder (可训练) --- self.context_blocks = nn.ModuleList([ @@ -637,7 +641,7 @@ class CWT_JEPA(nn.Module): # --- 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 = RotaryEmbedding(dim=embed_dim // predictor_num_heads) + self.predictor_rope = RotaryEmbedding2D(dim=embed_dim // predictor_num_heads) # 通道条件维度 cond_dim = embed_dim @@ -690,14 +694,15 @@ class CWT_JEPA(nn.Module): """ EMA 更新 Target Encoder (Tier 1 - I-JEPA 风格) θ_target ← m · θ_target + (1-m) · θ_context + 使用 _foreach 批量操作,避免逐参数 Python 循环 """ if momentum is None: momentum = self.ema_momentum - for ctx_param, tgt_param in zip(self.context_blocks.parameters(), self.target_blocks.parameters()): - tgt_param.data = momentum * tgt_param.data + (1.0 - momentum) * ctx_param.data - for ctx_param, tgt_param in zip(self.context_norm.parameters(), self.target_norm.parameters()): - tgt_param.data = momentum * tgt_param.data + (1.0 - momentum) * ctx_param.data + 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 @@ -769,39 +774,57 @@ class CWT_JEPA(nn.Module): 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, pos_ids): + 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, pos_ids) + 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(self, x, M, N_tgt, pos_ids): + def encode_target_full(self, x_fused, M, N, freq_ids, time_ids): """ - Target Encoder: 处理 target patches (EMA, stop-grad) - x: (B, M*N_tgt, D) - Returns: s_y (B, M*N_tgt, D) + 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, pos_ids) + rope_cos, rope_sin = self.rope_encoder(x_fused, freq_ids, time_ids) for blk in self.target_blocks: - x = blk(x, M, N_tgt, rope_cos=rope_cos, rope_sin=rope_sin) - x = self.target_norm(x) - return x + 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, channel_ids, W_grid): + def predict(self, s_x, M, N_vis, target_positions, context_indices, + channel_ids, W_grid): """ Predictor: s_x + mask_tokens → ŝ_y @@ -809,7 +832,8 @@ class CWT_JEPA(nn.Module): s_x: (B, M*N_vis, D) context representations M: 通道数 N_vis: 可见 patch 数量 - target_positions: (B, N_target) target 在网格中的位置索引 + target_positions: (N_target,) target 在网格中的位置索引 (共享) + context_indices: (N_vis,) context 在网格中的位置索引 (共享) channel_ids: (B,) 通道类型标识 W_grid: 时间网格宽度 @@ -817,7 +841,7 @@ class CWT_JEPA(nn.Module): s_y_hat: (B, M*N_target, D) 预测的 target 表征 """ B = s_x.shape[0] // M - N_target = target_positions.shape[1] + N_target = target_positions.shape[0] D = s_x.shape[-1] # Reshape s_x @@ -826,22 +850,19 @@ class CWT_JEPA(nn.Module): # 创建 mask tokens 并加位置编码 mask_tokens = self.mask_token.expand(B * M, N_target, -1) - - # 获取 target 位置编码: (B, N_target) → (B*M, N_target) - target_pos_expanded = target_positions.repeat_interleave(M, dim=0) # (B*M, N_target) - mask_pos_embed = self._gather_position_embed(self.predictor_pos_embed, target_pos_expanded) + 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) - # 构造位置 ID 用于 RoPE (context 和 mask token 各自的位置) - context_pos = self._get_context_pos(target_positions, N_vis, W_grid, s_x.device) - mask_pos = target_positions % W_grid - all_pos = torch.cat([context_pos, mask_pos], dim=1) # (B, N_vis+N_target) - all_pos_expanded = all_pos.repeat(M, 1) # (B*M, N_vis+N_target) + # 构造 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_pos_expanded) + rope_cos, rope_sin = self.predictor_rope(predictor_input, all_freq, all_time) # 生成通道条件 (用于 AdaLN) channel_cond = self.channel_type_embed(channel_ids) # (B, D) @@ -863,29 +884,37 @@ class CWT_JEPA(nn.Module): def _gather_position_embed(self, pos_embed, positions): """从位置嵌入中按索引收集""" - # pos_embed: (1, N_total, D) or (1, N_total, D) - # positions: (B*M, N_target) 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*M*N_target,) - gathered = pos_embed[0, pos_flat] # (B*M*N_target, D) + pos_flat = positions.reshape(-1) # (B*N,) + gathered = pos_embed[0, pos_flat] # (B*N, D) return gathered.reshape(B, N, D) - def _get_context_pos(self, target_positions, N_vis, W_grid, device): - """获取 context patches 的位置 ID (排除 target 位置)""" - B = target_positions.shape[0] - N_total = self.num_patches - context_pos = torch.zeros(B, N_vis, dtype=torch.long, device=device) - for b in range(B): - is_target = torch.zeros(N_total, dtype=torch.bool, device=device) - is_target[target_positions[b]] = True - vis_pos = (~is_target).nonzero(as_tuple=True)[0] - if len(vis_pos) > N_vis: - vis_pos = vis_pos[:N_vis] - context_pos[b, :len(vis_pos)] = vis_pos - return context_pos + 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 @@ -921,71 +950,73 @@ class CWT_JEPA(nn.Module): 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) + # 3. Multi-block Masking (Tier 1 — 共享 mask,无 padding) if current_mask_ratio > 0.0: - context_tokens, target_tokens, context_mask, target_positions, context_valid, target_valid = multi_block_masking( + 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] # 每个样本 context patch 数 (padded) - N_tgt = target_tokens.shape[2] # 每个样本 target patch 数 (padded) - - # Context encoder position IDs - context_pos_ids = self._get_context_pos(target_positions, N_vis, W_grid, x.device) + 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 - context_tokens = x_fused - target_tokens = x_fused - target_positions = torch.arange(N, device=x.device).unsqueeze(0).expand(B, -1) + # 无 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 - context_pos_ids = (torch.arange(N, device=x.device) % W_grid).unsqueeze(0).expand(B, -1) - context_tokens = context_tokens.reshape(B, M * N, D) - target_tokens = target_tokens.reshape(B, M * N, D) - context_valid = torch.ones(B, M * N, dtype=torch.bool, device=x.device) - target_valid = torch.ones(B, M * N, dtype=torch.bool, device=x.device) - # Reshape for encoder + # Reshape for encoder: (B, M, N_vis, D) → (B, M*N_vis, D) context_tokens = context_tokens.reshape(B, M * N_vis, D) - target_tokens = target_tokens.reshape(B, M * N_tgt, D) - # Flatten valid masks 以匹配 (B, M*N) 形状 - if current_mask_ratio > 0.0: - context_valid = context_valid.reshape(B, M * N_vis) - target_valid = target_valid.reshape(B, M * N_tgt) + # 计算 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, context_pos_ids) # (B, M*N_vis, D) + 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) + # 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(): - target_pos_ids = (target_positions % W_grid) - # 适配 target_pos_ids 到 encoder 需要的格式 - s_y = self.encode_target(target_tokens, M, N_tgt, target_pos_ids) # (B, M*N_tgt, D) + 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, channel_ids, W_grid) # (B, M*N_tgt, D) + s_y_hat = self.predict(s_x, M, N_vis, target_positions, context_indices, + channel_ids, W_grid) # 7. Loss 计算 - # JEPA 预测损失 (仅在表征空间,mask 掉 padding token) - loss_jepa = F.mse_loss(s_y_hat[target_valid], s_y[target_valid]) + # JEPA 预测损失 — target 归一化后用 smooth_l1 (I-JEPA 实践,防 scale 漂移) + s_y_normed = F.layer_norm(s_y, (D,)) + loss_jepa = F.smooth_l1_loss(s_y_hat, s_y_normed) - # SIGReg 正则化 (Tier 2) — 对 context 嵌入施加高斯约束 - # 只对真实 (非 padding) context token 做均值池化 - s_x_2d = s_x.reshape(B, M * N_vis, D) - context_valid_f32 = context_valid.float().unsqueeze(-1) - s_x_pooled = (s_x_2d * context_valid_f32).sum(dim=1) / context_valid_f32.sum(dim=1).clamp(min=1) + # 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_pooled, + s_x_tokens, lambda_var=self.sigreg_var_weight, lambda_cov=self.sigreg_cov_weight, ) - # 统计量预测损失 (保留自原模型) - pred_stats = self.stats_pred_head(s_x_pooled.detach() if not self.training else s_x_pooled) + # 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: - # Normalize stats target to avoid huge loss values 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) @@ -998,7 +1029,6 @@ class CWT_JEPA(nn.Module): # 8. EMA 更新 Target Encoder if self.training: - # Cosine EMA schedule (来自 I-JEPA 实践) 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) * ( @@ -1007,12 +1037,25 @@ class CWT_JEPA(nn.Module): 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_normed.reshape(-1, D), dim=-1 + ).mean() + # 汇总 loss_dict = { - 'loss_jepa': loss_jepa.detach() if isinstance(loss_jepa, torch.Tensor) else loss_jepa, - 'loss_sigreg': loss_sigreg.detach() if isinstance(loss_sigreg, torch.Tensor) else loss_sigreg, - 'loss_stats': loss_stats.detach() if isinstance(loss_stats, torch.Tensor) else loss_stats, + '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 @@ -1032,9 +1075,12 @@ class CWT_JEPA(nn.Module): x_fused = x_fused.reshape(B, M * N, D) H_grid, W_grid = self.grid_size - pos_ids = (torch.arange(N, device=x.device) % W_grid).unsqueeze(0).expand(B, -1) + 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, pos_ids) + 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): diff --git a/train_jepa.py b/train_jepa.py index 3d7d3bc..f36f21f 100644 --- a/train_jepa.py +++ b/train_jepa.py @@ -76,6 +76,10 @@ def train_one_epoch(model, dataloader, optimizer, scaler, epoch, logger, config, metric_logger['loss_jepa'] = SmoothedValue(window_size=20, fmt='{median:.4f} ({global_avg:.4f})') metric_logger['loss_sigreg'] = SmoothedValue(window_size=20, fmt='{median:.4f} ({global_avg:.4f})') metric_logger['loss_stats'] = SmoothedValue(window_size=20, fmt='{median:.4f} ({global_avg:.4f})') + metric_logger['repr_std'] = SmoothedValue(window_size=20, fmt='{value:.4f}') + metric_logger['pred_std'] = SmoothedValue(window_size=20, fmt='{value:.4f}') + metric_logger['std_ratio'] = SmoothedValue(window_size=20, fmt='{value:.4f}') + metric_logger['cosine_sim'] = SmoothedValue(window_size=20, fmt='{value:.4f}') metric_logger['lr'] = SmoothedValue(window_size=1, fmt='{value:.6f}') metric_logger['grad_norm'] = SmoothedValue(window_size=20, fmt='{value:.2f}') metric_logger['throughput'] = SmoothedValue(window_size=20, fmt='{value:.2f}') @@ -154,10 +158,18 @@ def train_one_epoch(model, dataloader, optimizer, scaler, epoch, logger, config, loss_jepa_val = loss_dict.get('loss_jepa', 0.0) loss_sigreg_val = loss_dict.get('loss_sigreg', 0.0) loss_stats_val = loss_dict.get('loss_stats', 0.0) - + repr_std_val = loss_dict.get('repr_std', 0.0) + pred_std_val = loss_dict.get('pred_std', 0.0) + std_ratio_val = loss_dict.get('std_ratio', 0.0) + cosine_sim_val = loss_dict.get('cosine_sim', 0.0) + if isinstance(loss_jepa_val, torch.Tensor): loss_jepa_val = loss_jepa_val.item() if isinstance(loss_sigreg_val, torch.Tensor): loss_sigreg_val = loss_sigreg_val.item() if isinstance(loss_stats_val, torch.Tensor): loss_stats_val = loss_stats_val.item() + if isinstance(repr_std_val, torch.Tensor): repr_std_val = repr_std_val.item() + if isinstance(pred_std_val, torch.Tensor): pred_std_val = pred_std_val.item() + if isinstance(std_ratio_val, torch.Tensor): std_ratio_val = std_ratio_val.item() + if isinstance(cosine_sim_val, torch.Tensor): cosine_sim_val = cosine_sim_val.item() if do_sync: scaler.unscale_(optimizer) @@ -178,6 +190,10 @@ def train_one_epoch(model, dataloader, optimizer, scaler, epoch, logger, config, metric_logger['loss_jepa'].update(loss_jepa_val) metric_logger['loss_sigreg'].update(loss_sigreg_val) metric_logger['loss_stats'].update(loss_stats_val) + metric_logger['repr_std'].update(repr_std_val) + metric_logger['pred_std'].update(pred_std_val) + metric_logger['std_ratio'].update(std_ratio_val) + metric_logger['cosine_sim'].update(cosine_sim_val) metric_logger['lr'].update(optimizer.param_groups[0]["lr"]) metric_logger['throughput'].update(throughput) @@ -203,6 +219,10 @@ def train_one_epoch(model, dataloader, optimizer, scaler, epoch, logger, config, f"JEPA: {metric_logger['loss_jepa']} " f"SIGReg: {metric_logger['loss_sigreg']} " f"Stats: {metric_logger['loss_stats']} " + f"ReprStd: {metric_logger['repr_std']} " + f"PredStd: {metric_logger['pred_std']} " + f"StdRatio: {metric_logger['std_ratio']} " + f"CosSim: {metric_logger['cosine_sim']} " f"LR: {metric_logger['lr']} " f"Grad: {metric_logger['grad_norm']} " f"Speed: {metric_logger['throughput'].avg:.1f} samp/s " @@ -217,6 +237,10 @@ def train_one_epoch(model, dataloader, optimizer, scaler, epoch, logger, config, 'loss_jepa': metric_logger['loss_jepa'].global_avg, 'loss_sigreg': metric_logger['loss_sigreg'].global_avg, 'loss_stats': metric_logger['loss_stats'].global_avg, + 'repr_std': metric_logger['repr_std'].global_avg, + 'pred_std': metric_logger['pred_std'].global_avg, + 'std_ratio': metric_logger['std_ratio'].global_avg, + 'cosine_sim': metric_logger['cosine_sim'].global_avg, 'grad_norm': metric_logger['grad_norm'].global_avg, 'throughput': metric_logger['throughput'].global_avg * ( dist.get_world_size() if dist.is_initialized() else 1) @@ -421,6 +445,10 @@ def main(): 'loss_jepa': train_metrics['loss_jepa'], 'loss_sigreg': train_metrics['loss_sigreg'], 'loss_stats': train_metrics['loss_stats'], + 'repr_std': train_metrics['repr_std'], + 'pred_std': train_metrics['pred_std'], + 'std_ratio': train_metrics['std_ratio'], + 'cosine_sim': train_metrics['cosine_sim'], 'grad_norm': train_metrics['grad_norm'], 'gpu_mem_mb': torch.cuda.max_memory_allocated() / 1024 / 1024, 'throughput': train_metrics['throughput'], diff --git a/utils_metrics.py b/utils_metrics.py index 8c027e3..78ab8e1 100644 --- a/utils_metrics.py +++ b/utils_metrics.py @@ -6,23 +6,26 @@ class ExperimentTracker: self.save_dir = save_dir self.metrics_file = os.path.join(save_dir, "metrics.csv") self.metrics = defaultdict(list) - + # Init CSV header if not os.path.exists(self.metrics_file): with open(self.metrics_file, 'w') as f: - f.write("epoch,train_loss,loss_spec,loss_time,loss_stats,grad_norm,gpu_mem_mb,throughput\n") - + f.write("epoch,train_loss,loss_jepa,loss_sigreg,loss_stats," + "grad_norm,gpu_mem_mb,throughput,repr_std,pred_std,std_ratio,cosine_sim\n") + def log(self, epoch, metrics_dict): # Update internal dict for k, v in metrics_dict.items(): self.metrics[k].append(v) - + # Write to CSV with open(self.metrics_file, 'a') as f: - f.write(f"{epoch},{metrics_dict.get('train_loss', 0):.4f},{metrics_dict.get('loss_spec', 0):.4f}," - f"{metrics_dict.get('loss_time', 0):.4f},{metrics_dict.get('loss_stats', 0):.4f}," + f.write(f"{epoch},{metrics_dict.get('train_loss', 0):.4f},{metrics_dict.get('loss_jepa', 0):.4f}," + f"{metrics_dict.get('loss_sigreg', 0):.4f},{metrics_dict.get('loss_stats', 0):.4f}," f"{metrics_dict.get('grad_norm', 0):.4f},{metrics_dict.get('gpu_mem_mb', 0):.1f}," - f"{metrics_dict.get('throughput', 0):.2f}\n") + f"{metrics_dict.get('throughput', 0):.2f}," + f"{metrics_dict.get('repr_std', 0):.4f},{metrics_dict.get('pred_std', 0):.4f}," + f"{metrics_dict.get('std_ratio', 0):.4f},{metrics_dict.get('cosine_sim', 0):.4f}\n") def check_early_stopping(self, patience=3): return False