TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Training a Tiny Character Transformer

Training a Tiny Character Transformer

You have the transformer block. Stack two of them, put a character embedding in front and a linear layer behind, apply a causal mask, and train the result to predict the next character of a text: that is a decoder-only language model, the same recipe as GPT, at less than a millionth of the size of GPT-3. Small as it is, training it exercises every engineering detail of the large ones: the shifted targets, the loss over every position at once, a warm-up plus cosine learning-rate schedule with AdamW, an honest held-out evaluation in perplexity, and sampling with a temperature.

The theory of language models, perplexity and sampling is in Language Modeling, Perplexity and Sampling and Temperature. Here you build one and measure it.

The data: one short text, split at the end

The corpus is a 1403-character text written for this lesson, about a lighthouse keeper: simple sentences, a small vocabulary, and a lot of repetition, so that a model with 100 thousand parameters can learn it in seconds. The last 10% is held out. For text the split must be contiguous: random characters from the middle of training sentences would be trivially predictable from their neighbours, which the model has seen.

Two baselines tell you what "good" means before any training. A model that knows nothing predicts the 27 characters uniformly: loss ln⁡27=3.296\ln 27 = 3.296 nats, perplexity 27. A bigram model, the probability of each character given only the previous one, counted on the training part, is the classic baseline to beat.

python · try it yourself
import numpy as np

text = (
    'the keeper of the light climbs the stairs at dusk. the lamp is cold, the glass is clean, and the sea is grey.\n'
    'she lights the lamp and the beam turns over the water. the boats see the beam and turn away from the rocks.\n'
    'at night the wind comes from the west. the wind shakes the door and the rain hits the glass.\n'
    'the keeper writes in her book: the wind is strong, the lamp is bright, the boats are safe.\n'
    'at dawn the sea is calm. the keeper puts out the lamp and walks down the stairs.\n'
    'she makes tea and bread and sits by the window. the gulls cry over the rocks.\n'
    'in the afternoon she cleans the glass and fills the lamp with oil.\n'
    'the sun goes down over the water. the keeper climbs the stairs at dusk.\n'
    'she lights the lamp and the beam turns over the sea. a small boat comes in from the north.\n'
    'the boat sees the beam and turns to the harbour. the keeper writes in her book: one boat, safe.\n'
    'at night the rain stops and the stars come out. the lamp turns and turns.\n'
    'at dawn the keeper puts out the lamp. the sea is green and the sky is clear.\n'
    'she walks down the stairs and makes tea. the gulls sit on the rocks in the sun.\n'
    'in the afternoon a letter comes from the town. the town will build a new lamp that needs no keeper.\n'
    'the keeper reads the letter and looks at the sea. then she climbs the stairs at dusk,\n'
    'lights the lamp, and writes in her book: the wind is soft, the lamp is bright, the boats are safe.\n'
)
chars = sorted(set(text))
stoi = {ch: i for i, ch in enumerate(chars)}
ids = np.array([stoi[ch] for ch in text])
V = len(chars)
n_train = int(0.9 * len(ids))
train, val = ids[:n_train], ids[n_train:]
print(f"{len(text)} characters, vocabulary of {V}: {''.join(chars)!r}")
print(f"train {len(train)}, held-out tail {len(val)}: {text[n_train:n_train + 30]!r}...")
print("tail characters all seen in training:", set(val) <= set(train))

# Next-token targets: the target sequence is the input shifted left by one.
block = 8
x, y = ids[100:100 + block], ids[101:101 + block]
print("input :", repr("".join(chars[i] for i in x)))
print("target:", repr("".join(chars[i] for i in y)))

# Bigram baseline: P(next | current) from training counts, add-one smoothing.
counts = np.ones((V, V))
np.add.at(counts, (train[:-1], train[1:]), 1)
P = counts / counts.sum(axis=1, keepdims=True)
prev, nxt = ids[n_train - 1:-1], ids[n_train:]          # every target in the tail, with its previous char
nll = -np.log(P[prev, nxt]).mean()
print(f"uniform model: loss {np.log(V):.3f}, perplexity {V}")
print(f"bigram model:  loss {nll:.3f}, perplexity {np.exp(nll):.2f}")
1403 characters, vocabulary of 27: '\n ,.:abcdefghiklmnoprstuvwy'
train 1262, held-out tail 141: ' sea. then she climbs the stai'...
tail characters all seen in training: True
input : ' is grey'
target: 'is grey.'
uniform model: loss 3.296, perplexity 27
bigram model:  loss 2.116, perplexity 8.30
  • Vocabulary: the 27 distinct characters, including the newline, sorted, each mapped to an integer. The vocabulary is built from the whole text, but the check shows that every character of the tail also occurs in training, so nothing leaks except the alphabet.
  • Targets are the inputs shifted by one. Input ' is grey', target 'is grey.': position tt of the target is the character that follows position tt of the input. One window of length TT therefore gives TT training examples at once, each predicting from a longer prefix, and the causal mask makes sure position tt cannot peek at its own target.
  • The bigram baseline reaches a held-out loss of 2.116, perplexity 8.30: knowing one previous character cuts the effective number of choices from 27 to about 8. Add-one smoothing keeps unseen pairs from getting probability zero (an infinite loss).

The loss of a language model is the mean cross-entropy over all predicted positions,

L=−1N∑t=1Nln⁡pθ(ct+1∣c1,…,ct),PPL=eLL = -\frac{1}{N} \sum_{t=1}^{N} \ln p_\theta(c_{t+1} \mid c_1, \dots, c_t), \qquad \text{PPL} = e^{L}

and perplexity is its exponential: the number of equally likely characters the model is, on average, choosing between. It must be computed from the loss in nats (natural log), on held-out text, with the same tokenisation as the model you compare with: a character model and a word model have perplexities on different scales.

The schedule: warm-up, then cosine

Transformers are usually trained with AdamW and a learning rate that rises linearly from almost 0 to its peak during a short warm-up, then decays to 0 along a half cosine. The warm-up matters because Adam's second-moment estimates are unreliable in the first steps, and early updates on random weights can be large enough to wreck the attention patterns; the cosine decay gives the big steps at the start and the fine steps at the end. The schedule itself is the subject of Learning Rate Scheduling; this lesson only wires it in.

The lab draws the schedules per epoch with an illustrative toy loss, not real training (it says so on screen). Here it is set to 120 "epochs" with 10 of warm-up, roughly the shape of our 600 steps with 50 of warm-up. Compare it with constant and plain cosine, and try a warm-up of 1 or 30.

0.000.050.10050100ηLearning rate η per epoch012050100epochlossLoss (toy model, not real training)Schedulesconstantstepcosinewarm-up + cosineIllustrative only:the loss is a toyformula, not realtraining.Final loss (toy model)constant: 0.170step: 0.089cosine: 0.072warm-up + cosine: 0.073

With these settings the toy loss ends at 0.073 for warm-up + cosine against 0.170 for a constant rate: decaying schedules finish lower. That qualitative pattern is the point; the toy numbers say nothing about a real network.

The exact numbers for the real run, and the step from loss to perplexity:

python · try it yourself
import numpy as np

peak, steps, warmup = 3e-3, 600, 50

def lr_at(s):                                     # step s = 0, 1, ..., steps - 1
    if s < warmup:
        return peak * (s + 1) / warmup            # linear warm-up
    progress = (s - warmup) / (steps - warmup)    # 0 at the end of warm-up, 1 at the last step
    return peak * 0.5 * (1 + np.cos(np.pi * progress))

for s in (0, 24, 49, 50, 199, 325, 399, 599):
    print(f"step {s + 1:3d}: lr = {lr_at(s):.5f}")
lrs = np.array([lr_at(s) for s in range(steps)])
print(f"mean lr over the run: {lrs.mean():.5f} ({lrs.mean() / peak:.0%} of the peak)")

# Perplexity is exp(mean cross-entropy in nats): the effective number of choices per character.
for name, loss in [("uniform over 27", np.log(27)), ("bigram", 2.116), ("loss 1.0", 1.0)]:
    print(f"{name:16s} loss {loss:.3f} -> perplexity {np.exp(loss):.2f}")
p = np.array([0.9, 0.5, 0.05])                    # probability given to the true next character
print("per-character losses:", np.round(-np.log(p), 3).tolist(), " perplexity:", round(float(np.exp(-np.log(p).mean())), 2))
step   1: lr = 0.00006
step  25: lr = 0.00150
step  50: lr = 0.00300
step  51: lr = 0.00300
step 200: lr = 0.00249
step 326: lr = 0.00150
step 400: lr = 0.00088
step 600: lr = 0.00000
mean lr over the run: 0.00151 (50% of the peak)
uniform over 27  loss 3.296 -> perplexity 27.00
bigram           loss 2.116 -> perplexity 8.30
loss 1.0         loss 1.000 -> perplexity 2.72
per-character losses: [0.105, 0.693, 2.996]  perplexity: 3.54

The rate reaches the peak of 0.003 at step 50, is back at half the peak at step 326 (the midpoint of the cosine) and ends at 0. Averaged over the run it is 50% of the peak. The last line shows why perplexity punishes confident mistakes: one character predicted with probability 0.05 costs 2.996 nats, more than the other two together, and drags the perplexity of three characters to 3.54.

The model and the training loop

The model in PyTorch (recorded on a CPU, as every PyTorch example here): token embedding plus a learned position embedding for 32 positions, two pre-norm blocks with E=64E = 64, 4 heads and a GELU MLP of width 256, the final LayerNorm a pre-norm stack needs, and a linear head to 27 logits. nn.TransformerEncoder with a causal mask is a decoder-only stack (no cross-attention). Training: 600 steps of 32 random windows of 32 characters from the training part, AdamW at a peak of 0.003 with weight decay 0.01, the schedule above through LambdaLR (which multiplies the base rate by the factor the function returns), and scheduler.step() once per optimiser step.

The held-out loss is measured on every character of the tail exactly once: for each target, the 32 characters before it are the input (some of those are from the training part, which is fine; only the targets must be unseen), and the model's prediction at the last position is scored.

python · try it yourself
import math
text = (
    'the keeper of the light climbs the stairs at dusk. the lamp is cold, the glass is clean, and the sea is grey.\n'
    'she lights the lamp and the beam turns over the water. the boats see the beam and turn away from the rocks.\n'
    'at night the wind comes from the west. the wind shakes the door and the rain hits the glass.\n'
    'the keeper writes in her book: the wind is strong, the lamp is bright, the boats are safe.\n'
    'at dawn the sea is calm. the keeper puts out the lamp and walks down the stairs.\n'
    'she makes tea and bread and sits by the window. the gulls cry over the rocks.\n'
    'in the afternoon she cleans the glass and fills the lamp with oil.\n'
    'the sun goes down over the water. the keeper climbs the stairs at dusk.\n'
    'she lights the lamp and the beam turns over the sea. a small boat comes in from the north.\n'
    'the boat sees the beam and turns to the harbour. the keeper writes in her book: one boat, safe.\n'
    'at night the rain stops and the stars come out. the lamp turns and turns.\n'
    'at dawn the keeper puts out the lamp. the sea is green and the sky is clear.\n'
    'she walks down the stairs and makes tea. the gulls sit on the rocks in the sun.\n'
    'in the afternoon a letter comes from the town. the town will build a new lamp that needs no keeper.\n'
    'the keeper reads the letter and looks at the sea. then she climbs the stairs at dusk,\n'
    'lights the lamp, and writes in her book: the wind is soft, the lamp is bright, the boats are safe.\n'
)
import torch
from torch import nn
import torch.nn.functional as F

torch.manual_seed(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
chars = sorted(set(text))
stoi = {ch: i for i, ch in enumerate(chars)}
data = torch.tensor([stoi[ch] for ch in text])
V, n_train = len(chars), int(0.9 * len(data))
ctx = 32

class TinyLM(nn.Module):
    def __init__(self, V, ctx, E=64, heads=4, layers=2):
        super().__init__()
        self.tok = nn.Embedding(V, E)
        self.pos = nn.Embedding(ctx, E)                      # learned positions
        layer = nn.TransformerEncoderLayer(E, heads, dim_feedforward=4 * E, dropout=0.0,
                                           activation="gelu", batch_first=True, norm_first=True)
        self.blocks = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False)
        self.ln = nn.LayerNorm(E)                            # final LayerNorm of a pre-norm stack
        self.head = nn.Linear(E, V)

    def forward(self, idx):                                  # idx: (B, T) -> logits (B, T, V)
        T = idx.shape[1]
        x = self.tok(idx) + self.pos(torch.arange(T, device=idx.device))
        mask = nn.Transformer.generate_square_subsequent_mask(T, device=idx.device)
        return self.head(self.ln(self.blocks(x, mask=mask, is_causal=True)))

model = TinyLM(V, ctx).to(device)
print("device:", device, " parameters:", sum(p.numel() for p in model.parameters()))

steps, warmup, batch = 600, 50, 32
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.01)
def lr_factor(s):                                            # linear warm-up, then cosine to 0
    if s < warmup:
        return (s + 1) / warmup
    return 0.5 * (1 + math.cos(math.pi * (s - warmup) / (steps - warmup)))
sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_factor)

def batch_from(lo, hi, n, g):                                # random windows with all targets in [lo, hi)
    starts = torch.randint(lo, hi - ctx, (n,), generator=g)
    x = torch.stack([data[s:s + ctx] for s in starts])
    y = torch.stack([data[s + 1:s + ctx + 1] for s in starts])
    return x.to(device), y.to(device)

@torch.no_grad()
def tail_loss():                                             # every target in the held-out tail, once
    model.eval()
    targets = range(n_train, len(data))
    x = torch.stack([data[t - ctx:t] for t in targets])      # the ctx characters before each target
    logits = model(x.to(device))[:, -1]                      # prediction for the last position
    model.train()
    return F.cross_entropy(logits, data[n_train:].to(device)).item()

g = torch.Generator().manual_seed(0)
for step in range(steps):
    x, y = batch_from(0, n_train - 1, batch, g)
    lr = sched.get_last_lr()[0]                              # the rate used for this step
    loss = F.cross_entropy(model(x).reshape(-1, V), y.reshape(-1))
    opt.zero_grad()
    loss.backward()
    opt.step()
    sched.step()
    if step in (0, 49, 199, 399, 599):
        vl = tail_loss()
        print(f"step {step + 1:3d}  lr {lr:.5f}  train loss {loss.item():.3f}"
              f"  held-out loss {vl:.3f}  perplexity {math.exp(vl):.2f}")

@torch.no_grad()
def generate(prompt, n, temperature=None, seed=0):
    model.eval()
    g = torch.Generator().manual_seed(seed)
    idx = torch.tensor([[stoi[c] for c in prompt]])
    for _ in range(n):
        logits = model(idx[:, -ctx:].to(device))[0, -1]
        if temperature is None:                              # greedy: the most likely character
            nxt = logits.argmax().view(1, 1)
        else:
            probs = F.softmax(logits / temperature, dim=-1)
            nxt = torch.multinomial(probs.cpu(), 1, generator=g).view(1, 1)
        idx = torch.cat([idx, nxt.cpu()], dim=1)
    return "".join(chars[i] for i in idx[0].tolist())

print("greedy :", repr(generate("at dusk the keeper ", 60)))
print("T = 0.8:", repr(generate("at dusk the keeper ", 60, temperature=0.8)))
print("T = 1.5:", repr(generate("at dusk the keeper ", 60, temperature=1.5)))
device: cpu  parameters: 105627
step   1  lr 0.00006  train loss 3.569  held-out loss 3.537  perplexity 34.38
step  50  lr 0.00300  train loss 1.865  held-out loss 2.098  perplexity 8.15
step 200  lr 0.00249  train loss 0.594  held-out loss 1.097  perplexity 2.99
step 400  lr 0.00088  train loss 0.259  held-out loss 1.010  perplexity 2.74
step 600  lr 0.00000  train loss 0.203  held-out loss 1.002  perplexity 2.73
greedy : 'at dusk the keeper puts out the lamp. the sea is green and the sky is clear.\nsh'
T = 0.8: 'at dusk the keeper puts out the lamp. the sea is grey.\nshe lights the lamp and '
T = 1.5: 'at dusk the keeper puts out the lam: is bris bright, the boafe. see the boat ni'

Reading the log:

  • At step 1 the held-out perplexity is 34.38, worse than the uniform 27: random initial logits are not flat, and confident wrong guesses cost more than uniform ones.
  • After warm-up (step 50) the model is at 8.15, already about the bigram's 8.30. By the end the held-out loss is 1.002 nats, perplexity 2.73: about 3 times better than the bigram baseline. Most of the gain comes in the first 200 steps, while the rate is high; the cosine tail takes the loss down by another 0.095 nats (perplexity 2.99 to 2.73).
  • The training loss on the last batch is 0.203 against 1.002 held out: a 105,627-parameter model on 1262 characters memorises its training text. The held-out tail is also easy, because it repeats phrases from earlier ("climbs the stairs", "lights the lamp"). Both caveats are why a real language model is trained on many orders of magnitude more text and evaluated on text that is new in content, not only in position.

Sampling. Generation feeds the prompt, takes the logits of the last position, picks a character, appends it and repeats, cropping the input to the last 32 characters because the position table has 32 rows. Greedy decoding takes the argmax: here it recites a training sentence ("the sea is green and the sky is clear"), and on longer runs greedy decoding tends to loop. Sampling from softmax⁡(z/T)\operatorname{softmax}(z / T) with a fixed generator seed gives a different but still well-formed sentence at T=0.8T = 0.8, and at T=1.5T = 1.5 the flattened distribution produces misspellings such as "bris bright" and "boafe". Each step here recomputes attention over the whole window; real systems cache the keys and values of earlier positions instead (KV Cache).

Pitfalls

  • Forgetting the causal mask. Training loss drops almost to 0 within a few steps, because every position can read its own target in the input. If a language model looks too good, check the mask first.
  • Off-by-one targets. Predicting x[t] from x[:t + 1] (no shift) is the same bug in another form. Print one input and target pair as text, as in the first example.
  • Scoring held-out text with a random split. For sequences, hold out a contiguous block at the end (or whole documents).
  • Perplexities that are not comparable. Different tokenisers, different vocabularies, log base 2 vs ee, or the training set instead of held-out data all change the number. State all of them.
  • Scheduler stepped per epoch when the function is per step (or the reverse): the warm-up then lasts 50 epochs instead of 50 steps. Here there are no epochs at all, only steps.
  • Generating beyond the context. With learned positions, a sequence longer than the table crashes; crop to the last ctx tokens.
  • Weight decay on everything. AdamW here decays all parameters, which is fine for a toy. Large models usually exclude biases, LayerNorm scales and often embeddings by passing two parameter groups to the optimiser.

Practice

  1. A friend reports "perplexity 1.4" for the same model. What questions do you ask?
Answer

On which data (training batches or the held-out tail)? Computed how (exp of the mean loss in nats, or 2L2^L with LL in bits, or the mean of per-batch perplexities, which is not the same)? With which context (every target with a full 32-character prefix, or windows starting from scratch)? A training-batch loss of 0.203 would give e0.203=1.23e^{0.203} = 1.23, so a training-set number is the likely explanation.

  1. Without warm-up (the factor is 1 from step 0) and with the same peak, what would you expect, and how would you check it?
Answer

With this tiny pre-norm model, probably little difference, perhaps a noisier start; warm-up matters most for large models, high peaks and post-norm stacks. Check it by changing lr_factor to return the cosine part only and comparing the held-out loss curve with the same seeds. One run is not evidence: repeat with a few seeds before concluding.

  1. Write the line that computes the bigram baseline's perplexity on the training part instead of the tail. Will it be lower or higher than 8.30?
Answer

np.exp(-np.log(P[train[:-1], train[1:]]).mean()). Lower: it prints 7.77 here, because the counts were taken from that same text; the gap between the two is the bigram model's own (small) overfitting.

  1. Why does generate crop the input to the last 32 characters, and what would a model with sinusoidal positions or RoPE do differently?
Answer

The learned position table has only 32 rows, so position 32 has no embedding. Sinusoidal or rotary positions can be computed for any position, so the code would run on longer inputs, but the model was never trained on them and usually gets worse beyond the training length; cropping (a sliding window) is still the safe choice.

Test yourself

In next-character training, what is the target sequence for the input window x = text[s : s + T]?

  1. text[s : s + T]
  2. text[s + 1 : s + T + 1]
  3. text[s - 1 : s + T - 1]
  4. Only the character text[s + T]

The held-out loss is 1.002 nats per character. What is the perplexity?

  1. About 1.0
  2. About 2.72
  3. About 10
  4. About 27

Why is the learning rate warmed up at the start of transformer training?

  1. To save memory
  2. Because the first updates, with unreliable Adam statistics and random weights, can be large enough to destabilise training
  3. Because the causal mask is not ready
  4. To make the schedule end at 0

What does lowering the sampling temperature from 1.5 to 0.8 do?

  1. Makes the distribution flatter, so output is more varied
  2. Makes the distribution sharper, so output is closer to the most likely characters
  3. Changes the model's weights
  4. Shortens the context window

Training loss falls to almost 0 within a few steps on a new language model. What is the first thing to check?

  1. The learning rate is too low
  2. The causal mask (or the target shift): the model may be seeing its own targets
  3. The vocabulary is too small
  4. The temperature