thalismind
Claude Opus 5.5
feat: add train_lora.py, a shareable LoRA trainer, with a README guide and a retrained ghost test sheet
86f928f Download train_lora.py from ThalisAI/solstice-80m: direct link, hf CLI and curl.
- Browser
- Download file 21.1 kB
-
https://huggingface.co/ThalisAI/solstice-80m/resolve/main/train_lora.py
- Command line
-
hf download hf://ThalisAI/solstice-80m/train_lora.py
-
curl -L -o train_lora.py https://huggingface.co/ThalisAI/solstice-80m/resolve/main/train_lora.py
21.1 kB
| """Train a LoRA for the Solstice r80-1202 teacher, and draw comparison sheets. | |
| A LoRA adds small low-rank adapters to the teacher's linear layers and trains only those; the teacher and the | |
| text encoder stay frozen. A fresh LoRA changes nothing (its B matrices start at zero), and a trained one is a | |
| ~12 MB file that generate.py merges into the teacher with --lora. | |
| # 1. a folder of 32x32 RGBA PNGs and their captions (captions.jsonl, or one .txt per image) | |
| python train_lora.py train --data my-sprites --trigger "my style" --out runs/my-style | |
| # 2. compare: rows = prompts, columns = base / LoRA at each strength | |
| python train_lora.py sheet --lora runs/my-style/lora.safetensors --prompts prompts.txt --out sheet.png | |
| # 3. use it | |
| python generate.py pytorch/r80-1202/teacher.safetensors --lora runs/my-style/lora.safetensors \\ | |
| --prompt "my style, red apple" --output apple.png | |
| Captions describe what is drawn ("red apple with a green leaf, front view"); the trigger is put in front of each | |
| one during training, and the template adds "pixel art, 32px, ". Sprites are also trained mirrored, with | |
| left/right swapped in their captions, unless the caption mentions writing (letters, digits, text). | |
| Prior preservation (on by default): half of every batch is ordinary sprites with their own captions and no | |
| trigger, so prompts without the trigger stay as they were. With --prior-prompts (default: prior_prompts.txt next | |
| to this file) the teacher first draws those sprites itself, once, into <out>/prior/; --prior-dir uses a folder of | |
| your own sprites instead (same layout as --data). --prior-frac 0 turns it off. | |
| Dependencies: torch transformers safetensors numpy pillow (the same as generate.py). Tested on an RTX A6000: | |
| drawing the 400 prior sprites takes about 2 minutes the first time, and 2,000 steps at batch 16 about 9 minutes. | |
| """ | |
| import argparse | |
| import json | |
| import math | |
| import re | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from PIL import Image | |
| import generate as G | |
| ROOT = Path(__file__).resolve().parent | |
| TEACHER = ROOT / "pytorch/r80-1202/teacher.safetensors" | |
| PRIOR_PROMPTS = ROOT / "prior_prompts.txt" | |
| # Which linear layers get adapters. The released LoRAs use all blocks and attn+mlp. | |
| BLOCKS = { | |
| "all": ("outer_encoder", "bottleneck", "outer_decoder"), | |
| "outer": ("outer_encoder", "outer_decoder"), # 16x16 tokens: outlines, shading, palette, texture | |
| "core": ("bottleneck",), # 8x8 tokens: shape, proportions, subject | |
| } | |
| LAYERS = { | |
| "attn+mlp": ("self_attn.qkv", "self_attn.proj", "cross_attn.q", "cross_attn.k", "cross_attn.v", | |
| "cross_attn.proj", "mlp.w12", "mlp.w3"), | |
| "cross": ("cross_attn.q", "cross_attn.k", "cross_attn.v", "cross_attn.proj"), | |
| } | |
| # Mirrored training: side words swap; sprites with drawn writing are never mirrored. | |
| _SIDE = {"left": "right", "right": "left", "leftward": "rightward", "rightward": "leftward", | |
| "leftwards": "rightwards", "rightwards": "leftwards", "clockwise": "anticlockwise", | |
| "anticlockwise": "clockwise", "counterclockwise": "clockwise", "counter-clockwise": "clockwise"} | |
| _SIDE_RE = re.compile(r"\b(" + "|".join(sorted(map(re.escape, _SIDE), key=len, reverse=True)) + r")\b", re.I) | |
| _NO_FLIP = re.compile(r"\b(letter|letters|digit|digits|number \d|numeral|text|word|words|written|reading|" | |
| r"lettering|alphabet|initials?|monogram|label(?:led)? with|[a-z]-shaped)\b", re.I) | |
| def mirror_text(s): | |
| def swap(m): | |
| w = _SIDE[m.group(0).lower()] | |
| return w.capitalize() if m.group(0)[0].isupper() else w | |
| return _SIDE_RE.sub(swap, s) | |
| # --- adapters --------------------------------------------------------------------------------------- | |
| class LoRALinear(nn.Module): | |
| """y = W x + (alpha / rank) * B (A x); B starts at zero, so a fresh adapter is the base layer.""" | |
| def __init__(self, base, rank, alpha): | |
| super().__init__() | |
| self.base, self.scale = base, alpha / rank | |
| self.A = nn.Parameter(torch.randn(rank, base.in_features) / math.sqrt(base.in_features)) | |
| self.B = nn.Parameter(torch.zeros(base.out_features, rank)) | |
| def forward(self, x): | |
| return self.base(x) + F.linear(F.linear(x, self.A.to(x.dtype)), self.B.to(x.dtype)) * self.scale | |
| def add_adapters(model, rank, alpha, blocks, layers): | |
| stacks, names = BLOCKS[blocks], LAYERS[layers] | |
| targets = [n for n, m in model.named_modules() if isinstance(m, nn.Linear) and n.split(".")[0] in stacks | |
| and any(n.endswith("." + k) for k in names)] | |
| for n in targets: | |
| parent, child = n.rsplit(".", 1) | |
| p = model.get_submodule(parent) | |
| setattr(p, child, LoRALinear(getattr(p, child), rank, alpha)) | |
| return {n: model.get_submodule(n) for n in targets} | |
| def save_lora(adapters, path, meta): | |
| from safetensors.torch import save_file | |
| state = {f"{n}.{k}": getattr(m, k).detach().float().cpu().contiguous() for n, m in adapters.items() for k in "AB"} | |
| save_file(state, str(path), metadata={k: str(v) for k, v in meta.items()}) | |
| # --- data ------------------------------------------------------------------------------------------- | |
| def read_folder(folder): | |
| """32x32 PNGs with captions from captions.jsonl ({"file", "caption"} per line) or <name>.txt sidecars.""" | |
| folder = Path(folder) | |
| caps = {} | |
| if (folder / "captions.jsonl").exists(): | |
| for line in open(folder / "captions.jsonl"): | |
| if line.strip(): | |
| r = json.loads(line) | |
| caps[r["file"]] = r["caption"].strip() | |
| images, texts = [], [] | |
| for p in sorted(folder.glob("*.png")): | |
| text = caps.get(p.name) | |
| if text is None and p.with_suffix(".txt").exists(): | |
| text = p.with_suffix(".txt").read_text().strip() | |
| if not text: | |
| raise SystemExit(f"{p}: no caption (add it to captions.jsonl or {p.with_suffix('.txt').name})") | |
| im = Image.open(p).convert("RGBA") | |
| if im.size != (32, 32): | |
| raise SystemExit(f"{p}: {im.size[0]}x{im.size[1]}; Solstice sprites are 32x32 (draw or pick native " | |
| "32 px art; downscaled images teach blurry pixels)") | |
| images.append(np.asarray(im)) | |
| texts.append(text) | |
| if not images: | |
| raise SystemExit(f"{folder}: no .png files") | |
| return np.stack(images), texts | |
| def to_x0(rgba_u8, device): | |
| """RGBA uint8 -> the model's 4 channels: RGB in [-1, 1] (0 under transparency), alpha -1 / +1.""" | |
| a = torch.from_numpy(rgba_u8).to(device).float() | |
| opaque = (a[..., 3:4] > 127).float() | |
| rgb = (a[..., :3] / 127.5 - 1) * opaque | |
| return torch.cat([rgb, opaque * 2 - 1], -1).permute(0, 3, 1, 2).contiguous() | |
| def loss_weights(x0): | |
| """The base model's loss weighting: RGB 0.15 background / 1 sprite / +0.5 on the outline ring; alpha 1 + ring.""" | |
| fg = (x0[:, 3:4] > 0).float() | |
| p = F.pad(fg, (1, 1, 1, 1)) | |
| edge = (F.max_pool2d(p, 3, 1) + F.max_pool2d(-p, 3, 1)).clamp(0, 1) | |
| rgb = 0.15 * (1 - fg) + fg + 0.5 * edge | |
| return torch.cat([rgb.expand(-1, 3, -1, -1), 1 + edge], 1) | |
| class Texts: | |
| """Every caption encoded once with the frozen T5Gemma encoder, then the encoder is freed.""" | |
| def __init__(self, captions, device): | |
| self.strings = [""] + sorted(set(captions) - {""}) | |
| self.where = {s: i for i, s in enumerate(self.strings)} | |
| enc = G.TextEncoder(G.TEXT_ENCODER, device) | |
| toks, masks = [], [] | |
| with torch.inference_mode(): | |
| for i in range(0, len(self.strings), 64): | |
| batch = enc.tokenizer(self.strings[i:i + 64], padding="max_length", max_length=64, truncation=True, | |
| return_tensors="pt").to(device) | |
| mask = batch.attention_mask.bool() | |
| hidden = enc.encoder(**batch).last_hidden_state.float() | |
| toks.append(torch.where(mask[..., None], hidden, 0.0).half().cpu()) | |
| masks.append(mask.cpu()) | |
| self.tok, self.mask = torch.cat(toks), torch.cat(masks) | |
| self.pool = self.tok.float().sum(1) / self.mask.sum(1).clamp(min=1)[:, None] | |
| self.device = device | |
| del enc | |
| if device.type == "cuda": | |
| torch.cuda.empty_cache() | |
| def ids(self, strings): | |
| return torch.tensor([self.where[s] for s in strings]) | |
| def get(self, ids): | |
| return (self.tok[ids].to(self.device).float(), self.mask[ids].to(self.device), | |
| self.pool[ids].to(self.device).float()) | |
| def template(text): | |
| return G.CONFIG["text_encoder"]["prompt_template"].replace("<caption>", text) | |
| def with_trigger(trigger, text): | |
| return ", ".join(s for s in (trigger, text) if s) | |
| def sample_batch(model, text, ids, seeds, device, cfg=4.0): | |
| """generate.sample for a batch: the teacher's Heun steps, CFG on t <= 0.75, self-conditioning; one noise seed | |
| per sprite (the same noise generate.py draws for that seed on this device).""" | |
| steps, sampler = G.teacher_sampling(G.CONFIG) | |
| cond = text.get(ids) | |
| uncond = text.get(torch.zeros_like(ids)) | |
| x = torch.cat([torch.randn((1, 4, 32, 32), generator=torch.Generator(device=device).manual_seed(s), device=device) | |
| for s in seeds]) | |
| state = {"sc": torch.zeros_like(x)} | |
| autocast = dict(device_type="cuda", dtype=torch.bfloat16, enabled=device.type == "cuda") | |
| def velocity(x, t): | |
| tt = torch.full((len(x),), t, device=device) | |
| with torch.autocast(**autocast): | |
| if t > 0.75 + 1e-5: | |
| v = model(x, tt, cond[2], cond[0], cond[1], sc=state["sc"]).float() | |
| else: | |
| both = model(torch.cat([x, x]), torch.cat([tt, tt]), torch.cat([cond[2], uncond[2]]), | |
| torch.cat([cond[0], uncond[0]]), torch.cat([cond[1], uncond[1]]), | |
| sc=torch.cat([state["sc"], state["sc"]])).float() | |
| c, u = both.chunk(2) | |
| v = u + cfg * (c - u) | |
| state["sc"] = (x - t * v).clamp(-1, 1) | |
| return v | |
| ts = torch.linspace(1, 0, steps + 1).tolist() | |
| for i, (t0, t1) in enumerate(zip(ts, ts[1:])): | |
| v = velocity(x, t0) | |
| if sampler == "heun" and i < steps - 1: | |
| v = 0.5 * (v + velocity(x + (t1 - t0) * v, t1)) | |
| x = x + (t1 - t0) * v | |
| return x | |
| def to_images(x): | |
| return [G.to_image(x[i:i + 1]) for i in range(len(x))] | |
| def draw_prior(prompts, out, device, seed=0, batch=50): | |
| """The teacher's own sprites for the prior prompts (one each), cached in out/prior/.""" | |
| out.mkdir(parents=True, exist_ok=True) | |
| todo = [(i, p) for i, p in enumerate(prompts) if not (out / f"{i:05d}.png").exists()] | |
| if todo: | |
| print(f"drawing {len(todo)} prior sprites with the teacher (cached in {out})", flush=True) | |
| text = Texts([template(p) for _, p in todo], device) | |
| model = load_teacher(device) | |
| for k in range(0, len(todo), batch): | |
| part = todo[k:k + batch] | |
| ids = text.ids([template(p) for _, p in part]) | |
| x = sample_batch(model, text, ids, [seed + i for i, _ in part], device) | |
| for (i, p), im in zip(part, to_images(x)): | |
| im.save(out / f"{i:05d}.png") | |
| (out / f"{i:05d}.txt").write_text(p) | |
| print(f" {min(k + batch, len(todo))}/{len(todo)}", flush=True) | |
| del model, text | |
| if device.type == "cuda": | |
| torch.cuda.empty_cache() | |
| return read_folder(out) | |
| def load_teacher(device, lora=None, strength=1.0): | |
| from safetensors.torch import load_file | |
| from model import SolsticeGenerator | |
| model = SolsticeGenerator(**G.CONFIG["constructor"]) | |
| model.load_state_dict(load_file(TEACHER), strict=True) | |
| if lora: | |
| G.merge_lora(model, lora, strength) # merged on the CPU, before the move | |
| return model.to(device).eval().requires_grad_(False) | |
| # --- train ------------------------------------------------------------------------------------------ | |
| def train(a): | |
| device = G.resolve_device(a.device) | |
| torch.manual_seed(a.seed) | |
| out = Path(a.out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| images, texts = read_folder(a.data) | |
| n_set = len(texts) | |
| flip_ok = [a.flip and not _NO_FLIP.search(t) for t in texts] | |
| caps = [template(with_trigger(a.trigger, t)) for t in texts] | |
| caps_m = [template(with_trigger(a.trigger, mirror_text(t))) for t in texts] | |
| print(f"{n_set} sprites from {a.data}; first caption: {caps[0]!r}", flush=True) | |
| if a.prior_frac > 0: | |
| if a.prior_dir: | |
| p_images, p_texts = read_folder(a.prior_dir) | |
| else: | |
| prompts = [l.strip() for l in open(a.prior_prompts) if l.strip() and not l.startswith("#")] | |
| p_images, p_texts = draw_prior(prompts[:a.prior_n], out / "prior", device, a.seed) | |
| images = np.concatenate([images, p_images]) | |
| caps += [template(t) for t in p_texts] | |
| caps_m += [template(mirror_text(t)) for t in p_texts] | |
| flip_ok += [a.flip and not _NO_FLIP.search(t) for t in p_texts] | |
| print(f"prior preservation: {len(p_texts)} sprites without the trigger, {a.prior_frac:.0%} of each batch", | |
| flush=True) | |
| else: | |
| print("prior preservation off: prompts without the trigger may change too", flush=True) | |
| text = Texts(caps + caps_m, device) | |
| sid, sid_m = text.ids(caps), text.ids(caps_m) | |
| flip_ok = torch.tensor(flip_ok) | |
| x0_all = to_x0(images, device) | |
| model = load_teacher(device) | |
| adapters = add_adapters(model, a.rank, a.alpha or a.rank, a.blocks, a.layers) | |
| model.to(device) | |
| params = [p for m in adapters.values() for p in (m.A, m.B)] | |
| for p in params: | |
| p.requires_grad_(True) | |
| opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=0.0, betas=(0.9, 0.99)) | |
| meta = {"base": "r80-1202 teacher", "rank": a.rank, "alpha": a.alpha or a.rank, "blocks": a.blocks, | |
| "layers": a.layers, "trigger": a.trigger, "train_sprites": n_set, "train_steps": a.steps, | |
| "prior_preservation": a.prior_frac > 0, "format": "<module>.A [rank, in], <module>.B [out, rank]; " | |
| "W += strength * alpha / rank * B @ A"} | |
| n_params = sum(p.numel() for p in params) | |
| print(f"{len(adapters)} adapted layers, {n_params / 1e6:.2f}M trainable parameters", flush=True) | |
| g = torch.Generator().manual_seed(a.seed) | |
| autocast = dict(device_type="cuda", dtype=torch.bfloat16, enabled=device.type == "cuda") | |
| t0, run = time.time(), 0.0 | |
| log = open(out / "log.jsonl", "w") | |
| for step in range(1, a.steps + 1): | |
| for gr in opt.param_groups: | |
| gr["lr"] = a.lr * min(1.0, step / a.warmup) | |
| pick = torch.randint(n_set, (a.batch,), generator=g) | |
| if a.prior_frac > 0: | |
| k = int(round(a.batch * a.prior_frac)) | |
| pick[:k] = n_set + torch.randint(len(images) - n_set, (k,), generator=g) | |
| flip = flip_ok[pick] & (torch.rand(a.batch, generator=g) < 0.5) | |
| ids = torch.where(flip, sid_m[pick], sid[pick]) | |
| ids = torch.where(torch.rand(a.batch, generator=g) < 0.1, torch.zeros_like(ids), ids) # keeps CFG working | |
| x0 = x0_all[pick.to(device)] | |
| x0 = torch.where(flip.to(device)[:, None, None, None], x0.flip(-1), x0) | |
| tok, mask, pool = text.get(ids) | |
| # rectified flow, as the teacher was trained: x_t = (1 - t) x0 + t eps, target velocity eps - x0 | |
| t = torch.sigmoid(torch.randn(a.batch, device=device)).clamp(1e-4, 1 - 1e-4) | |
| eps = torch.randn_like(x0) | |
| tt = t[:, None, None, None] | |
| xt = (1 - tt) * x0 + tt * eps | |
| with torch.no_grad(), torch.autocast(**autocast): # self-conditioning on half the batch | |
| v0 = model(xt, t, pool, tok, mask, sc=torch.zeros_like(xt)) | |
| est = (xt - tt * v0.float()).clamp(-1, 1) | |
| sc = torch.where((torch.rand(a.batch, device=device) < 0.5)[:, None, None, None], est, torch.zeros_like(est)) | |
| with torch.autocast(**autocast): | |
| v = model(xt, t, pool, tok, mask, sc=sc) | |
| loss = (loss_weights(x0) * (v.float() - (eps - x0)) ** 2).mean() | |
| opt.zero_grad(set_to_none=True) | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(params, 1.0) | |
| opt.step() | |
| run += loss.item() | |
| if step % 50 == 0: | |
| rec = {"step": step, "loss": round(run / 50, 5), "minutes": round((time.time() - t0) / 60, 2)} | |
| log.write(json.dumps(rec) + "\n"); log.flush() | |
| run = 0.0 | |
| if step % 250 == 0: | |
| print(rec, flush=True) | |
| if step in a.save: | |
| save_lora(adapters, out / f"lora_{step:06d}.safetensors", {**meta, "train_steps": step}) | |
| save_lora(adapters, out / "lora.safetensors", meta) | |
| print(f"saved {out / 'lora.safetensors'} after {(time.time() - t0) / 60:.1f} min", flush=True) | |
| # --- sheet ------------------------------------------------------------------------------------------ | |
| def sheet(a): | |
| """Rows: base, then the LoRA at each strength. Columns: each prompt at each seed. Teacher sampling.""" | |
| from PIL import ImageDraw, ImageFont | |
| import textwrap | |
| device = G.resolve_device(a.device) | |
| prompts = [l.strip() for l in open(a.prompts) if l.strip() and not l.startswith("#")] | |
| text = Texts([template(p) for p in prompts], device) | |
| ids = text.ids([template(p) for p in prompts for _ in range(a.seeds)]) | |
| seeds = [s for _ in prompts for s in range(a.seeds)] | |
| rows = [("base", 0.0)] + [(f"strength {s:g}", s) for s in a.strengths] | |
| cells = [] | |
| for label, s in rows: | |
| model = load_teacher(device, a.lora if s else None, s) | |
| cells.append(to_images(sample_batch(model, text, ids, seeds, device))) | |
| del model | |
| z, gap, lw, head = 3, 4, 110, 64 | |
| cw = 32 * z + gap | |
| W, H = lw + len(cells[0]) * cw + 10, head + len(rows) * cw + 6 | |
| im = Image.new("RGB", (W, H), (58, 58, 68)) | |
| d = ImageDraw.Draw(im) | |
| try: | |
| font = ImageFont.truetype("DejaVuSans.ttf", 12) | |
| except OSError: | |
| font = ImageFont.load_default() | |
| for i, p in enumerate(prompts): | |
| d.multiline_text((lw + i * a.seeds * cw, 6), "\n".join(textwrap.wrap(p, 15 * a.seeds)[:4]), | |
| fill=(235, 235, 240), font=font) | |
| for r, (label, _) in enumerate(rows): | |
| d.text((8, head + r * cw + 40), label, fill=(235, 235, 240), font=font) | |
| for c, sprite in enumerate(cells[r]): | |
| tile = Image.new("RGBA", (32, 32), (180, 180, 190, 255)) | |
| tile.alpha_composite(sprite) | |
| im.paste(tile.convert("RGB").resize((32 * z, 32 * z), Image.NEAREST), (lw + c * cw, head + r * cw)) | |
| im.save(a.out) | |
| print("saved", a.out) | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| sub = p.add_subparsers(dest="cmd", required=True) | |
| t = sub.add_parser("train", help="train a LoRA on a folder of captioned 32x32 sprites") | |
| t.add_argument("--data", required=True, help="folder of 32x32 PNGs with captions.jsonl or .txt sidecars") | |
| t.add_argument("--out", required=True) | |
| t.add_argument("--trigger", default="", help='words put before every caption, e.g. "spectral style"') | |
| t.add_argument("--steps", type=int, default=2000) | |
| t.add_argument("--batch", type=int, default=16) | |
| t.add_argument("--lr", type=float, default=1e-4) | |
| t.add_argument("--warmup", type=int, default=100) | |
| t.add_argument("--rank", type=int, default=16) | |
| t.add_argument("--alpha", type=float, default=0, help="default: equal to rank") | |
| t.add_argument("--blocks", default="all", choices=list(BLOCKS)) | |
| t.add_argument("--layers", default="attn+mlp", choices=list(LAYERS)) | |
| t.add_argument("--flip", type=int, default=1, help="1: also train mirrored copies (side words swapped)") | |
| t.add_argument("--prior-frac", type=float, default=0.5, help="share of each batch from the prior set (0: off)") | |
| t.add_argument("--prior-prompts", default=str(PRIOR_PROMPTS), help="prompts the teacher draws the prior from") | |
| t.add_argument("--prior-n", type=int, default=400, help="how many prior prompts to use") | |
| t.add_argument("--prior-dir", default="", help="use your own captioned sprites as the prior instead") | |
| t.add_argument("--save", type=int, nargs="*", default=[], help="also save at these steps") | |
| t.add_argument("--seed", type=int, default=0) | |
| t.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto") | |
| s = sub.add_parser("sheet", help="base vs LoRA comparison sheet") | |
| s.add_argument("--lora", required=True, type=Path) | |
| s.add_argument("--prompts", required=True, help="one prompt per line; include some without the trigger") | |
| s.add_argument("--strengths", type=float, nargs="*", default=[0.5, 1.0]) | |
| s.add_argument("--seeds", type=int, default=2) | |
| s.add_argument("--out", required=True) | |
| s.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto") | |
| a = p.parse_args() | |
| {"train": train, "sheet": sheet}[a.cmd](a) | |
| if __name__ == "__main__": | |
| main() | |