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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
import csv
import hashlib
import json
import tempfile
import time
import math
import os
import random
import re
from collections import Counter, defaultdict
from pathlib import Path

import numpy as np
import torch
from PIL import Image, ImageOps
from torch import nn
from torch.nn import functional as F

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
HOME = Path(__file__).resolve().parent
DATA = HOME.parent / "Image Datasets"
CHECKPOINT = HOME / "model.pt"
FORMATS = {".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp", ".jfif"}
MAX_ADDED_BLOCKS = 16


def words(s):
    return re.findall(r"[^\W_]+", s.lower())[:32]


def clean(s):
    return re.sub(r"\s+", " ", re.sub(r"[_\-.]+", " ", s)).strip()


def filename_label(stem):
    name = clean(stem)
    if re.fullmatch(r"(?:image|img|dsc|photo|download|hqdefault|hq720|maxresdefault|screenshot)?[\s\d()]*", name, re.I):
        return ""
    if re.search(r"[a-z0-9]{16,}", stem, re.I) or not re.search(r"[a-zA-Z]{3}", name):
        return ""
    return name


def file_stamp(entry):
    if entry is None:
        return None
    info = entry.stat()
    return [info.st_size, info.st_mtime_ns]


def folder_label(directory):
    label = re.sub(r"^\d+[.]|[-]101$|[ _-]+dataset$", "", directory.name, flags=re.I)
    return clean(label) or directory.name


def index(root, report, stop, folder_captions=False):
    root = Path(root).resolve()
    key = hashlib.sha256(os.path.normcase(str(root)).encode()).hexdigest()
    folder = HOME / ".dataset-index"
    cache = folder / (key + ".v1.json")
    try:
        with cache.open(encoding="utf-8") as f:
            old = json.load(f)
    except (OSError, ValueError):
        old = {}
    current = {}
    groups = defaultdict(list)
    counts = Counter()
    seen = set()
    pending = [root]
    hashed = reused = 0
    last_update = 0
    while pending and not stop.is_set():
        p = pending.pop()
        parts = p.relative_to(root).parts
        with os.scandir(p) as listing:
            entries = sorted(listing, key=lambda e: e.name)
        files = {}
        for entry in entries:
            if entry.is_dir(follow_symlinks=False):
                pending.append(Path(entry.path))
            elif entry.is_file():
                files[os.path.normcase(entry.name)] = entry
        csv_entry = files.get("metadata.csv")
        csv_stamp = file_stamp(csv_entry)
        meta = None
        for entry in files.values():
            if stop.is_set():
                break
            path = Path(entry.path)
            if path.suffix.lower() not in FORMATS:
                continue
            if time.monotonic() - last_update >= 1:
                report(f"Checking {p.name} | {reused:,} hashes reused | {hashed:,} images read")
                last_update = time.monotonic()
            name = str(path.relative_to(root))
            prior = old.get(name)
            try:
                stamp = file_stamp(entry)
                if prior and prior[0] == stamp:
                    digest = prior[1]
                    reused += 1
                else:
                    digest = hashlib.sha256(path.read_bytes()).hexdigest()
                    hashed += 1
                side = files.get(os.path.normcase(path.with_suffix(".txt").name))
                caption_stamp = [file_stamp(side), csv_stamp]
                if prior and prior[2] == caption_stamp:
                    caption, source = prior[3:]
                else:
                    source = "sidecar"
                    caption = Path(side.path).read_text(encoding="utf-8-sig", errors="replace").strip() if side else ""
                    if not caption and csv_entry:
                        if meta is None:
                            with open(csv_entry.path, encoding="utf-8-sig", errors="replace", newline="") as f:
                                meta = {r["file"]: (r.get("caption") or "").strip() for r in csv.DictReader(f) if r.get("file")}
                        source, caption = "CSV", meta.get(path.name, "")
                    if not caption:
                        source, caption = "filename", filename_label(path.stem)
                    if not caption:
                        source = "folder"
                        label = p.name if parts else ""
                        caption = clean(re.sub(r"^\d+[.]|[- ]?dataset$|[-]101$", "", label, flags=re.I))
                current[name] = [stamp, digest, caption_stamp, caption, source]
                if folder_captions:
                    caption, source = folder_label(p), "folder"
                if digest in seen or not words(caption):
                    continue
                seen.add(digest)
                groups[parts[0] if parts else "."].append((path, caption))
                counts[source] += 1
            except OSError:
                continue
    if not stop.is_set() and (current != old or not cache.exists()):
        folder.mkdir(exist_ok=True)
        with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=folder, delete=False) as f:
            temp = Path(f.name)
        try:
            with temp.open("w", encoding="utf-8") as f:
                json.dump(current, f, separators=(",", ":"))
            os.replace(temp, cache)
        finally:
            temp.unlink(missing_ok=True)
    report(f"{len(seen):,} unique labeled files | {reused:,} hashes reused | {hashed:,} images read. Caption sources {dict(counts)}")
    return groups


class Block(nn.Module):
    def __init__(self, a, b):
        super().__init__()
        self.conv = nn.Conv2d(a, b, 3, padding=1)
        self.norm = nn.GroupNorm(8, b)
        self.condition = nn.Linear(128, b * 2)
        self.out = nn.Conv2d(b, b, 3, padding=1)
        self.skip = nn.Conv2d(a, b, 1) if a != b else nn.Identity()

    def forward(self, x, c):
        scale, bias = self.condition(c)[:, :, None, None].chunk(2, 1)
        h = self.norm(self.conv(x)) * (1 + scale) + bias
        return self.skip(x) + self.out(F.silu(h))


def block_parameters():
    with torch.device("meta"):
        block = Block(128, 128)
    return sum(p.numel() for p in block.parameters())


class Model(nn.Module):
    def __init__(self, n, blocks=0):
        super().__init__()
        self.emb = nn.Embedding(n, 128, padding_idx=0)
        self.time = nn.Sequential(nn.Linear(32, 128), nn.SiLU(), nn.Linear(128, 128))
        self.register_buffer("freq", torch.exp(torch.linspace(0, math.log(1000), 16)))
        self.a = Block(3, 32)
        self.b = Block(32, 64)
        self.c = Block(64, 128)
        self.d = Block(128, 128)
        self.e = Block(192, 64)
        self.f = Block(96, 32)
        self.out = nn.Conv2d(32, 3, 3, padding=1)
        self.extra = nn.ModuleList()
        self.add_blocks(blocks)

    def add_blocks(self, count):
        for _ in range(count):
            block = Block(128, 128)
            nn.init.zeros_(block.out.weight)
            nn.init.zeros_(block.out.bias)
            self.extra.append(block)

    def forward(self, x, t, ids):
        phase = t[:, None] * self.freq
        cond = self.time(torch.cat([phase.sin(), phase.cos()], 1))
        cond = cond + self.emb(ids).sum(1) / ids.ne(0).sum(1, keepdim=True).clamp_min(1).sqrt()
        a = self.a(x, cond)
        b = self.b(F.avg_pool2d(a, 2), cond)
        c = self.c(F.avg_pool2d(b, 2), cond)
        h = self.d(F.avg_pool2d(c, 2), cond)
        for block in self.extra:
            h = block(h, cond)
        h = F.interpolate(h, scale_factor=2) + c
        h = self.e(torch.cat([F.interpolate(h, scale_factor=2), b], 1), cond)
        return self.out(self.f(torch.cat([F.interpolate(h, scale_factor=2), a], 1), cond))


def encode(captions, vocab):
    rows = []
    for s in captions:
        ids = [vocab.get(w, 1) for w in words(s)]
        rows.append(ids + [0] * (32 - len(ids)))
    return torch.tensor(rows, device=DEVICE)


def training_vocab(groups, saved):
    counts = Counter(w for group in groups.values() for _, s in group for w in words(s))
    if saved is None:
        return {w: i+2 for i, (w, _) in enumerate(counts.most_common(16000))}
    vocab = dict(saved["vocab"])
    for word in counts:
        if word not in vocab:
            vocab[word] = len(vocab) + 2
    return vocab


def analyze_size(root, checkpoint, report, stop, folder_captions=False):
    groups = index(root, report, stop, folder_captions)
    if stop.is_set():
        return None
    if not groups:
        raise ValueError("No labeled images found")
    saved = torch.load(checkpoint, map_location="cpu", weights_only=True) if checkpoint else None
    existing = saved.get("blocks", 0) if saved else 0
    vocab = training_vocab(groups, saved)
    # Meta tensors let us count the actual architecture without allocating weights.
    with torch.device("meta"):
        model = Model(len(vocab) + 2, existing)
    base_count = sum(p.numel() for p in model.parameters())
    per_block = block_parameters()
    images = sum(map(len, groups.values()))
    # Conservative starting tiers for experimentation, measured in total extra blocks.
    suggested = sum(images >= threshold for threshold in (1000, 4000, 10000, 25000))
    return images, base_count, per_block, max(0, suggested - existing)


ASPECT_RATIOS = {"1:1": (1, 1), "3:4": (3, 4), "4:3": (4, 3),
                 "1:2": (1, 2), "2:1": (2, 1)}


def canvas_size(resolution, ratio):
    w, h = ASPECT_RATIOS[ratio]
    return resolution * w // max(w, h), resolution * h // max(w, h)


def prepare_image(image, canvas, framing):
    rgb = ImageOps.exif_transpose(image).convert("RGB")
    if framing == "Fit with padding":
        return ImageOps.pad(rgb, canvas, method=Image.Resampling.BICUBIC, color="black")
    return ImageOps.fit(rgb, canvas, method=Image.Resampling.BICUBIC)


def train(root, target, steps, stop, report, *, source=None, resolution=None, lr=None,

          batch_size=16, folder_captions=False, progress=None, preview=None,

          preview_interval=100, preview_count=1, preview_prompt="", add_blocks=0, aspect_ratio=None, framing=None):
    if type(add_blocks) is not int or not 0 <= add_blocks <= MAX_ADDED_BLOCKS:
        raise ValueError(f"Choose between 0 and {MAX_ADDED_BLOCKS} additional blocks.")
    if add_blocks and target.exists() and source is None:
        raise ValueError("To expand an existing model, choose it under Fine-tune from and enter a new output filename.")
    if type(batch_size) is not int or batch_size < 1:
        raise ValueError("Batch size must be a positive integer.")
    if preview and (preview_interval < 1 or not 1 <= preview_count <= 4):
        raise ValueError("Choose a positive preview interval and 1 to 4 images.")
    if source is not None and target.exists():
        raise ValueError("Fine-tuning needs a new output filename. To resume, clear the base checkpoint field.")
    if source is not None and not source.is_file():
        raise ValueError("Base checkpoint does not exist.")
    checkpoint = source or target
    saved = torch.load(checkpoint, map_location="cpu", weights_only=True) if checkpoint.exists() else None
    previous_size = saved.get("resolution", 64) if saved else 64
    resolution = previous_size if resolution is None else resolution
    if resolution not in (64, 96, 128):
        raise ValueError("Choose 64, 96, or 128 pixels.")
    if saved and source is None and previous_size != resolution:
        raise ValueError("To change resolution, select a base checkpoint and a new output file.")
    previous_ratio = saved.get("aspect_ratio", "1:1") if saved else "1:1"
    aspect_ratio = aspect_ratio or previous_ratio
    framing = framing or (saved.get("framing", "Center crop") if saved else "Center crop")
    if aspect_ratio not in ASPECT_RATIOS or framing not in ("Center crop", "Fit with padding"):
        raise ValueError("Choose a supported aspect ratio and image framing.")
    if saved and source is None and aspect_ratio != previous_ratio:
        raise ValueError("To change aspect ratio, select a base checkpoint and a new output file.")
    canvas = canvas_size(resolution, aspect_ratio)
    if lr is not None and not 0 < lr <= 1:
        raise ValueError("Enter a positive learning rate up to 1.")

    groups = index(root, report, stop, folder_captions)
    if stop.is_set():
        return
    if not groups:
        raise ValueError("No labeled images found")
    vocab = training_vocab(groups, saved)
    if preview:
        if preview_prompt and not any(w in vocab for w in words(preview_prompt)):
            raise ValueError("The preview prompt has no words in this model’s vocabulary. Change it or leave it blank for dataset captions.")
        preview_rng = random.Random()
        caption_pool = [] if preview_prompt else list(dict.fromkeys(
            s for group in groups.values() for _, s in group if any(w in vocab for w in words(s))))
        deck = []
    model = Model(len(vocab)+2, saved.get("blocks", 0) if saved else 0)
    step = 0
    if saved:
        old_embedding = saved["model"]["emb.weight"]
        expanded = old_embedding.shape != model.emb.weight.shape
        if expanded:
            weights = model.emb.weight.detach().cpu().clone()
            weights[:len(old_embedding)] = old_embedding
            saved["model"]["emb.weight"] = weights
        model.load_state_dict(saved["model"])
        step = saved["step"]
    model.add_blocks(add_blocks)
    model.to(DEVICE)
    opt = torch.optim.AdamW(model.parameters(), lr=0.0003)
    if saved:
        if source is None:
            opt.load_state_dict(saved["optimizer"])
            if expanded:
                state = opt.state[model.emb.weight]
                for key, value in list(state.items()):
                    if isinstance(value, torch.Tensor) and value.shape == old_embedding.shape:
                        padded = torch.zeros_like(model.emb.weight)
                        padded[:len(value)] = value
                        state[key] = padded
    if lr is not None:
        for group in opt.param_groups:
            group["lr"] = lr
    parameters = sum(p.numel() for p in model.parameters())
    report(f"Starting at step {step} on {DEVICE}, {resolution} px, batch {batch_size}, {parameters:,} parameters")
    pools = list(groups.values())
    weights = [math.sqrt(len(pool)) for pool in pools]
    start = step
    started = time.monotonic()
    last_update = started
    last_saved = start
    while step < start + steps and not stop.is_set():
        images, captions = [], []
        for pool in random.choices(pools, weights, k=batch_size):
            path, caption = random.choice(pool)
            try:
                with Image.open(path) as im:
                    rgb = prepare_image(im, canvas, framing)
                    images.append(np.asarray(rgb))
                captions.append(caption)
            except (OSError, ValueError, Image.DecompressionBombError):
                continue
        if not images:
            raise ValueError("Could not decode any images in this batch")
        x = torch.from_numpy(np.stack(images)).to(DEVICE).permute(0,3,1,2).float()/127.5-1
        noise = torch.randn_like(x)
        t = torch.rand(len(x), device=DEVICE)
        pred = model(torch.lerp(noise, x, t[:,None,None,None]), t, encode(captions, vocab))
        loss = F.mse_loss(pred, x-noise)
        opt.zero_grad()
        loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), 1)
        opt.step()
        step += 1
        completed = step - start
        if progress and (completed == 1 or completed == steps or time.monotonic() - last_update >= 0.4):
            current_loss = loss.item()
            last_update = time.monotonic()
            progress(completed, steps, step, current_loss, last_update - started)
        elif not progress and (completed == 1 or step % 25 == 0):
            report(f"Step {step}    loss {loss.item():.4f}")
        if step % 250 == 0 or step == start+steps or stop.is_set():
            report(f"Saving checkpoint at step {step:,}…")
            save_model(target, model, opt, vocab, step, resolution, aspect_ratio, framing)
            last_saved = step
            report(f"Saved step {step}")
        if preview and completed % preview_interval == 0 and not stop.is_set():
            report(f"Generating previews for step {step:,}…")
            model.eval()
            samples = []
            try:
                for slot in range(preview_count):
                    caption = preview_prompt
                    if not caption:
                        if not deck:
                            deck = caption_pool.copy()
                            preview_rng.shuffle(deck)
                        caption = deck.pop()
                    seed = slot + 1
                    image = sample(model, vocab, canvas, caption, seed, stop=stop)
                    if image is None:
                        break
                    samples.append((caption, seed, image))
                if samples:
                    preview(step, samples)
            finally:
                model.train()
            if progress:
                last_update = time.monotonic()
                progress(completed, steps, step, loss.item(), last_update - started)
    if stop.is_set() and step > last_saved:
        save_model(target, model, opt, vocab, step, resolution, aspect_ratio, framing)
    if progress and stop.is_set() and step > start and completed != steps:
        progress(completed, steps, step, loss.item(), time.monotonic() - started)
    return step - start


def save_model(path, model, opt, vocab, step, resolution, aspect_ratio="1:1", framing="Center crop"):
    temp = path.with_suffix(".partial")
    torch.save(dict(model=model.state_dict(), optimizer=opt.state_dict(), vocab=vocab, step=step,
                    resolution=resolution, aspect_ratio=aspect_ratio, framing=framing, blocks=len(model.extra)), temp)
    os.replace(temp, path)


@torch.inference_mode()
def load_generator(path):
    saved = torch.load(path, map_location="cpu", weights_only=True)
    model = Model(len(saved["vocab"])+2, saved.get("blocks", 0)).to(DEVICE).eval()
    model.load_state_dict(saved["model"])
    resolution = saved.get("resolution", 64)
    ratio = saved.get("aspect_ratio", "1:1")
    return model, saved["vocab"], resolution if ratio == "1:1" else canvas_size(resolution, ratio)


def generate(path, prompt, seed, *, progress=None):
    return sample(*load_generator(path), prompt, seed, progress=progress)


@torch.inference_mode()
def sample(model, vocab, size, prompt, seed, *, progress=None, stop=None):
    ids = encode([prompt], vocab)
    if not any(w in vocab for w in words(prompt)):
        raise ValueError("This checkpoint has none of the words in your prompt. Train with image captions and select the updated checkpoint.")
    rng = torch.Generator(device=DEVICE).manual_seed(seed)
    width, height = (size, size) if isinstance(size, int) else size
    x = torch.randn((1,3,height,width), generator=rng, device=DEVICE)
    for i in range(40):
        if stop is not None and stop.is_set():
            return None
        x += model(x, torch.tensor([i/40], device=DEVICE), ids)/40
        if progress and (i + 1) % 4 == 0:
            if DEVICE == "cuda":
                torch.cuda.synchronize()
            progress(i + 1, 40)
    return Image.fromarray(((x[0].clamp(-1,1)+1)*127.5).byte().permute(1,2,0).cpu().numpy())