solstice-80m / generate.py
thalismind
Claude Opus 5.5
feat: add six example LoRAs for the r80-1202 teacher, with --lora support and example sheets
8cdd6e8
Raw History Blame Contribute Delete
11.8 kB
"""Generate one 32x32 RGBA sprite from a Safetensors checkpoint or ONNX export.
r80-1202 (pytorch/r80-1202, onnx/r80-1202) uses config.json: r80 sizes, x0 prediction and
self-conditioning, sampled by default with 30 Heun steps. s80-1201 files (pytorch/s80-1201,
pytorch/s80-1201-100k, onnx/s80-1201) use configs/s80-1201.json and Euler sampling. A Safetensors
file names its config in its metadata; files without that entry are s80-1201 files. An ONNX
export with an `sc` input is the r80-1202 teacher.
Dependencies: torch transformers safetensors numpy pillow
ONNX also needs onnxruntime (CPU) or onnxruntime-gpu (CUDA).
The text encoder is downloaded from Hugging Face on first use.
"""
import argparse
import json
import re
from pathlib import Path
import numpy as np
import torch
from PIL import Image
ROOT = Path(__file__).resolve().parent
CONFIG = json.loads((ROOT / "config.json").read_text())
S80_CONFIG = "configs/s80-1201.json"
TEXT_ENCODER = "google/t5gemma-2b-2b-ul2"
def load_config(name):
return json.loads((ROOT / name).read_text())
def teacher_sampling(config):
"""(steps, sampler) a teacher uses by default."""
sampling = config["sampling"]
return int(sampling["teacher_steps"]), sampling.get("solver", "euler")
def resolve_device(name="auto"):
if name == "auto":
name = "cuda" if torch.cuda.is_available() else "cpu"
if name == "cuda" and not torch.cuda.is_available():
raise RuntimeError("CUDA was requested but is not available to PyTorch")
return torch.device(name)
class TextEncoder:
def __init__(self, name, device):
from transformers import AutoTokenizer, T5GemmaEncoderModel
self.device = device
self.tokenizer = AutoTokenizer.from_pretrained(name)
self.tokenizer.padding_side = "right"
dtype = torch.bfloat16 if device.type == "cuda" else torch.float32
self.encoder = T5GemmaEncoderModel.from_pretrained(
name, dtype=dtype, is_encoder_decoder=False
).to(device).eval().requires_grad_(False)
@torch.inference_mode()
def encode(self, prompt):
# The empty string is deliberately unprefixed: it is the unconditional prompt.
strings = [CONFIG["text_encoder"]["prompt_template"].replace("<caption>", prompt), ""]
batch = self.tokenizer(
strings, padding="max_length", max_length=64, truncation=True, return_tensors="pt"
).to(self.device)
mask = batch.attention_mask.bool()
hidden = self.encoder(**batch).last_hidden_state.float()
hidden = torch.where(mask[..., None], hidden, 0.0)
pool = hidden.sum(1) / mask.sum(1).clamp(min=1)[:, None]
condition = (hidden, mask, pool)
return tuple(x[0:1] for x in condition), tuple(x[1:2] for x in condition)
def merge_lora(model, path, strength=1.0):
"""Add a LoRA (loras/r80-1202/*/lora.safetensors) into the model's linear weights: W += s * alpha/rank * B @ A.
LoRAs were trained on the r80-1202 teacher; on a distilled student they may work less well.
"""
from safetensors import safe_open
with safe_open(str(path), framework="pt", device="cpu") as f:
meta = f.metadata() or {}
scale = strength * float(meta.get("alpha", 16)) / float(meta.get("rank", 16))
modules = dict(model.named_modules())
names = sorted({k.rsplit(".", 1)[0] for k in f.keys()})
for name in names:
linear = modules[name]
a, b = f.get_tensor(f"{name}.A").float(), f.get_tensor(f"{name}.B").float()
linear.weight.data += (scale * (b @ a)).to(linear.weight.dtype)
return meta
class TorchBackend:
def __init__(self, checkpoint, device, lora=None, lora_strength=1.0):
from safetensors import safe_open
from safetensors.torch import load_file
from model import SolsticeGenerator
with safe_open(checkpoint, framework="pt", device="cpu") as f:
metadata = f.metadata() or {}
self.guided = metadata.get("guidance_distilled") == "true"
self.steps = int(metadata.get("sampling_steps", 40))
# Distilled students are Euler-step models; teachers name their sampler (s80-1201 files: Euler).
self.sampler = "euler" if self.guided else metadata.get("sampler", "euler")
config = load_config(metadata.get("config", S80_CONFIG))
kwargs = dict(config["constructor"], guidance=self.guided)
# Self-conditioning feeds the previous step's x0 estimate back in (zeros on the first step).
self.self_cond = bool(kwargs.get("self_cond")) and not self.guided
self.model = SolsticeGenerator(**kwargs)
self.model.load_state_dict(load_file(checkpoint), strict=True)
if lora:
merge_lora(self.model, lora, lora_strength)
self.model = self.model.to(device).eval().requires_grad_(False)
self.device = device
def call(self, x, t, condition, guidance, sc=None):
tokens, mask, pool = condition
tt = torch.full((1,), t, device=self.device)
w = torch.full((1,), guidance, device=self.device) if self.guided else None
with torch.autocast("cuda", torch.bfloat16, enabled=self.device.type == "cuda"):
return self.model(x, tt, pool, tokens, mask, w, sc=sc).float()
class OnnxBackend:
def __init__(self, checkpoint, device):
import onnxruntime as ort
requested = "CUDAExecutionProvider" if device.type == "cuda" else "CPUExecutionProvider"
if requested not in ort.get_available_providers():
raise RuntimeError(f"{requested} is not available; install the matching ONNX Runtime package")
self.session = ort.InferenceSession(str(checkpoint), providers=[requested])
self.inputs = {x.name for x in self.session.get_inputs()}
self.guided = "w" in self.inputs
# The r80-1202 teacher export takes the previous x0 estimate as input `sc`.
self.self_cond = "sc" in self.inputs
if self.self_cond:
self.steps, self.sampler = teacher_sampling(CONFIG)
else:
self.steps, self.sampler = steps_from_path(checkpoint), "euler"
self.device = torch.device("cpu")
def call(self, x, t, condition, guidance, sc=None):
tokens, mask, pool = condition
feed = {
"x": x.numpy().astype(np.float32),
"t": np.full((1,), t, np.float32),
"pool": pool.cpu().numpy().astype(np.float32),
"tokens": tokens.cpu().numpy().astype(np.float32),
"mask": mask.cpu().numpy().astype(bool),
}
if self.guided:
feed["w"] = np.full((1,), guidance, np.float32)
if self.self_cond:
feed["sc"] = (torch.zeros_like(x) if sc is None else sc).numpy().astype(np.float32)
return torch.from_numpy(self.session.run(None, feed)[0])
def steps_from_path(path):
for part in Path(path).parts:
match = re.search(r"(?:student|guidance)-(\d+)-step", part)
if match:
return int(match.group(1))
return 40
@torch.inference_mode()
def sample(backend, condition, uncondition, steps, guidance, seed, sampler="euler"):
"""Integrate from t = 1 to 0 on a uniform grid.
euler: one evaluation per step. heun: two per step (the second at the Euler predictor's
endpoint), except the last step, which is an Euler step to t = 0; 2 * steps - 1 evaluations.
Teachers get classifier-free guidance on t <= 0.75. A self-conditioning model gets the previous
evaluation's x0 estimate (x - t * v).clamp(-1, 1) from the guided velocity, zeros at the first;
within a Heun step the second evaluation sees the first one's estimate.
"""
generator = torch.Generator(device=backend.device).manual_seed(seed)
x = torch.randn((1, 4, 32, 32), generator=generator, device=backend.device)
schedule = torch.linspace(1, 0, steps + 1).tolist()
state = {"sc": None} # self-conditioning input: the previous evaluation's x0 estimate
def velocity(x, t):
conditional = backend.call(x, t, condition, guidance, state["sc"])
if backend.guided or guidance == 1.0 or t > 0.75 + 1e-5:
v = conditional
else:
unconditional = backend.call(x, t, uncondition, guidance, state["sc"])
v = unconditional + guidance * (conditional - unconditional)
if backend.self_cond:
state["sc"] = (x - t * v).clamp(-1, 1)
return v
for i, (t0, t1) in enumerate(zip(schedule, schedule[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
euler_sample = sample # the previous name
def to_image(x):
x = x.float().clamp(-1, 1).cpu()
rgb = ((x[:, :3] + 1) * 127.5).round().clamp(0, 255)
opaque = x[:, 3] > 0
alpha = opaque.float() * 255
rgba = torch.cat([rgb * opaque[:, None], alpha[:, None]], 1)
array = rgba.permute(0, 2, 3, 1).to(torch.uint8).numpy()[0]
return Image.fromarray(array, "RGBA")
def generate(prompt, checkpoint, seed=0, steps=None, guidance=4.0, device="auto", text_encoder=None,
sampler=None, lora=None, lora_strength=1.0):
"""Return a 32x32 PIL RGBA image. Checkpoint may be .safetensors or .onnx.
steps and sampler ("euler" or "heun") default to the checkpoint's own: 30 Heun steps for the
r80-1202 teacher, Euler at the distilled step count for students, 40 Euler for s80-1201 teachers.
"""
device = resolve_device(device)
checkpoint = Path(checkpoint)
if checkpoint.suffix == ".safetensors":
backend = TorchBackend(checkpoint, device, lora, lora_strength)
elif checkpoint.suffix == ".onnx":
if lora:
raise ValueError("LoRAs apply to .safetensors checkpoints (the teacher), not ONNX exports")
backend = OnnxBackend(checkpoint, device)
else:
raise ValueError("Choose a .safetensors or .onnx model")
steps = steps or backend.steps
sampler = sampler or backend.sampler
if steps < 1:
raise ValueError("steps must be positive")
if sampler not in ("euler", "heun"):
raise ValueError("sampler must be euler or heun")
encoder_name = text_encoder or TEXT_ENCODER
condition, uncondition = TextEncoder(encoder_name, device).encode(prompt)
result = sample(backend, condition, uncondition, steps, guidance, seed, sampler)
return to_image(result)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("checkpoint", type=Path, help=".safetensors or .onnx model")
parser.add_argument("--prompt", required=True)
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--steps", type=int, help="default: the checkpoint's own (30 for the r80-1202 teacher)")
parser.add_argument("--sampler", choices=("euler", "heun"),
help="default: the checkpoint's own (heun for the r80-1202 teacher, else euler)")
parser.add_argument("--guidance", type=float, default=4.0)
parser.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto")
parser.add_argument("--text-encoder", default=TEXT_ENCODER)
parser.add_argument("--lora", type=Path, help="a LoRA from loras/r80-1202 (teacher .safetensors only)")
parser.add_argument("--lora-strength", type=float, default=1.0)
args = parser.parse_args()
image = generate(
args.prompt, args.checkpoint, args.seed, args.steps, args.guidance,
args.device, args.text_encoder, args.sampler, args.lora, args.lora_strength,
)
image.save(args.output)
print(f"Saved {args.output} ({image.width}x{image.height})")
if __name__ == "__main__":
main()