File size: 7,497 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
"""
REFUGE2: Spatial mask control visualization
mask_mode='spatial' — mask patchified and added to patch embeddings
3-class masks: 0=background, 128=optic cup, 255=optic disc
Layout: Mask | No-CFG | 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

device = torch.device("cuda:0")

# Load model
print("Loading model...")
ckpt_path = "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_REFUGE2/last.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,
    mask_mode="spatial"
)
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
result = model.load_state_dict(ema_state, strict=False)
print(f"Loaded EMA model ({len(ema_state)} keys), missing: {result.missing_keys}, unexpected: {result.unexpected_keys}")
model = model.to(device).eval().to(torch.float32)

# Get current step from checkpoint
global_step = ckpt.get("global_step", "unknown")
print(f"Checkpoint global_step: {global_step}")


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):
    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):
    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 train+val (same splits used for training)
data_root = "/data2/sichengli/Data/test/Segmentation/REFUGE2"
all_pairs = []
for split in ["train", "val"]:
    img_dir = os.path.join(data_root, split, "images")
    mask_dir = os.path.join(data_root, split, "mask")
    img_files = sorted([f for f in os.listdir(img_dir) if f.endswith((".jpg", ".png", ".jpeg"))])
    for img_f in img_files:
        base_name = os.path.splitext(img_f)[0]
        img_path = os.path.join(img_dir, img_f)
        for ext in [".bmp", ".png", ".jpg"]:
            candidate = os.path.join(mask_dir, base_name + ext)
            if os.path.exists(candidate):
                all_pairs.append((img_path, candidate))
                break

# Use the val holdout samples (last 10%)
random.seed(42)
random.shuffle(all_pairs)
val_pairs = all_pairs[int(len(all_pairs) * 0.9):]

random.seed(789)
selected = random.sample(val_pairs, min(6, len(val_pairs)))

images_list, masks_list = [], []
for img_path, mask_path in selected:
    img = Image.open(img_path).convert("RGB")
    img = TF.resize(img, (256, 256))
    images_list.append(TF.to_tensor(img))
    mask = Image.open(mask_path).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)

torch.manual_seed(42)
shared_noise = torch.randn(len(selected), 3, 256, 256, device=device)

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,
}

# Colorize 3-class mask for better visualization
def colorize_mask(mask_gray):
    """Convert grayscale mask (0/0.5/1.0) to color: black/blue/red."""
    h, w = mask_gray.shape
    rgb = np.zeros((h, w, 3), dtype=np.uint8)
    rgb[mask_gray > 0.7] = [255, 80, 80]    # optic disc = red
    rgb[(mask_gray > 0.3) & (mask_gray <= 0.7)] = [80, 80, 255]  # optic cup = blue
    return rgb

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

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":
            m = masks_tensor[row, 0].cpu().numpy()
            canvas[y:y+h, x:x+w] = colorize_mask(m)
        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_REFUGE2/val_samples"
os.makedirs(out_dir, exist_ok=True)
out_path = os.path.join(out_dir, f"mask_control_spatial_step{global_step}.png")
Image.fromarray(canvas).save(out_path)
print(f"\nSaved: {out_path} ({canvas_w}x{canvas_h})")