Skip to content
ml-recall

Topic notes

Language Modeling

Language models assign probabilities to token sequences — n-gram counting and smoothing, perplexity, neural causal and masked LMs, and decoding by greedy, temperature, top-k and top-p sampling.

3-min read AI-checked

Practise 45 questions Take a test

Key ideas

Formulas

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:

PPL=P(w1,…,wN)−1/N=exp⁡(−1N∑t=1Nlog⁡P(wt∣w<t))\mathrm{PPL} = P(w_1, \dots, w_N)^{-1/N} = \exp\Big(-\frac{1}{N}\sum_{t=1}^{N} \log P(w_t \mid w_{\lt t})\Big)

Lower is better: a perfect model scores 1, and a uniform guess over ∣V∣|V| tokens scores ∣V∣|V|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>.

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

References

  1. 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
  2. Wikipedia: Kneser–Ney smoothing — Introduction (absolute discounting, the "San Francisco" example); Method (continuation probability)
  3. 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)
  4. 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
  5. 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
  6. Hugging Face LLM Course — Ch. 7, Training a causal language model from scratch (Initializing a new model, data collator with mlm=False)
  7. Wikipedia: Good–Turing frequency estimation — The method (Calculation, Smoothing)