Exercises

Agentic AI · L-Att

Calculations and conceptual questions on the four parts of the lecture. Exercises 1–5 are required; Exercises 6–7, on the parts of Part III and Part IV beyond the KV-cache, are optional. The programming exercises are in the lab notebook lecture-Att-lab.ipynb. Solutions in skip cells (tag solution).

Exercise 1 — Byte-Pair Encoding by Hand (calculation)

A BPE tokenizer is trained on a corpus of six words with the counts below. Pairs are counted only inside a word, as in BPE training (lecture section BPE Training), and the base vocabulary is the set of characters that occur in the corpus.

Word lower slow lows owl bowl only
Count 5 3 4 2 6 1

(a) Carry out three merges. At each step, list the count of every adjacent pair of symbols — a pair inside a word of count $c$ contributes $c$ — merge the most frequent pair, and write down the corpus after the merge. Which three merge rules does training produce, in which order, and how many symbols does the vocabulary hold afterwards?

(b) Encode the unseen words owls, bow and slowly with the rules of (a). How many tokens does each word become?

(c) Encode slowly again, but apply the third rule before the second. Which segmentation results? Explain why the result depends on the order of the rules, and which order the encoder uses (lecture section BPE Training).

(d) After training, the tokenizer of (a) is applied to a new document that was not part of the training corpus; the document contains the word bow 100 times. Does the segmentation of bow in this document change? Justify the answer.

(e) Encode wolf. Which symbol cannot be represented, and how does byte-level BPE avoid the problem?

(f) Open Tiktokenizer, an online visualizer of the GPT-4o tokenizer that Jurafsky & Martin (2026), §2.4.3, use, and switch on Show whitespace.

  1. Enter the corpus of (a) as one line, lower slow lows owl bowl only. How many tokens result, and to which side of a word is the space between two words attached? Which step before BPE decides that?
  2. Enter owls bow slowly wolf and compare the segmentation of owls at the start of the line with that of owl in item 1. Explain the difference.
  3. Enter a sentence in English and its translation into another language you know, and compare the two token counts (Jurafsky & Martin, 2026, Exercise 2.1). What does the difference mean for the cost of a request and for the context window?
  4. Enter the number 12345678901234. How is it divided into tokens? Why can this division make written arithmetic harder for a model (Jurafsky & Martin, 2026, Exercise 2.2)?

Exercise 2 — The Illustrated Transformer (reading)

Read Alammar (2018a), a step-by-step visual walkthrough of the Transformer of Vaswani et al. (2017), and answer the questions from the post and the lecture section The Transformer Stack. The post translates a sentence with two stacks. It calls the first one the encoder: in the course's terms a bidirectional stack, in which every position attends to every other. It calls the second one the decoder: a causally masked stack, in which position $i$ attends to positions $1, \dots, i$ only.

(a) The two stacks are joined by a sub-layer the post calls encoder-decoder attention — in the course's terms cross-attention: an attention sub-layer of the second stack whose queries come from the second stack and whose keys and values come from the output of the first stack (Vaswani et al., 2017, §3.2.3). Which of the two stacks has the structure of the lecture's generative language model? Which sub-layer of that stack does the language model not contain, and why can it not contain it?

(b) The post computes self-attention for one word in six steps. Write the six steps as formulas for the output $\mathbf z_1$ of position 1 in a sentence of $n$ words, with $\mathbf q_i = \mathbf x_i W^Q$, $\mathbf k_i = \mathbf x_i W^K$, $\mathbf v_i = \mathbf x_i W^V$ and key dimension $d_k$. Which steps produce the attention weights, and which produce the output?

(c) The post divides the scores by $\sqrt{d_k} = 8$ and gives as its only reason "more stable gradients". Assume that the $d_k$ components of $\mathbf q$ and $\mathbf k$ are independent, with mean 0 and variance 1. Compute the mean and the variance of $\mathbf q \cdot \mathbf k$, and of $\mathbf q \cdot \mathbf k / \sqrt{d_k}$. What happens to the softmax of a score vector whose entries have a standard deviation of 8?

(d) The model width is $d_{\text{model}} = 512$, and each of the 8 heads produces vectors of width 64. What is the width of the concatenated head outputs, and what is the shape of the matrix $W^O$ that the post multiplies them by? Which property of the concatenation does $W^O$ change?

(e) Leave out the positional encoding, and swap the input vectors of two words. What happens to the self-attention outputs of all positions? Use the result to explain why dog bites man and man bites dog cannot be told apart without positional information, and state how the post adds that information.

(f) In the second stack the post sets the scores of future positions to $-\infty$ before the softmax. Which attention weight does a masked position receive, and why? Which component of the lecture's language model is this?

(g) The final linear layer maps the top vector of width 512 to a logits vector over the post's example vocabulary of 10,000 words. What is the dimension of the logits vector, and how many weights (without bias) does the layer hold?

Exercise 3 — Scaled Dot-Product Attention by Hand (calculation)

For one query $\mathbf q=(1,0)$ and two keys $\mathbf k_1=(1,0)$, $\mathbf k_2=(0,1)$ with values $\mathbf v_1=(2,0)$, $\mathbf v_2=(0,2)$ and $d_k=2$: compute the scaled scores $s_j = \mathbf q\cdot\mathbf k_j/\sqrt{d_k}$, the attention weights $a_j$ and the output $\mathbf z = \sum_j a_j\mathbf v_j$ (lecture section Self-Attention at One Position).

Exercise 4 — KV-Cache VRAM (calculation)

A model has $L=32$ layers, $n_{\text{kv}}=8$ KV-heads, $d_{\text{head}}=128$, fp16 (2 bytes). Compute the KV-cache size for 4096 tokens. Then for 32768 tokens — what's the ratio?

Exercise 5 — Why $O(n^2)$? (conceptual)

Explain why self-attention is quadratic in sequence length, and name two architecture families that reduce it.

Exercise 6 — Acceptance Rate, Expected Tokens and $\gamma^{*}$ (calculation, optional)

Take an acceptance rate $\alpha = 0.8$, averaged over positions, and a draft model that costs a tenth of a target pass, $c = 0.1$. Recall

$$ \mathbb{E}[\text{tokens per round}] = \frac{1-\alpha^{\gamma+1}}{1-\alpha}, \qquad \text{speed-up}(\gamma) = \frac{1-\alpha^{\gamma+1}}{(1-\alpha)(\gamma c + 1)} . $$

(a) Compute the expected number of tokens per round for $\gamma = 1, 2, 4, 6$. Why is it never $\gamma + 1$, and never below 1?

(b) Compute the speed-up for $\gamma = 1, \dots, 8$ and read off the optimum $\gamma^{*}$. Explain in one sentence why the curve turns over instead of growing.

(c) Check the "is it worth it at all" condition $\alpha > c$, and the guaranteed floor $\frac{1+\alpha}{1+c}$. Which entry of your table is that floor?

(d) Now the draft costs half a target pass, $c = 0.5$ (say, a draft one order of magnitude smaller instead of two). Recompute for $\gamma = 1,2,3,4$. What happens to $\gamma^{*}$ and to the speed-up?

(e) A weak draft on an unfamiliar domain gives $\alpha = 0.1$. With $\gamma = 6$ and $c = 0.1$, what is the speed-up? Interpret the number.

Exercise 7 — Decoding Strategy vs. Decoding Speed (conceptual + calculation, optional)

The sampling rules — temperature, top-$k$ and top-$p$ (→ L-ReAct) — change the distribution the tokens are sampled from. A second family of techniques leaves that distribution unchanged and only makes generation faster. The two families must be kept apart for an agent: a tool call that changes when the inference server is exchanged is a defect that is difficult to locate.

Speculative decoding (Leviathan et al., 2023; Chen et al., 2023) belongs to the second family. A small draft model proposes $\gamma$ tokens; the large target model scores all $\gamma+1$ positions in a single forward pass; the modified rejection-sampling rule accepts a prefix of the draft and resamples the first rejected token from the residual distribution. The emitted tokens are then distributed exactly as the target model's own sampling would have distributed them. With the acceptance rate $\alpha$ — the probability that one drafted token is accepted — and the cost $c$ of one draft forward pass in units of one target forward pass, the speed-up over ordinary autoregressive generation is

$$ \text{speed-up}(\gamma,\alpha) \;=\; \frac{1}{\gamma c + 1}\cdot\frac{1-\alpha^{\gamma+1}}{1-\alpha}. $$

(a) Compute the speed-up. With $c = 0.05$ and $\gamma = 4$, evaluate it for $\alpha = 0.75$ and for $\alpha = 0.62$ — the two values Leviathan et al. (2023) measure for the same model pair at greedy search (argmax) and at $T = 1$. State in one sentence the interaction between the two families that this reveals.

(b) Sort the mechanisms. For each of temperature, top-$p$, constrained decoding, quantization and speculative decoding: does it change the distribution the emitted tokens follow? Where it does, is the change the point of the technique or a side effect of it?

(c) Why an agent course cares. An agent turn is many generations in a loop, so decode speed multiplies over a whole trajectory. Argue why a distribution-preserving speed-up is the only kind you may switch on without re-running your tool-call evaluation — and name the concrete failure you would expect from switching on a lossy one (say, a more aggressive quantization) on an agent whose tool calls are already marginal.

References.

  • Leviathan, Yaniv, et al. "Fast Inference from Transformers via Speculative Decoding." International Conference on Machine Learning. Vol. 202. 2023. arXiv:2211.17192.
  • Chen, Charlie, et al. "Accelerating Large Language Model Decoding with Speculative Sampling." arXiv preprint arXiv:2302.01318 (2023).

References

Peer-reviewed papers

  • Leviathan, Yaniv, et al. "Fast Inference from Transformers via Speculative Decoding." International Conference on Machine Learning. Vol. 202. 2023. arXiv:2211.17192.
  • Vaswani, Ashish, et al. "Attention Is All You Need." Advances in Neural Information Processing Systems. Vol. 30. 2017. arXiv:1706.03762.

Preprints & other non-peer-reviewed papers

  • Chen, Charlie, et al. "Accelerating Large Language Model Decoding with Speculative Sampling." arXiv preprint arXiv:2302.01318 (2023).

Textbooks & monographs

  • Jurafsky, Daniel, and James H. Martin. Speech and Language Processing: An Introduction to Natural Language Processing, Computational Linguistics, and Speech Recognition with Language Models. 3rd ed., online manuscript released August 19, 2026. https://web.stanford.edu/~jurafsky/slp3/ — byte-pair encoding: the learner, the encoder and byte-level BPE (ch. 2, §2.4).

Blogs, documentation & other web sources