"""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 one cross-attention context. CLIP-L alone caps compositional prompts (counting / position / attribute binding); T5 tokens are projected into the CLIP context width so the pretrained cross-attention keeps working from step 0. """ from __future__ import annotations import torch import torch.nn as nn from torch import Tensor CLIP_ID = "openai/clip-vit-large-patch14" T5_ID = "google/flan-t5-large" CLIP_LEN = 64 T5_LEN = 96 class TextFusion(nn.Module): """[CLIP tokens (ctx_dim) | proj(T5 tokens)] -> (ctx, mask). CLIP tokens are all attended (as in v1 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, mask def 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_state th = t5(input_ids=ti, attention_mask=tm).last_hidden_state return 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 the high-res training resolution, 1.0 everywhere else.""" if str(res) in (meta.get("shifts") or {}): # checkpoints trained at several high resolutions return 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 the value 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 channels ts = [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