Howwise RSS
AI & Automation7 min read

Large Language Model Vocabulary: How LLMs Handle 50k-200k Tokens

Short answer

Large language model vocabulary of 50k to 200k tokens is handled by predicting subword tokens, not words: the final hidden state is multiplied by one d_model x V matrix, softmax turns the V logits into probabilities, and context makes only a few candidates plausible.

Key takeaways
  • GPT models predict BPE subword tokens (50,257 in GPT-2, about 100k in cl100k_base, about 200k in o200k_base), and byte-level fallback means there is no out-of-vocabulary token.
  • The output layer is one matrix multiply, hidden state (d_model) times unembedding (d_model x V), giving V logits that softmax converts into probabilities.
  • It is not ImageNet: every position in trillions of tokens is a free label, token frequencies are Zipfian, and context leaves only a handful of plausible candidates.
  • Weight tying lets GPT-2 reuse the 50,257 x 768 embedding matrix (about 38.6M of 124M parameters) as the output projection.
  • The real cost of a big vocabulary is the batch x seq x V logits tensor and under-trained rare tokens, not the ability to classify.

What is large language model vocabulary, and what does the model predict?

A GPT-style model does not pick among dictionary words. Its large language model vocabulary is a fixed list of tokens, and the model predicts the next token, where a token is a subword piece produced by byte pair encoding (BPE). BPE starts from bytes and repeatedly merges the most frequent adjacent pairs until the vocabulary reaches a target size.

Common words such as ' the' become a single token. Rare words split into several pieces, for example 'unbelievability' might become 'un', 'believ', 'ability'. Because the base alphabet is the 256 possible bytes, any string, including emoji or a typo, can be encoded. There is no out-of-vocabulary case, only longer token sequences.

This is why 50,257 is not arbitrary: GPT-2 has 256 byte tokens, 50,000 learned merges, and one special token, <|endoftext|>. 256 + 50,000 + 1 = 50,257.

TokenizerUsed byVocabulary size (approx.)
gpt2 (r50k-style BPE)GPT-250,257
cl100k_baseGPT-3.5, GPT-4about 100k
o200k_baseGPT-4oabout 200k

How does the output layer turn a hidden state into 50k probabilities?

After the last transformer block, each position has a hidden vector of size d_model (768 for GPT-2 small). The unembedding matrix has shape d_model x V. Multiplying gives V raw scores called logits, one per vocabulary entry.

Softmax exponentiates the logits and normalizes them so they sum to 1. The result is a probability distribution, not a hard label. The model never 'chooses' a token internally; decoding does that afterwards.

The same forward pass produces logits at every position, so a sequence of length 100 yields 100 next-token predictions at once. That is what makes training so efficient.

  1. Tokenize the text into ids.
  2. Look up each id in the embedding matrix (V x d_model) to get input vectors.
  3. Run the transformer blocks to get a final hidden state per position.
  4. Multiply by the unembedding matrix to get V logits per position.
  5. Apply softmax to get probabilities, then pick a token by argmax or sampling.

How can I see the logits and top-5 probabilities myself?

This snippet loads GPT-2 small, prints the logits shape, and lists the five most likely next tokens. ' Paris' may or may not appear in the top 5; the exact probabilities depend on the model and library version, and the snippet shows how to inspect them. GPT-2 small is a weak model, so do not assume it puts most of the probability on the correct answer.

import torch
import tiktoken
from transformers import AutoTokenizer, AutoModelForCausalLM

enc = tiktoken.get_encoding("gpt2")
print(enc.n_vocab)                      # 50257
print(enc.encode("The capital of France is"))

tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2").eval()

inputs = tok("The capital of France is", return_tensors="pt")
with torch.no_grad():
    logits = model(**inputs).logits
print(logits.shape)                     # torch.Size([1, 5, 50257])

probs = torch.softmax(logits[0, -1], dim=-1)   # last position only
print(float(probs.sum()))               # 1.0
top = torch.topk(probs, 5)
for p, i in zip(top.values, top.indices):
    print(repr(tok.decode(int(i))), round(float(p), 4))

# weight tying check
print(model.lm_head.weight.data_ptr() == model.transformer.wte.weight.data_ptr())  # True
Tip: Take logits at position -1 for the next token. Position i predicts token i+1, so the earlier positions are predictions for tokens you already supplied.

Why is a 100k-way prediction not like ImageNet?

ImageNet has 1,000 classes, one hard correct label per image, and roughly 1.3M labelled images. A language model has a different data situation: self-supervision makes every position in the text a labelled example. A corpus of 1 trillion tokens is 1 trillion training examples, about 10 million per vocabulary entry on average.

Frequencies follow Zipf's law: a few thousand tokens (punctuation, ' the', ' of', common suffixes) account for most of the text. The head is seen constantly, while the tail is rare and mostly matters in specific contexts.

Context also does most of the work. After 'The capital of France is', only a handful of tokens (for example ' the', ' a', ' located', and for stronger models ' Paris') typically carry meaningful probability. The effective branching factor is tiny compared with V.

Finally, tokens are not independent one-hot classes. Each has an embedding, and similar tokens (' Paris', ' London') get similar vectors and similar gradient updates, so learning about one helps the others.

AspectImageNet classifierLanguage model
Classes1,00050k to 200k tokens
Labels per exampleOne hard labelSoft, many continuations valid
Label sourceHuman annotationFree, from the text itself
ExamplesAbout 1.3M imagesTrillions of token positions
Class relationshipsIndependent outputsShared embedding structure

How is it trained, and what do loss and perplexity mean?

Training minimizes cross-entropy between the predicted distribution and the true next token: loss = -log p(true token). If the model gives the true token probability 0.25, the loss is ln 4 ≈ 1.39.

Perplexity is exp(loss). A loss of 3.0 gives perplexity of about 20, meaning the model is on average as uncertain as if it were choosing uniformly among about 20 tokens. A uniform guess over GPT-2's vocabulary would give loss ln(50,257) ≈ 10.82, perplexity 50,257. That is where an untrained model starts, and a trained one falls to a perplexity of tens, a small fraction of V.

Many continuations are valid, so the target is calibrated probabilities, not a single right answer. The model is rewarded for putting mass on all plausible next tokens in proportion to how often they occur.

How do temperature, top-k and top-p pick a token?

Decoding turns the distribution into one token. Temperature divides logits by T before softmax: T below 1 sharpens the distribution, T above 1 flattens it. Top-k keeps only the k highest-probability tokens and renormalizes. Top-p (nucleus) keeps the smallest set whose cumulative probability reaches p.

Both truncations cut the long tail, where 50,000 tokens might jointly hold a few percent of mass made of poor choices. Sampling from it occasionally yields nonsense, which is why these filters exist.

def sample(logits, T=0.8, k=50, p=0.95):
    logits = logits / T
    topv, topi = torch.topk(logits, k)          # top-k trims the tail
    probs = torch.softmax(topv, dim=-1)
    cum = torch.cumsum(probs.sort(descending=True).values, 0)
    keep = cum - probs.sort(descending=True).values < p   # top-p
    order = probs.argsort(descending=True)
    probs = probs[order] * keep
    probs = probs / probs.sum()
    return topi[order][torch.multinomial(probs, 1)]

What does a big vocabulary really cost?

Parameters first. GPT-2 small has 50,257 x 768 ≈ 38.6M embedding weights out of about 124M total. Weight tying reuses that matrix as the output projection, so the vocabulary is paid for once. Many larger models untie them, which doubles that cost.

Memory is the bigger issue in training. The logits tensor is batch x seq x V. With batch 8, sequence 4,096 and V = 128,000 in float32, that is 8 x 4096 x 128000 x 4 bytes ≈ 16.8 GB, before the softmax copy and gradients. This can exceed the memory of the whole transformer body's activations.

Fixes include fused or chunked cross-entropy (computing the loss in slices of positions so full logits never exist at once), computing logits in bf16 with an fp32 loss, and, at inference, computing logits only for the last position. Older approaches avoided the full softmax: hierarchical softmax, adaptive softmax (frequent tokens in a cheap head, rare ones in clusters) and sampled softmax. Modern LLMs mostly use the full softmax with the memory fixes, because GPUs handle the matmul well.

The trade-off is about tokenization efficiency. A larger vocabulary means fewer tokens per text, so shorter sequences, cheaper attention and better multilingual and code efficiency. But embeddings grow, and rare tokens get few updates, leaving some under-trained. Glitch tokens such as ' SolidGoldMagikarp' were tokens in the vocabulary that barely appeared in training, so their embeddings stayed near-random and produced odd behavior. A smaller vocabulary avoids that but yields longer sequences.

VocabularyBenefitCost
Smaller (about 32k)Smaller embeddings and logits, fewer weak tokensLonger sequences, worse for non-English and code
Larger (100k to 200k)Shorter sequences, better multilingual coverageBigger logits tensor, more under-trained rare tokens
Warning: Computing full logits for a long sequence during training can cause out-of-memory crashes. Reduce the micro-batch or use chunked cross-entropy before assuming the model body is the problem.

Common questions

Does the model need to have seen every word?

No. Unseen words are split into known subwords or, in the worst case, raw bytes. The model can still read and generate them, though rare strings cost more tokens.

Why is GPT-2's vocabulary 50,257 and not a round number?

It is 256 byte-level base tokens plus 50,000 BPE merges plus one special end-of-text token. The count is a result of the merge budget, not a design target.

Does the model search a dictionary to find the next word?

No. It multiplies the final hidden state by the unembedding matrix to get one score per token, then applies softmax. In GPT-2 that matrix is tied to the input embedding table, but many other models use a separate one, and there is no lookup or search over a word list.

Is softmax over 200k tokens slow at inference?

It is usually a small share of the compute per generated token, since the matmul is d_model x V against much larger transformer layers. It matters more for small models, where the output layer can be a sizable fraction of total parameters.

Why do different models have different tokenizers?

Each tokenizer is trained on a chosen corpus with a chosen merge budget. Models trained on more multilingual or code-heavy data benefit from a larger vocabulary, so ids and token counts are not interchangeable between models.

Related topics:llmtokenizationsoftmaxbpegpt-2