Sub topic 3
Generating Text from a Language Model
Assume you know basic Python, vectors, matrix multiplication, probability, and the idea of a neural network. A language model produces text by repeatedly choosing one token from the probability distribution for the next token.
Decoding: choosing the next token
The simplest method is greedy decoding. It always chooses the token with the highest probability. This is predictable, but it can produce repetitive text.
Temperature changes how sharply probabilities are distributed. A low temperature makes the most likely tokens more likely. A high temperature makes less likely tokens more possible. Top-k sampling first keeps only the k most likely tokens, then samples from that smaller set.
| Setting | Typical effect |
|---|---|
| Greedy decoding | Deterministic and focused |
| Low temperature | Safe and repetitive |
| High temperature | Varied and less predictable |
| Small top-k | Restricts unlikely choices |
import numpy as np
def sample_next(logits, temperature=1.0, top_k=None, rng=None):
rng = rng or np.random.default_rng()
scores = np.asarray(logits, dtype=float) / temperature
if top_k is not None:
cutoff = np.sort(scores)[-top_k]
scores = np.where(scores < cutoff, -np.inf, scores)
probabilities = np.exp(scores - np.max(scores))
probabilities /= probabilities.sum()
return int(rng.choice(len(probabilities), p=probabilities))
print(sample_next([3.0, 2.0, 0.5, -1.0],
temperature=0.7, top_k=2,
rng=np.random.default_rng(0)))Context windows and the key-value cache
A context window is the maximum number of tokens the model can process in one request. Earlier tokens outside this window cannot directly influence the next prediction.
During self-attention, the model computes key and value vectors for each token. A key-value cache stores these vectors during generation. On the next step, the model computes them only for the new token and reuses the cached vectors. This reduces repeated work, although the cache consumes memory.
From base model to assistant
A base model learns to continue text. Instruction tuning trains it on examples containing requests and useful responses. Preference tuning further trains it toward responses that people or a preference model rank highly. These stages improve helpfulness and style, but they do not guarantee truth.
Scale and limitations
Model quality often improves with more parameters, training data, and compute. Scaling laws describe these trends, but gains depend on data quality, architecture, and training choices.
A model can hallucinate, meaning it generates plausible but unsupported information. Its knowledge has a cutoff based on its training data. Its output is also sensitive to wording, context, and requested format.
Exercise
Which decoding approach is usually best for a factual answer that should be consistent?
Show answer
Greedy decoding or a low temperature with a small top-k value.