302 lines
11 KiB
Python
302 lines
11 KiB
Python
"""
|
||
CWT-JEPA 下游分类器
|
||
基于 CWT-JEPA 预训练编码器的多标签分类模型,支持 CoT (Chain-of-Thought) 推理头
|
||
|
||
与 CWT-MAE 微调模型 (TF_MAE_Classifier) 的区别:
|
||
- Encoder 使用 CWT_JEPA (无 Decoder,EMA Target Encoder 可卸载)
|
||
- 使用 forward_encoder_with_stats 提取表征 + 统计量
|
||
- LatentReasoningHead 保持一致
|
||
"""
|
||
|
||
import torch
|
||
import torch.nn as nn
|
||
import torch.nn.functional as F
|
||
|
||
from model_jepa import CWT_JEPA
|
||
from utils import is_main_process
|
||
|
||
|
||
# ===================================================================
|
||
# 1. 隐式思维链模块 (Latent Reasoning / Chain-of-Thought Head)
|
||
# ===================================================================
|
||
class LatentReasoningHead(nn.Module):
|
||
"""
|
||
隐式思维链推理头
|
||
通过可学习的 reasoning tokens 与 encoder 输出做交叉注意力,
|
||
隐式执行多步推理后输出分类结果
|
||
"""
|
||
def __init__(self, embed_dim, num_heads, num_classes, num_reasoning_tokens=32, dropout=0.1):
|
||
super().__init__()
|
||
self.num_reasoning_tokens = num_reasoning_tokens
|
||
self.embed_dim = embed_dim
|
||
|
||
self.reasoning_tokens = nn.Parameter(torch.zeros(1, num_reasoning_tokens, embed_dim))
|
||
|
||
self.cross_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True, dropout=dropout)
|
||
self.norm1 = nn.LayerNorm(embed_dim)
|
||
|
||
self.self_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True, dropout=dropout)
|
||
self.norm2 = nn.LayerNorm(embed_dim)
|
||
|
||
self.ffn = nn.Sequential(
|
||
nn.Linear(embed_dim, embed_dim * 4),
|
||
nn.GELU(),
|
||
nn.Dropout(dropout),
|
||
nn.Linear(embed_dim * 4, embed_dim)
|
||
)
|
||
self.norm3 = nn.LayerNorm(embed_dim)
|
||
|
||
self.classifier = nn.Linear(embed_dim, num_classes)
|
||
|
||
self._init_weights()
|
||
nn.init.normal_(self.reasoning_tokens, std=0.02)
|
||
|
||
def _init_weights(self):
|
||
for p in self.parameters():
|
||
if p.dim() > 1:
|
||
nn.init.xavier_uniform_(p)
|
||
|
||
def forward(self, x_encoder, token_padding_mask=None, extra_features=None):
|
||
B = x_encoder.shape[0]
|
||
queries = self.reasoning_tokens.expand(B, -1, -1)
|
||
|
||
attn_out, _ = self.cross_attn(
|
||
query=queries, key=x_encoder, value=x_encoder,
|
||
key_padding_mask=token_padding_mask
|
||
)
|
||
queries = self.norm1(queries + attn_out)
|
||
|
||
attn_out2, _ = self.self_attn(query=queries, key=queries, value=queries)
|
||
queries = self.norm2(queries + attn_out2)
|
||
|
||
queries = self.norm3(queries + self.ffn(queries))
|
||
|
||
decision_token = queries.mean(dim=1)
|
||
if extra_features is not None:
|
||
decision_token = torch.cat([decision_token, extra_features], dim=-1)
|
||
logits = self.classifier(decision_token)
|
||
return logits
|
||
|
||
|
||
# ===================================================================
|
||
# 2. JEPA 分类器封装
|
||
# ===================================================================
|
||
class JEPA_Classifier(nn.Module):
|
||
"""
|
||
基于 CWT-JEPA 预训练 Encoder 的分类器
|
||
|
||
架构:
|
||
CWT-JEPA Context Encoder → LatentReasoningHead (CoT) → 分类 logits
|
||
|
||
与 TF_MAE_Classifier 的关键区别:
|
||
- 无需删除 Decoder (JEPA 的 Predictor + Target Encoder 本身不参与下游)
|
||
- 直接使用 forward_encoder_with_stats 获取表征
|
||
- 可选择性卸载 Target Encoder 和 Predictor 以节省显存
|
||
"""
|
||
|
||
def __init__(self, pretrained_path, num_classes,
|
||
use_cot=True,
|
||
num_reasoning_tokens=16,
|
||
**kwargs):
|
||
super().__init__()
|
||
|
||
self.use_stats_features = kwargs.pop('use_stats_features', False)
|
||
self.embed_dim = kwargs.get('embed_dim', 768)
|
||
|
||
# 初始化 CWT-JEPA (mask_ratio=0 用于下游无 masking)
|
||
self.encoder_model = CWT_JEPA(
|
||
mask_ratio=0.0,
|
||
**kwargs
|
||
)
|
||
|
||
# 加载预训练权重
|
||
if pretrained_path:
|
||
self._load_pretrained_weights(pretrained_path)
|
||
|
||
# 释放不需要的组件以节省显存
|
||
self._freeze_and_release()
|
||
|
||
# 分类头输入维度
|
||
classifier_in_dim = self.embed_dim
|
||
if self.use_stats_features:
|
||
classifier_in_dim += 16 # 统计特征
|
||
|
||
if use_cot:
|
||
if is_main_process():
|
||
print(f">>> Initializing Latent Reasoning Head (CoT) with {num_reasoning_tokens} tokens.")
|
||
self.head = LatentReasoningHead(
|
||
embed_dim=self.embed_dim,
|
||
num_heads=kwargs.get('num_heads', 12),
|
||
num_classes=num_classes,
|
||
num_reasoning_tokens=num_reasoning_tokens,
|
||
dropout=0.2
|
||
)
|
||
if self.use_stats_features:
|
||
# 扩展分类器以接收统计特征
|
||
self.head.classifier = nn.Linear(self.embed_dim + 16, num_classes)
|
||
else:
|
||
self.head = nn.Sequential(
|
||
nn.LayerNorm(classifier_in_dim),
|
||
nn.Linear(classifier_in_dim, num_classes)
|
||
)
|
||
|
||
def _load_pretrained_weights(self, path):
|
||
"""加载 JEPA 预训练权重"""
|
||
checkpoint = torch.load(path, map_location='cpu')
|
||
state_dict = checkpoint['model'] if 'model' in checkpoint else checkpoint
|
||
|
||
# 去掉 DDP/compile 前缀
|
||
new_state_dict = {}
|
||
for k, v in state_dict.items():
|
||
name = k.replace('module.', '').replace('_orig_mod.', '')
|
||
new_state_dict[name] = v
|
||
|
||
# 只加载 Encoder 相关权重(跳过 Predictor, Target Encoder 等)
|
||
encoder_dict = {}
|
||
for k, v in new_state_dict.items():
|
||
# 保留 context encoder 和共享组件
|
||
if any(x in k for x in ['predictor', 'target_blocks', 'target_norm',
|
||
'mask_token', 'predictor_pos_embed',
|
||
'predictor_norm', 'predictor_rope']):
|
||
continue
|
||
encoder_dict[k] = v
|
||
|
||
# 处理位置编码可能不匹配的情况
|
||
if hasattr(self.encoder_model, 'pos_embed'):
|
||
self._interpolate_pos_embed(encoder_dict, 'pos_embed',
|
||
self.encoder_model.pos_embed)
|
||
|
||
msg = self.encoder_model.load_state_dict(encoder_dict, strict=False)
|
||
|
||
actual_missing = [k for k in msg.missing_keys
|
||
if not any(x in k for x in ['predictor', 'target', 'mask_token'])]
|
||
|
||
if is_main_process():
|
||
print(f"JEPA weights loaded from {path}")
|
||
if actual_missing:
|
||
print(f"WARNING: Missing keys: {actual_missing}")
|
||
else:
|
||
print("Encoder weights loaded successfully.")
|
||
if msg.unexpected_keys:
|
||
actual_unexpected = [k for k in msg.unexpected_keys
|
||
if 'predictor' not in k and 'target' not in k]
|
||
if actual_unexpected:
|
||
print(f"Unexpected keys: {actual_unexpected}")
|
||
|
||
def _interpolate_pos_embed(self, state_dict, key, new_pos_embed):
|
||
"""插值位置编码以匹配不同 patch 数量"""
|
||
if key not in state_dict:
|
||
return
|
||
old_pos_embed = state_dict[key]
|
||
if old_pos_embed.shape[1] == new_pos_embed.shape[1]:
|
||
return
|
||
|
||
if is_main_process():
|
||
print(f"Interpolating {key}: {old_pos_embed.shape[1]} -> {new_pos_embed.shape[1]}")
|
||
|
||
patch_tokens = old_pos_embed
|
||
grid_h, grid_w_new = self.encoder_model.grid_size
|
||
n_old = patch_tokens.shape[1]
|
||
grid_w_old = n_old // grid_h
|
||
dim = patch_tokens.shape[-1]
|
||
|
||
patch_tokens = patch_tokens.transpose(1, 2).reshape(1, dim, grid_h, grid_w_old)
|
||
patch_tokens = F.interpolate(patch_tokens, size=(grid_h, grid_w_new),
|
||
mode='bicubic', align_corners=False)
|
||
patch_tokens = patch_tokens.flatten(2).transpose(1, 2)
|
||
state_dict[key] = patch_tokens
|
||
|
||
def _freeze_and_release(self):
|
||
"""
|
||
释放不需要的组件以节省显存。
|
||
JEPA 下游任务只需要 Context Encoder + Stats Head。
|
||
"""
|
||
components_to_delete = [
|
||
'target_blocks', 'target_norm',
|
||
'predictor_blocks', 'predictor_norm',
|
||
'mask_token', 'predictor_pos_embed',
|
||
'predictor_rope',
|
||
]
|
||
for comp in components_to_delete:
|
||
if hasattr(self.encoder_model, comp):
|
||
delattr(self.encoder_model, comp)
|
||
|
||
if is_main_process():
|
||
print("Released Target Encoder and Predictor to save memory.")
|
||
|
||
def forward(self, x, channel_mask=None, channel_ids=None):
|
||
"""
|
||
前向传播
|
||
|
||
Args:
|
||
x: (B, L) or (B, M, L) 原始信号
|
||
channel_mask: (B, M) 通道有效性 mask
|
||
channel_ids: (B,) 通道类型 ID
|
||
Returns:
|
||
logits: (B, num_classes)
|
||
"""
|
||
if x.dim() == 2:
|
||
x = x.unsqueeze(1)
|
||
|
||
if channel_ids is None:
|
||
channel_ids = torch.zeros(x.shape[0], dtype=torch.long, device=x.device)
|
||
|
||
# 使用 Encoder + Stats Head 提取表征
|
||
latent, latent_pooled, pred_stats = self.encoder_model.forward_encoder_with_stats(
|
||
x, channel_ids
|
||
)
|
||
# latent: (B, M*N, D), latent_pooled: (B, D), pred_stats: (B, 16)
|
||
|
||
# 构造 token padding mask (用于 CoT 交叉注意力)
|
||
token_padding_mask = None
|
||
if channel_mask is not None:
|
||
channel_mask = channel_mask.to(latent.device, dtype=torch.bool)
|
||
B_mask, M_total = channel_mask.shape
|
||
M_model = x.shape[1] # 实际通道数
|
||
total_tokens = latent.shape[1]
|
||
|
||
# 将通道 mask 扩展到 token 级别
|
||
if total_tokens % M_model == 0 and M_total >= M_model:
|
||
n_patches = total_tokens // M_model
|
||
# 截取实际通道数对应的 mask
|
||
mask_m = channel_mask[:, :M_model]
|
||
token_padding_mask = (~mask_m).unsqueeze(-1).expand(
|
||
B_mask, M_model, n_patches
|
||
).reshape(B_mask, total_tokens)
|
||
|
||
if isinstance(self.head, LatentReasoningHead):
|
||
logits = self.head(
|
||
latent, # (B, total_tokens, D)
|
||
token_padding_mask=token_padding_mask,
|
||
extra_features=pred_stats if self.use_stats_features else None
|
||
)
|
||
else:
|
||
global_feat = latent.mean(dim=1)
|
||
if self.use_stats_features:
|
||
global_feat = torch.cat([global_feat, pred_stats], dim=-1)
|
||
logits = self.head(global_feat)
|
||
|
||
return logits
|
||
|
||
|
||
# ===================================================================
|
||
# 3. 工厂函数
|
||
# ===================================================================
|
||
|
||
def jepa_classifier_base(pretrained_path, num_classes, **kwargs):
|
||
"""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,
|
||
use_diff=True,
|
||
use_cot=True,
|
||
num_reasoning_tokens=16,
|
||
)
|
||
defaults.update(kwargs)
|
||
return JEPA_Classifier(pretrained_path, num_classes, **defaults)
|