Key ideas
- Goal. A language model gives the probability of the next token given the previous ones, and by the chain rule the probability of a whole sequence: .
- Self-supervised. The targets (the next token, or a masked token) come from raw text, so no human labels are needed; that is why LMs can be pretrained on huge corpora4.
- n-gram models make a Markov assumption: an -gram model conditions on the last
words, so it is a Markov model of order (bigram = first order)1. Its
probabilities are maximum-likelihood count ratios, with
<s>and</s>marking sentence start and end1. - Sparsity. There are possible -grams, so the tables become huge and mostly
zero; longer contexts help only with enough data3. An unseen n-gram gets probability 0
and zeroes out the whole sentence, hence smoothing1:
- Laplace (add-one): add 1 to every count;
- interpolation: mix trigram, bigram and unigram estimates with weights summing to 1;
- backoff: use the shorter context only when the longer one has no counts;
- Good–Turing: unseen words together get probability ( = number of types seen once, = tokens), and a count becomes ; the must be smoothed first, since for the largest counts7.
- Kneser–Ney2 subtracts a fixed discount from every seen count (absolute discounting) and gives the freed mass to a continuation probability: how many different words follows, not how often occurs. "Kong" is frequent but follows almost only "Hong" (like "Francisco" after "San"), so it gets little mass in new contexts.
- Neural LMs replace counts with learned functions of embeddings. A Transformer decoder
with a causal mask (each position attends only to earlier ones) is the standard
left-to-right LM; it is trained by teacher forcing, predicting every next token of a text in
one parallel pass, and the LM head turns each hidden state into logits over the
vocabulary4. In Hugging Face,
DataCollatorForLanguageModeling(mlm=False)copies the inputs as labels and the model shifts them by one6. - Masked LMs (BERT, an encoder) see both sides and predict tokens hidden at random,
15% of positions in BERT, mostly replaced by
[MASK]; only those positions enter the loss, which makes training less sample-efficient5. They are not used to generate text left to right5. - RNN LMs are often trained on windows of
num_stepstokens cut from a long text3; if each window starts from a zero state, a training prediction can use at mostnum_stepstokens of context. - Decoding4: greedy takes the argmax every step (deterministic, repetitive); temperature divides the logits by ( sharpens, flattens); top-k keeps the most likely tokens and renormalizes; top-p (nucleus) keeps the smallest set whose probabilities sum to at least . Generation is sequential: one forward pass per new token.
Formulas
- Bigram MLE1: ; add-one: .
- Interpolation1: , .
- Temperature4: .
- MLM loss: , unmasked positions contribute nothing5.
Perplexity is the inverse probability of the test text normalized by its length, i.e. the exponential of the average negative log-likelihood per token1,3:
Lower is better: a perfect model scores 1, and a uniform guess over tokens scores 3.
Worked example
Train a bigram model on three sentences: <s> I like green tea </s>, <s> I like tea </s>,
<s> you like green tea </s>.
- , , , , .
- .
- Perplexity over the predicted tokens (including
</s>): . - "you like tea": , perplexity .
- Add-one with (I, like, green, tea, you,
</s>): , down from the MLE .
In code
import torch
logits = torch.tensor([2.0, 1.0, 0.0, -1.0])
for T in (1.0, 0.5, 2.0): # 1.0: [0.644 0.237 0.087 0.032] 0.5: [0.865 0.117 0.016 0.002]
print(T, torch.softmax(logits / T, dim=-1).numpy().round(3)) # 2.0: [0.455 0.276 0.167 0.102]
p = torch.softmax(logits, dim=-1)
topk = torch.where(p >= p.topk(2).values[-1], p, 0) # keep the 2 most likely tokens
print("top-k:", (topk / topk.sum()).numpy().round(3)) # [0.731 0.269 0. 0. ]
s, idx = p.sort(descending=True)
keep = (s.cumsum(0) - s) < 0.9 # smallest prefix with mass >= 0.9
nucleus = torch.zeros_like(p).scatter(0, idx[keep], s[keep])
print("top-p:", (nucleus / nucleus.sum()).numpy().round(3)) # [0.665 0.245 0.09 0. ]
print(torch.argmax(logits / 0.2) == torch.argmax(logits)) # tensor(True)
Common pitfalls
- A 5-gram model conditions on 4 previous words; to use a word 10 positions back you need an 11-gram.
- A longer n-gram context is not automatically better: on small data most long n-grams occur once, and held-out perplexity can rise.
- Perplexity depends on the tokenization and on whether
</s>is counted, so only compare models evaluated the same way. - Temperature changes the distribution but never the argmax: greedy decoding is unaffected by it. Low temperature is for precise text, higher temperature or top-p for creative text.
- The masked-LM loss ignores unmasked positions, so with the same data BERT gets targets at only about 15% of positions, while a causal LM gets one at every position.
- Causal LM labels are the inputs shifted by one; MLM labels are the original tokens at the masked positions, not shifted.
- Training is parallel over positions (teacher forcing), but generating tokens takes sequential forward passes.
References
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft (Aug 2026), Ch. 3 N-gram Language Models — Sec. 3.1 N-Grams, 3.3 Evaluating Language Models: Perplexity, 3.6 Smoothing, Interpolation, and Backoff
- Wikipedia: Kneser–Ney smoothing — Introduction (absolute discounting, the "San Francisco" example); Method (continuation probability)
- Dive into Deep Learning — Sec. 9.3 Language Models (9.3.1.1 Markov Models and n-grams, 9.3.2 Perplexity, 9.3.3 Partitioning Sequences)
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft (Aug 2026), Ch. 7 Transformers and Pretraining — Sec. 7.5 The Language Modeling Head, 7.6 Decoding, 7.7 Pretraining Transformer LLMs
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft (Aug 2026), Ch. 9 Masked Language Models — Sec. 9.1 Three architectures for language models, 9.3.1 Masking Words
- Hugging Face LLM Course — Ch. 7, Training a causal language model from scratch (Initializing a new model, data collator with mlm=False)
- Wikipedia: Good–Turing frequency estimation — The method (Calculation, Smoothing)