File size: 25,346 Bytes
8b2c7f9 66f440c 8b2c7f9 66f440c 8b2c7f9 66f440c 8b2c7f9 66f440c 8b2c7f9 66f440c 8b2c7f9 66f440c 8b2c7f9 66f440c 8b2c7f9 66f440c 8b2c7f9 66f440c 8b2c7f9 66f440c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 | """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
@dataclass
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
@torch.no_grad()
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)
@torch.no_grad()
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
|