HobbyLM-image-2 / hobby_image /inference.py
rootxhacker's picture
Add model_v2_768u (text-to-image, editing, text rendering), inference script and samples
20ebfa6 verified
Raw History Blame Contribute Delete
8.43 kB
"""HobbyLM-Image v2 inference: text-to-image, instruction editing and text rendering from one checkpoint.
from hobby_image.inference import HobbyImage
m = HobbyImage("model_v2_768u.pt")
m.generate(["a red fox sitting in a snowy forest, golden hour light, photo"])[0].save("fox.jpg")
m.edit([Image.open("fox.jpg")], ["make it autumn"])[0].save("fox_autumn.jpg")
m.text(['a wooden sign that says "OPEN" hanging on a cafe door'])[0].save("open.jpg")
Command line:
python -m hobby_image.inference --ckpt model_v2_768u.pt --prompt "a lighthouse on a cliff at sunset" --out out.jpg
python -m hobby_image.inference --ckpt model_v2_768u.pt --image in.jpg --prompt "make the car blue" --out edit.jpg
python -m hobby_image.inference --ckpt model_v2_768u.pt --text --prompt 'a road sign that says "NEXT EXIT"' --out sign.jpg
Tasks (the DiT's task id): 0 = text-to-image on one panel; 1 = edit, two panels [noisy target | source image];
2 = text rendering, two panels [noisy target | glyph panel with the words in a plain font].
"""
import numpy as np
import torch
from PIL import Image
from . import v2 as V2
from .dit import HobbyImageDiT, DiTConfig
from .glyph import glyph_panel, quoted, default_layout
DCAE = "mit-han-lab/dc-ae-f32c32-sana-1.1-diffusers"
class HobbyImage:
def __init__(self, ckpt: str, device: str = "cuda"):
from diffusers import AutoencoderDC
from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, AutoTokenizer
self.dev = device
ck = torch.load(ckpt, map_location=device, weights_only=False)
self.lat_std, self.sf, self.meta = float(ck["lat_std"]), float(ck["sf"]), ck["v2"]
self.model = HobbyImageDiT(DiTConfig(**ck["cfg_dict"])).to(device).eval()
self.model.load_state_dict(ck["sd"])
self.fusion = V2.TextFusion(1024, self.model.cfg.ctx_dim).to(device).eval()
self.fusion.load_state_dict(ck["fusion"])
self.ae = AutoencoderDC.from_pretrained(DCAE, torch_dtype=torch.bfloat16).to(device).eval()
self.tok = CLIPTokenizer.from_pretrained(V2.CLIP_ID)
self.clip = CLIPTextModel.from_pretrained(V2.CLIP_ID, torch_dtype=torch.bfloat16).to(device).eval()
self.t5_tok = AutoTokenizer.from_pretrained(ck["v2"]["t5"])
self.t5 = T5EncoderModel.from_pretrained(ck["v2"]["t5"], torch_dtype=torch.bfloat16).to(device).eval()
# ---- latents <-> images ----
def _decode(self, z):
out = []
with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
for j in range(0, len(z), 8):
out.append(self.ae.decode((z[j:j + 8] * self.lat_std / self.sf).bfloat16()).sample.float().clamp(-1, 1))
arr = ((torch.cat(out).permute(0, 2, 3, 1) + 1) * 127.5).clamp(0, 255).byte().cpu().numpy()
return [Image.fromarray(a) for a in arr]
def _encode(self, pil_list):
x = torch.from_numpy(np.stack([np.asarray(p.convert("RGB")) for p in pil_list])).to(self.dev)
x = x.permute(0, 3, 1, 2).float() / 127.5 - 1
with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
lat = self.ae.encode(x.bfloat16()).latent.float()
return lat * self.sf / self.lat_std
def _text(self, prompts):
ctx, mask = V2.encode_text(list(prompts), self.tok, self.clip, self.t5_tok, self.t5, self.fusion, self.dev)
return (ctx, mask) + tuple(V2.null_like(ctx, mask))
# ---- task 0: text-to-image ----
@torch.no_grad()
def generate(self, prompts, res: int = 768, steps: int = 50, cfg: float = 4.5, seed: int = 0):
"""Square images at 512 or 768px. 768px uses the timestep shift stored in the checkpoint."""
n, lat = len(prompts), res // 32
ctx, mask, uctx, umask = self._text(prompts)
z = torch.randn(n, 32, lat, lat, device=self.dev, generator=torch.Generator(self.dev).manual_seed(seed))
sh = V2.ckpt_shift(self.meta, res)
ts = [1 - sh * (1 - k / steps) / (1 + (sh - 1) * (1 - k / steps)) for k in range(steps + 1)]
task = torch.zeros(n, dtype=torch.long, device=self.dev)
pad = torch.zeros(n, 2, lat, lat, device=self.dev)
for i in range(steps):
tt = torch.full((n,), ts[i], device=self.dev)
inp = torch.cat([z, pad], dim=1)
with torch.autocast("cuda", dtype=torch.bfloat16):
vc = self.model(inp, tt, ctx, task, mask).float()
vu = self.model(inp, tt, uctx, task, umask).float()
z = z + (vu + cfg * (vc - vu)) * (ts[i + 1] - ts[i])
return self._decode(z)
# ---- tasks 1 and 2: two-panel sampling with separate text and image guidance ----
@torch.no_grad()
def _two_panel(self, src, prompts, task_id, steps, cfg_t, cfg_i, seed):
n, h, w = src.shape[0], src.shape[2], src.shape[3]
ctx, mask, uctx, umask = self._text(prompts)
z = torch.randn(n, 32, h, w, device=self.dev, generator=torch.Generator(self.dev).manual_seed(seed))
task = torch.full((n,), task_id, dtype=torch.long, device=self.dev)
pad = torch.zeros(n, 2, h, 2 * w, device=self.dev)
for i in range(steps):
tt = torch.full((n,), i / steps, device=self.dev)
a = torch.cat([torch.cat([z, src], dim=-1), pad], dim=1)
b = torch.cat([torch.cat([z, torch.zeros_like(src)], dim=-1), pad], dim=1)
with torch.autocast("cuda", dtype=torch.bfloat16):
vf = self.model(a, tt, ctx, task, mask).float()[..., :w] # text + panel
vi = self.model(a, tt, uctx, task, umask).float()[..., :w] # panel only
vu = self.model(b, tt, uctx, task, umask).float()[..., :w] # neither
z = z + (vu + cfg_i * (vi - vu) + cfg_t * (vf - vi)) / steps
return z
def edit(self, images, instructions, steps: int = 50, cfg_t: float = 7.5, cfg_i: float = 1.2, seed: int = 0, res: int = 512):
"""Instruction editing at 512px. The editor is square: other shapes are padded by repeating the edge
pixels, edited, cropped back and resized to the input size."""
fitted, boxes = [], []
for im in images:
im = im.convert("RGB")
w, h = im.size
s = res / max(w, h)
nw, nh = max(32, round(w * s)), max(32, round(h * s))
a = np.asarray(im.resize((nw, nh), Image.LANCZOS))
l, t = (res - nw) // 2, (res - nh) // 2
fitted.append(Image.fromarray(np.pad(a, ((t, res - nh - t), (l, res - nw - l), (0, 0)), mode="edge")))
boxes.append((l, t, l + nw, t + nh))
z = self._two_panel(self._encode(fitted), instructions, 1, steps, cfg_t, cfg_i, seed)
return [o.crop(b).resize(im.size, Image.LANCZOS) for o, b, im in zip(self._decode(z), boxes, images)]
def text(self, prompts, layouts=None, steps: int = 50, cfg_t: float = 5.0, cfg_i: float = 1.5, seed: int = 0, res: int = 512):
"""Text rendering at 512px. The words inside double quotes in each prompt are drawn into a glyph panel,
one word per line around the image centre, unless `layouts` gives [(word, (x0, y0, x1, y1)), ...] per
prompt. Short words in bold print on flat surfaces work best."""
panels = []
for k, p in enumerate(prompts):
items = layouts[k] if layouts else default_layout([w for t in quoted(p) for w in t.split()], res)
panels.append(glyph_panel(items, res))
return self._decode(self._two_panel(self._encode(panels), prompts, 2, steps, cfg_t, cfg_i, seed))
if __name__ == "__main__":
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", required=True)
ap.add_argument("--prompt", required=True)
ap.add_argument("--image", default="", help="source image: run an instruction edit")
ap.add_argument("--text", action="store_true", help='render the words in "double quotes" (glyph task)')
ap.add_argument("--res", type=int, default=768)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--out", default="out.jpg")
a = ap.parse_args()
m = HobbyImage(a.ckpt)
if a.image:
im = m.edit([Image.open(a.image)], [a.prompt], seed=a.seed)[0]
elif a.text:
im = m.text([a.prompt], seed=a.seed)[0]
else:
im = m.generate([a.prompt], res=a.res, seed=a.seed)[0]
im.save(a.out)
print("wrote", a.out)