File size: 4,731 Bytes
baa0a0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tiny CPU stand-ins for the real components (random weights, no downloads). Imported by the tests after they put
src/ and tests/ on sys.path."""

from __future__ import annotations

import zlib

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

JOINT = 24
C_LAT = 64
K = 2


def tiny_transformer(seed: int = 0, n_layers: int = 4):
    """A small QwenImage21Transformer2DModel in bf16 with its timestep table in fp32, as from_pretrained(torch_dtype=
    bf16) loads the real one."""
    from diffusers import QwenImage21Transformer2DModel

    torch.manual_seed(seed)
    m = QwenImage21Transformer2DModel(patch_size=1, in_channels=C_LAT, out_channels=C_LAT, num_layers=n_layers,
                                      attention_head_dim=16, num_attention_heads=2, context_in_dim=JOINT, mlp_ratio=3,
                                      axes_dims_rope=(4, 6, 6), causal_condition=True)
    with torch.no_grad():  # non-trivial modulations / zero-centred norms
        for p in m.parameters():
            p.add_(0.02 * torch.randn_like(p))
    freqs = m.time_text_embed.time_proj.freqs.float().clone()
    m = m.to(torch.bfloat16).eval()
    m.time_text_embed.time_proj.freqs = freqs
    return m


def tiny_tail_state(transformer, k: int = K, seed: int = 1, proj_out: bool = True) -> dict[str, torch.Tensor]:
    """A trained-looking fp32 tail state dict (the layout of the fp32 export): copies of the transformer's last k
    blocks, time embedding, modulation and norm_out, perturbed, plus a random head and (optionally) proj_out."""
    g = torch.Generator().manual_seed(seed)
    n = len(transformer.transformer_blocks)
    sd = {}
    for i, b in enumerate(transformer.transformer_blocks[n - k:]):
        for name, v in b.state_dict().items():
            sd[f"blocks.{i}.{name}"] = v.float()
    for part in ("time_text_embed", "modulation", "norm_out"):
        for name, v in getattr(transformer, part).state_dict().items():
            sd[f"{part}.{name}"] = v.float()
    sd = {n_: v + 0.01 * torch.randn(v.shape, generator=g) for n_, v in sd.items()}
    D = transformer.config.num_attention_heads * transformer.config.attention_head_dim
    sd["head.weight"] = 0.05 * torch.randn(768, D, generator=g)
    sd["head.bias"] = 0.05 * torch.randn(768, generator=g)
    if proj_out:
        sd["proj_out.weight"] = transformer.proj_out.weight.float() + 0.01 * torch.randn(
            transformer.proj_out.weight.shape, generator=g)
    return sd


class TinyText:
    """(prompt, images) -> (embeds [1, L, JOINT] bf16, None, img_mask): deterministic per prompt (crc32 seed). With
    condition images, one vision-language slot per 2x2 latent tokens of each image is inserted after two text
    tokens, as the stock template places the image before the instruction."""

    def __call__(self, prompt, images=None):
        crc = zlib.crc32(prompt.encode())
        g = torch.Generator().manual_seed(crc)
        txt = torch.randn(4 + crc % 4, JOINT, generator=g)
        mask = torch.zeros(txt.shape[0], dtype=torch.bool)
        if images:
            slots = sum((im.size[0] // 16) * (im.size[1] // 16) // 4 for im in images)
            s = torch.randn(slots, JOINT, generator=g)
            txt = torch.cat([txt[:2], s, txt[2:]])
            mask = torch.cat([mask[:2], torch.ones(slots, dtype=torch.bool), mask[2:]])
        return txt[None].to(torch.bfloat16), None, mask[None]


class TinyVAE(nn.Module):
    """encode_vae_input: [B, 4, 1, H, W] -> packed [B, (H/16)(W/16), 64] via a 16x16 average pool and a fixed linear
    map; decode: packed [B, h*w, 64] -> [B, 3, 16h, 16w] in [-1, 1] (first 3 channels, nearest x16)."""

    has_decoder = True

    def __init__(self, seed: int = 1):
        super().__init__()
        g = torch.Generator().manual_seed(seed)
        self.register_buffer("w", torch.randn(C_LAT, 4, generator=g) * 0.5)

    @torch.no_grad()
    def encode_vae_input(self, x):
        p = F.avg_pool2d(x[:, :, 0].float(), 16)  # [B, 4, h, w]
        B, C, h, w = p.shape
        return (p.reshape(B, C, h * w).permute(0, 2, 1) @ self.w.t()).to(torch.bfloat16)

    @torch.no_grad()
    def decode(self, lat, h, w):
        x = lat.float()[..., :3].permute(0, 2, 1).reshape(lat.shape[0], 3, h, w)
        return torch.tanh(F.interpolate(x, scale_factor=16, mode="nearest"))


def sched():
    from diffusers import FlowMatchEulerDiscreteScheduler

    # the turbo checkpoint's scheduler_config.json
    return FlowMatchEulerDiscreteScheduler(base_image_seq_len=256, base_shift=0.5, max_image_seq_len=8192,
                                           max_shift=0.9, shift=1.0, time_shift_type="exponential",
                                           use_dynamic_shifting=False)