""" Compare sampling: No-CFG (direct mask) vs CFG vs Validation pipeline """ 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 from src.diffusion.flow_matching.scheduling import LinearScheduler device = torch.device("cuda:0") # Load model print("Loading model...") ckpt_path = "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_B16/epoch=236-step=100000.ckpt" ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) state_dict = ckpt["state_dict"] model = JiTMedical( 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 ) 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.load_state_dict(ema_state, strict=False) model = model.to(device).eval().to(torch.float32) print(f"Loaded EMA model ({len(ema_state)} keys)") scheduler = LinearScheduler() def shift_respace_fn(t, shift=1.0): return t / (t + (1 - t) * shift) @torch.no_grad() def sample_no_cfg(model, noise, mask, num_steps=50, t_eps=0.05): """Single-path sampling: directly pass mask to model, no CFG.""" 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 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) # Single forward pass with mask pred_img = model(x, t_batch, y, mask=mask) # Convert x-prediction to velocity v = (pred_img - x) / (1.0 - t_batch.view(-1, 1, 1, 1)).clamp_min(t_eps) # Euler step x = x + v * dt return x @torch.no_grad() def sample_with_cfg(model, noise, mask, num_steps=50, cfg_scale=2.0, t_eps=0.05): """Dual-path CFG sampling.""" 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 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: concat uncond + cond 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(t_eps) # CFG v_uncond, v_cond = pred_v.chunk(2) v = v_uncond + cfg_scale * (v_cond - v_uncond) x = x + v * dt return x @torch.no_grad() def sample_no_mask(model, noise, num_steps=50, t_eps=0.05): """No-mask sampling (like validation pipeline).""" 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 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) # No mask -> mask_emb = zeros pred_img = model(x, t_batch, y, mask=None) v = (pred_img - x) / (1.0 - t_batch.view(-1, 1, 1, 1)).clamp_min(t_eps) x = x + v * dt return x # Load 6 samples data_root = "/data2/sichengli/Data/test/Segmentation/OCTA500" img_dir = os.path.join(data_root, "images") mask_dir = os.path.join(data_root, "masks") all_files = sorted([f for f in os.listdir(img_dir) if f.endswith(".png") and not f.startswith("thumb")]) random.seed(456) selected = random.sample(all_files, 6) images_list, masks_list = [], [] for fname in selected: img = Image.open(os.path.join(img_dir, fname)).convert("L") img = TF.resize(img, (256, 256)) images_list.append(TF.to_tensor(img).repeat(3, 1, 1)) mask = Image.open(os.path.join(mask_dir, fname)).convert("L") mask = TF.resize(mask, (256, 256), interpolation=transforms.InterpolationMode.NEAREST) masks_list.append(TF.to_tensor(mask)) real_images = torch.stack(images_list) masks_tensor = torch.stack(masks_list).to(device) # Same noise for all torch.manual_seed(42) shared_noise = torch.randn(6, 3, 256, 256, device=device) # Generate with different methods print("1/3 No-CFG (direct mask)...") gen_no_cfg = sample_no_cfg(model, shared_noise.clone(), masks_tensor).clamp(-1, 1) * 0.5 + 0.5 print("2/3 CFG=2.0 (current)...") gen_cfg = sample_with_cfg(model, shared_noise.clone(), masks_tensor, cfg_scale=2.0).clamp(-1, 1) * 0.5 + 0.5 print("3/3 No mask (like val pipeline)...") gen_no_mask = sample_no_mask(model, shared_noise.clone()).clamp(-1, 1) * 0.5 + 0.5 results = { "Mask": None, "No-CFG\n(+mask)": gen_no_cfg.cpu(), "CFG=2.0\n(+mask)": gen_cfg.cpu(), "No-Mask\n(val mode)": gen_no_mask.cpu(), "Real": None, } # Create comparison grid col_labels = list(results.keys()) n_rows = 6 n_cols = len(col_labels) h, w = 256, 256 pad = 4 label_h = 48 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 # Column labels try: font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 16) except Exception: font = ImageFont.load_default() pil_canvas = Image.fromarray(canvas) draw = ImageDraw.Draw(pil_canvas) for col, label in enumerate(col_labels): x_pos = pad + col * (w + pad) + w // 2 lines = label.split("\n") for li, line in enumerate(lines): bbox = draw.textbbox((0, 0), line, font=font) text_w = bbox[2] - bbox[0] draw.text((x_pos - text_w // 2, 4 + li * 20), line, fill=(255, 255, 255), font=font) canvas = np.array(pil_canvas) color_map = {0: (0,0,0), 50: (255,80,80), 100: (80,255,80), 150: (80,80,255), 200: (255,255,80), 250: (255,80,255)} for row in range(n_rows): y = label_h + pad + row * (h + pad) for col_idx, col_name in enumerate(col_labels): x = pad + col_idx * (w + pad) if "Mask" == col_name: m = masks_tensor[row, 0].cpu().numpy() m_uint8 = (m * 255).astype(np.uint8) m_colored = np.zeros((h, w, 3), dtype=np.uint8) for val, color in color_map.items(): mask_region = np.abs(m_uint8.astype(int) - val) < 13 m_colored[mask_region] = color canvas[y:y+h, x:x+w] = m_colored elif "Real" in col_name: r = real_images[row].permute(1, 2, 0).numpy() canvas[y:y+h, x:x+w] = (r * 255).clip(0, 255).astype(np.uint8) else: g = results[col_name][row].permute(1, 2, 0).numpy() canvas[y:y+h, x:x+w] = (g * 255).clip(0, 255).astype(np.uint8) out = "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_B16/val_samples/sampling_method_compare.png" Image.fromarray(canvas).save(out) print(f"\nSaved: {out}")