What is a Language Model?
A language model defines a probability distribution over sequences of tokens or words, scoring how plausible a sequence is in a language. Autoregressive language models factorize sequence probability via the chain rule into next-token predictions conditioned on prior context, whereas masked language models predict hidden tokens from bidirectional context. Evaluated commonly by perplexity, modern language models built on Transformers power text generation, translation, speech recognition, and reasoning tasks.
Study Card: What is a Language Model?
Direct Answer
A language model is a probability distribution over sequences of words or subword tokens. In an autoregressive (causal) language model, the joint probability of a sequence is factorized using the probability chain rule as a product of next-token conditional probabilities:
By contrast, masked language models (such as BERT) estimate probabilities of masked tokens conditioned on bidirectional surrounding context. Language models are evaluated intrinsically with perplexity, which measures how well the model predicts held-out text:
They capture statistical, syntactic, and semantic structure from large corpora, serving as the core engine for text generation and ranking hypotheses in machine translation and speech recognition, and adapting via fine-tuning or prompting to downstream tasks such as sentiment analysis. Common architectures range from -gram count models and recurrent neural networks (RNNs/LSTMs) to Transformers.
Key Terms
- Probability Distribution over Sequences: A normalized assignment of probabilities over token sequences so fluent, coherent sentences receive higher probability than random word orderings.
- Autoregressive Factorization: Decomposing into sequential next-token conditionals via the chain rule.
- N-gram Model: A count-based Markov approximation that assumes over a fixed window of preceding tokens.
- Recurrent Neural Network (RNN): A sequential neural model maintaining a hidden state across time steps; captures longer context than small -grams but struggles with very long-range dependencies.
- Transformer: A self-attention architecture that processes sequences in parallel during training and scales effectively to long contexts, underpinning modern large language models (LLMs).
- Perplexity: The exponentiated average negative log-likelihood per token; lower perplexity indicates better predictive fit on held-out text.
Example
Given the prefix "The cat sat on the", a well-trained autoregressive language model assigns high probability to "mat" or "sofa" and very low probability to "quickly" or "green", reflecting syntax and world semantics learned from training corpora. Similarly, in speech recognition or machine translation, a language model scores "The quick brown rabbit runs fast" much higher than "Fast quick rabbit runs brown", helping select fluent outputs over ungrammatical candidates.
Code Implementation
import numpy as np
import tensorflow as tf
# Sample corpus repeated so sequence length exceeds maxlen
corpus = (
"the cat sat on the mat. the dog chased the ball. "
"language models learn patterns in text sequences. "
) * 6
chars = sorted(set(corpus))
char_to_idx = {c: i for i, c in enumerate(chars)}
idx_to_char = {i: c for i, c in enumerate(chars)}
vocab_size = len(chars)
maxlen = 15
step = 2
sequences = []
next_chars = []
for i in range(0, len(corpus) - maxlen, step):
sequences.append(corpus[i : i + maxlen])
next_chars.append(corpus[i + maxlen])
x = np.zeros((len(sequences), maxlen, vocab_size), dtype=np.float32)
y = np.zeros((len(sequences), vocab_size), dtype=np.float32)
for i, seq in enumerate(sequences):
for t, ch in enumerate(seq):
x[i, t, char_to_idx[ch]] = 1.0
y[i, char_to_idx[next_chars[i]]] = 1.0
# Character-level LSTM outputting raw logits for numerically clean temperature scaling
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(maxlen, vocab_size)),
tf.keras.layers.LSTM(64),
tf.keras.layers.Dense(vocab_size),
])
model.compile(
loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),
)
model.fit(x, y, batch_size=32, epochs=5, verbose=0)
def sample_from_logits(logits, temperature=1.0):
scaled = logits / max(temperature, 1e-6)
scaled = scaled - np.max(scaled)
probs = np.exp(scaled) / np.sum(np.exp(scaled))
return np.random.choice(len(probs), p=probs)
rng = np.random.default_rng(42)
start_idx = int(rng.integers(0, len(corpus) - maxlen - 1))
seed_text = corpus[start_idx : start_idx + maxlen]
print(f'Seed: "{seed_text}"')
for temperature in [0.5, 1.0]:
window = seed_text
output = [seed_text]
for _ in range(40):
sampled = np.zeros((1, maxlen, vocab_size), dtype=np.float32)
for t, ch in enumerate(window):
sampled[0, t, char_to_idx[ch]] = 1.0
logits = model.predict(sampled, verbose=0)[0]
next_ch = idx_to_char[sample_from_logits(logits, temperature=temperature)]
output.append(next_ch)
window = window[1:] + next_ch
print(f"T={temperature}: {''.join(output)}")
Related Concepts
- N-gram Language Models: Classical count-based baselines using smoothing (e.g., Kneser-Ney) to handle unseen -grams.
- Masked vs. Causal Language Modeling: Bidirectional masked token prediction (BERT) for representation learning vs. causal next-token prediction (GPT) for generation.
- Subword Tokenization (BPE / WordPiece / Unigram): Splits words into subword units to balance vocabulary size and out-of-vocabulary coverage.
- Decoding Strategies: Greedy decoding, beam search, temperature scaling, top-, and top- (nucleus) sampling for controlling generation quality and diversity.
- Cross-Entropy Loss & Perplexity: Training objective (minimizing negative log-likelihood) and its exponentiated evaluation metric.