Attention-SSM duality and hybrid architectures
Derive structured state-space duality, chunkwise computation, delta-rule memory updates, and the quality and memory trade-offs of hybrid stacks.
After this lesson you can
- Express a scalar-transition state-space recurrence as a structured causal matrix.
- Prove the low-rank bound for blocks separated below the diagonal.
- Compare recurrent, quadratic, and chunkwise computations.
- Derive the delta rule as a retrieval-error gradient step.
- Measure and interpret small hybrid-model experiments.
Before you start
- 18Selective state space modelLinear attentionRecurrent form of linear attentionLinear recurrence as an associative scanAssociative recallSliding window attentionKV cache memoryGated linear recurrences
- 02Block matricesFast structured matricesRank
- 06Stochastic gradient descentGradient descent dynamics on quadratics
Two ways to mix a sequence
Attention and an SSM appear to be different operations: one builds relationships between positions and the other updates state. If coefficients produced by an input are fixed, both can be viewed as a matrix mixing values over time. State-space duality studies when that structured matrix admits both recurrent representation and masked linear-attention form. It does not claim Mamba and softmax attention are identical models.
In this lesson state , input and output are scalar per position, , and transition is a scalar shared among the components:
Parameters may depend on input, but while expanding one particular sequence we treat them as fixed. This does not make the full model linear as a function of input: changing input can also change . For , expanding the recurrence gives
The empty product is one, so . Matrix in the causal triangle lets us write . This is a semiseparable attention matrix: lower-part structure allows large blocks separated from the diagonal to be summarized at low rank.
The distinction between fixed and data-dependent coefficients is essential. Changing only vector while holding fixed changes output linearly through multiplication by . In a real selective layer, the same data usually generate those coefficients; changing input changes the mixing matrix too. Thus describes one conditioned run. It also does not by itself show residual contribution, output gate, or projections surrounding the sequence operation.
Scalar transition is a useful restriction. With a general transition matrix , the contribution from to is ; a semiseparable representation may still exist, but one scalar can no longer be factored out and multiplied by . SSD’s specific form uses this structure to share one mask across head dimensions and arrange work as matrix products. Comparing models also requires examining the parameter choice producing those matrices.
The SSD matrix can contain negative entries and rows need not sum to one. Causal softmax turns scores into nonnegative row weights summing to one; that normalization is absent from the preceding equation. Features and resemble keys and queries in structured linear attention, but the analogy does not automatically turn one into the other. In multi-channel or multi-head SSMs, additional dimensions and input/output projections matter too.
In the figure blue and orange distinguish SSD contribution signs; a nearly transparent cell is near zero. Control indices start at zero; transition zero multiplies zero initial state, so changing it does not affect this matrix. Softmax uses the same two feature products for scores and zeros future entries before row normalization. Changing another transition affects SSD paths crossing it, but not scores in that reference softmax. The comparison shows two specific operators over the same positions, not identical outputs from both.
Why low rank appears
Choose a cut and a block whose rows satisfy and columns . Column ‘s contribution crosses the cut and then reaches row . The product separates without division by any transition:
Both factors have dimension , so the block factors into a row matrix times a column matrix and has rank at most . The identity remains valid if any transition is zero; ratios of cumulative products would be dangerous then. The complete block, including elements near or on the diagonal, need not have rank .
Proof
The property is also a communication bottleneck: everything before the cut reaches the future through the -component state. Instead of storing each previous contribution separately for each later position, the algorithm can summarize them in that state. Quadratic form reveals position pairs; recurrent form reveals updates. SSD duality relates both calculations for the stated operator family and assumptions.
A low-rank block does not mean all its entries are equal. A sum of outer products can represent different combinations in each row and column; the restriction is only independent communication directions across the cut. Zero transitions can cause part of history to stop influencing the future and reduce observed rank. Linearly dependent input or output features can also reduce it. The bound says “at most”, not that a model necessarily uses its entire state dimension.
Blocks: pairs within, state between
Divide a sequence into contiguous blocks of size . For each block, build the triangular portion of its local matrix and apply it to its inputs. That accounts for within-block input contributions. The block’s incoming state summarizes everything earlier; internal positions read that state multiplied by transitions from block start. Finally, the block produces an outgoing state propagated to the next.
This chunkwise form combines matrix multiplication within each block with a recurrent summary between blocks. An efficient implementation can compute block summaries and prefixes with further parallelization techniques. The educational cell uses cumulative products and explicit matrices, not Mamba-2’s optimized kernel. As grows, internal pairs increase roughly as ; when it shrinks there are more boundaries and less matrix work per block. Exact cost depends on , value dimension, implementation, and temporary memory.
For and , each block contains ten causal pairs, twenty total. For , there are 36 pairs in one block; for , eight pairs and eight update boundaries. A block’s incoming state is not reset to zero: doing so would remove earlier contributions and change the result. The figure exposes that value and the cell checks every output, not only the last.
When constructing a block, an internal input’s contribution to a later output uses only transitions inside that block. An earlier block’s contribution travels in boundary state and is multiplied by transitions through the chosen output. Outgoing state combines incoming state propagated through the entire block and internal writes propagated to its end. These three pieces avoid double-counting inputs. Testing a zero transition helps detect implementations dividing by cumulative products.
On an accelerator, a small block reduces the local quadratic matrix but may yield operations too small to use matrix units well. A large one favors some dense multiplications while increasing temporary storage and within-block work. The useful point depends on GPU architecture, precision, and internal dimensions. The figure’s pair count describes only causal-matrix shape; it excludes projections, mode summation, memory access, and boundary-state computation.
import numpy as np
rng=np.random.default_rng(20)
T,N=12,3
a=rng.uniform(.4,.95,T);B=rng.normal(size=(T,N));C=rng.normal(size=(T,N));x=rng.normal(size=T)
a[5]=0. # Prueba una transición que corta la propagación sin dividir por ella.
def recurrent(a,B,C,x):
h=np.zeros(B.shape[1]);ys=[]
for t in range(len(x)):
h=a[t]*h+B[t]*x[t];ys.append(C[t]@h)
return np.array(ys)
def matrix(a,B,C):
t=len(a);m=np.zeros((t,t))
for i in range(t):
for j in range(i+1):m[i,j]=(C[i]@B[j])*np.prod(a[j+1:i+1])
return m
def chunked(a,B,C,x,size):
h=np.zeros(B.shape[1]);ys=[]
for lo in range(0,len(x),size):
hi=min(lo+size,len(x)); ac=a[lo:hi];bc=B[lo:hi];cc=C[lo:hi];xc=x[lo:hi]
local=matrix(ac,bc,cc)@xc
carry=np.cumprod(ac)*(cc@h)
ys.extend(local+carry)
suffix=np.r_[np.cumprod(ac[:0:-1])[::-1],1.]
h=np.prod(ac)*h+np.sum(suffix[:,None]*bc*xc[:,None],axis=0)
return np.array(ys)
y=recurrent(a,B,C,x);M=matrix(a,B,C)
for size in (1,3,5,12):
err=np.max(abs(y-chunked(a,B,C,x,size)));print('bloque',size,'error',err);assert err<1e-12
print('error matricial',np.max(abs(y-M@x)),'rango subbloque',np.linalg.matrix_rank(M[6:12,0:6]))
assert np.allclose(y,M@x) and np.linalg.matrix_rank(M[6:12,0:6])<=N
# Sobrescribir una clave y consultar otra no ortogonal.
k1=np.array([1.,0.]);k2=np.array([.6,.8]);pairs=[(k1,1.),(k2,-1.),(k1,.5)]
add=np.zeros(2);delta=np.zeros(2)
for k,v in pairs:
add+=v*k;delta+=(v-delta@k)*k
print('aditiva consultas',add@k1,add@k2,'delta consultas',delta@k1,delta@k2)
assert np.isclose(delta@k1,.5) and not np.isclose(delta@k2,-1.)The comparison tests length 12 with blocks of 1, 3, 5, and 12; the final size-5 block is incomplete. In this run maximum errors are below . Matrix form is not scalable for long sequences: it materializes entries. Recurrent form uses fixed state and blocked form keeps a local matrix per block rather than the whole matrix. Rounding differences may arise when product and sum order changes.
Writing by correcting error
In additive linear attention a matrix memory accumulates outer products . Writing the same key again with another value adds a second association rather than replacing the first. The delta rule uses retrieval error for the current key:
For pair loss , gradient is . The preceding update is a descent step at rate . If and , the readout at that same key after updating is exactly . If the key is not unit norm, the relevant factor is ; too large a rate can overcorrect. That one-key guarantee does not protect other correlated keys.
The update affects one direction in key space. For query vector , readout change is . If is orthogonal to , that isolated update does not change its readout; if similar to , it changes proportionally to their inner product. This expression explains interference without analogy: corrected writing and another key’s readout share matrix parameters. Repeated writes in different directions can modify previously stored associations.
For the current pair, residual after one step is multiplied by . A positive rate below decreases its magnitude in that isolated step; a larger rate can increase it. This does not guarantee convergence for an arbitrary sequence of changing pairs or a complete network with learned parameters. Normalizing keys helps control scale, but gate choice and stability evaluation remain experimental decisions.
Proof
With orthogonal keys, correction in one direction does not alter the other’s readout. At a small angle they share direction and correction can modify both. Identical keys cannot simultaneously retain two distinct values for the same query. The NumPy example uses keys with product 0.6: after writing three pairs, the delta rule exactly retrieves 0.5 for the first and −0.724 for the second, whose prior target was −1. This is a visible geometric limitation, not a test failure.
DeltaNet studies parallelizing this family for training; Gated DeltaNet combines the rule with decay gates. Their architectures and kernels contain more than this two-dimensional memory. A lower error on the last pair alone does not establish better retrieval by a trained model on every dataset.
Hybrid layers and budgets
A hybrid architecture interleaves mechanisms with different costs and memories. Griffin mixes recurrences with local attention; Jamba interleaves Mamba, attention, and experts; Nemotron-H explores another hybrid family. Number and position of each layer type are architecture and training decisions, not a universal “one layer is enough” rule.
In a published Jamba ablation, authors compare attention/Mamba ratios 1:3 and 1:7 in 1.3-billion-parameter models trained on 250 billion tokens and observe similar results on that table’s evaluations. They chose 1:7 for larger experiments due to compute cost in that setting. This is evidence about those configurations, not proof of optimal ratio for every size or task. Nemotron-H describes four attention layers among 52 in its 8B model, for example; counting includes other layer types, so percentages require checking that convention.
Local attention offers another trade-off. If keys before the window are discarded, that layer’s KV memory is bounded by window size. An old input may still affect the current representation through other layers or recurrent states; this is not direct access to all positions. A distant-association task may respond differently from one with local patterns. Evaluation design should specify distances, key count, and how queries are generated.
A full-attention layer retains keys and values for the entire context during generation. A local layer needs only its specified window if its implementation discards earlier entries; an SSM layer retains fixed state per sequence plus convolution history. MLP or MoE layers do not themselves need sequence cache in this accounting model. Weights, router, activations, fragmentation, and other temporaries do consume memory, though the figure excludes them.
To compare stacks, fix dimensions and precision. With 32 attention layers, , eight KV heads of dimension 128, and BF16, KV cache occupies 4096 MiB per sequence. Four such attention layers need 512 MiB; 28 SSM states of in FP32 add 2.625 MiB, before convolution buffers and other objects. Different state sizes do not imply equal model quality, weight size, or speed.
The recall-throughput trade-off requires measuring both. Compressed state can process long sequences with fixed persistent memory but can interfere when retaining many associations; attention cache grows and permits querying earlier positions. Based and Zoology use associative-recall tests to study that trade-off under their configurations. Higher accuracy on one task does not guarantee higher throughput or generalize to all data.
In a recall test, distinguish written pair count from subsequent query count. One query can be solved by a shortcut that does not retain every association; multiple queries and unique keys reveal another part of the problem. Letting a model see the previous correct answer during a series of queries simplifies evaluation but provides additional context. Free-generation measurement and varying length outside the trained range would be additional experiments, not implicit results of the included cell.
Generation throughput needs a concrete protocol: prefix length, batch size, new-token count, sampling policy, and what preparation is excluded from timing. In prefill the sequence is already available and parallelism differs. An architecture with less persistent state may be slower with unfused operators or have different prefill cost from generation. A theoretical memory figure budgets components; it does not replace end-to-end measurements on intended hardware and load.
Choosing an attention layer’s position also raises hypotheses. Placing it early or late changes representations it receives and how much recurrent processing occurs before or after. Two stacks with equal ratios may differ in quality, cache size, and per-layer time; isolating effects requires controlled parameters, data, optimizer, and budget. The calculator shows per-layer count and a proxy for keys explored, not actual latency or a unitless combination of attention and SSM operations.
Local lab: three small stacks
The cell trains three four-layer models from scratch: four SSMs, three SSMs plus one full-attention layer, and four mini-Llama-style blocks. Models have equal width and batch but not exactly equal parameter counts; all three are printed. First it trains character language modeling and measures a fixed validation batch, incremental generation after 32- and 128-token prefixes, and additional peak memory. Each layer uses its own cache and incremental output is checked against full-sequence computation.
Then new models are initialized and trained on a synthetic recall task: four or eight key-value pairs with unique keys, followed by four queries. The target is evaluated at each query; previous answers are supplied correctly as inputs. Validation pairs and queries use different seeds. Values have 16 possibilities, so uniform guessing among them scores 6.25%. That baseline assumes knowing the value set; the initial classifier can also choose other tokens.
Use lesson 12’s Tiny Shakespeare corpus and gpt_pytorch.py and mini_llama_classes.py classes from lessons 12 and 13. From lesson 19’s local cell save PyTorch imports and scan_seq, scan_chunks, and Selective definitions in mamba_core.py. Paths can be set with ORYON_CORPUS, ORYON_GPT_TORCH_CODE, ORYON_MINI_CODE, and ORYON_MAMBA_CODE. CUDA is required; ORYON_STEPS and ORYON_RECALL_STEPS set updates, default 20 and 100. It generates hybrid-results.json in the working directory.
Scan and generation use PyTorch operations and Python loops, not the papers’ fused kernels. GPU may be shared and timing of 16 tokens is noisy; peak is measured above allocations existing before each prefix. This trial cannot determine which architecture is faster in production. Repeating seeds, increasing training, and measuring longer sequences are needed before interpreting quality or speed differences.
In an RTX 3060 run with the first 12000 Tiny Shakespeare characters, 100 language steps and 300 recall steps, SSM, hybrid, and attention models had 196160, 198368, and 204992 language parameters. Their one-batch validation losses were 2.838, 2.900, and 2.979. For four pairs they got 31.35%, 32.13%, and 29.88% of 1024 queries correct; for eight pairs, 23.05%, 23.14%, and 22.85%. The figure shows those rounded values. These are small models and tasks with one seed and correct prior answers; differences do not establish a general ranking. Corpus is split before windows and newlines normalized; the 12000 characters have UTF-8 SHA-256 13755a378ca83b6707b89967339b999e457d2c4a8f86c889c4431d97de31cddb.
For the 128-token prefix in that run, additional peaks were 0.106, 0.207, and 0.570 MiB, and rates for the following 16 tokens were 151, 65, and 31 tokens per second in the same order. These are measured values for these implementations under shared load: a one-step check repeat produced very different rates. Peaks include temporaries as well as persistent state and do not directly equal the 24-layer figure’s estimates. All three models checked incremental output against the full sequence with maximum error below .
import json, math, os, time
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
def load_code(env,default):
scope={};exec(Path(os.environ.get(env,default)).read_text(encoding='utf8'),scope);return scope
base=load_code('ORYON_GPT_TORCH_CODE','gpt_pytorch.py')
mini=load_code('ORYON_MINI_CODE','mini_llama_classes.py')
ssm=load_code('ORYON_MAMBA_CODE','mamba_core.py')
TorchGPT=base['TorchGPT'];MiniLlama=mini['MiniLlama'];Selective=ssm['Selective']
assert torch.cuda.is_available()
text=Path(os.environ.get('ORYON_CORPUS','corpus.txt')).read_text(encoding='utf8')
chars=sorted(set(text));stoi={c:i for i,c in enumerate(chars)}; ids=torch.tensor([stoi[c] for c in text]);split=int(.9*len(ids))
assert len(ids)>500
lm_steps=int(os.environ.get('ORYON_STEPS','20')); recall_steps=int(os.environ.get('ORYON_RECALL_STEPS','100'))
def rope(z,pos):
d=z.shape[-1];freq=torch.exp(-math.log(10000)*torch.arange(0,d,2,device=z.device,dtype=z.dtype)/d)
theta=pos*freq;c,s=theta.cos(),theta.sin();u,v=z[...,0::2],z[...,1::2]
return torch.stack((u*c-v*s,u*s+v*c),-1).flatten(-2)
class Model(nn.Module):
def __init__(self,vocab,kind,width=64,layers=4):
super().__init__();self.kind=kind;self.emb=nn.Embedding(vocab,width);nn.init.normal_(self.emb.weight,std=.02)
torch_base=TorchGPT(vocab,128,width,layers,4,0.)
llama=MiniLlama(torch_base,False)
self.attention=nn.ModuleDict();self.ssm=nn.ModuleDict();self.ssm_norm=nn.ModuleDict()
self.kinds=[]
for i in range(layers):
use_attn=kind=='llama' or (kind=='hybrid' and i==layers-1)
self.kinds.append('attn' if use_attn else 'ssm')
if use_attn:self.attention[str(i)]=llama.blocks[i]
else:self.ssm[str(i)]=Selective(width);self.ssm_norm[str(i)]=nn.RMSNorm(width)
self.final=nn.RMSNorm(width)
def logits(self,ids):
x=self.emb(ids)
for i,kind in enumerate(self.kinds):
if kind=='attn':x=self.attention[str(i)](x)
else:x=x+self.ssm[str(i)](self.ssm_norm[str(i)](x))
return F.linear(self.final(x),self.emb.weight)
def step(self,ids,states,pos):
x=self.emb(ids);new=[]
for i,kind in enumerate(self.kinds):
if kind=='ssm':
y,c=self.ssm[str(i)].step(self.ssm_norm[str(i)](x),states[i]);x=x+y;new.append(c)
else:
block=self.attention[str(i)];z=block.n1(x);att=block.attn;bs,d=z.shape;dh=d//att.heads
def proj(layer):return layer(z).view(bs,att.heads,1,dh)
q=rope(proj(att.q),pos);k=rope(proj(att.k),pos);v=proj(att.v)
if states[i] is not None:k=torch.cat((states[i][0],k),2);v=torch.cat((states[i][1],v),2)
y=(([email protected](-2,-1)/math.sqrt(dh)).softmax(-1)@v).transpose(1,2).reshape(bs,d)
x=x+att.o(y);z=block.n2(x);x=x+block.down(F.silu(block.gate(z))*block.up(z));new.append((k,v))
return F.linear(self.final(x),self.emb.weight),new
def language_batch(generator):
ix=torch.randint(0,split-33,(4,),generator=generator)
return torch.stack([ids[i:i+32] for i in ix]).cuda(),torch.stack([ids[i+1:i+33] for i in ix]).cuda()
def recall_batch(generator,batch,pairs,queries=4):
x=torch.empty((batch,2*pairs+2*queries),dtype=torch.long);target=torch.full_like(x,-100)
for i in range(batch):
keys=torch.randperm(16,generator=generator)[:pairs];values=torch.randint(16,32,(pairs,),generator=generator)
for j in range(pairs):x[i,2*j]=keys[j];x[i,2*j+1]=values[j]
indices=torch.randint(pairs,(queries,),generator=generator)
for j,q in enumerate(indices):
pos=2*pairs+2*j;x[i,pos]=32+keys[q];x[i,pos+1]=values[q];target[i,pos]=values[q]
return x.cuda(),target.cuda()
results={}
for kind in ('mamba','hybrid','llama'):
torch.manual_seed(47);model=Model(len(chars),kind).cuda();vocab=len(chars)
probe=torch.randint(vocab,(1,16),device='cuda');cache=[None]*4
with torch.no_grad():
full=model.logits(probe);inc=[]
for i in range(16):out,cache=model.step(probe[:,i],cache,i);inc.append(out)
error=(full-torch.stack(inc,1)).abs().max().item();assert error<1e-4
optim=torch.optim.AdamW(model.parameters(),lr=.001);g=torch.Generator().manual_seed(55)
for step in range(lm_steps):
xx,yy=language_batch(g);optim.zero_grad(set_to_none=True);loss=F.cross_entropy(model.logits(xx).reshape(-1,vocab),yy.reshape(-1));loss.backward();optim.step()
idx=torch.Generator().manual_seed(77);ix=torch.randint(split,len(ids)-33,(4,),generator=idx)
xx=torch.stack([ids[i:i+32] for i in ix]).cuda();yy=torch.stack([ids[i+1:i+33] for i in ix]).cuda()
with torch.no_grad():val=float(F.cross_entropy(model.logits(xx).reshape(-1,vocab),yy.reshape(-1)))
generation=[]
for T in (32,128):
prompt=torch.randint(vocab,(1,T),device='cuda');cache=[None]*4
torch.cuda.synchronize();baseline=torch.cuda.memory_allocated();torch.cuda.reset_peak_memory_stats()
with torch.no_grad():
for i in range(T):out,cache=model.step(prompt[:,i],cache,i)
torch.cuda.synchronize();start=time.perf_counter()
for i in range(16):out,cache=model.step(out.argmax(-1),cache,T+i)
torch.cuda.synchronize();elapsed=time.perf_counter()-start
generation.append({'T':T,'tok_s':16/elapsed,'peak_extra_mib':(torch.cuda.max_memory_allocated()-baseline)/2**20})
row={'params':sum(p.numel() for p in model.parameters()),'cache_error':error,'lm_val_loss':val,'lm_steps':lm_steps,'generation':generation}
del model,optim,cache,out,full,inc
torch.manual_seed(147);model=Model(48,kind).cuda();optim=torch.optim.AdamW(model.parameters(),lr=.001);g=torch.Generator().manual_seed(155)
for step in range(recall_steps):
pairs=4 if step%2==0 else 8;xx,yy=recall_batch(g,16,pairs)
optim.zero_grad(set_to_none=True);loss=F.cross_entropy(model.logits(xx).reshape(-1,48),yy.reshape(-1),ignore_index=-100);loss.backward();optim.step()
scores=[]
with torch.no_grad():
for pairs in (4,8):
xx,yy=recall_batch(torch.Generator().manual_seed(177+pairs),256,pairs);logits=model.logits(xx);mask=yy!=-100
scores.append({'pairs':pairs,'accuracy':float((logits.argmax(-1)[mask]==yy[mask]).float().mean())})
row.update({'recall_steps':recall_steps,'recall':scores});results[kind]=row;print(kind,row,flush=True)
del model,optim,logits,xx,yy
Path('hybrid-results.json').write_text(json.dumps(results,indent=2),encoding='utf8')npm run lab and open the connection link.Exercises
Step 1 of 3. How is the transition product separated?
Step 1 of 3. What is the gradient with respect to S?
import numpy as np
def delta_step(S,k,v,beta):
pass