Segmentation / code /src /diffusion /flow_matching /training_medical.py
MaybeRichard's picture
Upload PixelGen code: cross-attention mask mode + multi-scale ablation configs
01fdb75 verified
raw
history blame
12.3 kB
# Training for Medical Image Generation with Mask Conditioning
# Based on training_repa_JiT_LPIPS_DINO_NoiseGating.py
import torch
import torch.nn as nn
import lpips
import math
from typing import Callable
from src.utils.no_grad import freeze_model
from src.diffusion.base.training import BaseTrainer
from src.diffusion.base.scheduling import BaseScheduler
def constant(alpha, sigma):
return 1
def time_shift_fn(t, timeshift=1.0):
return t / (t + (1 - t) * timeshift)
class MedicalREPATrainer(BaseTrainer):
"""
Trainer for medical image generation with:
- Mask conditioning
- LPIPS perceptual loss
- Optional DINO perceptual loss (if encoder provided)
- Noise-gating strategy
"""
def __init__(
self,
scheduler: BaseScheduler,
loss_weight_fn: Callable = constant,
feat_loss_weight: float = 0.5,
lognorm_t: bool = True,
timeshift: float = 1.0,
encoder: nn.Module = None, # DINOv2 encoder (optional for medical)
align_layer: int = 8,
proj_denoiser_dim: int = 768,
proj_hidden_dim: int = 768,
proj_encoder_dim: int = 768,
P_mean: float = -0.8,
P_std: float = 0.8,
t_eps: float = 0.05,
lpips_weight: float = 0.1,
dino_weight: float = 0.01,
percept_t_threshold: float = 0.3,
noise_scale: float = 1.0,
patch_size: int = 16,
use_dino: bool = False, # Disable DINO by default for medical
*args,
**kwargs
):
super().__init__(*args, **kwargs)
self.lognorm_t = lognorm_t
self.scheduler = scheduler
self.timeshift = timeshift
self.loss_weight_fn = loss_weight_fn
self.feat_loss_weight = feat_loss_weight
self.align_layer = align_layer
self.use_dino = use_dino and (encoder is not None)
# DINO encoder (optional)
if self.use_dino:
self.encoder = encoder
freeze_model(self.encoder)
self.proj = nn.Sequential(
nn.Linear(proj_denoiser_dim, proj_hidden_dim),
nn.SiLU(),
nn.Linear(proj_hidden_dim, proj_hidden_dim),
nn.SiLU(),
nn.Linear(proj_hidden_dim, proj_encoder_dim),
)
self.dino_layers = [11]
else:
self.encoder = None
self.proj = None
# LPIPS loss
self.lpips_loss_fn = lpips.LPIPS(net='vgg').eval()
freeze_model(self.lpips_loss_fn)
self.patch_size = patch_size
self.P_mean = P_mean
self.P_std = P_std
self.t_eps = t_eps
self.lpips_weight = lpips_weight
self.dino_weight = dino_weight
self.percept_t_threshold = percept_t_threshold
self.noise_scale = noise_scale
def compute_lpips_loss(self, pred_img, x, percept_mask=None):
"""Compute LPIPS loss with optional noise-gating mask."""
batch_size, _, height, width = pred_img.shape
# Resize for LPIPS if not 256
if self.patch_size != 16:
new_scale = int(height * 16 // self.patch_size)
pred_img = torch.nn.functional.interpolate(
pred_img, size=(new_scale, new_scale),
mode='bilinear', align_corners=False, antialias=True
)
x = torch.nn.functional.interpolate(
x, size=(new_scale, new_scale),
mode='bilinear', align_corners=False, antialias=True
)
if percept_mask is not None:
lpips_val = self.lpips_loss_fn(pred_img, x).view(batch_size, -1)
lpips_loss = (lpips_val * percept_mask).mean(dim=1)
lpips_loss = lpips_loss.sum() / percept_mask.sum() if percept_mask.sum() > 0 else lpips_loss.sum()
else:
lpips_loss = self.lpips_loss_fn(pred_img, x).mean()
return lpips_loss
def compute_dino_loss(self, pred_dino_feats, gt_dino_feats, percept_mask=None):
"""Compute DINO perceptual loss."""
cos_losses = {}
final_cos_loss = 0
batch_size = pred_dino_feats[0].shape[0]
for i, (pred_feat, gt_feat) in enumerate(zip(pred_dino_feats, gt_dino_feats)):
if percept_mask is not None:
mask = percept_mask.reshape(batch_size, 1, 1)
cos_sim = (torch.nn.functional.cosine_similarity(pred_feat, gt_feat, dim=-1) * mask).mean(dim=(1, 2))
cos_sim = cos_sim.sum() / mask.sum() if mask.sum() > 0 else cos_sim.sum()
cos_loss = 1 - cos_sim
else:
cos_loss = 1 - torch.nn.functional.cosine_similarity(pred_feat, gt_feat, dim=-1).view(batch_size, -1).mean()
cos_losses[f"inter_cos_{i}"] = cos_loss
final_cos_loss += cos_loss
cos_losses["dino_percept_loss"] = final_cos_loss / len(pred_dino_feats)
return cos_losses
def _impl_trainstep(self, net, ema_net, solver, x, condition, metadata=None):
"""Training step with mask conditioning.
For medical images, we use mask from metadata directly,
not the condition from conditioner.
"""
raw_images = metadata.get("raw_image", None)
mask = metadata.get("mask", None)
batch_size, c, height, width = x.shape
# Class labels - use zeros for medical (single class)
y = torch.zeros(batch_size, dtype=torch.long, device=x.device)
self.lpips_loss_fn.eval()
# Sample timesteps
if self.lognorm_t:
base_t = (torch.randn(batch_size, device=x.device, dtype=torch.float32) * self.P_std + self.P_mean).sigmoid()
else:
base_t = torch.rand((batch_size), device=x.device, dtype=torch.float32)
t = time_shift_fn(base_t, self.timeshift)
# Add noise
noise = self.noise_scale * torch.randn_like(x)
alpha = self.scheduler.alpha(t)
sigma = self.scheduler.sigma(t)
x_t = alpha * x + noise * sigma
# Velocity target
v_t = (x - x_t) / (1 - t.view(-1, 1, 1, 1)).clamp_min(self.t_eps)
# Forward pass with mask conditioning
if self.use_dino:
pred_img, src_feature = net(x_t, t, y, mask=mask, return_layer=self.align_layer)
src_feature = self.proj(src_feature)
else:
pred_img = net(x_t, t, y, mask=mask)
# Compute velocity from prediction
out = (pred_img - x_t) / (1 - t.view(-1, 1, 1, 1)).clamp_min(self.t_eps)
# Flow matching loss
weight = self.loss_weight_fn(alpha, sigma)
fm_loss = weight * (out - v_t) ** 2
# Noise-gating mask for perceptual losses
if self.percept_t_threshold > 0:
percept_mask = (t >= self.percept_t_threshold).float().reshape(batch_size, -1)
else:
percept_mask = None
# LPIPS loss
lpips_loss = self.compute_lpips_loss(pred_img, x, percept_mask)
# DINO loss (if enabled)
dino_losses = {}
cos_loss = torch.tensor(0.0, device=x.device)
if self.use_dino and raw_images is not None:
with torch.no_grad():
dst_features = self.encoder.get_intermediate_feats(raw_images, n=self.dino_layers)
# REPA loss (hidden feature alignment)
cos_sim = torch.nn.functional.cosine_similarity(src_feature, dst_features[-1], dim=-1)
cos_loss = (1 - cos_sim).mean()
# P-DINO loss (predicted image feature alignment)
raw_pred_img = (pred_img + 1) / 2 # [-1, 1] -> [0, 1]
pred_feats = self.encoder.get_intermediate_feats(raw_pred_img, n=self.dino_layers)
dino_losses = self.compute_dino_loss(pred_feats, dst_features, percept_mask)
# Total loss
final_loss = fm_loss.mean() + self.lpips_weight * lpips_loss
if self.use_dino:
final_loss = final_loss + self.feat_loss_weight * cos_loss
if "dino_percept_loss" in dino_losses:
final_loss = final_loss + self.dino_weight * dino_losses["dino_percept_loss"]
out_dict = dict(
fm_loss=fm_loss.mean(),
lpips_loss=lpips_loss,
loss=final_loss,
)
if self.use_dino:
out_dict["cos_loss"] = cos_loss
out_dict.update(dino_losses)
return out_dict
def state_dict(self, *args, destination=None, prefix="", keep_vars=False):
if self.proj is not None:
self.proj.state_dict(
destination=destination,
prefix=prefix + "proj.",
keep_vars=keep_vars)
class MedicalTrainerSimple(BaseTrainer):
"""
Simplified trainer for medical images with only LPIPS loss.
No DINO encoder required - suitable for domains where DINOv2 may not work well.
"""
def __init__(
self,
scheduler: BaseScheduler,
loss_weight_fn: Callable = constant,
lognorm_t: bool = True,
timeshift: float = 1.0,
P_mean: float = -0.8,
P_std: float = 0.8,
t_eps: float = 0.05,
lpips_weight: float = 0.1,
percept_t_threshold: float = 0.3,
noise_scale: float = 1.0,
patch_size: int = 16,
*args,
**kwargs
):
super().__init__(*args, **kwargs)
self.lognorm_t = lognorm_t
self.scheduler = scheduler
self.timeshift = timeshift
self.loss_weight_fn = loss_weight_fn
# LPIPS loss only
self.lpips_loss_fn = lpips.LPIPS(net='vgg').eval()
freeze_model(self.lpips_loss_fn)
self.patch_size = patch_size
self.P_mean = P_mean
self.P_std = P_std
self.t_eps = t_eps
self.lpips_weight = lpips_weight
self.percept_t_threshold = percept_t_threshold
self.noise_scale = noise_scale
def _impl_trainstep(self, net, ema_net, solver, x, condition, metadata=None):
"""
Training step for medical image generation.
For medical images, the 'condition' from conditioner is not used directly.
Instead, we use mask from metadata and class labels from metadata.
"""
mask = metadata.get("mask", None)
# Class labels - use zeros for medical (single class)
batch_size, c, height, width = x.shape
y = torch.zeros(batch_size, dtype=torch.long, device=x.device)
self.lpips_loss_fn.eval()
# Sample timesteps
if self.lognorm_t:
base_t = (torch.randn(batch_size, device=x.device, dtype=torch.float32) * self.P_std + self.P_mean).sigmoid()
else:
base_t = torch.rand((batch_size), device=x.device, dtype=torch.float32)
t = time_shift_fn(base_t, self.timeshift)
# Add noise
noise = self.noise_scale * torch.randn_like(x)
alpha = self.scheduler.alpha(t)
sigma = self.scheduler.sigma(t)
x_t = alpha * x + noise * sigma
v_t = (x - x_t) / (1 - t.view(-1, 1, 1, 1)).clamp_min(self.t_eps)
# Forward pass - mask is passed directly to the model
pred_img = net(x_t, t, y, mask=mask)
out = (pred_img - x_t) / (1 - t.view(-1, 1, 1, 1)).clamp_min(self.t_eps)
# Flow matching loss
weight = self.loss_weight_fn(alpha, sigma)
fm_loss = weight * (out - v_t) ** 2
# LPIPS loss with noise-gating
if self.percept_t_threshold > 0:
percept_mask = (t >= self.percept_t_threshold).float().reshape(batch_size, -1)
lpips_val = self.lpips_loss_fn(pred_img, x).view(batch_size, -1)
lpips_loss = (lpips_val * percept_mask).mean(dim=1)
lpips_loss = lpips_loss.sum() / percept_mask.sum() if percept_mask.sum() > 0 else lpips_loss.sum()
else:
lpips_loss = self.lpips_loss_fn(pred_img, x).mean()
final_loss = fm_loss.mean() + self.lpips_weight * lpips_loss
return dict(
fm_loss=fm_loss.mean(),
lpips_loss=lpips_loss,
loss=final_loss,
)
def state_dict(self, *args, destination=None, prefix="", keep_vars=False):
pass # No additional parameters to save