Module contents
Lesson 9 of 24Core 100 min

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

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 BB sequences, embeddings of dimension dd and state of dimension HH:

Xt∈RB×d,Ht−1∈RB×H,Ht=tanh⁡(XtWx+Ht−1Wh+b),Zt=HtWy+c.\begin{aligned} X_t&\in\mathbb{R}^{B\times d},& H_{t-1}&\in\mathbb{R}^{B\times H},\\ H_t&=\tanh(X_t W_x+H_{t-1}W_h+b),& Z_t&=H_tW_y+c. \end{aligned}

Shapes are Wx∈Rd×HW_x\in\mathbb{R}^{d\times H}, Wh∈RH×HW_h\in\mathbb{R}^{H\times H}, b∈RHb\in\mathbb{R}^{H}, Wy∈RH×VW_y\in\mathbb{R}^{H\times V} and c∈RVc\in\mathbb{R}^{V}. Biases broadcast across the batch; ZtZ_t contains logits, not probabilities until softmax is applied. The complete input sequence has shape (B,T,d)(B,T,d) and logits (B,T,V)(B,T,V).

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 WxW_x, WhW_h and bb 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.

InteractiveThe same cell in four steps

A scalar teaching model, without training or measured data. Each character maps to a fixed input: a → 1, b → 0, and c → −1. Set h₀ = 0 and compute hₜ = tanh(w xₜ + u hₜ₋₁ + b). All four copies use exactly the same w, u, and b.

x1=1w,u,bx2=0w,u,bx3=-1w,u,bx4=1w,u,bh₀0.000h₁0.716h₂0.538h₃−0.313h₄0.592

Step 2: tanh(0.80 · 0 + 0.70 · 0.7163 + 0.10) = 0.5381. The value inside tanh, without rounding intermediate states, is 0.6014.

h₀
0.000
h₁
0.716
h₂
0.538
h₃
−0.313
h₄
0.592

Heat map: color distinguishes negative and nonnegative values; intensity increases with absolute value. The numbers retain their signs.

Calculation per step, with shared parameters
StepInput xₜPrevious statezₜState hₜ
110.00000.90000.7163
200.71630.60140.5381
3-10.5381−0.3234−0.3125
41−0.31250.68120.5923

Numbers are rounded for display, but each transition uses the full computed state. The graph repeats the operation; it does not create new parameters at each step.

0.8
0.7
0.1
2
Selected stateh₂ = 0.5381
Input at this step0
Before tanh0.6014
Choose inputs and modify shared parameters to see state evolution.

State can be studied as a dynamical system driven by input. As an example only, consider a two-dimensional state and recurrent matrix Wh=rR(θ)W_h=rR(\theta), with r≥0r\geq0 and RR a rotation. For two initial states under the same inputs and bias, ∥ht−ht′∥2≤rt∥h0−h0′∥2\|h_t-h'_t\|_2\leq r^t\|h_0-h'_0\|_2: tanh⁡\tanh is 1-Lipschitz and ∥R∥2=1\|R\|_2=1. If 0≤r<10\leq r<1, distance tends to zero at at least that rate. r>1r>1 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.

InteractiveTrajectories and state sensitivity

Explicit model: A = rR(θ), h₀ = (0.300, 0.100). At each step, z = A h + (input, 0); compare h = z with h = tanh(z). The pulse acts only at t=1 and the step at every time. Noise is uniform between negative amplitude and amplitude, with fixed seed 17090 and the same sample for both trajectories. Bias is zero.

0.570020
Linear With tanhVertical axis: ln(1 + ||h||₂)
xy

State plane: both axes share a scale adjusted to the largest absolute coordinate across both trajectories (1.000). A very large linear trajectory can compress the tanh trajectory near the origin.

Step 8: linear state norm 0.3685, with tanh 0.2424. The accumulated linear norm with respect to h₀ is rᵗ = 0.4305.

For tanh, Jₜ = diag(1 − hₜ²) A. The spectral norm of the local Jacobian and of the product Jₜ ··· J₁, in that order, are computed along this trajectory; at t=0 the empty product is the identity. These are infinitesimal state sensitivities, not losses or gradients of a trained model.

If r<1, the transition is contractive in Euclidean norm for two states with the same input. If r>1, the linear system may grow and tanh may saturate, but neither necessarily happens on every trajectory: try zero initial state and zero input. The logarithmic vertical scale is ln(1+norm), not the norm itself.

0.9
45
0.3
0.1
Scalar input
0.6
8
Linear state(0.332, −0.160)
Tanh state(0.221, −0.100)
Local tanh Jacobian norm0.8911
Accumulated tanh Jacobian norm0.2902
Compare a linear recurrence and the same transition with tanh, using explicit inputs and parameters.

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 WhW_h and bb. For classification use the last real token’s state, stop updating at padded positions or use packed sequences.

InteractiveWhere does the loss go?

Symbolic diagram: nodes represent the same shared recurrent transition. Colors show where there is a target and are not outputs from a trained network.

InputStateOutputTargett=1x1h1nonenonem=0t=2x2h2nonenonem=0t=3x3h3ŷclassm=1t=4PADh4nonenonem=0t=5PADh5nonenonem=0
Inputs and supervision in detail
StepInputOutputTargetLoss mask
1x1nonenone0
2x2nonenone0
3x3ŷclass1
4PADnonenone0
5PADnonenone0

The classification head is applied only to h3, the last valid state.

PAD positions contribute no loss. The loss mask alone does not freeze the state: to recover the last valid state, save it or prevent padding transitions. Outputs and decisions are symbolic.

Task
3
Valid steps3
Loss terms1
Initial stateSet to zero
Compare which steps have input, output and supervision in four tasks.

Predict the next character

For a recurrent language model, fix an embedding table, start symbol BOS and end symbol EOS. If content characters are x1,…,xTx_1,\ldots,x_T, a consistent convention is to feed

[BOS,x1,…,xT]⟶[x1,x2,…,xT,EOS].[\text{BOS},x_1,\ldots,x_T] \quad\longrightarrow\quad [x_1,x_2,\ldots,x_T,\text{EOS}].

Each state after an input produces logits for its corresponding target. In particular, state after BOS predicts x1x_1 and state after xTx_T 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

pθ(x1:T,EOS)=∏t=1T+1pθ(xt∣x<t),L=−1M∑b,tmbtlog⁡pθ(xbt∣xb,<t),p_\theta(x_{1:T},\text{EOS})=\prod_{t=1}^{T+1}p_\theta(x_t\mid x_{<t}), \qquad L=-\frac{1}{M}\sum_{b,t}m_{bt}\log p_\theta(x_{bt}\mid x_{b,<t}),

where xT+1=EOSx_{T+1}=\text{EOS}, mbtm_{bt} is one for each real target including EOS and zero only for padding; M=∑mbt>0M=\sum m_{bt}>0. With fixed data and mask, dividing total log-likelihood by MM multiplies it by a positive constant: minimizing LL 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 exp⁡(L)\exp(L) 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.

InteractiveInside a char-RNN

Weights exported by the short local lab run on an excerpt of Don Quijote: 100 updates out of 800 in the full configuration. This tiny sample does not demonstrate linguistic quality. The distribution is computed in the browser using those weights.

Prefix: en␠
Generated: No characters yet

Next-symbol probabilities before the next action. The eight most likely are shown, as well as the selected symbol if it is not among them.

d23.02 %
␠ space16.75 %
l12.25 %
m8.66 %
n7.07 %
r6.25 %
c3.78 %
g3.14 %
UNK · selected0.45 %

Bars are scaled relative to the highest probability; percentages use the whole vocabulary, including EOS and UNK. The later probability concerns emitting the same symbol again, not whether the previous choice was correct. UNK represents any unknown character and is shown as �; ␠ makes spaces visible. The prefix is normalized to NFC and lowercase; the generator uses kit seed 17091 which differs from NumPy’s. The limit of 60 emissions is not EOS.

Emitted0 of 60
Unknown prefix characters0
StatusRunning
Sample or force a character and observe the distribution calculated from recurrent state.

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 (B,T,d)(B,T,d). In one unidirectional layer, output has shape (B,T,H)(B,T,H) and h_n shape (1,B,H)(1,B,H). batch_first does not change state-dimension order. The RNN returns states; character prediction still needs a linear layer to VV logits.

PyTorch stores input and recurrent matrices as (H,d)(H,d) and (H,H)(H,H) 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 bb. 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.

[ ]Character RNN from scratchBrowser
"""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.

[ ]Correspondence with nn.RNNLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericCount a cell and its output
A unidirectional RNN uses V=65 symbols in both input table and output, embeddings of dimension 32, state 128, one recurrent bias and an output layer with bias. There are no tied weights or initial-h parameters. How many parameters does it have?
NumericExactly equal logits
For 65 output classes and exactly equal logits on every valid event, what is mean loss per token in nats?
ProofFrom conditionals to likelihood
Prove: Show that minimizing mean per-token loss with teacher forcing maximizes dataset likelihood under the stated assumptions.
0
Sequences, masks and M>0 are fixed; every real target including EOS is scored and only padding omitted. Each term is conditioned on the observed prefix.

Step 1 of 3. How is complete sequence probability obtained?

QuizChoose a head
A network receives a variable-length review and must predict one sentiment label. Which configuration is coherent?
QuizMore steps than in training
What can temporal sharing in an RNN trained on short sequences establish?
CodeConsume the prefix and feed back
Implement generate(params, seed, n, rng). params contains E of shape (V+1,d), Wx (d,H), Wh (H,H), bh (H,), Wy (H,V) and by (V,). BOS is input row V and EOS output index V−1. seed is a list of content indices between 0 and V−2; n is the maximum number of new tokens. Start at h=0, consume BOS and then each seed index in order. At each step calculate stable softmax, sample with rng.choice(V,p=probabilities), stop on EOS and otherwise append the index and process it to update h. Return only the list of new indices without EOS. Do not modify parameters or seed; n=0 returns an empty list.
import numpy as np

def generate(params, seed, n, rng):
  pass
Shift+Enter to run

Further 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.