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
- 17Backpropagation through timeTruncated backpropagation through timeRecurrent neural network (Elman network)Hidden state as a summary of the prefix
- 15Vanishing gradientsExploding gradientsGradient clippingOrthogonal initialization
- 02Singular value decompositionSpectral radiusOrthogonal matrix
- 03Stability by linearizationBifurcations and limit cycles
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 , and . With fixed parameters and inputs, one transition’s Jacobian is
Order matters. Although is shared, depends on each step’s state and input. For terminal loss , the column gradient toward is . 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 at all visited points. Spectral-norm submultiplicativity gives
The sufficient spectral contraction condition is : the bound then tends exponentially to zero. A gradient contribution also vanishes if its loss and immediate-derivative factors remain bounded. If , state transport cannot grow exponentially under this bound; thus is necessary for exponential explosion under these assumptions, but not sufficient. The total gradient is a sum and needs separate analysis. For tanh take ; 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 , but saturated tanh can make some entries of near zero. Conversely, spectral radius below one does not prevent transient amplification if the matrix is non-normal. For example, with , both eigenvalues are 0.9 and contains term . It grows temporarily before tending to zero. The figure calculates product norm for an explicit trajectory.
In the diagonalizable linear case , an initial perturbation along a right eigenvector is multiplied by . Column gradients use and eigenvectors of , not necessarily the same ones. If 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 . A fixed point satisfies . If 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 , 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.
In the interactive, plots branches without numerically solving an equation. For a finite trajectory, and exactly calculate . That finite sensitivity is not automatically the equilibrium derivative. Figure branches are not training results.
Clip and preserve
With global gradient and threshold , norm clipping uses , with if . 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 . 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 and use ReLU. While all relevant units are active, and the initial product preserves that part of the signal. An inactive ReLU introduces zero; updates modify unless constrained. A scaled identity changes propagation to 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 to 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 , then . 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: for , or Cayley transform 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 ; 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 and a marker; two distinct positions are selected and the target is their values’ sum. Constant prediction 1 has population MSE 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 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.
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.
"""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.
"""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()npm run lab and open the connection link.Exercises
Step 1 of 3. What is one step’s Jacobian?
Step 1 of 3. If Wᵀuᵢ=λᵢuᵢ, what is (Wᵀ)ⁿuᵢ?
import numpy as np
def adding_problem(T, n, rng):
passFurther 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.