Module contents
Lesson 19 of 22Research 115 min

Mamba: selective state space models and parallel scan

Study selective state-space dynamics, affine associative scans, hardware-aware implementations, and a small Mamba-style language model.

After this lesson you can

  • Explain input-dependent state transitions and selective copying.
  • Derive and implement an associative scan of affine maps.
  • Distinguish mathematical scan complexity from hardware and training memory.
  • Compare selective SSM state with transformer KV cache.
  • Interpret a small controlled language-model experiment.

Before you start

Choosing what remains

In the previous lesson, a linear invariant SSM summarized the past with the same dynamics at every step. This permits a fixed convolution kernel, but also applies the same write and forgetting rule to inputs with the same delay. In selective copying, markers of interest appear at variable positions mixed with distractors. A rule that always keeps or forgets identically cannot adapt memory to the marker.

Do not turn this observation into a theorem about every network with a convolution: projections, nonlinearities, and external gates change the problem. Mamba compares specific configurations on synthetic tasks and makes the parameters governing state evolution input-dependent. In its selective-copying trial, sequences of length 4096 contain 16 relevant tokens; published figures belong to that task and training, not the small simulation below.

The difficulty is the variable distance between writing and querying. Imagine a signal with a marker followed by data, then distractors and finally a query. Constant-coefficient dynamics cannot know from input content to retain a particular value for an unpredictable number of steps. Selective dynamics can use a small gate to retain state during distractors and open it on new information. This solves one part of the problem; it does not itself guarantee a network learns to encode and retrieve an arbitrarily long list.

In practice selectivity is implemented through differentiable projections of representations, not a perfect external label announcing what will be useful in the future. Training needs examples and a loss that make the decision useful. If gate input contains incorrect information or state lacks capacity, changing transitions is insufficient for retrieval. Distinguish the ability to represent a rule from observing that an optimizer learns it on a particular distribution.

A selective SSM uses Δt\Delta_t, BtB_t, and CtC_t computed from each position’s input. For diagonal state and scalar input per channel, with exact interval ZOH,

at=exp⁡(ΔtA),bt=exp⁡(ΔtA)−1A⊙Btut,ht=at⊙ht−1+bt,yt=Ctht+Dut.a_t=\exp(\Delta_t A),\quad b_t=\frac{\exp(\Delta_t A)-1}{A}\odot B_t u_t,\quad h_t=a_t\odot h_{t-1}+b_t,\quad y_t=C_t h_t+Du_t.

The quotient is interpreted by its limit Δt\Delta_t where A=0A=0. With multiple channels and modes, AA and hh have channel and state axes; BtB_t and CtC_t broadcast according to parameterization. CthtC_t h_t denotes a sum over modes. The educational GPU implementation below uses write approximation ΔtBtut\Delta_t B_tu_t, like the Mamba reference scan, and computes exponential transition; it is not identical to exact ZOH for BB.

To fix dimensions, take batch size BloteB_{\rm lote} and sequence length TT. Processed signal has shape (Blote,T,dinner)(B_{\rm lote},T,d_{\rm inner}) and one-step expanded state (Blote,dinner,N)(B_{\rm lote},d_{\rm inner},N). One option computes BtB_t and CtC_t with shape (Blote,T,N)(B_{\rm lote},T,N) shared across channels, while Δt\Delta_t has one value per channel. Transition ata_t broadcasts to (Blote,T,dinner,N)(B_{\rm lote},T,d_{\rm inner},N). Other implementations may share differently: checking axes prevents a library-valid multiplication from accidentally mixing batch, channel, and state.

Parameterization A=−exp⁡(Alog⁡)A=-\exp(A_{\log}) and Δ=softplus⁡(q)\Delta=\operatorname{softplus}(q) keeps real transitions positive and below one in exact arithmetic for finite values. It does not guarantee every mode has a useful timescale. If Δ\Delta starts too large, previous state nearly disappears each step; if too small, writing can also be tiny. Exponentials and long products can overflow or lose precision in finite types. Inspect gate and gradient distributions and deliberately choose initialization and precision.

If A=−1A=-1, B=1B=1, and Δt=softplus⁡(qt)\Delta_t=\operatorname{softplus}(q_t), then at=e−Δt=1−σ(qt)a_t=e^{-\Delta_t}=1-\sigma(q_t). Write gt=σ(qt)g_t=\sigma(q_t) and the exact update becomes ht=(1−gt)ht−1+gtuth_t=(1-g_t)h_{t-1}+g_tu_t. A gate near zero preserves state and one near one replaces it. In the general system Δ\Delta modulates both transition and writing: calling it only a “forget gate” is a simplification, and its effect also depends on AA and BB.

InteractiveSelective copying in a scalar task
1 ★
0.9
2
−0.3
3
0.6
4
0.2
5
−0.4
6
0.8
7
0.7
8
−0.3
9
0.9
10
−0.6
11
0.6
12
0.4
13
−0.1
14
−0.9
15
0.8
16
0.1
17
−0.2
18 ★
−0.3
19
0.3
20
−0.3
21 ★
0.0
22 ★
−0.3
23
−0.9
24
−0.5
Model
23
Current input−0.499
Marked?no
First-layer Δ0.0064
Last marked value−0.258
Output at this step−0.253
Final validation MSE0.003384
Step through a sequence of 24 values. The star marks a relevant input. Both models trained on the same batches and were evaluated on separate validation; Δ comes from the learned gate.

The figure shows a deliberately simpler problem than copying a whole list: predict the last marked value at sequence end. Each model has two scalar filters; the first mixes current value and state, and the second filters that output. The selective model can condition its first gate on the marker; the invariant one uses a single gate. After 900 updates with the stated seed, validation squared losses were 0.003384 and 0.310314 respectively. The value depends on task and training and does not demonstrate universal superiority.

Learned selective-model steps were approximately 0.0064 on noise and 3.2108 on a marker. Since g=1−e−Δg=1-e^{-\Delta}, these correspond to retaining nearly all state or writing nearly all the new value. The invariant model obtained the same step, 0.1348, for both classes. Loss uses 1024 validation sequences generated with another seed, not training examples. The second layer has a fitted gate but adds no selectivity of its own in this demonstration.

[ ]Train two filters and check their gradientsBrowser
import json
import numpy as np
T=24

def batch(rng,n):
    v=rng.uniform(-1,1,(n,T)); m=(rng.random((n,T))<.12).astype(float);m[:,0]=1
    target=np.zeros(n)
    for t in range(T): target=np.where(m[:,t]>0,v[:,t],target)
    return v,m,target

def forward(v,m,p,selective):
    n,T=v.shape; h=np.zeros(n); z=np.zeros(n); cache=[]; history=[]
    for t in range(T):
        q=p[0]+(p[1]*m[:,t] if selective else 0); gate=1/(1+np.exp(-q)); r=1/(1+np.exp(-p[2]))
        hn=(1-gate)*h+gate*v[:,t]; zn=(1-r)*z+r*hn
        cache.append((h,z,hn,gate,r,m[:,t],v[:,t])); history.append(zn.copy());h,z=hn,zn
    return z,cache,np.stack(history,axis=1)

def loss_grad(v,m,y,p,selective):
    pred,c,_=forward(v,m,p,selective); grad=np.zeros(3); dz=2*(pred-y)/len(y);dh=np.zeros(len(y))
    for h,z,hn,g,r,mark,value in c[::-1]:
        grad[2]+=np.sum(dz*(hn-z)*r*(1-r)); dh+=dz*r; dz=dz*(1-r)
        q=dh*(value-h)*g*(1-g);grad[0]+=q.sum()
        if selective:grad[1]+=(q*mark).sum()
        dh*=1-g
    return np.mean((pred-y)**2),grad

def train(selective,steps=900):
    rng=np.random.default_rng(19);p=np.array([-1.,0.,2.]); means=np.zeros(3); vs=np.zeros(3)
    v,m,y=batch(rng,8); loss,g=loss_grad(v,m,y,p,selective)
    for k in range(3):
        perturb=np.zeros(3);perturb[k]=1e-5
        numeric=(loss_grad(v,m,y,p+perturb,selective)[0]-loss_grad(v,m,y,p-perturb,selective)[0])/2e-5
        assert abs(numeric-g[k])<1e-8
    for i in range(1,steps+1):
        v,m,y=batch(rng,128);loss,grad=loss_grad(v,m,y,p,selective)
        means=.9*means+.1*grad;vs=.999*vs+.001*grad**2
        p-=.02*(means/(1-.9**i))/(np.sqrt(vs/(1-.999**i))+1e-8)
    val=batch(np.random.default_rng(209),1024); pred,_,_=forward(val[0],val[1],p,selective)
    return p,float(np.mean((pred-val[2])**2))

sample=batch(np.random.default_rng(101),1);result={}
for selected in (False,True):
    p,mse=train(selected);_,_,history=forward(sample[0],sample[1],p,selected)
    gates=1/(1+np.exp(-(p[0]+(p[1]*sample[1][0] if selected else np.zeros(T)))))
    delta=-np.log1p(-gates)
    result['selective' if selected else 'fixed']={'params':p.tolist(),'mse':mse,'output':history[0].tolist(),'delta':delta.tolist()}
    print(selected,'params',p,'MSE',mse,'delta noise/marked',delta[sample[1][0]==0][0],delta[sample[1][0]==1][0])
result['sample']={'values':sample[0][0].tolist(),'marks':sample[1][0].astype(int).tolist(),'target':float(sample[2][0])}
with open('copy-results.json','w',encoding='utf8') as f:json.dump(result,f,indent=2)

The cell computes the gradient by backpropagation through time and checks it with central differences before training. The target variable updates only at marked positions. The selective network explicitly receives that marker: a real task must learn it from input representation, and a list of values would require more expressive memory and readout. The experiment checks gate mechanics without attributing paper figures to the small model.

Why there is no longer one fixed convolution

With variable coefficients, an earlier input’s contribution passes through a product of transitions depending on all intermediate positions:

ht=(∏r=1tar)h0+∑j=1t(∏r=j+1tar)bj.h_t=\left(\prod_{r=1}^{t}a_r\right)h_0+\sum_{j=1}^{t}\left(\prod_{r=j+1}^{t}a_r\right)b_j.

An empty product equals one. Two inputs at the same distance can receive different factors if their gate trajectories differ; consequently there is generally no single data-independent kernel. An associative composition of affine transformations remains, however, permitting all prefixes to be calculated by parallel scan once coefficients are known.

Write index matters: bjb_j already contains step jj‘s input, while the subsequent product contains transitions from j+1j+1 through tt. For t=jt=j there are no subsequent transitions and only btb_t remains. This matches reading after update, as in the previous lesson. If CtC_t also changes, output adds another content dependency even when two states coincide. The expression remains causal: no position after tt participates in hth_t.

A scan of affine maps

Represent each step by (a,b)(a,b) and function f(h)=a⊙h+bf(h)=a\odot h+b. If the left pair occurs before the right, composition is

(a,b)⋆(a′,b′)=(a′⊙a,  a′⊙b+b′).(a,b)\star(a',b')=(a'\odot a,\;a'\odot b+b').

This order applies the left pair first, then the right. Identity is (1,0)(1,0), and composition is associative because function composition is associative. With h0=0h_0=0, the inclusive prefix’s second component is exactly hth_t. An arbitrary initial state is included as a1:t⊙h0+b1:ta_{1:t}\odot h_0+b_{1:t}. Changing operator order reverses time order and often creates an error a constant-coefficient test does not detect.

Proof
Composing three steps from the left gives (a′′a′a,  a′′a′b+a′′b′+b′′)(a''a'a,\;a''a'b+a''b'+b''). Grouping the last two first gives the same pair by distributivity. Identity preserves both components. By induction, the prefix through tt represents ft∘⋯∘f1f_t\circ\cdots\circ f_1 and, applied to h0h_0, produces the recurrence.∎

Blelloch’s associative scan builds a reduction tree in an up-sweep, replaces the root with identity, and distributes exclusive prefixes in a down-sweep. For power-of-two TT, each phase has log⁡2T\log_2 T levels and T−1T-1 combinations; adding each input to its prefix gives inclusive prefixes. Total work is O(T)O(T) and depth O(log⁡T)O(\log T) with enough processors. Irregular lengths are padded with identities or the tree adapted. The figure executes the tree over 16 actual pairs; intermediate up-sweep cells are not yet all prefixes.

During the down-sweep, each node receives the prefix of everything to its left. Its left child inherits that prefix; its right child receives the prefix composed with the left child’s summary. Composition is noncommutative: even when scalar slopes multiply in either order, writes are multiplied by different transitions. The tree therefore preserves leaf order. Finally, combining each exclusive prefix with its own element gives the inclusive prefix and state after that input.

The next doubling variant is shorter to read than Blelloch. At each level it combines prefixes separated by 1, 2, 4, and so on; it requires O(Tlog⁡T)O(T\log T) work if all levels are materialized, though depth stays logarithmic. Its purpose here is to check the operator and a non-power-of-two length, not claim the previous tree’s work efficiency.

[ ]Level-wise selective scan in NumPyBrowser
import numpy as np
rng=np.random.default_rng(190)
T,N=17,5
x=rng.normal(size=T); Delta=rng.uniform(.02,.3,size=T)
A=-rng.uniform(.1,2,size=N); B=rng.normal(size=(T,N)); C=rng.normal(size=(T,N))
a=np.exp(Delta[:,None]*A[None,:])
b=np.expm1(Delta[:,None]*A[None,:])/A[None,:]*B*x[:,None]
h=np.zeros(N);reference=[]
for t in range(T):
    h=a[t]*h+b[t];reference.append(h.copy())
aa=a.copy(); bb=b.copy(); distance=1
while distance<T:
    old_a=aa.copy();old_b=bb.copy()
    aa[distance:]=old_a[distance:]*old_a[:-distance]
    bb[distance:]=old_a[distance:]*old_b[:-distance]+old_b[distance:]
    distance*=2
reference=np.stack(reference)
print('error de estado:',np.max(np.abs(bb-reference)))
print('error de salida:',np.max(np.abs(np.sum(C*bb,axis=1)-np.sum(C*reference,axis=1))))
assert np.allclose(bb,reference,atol=1e-12)

A complete check compares every prefix and output, not only final state. The cell uses different coefficients per step and irregular length, helping detect reversed composition or boundary errors. GPU gradients are also compared, since two forward-matching calculations could have incorrect backward in a custom implementation. Floating-point rearrangement changes rounding order; compare within tolerance instead of requiring bitwise equality.

InteractiveA 16-step scan tree
1
0.80, −0.25
2
0.80, 0.00
3
0.80, 0.25
4
0.80, 0.50
5
0.80, −0.25
6
0.80, 0.00
7
0.80, 0.25
8
0.80, 0.50
9
0.80, −0.25
10
0.80, 0.00
11
0.80, 0.25
12
0.80, 0.50
13
0.80, −0.25
14
0.80, 0.00
15
0.80, 0.25
16
0.80, 0.50
0
PhaseInput
Tree levels4 up-sweep + 4 down-sweep
Final error vs. sequential0.000000000000
Inspect up-sweep, identity root, down-sweep, and inclusive prefixes. Error compares the final stage with zero-initialized sequential recurrence.

On GPU, theoretical work and depth do not suffice to predict time. A hardware-aware scan groups operations to reduce global-fast-memory transfers and can recompute states in backward rather than saving them all. The paper describes a fused hardware-adapted implementation. This lesson’s PyTorch cell materializes intermediate arrays and uses general operations: it verifies mathematics and measures its own implementation, not those traffic or speed guarantees.

Saving one state per step would expand tensor size as BloteTdinnerNB_{\rm lote}T d_{\rm inner}N. Inputs and outputs can be much smaller than that intermediate representation. A fused kernel can process blocks and retain temporary states near computation, but SRAM has finite capacity: block partition and repeated work affect performance. Reconstructing states in backward trades extra computation for less storage. None of these choices changes the mathematical recurrence, but they change observed cost.

The lab’s chunked scan first combines each block’s pairs with doubling and then applies the previous block’s output state. This shortens each local tree, but the implementation still materializes states and links blocks from Python. Changing block size changes launch count and temporaries. Kernel comparison would require fixed hardware, precision, lengths, batch size, and protocol, plus measurement after warmup and synchronization; asymptotic complexity does not replace measurement.

From scan to a language block

The Mamba block projects input representation into two branches. One passes through short causal convolution and activation, generates selective parameters, and feeds the SSM; the other provides a SiLU gate. Their product projects back to model width and enters the residual stream. Short convolution needs its own history during generation in addition to SSM state. Local convolution must not be confused with the fixed global kernel lost on introducing selectivity.

For batch BB, inner width dinnerd_{\rm inner}, and NN modes, recurrent state has BdinnerNB d_{\rm inner}N elements; adding width-kk convolution retains up to Bdinner(k−1)B d_{\rm inner}(k-1) history elements. With dinner=1536d_{\rm inner}=1536, N=16N=16, and one example, the first term is 24576 elements or 98304 bytes in FP32. A per-layer KV cache with 8 KV heads, dimension 64, context 4096, and BF16 uses 2⋅8⋅64⋅4096⋅2=83886082\cdot8\cdot64\cdot4096\cdot2=8388608 bytes. Architectures are not equivalent because of those sizes: batch, precision, layer count, and chosen representation change the count.

Fixed memory makes long generation attractive but compresses information. Repeat After Me analyzes fixed-state model limits under specific assumptions and observes copying and retrieval difficulties; it does not imply every state model fails every memory task. Attention can retain individual elements in cache at the cost of growth with length. Both state size and available precision matter when interpreting a bound.

When comparing inference memory, distinguish persistent state, weights, temporaries, and framework allocations. Recurrent state must be kept for each active sequence and layer; attention cache also grows with batch, but additionally retains previous entries. Both can have extra projection or implementation buffers. The 98304-byte count covers only one layer’s SSM state matrix, not total model memory. The KV example also excludes queries, weights, and allocator; this compares two specific components, not total VRAM.

A selective block can process all training positions by scan when per-position parameters arise from causal input operations computable in parallel. During autoregressive generation the next token does not yet exist: compute one step, save state, and wait for the next choice. This dependency among generated tokens remains sequential even when context prefill or training has internal parallelism. In a served system batch scheduling, bandwidth, and sampling cost also matter.

Gated relatives

A gated linear recurrence combines a step-dependent transition and write. LSTM and GRU have similar expressions, but their gates usually depend on previous state: they are not all known in advance from input and the displayed affine scan is insufficient. In linear attention state can be an outer-sum matrix; RetNet adds decay and GLA input-dependent gates. RWKV combines recurrence and other operations with its own parameterizations. Superficially shared form does not make capabilities or kernels identical.

An LSTM cell sums forgotten memory and an incorporated candidate; gates and candidate normally depend on ht−1h_{t-1}. In linear attention, a matrix state accumulates products of key features and values and is queried with query features. Matrix size depends on both dimensions, not history. Adding decay or gates changes the preserve-replace balance, but also which objects are stored and which operations can be fused. The diagram summarizes structure only, not every paper’s details.

A further distinction appears at readout: an attention query can dynamically select among contributions stored in the state structure, while an SSM uses its own readout matrices. Both formulations can have input-dependent parameters; claiming one always “remembers” and the other always “forgets” does not describe actual behavior. Task, dimensionality, and training determine which information survives compression and what a query can retrieve.

InteractiveA family of gated recurrences
Update
hₜ = exp(ΔₜA) ⊙ hₜ₋₁ + bₜ
Dependence
Δₜ, Bₜ and Cₜ depend on the input
State
d_inner × N plus convolution state
Parallelism
Yes, with a scan of affine maps
Family
Compare schematic equation, dependencies, and state. Indicated parallelism assumes required coefficients can be computed before the scan.

Local lab: two small models

The cell builds two selective blocks in pure PyTorch and compares them with lesson 13’s mini Llama, both trained from initialization on the same character corpus. Chunked scan uses doubling prefixes and then incorporates incoming state; it checks output and gradients against the sequential version. It also checks full-sequence logits against incremental generation with SSM state and KV cache. Both models use their own cache during measurement.

This is not a fused kernel: the implementation creates (B,T,dinner,N)(B,T,d_{\rm inner},N) tensors and temporaries. Time is measured over 16 generated tokens after processing the prefix, using Python loops and shared GPU; additional peak includes prefix and generation above existing allocations. This measures this implementation, not optimized throughput. Validation is one fixed batch from the corpus’s final split, and one short run does not establish language quality.

Save lesson 13 classes in mini_llama_classes.py and lesson 12 classes in gpt_pytorch.py, with a corpus.txt of at least 500 characters. Alternatively set paths ORYON_MINI_CODE, ORYON_GPT_TORCH_CODE, and ORYON_CORPUS; ORYON_STEPS selects updates, default 20. The cell requires CUDA and produces mamba-lm-results.json in the working directory. Each architecture sees the same batch indices; a small parameter difference is printed for evaluation.

In a local 100-step RTX 3060 run, the selective model had 99968 parameters and mini Llama 104384; one-batch validation losses were 2.8465 and 3.1029. The first 12000 characters of Tiny Shakespeare were used, with newline normalized, 90% for fitting and 10% validation; normalized UTF-8 SHA-256 is 13755a378ca83b6707b89967339b999e457d2c4a8f86c889c4431d97de31cddb. Windows within a split can overlap. For a 128-token prefix, additional peak during processing and generation was approximately 0.067 and 0.288 MiB; measured generation produced 308 and 77 tokens per second respectively. Generation uses small operators and Python loops on a shared GPU, making rates especially sensitive to load and measurement. Both losses remain those of small, lightly trained models; no general architecture ranking follows.

[ ]Mini Mamba and mini Llama with cacheLocal GPU
import json, math, os, time
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
scope={};exec(Path(os.environ.get('ORYON_GPT_TORCH_CODE','gpt_pytorch.py')).read_text(encoding='utf8'),scope)
mini={};exec(Path(os.environ.get('ORYON_MINI_CODE','mini_llama_classes.py')).read_text(encoding='utf8'),mini)
TorchGPT=scope['TorchGPT'];MiniLlama=mini['MiniLlama']
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],dtype=torch.long)
assert len(ids)>500
split=int(.9*len(ids)); steps=int(os.environ.get('ORYON_STEPS','20')); length=32; batch=4

def scan_seq(a,b,initial=None):
    state=torch.zeros_like(b[:,0]) if initial is None else initial; out=[]
    for t in range(a.shape[1]):state=a[:,t]*state+b[:,t];out.append(state)
    return torch.stack(out,1)

def scan_chunks(a,b,chunk=8):
    state=torch.zeros_like(b[:,0]);outputs=[]
    for start in range(0,a.shape[1],chunk):
        aa=a[:,start:start+chunk];bb=b[:,start:start+chunk];distance=1
        while distance<aa.shape[1]:
            aa_old,bb_old=aa,bb
            aa=torch.cat((aa_old[:,:distance],aa_old[:,distance:]*aa_old[:,:-distance]),1)
            bb=torch.cat((bb_old[:,:distance],aa_old[:,distance:]*bb_old[:,:-distance]+bb_old[:,distance:]),1)
            distance*=2
        y=aa*state[:,None]+bb;state=y[:,-1];outputs.append(y)
    return torch.cat(outputs,1)

class Selective(nn.Module):
    def __init__(self,d,n=16,kernel=4):
        super().__init__(); inner=2*d; self.inner=inner;self.n=n;self.kernel=kernel
        self.proj=nn.Linear(d,2*inner,bias=False);self.conv=nn.Conv1d(inner,inner,kernel,groups=inner)
        self.select=nn.Linear(inner,2*n+inner);self.log_a=nn.Parameter(torch.log(torch.arange(1,n+1).float()).repeat(inner,1))
        self.skip=nn.Parameter(torch.ones(inner));self.out=nn.Linear(inner,d,bias=False)
        nn.init.constant_(self.select.bias[2*n:],-3.)
    def coefficients(self,u):
        v=self.select(u);B,C,raw=v.split((self.n,self.n,self.inner),dim=-1)
        dt=F.softplus(raw);a=torch.exp(-dt[...,None]*self.log_a.exp())
        b=dt[...,None]*B[:,:,None,:]*u[...,None]
        return a,b,C
    def forward(self,x,method='chunks'):
        u,z=self.proj(x).chunk(2,-1)
        u=F.silu(self.conv(F.pad(u.transpose(1,2),(self.kernel-1,0))).transpose(1,2))
        a,b,C=self.coefficients(u);h=scan_chunks(a,b) if method=='chunks' else scan_seq(a,b)
        y=(h*C[:,:,None,:]).sum(-1)+self.skip*u
        return self.out(y*F.silu(z))
    def step(self,x,cache):
        u,z=self.proj(x).chunk(2,-1)
        convbuf,h=cache if cache is not None else (torch.zeros(x.shape[0],self.inner,self.kernel-1,device=x.device),torch.zeros(x.shape[0],self.inner,self.n,device=x.device))
        buf=torch.cat((convbuf,u[:,None,:].transpose(1,2)),2)
        u=F.silu(F.conv1d(buf,self.conv.weight,self.conv.bias,groups=self.inner).squeeze(-1))
        a,b,C=self.coefficients(u[:,None,:]);h=a[:,0]*h+b[:,0]
        y=(h*C[:,0,None,:]).sum(-1)+self.skip*u
        return self.out(y*F.silu(z)),(buf[:,:,1:],h)

class TinyMamba(nn.Module):
    def __init__(self,vocab,d=64,layers=2):
        super().__init__();self.emb=nn.Embedding(vocab,d);nn.init.normal_(self.emb.weight,std=.02);self.norms=nn.ModuleList([nn.RMSNorm(d) for _ in range(layers)]);self.layers=nn.ModuleList([Selective(d) for _ in range(layers)]);self.final=nn.RMSNorm(d)
    def logits(self,ids,method='chunks'):
        h=self.emb(ids)
        for norm,layer in zip(self.norms,self.layers):h=h+layer(norm(h),method)
        return F.linear(self.final(h),self.emb.weight)
    def step(self,ids,states):
        h=self.emb(ids);new=[]
        for norm,layer,cache in zip(self.norms,self.layers,states):
            y,c=layer.step(norm(h),cache);h=h+y;new.append(c)
        return F.linear(self.final(h),self.emb.weight),new

def rope_step(z,pos):
    dh=z.shape[-1];freq=torch.exp(-math.log(10000)*torch.arange(0,dh,2,device=z.device,dtype=z.dtype)/dh)
    angle=pos*freq;c,s=angle.cos(),angle.sin();even,odd=z[...,0::2],z[...,1::2]
    return torch.stack((even*c-odd*s,even*s+odd*c),-1).flatten(-2)
def llama_step(model,ids,caches,pos):
    h=model.token(ids);new=[]
    for block,cache in zip(model.blocks,caches):
        z=block.n1(h);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_step(proj(att.q),pos);k=rope_step(proj(att.k),pos);v=proj(att.v)
        if cache is not None:k=torch.cat((cache[0],k),2);v=torch.cat((cache[1],v),2)
        out=((q@k.transpose(-2,-1)/math.sqrt(dh)).softmax(-1)@v).transpose(1,2).reshape(bs,d)
        h=h+att.o(out);z=block.n2(h);h=h+block.down(F.silu(block.gate(z))*block.up(z));new.append((k,v))
    return F.linear(model.final(h),model.token.weight),new

# Comprueba scan y gradientes en secuencia irregular y cachés token a token.
torch.manual_seed(19);a=torch.sigmoid(torch.randn(2,17,3,4,device='cuda')).requires_grad_();b=torch.randn_like(a).requires_grad_()
y1=scan_seq(a,b);y2=scan_chunks(a,b,8);g1=torch.autograd.grad(y1.square().mean(),(a,b),retain_graph=True);g2=torch.autograd.grad(y2.square().mean(),(a,b))
print('scan salida/gradientes:',(y1-y2).abs().max().item(),max((u-v).abs().max().item() for u,v in zip(g1,g2)))
assert torch.allclose(y1,y2,atol=1e-5) and all(torch.allclose(u,v,atol=1e-5) for u,v in zip(g1,g2))
old=TorchGPT(len(chars),128,64,2,4,0.)
models={'mamba':TinyMamba(len(chars)).cuda(),'llama':MiniLlama(old,False).cuda()}
for name,model in models.items():
    tokens=torch.randint(len(chars),(1,17),device='cuda'); full=model.logits(tokens);cache=[None]*2;out=[]
    if name=='mamba':
        seq=model.logits(tokens,method='seq');scan_error=(full-seq).abs().max().item()
        print('modelo scan paralelo/secuencial:',scan_error);assert scan_error<1e-4;del seq
    for i in range(tokens.shape[1]):
        logits,cache=model.step(tokens[:,i],cache) if name=='mamba' else llama_step(model,tokens[:,i],cache,i);out.append(logits)
    error=(full-torch.stack(out,1)).abs().max().item();print(name,'error caché:',error);assert error<1e-4

def minibatch(generator,start,end):
    ix=torch.randint(start,end-length-1,(batch,),generator=generator)
    x=torch.stack([ids[i:i+length] for i in ix]);y=torch.stack([ids[i+1:i+length+1] for i in ix]);return x.cuda(),y.cuda()
results={}
for name,model in models.items():
    torch.manual_seed(43);generator=torch.Generator().manual_seed(55);optim=torch.optim.AdamW(model.parameters(),lr=.001)
    torch.cuda.synchronize();start=time.perf_counter()
    for i in range(steps):
        x,y=minibatch(generator,0,split);optim.zero_grad(set_to_none=True);logits=model.logits(x);loss=F.cross_entropy(logits.reshape(-1,len(chars)),y.reshape(-1));loss.backward();optim.step()
    torch.cuda.synchronize();seconds=time.perf_counter()-start
    x,y=minibatch(torch.Generator().manual_seed(77),split,len(ids));
    with torch.no_grad():loss=F.cross_entropy(model.logits(x).reshape(-1,len(chars)),y.reshape(-1))
    assert torch.isfinite(loss)
    speeds=[]
    for T in (32,64,128):
        prompt=torch.randint(len(chars),(1,T),device='cuda');cache=[None]*2
        torch.cuda.synchronize();baseline=torch.cuda.memory_allocated();torch.cuda.reset_peak_memory_stats()
        with torch.no_grad():
            for i in range(T):logit,cache=model.step(prompt[:,i],cache) if name=='mamba' else llama_step(model,prompt[:,i],cache,i)
            torch.cuda.synchronize();start=time.perf_counter()
            for i in range(16):
                nxt=logit.argmax(-1);logit,cache=model.step(nxt,cache) if name=='mamba' else llama_step(model,nxt,cache,T+i)
            torch.cuda.synchronize();elapsed=time.perf_counter()-start
        speeds.append({'T':T,'tokens_per_second':16/elapsed,'peak_extra_mib':(torch.cuda.max_memory_allocated()-baseline)/2**20})
    row={'parameters':sum(p.numel() for p in model.parameters()),'validation_loss':float(loss),'steps':steps,'train_seconds':seconds,'generation':speeds}
    results[name]=row;print(name,row,flush=True)
Path('mamba-lm-results.json').write_text(json.dumps(results,indent=2),encoding='utf8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: Prove associativity of two affine-step compositions and relate it to scan.
0
Pair (a,b) represents h → a h + b and the left pair is applied first.

Step 1 of 3. What is the composition of first (a,b), then (c,d)?

Numeric
With d_inner = 1536 and N = 16, how many elements are in one sequence's SSM state, excluding convolution?
Numeric
For one layer with 8 KV heads, dimension 64, T = 4096, and BF16 values, how many MiB does one sequence's key-value cache occupy?
Quiz
With A = −1, B = 1, and exact ZOH, what does very small Δ do?
Quiz
What condition allows directly applying affine scan to all steps?
Quiz
Which comparison correctly describes these dependencies?
Code
Implement selective_scan(x, Delta, A, B, C) for scalar input per step, A with N modes, and B, C of shape T by N. Use exact ZOH, including the limit for A = 0; read after updating and return T real outputs.
import numpy as np
def selective_scan(x, Delta, A, B, C):
  pass
Shift+Enter to run
Key idea
Selectivity makes the transition content-dependent; affine-step composition remains associative, enabling a parallel scan.