File size: 5,599 Bytes
24baf68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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 io
import os
import tarfile
import zlib

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

JOINT = 24
N_TXT = 6


def tiny_base(seed: int = 0, n_single: int = 3):
    from diffusers import Flux2Transformer2DModel

    torch.manual_seed(seed)
    m = Flux2Transformer2DModel(patch_size=1, in_channels=128, num_layers=1, num_single_layers=n_single,
                                attention_head_dim=16, num_attention_heads=2, joint_attention_dim=JOINT,
                                timestep_guidance_channels=32, mlp_ratio=3.0, axes_dims_rope=(4, 4, 4, 4),
                                guidance_embeds=False)
    # diffusers zero-inits nothing here, but make the modulations non-trivial anyway
    with torch.no_grad():
        for p in m.parameters():
            p.add_(0.02 * torch.randn_like(p))
    return m.eval()


class TinyText:
    """caption -> deterministic [N_TXT, JOINT] embedding (seeded by crc32)."""

    def __call__(self, caps):
        out = []
        for c in caps:
            g = torch.Generator().manual_seed(zlib.crc32(c.encode()))
            out.append(torch.randn(N_TXT, JOINT, generator=g))
        return torch.stack(out).to(torch.bfloat16)


class TinyVAE(nn.Module):
    """[B, 3, H, W] in [-1, 1] -> packed [B, (H/16)(W/16), 128] via 16x16 average pool and a fixed linear map."""

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

    @torch.no_grad()
    def encode(self, x):
        p = F.avg_pool2d(x.float(), 16)  # [B, 3, 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):
        """packed [B, h*w, 128] -> [B, 3, 16h, 16w] in [-1, 1] (first 3 channels, nearest x16)."""
        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 tiny_lpips():
    import lpips

    from dwd_klein.losses import LPIPSLoss

    torch.manual_seed(5)
    lp = lpips.LPIPS(net="vgg", pretrained=False, pnet_rand=True, verbose=False)
    return LPIPSLoss(lp, autocast_dtype=None)


def tiny_disc(seed: int = 7):
    from dwd_klein.disc import DinoDisc, FrozenDINO

    torch.manual_seed(seed)
    bb = FrozenDINO(depth=3, key_depths=(1,), patch=8, d=32, heads=2, img_size=32)
    with torch.no_grad():
        for p in bb.parameters():
            p.normal_(0, 0.05)
    return DinoDisc(bb, ks=3)


def write_shards(root: str, buckets=("32x32", "48x32"), shards=2, per_shard=5, seed=0, split="train",
                 manifest=False, captions=False):
    """Tiny WebDataset tars in the docs/data_format.md layout: <root>/<split>/<WxH>/shard-XXXX.tar (jpg/txt/json).
    manifest=True also writes <root>/manifest.json; captions=True adds a 3-entry json.captions list."""
    import json

    from PIL import Image

    rng = np.random.default_rng(seed)
    entries, by_bucket = [], {}
    for b in buckets:
        W, H = map(int, b.split("x"))
        d = os.path.join(root, split, b)
        os.makedirs(d, exist_ok=True)
        for s in range(shards):
            path = os.path.join(d, f"shard-{s:04d}.tar")
            entries.append({"path": os.path.relpath(path, root), "split": split, "bucket": b, "count": per_shard})
            by_bucket[b] = {"count": by_bucket.get(b, {"count": 0})["count"] + per_shard}
            with tarfile.open(path, "w") as tf:
                for i in range(per_shard):
                    key = f"{b}_{s:02d}_{i:03d}"
                    meta = {"key": key, "bucket": b}
                    if captions:
                        meta["captions"] = [f"caption {key}", f"alt one {key}", f"alt two {key}"]
                    base = rng.integers(0, 255, (H // 8, W // 8, 3), dtype=np.uint8)
                    im = Image.fromarray(base).resize((W, H), Image.BILINEAR)
                    bio = io.BytesIO()
                    im.save(bio, format="JPEG", quality=95)
                    for ext, data in (("jpg", bio.getvalue()), ("txt", f"caption {key}".encode()),
                                      ("json", json.dumps(meta).encode())):
                        ti = tarfile.TarInfo(f"{key}.{ext}")
                        ti.size = len(data)
                        tf.addfile(ti, io.BytesIO(data))
    if manifest:
        with open(os.path.join(root, "manifest.json"), "w") as fh:
            json.dump({"format_version": 1, "shards": entries, "totals": {split: {"by_bucket": by_bucket}}}, fh)


def tiny_components(data_root: str, micro_batch: int = 2, seed: int = 0, k: int = 2, rank: int = 0, world: int = 1):
    from dwd_klein.data import BucketLoader
    from dwd_klein.model import DWDKlein

    model = DWDKlein(tiny_base(seed), k=k, prefix_dtype=torch.bfloat16)
    vae = TinyVAE()
    # the discriminator heads are seeded per rank, as scripts/train.py seeds every rank differently before the build:
    # the Trainer must broadcast them
    return dict(model=model, text=TinyText(), vae_encode=vae.encode, lpips=tiny_lpips(), disc=tiny_disc(7 + rank),
                loader=BucketLoader(data_root, micro_batch, rank, world, seed),
                lsq_loader=BucketLoader(data_root, micro_batch, rank, world, seed + 7777))