Module contents
Lesson 10 of 24Core 110 min

Backpropagation through time: derivation, implementation and truncation

Derive backpropagation through time, truncated gradients, contiguous stream batching and RTRL costs.

After this lesson you can

  • Accumulate recurrent gradients across local and future loss paths.
  • Explain truncation boundaries and persistent hidden state.
  • Build contiguous batches without crossing stream boundaries.
  • Compare BPTT and RTRL under explicit compute and memory assumptions.

Before you start

A loss arriving by two paths

In the previous Recurrent neural network (Elman network), one cell consumed a sequence and produced states. A loss at the last character depends on the previous state, which depends on its predecessor: a decision several steps ago can affect the current prediction.

The unrolled graph makes those dependencies visible. Signal reaching a state has two sources: loss calculated there and future losses using it through recurrence. Each temporal copy contributes to the same parameter gradients; no independent matrix is trained per position.

InteractiveA local signal and a future signal

Scalar toy model: h₀=0.2, hₜ=tanh(0.8xₜ+u hₜ₋₁+0.1). Inputs are [1, 0, −1, 1] and targets [0, 0.4, −0.3, 0.2]. Each active loss is ½(hₜ−targetₜ)²; inactive losses are zero.

Backward t=4
lossh1δ1=0.91lossh2δ2=0.29lossh3δ3=0.19lossh4δ4=0.40t=10.072t=20.151t=30.096t=4−0.0750

At t=4: δₜ = 0.4009 local + 0.0000 from t+1 = 0.4009. After tanh, ∂L/∂zₜ = 0.2561; multiplying by hₜ₋₁ = −0.2935 contributes −0.0752 to ∂L/∂u.

Bars show signed contributions per transition. They sum algebraically, not as positive areas: ∂L/∂u = 0.0722 + 0.1511 + 0.0964 + −0.0752 = 0.2445. Changing a loss also changes contributions at earlier steps through the future signal.

0.7
Total loss0.3970
Local δ0.4009
δ from the future0.0000
Total gradient of u0.2445
Toggle losses and inspect signed contributions to the same recurrent weight.

Derive BPTT without losing a branch

Fix the previous lesson’s convention: row vectors and batch size BB. At each step,

At=XtWx+Ht−1Wh+b,Ht=tanh⁡(At),Zt=HtWy+c.A_t=X_tW_x+H_{t-1}W_h+b,\qquad H_t=\tanh(A_t),\qquad Z_t=H_tW_y+c.

Let Et=∂L/∂ZtE_t=\partial L/\partial Z_t and Dt=∂L/∂HtD_t=\partial L/\partial H_t be total derivatives. With mean cross-entropy over M>0M>0 targets and a binary mask, Et=mt⊙(Pt−Yt)/ME_t=m_t\odot(P_t-Y_t)/M, broadcasting the mask across classes. An arbitrary loss has its own output derivative. For backpropagation through time, with GT+1=0G_{T+1}=0:

Dt=EtWy⊤+Gt+1Wh⊤,Gt=Dt⊙(1−Ht⊙Ht).D_t=E_tW_y^\top+G_{t+1}W_h^\top,\qquad G_t=D_t\odot(1-H_t\odot H_t).

GtG_t has shape (B,H)(B,H) and differentiates with respect to preactivation AtA_t. The first sum term incorporates the local output branch; the second, HtH_t‘s effect on At+1A_{t+1}. If a local loss is masked, its EtE_t term is zero, but the future term can remain nonzero. At t=Tt=T the second branch does not exist.

Shared matrices receive all contributions using parameters from the same forward pass:

∂L∂Wh=∑t=1THt−1⊤Gt,∂L∂Wx=∑tXt⊤Gt,∂L∂b=∑t,bGt[b,:],∂L∂Wy=∑tHt⊤Et,∂L∂c=∑t,bEt[b,:],∂L∂H0=G1Wh⊤.\begin{aligned} \frac{\partial L}{\partial W_h}&=\sum_{t=1}^{T}H_{t-1}^{\top}G_t,& \frac{\partial L}{\partial W_x}&=\sum_t X_t^\top G_t,\\ \frac{\partial L}{\partial b}&=\sum_{t,b}G_t[b,:],& \frac{\partial L}{\partial W_y}&=\sum_t H_t^\top E_t,\\ \frac{\partial L}{\partial c}&=\sum_{t,b}E_t[b,:],& \frac{\partial L}{\partial H_0}&=G_1W_h^\top. \end{aligned}

With column vectors, the first expression is written ∑tGtHt−1⊤\sum_t G_tH_{t-1}^\top, for example. If XtX_t comes from an embedding table, each occurrence contributes to the same row: repeated indices must accumulate. A sum’s gradient does not become a mean unless the objective defines it so. Updating a weight before calculating every branch produces a different rule.

Gradient checking perturbs a shared parameter, recalculates the entire sequence and compares (L(θ+ϵ)−L(θ−ϵ))/(2ϵ)(L(\theta+\epsilon)-L(\theta-\epsilon))/(2\epsilon) with the analytic gradient. It should also cover H0H_0, multiple sequences, repeated indices and masked loss. Compare before clipping: global clipping changes the update vector and it is no longer the original derivative.

Cut the graph without resetting state

Truncated BPTT limits the history through which derivatives propagate. A common scheme updates every k1k_1 steps and backpropagates through up to k2k_2 transitions. There can be overlap if k2>k1k_2>k_1. Specify which losses are included and where the window starts: the same number pair alone does not describe every implementation detail.

The boundary retains a state value to continue the sequence but treats it as constant in backward. In PyTorch, detach() cuts that graph without zeroing state. Detaching once per block allows credit within the block; detaching at every step reduces it to one step. Without detaching or backpropagating over the entire history, the graph can grow from batch to batch. Shuffling blocks while retaining state swaps histories.

An exact case shows the difference. With h0=1h_0=1, ht=θht−1h_t=\theta h_{t-1} and loss L=h4L=h_4, forward gives θ4\theta^4. For θ=2\theta=2, the full gradient is 4θ3=324\theta^3=32. If you cut before the last two steps, treat h2=4h_2=4 as constant and differentiate θ2h2\theta^2h_2: the result is 16. Forward value is unchanged, but the derivative loses paths crossing the boundary.

Truncation approximates the full gradient. If omitted derivatives are small it may be acceptable; if a signal needs to cross the boundary, it can remove direct attribution to distant steps. It does not follow that a model always learns when k2k_2 covers a delay or necessarily fails in every other configuration: data, state, initialization and optimization also matter.

InteractiveA delay task with truncation

An actual scalar toy RNN: hₜ=tanh(w xₜ+u hₜ₋₁+b); a sigmoid head predicts xₜ₋L. It trains on 32 fixed values and evaluates on another 32; there are 29 scorable targets for this delay. Every change restarts from the same initialization and recomputes training.

0 %50 %100 %Epoch 012

Training: accuracy 62.1 %, loss 0.6608. The sequences are small and fixed: accuracy can change irregularly and does not demonstrate a universal rule about horizon.

SGD updates with learning rate 0.1 and global clipping at 3. At each update the prefix is recomputed with current parameters; losses in the k₁ block are summed and each backpropagates at most k₂ transitions. This demonstration stores the entire prefix history to simplify recomputation; the differentiated-transition counter does not measure actual time or memory.

3
4
4
12
Validation accuracy62.1 %
Validation loss0.6736
Updates96
Differentiated transitions1392
Train a deterministic scalar model and observe actual metrics on two toy sequences.

In this figure each update recalculates the prefix with current parameters and each loss backpropagates up to k2k_2 transitions. The next lab shows another variant with a shared window and persistent boundary state. These are explicit protocols, not interchangeable results merely because both are called truncation.

Batches as contiguous streams

To process contiguous streams, take an identifier vector, retain a multiple of BB and divide it into BB consecutive segments. Each row advances through its own segment. A block returns inputs and targets shifted one step within the same stream. Between consecutive blocks, row bb‘s state is passed to row bb of the next block.

InteractiveFrom corpus to streams

Fixed teaching sequence: a b c d e f g h i j k l m n o p q r s t u v w x. Each stream receives a contiguous fragment; the last token of a stream serves as a target but does not predict the first of the next stream. There is no remainder to discard.

Stream 1
abcdefgh
Input → target pairs: c → d · d → e
Stream 2
ijklmnop
Input → target pairs: k → l · l → m
Stream 3
qrstuvwx
Input → target pairs: s → t · t → u

Block order: 1, 2, 3, 4. The received state corresponds to each stream’s immediate prefix.

Blue boxes are block inputs; the next highlighted box is the last target. Between contiguous batches the state value is retained per stream and its gradient history is cut. The last batch may be shorter.

3
2
1
Tokens per stream8
Discarded tokens0
Pairs per stream in this batch2
State continuityYes
Observe pairs and boundaries and change order to see when state no longer matches.

A row’s last token can be a target without becoming a scored input in that row. Do not create an artificial pair between one row’s end and another’s start. If document boundaries exist, also define whether state resets and BOS and EOS are included; cutting a corpus into arbitrary blocks does not guarantee document independence. The final block can have fewer than TT positions.

Another differentiation direction: RTRL

Real-time recurrent learning propagates each state’s sensitivity to each parameter forward. In column convention, with ht=fθ(ht−1,xt)h_t=f_\theta(h_{t-1},x_t), define St=∂ht/∂θS_t=\partial h_t/\partial\theta. The chain rule gives

St=JtSt−1+∂fθ(h,xt)∂θ∣h=ht−1,Jt=∂ht∂ht−1.S_t=J_tS_{t-1}+\left.\frac{\partial f_\theta(h,x_t)}{\partial\theta}\right|_{h=h_{t-1}}, \qquad J_t=\frac{\partial h_t}{\partial h_{t-1}}.

A local loss contribution is obtained by contracting ∂ℓt/∂ht\partial\ell_t/\partial h_t with StS_t, plus any direct dependence of ℓt\ell_t on θ\theta. For a trajectory with fixed parameters, the result matches the full gradient when the same losses are accumulated. If parameters change during the trajectory, specify which online derivative is calculated; it is not automatically identified with the gradient of a single forward pass with fixed weights.

A dense recurrent matrix has order n2n^2 parameters. Sensitivity of nn states to them occupies O(n3)O(n^3) scalars; multiplying a dense Jacobian by that matrix costs O(n4)O(n^4) per step in the direct implementation. Dense BPTT needs O(Tn2)O(Tn^2) work and, without recomputation, O(Tn)O(Tn) stored states, in addition to parameters, outputs and optimizer. Approximations and sparse structure change these costs. Williams and Zipser introduced RTRL; Menick and colleagues study a sparse approximation.

InteractiveMemory and compute, not wall-clock time

We count scalars and dominant operations in a dense single-stream RNN with n² recurrent parameters. This is an order-of-growth model with unit coefficients, not a measurement of actual memory or speed.

Approximate memory, in scalars

10^7.212256n, logarithmic axis

Work per sequence, in arbitrary units

10^12.612256n, logarithmic axis
BPTT Non-overlapping truncation RTRL
Estimates for n=16, T=1024, k=32
MethodScalarsWork
BPTT16640262144
Non-overlapping truncation768262144
RTRL435267108864

Memory: n²+Tn, n²+kn, and n²+n³. Work: Tn², Tn², and Tn⁴. Input, output, optimizer, and constants are ignored; truncation uses non-overlapping blocks. Overlap and recomputation change the cost. In this model RTRL can store less than BPTT for sufficiently large T, although its work grows much faster; there is no universal rule about runtime.

4
10
5
State n16
Length T1024
Window k32
RTRL / BPTT work ratio256
Compare explicit orders for dense recurrence and a non-overlapping window.

RTRL memory may be smaller than storing an entire sequence if TT is large enough, but its compute cost grows faster with nn. Activation recomputation, hardware and constants matter: comparing orders does not prove an implementation is always faster.

Lab: NumPy and persistent state

The lab reuses real excerpts and functions from the current Recurrent language model cell. It checks derivatives of all parameters and initial state, continuity and mask; then uses AdaGrad or Adam with global clipping. Short size verifies the pipeline, not generated-sample quality.

Training uses k1=4k_1=4 and k2=8k_2=8: it recomputes the window with current weights and treats boundary state, which may come from earlier weights, as constant. Thus its gradient is not that of a single uncut forward pass. EOS resets the document; optimizer and seed are declared in output.

[ ]BPTT and optimization in NumPyBrowser
"""RNN de caracteres desde cero; fragmentos pequeños y sin acceso a red.

Miguel de Cervantes, Don Quijote, primera parte, capítulos I y II:
https://www.gutenberg.org/files/2000/2000-0.txt . Project Gutenberg declara
dominio público en EE. UU.; consulta la ley local y su política de marca:
https://www.gutenberg.org/policy/license.html .
Los fragmentos son demasiado pequeños para demostrar calidad de generación.
"""
import hashlib
import json
import math
import unicodedata

import numpy as np

TRAIN_TEXT = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
VALID_TEXT = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
SEED = 17090
UNK = '<unk>'
EOS = '</s>'


def prepare(train, valid):
    train = unicodedata.normalize('NFC', train).lower()
    valid = unicodedata.normalize('NFC', valid).lower()
    if len(train) < 2 or len(valid) < 2 or train == valid:
        raise ValueError('Los textos deben ser distintos y tener al menos dos caracteres')
    vocab = [UNK, EOS, *sorted(set(train))]
    index = {char: i for i, char in enumerate(vocab)}
    encode = lambda text: np.asarray([index.get(char, 0) for char in text], dtype=np.int64)
    return vocab, encode(train), encode(valid)


def initial_params(vocab_size, embed, hidden, seed):
    if vocab_size < 2 or embed < 1 or hidden < 1:
        raise ValueError('Dimensiones inválidas')
    rng = np.random.default_rng(seed)
    # BOS es una fila adicional solo de entrada; EOS sí es clase de salida.
    return {'E': rng.normal(0., .08, (vocab_size + 1, embed)),
            'Wx': rng.normal(0., .08, (embed, hidden)),
            'Wh': rng.normal(0., .08, (hidden, hidden)),
            'bh': np.zeros(hidden),
            'Wy': rng.normal(0., .08, (hidden, vocab_size)),
            'by': np.zeros(vocab_size)}


def rnn_forward(x, h0, params):
    """x=(B,T,d), h0=(B,H), salida=(B,T,H), caché por paso."""
    if x.ndim != 3 or x.shape[1] == 0 or h0.shape != (x.shape[0], params['Wh'].shape[0]):
        raise ValueError('Formas incorrectas o secuencia vacía')
    states, cache = [], []
    h = h0.copy()
    for t in range(x.shape[1]):
        previous = h
        h = np.tanh(x[:, t] @ params['Wx'] + previous @ params['Wh'] + params['bh'])
        cache.append((x[:, t], previous, h))
        states.append(h)
    return np.stack(states, axis=1), h, cache


def teacher_loss(params, ids, targets, h0, backward=False, mask=None):
    """Pérdida por token válido; los objetivos ocultos siguen siendo índices válidos.

    La máscara solo afecta a la pérdida, no detiene la transición de estado.
    """
    if ids.ndim != 2 or targets.shape != ids.shape:
        raise ValueError('Entradas y objetivos deben tener forma (B,T)')
    mask = np.ones(ids.shape, dtype=float) if mask is None else np.asarray(mask, dtype=float)
    if mask.shape != ids.shape or not np.all((mask == 0) | (mask == 1)) or mask.sum() == 0:
        raise ValueError('La máscara debe ser binaria, de forma (B,T) y no vacía')
    normalizer = float(mask.sum())
    x = params['E'][ids]
    states, last, cache = rnn_forward(x, h0, params)
    logits = states @ params['Wy'] + params['by']
    shifted = logits - logits.max(axis=2, keepdims=True)
    logz = np.log(np.exp(shifted).sum(axis=2, keepdims=True))
    selected = np.take_along_axis(shifted - logz, targets[..., None], axis=2)
    loss = -float(np.sum(selected[..., 0] * mask) / normalizer)
    if not backward:
        return loss, last
    B, T = ids.shape
    grad_logits = np.exp(shifted - logz)
    rows = np.arange(B)[:, None]
    cols = np.arange(T)[None, :]
    grad_logits[rows, cols, targets] -= 1.
    grad_logits *= mask[..., None] / normalizer
    grads = {name: np.zeros_like(value) for name, value in params.items()}
    grads['Wy'] = states.reshape(-1, states.shape[-1]).T @ grad_logits.reshape(-1, logits.shape[-1])
    grads['by'] = grad_logits.sum(axis=(0, 1))
    dh_next = np.zeros_like(h0)
    for t in range(T - 1, -1, -1):
        xt, previous, state = cache[t]
        dh = grad_logits[:, t] @ params['Wy'].T + dh_next
        da = dh * (1. - state * state)
        grads['Wx'] += xt.T @ da
        grads['Wh'] += previous.T @ da
        grads['bh'] += da.sum(axis=0)
        np.add.at(grads['E'], ids[:, t], da @ params['Wx'].T)
        dh_next = da @ params['Wh'].T
    return loss, last, grads, dh_next


def gradcheck():
    p = initial_params(4, 2, 3, SEED)
    ids = np.array([[4, 1, 2], [4, 1, 3]], dtype=np.int64)
    target = np.array([[1, 2, 3], [1, 3, 2]], dtype=np.int64)
    mask = np.array([[1., 1., 0.], [1., 1., 1.]])
    h0 = np.array([[.1, -.2, .05], [-.1, .1, .2]])
    _, _, grads, dh0 = teacher_loss(p, ids, target, h0, backward=True, mask=mask)
    alternate = target.copy()
    alternate[0, 2] = (alternate[0, 2] + 1) % len(p['by'])
    original_loss = teacher_loss(p, ids, target, h0, mask=mask)[0]
    alternate_loss = teacher_loss(p, ids, alternate, h0, mask=mask)[0]
    assert np.isclose(original_loss, alternate_loss, atol=1e-12)
    errors = {}
    for name, arr in [*p.items(), ('h0', h0)]:
        analytic = dh0 if name == 'h0' else grads[name]
        error = 0.
        for idx in np.ndindex(arr.shape):
            value = arr[idx]
            arr[idx] = value + 1e-6
            plus = teacher_loss(p, ids, target, h0, mask=mask)[0]
            arr[idx] = value - 1e-6
            minus = teacher_loss(p, ids, target, h0, mask=mask)[0]
            arr[idx] = value
            error = max(error, abs((plus - minus) / 2e-6 - analytic[idx]))
        assert error < 1e-7, (name, error)
        errors[name] = error
    return errors


def sample(params, vocab, prefix, count, seed):
    if count < 0:
        raise ValueError('La cantidad debe ser no negativa')
    rng = np.random.default_rng(seed)
    index = {char: i for i, char in enumerate(vocab)}
    h = np.zeros((1, len(params['bh'])))
    # BOS y cada símbolo del prefijo se procesan exactamente una vez.
    _, h, _ = rnn_forward(params['E'][np.array([[len(vocab)]])], h, params)
    for char in unicodedata.normalize('NFC', prefix).lower():
        value = index.get(char, 0)
        _, h, _ = rnn_forward(params['E'][np.array([[value]])], h, params)
    output, first_distribution, reason = [], None, 'límite'
    for _ in range(count):
        logits = (h @ params['Wy'] + params['by'])[0]
        weights = np.exp(logits - logits.max())
        weights /= weights.sum()
        if first_distribution is None:
            first_distribution = weights.tolist()
        choice = int(rng.choice(len(vocab), p=weights))
        if vocab[choice] == EOS:
            reason = 'eos'
            break
        output.append('�' if choice == 0 else vocab[choice])
        _, h, _ = rnn_forward(params['E'][np.array([[choice]])], h, params)
    return ''.join(output), first_distribution, reason


def sequence_events(sequence, bos, eos):
    """Entradas [BOS, contenido] y objetivos [contenido, EOS]."""
    return (np.concatenate(([bos], sequence)).astype(np.int64),
            np.concatenate((sequence, [eos])).astype(np.int64))


def sampler_check():
    vocab = [UNK, EOS, 'a', 'b']
    params = initial_params(len(vocab), 2, 3, SEED)
    params['Wy'][:] = 0.
    params['by'][:] = [0., 1000., 0., 0.]
    text, _, reason = sample(params, vocab, '', 3, SEED)
    assert text == '' and reason == 'eos'
    params['by'][:] = [0., 0., 1000., 0.]
    text, _, reason = sample(params, vocab, '', 3, SEED)
    assert text == 'aaa' and reason == 'límite'


def train_small(params, train, valid, steps=25, rate=.3):
    inputs, targets = sequence_events(train, len(params['by']), 1)
    valid_inputs, valid_targets = sequence_events(valid, len(params['by']), 1)
    inputs, targets = inputs[None, :], targets[None, :]
    h0 = np.zeros((1, len(params['bh'])))
    history = []
    for step in range(steps + 1):
        loss, _, grads, _ = teacher_loss(params, inputs, targets, h0, backward=True)
        if not math.isfinite(loss) or any(not np.isfinite(g).all() for g in grads.values()):
            raise ValueError('Pérdida o gradiente no finito')
        if step in (0, steps):
            val, _ = teacher_loss(params, valid_inputs[None, :], valid_targets[None, :], h0)
            history.append({'step': step, 'train_nats': loss, 'valid_nats': val})
        if step < steps:
            for name in params:
                params[name] -= rate * grads[name]
    return history


def main():
    vocab, train, valid = prepare(TRAIN_TEXT, VALID_TEXT)
    train_x, train_y = sequence_events(train, len(vocab), vocab.index(EOS))
    assert train_x[0] == len(vocab) and train_y[-1] == vocab.index(EOS)
    assert np.array_equal(train_x[1:], train_y[:-1])
    params = initial_params(len(vocab), embed=6, hidden=10, seed=SEED)
    print('Gradcheck por diferencias finitas:', gradcheck())
    sampler_check()
    history = train_small(params, train, valid)
    print('Tokens y OOV de validación:', len(train), len(valid), int(np.sum(valid == 0)))
    print('Vocabulario de entrenamiento:', vocab, '| entropía uniforme log(V):', math.log(len(vocab)))
    print('Pérdidas train y validación exploratoria:', history)
    sample_a = sample(params, vocab, prefix='en ', count=40, seed=SEED + 1)
    sample_b = sample(params, vocab, prefix='en ', count=40, seed=SEED + 1)
    assert sample_a == sample_b
    print('Generación ancestral reproducible:', sample_a[0], '| terminación:', sample_a[2])
    print('Distribución siguiente tras el prefijo:', sample_a[1])
    print('Modelo entrenado en la muestra, para inspección:',
          json.dumps({'vocab': vocab, 'bos_index': len(vocab), 'eos_index': vocab.index(EOS),
                      'params': {key: value.tolist() for key, value in params.items()}},
                     ensure_ascii=False))
    print('BOS es solo entrada; EOS es salida. OOV se convierte a UNK, que no tiene ejemplos positivos en entrenamiento.')
    print('La máscara pondera la pérdida, pero no detiene la evolución del estado en padding.')
    print('Cada documento reinicia el estado; validación y muestra no prueban calidad general.')
    print('SHA-256 de fragmentos UTF-8:',
          hashlib.sha256(TRAIN_TEXT.encode('utf-8')).hexdigest(),
          hashlib.sha256(VALID_TEXT.encode('utf-8')).hexdigest())


# Extensión para m17-l10. Las funciones anteriores son la celda de m17-l09.
def batchify(tokens, batch_size):
    """Divide en flujos contiguos de igual longitud; descarta el resto final."""
    tokens = np.asarray(tokens, dtype=np.int64)
    if tokens.ndim != 1 or batch_size < 1 or len(tokens) // batch_size < 2:
        raise ValueError('Se necesitan al menos dos tokens por flujo')
    length = len(tokens) // batch_size
    return tokens[:length * batch_size].reshape(batch_size, length)


def get_batch(streams, start, length):
    if streams.ndim != 2 or start < 0 or length < 1 or start >= streams.shape[1] - 1:
        raise ValueError('Bloque fuera del flujo')
    end = min(start + length, streams.shape[1] - 1)
    return streams[:, start:end], streams[:, start + 1:end + 1]


def optimizer_step(params, grads, state, method, rate, max_norm=1.):
    """Recorte global antes de actualizar; AdaGrad o Adam, no ambos a la vez."""
    norm = math.sqrt(sum(float(np.sum(g * g)) for g in grads.values()))
    if not math.isfinite(norm) or max_norm <= 0:
        raise ValueError('Gradiente o límite inválido')
    factor = min(1., max_norm / max(norm, 1e-30))
    state['step'] += 1
    for name in params:
        g = grads[name] * factor
        if method == 'adagrad':
            state['v'][name] += g * g
            params[name] -= rate * g / (np.sqrt(state['v'][name]) + 1e-8)
        elif method == 'adam':
            state['m'][name] = .9 * state['m'][name] + .1 * g
            state['v'][name] = .999 * state['v'][name] + .001 * g * g
            mh = state['m'][name] / (1 - .9 ** state['step'])
            vh = state['v'][name] / (1 - .999 ** state['step'])
            params[name] -= rate * mh / (np.sqrt(vh) + 1e-8)
        else:
            raise ValueError('Optimizador desconocido')
    return norm


def optimizer_state(params):
    return {'step': 0, 'm': {k: np.zeros_like(v) for k, v in params.items()},
            'v': {k: np.zeros_like(v) for k, v in params.items()}}


def trailing_gradient(params, ids, targets, boundary, recent):
    """Últimos `recent` errores sobre una ventana; boundary se trata como constante."""
    if ids.ndim != 2 or targets.shape != ids.shape or not 1 <= recent <= ids.shape[1]:
        raise ValueError('Ventana inválida')
    mask = np.zeros(ids.shape)
    mask[:, -recent:] = 1.
    return teacher_loss(params, ids, targets, boundary, backward=True, mask=mask)


def verify_bptt():
    print('Gradcheck de todos los pesos compartidos y h0:', gradcheck())
    p = initial_params(4, 2, 3, SEED)
    x = np.array([[4, 2, 3]], dtype=np.int64)
    y = np.array([[2, 3, 1]], dtype=np.int64)
    h = np.array([[.1, -.2, .05]])
    complete = teacher_loss(p, x, y, h, backward=True)
    window = trailing_gradient(p, x, y, h, 3)
    assert np.isclose(complete[0], window[0])
    for key in p:
        assert np.allclose(complete[2][key], window[2][key], atol=1e-12)
    assert np.allclose(complete[3], window[3], atol=1e-12)
    # Cambiar un objetivo enmascarado no afecta al gradiente ni a la pérdida.
    changed = y.copy()
    changed[0, 0] = 0
    first = trailing_gradient(p, x, y, h, 1)
    second = trailing_gradient(p, x, changed, h, 1)
    assert np.isclose(first[0], second[0], atol=1e-12)
    for key in p:
        assert np.allclose(first[2][key], second[2][key], atol=1e-12)
    stream = batchify(np.arange(20), 2)
    left_x, left_y = get_batch(stream, 0, 4)
    right_x, _ = get_batch(stream, 4, 4)
    assert np.array_equal(left_y[:, -1], right_x[:, 0])
    assert np.array_equal(left_x[0], [0, 1, 2, 3])
    assert np.array_equal(left_x[1], [10, 11, 12, 13])
    print('Ventana completa = BPTT completo; máscara y continuidad verificadas.')


def train_truncated(params, train, vocab, k1, k2, updates, method, log_every=100):
    """Estado online persistente; replay de hasta k2 pasos por actualización.

    Se guarda el estado anterior a cada transición. Al actualizar se recalcula
    la ventana con parámetros actuales y se tratan como constante su estado
    inicial y la historia anterior. Este estado frontera puede haberse generado
    con parámetros previos. No es el gradiente de un forward único sin corte.
    Las pérdidas de los últimos k1 pasos se cuentan una vez por actualización.
    """
    if not (1 <= k1 <= k2 and updates >= 1 and log_every >= 1):
        raise ValueError('Exige 1 <= k1 <= k2, actualizaciones y frecuencia positivas')
    inputs, targets = sequence_events(train, len(vocab), vocab.index(EOS))
    if len(inputs) < k1:
        raise ValueError('El fragmento debe contener al menos k1 eventos')
    state = optimizer_state(params)
    history, events, h = [], [], np.zeros((1, len(params['bh'])))
    position, consumed = 0, 0
    while state['step'] < updates:
        if position == len(inputs):
            # EOS termina el documento; BOS y estado nulo comienzan el siguiente.
            position, h, events, consumed = 0, np.zeros_like(h), [], 0
        token, target = int(inputs[position]), int(targets[position])
        boundary = h.copy()
        _, h, _ = rnn_forward(params['E'][np.array([[token]])], h, params)
        events.append((token, target, boundary))
        events = events[-k2:]
        position += 1
        consumed += 1
        if consumed == k1 or position == len(inputs):
            ids = np.array([[item[0] for item in events]], dtype=np.int64)
            ys = np.array([[item[1] for item in events]], dtype=np.int64)
            loss, _, grads, _ = trailing_gradient(params, ids, ys, events[0][2], consumed)
            before_clip = optimizer_step(params, grads, state, method, rate=.03)
            if state['step'] in (1, updates) or state['step'] % log_every == 0:
                text, _, reason = sample(params, vocab, prefix='en ', count=25,
                                         seed=SEED + state['step'])
                history.append({'step': state['step'], 'window': len(events),
                                'loss_terms': consumed, 'train_nats': loss,
                                'gradient_norm_before_clip': before_clip,
                                'sample': text, 'stop': reason})
            consumed = 0
    return history


def main_bptt():
    verify_bptt()
    vocab, train, valid = prepare(TRAIN_TEXT, VALID_TEXT)
    print('Fragmento real y vocabulario de l09; validación OOV:', int(np.sum(valid == 0)))
    print('Cada condición parte de la misma inicialización; no es benchmark de optimizadores.')
    for method in ('adagrad', 'adam'):
        p = initial_params(len(vocab), embed=6, hidden=10, seed=SEED)
        history = train_truncated(p, train, vocab, k1=4, k2=8, updates=12,
                                  method=method, log_every=4)
        valid_x, valid_y = sequence_events(valid, len(vocab), vocab.index(EOS))
        valid_loss, _ = teacher_loss(p, valid_x[None, :], valid_y[None, :],
                                     np.zeros((1, len(p['bh']))))
        print(method, history, '| validación nats:', valid_loss)
    print('Cada muestra es ancestral, acotada y termina antes si sale EOS.')
    print('La ventana solapada recalcula con pesos actuales; la frontera usa un estado previo separado.')
    print('Fragmentos diminutos: la pérdida y las muestras no demuestran calidad semántica.')


if __name__ == '__main__':
    main_bptt()

Lab: PyTorch and graph detachment

The local cell uses per-stream sequences, nn.RNN, comparison of states and gradients with NumPy in float64 and explicit state detachment between blocks. Training uses float32 and k1=k2k_1=k_2. For larger texts set both ORYON_TRAIN_FILE and ORYON_VALID_FILE to UTF-8 paths and record provenance and split. Code rejects identical texts but does not detect partial overlaps. Each epoch resets states and does not cross row boundaries.

ORYON_VERIFY_SHORT=1 reduces work to check the pipeline. Timings depend on device and load and are comparable only for the same work and protocol; this cell’s timings are not a browser comparison.

[ ]Parity and truncation with PyTorchLocal GPU
"""RNN de caracteres desde cero; fragmentos pequeños y sin acceso a red.

Miguel de Cervantes, Don Quijote, primera parte, capítulos I y II:
https://www.gutenberg.org/files/2000/2000-0.txt . Project Gutenberg declara
dominio público en EE. UU.; consulta la ley local y su política de marca:
https://www.gutenberg.org/policy/license.html .
Los fragmentos son demasiado pequeños para demostrar calidad de generación.
"""
import hashlib
import json
import math
import unicodedata

import numpy as np

TRAIN_TEXT = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
VALID_TEXT = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
SEED = 17090
UNK = '<unk>'
EOS = '</s>'


def prepare(train, valid):
    train = unicodedata.normalize('NFC', train).lower()
    valid = unicodedata.normalize('NFC', valid).lower()
    if len(train) < 2 or len(valid) < 2 or train == valid:
        raise ValueError('Los textos deben ser distintos y tener al menos dos caracteres')
    vocab = [UNK, EOS, *sorted(set(train))]
    index = {char: i for i, char in enumerate(vocab)}
    encode = lambda text: np.asarray([index.get(char, 0) for char in text], dtype=np.int64)
    return vocab, encode(train), encode(valid)


def initial_params(vocab_size, embed, hidden, seed):
    if vocab_size < 2 or embed < 1 or hidden < 1:
        raise ValueError('Dimensiones inválidas')
    rng = np.random.default_rng(seed)
    # BOS es una fila adicional solo de entrada; EOS sí es clase de salida.
    return {'E': rng.normal(0., .08, (vocab_size + 1, embed)),
            'Wx': rng.normal(0., .08, (embed, hidden)),
            'Wh': rng.normal(0., .08, (hidden, hidden)),
            'bh': np.zeros(hidden),
            'Wy': rng.normal(0., .08, (hidden, vocab_size)),
            'by': np.zeros(vocab_size)}


def rnn_forward(x, h0, params):
    """x=(B,T,d), h0=(B,H), salida=(B,T,H), caché por paso."""
    if x.ndim != 3 or x.shape[1] == 0 or h0.shape != (x.shape[0], params['Wh'].shape[0]):
        raise ValueError('Formas incorrectas o secuencia vacía')
    states, cache = [], []
    h = h0.copy()
    for t in range(x.shape[1]):
        previous = h
        h = np.tanh(x[:, t] @ params['Wx'] + previous @ params['Wh'] + params['bh'])
        cache.append((x[:, t], previous, h))
        states.append(h)
    return np.stack(states, axis=1), h, cache


def teacher_loss(params, ids, targets, h0, backward=False, mask=None):
    """Pérdida por token válido; los objetivos ocultos siguen siendo índices válidos.

    La máscara solo afecta a la pérdida, no detiene la transición de estado.
    """
    if ids.ndim != 2 or targets.shape != ids.shape:
        raise ValueError('Entradas y objetivos deben tener forma (B,T)')
    mask = np.ones(ids.shape, dtype=float) if mask is None else np.asarray(mask, dtype=float)
    if mask.shape != ids.shape or not np.all((mask == 0) | (mask == 1)) or mask.sum() == 0:
        raise ValueError('La máscara debe ser binaria, de forma (B,T) y no vacía')
    normalizer = float(mask.sum())
    x = params['E'][ids]
    states, last, cache = rnn_forward(x, h0, params)
    logits = states @ params['Wy'] + params['by']
    shifted = logits - logits.max(axis=2, keepdims=True)
    logz = np.log(np.exp(shifted).sum(axis=2, keepdims=True))
    selected = np.take_along_axis(shifted - logz, targets[..., None], axis=2)
    loss = -float(np.sum(selected[..., 0] * mask) / normalizer)
    if not backward:
        return loss, last
    B, T = ids.shape
    grad_logits = np.exp(shifted - logz)
    rows = np.arange(B)[:, None]
    cols = np.arange(T)[None, :]
    grad_logits[rows, cols, targets] -= 1.
    grad_logits *= mask[..., None] / normalizer
    grads = {name: np.zeros_like(value) for name, value in params.items()}
    grads['Wy'] = states.reshape(-1, states.shape[-1]).T @ grad_logits.reshape(-1, logits.shape[-1])
    grads['by'] = grad_logits.sum(axis=(0, 1))
    dh_next = np.zeros_like(h0)
    for t in range(T - 1, -1, -1):
        xt, previous, state = cache[t]
        dh = grad_logits[:, t] @ params['Wy'].T + dh_next
        da = dh * (1. - state * state)
        grads['Wx'] += xt.T @ da
        grads['Wh'] += previous.T @ da
        grads['bh'] += da.sum(axis=0)
        np.add.at(grads['E'], ids[:, t], da @ params['Wx'].T)
        dh_next = da @ params['Wh'].T
    return loss, last, grads, dh_next


def gradcheck():
    p = initial_params(4, 2, 3, SEED)
    ids = np.array([[4, 1, 2], [4, 1, 3]], dtype=np.int64)
    target = np.array([[1, 2, 3], [1, 3, 2]], dtype=np.int64)
    mask = np.array([[1., 1., 0.], [1., 1., 1.]])
    h0 = np.array([[.1, -.2, .05], [-.1, .1, .2]])
    _, _, grads, dh0 = teacher_loss(p, ids, target, h0, backward=True, mask=mask)
    alternate = target.copy()
    alternate[0, 2] = (alternate[0, 2] + 1) % len(p['by'])
    original_loss = teacher_loss(p, ids, target, h0, mask=mask)[0]
    alternate_loss = teacher_loss(p, ids, alternate, h0, mask=mask)[0]
    assert np.isclose(original_loss, alternate_loss, atol=1e-12)
    errors = {}
    for name, arr in [*p.items(), ('h0', h0)]:
        analytic = dh0 if name == 'h0' else grads[name]
        error = 0.
        for idx in np.ndindex(arr.shape):
            value = arr[idx]
            arr[idx] = value + 1e-6
            plus = teacher_loss(p, ids, target, h0, mask=mask)[0]
            arr[idx] = value - 1e-6
            minus = teacher_loss(p, ids, target, h0, mask=mask)[0]
            arr[idx] = value
            error = max(error, abs((plus - minus) / 2e-6 - analytic[idx]))
        assert error < 1e-7, (name, error)
        errors[name] = error
    return errors


def sample(params, vocab, prefix, count, seed):
    if count < 0:
        raise ValueError('La cantidad debe ser no negativa')
    rng = np.random.default_rng(seed)
    index = {char: i for i, char in enumerate(vocab)}
    h = np.zeros((1, len(params['bh'])))
    # BOS y cada símbolo del prefijo se procesan exactamente una vez.
    _, h, _ = rnn_forward(params['E'][np.array([[len(vocab)]])], h, params)
    for char in unicodedata.normalize('NFC', prefix).lower():
        value = index.get(char, 0)
        _, h, _ = rnn_forward(params['E'][np.array([[value]])], h, params)
    output, first_distribution, reason = [], None, 'límite'
    for _ in range(count):
        logits = (h @ params['Wy'] + params['by'])[0]
        weights = np.exp(logits - logits.max())
        weights /= weights.sum()
        if first_distribution is None:
            first_distribution = weights.tolist()
        choice = int(rng.choice(len(vocab), p=weights))
        if vocab[choice] == EOS:
            reason = 'eos'
            break
        output.append('�' if choice == 0 else vocab[choice])
        _, h, _ = rnn_forward(params['E'][np.array([[choice]])], h, params)
    return ''.join(output), first_distribution, reason


def sequence_events(sequence, bos, eos):
    """Entradas [BOS, contenido] y objetivos [contenido, EOS]."""
    return (np.concatenate(([bos], sequence)).astype(np.int64),
            np.concatenate((sequence, [eos])).astype(np.int64))


def sampler_check():
    vocab = [UNK, EOS, 'a', 'b']
    params = initial_params(len(vocab), 2, 3, SEED)
    params['Wy'][:] = 0.
    params['by'][:] = [0., 1000., 0., 0.]
    text, _, reason = sample(params, vocab, '', 3, SEED)
    assert text == '' and reason == 'eos'
    params['by'][:] = [0., 0., 1000., 0.]
    text, _, reason = sample(params, vocab, '', 3, SEED)
    assert text == 'aaa' and reason == 'límite'


def train_small(params, train, valid, steps=25, rate=.3):
    inputs, targets = sequence_events(train, len(params['by']), 1)
    valid_inputs, valid_targets = sequence_events(valid, len(params['by']), 1)
    inputs, targets = inputs[None, :], targets[None, :]
    h0 = np.zeros((1, len(params['bh'])))
    history = []
    for step in range(steps + 1):
        loss, _, grads, _ = teacher_loss(params, inputs, targets, h0, backward=True)
        if not math.isfinite(loss) or any(not np.isfinite(g).all() for g in grads.values()):
            raise ValueError('Pérdida o gradiente no finito')
        if step in (0, steps):
            val, _ = teacher_loss(params, valid_inputs[None, :], valid_targets[None, :], h0)
            history.append({'step': step, 'train_nats': loss, 'valid_nats': val})
        if step < steps:
            for name in params:
                params[name] -= rate * grads[name]
    return history


def main():
    vocab, train, valid = prepare(TRAIN_TEXT, VALID_TEXT)
    train_x, train_y = sequence_events(train, len(vocab), vocab.index(EOS))
    assert train_x[0] == len(vocab) and train_y[-1] == vocab.index(EOS)
    assert np.array_equal(train_x[1:], train_y[:-1])
    params = initial_params(len(vocab), embed=6, hidden=10, seed=SEED)
    print('Gradcheck por diferencias finitas:', gradcheck())
    sampler_check()
    history = train_small(params, train, valid)
    print('Tokens y OOV de validación:', len(train), len(valid), int(np.sum(valid == 0)))
    print('Vocabulario de entrenamiento:', vocab, '| entropía uniforme log(V):', math.log(len(vocab)))
    print('Pérdidas train y validación exploratoria:', history)
    sample_a = sample(params, vocab, prefix='en ', count=40, seed=SEED + 1)
    sample_b = sample(params, vocab, prefix='en ', count=40, seed=SEED + 1)
    assert sample_a == sample_b
    print('Generación ancestral reproducible:', sample_a[0], '| terminación:', sample_a[2])
    print('Distribución siguiente tras el prefijo:', sample_a[1])
    print('Modelo entrenado en la muestra, para inspección:',
          json.dumps({'vocab': vocab, 'bos_index': len(vocab), 'eos_index': vocab.index(EOS),
                      'params': {key: value.tolist() for key, value in params.items()}},
                     ensure_ascii=False))
    print('BOS es solo entrada; EOS es salida. OOV se convierte a UNK, que no tiene ejemplos positivos en entrenamiento.')
    print('La máscara pondera la pérdida, pero no detiene la evolución del estado en padding.')
    print('Cada documento reinicia el estado; validación y muestra no prueban calidad general.')
    print('SHA-256 de fragmentos UTF-8:',
          hashlib.sha256(TRAIN_TEXT.encode('utf-8')).hexdigest(),
          hashlib.sha256(VALID_TEXT.encode('utf-8')).hexdigest())


# Extensión local para m17-l10. El bloque anterior procede de la celda de l09.
import os
import time
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F

torch.set_num_threads(1)
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
torch.manual_seed(SEED)


class TorchCharRNN(nn.Module):
    """Misma parametrización que l09; PyTorch tiene dos sesgos recurrentes."""
    def __init__(self, params):
        super().__init__()
        input_size, d = params['E'].shape
        v = len(params['by'])
        h = len(params['bh'])
        if input_size != v + 1:
            raise ValueError('BOS debe ser una fila adicional de entrada')
        self.embedding = nn.Embedding(input_size, d, dtype=torch.float64)
        self.rnn = nn.RNN(d, h, batch_first=True, dtype=torch.float64)
        self.output = nn.Linear(h, v, dtype=torch.float64)
        with torch.no_grad():
            self.embedding.weight.copy_(torch.from_numpy(params['E']))
            self.rnn.weight_ih_l0.copy_(torch.from_numpy(params['Wx'].T.copy()))
            self.rnn.weight_hh_l0.copy_(torch.from_numpy(params['Wh'].T.copy()))
            self.rnn.bias_ih_l0.copy_(torch.from_numpy(params['bh']))
            self.rnn.bias_hh_l0.zero_()
            self.output.weight.copy_(torch.from_numpy(params['Wy'].T.copy()))
            self.output.bias.copy_(torch.from_numpy(params['by']))

    def forward(self, ids, h0):
        states, last = self.rnn(self.embedding(ids), h0)
        return self.output(states), states, last


def compare_gradients():
    """Comprueba el forward y todos los gradientes, incluido el estado inicial."""
    p = initial_params(5, 3, 4, SEED)
    p['bh'][:] = [.1, -.2, .05, .3]
    ids = np.array([[5, 1, 2, 3], [5, 3, 1, 2]], dtype=np.int64)
    target = np.array([[1, 2, 3, 4], [3, 1, 4, 2]], dtype=np.int64)
    mask = np.array([[1., 1., 0., 1.], [1., 1., 1., 1.]])
    h0 = np.array([[.1, -.2, .3, .15], [.3, .1, -.1, -.2]])
    own_states, own_last, _ = rnn_forward(p['E'][ids], h0, p)
    loss, _, grads, dh0 = teacher_loss(p, ids, target, h0, backward=True, mask=mask)
    model = TorchCharRNN(p)
    initial = torch.tensor(h0[None, :, :], requires_grad=True)
    logits, states, last = model(torch.tensor(ids), initial)
    losses = F.cross_entropy(logits.reshape(-1, 5), torch.tensor(target).reshape(-1),
                             reduction='none')
    weights = torch.tensor(mask.reshape(-1))
    torch_loss = (losses * weights).sum() / weights.sum()
    torch_loss.backward()
    err = {
        'states': np.max(np.abs(states.detach().numpy() - own_states)),
        'last': np.max(np.abs(last.detach().numpy()[0] - own_last)),
        'loss': abs(float(torch_loss.detach()) - loss),
        'E': np.max(np.abs(model.embedding.weight.grad.numpy() - grads['E'])),
        'Wx': np.max(np.abs(model.rnn.weight_ih_l0.grad.numpy().T - grads['Wx'])),
        'Wh': np.max(np.abs(model.rnn.weight_hh_l0.grad.numpy().T - grads['Wh'])),
        'bias_ih': np.max(np.abs(model.rnn.bias_ih_l0.grad.numpy() - grads['bh'])),
        'bias_hh': np.max(np.abs(model.rnn.bias_hh_l0.grad.numpy() - grads['bh'])),
        'Wy': np.max(np.abs(model.output.weight.grad.numpy().T - grads['Wy'])),
        'by': np.max(np.abs(model.output.bias.grad.numpy() - grads['by'])),
        'h0': np.max(np.abs(initial.grad.numpy()[0] - dh0)),
    }
    errors = {k: float(v) for k, v in err.items()}
    if not all(math.isfinite(v) and v < 1e-10 for v in errors.values()):
        raise AssertionError(('Falla la paridad NumPy/PyTorch', errors))
    return errors


def verify_detach():
    """Con los mismos pesos, detach conserva el valor pero corta la historia."""
    p = initial_params(5, 3, 4, SEED)
    model = TorchCharRNN(p)
    x = torch.tensor([[5, 2, 3, 4]], dtype=torch.long)
    target = torch.tensor([[2, 3, 4, 1]], dtype=torch.long)
    all_states = []
    initial_grads = []
    for cut in (False, True):
        h0 = torch.tensor([[[.1, -.2, .3, .15]]], dtype=torch.float64,
                          requires_grad=True)
        _, first, boundary = model(x[:, :2], h0)
        if cut:
            boundary = boundary.detach()
        second_logits, second, _ = model(x[:, 2:], boundary)
        # Solo pérdidas del segundo bloque: su dependencia de h0 revela el corte.
        loss = F.cross_entropy(second_logits.reshape(-1, 5), target[:, 2:].reshape(-1))
        grad = torch.autograd.grad(loss, h0, allow_unused=True)[0]
        initial_grads.append(None if grad is None else float(grad.norm()))
        all_states.append(torch.cat((first, second), dim=1).detach())
    if not torch.allclose(all_states[0], all_states[1], atol=1e-12, rtol=0):
        raise AssertionError('detach cambió los valores del forward')
    if initial_grads[0] is None or not initial_grads[0] > 0 or initial_grads[1] is not None:
        raise AssertionError(('Corte inesperado', initial_grads))
    return {'norma_dh0_sin_corte': initial_grads[0],
            'dh0_con_corte': initial_grads[1],
            'diferencia_estados': float((all_states[0] - all_states[1]).abs().max())}


def batchify(tokens, batch_size):
    """Filas = flujos contiguos; se descarta el resto al final del documento."""
    tokens = np.asarray(tokens, dtype=np.int64)
    if tokens.ndim != 1 or batch_size < 1 or len(tokens) // batch_size < 2:
        raise ValueError('Se necesitan al menos dos tokens por flujo')
    length = len(tokens) // batch_size
    return tokens[:length * batch_size].reshape(batch_size, length)


def get_batch(streams, start, length):
    if streams.ndim != 2 or start < 0 or length < 1 or start >= streams.shape[1] - 1:
        raise ValueError('Bloque fuera del flujo')
    end = min(start + length, streams.shape[1] - 1)
    return streams[:, start:end], streams[:, start + 1:end + 1]


def check_batchify():
    streams = batchify(np.arange(20), 2)
    x1, y1 = get_batch(streams, 0, 4)
    x2, _ = get_batch(streams, 4, 4)
    assert np.array_equal(x1[0], [0, 1, 2, 3])
    assert np.array_equal(x1[1], [10, 11, 12, 13])
    assert np.array_equal(y1[:, -1], x2[:, 0])


@torch.inference_mode()
def evaluate(model, sequence, vocab_size, device, block):
    """Texto de validación separado; no se detecta solapamiento parcial."""
    model.eval()
    xs, ys = sequence_events(sequence, vocab_size, 1)
    h = torch.zeros((1, 1, model.rnn.hidden_size), device=device)
    total = 0.
    for start in range(0, len(xs), block):
        x = torch.as_tensor(xs[None, start:start + block], device=device)
        y = torch.as_tensor(ys[None, start:start + block], device=device)
        logits, _, h = model(x, h)
        total += float(F.cross_entropy(logits.reshape(-1, vocab_size), y.reshape(-1),
                                       reduction='sum').item())
    mean = total / len(xs)
    if not math.isfinite(mean):
        raise ValueError('Pérdida de validación no finita')
    return {'eventos': len(xs), 'nats_por_token': mean, 'perplejidad': math.exp(mean)}


def read_texts():
    paths = (os.environ.get('ORYON_TRAIN_FILE'), os.environ.get('ORYON_VALID_FILE'))
    if bool(paths[0]) != bool(paths[1]):
        raise ValueError('Suministra ambos archivos UTF-8 o ninguno')
    if paths[0]:
        return tuple(Path(path).read_text(encoding='utf-8') for path in paths)
    return TRAIN_TEXT, VALID_TEXT


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


def main_bptt_torch():
    print('Paridad NumPy/PyTorch, error máximo por magnitud:', compare_gradients())
    print('Ejemplo de detach:', verify_detach())
    check_batchify()
    train_text, valid_text = read_texts()
    vocab, train, valid = prepare(train_text, valid_text)
    # Dividir [BOS, texto, EOS] crea flujos artificiales: no se predice
    # el salto entre filas. Un resto descartado puede eliminar EOS.
    tokens = np.concatenate(([len(vocab)], train, [vocab.index(EOS)]))
    batch = 2 if SHORT else 8
    window = 8 if SHORT else 64
    epochs = 1 if SHORT else 10
    streams = batchify(tokens, batch)
    discarded = len(tokens) - streams.size
    params = initial_params(len(vocab), embed=16, hidden=32, seed=SEED)
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model = TorchCharRNN(params).to(device=device, dtype=torch.float32)
    # Dos sesgos sumados serían una parametrización distinta al entrenar.
    model.rnn.bias_hh_l0.requires_grad_(False)
    optimizer = torch.optim.Adam((p for p in model.parameters() if p.requires_grad), lr=.003)
    history = []
    sync(device)
    started = time.perf_counter()
    for epoch in range(epochs):
        model.train()
        h = torch.zeros((1, batch, model.rnn.hidden_size), device=device)
        total, events, updates = 0., 0, 0
        for start in range(0, streams.shape[1] - 1, window):
            x_np, y_np = get_batch(streams, start, window)
            x = torch.as_tensor(x_np.copy(), device=device)
            y = torch.as_tensor(y_np.copy(), device=device)
            # La frontera preserva el valor y descarta su grafo.
            h = h.detach()
            optimizer.zero_grad(set_to_none=True)
            logits, _, next_h = model(x, h)
            loss = F.cross_entropy(logits.reshape(-1, len(vocab)), y.reshape(-1))
            if not torch.isfinite(loss):
                raise ValueError('Pérdida de entrenamiento no finita')
            loss.backward()
            norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1., error_if_nonfinite=True)
            optimizer.step()
            h = next_h.detach()
            total += float(loss.detach()) * y.numel()
            events += y.numel()
            updates += 1
        history.append({'epoca': epoch + 1, 'actualizaciones': updates,
                        'eventos': events, 'nats_por_token_online': total / events,
                        'ultima_norma_pre_recorte': float(norm)})
    sync(device)
    seconds = time.perf_counter() - started
    valid_result = evaluate(model, valid, len(vocab), device, window)
    output = {
        'modo_corto': SHORT, 'dispositivo': str(device), 'torch': torch.__version__,
        'semilla': SEED, 'batch': batch, 'k1': window, 'k2': window,
        'tokens_descartados': discarded, 'historial': history, 'validacion': valid_result,
        'oov_validacion': int(np.sum(valid == 0)), 'segundos_entrenamiento': seconds,
        'hash_train_utf8': hashlib.sha256(train_text.encode('utf-8')).hexdigest(),
        'hash_valid_utf8': hashlib.sha256(valid_text.encode('utf-8')).hexdigest(),
    }
    out = Path(os.environ.get('ORYON_OUTPUT', 'bptt_torch_output'))
    out.mkdir(parents=True, exist_ok=True)
    (out / 'metrics.json').write_text(json.dumps(output, ensure_ascii=False, indent=2),
                                       encoding='utf-8')
    print(json.dumps(output, ensure_ascii=False, indent=2))
    print('Cada época reinicia estados; no se barajan bloques ni se cruza entre filas.')
    print('Se usa k1=k2. La ventana solapada k2>k1 se estudia en la práctica NumPy.')
    print('El estado de frontera se calculó antes de la última actualización.')
    print('Los tiempos sincronizados son exploratorios; no son una comparación con Pyodide.')
    print('Se rechazan textos idénticos, pero no se detecta solapamiento parcial entre archivos.')
    print('Los fragmentos y la validación son pequeños y no prueban calidad lingüística.')
    if device.type == 'cuda':
        torch.cuda.empty_cache()


if __name__ == '__main__':
    main_bptt_torch()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Compare the same calculation in browser and GPU

These cells measure the same tanh RNN forward pass without training: Ht=tanh⁡(XtWx+Ht−1Wh+b)H_t=\tanh(X_tW_x+H_{t-1}W_h+b), with zero initial state. Both create exactly the same deterministic float32 matrices, T=64T=64, B=4B=4, D=8D=8 and H=16H=16. Each sample repeats the forward three times, with one prior warm-up and five measured samples. First compare four coordinates and final-state sum: they may differ slightly due to float32 operation order; a large discrepancy invalidates timing comparison.

The first cell runs in Pyodide on CPU without BLAS or GPU access. The second prepares identical data in CUDA before measurement and synchronizes before and after each sample to distinguish queueing time from completed work. Both include state creation and operation dispatch costs but exclude data creation; CUDA additionally excludes initial transfer and library loading. They show median and all samples: divide browser median by GPU median only when both run on the same machine with enough stability. A small workload may be dominated by dispatch; this experiment does not predict large-batch training speed and is not a previously performed measurement. Other processes, browser, driver and hardware affect results.

[ ]RNN measurement in PyodideBrowser
"""Misma recurrencia float32 que la celda GPU; mide CPU en Pyodide."""
import time
import numpy as np

T, B, D, H = 64, 4, 8, 16
REPETITIONS, SAMPLES, WARMUP = 3, 5, 1


def make_arrays():
    def values(shape, modulus, scale):
        size = int(np.prod(shape))
        grid = np.arange(size, dtype=np.int32) % modulus - modulus // 2
        return (grid.astype(np.float32) * np.float32(scale)).reshape(shape)
    return (values((T, B, D), 23, .02), values((D, H), 17, .02),
            values((H, H), 19, .02), values((H,), 11, .01))


def forward(x, wx, wh, bias):
    h = np.zeros((B, H), dtype=np.float32)
    for t in range(T):
        h = np.tanh(x[t] @ wx + h @ wh + bias)
    return h


def main():
    x, wx, wh, bias = make_arrays()
    for _ in range(WARMUP):
        forward(x, wx, wh, bias)
    measurements = []
    for _ in range(SAMPLES):
        started = time.perf_counter()
        for _ in range(REPETITIONS):
            result = forward(x, wx, wh, bias)
        measurements.append((time.perf_counter() - started) / REPETITIONS)
    print('Protocolo:', {'T': T, 'B': B, 'D': D, 'H': H, 'dtype': 'float32',
                         'forward_por_muestra': REPETITIONS, 'muestras': SAMPLES,
                         'calentamiento': WARMUP})
    print('Estado final, primeras cuatro coordenadas:', result[0, :4].tolist())
    print('Suma float64 del estado final:', float(result.astype(np.float64).sum()))
    print('Segundos por forward:', measurements, '| mediana:', float(np.median(measurements)))
    print('Pyodide ejecuta NumPy en CPU, sin BLAS ni acceso a GPU; el tiempo depende del navegador y del equipo.')


if __name__ == '__main__':
    main()
[ ]The same forward pass in CUDALocal GPU
"""Misma recurrencia float32 que la celda de navegador; mide solo CUDA."""
import time
import numpy as np
import torch

T, B, D, H = 64, 4, 8, 16
REPETITIONS, SAMPLES, WARMUP = 3, 5, 1


def make_arrays():
    def values(shape, modulus, scale):
        size = int(np.prod(shape))
        grid = np.arange(size, dtype=np.int32) % modulus - modulus // 2
        return (grid.astype(np.float32) * np.float32(scale)).reshape(shape)
    return (values((T, B, D), 23, .02), values((D, H), 17, .02),
            values((H, H), 19, .02), values((H,), 11, .01))


def forward(x, wx, wh, bias):
    h = torch.zeros((B, H), dtype=torch.float32, device=x.device)
    for t in range(T):
        h = torch.tanh(x[t] @ wx + h @ wh + bias)
    return h


def main():
    if not torch.cuda.is_available():
        raise RuntimeError('Esta medición requiere CUDA; no se sustituye por CPU')
    device = torch.device('cuda')
    x, wx, wh, bias = (torch.from_numpy(a).to(device) for a in make_arrays())
    with torch.inference_mode():
        for _ in range(WARMUP):
            forward(x, wx, wh, bias)
        torch.cuda.synchronize(device)
        measurements = []
        for _ in range(SAMPLES):
            torch.cuda.synchronize(device)
            started = time.perf_counter()
            for _ in range(REPETITIONS):
                result = forward(x, wx, wh, bias)
            torch.cuda.synchronize(device)
            measurements.append((time.perf_counter() - started) / REPETITIONS)
    result = result.cpu().numpy()
    print('Protocolo:', {'T': T, 'B': B, 'D': D, 'H': H, 'dtype': 'float32',
                         'forward_por_muestra': REPETITIONS, 'muestras': SAMPLES,
                         'calentamiento': WARMUP})
    print('Estado final, primeras cuatro coordenadas:', result[0, :4].tolist())
    print('Suma float64 del estado final:', float(result.astype(np.float64).sum()))
    print('Segundos por forward:', measurements, '| mediana:', float(np.median(measurements)))
    print('El tiempo incluye lanzamiento de operaciones y sincronización, sin transferencias de entrada ni inicialización.')
    print('Compara las coordenadas y suma con la celda de navegador con tolerancia float32.')
    torch.cuda.empty_cache()


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

If CUDA is unavailable, the second cell reports the requirement and does not present a CPU run as GPU. Shared local execution uses the same resource control as other labs; no data download is needed.

Exercises

NumericStore states
A layer stores T=256 states of size H=512 for each of B=64 sequences in float32. How many MiB do these states occupy, excluding initial h and other tensors?
NumericSame forward, different gradient
If h₀=3, hₜ=θhₜ₋₁ and L=h₅ with θ=2, what is dL/dθ if you detach h₂ and backpropagate only the final three steps?
ProofA shared matrix
Prove: Derive the recurrent matrix gradient with a loss at each step.
0
Use row examples and Gₜ=∂L/∂Aₜ. Losses may be masked, but the graph retains all transitions.

Step 1 of 3. Which two paths contribute to Dₜ=∂L/∂Hₜ?

QuizA gradient boundary
You carry state between blocks and detach it from the graph at the start of each block. What effect does this have?
CodeBackward with shared weights
Implement rnn_backward(dout, cache). For T steps, x has shape (T,B,D), states (T+1,B,H), Wx (D,H), Wh (H,H) and dout (T,B,H) contains local loss derivatives with respect to each state. cache is (x,states,Wx,Wh). Return dx, dWx, dWh, db, dh0 for tanh and sum temporal contributions. Do not modify arguments.
import numpy as np

def rnn_backward(dout, cache):
  pass
Shift+Enter to run
CodeStreams without bridges
Implement batchify(ids, B) with equal-length contiguous streams discarding the remainder, and get_batch(source, i, T) with inputs and targets shifted one position in the same stream. Return the final block even if shorter. Reject nonpositive sizes, streams shorter than two tokens and out-of-range positions with ValueError; do not modify ids.
import numpy as np

def batchify(ids, B):
  pass

def get_batch(source, i, T):
  pass
Shift+Enter to run

Further connections

The Jacobian product in GtG_t connects with Spectral conditions for vanishing and exploding gradients in RNNs. The same tradeoffs between storing, recomputing and truncating recur in deep networks and recurrent policies. Before interpreting a curve, check which state and parameter history produced each point.