"""From-scratch text-conditioned image model (no pretrained weights anywhere): a small text transformer + a 64x64 pixel-space U-Net with cross-attention, trained as a rectified-flow (velocity) model. Written 2026-11-19 for the HP (GTX 1660 Ti 6 GB) five-day image-pretraining experiment.""" import math, torch, torch.nn as nn, torch.nn.functional as F def tsin(t, dim): # t in [0,1] -> sinusoidal embedding half = dim // 2; f = torch.exp(-math.log(10000) * torch.arange(half, device=t.device, dtype=torch.float32) / half) a = (t.float() * 1000)[:, None] * f[None]; return torch.cat([a.sin(), a.cos()], -1) class TextEnc(nn.Module): def __init__(s, vocab, dim=384, layers=4, heads=6, maxlen=24): super().__init__(); s.emb = nn.Embedding(vocab, dim); s.pos = nn.Parameter(torch.zeros(maxlen, dim)); nn.init.normal_(s.pos, std=0.02) L = nn.TransformerEncoderLayer(dim, heads, dim * 4, 0.0, activation="gelu", batch_first=True, norm_first=True); s.enc = nn.TransformerEncoder(L, layers, enable_nested_tensor=False); s.norm = nn.LayerNorm(dim) def forward(s, ids, pad): # ids [B,L], pad bool [B,L] True = padding x = s.emb(ids) + s.pos[: ids.shape[1]]; return s.norm(s.enc(x, src_key_padding_mask=pad)) class Res(nn.Module): def __init__(s, cin, cout, temb, drop=0.0): super().__init__(); s.n1 = nn.GroupNorm(32, cin); s.c1 = nn.Conv2d(cin, cout, 3, padding=1); s.t = nn.Linear(temb, cout * 2) s.n2 = nn.GroupNorm(32, cout); s.d = nn.Dropout(drop); s.c2 = nn.Conv2d(cout, cout, 3, padding=1); nn.init.zeros_(s.c2.weight); nn.init.zeros_(s.c2.bias) s.sk = nn.Conv2d(cin, cout, 1) if cin != cout else nn.Identity() def forward(s, x, te): h = s.c1(F.silu(s.n1(x))); sc, sh = s.t(F.silu(te))[:, :, None, None].chunk(2, 1) h = s.n2(h) * (1 + sc) + sh; h = s.c2(s.d(F.silu(h))); return s.sk(x) + h class Attn(nn.Module): # self-attention + cross-attention to text + feed-forward def __init__(s, c, ctx, hd=64): super().__init__(); s.h = c // hd; s.n1 = nn.GroupNorm(32, c); s.qkv = nn.Linear(c, c * 3); s.o1 = nn.Linear(c, c) s.n2 = nn.GroupNorm(32, c); s.q2 = nn.Linear(c, c); s.kv2 = nn.Linear(ctx, c * 2); s.o2 = nn.Linear(c, c) s.n3 = nn.LayerNorm(c); s.ff = nn.Sequential(nn.Linear(c, c * 4), nn.GELU(), nn.Linear(c * 4, c)) for m in (s.o1, s.o2, s.ff[2]): nn.init.zeros_(m.weight); nn.init.zeros_(m.bias) def forward(s, x, ctx, cmask): B, C, H, W = x.shape; sp = lambda t: t.view(B, -1, s.h, C // s.h).transpose(1, 2) t = s.n1(x).flatten(2).transpose(1, 2); q, k, v = s.qkv(t).chunk(3, -1); a = F.scaled_dot_product_attention(sp(q), sp(k), sp(v)) x1 = x.flatten(2).transpose(1, 2) + s.o1(a.transpose(1, 2).reshape(B, -1, C)) t2 = s.n2(x1.transpose(1, 2).view(B, C, H, W)).flatten(2).transpose(1, 2); q = s.q2(t2); k, v = s.kv2(ctx).chunk(2, -1) a2 = F.scaled_dot_product_attention(sp(q), sp(k), sp(v), attn_mask=cmask[:, None, None, :]) x2 = x1 + s.o2(a2.transpose(1, 2).reshape(B, -1, C)); x3 = x2 + s.ff(s.n3(x2)); return x3.transpose(1, 2).reshape(B, C, H, W) class UNet(nn.Module): def __init__(s, ch=128, mult=(1, 2, 3, 4), nres=2, attn_levels=(2, 3), ctx=384, drop=0.0): super().__init__(); s.ch = ch; te = ch * 4; s.temb = nn.Sequential(nn.Linear(ch, te), nn.SiLU(), nn.Linear(te, te)); s.inc = nn.Conv2d(3, ch, 3, padding=1) s.down = nn.ModuleList(); chans = [ch]; c = ch for i, m in enumerate(mult): for _ in range(nres): s.down.append(nn.ModuleList([Res(c, ch * m, te, drop), Attn(ch * m, ctx) if i in attn_levels else nn.Identity()])); c = ch * m; chans.append(c) if i < len(mult) - 1: s.down.append(nn.Conv2d(c, c, 3, stride=2, padding=1)); chans.append(c) s.mid = nn.ModuleList([Res(c, c, te, drop), Attn(c, ctx), Res(c, c, te, drop)]); s.up = nn.ModuleList() for i, m in reversed(list(enumerate(mult))): for j in range(nres + 1): s.up.append(nn.ModuleList([Res(c + chans.pop(), ch * m, te, drop), Attn(ch * m, ctx) if i in attn_levels else nn.Identity(), nn.Upsample(scale_factor=2, mode="nearest") if (i > 0 and j == nres) else nn.Identity()])); c = ch * m s.out = nn.Sequential(nn.GroupNorm(32, c), nn.SiLU(), nn.Conv2d(c, 3, 3, padding=1)); nn.init.zeros_(s.out[2].weight); nn.init.zeros_(s.out[2].bias) def forward(s, x, t, ctx, cmask): te = s.temb(tsin(t, s.ch)); h = s.inc(x); hs = [h] for b in s.down: if isinstance(b, nn.ModuleList): h = b[0](h, te); h = b[1](h, ctx, cmask) if not isinstance(b[1], nn.Identity) else h else: h = b(h) hs.append(h) h = s.mid[0](h, te); h = s.mid[1](h, ctx, cmask); h = s.mid[2](h, te) for r, a, u in s.up: h = r(torch.cat([h, hs.pop()], 1), te); h = a(h, ctx, cmask) if not isinstance(a, nn.Identity) else h; h = u(h) return s.out(h) class Gen(nn.Module): def __init__(s, vocab, ch=128, mult=(1, 2, 3, 4), nres=2, tdim=384): super().__init__(); s.text = TextEnc(vocab, tdim); s.unet = UNet(ch, mult, nres, ctx=tdim) def forward(s, x, t, ids, pad): ctx = s.text(ids, pad); return s.unet(x, t, ctx, ~pad) # a "null" prompt is [PAD]+padding with position 0 left unmasked, so no row is ever fully masked def nparams(m): return sum(p.numel() for p in m.parameters())