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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# splat_trainer2.py — the fast trainer (faces folder -> better splat_decoder.onnx)
|
| 3 |
+
#
|
| 4 |
+
# Same architecture as splat_generator.py (latent 128, Gabor packets, anchor
|
| 5 |
+
# grid, complex phase head) so every existing tool — splat_cv5, probe, surf,
|
| 6 |
+
# atlas, zoom — works on the new model unchanged. What changed is SPEED:
|
| 7 |
+
#
|
| 8 |
+
# 1. CACHE ONCE. The old trainer decoded 200k JPEGs every epoch — that was
|
| 9 |
+
# the real bottleneck, not the GPU. First run builds faces_cache_S.npy
|
| 10 |
+
# (uint8, center-cropped, resized) with threaded cv2. Every later run
|
| 11 |
+
# starts in seconds.
|
| 12 |
+
# 2. DATASET LIVES ON THE GPU. 202k x 96x96x3 uint8 = 5.6 GB -> fits a 12GB
|
| 13 |
+
# card next to the model (64px = 2.5 GB). Batches are fancy-indexed on
|
| 14 |
+
# device; there is NO DataLoader, no workers, no H2D copy per step.
|
| 15 |
+
# Falls back to pinned CPU memory automatically if it doesn't fit.
|
| 16 |
+
# 3. VECTORIZED RENDERER. The per-channel python loop is now shared-carrier
|
| 17 |
+
# multiply-sums per chunk (env*cos and env*sin are computed once, not three times).
|
| 18 |
+
# Verified equal to the old loop renderer to float tolerance in --smoke.
|
| 19 |
+
# 4. STEPS, NOT EPOCHS. VAEs converge per gradient step; random batches
|
| 20 |
+
# from the resident tensor, cosine LR with warmup, KL beta ramped in
|
| 21 |
+
# steps. --steps 30000 at batch 96 sees ~2.9M images (14 "epochs") in
|
| 22 |
+
# roughly the wall time the old loop needed for 2.
|
| 23 |
+
# 5. bf16 autocast for encoder/decoder (renderer stays fp32, as always),
|
| 24 |
+
# fused Adam when available, gradient checkpointing OFF by default
|
| 25 |
+
# (it halves VRAM but doubles renderer compute — flag it back on only
|
| 26 |
+
# if you OOM).
|
| 27 |
+
#
|
| 28 |
+
# python splat_trainer2.py --data_dir E:/path/to/faces # train
|
| 29 |
+
# python splat_trainer2.py --export # -> onnx
|
| 30 |
+
# python splat_trainer2.py --smoke # CPU test
|
| 31 |
+
#
|
| 32 |
+
# The export writes splat_decoder.onnx with the exact input/output names
|
| 33 |
+
# ("z_latent" / "rendered_image", opset 17, dynamic batch) the cv5 tools use.
|
| 34 |
+
#
|
| 35 |
+
# HONESTY: --smoke was run end-to-end (train -> export -> cv.dnn reload ->
|
| 36 |
+
# torch/ONNX parity) on CPU in the sandbox. The full-speed GPU path (bf16,
|
| 37 |
+
# fused Adam, resident-tensor indexing) follows the same code but its
|
| 38 |
+
# throughput numbers are yours to measure. PerceptionLab discipline: do not
|
| 39 |
+
# hype, do not lie, just show.
|
| 40 |
+
|
| 41 |
+
import argparse, glob, math, os, sys, time
|
| 42 |
+
import numpy as np
|
| 43 |
+
import torch
|
| 44 |
+
import torch.nn as nn
|
| 45 |
+
import torch.nn.functional as F
|
| 46 |
+
|
| 47 |
+
K = 11 # dpx,dpy,ls,th,lf + (a,b) x 3 channels
|
| 48 |
+
LATENT = 128 # fixed: every downstream tool assumes it
|
| 49 |
+
|
| 50 |
+
# ======================================================================
|
| 51 |
+
# 1) preprocessing cache: faces folder -> uint8 npy, once
|
| 52 |
+
# ======================================================================
|
| 53 |
+
def build_cache(data_dir, size, cache_path):
|
| 54 |
+
import cv2 as cv
|
| 55 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 56 |
+
exts = ("*.jpg", "*.jpeg", "*.png", "*.bmp", "*.webp")
|
| 57 |
+
paths = sorted(p for e in exts for p in glob.glob(os.path.join(data_dir, e)))
|
| 58 |
+
if not paths:
|
| 59 |
+
raise RuntimeError(f"no images in {data_dir}")
|
| 60 |
+
n = len(paths)
|
| 61 |
+
print(f"caching {n} images at {size}px -> {cache_path} (one time)")
|
| 62 |
+
arr = np.lib.format.open_memmap(cache_path, mode="w+", dtype=np.uint8,
|
| 63 |
+
shape=(n, size, size, 3))
|
| 64 |
+
def work(i):
|
| 65 |
+
im = cv.imread(paths[i], cv.IMREAD_COLOR)
|
| 66 |
+
if im is None:
|
| 67 |
+
return i, False
|
| 68 |
+
h, w = im.shape[:2]
|
| 69 |
+
s = min(h, w)
|
| 70 |
+
im = im[(h - s) // 2:(h + s) // 2, (w - s) // 2:(w + s) // 2]
|
| 71 |
+
im = cv.resize(im, (size, size), interpolation=cv.INTER_AREA)
|
| 72 |
+
arr[i] = im[:, :, ::-1] # BGR -> RGB
|
| 73 |
+
return i, True
|
| 74 |
+
t0, done = time.time(), 0
|
| 75 |
+
with ThreadPoolExecutor(max_workers=os.cpu_count()) as ex:
|
| 76 |
+
for i, ok in ex.map(work, range(n)):
|
| 77 |
+
done += 1
|
| 78 |
+
if done % 20000 == 0:
|
| 79 |
+
r = done / (time.time() - t0)
|
| 80 |
+
print(f" {done}/{n} ({r:.0f} img/s, eta {(n-done)/r/60:.1f} min)")
|
| 81 |
+
arr.flush()
|
| 82 |
+
print(f"cache built in {(time.time()-t0)/60:.1f} min")
|
| 83 |
+
|
| 84 |
+
def load_resident(cache_path, dev):
|
| 85 |
+
"""Whole dataset as a uint8 tensor, on GPU if it fits."""
|
| 86 |
+
a = np.load(cache_path, mmap_mode="r")
|
| 87 |
+
t = torch.from_numpy(np.ascontiguousarray(a))
|
| 88 |
+
if dev.type == "cuda":
|
| 89 |
+
need = t.numel()
|
| 90 |
+
free, _ = torch.cuda.mem_get_info()
|
| 91 |
+
if need < free - 3e9: # leave 3GB for training
|
| 92 |
+
t = t.to(dev)
|
| 93 |
+
print(f"dataset resident on GPU: {need/1e9:.2f} GB, {len(t)} images")
|
| 94 |
+
return t
|
| 95 |
+
t = t.pin_memory()
|
| 96 |
+
print(f"dataset pinned on CPU ({need/1e9:.2f} GB too big for VRAM)")
|
| 97 |
+
return t
|
| 98 |
+
|
| 99 |
+
def batch_from(data, idx, dev):
|
| 100 |
+
x = data[idx]
|
| 101 |
+
if x.device != dev:
|
| 102 |
+
x = x.to(dev, non_blocking=True)
|
| 103 |
+
return x.permute(0, 3, 1, 2).float().div_(255.0)
|
| 104 |
+
|
| 105 |
+
# ======================================================================
|
| 106 |
+
# 2) model — identical math to splat_generator.py, faster renderer
|
| 107 |
+
# ======================================================================
|
| 108 |
+
class GaborRenderer(nn.Module):
|
| 109 |
+
def __init__(self, image_size=96, num_packets=256, chunk=64, use_checkpoint=False):
|
| 110 |
+
super().__init__()
|
| 111 |
+
self.H = self.W = image_size
|
| 112 |
+
self.N, self.chunk, self.use_checkpoint = num_packets, chunk, use_checkpoint
|
| 113 |
+
gy, gx = torch.meshgrid(torch.linspace(0, 1, image_size),
|
| 114 |
+
torch.linspace(0, 1, image_size), indexing="ij")
|
| 115 |
+
self.register_buffer("GX", gx[None, None].contiguous())
|
| 116 |
+
self.register_buffer("GY", gy[None, None].contiguous())
|
| 117 |
+
side = int(math.ceil(math.sqrt(num_packets)))
|
| 118 |
+
ax = torch.linspace(0.08, 0.92, side)
|
| 119 |
+
anch = torch.stack(torch.meshgrid(ax, ax, indexing="ij"), -1).reshape(-1, 2)[:num_packets]
|
| 120 |
+
anch = torch.clamp(anch, 1e-3, 1 - 1e-3)
|
| 121 |
+
self.register_buffer("anchor_logit", torch.log(anch / (1 - anch)))
|
| 122 |
+
|
| 123 |
+
def activate(self, raw):
|
| 124 |
+
px = torch.sigmoid(self.anchor_logit[:, 0][None] + raw[..., 0])
|
| 125 |
+
py = torch.sigmoid(self.anchor_logit[:, 1][None] + raw[..., 1])
|
| 126 |
+
sigma = 0.012 + 0.14 * torch.sigmoid(raw[..., 2])
|
| 127 |
+
theta = raw[..., 3]
|
| 128 |
+
freq = 1.0 + 15.0 * torch.sigmoid(raw[..., 4])
|
| 129 |
+
coeff = torch.tanh(raw[..., 5:11]).reshape(*raw.shape[:2], 3, 2)
|
| 130 |
+
return px, py, sigma, theta, freq, coeff
|
| 131 |
+
|
| 132 |
+
def _chunk(self, px, py, sigma, theta, freq, coeff):
|
| 133 |
+
"""Vectorized: env*cos / env*sin once, channels via one einsum each."""
|
| 134 |
+
px_ = px[..., None, None]; py_ = py[..., None, None]
|
| 135 |
+
s_ = sigma[..., None, None]; th = theta[..., None, None]
|
| 136 |
+
f_ = freq[..., None, None]
|
| 137 |
+
dx = self.GX - px_; dy = self.GY - py_
|
| 138 |
+
xr = dx * torch.cos(th) + dy * torch.sin(th)
|
| 139 |
+
env = torch.exp(-(dx * dx + dy * dy) / (2 * s_ * s_))
|
| 140 |
+
ec = env * torch.cos(2 * math.pi * f_ * xr) # (B,n,H,W)
|
| 141 |
+
es = env * torch.sin(2 * math.pi * f_ * xr)
|
| 142 |
+
a, b = coeff[..., 0], coeff[..., 1] # (B,n,3)
|
| 143 |
+
# per-channel multiply-sum: ec/es are still computed ONCE (the speed
|
| 144 |
+
# win over the old loop), and the graph is pure Mul+ReduceSum+Stack —
|
| 145 |
+
# no Einsum, no dynamic Reshape — so it runs bit-identically on cv2
|
| 146 |
+
# 4.x legacy dnn AND cv5 ENGINE_NEW, at any batch size
|
| 147 |
+
chans = [(a[:, :, c, None, None] * ec).sum(1)
|
| 148 |
+
- (b[:, :, c, None, None] * es).sum(1) for c in range(3)]
|
| 149 |
+
return torch.stack(chans, dim=1)
|
| 150 |
+
|
| 151 |
+
def forward(self, raw):
|
| 152 |
+
raw = raw.float() # fp32 always
|
| 153 |
+
px, py, sigma, theta, freq, coeff = self.activate(raw)
|
| 154 |
+
out = None # no zeros(batch,...): keeps the ONNX
|
| 155 |
+
for i in range(0, self.N, self.chunk): # graph free of ConstantOfShape
|
| 156 |
+
sl = slice(i, i + self.chunk)
|
| 157 |
+
args = (px[:, sl], py[:, sl], sigma[:, sl],
|
| 158 |
+
theta[:, sl], freq[:, sl], coeff[:, sl])
|
| 159 |
+
if self.use_checkpoint and self.training:
|
| 160 |
+
from torch.utils.checkpoint import checkpoint
|
| 161 |
+
c = checkpoint(self._chunk, *args, use_reentrant=False)
|
| 162 |
+
else:
|
| 163 |
+
c = self._chunk(*args)
|
| 164 |
+
out = c if out is None else out + c
|
| 165 |
+
return torch.sigmoid(out)
|
| 166 |
+
|
| 167 |
+
class Encoder(nn.Module):
|
| 168 |
+
def __init__(self, image_size=96, latent=LATENT, ch=32):
|
| 169 |
+
super().__init__()
|
| 170 |
+
layers, c_in, sz, c = [], 3, image_size, ch
|
| 171 |
+
while sz > 4:
|
| 172 |
+
layers += [nn.Conv2d(c_in, c, 4, 2, 1), nn.BatchNorm2d(c),
|
| 173 |
+
nn.LeakyReLU(0.2, True)]
|
| 174 |
+
c_in, sz, c = c, sz // 2, min(c * 2, 512)
|
| 175 |
+
self.conv = nn.Sequential(*layers)
|
| 176 |
+
self.flat = c_in * sz * sz
|
| 177 |
+
self.fc_mu = nn.Linear(self.flat, latent)
|
| 178 |
+
self.fc_lv = nn.Linear(self.flat, latent)
|
| 179 |
+
def forward(self, x):
|
| 180 |
+
h = self.conv(x).flatten(1)
|
| 181 |
+
return self.fc_mu(h), self.fc_lv(h)
|
| 182 |
+
|
| 183 |
+
class Decoder(nn.Module):
|
| 184 |
+
def __init__(self, latent=LATENT, num_packets=256, hidden=512):
|
| 185 |
+
super().__init__()
|
| 186 |
+
self.N = num_packets
|
| 187 |
+
self.net = nn.Sequential(
|
| 188 |
+
nn.Linear(latent, hidden), nn.LeakyReLU(0.2, True),
|
| 189 |
+
nn.Linear(hidden, hidden), nn.LeakyReLU(0.2, True),
|
| 190 |
+
nn.Linear(hidden, num_packets * K))
|
| 191 |
+
nn.init.zeros_(self.net[-1].bias)
|
| 192 |
+
self.net[-1].weight.data *= 0.1
|
| 193 |
+
def forward(self, z):
|
| 194 |
+
return self.net(z).view(-1, self.N, K)
|
| 195 |
+
|
| 196 |
+
class SplatVAE(nn.Module):
|
| 197 |
+
def __init__(self, image_size=96, num_packets=256, chunk=64, ckpt=False):
|
| 198 |
+
super().__init__()
|
| 199 |
+
self.enc = Encoder(image_size)
|
| 200 |
+
self.dec = Decoder(LATENT, num_packets)
|
| 201 |
+
self.ren = GaborRenderer(image_size, num_packets, chunk, ckpt)
|
| 202 |
+
self.latent = LATENT
|
| 203 |
+
|
| 204 |
+
def kl(mu, lv):
|
| 205 |
+
return -0.5 * torch.mean(torch.sum(1 + lv - mu.pow(2) - lv.exp(), dim=1))
|
| 206 |
+
|
| 207 |
+
# ======================================================================
|
| 208 |
+
# 3) training — steps, resident data, bf16, cosine LR
|
| 209 |
+
# ======================================================================
|
| 210 |
+
def train(args, dev):
|
| 211 |
+
cache = os.path.join(args.out, f"faces_cache_{args.image_size}.npy")
|
| 212 |
+
os.makedirs(args.out, exist_ok=True)
|
| 213 |
+
if not os.path.exists(cache):
|
| 214 |
+
build_cache(args.data_dir, args.image_size, cache)
|
| 215 |
+
data = load_resident(cache, dev)
|
| 216 |
+
n = len(data)
|
| 217 |
+
|
| 218 |
+
model = SplatVAE(args.image_size, args.num_packets, args.chunk,
|
| 219 |
+
args.checkpointing).to(dev)
|
| 220 |
+
if args.resume and os.path.exists(args.resume):
|
| 221 |
+
model.load_state_dict(torch.load(args.resume, map_location=dev)["sd"])
|
| 222 |
+
print("resumed", args.resume)
|
| 223 |
+
print(f"params {sum(p.numel() for p in model.parameters())/1e6:.2f}M "
|
| 224 |
+
f"steps {args.steps} batch {args.batch} res {args.image_size}")
|
| 225 |
+
|
| 226 |
+
fused = dev.type == "cuda"
|
| 227 |
+
opt = torch.optim.Adam(model.parameters(), lr=args.lr, fused=fused)
|
| 228 |
+
warm = max(1, args.steps // 50)
|
| 229 |
+
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(
|
| 230 |
+
(s + 1) / warm, 0.5 * (1 + math.cos(math.pi * s / args.steps))))
|
| 231 |
+
use_bf16 = dev.type == "cuda" and torch.cuda.is_bf16_supported()
|
| 232 |
+
print(f"autocast bf16: {use_bf16} fused adam: {fused} "
|
| 233 |
+
f"checkpointing: {args.checkpointing}")
|
| 234 |
+
|
| 235 |
+
g = torch.Generator(device="cpu").manual_seed(0)
|
| 236 |
+
fixed_idx = torch.randint(0, n, (32,), generator=g)
|
| 237 |
+
z_fixed = torch.randn(64, LATENT, device=dev)
|
| 238 |
+
logf = open(os.path.join(args.out, "loss.csv"), "a")
|
| 239 |
+
t0, run_rec, run_kl, last = time.time(), 0.0, 0.0, 0
|
| 240 |
+
model.train()
|
| 241 |
+
for step in range(1, args.steps + 1):
|
| 242 |
+
idx = torch.randint(0, n, (args.batch,), generator=g)
|
| 243 |
+
x = batch_from(data, idx, dev)
|
| 244 |
+
beta = args.beta * min(1.0, step / max(1, args.beta_warmup_steps))
|
| 245 |
+
opt.zero_grad(set_to_none=True)
|
| 246 |
+
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
|
| 247 |
+
mu, lv = model.enc(x)
|
| 248 |
+
z = mu + torch.randn_like(mu) * torch.exp(0.5 * lv)
|
| 249 |
+
raw = model.dec(z)
|
| 250 |
+
recon = model.ren(raw) # fp32 renderer
|
| 251 |
+
rec = F.mse_loss(recon, x)
|
| 252 |
+
# floater penalty: charge amplitude carried by needle-thin envelopes.
|
| 253 |
+
# the floater strategy = sigma -> min, amp -> max (a bright orphan dot
|
| 254 |
+
# that patches one pixel). amp^2 * max(SIGMA_REF/sigma - 1, 0) prices
|
| 255 |
+
# point-brightness: zero cost above SIGMA_REF, growing cost as the
|
| 256 |
+
# envelope collapses toward the floor. gamma_floater=0 disables.
|
| 257 |
+
if args.gamma_floater > 0:
|
| 258 |
+
_, _, sg, _, _, cf = model.ren.activate(raw.float())
|
| 259 |
+
amp2 = cf.pow(2).sum(dim=(-1, -2)) # (B,N) per-packet energy
|
| 260 |
+
flo = (amp2 * (args.sigma_ref / sg - 1.0).clamp(min=0)).mean()
|
| 261 |
+
else:
|
| 262 |
+
flo = torch.zeros((), device=x.device)
|
| 263 |
+
loss = rec + beta * kl(mu, lv) + args.gamma_floater * flo
|
| 264 |
+
loss.backward()
|
| 265 |
+
nn.utils.clip_grad_norm_(model.parameters(), 5.0)
|
| 266 |
+
opt.step(); sched.step()
|
| 267 |
+
run_rec += rec.item(); run_kl += kl(mu, lv).item()
|
| 268 |
+
|
| 269 |
+
if step % args.log_every == 0 or step == args.steps:
|
| 270 |
+
nb = step - last; last = step
|
| 271 |
+
ips = nb * args.batch / (time.time() - t0); t0 = time.time()
|
| 272 |
+
psnr = 10 * math.log10(1.0 / max(run_rec / nb, 1e-9))
|
| 273 |
+
print(f"step {step:6d}/{args.steps} rec {run_rec/nb:.4f} "
|
| 274 |
+
f"(PSNR {psnr:4.1f}) kl {run_kl/nb:7.1f} beta {beta:.2f} "
|
| 275 |
+
f"lr {sched.get_last_lr()[0]:.2e} {ips:6.0f} img/s")
|
| 276 |
+
logf.write(f"{step},{run_rec/nb:.6f},{run_kl/nb:.6f}\n"); logf.flush()
|
| 277 |
+
run_rec = run_kl = 0.0
|
| 278 |
+
model.eval()
|
| 279 |
+
with torch.no_grad():
|
| 280 |
+
torch.save({"sd": model.state_dict(),
|
| 281 |
+
"image_size": args.image_size,
|
| 282 |
+
"num_packets": args.num_packets},
|
| 283 |
+
os.path.join(args.out, "model2.pt"))
|
| 284 |
+
fx = batch_from(data, fixed_idx, dev)
|
| 285 |
+
mu, _ = model.enc(fx)
|
| 286 |
+
rc = model.ren(model.dec(mu))
|
| 287 |
+
grid(torch.cat([fx, rc], 0),
|
| 288 |
+
os.path.join(args.out, f"recon_{step:06d}.png"))
|
| 289 |
+
grid(model.ren(model.dec(z_fixed)),
|
| 290 |
+
os.path.join(args.out, f"sample_{step:06d}.png"))
|
| 291 |
+
model.train()
|
| 292 |
+
print("done ->", os.path.join(args.out, "model2.pt"),
|
| 293 |
+
" | now: python splat_trainer2.py --export")
|
| 294 |
+
|
| 295 |
+
def grid(t, path, nrow=8):
|
| 296 |
+
import cv2 as cv
|
| 297 |
+
t = t.clamp(0, 1).cpu().numpy()
|
| 298 |
+
n, _, h, w = t.shape
|
| 299 |
+
rows = int(math.ceil(n / nrow))
|
| 300 |
+
g = np.zeros((rows * h, nrow * w, 3), np.float32)
|
| 301 |
+
for i in range(n):
|
| 302 |
+
r, c = divmod(i, nrow)
|
| 303 |
+
g[r*h:(r+1)*h, c*w:(c+1)*w] = np.transpose(t[i], (1, 2, 0))
|
| 304 |
+
cv.imwrite(path, (g[:, :, ::-1] * 255).astype(np.uint8))
|
| 305 |
+
|
| 306 |
+
# ======================================================================
|
| 307 |
+
# 4) ONNX export — same contract as the cv5 tools expect
|
| 308 |
+
# ======================================================================
|
| 309 |
+
class ExportHead(nn.Module):
|
| 310 |
+
def __init__(self, model):
|
| 311 |
+
super().__init__()
|
| 312 |
+
self.dec, self.ren = model.dec, model.ren
|
| 313 |
+
self.ren.use_checkpoint = False
|
| 314 |
+
def forward(self, z):
|
| 315 |
+
return self.ren(self.dec(z))
|
| 316 |
+
|
| 317 |
+
def export(args, dev):
|
| 318 |
+
ck = torch.load(os.path.join(args.out, "model2.pt"), map_location="cpu")
|
| 319 |
+
model = SplatVAE(ck["image_size"], ck["num_packets"], args.chunk)
|
| 320 |
+
model.load_state_dict(ck["sd"]); model.eval()
|
| 321 |
+
head = ExportHead(model)
|
| 322 |
+
dummy = torch.randn(1, LATENT)
|
| 323 |
+
out = args.onnx or "splat_decoder.onnx"
|
| 324 |
+
torch.onnx.export(head, dummy, out, export_params=True, opset_version=17,
|
| 325 |
+
do_constant_folding=True, input_names=["z_latent"],
|
| 326 |
+
output_names=["rendered_image"],
|
| 327 |
+
dynamic_axes={"z_latent": {0: "batch"},
|
| 328 |
+
"rendered_image": {0: "batch"}},
|
| 329 |
+
dynamo=False)
|
| 330 |
+
mb = os.path.getsize(out) / 1e6
|
| 331 |
+
print(f"exported {out} ({mb:.1f} MB, {ck['image_size']}px, "
|
| 332 |
+
f"{ck['num_packets']} packets) — drop-in for the cv5 tools")
|
| 333 |
+
|
| 334 |
+
# ======================================================================
|
| 335 |
+
# 5) smoke — CPU end-to-end: loop-vs-einsum parity, train, export, cv.dnn parity
|
| 336 |
+
# ======================================================================
|
| 337 |
+
def smoke():
|
| 338 |
+
ok = True
|
| 339 |
+
def check(name, cond, note=""):
|
| 340 |
+
nonlocal ok; ok &= bool(cond)
|
| 341 |
+
print(f" [{'PASS' if cond else 'FAIL'}] {name} {note}")
|
| 342 |
+
torch.manual_seed(0)
|
| 343 |
+
dev = torch.device("cpu")
|
| 344 |
+
|
| 345 |
+
# (a) vectorized renderer == original per-channel loop renderer
|
| 346 |
+
ren = GaborRenderer(32, 16, chunk=8)
|
| 347 |
+
raw = torch.randn(2, 16, K) * 0.5
|
| 348 |
+
with torch.no_grad():
|
| 349 |
+
fast = ren(raw)
|
| 350 |
+
px, py, sg, th, fq, cf = ren.activate(raw.float())
|
| 351 |
+
outs = []
|
| 352 |
+
for c in range(3): # the old loop, verbatim
|
| 353 |
+
px_ = px[..., None, None]; py_ = py[..., None, None]
|
| 354 |
+
s_ = sg[..., None, None]; t_ = th[..., None, None]
|
| 355 |
+
f_ = fq[..., None, None]
|
| 356 |
+
dx = ren.GX - px_; dy = ren.GY - py_
|
| 357 |
+
xr = dx * torch.cos(t_) + dy * torch.sin(t_)
|
| 358 |
+
env = torch.exp(-(dx*dx + dy*dy) / (2*s_*s_))
|
| 359 |
+
a = cf[:, :, c, 0][..., None, None]; b = cf[:, :, c, 1][..., None, None]
|
| 360 |
+
outs.append((env * (a*torch.cos(2*math.pi*f_*xr)
|
| 361 |
+
- b*torch.sin(2*math.pi*f_*xr))).sum(1))
|
| 362 |
+
slow = torch.sigmoid(torch.stack(outs, 1))
|
| 363 |
+
err = (fast - slow).abs().max().item()
|
| 364 |
+
check("einsum renderer == loop renderer", err < 1e-5, f"max|d| {err:.2e}")
|
| 365 |
+
|
| 366 |
+
# (b) tiny synthetic cache + short training run: loss must fall
|
| 367 |
+
import tempfile, cv2 as cv
|
| 368 |
+
tmp = tempfile.mkdtemp()
|
| 369 |
+
imdir = os.path.join(tmp, "imgs"); os.makedirs(imdir)
|
| 370 |
+
rng = np.random.default_rng(0)
|
| 371 |
+
for i in range(24):
|
| 372 |
+
im = np.zeros((40, 36, 3), np.uint8)
|
| 373 |
+
cv.circle(im, (rng.integers(8, 28), rng.integers(8, 32)),
|
| 374 |
+
rng.integers(4, 10), tuple(int(v) for v in rng.integers(60, 255, 3)), -1)
|
| 375 |
+
cv.imwrite(os.path.join(imdir, f"{i:03d}.png"), im)
|
| 376 |
+
a = argparse.Namespace(
|
| 377 |
+
data_dir=imdir, out=tmp, image_size=32, num_packets=16, chunk=8,
|
| 378 |
+
batch=8, steps=60, lr=3e-3, beta=1e-4, beta_warmup_steps=30,
|
| 379 |
+
log_every=30, resume="", checkpointing=False, gamma_floater=0.02,
|
| 380 |
+
sigma_ref=0.03, onnx=os.path.join(tmp, "t.onnx"))
|
| 381 |
+
import io, contextlib
|
| 382 |
+
buf = io.StringIO()
|
| 383 |
+
with contextlib.redirect_stdout(buf):
|
| 384 |
+
train(a, dev)
|
| 385 |
+
lines = [l for l in buf.getvalue().splitlines() if l.startswith("step")]
|
| 386 |
+
r0 = float(lines[0].split("rec")[1].split("(")[0])
|
| 387 |
+
r1 = float(lines[-1].split("rec")[1].split("(")[0])
|
| 388 |
+
check("training loss falls", r1 < r0, f"{r0:.4f} -> {r1:.4f}")
|
| 389 |
+
check("cache built", os.path.exists(os.path.join(tmp, "faces_cache_32.npy")))
|
| 390 |
+
|
| 391 |
+
# (c) export + cv.dnn reload + parity with torch
|
| 392 |
+
with contextlib.redirect_stdout(buf):
|
| 393 |
+
export(a, dev)
|
| 394 |
+
check("onnx written", os.path.exists(a.onnx))
|
| 395 |
+
ck = torch.load(os.path.join(tmp, "model2.pt"), map_location="cpu")
|
| 396 |
+
m = SplatVAE(32, 16, 8); m.load_state_dict(ck["sd"]); m.eval()
|
| 397 |
+
z = torch.randn(3, LATENT)
|
| 398 |
+
with torch.no_grad():
|
| 399 |
+
want = ExportHead(m)(z).numpy()
|
| 400 |
+
net = cv.dnn.readNetFromONNX(a.onnx)
|
| 401 |
+
net.setInput(z.numpy(), "z_latent")
|
| 402 |
+
got = net.forward("rendered_image")
|
| 403 |
+
err = float(np.abs(got - want).max())
|
| 404 |
+
check("cv.dnn output == torch output", err < 1e-4,
|
| 405 |
+
f"max|d| {err:.2e}, batch of 3 through dynamic axis")
|
| 406 |
+
print("smoke:", "ALL PASS" if ok else "FAILURES ABOVE")
|
| 407 |
+
return 0 if ok else 1
|
| 408 |
+
|
| 409 |
+
# ======================================================================
|
| 410 |
+
if __name__ == "__main__":
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("--data_dir", default="./faces")
|
| 413 |
+
ap.add_argument("--out", default="./runs/splat2")
|
| 414 |
+
ap.add_argument("--image_size", type=int, default=96)
|
| 415 |
+
ap.add_argument("--num_packets", type=int, default=256)
|
| 416 |
+
ap.add_argument("--chunk", type=int, default=64)
|
| 417 |
+
ap.add_argument("--batch", type=int, default=96)
|
| 418 |
+
ap.add_argument("--steps", type=int, default=30000)
|
| 419 |
+
ap.add_argument("--lr", type=float, default=3e-4)
|
| 420 |
+
ap.add_argument("--beta", type=float, default=1.0)
|
| 421 |
+
ap.add_argument("--beta_warmup_steps", type=int, default=3000)
|
| 422 |
+
ap.add_argument("--gamma_floater", type=float, default=0.02,
|
| 423 |
+
help="anti-floater energy penalty (0 = off)")
|
| 424 |
+
ap.add_argument("--sigma_ref", type=float, default=0.03,
|
| 425 |
+
help="envelopes thinner than this pay the penalty")
|
| 426 |
+
ap.add_argument("--log_every", type=int, default=250)
|
| 427 |
+
ap.add_argument("--resume", default="")
|
| 428 |
+
ap.add_argument("--checkpointing", action="store_true",
|
| 429 |
+
help="halve VRAM, double renderer compute (only if OOM)")
|
| 430 |
+
ap.add_argument("--export", action="store_true")
|
| 431 |
+
ap.add_argument("--onnx", default=None)
|
| 432 |
+
ap.add_argument("--smoke", action="store_true")
|
| 433 |
+
args = ap.parse_args()
|
| 434 |
+
if args.smoke:
|
| 435 |
+
sys.exit(smoke())
|
| 436 |
+
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 437 |
+
print("device:", dev)
|
| 438 |
+
if args.export:
|
| 439 |
+
export(args, dev)
|
| 440 |
+
else:
|
| 441 |
+
train(args, dev)
|