GRU and the family of gated recurrences
Derive GRU variants and gradients, interpret gates as leaky integrators, examine chrono initialization, and compare gated architectures under reproducible protocols.
After this lesson you can
- Write both GRU conventions and implement forward and backward passes in NumPy.
- Interpret a forget or update gate as an exponential average with a characteristic timescale.
- Implement chrono initialization and measure its effects on tasks with known dependency lengths.
- Design a fair comparison of RNN, GRU, and LSTM with comparable parameter budgets and multiple seeds.
- Summarize what large gated-architecture ablations do and do not establish.
Before you start
A gate can control a mixture
The LSTM cell maintains cell and hidden states with write, forget, and read gates. The GRU uses one state and two gates. One interpolates between the past and a candidate; the other regulates how much of the past enters the candidate. It has fewer parameters at the same state size, but that does not prove quality or measured cost are always better.
Two conventions for the same interpolation
With column vectors, a convention used by Cho and colleagues and PyTorch calls the retention weight :
The formulation of Chung and colleagues calls the candidate weight the update gate: . The interpolations agree if , but reusing the same gate values without complementing them changes the result. If the gate comes from a sigmoid, complementing it requires negating the entire preactivation, not merely renaming the variable.
There are also two reset locations. Cho’s equation (8) applies ; the PyTorch variant uses . The recurrent bias is inside the product in the second:
They are not generally equivalent: a nondiagonal matrix and coordinatewise gate do not commute, and bias placement matters too. Chung’s footnote attributes the later placement to Cho, but Cho’s original equation shows the earlier one. Cite specific formulas when porting weights. With in every coordinate, the candidate ignores in both variants, though biases can make their values differ. The interactive’s exact endpoints 0 and 1 are ideal limits, not outputs of a sigmoid with finite preactivation.
Backward pass of a GRU cell
Derive the PyTorch variant with examples in rows. Denote by and . If includes every later path, the first contributions are
For preactivations, ,
Therefore receives, besides the previous local loss,
Matrix and bias gradients accumulate contributions over all steps. The candidate’s recurrent bias receives , whereas its input bias receives : do not sum them as though they passed through the same gate. The laboratory checks both with finite differences and a nonzero initial state.
The gate as a leaky clock
In a scalar fixed-gate leaky integrator,
If input stops acting, a perturbation is multiplied by after steps. The exact scale at which it falls to is ; is useful when is close to one. A state-dependent gate adds other paths to the total Jacobian: this isolated product does not guarantee memory in a trained GRU.
The differential equation discretized by Euler with step gives . In that context fractional step uses . But to reproduce an original discrete transition exactly with substeps and constant , the condition is , that is . The two rules agree approximately for small steps, not generally.
Tallec and Ollivier relate gates and time warping under their model’s assumptions. This motivates adaptive-scale mechanisms; it does not prove that a trained network is invariant to every speed change or that repeating samples preserves every input.
Chrono initialization
Chrono initialization proposes a maximum target timescale for the LSTM and, for each unit,
If input and recurrent contributions to preactivations are zero, and . Thus is distributed between 2 and . This describes the isolated biases, not every gate in a real sequence. With the distribution degenerates at .
On the adding task, Tallec and Ollivier compared 128-unit LSTMs with standard bias 1 versus chrono; for they reported sevenfold faster convergence in their configuration. On text8 they reported 1.37 versus 1.38 bits per character with two independent runs. These are published results under specific protocols, not times measured on this machine or guarantees for other tasks.
The figure records a short run of the laboratory below on the copy task. Both conditions use the same batches per seed and show validation loss and pre-clipping gradient norm. Only two updates are performed: they check the pipeline, not convergence or general advantage.
What ablations compare
An ablation changes components under a defined protocol. Greff and colleagues ran 5400 experiments on LSTM variants and their tasks; they identified the forget gate and output activation among the most critical components in their study. Do not confuse output activation with output gate. Removing peepholes or coupling input and forget gates did not significantly change mean performance across their three datasets.
Chung and colleagues observed comparable GRU and LSTM results on their music and speech modeling tasks. Collins and colleagues reported about 5 bits of task information per parameter on average on their capacity tasks with careful training. These are measures under their definitions, not a universal memory bound for any model.
A comparison of your own must separate training, validation, and test, use multiple seeds, maintain comparable data and search budgets, and publish parameter counts and selected configuration. At equal state sizes, GRU and LSTM have different parameter counts; with nearly equal counts, their state sizes may differ. Intervals from a small seed set describe sampling uncertainty under the protocol, not equivalence.
Jozefowicz, Zaremba and Sutskever explored about 10 000 architectures and reported 230 000 hyperparameter configurations evaluated overall. On their tasks, adding 1 to forget bias improved LSTM where it trailed GRU. Their search and Greff’s are different studies: do not turn their conclusions into a universal ranking or confuse that improvement with a measurement from this lesson’s laboratory.
Laboratory: GRU in NumPy
The cell implements the PyTorch variant with input and recurrent biases, backward, and finite differences. It reuses the current LSTM functions from LSTM cell and compares RNN, GRU, and LSTM on the adding task with the same batches and validation from another seed. Three updates and one seed only verify the pipeline; neither MSE nor such a small sample identifies a winner. Budgets include the output head and are close, not identical.
"""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
# Implementación GRU: orden PyTorch r,z,n, ejemplos por filas, dos sesgos.
# El candidato usa r * (h @ U_n + b_hn). Cho usa (r*h) @ U_n.
def init_gru(d, h, out, rng):
return {'wx': rng.normal(0, .2, (d, 3*h)),
'wh': rng.normal(0, .2, (h, 3*h)),
'bi': np.zeros(3*h), 'bh': np.zeros(3*h),
'wy': rng.normal(0, .2, (h, out)), 'by': np.zeros(out)}
def gru_step(x, h, p):
xi_r, xi_z, xi_n = np.split(x @ p['wx'] + p['bi'], 3, axis=1)
hh_r, hh_z, hh_n = np.split(h @ p['wh'] + p['bh'], 3, axis=1)
r, z = sigmoid(xi_r + hh_r), sigmoid(xi_z + hh_z)
n = np.tanh(xi_n + r * hh_n)
hn = (1 - z) * n + z * h
return hn, (x, h, r, z, n, hh_n, p)
def gru_step_backward(dh, cache):
x, h, r, z, n, hn, p = cache
dn = dh * (1 - z)
dz = dh * (h - n)
dan = dn * (1 - n*n)
dar = (dan * hn) * r * (1 - r)
daz = dz * z * (1 - z)
di = np.concatenate((dar, daz, dan), axis=1)
dhh = np.concatenate((dar, daz, dan * r), axis=1)
grads = {'wx': x.T @ di, 'wh': h.T @ dhh,
'bi': di.sum(axis=0), 'bh': dhh.sum(axis=0)}
dx = di @ p['wx'].T
dh_previous = dh * z + dhh @ p['wh'].T
return dx, dh_previous, grads
def gru_forward(xs, p, h0=None):
h = np.zeros((xs.shape[1], p['wh'].shape[0])) if h0 is None else h0.copy()
states, caches = [], []
for x in xs:
h, cache = gru_step(x, h, p)
states.append(h); caches.append(cache)
hs = np.stack(states)
return hs @ p['wy'] + p['by'], hs, caches
def gru_backward(dy, hs, caches, p):
grads = {k: np.zeros_like(v) for k, v 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])
dx = 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
dx[t], dh, step_grads = gru_step_backward(dh, caches[t])
for key, value in step_grads.items():
grads[key] += value
return grads, dx, dh
def verify_gru():
rng = np.random.default_rng(17130)
xs = rng.normal(size=(3, 2, 2)); h0 = rng.normal(size=(2, 3))
p = init_gru(2, 3, 2, rng)
# Sesgos no nulos distinguen la puerta de reinicio también en su candidato.
p['bi'][:] = rng.normal(0, .2, p['bi'].shape)
p['bh'][:] = rng.normal(0, .2, p['bh'].shape)
dy = rng.normal(size=(3, 2, 2))
_, hs, caches = gru_forward(xs, p, h0)
grads, dx, dh0 = gru_backward(dy, hs, caches, p)
def objective():
return float(np.sum(gru_forward(xs, p, h0)[0] * dy))
errors = {}
for name, arr, grad in ([(k, p[k], grads[k]) for k in p] +
[('xs', xs, dx), ('h0', h0, dh0)]):
error = 0.
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
error = max(error, abs((plus - minus) / (2 * eps) - grad[index]))
errors[name] = error
if not all(np.isfinite(v) and v < 1e-7 for v in errors.values()):
raise AssertionError(('Gradcheck GRU fallido', errors))
# Puerta idéntica escrita con z o 1-z produce la misma mezcla.
old = np.array([[.3, -.2]])
candidate = np.array([[-.1, .6]])
z = np.array([[.2, .8]])
assert np.allclose(z*old + (1-z)*candidate,
(1-(1-z))*old + (1-z)*candidate)
return errors
def init_rnn(d, h, out, rng):
return {'wx': rng.normal(0, .2, (d, h)),
'wh': rng.normal(0, .2, (h, h)), 'b': np.zeros(h),
'wy': rng.normal(0, .2, (h, out)), 'by': np.zeros(out)}
def rnn_forward(xs, p):
h = np.zeros((xs.shape[1], p['wh'].shape[0]))
states, caches = [], []
for x in xs:
prev = h
h = np.tanh(x @ p['wx'] + prev @ p['wh'] + p['b'])
states.append(h); caches.append((x, prev, h))
hs = np.stack(states)
return hs @ p['wy'] + p['by'], hs, caches
def rnn_backward(dy, hs, caches, p):
grads = {k: np.zeros_like(v) for k, v 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])
for t in range(len(caches) - 1, -1, -1):
x, prev, h = caches[t]
dh += dy[t] @ p['wy'].T
dz = dh * (1 - h*h)
grads['wx'] += x.T @ dz
grads['wh'] += prev.T @ dz
grads['b'] += dz.sum(axis=0)
dh = dz @ p['wh'].T
return grads
def verify_rnn():
rng = np.random.default_rng(17134)
p = init_rnn(2, 2, 2, rng)
xs = rng.normal(size=(3, 2, 2))
dy = rng.normal(size=(3, 2, 2))
_, hs, caches = rnn_forward(xs, p)
grads = rnn_backward(dy, hs, caches, p)
def objective():
return float(np.sum(rnn_forward(xs, p)[0] * dy))
errors = {}
for name, arr in p.items():
error = 0.
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
error = max(error, abs((plus - minus) / (2 * eps) - grads[name][index]))
errors[name] = error
if not all(np.isfinite(value) and value < 1e-7 for value in errors.values()):
raise AssertionError(('Gradcheck RNN fallido', errors))
return errors
def get_model(kind, seed):
rng = np.random.default_rng(seed)
if kind == 'RNN':
p = init_rnn(2, 15, 1, rng)
return p, rnn_forward, rnn_backward
if kind == 'GRU':
p = init_gru(2, 8, 1, rng)
return p, gru_forward, gru_backward
if kind == 'LSTM':
p = initialize(2, 7, 1, rng)
return p, forward, backward
raise ValueError('Arquitectura desconocida')
def fit_small(kind, batches, valid):
p, fw, bw = get_model(kind, 17131)
training = []
for xs, target in batches:
result = fw(xs, p)
prediction, hs = result[0], result[1]
caches = result[-1]
error = prediction[-1] - target
loss = float(np.mean(error**2))
dy = np.zeros_like(prediction)
dy[-1] = 2 * error / error.size
derivatives = bw(dy, hs, caches, p)
grads = derivatives if isinstance(derivatives, dict) else derivatives[0]
norm = float(np.sqrt(sum(np.sum(g*g) for g in grads.values())))
if not np.isfinite(loss) or not np.isfinite(norm):
raise ValueError('Pérdida o gradiente no finito')
factor = min(1., 1. / norm) if norm else 1.
for key in p:
p[key] -= .03 * factor * grads[key]
training.append(loss)
vx, vy = valid
predicted = fw(vx, p)[0][-1]
mse = float(np.mean((predicted - vy)**2))
if not np.isfinite(mse):
raise ValueError('Validación no finita')
return {'parametros': sum(value.size for value in p.values()),
'mse_train_online': training, 'mse_validacion': mse}
def main_gru():
print('Gradcheck GRU por diferencias finitas:', verify_gru())
print('Gradcheck RNN por diferencias finitas:', verify_rnn())
check_gradients() # LSTM copiada de la celda vigente de m17-l12.
rng = np.random.default_rng(17132)
batches = [adding_batch(100, 8, rng) for _ in range(3)]
valid = adding_batch(100, 32, np.random.default_rng(17133))
baseline = float(np.mean((1 - valid[1])**2))
print('Suma T=100: mismos lotes, validación generada con otra semilla.')
print('La MSE de la constante 1 en esta validación:', baseline,
'| MSE poblacional teórica:', 1/6)
for kind in ('RNN', 'GRU', 'LSTM'):
print(kind, fit_small(kind, batches, valid))
print('Tres actualizaciones, una semilla: verifica el recorrido, no compara ganadores.')
print('Los presupuestos aproximados incluyen la cabeza; no igualan la búsqueda de hiperparámetros.')
print('Los tiempos dependen del dispositivo y de la carga; esta prueba no establece un ganador.')
if __name__ == '__main__':
main_gru()Laboratory: comparison across seeds
The second exercise compares architectures and initializations with paired seeds, the same learning-rate search, and similar parameter budgets. The copy task separates prefixes across splits. For characters you can supply three UTF-8 files via ORYON_TRAIN_FILE, ORYON_VALID_FILE and ORYON_TEST_FILE; identical texts are rejected, but partial overlap is not detected. State resets in each training window and is retained across blocks when evaluating each text. The task predicts the next character without BOS or EOS: perplexity measures those transitions and excludes document-termination probability. Characters outside the training vocabulary become UNK, which receives no positive training examples.
Learning rate and checkpoint are selected by validation; test is exploratory when comparing multiple conditions. The no-chrono condition zeros input and recurrent cell biases; it is a reference defined here, not the forget-bias-1 reference in the cited experiment. The bootstrap interval over three seeds is very uncertain. ORYON_VERIFY_SHORT=1 checks the path with a much smaller budget; full training is left to the reader. The curves above come from a short-mode run.
"""RNN, GRU y LSTM en caracteres y copia; ejecución local.
Sin datos externos usa dos fragmentos breves del Quijote de Project Gutenberg
2000, https://www.gutenberg.org/files/2000/2000-0.txt . Entrena y valida en
segmentos no solapados del primer fragmento y evalúa en el segundo.
Consulta https://www.gutenberg.org/policy/license.html y la legislación local.
Tres archivos UTF-8 opcionales permiten aportar particiones más amplias.
ORYON_VERIFY_SHORT=1 comprueba el flujo; no demuestra convergencia.
"""
import hashlib
import json
import math
import os
import time
import unicodedata
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
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 = [17130] if SHORT else [17130, 17131, 17132]
RATES = [.002] if SHORT else [.001, .003]
STEPS = 2 if SHORT else int(os.environ.get('ORYON_STEPS', '300'))
BATCH = 4 if SHORT else 32
WINDOW = 8 if SHORT else 16
REFERENCE_H = 8 if SHORT else 64
COPY_PREFIX = 8
COPY_SYMBOLS = 8
COPY_DELAY = 8 if SHORT else 80
COPY_TRAIN = 32 if SHORT else 1024
COPY_EVAL = 16 if SHORT else 256
T_MAX = 100
OUTPUT = Path(os.environ.get('ORYON_OUTPUT', 'gru_comparacion.json'))
TRAIN_FRAGMENT = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
TEST_FRAGMENT = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
def texts():
paths = [os.environ.get('ORYON_TRAIN_FILE'), os.environ.get('ORYON_VALID_FILE'),
os.environ.get('ORYON_TEST_FILE')]
if any(paths) and not all(paths):
raise ValueError('Indica los tres archivos UTF-8 o ninguno')
if all(paths):
values = [Path(path).read_text(encoding='utf-8') for path in paths]
source = 'tres archivos aportados por el lector'
else:
cut = int(.75 * len(TRAIN_FRAGMENT))
values = [TRAIN_FRAGMENT[:cut], TRAIN_FRAGMENT[cut:], TEST_FRAGMENT]
source = 'fragmentos Gutenberg 2000: primer fragmento dividido, segundo para test'
values = [unicodedata.normalize('NFC', s).lower() for s in values]
if any(len(s) < 2 for s in values) or len(set(values)) != 3:
raise ValueError('Se requieren tres textos no vacíos y no idénticos')
if len(values[0]) <= WINDOW:
raise ValueError('El texto de entrenamiento debe superar la ventana')
return values, source
def encode_texts(parts):
# UNK solo se crea a partir de train; sin ejemplos positivos de UNK.
vocab = ['<unk>', *sorted(set(parts[0]))]
index = {ch: i for i, ch in enumerate(vocab)}
encoded = [torch.tensor([index.get(ch, 0) for ch in part], dtype=torch.long)
for part in parts]
return vocab, encoded
def make_copy(count, seed, excluded=()):
rng = np.random.default_rng(seed)
seen = set(excluded)
if count < 1 or count > COPY_SYMBOLS ** COPY_PREFIX - len(seen):
raise ValueError('Número de prefijos inválido')
rows = []
for _ in range(max(1000, 20 * count)):
row = tuple(int(x) for x in rng.integers(0, COPY_SYMBOLS, COPY_PREFIX))
if row not in seen:
seen.add(row)
rows.append(row)
if len(rows) == count:
break
if len(rows) != count:
raise ValueError('No se encontraron suficientes prefijos únicos')
target = np.asarray(rows, dtype=np.int64)
inputs = np.full((count, 2 * COPY_PREFIX + COPY_DELAY + 1),
COPY_SYMBOLS, dtype=np.int64)
inputs[:, :COPY_PREFIX] = target
inputs[:, COPY_PREFIX + COPY_DELAY] = COPY_SYMBOLS + 1
return (torch.from_numpy(inputs), torch.from_numpy(target)), set(rows)
def copying_splits(seed):
train, a = make_copy(COPY_TRAIN, seed + 100)
val, b = make_copy(COPY_EVAL, seed + 200, a)
test, c = make_copy(COPY_EVAL, seed + 300, a | b)
assert not (a & b or a & c or b & c)
return train, val, test
def parameter_count(architecture, d, hidden, out):
gates = {'RNN': 1, 'GRU': 3, 'LSTM': 4}[architecture]
return gates * hidden * (d + hidden + 2) + hidden * out + out
def sizes(d, out):
target = parameter_count('GRU', d, REFERENCE_H, out)
result = {}
for arch in ('RNN', 'GRU', 'LSTM'):
h = min(range(1, 513), key=lambda n: abs(parameter_count(arch, d, n, out) - target))
result[arch] = {'hidden': h, 'params': parameter_count(arch, d, h, out)}
return target, result
class LanguageModel(nn.Module):
def __init__(self, architecture, d, out, hidden, chrono, seed):
super().__init__()
recurrent = {'RNN': nn.RNN, 'GRU': nn.GRU, 'LSTM': nn.LSTM}[architecture]
self.rnn = recurrent(d, hidden, batch_first=True)
self.head = nn.Linear(hidden, out)
self.d = d
self.hidden = hidden
self.architecture = architecture
self.chrono_scales = None
with torch.no_grad():
self.rnn.bias_ih_l0.zero_()
self.rnn.bias_hh_l0.zero_()
if chrono:
if architecture == 'RNN':
raise ValueError('Esta variante chrono solo se aplica a puertas')
u = np.random.default_rng(seed + 500).uniform(1., T_MAX - 1., hidden)
b = torch.tensor(np.log(u), dtype=self.rnn.bias_ih_l0.dtype)
# GRU: orden r,z,n, y z conserva el estado previo.
# LSTM: orden i,f,g,o. El sesgo recurrente se mantiene en cero.
self.rnn.bias_ih_l0[hidden:2*hidden].copy_(b)
if architecture == 'LSTM':
self.rnn.bias_ih_l0[:hidden].copy_(-b)
self.chrono_scales = (1. + u).tolist()
def forward(self, ids):
x = F.one_hot(ids, num_classes=self.d).float()
states, _ = self.rnn(x)
return self.head(states)
def make_model(arch, task, d, out, hidden, chrono, seed):
torch.manual_seed(seed)
model = LanguageModel(arch, d, out, hidden, chrono, seed).to(DEVICE)
assert sum(q.numel() for q in model.parameters()) == parameter_count(arch, d, hidden, out)
return model
def sync():
if DEVICE.type == 'cuda':
torch.cuda.synchronize(DEVICE)
def train_batch(task, train, rng):
if task == 'copy':
indices = torch.from_numpy(rng.integers(0, len(train[0]), BATCH))
return train[0][indices].to(DEVICE), train[1][indices].to(DEVICE)
starts = rng.integers(0, len(train) - WINDOW, size=BATCH)
offsets = np.arange(WINDOW)
indexes = torch.from_numpy(starts[:, None] + offsets[None, :])
return train[indexes].to(DEVICE), train[indexes + 1].to(DEVICE)
def loss_for(model, task, x, y):
scores = model(x)
if task == 'copy':
scores = scores[:, -COPY_PREFIX:, :]
return F.cross_entropy(scores.reshape(-1, scores.shape[-1]), y.reshape(-1))
@torch.inference_mode()
def evaluate(model, task, data):
model.eval()
if task == 'copy':
x, y = (v.to(DEVICE) for v in data)
scores = model(x)[:, -COPY_PREFIX:, :]
loss = float(F.cross_entropy(scores.reshape(-1, COPY_SYMBOLS), y.reshape(-1)))
pred = scores.argmax(-1)
result = {'loss': loss, 'symbol_accuracy': float((pred == y).float().mean()),
'sequence_accuracy': float((pred == y).all(dim=1).float().mean())}
else:
# Estado reiniciado al comenzar el documento, preservado entre bloques.
# No se construye una matriz one-hot para todo un corpus largo.
state, total, events = None, 0., 0
for start in range(0, len(data) - 1, 256):
end = min(start + 256, len(data) - 1)
x = data[start:end][None, :].to(DEVICE)
y = data[start + 1:end + 1][None, :].to(DEVICE)
sequence = F.one_hot(x, num_classes=model.d).float()
hidden, state = model.rnn(sequence, state)
scores = model.head(hidden)
total += float(F.cross_entropy(scores.reshape(-1, scores.shape[-1]),
y.reshape(-1), reduction='sum'))
events += y.numel()
loss = total / events
result = {'loss': loss, 'perplexity': math.exp(loss)}
if not all(math.isfinite(v) for v in result.values()):
raise ValueError(f'Métrica no finita para {task}: {result}')
return result
def train_candidate(arch, task, d, out, hidden, chrono, seed, rate, train, val):
model = make_model(arch, task, d, out, hidden, chrono, seed)
opt = torch.optim.Adam(model.parameters(), lr=rate)
rng = np.random.default_rng(seed + 1000)
best, state, best_step, history = math.inf, None, None, []
interval = max(1, STEPS // 5)
sync()
start_time = time.perf_counter()
for step in range(1, STEPS + 1):
model.train()
x, y = train_batch(task, train, rng)
opt.zero_grad(set_to_none=True)
loss = loss_for(model, task, x, y)
if not torch.isfinite(loss):
raise ValueError(f'Pérdida no finita en {arch}, {task}, paso {step}')
loss.backward()
norm = nn.utils.clip_grad_norm_(model.parameters(), 1., error_if_nonfinite=True)
opt.step()
if step == 1 or step % interval == 0 or step == STEPS:
measured = evaluate(model, task, val)
history.append({'step': step, 'validation_loss': measured['loss'],
'gradient_norm_before_clip': float(norm)})
if measured['loss'] < best:
best, best_step = measured['loss'], step
state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
sync()
elapsed = time.perf_counter() - start_time
if state is None:
raise ValueError('No existe checkpoint válido')
scales = model.chrono_scales
del model, opt
return {'rate': rate, 'best_validation_loss': best, 'best_step': best_step,
'history': history, 'seconds_with_validation': elapsed,
'chrono_scales': scales}, state
def run_condition(task, arch, chrono, seed, d, out, size, datasets):
train, val, test = datasets
choices = [train_candidate(arch, task, d, out, size['hidden'], chrono,
seed, rate, train, val) for rate in RATES]
winner = min(choices, key=lambda item: item[0]['best_validation_loss'])
model = make_model(arch, task, d, out, size['hidden'], chrono, seed)
model.load_state_dict(winner[1])
test_metrics = evaluate(model, task, test)
output = {'task': task, 'architecture': arch, 'chrono': chrono, 'seed': seed,
'hidden': size['hidden'], 'parameters': size['params'],
'selected_rate': winner[0]['rate'], 'selected_step': winner[0]['best_step'],
'validation_loss': winner[0]['best_validation_loss'],
'test_exploratory': test_metrics,
'search': [item[0] for item in choices]}
del model, choices
if DEVICE.type == 'cuda':
torch.cuda.empty_cache()
return output
def summarize(rows):
summary = []
for task in ('characters', 'copy'):
for arch, chrono in [('RNN', False), ('GRU', False), ('GRU', True),
('LSTM', False), ('LSTM', True)]:
group = [r for r in rows if r['task'] == task and
r['architecture'] == arch and r['chrono'] == chrono]
vals = np.asarray([r['test_exploratory']['loss'] for r in group])
interval = None
if len(vals) > 1:
rng = np.random.default_rng(17139)
sample = vals[rng.integers(0, len(vals), size=(2000, len(vals)))]
interval = np.quantile(sample.mean(axis=1), [.025, .975]).tolist()
summary.append({'task': task, 'architecture': arch, 'chrono': chrono,
'test_loss_by_seed': vals.tolist(), 'mean': float(vals.mean()),
'bootstrap_95_over_seeds': interval})
return summary
def main():
if STEPS < 1:
raise ValueError('ORYON_STEPS debe ser positivo')
parts, source = texts()
vocab, encoded = encode_texts(parts)
conditions = [('RNN', False), ('GRU', False), ('GRU', True),
('LSTM', False), ('LSTM', True)]
rows, budgets = [], {}
for task in ('characters', 'copy'):
d = len(vocab) if task == 'characters' else COPY_SYMBOLS + 2
out = len(vocab) if task == 'characters' else COPY_SYMBOLS
target, options = sizes(d, out)
budgets[task] = {'target_gru': target, 'models': options}
for seed in SEEDS:
datasets = encoded if task == 'characters' else copying_splits(seed)
for arch, chrono in conditions:
row = run_condition(task, arch, chrono, seed, d, out, options[arch], datasets)
rows.append(row)
print(task, arch, 'chrono', chrono, 'semilla', seed,
'test exploratorio', row['test_exploratory'])
payload = {
'short': SHORT, 'device': str(DEVICE), 'torch': torch.__version__,
'gpu': torch.cuda.get_device_name(DEVICE) if DEVICE.type == 'cuda' else None,
'cuda': torch.version.cuda, 'cudnn': torch.backends.cudnn.version(),
'source': source, 'text_sha256_nfc_lower': [
hashlib.sha256(part.encode('utf-8')).hexdigest() for part in parts],
'text_chars': [len(part) for part in parts],
'text_oov': [int((v == 0).sum()) for v in encoded],
'protocol': {'seeds': SEEDS, 'rates': RATES, 'steps_per_rate': STEPS,
'batch': BATCH, 'window': WINDOW, 'copy_delay': COPY_DELAY,
'copy_prefix': COPY_PREFIX, 'copy_split': 'prefijos sin duplicados',
'text_split': 'no idénticos; no se detectan solapamientos parciales',
'text_unknown': 'UNK sin ejemplos positivos de entrenamiento',
'character_state': 'cero por ventana de entrenamiento y documento de evaluación',
'selection': 'menor pérdida de validación entre checkpoints y tasas',
'test': 'exploratorio: comparación de varias condiciones',
'chrono': ('U uniforme [1,Tmax-1), bf=log(U); en GRU z retiene. '
'Las escalas guardadas suponen preactivación igual al sesgo '
'y no describen por sí solas la dinámica entrenada.'),
'timing': 'por candidato, sincronizado; incluye validación y generación de lotes',
'bootstrap': 'percentiles sobre semillas; muy incierto con tres'},
'parameter_budgets': budgets, 'rows': rows, 'summary': summarize(rows)}
OUTPUT.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding='utf-8')
print('Presupuestos:', budgets)
print('Resumen exploratorio:', payload['summary'])
print('Salida:', OUTPUT)
print('El modo corto solo comprueba el recorrido; no demuestra convergencia.')
print('La comparación usa los mismos lotes por semilla y la misma búsqueda por condición.')
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
Step 1 of 3. What recurrence does Euler with step 1 give for dh/dt=(u−h)/τ?
import numpy as np
def chrono_init(T_max, n, rng):
passFurther reading
Gated information flow connects with LSTM backward pass and later sequence models. For a reproducible comparison, record code, data, budgets, coverage, selection, and seeds before interpreting small differences.