File size: 13,856 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
"""
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 = []  # list of (step_idx, t_value, x0_pred, x_t)

    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 forward
        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)

        # The model predicts x0; extract conditional prediction
        pred_uncond, pred_cond = pred.chunk(2)

        # Velocity from x0 prediction
        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)

        # Save the CFG-guided x0 prediction: x0 = x_t + v * (1 - t)
        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(),
        })

        # Euler step
        x = x + v * dt

    # Final result
    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 = []  # (img_tensor, mask_tensor, name)

    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  # [-1,1] -> [0,1]
    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:
        # Multi-class (REFUGE2): colorize
        rgb = np.zeros((*m.shape, 3), dtype=np.uint8)
        rgb[m > 0.7] = [255, 80, 80]      # optic disc = red
        rgb[(m > 0.3) & (m <= 0.7)] = [80, 80, 255]  # optic cup = blue
        return rgb
    else:
        # Binary mask
        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)

    # Load model
    model = load_model(cfg["ckpt"])

    # Load samples
    samples = load_samples(cfg, cfg["n_samples"])
    print(f"  Loaded {len(samples)} samples")

    # Steps to show in combined grid (select ~12 representative steps)
    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)

        # Generate with intermediates
        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)

        # Save mask and real image
        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"))

        # Save initial noise
        noise_vis = tensor_to_uint8(noise[0].cpu())
        Image.fromarray(noise_vis).save(os.path.join(sample_dir, "step_00_noise.png"))

        # Save every step's x0 prediction
        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}/")

        # ─── Combined grid for this sample ───
        # Layout: Noise | step1 | step3 | ... | step50 | Real
        # With Mask on top-left or as first column
        h, w = 256, 256
        pad = 3

        # Columns: Mask, Noise, selected steps, Real
        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})")

    # ─── Final combined image: all samples for this dataset ───
    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())

        # Re-read saved step images for grid
        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)

    # Build combined grid
    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!")