smalt-medium / smalt /sampler.py
nyxia's picture
smalt-medium v1
20de354 verified
Raw History Blame Contribute Delete
4.52 kB
"""Parallel decoding for smalt (MIT): a blank 16x16 canvas becomes a sprite in a few steps.
Every step runs one batched forward (conditional + unconditional) for classifier-free guidance, samples a colour for
every masked pixel, ranks the masked pixels by log-confidence plus annealed Gumbel noise and commits enough of them to
follow a cosine schedule. An uncertain pixel is committed only if it is the best-scored masked pixel in its 3x3
neighbourhood, which keeps speckles away. The guided distribution feeds the next step. Inpainting: pass a canvas and a
keep mask; kept pixels never change.
`sample_steps` yields the state after every step (used for the live unmasking view); `generate` returns the result.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
import torch
import torch.nn.functional as F
@dataclass
class Step:
index: int # 0-based decoding step
total: int
tokens: torch.Tensor # (B, N) long, [MASK] where still undecided
preview: torch.Tensor # (B, N) long, the model's current best guess everywhere
confidence: torch.Tensor # (B, N) float in [0, 1], probability of the committed colour (0 where undecided)
@torch.no_grad()
def sample_steps(model, text, steps=16, guidance=3.0, temperature=0.7, top_p=1.0, gumbel=1.0, conf_free=0.9,
n_used=None, canvas=None, keep=None, generator=None):
"""text (B, L) long token ids. canvas (B, N) long + keep (B, N) bool for inpainting. Yields Step."""
dev = text.device
b = text.shape[0]
g = model.cfg.grid
n = g * g
k = model.cfg.n_colors
mask_id = model.mask_id
x = torch.full((b, n), mask_id, dtype=torch.long, device=dev)
if canvas is not None:
x = torch.where(keep, canvas.long(), x)
prev = torch.zeros(b, n, k, device=dev)
uncond = torch.zeros_like(text)
conf = torch.where(x != mask_id, 1.0, 0.0)
bad = None
if n_used is not None and n_used < k:
bad = torch.zeros(k, dtype=torch.bool, device=dev)
bad[n_used:] = True
def guided(xc, prevc):
ratio = (xc == mask_id).float().mean(1)
lo = model(torch.cat([xc, xc]), torch.cat([text, uncond]), torch.cat([ratio, ratio]),
torch.cat([prevc, prevc])).float()
lc, lu = lo.chunk(2)
lg = lu + guidance * (lc - lu)
if bad is not None:
lg = lg.masked_fill(bad, float("-inf"))
return lg
def draw(lg):
lt = lg / max(temperature, 1e-6)
if top_p < 1.0:
sp, si = lt.softmax(-1).sort(-1, descending=True)
drop = sp.cumsum(-1) - sp > top_p
lt = lt.masked_fill(torch.zeros_like(drop).scatter(-1, si, drop), float("-inf"))
s = torch.multinomial(lt.softmax(-1).view(-1, k), 1, generator=generator).view(b, n)
logp = lg.log_softmax(-1).gather(-1, s[..., None]).squeeze(-1)
return s, logp
for step in range(steps):
masked = x == mask_id
n_masked = masked.sum(1)
if int(n_masked.max()) == 0:
break
lg = guided(x, prev)
sampled, logp = draw(lg)
last = step == steps - 1
target = math.floor(n * math.cos(math.pi / 2 * (step + 1) / steps)) if not last else 0
n_commit = (n_masked - target).clamp(min=1)
gs = gumbel * (1 - (step + 1) / steps)
noise = -torch.log(-torch.log(torch.rand(b, n, device=dev, generator=generator).clamp(1e-9, 1 - 1e-9)))
score = (logp + gs * noise).masked_fill(~masked, float("-inf"))
if last:
eligible = masked
else:
local = F.max_pool2d(score.view(b, 1, g, g), 3, 1, 1).view(b, n)
eligible = masked & ((logp.exp() >= conf_free) | (score >= local))
se = score.masked_fill(~eligible, float("-inf"))
order = se.argsort(1, descending=True)
rank = torch.empty_like(order).scatter_(1, order, torch.arange(n, device=dev).expand(b, n))
commit = eligible & (rank < n_commit[:, None])
x = torch.where(commit, sampled, x)
conf = torch.where(commit, logp.exp(), conf)
prev = lg.softmax(-1)
preview = torch.where(x == mask_id, lg.argmax(-1), x)
yield Step(step, steps, x.clone(), preview, conf.clone())
@torch.no_grad()
def generate(model, text, **kw):
"""Run every step and return the final tokens (B, N)."""
last = None
for last in sample_steps(model, text, **kw):
pass
return last.tokens if last is not None else kw["canvas"]