优化 NormWear 类中的前向传播和损失计算,增强多模态重建的可读性和准确性

This commit is contained in:
yilv committed 2025-09-21 05:11:14 +08:00
1 parent 3589937b52
commit a02b5aa5c0
1 file changed
+72 -20
+72 -20
View File
@@ -98,19 +98,13 @@ class NormWear(nn.Module):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def patchify(self, imgs):
p_h, p_w = self.patch_size
h = imgs.shape[2] // p_h
w = imgs.shape[3] // p_w
x = imgs.reshape(shape=(imgs.shape[0], imgs.shape[1], h, p_h, w, p_w))
x = torch.einsum('nchpwq->nhwpqc', x)
x = x.reshape(shape=(imgs.shape[0], h * w, p_h * p_w * imgs.shape[1]))
return x
def unpatchify(self, x):
p_h, p_w = self.patch_size
h, w = self.patch_embed.patch_hw
# 推断通道数
C = self.decoder_pred_cwt.out_features // (p_h * p_w)
x = x.reshape(shape=(x.shape[0], h, w, p_h, p_w, C))
x = torch.einsum('nhwpqc->nchpwq', x)
imgs = x.reshape(shape=(x.shape[0], C, h * p_h, w * p_w))
@@ -151,36 +145,94 @@ class NormWear(nn.Module):
return x
def forward_loss(self, x_cwt_orig, cnn_1d_tokens_orig, decoded_features, mask):
# 1. CWT重建损失
pred_cwt_patches = self.decoder_pred_cwt(decoded_features)[:, 1:, :]
target_cwt_patches = self.patchify(x_cwt_orig)
loss_cwt = ((pred_cwt_patches - target_cwt_patches) ** 2).mean(dim=-1)
loss_cwt = (loss_cwt * mask).sum() / mask.sum()
"""
计算双路重建损失:
1. CWT损失在像素空间计算。
2. 1D Token损失在特征空间计算。
x_cwt_orig: [N*nvar, C, H, W], 原始CWT图像
cnn_1d_tokens_orig: [N*nvar, L, D], 原始1D CNN Tokens
decoded_features: [N*nvar, L+1, D_dec], 解码器输出的完整特征序列
mask: [N*nvar, L], 1表示被掩码
"""
# --- 1. CWT 重建损失 (在像素空间) ---
# a. 从解码器特征重建patch列表
pred_cwt_patches = self.decoder_pred_cwt(decoded_features)[:, 1:, :] # 去掉CLS token
# b. 将patch列表拼接回图像
pred_cwt_imgs = self.unpatchify(pred_cwt_patches)
# 2. 1D Token重建损失
pred_1d_tokens = self.decoder_pred_1d(decoded_features)[:, 1:, :]
# c. 计算像素级的MSE
loss_cwt = (pred_cwt_imgs - x_cwt_orig) ** 2
loss_cwt = loss_cwt.mean(dim=1, keepdim=True) # 在通道维度上取平均 [N, 1, H, W]
# d. 将patch级别的mask上采样到像素级别
mask_pixel = mask.reshape(shape=(mask.shape[0], self.patch_embed.patch_hw[0], self.patch_embed.patch_hw[1]))
mask_pixel = mask_pixel.unsqueeze(1).repeat_interleave(self.patch_size[0], dim=2).repeat_interleave(self.patch_size[1], dim=3)
# e. 确保尺寸完全一致 (处理1-2个像素的边界误差)
target_h, target_w = x_cwt_orig.shape[2:]
# 使用插值来调整mask尺寸,比pad+crop更通用
if mask_pixel.shape[2:] != (target_h, target_w):
mask_pixel = torch.nn.functional.interpolate(mask_pixel, size=(target_h, target_w), mode='nearest')
# f. 只计算被掩码区域的损失
# mask_pixel.sum() + 1e-8 避免除以零
loss_cwt = (loss_cwt * mask_pixel).sum() / (mask_pixel.sum() + 1e-8)
# --- 2. 1D Token 重建损失 (在特征空间) ---
# a. 从解码器特征重建1D tokens
pred_1d_tokens = self.decoder_pred_1d(decoded_features)[:, 1:, :] # 去掉CLS token
# b. 目标是原始的1D CNN tokens
target_1d_tokens = cnn_1d_tokens_orig
loss_1d = ((pred_1d_tokens - target_1d_tokens) ** 2).mean(dim=-1)
loss_1d = (loss_1d * mask).sum() / mask.sum()
# c. 计算token级别的MSE
loss_1d = ((pred_1d_tokens - target_1d_tokens) ** 2).mean(dim=-1) # 在embed_dim维度上取平均
# d. 只计算被掩码区域的损失
loss_1d = (loss_1d * mask).sum() / (mask.sum() + 1e-8)
# 3. 加权总损失
# --- 3. 加权总损失 ---
total_loss = (1 - self.loss_weight_1d) * loss_cwt + self.loss_weight_1d * loss_1d
# 返回所有损失以供调试和记录
return total_loss, loss_cwt, loss_1d
def forward(self, x_cwt, x_1d, mask_ratio=0.75):
"""
MAE预训练的完整前向传播,执行多模态重建。
"""
N, nvar, ch, L, F_ = x_cwt.shape
x_cwt_reshaped = x_cwt.reshape(N * nvar, ch, L, F_)
x_1d_reshaped = x_1d.reshape(N * nvar, L)
# 1. 提取并融合特征,同时获取原始token作为重建目标
fused_tokens, cwt_tokens_orig, cnn_1d_tokens_orig = self._forward_features(x_cwt_reshaped, x_1d_reshaped)
# 2. 编码可见的融合后patches
latent, mask, ids_restore = self.forward_encoder(fused_tokens, mask_ratio)
# 3. 解码完整的特征序列
decoded_features = self.forward_decoder(latent, ids_restore)
# 4. 计算双路损失
# 注意:forward_loss的第一个参数是原始CWT图像,而不是CWT token
loss, loss_cwt, loss_1d = self.forward_loss(x_cwt_reshaped, cnn_1d_tokens_orig, decoded_features, mask)
pred_pixels = self.unpatchify(self.decoder_pred_cwt(decoded_features)[:, 1:, :])
# 5. (可选) 为了可视化,重建CWT图像
pred_cwt_patches = self.decoder_pred_cwt(decoded_features)[:, 1:, :]
pred_pixels = self.unpatchify(pred_cwt_patches)
pred_pixels_unshaped = pred_pixels.view(N, nvar, ch, pred_pixels.shape[2], pred_pixels.shape[3])
return loss, pred_pixels, mask
# 6. 恢复掩码的nvar维度
mask_unshaped = mask.view(N, nvar, -1)
# 7. 返回主损失和用于可视化的内容
return loss, pred_pixels_unshaped, mask_unshaped
def get_signal_embedding(self, x_cwt):
"""
统一的、简化的推理接口,只接收CWT输入并提取特征。