File size: 11,307 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
"""
Batch generation for all medical datasets.
For each dataset, generates images conditioned on ALL masks, saves individually.
Records per-image sampling time.

Usage:
  python scripts/generate_all.py --dataset cvc
  python scripts/generate_all.py --dataset kvasir
  python scripts/generate_all.py --dataset refuge2
  python scripts/generate_all.py --dataset all
"""
import sys
sys.path.insert(0, "/data/sichengli/Code/PixelGen")

import argparse
import os
import gc
import time
import json
import random
import numpy as np
import torch
from PIL import Image
import torchvision.transforms as transforms
import torchvision.transforms.functional as TF
from torch.utils.data import Dataset, DataLoader

from src.models.transformer.JiT_medical import JiTMedical


# ─── Config ───────────────────────────────────────────────────────────
CONFIGS = {
    "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_dir": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_CVC/generated_images",
        "multi_split": False,
        "train_ratio": 0.9,
        "seed": 42,
    },
    "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_dir": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_Kvasir/generated_images",
        "multi_split": False,
        "train_ratio": 0.9,
        "seed": 42,
    },
    "refuge2": {
        "data_root": "/data2/sichengli/Data/test/Segmentation/REFUGE2",
        "splits": ["train", "val", "test"],
        "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_dir": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_REFUGE2/generated_images",
        "multi_split": True,
        "val_ratio": 0.1,
        "seed": 42,
    },
}

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

RESOLUTION = 256
BATCH_SIZE = 16
NUM_STEPS = 50
CFG_SCALE = 2.0


# ─── Dataset ──────────────────────────────────────────────────────────
class MaskDataset(Dataset):
    """Load all masks from a dataset for generation."""
    def __init__(self, cfg):
        self.resolution = RESOLUTION
        self.pairs = []  # (mask_path, save_name)

        if cfg.get("multi_split"):
            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_name = os.path.splitext(img_f)[0]
                    for ext in cfg["mask_ext"]:
                        candidate = os.path.join(mask_dir, base_name + ext)
                        if os.path.exists(candidate):
                            save_name = f"{split}_{base_name}"
                            self.pairs.append((candidate, save_name))
                            break
        else:
            mask_dir = os.path.join(cfg["data_root"], cfg["mask_subdir"])
            all_files = sorted([f for f in os.listdir(mask_dir) if f.endswith(cfg["file_ext"])])
            for f in all_files:
                base_name = os.path.splitext(f)[0]
                self.pairs.append((os.path.join(mask_dir, f), base_name))

        print(f"[MaskDataset] {len(self.pairs)} masks loaded")

    def __len__(self):
        return len(self.pairs)

    def __getitem__(self, idx):
        mask_path, save_name = self.pairs[idx]
        mask = Image.open(mask_path).convert("L")
        mask = TF.resize(mask, (self.resolution, self.resolution),
                        interpolation=transforms.InterpolationMode.NEAREST)
        mask_tensor = TF.to_tensor(mask)
        return mask_tensor, save_name


# ─── Sampling ─────────────────────────────────────────────────────────
def shift_respace_fn(t, shift=1.0):
    return t / (t + (1 - t) * shift)


@torch.no_grad()
def sample_batch_cfg(model, noise, mask, num_steps=50, cfg_scale=2.0, t_eps=0.05):
    """
    Euler ODE sampler with Classifier-Free Guidance.
    - Scheduler: Linear (t goes from 0 to 1)
    - Timeshift: 1.0 (no shift)
    - Prediction: x0-prediction, converted to velocity v = (x0 - x_t) / (1-t)
    - CFG: v = v_uncond + cfg_scale * (v_cond - v_uncond)
    """
    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: concat uncond (mask=0) and cond (mask=real)
        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


def load_model(ckpt_path, device):
    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)
    result = model.load_state_dict(ema_state, strict=False)
    print(f"Loaded EMA ({len(ema_state)} keys), missing: {result.missing_keys}, unexpected: {result.unexpected_keys}")
    model = model.to(device).eval().to(torch.float32)
    return model


# ─── Main ─────────────────────────────────────────────────────────────
def generate(dataset_name):
    cfg = CONFIGS[dataset_name]
    device = torch.device("cuda:0")

    out_dir = cfg["out_dir"]
    os.makedirs(out_dir, exist_ok=True)

    print(f"\n{'='*60}")
    print(f"  Generating: {dataset_name.upper()}")
    print(f"  Sampling: Euler ODE + CFG={CFG_SCALE}, {NUM_STEPS} steps")
    print(f"  Output: {out_dir}")
    print(f"{'='*60}\n")

    # Load dataset
    dataset = MaskDataset(cfg)
    loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=False,
                       num_workers=4, pin_memory=True)

    # Load model
    print("Loading model...")
    model = load_model(cfg["ckpt"], device)

    # Generate
    torch.manual_seed(0)
    timing_records = []
    total_images = 0
    total_time = 0.0

    for batch_idx, (masks, save_names) in enumerate(loader):
        bs = masks.shape[0]
        masks = masks.to(device)
        noise = torch.randn(bs, 3, RESOLUTION, RESOLUTION, device=device)

        # Time the sampling
        torch.cuda.synchronize()
        t_start = time.time()

        gen = sample_batch_cfg(model, noise, masks, NUM_STEPS, CFG_SCALE)

        torch.cuda.synchronize()
        t_end = time.time()

        batch_time = t_end - t_start
        per_image_time = batch_time / bs
        total_time += batch_time
        total_images += bs

        # Clamp and convert to [0, 255]
        gen = gen.clamp(-1, 1) * 0.5 + 0.5  # [-1,1] -> [0,1]

        # Save each image
        for i in range(bs):
            img_np = (gen[i].permute(1, 2, 0).cpu().numpy() * 255).clip(0, 255).astype(np.uint8)
            save_path = os.path.join(out_dir, f"{save_names[i]}.png")
            Image.fromarray(img_np).save(save_path)

            timing_records.append({
                "filename": f"{save_names[i]}.png",
                "time_seconds": per_image_time,
            })

        print(f"  Batch {batch_idx+1}/{len(loader)} | {bs} images | {batch_time:.2f}s ({per_image_time:.3f}s/img)")

    avg_time = total_time / total_images
    print(f"\nGeneration complete: {total_images} images")
    print(f"Total time: {total_time:.2f}s")
    print(f"Average per-image: {avg_time:.4f}s ({1.0/avg_time:.1f} img/s)")

    # Save timing summary
    summary = {
        "dataset": dataset_name,
        "num_images": total_images,
        "sampling_strategy": "Euler ODE (1st-order)",
        "num_steps": NUM_STEPS,
        "cfg_scale": CFG_SCALE,
        "scheduler": "LinearScheduler",
        "timeshift": 1.0,
        "resolution": RESOLUTION,
        "total_time_seconds": round(total_time, 4),
        "avg_time_per_image_seconds": round(avg_time, 4),
        "throughput_img_per_sec": round(1.0 / avg_time, 2),
        "per_image_timing": timing_records,
    }

    summary_path = os.path.join(out_dir, "generation_stats.json")
    with open(summary_path, "w") as f:
        json.dump(summary, f, indent=2)
    print(f"Stats saved: {summary_path}")

    return total_images, avg_time


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--dataset", type=str, required=True,
                       choices=["cvc", "kvasir", "refuge2", "all"])
    args = parser.parse_args()

    datasets = ["cvc", "kvasir", "refuge2"] if args.dataset == "all" else [args.dataset]

    all_results = {}
    for ds in datasets:
        n_imgs, avg_t = generate(ds)
        all_results[ds] = (n_imgs, avg_t)
        gc.collect()
        torch.cuda.empty_cache()

    # Final summary
    print(f"\n{'='*60}")
    print(f"  GENERATION SUMMARY")
    print(f"  Sampling: Euler ODE, {NUM_STEPS} steps, CFG={CFG_SCALE}")
    print(f"{'='*60}")
    print(f"{'Dataset':<15s} | {'Images':>8s} | {'Avg Time':>10s} | {'Throughput':>12s}")
    print("-" * 55)
    for name, (n, t) in all_results.items():
        print(f"{name:<15s} | {n:>8d} | {t:>8.4f}s | {1.0/t:>8.1f} img/s")
    print("=" * 55)