add training scripts
Browse files- training_scripts/.DS_Store +0 -0
- training_scripts/train_blur_brats_1.py +562 -0
- training_scripts/train_blur_brats_2.py +562 -0
- training_scripts/train_blur_brats_3.py +562 -0
- training_scripts/train_blur_brats_half.py +562 -0
- training_scripts/train_buildings_blur0.5.py +568 -0
- training_scripts/train_buildings_blur1.py +568 -0
- training_scripts/train_buildings_blur2.py +568 -0
- training_scripts/train_buildings_blur3.py +568 -0
- training_scripts/train_celebA_blur1.py +568 -0
- training_scripts/train_celebA_blur2.py +568 -0
- training_scripts/train_celebA_blur3.py +568 -0
- training_scripts/train_celebA_blur_half.py +568 -0
training_scripts/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
training_scripts/train_blur_brats_1.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_conditional_final.py — Robust conditional trainer (drop-in)
|
| 4 |
+
|
| 5 |
+
Changes made:
|
| 6 |
+
- ALWAYS skip loading optimizer state on resume (prints a clear message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression/train")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 240
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 1e-4
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 1.0):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("L").resize((self.image_size, self.image_size))
|
| 119 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 120 |
+
x0 = arr * 2.0 - 1.0
|
| 121 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 122 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 123 |
+
b = b_arr * 2.0 - 1.0
|
| 124 |
+
x0_t = torch.from_numpy(x0).unsqueeze(0).float()
|
| 125 |
+
b_t = torch.from_numpy(b).unsqueeze(0).float()
|
| 126 |
+
return x0_t, b_t
|
| 127 |
+
|
| 128 |
+
# --------------------------
|
| 129 |
+
# Model: UNet conditional
|
| 130 |
+
# --------------------------
|
| 131 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 132 |
+
def __init__(self, dim):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.dim = dim
|
| 135 |
+
def forward(self, t):
|
| 136 |
+
device = t.device
|
| 137 |
+
half = self.dim // 2
|
| 138 |
+
emb = math.log(10000) / (half - 1)
|
| 139 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 140 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 141 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 142 |
+
|
| 143 |
+
class ResBlock(nn.Module):
|
| 144 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 145 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 146 |
+
super().__init__()
|
| 147 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 148 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 149 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 150 |
+
self.act = nn.SiLU()
|
| 151 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 152 |
+
def forward(self, x, t_emb):
|
| 153 |
+
h = self.act(self.conv1(x))
|
| 154 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 155 |
+
h = self.conv2(h)
|
| 156 |
+
return self.act(h + self.res_conv(x))
|
| 157 |
+
|
| 158 |
+
class UNetCond(nn.Module):
|
| 159 |
+
def __init__(self, in_ch=2, base=64, time_dim=256):
|
| 160 |
+
super().__init__()
|
| 161 |
+
self.time_mlp = nn.Sequential(
|
| 162 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 163 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 164 |
+
nn.SiLU(),
|
| 165 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 166 |
+
)
|
| 167 |
+
# small condition projection to strengthen conditioning at early layers
|
| 168 |
+
self.cond_proj = nn.Sequential(
|
| 169 |
+
nn.Conv2d(1, base, 3, padding=1),
|
| 170 |
+
nn.SiLU(),
|
| 171 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 175 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 176 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 177 |
+
self.pool = nn.AvgPool2d(2)
|
| 178 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 179 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 180 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 181 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 182 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 183 |
+
self.final = nn.Conv2d(base, 1, 1)
|
| 184 |
+
|
| 185 |
+
def forward(self, noisy_and_cond, t):
|
| 186 |
+
device = noisy_and_cond.device
|
| 187 |
+
t_emb = self.time_mlp(t)
|
| 188 |
+
|
| 189 |
+
noisy = noisy_and_cond[:, :1, ...]
|
| 190 |
+
cond = noisy_and_cond[:, 1:, ...]
|
| 191 |
+
cond_feat = self.cond_proj(cond)
|
| 192 |
+
|
| 193 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 194 |
+
try:
|
| 195 |
+
d1 = d1 + cond_feat
|
| 196 |
+
except Exception:
|
| 197 |
+
pass
|
| 198 |
+
|
| 199 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 200 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 201 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 202 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 203 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 204 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 205 |
+
return self.final(u1)
|
| 206 |
+
|
| 207 |
+
# --------------------------
|
| 208 |
+
# Diffusion utils
|
| 209 |
+
# --------------------------
|
| 210 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 211 |
+
return torch.linspace(start, end, timesteps)
|
| 212 |
+
|
| 213 |
+
class Diffusion(nn.Module):
|
| 214 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 215 |
+
super().__init__()
|
| 216 |
+
self.timesteps = timesteps
|
| 217 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 218 |
+
alphas = 1.0 - betas
|
| 219 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 220 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 221 |
+
self.register_buffer("betas", betas)
|
| 222 |
+
self.register_buffer("alphas", alphas)
|
| 223 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 224 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 225 |
+
|
| 226 |
+
def q_sample(self, x0, t, noise=None):
|
| 227 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 228 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 229 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 230 |
+
|
| 231 |
+
def p_losses(self, model, x0, cond, t):
|
| 232 |
+
noise = torch.randn_like(x0)
|
| 233 |
+
x_t = self.q_sample(x0, t, noise)
|
| 234 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 235 |
+
noise_pred = model(inp, t)
|
| 236 |
+
return F.mse_loss(noise_pred, noise)
|
| 237 |
+
|
| 238 |
+
@torch.no_grad()
|
| 239 |
+
def p_sample(self, model, x_t, cond, t):
|
| 240 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 241 |
+
alphas_t = (1.0 - betas_t)
|
| 242 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 243 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 244 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 245 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 246 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 247 |
+
noise = torch.randn_like(x_t)
|
| 248 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 249 |
+
sigma = torch.sqrt(betas_t)
|
| 250 |
+
return mean + mask * sigma * noise
|
| 251 |
+
|
| 252 |
+
@torch.no_grad()
|
| 253 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 254 |
+
model.eval()
|
| 255 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 256 |
+
if num_steps is None: num_steps = start_t + 1
|
| 257 |
+
B = cond.shape[0]
|
| 258 |
+
x_t = torch.randn((B,1,cond.shape[2],cond.shape[3]), device=device)
|
| 259 |
+
t_values = list(range(start_t, -1, -1))
|
| 260 |
+
if num_steps < len(t_values):
|
| 261 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 262 |
+
t_values = [t_values[i] for i in idxs]
|
| 263 |
+
for t_scalar in t_values:
|
| 264 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 265 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 266 |
+
return x_t
|
| 267 |
+
|
| 268 |
+
# --------------------------
|
| 269 |
+
# EMA helper
|
| 270 |
+
# --------------------------
|
| 271 |
+
class EMA:
|
| 272 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 273 |
+
self.decay = decay
|
| 274 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 275 |
+
|
| 276 |
+
def update(self, net: nn.Module):
|
| 277 |
+
for k, v in net.state_dict().items():
|
| 278 |
+
if k in self.shadow:
|
| 279 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 280 |
+
else:
|
| 281 |
+
self.shadow[k] = v.clone().detach()
|
| 282 |
+
|
| 283 |
+
def to_state_dict(self):
|
| 284 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 285 |
+
|
| 286 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 287 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 288 |
+
|
| 289 |
+
# --------------------------
|
| 290 |
+
# Image grid save
|
| 291 |
+
# --------------------------
|
| 292 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 293 |
+
tensor = tensor.detach().cpu()
|
| 294 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 295 |
+
arr = arr.astype(np.uint8)
|
| 296 |
+
B,C,H,W = arr.shape
|
| 297 |
+
ncol = math.ceil(B / nrow)
|
| 298 |
+
grid = Image.new("L", (W * ncol, H * nrow))
|
| 299 |
+
idx = 0
|
| 300 |
+
for r in range(nrow):
|
| 301 |
+
for c in range(ncol):
|
| 302 |
+
if idx >= B: break
|
| 303 |
+
img = Image.fromarray(arr[idx,0])
|
| 304 |
+
grid.paste(img, (c*W, r*H))
|
| 305 |
+
idx += 1
|
| 306 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 307 |
+
grid.save(path)
|
| 308 |
+
print(f"[SAVE] image saved: {path}")
|
| 309 |
+
|
| 310 |
+
# --------------------------
|
| 311 |
+
# Trainer (main)
|
| 312 |
+
# --------------------------
|
| 313 |
+
def train(
|
| 314 |
+
base_dir: str,
|
| 315 |
+
train_list: Optional[str] = None,
|
| 316 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 317 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 318 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 319 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 320 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 321 |
+
lr: float = DEFAULT_LR,
|
| 322 |
+
base_channels: int = 64,
|
| 323 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 324 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 325 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 326 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 327 |
+
sample_only: Optional[str] = None,
|
| 328 |
+
):
|
| 329 |
+
base = Path(base_dir)
|
| 330 |
+
train_list = train_list or (base / "train_list.txt")
|
| 331 |
+
ckpt_dir = base / "checkpoints_cond_blur1"
|
| 332 |
+
samples_dir = base / "samples_cond_blur1"
|
| 333 |
+
progress_dir = base / "progress_cond_blur1"
|
| 334 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 335 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 336 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 337 |
+
|
| 338 |
+
device = get_device()
|
| 339 |
+
print("Device:", device)
|
| 340 |
+
|
| 341 |
+
model = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 342 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 343 |
+
|
| 344 |
+
if sample_only:
|
| 345 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 346 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 347 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 348 |
+
model.load_state_dict(sd, strict=False)
|
| 349 |
+
model_for_sampling = model
|
| 350 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 351 |
+
try:
|
| 352 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 353 |
+
tmp = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 354 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 355 |
+
model_for_sampling = tmp
|
| 356 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 357 |
+
except Exception as e:
|
| 358 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 359 |
+
conds = []
|
| 360 |
+
with open(train_list, "r") as f:
|
| 361 |
+
for i, line in enumerate(f):
|
| 362 |
+
if i >= 4: break
|
| 363 |
+
p = Path(line.strip())
|
| 364 |
+
im = Image.open(p).convert("L").resize((image_size, image_size))
|
| 365 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=1.0))
|
| 366 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 367 |
+
conds.append(torch.from_numpy(arr).unsqueeze(0).unsqueeze(0).float())
|
| 368 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 369 |
+
with torch.no_grad():
|
| 370 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 371 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 372 |
+
save_grid(samples, out, nrow=2)
|
| 373 |
+
return
|
| 374 |
+
|
| 375 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=1.0)
|
| 376 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 377 |
+
|
| 378 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 379 |
+
ema = EMA(model, decay=ema_decay)
|
| 380 |
+
|
| 381 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 382 |
+
start_step = 0
|
| 383 |
+
if latest.exists():
|
| 384 |
+
print("Resuming from", latest)
|
| 385 |
+
data = safe_torch_load(latest, map_location=device)
|
| 386 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 387 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 388 |
+
try:
|
| 389 |
+
model.load_state_dict(raw_model_sd)
|
| 390 |
+
print("[LOAD] model loaded (strict=True).")
|
| 391 |
+
except Exception as e:
|
| 392 |
+
print("[LOAD] strict load failed:", e)
|
| 393 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 394 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 395 |
+
|
| 396 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 397 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 398 |
+
|
| 399 |
+
if isinstance(data, dict) and "ema" in data:
|
| 400 |
+
try:
|
| 401 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 402 |
+
model_keys = set(model.state_dict().keys())
|
| 403 |
+
ema_keys = set(ema_sd.keys())
|
| 404 |
+
if ema_keys == model_keys:
|
| 405 |
+
ema.load_state_dict(ema_sd)
|
| 406 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 407 |
+
else:
|
| 408 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 409 |
+
ema = EMA(model, decay=ema_decay)
|
| 410 |
+
for g in opt.param_groups:
|
| 411 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 412 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 413 |
+
except Exception as e:
|
| 414 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
else:
|
| 417 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 418 |
+
ema = EMA(model, decay=ema_decay)
|
| 419 |
+
for g in opt.param_groups:
|
| 420 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 421 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 422 |
+
|
| 423 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 424 |
+
print("Resumed at step:", start_step)
|
| 425 |
+
|
| 426 |
+
stop = {"flag": False}
|
| 427 |
+
def handler(sig, frame):
|
| 428 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 429 |
+
stop["flag"] = True
|
| 430 |
+
signal.signal(signal.SIGINT, handler)
|
| 431 |
+
signal.signal(signal.SIGTERM, handler)
|
| 432 |
+
|
| 433 |
+
model.train()
|
| 434 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 435 |
+
step = start_step
|
| 436 |
+
ema_loss = None
|
| 437 |
+
|
| 438 |
+
try:
|
| 439 |
+
while step < total_steps:
|
| 440 |
+
for x0, cond in dl:
|
| 441 |
+
if stop["flag"]:
|
| 442 |
+
break
|
| 443 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 444 |
+
bsz = x0.shape[0]
|
| 445 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 446 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 447 |
+
|
| 448 |
+
opt.zero_grad()
|
| 449 |
+
loss.backward()
|
| 450 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 451 |
+
opt.step()
|
| 452 |
+
ema.update(model)
|
| 453 |
+
|
| 454 |
+
step += 1
|
| 455 |
+
val = float(loss.item())
|
| 456 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 457 |
+
|
| 458 |
+
if step % 50 == 0:
|
| 459 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 460 |
+
|
| 461 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 462 |
+
pbar.update(1)
|
| 463 |
+
|
| 464 |
+
if step % sample_every == 0 or step == 1:
|
| 465 |
+
with torch.no_grad():
|
| 466 |
+
try:
|
| 467 |
+
sample_model = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 468 |
+
try:
|
| 469 |
+
ema_sd = ema.to_state_dict()
|
| 470 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 471 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 472 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 473 |
+
except Exception:
|
| 474 |
+
try:
|
| 475 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 476 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 477 |
+
except Exception as e:
|
| 478 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 479 |
+
sample_model = model
|
| 480 |
+
except Exception as e:
|
| 481 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 482 |
+
sample_model = model
|
| 483 |
+
|
| 484 |
+
cond_batch = cond[:4].to(device)
|
| 485 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 486 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 487 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 488 |
+
save_grid(samples, s_path, nrow=2)
|
| 489 |
+
save_grid(samples, p_path, nrow=2)
|
| 490 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 491 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 492 |
+
|
| 493 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 494 |
+
ck = {
|
| 495 |
+
"model": model.state_dict(),
|
| 496 |
+
"optimizer": opt.state_dict(),
|
| 497 |
+
"ema": ema.to_state_dict(),
|
| 498 |
+
"step": step,
|
| 499 |
+
}
|
| 500 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 501 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 502 |
+
atomic_save(ck, p1)
|
| 503 |
+
atomic_save(ck, p2)
|
| 504 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 505 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 506 |
+
|
| 507 |
+
if step >= total_steps:
|
| 508 |
+
break
|
| 509 |
+
if stop["flag"]:
|
| 510 |
+
break
|
| 511 |
+
finally:
|
| 512 |
+
pbar.close()
|
| 513 |
+
ck = {
|
| 514 |
+
"model": model.state_dict(),
|
| 515 |
+
"optimizer": opt.state_dict(),
|
| 516 |
+
"ema": ema.to_state_dict(),
|
| 517 |
+
"step": step,
|
| 518 |
+
}
|
| 519 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 520 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 521 |
+
print("[FINAL] Final checkpoint saved.")
|
| 522 |
+
print("Exiting.")
|
| 523 |
+
|
| 524 |
+
# --------------------------
|
| 525 |
+
# CLI
|
| 526 |
+
# --------------------------
|
| 527 |
+
def parse_args():
|
| 528 |
+
p = argparse.ArgumentParser()
|
| 529 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 530 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 531 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 532 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 533 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 534 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 535 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 536 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 537 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 538 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 539 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 540 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 541 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 542 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 543 |
+
return p.parse_args()
|
| 544 |
+
|
| 545 |
+
if __name__ == "__main__":
|
| 546 |
+
args = parse_args()
|
| 547 |
+
train(
|
| 548 |
+
base_dir=args.base_dir,
|
| 549 |
+
train_list=args.train_list,
|
| 550 |
+
image_size=args.image_size,
|
| 551 |
+
batch_size=args.batch_size,
|
| 552 |
+
num_workers=args.num_workers,
|
| 553 |
+
timesteps=args.timesteps,
|
| 554 |
+
total_steps=args.total_steps,
|
| 555 |
+
lr=args.lr,
|
| 556 |
+
base_channels=args.base_channels,
|
| 557 |
+
save_every=args.save_every,
|
| 558 |
+
sample_every=args.sample_every,
|
| 559 |
+
ema_decay=args.ema_decay,
|
| 560 |
+
val_sample_steps=args.val_sample_steps,
|
| 561 |
+
sample_only=args.sample_only,
|
| 562 |
+
)
|
training_scripts/train_blur_brats_2.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_conditional_final.py — Robust conditional trainer (drop-in)
|
| 4 |
+
|
| 5 |
+
Changes made:
|
| 6 |
+
- ALWAYS skip loading optimizer state on resume (prints a clear message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression/train")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 240
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 1e-4
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 2.0):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("L").resize((self.image_size, self.image_size))
|
| 119 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 120 |
+
x0 = arr * 2.0 - 1.0
|
| 121 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 122 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 123 |
+
b = b_arr * 2.0 - 1.0
|
| 124 |
+
x0_t = torch.from_numpy(x0).unsqueeze(0).float()
|
| 125 |
+
b_t = torch.from_numpy(b).unsqueeze(0).float()
|
| 126 |
+
return x0_t, b_t
|
| 127 |
+
|
| 128 |
+
# --------------------------
|
| 129 |
+
# Model: UNet conditional
|
| 130 |
+
# --------------------------
|
| 131 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 132 |
+
def __init__(self, dim):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.dim = dim
|
| 135 |
+
def forward(self, t):
|
| 136 |
+
device = t.device
|
| 137 |
+
half = self.dim // 2
|
| 138 |
+
emb = math.log(10000) / (half - 1)
|
| 139 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 140 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 141 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 142 |
+
|
| 143 |
+
class ResBlock(nn.Module):
|
| 144 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 145 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 146 |
+
super().__init__()
|
| 147 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 148 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 149 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 150 |
+
self.act = nn.SiLU()
|
| 151 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 152 |
+
def forward(self, x, t_emb):
|
| 153 |
+
h = self.act(self.conv1(x))
|
| 154 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 155 |
+
h = self.conv2(h)
|
| 156 |
+
return self.act(h + self.res_conv(x))
|
| 157 |
+
|
| 158 |
+
class UNetCond(nn.Module):
|
| 159 |
+
def __init__(self, in_ch=2, base=64, time_dim=256):
|
| 160 |
+
super().__init__()
|
| 161 |
+
self.time_mlp = nn.Sequential(
|
| 162 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 163 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 164 |
+
nn.SiLU(),
|
| 165 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 166 |
+
)
|
| 167 |
+
# small condition projection to strengthen conditioning at early layers
|
| 168 |
+
self.cond_proj = nn.Sequential(
|
| 169 |
+
nn.Conv2d(1, base, 3, padding=1),
|
| 170 |
+
nn.SiLU(),
|
| 171 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 175 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 176 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 177 |
+
self.pool = nn.AvgPool2d(2)
|
| 178 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 179 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 180 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 181 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 182 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 183 |
+
self.final = nn.Conv2d(base, 1, 1)
|
| 184 |
+
|
| 185 |
+
def forward(self, noisy_and_cond, t):
|
| 186 |
+
device = noisy_and_cond.device
|
| 187 |
+
t_emb = self.time_mlp(t)
|
| 188 |
+
|
| 189 |
+
noisy = noisy_and_cond[:, :1, ...]
|
| 190 |
+
cond = noisy_and_cond[:, 1:, ...]
|
| 191 |
+
cond_feat = self.cond_proj(cond)
|
| 192 |
+
|
| 193 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 194 |
+
try:
|
| 195 |
+
d1 = d1 + cond_feat
|
| 196 |
+
except Exception:
|
| 197 |
+
pass
|
| 198 |
+
|
| 199 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 200 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 201 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 202 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 203 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 204 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 205 |
+
return self.final(u1)
|
| 206 |
+
|
| 207 |
+
# --------------------------
|
| 208 |
+
# Diffusion utils
|
| 209 |
+
# --------------------------
|
| 210 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 211 |
+
return torch.linspace(start, end, timesteps)
|
| 212 |
+
|
| 213 |
+
class Diffusion(nn.Module):
|
| 214 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 215 |
+
super().__init__()
|
| 216 |
+
self.timesteps = timesteps
|
| 217 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 218 |
+
alphas = 1.0 - betas
|
| 219 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 220 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 221 |
+
self.register_buffer("betas", betas)
|
| 222 |
+
self.register_buffer("alphas", alphas)
|
| 223 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 224 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 225 |
+
|
| 226 |
+
def q_sample(self, x0, t, noise=None):
|
| 227 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 228 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 229 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 230 |
+
|
| 231 |
+
def p_losses(self, model, x0, cond, t):
|
| 232 |
+
noise = torch.randn_like(x0)
|
| 233 |
+
x_t = self.q_sample(x0, t, noise)
|
| 234 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 235 |
+
noise_pred = model(inp, t)
|
| 236 |
+
return F.mse_loss(noise_pred, noise)
|
| 237 |
+
|
| 238 |
+
@torch.no_grad()
|
| 239 |
+
def p_sample(self, model, x_t, cond, t):
|
| 240 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 241 |
+
alphas_t = (1.0 - betas_t)
|
| 242 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 243 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 244 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 245 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 246 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 247 |
+
noise = torch.randn_like(x_t)
|
| 248 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 249 |
+
sigma = torch.sqrt(betas_t)
|
| 250 |
+
return mean + mask * sigma * noise
|
| 251 |
+
|
| 252 |
+
@torch.no_grad()
|
| 253 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 254 |
+
model.eval()
|
| 255 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 256 |
+
if num_steps is None: num_steps = start_t + 1
|
| 257 |
+
B = cond.shape[0]
|
| 258 |
+
x_t = torch.randn((B,1,cond.shape[2],cond.shape[3]), device=device)
|
| 259 |
+
t_values = list(range(start_t, -1, -1))
|
| 260 |
+
if num_steps < len(t_values):
|
| 261 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 262 |
+
t_values = [t_values[i] for i in idxs]
|
| 263 |
+
for t_scalar in t_values:
|
| 264 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 265 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 266 |
+
return x_t
|
| 267 |
+
|
| 268 |
+
# --------------------------
|
| 269 |
+
# EMA helper
|
| 270 |
+
# --------------------------
|
| 271 |
+
class EMA:
|
| 272 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 273 |
+
self.decay = decay
|
| 274 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 275 |
+
|
| 276 |
+
def update(self, net: nn.Module):
|
| 277 |
+
for k, v in net.state_dict().items():
|
| 278 |
+
if k in self.shadow:
|
| 279 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 280 |
+
else:
|
| 281 |
+
self.shadow[k] = v.clone().detach()
|
| 282 |
+
|
| 283 |
+
def to_state_dict(self):
|
| 284 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 285 |
+
|
| 286 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 287 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 288 |
+
|
| 289 |
+
# --------------------------
|
| 290 |
+
# Image grid save
|
| 291 |
+
# --------------------------
|
| 292 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 293 |
+
tensor = tensor.detach().cpu()
|
| 294 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 295 |
+
arr = arr.astype(np.uint8)
|
| 296 |
+
B,C,H,W = arr.shape
|
| 297 |
+
ncol = math.ceil(B / nrow)
|
| 298 |
+
grid = Image.new("L", (W * ncol, H * nrow))
|
| 299 |
+
idx = 0
|
| 300 |
+
for r in range(nrow):
|
| 301 |
+
for c in range(ncol):
|
| 302 |
+
if idx >= B: break
|
| 303 |
+
img = Image.fromarray(arr[idx,0])
|
| 304 |
+
grid.paste(img, (c*W, r*H))
|
| 305 |
+
idx += 1
|
| 306 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 307 |
+
grid.save(path)
|
| 308 |
+
print(f"[SAVE] image saved: {path}")
|
| 309 |
+
|
| 310 |
+
# --------------------------
|
| 311 |
+
# Trainer (main)
|
| 312 |
+
# --------------------------
|
| 313 |
+
def train(
|
| 314 |
+
base_dir: str,
|
| 315 |
+
train_list: Optional[str] = None,
|
| 316 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 317 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 318 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 319 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 320 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 321 |
+
lr: float = DEFAULT_LR,
|
| 322 |
+
base_channels: int = 64,
|
| 323 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 324 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 325 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 326 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 327 |
+
sample_only: Optional[str] = None,
|
| 328 |
+
):
|
| 329 |
+
base = Path(base_dir)
|
| 330 |
+
train_list = train_list or (base / "train_list.txt")
|
| 331 |
+
ckpt_dir = base / "checkpoints_cond_blur2"
|
| 332 |
+
samples_dir = base / "samples_cond_blur2"
|
| 333 |
+
progress_dir = base / "progress_cond_blur2"
|
| 334 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 335 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 336 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 337 |
+
|
| 338 |
+
device = get_device()
|
| 339 |
+
print("Device:", device)
|
| 340 |
+
|
| 341 |
+
model = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 342 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 343 |
+
|
| 344 |
+
if sample_only:
|
| 345 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 346 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 347 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 348 |
+
model.load_state_dict(sd, strict=False)
|
| 349 |
+
model_for_sampling = model
|
| 350 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 351 |
+
try:
|
| 352 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 353 |
+
tmp = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 354 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 355 |
+
model_for_sampling = tmp
|
| 356 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 357 |
+
except Exception as e:
|
| 358 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 359 |
+
conds = []
|
| 360 |
+
with open(train_list, "r") as f:
|
| 361 |
+
for i, line in enumerate(f):
|
| 362 |
+
if i >= 4: break
|
| 363 |
+
p = Path(line.strip())
|
| 364 |
+
im = Image.open(p).convert("L").resize((image_size, image_size))
|
| 365 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=2.0))
|
| 366 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 367 |
+
conds.append(torch.from_numpy(arr).unsqueeze(0).unsqueeze(0).float())
|
| 368 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 369 |
+
with torch.no_grad():
|
| 370 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 371 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 372 |
+
save_grid(samples, out, nrow=2)
|
| 373 |
+
return
|
| 374 |
+
|
| 375 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=2.0)
|
| 376 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 377 |
+
|
| 378 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 379 |
+
ema = EMA(model, decay=ema_decay)
|
| 380 |
+
|
| 381 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 382 |
+
start_step = 0
|
| 383 |
+
if latest.exists():
|
| 384 |
+
print("Resuming from", latest)
|
| 385 |
+
data = safe_torch_load(latest, map_location=device)
|
| 386 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 387 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 388 |
+
try:
|
| 389 |
+
model.load_state_dict(raw_model_sd)
|
| 390 |
+
print("[LOAD] model loaded (strict=True).")
|
| 391 |
+
except Exception as e:
|
| 392 |
+
print("[LOAD] strict load failed:", e)
|
| 393 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 394 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 395 |
+
|
| 396 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 397 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 398 |
+
|
| 399 |
+
if isinstance(data, dict) and "ema" in data:
|
| 400 |
+
try:
|
| 401 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 402 |
+
model_keys = set(model.state_dict().keys())
|
| 403 |
+
ema_keys = set(ema_sd.keys())
|
| 404 |
+
if ema_keys == model_keys:
|
| 405 |
+
ema.load_state_dict(ema_sd)
|
| 406 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 407 |
+
else:
|
| 408 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 409 |
+
ema = EMA(model, decay=ema_decay)
|
| 410 |
+
for g in opt.param_groups:
|
| 411 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 412 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 413 |
+
except Exception as e:
|
| 414 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
else:
|
| 417 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 418 |
+
ema = EMA(model, decay=ema_decay)
|
| 419 |
+
for g in opt.param_groups:
|
| 420 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 421 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 422 |
+
|
| 423 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 424 |
+
print("Resumed at step:", start_step)
|
| 425 |
+
|
| 426 |
+
stop = {"flag": False}
|
| 427 |
+
def handler(sig, frame):
|
| 428 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 429 |
+
stop["flag"] = True
|
| 430 |
+
signal.signal(signal.SIGINT, handler)
|
| 431 |
+
signal.signal(signal.SIGTERM, handler)
|
| 432 |
+
|
| 433 |
+
model.train()
|
| 434 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 435 |
+
step = start_step
|
| 436 |
+
ema_loss = None
|
| 437 |
+
|
| 438 |
+
try:
|
| 439 |
+
while step < total_steps:
|
| 440 |
+
for x0, cond in dl:
|
| 441 |
+
if stop["flag"]:
|
| 442 |
+
break
|
| 443 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 444 |
+
bsz = x0.shape[0]
|
| 445 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 446 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 447 |
+
|
| 448 |
+
opt.zero_grad()
|
| 449 |
+
loss.backward()
|
| 450 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 451 |
+
opt.step()
|
| 452 |
+
ema.update(model)
|
| 453 |
+
|
| 454 |
+
step += 1
|
| 455 |
+
val = float(loss.item())
|
| 456 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 457 |
+
|
| 458 |
+
if step % 50 == 0:
|
| 459 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 460 |
+
|
| 461 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 462 |
+
pbar.update(1)
|
| 463 |
+
|
| 464 |
+
if step % sample_every == 0 or step == 1:
|
| 465 |
+
with torch.no_grad():
|
| 466 |
+
try:
|
| 467 |
+
sample_model = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 468 |
+
try:
|
| 469 |
+
ema_sd = ema.to_state_dict()
|
| 470 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 471 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 472 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 473 |
+
except Exception:
|
| 474 |
+
try:
|
| 475 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 476 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 477 |
+
except Exception as e:
|
| 478 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 479 |
+
sample_model = model
|
| 480 |
+
except Exception as e:
|
| 481 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 482 |
+
sample_model = model
|
| 483 |
+
|
| 484 |
+
cond_batch = cond[:4].to(device)
|
| 485 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 486 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 487 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 488 |
+
save_grid(samples, s_path, nrow=2)
|
| 489 |
+
save_grid(samples, p_path, nrow=2)
|
| 490 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 491 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 492 |
+
|
| 493 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 494 |
+
ck = {
|
| 495 |
+
"model": model.state_dict(),
|
| 496 |
+
"optimizer": opt.state_dict(),
|
| 497 |
+
"ema": ema.to_state_dict(),
|
| 498 |
+
"step": step,
|
| 499 |
+
}
|
| 500 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 501 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 502 |
+
atomic_save(ck, p1)
|
| 503 |
+
atomic_save(ck, p2)
|
| 504 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 505 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 506 |
+
|
| 507 |
+
if step >= total_steps:
|
| 508 |
+
break
|
| 509 |
+
if stop["flag"]:
|
| 510 |
+
break
|
| 511 |
+
finally:
|
| 512 |
+
pbar.close()
|
| 513 |
+
ck = {
|
| 514 |
+
"model": model.state_dict(),
|
| 515 |
+
"optimizer": opt.state_dict(),
|
| 516 |
+
"ema": ema.to_state_dict(),
|
| 517 |
+
"step": step,
|
| 518 |
+
}
|
| 519 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 520 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 521 |
+
print("[FINAL] Final checkpoint saved.")
|
| 522 |
+
print("Exiting.")
|
| 523 |
+
|
| 524 |
+
# --------------------------
|
| 525 |
+
# CLI
|
| 526 |
+
# --------------------------
|
| 527 |
+
def parse_args():
|
| 528 |
+
p = argparse.ArgumentParser()
|
| 529 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 530 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 531 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 532 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 533 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 534 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 535 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 536 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 537 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 538 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 539 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 540 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 541 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 542 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 543 |
+
return p.parse_args()
|
| 544 |
+
|
| 545 |
+
if __name__ == "__main__":
|
| 546 |
+
args = parse_args()
|
| 547 |
+
train(
|
| 548 |
+
base_dir=args.base_dir,
|
| 549 |
+
train_list=args.train_list,
|
| 550 |
+
image_size=args.image_size,
|
| 551 |
+
batch_size=args.batch_size,
|
| 552 |
+
num_workers=args.num_workers,
|
| 553 |
+
timesteps=args.timesteps,
|
| 554 |
+
total_steps=args.total_steps,
|
| 555 |
+
lr=args.lr,
|
| 556 |
+
base_channels=args.base_channels,
|
| 557 |
+
save_every=args.save_every,
|
| 558 |
+
sample_every=args.sample_every,
|
| 559 |
+
ema_decay=args.ema_decay,
|
| 560 |
+
val_sample_steps=args.val_sample_steps,
|
| 561 |
+
sample_only=args.sample_only,
|
| 562 |
+
)
|
training_scripts/train_blur_brats_3.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_conditional_final.py — Robust conditional trainer (drop-in)
|
| 4 |
+
|
| 5 |
+
Changes made:
|
| 6 |
+
- ALWAYS skip loading optimizer state on resume (prints a clear message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression/train")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 240
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 1e-4
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 3.0):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("L").resize((self.image_size, self.image_size))
|
| 119 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 120 |
+
x0 = arr * 2.0 - 1.0
|
| 121 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 122 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 123 |
+
b = b_arr * 2.0 - 1.0
|
| 124 |
+
x0_t = torch.from_numpy(x0).unsqueeze(0).float()
|
| 125 |
+
b_t = torch.from_numpy(b).unsqueeze(0).float()
|
| 126 |
+
return x0_t, b_t
|
| 127 |
+
|
| 128 |
+
# --------------------------
|
| 129 |
+
# Model: UNet conditional
|
| 130 |
+
# --------------------------
|
| 131 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 132 |
+
def __init__(self, dim):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.dim = dim
|
| 135 |
+
def forward(self, t):
|
| 136 |
+
device = t.device
|
| 137 |
+
half = self.dim // 2
|
| 138 |
+
emb = math.log(10000) / (half - 1)
|
| 139 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 140 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 141 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 142 |
+
|
| 143 |
+
class ResBlock(nn.Module):
|
| 144 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 145 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 146 |
+
super().__init__()
|
| 147 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 148 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 149 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 150 |
+
self.act = nn.SiLU()
|
| 151 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 152 |
+
def forward(self, x, t_emb):
|
| 153 |
+
h = self.act(self.conv1(x))
|
| 154 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 155 |
+
h = self.conv2(h)
|
| 156 |
+
return self.act(h + self.res_conv(x))
|
| 157 |
+
|
| 158 |
+
class UNetCond(nn.Module):
|
| 159 |
+
def __init__(self, in_ch=2, base=64, time_dim=256):
|
| 160 |
+
super().__init__()
|
| 161 |
+
self.time_mlp = nn.Sequential(
|
| 162 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 163 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 164 |
+
nn.SiLU(),
|
| 165 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 166 |
+
)
|
| 167 |
+
# small condition projection to strengthen conditioning at early layers
|
| 168 |
+
self.cond_proj = nn.Sequential(
|
| 169 |
+
nn.Conv2d(1, base, 3, padding=1),
|
| 170 |
+
nn.SiLU(),
|
| 171 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 175 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 176 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 177 |
+
self.pool = nn.AvgPool2d(2)
|
| 178 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 179 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 180 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 181 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 182 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 183 |
+
self.final = nn.Conv2d(base, 1, 1)
|
| 184 |
+
|
| 185 |
+
def forward(self, noisy_and_cond, t):
|
| 186 |
+
device = noisy_and_cond.device
|
| 187 |
+
t_emb = self.time_mlp(t)
|
| 188 |
+
|
| 189 |
+
noisy = noisy_and_cond[:, :1, ...]
|
| 190 |
+
cond = noisy_and_cond[:, 1:, ...]
|
| 191 |
+
cond_feat = self.cond_proj(cond)
|
| 192 |
+
|
| 193 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 194 |
+
try:
|
| 195 |
+
d1 = d1 + cond_feat
|
| 196 |
+
except Exception:
|
| 197 |
+
pass
|
| 198 |
+
|
| 199 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 200 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 201 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 202 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 203 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 204 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 205 |
+
return self.final(u1)
|
| 206 |
+
|
| 207 |
+
# --------------------------
|
| 208 |
+
# Diffusion utils
|
| 209 |
+
# --------------------------
|
| 210 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 211 |
+
return torch.linspace(start, end, timesteps)
|
| 212 |
+
|
| 213 |
+
class Diffusion(nn.Module):
|
| 214 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 215 |
+
super().__init__()
|
| 216 |
+
self.timesteps = timesteps
|
| 217 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 218 |
+
alphas = 1.0 - betas
|
| 219 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 220 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 221 |
+
self.register_buffer("betas", betas)
|
| 222 |
+
self.register_buffer("alphas", alphas)
|
| 223 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 224 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 225 |
+
|
| 226 |
+
def q_sample(self, x0, t, noise=None):
|
| 227 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 228 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 229 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 230 |
+
|
| 231 |
+
def p_losses(self, model, x0, cond, t):
|
| 232 |
+
noise = torch.randn_like(x0)
|
| 233 |
+
x_t = self.q_sample(x0, t, noise)
|
| 234 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 235 |
+
noise_pred = model(inp, t)
|
| 236 |
+
return F.mse_loss(noise_pred, noise)
|
| 237 |
+
|
| 238 |
+
@torch.no_grad()
|
| 239 |
+
def p_sample(self, model, x_t, cond, t):
|
| 240 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 241 |
+
alphas_t = (1.0 - betas_t)
|
| 242 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 243 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 244 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 245 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 246 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 247 |
+
noise = torch.randn_like(x_t)
|
| 248 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 249 |
+
sigma = torch.sqrt(betas_t)
|
| 250 |
+
return mean + mask * sigma * noise
|
| 251 |
+
|
| 252 |
+
@torch.no_grad()
|
| 253 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 254 |
+
model.eval()
|
| 255 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 256 |
+
if num_steps is None: num_steps = start_t + 1
|
| 257 |
+
B = cond.shape[0]
|
| 258 |
+
x_t = torch.randn((B,1,cond.shape[2],cond.shape[3]), device=device)
|
| 259 |
+
t_values = list(range(start_t, -1, -1))
|
| 260 |
+
if num_steps < len(t_values):
|
| 261 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 262 |
+
t_values = [t_values[i] for i in idxs]
|
| 263 |
+
for t_scalar in t_values:
|
| 264 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 265 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 266 |
+
return x_t
|
| 267 |
+
|
| 268 |
+
# --------------------------
|
| 269 |
+
# EMA helper
|
| 270 |
+
# --------------------------
|
| 271 |
+
class EMA:
|
| 272 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 273 |
+
self.decay = decay
|
| 274 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 275 |
+
|
| 276 |
+
def update(self, net: nn.Module):
|
| 277 |
+
for k, v in net.state_dict().items():
|
| 278 |
+
if k in self.shadow:
|
| 279 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 280 |
+
else:
|
| 281 |
+
self.shadow[k] = v.clone().detach()
|
| 282 |
+
|
| 283 |
+
def to_state_dict(self):
|
| 284 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 285 |
+
|
| 286 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 287 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 288 |
+
|
| 289 |
+
# --------------------------
|
| 290 |
+
# Image grid save
|
| 291 |
+
# --------------------------
|
| 292 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 293 |
+
tensor = tensor.detach().cpu()
|
| 294 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 295 |
+
arr = arr.astype(np.uint8)
|
| 296 |
+
B,C,H,W = arr.shape
|
| 297 |
+
ncol = math.ceil(B / nrow)
|
| 298 |
+
grid = Image.new("L", (W * ncol, H * nrow))
|
| 299 |
+
idx = 0
|
| 300 |
+
for r in range(nrow):
|
| 301 |
+
for c in range(ncol):
|
| 302 |
+
if idx >= B: break
|
| 303 |
+
img = Image.fromarray(arr[idx,0])
|
| 304 |
+
grid.paste(img, (c*W, r*H))
|
| 305 |
+
idx += 1
|
| 306 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 307 |
+
grid.save(path)
|
| 308 |
+
print(f"[SAVE] image saved: {path}")
|
| 309 |
+
|
| 310 |
+
# --------------------------
|
| 311 |
+
# Trainer (main)
|
| 312 |
+
# --------------------------
|
| 313 |
+
def train(
|
| 314 |
+
base_dir: str,
|
| 315 |
+
train_list: Optional[str] = None,
|
| 316 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 317 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 318 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 319 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 320 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 321 |
+
lr: float = DEFAULT_LR,
|
| 322 |
+
base_channels: int = 64,
|
| 323 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 324 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 325 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 326 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 327 |
+
sample_only: Optional[str] = None,
|
| 328 |
+
):
|
| 329 |
+
base = Path(base_dir)
|
| 330 |
+
train_list = train_list or (base / "train_list.txt")
|
| 331 |
+
ckpt_dir = base / "checkpoints_cond_blur3"
|
| 332 |
+
samples_dir = base / "samples_cond_blur3"
|
| 333 |
+
progress_dir = base / "progress_cond_blur3"
|
| 334 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 335 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 336 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 337 |
+
|
| 338 |
+
device = get_device()
|
| 339 |
+
print("Device:", device)
|
| 340 |
+
|
| 341 |
+
model = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 342 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 343 |
+
|
| 344 |
+
if sample_only:
|
| 345 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 346 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 347 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 348 |
+
model.load_state_dict(sd, strict=False)
|
| 349 |
+
model_for_sampling = model
|
| 350 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 351 |
+
try:
|
| 352 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 353 |
+
tmp = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 354 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 355 |
+
model_for_sampling = tmp
|
| 356 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 357 |
+
except Exception as e:
|
| 358 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 359 |
+
conds = []
|
| 360 |
+
with open(train_list, "r") as f:
|
| 361 |
+
for i, line in enumerate(f):
|
| 362 |
+
if i >= 4: break
|
| 363 |
+
p = Path(line.strip())
|
| 364 |
+
im = Image.open(p).convert("L").resize((image_size, image_size))
|
| 365 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=3.0))
|
| 366 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 367 |
+
conds.append(torch.from_numpy(arr).unsqueeze(0).unsqueeze(0).float())
|
| 368 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 369 |
+
with torch.no_grad():
|
| 370 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 371 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 372 |
+
save_grid(samples, out, nrow=2)
|
| 373 |
+
return
|
| 374 |
+
|
| 375 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=3.0)
|
| 376 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 377 |
+
|
| 378 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 379 |
+
ema = EMA(model, decay=ema_decay)
|
| 380 |
+
|
| 381 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 382 |
+
start_step = 0
|
| 383 |
+
if latest.exists():
|
| 384 |
+
print("Resuming from", latest)
|
| 385 |
+
data = safe_torch_load(latest, map_location=device)
|
| 386 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 387 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 388 |
+
try:
|
| 389 |
+
model.load_state_dict(raw_model_sd)
|
| 390 |
+
print("[LOAD] model loaded (strict=True).")
|
| 391 |
+
except Exception as e:
|
| 392 |
+
print("[LOAD] strict load failed:", e)
|
| 393 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 394 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 395 |
+
|
| 396 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 397 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 398 |
+
|
| 399 |
+
if isinstance(data, dict) and "ema" in data:
|
| 400 |
+
try:
|
| 401 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 402 |
+
model_keys = set(model.state_dict().keys())
|
| 403 |
+
ema_keys = set(ema_sd.keys())
|
| 404 |
+
if ema_keys == model_keys:
|
| 405 |
+
ema.load_state_dict(ema_sd)
|
| 406 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 407 |
+
else:
|
| 408 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 409 |
+
ema = EMA(model, decay=ema_decay)
|
| 410 |
+
for g in opt.param_groups:
|
| 411 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 412 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 413 |
+
except Exception as e:
|
| 414 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
else:
|
| 417 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 418 |
+
ema = EMA(model, decay=ema_decay)
|
| 419 |
+
for g in opt.param_groups:
|
| 420 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 421 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 422 |
+
|
| 423 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 424 |
+
print("Resumed at step:", start_step)
|
| 425 |
+
|
| 426 |
+
stop = {"flag": False}
|
| 427 |
+
def handler(sig, frame):
|
| 428 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 429 |
+
stop["flag"] = True
|
| 430 |
+
signal.signal(signal.SIGINT, handler)
|
| 431 |
+
signal.signal(signal.SIGTERM, handler)
|
| 432 |
+
|
| 433 |
+
model.train()
|
| 434 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 435 |
+
step = start_step
|
| 436 |
+
ema_loss = None
|
| 437 |
+
|
| 438 |
+
try:
|
| 439 |
+
while step < total_steps:
|
| 440 |
+
for x0, cond in dl:
|
| 441 |
+
if stop["flag"]:
|
| 442 |
+
break
|
| 443 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 444 |
+
bsz = x0.shape[0]
|
| 445 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 446 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 447 |
+
|
| 448 |
+
opt.zero_grad()
|
| 449 |
+
loss.backward()
|
| 450 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 451 |
+
opt.step()
|
| 452 |
+
ema.update(model)
|
| 453 |
+
|
| 454 |
+
step += 1
|
| 455 |
+
val = float(loss.item())
|
| 456 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 457 |
+
|
| 458 |
+
if step % 50 == 0:
|
| 459 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 460 |
+
|
| 461 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 462 |
+
pbar.update(1)
|
| 463 |
+
|
| 464 |
+
if step % sample_every == 0 or step == 1:
|
| 465 |
+
with torch.no_grad():
|
| 466 |
+
try:
|
| 467 |
+
sample_model = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 468 |
+
try:
|
| 469 |
+
ema_sd = ema.to_state_dict()
|
| 470 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 471 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 472 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 473 |
+
except Exception:
|
| 474 |
+
try:
|
| 475 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 476 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 477 |
+
except Exception as e:
|
| 478 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 479 |
+
sample_model = model
|
| 480 |
+
except Exception as e:
|
| 481 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 482 |
+
sample_model = model
|
| 483 |
+
|
| 484 |
+
cond_batch = cond[:4].to(device)
|
| 485 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 486 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 487 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 488 |
+
save_grid(samples, s_path, nrow=2)
|
| 489 |
+
save_grid(samples, p_path, nrow=2)
|
| 490 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 491 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 492 |
+
|
| 493 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 494 |
+
ck = {
|
| 495 |
+
"model": model.state_dict(),
|
| 496 |
+
"optimizer": opt.state_dict(),
|
| 497 |
+
"ema": ema.to_state_dict(),
|
| 498 |
+
"step": step,
|
| 499 |
+
}
|
| 500 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 501 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 502 |
+
atomic_save(ck, p1)
|
| 503 |
+
atomic_save(ck, p2)
|
| 504 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 505 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 506 |
+
|
| 507 |
+
if step >= total_steps:
|
| 508 |
+
break
|
| 509 |
+
if stop["flag"]:
|
| 510 |
+
break
|
| 511 |
+
finally:
|
| 512 |
+
pbar.close()
|
| 513 |
+
ck = {
|
| 514 |
+
"model": model.state_dict(),
|
| 515 |
+
"optimizer": opt.state_dict(),
|
| 516 |
+
"ema": ema.to_state_dict(),
|
| 517 |
+
"step": step,
|
| 518 |
+
}
|
| 519 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 520 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 521 |
+
print("[FINAL] Final checkpoint saved.")
|
| 522 |
+
print("Exiting.")
|
| 523 |
+
|
| 524 |
+
# --------------------------
|
| 525 |
+
# CLI
|
| 526 |
+
# --------------------------
|
| 527 |
+
def parse_args():
|
| 528 |
+
p = argparse.ArgumentParser()
|
| 529 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 530 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 531 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 532 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 533 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 534 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 535 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 536 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 537 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 538 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 539 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 540 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 541 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 542 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 543 |
+
return p.parse_args()
|
| 544 |
+
|
| 545 |
+
if __name__ == "__main__":
|
| 546 |
+
args = parse_args()
|
| 547 |
+
train(
|
| 548 |
+
base_dir=args.base_dir,
|
| 549 |
+
train_list=args.train_list,
|
| 550 |
+
image_size=args.image_size,
|
| 551 |
+
batch_size=args.batch_size,
|
| 552 |
+
num_workers=args.num_workers,
|
| 553 |
+
timesteps=args.timesteps,
|
| 554 |
+
total_steps=args.total_steps,
|
| 555 |
+
lr=args.lr,
|
| 556 |
+
base_channels=args.base_channels,
|
| 557 |
+
save_every=args.save_every,
|
| 558 |
+
sample_every=args.sample_every,
|
| 559 |
+
ema_decay=args.ema_decay,
|
| 560 |
+
val_sample_steps=args.val_sample_steps,
|
| 561 |
+
sample_only=args.sample_only,
|
| 562 |
+
)
|
training_scripts/train_blur_brats_half.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_conditional_final.py — Robust conditional trainer (drop-in)
|
| 4 |
+
|
| 5 |
+
Changes made:
|
| 6 |
+
- ALWAYS skip loading optimizer state on resume (prints a clear message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression/train")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 240
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 1e-4
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 0.5):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("L").resize((self.image_size, self.image_size))
|
| 119 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 120 |
+
x0 = arr * 2.0 - 1.0
|
| 121 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 122 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 123 |
+
b = b_arr * 2.0 - 1.0
|
| 124 |
+
x0_t = torch.from_numpy(x0).unsqueeze(0).float()
|
| 125 |
+
b_t = torch.from_numpy(b).unsqueeze(0).float()
|
| 126 |
+
return x0_t, b_t
|
| 127 |
+
|
| 128 |
+
# --------------------------
|
| 129 |
+
# Model: UNet conditional
|
| 130 |
+
# --------------------------
|
| 131 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 132 |
+
def __init__(self, dim):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.dim = dim
|
| 135 |
+
def forward(self, t):
|
| 136 |
+
device = t.device
|
| 137 |
+
half = self.dim // 2
|
| 138 |
+
emb = math.log(10000) / (half - 1)
|
| 139 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 140 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 141 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 142 |
+
|
| 143 |
+
class ResBlock(nn.Module):
|
| 144 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 145 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 146 |
+
super().__init__()
|
| 147 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 148 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 149 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 150 |
+
self.act = nn.SiLU()
|
| 151 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 152 |
+
def forward(self, x, t_emb):
|
| 153 |
+
h = self.act(self.conv1(x))
|
| 154 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 155 |
+
h = self.conv2(h)
|
| 156 |
+
return self.act(h + self.res_conv(x))
|
| 157 |
+
|
| 158 |
+
class UNetCond(nn.Module):
|
| 159 |
+
def __init__(self, in_ch=2, base=64, time_dim=256):
|
| 160 |
+
super().__init__()
|
| 161 |
+
self.time_mlp = nn.Sequential(
|
| 162 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 163 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 164 |
+
nn.SiLU(),
|
| 165 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 166 |
+
)
|
| 167 |
+
# small condition projection to strengthen conditioning at early layers
|
| 168 |
+
self.cond_proj = nn.Sequential(
|
| 169 |
+
nn.Conv2d(1, base, 3, padding=1),
|
| 170 |
+
nn.SiLU(),
|
| 171 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 175 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 176 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 177 |
+
self.pool = nn.AvgPool2d(2)
|
| 178 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 179 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 180 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 181 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 182 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 183 |
+
self.final = nn.Conv2d(base, 1, 1)
|
| 184 |
+
|
| 185 |
+
def forward(self, noisy_and_cond, t):
|
| 186 |
+
device = noisy_and_cond.device
|
| 187 |
+
t_emb = self.time_mlp(t)
|
| 188 |
+
|
| 189 |
+
noisy = noisy_and_cond[:, :1, ...]
|
| 190 |
+
cond = noisy_and_cond[:, 1:, ...]
|
| 191 |
+
cond_feat = self.cond_proj(cond)
|
| 192 |
+
|
| 193 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 194 |
+
try:
|
| 195 |
+
d1 = d1 + cond_feat
|
| 196 |
+
except Exception:
|
| 197 |
+
pass
|
| 198 |
+
|
| 199 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 200 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 201 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 202 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 203 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 204 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 205 |
+
return self.final(u1)
|
| 206 |
+
|
| 207 |
+
# --------------------------
|
| 208 |
+
# Diffusion utils
|
| 209 |
+
# --------------------------
|
| 210 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 211 |
+
return torch.linspace(start, end, timesteps)
|
| 212 |
+
|
| 213 |
+
class Diffusion(nn.Module):
|
| 214 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 215 |
+
super().__init__()
|
| 216 |
+
self.timesteps = timesteps
|
| 217 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 218 |
+
alphas = 1.0 - betas
|
| 219 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 220 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 221 |
+
self.register_buffer("betas", betas)
|
| 222 |
+
self.register_buffer("alphas", alphas)
|
| 223 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 224 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 225 |
+
|
| 226 |
+
def q_sample(self, x0, t, noise=None):
|
| 227 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 228 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 229 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 230 |
+
|
| 231 |
+
def p_losses(self, model, x0, cond, t):
|
| 232 |
+
noise = torch.randn_like(x0)
|
| 233 |
+
x_t = self.q_sample(x0, t, noise)
|
| 234 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 235 |
+
noise_pred = model(inp, t)
|
| 236 |
+
return F.mse_loss(noise_pred, noise)
|
| 237 |
+
|
| 238 |
+
@torch.no_grad()
|
| 239 |
+
def p_sample(self, model, x_t, cond, t):
|
| 240 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 241 |
+
alphas_t = (1.0 - betas_t)
|
| 242 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 243 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 244 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 245 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 246 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 247 |
+
noise = torch.randn_like(x_t)
|
| 248 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 249 |
+
sigma = torch.sqrt(betas_t)
|
| 250 |
+
return mean + mask * sigma * noise
|
| 251 |
+
|
| 252 |
+
@torch.no_grad()
|
| 253 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 254 |
+
model.eval()
|
| 255 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 256 |
+
if num_steps is None: num_steps = start_t + 1
|
| 257 |
+
B = cond.shape[0]
|
| 258 |
+
x_t = torch.randn((B,1,cond.shape[2],cond.shape[3]), device=device)
|
| 259 |
+
t_values = list(range(start_t, -1, -1))
|
| 260 |
+
if num_steps < len(t_values):
|
| 261 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 262 |
+
t_values = [t_values[i] for i in idxs]
|
| 263 |
+
for t_scalar in t_values:
|
| 264 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 265 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 266 |
+
return x_t
|
| 267 |
+
|
| 268 |
+
# --------------------------
|
| 269 |
+
# EMA helper
|
| 270 |
+
# --------------------------
|
| 271 |
+
class EMA:
|
| 272 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 273 |
+
self.decay = decay
|
| 274 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 275 |
+
|
| 276 |
+
def update(self, net: nn.Module):
|
| 277 |
+
for k, v in net.state_dict().items():
|
| 278 |
+
if k in self.shadow:
|
| 279 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 280 |
+
else:
|
| 281 |
+
self.shadow[k] = v.clone().detach()
|
| 282 |
+
|
| 283 |
+
def to_state_dict(self):
|
| 284 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 285 |
+
|
| 286 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 287 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 288 |
+
|
| 289 |
+
# --------------------------
|
| 290 |
+
# Image grid save
|
| 291 |
+
# --------------------------
|
| 292 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 293 |
+
tensor = tensor.detach().cpu()
|
| 294 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 295 |
+
arr = arr.astype(np.uint8)
|
| 296 |
+
B,C,H,W = arr.shape
|
| 297 |
+
ncol = math.ceil(B / nrow)
|
| 298 |
+
grid = Image.new("L", (W * ncol, H * nrow))
|
| 299 |
+
idx = 0
|
| 300 |
+
for r in range(nrow):
|
| 301 |
+
for c in range(ncol):
|
| 302 |
+
if idx >= B: break
|
| 303 |
+
img = Image.fromarray(arr[idx,0])
|
| 304 |
+
grid.paste(img, (c*W, r*H))
|
| 305 |
+
idx += 1
|
| 306 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 307 |
+
grid.save(path)
|
| 308 |
+
print(f"[SAVE] image saved: {path}")
|
| 309 |
+
|
| 310 |
+
# --------------------------
|
| 311 |
+
# Trainer (main)
|
| 312 |
+
# --------------------------
|
| 313 |
+
def train(
|
| 314 |
+
base_dir: str,
|
| 315 |
+
train_list: Optional[str] = None,
|
| 316 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 317 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 318 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 319 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 320 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 321 |
+
lr: float = DEFAULT_LR,
|
| 322 |
+
base_channels: int = 64,
|
| 323 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 324 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 325 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 326 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 327 |
+
sample_only: Optional[str] = None,
|
| 328 |
+
):
|
| 329 |
+
base = Path(base_dir)
|
| 330 |
+
train_list = train_list or (base / "train_list.txt")
|
| 331 |
+
ckpt_dir = base / "checkpoints_cond_blur_0.5"
|
| 332 |
+
samples_dir = base / "samples_cond_blur_0.5"
|
| 333 |
+
progress_dir = base / "progress_cond_blur_0.5"
|
| 334 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 335 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 336 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 337 |
+
|
| 338 |
+
device = get_device()
|
| 339 |
+
print("Device:", device)
|
| 340 |
+
|
| 341 |
+
model = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 342 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 343 |
+
|
| 344 |
+
if sample_only:
|
| 345 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 346 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 347 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 348 |
+
model.load_state_dict(sd, strict=False)
|
| 349 |
+
model_for_sampling = model
|
| 350 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 351 |
+
try:
|
| 352 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 353 |
+
tmp = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 354 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 355 |
+
model_for_sampling = tmp
|
| 356 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 357 |
+
except Exception as e:
|
| 358 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 359 |
+
conds = []
|
| 360 |
+
with open(train_list, "r") as f:
|
| 361 |
+
for i, line in enumerate(f):
|
| 362 |
+
if i >= 4: break
|
| 363 |
+
p = Path(line.strip())
|
| 364 |
+
im = Image.open(p).convert("L").resize((image_size, image_size))
|
| 365 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=0.5))
|
| 366 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 367 |
+
conds.append(torch.from_numpy(arr).unsqueeze(0).unsqueeze(0).float())
|
| 368 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 369 |
+
with torch.no_grad():
|
| 370 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 371 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 372 |
+
save_grid(samples, out, nrow=2)
|
| 373 |
+
return
|
| 374 |
+
|
| 375 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=0.5)
|
| 376 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 377 |
+
|
| 378 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 379 |
+
ema = EMA(model, decay=ema_decay)
|
| 380 |
+
|
| 381 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 382 |
+
start_step = 0
|
| 383 |
+
if latest.exists():
|
| 384 |
+
print("Resuming from", latest)
|
| 385 |
+
data = safe_torch_load(latest, map_location=device)
|
| 386 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 387 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 388 |
+
try:
|
| 389 |
+
model.load_state_dict(raw_model_sd)
|
| 390 |
+
print("[LOAD] model loaded (strict=True).")
|
| 391 |
+
except Exception as e:
|
| 392 |
+
print("[LOAD] strict load failed:", e)
|
| 393 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 394 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 395 |
+
|
| 396 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 397 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 398 |
+
|
| 399 |
+
if isinstance(data, dict) and "ema" in data:
|
| 400 |
+
try:
|
| 401 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 402 |
+
model_keys = set(model.state_dict().keys())
|
| 403 |
+
ema_keys = set(ema_sd.keys())
|
| 404 |
+
if ema_keys == model_keys:
|
| 405 |
+
ema.load_state_dict(ema_sd)
|
| 406 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 407 |
+
else:
|
| 408 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 409 |
+
ema = EMA(model, decay=ema_decay)
|
| 410 |
+
for g in opt.param_groups:
|
| 411 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 412 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 413 |
+
except Exception as e:
|
| 414 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
else:
|
| 417 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 418 |
+
ema = EMA(model, decay=ema_decay)
|
| 419 |
+
for g in opt.param_groups:
|
| 420 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 421 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 422 |
+
|
| 423 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 424 |
+
print("Resumed at step:", start_step)
|
| 425 |
+
|
| 426 |
+
stop = {"flag": False}
|
| 427 |
+
def handler(sig, frame):
|
| 428 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 429 |
+
stop["flag"] = True
|
| 430 |
+
signal.signal(signal.SIGINT, handler)
|
| 431 |
+
signal.signal(signal.SIGTERM, handler)
|
| 432 |
+
|
| 433 |
+
model.train()
|
| 434 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 435 |
+
step = start_step
|
| 436 |
+
ema_loss = None
|
| 437 |
+
|
| 438 |
+
try:
|
| 439 |
+
while step < total_steps:
|
| 440 |
+
for x0, cond in dl:
|
| 441 |
+
if stop["flag"]:
|
| 442 |
+
break
|
| 443 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 444 |
+
bsz = x0.shape[0]
|
| 445 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 446 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 447 |
+
|
| 448 |
+
opt.zero_grad()
|
| 449 |
+
loss.backward()
|
| 450 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 451 |
+
opt.step()
|
| 452 |
+
ema.update(model)
|
| 453 |
+
|
| 454 |
+
step += 1
|
| 455 |
+
val = float(loss.item())
|
| 456 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 457 |
+
|
| 458 |
+
if step % 50 == 0:
|
| 459 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 460 |
+
|
| 461 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 462 |
+
pbar.update(1)
|
| 463 |
+
|
| 464 |
+
if step % sample_every == 0 or step == 1:
|
| 465 |
+
with torch.no_grad():
|
| 466 |
+
try:
|
| 467 |
+
sample_model = UNetCond(in_ch=2, base=base_channels).to(device)
|
| 468 |
+
try:
|
| 469 |
+
ema_sd = ema.to_state_dict()
|
| 470 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 471 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 472 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 473 |
+
except Exception:
|
| 474 |
+
try:
|
| 475 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 476 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 477 |
+
except Exception as e:
|
| 478 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 479 |
+
sample_model = model
|
| 480 |
+
except Exception as e:
|
| 481 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 482 |
+
sample_model = model
|
| 483 |
+
|
| 484 |
+
cond_batch = cond[:4].to(device)
|
| 485 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 486 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 487 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 488 |
+
save_grid(samples, s_path, nrow=2)
|
| 489 |
+
save_grid(samples, p_path, nrow=2)
|
| 490 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 491 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 492 |
+
|
| 493 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 494 |
+
ck = {
|
| 495 |
+
"model": model.state_dict(),
|
| 496 |
+
"optimizer": opt.state_dict(),
|
| 497 |
+
"ema": ema.to_state_dict(),
|
| 498 |
+
"step": step,
|
| 499 |
+
}
|
| 500 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 501 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 502 |
+
atomic_save(ck, p1)
|
| 503 |
+
atomic_save(ck, p2)
|
| 504 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 505 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 506 |
+
|
| 507 |
+
if step >= total_steps:
|
| 508 |
+
break
|
| 509 |
+
if stop["flag"]:
|
| 510 |
+
break
|
| 511 |
+
finally:
|
| 512 |
+
pbar.close()
|
| 513 |
+
ck = {
|
| 514 |
+
"model": model.state_dict(),
|
| 515 |
+
"optimizer": opt.state_dict(),
|
| 516 |
+
"ema": ema.to_state_dict(),
|
| 517 |
+
"step": step,
|
| 518 |
+
}
|
| 519 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 520 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 521 |
+
print("[FINAL] Final checkpoint saved.")
|
| 522 |
+
print("Exiting.")
|
| 523 |
+
|
| 524 |
+
# --------------------------
|
| 525 |
+
# CLI
|
| 526 |
+
# --------------------------
|
| 527 |
+
def parse_args():
|
| 528 |
+
p = argparse.ArgumentParser()
|
| 529 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 530 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 531 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 532 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 533 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 534 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 535 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 536 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 537 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 538 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 539 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 540 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 541 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 542 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 543 |
+
return p.parse_args()
|
| 544 |
+
|
| 545 |
+
if __name__ == "__main__":
|
| 546 |
+
args = parse_args()
|
| 547 |
+
train(
|
| 548 |
+
base_dir=args.base_dir,
|
| 549 |
+
train_list=args.train_list,
|
| 550 |
+
image_size=args.image_size,
|
| 551 |
+
batch_size=args.batch_size,
|
| 552 |
+
num_workers=args.num_workers,
|
| 553 |
+
timesteps=args.timesteps,
|
| 554 |
+
total_steps=args.total_steps,
|
| 555 |
+
lr=args.lr,
|
| 556 |
+
base_channels=args.base_channels,
|
| 557 |
+
save_every=args.save_every,
|
| 558 |
+
sample_every=args.sample_every,
|
| 559 |
+
ema_decay=args.ema_decay,
|
| 560 |
+
val_sample_steps=args.val_sample_steps,
|
| 561 |
+
sample_only=args.sample_only,
|
| 562 |
+
)
|
training_scripts/train_buildings_blur0.5.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 256
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 1e-4
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 0.5):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("RGB")
|
| 119 |
+
assert img.size == (self.image_size, self.image_size), f"Bad image size: {img.size}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 123 |
+
x0 = arr * 2.0 - 1.0
|
| 124 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 125 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 126 |
+
b = b_arr * 2.0 - 1.0
|
| 127 |
+
x0_t = torch.from_numpy(x0).permute(2, 0, 1).float()
|
| 128 |
+
b_t = torch.from_numpy(b).permute(2, 0, 1).float()
|
| 129 |
+
return x0_t, b_t
|
| 130 |
+
|
| 131 |
+
# --------------------------
|
| 132 |
+
# Model: UNet conditional
|
| 133 |
+
# --------------------------
|
| 134 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 135 |
+
def __init__(self, dim):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.dim = dim
|
| 138 |
+
def forward(self, t):
|
| 139 |
+
device = t.device
|
| 140 |
+
half = self.dim // 2
|
| 141 |
+
emb = math.log(10000) / (half - 1)
|
| 142 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 143 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 144 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 145 |
+
|
| 146 |
+
class ResBlock(nn.Module):
|
| 147 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 148 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 151 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 152 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 153 |
+
self.act = nn.SiLU()
|
| 154 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 155 |
+
def forward(self, x, t_emb):
|
| 156 |
+
h = self.act(self.conv1(x))
|
| 157 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 158 |
+
h = self.conv2(h)
|
| 159 |
+
return self.act(h + self.res_conv(x))
|
| 160 |
+
|
| 161 |
+
class UNetCond(nn.Module):
|
| 162 |
+
def __init__(self, in_ch=6, base=64, time_dim=256):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.time_mlp = nn.Sequential(
|
| 165 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 166 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 167 |
+
nn.SiLU(),
|
| 168 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 169 |
+
)
|
| 170 |
+
# small condition projection to strengthen conditioning at early layers
|
| 171 |
+
self.cond_proj = nn.Sequential(
|
| 172 |
+
nn.Conv2d(3, base, 3, padding=1),
|
| 173 |
+
nn.SiLU(),
|
| 174 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 178 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 179 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 180 |
+
self.pool = nn.AvgPool2d(2)
|
| 181 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 182 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 183 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 184 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 185 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 186 |
+
self.final = nn.Conv2d(base, 3, 1)
|
| 187 |
+
|
| 188 |
+
def forward(self, noisy_and_cond, t):
|
| 189 |
+
device = noisy_and_cond.device
|
| 190 |
+
t_emb = self.time_mlp(t)
|
| 191 |
+
|
| 192 |
+
noisy = noisy_and_cond[:, :3, ...]
|
| 193 |
+
cond = noisy_and_cond[:, 3:, ...]
|
| 194 |
+
cond_feat = self.cond_proj(cond)
|
| 195 |
+
|
| 196 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 197 |
+
try:
|
| 198 |
+
d1 = d1 + cond_feat
|
| 199 |
+
except Exception:
|
| 200 |
+
pass
|
| 201 |
+
|
| 202 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 203 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 204 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 205 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 206 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 207 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 208 |
+
return self.final(u1)
|
| 209 |
+
|
| 210 |
+
# --------------------------
|
| 211 |
+
# Diffusion utils
|
| 212 |
+
# --------------------------
|
| 213 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 214 |
+
return torch.linspace(start, end, timesteps)
|
| 215 |
+
|
| 216 |
+
class Diffusion(nn.Module):
|
| 217 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.timesteps = timesteps
|
| 220 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 221 |
+
alphas = 1.0 - betas
|
| 222 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 223 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 224 |
+
self.register_buffer("betas", betas)
|
| 225 |
+
self.register_buffer("alphas", alphas)
|
| 226 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 227 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 228 |
+
|
| 229 |
+
def q_sample(self, x0, t, noise=None):
|
| 230 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 231 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 232 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 233 |
+
|
| 234 |
+
def p_losses(self, model, x0, cond, t):
|
| 235 |
+
noise = torch.randn_like(x0)
|
| 236 |
+
x_t = self.q_sample(x0, t, noise)
|
| 237 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 238 |
+
noise_pred = model(inp, t)
|
| 239 |
+
return F.mse_loss(noise_pred, noise)
|
| 240 |
+
|
| 241 |
+
@torch.no_grad()
|
| 242 |
+
def p_sample(self, model, x_t, cond, t):
|
| 243 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 244 |
+
alphas_t = (1.0 - betas_t)
|
| 245 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 246 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 247 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 248 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 249 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 250 |
+
noise = torch.randn_like(x_t)
|
| 251 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 252 |
+
sigma = torch.sqrt(betas_t)
|
| 253 |
+
return mean + mask * sigma * noise
|
| 254 |
+
|
| 255 |
+
@torch.no_grad()
|
| 256 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 257 |
+
model.eval()
|
| 258 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 259 |
+
if num_steps is None: num_steps = start_t + 1
|
| 260 |
+
B = cond.shape[0]
|
| 261 |
+
x_t = torch.randn((B, 3, cond.shape[2], cond.shape[3]), device=device)
|
| 262 |
+
t_values = list(range(start_t, -1, -1))
|
| 263 |
+
if num_steps < len(t_values):
|
| 264 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 265 |
+
t_values = [t_values[i] for i in idxs]
|
| 266 |
+
for t_scalar in t_values:
|
| 267 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 268 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 269 |
+
return x_t
|
| 270 |
+
|
| 271 |
+
# --------------------------
|
| 272 |
+
# EMA helper
|
| 273 |
+
# --------------------------
|
| 274 |
+
class EMA:
|
| 275 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 276 |
+
self.decay = decay
|
| 277 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 278 |
+
|
| 279 |
+
def update(self, net: nn.Module):
|
| 280 |
+
for k, v in net.state_dict().items():
|
| 281 |
+
if k in self.shadow:
|
| 282 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 283 |
+
else:
|
| 284 |
+
self.shadow[k] = v.clone().detach()
|
| 285 |
+
|
| 286 |
+
def to_state_dict(self):
|
| 287 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 288 |
+
|
| 289 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 290 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 291 |
+
|
| 292 |
+
# --------------------------
|
| 293 |
+
# Image grid save
|
| 294 |
+
# --------------------------
|
| 295 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 296 |
+
tensor = tensor.detach().cpu()
|
| 297 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 298 |
+
arr = arr.astype(np.uint8)
|
| 299 |
+
B,C,H,W = arr.shape
|
| 300 |
+
ncol = math.ceil(B / nrow)
|
| 301 |
+
grid = Image.new("RGB", (W * ncol, H * nrow))
|
| 302 |
+
idx = 0
|
| 303 |
+
for r in range(nrow):
|
| 304 |
+
for c in range(ncol):
|
| 305 |
+
if idx >= B: break
|
| 306 |
+
img = Image.fromarray(arr[idx].transpose(1, 2, 0))
|
| 307 |
+
grid.paste(img, (c*W, r*H))
|
| 308 |
+
idx += 1
|
| 309 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 310 |
+
grid.save(path)
|
| 311 |
+
print(f"[SAVE] image saved: {path}")
|
| 312 |
+
|
| 313 |
+
# --------------------------
|
| 314 |
+
# Trainer (main)
|
| 315 |
+
# --------------------------
|
| 316 |
+
def train(
|
| 317 |
+
base_dir: str,
|
| 318 |
+
train_list: Optional[str] = None,
|
| 319 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 320 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 321 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 322 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 323 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 324 |
+
lr: float = DEFAULT_LR,
|
| 325 |
+
base_channels: int = 64,
|
| 326 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 327 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 328 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 329 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 330 |
+
sample_only: Optional[str] = None,
|
| 331 |
+
):
|
| 332 |
+
base = Path(base_dir)
|
| 333 |
+
train_list = train_list or (base / "train_list_buildings.txt")
|
| 334 |
+
ckpt_dir = base / "checkpoints_cond_blur_0.5_buildings"
|
| 335 |
+
samples_dir = base / "samples_cond_blur_0.5_buildings"
|
| 336 |
+
progress_dir = base / "progress_cond_blur_0.5_buildings"
|
| 337 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 338 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 339 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 340 |
+
|
| 341 |
+
device = get_device()
|
| 342 |
+
print("Device:", device)
|
| 343 |
+
|
| 344 |
+
model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 345 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 346 |
+
|
| 347 |
+
if sample_only:
|
| 348 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 349 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 350 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 351 |
+
model.load_state_dict(sd, strict=False)
|
| 352 |
+
model_for_sampling = model
|
| 353 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 354 |
+
try:
|
| 355 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 356 |
+
tmp = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 357 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 358 |
+
model_for_sampling = tmp
|
| 359 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 360 |
+
except Exception as e:
|
| 361 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 362 |
+
conds = []
|
| 363 |
+
with open(train_list, "r") as f:
|
| 364 |
+
for i, line in enumerate(f):
|
| 365 |
+
if i >= 4: break
|
| 366 |
+
p = Path(line.strip())
|
| 367 |
+
im = Image.open(p).convert("RGB")
|
| 368 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=0.5))
|
| 369 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 370 |
+
conds.append(
|
| 371 |
+
torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).float()
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 375 |
+
with torch.no_grad():
|
| 376 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 377 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 378 |
+
save_grid(samples, out, nrow=2)
|
| 379 |
+
return
|
| 380 |
+
|
| 381 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=0.5)
|
| 382 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 383 |
+
|
| 384 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 385 |
+
ema = EMA(model, decay=ema_decay)
|
| 386 |
+
|
| 387 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 388 |
+
start_step = 0
|
| 389 |
+
if latest.exists():
|
| 390 |
+
print("Resuming from", latest)
|
| 391 |
+
data = safe_torch_load(latest, map_location=device)
|
| 392 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 393 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 394 |
+
try:
|
| 395 |
+
model.load_state_dict(raw_model_sd)
|
| 396 |
+
print("[LOAD] model loaded (strict=True).")
|
| 397 |
+
except Exception as e:
|
| 398 |
+
print("[LOAD] strict load failed:", e)
|
| 399 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 400 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 401 |
+
|
| 402 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 403 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 404 |
+
|
| 405 |
+
if isinstance(data, dict) and "ema" in data:
|
| 406 |
+
try:
|
| 407 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 408 |
+
model_keys = set(model.state_dict().keys())
|
| 409 |
+
ema_keys = set(ema_sd.keys())
|
| 410 |
+
if ema_keys == model_keys:
|
| 411 |
+
ema.load_state_dict(ema_sd)
|
| 412 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 413 |
+
else:
|
| 414 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
for g in opt.param_groups:
|
| 417 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 418 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 419 |
+
except Exception as e:
|
| 420 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 421 |
+
ema = EMA(model, decay=ema_decay)
|
| 422 |
+
else:
|
| 423 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 424 |
+
ema = EMA(model, decay=ema_decay)
|
| 425 |
+
for g in opt.param_groups:
|
| 426 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 427 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 428 |
+
|
| 429 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 430 |
+
print("Resumed at step:", start_step)
|
| 431 |
+
|
| 432 |
+
stop = {"flag": False}
|
| 433 |
+
def handler(sig, frame):
|
| 434 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 435 |
+
stop["flag"] = True
|
| 436 |
+
signal.signal(signal.SIGINT, handler)
|
| 437 |
+
signal.signal(signal.SIGTERM, handler)
|
| 438 |
+
|
| 439 |
+
model.train()
|
| 440 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 441 |
+
step = start_step
|
| 442 |
+
ema_loss = None
|
| 443 |
+
|
| 444 |
+
try:
|
| 445 |
+
while step < total_steps:
|
| 446 |
+
for x0, cond in dl:
|
| 447 |
+
if stop["flag"]:
|
| 448 |
+
break
|
| 449 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 450 |
+
bsz = x0.shape[0]
|
| 451 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 452 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 453 |
+
|
| 454 |
+
opt.zero_grad()
|
| 455 |
+
loss.backward()
|
| 456 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 457 |
+
opt.step()
|
| 458 |
+
ema.update(model)
|
| 459 |
+
|
| 460 |
+
step += 1
|
| 461 |
+
val = float(loss.item())
|
| 462 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 463 |
+
|
| 464 |
+
if step % 50 == 0:
|
| 465 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 466 |
+
|
| 467 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 468 |
+
pbar.update(1)
|
| 469 |
+
|
| 470 |
+
if step % sample_every == 0 or step == 1:
|
| 471 |
+
with torch.no_grad():
|
| 472 |
+
try:
|
| 473 |
+
sample_model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 474 |
+
try:
|
| 475 |
+
ema_sd = ema.to_state_dict()
|
| 476 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 477 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 478 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 479 |
+
except Exception:
|
| 480 |
+
try:
|
| 481 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 482 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 483 |
+
except Exception as e:
|
| 484 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 485 |
+
sample_model = model
|
| 486 |
+
except Exception as e:
|
| 487 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 488 |
+
sample_model = model
|
| 489 |
+
|
| 490 |
+
cond_batch = cond[:4].to(device)
|
| 491 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 492 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 493 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 494 |
+
save_grid(samples, s_path, nrow=2)
|
| 495 |
+
save_grid(samples, p_path, nrow=2)
|
| 496 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 497 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 498 |
+
|
| 499 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 500 |
+
ck = {
|
| 501 |
+
"model": model.state_dict(),
|
| 502 |
+
"optimizer": opt.state_dict(),
|
| 503 |
+
"ema": ema.to_state_dict(),
|
| 504 |
+
"step": step,
|
| 505 |
+
}
|
| 506 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 507 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 508 |
+
atomic_save(ck, p1)
|
| 509 |
+
atomic_save(ck, p2)
|
| 510 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 511 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 512 |
+
|
| 513 |
+
if step >= total_steps:
|
| 514 |
+
break
|
| 515 |
+
if stop["flag"]:
|
| 516 |
+
break
|
| 517 |
+
finally:
|
| 518 |
+
pbar.close()
|
| 519 |
+
ck = {
|
| 520 |
+
"model": model.state_dict(),
|
| 521 |
+
"optimizer": opt.state_dict(),
|
| 522 |
+
"ema": ema.to_state_dict(),
|
| 523 |
+
"step": step,
|
| 524 |
+
}
|
| 525 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 526 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 527 |
+
print("[FINAL] Final checkpoint saved.")
|
| 528 |
+
print("Exiting.")
|
| 529 |
+
|
| 530 |
+
# --------------------------
|
| 531 |
+
# CLI
|
| 532 |
+
# --------------------------
|
| 533 |
+
def parse_args():
|
| 534 |
+
p = argparse.ArgumentParser()
|
| 535 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 536 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 537 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 538 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 539 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 540 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 541 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 542 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 543 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 544 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 545 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 546 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 547 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 548 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 549 |
+
return p.parse_args()
|
| 550 |
+
|
| 551 |
+
if __name__ == "__main__":
|
| 552 |
+
args = parse_args()
|
| 553 |
+
train(
|
| 554 |
+
base_dir=args.base_dir,
|
| 555 |
+
train_list=args.train_list,
|
| 556 |
+
image_size=args.image_size,
|
| 557 |
+
batch_size=args.batch_size,
|
| 558 |
+
num_workers=args.num_workers,
|
| 559 |
+
timesteps=args.timesteps,
|
| 560 |
+
total_steps=args.total_steps,
|
| 561 |
+
lr=args.lr,
|
| 562 |
+
base_channels=args.base_channels,
|
| 563 |
+
save_every=args.save_every,
|
| 564 |
+
sample_every=args.sample_every,
|
| 565 |
+
ema_decay=args.ema_decay,
|
| 566 |
+
val_sample_steps=args.val_sample_steps,
|
| 567 |
+
sample_only=args.sample_only,
|
| 568 |
+
)
|
training_scripts/train_buildings_blur1.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_conditional_final.py — Robust conditional trainer (drop-in)
|
| 4 |
+
|
| 5 |
+
Changes made:
|
| 6 |
+
- ALWAYS skip loading optimizer state on resume (prints a clear message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 256
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 1e-4
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 1.0):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("RGB")
|
| 119 |
+
assert img.size == (self.image_size, self.image_size), f"Bad image size: {img.size}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 123 |
+
x0 = arr * 2.0 - 1.0
|
| 124 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 125 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 126 |
+
b = b_arr * 2.0 - 1.0
|
| 127 |
+
x0_t = torch.from_numpy(x0).permute(2, 0, 1).float()
|
| 128 |
+
b_t = torch.from_numpy(b).permute(2, 0, 1).float()
|
| 129 |
+
return x0_t, b_t
|
| 130 |
+
|
| 131 |
+
# --------------------------
|
| 132 |
+
# Model: UNet conditional
|
| 133 |
+
# --------------------------
|
| 134 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 135 |
+
def __init__(self, dim):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.dim = dim
|
| 138 |
+
def forward(self, t):
|
| 139 |
+
device = t.device
|
| 140 |
+
half = self.dim // 2
|
| 141 |
+
emb = math.log(10000) / (half - 1)
|
| 142 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 143 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 144 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 145 |
+
|
| 146 |
+
class ResBlock(nn.Module):
|
| 147 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 148 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 151 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 152 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 153 |
+
self.act = nn.SiLU()
|
| 154 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 155 |
+
def forward(self, x, t_emb):
|
| 156 |
+
h = self.act(self.conv1(x))
|
| 157 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 158 |
+
h = self.conv2(h)
|
| 159 |
+
return self.act(h + self.res_conv(x))
|
| 160 |
+
|
| 161 |
+
class UNetCond(nn.Module):
|
| 162 |
+
def __init__(self, in_ch=6, base=64, time_dim=256):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.time_mlp = nn.Sequential(
|
| 165 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 166 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 167 |
+
nn.SiLU(),
|
| 168 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 169 |
+
)
|
| 170 |
+
# small condition projection to strengthen conditioning at early layers
|
| 171 |
+
self.cond_proj = nn.Sequential(
|
| 172 |
+
nn.Conv2d(3, base, 3, padding=1),
|
| 173 |
+
nn.SiLU(),
|
| 174 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 178 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 179 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 180 |
+
self.pool = nn.AvgPool2d(2)
|
| 181 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 182 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 183 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 184 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 185 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 186 |
+
self.final = nn.Conv2d(base, 3, 1)
|
| 187 |
+
|
| 188 |
+
def forward(self, noisy_and_cond, t):
|
| 189 |
+
device = noisy_and_cond.device
|
| 190 |
+
t_emb = self.time_mlp(t)
|
| 191 |
+
|
| 192 |
+
noisy = noisy_and_cond[:, :3, ...]
|
| 193 |
+
cond = noisy_and_cond[:, 3:, ...]
|
| 194 |
+
cond_feat = self.cond_proj(cond)
|
| 195 |
+
|
| 196 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 197 |
+
try:
|
| 198 |
+
d1 = d1 + cond_feat
|
| 199 |
+
except Exception:
|
| 200 |
+
pass
|
| 201 |
+
|
| 202 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 203 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 204 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 205 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 206 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 207 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 208 |
+
return self.final(u1)
|
| 209 |
+
|
| 210 |
+
# --------------------------
|
| 211 |
+
# Diffusion utils
|
| 212 |
+
# --------------------------
|
| 213 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 214 |
+
return torch.linspace(start, end, timesteps)
|
| 215 |
+
|
| 216 |
+
class Diffusion(nn.Module):
|
| 217 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.timesteps = timesteps
|
| 220 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 221 |
+
alphas = 1.0 - betas
|
| 222 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 223 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 224 |
+
self.register_buffer("betas", betas)
|
| 225 |
+
self.register_buffer("alphas", alphas)
|
| 226 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 227 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 228 |
+
|
| 229 |
+
def q_sample(self, x0, t, noise=None):
|
| 230 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 231 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 232 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 233 |
+
|
| 234 |
+
def p_losses(self, model, x0, cond, t):
|
| 235 |
+
noise = torch.randn_like(x0)
|
| 236 |
+
x_t = self.q_sample(x0, t, noise)
|
| 237 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 238 |
+
noise_pred = model(inp, t)
|
| 239 |
+
return F.mse_loss(noise_pred, noise)
|
| 240 |
+
|
| 241 |
+
@torch.no_grad()
|
| 242 |
+
def p_sample(self, model, x_t, cond, t):
|
| 243 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 244 |
+
alphas_t = (1.0 - betas_t)
|
| 245 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 246 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 247 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 248 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 249 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 250 |
+
noise = torch.randn_like(x_t)
|
| 251 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 252 |
+
sigma = torch.sqrt(betas_t)
|
| 253 |
+
return mean + mask * sigma * noise
|
| 254 |
+
|
| 255 |
+
@torch.no_grad()
|
| 256 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 257 |
+
model.eval()
|
| 258 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 259 |
+
if num_steps is None: num_steps = start_t + 1
|
| 260 |
+
B = cond.shape[0]
|
| 261 |
+
x_t = torch.randn((B, 3, cond.shape[2], cond.shape[3]), device=device)
|
| 262 |
+
t_values = list(range(start_t, -1, -1))
|
| 263 |
+
if num_steps < len(t_values):
|
| 264 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 265 |
+
t_values = [t_values[i] for i in idxs]
|
| 266 |
+
for t_scalar in t_values:
|
| 267 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 268 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 269 |
+
return x_t
|
| 270 |
+
|
| 271 |
+
# --------------------------
|
| 272 |
+
# EMA helper
|
| 273 |
+
# --------------------------
|
| 274 |
+
class EMA:
|
| 275 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 276 |
+
self.decay = decay
|
| 277 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 278 |
+
|
| 279 |
+
def update(self, net: nn.Module):
|
| 280 |
+
for k, v in net.state_dict().items():
|
| 281 |
+
if k in self.shadow:
|
| 282 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 283 |
+
else:
|
| 284 |
+
self.shadow[k] = v.clone().detach()
|
| 285 |
+
|
| 286 |
+
def to_state_dict(self):
|
| 287 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 288 |
+
|
| 289 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 290 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 291 |
+
|
| 292 |
+
# --------------------------
|
| 293 |
+
# Image grid save
|
| 294 |
+
# --------------------------
|
| 295 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 296 |
+
tensor = tensor.detach().cpu()
|
| 297 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 298 |
+
arr = arr.astype(np.uint8)
|
| 299 |
+
B,C,H,W = arr.shape
|
| 300 |
+
ncol = math.ceil(B / nrow)
|
| 301 |
+
grid = Image.new("RGB", (W * ncol, H * nrow))
|
| 302 |
+
idx = 0
|
| 303 |
+
for r in range(nrow):
|
| 304 |
+
for c in range(ncol):
|
| 305 |
+
if idx >= B: break
|
| 306 |
+
img = Image.fromarray(arr[idx].transpose(1, 2, 0))
|
| 307 |
+
grid.paste(img, (c*W, r*H))
|
| 308 |
+
idx += 1
|
| 309 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 310 |
+
grid.save(path)
|
| 311 |
+
print(f"[SAVE] image saved: {path}")
|
| 312 |
+
|
| 313 |
+
# --------------------------
|
| 314 |
+
# Trainer (main)
|
| 315 |
+
# --------------------------
|
| 316 |
+
def train(
|
| 317 |
+
base_dir: str,
|
| 318 |
+
train_list: Optional[str] = None,
|
| 319 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 320 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 321 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 322 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 323 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 324 |
+
lr: float = DEFAULT_LR,
|
| 325 |
+
base_channels: int = 64,
|
| 326 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 327 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 328 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 329 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 330 |
+
sample_only: Optional[str] = None,
|
| 331 |
+
):
|
| 332 |
+
base = Path(base_dir)
|
| 333 |
+
train_list = train_list or (base / "train_list_buildings.txt")
|
| 334 |
+
ckpt_dir = base / "checkpoints_cond_blur1_buildings"
|
| 335 |
+
samples_dir = base / "samples_cond_blur1_buildings"
|
| 336 |
+
progress_dir = base / "progress_cond_blur1_buildings"
|
| 337 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 338 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 339 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 340 |
+
|
| 341 |
+
device = get_device()
|
| 342 |
+
print("Device:", device)
|
| 343 |
+
|
| 344 |
+
model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 345 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 346 |
+
|
| 347 |
+
if sample_only:
|
| 348 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 349 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 350 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 351 |
+
model.load_state_dict(sd, strict=False)
|
| 352 |
+
model_for_sampling = model
|
| 353 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 354 |
+
try:
|
| 355 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 356 |
+
tmp = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 357 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 358 |
+
model_for_sampling = tmp
|
| 359 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 360 |
+
except Exception as e:
|
| 361 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 362 |
+
conds = []
|
| 363 |
+
with open(train_list, "r") as f:
|
| 364 |
+
for i, line in enumerate(f):
|
| 365 |
+
if i >= 4: break
|
| 366 |
+
p = Path(line.strip())
|
| 367 |
+
im = Image.open(p).convert("RGB")
|
| 368 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=1.0))
|
| 369 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 370 |
+
conds.append(
|
| 371 |
+
torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).float()
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 375 |
+
with torch.no_grad():
|
| 376 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 377 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 378 |
+
save_grid(samples, out, nrow=2)
|
| 379 |
+
return
|
| 380 |
+
|
| 381 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=1.0)
|
| 382 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 383 |
+
|
| 384 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 385 |
+
ema = EMA(model, decay=ema_decay)
|
| 386 |
+
|
| 387 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 388 |
+
start_step = 0
|
| 389 |
+
if latest.exists():
|
| 390 |
+
print("Resuming from", latest)
|
| 391 |
+
data = safe_torch_load(latest, map_location=device)
|
| 392 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 393 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 394 |
+
try:
|
| 395 |
+
model.load_state_dict(raw_model_sd)
|
| 396 |
+
print("[LOAD] model loaded (strict=True).")
|
| 397 |
+
except Exception as e:
|
| 398 |
+
print("[LOAD] strict load failed:", e)
|
| 399 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 400 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 401 |
+
|
| 402 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 403 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 404 |
+
|
| 405 |
+
if isinstance(data, dict) and "ema" in data:
|
| 406 |
+
try:
|
| 407 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 408 |
+
model_keys = set(model.state_dict().keys())
|
| 409 |
+
ema_keys = set(ema_sd.keys())
|
| 410 |
+
if ema_keys == model_keys:
|
| 411 |
+
ema.load_state_dict(ema_sd)
|
| 412 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 413 |
+
else:
|
| 414 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
for g in opt.param_groups:
|
| 417 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 418 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 419 |
+
except Exception as e:
|
| 420 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 421 |
+
ema = EMA(model, decay=ema_decay)
|
| 422 |
+
else:
|
| 423 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 424 |
+
ema = EMA(model, decay=ema_decay)
|
| 425 |
+
for g in opt.param_groups:
|
| 426 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 427 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 428 |
+
|
| 429 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 430 |
+
print("Resumed at step:", start_step)
|
| 431 |
+
|
| 432 |
+
stop = {"flag": False}
|
| 433 |
+
def handler(sig, frame):
|
| 434 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 435 |
+
stop["flag"] = True
|
| 436 |
+
signal.signal(signal.SIGINT, handler)
|
| 437 |
+
signal.signal(signal.SIGTERM, handler)
|
| 438 |
+
|
| 439 |
+
model.train()
|
| 440 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 441 |
+
step = start_step
|
| 442 |
+
ema_loss = None
|
| 443 |
+
|
| 444 |
+
try:
|
| 445 |
+
while step < total_steps:
|
| 446 |
+
for x0, cond in dl:
|
| 447 |
+
if stop["flag"]:
|
| 448 |
+
break
|
| 449 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 450 |
+
bsz = x0.shape[0]
|
| 451 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 452 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 453 |
+
|
| 454 |
+
opt.zero_grad()
|
| 455 |
+
loss.backward()
|
| 456 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 457 |
+
opt.step()
|
| 458 |
+
ema.update(model)
|
| 459 |
+
|
| 460 |
+
step += 1
|
| 461 |
+
val = float(loss.item())
|
| 462 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 463 |
+
|
| 464 |
+
if step % 50 == 0:
|
| 465 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 466 |
+
|
| 467 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 468 |
+
pbar.update(1)
|
| 469 |
+
|
| 470 |
+
if step % sample_every == 0 or step == 1:
|
| 471 |
+
with torch.no_grad():
|
| 472 |
+
try:
|
| 473 |
+
sample_model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 474 |
+
try:
|
| 475 |
+
ema_sd = ema.to_state_dict()
|
| 476 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 477 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 478 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 479 |
+
except Exception:
|
| 480 |
+
try:
|
| 481 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 482 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 483 |
+
except Exception as e:
|
| 484 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 485 |
+
sample_model = model
|
| 486 |
+
except Exception as e:
|
| 487 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 488 |
+
sample_model = model
|
| 489 |
+
|
| 490 |
+
cond_batch = cond[:4].to(device)
|
| 491 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 492 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 493 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 494 |
+
save_grid(samples, s_path, nrow=2)
|
| 495 |
+
save_grid(samples, p_path, nrow=2)
|
| 496 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 497 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 498 |
+
|
| 499 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 500 |
+
ck = {
|
| 501 |
+
"model": model.state_dict(),
|
| 502 |
+
"optimizer": opt.state_dict(),
|
| 503 |
+
"ema": ema.to_state_dict(),
|
| 504 |
+
"step": step,
|
| 505 |
+
}
|
| 506 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 507 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 508 |
+
atomic_save(ck, p1)
|
| 509 |
+
atomic_save(ck, p2)
|
| 510 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 511 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 512 |
+
|
| 513 |
+
if step >= total_steps:
|
| 514 |
+
break
|
| 515 |
+
if stop["flag"]:
|
| 516 |
+
break
|
| 517 |
+
finally:
|
| 518 |
+
pbar.close()
|
| 519 |
+
ck = {
|
| 520 |
+
"model": model.state_dict(),
|
| 521 |
+
"optimizer": opt.state_dict(),
|
| 522 |
+
"ema": ema.to_state_dict(),
|
| 523 |
+
"step": step,
|
| 524 |
+
}
|
| 525 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 526 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 527 |
+
print("[FINAL] Final checkpoint saved.")
|
| 528 |
+
print("Exiting.")
|
| 529 |
+
|
| 530 |
+
# --------------------------
|
| 531 |
+
# CLI
|
| 532 |
+
# --------------------------
|
| 533 |
+
def parse_args():
|
| 534 |
+
p = argparse.ArgumentParser()
|
| 535 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 536 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 537 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 538 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 539 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 540 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 541 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 542 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 543 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 544 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 545 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 546 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 547 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 548 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 549 |
+
return p.parse_args()
|
| 550 |
+
|
| 551 |
+
if __name__ == "__main__":
|
| 552 |
+
args = parse_args()
|
| 553 |
+
train(
|
| 554 |
+
base_dir=args.base_dir,
|
| 555 |
+
train_list=args.train_list,
|
| 556 |
+
image_size=args.image_size,
|
| 557 |
+
batch_size=args.batch_size,
|
| 558 |
+
num_workers=args.num_workers,
|
| 559 |
+
timesteps=args.timesteps,
|
| 560 |
+
total_steps=args.total_steps,
|
| 561 |
+
lr=args.lr,
|
| 562 |
+
base_channels=args.base_channels,
|
| 563 |
+
save_every=args.save_every,
|
| 564 |
+
sample_every=args.sample_every,
|
| 565 |
+
ema_decay=args.ema_decay,
|
| 566 |
+
val_sample_steps=args.val_sample_steps,
|
| 567 |
+
sample_only=args.sample_only,
|
| 568 |
+
)
|
training_scripts/train_buildings_blur2.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_conditional_final.py — Robust conditional trainer (drop-in)
|
| 4 |
+
|
| 5 |
+
Changes made:
|
| 6 |
+
- ALWAYS skip loading optimizer state on resume (prints a clear message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 256
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 1e-4
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 2.0):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("RGB")
|
| 119 |
+
assert img.size == (self.image_size, self.image_size), f"Bad image size: {img.size}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 123 |
+
x0 = arr * 2.0 - 1.0
|
| 124 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 125 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 126 |
+
b = b_arr * 2.0 - 1.0
|
| 127 |
+
x0_t = torch.from_numpy(x0).permute(2, 0, 1).float()
|
| 128 |
+
b_t = torch.from_numpy(b).permute(2, 0, 1).float()
|
| 129 |
+
return x0_t, b_t
|
| 130 |
+
|
| 131 |
+
# --------------------------
|
| 132 |
+
# Model: UNet conditional
|
| 133 |
+
# --------------------------
|
| 134 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 135 |
+
def __init__(self, dim):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.dim = dim
|
| 138 |
+
def forward(self, t):
|
| 139 |
+
device = t.device
|
| 140 |
+
half = self.dim // 2
|
| 141 |
+
emb = math.log(10000) / (half - 1)
|
| 142 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 143 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 144 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 145 |
+
|
| 146 |
+
class ResBlock(nn.Module):
|
| 147 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 148 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 151 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 152 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 153 |
+
self.act = nn.SiLU()
|
| 154 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 155 |
+
def forward(self, x, t_emb):
|
| 156 |
+
h = self.act(self.conv1(x))
|
| 157 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 158 |
+
h = self.conv2(h)
|
| 159 |
+
return self.act(h + self.res_conv(x))
|
| 160 |
+
|
| 161 |
+
class UNetCond(nn.Module):
|
| 162 |
+
def __init__(self, in_ch=6, base=64, time_dim=256):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.time_mlp = nn.Sequential(
|
| 165 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 166 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 167 |
+
nn.SiLU(),
|
| 168 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 169 |
+
)
|
| 170 |
+
# small condition projection to strengthen conditioning at early layers
|
| 171 |
+
self.cond_proj = nn.Sequential(
|
| 172 |
+
nn.Conv2d(3, base, 3, padding=1),
|
| 173 |
+
nn.SiLU(),
|
| 174 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 178 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 179 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 180 |
+
self.pool = nn.AvgPool2d(2)
|
| 181 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 182 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 183 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 184 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 185 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 186 |
+
self.final = nn.Conv2d(base, 3, 1)
|
| 187 |
+
|
| 188 |
+
def forward(self, noisy_and_cond, t):
|
| 189 |
+
device = noisy_and_cond.device
|
| 190 |
+
t_emb = self.time_mlp(t)
|
| 191 |
+
|
| 192 |
+
noisy = noisy_and_cond[:, :3, ...]
|
| 193 |
+
cond = noisy_and_cond[:, 3:, ...]
|
| 194 |
+
cond_feat = self.cond_proj(cond)
|
| 195 |
+
|
| 196 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 197 |
+
try:
|
| 198 |
+
d1 = d1 + cond_feat
|
| 199 |
+
except Exception:
|
| 200 |
+
pass
|
| 201 |
+
|
| 202 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 203 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 204 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 205 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 206 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 207 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 208 |
+
return self.final(u1)
|
| 209 |
+
|
| 210 |
+
# --------------------------
|
| 211 |
+
# Diffusion utils
|
| 212 |
+
# --------------------------
|
| 213 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 214 |
+
return torch.linspace(start, end, timesteps)
|
| 215 |
+
|
| 216 |
+
class Diffusion(nn.Module):
|
| 217 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.timesteps = timesteps
|
| 220 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 221 |
+
alphas = 1.0 - betas
|
| 222 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 223 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 224 |
+
self.register_buffer("betas", betas)
|
| 225 |
+
self.register_buffer("alphas", alphas)
|
| 226 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 227 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 228 |
+
|
| 229 |
+
def q_sample(self, x0, t, noise=None):
|
| 230 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 231 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 232 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 233 |
+
|
| 234 |
+
def p_losses(self, model, x0, cond, t):
|
| 235 |
+
noise = torch.randn_like(x0)
|
| 236 |
+
x_t = self.q_sample(x0, t, noise)
|
| 237 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 238 |
+
noise_pred = model(inp, t)
|
| 239 |
+
return F.mse_loss(noise_pred, noise)
|
| 240 |
+
|
| 241 |
+
@torch.no_grad()
|
| 242 |
+
def p_sample(self, model, x_t, cond, t):
|
| 243 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 244 |
+
alphas_t = (1.0 - betas_t)
|
| 245 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 246 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 247 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 248 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 249 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 250 |
+
noise = torch.randn_like(x_t)
|
| 251 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 252 |
+
sigma = torch.sqrt(betas_t)
|
| 253 |
+
return mean + mask * sigma * noise
|
| 254 |
+
|
| 255 |
+
@torch.no_grad()
|
| 256 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 257 |
+
model.eval()
|
| 258 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 259 |
+
if num_steps is None: num_steps = start_t + 1
|
| 260 |
+
B = cond.shape[0]
|
| 261 |
+
x_t = torch.randn((B, 3, cond.shape[2], cond.shape[3]), device=device)
|
| 262 |
+
t_values = list(range(start_t, -1, -1))
|
| 263 |
+
if num_steps < len(t_values):
|
| 264 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 265 |
+
t_values = [t_values[i] for i in idxs]
|
| 266 |
+
for t_scalar in t_values:
|
| 267 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 268 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 269 |
+
return x_t
|
| 270 |
+
|
| 271 |
+
# --------------------------
|
| 272 |
+
# EMA helper
|
| 273 |
+
# --------------------------
|
| 274 |
+
class EMA:
|
| 275 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 276 |
+
self.decay = decay
|
| 277 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 278 |
+
|
| 279 |
+
def update(self, net: nn.Module):
|
| 280 |
+
for k, v in net.state_dict().items():
|
| 281 |
+
if k in self.shadow:
|
| 282 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 283 |
+
else:
|
| 284 |
+
self.shadow[k] = v.clone().detach()
|
| 285 |
+
|
| 286 |
+
def to_state_dict(self):
|
| 287 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 288 |
+
|
| 289 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 290 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 291 |
+
|
| 292 |
+
# --------------------------
|
| 293 |
+
# Image grid save
|
| 294 |
+
# --------------------------
|
| 295 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 296 |
+
tensor = tensor.detach().cpu()
|
| 297 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 298 |
+
arr = arr.astype(np.uint8)
|
| 299 |
+
B,C,H,W = arr.shape
|
| 300 |
+
ncol = math.ceil(B / nrow)
|
| 301 |
+
grid = Image.new("RGB", (W * ncol, H * nrow))
|
| 302 |
+
idx = 0
|
| 303 |
+
for r in range(nrow):
|
| 304 |
+
for c in range(ncol):
|
| 305 |
+
if idx >= B: break
|
| 306 |
+
img = Image.fromarray(arr[idx].transpose(1, 2, 0))
|
| 307 |
+
grid.paste(img, (c*W, r*H))
|
| 308 |
+
idx += 1
|
| 309 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 310 |
+
grid.save(path)
|
| 311 |
+
print(f"[SAVE] image saved: {path}")
|
| 312 |
+
|
| 313 |
+
# --------------------------
|
| 314 |
+
# Trainer (main)
|
| 315 |
+
# --------------------------
|
| 316 |
+
def train(
|
| 317 |
+
base_dir: str,
|
| 318 |
+
train_list: Optional[str] = None,
|
| 319 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 320 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 321 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 322 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 323 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 324 |
+
lr: float = DEFAULT_LR,
|
| 325 |
+
base_channels: int = 64,
|
| 326 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 327 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 328 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 329 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 330 |
+
sample_only: Optional[str] = None,
|
| 331 |
+
):
|
| 332 |
+
base = Path(base_dir)
|
| 333 |
+
train_list = train_list or (base / "train_list_buildings.txt")
|
| 334 |
+
ckpt_dir = base / "checkpoints_cond_blur2_buildings"
|
| 335 |
+
samples_dir = base / "samples_cond_blur2_buildings"
|
| 336 |
+
progress_dir = base / "progress_cond_blur2_buildings"
|
| 337 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 338 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 339 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 340 |
+
|
| 341 |
+
device = get_device()
|
| 342 |
+
print("Device:", device)
|
| 343 |
+
|
| 344 |
+
model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 345 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 346 |
+
|
| 347 |
+
if sample_only:
|
| 348 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 349 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 350 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 351 |
+
model.load_state_dict(sd, strict=False)
|
| 352 |
+
model_for_sampling = model
|
| 353 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 354 |
+
try:
|
| 355 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 356 |
+
tmp = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 357 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 358 |
+
model_for_sampling = tmp
|
| 359 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 360 |
+
except Exception as e:
|
| 361 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 362 |
+
conds = []
|
| 363 |
+
with open(train_list, "r") as f:
|
| 364 |
+
for i, line in enumerate(f):
|
| 365 |
+
if i >= 4: break
|
| 366 |
+
p = Path(line.strip())
|
| 367 |
+
im = Image.open(p).convert("RGB")
|
| 368 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=2.0))
|
| 369 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 370 |
+
conds.append(
|
| 371 |
+
torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).float()
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 375 |
+
with torch.no_grad():
|
| 376 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 377 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 378 |
+
save_grid(samples, out, nrow=2)
|
| 379 |
+
return
|
| 380 |
+
|
| 381 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=2.0)
|
| 382 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 383 |
+
|
| 384 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 385 |
+
ema = EMA(model, decay=ema_decay)
|
| 386 |
+
|
| 387 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 388 |
+
start_step = 0
|
| 389 |
+
if latest.exists():
|
| 390 |
+
print("Resuming from", latest)
|
| 391 |
+
data = safe_torch_load(latest, map_location=device)
|
| 392 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 393 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 394 |
+
try:
|
| 395 |
+
model.load_state_dict(raw_model_sd)
|
| 396 |
+
print("[LOAD] model loaded (strict=True).")
|
| 397 |
+
except Exception as e:
|
| 398 |
+
print("[LOAD] strict load failed:", e)
|
| 399 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 400 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 401 |
+
|
| 402 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 403 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 404 |
+
|
| 405 |
+
if isinstance(data, dict) and "ema" in data:
|
| 406 |
+
try:
|
| 407 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 408 |
+
model_keys = set(model.state_dict().keys())
|
| 409 |
+
ema_keys = set(ema_sd.keys())
|
| 410 |
+
if ema_keys == model_keys:
|
| 411 |
+
ema.load_state_dict(ema_sd)
|
| 412 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 413 |
+
else:
|
| 414 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
for g in opt.param_groups:
|
| 417 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 418 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 419 |
+
except Exception as e:
|
| 420 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 421 |
+
ema = EMA(model, decay=ema_decay)
|
| 422 |
+
else:
|
| 423 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 424 |
+
ema = EMA(model, decay=ema_decay)
|
| 425 |
+
for g in opt.param_groups:
|
| 426 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 427 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 428 |
+
|
| 429 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 430 |
+
print("Resumed at step:", start_step)
|
| 431 |
+
|
| 432 |
+
stop = {"flag": False}
|
| 433 |
+
def handler(sig, frame):
|
| 434 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 435 |
+
stop["flag"] = True
|
| 436 |
+
signal.signal(signal.SIGINT, handler)
|
| 437 |
+
signal.signal(signal.SIGTERM, handler)
|
| 438 |
+
|
| 439 |
+
model.train()
|
| 440 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 441 |
+
step = start_step
|
| 442 |
+
ema_loss = None
|
| 443 |
+
|
| 444 |
+
try:
|
| 445 |
+
while step < total_steps:
|
| 446 |
+
for x0, cond in dl:
|
| 447 |
+
if stop["flag"]:
|
| 448 |
+
break
|
| 449 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 450 |
+
bsz = x0.shape[0]
|
| 451 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 452 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 453 |
+
|
| 454 |
+
opt.zero_grad()
|
| 455 |
+
loss.backward()
|
| 456 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 457 |
+
opt.step()
|
| 458 |
+
ema.update(model)
|
| 459 |
+
|
| 460 |
+
step += 1
|
| 461 |
+
val = float(loss.item())
|
| 462 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 463 |
+
|
| 464 |
+
if step % 50 == 0:
|
| 465 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 466 |
+
|
| 467 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 468 |
+
pbar.update(1)
|
| 469 |
+
|
| 470 |
+
if step % sample_every == 0 or step == 1:
|
| 471 |
+
with torch.no_grad():
|
| 472 |
+
try:
|
| 473 |
+
sample_model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 474 |
+
try:
|
| 475 |
+
ema_sd = ema.to_state_dict()
|
| 476 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 477 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 478 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 479 |
+
except Exception:
|
| 480 |
+
try:
|
| 481 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 482 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 483 |
+
except Exception as e:
|
| 484 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 485 |
+
sample_model = model
|
| 486 |
+
except Exception as e:
|
| 487 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 488 |
+
sample_model = model
|
| 489 |
+
|
| 490 |
+
cond_batch = cond[:4].to(device)
|
| 491 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 492 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 493 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 494 |
+
save_grid(samples, s_path, nrow=2)
|
| 495 |
+
save_grid(samples, p_path, nrow=2)
|
| 496 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 497 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 498 |
+
|
| 499 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 500 |
+
ck = {
|
| 501 |
+
"model": model.state_dict(),
|
| 502 |
+
"optimizer": opt.state_dict(),
|
| 503 |
+
"ema": ema.to_state_dict(),
|
| 504 |
+
"step": step,
|
| 505 |
+
}
|
| 506 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 507 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 508 |
+
atomic_save(ck, p1)
|
| 509 |
+
atomic_save(ck, p2)
|
| 510 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 511 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 512 |
+
|
| 513 |
+
if step >= total_steps:
|
| 514 |
+
break
|
| 515 |
+
if stop["flag"]:
|
| 516 |
+
break
|
| 517 |
+
finally:
|
| 518 |
+
pbar.close()
|
| 519 |
+
ck = {
|
| 520 |
+
"model": model.state_dict(),
|
| 521 |
+
"optimizer": opt.state_dict(),
|
| 522 |
+
"ema": ema.to_state_dict(),
|
| 523 |
+
"step": step,
|
| 524 |
+
}
|
| 525 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 526 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 527 |
+
print("[FINAL] Final checkpoint saved.")
|
| 528 |
+
print("Exiting.")
|
| 529 |
+
|
| 530 |
+
# --------------------------
|
| 531 |
+
# CLI
|
| 532 |
+
# --------------------------
|
| 533 |
+
def parse_args():
|
| 534 |
+
p = argparse.ArgumentParser()
|
| 535 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 536 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 537 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 538 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 539 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 540 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 541 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 542 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 543 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 544 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 545 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 546 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 547 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 548 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 549 |
+
return p.parse_args()
|
| 550 |
+
|
| 551 |
+
if __name__ == "__main__":
|
| 552 |
+
args = parse_args()
|
| 553 |
+
train(
|
| 554 |
+
base_dir=args.base_dir,
|
| 555 |
+
train_list=args.train_list,
|
| 556 |
+
image_size=args.image_size,
|
| 557 |
+
batch_size=args.batch_size,
|
| 558 |
+
num_workers=args.num_workers,
|
| 559 |
+
timesteps=args.timesteps,
|
| 560 |
+
total_steps=args.total_steps,
|
| 561 |
+
lr=args.lr,
|
| 562 |
+
base_channels=args.base_channels,
|
| 563 |
+
save_every=args.save_every,
|
| 564 |
+
sample_every=args.sample_every,
|
| 565 |
+
ema_decay=args.ema_decay,
|
| 566 |
+
val_sample_steps=args.val_sample_steps,
|
| 567 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_conditional_final.py — Robust conditional trainer (drop-in)
|
| 4 |
+
|
| 5 |
+
Changes made:
|
| 6 |
+
- ALWAYS skip loading optimizer state on resume (prints a clear message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 256
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 1e-4
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 3.0):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("RGB")
|
| 119 |
+
assert img.size == (self.image_size, self.image_size), f"Bad image size: {img.size}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 123 |
+
x0 = arr * 2.0 - 1.0
|
| 124 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 125 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 126 |
+
b = b_arr * 2.0 - 1.0
|
| 127 |
+
x0_t = torch.from_numpy(x0).permute(2, 0, 1).float()
|
| 128 |
+
b_t = torch.from_numpy(b).permute(2, 0, 1).float()
|
| 129 |
+
return x0_t, b_t
|
| 130 |
+
|
| 131 |
+
# --------------------------
|
| 132 |
+
# Model: UNet conditional
|
| 133 |
+
# --------------------------
|
| 134 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 135 |
+
def __init__(self, dim):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.dim = dim
|
| 138 |
+
def forward(self, t):
|
| 139 |
+
device = t.device
|
| 140 |
+
half = self.dim // 2
|
| 141 |
+
emb = math.log(10000) / (half - 1)
|
| 142 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 143 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 144 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 145 |
+
|
| 146 |
+
class ResBlock(nn.Module):
|
| 147 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 148 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 151 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 152 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 153 |
+
self.act = nn.SiLU()
|
| 154 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 155 |
+
def forward(self, x, t_emb):
|
| 156 |
+
h = self.act(self.conv1(x))
|
| 157 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 158 |
+
h = self.conv2(h)
|
| 159 |
+
return self.act(h + self.res_conv(x))
|
| 160 |
+
|
| 161 |
+
class UNetCond(nn.Module):
|
| 162 |
+
def __init__(self, in_ch=6, base=64, time_dim=256):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.time_mlp = nn.Sequential(
|
| 165 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 166 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 167 |
+
nn.SiLU(),
|
| 168 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 169 |
+
)
|
| 170 |
+
# small condition projection to strengthen conditioning at early layers
|
| 171 |
+
self.cond_proj = nn.Sequential(
|
| 172 |
+
nn.Conv2d(3, base, 3, padding=1),
|
| 173 |
+
nn.SiLU(),
|
| 174 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 178 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 179 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 180 |
+
self.pool = nn.AvgPool2d(2)
|
| 181 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 182 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 183 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 184 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 185 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 186 |
+
self.final = nn.Conv2d(base, 3, 1)
|
| 187 |
+
|
| 188 |
+
def forward(self, noisy_and_cond, t):
|
| 189 |
+
device = noisy_and_cond.device
|
| 190 |
+
t_emb = self.time_mlp(t)
|
| 191 |
+
|
| 192 |
+
noisy = noisy_and_cond[:, :3, ...]
|
| 193 |
+
cond = noisy_and_cond[:, 3:, ...]
|
| 194 |
+
cond_feat = self.cond_proj(cond)
|
| 195 |
+
|
| 196 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 197 |
+
try:
|
| 198 |
+
d1 = d1 + cond_feat
|
| 199 |
+
except Exception:
|
| 200 |
+
pass
|
| 201 |
+
|
| 202 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 203 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 204 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 205 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 206 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 207 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 208 |
+
return self.final(u1)
|
| 209 |
+
|
| 210 |
+
# --------------------------
|
| 211 |
+
# Diffusion utils
|
| 212 |
+
# --------------------------
|
| 213 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 214 |
+
return torch.linspace(start, end, timesteps)
|
| 215 |
+
|
| 216 |
+
class Diffusion(nn.Module):
|
| 217 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.timesteps = timesteps
|
| 220 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 221 |
+
alphas = 1.0 - betas
|
| 222 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 223 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 224 |
+
self.register_buffer("betas", betas)
|
| 225 |
+
self.register_buffer("alphas", alphas)
|
| 226 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 227 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 228 |
+
|
| 229 |
+
def q_sample(self, x0, t, noise=None):
|
| 230 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 231 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 232 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 233 |
+
|
| 234 |
+
def p_losses(self, model, x0, cond, t):
|
| 235 |
+
noise = torch.randn_like(x0)
|
| 236 |
+
x_t = self.q_sample(x0, t, noise)
|
| 237 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 238 |
+
noise_pred = model(inp, t)
|
| 239 |
+
return F.mse_loss(noise_pred, noise)
|
| 240 |
+
|
| 241 |
+
@torch.no_grad()
|
| 242 |
+
def p_sample(self, model, x_t, cond, t):
|
| 243 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 244 |
+
alphas_t = (1.0 - betas_t)
|
| 245 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 246 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 247 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 248 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 249 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 250 |
+
noise = torch.randn_like(x_t)
|
| 251 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 252 |
+
sigma = torch.sqrt(betas_t)
|
| 253 |
+
return mean + mask * sigma * noise
|
| 254 |
+
|
| 255 |
+
@torch.no_grad()
|
| 256 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 257 |
+
model.eval()
|
| 258 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 259 |
+
if num_steps is None: num_steps = start_t + 1
|
| 260 |
+
B = cond.shape[0]
|
| 261 |
+
x_t = torch.randn((B, 3, cond.shape[2], cond.shape[3]), device=device)
|
| 262 |
+
t_values = list(range(start_t, -1, -1))
|
| 263 |
+
if num_steps < len(t_values):
|
| 264 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 265 |
+
t_values = [t_values[i] for i in idxs]
|
| 266 |
+
for t_scalar in t_values:
|
| 267 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 268 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 269 |
+
return x_t
|
| 270 |
+
|
| 271 |
+
# --------------------------
|
| 272 |
+
# EMA helper
|
| 273 |
+
# --------------------------
|
| 274 |
+
class EMA:
|
| 275 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 276 |
+
self.decay = decay
|
| 277 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 278 |
+
|
| 279 |
+
def update(self, net: nn.Module):
|
| 280 |
+
for k, v in net.state_dict().items():
|
| 281 |
+
if k in self.shadow:
|
| 282 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 283 |
+
else:
|
| 284 |
+
self.shadow[k] = v.clone().detach()
|
| 285 |
+
|
| 286 |
+
def to_state_dict(self):
|
| 287 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 288 |
+
|
| 289 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 290 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 291 |
+
|
| 292 |
+
# --------------------------
|
| 293 |
+
# Image grid save
|
| 294 |
+
# --------------------------
|
| 295 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 296 |
+
tensor = tensor.detach().cpu()
|
| 297 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 298 |
+
arr = arr.astype(np.uint8)
|
| 299 |
+
B,C,H,W = arr.shape
|
| 300 |
+
ncol = math.ceil(B / nrow)
|
| 301 |
+
grid = Image.new("RGB", (W * ncol, H * nrow))
|
| 302 |
+
idx = 0
|
| 303 |
+
for r in range(nrow):
|
| 304 |
+
for c in range(ncol):
|
| 305 |
+
if idx >= B: break
|
| 306 |
+
img = Image.fromarray(arr[idx].transpose(1, 2, 0))
|
| 307 |
+
grid.paste(img, (c*W, r*H))
|
| 308 |
+
idx += 1
|
| 309 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 310 |
+
grid.save(path)
|
| 311 |
+
print(f"[SAVE] image saved: {path}")
|
| 312 |
+
|
| 313 |
+
# --------------------------
|
| 314 |
+
# Trainer (main)
|
| 315 |
+
# --------------------------
|
| 316 |
+
def train(
|
| 317 |
+
base_dir: str,
|
| 318 |
+
train_list: Optional[str] = None,
|
| 319 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 320 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 321 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 322 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 323 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 324 |
+
lr: float = DEFAULT_LR,
|
| 325 |
+
base_channels: int = 64,
|
| 326 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 327 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 328 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 329 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 330 |
+
sample_only: Optional[str] = None,
|
| 331 |
+
):
|
| 332 |
+
base = Path(base_dir)
|
| 333 |
+
train_list = train_list or (base / "train_list_buildings.txt")
|
| 334 |
+
ckpt_dir = base / "checkpoints_cond_blur3_buildings"
|
| 335 |
+
samples_dir = base / "samples_cond_blur3_buildings"
|
| 336 |
+
progress_dir = base / "progress_cond_blur3_buildings"
|
| 337 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 338 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 339 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 340 |
+
|
| 341 |
+
device = get_device()
|
| 342 |
+
print("Device:", device)
|
| 343 |
+
|
| 344 |
+
model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 345 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 346 |
+
|
| 347 |
+
if sample_only:
|
| 348 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 349 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 350 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 351 |
+
model.load_state_dict(sd, strict=False)
|
| 352 |
+
model_for_sampling = model
|
| 353 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 354 |
+
try:
|
| 355 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 356 |
+
tmp = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 357 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 358 |
+
model_for_sampling = tmp
|
| 359 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 360 |
+
except Exception as e:
|
| 361 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 362 |
+
conds = []
|
| 363 |
+
with open(train_list, "r") as f:
|
| 364 |
+
for i, line in enumerate(f):
|
| 365 |
+
if i >= 4: break
|
| 366 |
+
p = Path(line.strip())
|
| 367 |
+
im = Image.open(p).convert("RGB")
|
| 368 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=3.0))
|
| 369 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 370 |
+
conds.append(
|
| 371 |
+
torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).float()
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 375 |
+
with torch.no_grad():
|
| 376 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 377 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 378 |
+
save_grid(samples, out, nrow=2)
|
| 379 |
+
return
|
| 380 |
+
|
| 381 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=3.0)
|
| 382 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 383 |
+
|
| 384 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 385 |
+
ema = EMA(model, decay=ema_decay)
|
| 386 |
+
|
| 387 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 388 |
+
start_step = 0
|
| 389 |
+
if latest.exists():
|
| 390 |
+
print("Resuming from", latest)
|
| 391 |
+
data = safe_torch_load(latest, map_location=device)
|
| 392 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 393 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 394 |
+
try:
|
| 395 |
+
model.load_state_dict(raw_model_sd)
|
| 396 |
+
print("[LOAD] model loaded (strict=True).")
|
| 397 |
+
except Exception as e:
|
| 398 |
+
print("[LOAD] strict load failed:", e)
|
| 399 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 400 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 401 |
+
|
| 402 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 403 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 404 |
+
|
| 405 |
+
if isinstance(data, dict) and "ema" in data:
|
| 406 |
+
try:
|
| 407 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 408 |
+
model_keys = set(model.state_dict().keys())
|
| 409 |
+
ema_keys = set(ema_sd.keys())
|
| 410 |
+
if ema_keys == model_keys:
|
| 411 |
+
ema.load_state_dict(ema_sd)
|
| 412 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 413 |
+
else:
|
| 414 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
for g in opt.param_groups:
|
| 417 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 418 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 419 |
+
except Exception as e:
|
| 420 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 421 |
+
ema = EMA(model, decay=ema_decay)
|
| 422 |
+
else:
|
| 423 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 424 |
+
ema = EMA(model, decay=ema_decay)
|
| 425 |
+
for g in opt.param_groups:
|
| 426 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 427 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 428 |
+
|
| 429 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 430 |
+
print("Resumed at step:", start_step)
|
| 431 |
+
|
| 432 |
+
stop = {"flag": False}
|
| 433 |
+
def handler(sig, frame):
|
| 434 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 435 |
+
stop["flag"] = True
|
| 436 |
+
signal.signal(signal.SIGINT, handler)
|
| 437 |
+
signal.signal(signal.SIGTERM, handler)
|
| 438 |
+
|
| 439 |
+
model.train()
|
| 440 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 441 |
+
step = start_step
|
| 442 |
+
ema_loss = None
|
| 443 |
+
|
| 444 |
+
try:
|
| 445 |
+
while step < total_steps:
|
| 446 |
+
for x0, cond in dl:
|
| 447 |
+
if stop["flag"]:
|
| 448 |
+
break
|
| 449 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 450 |
+
bsz = x0.shape[0]
|
| 451 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 452 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 453 |
+
|
| 454 |
+
opt.zero_grad()
|
| 455 |
+
loss.backward()
|
| 456 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 457 |
+
opt.step()
|
| 458 |
+
ema.update(model)
|
| 459 |
+
|
| 460 |
+
step += 1
|
| 461 |
+
val = float(loss.item())
|
| 462 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 463 |
+
|
| 464 |
+
if step % 50 == 0:
|
| 465 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 466 |
+
|
| 467 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 468 |
+
pbar.update(1)
|
| 469 |
+
|
| 470 |
+
if step % sample_every == 0 or step == 1:
|
| 471 |
+
with torch.no_grad():
|
| 472 |
+
try:
|
| 473 |
+
sample_model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 474 |
+
try:
|
| 475 |
+
ema_sd = ema.to_state_dict()
|
| 476 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 477 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 478 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 479 |
+
except Exception:
|
| 480 |
+
try:
|
| 481 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 482 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 483 |
+
except Exception as e:
|
| 484 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 485 |
+
sample_model = model
|
| 486 |
+
except Exception as e:
|
| 487 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 488 |
+
sample_model = model
|
| 489 |
+
|
| 490 |
+
cond_batch = cond[:4].to(device)
|
| 491 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 492 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 493 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 494 |
+
save_grid(samples, s_path, nrow=2)
|
| 495 |
+
save_grid(samples, p_path, nrow=2)
|
| 496 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 497 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 498 |
+
|
| 499 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 500 |
+
ck = {
|
| 501 |
+
"model": model.state_dict(),
|
| 502 |
+
"optimizer": opt.state_dict(),
|
| 503 |
+
"ema": ema.to_state_dict(),
|
| 504 |
+
"step": step,
|
| 505 |
+
}
|
| 506 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 507 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 508 |
+
atomic_save(ck, p1)
|
| 509 |
+
atomic_save(ck, p2)
|
| 510 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 511 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 512 |
+
|
| 513 |
+
if step >= total_steps:
|
| 514 |
+
break
|
| 515 |
+
if stop["flag"]:
|
| 516 |
+
break
|
| 517 |
+
finally:
|
| 518 |
+
pbar.close()
|
| 519 |
+
ck = {
|
| 520 |
+
"model": model.state_dict(),
|
| 521 |
+
"optimizer": opt.state_dict(),
|
| 522 |
+
"ema": ema.to_state_dict(),
|
| 523 |
+
"step": step,
|
| 524 |
+
}
|
| 525 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 526 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 527 |
+
print("[FINAL] Final checkpoint saved.")
|
| 528 |
+
print("Exiting.")
|
| 529 |
+
|
| 530 |
+
# --------------------------
|
| 531 |
+
# CLI
|
| 532 |
+
# --------------------------
|
| 533 |
+
def parse_args():
|
| 534 |
+
p = argparse.ArgumentParser()
|
| 535 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 536 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 537 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 538 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 539 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 540 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 541 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 542 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 543 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 544 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 545 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 546 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 547 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 548 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 549 |
+
return p.parse_args()
|
| 550 |
+
|
| 551 |
+
if __name__ == "__main__":
|
| 552 |
+
args = parse_args()
|
| 553 |
+
train(
|
| 554 |
+
base_dir=args.base_dir,
|
| 555 |
+
train_list=args.train_list,
|
| 556 |
+
image_size=args.image_size,
|
| 557 |
+
batch_size=args.batch_size,
|
| 558 |
+
num_workers=args.num_workers,
|
| 559 |
+
timesteps=args.timesteps,
|
| 560 |
+
total_steps=args.total_steps,
|
| 561 |
+
lr=args.lr,
|
| 562 |
+
base_channels=args.base_channels,
|
| 563 |
+
save_every=args.save_every,
|
| 564 |
+
sample_every=args.sample_every,
|
| 565 |
+
ema_decay=args.ema_decay,
|
| 566 |
+
val_sample_steps=args.val_sample_steps,
|
| 567 |
+
sample_only=args.sample_only,
|
| 568 |
+
)
|
training_scripts/train_celebA_blur1.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_conditional_final.py — Robust conditional trainer (drop-in)
|
| 4 |
+
|
| 5 |
+
Changes made:
|
| 6 |
+
- ALWAYS skip loading optimizer state on resume (prints a clear message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 176
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 1e-4
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 1.0):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("RGB")
|
| 119 |
+
assert img.size == (self.image_size, self.image_size), f"Bad image size: {img.size}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 123 |
+
x0 = arr * 2.0 - 1.0
|
| 124 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 125 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 126 |
+
b = b_arr * 2.0 - 1.0
|
| 127 |
+
x0_t = torch.from_numpy(x0).permute(2, 0, 1).float()
|
| 128 |
+
b_t = torch.from_numpy(b).permute(2, 0, 1).float()
|
| 129 |
+
return x0_t, b_t
|
| 130 |
+
|
| 131 |
+
# --------------------------
|
| 132 |
+
# Model: UNet conditional
|
| 133 |
+
# --------------------------
|
| 134 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 135 |
+
def __init__(self, dim):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.dim = dim
|
| 138 |
+
def forward(self, t):
|
| 139 |
+
device = t.device
|
| 140 |
+
half = self.dim // 2
|
| 141 |
+
emb = math.log(10000) / (half - 1)
|
| 142 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 143 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 144 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 145 |
+
|
| 146 |
+
class ResBlock(nn.Module):
|
| 147 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 148 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 151 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 152 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 153 |
+
self.act = nn.SiLU()
|
| 154 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 155 |
+
def forward(self, x, t_emb):
|
| 156 |
+
h = self.act(self.conv1(x))
|
| 157 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 158 |
+
h = self.conv2(h)
|
| 159 |
+
return self.act(h + self.res_conv(x))
|
| 160 |
+
|
| 161 |
+
class UNetCond(nn.Module):
|
| 162 |
+
def __init__(self, in_ch=6, base=64, time_dim=256):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.time_mlp = nn.Sequential(
|
| 165 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 166 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 167 |
+
nn.SiLU(),
|
| 168 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 169 |
+
)
|
| 170 |
+
# small condition projection to strengthen conditioning at early layers
|
| 171 |
+
self.cond_proj = nn.Sequential(
|
| 172 |
+
nn.Conv2d(3, base, 3, padding=1),
|
| 173 |
+
nn.SiLU(),
|
| 174 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 178 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 179 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 180 |
+
self.pool = nn.AvgPool2d(2)
|
| 181 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 182 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 183 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 184 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 185 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 186 |
+
self.final = nn.Conv2d(base, 3, 1)
|
| 187 |
+
|
| 188 |
+
def forward(self, noisy_and_cond, t):
|
| 189 |
+
device = noisy_and_cond.device
|
| 190 |
+
t_emb = self.time_mlp(t)
|
| 191 |
+
|
| 192 |
+
noisy = noisy_and_cond[:, :3, ...]
|
| 193 |
+
cond = noisy_and_cond[:, 3:, ...]
|
| 194 |
+
cond_feat = self.cond_proj(cond)
|
| 195 |
+
|
| 196 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 197 |
+
try:
|
| 198 |
+
d1 = d1 + cond_feat
|
| 199 |
+
except Exception:
|
| 200 |
+
pass
|
| 201 |
+
|
| 202 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 203 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 204 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 205 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 206 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 207 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 208 |
+
return self.final(u1)
|
| 209 |
+
|
| 210 |
+
# --------------------------
|
| 211 |
+
# Diffusion utils
|
| 212 |
+
# --------------------------
|
| 213 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 214 |
+
return torch.linspace(start, end, timesteps)
|
| 215 |
+
|
| 216 |
+
class Diffusion(nn.Module):
|
| 217 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.timesteps = timesteps
|
| 220 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 221 |
+
alphas = 1.0 - betas
|
| 222 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 223 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 224 |
+
self.register_buffer("betas", betas)
|
| 225 |
+
self.register_buffer("alphas", alphas)
|
| 226 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 227 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 228 |
+
|
| 229 |
+
def q_sample(self, x0, t, noise=None):
|
| 230 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 231 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 232 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 233 |
+
|
| 234 |
+
def p_losses(self, model, x0, cond, t):
|
| 235 |
+
noise = torch.randn_like(x0)
|
| 236 |
+
x_t = self.q_sample(x0, t, noise)
|
| 237 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 238 |
+
noise_pred = model(inp, t)
|
| 239 |
+
return F.mse_loss(noise_pred, noise)
|
| 240 |
+
|
| 241 |
+
@torch.no_grad()
|
| 242 |
+
def p_sample(self, model, x_t, cond, t):
|
| 243 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 244 |
+
alphas_t = (1.0 - betas_t)
|
| 245 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 246 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 247 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 248 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 249 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 250 |
+
noise = torch.randn_like(x_t)
|
| 251 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 252 |
+
sigma = torch.sqrt(betas_t)
|
| 253 |
+
return mean + mask * sigma * noise
|
| 254 |
+
|
| 255 |
+
@torch.no_grad()
|
| 256 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 257 |
+
model.eval()
|
| 258 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 259 |
+
if num_steps is None: num_steps = start_t + 1
|
| 260 |
+
B = cond.shape[0]
|
| 261 |
+
x_t = torch.randn((B, 3, cond.shape[2], cond.shape[3]), device=device)
|
| 262 |
+
t_values = list(range(start_t, -1, -1))
|
| 263 |
+
if num_steps < len(t_values):
|
| 264 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 265 |
+
t_values = [t_values[i] for i in idxs]
|
| 266 |
+
for t_scalar in t_values:
|
| 267 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 268 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 269 |
+
return x_t
|
| 270 |
+
|
| 271 |
+
# --------------------------
|
| 272 |
+
# EMA helper
|
| 273 |
+
# --------------------------
|
| 274 |
+
class EMA:
|
| 275 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 276 |
+
self.decay = decay
|
| 277 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 278 |
+
|
| 279 |
+
def update(self, net: nn.Module):
|
| 280 |
+
for k, v in net.state_dict().items():
|
| 281 |
+
if k in self.shadow:
|
| 282 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 283 |
+
else:
|
| 284 |
+
self.shadow[k] = v.clone().detach()
|
| 285 |
+
|
| 286 |
+
def to_state_dict(self):
|
| 287 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 288 |
+
|
| 289 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 290 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 291 |
+
|
| 292 |
+
# --------------------------
|
| 293 |
+
# Image grid save
|
| 294 |
+
# --------------------------
|
| 295 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 296 |
+
tensor = tensor.detach().cpu()
|
| 297 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 298 |
+
arr = arr.astype(np.uint8)
|
| 299 |
+
B,C,H,W = arr.shape
|
| 300 |
+
ncol = math.ceil(B / nrow)
|
| 301 |
+
grid = Image.new("RGB", (W * ncol, H * nrow))
|
| 302 |
+
idx = 0
|
| 303 |
+
for r in range(nrow):
|
| 304 |
+
for c in range(ncol):
|
| 305 |
+
if idx >= B: break
|
| 306 |
+
img = Image.fromarray(arr[idx].transpose(1, 2, 0))
|
| 307 |
+
grid.paste(img, (c*W, r*H))
|
| 308 |
+
idx += 1
|
| 309 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 310 |
+
grid.save(path)
|
| 311 |
+
print(f"[SAVE] image saved: {path}")
|
| 312 |
+
|
| 313 |
+
# --------------------------
|
| 314 |
+
# Trainer (main)
|
| 315 |
+
# --------------------------
|
| 316 |
+
def train(
|
| 317 |
+
base_dir: str,
|
| 318 |
+
train_list: Optional[str] = None,
|
| 319 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 320 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 321 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 322 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 323 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 324 |
+
lr: float = DEFAULT_LR,
|
| 325 |
+
base_channels: int = 64,
|
| 326 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 327 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 328 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 329 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 330 |
+
sample_only: Optional[str] = None,
|
| 331 |
+
):
|
| 332 |
+
base = Path(base_dir)
|
| 333 |
+
train_list = train_list or (base / "train_list_celebA.txt")
|
| 334 |
+
ckpt_dir = base / "checkpoints_cond_blur1_rgb"
|
| 335 |
+
samples_dir = base / "samples_cond_blur1_rgb"
|
| 336 |
+
progress_dir = base / "progress_cond_blur1_rgb"
|
| 337 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 338 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 339 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 340 |
+
|
| 341 |
+
device = get_device()
|
| 342 |
+
print("Device:", device)
|
| 343 |
+
|
| 344 |
+
model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 345 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 346 |
+
|
| 347 |
+
if sample_only:
|
| 348 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 349 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 350 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 351 |
+
model.load_state_dict(sd, strict=False)
|
| 352 |
+
model_for_sampling = model
|
| 353 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 354 |
+
try:
|
| 355 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 356 |
+
tmp = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 357 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 358 |
+
model_for_sampling = tmp
|
| 359 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 360 |
+
except Exception as e:
|
| 361 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 362 |
+
conds = []
|
| 363 |
+
with open(train_list, "r") as f:
|
| 364 |
+
for i, line in enumerate(f):
|
| 365 |
+
if i >= 4: break
|
| 366 |
+
p = Path(line.strip())
|
| 367 |
+
im = Image.open(p).convert("RGB")
|
| 368 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=1.0))
|
| 369 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 370 |
+
conds.append(
|
| 371 |
+
torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).float()
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 375 |
+
with torch.no_grad():
|
| 376 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 377 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 378 |
+
save_grid(samples, out, nrow=2)
|
| 379 |
+
return
|
| 380 |
+
|
| 381 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=1.0)
|
| 382 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 383 |
+
|
| 384 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 385 |
+
ema = EMA(model, decay=ema_decay)
|
| 386 |
+
|
| 387 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 388 |
+
start_step = 0
|
| 389 |
+
if latest.exists():
|
| 390 |
+
print("Resuming from", latest)
|
| 391 |
+
data = safe_torch_load(latest, map_location=device)
|
| 392 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 393 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 394 |
+
try:
|
| 395 |
+
model.load_state_dict(raw_model_sd)
|
| 396 |
+
print("[LOAD] model loaded (strict=True).")
|
| 397 |
+
except Exception as e:
|
| 398 |
+
print("[LOAD] strict load failed:", e)
|
| 399 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 400 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 401 |
+
|
| 402 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 403 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 404 |
+
|
| 405 |
+
if isinstance(data, dict) and "ema" in data:
|
| 406 |
+
try:
|
| 407 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 408 |
+
model_keys = set(model.state_dict().keys())
|
| 409 |
+
ema_keys = set(ema_sd.keys())
|
| 410 |
+
if ema_keys == model_keys:
|
| 411 |
+
ema.load_state_dict(ema_sd)
|
| 412 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 413 |
+
else:
|
| 414 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
for g in opt.param_groups:
|
| 417 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 418 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 419 |
+
except Exception as e:
|
| 420 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 421 |
+
ema = EMA(model, decay=ema_decay)
|
| 422 |
+
else:
|
| 423 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 424 |
+
ema = EMA(model, decay=ema_decay)
|
| 425 |
+
for g in opt.param_groups:
|
| 426 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 427 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 428 |
+
|
| 429 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 430 |
+
print("Resumed at step:", start_step)
|
| 431 |
+
|
| 432 |
+
stop = {"flag": False}
|
| 433 |
+
def handler(sig, frame):
|
| 434 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 435 |
+
stop["flag"] = True
|
| 436 |
+
signal.signal(signal.SIGINT, handler)
|
| 437 |
+
signal.signal(signal.SIGTERM, handler)
|
| 438 |
+
|
| 439 |
+
model.train()
|
| 440 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 441 |
+
step = start_step
|
| 442 |
+
ema_loss = None
|
| 443 |
+
|
| 444 |
+
try:
|
| 445 |
+
while step < total_steps:
|
| 446 |
+
for x0, cond in dl:
|
| 447 |
+
if stop["flag"]:
|
| 448 |
+
break
|
| 449 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 450 |
+
bsz = x0.shape[0]
|
| 451 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 452 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 453 |
+
|
| 454 |
+
opt.zero_grad()
|
| 455 |
+
loss.backward()
|
| 456 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 457 |
+
opt.step()
|
| 458 |
+
ema.update(model)
|
| 459 |
+
|
| 460 |
+
step += 1
|
| 461 |
+
val = float(loss.item())
|
| 462 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 463 |
+
|
| 464 |
+
if step % 50 == 0:
|
| 465 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 466 |
+
|
| 467 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 468 |
+
pbar.update(1)
|
| 469 |
+
|
| 470 |
+
if step % sample_every == 0 or step == 1:
|
| 471 |
+
with torch.no_grad():
|
| 472 |
+
try:
|
| 473 |
+
sample_model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 474 |
+
try:
|
| 475 |
+
ema_sd = ema.to_state_dict()
|
| 476 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 477 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 478 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 479 |
+
except Exception:
|
| 480 |
+
try:
|
| 481 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 482 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 483 |
+
except Exception as e:
|
| 484 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 485 |
+
sample_model = model
|
| 486 |
+
except Exception as e:
|
| 487 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 488 |
+
sample_model = model
|
| 489 |
+
|
| 490 |
+
cond_batch = cond[:4].to(device)
|
| 491 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 492 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 493 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 494 |
+
save_grid(samples, s_path, nrow=2)
|
| 495 |
+
save_grid(samples, p_path, nrow=2)
|
| 496 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 497 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 498 |
+
|
| 499 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 500 |
+
ck = {
|
| 501 |
+
"model": model.state_dict(),
|
| 502 |
+
"optimizer": opt.state_dict(),
|
| 503 |
+
"ema": ema.to_state_dict(),
|
| 504 |
+
"step": step,
|
| 505 |
+
}
|
| 506 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 507 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 508 |
+
atomic_save(ck, p1)
|
| 509 |
+
atomic_save(ck, p2)
|
| 510 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 511 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 512 |
+
|
| 513 |
+
if step >= total_steps:
|
| 514 |
+
break
|
| 515 |
+
if stop["flag"]:
|
| 516 |
+
break
|
| 517 |
+
finally:
|
| 518 |
+
pbar.close()
|
| 519 |
+
ck = {
|
| 520 |
+
"model": model.state_dict(),
|
| 521 |
+
"optimizer": opt.state_dict(),
|
| 522 |
+
"ema": ema.to_state_dict(),
|
| 523 |
+
"step": step,
|
| 524 |
+
}
|
| 525 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 526 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 527 |
+
print("[FINAL] Final checkpoint saved.")
|
| 528 |
+
print("Exiting.")
|
| 529 |
+
|
| 530 |
+
# --------------------------
|
| 531 |
+
# CLI
|
| 532 |
+
# --------------------------
|
| 533 |
+
def parse_args():
|
| 534 |
+
p = argparse.ArgumentParser()
|
| 535 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 536 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 537 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 538 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 539 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 540 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 541 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 542 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 543 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 544 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 545 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 546 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 547 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 548 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 549 |
+
return p.parse_args()
|
| 550 |
+
|
| 551 |
+
if __name__ == "__main__":
|
| 552 |
+
args = parse_args()
|
| 553 |
+
train(
|
| 554 |
+
base_dir=args.base_dir,
|
| 555 |
+
train_list=args.train_list,
|
| 556 |
+
image_size=args.image_size,
|
| 557 |
+
batch_size=args.batch_size,
|
| 558 |
+
num_workers=args.num_workers,
|
| 559 |
+
timesteps=args.timesteps,
|
| 560 |
+
total_steps=args.total_steps,
|
| 561 |
+
lr=args.lr,
|
| 562 |
+
base_channels=args.base_channels,
|
| 563 |
+
save_every=args.save_every,
|
| 564 |
+
sample_every=args.sample_every,
|
| 565 |
+
ema_decay=args.ema_decay,
|
| 566 |
+
val_sample_steps=args.val_sample_steps,
|
| 567 |
+
sample_only=args.sample_only,
|
| 568 |
+
)
|
training_scripts/train_celebA_blur2.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_conditional_final.py — Robust conditional trainer (drop-in)
|
| 4 |
+
|
| 5 |
+
Changes made:
|
| 6 |
+
- ALWAYS skip loading optimizer state on resume (prints a clear message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 176
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 5e-5
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 2.0):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("RGB")
|
| 119 |
+
assert img.size == (self.image_size, self.image_size), f"Bad image size: {img.size}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 123 |
+
x0 = arr * 2.0 - 1.0
|
| 124 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 125 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 126 |
+
b = b_arr * 2.0 - 1.0
|
| 127 |
+
x0_t = torch.from_numpy(x0).permute(2, 0, 1).float()
|
| 128 |
+
b_t = torch.from_numpy(b).permute(2, 0, 1).float()
|
| 129 |
+
return x0_t, b_t
|
| 130 |
+
|
| 131 |
+
# --------------------------
|
| 132 |
+
# Model: UNet conditional
|
| 133 |
+
# --------------------------
|
| 134 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 135 |
+
def __init__(self, dim):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.dim = dim
|
| 138 |
+
def forward(self, t):
|
| 139 |
+
device = t.device
|
| 140 |
+
half = self.dim // 2
|
| 141 |
+
emb = math.log(10000) / (half - 1)
|
| 142 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 143 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 144 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 145 |
+
|
| 146 |
+
class ResBlock(nn.Module):
|
| 147 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 148 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 151 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 152 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 153 |
+
self.act = nn.SiLU()
|
| 154 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 155 |
+
def forward(self, x, t_emb):
|
| 156 |
+
h = self.act(self.conv1(x))
|
| 157 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 158 |
+
h = self.conv2(h)
|
| 159 |
+
return self.act(h + self.res_conv(x))
|
| 160 |
+
|
| 161 |
+
class UNetCond(nn.Module):
|
| 162 |
+
def __init__(self, in_ch=6, base=64, time_dim=256):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.time_mlp = nn.Sequential(
|
| 165 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 166 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 167 |
+
nn.SiLU(),
|
| 168 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 169 |
+
)
|
| 170 |
+
# small condition projection to strengthen conditioning at early layers
|
| 171 |
+
self.cond_proj = nn.Sequential(
|
| 172 |
+
nn.Conv2d(3, base, 3, padding=1),
|
| 173 |
+
nn.SiLU(),
|
| 174 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 178 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 179 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 180 |
+
self.pool = nn.AvgPool2d(2)
|
| 181 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 182 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 183 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 184 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 185 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 186 |
+
self.final = nn.Conv2d(base, 3, 1)
|
| 187 |
+
|
| 188 |
+
def forward(self, noisy_and_cond, t):
|
| 189 |
+
device = noisy_and_cond.device
|
| 190 |
+
t_emb = self.time_mlp(t)
|
| 191 |
+
|
| 192 |
+
noisy = noisy_and_cond[:, :3, ...]
|
| 193 |
+
cond = noisy_and_cond[:, 3:, ...]
|
| 194 |
+
cond_feat = self.cond_proj(cond)
|
| 195 |
+
|
| 196 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 197 |
+
try:
|
| 198 |
+
d1 = d1 + 0.5 * cond_feat
|
| 199 |
+
except Exception:
|
| 200 |
+
pass
|
| 201 |
+
|
| 202 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 203 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 204 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 205 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 206 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 207 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 208 |
+
return self.final(u1)
|
| 209 |
+
|
| 210 |
+
# --------------------------
|
| 211 |
+
# Diffusion utils
|
| 212 |
+
# --------------------------
|
| 213 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 214 |
+
return torch.linspace(start, end, timesteps)
|
| 215 |
+
|
| 216 |
+
class Diffusion(nn.Module):
|
| 217 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.timesteps = timesteps
|
| 220 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 221 |
+
alphas = 1.0 - betas
|
| 222 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 223 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 224 |
+
self.register_buffer("betas", betas)
|
| 225 |
+
self.register_buffer("alphas", alphas)
|
| 226 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 227 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 228 |
+
|
| 229 |
+
def q_sample(self, x0, t, noise=None):
|
| 230 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 231 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 232 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 233 |
+
|
| 234 |
+
def p_losses(self, model, x0, cond, t):
|
| 235 |
+
noise = torch.randn_like(x0)
|
| 236 |
+
x_t = self.q_sample(x0, t, noise)
|
| 237 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 238 |
+
noise_pred = model(inp, t)
|
| 239 |
+
return F.mse_loss(noise_pred, noise)
|
| 240 |
+
|
| 241 |
+
@torch.no_grad()
|
| 242 |
+
def p_sample(self, model, x_t, cond, t):
|
| 243 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 244 |
+
alphas_t = (1.0 - betas_t)
|
| 245 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 246 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 247 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 248 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 249 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 250 |
+
noise = torch.randn_like(x_t)
|
| 251 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 252 |
+
sigma = torch.sqrt(betas_t)
|
| 253 |
+
return mean + mask * sigma * noise
|
| 254 |
+
|
| 255 |
+
@torch.no_grad()
|
| 256 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 257 |
+
model.eval()
|
| 258 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 259 |
+
if num_steps is None: num_steps = start_t + 1
|
| 260 |
+
B = cond.shape[0]
|
| 261 |
+
x_t = torch.randn((B, 3, cond.shape[2], cond.shape[3]), device=device)
|
| 262 |
+
t_values = list(range(start_t, -1, -1))
|
| 263 |
+
if num_steps < len(t_values):
|
| 264 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 265 |
+
t_values = [t_values[i] for i in idxs]
|
| 266 |
+
for t_scalar in t_values:
|
| 267 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 268 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 269 |
+
return x_t
|
| 270 |
+
|
| 271 |
+
# --------------------------
|
| 272 |
+
# EMA helper
|
| 273 |
+
# --------------------------
|
| 274 |
+
class EMA:
|
| 275 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 276 |
+
self.decay = decay
|
| 277 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 278 |
+
|
| 279 |
+
def update(self, net: nn.Module):
|
| 280 |
+
for k, v in net.state_dict().items():
|
| 281 |
+
if k in self.shadow:
|
| 282 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 283 |
+
else:
|
| 284 |
+
self.shadow[k] = v.clone().detach()
|
| 285 |
+
|
| 286 |
+
def to_state_dict(self):
|
| 287 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 288 |
+
|
| 289 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 290 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 291 |
+
|
| 292 |
+
# --------------------------
|
| 293 |
+
# Image grid save
|
| 294 |
+
# --------------------------
|
| 295 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 296 |
+
tensor = tensor.detach().cpu()
|
| 297 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 298 |
+
arr = arr.astype(np.uint8)
|
| 299 |
+
B,C,H,W = arr.shape
|
| 300 |
+
ncol = math.ceil(B / nrow)
|
| 301 |
+
grid = Image.new("RGB", (W * ncol, H * nrow))
|
| 302 |
+
idx = 0
|
| 303 |
+
for r in range(nrow):
|
| 304 |
+
for c in range(ncol):
|
| 305 |
+
if idx >= B: break
|
| 306 |
+
img = Image.fromarray(arr[idx].transpose(1, 2, 0))
|
| 307 |
+
grid.paste(img, (c*W, r*H))
|
| 308 |
+
idx += 1
|
| 309 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 310 |
+
grid.save(path)
|
| 311 |
+
print(f"[SAVE] image saved: {path}")
|
| 312 |
+
|
| 313 |
+
# --------------------------
|
| 314 |
+
# Trainer (main)
|
| 315 |
+
# --------------------------
|
| 316 |
+
def train(
|
| 317 |
+
base_dir: str,
|
| 318 |
+
train_list: Optional[str] = None,
|
| 319 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 320 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 321 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 322 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 323 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 324 |
+
lr: float = DEFAULT_LR,
|
| 325 |
+
base_channels: int = 64,
|
| 326 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 327 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 328 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 329 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 330 |
+
sample_only: Optional[str] = None,
|
| 331 |
+
):
|
| 332 |
+
base = Path(base_dir)
|
| 333 |
+
train_list = train_list or (base / "train_list_celebA.txt")
|
| 334 |
+
ckpt_dir = base / "checkpoints_cond_blur2_rgb"
|
| 335 |
+
samples_dir = base / "samples_cond_blur2_rgb"
|
| 336 |
+
progress_dir = base / "progress_cond_blur2_rgb"
|
| 337 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 338 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 339 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 340 |
+
|
| 341 |
+
device = get_device()
|
| 342 |
+
print("Device:", device)
|
| 343 |
+
|
| 344 |
+
model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 345 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 346 |
+
|
| 347 |
+
if sample_only:
|
| 348 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 349 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 350 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 351 |
+
model.load_state_dict(sd, strict=False)
|
| 352 |
+
model_for_sampling = model
|
| 353 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 354 |
+
try:
|
| 355 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 356 |
+
tmp = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 357 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 358 |
+
model_for_sampling = tmp
|
| 359 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 360 |
+
except Exception as e:
|
| 361 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 362 |
+
conds = []
|
| 363 |
+
with open(train_list, "r") as f:
|
| 364 |
+
for i, line in enumerate(f):
|
| 365 |
+
if i >= 4: break
|
| 366 |
+
p = Path(line.strip())
|
| 367 |
+
im = Image.open(p).convert("RGB")
|
| 368 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=2.0))
|
| 369 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 370 |
+
conds.append(
|
| 371 |
+
torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).float()
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 375 |
+
with torch.no_grad():
|
| 376 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 377 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 378 |
+
save_grid(samples, out, nrow=2)
|
| 379 |
+
return
|
| 380 |
+
|
| 381 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=2.0)
|
| 382 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 383 |
+
|
| 384 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 385 |
+
ema = EMA(model, decay=ema_decay)
|
| 386 |
+
|
| 387 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 388 |
+
start_step = 0
|
| 389 |
+
if latest.exists():
|
| 390 |
+
print("Resuming from", latest)
|
| 391 |
+
data = safe_torch_load(latest, map_location=device)
|
| 392 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 393 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 394 |
+
try:
|
| 395 |
+
model.load_state_dict(raw_model_sd)
|
| 396 |
+
print("[LOAD] model loaded (strict=True).")
|
| 397 |
+
except Exception as e:
|
| 398 |
+
print("[LOAD] strict load failed:", e)
|
| 399 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 400 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 401 |
+
|
| 402 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 403 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 404 |
+
|
| 405 |
+
if isinstance(data, dict) and "ema" in data:
|
| 406 |
+
try:
|
| 407 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 408 |
+
model_keys = set(model.state_dict().keys())
|
| 409 |
+
ema_keys = set(ema_sd.keys())
|
| 410 |
+
if ema_keys == model_keys:
|
| 411 |
+
ema.load_state_dict(ema_sd)
|
| 412 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 413 |
+
else:
|
| 414 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
for g in opt.param_groups:
|
| 417 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 418 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 419 |
+
except Exception as e:
|
| 420 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 421 |
+
ema = EMA(model, decay=ema_decay)
|
| 422 |
+
else:
|
| 423 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 424 |
+
ema = EMA(model, decay=ema_decay)
|
| 425 |
+
for g in opt.param_groups:
|
| 426 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 427 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 428 |
+
|
| 429 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 430 |
+
print("Resumed at step:", start_step)
|
| 431 |
+
|
| 432 |
+
stop = {"flag": False}
|
| 433 |
+
def handler(sig, frame):
|
| 434 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 435 |
+
stop["flag"] = True
|
| 436 |
+
signal.signal(signal.SIGINT, handler)
|
| 437 |
+
signal.signal(signal.SIGTERM, handler)
|
| 438 |
+
|
| 439 |
+
model.train()
|
| 440 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 441 |
+
step = start_step
|
| 442 |
+
ema_loss = None
|
| 443 |
+
|
| 444 |
+
try:
|
| 445 |
+
while step < total_steps:
|
| 446 |
+
for x0, cond in dl:
|
| 447 |
+
if stop["flag"]:
|
| 448 |
+
break
|
| 449 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 450 |
+
bsz = x0.shape[0]
|
| 451 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 452 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 453 |
+
|
| 454 |
+
opt.zero_grad()
|
| 455 |
+
loss.backward()
|
| 456 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 457 |
+
opt.step()
|
| 458 |
+
ema.update(model)
|
| 459 |
+
|
| 460 |
+
step += 1
|
| 461 |
+
val = float(loss.item())
|
| 462 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 463 |
+
|
| 464 |
+
if step % 50 == 0:
|
| 465 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 466 |
+
|
| 467 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 468 |
+
pbar.update(1)
|
| 469 |
+
|
| 470 |
+
if step % sample_every == 0 or step == 1:
|
| 471 |
+
with torch.no_grad():
|
| 472 |
+
try:
|
| 473 |
+
sample_model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 474 |
+
try:
|
| 475 |
+
ema_sd = ema.to_state_dict()
|
| 476 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 477 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 478 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 479 |
+
except Exception:
|
| 480 |
+
try:
|
| 481 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 482 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 483 |
+
except Exception as e:
|
| 484 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 485 |
+
sample_model = model
|
| 486 |
+
except Exception as e:
|
| 487 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 488 |
+
sample_model = model
|
| 489 |
+
|
| 490 |
+
cond_batch = cond[:4].to(device)
|
| 491 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 492 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 493 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 494 |
+
save_grid(samples, s_path, nrow=2)
|
| 495 |
+
save_grid(samples, p_path, nrow=2)
|
| 496 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 497 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 498 |
+
|
| 499 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 500 |
+
ck = {
|
| 501 |
+
"model": model.state_dict(),
|
| 502 |
+
"optimizer": opt.state_dict(),
|
| 503 |
+
"ema": ema.to_state_dict(),
|
| 504 |
+
"step": step,
|
| 505 |
+
}
|
| 506 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 507 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 508 |
+
atomic_save(ck, p1)
|
| 509 |
+
atomic_save(ck, p2)
|
| 510 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 511 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 512 |
+
|
| 513 |
+
if step >= total_steps:
|
| 514 |
+
break
|
| 515 |
+
if stop["flag"]:
|
| 516 |
+
break
|
| 517 |
+
finally:
|
| 518 |
+
pbar.close()
|
| 519 |
+
ck = {
|
| 520 |
+
"model": model.state_dict(),
|
| 521 |
+
"optimizer": opt.state_dict(),
|
| 522 |
+
"ema": ema.to_state_dict(),
|
| 523 |
+
"step": step,
|
| 524 |
+
}
|
| 525 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 526 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 527 |
+
print("[FINAL] Final checkpoint saved.")
|
| 528 |
+
print("Exiting.")
|
| 529 |
+
|
| 530 |
+
# --------------------------
|
| 531 |
+
# CLI
|
| 532 |
+
# --------------------------
|
| 533 |
+
def parse_args():
|
| 534 |
+
p = argparse.ArgumentParser()
|
| 535 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 536 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 537 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 538 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 539 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 540 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 541 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 542 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 543 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 544 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 545 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 546 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 547 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 548 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 549 |
+
return p.parse_args()
|
| 550 |
+
|
| 551 |
+
if __name__ == "__main__":
|
| 552 |
+
args = parse_args()
|
| 553 |
+
train(
|
| 554 |
+
base_dir=args.base_dir,
|
| 555 |
+
train_list=args.train_list,
|
| 556 |
+
image_size=args.image_size,
|
| 557 |
+
batch_size=args.batch_size,
|
| 558 |
+
num_workers=args.num_workers,
|
| 559 |
+
timesteps=args.timesteps,
|
| 560 |
+
total_steps=args.total_steps,
|
| 561 |
+
lr=args.lr,
|
| 562 |
+
base_channels=args.base_channels,
|
| 563 |
+
save_every=args.save_every,
|
| 564 |
+
sample_every=args.sample_every,
|
| 565 |
+
ema_decay=args.ema_decay,
|
| 566 |
+
val_sample_steps=args.val_sample_steps,
|
| 567 |
+
sample_only=args.sample_only,
|
| 568 |
+
)
|
training_scripts/train_celebA_blur3.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 4 |
+
|
| 5 |
+
Changes made:
|
| 6 |
+
- ALWAYS skip loading optimizer state on resume (prints a clear message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 176
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 5e-5
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 3.0):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("RGB")
|
| 119 |
+
assert img.size == (self.image_size, self.image_size), f"Bad image size: {img.size}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 123 |
+
x0 = arr * 2.0 - 1.0
|
| 124 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 125 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 126 |
+
b = b_arr * 2.0 - 1.0
|
| 127 |
+
x0_t = torch.from_numpy(x0).permute(2, 0, 1).float()
|
| 128 |
+
b_t = torch.from_numpy(b).permute(2, 0, 1).float()
|
| 129 |
+
return x0_t, b_t
|
| 130 |
+
|
| 131 |
+
# --------------------------
|
| 132 |
+
# Model: UNet conditional
|
| 133 |
+
# --------------------------
|
| 134 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 135 |
+
def __init__(self, dim):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.dim = dim
|
| 138 |
+
def forward(self, t):
|
| 139 |
+
device = t.device
|
| 140 |
+
half = self.dim // 2
|
| 141 |
+
emb = math.log(10000) / (half - 1)
|
| 142 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 143 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 144 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 145 |
+
|
| 146 |
+
class ResBlock(nn.Module):
|
| 147 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 148 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 151 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 152 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 153 |
+
self.act = nn.SiLU()
|
| 154 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 155 |
+
def forward(self, x, t_emb):
|
| 156 |
+
h = self.act(self.conv1(x))
|
| 157 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 158 |
+
h = self.conv2(h)
|
| 159 |
+
return self.act(h + self.res_conv(x))
|
| 160 |
+
|
| 161 |
+
class UNetCond(nn.Module):
|
| 162 |
+
def __init__(self, in_ch=6, base=64, time_dim=256):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.time_mlp = nn.Sequential(
|
| 165 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 166 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 167 |
+
nn.SiLU(),
|
| 168 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 169 |
+
)
|
| 170 |
+
# small condition projection to strengthen conditioning at early layers
|
| 171 |
+
self.cond_proj = nn.Sequential(
|
| 172 |
+
nn.Conv2d(3, base, 3, padding=1),
|
| 173 |
+
nn.SiLU(),
|
| 174 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 178 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 179 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 180 |
+
self.pool = nn.AvgPool2d(2)
|
| 181 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 182 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 183 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 184 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 185 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 186 |
+
self.final = nn.Conv2d(base, 3, 1)
|
| 187 |
+
|
| 188 |
+
def forward(self, noisy_and_cond, t):
|
| 189 |
+
device = noisy_and_cond.device
|
| 190 |
+
t_emb = self.time_mlp(t)
|
| 191 |
+
|
| 192 |
+
noisy = noisy_and_cond[:, :3, ...]
|
| 193 |
+
cond = noisy_and_cond[:, 3:, ...]
|
| 194 |
+
cond_feat = self.cond_proj(cond)
|
| 195 |
+
|
| 196 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 197 |
+
try:
|
| 198 |
+
d1 = d1 + 0.5 * cond_feat
|
| 199 |
+
except Exception:
|
| 200 |
+
pass
|
| 201 |
+
|
| 202 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 203 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 204 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 205 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 206 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 207 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 208 |
+
return self.final(u1)
|
| 209 |
+
|
| 210 |
+
# --------------------------
|
| 211 |
+
# Diffusion utils
|
| 212 |
+
# --------------------------
|
| 213 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 214 |
+
return torch.linspace(start, end, timesteps)
|
| 215 |
+
|
| 216 |
+
class Diffusion(nn.Module):
|
| 217 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.timesteps = timesteps
|
| 220 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 221 |
+
alphas = 1.0 - betas
|
| 222 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 223 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 224 |
+
self.register_buffer("betas", betas)
|
| 225 |
+
self.register_buffer("alphas", alphas)
|
| 226 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 227 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 228 |
+
|
| 229 |
+
def q_sample(self, x0, t, noise=None):
|
| 230 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 231 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 232 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 233 |
+
|
| 234 |
+
def p_losses(self, model, x0, cond, t):
|
| 235 |
+
noise = torch.randn_like(x0)
|
| 236 |
+
x_t = self.q_sample(x0, t, noise)
|
| 237 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 238 |
+
noise_pred = model(inp, t)
|
| 239 |
+
return F.mse_loss(noise_pred, noise)
|
| 240 |
+
|
| 241 |
+
@torch.no_grad()
|
| 242 |
+
def p_sample(self, model, x_t, cond, t):
|
| 243 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 244 |
+
alphas_t = (1.0 - betas_t)
|
| 245 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 246 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 247 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 248 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 249 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 250 |
+
noise = torch.randn_like(x_t)
|
| 251 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 252 |
+
sigma = torch.sqrt(betas_t)
|
| 253 |
+
return mean + mask * sigma * noise
|
| 254 |
+
|
| 255 |
+
@torch.no_grad()
|
| 256 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 257 |
+
model.eval()
|
| 258 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 259 |
+
if num_steps is None: num_steps = start_t + 1
|
| 260 |
+
B = cond.shape[0]
|
| 261 |
+
x_t = torch.randn((B, 3, cond.shape[2], cond.shape[3]), device=device)
|
| 262 |
+
t_values = list(range(start_t, -1, -1))
|
| 263 |
+
if num_steps < len(t_values):
|
| 264 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 265 |
+
t_values = [t_values[i] for i in idxs]
|
| 266 |
+
for t_scalar in t_values:
|
| 267 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 268 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 269 |
+
return x_t
|
| 270 |
+
|
| 271 |
+
# --------------------------
|
| 272 |
+
# EMA helper
|
| 273 |
+
# --------------------------
|
| 274 |
+
class EMA:
|
| 275 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 276 |
+
self.decay = decay
|
| 277 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 278 |
+
|
| 279 |
+
def update(self, net: nn.Module):
|
| 280 |
+
for k, v in net.state_dict().items():
|
| 281 |
+
if k in self.shadow:
|
| 282 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 283 |
+
else:
|
| 284 |
+
self.shadow[k] = v.clone().detach()
|
| 285 |
+
|
| 286 |
+
def to_state_dict(self):
|
| 287 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 288 |
+
|
| 289 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 290 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 291 |
+
|
| 292 |
+
# --------------------------
|
| 293 |
+
# Image grid save
|
| 294 |
+
# --------------------------
|
| 295 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 296 |
+
tensor = tensor.detach().cpu()
|
| 297 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 298 |
+
arr = arr.astype(np.uint8)
|
| 299 |
+
B,C,H,W = arr.shape
|
| 300 |
+
ncol = math.ceil(B / nrow)
|
| 301 |
+
grid = Image.new("RGB", (W * ncol, H * nrow))
|
| 302 |
+
idx = 0
|
| 303 |
+
for r in range(nrow):
|
| 304 |
+
for c in range(ncol):
|
| 305 |
+
if idx >= B: break
|
| 306 |
+
img = Image.fromarray(arr[idx].transpose(1, 2, 0))
|
| 307 |
+
grid.paste(img, (c*W, r*H))
|
| 308 |
+
idx += 1
|
| 309 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 310 |
+
grid.save(path)
|
| 311 |
+
print(f"[SAVE] image saved: {path}")
|
| 312 |
+
|
| 313 |
+
# --------------------------
|
| 314 |
+
# Trainer (main)
|
| 315 |
+
# --------------------------
|
| 316 |
+
def train(
|
| 317 |
+
base_dir: str,
|
| 318 |
+
train_list: Optional[str] = None,
|
| 319 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 320 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 321 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 322 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 323 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 324 |
+
lr: float = DEFAULT_LR,
|
| 325 |
+
base_channels: int = 64,
|
| 326 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 327 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 328 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 329 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 330 |
+
sample_only: Optional[str] = None,
|
| 331 |
+
):
|
| 332 |
+
base = Path(base_dir)
|
| 333 |
+
train_list = train_list or (base / "train_list_celebA.txt")
|
| 334 |
+
ckpt_dir = base / "checkpoints_cond_blur3_rgb"
|
| 335 |
+
samples_dir = base / "samples_cond_blur3_rgb"
|
| 336 |
+
progress_dir = base / "progress_cond_blur3_rgb"
|
| 337 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 338 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 339 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 340 |
+
|
| 341 |
+
device = get_device()
|
| 342 |
+
print("Device:", device)
|
| 343 |
+
|
| 344 |
+
model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 345 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 346 |
+
|
| 347 |
+
if sample_only:
|
| 348 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 349 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 350 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 351 |
+
model.load_state_dict(sd, strict=False)
|
| 352 |
+
model_for_sampling = model
|
| 353 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 354 |
+
try:
|
| 355 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 356 |
+
tmp = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 357 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 358 |
+
model_for_sampling = tmp
|
| 359 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 360 |
+
except Exception as e:
|
| 361 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 362 |
+
conds = []
|
| 363 |
+
with open(train_list, "r") as f:
|
| 364 |
+
for i, line in enumerate(f):
|
| 365 |
+
if i >= 4: break
|
| 366 |
+
p = Path(line.strip())
|
| 367 |
+
im = Image.open(p).convert("RGB")
|
| 368 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=3.0))
|
| 369 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 370 |
+
conds.append(
|
| 371 |
+
torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).float()
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 375 |
+
with torch.no_grad():
|
| 376 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 377 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 378 |
+
save_grid(samples, out, nrow=2)
|
| 379 |
+
return
|
| 380 |
+
|
| 381 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=3.0)
|
| 382 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 383 |
+
|
| 384 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 385 |
+
ema = EMA(model, decay=ema_decay)
|
| 386 |
+
|
| 387 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 388 |
+
start_step = 0
|
| 389 |
+
if latest.exists():
|
| 390 |
+
print("Resuming from", latest)
|
| 391 |
+
data = safe_torch_load(latest, map_location=device)
|
| 392 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 393 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 394 |
+
try:
|
| 395 |
+
model.load_state_dict(raw_model_sd)
|
| 396 |
+
print("[LOAD] model loaded (strict=True).")
|
| 397 |
+
except Exception as e:
|
| 398 |
+
print("[LOAD] strict load failed:", e)
|
| 399 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 400 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 401 |
+
|
| 402 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 403 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 404 |
+
|
| 405 |
+
if isinstance(data, dict) and "ema" in data:
|
| 406 |
+
try:
|
| 407 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 408 |
+
model_keys = set(model.state_dict().keys())
|
| 409 |
+
ema_keys = set(ema_sd.keys())
|
| 410 |
+
if ema_keys == model_keys:
|
| 411 |
+
ema.load_state_dict(ema_sd)
|
| 412 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 413 |
+
else:
|
| 414 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
for g in opt.param_groups:
|
| 417 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 418 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 419 |
+
except Exception as e:
|
| 420 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 421 |
+
ema = EMA(model, decay=ema_decay)
|
| 422 |
+
else:
|
| 423 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 424 |
+
ema = EMA(model, decay=ema_decay)
|
| 425 |
+
for g in opt.param_groups:
|
| 426 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 427 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 428 |
+
|
| 429 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 430 |
+
print("Resumed at step:", start_step)
|
| 431 |
+
|
| 432 |
+
stop = {"flag": False}
|
| 433 |
+
def handler(sig, frame):
|
| 434 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 435 |
+
stop["flag"] = True
|
| 436 |
+
signal.signal(signal.SIGINT, handler)
|
| 437 |
+
signal.signal(signal.SIGTERM, handler)
|
| 438 |
+
|
| 439 |
+
model.train()
|
| 440 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 441 |
+
step = start_step
|
| 442 |
+
ema_loss = None
|
| 443 |
+
|
| 444 |
+
try:
|
| 445 |
+
while step < total_steps:
|
| 446 |
+
for x0, cond in dl:
|
| 447 |
+
if stop["flag"]:
|
| 448 |
+
break
|
| 449 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 450 |
+
bsz = x0.shape[0]
|
| 451 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 452 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 453 |
+
|
| 454 |
+
opt.zero_grad()
|
| 455 |
+
loss.backward()
|
| 456 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 457 |
+
opt.step()
|
| 458 |
+
ema.update(model)
|
| 459 |
+
|
| 460 |
+
step += 1
|
| 461 |
+
val = float(loss.item())
|
| 462 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 463 |
+
|
| 464 |
+
if step % 50 == 0:
|
| 465 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 466 |
+
|
| 467 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 468 |
+
pbar.update(1)
|
| 469 |
+
|
| 470 |
+
if step % sample_every == 0 or step == 1:
|
| 471 |
+
with torch.no_grad():
|
| 472 |
+
try:
|
| 473 |
+
sample_model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 474 |
+
try:
|
| 475 |
+
ema_sd = ema.to_state_dict()
|
| 476 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 477 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 478 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 479 |
+
except Exception:
|
| 480 |
+
try:
|
| 481 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 482 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 483 |
+
except Exception as e:
|
| 484 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 485 |
+
sample_model = model
|
| 486 |
+
except Exception as e:
|
| 487 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 488 |
+
sample_model = model
|
| 489 |
+
|
| 490 |
+
cond_batch = cond[:4].to(device)
|
| 491 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 492 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 493 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 494 |
+
save_grid(samples, s_path, nrow=2)
|
| 495 |
+
save_grid(samples, p_path, nrow=2)
|
| 496 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 497 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 498 |
+
|
| 499 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 500 |
+
ck = {
|
| 501 |
+
"model": model.state_dict(),
|
| 502 |
+
"optimizer": opt.state_dict(),
|
| 503 |
+
"ema": ema.to_state_dict(),
|
| 504 |
+
"step": step,
|
| 505 |
+
}
|
| 506 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 507 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 508 |
+
atomic_save(ck, p1)
|
| 509 |
+
atomic_save(ck, p2)
|
| 510 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 511 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 512 |
+
|
| 513 |
+
if step >= total_steps:
|
| 514 |
+
break
|
| 515 |
+
if stop["flag"]:
|
| 516 |
+
break
|
| 517 |
+
finally:
|
| 518 |
+
pbar.close()
|
| 519 |
+
ck = {
|
| 520 |
+
"model": model.state_dict(),
|
| 521 |
+
"optimizer": opt.state_dict(),
|
| 522 |
+
"ema": ema.to_state_dict(),
|
| 523 |
+
"step": step,
|
| 524 |
+
}
|
| 525 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 526 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 527 |
+
print("[FINAL] Final checkpoint saved.")
|
| 528 |
+
print("Exiting.")
|
| 529 |
+
|
| 530 |
+
# --------------------------
|
| 531 |
+
# CLI
|
| 532 |
+
# --------------------------
|
| 533 |
+
def parse_args():
|
| 534 |
+
p = argparse.ArgumentParser()
|
| 535 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 536 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 537 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 538 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 539 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 540 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 541 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 542 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 543 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 544 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 545 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 546 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 547 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 548 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 549 |
+
return p.parse_args()
|
| 550 |
+
|
| 551 |
+
if __name__ == "__main__":
|
| 552 |
+
args = parse_args()
|
| 553 |
+
train(
|
| 554 |
+
base_dir=args.base_dir,
|
| 555 |
+
train_list=args.train_list,
|
| 556 |
+
image_size=args.image_size,
|
| 557 |
+
batch_size=args.batch_size,
|
| 558 |
+
num_workers=args.num_workers,
|
| 559 |
+
timesteps=args.timesteps,
|
| 560 |
+
total_steps=args.total_steps,
|
| 561 |
+
lr=args.lr,
|
| 562 |
+
base_channels=args.base_channels,
|
| 563 |
+
save_every=args.save_every,
|
| 564 |
+
sample_every=args.sample_every,
|
| 565 |
+
ema_decay=args.ema_decay,
|
| 566 |
+
val_sample_steps=args.val_sample_steps,
|
| 567 |
+
sample_only=args.sample_only,
|
| 568 |
+
)
|
training_scripts/train_celebA_blur_half.py
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_conditional_final.py — Robust conditional trainer (drop-in)
|
| 4 |
+
|
| 5 |
+
Changes made:
|
| 6 |
+
- ALWAYS skip loading optimizer state on resume (prints a clear message).
|
| 7 |
+
- Fixed safe_torch_load (removed nonexistent weights_only kwarg).
|
| 8 |
+
- Use the single `device` variable everywhere (no repeated get_device() calls).
|
| 9 |
+
- More robust EMA sampling/load logic.
|
| 10 |
+
- DEFAULT_VAL_SAMPLE_STEPS set to 1000 (can still be overridden by CLI).
|
| 11 |
+
- Small defensive logging & comments.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import random
|
| 18 |
+
import signal
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from PIL import Image, ImageFilter
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import Dataset, DataLoader
|
| 29 |
+
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# --------------------------
|
| 33 |
+
# Default config (will be overridden by CLI)
|
| 34 |
+
# --------------------------
|
| 35 |
+
DEFAULT_BASE_DIR = Path("/Users/arvindarya/Documents/compression")
|
| 36 |
+
DEFAULT_IMAGE_SIZE = 176
|
| 37 |
+
DEFAULT_BATCH_SIZE = 8
|
| 38 |
+
DEFAULT_NUM_WORKERS = 2
|
| 39 |
+
DEFAULT_TIMESTEPS = 1000
|
| 40 |
+
DEFAULT_TOTAL_STEPS = 600000
|
| 41 |
+
DEFAULT_LR = 1e-4
|
| 42 |
+
DEFAULT_SAVE_EVERY = 2000
|
| 43 |
+
DEFAULT_SAMPLE_EVERY = 1000
|
| 44 |
+
DEFAULT_EMA_DECAY = 0.9999
|
| 45 |
+
DEFAULT_VAL_SAMPLE_STEPS = 1000
|
| 46 |
+
|
| 47 |
+
# --------------------------
|
| 48 |
+
# Helpers: device, atomic save, safe load, remapper
|
| 49 |
+
# --------------------------
|
| 50 |
+
def get_device():
|
| 51 |
+
# prefer mps if available (mac), else cuda, else cpu
|
| 52 |
+
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():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
if torch.cuda.is_available():
|
| 55 |
+
return torch.device("cuda")
|
| 56 |
+
return torch.device("cpu")
|
| 57 |
+
|
| 58 |
+
def atomic_save(obj, path: Path):
|
| 59 |
+
tmp = path.with_suffix(".tmp")
|
| 60 |
+
torch.save(obj, tmp)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
def safe_torch_load(path: Path, map_location):
|
| 64 |
+
"""
|
| 65 |
+
Robust local load. If it fails, raise with a clear message.
|
| 66 |
+
(Don't attempt unsupported torch.load kwargs.)
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
return torch.load(path, map_location=map_location)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
raise RuntimeError(f"Failed to load checkpoint {path}: {e}")
|
| 72 |
+
|
| 73 |
+
def remap_checkpoint_to_model(checkpoint_sd: Dict[str, torch.Tensor], model: torch.nn.Module) -> Dict[str, torch.Tensor]:
|
| 74 |
+
"""
|
| 75 |
+
Remap checkpoint state-dict keys to match the model's key naming for res/res_conv.
|
| 76 |
+
"""
|
| 77 |
+
ck_keys = set(checkpoint_sd.keys())
|
| 78 |
+
model_keys = set(model.state_dict().keys())
|
| 79 |
+
|
| 80 |
+
has_ck_res_conv = any(".res_conv." in k for k in ck_keys)
|
| 81 |
+
has_ck_res = any(".res." in k for k in ck_keys)
|
| 82 |
+
has_mod_res_conv = any(".res_conv." in k for k in model_keys)
|
| 83 |
+
has_mod_res = any(".res." in k for k in model_keys)
|
| 84 |
+
|
| 85 |
+
# checkpoint uses res_conv, model expects res
|
| 86 |
+
if has_ck_res_conv and has_mod_res and not has_mod_res_conv:
|
| 87 |
+
return {k.replace(".res_conv.", ".res."): v for k, v in checkpoint_sd.items()}
|
| 88 |
+
|
| 89 |
+
# checkpoint uses res, model expects res_conv
|
| 90 |
+
if has_ck_res and has_mod_res_conv and not has_mod_res:
|
| 91 |
+
return {k.replace(".res.", ".res_conv."): v for k, v in checkpoint_sd.items()}
|
| 92 |
+
|
| 93 |
+
# otherwise return unchanged
|
| 94 |
+
return checkpoint_sd
|
| 95 |
+
|
| 96 |
+
# --------------------------
|
| 97 |
+
# Dataset: returns (x0, cond_blur)
|
| 98 |
+
# --------------------------
|
| 99 |
+
class ConditionalMRI(Dataset):
|
| 100 |
+
def __init__(self, list_path: str, image_size: int = DEFAULT_IMAGE_SIZE, blur_radius: float = 0.5):
|
| 101 |
+
p = Path(list_path)
|
| 102 |
+
if not p.exists():
|
| 103 |
+
raise RuntimeError(f"Train list not found: {p}")
|
| 104 |
+
with open(p, "r") as f:
|
| 105 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 106 |
+
if not lines:
|
| 107 |
+
raise RuntimeError(f"No image paths found in {p}")
|
| 108 |
+
self.paths = [Path(x) for x in lines]
|
| 109 |
+
self.image_size = image_size
|
| 110 |
+
self.blur_radius = blur_radius
|
| 111 |
+
print(f"[Dataset] {len(self.paths)} items; blur radius {self.blur_radius}")
|
| 112 |
+
|
| 113 |
+
def __len__(self):
|
| 114 |
+
return len(self.paths)
|
| 115 |
+
|
| 116 |
+
def __getitem__(self, idx):
|
| 117 |
+
p = self.paths[idx]
|
| 118 |
+
img = Image.open(p).convert("RGB")
|
| 119 |
+
assert img.size == (self.image_size, self.image_size), f"Bad image size: {img.size}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
arr = np.array(img, dtype=np.float32) / 255.0
|
| 123 |
+
x0 = arr * 2.0 - 1.0
|
| 124 |
+
blurred = img.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
|
| 125 |
+
b_arr = np.array(blurred, dtype=np.float32) / 255.0
|
| 126 |
+
b = b_arr * 2.0 - 1.0
|
| 127 |
+
x0_t = torch.from_numpy(x0).permute(2, 0, 1).float()
|
| 128 |
+
b_t = torch.from_numpy(b).permute(2, 0, 1).float()
|
| 129 |
+
return x0_t, b_t
|
| 130 |
+
|
| 131 |
+
# --------------------------
|
| 132 |
+
# Model: UNet conditional
|
| 133 |
+
# --------------------------
|
| 134 |
+
class SinusoidalTimeEmbedding(nn.Module):
|
| 135 |
+
def __init__(self, dim):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.dim = dim
|
| 138 |
+
def forward(self, t):
|
| 139 |
+
device = t.device
|
| 140 |
+
half = self.dim // 2
|
| 141 |
+
emb = math.log(10000) / (half - 1)
|
| 142 |
+
emb = torch.exp(torch.arange(half, device=device) * -emb)
|
| 143 |
+
emb = t.float().unsqueeze(1) * emb.unsqueeze(0)
|
| 144 |
+
return torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 145 |
+
|
| 146 |
+
class ResBlock(nn.Module):
|
| 147 |
+
# keep attribute name res_conv to match both variants (remapper handles differences)
|
| 148 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 151 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 152 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 153 |
+
self.act = nn.SiLU()
|
| 154 |
+
self.res_conv = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 155 |
+
def forward(self, x, t_emb):
|
| 156 |
+
h = self.act(self.conv1(x))
|
| 157 |
+
h = h + self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1)
|
| 158 |
+
h = self.conv2(h)
|
| 159 |
+
return self.act(h + self.res_conv(x))
|
| 160 |
+
|
| 161 |
+
class UNetCond(nn.Module):
|
| 162 |
+
def __init__(self, in_ch=6, base=64, time_dim=256):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.time_mlp = nn.Sequential(
|
| 165 |
+
SinusoidalTimeEmbedding(time_dim),
|
| 166 |
+
nn.Linear(time_dim, time_dim * 2),
|
| 167 |
+
nn.SiLU(),
|
| 168 |
+
nn.Linear(time_dim * 2, time_dim),
|
| 169 |
+
)
|
| 170 |
+
# small condition projection to strengthen conditioning at early layers
|
| 171 |
+
self.cond_proj = nn.Sequential(
|
| 172 |
+
nn.Conv2d(3, base, 3, padding=1),
|
| 173 |
+
nn.SiLU(),
|
| 174 |
+
nn.Conv2d(base, base, 3, padding=1),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
self.down1 = ResBlock(in_ch, base, time_dim)
|
| 178 |
+
self.down2 = ResBlock(base, base * 2, time_dim)
|
| 179 |
+
self.down3 = ResBlock(base * 2, base * 4, time_dim)
|
| 180 |
+
self.pool = nn.AvgPool2d(2)
|
| 181 |
+
self.bot = ResBlock(base * 4, base * 4, time_dim)
|
| 182 |
+
self.up3 = ResBlock(base * 4 + base * 4, base * 2, time_dim)
|
| 183 |
+
self.up2 = ResBlock(base * 2 + base * 2, base, time_dim)
|
| 184 |
+
self.up1 = ResBlock(base + base, base, time_dim)
|
| 185 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 186 |
+
self.final = nn.Conv2d(base, 3, 1)
|
| 187 |
+
|
| 188 |
+
def forward(self, noisy_and_cond, t):
|
| 189 |
+
device = noisy_and_cond.device
|
| 190 |
+
t_emb = self.time_mlp(t)
|
| 191 |
+
|
| 192 |
+
noisy = noisy_and_cond[:, :3, ...]
|
| 193 |
+
cond = noisy_and_cond[:, 3:, ...]
|
| 194 |
+
cond_feat = self.cond_proj(cond)
|
| 195 |
+
|
| 196 |
+
d1 = self.down1(torch.cat([noisy, cond], dim=1), t_emb)
|
| 197 |
+
try:
|
| 198 |
+
d1 = d1 + cond_feat
|
| 199 |
+
except Exception:
|
| 200 |
+
pass
|
| 201 |
+
|
| 202 |
+
d2 = self.down2(self.pool(d1), t_emb)
|
| 203 |
+
d3 = self.down3(self.pool(d2), t_emb)
|
| 204 |
+
b = self.bot(self.pool(d3), t_emb)
|
| 205 |
+
u3 = self.upsample(b); u3 = torch.cat([u3, d3], dim=1); u3 = self.up3(u3, t_emb)
|
| 206 |
+
u2 = self.upsample(u3); u2 = torch.cat([u2, d2], dim=1); u2 = self.up2(u2, t_emb)
|
| 207 |
+
u1 = self.upsample(u2); u1 = torch.cat([u1, d1], dim=1); u1 = self.up1(u1, t_emb)
|
| 208 |
+
return self.final(u1)
|
| 209 |
+
|
| 210 |
+
# --------------------------
|
| 211 |
+
# Diffusion utils
|
| 212 |
+
# --------------------------
|
| 213 |
+
def make_beta_schedule(timesteps, start=1e-4, end=0.02):
|
| 214 |
+
return torch.linspace(start, end, timesteps)
|
| 215 |
+
|
| 216 |
+
class Diffusion(nn.Module):
|
| 217 |
+
def __init__(self, timesteps=1000, device="cpu"):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.timesteps = timesteps
|
| 220 |
+
betas = make_beta_schedule(timesteps).to(device)
|
| 221 |
+
alphas = 1.0 - betas
|
| 222 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 223 |
+
alphas_cumprod_prev = torch.cat([torch.tensor([1.0], device=device), alphas_cumprod[:-1]], dim=0)
|
| 224 |
+
self.register_buffer("betas", betas)
|
| 225 |
+
self.register_buffer("alphas", alphas)
|
| 226 |
+
self.register_buffer("alphas_cumprod", alphas_cumprod)
|
| 227 |
+
self.register_buffer("alphas_cumprod_prev", alphas_cumprod_prev)
|
| 228 |
+
|
| 229 |
+
def q_sample(self, x0, t, noise=None):
|
| 230 |
+
if noise is None: noise = torch.randn_like(x0)
|
| 231 |
+
ac = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 232 |
+
return torch.sqrt(ac) * x0 + torch.sqrt(1.0 - ac) * noise
|
| 233 |
+
|
| 234 |
+
def p_losses(self, model, x0, cond, t):
|
| 235 |
+
noise = torch.randn_like(x0)
|
| 236 |
+
x_t = self.q_sample(x0, t, noise)
|
| 237 |
+
inp = torch.cat([x_t, cond], dim=1)
|
| 238 |
+
noise_pred = model(inp, t)
|
| 239 |
+
return F.mse_loss(noise_pred, noise)
|
| 240 |
+
|
| 241 |
+
@torch.no_grad()
|
| 242 |
+
def p_sample(self, model, x_t, cond, t):
|
| 243 |
+
betas_t = self.betas[t].view(-1,1,1,1)
|
| 244 |
+
alphas_t = (1.0 - betas_t)
|
| 245 |
+
alphas_cumprod_t = self.alphas_cumprod[t].view(-1,1,1,1)
|
| 246 |
+
eps_theta = model(torch.cat([x_t, cond], dim=1), t)
|
| 247 |
+
coef1 = 1.0 / torch.sqrt(alphas_t)
|
| 248 |
+
coef2 = (1.0 - alphas_t) / torch.sqrt(1.0 - alphas_cumprod_t)
|
| 249 |
+
mean = coef1 * (x_t - coef2 * eps_theta)
|
| 250 |
+
noise = torch.randn_like(x_t)
|
| 251 |
+
mask = (t > 0).float().view(-1,1,1,1)
|
| 252 |
+
sigma = torch.sqrt(betas_t)
|
| 253 |
+
return mean + mask * sigma * noise
|
| 254 |
+
|
| 255 |
+
@torch.no_grad()
|
| 256 |
+
def sample_conditional(self, model, cond, device, start_t=None, num_steps=None):
|
| 257 |
+
model.eval()
|
| 258 |
+
if start_t is None: start_t = self.timesteps - 1
|
| 259 |
+
if num_steps is None: num_steps = start_t + 1
|
| 260 |
+
B = cond.shape[0]
|
| 261 |
+
x_t = torch.randn((B, 3, cond.shape[2], cond.shape[3]), device=device)
|
| 262 |
+
t_values = list(range(start_t, -1, -1))
|
| 263 |
+
if num_steps < len(t_values):
|
| 264 |
+
idxs = np.linspace(0, len(t_values)-1, num_steps).astype(int)
|
| 265 |
+
t_values = [t_values[i] for i in idxs]
|
| 266 |
+
for t_scalar in t_values:
|
| 267 |
+
t_batch = torch.tensor([t_scalar]*B, device=device).long()
|
| 268 |
+
x_t = self.p_sample(model, x_t, cond, t_batch)
|
| 269 |
+
return x_t
|
| 270 |
+
|
| 271 |
+
# --------------------------
|
| 272 |
+
# EMA helper
|
| 273 |
+
# --------------------------
|
| 274 |
+
class EMA:
|
| 275 |
+
def __init__(self, net: nn.Module, decay: float = DEFAULT_EMA_DECAY):
|
| 276 |
+
self.decay = decay
|
| 277 |
+
self.shadow = {k: v.clone().detach() for k, v in net.state_dict().items()}
|
| 278 |
+
|
| 279 |
+
def update(self, net: nn.Module):
|
| 280 |
+
for k, v in net.state_dict().items():
|
| 281 |
+
if k in self.shadow:
|
| 282 |
+
self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1.0 - self.decay)
|
| 283 |
+
else:
|
| 284 |
+
self.shadow[k] = v.clone().detach()
|
| 285 |
+
|
| 286 |
+
def to_state_dict(self):
|
| 287 |
+
return {k: v.clone().cpu() for k, v in self.shadow.items()}
|
| 288 |
+
|
| 289 |
+
def load_state_dict(self, sd: Dict[str, torch.Tensor]):
|
| 290 |
+
self.shadow = {k: v.clone().detach() for k, v in sd.items()}
|
| 291 |
+
|
| 292 |
+
# --------------------------
|
| 293 |
+
# Image grid save
|
| 294 |
+
# --------------------------
|
| 295 |
+
def save_grid(tensor: torch.Tensor, path: Path, nrow: int = 2):
|
| 296 |
+
tensor = tensor.detach().cpu()
|
| 297 |
+
arr = ((tensor + 1.0) / 2.0).clamp(0,1).numpy() * 255.0
|
| 298 |
+
arr = arr.astype(np.uint8)
|
| 299 |
+
B,C,H,W = arr.shape
|
| 300 |
+
ncol = math.ceil(B / nrow)
|
| 301 |
+
grid = Image.new("RGB", (W * ncol, H * nrow))
|
| 302 |
+
idx = 0
|
| 303 |
+
for r in range(nrow):
|
| 304 |
+
for c in range(ncol):
|
| 305 |
+
if idx >= B: break
|
| 306 |
+
img = Image.fromarray(arr[idx].transpose(1, 2, 0))
|
| 307 |
+
grid.paste(img, (c*W, r*H))
|
| 308 |
+
idx += 1
|
| 309 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 310 |
+
grid.save(path)
|
| 311 |
+
print(f"[SAVE] image saved: {path}")
|
| 312 |
+
|
| 313 |
+
# --------------------------
|
| 314 |
+
# Trainer (main)
|
| 315 |
+
# --------------------------
|
| 316 |
+
def train(
|
| 317 |
+
base_dir: str,
|
| 318 |
+
train_list: Optional[str] = None,
|
| 319 |
+
image_size: int = DEFAULT_IMAGE_SIZE,
|
| 320 |
+
batch_size: int = DEFAULT_BATCH_SIZE,
|
| 321 |
+
num_workers: int = DEFAULT_NUM_WORKERS,
|
| 322 |
+
timesteps: int = DEFAULT_TIMESTEPS,
|
| 323 |
+
total_steps: int = DEFAULT_TOTAL_STEPS,
|
| 324 |
+
lr: float = DEFAULT_LR,
|
| 325 |
+
base_channels: int = 64,
|
| 326 |
+
save_every: int = DEFAULT_SAVE_EVERY,
|
| 327 |
+
sample_every: int = DEFAULT_SAMPLE_EVERY,
|
| 328 |
+
ema_decay: float = DEFAULT_EMA_DECAY,
|
| 329 |
+
val_sample_steps: int = DEFAULT_VAL_SAMPLE_STEPS,
|
| 330 |
+
sample_only: Optional[str] = None,
|
| 331 |
+
):
|
| 332 |
+
base = Path(base_dir)
|
| 333 |
+
train_list = train_list or (base / "train_list_celebA.txt")
|
| 334 |
+
ckpt_dir = base / "checkpoints_cond_blur0.5_rgb"
|
| 335 |
+
samples_dir = base / "samples_cond_blur0.5_rgb"
|
| 336 |
+
progress_dir = base / "progress_cond_blur0.5_rgb"
|
| 337 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 338 |
+
samples_dir.mkdir(parents=True, exist_ok=True)
|
| 339 |
+
progress_dir.mkdir(parents=True, exist_ok=True)
|
| 340 |
+
|
| 341 |
+
device = get_device()
|
| 342 |
+
print("Device:", device)
|
| 343 |
+
|
| 344 |
+
model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 345 |
+
diffusion = Diffusion(timesteps=timesteps, device=device).to(device)
|
| 346 |
+
|
| 347 |
+
if sample_only:
|
| 348 |
+
ck = safe_torch_load(Path(sample_only), map_location=device)
|
| 349 |
+
sd = ck.get("model", ck) if isinstance(ck, dict) else ck
|
| 350 |
+
sd = remap_checkpoint_to_model(sd, model)
|
| 351 |
+
model.load_state_dict(sd, strict=False)
|
| 352 |
+
model_for_sampling = model
|
| 353 |
+
if isinstance(ck, dict) and "ema" in ck:
|
| 354 |
+
try:
|
| 355 |
+
ema_sd = remap_checkpoint_to_model(ck["ema"], model)
|
| 356 |
+
tmp = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 357 |
+
tmp.load_state_dict(ema_sd, strict=False)
|
| 358 |
+
model_for_sampling = tmp
|
| 359 |
+
print("[SAMPLE_ONLY] Using EMA from checkpoint for sampling.")
|
| 360 |
+
except Exception as e:
|
| 361 |
+
print("[SAMPLE_ONLY] EMA load failed, using raw model:", e)
|
| 362 |
+
conds = []
|
| 363 |
+
with open(train_list, "r") as f:
|
| 364 |
+
for i, line in enumerate(f):
|
| 365 |
+
if i >= 4: break
|
| 366 |
+
p = Path(line.strip())
|
| 367 |
+
im = Image.open(p).convert("RGB")
|
| 368 |
+
b = im.filter(ImageFilter.GaussianBlur(radius=0.5))
|
| 369 |
+
arr = (np.array(b, dtype=np.float32) / 255.0) * 2.0 - 1.0
|
| 370 |
+
conds.append(
|
| 371 |
+
torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).float()
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
cond_batch = torch.cat(conds, dim=0).to(device)
|
| 375 |
+
with torch.no_grad():
|
| 376 |
+
samples = diffusion.sample_conditional(model_for_sampling, cond_batch, device=device, num_steps=val_sample_steps)
|
| 377 |
+
out = samples_dir / f"samples_cond_sampleonly_{Path(sample_only).stem}.png"
|
| 378 |
+
save_grid(samples, out, nrow=2)
|
| 379 |
+
return
|
| 380 |
+
|
| 381 |
+
ds = ConditionalMRI(str(train_list), image_size=image_size, blur_radius=0.5)
|
| 382 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
| 383 |
+
|
| 384 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 385 |
+
ema = EMA(model, decay=ema_decay)
|
| 386 |
+
|
| 387 |
+
latest = ckpt_dir / "cond_latest.pt"
|
| 388 |
+
start_step = 0
|
| 389 |
+
if latest.exists():
|
| 390 |
+
print("Resuming from", latest)
|
| 391 |
+
data = safe_torch_load(latest, map_location=device)
|
| 392 |
+
raw_model_sd = data.get("model", data) if isinstance(data, dict) else data
|
| 393 |
+
raw_model_sd = remap_checkpoint_to_model(raw_model_sd, model)
|
| 394 |
+
try:
|
| 395 |
+
model.load_state_dict(raw_model_sd)
|
| 396 |
+
print("[LOAD] model loaded (strict=True).")
|
| 397 |
+
except Exception as e:
|
| 398 |
+
print("[LOAD] strict load failed:", e)
|
| 399 |
+
model.load_state_dict(raw_model_sd, strict=False)
|
| 400 |
+
print("[LOAD] model loaded (strict=False). Some keys may be missing/unexpected.")
|
| 401 |
+
|
| 402 |
+
if isinstance(data, dict) and "optimizer" in data:
|
| 403 |
+
print("[LOAD] Skipping optimizer state load (always resume with fresh optimizer).")
|
| 404 |
+
|
| 405 |
+
if isinstance(data, dict) and "ema" in data:
|
| 406 |
+
try:
|
| 407 |
+
ema_sd = remap_checkpoint_to_model(data["ema"], model)
|
| 408 |
+
model_keys = set(model.state_dict().keys())
|
| 409 |
+
ema_keys = set(ema_sd.keys())
|
| 410 |
+
if ema_keys == model_keys:
|
| 411 |
+
ema.load_state_dict(ema_sd)
|
| 412 |
+
print("[LOAD] EMA loaded from checkpoint.")
|
| 413 |
+
else:
|
| 414 |
+
print("[WARN] EMA keys do not match model keys (mismatch). Rebuilding EMA from current model.")
|
| 415 |
+
ema = EMA(model, decay=ema_decay)
|
| 416 |
+
for g in opt.param_groups:
|
| 417 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 418 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 419 |
+
except Exception as e:
|
| 420 |
+
print("[WARN] Failed to load EMA from checkpoint:", e)
|
| 421 |
+
ema = EMA(model, decay=ema_decay)
|
| 422 |
+
else:
|
| 423 |
+
print("[WARN] No EMA present in checkpoint. Rebuilding EMA from current model and using SAFE low LR.")
|
| 424 |
+
ema = EMA(model, decay=ema_decay)
|
| 425 |
+
for g in opt.param_groups:
|
| 426 |
+
g["lr"] = min(g.get("lr", lr), 5e-05)
|
| 427 |
+
print("[SAFE] Optimizer LR reduced to", opt.param_groups[0]["lr"])
|
| 428 |
+
|
| 429 |
+
start_step = int(data.get("step", 0)) if isinstance(data, dict) else 0
|
| 430 |
+
print("Resumed at step:", start_step)
|
| 431 |
+
|
| 432 |
+
stop = {"flag": False}
|
| 433 |
+
def handler(sig, frame):
|
| 434 |
+
print("\nSignal received: will save checkpoint and exit after current batch.")
|
| 435 |
+
stop["flag"] = True
|
| 436 |
+
signal.signal(signal.SIGINT, handler)
|
| 437 |
+
signal.signal(signal.SIGTERM, handler)
|
| 438 |
+
|
| 439 |
+
model.train()
|
| 440 |
+
pbar = tqdm(total=total_steps, initial=start_step, desc="Train", ncols=120)
|
| 441 |
+
step = start_step
|
| 442 |
+
ema_loss = None
|
| 443 |
+
|
| 444 |
+
try:
|
| 445 |
+
while step < total_steps:
|
| 446 |
+
for x0, cond in dl:
|
| 447 |
+
if stop["flag"]:
|
| 448 |
+
break
|
| 449 |
+
x0 = x0.to(device); cond = cond.to(device)
|
| 450 |
+
bsz = x0.shape[0]
|
| 451 |
+
t = torch.randint(0, timesteps, (bsz,), device=device).long()
|
| 452 |
+
loss = diffusion.p_losses(model, x0, cond, t)
|
| 453 |
+
|
| 454 |
+
opt.zero_grad()
|
| 455 |
+
loss.backward()
|
| 456 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 457 |
+
opt.step()
|
| 458 |
+
ema.update(model)
|
| 459 |
+
|
| 460 |
+
step += 1
|
| 461 |
+
val = float(loss.item())
|
| 462 |
+
ema_loss = val if ema_loss is None else 0.9 * ema_loss + 0.1 * val
|
| 463 |
+
|
| 464 |
+
if step % 50 == 0:
|
| 465 |
+
print(f"[{step}/{total_steps}] loss={val:.6f} ema={ema_loss:.6f}")
|
| 466 |
+
|
| 467 |
+
pbar.set_postfix({"loss": f"{val:.3e}", "ema": f"{ema_loss:.3e}"})
|
| 468 |
+
pbar.update(1)
|
| 469 |
+
|
| 470 |
+
if step % sample_every == 0 or step == 1:
|
| 471 |
+
with torch.no_grad():
|
| 472 |
+
try:
|
| 473 |
+
sample_model = UNetCond(in_ch=6, base=base_channels).to(device)
|
| 474 |
+
try:
|
| 475 |
+
ema_sd = ema.to_state_dict()
|
| 476 |
+
ema_sd = remap_checkpoint_to_model(ema_sd, sample_model)
|
| 477 |
+
sample_model.load_state_dict(ema_sd, strict=False)
|
| 478 |
+
print("[SAMPLE] Using EMA shadow for sampling (remapped if needed).")
|
| 479 |
+
except Exception:
|
| 480 |
+
try:
|
| 481 |
+
sample_model.load_state_dict(ema.shadow, strict=False)
|
| 482 |
+
print("[SAMPLE] Loaded EMA shadow (fallback strict=False).")
|
| 483 |
+
except Exception as e:
|
| 484 |
+
print("[SAMPLE] EMA load fallback failed, using raw model for sampling:", e)
|
| 485 |
+
sample_model = model
|
| 486 |
+
except Exception as e:
|
| 487 |
+
print("[SAMPLE] Failed to build EMA sample model:", e)
|
| 488 |
+
sample_model = model
|
| 489 |
+
|
| 490 |
+
cond_batch = cond[:4].to(device)
|
| 491 |
+
samples = diffusion.sample_conditional(sample_model, cond_batch, device=device, num_steps=val_sample_steps)
|
| 492 |
+
s_path = samples_dir / f"samples_cond_{step}.png"
|
| 493 |
+
p_path = progress_dir / f"progress_cond_{step}.png"
|
| 494 |
+
save_grid(samples, s_path, nrow=2)
|
| 495 |
+
save_grid(samples, p_path, nrow=2)
|
| 496 |
+
print(f"[SAMPLE] Saved sample: {s_path}")
|
| 497 |
+
print(f"[SAMPLE] Saved progress: {p_path}")
|
| 498 |
+
|
| 499 |
+
if step % save_every == 0 or stop["flag"] or step >= total_steps:
|
| 500 |
+
ck = {
|
| 501 |
+
"model": model.state_dict(),
|
| 502 |
+
"optimizer": opt.state_dict(),
|
| 503 |
+
"ema": ema.to_state_dict(),
|
| 504 |
+
"step": step,
|
| 505 |
+
}
|
| 506 |
+
p1 = ckpt_dir / f"cond_step_{step}.pt"
|
| 507 |
+
p2 = ckpt_dir / "cond_latest.pt"
|
| 508 |
+
atomic_save(ck, p1)
|
| 509 |
+
atomic_save(ck, p2)
|
| 510 |
+
print(f"[CKPT] Saved checkpoint: {p1}")
|
| 511 |
+
print(f"[CKPT] Updated latest checkpoint: {p2}")
|
| 512 |
+
|
| 513 |
+
if step >= total_steps:
|
| 514 |
+
break
|
| 515 |
+
if stop["flag"]:
|
| 516 |
+
break
|
| 517 |
+
finally:
|
| 518 |
+
pbar.close()
|
| 519 |
+
ck = {
|
| 520 |
+
"model": model.state_dict(),
|
| 521 |
+
"optimizer": opt.state_dict(),
|
| 522 |
+
"ema": ema.to_state_dict(),
|
| 523 |
+
"step": step,
|
| 524 |
+
}
|
| 525 |
+
atomic_save(ck, ckpt_dir / f"cond_step_{step}.pt")
|
| 526 |
+
atomic_save(ck, ckpt_dir / "cond_latest.pt")
|
| 527 |
+
print("[FINAL] Final checkpoint saved.")
|
| 528 |
+
print("Exiting.")
|
| 529 |
+
|
| 530 |
+
# --------------------------
|
| 531 |
+
# CLI
|
| 532 |
+
# --------------------------
|
| 533 |
+
def parse_args():
|
| 534 |
+
p = argparse.ArgumentParser()
|
| 535 |
+
p.add_argument("--base_dir", default=str(DEFAULT_BASE_DIR))
|
| 536 |
+
p.add_argument("--train_list", default=None, help="path to train list (one image per line)")
|
| 537 |
+
p.add_argument("--image_size", type=int, default=DEFAULT_IMAGE_SIZE)
|
| 538 |
+
p.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
|
| 539 |
+
p.add_argument("--num_workers", type=int, default=DEFAULT_NUM_WORKERS)
|
| 540 |
+
p.add_argument("--timesteps", type=int, default=DEFAULT_TIMESTEPS)
|
| 541 |
+
p.add_argument("--total_steps", type=int, default=DEFAULT_TOTAL_STEPS)
|
| 542 |
+
p.add_argument("--lr", type=float, default=DEFAULT_LR)
|
| 543 |
+
p.add_argument("--base_channels", type=int, default=64)
|
| 544 |
+
p.add_argument("--save_every", type=int, default=DEFAULT_SAVE_EVERY)
|
| 545 |
+
p.add_argument("--sample_every", type=int, default=DEFAULT_SAMPLE_EVERY)
|
| 546 |
+
p.add_argument("--ema_decay", type=float, default=DEFAULT_EMA_DECAY)
|
| 547 |
+
p.add_argument("--val_sample_steps", type=int, default=DEFAULT_VAL_SAMPLE_STEPS)
|
| 548 |
+
p.add_argument("--sample_only", default=None, help="path to ckpt to sample and exit")
|
| 549 |
+
return p.parse_args()
|
| 550 |
+
|
| 551 |
+
if __name__ == "__main__":
|
| 552 |
+
args = parse_args()
|
| 553 |
+
train(
|
| 554 |
+
base_dir=args.base_dir,
|
| 555 |
+
train_list=args.train_list,
|
| 556 |
+
image_size=args.image_size,
|
| 557 |
+
batch_size=args.batch_size,
|
| 558 |
+
num_workers=args.num_workers,
|
| 559 |
+
timesteps=args.timesteps,
|
| 560 |
+
total_steps=args.total_steps,
|
| 561 |
+
lr=args.lr,
|
| 562 |
+
base_channels=args.base_channels,
|
| 563 |
+
save_every=args.save_every,
|
| 564 |
+
sample_every=args.sample_every,
|
| 565 |
+
ema_decay=args.ema_decay,
|
| 566 |
+
val_sample_steps=args.val_sample_steps,
|
| 567 |
+
sample_only=args.sample_only,
|
| 568 |
+
)
|