Module contents
Lesson 12 of 24Core 115 min

LSTM: the memory cell and the constant error carousel

Study LSTM memory cells, multiplicative gates, backward propagation and implementation parity.

After this lesson you can

  • Explain cell and hidden state, input, forget and output gates.
  • Derive direct cell-gradient paths and complete backward contributions.
  • Map gate weights and biases between NumPy and PyTorch.
  • Interpret cell activations and controlled memory-task evaluations.

Before you start

Storing, writing and reading are different decisions

In the simple Recurrent neural network (Elman network), each step transforms the entire state again. When the temporal Jacobian attenuates a direction, a distant loss struggles to assign it credit. Can we reserve a path preserving information while allowing the model to replace it?

An LSTM separates cell state ctc_t from hidden output hth_t. A cell sum provides a direct path; multiplicative gates control what to retain, write and read. This facilitates certain information and gradient paths, but does not guarantee training discovers a solution or every derivative stays constant.

InteractiveInside a scalar cell

Toy scalar cell with constant preactivations: c₀=1, cₜ=f cₜ₋₁+i g and hₜ=o tanh(cₜ), with i=0.0474, f=0.9526, o=0.7311 and g=0.0000. Here gates and candidate depend on neither state nor data.

1.0−1.00200

● State c · ● Output h. Direct sensitivity of cₜ to c₀ for these fixed gates is fᵗ=0.143203 (14.32 %).

A sigmoid with finite preactivation never yields exactly 0 or 1. Ideal memory and closed output switches represent limits; fixed f=0.95 can be obtained with finite preactivation and replaces the forget slider. Ideal memory takes priority over that fixed value. In a trained LSTM, gates depend on state and additional gradient paths exist.

−3.0
3.0
1.0
0.0
40
Forget f0.9526
Input i0.0474
State cₜ0.1432
Output hₜ0.1040
Change preactivations and distinguish stored state from visible output.

The constant error carousel of Hochreiter and Schmidhuber starts from a linear self-connection of weight one: if along that path ct=ct−1+utc_t=c_{t-1}+u_t, the direct partial derivative with respect to previous state is one. That calculation holds the write signal fixed; other paths can alter the total derivative. Memory never cleared presents another problem: it can accumulate information no longer useful.

Multiplicative gates modulate components elementwise. The original design included input and output gates. Gers, Schmidhuber and Cummins introduced an adaptive forget gate allowing the system to release memory. The modern cell below is a particular variant without peepholes.

For row examples, input Xt∈RB×dX_t\in\mathbb{R}^{B\times d} and states Ht,Ct∈RB×HH_t,C_t\in\mathbb{R}^{B\times H}, each gate has its matrices and bias:

It=σ(XtWi+Ht−1Ui+bi),Ft=σ(XtWf+Ht−1Uf+bf),Gt=tanh⁡(XtWg+Ht−1Ug+bg),Ot=σ(XtWo+Ht−1Uo+bo),Ct=Ft⊙Ct−1+It⊙Gt,Ht=Ot⊙tanh⁡(Ct).\begin{aligned} I_t&=\sigma(X_tW_i+H_{t-1}U_i+b_i),& F_t&=\sigma(X_tW_f+H_{t-1}U_f+b_f),\\ G_t&=\tanh(X_tW_g+H_{t-1}U_g+b_g),& O_t&=\sigma(X_tW_o+H_{t-1}U_o+b_o),\\ C_t&=F_t\odot C_{t-1}+I_t\odot G_t,& H_t&=O_t\odot\tanh(C_t). \end{aligned}

Matrices W∙W_\bullet have shape (d,H)(d,H), U∙U_\bullet shape (H,H)(H,H) and biases length HH. Sigmoid allows weights between zero and one; tanh allows a positive or negative candidate and bounds readout. State CtC_t is not replaced by tanh⁡(Ct)\tanh(C_t): nonlinearity applies when reading it. With finite preactivations sigmoid never reaches exactly zero or one; the figure’s ideal switches show mathematical limits.

An output gate near zero can hide information remaining in CtC_t. A small input gate reduces immediate writing, but state may still change through forgetting. Thus no gate is interpreted without the others and inputs. Values depend on context and learned parameters.

The direct path is not the whole Jacobian

If gates are held fixed and we follow only the cell’s recurrent summand, the one-step derivative is diag⁡(Ft)\operatorname{diag}(F_t). Across dd steps, that path contributes

∂CT∂Ct∣directa=diag⁡ ⁣(∏k=t+1TFk).\left.\frac{\partial C_T}{\partial C_t}\right|_{\text{directa}} =\operatorname{diag}\!\left(\prod_{k=t+1}^{T}F_k\right).

The product is coordinatewise. In an actual LSTM gates also depend on Hk−1H_{k-1}, which depends on previous states: additional paths appear. This equality therefore identifies one path contribution and does not ensure the total Jacobian is diagonal, equal to that product or unit norm. The read path also includes the output gate and tanh derivative.

InteractiveDirect paths and recurrent sensitivity

Explicit model: forget gates are externally fixed and the derivative along the direct path is fᵈ. We compare biases 0, 1 and the chosen value, with preactivation equal to bias. The other curve computes exact sensitivity of the scalar RNN hₜ=tanh(w hₜ₋₁), without inputs.

10^0.010⁻¹⁶0100 steps
f with bias 0 f with bias 1 chosen f tanh RNN

The plot is logarithmic and draws values below 10⁻¹⁶ at that floor; readouts do not use that clipping. In a general LSTM, gates depend on h and may add paths to the total Jacobian: the forget product describes only the direct path. A bias of 1 increases f relative to 0 under this assumption, but does not guarantee memory or successful training.

1.0
0.9
0.1
30
Constant gate σ(b𝒇)0.7311
Direct cell path8.29e-5
Scalar RNN sensitivity0.0406
Direct half-life2.21 steps
Compare constant-gate products with an explicit scalar RNN.

The forget gate can be initialized with positive bias to favor initial retention. In the simplified model where preactivation equals bias, bf=0b_f=0 gives f=0,5f=0,5 (0.5) and bf=1b_f=1 gives f≈0,7311f\approx0,7311 (0.7311). Even with bf=1b_f=1, the product over one hundred steps is approximately 2,48⋅10−142,48\cdot10^{-14} (2.48 × 10⁻¹⁴): positive bias does not guarantee hundred-step memory. Actual preactivation also contains input and state.

Jozefowicz, Zaremba and Sutskever observed that adding 1 to forget bias reduced the gap between LSTM and GRU in their experiments. This is an empirical choice, not a universal theorem. If f=0,95f=0,95 (0.95) is constant, the factor falls to e−1e^{-1} in −1/log⁡(0,95)≈19,50-1/\log(0,95)\approx19,50 steps (about 19.50); 1/(1−f)=201/(1-f)=20 is an approximation, not the exact scale.

Backpropagate through both states

In LSTM backward, derivatives arrive from the rest of the graph at both HtH_t and CtC_t. Let Hˉt\bar H_t be the total derivative with respect to HtH_t and Cˉtfut\bar C_t^{\text{fut}} the derivative arriving directly at CtC_t from the next step (“fut” means future). Then

Cˉt=Cˉtfut+Hˉt⊙Ot⊙(1−tanh⁡2Ct).\bar C_t=\bar C_t^{\text{fut}} +\bar H_t\odot O_t\odot(1-\tanh^2 C_t).

The second summand follows cell readout. Before differentiating preactivations, gate and candidate contributions are

Oˉt=Hˉt⊙tanh⁡Ct,Fˉt=Cˉt⊙Ct−1,Iˉt=Cˉt⊙Gt,Gˉt=Cˉt⊙It.\bar O_t=\bar H_t\odot\tanh C_t,\quad \bar F_t=\bar C_t\odot C_{t-1},\quad \bar I_t=\bar C_t\odot G_t,\quad \bar G_t=\bar C_t\odot I_t.

Multiply Iˉt,Fˉt,Oˉt\bar I_t,\bar F_t,\bar O_t by It(1−It)I_t(1-I_t), Ft(1−Ft)F_t(1-F_t) and Ot(1−Ot)O_t(1-O_t) respectively, and Gˉt\bar G_t by 1−Gt21-G_t^2. The direct contribution to previous state is Cˉt−1=Cˉt⊙Ft\bar C_{t-1}=\bar C_t\odot F_t. In this peephole-free cell, all four preactivations also contribute to Hˉt−1\bar H_{t-1} through transposes of their recurrent matrices. BPTT accumulates contributions through hidden state, cell and local losses before processing the previous step.

To complete parameter calculation, call Aˉq,t\bar A_{q,t} the derivative with respect to gate q∈{i,f,g,o}q\in\{i,f,g,o\}‘s preactivation. For row examples, one-step contributions are

Wˉq(t)=Xt⊤Aˉq,t,Uˉq(t)=Ht−1⊤Aˉq,t,bˉq(t)=∑n=1BAˉq,t[n,:].\bar W_q^{(t)}=X_t^\top\bar A_{q,t},\qquad \bar U_q^{(t)}=H_{t-1}^\top\bar A_{q,t},\qquad \bar b_q^{(t)}=\sum_{n=1}^{B}\bar A_{q,t}[n,:].

Also Xˉt=∑qAˉq,tWq⊤\bar X_t=\sum_q\bar A_{q,t}W_q^\top and Hˉt−1=∑qAˉq,tUq⊤\bar H_{t-1}=\sum_q\bar A_{q,t}U_q^\top. Sharing parameters across steps makes their gradients sums of these contributions over time. Resulting shapes match each parameter; example gradients are not summed before forming outer products. The lab compares these derivatives with finite differences and separately with PyTorch.

Peephole connections feed cell states to some gates; their derivatives add paths absent from the formulas above. Greff and colleagues compared variants on specific tasks. An ablation with small effect in those experiments does not prove a connection useless for every task.

The order of four slices

In torch.nn.LSTM, concatenated slices are ordered input, forget, candidate and output: i, f, g, o. The module stores matrices of shape (4H,d)(4H,d) and (4H,H)(4H,H) and two length-4H4H biases that are summed. To transfer a row-based implementation, transpose its matrices. If effective bias is bb, copy bb to input bias and zero to recurrent bias; copying bb to both applies 2b2b.

InteractivePack the weights

An explicit cell with input dimension 2 and state dimension 1. PyTorch interprets rows in i, f, g, o slices. The blocks you place contain their input and recurrent weights and the original bias.

Slot i ← block iInput W [0.4, −0.2], recurrent W 0.3, b 0.1
Slot f ← block fInput W [−0.1, 0.5], recurrent W 0.2, b 0.4
Slot g ← block oInput W [0.2, 0.6], recurrent W 0.1, b −0.3
Slot o ← block gInput W [0.7, 0.2], recurrent W −0.3, b −0.1

The packing does not reproduce both reference conventions. Difference in h: 0.119014.

Model calculated directly with x=[0.7; −0.2], h₀=0.3 and c₀=0.4. weight_ih has shape 4×2 and weight_hh 4×1; each bias has four entries. The reference copies b to bias_ih and zero to bias_hh. Copying b to both yields 2b. Matching a single example does not prove general parity: the local cell checks all outputs and gradients.

Reference c0.38768
Packed c0.07577
Reference h0.16172
Packed h0.04270
Reorder blocks and check an explicit cell; matches are verified on more cases in the lab.

CuDNN can execute a fused implementation when device and configuration permit. Availability does not imply a particular operation used it: the lab inspects the operator and synchronizes the device when measuring. Compare the same calculations and treat timings as measurements of that environment.

Which cells follow the text?

Karpathy, Johnson and Fei-Fei studied internal character-network activations and examples associated with text structure. A visualization on real code needs a trained model, identified excerpt and activations saved by a reproducible run. A cell correlated with a property in one example does not prove that neuron is a universal detector.

InteractiveRead cell states over code

Real lab report: short verification run, 3 updates, seed 17120, 16 units and 0 out-of-vocabulary characters in the example. State is shown after processing each character.

Evaluation code, colored by state of unit 0:

● Negative ● Positive. Intensity uses the maximum absolute value of this unit in the text; colors are not comparable as absolute magnitudes across units.

View values and provenance

Training source: textwrap.py, SHA-256 92df473a6da51156bc40fe0f1680c45daf91421627760e00b107a3cf2209910b, Python 3.13.1, PyTorch 2.11.0+cu128. Windows of 32, batch 4; maximum incremental parity error in logits 0.0000001 and state 0.0000002.

PositionCharacterc
1d−0.20413
2e−0.69847
3f0.02379
4space−0.21620
5s−0.66131
6q−0.23164
7u0.00112
8a−0.28632
9r−0.02775
10e−0.55294
11_−0.61426
12s−0.86749
13u−0.11702
14m−0.17967
15(0.22053
16x0.27611
17s−0.35852
18)−0.39022
19:−0.10326
20newline−0.06349
21space−0.15824
22space−0.22967
23space−0.29351
24space−0.34646
25r−0.08905
26e−0.61047
27t−0.20952
28u0.00407
29r0.16854
30n−0.02110
31space−0.12950
32s−0.59639
33u−0.04842
34m−0.15102
35(0.22796
36x0.26568
37space−0.02232
38*−0.42350
39space−0.38063
40x−0.16242
41space−0.24735
42f0.11064
43o−0.16235
44r−0.00704
45space−0.19262
46x−0.08598
47space−0.21235
48i0.05705
49n−0.21590
50space−0.26598
51x−0.10285
52s−0.57367
53)−0.54812
54newline−0.32570

The full training source is not included in the report. The complete example does not literally appear in that file, though partial overlap is not ruled out. An activation visually aligned with quotes or parentheses in this fragment does not demonstrate that the unit generally detects that property. The short run only verifies the pipeline.

0
1 / 54
Selected characterd
Cell state c−0.2041
Range of this unit−0.867 to 0.276
Inspect an actual state per character and compare units without assuming a visual match proves a detector.

The figure comes from the next local cell’s short run: three updates check the pipeline but do not justify assigning a learned function to a unit. Evaluation text does not occur literally in the training file, though it may share fragments. Intensity is normalized per unit; do not compare color intensity between units as an absolute magnitude. For stronger investigation, run the full version and evaluate many separate excerpts.

A useful test begins by defining the property before looking at activations. For example, use a parser to calculate whether each position is inside a string and compare states on evaluation excerpts separated by file. Choose thresholds using training or validation only, then measure hits and false positives on held-out files. Also compare with a character-frequency baseline: a unit responding to isolated quotes does not necessarily remember whether the string remains open. This inspection measures association; intervening on the unit asks a different causal question.

The lab defaults to textwrap.py from your Python installation and records its SHA-256; you can specify another UTF-8 file through ORYON_PY_SOURCE. Check usage rights of the chosen source. TF32 is disabled for more precise comparison between full and incremental GPU evaluation. ORYON_VERIFY_SHORT=1 reduces work to a functional check.

[ ]Character LSTM activationsLocal GPU
"""Entrena un LSTM de caracteres y exporta sus estados de celda reales.

El corpus es textwrap.py de la biblioteca estándar de Python local, o el
archivo ORYON_PY_SOURCE facilitado por el lector. No redistribuye ese corpus:
registra su ruta, versión de Python y SHA-256. El texto inspeccionado es el
ejemplo breve original de abajo, no una copia del corpus de entrenamiento.
Comprueba las condiciones de uso del archivo elegido. SHORT solo prueba el
recorrido; no demuestra que haya celdas que detecten estructuras del código.
"""
import hashlib
import json
import os
import platform
import sysconfig
from pathlib import Path

import numpy as np
import torch
from torch import nn

SEED = 17120
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
STEPS = 3 if SHORT else int(os.environ.get('ORYON_CHAR_STEPS', '1500'))
HIDDEN = 16 if SHORT else 64
EMBED = 16 if SHORT else 32
LENGTH = 32 if SHORT else 64
BATCH = 4 if SHORT else 16
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.backends.cudnn.allow_tf32 = False
torch.backends.cuda.matmul.allow_tf32 = False
SOURCE = Path(os.environ.get('ORYON_PY_SOURCE', Path(sysconfig.get_path('stdlib')) / 'textwrap.py'))
OUTPUT = Path(os.environ.get('ORYON_ACTIVATIONS_OUTPUT', 'lstm_activaciones_codigo.json'))
EXAMPLE = 'def square_sum(xs):\n    return sum(x * x for x in xs)\n'


class CharacterModel(nn.Module):
    def __init__(self, vocabulary):
        super().__init__()
        self.embedding = nn.Embedding(vocabulary, EMBED)
        self.lstm = nn.LSTM(EMBED, HIDDEN)
        self.output = nn.Linear(HIDDEN, vocabulary)

    def forward(self, ids, state=None):
        hidden, state = self.lstm(self.embedding(ids), state)
        return self.output(hidden), state


def main():
    if STEPS < 1:
        raise ValueError('El número de pasos debe ser positivo')
    if SOURCE.stat().st_size > 8 * 1024 * 1024:
        raise ValueError('El archivo fuente supera 8 MiB')
    raw = SOURCE.read_bytes()
    text = raw.decode('utf-8')
    if len(text) <= LENGTH + 1:
        raise ValueError('El archivo debe superar la longitud de la ventana')
    if EXAMPLE in text:
        raise ValueError('El texto de inspección aparece literalmente en entrenamiento')
    chars = sorted(set(text))
    index = {char: i + 1 for i, char in enumerate(chars)}
    ids = np.array([index[char] for char in text], dtype=np.int64)
    encoded_example = [index.get(char, 0) for char in EXAMPLE]
    rng = np.random.default_rng(SEED)
    torch.manual_seed(SEED)
    if DEVICE.type == 'cuda': torch.cuda.manual_seed_all(SEED)
    model = CharacterModel(len(chars) + 1).to(DEVICE)
    optimizer = torch.optim.Adam(model.parameters(), lr=.002)
    history = []
    for step in range(1, STEPS + 1):
        starts = rng.integers(0, len(ids) - LENGTH, size=BATCH)
        inputs = np.stack([ids[start:start + LENGTH] for start in starts], axis=1)
        labels = np.stack([ids[start + 1:start + LENGTH + 1] for start in starts], axis=1)
        xt = torch.as_tensor(inputs, dtype=torch.long, device=DEVICE)
        yt = torch.as_tensor(labels, dtype=torch.long, device=DEVICE)
        optimizer.zero_grad(set_to_none=True)
        logits, _ = model(xt)
        loss = nn.functional.cross_entropy(logits.reshape(-1, logits.shape[-1]), yt.reshape(-1))
        if not torch.isfinite(loss): raise ValueError('Pérdida no finita')
        loss.backward()
        norm = nn.utils.clip_grad_norm_(model.parameters(), 1., error_if_nonfinite=True)
        optimizer.step()
        if step == 1 or step == STEPS or step % max(1, STEPS // 10) == 0:
            history.append({'step': step, 'train_cross_entropy': float(loss.detach()),
                            'gradient_norm_before_clip': float(norm)})
    model.eval()
    example = torch.tensor(encoded_example, dtype=torch.long, device=DEVICE)[:, None]
    with torch.no_grad():
        # La secuencia completa y los pasos individuales deben producir la misma salida.
        all_logits, final_state = model(example)
        state, single_logits, cells = None, [], []
        for token in example.split(1, dim=0):
            logits, state = model(token, state)
            single_logits.append(logits)
            cells.append(state[1][0, 0].cpu().tolist())
        incremental = torch.cat(single_logits, dim=0)
        difference = float((incremental - all_logits).abs().max().cpu())
        state_difference = float((state[1] - final_state[1]).abs().max().cpu())
    if difference > 1e-4 or state_difference > 1e-4:
        raise AssertionError(('La evaluación incremental no coincide', difference, state_difference))
    result = {'short': SHORT, 'seed': SEED, 'device': str(DEVICE), 'python': platform.python_version(),
              'torch': torch.__version__, 'source_name': SOURCE.name, 'source_sha256': hashlib.sha256(raw).hexdigest(),
              'source_characters': len(text), 'training_steps': STEPS, 'window': LENGTH,
              'batch': BATCH, 'hidden': HIDDEN, 'vocabulary': len(chars) + 1,
              'evaluation_text': EXAMPLE, 'evaluation_oov': sum(token == 0 for token in encoded_example),
              'cells': cells, 'history': history, 'incremental_logits_max_error': difference,
              'incremental_cell_max_error': state_difference,
              'limitations': 'Una muestra y una semilla no prueban detección de sintaxis; el control corto solo verifica ejecución. '
                             'El ejemplo completo no está en el corpus, pero no se detecta solapamiento parcial.'}
    OUTPUT.parent.mkdir(parents=True, exist_ok=True)
    OUTPUT.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
    print('Activaciones:', OUTPUT, '| pasos:', STEPS, '| OOV:', result['evaluation_oov'])
    print('Errores de paridad incremental:', difference, state_difference)
    del model, optimizer
    if DEVICE.type == 'cuda': 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.

Lab: NumPy from scratch

The next cell implements an LSTM without peepholes with manual step and backward, BPTT, numerical checking and two tasks. Character data are current Recurrent language model excerpts from Project Gutenberg, lowercased here. Vocabulary is built only on training; validation maps missing characters to UNK. This variant has no EOS and sampling ends by length.

The adding task uses length 100: sum two marked values. The short version runs only three updates and shows validation MSE and constant-1 baseline; it does not demonstrate the task is solved. For longer training, call the function with more steps in an appropriate local environment and retain a separate evaluation sample. Short losses and samples do not prove linguistic quality.

[ ]NumPy LSTM: backward and tasksBrowser
"""LSTM en NumPy: paso, BPTT, gradcheck y tareas pequeñas reproducibles.

Orden i, f, g, o; un único sesgo efectivo. La suma usa T=100, pero las
pocas actualizaciones impresas solo comprueban que el código funciona.
"""
import numpy as np


def sigmoid(x):
    # Esta forma evita desbordamientos tanto en x muy positivo como negativo.
    return np.exp(-np.logaddexp(0.0, -x))


def initialize(d, h, out, rng, forget_bias=1.0):
    p = {'wx': rng.normal(0, 0.2, (d, 4*h)),
         'wh': rng.normal(0, 0.2, (h, 4*h)), 'b': np.zeros(4*h),
         'wy': rng.normal(0, 0.2, (h, out)), 'by': np.zeros(out)}
    p['b'][h:2*h] = forget_bias
    return p


def lstm_step_forward(x, h, c, p):
    z = x @ p['wx'] + h @ p['wh'] + p['b']
    zi, zf, zg, zo = np.split(z, 4, axis=1)
    i, f, g, o = sigmoid(zi), sigmoid(zf), np.tanh(zg), sigmoid(zo)
    cn = f*c + i*g
    hn = o*np.tanh(cn)
    return hn, cn, (x, h, c, i, f, g, o, cn, p)


def lstm_step_backward(dh_next, dc_next, cache):
    x, h, c, i, f, g, o, cn, p = cache
    tanhc = np.tanh(cn)
    dc = dc_next + dh_next * o * (1 - tanhc*tanhc)
    di, df, dg, do = dc*g, dc*c, dc*i, dh_next*tanhc
    dz = np.concatenate((di*i*(1-i), df*f*(1-f), dg*(1-g*g), do*o*(1-o)), axis=1)
    grads = {'wx': x.T @ dz, 'wh': h.T @ dz, 'b': dz.sum(axis=0)}
    return dz @ p['wx'].T, dz @ p['wh'].T, dc*f, grads


def forward(xs, p, h0=None, c0=None):
    T, B, _ = xs.shape
    H = p['wh'].shape[0]
    h = np.zeros((B, H)) if h0 is None else h0.copy()
    c = np.zeros((B, H)) if c0 is None else c0.copy()
    states, cells, caches = [], [], []
    for x in xs:
        h, c, cache = lstm_step_forward(x, h, c, p)
        states.append(h); cells.append(c); caches.append(cache)
    hs, cs = np.stack(states), np.stack(cells)
    return hs @ p['wy'] + p['by'], hs, cs, caches


def backward(dy, hs, caches, p):
    grads = {key: np.zeros_like(value) for key, value in p.items()}
    grads['wy'] = np.einsum('tbh,tbo->ho', hs, dy)
    grads['by'] = dy.sum(axis=(0, 1))
    dh = np.zeros_like(hs[0]); dc = np.zeros_like(dh)
    dxs = np.zeros((len(caches), hs.shape[1], p['wx'].shape[0]))
    for t in range(len(caches)-1, -1, -1):
        dh += dy[t] @ p['wy'].T
        dxs[t], dh, dc, step_grads = lstm_step_backward(dh, dc, caches[t])
        for key, value in step_grads.items():
            grads[key] += value
    return grads, dxs, dh, dc


def check_gradients():
    rng = np.random.default_rng(1712)
    xs = rng.normal(size=(4, 2, 3)); p = initialize(3, 2, 2, rng)
    h0 = rng.normal(size=(2, 2)); c0 = rng.normal(size=(2, 2))
    dy = rng.normal(size=(4, 2, 2))
    _, hs, _, caches = forward(xs, p, h0, c0)
    grads, dx, dh0, dc0 = backward(dy, hs, caches, p)
    def objective():
        return float(np.sum(forward(xs, p, h0, c0)[0] * dy))
    errors = []
    for arr, grad in [(p[k], grads[k]) for k in p] + [(xs, dx), (h0, dh0), (c0, dc0)]:
        for index in np.ndindex(arr.shape):
            old = arr[index]; eps = 1e-5
            arr[index] = old + eps; plus = objective()
            arr[index] = old - eps; minus = objective()
            arr[index] = old
            numerical = (plus-minus)/(2*eps)
            errors.append(abs(numerical-grad[index]))
    print('Gradcheck, error absoluto máximo:', max(errors))
    assert max(errors) < 1e-7


def adding_batch(T, B, rng):
    values = rng.random((T, B)); markers = np.zeros((T, B))
    for b in range(B):
        positions = rng.choice(T, 2, replace=False)
        markers[positions, b] = 1
    target = (values*markers).sum(axis=0)[:, None]
    return np.stack((values, markers), axis=2), target


def update(p, grads, rate, cap=1.0):
    norm = np.sqrt(sum(np.sum(g*g) for g in grads.values()))
    if not np.isfinite(norm) or not np.isfinite(cap) or cap <= 0:
        raise ValueError('Gradiente o límite no finito o inválido')
    scale = min(1.0, cap/norm) if norm else 1.0
    for key in p:
        p[key] -= rate*scale*grads[key]


def train_adding(steps=3, T=100):
    if steps < 1 or T < 2:
        raise ValueError('Se necesitan pasos positivos y T >= 2')
    rng = np.random.default_rng(1713); p = initialize(2, 8, 1, rng)
    for _ in range(steps):
        xs, target = adding_batch(T, 8, rng)
        ys, hs, _, caches = forward(xs, p)
        error = ys[-1] - target
        loss = float(np.mean(error**2))
        dy = np.zeros_like(ys); dy[-1] = 2*error/error.size
        grads, _, _, _ = backward(dy, hs, caches, p)
        update(p, grads, .01)
    # Semilla distinta; no participa en la actualización ni representa test final.
    vx, vy = adding_batch(T, 32, np.random.default_rng(1715))
    prediction = forward(vx, p)[0][-1]
    validation = float(np.mean((prediction - vy)**2))
    baseline = float(np.mean((1. - vy)**2))
    print('Suma, última pérdida train:', loss, '| validación MSE:', validation,
          '| baseline constante 1 MSE:', baseline, '| pasos:', steps, '| T:', T)
    return p


def train_characters(steps=3):
    if steps < 1:
        raise ValueError('Se necesitan pasos positivos')
    # Fragmentos de la celda vigente m17-l09, Don Quijote, capítulos I y II:
    # https://www.gutenberg.org/files/2000/2000-0.txt
    text = 'en un lugar de la mancha, de cuyo nombre no quiero acordarme'
    valid = 'hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
    alphabet = ['<unk>', *sorted(set(text))]; ids = {ch: i for i, ch in enumerate(alphabet)}
    xs = np.eye(len(alphabet))[[ids[ch] for ch in text[:-1]]][:, None, :]
    target = np.array([ids[ch] for ch in text[1:]])
    rng = np.random.default_rng(1714); p = initialize(len(alphabet), 8, len(alphabet), rng)
    for _ in range(steps):
        logits, hs, _, caches = forward(xs, p)
        shifted = logits[:, 0] - logits[:, 0].max(axis=1, keepdims=True)
        probs = np.exp(shifted); probs /= probs.sum(axis=1, keepdims=True)
        loss = float(-np.log(probs[np.arange(len(target)), target]).mean())
        dy = probs.copy(); dy[np.arange(len(target)), target] -= 1
        grads, _, _, _ = backward((dy/len(target))[:, None, :], hs, caches, p)
        update(p, grads, .05)
    valid_ids = np.array([ids.get(ch, 0) for ch in valid])
    valid_x = np.eye(len(alphabet))[valid_ids[:-1]][:, None, :]
    valid_logits = forward(valid_x, p)[0][:, 0]
    valid_logits -= valid_logits.max(axis=1, keepdims=True)
    logz = np.log(np.exp(valid_logits).sum(axis=1))
    valid_loss = float(np.mean(logz - valid_logits[np.arange(len(valid_ids)-1), valid_ids[1:]]))
    print('Caracteres, última pérdida train:', loss, '| validación nats:', valid_loss,
          '| caracteres OOV:', int((valid_ids == 0).sum()), '| pasos:', steps)
    print('La clase UNK no tiene ejemplos positivos en train. No se modela EOS.')
    print('Muestra ancestral con límite de 40 pasos:', generate_characters(p, alphabet, 'en ', 40, 1716))
    return p, alphabet


def generate_characters(p, alphabet, prefix, length, seed):
    if not prefix or length < 0:
        raise ValueError('Prefijo vacío o longitud negativa')
    index = {ch: i for i, ch in enumerate(alphabet)}
    h = np.zeros((1, p['wh'].shape[0])); c = np.zeros_like(h)
    def consume(token):
        nonlocal h, c
        vector = np.eye(len(alphabet))[[token]]
        h, c, _ = lstm_step_forward(vector, h, c, p)
    for ch in prefix:
        consume(index.get(ch, 0))
    rng = np.random.default_rng(seed); out = []
    for _ in range(length):
        logits = (h @ p['wy'] + p['by'])[0]
        probabilities = np.exp(logits - logits.max()); probabilities /= probabilities.sum()
        token = int(rng.choice(len(alphabet), p=probabilities))
        out.append('<unk>' if token == 0 else alphabet[token])
        consume(token)
    return ''.join(out)


if __name__ == '__main__':
    check_gradients()
    train_adding()
    train_characters()

Lab: parity and forget bias

The second cell compares NumPy forward and gradients with a manual PyTorch cell and nn.LSTM, including both initial states and both biases. It also prepares an ablation of initial biases 0 and 1 with paired seeds, validation selection and exploratory test. Short mode checks the pipeline; its results do not establish which initialization wins. Timings depend on device and shared load.

[ ]LSTM: parity and ablationLocal GPU
"""LSTM en NumPy: paso, BPTT, gradcheck y tareas pequeñas reproducibles.

Orden i, f, g, o; un único sesgo efectivo. La suma usa T=100, pero las
pocas actualizaciones impresas solo comprueban que el código funciona.
"""
import numpy as np


def sigmoid(x):
    # Esta forma evita desbordamientos tanto en x muy positivo como negativo.
    return np.exp(-np.logaddexp(0.0, -x))


def initialize(d, h, out, rng, forget_bias=1.0):
    p = {'wx': rng.normal(0, 0.2, (d, 4*h)),
         'wh': rng.normal(0, 0.2, (h, 4*h)), 'b': np.zeros(4*h),
         'wy': rng.normal(0, 0.2, (h, out)), 'by': np.zeros(out)}
    p['b'][h:2*h] = forget_bias
    return p


def lstm_step_forward(x, h, c, p):
    z = x @ p['wx'] + h @ p['wh'] + p['b']
    zi, zf, zg, zo = np.split(z, 4, axis=1)
    i, f, g, o = sigmoid(zi), sigmoid(zf), np.tanh(zg), sigmoid(zo)
    cn = f*c + i*g
    hn = o*np.tanh(cn)
    return hn, cn, (x, h, c, i, f, g, o, cn, p)


def lstm_step_backward(dh_next, dc_next, cache):
    x, h, c, i, f, g, o, cn, p = cache
    tanhc = np.tanh(cn)
    dc = dc_next + dh_next * o * (1 - tanhc*tanhc)
    di, df, dg, do = dc*g, dc*c, dc*i, dh_next*tanhc
    dz = np.concatenate((di*i*(1-i), df*f*(1-f), dg*(1-g*g), do*o*(1-o)), axis=1)
    grads = {'wx': x.T @ dz, 'wh': h.T @ dz, 'b': dz.sum(axis=0)}
    return dz @ p['wx'].T, dz @ p['wh'].T, dc*f, grads


def forward(xs, p, h0=None, c0=None):
    T, B, _ = xs.shape
    H = p['wh'].shape[0]
    h = np.zeros((B, H)) if h0 is None else h0.copy()
    c = np.zeros((B, H)) if c0 is None else c0.copy()
    states, cells, caches = [], [], []
    for x in xs:
        h, c, cache = lstm_step_forward(x, h, c, p)
        states.append(h); cells.append(c); caches.append(cache)
    hs, cs = np.stack(states), np.stack(cells)
    return hs @ p['wy'] + p['by'], hs, cs, caches


def backward(dy, hs, caches, p):
    grads = {key: np.zeros_like(value) for key, value in p.items()}
    grads['wy'] = np.einsum('tbh,tbo->ho', hs, dy)
    grads['by'] = dy.sum(axis=(0, 1))
    dh = np.zeros_like(hs[0]); dc = np.zeros_like(dh)
    dxs = np.zeros((len(caches), hs.shape[1], p['wx'].shape[0]))
    for t in range(len(caches)-1, -1, -1):
        dh += dy[t] @ p['wy'].T
        dxs[t], dh, dc, step_grads = lstm_step_backward(dh, dc, caches[t])
        for key, value in step_grads.items():
            grads[key] += value
    return grads, dxs, dh, dc


def check_gradients():
    rng = np.random.default_rng(1712)
    xs = rng.normal(size=(4, 2, 3)); p = initialize(3, 2, 2, rng)
    h0 = rng.normal(size=(2, 2)); c0 = rng.normal(size=(2, 2))
    dy = rng.normal(size=(4, 2, 2))
    _, hs, _, caches = forward(xs, p, h0, c0)
    grads, dx, dh0, dc0 = backward(dy, hs, caches, p)
    def objective():
        return float(np.sum(forward(xs, p, h0, c0)[0] * dy))
    errors = []
    for arr, grad in [(p[k], grads[k]) for k in p] + [(xs, dx), (h0, dh0), (c0, dc0)]:
        for index in np.ndindex(arr.shape):
            old = arr[index]; eps = 1e-5
            arr[index] = old + eps; plus = objective()
            arr[index] = old - eps; minus = objective()
            arr[index] = old
            numerical = (plus-minus)/(2*eps)
            errors.append(abs(numerical-grad[index]))
    print('Gradcheck, error absoluto máximo:', max(errors))
    assert max(errors) < 1e-7


def adding_batch(T, B, rng):
    values = rng.random((T, B)); markers = np.zeros((T, B))
    for b in range(B):
        positions = rng.choice(T, 2, replace=False)
        markers[positions, b] = 1
    target = (values*markers).sum(axis=0)[:, None]
    return np.stack((values, markers), axis=2), target


def update(p, grads, rate, cap=1.0):
    norm = np.sqrt(sum(np.sum(g*g) for g in grads.values()))
    if not np.isfinite(norm) or not np.isfinite(cap) or cap <= 0:
        raise ValueError('Gradiente o límite no finito o inválido')
    scale = min(1.0, cap/norm) if norm else 1.0
    for key in p:
        p[key] -= rate*scale*grads[key]


def train_adding(steps=3, T=100):
    if steps < 1 or T < 2:
        raise ValueError('Se necesitan pasos positivos y T >= 2')
    rng = np.random.default_rng(1713); p = initialize(2, 8, 1, rng)
    for _ in range(steps):
        xs, target = adding_batch(T, 8, rng)
        ys, hs, _, caches = forward(xs, p)
        error = ys[-1] - target
        loss = float(np.mean(error**2))
        dy = np.zeros_like(ys); dy[-1] = 2*error/error.size
        grads, _, _, _ = backward(dy, hs, caches, p)
        update(p, grads, .01)
    # Semilla distinta; no participa en la actualización ni representa test final.
    vx, vy = adding_batch(T, 32, np.random.default_rng(1715))
    prediction = forward(vx, p)[0][-1]
    validation = float(np.mean((prediction - vy)**2))
    baseline = float(np.mean((1. - vy)**2))
    print('Suma, última pérdida train:', loss, '| validación MSE:', validation,
          '| baseline constante 1 MSE:', baseline, '| pasos:', steps, '| T:', T)
    return p


def train_characters(steps=3):
    if steps < 1:
        raise ValueError('Se necesitan pasos positivos')
    # Fragmentos de la celda vigente m17-l09, Don Quijote, capítulos I y II:
    # https://www.gutenberg.org/files/2000/2000-0.txt
    text = 'en un lugar de la mancha, de cuyo nombre no quiero acordarme'
    valid = 'hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
    alphabet = ['<unk>', *sorted(set(text))]; ids = {ch: i for i, ch in enumerate(alphabet)}
    xs = np.eye(len(alphabet))[[ids[ch] for ch in text[:-1]]][:, None, :]
    target = np.array([ids[ch] for ch in text[1:]])
    rng = np.random.default_rng(1714); p = initialize(len(alphabet), 8, len(alphabet), rng)
    for _ in range(steps):
        logits, hs, _, caches = forward(xs, p)
        shifted = logits[:, 0] - logits[:, 0].max(axis=1, keepdims=True)
        probs = np.exp(shifted); probs /= probs.sum(axis=1, keepdims=True)
        loss = float(-np.log(probs[np.arange(len(target)), target]).mean())
        dy = probs.copy(); dy[np.arange(len(target)), target] -= 1
        grads, _, _, _ = backward((dy/len(target))[:, None, :], hs, caches, p)
        update(p, grads, .05)
    valid_ids = np.array([ids.get(ch, 0) for ch in valid])
    valid_x = np.eye(len(alphabet))[valid_ids[:-1]][:, None, :]
    valid_logits = forward(valid_x, p)[0][:, 0]
    valid_logits -= valid_logits.max(axis=1, keepdims=True)
    logz = np.log(np.exp(valid_logits).sum(axis=1))
    valid_loss = float(np.mean(logz - valid_logits[np.arange(len(valid_ids)-1), valid_ids[1:]]))
    print('Caracteres, última pérdida train:', loss, '| validación nats:', valid_loss,
          '| caracteres OOV:', int((valid_ids == 0).sum()), '| pasos:', steps)
    print('La clase UNK no tiene ejemplos positivos en train. No se modela EOS.')
    print('Muestra ancestral con límite de 40 pasos:', generate_characters(p, alphabet, 'en ', 40, 1716))
    return p, alphabet


def generate_characters(p, alphabet, prefix, length, seed):
    if not prefix or length < 0:
        raise ValueError('Prefijo vacío o longitud negativa')
    index = {ch: i for i, ch in enumerate(alphabet)}
    h = np.zeros((1, p['wh'].shape[0])); c = np.zeros_like(h)
    def consume(token):
        nonlocal h, c
        vector = np.eye(len(alphabet))[[token]]
        h, c, _ = lstm_step_forward(vector, h, c, p)
    for ch in prefix:
        consume(index.get(ch, 0))
    rng = np.random.default_rng(seed); out = []
    for _ in range(length):
        logits = (h @ p['wy'] + p['by'])[0]
        probabilities = np.exp(logits - logits.max()); probabilities /= probabilities.sum()
        token = int(rng.choice(len(alphabet), p=probabilities))
        out.append('<unk>' if token == 0 else alphabet[token])
        consume(token)
    return ''.join(out)


# Extensión local: los pesos y backward anteriores se incluyen para que
# la celda sea autocontenida y no dependa de archivos de informes.
import json
import math
import os
import time
from pathlib import Path
import torch
from torch import nn
from torch.profiler import profile, ProfilerActivity

torch.set_num_threads(1)
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
SEEDS = [17120] if SHORT else [17120, 17121, 17122]
STEPS = 8 if SHORT else 1200
LENGTH = 20 if SHORT else 100
BATCH = 8 if SHORT else 64
HIDDEN = 16 if SHORT else 64
EVAL_N = 32 if SHORT else 512
OUTPUT = Path(os.environ.get('ORYON_OUTPUT', 'lstm_comparacion.json'))


class TorchLSTM(nn.Module):
    def __init__(self, p, second_bias=None):
        super().__init__()
        d, four_h = p['wx'].shape
        h, out = p['wh'].shape[0], p['wy'].shape[1]
        if four_h != 4*h:
            raise ValueError('La anchura debe contener cuatro puertas')
        self.lstm = nn.LSTM(d, h, dtype=torch.float64)
        self.head = nn.Linear(h, out, dtype=torch.float64)
        bias_hh = np.zeros(4*h) if second_bias is None else second_bias
        with torch.no_grad():
            self.lstm.weight_ih_l0.copy_(torch.from_numpy(p['wx'].T.copy()))
            self.lstm.weight_hh_l0.copy_(torch.from_numpy(p['wh'].T.copy()))
            # PyTorch suma los dos sesgos: su suma debe ser el sesgo de NumPy.
            self.lstm.bias_hh_l0.copy_(torch.as_tensor(bias_hh))
            self.lstm.bias_ih_l0.copy_(torch.as_tensor(p['b'] - bias_hh))
            self.head.weight.copy_(torch.from_numpy(p['wy'].T.copy()))
            self.head.bias.copy_(torch.from_numpy(p['by']))

    def forward(self, xs, state):
        hs, (hn, cn) = self.lstm(xs, state)
        return self.head(hs), hs, hn, cn


def manual_torch(model, xs, state):
    """Celda explícita i,f,g,o; usa exactamente los pesos del módulo."""
    h, c = state[0][0], state[1][0]
    lstm = model.lstm
    states, cells = [], []
    for x in xs.unbind(0):
        z = (x @ lstm.weight_ih_l0.T + lstm.bias_ih_l0 +
             h @ lstm.weight_hh_l0.T + lstm.bias_hh_l0)
        zi, zf, zg, zo = z.chunk(4, dim=1)
        i, f, g, o = zi.sigmoid(), zf.sigmoid(), zg.tanh(), zo.sigmoid()
        c = f * c + i * g
        h = o * c.tanh()
        states.append(h)
        cells.append(c)
    hs = torch.stack(states)
    cs = torch.stack(cells)
    return model.head(hs), hs, h.unsqueeze(0), c.unsqueeze(0), cs


def max_error(a, b):
    return float(np.max(np.abs(np.asarray(a) - np.asarray(b))))


def verify_parity():
    rng = np.random.default_rng(17120)
    p = initialize(3, 4, 2, rng, forget_bias=1.)
    bias_hh = rng.normal(0., .1, 16)
    xs = rng.normal(size=(5, 2, 3))
    h0, c0 = rng.normal(size=(2, 4)), rng.normal(size=(2, 4))
    dy = rng.normal(size=(5, 2, 2))
    y_np, hs_np, cs_np, caches = forward(xs, p, h0, c0)
    grads, dx, dh0, dc0 = backward(dy, hs_np, caches, p)
    errors = {}
    for mode in ('fused', 'manual'):
        model = TorchLSTM(p, bias_hh)
        x = torch.tensor(xs, requires_grad=True)
        h = torch.tensor(h0[None], requires_grad=True)
        c = torch.tensor(c0[None], requires_grad=True)
        if mode == 'fused':
            y, hs, hn, cn = model(x, (h, c))
        else:
            y, hs, hn, cn, cs = manual_torch(model, x, (h, c))
            errors['manual_cells'] = max_error(cs.detach().numpy(), cs_np)
        (y * torch.tensor(dy)).sum().backward()
        vals = {
            'output': max_error(y.detach().numpy(), y_np),
            'states': max_error(hs.detach().numpy(), hs_np),
            'last_h': max_error(hn.detach().numpy()[0], hs_np[-1]),
            'last_c': max_error(cn.detach().numpy()[0], cs_np[-1]),
            'wx': max_error(model.lstm.weight_ih_l0.grad.numpy().T, grads['wx']),
            'wh': max_error(model.lstm.weight_hh_l0.grad.numpy().T, grads['wh']),
            'bias_ih': max_error(model.lstm.bias_ih_l0.grad.numpy(), grads['b']),
            'bias_hh': max_error(model.lstm.bias_hh_l0.grad.numpy(), grads['b']),
            'wy': max_error(model.head.weight.grad.numpy().T, grads['wy']),
            'by': max_error(model.head.bias.grad.numpy(), grads['by']),
            'input': max_error(x.grad.numpy(), dx),
            'h0': max_error(h.grad.numpy()[0], dh0),
            'c0': max_error(c.grad.numpy()[0], dc0),
        }
        errors.update({f'{mode}_{key}': value for key, value in vals.items()})
    # nn.LSTM expone la celda final; procesar un paso cada vez permite
    # contrastar también cada c_t con NumPy, preservando el estado.
    model = TorchLSTM(p, bias_hh)
    state = (torch.tensor(h0[None]), torch.tensor(c0[None]))
    cells = []
    with torch.no_grad():
        for x in torch.tensor(xs).split(1, dim=0):
            _, state = model.lstm(x, state)
            cells.append(state[1][0].numpy())
    errors['fused_cells'] = max_error(np.stack(cells), cs_np)
    if not all(math.isfinite(e) and e < 1e-9 for e in errors.values()):
        raise AssertionError(('Paridad NumPy/PyTorch incorrecta', errors))
    return errors


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


def benchmark():
    """Mismo forward, pérdida y backward; tiempo sincronizado, sin actualizar pesos."""
    rng = np.random.default_rng(17122)
    p = initialize(2, HIDDEN, 1, rng)
    model = TorchLSTM(p).to(device=DEVICE, dtype=torch.float32)
    xs = torch.randn(LENGTH, BATCH, 2, device=DEVICE)
    state = (torch.zeros(1, BATCH, HIDDEN, device=DEVICE),
             torch.zeros(1, BATCH, HIDDEN, device=DEVICE))
    # Detectar la operación concreta observada, sin confundir disponibilidad
    # de cuDNN con que esta llamada lo haya utilizado.
    with profile(activities=[ProfilerActivity.CPU]) as prof:
        y, _, _, _ = model(xs, state)
        y.square().mean().backward()
    operators = {entry.key for entry in prof.key_averages()}
    cudnn_observed = 'aten::_cudnn_rnn' in operators
    results = {}
    repeats = 3 if SHORT else 20
    warmup = 1 if SHORT else 5
    for mode in ('fused', 'manual'):
        def iteration():
            model.zero_grad(set_to_none=True)
            output = (model(xs, state)[0] if mode == 'fused'
                      else manual_torch(model, xs, state)[0])
            output.square().mean().backward()
        for _ in range(warmup):
            iteration()
        sync(DEVICE)
        times = []
        for _ in range(repeats):
            sync(DEVICE)
            start = time.perf_counter()
            iteration()
            sync(DEVICE)
            times.append(time.perf_counter() - start)
        if not all(math.isfinite(t) and t > 0 for t in times):
            raise ValueError('Tiempo de benchmark inválido')
        results[mode] = {'segundos': times, 'mediana': float(np.median(times))}
    results['manual_sobre_fused'] = results['manual']['mediana'] / results['fused']['mediana']
    results['cudnn_observado'] = cudnn_observed
    results['backend'] = 'cuDNN observado' if cudnn_observed else 'no confirmado'
    results['alcance'] = ('forward y backward, sin optimizador; tiempos orientativos '
                         'bajo carga compartida; celda manual usa bucle Python')
    del model, xs, state
    if DEVICE.type == 'cuda':
        torch.cuda.empty_cache()
    return results


@torch.inference_mode()
def evaluate_adding(model, data):
    model.eval()
    x, y = data
    out = model(x.to(DEVICE), (
        torch.zeros(1, x.shape[1], HIDDEN, device=DEVICE),
        torch.zeros(1, x.shape[1], HIDDEN, device=DEVICE)))[0][-1]
    mse = float((out - y.to(DEVICE)).square().mean())
    if not math.isfinite(mse):
        raise ValueError('MSE de evaluación no finita')
    return mse


def make_adding(seed, count):
    x, y = adding_batch(LENGTH, count, np.random.default_rng(seed))
    return torch.tensor(x, dtype=torch.float32), torch.tensor(y, dtype=torch.float32)


def train_forget_bias(seed, bias):
    """Los datos y la inicialización están emparejados entre condiciones."""
    torch.manual_seed(seed)
    p = initialize(2, HIDDEN, 1, np.random.default_rng(seed), forget_bias=bias)
    model = TorchLSTM(p).to(device=DEVICE, dtype=torch.float32)
    # Congelar el segundo sesgo permite exactamente un sesgo efectivo entrenable.
    model.lstm.bias_hh_l0.requires_grad_(False)
    optimizer = torch.optim.Adam((q for q in model.parameters() if q.requires_grad), lr=.001)
    val = make_adding(seed + 1000, EVAL_N)
    test = make_adding(seed + 2000, EVAL_N)
    train_rng = np.random.default_rng(seed + 3000)
    best, best_step, best_state = math.inf, None, None
    history = []
    interval = max(1, STEPS // 10)
    for step in range(1, STEPS + 1):
        model.train()
        x, y = adding_batch(LENGTH, BATCH, train_rng)
        xt = torch.tensor(x, dtype=torch.float32, device=DEVICE)
        yt = torch.tensor(y, dtype=torch.float32, device=DEVICE)
        zero = torch.zeros(1, BATCH, HIDDEN, device=DEVICE)
        optimizer.zero_grad(set_to_none=True)
        predictions = model(xt, (zero, zero))[0][-1]
        loss = (predictions - yt).square().mean()
        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()
        if step == 1 or step % interval == 0 or step == STEPS:
            mse = evaluate_adding(model, val)
            history.append({'paso': step, 'mse_validacion': mse,
                            'norma_pre_recorte': float(norm)})
            if mse < best:
                best, best_step = mse, step
                best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
    if best_state is None:
        raise ValueError('No existe checkpoint válido')
    model.load_state_dict(best_state)
    result = {'semilla': seed, 'sesgo_olvido_inicial': bias, 'paso_elegido': best_step,
              'mse_validacion': best, 'mse_test_exploratorio': evaluate_adding(model, test),
              'historial': history}
    del model, optimizer
    if DEVICE.type == 'cuda':
        torch.cuda.empty_cache()
    return result


def main_local():
    print('Errores máximos NumPy, nn.LSTM y celda manual:', verify_parity())
    timing = benchmark()
    print('Tiempos exploratorios:', timing)
    rows = [train_forget_bias(seed, b) for seed in SEEDS for b in (0., 1.)]
    payload = {
        'corto': SHORT, 'dispositivo': str(DEVICE), 'torch': torch.__version__,
        'nombre_gpu': torch.cuda.get_device_name(DEVICE) if DEVICE.type == 'cuda' else None,
        'cuda': torch.version.cuda, 'cudnn': torch.backends.cudnn.version(),
        'protocolo': {'longitud': LENGTH, 'pasos': STEPS, 'lote': BATCH,
                      'ocultas': HIDDEN, 'n_validacion': EVAL_N, 'n_test': EVAL_N,
                      'semillas': SEEDS, 'recorte_norma': 1.,
                      'referencia_mse_constante_1_poblacional': 1 / 6,
                      'particiones': 'generadores independientes; sin detectar duplicados',
                      'seleccion': 'menor MSE de validación por condición',
                      'test': 'exploratorio por comparación de condiciones'},
        'benchmark': timing, 'resultados': rows,
    }
    OUTPUT.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding='utf-8')
    print(json.dumps(payload, indent=2, ensure_ascii=False))
    print('SHORT comprueba el recorrido; no demuestra convergencia ni superioridad.')
    print('Las salidas y gradientes comparados usan doble precisión y tolerancia explícita.')
    print('Misma semilla empareja datos e inicialización; la GPU puede variar numéricamente.')


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

Exercises

NumericFour gates and two biases
For a one-layer PyTorch LSTM with input d=256 and state H=512, without projection or output head, how many parameters are there counting both biases?
NumericOne hundred multiplications
A direct path retains f=0.99 for 100 steps and has no writing. What fraction of c₀ remains?
ProofOne product and other paths
Prove: Derive the direct cell-path contribution across several steps.
0
Hold gates fixed while following this path and use elementwise multiplication.

Step 1 of 3. What is the direct derivative of Cₜ with respect to Cₜ₋₁?

QuizStore without showing
A cell has nonzero content but its output h is near zero. What condition can directly produce this?
CodeTwo paths to the cell
Implement lstm_step_backward(dh_next, dc_next, cache) for a peephole-free cell. cache contains (x,h,c,i,f,g,o,cn,wx,wh), with row examples and weights concatenated in i,f,g,o order. Return dx, dh, dc, dwx, dwh, db; combine both signals arriving at cn and do not modify the cache. Arrays are float64 with compatible dimensions.
import numpy as np

def lstm_step_backward(dh_next, dc_next, cache):
  pass
Shift+Enter to run

Further connections

Gates and additive connections link to Activation saturation and gradient-preservation methods in Spectral conditions for vanishing and exploding gradients in RNNs. Evaluating memory needs states, outputs, gradients and a task with data separation, not only a gate plot.