File size: 6,934 Bytes
01fdb75 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | """
CVC-ClinicDB: Mask control visualization
No-CFG sampling (single-path with mask) using the trained model with null condition dropout.
Layout: Mask | Generated (No-CFG) | Generated (CFG=2.0) | Real
"""
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_CVC/epoch=999-step=5000.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)")
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)
pred_img = model(x, t_batch, y, mask=mask)
v = (pred_img - x) / (1.0 - t_batch.view(-1, 1, 1, 1)).clamp_min(t_eps)
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_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)
v_uncond, v_cond = pred_v.chunk(2)
v = v_uncond + cfg_scale * (v_cond - v_uncond)
x = x + v * dt
return x
# Load samples from val set
data_root = "/data2/sichengli/Data/test/Segmentation/CVC-ClinicDB"
img_dir = os.path.join(data_root, "PNG", "Original")
mask_dir = os.path.join(data_root, "PNG", "Ground Truth")
all_files = sorted([f for f in os.listdir(img_dir) if f.endswith(".png")])
# Use val set samples (same split as training)
random.seed(42)
indices = list(range(len(all_files)))
random.shuffle(indices)
val_indices = indices[int(len(indices) * 0.9):] # last 10% = val
val_files = [all_files[i] for i in sorted(val_indices)]
random.seed(123)
selected = random.sample(val_files, min(6, len(val_files)))
images_list, masks_list = [], []
for fname in selected:
img = Image.open(os.path.join(img_dir, fname)).convert("RGB")
img = TF.resize(img, (256, 256))
images_list.append(TF.to_tensor(img))
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(len(selected), 3, 256, 256, device=device)
# Generate
print("1/2 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/2 CFG=2.0...")
gen_cfg = sample_with_cfg(model, shared_noise.clone(), masks_tensor, cfg_scale=2.0).clamp(-1, 1) * 0.5 + 0.5
results = {
"Mask": None,
"No-CFG": gen_no_cfg.cpu(),
"CFG=2.0": gen_cfg.cpu(),
"Real": None,
}
# Create comparison grid
col_labels = list(results.keys())
n_rows = len(selected)
n_cols = len(col_labels)
h, w = 256, 256
pad = 4
label_h = 36
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", 20)
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
bbox = draw.textbbox((0, 0), label, font=font)
text_w = bbox[2] - bbox[0]
draw.text((x_pos - text_w // 2, 8), label, fill=(255, 255, 255), font=font)
canvas = np.array(pil_canvas)
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 col_name == "Mask":
# Binary mask: white = polyp, black = background
m = masks_tensor[row, 0].cpu().numpy()
m_rgb = np.stack([m, m, m], axis=-1)
canvas[y:y+h, x:x+w] = (m_rgb * 255).clip(0, 255).astype(np.uint8)
elif col_name == "Real":
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_dir = "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_CVC/val_samples"
os.makedirs(out_dir, exist_ok=True)
out_path = os.path.join(out_dir, "mask_control_step5000.png")
Image.fromarray(canvas).save(out_path)
print(f"\nSaved: {out_path} ({canvas_w}x{canvas_h})")
|