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
- 17Gated recurrent unitLSTM cellForget gate and its initializationGates as leaky integratorsSequential computation bottleneckParallelizable recurrences: QRNN and SRUFixed-size state memoryRNNs as dynamical systems
- 09Log-sum-exp trick and stable softmaxNewton's method for nonlinear systems
- 14Scaling and log-space recursions
- 08Prefix sumsParallel prefix scanScans over associative operators
- 15Group and instance normalizationLayer normalization
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 . A minimal gated RNN removes that dependency: in minGRU , and . The lab’s positive version of is if and otherwise. The basic form can use signed candidates, but the shown log method needs positive quantities.
For minLSTM compute and , normalize and , and use . Output and state are simplified. Both recurrences are affine in state: . Removing gate dependence on changes the function family; stacking layers restores position interactions in later representations but does not make one layer identical to a conventional GRU.
A product outside the format
Let . If , rearrangement gives . Forming directly may underflow even when stays moderate. For and , define and compute . Cumulative sums and log-sum-exp admit parallel implementations; NumPy code describes the operation without promising a particular kernel. Zeros may be represented by 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 , , 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 , log gates , and output , unstabilized variables satisfy , and . To avoid overflow use and rescaled gates , . Update and 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.
Matrix memory and recall
mLSTM matrix memory stores associations with and reads normalized by a state accumulating keys. Memory of dimension costs values, versus 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.
Newton over the entire trajectory
For , a Newton iteration around trajectory evaluates at and solves linear recurrence . 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 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.
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):
[email protected]+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.
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()
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.
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()
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
Step 1 of 3. What happens when dividing by Aₜ?
import numpy as np
def slstm_step(x, state, params):
pass