sunstone-image-preview / generate.py
VertexAIco's picture
Update docstring name
5f9b67b verified
Raw History Blame Contribute Delete
2.45 kB
"""Sunstone Image Preview: text -> 64x64 image. python generate.py "a sunset over the beach" --n 4 --out sunset.png
Needs: torch, numpy, pillow, tokenizers. Runs on CUDA, Apple MPS or CPU (CPU: ~1 min per batch of 4)."""
import argparse, json, os, sys, numpy as np, torch
from PIL import Image
HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)
from model import Gen
from tokenizers import ByteLevelBPETokenizer
ap = argparse.ArgumentParser(); ap.add_argument("prompt"); ap.add_argument("--n", type=int, default=4, help="images (different seeds)")
ap.add_argument("--seed", type=int, default=1); ap.add_argument("--cfg", type=float, default=3.0); ap.add_argument("--steps", type=int, default=40)
ap.add_argument("--scale", type=int, default=4, help="enlarge the 64x64 output by this factor"); ap.add_argument("--out", default="out.png"); a = ap.parse_args()
dev = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
tk = ByteLevelBPETokenizer(os.path.join(HERE, "tokenizer/vocab.json"), os.path.join(HERE, "tokenizer/merges.txt"))
ids = np.zeros((a.n, 24), np.int64); e = tk.encode(a.prompt.lower()).ids[:24]; ids[:, :len(e)] = e # prompts are lower-cased, max 24 tokens
net = Gen(32000, ch=64).to(dev); sd = torch.load(os.path.join(HERE, "final_ema_fp16.pt"), map_location="cpu")
net.load_state_dict({k: v.float() for k, v in sd["ema"].items()}); net.eval()
def pad_of(t, null):
t = t.clone(); p = t == 0; p[:, 0] = False
if null: t[:] = 0; p[:] = True; p[:, 0] = False
return t, p
with torch.no_grad():
g = torch.Generator(device="cpu").manual_seed(a.seed); x = torch.randn(a.n, 3, 64, 64, generator=g).to(dev)
c, cp = pad_of(torch.as_tensor(ids).to(dev), False); u, up = pad_of(torch.as_tensor(ids).to(dev), True)
for i in range(a.steps): # rectified flow, Euler, classifier-free guidance
t = torch.full((a.n,), 1 - i / a.steps, device=dev); dt = 1.0 / a.steps
v = net(torch.cat([x, x]), torch.cat([t, t]), torch.cat([c, u]), torch.cat([cp, up])).float(); vc, vu = v.chunk(2); x = x - dt * (vu + a.cfg * (vc - vu))
im = ((x.clamp(-1, 1) + 1) * 127.5).round().byte().permute(0, 2, 3, 1).cpu().numpy()
row = np.concatenate(list(im), axis=1); Image.fromarray(row).resize((row.shape[1] * a.scale, row.shape[0] * a.scale), Image.LANCZOS).save(a.out); print("saved", a.out, "on", dev)