File size: 5,907 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
"""
Kvasir-SEG: Training progression visualization
Compare generated images across different checkpoints
Layout: Mask | 10k | 30k | 50k | 70k | 100k | 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, gc

from src.models.transformer.JiT_medical import JiTMedical

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

# Checkpoints to compare
ckpt_dir = "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_Kvasir"
checkpoints = [
    ("10k",  os.path.join(ckpt_dir, "epoch=1249-step=10000.ckpt")),
    ("30k",  os.path.join(ckpt_dir, "epoch=3749-step=30000.ckpt")),
    ("50k",  os.path.join(ckpt_dir, "epoch=6249-step=50000.ckpt")),
    ("70k",  os.path.join(ckpt_dir, "epoch=8749-step=70000.ckpt")),
    ("100k", os.path.join(ckpt_dir, "epoch=12499-step=100000.ckpt")),
]

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


def load_ema_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_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.clone()
    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


# Load val samples
data_root = "/data2/sichengli/Data/test/Segmentation/Kvasir-SEG/Kvasir-SEG"
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((".jpg", ".png", ".jpeg"))])

random.seed(42)
indices = list(range(len(all_files)))
random.shuffle(indices)
val_indices = indices[int(len(indices) * 0.9):]
val_files = [all_files[i] for i in sorted(val_indices)]

random.seed(456)
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)

# Use same noise for all checkpoints
torch.manual_seed(123)
shared_noise = torch.randn(len(selected), 3, 256, 256, device=device)

# Generate for each checkpoint
generated = {}
for name, ckpt_path in checkpoints:
    print(f"Generating with {name} checkpoint...")
    model = load_ema_model(ckpt_path)
    gen = sample_no_cfg(model, shared_noise, masks_tensor).clamp(-1, 1) * 0.5 + 0.5
    generated[name] = gen.cpu()
    del model
    gc.collect()
    torch.cuda.empty_cache()

# Build visualization grid
col_labels = ["Mask"] + [name for name, _ in checkpoints] + ["Real"]
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()
            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 = generated[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 = os.path.join(ckpt_dir, "val_samples")
os.makedirs(out_dir, exist_ok=True)
out_path = os.path.join(out_dir, "training_progression.png")
Image.fromarray(canvas).save(out_path)
print(f"\nSaved: {out_path} ({canvas_w}x{canvas_h})")