"""Run guards on the tiny CPU trainer: non-finite steps are skipped (weights, Adam, EMA untouched) and abort the run after max_bad_steps without a checkpoint; poisoned weights are never saved; graceful stops record why (signal, deadline) in exit_status.json; a resume drops replayed log rows; the training CLI parses into the recipe defaults.""" import json import os import random import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(HERE), "src")) sys.path.insert(0, HERE) import numpy as np # noqa: E402 import pytest # noqa: E402 import torch # noqa: E402 pytest.importorskip("diffusers") pytest.importorskip("lpips") from dwd_klein.trainer import Config, NonFiniteAbort, Trainer # noqa: E402 from tiny import tiny_components, write_shards # noqa: E402 def _seed(): random.seed(0) np.random.seed(0) torch.manual_seed(0) def _trainer(root, run, **kw): base = dict(run=run, ckpt_root=str(root / "ck"), data_root=str(root / "data"), k=2, iters=6, d_start=1, adv_start=2, global_batch=4, micro_batch=2, warmup=2, ema_start=1, ckpt_every=100, keep=10, log_every=1, lsq_images=4, crops=2, crop_size=16, seed=0) base.update(kw) cfg = Config(**base) comps = tiny_components(cfg.data_root, micro_batch=2, seed=0, k=2) return Trainer(cfg, comps, torch.device("cpu"), log=lambda m: None) class NaNAt: """LPIPS stand-in that returns NaN on the listed calls (call counter over the run).""" def __init__(self, lp, bad_calls): self.lp, self.bad, self.n = lp, set(bad_calls), 0 def __call__(self, x, y): out = self.lp(x, y) self.n += 1 return out * float("nan") if (self.n - 1) in self.bad else out def _snap(tr): return ({k: v.clone() for k, v in tr.student.state_dict().items()}, tr.ema.state_dict(), {k: v.clone() for k, v in tr.disc.head_state_dict().items()}) def _status(tr): return json.load(open(os.path.join(tr.cfg.run_dir, "exit_status.json"))) def _log(tr): return [json.loads(x) for x in open(os.path.join(tr.cfg.run_dir, "log.jsonl"))] def test_nonfinite_step_is_skipped(tmp_path): write_shards(str(tmp_path / "data"), shards=2, per_shard=6) _seed() tr = _trainer(tmp_path, "skip", iters=5) tr.lsq_init() tr.loader.start(0, tr.accum) for _ in range(3): # through the adversarial start (it 2) tr.step() tr.lpips = NaNAt(tr.lpips, range(tr.accum)) # every micro-batch of the next step before = _snap(tr) opt_before = [s["exp_avg"].clone() for s in tr.opt.state.values()] m = tr.step() after = _snap(tr) assert m["skipped"] == 1.0 and not np.isfinite(m["gnorm"]) and tr.bad_steps == 1 and tr.it == 4 for a, b in zip(before[:2], after[:2]): for k in a: assert torch.equal(a[k], b[k]), k # student and EMA untouched # D's own loss (on x_hat.detach()) is finite, so D still steps assert m["d_skipped"] == 0.0 and any(not torch.equal(before[2][k], after[2][k]) for k in before[2]) assert all(torch.equal(x, s["exp_avg"]) for x, s in zip(opt_before, tr.opt.state.values())) assert all(p.grad is None for p in tr.student.parameters()) m = tr.step() # the next good step trains again and resets the counter tr.loader.stop() assert m["skipped"] == 0.0 and np.isfinite(m["gnorm"]) and tr.bad_steps == 0 assert any(not torch.equal(after[0][k], v) for k, v in tr.student.state_dict().items()) ev = [r for r in _log(tr) if r.get("event") == "nonfinite_skip"] assert len(ev) == 1 and ev[0]["it"] == 3 and ev[0]["g_skipped"] def test_nonfinite_run_aborts_without_checkpoint(tmp_path): write_shards(str(tmp_path / "data"), shards=2, per_shard=6) _seed() tr = _trainer(tmp_path, "abort", iters=10, max_bad_steps=3, ckpt_every=2) tr.lpips = NaNAt(tr.lpips, range(2 * tr.accum, 10_000)) # NaN from it 2 on with pytest.raises(NonFiniteAbort): tr.fit(install_signals=False) assert tr.it == 5 and _status(tr)["status"] == "nonfinite" cks = sorted(os.listdir(tr.cfg.run_dir)) assert "ckpt_000002.pt" in cks and "ckpt_000004.pt" in cks # skipped steps leave the weights finite: fine to save assert "ckpt_000005.pt" not in cks def test_poisoned_weights_are_never_saved(tmp_path): write_shards(str(tmp_path / "data"), shards=1, per_shard=4) _seed() tr = _trainer(tmp_path, "poison", lsq_images=0, keep=1) tr.save() tr.it = 1 tr.save() with torch.no_grad(): next(tr.student.parameters())[0].fill_(float("nan")) tr.it = 2 with pytest.raises(NonFiniteAbort): tr.save() cks = sorted(f for f in os.listdir(tr.cfg.run_dir) if f.startswith("ckpt_")) assert cks == ["ckpt_000000.pt", "ckpt_000001.pt"] # nothing written, nothing pruned assert open(os.path.join(tr.cfg.run_dir, "latest")).read() == "ckpt_000001.pt" def test_signal_stop_checkpoints_and_reports(tmp_path): write_shards(str(tmp_path / "data"), shards=2, per_shard=6) _seed() tr = _trainer(tmp_path, "sig") orig = tr.loader.next def nxt(step, micro): if step == 2 and micro == 0: tr._on_signal(15, None) # SIGTERM / SIGINT arrives during it 2 return orig(step, micro) tr.loader.next = nxt assert tr.fit(install_signals=False) == 3 assert tr.stop_reason == "signal" and _status(tr)["status"] == "signal" and _status(tr)["it"] == 3 assert os.path.exists(os.path.join(tr.cfg.run_dir, "ckpt_000003.pt")) _seed() tr2 = _trainer(tmp_path, "sig") assert tr2.fit(install_signals=False) == 6 and tr2.stop_reason == "done" and _status(tr2)["status"] == "done" def test_deadline_stop(tmp_path): write_shards(str(tmp_path / "data"), shards=2, per_shard=6) _seed() tr = _trainer(tmp_path, "deadline", max_hours=1e-9) assert tr.fit(install_signals=False) == 1 assert tr.stop_reason == "deadline" and _status(tr)["status"] == "deadline" assert os.path.exists(os.path.join(tr.cfg.run_dir, "ckpt_000001.pt")) def test_resume_drops_replayed_log_rows(tmp_path): write_shards(str(tmp_path / "data"), shards=2, per_shard=6) _seed() tr = _trainer(tmp_path, "log", ckpt_every=2, iters=3) # checkpoints at 2 and 3 tr.fit(install_signals=False) os.remove(os.path.join(tr.cfg.run_dir, "ckpt_000003.pt")) # as if killed before the it-3 checkpoint landed with open(os.path.join(tr.cfg.run_dir, "latest"), "w") as fh: fh.write("ckpt_000002.pt") with open(os.path.join(tr.cfg.run_dir, "log.jsonl"), "a") as fh: fh.write('{"it": 4, "l1": 0.1') # a row torn by the kill _seed() tr2 = _trainer(tmp_path, "log") tr2.fit(install_signals=False) its = [r["it"] for r in _log(tr2) if "event" not in r] assert its == [1, 2, 3, 4, 5, 6] # it 3 logged once, the torn row gone def _train_cli(): import importlib.util spec = importlib.util.spec_from_file_location("dwd_train_cli", os.path.join(os.path.dirname(HERE), "scripts", "train.py")) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod def test_train_cli_defaults_are_the_recipe(): cfg = _train_cli().parse([]) assert (cfg.iters, cfg.d_start, cfg.adv_start, cfg.global_batch, cfg.micro_batch) == (26000, 2500, 3000, 128, 16) assert (cfg.lr, cfg.head_lr_mult, cfg.warmup, cfg.clip, cfg.lambda_traj) == (1e-4, 5.0, 100, 200.0, 10.0) assert (cfg.ema_gamma, cfg.ckpt_every, cfg.keep, cfg.k) == (7.0, 500, 2, 4) assert cfg.ckpt_root == "./checkpoints" and cfg.data_root == "./data" and cfg.grad_ckpt assert cfg.model_path == "black-forest-labs/FLUX.2-klein-4B" def test_train_cli_flags(): cli = _train_cli() cfg = cli.parse(["--run-name", "x", "--iters", "7", "--max-hours", "23.25", "--iters", "9", "--keep-every", "1000", "--buckets", "1024x1024,1152x896", "--bucket-weights", '{"1024x1024": 2}', "--no-grad-ckpt"]) assert cfg.run == "x" and cfg.iters == 9 and cfg.max_hours == 23.25 and cfg.keep_every == 1000 assert cfg.buckets == ["1024x1024", "1152x896"] and cfg.bucket_weights == {"1024x1024": 2} and not cfg.grad_ckpt smoke = cli.parse(["--smoke"]) assert smoke.iters == 20 and smoke.d_start == 5 and smoke.adv_start == 10 with pytest.raises(SystemExit): # unknown flags are rejected cli.parse(["--no-such-flag", "3"])