Upload 11 files
Browse files- ADiM 1.0.pt +3 -0
- Generate.bat +4 -0
- adamimg-177509509.png +0 -0
- adamimg-391060348.png +0 -0
- adamimg-3946196579.png +0 -0
- adamimg-4031264376.png +0 -0
- adamimg-4057671677.png +0 -0
- adamimg-692119127.png +0 -0
- adamimg-711453684.png +0 -0
- desktop.py +445 -0
- engine.py +448 -0
ADiM 1.0.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1ec93da357368856881e365c369c9faff6c58442cb37fa972a125252ec16b5ce
|
| 3 |
+
size 39800611
|
Generate.bat
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@echo off
|
| 2 |
+
cd /d "%~dp0"
|
| 3 |
+
"C:\Users\plays\AppData\Local\Programs\Python\Python310\python.exe" -c "from desktop import run; run(False)"
|
| 4 |
+
if errorlevel 1 pause
|
adamimg-177509509.png
ADDED
|
adamimg-391060348.png
ADDED
|
adamimg-3946196579.png
ADDED
|
adamimg-4031264376.png
ADDED
|
adamimg-4057671677.png
ADDED
|
adamimg-692119127.png
ADDED
|
adamimg-711453684.png
ADDED
|
desktop.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import queue
|
| 2 |
+
import random
|
| 3 |
+
import threading
|
| 4 |
+
import tkinter as tk
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from tkinter import filedialog, messagebox, ttk
|
| 7 |
+
|
| 8 |
+
from PIL import Image, ImageOps, ImageTk
|
| 9 |
+
import engine
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def duration(seconds):
|
| 13 |
+
minutes, seconds = divmod(round(seconds), 60)
|
| 14 |
+
hours, minutes = divmod(minutes, 60)
|
| 15 |
+
if hours:
|
| 16 |
+
return f"{hours}h {minutes:02}m"
|
| 17 |
+
return f"{minutes}m {seconds:02}s" if minutes else f"{seconds}s"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def run(training):
|
| 21 |
+
win = tk.Tk()
|
| 22 |
+
title = "Model trainer" if training else "Image generator"
|
| 23 |
+
win.title(f"AdamIMG · {title}")
|
| 24 |
+
win.configure(bg="#edf1f4")
|
| 25 |
+
style = ttk.Style(win)
|
| 26 |
+
style.theme_use("clam")
|
| 27 |
+
style.configure(".", font=("Segoe UI", 10), background="#ffffff", foreground="#1d3243")
|
| 28 |
+
style.configure("TEntry", padding=5, fieldbackground="#f7f9fa")
|
| 29 |
+
style.configure("TButton", padding=(10, 5))
|
| 30 |
+
style.configure("Primary.TButton", background="#136964", foreground="white")
|
| 31 |
+
style.map("Primary.TButton", background=[("disabled", "#788c8b"), ("active", "#0c5450")])
|
| 32 |
+
style.configure("TProgressbar", troughcolor="#e5edef", background="#208279",
|
| 33 |
+
borderwidth=0, thickness=8)
|
| 34 |
+
banner = tk.Frame(win, bg="#183744", padx=20, pady=12)
|
| 35 |
+
banner.pack(fill="x")
|
| 36 |
+
tk.Label(banner, text="AdamIMG", font=("Segoe UI", 10, "bold"),
|
| 37 |
+
bg="#183744", fg="#99d7c9").pack(anchor="w")
|
| 38 |
+
tk.Label(banner, text=title, font=("Segoe UI", 19, "bold"),
|
| 39 |
+
bg="#183744", fg="white").pack(side="left")
|
| 40 |
+
tk.Label(banner, text=engine.DEVICE.upper(), font=("Segoe UI", 10),
|
| 41 |
+
bg="#183744", fg="#cce0e5").pack(side="right")
|
| 42 |
+
if training:
|
| 43 |
+
gallery = ttk.Frame(win, padding=12)
|
| 44 |
+
gallery.pack(side="right", fill="y", padx=(0, 14), pady=12)
|
| 45 |
+
gallery_title = tk.StringVar(value="Training previews")
|
| 46 |
+
ttk.Label(gallery, textvariable=gallery_title, font=("Segoe UI", 11, "bold")).pack(anchor="w")
|
| 47 |
+
tiles = ttk.Frame(gallery)
|
| 48 |
+
tiles.pack(anchor="nw", pady=8)
|
| 49 |
+
ttk.Label(tiles, text="Waiting for a training run.").grid()
|
| 50 |
+
panel = ttk.Frame(win, padding=14)
|
| 51 |
+
panel.pack(fill="x", padx=14, pady=(12, 0))
|
| 52 |
+
panel.columnconfigure(1, weight=1)
|
| 53 |
+
events = queue.Queue()
|
| 54 |
+
stop = threading.Event()
|
| 55 |
+
busy = False
|
| 56 |
+
analyzing = False
|
| 57 |
+
size_info = None
|
| 58 |
+
controls = []
|
| 59 |
+
|
| 60 |
+
def field(row, title, default, browse=None):
|
| 61 |
+
ttk.Label(panel, text=title).grid(row=row, column=0, sticky="w", padx=(0, 12))
|
| 62 |
+
value = tk.StringVar(value=str(default))
|
| 63 |
+
entry = ttk.Entry(panel, textvariable=value, width=48)
|
| 64 |
+
entry.grid(row=row, column=1, columnspan=1 if browse else 2, sticky="ew", pady=3)
|
| 65 |
+
controls.append(entry)
|
| 66 |
+
if browse:
|
| 67 |
+
def choose():
|
| 68 |
+
path = browse()
|
| 69 |
+
if path:
|
| 70 |
+
value.set(path)
|
| 71 |
+
button = ttk.Button(panel, text="Browse…", command=choose)
|
| 72 |
+
button.grid(row=row, column=2, padx=(6, 0))
|
| 73 |
+
controls.append(button)
|
| 74 |
+
return value
|
| 75 |
+
|
| 76 |
+
ck = field(0, "Output / resume checkpoint" if training else "Checkpoint", engine.CHECKPOINT,
|
| 77 |
+
(lambda: filedialog.asksaveasfilename(defaultextension=".pt", confirmoverwrite=False))
|
| 78 |
+
if training else filedialog.askopenfilename)
|
| 79 |
+
def choice(parent, title, values):
|
| 80 |
+
ttk.Label(parent, text=title).pack(side="left", padx=(8, 3))
|
| 81 |
+
value = tk.StringVar(value=values[0])
|
| 82 |
+
widget = ttk.Combobox(parent, textvariable=value, values=values, state="readonly",
|
| 83 |
+
width=max(map(len, values)))
|
| 84 |
+
widget.pack(side="left")
|
| 85 |
+
controls.append(widget)
|
| 86 |
+
return value
|
| 87 |
+
|
| 88 |
+
geometry_row = ttk.Frame(panel)
|
| 89 |
+
geometry_row.grid(row=4, column=1, columnspan=2, sticky="w")
|
| 90 |
+
if training:
|
| 91 |
+
data = field(1, "Image folder", engine.DATA, filedialog.askdirectory)
|
| 92 |
+
amount = field(2, "Additional steps", "1000")
|
| 93 |
+
base = field(3, "Fine-tune from (optional)", "", filedialog.askopenfilename)
|
| 94 |
+
resolution = tk.StringVar(value="Auto")
|
| 95 |
+
ttk.Label(panel, text="Resolution").grid(row=4, column=0, sticky="w")
|
| 96 |
+
sizes = ttk.Combobox(geometry_row, textvariable=resolution, values=("Auto", "64", "96", "128"),
|
| 97 |
+
state="readonly", width=10)
|
| 98 |
+
sizes.pack(side="left")
|
| 99 |
+
ratio = choice(geometry_row, "Ratio", ("Auto", *engine.ASPECT_RATIOS))
|
| 100 |
+
framing = choice(geometry_row, "Framing", ("Auto", "Center crop", "Fit with padding"))
|
| 101 |
+
controls.append(sizes)
|
| 102 |
+
rate = field(5, "Learning rate (optional)", "")
|
| 103 |
+
batch = field(6, "Batch size", "16")
|
| 104 |
+
folders = tk.BooleanVar(value=False)
|
| 105 |
+
captions = ttk.Checkbutton(panel, text="Use folder names as captions", variable=folders)
|
| 106 |
+
captions.grid(row=7, column=1, sticky="w")
|
| 107 |
+
controls.append(captions)
|
| 108 |
+
|
| 109 |
+
def preset():
|
| 110 |
+
parent = engine.HOME / "model2.pt"
|
| 111 |
+
output = parent.with_name("model2-96px.pt")
|
| 112 |
+
i = 2
|
| 113 |
+
while output.exists():
|
| 114 |
+
output = parent.with_name(f"model2-96px-{i}.pt")
|
| 115 |
+
i += 1
|
| 116 |
+
base.set(str(parent))
|
| 117 |
+
ck.set(str(output))
|
| 118 |
+
resolution.set("96")
|
| 119 |
+
amount.set("2000")
|
| 120 |
+
rate.set("0.0001")
|
| 121 |
+
batch.set("16")
|
| 122 |
+
|
| 123 |
+
preset_button = ttk.Button(panel, text="Model2 preset", command=preset)
|
| 124 |
+
preset_button.grid(row=7, column=2)
|
| 125 |
+
controls.append(preset_button)
|
| 126 |
+
preview_prompt = field(8, "Preview prompt", "")
|
| 127 |
+
ttk.Label(panel, text="Leave blank to cycle through dataset captions.",
|
| 128 |
+
foreground="#42636b").grid(row=9, column=1, columnspan=2, sticky="w")
|
| 129 |
+
ttk.Label(panel, text="Preview schedule").grid(row=10, column=0, sticky="w")
|
| 130 |
+
schedule = ttk.Frame(panel)
|
| 131 |
+
schedule.grid(row=10, column=1, columnspan=2, sticky="w", pady=(4, 0))
|
| 132 |
+
interval = tk.StringVar(value="100")
|
| 133 |
+
count_var = tk.StringVar(value="1")
|
| 134 |
+
for text, var, options in [("Every", interval, None), ("steps · Images", count_var, ("0", "1", "2", "3", "4"))]:
|
| 135 |
+
ttk.Label(schedule, text=text).pack(side="left", padx=(0, 5))
|
| 136 |
+
control = (ttk.Combobox(schedule, values=options, state="readonly", width=3, textvariable=var)
|
| 137 |
+
if options else ttk.Entry(schedule, width=6, textvariable=var))
|
| 138 |
+
control.pack(side="left", padx=(0, 6))
|
| 139 |
+
controls.append(control)
|
| 140 |
+
ttk.Label(schedule, text="(0 = off)", foreground="#42636b").pack(side="left")
|
| 141 |
+
ttk.Label(panel, text="Additional model blocks").grid(row=11, column=0, sticky="w")
|
| 142 |
+
blocks = tk.DoubleVar(value=0)
|
| 143 |
+
size_label = tk.StringVar()
|
| 144 |
+
block_params = engine.block_parameters()
|
| 145 |
+
advice = tk.StringVar(value="Check the dataset for a suggested size and exact parameter counts.")
|
| 146 |
+
|
| 147 |
+
def show_size(*_):
|
| 148 |
+
added = round(blocks.get())
|
| 149 |
+
label = f"+{added} blocks"
|
| 150 |
+
if size_info:
|
| 151 |
+
_, base_count, per_block, _ = size_info
|
| 152 |
+
label += f" · {base_count + added * per_block:,} parameters"
|
| 153 |
+
else:
|
| 154 |
+
label += f" · +{added * block_params:,} parameters"
|
| 155 |
+
size_label.set(label)
|
| 156 |
+
|
| 157 |
+
slider = ttk.Scale(panel, from_=0, to=engine.MAX_ADDED_BLOCKS, variable=blocks,
|
| 158 |
+
command=show_size)
|
| 159 |
+
slider.grid(row=11, column=1, sticky="ew", pady=5)
|
| 160 |
+
controls.append(slider)
|
| 161 |
+
ttk.Label(panel, textvariable=size_label).grid(row=12, column=1, sticky="w")
|
| 162 |
+
ttk.Label(panel, textvariable=advice, wraplength=500, foreground="#42636b").grid(
|
| 163 |
+
row=13, column=0, columnspan=3, sticky="w")
|
| 164 |
+
|
| 165 |
+
def reset_size(*_):
|
| 166 |
+
nonlocal size_info
|
| 167 |
+
size_info = None
|
| 168 |
+
advice.set("Check the dataset for a suggested size and exact parameter counts.")
|
| 169 |
+
show_size()
|
| 170 |
+
|
| 171 |
+
for setting in (data, folders, ck, base):
|
| 172 |
+
setting.trace_add("write", reset_size)
|
| 173 |
+
show_size()
|
| 174 |
+
|
| 175 |
+
def analyze():
|
| 176 |
+
nonlocal busy, analyzing
|
| 177 |
+
if busy:
|
| 178 |
+
return
|
| 179 |
+
root = Path(data.get())
|
| 180 |
+
if not data.get().strip() or not root.is_dir():
|
| 181 |
+
messagebox.showerror("Check settings", "Choose an image folder.")
|
| 182 |
+
return
|
| 183 |
+
checkpoint = Path(base.get().strip()) if base.get().strip() else None
|
| 184 |
+
if checkpoint is None and Path(ck.get()).is_file():
|
| 185 |
+
checkpoint = Path(ck.get())
|
| 186 |
+
use_folders = folders.get()
|
| 187 |
+
reset_size()
|
| 188 |
+
busy = analyzing = True
|
| 189 |
+
stop.clear()
|
| 190 |
+
for control in [go, *controls]:
|
| 191 |
+
control.state(["disabled"])
|
| 192 |
+
status.set("Checking dataset and model size…")
|
| 193 |
+
bar.configure(mode="indeterminate", value=0)
|
| 194 |
+
bar.start(18)
|
| 195 |
+
|
| 196 |
+
def scan():
|
| 197 |
+
try:
|
| 198 |
+
info = engine.analyze_size(root, checkpoint, lambda s: events.put(("status", s)),
|
| 199 |
+
stop, use_folders)
|
| 200 |
+
events.put(("size", info))
|
| 201 |
+
except Exception as exc:
|
| 202 |
+
events.put(("error", str(exc)))
|
| 203 |
+
finally:
|
| 204 |
+
events.put(("done", None))
|
| 205 |
+
threading.Thread(target=scan, daemon=True).start()
|
| 206 |
+
|
| 207 |
+
analyze_button = ttk.Button(panel, text="Check dataset", command=analyze)
|
| 208 |
+
analyze_button.grid(row=11, column=2, padx=(6, 0))
|
| 209 |
+
controls.append(analyze_button)
|
| 210 |
+
else:
|
| 211 |
+
prompt = field(1, "Prompt", "")
|
| 212 |
+
seed = field(2, "Starting seed (blank for random)", "")
|
| 213 |
+
count_var = tk.StringVar(value="1")
|
| 214 |
+
ttk.Label(panel, text="Images per prompt").grid(row=3, column=0, sticky="w")
|
| 215 |
+
count_box = ttk.Combobox(panel, textvariable=count_var, values=("1", "2", "3", "4"),
|
| 216 |
+
state="readonly", width=4)
|
| 217 |
+
count_box.grid(row=3, column=1, sticky="w")
|
| 218 |
+
controls.append(count_box)
|
| 219 |
+
ratio = choice(geometry_row, "Output ratio", ("Auto", *engine.ASPECT_RATIOS))
|
| 220 |
+
|
| 221 |
+
activity = ttk.Frame(win, padding=14)
|
| 222 |
+
activity.pack(fill="both", expand=True, padx=14, pady=10)
|
| 223 |
+
status = tk.StringVar(value="Ready to train" if training else "Ready to generate")
|
| 224 |
+
metrics = tk.StringVar()
|
| 225 |
+
ttk.Label(activity, textvariable=status, wraplength=580).pack(anchor="w")
|
| 226 |
+
bar = ttk.Progressbar(activity, maximum=100)
|
| 227 |
+
bar.pack(fill="x", pady=(9, 4))
|
| 228 |
+
ttk.Label(activity, textvariable=metrics, foreground="#42636b").pack(anchor="w")
|
| 229 |
+
if not training:
|
| 230 |
+
preview = ttk.Frame(activity)
|
| 231 |
+
preview.pack(pady=(8, 0))
|
| 232 |
+
actions = ttk.Frame(win, padding=(14, 8))
|
| 233 |
+
actions.pack(fill="x")
|
| 234 |
+
|
| 235 |
+
def start():
|
| 236 |
+
nonlocal busy
|
| 237 |
+
if busy:
|
| 238 |
+
return
|
| 239 |
+
try:
|
| 240 |
+
if not ck.get().strip() or Path(ck.get()).is_dir():
|
| 241 |
+
raise ValueError("Choose a checkpoint filename.")
|
| 242 |
+
path = Path(ck.get())
|
| 243 |
+
selected_ratio = None if ratio.get() == "Auto" else ratio.get()
|
| 244 |
+
if training:
|
| 245 |
+
selected_framing = None if framing.get() == "Auto" else framing.get()
|
| 246 |
+
root, steps = Path(data.get()), int(amount.get())
|
| 247 |
+
added = round(blocks.get())
|
| 248 |
+
preview_count = int(count_var.get())
|
| 249 |
+
every = int(interval.get()) if preview_count else 100
|
| 250 |
+
if every < 1:
|
| 251 |
+
raise ValueError("Steps per preview must be a positive integer.")
|
| 252 |
+
caption = preview_prompt.get().strip()
|
| 253 |
+
folder_captions = folders.get()
|
| 254 |
+
batch_size = int(batch.get())
|
| 255 |
+
if batch_size < 1:
|
| 256 |
+
raise ValueError("Batch size must be a positive integer.")
|
| 257 |
+
source = Path(base.get().strip()) if base.get().strip() else None
|
| 258 |
+
training_resolution = None if resolution.get() == "Auto" else int(resolution.get())
|
| 259 |
+
lr = float(rate.get()) if rate.get().strip() else None
|
| 260 |
+
if not data.get().strip() or not root.is_dir() or steps < 1:
|
| 261 |
+
raise ValueError("Choose an image folder and a positive step count.")
|
| 262 |
+
else:
|
| 263 |
+
description = prompt.get().strip()
|
| 264 |
+
number = int(seed.get()) if seed.get().strip() else random.randrange(2**32)
|
| 265 |
+
count = int(count_var.get())
|
| 266 |
+
if number < -(2**63) or number + count > 2**64:
|
| 267 |
+
raise ValueError("Starting seed is outside the supported range for this batch.")
|
| 268 |
+
if not description or not path.is_file():
|
| 269 |
+
raise ValueError("Choose a trained checkpoint and enter a prompt.")
|
| 270 |
+
except ValueError as exc:
|
| 271 |
+
messagebox.showerror("Check settings", str(exc))
|
| 272 |
+
return
|
| 273 |
+
stop.clear()
|
| 274 |
+
if training:
|
| 275 |
+
for tile in tiles.winfo_children():
|
| 276 |
+
tile.destroy()
|
| 277 |
+
gallery_title.set("Training previews")
|
| 278 |
+
hint = f"First preview after {every:,} steps." if every <= steps else "Preview interval exceeds this run."
|
| 279 |
+
ttk.Label(tiles, text=hint if preview_count else "Previews disabled.").grid()
|
| 280 |
+
busy = True
|
| 281 |
+
for control in [go, *controls]:
|
| 282 |
+
control.state(["disabled"])
|
| 283 |
+
if training:
|
| 284 |
+
secondary.state(["!disabled"])
|
| 285 |
+
status.set("Preparing training data…" if training else "Loading checkpoint…")
|
| 286 |
+
metrics.set("Estimating after the first training step…" if training else "")
|
| 287 |
+
bar.configure(mode="indeterminate", value=0)
|
| 288 |
+
bar.start(18)
|
| 289 |
+
|
| 290 |
+
def worker():
|
| 291 |
+
try:
|
| 292 |
+
if training:
|
| 293 |
+
completed = engine.train(root, path, steps, stop, lambda s: events.put(("status", s)),
|
| 294 |
+
source=source, resolution=training_resolution, aspect_ratio=selected_ratio, framing=selected_framing,
|
| 295 |
+
lr=lr, batch_size=batch_size,
|
| 296 |
+
folder_captions=folder_captions, add_blocks=added,
|
| 297 |
+
progress=lambda *p: events.put(("training", p)),
|
| 298 |
+
preview=(lambda *p: events.put(("preview", p))) if preview_count else None,
|
| 299 |
+
preview_interval=every, preview_count=preview_count, preview_prompt=caption)
|
| 300 |
+
if completed == steps:
|
| 301 |
+
message = "Training complete"
|
| 302 |
+
elif completed:
|
| 303 |
+
message = "Training stopped"
|
| 304 |
+
else:
|
| 305 |
+
message = "Stopped before the first step"
|
| 306 |
+
if completed:
|
| 307 |
+
message += f" · Saved {path.name}"
|
| 308 |
+
events.put(("finished", message))
|
| 309 |
+
else:
|
| 310 |
+
model, vocab, size = engine.load_generator(path)
|
| 311 |
+
if selected_ratio:
|
| 312 |
+
size = engine.canvas_size(size if isinstance(size, int) else max(size), selected_ratio)
|
| 313 |
+
for i in range(count):
|
| 314 |
+
def update(done, total):
|
| 315 |
+
events.put(("sampling", (i, count, done, total)))
|
| 316 |
+
image = engine.sample(model, vocab, size, description, number + i, progress=update)
|
| 317 |
+
events.put(("image", (i, count, image, number + i)))
|
| 318 |
+
except Exception as exc:
|
| 319 |
+
events.put(("error", str(exc)))
|
| 320 |
+
finally:
|
| 321 |
+
events.put(("done", None))
|
| 322 |
+
threading.Thread(target=worker, daemon=True).start()
|
| 323 |
+
|
| 324 |
+
def secondary_action():
|
| 325 |
+
if training:
|
| 326 |
+
stop.set()
|
| 327 |
+
secondary.state(["disabled"])
|
| 328 |
+
status.set("Stopping after the current operation…")
|
| 329 |
+
|
| 330 |
+
def save_image(image, number):
|
| 331 |
+
path = filedialog.asksaveasfilename(initialfile=f"adamimg-{number}.png",
|
| 332 |
+
defaultextension=".png", filetypes=[("PNG", "*.png")])
|
| 333 |
+
if path:
|
| 334 |
+
try:
|
| 335 |
+
image.save(path)
|
| 336 |
+
except OSError as exc:
|
| 337 |
+
messagebox.showerror("Save failed", str(exc))
|
| 338 |
+
|
| 339 |
+
def progress(done, total):
|
| 340 |
+
bar.stop()
|
| 341 |
+
bar.configure(mode="determinate", maximum=100, value=100 * done / total)
|
| 342 |
+
|
| 343 |
+
def poll():
|
| 344 |
+
nonlocal busy, analyzing, size_info
|
| 345 |
+
while not events.empty():
|
| 346 |
+
kind, val = events.get()
|
| 347 |
+
if kind == "size":
|
| 348 |
+
size_info = val
|
| 349 |
+
if val:
|
| 350 |
+
images, base_count, per_block, suggested = val
|
| 351 |
+
advice.set(f"{images:,} unique labeled images · Suggested starting size: "
|
| 352 |
+
f"+{suggested} blocks ({base_count + suggested * per_block:,} parameters). "
|
| 353 |
+
"This estimate uses image count alone.")
|
| 354 |
+
show_size()
|
| 355 |
+
status.set("Dataset check complete" if val else "Dataset check stopped")
|
| 356 |
+
metrics.set("")
|
| 357 |
+
elif kind == "training":
|
| 358 |
+
done, total, step, loss, elapsed = val
|
| 359 |
+
progress(done, total)
|
| 360 |
+
if not stop.is_set():
|
| 361 |
+
status.set(f"Training · Checkpoint step {step:,} · Loss {loss:.4f}")
|
| 362 |
+
detail = f"{done:,} / {total:,} steps ({100*done/total:.1f}%) · {duration(elapsed)} elapsed"
|
| 363 |
+
if done < total and not stop.is_set():
|
| 364 |
+
eta = duration(elapsed * (total - done) / done)
|
| 365 |
+
detail += f" · About {eta} left"
|
| 366 |
+
metrics.set(detail)
|
| 367 |
+
elif kind == "preview":
|
| 368 |
+
step, samples = val
|
| 369 |
+
gallery_title.set(f"Previews · Step {step:,}")
|
| 370 |
+
for tile in tiles.winfo_children():
|
| 371 |
+
tile.destroy()
|
| 372 |
+
for i, (caption, seed_value, img) in enumerate(samples):
|
| 373 |
+
tile = ttk.Frame(tiles, padding=3)
|
| 374 |
+
tile.grid(row=i // 2, column=i % 2, sticky="nw")
|
| 375 |
+
photo = ImageTk.PhotoImage(ImageOps.contain(img, (112, 112), Image.Resampling.NEAREST))
|
| 376 |
+
thumb = ttk.Label(tile, image=photo)
|
| 377 |
+
thumb.image = photo
|
| 378 |
+
thumb.pack()
|
| 379 |
+
label = caption if len(caption) <= 54 else caption[:53] + "…"
|
| 380 |
+
ttk.Label(tile, text=label, wraplength=112).pack(anchor="w")
|
| 381 |
+
ttk.Label(tile, text=f"Seed {seed_value}", foreground="#42636b").pack(anchor="w")
|
| 382 |
+
elif kind == "sampling":
|
| 383 |
+
i, count, done, total = val
|
| 384 |
+
progress(i * total + done, count * total)
|
| 385 |
+
status.set(f"Generating image {i+1} of {count}…")
|
| 386 |
+
metrics.set(f"Sampling step {done} of {total}")
|
| 387 |
+
elif kind == "image":
|
| 388 |
+
i, count, img, number = val
|
| 389 |
+
if i == 0:
|
| 390 |
+
for child in preview.winfo_children():
|
| 391 |
+
child.destroy()
|
| 392 |
+
tile = ttk.Frame(preview, padding=4)
|
| 393 |
+
tile.grid(row=i // 2, column=i % 2)
|
| 394 |
+
width = 256 if count == 1 else 144
|
| 395 |
+
photo = ImageTk.PhotoImage(ImageOps.contain(img, (width, width), Image.Resampling.NEAREST))
|
| 396 |
+
thumb = ttk.Label(tile, image=photo)
|
| 397 |
+
thumb.image = photo
|
| 398 |
+
thumb.pack()
|
| 399 |
+
ttk.Label(tile, text=f"Seed {number}").pack()
|
| 400 |
+
ttk.Button(tile, text="Save PNG", command=lambda im=img, n=number: save_image(im, n)).pack()
|
| 401 |
+
if i+1 == count:
|
| 402 |
+
status.set("Image ready" if count == 1 else f"{count} images ready")
|
| 403 |
+
metrics.set(f"{img.width} × {img.height} px")
|
| 404 |
+
elif kind == "error":
|
| 405 |
+
status.set("Dataset check failed" if analyzing else "Training failed" if training else "Generation failed")
|
| 406 |
+
metrics.set("")
|
| 407 |
+
messagebox.showerror("Operation failed", val)
|
| 408 |
+
elif kind == "finished":
|
| 409 |
+
status.set(val)
|
| 410 |
+
if training and size_info and "Saved " in val and not base.get().strip():
|
| 411 |
+
reset_size()
|
| 412 |
+
if str(bar.cget("mode")) == "indeterminate":
|
| 413 |
+
metrics.set("")
|
| 414 |
+
elif kind == "status":
|
| 415 |
+
if not stop.is_set():
|
| 416 |
+
status.set(val)
|
| 417 |
+
elif kind == "done":
|
| 418 |
+
if str(bar.cget("mode")) == "indeterminate":
|
| 419 |
+
progress(0, 1)
|
| 420 |
+
busy = analyzing = False
|
| 421 |
+
for control in [go, *controls]:
|
| 422 |
+
control.state(["!disabled"])
|
| 423 |
+
if training:
|
| 424 |
+
secondary.state(["disabled"])
|
| 425 |
+
win.after(100, poll)
|
| 426 |
+
|
| 427 |
+
def close():
|
| 428 |
+
if analyzing:
|
| 429 |
+
stop.set()
|
| 430 |
+
win.destroy()
|
| 431 |
+
elif busy and training:
|
| 432 |
+
secondary_action()
|
| 433 |
+
else:
|
| 434 |
+
win.destroy()
|
| 435 |
+
|
| 436 |
+
go = ttk.Button(actions, text="Train / resume" if training else "Generate image",
|
| 437 |
+
style="Primary.TButton", command=start)
|
| 438 |
+
go.pack(side="left")
|
| 439 |
+
if training:
|
| 440 |
+
secondary = ttk.Button(actions, text="Stop and save", command=secondary_action)
|
| 441 |
+
secondary.pack(side="left", padx=8)
|
| 442 |
+
secondary.state(["disabled"])
|
| 443 |
+
win.protocol("WM_DELETE_WINDOW", close)
|
| 444 |
+
poll()
|
| 445 |
+
win.mainloop()
|
engine.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import tempfile
|
| 5 |
+
import time
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import random
|
| 9 |
+
import re
|
| 10 |
+
from collections import Counter, defaultdict
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import torch
|
| 15 |
+
from PIL import Image, ImageOps
|
| 16 |
+
from torch import nn
|
| 17 |
+
from torch.nn import functional as F
|
| 18 |
+
|
| 19 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 20 |
+
HOME = Path(__file__).resolve().parent
|
| 21 |
+
DATA = HOME.parent / "Image Datasets"
|
| 22 |
+
CHECKPOINT = HOME / "model.pt"
|
| 23 |
+
FORMATS = {".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp", ".jfif"}
|
| 24 |
+
MAX_ADDED_BLOCKS = 16
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def words(s):
|
| 28 |
+
return re.findall(r"[^\W_]+", s.lower())[:32]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def clean(s):
|
| 32 |
+
return re.sub(r"\s+", " ", re.sub(r"[_\-.]+", " ", s)).strip()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def filename_label(stem):
|
| 36 |
+
name = clean(stem)
|
| 37 |
+
if re.fullmatch(r"(?:image|img|dsc|photo|download|hqdefault|hq720|maxresdefault|screenshot)?[\s\d()]*", name, re.I):
|
| 38 |
+
return ""
|
| 39 |
+
if re.search(r"[a-z0-9]{16,}", stem, re.I) or not re.search(r"[a-zA-Z]{3}", name):
|
| 40 |
+
return ""
|
| 41 |
+
return name
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def file_stamp(entry):
|
| 45 |
+
if entry is None:
|
| 46 |
+
return None
|
| 47 |
+
info = entry.stat()
|
| 48 |
+
return [info.st_size, info.st_mtime_ns]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def folder_label(directory):
|
| 52 |
+
label = re.sub(r"^\d+[.]|[-]101$|[ _-]+dataset$", "", directory.name, flags=re.I)
|
| 53 |
+
return clean(label) or directory.name
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def index(root, report, stop, folder_captions=False):
|
| 57 |
+
root = Path(root).resolve()
|
| 58 |
+
key = hashlib.sha256(os.path.normcase(str(root)).encode()).hexdigest()
|
| 59 |
+
folder = HOME / ".dataset-index"
|
| 60 |
+
cache = folder / (key + ".v1.json")
|
| 61 |
+
try:
|
| 62 |
+
with cache.open(encoding="utf-8") as f:
|
| 63 |
+
old = json.load(f)
|
| 64 |
+
except (OSError, ValueError):
|
| 65 |
+
old = {}
|
| 66 |
+
current = {}
|
| 67 |
+
groups = defaultdict(list)
|
| 68 |
+
counts = Counter()
|
| 69 |
+
seen = set()
|
| 70 |
+
pending = [root]
|
| 71 |
+
hashed = reused = 0
|
| 72 |
+
last_update = 0
|
| 73 |
+
while pending and not stop.is_set():
|
| 74 |
+
p = pending.pop()
|
| 75 |
+
parts = p.relative_to(root).parts
|
| 76 |
+
with os.scandir(p) as listing:
|
| 77 |
+
entries = sorted(listing, key=lambda e: e.name)
|
| 78 |
+
files = {}
|
| 79 |
+
for entry in entries:
|
| 80 |
+
if entry.is_dir(follow_symlinks=False):
|
| 81 |
+
pending.append(Path(entry.path))
|
| 82 |
+
elif entry.is_file():
|
| 83 |
+
files[os.path.normcase(entry.name)] = entry
|
| 84 |
+
csv_entry = files.get("metadata.csv")
|
| 85 |
+
csv_stamp = file_stamp(csv_entry)
|
| 86 |
+
meta = None
|
| 87 |
+
for entry in files.values():
|
| 88 |
+
if stop.is_set():
|
| 89 |
+
break
|
| 90 |
+
path = Path(entry.path)
|
| 91 |
+
if path.suffix.lower() not in FORMATS:
|
| 92 |
+
continue
|
| 93 |
+
if time.monotonic() - last_update >= 1:
|
| 94 |
+
report(f"Checking {p.name} | {reused:,} hashes reused | {hashed:,} images read")
|
| 95 |
+
last_update = time.monotonic()
|
| 96 |
+
name = str(path.relative_to(root))
|
| 97 |
+
prior = old.get(name)
|
| 98 |
+
try:
|
| 99 |
+
stamp = file_stamp(entry)
|
| 100 |
+
if prior and prior[0] == stamp:
|
| 101 |
+
digest = prior[1]
|
| 102 |
+
reused += 1
|
| 103 |
+
else:
|
| 104 |
+
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
| 105 |
+
hashed += 1
|
| 106 |
+
side = files.get(os.path.normcase(path.with_suffix(".txt").name))
|
| 107 |
+
caption_stamp = [file_stamp(side), csv_stamp]
|
| 108 |
+
if prior and prior[2] == caption_stamp:
|
| 109 |
+
caption, source = prior[3:]
|
| 110 |
+
else:
|
| 111 |
+
source = "sidecar"
|
| 112 |
+
caption = Path(side.path).read_text(encoding="utf-8-sig", errors="replace").strip() if side else ""
|
| 113 |
+
if not caption and csv_entry:
|
| 114 |
+
if meta is None:
|
| 115 |
+
with open(csv_entry.path, encoding="utf-8-sig", errors="replace", newline="") as f:
|
| 116 |
+
meta = {r["file"]: (r.get("caption") or "").strip() for r in csv.DictReader(f) if r.get("file")}
|
| 117 |
+
source, caption = "CSV", meta.get(path.name, "")
|
| 118 |
+
if not caption:
|
| 119 |
+
source, caption = "filename", filename_label(path.stem)
|
| 120 |
+
if not caption:
|
| 121 |
+
source = "folder"
|
| 122 |
+
label = p.name if parts else ""
|
| 123 |
+
caption = clean(re.sub(r"^\d+[.]|[- ]?dataset$|[-]101$", "", label, flags=re.I))
|
| 124 |
+
current[name] = [stamp, digest, caption_stamp, caption, source]
|
| 125 |
+
if folder_captions:
|
| 126 |
+
caption, source = folder_label(p), "folder"
|
| 127 |
+
if digest in seen or not words(caption):
|
| 128 |
+
continue
|
| 129 |
+
seen.add(digest)
|
| 130 |
+
groups[parts[0] if parts else "."].append((path, caption))
|
| 131 |
+
counts[source] += 1
|
| 132 |
+
except OSError:
|
| 133 |
+
continue
|
| 134 |
+
if not stop.is_set() and (current != old or not cache.exists()):
|
| 135 |
+
folder.mkdir(exist_ok=True)
|
| 136 |
+
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=folder, delete=False) as f:
|
| 137 |
+
temp = Path(f.name)
|
| 138 |
+
try:
|
| 139 |
+
with temp.open("w", encoding="utf-8") as f:
|
| 140 |
+
json.dump(current, f, separators=(",", ":"))
|
| 141 |
+
os.replace(temp, cache)
|
| 142 |
+
finally:
|
| 143 |
+
temp.unlink(missing_ok=True)
|
| 144 |
+
report(f"{len(seen):,} unique labeled files | {reused:,} hashes reused | {hashed:,} images read. Caption sources {dict(counts)}")
|
| 145 |
+
return groups
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class Block(nn.Module):
|
| 149 |
+
def __init__(self, a, b):
|
| 150 |
+
super().__init__()
|
| 151 |
+
self.conv = nn.Conv2d(a, b, 3, padding=1)
|
| 152 |
+
self.norm = nn.GroupNorm(8, b)
|
| 153 |
+
self.condition = nn.Linear(128, b * 2)
|
| 154 |
+
self.out = nn.Conv2d(b, b, 3, padding=1)
|
| 155 |
+
self.skip = nn.Conv2d(a, b, 1) if a != b else nn.Identity()
|
| 156 |
+
|
| 157 |
+
def forward(self, x, c):
|
| 158 |
+
scale, bias = self.condition(c)[:, :, None, None].chunk(2, 1)
|
| 159 |
+
h = self.norm(self.conv(x)) * (1 + scale) + bias
|
| 160 |
+
return self.skip(x) + self.out(F.silu(h))
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def block_parameters():
|
| 164 |
+
with torch.device("meta"):
|
| 165 |
+
block = Block(128, 128)
|
| 166 |
+
return sum(p.numel() for p in block.parameters())
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class Model(nn.Module):
|
| 170 |
+
def __init__(self, n, blocks=0):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.emb = nn.Embedding(n, 128, padding_idx=0)
|
| 173 |
+
self.time = nn.Sequential(nn.Linear(32, 128), nn.SiLU(), nn.Linear(128, 128))
|
| 174 |
+
self.register_buffer("freq", torch.exp(torch.linspace(0, math.log(1000), 16)))
|
| 175 |
+
self.a = Block(3, 32)
|
| 176 |
+
self.b = Block(32, 64)
|
| 177 |
+
self.c = Block(64, 128)
|
| 178 |
+
self.d = Block(128, 128)
|
| 179 |
+
self.e = Block(192, 64)
|
| 180 |
+
self.f = Block(96, 32)
|
| 181 |
+
self.out = nn.Conv2d(32, 3, 3, padding=1)
|
| 182 |
+
self.extra = nn.ModuleList()
|
| 183 |
+
self.add_blocks(blocks)
|
| 184 |
+
|
| 185 |
+
def add_blocks(self, count):
|
| 186 |
+
for _ in range(count):
|
| 187 |
+
block = Block(128, 128)
|
| 188 |
+
nn.init.zeros_(block.out.weight)
|
| 189 |
+
nn.init.zeros_(block.out.bias)
|
| 190 |
+
self.extra.append(block)
|
| 191 |
+
|
| 192 |
+
def forward(self, x, t, ids):
|
| 193 |
+
phase = t[:, None] * self.freq
|
| 194 |
+
cond = self.time(torch.cat([phase.sin(), phase.cos()], 1))
|
| 195 |
+
cond = cond + self.emb(ids).sum(1) / ids.ne(0).sum(1, keepdim=True).clamp_min(1).sqrt()
|
| 196 |
+
a = self.a(x, cond)
|
| 197 |
+
b = self.b(F.avg_pool2d(a, 2), cond)
|
| 198 |
+
c = self.c(F.avg_pool2d(b, 2), cond)
|
| 199 |
+
h = self.d(F.avg_pool2d(c, 2), cond)
|
| 200 |
+
for block in self.extra:
|
| 201 |
+
h = block(h, cond)
|
| 202 |
+
h = F.interpolate(h, scale_factor=2) + c
|
| 203 |
+
h = self.e(torch.cat([F.interpolate(h, scale_factor=2), b], 1), cond)
|
| 204 |
+
return self.out(self.f(torch.cat([F.interpolate(h, scale_factor=2), a], 1), cond))
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def encode(captions, vocab):
|
| 208 |
+
rows = []
|
| 209 |
+
for s in captions:
|
| 210 |
+
ids = [vocab.get(w, 1) for w in words(s)]
|
| 211 |
+
rows.append(ids + [0] * (32 - len(ids)))
|
| 212 |
+
return torch.tensor(rows, device=DEVICE)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def training_vocab(groups, saved):
|
| 216 |
+
counts = Counter(w for group in groups.values() for _, s in group for w in words(s))
|
| 217 |
+
if saved is None:
|
| 218 |
+
return {w: i+2 for i, (w, _) in enumerate(counts.most_common(16000))}
|
| 219 |
+
vocab = dict(saved["vocab"])
|
| 220 |
+
for word in counts:
|
| 221 |
+
if word not in vocab:
|
| 222 |
+
vocab[word] = len(vocab) + 2
|
| 223 |
+
return vocab
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def analyze_size(root, checkpoint, report, stop, folder_captions=False):
|
| 227 |
+
groups = index(root, report, stop, folder_captions)
|
| 228 |
+
if stop.is_set():
|
| 229 |
+
return None
|
| 230 |
+
if not groups:
|
| 231 |
+
raise ValueError("No labeled images found")
|
| 232 |
+
saved = torch.load(checkpoint, map_location="cpu", weights_only=True) if checkpoint else None
|
| 233 |
+
existing = saved.get("blocks", 0) if saved else 0
|
| 234 |
+
vocab = training_vocab(groups, saved)
|
| 235 |
+
# Meta tensors let us count the actual architecture without allocating weights.
|
| 236 |
+
with torch.device("meta"):
|
| 237 |
+
model = Model(len(vocab) + 2, existing)
|
| 238 |
+
base_count = sum(p.numel() for p in model.parameters())
|
| 239 |
+
per_block = block_parameters()
|
| 240 |
+
images = sum(map(len, groups.values()))
|
| 241 |
+
# Conservative starting tiers for experimentation, measured in total extra blocks.
|
| 242 |
+
suggested = sum(images >= threshold for threshold in (1000, 4000, 10000, 25000))
|
| 243 |
+
return images, base_count, per_block, max(0, suggested - existing)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
ASPECT_RATIOS = {"1:1": (1, 1), "3:4": (3, 4), "4:3": (4, 3),
|
| 247 |
+
"1:2": (1, 2), "2:1": (2, 1)}
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def canvas_size(resolution, ratio):
|
| 251 |
+
w, h = ASPECT_RATIOS[ratio]
|
| 252 |
+
return resolution * w // max(w, h), resolution * h // max(w, h)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def prepare_image(image, canvas, framing):
|
| 256 |
+
rgb = ImageOps.exif_transpose(image).convert("RGB")
|
| 257 |
+
if framing == "Fit with padding":
|
| 258 |
+
return ImageOps.pad(rgb, canvas, method=Image.Resampling.BICUBIC, color="black")
|
| 259 |
+
return ImageOps.fit(rgb, canvas, method=Image.Resampling.BICUBIC)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def train(root, target, steps, stop, report, *, source=None, resolution=None, lr=None,
|
| 263 |
+
batch_size=16, folder_captions=False, progress=None, preview=None,
|
| 264 |
+
preview_interval=100, preview_count=1, preview_prompt="", add_blocks=0, aspect_ratio=None, framing=None):
|
| 265 |
+
if type(add_blocks) is not int or not 0 <= add_blocks <= MAX_ADDED_BLOCKS:
|
| 266 |
+
raise ValueError(f"Choose between 0 and {MAX_ADDED_BLOCKS} additional blocks.")
|
| 267 |
+
if add_blocks and target.exists() and source is None:
|
| 268 |
+
raise ValueError("To expand an existing model, choose it under Fine-tune from and enter a new output filename.")
|
| 269 |
+
if type(batch_size) is not int or batch_size < 1:
|
| 270 |
+
raise ValueError("Batch size must be a positive integer.")
|
| 271 |
+
if preview and (preview_interval < 1 or not 1 <= preview_count <= 4):
|
| 272 |
+
raise ValueError("Choose a positive preview interval and 1 to 4 images.")
|
| 273 |
+
if source is not None and target.exists():
|
| 274 |
+
raise ValueError("Fine-tuning needs a new output filename. To resume, clear the base checkpoint field.")
|
| 275 |
+
if source is not None and not source.is_file():
|
| 276 |
+
raise ValueError("Base checkpoint does not exist.")
|
| 277 |
+
checkpoint = source or target
|
| 278 |
+
saved = torch.load(checkpoint, map_location="cpu", weights_only=True) if checkpoint.exists() else None
|
| 279 |
+
previous_size = saved.get("resolution", 64) if saved else 64
|
| 280 |
+
resolution = previous_size if resolution is None else resolution
|
| 281 |
+
if resolution not in (64, 96, 128):
|
| 282 |
+
raise ValueError("Choose 64, 96, or 128 pixels.")
|
| 283 |
+
if saved and source is None and previous_size != resolution:
|
| 284 |
+
raise ValueError("To change resolution, select a base checkpoint and a new output file.")
|
| 285 |
+
previous_ratio = saved.get("aspect_ratio", "1:1") if saved else "1:1"
|
| 286 |
+
aspect_ratio = aspect_ratio or previous_ratio
|
| 287 |
+
framing = framing or (saved.get("framing", "Center crop") if saved else "Center crop")
|
| 288 |
+
if aspect_ratio not in ASPECT_RATIOS or framing not in ("Center crop", "Fit with padding"):
|
| 289 |
+
raise ValueError("Choose a supported aspect ratio and image framing.")
|
| 290 |
+
if saved and source is None and aspect_ratio != previous_ratio:
|
| 291 |
+
raise ValueError("To change aspect ratio, select a base checkpoint and a new output file.")
|
| 292 |
+
canvas = canvas_size(resolution, aspect_ratio)
|
| 293 |
+
if lr is not None and not 0 < lr <= 1:
|
| 294 |
+
raise ValueError("Enter a positive learning rate up to 1.")
|
| 295 |
+
|
| 296 |
+
groups = index(root, report, stop, folder_captions)
|
| 297 |
+
if stop.is_set():
|
| 298 |
+
return
|
| 299 |
+
if not groups:
|
| 300 |
+
raise ValueError("No labeled images found")
|
| 301 |
+
vocab = training_vocab(groups, saved)
|
| 302 |
+
if preview:
|
| 303 |
+
if preview_prompt and not any(w in vocab for w in words(preview_prompt)):
|
| 304 |
+
raise ValueError("The preview prompt has no words in this model’s vocabulary. Change it or leave it blank for dataset captions.")
|
| 305 |
+
preview_rng = random.Random()
|
| 306 |
+
caption_pool = [] if preview_prompt else list(dict.fromkeys(
|
| 307 |
+
s for group in groups.values() for _, s in group if any(w in vocab for w in words(s))))
|
| 308 |
+
deck = []
|
| 309 |
+
model = Model(len(vocab)+2, saved.get("blocks", 0) if saved else 0)
|
| 310 |
+
step = 0
|
| 311 |
+
if saved:
|
| 312 |
+
old_embedding = saved["model"]["emb.weight"]
|
| 313 |
+
expanded = old_embedding.shape != model.emb.weight.shape
|
| 314 |
+
if expanded:
|
| 315 |
+
weights = model.emb.weight.detach().cpu().clone()
|
| 316 |
+
weights[:len(old_embedding)] = old_embedding
|
| 317 |
+
saved["model"]["emb.weight"] = weights
|
| 318 |
+
model.load_state_dict(saved["model"])
|
| 319 |
+
step = saved["step"]
|
| 320 |
+
model.add_blocks(add_blocks)
|
| 321 |
+
model.to(DEVICE)
|
| 322 |
+
opt = torch.optim.AdamW(model.parameters(), lr=0.0003)
|
| 323 |
+
if saved:
|
| 324 |
+
if source is None:
|
| 325 |
+
opt.load_state_dict(saved["optimizer"])
|
| 326 |
+
if expanded:
|
| 327 |
+
state = opt.state[model.emb.weight]
|
| 328 |
+
for key, value in list(state.items()):
|
| 329 |
+
if isinstance(value, torch.Tensor) and value.shape == old_embedding.shape:
|
| 330 |
+
padded = torch.zeros_like(model.emb.weight)
|
| 331 |
+
padded[:len(value)] = value
|
| 332 |
+
state[key] = padded
|
| 333 |
+
if lr is not None:
|
| 334 |
+
for group in opt.param_groups:
|
| 335 |
+
group["lr"] = lr
|
| 336 |
+
parameters = sum(p.numel() for p in model.parameters())
|
| 337 |
+
report(f"Starting at step {step} on {DEVICE}, {resolution} px, batch {batch_size}, {parameters:,} parameters")
|
| 338 |
+
pools = list(groups.values())
|
| 339 |
+
weights = [math.sqrt(len(pool)) for pool in pools]
|
| 340 |
+
start = step
|
| 341 |
+
started = time.monotonic()
|
| 342 |
+
last_update = started
|
| 343 |
+
last_saved = start
|
| 344 |
+
while step < start + steps and not stop.is_set():
|
| 345 |
+
images, captions = [], []
|
| 346 |
+
for pool in random.choices(pools, weights, k=batch_size):
|
| 347 |
+
path, caption = random.choice(pool)
|
| 348 |
+
try:
|
| 349 |
+
with Image.open(path) as im:
|
| 350 |
+
rgb = prepare_image(im, canvas, framing)
|
| 351 |
+
images.append(np.asarray(rgb))
|
| 352 |
+
captions.append(caption)
|
| 353 |
+
except (OSError, ValueError, Image.DecompressionBombError):
|
| 354 |
+
continue
|
| 355 |
+
if not images:
|
| 356 |
+
raise ValueError("Could not decode any images in this batch")
|
| 357 |
+
x = torch.from_numpy(np.stack(images)).to(DEVICE).permute(0,3,1,2).float()/127.5-1
|
| 358 |
+
noise = torch.randn_like(x)
|
| 359 |
+
t = torch.rand(len(x), device=DEVICE)
|
| 360 |
+
pred = model(torch.lerp(noise, x, t[:,None,None,None]), t, encode(captions, vocab))
|
| 361 |
+
loss = F.mse_loss(pred, x-noise)
|
| 362 |
+
opt.zero_grad()
|
| 363 |
+
loss.backward()
|
| 364 |
+
nn.utils.clip_grad_norm_(model.parameters(), 1)
|
| 365 |
+
opt.step()
|
| 366 |
+
step += 1
|
| 367 |
+
completed = step - start
|
| 368 |
+
if progress and (completed == 1 or completed == steps or time.monotonic() - last_update >= 0.4):
|
| 369 |
+
current_loss = loss.item()
|
| 370 |
+
last_update = time.monotonic()
|
| 371 |
+
progress(completed, steps, step, current_loss, last_update - started)
|
| 372 |
+
elif not progress and (completed == 1 or step % 25 == 0):
|
| 373 |
+
report(f"Step {step} loss {loss.item():.4f}")
|
| 374 |
+
if step % 250 == 0 or step == start+steps or stop.is_set():
|
| 375 |
+
report(f"Saving checkpoint at step {step:,}…")
|
| 376 |
+
save_model(target, model, opt, vocab, step, resolution, aspect_ratio, framing)
|
| 377 |
+
last_saved = step
|
| 378 |
+
report(f"Saved step {step}")
|
| 379 |
+
if preview and completed % preview_interval == 0 and not stop.is_set():
|
| 380 |
+
report(f"Generating previews for step {step:,}…")
|
| 381 |
+
model.eval()
|
| 382 |
+
samples = []
|
| 383 |
+
try:
|
| 384 |
+
for slot in range(preview_count):
|
| 385 |
+
caption = preview_prompt
|
| 386 |
+
if not caption:
|
| 387 |
+
if not deck:
|
| 388 |
+
deck = caption_pool.copy()
|
| 389 |
+
preview_rng.shuffle(deck)
|
| 390 |
+
caption = deck.pop()
|
| 391 |
+
seed = slot + 1
|
| 392 |
+
image = sample(model, vocab, canvas, caption, seed, stop=stop)
|
| 393 |
+
if image is None:
|
| 394 |
+
break
|
| 395 |
+
samples.append((caption, seed, image))
|
| 396 |
+
if samples:
|
| 397 |
+
preview(step, samples)
|
| 398 |
+
finally:
|
| 399 |
+
model.train()
|
| 400 |
+
if progress:
|
| 401 |
+
last_update = time.monotonic()
|
| 402 |
+
progress(completed, steps, step, loss.item(), last_update - started)
|
| 403 |
+
if stop.is_set() and step > last_saved:
|
| 404 |
+
save_model(target, model, opt, vocab, step, resolution, aspect_ratio, framing)
|
| 405 |
+
if progress and stop.is_set() and step > start and completed != steps:
|
| 406 |
+
progress(completed, steps, step, loss.item(), time.monotonic() - started)
|
| 407 |
+
return step - start
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def save_model(path, model, opt, vocab, step, resolution, aspect_ratio="1:1", framing="Center crop"):
|
| 411 |
+
temp = path.with_suffix(".partial")
|
| 412 |
+
torch.save(dict(model=model.state_dict(), optimizer=opt.state_dict(), vocab=vocab, step=step,
|
| 413 |
+
resolution=resolution, aspect_ratio=aspect_ratio, framing=framing, blocks=len(model.extra)), temp)
|
| 414 |
+
os.replace(temp, path)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
@torch.inference_mode()
|
| 418 |
+
def load_generator(path):
|
| 419 |
+
saved = torch.load(path, map_location="cpu", weights_only=True)
|
| 420 |
+
model = Model(len(saved["vocab"])+2, saved.get("blocks", 0)).to(DEVICE).eval()
|
| 421 |
+
model.load_state_dict(saved["model"])
|
| 422 |
+
resolution = saved.get("resolution", 64)
|
| 423 |
+
ratio = saved.get("aspect_ratio", "1:1")
|
| 424 |
+
return model, saved["vocab"], resolution if ratio == "1:1" else canvas_size(resolution, ratio)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def generate(path, prompt, seed, *, progress=None):
|
| 428 |
+
return sample(*load_generator(path), prompt, seed, progress=progress)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
@torch.inference_mode()
|
| 432 |
+
def sample(model, vocab, size, prompt, seed, *, progress=None, stop=None):
|
| 433 |
+
ids = encode([prompt], vocab)
|
| 434 |
+
if not any(w in vocab for w in words(prompt)):
|
| 435 |
+
raise ValueError("This checkpoint has none of the words in your prompt. Train with image captions and select the updated checkpoint.")
|
| 436 |
+
rng = torch.Generator(device=DEVICE).manual_seed(seed)
|
| 437 |
+
width, height = (size, size) if isinstance(size, int) else size
|
| 438 |
+
x = torch.randn((1,3,height,width), generator=rng, device=DEVICE)
|
| 439 |
+
for i in range(40):
|
| 440 |
+
if stop is not None and stop.is_set():
|
| 441 |
+
return None
|
| 442 |
+
x += model(x, torch.tensor([i/40], device=DEVICE), ids)/40
|
| 443 |
+
if progress and (i + 1) % 4 == 0:
|
| 444 |
+
if DEVICE == "cuda":
|
| 445 |
+
torch.cuda.synchronize()
|
| 446 |
+
progress(i + 1, 40)
|
| 447 |
+
return Image.fromarray(((x[0].clamp(-1,1)+1)*127.5).byte().permute(1,2,0).cpu().numpy())
|
| 448 |
+
|