#!/usr/bin/env python3 """Самопроверка ra4: бюджеты, тривиальность инициализации, обучаемость всех параметров, инвариантность к длине текста, знак CFG, diffusers-чекпойнт, данные. python3 src/selftest.py Код выхода 1, если хоть одна проверка провалилась. Данные, VAE и текстовый энкодер не нужны: всё на мини-конфигурации. """ from __future__ import annotations import json import sys import tempfile from pathlib import Path import numpy as np import torch import torch.nn as nn sys.path.insert(0, str(Path(__file__).resolve().parent)) from model import (ATTN, CONV, WIN, Cfg, Level, Body, count_flops, count_params, # noqa: E402 params_of, tokens_at) from text import TextAdapter # noqa: E402 from transformer import UDiTModel # noqa: E402 PASS, FAIL = [], [] def check(name: str, ok: bool, detail: str = "") -> None: (PASS if ok else FAIL).append(name) print(f" {'ok ' if ok else 'FAIL'} {name}" + (f" — {detail}" if detail else "")) MINI = Cfg(levels=(Level(64, 4, enc=(CONV, WIN, CONV), dec=(CONV, WIN, CONV, CONV)), Level(128, 4, enc=(ATTN,), dec=(ATTN,)), Level(256, 8, enc=(ATTN,))), cond_dim=32, pe_dim=16, text_dim=32, t_dim=32) def mini_model() -> UDiTModel: return UDiTModel(**MINI.to_dict()).eval() def txt_batch(b: int, l: int, d: int, mask_frac: float = 0.5, seed: int = 0): g = torch.Generator().manual_seed(seed) t = torch.randn(b, l, d, generator=g) m = torch.ones(b, l, dtype=torch.bool) m[:, int(l * mask_frac):] = False return t, m def main() -> None: torch.manual_seed(0) # ---- 1. бюджеты print("\n[1] бюджеты (реальный конфиг, meta-устройство)") cfg = Cfg() body = Body(cfg).to("meta") live, ana = count_params(body), params_of(cfg) fl = count_flops(cfg, tokens_at(cfg, 256), 192) widths = [lv.width for lv in cfg.levels] print(f" параметры {live['total']:.0f}M " + " ".join( f"{k}={v:.0f}M" for k, v in live["per_stack"].items())) print(f" FLOPs @256px→512px {fl['total_gflop']:.1f} GFLOP, доли {[f'{s:.0%}' for s in fl['share']]}") check("аналитический счёт параметров сходится с моделью", abs(ana["total"] - live["total"]) / live["total"] < 0.02, f"формула {ana['total']:.1f}M против модели {live['total']:.1f}M") check("ширины шире SDXL (320/640/1280)", all(a > b for a, b in zip(widths, [320, 640, 1280])), str(widths)) check("параметров 120-400M", 120 <= live["total"] <= 400, f"{live['total']:.0f}M") check("FLOPs @256px < 150 GFLOP", fl["total_gflop"] < 150, f"{fl['total_gflop']:.1f}") check("каждый уровень даёт >=8% FLOPs", min(fl["share"]) >= 0.08, " ".join(f"{s:.0%}" for s in fl["share"])) del body # ---- 2. инициализация print("\n[2] старт: блоки тождественны, выход ровно нулевой") m = mini_model() blk_ok, worst = True, 0.0 for part in ("enc", "dec"): for lvl, stack in enumerate(getattr(m.body, part)): w = MINI.levels[lvl].width n = (16, 8, 4)[lvl] ** 2 x = torch.randn(2, n, w) cond0 = torch.zeros(2, MINI.cond_dim) for blk in stack: y = blk(x, blk.ada(cond0), int(n ** 0.5), int(n ** 0.5), None, None) worst = max(worst, float((x - y).abs().max())) blk_ok &= torch.equal(x, y) check("каждый блок тождественен при нулевом ada", blk_ok, f"max|Δ| {worst:.1e}") with torch.no_grad(): out = m.body(torch.randn(2, MINI.latent_ch, 16, 16), torch.tensor([0.3, 0.7])) check("тело выдаёт нулевую скорость на старте", float(out.abs().max()) == 0.0, f"max {float(out.abs().max()):.1e}") # ---- 3. обучаемость ВСЕХ параметров (в ra3 часть текста не попадала в оптимизатор) print("\n[3] обучение: все параметры в оптимизаторе и получают градиент") opt = torch.optim.AdamW(m.parameters(), lr=1e-3) in_opt = {id(p) for g in opt.param_groups for p in g["params"]} missing = [n for n, p in m.named_parameters() if id(p) not in in_opt] check("нет обучаемых параметров вне оптимизатора", not missing, f"вне: {len(missing)} {missing[:2]}") w0 = m.text_adapter.proj.weight.detach().clone() nmask = torch.ones(2, 12, dtype=torch.bool) from train import null_rows for _ in range(5): txt = m.encode_text(torch.randn(2, 12, MINI.text_dim) * 0.5) nr, nm = null_rows(txt, nmask, m.null_text) # как при drop-text txt = torch.where(torch.tensor([[[True]], [[False]]]), nr, txt) mk = torch.where(torch.tensor([[True], [False]]), nm, nmask) z0 = torch.randn(2, MINI.latent_ch, 16, 16) eb = torch.randn_like(z0) t = torch.rand(2) pred = m.body((1 - t[:, None, None, None]) * eb + t[:, None, None, None] * z0, t, txt, mk) loss = (pred - (z0 - eb)).pow(2).mean() opt.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(m.parameters(), 1.0) opt.step() dead = [n for n, p in m.named_parameters() if p.grad is None or float(p.grad.abs().sum()) == 0] check("на 5-м шаге нет параметров без градиента", not dead, f"мёртвых {len(dead)}: {dead[:3]}") check("текстовый адаптер реально изменился", not torch.equal(w0, m.text_adapter.proj.weight), f"|Δproj| {float((w0 - m.text_adapter.proj.weight).abs().max()):.2e}") # ---- 4. инвариантность к длине текста print("\n[4] текст: длина последовательности не влияет на результат") x = torch.randn(1, 40, MINI.text_dim, generator=torch.Generator().manual_seed(1)) with torch.no_grad(): a_full, a_short = m.encode_text(x), m.encode_text(x[:, :17]) check("адаптер по-токенный: короткая подпись = те же значения внутри длинной", torch.allclose(a_short, a_full[:, :17], atol=1e-6), f"max|Δ| {float((a_short - a_full[:, :17]).abs().max()):.1e}") # ---- 5. формы и ограничения сетки print("\n[5] формы и ограничения сетки") m.eval() for lat in (16, 32): with torch.no_grad(): o = m.body(torch.randn(1, MINI.latent_ch, lat, lat), torch.tensor([0.5])) check(f"выход совпадает по форме с входом {lat}²", tuple(o.shape) == (1, MINI.latent_ch, lat, lat), str(tuple(o.shape))) try: with torch.no_grad(): m.body(torch.randn(1, MINI.latent_ch, 20, 20), torch.tensor([0.5])) check("неделимая на окно сетка ругается", False) except ValueError as e: check("неделимая на окно сетка ругается", True, str(e)[:80]) # ---- 6. сэмплер print("\n[6] сэмплер") body_orig = m.body t3, m3 = txt_batch(3, 24, MINI.text_dim, seed=2) txt3 = m.encode_text(t3) g = lambda s=0: torch.Generator("cpu").manual_seed(s) za = m.sample(txt3, m3, 16, 16, steps=4, cfg_scale=3.0, generator=g(0)) zb = m.sample(txt3, m3, 16, 16, steps=4, cfg_scale=3.0, generator=g(0)) zc = m.sample(txt3, m3, 16, 16, steps=4, cfg_scale=1.0, generator=g(0)) check("батч из 3 сэмплируется сразу", tuple(za.shape) == (3, MINI.latent_ch, 16, 16), str(tuple(za.shape))) check("детерминизм по сиду", torch.equal(za, zb)) check("cfg=1 и cfg=3 дают разные латенты", not torch.allclose(za, zc)) check("латент конечный", bool(torch.isfinite(za).all())) # ---- 6b. знак CFG print("\n[6b] направление CFG") class SignBody(nn.Module): """Заглушка: +1 для условной ветки, 0 для пустой (различаем по числу реальных токенов).""" def forward(self, z, t, text=None, text_mask=None): s = (text_mask.sum(1) > 1).float() if text_mask is not None else torch.zeros(z.shape[0]) return s.view(-1, 1, 1, 1).expand_as(z) m.body = SignBody() tz, tm = txt_batch(1, 8, MINI.text_dim, seed=5) # 4 реальных токена → cond = 1 noise = torch.zeros(1, MINI.latent_ch, 8, 8) z1 = m.sample(tz, tm, 8, 8, steps=8, cfg_scale=1.0, noise=noise) z3 = m.sample(tz, tm, 8, 8, steps=8, cfg_scale=3.0, noise=noise) ratio = float((z3 - noise).mean() / (z1 - noise).mean()) check("CFG тянет К подписи, а не от неё", ratio > 1.5, f"отношение сдвигов cfg3/cfg1 = {ratio:.2f} (<1 означает инверсию)") check("величина сдвига соответствует cfg", abs(ratio - 3.0) < 0.05, f"{ratio:.3f}") m.body = body_orig # ---- 7. diffusers-чекпойнт print("\n[7] diffusers-чекпойнт: save_pretrained → from_pretrained") m.eval() with tempfile.TemporaryDirectory() as tmp: m.save_pretrained(tmp) files = sorted(p.name for p in Path(tmp).iterdir()) m2 = UDiTModel.from_pretrained(tmp).eval() zd = m2.sample(txt3, m3, 16, 16, steps=4, cfg_scale=3.0, generator=g(0)) with torch.no_grad(): same = torch.equal(m.body(torch.zeros(1, MINI.latent_ch, 16, 16), torch.tensor([0.4])), m2.body(torch.zeros(1, MINI.latent_ch, 16, 16), torch.tensor([0.4]))) check("в папке config.json и safetensors", "config.json" in files and any(f.endswith(".safetensors") for f in files), str(files)) check("загруженная модель сэмплирует идентично", torch.equal(za, zd)) check("форвард совпадает бит-в-бит", same) # ---- 8. пустой текст для CFG print("\n[8] пустой текст для CFG") txt, mk = txt_batch(3, 24, MINI.text_dim, mask_frac=0.0) null = torch.randn(1, MINI.text_dim) * 0.02 nr, nm = null_rows(txt, mk, null) check("в пустом тексте ровно один реальный токен", int(nm.sum()) == 3 and bool(nm[:, 0].all())) with torch.no_grad(): o = m.body(torch.randn(3, MINI.latent_ch, 16, 16), torch.tensor([0.5, 0.5, 0.5]), nr, nm) check("форвард с пустым текстом конечен", bool(torch.isfinite(o).all())) # ---- 9. данные print("\n[9] данные: скан папки, кропы, кэш") from data import Latents, _load, scan from PIL import Image with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) for i, (w, h) in enumerate([(300, 200), (256, 256), (128, 256)]): rng = np.random.default_rng(i) Image.fromarray(rng.integers(0, 255, (h, w, 3), dtype=np.uint8)).save(root / f"a{i}.jpg") (root / f"a{i}.txt").write_text(f"caption {i}") items = scan(root) check("скан папки находит пары", len(items) == 3, f"{len(items)}") arr = _load(items[0][0], 256, "center") check("кроп даёт (3,256,256) в [-1,1]", arr.shape == (3, 256, 256) and arr.min() >= -1 and arr.max() <= 1, f"{arr.shape} {arr.min():.2f}..{arr.max():.2f}") r1, r2 = _load(items[0][0], 256, "r:5"), _load(items[0][0], 256, "r:5") variants = [_load(items[0][0], 256, f"r:{s}") for s in range(1, 9)] n_distinct = len({v.tobytes() for v in variants}) check("кроп воспроизводим по сиду и не вырожден", np.array_equal(r1, r2) and n_distinct > 1, f"одинаковых сидов = {np.array_equal(r1, r2)}, разных кропов {n_distinct}/8") lat = np.zeros((6, 32, 32, 32), dtype=np.float16) lat[np.arange(6)] = np.arange(6)[:, None, None, None] np.save(root / "latents.npy", lat) (root / "meta.json").write_text(json.dumps({"captions": [f"c{i}" for i in range(6)], "size": 256, "latent": 32, "channels": 32})) d = Latents(root) z, caps = d.batch(3, __import__("random").Random(0)) check("батч сохраняет соответствие латент↔подпись", all(int(z[i].mean().round()) == int(caps[i][1:]) for i in range(3)), str(caps)) zv, cv = d.val_batch(2) check("отложенные примеры берутся с конца кэша", float(zv[0].mean()) >= 4.0, str(cv)) print(f"\nитого: {len(PASS)} ok, {len(FAIL)} провалов") if FAIL: print("провалились:", ", ".join(FAIL)) sys.exit(1) if __name__ == "__main__": main()