Sequence labeling and alignments: BiLSTM-CRF and CTC
Model structured sequence labels with BiLSTM-CRF and marginalize monotonic alignments with CTC, including dynamic programs, gradients, and evaluation.
After this lesson you can
- Formulate named-entity recognition with BIO labels and entity-level F1.
- Implement sequence scoring, log-space CRF forward, and Viterbi decoding.
- Explain CTC alignment, blank, and collapse.
- Implement CTC forward-backward and check the loss and gradients.
- Discuss CTC conditional independence and decoding consequences.
Before you start
- 17Bidirectional RNNLSTM cellTaxonomy of sequence tasksVariable-length batching: padding, masking and packing
- 14Linear-chain conditional random fieldForward-backward algorithm (smoothing)Viterbi algorithm
- 08Subproblem DAGDynamic programming
- 09Log-sum-exp trick and stable softmax
- 11Confusion matrix and derived metrics
Two structural problems
A labeled sentence has one category per token, but neighboring labels are not independent: “I-PER” after “O” continues no person under strict BIO. Speech poses another difficulty: we do not know which frame corresponds to each letter, and output is usually shorter than input. A linear-chain CRF scores label sequences; CTC sums monotonic alignments compatible with a transcript. They are not two names for the same model.
The graph’s emissions are explicit values in a teaching example, not outputs of a trained BiLSTM. The illustrated prohibition affects only O → I-PER; a strict BIO implementation must also control starts and transitions between types.
Complete entities, not just tokens
In BIO, B-X starts an entity of type X, I-X continues it, and O is outside. BIOES also distinguishes endings E and single-token entities S. Entity recognition is measured by extracting spans and types and requiring both to match exactly: a wrongly bounded entity contributes a false positive and false negative. Token accuracy can be high when O dominates even with poor entity F1. For invalid BIO sequences, document whether they are rejected or repaired and how entities are extracted.
A BiLSTM gives each token a representation dependent on left and right context. A linear layer computes per-label emissions. A character encoder, for example a CNN or per-word character BiLSTM, can add information about shape and suffixes of rare words. Lample and colleagues report entity F1 85.75 on Spanish CoNLL-2002 test for their LSTM-CRF versus 83.44 for the variant without characters; they use pretrained word representations and their own protocol. These are not reduced-lab results.
A distribution over complete sequences
For fixed input of tokens, emissions and transition from previous label to next , the linear CRF over a BiLSTM assigns:
normalizes over admissible sequences. Apply constraints consistently during training and decoding; a forbidden transition has score . If every path is forbidden there is no normalized distribution. Viterbi finds a global maximum, not a sum of probabilities; an unconstrained CRF does not guarantee valid BIO either. Huang and colleagues study BiLSTM plus CRF for labeling.
In the logarithmic semiring, forward computes the sum without enumerating sequences:
The invariant is that is the logarithm of the sum of exponentiated scores of all prefixes ending in . Each of steps combines predecessors for each of labels, costing and memory if only the final value is needed. Replacing LSE by maximum and storing predecessors yields Viterbi; traceback memory grows with . For a padded batch retain actual lengths and include the end at the last valid token.
Alignment without labeling each frame
CTC adds blank to the alphabet. A path has one label per step; collapse first merges adjacent identical symbols and then removes blanks. For example collapses to , whereas collapses to .
Per-step outputs factorize conditioned on the entire input; with a bidirectional encoder each distribution can depend on all that input. The transcript marginalizes paths, and letters are not independent after collapse. For a label of length with adjacent equal pairs, at least steps are needed: each adjacent repetition needs a separating blank. An empty target admits the all-blank path.
The figure uses a fixed toy distribution, not a trained model. A path traverses extended states and may skip intermediate blanks when permitted; target probability is the sum of products over all compatible paths, not the probability of the single best path.
CTC forward, backward, and gradient
The CTC forward–backward algorithm inserts blanks before, between, and after letters to obtain of length . For only the first two states are reachable, or only blank if . Let and be the log sum of paths that have emitted through and end in state . Then:
Omit negative indices and unreachable states, represented by . The result sums the last two states at , except for an empty target, which has one state. For backward, define as the sum of suffixes after , without including the current emission again. Initialize permitted final states with log zero and the rest with ; traverse the same forward edges including the next step’s emission.
If , posterior occupancy of symbol and loss gradient with respect to logits are:
The last equality uses softmax over logits and for a possible target. If no path is valid, loss is infinite and this posterior is undefined; do not divide by zero or present an arbitrary gradient as a derivative. Graves and colleagues present this sum and its dynamic computation.
Decoding and measurement
The best path takes the most probable class at each step and collapses it; it can differ from the most probable transcript because multiple paths can collapse to the same string. Prefix beam search approximates the path sum and can include an external language model. CTC without an external model imposes no grammar, though the encoder can learn regularities from observed inputs and labels. Alignments are monotonic; an attention seq2seq architecture can represent more flexible correspondences, although attention alone does not guarantee correct alignment.
Peaked outputs require actual per-step probabilities, phase, seed, and example. The figure shows a short laboratory run on the same validation sequence before training and after one epoch. Compare blank with a selected digit and observe greedy collapse. This checks the pipeline: results do not establish that the model learned or that peaks appear.
Laboratory: CRF and CTC from scratch
The exercise compares log-space recursions with independent enumeration of small cases and the CTC gradient with finite differences. Impossible alignments and empty labels require an explicit convention.
This lab’s CTC function requires finite, normalized log probabilities. If no alignment exists it returns infinite loss and gradient None; it does not apply zero_infinity.
"""CRF lineal y CTC en NumPy, con enumeración y diferencias finitas.
La matriz de transición CRF usa trans[etiqueta_anterior, etiqueta_actual].
CTC recibe log-probabilidades finitas normalizadas y admite etiquetas repetidas;
el gradiente devuelto es respecto a logits antes de log-softmax.
Los ejemplos son controles matemáticos pequeños, no resultados entrenados.
"""
from itertools import product
import math
import numpy as np
def lse(values):
values = np.asarray(list(values), dtype=np.float64)
return float(np.logaddexp.reduce(values)) if values.size else -math.inf
def log_softmax(logits):
logits = np.asarray(logits, dtype=np.float64)
if logits.ndim != 2 or logits.shape[1] < 2 or not np.isfinite(logits).all():
raise ValueError('Los logits deben ser finitos y tener forma (T,C), C>=2')
if logits.shape[0] == 0:
return logits.copy()
shifted = logits - logits.max(axis=1, keepdims=True)
return shifted - np.log(np.exp(shifted).sum(axis=1, keepdims=True))
def validate_crf(emission, trans, start, end):
emission = np.asarray(emission, dtype=np.float64)
trans, start, end = (np.asarray(v, dtype=np.float64) for v in (trans, start, end))
if emission.ndim != 2 or min(emission.shape) < 1:
raise ValueError('Emisiones deben tener forma (T,K), con T,K>=1')
T, K = emission.shape
if trans.shape != (K, K) or start.shape != (K,) or end.shape != (K,):
raise ValueError('Formas incompatibles de transición, inicio o fin')
for value in (emission, trans, start, end):
if np.isnan(value).any() or np.isposinf(value).any():
raise ValueError('Se admiten valores finitos o -inf, no NaN ni +inf')
return emission, trans, start, end, T, K
def crf_forward_backward(emission, trans, start, end):
e, a, s, f, T, K = validate_crf(emission, trans, start, end)
alpha = np.full((T, K), -np.inf)
alpha[0] = s + e[0]
for t in range(1, T):
for j in range(K):
alpha[t, j] = e[t, j] + lse(alpha[t-1, i] + a[i, j] for i in range(K))
logz = lse(alpha[-1, i] + f[i] for i in range(K))
if not math.isfinite(logz):
raise ValueError('No existe ningún camino CRF admisible')
beta = np.full((T, K), -np.inf)
beta[-1] = f
for t in range(T-2, -1, -1):
for i in range(K):
beta[t, i] = lse(a[i, j] + e[t+1, j] + beta[t+1, j] for j in range(K))
nodes = np.exp(alpha + beta - logz)
edges = np.zeros((max(0, T-1), K, K))
for t in range(1, T):
edges[t-1] = np.exp(alpha[t-1, :, None] + a +
e[t, None, :] + beta[t, None, :] - logz)
return {'log_z': logz, 'alpha': alpha, 'beta': beta,
'nodes': nodes, 'edges': edges}
def crf_log_likelihood(emission, trans, start, end, tags):
e, a, s, f, T, K = validate_crf(emission, trans, start, end)
y = np.asarray(tags)
if y.shape != (T,) or not np.issubdtype(y.dtype, np.integer) or np.any((y < 0) | (y >= K)):
raise ValueError('La secuencia de etiquetas tiene valores o forma inválidos')
fb = crf_forward_backward(e, a, s, f)
score = s[y[0]] + f[y[-1]] + sum(e[t, y[t]] for t in range(T))
score += sum(a[y[t-1], y[t]] for t in range(1, T))
if not np.isfinite(score):
raise ValueError('La secuencia observada está prohibida')
empirical_nodes = np.zeros_like(e)
empirical_nodes[np.arange(T), y] = 1.
empirical_edges = np.zeros_like(a)
for t in range(1, T):
empirical_edges[y[t-1], y[t]] += 1.
start_count, end_count = np.zeros(K), np.zeros(K)
start_count[y[0]], end_count[y[-1]] = 1., 1.
gradients = {'emission': empirical_nodes - fb['nodes'],
'transition': empirical_edges - fb['edges'].sum(axis=0),
'start': start_count - fb['nodes'][0],
'end': end_count - fb['nodes'][-1]}
return float(score - fb['log_z']), gradients, fb
def crf_viterbi(emission, trans, start, end):
e, a, s, f, T, K = validate_crf(emission, trans, start, end)
dp, back = np.full((T, K), -np.inf), np.zeros((T, K), dtype=np.int64)
dp[0] = s + e[0]
for t in range(1, T):
for j in range(K):
candidates = dp[t-1] + a[:, j]
back[t, j] = int(np.argmax(candidates))
dp[t, j] = e[t, j] + candidates[back[t, j]]
final = dp[-1] + f
if not np.isfinite(final).any():
raise ValueError('No existe camino CRF admisible')
last = int(np.argmax(final))
best_score = float(final[last])
path = [last]
for t in range(T-1, 0, -1):
path.append(int(back[t, path[-1]]))
return np.asarray(path[::-1]), best_score
def enumerate_crf(emission, trans, start, end):
e, a, s, f, T, K = validate_crf(emission, trans, start, end)
if K**T > 100000:
raise ValueError('Enumeración limitada a 100000 caminos')
paths, scores = [], []
for path in product(range(K), repeat=T):
score = s[path[0]] + f[path[-1]] + sum(e[t, path[t]] for t in range(T))
score += sum(a[path[t-1], path[t]] for t in range(1, T))
if np.isfinite(score):
paths.append(path)
scores.append(float(score))
if not paths:
raise ValueError('No hay caminos admisibles')
z = lse(scores)
nodes, edges = np.zeros((T, K)), np.zeros((max(T-1, 0), K, K))
for path, score in zip(paths, scores):
probability = math.exp(score-z)
for t, tag in enumerate(path):
nodes[t, tag] += probability
if t:
edges[t-1, path[t-1], tag] += probability
i = int(np.argmax(scores))
return {'log_z': z, 'nodes': nodes, 'edges': edges,
'best_path': np.asarray(paths[i]), 'best_score': scores[i],
'paths': len(paths)}
def collapse(path, blank=0):
output, previous = [], None
for symbol in path:
if symbol != previous and symbol != blank:
output.append(int(symbol))
previous = symbol
return tuple(output)
def ctc_forward_backward(log_probs, target, blank=0):
lp = np.asarray(log_probs, dtype=np.float64)
if (lp.ndim != 2 or lp.shape[1] < 2 or
not isinstance(blank, (int, np.integer)) or isinstance(blank, (bool, np.bool_)) or
not 0 <= blank < lp.shape[1]):
raise ValueError('Se requieren log-probabilidades (T,C) y blanco válido')
if not np.isfinite(lp).all():
raise ValueError('Las log-probabilidades deben ser finitas')
T, C = lp.shape
target = np.asarray(target)
if target.ndim != 1:
raise ValueError('El objetivo debe tener una dimensión')
if target.size == 0:
target = np.array([], dtype=np.int64)
if (target.ndim != 1 or not np.issubdtype(target.dtype, np.integer) or
np.any((target < 0) | (target >= C) | (target == blank))):
raise ValueError('El objetivo debe contener símbolos válidos distintos del blanco')
if T and not np.allclose(np.logaddexp.reduce(lp, axis=1), 0., atol=1e-8, rtol=0):
raise ValueError('Las log-probabilidades deben estar normalizadas por paso')
if T == 0:
if len(target) == 0:
return {'loss': 0., 'gradient_logits': np.empty((0, C)),
'posterior': np.empty((0, C)), 'log_probability': 0.}
return {'loss': math.inf, 'gradient_logits': None,
'posterior': None, 'log_probability': -math.inf}
ext = [blank]
for symbol in target:
ext.extend((int(symbol), blank))
S = len(ext)
alpha, beta = np.full((T, S), -np.inf), np.full((T, S), -np.inf)
alpha[0, 0] = lp[0, blank]
if S > 1:
alpha[0, 1] = lp[0, ext[1]]
for t in range(1, T):
for j in range(S):
prev = [alpha[t-1, j]]
if j >= 1:
prev.append(alpha[t-1, j-1])
if j >= 2 and ext[j] != blank and ext[j] != ext[j-2]:
prev.append(alpha[t-1, j-2])
alpha[t, j] = lse(prev) + lp[t, ext[j]]
terminal = [alpha[-1, -1]]
if S > 1:
terminal.append(alpha[-1, -2])
logz = lse(terminal)
if logz == -math.inf:
# Pérdida infinita: el gradiente condicional no está definido.
return {'loss': math.inf, 'gradient_logits': None,
'posterior': None, 'log_probability': logz,
'extended': ext, 'alpha': alpha}
beta[-1, -1] = 0.
if S > 1:
beta[-1, -2] = 0.
for t in range(T-2, -1, -1):
for j in range(S):
nxt = [beta[t+1, j] + lp[t+1, ext[j]]]
if j + 1 < S:
nxt.append(beta[t+1, j+1] + lp[t+1, ext[j+1]])
if j + 2 < S and ext[j+2] != blank and ext[j+2] != ext[j]:
nxt.append(beta[t+1, j+2] + lp[t+1, ext[j+2]])
beta[t, j] = lse(nxt)
posterior = np.zeros((T, C))
for j, symbol in enumerate(ext):
posterior[:, symbol] += np.exp(alpha[:, j] + beta[:, j] - logz)
grad = np.exp(lp) - posterior
return {'loss': -logz, 'gradient_logits': grad, 'posterior': posterior,
'log_probability': logz, 'extended': ext, 'alpha': alpha, 'beta': beta}
def enumerate_ctc(log_probs, target, blank=0):
lp = np.asarray(log_probs, dtype=np.float64)
T, C = lp.shape
if C**T > 100000:
raise ValueError('Enumeración limitada a 100000 caminos')
paths, scores = [], []
for path in product(range(C), repeat=T):
if collapse(path, blank) == tuple(target):
score = sum(lp[t, symbol] for t, symbol in enumerate(path))
if np.isfinite(score):
paths.append(path); scores.append(float(score))
if not paths:
return {'loss': math.inf, 'posterior': None, 'paths': 0}
z = lse(scores)
posterior = np.zeros((T, C))
for path, score in zip(paths, scores):
for t, symbol in enumerate(path):
posterior[t, symbol] += math.exp(score-z)
return {'loss': -z, 'posterior': posterior, 'paths': len(paths)}
def check_crf():
rng = np.random.default_rng(17160)
e = rng.normal(size=(3, 3)); a = rng.normal(size=(3, 3))
s = rng.normal(size=3); f = rng.normal(size=3)
a[0, 2] = -np.inf; s[2] = -np.inf; f[0] = -np.inf
y = np.array([0, 1, 2])
loglik, grad, fb = crf_log_likelihood(e, a, s, f, y)
brute = enumerate_crf(e, a, s, f)
path, score = crf_viterbi(e, a, s, f)
assert np.isclose(fb['log_z'], brute['log_z'], atol=1e-12)
assert np.allclose(fb['nodes'], brute['nodes'], atol=1e-12)
assert np.allclose(fb['edges'], brute['edges'], atol=1e-12)
empirical = np.zeros_like(e); empirical[np.arange(len(y)), y] = 1.
assert np.allclose(grad['emission'], empirical - brute['nodes'], atol=1e-12)
transition_count = np.zeros_like(a)
for t in range(1, len(y)):
transition_count[y[t-1], y[t]] += 1.
assert np.allclose(grad['transition'], transition_count - brute['edges'].sum(axis=0), atol=1e-12)
assert np.array_equal(path, brute['best_path']) and np.isclose(score, brute['best_score'])
assert np.allclose(fb['nodes'].sum(axis=1), 1.)
assert np.allclose(fb['edges'].sum(axis=(1, 2)), 1.)
arrays = [('emission', e), ('transition', a), ('start', s), ('end', f)]
max_error = 0.
for name, arr in arrays:
for idx in np.ndindex(arr.shape):
if not np.isfinite(arr[idx]):
continue
old, eps = arr[idx], 1e-5
arr[idx] = old + eps; plus = crf_log_likelihood(e, a, s, f, y)[0]
arr[idx] = old - eps; minus = crf_log_likelihood(e, a, s, f, y)[0]
arr[idx] = old
max_error = max(max_error, abs((plus-minus)/(2*eps) - grad[name][idx]))
assert max_error < 1e-7
return {'log_z': fb['log_z'], 'log_likelihood': loglik,
'best_path': path.tolist(), 'best_score': score,
'allowed_paths': brute['paths'], 'gradient_max_error': float(max_error)}
def check_ctc():
rng = np.random.default_rng(17161)
cases = [(4, (1, 1, 2)), (5, (1, 1, 2)), (4, (1, 2)), (3, (1, 1)), (3, ()),
(3, (1, 1, 2)), (0, ()), (0, (1,))]
rows = []
for T, target in cases:
logits = rng.normal(size=(T, 3))
lp = log_softmax(logits)
dp = ctc_forward_backward(lp, target)
brute = enumerate_ctc(lp, target)
error = None
if math.isinf(brute['loss']):
assert math.isinf(dp['loss']) and dp['gradient_logits'] is None
else:
assert np.isclose(dp['loss'], brute['loss'], atol=1e-12)
assert np.allclose(dp['posterior'], brute['posterior'], atol=1e-12)
if T:
assert np.allclose(dp['posterior'].sum(axis=1), 1., atol=1e-12)
assert np.allclose(dp['gradient_logits'].sum(axis=1), 0., atol=1e-12)
assert np.allclose(dp['gradient_logits'], np.exp(lp) - brute['posterior'], atol=1e-12)
error = 0.
for idx in np.ndindex(logits.shape):
old, eps = logits[idx], 1e-5
logits[idx] = old + eps
plus = ctc_forward_backward(log_softmax(logits), target)['loss']
logits[idx] = old - eps
minus = ctc_forward_backward(log_softmax(logits), target)['loss']
logits[idx] = old
error = max(error, abs((plus-minus)/(2*eps) - dp['gradient_logits'][idx]))
assert error < 1e-7
rows.append({'T': T, 'target': list(target),
'loss': None if math.isinf(dp['loss']) else dp['loss'],
'status': 'imposible' if math.isinf(dp['loss']) else 'finito',
'enumerated_paths': brute['paths'],
'gradient_max_error': None if error is None else float(error)})
assert collapse((1, 1, 0, 1, 2), blank=0) == (1, 1, 2)
assert collapse((1, 1, 2), blank=0) == (1, 2)
assert any(row['enumerated_paths'] > 1 for row in rows)
# El blanco no tiene por qué ser el símbolo de índice cero.
lp = log_softmax(rng.normal(size=(4, 3)))
other_blank = ctc_forward_backward(lp, [0, 0], blank=2)
brute_other = enumerate_ctc(lp, [0, 0], blank=2)
assert np.isclose(other_blank['loss'], brute_other['loss'], atol=1e-12)
assert np.allclose(other_blank['posterior'], brute_other['posterior'], atol=1e-12)
extreme = np.array([[1000., -1000., 0.], [1000., -1000., 0.]])
extreme_result = ctc_forward_backward(log_softmax(extreme), [1])
assert math.isfinite(extreme_result['loss']) and np.isfinite(extreme_result['gradient_logits']).all()
for bad_lp, bad_target, bad_blank in ((lp, np.empty((0, 2)), 0),
(np.array([[0., -np.inf, -np.inf]]), [], 0),
(lp, [], .5)):
try:
ctc_forward_backward(bad_lp, bad_target, bad_blank)
except ValueError:
pass
else:
raise AssertionError('Se aceptó una entrada fuera del contrato')
return rows
def main():
print('CRF: partición, Viterbi y gradientes:', check_crf())
print('CTC: forward-backward, enumeración y gradientes:', check_ctc())
print('Si no hay alineamientos válidos, la pérdida es infinita y el gradiente no está definido.')
print('Los ejemplos se enumeran completamente; no son métricas de un modelo entrenado.')
if __name__ == '__main__':
main()Local laboratory: entities and digits
You will train taggers on the Spanish CoNLL-2002 split and a CTC recognizer on MNIST digit sequences. Split original images before constructing sequences so the same image cannot appear in training and test, and keep validation separate for checkpoint selection. A short run checks the pipeline, not a definitive F1 or recognition comparison.
The lab needs PyTorch, TorchVision, NLTK, and seqeval. Download CoNLL-2002 with python -m nltk.downloader conll2002 and consult its terms: the Spanish language resources catalog restricts it to research. MNIST comes from TorchVision. Official entity splits are not deduplicated; digit images are split before constructing sequences, though identical images with different indices are still possible. Entity F1 uses strict IOB2 in seqeval, which can differ from the official evaluator for malformed predictions.
With ORYON_VERIFY_SHORT=1, reduce data and epochs to check the path. Normal mode runs full training. The report distinguishes validation from exploratory test and saves CTC probabilities for one validation example without assuming it learned.
In the displayed short run, both position classifier and CRF obtained entity F1 0 on 24 validation sentences; the CTC recognizer correctly identified 0 of 16 validation sequences. One epoch and such small samples verify execution but cannot compare final model quality.
"""BiLSTM-CRF y CTC con CoNLL-2002 español y secuencias de MNIST.
Dependencias: numpy, nltk, seqeval, torch, torchvision. Descarga CoNLL-2002
con `python -m nltk.downloader conll2002`; respeta los derechos del corpus y de
MNIST. MNIST se descarga en ORYON_DATA_DIR o ~/.cache/oryon-data. El informe y
los posteriores se escriben en ORYON_OUTPUT_DIR o ./oryon-m17-l16.
ORYON_VERIFY_SHORT=1 comprueba el recorrido, no la calidad. El entrenamiento
completo es para el lector.
"""
import hashlib
import importlib.metadata
import json
import math
import os
import random
from collections import Counter
from pathlib import Path
import numpy as np
import torch
from nltk.corpus import conll2002
from seqeval.metrics import f1_score
from seqeval.scheme import IOB2
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from torch.utils.data import DataLoader, Dataset
from torchvision.datasets import MNIST
SEED = 17160
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
OUTPUT = Path(os.environ.get('ORYON_OUTPUT_DIR', 'oryon-m17-l16'))
DATA = Path(os.environ.get('ORYON_DATA_DIR', Path.home() / '.cache' / 'oryon-data'))
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
PAD, UNK = 0, 1
def seed_all(seed=SEED):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def entity_data():
try:
# NLTK entrega (token, POS, BIO). Se conservan las particiones oficiales.
splits = [conll2002.iob_sents(f'esp.{part}') for part in ('train', 'testa', 'testb')]
except LookupError as error:
raise RuntimeError('Descarga el corpus con python -m nltk.downloader conll2002') from error
result = [[([word for word, _, _ in sentence], [tag for _, _, tag in sentence])
for sentence in split] for split in splits]
if SHORT:
result = [split[:limit] for split, limit in zip(result, (96, 24, 24))]
if not all(result) or any(not tokens for split in result for tokens, _ in split):
raise ValueError('Partición vacía o frase vacía')
return result
def build_vocab(train):
words = Counter(word.lower() for tokens, _ in train for word in tokens)
chars = Counter(char for tokens, _ in train for word in tokens for char in word)
word_map = {'<pad>': PAD, '<unk>': UNK}
char_map = {'<pad>': PAD, '<unk>': UNK}
for word in sorted(words):
if word not in word_map:
word_map[word] = len(word_map)
for char in sorted(chars):
if char not in char_map:
char_map[char] = len(char_map)
tags = sorted({tag for _, labels in train for tag in labels})
return word_map, char_map, {tag: i for i, tag in enumerate(tags)}
def make_ner_batch(batch, word_map, char_map, tag_map):
lengths = [len(words) for words, _ in batch]
max_len = max(lengths)
max_chars = min(32, max(len(word) for tokens, _ in batch for word in tokens))
token_ids = torch.zeros((len(batch), max_len), dtype=torch.long)
char_ids = torch.zeros((len(batch), max_len, max_chars), dtype=torch.long)
labels = torch.zeros((len(batch), max_len), dtype=torch.long)
mask = torch.zeros((len(batch), max_len), dtype=torch.bool)
for i, (tokens, gold) in enumerate(batch):
for j, (word, tag) in enumerate(zip(tokens, gold)):
if tag not in tag_map:
raise ValueError(f'Etiqueta fuera del vocabulario de train: {tag}')
token_ids[i, j] = word_map.get(word.lower(), UNK)
for h, char in enumerate(word[:max_chars]):
char_ids[i, j, h] = char_map.get(char, UNK)
labels[i, j] = tag_map[tag]
mask[i, j] = True
return token_ids, char_ids, labels, mask, lengths
class Encoder(nn.Module):
def __init__(self, num_words, num_chars, num_tags):
super().__init__()
self.words = nn.Embedding(num_words, 64, padding_idx=PAD)
self.chars = nn.Embedding(num_chars, 16, padding_idx=PAD)
self.conv = nn.Conv1d(16, 24, kernel_size=3, padding=1)
self.bilstm = nn.LSTM(88, 64, batch_first=True, bidirectional=True)
self.output = nn.Linear(128, num_tags)
def forward(self, words, chars, lengths):
batch, time, width = chars.shape
flat = chars.reshape(batch * time, width)
x = self.chars(flat).transpose(1, 2)
x = torch.relu(self.conv(x))
# Un mínimo finito evita introducir infinitos en la ruta de padding.
x = x.masked_fill(~flat.ne(PAD).unsqueeze(1), torch.finfo(x.dtype).min)
x = x.amax(dim=2)
# Las posiciones de padding no tienen caracteres válidos.
x = torch.where(flat.ne(PAD).any(dim=1, keepdim=True), x, torch.zeros_like(x))
x = torch.cat((self.words(words), x.reshape(batch, time, -1)), dim=2)
packed = pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False)
encoded, _ = self.bilstm(packed)
padded, _ = pad_packed_sequence(encoded, batch_first=True, total_length=time)
return self.output(padded)
class LinearCRF(nn.Module):
"""Transiciones sin restricciones duras: A[etiqueta anterior, actual]."""
def __init__(self, tags):
super().__init__()
self.transition = nn.Parameter(torch.zeros(tags, tags))
self.start = nn.Parameter(torch.zeros(tags))
self.end = nn.Parameter(torch.zeros(tags))
def loss(self, emission, tags, mask):
batch = torch.arange(emission.size(0), device=emission.device)
alpha = self.start + emission[:, 0]
gold = self.start[tags[:, 0]] + emission[batch, 0, tags[:, 0]]
for t in range(1, emission.size(1)):
next_alpha = torch.logsumexp(alpha.unsqueeze(2) + self.transition.unsqueeze(0), dim=1) + emission[:, t]
alpha = torch.where(mask[:, t, None], next_alpha, alpha)
contribution = self.transition[tags[:, t - 1], tags[:, t]] + emission[batch, t, tags[:, t]]
gold = gold + torch.where(mask[:, t], contribution, torch.zeros_like(contribution))
last = tags[batch, mask.sum(dim=1) - 1]
return (torch.logsumexp(alpha + self.end, dim=1) - gold - self.end[last]).mean()
def decode(self, emission, lengths):
paths = []
for e, length in zip(emission, lengths):
score = self.start + e[0]
back = []
for t in range(1, length):
best, index = (score[:, None] + self.transition).max(dim=0)
score = best + e[t]
back.append(index)
current = int((score + self.end).argmax())
path = [current]
for index in reversed(back):
current = int(index[current]); path.append(current)
paths.append(list(reversed(path)))
return paths
def invalid_iob(labels):
invalid = 0
previous = 'O'
for label in labels:
if label.startswith('I-') and previous not in ('B-' + label[2:], label):
invalid += 1
previous = label
return invalid
def ner_evaluate(encoder, crf, batches, tag_names):
encoder.eval()
if crf is not None:
crf.eval()
gold, predictions = [], []
with torch.no_grad():
for words, chars, labels, mask, lengths in batches:
emissions = encoder(words.to(DEVICE), chars.to(DEVICE), lengths)
if crf is None:
paths = [row[:length].tolist() for row, length in zip(emissions.argmax(dim=2).cpu(), lengths)]
else:
paths = crf.decode(emissions, lengths)
gold.extend([[tag_names[int(x)] for x in row[:length]] for row, length in zip(labels, lengths)])
predictions.extend([[tag_names[x] for x in row] for row in paths])
return {'entity_f1_iob2': float(f1_score(gold, predictions, mode='strict', scheme=IOB2, zero_division=0)),
'invalid_i_transitions': sum(invalid_iob(row) for row in predictions),
'sentences': len(gold), 'tokens': sum(map(len, gold))}
def run_ner():
train, validation, test = entity_data()
word_map, char_map, tag_map = build_vocab(train)
# SHORT puede no contener todos los tipos presentes en validación. Se usan
# los nombres BIO del entrenamiento completo, no sus palabras ni ejemplos.
full_train = conll2002.iob_sents('esp.train')
names = sorted({tag for sentence in full_train for _, _, tag in sentence})
tag_map = {tag: i for i, tag in enumerate(names)}
collate = lambda batch: make_ner_batch(batch, word_map, char_map, tag_map)
val_loader = DataLoader(validation, batch_size=16, shuffle=False, collate_fn=collate)
test_loader = DataLoader(test, batch_size=16, shuffle=False, collate_fn=collate)
report = {}
for model_kind in ('softmax', 'crf'):
seed_all()
encoder = Encoder(len(word_map), len(char_map), len(names)).to(DEVICE)
crf = LinearCRF(len(names)).to(DEVICE) if model_kind == 'crf' else None
parameters = list(encoder.parameters()) + (list(crf.parameters()) if crf is not None else [])
optimizer = torch.optim.Adam(parameters, lr=.001)
generator = torch.Generator().manual_seed(SEED)
loader = DataLoader(train, batch_size=16, shuffle=True, generator=generator, collate_fn=collate)
best_f1, best = -1., None
for epoch in range(1, (2 if SHORT else 9)):
encoder.train()
if crf is not None: crf.train()
for words, chars, labels, mask, lengths in loader:
words, chars, labels, mask = (x.to(DEVICE) for x in (words, chars, labels, mask))
optimizer.zero_grad(set_to_none=True)
emission = encoder(words, chars, lengths)
if crf is None:
loss = nn.functional.cross_entropy(emission[mask], labels[mask])
else:
loss = crf.loss(emission, labels, mask)
if not torch.isfinite(loss): raise ValueError('Pérdida NER no finita')
loss.backward()
nn.utils.clip_grad_norm_(parameters, 5.)
optimizer.step()
val = ner_evaluate(encoder, crf, val_loader, names)
if val['entity_f1_iob2'] > best_f1:
best_f1 = val['entity_f1_iob2']
best = {'epoch': epoch, 'encoder': {k: v.detach().cpu().clone() for k, v in encoder.state_dict().items()},
'crf': None if crf is None else {k: v.detach().cpu().clone() for k, v in crf.state_dict().items()},
'validation': val}
encoder.load_state_dict(best['encoder'])
if crf is not None: crf.load_state_dict(best['crf'])
report[model_kind] = {'best_epoch': best['epoch'], 'validation': best['validation'],
'test': ner_evaluate(encoder, crf, test_loader, names)}
del encoder, crf, optimizer
if torch.cuda.is_available(): torch.cuda.empty_cache()
hashes = []
for partition in (train, validation, test):
digest = hashlib.sha256()
for sentence in partition:
digest.update(json.dumps(sentence, ensure_ascii=False, separators=(',', ':')).encode('utf-8'))
digest.update(b'\n')
hashes.append(digest.hexdigest())
return {'split': 'CoNLL-2002 esp.train, esp.testa, esp.testb', 'counts': [len(train),len(validation),len(test)],
'observed_partition_sha256': hashes,
'hash_note': 'Huella de los ejemplos usados, calculada localmente; no autentica una fuente externa.',
'word_vocab_from': 'train', 'tag_inventory_from': 'esp.train completo',
'entity_metric': 'seqeval strict IOB2, no es el evaluador oficial conlleval', 'models': report}
class DigitSequences(Dataset):
def __init__(self, images, labels, indexes, count, seed):
self.images, self.labels, self.indexes, self.count, self.seed = images, labels, indexes, count, seed
def __len__(self): return self.count
def __getitem__(self, index):
generator = np.random.default_rng(self.seed + index)
length = int(generator.integers(1, 6))
chosen = generator.choice(self.indexes, size=length, replace=True)
image = torch.cat([self.images[int(i)].float() / 255. for i in chosen], dim=1)
# 0 es blanco; los dígitos 0 a 9 se convierten en clases 1 a 10.
target = [int(self.labels[int(i)]) + 1 for i in chosen]
return image.transpose(0, 1), target
def digit_batch(batch):
lengths = [x.size(0) for x, _ in batch]
targets = [target for _, target in batch]
x = torch.zeros((len(batch), max(lengths), 28), dtype=torch.float32)
for i, (image, _) in enumerate(batch): x[i, :len(image)] = image
return x, lengths, torch.tensor([c for target in targets for c in target], dtype=torch.long), [len(t) for t in targets], targets
class DigitCTC(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.LSTM(28, 64, batch_first=True, bidirectional=True)
self.classifier = nn.Linear(128, 11)
def forward(self, x, lengths):
packed = pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False)
output, _ = self.encoder(packed)
output, _ = pad_packed_sequence(output, batch_first=True, total_length=x.size(1))
return self.classifier(output).transpose(0, 1).log_softmax(dim=2)
def collapse(ids):
result, previous = [], None
for item in ids:
if item != previous and item != 0: result.append(item)
previous = item
return result
def ctc_forward_np(log_probs, target):
"""La misma recurrencia forward de la primera celda, con blanco 0."""
extended = [0]
for symbol in target: extended.extend([symbol, 0])
alpha = np.full(len(extended), -np.inf)
alpha[0] = log_probs[0, 0]
if target: alpha[1] = log_probs[0, target[0]]
for row in log_probs[1:]:
updated = np.full_like(alpha, -np.inf)
for s, symbol in enumerate(extended):
candidates = [alpha[s]]
if s > 0: candidates.append(alpha[s - 1])
if s > 1 and symbol != 0 and symbol != extended[s - 2]: candidates.append(alpha[s - 2])
updated[s] = np.logaddexp.reduce(candidates) + row[symbol]
alpha = updated
return -float(np.logaddexp(alpha[-1], alpha[-2])) if target else -float(alpha[-1])
def digit_evaluate(model, loader):
model.eval()
exact = count = 0
with torch.no_grad():
for x, lengths, _, _, targets in loader:
logp = model(x.to(DEVICE), lengths).cpu()
for i, target in enumerate(targets):
prediction = collapse(logp[:lengths[i], i].argmax(dim=1).tolist())
exact += int(prediction == target); count += 1
return {'exact_sequences': exact, 'sequences': count, 'accuracy': exact / count if count else None}
def ctc_stage(model, sample, epoch):
model.eval()
x, lengths, _, _, targets = digit_batch([sample])
with torch.no_grad(): logp = model(x.to(DEVICE), lengths)[:, 0].cpu().numpy()
probs = np.exp(logp)
return {'epoch': epoch, 'target': [n - 1 for n in targets[0]],
'greedy': [n - 1 for n in collapse(probs.argmax(axis=1).tolist())],
'posterior': probs.tolist()}
def run_digits():
seed_all()
train_set = MNIST(str(DATA), train=True, download=True)
test_set = MNIST(str(DATA), train=False, download=True)
raw_hashes = {}
for filename in ('train-images-idx3-ubyte', 'train-labels-idx1-ubyte',
't10k-images-idx3-ubyte', 't10k-labels-idx1-ubyte'):
digest = hashlib.sha256()
with (Path(train_set.raw_folder) / filename).open('rb') as source:
for block in iter(lambda: source.read(1024 * 1024), b''):
digest.update(block)
raw_hashes[filename] = digest.hexdigest()
permutation = np.random.default_rng(SEED).permutation(len(train_set.data))
train_ids, val_ids = permutation[:55000], permutation[55000:]
assert not set(train_ids).intersection(val_ids)
if SHORT: train_ids, val_ids = train_ids[:96], val_ids[:32]
test_ids = np.arange(len(test_set.data))[:32 if SHORT else len(test_set.data)]
train = DigitSequences(train_set.data, train_set.targets, train_ids, 64 if SHORT else 40000, SEED + 100)
val = DigitSequences(train_set.data, train_set.targets, val_ids, 16 if SHORT else 2000, SEED + 100000)
test = DigitSequences(test_set.data, test_set.targets, test_ids, 16 if SHORT else 3000, SEED + 200000)
generator = torch.Generator().manual_seed(SEED)
loader = DataLoader(train, batch_size=8 if SHORT else 32, shuffle=True, generator=generator, collate_fn=digit_batch)
val_loader = DataLoader(val, batch_size=16, shuffle=False, collate_fn=digit_batch)
test_loader = DataLoader(test, batch_size=16, shuffle=False, collate_fn=digit_batch)
model = DigitCTC().to(DEVICE)
optimizer = torch.optim.Adam(model.parameters(), lr=.001)
criterion = nn.CTCLoss(blank=0, reduction='mean', zero_infinity=False)
stages = [ctc_stage(model, val[0], 0)]
history = []
best_accuracy, best_state, best_epoch = -1., None, None
parity_error = None
for epoch in range(1, (2 if SHORT else 9)):
model.train()
for x, lengths, target, target_lengths, target_lists in loader:
optimizer.zero_grad(set_to_none=True)
logp = model(x.to(DEVICE), lengths)
loss = criterion(logp, target.to(DEVICE), torch.tensor(lengths), torch.tensor(target_lengths))
if not torch.isfinite(loss): raise ValueError('Pérdida CTC no finita')
if parity_error is None:
own = ctc_forward_np(logp[:lengths[0], 0].detach().cpu().double().numpy(), target_lists[0])
library = nn.functional.ctc_loss(logp[:lengths[0], :1].detach().cpu().double(),
torch.tensor(target_lists[0], dtype=torch.long), torch.tensor([lengths[0]]),
torch.tensor([len(target_lists[0])]), blank=0, reduction='sum').item()
parity_error = abs(own - library)
if parity_error > 1e-8: raise AssertionError(('CTC distinta de NumPy', own, library))
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 5.)
optimizer.step()
validation = digit_evaluate(model, val_loader)
history.append({'epoch': epoch, 'validation': validation})
stages.append(ctc_stage(model, val[0], epoch))
if validation['accuracy'] > best_accuracy:
best_accuracy = validation['accuracy']; best_epoch = epoch
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
model.load_state_dict(best_state)
test_metrics = digit_evaluate(model, test_loader)
del model, optimizer
if torch.cuda.is_available(): torch.cuda.empty_cache()
return {'mnist_split': 'train oficial en 55000/5000 imágenes; test oficial independiente',
'raw_sha256_measured': raw_hashes,
'hash_note': 'Huella de archivos leídos, no autentica por sí sola una fuente externa.',
'image_counts': [len(train_ids), len(val_ids), len(test_ids)],
'sequence_counts': [len(train), len(val), len(test)],
'generation': '1 a 5 imágenes concatenadas, muestreo con reposición dentro de cada partición',
'ctc_numpy_torch_abs_difference': parity_error, 'best_epoch': best_epoch,
'history': history, 'test': test_metrics}, stages
def main():
seed_all()
OUTPUT.mkdir(parents=True, exist_ok=True)
ner = run_ner()
digits, stages = run_digits()
versions = {name: importlib.metadata.version(name) for name in ('torch', 'torchvision', 'numpy', 'nltk', 'seqeval')}
report = {'short': SHORT, 'seed': SEED, 'device': str(DEVICE), 'versions': versions,
'limitations': 'SHORT solo verifica funcionamiento; una semilla no establece conclusiones. '
'Conjuntos CoNLL oficiales pueden compartir textos. MNIST se separa por índices, '
'lo que no descarta imágenes idénticas. La exactitud CTC es por secuencia completa.',
'ner': ner, 'digits': digits}
(OUTPUT / 'metrics.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
(OUTPUT / 'ctc-stages.json').write_text(json.dumps({'source':'MNIST validación', 'seed':SEED,
'short':SHORT, 'blank_class':0, 'class_mapping':'dígito = clase − 1', 'stages':stages},
ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(report, ensure_ascii=False, indent=2))
print('Posteriores de la misma secuencia de validación:', OUTPUT / 'ctc-stages.json')
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
Step 1 of 3. What does α₁(j) represent?
import numpy as np
def ctc_loss(log_probs, target, blank=0):
passFurther reading
Dynamic programming over strings connects to Linear-chain conditional random field and Forward-backward algorithm (smoothing). Entity-level evaluation requires reviewing precision and recall definitions, not only token accuracy.