Module contents
Lesson 16 of 22Advanced 110 min

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

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 ii sees the last ww positions including itself. At length TT, valid pair count is ∑i=0T−1min⁡(i+1,w)\sum_{i=0}^{T-1}\min(i+1,w), of order TwTw when T≥wT\ge w. 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 ww entries per layer if the model uses only that window.

For T≥wT\ge w, the sum is Tw−w(w−1)/2Tw-w(w-1)/2: initial rows do not yet have a full window. For example, eight positions and window three give 1+2+6⋅3=211+2+6\cdot3=21 pairs, versus 36 for a dense causal mask. If window size grows proportionally with TT, the count becomes quadratic again; “local” is linear in length only when ww 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 w−1w-1 preceding positions, after LL layers the final position can depend on up to 1+L(w−1)1+L(w-1) positions, bounded by available length. This count includes the current position and assumes equal contiguous windows with no additional paths. For L=32L=32 and w=4096w=4096 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.

InteractiveMask and receptive field
015015key
3
1
2
Positions reachable from 155
Indices11, 12, 13, 14, 15
The query row looks at earlier columns. The figure propagates dependencies of position 15 backward for the chosen number of layers; additional jumps are deterministic.

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 gg global positions that all queries can read typically adds work proportional to TgTg; if gg grows with TT, 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 ϕ(q),ϕ(k)∈Rm\phi(\vb q),\phi(\vb k)\in\R^m with a nonnegative product as weight. For Q′,K′∈RT×m\mat{Q}',\mat{K}'\in\R^{T\times m} and V∈RT×dv\mat V\in\R^{T\times d_v}, without a mask, the numerator can be calculated as

(Q′K′⊤)V=Q′(K′⊤V).(\mat Q'\mat K'\T)\mat V=\mat Q'(\mat K'\T\mat V).

The first order constructs a T×TT\times T matrix; the second constructs m×dvm\times d_v. Counting multiplication and addition as two FLOPs, their principal products cost approximately 2T2(m+dv)2T^2(m+d_v) and 4Tmdv4Tmd_v respectively. Feature construction, normalization, and input projection costs are additional. Associative order is linear in TT if mm and dvd_v remain fixed, but is not necessarily faster for short sequences on a GPU.

To make the output a weighted mean, divide each row by ϕ(qi)⊤∑jϕ(kj)\phi(\vb q_i)\T\sum_j\phi(\vb k_j). Omit it and scale changes with key count and magnitude. Choosing ϕ(x)=ELU⁡(x)+1\phi(x)=\operatorname{ELU}(x)+1 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 ϕ(qi)⊤ϕ(kj)\phi(\vb q_i)\T\phi(\vb k_j) 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 ϵ\epsilon to protect arithmetic also slightly changes normalization; declare it and test small-value cases.

The causal mask prevents simply using K′⊤V\mat K'\T\mat V 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 SS 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 m=32m=32 and dv=64d_v=64, for example, SS and zz store 32⋅64+32=208032\cdot64+32=2080 elements per head. Dense cache stores keys and values per position, and comparison requires fixing types and dimensions of both.

InteractiveTwo orders and a causal state

First order: (T × m) · (m × T) produces T × T; then multiply by T × 64.

Second order: (m × T) · (T × 64) produces m × 64; then multiply by T × m.

For the fixed query [1, 2], the state after 1 keys is S = [2, 4] and z = [1, 2]. The quotient (q · S)/(q · z) = 10/5.

1024
32
1
Order that materializes T × T0.201 GFLOPs
Associative order0.008 GFLOPs
Example causal output2.000
FLOP accounting excludes projections and normalization. The causal example uses four positive keys and a fixed query; advance to update S and z before division.

The recurrent form

With a causal mask, each query sees keys only through tt. The recurrent form maintains a matrix state and vector:

St=St−1+ϕ(kt)vt⊤,zt=zt−1+ϕ(kt),ot=ϕ(qt)⊤Stϕ(qt)⊤zt.\mat S_t=\mat S_{t-1}+\phi(\vb k_t)\vb v_t\T,\qquad \vb z_t=\vb z_{t-1}+\phi(\vb k_t),\qquad \vb o_t=\frac{\phi(\vb q_t)\T\mat S_t}{\phi(\vb q_t)\T\vb z_t}.

State occupies mdv+mmd_v+m elements per head independently of tt, and updating it costs O(mdv+m)\bigO(md_v+m) 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 T×m×dvT\times m\times d_v 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
By induction, St=∑j≤tϕ(kj)vj⊤\mat S_t=\sum_{j\le t}\phi(\vb k_j)\vb v_j\T and zt=∑j≤tϕ(kj)\vb z_t=\sum_{j\le t}\phi(\vb k_j). Multiplication by ϕ(qt)⊤\phi(\vb q_t)\T distributes over the sum and recovers the masked numerator and denominator. Equality requires a nonzero denominator; with strictly positive features and at least one valid key it is positive.∎
[ ]Window and causal linear attentionBrowser
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 ωr\omega_r and ϕr(x)=exp⁡(ωr⊤x−∥x∥2/2)/m\phi_r(\vb x)=\exp(\omega_r\T\vb x-\lVert\vb x\rVert^2/2)/\sqrt m. Expected inner product is ex⊤ye^{\vb x\T\vb y}; for the usual 1/d1/\sqrt d factor transform x=q/d1/4\vb x=\vb q/d^{1/4} and y=k/d1/4\vb y=\vb k/d^{1/4}. 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: E[eω⊤(x+y)]=e∥x+y∥2/2\mathbb E[e^{\omega\T(\vb x+\vb y)}]=e^{\lVert\vb x+\vb y\rVert^2/2}. Multiplying by e−(∥x∥2+∥y∥2)/2e^{-(\lVert\vb x\rVert^2+\lVert\vb y\rVert^2)/2} leaves ex⊤ye^{\vb x\T\vb y}. 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 mm 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.

[ ]Approximate the exponential kernelBrowser
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 ii is represented by a one-hot vector whose active position is i mod mi\bmod m; 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 n≤32n\le32 distinct keys, min⁡(n,m)\min(n,m) values are retrieved and accuracy is min⁡(n,m)/n\min(n,m)/n; state always has 32m+m32m+m elements as nn changes. Features in this example are nonnegative and each query has at least one match, so the denominator is positive.

InteractiveCollisions in a fixed memory
Feature 0
2 pairs
Feature 1
2 pairs
Feature 2
2 pairs
Feature 3
2 pairs
4
8
Pairs recovered4 de 8
Accuracy with this tie-break50.00 %
State S and z, elements132
Each box counts pairs sharing a feature. This construction uses dimension-32 values and index tie-breaking; it shows one interference mechanism, not a universal bound for all linear memories.
[ ]Check a memory with collisionsBrowser
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 m=16m=16, 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 m=16m=16 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.

InteractiveRecall in a short experiment
25.804816%key-value pairs

■ Dense■ Local■ ELU+1■ Random

Features m
Metric
0
Selected pairs4
Dense22.46 %
Local13.67 %
ELU+118.55 %
Random19.34 %
Chance for 32 values3.125 %
Change feature dimension and measure; each curve contains three lengths. Dense and local models do not use m, so their accuracies repeat. Peak includes all allocated tensors and time includes preparation and optimizer initialization on a shared GPU.

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.

[ ]Train and measure associative recallLocal GPU
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')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
A causal stack has 32 layers and each position attends to a contiguous window of 4096 positions including itself. What is the maximum receptive-field position count if the sequence is long enough?
Numeric
A causal linear head uses 32 features and values of dimension 64. How many elements do S and z store together?
Proof
Prove: Prove the recurrent form of normalized causal linear attention.
0
Features are positive, the sequence has at least one key, and S and z start at zero.

Step 1 of 3. What does S accumulate after t steps?

Quiz
A transcript must be processed as an unbounded stream and fixed memory matters more than exact retrieval of each old quotation. Which family merits testing?
Quiz
You must find an exact quotation in a book that fits context, and can afford dense attention. Which option retains direct access to all visible tokens?
Code
Implement causal_linear_attention_recurrent(Q, K, V, phi). Q and K have T rows; phi transforms each row into a positive vector of m features. Return normalized outputs using an accumulated matrix state and vector.
import numpy as np
def causal_linear_attention_recurrent(Q, K, V, phi):
  pass
Shift+Enter to run
Key idea
Sparsity changes the access graph; linear attention changes the kernel and compresses history into state. Both savings depend on what information the task needs.