Lesson 4 of 6 · 2 min
Draw from a word
Classifier-free guidance compares the guess with and without the prompt, and pushes further towards the prompt.
# run locally: sample.py
import sys, torch, torchvision as tv
from train import UNet, T, alpha, beta, keep, device
NAMES = ["t-shirt", "trouser", "pullover", "dress", "coat", "sandal", "shirt", "sneaker", "bag", "boot"]
word = NAMES.index(sys.argv[1] if len(sys.argv) > 1 else "sneaker")
net = UNet().to(device).eval()
net.load_state_dict(torch.load("diffusion.pt", map_location=device))
x = torch.randn(16, 1, 28, 28, device=device)
y, none = torch.full((16,), word, device=device), torch.full((16,), 10, device=device)
with torch.no_grad():
for t in reversed(range(T)):
tt = torch.full((16,), t, device=device)
base = net(x, tt, none)
eps = base + 3.0 * (net(x, tt, y) - base)
x = (x - beta[t] / (1 - keep[t]).sqrt() * eps) / alpha[t].sqrt()
if t:
x += beta[t].sqrt() * torch.randn_like(x)
tv.utils.save_image((x.clamp(-1, 1) + 1) / 2, "out.png", nrow=4)