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
--embeddingand--pooling {none,mean,cls,last,rank}, and--rerankfor 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_recurrentlistsmamba,mamba2,rwkv6,rwkv6qwen2,rwkv7andarwkv7, whose layers are all recurrent, andllm_arch_is_hybridlists seventeen architectures in which “each layer may be either attention-based or recurrent”, among themjamba,falcon-h1,granitehybrid,nemotron_h,qwen3next,qwen35,qwen35moeandlfm2. The reader’sornith-1.5-35b-a3bis aqwen35moe: itsconfig.jsonlists 30 of its 40 layers aslinear_attentionand every fourth asfull_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_diffusionlistsdream,llada,llada-moeandrnd1, 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.
Mechanism
Encoders: attention without the mask
Chapter 10’s attention scores query against key and adds the causal mask, where . Drop the mask. For one head with , , of shape (T, d_h),
with the scores and weights of shape (T, T) and of shape (T, d_h). The sums now run over all 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 , the input gives the output . 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 to times its output on ; the residual sum keeps the property, . Equivariant maps compose, , 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 as it draws the token table: at initialisation each position is a vector of norm about (at ) 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 ’s state depends only on , 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 ’s state is a weighted sum over the values of all positions, so it depends on every token, and appending 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 tokens by tokens with an encoder, append a [MASK], run the whole sequence, sample the masked position, and repeat: pass processes positions, in all
positions against the cached decoder’s , and each pass computes a full 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 from ” 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 and chosen set ,
with at position 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 is then , where is every token but , and summed over positions this is the negative pseudo-log-likelihood,
which Besag defined for spatial data in 1975. It is not the log-likelihood. Take two tokens. By the definition of conditional probability, and , so
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 , so the expected pseudo-NLL is , below the entropy by exactly the information the tokens share. For tokens the same comparison uses chapter 4’s chain rule: the entropy is , and the expected pseudo-NLL is . 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
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 of the time and, with a 512-token vocabulary, wrong 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, . CLS pooling prepends a special token and takes its final state, : 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 in continuous time , and drive a state of shape (N,) with it:
with (N, N) and , (N,). This is a linear time-invariant system, the object S4 and Mamba start from. Make diagonal and the coordinates decouple into scalar equations . Drop the index and solve one. Multiply by : the left side becomes a derivative,
Integrate from to and multiply by :
Tokens arrive at discrete steps, so hold the input constant over each interval of length , : the zero-order hold. Substituting , which runs from down to 0,
and the step from one token to the next is
the last form being Mamba’s equation (4) for a diagonal , where the inverse is elementwise. With , and the state decays: sets how fast, in units of . For small , and , the Euler step; the ratio of the exact to Euler’s is with . Mamba’s reference implementation, selective_scan_ref in mamba_ssm/ops/selective_scan_interface.py, uses exactly this pair: for and for . At its initial step sizes, , and its rates (below), the ratio runs from 0.9995 (, ) to 0.4988 (, ), 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 channels, one system each, so the state is (D, N), and each channel’s output is with its own .
Recurrence and convolution are the same map
With , and fixed, unroll the recurrence from . Claim: , powers and products elementwise over the coordinates. For , , the single term . If it holds for ,
substituting , which is the claim for . Take the dot product with :
The output is a causal convolution of the input with the kernel , one kernel per channel, shape (T, D) for positions. The two forms compute the same numbers and suit different jobs. Training sees the whole sequence, and the convolution is parallel over (S4 computes it with FFTs in ). Generation sees one token at a time, and the recurrence costs 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 .
Selectivity
A time-invariant system treats every token alike: the kernel depends on the distance , 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 , the (D,) vector of all channels at step :
with of shape (D,), one step per channel and positive because , and , of shape (N,), shared by the channels. (Mamba computes through a low-rank projection; SelectiveSSM uses a full (D, D) one.) Discretising with each channel’s own step gives and of shape (D, N) that change from token to token, and the recurrence per channel becomes . Unrolling it by the same induction,
The bracket plays the role of , but it depends on and separately and, through , and , 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 changes the steps, which test_selective_ssm_is_causal_and_input_dependent checks.
What selectivity buys shows most simply with one state number, and , the case of Mamba’s Theorem 1. Then and . With , , so
a gated recurrence whose gate is the sigmoid of a linear function of the input. A large 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 , so each step is an affine map with , and two steps compose into one of the same form:
Composition of functions is associative, so the prefix compositions, which are the states, can be computed in 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 : 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 be the gradient of the loss with respect to the output as used downstream, and the full gradient; both have the shape of , (B, D, N) in SelectiveSSM. The full gradient of also counts its influence through , and through that on everything later:
a scan from the last step to the first. Then, since depends on with derivative 1 and on through the product with ,
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 layers keeps numbers whatever the length; chapter 12’s KV cache keeps numbers after positions. The lab’s models, , , , 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 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 f32 numbers, 2 MiB, per layer, and a convolution state holding the last 3 inputs of its 8,192 query, key and value channels, 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 bits can be in at most configurations, so it cannot tell apart more than 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 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 has already mixed in every token up to . llama.cpp’sllama_memory_recurrent::seq_rmsays 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 inllm_arch_supports_rs_rollback.qwen35moeis 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 be a sequence of tokens (from here on is a length, not the number of layers of the previous sections) and a time. The forward process masks each position independently with probability :
where is the mask token and the superscript is the position. At nothing is masked; at everything is, whatever was. The mask is absorbing: once masked, a position stays masked as grows. As a process in time, for a masked position stays masked, and an unmasked one is masked by time with probability , which keeps the marginal right: unmasked at with probability . D3PM introduced this absorbing-state corruption for discrete diffusion; MDLM and LLaDA are its current form.
The model runs time backwards. Its network, the denoiser, reads and returns at every position a distribution of shape (V,) over the clean token there; it is an encoder whose head predicts only text tokens, never . This one has no input for : 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 , what does look like given and the clean ? If is not masked, it was not masked at either (masks absorb), so . If , Bayes’ rule with the forward probabilities gives
Going back from to , a masked position is revealed with probability , and if revealed it is the clean token. The model’s reverse step copies this with its prediction in place of the unknown : unmasked positions are copied, and a masked position stays masked with probability or becomes token with probability , independently across positions.
The ELBO. Fix times and write the latent path . The model generates (all masks, with probability 1) and then steps back: . Its probability of sums over paths, and multiplying and dividing by the forward path probability turns the sum into an expectation:
is concave, so by Jensen’s inequality , and
To compare the two path probabilities factor by factor, rewrite ’s. The forward process is a Markov chain, . For , the Markov property lets each factor also condition on , and Bayes’ rule turns it around:
In the product over the ratios of marginals telescope to , and the factor is , which cancels the denominator:
Pair each factor with the model’s and the bound splits into three kinds of term:
The first is 0: both sides put probability 1 on the all-mask sequence. In the -th term the expectation over the rest of the path reduces to one over and then 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 on staying masked, and the posterior puts on where the model puts (the other outcomes have posterior probability 0 and contribute nothing), so with , ,
The last term is the same formula at : the model’s final step reveals every remaining mask, and is the sum over masked positions of , with weight . Altogether,
With equal steps, , this is a Riemann sum of over , and as it becomes
a masked-token cross-entropy weighted by . 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 gives nats per token. diffusion_loss estimates it with one per sequence, the batch’s values spread one per equal slice of 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 at time , is the one used here.
A second form, and what the bound bounds. Each finite bounds the NLL of the -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 and not on ; write . A particular set of size is exactly the masked set with probability , so
The integral is a Beta function. With , integrating by parts for (the boundary terms vanish at both ends) gives ; applying it times and using ,
There are sets of size , and that count times the weight is exactly . Grouping the sets by size,
with uniform among the sets of size : mask exactly positions, uniform from 1 to , 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 of the positions uniformly, and reveal in that order, predicting position from the positions revealed before it. Before step the masked set is , of size and uniform among sets of that size, and is uniform within it; so the expected total loss of this procedure is the double sum above. For each fixed the product is a proper distribution over sequences, an autoregressive model that writes positions in the order , and so is their average . By Jensen again, being convex,
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 form and the form have the same mean, but not the same variance. With a constant loss of 1 per masked token, the form’s sample is with the number masked, binomial with trials and probability , so and
since diverges: the variance is infinite, from rare samples with a tiny and one mask weighted by . In ten runs of draws with (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 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 form, as MDLM and LLaDA do, and nll_bound evaluates with the form.
Sampling by unmasking
The ancestral sampler follows the reverse steps. Start with every position masked at (or the prompt’s positions filled and the rest masked). Split time into equal steps; at the step from to , run the denoiser once on the whole sequence, and reveal each still-masked position with probability , drawing its token from . At 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 steps: it survives steps and is revealed at step with probability
the product telescoping. So every pass reveals tokens on average, and generating tokens costs forward passes over all positions, against passes of one position each for a cached decoder. In chapter 14’s terms, a pass over positions costs about one read of the weights, so in the memory-bound regime 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 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 , 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 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 , and . Shapes are the caller’s business: SelectiveSSM passes as (D, N), as (B, T, 1, N) and as (B, T, D, 1), and broadcasting produces (B, T, D, N). a ** -1.0 is safe because , 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 , built from the output gradient at plus times the previous iteration’s ; it is added into u.grad, and times 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 to the powers at once, (T, D, N), and sums over . causal_conv adds the kernel’s -th tap times the input shifted right by ; it is , 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 and stored as the bias of dt through the inverse of softplus, for ; the rates are S4D-Real’s for , stored as a_log so that , minus the exponential of a_log, stays negative whatever training does to it; and the skip weight , which adds 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 , at initialisation and with every parameter moved off it, and checks that the state has the same size, 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 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 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 , which lie in because , so is always finite; masks each sequence at its own rate; and weights each sequence’s masked cross-entropy by , dividing by for nats per token. test_diffusion_loss_weights_each_sequence_by_one_over_t recomputes it from the model’s logits with three different , 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 form. For each window it draws samples values of stratified over (with samples equal to , each value exactly once), and masks exactly positions per row by ranking random keys: argsort of argsort gives each position’s rank, and the lowest ranks are a uniform set of size . Each row’s masked losses are weighted by , 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 .
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 down from steps to 1, calls the model once per step on the whole sequence, and reveals each masked position with probability . 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 have the joint distribution below (rows , columns ). For the pairs , and compute the log-likelihood, the pseudo-log-likelihood and the pointwise mutual information, and check ; 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 and . For : ; ; , and . For : , , : a pair that occurs less often than independence predicts, and its pseudo-likelihood is below its likelihood. For : , , .
So per sequence the pseudo-likelihood is neither an upper nor a lower bound on the likelihood. In expectation it is: the entropy is nats, the expected pseudo-NLL 1.7309 and the mutual information 0.1864, and (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 tokens after a prompt of 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 runs positions: positions, and scores, since every pass computes a full square. The cached decoder runs the prompt once and then one position per step, positions; its scores are for the causal prompt plus for one query against keys at step , 523,776 in all. The encoder does 513 times the positions and 684 times the attention work. Both ratios grow with : 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 , and , compute and by the zero-order hold and by Euler’s . Hold the input at 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 .
Answer
; the zero-order hold gives , Euler 0.1. The continuous steady state has : , . A discrete fixed point satisfies , : 0.0625 for the zero-order hold and 0.1253 for Euler, twice the true value. In general for any : 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 large step with a fast rate is where Mamba’s initial range reaches ( up to 0.1, down to ).
(d) Implement the scan as rounds of the associative combine and check it against scan.
Answer
Round , counting from 0, combines each position with the one before it; after it, position holds the composition of the steps (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 part is the state because each composition is applied to , which the part multiplies away. This version does combines; the work-efficient version (an up-sweep and a down-sweep over a tree) does in 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 numbers and an SSM state of 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: convolution numbers and 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 term of the convolution size is 0.) The transformer’s cache, with full multi-head attention, holds 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 , and steps, and why can an engine skip them?
Answer
Only the 56 masked positions are revealed; each lands on a step uniform over the 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 , so the expected number of empty passes is : 20.42 of 56 passes for , more than a third although there are as many steps as free tokens; 0.43 for ; 0.0045 for . 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 and could not be reused. test_generate_reveals_a_uniform_share_per_step checks the average of revealed per pass.
(g) A two-position text is “New York” or “Los Angeles” with probability each, and the denoiser is perfect: with both positions masked each marginal is –, and with one revealed the other is determined. Find the probability that generate with 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 (“New Angeles” or “Los York”). The two reveal steps are independent and uniform over the steps (the Mechanism’s telescoping product), so they coincide with probability , and
in one step, in two, 0.0078 in 64. The bound is the same for every (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 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 for the encoder, which was faster there, and 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_textasks 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 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_boundrequires 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 : 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 , 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 (the decoder with learned positions; the SSM needs none); the encoder and the denoiser use RoPE at lr , 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 , 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 moved every seed off it. Either change alone did less: RoPE at 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 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 , or from , 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 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, ; the SSM makes the same 63 passes and keeps 16,384 bytes, , the same after one token as after 63. The encoder’s 63 passes compute 2,079 positions, the of the Mechanism with , , 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
- Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova, “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding”, NAACL (2019). The masked-language-model objective with 15% of positions chosen and the 80/10/10 rule, motivated by the mismatch between pre-training and fine-tuning (section 3.1), and the
[CLS]token as the aggregate representation for classification. - Nils Reimers and Iryna Gurevych, “Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks”, EMNLP (2019). Why BERT’s raw pooled states are poor for cosine similarity, and siamese fine-tuning of mean-pooled BERT into sentence embeddings.
- Julian Besag, “Statistical Analysis of Non-Lattice Data”, The Statistician 24(3) (1975). The pseudo-likelihood, the product of each variable’s conditional given all the others.
- Albert Gu, Karan Goel and Christopher Ré, “Efficiently Modeling Long Sequences with Structured State Spaces”, ICLR (2022). S4: the continuous state-space model, its discretisation, and computing the time-invariant system as a convolution.
- Albert Gu and Tri Dao, “Mamba: Linear-Time Sequence Modeling with Selective State Spaces” (2023). Selection (Algorithm 2), the zero-order hold (equation 4), the gate interpretation of (Theorem 1), the S4D-Real initialisation and initialised in , and the hardware-aware scan.
- Songlin Yang, Jan Kautz and Ali Hatamizadeh, “Gated Delta Networks: Improving Mamba2 with Delta Rule”, ICLR (2025). The gated delta rule and Gated DeltaNet, the linear-attention layer of ornith’s 30 recurrent layers, and hybrids that interleave it with attention.
- Jacob Austin, Daniel D. Johnson, Jonathan Ho, Daniel Tarlow and Rianne van den Berg, “Structured Denoising Diffusion Models in Discrete State-Spaces”, NeurIPS (2021). D3PM: discrete diffusion with transition matrices, including the absorbing-state (mask) corruption and its connection to masked language models.
- Subham Sekhar Sahoo, Marianne Arriola, Yair Schiff, Aaron Gokaslan, Edgar Marroquin, Justin T Chiu, Alexander Rush and Volodymyr Kuleshov, “Simple and Effective Masked Diffusion Language Models”, NeurIPS (2024). MDLM: the continuous-time bound as a weighted average of masked-language-model losses, its independence of the noise schedule, carry-over unmasking, and the time-conditioning ablation.
- Shen Nie, Fengqi Zhu, Zebin You, Xiaolu Zhang, Jingyang Ou, Jun Hu, Jun Zhou, Yankai Lin, Ji-Rong Wen and Chongxuan Li, “Large Language Diffusion Models”, NeurIPS (2025). LLaDA, a masked diffusion model trained from scratch at 8B parameters; the -weighted loss, the lower-variance evaluation that masks exactly tokens with uniform, and low-confidence remasking.
- Jingyang Ou, Shen Nie, Kaiwen Xue, Fengqi Zhu, Jiacheng Sun, Zhenguo Li and Chongxuan Li, “Your Absorbing Discrete Diffusion Secretly Models the Conditional Distributions of Clean Data”, ICLR (2025). A denoiser without time input, caching its output when the noisy sequence has not changed, and the bound as the expected NLL of any-order autoregressive models.
- llama.cpp at commit
da89bb3:src/llama-arch.cppforllm_arch_is_recurrent,llm_arch_is_hybrid,llm_arch_is_diffusionandllm_arch_supports_rs_rollback;src/llama-memory-recurrent.cppfor the recurrent state andseq_rm;src/llama-hparams.cppfor its size;src/models/qwen35moe.cppfor ornith’s hybrid graph;examples/diffusion/forllama-diffusion-cli;tools/server/README.mdfor--embedding,--poolingand--rerank.