Generation exercises
Extended practice, worked solutions, and transfer
← Back to the exercise catalogue
Generation
Prerequisites: logits, output probabilities, next-token prediction and autoregressive generation.
Eight formative exercises published: GE-A–GE-H. They cover next-token selection, the autoregressive loop and stopping, prefill/decode, KV caching, multi-request serving mechanisms, then the effects of temperature and top-k/top-p filters.
Distribution and selection
For a fixed context, a model produces logits \(z=(0,\ln 2,\ln 3)\) for vocabulary \(\{A,B,C\}\). Both rules start from these same logits, with temperature set to \(1\) and no filtering.
- Compute the softmax distribution.
- Which token does greedy decoding select?
- What is the probability of selecting \(C\) under each rule? Which other tokens can sampling select?
Show the solution
- The exponentials are \((1,2,3)\) and sum to \(6\). The model assigns probabilities \(p=(1/6,1/3,1/2)\).
- Greedy decoding selects \(C\), the unique highest-probability token.
- The probability of selecting \(C\) is \(1\) under greedy decoding and \(1/2\) under sampling. Sampling can also draw \(A\) with probability \(1/6\) or \(B\) with probability \(1/3\). The choice of rule determines the distribution of the selected token from the same predicted distribution.
Return to the review plan · From hidden states to the predictive distribution · Run inference and generate text
Trace the autoregressive loop
We start with \(c_1=(A,B)\). Decoding is greedy and the distributions are given:
| Current context | Distribution |
|---|---|
| \((A,B)\) | \(P(C)=0.8\), \(P(D)=0.2\) |
| \((A,B,C)\) | \(P(D)=0.7\), \(P(E)=0.3\) |
| \((A,B,C,D)\) | \(P(\mathrm{EOS})=0.9\), \(P(E)=0.1\) |
- Give the selected token at each step.
- Write the context after each selection.
- How many elementary steps are executed?
- What is repeated and what changes?
- If sampling picked \(D\) on the first turn, what would the second context be? Does the table give its distribution?
Show the solution
The selections are \(C\), then \(D\), then EOS. The contexts become \((A,B,C)\), \((A,B,C,D)\), then \((A,B,C,D,\mathrm{EOS})\) if EOS is explicitly represented in the sequence. Three elementary steps are executed. The prediction-selection mechanism repeats; the context changes after each feedback step. Model parameters remain fixed.
If the first draw picked \(D\), the second context would be \((A,B,D)\). The second row is conditioned on \((A,B,C)\). A distribution for \((A,B,D)\) would have to be computed before selecting the next token.
Stopping criteria
A generation uses max_new_tokens = 4. EOS is selected at the second step.
- What is the maximum number of new tokens allowed?
- How many are actually generated if EOS counts?
- What happens if EOS is never selected?
- Why are EOS and the length limit distinct criteria?
Show the solution
The limit allows at most four new tokens. Since EOS is selected at the second step, two tokens are generated, including EOS, and the loop stops. Without EOS, generation stops after four new tokens. EOS is a semantic criterion carried by a token; the limit is an external execution constraint.
Trace prefill and incremental decode
A prompt contains the token IDs \((A,B,C)\). Assume a causal Transformer with KV caching enabled.
- During prefill, how many prompt positions are processed?
- Which position’s logits are used to select the first generated token \(D\)?
- To predict the following token \(E\), which token is newly supplied during incremental decode?
- Why is prefill not the same operation as teacher forcing?
- Are the model parameters updated during these inference phases?
Show the solution
Prefill processes the three prompt positions in one forward pass and, in this scenario, populates the KV cache. The logits at the position of \(C\) give the first distribution, from which the decoding rule selects \(D\). The decode step receives \(D\) and reuses cached keys and values to compute the next distribution, from which \(E\) can be selected. The parameters stay fixed. The similarity to teacher forcing is limited to the fact that the model receives known tokens under a causal mask. Prefill is an inference phase: it produces the first-token distribution and optionally the cache, with no reference target or training loss. During training, teacher forcing conditions the model on reference tokens: the logits at each position are compared with shifted targets. A scoring computation can likewise condition predictions on an observed prefix, with fixed parameters and no update. Compare the scoring computation and the teacher-forcing alignment exercise.
What does the KV cache save?
Assume a prompt of three tokens \((A,B,C)\) and generate three tokens \(D,E,F\). Ignore context-window eviction and count only token positions newly passed through the model:
- Without a KV cache, how many token positions are processed across the prompt pass and the two subsequent predictions?
- With a KV cache, how many new token positions are processed after prefill?
- What information is retained in the cache?
- Does the cache change the model parameters or the conditional distribution being computed?
- Why does the count above not represent the total attention computation?
Show the solution
Without a cache, the model processes lengths \(3\), then \(4\) (to predict \(E\)), then \(5\) (to predict \(F\)): \(3+4+5=12\) token positions. With a cache, prefill processes the three prompt tokens; the decode steps then process only \(D\) and \(E\) as new positions: \(3+1+1=5\) newly processed positions. The cache retains previously computed keys and values at each Transformer layer. It does not update parameters or change the intended conditional prediction; it avoids recomputing the prefix. The new query at each decode step still attends to the cached keys and values, so counting new positions is not a count of all attention operations or total FLOPs.
Temperature and distribution concentration
Optional preparation: Advanced decoding strategies, to review logit transformations and distribution concentration.
A model produces logits \(z=(0,\ln 4,\ln 16)\) for tokens \(\{A,B,C\}\). Apply temperature using \(p(T)=\operatorname{softmax}(z/T)\).
- Compute the distribution for \(T=1\).
- Compute the distribution for \(T=2\).
- Does the most probable token change? What changes nevertheless?
- Does a higher temperature make an answer more truthful or creative by definition?
Show the worked solution
For \(T=1\), the exponentials of the logits are \((1,4,16)\), so \(p(1)=(1/21,4/21,16/21)\).
For \(T=2\), the logits divided by two are \((0,\ln 2,\ln 4)\); their exponentials are \((1,2,4)\), so \(p(2)=(1/7,2/7,4/7)\).
The ranking remains \(C\), then \(B\), then \(A\): dividing all logits by a strictly positive temperature preserves their order. The distribution nevertheless becomes flatter: less probable tokens receive more relative probability mass. Temperature guarantees neither truth, creativity, nor quality; it controls the spread of choices.
Compare top-k and top-p
Optional preparation: Advanced decoding strategies, to review fixed-size candidate selection and cumulative probability mass.
After softmax, the distribution over four tokens is:
| Token | A | B | C | D |
|---|---|---|---|---|
| Probability | 0.50 | 0.25 | 0.15 | 0.10 |
- With top-k and \(k=2\), which tokens are retained? Compute their probabilities after renormalization.
- With top-p and \(p=0.80\), which tokens are retained? Compute their probabilities after renormalization.
- Why do the two methods not necessarily retain the same number of candidates?
- What is lost when a filter excludes a token with nonzero probability?
Show the worked solution
Top-k, \(k=2\): tokens A and B are retained. Their original mass is \(0.50+0.25=0.75\). After renormalization, \(P(A)=0.50/0.75=2/3\) and \(P(B)=0.25/0.75=1/3\).
Top-p, \(p=0.80\): add tokens in descending probability order until cumulative mass reaches or exceeds 0.80. A alone gives 0.50; A+B give 0.75; A+B+C give 0.90. The nucleus is therefore {A, B, C}. After renormalization, \(P(A)=5/9\), \(P(B)=5/18\), and \(P(C)=1/6\).
Top-k fixes the number of candidates; top-p fixes a target cumulative mass, so the number varies with the distribution. Both filters exclude continuations that had nonzero probability in the original distribution: they change the effective distribution and may remove a continuation that would have been relevant.
These exercises focus on distribution controls. Sequence search (beam search) and contrastive decoding remain optional deep dives, not prerequisites for the main learning path.
Prefix caching and continuous batching
A server has already processed the tokenized prefix \(S=(s_1,\ldots,s_{1200})\) for one request. A second request begins with exactly the same 1,200 tokens, then adds a 300-token suffix. The cache for \(S\) is still available on the selected worker.
- How many tokens of the second prompt still need prefill processing?
- If the second prompt has the same meaning but differs from token 20 onward, can it reuse the cache for \(S\) after that point?
- Sequences A, B, and C are active. A finishes after 2 iterations, B after 7; a new request D arrives. What does continuous batching allow?
- Does continuous batching make tokens within one sequence independent of one another?
Show the worked solution
- The prefix \(S\) is reused; only the 300-token suffix needs prefill, assuming the cache is compatible and still available.
- No. Cache sharing requires an exactly identical tokenized prefix. Semantic similarity is not enough; after the first divergence, later states cannot be reused as a continuation of the same prefix.
- When A finishes, its slot can be assigned to D at a subsequent iteration, without waiting for B. Batch composition changes during decode.
- No. Each sequence keeps its autoregressive dependency: its next token depends on its own prefix. Batching combines computation across sequences; it does not remove that dependency.