File size: 11,849 Bytes
40c5ebe
 
02d5c4b
 
 
 
 
 
40c5ebe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02d5c4b
40c5ebe
 
 
02d5c4b
 
 
 
 
 
 
 
 
 
40c5ebe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cdd6e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40c5ebe
8cdd6e8
40c5ebe
 
 
 
 
 
 
 
02d5c4b
 
 
 
 
 
40c5ebe
 
8cdd6e8
 
40c5ebe
 
 
02d5c4b
40c5ebe
 
 
 
02d5c4b
40c5ebe
 
 
 
 
 
 
 
 
 
 
 
02d5c4b
 
 
 
 
 
40c5ebe
 
02d5c4b
40c5ebe
 
 
 
 
 
 
 
 
 
02d5c4b
 
40c5ebe
 
 
 
 
 
 
 
 
 
 
 
02d5c4b
 
 
 
 
 
 
 
 
40c5ebe
 
 
02d5c4b
 
 
 
 
 
40c5ebe
02d5c4b
 
 
 
 
 
 
 
 
 
 
40c5ebe
 
 
02d5c4b
 
 
40c5ebe
 
 
 
 
 
 
 
 
 
02d5c4b
8cdd6e8
02d5c4b
 
 
 
 
40c5ebe
 
 
8cdd6e8
40c5ebe
8cdd6e8
 
40c5ebe
 
 
 
02d5c4b
40c5ebe
 
02d5c4b
 
40c5ebe
 
02d5c4b
40c5ebe
 
 
 
 
 
 
 
 
02d5c4b
 
 
40c5ebe
 
 
8cdd6e8
 
40c5ebe
 
 
8cdd6e8
40c5ebe
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
"""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()