Recurrent neural networks: hidden state, shared parameters and language models
Study recurrent neural networks, shared state transitions, task losses and character generation.
After this lesson you can
- Explain Elman recurrent state and shared parameters through time.
- Place losses and masks for sequence tasks.
- Derive teacher-forced autoregressive likelihood and generate characters.
- Compare a NumPy recurrent forward pass with PyTorch under matched conventions.
Before you start
- 17Autoregressive factorizationTaxonomy of sequence tasksEmbedding lookup table and its sparse gradientNeural probabilistic language modelAncestral sampling from an autoregressive modelIntrinsic language model evaluation
- 15Forward propagationTanh activationBatch shape convention
- 07Softmax cross-entropy loss
- 00Broadcasting rules
A memory that advances with the sequence
In a fixed-window neural model, each prediction receives only a fixed number of previous tokens. A recurrent neural network introduces a state variable updated as each token is read. The same operation can be applied to a short sequence or one longer than those seen during training.
The program’s ability to advance more steps does not imply it retains useful information throughout them. State has fixed size, the transition may forget information and training may not generalize to long sequences. Separating execution capability from memory quality is essential when studying gradients.
The Elman state
In a simple Elman network, the previous hidden state participates in calculating the next. In this convention examples are rows. For sequences, embeddings of dimension and state of dimension :
Shapes are , , , and . Biases broadcast across the batch; contains logits, not probabilities until softmax is applied. The complete input sequence has shape and logits .
State summarizes the prefix for the model and learned task. It need not retain all text or be a sufficient statistic of the true language distribution. Elman architecture feeds back hidden state. A Jordan network uses a form of output feedback; both explore recurrent memory but are not the same graph by definition.
One cell, many steps
Parameter sharing means , and are the same matrices at every time. When unrolling the graph, we draw a copy of the operation per step with its own activations, but not an independent parameter copy. Editing one weight affects all applications; gradient contributions accumulate across them.
Applying the same input sequence from the same initial state yields the same state sequence under the shared transition, even if the block appears elsewhere. That homogeneity does not make the network invariant to token permutations. Nor does it ensure prepending zeros shifts outputs unchanged: those extra steps can modify state through recurrence and bias.
State can be studied as a dynamical system driven by input. As an example only, consider a two-dimensional state and recurrent matrix , with and a rotation. For two initial states under the same inputs and bias, : is 1-Lipschitz and . If , distance tends to zero at at least that rate. does not guarantee saturation: with zero state, input and bias, state stays zero. A nonzero angle also does not guarantee visible oscillations on every trajectory. Examine conditions and calculate the particular example.
Where loss is applied
The same transition type can serve different tasks, but inputs, outputs and targets must be specified:
- Many to one: when classifying a review, a head can use the final valid state to predict a label.
- Aligned many to many: when tagging each token, a head produces a prediction and loss for every valid position.
- Language model: each state predicts the next token, not the one just consumed.
- Conditional one to many: an image representation can initialize a generator’s state or enter in another explicit way; successive tokens are then produced.
Loss placement and feedback are different decisions. If a batch has different lengths, the mask must exclude padding from both loss and denominator. Also, feeding zero padding vectors after the end can change state through and . For classification use the last real token’s state, stop updating at padded positions or use packed sequences.
Predict the next character
For a recurrent language model, fix an embedding table, start symbol BOS and end symbol EOS. If content characters are , a consistent convention is to feed
Each state after an input produces logits for its corresponding target. In particular, state after BOS predicts and state after predicts EOS. This convention prevents the network seeing the character it must predict at the same position. BOS can have an input row without being an output class; that choice affects vocabulary and parameter count.
During teacher forcing, previous input comes from the observed sequence. Williams and Zipser named the replacement of a feedback output by the teaching signal and acknowledged earlier antecedents. In the language model we use the observed token as next-step input; we do not fix hidden state to a label.
Autoregressive factorization and cross-entropy loss are
where , is one for each real target including EOS and zero only for padding; . With fixed data and mask, dividing total log-likelihood by multiplies it by a positive constant: minimizing equals maximizing joint likelihood of the sequence set. If the mask omits real targets, the sum is a partial objective, not the same complete likelihood. Averaging first per sequence and then across sequences of different lengths applies different weighting. Perplexity compares directly only between models scoring the same events with the same vocabulary and EOS and OOV treatment.
Generate without the true next token
In free generation, consume BOS and seed characters, obtain a next-character distribution, sample and feed the emitted character. Retain state between steps. Stop on EOS; if a safety limit is reached, report truncation. An unknown seed character requires an explicit policy: reject it or map it to an unknown symbol with appropriate support.
If you force a character, it must pass through the transition before displaying the following distribution. A reproducible pseudorandom seed repeats a draw under the same algorithm; it does not prove a short sample representative. Loss with observed prefixes and quality of a free trajectory answer different questions.
The next figure uses weights exported by a short local lab run: 100 of the full configuration’s 800 updates on the training excerpt. Vocabulary contains observed characters, UNK and EOS, while BOS has only an input embedding. The test observes the mechanism, not proves the model learned to write. After choosing an unlikely character, compare the distribution before and after forcing it: the new distribution depends on updated state, not only the last character.
A published result and its context
Mikolov and colleagues evaluated language models for speech recognition. In Table 2, with 6.4 million training words and WSJ DEV, KN5 obtained perplexity 221 and 13.5% word error. An RNN with 250 hidden units and vocabulary threshold 5 obtained 173 and 12.3%. Mixed with KN, figures were 155 and 11.7%, with weights 0.75 for RNN and 0.25 for backoff in those combinations.
Those figures belong to that task, corpus and configuration; the mixture is not an isolated RNN. The table also includes dynamic models adapting online, so do not present them as evaluation of completely frozen parameters. Neither teacher-forcing perplexity nor a generated example guarantees the same outcome in another application.
Correspondence with PyTorch
With nn.RNN(..., batch_first=True), batch input has shape . In one unidirectional layer, output has shape and h_n shape . batch_first does not change state-dimension order. The RNN returns states; character prediction still needs a linear layer to logits.
PyTorch stores input and recurrent matrices as and and uses two biases by default. To compare with row equations, copy corresponding transposes and distribute mathematical bias so the sum of both PyTorch biases equals . For a robust check use batch and sequence longer than one element, nonzero initial state and compare every step, not just the last.
Labs
Forward and generation from scratch
The first lab implements an RNN forward pass in NumPy, retains activations and checks shapes, mask and target shift. A reproducible cell should provide generator weights along with text provenance, seed and train/evaluation separation. A short model checks the pipeline and may generate incoherent sequences; it does not replace full training.
This cell uses two excerpts from different chapters of part one of Don Quixote from Project Gutenberg. Vocabulary comes only from training; UNK does not appear as a positive target in that training, limiting interpretation of unknown characters. Identical texts are rejected, but partial matches are not ruled out. Input starts with BOS and targets end in EOS. With padding, the mask excludes its loss and denominator but does not prevent recurrent state updates.
Here BOS occupies input row V and EOS output index 1. The self-contained exercise below uses another convention: EOS is V−1; adapt indices before reusing code between them. Generation reports whether EOS or the limit ended it. Steps on this sample only verify the pipeline and do not establish weight quality.
"""RNN de caracteres desde cero; fragmentos pequeños y sin acceso a red.
Miguel de Cervantes, Don Quijote, primera parte, capítulos I y II:
https://www.gutenberg.org/files/2000/2000-0.txt . Project Gutenberg declara
dominio público en EE. UU.; consulta la ley local y su política de marca:
https://www.gutenberg.org/policy/license.html .
Los fragmentos son demasiado pequeños para demostrar calidad de generación.
"""
import hashlib
import json
import math
import unicodedata
import numpy as np
TRAIN_TEXT = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
VALID_TEXT = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
SEED = 17090
UNK = '<unk>'
EOS = '</s>'
def prepare(train, valid):
train = unicodedata.normalize('NFC', train).lower()
valid = unicodedata.normalize('NFC', valid).lower()
if len(train) < 2 or len(valid) < 2 or train == valid:
raise ValueError('Los textos deben ser distintos y tener al menos dos caracteres')
vocab = [UNK, EOS, *sorted(set(train))]
index = {char: i for i, char in enumerate(vocab)}
encode = lambda text: np.asarray([index.get(char, 0) for char in text], dtype=np.int64)
return vocab, encode(train), encode(valid)
def initial_params(vocab_size, embed, hidden, seed):
if vocab_size < 2 or embed < 1 or hidden < 1:
raise ValueError('Dimensiones inválidas')
rng = np.random.default_rng(seed)
# BOS es una fila adicional solo de entrada; EOS sí es clase de salida.
return {'E': rng.normal(0., .08, (vocab_size + 1, embed)),
'Wx': rng.normal(0., .08, (embed, hidden)),
'Wh': rng.normal(0., .08, (hidden, hidden)),
'bh': np.zeros(hidden),
'Wy': rng.normal(0., .08, (hidden, vocab_size)),
'by': np.zeros(vocab_size)}
def rnn_forward(x, h0, params):
"""x=(B,T,d), h0=(B,H), salida=(B,T,H), caché por paso."""
if x.ndim != 3 or x.shape[1] == 0 or h0.shape != (x.shape[0], params['Wh'].shape[0]):
raise ValueError('Formas incorrectas o secuencia vacía')
states, cache = [], []
h = h0.copy()
for t in range(x.shape[1]):
previous = h
h = np.tanh(x[:, t] @ params['Wx'] + previous @ params['Wh'] + params['bh'])
cache.append((x[:, t], previous, h))
states.append(h)
return np.stack(states, axis=1), h, cache
def teacher_loss(params, ids, targets, h0, backward=False, mask=None):
"""Pérdida por token válido; los objetivos ocultos siguen siendo índices válidos.
La máscara solo afecta a la pérdida, no detiene la transición de estado.
"""
if ids.ndim != 2 or targets.shape != ids.shape:
raise ValueError('Entradas y objetivos deben tener forma (B,T)')
mask = np.ones(ids.shape, dtype=float) if mask is None else np.asarray(mask, dtype=float)
if mask.shape != ids.shape or not np.all((mask == 0) | (mask == 1)) or mask.sum() == 0:
raise ValueError('La máscara debe ser binaria, de forma (B,T) y no vacía')
normalizer = float(mask.sum())
x = params['E'][ids]
states, last, cache = rnn_forward(x, h0, params)
logits = states @ params['Wy'] + params['by']
shifted = logits - logits.max(axis=2, keepdims=True)
logz = np.log(np.exp(shifted).sum(axis=2, keepdims=True))
selected = np.take_along_axis(shifted - logz, targets[..., None], axis=2)
loss = -float(np.sum(selected[..., 0] * mask) / normalizer)
if not backward:
return loss, last
B, T = ids.shape
grad_logits = np.exp(shifted - logz)
rows = np.arange(B)[:, None]
cols = np.arange(T)[None, :]
grad_logits[rows, cols, targets] -= 1.
grad_logits *= mask[..., None] / normalizer
grads = {name: np.zeros_like(value) for name, value in params.items()}
grads['Wy'] = states.reshape(-1, states.shape[-1]).T @ grad_logits.reshape(-1, logits.shape[-1])
grads['by'] = grad_logits.sum(axis=(0, 1))
dh_next = np.zeros_like(h0)
for t in range(T - 1, -1, -1):
xt, previous, state = cache[t]
dh = grad_logits[:, t] @ params['Wy'].T + dh_next
da = dh * (1. - state * state)
grads['Wx'] += xt.T @ da
grads['Wh'] += previous.T @ da
grads['bh'] += da.sum(axis=0)
np.add.at(grads['E'], ids[:, t], da @ params['Wx'].T)
dh_next = da @ params['Wh'].T
return loss, last, grads, dh_next
def gradcheck():
p = initial_params(4, 2, 3, SEED)
ids = np.array([[4, 1, 2], [4, 1, 3]], dtype=np.int64)
target = np.array([[1, 2, 3], [1, 3, 2]], dtype=np.int64)
mask = np.array([[1., 1., 0.], [1., 1., 1.]])
h0 = np.array([[.1, -.2, .05], [-.1, .1, .2]])
_, _, grads, dh0 = teacher_loss(p, ids, target, h0, backward=True, mask=mask)
alternate = target.copy()
alternate[0, 2] = (alternate[0, 2] + 1) % len(p['by'])
original_loss = teacher_loss(p, ids, target, h0, mask=mask)[0]
alternate_loss = teacher_loss(p, ids, alternate, h0, mask=mask)[0]
assert np.isclose(original_loss, alternate_loss, atol=1e-12)
errors = {}
for name, arr in [*p.items(), ('h0', h0)]:
analytic = dh0 if name == 'h0' else grads[name]
error = 0.
for idx in np.ndindex(arr.shape):
value = arr[idx]
arr[idx] = value + 1e-6
plus = teacher_loss(p, ids, target, h0, mask=mask)[0]
arr[idx] = value - 1e-6
minus = teacher_loss(p, ids, target, h0, mask=mask)[0]
arr[idx] = value
error = max(error, abs((plus - minus) / 2e-6 - analytic[idx]))
assert error < 1e-7, (name, error)
errors[name] = error
return errors
def sample(params, vocab, prefix, count, seed):
if count < 0:
raise ValueError('La cantidad debe ser no negativa')
rng = np.random.default_rng(seed)
index = {char: i for i, char in enumerate(vocab)}
h = np.zeros((1, len(params['bh'])))
# BOS y cada símbolo del prefijo se procesan exactamente una vez.
_, h, _ = rnn_forward(params['E'][np.array([[len(vocab)]])], h, params)
for char in unicodedata.normalize('NFC', prefix).lower():
value = index.get(char, 0)
_, h, _ = rnn_forward(params['E'][np.array([[value]])], h, params)
output, first_distribution, reason = [], None, 'límite'
for _ in range(count):
logits = (h @ params['Wy'] + params['by'])[0]
weights = np.exp(logits - logits.max())
weights /= weights.sum()
if first_distribution is None:
first_distribution = weights.tolist()
choice = int(rng.choice(len(vocab), p=weights))
if vocab[choice] == EOS:
reason = 'eos'
break
output.append('�' if choice == 0 else vocab[choice])
_, h, _ = rnn_forward(params['E'][np.array([[choice]])], h, params)
return ''.join(output), first_distribution, reason
def sequence_events(sequence, bos, eos):
"""Entradas [BOS, contenido] y objetivos [contenido, EOS]."""
return (np.concatenate(([bos], sequence)).astype(np.int64),
np.concatenate((sequence, [eos])).astype(np.int64))
def sampler_check():
vocab = [UNK, EOS, 'a', 'b']
params = initial_params(len(vocab), 2, 3, SEED)
params['Wy'][:] = 0.
params['by'][:] = [0., 1000., 0., 0.]
text, _, reason = sample(params, vocab, '', 3, SEED)
assert text == '' and reason == 'eos'
params['by'][:] = [0., 0., 1000., 0.]
text, _, reason = sample(params, vocab, '', 3, SEED)
assert text == 'aaa' and reason == 'límite'
def train_small(params, train, valid, steps=25, rate=.3):
inputs, targets = sequence_events(train, len(params['by']), 1)
valid_inputs, valid_targets = sequence_events(valid, len(params['by']), 1)
inputs, targets = inputs[None, :], targets[None, :]
h0 = np.zeros((1, len(params['bh'])))
history = []
for step in range(steps + 1):
loss, _, grads, _ = teacher_loss(params, inputs, targets, h0, backward=True)
if not math.isfinite(loss) or any(not np.isfinite(g).all() for g in grads.values()):
raise ValueError('Pérdida o gradiente no finito')
if step in (0, steps):
val, _ = teacher_loss(params, valid_inputs[None, :], valid_targets[None, :], h0)
history.append({'step': step, 'train_nats': loss, 'valid_nats': val})
if step < steps:
for name in params:
params[name] -= rate * grads[name]
return history
def main():
vocab, train, valid = prepare(TRAIN_TEXT, VALID_TEXT)
train_x, train_y = sequence_events(train, len(vocab), vocab.index(EOS))
assert train_x[0] == len(vocab) and train_y[-1] == vocab.index(EOS)
assert np.array_equal(train_x[1:], train_y[:-1])
params = initial_params(len(vocab), embed=6, hidden=10, seed=SEED)
print('Gradcheck por diferencias finitas:', gradcheck())
sampler_check()
history = train_small(params, train, valid)
print('Tokens y OOV de validación:', len(train), len(valid), int(np.sum(valid == 0)))
print('Vocabulario de entrenamiento:', vocab, '| entropía uniforme log(V):', math.log(len(vocab)))
print('Pérdidas train y validación exploratoria:', history)
sample_a = sample(params, vocab, prefix='en ', count=40, seed=SEED + 1)
sample_b = sample(params, vocab, prefix='en ', count=40, seed=SEED + 1)
assert sample_a == sample_b
print('Generación ancestral reproducible:', sample_a[0], '| terminación:', sample_a[2])
print('Distribución siguiente tras el prefijo:', sample_a[1])
print('Modelo entrenado en la muestra, para inspección:',
json.dumps({'vocab': vocab, 'bos_index': len(vocab), 'eos_index': vocab.index(EOS),
'params': {key: value.tolist() for key, value in params.items()}},
ensure_ascii=False))
print('BOS es solo entrada; EOS es salida. OOV se convierte a UNK, que no tiene ejemplos positivos en entrenamiento.')
print('La máscara pondera la pérdida, pero no detiene la evolución del estado en padding.')
print('Cada documento reinicia el estado; validación y muestra no prueban calidad general.')
print('SHA-256 de fragmentos UTF-8:',
hashlib.sha256(TRAIN_TEXT.encode('utf-8')).hexdigest(),
hashlib.sha256(VALID_TEXT.encode('utf-8')).hexdigest())
if __name__ == '__main__':
main()The same forward pass with nn.RNN
The second lab loads the same parameters and initial state in PyTorch and compares outputs and states with NumPy. Weight transposition, both biases, numerical precision and batch lengths are part of the check.
The local cell requires PyTorch and NumPy and compares states, loss and gradients with the same parameters in double precision. PyTorch adds two biases: for the check the NumPy cell bias is loaded into bias_ih and bias_hh set to zero. Since both biases are subsequently trained, that evolution need not match updating only one. batch_first affects inputs and outputs, not initial-state shape.
ORYON_VERIFY_SHORT=1 reduces steps and batch; ORYON_VERIFY_STEPS permits another positive step count. You can supply two UTF-8 files via ORYON_TRAIN_FILE and ORYON_VALID_FILE; otherwise the cited short excerpts are used. Training windows start from zero state; validation resets per document and retains state across contiguous blocks. Validation is exploratory. Model and metrics are written to ORYON_OUTPUT, without relying on internal reports.
The figure’s model was exported with ORYON_VERIFY_SHORT=1, ORYON_VERIFY_STEPS=100, seed 17090 and PyTorch 2.11.0 on CPU: batches of two and twelve-token windows on the 60-character excerpt. The bundled weights file has SHA-256 050ff26156f1ee610a7ebeade62583e67917a7fa20d94d96a88505496fc02ae3; versions or platforms may change its bytes. In that run parity checking covered states, losses and gradients, and gradcheck used finite differences. Validation was tiny and contained unknown characters, so its metrics do not establish generalization.
"""RNN de caracteres desde cero; fragmentos pequeños y sin acceso a red.
Miguel de Cervantes, Don Quijote, primera parte, capítulos I y II:
https://www.gutenberg.org/files/2000/2000-0.txt . Project Gutenberg declara
dominio público en EE. UU.; consulta la ley local y su política de marca:
https://www.gutenberg.org/policy/license.html .
Los fragmentos son demasiado pequeños para demostrar calidad de generación.
"""
import hashlib
import json
import math
import unicodedata
import numpy as np
TRAIN_TEXT = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
VALID_TEXT = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
SEED = 17090
UNK = '<unk>'
EOS = '</s>'
def prepare(train, valid):
train = unicodedata.normalize('NFC', train).lower()
valid = unicodedata.normalize('NFC', valid).lower()
if len(train) < 2 or len(valid) < 2 or train == valid:
raise ValueError('Los textos deben ser distintos y tener al menos dos caracteres')
vocab = [UNK, EOS, *sorted(set(train))]
index = {char: i for i, char in enumerate(vocab)}
encode = lambda text: np.asarray([index.get(char, 0) for char in text], dtype=np.int64)
return vocab, encode(train), encode(valid)
def initial_params(vocab_size, embed, hidden, seed):
if vocab_size < 2 or embed < 1 or hidden < 1:
raise ValueError('Dimensiones inválidas')
rng = np.random.default_rng(seed)
# BOS es una fila adicional solo de entrada; EOS sí es clase de salida.
return {'E': rng.normal(0., .08, (vocab_size + 1, embed)),
'Wx': rng.normal(0., .08, (embed, hidden)),
'Wh': rng.normal(0., .08, (hidden, hidden)),
'bh': np.zeros(hidden),
'Wy': rng.normal(0., .08, (hidden, vocab_size)),
'by': np.zeros(vocab_size)}
def rnn_forward(x, h0, params):
"""x=(B,T,d), h0=(B,H), salida=(B,T,H), caché por paso."""
if x.ndim != 3 or x.shape[1] == 0 or h0.shape != (x.shape[0], params['Wh'].shape[0]):
raise ValueError('Formas incorrectas o secuencia vacía')
states, cache = [], []
h = h0.copy()
for t in range(x.shape[1]):
previous = h
h = np.tanh(x[:, t] @ params['Wx'] + previous @ params['Wh'] + params['bh'])
cache.append((x[:, t], previous, h))
states.append(h)
return np.stack(states, axis=1), h, cache
def teacher_loss(params, ids, targets, h0, backward=False, mask=None):
"""Pérdida por token válido; los objetivos ocultos siguen siendo índices válidos.
La máscara solo afecta a la pérdida, no detiene la transición de estado.
"""
if ids.ndim != 2 or targets.shape != ids.shape:
raise ValueError('Entradas y objetivos deben tener forma (B,T)')
mask = np.ones(ids.shape, dtype=float) if mask is None else np.asarray(mask, dtype=float)
if mask.shape != ids.shape or not np.all((mask == 0) | (mask == 1)) or mask.sum() == 0:
raise ValueError('La máscara debe ser binaria, de forma (B,T) y no vacía')
normalizer = float(mask.sum())
x = params['E'][ids]
states, last, cache = rnn_forward(x, h0, params)
logits = states @ params['Wy'] + params['by']
shifted = logits - logits.max(axis=2, keepdims=True)
logz = np.log(np.exp(shifted).sum(axis=2, keepdims=True))
selected = np.take_along_axis(shifted - logz, targets[..., None], axis=2)
loss = -float(np.sum(selected[..., 0] * mask) / normalizer)
if not backward:
return loss, last
B, T = ids.shape
grad_logits = np.exp(shifted - logz)
rows = np.arange(B)[:, None]
cols = np.arange(T)[None, :]
grad_logits[rows, cols, targets] -= 1.
grad_logits *= mask[..., None] / normalizer
grads = {name: np.zeros_like(value) for name, value in params.items()}
grads['Wy'] = states.reshape(-1, states.shape[-1]).T @ grad_logits.reshape(-1, logits.shape[-1])
grads['by'] = grad_logits.sum(axis=(0, 1))
dh_next = np.zeros_like(h0)
for t in range(T - 1, -1, -1):
xt, previous, state = cache[t]
dh = grad_logits[:, t] @ params['Wy'].T + dh_next
da = dh * (1. - state * state)
grads['Wx'] += xt.T @ da
grads['Wh'] += previous.T @ da
grads['bh'] += da.sum(axis=0)
np.add.at(grads['E'], ids[:, t], da @ params['Wx'].T)
dh_next = da @ params['Wh'].T
return loss, last, grads, dh_next
def gradcheck():
p = initial_params(4, 2, 3, SEED)
ids = np.array([[4, 1, 2], [4, 1, 3]], dtype=np.int64)
target = np.array([[1, 2, 3], [1, 3, 2]], dtype=np.int64)
mask = np.array([[1., 1., 0.], [1., 1., 1.]])
h0 = np.array([[.1, -.2, .05], [-.1, .1, .2]])
_, _, grads, dh0 = teacher_loss(p, ids, target, h0, backward=True, mask=mask)
alternate = target.copy()
alternate[0, 2] = (alternate[0, 2] + 1) % len(p['by'])
original_loss = teacher_loss(p, ids, target, h0, mask=mask)[0]
alternate_loss = teacher_loss(p, ids, alternate, h0, mask=mask)[0]
assert np.isclose(original_loss, alternate_loss, atol=1e-12)
errors = {}
for name, arr in [*p.items(), ('h0', h0)]:
analytic = dh0 if name == 'h0' else grads[name]
error = 0.
for idx in np.ndindex(arr.shape):
value = arr[idx]
arr[idx] = value + 1e-6
plus = teacher_loss(p, ids, target, h0, mask=mask)[0]
arr[idx] = value - 1e-6
minus = teacher_loss(p, ids, target, h0, mask=mask)[0]
arr[idx] = value
error = max(error, abs((plus - minus) / 2e-6 - analytic[idx]))
assert error < 1e-7, (name, error)
errors[name] = error
return errors
def sample(params, vocab, prefix, count, seed):
if count < 0:
raise ValueError('La cantidad debe ser no negativa')
rng = np.random.default_rng(seed)
index = {char: i for i, char in enumerate(vocab)}
h = np.zeros((1, len(params['bh'])))
# BOS y cada símbolo del prefijo se procesan exactamente una vez.
_, h, _ = rnn_forward(params['E'][np.array([[len(vocab)]])], h, params)
for char in unicodedata.normalize('NFC', prefix).lower():
value = index.get(char, 0)
_, h, _ = rnn_forward(params['E'][np.array([[value]])], h, params)
output, first_distribution, reason = [], None, 'límite'
for _ in range(count):
logits = (h @ params['Wy'] + params['by'])[0]
weights = np.exp(logits - logits.max())
weights /= weights.sum()
if first_distribution is None:
first_distribution = weights.tolist()
choice = int(rng.choice(len(vocab), p=weights))
if vocab[choice] == EOS:
reason = 'eos'
break
output.append('�' if choice == 0 else vocab[choice])
_, h, _ = rnn_forward(params['E'][np.array([[choice]])], h, params)
return ''.join(output), first_distribution, reason
def sequence_events(sequence, bos, eos):
"""Entradas [BOS, contenido] y objetivos [contenido, EOS]."""
return (np.concatenate(([bos], sequence)).astype(np.int64),
np.concatenate((sequence, [eos])).astype(np.int64))
def sampler_check():
vocab = [UNK, EOS, 'a', 'b']
params = initial_params(len(vocab), 2, 3, SEED)
params['Wy'][:] = 0.
params['by'][:] = [0., 1000., 0., 0.]
text, _, reason = sample(params, vocab, '', 3, SEED)
assert text == '' and reason == 'eos'
params['by'][:] = [0., 0., 1000., 0.]
text, _, reason = sample(params, vocab, '', 3, SEED)
assert text == 'aaa' and reason == 'límite'
def train_small(params, train, valid, steps=25, rate=.3):
inputs, targets = sequence_events(train, len(params['by']), 1)
valid_inputs, valid_targets = sequence_events(valid, len(params['by']), 1)
inputs, targets = inputs[None, :], targets[None, :]
h0 = np.zeros((1, len(params['bh'])))
history = []
for step in range(steps + 1):
loss, _, grads, _ = teacher_loss(params, inputs, targets, h0, backward=True)
if not math.isfinite(loss) or any(not np.isfinite(g).all() for g in grads.values()):
raise ValueError('Pérdida o gradiente no finito')
if step in (0, steps):
val, _ = teacher_loss(params, valid_inputs[None, :], valid_targets[None, :], h0)
history.append({'step': step, 'train_nats': loss, 'valid_nats': val})
if step < steps:
for name in params:
params[name] -= rate * grads[name]
return history
def main():
vocab, train, valid = prepare(TRAIN_TEXT, VALID_TEXT)
train_x, train_y = sequence_events(train, len(vocab), vocab.index(EOS))
assert train_x[0] == len(vocab) and train_y[-1] == vocab.index(EOS)
assert np.array_equal(train_x[1:], train_y[:-1])
params = initial_params(len(vocab), embed=6, hidden=10, seed=SEED)
print('Gradcheck por diferencias finitas:', gradcheck())
sampler_check()
history = train_small(params, train, valid)
print('Tokens y OOV de validación:', len(train), len(valid), int(np.sum(valid == 0)))
print('Vocabulario de entrenamiento:', vocab, '| entropía uniforme log(V):', math.log(len(vocab)))
print('Pérdidas train y validación exploratoria:', history)
sample_a = sample(params, vocab, prefix='en ', count=40, seed=SEED + 1)
sample_b = sample(params, vocab, prefix='en ', count=40, seed=SEED + 1)
assert sample_a == sample_b
print('Generación ancestral reproducible:', sample_a[0], '| terminación:', sample_a[2])
print('Distribución siguiente tras el prefijo:', sample_a[1])
print('Modelo entrenado en la muestra, para inspección:',
json.dumps({'vocab': vocab, 'bos_index': len(vocab), 'eos_index': vocab.index(EOS),
'params': {key: value.tolist() for key, value in params.items()}},
ensure_ascii=False))
print('BOS es solo entrada; EOS es salida. OOV se convierte a UNK, que no tiene ejemplos positivos en entrenamiento.')
print('La máscara pondera la pérdida, pero no detiene la evolución del estado en padding.')
print('Cada documento reinicia el estado; validación y muestra no prueban calidad general.')
print('SHA-256 de fragmentos UTF-8:',
hashlib.sha256(TRAIN_TEXT.encode('utf-8')).hexdigest(),
hashlib.sha256(VALID_TEXT.encode('utf-8')).hexdigest())
# La implementación anterior se incluye para que la celda sea autocontenida.
import os
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.set_num_threads(1)
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
BATCH = 2 if SHORT else 16
WINDOW = 12 if SHORT else 64
STEPS = int(os.environ.get('ORYON_VERIFY_STEPS', 4 if SHORT else 800))
if STEPS < 1:
raise ValueError('El número de pasos debe ser positivo')
OUT = Path(os.environ.get('ORYON_OUTPUT', 'char_rnn_output'))
DTYPE = torch.float64
torch.manual_seed(SEED)
class TorchCharRNN(nn.Module):
def __init__(self, params):
super().__init__()
input_size, d = params['E'].shape
V = len(params['by'])
if input_size != V + 1:
raise ValueError('La tabla de entrada debe incluir BOS adicional')
H = len(params['bh'])
self.embedding = nn.Embedding(input_size, d, dtype=DTYPE)
self.rnn = nn.RNN(d, H, num_layers=1, nonlinearity='tanh',
bias=True, batch_first=True, bidirectional=False, dtype=DTYPE)
self.output = nn.Linear(H, V, bias=True, dtype=DTYPE)
with torch.no_grad():
self.embedding.weight.copy_(torch.as_tensor(params['E'], dtype=DTYPE))
self.rnn.weight_ih_l0.copy_(torch.as_tensor(params['Wx'].T.copy(), dtype=DTYPE))
self.rnn.weight_hh_l0.copy_(torch.as_tensor(params['Wh'].T.copy(), dtype=DTYPE))
# PyTorch suma bias_ih y bias_hh; aquí su suma reproduce bh.
self.rnn.bias_ih_l0.copy_(torch.as_tensor(params['bh'], dtype=DTYPE))
self.rnn.bias_hh_l0.zero_()
self.output.weight.copy_(torch.as_tensor(params['Wy'].T.copy(), dtype=DTYPE))
self.output.bias.copy_(torch.as_tensor(params['by'], dtype=DTYPE))
def forward(self, ids, h0):
states, hlast = self.rnn(self.embedding(ids), h0)
return self.output(states), states, hlast
def torch_to_numpy(model):
return {'E': model.embedding.weight.detach().numpy().copy(),
'Wx': model.rnn.weight_ih_l0.detach().numpy().T.copy(),
'Wh': model.rnn.weight_hh_l0.detach().numpy().T.copy(),
'bh': (model.rnn.bias_ih_l0 + model.rnn.bias_hh_l0).detach().numpy().copy(),
'Wy': model.output.weight.detach().numpy().T.copy(),
'by': model.output.bias.detach().numpy().copy()}
def verify_parity():
p = initial_params(5, 3, 4, SEED)
# Sesgo no nulo y estado inicial distinto por elemento del lote.
p['bh'][:] = [.1, -.2, .05, .3]
ids = np.array([[5, 1, 2], [5, 3, 1]], dtype=np.int64)
target = np.array([[1, 2, 3], [3, 1, 4]], dtype=np.int64)
mask = np.array([[1., 1., 0.], [1., 1., 1.]])
h0 = np.array([[.1, -.2, .3, .15], [.3, .1, -.1, -.2]])
own_states, own_last, _ = rnn_forward(p['E'][ids], h0, p)
loss, _, grads, dh0 = teacher_loss(p, ids, target, h0, backward=True, mask=mask)
model = TorchCharRNN(p)
initial = torch.tensor(h0[None, :, :], dtype=DTYPE, requires_grad=True)
scores, states, last = model(torch.tensor(ids), initial)
targets_t = torch.tensor(target)
losses = F.cross_entropy(scores.reshape(-1, 5), targets_t.reshape(-1), reduction='none')
mask_t = torch.tensor(mask.reshape(-1), dtype=DTYPE)
torch_loss = (losses * mask_t).sum() / mask_t.sum()
torch_loss.backward()
errors = {'states': float(np.max(np.abs(states.detach().numpy() - own_states))),
'last': float(np.max(np.abs(last.detach().numpy()[0] - own_last))),
'loss': abs(float(torch_loss.detach()) - loss),
'E': float(np.max(np.abs(model.embedding.weight.grad.numpy() - grads['E']))),
'Wx': float(np.max(np.abs(model.rnn.weight_ih_l0.grad.numpy().T - grads['Wx']))),
'Wh': float(np.max(np.abs(model.rnn.weight_hh_l0.grad.numpy().T - grads['Wh']))),
'bh_ih': float(np.max(np.abs(model.rnn.bias_ih_l0.grad.numpy() - grads['bh']))),
'bh_hh': float(np.max(np.abs(model.rnn.bias_hh_l0.grad.numpy() - grads['bh']))),
'Wy': float(np.max(np.abs(model.output.weight.grad.numpy().T - grads['Wy']))),
'by': float(np.max(np.abs(model.output.bias.grad.numpy() - grads['by']))),
'h0': float(np.max(np.abs(initial.grad.numpy()[0] - dh0)))}
if max(errors.values()) > 1e-10:
raise AssertionError(('Paridad incorrecta', errors))
return errors
@torch.inference_mode()
def evaluate(model, data, block):
model.eval()
state = torch.zeros((1, 1, model.rnn.hidden_size), dtype=DTYPE)
total, count = 0., 0
# Estado preservado entre bloques contiguos dentro de la misma secuencia.
inputs, targets = sequence_events(data, model.output.out_features, 1)
for start in range(0, len(inputs), block):
end = min(len(inputs), start + block)
x = torch.tensor(inputs[start:end][None, :])
y = torch.tensor(targets[start:end][None, :])
logits, _, state = model(x, state)
total += float(F.cross_entropy(logits.reshape(-1, logits.shape[-1]),
y.reshape(-1), reduction='sum'))
count += y.numel()
if not count:
raise ValueError('Faltan eventos de evaluación')
return {'events': count, 'mean_nats': total / count, 'ppl': math.exp(total / count)}
def reader_texts():
train_path, valid_path = os.environ.get('ORYON_TRAIN_FILE'), os.environ.get('ORYON_VALID_FILE')
if bool(train_path) != bool(valid_path):
raise ValueError('Suministra ambos archivos UTF-8, o ninguno')
if train_path:
return Path(train_path).read_text(encoding='utf-8'), Path(valid_path).read_text(encoding='utf-8')
return TRAIN_TEXT, VALID_TEXT
def main_torch():
train_text, valid_text = reader_texts()
vocab, train, valid = prepare(train_text, valid_text)
train_inputs, train_targets = sequence_events(train, len(vocab), vocab.index(EOS))
window = min(WINDOW, len(train_inputs))
p = initial_params(len(vocab), embed=16, hidden=32, seed=SEED)
model = TorchCharRNN(p)
optimizer = torch.optim.Adam(model.parameters(), lr=.003)
rng = np.random.default_rng(SEED)
history = []
print('Paridad NumPy/PyTorch:', verify_parity())
print('Gradcheck propio:', gradcheck())
sampler_check()
for step in range(STEPS + 1):
if step in (0, STEPS):
history.append({'step': step, 'validation': evaluate(model, valid, 64)})
if step == STEPS:
break
starts = rng.integers(0, len(train_inputs) - window + 1, size=BATCH)
x = torch.tensor(np.stack([train_inputs[start:start + window] for start in starts]))
y = torch.tensor(np.stack([train_targets[start:start + window] for start in starts]))
h0 = torch.zeros((1, BATCH, model.rnn.hidden_size), dtype=DTYPE)
model.train()
optimizer.zero_grad(set_to_none=True)
logits, _, _ = model(x, h0)
loss = F.cross_entropy(logits.reshape(-1, len(vocab)), y.reshape(-1))
if not torch.isfinite(loss):
raise ValueError('Pérdida no finita')
loss.backward()
if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in model.parameters()):
raise ValueError('Gradiente no finito')
optimizer.step()
exported = torch_to_numpy(model)
text, distribution, termination = sample(exported, vocab, 'en ', 40, SEED + 1)
result = {'short': SHORT, 'steps': STEPS, 'batch': BATCH, 'window': window, 'seed': SEED,
'torch': torch.__version__, 'device': 'cpu', 'tokens_train': len(train),
'tokens_valid': len(valid), 'valid_unknown': int(np.sum(valid == 0)),
'sha256_train': hashlib.sha256(train_text.encode('utf-8')).hexdigest(),
'sha256_valid': hashlib.sha256(valid_text.encode('utf-8')).hexdigest(),
'history': history, 'sample': text, 'next_distribution': distribution, 'termination': termination,
'limitations': 'Muestras aleatorias independientes con estado cero; validación continua '
'por bloques desde cero y con EOS. UNK no tiene objetivos positivos '
'en entrenamiento. Texto reservado exploratorio; no asegura convergencia.'}
OUT.mkdir(parents=True, exist_ok=True)
(OUT / 'metrics.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
(OUT / 'model.json').write_text(json.dumps({'vocab': vocab, 'bos_index': len(vocab),
'eos_index': vocab.index(EOS),
'params': {k: v.tolist() for k, v in exported.items()}},
ensure_ascii=False), encoding='utf-8')
print('Resultado:', result)
print('Datos y pesos:', OUT)
print('batch_first modifica entradas/salidas, no la forma de h0=(capas × direcciones,B,H).')
if __name__ == '__main__':
main_torch()npm run lab and open the connection link.Exercises
Step 1 of 3. How is complete sequence probability obtained?
import numpy as np
def generate(params, seed, n, rng):
passFurther connections
Recurrence connects with dynamical systems and autoregressive factorization studied earlier. Next we examine what happens when derivatives propagate through many states and why other recurrent cells incorporate memory-control mechanisms.