Module contents
Lesson 11 of 24Advanced 105 min

Vanishing and exploding gradients through time

Analyze temporal Jacobians, vanishing and exploding gradients, clipping and recurrent memory benchmarks.

After this lesson you can

  • Derive sufficient spectral bounds for temporal gradient transport.
  • Distinguish transient amplification, retention and learnability.
  • Explain clipping and identity or orthogonal initialization and their limits.
  • Evaluate adding and copying tasks under controlled protocols.

Before you start

A signal that must travel

An RNN can in principle contain a state capable of remembering an input. Learning to use it is another matter: a late prediction’s error must cross every transition separating it from that input. If the arriving signal is tiny, the optimizer receives little information about changing earlier decisions. If enormous, an update can jump outside the region being explored.

The character network in Recurrent neural network (Elman network) and its Backpropagation through time provide a starting point. Its small sample does not demonstrate failure at a particular distance; here we study the mechanism and then measure it. Nor does every small loss mean useful memory: compare against a baseline and retain independent data.

A product, not just any power

For column states define at=Wht−1+Uxt+ba_t=Wh_{t-1}+Ux_t+b, ht=ϕ(at)h_t=\phi(a_t) and Dt=diag⁡(ϕ′(at))D_t=\operatorname{diag}(\phi'(a_t)). With fixed parameters and inputs, one transition’s Jacobian is

Jt=∂ht∂ht−1=DtW,∂hT∂ht=JTJT−1⋯Jt+1.J_t=\frac{\partial h_t}{\partial h_{t-1}}=D_tW, \qquad \frac{\partial h_T}{\partial h_t}=J_TJ_{T-1}\cdots J_{t+1}.

Order matters. Although WW is shared, DtD_t depends on each step’s state and input. For terminal loss LTL_T, the column gradient toward hth_t is (JT⋯Jt+1)⊤∇hTLT(J_T\cdots J_{t+1})^\top\nabla_{h_T}L_T. For loss with intermediate terms, each term generates an additional contribution; a vanishing remote contribution does not mean the entire parameter gradient is small. Pascanu, Mikolov and Bengio decompose BPTT into precisely these temporal contributions.

Suppose ∣ϕ′(z)∣≤γ|\phi'(z)|\leq\gamma at all visited points. Spectral-norm submultiplicativity gives

∥∂hT∂ht∥2≤∏j=t+1T∥Dj∥2∥W∥2≤(γσmax⁡(W))T−t.\left\|\frac{\partial h_T}{\partial h_t}\right\|_2 \leq \prod_{j=t+1}^T\|D_j\|_2\|W\|_2 \leq (\gamma\sigma_{\max}(W))^{T-t}.

The sufficient spectral contraction condition is q=γσmax⁡(W)<1q=\gamma\sigma_{\max}(W)<1: the bound then tends exponentially to zero. A gradient contribution also vanishes if its loss and immediate-derivative factors remain bounded. If q≤1q\leq1, state transport cannot grow exponentially under this bound; thus q>1q>1 is necessary for exponential explosion under these assumptions, but not sufficient. The total gradient is a sum and needs separate analysis. For tanh take γ=1\gamma=1; for ReLU the derivative is 0 or 1 away from the corner, with a subderivative chosen at zero.

The bound is uniform, not necessarily tight. An orthogonal matrix has σi=1\sigma_i=1, but saturated tanh can make some entries of DtD_t near zero. Conversely, spectral radius below one does not prevent transient amplification if the matrix is non-normal. For example, with W=(0.9100.9)W=\begin{pmatrix}0.9&1\\0&0.9\end{pmatrix}, both eigenvalues are 0.9 and WnW^n contains term n(0.9)n−1n(0.9)^{n-1}. It grows temporarily before tending to zero. The figure calculates product norm for an explicit trajectory.

InteractiveRadius, non-normality and saturation

Explicit model without input: W = [[ρ, coupling], [0, ρ]], h₀ = (s,s). The curve is the spectral norm of the product Jₜ ··· J₁, not a measurement from a trained network.

10^-1210^-610^010^6Steps: 0 to 40
  • Spectral norm of product

Logarithmic scale, visually clipped between 10⁻¹² and 10⁶. With tanh the displayed trajectory is differentiated; saturation at each step modifies the Jacobian. A norm greater than one permits amplification in some direction, not every direction.

Activation
0.90
1.0
0.5
Initial norm1.00
Maximum over 40 steps3.913
Norm at step 400.657261
Norm of W1.530
Spectral radius describes W's eigenvalues; the curve calculates the norm of the complete Jacobian product.

In the diagonalizable linear case W=VΛV−1W=V\Lambda V^{-1}, an initial perturbation along a right eigenvector is multiplied by λin\lambda_i^n. Column gradients use (W⊤)n(W^\top)^n and eigenvectors of W⊤W^\top, not necessarily the same ones. If WW is non-normal, eigenvectors may not be orthogonal and their combination can amplify transiently. An eigenvalue with modulus above one does not force a particular nonlinear trajectory to explode either.

Retaining and learning

In a locally contractive attractor, nearby perturbed states converge and a representation is robust to noise. The same contraction attenuates an old change’s influence on current state. Bengio, Simard and Frasconi study the long-term dependency dilemma: tension between storing information for a long time, resisting perturbations and learning dependencies by gradient descent. This observation depends on dynamics and the region traversed: it does not show all robust memory makes all learning impossible, or that vanishing means representational inability.

A system can preserve one direction and contract another; a gate can select when to write and forget. The difficulty of Jacobian products motivates gated architectures studied later, without guaranteeing all optimization problems disappear.

Fixed points and walls

Consider scalar system xt=wtanh⁡(xt−1)+bx_t=w\tanh(x_{t-1})+b. A fixed point satisfies x∗=wtanh⁡(x∗)+bx^*=w\tanh(x^*)+b. If ∣wsech⁡2(x∗)∣<1|w\operatorname{sech}^2(x^*)|<1 it is locally asymptotically stable; if above one, unstable. At exactly one that linear test is inconclusive and higher-order terms must be studied. With w>1w>1, stable branches separated by an unstable one can coexist. Near a stability transition, small parameter changes can change a trajectory and produce a steep loss region. This is the dynamical intuition behind walls and exploding gradients studied by Pascanu and colleagues, not a universal equivalence between bifurcation and explosion of every loss.

InteractiveOne neuron, multiple branches

Scalar system xₜ = w tanh(xₜ₋₁) + b. Fixed points are parametrized exactly by b = x − w tanh(x); the 50-step curve depends on the initial state.

Bias b: −1.5 to 1.53.5−3.5
  • Stable fixed point
  • Unstable fixed point
  • Slope magnitude 1
  • State after 50 steps

A slope magnitude below 1 guarantees local stability; above 1 implies instability. At exactly 1 this linear test is inconclusive; points are classified with numerical tolerance 10⁻¹⁰. Finite sensitivity is calculated by exact recurrence; it is not the equilibrium derivative. A bifurcation does not imply that every loss or gradient explodes.

1.50
0.00
0.1
State after 50 steps1.2878
Sensitivity ∂x₅₀/∂b1.6510
Local transition slope0.3943
The 50-step state curve also depends on initial state; fixed points are calculated by parameterizing their equation.

In the interactive, b=x∗−wtanh⁡(x∗)b=x^*-w\tanh(x^*) plots branches without numerically solving an equation. For a finite trajectory, s0=0s_0=0 and st=w(1−tanh⁡2(xt−1))st−1+1s_t=w(1-\tanh^2(x_{t-1}))s_{t-1}+1 exactly calculate st=∂xt/∂bs_t=\partial x_t/\partial b. That finite sensitivity is not automatically the equilibrium derivative. Figure branches are not training results.

InteractiveDescent beside a wall

Explicit model: x₀=0.1; xₜ=w tanh(xₜ₋₁)+b for 25 steps; L=(x₂₅−1)²/2. Loss and derivatives are recomputed at each of 20 descent steps.

w: −0.5 to 2.5b=1b=−1
  • Without clipping
  • With clipping
  • Loss: darker means greater

Intensity saturates at L≥4. Paths use direct descent with the same rate; clipping does not guarantee lower loss or fix small signals. Parameters outside the frame are not clipped.

1.50
0.00
0.20
0.5
Initial loss0.0414
Initial gradient norm0.6264
Final loss without clipping0.0000
Final loss with clipping0.0000
Steps outside map, without / with0 / 0
Two trajectories calculated on the same scalar loss compare descent with and without norm clipping.

Clip and preserve

With global gradient gg and threshold c>0c>0, norm clipping uses g′=gmin⁡(1,c/∥g∥2)g'=g\min(1,c/\|g\|_2), with g′=0g'=0 if g=0g=0. It preserves direction and limits the gradient norm delivered to the optimizer; it does not by itself guarantee an Adam update, with its states and rates, has norm below cc. It neither enlarges tiny gradients nor guarantees stability of the entire trajectory. Componentwise clipping is a different operation and can change direction.

Pascanu and colleagues also propose a soft term penalizing norm changes during temporal propagation. Their regularizer encourages norm preservation in observed directions; it does not turn all Jacobians into isometries or guarantee useful memory. Training loss, threshold and norm definition must be specified when comparing experiments.

Identity, orthogonality and their limits

An IRNN applies identity recurrent initialization: initialize W=IW=I and use ReLU. While all relevant units are active, Dt=ID_t=I and the initial product preserves that part of the signal. An inactive ReLU introduces zero; updates modify WW unless constrained. A scaled identity αI\alpha I changes propagation to αn\alpha^n in the active region, allowing time-scale adjustment but also contraction or amplification. Learning rate and clipping matter.

In Le, Jaitly and Hinton’s evaluation, the adding problem uses 100,000 training examples, 10,000 test examples and 100 hidden units; they explore lengths 150, 200, 300 and 400. They search learning rates from 10−910^{-9} to 10−110^{-1} and clipping thresholds 1, 10, 100 and 1,000 with batches of 16. Results depend on that search. In sequential MNIST they process 784 pixels, also with a fixed permutation; they report 3% IRNN test error for original order, without claiming superiority on every task.

If Q⊤Q=IQ^\top Q=I, then ∥Qv∥2=∥v∥2\|Qv\|_2=\|v\|_2. Orthogonal and unitary recurrences exploit this: a purely orthogonal linear transition preserves norms and does not contract differences, so it cannot forget through contraction. Activation, output projection and inputs can change that conclusion for the complete network. Orthogonal initialization does not maintain the constraint after updating. A parameterization can enforce it: Q=exp⁡(A)Q=\exp(A) for A⊤=−AA^\top=-A, or Cayley transform (I−A)(I+A)−1(I-A)(I+A)^{-1} when the inverse exists. Cayley does not represent matrices with eigenvalue −1; the real antisymmetric exponential yields orthogonal matrices of determinant +1. Over complex numbers the analogous condition is U∗U=IU^*U=I; Arjovsky and colleagues build a uRNN with structured unitary factors, a family with its own constraints, not any unitary matrix without cost.

Vorontsov and colleagues compare spectral constraints in one architecture. In Table 1 for permuted sequential MNIST, with 128 units and their protocol, accuracy changes from 83.56% with zero spectral margin to 91.44% with margin 0.1; this does not show relaxing orthogonality always improves results. It illustrates the stability-flexibility tradeoff.

Adding and copying problems

In adding, each step carries a uniform number in [0,1][0,1] and a marker; two distinct positions are selected and the target is their values’ sum. Constant prediction 1 has population MSE 1/61/6 if values are independent uniform and position selection independent of them. The IRNN paper cites approximately 0.1767 for that baseline without explaining the figure’s origin; it differs from the exact theoretical value 1/61/6 for this ideal distribution. Copying requires remembering symbols over a delay and emitting them when signaled; state alphabet, prefix length, delay and positions included in loss. A model always predicting blank can obtain misleading accuracy when many positions are blank.

Comparing tanh, IRNN and orthogonal recurrence must fix architecture, initialization, seeds, data generation, success criterion, splits and budget. A short run verifies the pipeline; it cannot identify a reliable maximum horizon. Permuted MNIST requires one fixed permutation applied equally to training and evaluation, and reserved test.

The next figure shows the local cell’s short run: twelve updates, one seed and length or delay 20. Each curve comes from the report generated by that cell. Change task and compare metrics with their theoretical baseline; this sample only checks the pipeline and does not establish a learned horizon.

InteractiveA short memory test

Lab report: short run to verify the pipeline, device cuda, PyTorch 2.11.0+cu128. Data: 64 training examples and 32 validation examples. Values are validation, not test results or invented metrics.

Mean squared error on validation

0.001.042.07112Updates
tanhIRNNorthogonal

Dotted line: population MSE for predicting 1 = 0.1667. A finite sample may differ from that value.

Show validation data
MethodStepValue
tanh11.04077
tanh20.97818
tanh30.91819
tanh40.86095
tanh50.80666
tanh60.75535
tanh70.70689
tanh80.66103
tanh90.61755
tanh100.57626
tanh110.53709
tanh120.49996
IRNN11.92016
IRNN21.36659
IRNN30.95999
IRNN40.66335
IRNN50.44622
IRNN60.29194
IRNN70.19757
IRNN80.16384
IRNN90.17621
IRNN100.19544
IRNN110.20463
IRNN120.20102
orthogonal11.13217
orthogonal21.09119
orthogonal31.05241
orthogonal41.01533
orthogonal50.98034
orthogonal60.94592
orthogonal70.91181
orthogonal80.87825
orthogonal90.84564
orthogonal100.81385
orthogonal110.78316
orthogonal120.75317

IRNN initialization uses ReLU and identity; the orthogonal method uses tanh and maintains the constraint through parametrization. These are distinct architectural decisions, not a single-factor ablation. Each curve represents one seed; the full protocol includes several. No maximum horizon or guaranteed learning is claimed from the short run. Test is exploratory when multiple configurations are consulted.

Task
Length T20
Seed17110
Planned steps12
Compare actual adding and copying validation curves with their theoretical baselines.

Labs

The next cell reuses the previous lesson’s character RNN. It measures final-step loss gradient with respect to each earlier state before and after 25 exploratory updates, and checks the bound with current singular norm. It sets three initial recurrent-matrix norms without attributing spectral radii to them. One excerpt and seed do not support generalization comparisons. Output includes full traces for plotting; finite differences check the derivative with respect to initial state.

[ ]Gradients through timeBrowser
"""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())


# Medición añadida para m17-l11; la RNN anterior es la celda vigente de l09.
def terminal_gradients(params, ids, target, h0):
    """Norma de ∂L_T/∂h_t desde el último estado hasta h_0, y cota uniforme."""
    states, last, cache = rnn_forward(params['E'][ids], h0, params)
    logits = (last @ params['Wy'] + params['by'])[0]
    logits -= logits.max()
    p = np.exp(logits)
    p /= p.sum()
    p[target] -= 1.
    gradient = (p @ params['Wy'].T)[None, :]
    terminal_norm = float(np.linalg.norm(gradient))
    sigma = float(np.linalg.norm(params['Wh'], ord=2))
    norms = [terminal_norm]
    for _, _, state in reversed(cache):
        gradient = (gradient * (1. - state * state)) @ params['Wh'].T
        norms.append(float(np.linalg.norm(gradient)))
    bound = [terminal_norm * sigma ** lag for lag in range(len(norms))]
    assert all(value <= limit + 1e-10 * max(1., limit)
               for value, limit in zip(norms, bound))
    return {'sigma_max': sigma, 'terminal_norm': terminal_norm,
            'distance': list(range(len(norms))), 'norms': norms, 'bound': bound}


def jacobian_checks():
    params = initial_params(4, 2, 3, SEED)
    ids = np.array([[4, 2, 3]], dtype=np.int64)
    h = np.array([[.1, -.2, .05]])
    result = terminal_gradients(params, ids, 1, h)
    # teacher_loss con máscara solo en el último paso tiene esa misma dL/dh0.
    mask = np.array([[0., 0., 1.]])
    _, _, _, dh0 = teacher_loss(params, ids, np.array([[2, 3, 1]]), h,
                                backward=True, mask=mask)
    assert np.isclose(np.linalg.norm(dh0), result['norms'][-1], atol=1e-12)
    # Diferencias finitas de la pérdida terminal respecto a cada componente h0.
    for j in range(h.shape[1]):
        original = h[0, j]
        h[0, j] = original + 1e-6
        plus = teacher_loss(params, ids, np.array([[2, 3, 1]]), h, mask=mask)[0]
        h[0, j] = original - 1e-6
        minus = teacher_loss(params, ids, np.array([[2, 3, 1]]), h, mask=mask)[0]
        h[0, j] = original
        assert abs((plus - minus) / 2e-6 - dh0[0, j]) < 1e-7
    print('Gradiente terminal y cota contrastados con BPTT y diferencias finitas.')


def main_gradients():
    jacobian_checks()
    vocab, train, valid = prepare(TRAIN_TEXT, VALID_TEXT)
    inputs, targets = sequence_events(train, len(vocab), vocab.index(EOS))
    result = {}
    for scale in (.5, 1., 1.5):
        params = initial_params(len(vocab), embed=6, hidden=10, seed=SEED)
        # Ajusta la norma singular, no el radio espectral.
        params['Wh'] *= scale / np.linalg.norm(params['Wh'], ord=2)
        h0 = np.zeros((1, len(params['bh'])))
        before = terminal_gradients(params, inputs[None, :], int(targets[-1]), h0)
        train_small(params, train, valid, steps=25, rate=.3)
        after = terminal_gradients(params, inputs[None, :], int(targets[-1]), h0)
        result[str(scale)] = {'initial': before, 'after_25_steps': after}
        print('Escala inicial:', scale, 'sigma antes/después:',
              before['sigma_max'], after['sigma_max'])
        print('Norma terminal y a distancia completa, antes:',
              before['norms'][0], before['norms'][-1],
              '| después:', after['norms'][0], after['norms'][-1])
    print('Trazas completas:', json.dumps(result, ensure_ascii=False))
    print('Muestra diminuta y una semilla: verifica el mecanismo, no concluye rendimiento.')
    print('La cota usa la norma singular actual y gamma=1 para tanh; no es una predicción exacta.')


if __name__ == '__main__':
    main_gradients()

This local lab compares three recurrences on training, validation and test data generated with separate seeds. For copying it also checks prefixes differ within and between splits; adding does not check exact matches. Copying loss and accuracy are measured only on the eight output symbols after the delimiter; full-sequence accuracy is also reported. Checkpoints are selected by validation loss and test is consulted for several configurations, so results are exploratory. The orthogonal recurrent matrix remains Cayley-parameterized; IRNN starts at identity but may change during learning. The seed fixes data and initialization, though GPU execution may vary numerically.

With ORYON_VERIFY_SHORT=1, data, steps and seeds are reduced to check the pipeline without expecting convergence. The full experiment explores three lengths or delays and three seeds, but each configuration needs an additional success criterion and budget to estimate a horizon. The previous figure shows only the short run and cannot establish which architecture learns better.

[ ]Adding and copying with three recurrencesLocal GPU
"""Suma y copia con tres recurrencias. Entrenamiento completo para ejecución local.

ORYON_VERIFY_SHORT=1 verifica el recorrido con menos datos y pasos; no busca
convergencia. ORYON_OUTPUT controla el archivo JSON de resultados.
"""
import json
import math
import os
from pathlib import Path

import numpy as np
import torch
from torch import nn
from torch.nn.utils import clip_grad_norm_
from torch.nn.utils.parametrizations import orthogonal

SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
HIDDEN = 16 if SHORT else 64
STEPS = 12 if SHORT else 1500
BATCH = 16 if SHORT else 64
TRAIN_N = 64 if SHORT else 2048
EVAL_N = 32 if SHORT else 512
LENGTHS = [20] if SHORT else [40, 80, 160]
SEEDS = [17110] if SHORT else [17110, 17111, 17112]
LR = .001
CLIP = 1.
COPY_SYMBOLS = 8
COPY_PREFIX = 8
OUTPUT = Path(os.environ.get('ORYON_OUTPUT', 'rnn_long_memory.json'))


def adding(length, count, seed):
    if length < 2 or count < 1:
        raise ValueError('Longitud o número de ejemplos inválido')
    rng = np.random.default_rng(seed)
    values = rng.random((count, length)).astype(np.float32)
    mask = np.zeros((count, length), dtype=np.float32)
    for i in range(count):
        mask[i, rng.choice(length, 2, replace=False)] = 1.
    x = np.stack([values, mask], axis=-1)
    y = (values * mask).sum(axis=1)
    return torch.from_numpy(x), torch.from_numpy(y)


def copying(delay, count, seed, forbidden=()):
    """Prefijos únicos, excluyendo los presentes en particiones anteriores."""
    if delay < 1 or count < 1:
        raise ValueError('Retardo o número de ejemplos inválido')
    rng = np.random.default_rng(seed)
    seen = set(forbidden)
    if count > COPY_SYMBOLS ** COPY_PREFIX - len(seen):
        raise ValueError('No quedan suficientes prefijos distintos')
    rows = []
    for _ in range(max(1000, 20 * count)):
        prefix = tuple(int(v) for v in rng.integers(0, COPY_SYMBOLS, COPY_PREFIX))
        if prefix not in seen:
            seen.add(prefix)
            rows.append(prefix)
            if len(rows) == count:
                break
    if len(rows) != count:
        raise ValueError('No se reunieron suficientes prefijos únicos en el límite de intentos')
    target = np.asarray(rows, dtype=np.int64)
    inputs = np.full((count, 2 * COPY_PREFIX + delay + 1), COPY_SYMBOLS, dtype=np.int64)
    inputs[:, :COPY_PREFIX] = target
    inputs[:, COPY_PREFIX + delay] = COPY_SYMBOLS + 1
    return torch.from_numpy(inputs), torch.from_numpy(target)


class RecurrentModel(nn.Module):
    def __init__(self, task, mode):
        super().__init__()
        input_size = 2 if task == 'adding' else COPY_SYMBOLS + 2
        output_size = 1 if task == 'adding' else COPY_SYMBOLS
        nonlinearity = 'relu' if mode == 'irnn' else 'tanh'
        self.cell = nn.RNNCell(input_size, HIDDEN, nonlinearity=nonlinearity)
        self.head = nn.Linear(HIDDEN, output_size)
        self.task = task
        with torch.no_grad():
            nn.init.xavier_uniform_(self.cell.weight_ih)
            self.cell.bias_ih.zero_()
            self.cell.bias_hh.zero_()
            if mode == 'irnn':
                nn.init.eye_(self.cell.weight_hh)
            elif mode == 'orthogonal':
                nn.init.orthogonal_(self.cell.weight_hh)
            elif mode == 'tanh':
                nn.init.xavier_uniform_(self.cell.weight_hh)
            else:
                raise ValueError('Modo desconocido')
        if mode == 'orthogonal':
            orthogonal(self.cell, 'weight_hh', orthogonal_map='cayley')

    def forward(self, inputs):
        if self.task == 'copying':
            inputs = torch.nn.functional.one_hot(inputs, num_classes=COPY_SYMBOLS + 2).float()
        h = inputs.new_zeros((len(inputs), HIDDEN))
        outputs = []
        for t in range(inputs.shape[1]):
            h = self.cell(inputs[:, t], h)
            if self.task == 'copying' and t >= inputs.shape[1] - COPY_PREFIX:
                outputs.append(self.head(h))
        if self.task == 'adding':
            return self.head(h).squeeze(-1)
        return torch.stack(outputs, dim=1)


def metric(model, dataset, task):
    model.eval()
    x, y = (part.to(DEVICE) for part in dataset)
    with torch.no_grad():
        pred = model(x)
        if task == 'adding':
            values = {'mse': float(((pred - y) ** 2).mean().cpu())}
        else:
            loss = nn.functional.cross_entropy(pred.reshape(-1, COPY_SYMBOLS), y.reshape(-1))
            values = {'cross_entropy': float(loss.cpu()),
                      'symbol_accuracy': float((pred.argmax(-1) == y).float().mean().cpu()),
                      'exact_sequence_accuracy': float((pred.argmax(-1) == y).all(dim=1).float().mean().cpu())}
    if not all(math.isfinite(value) for value in values.values()):
        raise ValueError(f'Métrica de {task} no finita: {values}')
    return values


def run_experiment(task, mode, length, seed):
    torch.manual_seed(seed)
    if DEVICE.type == 'cuda':
        torch.cuda.manual_seed_all(seed)
    if task == 'adding':
        train = adding(length, TRAIN_N, seed + 100)
        val = adding(length, EVAL_N, seed + 200)
        test = adding(length, EVAL_N, seed + 300)
    else:
        train = copying(length, TRAIN_N, seed + 100)
        train_prefixes = {tuple(row) for row in train[1].tolist()}
        val = copying(length, EVAL_N, seed + 200, train_prefixes)
        val_prefixes = {tuple(row) for row in val[1].tolist()}
        test = copying(length, EVAL_N, seed + 300, train_prefixes | val_prefixes)
        test_prefixes = {tuple(row) for row in test[1].tolist()}
        assert len(train_prefixes) == TRAIN_N and len(val_prefixes) == EVAL_N
        assert len(test_prefixes) == EVAL_N
        assert not (train_prefixes & val_prefixes or train_prefixes & test_prefixes
                    or val_prefixes & test_prefixes)
    model = RecurrentModel(task, mode).to(DEVICE)
    optimizer = torch.optim.Adam(model.parameters(), lr=LR)
    rng = np.random.default_rng(seed + 400)
    best_state, best_metric, history = None, math.inf, []
    interval = max(1, STEPS // 12)
    for step in range(1, STEPS + 1):
        model.train()
        ids = torch.from_numpy(rng.integers(0, TRAIN_N, size=BATCH))
        x, y = train[0][ids].to(DEVICE), train[1][ids].to(DEVICE)
        optimizer.zero_grad(set_to_none=True)
        output = model(x)
        loss = (nn.functional.mse_loss(output, y) if task == 'adding' else
                nn.functional.cross_entropy(output.reshape(-1, COPY_SYMBOLS), y.reshape(-1)))
        if not torch.isfinite(loss):
            raise ValueError('Pérdida no finita')
        loss.backward()
        norm = clip_grad_norm_(model.parameters(), CLIP, error_if_nonfinite=True)
        optimizer.step()
        if step == 1 or step % interval == 0 or step == STEPS:
            measured = metric(model, val, task)
            score = measured['mse'] if task == 'adding' else measured['cross_entropy']
            history.append({'step': step, 'validation': measured,
                            'gradient_norm_before_clip': float(norm.cpu())})
            if score < best_metric:
                best_metric = score
                best_state = {key: value.detach().cpu().clone()
                              for key, value in model.state_dict().items()}
    model.load_state_dict(best_state)
    selected_test = metric(model, test, task)
    del model, optimizer
    if DEVICE.type == 'cuda':
        torch.cuda.empty_cache()
    return {'task': task, 'mode': mode, 'length_or_delay': length, 'seed': seed,
            'history': history, 'best_validation_loss': best_metric,
            'test_after_selection': selected_test}


def checks():
    x, y = adding(2, 10, 1)
    assert x.shape == (10, 2, 2) and torch.all(x[:, :, 1] == 1)
    assert torch.allclose(y, (x[:, :, 0] * x[:, :, 1]).sum(1))
    a, target = copying(3, 10, 1)
    assert a.shape == (10, 2 * COPY_PREFIX + 3 + 1)
    assert torch.equal(a[:, :COPY_PREFIX], target)
    assert torch.all(a[:, COPY_PREFIX + 3] == COPY_SYMBOLS + 1)
    assert torch.all(a[:, -COPY_PREFIX:] == COPY_SYMBOLS)
    known = {tuple(row) for row in target.tolist()}
    _, other = copying(3, 10, 2, known)
    other_prefixes = {tuple(row) for row in other.tolist()}
    assert len(known) == len(other_prefixes) == 10 and not known & other_prefixes
    _, repeated = copying(3, 10, 2, known)
    assert torch.equal(other, repeated)


def main():
    checks()
    results = []
    for task in ('adding', 'copying'):
        for length in LENGTHS:
            for seed in SEEDS:
                for mode in ('tanh', 'irnn', 'orthogonal'):
                    row = run_experiment(task, mode, length, seed)
                    results.append(row)
                    print(task, mode, length, seed, 'validation', row['best_validation_loss'],
                          'test exploratorio', row['test_after_selection'])
    payload = {'short': SHORT, 'device': str(DEVICE), 'torch': torch.__version__,
               'protocol': {'hidden': HIDDEN, 'steps': STEPS, 'batch': BATCH,
                            'train_n': TRAIN_N, 'validation_n': EVAL_N, 'test_n': EVAL_N,
                            'lr': LR, 'clip_global': CLIP, 'seeds': SEEDS,
                            'lengths_or_delays': LENGTHS,
                            'copy_loss': 'solo los 8 símbolos de salida tras el delimitador',
                            'copy_split': 'prefijos sin repetición entre ni dentro de particiones',
                            'adding_split': 'semillas distintas; coincidencias exactas no comprobadas',
                            'adding_constant_1_population_mse': 1 / 6,
                            'copy_uniform_symbol_accuracy': 1 / COPY_SYMBOLS,
                            'selection': 'mínima pérdida de validación por configuración',
                            'test': 'exploratorio: se consulta para varias configuraciones'},
               'results': results}
    OUTPUT.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding='utf-8')
    print('Resultados:', OUTPUT)
    print('Modo corto no demuestra convergencia ni horizonte máximo.')


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.

Exercises

ProofA uniform bound
Prove: Prove the transport bound for a differentiable recurrence with bounded activation derivative.
0
Assume |φ′|≤γ, fixed matrix W and length n=T−t.

Step 1 of 3. What is one step’s Jacobian?

ProofGradient directions
Prove: Show how a terminal gradient contribution evolves in a diagonalizable linear recurrence. Work over complex numbers if necessary and use column gradients.
0
Let W be a real diagonalizable matrix and n=T−t. The terminal contribution is (Wᵀ)ⁿg. Write g as a combination of right eigenvectors of Wᵀ.

Step 1 of 3. If Wᵀuᵢ=λᵢuᵢ, what is (Wᵀ)ⁿuᵢ?

NumericHow many steps?
In a normal linear recurrence with spectral radius 0.9, what is the smallest integer n for which the norm of Wⁿ is strictly less than 10⁻⁶?
QuizClipping does not amplify
A gradient with norm 10⁻¹² is norm-clipped at threshold 1. What happens?
QuizEigenvalues and norm
A linear recurrent matrix has all eigenvalues of modulus 0.9 but is non-normal. Can it amplify a perturbation for some steps?
CodeBuild an adding task and its baseline
Implement adding_problem(T, n, rng). Return X with shape (n,T,2) and y with shape (n,), where X[:,:,0] are independent uniform values in [0,1), X[:,:,1] contains exactly two ones per row at distinct uniformly selected positions, and y is the sum of the two marked values. Require T≥2 and n≥1. Use only the supplied NumPy generator. Also return theoretical population MSE of predicting 1 under this distribution.
import numpy as np

def adding_problem(T, n, rng):
  pass
Shift+Enter to run

Further connections

Temporal products connect with Singular value decomposition and Stability by linearization. Gates introduce trainable mechanisms to modulate retention and forgetting, but still require evaluation with explicit dependencies and splits.