Module contents
Lesson 24 of 24Research 110 min

The return of RNNs: xLSTM, minimal RNNs and parallel recurrences

Study minimal gated recurrences, stable exponential gating, matrix memory, and Newton-based parallelization, with measured implementation tradeoffs.

After this lesson you can

  • Derive minGRU and minLSTM as affine recurrences in their state.
  • Implement log-space linear recurrence evaluation and compare it with a sequential loop.
  • Implement a numerically stable sLSTM step with normalization.
  • Explain mLSTM matrix memory and its state cost.
  • Describe DEER linearization and its convergence conditions.
  • Compare small recurrent models under measured quality, training, and inference costs.

Before you start

A state that travels with the sequence

An RNN retains a fixed-size state during generation: adding tokens requires no cache per earlier position. Fixed size nevertheless depends on architecture, width, layer count, and batch size. Finite memory also does not guarantee exact recovery of every distant item. The tradeoff is that general recurrence must await the previous state; Feng and colleagues study simplifications allowing all position gates to be calculated before states.

A conventional GRU combines a candidate with the previous state, but candidate and gates both receive ht−1h_{t-1}. A minimal gated RNN removes that dependency: in minGRU zt=σ(Wzxt)z_t=\sigma(W_zx_t), h~t=g(Whxt)\tilde h_t=g(W_hx_t) and ht=(1−zt)ht−1+zth~th_t=(1-z_t)h_{t-1}+z_t\tilde h_t. The lab’s positive version of gg is g(u)=u+0.5g(u)=u+0.5 if u≥0u\geq0 and σ(u)\sigma(u) otherwise. The basic form can use signed candidates, but the shown log method needs positive quantities.

For minLSTM compute it=σ(Wixt)i_t=\sigma(W_i x_t) and ft=σ(Wfxt)f_t=\sigma(W_f x_t), normalize it′=it/(it+ft)i'_t=i_t/(i_t+f_t) and ft′=ft/(it+ft)f'_t=f_t/(i_t+f_t), and use ht=ft′ht−1+it′h~th_t=f'_t h_{t-1}+i'_t\tilde h_t. Output and state are simplified. Both recurrences are affine in state: ht=atht−1+bth_t=a_t h_{t-1}+b_t. Removing gate dependence on ht−1h_{t-1} changes the function family; stacking layers restores position interactions in later representations but does not make one layer identical to a conventional GRU.

InteractiveFrom GRU to minGRU
xₜgatehₜhₜ₋₁hₜ

In minGRU gates and candidates depend only on xₜ; aₜ and bₜ can be computed for all positions.

  • sequential loop
  • logarithmic formula

The accumulated product and direct division in float32 can lose range; the sequential loop and logarithmic formula avoid that explicit quotient.

Dependencies
180
Maximum log/loop error8.99e-15
Float32 product8.44e-27
Compare dependencies and log-space evaluation of a deterministic positive sequence.

A product outside the format

Let At=∏j=1tajA_t=\prod_{j=1}^{t}a_j. If aj>0a_j>0, rearrangement gives ht=At(h0+∑k≤tbk/Ak)h_t=A_t(h_0+\sum_{k\leq t}b_k/A_k). Forming AtA_t directly may underflow even when hth_t stays moderate. For h0>0h_0>0 and bk>0b_k>0, define st=∑j≤tlog⁡ajs_t=\sum_{j\leq t}\log a_j and compute log⁡ht=st+logaddexp⁡(log⁡h0,LSE⁡k≤t(log⁡bk−sk))\log h_t=s_t+\operatorname{logaddexp}(\log h_0,\operatorname{LSE}_{k\leq t}(\log b_k-s_k)). Cumulative sums and log-sum-exp admit parallel implementations; NumPy code describes the operation without promising a particular kernel. Zeros may be represented by −∞-\infty with appropriate boundary handling; negative values need another method, such as an associative affine scan.

The log-space linear recurrence avoids constructing tiny products and huge quotients. Algebraic equality does not eliminate all rounding error: compare with the loop and measure error. Map composition operator (A,b)(A,b), (A2,b2)∘(A1,b1)=(A2A1,A2b1+b2)(A_2,b_2)\circ(A_1,b_1)=(A_2A_1,A_2b_1+b_2), also allows a scan with matrices and terms of either sign. Heinsen develops methods for this computation.

sLSTM: store with exponential gates

The exponential gate in xLSTM can give a new observation more weight than earlier accumulation. In Beck and colleagues’ scalar sLSTM, with candidate ztz_t, log gates ℓti,ℓtf\ell^i_t,\ell^f_t, and output oto_t, unstabilized variables satisfy ct=ftct−1+itztc_t=f_tc_{t-1}+i_tz_t, nt=ftnt−1+itn_t=f_tn_{t-1}+i_t and ht=otct/nth_t=o_tc_t/n_t. To avoid overflow use mt=max⁡(ℓtf+mt−1,ℓti)m_t=\max(\ell^f_t+m_{t-1},\ell^i_t) and rescaled gates fˉt=eℓtf+mt−1−mt\bar f_t=e^{\ell^f_t+m_{t-1}-m_t}, iˉt=eℓti−mt\bar i_t=e^{\ell^i_t-m_t}. Update cˉ\bar c and nˉ\bar n with them; their ratio matches when both forms are representable. The paper also uses headwise memory mixing and additional blocks; this lesson’s cell is a small version, not the full model.

InteractiveExponential gates without overflow

The first six candidates are +1 and the next are −1. A large exponential gate weights the new candidate; the gate is not restricted to [0,1].

100
Stabilized c−1.0000
Stabilized n1.0000
m98.88
Unstabilized float32 outputInf / NaN
Output uses a normalizer and stabilizer; change preactivation and compare with unstabilized float32.

Matrix memory and recall

mLSTM matrix memory stores associations with Ct=ftCt−1+itvtkt⊤C_t=f_tC_{t-1}+i_tv_tk_t^\top and reads CtqtC_tq_t normalized by a state accumulating keys. Memory of dimension d×dd\times d costs O(d2)O(d^2) values, versus O(d)O(d) for a vector state of equal width; this does not automatically equalize parameters, quality, or compute. The parallel form expresses causal contributions via query–key products and gates, subject to implementation and stability constraints.

The figure compares three small models trained on discrete keys and values. The matrix variant uses fixed gates equal to one, learned projections, and normalization; it simplifies mLSTM and is not the full xLSTM block. Parameter counts were approximately matched by changing recurrent width. Keys are distinct per example and values random; chance accuracy is 12.5%. These are measurements from this finite experiment, not a universal architecture ranking. With matrix dimension 8 and 16 pairs, LSTM, minGRU, and matrix memory got 20.5%, 20.7%, and 92.6% of 512 queries right; with dimension 16, 22.5%, 24.0%, and 100%. Keys come from a fixed vocabulary of 16, values from one of 8, and every length appears in training. Sequences are independently generated, but overlap with training was not checked. The result does not prove out-of-distribution retrieval.

InteractiveVector versus matrix memory
LSTM: 34.6 % · 380 parameters · state 3
minGRU: 40.4 % · 414 parameters · state 7
Matrix memory: 99.6 % · 416 parameters

Each bar is a proportion of 512 examples generated with another seed. A single seed and one example family limit the comparison.

Stored pairs
Matrix memory dimension
Random accuracy12,5 %
Accuracy measured on 512 queries generated with another seed per condition; change pair count and memory size.

Newton over the entire trajectory

For ht=F(ht−1,xt)h_t=F(h_{t-1},x_t), a Newton iteration around trajectory h^\hat h evaluates Jt=∂F/∂hJ_t=\partial F/\partial h at h^t−1\hat h_{t-1} and solves linear recurrence htnuevo=Jtht−1nuevo+F(h^t−1,xt)−Jth^t−1h_t^{\rm nuevo}=J_th_{t-1}^{\rm nuevo}+F(\hat h_{t-1},x_t)-J_t\hat h_{t-1}. DEER by Lim and colleagues uses that linear problem to parallelize an iteration. Matrix scan adds work and memory.

A later proof establishes that a causal discrete recurrence converges in at most TT iterations from any initial trajectory in exact arithmetic: each iteration fixes at least one more position. This does not guarantee few iterations or numerical stability. Large Jacobians can amplify errors; quasi-DEER approximates Jacobians and ELK adds damping, with different costs and tradeoffs.

InteractiveNewton over the trajectory
  • sequential loop
  • Newton / scan

Linearization is recalculated at every iteration. In exact arithmetic, the causal structure fixes at least one additional position per iteration; this does not guarantee rapid convergence or floating-point stability.

Dynamics
0.4
3
Maximum error versus loop1.734e-12
Compare forced tanh with the chaotic logistic map r=4; each iteration uses an affine scan.
[ ]Linear recurrences and DEERBrowser
import numpy as np

def serial(a,b,h0):
    h=np.array(h0,dtype=float);out=[]
    for ai,bi in zip(a,b):h=ai*h+bi;out.append(h.copy())
    return np.stack(out)

def log_scan(a,b,h0):
    # a>0, b>0, h0>0. For zeros, take the corresponding log as -inf.
    s=np.cumsum(np.log(a),axis=0)
    sums=np.logaddexp.accumulate(np.log(b)-s,axis=0)
    return np.exp(s+np.logaddexp(np.log(h0),sums))

def affine_scan(A,b,h0):
    # Inclusive associative scan of (A,b) maps: later ∘ earlier.
    A=A.copy();b=b.copy();n=len(A);stride=1
    while stride<n:
        oldA=A.copy();oldb=b.copy()
        A[stride:]=oldA[stride:]@oldA[:-stride]
        b[stride:]=(oldA[stride:]@oldb[:-stride,:,None])[...,0]+oldb[stride:]
        stride*=2
    return (A@h0[:,None])[...,0]+b

def deer(x,W,U,h0,iterations):
    T=len(x);D=len(h0);guess=np.zeros((T+1,D));guess[0]=h0;errors=[]
    target=serial_tanh(x,W,U,h0)
    for _ in range(iterations):
        z=x@U.T+guess[:-1]@W.T;f=np.tanh(z);J=(1-f*f)[:,:,None]*W[None,:,:]
        bias=f-(J@guess[:-1,:,None])[...,0]
        guess[1:]=affine_scan(J,bias,h0)
        errors.append(float(np.max(np.abs(guess[1:]-target))))
    return guess[1:],errors

def serial_tanh(x,W,U,h0):
    h=h0.copy();out=[]
    for v in x:h=np.tanh(W@h+U@v);out.append(h.copy())
    return np.stack(out)

def slstm_step(z,log_i,log_f,o,state):
    c,n,m=state;mnew=np.maximum(log_f+m,log_i);i=np.exp(log_i-mnew);f=np.exp(log_f+m-mnew)
    c=f*c+i*z;n=f*n+i;return o*c/n,(c,n,mnew)

rng=np.random.default_rng(2401);T=2048;D=4
a=rng.uniform(.25,.95,(T,D));b=rng.uniform(.01,.5,(T,D));h0=np.ones(D)
reference=serial(a,b,h0);parallel=log_scan(a,b,h0)
print('Recurrencia: error máximo log/serial',np.max(np.abs(reference-parallel)))
z=rng.normal(size=(64,D));gate=1/(1+np.exp(-rng.normal(size=(64,D))));candidate=np.logaddexp(0,z)+.5
print('minGRU: error máximo',np.max(np.abs(serial(1-gate,gate*candidate,h0)-log_scan(1-gate,gate*candidate,h0))))
for gain in (.4,2.0):
    W=np.array([[.3,.8],[-.6,.25]])*gain;U=np.array([[.8],[-.4]]);x=rng.normal(size=(48,1));_,errors=deer(x,W,U,np.zeros(2),12)
    print('DEER ganancia',gain,'errores por iteración',np.round(errors,8).tolist())
state=(np.zeros(1),np.zeros(1),np.zeros(1))
for log_i in (0.,2.,1000.):
    h,state=slstm_step(np.array([.7]),np.array([log_i]),np.array([-.1]),np.ones(1),state)
print('sLSTM finita con log puerta 1000:',h[0],all(np.isfinite(v).all() for v in state))

The cell compares a loop with a log scan over 2 048 steps and applies a doubling affine scan to linearizations of a two-dimensional RNN. Large gain can oscillate before convergence. NumPy cost, actual browser parallelism, and GPU-kernel cost are separate questions.

Measure on the available GPU

The next lab implements a character model with three cores, fixed initialization, and fixed split. It uses Tiny Shakespeare, a contiguous 90/10 split, and the same batch and length for all architectures. sLSTM is a simplified Python cell; minGRU uses PyTorch cumulative operations and LSTM calls PyTorch/cuDNN when available. Timings therefore include implementation differences, not only architecture. The cell downloads the corpus if absent, needs PyTorch, and optionally a GPU. It defaults to three check steps; LM_STEPS=200 reproduces the measured budget and LM_OUT saves results. Optimizer state is not saved and no convergence comparison is claimed.

[ ]Three character language modelsLocal GPU
import os,json,time,math,hashlib,urllib.request
import torch
from torch import nn
from torch.nn import functional as F
torch.set_num_threads(1);torch.manual_seed(2401)
url='https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt'
path=os.environ.get('SHAKESPEARE_PATH','tinyshakespeare.txt')
if not os.path.exists(path):urllib.request.urlretrieve(url,path)
raw=open(path,encoding='utf8').read();print('SHA256',hashlib.sha256(raw.encode()).hexdigest(),flush=True)
vocab=sorted(set(raw));stoi={c:i for i,c in enumerate(vocab)};tokens=torch.tensor([stoi[c] for c in raw],dtype=torch.long);split=int(.9*len(tokens));train=tokens[:split];valid=tokens[split:]
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu');V=len(vocab);E=48
class Model(nn.Module):
 def __init__(self,kind):
  super().__init__();self.kind=kind;self.H=77 if kind=='minGRU' else 32;self.emb=nn.Embedding(V,E);self.head=nn.Linear(self.H,V)
  if kind=='LSTM':self.rnn=nn.LSTM(E,self.H,batch_first=True)
  elif kind=='minGRU':self.proj=nn.Linear(E,2*self.H)
  else:self.xproj=nn.Linear(E,4*self.H);self.hproj=nn.Linear(self.H,4*self.H)
 def forward(self,x):
  x=self.emb(x);B,T,_=x.shape;H=self.H
  if self.kind=='LSTM':out,_=self.rnn(x)
  elif self.kind=='minGRU':
   z,y=self.proj(x).chunk(2,-1);loga=F.logsigmoid(-z);logg=torch.where(y>=0,torch.log(torch.clamp(y+.5,min=1e-8)),F.logsigmoid(y));logb=F.logsigmoid(z)+logg
   s=loga.cumsum(dim=1);out=torch.exp(s+torch.logcumsumexp(logb-s,dim=1))
  else:
   h=x.new_zeros(B,H);c=h.clone();n=h.clone();m=h.clone();ys=[]
   proj=self.xproj(x)
   for xt in proj.unbind(1):
    z,li,lf,o=(xt+self.hproj(h)).chunk(4,-1);z=z.tanh();lf=F.logsigmoid(lf);mnew=torch.maximum(lf+m,li);i=(li-mnew).exp();f=(lf+m-mnew).exp();c=f*c+i*z;n=f*n+i;h=o.sigmoid()*c/n.clamp_min(1e-8);m=mnew;ys.append(h)
   out=torch.stack(ys,1)
  return self.head(out)
@torch.inference_mode()
def infer_profile(model):
 model.eval();H=model.H;B=1;state=[torch.zeros(B,H,device=device) for _ in range(2 if model.kind=='LSTM' else 4 if model.kind=='sLSTM' else 1)]
 if device.type=='cuda':torch.cuda.synchronize();torch.cuda.reset_peak_memory_stats()
 start=time.perf_counter()
 for t in range(128):
  x=model.emb(tokens[t:t+1].to(device))
  if model.kind=='LSTM':
   y,(h,c)=model.rnn(x[:,None,:],(state[0][None],state[1][None]));state=[h[0],c[0]];output=y[:,0,:]
  elif model.kind=='minGRU':
   z,y=model.proj(x).chunk(2,-1);candidate=torch.where(y>=0,y+.5,y.sigmoid());state=[(1-z.sigmoid())*state[0]+z.sigmoid()*candidate];output=state[0]
  else:
   h,c,n,m=state;z,li,lf,o=(model.xproj(x)+model.hproj(h)).chunk(4,-1);lf=F.logsigmoid(lf);mnew=torch.maximum(lf+m,li);i=(li-mnew).exp();f=(lf+m-mnew).exp();c=f*c+i*z.tanh();n=f*n+i;h=o.sigmoid()*c/n.clamp_min(1e-8);state=[h,c,n,mnew];output=h
  model.head(output)
 if device.type=='cuda':torch.cuda.synchronize()
 return {'tokens':128,'seconds':time.perf_counter()-start,'state_bytes':sum(t.numel()*t.element_size() for t in state),'peak_allocated_bytes':torch.cuda.max_memory_allocated() if device.type=='cuda' else None}
def batch(data,B,T,g):
 ix=torch.randint(len(data)-T-1,(B,),generator=g);xx=torch.stack([data[i:i+T] for i in ix]);yy=torch.stack([data[i+1:i+T+1] for i in ix]);return xx.to(device),yy.to(device)
def measure(model,T,B=8,reps=3):
 model.train();opt=torch.optim.Adam(model.parameters(),lr=.001);g=torch.Generator().manual_seed(99);x,y=batch(train,B,T,g)
 for _ in range(2):opt.zero_grad(set_to_none=True);loss=F.cross_entropy(model(x).reshape(-1,V),y.reshape(-1));loss.backward();opt.step()
 if device.type=='cuda':torch.cuda.synchronize();torch.cuda.reset_peak_memory_stats()
 t=time.perf_counter()
 for _ in range(reps):opt.zero_grad(set_to_none=True);loss=F.cross_entropy(model(x).reshape(-1,V),y.reshape(-1));loss.backward();opt.step()
 if device.type=='cuda':torch.cuda.synchronize()
 dt=time.perf_counter()-t;return {'T':T,'B':B,'tokens_per_s':reps*B*T/dt,'seconds':dt,'peak_allocated_bytes':torch.cuda.max_memory_allocated() if device.type=='cuda' else None}
def run():
 steps=int(os.environ.get('LM_STEPS','3'));B=8;T=32;results=[]
 for kind in ('LSTM','minGRU','sLSTM'):
  torch.manual_seed(2401);model=Model(kind).to(device);opt=torch.optim.Adam(model.parameters(),lr=.001);g=torch.Generator().manual_seed(2402);model.train();start=time.perf_counter()
  for step in range(steps):
   x,y=batch(train,B,T,g);opt.zero_grad(set_to_none=True);loss=F.cross_entropy(model(x).reshape(-1,V),y.reshape(-1));loss.backward();nn.utils.clip_grad_norm_(model.parameters(),1.);opt.step()
   if (step+1)%50==0:print(kind,step+1,'loss',float(loss.detach()),flush=True)
  if device.type=='cuda':torch.cuda.synchronize()
  elapsed=time.perf_counter()-start;model.eval();gval=torch.Generator().manual_seed(2403)
  with torch.no_grad():
   val=[]
   for _ in range(20):
    x,y=batch(valid,B,T,gval);val.append(float(F.cross_entropy(model(x).reshape(-1,V),y.reshape(-1))))
  inference=infer_profile(model);timings=[measure(model,t) for t in (32,64,128)]
  row={'kind':kind,'parameters':sum(p.numel() for p in model.parameters()),'steps':steps,'train_loss':float(loss.detach()),'val_loss':sum(val)/len(val),'training_seconds':elapsed,'tokens_per_s_training':steps*B*T/elapsed,'timings':timings,'inference':inference}
  print(json.dumps(row),flush=True);results.append(row)
  if os.environ.get('LM_OUT'):
   with open(os.environ['LM_OUT'],'w',encoding='utf8') as f:json.dump({'device':torch.cuda.get_device_name(0) if device.type=='cuda' else 'CPU','torch':torch.__version__,'vocab':V,'sha256':hashlib.sha256(raw.encode()).hexdigest(),'results':results},f,indent=2)
 return results
if __name__=='__main__':run()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On an RTX 3060 with PyTorch and concurrent work, the 200-step run achieved mean validation losses 2.866 (LSTM), 2.653 (minGRU), and 2.774 (sLSTM). Networks have 15 761, 15 736, and 15 761 parameters, respectively. For batch 8 and length 128, short forward, backward, and update tests yielded about 84 872, 94 767, and 618 tokens/s, respectively; measurements are sensitive to concurrency and kernels, and sLSTM uses a Python loop. Explicit inference states per sequence occupied 256, 308, and 512 bytes in float32. The corpus SHA-256 is 86c4e6aa9db7c042ec79f339dcb96d42b0075e16b8fc2e86bf0ca57e2dc565ed. One short run and seed do not justify a general ranking.

Recurrent inference stores tensors different from a key–value cache; lab state size includes explicit tensors, while GPU peak includes parameters, temporaries, and allocator too. Measurements are short, include CUDA warmup and synchronization, and may be affected by other processes. Quality uses the same validation and is not extrapolated to large models.

[ ]Controlled associative recallLocal GPU
import os,json,math,numpy as np,torch
from torch import nn
from torch.nn import functional as F
torch.set_num_threads(1);device=torch.device('cuda' if torch.cuda.is_available() else 'cpu');K=16;V=8
class Recall(nn.Module):
 def __init__(self,kind,dim,hidden=None):
  super().__init__();self.kind=kind;self.dim=dim
  if kind=='matriz':self.key=nn.Linear(K,dim);self.value=nn.Linear(V,dim);self.query=nn.Linear(K,dim);self.head=nn.Linear(dim,V)
  else:
   self.hidden=hidden;self.head=nn.Linear(hidden,V)
   if kind=='LSTM':self.cell=nn.LSTM(K+V,hidden,batch_first=True)
   else:self.proj=nn.Linear(K+V,2*hidden)
 def forward(self,key,value,query):
  B,N,_=key.shape
  if self.kind=='matriz':
   k=self.key(key);v=self.value(value);q=self.query(query);C=torch.einsum('bnd,bne->bde',v,k);n=k.sum(1);numer=torch.einsum('bde,be->bd',C,q);denom=torch.einsum('bd,bd->b',n,q).abs().clamp_min(1);out=numer/denom[:,None]
  else:
   x=torch.cat((key,value),-1);query_token=torch.cat((query,query.new_zeros(B,V)),-1)[:,None];x=torch.cat((x,query_token),1)
   if self.kind=='LSTM':out=self.cell(x)[0][:,-1]
   else:
    z,y=self.proj(x).chunk(2,-1);gate=z.sigmoid();candidate=torch.where(y>=0,y+.5,y.sigmoid());h=x.new_zeros(B,self.hidden)
    for t in range(N+1):h=(1-gate[:,t])*h+gate[:,t]*candidate[:,t]
    out=h
  return self.head(out)
def count(m):return sum(p.numel() for p in m.parameters())
def make_models(dim):
 matrix=Recall('matriz',dim);target=count(matrix);models={'matriz':matrix}
 for kind in ('LSTM','minGRU'):
  candidates=[Recall(kind,dim,h) for h in range(2,80)];models[kind]=min(candidates,key=lambda m:abs(count(m)-target))
 return models
def batch(B,N,g):
 keys=torch.stack([torch.randperm(K,generator=g)[:N] for _ in range(B)]);values=torch.randint(V,(B,N),generator=g);qidx=torch.randint(N,(B,),generator=g);q=keys[torch.arange(B),qidx];y=values[torch.arange(B),qidx]
 return F.one_hot(keys,K).float().to(device),F.one_hot(values,V).float().to(device),F.one_hot(q,K).float().to(device),y.to(device)
def run():
 steps=int(os.environ.get('RECALL_STEPS','3'));rows=[]
 for dim in (8,16):
  for kind in ('LSTM','minGRU','matriz'):
   torch.manual_seed(2401);models=make_models(dim);model=models[kind].to(device);opt=torch.optim.Adam(model.parameters(),lr=.003);g=torch.Generator().manual_seed(2402)
   for t in range(steps):
    N=(2,4,8,16)[t%4];k,v,q,y=batch(64,N,g);opt.zero_grad(set_to_none=True);loss=F.cross_entropy(model(k,v,q),y);loss.backward();opt.step()
    if (t+1)%100==0:print(dim,kind,t+1,float(loss.detach()),flush=True)
   scores={};gv=torch.Generator().manual_seed(2403)
   with torch.no_grad():
    for N in (2,4,8,16):
     k,v,q,y=batch(512,N,gv);scores[str(N)]=float((model(k,v,q).argmax(-1)==y).float().mean())
   row={'dimension':dim,'kind':kind,'hidden':getattr(model,'hidden',None),'parameters':count(model),'steps':steps,'accuracy':scores};rows.append(row);print(json.dumps(row),flush=True)
   if os.environ.get('RECALL_OUT'):
    with open(os.environ['RECALL_OUT'],'w',encoding='utf8') as f:json.dump(rows,f,indent=2)
if __name__=='__main__':run()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In this lab RECALL_STEPS=1000 trains one seed per model and dimension; RECALL_OUT saves accuracy. Each minibatch alternates 2, 4, 8, and 16 pairs, and 512 queries generated with another seed are evaluated per length. Integer width granularity causes a slight parameter mismatch; the exact count appears in the figure. Confirming a trend needs more seeds and controls, and vector and matrix dimensions have different state costs.

Linear recurrences, matrix memories, and linear attention share accumulation operations, but gates and normalizers matter. LRU, RWKV, state-space models, and hybrid architectures explore other choices; the next module studies these connections without assuming implementations are equivalent.

Exercises

Proof
Prove: Expand hₜ = aₜhₜ₋₁ + bₜ for positive coefficients.
0
Define Aₜ as the product from a₁ through aₜ, with A₀=1.

Step 1 of 3. What happens when dividing by Aₜ?

Numeric
With input and state dimension 512 and no biases, how many fewer parameters does a minGRU with two input projections have than a GRU with three input and three recurrent projections?
Code
Implement slstm_step(x,state,params), with rescaled state=(h,c,n,m). params contains W of shape (input,4H), U of shape (H,4H), and b of shape (4H,). Split preactivations into candidate z, input log-gate, forget preactivation, and output gate; use tanh for z and sigmoid for output and forget. Return (h_new,c_new,n_new,m_new).
import numpy as np
def slstm_step(x, state, params):
  pass
Shift+Enter to run
Quiz
What is lost by removing hₜ₋₁ from a layer's gates?
Quiz
What best describes a fixed recurrent state?