abidlabs's picture
download
raw
20.8 kB
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "torch==2.14.1",
# "torchvision==0.29.1",
# "piq==0.8.0",
# "pytorch-fid==0.3.0",
# "scipy<1.15", # pytorch-fid 0.3.0 calls scipy.linalg.sqrtm(disp=False), removed in scipy 1.15
# "trackio==0.40.0",
# "gdown",
# "matplotlib",
# "pillow",
# "numpy",
# "tqdm",
# "typing-extensions",
# ]
# ///
"""
Reproduction driver for arXiv:2510.08570 ("Who Said Neural Networks Aren't
Linear?", the Linearizer paper) - core scope: one-step flow matching on MNIST.
Grounded in the official repo assafshocher/Linearizer @ adfca2c (fetched and
imported verbatim); training/eval logic adapted from
one_step/train_one_step.py and one_step/test_one_step.py.
What it does:
1. Builds the official MNIST Linearizer (InverseUnet g with 4 invertible
blocks, rank-8 time-dependent LoRA core, dim 1024).
2. Trains flow matching with the official loss (induced-space MSE +
noisy reconstruction terms), logging to trackio.
3. Evaluates the paper's central claims:
- Lemma 1/2 (linearity under induced ops): f(x1 (+)x x2) == f(x1) (+)y f(x2)
- one-step vs multi-step sampling equivalence (collapsed operator B)
- latent collapse error of B vs iterated Euler/RK updates
- inversion roundtrip via B^{-1} (paper Fig. 4b)
- FID (one-step vs multi-step vs real), pytorch-fid Inception features
4. Writes checkpoint, sample grids, results.json to --out.
"""
import argparse
import glob
import json
import os
import shutil
import sys
import tarfile
import time
import urllib.request
from pathlib import Path
import torch
import torch.nn.functional as F
REPO_COMMIT = "adfca2c3e3992f6605c84f470b0866fbfa4ada15"
REPO_TGZ = f"https://codeload.github.com/assafshocher/Linearizer/tar.gz/{REPO_COMMIT}"
def ensure_official_repo(base: Path) -> Path:
"""Fetch the official repo at the pinned commit (stdlib only)."""
repo_dir = base / "Linearizer-official"
if not repo_dir.exists():
tgz = base / "linearizer.tgz"
print(f"downloading official repo {REPO_TGZ}")
urllib.request.urlretrieve(REPO_TGZ, tgz)
with tarfile.open(tgz) as tf:
tf.extractall(base, filter="data")
extracted = [
d for d in base.iterdir()
if d.is_dir() and d.name.startswith("Linearizer-") and d.name != repo_dir.name
]
assert len(extracted) == 1, f"unexpected extraction layout: {extracted}"
extracted[0].rename(repo_dir)
sys.path.insert(0, str(repo_dir))
sys.path.insert(0, str(repo_dir / "one_step")) # official code does: from configs.celeba import ...
return repo_dir
BASE = Path(os.environ.get("REPRO_WORKDIR", "/root/repro"))
BASE.mkdir(parents=True, exist_ok=True)
REPO_DIR = ensure_official_repo(BASE)
# official modules (import after sys.path setup)
from one_step.data.data_utils import get_data_loaders # noqa: E402
from one_step.modules.one_step_linearizer import OneStepLinearizer # noqa: E402
from one_step.utils.loss_utils import calculate_lpips # noqa: E402
from one_step.utils.model_utils import get_linear_network, get_g # noqa: E402
from one_step.train_one_step import FlowMatcher # noqa: E402
from torchvision import utils as tv_utils # noqa: E402
def parse_args():
p = argparse.ArgumentParser(description="Linearizer MNIST FM reproduction")
# model (official MNIST config defaults)
p.add_argument("--lora", type=int, default=8)
p.add_argument("--num-of-layers", type=int, default=2)
p.add_argument("--img-size", type=int, default=32)
p.add_argument("--in-ch", type=int, default=1)
p.add_argument("--out-ch", type=int, default=1)
# training
p.add_argument("--epochs", type=int, default=201)
p.add_argument("--batch-size", type=int, default=256)
p.add_argument("--batch-size-val", type=int, default=128)
p.add_argument("--lr", type=float, default=1e-4)
p.add_argument("--noise-level", type=float, default=0.3)
p.add_argument("--max-train-batches", type=int, default=0, help="cap batches/epoch (0 = all)")
p.add_argument("--eval-every", type=int, default=10)
p.add_argument("--ckpt-every", type=int, default=5)
# eval
p.add_argument("--steps", type=int, default=1000, help="T for training-time artifact sampling")
p.add_argument("--eval-steps", type=int, default=100, help="T for the headline one-vs-multi eval")
p.add_argument("--fid-samples", type=int, default=10000)
p.add_argument("--seed", type=int, default=0)
# io / mode
p.add_argument("--data-root", type=str, default=str(BASE / "data"))
p.add_argument("--out", type=str, default=str(BASE / "out"))
p.add_argument("--model-path", type=str, default="", help="eval-only: load this checkpoint")
p.add_argument("--pretrained-gdrive", action="store_true",
help="eval-only: additionally download the authors' MNIST checkpoint via gdown")
p.add_argument("--eval-only", action="store_true")
p.add_argument("--smoke", action="store_true", help="fast run to validate pipeline + measure it/s")
# trackio
p.add_argument("--trackio-project", type=str, default="linearizer-mnist-fm")
p.add_argument("--trackio-space", type=str, default="")
p.add_argument("--no-trackio", action="store_true")
return p.parse_args()
def build_model(args):
linear_network = get_linear_network("TimeDependentLoRALinearLayer",
linear_lora_features=args.lora,
img_size=args.img_size)
g = get_g("InverseUnet", args.num_of_layers, args.out_ch, args.img_size)
return OneStepLinearizer(gx=g, linear_network=linear_network)
def save_grid(samples, path, n=16):
samples = torch.clamp(samples[:n], 0, 1)
tv_utils.save_image(samples, path, nrow=4 if n <= 16 else 6)
def train(linearizer, fm, dl, args, device, tracker):
out = Path(args.out)
models_dir = out / "models"
artifacts_dir = out / "artifacts"
models_dir.mkdir(parents=True, exist_ok=True)
artifacts_dir.mkdir(parents=True, exist_ok=True)
optimizer = torch.optim.Adam([{"params": linearizer.parameters(), "lr": args.lr}],
betas=(0.9, 0.999), weight_decay=0.0)
n_batches = len(dl)
if args.max_train_batches:
n_batches = min(n_batches, args.max_train_batches)
t_start = time.time()
step_times = []
global_step = 0
history = []
for epoch in range(args.epochs):
linearizer.train()
total = 0.0
for bi, (x1, _lbl) in enumerate(dl):
if args.max_train_batches and bi >= args.max_train_batches:
break
x1 = x1.to(device)
optimizer.zero_grad()
loss = fm.training_losses(x1=x1, x0=None, noise_level=args.noise_level)
loss.backward()
optimizer.step()
total += loss.item()
if global_step % 25 == 0:
tracker.log({"loss": loss.item(), "epoch": epoch}, step=global_step)
print(f"epoch {epoch} batch {bi}/{n_batches} loss {loss.item():.4f}", flush=True)
step_times.append(time.time())
global_step += 1
avg = total / n_batches
history.append({"epoch": epoch, "loss": avg})
ips = 0.0
if len(step_times) > 1:
ips = (len(step_times) - 1) / max(step_times[-1] - step_times[0], 1e-9)
tracker.log({"epoch_loss": avg, "epoch": epoch, "steps_per_sec": ips}, step=global_step)
print(f"epoch {epoch}/{args.epochs} avg_loss {avg:.4f} ({ips:.2f} it/s)", flush=True)
if epoch % args.ckpt_every == 0 or epoch == args.epochs - 1:
torch.save(linearizer, models_dir / "lin_latest.pth")
if epoch % args.eval_every == 0:
linearizer.eval()
x = torch.randn(16, args.in_ch, args.img_size, args.img_size, device=device)
one = fm.sample_one_step(x, device, sampling_method="euler", T=args.steps)
multi = fm.sample(x, device, steps=args.steps, method="euler")
save_grid(one, artifacts_dir / f"one_step_e{epoch:03d}.png")
save_grid(multi, artifacts_dir / f"multi_step_e{epoch:03d}.png")
torch.save(linearizer, models_dir / "lin_final.pth")
(out / "history.json").write_text(json.dumps(history))
wall = time.time() - t_start
print(f"training done in {wall/60:.1f} min")
return wall, global_step
# ---------------- evaluation ----------------
@torch.no_grad()
def linearity_check(fm, xs, device, t_val=0.5):
"""Lemma 1/2: f(x1 (+)x x2) == f(x1) (+)y f(x2), and scalar homogeneity."""
lin = fm.linearizer
lin.eval()
def f(x):
return lin.forward(x, t=torch.full((x.shape[0],), t_val, device=device))
results = []
n = xs.shape[0]
# pairwise addition
for _ in range(8):
i, j = torch.randint(0, n, (2,))
x1, x2 = xs[i:i + 1], xs[j:j + 1]
z = lin.gx_inverse(lin.gx(x1) + lin.gx(x2)) # x1 (+)x x2
lhs = f(z)
rhs = lin.gy_inverse(lin.gy(f(x1)) + lin.gy(f(x2))) # f(x1) (+)y f(x2)
diff = (lhs - rhs).abs().max().item()
rel = diff / max(lhs.abs().max().item(), 1e-8)
results.append({"add_abs_diff": diff, "add_rel_err": rel})
# scalar multiplication
for a in (0.7, 1.7, -1.3):
i = torch.randint(0, n, (1,)).item()
x1 = xs[i:i + 1]
z = lin.gx_inverse(a * lin.gx(x1)) # a (.)x x1
lhs = f(z)
rhs = lin.gy_inverse(a * lin.gy(f(x1)))
diff = (lhs - rhs).abs().max().item()
rel = diff / max(lhs.abs().max().item(), 1e-8)
results.append({"scale_abs_diff": diff, "scale_rel_err": rel, "a": a})
return results
@torch.no_grad()
def invertibility_check(fm, xs):
lin = fm.linearizer
d_gx = (lin.gx_inverse(lin.gx(xs)) - xs).abs().max().item()
d_gy = (lin.gy_inverse(lin.gy(xs)) - xs).abs().max().item()
return {"gx_roundtrip_max_abs": d_gx, "gy_roundtrip_max_abs": d_gy}
@torch.no_grad()
def onestep_vs_multistep(fm, noise, device, T, method="euler"):
"""One-step (collapsed B) vs iterative sampling, on identical noise."""
lin = fm.linearizer
multi = fm.sample(noise.clone(), device, steps=T, method=method)
B = fm.get_sampling_terms(device, T=T, sampling_method=method)
one = fm.sample_one_step(noise.clone(), device, sampling_method=method, T=T, B=B)
mse = F.mse_loss(one, multi).item()
psnr = -10 * torch.log10(torch.tensor(max(mse, 1e-12))).item()
lp = calculate_lpips(torch.clamp(one, 0, 1), torch.clamp(multi, 0, 1)).item()
res = {"T": T, "method": method, "mse": mse, "psnr": psnr, "lpips": lp}
if method == "euler":
# latent-space collapse error: iterate Euler manually, compare with B @ z0
z0 = lin.gy(noise)
z = z0
dt = 1.0 / T
for i in range(0, T - 1): # ascending t: matches the official sampler's order
t_k = i * dt
z = z + (dt / (1.0 - t_k)) * (
lin.linear_network(z, t=torch.full((z.shape[0],), t_k, device=device)) - z)
z_B = (z0.reshape(z.shape[0], -1) @ B).reshape(z.shape)
res["latent_collapse_rel_err"] = ((z_B - z).norm() / z.norm().clamp_min(1e-12)).item()
return res, B
@torch.no_grad()
def inversion_roundtrip(fm, xs, B, device):
"""Paper Fig 4b: encode x1 -> latent noise x0 via B^{-1}, decode back."""
lin = fm.linearizer
B_inv = torch.pinverse(B)
g_x1 = lin.gx(xs).reshape(xs.shape[0], -1)
g_x0 = g_x1 @ B_inv
x0 = lin.gy_inverse(g_x0.reshape(xs.shape).contiguous())
g_x1_rec = (lin.gy(x0).reshape(xs.shape[0], -1) @ B).reshape(xs.shape)
x1_rec = lin.gx_inverse(g_x1_rec.contiguous())
mse = F.mse_loss(x1_rec, xs).item()
psnr = -10 * torch.log10(torch.tensor(max(mse, 1e-12))).item()
lp = calculate_lpips(torch.clamp(x1_rec, 0, 1), torch.clamp(xs, 0, 1)).item()
return {"psnr": psnr, "lpips": lp, "mse": mse}
def save_fid_images(samples, out_dir, offset=0):
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
samples = torch.clamp(samples, 0, 1)
for i in range(samples.shape[0]):
tv_utils.save_image(samples[i], out_dir / f"{offset + i:05d}.png")
@torch.no_grad()
def fid_evaluation(fm, dl_real, args, device, tracker):
"""FID of one-step (T=100, T=1000) and multi-step (T=100) vs real test images."""
from pytorch_fid.fid_score import get_activations, calculate_frechet_distance
from pytorch_fid.inception import InceptionV3
out = Path(args.out)
fid_dir = Path(os.environ.get("REPRO_FID_DIR", str(BASE / "fid_cache"))) # local disk: bucket round-trips are too slow
n = args.fid_samples
n_real = min(n, 10000)
# real images (test split)
real_dir = fid_dir / "real"
if not (real_dir / f"{n_real - 1:05d}.png").exists():
real_dir.mkdir(parents=True, exist_ok=True)
saved = 0
for xb, _ in dl_real:
for k in range(xb.shape[0]):
if saved >= n_real:
break
tv_utils.save_image(torch.clamp(xb[k], 0, 1), real_dir / f"{saved:05d}.png")
saved += 1
if saved >= n_real:
break
def gen_dir(method, T):
d = fid_dir / f"{method}_T{T}"
if not (d / f"{n - 1:05d}.png").exists():
d.mkdir(parents=True, exist_ok=True)
remaining, bs = n, 250
while remaining > 0:
m = min(bs, remaining)
noise = torch.randn(m, args.in_ch, args.img_size, args.img_size, device=device)
if method == "one":
s = fm.sample_one_step(noise, device, sampling_method="euler", T=T)
else:
s = fm.sample(noise, device, steps=T, method="euler")
save_fid_images(s, d, offset=n - remaining)
remaining -= m
return d
dirs = {"real": real_dir, "one_T100": gen_dir("one", 100),
"one_T1000": gen_dir("one", 1000), "multi_T100": gen_dir("multi", 100)}
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]
fid_model = InceptionV3([block_idx]).to(device)
import numpy as np
def dir_stats(v):
files = sorted(glob.glob(str(Path(v) / "*.png")))
assert files, f"no images found in {v}"
print(f"[fid] {v}: {len(files)} images", flush=True)
act = get_activations(files, fid_model, batch_size=200, device=device)
return np.mean(act, axis=0), np.cov(act, rowvar=False)
stats = {k: dir_stats(v) for k, v in dirs.items()}
fids = {
"fid_one_T100_vs_real": calculate_frechet_distance(*stats["one_T100"], *stats["real"]),
"fid_one_T1000_vs_real": calculate_frechet_distance(*stats["one_T1000"], *stats["real"]),
"fid_multi_T100_vs_real": calculate_frechet_distance(*stats["multi_T100"], *stats["real"]),
"fid_one_vs_multi_T100": calculate_frechet_distance(*stats["one_T100"], *stats["multi_T100"]),
}
for k, v in fids.items():
tracker.log({k: v})
return fids
def run_eval(fm, args, device, dl_val, tracker):
out = Path(args.out)
results_path = out / "results.json"
results = {}
def checkpoint_results():
results_path.write_text(json.dumps(results, indent=2))
torch.manual_seed(args.seed)
xs = next(iter(dl_val))[0].to(device)[:64]
print("[eval] linearity (induced ops) ...", flush=True)
results["linearity"] = linearity_check(fm, xs, device)
checkpoint_results()
print("[eval] invertibility ...", flush=True)
results["invertibility"] = invertibility_check(fm, xs)
checkpoint_results()
print(f"[eval] one-step vs multi-step (euler, T={args.eval_steps}) ...", flush=True)
noise = torch.randn(1000, args.in_ch, args.img_size, args.img_size, device=device)
m100, B100 = onestep_vs_multistep(fm, noise[:500], device, args.eval_steps, "euler")
results["one_vs_multi_euler_T100"] = m100
checkpoint_results()
mrk, _ = onestep_vs_multistep(fm, noise[:500], device, args.eval_steps, "rk")
results["one_vs_multi_rk_T100"] = mrk
checkpoint_results()
print("[eval] inversion roundtrip ...", flush=True)
results["inversion_roundtrip"] = inversion_roundtrip(fm, xs, B100, device)
checkpoint_results()
print("[eval] sample grids ...", flush=True)
g24 = torch.randn(24, args.in_ch, args.img_size, args.img_size, device=device)
save_grid(fm.sample_one_step(g24, device, sampling_method="euler", T=args.eval_steps),
out / "samples_one_step.png", n=24)
save_grid(fm.sample(g24, device, steps=args.eval_steps, method="euler"),
out / "samples_multi_step.png", n=24)
if not args.smoke:
print("[eval] FID ...", flush=True)
results["fid"] = fid_evaluation(fm, dl_val, args, device, tracker)
return results
def main():
args = parse_args()
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
(out / "args.json").write_text(json.dumps(vars(args), indent=2))
torch.manual_seed(args.seed)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"device={device}, args={vars(args)}", flush=True)
# snapshot official code for provenance
code_dir = out / "code" / "Linearizer-official"
if not code_dir.exists():
shutil.copytree(REPO_DIR, code_dir,
ignore=shutil.ignore_patterns("figs", "style_transfer", "data"))
tracker = _Tracker(args)
if args.model_path or args.pretrained_gdrive:
args.eval_only = True
dl_train, dl_val = get_data_loaders("mnist", args.batch_size, args.batch_size_val,
target_size=args.img_size)
print("mnist loaded", flush=True)
if args.eval_only:
if args.pretrained_gdrive:
ck = download_gdrive_checkpoint(BASE)
if ck:
args.model_path = ck
assert args.model_path, "no checkpoint to evaluate"
print(f"loading checkpoint {args.model_path}")
linearizer = torch.load(args.model_path, map_location=device, weights_only=False)
fm = FlowMatcher(linearizer)
else:
linearizer = build_model(args)
n_params = sum(p.numel() for p in linearizer.parameters())
print(f"linearizer params: {n_params/1e6:.2f}M", flush=True)
fm = FlowMatcher(linearizer)
linearizer = linearizer.to(device)
if not args.eval_only:
wall, global_step = train(linearizer, fm, dl_train, args, device, tracker)
tracker.log({"train_wall_minutes": wall / 60.0})
results = run_eval(fm, args, device, dl_val, tracker)
results["train"] = {"wall_minutes": wall / 60.0, "global_steps": global_step,
"params": n_params}
else:
results = run_eval(fm, args, device, dl_val, tracker)
(out / "results.json").write_text(json.dumps(results, indent=2))
print("=== RESULTS ===")
print(json.dumps(results, indent=2))
tracker.finish()
class _Tracker:
def __init__(self, args):
self.enabled = not args.no_trackio
if self.enabled:
import trackio
kwargs = {"project": args.trackio_project}
if args.trackio_space:
kwargs["space_id"] = args.trackio_space
trackio.init(**kwargs)
self._t = trackio
def log(self, metrics, step=None):
if not self.enabled:
return
try:
if step is None:
self._t.log(metrics)
else:
self._t.log(metrics, step=step)
except Exception as e: # never kill a run over metrics
print(f"[trackio] log failed: {e}", flush=True)
def finish(self):
if self.enabled:
try:
self._t.finish()
except Exception as e:
print(f"[trackio] finish failed: {e}", flush=True)
def download_gdrive_checkpoint(base: Path):
"""Best-effort download of the authors' MNIST checkpoint (Google Drive)."""
try:
import gdown
folder = "https://drive.google.com/drive/folders/1kKnfhvhFH7Tyhqb3UflSzWDB43i12ger?usp=sharing"
dest = base / "gdrive_ckpt"
if not dest.exists():
gdown.download_folder(url=folder, output=str(dest), quiet=False, use_cookies=False)
ckpts = list(dest.rglob("model.pth"))
if ckpts:
return str(ckpts[0])
print("[gdrive] folder downloaded but no model.pth found", flush=True)
except Exception as e:
print(f"[gdrive] download failed (quota/network): {e}", flush=True)
return ""
if __name__ == "__main__":
main()

Xet Storage Details

Size:
20.8 kB
·
Xet hash:
19b621810fae83464046853919b4ed6782ce9c4f5b26e53706c03a1b54c4df66

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.