| """ |
| Visualize the step-by-step denoising process for each dataset. |
| For each sample: |
| - Save predicted x0 at EVERY step as individual images |
| - Create a combined grid showing the full progression |
| """ |
| import sys |
| sys.path.insert(0, "/data/sichengli/Code/PixelGen") |
|
|
| import torch |
| import numpy as np |
| from PIL import Image, ImageDraw, ImageFont |
| import torchvision.transforms as transforms |
| import torchvision.transforms.functional as TF |
| import os, random |
|
|
| from src.models.transformer.JiT_medical import JiTMedical |
|
|
| device = torch.device("cuda:0") |
|
|
| MODEL_KWARGS = dict( |
| input_size=256, patch_size=16, in_channels=3, |
| hidden_size=768, depth=12, num_heads=12, mlp_ratio=4.0, |
| attn_drop=0.0, proj_drop=0.1, num_classes=1, |
| use_bottleneck=True, bottleneck_dim=128, |
| in_context_len=32, in_context_start=4, mask_in_channels=1, |
| mask_mode="spatial" |
| ) |
|
|
| NUM_STEPS = 50 |
| CFG_SCALE = 2.0 |
|
|
| DATASETS = { |
| "cvc": { |
| "data_root": "/data2/sichengli/Data/test/Segmentation/CVC-ClinicDB", |
| "img_subdir": "PNG/Original", |
| "mask_subdir": "PNG/Ground Truth", |
| "file_ext": (".png",), |
| "ckpt": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_CVC/epoch=19999-step=100000.ckpt", |
| "out_base": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_CVC/sampling_process", |
| "multi_split": False, |
| "n_samples": 3, |
| }, |
| "kvasir": { |
| "data_root": "/data2/sichengli/Data/test/Segmentation/Kvasir-SEG/Kvasir-SEG", |
| "img_subdir": "images", |
| "mask_subdir": "masks", |
| "file_ext": (".jpg", ".png", ".jpeg"), |
| "ckpt": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_Kvasir/epoch=12499-step=100000.ckpt", |
| "out_base": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_Kvasir/sampling_process", |
| "multi_split": False, |
| "n_samples": 3, |
| }, |
| "refuge2": { |
| "data_root": "/data2/sichengli/Data/test/Segmentation/REFUGE2", |
| "img_subdir": None, |
| "mask_subdir": None, |
| "file_ext": (".jpg", ".png", ".jpeg"), |
| "mask_ext": (".bmp", ".png"), |
| "ckpt": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_REFUGE2/epoch=16666-step=100000.ckpt", |
| "out_base": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_REFUGE2/sampling_process", |
| "multi_split": True, |
| "splits": ["train", "val"], |
| "n_samples": 3, |
| }, |
| } |
|
|
|
|
| def load_model(ckpt_path): |
| ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) |
| state_dict = ckpt["state_dict"] |
| ema_state = {} |
| for k, v in state_dict.items(): |
| if k.startswith("ema_denoiser."): |
| new_k = k.replace("ema_denoiser.", "").replace("_orig_mod.", "") |
| ema_state[new_k] = v |
| model = JiTMedical(**MODEL_KWARGS) |
| model.load_state_dict(ema_state, strict=False) |
| model = model.to(device).eval().to(torch.float32) |
| return model |
|
|
|
|
| def shift_respace_fn(t, shift=1.0): |
| return t / (t + (1 - t) * shift) |
|
|
|
|
| @torch.no_grad() |
| def sample_with_intermediates(model, noise, mask, num_steps=50, cfg_scale=2.0, t_eps=0.05): |
| """ |
| Euler ODE sampler with CFG. Returns predicted x0 at every step. |
| """ |
| batch_size = noise.shape[0] |
| timesteps = torch.linspace(0.0, 1 - 1.0 / num_steps, num_steps) |
| timesteps = torch.cat([timesteps, torch.tensor([1.0])], dim=0) |
| timesteps = shift_respace_fn(timesteps, 1.0).to(noise.device) |
| y = torch.zeros(batch_size, dtype=torch.long, device=noise.device) |
|
|
| x = noise.clone() |
| intermediates = [] |
|
|
| 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(batch_size) |
|
|
| |
| 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_uncond, pred_cond = pred.chunk(2) |
|
|
| |
| pred_v = (pred - cfg_x) / (1.0 - cfg_t.view(-1, 1, 1, 1)).clamp_min(t_eps) |
| v_uncond, v_cond = pred_v.chunk(2) |
| v = v_uncond + cfg_scale * (v_cond - v_uncond) |
|
|
| |
| x0_pred = x + v * (1.0 - t_cur) |
|
|
| intermediates.append({ |
| "step": i + 1, |
| "t": t_cur.item(), |
| "x0_pred": x0_pred.clamp(-1, 1).cpu(), |
| "x_t": x.clamp(-1, 1).cpu(), |
| }) |
|
|
| |
| x = x + v * dt |
|
|
| |
| intermediates.append({ |
| "step": num_steps, |
| "t": 1.0, |
| "x0_pred": x.clamp(-1, 1).cpu(), |
| "x_t": x.clamp(-1, 1).cpu(), |
| }) |
|
|
| return x, intermediates |
|
|
|
|
| def load_samples(cfg, n_samples, seed=777): |
| """Load random image-mask pairs from dataset.""" |
| pairs = [] |
|
|
| if cfg["multi_split"]: |
| all_pairs = [] |
| for split in cfg["splits"]: |
| img_dir = os.path.join(cfg["data_root"], split, "images") |
| mask_dir = os.path.join(cfg["data_root"], split, "mask") |
| img_files = sorted([f for f in os.listdir(img_dir) if f.endswith(cfg["file_ext"])]) |
| for img_f in img_files: |
| base = os.path.splitext(img_f)[0] |
| for ext in cfg["mask_ext"]: |
| cand = os.path.join(mask_dir, base + ext) |
| if os.path.exists(cand): |
| all_pairs.append((os.path.join(img_dir, img_f), cand, f"{split}_{base}")) |
| break |
| random.seed(seed) |
| selected = random.sample(all_pairs, min(n_samples, len(all_pairs))) |
| for img_path, mask_path, name in selected: |
| img = Image.open(img_path).convert("RGB") |
| img = TF.resize(img, (256, 256)) |
| mask = Image.open(mask_path).convert("L") |
| mask = TF.resize(mask, (256, 256), interpolation=transforms.InterpolationMode.NEAREST) |
| pairs.append((TF.to_tensor(img), TF.to_tensor(mask), name)) |
| else: |
| img_dir = os.path.join(cfg["data_root"], cfg["img_subdir"]) |
| mask_dir = os.path.join(cfg["data_root"], cfg["mask_subdir"]) |
| all_files = sorted([f for f in os.listdir(img_dir) if f.endswith(cfg["file_ext"])]) |
| random.seed(seed) |
| selected = random.sample(all_files, min(n_samples, len(all_files))) |
| for fname in selected: |
| img = Image.open(os.path.join(img_dir, fname)).convert("RGB") |
| img = TF.resize(img, (256, 256)) |
| mask = Image.open(os.path.join(mask_dir, fname)).convert("L") |
| mask = TF.resize(mask, (256, 256), interpolation=transforms.InterpolationMode.NEAREST) |
| name = os.path.splitext(fname)[0] |
| pairs.append((TF.to_tensor(img), TF.to_tensor(mask), name)) |
|
|
| return pairs |
|
|
|
|
| def tensor_to_uint8(t): |
| """Convert [-1,1] or [0,1] tensor to uint8 numpy [H,W,3].""" |
| img = t.clamp(-1, 1) * 0.5 + 0.5 |
| return (img.permute(1, 2, 0).numpy() * 255).clip(0, 255).astype(np.uint8) |
|
|
|
|
| def mask_to_rgb(mask_tensor): |
| """Convert [1,H,W] mask tensor to [H,W,3] uint8.""" |
| m = mask_tensor[0].numpy() |
| if len(np.unique(m)) > 2: |
| |
| rgb = np.zeros((*m.shape, 3), dtype=np.uint8) |
| rgb[m > 0.7] = [255, 80, 80] |
| rgb[(m > 0.3) & (m <= 0.7)] = [80, 80, 255] |
| return rgb |
| else: |
| |
| m_rgb = np.stack([m, m, m], axis=-1) |
| return (m_rgb * 255).clip(0, 255).astype(np.uint8) |
|
|
|
|
| def process_dataset(ds_name, cfg): |
| print(f"\n{'='*60}") |
| print(f" Processing: {ds_name.upper()}") |
| print(f"{'='*60}") |
|
|
| out_base = cfg["out_base"] |
| os.makedirs(out_base, exist_ok=True) |
|
|
| |
| model = load_model(cfg["ckpt"]) |
|
|
| |
| samples = load_samples(cfg, cfg["n_samples"]) |
| print(f" Loaded {len(samples)} samples") |
|
|
| |
| grid_steps = [1, 3, 5, 8, 10, 15, 20, 25, 30, 35, 40, 45, 50] |
|
|
| for sample_idx, (real_img, mask_tensor, name) in enumerate(samples): |
| print(f"\n Sample {sample_idx+1}/{len(samples)}: {name}") |
| sample_dir = os.path.join(out_base, name) |
| os.makedirs(sample_dir, exist_ok=True) |
|
|
| |
| mask_gpu = mask_tensor.unsqueeze(0).to(device) |
| torch.manual_seed(sample_idx * 100 + 42) |
| noise = torch.randn(1, 3, 256, 256, device=device) |
|
|
| _, intermediates = sample_with_intermediates(model, noise, mask_gpu, NUM_STEPS, CFG_SCALE) |
|
|
| |
| Image.fromarray(mask_to_rgb(mask_tensor)).save(os.path.join(sample_dir, "mask.png")) |
| Image.fromarray((real_img.permute(1, 2, 0).numpy() * 255).clip(0, 255).astype(np.uint8)).save( |
| os.path.join(sample_dir, "real.png")) |
|
|
| |
| noise_vis = tensor_to_uint8(noise[0].cpu()) |
| Image.fromarray(noise_vis).save(os.path.join(sample_dir, "step_00_noise.png")) |
|
|
| |
| for item in intermediates: |
| step = item["step"] |
| x0 = tensor_to_uint8(item["x0_pred"][0]) |
| Image.fromarray(x0).save(os.path.join(sample_dir, f"step_{step:02d}_x0pred.png")) |
|
|
| print(f" Saved {len(intermediates)+2} individual images to {sample_dir}/") |
|
|
| |
| |
| |
| h, w = 256, 256 |
| pad = 3 |
|
|
| |
| col_items = [("Mask", mask_to_rgb(mask_tensor))] |
| col_items.append(("Noise", noise_vis)) |
| for item in intermediates: |
| if item["step"] in grid_steps: |
| label = f"Step {item['step']}" |
| col_items.append((label, tensor_to_uint8(item["x0_pred"][0]))) |
| col_items.append(("Real", (real_img.permute(1, 2, 0).numpy() * 255).clip(0, 255).astype(np.uint8))) |
|
|
| n_cols = len(col_items) |
| label_h = 30 |
| canvas_w = n_cols * w + (n_cols + 1) * pad |
| canvas_h = h + 2 * pad + label_h |
| canvas = np.ones((canvas_h, canvas_w, 3), dtype=np.uint8) * 30 |
|
|
| try: |
| font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 14) |
| except Exception: |
| font = ImageFont.load_default() |
|
|
| pil_canvas = Image.fromarray(canvas) |
| draw = ImageDraw.Draw(pil_canvas) |
| for col, (label, _) in enumerate(col_items): |
| x_pos = pad + col * (w + pad) + w // 2 |
| bbox = draw.textbbox((0, 0), label, font=font) |
| text_w = bbox[2] - bbox[0] |
| draw.text((x_pos - text_w // 2, 6), label, fill=(255, 255, 255), font=font) |
| canvas = np.array(pil_canvas) |
|
|
| for col, (_, img_np) in enumerate(col_items): |
| x = pad + col * (w + pad) |
| y = label_h + pad |
| canvas[y:y+h, x:x+w] = img_np |
|
|
| grid_path = os.path.join(sample_dir, f"progression_grid.png") |
| Image.fromarray(canvas).save(grid_path) |
| print(f" Saved grid: {grid_path} ({canvas_w}x{canvas_h})") |
|
|
| |
| all_samples_data = [] |
| for sample_idx, (real_img, mask_tensor, name) in enumerate(samples): |
| sample_dir = os.path.join(out_base, name) |
| mask_gpu = mask_tensor.unsqueeze(0).to(device) |
| torch.manual_seed(sample_idx * 100 + 42) |
| noise = torch.randn(1, 3, 256, 256, device=device) |
| noise_vis = tensor_to_uint8(noise[0].cpu()) |
|
|
| |
| row_imgs = [("Mask", mask_to_rgb(mask_tensor)), ("Noise", noise_vis)] |
| for step in grid_steps: |
| fpath = os.path.join(sample_dir, f"step_{step:02d}_x0pred.png") |
| if os.path.exists(fpath): |
| row_imgs.append((f"Step {step}", np.array(Image.open(fpath)))) |
| row_imgs.append(("Real", (real_img.permute(1, 2, 0).numpy() * 255).clip(0, 255).astype(np.uint8))) |
| all_samples_data.append(row_imgs) |
|
|
| |
| n_rows = len(all_samples_data) |
| n_cols = len(all_samples_data[0]) |
| h, w = 256, 256 |
| pad = 3 |
| label_h = 30 |
|
|
| canvas_w = n_cols * w + (n_cols + 1) * pad |
| canvas_h = n_rows * h + (n_rows + 1) * pad + label_h |
| canvas = np.ones((canvas_h, canvas_w, 3), dtype=np.uint8) * 30 |
|
|
| pil_canvas = Image.fromarray(canvas) |
| draw = ImageDraw.Draw(pil_canvas) |
| for col, (label, _) in enumerate(all_samples_data[0]): |
| x_pos = pad + col * (w + pad) + w // 2 |
| bbox = draw.textbbox((0, 0), label, font=font) |
| text_w = bbox[2] - bbox[0] |
| draw.text((x_pos - text_w // 2, 6), label, fill=(255, 255, 255), font=font) |
| canvas = np.array(pil_canvas) |
|
|
| for row_idx, row_imgs in enumerate(all_samples_data): |
| y = label_h + pad + row_idx * (h + pad) |
| for col_idx, (_, img_np) in enumerate(row_imgs): |
| x = pad + col_idx * (w + pad) |
| canvas[y:y+h, x:x+w] = img_np |
|
|
| combined_path = os.path.join(out_base, f"all_samples_progression.png") |
| Image.fromarray(canvas).save(combined_path) |
| print(f"\n Combined grid saved: {combined_path} ({canvas_w}x{canvas_h})") |
|
|
| del model |
| import gc |
| gc.collect() |
| torch.cuda.empty_cache() |
|
|
|
|
| if __name__ == "__main__": |
| for ds_name, cfg in DATASETS.items(): |
| process_dataset(ds_name, cfg) |
| print("\nAll done!") |
|
|