Deep and bidirectional RNNs and contextual embeddings
Explore stacked and bidirectional recurrent networks, causal context, ELMo-style contextual representations, and language-model pretraining and transfer.
After this lesson you can
- Implement stacked and bidirectional RNNs and reason about their dependency fields.
- Identify tasks where bidirectional context is valid and detect generation leakage.
- Combine biLM layers with learned ELMo-style weights for contextual embeddings.
- Pretrain an LSTM language model and fine-tune it for classification following ULMFiT.
- Compare static and contextual embeddings on disambiguation.
Before you start
Depth and context are different decisions
An LSTM processes a sequence with parameters shared across time. We can add depth by having another recurrence consume its states; we can also process the sequence in both directions. The first decision adds transformations per position. The second adds future information, useful for labeling a complete sentence but incompatible with some causal uses.
The graph shows possible paths, not guaranteed numerical influence: a weight can be zero or a gate can block a path. The displayed length counts graph edges, not gradient magnitude.
Multiple recurrent layers
In a stacked RNN, the bottom layer receives and each higher layer consumes the previous one’s output at the same position:
There is temporal depth through the state chain and vertical depth through layers applied at each step. Each layer has its own parameters shared over time. A residual connection can add to layer ‘s output if dimensions match; otherwise it needs an explicit projection. The extra path does not guarantee total-gradient stability.
Dropout between layers regularizes vertical signals. Specify whether the mask changes over time or is shared across steps: these are different procedures. In PyTorch the dropout argument of a stacked RNN acts between layers and adds no dropout after the last; with one layer it creates no intermediate connection. The exact recipe and evaluation mode matter.
Reading from the right too
A bidirectional RNN runs a forward and a backward recurrence:
For labeling an already available sentence, can collect past and future information. If each state has coordinates, concatenation has ; a higher bidirectional layer receives that full width. Schuster and Paliwal studied this construction for processing sequences in both directions.
A sentence summary needs care. At the last position the forward component has consumed the whole prefix, but the backward component has just started at the final token. To gather both complete traversals use the last forward state and the backward state at the first valid position. Pooling or attention are alternatives; they must exclude padding and specify which positions they aggregate.
When reversing a batch of different lengths, reverse each valid prefix and keep padding on the right. Reversing the entire time dimension makes the backward direction process padding before content. The lab tests zero-length sequences and padding even with nonfinite values; a real task must also define how to represent an empty example.
The future can leak
For left-to-right generation, conditional can use only information available before . A backward state that has seen or later tokens is not a legitimate input to that head. A bidirectional network could learn to ignore the future or receive a causal mask, but this cannot be presumed: if its score depends on a future token, it does not implement that causal conditional.
A biLM trains two separate objectives: the forward model predicts the next token from the prefix and the backward model predicts the previous token from the suffix. Their states can then be combined for a task with the full text available. Multiplying both conditionals without normalization does not automatically produce a left-to-right autoregressive distribution. In speech recognition or simultaneous translation, permitted right context depends on latency and protocol; a BiRNN over the entire input does not itself meet strict streaming requirements.
ELMo: choose a task-specific combination
Contextual embeddings from a biLM assign a representation to each occurrence. Two sentences containing “bank” share the written word but can produce different states. Peters and colleagues combined the context-independent representation and outputs of two bidirectional layers using task-learned weights:
Representations must have compatible dimensions; the contextual layer concatenates both directions. Weights sum to one and scales the whole combination. Their values express a task model’s preference under that training, not proof that a layer contains syntax or semantics exclusively.
The original biLM uses two LSTM layers of 4096 units with 512-dimensional projections, a character-based input representation, and a residual connection between layers. After ten epochs on the billion-word benchmark, the authors reported mean perplexity 39.7 across both directions. In their SQuAD evaluation, single-model F1 rose from 81.1 to 85.8 with ELMo. These figures come from their protocol, not this lesson’s small lab. Their probes suggest layer differences, but interpretation depends on task and evaluation.
A neighbor figure for “bank” requires representations computed by an actual biLM, specified sentences and layer, and reproducible neighbor search. The formula alone does not imply that a short run separates senses or that an upper layer is always more semantic.
The figure uses representations from an actual short lab run. There “bank” is out of vocabulary and shares the UNK input vector in both sentences; the recurrent layers do receive different contexts. This test does not show that the model learned both senses.
Pretrain and transfer
Pretraining and fine-tuning separates learning a self-supervised task from later use of its parameters in another task. Dai and Le studied transfer from language models and sequence autoencoders; CoVe uses an encoder trained for translation. These paths have different objectives and corpora and should not be presented as the same model.
ULMFiT has three stages: pretrain a general language model, adapt it on target-domain text, and fine-tune a classifier. It proposes layer-specific rates, a slanted triangular schedule, and gradual unfreezing from upper layers. The paper reports 4.6% IMDb error under its protocol; that number is not from our run. Aggressive fine-tuning of every layer can erase useful information, but gradual unfreezing does not always improve results: compare under the same budget.
A protocol separates training, validation, and test documents, records duplicates and coverage, and decides whether unlabeled test text participates in pretraining. Consulting test to select rate, epoch, or architecture breaks independence. A linear probe measures what that classifier family can extract from a representation on a dataset and split; it does not by itself identify how a property is encoded.
From chains to trees
A Tree-LSTM changes the graph: a node can receive states from multiple children and use one forget gate per child. Syntactic structure determines which messages combine. It is not a BiLSTM on a different sentence permutation; it opens the way to recurrences over graphs, where edges and aggregation also matter.
Laboratory: reversal and dependencies from scratch
The cell starts from GRU functions in the current Gated recurrent unit. It builds one or two directions in multiple layers, reverses only valid positions, and computes derivatives of each output with respect to each input. Weights are random with a fixed seed and untrained. Structural zeros are tested; a numerical zero does not prove a path absent.
"""BiGRU apilada y gradientes de dependencias, sin datos externos.
Las funciones de celda y backward son la versión vigente de m17-l13.
Ejemplo numérico pequeño con parámetros aleatorios fijados, no entrenados.
"""
import numpy as np
def sigmoid(x):
# Esta forma evita desbordamientos tanto en x muy positivo como negativo.
return np.exp(-np.logaddexp(0.0, -x))
def init_gru(d, h, out, rng):
return {'wx': rng.normal(0, .2, (d, 3*h)),
'wh': rng.normal(0, .2, (h, 3*h)),
'bi': np.zeros(3*h), 'bh': np.zeros(3*h),
'wy': rng.normal(0, .2, (h, out)), 'by': np.zeros(out)}
def gru_step(x, h, p):
xi_r, xi_z, xi_n = np.split(x @ p['wx'] + p['bi'], 3, axis=1)
hh_r, hh_z, hh_n = np.split(h @ p['wh'] + p['bh'], 3, axis=1)
r, z = sigmoid(xi_r + hh_r), sigmoid(xi_z + hh_z)
n = np.tanh(xi_n + r * hh_n)
hn = (1 - z) * n + z * h
return hn, (x, h, r, z, n, hh_n, p)
def gru_step_backward(dh, cache):
x, h, r, z, n, hn, p = cache
dn = dh * (1 - z)
dz = dh * (h - n)
dan = dn * (1 - n*n)
dar = (dan * hn) * r * (1 - r)
daz = dz * z * (1 - z)
di = np.concatenate((dar, daz, dan), axis=1)
dhh = np.concatenate((dar, daz, dan * r), axis=1)
grads = {'wx': x.T @ di, 'wh': h.T @ dhh,
'bi': di.sum(axis=0), 'bh': dhh.sum(axis=0)}
dx = di @ p['wx'].T
dh_previous = dh * z + dhh @ p['wh'].T
return dx, dh_previous, grads
def check_lengths(x, lengths):
if x.ndim != 3 or any(size < 1 for size in x.shape):
raise ValueError('x debe tener forma (T,B,D) con dimensiones positivas')
lens = np.asarray(lengths)
if lens.shape != (x.shape[1],) or not np.issubdtype(lens.dtype, np.integer):
raise ValueError('Se requiere una longitud entera por secuencia')
if np.any(lens < 0) or np.any(lens > len(x)):
raise ValueError('Cada longitud debe estar entre cero y T')
return lens.astype(np.int64)
def reverse_padded(x, lengths):
"""Invierte cada prefijo válido, preservando el relleno en su sitio."""
lens = check_lengths(x, lengths)
result = x.copy()
for b, length in enumerate(lens):
result[:length, b] = x[:length, b][::-1]
return result
def layer_forward(xs, lengths, p, reverse=False):
lens = check_lengths(xs, lengths)
work = reverse_padded(xs, lens) if reverse else xs
batch, hidden = xs.shape[1], p['wh'].shape[0]
h = np.zeros((batch, hidden))
outputs, cache = [], []
for t in range(len(xs)):
active = (t < lens)[:, None]
# Ni el estado ni el producto numérico leen valores de relleno.
safe_x = np.where(active, work[t], 0.)
next_h, step_cache = gru_step(safe_x, h, p)
h = np.where(active, next_h, h)
outputs.append(np.where(active, h, 0.))
cache.append((active, step_cache))
y = np.stack(outputs)
if reverse:
y = reverse_padded(y, lens)
return y, (cache, lens, reverse, p)
def layer_backward(dy, layer_cache):
cache, lens, reverse, p = layer_cache
if reverse:
dy = reverse_padded(dy, lens)
dh = np.zeros((dy.shape[1], p['wh'].shape[0]))
dx = np.zeros((len(dy), dy.shape[1], p['wx'].shape[0]))
for t in range(len(dy) - 1, -1, -1):
active, step_cache = cache[t]
# La salida del padding es cero; el estado pasa intacto a través de él.
dh = dh + np.where(active, dy[t], 0.)
dx[t], through_step, _ = gru_step_backward(np.where(active, dh, 0.), step_cache)
dh = through_step + np.where(active, 0., dh)
if reverse:
dx = reverse_padded(dx, lens)
return dx
def make_network(input_size, hidden, layers, directions, seed):
if layers < 1 or directions not in (1, 2):
raise ValueError('Capas o direcciones inválidas')
rng = np.random.default_rng(seed)
network = []
width = input_size
for _ in range(layers):
# wy/by son la cabeza de l13 y no se utilizan en esta comparación.
forward_params = init_gru(width, hidden, 1, rng)
backward_params = init_gru(width, hidden, 1, rng) if directions == 2 else None
network.append((forward_params, backward_params))
width = hidden * directions
return network
def network_forward(xs, lengths, network, residual=False):
lens = check_lengths(xs, lengths)
active = (np.arange(len(xs))[:, None] < lens[None, :])[:, :, None]
if not np.isfinite(xs[active.repeat(xs.shape[2], axis=2)]).all():
raise ValueError('Los valores válidos deben ser finitos')
h = xs
layers = []
for forward_params, backward_params in network:
incoming = h
left, left_cache = layer_forward(incoming, lens, forward_params)
if backward_params is None:
h, right_cache = left, None
else:
right, right_cache = layer_forward(incoming, lens, backward_params, reverse=True)
h = np.concatenate((left, right), axis=2)
add_skip = bool(residual and incoming.shape[2] == h.shape[2])
if add_skip:
h = h + np.where(active, incoming, 0.)
layers.append((left_cache, right_cache, add_skip))
return h, layers
def network_backward(dy, layers):
grad = dy.copy()
for left, right, skip in reversed(layers):
hidden = left[3]['wh'].shape[0]
if right is None:
bottom = layer_backward(grad, left)
else:
bottom = layer_backward(grad[:, :, :hidden], left)
bottom += layer_backward(grad[:, :, hidden:], right)
if skip:
lens = left[1]
active = (np.arange(len(grad))[:, None] < lens[None, :])[:, :, None]
bottom += np.where(active, grad, 0.)
grad = bottom
return grad
def dependency_map(xs, lengths, network, residual=False):
"""Devuelve ||d y[t,b,k] / d x[s,b,:]|| y comprueba independencia por lote."""
ys, layers = network_forward(xs, lengths, network, residual=residual)
T, B, outputs = ys.shape
result = np.zeros((B, T, outputs, T))
for b in range(B):
for t in range(T):
for k in range(outputs):
upstream = np.zeros_like(ys)
upstream[t, b, k] = 1.
dx = network_backward(upstream, layers)
other = np.arange(B) != b
if not np.allclose(dx[:, other], 0., atol=1e-12):
raise AssertionError('Una secuencia afecta a otra')
result[b, t, k] = np.linalg.norm(dx[:, b], axis=1)
return result
def tests():
rng = np.random.default_rng(17140)
xs = rng.normal(size=(5, 3, 4))
lengths = np.array([5, 3, 0])
flipped = reverse_padded(xs, lengths)
assert np.array_equal(flipped[:, 0], xs[::-1, 0])
assert np.array_equal(flipped[:3, 1], xs[:3, 1][::-1])
assert np.array_equal(flipped[3:, 1], xs[3:, 1])
assert np.array_equal(flipped[:, 2], xs[:, 2])
assert np.array_equal(reverse_padded(flipped, lengths), xs)
for invalid in ([6, 3, 0], [-1, 3, 0], [5., 3., 0.], [5, 3]):
try:
reverse_padded(xs, invalid)
except ValueError:
pass
else:
raise AssertionError('Longitudes inválidas aceptadas')
# El padding puede contener NaN: nunca debe contaminar valores válidos.
xs[3:, 1] = np.nan
xs[:, 2] = np.nan
dy = rng.normal(size=(5, 3, 4))
net = make_network(4, 2, layers=2, directions=2, seed=17141)
output, cache = network_forward(xs, lengths, net, residual=True)
assert np.isfinite(output).all()
assert np.all(output[3:, 1] == 0.) and np.all(output[:, 2] == 0.)
dx = network_backward(dy, cache)
assert np.isfinite(dx).all()
assert np.all(dx[3:, 1] == 0.) and np.all(dx[:, 2] == 0.)
# Diferencias finitas de una pérdida escalar para todos los valores válidos.
def objective():
return float(np.sum(network_forward(xs, lengths, net, residual=True)[0] * dy))
max_error = 0.
for t in range(len(xs)):
for b, length in enumerate(lengths):
if t >= length:
continue
for k in range(xs.shape[2]):
old = xs[t, b, k]; eps = 1e-5
xs[t, b, k] = old + eps; plus = objective()
xs[t, b, k] = old - eps; minus = objective()
xs[t, b, k] = old
max_error = max(max_error, abs((plus - minus) / (2*eps) - dx[t, b, k]))
if not np.isfinite(max_error) or max_error >= 1e-7:
raise AssertionError(('Gradcheck de entradas fallido', max_error))
return xs, lengths, max_error
def main():
xs, lengths, max_error = tests()
print('Inversión por longitud y gradcheck de entradas: error máximo', max_error)
for direction in (1, 2):
model = make_network(4, 2, layers=2, directions=direction, seed=17142)
maps = dependency_map(xs, lengths, model, residual=True)
# Las entradas futuras son imposibles en una red estrictamente causal.
if direction == 1:
for t in range(len(xs)):
assert np.all(maps[:, t, :, t+1:] == 0.)
for b, length in enumerate(lengths):
assert np.all(maps[b, length:] == 0.)
assert np.all(maps[b, :, :, length:] == 0.)
print('Direcciones:', direction, '| mapa secuencia 0, norma por salida y entrada:')
print(np.array2string(maps[0], precision=5, suppress_small=False))
print('Normas máximas por posiciones salida/entrada:',
np.array2string(maps[0].max(axis=1), precision=5, suppress_small=False))
print('Los ceros estructurales se prueban; un cero numérico no demuestra ausencia de camino.')
print('Las dos capas usan parámetros no entrenados. El residual solo actúa cuando coinciden formas.')
print('Las entradas y pesos de este control son explícitos; no representan una red entrenada.')
if __name__ == '__main__':
main()Laboratory: biLM and transfer
The local exercise trains a biLM, extracts layer representations, evaluates a probe on separate labeled data, and compares fine-tuned classification with a model from scratch. Provenance, splits, coverage, seeds, and budget are part of the output. A short run only demonstrates the pipeline and does not justify attributing ELMo or ULMFiT results to the small model.
The example uses WikiText-2 for pretraining, UD EWT for probing, and IMDb reviews for adaptation and classification. Full CoNLL-U tokens do not always match WikiText’s regex; the report counts OOV per split. The comparison combines pretraining and adaptation and does not isolate either effect. Test evaluation is exploratory and does not select checkpoints.
"""Mini biLM, sonda UPOS y transferencia de LM a clasificación.
Datos: WikiText-2 raw (Salesforce), UD English EWT r2.16 e IMDb (Stanford).
Consulta las fichas y condiciones; IMDb no declara licencia concreta. UD
distingue derechos de las anotaciones y de los textos de terceros.
Requiere torch, numpy, pyarrow, scikit-learn y huggingface_hub.
ORYON_VERIFY_SHORT=1 solo verifica el circuito. ORYON_OUTPUT es un directorio.
No es una reproducción de ELMo, AWD-LSTM o ULMFiT.
"""
import copy
import hashlib
import json
import math
import os
import re
import unicodedata
from collections import Counter
from pathlib import Path
from urllib.request import Request, urlopen
import numpy as np
import pyarrow.parquet as pq
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence, pad_sequence
from huggingface_hub import hf_hub_download
from sklearn.model_selection import train_test_split
torch.set_num_threads(1)
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
SEED = 17140
RNG = np.random.default_rng(SEED)
torch.manual_seed(SEED)
OUT = Path(os.environ.get('ORYON_OUTPUT', 'bilm_transfer_output'))
WIKI_REV = 'b08601e04326c79dfdd32d625aee71d232d685c3'
WIKI_FILES = {
'train': ('wikitext-2-raw-v1/train-00000-of-00001.parquet',
'e83889baabc497075506f91975be5fac0d45c5290b6b20582c8cd1e853d0c9f7'),
'validation': ('wikitext-2-raw-v1/validation-00000-of-00001.parquet',
'204929b7ff9d6184953f867dedb860e40aa69c078fc1e54b3baaa8fb28511c4c'),
}
IMDB_REV = 'e6281661ce1c48d982bc483cf8a173c1bbeb5d31'
IMDB_FILES = {
'train': ('plain_text/train-00000-of-00001.parquet',
'db47d16b5c297cc0dd625e519c81319c24c9149e70e8496de5475f6fa928342c'),
'test': ('plain_text/test-00000-of-00001.parquet',
'b52e26e2f872d282ffac460bf9770b25ac6f102cda0e6ca7158df98c94e8b3da'),
}
UD_TAG = 'r2.16' # Etiqueta de publicación, no un hash inmutable.
UD_BASE = 'https://raw.githubusercontent.com/UniversalDependencies/UD_English-EWT/' + UD_TAG
UD_CACHE = Path(os.environ.get('ORYON_UD_CACHE', str(Path.home() / '.cache' / 'oryon' / 'ud-ewt-r2.16')))
TOKEN = re.compile(r"\w+(?:['’]\w+)*|[^\w\s]", re.UNICODE)
PAD, UNK, EOS = '<pad>', '<unk>', '</s>'
DIM = 16 if SHORT else 128
WINDOW = 12 if SHORT else 48
BATCH = 4 if SHORT else 24
LM_STEPS = 4 if SHORT else 4000
DOMAIN_STEPS = 2 if SHORT else 1000
PROBE_EPOCHS = 1 if SHORT else 6
CLASS_EPOCHS = 1 if SHORT else 3
MAX_REVIEW = 48 if SHORT else 256
MAX_UD = 80
CAP = 4000 if SHORT else None
def tokens(text):
text = re.sub(r'<br\s*/?>', ' ', unicodedata.normalize('NFC', text).lower())
return TOKEN.findall(text)
def canonical(text):
return ' '.join(unicodedata.normalize('NFC', text).lower().split())
def digest_bytes(data):
return hashlib.sha256(data).hexdigest()
def hub_file(repo, revision, entry):
filename, expected = entry
path = hf_hub_download(repo_id=repo, repo_type='dataset', revision=revision, filename=filename)
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: ' + filename)
return path
def wiki_data():
out, owners, removed = {}, {}, Counter()
for part in ('train', 'validation'):
path = hub_file('Salesforce/wikitext', WIKI_REV, WIKI_FILES[part])
accepted, count = [], 0
done = False
for batch in pq.ParquetFile(path).iter_batches(batch_size=256, columns=['text']):
for row in batch.column(0).to_pylist():
seq = tokens(row or '')
if not seq:
continue
key = digest_bytes('\0'.join(seq).encode('utf-8'))
if key in owners and owners[key] != part:
removed[part] += 1
continue
if CAP is not None and count >= CAP:
done = True
break
owners.setdefault(key, part)
if CAP is not None:
seq = seq[:max(0, CAP - count)]
accepted.extend(seq + [EOS])
count += len(seq)
if done:
break
if len(accepted) <= WINDOW + 1:
raise ValueError('WikiText contiene demasiado pocos tokens')
out[part] = accepted
counts = Counter(out['train'])
ordered = sorted((w for w in counts if w not in (PAD, UNK, EOS)),
key=lambda w: (-counts[w], w))
vocab = [PAD, UNK, EOS, *ordered[:(3000 if SHORT else 20000) - 3]]
index = {w: i for i, w in enumerate(vocab)}
encoded = {k: torch.tensor([index.get(w, 1) for w in data], dtype=torch.long)
for k, data in out.items()}
return vocab, index, encoded, dict(removed)
def ud_bytes(split):
name = 'en_ewt-ud-' + split + '.conllu'
path = UD_CACHE / name
UD_CACHE.mkdir(parents=True, exist_ok=True)
if not path.exists():
request = Request(UD_BASE + '/' + name, headers={'User-Agent': 'OryonLearn/1.0'})
with urlopen(request, timeout=60) as response:
data = response.read(32 * 1024 * 1024 + 1)
if len(data) > 32 * 1024 * 1024:
raise ValueError('UD supera el límite de tamaño')
# Evita dejar una descarga parcial como caché válida.
if not parse_ud(data.decode('utf-8')):
raise ValueError('La descarga UD no contiene frases válidas')
temporary = path.with_name(path.name + '.' + str(os.getpid()) + '.part')
try:
temporary.write_bytes(data)
os.replace(temporary, path)
finally:
if temporary.exists():
temporary.unlink()
if path.stat().st_size > 32 * 1024 * 1024:
raise ValueError('Archivo UD demasiado grande')
raw = path.read_bytes()
if not raw:
raise ValueError('Archivo UD vacío o demasiado grande')
# El hash identifica el archivo descargado; no autentica una etiqueta mutable.
sha = digest_bytes(raw)
expected = os.environ.get('ORYON_UD_SHA256_' + split.upper())
if expected and sha.lower() != expected.lower():
raise ValueError('SHA-256 de UD inesperado: ' + split)
return raw.decode('utf-8'), sha
def parse_ud(text):
sentences, words, labels = [], [], []
for line in (text + '\n\n').splitlines():
if not line.strip():
if words and len(words) <= MAX_UD:
sentences.append((words, labels))
words, labels = [], []
continue
if line.startswith('#'):
continue
fields = line.split('\t')
if len(fields) != 10:
raise ValueError('Fila CoNLL-U inválida')
# Ignora rangos de palabras múltiples y nodos vacíos.
if not fields[0].isdigit():
continue
if fields[3] == '_':
raise ValueError('Falta UPOS')
words.append(unicodedata.normalize('NFC', fields[1]).lower())
labels.append(fields[3])
return sentences
def ud_data():
result, seen, hashes, removed = {}, set(), {}, Counter()
for split in ('train', 'dev', 'test'):
raw, hashes[split] = ud_bytes(split)
rows = parse_ud(raw)
unique = []
for words, tags in rows:
key = digest_bytes('\0'.join(words).encode('utf-8'))
if key in seen:
removed[split] += 1
continue
seen.add(key)
unique.append((words, tags))
result[split] = unique[:(32 if split == 'train' else 16)] if SHORT else unique
labels = sorted({tag for _, tags in result['train'] for tag in tags})
if not labels or not all(result.values()):
raise ValueError('UD no tiene suficientes ejemplos')
return result, labels, hashes, dict(removed)
def imdb_data():
partitions = {}
for split in ('train', 'test'):
path = hub_file('stanfordnlp/imdb', IMDB_REV, IMDB_FILES[split])
table = pq.read_table(path, columns=['text', 'label'])
text, labels = table.column('text').to_pylist(), table.column('label').to_pylist()
if len(text) != 25000 or len(labels) != 25000:
raise ValueError('Número inesperado de reseñas')
partitions[split] = [(i, canonical(t), int(y)) for i, (t, y) in enumerate(zip(text, labels))]
# Conflictos resueltos dentro de cada partición; train no usa etiquetas test.
groups = {}
for split in ('train', 'test'):
groups[split] = {}
for _, text, label in partitions[split]:
groups[split].setdefault(text, set()).add(label)
removed, clean = Counter(), {}
for split in ('train', 'test'):
seen, rows = set(), []
for i, text, label in partitions[split]:
if split == 'test' and text in groups['train']:
removed['test_in_original_train'] += 1
elif len(groups[split][text]) != 1:
removed[split + '_conflict'] += 1
elif text in seen:
removed[split + '_duplicate'] += 1
else:
seen.add(text)
rows.append((i, text, label))
clean[split] = rows
train, val = train_test_split(clean['train'], test_size=.2, random_state=SEED,
stratify=[row[2] for row in clean['train']])
if SHORT:
train, _ = train_test_split(train, train_size=32, random_state=SEED,
stratify=[row[2] for row in train])
val, _ = train_test_split(val, train_size=16, random_state=SEED + 1,
stratify=[row[2] for row in val])
clean['test'], _ = train_test_split(clean['test'], train_size=16, random_state=SEED + 2,
stratify=[row[2] for row in clean['test']])
return {'train': train, 'dev': val, 'test': clean['test']}, dict(removed)
def sample_windows(data, rng):
starts = rng.integers(0, len(data) - WINDOW, size=BATCH)
ids = torch.from_numpy(starts[:, None] + np.arange(WINDOW)[None, :])
return data[ids].to(DEVICE)
def reverse_valid(x, lengths):
steps = torch.arange(x.shape[1], device=x.device)[None, :]
idx = torch.where(steps < lengths[:, None], lengths[:, None] - 1 - steps, steps)
return x.gather(1, idx.unsqueeze(-1).expand_as(x))
class MiniBiLM(nn.Module):
def __init__(self, vocabulary_size):
super().__init__()
self.embedding = nn.Embedding(vocabulary_size, DIM, padding_idx=0)
self.f1, self.f2 = nn.LSTM(DIM, DIM, batch_first=True), nn.LSTM(DIM, DIM, batch_first=True)
self.b1, self.b2 = nn.LSTM(DIM, DIM, batch_first=True), nn.LSTM(DIM, DIM, batch_first=True)
self.fhead, self.bhead = nn.Linear(DIM, vocabulary_size), nn.Linear(DIM, vocabulary_size)
@staticmethod
def layer(lstm, x, lengths):
packed = pack_padded_sequence(x, lengths.cpu(), batch_first=True, enforce_sorted=False)
output, _ = lstm(packed)
return pad_packed_sequence(output, batch_first=True, total_length=x.shape[1])[0]
def representations(self, ids, lengths):
e = self.embedding(ids)
f1 = self.layer(self.f1, e, lengths)
f2 = self.layer(self.f2, f1, lengths)
reverse = reverse_valid(e, lengths)
b1 = self.layer(self.b1, reverse, lengths)
b2 = self.layer(self.b2, b1, lengths)
b1, b2 = reverse_valid(b1, lengths), reverse_valid(b2, lengths)
return [torch.cat((e, e), -1), torch.cat((f1, b1), -1), torch.cat((f2, b2), -1)]
def lm_loss(self, ids):
# Los logits en t predicen el token vecino, no el propio.
lengths = torch.full((len(ids),), ids.shape[1], dtype=torch.long, device=ids.device)
reps = self.representations(ids, lengths)[-1]
fwd, bwd = reps.split(DIM, dim=-1)
fscore, bscore = self.fhead(fwd[:, :-1]), self.bhead(bwd[:, 1:])
return (F.cross_entropy(fscore.reshape(-1, fscore.shape[-1]), ids[:, 1:].reshape(-1)) +
F.cross_entropy(bscore.reshape(-1, bscore.shape[-1]), ids[:, :-1].reshape(-1))) / 2
def train_bilm(vocab, wiki):
model = MiniBiLM(len(vocab)).to(DEVICE)
optimizer = torch.optim.Adam(model.parameters(), lr=.002)
rng = np.random.default_rng(SEED + 1)
history, best, saved = [], math.inf, None
interval = max(1, LM_STEPS // 5)
for step in range(1, LM_STEPS + 1):
model.train()
batch = sample_windows(wiki['train'], rng)
optimizer.zero_grad(set_to_none=True)
loss = model.lm_loss(batch)
if not torch.isfinite(loss):
raise ValueError('Pérdida biLM no finita')
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1., error_if_nonfinite=True)
optimizer.step()
if step == 1 or step % interval == 0 or step == LM_STEPS:
model.eval()
# Mismo lote de validación para cada checkpoint.
with torch.no_grad():
valid = float(model.lm_loss(sample_windows(wiki['validation'],
np.random.default_rng(SEED + 2))))
if not math.isfinite(valid):
raise ValueError('Validación biLM no finita')
history.append({'step': step, 'validation_nats': valid})
if valid < best:
best = valid
saved = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
model.load_state_dict(saved)
return model, history
def pos_batch(rows, index, labels):
lx = {name: i for i, name in enumerate(labels)}
x = [torch.tensor([index.get(w, 1) for w in words], dtype=torch.long) for words, _ in rows]
y = [torch.tensor([lx.get(tag, -100) for tag in tags], dtype=torch.long) for _, tags in rows]
lengths = torch.tensor([len(v) for v in x], device=DEVICE)
return (pad_sequence(x, batch_first=True, padding_value=0).to(DEVICE),
pad_sequence(y, batch_first=True, padding_value=-100).to(DEVICE), lengths)
class Probe(nn.Module):
def __init__(self, count, mix):
super().__init__()
self.mix = mix
self.logits = nn.Parameter(torch.zeros(3)) if mix else None
self.scale = nn.Parameter(torch.ones(())) if mix else None
self.head = nn.Linear(2 * DIM, count)
def forward(self, reps):
if self.mix:
weights = self.logits.softmax(0)
value = self.scale * sum(weights[i] * reps[i] for i in range(3))
else:
value = reps[0]
return self.head(value)
def probe_eval(encoder, probe, rows, index, labels):
encoder.eval(); probe.eval()
correct = covered = total = 0
with torch.inference_mode():
for start in range(0, len(rows), 16):
x, y, lengths = pos_batch(rows[start:start+16], index, labels)
scores = probe(encoder.representations(x, lengths))
# Diferencia padding de etiquetas que no aparecen en train.
valid_tokens = torch.arange(y.shape[1], device=DEVICE)[None, :] < lengths[:, None]
known = valid_tokens & (y != -100)
correct += int(((scores.argmax(-1) == y) & known).sum())
covered += int(known.sum()); total += int(valid_tokens.sum())
if covered == 0:
raise ValueError('No hay etiquetas UPOS conocidas en evaluación')
return {'accuracy_known': correct / covered, 'covered': covered, 'tokens': total}
def train_probe(encoder, rows, index, labels, mix):
torch.manual_seed(SEED + 10)
encoder.eval()
for p in encoder.parameters():
p.requires_grad_(False)
probe = Probe(len(labels), mix).to(DEVICE)
opt = torch.optim.Adam(probe.parameters(), lr=.01)
rng = np.random.default_rng(SEED + 11)
best, state, history = -1., None, []
for epoch in range(PROBE_EPOCHS):
order = rng.permutation(len(rows['train']))
for start in range(0, len(order), 16):
selected = [rows['train'][i] for i in order[start:start+16]]
x, y, lengths = pos_batch(selected, index, labels)
with torch.no_grad():
reps = encoder.representations(x, lengths)
opt.zero_grad(set_to_none=True)
scores = probe(reps)
loss = F.cross_entropy(scores.reshape(-1, len(labels)), y.reshape(-1), ignore_index=-100)
if not torch.isfinite(loss):
raise ValueError('Pérdida de sonda no finita')
loss.backward()
opt.step()
val = probe_eval(encoder, probe, rows['dev'], index, labels)
history.append({'epoch': epoch + 1, 'validation': val})
if val['accuracy_known'] > best:
best = val['accuracy_known']
state = {k: v.detach().cpu().clone() for k, v in probe.state_dict().items()}
probe.load_state_dict(state)
result = {'kind': 'mezcla entrenada' if mix else 'entrada estática',
'validation': history, 'test_exploratorio': probe_eval(encoder, probe, rows['test'], index, labels),
'layer_weights': probe.logits.softmax(0).detach().cpu().tolist() if mix else [1., 0., 0.]}
return result
def review_batches(rows, index, batch_size, rng=None):
order = np.arange(len(rows)) if rng is None else rng.permutation(len(rows))
for start in range(0, len(order), batch_size):
chosen = [rows[i] for i in order[start:start+batch_size]]
sequences = [torch.tensor([index.get(w, 1) for w in tokens(text)[:MAX_REVIEW]] or [1],
dtype=torch.long) for _, text, _ in chosen]
lengths = torch.tensor([len(s) for s in sequences], device=DEVICE)
x = pad_sequence(sequences, batch_first=True, padding_value=0).to(DEVICE)
y = torch.tensor([label for _, _, label in chosen], device=DEVICE)
yield x, y, lengths
class ReviewHead(nn.Module):
def __init__(self, encoder):
super().__init__()
self.encoder = encoder
self.head = nn.Linear(3 * DIM, 2)
def forward(self, ids, lengths):
e = self.encoder.embedding(ids)
h1 = self.encoder.layer(self.encoder.f1, e, lengths)
h2 = self.encoder.layer(self.encoder.f2, h1, lengths)
valid = torch.arange(h2.shape[1], device=DEVICE)[None, :] < lengths[:, None]
last = h2[torch.arange(len(ids), device=DEVICE), lengths - 1]
mean = (h2 * valid.unsqueeze(-1)).sum(1) / lengths[:, None]
maximum = h2.masked_fill(~valid.unsqueeze(-1), -torch.inf).max(1).values
return self.head(torch.cat((last, mean, maximum), dim=1))
@torch.inference_mode()
def review_eval(model, rows, index):
model.eval()
correct = count = loss_sum = 0
for x, y, lengths in review_batches(rows, index, 16):
scores = model(x, lengths)
loss_sum += float(F.cross_entropy(scores, y, reduction='sum'))
correct += int((scores.argmax(-1) == y).sum())
count += len(y)
if count == 0 or not math.isfinite(loss_sum):
raise ValueError('Evaluación IMDb vacía o no finita')
return {'accuracy': correct / count, 'loss': loss_sum / count, 'n': count}
def domain_adapt(encoder, train, index):
# Solo reseñas del train de clasificación, sin usar sus etiquetas.
encoder.train()
data = []
for _, text, _ in train:
data.extend(index.get(w, 1) for w in tokens(text)[:MAX_REVIEW])
data.append(index[EOS])
data = torch.tensor(data, dtype=torch.long)
if len(data) <= WINDOW:
raise ValueError('Faltan tokens para adaptación al dominio')
active = list(encoder.embedding.parameters()) + list(encoder.f1.parameters()) + \
list(encoder.f2.parameters()) + list(encoder.fhead.parameters())
for p in encoder.parameters():
p.requires_grad_(False)
for p in active:
p.requires_grad_(True)
opt = torch.optim.Adam(active, lr=.001)
rng = np.random.default_rng(SEED + 30)
for _ in range(DOMAIN_STEPS):
ids = sample_windows(data, rng)
e = encoder.embedding(ids)
f1, _ = encoder.f1(e); f2, _ = encoder.f2(f1)
scores = encoder.fhead(f2[:, :-1])
loss = F.cross_entropy(scores.reshape(-1, scores.shape[-1]), ids[:, 1:].reshape(-1))
if not torch.isfinite(loss):
raise ValueError('Pérdida de adaptación no finita')
opt.zero_grad(set_to_none=True); loss.backward()
nn.utils.clip_grad_norm_(active, 1., error_if_nonfinite=True); opt.step()
def train_classifier(initial_encoder, reviews, index):
# Tres fases: cabeza, capa recurrente superior, todas las capas forward.
encoder = copy.deepcopy(initial_encoder)
torch.manual_seed(SEED + 40)
model = ReviewHead(encoder).to(DEVICE)
best, saved, history = -1., None, []
for phase in range(3):
for p in model.encoder.parameters():
p.requires_grad_(False)
if phase >= 1:
for p in model.encoder.f2.parameters():
p.requires_grad_(True)
if phase >= 2:
for module in (model.encoder.embedding, model.encoder.f1):
for p in module.parameters():
p.requires_grad_(True)
groups = [{'params': model.head.parameters(), 'lr': .003}]
if phase >= 1:
groups.append({'params': model.encoder.f2.parameters(), 'lr': .001})
if phase >= 2:
groups.append({'params': model.encoder.f1.parameters(), 'lr': .0005})
groups.append({'params': model.encoder.embedding.parameters(), 'lr': .0003})
opt = torch.optim.Adam(groups)
for epoch in range(CLASS_EPOCHS):
model.train()
rng = np.random.default_rng(SEED + 50 + phase * 10 + epoch)
for x, y, lengths in review_batches(reviews['train'], index, 16, rng):
opt.zero_grad(set_to_none=True)
logits = model(x, lengths)
loss = F.cross_entropy(logits, y)
if not torch.isfinite(loss):
raise ValueError('Pérdida del clasificador no finita')
loss.backward()
nn.utils.clip_grad_norm_([p for p in model.parameters() if p.requires_grad],
1., error_if_nonfinite=True)
opt.step()
val = review_eval(model, reviews['dev'], index)
history.append({'phase': phase, 'epoch': epoch + 1, 'validation': val})
if val['accuracy'] > best:
best = val['accuracy']
saved = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
model.load_state_dict(saved)
return {'history': history, 'test_exploratorio': review_eval(model, reviews['test'], index)}
def context_examples(encoder, index):
# Frases de demostración definidas aquí; las activaciones salen del modelo.
examples = [['the', 'bank', 'approved', 'the', 'loan'],
['she', 'sat', 'on', 'the', 'bank', 'of', 'the', 'river']]
result = []
encoder.eval()
with torch.inference_mode():
for words in examples:
ids = torch.tensor([[index.get(w, 1) for w in words]], device=DEVICE)
lengths = torch.tensor([len(words)], device=DEVICE)
reps = encoder.representations(ids, lengths)
at = words.index('bank')
result.append({'words': words, 'position': at, 'bank_oov': index.get('bank', 1) == 1,
'token_oov': [index.get(word, 1) == 1 for word in words],
'layers': [v[0, at].cpu().tolist() for v in reps],
'token_layers': [[v[0, i].cpu().tolist() for v in reps]
for i in range(len(words))]})
return result
def main():
OUT.mkdir(parents=True, exist_ok=True)
vocab, index, wiki, wiki_removed = wiki_data()
ud, labels, ud_hashes, ud_removed = ud_data()
imdb, imdb_removed = imdb_data()
encoder, lm_history = train_bilm(vocab, wiki)
probes = [train_probe(encoder, ud, index, labels, False),
train_probe(encoder, ud, index, labels, True)]
contexts = context_examples(encoder, index)
pretrained = copy.deepcopy(encoder)
domain_adapt(pretrained, imdb['train'], index)
torch.manual_seed(SEED)
scratch = MiniBiLM(len(vocab)).to(DEVICE)
classifiers = {'pretrained_and_domain_adapted': train_classifier(pretrained, imdb, index),
'random_initialization': train_classifier(scratch, imdb, index)}
payload = {
'short': SHORT, 'device': str(DEVICE), 'seed': SEED, 'torch': torch.__version__,
'wiki_revision': WIKI_REV, 'wiki_sha256': WIKI_FILES,
'wiki_cross_split_duplicates_removed': wiki_removed,
'ud_release_tag': UD_TAG, 'ud_sha256_calculated': ud_hashes,
'ud_sha256_external_verified': {k: bool(os.environ.get('ORYON_UD_SHA256_' + k.upper()))
for k in ud_hashes},
'ud_duplicates_removed': ud_removed, 'ud_counts': {k: len(v) for k, v in ud.items()},
'ud_oov_tokens': {k: sum(index.get(word, 1) == 1 for words, _ in rows for word in words)
for k, rows in ud.items()},
'imdb_revision': IMDB_REV, 'imdb_sha256': IMDB_FILES, 'imdb_duplicates_removed': imdb_removed,
'imdb_counts': {k: len(v) for k, v in imdb.items()}, 'vocab_size': len(vocab),
'labels_train': labels, 'bilm_validation': lm_history, 'probes': probes,
'classifiers': classifiers, 'context_examples': contexts,
'limitations': [
'UD tag se identifica por hash calculado; no es una verificación independiente.',
'WikiText excluye duplicados exactos entre particiones; UD e IMDb deduplican dentro y entre particiones. '
'No se detectan coincidencias parciales.',
'No se ha descartado solapamiento entre el preentrenamiento WikiText y corpus posteriores.',
'UD usa tokens CoNLL-U completos y WikiText usa una regex: signos y contracciones '
'pueden ser OOV aunque alguna pieza esté en vocabulario.',
'Comparaciones de test son exploratorias; no se eligen checkpoints con test.',
'Modelo pequeño sin caracteres, proyecciones, AWD-LSTM, STLR ni optimización original de ELMo o ULMFiT.',
'IMDb no aclara licencia; UD distingue derechos de anotaciones y textos.',
]}
(OUT / 'metrics.json').write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding='utf-8')
torch.save({'vocab': vocab, 'model': encoder.state_dict()}, OUT / 'bilm.pt')
print(json.dumps(payload, ensure_ascii=False, indent=2))
print('Salida:', OUT, '| SHORT no demuestra convergencia ni superioridad.')
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
Step 1 of 3. Which state does the backward recurrence receive directly at t?
import numpy as np
def reverse_padded(x, lengths):
passFurther reading
The distinction between encoding a complete input and generating token by token reappears in attention models. Contextual representations contrast with Polysemy and the limit of static embeddings; propagation over trees connects to graph models.