File size: 15,663 Bytes
28db2ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2026 SurjoLabs. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import math

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


try:
    from diffusers import ConfigMixin, ModelMixin
    from diffusers.configuration_utils import register_to_config

    HAS_DIFFUSERS = True
except ImportError:  # pragma: no cover
    import functools
    import inspect
    import json
    import os

    HAS_DIFFUSERS = False

    class ConfigMixin:
        def register_to_config(self, **kwargs):
            self._internal_dict = dict(kwargs)

        @property
        def config(self):
            return self._internal_dict

    def register_to_config(init):
        sig = inspect.signature(init)

        @functools.wraps(init)
        def wrapper(self, *args, **kwargs):
            bound = sig.bind(self, *args, **kwargs)
            bound.apply_defaults()
            out = init(self, *args, **kwargs)
            self.register_to_config(**{k: v for k, v in bound.arguments.items() if k != "self"})
            return out

        return wrapper

    class ModelMixin(nn.Module, ConfigMixin):
        config_name = "config.json"
        weights_name = "diffusion_pytorch_model.safetensors"

        def save_pretrained(self, save_directory, **kwargs):
            os.makedirs(save_directory, exist_ok=True)
            cfg = dict(self.config)
            cfg["_class_name"] = type(self).__name__
            cfg["_diffusers_version"] = "none"
            tmp = os.path.join(save_directory, self.config_name + ".tmp")
            with open(tmp, "w", encoding="utf-8") as f:
                json.dump(cfg, f, indent=2, sort_keys=True)
            os.replace(tmp, os.path.join(save_directory, self.config_name))
            from safetensors.torch import save_file

            clean = {k: v.detach().to("cpu", copy=True).contiguous() for k, v in self.state_dict().items()}
            tmp = os.path.join(save_directory, self.weights_name + ".tmp")
            save_file(clean, tmp)
            os.replace(tmp, os.path.join(save_directory, self.weights_name))

        @classmethod
        def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
            with open(os.path.join(pretrained_model_name_or_path, cls.config_name), encoding="utf-8") as f:
                cfg = json.load(f)
            cfg = {k: v for k, v in cfg.items() if not k.startswith("_") and k != "torch_dtype"}
            model = cls(**cfg)
            from safetensors.torch import load_file

            sd = load_file(os.path.join(pretrained_model_name_or_path, cls.weights_name))
            model.load_state_dict(sd, strict=True)
            return model


def timestep_embedding(t: torch.Tensor, dim: int, max_period: float = 10000.0) -> torch.Tensor:
    half = dim // 2
    freqs = torch.exp(
        -math.log(max_period) * torch.arange(half, dtype=torch.float32, device=t.device) / max(1, half)
    )
    args = t.float().unsqueeze(-1) * freqs.unsqueeze(0)
    emb = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
    if dim % 2:
        emb = F.pad(emb, (0, 1))
    return emb


class TimestepEmbedder(nn.Module):
    def __init__(self, hidden: int, freq_dim: int = 256, scale: float = 1000.0):
        super().__init__()
        self.freq_dim = freq_dim
        self.scale = scale
        self.mlp = nn.Sequential(nn.Linear(freq_dim, hidden), nn.SiLU(), nn.Linear(hidden, hidden))

    def forward(self, t: torch.Tensor) -> torch.Tensor:
        return self.mlp(timestep_embedding(self.scale * t, self.freq_dim))


FP_CLAMP = 65504.0  # bf16 max; keeps autocast casts finite


class RMSNorm1P(nn.Module):
    def __init__(self, dim: int, eps: float = 1e-6):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.zeros(dim))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps) * (1.0 + self.weight)


def rope_2d_tables(grid: int, head_half: int, theta: float = 10000.0) -> tuple[torch.Tensor, ...]:
    n_freq = head_half // 2  # one freq per rotate-half pair within each axis-half
    freqs = 1.0 / (theta ** (torch.arange(0, head_half, 2, dtype=torch.float32) / head_half))
    pos = torch.arange(grid, dtype=torch.float32)
    ang = torch.outer(pos, freqs)
    return torch.cos(ang), torch.sin(ang), torch.cos(ang), torch.sin(ang)


def apply_rope_2d(

    t: torch.Tensor,

    cos_h: torch.Tensor,

    sin_h: torch.Tensor,

    cos_w: torch.Tensor,

    sin_w: torch.Tensor,

    grid: int,

) -> torch.Tensor:
    b, h, _, d = t.shape
    half = d // 2
    t = t.view(b, h, grid, grid, d)
    ta, tb = t[..., :half], t[..., half:]

    def _rot(x, cos, sin):
        x1, x2 = x[..., 0::2], x[..., 1::2]
        o = torch.empty_like(x)
        o[..., 0::2] = x1 * cos - x2 * sin
        o[..., 1::2] = x1 * sin + x2 * cos
        return o

    ta = _rot(ta, cos_h[:, None, :], sin_h[:, None, :])
    tb = _rot(tb, cos_w[None, :, :], sin_w[None, :, :])
    return torch.cat([ta, tb], dim=-1).reshape(b, h, grid * grid, d)


class SelfAttention(nn.Module):
    def __init__(self, dim: int, heads: int, xsa: bool):
        super().__init__()
        self.heads = heads
        self.head_dim = dim // heads
        self.xsa = xsa
        self.qk_norm_q = RMSNorm1P(self.head_dim)
        self.qk_norm_k = RMSNorm1P(self.head_dim)
        self.qkv = nn.Linear(dim, dim * 3)
        self.proj = nn.Linear(dim, dim)

    def forward(self, x: torch.Tensor, rope=None) -> torch.Tensor:
        b, n, _ = x.shape
        q, k, v = self.qkv(x).chunk(3, dim=-1)
        q = q.view(b, n, self.heads, self.head_dim).transpose(1, 2)
        k = k.view(b, n, self.heads, self.head_dim).transpose(1, 2)
        v = v.view(b, n, self.heads, self.head_dim).transpose(1, 2)
        q = self.qk_norm_q(q)
        k = self.qk_norm_k(k)
        if rope is not None:
            cos_h, sin_h, cos_w, sin_w, grid = rope
            dt = q.dtype
            q = apply_rope_2d(q, cos_h.to(dt), sin_h.to(dt), cos_w.to(dt), sin_w.to(dt), grid)
            k = apply_rope_2d(k, cos_h.to(dt), sin_h.to(dt), cos_w.to(dt), sin_w.to(dt), grid)
        o = F.scaled_dot_product_attention(q, k, v)
        if self.xsa:
            # XSA (arXiv:2603.09078): strip each token's own value-component so attention carries context only
            v_hat = F.normalize(v.float(), dim=-1).to(o.dtype)
            o = o - v_hat * (v_hat.float() * o.float()).sum(dim=-1, keepdim=True).to(o.dtype)
        o = o.transpose(1, 2).reshape(b, n, -1)
        return self.proj(o)


class CrossAttention(nn.Module):
    def __init__(self, dim: int, heads: int):
        super().__init__()
        self.heads = heads
        self.head_dim = dim // heads
        self.qk_norm_q = RMSNorm1P(self.head_dim)
        self.qk_norm_k = RMSNorm1P(self.head_dim)
        self.q = nn.Linear(dim, dim)
        self.kv = nn.Linear(dim, dim * 2)
        self.proj = nn.Linear(dim, dim)

    def forward(

        self,

        x: torch.Tensor,

        ctx: torch.Tensor,

        ctx_mask: torch.Tensor | None = None,

    ) -> torch.Tensor:
        b, n, _ = x.shape
        m = ctx.shape[1]
        q = self.qk_norm_q(self.q(x).view(b, n, self.heads, self.head_dim).transpose(1, 2))
        kv = self.kv(ctx).view(b, m, 2, self.heads, self.head_dim)
        k = self.qk_norm_k(kv[:, :, 0].transpose(1, 2))
        v = kv[:, :, 1].transpose(1, 2)
        bias = None
        if ctx_mask is not None:
            bias = (1.0 - ctx_mask.to(dtype=q.dtype, device=q.device)) * (-1e4)
            bias = bias[:, None, None, :]
        o = F.scaled_dot_product_attention(q, k, v, attn_mask=bias)
        o = o.transpose(1, 2).reshape(b, n, -1)
        return self.proj(o)


class DiTBlock(nn.Module):
    def __init__(self, dim: int, heads: int, mlp_ratio: float, xsa: bool):
        super().__init__()
        self.norm1 = nn.LayerNorm(dim, elementwise_affine=False)
        self.attn = SelfAttention(dim, heads, xsa=xsa)
        self.norm_c = nn.LayerNorm(dim, elementwise_affine=True)
        self.cross = CrossAttention(dim, heads)
        self.norm2 = nn.LayerNorm(dim, elementwise_affine=False)
        hidden = max(8, (int(dim * mlp_ratio * 2 / 3) // 8) * 8)  # SwiGLU width at GELU-4x param parity
        self.mlp_gate = nn.Linear(dim, hidden)
        self.mlp_up = nn.Linear(dim, hidden)
        self.mlp_down = nn.Linear(hidden, dim)
        self.ada = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * 6))
        nn.init.zeros_(self.ada[-1].weight)
        nn.init.zeros_(self.ada[-1].bias)

    def forward(

        self,

        x: torch.Tensor,

        temb: torch.Tensor,

        ctx: torch.Tensor,

        ctx_mask: torch.Tensor | None = None,

        rope=None,

    ) -> torch.Tensor:
        shift1, scale1, gate1, shift2, scale2, gate2 = self.ada(temb).chunk(6, dim=-1)
        s1 = scale1.unsqueeze(1)
        g1 = gate1.unsqueeze(1)
        s2 = scale2.unsqueeze(1)
        g2 = gate2.unsqueeze(1)
        h = self.norm1(x)
        x = x + g1 * self.attn(h * (1.0 + s1) + shift1.unsqueeze(1), rope=rope)
        x = x + self.cross(self.norm_c(x), ctx, ctx_mask)
        h = self.norm2(x)
        h = h * (1.0 + s2) + shift2.unsqueeze(1)
        x = x + g2 * self.mlp_down(F.silu(self.mlp_gate(h)) * self.mlp_up(h))
        return x.clamp(-FP_CLAMP, FP_CLAMP)


class FinalLayer(nn.Module):
    def __init__(self, dim: int, out_ch: int):
        super().__init__()
        self.norm = nn.LayerNorm(dim, elementwise_affine=False)
        self.linear = nn.Linear(dim, out_ch)
        self.ada = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * 2))
        nn.init.zeros_(self.ada[-1].weight)
        nn.init.zeros_(self.ada[-1].bias)

    def forward(self, x: torch.Tensor, temb: torch.Tensor) -> torch.Tensor:
        shift, scale = self.ada(temb).chunk(2, dim=-1)
        h = self.norm(x) * (1.0 + scale.unsqueeze(1)) + shift.unsqueeze(1)
        return self.linear(h)


class SurjoImagePreviewDiT(ModelMixin, ConfigMixin):
    @register_to_config
    def __init__(

        self,

        dim: int = 512,

        heads: int = 8,

        mlp_ratio: float = 4.0,

        split: tuple[int, int, int] = (7, 4, 7),

        loop_iters: int = 4,

        xsa: bool = True,

        deepsup: bool = True,

        n_tokens: int = 256,

        in_ch: int = 128,

        text_dim: int = 1024,

        repa_dim: int = 384,  # DINOv2-S patch dim

        freq_dim: int = 256,

        t_scale: float = 1000.0,  # t arrives in [0,1]

        rope_theta: float = 10000.0,

    ):
        super().__init__()
        if dim % heads != 0:
            raise ValueError(f"dim {dim} must be divisible by heads {heads}")
        if len(split) != 3 or sum(split) < 3:
            raise ValueError(f"bad split {split}")
        self.dim = dim
        self.split = tuple(split)
        self.loop_iters = loop_iters
        self.deepsup = deepsup
        self.n_tokens = n_tokens
        self.in_ch = in_ch
        self.grid = int(math.sqrt(n_tokens))
        if self.grid * self.grid != n_tokens:
            raise ValueError(f"n_tokens {n_tokens} must be a perfect square")

        self.x_embed = nn.Linear(in_ch, dim)
        cos_h, sin_h, cos_w, sin_w = rope_2d_tables(self.grid, (dim // heads) // 2, theta=rope_theta)
        self.register_buffer("rope_cos_h", cos_h)
        self.register_buffer("rope_sin_h", sin_h)
        self.register_buffer("rope_cos_w", cos_w)
        self.register_buffer("rope_sin_w", sin_w)
        self.t_embed = TimestepEmbedder(dim, freq_dim=freq_dim, scale=t_scale)
        t_hidden = max(8, (text_dim * 2 // 8) * 8)
        self.ctx_in = RMSNorm1P(text_dim)
        self.ctx_mlp = nn.Sequential(
            nn.Linear(text_dim, t_hidden), nn.GELU(approximate="tanh"), nn.Linear(t_hidden, dim)
        )
        self.repa_proj = nn.Linear(dim, repa_dim)

        self.pre_blocks = nn.ModuleList(DiTBlock(dim, heads, mlp_ratio, xsa=False) for _ in range(split[0]))
        self.loop_blocks = nn.ModuleList(DiTBlock(dim, heads, mlp_ratio, xsa=xsa) for _ in range(split[1]))
        self.post_blocks = nn.ModuleList(DiTBlock(dim, heads, mlp_ratio, xsa=False) for _ in range(split[2]))
        self.final = FinalLayer(dim, in_ch)

    @property
    def n_effective_depth(self) -> int:
        return self.split[0] + self.split[1] * self.loop_iters + self.split[2]

    def forward(

        self,

        z: torch.Tensor,

        t: torch.Tensor,

        ctx: torch.Tensor,

        *,

        ctx_mask: torch.Tensor | None = None,

        deepsup: bool | None = None,

        loop_iters: int | None = None,

        capture_mid: bool = False,

    ) -> torch.Tensor | list[torch.Tensor] | tuple:
        deep = self.deepsup if deepsup is None else deepsup
        k = self.loop_iters if loop_iters is None else loop_iters
        if k < 1:
            raise ValueError(f"loop_iters must be >= 1, got {k}")

        b = z.shape[0]
        x = z.flatten(2).transpose(1, 2)  # raster order = DINO patch order (REPA cosine assumes it)
        if x.shape[1] != self.n_tokens:
            raise ValueError(f"expected {self.n_tokens} tokens, got {x.shape[1]}")
        x = self.x_embed(x)
        temb = self.t_embed(t)
        ctx = self.ctx_mlp(self.ctx_in(ctx))
        rope = (self.rope_cos_h, self.rope_sin_h, self.rope_cos_w, self.rope_sin_w, self.grid)

        for blk in self.pre_blocks:
            x = blk(x, temb, ctx, ctx_mask, rope=rope)
        mid = x if capture_mid else None

        exits: list[torch.Tensor] = []
        for _ in range(k):
            for blk in self.loop_blocks:
                x = blk(x, temb, ctx, ctx_mask, rope=rope)
            if deep:
                exits.append(x)

        def through_post_and_final(h: torch.Tensor) -> torch.Tensor:
            for blk in self.post_blocks:
                h = blk(h, temb, ctx, ctx_mask, rope=rope)
            out = self.final(h, temb)
            return out.transpose(1, 2).reshape(b, self.in_ch, self.grid, self.grid)

        if deep:
            outs = [through_post_and_final(h) for h in exits]
            return (outs, mid) if capture_mid else outs
        out = through_post_and_final(x)
        return (out, mid) if capture_mid else out

    def num_params(self) -> int:
        return sum(p.numel() for p in self.parameters())


_ROPE_BUFFERS = ("rope_cos_h", "rope_sin_h", "rope_cos_w", "rope_sin_w")


def load_ema_state(ema_model: nn.Module, ema_state: dict) -> None:
    missing, unexpected = ema_model.load_state_dict(ema_state, strict=False)
    bad_missing = [k for k in missing if k not in _ROPE_BUFFERS]
    if bad_missing or unexpected:
        raise RuntimeError(f"EMA load mismatch: missing={bad_missing} unexpected={unexpected}")