Segmentation / code /src /callbacks /medical_visualization.py
MaybeRichard's picture
Update: fix mask passing in validation, add MedicalVisualizationCallback, optimize for 2xH800
e18eb8a verified
raw
history blame
7.51 kB
# Medical Visualization Callback
# Saves mask + generated image grids during training for visual quality monitoring
import os
import torch
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import lightning.pytorch as pl
from lightning.pytorch import Callback
from lightning_utilities.core.rank_zero import rank_zero_info
class MedicalVisualizationCallback(Callback):
"""
Periodically generates and saves visualization grids during training.
Each grid shows: [Mask | Generated (CFG) | Generated (No-CFG)]
for a fixed set of masks, allowing visual comparison across training.
"""
def __init__(
self,
every_n_steps: int = 5000,
num_samples: int = 8,
num_sampling_steps: int = 50,
cfg_scale: float = 2.0,
save_dir: str = "training_vis",
t_eps: float = 0.05,
):
super().__init__()
self.every_n_steps = every_n_steps
self.num_samples = num_samples
self.num_sampling_steps = num_sampling_steps
self.cfg_scale = cfg_scale
self.save_dir = save_dir
self.t_eps = t_eps
self._fixed_noise = None
self._fixed_masks = None
def _shift_respace_fn(self, t, shift=1.0):
return t / (t + (1 - t) * shift)
@torch.no_grad()
def _sample(self, model, noise, mask, cfg_scale=None):
"""Euler sampling with optional CFG, directly passing mask to model."""
bs = noise.shape[0]
timesteps = torch.linspace(0.0, 1 - 1.0 / self.num_sampling_steps, self.num_sampling_steps)
timesteps = torch.cat([timesteps, torch.tensor([1.0])], dim=0)
timesteps = self._shift_respace_fn(timesteps, 1.0).to(noise.device)
y = torch.zeros(bs, dtype=torch.long, device=noise.device)
x = noise
for i in range(len(timesteps) - 1):
t_cur = timesteps[i]
t_next = timesteps[i + 1]
dt = t_next - t_cur
t_batch = t_cur.repeat(bs)
if cfg_scale is not None and cfg_scale > 1.0:
# CFG: concat unconditional + conditional
cfg_x = torch.cat([x, x], dim=0)
cfg_t = t_batch.repeat(2)
cfg_y = torch.cat([y, y], dim=0)
cfg_mask = torch.cat([torch.zeros_like(mask), mask], dim=0)
pred = model(cfg_x, cfg_t, cfg_y, mask=cfg_mask)
pred_v = (pred - cfg_x) / (1.0 - cfg_t.view(-1, 1, 1, 1)).clamp_min(self.t_eps)
v_uncond, v_cond = pred_v.chunk(2)
v = v_uncond + cfg_scale * (v_cond - v_uncond)
else:
# No CFG
pred = model(x, t_batch, y, mask=mask)
v = (pred - x) / (1.0 - t_batch.view(-1, 1, 1, 1)).clamp_min(self.t_eps)
x = x + v * dt
return x.clamp(-1, 1) * 0.5 + 0.5 # [-1,1] -> [0,1]
def _mask_to_rgb(self, mask_tensor):
"""Convert single-channel mask [1, H, W] to RGB [H, W, 3] uint8."""
m = mask_tensor[0].cpu().numpy()
unique_vals = np.unique(m)
if len(unique_vals) <= 3:
# Multi-class: colorize (e.g., REFUGE2: 0=black, ~0.5=blue, ~1.0=red)
rgb = np.zeros((*m.shape, 3), dtype=np.uint8)
rgb[m < 0.1] = [0, 0, 0] # background
rgb[(m >= 0.1) & (m < 0.7)] = [0, 120, 255] # class 1 (blue)
rgb[m >= 0.7] = [255, 60, 60] # class 2 (red)
else:
# Binary or continuous: grayscale
m_uint8 = (m * 255).astype(np.uint8)
rgb = np.stack([m_uint8] * 3, axis=-1)
return rgb
def _make_grid(self, masks, gen_cfg, gen_nocfg, step):
"""Create visualization grid: Mask | CFG | No-CFG."""
n = masks.shape[0]
h, w = masks.shape[2], masks.shape[3]
pad = 4
col_labels = ["Mask", f"CFG={self.cfg_scale}", "No-CFG"]
n_cols = len(col_labels)
header_h = 30
canvas_w = n_cols * w + (n_cols + 1) * pad
canvas_h = n * h + (n + 1) * pad + header_h
canvas = np.ones((canvas_h, canvas_w, 3), dtype=np.uint8) * 40
# Header
try:
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 16)
except (IOError, OSError):
font = ImageFont.load_default()
img_pil = Image.fromarray(canvas)
draw = ImageDraw.Draw(img_pil)
for col_idx, label in enumerate(col_labels):
x_pos = pad + col_idx * (w + pad) + w // 2
draw.text((x_pos, 6), label, fill=(255, 255, 255), font=font, anchor="mt")
# Step info
draw.text((canvas_w - 10, 6), f"step={step}", fill=(180, 180, 180), font=font, anchor="rt")
canvas = np.array(img_pil)
for row in range(n):
y_pos = header_h + pad + row * (h + pad)
# Mask column
mask_rgb = self._mask_to_rgb(masks[row])
x_pos = pad
canvas[y_pos:y_pos + h, x_pos:x_pos + w] = mask_rgb
# CFG generated
img_cfg = (gen_cfg[row].permute(1, 2, 0).cpu().numpy() * 255).clip(0, 255).astype(np.uint8)
x_pos = pad + (w + pad)
canvas[y_pos:y_pos + h, x_pos:x_pos + w] = img_cfg
# No-CFG generated
img_nocfg = (gen_nocfg[row].permute(1, 2, 0).cpu().numpy() * 255).clip(0, 255).astype(np.uint8)
x_pos = pad + 2 * (w + pad)
canvas[y_pos:y_pos + h, x_pos:x_pos + w] = img_nocfg
return canvas
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
step = trainer.global_step
if step == 0 or step % self.every_n_steps != 0:
return
if not trainer.is_global_zero:
return
# Initialize fixed noise and masks from first validation batch
if self._fixed_masks is None:
eval_dl = trainer.datamodule.val_dataloader()
for eval_batch in eval_dl:
xT, y, metadata = eval_batch
mask = metadata.get('mask', None) if isinstance(metadata, dict) else None
if mask is None:
rank_zero_info("[MedicalVis] No mask in eval batch, skipping visualization")
return
n = min(self.num_samples, mask.shape[0])
self._fixed_masks = mask[:n].to(pl_module.device)
self._fixed_noise = torch.randn(
n, 3, pl_module.denoiser.input_size, pl_module.denoiser.input_size,
device=pl_module.device, generator=torch.Generator(device=pl_module.device).manual_seed(42)
)
break
if self._fixed_masks is None:
return
# Generate samples using EMA model
model = pl_module.ema_denoiser
was_training = model.training
model.eval()
noise = self._fixed_noise
masks = self._fixed_masks
gen_cfg = self._sample(model, noise, masks, cfg_scale=self.cfg_scale)
gen_nocfg = self._sample(model, noise, masks, cfg_scale=None)
if was_training:
model.train()
# Save grid
save_path = os.path.join(trainer.default_root_dir, self.save_dir)
os.makedirs(save_path, exist_ok=True)
grid = self._make_grid(masks, gen_cfg, gen_nocfg, step)
Image.fromarray(grid).save(os.path.join(save_path, f"vis_step_{step:06d}.png"))
rank_zero_info(f"[MedicalVis] Saved visualization at step {step}")