Module contents
Lesson 22 of 24Advanced 100 min

The limits of sequential processing and convolutional alternatives

Examine sequential dependencies, fixed-size recurrent memory, effective context, parallelizable recurrences, and causal convolutional alternatives.

After this lesson you can

  • Measure recurrent training and inference time across sequence lengths and batch sizes.
  • Probe effective language-model context by perturbing distant inputs.
  • Evaluate long syntactic dependencies in a recurrent language model.
  • Implement causal dilated convolution and compute a TCN receptive field.
  • Compare LSTM, QRNN, and TCN quality, speed, and memory on one task.

Before you start

Work and depth

An LSTM applies large multiplications at each step, but hth_t and ctc_t depend on previous states. The sequential bottleneck does not mean the entire GPU is always idle: examples, features, and operations within a step are parallelized. It means that for one sequence the dependency prevents simultaneous computation of all recurrent states. A larger batch can exploit more independent work, but increases memory and does not remove the temporal chain.

In an ideal graph of three recurrent layers with all inputs available and one time unit per cell, the wavefront needs T+3−1T+3-1 steps to produce the last upper state. Real hardware has fused kernels, launch, transfer, memory limits, and contention: that depth count does not predict milliseconds. Training adds backward computation. Autoregressive generation also depends on earlier selected tokens even when the prefix-processing network is convolutional.

The figure uses real synchronized timings and CUDA traces from a shared RTX 3060. Each configuration was measured five times after warmup; the median is shown. Traces are separate runs with extra overhead. Gaps between observed kernels from our process do not prove the whole GPU was idle, because transfers or other processes may run. The QRNN below keeps pooling in a Python loop: it is not an optimized kernel and cannot disprove fused-implementation improvements.

In the repeat with delay-eight copying as the timed loss, T=128T=128 and batch 8, median inference was 3.184 ms for LSTM, 43.449 ms for unfused QRNN, and 3.033 ms for TCN; forward-and-backward medians were 7.517, 159.339, and 6.731 ms. The process shared the GPU: these figures describe that run, not a definitive implementation comparison. Models have 12 424, 13 256, and 12 936 parameters: close but unequal. Quality was measured in a separate training run with the same objective.

InteractiveGPU and temporal dependence

A profiler capture records 9 process kernels between the first and last (4.01 ms). The bar shows their actual merged intervals; each model uses its own horizontal scale.

first kernellast kernel

The union covers 2.2 % of that interval in this trace. Gaps only indicate that this profile recorded no model kernels; transfers, CPU work or other GPU processes may exist. Profiling adds overhead and is not the same repetition as the timed median.

Model compared on delayed copy: accuracy 67.0 % after 500 steps. This is a synthetic task and one seed; it does not measure language quality.

Model
Length T
Batch B
Median inference3.18 ms
Forward + backward7.52 ms
Parameters12424
PyTorch peak allocated29.4 MiB
Actual timing and kernel trace by model, length, and batch. Each trace spans its first to last captured kernel.

What fits in the state

Fixed-size state memory compresses all history into a constant-dimensional vector before predicting the next token. With bb bits per coordinate and HH coordinates there are at most 2bH2^{bH} distinct states; different histories can share a state. This bound requires finite precision: an ideal fixed-dimensional real vector can encode infinitely many possibilities, and dimension alone gives no finite bit bound. Noise, precision, and learning make details harder to recover in a physical network. Encoder attention offers another route to consult the whole source, though it does not eliminate decoder dependencies.

Effective context is measured by interventions, not the theoretical limit. Khandelwal and colleagues studied LSTMs on Penn Treebank and WikiText-2: under their conditions they found average use around 200 tokens and greater sensitivity to recent than distant order. These are results for those models and protocols, not a constant for every RNN. Shuffling a distant prefix retains words but changes order; replacing or removing them changes content or initial state too. If shuffling barely changes loss but removal does, content may help without exact order mattering much; controls are needed before attributing a mechanism.

The recorded curve comes from one epoch of the reduced m17-l15 variant, seed 17150, with 2 145 860 tokens and the lab’s WikiText-2 hashes. Full validation gave NLL 6.568 and perplexity 711.8; this model is undertrained, not the published AWD-LSTM result. On 128 held-out targets, original NLL was 6.554; retaining only the final token, shuffling the rest raised it 0.0007 nats, replacement 0.0019, and deletion 2.147. Deletion also resets a cold state, so it does not establish stored distant content. Do not extrapolate these values to a converged LSTM or other corpora.

InteractiveHow much context is used?

The vertical axis shows mean NLL change in nats; the scale fits the visible curves. Shuffle preserves the multiset of distant words; replace draws from training and drop resets state over the suffix. Differences can be negative in a finite sample. At d=128 the context is unchanged.

Intervention
Chart scale
Δ NLL con d=10.0007
Δ NLL con d=1280.0000
Original NLL6.5537
Actual change in nats per token on held-out WikiText-2 windows when perturbing only the prefix before the last d tokens.

Subject–verb agreement offers another test. Linzen and colleagues compared supervised LSTMs and language models on English agreement, including opposite-number attractor nouns. Spanish evaluation requires Spanish data and vocabulary: lesson 15’s reduced AWD-LSTM trained on English WikiText-2 and saved no weights for these tests. Its architecture is reconstructed and a separate English checkpoint generated; for the next figure another instance is trained on Spanish Tatoeba sentences. This measurement is not attributed to the English model or a standard agreement set.

InteractiveAgreement with attractors

las llaves del armario ...

es
0.868
son
0.132

Bars renormalize only between those two candidates; absolute probabilities appear below. All prefix tokens are in the vocabulary.

In all 16 prefixes the model prefers «es», including for plural subjects. The controls show a failure of this run, not a general estimate of syntactic competence.

Subject
Intervening phrase
Absolute P(es)0.0083
Absolute P(son)0.0013
P(es | es o son)0.868
Probabilities from the lab-trained Spanish model for es and son after controlled prefixes. Out-of-vocabulary words are marked.

Probabilities show model preferences between two candidates, not human grammatical judgment. A pair can also change through lexical frequency, gender, sentence naturalness, or unknown vocabulary. A syntactic conclusion needs many minimal pairs, varied subjects and verbs, a separate split, and analysis by attractor count. Two examples sharing a template are not a complete linguistic evaluation.

The recorded Spanish instance took 1 000 updates on Tatoeba sources with seed 2222 and SHA-256 07bb8aaaf1458abbcdc8a3a51ce5b9f8a2643c829dcb7c2a63b3fec8dde934dc. Its NLL was 4.889 nats per token on the first 9 999 validation targets. On the figure’s 16 prefixes it preferred es, even for plural subjects; armarios was out of vocabulary. This failure and limited domain prevent presenting the battery as evidence of general grammatical competence.

Gates and parallel convolutions

Parallelizable recurrences separate gate computation from the previous state. A QRNN computes zt,ft,otz_t,f_t,o_t in parallel by convolution over input, then applies per channel ct=ft⊙ct−1+(1−ft)⊙ztc_t=f_t\odot c_{t-1}+(1-f_t)\odot z_t and ht=ot⊙cth_t=o_t\odot c_t. This simplified recurrence still has temporal dependence, though parallel implementations or specialized kernels are possible. In an LSTM gates also depend on ht−1h_{t-1}; removing that dependence changes the function family. Bradbury and colleagues measured improvements with particular implementations, not a guarantee every QRNN loop is faster. SRU uses another lightweight recurrence with parallel matrix operations.

A dilated causal convolution with kernel kk and dilation dd computes yt=∑j=0k−1Wjxt−jd+by_t=\sum_{j=0}^{k-1}W_jx_{t-jd}+b, padding with zeros only on the left. For layers with dilation 1,2,4,…,2L−11,2,4,\ldots,2^{L-1} and one kernel per layer, the reach is R=1+(k−1)(2L−1)R=1+(k-1)(2^L-1). This counts the theoretical interval including padding; at a sequence edge fewer real inputs exist. Arbitrary dilations can leave gaps: maximum reach does not always count distinct reachable positions.

InteractiveDilated receptive field

Select an output; inputs it can depend on are highlighted. The theoretical field counts the maximum span, including padding before the start.

An input after the output is never highlighted: changing it cannot affect that causal output.

Dilation
32
4
2
31
Theoretical span16
Valid inputs reached16 / 32
Layers to cover T5 dilated; 31 undilated
Click an output to highlight reachable inputs; change layers, kernel, and dilation.

The cell implements causal convolution, backward, and a small TCN with dilations 1, 2, and 4. The synthetic task copies the symbol six positions earlier; a field of size eight can reach it. A short run checks flow; longer training must report its own results. The causality test changes the future and checks past outputs remain equal.

With 1 500 updates and one seed, the code achieved 1 280 of 1 280 held-out symbols on this synthetic task in both local NumPy and Pyodide. Convolution gradients were checked by central differences with maximum absolute error 1.81⋅10−101.81\cdot10^{-10}. This success is not extrapolated to linguistic dependencies.

[ ]Causal convolution and copyingBrowser
import numpy as np

def causal_conv(x,w,b,dilation):
    # x=(B,T,I), w=(K,I,O). w[0] acts on the current position.
    B,T,_=x.shape;K,_,O=w.shape;y=np.broadcast_to(b,(B,T,O)).copy()
    for j in range(K):
        shift=j*dilation
        if shift<T:y[:,shift:]+=x[:,:T-shift]@w[j]
    return y

def conv_backward(x,w,dy,dilation):
    B,T,_=x.shape;dw=np.zeros_like(w);dx=np.zeros_like(x)
    for j in range(len(w)):
        shift=j*dilation
        if shift<T:
            dw[j]=np.einsum('bti,bto->io',x[:,:T-shift],dy[:,shift:])
            dx[:,:T-shift]+=dy[:,shift:]@w[j].T
    return dx,dw,dy.sum(axis=(0,1))

def init(rng,width=8,classes=4):
    dims=[classes,width,width,width];p=[]
    for i in range(3):p.append([rng.normal(0,.25,(2,dims[i],dims[i+1])),np.full(dims[i+1],.1)])
    return p,[rng.normal(0,.25,(width,classes)),np.zeros(classes)]

def pass_tcn(x,p,out):
    caches=[]
    for i,(w,b) in enumerate(p):
        z=causal_conv(x,w,b,2**i);caches.append((x,z));x=np.maximum(z,0)
    return x@out[0]+out[1],caches,x

def train(steps=10,seed=22):
    rng=np.random.default_rng(seed);p,out=init(rng);classes=4;params=[a for pair in p for a in pair]+out
    m=[np.zeros_like(a) for a in params];v=[np.zeros_like(a) for a in params]
    for step in range(1,steps+1):
        values=rng.integers(0,classes,(32,16));x=np.eye(classes)[values];logits,caches,features=pass_tcn(x,p,out)
        z=logits[:,6:]-logits[:,6:].max(-1,keepdims=True);prob=np.exp(z);prob/=prob.sum(-1,keepdims=True)
        target=values[:,:-6];loss=-np.log(np.take_along_axis(prob,target[:,:,None],axis=2)+1e-15).mean()
        d=prob.copy();np.put_along_axis(d,target[:,:,None],np.take_along_axis(d,target[:,:,None],axis=2)-1,axis=2);d/=target.size
        dy=np.zeros_like(logits);dy[:,6:]=d;grads_out=[np.einsum('bti,bto->io',features,dy),dy.sum((0,1))];dx=dy@out[0].T;grads=[]
        for i in range(2,-1,-1):
            inp,pre=caches[i];dx=dx*(pre>0);dx,dw,db=conv_backward(inp,p[i][0],dx,2**i);grads.append([dw,db])
        grads=[a for pair in reversed(grads) for a in pair]+grads_out
        for j,(a,g) in enumerate(zip(params,grads)):
            m[j]=.9*m[j]+.1*g;v[j]=.999*v[j]+.001*g*g
            a-=.01*(m[j]/(1-.9**step))/(np.sqrt(v[j]/(1-.999**step))+1e-8)
    test=np.random.default_rng(2200).integers(0,classes,(128,16));pred=pass_tcn(np.eye(classes)[test],p,out)[0].argmax(-1)
    accuracy=np.mean(pred[:,6:]==test[:,:-6]);return p,out,float(loss),float(accuracy)

if __name__=='__main__':
    rng=np.random.default_rng(23);x=rng.normal(size=(2,12,3));w=rng.normal(size=(3,3,4));b=np.zeros(4)
    original=causal_conv(x,w,b,2);changed=x.copy();changed[:,8:]+=100
    assert np.allclose(original[:,:8],causal_conv(changed,w,b,2)[:,:8])
    p,out,loss,accuracy=train(10);print('Prueba de 10 pasos:',loss,accuracy)

WaveNet models audio autoregressively with causal convolutions; ByteNet and ConvS2S applied convolutional networks to sequences. Bai and colleagues compared TCNs and recurrences across tasks and observed greater effective memory for their configuration. Comparisons depend on hyperparameter search, parameters, regularization, and backend; synthetic copying does not establish universal superiority. A TCN can process training positions in parallel per layer, but generation of a new token needs the previous result.

Local laboratories

The measurement cell builds cuDNN LSTM, simple QRNN, and TCN with widths chosen for approximate parameter matching. It times inference and forward plus backward, synchronizing before and after; optimizer steps are excluded. Models train on the same delayed copy task without dropout and with the same step count. Parameter counts and allocated memory are shown, not assumed equal. CUDA trace is available only if the installed profiler captures kernels; profiling is not the same repeat as the timing median.

[ ]Time the architecturesLocal GPU
import json, os, time
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F

torch.set_num_threads(1);device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class LSTMNet(nn.Module):
    def __init__(self):
        super().__init__();self.emb=nn.Embedding(8,32);self.rnn=nn.LSTM(32,40,batch_first=True);self.head=nn.Linear(40,8)
    def forward(self,x):return self.head(self.rnn(self.emb(x))[0])
class QRNNNet(nn.Module):
    def __init__(self):
        super().__init__();self.emb=nn.Embedding(8,32);self.conv=nn.Conv1d(32,64*3,2);self.head=nn.Linear(64,8)
    def forward(self,x):
        u=self.conv(F.pad(self.emb(x).transpose(1,2),(1,0))).transpose(1,2);z,f,o=u.chunk(3,-1);z=z.tanh();f=f.sigmoid();o=o.sigmoid();c=torch.zeros_like(z[:,0]);states=[]
        for t in range(x.shape[1]):c=f[:,t]*c+(1-f[:,t])*z[:,t];states.append(o[:,t]*c)
        return self.head(torch.stack(states,1))
class TCNNet(nn.Module):
    def __init__(self):
        super().__init__();self.emb=nn.Embedding(8,32);self.layers=nn.ModuleList([nn.Conv1d(32,32,3,dilation=2**i) for i in range(4)]);self.head=nn.Linear(32,8)
    def forward(self,x):
        h=self.emb(x).transpose(1,2)
        for i,layer in enumerate(self.layers):h=h+F.relu(layer(F.pad(h,(2*(2**i),0))))
        return self.head(h.transpose(1,2))
models={'LSTM':LSTMNet,'QRNN':QRNNNet,'TCN':TCNNet}
def sync():
    if device.type=='cuda':torch.cuda.synchronize()
def measure(model,x,training,repeats=5):
    model.train(training)
    def step():
        if training:
            logits=model(x)
            loss=F.cross_entropy(logits[:,8:].reshape(-1,8),x[:,:-8].reshape(-1));model.zero_grad(set_to_none=True);loss.backward()
        else:
            with torch.no_grad():model(x)
    for _ in range(2):step()
    sync();times=[]
    for _ in range(repeats):
        start=time.perf_counter();step();sync();times.append(1000*(time.perf_counter()-start))
    return float(np.median(times))
def benchmark(lengths=(32,128,512),batches=(8,32),repeats=5):
    result=[]
    for name,ctor in models.items():
        torch.manual_seed(22);model=ctor().to(device)
        for T in lengths:
            for B in batches:
                x=torch.randint(0,8,(B,T),device=device)
                if device.type=='cuda':torch.cuda.reset_peak_memory_stats()
                inference=measure(model,x,False,repeats);training=measure(model,x,True,repeats)
                result.append({'model':name,'T':T,'B':B,'inference_ms':inference,'train_ms':training,'parameters':sum(p.numel() for p in model.parameters()),'peak_bytes':torch.cuda.max_memory_allocated() if device.type=='cuda' else None})
                print(name,'T',T,'B',B,'inferencia',round(inference,3),'entrenamiento',round(training,3),'ms',flush=True)
        del model
    return result
def copy_quality(steps=5):
    result=[]
    for name,ctor in models.items():
        torch.manual_seed(2201);gen=torch.Generator(device=device).manual_seed(2202);model=ctor().to(device);optim=torch.optim.Adam(model.parameters(),lr=.003)
        for step in range(steps):
            x=torch.randint(0,8,(32,32),generator=gen,device=device);logits=model(x);loss=F.cross_entropy(logits[:,8:].reshape(-1,8),x[:,:-8].reshape(-1))
            optim.zero_grad();loss.backward();nn.utils.clip_grad_norm_(model.parameters(),1.);optim.step()
        test=torch.randint(0,8,(256,32),generator=torch.Generator(device=device).manual_seed(2299),device=device)
        model.eval()
        with torch.no_grad():acc=float((model(test)[:,8:].argmax(-1)==test[:,:-8]).float().mean())
        result.append({'model':name,'steps':steps,'loss':float(loss.detach()),'accuracy':acc,'parameters':sum(p.numel() for p in model.parameters())})
        print('copia retrasada',name,steps,'acierto',round(acc,4),flush=True)
    return result
def profile_example():
    if device.type!='cuda':return []
    # The trace stores real CUDA kernels; unioning intervals avoids double counting overlaps.
    events=[];directory=Path(os.environ.get('PROFILE_DIR','trazas_cuda'));directory.mkdir(parents=True,exist_ok=True)
    for name,ctor in models.items():
        model=ctor().to(device).eval()
        for T in (32,128,512):
            for B in (8,32):
                x=torch.randint(0,8,(B,T),device=device)
                with torch.no_grad():
                    for _ in range(2):model(x)
                    sync()
                    with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU,torch.profiler.ProfilerActivity.CUDA]) as prof:model(x);sync()
                path=directory/f'{name}-{T}-{B}.json';prof.export_chrome_trace(str(path))
                with path.open(encoding='utf8') as f:trace=json.load(f)
                kernel=[e for e in trace['traceEvents'] if e.get('ph')=='X' and e.get('cat')=='kernel' and e.get('dur',0)>0]
                if not kernel:raise RuntimeError('El perfilador no ha registrado kernels CUDA')
                start=min(e['ts'] for e in kernel);end=max(e['ts']+e['dur'] for e in kernel)
                ranges=sorted((float(e['ts']-start),float(e['ts']-start+e['dur'])) for e in kernel);union=[]
                for a,z in ranges:
                    if union and a<=union[-1][1]:union[-1][1]=max(union[-1][1],z)
                    else:union.append([a,z])
                events.append({'model':name,'T':T,'B':B,'kernels':len(kernel),'span_us':end-start,'segments':union})
                print('perfil',name,T,B,'kernels',len(kernel),flush=True)
    return events
if __name__=='__main__':
    short=os.environ.get('BENCH_SHORT','1')=='1';lengths=(32,) if short else (32,128,512);batches=(8,) if short else (8,32)
    out={'device':str(device),'gpu':torch.cuda.get_device_name() if device.type=='cuda' else None,'torch':torch.__version__,'timings':benchmark(lengths,batches,1 if short else 5),'quality':copy_quality(5 if short else int(os.environ.get('COPY_STEPS','500'))),'profile':profile_example() if not short else []}
    if os.environ.get('BENCH_OUT'):
        with open(os.environ['BENCH_OUT'],'w',encoding='utf8') as f:json.dump(out,f,ensure_ascii=False)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The English model needs the checkpoint produced by the reproducible training below, based on m17-l15’s class and regularization. The original lab discards the best state at the end; this variant saves it with configuration and vocabulary. One epoch does not reproduce AWD-LSTM training or published results. WikiText-2 files have fixed revision and hashes; splits must not be mixed. ORYON_EPOCHS controls budget; a reader may start with a short check, but the graph records exactly the indicated run.

The cell defaults to ORYON_VERIFY_SHORT=1: two epochs of two steps, useful to check saving and probing but not to measure a trained model’s context. For the full corpus set ORYON_VERIFY_SHORT=0 before running and, for example, ORYON_EPOCHS=1; the checkpoint is saved to awd_checkpoint.pt or the path in AWD_CHECKPOINT. PyTorch, PyArrow, and huggingface_hub are needed, plus access to the fixed-revision files or a verified cache.

[ ]Train and save reduced AWDLocal GPU
import os
os.environ.setdefault('ORYON_VERIFY_SHORT','1')
"""AWD-LSTM reducido en WikiText-2: variantes y diagnósticos reales.

Fuente: Salesforce/wikitext, wikitext-2-raw-v1, revisión y hashes declarados.
La ficha enumera CC BY-SA 3.0 y GFDL, y su descripción menciona CC BY-SA 4.0;
consulta las condiciones antes de redistribuir. Requiere PyTorch, NumPy,
PyArrow y huggingface_hub. ORYON_VERIFY_SHORT=1 solo verifica el recorrido.
No reproduce las dimensiones, búsqueda, atado de pesos ni puntuación del paper.
"""
import hashlib
import json
import math
import os
import re
import time
import unicodedata
from collections import Counter
from contextlib import contextmanager
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
import torch
from torch import nn
import torch.nn.functional as F
from torch.func import functional_call
from huggingface_hub import hf_hub_download

torch.set_num_threads(1)
# La comprobación manual de puertas compara operaciones float32 con cuDNN.
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
OUT = Path(os.environ.get('ORYON_OUTPUT', 'awd_lstm_output'))
REV = 'b08601e04326c79dfdd32d625aee71d232d685c3'
FILES = {
    'train': ('wikitext-2-raw-v1/train-00000-of-00001.parquet',
              'e83889baabc497075506f91975be5fac0d45c5290b6b20582c8cd1e853d0c9f7'),
    'validation': ('wikitext-2-raw-v1/validation-00000-of-00001.parquet',
                   '204929b7ff9d6184953f867dedb860e40aa69c078fc1e54b3baaa8fb28511c4c'),
    'test': ('wikitext-2-raw-v1/test-00000-of-00001.parquet',
             '5f1bea067869d04849c0f975a2b29c4ff47d867f484f5010ea5e861eab246d91'),
}
PATTERN = re.compile(r"\w+(?:['’]\w+)*|[^\w\s]", re.UNICODE)
UNK, EOS = '<unk>', '</s>'
SEEDS = [17150] if SHORT else [17150, 17151, 17152]
DIM = 16 if SHORT else 256
BATCH = 4 if SHORT else 20
BPTT = 8 if SHORT else 35
EPOCHS = 2 if SHORT else int(os.environ.get('ORYON_EPOCHS', '10'))
MAX_STEPS = 2 if SHORT else None
VOCAB_CAP = 500 if SHORT else 20000
LR = .1
CLIP = .25
NONMONO = 2
BASE = {'weight_drop': .3, 'embedding_drop': .1, 'locked_drop': .2,
        'ar': .1, 'tar': .1, 'variable_bptt': True,
        'nt_asgd': True, 'adaptive': True}
ABLATIONS = [
    ('referencia', {}),
    ('sin_dropconnect', {'weight_drop': 0.}),
    ('sin_dropout_embedding', {'embedding_drop': 0.}),
    ('sin_dropout_bloqueado', {'locked_drop': 0.}),
    ('sin_ar', {'ar': 0.}),
    ('sin_tar', {'tar': 0.}),
    ('bptt_fijo', {'variable_bptt': False}),
    ('sin_asgd', {'nt_asgd': False}),
    ('softmax_completo', {'adaptive': False}),
]


def tokenize(text):
    return PATTERN.findall(unicodedata.normalize('NFC', text).lower())


def checked_file(split):
    name, expected = FILES[split]
    path = hf_hub_download(repo_id='Salesforce/wikitext', repo_type='dataset',
                           revision=REV, filename=name)
    digest = hashlib.sha256()
    with open(path, 'rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            digest.update(block)
    if digest.hexdigest() != expected:
        raise ValueError('SHA-256 inesperado: ' + name)
    return path


def data_and_vocab():
    owners, removed, data = {}, Counter(), {}
    limits = {'train': 3000, 'validation': 512, 'test': 512} if SHORT else {}
    for split in ('train', 'validation', 'test'):
        result, count = [], 0
        for batch in pq.ParquetFile(checked_file(split)).iter_batches(batch_size=64, columns=['text']):
            for text in batch.column(0).to_pylist():
                if split in limits and count >= limits[split]:
                    break
                words = tokenize(text or '')
                if not words:
                    continue
                key = hashlib.sha256('\0'.join(words).encode('utf-8')).hexdigest()
                if key in owners and owners[key] != split:
                    removed[split] += 1
                    continue
                # La huella identifica la fila completa; el recorte se aplica después.
                owners.setdefault(key, split)
                if split in limits:
                    words = words[:limits[split] - count]
                result.extend(words + [EOS])
                count += len(words)
            if split in limits and count >= limits[split]:
                break
        if len(result) <= BPTT + 1:
            raise ValueError('Partición insuficiente: ' + split)
        data[split] = result
    counts = Counter(data['train'])
    if UNK in counts:
        raise ValueError('Colisión del marcador UNK con el corpus')
    vocab = [UNK, EOS] + sorted((w for w in counts if w != EOS),
                                key=lambda w: (-counts[w], w))[:VOCAB_CAP-2]
    if len(vocab) < 12:
        raise ValueError('Se requieren al menos 12 palabras para softmax adaptativo')
    ids = {token: i for i, token in enumerate(vocab)}
    encoded = {k: torch.tensor([ids.get(w, 0) for w in words], dtype=torch.long)
               for k, words in data.items()}
    return vocab, encoded, dict(removed)


def batchify(data, batch_size):
    width = len(data) // batch_size
    if width < 2:
        raise ValueError('Se necesitan dos tokens por flujo')
    return data[:width * batch_size].reshape(batch_size, width).T.contiguous()


def locked_dropout(x, p, training):
    if not training or p == 0:
        return x
    if not 0 <= p < 1:
        raise ValueError('Probabilidad de dropout inválida')
    mask = F.dropout(torch.ones_like(x[:1]), p=p, training=True)
    return x * mask


class RecurrentLayer(nn.Module):
    def __init__(self, dim, weight_drop):
        super().__init__()
        self.rnn = nn.LSTM(dim, dim)
        self.weight_drop = weight_drop

    def forward(self, x, state, diagnostic=False):
        raw_weight = self.rnn.weight_hh_l0
        effective = F.dropout(raw_weight, p=self.weight_drop, training=self.training)
        # Una única matriz muestreada para todo este bloque temporal.
        if self.training and self.weight_drop:
            out, new_state = functional_call(self.rnn, {'weight_hh_l0': effective}, (x, state))
        else:
            out, new_state = self.rnn(x, state)
        observation = None
        if diagnostic:
            # Reconstrucción independiente de puertas de esta misma pasada.
            with torch.no_grad():
                if state is None:
                    h = x.new_zeros((x.shape[1], self.rnn.hidden_size))
                    c = torch.zeros_like(h)
                else:
                    h, c = state[0][0].detach(), state[1][0].detach()
                saturated, count = 0, 0
                for xt in x.detach():
                    z = F.linear(xt, self.rnn.weight_ih_l0, self.rnn.bias_ih_l0)
                    z += F.linear(h, effective.detach(), self.rnn.bias_hh_l0)
                    zi, zf, zg, zo = z.chunk(4, dim=1)
                    i, f, g, o = zi.sigmoid(), zf.sigmoid(), zg.tanh(), zo.sigmoid()
                    saturated += int(((f < .05) | (f > .95)).sum())
                    count += f.numel()
                    c = f*c + i*g
                    h = o*c.tanh()
                error = float((h - out[-1].detach()).abs().max())
                if not math.isfinite(error) or error > 2e-4:
                    raise AssertionError(('Puertas manuales no coinciden con LSTM', error))
                observation = {'forget_saturated_fraction': saturated / count,
                               'manual_last_state_max_error': error,
                               'layer': 0, 'criterion': 'f<0,05 o f>0,95'}
        return out, new_state, observation


class LanguageModel(nn.Module):
    def __init__(self, vocab_size, config):
        super().__init__()
        self.config = config.copy()
        self.embedding = nn.Embedding(vocab_size, DIM)
        self.layers = nn.ModuleList([RecurrentLayer(DIM, config['weight_drop']) for _ in range(3)])
        self.vocab_size = vocab_size
        self.cutoffs = None
        if config['adaptive']:
            a = max(2, vocab_size // 10)
            b = max(a + 1, vocab_size * 35 // 100)
            self.cutoffs = [a, min(b, vocab_size - 1)]
            self.decoder = nn.AdaptiveLogSoftmaxWithLoss(DIM, vocab_size, self.cutoffs, div_value=4.)
        else:
            self.decoder = nn.Linear(DIM, vocab_size)

    def forward(self, ids, states=None, diagnostic=False):
        states = [None] * len(self.layers) if states is None else states
        w = self.embedding.weight
        if self.training and self.config['embedding_drop']:
            mask = F.dropout(w.new_ones((w.shape[0], 1)),
                             p=self.config['embedding_drop'], training=True)
            w = w * mask
        x = F.embedding(ids, w)
        x = locked_dropout(x, self.config['locked_drop'], self.training)
        next_states, obs = [], None
        for j, layer in enumerate(self.layers):
            raw, state, observation = layer(x, states[j], diagnostic=(diagnostic and j == 0))
            next_states.append(state)
            if observation is not None:
                obs = observation
            x = locked_dropout(raw, self.config['locked_drop'], self.training)
        return x, raw, next_states, obs

    def nll(self, features, targets):
        flat = features.reshape(-1, features.shape[-1])
        y = targets.reshape(-1)
        if self.config['adaptive']:
            return self.decoder(flat, y).loss
        return F.cross_entropy(self.decoder(flat), y)


def detach_state(states):
    return [(h.detach(), c.detach()) for h, c in states]


def sync():
    if DEVICE.type == 'cuda':
        torch.cuda.synchronize(DEVICE)


@contextmanager
def averaged_weights(model, optimizer):
    """Usa ax de ASGD si existe; los parámetros sin gradiente conservan valor actual."""
    originals = []
    try:
        if isinstance(optimizer, torch.optim.ASGD):
            with torch.no_grad():
                for p in model.parameters():
                    average = optimizer.state.get(p, {}).get('ax')
                    if average is not None:
                        originals.append((p, p.detach().clone()))
                        p.copy_(average)
        yield
    finally:
        with torch.no_grad():
            for p, value in originals:
                p.copy_(value)


@torch.inference_mode()
def evaluate(model, data):
    model.eval()
    stream = batchify(data, 1).to(DEVICE)
    total, count, states = 0., 0, None
    for start in range(0, len(stream) - 1, BPTT):
        length = min(BPTT, len(stream) - 1 - start)
        x, target = stream[start:start+length], stream[start+1:start+length+1]
        features, _, states, _ = model(x, states)
        loss = model.nll(features, target)
        if not torch.isfinite(loss):
            raise ValueError('Pérdida de evaluación no finita')
        total += float(loss) * target.numel()
        count += target.numel()
    mean = total / count
    if mean > 700:
        raise ValueError('Perplejidad fuera de rango')
    return {'nats_per_token': mean, 'perplexity': math.exp(mean), 'tokens': count}


def check_masks():
    # Prueba sin depender de coincidencias aleatorias: los ceros se repiten en T.
    torch.manual_seed(17159)
    x = torch.ones(7, 4, 64)
    y = locked_dropout(x, .4, True)
    assert all(torch.equal(y[0], y[t]) for t in range(1, len(y)))
    assert torch.equal(locked_dropout(x, .4, False), x)
    # DropConnect recibe gradiente en el parámetro original.
    layer = RecurrentLayer(4, .3)
    parameter = layer.rnn.weight_hh_l0
    output, _, _ = layer(torch.randn(5, 3, 4), None)
    output.square().mean().backward()
    assert layer.rnn.weight_hh_l0 is parameter and parameter.grad is not None
    assert torch.isfinite(parameter.grad).all()


def run(seed, name, options, encoded, vocab_size):
    torch.manual_seed(seed)
    if DEVICE.type == 'cuda':
        torch.cuda.manual_seed_all(seed)
        torch.cuda.reset_peak_memory_stats(DEVICE)
    config = dict(BASE); config.update(options)
    model = LanguageModel(vocab_size, config).to(DEVICE)
    optimizer = torch.optim.SGD(model.parameters(), lr=LR)
    stream = batchify(encoded['train'], BATCH).to(DEVICE)
    rng = np.random.default_rng(seed + 1)
    best, best_state, best_epoch = math.inf, None, None
    val_history, history, training_seconds, trained_tokens = [], [], 0., 0
    switched = False
    for epoch in range(1, EPOCHS + 1):
        model.train()
        states, start, step = None, 0, 0
        sync(); began = time.perf_counter()
        while start < len(stream) - 1 and (MAX_STEPS is None or step < MAX_STEPS):
            length = BPTT
            if config['variable_bptt']:
                center = BPTT if rng.random() < .95 else BPTT / 2
                length = int(np.clip(round(rng.normal(center, max(1., BPTT / 8))),
                                     2, 2 * BPTT))
            length = min(length, len(stream) - 1 - start)
            x, y = stream[start:start+length], stream[start+1:start+length+1]
            states = None if states is None else detach_state(states)
            optimizer.zero_grad(set_to_none=True)
            features, raw, states, observation = model(x, states, diagnostic=(step == 0))
            nll = model.nll(features, y)
            ar = features.square().mean()
            tar = (raw[1:] - raw[:-1]).square().mean() if len(raw) > 1 else raw.new_zeros(())
            loss = nll + config['ar'] * ar + config['tar'] * tar
            if not torch.isfinite(loss):
                raise ValueError('Pérdida no finita')
            loss.backward()
            before = nn.utils.clip_grad_norm_(model.parameters(), CLIP, error_if_nonfinite=True)
            after = torch.sqrt(sum(p.grad.detach().square().sum() for p in model.parameters()
                                   if p.grad is not None))
            optimizer.step()
            step += 1
            trained_tokens += y.numel()
            if step == 1:
                history.append({'epoch': epoch, 'step': step, 'nll': float(nll.detach()),
                                'gradient_norm_before_clip': float(before),
                                'gradient_norm_after_clip': float(after),
                                'forget_sample': observation})
            start += length
            if step % 500 == 0: print("AWD época", epoch, "paso", step, "nll", float(nll.detach()), flush=True)
        sync(); training_seconds += time.perf_counter() - began
        with averaged_weights(model, optimizer):
            valid = evaluate(model, encoded['validation'])
            if valid['nats_per_token'] < best:
                best, best_epoch = valid['nats_per_token'], epoch
                best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
        val_history.append(valid)
        # Variante explícita de criterio no monótono: compara contra el mejor
        # valor anterior a las dos validaciones más recientes.
        should_switch = (len(val_history) > NONMONO and
                         valid['nats_per_token'] < math.inf and
                         valid['nats_per_token'] > min(v['nats_per_token']
                                                      for v in val_history[:-NONMONO]))
        # En SHORT se fuerza tras época 1 solo para cubrir el código ASGD.
        if SHORT and epoch == 1:
            should_switch = True
        if config['nt_asgd'] and not switched and should_switch:
            optimizer = torch.optim.ASGD(model.parameters(), lr=LR, t0=0, lambd=0.)
            switched = True
    if best_state is None:
        raise ValueError('No se seleccionó checkpoint')
    model.load_state_dict(best_state)
    test = evaluate(model, encoded['test'])
    peak = int(torch.cuda.max_memory_allocated(DEVICE)) if DEVICE.type == 'cuda' else None
    result = {'seed': seed, 'ablation': name, 'config': config,
              'parameters': sum(p.numel() for p in model.parameters()),
              'adaptive_cutoffs': model.cutoffs, 'validation': val_history,
              'selected_epoch': best_epoch, 'test_exploratory': test,
              'gradient_and_gate_samples': history, 'asgd_switched': switched,
              'asgd_forced_for_short': bool(SHORT and config['nt_asgd']),
              'training_tokens': trained_tokens,
              'training_seconds_synchronized': training_seconds,
              'training_tokens_per_second': trained_tokens / training_seconds,
              'gpu_peak_allocated_bytes': peak}
    torch.save({'state_dict':best_state,'config':config,'vocab':vocab,'dim':DIM,'seed':seed,'best_epoch':best_epoch,'validation':valid,'test':test}, os.environ.get('AWD_CHECKPOINT','awd_checkpoint.pt'))
    del model, optimizer, stream, best_state
    if DEVICE.type == 'cuda':
        torch.cuda.empty_cache()
    return result


def main():
    if EPOCHS < 1:
        raise ValueError('ORYON_EPOCHS debe ser positivo')
    check_masks()
    vocab, encoded, removed = data_and_vocab()
    OUT.mkdir(parents=True, exist_ok=True)
    payload = {'short': SHORT, 'source_revision': REV, 'file_sha256': FILES,
               'split': 'filas duplicadas exactas entre particiones excluidas; '
                        'coincidencias parciales no detectadas',
               'excluded': removed, 'vocab_size': len(vocab),
               'oov': {k: int((data == 0).sum()) for k, data in encoded.items()},
               'device': str(DEVICE), 'torch': torch.__version__, 'cuda': torch.version.cuda,
               'cudnn': torch.backends.cudnn.version(),
               'gpu': torch.cuda.get_device_name(DEVICE) if DEVICE.type == 'cuda' else None,
               'protocol': {'seeds': SEEDS, 'epochs': EPOCHS, 'batch': BATCH,
                            'bptt': BPTT, 'eval_batch': 1, 'eval_bptt': BPTT,
                            'eval_state': 'estado preservado entre bloques dentro de la partición',
                            'test': 'exploratorio tras selección en validación por configuración',
                            'timing': 'tiempo sincronizado de entrenamiento; incluye diagnóstico de puertas',
                            'memory': 'pico asignado por PyTorch, no uso global del dispositivo',
                            'asgd': 'criterio no monótono descrito en el código; SHORT fuerza el cambio',
                            'limitations': 'sin atado de pesos ni búsqueda original; no reproduce el paper'},
               'results': []}
    for seed in SEEDS:
        for name, options in ABLATIONS:
            row = run(seed, name, options, encoded, len(vocab))
            payload['results'].append(row)
            (OUT / 'results.json').write_text(json.dumps(payload, ensure_ascii=False, indent=2),
                                               encoding='utf-8')
            print(name, seed, 'validación', row['validation'],
                  'test exploratorio', row['test_exploratory'])
    print('Datos:', OUT / 'results.json')
    print('SHORT comprueba las rutas, no mide convergencia ni identifica ganadores.')


vocab,encoded,removed=data_and_vocab()
print("vocabulario",len(vocab),"tokens",{k:len(v) for k,v in encoded.items()},flush=True)
result=run(17150,"referencia",{},encoded,len(vocab))
print("resultado",json.dumps(result,ensure_ascii=False),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The probe uses the same 128 held-out targets in every condition and evaluates their log probability after up to 128 context tokens. Replacement draws training tokens, not a conditional linguistic distribution; deletion resets state. NLL difference can be negative due to sample noise. The figure records the real run, not a theoretical curve.

[ ]Perturb English contextLocal GPU
checkpoint=torch.load(os.environ.get('AWD_CHECKPOINT','awd_checkpoint.pt'),map_location='cpu',weights_only=False)
DIM=checkpoint['dim'];vocab,encoded,removed=data_and_vocab()
if vocab!=checkpoint['vocab']:raise ValueError('El vocabulario reconstruido difiere del checkpoint')
model=LanguageModel(len(vocab),checkpoint['config']).to(DEVICE);model.load_state_dict(checkpoint['state_dict']);model.eval()
rng=np.random.default_rng(2223);data=encoded['validation'].numpy();train_data=encoded['train'].numpy();N=128;L=128
starts=rng.integers(0,len(data)-L-1,size=N);contexts=np.stack([data[s:s+L] for s in starts]);targets=np.array([data[s+L] for s in starts]);target=torch.tensor(targets,device=DEVICE)
@torch.inference_mode()
def nll(inputs):
    x=torch.tensor(inputs.T,device=DEVICE,dtype=torch.long);features,_,_,_=model(x)
    logp=model.decoder.log_prob(features[-1]) if checkpoint['config']['adaptive'] else model.decoder(features[-1]).log_softmax(-1)
    return float(-logp[torch.arange(len(inputs),device=DEVICE),target].mean())
base=nll(contexts);results=[]
for distance in (1,8,16,32,64,128):
    prefix=L-distance;shuffled=contexts.copy();replaced=contexts.copy()
    for i in range(N):
        shuffled[i,:prefix]=rng.permutation(shuffled[i,:prefix])
        replaced[i,:prefix]=rng.choice(train_data,size=prefix,replace=True)
    vals={'distance':distance,'shuffle':nll(shuffled)-base,'replace':nll(replaced)-base,'drop':nll(contexts[:,-distance:])-base}
    results.append(vals);print('distancia',distance,vals,flush=True)
result={'source':'WikiText-2 validation','seed':2223,'base_nll':base,'n':N,'length':L,'rows':results,'checkpoint_epoch':checkpoint['best_epoch']}
if os.environ.get('CONTEXT_OUT'):Path(os.environ['CONTEXT_OUT']).write_text(json.dumps(result,ensure_ascii=False),encoding='utf8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second model trains in Spanish on Tatoeba sources with sentence-based splits and generates its own weights. It uses a reduced architecture related to m17-l15, not the English checkpoint. The control combinations form an illustrative prefix battery; OOV and absolute probabilities are shown alongside the normalized proportion between the two candidate verbs.

[ ]Train and test in SpanishLocal GPU
import io,zipfile,random,hashlib
archive=Path(os.environ.get('SEQ_DATA','spa-eng.zip')).read_bytes()
print('Tatoeba SHA-256:',hashlib.sha256(archive).hexdigest(),flush=True)
with zipfile.ZipFile(io.BytesIO(archive)) as z:rows=z.read('spa.txt').decode('utf8').splitlines()
groups={}
for row in rows:
    parts=row.split('\t')
    if len(parts)<3:continue
    es=tokenize(parts[1]);en=tokenize(parts[0])
    if 2<=len(es)<=18 and 2<=len(en)<=18:groups.setdefault(tuple(es),tuple(en))
keys=list(groups);random.Random(1717).shuffle(keys);trainkeys=keys[:30000];valkeys=keys[30000:32000];testkeys=keys[32000:34000]
counts=Counter(w for s in trainkeys for w in s);vocab=[UNK,EOS]+sorted((w for w in counts if w not in (UNK,EOS)),key=lambda w:(-counts[w],w))[:19998];ids={w:i for i,w in enumerate(vocab)}
assert 'es' in ids and 'son' in ids
def encode(keys):return torch.tensor([ids.get(w,0) for s in keys for w in (*s,EOS)],dtype=torch.long)
train=encode(trainkeys);valid=encode(valkeys);test=encode(testkeys)
DIM=128;cfg=dict(BASE);cfg['adaptive']=True;torch.manual_seed(2222);model=LanguageModel(len(vocab),cfg).to(DEVICE);opt=torch.optim.Adam(model.parameters(),lr=.001);gen=torch.Generator().manual_seed(2222)
steps=int(os.environ.get('SPANISH_STEPS','10'));T=35;B=32;model.train()
for step in range(steps):
    starts=torch.randint(0,len(train)-T-1,(B,),generator=gen);indices=starts[None,:]+torch.arange(T)[:,None]
    x=train[indices].to(DEVICE);y=train[indices+1].to(DEVICE);feat,raw,_,_=model(x);loss=model.nll(feat,y)+cfg['ar']*feat.square().mean()+cfg['tar']*(raw[1:]-raw[:-1]).square().mean()
    opt.zero_grad();loss.backward();nn.utils.clip_grad_norm_(model.parameters(),.25);opt.step()
    if (step+1)%500==0:print('español',step+1,'pérdida',round(float(loss.detach()),4),flush=True)
model.eval()
validation=evaluate(model,valid[:min(10000,len(valid))]);print('Validación, primer bloque de 10000 tokens:',validation,flush=True)
@torch.inference_mode()
def probability(prefix):
    words=tokenize(prefix);x=torch.tensor([[ids[EOS]]]+[[ids.get(w,0)] for w in words],device=DEVICE)
    feature,_,_,_=model(x);logp=model.decoder.log_prob(feature[-1]) if cfg['adaptive'] else model.decoder(feature[-1]).log_softmax(-1)
    return {'es':float(logp[0,ids['es']].exp()),'son':float(logp[0,ids['son']].exp()),'oov':[w for w in words if w not in ids]}
subjects=['la llave','las llaves','el gato','los gatos'];attractors=['','del armario','de los armarios','del vecino de los perros']
probes=[]
for s in subjects:
    for a in attractors:
        phrase=(s+' '+a).strip();v=probability(phrase);probes.append({'subject':s,'attractor':a,'prefix':phrase,**v})
print('Ejemplos:',json.dumps(probes[:2],ensure_ascii=False),flush=True)
checkpoint={'state_dict':model.state_dict(),'vocab':vocab,'config':cfg,'dim':DIM,'steps':steps,'seed':2222,'validation':validation,'archive_sha256':hashlib.sha256(archive).hexdigest()}
torch.save(checkpoint,os.environ.get('SPANISH_CHECKPOINT','spanish_checkpoint.pt'))
if os.environ.get('SPANISH_OUT'):
    Path(os.environ['SPANISH_OUT']).write_text(json.dumps({'steps':steps,'seed':2222,'validation':validation,'probes':probes},ensure_ascii=False),encoding='utf8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Attention in m18 can connect positions without a recurrent chain of TT states, but materialized global attention has quadratic length cost and autoregressive generation retains token dependence. Changing architecture moves bottlenecks; it does not remove every context or memory cost.

Exercises

Numeric
A stack has kernel 3 and one convolution per layer with dilations 1, 2, 4, 8, 16, and 32. What is the theoretical receptive-field size?
Proof
Prove: Derive the reach of a dilated causal stack.
0
Each layer has kernel k and layer l uses dilation 2ˡ, for l=0,...,L−1.

Step 1 of 3. How much does a layer with dilation d increase reach?

Numeric
With inputs available, one time unit per operation, and unlimited parallelism, how many sequential steps does the last token of a 3-layer stacked LSTM need for T=1024 using a wavefront?
Quiz
What permits more potential parallelism in a QRNN, and what changes relative to an LSTM?
Quiz
If shuffling distant context barely changes loss but removing it does, what interpretation is compatible?