Training RNNs for real: batching, regularization and GPU speed
Train recurrent language models using variable-length batching, recurrent regularization, adaptive softmax, and careful diagnostics and benchmarking.
After this lesson you can
- Implement padding, loss and state masks, length sorting, and packing without contaminating final states.
- Explain recurrent dropout and apply shared-mask dropout and zoneout.
- Reproduce a reduced AWD-LSTM with recurrent DropConnect and activation regularization.
- Use adaptive softmax and measure speed and perplexity under comparable protocols.
- Diagnose RNN training with gradient norms, gate saturation, validation perplexity, and GPU memory.
Before you start
- 17LSTM cellTruncated backpropagation through timeContiguous stream batchingLarge-vocabulary softmax costHierarchical softmaxZipf's and Heaps' lawsStacked (deep) RNNs
- 15Inverted dropoutLayer normalization
- 14Scalable Bayesian neural network approximations
- 00Canonical training and evaluation loopFull training checkpointTraining memory budget
- 06Iterate averaging
Length is not a formatting detail
A batch can mix a five-token sentence with a one-token sentence. If both are padded to length five and every step goes through an LSTM, the second changes during four padding steps too: zero input does not freeze state. Taking the batch’s last state without checking length summarizes a different sequence.
The example shows that sorting within a batch changes neither its maximum nor the number of padded positions. Grouping by length can reduce padding by changing which examples share a batch; it also changes minibatch composition. Packing avoids invalid-step computation in a supporting implementation but can incur sorting and irregular scheduling costs. Fewer operations do not guarantee less time on a particular GPU.
For lengths and maximum , define . The length mask protects both state and denominator:
The loss here is scalar per token and requires at least one valid token. If also averaging over output components, include that dimension in the denominator. Masking only loss still lets padding modify state. In an LSTM both and must be frozen; for length zero the final state is the initial one. For invalid nonfinite values, selecting valid examples before the cell avoids undefined backward operations: multiplying NaN by zero does not eliminate it.
PyTorch offers a packed representation from positive lengths. If empty examples are allowed, separate them or assign a convention before packing. Restore original order after sorting and exclude padding from loss, pooling, and metrics.
One fixed mask is not a fresh mask
The figure uses a deliberately simple scalar model without rescaling: it is not LSTM training. With fresh masks, a coordinate falling to zero stops carrying that identity signal. With a fixed mask, the same selection persists at every step. A real LSTM has other paths, inputs, and gates: this example does not prove per-step dropout always destroys all memory.
In this toy model with independent draws and retention probability , an unrenewed signal survives fresh masks with probability ; with one fixed mask it survives with probability . These describe this particular unscaled path, not total memory of an arbitrary network.
Shared-mask recurrent dropout reuses the mask across a sequence, with a declared policy for example, sequence, and layer. With inverted dropout and discard probability , each retained component is multiplied by in training and dropout is removed at evaluation. This preserves expectation for one application, but does not imply repeated recurrent multiplication has the same dynamics as the unscaled figure. Gal and Ghahramani relate a family of shared masks to approximate variational inference under specific assumptions; sharing a mask alone does not guarantee calibrated uncertainty.
Zoneout chooses between retaining and updating rather than replacing with zero. For candidate and mask :
An LSTM may use different masks and probabilities for and . Conditioned on the mask, the derivative has direct path in addition to the path through ; this does not guarantee nonzero or stable gradients throughout the network. At evaluation one may use deterministic mixture or sample, stating which. The mixture is the conditional one-step expectation for given states, not necessarily the exact expectation of an entire nonlinear trajectory. See Krueger and colleagues.
Regularizing recurrent weights
A weight-dropped LSTM applies DropConnect to the recurrent matrix, not the same as dropping activations. For mask shared over a sequence, the effective training matrix is . Gradients accumulate on the original parameter; it must not be replaced with a disconnected tensor. Evaluation uses the unmasked matrix. Specify whether the mask is shared across batch examples and when it is resampled.
Merity, Keskar and Socher combine this idea with embedding and activation regularization, variable BPTT length, and NT-ASGD. Activation regularization may use and temporal regularization ; specify the output, mask, and normalization used by each implementation. NT-ASGD begins averaging when a nonmonotonic validation criterion triggers: it is not synonymous with Adam and does not necessarily average from the first step.
The paper reports word-level perplexity 65.8 on WikiText-2, or 52.0 with a neural cache, under its own protocol. These are not results of this cell. Perplexities are directly comparable only when split, tokenization, vocabulary, unknown treatment, and context are compatible.
A library’s fused path may change when parameterizing weights, packing, or modifying the cell. Measure cuDNN compatibility and speed for the actual version, device, and shape; neither follows from operation count or the class name LSTM.
Normalization in recurrence
Layer normalization computes statistics across features of one example and step, so it does not need other batch examples’ statistics. Specify which gate preactivations or state are normalized: placements define different models. Batch normalization uses batch statistics; with varying lengths the number of active examples changes over time and padding positions must not be included as data. Per-step and evaluation statistics need special care. This does not make the technique impossible: Cooijmans and colleagues propose a recurrent batch-normalization variant.
Adaptive output for large vocabularies
A full softmax computes scores. Adaptive softmax assigns frequent words to a head and groups the rest into tails. The head also normalizes a selector per tail. For a word in tail :
Each conditional distribution is normalized. If head classes and tails partition the vocabulary exhaustively and disjointly, probabilities sum to one. Target loss needs the head and, for an infrequent target, its tail. Computing all probabilities or finding the global maximum may need more tails. Tails can use lower-dimensional projections. Grave and colleagues design partitions considering frequencies and hardware costs, not just a power law.
The figure counts matrix–vector multiply-accumulates per target: head plus probability of visiting each tail times its projection and scores. It excludes biases, normalization, and latencies. Batch training can group targets in one tail and use matrix multiplications, so this count does not directly predict wall time.
A health dashboard needs measurements
Record loss, perplexity, global gradient norm before and after clipping, forget-gate saturation with a declared threshold, padded-position fraction, BPTT length, memory, and synchronized times. Distinguish token-level loss from batch averages; record seeds and training/evaluation modes. A small clipped norm can conceal a huge pre-clipping value. Falling training loss does not guarantee generalization. Melis and colleagues show the importance of controlled hyperparameter tuning and code in architecture comparisons. The dashboard collects a short laboratory run; it supports inspecting measurements without turning that test into a conclusion about the best variant.
Laboratory: lengths and masks
The example reuses the current LSTM cell from LSTM cell. It compares individually run and batched sequences, applies inverted dropout fixed per sequence and independent zoneout to and , and checks padding does not enter loss. Synthetic data do not show learning.
"""Lotes con relleno, dropout fijo y zoneout sobre la LSTM de m17-l12.
Ejemplos sintéticos explícitos; no representan entrenamiento ni una métrica real.
Cada fila de la máscara de dropout corresponde a una secuencia del lote y se
comparte en el tiempo. Las máscaras de zoneout se fijan antes de comparar.
"""
import numpy as np
# Estas tres funciones corresponden a la celda NumPy vigente de m17-l12.
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 sequence_mask(lengths, max_time):
lengths = np.asarray(lengths)
if (lengths.ndim != 1 or not np.issubdtype(lengths.dtype, np.integer) or
max_time < 1 or np.any(lengths < 0) or np.any(lengths > max_time)):
raise ValueError('Longitudes enteras en el intervalo [0, T]')
return np.arange(max_time)[:, None] < lengths[None, :]
def locked_dropout(x, p, training, rng):
"""Dropout invertido sobre entradas (T,B,D), misma máscara para cada t."""
if x.ndim != 3 or not np.isfinite(p) or not 0 <= p < 1:
raise ValueError('Se exige x de forma (T,B,D) y 0 <= p < 1')
if not training or p == 0:
return x.copy(), np.ones((x.shape[1], x.shape[2]))
scale = (rng.random((x.shape[1], x.shape[2])) >= p).astype(float) / (1 - p)
return x * scale[None, :, :], scale
def make_zoneout_masks(T, batch, hidden, probability, rng):
"""True conserva la componente anterior; h y c reciben muestras separadas."""
if min(T, batch, hidden) < 1 or not np.isfinite(probability) or not 0 <= probability <= 1:
raise ValueError('Dimensiones o probabilidad inválidas')
shape = (T, batch, hidden)
return rng.random(shape) < probability, rng.random(shape) < probability
def masked_lstm_forward(xs, mask, params, h0=None, c0=None, keep_h=None, keep_c=None):
"""En posiciones inválidas conserva h y c; opcionalmente aplica zoneout."""
xs, mask = np.asarray(xs), np.asarray(mask)
if xs.ndim != 3 or mask.shape != xs.shape[:2] or mask.dtype != np.bool_:
raise ValueError('Se esperan xs (T,B,D) y máscara booleana (T,B)')
T, batch, _ = xs.shape
hidden = params['wh'].shape[0]
h = np.zeros((batch, hidden)) if h0 is None else np.asarray(h0).copy()
c = np.zeros((batch, hidden)) if c0 is None else np.asarray(c0).copy()
if h.shape != (batch, hidden) or c.shape != h.shape or T < 1:
raise ValueError('Estado inicial inválido')
shape = (T, batch, hidden)
if (keep_h is None) != (keep_c is None):
raise ValueError('Indica ambas máscaras de zoneout o ninguna')
if keep_h is not None:
keep_h, keep_c = np.asarray(keep_h), np.asarray(keep_c)
if (keep_h.shape != shape or keep_c.shape != shape or
keep_h.dtype != np.bool_ or keep_c.dtype != np.bool_):
raise ValueError('Máscaras de zoneout booleanas de forma (T,B,H)')
states, cells = [], []
for t in range(T):
candidate_h, candidate_c, _ = lstm_step_forward(xs[t], h, c, params)
if keep_h is not None:
candidate_h = np.where(keep_h[t], h, candidate_h)
candidate_c = np.where(keep_c[t], c, candidate_c)
h = np.where(mask[t, :, None], candidate_h, h)
c = np.where(mask[t, :, None], candidate_c, c)
states.append(h.copy()); cells.append(c.copy())
return np.stack(states), np.stack(cells), h, c
def masked_mse(predictions, targets, mask):
"""Media sobre todos los escalares de salida válidos; padding se ignora."""
if predictions.shape != targets.shape or mask.shape != predictions.shape[:2]:
raise ValueError('Formas incompatibles')
valid = predictions[mask] - targets[mask]
if valid.size == 0:
raise ValueError('No hay objetivos válidos')
return float(np.mean(valid ** 2))
def main():
rng = np.random.default_rng(17150)
T, batch, d, hidden, out = 6, 4, 3, 4, 2
lengths = np.array([6, 4, 1, 0])
mask = sequence_mask(lengths, T)
xs = rng.normal(size=(T, batch, d))
xs[~mask] = 123. # Relleno deliberadamente distinto de cero.
params = initialize(d, hidden, out, np.random.default_rng(17151))
h0 = rng.normal(size=(batch, hidden))
c0 = rng.normal(size=(batch, hidden))
dropped, dropout_scale = locked_dropout(xs, .25, True, np.random.default_rng(17152))
keep_h, keep_c = make_zoneout_masks(T, batch, hidden, .2, np.random.default_rng(17153))
hs, cs, last_h, last_c = masked_lstm_forward(dropped, mask, params, h0, c0, keep_h, keep_c)
maximum = 0.
for b, length in enumerate(lengths):
if length:
alone_h, alone_c, end_h, end_c = masked_lstm_forward(
dropped[:length, b:b+1], np.ones((length, 1), dtype=bool), params,
h0[b:b+1], c0[b:b+1], keep_h[:length, b:b+1], keep_c[:length, b:b+1])
maximum = max(maximum, float(np.max(np.abs(alone_h[:, 0] - hs[:length, b]))),
float(np.max(np.abs(alone_c[:, 0] - cs[:length, b]))),
float(np.max(np.abs(end_h[0] - last_h[b]))),
float(np.max(np.abs(end_c[0] - last_c[b]))))
else:
assert np.array_equal(last_h[b], h0[b]) and np.array_equal(last_c[b], c0[b])
if length < T:
np.testing.assert_allclose(hs[length:, b], np.broadcast_to(last_h[b], (T-length, hidden)))
np.testing.assert_allclose(cs[length:, b], np.broadcast_to(last_c[b], (T-length, hidden)))
assert maximum < 1e-12
# Mismas entradas válidas, distinto padding: estados finales idénticos.
altered = dropped.copy(); altered[~mask] = -99.
altered_result = masked_lstm_forward(altered, mask, params, h0, c0, keep_h, keep_c)
np.testing.assert_allclose(altered_result[2], last_h, rtol=0, atol=1e-12)
np.testing.assert_allclose(altered_result[3], last_c, rtol=0, atol=1e-12)
for t in range(T):
np.testing.assert_allclose(dropped[t], xs[t] * dropout_scale)
inference, inference_scale = locked_dropout(xs, .25, False, np.random.default_rng(1))
np.testing.assert_array_equal(inference, xs)
np.testing.assert_array_equal(inference_scale, np.ones_like(inference_scale))
# Zoneout 100 % mantiene ambos estados; 0 % equivale a la LSTM enmascarada.
none = np.zeros((T, batch, hidden), dtype=bool)
all_keep = np.ones_like(none)
plain = masked_lstm_forward(xs, mask, params, h0, c0)
zero = masked_lstm_forward(xs, mask, params, h0, c0, none, none)
frozen = masked_lstm_forward(xs, mask, params, h0, c0, all_keep, all_keep)
np.testing.assert_allclose(plain[2], zero[2]); np.testing.assert_allclose(plain[3], zero[3])
np.testing.assert_array_equal(frozen[2], h0); np.testing.assert_array_equal(frozen[3], c0)
predictions = hs @ params['wy'] + params['by']
targets = rng.normal(size=predictions.shape)
mse = masked_mse(predictions, targets, mask)
altered_targets = targets.copy(); altered_targets[~mask] = 1e6
assert masked_mse(predictions, altered_targets, mask) == mse
print('Longitudes y máscara válida:', lengths.tolist(), '| pasos válidos:', int(mask.sum()))
print('Escalas de dropout fijo por secuencia y componente:', dropout_scale.tolist())
print('Zoneout aplicado a h y c con máscaras independientes y semillas declaradas.')
print('Máxima diferencia lote frente a secuencias individuales:', maximum)
print('MSE sobre escalares válidos:', mse, '| invariancia del padding: comprobada')
print('Los casos extremos de zoneout y la inferencia sin dropout coinciden con su definición.')
print('Son datos sintéticos de verificación, no mediciones de aprendizaje ni rendimiento.')
if __name__ == '__main__':
main()Local laboratory: recurrent language model
The local exercise separates training, validation, and test before building the vocabulary and fixes seeds. It compares strategies under a declared budget and saves curves and diagnostics. A short verification checks the pipeline, not convergence or reproduction of the paper’s full result.
The saturation diagnostic samples the first block and first layer each epoch. Synchronized times include this diagnostic. Each configuration’s test is exploratory and computed after validation selection; it must not select the winning ablation.
"""AWD-LSTM reducido en WikiText-2: variantes y diagnósticos reales.
Fuente: Salesforce/wikitext, wikitext-2-raw-v1, revisión y hashes declarados.
La ficha enumera CC BY-SA 3.0 y GFDL, y su descripción menciona CC BY-SA 4.0;
consulta las condiciones antes de redistribuir. Requiere PyTorch, NumPy,
PyArrow y huggingface_hub. ORYON_VERIFY_SHORT=1 solo verifica el recorrido.
No reproduce las dimensiones, búsqueda, atado de pesos ni puntuación del paper.
"""
import hashlib
import json
import math
import os
import re
import time
import unicodedata
from collections import Counter
from contextlib import contextmanager
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
import torch
from torch import nn
import torch.nn.functional as F
from torch.func import functional_call
from huggingface_hub import hf_hub_download
torch.set_num_threads(1)
# La comprobación manual de puertas compara operaciones float32 con cuDNN.
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
OUT = Path(os.environ.get('ORYON_OUTPUT', 'awd_lstm_output'))
REV = 'b08601e04326c79dfdd32d625aee71d232d685c3'
FILES = {
'train': ('wikitext-2-raw-v1/train-00000-of-00001.parquet',
'e83889baabc497075506f91975be5fac0d45c5290b6b20582c8cd1e853d0c9f7'),
'validation': ('wikitext-2-raw-v1/validation-00000-of-00001.parquet',
'204929b7ff9d6184953f867dedb860e40aa69c078fc1e54b3baaa8fb28511c4c'),
'test': ('wikitext-2-raw-v1/test-00000-of-00001.parquet',
'5f1bea067869d04849c0f975a2b29c4ff47d867f484f5010ea5e861eab246d91'),
}
PATTERN = re.compile(r"\w+(?:['’]\w+)*|[^\w\s]", re.UNICODE)
UNK, EOS = '<unk>', '</s>'
SEEDS = [17150] if SHORT else [17150, 17151, 17152]
DIM = 16 if SHORT else 256
BATCH = 4 if SHORT else 20
BPTT = 8 if SHORT else 35
EPOCHS = 2 if SHORT else int(os.environ.get('ORYON_EPOCHS', '10'))
MAX_STEPS = 2 if SHORT else None
VOCAB_CAP = 500 if SHORT else 20000
LR = .1
CLIP = .25
NONMONO = 2
BASE = {'weight_drop': .3, 'embedding_drop': .1, 'locked_drop': .2,
'ar': .1, 'tar': .1, 'variable_bptt': True,
'nt_asgd': True, 'adaptive': True}
ABLATIONS = [
('referencia', {}),
('sin_dropconnect', {'weight_drop': 0.}),
('sin_dropout_embedding', {'embedding_drop': 0.}),
('sin_dropout_bloqueado', {'locked_drop': 0.}),
('sin_ar', {'ar': 0.}),
('sin_tar', {'tar': 0.}),
('bptt_fijo', {'variable_bptt': False}),
('sin_asgd', {'nt_asgd': False}),
('softmax_completo', {'adaptive': False}),
]
def tokenize(text):
return PATTERN.findall(unicodedata.normalize('NFC', text).lower())
def checked_file(split):
name, expected = FILES[split]
path = hf_hub_download(repo_id='Salesforce/wikitext', repo_type='dataset',
revision=REV, filename=name)
digest = hashlib.sha256()
with open(path, 'rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(block)
if digest.hexdigest() != expected:
raise ValueError('SHA-256 inesperado: ' + name)
return path
def data_and_vocab():
owners, removed, data = {}, Counter(), {}
limits = {'train': 3000, 'validation': 512, 'test': 512} if SHORT else {}
for split in ('train', 'validation', 'test'):
result, count = [], 0
for batch in pq.ParquetFile(checked_file(split)).iter_batches(batch_size=64, columns=['text']):
for text in batch.column(0).to_pylist():
if split in limits and count >= limits[split]:
break
words = tokenize(text or '')
if not words:
continue
key = hashlib.sha256('\0'.join(words).encode('utf-8')).hexdigest()
if key in owners and owners[key] != split:
removed[split] += 1
continue
# La huella identifica la fila completa; el recorte se aplica después.
owners.setdefault(key, split)
if split in limits:
words = words[:limits[split] - count]
result.extend(words + [EOS])
count += len(words)
if split in limits and count >= limits[split]:
break
if len(result) <= BPTT + 1:
raise ValueError('Partición insuficiente: ' + split)
data[split] = result
counts = Counter(data['train'])
if UNK in counts:
raise ValueError('Colisión del marcador UNK con el corpus')
vocab = [UNK, EOS] + sorted((w for w in counts if w != EOS),
key=lambda w: (-counts[w], w))[:VOCAB_CAP-2]
if len(vocab) < 12:
raise ValueError('Se requieren al menos 12 palabras para softmax adaptativo')
ids = {token: i for i, token in enumerate(vocab)}
encoded = {k: torch.tensor([ids.get(w, 0) for w in words], dtype=torch.long)
for k, words in data.items()}
return vocab, encoded, dict(removed)
def batchify(data, batch_size):
width = len(data) // batch_size
if width < 2:
raise ValueError('Se necesitan dos tokens por flujo')
return data[:width * batch_size].reshape(batch_size, width).T.contiguous()
def locked_dropout(x, p, training):
if not training or p == 0:
return x
if not 0 <= p < 1:
raise ValueError('Probabilidad de dropout inválida')
mask = F.dropout(torch.ones_like(x[:1]), p=p, training=True)
return x * mask
class RecurrentLayer(nn.Module):
def __init__(self, dim, weight_drop):
super().__init__()
self.rnn = nn.LSTM(dim, dim)
self.weight_drop = weight_drop
def forward(self, x, state, diagnostic=False):
raw_weight = self.rnn.weight_hh_l0
effective = F.dropout(raw_weight, p=self.weight_drop, training=self.training)
# Una única matriz muestreada para todo este bloque temporal.
if self.training and self.weight_drop:
out, new_state = functional_call(self.rnn, {'weight_hh_l0': effective}, (x, state))
else:
out, new_state = self.rnn(x, state)
observation = None
if diagnostic:
# Reconstrucción independiente de puertas de esta misma pasada.
with torch.no_grad():
if state is None:
h = x.new_zeros((x.shape[1], self.rnn.hidden_size))
c = torch.zeros_like(h)
else:
h, c = state[0][0].detach(), state[1][0].detach()
saturated, count = 0, 0
for xt in x.detach():
z = F.linear(xt, self.rnn.weight_ih_l0, self.rnn.bias_ih_l0)
z += F.linear(h, effective.detach(), self.rnn.bias_hh_l0)
zi, zf, zg, zo = z.chunk(4, dim=1)
i, f, g, o = zi.sigmoid(), zf.sigmoid(), zg.tanh(), zo.sigmoid()
saturated += int(((f < .05) | (f > .95)).sum())
count += f.numel()
c = f*c + i*g
h = o*c.tanh()
error = float((h - out[-1].detach()).abs().max())
if not math.isfinite(error) or error > 2e-4:
raise AssertionError(('Puertas manuales no coinciden con LSTM', error))
observation = {'forget_saturated_fraction': saturated / count,
'manual_last_state_max_error': error,
'layer': 0, 'criterion': 'f<0,05 o f>0,95'}
return out, new_state, observation
class LanguageModel(nn.Module):
def __init__(self, vocab_size, config):
super().__init__()
self.config = config.copy()
self.embedding = nn.Embedding(vocab_size, DIM)
self.layers = nn.ModuleList([RecurrentLayer(DIM, config['weight_drop']) for _ in range(3)])
self.vocab_size = vocab_size
self.cutoffs = None
if config['adaptive']:
a = max(2, vocab_size // 10)
b = max(a + 1, vocab_size * 35 // 100)
self.cutoffs = [a, min(b, vocab_size - 1)]
self.decoder = nn.AdaptiveLogSoftmaxWithLoss(DIM, vocab_size, self.cutoffs, div_value=4.)
else:
self.decoder = nn.Linear(DIM, vocab_size)
def forward(self, ids, states=None, diagnostic=False):
states = [None] * len(self.layers) if states is None else states
w = self.embedding.weight
if self.training and self.config['embedding_drop']:
mask = F.dropout(w.new_ones((w.shape[0], 1)),
p=self.config['embedding_drop'], training=True)
w = w * mask
x = F.embedding(ids, w)
x = locked_dropout(x, self.config['locked_drop'], self.training)
next_states, obs = [], None
for j, layer in enumerate(self.layers):
raw, state, observation = layer(x, states[j], diagnostic=(diagnostic and j == 0))
next_states.append(state)
if observation is not None:
obs = observation
x = locked_dropout(raw, self.config['locked_drop'], self.training)
return x, raw, next_states, obs
def nll(self, features, targets):
flat = features.reshape(-1, features.shape[-1])
y = targets.reshape(-1)
if self.config['adaptive']:
return self.decoder(flat, y).loss
return F.cross_entropy(self.decoder(flat), y)
def detach_state(states):
return [(h.detach(), c.detach()) for h, c in states]
def sync():
if DEVICE.type == 'cuda':
torch.cuda.synchronize(DEVICE)
@contextmanager
def averaged_weights(model, optimizer):
"""Usa ax de ASGD si existe; los parámetros sin gradiente conservan valor actual."""
originals = []
try:
if isinstance(optimizer, torch.optim.ASGD):
with torch.no_grad():
for p in model.parameters():
average = optimizer.state.get(p, {}).get('ax')
if average is not None:
originals.append((p, p.detach().clone()))
p.copy_(average)
yield
finally:
with torch.no_grad():
for p, value in originals:
p.copy_(value)
@torch.inference_mode()
def evaluate(model, data):
model.eval()
stream = batchify(data, 1).to(DEVICE)
total, count, states = 0., 0, None
for start in range(0, len(stream) - 1, BPTT):
length = min(BPTT, len(stream) - 1 - start)
x, target = stream[start:start+length], stream[start+1:start+length+1]
features, _, states, _ = model(x, states)
loss = model.nll(features, target)
if not torch.isfinite(loss):
raise ValueError('Pérdida de evaluación no finita')
total += float(loss) * target.numel()
count += target.numel()
mean = total / count
if mean > 700:
raise ValueError('Perplejidad fuera de rango')
return {'nats_per_token': mean, 'perplexity': math.exp(mean), 'tokens': count}
def check_masks():
# Prueba sin depender de coincidencias aleatorias: los ceros se repiten en T.
torch.manual_seed(17159)
x = torch.ones(7, 4, 64)
y = locked_dropout(x, .4, True)
assert all(torch.equal(y[0], y[t]) for t in range(1, len(y)))
assert torch.equal(locked_dropout(x, .4, False), x)
# DropConnect recibe gradiente en el parámetro original.
layer = RecurrentLayer(4, .3)
parameter = layer.rnn.weight_hh_l0
output, _, _ = layer(torch.randn(5, 3, 4), None)
output.square().mean().backward()
assert layer.rnn.weight_hh_l0 is parameter and parameter.grad is not None
assert torch.isfinite(parameter.grad).all()
def run(seed, name, options, encoded, vocab_size):
torch.manual_seed(seed)
if DEVICE.type == 'cuda':
torch.cuda.manual_seed_all(seed)
torch.cuda.reset_peak_memory_stats(DEVICE)
config = dict(BASE); config.update(options)
model = LanguageModel(vocab_size, config).to(DEVICE)
optimizer = torch.optim.SGD(model.parameters(), lr=LR)
stream = batchify(encoded['train'], BATCH).to(DEVICE)
rng = np.random.default_rng(seed + 1)
best, best_state, best_epoch = math.inf, None, None
val_history, history, training_seconds, trained_tokens = [], [], 0., 0
switched = False
for epoch in range(1, EPOCHS + 1):
model.train()
states, start, step = None, 0, 0
sync(); began = time.perf_counter()
while start < len(stream) - 1 and (MAX_STEPS is None or step < MAX_STEPS):
length = BPTT
if config['variable_bptt']:
center = BPTT if rng.random() < .95 else BPTT / 2
length = int(np.clip(round(rng.normal(center, max(1., BPTT / 8))),
2, 2 * BPTT))
length = min(length, len(stream) - 1 - start)
x, y = stream[start:start+length], stream[start+1:start+length+1]
states = None if states is None else detach_state(states)
optimizer.zero_grad(set_to_none=True)
features, raw, states, observation = model(x, states, diagnostic=(step == 0))
nll = model.nll(features, y)
ar = features.square().mean()
tar = (raw[1:] - raw[:-1]).square().mean() if len(raw) > 1 else raw.new_zeros(())
loss = nll + config['ar'] * ar + config['tar'] * tar
if not torch.isfinite(loss):
raise ValueError('Pérdida no finita')
loss.backward()
before = nn.utils.clip_grad_norm_(model.parameters(), CLIP, error_if_nonfinite=True)
after = torch.sqrt(sum(p.grad.detach().square().sum() for p in model.parameters()
if p.grad is not None))
optimizer.step()
step += 1
trained_tokens += y.numel()
if step == 1:
history.append({'epoch': epoch, 'step': step, 'nll': float(nll.detach()),
'gradient_norm_before_clip': float(before),
'gradient_norm_after_clip': float(after),
'forget_sample': observation})
start += length
sync(); training_seconds += time.perf_counter() - began
with averaged_weights(model, optimizer):
valid = evaluate(model, encoded['validation'])
if valid['nats_per_token'] < best:
best, best_epoch = valid['nats_per_token'], epoch
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
val_history.append(valid)
# Variante explícita de criterio no monótono: compara contra el mejor
# valor anterior a las dos validaciones más recientes.
should_switch = (len(val_history) > NONMONO and
valid['nats_per_token'] < math.inf and
valid['nats_per_token'] > min(v['nats_per_token']
for v in val_history[:-NONMONO]))
# En SHORT se fuerza tras época 1 solo para cubrir el código ASGD.
if SHORT and epoch == 1:
should_switch = True
if config['nt_asgd'] and not switched and should_switch:
optimizer = torch.optim.ASGD(model.parameters(), lr=LR, t0=0, lambd=0.)
switched = True
if best_state is None:
raise ValueError('No se seleccionó checkpoint')
model.load_state_dict(best_state)
test = evaluate(model, encoded['test'])
peak = int(torch.cuda.max_memory_allocated(DEVICE)) if DEVICE.type == 'cuda' else None
result = {'seed': seed, 'ablation': name, 'config': config,
'parameters': sum(p.numel() for p in model.parameters()),
'adaptive_cutoffs': model.cutoffs, 'validation': val_history,
'selected_epoch': best_epoch, 'test_exploratory': test,
'gradient_and_gate_samples': history, 'asgd_switched': switched,
'asgd_forced_for_short': bool(SHORT and config['nt_asgd']),
'training_tokens': trained_tokens,
'training_seconds_synchronized': training_seconds,
'training_tokens_per_second': trained_tokens / training_seconds,
'gpu_peak_allocated_bytes': peak}
del model, optimizer, stream, best_state
if DEVICE.type == 'cuda':
torch.cuda.empty_cache()
return result
def main():
if EPOCHS < 1:
raise ValueError('ORYON_EPOCHS debe ser positivo')
check_masks()
vocab, encoded, removed = data_and_vocab()
OUT.mkdir(parents=True, exist_ok=True)
payload = {'short': SHORT, 'source_revision': REV, 'file_sha256': FILES,
'split': 'filas duplicadas exactas entre particiones excluidas; '
'coincidencias parciales no detectadas',
'excluded': removed, 'vocab_size': len(vocab),
'oov': {k: int((data == 0).sum()) for k, data in encoded.items()},
'device': str(DEVICE), 'torch': torch.__version__, 'cuda': torch.version.cuda,
'cudnn': torch.backends.cudnn.version(),
'gpu': torch.cuda.get_device_name(DEVICE) if DEVICE.type == 'cuda' else None,
'protocol': {'seeds': SEEDS, 'epochs': EPOCHS, 'batch': BATCH,
'bptt': BPTT, 'eval_batch': 1, 'eval_bptt': BPTT,
'eval_state': 'estado preservado entre bloques dentro de la partición',
'test': 'exploratorio tras selección en validación por configuración',
'timing': 'tiempo sincronizado de entrenamiento; incluye diagnóstico de puertas',
'memory': 'pico asignado por PyTorch, no uso global del dispositivo',
'asgd': 'criterio no monótono descrito en el código; SHORT fuerza el cambio',
'limitations': 'sin atado de pesos ni búsqueda original; no reproduce el paper'},
'results': []}
for seed in SEEDS:
for name, options in ABLATIONS:
row = run(seed, name, options, encoded, len(vocab))
payload['results'].append(row)
(OUT / 'results.json').write_text(json.dumps(payload, ensure_ascii=False, indent=2),
encoding='utf-8')
print(name, seed, 'validación', row['validation'],
'test exploratorio', row['test_exploratory'])
print('Datos:', OUT / 'results.json')
print('SHORT comprueba las rutas, no mide convergencia ni identifica ganadores.')
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
import numpy as np
def masked_forward(xs, mask, h0, c0, step):
passimport numpy as np
def masked_state(h, c, h_new, c_new, valid):
passimport numpy as np
def locked_dropout(x, keep, p):
passFurther reading
Regularization and careful splits remain important with attention and Transformer block. Before comparing models, check the definition and support of perplexity in Intrinsic language model evaluation.