File size: 23,289 Bytes
c2d79c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
#!/usr/bin/env python3
"""
train_conditional_final.py — Robust conditional trainer (drop-in)

Changes made:
- ALWAYS skip loading optimizer state on resume (prints a clear message).
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
- Use the single `device` variable everywhere (no repeated get_device() calls).
- More robust EMA sampling/load logic.
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
- Small defensive logging & comments.
"""

import argparse
import math
import os
import random
import signal
from pathlib import Path
from typing import Dict, Optional

import numpy as np
from PIL import Image, ImageFilter

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader

from tqdm import tqdm

# --------------------------
# Default config (will be overridden by CLI)
# --------------------------
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression/train")
DEFAULT_IMAGE_SIZE = 240
DEFAULT_BATCH_SIZE = 8
DEFAULT_NUM_WORKERS = 2
DEFAULT_TIMESTEPS = 1000
DEFAULT_TOTAL_STEPS = 600000
DEFAULT_LR = 1e-4
DEFAULT_SAVE_EVERY = 2000
DEFAULT_SAMPLE_EVERY = 1000
DEFAULT_EMA_DECAY = 0.9999
DEFAULT_VAL_SAMPLE_STEPS = 1000

# --------------------------
# Helpers: device, atomic save, safe load, remapper
# --------------------------
def get_device():
    # prefer mps if available (mac), else cuda, else cpu
    if getattr(torch.backends, "mps", None) is not None and getattr(torch.backends, "mps", None).is_available() and getattr(torch.backends, "mps", None).is_built():
        return torch.device("mps")
    if torch.cuda.is_available():
        return torch.device("cuda")
    return torch.device("cpu")

def atomic_save(obj, path: Path):
    tmp = path.with_suffix(".tmp")
    torch.save(obj, tmp)
    tmp.replace(path)

def safe_torch_load(path: Path, map_location):
    """
    Robust local load. If it fails, raise with a clear message.
    (Don't attempt unsupported torch.load kwargs.)
    """
    try:
        return torch.load(path, map_location=map_location)
    except Exception as e:
        raise RuntimeError(f"Failed to load checkpoint {path}: {e}")

def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
    """
    Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
    """
    ck_keys = set(checkpoint_sd.keys())
    model_keys = set(model.state_dict().keys())

    has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
    has_ck_res = any(".res." in k for k in ck_keys)
    has_mod_res_conv = any(".res_conv." in k for k in model_keys)
    has_mod_res = any(".res." in k for k in model_keys)

    # checkpoint uses res_conv, model expects res
    if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
        return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}

    # checkpoint uses res, model expects res_conv
    if has_ck_res and has_mod_res_conv and not has_mod_res:
        return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}

    # otherwise return unchanged
    return checkpoint_sd

# --------------------------
# Dataset: returns (x0, cond_blur)
# --------------------------
class ConditionalMRI(Dataset):
    def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 2.0):
        p = Path(list_path)
        if not p.exists():
            raise RuntimeError(f"Train list not found: {p}")
        with open(p, "r") as f:
            lines = [l.strip() for l in f.readlines() if l.strip()]
        if not lines:
            raise RuntimeError(f"No image paths found in {p}")
        self.paths = [Path(x) for x in lines]
        self.image_size = image_size
        self.blur_radius = blur_radius
        print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")

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

    def __getitem__(self, idx):
        p = self.paths[idx]
        img = Image.open(p).convert("L").resize((self.image_size, self.image_size))
        arr = np.array(img, dtype=np.float32) / 255.0
        x0 = arr * 2.0 - 1.0
        blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
        b_arr = np.array(blurred, dtype=np.float32) / 255.0
        b = b_arr * 2.0 - 1.0
        x0_t = torch.from_numpy(x0).unsqueeze(0).float()
        b_t = torch.from_numpy(b).unsqueeze(0).float()
        return x0_t, b_t

# --------------------------
# Model: UNet conditional
# --------------------------
class SinusoidalTimeEmbedding(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.dim = dim
    def forward(self, t):
        device = t.device
        half = self.dim // 2
        emb = math.log(10000) / (half - 1)
        emb = torch.exp(torch.arange(half, device=device) * -emb)
        emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
        return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)

class ResBlock(nn.Module):
    # keep attribute name res_conv to match both variants (remapper handles differences)
    def __init__(self, in_ch, out_ch, time_dim):
        super().__init__()
        self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
        self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
        self.time_mlp = nn.Linear(time_dim, out_ch)
        self.act = nn.SiLU()
        self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
    def forward(self, x, t_emb):
        h = self.act(self.conv1(x))
        h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
        h = self.conv2(h)
        return self.act(h + self.res_conv(x))

class UNetCond(nn.Module):
    def __init__(self, in_ch=2, base=64, time_dim=256):
        super().__init__()
        self.time_mlp = nn.Sequential(
            SinusoidalTimeEmbedding(time_dim),
            nn.Linear(time_dim, time_dim * 2),
            nn.SiLU(),
            nn.Linear(time_dim * 2, time_dim),
        )
        # small condition projection to strengthen conditioning at early layers
        self.cond_proj = nn.Sequential(
            nn.Conv2d(1, base, 3, padding=1),
            nn.SiLU(),
            nn.Conv2d(base, base, 3, padding=1),
        )

        self.down1 = ResBlock(in_ch, base, time_dim)
        self.down2 = ResBlock(base, base * 2, time_dim)
        self.down3 = ResBlock(base * 2, base * 4, time_dim)
        self.pool = nn.AvgPool2d(2)
        self.bot = ResBlock(base * 4, base * 4, time_dim)
        self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
        self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
        self.up1 = ResBlock(base + base, base, time_dim)
        self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
        self.final = nn.Conv2d(base, 1, 1)

    def forward(self, noisy_and_cond, t):
        device = noisy_and_cond.device
        t_emb = self.time_mlp(t)

        noisy = noisy_and_cond[:, :1, ...]
        cond = noisy_and_cond[:, 1:, ...]
        cond_feat = self.cond_proj(cond)

        d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
        try:
            d1 = d1 + cond_feat
        except Exception:
            pass

        d2 = self.down2(self.pool(d1), t_emb)
        d3 = self.down3(self.pool(d2), t_emb)
        b = self.bot(self.pool(d3), t_emb)
        u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
        u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
        u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
        return self.final(u1)

# --------------------------
# Diffusion utils
# --------------------------
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
    return torch.linspace(start, end, timesteps)

class Diffusion(nn.Module):
    def __init__(self, timesteps=1000, device="cpu"):
        super().__init__()
        self.timesteps = timesteps
        betas = make_beta_schedule(timesteps).to(device)
        alphas = 1.0 - betas
        alphas_cumprod = torch.cumprod(alphas, dim=0)
        alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
        self.register_buffer("betas", betas)
        self.register_buffer("alphas", alphas)
        self.register_buffer("alphas_cumprod", alphas_cumprod)
        self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)

    def q_sample(self, x0, t, noise=None):
        if noise is None: noise = torch.randn_like(x0)
        ac = self.alphas_cumprod[t].view(-1,1,1,1)
        return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise

    def p_losses(self, model, x0, cond, t):
        noise = torch.randn_like(x0)
        x_t = self.q_sample(x0, t, noise)
        inp = torch.cat([x_t, cond], dim=1)
        noise_pred = model(inp, t)
        return F.mse_loss(noise_pred, noise)

    @torch.no_grad()
    def p_sample(self, model, x_t, cond, t):
        betas_t = self.betas[t].view(-1,1,1,1)
        alphas_t = (1.0 - betas_t)
        alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
        eps_theta = model(torch.cat([x_t, cond], dim=1), t)
        coef1 = 1.0 / torch.sqrt(alphas_t)
        coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
        mean = coef1 * (x_t - coef2 * eps_theta)
        noise = torch.randn_like(x_t)
        mask = (t > 0).float().view(-1,1,1,1)
        sigma = torch.sqrt(betas_t)
        return mean + mask * sigma * noise

    @torch.no_grad()
    def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
        model.eval()
        if start_t is None: start_t = self.timesteps - 1
        if num_steps is None: num_steps = start_t + 1
        B = cond.shape[0]
        x_t = torch.randn((B,1,cond.shape[2],cond.shape[3]), device=device)
        t_values = list(range(start_t, -1, -1))
        if num_steps < len(t_values):
            idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
            t_values = [t_values[i] for i in idxs]
        for t_scalar in t_values:
            t_batch = torch.tensor([t_scalar]*B, device=device).long()
            x_t = self.p_sample(model, x_t, cond, t_batch)
        return x_t

# --------------------------
# EMA helper
# --------------------------
class EMA:
    def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
        self.decay = decay
        self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}

    def update(self, net: nn.Module):
        for k, v in net.state_dict().items():
            if k in self.shadow:
                self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
            else:
                self.shadow[k] = v.clone().detach()

    def to_state_dict(self):
        return {k: v.clone().cpu() for k, v in self.shadow.items()}

    def load_state_dict(self, sd: Dict[str, torch.Tensor]):
        self.shadow = {k: v.clone().detach() for k, v in sd.items()}

# --------------------------
# Image grid save
# --------------------------
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
    tensor = tensor.detach().cpu()
    arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
    arr = arr.astype(np.uint8)
    B,C,H,W = arr.shape
    ncol = math.ceil(B / nrow)
    grid = Image.new("L", (W * ncol, H * nrow))
    idx = 0
    for r in range(nrow):
        for c in range(ncol):
            if idx >= B: break
            img = Image.fromarray(arr[idx,0])
            grid.paste(img, (c*W, r*H))
            idx += 1
    path.parent.mkdir(parents=True, exist_ok=True)
    grid.save(path)
    print(f"[SAVE] image saved: {path}")

# --------------------------
# Trainer (main)
# --------------------------
def train(
    base_dir: str,
    train_list: Optional[str] = None,
    image_size: int = DEFAULT_IMAGE_SIZE,
    batch_size: int = DEFAULT_BATCH_SIZE,
    num_workers: int = DEFAULT_NUM_WORKERS,
    timesteps: int = DEFAULT_TIMESTEPS,
    total_steps: int = DEFAULT_TOTAL_STEPS,
    lr: float = DEFAULT_LR,
    base_channels: int = 64,
    save_every: int = DEFAULT_SAVE_EVERY,
    sample_every: int = DEFAULT_SAMPLE_EVERY,
    ema_decay: float = DEFAULT_EMA_DECAY,
    val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
    sample_only: Optional[str] = None,
):
    base = Path(base_dir)
    train_list = train_list or (base / "train_list.txt")
    ckpt_dir = base / "checkpoints_cond_blur2"
    samples_dir = base / "samples_cond_blur2"
    progress_dir = base / "progress_cond_blur2"
    ckpt_dir.mkdir(parents=True, exist_ok=True)
    samples_dir.mkdir(parents=True, exist_ok=True)
    progress_dir.mkdir(parents=True, exist_ok=True)

    device = get_device()
    print("Device:", device)

    model = UNetCond(in_ch=2, base=base_channels).to(device)
    diffusion = Diffusion(timesteps=timesteps, device=device).to(device)

    if sample_only:
        ck = safe_torch_load(Path(sample_only), map_location=device)
        sd = ck.get("model", ck) if isinstance(ck, dict) else ck
        sd = remap_checkpoint_to_model(sd, model)
        model.load_state_dict(sd, strict=False)
        model_for_sampling = model
        if isinstance(ck, dict) and "ema" in ck:
            try:
                ema_sd = remap_checkpoint_to_model(ck["ema"], model)
                tmp = UNetCond(in_ch=2, base=base_channels).to(device)
                tmp.load_state_dict(ema_sd, strict=False)
                model_for_sampling = tmp
                print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
            except Exception as e:
                print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
        conds = []
        with open(train_list, "r") as f:
            for i, line in enumerate(f):
                if i >= 4: break
                p = Path(line.strip())
                im = Image.open(p).convert("L").resize((image_size, image_size))
                b = im.filter(ImageFilter.GaussianBlur(radius=2.0))
                arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
                conds.append(torch.from_numpy(arr).unsqueeze(0).unsqueeze(0).float())
        cond_batch = torch.cat(conds, dim=0).to(device)
        with torch.no_grad():
            samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
        out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
        save_grid(samples, out, nrow=2)
        return

    ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=2.0)
    dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)

    opt = torch.optim.AdamW(model.parameters(), lr=lr)
    ema = EMA(model, decay=ema_decay)

    latest = ckpt_dir / "cond_latest.pt"
    start_step = 0
    if latest.exists():
        print("Resuming from", latest)
        data = safe_torch_load(latest, map_location=device)
        raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
        raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
        try:
            model.load_state_dict(raw_model_sd)
            print("[LOAD] model loaded (strict=True).")
        except Exception as e:
            print("[LOAD] strict load failed:", e)
            model.load_state_dict(raw_model_sd, strict=False)
            print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")

        if isinstance(data, dict) and "optimizer" in data:
            print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")

        if isinstance(data, dict) and "ema" in data:
            try:
                ema_sd = remap_checkpoint_to_model(data["ema"], model)
                model_keys = set(model.state_dict().keys())
                ema_keys = set(ema_sd.keys())
                if ema_keys == model_keys:
                    ema.load_state_dict(ema_sd)
                    print("[LOAD] EMA loaded from checkpoint.")
                else:
                    print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
                    ema = EMA(model, decay=ema_decay)
                    for g in opt.param_groups:
                        g["lr"] = min(g.get("lr", lr), 5e-05)
                    print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
            except Exception as e:
                print("[WARN] Failed to load EMA from checkpoint:", e)
                ema = EMA(model, decay=ema_decay)
        else:
            print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
            ema = EMA(model, decay=ema_decay)
            for g in opt.param_groups:
                g["lr"] = min(g.get("lr", lr), 5e-05)
            print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])

        start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
        print("Resumed at step:", start_step)

    stop = {"flag": False}
    def handler(sig, frame):
        print("\nSignal received: will save checkpoint and exit after current batch.")
        stop["flag"] = True
    signal.signal(signal.SIGINT, handler)
    signal.signal(signal.SIGTERM, handler)

    model.train()
    pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
    step = start_step
    ema_loss = None

    try:
        while step < total_steps:
            for x0, cond in dl:
                if stop["flag"]:
                    break
                x0 = x0.to(device); cond = cond.to(device)
                bsz = x0.shape[0]
                t = torch.randint(0, timesteps, (bsz,), device=device).long()
                loss = diffusion.p_losses(model, x0, cond, t)

                opt.zero_grad()
                loss.backward()
                torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
                opt.step()
                ema.update(model)

                step += 1
                val = float(loss.item())
                ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val

                if step % 50 == 0:
                    print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")

                pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
                pbar.update(1)

                if step % sample_every == 0 or step == 1:
                    with torch.no_grad():
                        try:
                            sample_model = UNetCond(in_ch=2, base=base_channels).to(device)
                            try:
                                ema_sd = ema.to_state_dict()
                                ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
                                sample_model.load_state_dict(ema_sd, strict=False)
                                print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
                            except Exception:
                                try:
                                    sample_model.load_state_dict(ema.shadow, strict=False)
                                    print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
                                except Exception as e:
                                    print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
                                    sample_model = model
                        except Exception as e:
                            print("[SAMPLE] Failed to build EMA sample model:", e)
                            sample_model = model

                        cond_batch = cond[:4].to(device)
                        samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
                        s_path = samples_dir / f"samples_cond_{step}.png"
                        p_path = progress_dir / f"progress_cond_{step}.png"
                        save_grid(samples, s_path, nrow=2)
                        save_grid(samples, p_path, nrow=2)
                        print(f"[SAMPLE] Saved sample: {s_path}")
                        print(f"[SAMPLE] Saved progress: {p_path}")

                if step % save_every == 0 or stop["flag"] or step >= total_steps:
                    ck = {
                        "model": model.state_dict(),
                        "optimizer": opt.state_dict(),
                        "ema": ema.to_state_dict(),
                        "step": step,
                    }
                    p1 = ckpt_dir / f"cond_step_{step}.pt"
                    p2 = ckpt_dir / "cond_latest.pt"
                    atomic_save(ck, p1)
                    atomic_save(ck, p2)
                    print(f"[CKPT] Saved checkpoint: {p1}")
                    print(f"[CKPT] Updated latest checkpoint: {p2}")

                if step >= total_steps:
                    break
            if stop["flag"]:
                break
    finally:
        pbar.close()
        ck = {
            "model": model.state_dict(),
            "optimizer": opt.state_dict(),
            "ema": ema.to_state_dict(),
            "step": step,
        }
        atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
        atomic_save(ck, ckpt_dir / "cond_latest.pt")
        print("[FINAL] Final checkpoint saved.")
        print("Exiting.")

# --------------------------
# CLI
# --------------------------
def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
    p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
    p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
    p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
    p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
    p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
    p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
    p.add_argument("--lr", type=float, default=DEFAULT_LR)
    p.add_argument("--base_channels", type=int, default=64)
    p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
    p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
    p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
    p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
    p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
    return p.parse_args()

if __name__ == "__main__":
    args = parse_args()
    train(
        base_dir=args.base_dir,
        train_list=args.train_list,
        image_size=args.image_size,
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        timesteps=args.timesteps,
        total_steps=args.total_steps,
        lr=args.lr,
        base_channels=args.base_channels,
        save_every=args.save_every,
        sample_every=args.sample_every,
        ema_decay=args.ema_decay,
        val_sample_steps=args.val_sample_steps,
        sample_only=args.sample_only,
    )