Add model_v2_768u (text-to-image, editing, text rendering), inference script and samples
Browse filesFiles changed (13)
- .gitattributes+7
- README.md+80-36
- hobby_image/glyph.pyAdded+41
- hobby_image/inference.pyAdded+150
- hobby_image/v2.py+83-81
- model_v2_768u.ptAdded+3
- samples/editing_768u.jpgAdded
- samples/inference_check.jpgAdded
- samples/mixed_768u.jpgAdded
- samples/text_benchmark_768u.jpgAdded
- samples/text_rendering_768u.jpgAdded
- samples/text_to_image_768u.jpgAdded
- samples/text_to_image_768u_2.jpgAdded
35 unmodified lines36373835 unmodified linessamples/humans_v2_768.jpg filter=lfs diff=lfs merge=lfs -textsamples/cars_v2_768.jpg filter=lfs diff=lfs merge=lfs -textsamples/scenes_v2_768.jpg filter=lfs diff=lfs merge=lfs -text35 unmodified lines3637383940414243444535 unmodified linessamples/humans_v2_768.jpg filter=lfs diff=lfs merge=lfs -textsamples/cars_v2_768.jpg filter=lfs diff=lfs merge=lfs -textsamples/scenes_v2_768.jpg filter=lfs diff=lfs merge=lfs -textsamples/editing_768u.jpg filter=lfs diff=lfs merge=lfs -textsamples/inference_check.jpg filter=lfs diff=lfs merge=lfs -textsamples/mixed_768u.jpg filter=lfs diff=lfs merge=lfs -textsamples/text_benchmark_768u.jpg filter=lfs diff=lfs merge=lfs -textsamples/text_rendering_768u.jpg filter=lfs diff=lfs merge=lfs -textsamples/text_to_image_768u.jpg filter=lfs diff=lfs merge=lfs -textsamples/text_to_image_768u_2.jpg filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667---license: otherpipeline_tag: text-to-imagetags: [text-to-image, flow-matching, dit, dc-ae]---# HobbyLM-image-2Private working checkpoint of HobbyLM-Image v2 (`model_v2_768`, 23 November 2026).- **Model:** 333M-parameter flow-matching DiT, single panel, with a small text-fusion module.- **Text encoders (not included):** `openai/clip-vit-large-patch14` (64 tokens) and `google/flan-t5-large` (96 tokens).- **Autoencoder (not included):** `mit-han-lab/dc-ae-f32c32-sana-1.1-diffusers` (32x compression, 32 channels).- **Resolution:** trained at 512px and 768px; sample at 768px with timestep shift 1.5 (stored in the checkpoint), or at 512px with no shift.- **Sampler:** Euler, 50 steps, CFG 4.5, all-zero null conditioning.## Files- `model_v2_768.pt`: EMA weights. Keys: `sd` (DiT), `fusion` (text fusion), `cfg_dict`, `lat_std`, `sf`, `steps`, `v2` (metadata incl. `hi_res`, `hi_shift`).- `hobby_image/dit.py`, `hobby_image/v2.py`: model and sampler code.- `samples/`: fixed-seed grids at 768px.## SamplesAll generated at 768px, 50 Euler steps, CFG 4.5, timestep shift 1.5, fixed seed, no cherry-picking. The prompt is printed under each image.**People****Cars****Scenes**## Usage sketch```pythonimport torchfrom diffusers import AutoencoderDCfrom hobby_image.dit import HobbyImageDiT, DiTConfigfrom hobby_image import v2 as V2ck = torch.load("model_v2_768.pt", map_location="cuda")dit = HobbyImageDiT(DiTConfig(**ck["cfg_dict"])).cuda().eval(); dit.load_state_dict(ck["sd"])fusion = V2.TextFusion(1024, dit.cfg.ctx_dim).cuda().eval(); fusion.load_state_dict(ck["fusion"])# encode text with V2.encode_text(...), build the null condition with V2.null_like(...),# sample with V2.sample(dit, ctx, mask, uctx, umask, z, n_steps=50, cfg=4.5, shift=V2.ckpt_shift(ck["v2"], 768)),# decode with ae.decode(z * ck["lat_std"] / ck["sf"]).```## Scores (self-run, one seed)| Benchmark | Score ||---|---|| GenEval 2 Soft-TIFA, 768px | AM 59.55 / GM 15.99 || GenEval 2 Soft-TIFA, 512px | AM 57.39 / GM 15.08 || GenEval (previous checkpoint `model_v2_512c`, 512px) | 0.831 |## Disclosures- The training mix includes GenEval-style compositional data (Echo-4o-Image, BLIP3o-60k), so GenEval is not zero-shot.- The mix includes FLUX-Reason-6M (FLUX.1-dev outputs), whose licence restricts training competing models. Check before any public release.- Known weaknesses: hands, text rendering, faces smaller than about 55px, counts above three.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111---license: otherpipeline_tag: text-to-imagetags: [text-to-image, image-to-image, image-editing, text-rendering, flow-matching, dit, dc-ae]---# HobbyLM-image-2Private working checkpoints of HobbyLM-Image v2. The current one is `model_v2_768u` (26 November 2026). It does three things from one set of weights:1. **Text-to-image** at 512px and 768px.2. **Instruction editing** at 512px: give it an image and an instruction such as "make the car blue".3. **Text rendering** at 512px: words in double quotes in the prompt are drawn into the image.All sample images below are first-seed outputs with no selection.## Model- **Size:** 333M-parameter flow-matching DiT with a small text-fusion module.- **Text encoders (not included):** `openai/clip-vit-large-patch14` (64 tokens) and `google/flan-t5-large` (96 tokens).- **Autoencoder (not included):** `mit-han-lab/dc-ae-f32c32-sana-1.1-diffusers` (32x compression, 32 channels).- **Tasks:** the DiT takes a task id. 0 is text-to-image on one panel. 1 is editing on two panels, `[noisy target | source image]`. 2 is text rendering on two panels, `[noisy target | glyph panel]`, where the glyph panel is the requested words in a plain font on white.## Text-to-image768px, Euler 50 steps, CFG 4.5, timestep shift 1.5 (stored in the checkpoint).## Instruction editingEach pair is a 512px image generated by the model (left) and the same model's edit of it (right). Text guidance 7.5, image guidance 1.2.Ten of these twelve edits are clean. "Add a croissant beside the cup" replaced the cup, and "change the background to a beach" changed the ground but kept the buildings.## Text rendering512px. The quoted words are placed in the glyph panel one word per line around the image centre.The second grid shows the limits: bold print on flat surfaces (shirts, road signs, book covers) is usually right, while neon, chalk, handwriting and words of seven or more letters are often misspelled. Without the glyph panel the model cannot spell.## Usage```pythonfrom PIL import Imagefrom hobby_image.inference import HobbyImagem = HobbyImage("model_v2_768u.pt")# text-to-image (768px)m.generate(["a red fox sitting in a snowy forest, golden hour light, photo"])[0].save("fox.jpg")# instruction editing (any aspect ratio in, same size out)m.edit([Image.open("fox.jpg")], ["make it autumn"])[0].save("fox_autumn.jpg")# text rendering (words in double quotes)m.text(['a wooden sign that says "OPEN" hanging on a cafe door'])[0].save("open.jpg")```Command line:```bashpython -m hobby_image.inference --ckpt model_v2_768u.pt --prompt "a lighthouse on a cliff at sunset" --out out.jpgpython -m hobby_image.inference --ckpt model_v2_768u.pt --image in.jpg --prompt "make the car blue" --out edit.jpgpython -m hobby_image.inference --ckpt model_v2_768u.pt --text --prompt 'a road sign that says "NEXT EXIT"' --out sign.jpg```Requires `torch`, `diffusers>=0.32`, `transformers`, `sentencepiece` and `pillow`. `samples/inference_check.jpg` is the output of this script run end to end (generate, crop to a wide image, edit, text).## Scores (self-run, one seed)| Benchmark | `model_v2_768` | `model_v2_768u` ||---|---|---|| GenEval 2 Soft-TIFA at 768px, GM / AM | 15.99 / 59.55 | 15.92 / 61.06 || GEdit-Bench-EN, Qwen2.5-VL-72B judge, SC / PQ / O | no editing | 6.03 / 6.00 / 5.35 || Text benchmark, all words spelled right | cannot spell | 74% |- **GenEval 2:** 800 prompts, Qwen3-VL-8B judge, official code. Differences under about 2 GM are noise.- **GEdit-Bench-EN:** all 606 English edits, official VIEScore prompts, judge served with vLLM. The same setup scores the released Step1X-Edit v1.0 outputs at 7.43 / 7.25 / 7.01 against a published 7.39 / 7.28 / 7.07. Sources are padded to a square, edited at 512px and cropped back.- **Text benchmark:** 100 prompts of my own (40 one-word, 40 two-word, 20 three-word texts on signs, shirts, mugs, posters and similar), read back by Qwen3-VL-8B. 74% have every requested word spelled correctly and 68% match exactly with no stray text. It is not a published benchmark, and scene-heavy prompts do worse (about half correct).- **Emu Edit test set** (previous checkpoint `model_v2_768t`, 500 edits): CLIP-dir 0.090, CLIP-im 0.859, L1 0.120, DINO 0.787. InstructPix2Pix through the same code scores 0.075 / 0.852 / 0.123 / 0.772.## Files- `model_v2_768u.pt`: current EMA weights, all three tasks. Keys: `sd` (DiT), `fusion` (text fusion), `cfg_dict`, `lat_std`, `sf`, `steps`, `v2` (metadata, including the timestep shifts).- `model_v2_768.pt`: the 23 November checkpoint, text-to-image only.- `hobby_image/inference.py`: the three entry points shown above.- `hobby_image/dit.py`, `hobby_image/v2.py`, `hobby_image/glyph.py`: model, text conditioning and glyph panel code.- `samples/`: the grids on this page, plus `text_benchmark_768u.jpg` (twelve images from the text benchmark).## Known weaknesses- Faces smaller than about 100px, hands, and wide laughing mouths.- Editing follows the instruction less reliably than large editors (GEdit-Bench overall 5.35 against about 7 for Step1X-Edit). Changing text inside an image, style transfer and motion changes are the weakest edit types.- The editor and the text mode are square, 512px only. Non-square edit inputs are padded.- Text rendering needs the glyph panel and works for one to three short words.- Counts above three people.## Disclosures- The training mix includes GenEval-style compositional data (Echo-4o-Image, BLIP3o-60k), so GenEval and GenEval 2 are not zero-shot.- The mix includes FLUX-Reason-6M (FLUX.1-dev outputs), whose licence restricts training competing models. Check before any public release.- Editing was trained on OmniEdit-Filtered-1.2M and the editing split of ShareGPT-4o-Image (GPT-4o outputs). Text rendering was trained on the LAION subset of AnyWord-3M. People photos come from `data-archetype/pexels_aesth_2_1024`. Check each licence before any public release.
1234567891011121314151617181920212223242526272829303132333435363738394041"""Glyph panel for text rendering (task id 2): the words to draw, rendered in a plain font on a white square atthe place they should appear. The DiT sees this panel next to the noisy target, the same two-panel layout asinstruction editing, and learns to copy the spelling into the scene."""import re
def glyph_panel(items, res: int = 512): """items: [(text, (x0, y0, x1, y1)), ...] in pixel coordinates of a res x res image -> PIL image.""" from PIL import Image, ImageDraw, ImageFont im = Image.new("RGB", (res, res), "white") d = ImageDraw.Draw(im) for text, (x0, y0, x1, y1) in items: bw, bh = max(8, x1 - x0), max(8, y1 - y0) s = max(8, int(bh * 0.95)) f = ImageFont.load_default(size=s) l, t, r, b = d.textbbox((0, 0), text, font=f) if r - l > bw: # too wide for the box: shrink to fit s = max(8, int(s * bw / (r - l))) f = ImageFont.load_default(size=s) l, t, r, b = d.textbbox((0, 0), text, font=f) d.text((x0 + (bw - (r - l)) / 2 - l, y0 + (bh - (b - t)) / 2 - t), text, font=f, fill="black") return im
def quoted(prompt: str): """Strings inside double (or curly) quotes in a prompt, in order.""" return [m.strip() for m in re.findall(r'["“]([^"”]{1,40})["”]', prompt) if m.strip()]
def default_layout(texts, res: int = 512): """Boxes for prompts that give no layout: lines stacked around the image centre, each as wide as its letters allow at a height of about 1/6 of the image.""" n = len(texts) h = min(res // 6, int(res * 0.6 / max(1, n))) y = (res - n * h - (n - 1) * h // 4) // 2 out = [] for t in texts: w = min(int(res * 0.84), int(h * 0.62 * max(2, len(t)))) out.append((t, ((res - w) // 2, y, (res + w) // 2, y + h))) y += h + h // 4 return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""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 npimport torchfrom PIL import Image
from . import v2 as V2from .dit import HobbyImageDiT, DiTConfigfrom .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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""HobbyLM-Image v2 conditioning + sampling helpers.v2 keeps the v1 DiT weights but (a) runs text-to-image on a SINGLE panel (no blank source panel ->half the tokens) and (b) conditions on CLIP-L tokens *plus* FLAN-T5 encoder tokens, fused into onecross-attention context. CLIP-L alone caps compositional prompts (counting / position / attributebinding); T5 tokens are projected into the CLIP context width so the pretrained cross-attentionkeeps working from step 0."""from __future__ import annotationsimport torchimport torch.nn as nnfrom torch import TensorCLIP_ID = "openai/clip-vit-large-patch14"T5_ID = "google/flan-t5-large"CLIP_LEN = 64T5_LEN = 96class TextFusion(nn.Module):"""[CLIP tokens (ctx_dim) | proj(T5 tokens)] -> (ctx, mask). CLIP tokens are all attended (as inv1 training); T5 padding is masked out."""def __init__(self, t5_dim: int = 1024, ctx_dim: int = 768):super().__init__()self.ln = nn.LayerNorm(t5_dim)self.proj = nn.Linear(t5_dim, ctx_dim)nn.init.normal_(self.proj.weight, std=0.02); nn.init.zeros_(self.proj.bias)def forward(self, clip_h: Tensor, t5_h: Tensor, t5_mask: Tensor) -> tuple[Tensor, Tensor]:t = self.proj(self.ln(t5_h.float())) * t5_mask[..., None].float()ctx = torch.cat([clip_h.float(), t], dim=1)mask = torch.cat([torch.ones(clip_h.shape[:2], dtype=torch.bool, device=clip_h.device),t5_mask.bool()], dim=1)return ctx, maskdef null_like(ctx: Tensor, mask: Tensor) -> tuple[Tensor, Tensor]:"""Unconditional branch used in training (10% drop): all-zero context, nothing masked."""return torch.zeros_like(ctx), torch.ones_like(mask)@torch.no_grad()def encode_text(texts, clip_tok, clip, t5_tok, t5, fusion, dev="cuda"):"""texts -> fused (ctx, mask) with frozen encoders (bf16 autocast)."""ci = clip_tok(texts, padding="max_length", max_length=CLIP_LEN, truncation=True,return_tensors="pt").input_ids.to(dev)tt = t5_tok(texts, padding="max_length", max_length=T5_LEN, truncation=True, return_tensors="pt")ti, tm = tt.input_ids.to(dev), tt.attention_mask.to(dev)with torch.autocast("cuda", dtype=torch.bfloat16):ch = clip(ci).last_hidden_stateth = t5(input_ids=ti, attention_mask=tm).last_hidden_statereturn fusion(ch, th, tm)def ckpt_shift(meta: dict, res: int) -> float:"""Sampling shift for a checkpoint's meta (ck["v2"]) at `res`: the trained high-res shift at thehigh-res training resolution, 1.0 everywhere else."""return float(meta.get("hi_shift") or 1.0) if meta.get("hi_res") == res else 1.0@torch.no_grad()def sample(dit, ctx, mask, uctx, umask, z, n_steps: int = 50, cfg: float = 4.0, shift: float = 1.0):"""Single-panel Euler flow-matching sampler with classifier-free guidance (t: 0 = noise -> 1 = data).shift > 1 spends more steps at high noise (SD3 resolution shift on the noise level 1 - t); use thevalue the checkpoint was trained with at that resolution (ck["v2"]["hi_shift"]), 1.0 otherwise."""n = z.shape[0]task = torch.zeros(n, dtype=torch.long, device=z.device)pad = torch.zeros(n, 2, z.shape[2], z.shape[3], device=z.device) # unused mask channelsts = [i / n_steps for i in range(n_steps + 1)]if shift != 1.0:ts = [1 - shift * (1 - t) / (1 + (shift - 1) * (1 - t)) for t in ts]for i in range(n_steps):tt = torch.full((n,), ts[i], device=z.device)inp = torch.cat([z, pad], dim=1)with torch.autocast("cuda", dtype=torch.bfloat16):vc = dit(inp, tt, ctx, task, mask).float()vu = dit(inp, tt, uctx, task, umask).float()z = z + (vu + cfg * (vc - vu)) * (ts[i + 1] - ts[i])return z1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""HobbyLM-Image v2 conditioning + sampling helpers.v2 keeps the v1 DiT weights but (a) runs text-to-image on a SINGLE panel (no blank source panel ->half the tokens) and (b) conditions on CLIP-L tokens *plus* FLAN-T5 encoder tokens, fused into onecross-attention context. CLIP-L alone caps compositional prompts (counting / position / attributebinding); T5 tokens are projected into the CLIP context width so the pretrained cross-attentionkeeps working from step 0."""from __future__ import annotationsimport torchimport torch.nn as nnfrom torch import TensorCLIP_ID = "openai/clip-vit-large-patch14"T5_ID = "google/flan-t5-large"CLIP_LEN = 64T5_LEN = 96class TextFusion(nn.Module):"""[CLIP tokens (ctx_dim) | proj(T5 tokens)] -> (ctx, mask). CLIP tokens are all attended (as inv1 training); T5 padding is masked out."""def __init__(self, t5_dim: int = 1024, ctx_dim: int = 768):super().__init__()self.ln = nn.LayerNorm(t5_dim)self.proj = nn.Linear(t5_dim, ctx_dim)nn.init.normal_(self.proj.weight, std=0.02); nn.init.zeros_(self.proj.bias)def forward(self, clip_h: Tensor, t5_h: Tensor, t5_mask: Tensor) -> tuple[Tensor, Tensor]:t = self.proj(self.ln(t5_h.float())) * t5_mask[..., None].float()ctx = torch.cat([clip_h.float(), t], dim=1)mask = torch.cat([torch.ones(clip_h.shape[:2], dtype=torch.bool, device=clip_h.device),t5_mask.bool()], dim=1)return ctx, maskdef null_like(ctx: Tensor, mask: Tensor) -> tuple[Tensor, Tensor]:"""Unconditional branch used in training (10% drop): all-zero context, nothing masked."""return torch.zeros_like(ctx), torch.ones_like(mask)@torch.no_grad()def encode_text(texts, clip_tok, clip, t5_tok, t5, fusion, dev="cuda"):"""texts -> fused (ctx, mask) with frozen encoders (bf16 autocast)."""ci = clip_tok(texts, padding="max_length", max_length=CLIP_LEN, truncation=True,return_tensors="pt").input_ids.to(dev)tt = t5_tok(texts, padding="max_length", max_length=T5_LEN, truncation=True, return_tensors="pt")ti, tm = tt.input_ids.to(dev), tt.attention_mask.to(dev)with torch.autocast("cuda", dtype=torch.bfloat16):ch = clip(ci).last_hidden_stateth = t5(input_ids=ti, attention_mask=tm).last_hidden_statereturn fusion(ch, th, tm)def ckpt_shift(meta: dict, res: int) -> float:"""Sampling shift for a checkpoint's meta (ck["v2"]) at `res`: the trained high-res shift at thehigh-res training resolution, 1.0 everywhere else."""if str(res) in (meta.get("shifts") or {}): # checkpoints trained at several high resolutionsreturn float(meta["shifts"][str(res)])return float(meta.get("hi_shift") or 1.0) if meta.get("hi_res") == res else 1.0@torch.no_grad()def sample(dit, ctx, mask, uctx, umask, z, n_steps: int = 50, cfg: float = 4.0, shift: float = 1.0):"""Single-panel Euler flow-matching sampler with classifier-free guidance (t: 0 = noise -> 1 = data).shift > 1 spends more steps at high noise (SD3 resolution shift on the noise level 1 - t); use thevalue the checkpoint was trained with at that resolution (ck["v2"]["hi_shift"]), 1.0 otherwise."""n = z.shape[0]task = torch.zeros(n, dtype=torch.long, device=z.device)pad = torch.zeros(n, 2, z.shape[2], z.shape[3], device=z.device) # unused mask channelsts = [i / n_steps for i in range(n_steps + 1)]if shift != 1.0:ts = [1 - shift * (1 - t) / (1 + (shift - 1) * (1 - t)) for t in ts]for i in range(n_steps):tt = torch.full((n,), ts[i], device=z.device)inp = torch.cat([z, pad], dim=1)with torch.autocast("cuda", dtype=torch.bfloat16):vc = dit(inp, tt, ctx, task, mask).float()vu = dit(inp, tt, uctx, task, umask).float()z = z + (vu + cfg * (vc - vu)) * (ts[i + 1] - ts[i])return z
123version https://git-lfs.github.com/spec/v1oid sha256:3f6998dfcb649096c9065d025cbdb5a0a28abb1726aef4093a4ae03144b949casize 1338173196.gitattributes+7
README.md+80-36
hobby_image/glyph.pyAdded+41
hobby_image/inference.pyAdded+150
hobby_image/v2.py+83-81
model_v2_768u.ptAdded+3
samples/editing_768u.jpgAdded

Large File Pointer Details
- SHA256: a4a388148b848d5a971d12f721c09d6c246ceb1fe4c21a55f4d9205cf1e74272
- Pointer size: 132 Bytes
- Size of remote file: 2.19 MB
samples/inference_check.jpgAdded

Large File Pointer Details
- SHA256: 4bf71fbace35135de536d55f1666e4abea7b954b80e4b3a0bfe8a8785df16fe7
- Pointer size: 131 Bytes
- Size of remote file: 284 kB
samples/mixed_768u.jpgAdded

Large File Pointer Details
- SHA256: d457597e9972addcc2c14a67e52ec1e8eb2de6f6ec2e70a99c143605ce1fd0b6
- Pointer size: 132 Bytes
- Size of remote file: 1.09 MB
samples/text_benchmark_768u.jpgAdded

Large File Pointer Details
- SHA256: 6b4e33f81e05e7841254b6f23affb800fa247a67be811843fdcb1f1f59c6e470
- Pointer size: 131 Bytes
- Size of remote file: 455 kB
samples/text_rendering_768u.jpgAdded

Large File Pointer Details
- SHA256: 916e19ca970ed6b1fc342755c7e6c045d2be288ba605a27344f874262e197fa7
- Pointer size: 131 Bytes
- Size of remote file: 783 kB
samples/text_to_image_768u.jpgAdded

Large File Pointer Details
- SHA256: 8a8820ad8025e9b4e5a8243b0f9e13b2f6e7f02d24c58ff2af6c617fe1b69b00
- Pointer size: 132 Bytes
- Size of remote file: 1.46 MB
samples/text_to_image_768u_2.jpgAdded

Large File Pointer Details
- SHA256: 747fa5f221d80682fd5bed1db879f54eac0fbad44196da069703b89775956a7d
- Pointer size: 132 Bytes
- Size of remote file: 1.81 MB