🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Language Modeling: Causal, Masked, and Perplexity

Conversational NLPPerplexity, Masked LM, and Causal LMđŸŸĸ Free Lesson

What is actually being estimated

A language model is a probability distribution over token sequences, factorised as a product of conditional probabilities. That is the entire definition, and every architecture decision follows from it. Factorising left to right gives an autoregressive model that can generate text but can never condition on the right. Factorising around randomly masked positions gives a bidirectional model that reads both directions but cannot generate by construction. The factorisation is the design choice; the architecture is an implementation detail downstream of it.

The training signal is always the same: maximize the log likelihood of real text under whatever factorisation you chose. For a causal model that means predicting every token from its prefix, which is a supervision signal at every position. For a masked model it means predicting only the corrupted positions, which is a sparser signal that is nonetheless conditioned on richer context. Everything practical — how much data you need, whether you can generate, whether you can fine-tune for understanding tasks — is a consequence of that difference.

This lesson implements both objectives, derives perplexity and the traps around it, and closes with the decoding controls that turn a probability distribution into a text a user will accept.

The causal factorisation

Autoregressive models condition strictly on the past. In PyTorch this is implemented with a causal mask that blocks attention from position t to any position after t, plus a label shift by one so the model predicts the next token rather than reconstructing itself.

python
import torch
import torch.nn as nn

class TinyCausalLM(nn.Module):
    def __init__(self, vocab, d=256, heads=4, layers=4, max_len=512):
        super().__init__()
        self.tok = nn.Embedding(vocab, d)
        self.pos = nn.Embedding(max_len, d)
        layer = nn.TransformerEncoderLayer(
            d_model=d, nhead=heads, dim_feedforward=4 * d,
            batch_first=True, activation="gelu")
        self.blocks = nn.TransformerEncoder(layer, layers)
        self.norm = nn.LayerNorm(d)
        self.head = nn.Linear(d, vocab, bias=False)

    def forward(self, ids):
        b, t = ids.shape
        pos = torch.arange(t, device=ids.device).unsqueeze(0)
        x = self.tok(ids) + self.pos(pos)
        mask = torch.triu(torch.full((t, t), float("-inf"), device=ids.device), 1)
        x = self.blocks(x, mask=mask)
        return self.head(self.norm(x))

def causal_step(model, ids, optimizer):
    logits = model(ids[:, :-1])
    loss = nn.functional.cross_entropy(
        logits.reshape(-1, logits.size(-1)), ids[:, 1:].reshape(-1))
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    return loss.item()

model = TinyCausalLM(vocab=32000)
opt = torch.optim.AdamW(model.parameters(), lr=3e-4)
batch = torch.randint(0, 32000, (8, 128))
print("loss:", round(causal_step(model, batch, opt), 3))

The mask is the load-bearing piece. Without it, attention at position t would see position t + 1, the model would trivially copy the answer, training loss would collapse, and the resulting model would be useless for generation. This is also why causal models cannot be used directly for tasks that need bidirectional reading, which is the entire motivation for the next section. One operational consequence of the factorisation is streaming: because the distribution over the next token depends only on the prefix, a causal model can emit tokens incrementally as a user types, whereas a masked model cannot begin until the whole input is available. That single property is why every interactive text system is causal, and why masked encoders live almost entirely inside the understanding half of the stack rather than the generation half.

The masked objective

Masked models corrupt a fraction of the input and train only on the corrupted positions. The corruption scheme itself is a design decision: BERT replaces 15 percent of tokens, and of those, 80 percent with the mask symbol, 10 percent with a random token, and 10 percent left unchanged. The random and unchanged splits prevent the model from over-relying on the mask token as a signal that a prediction is expected, which it otherwise does within a few epochs.

python
def apply_mlm_corruption(input_ids, mask_id=103, p=0.15, seed=0):
    labels = input_ids.clone()
    mask = torch.rand(input_ids.shape, generator=torch.Generator().manual_seed(seed)) < p
    mask &= (input_ids != 0) & (input_ids != 101) & (input_ids != 102)

    labels[~mask] = -100                      # loss on corrupted only
    draw = torch.rand(input_ids.shape, generator=torch.Generator().manual_seed(seed + 1))

    replace_mask = mask & (draw < 0.8)
    random_token = mask & (draw >= 0.8) & (draw < 0.9)
    keep = mask & (draw >= 0.9)

    corrupted = input_ids.clone()
    corrupted[replace_mask] = mask_id
    corrupted[random_token] = torch.randint_like(input_ids, 0, 30522)[random_token]
    # keep leaves the original token in place
    _ = keep
    return corrupted, labels

def masked_loss(model, corrupted, labels):
    logits = model(corrupted)
    return nn.functional.cross_entropy(
        logits.view(-1, logits.size(-1)), labels.view(-1), ignore_index=-100)

Because the loss ignores every uncorrupted position, a masked model receives roughly a seventh of the supervision a causal model gets per token at the standard 15 percent rate. That is part of why masked models need more epochs and more data to reach comparable quality on the same corpus.

Perplexity and the tokenization trap

Perplexity is the exponent of the average negative log likelihood per token, equivalently the geometric mean of the inverse probability assigned to the observed tokens. A model with perplexity 50 is, on average, choosing among fifty equally plausible candidates at each position.

python
import math

def perplexity(model, input_ids):
    with torch.no_grad():
        logits = model(input_ids[:, :-1])
        loss = nn.functional.cross_entropy(
            logits.reshape(-1, logits.size(-1)), input_ids[:, 1:].reshape(-1))
    return math.exp(loss.item())

def perplexity_with_temperature(model, input_ids, temperature=1.0):
    with torch.no_grad():
        logits = model(input_ids[:, :-1]) / temperature
        loss = nn.functional.cross_entropy(
            logits.reshape(-1, logits.size(-1)), input_ids[:, 1:].reshape(-1))
    return math.exp(loss.item())

ids = torch.randint(0, 32000, (2, 64))
print("ppl:", round(perplexity(model, ids), 2))
for t in (0.5, 1.0, 2.0):
    print(f"t={t}: ppl={perplexity_with_temperature(model, ids, t):.2f}")

The trap is that perplexity is defined per token, so two models tokenizing the same text differently are not comparable. A tokenizer that splits internationalization into four pieces gives each piece an easier prediction task and reports a lower perplexity without understanding anything better. Perplexity is therefore only meaningful between models sharing a tokenizer, and even then it correlates only loosely with downstream quality — a model can improve perplexity by better modelling function words while getting content words no closer to correct.

Comparing the objectives

PropertyCausal LMMasked LMPrefix LM
FactorisationLeft to rightBidirectional around masksBidirectional prefix, autoregressive suffix
Supervision per tokenEvery positionCorrupted positions onlyPrefix plus generated suffix
Can generateYes, nativelyNoYes, from a prefix
Best fine-tune fitGeneration, chat, agentsClassification, NER, retrievalControlled generation
Example modelsGPT familyBERT, RoBERTaT5, UniLM
Training cost per tokenHigherLower signal, more epochsIntermediate

The choice is dictated by the downstream task rather than by any general quality ranking. If you are building a chatbot, a summariser, or an agent that must emit text, the causal factorisation is essentially mandatory. If you are building a classifier, a reranker, or an information extractor, a masked encoder gives better representations at comparable or lower compute, because reading both directions is a genuine advantage when no text needs to be generated.

Decoding: turning probabilities into text

At inference a causal model produces a distribution over the vocabulary, and sampling policy determines what comes out. Temperature rescales the logits before the softmax: below one sharpens the distribution toward the argmax, above one flattens it toward uniform. Top-k truncates the support to the k most likely tokens and resamples. Nucleus sampling, also called top-p, keeps the smallest set of tokens whose cumulative probability exceeds p, which adapts the support width to how peaked the distribution happens to be at that position.

python
def sample_next(logits, temperature=1.0, top_k=None, top_p=None):
    logits = logits / max(temperature, 1e-6)
    probs = torch.softmax(logits, dim=-1)

    if top_k is not None:
        kth = torch.topk(probs, top_k).values[..., -1, None]
        probs = torch.where(probs < kth, torch.zeros_like(probs), probs)

    if top_p is not None:
        sorted_probs, sorted_idx = torch.sort(probs, descending=True)
        cumsum = torch.cumsum(sorted_probs, dim=-1)
        cutoff = cumsum > top_p
        cutoff[..., 1:] = cutoff[..., :-1].clone()
        cutoff[..., 0] = False
        sorted_probs = sorted_probs.masked_fill(cutoff, 0.0)
        probs = torch.zeros_like(probs).scatter(-1, sorted_idx, sorted_probs)

    probs = probs / probs.sum().clamp_min(1e-9)
    return torch.multinomial(probs, 1).item()

logits = torch.tensor([2.0, 1.0, 0.5, 0.1, -1.0])
for t, k, p in [(1.0, None, None), (0.5, None, None), (1.0, 3, None), (1.0, None, 0.9)]:
    print(f"t={t} k={k} p={p} -> token", sample_next(logits, t, k, p))
StrategyBehaviourTypical use
GreedyAlways argmaxEvaluation, short answers
Temperature lowSharper, more repetitiveFactual extraction
Top-kFixed support widthGeneral dialogue
Top-pAdaptive support widthOpen-ended generation
Beam searchBest average log prob sequenceTranslation, summarisation

In practice a combination is used: temperature between 0.7 and 1.0 with top-p between 0.9 and 0.95 for open-ended generation, greedy or near-zero temperature for tasks where the output must be deterministic and verifiable. Beam search remains the right tool for encoder-decoder tasks where the objective is a high-likelihood output rather than a varied one.

💡Report perplexity with the tokenizer attached

A perplexity number without its tokenizer and vocabulary size is not interpretable. Put both in the model card, and never compare across runs whose tokenizers differ without normalising to bits per byte first.

Common Mistakes

Comparing perplexity between models with different tokenizers

Fix: Perplexity is per token; compare bits per byte, or restrict comparison to shared tokenizers.

Forgetting the causal mask during training

Fix: Without it the model copies the next token and training loss collapses while generation becomes useless.

Training a masked model with loss on uncorrupted positions

Fix: Set labels to ignore_index on uncorrupted positions, otherwise the model learns the identity function.

Using greedy decoding for open-ended generation

Fix: Greedy produces repetitive text; sample with temperature and top-p for anything user-facing.

Best Practices

  • Choose the factorisation from the downstream task, not from model popularity
  • Keep tokenizer, vocabulary size, and perplexity together in every reported number
  • Use bits per byte when comparing across tokenizers
  • Match decoding strategy to the task: sampling for open-ended, beam or greedy for structured output

Interview Questions

Q1: Why can a masked language model not generate text?

It is trained to predict tokens given both left and right context, so at generation time there is no right context to condition on and no left-to-right factorisation to sample from.

Q2: Why is perplexity not comparable across tokenizers?

It is the exponentiated average negative log likelihood per token, so a finer tokenization makes each prediction easier and lowers perplexity without any improvement in language understanding.

Q3: What does top-p sampling change relative to top-k?

Top-p keeps the smallest set of tokens whose cumulative probability exceeds p, adapting the support width to how peaked the distribution is at that position, while top-k uses a fixed support size regardless of peakedness.

Key Takeaways

  • The factorisation — causal, masked, or prefix — is the design choice; architecture follows from it
  • Causal models supervise every position and can generate; masked models supervise a fraction and read both directions
  • Perplexity is a per-token measure and is meaningless across differing tokenizers
  • Temperature, top-k, and top-p are three independent controls over the sampling distribution
  • Decoding strategy should match the task: sample for openness, constrain for verifiability
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement