12.6 Matrix-State Recurrences
The selective state space models of Section 12.5 decide, token by token, what to keep and for how long, yet we have not asked how many distinct associations a fixed-size state can store and retrieve. Much of language modeling requires associative recall—binding a key to a value (rate = 0.05, or "Mira is the ship's engineer") and retrieving the value hundreds of tokens later when the key reappears. Transformers solve associative recall by keeping every past key and value in a growing KV cache and comparing the query against all of them. Can a recurrent state of fixed size store and retrieve key–value pairs too, and how does its capacity scale with state size?
Yes—when the state is a matrix updated by adding outer products and queried by matrix-vector multiplication . We have already met two instances of this structure: unnormalized linear attention (Section 10.6) and the channel-by-state matrix of Mamba (Section 12.5). Below we derive the exact retrieval-error and capacity scaling law of outer-product matrix memories, add an input-dependent scalar decay to forget stale pairs, establish state space duality between decayed matrix recurrences and causally masked linear attention, implement the hardware-efficient chunked training algorithm (chunked_linear_attention), and test whether trained GatedLinearAttention layers obey the theoretical capacity law on multi-query associative recall.
12.6.1 An Associative Memory#
12.6.1.1 Writing and Reading Pairs#
The simplest associative memory stores pairs by summing outer products. For a toy illustration in , bind orthogonal unit keys and to scalar values and in the row vector . Multiplying by either key retrieves its value without error: and . Once we add a third pair with , however, overlaps and : becomes , and querying returns instead of . Two key dimensions hold at most two orthogonal keys without cross-talk.
In general, with key vectors , value vectors , and query vectors , the state is a matrix updated and read at each step via:
Each write adds a rank-one matrix mapping the direction to , where are learned linear projections of the token representation.
12.6.1.2 Linear Attention#
Unrolling (12.6.1) from reveals that an additive matrix recurrence computes unnormalized causal linear attention (Section 10.6, Katharopoulos et al. (2020)):
Evaluated from the right, each output weights every past value by the dot-product similarity ; evaluated from the left, the sum of outer products is carried forward in the fixed-size recurrent state .
12.6.1.3 Interference#
How many pairs can store before cross-talk overwhelms the signal? Querying with a stored unit key () separates the target value from the interference of the other pairs:
Exact zero-error readout requires mutually orthogonal keys, of which admits at most . For random unit keys, we can compute the expected interference exactly.
Proposition. Let be independent and uniformly distributed on the unit sphere of , and let be unit vectors chosen independently of the keys. Then the expected squared retrieval error at every stored key is:
Proof. Expanding the squared norm of , cross terms with vanish in expectation because, conditioned on , and are independent with mean zero. Since , there remain diagonal terms . By rotational symmetry of the unit sphere in , each coordinate of has expected square , so . Summing over the interfering pairs gives .
Notice that retrieval error depends on the load ratio and not on when a pair was written: an additive memory loses pairs through crowding, not aging.
To test (12.6.3) empirically in NumPy, matrix_memory writes pairs of unit keys and codebook values into (with optional shared-direction correlation ) and returns both the mean squared retrieval error and nearest-neighbor recall over a 256-vector unit codebook:
def matrix_memory(d_k, nums, rho=0, num_values=256, trials=20, seed=0):
"""Read error and recall of S = sum_i v_i k_i^T over random unit keys."""
rng = np.random.default_rng(seed)
unit = lambda X: X / np.linalg.norm(X, axis=-1, keepdims=True)
codebook = unit(rng.standard_normal((num_values, d_k)))
errors, recalls = [], []
for n in nums:
error = recall = 0
for _ in range(trials):
K = unit(rng.standard_normal((n, d_k))) # Keys as rows
shared = unit(rng.standard_normal(d_k)) # A common direction
K = unit(np.sqrt(1 - rho**2) * K + rho * shared)
ids = rng.integers(0, num_values, n)
S = codebook[ids].T @ K # Sum of v_i k_i^T
reads = K @ S.T # Row j is S k_j
error += ((reads - codebook[ids]) ** 2).sum(1).mean() / trials
recall += ((reads @ codebook.T).argmax(1) == ids).mean() / trials
errors.append(error)
recalls.append(recall)
return errors, recallsWe evaluate matrix_memory across pair loads for independent random keys () and correlated keys (), plotting the squared read errors against the theoretical line :
nums = [8, 16, 32, 64, 128, 256, 512]
results = {f'dₖ = {d_k}': matrix_memory(d_k, nums) for d_k in (32, 64, 128)}
results['dₖ = 64, ρ = 0.5'] = matrix_memory(64, nums, rho=0.5)
predictions = [[(n - 1) / d_k for n in nums] for d_k in (32, 64, 128)]
d2l.plot(nums, [err for err, _ in results.values()] + predictions,
'stored pairs n', 'squared read error',
legend=list(results) + ['$(n-1)/d_k$'], xscale='log', yscale='log',
fmts=('-o', '-o', '-o', '-s', 'k:', 'k:', 'k:'), figsize=(5, 3.5))
print('recall at n = ', ' '.join(f'{n:4d}' for n in nums))
for name, (_, recalls) in results.items():
print(f'{name:17s}', ' '.join(f'{r:4.2f}' for r in recalls))recall at n = 8 16 32 64 128 256 512
dₖ = 32 1.00 0.99 0.96 0.74 0.39 0.16 0.07
dₖ = 64 1.00 1.00 1.00 1.00 0.96 0.72 0.37
dₖ = 128 1.00 1.00 1.00 1.00 1.00 1.00 0.94
dₖ = 64, ρ = 0.5 1.00 0.99 0.83 0.49 0.21 0.07 0.03
Two properties jump out from the plot and table:
- Recall scales with the total state entries : The squared error curves lie directly on . Yet at , where the total squared error is (as large as the unit signal ), nearest-neighbor recall is still ( at ). Why? Because the interference vector is spread isotropically across all value dimensions, so its projection onto any single candidate codebook vector has variance . With , doubling quadruples the state entries and quadruples the number of pairs recalled at a fixed accuracy ( at for and at for ; at for ; Exercise 5 varies and independently).
- Key correlation creates an irreducible error floor: When keys share a direction with weight , pairwise key overlap averages , yielding expected squared error:
for zero-mean values (plus a quadratic term in from the finite-codebook sample mean; see Exercise 4). Because does not shrink with , correlated keys () cut recall at from to .
12.6.2 Decay#
12.6.2.1 Forgetting Old Pairs#
Without decay, every pair ever written remains in with full weight, so interference grows unboundedly with sequence length. Multiplying the state by a scalar decay before each write fades older pairs:
At a constant decay , a pair written steps ago carries weight . The weights sum to (an effective window of pairs), while the squared weights entering the interference variance sum to , bounding steady-state expected interference by regardless of total sequence length (Exercise 6). Computing from the input token lets each head hold its state across a span and flush it at topic or clause boundaries. (Related variants use fixed per-head decays in RetNet (Sun et al., 2023), input-dependent scalar decays per head in Mamba-2 (Dao and Gu, 2024), or per-key-coordinate vector decays in Gated Linear Attention (Yang et al., 2024); we use one input-dependent scalar decay per head.)
12.6.2.2 Selective State Space Models as Matrix Memories#
Stacking the channel states of Mamba's selective SSM (Section 12.5, omitting the skip connection ) as rows of a matrix reveals that Mamba is already a decayed matrix-state recurrence:
Matching terms against (12.6.4), the value vector is , the key vector is , and the query vector is . The only difference is that Mamba's decay matrix varies across both channels and states; restricting to a single scalar per head yields Mamba-2 (Dao and Gu, 2024) (Exercise 1) and unlocks the matrix-multiplication dual form below.
12.6.3 The Dual Form#
12.6.3.1 Unrolling with Decay#
Unrolling (12.6.4) from shows that a pair written at step arrives at step attenuated by the cumulative decay product :
Stacking as rows of and setting for yields the dual form:
Equation (12.6.6) is causal linear attention with a learned, input-dependent decay mask —a correspondence Dao and Gu (2024) term state space duality (SSD). Evaluating (12.6.6) as a step-by-step recurrence takes work and memory; evaluating it via the full matrix runs in parallel matrix multiplications at work and memory. Let us write both forms explicitly, starting with the sequential step-by-step recurrence linear_attention_recurrent:
def linear_attention_recurrent(Q, K, V, a):
"""y_t = S_t q_t with S_t = a_t S_{t-1} + v_t k_t^T, step by step."""
S, outputs = Q.new_zeros(V.shape[-1], K.shape[-1]), []
for q, k, v, a_t in zip(Q, K, V, a):
S = a_t * S + torch.outer(v, k)
outputs.append(S @ q)
return torch.stack(outputs)Next, decay_mask(log_a) forms the lower-triangular decay matrix via cumulative sums so linear_attention_dual can evaluate across all positions at once:
def decay_mask(log_a):
"""L[t, s] = a_{s+1} * ... * a_t for s <= t, and 0 for s > t."""
cum = log_a.cumsum(-1)
log_L = cum[..., :, None] - cum[..., None, :] # Sum of log a over (s, t]
causal = torch.ones(log_L.shape[-2:], dtype=torch.bool,
device=log_a.device).tril()
return torch.exp(log_L.masked_fill(~causal, -torch.inf))
def linear_attention_dual(Q, K, V, a):
"""The same outputs as Y = (L * Q K^T) V, all positions at once."""
return (decay_mask(torch.log(a)) * (Q @ K.T)) @ V12.6.3.2 Chunked Computation#
Neither pure form is ideal for GPU training: the token-level recurrence runs tiny sequential steps, while the full dual form materializes a matrix per head. Chunking gets the best of both worlds by partitioning the sequence into chunks of length (Figure 12.6.1). Because any cross-chunk decay factors into (key decay to the end of its chunk) (intermediate chunk decays) (query decay from the start of its chunk), every off-diagonal block of has rank —and every off-diagonal block of has rank at most , summarized completely by the state matrix carried across chunk boundaries (Exercise 2).
The mask of (12.6.6) for random decays, partitioned into chunks. Diagonal blocks (outlined in blue) are small masked-attention products computed in parallel. Every block below the diagonal (outlined in orange) has rank one in and rank at most in , and is accounted for by the state passed from chunk to chunk (arrows); the shading fades as the decays compound.
Indexing positions within each chunk from to , chunked_linear_attention proceeds in three batched steps:
- Within chunks (diagonal blocks): Evaluate the dual form (12.6.6) inside each length- chunk in parallel using its decay mask.
- Across chunks (chunk-boundary states): Let be the total decay of chunk . The state at the end of chunk satisfies the chunk-level linear recurrence
which d2l.linear_scan evaluates across all chunks in rounds.
3. Past-state readout (off-diagonal blocks): Add to each position in chunk .
Almost all FLOPs are now dense matrix multiplications, and peak working memory drops from to .
def chunked_linear_attention(Q, K, V, log_a, chunk_size):
"""y_t = S_t q_t with S_t = a_t S_{t-1} + v_t k_t^T, computed in chunks.
Q, K: (batch_size, T, d_k); V: (batch_size, T, d_v); log_a: (batch_size, T)
"""
B, T, m = Q.shape[0], Q.shape[1], chunk_size
Q, K, V = (X.reshape(B, T // m, m, -1) for X in (Q, K, V))
log_a = log_a.reshape(B, T // m, m)
# 1. Within chunks: the dual form, one m x m mask per chunk
Y = (decay_mask(log_a) * (Q @ K.mT)) @ V
# 2. Across chunks: S^(c) = gamma^(c) S^(c-1) + sum_t L_mt v_t k_t^T
cum = log_a.cumsum(-1).unsqueeze(-1) # Log decay from the chunk's start
writes = V.mT @ (K * torch.exp(cum[:, :, -1:] - cum))
S = d2l.linear_scan(torch.exp(cum[:, :, -1:]), writes) # At chunk ends
S = torch.cat([torch.zeros_like(S[:, :1]), S[:, :-1]], 1) # At the starts
# 3. Every step reads the state at its chunk's start, decayed to it
return (Y + (Q * torch.exp(cum)) @ S.mT).reshape(B, T, -1)Let us check that the sequential recurrence, the full dual form, and the chunked algorithm across chunk sizes agree to float32 precision on a sequence of length .
gen = torch.Generator().manual_seed(0) # Local: later training stays unseeded
T, d_k, d_v = 512, 64, 64
Q, K, V = (torch.randn(T, d, generator=gen) for d in (d_k, d_k, d_v))
a = 0.8 + 0.19 * torch.rand(T, generator=gen) # Decays in (0.8, 0.99)
Y = linear_attention_recurrent(Q, K, V, a)
forms = {'dual form': linear_attention_dual(Q, K, V, a)}
for m in (16, 64, 256):
forms[f'chunks of {m}'] = chunked_linear_attention(
Q[None], K[None], V[None], torch.log(a)[None], m)[0]
for name, Y_form in forms.items():
print(f'{name:13s} relative deviation from the recurrence: '
f'{(Y_form - Y).abs().max() / Y.abs().max():.1e}')dual form relative deviation from the recurrence: 1.5e-06
chunks of 16 relative deviation from the recurrence: 2.2e-07
chunks of 64 relative deviation from the recurrence: 2.5e-07
chunks of 256 relative deviation from the recurrence: 8.8e-07
All forms agree to relative error (Exercise 3 analyzes the optimal chunk size ).
12.6.4 A Gated Linear Attention Layer#
12.6.4.1 The Layer#
GatedLinearAttention wraps multi-head chunked linear attention into a sequence mixer. For each head , it computes an input-dependent scalar decay , with biases initialized via init_decays so initial timescales () span steps log-uniformly across heads.
class GatedLinearAttention(nn.Module):
"""Multi-head linear attention with one input-dependent decay per head."""
def __init__(self, num_hiddens, num_heads, chunk_size=16, conv_width=4,
timescales=(4, 256)):
super().__init__()
d = num_hiddens
self.num_heads, self.chunk_size = num_heads, chunk_size
self.W_qkv = nn.Linear(d, 3 * d, bias=False)
self.conv = nn.Conv1d(3 * d, 3 * d, conv_width, groups=3 * d,
padding=conv_width - 1) # One filter per channel
self.W_a = nn.Linear(d, num_heads) # Decay gate, one per head
self.W_g = nn.Linear(d, d) # Output gate
self.W_o = nn.Linear(d, d, bias=False)
d2l.init_lecun(self)
self.init_decays(*timescales) # Memories of 4 to 256 steps by default
def init_decays(self, tau_min, tau_max):
"""Start the decays at exp(-1/tau), tau log-uniform in range."""
b = self.W_a.bias
tau = torch.logspace(math.log10(tau_min), math.log10(tau_max), len(b))
with torch.no_grad(): # log sigmoid(b) = -1 / tau
b.copy_(-torch.log(torch.expm1(1 / tau)))We isolate the memory update in a memory method so Section 12.7 can subclass GatedLinearAttention and swap in the delta rule without duplicating the rest of the block. heads_to_batch and batch_to_heads fold and unfold the head axis into the batch axis.
def heads_to_batch(Z, num_heads):
"""(batch_size, T, num_heads * e) -> (batch_size * num_heads, T, e)."""
B, T, _ = Z.shape
return Z.reshape(B, T, num_heads, -1).transpose(1, 2).flatten(0, 1)
def batch_to_heads(Y, batch_size):
"""(batch_size * num_heads, T, e) -> (batch_size, T, num_heads * e)."""
_, T, e = Y.shape
return Y.reshape(batch_size, -1, T, e).transpose(1, 2).flatten(2)
@d2l.add_to_class(GatedLinearAttention)
def decays(self, X):
"""Log decays, (batch_size * num_heads, T)."""
return heads_to_batch(F.logsigmoid(self.W_a(X)), self.num_heads)[..., 0]
@d2l.add_to_class(GatedLinearAttention)
def memory(self, X, Q, K, V, log_a):
"""Outputs of the decayed matrix memory of every head. X is unused here;
the delta rule of the next section reads its write strengths from it."""
return chunked_linear_attention(Q, K, V, log_a, self.chunk_size)In the forward pass (Figure 12.6.2):
- A width-4 depthwise causal convolution and SiLU mix adjacent tokens into so a value token at position can bind directly to the key token at position inside a single layer (Section 12.8 ablates this convolution).
- Queries and keys are -normalized to unit length (matching the setting of (12.6.3)).
- Each head's readout is RMS-normalized, gated by , and projected back to width (Yang et al., 2024).
The gated linear attention layer. One projection and a short causal convolution give the queries, keys, and values of every head, and a second projection gives each head its decay . The matrix memory is computed in chunks. Its readout is RMS-normalized per head, multiplied by a gate computed from the input, and projected back to width .
@d2l.add_to_class(GatedLinearAttention)
def forward(self, X): # X: (batch_size, num_steps, num_hiddens)
B, T = X.shape[:2]
QKV = self.conv(self.W_qkv(X).mT)[..., :T].mT # Causal: drop the tail
Q, K, V = (heads_to_batch(Z, self.num_heads)
for Z in F.silu(QKV).chunk(3, -1))
Q, K = F.normalize(Q, dim=-1), F.normalize(K, dim=-1) # Unit length
Y = self.memory(X, Q, K, V, self.decays(X)) # (B * num_heads, T, d / h)
Y = F.rms_norm(Y, Y.shape[-1:], eps=1e-6) # Unit RMS per head
return self.W_o(batch_to_heads(Y, B) * F.silu(self.W_g(X)))12.6.4.2 Associative Recall#
Does a trained neural network populate its matrix state according to the capacity law derived for random keys? We test this using the synthetic multi-query associative recall benchmark (Arora et al., 2024). Each sequence presents key–value pairs (a distinct key token followed by a value token drawn from 4 classes), optional filler tokens, and finally all keys again in random order as queries. (The options num_rebound and gap overwrite a subset of keys with a new value and are used in Section 12.7.)
def associative_recall(rng, batch_size, num_pairs, num_keys=512,
num_values=4, num_steps=256, num_rebound=0, gap=None):
"""Key-value pairs, filler, then every key again as a query. The first
num_rebound keys are written twice, the second time with a new value,
at any later write or, given gap, gap writes after the first one.
Returns the tokens (values, then keys, then the filler), the latest
value of each query's key, and a mask of the queries for rebound keys."""
n, r = num_pairs, num_rebound
keys = np.argsort(rng.random((batch_size, num_keys)), 1)[:, :n]
values = rng.integers(0, num_values, (batch_size, n + r))
values[:, n:] = (values[:, :r] + rng.integers( # A new value
1, num_values, (batch_size, r))) % num_values
if gap is None: # Random write order, each second write after the first
slots = np.argsort(rng.random((batch_size, n + r)), 1)
slots[:, :r], slots[:, n:] = (np.minimum(slots[:, :r], slots[:, n:]),
np.maximum(slots[:, :r], slots[:, n:]))
else: # First writes in random order, second ones gap first writes later
first = np.argsort(rng.random((batch_size, n)), 1)
times = np.concatenate([first, first[:, :r] + gap - 0.5], 1)
slots = np.argsort(np.argsort(times, 1), 1)
X = np.full((batch_size, num_steps), num_values + num_keys) # Filler
rows = np.arange(batch_size)[:, None]
X[rows, 2 * slots] = num_values + np.concatenate([keys, keys[:, :r]], 1)
X[rows, 2 * slots + 1] = values
order = np.argsort(rng.random((batch_size, n)), 1) # Queries
X[:, -n:] = num_values + np.take_along_axis(keys, order, 1)
latest = np.concatenate([values[:, n:], values[:, r:n]], 1)
return X, np.take_along_axis(latest, order, 1), order < rLet us inspect one short sequence with 4 pairs and 1 rebound key (tokens 0..3 are values, 4..515 are keys, and 516 is filler):
X, Y, rebound = associative_recall(np.random.default_rng(0), 1, 4,
num_steps=16, num_rebound=1)
print('tokens: ', X[0])
print('answers:', Y[0], ' written twice:', rebound[0])tokens: [273 3 15 3 200 2 407 0 273 0 516 516 200 407 273 15]
answers: [2 0 0 3] written twice: [False False True False]
We save the training harness train_recall, which trains a model for 2,000 steps of AdamW (peak learning rate with cosine warmup) cycling through pair loads and evaluates recall at each load on 1,024 fresh sequences.
def train_recall(model, pairs=(4, 8, 16, 32, 64), num_updates=2000,
**task):
"""Train on associative recall (task: options of associative_recall)
with a cycling number of pairs, 256 sequences per update, AdamW at peak
rate 0.01; return the accuracy per number of pairs."""
rng = np.random.default_rng()
length = lambda n: 32 * math.ceil(
(3 * n + 2 * task.get('num_rebound', 0)) / 32)
data = lambda n, size: associative_recall(
rng, size, n, num_steps=length(n), **task)[:2]
model.to(d2l.try_gpu())
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-2,
weight_decay=0.01)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda t: (
d2l.cosine_warmup(t, num_updates, num_updates // 10)))
d2l.train_queries(model, lambda step: data(pairs[step % len(pairs)],
256), num_updates, optimizer, scheduler)
return {n: float(d2l.query_accuracy(model, *data(n, 1024)))
for n in pairs}To vary matrix-state capacity without changing model width or parameter count, we fix a two-block SeqLM at width in memory_model(num_heads) and partition the width into heads of dimension :
def memory_model(num_heads, num_hiddens=32, vocab_size=4 + 128 + 1):
"""Two blocks of gated linear attention; tokens: values, keys, filler."""
return d2l.SeqLM(vocab_size, num_hiddens, [GatedLinearAttention(
num_hiddens, num_heads, timescales=(256, 2048)) for _ in range(2)])Because each head maintains an state matrix, total state entries per layer scale as while total parameters stay nearly identical (about ). We train two runs of each head configuration with train_recall:
recall = {}
for num_heads in (8, 4, 2):
d_h = 32 // num_heads
name = f'{num_heads} heads of {d_h}, {num_heads * d_h ** 2} entries'
models = [memory_model(num_heads) for _ in range(2)]
recall[name] = [train_recall(model, num_keys=128) for model in models]
print(f'{name:26s} {d2l.num_params(models[0]):,} parameters')8 heads of 4, 128 entries 37,461 parameters
4 heads of 8, 256 entries 37,197 parameters
2 heads of 16, 512 entries 37,065 parameters
Plotting and tabulating the mean recall accuracy against the number of pairs shows how retrieval capacity scales with total state entries:
pairs = list(recall[name][0])
d2l.plot(pairs, [[np.mean([run[n] for run in runs]) for n in pairs]
for runs in recall.values()], 'pairs in the sequence',
'recall, mean of two runs', legend=list(recall), xscale='log',
ylim=(0.2, 1.02), fmts=('-o', '-s', '-^'), figsize=(4.5, 3))
d2l.plt.xticks(pairs, pairs) # Ticks at the numbers of pairs
print(f'{"pairs":26s}', ''.join(f'{n:>11d}' for n in pairs))
for name, runs in recall.items():
print(f'{name:26s}', ''.join(f'{runs[0][n]:6.2f}/{runs[1][n]:.2f}'
for n in pairs))pairs 4 8 16 32 64
8 heads of 4, 128 entries 0.99/0.99 0.95/0.95 0.84/0.84 0.67/0.66 0.53/0.51
4 heads of 8, 256 entries 1.00/1.00 0.99/0.99 0.95/0.96 0.87/0.88 0.72/0.73
2 heads of 16, 512 entries 1.00/1.00 1.00/1.00 1.00/0.99 1.00/0.96 0.99/0.91
All three configurations solve 4 pairs (), and as the pair load grows, recall scales directly with state entries: doubling state capacity from 128 entries () to 256 entries () roughly doubles the number of pairs recalled at a given accuracy (from to at 64 pairs), and 512 entries () outperforms 128 entries across all loads .
One structural flaw remains in every additive matrix memory: writing simply adds to whatever value is already stored under . If a key is bound a second time to a new value, querying that key returns a superposition of old and new values. Teaching the memory to overwrite a key's value is the subject of Section 12.7.
12.6.5 Summary#
A matrix-valued state stores key–value pairs via outer-product writes and retrieves them via linear queries . Unrolled, this recurrence is causal linear attention—and Mamba's selective SSM is an instance with key and query . Under random unit keys, pairwise cross-talk produces an expected squared retrieval error of after writes, while nearest-neighbor recall capacity scales with the total state entries . Adding an input-dependent scalar decay per head fades old pairs and yields state space duality with causally masked linear attention . Evaluating this dual form in chunks combines parallel intra-chunk matrix multiplications with an inter-chunk scan in memory. On multi-query associative recall at fixed parameter count, doubling a GatedLinearAttention layer's state entries roughly doubles the number of pairs it can recall, though purely additive writes still cannot overwrite a previously bound key.
12.6.6 Exercises#
-
Mamba as a matrix memory. In the form with , the logarithm of the decay is the matrix of rates with row scaled by the step size .
- Under which conditions on and on the rates is a scalar multiple of the matrix of ones, so that the update has the form (12.6.4)? Which of these conditions does Mamba-2 impose, and what does it keep input-dependent?
- For each form of decay in this section (RetNet, Mamba-2, gated linear attention, Mamba), count the input-dependent numbers per token that determine the decay of one head of entries.
-
Rank-one blocks. Let be the products of the decays in (12.6.6).
- Express through the , and show that every submatrix of whose row indices are all at least as large as its column indices has rank one.
- Deduce that every block of that couples a chunk to an earlier chunk
has rank at most . Identify where
chunked_linear_attentionapplies the query-side and the key-side decays of such a block. - With a decay per key coordinate, , no single mask multiplies . Write the decayed score of query and key , and show that a block coupling two chunks still has rank at most .
-
Counting operations. Count one multiply-add as two floating-point operations, set , and keep the leading terms.
- Count the operations of the recurrence, the dual form, and the chunked form at length and chunk size . Split the chunked count into the three parts of the algorithm.
- Show that the chunked form costs at most a small constant times the recurrence while , and compute the ratio of chunked to dual operations at , , and .
- Model the run time of a schedule as its operations divided by a throughput , plus a fixed time per sequential step: steps for the recurrence and for the chunked form. Find the chunk size that minimizes the chunked time, and evaluate it for , , operations per second, and . How much faster than the recurrence does the model predict the chunked form to be?
-
Correlated keys. ● The keys with in
matrix_memoryare normalized versions of , with independent random unit vectors and one shared unit vector . The formula in the text models the overlap of two distinct keys as , with independent of mean zero and variance , and assumes values of mean zero.- The values of
matrix_memorycome from a codebook of 256 random vectors, whose mean is not exactly zero. Show that this adds a term proportional to to the expected squared error, and compare your complete prediction with the measured errors. - Center the codebook (subtract its mean, then normalize each entry again) and check that the upward bend of the curve disappears.
- Measure the error and the recall for at and . For which does the wider key still help, and where does the error approach ?
- The values of
-
[code] Keys and values of different widths. ● Give
matrix_memorya value widthd_vof its own, so that the codebook holds 256 random unit vectors in .- Keep and measure recall for , , and . Does recall depend on the product alone?
- Show that the expected squared read error does not depend on , so that it cannot explain what you measured.
- Every codebook entry is stored under about of the keys. Show that their overlaps with the read key add a component of variance about along that entry, and use it to explain for which shapes the product law fails.
-
[code] Decay as a sliding window. ● Add a constant decay to
matrix_memory, so that the pair written steps before the end enters the final memory with weight .- At and , measure recall separately for the oldest and the newest quarter of the pairs, for . What does the decay give the newest pairs, and what does it cost the oldest?
- Following the proof of the proposition, show that the expected squared interference at any key is at most . Show that the number of pairs whose squared signal exceeds this bound is at most about , whatever is.