REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project: train and reload a tiny causal language model

This project trains a complete tiny decoder instead of inspecting fixed logits.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Project: train and reload a tiny causal language model →

Your task

Implement TinyDecoder(vocab) with token/32-position embeddings of width 8; pre-norm two-head attention (head width 4), bias-free qkv/output projections, residual; pre-norm 8→16→8 GELU feed-forward residual; final LayerNorm and output tied to token.weight. Train rectangular in-vocabulary sequences length 2..32 using shifted mean CE, AdamW lr=.03 weight_decay=.01, global gradient cap 1, positive steps and fork_rng seed. Return artifact (vocab/state lists), initial_loss, loss, perplexity and pre-update history. Also implement tiny_lm_logits(artifact,tokens) for detached eval. Trace uses four updates; tests train longer.

Starter

import torch


def train_tiny_lm(tokens, vocab, steps, seed):
    return None
Inspect the worked answer
import math
import torch
from torch import nn
from torch.nn import functional as F


class TinyDecoder(nn.Module):
    def __init__(self, vocab):
        super().__init__()
        self.token = nn.Embedding(vocab, 8)
        self.position = nn.Embedding(32, 8)
        self.norm1 = nn.LayerNorm(8)
        self.qkv = nn.Linear(8, 24, bias=False)
        self.projection = nn.Linear(8, 8, bias=False)
        self.norm2 = nn.LayerNorm(8)
        self.feedforward = nn.Sequential(nn.Linear(8, 16), nn.GELU(), nn.Linear(16, 8))
        self.final = nn.LayerNorm(8)

    def forward(self, tokens):
        batch, length = tokens.shape
        x = self.token(tokens) + self.position(torch.arange(length, device=tokens.device))
        normalized = self.norm1(x)
        q, k, v = [part.reshape(batch, length, 2, 4).transpose(1, 2)
                   for part in self.qkv(normalized).chunk(3, dim=-1)]
        scores = q @ k.transpose(-2, -1) / math.sqrt(4)
        allow = torch.ones(length, length, dtype=torch.bool, device=tokens.device).tril()
        mixed = torch.softmax(scores.masked_fill(~allow, float('-inf')), dim=-1) @ v
        x = x + self.projection(mixed.transpose(1, 2).reshape(batch, length, 8))
        x = x + self.feedforward(self.norm2(x))
        return F.linear(self.final(x), self.token.weight)


def _tokens(rows, vocab):
    if type(vocab) is not int or vocab < 2 or not rows or not rows[0] or len(rows[0]) > 32:
        raise ValueError('nonempty token rows with length at most 32 required')
    if any(len(row) != len(rows[0]) or any(type(t) is not int or not 0 <= t < vocab for t in row) for row in rows):
        raise ValueError('rectangular in-vocabulary integer tokens required')
    return torch.tensor(rows, dtype=torch.long)


def tiny_lm_logits(artifact, tokens):
    encoded = _tokens(tokens, artifact['vocab'])
    with torch.random.fork_rng(devices=[]):
        model = TinyDecoder(artifact['vocab'])
        model.load_state_dict({k: torch.tensor(v, dtype=torch.float32) for k, v in artifact['state'].items()})
        model.eval()
        with torch.no_grad():
            return model(encoded)


def train_tiny_lm(tokens, vocab, steps, seed):
    encoded = _tokens(tokens, vocab)
    if encoded.shape[1] < 2 or type(steps) is not int or steps < 1:
        raise ValueError('next-token sequences and positive training steps required')
    with torch.random.fork_rng(devices=[]):
        torch.manual_seed(seed)
        model = TinyDecoder(vocab)
        optimizer = torch.optim.AdamW(model.parameters(), lr=.03, weight_decay=.01)
        def objective():
            logits = model(encoded)[:, :-1, :]
            return F.cross_entropy(logits.reshape(-1, vocab), encoded[:, 1:].reshape(-1))
        initial = float(objective().detach())
        history = []
        for step in range(steps):
            model.train()
            optimizer.zero_grad(set_to_none=True)
            loss = objective()
            loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0, error_if_nonfinite=True)
            optimizer.step()
            history.append(float(loss.detach()))
        model.eval()
        with torch.no_grad():
            final = float(objective())
        artifact = {'vocab': vocab, 'state': {k: v.tolist() for k, v in model.state_dict().items()}}
        return {'artifact': artifact, 'initial_loss': initial, 'loss': final,
                'perplexity': math.exp(final), 'history': history}

About this algorithm

How Project: train and reload a tiny causal language model works

The idea

Predicting the next token from the tokens before it is the whole task of a causal language model, and the text supplies its own labels. The logits at positions 0 to T - 2 are compared with the tokens at positions 1 to T - 1, so one sequence gives T - 1 training examples in a single forward pass, and the causal mask stops each position from seeing its own answer.

TinyDecoder is a complete model of that kind: token and position embeddings of width 8, one pre-norm block with two attention heads, a final LayerNorm, and an output layer that reuses token.weight. train_tiny_lm runs AdamW with gradient clipping and reports the loss and its exponential, the perplexity.

How it works

  1. Check the token rows are rectangular, in vocabulary and between 2 and 32 tokens long, then seed PyTorch inside fork_rng so the caller's random state is untouched.
  2. Build TinyDecoder(vocab) and an AdamW optimizer with lr=.03 and weight_decay=.01.
  3. Define the objective: cross-entropy between the logits at every position but the last and the tokens shifted left by one.
  4. On each step, zero the gradients, compute the loss, call backward, clip the global gradient norm to 1 and step the optimizer.
  5. Record each pre-update loss in history, then measure the final loss in eval mode and set perplexity to its exponential.
  6. Return the weights as plain lists in artifact; tiny_lm_logits rebuilds the model from them and returns detached logits.

What it costs

Per step
one pass over all rows
Attention
O(T²) per sequence
Model size
8·vocab + 840 values

Each update runs the whole batch forward and backward. Attention compares every pair of positions, which stays small because sequences stop at 32 tokens.

Where it is used

  • GPT-2 shares one matrix between its token embedding and its output layer, the same tying as F.linear(..., self.token.weight).
  • Andrej Karpathy's nanoGPT trains character-level Shakespeare with this shifted cross-entropy, AdamW and gradient clipping.
  • Language model papers report perplexity on benchmarks such as WikiText-103 and Penn Treebank.

Watch out for

  • Comparing the logits with the unshifted tokens, which trains the model to copy its input instead of predicting the next token.
  • Leaving out the causal mask: training loss drops quickly because each position can read the token it is asked to predict.
  • Reading the last entry of history as the final loss: it was measured before the final update, so loss is the number to report.