Segmentation / code /scripts /vis_sampling_compare.py
MaybeRichard's picture
Upload PixelGen code: cross-attention mask mode + multi-scale ablation configs
01fdb75 verified
raw
history blame
5.77 kB
"""
Compare different sampling strategies: Euler-50, Euler-100, Euler-200, Heun-50
Layout: Mask | Euler-50 | Euler-100 | Euler-200 | Heun-50 | 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.sampling_medical import EulerSamplerMedical, HeunSamplerMedical
from src.diffusion.flow_matching.scheduling import LinearScheduler
from src.diffusion.base.guidance import simple_guidance_fn
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)
# Shared sampler kwargs
sampler_kwargs = dict(
guidance=2.0, timeshift=1.0,
guidance_interval_min=0.1, guidance_interval_max=0.9,
scheduler=LinearScheduler(), w_scheduler=LinearScheduler(),
guidance_fn=simple_guidance_fn,
)
# Build samplers
samplers = {
"Euler-50": EulerSamplerMedical(num_steps=50, **sampler_kwargs).to(device),
"Euler-100": EulerSamplerMedical(num_steps=100, **sampler_kwargs).to(device),
"Euler-200": EulerSamplerMedical(num_steps=200, **sampler_kwargs).to(device),
"Heun-50": HeunSamplerMedical(num_steps=50, **sampler_kwargs).to(device),
}
# 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)
# Use same noise for fair comparison
torch.manual_seed(42)
shared_noise = torch.randn(6, 3, 256, 256, device=device)
# Generate with each sampler
results = {}
for name, sampler in samplers.items():
print(f"Generating with {name}...")
with torch.no_grad():
noise = shared_noise.clone()
x_trajs, _ = sampler._impl_sampling(model, noise, None, None, mask=masks_tensor.to(device))
gen = x_trajs[-1].clamp(-1, 1) * 0.5 + 0.5
results[name] = gen.cpu()
print(f" Done. range=[{gen.min():.3f}, {gen.max():.3f}]")
# Create comparison grid
# Columns: Mask | Euler-50 | Euler-100 | Euler-200 | Heun-50 | Real
col_labels = ["Mask", "Euler-50", "Euler-100", "Euler-200", "Heun-50", "Real"]
n_rows = 6
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)
# Colormap for mask
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 col_name == "Mask":
m = masks_tensor[row, 0].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 col_name == "Real":
r = real_images[row].permute(1, 2, 0).numpy()
r = (r * 255).clip(0, 255).astype(np.uint8)
canvas[y:y+h, x:x+w] = r
else:
g = results[col_name][row].permute(1, 2, 0).numpy()
g = (g * 255).clip(0, 255).astype(np.uint8)
canvas[y:y+h, x:x+w] = g
out_dir = "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_B16/val_samples"
out_path = os.path.join(out_dir, "sampling_compare.png")
Image.fromarray(canvas).save(out_path)
print(f"\nSaved: {out_path} ({canvas_w}x{canvas_h})")