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 from hidden output . 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.
From carousel to gates
The constant error carousel of Hochreiter and Schmidhuber starts from a linear self-connection of weight one: if along that path , 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 and states , each gate has its matrices and bias:
Matrices have shape , shape and biases length . Sigmoid allows weights between zero and one; tanh allows a positive or negative candidate and bounds readout. State is not replaced by : 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 . 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 . Across steps, that path contributes
The product is coordinatewise. In an actual LSTM gates also depend on , 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.
The forget gate can be initialized with positive bias to favor initial retention. In the simplified model where preactivation equals bias, gives (0.5) and gives (0.7311). Even with , the product over one hundred steps is approximately (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 (0.95) is constant, the factor falls to in steps (about 19.50); is an approximation, not the exact scale.
Backpropagate through both states
In LSTM backward, derivatives arrive from the rest of the graph at both and . Let be the total derivative with respect to and the derivative arriving directly at from the next step (“fut” means future). Then
The second summand follows cell readout. Before differentiating preactivations, gate and candidate contributions are
Multiply by , and respectively, and by . The direct contribution to previous state is . In this peephole-free cell, all four preactivations also contribute to 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 the derivative with respect to gate ‘s preactivation. For row examples, one-step contributions are
Also and . 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 and and two length- biases that are summed. To transfer a row-based implementation, transpose its matrices. If effective bias is , copy to input bias and zero to recurrent bias; copying to both applies .
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.
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.
"""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()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.
"""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 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()npm run lab and open the connection link.Exercises
Step 1 of 3. What is the direct derivative of Cₜ with respect to Cₜ₋₁?
import numpy as np
def lstm_step_backward(dh_next, dc_next, cache):
passFurther 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.