# Cpu trainer open source

**URL:** </static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcpu-trainer-open-source%2F192506%3E%5C
**Category:** Research\
**Created:** [November 24, 2026, 10:38pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcpu-trainer-open-source%2F192506 "2026-11-24T22:38:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![lea97338](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/lea97338/32/64708_2.png) [@lea97338](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Flea97338)%5C
**Post date:** [November 24, 2026, 10:38pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcpu-trainer-open-source%2F192506%2F1 "2026-11-24T22:38:14Z")

</div>

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](https://user.uploads.dev/file/906af86a715c0e31fa9e7218d15c3d35.png),[Unet génération image](https://user.uploads.dev/file/2d6c8dac7203e0321241fe05671b0ed0.png) )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)```

---

<div class="post-metadata">

**Author:** ![jaharoni](https://avatars.discourse-cdn.com/v4/letter/j/57b2e6/32.png) [@jaharoni](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fjaharoni)%5C
**Post date:** [November 25, 2026, 1:32am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcpu-trainer-open-source%2F192506%2F2 "2026-11-25T01:32:19Z")

</div>

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.
