15. Beyond the decoder: encoders, state-space models, and text diffusion

Why this layer exists

Chapters 10 to 14 built one design: a decoder-only transformer, whose positions read only themselves and earlier positions, which keeps every earlier position’s keys and values in a cache that grows by one position per token, and which commits one token per forward pass. Each of those three properties can be changed independently, and each change gives a family of models the reader meets in model cards and in llama.cpp.

  • What a position may read. Remove the causal mask and every position reads every other: an encoder. Its states describe a whole text at once, which is what embedding models and rerankers need. llama-server serves them with --embedding and --pooling {none,mean,cls,last,rank}, and --rerank for rerankers; llama.cpp’s list of architectures names a BERT family (bert, modern-bert, nomic-bert, nomic-bert-moe, neo-bert, jina-bert-v2, jina-bert-v3, eurobert). Chapter 21 puts a scoring head on this chapter’s encoder, and chapter 32 searches over embeddings.
  • What a model keeps between tokens. Replace attention with a linear recurrence and each layer keeps a fixed-size state instead of a cache that grows with the context: a state-space model (SSM). llama.cpp’s llm_arch_is_recurrent lists mamba, mamba2, rwkv6, rwkv6qwen2, rwkv7 and arwkv7, whose layers are all recurrent, and llm_arch_is_hybrid lists seventeen architectures in which “each layer may be either attention-based or recurrent”, among them jamba, falcon-h1, granitehybrid, nemotron_h, qwen3next, qwen35, qwen35moe and lfm2. The reader’s ornith-1.5-35b-a3b is a qwen35moe: its config.json lists 30 of its 40 layers as linear_attention and every fourth as full_attention, and llama.cpp’s graph for it (src/models/qwen35moe.cpp) builds the linear-attention layers as a gated delta net, Gated DeltaNet, a linear recurrence with a fixed-size state. The reader’s main model is this chapter’s hybrid case.
  • How many tokens a pass commits. Start from a sequence of mask tokens and fill in several positions per pass, reading the whole sequence each time: text diffusion. llm_arch_is_diffusion lists dream, llada, llada-moe and rnd1, which llama.cpp runs with a separate program, llama-diffusion-cli, not with llama-server.

(The lists are llama.cpp’s src/llama-arch.cpp at commit da89bb3, 2026-09-29, the commit chapter 14 describes.)

The chapter builds one small model of each family on the same corpus as chapter 11: tinygpt.encoder, tinygpt.ssm and tinygpt.diffusion. The three share chapter 11’s block and differ in exactly the property above, so the lab can train all three beside chapter 11’s decoder and compare what each loss means and what each costs to generate.

What each position reads, and how each family generates Four panels. Decoder, top left: a five by five grid whose rows are positions and whose filled cells are the positions each row reads, filled on and below the diagonal; one new token per pass, earlier states never change, so the KV cache keeps them, 2 times L times d numbers per token for L layers of width d. Encoder, top right: the same grid completely filled, every position reads every position; one new token changes every state, so nothing can be kept and each new token recomputes every position. State-space model, bottom left: a chain of five state boxes, each with an arrow to the next; each position reads only the state left by the one before; one new token per pass, and the state of D times N numbers per layer is all it keeps, whatever the length. Masked diffusion, bottom right: a row of six masked cells, then three passes that reveal the letters of the word SAILOR, two or so per pass, and letters once revealed never change; every position reads every position, and each of the S passes runs over every position. Decoder Encoder State-space model Masked diffusion row: a position filled: what it reads row: a position filled: what it reads reads itself and earlier one new token per pass earlier states never change, so the KV cache keeps them: 2·L·d numbers per token reads every position one new token changes every state, so nothing is kept: each new token recomputes every position each position reads only the state the one before left one new token per pass; the state is all it keeps: D·N numbers per layer, whatever the length start pass 1 pass 2 pass 3 AL SALO SAILOR every position reads every position; S passes, each over every position; a revealed token never changes

Mechanism

Encoders: attention without the mask

Chapter 10’s attention scores query ii against key jj and adds the causal mask, −∞-\infty where j>ij > i. Drop the mask. For one head with Q\mathbf{Q}, K\mathbf{K}, V\mathbf{V} of shape (T, d_h),

sij=qi⋅kjdh,wij=esij∑j′=0T−1esij′,yi=∑j=0T−1wijvj, s_{ij} = \frac{\mathbf{q}_i \cdot \mathbf{k}_j}{\sqrt{d_h}} , \qquad w_{ij} = \frac{e^{s_{ij}}}{\sum_{j'=0}^{T-1} e^{s_{ij'}}} , \qquad \mathbf{y}_i = \sum_{j=0}^{T-1} w_{ij} \mathbf{v}_j ,

with the scores and weights of shape (T, T) and Y\mathbf{Y} of shape (T, d_h). The sums now run over all TT positions. That is the only change: the block, the residual stream, the layer norms and the feed-forward sublayer are chapter 11’s. In tinygpt the switch is a constructor keyword, MultiHeadAttention(cfg, rng, causal=True), which Encoder turns off in each of chapter 11’s blocks after building them, as chapter 16’s vision encoder does.

Without the mask, order comes only from the positions. Chapter 10 showed that unmasked attention is permutation-equivariant: for a (T, T) permutation matrix P\mathbf{P}, the input PX\mathbf{P}\mathbf{X} gives the output PY\mathbf{P}\mathbf{Y}. The rest of a block acts on each row alone. Layer norm normalises a row by its own mean and variance, and the feed-forward sublayer multiplies every row by the same matrices, so each maps PX\mathbf{P}\mathbf{X} to P\mathbf{P} times its output on X\mathbf{X}; the residual sum keeps the property, PX+Pf(X)=P(X+f(X))\mathbf{P}\mathbf{X} + \mathbf{P}f(\mathbf{X}) = \mathbf{P}\big(\mathbf{X} + f(\mathbf{X})\big). Equivariant maps compose, g(f(PX))=g(Pf(X))=Pg(f(X))g(f(\mathbf{P}\mathbf{X})) = g(\mathbf{P}f(\mathbf{X})) = \mathbf{P}g(f(\mathbf{X})), so a whole stack of unmasked blocks is equivariant, and so is the head, which acts row by row: without a position encoding, shuffle an encoder’s input tokens and every prediction moves with its token, unchanged. Chapter 10 also showed that the causal mask breaks this partly, so that a causal position knows which tokens precede it and roughly how many. An encoder has no such signal, and the only thing that can tell it where a token is, is its position encoding. With RoPE the rotation puts relative position into every layer’s scores. With a learned table, position enters once, as a row added to each token’s embedding, and chapter 11 draws that table from N(0,0.022)\mathcal{N}(0, 0.02^2) as it draws the token table: at initialisation each position is a vector of norm about 0.02d=0.160.02\sqrt{d} = 0.16 (at d=64d = 64) beside a token vector of the same size, and the blocks must learn to read it. Until they do, the encoder is a function of the bag of tokens in its window. The lab tests whether that is why a learned-position encoder can stall.

Why an encoder cannot generate cheaply. Chapter 12 proved by induction that under a causal mask position jj’s state depends only on x0,…,xjx_0, \ldots, x_j, so appending a token leaves every earlier state, and every cached key and value, unchanged. Without the mask the induction gives the opposite: after one layer, position jj’s state is a weighted sum over the values of all positions, so it depends on every token, and appending xTx_T adds a term to every softmax row, changing every denominator and every state from the first layer up. Nothing computed for the shorter sequence can be reused. To extend a text of PP tokens by nn tokens with an encoder, append a [MASK], run the whole sequence, sample the masked position, and repeat: pass k=0,…,n−1k = 0, \ldots, n-1 processes P+k+1P + k + 1 positions, in all

∑k=0n−1(P+k+1)=nP+n(n+1)2 \sum_{k=0}^{n-1} (P + k + 1) = nP + \frac{n(n+1)}{2}

positions against the cached decoder’s P+n−1P + n - 1, and each pass computes a full (P+k+1)2(P + k + 1)^2 score matrix where the cached decoder computes one row. The model is also asked a question it rarely trained on: a masked position with nothing to its right, which in training happens only at the end of a window.

The masked-token objective

A causal model trains on “predict xt+1x_{t+1} from x0,…,xtx_0, \ldots, x_t” at every position. That is impossible without the mask: each position would read its own answer. BERT’s objective hides the answers instead. Choose each text position with probability 0.15; replace a chosen token by [MASK] 80% of the time, by a uniformly random token 10% of the time, and leave it unchanged 10% of the time; then minimise the cross-entropy of the model’s prediction of the original token at the chosen positions, and only there. For a corrupted input x~\tilde{\mathbf{x}} and chosen set MM,

LMLM=−1∣M∣∑i∈Mlogpθ(xi∣x~), \mathcal{L}_{\text{MLM}} = -\frac{1}{|M|} \sum_{i \in M} \log p_\theta\big(x_i \mid \tilde{\mathbf{x}}\big) ,

with pθ(⋅∣x~)p_\theta(\cdot \mid \tilde{\mathbf{x}}) at position ii the softmax of the head’s logits there, shape (V,).

What the loss measures. Suppose one position at a time is masked and the rest are shown. The loss at ii is then −logpθ(xi∣x−i)-\log p_\theta(x_i \mid \mathbf{x}_{-i}), where x−i\mathbf{x}_{-i} is every token but xix_i, and summed over positions this is the negative pseudo-log-likelihood,

PLL(x)=∑ilogp(xi∣x−i), \mathrm{PLL}(\mathbf{x}) = \sum_{i} \log p(x_i \mid \mathbf{x}_{-i}) ,

which Besag defined for spatial data in 1975. It is not the log-likelihood. Take two tokens. By the definition of conditional probability, p(x1∣x2)=p(x1,x2)/p(x2)p(x_1 \mid x_2) = p(x_1, x_2)/p(x_2) and p(x2∣x1)=p(x1,x2)/p(x1)p(x_2 \mid x_1) = p(x_1, x_2)/p(x_1), so

PLL=logp(x1,x2)p(x2)+logp(x1,x2)p(x1)=logp(x1,x2)+logp(x1,x2)p(x1)p(x2). \mathrm{PLL} = \log \frac{p(x_1, x_2)}{p(x_2)} + \log \frac{p(x_1, x_2)}{p(x_1)} = \log p(x_1, x_2) + \log \frac{p(x_1, x_2)}{p(x_1)\, p(x_2)} .

The first term is the log-likelihood; the second is the pointwise mutual information of the two tokens, positive when they occur together more often than independence would give. Averaged over the data, the second term is the mutual information I(X1;X2)≥0I(X_1; X_2) \ge 0, so the expected pseudo-NLL is H(X1,X2)−I(X1;X2)H(X_1, X_2) - I(X_1; X_2), below the entropy by exactly the information the tokens share. For nn tokens the same comparison uses chapter 4’s chain rule: the entropy is H(X)=∑iH(Xi∣X<i)H(\mathbf{X}) = \sum_i H(X_i \mid \mathbf{X}_{<i}), and the expected pseudo-NLL is ∑iH(Xi∣X−i)\sum_i H(X_i \mid \mathbf{X}_{-i}). Each term of the second sum conditions on a superset of what the matching term of the first conditions on, and the difference of the two is a conditional mutual information, an expected KL divergence, so it is non-negative. The expected pseudo-NLL is at most the entropy. A masked-token loss can therefore read below the best per-token NLL any causal model can reach on the same text, by an amount set by how much the tokens predict each other, and it cannot be compared with one. With 15% masked instead of one position, the other masked positions are hidden too; the loss sits between the two cases, still not a likelihood.

Why 80/10/10. The fractions of all text positions are

0.15×0.8=0.12 shown as [MASK],0.15×0.1=0.015 random,0.015 unchanged targets,0.85 untouched. 0.15 \times 0.8 = 0.12 \text{ shown as } \text{[MASK]} , \qquad 0.15 \times 0.1 = 0.015 \text{ random} , \qquad 0.015 \text{ unchanged targets} , \qquad 0.85 \text{ untouched} .

With [MASK] only, every target would be at a [MASK]: the model would learn to predict only there, and the states of real tokens would have no reason to carry what the token is, although fine-tuning and embedding never show a [MASK] at all. BERT’s authors name this mismatch between pre-training and fine-tuning as the reason for the rule. Under 80/10/10 a visible token (88% of positions) is a target 0.03/0.88=3.4%0.03/0.88 = 3.4\% of the time and, with a 512-token vocabulary, wrong 0.015×(511/512)/0.88=1.7%0.015 \times (511/512)/0.88 = 1.7\% of the time: the model is scored on real tokens too, cannot trust any of them completely, and must keep a representation of each position’s own token as well as its context.

Pooling to one vector

An encoder returns (B, T, d) hidden states; an embedding is one (B, d) vector per text. Mean pooling averages over positions, e=1T∑tht\mathbf{e} = \frac{1}{T}\sum_t \mathbf{h}_t. CLS pooling prepends a special token and takes its final state, e=h0\mathbf{e} = \mathbf{h}_0: since every position reads every other, position 0 can summarise the text, and the training objective decides whether it does. (A decoder’s last pooling is the causal counterpart: only the last position has read the whole text. Chapter 21’s “Pooling a decoder into one vector” proves it, and shows what cls pooling does to a decoder.) Embeddings are compared by chapter 2’s cosine similarity; llama-server’s /v1/embeddings returns them normalised to unit length, so their dot product is the cosine.

The masked-token objective does not train pooled vectors to be compared this way. Sentence-BERT’s authors report that BERT “out-of-the-box maps sentences to a vector space that is rather unsuitable to be used with common similarity measures like cosine-similarity”, and fine-tune mean-pooled BERT on sentence pairs to fix it; embedding models are trained that way. A reranker is the other use: the query and a document go in as one sequence, every token of each reads every token of the other, and a head on the pooled state gives a relevance score (llama-server’s --pooling rank with --rerank). It is more precise than comparing two separately computed embeddings and costs a forward pass per query-document pair.

State-space models: a linear system in continuous time

Take one channel of the residual stream, a scalar signal x(τ)x(\tau) in continuous time τ\tau, and drive a state h(τ)\mathbf{h}(\tau) of shape (N,) with it:

h′(τ)=Ah(τ)+bx(τ),y(τ)=c⋅h(τ), \mathbf{h}'(\tau) = \mathbf{A}\,\mathbf{h}(\tau) + \mathbf{b}\, x(\tau) , \qquad y(\tau) = \mathbf{c} \cdot \mathbf{h}(\tau) ,

with A\mathbf{A} (N, N) and b\mathbf{b}, c\mathbf{c} (N,). This is a linear time-invariant system, the object S4 and Mamba start from. Make A=diag(a1,…,aN)\mathbf{A} = \mathrm{diag}(a_1, \ldots, a_N) diagonal and the NN coordinates decouple into scalar equations hn′=anhn+bnxh_n' = a_n h_n + b_n x. Drop the index nn and solve one. Multiply by e−aτe^{-a\tau}: the left side becomes a derivative,

ddτ(e−aτh(τ))=e−aτ(h′(τ)−ah(τ))=e−aτbx(τ). \frac{d}{d\tau}\Big(e^{-a\tau} h(\tau)\Big) = e^{-a\tau}\big(h'(\tau) - a h(\tau)\big) = e^{-a\tau}\, b\, x(\tau) .

Integrate from τ0\tau_0 to τ0+Δ\tau_0 + \Delta and multiply by ea(τ0+Δ)e^{a(\tau_0 + \Delta)}:

h(τ0+Δ)=eaΔh(τ0)+∫τ0τ0+Δea(τ0+Δ−σ)bx(σ)dσ. h(\tau_0 + \Delta) = e^{a\Delta} h(\tau_0) + \int_{\tau_0}^{\tau_0 + \Delta} e^{a(\tau_0 + \Delta - \sigma)}\, b\, x(\sigma)\, d\sigma .

Tokens arrive at discrete steps, so hold the input constant over each interval of length Δ\Delta, x(σ)=xtx(\sigma) = x_t: the zero-order hold. Substituting ρ=τ0+Δ−σ\rho = \tau_0 + \Delta - \sigma, which runs from Δ\Delta down to 0,

∫τ0τ0+Δea(τ0+Δ−σ)dσ=∫0Δeaρdρ=eaΔ−1a, \int_{\tau_0}^{\tau_0 + \Delta} e^{a(\tau_0 + \Delta - \sigma)}\, d\sigma = \int_0^{\Delta} e^{a\rho}\, d\rho = \frac{e^{a\Delta} - 1}{a} ,

and the step from one token to the next is

ht=a¯ht−1+b¯xt,a¯=eΔa,b¯=eΔa−1ab=(Δa)−1(eΔa−1)Δb, h_t = \bar{a}\, h_{t-1} + \bar{b}\, x_t , \qquad \bar{a} = e^{\Delta a} , \qquad \bar{b} = \frac{e^{\Delta a} - 1}{a}\, b = (\Delta a)^{-1}\big(e^{\Delta a} - 1\big)\, \Delta b ,

the last form being Mamba’s equation (4) for a diagonal A\mathbf{A}, where the inverse is elementwise. With a<0a < 0, 0<a¯<10 < \bar{a} < 1 and the state decays: aa sets how fast, in units of Δ\Delta. For small Δa\Delta a, eΔa≈1+Δae^{\Delta a} \approx 1 + \Delta a and b¯≈Δb\bar{b} \approx \Delta b, the Euler step; the ratio of the exact b¯\bar{b} to Euler’s is (ex−1)/x(e^{x} - 1)/x with x=Δax = \Delta a. Mamba’s reference implementation, selective_scan_ref in mamba_ssm/ops/selective_scan_interface.py, uses exactly this pair: eΔae^{\Delta a} for a¯\bar{a} and Δb\Delta b for b¯\bar{b}. At its initial step sizes, Δ∈[0.001,0.1]\Delta \in [0.001, 0.1], and its rates an=−1,…,−16a_n = -1, \ldots, -16 (below), the ratio runs from 0.9995 (Δ=0.001\Delta = 0.001, a=−1a = -1) to 0.4988 (Δ=0.1\Delta = 0.1, a=−16a = -16), where Euler’s input gain is twice the exact one; exercise (c) shows what that does to the state’s steady value. discretize uses the exact formula.

A layer has DD channels, one system each, so the state is (D, N), and each channel’s output is yt=c⋅hty_t = \mathbf{c} \cdot \mathbf{h}_t with its own ht\mathbf{h}_t.

Recurrence and convolution are the same map

With a¯\bar{a}, b¯\bar{b} and c\mathbf{c} fixed, unroll the recurrence from h−1=0\mathbf{h}_{-1} = \mathbf{0}. Claim: ht=∑k=0ta¯k⊙b¯xt−k\mathbf{h}_t = \sum_{k=0}^{t} \bar{\mathbf{a}}^{k} \odot \bar{\mathbf{b}}\, x_{t-k}, powers and products elementwise over the NN coordinates. For t=0t = 0, h0=a¯⊙0+b¯x0\mathbf{h}_0 = \bar{\mathbf{a}} \odot \mathbf{0} + \bar{\mathbf{b}} x_0, the single term k=0k = 0. If it holds for t−1t - 1,

ht=a¯⊙∑k=0t−1a¯k⊙b¯xt−1−k+b¯xt=∑k′=1ta¯k′⊙b¯xt−k′+a¯0⊙b¯xt, \mathbf{h}_t = \bar{\mathbf{a}} \odot \sum_{k=0}^{t-1} \bar{\mathbf{a}}^{k} \odot \bar{\mathbf{b}}\, x_{t-1-k} + \bar{\mathbf{b}}\, x_t = \sum_{k'=1}^{t} \bar{\mathbf{a}}^{k'} \odot \bar{\mathbf{b}}\, x_{t-k'} + \bar{\mathbf{a}}^{0} \odot \bar{\mathbf{b}}\, x_t ,

substituting k′=k+1k' = k + 1, which is the claim for tt. Take the dot product with c\mathbf{c}:

yt=∑k=0tKkxt−k,Kk=∑n=1Ncna¯nkb¯n. y_t = \sum_{k=0}^{t} K_k\, x_{t-k} , \qquad K_k = \sum_{n=1}^{N} c_n\, \bar{a}_n^{\,k}\, \bar{b}_n .

The output is a causal convolution of the input with the kernel K\mathbf{K}, one kernel per channel, shape (T, D) for TT positions. The two forms compute the same numbers and suit different jobs. Training sees the whole sequence, and the convolution is parallel over tt (S4 computes it with FFTs in O(TlogT)O(T \log T)). Generation sees one token at a time, and the recurrence costs O(N)O(N) per token per channel however long the text is, with the state as the only memory. test_recurrence_equals_convolution_when_time_invariant checks ssm_kernel and causal_conv against the scan to 10−1210^{-12}.

Selectivity

A time-invariant system treats every token alike: the kernel KkK_k depends on the distance kk, never on what the tokens are, so it cannot decide to remember one token and ignore the next. Mamba makes three of the parameters functions of the current input xt\mathbf{x}_t, the (D,) vector of all channels at step tt:

Δt=softplus(WΔxt+bΔ),bt=WBxt,ct=WCxt, \Delta_t = \mathrm{softplus}(\mathbf{W}_\Delta \mathbf{x}_t + \mathbf{b}_\Delta) , \qquad \mathbf{b}_t = \mathbf{W}_B \mathbf{x}_t , \qquad \mathbf{c}_t = \mathbf{W}_C \mathbf{x}_t ,

with Δt\Delta_t of shape (D,), one step per channel and positive because softplus(z)=log(1+ez)>0\mathrm{softplus}(z) = \log(1 + e^z) > 0, and bt\mathbf{b}_t, ct\mathbf{c}_t of shape (N,), shared by the channels. (Mamba computes Δt\Delta_t through a low-rank projection; SelectiveSSM uses a full (D, D) one.) Discretising with each channel’s own step gives a¯t\bar{\mathbf{a}}_t and b¯t\bar{\mathbf{b}}_t of shape (D, N) that change from token to token, and the recurrence per channel becomes ht=a¯t⊙ht−1+b¯txt\mathbf{h}_t = \bar{\mathbf{a}}_t \odot \mathbf{h}_{t-1} + \bar{\mathbf{b}}_t\, x_t. Unrolling it by the same induction,

ht=∑s=0t(∏r=s+1ta¯r)⊙b¯sxs,yt=∑s=0t[ct⋅(∏r=s+1ta¯r)⊙b¯s]xs. \mathbf{h}_t = \sum_{s=0}^{t} \Big(\prod_{r=s+1}^{t} \bar{\mathbf{a}}_r\Big) \odot \bar{\mathbf{b}}_s\, x_s , \qquad y_t = \sum_{s=0}^{t} \Big[\mathbf{c}_t \cdot \Big(\prod_{r=s+1}^{t} \bar{\mathbf{a}}_r\Big) \odot \bar{\mathbf{b}}_s\Big] x_s .

The bracket plays the role of Kt−sK_{t-s}, but it depends on tt and ss separately and, through Δ\Delta, b\mathbf{b} and c\mathbf{c}, on the inputs themselves. There is no fixed kernel, and no FFT. The map from inputs to outputs is not even linear any more: doubling x\mathbf{x} changes the steps, which test_selective_ssm_is_causal_and_input_dependent checks.

What selectivity buys shows most simply with one state number, a=−1a = -1 and b=1b = 1, the case of Mamba’s Theorem 1. Then a¯t=e−Δt\bar{a}_t = e^{-\Delta_t} and b¯t=(e−Δt−1)/(−1)=1−e−Δt\bar{b}_t = (e^{-\Delta_t} - 1)/(-1) = 1 - e^{-\Delta_t}. With Δt=softplus(zt)=log(1+ezt)\Delta_t = \mathrm{softplus}(z_t) = \log(1 + e^{z_t}), e−Δt=1/(1+ezt)e^{-\Delta_t} = 1/(1 + e^{z_t}), so

b¯t=1−11+ezt=ezt1+ezt=σ(zt),a¯t=1−σ(zt),ht=(1−σ(zt))ht−1+σ(zt)xt: \bar{b}_t = 1 - \frac{1}{1 + e^{z_t}} = \frac{e^{z_t}}{1 + e^{z_t}} = \sigma(z_t) , \qquad \bar{a}_t = 1 - \sigma(z_t) , \qquad h_t = \big(1 - \sigma(z_t)\big)\, h_{t-1} + \sigma(z_t)\, x_t :

a gated recurrence whose gate is the sigmoid of a linear function of the input. A large ztz_t overwrites the state with the current token; a very negative one leaves it untouched and ignores the token. The discretisation step is the gate.

The scan is still linear-time. The recurrence is linear in h\mathbf{h}, so each step is an affine map h↦a¯t⊙h+ut\mathbf{h} \mapsto \bar{\mathbf{a}}_t \odot \mathbf{h} + \mathbf{u}_t with ut=b¯txt\mathbf{u}_t = \bar{\mathbf{b}}_t x_t, and two steps compose into one of the same form:

(a¯2,u2)∘(a¯1,u1):h↦a¯2⊙(a¯1⊙h+u1)+u2=(a¯2⊙a¯1)⊙h+(a¯2⊙u1+u2). (\bar{\mathbf{a}}_2, \mathbf{u}_2) \circ (\bar{\mathbf{a}}_1, \mathbf{u}_1) : \mathbf{h} \mapsto \bar{\mathbf{a}}_2 \odot (\bar{\mathbf{a}}_1 \odot \mathbf{h} + \mathbf{u}_1) + \mathbf{u}_2 = (\bar{\mathbf{a}}_2 \odot \bar{\mathbf{a}}_1) \odot \mathbf{h} + (\bar{\mathbf{a}}_2 \odot \mathbf{u}_1 + \mathbf{u}_2) .

Composition of functions is associative, so the prefix compositions, which are the states, can be computed in ⌈log2T⌉\lceil \log_2 T \rceil rounds of parallel combines, the prefix-sum pattern; Mamba’s kernel is a hardware-aware version of it, and exercise (d) builds the plain one. On a CPU, scan loops over tt: TT sequential steps, each over a (B, D, N) array.

The scan’s gradient is the same recurrence run backwards. scan is one fused op, like chapter 10’s softmax, with a hand-written backward. Let Gt\mathbf{G}_t be the gradient of the loss with respect to the output ht\mathbf{h}_t as used downstream, and λt\lambda_t the full gradient; both have the shape of ht\mathbf{h}_t, (B, D, N) in SelectiveSSM. The full gradient of ht\mathbf{h}_t also counts its influence through ht+1=a¯t+1⊙ht+ut+1\mathbf{h}_{t+1} = \bar{\mathbf{a}}_{t+1} \odot \mathbf{h}_t + \mathbf{u}_{t+1}, and through that on everything later:

λt=Gt+a¯t+1⊙λt+1,λT−1=GT−1, \lambda_t = \mathbf{G}_t + \bar{\mathbf{a}}_{t+1} \odot \lambda_{t+1} , \qquad \lambda_{T-1} = \mathbf{G}_{T-1} ,

a scan from the last step to the first. Then, since ht\mathbf{h}_t depends on ut\mathbf{u}_t with derivative 1 and on a¯t\bar{\mathbf{a}}_t through the product with ht−1\mathbf{h}_{t-1},

∂L∂ut=λt,∂L∂a¯t=λt⊙ht−1(0 for t=0). \frac{\partial \mathcal{L}}{\partial \mathbf{u}_t} = \lambda_t , \qquad \frac{\partial \mathcal{L}}{\partial \bar{\mathbf{a}}_t} = \lambda_t \odot \mathbf{h}_{t-1} \quad (\text{0 for } t = 0) .

A fixed-size state against the KV cache

A decoding step of an SSM layer reads the (D, N) state, updates it and writes it back. Nothing else about the past is kept. Per sequence, an SSM of LL layers keeps L⋅D⋅NL \cdot D \cdot N numbers whatever the length; chapter 12’s KV cache keeps 2⋅L⋅S⋅d2 \cdot L \cdot S \cdot d numbers after SS positions. The lab’s models, L=2L = 2, D=d=64D = d = 64, N=16N = 16, in float64: 16,384 bytes of state against 2,048 bytes of cache per position, equal at 8 positions and 8 times smaller at the full window of 64. At real sizes the state is larger and so are the contexts; exercise (e) works it out for Mamba-2.8B, which keeps 23.75 MiB per sequence in llama.cpp, as much as 38 positions of a same-shaped transformer’s f16 cache, where a 32,768-position cache is 20 GiB.

Ornith keeps both kinds of memory. In each of its 30 Gated DeltaNet layers, each of 32 value heads keeps a 128×128128 \times 128 matrix as its state, where this chapter’s layer keeps a (D, N) array, and updates it every token by the gated delta rule of Yang, Kautz and Hatamizadeh. By llama.cpp’s sizes at da89bb3 (n_embd_s and n_embd_r in src/llama-hparams.cpp, read with src/models/qwen35moe.cpp’s mapping of the config), that is 32×128×128=524,28832 \times 128 \times 128 = 524{,}288 f32 numbers, 2 MiB, per layer, and a convolution state holding the last 3 inputs of its 8,192 query, key and value channels, 3×8,192=24,5763 \times 8{,}192 = 24{,}576 numbers, 96 KiB: about 62.8 MiB per sequence over the 30 layers, whatever the length. Its 10 full-attention layers keep a KV cache with 2 key-value heads of width 256, 20,480 f16 bytes per position: 640 MiB (0.67 GB) at 32,768 positions, where the same heads in all 40 layers would need 2.5 GiB (2.68 GB). The state costs as much as 3,216 positions of that cache, and each position adds a quarter of what it would add to an all-attention model with the same heads. Chapter 14 turns these figures into bytes per decoding step. (The figures are approximate: they take the GGUF’s sizes to be the config’s, and they leave out the multi-token-prediction layer.)

This is what chapter 14’s bandwidth argument and chapter 19’s slots care about. A decoding step reads the weights and each sequence’s cache; with a state instead of a cache, the per-sequence term stops growing, so a long context no longer slows each token, and a slot’s memory is known in advance and does not depend on its context length. Two costs come with it.

  • The past is compressed. A state of ss bits can be in at most 2s2^s configurations, so it cannot tell apart more than 2s2^s histories: an SSM cannot, in general, reproduce an earlier stretch of text longer than its state can encode, where attention can look up any cached position exactly; keeping some attention layers, as the hybrid architectures do, keeps that ability.
  • The state cannot be rewound. KVCache.truncate(n) drops positions from nn on, which chapter 14’s speculative decoding needs after a rejection and llama-server’s prompt caching needs to reuse a common prefix. A recurrent state at step tt has already mixed in every token up to tt. llama.cpp’s llama_memory_recurrent::seq_rm says why partial removal fails (“models like Mamba or RWKV can’t have a state partially erased at the end of the sequence because their state isn’t preserved for previous tokens”), and supports rollback only through snapshots of the state kept for the last few tokens (n_rs_seq), for the architectures in llm_arch_supports_rs_rollback. qwen35moe is one of them, which is what lets llama-server roll ornith back after a rejected speculative draft.

Masked diffusion: the forward process

A diffusion model defines a way of destroying data and learns to reverse it. For text the destruction is masking. Let x0\mathbf{x}_0 be a sequence of LL tokens (from here on LL is a length, not the number of layers of the previous sections) and t∈[0,1]t \in [0, 1] a time. The forward process qq masks each position independently with probability tt:

q(xt∣x0)=∏i=1Lq(xti∣x0i),q(xti=M∣x0i)=t,q(xti=x0i∣x0i)=1−t, q(\mathbf{x}_t \mid \mathbf{x}_0) = \prod_{i=1}^{L} q(x_t^i \mid x_0^i) , \qquad q(x_t^i = \mathrm{M} \mid x_0^i) = t , \qquad q(x_t^i = x_0^i \mid x_0^i) = 1 - t ,

where M\mathrm{M} is the mask token and the superscript is the position. At t=0t = 0 nothing is masked; at t=1t = 1 everything is, whatever x0\mathbf{x}_0 was. The mask is absorbing: once masked, a position stays masked as tt grows. As a process in time, for s<ts < t a masked position stays masked, and an unmasked one is masked by time tt with probability (t−s)/(1−s)(t - s)/(1 - s), which keeps the marginal right: unmasked at tt with probability (1−s)⋅(1−t)/(1−s)=1−t(1 - s) \cdot (1 - t)/(1 - s) = 1 - t. D3PM introduced this absorbing-state corruption for discrete diffusion; MDLM and LLaDA are its current form.

The model pθp_\theta runs time backwards. Its network, the denoiser, reads xt\mathbf{x}_t and returns at every position a distribution x^θ(xt)i\hat{\mathbf{x}}_\theta(\mathbf{x}_t)^i of shape (V,) over the clean token there; it is an encoder whose head predicts only text tokens, never M\mathrm{M}. This one has no input for tt: the share of masked positions already tells it roughly how much noise there is, and MDLM reports that time conditioning “has minimal impact on perplexity”.

The bound, derived

The posterior of one step. For s<ts < t, what does xsix_s^i look like given xtix_t^i and the clean x0ix_0^i? If xtix_t^i is not masked, it was not masked at ss either (masks absorb), so xsi=xti=x0ix_s^i = x_t^i = x_0^i. If xti=Mx_t^i = \mathrm{M}, Bayes’ rule with the forward probabilities gives

q(xsi=M∣xti=M,x0i)=q(xti=M∣xsi=M)q(xsi=M∣x0i)q(xti=M∣x0i)=1⋅st, q(x_s^i = \mathrm{M} \mid x_t^i = \mathrm{M}, x_0^i) = \frac{q(x_t^i = \mathrm{M} \mid x_s^i = \mathrm{M})\, q(x_s^i = \mathrm{M} \mid x_0^i)}{q(x_t^i = \mathrm{M} \mid x_0^i)} = \frac{1 \cdot s}{t} ,

q(xsi=x0i∣xti=M,x0i)=t−s1−s⋅1−st=t−st. q(x_s^i = x_0^i \mid x_t^i = \mathrm{M}, x_0^i) = \frac{t - s}{1 - s} \cdot \frac{1 - s}{t} = \frac{t - s}{t} .

Going back from tt to ss, a masked position is revealed with probability (t−s)/t(t - s)/t, and if revealed it is the clean token. The model’s reverse step copies this with its prediction in place of the unknown x0ix_0^i: unmasked positions are copied, and a masked position stays masked with probability s/ts/t or becomes token vv with probability t−stx^θ(xt)i(v)\frac{t - s}{t}\, \hat{\mathbf{x}}_\theta(\mathbf{x}_t)^i(v), independently across positions.

The ELBO. Fix times 0=t0<t1<⋯<tN=10 = t_0 < t_1 < \cdots < t_N = 1 and write the latent path z=(xt1,…,xtN)\mathbf{z} = (\mathbf{x}_{t_1}, \ldots, \mathbf{x}_{t_N}). The model generates x1\mathbf{x}_1 (all masks, with probability 1) and then steps back: pθ(x0,z)=p(x1)∏k=1Npθ(xtk−1∣xtk)p_\theta(\mathbf{x}_0, \mathbf{z}) = p(\mathbf{x}_1) \prod_{k=1}^{N} p_\theta(\mathbf{x}_{t_{k-1}} \mid \mathbf{x}_{t_k}). Its probability of x0\mathbf{x}_0 sums over paths, and multiplying and dividing by the forward path probability q(z∣x0)q(\mathbf{z} \mid \mathbf{x}_0) turns the sum into an expectation:

pθ(x0)=∑zpθ(x0,z)=Eq(z∣x0)[pθ(x0,z)q(z∣x0)]. p_\theta(\mathbf{x}_0) = \sum_{\mathbf{z}} p_\theta(\mathbf{x}_0, \mathbf{z}) = \mathbb{E}_{q(\mathbf{z} \mid \mathbf{x}_0)}\!\left[\frac{p_\theta(\mathbf{x}_0, \mathbf{z})}{q(\mathbf{z} \mid \mathbf{x}_0)}\right] .

log\log is concave, so by Jensen’s inequality logE[Y]≥E[logY]\log \mathbb{E}[Y] \ge \mathbb{E}[\log Y], and

−logpθ(x0)≤Eq[logq(z∣x0)pθ(x0,z)]. -\log p_\theta(\mathbf{x}_0) \le \mathbb{E}_{q}\!\left[\log \frac{q(\mathbf{z} \mid \mathbf{x}_0)}{p_\theta(\mathbf{x}_0, \mathbf{z})}\right] .

To compare the two path probabilities factor by factor, rewrite qq’s. The forward process is a Markov chain, q(z∣x0)=∏k=1Nq(xtk∣xtk−1)q(\mathbf{z} \mid \mathbf{x}_0) = \prod_{k=1}^{N} q(\mathbf{x}_{t_k} \mid \mathbf{x}_{t_{k-1}}). For k≥2k \ge 2, the Markov property lets each factor also condition on x0\mathbf{x}_0, and Bayes’ rule turns it around:

q(xtk∣xtk−1,x0)=q(xtk−1∣xtk,x0)q(xtk∣x0)q(xtk−1∣x0). q(\mathbf{x}_{t_k} \mid \mathbf{x}_{t_{k-1}}, \mathbf{x}_0) = \frac{q(\mathbf{x}_{t_{k-1}} \mid \mathbf{x}_{t_k}, \mathbf{x}_0)\, q(\mathbf{x}_{t_k} \mid \mathbf{x}_0)}{q(\mathbf{x}_{t_{k-1}} \mid \mathbf{x}_0)} .

In the product over k=2,…,Nk = 2, \ldots, N the ratios of marginals telescope to q(xtN∣x0)/q(xt1∣x0)q(\mathbf{x}_{t_N} \mid \mathbf{x}_0)/q(\mathbf{x}_{t_1} \mid \mathbf{x}_0), and the k=1k = 1 factor is q(xt1∣x0)q(\mathbf{x}_{t_1} \mid \mathbf{x}_0), which cancels the denominator:

q(z∣x0)=q(x1∣x0)∏k=2Nq(xtk−1∣xtk,x0). q(\mathbf{z} \mid \mathbf{x}_0) = q(\mathbf{x}_1 \mid \mathbf{x}_0) \prod_{k=2}^{N} q(\mathbf{x}_{t_{k-1}} \mid \mathbf{x}_{t_k}, \mathbf{x}_0) .

Pair each factor with the model’s and the bound splits into three kinds of term:

−logpθ(x0)≤Eq[logq(x1∣x0)p(x1)]+∑k=2NEq[logq(xtk−1∣xtk,x0)pθ(xtk−1∣xtk)]−Eq[logpθ(x0∣xt1)]. -\log p_\theta(\mathbf{x}_0) \le \mathbb{E}_q\!\left[\log \frac{q(\mathbf{x}_1 \mid \mathbf{x}_0)}{p(\mathbf{x}_1)}\right] + \sum_{k=2}^{N} \mathbb{E}_q\!\left[\log \frac{q(\mathbf{x}_{t_{k-1}} \mid \mathbf{x}_{t_k}, \mathbf{x}_0)}{p_\theta(\mathbf{x}_{t_{k-1}} \mid \mathbf{x}_{t_k})}\right] - \mathbb{E}_q\big[\log p_\theta(\mathbf{x}_0 \mid \mathbf{x}_{t_1})\big] .

The first is 0: both sides put probability 1 on the all-mask sequence. In the kk-th term the expectation over the rest of the path reduces to one over xtk∼q(⋅∣x0)\mathbf{x}_{t_k} \sim q(\cdot \mid \mathbf{x}_0) and then xtk−1\mathbf{x}_{t_{k-1}} from the posterior, so it is the expected KL divergence between the posterior step and the model’s step. Both factor over positions, so the KL is a sum over positions. At an unmasked position both copy the same token: 0. At a masked position both put probability s/ts/t on staying masked, and the posterior puts (t−s)/t(t - s)/t on x0ix_0^i where the model puts t−stx^θ(xt)i(x0i)\frac{t - s}{t}\hat{\mathbf{x}}_\theta(\mathbf{x}_t)^i(x_0^i) (the other outcomes have posterior probability 0 and contribute nothing), so with s=tk−1s = t_{k-1}, t=tkt = t_k,

KL=stlogs/ts/t+t−stlog(t−s)/tt−stx^θ(xt)i(x0i)=−t−stlogx^θ(xt)i(x0i). \mathrm{KL} = \frac{s}{t} \log \frac{s/t}{s/t} + \frac{t - s}{t} \log \frac{(t - s)/t}{\frac{t - s}{t}\, \hat{\mathbf{x}}_\theta(\mathbf{x}_t)^i(x_0^i)} = -\frac{t - s}{t} \log \hat{\mathbf{x}}_\theta(\mathbf{x}_t)^i(x_0^i) .

The last term is the same formula at s=t0=0s = t_0 = 0: the model’s final step reveals every remaining mask, and −logpθ(x0∣xt1)-\log p_\theta(\mathbf{x}_0 \mid \mathbf{x}_{t_1}) is the sum over masked positions of −logx^θ(xt1)i(x0i)-\log \hat{\mathbf{x}}_\theta(\mathbf{x}_{t_1})^i(x_0^i), with weight (t1−0)/t1=1(t_1 - 0)/t_1 = 1. Altogether,

−logpθ(x0)≤∑k=1Ntk−tk−1tkExtk∼q(⋅∣x0)[∑i:xtki=M−logx^θ(xtk)i(x0i)]. -\log p_\theta(\mathbf{x}_0) \le \sum_{k=1}^{N} \frac{t_k - t_{k-1}}{t_k}\; \mathbb{E}_{\mathbf{x}_{t_k} \sim q(\cdot \mid \mathbf{x}_0)}\Big[\sum_{i:\, x_{t_k}^i = \mathrm{M}} -\log \hat{\mathbf{x}}_\theta(\mathbf{x}_{t_k})^i(x_0^i)\Big] .

With equal steps, tk−tk−1=1/Nt_k - t_{k-1} = 1/N, this is a Riemann sum of 1tE[⋅]\frac{1}{t} \mathbb{E}[\cdot] over (0,1](0, 1], and as N→∞N \to \infty it becomes

Ldiff(x0)=∫011tExt∼q(⋅∣x0)[∑i:xti=M−logx^θ(xt)i(x0i)]dt=Et∼U(0,1][1t∑i masked−logx^θ(xt)i(x0i)], \mathcal{L}_{\text{diff}}(\mathbf{x}_0) = \int_0^1 \frac{1}{t}\; \mathbb{E}_{\mathbf{x}_t \sim q(\cdot \mid \mathbf{x}_0)}\Big[\sum_{i:\, x_t^i = \mathrm{M}} -\log \hat{\mathbf{x}}_\theta(\mathbf{x}_t)^i(x_0^i)\Big]\, dt = \mathbb{E}_{t \sim U(0, 1]}\Big[\frac{1}{t} \sum_{i \text{ masked}} -\log \hat{\mathbf{x}}_\theta(\mathbf{x}_t)^i(x_0^i)\Big] ,

a masked-token cross-entropy weighted by 1/t1/t. That weight is the whole difference from BERT’s loss: the masking rate is random instead of 15%, and heavily masked samples, where few clean tokens are left to predict from, count less per mask. Dividing by LL gives nats per token. diffusion_loss estimates it with one tt per sequence, the batch’s tt values spread one per equal slice of (0,1](0, 1] to cut the variance. MDLM derives this bound for any schedule of masking probabilities and shows it does not depend on the schedule; the linear one, masking probability tt at time tt, is the one used here.

A second form, and what the bound bounds. Each finite NN bounds the NLL of the NN-step sampler; the integral is their limit. A direct argument says what it bounds. The denoiser here sees only which positions are masked and the clean tokens elsewhere, so the loss at a masked position depends on the masked set JJ and not on tt; write ℓi(J)=−logx^θ(x0 with J masked)i(x0i)\ell_i(J) = -\log \hat{\mathbf{x}}_\theta(\mathbf{x}_0 \text{ with } J \text{ masked})^i(x_0^i). A particular set of size mm is exactly the masked set with probability tm(1−t)L−mt^m (1 - t)^{L - m}, so

Ldiff=∑∣J∣≥1[∫01tm−1(1−t)L−mdt]∑i∈Jℓi(J),m=∣J∣. \mathcal{L}_{\text{diff}} = \sum_{|J| \ge 1} \Big[\int_0^1 t^{m-1} (1 - t)^{L - m}\, dt\Big] \sum_{i \in J} \ell_i(J) , \qquad m = |J| .

The integral is a Beta function. With I(p,q)=∫01tp(1−t)qdtI(p, q) = \int_0^1 t^p (1 - t)^q\, dt, integrating by parts for q≥1q \ge 1 (the boundary terms vanish at both ends) gives I(p,q)=qp+1I(p+1,q−1)I(p, q) = \frac{q}{p + 1} I(p + 1, q - 1); applying it qq times and using I(p+q,0)=1/(p+q+1)I(p + q, 0) = 1/(p + q + 1),

I(p,q)=q!(p+1)(p+2)⋯(p+q)⋅1p+q+1=p!q!(p+q+1)!,I(m−1,L−m)=(m−1)!(L−m)!L!. I(p, q) = \frac{q!}{(p+1)(p+2)\cdots(p+q)} \cdot \frac{1}{p + q + 1} = \frac{p!\, q!}{(p + q + 1)!} , \qquad I(m - 1, L - m) = \frac{(m-1)!\,(L-m)!}{L!} .

There are L!/(m!(L−m)!)L!/(m!\,(L-m)!) sets of size mm, and that count times the weight is exactly 1/m1/m. Grouping the sets by size,

Ldiff=∑m=1L1mE∣J∣=m[∑i∈Jℓi(J)]=L⋅Em∼U{1,…,L}E∣J∣=m[1m∑i∈Jℓi(J)], \mathcal{L}_{\text{diff}} = \sum_{m=1}^{L} \frac{1}{m}\; \mathbb{E}_{|J| = m}\Big[\sum_{i \in J} \ell_i(J)\Big] = L \cdot \mathbb{E}_{m \sim U\{1, \ldots, L\}}\; \mathbb{E}_{|J| = m}\Big[\frac{1}{m} \sum_{i \in J} \ell_i(J)\Big] ,

with JJ uniform among the sets of size mm: mask exactly mm positions, mm uniform from 1 to LL, and average the loss over the masked positions. This is LLaDA’s evaluation formula. Now read it as generation in a random order. Pick an ordering σ\sigma of the LL positions uniformly, and reveal x0\mathbf{x}_0 in that order, predicting position σj\sigma_j from the positions revealed before it. Before step jj the masked set is {σj,…,σL}\{\sigma_j, \ldots, \sigma_L\}, of size m=L−j+1m = L - j + 1 and uniform among sets of that size, and σj\sigma_j is uniform within it; so the expected total loss of this procedure is the double sum above. For each fixed σ\sigma the product pσ(x0)=∏jx^θ(⋅)σj(x0σj)p_\sigma(\mathbf{x}_0) = \prod_j \hat{\mathbf{x}}_\theta(\cdot)^{\sigma_j}(x_0^{\sigma_j}) is a proper distribution over sequences, an autoregressive model that writes positions in the order σ\sigma, and so is their average pmix=Eσ[pσ]p_{\text{mix}} = \mathbb{E}_\sigma[p_\sigma]. By Jensen again, −log-\log being convex,

−logpmix(x0)=−logEσ[pσ(x0)]≤Eσ[−logpσ(x0)]=Ldiff(x0). -\log p_{\text{mix}}(\mathbf{x}_0) = -\log \mathbb{E}_\sigma\big[p_\sigma(\mathbf{x}_0)\big] \le \mathbb{E}_\sigma\big[-\log p_\sigma(\mathbf{x}_0)\big] = \mathcal{L}_{\text{diff}}(\mathbf{x}_0) .

The loss is an upper bound on the NLL of a real distribution: the one of a sampler that reveals one token at a time at uniformly random positions (Ou and co-authors make this connection to any-order autoregressive models). How much larger than that NLL the bound is, the bound does not say. So a diffusion model’s held-out bound compares with a causal model’s exact NLL in one direction only: if the bound is lower, the diffusion model is better; if it is higher, the comparison is undecided.

Two estimators of one quantity. The 1/t1/t form and the 1/m1/m form have the same mean, but not the same variance. With a constant loss of 1 per masked token, the 1/t1/t form’s sample is X/tX/t with XX the number masked, binomial with LL trials and probability tt, so E[X2]=Lt(1−t)+L2t2\mathbb{E}[X^2] = Lt(1 - t) + L^2 t^2 and

Et[X2t2]=∫01(L(1−t)t+L2)dt=∞, \mathbb{E}_t\!\left[\frac{X^2}{t^2}\right] = \int_0^1 \left(\frac{L(1 - t)}{t} + L^2\right) dt = \infty ,

since ∫01dt/t\int_0^1 dt/t diverges: the variance is infinite, from rare samples with a tiny tt and one mask weighted by 1/t1/t. In ten runs of 10610^6 draws with L=64L = 64 (seeds 0 to 9) the per-token estimate averaged between 0.9993 and 1.0012, and its largest value in a run ranged from 69.8 to 858.4. Each sample of the 1/m1/m form is a mean of per-token losses, scaled by nothing larger than 1, so its variance is finite whenever the losses are bounded. The lab trains with the 1/t1/t form, as MDLM and LLaDA do, and nll_bound evaluates with the 1/m1/m form.

Sampling by unmasking

The ancestral sampler follows the reverse steps. Start with every position masked at t=1t = 1 (or the prompt’s positions filled and the rest masked). Split time into SS equal steps; at the step from t=k/St = k/S to s=(k−1)/Ss = (k-1)/S, run the denoiser once on the whole sequence, and reveal each still-masked position with probability (t−s)/t=1/k(t - s)/t = 1/k, drawing its token from x^θ(xt)i\hat{\mathbf{x}}_\theta(\mathbf{x}_t)^i. At k=1k = 1 the probability is 1 and every position is filled. Revealed tokens never change.

Under this schedule each position’s reveal step is uniform over the SS steps: it survives steps S,…,k+1S, \ldots, k+1 and is revealed at step kk with probability

∏j=k+1S(1−1j)⋅1k=∏j=k+1Sj−1j⋅1k=kS⋅1k=1S, \prod_{j=k+1}^{S} \Big(1 - \frac{1}{j}\Big) \cdot \frac{1}{k} = \prod_{j=k+1}^{S} \frac{j - 1}{j} \cdot \frac{1}{k} = \frac{k}{S} \cdot \frac{1}{k} = \frac{1}{S} ,

the product telescoping. So every pass reveals L/SL/S tokens on average, and generating LL tokens costs SS forward passes over all LL positions, against LL passes of one position each for a cached decoder. In chapter 14’s terms, a pass over L≤B∗L \le B^* positions costs about one read of the weights, so in the memory-bound regime S<LS < L passes are that much less weight traffic; but no cache survives between passes, since every revealed token changes every state, and each pass recomputes attention over all LL positions.

The saving has a price that the bound does not see. Positions revealed in the same pass are drawn independently, each from its own distribution given the same xt\mathbf{x}_t, so any dependence between them is lost. Two masked positions that must agree, “New York” or “Los Angeles”, can come out as “New Angeles” when both are revealed together; exercise (g) computes how often. Fewer steps means more tokens per pass and more of this. llama.cpp’s llama-diffusion-cli defaults to 256 steps, runs every step over the whole -ub length with causal attention switched off (llama_set_causal_attn(ctx, false)), and offers other choices of which positions to reveal: --diffusion-algorithm 0 is this random order, attributed in its README to D3PM, and the default, 4, reveals the positions where the model is most confident, the “low-confidence remasking” LLaDA uses. --diffusion-block-length generates block by block from left to right.

Walkthrough

The three reference modules are py/tinygpt/encoder.py, py/tinygpt/ssm.py and py/tinygpt/diffusion.py.

class Encoder:
    """Chapter 11's model with the mask switched off in every block, returning hidden states.

    The token table has vocab_size + 2 rows: text tokens, then [MASK] (mask_id = vocab_size) and
    [CLS] (cls_id = vocab_size + 1). logits() is the masked-token head over the text tokens only.
    """

    def __init__(self, cfg, rng):
        if cfg.n_experts:
            raise ValueError("Encoder has no load-balancing loss; use n_experts=0")
        self.cfg = cfg
        self.mask_id, self.cls_id = cfg.vocab_size, cfg.vocab_size + 1
        self.tok = Tensor(rng.normal(0.0, 0.02, size=(cfg.vocab_size + 2, cfg.d_model)))
        self.pos = Tensor(rng.normal(0.0, 0.02, size=(cfg.context, cfg.d_model))) if cfg.pos == "learned" else None
        self.blocks = [Block(cfg, rng) for _ in range(cfg.n_layers)]
        for block in self.blocks:
            block.attn.causal = False                     # the same block, without the mask
        self.ln_f = LayerNorm(cfg.d_model)
        self.head = Linear(cfg.d_model, cfg.vocab_size, rng, bias=False)

    def parameters(self):
        ps = [self.tok] + ([self.pos] if self.pos is not None else [])
        for m in self.blocks + [self.ln_f, self.head]:
            ps += m.parameters()
        return ps

    def encode(self, x):
        """Input vectors x, a Tensor (B, T, d), through positions, the blocks and the final norm: (B, T, d)."""
        T = x.shape[1]
        if T > self.cfg.context:
            raise ValueError(f"sequence length {T} exceeds context {self.cfg.context}")
        if self.pos is not None:
            x = x + embedding(self.pos, np.arange(T))     # (T, d) broadcasts over the batch
        for block in self.blocks:
            x = block(x)                                  # every position reads every position
        return self.ln_f(x)

    def __call__(self, ids):
        ids = np.asarray(ids, dtype=np.int64)            # (B, T)
        if ids.ndim != 2 or 0 in ids.shape:
            raise ValueError(f"ids must have shape (B, T) with B, T >= 1, got {ids.shape}")
        if ids.min() < 0 or ids.max() > self.cls_id:
            raise ValueError(f"token ids must lie in [0, {self.cls_id + 1}), got {ids.min()}..{ids.max()}")
        return self.encode(embedding(self.tok, ids))     # (B, T, d)

    def logits(self, h):
        """(B, T, d) hidden states -> (B, T, vocab_size) logits for the token at each position."""
        return self.head(h)

Encoder builds chapter 11’s model and switches each block’s attention to non-causal after construction; the flag itself draws nothing from rng. The token table has two extra rows, mask_id = vocab_size and cls_id = vocab_size + 1, while the head predicts only the vocab_size text tokens, so the model is never asked to output [MASK]. encode takes vectors rather than token ids, so a caller can feed the stack inputs that are not rows of the token table; __call__ validates ids, looks them up and calls it. (Chapter 16’s vision encoder uses the same unmasked blocks but builds its own stack: it has no use for the token table or the head, and it needs a larger position table, for a reason given there.) The result is the hidden states after the final norm, (B, T, d), and logits applies the head separately, so callers that want embeddings never pay for the (B, T, V) projection. A mixture-of-experts config is refused: nothing in this chapter adds chapter 11’s balance loss to a masked objective, so an MoE encoder would train its router unbalanced without a word. Chapter 11’s save writes an encoder like any model built from a GPTConfig, recording its class, and load(path, Encoder) reads it back, which is how chapter 21 can start from a trained encoder instead of retraining one; load refuses a file that holds another kind of model.

def pool(h, how="mean"):
    """(B, T, d) hidden states -> (B, d): their mean over positions, or position 0 ("cls")."""
    if how == "mean":
        return h.mean(axis=1)
    if how == "cls":
        B, T, d = h.shape
        first = np.zeros((1, T))
        first[0, 0] = 1.0                                 # (1, T) @ (B, T, d) selects row 0 of each
        return (Tensor(first) @ h).reshape(B, d)
    raise ValueError(f"pool must be 'mean' or 'cls', not {how!r}")

pool needs to select position 0 of a Tensor, and chapter 6’s engine has no indexing op. A (1, T) row with a 1 in column 0, matrix-multiplied into (B, T, d), selects row 0 of each batch element, (B, 1, d), and the gradient flows back only into that row.

def mask_tokens(ids, rng, mask_id, vocab_size, rate=0.15):
    """BERT's corruption: select each text token (id < vocab_size) with probability rate; of those,
    80% become mask_id, 10% a uniform random text token, 10% stay. Returns (inputs, targets), both
    (B, T): targets holds the original token where selected and -1 elsewhere. If nothing was
    selected, one text position is, uniformly, so the loss always has a target.
    """
    ids = np.asarray(ids, dtype=np.int64)
    text = ids < vocab_size
    sel = (rng.random(ids.shape) < rate) & text
    if not sel.any():
        sel.flat[rng.choice(np.flatnonzero(text))] = True
    r = rng.random(ids.shape)
    inputs = ids.copy()
    inputs[sel & (r < 0.8)] = mask_id
    swap = sel & (r >= 0.8) & (r < 0.9)
    inputs[swap] = rng.integers(0, vocab_size, size=int(swap.sum()))
    return inputs, np.where(sel, ids, -1)


def mlm_loss(model, ids, rng, rate=0.15):
    """Masked-token loss: corrupt ids with mask_tokens (its first use of rng), then the mean
    cross-entropy of the encoder's predictions at the selected positions."""
    inputs, targets = mask_tokens(ids, rng, model.mask_id, model.cfg.vocab_size, rate)
    return cross_entropy(model.logits(model(inputs)), targets)

mask_tokens draws the selection first, restricted to text tokens so a [CLS] is never a target, and forces one position when a short input selects none: cross_entropy refuses a batch without targets. One uniform r per position splits the selected ones: below 0.8 [MASK], from 0.8 to 0.9 a random token (which equals the original one time in vocab_size, as in BERT), and the rest unchanged. The targets hold the original token at every selected position, the unchanged ones included, and −1-1 elsewhere, which chapter 8’s cross_entropy ignores. mlm_loss is corruption plus that loss.

def train_objective(loss_fn, opt, ids, steps, context, batch_size, rng):
    """Chapter 8's train with the loss as an argument: loss_fn(x, rng) -> scalar Tensor for a batch x
    (B, T) of random windows of ids. Returns the loss of every step."""
    losses = []
    for _ in range(steps):
        x, _ = get_batch(ids, context, batch_size, rng)
        opt.zero_grad()
        loss = loss_fn(x, rng)
        loss.backward()
        opt.step()
        losses.append(float(loss.data))
        free_graph(loss)
    return losses

train_objective is chapter 8’s train with the loss passed in, since neither the encoder’s nor the diffusion model’s loss is next-token prediction; both corrupt the batch with the same rng the batches come from.

def discretize(a, b, delta):
    """Zero-order hold for a diagonal SSM: abar = exp(delta a), bbar = (exp(delta a) - 1) / a * b.

    Tensors that broadcast together, e.g. a (D, N), b (..., 1, N), delta (..., D, 1) -> (..., D, N).
    a must be nonzero (negative, for a stable system).
    """
    abar = (delta * a).exp()
    return abar, (abar - 1.0) * a ** -1.0 * b

discretize is the zero-order hold, written with Tensor ops so the gradient reaches aa, b\mathbf{b} and Δ\Delta. Shapes are the caller’s business: SelectiveSSM passes aa as (D, N), bt\mathbf{b}_t as (B, T, 1, N) and Δt\Delta_t as (B, T, D, 1), and broadcasting produces (B, T, D, N). a ** -1.0 is safe because aa, minus the exponential of a_log, is never 0.

def scan(a, u):
    """h_t = a_t * h_(t-1) + u_t along axis 1 (time), from h_(-1) = 0. a, u: Tensors (B, T, ...).

    One fused op: a Python loop over T forward, and the same recurrence run backwards for the gradient.
    """
    A, U = a.data, u.data
    h = np.empty_like(U)
    state = np.zeros_like(U[:, 0])
    for t in range(U.shape[1]):
        state = A[:, t] * state + U[:, t]
        h[:, t] = state
    out = Tensor(h, (a, u), "scan")

    def backward():
        # g_t = dL/dh_t in full: its own gradient plus what h_(t+1) = a_(t+1) h_t + ... passes back.
        g = np.zeros_like(U[:, 0])
        for t in reversed(range(U.shape[1])):
            g = out.grad[:, t] + (A[:, t + 1] * g if t + 1 < U.shape[1] else 0.0)
            u.grad[:, t] += g
            if t > 0:
                a.grad[:, t] += g * h[:, t - 1]

    out._backward = backward
    return out

The forward loop is the recurrence. The backward loop is the derivation above: g carries λt\lambda_t, built from the output gradient at tt plus a¯t+1\bar{\mathbf{a}}_{t+1} times the previous iteration’s λt+1\lambda_{t+1}; it is added into u.grad, and times ht−1\mathbf{h}_{t-1} into a.grad. Both use +=, as every backward in chapter 6 does, so a scan whose inputs feed other ops too accumulates correctly (test_scan_gradcheck squares the scan’s output to check this).

def ssm_kernel(abar, bbar, c, T):
    """The convolution kernel of a time-invariant diagonal SSM: K[k] = sum_n c_n abar_n^k bbar_n.

    abar, bbar (D, N) arrays, c (N,) or (D, N) -> K (T, D).
    """
    powers = abar[None] ** np.arange(T)[:, None, None]      # (T, D, N)
    return (c * powers * bbar).sum(-1)


def causal_conv(K, x):
    """y_t = sum_(k=0..t) K[k] x_(t-k), channel by channel. K (T, D), x (B, T, D) -> (B, T, D)."""
    T = x.shape[1]
    y = np.zeros_like(x)
    for k in range(T):
        y[:, k:] += K[k] * x[:, :T - k]
    return y

ssm_kernel raises a¯\bar{a} to the powers 0,…,T−10, \ldots, T-1 at once, (T, D, N), and sums cna¯nkb¯nc_n \bar{a}_n^k \bar{b}_n over nn. causal_conv adds the kernel’s kk-th tap times the input shifted right by kk; it is O(T2)O(T^2), fine for a test oracle.

class SelectiveSSM:
    """A diagonal selective SSM mixing tokens along time, (B, T, D) -> (B, T, D).

    Per token: u = inp(x), step delta = softplus(dt(x)) (B, T, D), B_t = to_b(x) and C_t = to_c(x)
    (B, T, N); per channel d the state h (N,) follows h_t = abar_t h_(t-1) + bbar_t u_t with
    discretize(a, B_t, delta_t), a = -exp(a_log) (D, N); y_t = C_t . h_t + skip * u_t; then out(y).
    """

    def __init__(self, cfg, rng):
        D, N = cfg.d_model, cfg.d_state
        self.inp = Linear(D, D, rng)
        self.dt = Linear(D, D, rng)
        step = np.exp(rng.uniform(np.log(1e-3), np.log(1e-1), size=D))   # Mamba's range of step sizes
        self.dt.bias.data = _inverse_softplus(step)                      # softplus(bias) = step at x = 0
        self.to_b = Linear(D, N, rng, bias=False)
        self.to_c = Linear(D, N, rng, bias=False)
        self.a_log = Tensor(np.log(np.tile(np.arange(1, N + 1, dtype=np.float64), (D, 1))))  # a = -1..-N
        self.skip = Tensor(np.ones(D))
        self.out = Linear(D, D, rng)

    def parameters(self):
        return (self.inp.parameters() + self.dt.parameters() + self.to_b.parameters() + self.to_c.parameters()
                + [self.a_log, self.skip] + self.out.parameters())

    def __call__(self, x):
        B, T, D = x.shape
        N = self.a_log.shape[1]
        u = self.inp(x)                                             # (B, T, D)
        delta = (self.dt(x).exp() + 1.0).log()                      # softplus: (B, T, D), positive
        b, c = self.to_b(x), self.to_c(x)                           # (B, T, N) each
        a = -self.a_log.exp()                                       # (D, N), negative: a decaying state
        abar, bbar = discretize(a, b.reshape(B, T, 1, N), delta.reshape(B, T, D, 1))  # (B, T, D, N)
        h = scan(abar, bbar * u.reshape(B, T, D, 1))                # (B, T, D, N)
        y = (h * c.reshape(B, T, 1, N)).sum(axis=-1) + u * self.skip  # (B, T, D)
        return self.out(y)

SelectiveSSM.__init__ follows Mamba’s initialisation, checked against its reference code (mamba_ssm/modules/mamba_simple.py): the step sizes at zero input are drawn log-uniformly from [0.001,0.1][0.001, 0.1] and stored as the bias of dt through the inverse of softplus, z=y+log(1−e−y)z = y + \log(1 - e^{-y}) for y=softplus(z)y = \mathrm{softplus}(z); the rates are S4D-Real’s an=−na_n = -n for n=1,…,Nn = 1, \ldots, N, stored as a_log =logn= \log n so that aa, minus the exponential of a_log, stays negative whatever training does to it; and the skip weight DD, which adds ut\mathbf{u}_t straight to the output, starts at 1. The call is the Mechanism’s equations in order, with the shapes in the comments. Mamba also puts a short causal convolution and a multiplicative gate around this core; SelectiveSSM leaves both out.

class SSMBlock:
    """Chapter 11's pre-norm block with the attention replaced by a SelectiveSSM."""

    def __init__(self, cfg, rng):
        d = cfg.d_model
        self.ln1, self.mixer = LayerNorm(d), SelectiveSSM(cfg, rng)
        self.ln2, self.up, self.down = LayerNorm(d), Linear(d, 4 * d, rng), Linear(4 * d, d, rng)

    def parameters(self):
        return [p for m in (self.ln1, self.mixer, self.ln2, self.up, self.down) for p in m.parameters()]

    def __call__(self, x):
        x = x + self.mixer(self.ln1(x))
        return x + self.down(gelu(self.up(self.ln2(x))))


class SSMLM:
    """Token embeddings (no position table: the recurrence knows order), SSM blocks, norm, head."""

    def __init__(self, cfg, rng):
        self.cfg = cfg
        self.tok = Tensor(rng.normal(0.0, 0.02, size=(cfg.vocab_size, cfg.d_model)))
        self.blocks = [SSMBlock(cfg, rng) for _ in range(cfg.n_layers)]
        self.ln_f = LayerNorm(cfg.d_model)
        self.head = Linear(cfg.d_model, cfg.vocab_size, rng, bias=False)

    def parameters(self):
        ps = [self.tok]
        for m in self.blocks + [self.ln_f, self.head]:
            ps += m.parameters()
        return ps

    def __call__(self, ids):
        ids = np.asarray(ids, dtype=np.int64)                       # (B, T)
        if ids.ndim != 2 or 0 in ids.shape:
            raise ValueError(f"ids must have shape (B, T) with B, T >= 1, got {ids.shape}")
        if ids.min() < 0 or ids.max() >= self.cfg.vocab_size:
            raise ValueError(f"token ids must lie in [0, {self.cfg.vocab_size}), got {ids.min()}..{ids.max()}")
        x = embedding(self.tok, ids)                                # (B, T, d)
        for block in self.blocks:
            x = block(x)
        return self.head(self.ln_f(x))                              # (B, T, V)

SSMBlock is chapter 11’s pre-norm block with the mixer swapped, and SSMLM is GPT without a position table: the recurrence already knows which token came first.

def init_state(self, batch):
    """The state before any token: one (batch, D, N) array of zeros per layer."""
    return [np.zeros((batch, self.cfg.d_model, self.cfg.d_state)) for _ in self.blocks]

def step(self, ids, state):
    """One token per sequence, ids (B,), in plain numpy: (logits (B, V), the next state).

    The state is all the model keeps between tokens; its size does not grow. The state passed in
    is not modified.
    """
    ids = np.asarray(ids, dtype=np.int64)
    if ids.min() < 0 or ids.max() >= self.cfg.vocab_size:
        raise ValueError(f"token ids must lie in [0, {self.cfg.vocab_size}), got {ids.min()}..{ids.max()}")
    x = self.tok.data[ids]                                      # (B, D)
    new = []
    for blk, h in zip(self.blocks, state):
        m, z = blk.mixer, layer_norm_np(x, blk.ln1)
        u = z @ m.inp.weight.data + m.inp.bias.data             # (B, D)
        delta = np.logaddexp(0.0, z @ m.dt.weight.data + m.dt.bias.data)  # softplus, (B, D)
        b, c = z @ m.to_b.weight.data, z @ m.to_c.weight.data   # (B, N)
        a = -np.exp(m.a_log.data)                               # (D, N)
        abar = np.exp(delta[:, :, None] * a)                    # (B, D, N)
        h = abar * h + (abar - 1.0) / a * b[:, None, :] * u[:, :, None]
        new.append(h)
        y = (h * c[:, None, :]).sum(-1) + m.skip.data * u       # (B, D)
        x = x + y @ m.out.weight.data + m.out.bias.data
        x = x + gelu_np(layer_norm_np(x, blk.ln2) @ blk.up.weight.data + blk.up.bias.data) @ blk.down.weight.data \
            + blk.down.bias.data
    return layer_norm_np(x, self.ln_f) @ self.head.weight.data, new

step is the SSM’s forward_cached: plain numpy over the parameter arrays, one token per sequence, using chapter 12’s layer_norm_np and gelu_np. It computes the new state as a new array rather than updating the old one in place, so a caller can keep an old state, which is the snapshot llama.cpp keeps for rollback. test_stepping_with_a_fixed_state_equals_the_full_forward feeds 12 tokens one at a time and compares the logits with one call of the full model, to 10−1010^{-10}, at initialisation and with every parameter moved off it, and checks that the state has the same size, L⋅B⋅D⋅N⋅8L \cdot B \cdot D \cdot N \cdot 8 bytes, after every step.

def forward_mask(ids, t, rng, mask_id):
    """x_t: each token of ids (B, L) replaced by mask_id independently with probability t, a scalar
    or one value per sequence (B,). Returns (x_t, masked), both (B, L)."""
    ids = np.asarray(ids, dtype=np.int64)
    t = np.asarray(t, dtype=np.float64)
    if t.ndim:
        t = t.reshape(-1, *([1] * (ids.ndim - 1)))            # (B, 1): one rate per sequence
    masked = rng.random(ids.shape) < t
    return np.where(masked, mask_id, ids), masked

forward_mask reshapes a per-sequence (B,) rate to (B, 1) so it broadcasts along positions; a scalar applies to everything.

def masked_nll(logits, targets, weights):
    """Sum over positions with target >= 0 of weight * -log softmax(logits)[target], one fused op.

    logits: Tensor (B, L, V); targets: ints (B, L), -1 where there is nothing to predict;
    weights: broadcastable to (B, L). Returns a scalar Tensor (a sum, not a mean).
    """
    targets = np.asarray(targets, dtype=np.int64)
    keep = targets >= 0
    w = np.where(keep, np.broadcast_to(np.asarray(weights, dtype=np.float64), targets.shape), 0.0)  # (B, L)
    logp = log_softmax(logits.data)                           # (B, L, V)
    tgt = np.where(keep, targets, 0)[..., None]               # (B, L, 1)
    out = Tensor(-(w * np.take_along_axis(logp, tgt, -1)[..., 0]).sum(), (logits,), "masked_nll")

    def backward():
        g = np.exp(logp)                                      # softmax
        np.put_along_axis(g, tgt, np.take_along_axis(g, tgt, -1) - 1.0, -1)  # minus the one-hot target
        logits.grad += out.grad * w[..., None] * g

    out._backward = backward
    return out

masked_nll is chapter 8’s fused cross-entropy with a weight per position and a sum instead of a mean. Positions whose target is −1-1 get weight 0 in both directions; their target index is replaced by 0 only so that take_along_axis has a valid index to read. The backward is wi(softmax−one-hot)w_i(\mathrm{softmax} - \text{one-hot}) at each position, scaled by the incoming gradient.

class DiffusionLM:
    """The denoiser: an Encoder (bidirectional, with a [MASK] token) whose head gives, at every
    position, logits (B, L, V) for the clean token there. No time input: the share of masks shows t."""

    def __init__(self, cfg, rng):
        self.cfg = cfg
        self.net = Encoder(cfg, rng)
        self.mask_id = self.net.mask_id

    def parameters(self):
        return self.net.parameters()

    def __call__(self, ids):
        return self.net.logits(self.net(ids))
def diffusion_loss(model, ids, rng, t=None):
    """A one-sample estimate of the bound on -log p(ids) per token, for a batch ids (B, L):

        (1 / (B L)) sum_b (1 / t_b) sum_(i masked in b) -log p(ids[b, i] | x_t[b]).

    t, one time per sequence in (0, 1], is drawn stratified, t_b = 1 - (b + u) / B with one uniform
    u (the first use of rng), unless given. The masks come from forward_mask (the next use of rng).
    """
    ids = np.asarray(ids, dtype=np.int64)
    B, L = ids.shape
    if t is None:
        t = 1.0 - (np.arange(B) + rng.random()) / B            # one t in each of B equal slices of (0, 1]
    t = np.broadcast_to(np.asarray(t, dtype=np.float64), (B,))
    x, masked = forward_mask(ids, t, rng, model.mask_id)
    return masked_nll(model(x), np.where(masked, ids, -1), (1.0 / t)[:, None]) * (1.0 / (B * L))

DiffusionLM is an Encoder that returns logits. diffusion_loss draws the stratified times tb=1−(b+u)/Bt_b = 1 - (b + u)/B, which lie in (0,1](0, 1] because u<1u < 1, so 1/t1/t is always finite; masks each sequence at its own rate; and weights each sequence’s masked cross-entropy by 1/tb1/t_b, dividing by B⋅LB \cdot L for nats per token. test_diffusion_loss_weights_each_sequence_by_one_over_t recomputes it from the model’s logits with three different tt, and test_diffusion_loss_at_t_one_is_the_mean_cross_entropy checks the all-masked case, where the weight is 1.

def nll_bound(model, ids, context, rng, samples=8):
    """The bound in nats per token on held-out ids, window by window of context tokens.

    Uses the bound's second form: for a window of L tokens it is L times the mean, over m uniform on
    1..L and a uniform set of exactly m masked positions, of the mean -log p at those positions.
    Each window averages samples stratified values of m. An upper bound on the model's NLL, up to
    Monte Carlo noise, and unlike the 1/t form every term is bounded.
    """
    ids = np.asarray(ids, dtype=np.int64)
    total = 0.0
    for s in range(0, len(ids), context):
        w = ids[s:s + context]
        L = len(w)
        m = 1 + ((np.arange(samples) + rng.random()) * L / samples).astype(np.int64)  # (samples,) in 1..L
        order = np.argsort(rng.random((samples, L)), axis=1)                           # a random order per row
        masked = np.argsort(order, axis=1) < m[:, None]        # rank below m: exactly m masked per row
        window = np.broadcast_to(w, (samples, L))
        loss = masked_nll(model(np.where(masked, model.mask_id, window)), np.where(masked, window, -1),
                          (1.0 / m)[:, None])
        total += L * float(loss.data) / samples                 # L * mean over rows of the masked mean
        free_graph(loss)
    return total / len(ids)

nll_bound is the 1/m1/m form. For each window it draws samples values of mm stratified over 1,…,L1, \ldots, L (with samples equal to LL, each value exactly once), and masks exactly mm positions per row by ranking random keys: argsort of argsort gives each position’s rank, and the mm lowest ranks are a uniform set of size mm. Each row’s masked losses are weighted by 1/m1/m, their mean over rows is the window’s per-token bound, and multiplying by the window’s length before dividing by the total length averages over tokens, so a short last window counts in proportion. test_bound_equals_exact_nll_for_a_model_without_context uses a model that ignores its input, for which the bound equals the exact NLL, and test_bound_averages_over_every_number_of_masks one whose confidence grows with the number of masks, for which the bound is a known average over mm.

def generate(model, length, steps, rng, prompt=()):
    """A sequence of length tokens by unmasking in steps parallel steps; prompt fixes its first tokens.

    Start with every free position masked (t = 1). The step from t = k/steps to (k-1)/steps reveals
    each still-masked position with probability (t - s)/t = 1/k, drawing its token from the model's
    distribution there; revealed tokens never change. One forward pass per step: steps passes.
    """
    prompt = [int(p) for p in prompt]
    if steps < 1:
        raise ValueError(f"steps must be at least 1, not {steps}")
    if length > model.cfg.context or len(prompt) > length:
        raise ValueError(f"need len(prompt) <= length <= context {model.cfg.context}")
    if any(not 0 <= p < model.cfg.vocab_size for p in prompt):          # [MASK] and [CLS] are not text
        raise ValueError(f"prompt tokens must lie in [0, {model.cfg.vocab_size})")
    x = np.full(length, model.mask_id, dtype=np.int64)
    x[:len(prompt)] = prompt
    for k in range(steps, 0, -1):
        logits = model(x[None])                               # (1, L, V): every position at once
        z = logits.data[0]
        free_graph(logits)
        hidden = np.flatnonzero(x == model.mask_id)
        reveal = hidden[rng.random(len(hidden)) < 1.0 / k]    # k = 1: every remaining position
        p = np.exp(log_softmax(z[reveal]))                    # (n, V)
        u = rng.random(len(reveal))[:, None]
        x[reveal] = np.minimum((p.cumsum(-1) < u).sum(-1), z.shape[-1] - 1)  # inverse-CDF draws
    return x

generate counts kk down from steps to 1, calls the model once per step on the whole sequence, and reveals each masked position with probability 1/k1/k. It draws the revealed tokens by inverse CDF: one uniform per position, and the token is the number of cumulative probabilities below it (the minimum guards against a cumulative sum that rounds to just under 1). It calls the model even on a step that reveals nothing; Ou and co-authors point out that a denoiser without a time input gives the same output for the same input, so such passes can be skipped, and exercise (f) counts them.

Exercises

(a) Two tokens with values in {0,1,2}\{0, 1, 2\} have the joint distribution below (rows x1x_1, columns x2x_2). For the pairs (0,0)(0, 0), (0,1)(0, 1) and (2,2)(2, 2) compute the log-likelihood, the pseudo-log-likelihood and the pointwise mutual information, and check PLL=logp+PMI\mathrm{PLL} = \log p + \mathrm{PMI}; then compute the entropy, the expected pseudo-NLL and the mutual information.

first token, then second 0 1 2
0 0.30 0.10 0.05
1 0.05 0.25 0.05
2 0.05 0.05 0.10
Answer

The marginals are p(x1)=(0.45,0.35,0.20)p(x_1) = (0.45, 0.35, 0.20) and p(x2)=(0.40,0.40,0.20)p(x_2) = (0.40, 0.40, 0.20). For (0,0)(0, 0): log0.30=−1.2040\log 0.30 = -1.2040; PLL=log(0.30/0.40)+log(0.30/0.45)=−0.6931\mathrm{PLL} = \log(0.30/0.40) + \log(0.30/0.45) = -0.6931; PMI=log(0.30/(0.45×0.40))=0.5108\mathrm{PMI} = \log\big(0.30/(0.45 \times 0.40)\big) = 0.5108, and −1.2040+0.5108=−0.6931-1.2040 + 0.5108 = -0.6931. For (0,1)(0, 1): log0.10=−2.3026\log 0.10 = -2.3026, PLL=−2.8904\mathrm{PLL} = -2.8904, PMI=−0.5878\mathrm{PMI} = -0.5878: a pair that occurs less often than independence predicts, and its pseudo-likelihood is below its likelihood. For (2,2)(2, 2): log0.10=−2.3026\log 0.10 = -2.3026, PLL=−1.3863\mathrm{PLL} = -1.3863, PMI=0.9163\mathrm{PMI} = 0.9163.

So per sequence the pseudo-likelihood is neither an upper nor a lower bound on the likelihood. In expectation it is: the entropy is H=1.9172H = 1.9172 nats, the expected pseudo-NLL 1.7309 and the mutual information 0.1864, and 1.9172−0.1864=1.73081.9172 - 0.1864 = 1.7308 (the last digit is rounding). A masked-token loss of 1.73 on this data would not mean the model beats the entropy of 1.92.

(b) Generate n=1000n = 1000 tokens after a prompt of P=24P = 24 with an encoder (append [MASK], run, sample, repeat) and with a cached decoder. Count the positions each processes and the attention scores each computes.

Answer

The encoder’s pass kk runs P+k+1P + k + 1 positions: nP+n(n+1)/2=24,000+500,500=524,500nP + n(n+1)/2 = 24{,}000 + 500{,}500 = 524{,}500 positions, and ∑k=0999(24+k+1)2=358,433,500\sum_{k=0}^{999} (24 + k + 1)^2 = 358{,}433{,}500 scores, since every pass computes a full square. The cached decoder runs the prompt once and then one position per step, P+n−1=1,023P + n - 1 = 1{,}023 positions; its scores are 24×25/2=30024 \times 25/2 = 300 for the causal prompt plus ∑k=1999(24+k)=523,476\sum_{k=1}^{999} (24 + k) = 523{,}476 for one query against P+kP + k keys at step kk, 523,776 in all. The encoder does 513 times the positions and 684 times the attention work. Both ratios grow with nn: per new token the decoder’s work is one position and a row of scores, and the encoder’s is the whole sequence and its full square.

(c) For a=−16a = -16, b=1b = 1 and Δ=0.1\Delta = 0.1, compute a¯\bar{a} and b¯\bar{b} by the zero-order hold and by Euler’s b¯=Δb\bar{b} = \Delta b. Hold the input at x=1x = 1 for ever: find the continuous system’s steady state and each discrete system’s fixed point, and prove that the zero-order hold’s is right for every Δ\Delta.

Answer

a¯=e−1.6=0.2019\bar{a} = e^{-1.6} = 0.2019; the zero-order hold gives b¯=(0.2019−1)/(−16)=0.0499\bar{b} = (0.2019 - 1)/(-16) = 0.0499, Euler 0.1. The continuous steady state has h′=0h' = 0: ah+b=0ah + b = 0, h∗=−b/a=0.0625h^* = -b/a = 0.0625. A discrete fixed point satisfies h=a¯h+b¯h = \bar{a} h + \bar{b}, h=b¯/(1−a¯)h = \bar{b}/(1 - \bar{a}): 0.0625 for the zero-order hold and 0.1253 for Euler, twice the true value. In general b¯/(1−a¯)=(eΔa−1)b/a1−eΔa=−b/a\bar{b}/(1 - \bar{a}) = \frac{(e^{\Delta a} - 1) b/a}{1 - e^{\Delta a}} = -b/a for any Δ\Delta: with the input held constant the zero-order hold is the exact solution at the sample times, so it cannot drift from the continuous system’s equilibrium. Euler’s is right only as Δa→0\Delta a \to 0. A large step with a fast rate is where Mamba’s initial range reaches (Δ\Delta up to 0.1, aa down to −N-N).

(d) Implement the scan as ⌈log2T⌉\lceil \log_2 T \rceil rounds of the associative combine and check it against scan.

Answer

Round rr, counting from 0, combines each position with the one 2r2^r before it; after it, position tt holds the composition of the steps t−2r+1+1,…,tt - 2^{r+1} + 1, \ldots, t (fewer at the start). Every position updates at once, which is where the parallelism is.

import numpy as np

from tinygpt.autograd import Tensor
from tinygpt.ssm import scan


def combine(first, second):
    """(a1, u1) then (a2, u2): h -> a2 (a1 h + u1) + u2 = (a2 a1) h + (a2 u1 + u2)."""
    (a1, u1), (a2, u2) = first, second
    return a2 * a1, a2 * u1 + u2


def parallel_scan(a, u):
    """Hillis-Steele: after round r (from 0), position t holds the composition of steps t - 2^(r+1) + 1 .. t."""
    a, u, T, levels, shift = a.copy(), u.copy(), a.shape[1], 0, 1
    while shift < T:
        a_new, u_new = combine((a[:, :-shift], u[:, :-shift]), (a[:, shift:], u[:, shift:]))
        a[:, shift:], u[:, shift:] = a_new, u_new      # every position updates at once
        shift, levels = 2 * shift, levels + 1
    return u, levels                                   # from h_(-1) = 0 the state is the u part


rng = np.random.default_rng(0)
a, u = np.exp(-rng.random((2, 64, 3, 4))), rng.normal(size=(2, 64, 3, 4))
h, levels = parallel_scan(a, u)
print("levels", levels, "max difference from scan", np.abs(h - scan(Tensor(a), Tensor(u)).data).max())
levels 6 max difference from scan 8.881784197001252e-16

Six rounds for 64 steps. The uu part is the state because each composition is applied to h−1=0\mathbf{h}_{-1} = \mathbf{0}, which the a¯\bar{a} part multiplies away. This version does O(TlogT)O(T \log T) combines; the work-efficient version (an up-sweep and a down-sweep over a tree) does O(T)O(T) in 2log2T2 \log_2 T rounds. The differences from the sequential scan are rounding: the products are formed in a different order.

(e) Mamba-2.8B’s configuration (state-spaces/mamba-2.8b-hf) has 64 layers, hidden_size 2560, intermediate_size 5120, state_size 16 and conv_kernel 4. llama.cpp keeps, per layer and sequence, a convolution state of (dconv−1)⋅dinner(d_{\text{conv}} - 1) \cdot d_{\text{inner}} numbers and an SSM state of dstate⋅dinnerd_{\text{state}} \cdot d_{\text{inner}} numbers, both f32 (n_embd_r and n_embd_s in src/llama-hparams.cpp, and GGML_TYPE_F32 for both where llama_memory_recurrent is created). How much memory does one sequence need, and how many positions of a transformer’s f16 KV cache with the same 64 layers and width 2560 is that?

Answer

Per layer: 3×5120=15,3603 \times 5120 = 15{,}360 convolution numbers and 16×5120=81,92016 \times 5120 = 81{,}920 state numbers, 97,280 in all, 389,120 bytes at 4 bytes each; for 64 layers, 24,903,680 bytes, 23.75 MiB per sequence, at any context length. (Mamba-1 has no group count, so the 2⋅ngroup⋅dstate2 \cdot n_{\text{group}} \cdot d_{\text{state}} term of the convolution size is 0.) The transformer’s cache, with full multi-head attention, holds 2×64×2560×2=655,3602 \times 64 \times 2560 \times 2 = 655{,}360 bytes per position, so the SSM’s state equals 38.0 positions of it. At 4,096 positions the cache is 2.5 GiB and at 32,768 it is 20.0 GiB, where the SSM still keeps 23.75 MiB. Grouped-query attention would divide the transformer’s figures by its group size, not change the conclusion.

(f) generate fills a window of 64 after a prompt of 8 tokens. How many of its passes are expected to reveal nothing with S=56S = 56, S=16S = 16 and S=8S = 8 steps, and why can an engine skip them?

Answer

Only the 56 masked positions are revealed; each lands on a step uniform over the SS steps (the Mechanism’s telescoping product), independently of the others, since each draws its own uniforms. A pass reveals nothing when all 56 land elsewhere, probability (1−1/S)56(1 - 1/S)^{56}, so the expected number of empty passes is S(1−1/S)56S(1 - 1/S)^{56}: 20.42 of 56 passes for S=56S = 56, more than a third although there are as many steps as free tokens; 0.43 for S=16S = 16; 0.0045 for S=8S = 8. An empty pass leaves the sequence unchanged, and a denoiser without a time input returns the same logits for the same input, so the next pass can reuse them instead of running the model; with a time input the logits would change with tt and could not be reused. test_generate_reveals_a_uniform_share_per_step checks the average of L/SL/S revealed per pass.

(g) A two-position text is “New York” or “Los Angeles” with probability 12\frac{1}{2} each, and the denoiser is perfect: with both positions masked each marginal is 12\frac{1}{2}–12\frac{1}{2}, and with one revealed the other is determined. Find the probability that generate with SS steps produces one of the two incoherent texts.

Answer

If the two positions are revealed at different steps, the second is drawn given the first and the text is coherent. If they are revealed at the same step, each is drawn from its marginal independently, and the pair is incoherent with probability 12\frac{1}{2} (“New Angeles” or “Los York”). The two reveal steps are independent and uniform over the SS steps (the Mechanism’s telescoping product), so they coincide with probability S⋅(1/S)2=1/SS \cdot (1/S)^2 = 1/S, and

P(incoherent)=12S: P(\text{incoherent}) = \frac{1}{2S} :

12\frac{1}{2} in one step, 14\frac{1}{4} in two, 0.0078 in 64. The bound is the same for every SS (it is a property of the denoiser, not the sampler), which is why the lab also judges the samples themselves.

Lab

Implement the functions and classes of py/labs/ch15/starter.py except the four it provides (SSMConfig, SSMBlock, DiffusionLM and train_objective), following its docstring for the attribute names, the order of parameters() and the order of draws from rng. Run

make lab CH=15 IMPL=mine

until it passes. Read py/labs/ch15/test_lab.py first. For the encoder it checks that the hidden states are exactly chapter 11’s blocks without the mask (for both position schemes), that position 0 reads the last token, the pooling, the 80/10/10 rates on 20,000 positions, and a gradient check. For the SSM, the zero-order hold against a 30,000-step Runge–Kutta integration, the scan and its gradient, recurrence against convolution, the selective mixer against its definition, causality, the initialisation, the step-by-step equality with the full forward pass and the constant state size. For diffusion, the masking rate per sequence, the 1/t1/t weighting, the stratified times, the bound on two toy models where it is known exactly, the number of passes, that revealed tokens never change, and that generate draws from the model’s distribution.

Three tests train. test_ssmlm_beats_unigram_on_persuasion is chapter 11’s acceptance test for the SSM: 100 steps on the first 30,000 characters of Persuasion must beat the add-one unigram by 0.3 nats. The other two use the tiny corpus of chapter 8, because each test must run in under 15 s, the suite’s budget per test. At the tests’ sizes on those 30,000 characters of Persuasion (width 32, windows of 32, RoPE, with lr 3×10−33 \times 10^{-3} for the encoder, which was faster there, and 10−310^{-3} for the denoiser), the encoder’s probe was at 0.965 after 1,250 steps, and the denoiser’s bound 0.155 nats below the unigram’s 4.205 after 1,500; on an idle straylight that took 20 s and 33 s, over the budget, against 2.1 s and 2.6 s for the tiny-corpus runs below.

  • test_encoder_embeddings_tell_text_from_shuffled_text asks whether mean-pooled embeddings know word order. It takes windows of 16 held-out tokens and the same tokens shuffled; no feature of the bag of tokens can tell them apart, so chance is exactly 0.5. A linear probe is fitted on 200 training pairs, the mean of the real-minus-shuffled differences whitened by their covariance, and scores a held-out pair right when it ranks the real window higher. After 300 steps at lr 10−310^{-3} the probe is right on 198 of the 200 held-out pairs, 0.990, against 0.500 for the untrained encoder; the test requires the trained probe above 0.9 and the untrained one below 0.7. This encoder has learned positions: untrained encoders with RoPE scored 0.64 to 0.86 on the same probe in five seeds, against 0.48 to 0.57 with learned positions, so they would give the test no clean starting point.
  • test_diffusion_training_lowers_the_bound requires 300 steps to take the bound from a uniform guess to 0.3 nats below the unigram’s loss, which the denoiser can only do by using context. It trains as the lab’s denoiser does, with RoPE at lr 10−310^{-3}: from 2.906 to 1.763 against a unigram of 2.609, and 1.76 to 2.14 in five seeds. With learned positions at 3×10−33 \times 10^{-3}, two of five seeds were still at 2.617 and 2.600 after 300 steps; the results below come back to this.

Then train chapter 11’s decoder and the three models of this chapter side by side on Persuasion. The decoder and the SSM train as in chapter 11, at lr 3×10−33 \times 10^{-3} (the decoder with learned positions; the SSM needs none); the encoder and the denoiser use RoPE at lr 10−310^{-3}, for the reason in the results. Save as /tmp/beyond_lab.py:

import pathlib
import sys
import time

import numpy as np

from tinygpt.bpe import BPE
from tinygpt.diffusion import DiffusionLM, diffusion_loss, forward_mask, generate, nll_bound
from tinygpt.encoder import Encoder, mlm_loss, pool, train_objective
from tinygpt.mlp import Adam
from tinygpt.nn import cross_entropy, evaluate, free_graph, train
from tinygpt.prob import fit_categorical, nll
from tinygpt.sample import KVCache, forward_cached, sample_token
from tinygpt.ssm import SSMLM, SSMConfig
from tinygpt.transformer import GPT, GPTConfig, load

run = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else "/tmp/tinygpt-persuasion")
steps = int(sys.argv[2]) if len(sys.argv) > 2 else 300
tok, judge = BPE.load(run / "tokenizer.json"), load(run / "model.npz")
ids = np.array(tok.encode(pathlib.Path("data/persuasion.txt").read_text()))
cut = int(0.9 * len(ids))
train_ids, held_out = ids[:cut], ids[cut:cut + 20_000]  # train_gpt's split and held-out tokens
C = 64
cfg = GPTConfig(tok.vocab_size, C, d_model=64, n_heads=4, n_layers=2)
bidirectional = GPTConfig(tok.vocab_size, C, d_model=64, n_heads=4, n_layers=2, pos="rope")
lr = {"decoder": 3e-3, "ssm": 3e-3, "encoder": 1e-3, "diffusion": 1e-3}


def masked_ce(logits_of, mask_id, ids, rng):
    """Held-out cross-entropy at 15% of positions replaced by [MASK], window by window: not an NLL."""
    total = count = 0
    for s in range(0, len(ids) - C + 1, C):
        x, masked = forward_mask(ids[None, s:s + C], 0.15, rng, mask_id)
        loss = cross_entropy(logits_of(x), np.where(masked, ids[None, s:s + C], -1))
        total, count = total + float(loss.data) * masked.sum(), count + masked.sum()
        free_graph(loss)
    return total / count


def shuffle_probe(enc):
    """Held-out accuracy of the paired, whitened linear probe of the lab test (chance 0.5)."""
    g = np.random.default_rng(1)

    def pairs(src):
        real = np.stack([src[s:s + C] for s in g.integers(0, len(src) - C, size=200)])
        return pool(enc(real)).data - pool(enc(np.stack([g.permutation(w) for w in real]))).data
    d = pairs(train_ids)
    w = np.linalg.solve(np.cov(d.T) + 1e-3 * np.eye(d.shape[1]), d.mean(0))
    return float(np.mean(pairs(held_out) @ w > 0))


def judged(seq):
    """Nats per token the chapter 11 model assigns to the 63 tokens after the prompt."""
    loss = cross_entropy(judge(np.array([seq[:-1]])), np.array([seq[1:]]))
    free_graph(loss)
    return float(loss.data)


rng = np.random.default_rng(0)
models = {"decoder": GPT(cfg, rng), "encoder": Encoder(bidirectional, rng),
          "ssm": SSMLM(SSMConfig(tok.vocab_size), rng), "diffusion": DiffusionLM(bidirectional, rng)}
objectives = {"encoder": mlm_loss, "diffusion": diffusion_loss}
start = time.time()
for name, m in models.items():
    t0, opt, g = time.time(), Adam(m.parameters(), lr[name]), np.random.default_rng(1)
    if name in objectives:
        train_objective(lambda x, r, m=m, f=objectives[name]: f(m, x, r), opt, train_ids, steps, C, 16, g)
    else:
        train(m, opt, train_ids, steps, C, 16, g)
    print(f"{name:9s} {sum(p.data.size for p in m.parameters()):7,d} parameters  {steps} steps  "
          f"{time.time() - t0:5.1f}s", flush=True)

print("held-out loss, nats per token:")
print(f"  decoder    {evaluate(models['decoder'], held_out, C):.3f}  exact NLL")
print(f"  ssm        {evaluate(models['ssm'], held_out, C):.3f}  exact NLL")
print(f"  diffusion  {nll_bound(models['diffusion'], held_out, C, np.random.default_rng(2)):.3f}  upper bound on NLL")
enc, dif = models["encoder"], models["diffusion"]
print(f"  encoder    {masked_ce(lambda x: enc.logits(enc(x)), enc.mask_id, held_out, np.random.default_rng(2)):.3f}"
      "  CE at 15% masked, not an NLL")
print(f"  diffusion  {masked_ce(dif, dif.mask_id, held_out, np.random.default_rng(2)):.3f}  CE at 15% masked, not an NLL")
unigram = fit_categorical(train_ids, tok.vocab_size, alpha=1.0)
print(f"  unigram    {nll(unigram, held_out):.3f}  exact NLL, add-one counts")
print(f"encoder shuffle probe: {shuffle_probe(models['encoder']):.3f}")

print("8 windows of 64 tokens, each from one held-out prompt token (sampling at temperature 1):")
print("  model        passes  positions  bytes kept  judged nats/token")
prompts, g = [int(t) for t in held_out[:8 * C:C]], np.random.default_rng(3)


def report(name, passes, positions, kept, samples):
    print(f"  {name:12s} {passes:6d}  {positions:9d}  {kept:10,d}  {np.mean([judged(s) for s in samples]):.3f}")


gpt, samples = models["decoder"], []
for p in prompts:
    cache, seq = KVCache(cfg.n_layers), [p]
    for i in range(C - 1):
        seq.append(sample_token(forward_cached(gpt, seq if i == 0 else seq[-1:], cache)[-1], g))
    samples.append(seq)
report("decoder", C - 1, C - 1, sum(a.nbytes for a in cache.k + cache.v), samples)
ssm, samples = models["ssm"], []
for p in prompts:
    state, seq = ssm.init_state(1), [p]
    for i in range(C - 1):
        logits, state = ssm.step(np.array([seq[-1]]), state)
        seq.append(sample_token(logits[0], g))
    samples.append(seq)
report("ssm", C - 1, C - 1, sum(s.nbytes for s in state), samples)
enc, samples = models["encoder"], []
for p in prompts:
    seq, positions = [p], 0
    for i in range(C - 1):
        h = enc(np.array([seq + [enc.mask_id]]))       # append [MASK], predict it, recompute everything
        seq.append(sample_token(enc.logits(h).data[0, -1], g))
        positions += len(seq)
        free_graph(h)
    samples.append(seq)
report("encoder", C - 1, positions, 0, samples)
report("unigram", 0, 0, 0, [[f] + g.choice(tok.vocab_size, size=C - 1, p=unigram).tolist() for f in prompts])
for S in (63, 16, 4, 1):
    samples = [generate(models["diffusion"], C, S, g, prompt=[p]).tolist() for p in prompts]
    report(f"diffusion {S}", S, S * C, 0, samples)
print(f"total {time.time() - start:.0f}s")

and run it from py/, with the tokenizer and model chapter 11 saved:

OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python /tmp/beyond_lab.py /tmp/tinygpt-persuasion

It printed, in two minutes on straylight (load average falling from 8.5 to 2.8 as earlier runs ended, on 32 threads; the script uses one):

decoder   169,344 parameters  300 steps   19.9s
encoder   165,376 parameters  300 steps   19.6s
ssm       163,584 parameters  300 steps   41.8s
diffusion 165,376 parameters  300 steps   19.8s
held-out loss, nats per token:
  decoder    3.816  exact NLL
  ssm        3.387  exact NLL
  diffusion  5.259  upper bound on NLL
  encoder    5.204  CE at 15% masked, not an NLL
  diffusion  5.263  CE at 15% masked, not an NLL
  unigram    5.238  exact NLL, add-one counts
encoder shuffle probe: 0.645
8 windows of 64 tokens, each from one held-out prompt token (sampling at temperature 1):
  model        passes  positions  bytes kept  judged nats/token
  decoder          63         63     129,024  5.128
  ssm              63         63      16,384  4.407
  encoder          63       2079           0  8.873
  unigram           0          0           0  8.901
  diffusion 63     63       4032           0  9.084
  diffusion 16     16       1024           0  9.160
  diffusion 4       4        256           0  9.007
  diffusion 1       1         64           0  9.018
total 115s

Rerun with 2,000 steps, the second argument, it took 12 minutes on straylight (load average 1.5 to 2.8) and printed:

decoder   169,344 parameters  2000 steps  142.4s
encoder   165,376 parameters  2000 steps  137.5s
ssm       163,584 parameters  2000 steps  287.1s
diffusion 165,376 parameters  2000 steps  134.7s
held-out loss, nats per token:
  decoder    3.025  exact NLL
  ssm        2.921  exact NLL
  diffusion  5.053  upper bound on NLL
  encoder    3.179  CE at 15% masked, not an NLL
  diffusion  4.903  CE at 15% masked, not an NLL
  unigram    5.238  exact NLL, add-one counts
encoder shuffle probe: 1.000
8 windows of 64 tokens, each from one held-out prompt token (sampling at temperature 1):
  model        passes  positions  bytes kept  judged nats/token
  decoder          63         63     129,024  3.300
  ssm              63         63      16,384  3.643
  encoder          63       2079           0  5.853
  unigram           0          0           0  8.901
  diffusion 63     63       4032           0  8.881
  diffusion 16     16       1024           0  8.384
  diffusion 4       4        256           0  8.804
  diffusion 1       1         64           0  8.825
total 717s

On titan, an Apple M-series machine at load average 1.8 to 12.8, the same script printed every figure of the 300-step run identically, in 171 s. At 2,000 steps (655 s) every figure matched except the denoiser’s six lines, and the same held on every machine of the fleet but straylight: the bound was 5.106 on titan, 5.096 on talos and dixie and 5.084 on orion; the masked CE 5.019, 4.978 and 4.963; and the judged figures 8.50 to 9.16 across the four, where straylight printed 8.38 to 8.88. Each CPU runs different vectorised kernels, OpenBLAS’s matrix products and numpy’s own loops, which group the same sums differently (chapter 16 shows it), and training carries the difference forward.

  • Each loss is labelled with what it is. The decoder’s and the SSM’s held-out figures are exact NLLs of the same tokens and compare directly: after 300 steps the SSM is 0.43 nats ahead, after 2,000 steps 0.10 (2.921 against 3.025, where chapter 11’s own run reached 3.012). One seed, one width and a few minutes of training decide nothing about the architectures at scale; what the toy does show is that a diagonal recurrence of 16 numbers per channel, with no attention anywhere, learns this text as fast as attention does. The diffusion model’s 5.053 is an upper bound: its NLL is at most that, and the comparison with the decoder’s 3.025 is undecided in principle. The two “CE at 15% masked” lines are neither NLLs nor bounds: they score one token given 85% of the others, which by the pseudo-likelihood argument can come out below an NLL on the same text.
  • Both bidirectional models leave the unigram level, the encoder far sooner. After 300 steps the encoder and the denoiser score 5.204 and 5.263 at 15% masked, about the unigram’s 5.238: they predict a masked token from nothing but token frequencies. After 2,000 steps the encoder is at 3.179 and its shuffle probe at 1.000; the denoiser has only started, at 4.903 and a bound of 5.053. Trained alone for 3,000 steps with the same settings, three seeds of each (scored on the first 4,096 held-out tokens, on straylight) reached 2.77 to 2.84 for the encoder, and 3.40 to 3.91 at 15% masked with bounds of 4.07 to 4.41 for the denoiser. At step 2,000 those denoiser runs were at 4.07 to 4.61 at 15% masked, against the lab’s 4.903, so the lab’s seed is a slow one. The 300-step probe of 0.645 is weak evidence of order: the lab’s own untrained encoder scores 0.520 (a run on talos), and untrained RoPE encoders in the tests’ smaller setup scored 0.64 to 0.86.
  • What a stalled masked objective looks like, and what got it out. Trained with the decoder’s settings, learned positions at lr 3×10−33 \times 10^{-3}, three seeds of each model (on dixie, scored the same way) stayed at the unigram for 3,000 steps: the encoder at 5.21 to 5.24 at 15% masked and the denoiser’s bound at 5.22 to 5.23, against the unigram’s 5.235 on those tokens. The encoder’s training loss meanwhile fell to about 4.9, from the unchanged 10% of its targets, which it can copy. So a held-out masked loss parked at the unigram’s value for thousands of steps, samples scoring like unigram draws and a probe at chance are the signature of a model that uses no context, whatever its training loss says. RoPE at lr 10−310^{-3} moved every seed off it. Either change alone did less: RoPE at 3×10−33 \times 10^{-3} freed all three encoders (2.82 to 3.27) but left one of three denoisers at the unigram (bound 5.228), and learned positions at 10−310^{-3} barely moved either model (encoder 5.07 to 5.18, denoiser bounds 5.20 to 5.21). The tempting explanation, that a masked position must get everything through attention that starts near uniform, fails a control: the same encoder with the causal mask put back, at the stalled settings, must also fetch its left neighbour through attention to predict a masked token, and it left the unigram in all three seeds, at 4.03 to 4.07 after 3,000 steps. The Mechanism’s argument suggests another: an encoder learns order only through its position table, which starts as small as its token rows, and chapter 16 measures a vision encoder whose small position table left it blind to position for a whole run. Scaling the table up tests this. On straylight, three seeds of each model at the stalled settings with the table drawn from N(0,1)\mathcal{N}(0, 1), or from N(0,0.22)\mathcal{N}(0, 0.2^2), stayed within 0.11 nats of the unigram’s 5.235 after 3,000 steps (the encoder at 5.22 to 5.24 and 5.13 to 5.21 at 15% masked, the denoiser’s bound at 5.23 and 5.22 to 5.23), as did the unchanged N(0,0.022)\mathcal{N}(0, 0.02^2) control (5.20 to 5.24; bounds 5.22 to 5.23). With no position table at all, a model that by the Mechanism’s argument sees only the bag of tokens in its window, and could in principle beat the unigram with that alone, stayed there too (5.20 to 5.21; bounds 5.22 to 5.23). So the stalled models used no context of either kind, ordered or not, and the size of the position table is ruled out as the cause. What holds them at those settings remains unidentified; what the runs show is that the stall came from the training settings, not from the size of the model or of the corpus.
  • The cost columns do not depend on training. Filling a window of 64 from one token, the decoder makes 63 passes of one position and keeps 129,024 bytes of cache at the end, 2×2×63×64×82 \times 2 \times 63 \times 64 \times 8; the SSM makes the same 63 passes and keeps 16,384 bytes, 2×64×16×82 \times 64 \times 16 \times 8, the same after one token as after 63. The encoder’s 63 passes compute 2,079 positions, the nP+n(n+1)/2nP + n(n+1)/2 of the Mechanism with P=1P = 1, n=63n = 63, and keep nothing. The diffusion model makes as many passes as it is given steps, each over all 64 positions.
  • The judged column is what the samples are worth. The chapter 11 model scores each 63-token continuation. In the 2,000-step run the decoder’s and the SSM’s samples score 3.300 and 3.643 nats per token, not far from the judge’s own held-out loss of 3.012. The encoder’s score 5.853, far better than i.i.d. draws from the unigram at 8.901 but far behind the causal models; each of its tokens is predicted at a masked last position with nothing to its right, a position that gets 1 in 64 of the masks it trains on. The denoiser’s samples, at 8.38 to 8.88 (8.50 to 9.16 on the other machines), are close to unigram draws, as a model that has just begun to use context would give. The factorisation error of few steps, exercise (g), cannot show until the denoiser’s tokens depend on each other.

What the toy can show is the arithmetic of each family (what a position reads, what is kept between tokens, how many passes a sequence costs), how to read each loss, and that a masked objective trains on this corpus once its settings let it. What it cannot show is how the families compare as language models: after 2,000 steps the denoiser’s bound is still 2 nats above the decoder’s NLL and the encoder’s loss is a different quantity, and the orderings reported in the papers above come from models thousands of times larger trained on billions of tokens.

Further reading

results matching ""

    No results matching ""