# Cpu trainer open source

**URL:** <https://discuss.huggingface.co/t/cpu-trainer-open-source/192506>\
**Category:** Research\
**Created:** [November 24, 2026, 10:38pm UTC](https://discuss.huggingface.co/t/cpu-trainer-open-source/192506 "2026-11-24T22:38:14Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](https://discuss.huggingface.co/u/John6666)\
**Post date:** [November 26, 2026, 9:45am UTC](https://discuss.huggingface.co/t/cpu-trainer-open-source/192506/3 "2026-11-26T09:45:07Z")

</div>

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.
> 
> ```python
> 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:
> 
> ```python
> 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](https://docs.pytorch.org/docs/stable/generated/torch.set_num_threads.html), [CPU tuning](https://docs.pytorch.org/tutorials/recipes/recipes/tuning_guide.html), [benchmark utilities](https://docs.pytorch.org/docs/stable/benchmark_utils.html).
> 
> Profile separately after warmup:
> 
> ```python
> 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](https://docs.pytorch.org/tutorials/recipes/recipes/profiler_recipe.html).

> **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`:
> 
> ```python
> 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](https://docs.pytorch.org/tutorials/intermediate/memory_format_tutorial.html).
> - BF16 VAE 43.89-46.38 ms, slower here; a different CPU had a smaller difference. [AMP](https://docs.pytorch.org/docs/stable/amp.html).
> - 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](https://docs.pytorch.org/docs/stable/generated/torch.optim.AdamW.html).

> **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:
> 
> ```python
> 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:
> 
> ```python
> # 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](https://docs.pytorch.org/docs/main/user_guide/torch_compiler/compile/programming_model.reducing_compile_time.html), [recompilation](https://docs.pytorch.org/docs/main/user_guide/torch_compiler/compile/programming_model.recompilation.html), [cache](https://docs.pytorch.org/tutorials/recipes/torch_compile_caching_configuration_tutorial.html). 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.
> 
> ```python
> 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:
> 
> ```python
> 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](https://docs.pytorch.org/tutorials/beginner/saving_loading_models.html), [serialization](https://docs.pytorch.org/docs/stable/notes/serialization.html), [reproducibility](https://docs.pytorch.org/docs/stable/notes/randomness.html).

> **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`:
> 
> ```auto
> 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](https://arxiv.org/abs/2305.08891) 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:
> 
> ```auto
> 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:
> 
> ```auto
> 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:
> 
> ```python
> 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:
> 
> ```python
> 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:
> 
> ```python
> 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.
> 
> ```python
> 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](https://arxiv.org/abs/2010.02502), [DDIMScheduler](https://huggingface.co/docs/diffusers/en/api/schedulers/ddim), [scheduler guide](https://huggingface.co/docs/diffusers/en/using-diffusers/schedulers). 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](https://arxiv.org/abs/2112.10752), [regularized AE](https://arxiv.org/abs/1903.12436).
> 
> 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](https://huggingface.co/datasets/diffusers/pokemon-gpt4-captions): 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](https://discuss.huggingface.co/t/training-from-scratch/35433).
> 
> ### 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](https://arxiv.org/abs/2207.12598).

> **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](https://arxiv.org/abs/2303.09556) 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](https://arxiv.org/abs/2006.11239).

## 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.

---

_[View the full topic](https://discuss.huggingface.co/t/cpu-trainer-open-source/192506)._
