Module contents
Lesson 21 of 22Research 105 min

Long context: extending RoPE and length generalization

Explore long-context extrapolation, RoPE scaling, attention sinks and measured retrieval.

After this lesson you can

  • Explain from the frequency spectrum why RoPE extrapolates poorly beyond training length.
  • Implement position interpolation, NTK-aware scaling and YaRN and compare loss at two and four times the original context.
  • Explain attention sinks and how StreamingLLM uses them for indefinite generation with a bounded cache.
  • Evaluate length generalization with and without positional encoding on algorithmic tasks.
  • Design a long-context evaluation that goes beyond average perplexity.

Before you start

Context is a distribution, not just a number

A model trained on 2048 tokens can receive a document of 32768 without a matrix multiplication preventing it. That does not mean it has learned to use it: relative distances, the number of competitors in the softmax and the relationships between clues and answers are different. Length generalization asks about behavior outside the training range; extending the declared window does not guarantee it.

In RoPE, pair jj rotates at frequency ωj=θ−2j/d\omega_j=\theta^{-2j/d} and position mm. When comparing query and key, the product depends on the displacement m−nm-n. If training covers positions 0,…,L−10,\dots,L-1, distances reach at most L−1L-1. For slow frequencies, greater distances can introduce phases that did not occur during training; fast frequencies make many rotations and their phase repeats. It is not correct to claim that every new angle causes a failure or that all pairs distinguish positions uniquely. The joint distribution of scores and the training matter.

InteractiveAngles and frequencies
  • Last trained angle
  • Last extended angle
Scaling
4
32
Pairs within the original discrete maximum0 / 16
Modified / original fast frequency0.250
Compare the maximum phase during training and in the extended context. Angles are not reduced modulo 2π; a larger phase alone does not demonstrate a model error.

Compressing without treating every frequency alike

Position interpolation applies m′=m/sm'=m/s, equivalent to ωj′=ωj/s\omega'_j=\omega_j/s. For an integer extension sLsL, the last position is sL−1sL-1 and transforms into L−1/sL-1/s: it lies within the continuous interval [0,L)[0,L), although it exceeds the last discrete position L−1L-1 when s>1s>1. If both discrete endpoints must match exactly, use m′=m(L−1)/(sL−1)m'=m(L-1)/(sL-1). Standard interpolation compresses distances and reduces resolution, particularly for fast local patterns. Chen et al. combine interpolation and fine-tuning; applying a formula without fine-tuning does not automatically reproduce their results.

NTK-aware scaling changes the base to θ′=θsd/(d−2)\theta'=\theta s^{d/(d-2)} for d>2d>2 and computes the frequencies with that base. The fastest pair keeps frequency one, while slower pairs are compressed more. The name does not imply that the learned function preserves its kernel exactly in every network.

The exponent follows by requiring the frequency of the last pair to decrease by ss. Since its exponent is (d−2)/d(d-2)/d, the condition is (θ′)−(d−2)/d=θ−(d−2)/d/s(\theta')^{-(d-2)/d}=\theta^{-(d-2)/d}/s. Solving gives the stated base. Unlike PI, the pair at index zero keeps ω0=1\omega_0=1: this local scale is preserved, but intermediate frequencies change gradually. The comparison controls only the spectrum; it does not control what the query and key projections learned.

YaRN mixes interpolation and extrapolation according to the number of rotations each frequency makes in the original context. If rj=Lωj/(2π)r_j=L\omega_j/(2\pi), with thresholds α<β\alpha<\beta define

γj=clip⁡ ⁣(rj−αβ−α,0,1),ωj′=(1−γj)ωjs+γjωj.\gamma_j=\operatorname{clip}\!\left(\frac{r_j-\alpha}{\beta-\alpha},0,1\right),\qquad \omega'_j=(1-\gamma_j)\frac{\omega_j}{s}+\gamma_j\omega_j.

Frequencies with few rotations are interpolated; those with many rotations retain their frequency. One published parameterization uses α=1\alpha=1, β=32\beta=32 and multiplies logits by (1+0.1ln⁡s)2(1+0.1\ln s)^2: this is equivalent to scaling each of Q and K by 1+0.1ln⁡s1+0.1\ln s. This is an empirical recipe for the models studied, not a theorem of universal improvement. The same variant and scale must be applied during fine-tuning and evaluation. YaRN describes both the ramp and the temperature.

To understand temperature, fix logits zz and define pi(β)=eβzi/∑jeβzjp_i(\beta)=e^{\beta z_i}/\sum_j e^{\beta z_j}. Their entropy satisfies H(β)=log⁡Z−βEp[z]H(\beta)=\log Z-\beta\mathbb{E}_p[z] and dH/dβ=−βVar⁡p(z)≤0dH/d\beta=-\beta\operatorname{Var}_p(z)\le 0 when β≥0\beta\ge0. Increasing the multiplier concentrates that same row or leaves it unchanged if all logits are equal. Changing frequencies also changes the logits themselves: hence this derivation does not prove that complete YaRN always has lower entropy or better loss than another variant.

Cache, sinks and evaluation

In some models a large amount of attention mass is observed on initial tokens even when they do not appear to carry useful semantic content: these are attention sinks. One hypothesis is that they offer a stable destination when softmax must assign all its mass, but their presence and strength depend on model, head and context. StreamingLLM keeps a few initial tokens and a recent window in the KV cache; it removes the intermediate ones and keeps memory bounded. It can process a stream longer than the window, but cannot recover arbitrary information already evicted. Processing indefinitely should not be confused with retaining unlimited memory.

In a conventional cache with BB sequences, HH KV heads, NN positions, head dimension dhd_h and bb bytes per scalar, keys and values occupy approximately 2BHNdhb2BHN d_h b bytes per layer, before metadata and alignment. Limiting NN bounds that portion of memory; it does not eliminate the cost of computing the current token. When comparing retention of the start with a recent window, match the total number of positions and avoid attributing an improvement merely to having more memory. The way retained keys are assigned positions must also be consistent with the positional scheme used.

The local experiment stores attention from the first head of the first layer of the mini Llama and compares a 64-position cache that keeps the start with another that keeps only recent positions. In this run perplexity was 14.1855 and 14.1976 respectively over 512 predictions. The difference is small: it does not demonstrate a collapse when the first token is evicted or that this head is a sink. Cache positions retain their original absolute indices.

InteractiveInitial attention and a bounded window

Sampled rows ↓ · first 32 keys →

0
Methodbase, 2×
PPL with initial token14.186
PPL recent window14.198
Explore measured maps before and after fine-tuning, and compare the two caches with an equal budget. Color uses a square root to reveal small weights.

A model without explicit positional encoding retains a causal mask: positions have different available histories and can infer indirect positional information. This does not guarantee generalization on every task. Comparing copying and addition requires specifying the distribution, lengths seen, success criterion, sample size and seed. A result at length 60 does not demonstrate indefinite extrapolation. Haviv et al. and Kazemnejad et al. study these effects; RASP-L proposes a hypothesis about algorithms that generalize, not a guarantee about all training.

In this trial eight small models were trained, one for each combination of task and positional scheme, for 400 steps each, with inputs of lengths 4 to 20 and seed 51. Each point evaluates 32 new examples using greedy generation. In this recipe none produced a fully correct sequence at the evaluated lengths: it would not be legitimate to attribute to extrapolation a failure that also occurs at length 20. Token accuracy provides additional information, but does not turn a partial sequence into a correct solution. Absolute positions outside training are initialized embeddings that were not updated.

InteractiveDoes it generalize to greater length?
  • Absolute
  • RoPE
  • ALiBi
  • No position
Task
Metric
Training lengths4–20
Seed and steps51 · 400
Choose copying or addition and compare complete-sequence and token accuracy for the eight models actually trained. EOS termination counts in both metrics.

Low average loss can coexist with a wrong answer that depends on a fact located at the beginning. Evaluate loss by position bands, key retrieval with the clue in several positions and a distractor, and actual generation. Accompany accuracy with the number of examples and uncertainty intervals. A needle task measures the chosen distribution, not all document comprehension; keeping the initial token in cache is not the same as keeping the needle.

A useful retrieval test controls the distance between clue and query, the value vocabulary size and accidental matches with filler. Compare against chance and against a version without the clue; change the clue’s location without changing the expected answer. If the needle has been evicted from the cache, a correct answer could come from patterns or prior knowledge, so it is useful to use random values and keep training and evaluation separate. The local example is deliberately minimal: it measures probability and accuracy on synthetic markers, without pretending that this equals answering questions about a real document.

Lab: frequencies

The next cell inspects frequencies and a single synthetic attention row. Fixed random vectors isolate the geometry; the resulting entropy is not that of a trained model and does not by itself predict its loss.

[ ]PythonBrowser
import numpy as np

def frequencies(theta, d, scale, context, method, alpha=1, beta=32):
    if d < 4 or d % 2 or theta <= 1 or scale < 1 or context < 1:
        raise ValueError('parámetros inválidos')
    f = theta ** (-2 * np.arange(d // 2) / d)
    multiplier = 1.
    if method == 'pi':
        f = f / scale
    elif method == 'ntk':
        f = (theta * scale ** (d / (d - 2))) ** (-2 * np.arange(d // 2) / d)
    elif method == 'yarn':
        if not 0 <= alpha < beta:
            raise ValueError('umbrales inválidos')
        turns = context * f / (2 * np.pi)
        gamma = np.clip((turns - alpha) / (beta - alpha), 0, 1)
        f = (1 - gamma) * f / scale + gamma * f
        multiplier = (1 + .1 * np.log(scale)) ** 2
    elif method != 'base':
        raise ValueError('método desconocido')
    return f, multiplier

def diagnostic(method, scale, context=256, d=32, theta=10000):
    f, temperature = frequencies(theta, d, scale, context, method)
    n = int(scale * context)
    rng = np.random.default_rng(5)
    q, k = rng.normal(size=d).reshape(-1, 2), rng.normal(size=d).reshape(-1, 2)
    delta = np.arange(n) - (n - 1)
    angles = delta[:, None] * f[None, :]
    c, s = np.cos(angles), np.sin(angles)
    score = (q[:, 0] * (k[:, 0] * c - k[:, 1] * s)
           + q[:, 1] * (k[:, 0] * s + k[:, 1] * c)).sum(-1) / np.sqrt(d)
    score *= temperature
    p = np.exp(score - score.max()); p /= p.sum()
    entropy = -(p * np.log(np.maximum(p, 1e-300))).sum()
    return round(float((n-1) * f[-1]), 6), round(float(entropy / np.log(n)), 6)

for scale in (2, 4):
    for method in ('base', 'pi', 'ntk', 'yarn'):
        print(scale, method, diagnostic(method, scale))

Local lab: copying and addition

To reproduce the sweep, the next local cell trains from scratch and saves its eight results. With ORYON_LENGTH_DEVICE=cpu and ORYON_LENGTH_THREADS=1 it reproduces the recorded run; by default it uses CUDA. In copying, output bits use symbols distinct from input bits. In addition, each input symbol encodes two bits and carry propagates from least to most significant.

[ ]PythonLocal GPU
import json, math, os, random
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F

DEVICE=os.environ.get('ORYON_LENGTH_DEVICE','cuda')
assert DEVICE in ('cpu','cuda') and (DEVICE=='cpu' or torch.cuda.is_available())
if DEVICE=='cpu' and 'ORYON_LENGTH_THREADS' in os.environ:
    torch.set_num_threads(int(os.environ['ORYON_LENGTH_THREADS']))
SEP=4;ZERO=5;ONE=6;EOS=7;VOCAB=8

def make_examples(n,B,task,generator):
    a=torch.randint(0,2,(B,n),generator=generator);b=torch.randint(0,2,(B,n),generator=generator)
    if task=='copy': source=a;out=a+ZERO
    elif task=='addition':
        source=a+2*b;carry=torch.zeros(B,dtype=torch.long);values=[]
        for i in range(n):
            z=a[:,i]+b[:,i]+carry;values.append(z%2+ZERO);carry=z//2
        values.append(carry+ZERO);out=torch.stack(values,1)
    else:raise ValueError(task)
    target=torch.cat((out,torch.full((B,1),EOS)),1)
    inp=torch.cat((source,torch.full((B,1),SEP),target[:,:-1]),1)
    labels=torch.cat((torch.full((B,n),-100),target),1)
    return inp.to(DEVICE),labels.to(DEVICE),source.to(DEVICE),target.to(DEVICE)

def rotary(x):
    dh=x.shape[-1];freq=10000**(-torch.arange(0,dh,2,device=x.device,dtype=torch.float32)/dh)
    angle=torch.arange(x.shape[-2],device=x.device,dtype=torch.float32)[:,None]*freq[None,:]
    c,s=angle.cos(),angle.sin();a,b=x[...,::2],x[...,1::2]
    return torch.stack((a*c-b*s,a*s+b*c),dim=-1).flatten(-2)

class Block(nn.Module):
    def __init__(self,d=32,h=2,mode='rope'):
        super().__init__();self.h=h;self.mode=mode;self.n1=nn.LayerNorm(d);self.n2=nn.LayerNorm(d)
        self.qkv=nn.Linear(d,3*d);self.o=nn.Linear(d,d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d))
    def forward(self,x):
        b,t,d=x.shape;h=self.h;z=self.n1(x);q,k,v=self.qkv(z).chunk(3,-1)
        q,k,v=[a.reshape(b,t,h,d//h).transpose(1,2) for a in (q,k,v)]
        if self.mode=='rope':q,k=rotary(q),rotary(k)
        scores=q@k.transpose(-1,-2)/math.sqrt(d//h)
        i=torch.arange(t,device=x.device)[:,None];j=torch.arange(t,device=x.device)[None,:]
        if self.mode=='alibi':
            slopes=torch.tensor([2**-4,2**-8],device=x.device)[None,:,None,None]
            scores=scores-slopes*(i-j).clamp(min=0)
        scores=scores.masked_fill(j>i,float('-inf'));a=scores.softmax(-1)
        hval=(a@v).transpose(1,2).contiguous().reshape(b,t,d);x=x+self.o(hval)
        return x+self.ff(self.n2(x))

class Model(nn.Module):
    def __init__(self,mode,d=32):
        super().__init__();self.mode=mode;self.emb=nn.Embedding(VOCAB,d);self.pos=nn.Embedding(122,d) if mode=='absolute' else None
        self.blocks=nn.ModuleList([Block(d,2,mode) for _ in range(2)]);self.final=nn.LayerNorm(d);self.head=nn.Linear(d,VOCAB)
    def forward(self,x):
        z=self.emb(x)
        if self.pos is not None:z=z+self.pos(torch.arange(x.shape[1],device=x.device))[None,:,:]
        for block in self.blocks:z=block(z)
        return self.head(self.final(z))

@torch.no_grad()
def evaluate(model,task,n,B=32):
    model.eval();g=torch.Generator().manual_seed(4000+n);_,_,source,target=make_examples(n,B,task,g)
    x=torch.cat((source,torch.full((B,1),SEP,device=DEVICE,dtype=torch.long)),1);generated=[];done=torch.zeros(B,device=DEVICE,dtype=torch.bool)
    for _ in range(target.shape[1]):
        token=model(x)[:,-1].argmax(-1);token=torch.where(done,EOS,token);generated.append(token);done|=token==EOS;x=torch.cat((x,token[:,None]),1)
    pred=torch.stack(generated,1);return {'n':n,'token_accuracy':float((pred==target).float().mean()),'exact':float((pred==target).all(-1).float().mean()),'examples':B}

def train_one(task,mode,steps=400):
    torch.manual_seed(51)
    if DEVICE=='cuda':torch.cuda.manual_seed_all(51)
    rng=random.Random(51);g=torch.Generator().manual_seed(51)
    model=Model(mode).to(DEVICE);opt=torch.optim.AdamW(model.parameters(),lr=.001)
    for step in range(steps):
        n=rng.randint(4,20);x,y,_,_=make_examples(n,16,task,g);model.train()
        logits=model(x);loss=F.cross_entropy(logits.reshape(-1,VOCAB),y.reshape(-1),ignore_index=-100)
        opt.zero_grad(set_to_none=True);loss.backward();nn.utils.clip_grad_norm_(model.parameters(),1.0);opt.step()
        if (step+1)%100==0:print(task,mode,'paso',step+1,'pérdida',float(loss.detach()))
    metrics=[evaluate(model,task,n) for n in (20,30,40,50,60)]
    return {'task':task,'mode':mode,'steps':steps,'device':DEVICE,
            'threads':torch.get_num_threads() if DEVICE=='cpu' else None,
            'metrics':metrics,'parameters':sum(p.numel() for p in model.parameters())}

results=[]
for task in ('copy','addition'):
    for mode in ('absolute','rope','alibi','nope'):
        row=train_one(task,mode);results.append(row);print(row)
Path('algorithm-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.

Local lab: extending the mini Llama

Start from the files from lessons 11 to 13: corpus.txt, gpt_pytorch.py, gpt-pytorch-small.pt and mini-llama.pt, all in the working directory, or use the environment variables specified in lesson 13. Seed 11, rate 0.001 and the variant without QK-norm determine the initial checkpoint. By default it uses CUDA; ORYON_EXTEND_DEVICE=cpu and ORYON_EXTEND_THREADS=1 reproduce the CPU run. Results and checkpoints are saved in the current directory. It trains at length 256 and compares contexts 512 and 1024 before and after 20 fine-tuning steps. Retrieval tests use a marker, a value and synthetic filler; it was not specifically trained for them. The cache comparison uses the same 64 positions and first checks that incremental computation without evictions matches the full computation.

[ ]PythonLocal GPU
import os, math, json
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F


scope = {}
exec(Path(os.environ.get('ORYON_GPT_TORCH_CODE','gpt_pytorch.py')).read_text(encoding='utf-8'),scope)
path = Path(os.environ.get('ORYON_GPT_TORCH','gpt-pytorch-small.pt'))
corpus = Path(os.environ.get('ORYON_CORPUS','corpus.txt')).read_text(encoding='utf-8')
base, chars = scope['load_checkpoint'](path, map_location='cpu')
stoi = {c:i for i,c in enumerate(chars)}
assert all(c in stoi for c in corpus) and len(corpus)>4000
ids = torch.tensor([stoi[c] for c in corpus],dtype=torch.long)
split = int(len(ids)*0.8); train, valid = ids[:split],ids[split:]

class RMS(nn.Module):
    def __init__(self, weight):
        super().__init__(); self.weight = nn.Parameter(weight.detach().float().clone())
    def forward(self,x):
        return x*torch.rsqrt(x.float().square().mean(-1,keepdim=True)+1e-5)*self.weight

def rotate(z):
    d = z.shape[-1]
    assert d % 2 == 0
    freq = torch.exp(-math.log(10000)*torch.arange(0,d,2,device=z.device,dtype=z.dtype)/d)
    angles = torch.arange(z.shape[-2],device=z.device,dtype=z.dtype)[:,None]*freq
    c,s = angles.cos(),angles.sin()
    even,odd = z[...,0::2],z[...,1::2]
    return torch.stack((even*c-odd*s,even*s+odd*c),dim=-1).flatten(-2)

class ModernAttention(nn.Module):
    def __init__(self, original, width, heads, qknorm):
        super().__init__(); self.heads=heads; self.qknorm=qknorm; self.use_rope=True; self.cap=None
        for name in ('q','k','v','o'):
            layer = nn.Linear(width,width,bias=False)
            layer.weight.data.copy_(getattr(original,name).weight.detach().float())
            setattr(self,name,layer)
    def forward(self,x):
        b,t,d=x.shape; dh=d//self.heads
        def proj(layer): return layer(x).view(b,t,self.heads,dh).transpose(1,2)
        q,k,v=proj(self.q),proj(self.k),proj(self.v)
        if self.use_rope: q,k=rotate(q),rotate(k)
        if self.qknorm:
            q=F.normalize(q,dim=-1); k=F.normalize(k,dim=-1)
            scores=q@k.transpose(-2,-1)*math.sqrt(dh)
        else:
            scores=q@k.transpose(-2,-1)/math.sqrt(dh)
        if self.cap is not None: scores=self.cap*torch.tanh(scores/self.cap)
        mask=torch.ones((t,t),device=x.device,dtype=torch.bool).tril()
        scores=scores.masked_fill(~mask,float('-inf'))
        probs=scores.softmax(-1)
        self.max_logit=scores.masked_select(mask).abs().max().detach()
        self.entropy=-(probs*probs.clamp_min(1e-30).log()).sum(-1).mean().detach()
        out=(probs@v).transpose(1,2).contiguous().view(b,t,d)
        return self.o(out)

class ModernBlock(nn.Module):
    def __init__(self, old, width, heads, qknorm):
        super().__init__(); self.n1=RMS(old.n1.weight); self.n2=RMS(old.n2.weight)
        self.attn=ModernAttention(old.attn,width,heads,qknorm)
        hidden=math.ceil((8*width/3)/8)*8
        self.gate=nn.Linear(width,hidden,bias=False); self.up=nn.Linear(width,hidden,bias=False)
        self.down=nn.Linear(hidden,width,bias=False)
        for layer in (self.gate,self.up,self.down): nn.init.normal_(layer.weight,std=0.02)
    def forward(self,x):
        x=x+self.attn(self.n1(x)); z=self.n2(x)
        return x+self.down(F.silu(self.gate(z))*self.up(z))

class MiniLlama(nn.Module):
    def __init__(self, old, qknorm):
        super().__init__(); c=old.config
        self.token=nn.Embedding(c['vocab'],c['width'])
        self.token.weight.data.copy_(old.token.weight.detach().float())
        self.blocks=nn.ModuleList([ModernBlock(b,c['width'],c['heads'],qknorm) for b in old.blocks])
        self.final=RMS(old.final.weight)
        self.register_buffer('position_table',None)
    def logits(self,x):
        h=self.token(x)
        if self.position_table is not None: h=h+self.position_table[:x.shape[1]][None,:,:]
        for block in self.blocks: h=block(h)
        return F.linear(self.final(h),self.token.weight)
    def forward(self,x,y):
        logits=self.logits(x)
        return F.cross_entropy(logits.reshape(-1,logits.shape[-1]),y.reshape(-1))


import hashlib, time
import numpy as np
device=os.environ.get('ORYON_EXTEND_DEVICE','cuda')
assert device in ('cpu','cuda') and (device=='cpu' or torch.cuda.is_available())
if device=='cpu' and 'ORYON_EXTEND_THREADS' in os.environ:torch.set_num_threads(int(os.environ['ORYON_EXTEND_THREADS']))
rotate_original=rotate; globals13=ModernAttention.forward.__globals__

state=torch.load('mini-llama.pt',map_location='cpu',weights_only=True)
assert state['characters']==chars and not state['qknorm'] and state['config']==base.config
torch.manual_seed(101)
net=MiniLlama(base,False).to(device);net.load_state_dict(state['state_dict'],strict=True)
train=train.to(device);valid=valid.to(device);gen=torch.Generator(device=device).manual_seed(101)
print('checkpoint SHA256',hashlib.sha256(Path('mini-llama.pt').read_bytes()).hexdigest(),flush=True)

def set_rope(method,scale,context=256):
    def rotate(z):
        d=z.shape[-1]; j=torch.arange(0,d,2,device=z.device,dtype=z.dtype)
        freq=torch.exp(-math.log(10000)*j/d)
        if method=='pi':freq=freq/scale
        if method=='ntk':freq=torch.exp(-math.log(10000*scale**(d/(d-2)))*j/d)
        if method=='yarn':
            ramp=((context*freq/(2*math.pi)-1)/31).clamp(0,1)
            freq=freq*((1-ramp)/scale+ramp)
        angle=torch.arange(z.shape[-2],device=z.device,dtype=z.dtype)[:,None]*freq
        c,s=angle.cos(),angle.sin(); a,b=z[...,0::2],z[...,1::2]
        return torch.stack((a*c-b*s,a*s+b*c),dim=-1).flatten(-2)
    globals13['rotate']=rotate
    # La escala de logits equivale a multiplicar Q por el factor de temperatura.
    mult=(1+.1*math.log(scale))**2 if method=='yarn' else 1.
    for block in net.blocks:
        block.attn._temperature=mult
    return mult

def modify_temperature():
    original=ModernAttention.forward
    def forward(attn,x):
        b,t,d=x.shape;dh=d//attn.heads
        def project(layer):return layer(x).view(b,t,attn.heads,dh).transpose(1,2)
        q,k,v=project(attn.q),project(attn.k),project(attn.v)
        q,k=globals13['rotate'](q),globals13['rotate'](k)
        scores=q@k.transpose(-2,-1)/math.sqrt(dh)*attn._temperature
        mask=torch.ones((t,t),device=x.device,dtype=torch.bool).tril();probs=scores.masked_fill(~mask,float('-inf')).softmax(-1)
        attn.last_probs=probs.detach()
        return attn.o((probs@v).transpose(1,2).contiguous().view(b,t,d))
    ModernAttention.forward=forward
modify_temperature()

def train_steps(model,n,steps,lr,seed,stage):
    rng=torch.Generator(device=device).manual_seed(seed);opt=torch.optim.AdamW(model.parameters(),lr=lr)
    checkpoint=Path('checkpoint-'+stage+'.pt');model.train();losses=[];start=0
    if checkpoint.exists():
        saved=torch.load(checkpoint,map_location=device,weights_only=False)
        model.load_state_dict(saved['model']);opt.load_state_dict(saved['optimizer'])
        rng.set_state(saved['generator'].cpu());losses=saved['losses'];start=saved['step']
        print('reanuda',stage,start,flush=True)
    for step in range(start,steps):
        starts=torch.randint(len(train)-n-1,(2,),generator=rng,device=device)
        x=torch.stack([train[s:s+n] for s in starts]);y=torch.stack([train[s+1:s+n+1] for s in starts])
        loss=model(x,y);opt.zero_grad(set_to_none=True);loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),1.);opt.step();losses.append(float(loss.detach()))
        if (step+1)%min(50,steps)==0:
            print('longitud',n,'paso',step+1,'loss',losses[-1],flush=True)
            temporary=checkpoint.with_suffix('.tmp')
            torch.save({'step':step+1,'model':model.state_dict(),'optimizer':opt.state_dict(),
                        'generator':rng.get_state(),'losses':losses},temporary)
            temporary.replace(checkpoint)
            if Path('pause').exists():print('pausa tras guardar',checkpoint,flush=True);raise SystemExit(0)
    return losses

@torch.no_grad()
def evaluate(n):
    net.eval();x=valid[:n][None,:];y=valid[1:n+1][None,:];logits=net.logits(x)
    per=F.cross_entropy(logits.reshape(-1,len(chars)),y.reshape(-1),reduction='none').reshape(n)
    sections=[float(v.mean()) for v in torch.tensor_split(per,8)]
    matrix=net.blocks[0].attn.last_probs[0,0].float().cpu().numpy()
    return {'loss':float(per.mean()),'bins':sections,'attention':matrix[::max(1,n//32),:32].tolist()}

@torch.no_grad()
def retrieval(distance, trials=16):
    # Un marcador de clave, valor y separador; el relleno no contiene marcadores.
    # La tarea no formó parte del entrenamiento y se mide sin prometer éxito.
    key,sep=0,1
    values=torch.arange(2,2+trials,device=device)
    filler=torch.full((trials,distance),len(chars)-1,device=device,dtype=torch.long)
    prompt=torch.cat((torch.full((trials,1),key,device=device),values[:,None],
                      torch.full((trials,1),sep,device=device),filler,
                      torch.full((trials,1),key,device=device)),1)
    net.eval(); logits=torch.cat([net.logits(prompt[i:i+4])[:,-1] for i in range(0,trials,4)],0);p=logits.softmax(-1)
    return {'distance':distance,'trials':trials,'accuracy':float((p.argmax(-1)==values).float().mean()),
            'mean_probability':float(p.gather(1,values[:,None]).mean())}

@torch.no_grad()
def streaming(keep_sink,window=64,limit=512):
    # Caché KV real por capa, con índices globales y mismo presupuesto total.
    # Se conserva el primer token solo en la variante sink; el resto es reciente.
    net.eval(); caches=[{'k':None,'v':None,'positions':[]} for _ in net.blocks];losses=[]
    for t in range(limit):
        h=net.token(valid[t].reshape(1,1));pos=torch.tensor([t],device=device)
        for idx,block in enumerate(net.blocks):
            a=block.attn;z=block.n1(h);d=z.shape[-1];dh=d//a.heads
            def project(layer):return layer(z).view(1,1,a.heads,dh).transpose(1,2)
            q,k,v=project(a.q),project(a.k),project(a.v)
            f=torch.exp(-math.log(10000)*torch.arange(0,dh,2,device=device,dtype=q.dtype)/dh)
            ang=pos[:,None]*f;c,s=ang.cos(),ang.sin()
            def rotation(x):
                even,odd=x[...,0::2],x[...,1::2]
                return torch.stack((even*c-odd*s,even*s+odd*c),dim=-1).flatten(-2)
            q,k=rotation(q),rotation(k);cache=caches[idx]
            K=k if cache['k'] is None else torch.cat((cache['k'],k),-2)
            V=v if cache['v'] is None else torch.cat((cache['v'],v),-2)
            positions=cache['positions']+[t]
            if len(positions)>window:
                selected=([0]+list(range(len(positions)-(window-1),len(positions)))) if keep_sink else list(range(len(positions)-window,len(positions)))
                K,V=K[:,:,selected],V[:,:,selected];positions=[positions[i] for i in selected]
            cache.update(k=K,v=V,positions=positions)
            p=(q@K.transpose(-2,-1)/math.sqrt(dh)).softmax(-1)
            out=a.o((p@V).transpose(1,2).contiguous().view(1,1,d));h=h+out
            z=block.n2(h);h=h+block.down(F.silu(block.gate(z))*block.up(z))
        logits=F.linear(net.final(h),net.token.weight)
        losses.append(float(F.cross_entropy(logits.reshape(1,-1),valid[t+1].reshape(1))))
    return {'keep_sink':keep_sink,'window':window,'n':limit,'loss':sum(losses)/len(losses),
            'perplexity':math.exp(sum(losses)/len(losses)),'final_positions':caches[0]['positions']}

if __name__=='__main__':
    set_rope('base',1); history=train_steps(net,256,200,.0003,101,'base-256')
    base_state={k:v.detach().cpu().clone() for k,v in net.state_dict().items()}
    torch.save(base_state,'mini-llama-256.pt')
    print('SHA256 T256',hashlib.sha256(Path('mini-llama-256.pt').read_bytes()).hexdigest(),flush=True)
    result_path=Path('extension-results.json')
    results=json.loads(result_path.read_text(encoding='utf8')) if result_path.exists() else {'training':history,'rows':[]}
    # La comparación de cachés utiliza RoPE base y el mismo presupuesto de 64 claves.
    if 'streaming' not in results:
        full=evaluate(32)['loss'];cache=streaming(False,window=32,limit=32)['loss']
        assert abs(full-cache)<1e-4,(full,cache)
        print('KV frente a cálculo completo',full,cache,flush=True)
        results['streaming']=[streaming(True),streaming(False)]
        result_path.write_text(json.dumps(results),encoding='utf8')
    for scale in (2,4):
        for method in ('base','pi','ntk','yarn'):
            if any(row['scale']==scale and row['method']==method for row in results['rows']):continue
            net.load_state_dict(base_state);mult=set_rope(method,scale)
            before=evaluate(256*scale)
            before['retrieval']=[retrieval(distance) for distance in (32,128,256*scale-4)]
            finetune=train_steps(net,256*scale,20,.0001,201+scale,f'{method}-{scale}')
            after=evaluate(256*scale)
            after['retrieval']=[retrieval(distance) for distance in (32,128,256*scale-4)]
            row={'method':method,'scale':scale,'logit_multiplier':mult,'before':before,'after':after,'finetune':finetune}
            results['rows'].append(row)
            result_path.write_text(json.dumps(results),encoding='utf8')
            print(method,scale,'loss antes/después',before['loss'],after['loss'],flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The CPU run started from the regenerated checkpoint of lesson 13, trained for 200 steps at T=256T=256 and fine-tuned for 20 steps per method and scale. The SHA-256 hash of the 256-context checkpoint was 63964d3a85e4c99137a456d385d69717c2b5104056e678c271812e2da53c5d93. Loss is measured on a fixed held-out window, in nats per character; eight position bands are also saved.

Method512 before512 after1024 before1024 after
Unscaled2.66042.63862.67782.6523
PI2.67322.65222.69422.6701
NTK-aware2.66112.63852.67702.6523
YaRN2.65682.63462.68502.6528

The differences are small for a toy model and corpus; the ordering does not establish a general ranking. Synthetic retrieval achieved 0 of 16 at all distances and variants, before and after fine-tuning. The model was not trained in that key format, so this result does not separate forgetting from failure to learn the task. Incremental verification without evictions matched the full computation: losses 2.5759269 and 2.5759268. This illustrates why loss and retrieval must be measured separately, not that this recipe solves long contexts.

Exercises

Numeric
For θ=10000, d=128 and an extension from 4096 to 16384, calculate the new NTK-aware base. Round to two decimal places.
Quiz
Which strategy best expresses the conditions for an extension?
Code
Implement yarn_frequencies(theta, d, scale, context, alpha=1, beta=32). Return the d/2 frequencies using the ramp described in the text. context is the original length, needed to calculate the number of rotations. Reject invalid parameters.
import numpy as np
def yarn_frequencies(theta,d,scale,context,alpha=1,beta=32):
  pass
Shift+Enter to run
Proof
Prove: Prove the continuous bound of standard interpolation and explain its local cost.
0
The original context uses indices 0 to L−1 and the extended context 0 to sL−1, with integer s greater than 1.

Step 1 of 3. What is the largest interpolated position?

Key idea
A longer window and lower loss are different outcomes from retrieving distant information. Compare methods under the same conditions, including fine-tuning, positions, cache and task.