Sparse, local and linear attention
Compare sparse and sliding-window attention with linear recurrent attention, positive random features, and associative recall.
After this lesson you can
- Calculate local attention pairs and receptive fields across layers.
- Derive normalized linear attention and its causal recurrent state.
- Explain positive random-feature approximation of the exponential kernel.
- Analyze information loss in fixed-size associative memory.
- Compare measured quality, time, and memory with explicit experimental limits.
Before you start
- 18Quadratic cost of attentionAttention as a kernel smootherAdditive attention biasKV cacheCausal mask
- 13Random features modelRandom features approximation errorMoore-Aronszajn theorem
- 11Common kernels and construction rules
- 17Recurrent neural network (Elman network)Hidden state as a summary of the prefix
Fewer pairs, or a different memory
FlashAttention retains all allowed interactions and reorganizes their transfers. For much longer documents or sequences, another family of methods changes which pairs are computed or which function assigns weights. The saving comes with a modeling question: can needed information reach the query, and can it be distinguished from everything sharing its memory?
In causal sliding-window attention, position sees the last positions including itself. At length , valid pair count is , of order when . An implementation first constructing a masked dense matrix may still use quadratic memory: the mathematical pattern alone does not guarantee an efficient kernel. The inference KV cache can be limited to the last entries per layer if the model uses only that window.
For , the sum is : initial rows do not yet have a full window. For example, eight positions and window three give pairs, versus 36 for a dense causal mask. If window size grows proportionally with , the count becomes quadratic again; “local” is linear in length only when remains bounded. Multiply by batch, head count, and head dimension to estimate product work, and add projections and softmax.
During decoding, a circular cache can replace the oldest entry when inserting a new one. Also retain the logical position needed for positional encoding and mask: the physical buffer index is not necessarily the original position. Each layer’s cache contains different representations and must be maintained separately. A bounded window limits direct storage, but an old token’s effect may remain in later states that incorporated its information. Such indirect transmission does not guarantee preservation of an exact quotation.
Depth enlarges the receptive field. If each layer reaches up to preceding positions, after layers the final position can depend on up to positions, bounded by available length. This count includes the current position and assumes equal contiguous windows with no additional paths. For and this is 131041 positions; it does not mean the model remembers that entire distance accurately. Mistral 7B combines window attention and circular cache; results depend on its particular architecture and training.
Sparse patterns can add dilated jumps, global positions, or predetermined connections. Sparse Transformer, Longformer, and BigBird propose different, noninterchangeable patterns. In a causal model, a global position cannot look into the future either: connection direction and masking matter. The next diagram uses an educational rule and does not exactly reproduce any of those models.
Fixed dilation may leave coverage gaps even after several layers: reaching a distant endpoint does not imply every intermediate point is accessible. Alternating dilations or adding global paths changes the dependency graph. Adding global positions that all queries can read typically adds work proportional to ; if grows with , that cost changes too. Long-distance communication may need several layers: a causal global token must first have received earlier information before a later query reads it.
Another possibility projects the sequence dimension to fewer latent positions. Linformer studies low-rank approximations to reduce attention cost; quality depends on how much useful structure projection retains. In causal generation, projecting all sequence keys and masking afterward is insufficient: a projected component may have mixed future information before masking. A construction respecting each prefix or a different formulation is needed. The attention matrix is not low-rank by definition for every input or task.
The figure shows a one-layer mask and separately calculates which inputs can affect the last position after multiple layers. Check by hand with window three and two layers: the final row reads positions 13, 14, and 15; together their representations can read 11 through 15 in the preceding layer. The result is five positions, not six: each window counts its own position, already in the set. Dilation two yields alternating positions and cardinality differs from interval size between endpoints.
Practical cost also depends on mask regularity. Contiguous blocks may better exploit matrix products and grouped reads; irregular sparse connections may require indices and less coherent accesses. Applying a mask only after computing every score preserves the local mathematical result but does not necessarily obtain its compute saving. Distinguish allowed pair count from executed operation count and measure both when comparing hardware.
Change the kernel and order
Linear attention uses features with a nonnegative product as weight. For and , without a mask, the numerator can be calculated as
The first order constructs a matrix; the second constructs . Counting multiplication and addition as two FLOPs, their principal products cost approximately and respectively. Feature construction, normalization, and input projection costs are additional. Associative order is linear in if and remain fixed, but is not necessarily faster for short sequences on a GPU.
To make the output a weighted mean, divide each row by . Omit it and scale changes with key count and magnitude. Choosing is positive and defines a different kernel; it does not reproduce softmax exactly. Rearrangement is exact for that kernel in exact arithmetic, not proof of equivalence to exponential attention.
Normalization has a specific interpretation. If every product is nonnegative and their sum is nonzero, dividing by the sum produces weights summing to one. Output lies in the convex hull of values for that query. This does not say weights match softmax: two positive kernels can assign very different probabilities to the same pairs. Adding a small to protect arithmetic also slightly changes normalization; declare it and test small-value cases.
The causal mask prevents simply using calculated over the whole sequence, because that matrix would include keys later than each query. The next section’s prefix state addresses exactly that dependency. A parallel implementation can calculate prefixes with a scan, but must control which intermediates it materializes and retains for backward. Linear arithmetic complexity does not automatically determine that implementation’s wall time or peak memory.
Recurrent state is not a table of individual keys: it sums outer products. If two keys produce similar features, their contributions overlap in and a query may retrieve a mixture. Higher dimension provides more degrees of freedom while increasing state and per-token work; it does not itself guarantee learned parameters separate every pair. With and , for example, and store elements per head. Dense cache stores keys and values per position, and comparison requires fixing types and dimensions of both.
The recurrent form
With a causal mask, each query sees keys only through . The recurrent form maintains a matrix state and vector:
State occupies elements per head independently of , and updating it costs per token. Katharopoulos et al. show this relationship between linear transformers and recurrent networks. This state cost describes stepwise inference: during training autograd may retain states or activations for backward. Materializing every outer product and applying cumsum creates a tensor, so it does not automatically inherit inference recurrence’s constant memory.
A batch of independent sequences maintains state per sequence and head. Reset it for a new conversation; accidental reuse would mix histories. To process a fragment of an existing conversation, pass the previous fragment’s final state and preserve causal order. Saving that state permits continuation without repeating the prefix, but cannot reconstruct individual keys and values already summed.
Proof
import numpy as np
def phi(x):
return np.where(x > 0, x + 1, np.exp(np.minimum(x,0)))
def local(Q,K,V,w):
T,d=Q.shape
scores=Q @ K.T/np.sqrt(d)
i=np.arange(T)[:,None]; j=np.arange(T)[None,:]
mask=(j<=i)&(j>=i-w+1)
scores=np.where(mask,scores,-np.inf)
p=np.exp(scores-scores.max(axis=1,keepdims=True)); p/=p.sum(axis=1,keepdims=True)
return p @ V
def linear_parallel(Q,K,V):
q,k=phi(Q),phi(K)
weights=q @ k.T
weights=np.tril(weights)
return (weights @ V)/weights.sum(axis=1,keepdims=True)
def linear_recurrent(Q,K,V):
q,k=phi(Q),phi(K)
S=np.zeros((q.shape[1],V.shape[1])); z=np.zeros(q.shape[1]); out=[]
for qt,kt,vt in zip(q,k,V):
S+=np.outer(kt,vt); z+=kt
out.append(qt @ S/(qt @ z))
return np.array(out)
rng=np.random.default_rng(16)
Q,K,V=rng.normal(size=(9,4)),rng.normal(size=(9,4)),rng.normal(size=(9,3))
parallel=linear_parallel(Q,K,V); recurrent=linear_recurrent(Q,K,V)
print('error paralelo/recurrente:',np.max(np.abs(parallel-recurrent)))
assert np.allclose(parallel,recurrent,atol=1e-12)
assert np.allclose(local(Q,K,V,1),V)
future=V.copy(); future[6:]+=100
assert np.allclose(local(Q,K,V,3)[:6],local(Q,K,future,3)[:6])
assert np.allclose(linear_recurrent(Q,K,V)[:6],linear_recurrent(Q,K,future)[:6])
print('ventana de una posición y causalidad comprobadas')Positive random features
In random-feature attention, the softmax kernel can be approximated using Gaussian vectors and . Expected inner product is ; for the usual factor transform and . The estimated kernel mean is unbiased under these assumptions, but the normalized quotient need not be an unbiased output estimator.
The identity follows from the moment-generating function of a standard Gaussian: . Multiplying by leaves . Each sample contributes a positive product and the average estimates that kernel. One estimated sum is then divided by another: the expectation of a ratio is generally not the ratio of expectations, even when both sums are unbiased.
Performer uses FAVOR+, positive and orthogonalized features to reduce variance. The next cell compares independent Gaussians with blocks of orthogonal directions and Gaussian radii, and normalizes output. This is a didactic positive-orthogonal-feature construction and does not reproduce every FAVOR+ optimization. For large vectors exponentials may overflow; production needs stabilization and appropriate numerical controls. Increasing raises cost and may reduce statistical error without promising monotonicity for one sample.
The same random-feature matrix must be applied to queries and keys for their product to estimate the desired kernel. Independent projections on both sides do not give the above identity. When testing an approximation, first compare the kernel and then normalized output with a dense reference: small entrywise error can amplify when the denominator is very small. Repeat seeds and consider outliers as well as averages. Orthogonalization and the paper’s guarantees concern specific constructions and assumptions, not every exponential transformation.
import numpy as np
rng=np.random.default_rng(11)
q=rng.normal(size=(5,4))*.4; k=rng.normal(size=(6,4))*.4
x=q/(4**.25); y=k/(4**.25)
exact=np.exp(x @ y.T)
def features(x,omega):
return np.exp(x @ omega.T-.5*(x*x).sum(axis=1,keepdims=True))/np.sqrt(len(omega))
omega=rng.normal(size=(4096,4))
approx=features(x,omega) @ features(y,omega).T
print('error medio absoluto del kernel:',np.mean(np.abs(exact-approx)))
assert np.isfinite(approx).all() and (approx>0).all()
def orthogonal_gaussians(m,d,rng):
blocks=[]
while len(blocks)*d < m:
matrix=rng.normal(size=(d,d))
Q,R=np.linalg.qr(matrix)
Q=Q*np.where(np.diag(R)>=0,1.,-1.)
radius=np.sqrt(rng.chisquare(d,size=d))
blocks.append(Q.T*radius[:,None])
return np.concatenate(blocks,axis=0)[:m]
omega_orth=orthogonal_gaussians(256,4,rng)
gram=omega_orth[:4] @ omega_orth[:4].T
assert np.allclose(gram-np.diag(np.diag(gram)),0,atol=1e-12)
ortho=features(x,omega_orth) @ features(y,omega_orth).T
V=rng.normal(size=(6,3))
reference=(exact/exact.sum(axis=1,keepdims=True)) @ V
output=(ortho/ortho.sum(axis=1,keepdims=True)) @ V
print('error medio kernel ortogonal:',np.mean(np.abs(exact-ortho)))
print('error máximo salida normalizada:',np.max(np.abs(reference-output)))
assert np.isfinite(output).all()Remembering associations
In associative recall, a sequence presents key-value pairs and later requests a key’s value. Dense attention can query past entries individually; a short window loses direct access to old pairs and fixed-dimensional recurrent memory combines many key contributions. This intuition alone does not predict a trained model’s accuracy. Zoology studies a multi-query task and warns of the distance between synthetic controls and real language.
The example below selects nonrepeating keys from a vocabulary of 32 and assigns independent values from another vocabulary of 32. It then adds four queries selected among presented keys and evaluates each against its value. Queries and values may repeat; accuracy is therefore the fraction of correct responses, not the number of distinct pairs retrieved. Validation generated with another seed avoids measuring only update batches, although it remains from the same synthetic distribution.
With window four and two layers, a query can have a path of up to seven positions including itself. Queries at the end may lose paths to older pairs, but each query’s distance from its pair varies. With linear attention each pair can contribute to state; the issue is separating its contribution from others sharing features. Neither access graph nor state size alone guarantees training learns the rule. Studying saturation would require more steps, seeds, sizes, and comparable quality controls.
Before training, consider a constructed case isolating a collision. Each integer key is represented by a one-hot vector whose active position is ; its value is another fixed-dimension-32 one-hot vector. If two keys share a feature, state sums both values in the same row. A query retrieves their average and deterministic tie-breaking chooses the smaller index. With distinct keys, values are retrieved and accuracy is ; state always has elements as changes. Features in this example are nonnegative and each query has at least one match, so the denominator is positive.
import numpy as np
def recall_modulo(n,m):
key_features=np.eye(m)[np.arange(n)%m]
values=np.eye(32)[:n]
S=key_features.T @ values
z=key_features.sum(axis=0)
outputs=(key_features @ S)/(key_features @ z)[:,None]
return np.argmax(outputs,axis=1),outputs
for m in (4,8,16):
for n in (2,4,8,16,32):
prediction,output=recall_modulo(n,m)
correct=np.sum(prediction==np.arange(n))
assert correct==min(n,m) and np.allclose(output.sum(axis=1),1)
print('m, pares, aciertos:',m,n,correct)This control identifies the exact cause of information loss: keys in one residue class have identical representations. It does not prove a learned ELU+1 or Performer model collides in the same way or follows this accuracy curve. Testing that requires training and evaluation, as in the next experiment.
The figure shows one run of the next lab on RTX 3060, PyTorch 2.11.0+cu128, with 200 updates per configuration, model seed 31, and fixed validation of 256 sequences with four queries each. There are 32 possible values, so uniform guessing has expected accuracy 3.125%. Queries in one sequence share pairs and are not independent observations. With four pairs and , observed accuracy was 22.46% dense, 13.67% local, 18.55% ELU+1, and 19.34% random features. With 16 pairs, the eight measurements lie between 4.20% and 5.86%. This one short run does not demonstrate a general method ordering or where a longer-trained model would saturate.
To check that training duration matters, a second 1000-step run with four pairs and obtained 100% dense, 27.64% local, 28.03% ELU+1, and 28.52% random features on the same validation. With 16 pairs, respective values were 14.26%, 4.39%, 12.60%, and 12.11%. The figure retains 200 steps and does not mix trials. Differences remain a one-seed result for models with potentially different budgets; they do not by themselves prove a capacity bound or general ranking.
When comparing application designs, separate quality, latency, and memory. A 4k-token chat that fits the budget can use dense attention with an efficient kernel and retain direct context access. A continuous transcript may benefit from bounded state or a window if the task tolerates loss of old detail. Searching for an exact quotation requires measuring retrieval specifically and perhaps using an external search strategy; favorable mean loss does not prove that ability. Hardware matters too: a better asymptotic order can lose to optimized matmul at the sizes actually used.
The graph shows time and peak memory as well as accuracy. Numbers describe this educational implementation and run, not just the abstract algorithm. Data batches, output layer, projections, optimizer, and whole model also consume memory. Local mode materializes the square to simplify code, and linear modes retain temporary training states; these curves therefore cannot establish that all local or linear kernels use more memory than dense attention. Repeat with an appropriate kernel, longer lengths, and comparable conditions before deciding.
This lab trains synthetic two-layer models with four queries per sequence. It generates unique keys, independent values, and fixed validation distinct from training batches. Local mode uses a four-position causal window; linear uses ELU+1 and random uses independent positive Gaussian features, not full orthogonal FAVOR+. Seeds and batches match per configuration, but parameter sizes can vary and are printed for checking. This is an educational associative-recall-inspired task, not a reproduction of Zoology.
By default each combination runs 200 updates; ORYON_STEPS allows shorter or longer trials. Peak is maximum allocated memory during training and includes model, data, gradients, and optimizer; it is not solely activation memory. Time includes batch preparation and first AdamW initialization after forward/backward warmup and can vary with shared load. Local mode constructs and masks the full square, so its time is not an optimized sparse kernel measurement. This control’s linear models materialize per-time states for autograd; they are not constant-memory training implementations. recall-results.json is generated in your working directory.
import json, math, os, time
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
assert torch.cuda.is_available(), 'se necesita CUDA'
device='cuda'
steps=int(os.environ.get('ORYON_STEPS','200'))
assert steps>0
def batch(pairs,batch_size,generator):
keys=torch.stack([torch.randperm(32,generator=generator)[:pairs] for _ in range(batch_size)])
values=torch.randint(32,(batch_size,pairs),generator=generator)
which=torch.randint(pairs,(batch_size,4),generator=generator)
query=keys.gather(1,which)
target=values.gather(1,which)
seq=torch.stack((keys,values+32),dim=-1).reshape(batch_size,2*pairs)
return torch.cat((seq,query),dim=1).to(device),target.to(device)
class Block(nn.Module):
def __init__(self,width,features,kind,seed):
super().__init__()
self.kind=kind; self.width=width; self.features=features
self.norm=nn.LayerNorm(width)
self.q=nn.Linear(width,features if kind=='linear' else width,bias=False)
self.k=nn.Linear(width,features if kind=='linear' else width,bias=False)
self.v=nn.Linear(width,width,bias=False); self.o=nn.Linear(width,width,bias=False)
self.mlp=nn.Sequential(nn.LayerNorm(width),nn.Linear(width,2*width),nn.GELU(),nn.Linear(2*width,width))
gen=torch.Generator().manual_seed(seed)
self.register_buffer('omega',torch.randn(width,features,generator=gen))
def forward(self,x):
y=self.norm(x); q,k,v=self.q(y),self.k(y),self.v(y)
t=x.shape[1]
if self.kind in ('dense','local'):
scores=q @ k.transpose(-1,-2)/math.sqrt(self.width)
i=torch.arange(t,device=x.device)[:,None]; j=torch.arange(t,device=x.device)[None,:]
mask=j<=i
if self.kind=='local': mask=mask & (j>=i-3)
out=torch.softmax(scores.masked_fill(~mask,float('-inf')),dim=-1) @ v
else:
if self.kind=='linear':
q=F.elu(q)+1; k=F.elu(k)+1
else:
q=q/(self.width**.25); k=k/(self.width**.25)
q=torch.exp(q @ self.omega-(q*q).sum(-1,keepdim=True)/2)/math.sqrt(self.features)
k=torch.exp(k @ self.omega-(k*k).sum(-1,keepdim=True)/2)/math.sqrt(self.features)
# Control de entrenamiento: materializa estados por tiempo para autograd.
state=(k.unsqueeze(-1)*v.unsqueeze(-2)).cumsum(dim=1)
z=k.cumsum(dim=1)
out=(q.unsqueeze(-2) @ state).squeeze(-2)/(q*z).sum(-1,keepdim=True).clamp_min(1e-9)
x=x+self.o(out)
return x+self.mlp(x)
class Model(nn.Module):
def __init__(self,kind,features):
super().__init__()
width=32
self.token=nn.Embedding(64,width); self.pos=nn.Embedding(36,width)
self.blocks=nn.ModuleList([Block(width,features,kind,17+i) for i in range(2)])
self.head=nn.Linear(width,32)
def forward(self,x):
x=self.token(x)+self.pos(torch.arange(x.shape[1],device=x.device))
for block in self.blocks: x=block(x)
return self.head(x[:,-4:])
results=[]
for pairs in (4,8,16):
for features in (16,32):
for kind in ('dense','local','linear','random'):
torch.manual_seed(31)
model=Model(kind,features).to(device)
opt=torch.optim.AdamW(model.parameters(),lr=.001)
train_gen=torch.Generator().manual_seed(500+pairs)
val_gen=torch.Generator().manual_seed(900+pairs)
val_x,val_y=batch(pairs,256,val_gen)
warm_gen=torch.Generator().manual_seed(1300+pairs)
warm_x,warm_y=batch(pairs,32,warm_gen)
F.cross_entropy(model(warm_x).reshape(-1,32),warm_y.reshape(-1)).backward()
opt.zero_grad(set_to_none=True)
torch.cuda.synchronize(); torch.cuda.reset_peak_memory_stats()
begin=time.perf_counter()
for _ in range(steps):
x,y=batch(pairs,32,train_gen)
opt.zero_grad(set_to_none=True)
loss=F.cross_entropy(model(x).reshape(-1,32),y.reshape(-1))
loss.backward(); opt.step()
torch.cuda.synchronize(); elapsed=time.perf_counter()-begin
peak_mib=torch.cuda.max_memory_allocated()/2**20
with torch.no_grad():
logits=model(val_x)
assert torch.isfinite(loss).item() and torch.isfinite(logits).all().item(), 'resultado no finito'
acc=(logits.argmax(-1)==val_y).float().mean().item()
row={'pairs':pairs,'features':features,'kind':kind,'steps':steps,
'accuracy':acc,'seconds':elapsed,'peak_mib':peak_mib,
'parameters':sum(p.numel() for p in model.parameters())}
results.append(row); print(row,flush=True)
del loss,logits,model,opt,val_x,val_y,warm_x,warm_y,x,y
Path('recall-results.json').write_text(json.dumps(results,indent=2),encoding='utf8')
npm run lab and open the connection link.Exercises
Step 1 of 3. What does S accumulate after t steps?
import numpy as np
def causal_linear_attention_recurrent(Q, K, V, phi):
pass