TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Pretraining a Tiny GPT with Your Own Tokenizer

Pretraining a Tiny GPT with Your Own Tokenizer

Training a Tiny Character Transformer trained a decoder on one 1403-character text, one character per token, with random windows as batches. Real pretraining differs in three ways that this lesson adds, one at a time: a subword tokenizer trained on the corpus, a data pipeline that turns many documents into packed, shuffled blocks with end-of-sequence separators and an honest document-level split, and an evaluation against baselines in units that can be compared across tokenizers. Everything is small enough to run in seconds: a corpus of 1000 short documents, a 237-token BPE vocabulary and a 119,360-parameter model. The objective is the causal LM of Pretraining Objectives.

The corpus and the tokenizer

The corpus is written for this lesson: daily log entries of a mountain hut, generated from templates with a seeded random generator, one document per day. Templated text is far more predictable than real text, which is exactly what makes it useful here: we can compute how predictable it is, so we know the best loss any model could reach.

The tokenizer is byte-pair encoding as in Byte-Pair Encoding from Scratch, in a compact version: split text into words that keep their leading space (GPT-2's convention), start from single characters, and repeatedly merge the most frequent adjacent pair, 200 times. Encoding applies the learned merges in the order they were learned. The pipeline then:

  1. Splits by document before anything is fitted: 900 training documents, 100 validation documents. The tokenizer and the baselines see only the training documents.
  2. Encodes each document and appends an <eos> token, so the model learns where documents end and that the text after <eos> is unrelated to the text before it.
  3. Packs the concatenated stream into fixed blocks of 64 tokens (plus one for the shifted targets), with no padding: a block may contain the end of one document and the start of the next.
  4. Shuffles the blocks, so consecutive batches do not come from neighbouring documents.
python · try it yourself
import math
import numpy as np
import random
import re
from collections import Counter

def make_corpus(n_docs=1000, seed=0):
    """Original toy corpus: daily log entries of a mountain hut, one document per day."""
    r = random.Random(seed)
    days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
    weather = ["clear and cold", "windy with low cloud", "warm and sunny", "foggy until noon",
               "snowing lightly", "rainy all afternoon"]
    trails = ["the north trail is open", "the north trail is closed after a rock fall",
              "the ridge path is icy near the top", "the lake path is muddy but safe", "the forest road is clear"]
    events = ["{n} walkers stayed the night", "a group of {n} climbers left at dawn for the summit",
              "the warden checked the radio and the first aid kit", "the water pump froze and was repaired by noon",
              "two goats were seen near the upper lake", "supplies arrived by mule in the morning",
              "{n} hikers asked about the weather for tomorrow"]
    advice = ["walkers should carry warm clothes and a map.", "do not start the ridge after two in the afternoon.",
              "the hut kitchen is open from six to nine.", "please close the gate behind the goats."]
    docs = []
    for i in range(n_docs):
        e1, e2 = r.sample(events, 2)
        docs.append(f"{days[i % 7]}. the weather was {r.choice(weather)}. {r.choice(trails)}. "
                    f"{e1.format(n=r.randint(2, 19))}. {e2.format(n=r.randint(2, 19))}. {r.choice(advice)}")
    return docs

PRE = re.compile(r" ?[a-z]+| ?[0-9]+| ?[^\sa-z0-9]")       # GPT-2 style: a word keeps its leading space

def train_bpe(texts, n_merges):
    words = Counter(w for t in texts for w in PRE.findall(t))
    splits = {w: list(w) for w in words}
    vocab = sorted({c for w in words for c in w})
    merges = []
    for _ in range(n_merges):
        pairs = Counter()
        for w, f in words.items():
            s = splits[w]
            for a, b in zip(s, s[1:]):
                pairs[a, b] += f
        if not pairs:
            break
        (a, b), _ = max(pairs.items(), key=lambda kv: (kv[1], kv[0]))   # most frequent, ties broken by the pair
        merges.append((a, b))
        vocab.append(a + b)
        for w, s in splits.items():
            i, out = 0, []
            while i < len(s):
                if i + 1 < len(s) and s[i] == a and s[i + 1] == b:
                    out.append(a + b); i += 2
                else:
                    out.append(s[i]); i += 1
            splits[w] = out
    return merges, vocab

def make_encoder(merges, vocab):
    rank = {m: i for i, m in enumerate(merges)}
    stoi = {t: i for i, t in enumerate(vocab)}
    cache = {}
    def encode_word(w):
        if w not in cache:
            s = list(w)
            while len(s) > 1:                                      # apply the earliest-learned merge first
                best = min(range(len(s) - 1), key=lambda i: rank.get((s[i], s[i + 1]), 1e9))
                if (s[best], s[best + 1]) not in rank:
                    break
                s[best:best + 2] = [s[best] + s[best + 1]]
            cache[w] = [stoi[t] for t in s]
        return cache[w]
    return lambda text: [i for w in PRE.findall(text) for i in encode_word(w)]

docs = make_corpus()
rng = np.random.default_rng(0)
order = rng.permutation(len(docs))
train_docs = [docs[i] for i in order[:900]]          # split by DOCUMENT, before anything is fitted
val_docs = [docs[i] for i in order[900:]]
print(f"{len(docs)} documents, {sum(map(len, docs))} characters; train {len(train_docs)}, validation {len(val_docs)}")
print("example:", docs[0])

merges, vocab = train_bpe(train_docs, n_merges=200)   # tokenizer fitted on training documents only
EOS = len(vocab); vocab.append("<eos>")
encode = make_encoder(merges, vocab[:-1])
print(f"vocabulary {len(vocab)} = {len(vocab) - 201} characters + 200 merges + <eos>; first merges: {merges[:6]}")
print("tokens:", [vocab[i] for i in encode("the ridge path is icy near the summit.")])

def to_stream(ds):                                    # documents joined with an end-of-sequence token
    return np.array([t for d in ds for t in encode(d) + [EOS]])
train, val = to_stream(train_docs), to_stream(val_docs)
chars_val = sum(len(d) + 1 for d in val_docs)         # +1: count <eos> as one character (a document break)
print(f"train {len(train)} tokens, validation {len(val)} tokens, {chars_val / len(val):.2f} characters per token")

# Packing: cut the stream into fixed blocks of ctx + 1 tokens (inputs and shifted targets), then shuffle.
ctx = 64
n_blocks = (len(train) - 1) // ctx
blocks = train[:n_blocks * ctx + 1]
X = np.stack([blocks[i * ctx:(i + 1) * ctx] for i in range(n_blocks)])
Y = np.stack([blocks[i * ctx + 1:(i + 1) * ctx + 1] for i in range(n_blocks)])
perm = rng.permutation(n_blocks)
X, Y = X[perm], Y[perm]
print(f"{n_blocks} packed blocks of {ctx}; <eos> tokens inside the first block: {int((X[0] == EOS).sum())}")

# Baselines on the validation stream (fitted on training tokens, add-0.1 smoothing).
V = len(vocab)
uni = np.bincount(train, minlength=V) + 0.1
uni_nll = -np.log(uni[val[1:]] / uni.sum()).mean()
big = np.full((V, V), 0.1)
np.add.at(big, (train[:-1], train[1:]), 1)
big_nll = -np.log(big[val[:-1], val[1:]] / big[val[:-1]].sum(1)).mean()
for name, nll in [("unigram", uni_nll), ("bigram", big_nll)]:
    per_char = nll * (len(val) - 1) / chars_val
    print(f"{name}: {nll:.3f} nats/token, perplexity {math.exp(nll):.2f}, {per_char:.3f} nats/character")

# For comparison with character models: a character bigram on the same split.
tr_c, va_c = "\n".join(train_docs), "\n".join(val_docs)
chars = sorted(set(tr_c) | set(va_c))
ci = {c: i for i, c in enumerate(chars)}
cb = np.full((len(chars), len(chars)), 0.1)
np.add.at(cb, ([ci[c] for c in tr_c[:-1]], [ci[c] for c in tr_c[1:]]), 1)
a, b = [ci[c] for c in va_c[:-1]], [ci[c] for c in va_c[1:]]
print(f"character bigram: {-np.log(cb[a, b] / cb[a].sum(1)).mean():.3f} nats/character")

# The floor: the generator's own entropy (day, weather, trail, two ordered events, the numbers, advice).
H_doc = (math.log(7) + math.log(6) + math.log(5) + math.log(7 * 6)
         + 2 * (3 / 7) * math.log(18) + math.log(4))     # 3 of 7 events contain a number from 2 to 19
print(f"entropy of the generator: about {H_doc:.2f} nats per document = {H_doc * len(val_docs) / (len(val) - 1):.3f} nats/token")
1000 documents, 208701 characters; train 900, validation 100
example: monday. the weather was foggy until noon. the north trail is open. 10 hikers asked about the weather for tomorrow. the water pump froze and was repaired by noon. please close the gate behind the goats.
vocabulary 237 = 36 characters + 200 merges + <eos>; first merges: [('t', 'h'), ('th', 'e'), (' ', 'the'), (' ', 'w'), (' ', 'a'), ('e', 'r')]
tokens: ['the', ' ridge', ' path', ' is', ' i', 'c', 'y', ' near', ' the', ' summit', '.']
train 56629 tokens, validation 6225 tokens, 3.37 characters per token
884 packed blocks of 64; <eos> tokens inside the first block: 1
unigram: 4.434 nats/token, perplexity 84.25, 1.317 nats/character
bigram: 1.039 nats/token, perplexity 2.83, 0.308 nats/character
character bigram: 1.983 nats/character
entropy of the generator: about 12.95 nats per document = 0.208 nats/token

What the numbers say:

  • The first merges are t h, then th e, then a space with "the": the most frequent word of the corpus becomes a single token after three merges. "summit" becomes one token, while "icy", rarer in the training documents, is still split into i c y. 200 merges compress the text to 3.37 characters per token: the model sees 3.4 times shorter sequences than a character model, so the same 64-token context covers about 215 characters.
  • The packed blocks contain document boundaries (one <eos> in the first block). With attention over the whole block, a token may attend to the previous document; for unrelated documents the model learns to ignore what lies before <eos>. Some pipelines block attention across documents instead (a "document mask"), which matters more for long contexts.
  • Baselines on the validation stream: a unigram model (token frequencies) gets perplexity 84.25, a bigram model 2.83. The bigram is already strong because the templates are rigid.
  • Comparable units. Perplexity per token depends on the tokenizer, so it cannot be compared with a character model's perplexity. Nats per character can: total loss divided by the number of characters. The token bigram reaches 0.308 nats per character, a character bigram on the same split 1.983: a bigram over subwords sees far more context than a bigram over characters.
  • The floor. Each document makes about 12.95 nats of random choices (day, weather, trail, two events and their numbers, advice), which spread over the validation tokens is 0.208 nats per token. No model can do better on average; a perfect model of the generator would reach it.

The schedule

The training run uses a linear warm-up over the first 10% of the steps and a cosine decay to zero, the usual pretraining schedule, here as a LambdaLR factor on AdamW's peak rate. The lab draws the four classic schedules with an illustrative loss (a toy formula, not this model; see Learning-Rate Scheduling): pick a warm-up length and compare where each schedule ends.

0.000.050.10020406080100ηLearning rate η per epoch012020406080100epochlossLoss (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.074warm-up + cosine: 0.076

Warm-up protects the start: with Adam, the first updates are taken with poorly estimated second moments and a randomly initialised network, and a full-size step can push the weights into a region from which training recovers slowly or diverges. The cosine tail then takes smaller and smaller steps, which lowers the loss at the end. In the lab's toy formula the final losses are 0.170 for a constant rate, 0.089 for step decay, 0.074 for cosine and 0.076 for warm-up plus cosine: decaying the rate is what matters, and warm-up costs a little there because the toy loss has no instability for it to prevent. In real training it is the instability that warm-up is for.

Pretraining the model

The recorded example repeats the corpus, the BPE functions and the pipeline (each recorded example runs on its own), then trains a decoder-only transformer: token embeddings tied to the output layer, learned positions for 64 tokens, two pre-norm blocks with E=64E = 64 and 4 heads built from nn.TransformerEncoderLayer with a causal mask (the same construction as the deep-learning lesson), AdamW with peak rate 3⋅10−33 \cdot 10^{-3} and weight decay 0.1, gradient clipping at 1.0, and 300 steps of 32 blocks with the blocks reshuffled at every epoch. The embeddings are initialised with standard deviation 0.02 (GPT-2's choice): with PyTorch's default N(0,1)\mathcal{N}(0, 1) and tied weights, the first logits are huge and the initial loss is far above ln⁡V\ln V.

python · try it yourself
import math
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import random
import re
from collections import Counter

def make_corpus(n_docs=1000, seed=0):
    """Original toy corpus: daily log entries of a mountain hut, one document per day."""
    r = random.Random(seed)
    days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
    weather = ["clear and cold", "windy with low cloud", "warm and sunny", "foggy until noon",
               "snowing lightly", "rainy all afternoon"]
    trails = ["the north trail is open", "the north trail is closed after a rock fall",
              "the ridge path is icy near the top", "the lake path is muddy but safe", "the forest road is clear"]
    events = ["{n} walkers stayed the night", "a group of {n} climbers left at dawn for the summit",
              "the warden checked the radio and the first aid kit", "the water pump froze and was repaired by noon",
              "two goats were seen near the upper lake", "supplies arrived by mule in the morning",
              "{n} hikers asked about the weather for tomorrow"]
    advice = ["walkers should carry warm clothes and a map.", "do not start the ridge after two in the afternoon.",
              "the hut kitchen is open from six to nine.", "please close the gate behind the goats."]
    docs = []
    for i in range(n_docs):
        e1, e2 = r.sample(events, 2)
        docs.append(f"{days[i % 7]}. the weather was {r.choice(weather)}. {r.choice(trails)}. "
                    f"{e1.format(n=r.randint(2, 19))}. {e2.format(n=r.randint(2, 19))}. {r.choice(advice)}")
    return docs

PRE = re.compile(r" ?[a-z]+| ?[0-9]+| ?[^\sa-z0-9]")       # GPT-2 style: a word keeps its leading space

def train_bpe(texts, n_merges):
    words = Counter(w for t in texts for w in PRE.findall(t))
    splits = {w: list(w) for w in words}
    vocab = sorted({c for w in words for c in w})
    merges = []
    for _ in range(n_merges):
        pairs = Counter()
        for w, f in words.items():
            s = splits[w]
            for a, b in zip(s, s[1:]):
                pairs[a, b] += f
        if not pairs:
            break
        (a, b), _ = max(pairs.items(), key=lambda kv: (kv[1], kv[0]))   # most frequent, ties broken by the pair
        merges.append((a, b))
        vocab.append(a + b)
        for w, s in splits.items():
            i, out = 0, []
            while i < len(s):
                if i + 1 < len(s) and s[i] == a and s[i + 1] == b:
                    out.append(a + b); i += 2
                else:
                    out.append(s[i]); i += 1
            splits[w] = out
    return merges, vocab

def make_encoder(merges, vocab):
    rank = {m: i for i, m in enumerate(merges)}
    stoi = {t: i for i, t in enumerate(vocab)}
    cache = {}
    def encode_word(w):
        if w not in cache:
            s = list(w)
            while len(s) > 1:                                      # apply the earliest-learned merge first
                best = min(range(len(s) - 1), key=lambda i: rank.get((s[i], s[i + 1]), 1e9))
                if (s[best], s[best + 1]) not in rank:
                    break
                s[best:best + 2] = [s[best] + s[best + 1]]
            cache[w] = [stoi[t] for t in s]
        return cache[w]
    return lambda text: [i for w in PRE.findall(text) for i in encode_word(w)]

torch.manual_seed(0)
docs = make_corpus()
order = np.random.default_rng(0).permutation(len(docs))
train_docs, val_docs = [docs[i] for i in order[:900]], [docs[i] for i in order[900:]]
merges, vocab = train_bpe(train_docs, n_merges=200)
EOS = len(vocab); vocab.append("<eos>")
encode = make_encoder(merges, vocab[:-1])
stream = lambda ds: torch.tensor([t for d in ds for t in encode(d) + [EOS]])
train, val = stream(train_docs), stream(val_docs)
chars_val = sum(len(d) + 1 for d in val_docs)
V, ctx = len(vocab), 64

class TinyGPT(nn.Module):
    def __init__(self, V, ctx, E=64, heads=4, layers=2):
        super().__init__()
        self.tok, self.pos = nn.Embedding(V, E), nn.Embedding(ctx, E)
        layer = nn.TransformerEncoderLayer(E, heads, 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, self.head = nn.LayerNorm(E), nn.Linear(E, V, bias=False)
        self.head.weight = self.tok.weight                       # tied input and output embeddings
        nn.init.normal_(self.tok.weight, std=0.02)               # GPT-2's small init keeps first logits near 0
        nn.init.normal_(self.pos.weight, std=0.02)

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

model = TinyGPT(V, ctx)
print(f"vocabulary {V}, train {len(train)} tokens, validation {len(val)} tokens, "
      f"parameters {sum(p.numel() for p in model.parameters()):,}")

# Packed blocks, reshuffled every epoch; validation packed the same way (no shuffling needed).
def blocks(s):
    n = (len(s) - 1) // ctx
    return s[:n * ctx].view(n, ctx), s[1:n * ctx + 1].view(n, ctx)
Xtr, Ytr = blocks(train)
Xva, Yva = blocks(val)

steps, warmup, batch = 300, 30, 32
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.1)
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: (s + 1) / warmup if s < warmup
                                          else 0.5 * (1 + math.cos(math.pi * (s - warmup) / (steps - warmup))))

@torch.no_grad()
def val_loss():
    model.eval()
    l = F.cross_entropy(model(Xva).reshape(-1, V), Yva.reshape(-1)).item()
    model.train()
    return l

g = torch.Generator().manual_seed(0)
perm, pos = torch.randperm(len(Xtr), generator=g), 0
for step in range(steps):
    if pos + batch > len(perm):                                  # new epoch: reshuffle the blocks
        perm, pos = torch.randperm(len(Xtr), generator=g), 0
    i = perm[pos:pos + batch]; pos += batch
    loss = F.cross_entropy(model(Xtr[i]).reshape(-1, V), Ytr[i].reshape(-1))
    opt.zero_grad(); loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    opt.step(); sched.step()
    if step in (0, 29, 99, 299):
        vl = val_loss()
        print(f"step {step + 1:3d}  train {loss.item():.3f}  val {vl:.3f} nats/token  perplexity {math.exp(vl):6.2f}")
vl = val_loss()
n_scored = Yva.numel()
chars_scored = chars_val * n_scored / (len(val) - 1)            # characters covered by the scored tokens
print(f"validation: {vl * n_scored / chars_scored:.3f} nats/character over {n_scored} tokens")

@torch.no_grad()
def sample(prompt, n=40, temperature=0.8, seed=0):
    model.eval()
    g = torch.Generator().manual_seed(seed)
    idx = torch.tensor([encode(prompt)])
    for _ in range(n):
        p = F.softmax(model(idx[:, -ctx:])[0, -1] / temperature, -1)
        nxt = torch.multinomial(p, 1, generator=g)
        if nxt.item() == EOS:
            break
        idx = torch.cat([idx, nxt.view(1, 1)], 1)
    return "".join(vocab[i] for i in idx[0].tolist())

print(sample("friday. the weather was"))
print(sample("sunday. the"))
vocabulary 237, train 56629 tokens, validation 6225 tokens, parameters 119,360
step   1  train 5.456  val 5.445 nats/token  perplexity 231.56
step  30  train 4.080  val 3.999 nats/token  perplexity  54.55
step 100  train 0.464  val 0.455 nats/token  perplexity   1.58
step 300  train 0.231  val 0.257 nats/token  perplexity   1.29
validation: 0.076 nats/character over 6208 tokens
friday. the weather was foggy until noon. the ridge path is icy near the top. 19 hikers asked about the weather for tomorrow. 4 walkers stayed the night
sunday. the weather was warm and sunny. the north trail is open. the warden checked the radio and the first aid kit. a group of 18 climbers left at dawn for the summit. walkers s
  • Start: loss 5.445 nats per token, perplexity 231.56, close to the uniform ln⁡237=5.47\ln 237 = 5.47: the small initialisation works as intended.
  • After warm-up (step 30) the model has passed the unigram baseline (perplexity 54.55 against 84.25) but is far from the bigram's 2.83. By step 100 it is at 1.58, better than the bigram.
  • End: 0.257 nats per token on the 100 unseen documents, perplexity 1.29, close to the floor of 0.208 computed from the generator. Training and validation loss are almost equal (0.231 and 0.257): with 56,629 training tokens of templated text there is little to overfit.
  • In nats per character the model reaches 0.076, against 0.308 for the token bigram and 1.983 for the character bigram on the same text.
  • Samples at temperature 0.8 are well-formed log entries with plausible combinations ("the ridge path is icy near the top", "a group of 18 climbers left at dawn for the summit"). The second sample stops mid-word because the 40-token limit was reached.

Honest comparison with the character model

The character model of the deep-learning course ended at 1.002 nats per character on its held-out tail; this model reaches 0.076. That gap is not the tokenizer's achievement. The texts differ completely: the lighthouse story is free prose of 1403 characters, this corpus is 208,701 characters from a handful of templates, with a floor of 0.208 nats per token. The fair comparisons are within one corpus: here, the same split under a character bigram (1.983), a token bigram (0.308) and the transformer (0.076 nats per character). What subword tokens do buy, at equal model and context size, is a longer effective context (64 tokens cover about 215 characters instead of 64) and fewer steps per sentence at generation time. What they cost is a tokenizer to train and maintain, words split in arbitrary places ("icy" into three tokens), and perplexities that cannot be compared across tokenizers.

Pitfalls

  • Training the tokenizer on validation or test text. The tokenizer is fitted like any preprocessing step: on the training documents only.
  • Splitting by blocks instead of documents. Packed blocks from the same document on both sides of the split leak phrasing and content; split documents first, then pack each side.
  • No separator between documents. Without <eos>, the model learns that the start of one log entry continues the previous one, and at generation time it never knows when to stop.
  • Perplexity across tokenizers. Report nats (or bits) per character or per byte when tokenizers differ, and always on held-out documents.
  • Default embedding initialisation with tied weights. N(0,1)\mathcal{N}(0, 1) embeddings make the first logits enormous (an initial loss of 50 or more instead of about ln⁡V\ln V); use a small standard deviation.
  • Concluding from templated data. A model that nearly reaches the floor of a template generator has learned the templates; it says nothing about real language. Templates are a debugging tool for the pipeline, not a benchmark.

Practice

  1. In ptg1.py, change n_merges to 50 and to 400. How do the characters per token and the bigram perplexity change, and why can't the perplexities be compared directly?
Answer

With fewer merges the tokens are shorter (fewer characters per token) and each token is easier to predict, so per-token perplexity drops; with more merges, the reverse. Each perplexity is per token, and the tokens differ, so only the nats-per-character values are comparable.

  1. Why is the <eos> token counted as one character in chars_val?
Answer

The models must predict it (it is a real token in the stream), so its loss is included in the total. Counting it as one "character", the document break, keeps the per-character normalisation consistent for token and character models: each predicts the same document boundaries.

  1. Compute the floor of the generator per document if the advice sentence were always the same. How many nats per token would that save on the validation set?
Answer

The advice contributes ln⁡4=1.386\ln 4 = 1.386 nats per document. Without it, 12.95−1.39=11.5612.95 - 1.39 = 11.56 nats per document; over the validation set that saves 1.386⋅100/6224≈0.0221.386 \cdot 100 / 6224 \approx 0.022 nats per token.

  1. The model has 119,360 parameters and saw 300⋅32⋅64=614,400300 \cdot 32 \cdot 64 = 614{,}400 tokens. How many epochs over the training stream is that, and how many tokens per parameter?
Answer

614,400/56,629≈10.8614{,}400 / 56{,}629 \approx 10.8 epochs, and 614,400/119,360≈5.1614{,}400 / 119{,}360 \approx 5.1 tokens per parameter. Large pretraining runs usually see each token about once and use about 20 or more tokens per parameter (Scaling Laws).

Test yourself

When should the train/validation split be made in a pretraining pipeline?

  1. After packing, by randomly choosing blocks
  2. By document, before the tokenizer or any statistic is fitted
  3. After training the tokenizer on all the text
  4. It is not needed for language models

What is the purpose of the <eos> token between packed documents?

  1. Padding
  2. It marks document boundaries, so the model learns where texts end and that what follows is unrelated
  3. It separates the input from the target
  4. It is the masked token

Why report nats per character rather than perplexity per token when comparing the subword model with a character model?

  1. Characters are easier to count
  2. Per-token perplexity depends on the tokenizer; per-character loss measures the same text in the same units
  3. Perplexity cannot be computed for subwords
  4. Nats per character are always smaller

The tiny GPT reached 0.257 nats per token on validation. The generator's floor is 0.208. What does that mean?

  1. The model overfits
  2. The model is close to the best possible average loss on this data
  3. The model is broken: the loss should be 0
  4. The tokenizer is too small

Why are the embeddings initialised with standard deviation 0.02 when the output layer is tied to them?

  1. To save memory
  2. With N(0,1)\mathcal{N}(0, 1) the first logits are huge and the initial loss far above ln⁡V\ln V
  3. It is required by nn.TransformerEncoderLayer
  4. To make the model deterministic