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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
LatentRecurrentFlow v3 — Complete Self-Contained Training & Generation
|
| 4 |
+
======================================================================
|
| 5 |
+
|
| 6 |
+
This is one file. Run it and it:
|
| 7 |
+
1. Downloads TAESD (pre-trained tiny VAE, 2.4M params, frozen)
|
| 8 |
+
2. Pre-computes CIFAR-10 latents (~4 min on CPU)
|
| 9 |
+
3. Trains a 1.5M-param recursive flow-matching denoiser (30 epochs, ~60 min CPU)
|
| 10 |
+
4. Generates class-conditional 32×32 images and saves them
|
| 11 |
+
5. Saves everything to a HuggingFace repo
|
| 12 |
+
|
| 13 |
+
No custom VAE training. No grey images. Works end-to-end.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import math, os, sys, time, json
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
import torch.nn.functional as F
|
| 20 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 21 |
+
from einops import rearrange
|
| 22 |
+
from typing import Optional, Dict, Any
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 26 |
+
print(f"Device: {DEVICE}")
|
| 27 |
+
|
| 28 |
+
# =============================================================================
|
| 29 |
+
# 1. MODEL ARCHITECTURE
|
| 30 |
+
# =============================================================================
|
| 31 |
+
|
| 32 |
+
class RMSNorm(nn.Module):
|
| 33 |
+
def __init__(self, d, eps=1e-6):
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.eps = eps
|
| 36 |
+
self.w = nn.Parameter(torch.ones(d))
|
| 37 |
+
def forward(self, x):
|
| 38 |
+
return x * (x.float().pow(2).mean(-1, keepdim=True) + self.eps).rsqrt().type_as(x) * self.w
|
| 39 |
+
|
| 40 |
+
class SwiGLU(nn.Module):
|
| 41 |
+
def __init__(self, d, hd=None):
|
| 42 |
+
super().__init__()
|
| 43 |
+
hd = hd or ((d * 8 // 3 + 7) // 8 * 8)
|
| 44 |
+
self.w1 = nn.Linear(d, hd, bias=False)
|
| 45 |
+
self.w2 = nn.Linear(hd, d, bias=False)
|
| 46 |
+
self.w3 = nn.Linear(d, hd, bias=False)
|
| 47 |
+
def forward(self, x):
|
| 48 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
| 49 |
+
|
| 50 |
+
class SpatialMixer(nn.Module):
|
| 51 |
+
"""Multi-head self-attention + depthwise conv for 2D locality."""
|
| 52 |
+
def __init__(self, d, nh=4, hd=32):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.nh, self.hd = nh, hd
|
| 55 |
+
inner = nh * hd
|
| 56 |
+
self.qkv = nn.Linear(d, 3 * inner, bias=False)
|
| 57 |
+
self.out = nn.Linear(inner, d, bias=False)
|
| 58 |
+
self.gate = nn.Sequential(nn.Linear(d, inner, bias=False), nn.SiLU())
|
| 59 |
+
self.dw = nn.Conv2d(inner, inner, 3, padding=1, groups=inner, bias=False)
|
| 60 |
+
self.norm = RMSNorm(inner)
|
| 61 |
+
|
| 62 |
+
def forward(self, x, h, w):
|
| 63 |
+
B, N, D = x.shape
|
| 64 |
+
q, k, v = self.qkv(x).chunk(3, dim=-1)
|
| 65 |
+
q = rearrange(q, 'b n (h d) -> b h n d', h=self.nh)
|
| 66 |
+
k = rearrange(k, 'b n (h d) -> b h n d', h=self.nh)
|
| 67 |
+
v = rearrange(v, 'b n (h d) -> b h n d', h=self.nh)
|
| 68 |
+
a = (q @ k.transpose(-2, -1)) * (self.hd ** -0.5)
|
| 69 |
+
o = rearrange(F.softmax(a, -1) @ v, 'b h n d -> b n (h d)')
|
| 70 |
+
o = self.norm(o)
|
| 71 |
+
# 2D locality
|
| 72 |
+
inner = self.nh * self.hd
|
| 73 |
+
lc = self.dw(rearrange(x[:, :, :inner], 'b (h w) d -> b d h w', h=h, w=w))
|
| 74 |
+
lc = rearrange(lc, 'b d h w -> b (h w) d')
|
| 75 |
+
return self.out(self.gate(x) * o + 0.1 * lc)
|
| 76 |
+
|
| 77 |
+
class DenoiseBlock(nn.Module):
|
| 78 |
+
"""AdaLN-modulated SpatialMixer + cross-attn + SwiGLU."""
|
| 79 |
+
def __init__(self, d, cd, nh=4, hd=32, fm=2.67):
|
| 80 |
+
super().__init__()
|
| 81 |
+
self.n1 = RMSNorm(d); self.n2 = RMSNorm(d)
|
| 82 |
+
self.mix = SpatialMixer(d, nh, hd)
|
| 83 |
+
self.ffn = SwiGLU(d, int(d * fm))
|
| 84 |
+
self.mod = nn.Sequential(nn.SiLU(), nn.Linear(cd, 6 * d))
|
| 85 |
+
# Cross-attn to condition tokens
|
| 86 |
+
self.cn = RMSNorm(d)
|
| 87 |
+
self.cq = nn.Linear(d, d, bias=False)
|
| 88 |
+
self.ckv = nn.Linear(cd, 2 * d, bias=False)
|
| 89 |
+
self.co = nn.Linear(d, d, bias=False)
|
| 90 |
+
self.cs = nn.Parameter(torch.zeros(1))
|
| 91 |
+
|
| 92 |
+
def forward(self, x, c, ctx=None, h=4, w=4):
|
| 93 |
+
s1, h1, g1, s2, h2, g2 = self.mod(c).chunk(6, -1)
|
| 94 |
+
xn = self.n1(x) * (1 + s1.unsqueeze(1)) + h1.unsqueeze(1)
|
| 95 |
+
x = x + g1.unsqueeze(1) * self.mix(xn, h, w)
|
| 96 |
+
if ctx is not None:
|
| 97 |
+
xc = self.cn(x); q = self.cq(xc)
|
| 98 |
+
k, v = self.ckv(ctx).chunk(2, -1)
|
| 99 |
+
a = F.softmax(q @ k.transpose(-2,-1) * (q.shape[-1]**-0.5), -1)
|
| 100 |
+
x = x + self.cs.tanh() * self.co(a @ v)
|
| 101 |
+
xn = self.n2(x) * (1 + s2.unsqueeze(1)) + h2.unsqueeze(1)
|
| 102 |
+
x = x + g2.unsqueeze(1) * self.ffn(xn)
|
| 103 |
+
return x
|
| 104 |
+
|
| 105 |
+
class RecursiveCore(nn.Module):
|
| 106 |
+
"""N shared blocks × T recursions with abstract state + IFT training."""
|
| 107 |
+
def __init__(self, lc=4, d=128, cd=128, nb=4, nh=4, hd=32,
|
| 108 |
+
ti=2, to=1, fm=2.67, ift=False):
|
| 109 |
+
super().__init__()
|
| 110 |
+
self.nb, self.ti, self.to_, self.ift = nb, ti, to, ift
|
| 111 |
+
self.inp = nn.Linear(lc, d)
|
| 112 |
+
self.tmb = nn.Sequential(nn.Linear(256, cd), nn.SiLU(), nn.Linear(cd, cd))
|
| 113 |
+
self.blk = nn.ModuleList([DenoiseBlock(d, cd, nh, hd, fm) for _ in range(nb)])
|
| 114 |
+
self.ag = nn.Parameter(torch.tensor(0.0))
|
| 115 |
+
self.ap = nn.Sequential(nn.Linear(d, d, bias=False), nn.SiLU(), nn.Linear(d, d, bias=False))
|
| 116 |
+
self.se = nn.Embedding(to * ti + 1, cd)
|
| 117 |
+
self.on = RMSNorm(d)
|
| 118 |
+
self.op = nn.Linear(d, lc)
|
| 119 |
+
nn.init.zeros_(self.op.weight); nn.init.zeros_(self.op.bias)
|
| 120 |
+
|
| 121 |
+
def _sinemb(self, t, d=256):
|
| 122 |
+
h = d // 2
|
| 123 |
+
f = torch.exp(torch.arange(h, device=t.device).float() * -(math.log(10000) / h))
|
| 124 |
+
a = t.unsqueeze(-1) * f.unsqueeze(0)
|
| 125 |
+
return torch.cat([a.sin(), a.cos()], -1)
|
| 126 |
+
|
| 127 |
+
def _blocks(self, z, c, ctx, h, w):
|
| 128 |
+
for b in self.blk: z = b(z, c, ctx, h, w)
|
| 129 |
+
return z
|
| 130 |
+
|
| 131 |
+
def _refine(self, z, cb, ctx, h, w):
|
| 132 |
+
za = z.mean(1, keepdim=True).expand_as(z)
|
| 133 |
+
s = 0
|
| 134 |
+
for j in range(self.to_):
|
| 135 |
+
za = za + self.ag.tanh() * self.ap(z.mean(1, keepdim=True).expand_as(z))
|
| 136 |
+
for i in range(self.ti):
|
| 137 |
+
se = self.se(torch.tensor([s], device=z.device)).expand(z.shape[0], -1)
|
| 138 |
+
zn = self._blocks(z + za, cb + se, ctx, h, w)
|
| 139 |
+
z = z + 0.5 * (zn - z)
|
| 140 |
+
s += 1
|
| 141 |
+
return z
|
| 142 |
+
|
| 143 |
+
def forward(self, zt, t, tg=None, ic=None):
|
| 144 |
+
B, C, H, W = zt.shape
|
| 145 |
+
z = self.inp(rearrange(zt, 'b c h w -> b (h w) c'))
|
| 146 |
+
if ic is not None:
|
| 147 |
+
z = z + self.inp(rearrange(ic, 'b c h w -> b (h w) c'))
|
| 148 |
+
c = self.tmb(self._sinemb(t))
|
| 149 |
+
if tg is not None: c = c + tg
|
| 150 |
+
if self.training and self.ift and self.to_ > 1:
|
| 151 |
+
with torch.no_grad():
|
| 152 |
+
for _ in range(self.to_ - 1): z = self._refine(z, c, None, H, W)
|
| 153 |
+
z = self._refine(z, c, None, H, W)
|
| 154 |
+
else:
|
| 155 |
+
z = self._refine(z, c, None, H, W)
|
| 156 |
+
return rearrange(self.op(self.on(z)), 'b (h w) c -> b c h w', h=H, w=W)
|
| 157 |
+
|
| 158 |
+
class LRF(nn.Module):
|
| 159 |
+
"""Complete model: RecursiveCore + class conditioner."""
|
| 160 |
+
def __init__(self, cfg=None):
|
| 161 |
+
super().__init__()
|
| 162 |
+
cfg = cfg or self.default()
|
| 163 |
+
self.cfg = cfg
|
| 164 |
+
nc = cfg.get('nc', 10)
|
| 165 |
+
self.core = RecursiveCore(
|
| 166 |
+
lc=cfg['lc'], d=cfg['d'], cd=cfg['cd'], nb=cfg['nb'],
|
| 167 |
+
nh=cfg['nh'], hd=cfg['hd'], ti=cfg['ti'], to=cfg['to'],
|
| 168 |
+
fm=cfg.get('fm', 2.67), ift=cfg.get('ift', False))
|
| 169 |
+
self.cemb = nn.Embedding(nc + 1, cfg['cd'])
|
| 170 |
+
self.null = nc
|
| 171 |
+
|
| 172 |
+
@staticmethod
|
| 173 |
+
def default():
|
| 174 |
+
return dict(lc=4, d=128, cd=128, nb=4, nh=4, hd=32, ti=2, to=1, fm=2.0, ift=False, nc=10)
|
| 175 |
+
|
| 176 |
+
def predict_v(self, zt, t, cls=None, cfg_drop=0.0):
|
| 177 |
+
B = zt.shape[0]
|
| 178 |
+
if cls is not None:
|
| 179 |
+
if self.training and cfg_drop > 0:
|
| 180 |
+
m = torch.rand(B, device=zt.device) < cfg_drop
|
| 181 |
+
cls = cls.clone(); cls[m] = self.null
|
| 182 |
+
c = self.cemb(cls)
|
| 183 |
+
else:
|
| 184 |
+
c = self.cemb(torch.full((B,), self.null, device=zt.device, dtype=torch.long))
|
| 185 |
+
return self.core(zt, t, tg=c)
|
| 186 |
+
|
| 187 |
+
def count(self):
|
| 188 |
+
return sum(p.numel() for p in self.parameters())
|
| 189 |
+
|
| 190 |
+
# =============================================================================
|
| 191 |
+
# 2. FLOW SCHEDULER
|
| 192 |
+
# =============================================================================
|
| 193 |
+
|
| 194 |
+
class FlowScheduler:
|
| 195 |
+
def add_noise(self, z0, eps, t):
|
| 196 |
+
t = t.view(-1, 1, 1, 1)
|
| 197 |
+
return (1 - t) * z0 + t * eps
|
| 198 |
+
|
| 199 |
+
def velocity(self, z0, eps):
|
| 200 |
+
return eps - z0
|
| 201 |
+
|
| 202 |
+
def sample_t(self, B, dev):
|
| 203 |
+
return torch.rand(B, device=dev).clamp(1e-4, 1 - 1e-4)
|
| 204 |
+
|
| 205 |
+
@torch.no_grad()
|
| 206 |
+
def sample(self, model, shape, cls=None, steps=50, cfg=3.0, dev='cpu'):
|
| 207 |
+
z = torch.randn(shape, device=dev)
|
| 208 |
+
ts = torch.linspace(1, 0, steps + 1, device=dev)
|
| 209 |
+
for i in range(steps):
|
| 210 |
+
tb = torch.full((shape[0],), ts[i].item(), device=dev)
|
| 211 |
+
dt = ts[i] - ts[i + 1]
|
| 212 |
+
if cfg > 1.0 and cls is not None:
|
| 213 |
+
vc = model.predict_v(z, tb, cls)
|
| 214 |
+
vu = model.predict_v(z, tb, None)
|
| 215 |
+
v = vu + cfg * (vc - vu)
|
| 216 |
+
else:
|
| 217 |
+
v = model.predict_v(z, tb, cls)
|
| 218 |
+
z = z - dt * v
|
| 219 |
+
return z
|
| 220 |
+
|
| 221 |
+
# =============================================================================
|
| 222 |
+
# 3. DATA + TAESD
|
| 223 |
+
# =============================================================================
|
| 224 |
+
|
| 225 |
+
def get_taesd(dev='cpu'):
|
| 226 |
+
from diffusers import AutoencoderTiny
|
| 227 |
+
vae = AutoencoderTiny.from_pretrained('madebyollin/taesd', torch_dtype=torch.float32)
|
| 228 |
+
vae.eval().to(dev)
|
| 229 |
+
for p in vae.parameters(): p.requires_grad_(False)
|
| 230 |
+
return vae
|
| 231 |
+
|
| 232 |
+
def get_cifar(root='/app/data'):
|
| 233 |
+
import torchvision, torchvision.transforms as T
|
| 234 |
+
tf = T.Compose([T.ToTensor(), T.Normalize([.5]*3, [.5]*3)])
|
| 235 |
+
tr = torchvision.datasets.CIFAR10(root, True, tf, download=True)
|
| 236 |
+
te = torchvision.datasets.CIFAR10(root, False, tf, download=True)
|
| 237 |
+
return tr, te
|
| 238 |
+
|
| 239 |
+
def precompute(vae, ds, bs=256, dev='cpu', cache=None):
|
| 240 |
+
if cache and os.path.exists(cache):
|
| 241 |
+
print(f" Loading cached latents from {cache}", flush=True)
|
| 242 |
+
d = torch.load(cache, weights_only=True)
|
| 243 |
+
return d['lat'], d['lab']
|
| 244 |
+
dl = DataLoader(ds, bs, shuffle=False, num_workers=0)
|
| 245 |
+
lats, labs = [], []
|
| 246 |
+
t0 = time.time()
|
| 247 |
+
with torch.no_grad():
|
| 248 |
+
for i, (img, lab) in enumerate(dl):
|
| 249 |
+
lats.append(vae.encode(img.to(dev)).latents.cpu())
|
| 250 |
+
labs.append(lab)
|
| 251 |
+
if (i+1) % 50 == 0 or i == 0:
|
| 252 |
+
print(f" batch {i+1}/{len(dl)} ({time.time()-t0:.0f}s)", flush=True)
|
| 253 |
+
lats, labs = torch.cat(lats), torch.cat(labs)
|
| 254 |
+
if cache:
|
| 255 |
+
os.makedirs(os.path.dirname(cache) or '.', exist_ok=True)
|
| 256 |
+
torch.save({'lat': lats, 'lab': labs}, cache)
|
| 257 |
+
print(f" Done: {lats.shape}, mean={lats.mean():.3f}, std={lats.std():.3f}", flush=True)
|
| 258 |
+
return lats, labs
|
| 259 |
+
|
| 260 |
+
# =============================================================================
|
| 261 |
+
# 4. TRAINING
|
| 262 |
+
# =============================================================================
|
| 263 |
+
|
| 264 |
+
def train(epochs=30, bs=64, lr=3e-4, dev=DEVICE, out='/app/lrf_out'):
|
| 265 |
+
os.makedirs(out, exist_ok=True)
|
| 266 |
+
print("=" * 60, flush=True)
|
| 267 |
+
print("LatentRecurrentFlow v3 — Training on CIFAR-10", flush=True)
|
| 268 |
+
print("=" * 60, flush=True)
|
| 269 |
+
|
| 270 |
+
# VAE
|
| 271 |
+
print("\n[1/5] Loading TAESD...", flush=True)
|
| 272 |
+
vae = get_taesd(dev)
|
| 273 |
+
print(f" TAESD: {sum(p.numel() for p in vae.parameters()):,} params (frozen)", flush=True)
|
| 274 |
+
|
| 275 |
+
# Data
|
| 276 |
+
print("\n[2/5] Loading CIFAR-10 + precomputing latents...", flush=True)
|
| 277 |
+
tr, te = get_cifar()
|
| 278 |
+
tr_lat, tr_lab = precompute(vae, tr, 256, dev, f'{out}/cache_train.pt')
|
| 279 |
+
te_lat, te_lab = precompute(vae, te, 256, dev, f'{out}/cache_test.pt')
|
| 280 |
+
|
| 281 |
+
# Verify VAE works
|
| 282 |
+
print("\n[2b] VAE sanity check...", flush=True)
|
| 283 |
+
with torch.no_grad():
|
| 284 |
+
imgs = torch.stack([tr[i][0] for i in range(8)]).to(dev)
|
| 285 |
+
rec = vae.decode(vae.encode(imgs).latents).sample
|
| 286 |
+
mse = F.mse_loss(rec, imgs).item()
|
| 287 |
+
print(f" Recon MSE = {mse:.4f} (should be <0.1)", flush=True)
|
| 288 |
+
save_grid(torch.cat([imgs[:4].cpu(), rec[:4].cpu()]), f'{out}/vae_check.png', 4)
|
| 289 |
+
|
| 290 |
+
# Model
|
| 291 |
+
print("\n[3/5] Creating model...", flush=True)
|
| 292 |
+
cfg = LRF.default()
|
| 293 |
+
model = LRF(cfg).to(dev)
|
| 294 |
+
print(f" Params: {model.count():,}", flush=True)
|
| 295 |
+
print(f" Depth: {cfg['to']}×{cfg['ti']}×{cfg['nb']} = {cfg['to']*cfg['ti']*cfg['nb']} eff. layers", flush=True)
|
| 296 |
+
|
| 297 |
+
# Train
|
| 298 |
+
print(f"\n[4/5] Training {epochs} epochs, bs={bs}, lr={lr}...", flush=True)
|
| 299 |
+
sched = FlowScheduler()
|
| 300 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01, betas=(0.9, 0.95))
|
| 301 |
+
lrs = torch.optim.lr_scheduler.CosineAnnealingLR(opt, epochs * (len(tr_lat)//bs), lr*0.01)
|
| 302 |
+
ema = {n: p.clone().detach() for n, p in model.named_parameters()}
|
| 303 |
+
losses = []
|
| 304 |
+
|
| 305 |
+
dl = DataLoader(TensorDataset(tr_lat, tr_lab), bs, shuffle=True, drop_last=True)
|
| 306 |
+
t0 = time.time()
|
| 307 |
+
for ep in range(epochs):
|
| 308 |
+
model.train()
|
| 309 |
+
el = 0; nb = 0
|
| 310 |
+
for lat, lab in dl:
|
| 311 |
+
lat, lab = lat.to(dev), lab.to(dev)
|
| 312 |
+
B = lat.shape[0]
|
| 313 |
+
t = sched.sample_t(B, dev)
|
| 314 |
+
eps = torch.randn_like(lat)
|
| 315 |
+
zt = sched.add_noise(lat, eps, t)
|
| 316 |
+
vp = model.predict_v(zt, t, lab, cfg_drop=0.1)
|
| 317 |
+
vt = sched.velocity(lat, eps)
|
| 318 |
+
lps = (vp - vt).pow(2).mean([1,2,3])
|
| 319 |
+
w = 1.0 / (t * (1-t) + 0.01); w = w / w.mean()
|
| 320 |
+
loss = (lps * w).mean()
|
| 321 |
+
opt.zero_grad(); loss.backward()
|
| 322 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 323 |
+
opt.step(); lrs.step()
|
| 324 |
+
with torch.no_grad():
|
| 325 |
+
for n, p in model.named_parameters():
|
| 326 |
+
ema[n].mul_(0.999).add_(p, alpha=0.001)
|
| 327 |
+
el += loss.item(); nb += 1
|
| 328 |
+
al = el / nb; losses.append(al)
|
| 329 |
+
elapsed = time.time() - t0
|
| 330 |
+
if (ep+1) % 5 == 0 or ep == 0:
|
| 331 |
+
print(f" Ep {ep+1:3d}/{epochs}: loss={al:.4f}, lr={opt.param_groups[0]['lr']:.1e}, "
|
| 332 |
+
f"time={elapsed:.0f}s", flush=True)
|
| 333 |
+
if (ep+1) % 10 == 0 or ep == epochs - 1:
|
| 334 |
+
# Sample with EMA
|
| 335 |
+
bak = {n: p.clone() for n, p in model.named_parameters()}
|
| 336 |
+
with torch.no_grad():
|
| 337 |
+
for n, p in model.named_parameters(): p.copy_(ema[n])
|
| 338 |
+
model.eval()
|
| 339 |
+
samps = gen(model, vae, sched, dev, 16, 20, 2.0)
|
| 340 |
+
save_grid(samps, f'{out}/ep{ep+1:03d}.png', 4)
|
| 341 |
+
with torch.no_grad():
|
| 342 |
+
for n, p in model.named_parameters(): p.copy_(bak[n])
|
| 343 |
+
|
| 344 |
+
# Final: swap to EMA permanently
|
| 345 |
+
with torch.no_grad():
|
| 346 |
+
for n, p in model.named_parameters(): p.copy_(ema[n])
|
| 347 |
+
model.eval()
|
| 348 |
+
|
| 349 |
+
# Save checkpoint
|
| 350 |
+
torch.save({'state': model.state_dict(), 'cfg': cfg, 'losses': losses}, f'{out}/model.pt')
|
| 351 |
+
|
| 352 |
+
# Final generation
|
| 353 |
+
print(f"\n[5/5] Generating final samples...", flush=True)
|
| 354 |
+
classes = ['airplane','auto','bird','cat','deer','dog','frog','horse','ship','truck']
|
| 355 |
+
all_s = []
|
| 356 |
+
for ci in range(10):
|
| 357 |
+
s = gen(model, vae, sched, dev, 4, 50, 3.0, ci)
|
| 358 |
+
all_s.append(s)
|
| 359 |
+
std = s.std().item()
|
| 360 |
+
print(f" {classes[ci]:10s}: std={std:.3f} {'✓' if std > 0.1 else '✗ FLAT'}", flush=True)
|
| 361 |
+
save_grid(torch.cat(all_s), f'{out}/final.png', 4)
|
| 362 |
+
|
| 363 |
+
# Loss plot
|
| 364 |
+
try:
|
| 365 |
+
import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt
|
| 366 |
+
plt.figure(figsize=(8,3)); plt.plot(losses); plt.xlabel('Epoch'); plt.ylabel('Loss')
|
| 367 |
+
plt.title('Training Loss'); plt.grid(True, alpha=.3)
|
| 368 |
+
plt.savefig(f'{out}/loss.png', dpi=100, bbox_inches='tight'); plt.close()
|
| 369 |
+
except: pass
|
| 370 |
+
|
| 371 |
+
print(f"\n{'='*60}", flush=True)
|
| 372 |
+
print(f"DONE. Best loss: {min(losses):.4f}. Files in {out}/", flush=True)
|
| 373 |
+
print(f"{'='*60}", flush=True)
|
| 374 |
+
return model, vae, losses
|
| 375 |
+
|
| 376 |
+
def gen(model, vae, sched, dev, n=8, steps=20, cfg=2.0, cls_id=None):
|
| 377 |
+
cls = torch.full((n,), cls_id if cls_id is not None else 0, dtype=torch.long, device=dev)
|
| 378 |
+
if cls_id is None: cls = torch.randint(0, 10, (n,), device=dev)
|
| 379 |
+
z = sched.sample(model, (n, 4, 4, 4), cls, steps, cfg, dev)
|
| 380 |
+
with torch.no_grad(): imgs = vae.decode(z.to(dev)).sample.clamp(-1, 1)
|
| 381 |
+
return imgs.cpu()
|
| 382 |
+
|
| 383 |
+
def save_grid(imgs, path, nr=8):
|
| 384 |
+
from PIL import Image
|
| 385 |
+
imgs = ((imgs + 1) / 2).clamp(0, 1)
|
| 386 |
+
import torchvision
|
| 387 |
+
g = torchvision.utils.make_grid(imgs, nrow=nr, padding=2)
|
| 388 |
+
arr = (g.permute(1,2,0).numpy() * 255).astype(np.uint8)
|
| 389 |
+
Image.fromarray(arr).save(path)
|
| 390 |
+
print(f" Saved: {path}", flush=True)
|
| 391 |
+
|
| 392 |
+
# =============================================================================
|
| 393 |
+
# 5. NOTEBOOK CONVERSION (Jupyter-compatible cells as functions)
|
| 394 |
+
# =============================================================================
|
| 395 |
+
|
| 396 |
+
def notebook_cell_1_setup():
|
| 397 |
+
"""Cell 1: Install & import."""
|
| 398 |
+
print("Installing dependencies...")
|
| 399 |
+
os.system("pip install -q torch torchvision einops diffusers safetensors huggingface_hub matplotlib pillow")
|
| 400 |
+
print("Done.")
|
| 401 |
+
|
| 402 |
+
def notebook_cell_2_architecture():
|
| 403 |
+
"""Cell 2: Show architecture details."""
|
| 404 |
+
cfg = LRF.default()
|
| 405 |
+
model = LRF(cfg)
|
| 406 |
+
print(f"LatentRecurrentFlow Architecture")
|
| 407 |
+
print(f"================================")
|
| 408 |
+
print(f"Latent channels: {cfg['lc']} (TAESD)")
|
| 409 |
+
print(f"Model dim: {cfg['d']}")
|
| 410 |
+
print(f"Shared blocks: {cfg['nb']}")
|
| 411 |
+
print(f"Recursions: {cfg['to']}×{cfg['ti']} = {cfg['to']*cfg['ti']}")
|
| 412 |
+
print(f"Effective depth: {cfg['to']*cfg['ti']*cfg['nb']} layers")
|
| 413 |
+
print(f"Total params: {model.count():,}")
|
| 414 |
+
print(f"FP32 size: {model.count()*4/1e6:.1f} MB")
|
| 415 |
+
print(f"INT8 size: {model.count()/1e6:.1f} MB")
|
| 416 |
+
return model
|
| 417 |
+
|
| 418 |
+
def notebook_cell_3_train():
|
| 419 |
+
"""Cell 3: Full training loop."""
|
| 420 |
+
return train(epochs=30, bs=64, lr=3e-4, out='/app/lrf_out')
|
| 421 |
+
|
| 422 |
+
def notebook_cell_4_generate(model, vae):
|
| 423 |
+
"""Cell 4: Generate and display images."""
|
| 424 |
+
sched = FlowScheduler()
|
| 425 |
+
classes = ['airplane','auto','bird','cat','deer','dog','frog','horse','ship','truck']
|
| 426 |
+
for ci, cn in enumerate(classes):
|
| 427 |
+
imgs = gen(model, vae, sched, DEVICE, 4, 50, 3.0, ci)
|
| 428 |
+
save_grid(imgs, f'/app/lrf_out/class_{cn}.png', 4)
|
| 429 |
+
print("All class images generated!")
|
| 430 |
+
|
| 431 |
+
def notebook_cell_5_push(repo_id='krystv/LatentRecurrentFlow'):
|
| 432 |
+
"""Cell 5: Push to HuggingFace Hub."""
|
| 433 |
+
from huggingface_hub import HfApi
|
| 434 |
+
api = HfApi()
|
| 435 |
+
out = '/app/lrf_out'
|
| 436 |
+
for f in os.listdir(out):
|
| 437 |
+
if f.endswith(('.pt', '.png', '.json')):
|
| 438 |
+
fp = os.path.join(out, f)
|
| 439 |
+
if os.path.getsize(fp) < 50_000_000: # Skip huge files
|
| 440 |
+
api.upload_file(path_or_fileobj=fp, path_in_repo=f'v3/{f}',
|
| 441 |
+
repo_id=repo_id, repo_type='model')
|
| 442 |
+
print(f" Uploaded v3/{f}")
|
| 443 |
+
print(f"Done! See https://huggingface.co/{repo_id}")
|
| 444 |
+
|
| 445 |
+
# =============================================================================
|
| 446 |
+
# MAIN
|
| 447 |
+
# =============================================================================
|
| 448 |
+
|
| 449 |
+
if __name__ == '__main__':
|
| 450 |
+
model, vae, losses = train(epochs=30, bs=64, lr=3e-4, out='/app/lrf_out')
|