File size: 24,234 Bytes
eb8084e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
"""ra4 — UDiT: трёхуровневая пирамида для латентного rectified flow.

Картинка 256² → латент VAE 32×32×32 (f8) → три уровня токенов:

    L0  32×32 = 1024 токена   C=448    conv 3×3 + окно 8×8 (циклический сдвиг)
    L1  16×16 =  256 токенов  C=896    полное внимание
    L2   8×8  =   64 токена   C=1792   полное внимание (боттлнек)

Почему так, а не как в ra3:
  * patch=1: детализация не отдаётся в пользу FLOPs. Compute на L0 всё равно
    дешевле, потому что там преобладают depthwise-свёртки, а не MLP полной ширины.
  * Лестница ширин 448/896/1792 — шире SDXL (320/640/1280) на ~40%. Причина:
    латент 32-канальный, информации на позицию в 8 раз больше, чем в 4-канальном
    у SD/SDXL; на узком боттлнеке такая плотность не моделируется (это и есть
    «мыло» + слабый промпт-фоллоу). Ширина на 64 токенах стоит параметров, но
    почти не FLOPs, поэтому это самая дешёвая ёмкость в модели — её и наращиваем.
  * Каждый блок модулируется СВОИМ ada (shift + scale + gate на каждую ветвь),
    а не общим вектором на уровень.
  * Окна на L0 сдвигаются на полокна через блок — иначе внимание заперто
    внутри окна и ничего не переносит через границы.

Инициализация: последний слой каждого `ada` и `out` — нули. Значит на шаге 0
каждый блок тождественен, тело выдаёт нулевую скорость, и сеть растёт
равномерно, а не по случайности инита.
"""
from __future__ import annotations

import math
from dataclasses import asdict, dataclass, fields, replace

import torch
import torch.nn as nn
import torch.nn.functional as F

DEV = "cuda" if torch.cuda.is_available() else "cpu"
_CACHE: dict = {}


# ---------------------------------------------------------------- позиции
def t_embed(t: torch.Tensor, dim: int = 256) -> torch.Tensor:
    """Синусоидальный эмбеддинг t∈[0,1]."""
    half = dim // 2
    f = torch.exp(-math.log(10000.0) * torch.arange(half, device=t.device, dtype=torch.float32) / half)
    a = t.float()[:, None] * 1000.0 * f[None]
    return torch.cat([a.sin(), a.cos()], -1)


def sincos_2d(gh: int, gw: int, dim: int, device, dtype=None) -> torch.Tensor:
    """Абсолютные 2D-позиции: sin/cos по каждой оси → (gh*gw, dim)."""
    key = ("pe", gh, gw, dim, str(device))
    tab = _CACHE.get(key)
    if tab is None:
        half = dim // 2
        f = 1.0 / (10000 ** (torch.arange(half // 2, device=device, dtype=torch.float32) / (half / 2)))
        y = torch.arange(gh, device=device, dtype=torch.float32)[:, None] * f[None]
        x = torch.arange(gw, device=device, dtype=torch.float32)[:, None] * f[None]
        ey = torch.cat([y.sin(), y.cos()], -1)[:, None, :].expand(gh, gw, half)
        ex = torch.cat([x.sin(), x.cos()], -1)[None, :, :].expand(gh, gw, half)
        tab = torch.cat([ey, ex], -1).reshape(gh * gw, dim)
        _CACHE[key] = tab
    return tab if dtype is None else tab.to(dtype)


def rope2d(q, k, gh: int, gw: int, base: float = 10000.0):
    """2D RoPE: 4 четверти head_dim, две крутятся по x, две — по y."""
    hd = q.shape[-1]
    key = ("rope", gh, gw, hd, str(q.device), base)
    tabs = _CACHE.get(key)
    if tabs is None:
        dq = hd // 4
        fr = torch.exp(-math.log(base) * torch.arange(dq, device=q.device, dtype=torch.float32) / dq)
        yy = torch.arange(gh, device=q.device).repeat_interleave(gw).float()
        xx = torch.arange(gw, device=q.device).repeat(gh).float()
        ax, ay = xx[:, None] * fr, yy[:, None] * fr
        tabs = tuple(x[None, None] for x in (ax.cos(), ax.sin(), ay.cos(), ay.sin()))
        _CACHE[key] = tabs
    cx, sx, cy, sy = tabs

    def rot(t):
        dq = t.shape[-1] // 4
        a, b, c, e = t[..., :dq], t[..., dq:2 * dq], t[..., 2 * dq:3 * dq], t[..., 3 * dq:]
        return torch.cat([a * cx - b * sx, a * sx + b * cx, c * cy - e * sy, c * sy + e * cy], dim=-1).to(t.dtype)

    return rot(q), rot(k)


# ---------------------------------------------------------------- окна
def win_part(x, gh, gw, win, shift=0):
    """(B, gh*gw, C) → (B*окон, win*win, C). shift — циклический сдвиг сетки."""
    B, _, C = x.shape
    h, w = gh // win, gw // win
    if shift:
        x = x.view(B, gh, gw, C).roll((shift, shift), (1, 2)).view(B, gh, gw, C)
    return x.view(B, h, win, w, win, C).permute(0, 1, 3, 2, 4, 5).reshape(B * h * w, win * win, C)


def win_merge(x, gh, gw, win, shift=0):
    C = x.shape[-1]
    h, w = gh // win, gw // win
    x = x.view(-1, h, w, win, win, C).permute(0, 1, 3, 2, 4, 5).reshape(-1, gh, gw, C)
    if shift:
        x = x.roll((-shift, -shift), (1, 2))
    return x.reshape(x.shape[0], gh * gw, C)


# ---------------------------------------------------------------- мелочи
class RMSNorm(nn.Module):
    def __init__(self, d: int, eps: float = 1e-6):
        super().__init__()
        self.d, self.eps = d, eps
        self.w = nn.Parameter(torch.ones(d))

    def forward(self, x):
        return F.rms_norm(x, (self.d,), weight=self.w.to(x.dtype), eps=self.eps)


class Ada(nn.Module):
    """Модуляция блока: на каждую ветвь пара (shift, scale, gate). Нули на старте."""

    def __init__(self, cond_dim: int, n: int, c: int):
        super().__init__()
        self.c, self.n = c, n
        self.lin = nn.Linear(cond_dim, 3 * n * c)
        nn.init.zeros_(self.lin.weight)
        nn.init.zeros_(self.lin.bias)

    def forward(self, cond):
        x = self.lin(F.silu(cond)).view(cond.shape[0], self.n, 3, self.c)
        return [x[:, i].unbind(1) for i in range(self.n)]   # n троек (B, C)


# ---------------------------------------------------------------- блоки
class Block(nn.Module):
    """Гибридный блок: conv | win | attn + кросс-внимание к тексту, всё под ada-гейтами.

    conv: depthwise 3×3 → MLP ×2 (ConvNeXt-подобный, локальность).
    attn: внимание (полное или оконное) + QK-norm + RoPE → MLP ×2.
    Кросс-внимание к тексту есть на всех уровнях: промпт-фоллоу держится не
    только на adaLN, а на каждом блоке.
    """

    def __init__(self, kind: str, c: int, heads: int, win: int = 0, cond_dim: int = 256, shift: int = 0):
        super().__init__()
        assert kind in ("conv", "win", "attn")
        assert c % heads == 0 and (c // heads) % 4 == 0, "ширина/головы не подходят для RoPE"
        self.kind, self.c, self.h, self.hd = kind, c, heads, c // heads
        self.win = win if kind == "win" else 0
        self.shift = shift
        n_sub = 2 if kind == "conv" else 3
        self.ada = Ada(cond_dim, n_sub, c)
        self.n1, self.nx = RMSNorm(c), RMSNorm(c)
        if kind == "conv":
            self.dw = nn.Conv2d(c, c, 3, padding=1, groups=c)
            self.fc1, self.fc2 = nn.Linear(c, 2 * c), nn.Linear(2 * c, c)
        else:
            self.n2 = RMSNorm(c)
            self.qkv = nn.Linear(c, 3 * c, bias=False)
            self.o = nn.Linear(c, c, bias=False)
            self.qk = nn.Parameter(torch.ones(2, heads, self.hd))
            self.fc1, self.fc2 = nn.Linear(c, 2 * c), nn.Linear(2 * c, c)
        self.xq = nn.Linear(c, c, bias=False)
        self.xo = nn.Linear(c, c, bias=False)
        self.xqk = nn.Parameter(torch.ones(2, heads, self.hd))   # QK-norm кросс-внимания

    def _attn(self, h, gh, gw):
        B, N, C = h.shape
        grid = (gh, gw)
        if self.win:
            h, grid = win_part(h, gh, gw, self.win, self.shift), (self.win, self.win)
        n = h.shape[1]
        q, k, v = self.qkv(h).reshape(-1, n, 3, self.h, self.hd).permute(2, 0, 3, 1, 4)
        q = F.rms_norm(q, (self.hd,)) * self.qk[0][None, :, None, :]
        k = F.rms_norm(k, (self.hd,)) * self.qk[1][None, :, None, :]
        q, k = rope2d(q, k, *grid)
        a = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(-1, n, C)
        if self.win:
            a = win_merge(a, gh, gw, self.win, self.shift)
        return self.o(a)

    def forward(self, x, mods, gh, gw, text_kv, text_mask):
        B, N, C = x.shape
        sh1, sc1, g1 = mods[0]
        h = self.n1(x) * (1 + sc1[:, None]) + sh1[:, None]
        if self.kind == "conv":
            h = self.dw(h.transpose(1, 2).reshape(B, C, gh, gw)).flatten(2).transpose(1, 2)
            x = x + g1[:, None] * self.fc2(F.gelu(self.fc1(h), approximate='tanh'))
        else:
            x = x + g1[:, None] * self._attn(h, gh, gw)

        if text_kv is not None:
            shx, scx, gx = mods[1]
            q = self.xq(self.nx(x) * (1 + scx[:, None]) + shx[:, None])
            q = q.reshape(B, N, self.h, self.hd).transpose(1, 2)
            q = F.rms_norm(q, (self.hd,)) * self.xqk[0][None, :, None, :]
            k = F.rms_norm(text_kv[0], (self.hd,)) * self.xqk[1][None, :, None, :]
            mask = text_mask[:, None, None, :] if text_mask is not None else None
            a = F.scaled_dot_product_attention(q, k, text_kv[1], attn_mask=mask)
            x = x + gx[:, None] * self.xo(a.transpose(1, 2).reshape(B, N, C))

        if self.kind != "conv":
            sh2, sc2, g2 = mods[2]
            h = self.n2(x) * (1 + sc2[:, None]) + sh2[:, None]
            x = x + g2[:, None] * self.fc2(F.gelu(self.fc1(h), approximate='tanh'))
        return x


# ---------------------------------------------------------------- конфигурация
@dataclass(frozen=True)
class Level:
    width: int
    heads: int
    enc: tuple = ()
    dec: tuple = ()

    def kinds(self, part: str) -> tuple:
        return self.enc if part == "enc" else self.dec


CONV = "conv"
WIN = "win"
ATTN = "attn"

# Лестница ширин 448/896/1792 (шире SDXL), head_dim = 64 на всех уровнях.
# Глубины выбраны под бюджет FLOPs: L0 12 блоков (9 conv + 3 окна, из них
# 7 в декодере — детали синтезируются там), L1 3+3 полного внимания,
# L2 3 блока на 64 токенах. Параметры при этом перекошены в боттлнек — это
# плата за ширину, FLOPs сбалансированы: ~2.7G на conv-блок, ~4.6G на остальные.
DEFAULT_LEVELS = (
    Level(448, 7,
          enc=(CONV, CONV, WIN, CONV, CONV),
          dec=(CONV, WIN, CONV, CONV, CONV, WIN, CONV)),
    Level(896, 14, enc=(ATTN,) * 3, dec=(ATTN,) * 3),
    Level(1792, 28, enc=(ATTN,) * 3),
)


@dataclass(frozen=True)
class Cfg:
    levels: tuple = DEFAULT_LEVELS
    latent_ch: int = 32
    text_dim: int = 768
    win: int = 8
    pe_dim: int = 64
    cond_dim: int = 256
    t_dim: int = 256
    predict: str = "v"        # что выдаёт тело: "v" (скорость) или "x" (чистый латент)

    def kinds(self, lvl: int, part: str) -> tuple:
        return self.levels[lvl].kinds(part)

    def to_dict(self) -> dict:
        d = {k: v for k, v in asdict(self).items() if k != "levels"}
        d["levels"] = [asdict(lv) for lv in self.levels]
        return d

    @staticmethod
    def from_dict(d: dict) -> "Cfg":
        known = {f.name for f in fields(Cfg)}
        d = {k: v for k, v in d.items() if k in known}
        d["levels"] = tuple(Level(**{**lv, "enc": tuple(lv["enc"]), "dec": tuple(lv.get("dec", ()))}) for lv in d["levels"])
        return Cfg(**d)


def x_to_v(x_pred, xt, t, eps: float = 0.02):
    """Скорость из x-предсказания: v = (x − x_t)/(1 − t); t=1 — данные."""
    return (x_pred - xt) / (1.0 - t).clamp(min=eps).view(-1, 1, 1, 1)


def _make_block(kind: str, c: int, heads: int, win: int, cond_dim: int, shift: int) -> Block:
    return Block(kind, c, heads, win, cond_dim, shift)


# ---------------------------------------------------------------- тело
class Body(nn.Module):
    def __init__(self, cfg: Cfg):
        super().__init__()
        self.cfg = cfg
        L = cfg.levels
        w = [lv.width for lv in L]

        self.stem = nn.Conv2d(cfg.latent_ch, w[0], 3, padding=1)
        self.pe = nn.ModuleList([nn.Linear(cfg.pe_dim, wi) for wi in w])
        for m in self.pe:                      # PE живой со шага 0 (блоки всё равно тождественны)
            nn.init.normal_(m.weight, std=0.02)

        def stack(part: str, i: int):
            blks, nwin = [], 0
            for kind in cfg.kinds(i, part):
                shift = 0
                if kind == WIN:
                    shift = (cfg.win // 2) * (nwin % 2)   # 0, 4, 0, 4 — окна перекрываются
                    nwin += 1
                blks.append(_make_block(kind, L[i].width, L[i].heads, cfg.win, cfg.cond_dim, shift))
            return nn.ModuleList(blks)

        self.enc = nn.ModuleList([stack("enc", i) for i in range(3)])
        self.dec = nn.ModuleList([stack("dec", i) for i in range(3)])

        # 2×2 space-to-depth (без потерь) и обратный pixel-shuffle
        self.dn = nn.ModuleList([nn.Linear(4 * w[i], w[i + 1]) for i in range(2)])
        # i=0: L2→L1, i=1: L1→L0 (декодер идёт сверху вниз)
        self.up = nn.ModuleList([nn.Linear(w[i + 1], 4 * w[i]) for i in (1, 0)])
        self.sk = nn.ParameterList([nn.Parameter(torch.ones(w[i])) for i in range(2)])

        self.tmlp = nn.Sequential(nn.Linear(cfg.t_dim, cfg.cond_dim), nn.SiLU(),
                                  nn.Linear(cfg.cond_dim, cfg.cond_dim))
        self.kv_norm = RMSNorm(cfg.text_dim)     # масштаб текста не зависит от длины
        # пул текста в adaLN НЕ тяням: по опыту владельца он мешает (на ранних
        # этапах чуть помогает, дальше только вредит). Условие — только кросс-внимание.
        self.xk = nn.ModuleList([nn.Linear(cfg.text_dim, 2 * wi, bias=False) for wi in w])
        self.out_norm = RMSNorm(w[0])
        self.out = nn.Linear(w[0], cfg.latent_ch)
        nn.init.zeros_(self.out.weight)
        nn.init.zeros_(self.out.bias)

    @staticmethod
    def _down(x, gh, gw, proj):
        B = x.shape[0]
        d = x.view(B, gh // 2, 2, gw // 2, 2, -1).permute(0, 1, 3, 2, 4, 5).reshape(B, (gh // 2) * (gw // 2), -1)
        return proj(d)

    @staticmethod
    def _up(x, gh, gw, proj):
        B = x.shape[0]
        d = proj(x).view(B, gh, gw, 2, 2, -1).permute(0, 1, 3, 2, 4, 5).reshape(B, 4 * gh * gw, -1)
        return d

    def _kv(self, lvl: int, text):
        B, Ln, _ = text.shape
        h = self.cfg.levels[lvl].heads
        k, v = self.xk[lvl](text).chunk(2, dim=-1)
        hd = k.shape[-1] // h
        return (k.reshape(B, Ln, h, hd).transpose(1, 2), v.reshape(B, Ln, h, hd).transpose(1, 2))

    def forward(self, z, t, text=None, text_mask=None):
        cfg = self.cfg
        B, _, gh, gw = z.shape
        if gh % cfg.win or gw % cfg.win:
            raise ValueError(
                f"сетка {gh}×{gw} не делится на окно {cfg.win}: сторона входной картинки "
                f"должна быть кратна {8 * cfg.win} px (сейчас латент {gh}×{gw}, "
                f"то есть картинка {gh * 8}×{gw * 8})")
        x = self.stem(z).flatten(2).transpose(1, 2)
        x = x + self.pe[0](sincos_2d(gh, gw, cfg.pe_dim, x.device, x.dtype))

        cond = self.tmlp(t_embed(t, cfg.t_dim).to(x.dtype))    # только время, без текста
        tn = self.kv_norm(text) if text is not None else None
        kv = [self._kv(i, tn) if tn is not None else None for i in range(3)]

        skips = []
        for lvl in range(3):
            for blk in self.enc[lvl]:
                x = blk(x, blk.ada(cond), gh, gw, kv[lvl], text_mask)
            if lvl < 2:
                skips.append(x)
                x = self._down(x, gh, gw, self.dn[lvl])
                gh, gw = gh // 2, gw // 2
                x = x + self.pe[lvl + 1](sincos_2d(gh, gw, cfg.pe_dim, x.device, x.dtype))

        for i, lvl in enumerate((1, 0)):
            x = self._up(x, gh, gw, self.up[i]) + self.sk[lvl] * skips.pop()
            gh, gw = gh * 2, gw * 2
            # PE уровня уже лежит в скипе — второй раз не добавляем
            for blk in self.dec[lvl]:
                x = blk(x, blk.ada(cond), gh, gw, kv[lvl], text_mask)

        return self.out(self.out_norm(x)).transpose(1, 2).reshape(B, cfg.latent_ch, gh, gw)


# ---------------------------------------------------------------- модель
class UDiT(nn.Module):
    def __init__(self, ae, cfg: Cfg | None = None, text_dim: int | None = None):
        super().__init__()
        cfg = cfg or Cfg()
        if text_dim is not None:
            cfg = replace(cfg, text_dim=text_dim)
        self.cfg, self.ae = cfg, ae
        self.body = Body(cfg)
        # обучаемый «пустой» текст для CFG: лучше, чем энкодер пустой строки
        self.null_text = nn.Parameter(torch.randn(1, cfg.text_dim) * 0.02)

    def to_raw(self, z):
        return z * self.ae.latent_std + self.ae.latent_mean

    @torch.no_grad()
    def sample(self, text, text_mask, gh, gw, steps=24, cfg_scale=3.0, shift=0.3,
               generator=None, latent_only=False, null_text=None, noise=None):
        """Эйлер от t=0 (шум) к t=1 (данные). Условная и пустая ветки — одним батчем."""
        dev = self.ae.device
        B = text.shape[0]
        times = torch.linspace(0.0, 1.0, steps + 1, device=dev, dtype=torch.float32)
        if shift:
            times = (shift * times) / (1.0 + (shift - 1.0) * times)
        if noise is None:
            z = torch.randn(B, self.cfg.latent_ch, gh, gw, device=dev, dtype=torch.float32, generator=generator)
        else:                                  # один и тот же старт для всех промптов
            z = noise.expand(B, -1, -1, -1).float().clone()
        uncond = cfg_scale != 1.0 or null_text is not None
        if uncond:
            # пустая ветка: один реальный токен в позиции 0, остальное замаскировано —
            # ровно та же раскладка, что и при drop-text в обучении
            L = text.shape[1]
            nt = self.null_text.to(text.dtype).view(1, 1, -1).expand(B, L, -1)
            nmask = torch.zeros(B, L, dtype=torch.bool, device=dev)
            nmask[:, 0] = True
            text2 = torch.cat([text, nt], 0)
            mask2 = torch.cat([text_mask, nmask], 0)
        with torch.autocast(dev.type, torch.bfloat16, enabled=dev.type == "cuda"):
            for i in range(steps):
                t = times[i].expand(B)
                if uncond:
                    # батч собран как [условная; пустая] — первая половина это cond
                    out = self.body(torch.cat([z, z], 0), t.repeat(2), text2, mask2).float()
                    cond, null = out.chunk(2, 0)
                    if self.cfg.predict == "x":
                        vc, vu = x_to_v(cond, z, t), x_to_v(null, z, t)
                    else:
                        vc, vu = cond, null
                    v = vu + cfg_scale * (vc - vu)      # CFG: уходим от пустой ветки к подписи
                else:
                    out = self.body(z, t, text, text_mask).float()
                    v = x_to_v(out, z, t) if self.cfg.predict == "x" else out
                z = z + (times[i + 1] - times[i]) * v
        if latent_only:
            return z
        return self.ae.decode_raw(self.to_raw(z))


# ---------------------------------------------------------------- бюджеты
def count_params(body: Body) -> dict:
    per = {}
    for part in ("enc", "dec"):
        for lvl in range(3):
            per[f"{part}{lvl}"] = sum(p.numel() for blk in getattr(body, part)[lvl]
                                      for p in blk.parameters()) / 1e6
    rest = sum(p.numel() for n, p in body.named_parameters()
               if not n.startswith(("enc.", "dec."))) / 1e6
    return {"total": sum(p.numel() for p in body.parameters()) / 1e6, "per_stack": per, "rest": rest}


def tokens_at(cfg: Cfg, image_size: int = 256) -> list[int]:
    """Латент f8, patch=1: уровень i — сетка (size/8) / 2^i."""
    n0 = (image_size // 8) ** 2
    return [n0, n0 // 4, n0 // 16]


def count_flops(cfg: Cfg, tokens: list[int], text_len: int) -> dict:
    """FLOPs одного forward по уровням, аналитически из состава блоков."""
    per = []
    for lvl in range(3):
        w, n = cfg.levels[lvl].width, tokens[lvl]
        fl = 0.0
        for kind in cfg.kinds(lvl, "enc") + cfg.kinds(lvl, "dec"):
            if kind == CONV:
                fl += 2 * n * (6 * w * w + 9 * w)        # dw 3×3 + MLP ×2
                nsub = 2
            else:
                fl += 2 * n * 10 * w * w                 # qkv/o/ffn/xq/xo
                ctx = cfg.win * cfg.win if kind == WIN else n
                fl += 2 * 4 * n * ctx * w                # qk + av
                nsub = 3
            fl += 2 * 4 * n * text_len * w               # кросс-внимание к тексту
            fl += 2 * 3 * nsub * cfg.cond_dim * w       # ada (считается на батч, не на токен)
        per.append(fl)
    total = sum(per)
    return {"total_gflop": total / 1e9, "per_level_gflop": [x / 1e9 for x in per],
            "share": [x / total for x in per]}


def params_of(cfg: Cfg) -> dict:
    """Аналитический счёт параметров (сверяется с живой моделью в selftest)."""
    per_stack, cd = {}, cfg.cond_dim
    for part in ("enc", "dec"):
        for lvl in range(3):
            w = cfg.levels[lvl].width
            n = 0.0
            for kind in cfg.kinds(lvl, part):
                if kind == CONV:      # dw + MLP×2 + xq/xo + norms + ada(n=2) + xqk
                    n += 6 * w * w + 24 * w + 6 * cd * w
                else:                 # qkv/o/ffn + xq/xo + qk + norms + ada(n=3) + xqk
                    n += 10 * w * w + 20 * w + 9 * cd * w
            per_stack[f"{part}{lvl}"] = n / 1e6
    w = [lv.width for lv in cfg.levels]
    ch, td = cfg.latent_ch, cfg.text_dim
    extra = (ch * w[0] * 9 + w[0]) + sum(cfg.pe_dim * wi for wi in w)
    extra += sum(4 * w[i] * w[i + 1] + w[i + 1] for i in range(2))            # down
    extra += sum(4 * w[i] * w[i + 1] for i in range(2))                       # up
    extra += sum(w[i] for i in range(2))                                      # skips
    extra += cfg.t_dim * cd + cd + cd * cd + cd                              # tmlp
    extra += sum(td * 2 * wi for wi in w)
    extra += 2 * td                                              # p_norm, kv_norm
    extra += w[0] + w[0] * ch + ch                                            # out_norm / out
    return {"total": (sum(per_stack.values()) * 1e6 + extra) / 1e6,
            "per_stack": per_stack, "extra": extra / 1e6}