Skip to content

Advanced Text Generation

Advanced text generation goes beyond vanilla autoregressive decoding to improve reasoning depth, memory efficiency, controllability, and speed. This file covers discrete masked diffusion language models (D3PM, MDLM, LLaDA), OCR, alignment (RLHF, DPO, GRPO), long-context scaling, modern linear attention and state-space models (Mamba-2 SSD, Gated DeltaNet, TTT, Titans), retrieval-augmented generation, speculative decoding, frontier MoE and multi-token prediction primitives, and Looped Transformers for recurrent-depth latent reasoning.

  • Standard autoregressive generation (file 04) produces text one token at a time, left to right, through a fixed stack of layers. This is simple and effective, yet it is inherently sequential, spends identical compute on trivial and hard tokens alike, and carries a growing KV cache over long sequences. This file surveys the modern techniques that transcend vanilla autoregressive decoding, from parallel text diffusion and sub-quadratic sequence models to preference alignment, speculative decoding, frontier MoE engineering, and Looped Transformers that think iteratively in latent space.

  • Text diffusion models apply the diffusion framework (introduced for images in chapter 08) to discrete text. The core challenge is that text is discrete: you cannot add continuous Gaussian noise to tokens the way you add noise to pixels. Several approaches address this.

  • D3PM (Discrete Denoising Diffusion Probabilistic Models, Austin et al., 2021) defines a forward corruption process directly over discrete tokens using transition matrices. At each forward step, a token has some probability of being replaced by another token (uniform noise), masked (absorbing state), or staying the same. The reverse process learns to denoise, predicting the clean token from the corrupted one. The transition matrix \(Q_t\) at step \(t\) controls corruption:

\[q(x_t \mid x_{t-1}) = \text{Cat}(x_t ; \, x_{t-1} Q_t)\]
  • where \(\text{Cat}\) denotes a categorical distribution and \(x\) is a one-hot vector. The multi-step forward process \(q(x_t \mid x_0)\) has a closed form: \(q(x_t \mid x_0) = \text{Cat}(x_t ; \, x_0 \bar{Q}_t)\) where \(\bar{Q}_t = Q_1 Q_2 \cdots Q_t\) is the product of all transition matrices up to step \(t\). Training minimises a variational lower bound (ELBO) that decomposes across timesteps, similar to the continuous case (chapter 08):
\[\mathcal{L}_{\text{D3PM}} = D_{\text{KL}}(q(x_T \mid x_0) \| p(x_T)) + \sum_{t=2}^{T} D_{\text{KL}}(q(x_{t-1} \mid x_t, x_0) \| p_\theta(x_{t-1} \mid x_t)) - \log p_\theta(x_0 \mid x_1)\]
  • The first term ensures the fully corrupted distribution matches the prior (uniform or all-mask). The sum of KL terms trains the model to reverse each corruption step: the true reverse posterior \(q(x_{t-1} \mid x_t, x_0)\) can be computed in closed form using Bayes' rule and the known transition matrices, and the model \(p_\theta(x_{t-1} \mid x_t)\) is trained to match it.

  • Since both distributions are categorical, the KL divergence is a simple sum over vocabulary entries. The final term measures reconstruction quality from the least corrupted state.

  • MDLM (Masked Diffusion Language Models, Sahoo et al., 2024) simplifies D3PM by using masking as the only corruption operation. The forward process gradually replaces tokens with a [MASK] token according to a continuous-time noise schedule, and the reverse process predicts the original tokens. Sahoo et al. showed that the resulting variational objective reduces to a clean weighted integral of masked language modelling losses (connecting directly back to BERT in file 04), closing much of the perplexity gap to autoregressive models while supporting fast parallel denoising.

  • LLaDA (Large Language Diffusion with mAsking, Nie et al., 2025) scaled masked discrete diffusion from scratch to an 8B-parameter foundation model trained on trillions of tokens, matching comparable autoregressive models on in-context learning, mathematics, and code. At inference time, LLaDA begins from a fully masked response and iteratively unmasks the highest-confidence positions in parallel, enabling flexible parallel token refinement and naturally overcoming the autoregressive reversal curse (where left-to-right models trained on "A is B" fail to retrieve "A" when asked about "B").

  • Continuous text diffusion sidesteps the discrete problem by working in the continuous embedding space. Tokens are first mapped to their embedding vectors (chapter 06), noise is added in this continuous space, and a denoising model (typically a Transformer) learns to reverse the process. At generation time, the model produces continuous vectors that are mapped back to discrete tokens by finding the nearest embedding. The challenge is that small errors in continuous space can map to completely wrong tokens, so careful rounding and clamping are needed.

Text Diffusion Process

  • The appeal of discrete masked diffusion is that it generates and refines many tokens simultaneously rather than strictly left to right. This gives natural bidirectional infilling, controllable parallel decoding speed (trading denoising steps against quality), and global structural coherence, making masked diffusion a genuine challenger to pure autoregressive decoding.

  • Text OCR (Optical Character Recognition) is the task of extracting text from images. While not traditionally grouped with language generation, modern OCR systems are deeply integrated with NLP and increasingly use language model components.

  • Scene text detection locates text regions in natural images (street signs, product labels, licence plates). This is challenging because text in the wild appears at arbitrary angles, scales, fonts, and against cluttered backgrounds. Detection methods typically use CNN or Transformer backbones to produce bounding boxes or segmentation masks around text regions.

  • CRNN (Convolutional Recurrent Neural Network, Shi et al., 2017) is a classic text recognition architecture. A CNN extracts visual features from the text image, the feature map is sliced into a sequence of columns (one per horizontal position), and a bidirectional LSTM reads this sequence to model context. The output is decoded using CTC (Connectionist Temporal Classification), which handles the alignment between input columns and output characters without requiring explicit segmentation.

  • The fundamental problem CTC solves: the model produces \(T\) output distributions (one per input column), but the target text has \(L \leq T\) characters.

  • We do not know which columns correspond to which characters. CTC introduces a blank token \(\epsilon\) and defines a many-to-one mapping \(\mathcal{B}\) that collapses repeated characters and removes blanks: \(\mathcal{B}(\text{"HH-ee-ll-ll-oo"}) = \text{"Hello"}\) (where "-" is blank).

  • The probability of the target sequence \(y\) is the sum over all input alignments that collapse to \(y\):

\[P(y \mid x) = \sum_{\pi \in \mathcal{B}^{-1}(y)} \prod_{t=1}^{T} P(\pi_t \mid x)\]
  • where \(\pi\) is an alignment path of length \(T\) (one label per column, including blanks). Naively summing over all paths is exponential, but the forward algorithm (chapter 05 HMMs) computes this sum efficiently in \(O(T \cdot L)\) time using dynamic programming.

  • The blank token is essential: without it, repeated characters like "ll" in "Hello" would be indistinguishable from a single "l". Training maximises \(\log P(y \mid x)\), and at inference time, the best path is found by beam search or greedy decoding over the CTC output.

  • Document OCR processes structured documents (invoices, forms, scientific papers) and must understand layout in addition to recognising characters. Modern systems like LayoutLM combine text recognition with spatial position features: each token gets both its text embedding and a positional embedding encoding its \((x, y)\) coordinates on the page. This allows the model to understand that a number appearing below "Total:" is the total amount.

CRNN OCR Pipeline

  • Vision-language OCR models like TrOCR treat text recognition as image-to-text generation: a Vision Transformer encoder processes the image, and a language model decoder generates the text character by character. This leverages the power of pre-trained vision and language models and handles diverse scripts, fonts, and layouts without handcrafted feature engineering.

  • Controllable generation is the challenge of steering a language model to produce outputs with desired properties: a particular style, topic, sentiment, safety level, or factual accuracy. The model should follow instructions while remaining fluent and coherent.

  • Classifier-free guidance (CFG) for text adapts a technique from image generation. During training, the conditioning signal (e.g., a prompt) is randomly dropped some fraction of the time, training both a conditional and unconditional model in one. At inference, the output logits are interpolated:

\[\text{logits}_{\text{guided}} = (1 + w) \cdot \text{logits}_{\text{conditional}} - w \cdot \text{logits}_{\text{unconditional}}\]
  • where \(w > 0\) amplifies the influence of the condition. Higher \(w\) makes the output more strongly follow the prompt but reduces diversity.

  • RLHF (Reinforcement Learning from Human Feedback, Ouyang et al., 2022) is the dominant method for aligning language models with human preferences. The process has three stages:

  • First, supervised fine-tuning (SFT): fine-tune the base language model on a dataset of high-quality human-written responses to prompts.

  • Second, reward model training: collect human comparisons (given prompt \(x\) and two responses \(y_1, y_2\), which is better?) and train a reward model \(r_\phi(x, y)\) to predict human preferences. The reward model is trained with a pairwise ranking loss:

\[\mathcal{L}_{\text{RM}} = -\log \sigma(r_\phi(x, y_w) - r_\phi(x, y_l))\]
  • where \(y_w\) is the preferred response and \(y_l\) is the dispreferred one.

  • Third, RL fine-tuning: optimise the language model to maximise the reward while staying close to the SFT model (to prevent mode collapse). This uses PPO (Proximal Policy Optimisation, from chapter 06) with a KL penalty:

\[\mathcal{L}_{\text{RL}} = -\mathbb{E}\left[r_\phi(x, y) - \beta \, D_{\text{KL}}(\pi_\theta \| \pi_{\text{SFT}})\right]\]
  • The KL term prevents the model from drifting too far from the base model and exploiting quirks of the reward model ("reward hacking").

RLHF Pipeline

  • DPO (Direct Preference Optimisation, Rafailov et al., 2023) simplifies RLHF by eliminating the reward model entirely. The key mathematical insight is that the KL-constrained RL objective above has a closed-form optimal policy:
\[\pi^\ast(y \mid x) = \frac{1}{Z(x)} \pi_{\text{ref}}(y \mid x) \exp\!\left(\frac{r(x, y)}{\beta}\right)\]
  • where \(Z(x)\) is a normalising partition function. Rearranging this for the reward gives \(r(x, y) = \beta \log \frac{\pi^\ast(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta \log Z(x)\). Substituting this implicit reward into the Bradley-Terry preference model \(P(y_w \succ y_l) = \sigma(r(x, y_w) - r(x, y_l))\) causes the intractable \(Z(x)\) terms to cancel, yielding the DPO loss directly:
\[\mathcal{L}_{\text{DPO}} = -\log \sigma\!\left(\beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)}\right)\]
  • This is mathematically equivalent to RLHF but collapses the reward model and RL training into a single supervised step.

  • The expression inside the sigmoid can be read as: "increase the relative probability of the preferred response and decrease the relative probability of the dispreferred response, measured against the reference model."

  • The \(\beta\) parameter controls how much the policy can deviate from the reference. In practice, DPO is simpler to implement (just compute log-probabilities under the current and reference models for both completions) and avoids the instabilities of PPO training.

  • Constitutional AI (Bai et al., 2022) automates parts of the alignment process. Instead of collecting human comparisons, it uses the language model itself to critique and revise its own outputs according to a set of principles (the "constitution"), such as "choose the response that is less harmful." The AI-generated comparisons are then used for preference training (RLAIF: RL from AI Feedback).

  • Long-context methods address the \(O(n^2)\) memory and compute cost of standard self-attention, which limits sequence length. As \(n\) grows into the tens or hundreds of thousands of tokens, standard attention becomes infeasible.

  • Sparse attention replaces the dense \(n \times n\) attention matrix with a sparse pattern where each token attends to only a subset of other tokens. Common patterns include local attention (each token attends to a fixed-size window of neighbours), strided attention (attend to every \(k\)-th token), and random attention (attend to a random subset). Combinations of these patterns (used in BigBird, Longformer) achieve \(O(n)\) or \(O(n \sqrt{n})\) complexity while maintaining the ability to capture both local and global dependencies.

Sparse Attention Patterns

  • Sliding window attention restricts each token to attend only to the previous \(w\) tokens (its local window). This is \(O(nw)\) rather than \(O(n^2)\), but long-range information must propagate through overlapping windows across layers. With \(L\) layers and window size \(w\), the effective receptive field is \(L \times w\) tokens.

  • Ring attention distributes long sequences across multiple devices by arranging them in a ring topology. Each device holds a chunk of the sequence and computes attention for its chunk while simultaneously sending key-value blocks to the next device in the ring. This overlaps computation with communication and allows sequences of arbitrary length limited only by the total memory across all devices, not the memory of any single one.

  • Memory-augmented models extend context by equipping the Transformer with an external memory bank. At each layer, the model can read from and write to this memory using attention. Memorizing Transformers cache key-value pairs from previous chunks and attend to them in subsequent chunks, effectively extending context beyond the training window. The retrieval is approximate (using \(k\)-nearest neighbours over cached keys) to keep it efficient.

  • The methods above are architectural solutions to long context. Equally important is how models are trained to use long contexts effectively.

  • Progressive context extension is the standard approach. Training on very long sequences from the start is prohibitively expensive (\(O(n^2)\) attention cost), so models are pre-trained at a short context length (typically 4K–8K tokens) and then continued pre-training extends to the target length in stages.

  • Llama 3.1 extends from 8K to 128K over 800B tokens with gradually increasing sequence length. DeepSeek-V3 trains at 4K, then extends to 32K, then 128K.

  • Each stage uses a modest number of tokens (relative to the full pre-training budget) because the model only needs to learn how to use longer positions, not relearn language itself.

  • The position encoding must be adjusted during extension. RoPE interpolation scales down the position indices so that the model sees the same rotation angles it was trained on, just spread over a longer sequence. If the model was trained at length \(L\) and you want to extend to \(L' = 4L\), you divide all position indices by 4.

  • This means the model never sees a rotation angle it has not encountered, but the effective resolution between adjacent positions drops.

  • RoPE extrapolation keeps the original position indices unchanged and simply applies RoPE to positions beyond \(L\), relying on the model generalising to unseen angles.

  • Interpolation is much more stable; extrapolation degrades rapidly without base frequency adjustment (ABF).

  • YaRN (Yet another RoPE extensioN) improves on naive interpolation by recognising that not all RoPE dimensions should be treated equally.

  • High-frequency dimensions (small \(i\) in \(\theta_i = \theta_{\text{base}}^{-2i/d}\)) rotate many times within the training length and can extrapolate well.

  • Low-frequency dimensions (large \(i\)) rotate slowly and are more sensitive to length extension.

  • YaRN interpolates only the low-frequency dimensions, extrapolates the high-frequency ones, and applies a temperature scaling \(t\) to the attention logits to compensate for the distributional shift:

\[\text{score}'_{ij} = \frac{q_i^T k_j}{t \sqrt{d_k}}\]
  • where \(t > 1\) flattens the attention distribution, preventing the model from attending too sharply to nearby tokens when position signals are compressed.

  • Long-context data curation is a critical and often underestimated challenge. Most pre-training corpora consist of short documents (news articles, web pages, social media posts).

  • Long-context training requires a data mix that actually exercises the full context window: books, code repositories, long-form scientific articles, multi-turn conversation logs, and concatenated thematically related documents.

  • If the model is only trained on short documents padded or packed to fill the context window, it learns to ignore distant tokens because they are never relevant.

  • Sequence packing is a training efficiency technique: multiple documents are concatenated into a single training sequence to avoid padding waste, with attention masks preventing cross-document attention.

  • For long-context training, the packing strategy matters: packing many unrelated short documents teaches the model that distant tokens are noise, while packing fewer, genuinely long documents teaches it to use the full context.

  • A known failure mode is the "lost in the middle" phenomenon (Liu et al., 2023): language models tend to use information at the beginning and end of the context window effectively but struggle with information placed in the middle.

  • This resembles the serial position effect in human memory (primacy and recency).

  • It arises partly from training data distributions (important information is often at the start or end of documents) and partly from attention patterns that concentrate on nearby and initial tokens.

  • Long-context training with diverse placement of key information mitigates but does not fully solve this.

  • Needle-in-a-haystack evaluation tests whether a model can retrieve a specific fact ("the needle") placed at various positions within a long distractor context ("the haystack").

  • A model with genuine long-context ability should achieve near-perfect retrieval regardless of where the needle is placed.

  • This test reveals the lost-in-the-middle effect clearly and is used to benchmark context extension methods.

  • Long-context fine-tuning after pre-training uses targeted SFT data: long multi-turn dialogues, document QA with evidence scattered across thousands of tokens, long-form summarisation, and repository-level code understanding.

  • Qwen3 uses Dual Chunk Attention (DCA) during this stage, which processes long sequences as pairs of chunks where intra-chunk attention is full and inter-chunk attention is efficient, achieving 4x the effective sequence capacity during fine-tuning.

  • State Space Models (SSMs) offer a fundamentally different approach to long-sequence modelling. Rather than modifying attention, they replace it entirely with a linear dynamical system inspired by continuous-time control theory.

  • An SSM maps an input sequence \(u(t)\) to an output \(y(t)\) through a latent state \(x(t) \in \mathbb{R}^N\) governed by:

\[x'(t) = Ax(t) + Bu(t), \quad y(t) = Cx(t) + Du(t)\]
  • where \(A \in \mathbb{R}^{N \times N}\) is the state transition matrix, \(B \in \mathbb{R}^{N \times 1}\) is the input projection, \(C \in \mathbb{R}^{1 \times N}\) is the output projection, and \(D\) is a skip connection.

  • To apply this to discrete sequences (tokens), the continuous system is discretised using a step size \(\Delta\). The zero-order hold discretisation gives:

\[\bar{A} = \exp(\Delta A), \quad \bar{B} = (\Delta A)^{-1}(\exp(\Delta A) - I) \cdot \Delta B\]
  • The discrete recurrence then becomes \(x_k = \bar{A} x_{k-1} + \bar{B} u_k\), \(y_k = C x_k + D u_k\), which looks like an RNN: process one token at a time with a hidden state.

  • Unlike RNNs, this recurrence can also be unrolled as a global convolution: because the system is linear, the output is \(y = \bar{K} \ast u\) where the kernel \(\bar{K} = (C\bar{B}, \, C\bar{A}\bar{B}, \, C\bar{A}^2\bar{B}, \ldots)\) depends only on the fixed parameters.

  • This dual view — recurrence for efficient autoregressive inference (\(O(1)\) per step) and convolution for efficient parallel training (\(O(n \log n)\) via FFT) — is the central insight of SSMs.

SSM Dual View: recurrence for inference, convolution for training, and Mamba's selective extension

  • S4 (Structured State Spaces for Sequence Modeling, Gu et al., 2022) made SSMs practical by solving the key numerical challenge: the state matrix \(A\) must capture long-range dependencies, but naively parameterising it leads to vanishing or exploding dynamics (the same problem as vanilla RNNs).

  • S4 initialises \(A\) using the HiPPO (High-order Polynomial Projection Operators) matrix, which is derived from the theory of optimal polynomial approximation of continuous signals. The HiPPO matrix has a specific structure that provably enables the state to maintain a compressed representation of the entire input history with graceful decay.

\[A_{nk} = -\begin{cases} (2n+1)^{1/2}(2k+1)^{1/2} & \text{if } n > k \\ n+1 & \text{if } n = k \\ 0 & \text{if } n < k \end{cases}\]
  • This lower-triangular structure ensures that the state acts as an online approximation of the input signal using Legendre polynomials. Computing \(\bar{A}^k\) for long kernels is expensive, so S4 uses the fact that the HiPPO matrix can be decomposed as a sum of low-rank and diagonal terms, enabling \(O(n \log n)\) kernel computation.

  • Mamba (Gu and Dao, 2023) introduces the critical innovation of selective state spaces: making the SSM parameters input-dependent. In S4, the matrices \(A\), \(B\), \(C\), and the step size \(\Delta\) are fixed — the same dynamics apply to every token regardless of content. Mamba makes \(B\), \(C\), and \(\Delta\) functions of the input:

\[B_k = \text{Linear}(u_k), \quad C_k = \text{Linear}(u_k), \quad \Delta_k = \text{softplus}(\text{Linear}(u_k))\]
  • This selectivity allows the model to decide, at each position, what information to store in the state and what to ignore — analogous to how attention selects relevant tokens, but without the quadratic cost. The step size \(\Delta_k\) controls the "gate": a large \(\Delta\) causes the state to integrate the current input strongly (the continuous dynamics advance a large step, effectively resetting the state), while a small \(\Delta\) preserves the existing state and ignores the current input.

  • The trade-off is that input-dependent parameters break the convolution view (the kernel is no longer fixed), so Mamba cannot use FFT-based training. Instead, it uses a hardware-aware parallel scan algorithm that exploits the associativity of the recurrence: the state update \((x_k, u_k) \mapsto x_{k+1}\) can be expressed as a sequence of associative operations and parallelised using a prefix sum (scan), analogous to parallel prefix addition in hardware design. This runs in \(O(n)\) time with \(O(\log n)\) depth on a GPU, nearly matching the efficiency of convolution.

  • Mamba achieves inference that is truly \(O(1)\) per token (just update the fixed-size state, no KV cache that grows with context), making it fundamentally more memory-efficient than Transformers at long sequence lengths. The state size \(N\) (typically 16) is much smaller than a Transformer's KV cache, which stores \(O(n \cdot d)\) values. In practice, Mamba matches or exceeds Transformer quality at the same parameter count on language modelling benchmarks, with significantly faster inference on long sequences.

  • Mamba-2 and Structured State Space Duality (SSD) (Dao and Gu, 2024) uncovered a deep mathematical unification between state-space models and attention. When the state transition matrix is simplified to a scalar multiple of the identity (\(A_t = a_t I\)), a selective SSM and a structured form of masked linear attention are two factorisations of the exact same semiseparable matrix \(M\).

\[y = (L \circ Q K^T) V \quad \Longleftrightarrow \quad h_t = a_t h_{t-1} + B_t x_t, \quad y_t = C_t^T h_t\]
  • Here \(L\) is the lower-triangular causal decay mask with entries \(L_{ij} = \prod_{k=j+1}^{i} a_k\) for \(i \ge j\) and \(0\) otherwise, while \(Q, K, V\) correspond directly to the SSM projections \(C, B, x\). Because SSD casts sequence mixing into chunked matrix multiplications rather than only sequential scans, Mamba-2 runs directly on GPU tensor cores (chapter 19), training 2x to 8x faster than original Mamba while supporting far larger state dimensions.

  • Gated DeltaNet (Yang et al., 2024) solves a lingering weakness of both vanilla linear attention and Mamba-2, namely blurry associative recall. Standard linear attention accumulates key-value pairs by simple addition (\(S_t = \alpha_t S_{t-1} + v_t k_t^T\)), so when many keys share similar directions, old associations interfere with new ones. Gated DeltaNet combines Mamba-2's data-dependent decay gate \(\alpha_t \in (0, 1)\) (for fast memory erasure when topics shift) with the delta rule (Widrow-Hoff error-correcting memory update), which first retrieves what memory currently predicts for key \(k_t\) and writes only the correction.

\[S_t = \alpha_t S_{t-1} + \beta_t \left(v_t - \alpha_t S_{t-1} k_t\right) k_t^T = S_{t-1}\left(\alpha_t I - \beta_t k_t k_t^T\right) + \beta_t v_t k_t^T\]
  • Intuitively, the term \(\alpha_t\) clears stale context across the whole memory while the delta update \((v_t - \alpha_t S_{t-1} k_t)\) surgically overwrites a specific key's slot without disturbing unrelated slots. This delivers substantially sharper in-context retrieval and long-context needle-in-a-haystack accuracy than pure gated SSMs.

  • Test-Time Training (TTT) and Titans push recurrent memory one conceptual leap further by turning the hidden state itself into a neural fast-weight memory updated online at test time via gradient descent. In TTT (Sun et al., 2024), each sequence layer's hidden state is no longer a static vector or linear matrix, it is a small neural network (a linear model or two-layer MLP) whose weights \(W_t\) are optimised token by token on a self-supervised reconstruction loss \(\ell\) as context streams in.

\[W_t = W_{t-1} - \eta_t \nabla_W \ell(W_{t-1}; x_t)\]
  • Titans (Behrouz et al., 2024) pairs precise short-term sliding-window attention with a deep neural long-term memory trained online using momentum, adaptive weight decay (forgetting), and a gradient-norm surprise signal (unexpected tokens produce larger gradients and therefore write more strongly into memory), enabling effective reasoning across contexts exceeding 2 million tokens. This dual fast-weight architecture echoes the interplay between working memory and long-term consolidation in cognitive science (chapter 11) and rapid synaptic plasticity in neuroAI (chapter 12).

  • Hybrid SSM-attention and linear-attention architectures combine sub-quadratic layers for the vast majority of the network with periodic full softmax attention layers for exact content-based lookup. Models such as Jamba and Zamba interleave Mamba and Transformer blocks, while MiniMax-01 (456B total parameters, 45.9B active) interleaves seven layers of hardware-efficient Lightning linear attention with every single softmax attention layer to reach 1M to 4M token context windows. In practice, hybrid ratios capture the complementary strengths of both families, pairing linear-time state propagation with surgical long-range retrieval.

  • Retrieval-Augmented Generation (RAG) addresses the knowledge limitations of language models by giving them access to an external knowledge base at inference time. Instead of relying solely on knowledge encoded in model parameters during training, RAG retrieves relevant documents and conditions generation on them.

  • The classic retriever-reader architecture has two components. The retriever takes a query and fetches the top-\(k\) most relevant passages from a corpus. The reader (a language model) generates the answer conditioned on both the query and the retrieved passages. The retriever can use sparse methods (BM25, which extends TF-IDF from file 02) or dense methods.

  • Dense passage retrieval (DPR) uses a dual-encoder architecture: one encoder maps questions to vectors, another maps passages to vectors. Both are typically BERT-based. At indexing time, all passages are encoded and stored. At query time, the question is encoded and the nearest passages are found using approximate nearest neighbour search (such as FAISS). The similarity metric is the dot product between question and passage vectors.

  • Chunking strategies affect retrieval quality significantly. Documents must be split into passages small enough for the retriever to handle, but large enough to contain complete ideas. Fixed-size chunking (e.g., 256 tokens with 50-token overlap) is simple but may split sentences awkwardly. Semantic chunking splits at paragraph or section boundaries. Hierarchical chunking creates a tree of summaries at different granularities.

RAG Architecture

  • RAG provides several advantages: the knowledge base can be updated without retraining the model, the model can cite sources, and hallucination is reduced because the model can ground its answers in retrieved text. The main challenges are retrieval quality (if the wrong passages are retrieved, the model may produce wrong answers confidently) and latency (retrieval adds a step to inference).

  • Speculative decoding accelerates autoregressive generation by using a small, fast draft model to propose multiple tokens in parallel, which are then verified by the large target model in a single forward pass.

  • The algorithm works as follows: the draft model generates \(k\) candidate tokens autoregressively (this is fast because the draft model is small).

  • The target model then scores all \(k\) tokens simultaneously in a single forward pass (this is efficient because the work is batched).

  • For each candidate token \(t\) sampled from the draft distribution \(p_d(t)\), it is accepted with probability \(\min(1, \, p_{\text{target}}(t) / p_d(t))\). If rejected, a corrected token is resampled from the adjusted distribution \(p_{\text{adj}}(t) = \max(0, \, p_{\text{target}}(t) - p_d(t))\), normalised.

  • This acceptance-rejection scheme guarantees that the output distribution is identical to the target model alone.

  • To see why, consider the effective probability of emitting token \(t\). It can be accepted directly (probability \(p_d(t) \cdot \min(1, p_{\text{target}}(t)/p_d(t))\)) or produced through resampling.

  • For tokens where \(p_{\text{target}}(t) \leq p_d(t)\), the direct acceptance contributes \(p_{\text{target}}(t)\). For tokens where \(p_{\text{target}}(t) > p_d(t)\), direct acceptance contributes \(p_d(t)\) and resampling contributes the remainder \(p_{\text{target}}(t) - p_d(t)\) (after accounting for the rejection probability).

  • In both cases, the total probability of emitting \(t\) equals \(p_{\text{target}}(t)\). The draft model affects only speed, not quality.

Speculative Decoding

  • The speedup depends on the acceptance rate: if the draft model is well-aligned with the target model, most tokens are accepted and the wall-clock time is roughly that of the draft model. Typical speedups are 2-3x with no quality degradation.

  • Medusa (Cai et al., 2024) takes a different approach: instead of a separate draft model, it adds multiple lightweight prediction heads to the target model itself. Each head predicts a different future token position simultaneously (\(k = 1, 2, 3, \ldots\) steps ahead). At each step, Medusa proposes several candidate continuations using a tree structure, and a single forward pass through the target model's attention layers verifies which candidates are consistent. This avoids the need for a separate draft model entirely.

  • Parallel generation methods more broadly aim to break the sequential bottleneck of autoregressive decoding. Jacobi decoding initialises all positions with guesses and iteratively refines them in parallel until convergence, treating generation as a fixed-point iteration. Non-autoregressive models (NAT) generate all tokens simultaneously in a single forward pass but typically suffer quality degradation and require techniques like iterative refinement, CTC loss, or knowledge distillation from autoregressive teachers to close the gap.

  • The techniques above — alignment, long context, retrieval, efficient decoding, state space models — come together in modern production LLMs.

  • The remainder of this file surveys the architectural innovations in frontier models, showing how theoretical ideas from files 01–04 and the methods above are combined in practice.

  • Grouped Query Attention (GQA) is the most widely adopted attention efficiency technique. Standard multi-head attention (MHA) maintains separate key and value projections per head, requiring \(n_{\text{heads}} \times d_{\text{head}}\) values cached per token. GQA groups multiple query heads to share a single key-value head.

  • With 64 query heads and 8 KV heads (a common configuration in Llama 3, Qwen, Gemma), each KV head is shared by 8 query heads, reducing the KV cache by 8x compared to MHA.

  • The output quality is nearly identical to MHA because the queries can still attend to different patterns, they just share the same key-value subspace. Multi-query attention (MQA) is the extreme case with a single KV head for all queries, but GQA provides a better quality-efficiency trade-off.

  • Multi-head Latent Attention (MLA), introduced in DeepSeek-V2, achieves even more aggressive KV cache compression. Instead of caching the full key-value projections (even with GQA), MLA down-projects the hidden state into a low-rank latent vector \(c_t \in \mathbb{R}^{d_c}\) with \(d_c \ll n_{\text{heads}} \times d_{\text{head}}\):

\[c_t = W_{\text{down}} \, h_t\]
  • Only this compressed vector is cached. At attention time, the full key and value representations are reconstructed via up-projection: \(k_t = W_{\text{up}}^K c_t\), \(v_t = W_{\text{up}}^V c_t\). In DeepSeek-V3 (671B total parameters, 37B active), the compression dimension is \(d_c = 512\) versus \(128 \times 128 = 16{,}384\) for full MHA, a 93% reduction in KV cache.

  • A subtlety: standard RoPE is position-dependent and incompatible with the shared compression, so MLA uses decoupled RoPE: a small separate stream of the query and key (64 dimensions per head) carries position information via RoPE, while the bulk of the representation flows through the compressed latent path.

Attention KV Cache Strategies: MHA, GQA, and MLA compared

  • Position encoding at scale has diverged significantly from the original sinusoidal scheme. All frontier models use RoPE (file 04), but with key modifications for long context. The base frequency \(\theta_{\text{base}}\) in the original RoPE formula \(\theta_i = \theta_{\text{base}}^{-2i/d}\) is typically 10,000, which limits extrapolation beyond the training length.

  • Adjusted Base Frequency (ABF) simply increases \(\theta_{\text{base}}\) to 500,000 (Llama 3) or 1,000,000 (Qwen3, Gemma 3), stretching the rotation periods so the model encounters fewer full rotations during training and can extrapolate further.

  • YaRN (Yet another RoPE extensioN) applies frequency-dependent interpolation: low-frequency dimensions are interpolated (scaled down), high-frequency dimensions are extrapolated, and a temperature factor adjusts the attention distribution. DeepSeek-V3, Qwen, and Kimi K2 all use YaRN-based extension to reach 128K context from models pre-trained at 4K–8K.

  • iRoPE (interleaved RoPE), introduced in Llama 4, takes a more radical approach: every 4th attention layer uses no positional encoding at all (NoPE), while the other layers use standard RoPE with chunked attention.

  • The NoPE layers can attend to all positions without any positional bias, while the RoPE layers provide local ordering. Combined with temperature scaling at inference, this enables Llama 4 Scout's 10M-token context window — orders of magnitude beyond any pure RoPE approach.

  • Mixture of Experts at scale has become the dominant architecture for frontier models (file 04 introduced MoE fundamentals). The key design choices are the number of experts, routing sparsity, and load balancing.

  • Routing sparsity varies significantly: DeepSeek-V3 uses 256 experts with top-8 routing (32x sparsity), Qwen3 uses 128 experts with top-8 (16x sparsity), Mixtral uses 8 experts with top-2 (4x sparsity), and Llama 4 Maverick uses 128 experts with top-1 plus a shared expert (128x sparsity).

  • Higher sparsity means more total parameters for the same active compute, but requires more careful load balancing and communication infrastructure.

  • Auxiliary-loss-free load balancing (Wang et al., 2024, deployed at scale in DeepSeek-V3) replaces the traditional load-balancing loss (file 04), which fights against the language modelling objective and degrades model quality. Instead, each expert \(i\) carries a dynamic bias term \(b_i\) used strictly to steer top-\(K\) selection while keeping the final gating weight equal to the unbiased affinity score \(s_i\).

\[g'_i = \begin{cases} s_i & \text{if } s_i + b_i \in \text{TopK}(\{s_j + b_j\}_{j=1}^{E}, K) \\ 0 & \text{otherwise} \end{cases}\]
  • After every training step, overloaded experts have \(b_i\) nudged down by a small step \(\gamma\) and underloaded experts have \(b_i\) nudged up by \(\gamma\). Because no auxiliary penalty enters the gradient, routing stays balanced without polluting representation learning.

  • Fine-grained and shared experts refine sparse MoE capacity further. Splitting a few coarse FFNs into many fine-grained experts (for example, 256 small experts with top-8 routing) allows far richer combinations of specialised sub-networks per token. Pairing those routed experts with one or more always-active shared experts ensures that universal linguistic knowledge (basic syntax, punctuation, common function words) lives in a dedicated shared path rather than being duplicated wastefully across routed experts.

  • Alternating dense and MoE layers provide another design axis. Gemma 2 and 3 alternate local and global attention layers (5 local 1,024-token sliding-window layers for every 1 global 128K-context layer in Gemma 3, cutting KV cache memory dramatically, chapter 20). Llama 4 Maverick interleaves dense FFN layers with MoE layers, and Kimi K2 uses hybrid-sparsity layouts so different depths specialise in different kinds of routing.

  • Multi-Token Prediction (MTP) (Gloeckle et al., 2024; DeepSeek-V3) trains the model to predict not only the immediate next token \(w_{t+1}\), but also several future tokens \(w_{t+2}, \dots, w_{t+D}\) in parallel at every position using lightweight shared-embedding prediction heads. Predicting multiple steps ahead delivers a denser training signal that forces intermediate hidden states to plan ahead rather than greedily fitting local transitions, boosting coding and algorithmic reasoning accuracy. At inference time, those already-trained MTP heads double as free draft heads for speculative decoding (connecting directly to the verification algorithm above and serving pipelines in chapter 20), accelerating generation without maintaining a separate draft model.

  • Knowledge distillation is a training strategy where a large "teacher" model's outputs guide the training of a smaller "student" model. Gemma 2 and 3 use distillation extensively: the smaller models (2B, 4B) are trained on 50x the compute-optimal amount of data with the teacher's probability distributions as soft targets. This is why Gemma 3-4B matches Gemma 2-27B in quality.

  • The distillation loss replaces or supplements the standard cross-entropy: the student minimises the KL divergence between its output distribution and the teacher's:

\[\mathcal{L}_{\text{distill}} = D_{\text{KL}}(p_{\text{teacher}}(\cdot \mid x) \| p_{\text{student}}(\cdot \mid x))\]
  • DeepSeek-R1 distilled its 671B reasoning model into dense models as small as 1.5B using 800K curated chain-of-thought samples, producing small models with disproportionately strong reasoning.

  • Reasoning via reinforcement learning represents the most significant recent advance in LLM capabilities. DeepSeek-R1 demonstrated that pure reinforcement learning on a base model (without supervised fine-tuning) can elicit chain-of-thought reasoning, self-verification, and error correction, behaviours that emerge spontaneously when the model is rewarded for correct final answers.

  • DeepSeek-R1 uses GRPO (Group Relative Policy Optimisation), which eliminates the value network required by PPO. For each prompt, GRPO samples a group of \(G\) outputs, computes their rewards, and normalises advantages within the group:

\[A_i = \frac{r_i - \text{mean}(r_1, \ldots, r_G)}{\text{std}(r_1, \ldots, r_G)}\]
  • The policy gradient then uses these group-relative advantages with a clipped objective (similar to PPO's clipping).

  • Eliminating the critic network halves the memory and compute requirements of RL training, making it practical to train 671B-parameter models with RL.

  • A critical design choice: DeepSeek-R1 uses rule-based rewards (checking mathematical answers against ground truth, running code test cases) rather than neural reward models, because neural reward models were found to be susceptible to reward hacking at this scale.

  • Qwen3's hybrid thinking mode integrates reasoning (with <think> tags for step-by-step chain-of-thought) and fast direct response into a single model, allowing users to control a "thinking budget" that trades latency for reasoning depth.

  • This is achieved by training on both thinking and non-thinking data, not through separate model checkpoints.

Looped Transformers and Recurrent-Depth Models

  • Every standard Transformer we have studied so far obeys a rigid architectural bargain. To give a model more sequential computation steps (greater depth \(L\)), you must stack \(L\) distinct blocks with \(L\) separate sets of weights \(\theta_1, \dots, \theta_L\). As a result, parameter count and reasoning depth are locked together, and every single token (whether a predictable function word like "the" or a crucial algebraic leap) passes through the exact same fixed number of layers.

  • Looped Transformers (also called recurrent-depth models) break that coupling entirely. Instead of marching once through \(L\) separate layers, a Looped Transformer reuses one shared core block \(f_\theta\) iteratively for \(R\) steps before emitting a token. Scaling \(R\) at test time lets a compact model think deeper without adding a single parameter.

Comparison between a standard deep Transformer with L distinct weight sets and a Looped Recurrent-Depth Transformer reusing a shared core block R times with prelude, input injection, adaptive early-exit halting, and coda

  • The intellectual lineage stretches from early recurrent-depth theory to modern billion-parameter reasoning engines.

    • Universal Transformers (Dehghani et al., 2018) first introduced weight-tied depth across Transformer blocks, pairing the loop with Adaptive Computation Time (ACT) (Graves, 2016) so a learned halting gate could let simple tokens exit after a couple of iterations while complex tokens looped deeper.
    • Looped Transformers as Programmable Computers (Giannou et al., 2023) proved why looping is computationally profound. Placing a shallow constant-depth Transformer in a feedback loop turns the sequence into an editable tape, allowing a tiny fixed-weight model to emulate a general-purpose computer capable of executing multi-step algorithms, linear algebra routines, and even iterative in-context gradient descent.
  • Modern recurrent-depth language models organise the network into a clean three-part sandwich architecture.

    1. A small non-recurrent prelude \(P\) embeds the input tokens \(x\) into an initial working representation \(e = P(x)\) and sets the starting latent state \(h^{(0)}\).
    2. A shared recurrent core \(f_\theta\) (typically a tight stack of 2 to 4 Transformer layers) refines the latent state over \(k = 0, 1, \dots, R-1\) iterations using the same tied parameters \(\theta\) at every step.
    3. A small non-recurrent coda \(C\) projects the final refined latent state \(h^{(R)}\) into vocabulary logits \(y = C(h^{(R)})\).
  • A subtle failure mode arises if you naively feed \(h^{(k)}\) back into \(f_\theta\) dozens of times on its own. Repeated transformations gradually wash out the original input signal, causing representations to drift or collapse toward a dull fixed point. Modern looped models prevent state washout through input injection, re-supplying the static prelude representation \(x\) (or \(e = P(x)\)) at every single loop step alongside the evolving latent state.

\[h^{(k+1)} = f_\theta\!\left(h^{(k)}, \, x\right)\]
  • In practice, input injection is implemented either by concatenating and projecting \([h^{(k)}, e]\) back to the model dimension or by adding \(e\) into a normalised residual stream before each core pass (using RMSNorm to keep activation norms steady regardless of how large \(R\) grows). Because \(x\) remains freshly visible at iteration 1 and iteration 64 alike, the core can focus each loop on updating its working memory without ever forgetting the prompt.

  • Training a deep loop introduces an immediate memory challenge. Unrolling 32 or 64 loops and backpropagating through every step requires storing activations for all \(R\) iterations and risks exploding or vanishing gradients. Modern recurrent-depth pre-training solves both problems with two practical tricks.

    • Randomised loop depth samples a different number of recurrent steps \(R\) for each training batch (for example, drawing \(R\) from a log-normal or Poisson distribution). Because the model never knows in advance when the loop will stop, it learns to make steady, anytime progress at every iteration and generalises cleanly when run for even more loops at inference time.
    • Truncated backpropagation through loops runs the early iterations with gradients detached (stop_gradient) and propagates gradients only through the final \(k\) steps (such as the last 8 iterations). This bounds training activation memory to a small constant while still teaching the shared core to refine its latent state stably.
  • Two landmark model families have demonstrated that recurrent depth scales smoothly to real language modelling and reasoning.

    • Recurrent-Depth Latent Reasoning and Huginn-3.5B (Geiping et al., 2025, "Scaling up Test-Time Compute with Latent Reasoning, A Recurrent Depth Approach") trained a 3.5B-parameter prelude-core-coda Transformer (using a 4-layer recurrent core) on 800 billion tokens with randomised depth and truncated backpropagation. Simply dialling up the test-time loop count \(R\) allows Huginn-3.5B to solve challenging mathematical and coding benchmarks at a level comparable to much larger standard models, purely through next-token pre-training and without any explicit chain-of-thought fine-tuning data.
    • Ouro (Looped Language Models) (ByteDance, 2025) scaled looped pre-training to 7.7 trillion tokens across open-weight 1.4B and 2.6B models (looping a 24-layer backbone across multiple recurrent steps) equipped with an entropy-regularised learned early-exit halting gate. Easy tokens exit after minimal passes while multi-hop logical steps loop deeper, allowing Ouro-2.6B to rival dense models up to four times its parameter count.
  • Adaptive computation time and early-exit halting turn recurrent depth into a dynamic test-time budget. At each iteration \(k\), either a learned halting head predicts a stopping probability \(p_k = \sigma(w_h^T h^{(k)})\) (stopping once cumulative halting mass crosses a threshold) or the serving engine tracks the latent drift \(\|h^{(k)} - h^{(k-1)}\|\) (halting once the representation converges to a fixed point). This allocates compute where it actually matters rather than wasting identical FLOPs on every word.

  • Why does latent-space reasoning matter so much alongside explicit chain-of-thought (CoT) reasoning? Verbal CoT (trained with GRPO above) forces every intermediate thought to pass through a narrow bottleneck of discrete vocabulary tokens, inflating context lengths, KV cache memory, and serving latency (chapter 20). Furthermore, many algorithmic computations (such as graph traversal, multi-hop relational tracking, or maintaining parallel hypotheses) are clumsy to serialise into English prose. Looping inside continuous latent space lets the model perform rich multi-hop reasoning directly in high-dimensional vectors without emitting a single extra token, while remaining naturally composable with explicit CoT whenever human-readable steps are desired.

  • Training stabilisation at scale requires new techniques beyond standard practices. Logit soft-capping (Gemma 2) passes attention scores through \(s \cdot \tanh(\text{logits} / s)\) with a soft cap \(s\) (typically 30–50) to prevent unbounded growth.

  • QK-Norm (Qwen3) applies RMSNorm to query and key vectors before computing attention scores, replacing the need for QKV bias. QK-Clip (Kimi K2's MuonClip optimiser) monitors the maximum attention logit during training and rescales query-key weight matrices when they exceed a threshold, enabling stable pre-training of 1T-parameter models with zero instability events.

  • FP8 mixed-precision training (DeepSeek-V3) uses 8-bit floating point for the compute-intensive matrix multiplications in the forward and backward passes while keeping master weights in higher precision.

  • This roughly doubles throughput compared to BF16/FP16 training with negligible quality loss. DeepSeek-V3 trained its 671B-parameter model for only 2.8M H800 GPU-hours — a fraction of comparable models — largely due to this and other engineering optimisations.

Coding Tasks (use CoLab or notebook)

  1. Implement a simple retrieval-augmented generation pipeline from scratch. Index a set of documents using TF-IDF (file 02), retrieve the most relevant passage for a query, and prepend it to a prompt.

    import jax.numpy as jnp
    import math
    from collections import Counter
    
    # Knowledge base: a set of short passages
    knowledge_base = [
        "The Eiffel Tower is a wrought-iron lattice tower in Paris, France. It was constructed from 1887 to 1889 as the centerpiece of the 1889 World's Fair.",
        "The Great Wall of China is a series of fortifications built along the northern borders of China. Construction began in the 7th century BC.",
        "Photosynthesis is the process by which plants convert sunlight, water, and carbon dioxide into glucose and oxygen using chlorophyll.",
        "The theory of general relativity, published by Albert Einstein in 1915, describes gravity as the curvature of spacetime caused by mass and energy.",
        "Python is a high-level programming language known for its simple syntax and readability. It was created by Guido van Rossum and released in 1991.",
        "The mitochondria are organelles found in eukaryotic cells. They generate most of the cell's supply of ATP, used as a source of chemical energy.",
    ]
    
    # Build TF-IDF index (reusing concepts from file 02)
    def tokenise(text):
        return text.lower().split()
    
    vocab = sorted(set(w for doc in knowledge_base for w in tokenise(doc)))
    word2idx = {w: i for i, w in enumerate(vocab)}
    V = len(vocab)
    N = len(knowledge_base)
    
    # Document frequencies
    doc_freq = Counter()
    for doc in knowledge_base:
        for w in set(tokenise(doc)):
            doc_freq[w] += 1
    
    def tfidf_vector(text):
        words = tokenise(text)
        counts = Counter(words)
        vec = jnp.zeros(V)
        for w, c in counts.items():
            if w in word2idx:
                tf = 1 + math.log(c)
                idf = math.log(N / (doc_freq.get(w, 0) + 1))
                vec = vec.at[word2idx[w]].set(tf * idf)
        return vec
    
    # Index all documents
    doc_vectors = jnp.stack([tfidf_vector(doc) for doc in knowledge_base])
    
    def cosine_sim(a, b):
        return jnp.dot(a, b) / (jnp.linalg.norm(a) * jnp.linalg.norm(b) + 1e-8)
    
    def retrieve(query, top_k=2):
        """Retrieve top-k most relevant passages for a query."""
        q_vec = tfidf_vector(query)
        sims = jnp.array([cosine_sim(q_vec, doc_vectors[i]) for i in range(N)])
        top_indices = jnp.argsort(-sims)[:top_k]
        return [(int(i), float(sims[i]), knowledge_base[int(i)]) for i in top_indices]
    
    # Test retrieval
    queries = [
        "Who built the Eiffel Tower?",
        "How do plants make food?",
        "What did Einstein discover?",
    ]
    
    for query in queries:
        results = retrieve(query, top_k=1)
        print(f"\nQuery: '{query}'")
        for idx, sim, passage in results:
            print(f"  Retrieved (sim={sim:.3f}): '{passage[:80]}...'")
    
        # RAG-style prompt construction
        context = results[0][2]
        rag_prompt = f"Context: {context}\n\nQuestion: {query}\nAnswer:"
        print(f"  RAG prompt:\n    {rag_prompt[:120]}...")
    

  2. Implement speculative decoding with a toy draft and target model. Show that the accepted output matches the target model's distribution.

    import jax
    import jax.numpy as jnp
    
    # Simulate a draft model (fast, less accurate) and target model (slow, accurate)
    vocab_size = 8
    seq_len = 5
    
    key = jax.random.PRNGKey(42)
    
    # Target model: returns logits given a sequence
    def target_model(seq, key):
        """Simulated target model: produces token logits (expensive)."""
        # In practice this would be a large Transformer forward pass
        k1, k2 = jax.random.split(key)
        logits = jax.random.normal(k1, (len(seq), vocab_size)) * 2
        # Make it somewhat predictable: bias toward token (seq[-1] + 1) % vocab_size
        for i in range(len(seq)):
            logits = logits.at[i, (seq[i] + 1) % vocab_size].add(3.0)
        return logits
    
    def draft_model(seq, key):
        """Simulated draft model: similar but noisier (cheap)."""
        k1, k2 = jax.random.split(key)
        logits = jax.random.normal(k1, (len(seq), vocab_size))
        for i in range(len(seq)):
            logits = logits.at[i, (seq[i] + 1) % vocab_size].add(2.0)
        return logits
    
    def sample_token(logits, key):
        return jax.random.categorical(key, logits)
    
    def speculative_decode(prefix, draft_steps=3, key=jax.random.PRNGKey(0)):
        """Speculative decoding: draft proposes, target verifies."""
        seq = list(prefix)
        total_accepted = 0
        total_proposed = 0
    
        for _ in range(4):  # generate 4 rounds
            key, *subkeys = jax.random.split(key, draft_steps + 3)
    
            # Draft model proposes draft_steps tokens
            draft_tokens = []
            draft_probs = []
            draft_seq = list(seq)
            for i in range(draft_steps):
                d_logits = draft_model(jnp.array(draft_seq), subkeys[i])
                d_probs = jax.nn.softmax(d_logits[-1])
                tok = sample_token(d_logits[-1], subkeys[i])
                draft_tokens.append(int(tok))
                draft_probs.append(d_probs)
                draft_seq.append(int(tok))
    
            # Target model scores all draft tokens in one pass
            target_logits = target_model(jnp.array(draft_seq), subkeys[draft_steps])
            target_start = len(seq) - 1  # position of last prefix token
    
            # Accept/reject each draft token
            accepted = 0
            for i in range(draft_steps):
                t_probs = jax.nn.softmax(target_logits[target_start + i])
                d_prob = draft_probs[i][draft_tokens[i]]
                t_prob = t_probs[draft_tokens[i]]
    
                # Accept with probability min(1, target_prob / draft_prob)
                accept_prob = jnp.minimum(1.0, t_prob / (d_prob + 1e-10))
                key, accept_key = jax.random.split(key)
                if jax.random.uniform(accept_key) < accept_prob:
                    seq.append(draft_tokens[i])
                    accepted += 1
                else:
                    # Reject: sample from adjusted distribution
                    key, resample_key = jax.random.split(key)
                    adjusted = jnp.maximum(0, t_probs - draft_probs[i])
                    adjusted = adjusted / (adjusted.sum() + 1e-10)
                    new_tok = jax.random.categorical(resample_key, jnp.log(adjusted + 1e-10))
                    seq.append(int(new_tok))
                    break
    
            total_accepted += accepted
            total_proposed += draft_steps
    
        return seq, total_accepted, total_proposed
    
    # Run speculative decoding
    prefix = [0, 1]
    result_seq, accepted, proposed = speculative_decode(prefix)
    acceptance_rate = accepted / proposed if proposed > 0 else 0
    
    print(f"Prefix: {prefix}")
    print(f"Generated sequence: {result_seq}")
    print(f"Draft proposals: {proposed}")
    print(f"Accepted: {accepted}")
    print(f"Acceptance rate: {acceptance_rate:.1%}")
    print(f"Speedup potential: {(accepted + proposed) / proposed:.2f}x")
    

  3. Build a simple DPO training loop. Given pairs of preferred and dispreferred completions, update a small model using the DPO loss.

    import jax
    import jax.numpy as jnp
    
    # Tiny language model: linear projection from one-hot to logits
    vocab_size = 10
    seq_len = 4
    
    key = jax.random.PRNGKey(42)
    k1, k2 = jax.random.split(key)
    
    # Current policy parameters (trainable)
    theta = jax.random.normal(k1, (vocab_size, vocab_size)) * 0.1
    # Reference policy parameters (frozen copy of initial theta)
    theta_ref = theta.copy()
    
    def log_prob_sequence(params, sequence):
        """Compute log P(sequence) under a simple autoregressive model."""
        total = 0.0
        for t in range(1, len(sequence)):
            # Simple: logits at position t depend on token at t-1
            logits = params[sequence[t-1]]
            log_probs = jax.nn.log_softmax(logits)
            total += log_probs[sequence[t]]
        return total
    
    def dpo_loss(theta, theta_ref, preferred, dispreferred, beta=0.1):
        """Direct Preference Optimisation loss for one pair."""
        log_pi_w = log_prob_sequence(theta, preferred)
        log_pi_l = log_prob_sequence(theta, dispreferred)
        log_ref_w = log_prob_sequence(theta_ref, preferred)
        log_ref_l = log_prob_sequence(theta_ref, dispreferred)
    
        # DPO objective
        return -jax.nn.log_sigmoid(
            beta * ((log_pi_w - log_ref_w) - (log_pi_l - log_ref_l))
        )
    
    # Preference dataset: (prompt_prefix, preferred_completion, dispreferred_completion)
    preferences = [
        (jnp.array([1, 3, 5, 7]), jnp.array([1, 3, 5, 2])),  # prefer 7 over 2 at end
        (jnp.array([0, 2, 4, 6]), jnp.array([0, 2, 4, 9])),  # prefer 6 over 9
        (jnp.array([3, 3, 3, 3]), jnp.array([3, 3, 3, 0])),  # prefer repeating over 0
        (jnp.array([5, 6, 7, 8]), jnp.array([5, 6, 7, 1])),  # prefer 8 over 1
    ]
    
    grad_fn = jax.jit(jax.grad(dpo_loss))
    lr = 0.05
    
    print("Training DPO...")
    for epoch in range(100):
        total_loss = 0.0
        for preferred, dispreferred in preferences:
            loss = dpo_loss(theta, theta_ref, preferred, dispreferred)
            grads = grad_fn(theta, theta_ref, preferred, dispreferred)
            theta = theta - lr * grads
            total_loss += loss
        if (epoch + 1) % 20 == 0:
            avg_loss = total_loss / len(preferences)
            print(f"  Epoch {epoch+1}: avg DPO loss = {avg_loss:.4f}")
    
    # Check: the model should now prefer the preferred completions
    print("\nPreference check after DPO training:")
    for preferred, dispreferred in preferences:
        lp_w = log_prob_sequence(theta, preferred)
        lp_l = log_prob_sequence(theta, dispreferred)
        print(f"  Preferred {list(preferred.astype(int))}: logP={lp_w:.3f}  "
              f"Dispreferred {list(dispreferred.astype(int))}: logP={lp_l:.3f}  "
              f"{'correct' if lp_w > lp_l else 'WRONG'}")
    

  4. Build a Looped Transformer (prelude, shared self-attention recurrent core with input injection and RMS-style unit normalisation, and coda) in JAX and train it exclusively on short 1-hop and 2-hop pointer-chasing chains. Then scale the test-time loop count \(R\) from 1 to 6 with the exact same frozen parameters to watch accuracy climb on unseen 3-, 4-, and 5-hop reasoning chains, and measure adaptive early-exit depth by problem difficulty.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Multi-hop pointer-chasing task over N=6 entities (0..5).
    # Each sequence encodes directed edges u -> v ending at a self-loop sink (sink -> sink).
    N = 6
    E = jnp.eye(N)
    
    def make_dataset(seed, num_samples, min_hops, max_hops):
        key = jax.random.PRNGKey(seed)
        keys_batch, vals_batch, starts, targets, hops_list = [], [], [], [], []
        for _ in range(num_samples):
            key, k1, k2 = jax.random.split(key, 3)
            hops = int(jax.random.randint(k1, (), min_hops, max_hops + 1))
            # Random node ordering via argsort of uniform noise (Pyodide-safe)
            order = jnp.argsort(jax.random.uniform(k2, (N,)))
            order_list = [int(x) for x in order]
            next_node = list(range(N))
            for step in range(hops):
                next_node[order_list[step]] = order_list[step + 1]
            sink = order_list[hops]
            next_node[sink] = sink  # fixed point so extra loops preserve the answer
            keys_batch.append(E)
            vals_batch.append(E[jnp.array(next_node)])
            starts.append(E[order_list[0]])
            targets.append(sink)
            hops_list.append(hops)
        return (
            jnp.stack(keys_batch),
            jnp.stack(vals_batch),
            jnp.stack(starts),
            jnp.array(targets),
            jnp.array(hops_list),
        )
    
    # Train ONLY on short 1-hop and 2-hop chains
    K_tr, V_tr, S_tr, Y_tr, H_tr = make_dataset(seed=7, num_samples=60, min_hops=1, max_hops=2)
    # Evaluate on 1-hop through 5-hop chains (including unseen deeper hops)
    K_te, V_te, S_te, Y_te, H_te = make_dataset(seed=99, num_samples=150, min_hops=1, max_hops=5)
    
    def unit_norm(x, eps=1e-6):
        return x / (jnp.linalg.norm(x, axis=-1, keepdims=True) + eps)
    
    def unpack(theta):
        # Shared recurrent core weights (only 2*N^2 + 2 = 74 parameters)
        W_q = theta[:N * N].reshape(N, N)
        W_v = theta[N * N:2 * N * N].reshape(N, N)
        log_temp = theta[2 * N * N]
        gate_logit = theta[2 * N * N + 1]
        return W_q, W_v, log_temp, gate_logit
    
    def looped_transformer(theta, K_in, V_in, start_vec, n_loops):
        """Prelude -> Shared Recurrent Core (R loops with input injection) -> Coda."""
        W_q, W_v, log_temp, gate_logit = unpack(theta)
        temp = jnp.exp(jnp.clip(log_temp, -2.0, 3.0))
        gate = jax.nn.sigmoid(gate_logit)
    
        # Prelude: embed query start node into initial latent state h^(0)
        h = unit_norm(start_vec)
        drifts = []
    
        # Shared recurrent core: iterate R times with static input injection (K_in, V_in)
        for _ in range(n_loops):
            q = h @ W_q
            scores = jnp.einsum("bi,bji->bj", q, K_in) * temp
            attn = jax.nn.softmax(scores, axis=-1)
            retrieved = jnp.einsum("bj,bji->bi", attn, V_in) @ W_v
            h_next = unit_norm((1.0 - gate) * h + gate * retrieved)
            drifts.append(jnp.linalg.norm(h_next - h, axis=-1))
            h = h_next
    
        # Coda: map refined latent state to destination logits
        logits = h * 8.0
        return logits, jnp.stack(drifts, axis=1)
    
    def loss_fn(theta):
        # Train with fixed shallow depth R=2 on 1- and 2-hop chains
        logits, _ = looped_transformer(theta, K_tr, V_tr, S_tr, n_loops=2)
        log_probs = jax.nn.log_softmax(logits, axis=-1)
        idx = jnp.arange(len(Y_tr))
        return -jnp.mean(log_probs[idx, Y_tr])
    
    key = jax.random.PRNGKey(42)
    theta = jax.random.normal(key, (2 * N * N + 2,)) * 0.15
    grad_fn = jax.jit(jax.grad(loss_fn))
    
    lr = 1.4
    for step in range(60):
        theta = theta - lr * grad_fn(theta)
        if (step + 1) % 20 == 0:
            print(f"Step {step + 1:2d} | train loss = {loss_fn(theta):.4f}")
    
    # Test-time compute scaling: increase loop depth R with ZERO extra parameters
    loop_counts = [1, 2, 3, 4, 5, 6]
    accuracies = []
    print(f"\nTest-time compute scaling ({len(theta)} shared parameters, trained only up to 2 hops):")
    for R in loop_counts:
        logits, _ = looped_transformer(theta, K_te, V_te, S_te, n_loops=R)
        acc = float(jnp.mean(jnp.argmax(logits, axis=-1) == Y_te)) * 100.0
        accuracies.append(acc)
        print(f"  Loops R={R} | 1-to-5 hop accuracy = {acc:5.1f}%")
    
    # Adaptive early-exit halting: stop once latent drift ||h^(k) - h^(k-1)|| < 0.15
    _, drifts_6 = looped_transformer(theta, K_te, V_te, S_te, n_loops=6)
    hop_depths = [1, 2, 3, 4, 5]
    mean_exits = []
    print("\nAdaptive early-exit loop depth by problem difficulty:")
    for h_len in hop_depths:
        d_sub = drifts_6[H_te == h_len]
        exit_steps = []
        for row in d_sub:
            below = jnp.where(row < 0.15)[0]
            exit_steps.append(int(below[0]) + 1 if len(below) > 0 else 6)
        avg_exit = float(jnp.mean(jnp.array(exit_steps)))
        mean_exits.append(avg_exit)
        print(f"  {h_len}-hop chains | mean halting loop = {avg_exit:.2f}")
    
    # Visualise test-time compute scaling and adaptive halting
    fig, axes = plt.subplots(1, 2, figsize=(11, 4))
    axes[0].plot(loop_counts, accuracies, marker="o", linewidth=2.2, color="#9b59b6")
    axes[0].axvline(2, color="#e74c3c", linestyle="--", alpha=0.7, label="Max train depth (R=2)")
    axes[0].set_title("Test-Time Compute Scaling (Fixed Weights)")
    axes[0].set_xlabel("Recurrent Loop Count R")
    axes[0].set_ylabel("Accuracy on 1-to-5 Hop Chains (%)")
    axes[0].set_ylim(0, 108)
    axes[0].grid(alpha=0.3)
    axes[0].legend()
    
    axes[1].bar(hop_depths, mean_exits, color="#3498db", alpha=0.85)
    axes[1].set_title("Adaptive Early-Exit Depth vs Difficulty")
    axes[1].set_xlabel("True Chain Hop Depth")
    axes[1].set_ylabel("Mean Halting Loop")
    axes[1].set_ylim(0, 6.5)
    axes[1].grid(axis="y", alpha=0.3)
    plt.tight_layout()
    plt.show()