Cpu trainer open source

I’ve found a code to train from scratch cpu a model but that isn’t the best i hope someone can upgrade it the code (the vae nedd to train minimum 20 epochs and you can up the dataset images to 833 for better images,the training of the unet(Vae reconstruction image,Unet génération image )is the most slower step):

I think it’s can work :

```# Au besoin, décommentez :

# %pip -q install datasets pillow matplotlib

import re, math, random, torch

import torch.nn as nn

import torch.nn.functional as F

import matplotlib.pyplot as plt

from datasets import load_dataset

from PIL import Image

# Réglages

torch.set_num_threads(min(4, torch.get_num_threads()))

torch.manual_seed(42)

random.seed(42)

device = torch.device(“cpu”)

SIZE = 64

LIMIT = 500

BATCH = 4

VAE_EPOCHS = 20

DIFF_STEPS = 2000

T = 100

MAX_TOKENS = 24

LR = 1e-3

# Chargement des images et légendes

ds = load_dataset(“diffusers/pokemon-gpt4-captions”, split=“train”)

images, captions = [], []

for row in ds:

im = row.get("image")

caption = row.get("text") or row.get("caption") or row.get("prompt")

if im is None or not caption:

    continue

if not isinstance(im, Image.Image):

    im = Image.fromarray(im)

im = im.convert("RGB").resize((SIZE, SIZE))

arr = torch.tensor(bytearray(im.tobytes()), dtype=torch.uint8)

image = arr.reshape(SIZE, SIZE, 3).permute(2, 0, 1).float() / 127.5 - 1

images.append(image)

captions.append(str(caption))

if len(images) >= LIMIT:

    break

if not images:

raise ValueError("Aucune image/légende trouvée dans le dataset.")

images = torch.stack(images)

print(f"Images : {len(images)} — forme : {tuple(images.shape)}")

# Vocabulaire construit à partir des légendes

words = [re.findall(r"\w+", s.lower())[:MAX_TOKENS] for s in captions]

vocab = {“”: 0, “”: 1}

for sentence in words:

for word in sentence:

    if word not in vocab:

        vocab\[word\] = len(vocab)

tokens = torch.zeros(len(words), MAX_TOKENS, dtype=torch.long)

for i, sentence in enumerate(words):

ids = \[vocab.get(w, 1) for w in sentence\]

if ids:

    tokens\[i, :len(ids)\] = torch.tensor(ids)

# VAE : 64x64 → latent 16x16 → 64x64

class VAE(nn.Module):

def \__init_\_(self):

    super().\__init_\_()

    self.enc = nn.Sequential(

        nn.Conv2d(3, 32, 4, 2, 1), nn.SiLU(),

        nn.Conv2d(32, 64, 4, 2, 1), nn.SiLU(),

        nn.Conv2d(64, 128, 3, padding=1), nn.SiLU()

    )

    self.mu = nn.Conv2d(128, 4, 3, padding=1)

    self.logvar = nn.Conv2d(128, 4, 3, padding=1)

    self.dec = nn.Sequential(

        nn.Conv2d(4, 128, 3, padding=1), nn.SiLU(),

        nn.ConvTranspose2d(128, 64, 4, 2, 1), nn.SiLU(),

        nn.ConvTranspose2d(64, 32, 4, 2, 1), nn.SiLU(),

        nn.Conv2d(32, 3, 3, padding=1), nn.Tanh()

    )

def encode(self, x):

    h = self.enc(x)

    return self.mu(h), self.logvar(h).clamp(-10, 10)

vae = VAE().to(device)

opt_vae = torch.optim.AdamW(vae.parameters(), lr=2e-4)

# Entraînement VAE

for epoch in range(VAE_EPOCHS):

vae.train()

order = torch.randperm(len(images))

losses = \[\]

for start in range(0, len(images), BATCH):

    batch = images\[order\[start:start+BATCH\]\]

    mu, logvar = vae.encode(batch)

    recon = vae.dec(mu)  # reconstruction déterministe depuis mu

    recon_loss = F.l1_loss(recon, batch)

    kl = -0.5 \* (1 + logvar - mu.square() - logvar.exp()).mean()

    loss = recon_loss + 1e-4 \* kl

    opt_vae.zero_grad(set_to_none=True)

    loss.backward()

    opt_vae.step()

    losses.append(loss.item())

print(f"VAE {epoch+1}/{VAE_EPOCHS} — loss {sum(losses)/len(losses):.4f}")

# Vérification des reconstructions

vae.eval()

with torch.no_grad():

sample = images\[:8\]

mu, \_ = vae.encode(sample)

recon = vae.dec(mu)

assert recon.shape == sample.shape

assert torch.isfinite(recon).all()

print("Latent VAE :", tuple(mu.shape),

      "| MAE :", round(F.l1_loss(recon, sample).item(), 4))

fig, ax = plt.subplots(2, 8, figsize=(14, 4))

for i in range(8):

ax\[0, i\].imshow(((sample\[i\].permute(1,2,0)+1)/2).clamp(0,1))

ax\[1, i\].imshow(((recon\[i\].permute(1,2,0)+1)/2).clamp(0,1))

ax\[0, i\].axis("off")

ax\[1, i\].axis("off")

ax[0, 0].set_ylabel(“Original”)

ax[1, 0].set_ylabel(“VAE”)

plt.tight_layout()

plt.show()

# Encodage et normalisation des latents

vae.eval()

with torch.no_grad():

latents = torch.cat(\[

    vae.encode(images\[i:i+BATCH\])\[0\]

    for i in range(0, len(images), BATCH)

\])

latent_mean = latents.mean()

latent_std = latents.std().clamp(min=1e-5)

latents = (latents - latent_mean) / latent_std

assert latents.shape[1:] == (4, SIZE // 4, SIZE // 4)

assert torch.isfinite(latents).all()

print(“Latents :”, tuple(latents.shape), “écart-type :”, latent_std.item())

# Encodeur de texte appris de zéro

class TextModel(nn.Module):

def \__init_\_(self, vocab_size):

    super().\__init_\_()

    self.embedding = nn.Embedding(vocab_size, 128, padding_idx=0)

def forward(self, ids):

    emb = self.embedding(ids)

    mask = (ids != 0).float().unsqueeze(-1)

    return (emb \* mask).sum(1) / mask.sum(1).clamp(min=1)

text_model = TextModel(len(vocab)).to(device)

def norm_groups(ch):

return 8 if ch % 8 == 0 else 4

# Bloc résiduel qui injecte le conditionnement temps/texte

class ResBlock(nn.Module):

def \__init_\_(self, cin, cout):

    super().\__init_\_()

    self.norm1 = nn.GroupNorm(norm_groups(cin), cin)

    self.conv1 = nn.Conv2d(cin, cout, 3, padding=1)

    self.norm2 = nn.GroupNorm(norm_groups(cout), cout)

    self.conv2 = nn.Conv2d(cout, cout, 3, padding=1)

    self.emb = nn.Linear(128, 2 \* cout)

    self.skip = nn.Conv2d(cin, cout, 1) if cin != cout else nn.Identity()

def forward(self, x, emb):

    h = self.conv1(F.silu(self.norm1(x)))

    scale, shift = self.emb(F.silu(emb)).chunk(2, dim=1)

    h = self.norm2(h) \* (1 + scale\[:, :, None, None\]) + shift\[:, :, None, None\]

    h = self.conv2(F.silu(h))

    return (h + self.skip(x)) / math.sqrt(2)

# U-Net latent résiduel, créé de zéro

class UNet(nn.Module):

def \__init_\_(self):

    super().\__init_\_()

    self.time_mlp = nn.Sequential(

        nn.Linear(32, 128), nn.SiLU(), nn.Linear(128, 128)

    )

    self.text_mlp = nn.Sequential(

        nn.Linear(128, 128), nn.SiLU(), nn.Linear(128, 128)

    )

    self.input = nn.Conv2d(4, 64, 3, padding=1)

    self.enc1 = ResBlock(64, 64)

    self.down = nn.Conv2d(64, 128, 4, stride=2, padding=1)

    self.enc2 = ResBlock(128, 128)

    self.mid1 = ResBlock(128, 128)

    self.mid2 = ResBlock(128, 128)

    self.up = nn.ConvTranspose2d(128, 64, 4, stride=2, padding=1)

    self.dec = ResBlock(128, 64)

    self.out_norm = nn.GroupNorm(8, 64)

    self.out = nn.Conv2d(64, 4, 3, padding=1)

def forward(self, z, t, cond):

    f = torch.arange(16, device=z.device, dtype=z.dtype)

    phase = (t\[:, None\] \* T) \* torch.exp(-f \* math.log(10000) / 16)

    time_emb = torch.cat(\[phase.sin(), phase.cos()\], dim=1)

    emb = self.time_mlp(time_emb) + self.text_mlp(cond)

    h1 = self.enc1(self.input(z), emb)

    h2 = self.enc2(self.down(h1), emb)

    h = self.mid1(h2, emb)

    h = self.mid2(h, emb)

    h = self.up(h)

    h = self.dec(torch.cat(\[h, h1\], dim=1), emb)

    return self.out(F.silu(self.out_norm(h)))

unet = UNet().to(device)

train_params = list(unet.parameters()) + list(text_model.parameters())

optimizer = torch.optim.AdamW(train_params, lr=LR)

# Calendrier de diffusion

beta = torch.linspace(1e-4, 0.02, T, device=device)

alpha_bar = torch.cumprod(1 - beta, dim=0)

# Entraînement du U-Net

unet.train()

text_model.train()

for step in range(DIFF_STEPS):

ix = torch.randint(len(latents), (min(BATCH, len(latents)),))

clean = latents\[ix\]

ids = tokens\[ix\]

cond = text_model(ids)

t = torch.randint(T, (len(ix),))

noise = torch.randn_like(clean)

a = alpha_bar\[t\].view(-1, 1, 1, 1)

noisy = a.sqrt() \* clean + (1 - a).sqrt() \* noise

\# Masquage occasionnel du texte pour le classifier-free guidance

keep_text = (torch.rand(len(ix), 1) > 0.1).float()

cond = cond \* keep_text

pred = unet(noisy, t.float() / T, cond)

loss = F.mse_loss(pred, noise)

optimizer.zero_grad(set_to_none=True)

loss.backward()

torch.nn.utils.clip_grad_norm\_(train_params, 1.0)

optimizer.step()

if (step + 1) % 250 == 0:

    print(f"Diffusion {step+1}/{DIFF_STEPS} — loss {loss.item():.4f}")

# Génération DDIM

@torch.no_grad()

def generate(prompt, steps=50, guidance=1.5, seed=123):

unet.eval()

text_model.eval()

ws = re.findall(r"\\w+", prompt.lower())\[:MAX_TOKENS\]

ids = torch.zeros(1, MAX_TOKENS, dtype=torch.long)

if ws:

    ids\[0, :len(ws)\] = torch.tensor(\[vocab.get(w, 1) for w in ws\])

cond = text_model(ids)

null_cond = torch.zeros_like(cond)

gen = torch.Generator(device=device).manual_seed(seed)

z = torch.randn(1, 4, SIZE // 4, SIZE // 4, generator=gen, device=device)

schedule = torch.linspace(T - 1, 0, steps).long().tolist()

for j, i in enumerate(schedule):

    ti = torch.full((1,), i / T, device=device)

    eps0 = unet(z, ti, null_cond)

    eps1 = unet(z, ti, cond)

    eps = eps0 + guidance \* (eps1 - eps0)

    ab = alpha_bar\[i\]

    x0 = (z - (1 - ab).sqrt() \* eps) / ab.sqrt()

    if j + 1 < len(schedule):

        nxt = schedule\[j + 1\]

        z = alpha_bar\[nxt\].sqrt() \* x0 + (1 - alpha_bar\[nxt\]).sqrt() \* eps

    else:

        z = x0

z = z \* latent_std + latent_mean

result = vae.dec(z).clamp(-1, 1)

result = ((result\[0\] + 1) \* 127.5).byte().permute(1, 2, 0).cpu().numpy()

plt.figure(figsize=(5, 5))

plt.imshow(result)

plt.axis("off")

plt.title(prompt\[:70\])

plt.show()

return result

prompt = captions[0]

print(“Prompt de test :”, prompt)

generate(prompt)```

For PyTorch 2.0+, wrap your VAE model with torch.compile (e.g., vae = torch.compile(vae) after initialization) to optimize the computational graph for significant CPU speedups. Your manual image loading and batching loop can bottleneck performance, especially with more images. Refactor your data pipeline to use torch.utils.data.Dataset and torch.utils.data.DataLoader with num_workers > 0 for parallel loading and preprocessing, improving throughput. These steps will make both VAE and UNet training more efficient on CPU.

For now, I tried a few things with CPU-only training in mind:


I would keep the basic CPU-only scratch design. The cached 4x16x16 latents are already a useful optimization. I reconstructed the displayed code to compare cost per U-Net update and quality per training budget separately.

What I would try first

  1. Start with FP32, eager, cached latents and the original width; compare CPU thread counts. Your four-thread cap is sensible.
  2. Try batch 8 vs 4 if RAM allows, comparing equal draws and equal updates.
  3. Save VAE, latents, normalization and vocabulary.
  4. Try width 32 or 48 if updates remain costly; capacity changes too.
  5. Make compilation optional; include startup in timing.

A few CPU measurements

Short repeated runs on a Colab Intel Xeon CPU allocation (PyTorch 2.14.1+cu130 executing on CPU, using cached real-image latents):

Configuration ms/update Latent draws/s
Original width, batch 4, 4 threads, FP32 31.27-32.75 122-128
Same, 1 thread 56.16-59.40 67-71
Same, 2 threads 40.78-42.32 95-98
Original width, batch 8, 4 threads 39.47-41.70 192-203
Half width, batch 4, 4 threads 22.90-24.39 164-175
Original width, batch 4, 4 threads, BF16 autocast 54.73-59.41 67-73

Ranges are short-run medians, not confidence intervals. Batch 8 increased throughput, width 32 reduced update time, BF16 was slower. Quality equivalence is unproven. Data preparation was ~0.16 ms (0.5%) in one reference run; loader workers would be more relevant with on-the-fly image preprocessing.

Separate two-thread CPU test, estimated 2,000 updates: 193-200 s eager, 276 s fresh compile, 190 s reused cache. Start eager.

For quality, zero terminal SNR with a matching velocity target increased prompt response in two paired training seeds, but samples remained rough. I used a T4 for quality comparisons, not CPU speed evidence. This requires new training; the speed changes are independent.

1. Measure the actual training loop

Measure setup, VAE, denoiser and sampling separately. One reference CPU update breakdown:

Phase Median ms
Prepare batch/noise/timestep/mask .155
Forward and loss 8.968
Zero gradients and backward 14.538
Gradient clipping 1.343
AdamW 6.148

Individual medians need not sum to the full-step median. Convolution/backward and optimizer were prominent. FP32 500-image tensor: 23.44 MiB; latent tensor: 1.95 MiB, excluding model/activation overhead.

CPU timer for a callable performing one full update and returning draw count. Warmup trains too; use disposable state, record startup separately.

import statistics
import time


def measure_updates(train_step, warmup=5, repeats=30):
    if repeats < 1 or warmup < 0:
        raise ValueError("Invalid number of updates")
    for _ in range(warmup):
        train_step()

    elapsed = []
    draws = 0
    for _ in range(repeats):
        start = time.perf_counter()
        n = train_step()
        elapsed.append(time.perf_counter() - start)
        draws += n

    total = sum(elapsed)
    return {
        "updates": repeats,
        "draws": draws,
        "median_ms": 1000 * statistics.median(elapsed),
        "mean_ms": 1000 * statistics.mean(elapsed),
        "min_ms": 1000 * min(elapsed),
        "max_ms": 1000 * max(elapsed),
        "draws_per_second": draws / total,
    }

Use the original CPU model, optimizer, tensors and schedule:

import torch
import torch.nn.functional as F


def epsilon_update(batch_size):
    unet.train()
    text_model.train()
    ix = torch.randint(len(latents), (batch_size,))
    clean = latents[ix]
    ids = tokens[ix]
    t = torch.randint(T, (batch_size,))
    eps = torch.randn_like(clean)
    a = alpha_bar[t].reshape(-1, 1, 1, 1)
    noisy = a.sqrt() * clean + (1 - a).sqrt() * eps

    optimizer.zero_grad(set_to_none=True)
    cond = text_model(ids)
    keep = (torch.rand(batch_size, 1) > 0.1).to(cond.dtype)
    pred = unet(noisy, t.float() / T, cond * keep)
    loss = F.mse_loss(pred, eps)
    loss.backward()
    torch.nn.utils.clip_grad_norm_(train_params, 1.0)
    optimizer.step()
    return batch_size

# On a fresh/disposable instance of the trainer:
# print(measure_updates(lambda: epsilon_update(4)))

Keep batch convention, initialization and logging comparable; GPU timing needs synchronization.

Compare sensible intra-op thread counts (1, 2, 4) in fresh processes, setting them before computation. Loader workers do different work. Record CPU model, affinity and PyTorch version; more threads need not help. Thread API, CPU tuning, benchmark utilities.

Profile separately after warmup:

from torch.profiler import profile, ProfilerActivity, record_function

# With a disposable instance after warmup:
with profile(activities=[ProfilerActivity.CPU],
             record_shapes=True, profile_memory=True) as prof:
    for _ in range(3):
        with record_function("diffusion_update"):
            epsilon_update(4)
print(prof.key_averages().table(
    sort_by="self_cpu_time_total", row_limit=20
))

Inspect convolution backward, optimizer and copies. Nested CPU totals overlap. Profiler recipe.

2. Batch size, smaller network and CPU options

At 500 images, batch 4 and 2,000 updates give 8,000 draws (16 expected per image, not exact epochs). Extrapolations:

Batch Updates Draws Estimated diffusion-loop time
4 2,000 8,000 62.5-65.5 s
8 1,000 8,000 39.5-41.7 s
8 2,000 16,000 78.9-83.4 s

Equal draws halve updates; equal updates double exposure. Neither guarantees quality; batch-8 quality tests showed no clear win. Compare equal CPU time too. Gradient accumulation can reduce memory but still executes multiple forwards/backwards; scale losses and clip/step once.

Optional smaller U-Net

Width 64: 1,533,508 U-Net parameters; width 32: 458,788 (plus 188,672 text parameters in both). Keep the original ResBlock:

import math
import torch
from torch import nn
import torch.nn.functional as F


class UNet(nn.Module):
    def __init__(self, width=64, timesteps=100):
        super().__init__()
        if width < 8 or width % 8 or timesteps < 2:
            raise ValueError("Use width divisible by 8 and timesteps >= 2")
        self.timesteps = timesteps
        w = width
        self.time_mlp = nn.Sequential(
            nn.Linear(32, 128), nn.SiLU(), nn.Linear(128, 128)
        )
        self.text_mlp = nn.Sequential(
            nn.Linear(128, 128), nn.SiLU(), nn.Linear(128, 128)
        )
        self.input = nn.Conv2d(4, w, 3, padding=1)
        self.enc1 = ResBlock(w, w)
        self.down = nn.Conv2d(w, 2 * w, 4, stride=2, padding=1)
        self.enc2 = ResBlock(2 * w, 2 * w)
        self.mid1 = ResBlock(2 * w, 2 * w)
        self.mid2 = ResBlock(2 * w, 2 * w)
        self.up = nn.ConvTranspose2d(2 * w, w, 4, stride=2, padding=1)
        self.dec = ResBlock(2 * w, w)
        self.out_norm = nn.GroupNorm(8, w)
        self.out = nn.Conv2d(w, 4, 3, padding=1)

    def forward(self, z, t, cond):
        f = torch.arange(16, device=z.device, dtype=z.dtype)
        phase = (t[:, None] * self.timesteps) * torch.exp(
            -f * math.log(10000) / 16
        )
        time_emb = torch.cat([phase.sin(), phase.cos()], dim=1)
        emb = self.time_mlp(time_emb) + self.text_mlp(cond)
        h1 = self.enc1(self.input(z), emb)
        h2 = self.enc2(self.down(h1), emb)
        h = self.mid2(self.mid1(h2, emb), emb)
        h = self.up(h)
        h = self.dec(torch.cat([h, h1], dim=1), emb)
        return self.out(F.silu(self.out_norm(h)))

Construct with timesteps=T and use t.float()/T; rebuild optimizer. Check shape and backward before training.

Width 48 is unmeasured for quality. Width 32 resembled the weak original-schedule baseline; no evidence of preserving a better model. Use compatible new weights and compare fixed prompts at equal draws/time.

Other execution options

  • channels_last: U-Net 31.26-31.32 ms (near reference); VAE 18.05-21.55 vs 19.60-24.43 ms. Possible, variable benefit; use matching model/input formats, not manual NHWC permutation. Layout.
  • BF16 VAE 43.89-46.38 ms, slower here; a different CPU had a smaller difference. AMP.
  • AdamW foreach 31.33-31.44 ms, near reference. set_to_none=True is already used. Compare finite loss, gradients and updates before adopting other optimizer modes. AdamW.
3. Compilation: include the startup cost

Separate two-thread CPU VM, PyTorch 2.14.1+cpu, FP32 synthetic latents, batch 4, only U-Net Inductor fullgraph=True. Matched initialization/draws, 45 updates in each fresh process:

Mode First update (s) Steady median (ms) Wrap + first 5 updates (s) Est. 2,000 updates (s)
Eager, before .407 99.622 .859 199.605
Compile, fresh cache 78.566 97.898 81.025 276.332
Compile, reused cache 3.115 93.201 4.107 190.044
Eager, after .134 96.381 .556 192.837

For N updates estimate A+(N-k)*m, with wrapping + first k updates A and steady median m (seconds). Break-even if compile is faster: k+(A_compiled-A_eager)/(m_eager-m_compiled). Cold estimate ~46,500 vs first eager, none vs last; warm ~511-1,122. Eager varied; these are not robust thresholds. Loss max difference 1.49e-6, relative update L2 difference 8.41e-5; final strict parameter allclose failed. Close losses are not exact equivalence.

Make sure the compiled path is called

Set use_compile explicitly; select once, save the base module:

unet_run = unet
if use_compile:  # set this explicitly for a comparison run
    unet_run = torch.compile(unet, backend="inductor")

# optimizer still uses the base model's parameters plus text_model
# Inside the update, instead of unet(...):
# pred = unet_run(noisy, t.float() / T, cond * keep)

Use unet_run(...) in the update. Avoid compiled_model or original_model (truth testing may call __len__; my first harness failed there, corrected follow-up succeeded). New shapes/modes can recompile.

Direct VAE encode/dec calls bypassed compiled forward in a small capture check. To test a compiled module call, add inside the VAE:

# Add inside class VAE(nn.Module):
def forward(self, x):
    mu, logvar = self.encode(x)
    return self.dec(mu), mu, logvar

Then choose vae_run = torch.compile(vae) or vae_run = vae before training, and replace the two reconstruction calls with recon, mu, logvar = vae_run(batch). Keep the original loss.

This retains reconstruction from mu plus KL. VAE Inductor speed is unmeasured. Compile time, recompilation, cache. AOT eager tests capture, not Inductor speed.

4. Reuse the VAE and save compatible checkpoints

Cache token IDs, not embeddings: the latter are still trained.

Artifact Contents that must agree
Representation VAE, ordered rows/split/transform, latents and normalization, token IDs and vocabulary/tokenizer
Inference VAE, text and U-Net weights, architecture, schedule/target, vocabulary and inverse normalization
Resume Compatible representation, trainable weights, optimizer, completed updates, RNG states and training settings

Cache identity must include actual revision/ordered rows/transform/tokenizer and trained VAE identity; matching shapes or vocabulary size are insufficient. This example assumes scalar normalization, 64px, 24 tokens.

import os
from pathlib import Path
import torch


def atomic_torch_save(obj, filename):
    path = Path(filename)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(path.name + ".tmp")
    torch.save(obj, tmp)
    os.replace(tmp, path)


def save_representation(filename, data_id):
    # These variables are from the existing trainer.
    atomic_torch_save({
        "format": 1,
        "data_id": data_id,
        "vae": vae.state_dict(),
        "latents": latents.detach().cpu(),
        "tokens": tokens.detach().cpu(),
        "vocab": dict(vocab),
        "latent_mean": latent_mean.detach().cpu(),
        "latent_std": latent_std.detach().cpu(),
    }, filename)


def load_representation(filename, expected_data_id):
    d = torch.load(filename, map_location="cpu", weights_only=True)
    if d["format"] != 1 or d["data_id"] != expected_data_id:
        raise ValueError("Incompatible cache; rebuild it")
    z, ids = d["latents"], d["tokens"]
    if z.ndim != 4 or z.shape[1:] != (4, 16, 16):
        raise ValueError("Unexpected latent shape")
    if ids.shape != (len(z), 24) or ids.dtype != torch.long:
        raise ValueError("Unexpected token tensor")
    if len(z) == 0 or not torch.isfinite(z).all():
        raise ValueError("Empty or nonfinite cache")
    if d["latent_mean"].numel() != 1 or not torch.isfinite(d["latent_mean"]).all():
        raise ValueError("Invalid latent mean")
    sd = d["latent_std"]
    if sd.numel() != 1 or not torch.isfinite(sd).all() or sd.item() <= 0:
        raise ValueError("Invalid latent standard deviation")
    if ids.min().item() < 0 or ids.max().item() >= len(d["vocab"]):
        raise ValueError("Token IDs outside saved vocabulary")
    vae.load_state_dict(d["vae"])
    vae.eval()
    return z, ids, d["vocab"], d["latent_mean"], sd

Construct compatible VAE; assign latents, tokens, vocab, latent_mean, latent_std = load_representation(path, expected_data_id) before text model/optimizer. Trusted local files only; weights_only=True needs compatible PyTorch. Temp replacement is not a backup; avoid concurrent writers.

Resume assumes CPU, global Python/PyTorch RNG, no scheduler/scaler, completed updates. run_config includes cache identity, width/T/target/batch/optimizer settings. Construct compatible models/optimizer/schedule first:

import random


def save_diffusion_resume(filename, completed_steps, run_config):
    atomic_torch_save({
        "format": 1,
        "completed_steps": int(completed_steps),
        "config": run_config,
        "alpha_bar": alpha_bar.detach().cpu(),
        "unet": unet.state_dict(),
        "text_model": text_model.state_dict(),
        "optimizer": optimizer.state_dict(),
        "rng_torch": torch.get_rng_state(),
        "rng_python": random.getstate(),
    }, filename)


def load_diffusion_resume(filename, expected_config):
    d = torch.load(filename, map_location="cpu", weights_only=True)
    if d["format"] != 1 or d["config"] != expected_config:
        raise ValueError("Incompatible training checkpoint")
    if not torch.equal(d["alpha_bar"], alpha_bar.cpu()):
        raise ValueError("Diffusion schedule changed")
    unet.load_state_dict(d["unet"])
    text_model.load_state_dict(d["text_model"])
    optimizer.load_state_dict(d["optimizer"])
    # Restore RNG after constructing/loading the models and optimizer.
    random.setstate(d["rng_python"])
    torch.set_rng_state(d["rng_torch"])
    return d["completed_steps"]

Continue at returned count; capture additional RNG/iterator/scheduler/scaler state if added. Inference needs no optimizer/RNG. Changed representation/width/target is not a resume. Saving/loading, serialization, reproducibility.

5. A separate quality experiment: schedule and prediction target

Terminal noise

100 betas linearly spaced .0001-.02; a[t] is cumulative product of 1-beta:

x_t = sqrt(a[t]) * x0 + sqrt(1 - a[t]) * eps

At t=99, a=.36356, nominal SNR .57125, clean/noise coefficients .603/.798. Training retains clean signal while generation starts at T-1 with pure noise. Global normalization does not establish Gaussian caption-conditional latents. Common Diffusion Noise Schedules and Sample Steps are Flawed discusses this mechanism, not your measured outputs.

T noise levels, optimizer updates and sampling steps are distinct: training samples one timestep per draw, so increasing T alone does not multiply forward calls.

Match target and reverse equations

Epsilon recovery is:

x0_hat = (x_t - sqrt(1 - a[t]) * eps_hat) / sqrt(a[t])

Zero denominator at a=0; near zero the epsilon error is amplified by sqrt((1-a)/a). My terminal-alpha-.01 control: epsilon MSE .0147, recovered-clean MSE 1.459 (factor 99). A compatible alternative to denominator clamping is velocity:

v = sqrt(a[t]) * eps - sqrt(1 - a[t]) * x0
x0_hat  = sqrt(a[t]) * x_t - sqrt(1 - a[t]) * v_hat
eps_hat = sqrt(1 - a[t]) * x_t + sqrt(a[t]) * v_hat

At exact zero, input is pure noise, target -x0, recovery finite. Native losses across targets are not comparable.

Manual replacement code

Use the existing CPU models/latents with fresh denoiser/text weights and optimizer. Keep the old epsilon run as a reference. The following changes are coupled:

import torch
import torch.nn.functional as F


def make_alpha_bar(T=100, zero_terminal=False):
    if T < 2:
        raise ValueError("Need at least two training timesteps")
    beta = torch.linspace(1e-4, 0.02, T, dtype=torch.float64)
    a = torch.cumprod(1 - beta, dim=0).float()
    if zero_terminal:
        # Keep the initial sqrt(alpha_bar), move the end to zero.
        s = a.sqrt()
        s = (s - s[-1]) * (s[0] / (s[0] - s[-1]))
        a = s.square()
    return a


def noise_and_target(clean, eps, a, prediction_type):
    signal, noise = a.sqrt(), (1 - a).sqrt()
    x_t = signal * clean + noise * eps
    if prediction_type == "v":
        target = signal * eps - noise * clean
    elif prediction_type == "epsilon":
        target = eps
    else:
        raise ValueError("Unknown prediction type")
    return x_t, target


def recover_clean_and_noise(x_t, pred, a, prediction_type):
    signal, noise = a.sqrt(), (1 - a).sqrt()
    if prediction_type == "v":
        return signal * x_t - noise * pred, noise * x_t + signal * pred
    if prediction_type == "epsilon":
        if (a <= 0).any():
            raise ValueError("Epsilon recovery requires positive alpha_bar")
        return (x_t - noise * pred) / signal, pred
    raise ValueError("Unknown prediction type")

Float64 cumulative product then FP32 is not necessarily bit-identical to the original. Rescale sqrt(alpha_bar), retaining its first value and ending at zero. These cumulative alphas are not betas. Perfect-prediction test:

g = torch.Generator().manual_seed(123)
x = torch.randn(2, 4, 16, 16, generator=g)
eps = torch.randn(x.shape, generator=g)
for zero, kind in [(False, "epsilon"), (False, "v"), (True, "v")]:
    ab = make_alpha_bar(100, zero)
    assert torch.isfinite(ab).all()
    assert (ab[:-1] > ab[1:]).all()
    assert (ab >= 0).all() and (ab <= 1).all()
    if zero:
        assert ab[-1].item() == 0.0
    for i in (0, 50, 99):
        z, exact = noise_and_target(x, eps, ab[i], kind)
        rx, re = recover_clean_and_noise(z, exact, ab[i], kind)
        torch.testing.assert_close(rx, x, atol=1e-5, rtol=1e-5)
        torch.testing.assert_close(re, eps, atol=1e-5, rtol=1e-5)

Keep the all-zero condition for dropout and optimize both models:

T = 100
prediction_type = "v"
alpha_bar = make_alpha_bar(T, zero_terminal=True)


def diffusion_update(batch_size):
    unet.train()
    text_model.train()
    ix = torch.randint(len(latents), (batch_size,))
    clean = latents[ix]
    ids = tokens[ix]
    t = torch.randint(T, (batch_size,))
    eps = torch.randn_like(clean)
    a = alpha_bar[t].view(-1, 1, 1, 1)
    noisy, target = noise_and_target(clean, eps, a, prediction_type)
    optimizer.zero_grad(set_to_none=True)
    cond = text_model(ids)
    keep = (torch.rand(batch_size, 1) > 0.1).to(cond.dtype)
    pred = unet(noisy, t.float() / T, cond * keep)
    loss = F.mse_loss(pred, target)
    loss.backward()
    torch.nn.utils.clip_grad_norm_(train_params, 1.0)
    optimizer.step()
    return loss.detach().item()

# For a new run (or start from the saved step with compatible resume state):
# for step in range(DIFF_STEPS):
#     value = diffusion_update(min(BATCH, len(latents)))
#     if (step + 1) % 250 == 0:
#         print(f"Diffusion {step+1}/{DIFF_STEPS}: {value:.4f}")

Reference: prediction_type="epsilon", alpha_bar=make_alpha_bar(T, False); target-only control: original schedule with "v". Combined: exact-zero plus velocity. No exact-zero epsilon recovery.

Matched sampler; keep actual vocabulary and tokenization. I used explicit PAD=0, UNK=1 and shared re.findall(r"\w+", text.lower())[:MAX_TOKENS] in my reconstruction. CFG batching is optional.

import re


@torch.no_grad()
def generate_cpu(prompt, steps=50, guidance=1.5, seed=123,
                 batch_cfg=False):
    if not 2 <= steps <= T:
        raise ValueError("Use between 2 and T sampling steps")
    if len(alpha_bar) != T:
        raise ValueError("Schedule/timestep mismatch")
    if prediction_type == "epsilon" and alpha_bar[-1] <= 0:
        raise ValueError("Use v-prediction for exact zero terminal alpha")

    unet.eval()
    text_model.eval()
    vae.eval()
    words = re.findall(r"\w+", prompt.lower())[:MAX_TOKENS]
    ids = torch.zeros(1, MAX_TOKENS, dtype=torch.long)
    if words:
        ids[0, :len(words)] = torch.tensor(
            [vocab.get(w, 1) for w in words], dtype=torch.long
        )
    cond = text_model(ids)
    null = torch.zeros_like(cond)
    gen = torch.Generator(device="cpu").manual_seed(seed)
    z = torch.randn(1, 4, SIZE // 4, SIZE // 4, generator=gen)
    ts = torch.linspace(T - 1, 0, steps).long().tolist()
    assert ts[0] == T - 1 and ts[-1] == 0
    assert all(i > j for i, j in zip(ts, ts[1:]))

    for j, i in enumerate(ts):
        ti = torch.full((len(z),), i / T)
        if batch_cfg:
            p0, p1 = unet(
                torch.cat((z, z), dim=0),
                torch.cat((ti, ti), dim=0),
                torch.cat((null, cond), dim=0),
            ).chunk(2, dim=0)
        else:
            p0 = unet(z, ti, null)
            p1 = unet(z, ti, cond)
        pred = p0 + guidance * (p1 - p0)
        x0, eps = recover_clean_and_noise(
            z, pred, alpha_bar[i], prediction_type
        )
        if not torch.isfinite(x0).all() or not torch.isfinite(eps).all():
            raise FloatingPointError(f"Nonfinite estimate at timestep {i}")
        if j + 1 < len(ts):
            a_next = alpha_bar[ts[j + 1]]
            z = a_next.sqrt() * x0 + (1 - a_next).sqrt() * eps
        else:
            z = x0

    # Undo the exact training normalization before decoding.
    decoded = vae.dec(z * latent_std + latent_mean)
    if not torch.isfinite(decoded).all():
        raise FloatingPointError("Nonfinite decoded image")
    return decoded.clamp(-1, 1)

# After training:
# import matplotlib.pyplot as plt
# result = generate_cpu(captions[0])
# plt.imshow(((result[0].permute(1, 2, 0) + 1) / 2).numpy())
# plt.axis("off")
# plt.show()

Deterministic DDIM reuses recovered clean/noise at the next alpha, then inverts normalization. Do not clamp standardized latents as pixels. DDIM paper, DDIMScheduler, scheduler guide. For library use, match schedule/target/spacing, inspect clip_sample; trailing spacing need not exactly match this grid. Guidance rescaling is not implemented.

What happened in the real-image test

Shared VAE, 500 train/333 held out. Same-noise prompt L1 averages adjacent prompts (wraparound included) at first sampling seed; matched/null uses first four prompts. Decoded pixels [-1,1]. Sensitivity, not semantic accuracy:

Training variant Same-noise prompt L1 Matched/null L1
Original epsilon, seed 42 .0180 .0134
Original epsilon, seed 43 .0155 .0116
Velocity, original schedule, seed 42 .0225 .0151
Epsilon, terminal alpha .01, seed 42 .0391 .0304
Velocity, zero terminal SNR, seed 42 .0952 .0665
Velocity, zero terminal SNR, seed 43 .1707 .1176

My original samples often showed blue/grey fragments on light backgrounds; combined samples had more varied colors/shapes with prompt changes in both seeds, but not reliably correct creatures. Velocity alone changed less. Seeds share VAE/data; no independent-dataset proof. These are my outputs, not an assessment of yours.

At t=99, combined matched/shuffled/null clean MSE: .4931/.5162/.5050 (seed 42), .4979/.5194/.5225 (43). Supports possible condition use. Do not compare absolute clean MSE across schedules: original has residual clean signal. Promising quality branch, not a proven optimum or speedup.

6. VAE, dataset and text conditioning

Held-out VAE L1 .21740 (epoch 1), .10534 (5), .08573 (10), .07170 (20); train .06954 at 20, pixels [-1,1]. Outlines often survive, blur/colors imperfect. Check reconstruction separately; 20 epochs is not universal. Your VAE decodes mu directly with weak KL, so sampled posterior/latent size/KL changes are separate. Latent diffusion, regularized AE.

Global normalization does not whiten. Per-channel train statistics are an untested alternative; retrain and invert before decoding, adapting cache checks.

500 vs 833 images

Dataset: 833 valid rows, first 500 train/333 held out; no exact RGB/resized duplicate crossing, near duplicates/order bias untested. Card has non-commercial usage statement; check underlying rights before redistribution or other use.

At 2,000 updates/batch 4, expected draws/image fall 16 to 9.6 with 833 images. About 3,332 updates (batch 4) or 1,666 (8) match exposure, not convergence. Reserve a common evaluation set for subset comparisons. Scratch discussion.

Small text encoder

Masked mean embedding (128d) is order-invariant for the same retained multiset. Vocab 1,474; 100/500 train and 61/333 held-out captions exceeded 24 tokens; held-out OOV 673/6,617 (~10.2%). Depends on tokenizer/split. Try familiar short attribute prompts, shuffled words, unknown words, novel combinations before adding a sequence encoder.

Low-cost quality checks

Compare fixed reconstruction pairs, matched/shuffled/null conditions, same-noise prompt grids and multiple seeds. Nearest training images may flag copies; pixel distance/FID cannot establish novelty or semantic accuracy. Fit vocabulary/stats on train only.

Save prompts, seeds, checkpoint and sampler settings; repeated selection on held-out samples limits generalization. Memorization research.

7. Generation speed and other directions

batch_cfg=True combines two CFG calls into a batch of two; more memory, potentially better throughput. One full T4 50-step sample had max pixel difference 2.56e-6; CPU speed unmeasured. Try 20/25 preview steps vs 50 on fixed seeds. Guidance 1 needs only conditional prediction mathematically but changes behavior.

Later options (untested): Min-SNR weighting with target-specific endpoint-safe weights, or EMA with compatible text state.

8. Experiment settings and limits

Quality: revision 6dc8154426e8a36ecc22b0001bb01a5ad78309c7, RGB64 [-1,1], 24 tokens, masked 128d embeddings, 4x16x16 mean latents. Shared VAE20 epochs/batch4/AdamW LR2e-4/L1+1e-4 KL. Denoiser LR1e-3/clip1/dropout.1/T100, T4/PyTorch 2.14.1+cu130 FP32 TF32 off. Eight arms, nine checkpoints:

Seed Schedule/target Width Batch Updates
42 Original/epsilon 64 4 2,000
42 Original/velocity 64 4 2,000
42 Terminal alpha .01/epsilon 64 4 2,000
42 Zero terminal SNR/velocity 64 4 2,000
42 Original/epsilon 32 4 2,000
42 Original/epsilon 64 8 1,000 and 2,000
43 Original/epsilon 64 4 2,000
43 Zero terminal SNR/velocity 64 4 2,000

DDIM50/CFG1.5, seeds123/456, 12 prompts (6 train, 6 held-out), 48 held-out denoising examples. No all-833, equal-CPU-time quality or combined width/batch/schedule tests.

CPU timing: Xeon family6/model85, four physical cores reported/eight logical affinity, oneDNN, 2.14.1+cu130 CPU, real cache, original schedule/epsilon, 5 warmup+18 timed updates, two orders/repeated references. Compile: different Xeon model79/AVX2 two-logical-CPU VM, 2 intra-op/1 inter-op, synthetic latents. Do not compare absolute times across machines as a compiler effect.

Reconstruction of displayed code, not byte-identical original: explicit PAD/UNK/regex, diagnostics, fused AdamW disabled. Snippets checked on artificial CPU inputs (forward/backward, algebra, short generation/CFG, cache/resume), not full integrated real-data training or fresh Inductor benchmark. Author CPU/version/output unknown. DDPM.

Choosing a next step

Main limit First option
Seconds/update Thread count, batch throughput, profile
Repeated setup VAE and latent/token cache
Compute/RAM per update Width or physical batch
Rough images Reconstructions, matched schedule/target/sampler
Weak prompt response Same-noise controls, known words
Slow generation CFG batching, preview steps
Long repeated fixed-shape runs Compilation including startup/reuse

CPU model, PyTorch version and update timing would help tailor settings.