Download halide_modeling.py from Emergent-Knowledge/halide-preview: direct link, hf CLI and curl.
- Browser
- Download file 25.3 kB
-
https://huggingface.co/Emergent-Knowledge/halide-preview/resolve/main/halide_modeling.py
- Command line
-
hf download hf://Emergent-Knowledge/halide-preview/halide_modeling.py
-
curl -L -o halide_modeling.py https://huggingface.co/Emergent-Knowledge/halide-preview/resolve/main/halide_modeling.py
25.3 kB
| """Halide Preview (v5, 768px): Portable PyTorch inference model & pipeline. | |
| Architecture: | |
| - 192.2M-param FCDM-Thinker2-MR (flat 768px mode, 96x96 SD-VAE latent grid) | |
| * Perceiver-based recurrent Thinker (24x24 spatial plan + 16 global tokens, | |
| 4 perceiver blocks, 3 prelude + 3 recurrent core x 4 loops + 2 coda blocks, | |
| 2D RoPE + QK-RMSNorm + multi-res ConvRead) | |
| * Pure-ConvNeXt V2 SpatialMod U-Net renderer (widths [288, 832, 1664], | |
| depths [4, 6, 2], expansion 3, steer_rank [128, 256, 256], PlanUp + CoordIn) | |
| - DistillT5 text encoder (LifuWang/DistillT5 + google-t5/t5-base tokenizer) | |
| with learned 4096 -> 512 ctx_proj adapter (2.1M params). | |
| - Frozen stabilityai/sd-vae-ft-mse (scale 0.18215). | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from dataclasses import dataclass, field | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| N_COORD = 3 | |
| COUNT_K = (1, 2, 4, 8) | |
| COUNT_W = (1.0, 0.7, 0.5, 0.35) | |
| DISTILLT5_REPO = "LifuWang/DistillT5" | |
| DISTILLT5_TOKENIZER_REPO = "google-t5/t5-base" | |
| DISTILLT5_D_MODEL = 768 | |
| DISTILLT5_OUT_DIM = 4096 | |
| HALIDE_CTX_DIM = 512 | |
| VAE_REPO = "stabilityai/sd-vae-ft-mse" | |
| VAE_SCALE = 0.18215 | |
| class HalideConfig: | |
| latent_ch: int = 4 | |
| widths: list[int] = field(default_factory=lambda: [288, 832, 1664]) | |
| depths: list[int] = field(default_factory=lambda: [4, 6, 2]) | |
| steer_rank: list[int] = field(default_factory=lambda: [128, 256, 256]) | |
| expansion: int = 3 | |
| ctx_dim: int = 512 | |
| dim: int = 640 | |
| p_dim: int = 256 | |
| perceiver_depth: int = 4 | |
| prelude: int = 3 | |
| core: int = 3 | |
| coda: int = 2 | |
| loops: int = 4 | |
| grid: int = 24 | |
| n_global: int = 16 | |
| n_freq: int = 6 | |
| head_dim: int = 64 | |
| read_ch: int = 96 | |
| read_depth: int = 2 | |
| up_rank: int = 32 | |
| outer_mode: str = "flat" | |
| coord_res: bool = True | |
| rope: bool = True | |
| resolution_px: int = 768 | |
| vae_downsample: int = 8 | |
| vae_scale: float = VAE_SCALE | |
| class LayerNorm2d(nn.Module): | |
| def __init__(self, dim: int, affine: bool = True, eps: float = 1e-6): | |
| super().__init__() | |
| self.ln = nn.LayerNorm(dim, eps=eps, elementwise_affine=affine) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| return self.ln(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) | |
| class GRN(nn.Module): | |
| def __init__(self, dim: int, eps: float = 1e-6): | |
| super().__init__() | |
| self.gamma = nn.Parameter(torch.zeros(1, dim, 1, 1)) | |
| self.beta = nn.Parameter(torch.zeros(1, dim, 1, 1)) | |
| self.eps = eps | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| gx = torch.linalg.vector_norm(x.float(), dim=(2, 3), keepdim=True) | |
| nx = gx / (gx.mean(dim=1, keepdim=True) + self.eps) | |
| return self.gamma * (x * nx.to(x.dtype)) + self.beta + x | |
| class TimestepEmbedder(nn.Module): | |
| def __init__(self, dim: int, freq_dim: int = 256): | |
| super().__init__() | |
| self.freq_dim = freq_dim | |
| self.mlp = nn.Sequential(nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim)) | |
| def forward(self, t: torch.Tensor) -> torch.Tensor: | |
| half = self.freq_dim // 2 | |
| freqs = torch.exp(-math.log(10000.0) * torch.arange(half, device=t.device) / half) | |
| args = t[:, None].float() * freqs[None] * 1000.0 | |
| return self.mlp(torch.cat([torch.cos(args), torch.sin(args)], dim=-1)) | |
| def fourier_coords(h: int, w: int, n_freq: int, device) -> torch.Tensor: | |
| ys = (torch.arange(h, device=device, dtype=torch.float32) + 0.5) / h * 2 - 1 | |
| xs = (torch.arange(w, device=device, dtype=torch.float32) + 0.5) / w * 2 - 1 | |
| yy, xx = torch.meshgrid(ys, xs, indexing="ij") | |
| f = (2.0 ** torch.arange(n_freq, device=device, dtype=torch.float32)) * math.pi | |
| feats = [fn(c.reshape(-1, 1) * f) for c in (xx, yy) for fn in (torch.sin, torch.cos)] | |
| return torch.cat(feats, 1) | |
| def raw_coords(h: int, w: int, device, dtype=torch.float32) -> torch.Tensor: | |
| ys = (torch.arange(h, device=device, dtype=torch.float32) + 0.5) / h * 2 - 1 | |
| xs = (torch.arange(w, device=device, dtype=torch.float32) + 0.5) / w * 2 - 1 | |
| yy, xx = torch.meshgrid(ys, xs, indexing="ij") | |
| return torch.stack([xx, yy, (xx ** 2 + yy ** 2).sqrt()])[None].to(dtype) | |
| def rope_freqs(head_dim: int, device) -> torch.Tensor: | |
| n = head_dim // 4 | |
| return math.pi * 2.0 ** torch.linspace(-1.0, 3.0, n, device=device, dtype=torch.float32) | |
| def grid_xy(h: int, w: int, device) -> torch.Tensor: | |
| ys = (torch.arange(h, device=device, dtype=torch.float32) + 0.5) / h * 2 - 1 | |
| xs = (torch.arange(w, device=device, dtype=torch.float32) + 0.5) / w * 2 - 1 | |
| yy, xx = torch.meshgrid(ys, xs, indexing="ij") | |
| return torch.stack([xx.reshape(-1), yy.reshape(-1)], 1) | |
| def rope_angles(xy: torch.Tensor, head_dim: int, n_unrotated: int = 0) -> torch.Tensor: | |
| f = rope_freqs(head_dim, xy.device) | |
| ang = torch.cat([xy[:, :1] * f, xy[:, 1:] * f], 1) | |
| if n_unrotated: | |
| ang = torch.cat([ang, ang.new_zeros(n_unrotated, ang.shape[1])], 0) | |
| return ang | |
| def apply_rope(x: torch.Tensor, ang: torch.Tensor | None) -> torch.Tensor: | |
| if ang is None: | |
| return x | |
| with torch.autocast(x.device.type, enabled=False): | |
| xf = x.float() | |
| x1, x2 = xf[..., 0::2], xf[..., 1::2] | |
| c, s = ang.cos(), ang.sin() | |
| out = torch.stack([x1 * c - x2 * s, x1 * s + x2 * c], -1).flatten(-2) | |
| return out.to(x.dtype) | |
| def zero_last(m: nn.Module) -> nn.Module: | |
| last = [x for x in m.modules() if isinstance(x, (nn.Linear, nn.Conv2d))][-1] | |
| nn.init.zeros_(last.weight) | |
| if last.bias is not None: | |
| nn.init.zeros_(last.bias) | |
| return m | |
| def subsample(z: torch.Tensor, native: int) -> torch.Tensor: | |
| s = z.shape[-1] // native | |
| if z.shape[-1] == native: | |
| return z | |
| if s * native != z.shape[-1] or z.shape[-2] != z.shape[-1] or s != 2: | |
| raise ValueError(f"latent {tuple(z.shape[-2:])}: only {native}^2 and {2 * native}^2 supported") | |
| return z[..., ::2, ::2] | |
| def res_scale(z: torch.Tensor, native: int) -> torch.Tensor: | |
| return torch.full((z.shape[0],), math.log2(z.shape[-1] / native), device=z.device) | |
| class Attn(nn.Module): | |
| def __init__(self, dim: int, kv_dim: int, head_dim: int = 64): | |
| super().__init__() | |
| self.h, self.d = dim // head_dim, head_dim | |
| self.q = nn.Linear(dim, dim) | |
| self.kv = nn.Linear(kv_dim, 2 * dim) | |
| self.qn, self.kn = nn.RMSNorm(head_dim), nn.RMSNorm(head_dim) | |
| self.out = nn.Linear(dim, dim) | |
| def forward(self, x, kv, pad=None, ang_q=None, ang_k=None): | |
| B, N, _ = x.shape | |
| q = self.q(x).view(B, N, self.h, self.d).transpose(1, 2) | |
| k, v = self.kv(kv).view(B, kv.shape[1], 2, self.h, self.d).permute(2, 0, 3, 1, 4) | |
| q, k = apply_rope(self.qn(q), ang_q), apply_rope(self.kn(k), ang_k) | |
| m = None if pad is None else ~pad[:, None, None, :] | |
| o = F.scaled_dot_product_attention(q, k, v, attn_mask=m) | |
| return self.out(o.transpose(1, 2).reshape(B, N, -1)) | |
| class XBlock2(nn.Module): | |
| def __init__(self, dim: int, ctx_dim: int | None, self_attn: bool = True, mlp: int = 2, head_dim: int = 64): | |
| super().__init__() | |
| self.sa = Attn(dim, dim, head_dim) if self_attn else None | |
| self.n_sa = nn.LayerNorm(dim) if self_attn else None | |
| self.xa = Attn(dim, ctx_dim, head_dim) if ctx_dim else None | |
| self.n_xa = nn.LayerNorm(dim) if ctx_dim else None | |
| self.n_ctx = nn.LayerNorm(ctx_dim) if ctx_dim else None | |
| self.n_mlp = nn.LayerNorm(dim) | |
| self.mlp = nn.Sequential(nn.Linear(dim, mlp * dim), nn.GELU(), nn.Linear(mlp * dim, dim)) | |
| def forward(self, q, ctx=None, pad=None, ang_q=None, ang_ctx=None): | |
| if self.sa is not None: | |
| h = self.n_sa(q) | |
| q = q + self.sa(h, h, None, ang_q, ang_q) | |
| if self.xa is not None: | |
| c = self.n_ctx(ctx) | |
| q = q + self.xa(self.n_xa(q), c, pad, ang_q if ang_ctx is not None else None, ang_ctx) | |
| return q + self.mlp(self.n_mlp(q)) | |
| class ResEmbed(nn.Module): | |
| def __init__(self, dim: int, zero_init: bool = True): | |
| super().__init__() | |
| self.emb = TimestepEmbedder(dim) | |
| if zero_init: | |
| zero_last(self.emb) | |
| def forward(self, r): | |
| return self.emb(r) - self.emb(torch.zeros_like(r)) | |
| class FiLMConvNeXt(nn.Module): | |
| def __init__(self, ch: int, cond_dim: int, expansion: int = 2): | |
| super().__init__() | |
| self.dw = nn.Conv2d(ch, ch, 7, padding=3, groups=ch) | |
| self.norm = LayerNorm2d(ch, affine=False) | |
| self.film = nn.Linear(cond_dim, 3 * ch) | |
| self.pw1 = nn.Conv2d(ch, expansion * ch, 1) | |
| self.pw2 = nn.Conv2d(expansion * ch, ch, 1) | |
| nn.init.zeros_(self.film.weight) | |
| nn.init.zeros_(self.film.bias) | |
| def forward(self, x, cond): | |
| shift, scale, gate = self.film(cond)[:, :, None, None].chunk(3, 1) | |
| h = self.norm(self.dw(x)) * (1 + scale) + shift | |
| return x + (1 + gate) * self.pw2(F.gelu(self.pw1(h))) | |
| class ConvRead(nn.Module): | |
| def __init__(self, latent_ch: int, out_dim: int, cond_dim: int, ch: int = 96, depth: int = 2): | |
| super().__init__() | |
| self.stem = nn.Conv2d(latent_ch + N_COORD, ch, 3, padding=1) | |
| self.blocks = nn.ModuleList(FiLMConvNeXt(ch, cond_dim) for _ in range(depth)) | |
| self.norm = LayerNorm2d(ch) | |
| self.proj = zero_last(nn.Linear(ch, out_dim)) | |
| def forward(self, z_hr, coords_hr, cond, grid_hw): | |
| h = self.stem(torch.cat([z_hr, coords_hr.expand(z_hr.shape[0], -1, -1, -1).to(z_hr.dtype)], 1)) | |
| for b in self.blocks: | |
| h = b(h, cond) | |
| h = F.adaptive_avg_pool2d(self.norm(h), grid_hw) | |
| return self.proj(h.flatten(2).transpose(1, 2)) | |
| class SpatialModBlock(nn.Module): | |
| def __init__(self, dim: int, d_mod: int, expansion: int = 3): | |
| super().__init__() | |
| self.dwconv = nn.Conv2d(dim, dim, 7, padding=3, groups=dim) | |
| self.norm = LayerNorm2d(dim, affine=False) | |
| self.pw1 = nn.Conv2d(dim, expansion * dim, 1) | |
| self.act = nn.GELU() | |
| self.grn = GRN(expansion * dim) | |
| self.pw2 = nn.Conv2d(expansion * dim, dim, 1) | |
| self.mod = nn.Conv2d(d_mod, 3 * dim, 1) | |
| nn.init.zeros_(self.mod.weight) | |
| nn.init.zeros_(self.mod.bias) | |
| def forward(self, x: torch.Tensor, m: torch.Tensor) -> torch.Tensor: | |
| mod = self.mod(m) | |
| if mod.shape[-2:] != x.shape[-2:]: | |
| mod = F.interpolate(mod, size=x.shape[-2:], mode="bilinear", align_corners=False) | |
| shift, scale, gate = mod.chunk(3, dim=1) | |
| h = self.norm(self.dwconv(x)) * (1 + scale) + shift | |
| h = self.pw2(self.grn(self.act(self.pw1(h)))) | |
| return x + gate * h | |
| class CoordIn(nn.Module): | |
| def __init__(self, ch: int, res_channel: bool = False): | |
| super().__init__() | |
| self.res_channel = res_channel | |
| self.proj = zero_last(nn.Conv2d(N_COORD + int(res_channel), ch, 1)) | |
| def forward(self, x, r: float = 0.0): | |
| c = raw_coords(x.shape[-2], x.shape[-1], x.device, x.dtype) | |
| if self.res_channel: | |
| c = torch.cat([c, torch.full_like(c[:, :1], float(r))], 1) | |
| return x + self.proj(c) | |
| class PlanUp(nn.Module): | |
| def __init__(self, dim: int, rank: int = 32, kernel: int = 5, latent_ch: int = 4): | |
| super().__init__() | |
| self.dw = nn.Conv2d(dim, dim, kernel, padding=kernel // 2, groups=dim) | |
| self.dw2 = nn.Conv2d(dim, dim, kernel, padding=kernel // 2, groups=dim) | |
| self.down = nn.Conv2d(dim, rank, 1) | |
| self.coord = nn.Conv2d(N_COORD, rank, 1) | |
| self.guide = nn.Conv2d(latent_ch, rank, 3, padding=1) | |
| self.up = zero_last(nn.Conv2d(rank, dim, 1)) | |
| def forward(self, m, z): | |
| size = z.shape[-2:] | |
| b = F.interpolate(m, size=size, mode="bilinear", align_corners=False) | |
| h = (self.down(self.dw2(F.gelu(self.dw(b)))) | |
| + self.coord(raw_coords(*size, m.device, b.dtype)) | |
| + self.guide(z.to(b.dtype))) | |
| return b + self.up(F.gelu(h)) | |
| def count_features(n: torch.Tensor) -> torch.Tensor: | |
| nf = n.float() | |
| th = math.pi * torch.log2(nf.clamp(1, 16)) / 4 | |
| parts = [w * f(k * th) for k, w in zip(COUNT_K, COUNT_W) for f in (torch.cos, torch.sin)] | |
| parts += [torch.log2(nf.clamp(min=1)) / 4, (nf > 16).float()] | |
| return torch.stack(parts, -1) | |
| class CountCode(nn.Module): | |
| def __init__(self, ctx_dim: int): | |
| super().__init__() | |
| self.proj = nn.Linear(10, ctx_dim) | |
| self.gate = nn.Parameter(torch.zeros(ctx_dim)) | |
| def forward(self, ctx, counts=None): | |
| if counts is None: | |
| return ctx | |
| counts = counts.to(ctx.device) | |
| on = (counts > 0).to(ctx.dtype)[..., None] | |
| code = self.proj(count_features(counts).to(ctx.dtype)) | |
| return ctx + on * self.gate.to(ctx.dtype) * (code - ctx) | |
| class HalideThinker(nn.Module): | |
| def __init__(self, cfg: HalideConfig): | |
| super().__init__() | |
| self.grid, self.n_global, self.n_freq, self.rope = cfg.grid, cfg.n_global, cfg.n_freq, cfg.rope | |
| self.loops = cfg.loops | |
| self.native = 2 * cfg.grid | |
| self.head_dim = cfg.head_dim | |
| pos = 4 * cfg.n_freq | |
| self.queries = nn.Parameter(torch.randn(cfg.grid * cfg.grid + cfg.n_global, cfg.p_dim) * 0.02) | |
| self.q_pos = nn.Linear(pos, cfg.p_dim) | |
| self.t1 = TimestepEmbedder(cfg.p_dim) | |
| self.t2 = TimestepEmbedder(cfg.dim) | |
| self.in_latent = nn.Linear(cfg.latent_ch * 4 + pos, cfg.p_dim) | |
| self.perceiver = nn.ModuleList( | |
| XBlock2(cfg.p_dim, cfg.p_dim, self_attn=False, head_dim=cfg.head_dim) | |
| for _ in range(cfg.perceiver_depth) | |
| ) | |
| self.lift = nn.Linear(cfg.p_dim, cfg.dim) | |
| self.prelude = nn.ModuleList( | |
| XBlock2(cfg.dim, cfg.ctx_dim, head_dim=cfg.head_dim) for _ in range(cfg.prelude) | |
| ) | |
| self.core = nn.ModuleList( | |
| XBlock2(cfg.dim, cfg.ctx_dim, head_dim=cfg.head_dim) for _ in range(cfg.core) | |
| ) | |
| self.coda = nn.ModuleList( | |
| XBlock2(cfg.dim, cfg.ctx_dim, head_dim=cfg.head_dim) for _ in range(cfg.coda) | |
| ) | |
| self.adapter = nn.Linear(2 * cfg.dim, cfg.dim) | |
| self.norm = nn.LayerNorm(cfg.dim) | |
| self.mr_taps = zero_last(nn.Linear(cfg.latent_ch * 16, cfg.p_dim)) | |
| self.mr_read = ConvRead(cfg.latent_ch, cfg.p_dim, cond_dim=cfg.p_dim, | |
| ch=cfg.read_ch, depth=cfg.read_depth) | |
| self.mr_res_q = ResEmbed(cfg.p_dim) | |
| self.mr_res_s = ResEmbed(cfg.dim) | |
| self.mr_res_c = ResEmbed(cfg.p_dim, zero_init=False) | |
| def read(self, z, t_emb, r): | |
| B = z.shape[0] | |
| zb = subsample(z, self.native) | |
| hb, wb = zb.shape[-2:] | |
| pos = fourier_coords(hb // 2, wb // 2, self.n_freq, z.device)[None].expand(B, -1, -1) | |
| lat = F.pixel_unshuffle(zb, 2).flatten(2).transpose(1, 2) | |
| kv = self.in_latent(torch.cat([lat, pos], -1)) | |
| coords = raw_coords(*z.shape[-2:], z.device) | |
| if z.shape[-1] == 2 * self.native: | |
| z_hr, c_hr = z, coords | |
| else: | |
| z_hr = F.interpolate(z, scale_factor=2, mode="nearest") | |
| c_hr = F.interpolate(coords, scale_factor=2, mode="nearest") | |
| taps = F.pixel_unshuffle(z_hr, 4).flatten(2).transpose(1, 2) | |
| cond = t_emb + self.mr_res_c(r) | |
| return kv + self.mr_taps(taps) + self.mr_read(z_hr, c_hr, cond, (hb // 2, wb // 2)), (hb, wb) | |
| def forward(self, z, t, ctx, mask, loops: int | None = None, mask_all: bool = False): | |
| B = z.shape[0] | |
| g, dev = self.grid, z.device | |
| loops = self.loops if loops is None else loops | |
| r = res_scale(z, self.native) | |
| t1 = self.t1(t) | |
| kv, (hb, wb) = self.read(z, t1, r) | |
| q = self.queries[None].expand(B, -1, -1).clone() | |
| q[:, :g * g] = q[:, :g * g] + self.q_pos(fourier_coords(g, g, self.n_freq, dev)[None].expand(B, -1, -1)) | |
| q = q + t1[:, None] + self.mr_res_q(r)[:, None] | |
| ang_pq = ang_pk = ang_q = None | |
| if self.rope: | |
| ang_pq = rope_angles(grid_xy(g, g, dev), self.head_dim, self.n_global) | |
| ang_pk = rope_angles(grid_xy(hb // 2, wb // 2, dev), self.head_dim) | |
| ang_q = ang_pq | |
| for blk in self.perceiver: | |
| q = blk(q, kv, None, ang_pq, ang_pk) | |
| q = self.lift(q) + self.t2(t)[:, None] + self.mr_res_s(r)[:, None] | |
| pad = None if mask_all else ~mask.bool() | |
| for blk in self.prelude: | |
| q = blk(q, ctx, pad, ang_q) | |
| e, s = q, q | |
| for _ in range(loops): | |
| s = self.adapter(torch.cat([s, e], -1)) | |
| for blk in self.core: | |
| s = blk(s, ctx, pad, ang_q) | |
| for blk in self.coda: | |
| s = blk(s, ctx, pad, ang_q) | |
| out = self.norm(s) | |
| return out[:, :g * g].transpose(1, 2).reshape(B, -1, g, g) | |
| class HalideGenerator(nn.Module): | |
| def __init__(self, cfg: HalideConfig | None = None): | |
| super().__init__() | |
| cfg = cfg or HalideConfig() | |
| self.cfg = cfg | |
| self.native = 2 * cfg.grid | |
| self.loops = cfg.loops | |
| self.thinker = HalideThinker(cfg) | |
| self.mr_count = CountCode(cfg.ctx_dim) | |
| w0, w1, w2 = cfg.widths | |
| d0, d1, d2 = cfg.depths | |
| sr = cfg.steer_rank | |
| self.steer_in = nn.ModuleDict({ | |
| lvl: nn.Conv2d(cfg.dim, r, 1) for lvl, r in zip(("l0", "l1", "l2"), sr) if r | |
| }) | |
| d_in = [r or cfg.dim for r in sr] | |
| self.stem = nn.Conv2d(cfg.latent_ch, w0, 3, padding=1) | |
| mk = lambda w, dm, n: nn.ModuleList(SpatialModBlock(w, dm, cfg.expansion) for _ in range(n)) | |
| self.enc0 = mk(w0, d_in[0], d0) | |
| self.enc1 = mk(w1, d_in[1], d1) | |
| self.mid = mk(w2, d_in[2], 2 * d2) | |
| self.dec1 = mk(w1, d_in[1], d1) | |
| self.dec0 = mk(w0, d_in[0], d0) | |
| self.down0 = nn.Sequential(LayerNorm2d(w0), nn.Conv2d(w0, w1, 2, stride=2)) | |
| self.down1 = nn.Sequential(LayerNorm2d(w1), nn.Conv2d(w1, w2, 2, stride=2)) | |
| self.up1 = nn.ConvTranspose2d(w2, w1, 2, stride=2) | |
| self.up0 = nn.ConvTranspose2d(w1, w0, 2, stride=2) | |
| self.final_norm = LayerNorm2d(w0, affine=False) | |
| self.final_mod = nn.Conv2d(cfg.dim, 2 * w0, 1) | |
| self.final_conv = nn.Conv2d(w0, cfg.latent_ch, 3, padding=1) | |
| self.plan_up = PlanUp(cfg.dim, cfg.up_rank, 5, cfg.latent_ch) | |
| self.coord = nn.ModuleDict({ | |
| k: CoordIn(w, cfg.coord_res) | |
| for k, w in (("enc0", w0), ("enc1", w1), ("mid", w2), ("dec1", w1), ("dec0", w0)) | |
| }) | |
| def _run(self, blocks, x, s): | |
| for blk in blocks: | |
| x = blk(x, s) | |
| return x | |
| def _steer(self, lvl, m, x, m_up=None): | |
| if m_up is not None and m_up.shape[-2:] == x.shape[-2:]: | |
| m = m_up | |
| s = self.steer_in[lvl](m) if lvl in self.steer_in else m | |
| if s.shape[-1] > x.shape[-1]: | |
| return F.adaptive_avg_pool2d(s, x.shape[-2:]) | |
| if s.shape[-1] < x.shape[-1]: | |
| return F.interpolate(s, size=x.shape[-2:], mode="bilinear", align_corners=False) | |
| return s | |
| def forward(self, z, t, ctx, mask, loops: int | None = None, counts=None, mask_all: bool = False): | |
| ctx = self.mr_count(ctx.float(), counts) | |
| m = self.thinker(z, t, ctx, mask, self.loops if loops is None else loops, mask_all=mask_all) | |
| r = math.log2(z.shape[-1] / self.native) | |
| m_up = self.plan_up(m, z) if m.shape[-1] < z.shape[-1] else None | |
| h = self.stem(z) | |
| c = self.coord | |
| x0 = self._run(self.enc0, c["enc0"](h, r), self._steer("l0", m, h, m_up)) | |
| x = self.down0(x0) | |
| x1 = self._run(self.enc1, c["enc1"](x, r), self._steer("l1", m, x, m_up)) | |
| x = self.down1(x1) | |
| x = self._run(self.mid, c["mid"](x, r), self._steer("l2", m, x, m_up)) | |
| x = self.up1(x) + x1 | |
| x = self._run(self.dec1, c["dec1"](x, r), self._steer("l1", m, x, m_up)) | |
| x = self.up0(x) + x0 | |
| feat = self._run(self.dec0, c["dec0"](x, r), self._steer("l0", m, x, m_up)) | |
| fm = self.final_mod(m_up if m_up is not None else m) | |
| if fm.shape[-2:] != feat.shape[-2:]: | |
| fm = F.interpolate(fm, size=feat.shape[-2:], mode="bilinear", align_corners=False) | |
| shift, scale = fm.chunk(2, dim=1) | |
| return self.final_conv(self.final_norm(feat) * (1 + scale) + shift) | |
| class DistillT5TextEncoder: | |
| """LifuWang/DistillT5 (with explicit key remap) + google-t5/t5-base tokenizer + Halide ctx_proj.""" | |
| def __init__(self, device: str = "cuda", max_len: int = 512): | |
| self.device = device | |
| self.max_len = max_len | |
| self.tokenizer = None | |
| self.encoder = None | |
| self.final_projection = None | |
| self.ctx_proj = nn.Linear(DISTILLT5_OUT_DIM, HALIDE_CTX_DIM) | |
| def load(self): | |
| from huggingface_hub import hf_hub_download | |
| from safetensors import safe_open | |
| from transformers import AutoTokenizer, T5EncoderModel | |
| self.tokenizer = AutoTokenizer.from_pretrained(DISTILLT5_TOKENIZER_REPO) | |
| self.encoder = T5EncoderModel.from_pretrained(DISTILLT5_REPO, dtype=torch.float32).to(self.device) | |
| path = hf_hub_download(DISTILLT5_REPO, "model.safetensors") | |
| mapped = {} | |
| with safe_open(path, framework="pt") as f: | |
| for k in f.keys(): | |
| if k.startswith("encoder.encoder."): | |
| mapped[k[len("encoder."):]] = f.get_tensor(k) | |
| elif k == "encoder.shared.weight": | |
| mapped["shared.weight"] = f.get_tensor(k) | |
| mapped["encoder.embed_tokens.weight"] = f.get_tensor(k) | |
| missing, unexpected = self.encoder.load_state_dict(mapped, strict=False) | |
| if missing or unexpected: | |
| raise RuntimeError(f"DistillT5 remap incomplete: missing={missing} unexpected={unexpected}") | |
| self.final_projection = nn.Sequential( | |
| nn.Linear(DISTILLT5_D_MODEL, DISTILLT5_OUT_DIM, bias=False), | |
| nn.ReLU(), | |
| nn.Dropout(0.1), | |
| nn.Linear(DISTILLT5_OUT_DIM, DISTILLT5_OUT_DIM, bias=False), | |
| ) | |
| with safe_open(path, framework="pt") as f: | |
| self.final_projection[0].weight.data.copy_(f.get_tensor("final_projection.0.weight")) | |
| self.final_projection[3].weight.data.copy_(f.get_tensor("final_projection.3.weight")) | |
| self.final_projection = self.final_projection.to(self.device).eval() | |
| self.ctx_proj = self.ctx_proj.to(self.device).eval() | |
| self.encoder.eval() | |
| return self | |
| def encode_texts(self, texts: list[str]): | |
| t = self.tokenizer(texts, padding="longest", truncation=True, max_length=self.max_len, return_tensors="pt") | |
| ids, mask = t["input_ids"].to(self.device), t["attention_mask"].to(self.device) | |
| with torch.autocast(self.device, dtype=torch.bfloat16, enabled=self.device == "cuda"): | |
| hidden = self.encoder(input_ids=ids, attention_mask=mask).last_hidden_state | |
| hidden = self.final_projection(hidden) | |
| hidden = self.ctx_proj(hidden) | |
| return hidden.float(), mask | |
| def shift_t(t: float, shift: float) -> float: | |
| if shift == 1.0: | |
| return t | |
| s = 1.0 - t | |
| return 1.0 - shift * s / (1.0 + (shift - 1.0) * s) | |
| def sample_halide(model: HalideGenerator, text_enc: DistillT5TextEncoder, vae, | |
| prompts: list[str], steps: int = 50, cfg: float = 4.0, | |
| shift: float = 2.0, resolution: int = 768, seed: int = 42, | |
| device: str = "cuda"): | |
| """Euler flow-matching sampler from t=0 (noise) -> t=1 (data) with CFG.""" | |
| from PIL import Image | |
| import numpy as np | |
| B = len(prompts) | |
| H = W = resolution // 8 | |
| gen = torch.Generator(device=device).manual_seed(seed) | |
| z = torch.randn((B, 4, H, W), generator=gen, device=device, dtype=torch.float32) | |
| ctx_c, mask_c = text_enc.encode_texts(prompts) | |
| ctx_u, mask_u = text_enc.encode_texts([""] * B) | |
| # Pad cond & uncond to same length for single batched CFG pass | |
| L = max(ctx_c.shape[1], ctx_u.shape[1]) | |
| if ctx_c.shape[1] < L: | |
| ctx_c = F.pad(ctx_c, (0, 0, 0, L - ctx_c.shape[1])) | |
| mask_c = F.pad(mask_c, (0, L - mask_c.shape[1])) | |
| if ctx_u.shape[1] < L: | |
| ctx_u = F.pad(ctx_u, (0, 0, 0, L - ctx_u.shape[1])) | |
| mask_u = F.pad(mask_u, (0, L - mask_u.shape[1])) | |
| ctx_both = torch.cat([ctx_u, ctx_c], dim=0) | |
| mask_both = torch.cat([mask_u, mask_c], dim=0) | |
| ts = [shift_t(i / steps, shift) for i in range(steps + 1)] | |
| for i in range(steps): | |
| t_cur, t_nxt = ts[i], ts[i + 1] | |
| dt = t_nxt - t_cur | |
| t_vec = torch.full((2 * B,), t_cur, device=device, dtype=torch.float32) | |
| z_in = torch.cat([z, z], dim=0) | |
| with torch.autocast(device, dtype=torch.bfloat16, enabled=device == "cuda"): | |
| v_both = model(z_in, t_vec, ctx_both, mask_both) | |
| vu, vc = v_both.float().chunk(2, dim=0) | |
| v = vu + cfg * (vc - vu) | |
| z = z + dt * v | |
| images = [] | |
| for b in range(B): | |
| lat = (z[b:b + 1] / VAE_SCALE).to(dtype=vae.dtype) | |
| img = vae.decode(lat).sample.float().clamp(-1, 1) | |
| arr = ((img[0].permute(1, 2, 0).cpu().numpy() + 1.0) * 127.5).round().clip(0, 255).astype(np.uint8) | |
| images.append(Image.fromarray(arr)) | |
| return images | |