The neural probabilistic language model: end-to-end learned embeddings
Build a fixed-window neural language model, derive embedding gradients and analyze full-vocabulary output cost.
After this lesson you can
- Explain embedding lookup and accumulate gradients for repeated indices.
- Implement a neural language model and stable cross-entropy.
- Compare similarity-based generalization with count-based models.
- Calculate parameters and output computation under explicit conventions.
Before you start
- 17N-gram Markov assumptionData sparsity and zero countsIntrinsic language model evaluationLocal versus distributed representationsKneser-Ney smoothingAncestral sampling from an autoregressive model
- 15Multilayer perceptronBackpropagationEpochs and shuffling
- 09Gradient checkingLog-sum-exp trick and stable softmax
- 07Softmax cross-entropy loss
- 00Canonical training and evaluation loop
A sentence you had not counted
You observed “the cat walks” and want to assign a probability to “the dog walks.” A count model can use lower-order continuations when an n-gram is missing; a neural model can also share parameters between contexts with similar representations. The possibility of sharing does not guarantee it learns the correct relationship: that depends on data, architecture and optimization.
In the previous lesson you described a word through context counts. Now its representation is learned alongside next-unit prediction. Bengio, Ducharme, Vincent and Jauvin proposed a neural probabilistic model with a feature table per word and a network receiving a fixed window of representations. As in an n-gram, the model sees only tokens in that window. Parameter sharing alleviates some statistical sparsity but provides no memory of what was left outside.
A table is a special multiplication
Let be a table of vectors of dimension . For index , one-hot vector has one at position and zeros elsewhere. The embedding lookup operation satisfies
Computing the dense product would waste operations on zeros: indexing the row suffices. These are not different models. For occurrences of indices in a batch of examples (“lote” means batch), call lookup output at occurrence and its gradient . One example can contribute several occurrences. The chain rule gives
An index can appear in multiple examples and multiple positions in one context: all contributions sum. If is the mean loss over examples, the factor must appear once in calculating ; do not divide by again. Other rows receive zero gradient from this operation, provided no other path uses the table and there is no direct penalty on it.
In NumPy, np.add.at(dE, ids, dout) also accumulates repeated indices. By contrast, dE[ids] += dout uses buffered advanced indexing and can lose repeated contributions; NumPy documentation shows the difference. add.at on a full zero-initialized matrix yields a mathematically row-sparse result, but matrix storage remains dense.
From vectors to a distribution
Let denote the number of previous tokens and concatenate their embeddings in the chosen order:
The neural language model uses a hidden layer of units and logits :
Here has shape , shape and optional direct connection shape . If absent, take without counting its parameters. Concatenation preserves order, unlike a vector sum. In the original paper’s n-gram notation, : an order-three model receives two previous tokens. In this lesson “three-token context” means , not order three.
A sequence is scored by multiplying each token’s conditionals, with start and end markers according to the chosen protocol. The network does not know the future: comparing models requires both to score exactly the same events. Changing document boundaries, including or excluding EOS or transforming vocabulary changes perplexity.
Cross-entropy for target is . For finite logits, subtract the maximum before summing exponentials to avoid overflow. Its gradient with respect to each logit is . Backward then passes through , tanh and ; each position’s portion accumulates in the selected embedding row. Finite differences with a repeated index detect errors a batch without repetition could hide.
Sharing without promising the outcome
If “cat” and “dog” embeddings are close, replacing one with the other in the same position changes the concatenated input little. For finite weights, the network is continuous: sufficiently close inputs produce close logits. This explains a route to similarity-based generalization, not a guarantee that vectors will become close or the continuation receive high probability. Nor does it prove semantic similarity: an equivalent predictive function can be expressed in different coordinate systems.
A reasonable comparison keeps the same target sequence for the neural model and Kneser-Ney fitted on the same training data. When a bigram was not observed but its context was, interpolated Kneser-Ney retains its continuation contribution multiplied by discounted mass. If context was unseen, the backoff convention defines the lower distribution. In particular, the continuation base is not necessarily the raw-frequency unigram. Architectural advantage is measured on separate data, not inferred from a particular new sentence.
Data can also supply contradictory signals. A single static vector per type mixes a word’s uses; a two-dimensional projection can distort original distances. When inspecting neighbors, state dataset, metric and coverage. Learning a representation from a task does not guarantee all its axes or neighbors are interpretable.
What was compared in 2003
In Table 1 of Bengio and colleagues, Brown was split into 800,000 training tokens, 200,000 validation and 181,041 test. After grouping rare words the vocabulary had 16,383 symbols. MLP9, with four previous words, dimension 30, 100 hidden units and no direct connection, obtained perplexity 280 on validation and 276 on test. MLP10, which equally mixes its probabilities with an interpolated trigram, obtained 265 and 252. The figure 252 belongs to the mixture, not the network alone.
The class-based n-gram selected on validation obtained 312 on test. Ratio expresses that its perplexity is approximately 24% higher than the mixture’s. Expressing the reduction from 312 to 252 changes the denominator and gives approximately 19.2%. Both models used that experiment’s protocol; no universal improvement over Kneser-Ney on every corpus follows.
For AP News, Table 2 reports 109 on test for a five-context-word network mixed with the trigram and 117 for the best order-five Kneser-Ney. Corpora and vocabulary treatments differed from Brown. These published figures are not this lesson’s lab results. Validation was used to choose configurations; repeatedly looking at test to select one makes its result exploratory.
How many parameters and operations
Without a direct connection or weights shared between input and output, the table contributes parameters, the first transform and output . The total is
With a direct connection add parameters. Tying input and output weights is possible only when dimensions and design are compatible; the same table then receives gradients from both paths.
For one forward pass per token, counting one multiplication and addition as two FLOPs per MAC, dominant multiplications are approximately in the hidden layer and in the output projection. Softmax normalization itself adds order- operations. Lookup reads values: it does not multiply a dense one-hot matrix. We have excluded backward, optimizer, memory, transfers and specific tanh and exponential costs. Under that partial accounting without a direct connection, output projection exceeds hidden multiplication when ; this is not a universal latency prediction.
Full-vocabulary output must calculate and normalize one logit per class. Even with one correct label, gradient generally affects every class. Later lessons study other ways to organize or approximate this calculation. Removing output and loss in a measurement does not produce equivalent training: measure operations separately and explain exclusions to understand cost.
Sparse lookup in PyTorch
nn.Embedding(V, d, sparse=True) returns a sparse-format weight gradient for the lookup path; the table itself remains dense. Not all optimizers accept that format: documentation lists SGD on CPU and CUDA, SparseAdam on CPU and CUDA and Adagrad on CPU. A network with dense layers also needs an optimizer configuration compatible with both gradient types.
SparseAdam updates parameters and moments at materialized gradient entries; it is not generally equivalent to dense Adam. padding_idx, scale_grad_by_freq and max_norm change the documented rules. Dense weight decay can also modify rows absent from the batch. Equal shrinkage per step does not penalize rare words differently in absolute terms, but can weigh more relative to their less frequent data signal. Applying decay only to visited rows changes dynamics and requires justifying any claimed equivalence.
Labs
Window network in NumPy
The lab implements lookup, linear layers, tanh, stable cross-entropy and custom backward; it checks derivatives by finite differences, including repeated indices. It compares at character level with the previous lesson’s Kneser-Ney using the same vocabulary, context and scored events. Training and validation are separated; the result is reported as obtained. The small sample verifies the pipeline, not establishes a general advantage or compares character and word perplexities.
The cell uses two short excerpts from different chapters of part one of Don Quixote on Project Gutenberg. You can replace them with separate complete chapters; the check rejects identical normalized texts but does not detect partial overlap. Validation is exploratory and there is no independent test. The integrated sample is a small check with no results attributed in advance.
"""Modelo de ventana por caracteres en NumPy, con backward y control KN.
Usa fragmentos de Miguel de Cervantes, Don Quijote, primera parte, capítulos
I y II, edición Project Gutenberg 2000:
https://www.gutenberg.org/files/2000/2000-0.txt . La ficha declara dominio
público en EE. UU.; consulta https://www.gutenberg.org/policy/license.html y la
ley aplicable antes de redistribuir. Son muestras demasiado pequeñas para
concluir qué modelo generaliza mejor. El lector puede sustituir TRAIN y VALID
por capítulos distintos de la primera parte y debe medir el tiempo Pyodide.
"""
import math
import unicodedata
from collections import Counter, defaultdict
import numpy as np
TRAIN = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
VALID = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
SEED = 17050
WINDOW, EMBED, HIDDEN, EPOCHS, LR = 3, 6, 12, 30, .2
BOS, EOS, UNK = '<s>', '</s>', '<unk>'
def normalized(text):
return list(unicodedata.normalize('NFC', text).lower())
def events(sentence, order):
context = [BOS] * (order - 1)
for token in [*sentence, EOS]:
yield tuple(context), token
if order > 1:
context = (context + [token])[-(order - 1):]
class Embedding:
def __init__(self, rows, width, rng):
self.weight = rng.normal(0., .1, (rows, width))
def forward(self, indices):
self.indices = indices
return self.weight[indices]
def backward(self, gradient):
self.grad = np.zeros_like(self.weight)
np.add.at(self.grad, self.indices, gradient)
return self.grad
class Linear:
def __init__(self, inputs, outputs, rng):
self.weight = rng.normal(0., 1 / np.sqrt(inputs), (inputs, outputs))
self.bias = np.zeros(outputs)
def forward(self, x):
self.input = x
return x @ self.weight + self.bias
def backward(self, grad):
self.grad_weight = self.input.T @ grad
self.grad_bias = grad.sum(axis=0)
return grad @ self.weight.T
def cross_entropy(logits, targets):
shifted = logits - logits.max(axis=1, keepdims=True)
log_partition = np.log(np.exp(shifted).sum(axis=1))
loss = np.mean(log_partition - shifted[np.arange(len(targets)), targets])
probs = np.exp(shifted - log_partition[:, None])
probs[np.arange(len(targets)), targets] -= 1
return float(loss), probs / len(targets)
class WindowLM:
def __init__(self, inputs, outputs, window, width, hidden, seed):
rng = np.random.default_rng(seed)
self.embedding = Embedding(inputs, width, rng)
self.hidden = Linear(window * width, hidden, rng)
self.output = Linear(hidden, outputs, rng)
def loss(self, ids, targets, backward=False):
embedded = self.embedding.forward(ids)
x = embedded.reshape(len(ids), -1)
hidden = np.tanh(self.hidden.forward(x))
loss, grad = cross_entropy(self.output.forward(hidden), targets)
if backward:
grad_hidden = self.output.backward(grad)
grad_x = self.hidden.backward(grad_hidden * (1 - hidden ** 2))
self.embedding.backward(grad_x.reshape(embedded.shape))
return loss
def params(self):
return {'E': self.embedding.weight, 'W1': self.hidden.weight, 'b1': self.hidden.bias,
'W2': self.output.weight, 'b2': self.output.bias}
def grads(self):
return {'E': self.embedding.grad, 'W1': self.hidden.grad_weight, 'b1': self.hidden.grad_bias,
'W2': self.output.grad_weight, 'b2': self.output.grad_bias}
def encode(sentence, vocab, window):
index = {token: i for i, token in enumerate(vocab)}
bos = len(vocab)
ids, targets = [], []
mapped = [token if token in index else UNK for token in sentence]
for context, target in events(mapped, window + 1):
ids.append([bos if token == BOS else index[token] for token in context])
targets.append(index[target])
return np.asarray(ids, dtype=np.int64), np.asarray(targets, dtype=np.int64), mapped
def gradcheck(model, ids, targets):
# Un contexto repetido garantiza índices repetidos en posiciones distintas.
ids = np.vstack([ids[:1], ids[:1], ids[1:3]])
targets = np.concatenate([targets[:1], targets[:1], targets[1:3]])
model.loss(ids, targets, backward=True)
analytic = {name: grad.copy() for name, grad in model.grads().items()}
errors = {}
for name, param in model.params().items():
candidates = [(0,) * param.ndim, np.unravel_index(param.size // 2, param.shape),
np.unravel_index(param.size - 1, param.shape)]
if name == 'E':
candidates.append((int(ids[0, 0]), 0))
largest = 0.
for idx in candidates:
original = param[idx]
param[idx] = original + 1e-6
plus = model.loss(ids, targets)
param[idx] = original - 1e-6
minus = model.loss(ids, targets)
param[idx] = original
numerical = (plus - minus) / 2e-6
error = abs(analytic[name][idx] - numerical)
largest = max(largest, error)
errors[name] = largest
assert largest < 1e-6, (name, largest)
# Equivalencia de scatter-add con suma explícita en un lote repetido.
example_ids = np.array([[1, 2, 1], [1, 2, 2]])
example_grad = np.arange(12, dtype=float).reshape(2, 3, 2)
layer = Embedding(4, 2, np.random.default_rng(SEED))
layer.forward(example_ids)
actual = layer.backward(example_grad)
dense = np.eye(4)[example_ids].reshape(-1, 4).T @ example_grad.reshape(-1, 2)
assert np.array_equal(actual, dense)
return errors
class KNReference:
"""MKN de la celda vigente de m17-l03, adaptada a tokens de caracteres.
Conserva cuenta de predecesores distintos, descuentos por frecuencias o
respaldo .5 y base con 1 % uniforme. Mismo soporte y EOS que la red.
"""
def __init__(self, train, order):
self.order, self.epsilon = order, .01
self.vocab = sorted(set(train) | {UNK, EOS})
self.allowed = set(self.vocab)
raw = {}
for n in range(1, order + 1):
table = defaultdict(Counter)
for context, token in events(train, n):
table[context][token] += 1
raw[n] = table
self.tables = {order: raw[order]}
for n in range(order - 1, 0, -1):
predecessors = defaultdict(set)
for context, successors in raw[n + 1].items():
for token in successors:
predecessors[(context[1:], token)].add(context[0])
table = defaultdict(Counter)
for (context, token), preceding in predecessors.items():
table[context][token] = len(preceding)
self.tables[n] = table
self.discounts, self.origins = {}, {}
for n in range(2, order + 1):
hist = Counter(c for row in self.tables[n].values() for c in row.values())
a, b, c, d = (hist[i] for i in (1, 2, 3, 4))
value = None
if a and b and c:
y = a / (a + 2 * b)
candidate = (1 - 2 * y * b / a, 2 - 3 * y * c / b, 3 - 4 * y * d / c)
if all(math.isfinite(x) and 0 <= x <= cap for x, cap in zip(candidate, (1, 2, 3))):
value = candidate
self.discounts[n] = value if value is not None else (.5, .5, .5)
self.origins[n] = 'estimado' if value is not None else 'respaldo fijo'
def prob(self, context, token, n=None):
n = self.order if n is None else n
token = token if token in self.allowed else UNK
if n == 1:
row = self.tables[1].get((), Counter())
total = sum(row.values())
continuation = row[token] / total if total else 1 / len(self.vocab)
return .99 * continuation + .01 / len(self.vocab)
row = self.tables[n].get(tuple(context[-(n - 1):]), Counter())
total = sum(row.values())
if not total:
return self.prob(context, token, n - 1)
ds = self.discounts[n]
def discount(c):
return 0. if c == 0 else min(c, ds[0 if c == 1 else 1 if c == 2 else 2])
mass = sum(discount(c) for c in row.values()) / total
return (row[token] - discount(row[token])) / total + mass * self.prob(context, token, n - 1)
def kn_perplexity(model, sentence):
mapped = [token if token in model.allowed else UNK for token in sentence]
losses = []
for context, token in events(mapped, model.order):
p = model.prob(context, token)
if not math.isfinite(p) or p <= 0 or p > 1 + 1e-12:
raise ValueError('KN sin soporte o probabilidad inválida')
losses.append(-math.log(p))
return math.exp(sum(losses) / len(losses))
def generate(model, vocab, seed, maximum=40):
rng = np.random.default_rng(seed)
history = [len(vocab)] * WINDOW
output = []
for _ in range(maximum):
ids = np.asarray([history], dtype=np.int64)
embedded = model.embedding.forward(ids).reshape(1, -1)
logits = model.output.forward(np.tanh(model.hidden.forward(embedded)))[0]
weights = np.exp(logits - logits.max())
weights /= weights.sum()
selected = int(rng.choice(len(vocab), p=weights))
if vocab[selected] == EOS:
return ''.join(output), 'eos'
output.append('�' if vocab[selected] == UNK else vocab[selected])
history = (history + [selected])[-WINDOW:]
return ''.join(output), 'límite'
def main():
train, valid = normalized(TRAIN), normalized(VALID)
if not train or not valid:
raise ValueError('Se necesitan entrenamiento y validación no vacíos')
if train == valid:
raise ValueError('Entrenamiento y validación coinciden exactamente')
kn = KNReference(train, WINDOW + 1)
vocab = kn.vocab
train_x, train_y, _ = encode(train, vocab, WINDOW)
valid_x, valid_y, valid_mapped = encode(valid, vocab, WINDOW)
expected = list(events(valid_mapped, WINDOW + 1))
lookup = vocab + [BOS]
assert [(tuple(lookup[i] for i in x), vocab[y]) for x, y in zip(valid_x, valid_y)] == expected
model = WindowLM(len(vocab) + 1, len(vocab), WINDOW, EMBED, HIDDEN, SEED)
errors = gradcheck(model, train_x, train_y)
for context, _ in expected:
assert math.isclose(sum(kn.prob(context, word) for word in vocab), 1., abs_tol=1e-10)
print('NumPy:', np.__version__, '| semilla:', SEED, '| ventana:', WINDOW)
print('Eventos train/valid con EOS:', len(train_y), len(valid_y), '| vocabulario de salida:', len(vocab))
print('OOV de validación:', sum(c not in kn.allowed for c in valid), '| gradcheck error absoluto:', errors)
print('KN interpolado de l03, descuentos:', kn.discounts, '| origen:', kn.origins)
print('PPL KN, validación exploratoria:', kn_perplexity(kn, valid))
for epoch in range(EPOCHS + 1):
train_loss = model.loss(train_x, train_y, backward=True)
if epoch in (0, EPOCHS):
valid_loss = model.loss(valid_x, valid_y)
print('Época:', epoch, '| pérdida train:', train_loss, '| PPL validación exploratoria:', math.exp(valid_loss))
# El forward de validación cambia cachés; recalcular gradientes train.
train_loss = model.loss(train_x, train_y, backward=True)
if epoch < EPOCHS:
for name, param in model.params().items():
param -= LR * model.grads()[name]
print('Muestra neuronal:', generate(model, vocab, SEED + 1))
print('Mismo vocabulario y eventos de caracteres, incluidos UNK y EOS; no hay selección sobre test.')
print('Se rechazan particiones idénticas, pero esa prueba no descarta solapamientos parciales.')
print('La validación se inspecciona repetidamente y el corpus pequeño no permite conclusiones generales.')
main()Train and measure with PyTorch
The second lab builds the model at word level, separates training and evaluation and records treatment of unknown symbols. For WikiText-2, Merity and colleagues report 2,088,628 training tokens, 217,646 validation and 245,569 test, including line breaks, and vocabulary of 33,278 under their protocol. Custom tokenization can produce different numbers. The reduced version verifies implementation; output measurement must state batch, precision and synchronization and should not be interpreted as universal timing.
This local cell requires CUDA, PyTorch, NumPy, huggingface_hub and pyarrow. It downloads official WikiText-2 raw splits into the shared cache, pins revision and checks SHA-256 hashes. The card lists CC BY-SA 3.0 and GFDL, but its description mentions CC BY-SA 4.0: check the version’s terms before redistribution. Each nonempty row ends in EOS, vocabulary comes only from training and unknowns are represented by <unk>. Across splits, complete normalized rows with repeated hashes are excluded; SHORT can truncate an accepted row and deduplication does not detect partial matches.
With ORYON_VERIFY_SHORT=1 size is reduced and only the pipeline is checked; it is not a conclusive comparison. Normal mode provides a broader recipe. Validation is consulted per epoch and test evaluated once after training; synchronized measurements are exploratory and vary with load. ORYON_SPARSE_EMBEDDING=1 also changes optimizer and dynamics, so it does not by itself isolate the effect of sparsity.
"""Modelo de ventana sobre WikiText-2 con entrenamiento corto opcional.
Requiere torch con CUDA, huggingface_hub y pyarrow. Para verificar el recorrido
fija ORYON_VERIFY_SHORT=1; el modo normal entrega
una receta más amplia para el lector, no se ejecutó aquí. Opcionalmente fija
ORYON_SPARSE_EMBEDDING=1 para SparseAdam en embeddings y AdamW sin decay para
las capas densas. Las dinámicas no son idénticas a las de un solo AdamW.
Fuente Salesforce/wikitext, wikitext-2-raw-v1, revisión y SHA-256 fijados. La
ficha enumera CC BY-SA 3.0 y GFDL, mientras su descripción menciona CC BY-SA
4.0: comprueba las condiciones y atribución de la versión antes de redistribuir.
No se garantiza reproducir el vocabulario o las cifras del artículo original.
"""
import hashlib
import json
import math
import os
import random
import re
import time
import unicodedata
from collections import Counter
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
import torch
import torch.nn as nn
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
REPO = 'Salesforce/wikitext'
REVISION = 'b08601e04326c79dfdd32d625aee71d232d685c3'
FILES = {
'train': ('wikitext-2-raw-v1/train-00000-of-00001.parquet', 'e83889baabc497075506f91975be5fac0d45c5290b6b20582c8cd1e853d0c9f7'),
'validation': ('wikitext-2-raw-v1/validation-00000-of-00001.parquet', '204929b7ff9d6184953f867dedb860e40aa69c078fc1e54b3baaa8fb28511c4c'),
'test': ('wikitext-2-raw-v1/test-00000-of-00001.parquet', '5f1bea067869d04849c0f975a2b29c4ff47d867f484f5010ea5e861eab246d91'),
}
PATTERN = re.compile(r"\w+(?:['’]\w+)*|[^\w\s]", re.UNICODE)
SEED = 17050
WINDOW, EMBED, HIDDEN = 3, 64, 128
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
SPARSE = os.environ.get('ORYON_SPARSE_EMBEDDING') == '1'
BATCH = 64 if SHORT else 256
EPOCHS = 1 if SHORT else 3
MAX_STEPS = 4 if SHORT else None
CAP = 1000 if SHORT else 33000
OUT = Path(os.environ.get('ORYON_OUTPUT', 'nplm_wikitext_output'))
UNK, EOS, BOS = '<unk>', '</s>', '<s>'
torch.set_num_threads(1)
if not torch.cuda.is_available():
raise RuntimeError('Este laboratorio requiere CUDA.')
DEVICE = torch.device('cuda')
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed_all(SEED)
def tokenize(text):
return PATTERN.findall(unicodedata.normalize('NFC', text).lower())
def checked_file(split):
filename, expected = FILES[split]
path = hf_hub_download(repo_id=REPO, repo_type='dataset', revision=REVISION, filename=filename)
digest = hashlib.sha256()
with open(path, 'rb') as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(chunk)
if digest.hexdigest() != expected:
raise ValueError('Hash inesperado: ' + filename)
return path
def read_data():
owners, excluded, result = {}, Counter(), {}
limits = {'train': 4096, 'validation': 1024, 'test': 1024} if SHORT else {}
for split in ('train', 'validation', 'test'):
paragraphs, token_count = [], 0
path = checked_file(split)
for batch in pq.ParquetFile(path).iter_batches(batch_size=64, columns=['text']):
for text in batch.column(0).to_pylist():
if split in limits and token_count >= limits[split]:
break
tokens = tokenize(text or '')
if not tokens:
continue
key = hashlib.sha256('\x00'.join(tokens).encode('utf-8')).hexdigest()
if key in owners and owners[key] != split:
excluded[split] += 1
continue
if split in limits:
remaining = limits[split] - token_count
tokens = tokens[:remaining]
# La huella identifica la fila completa incluso si el modo corto
# recorta su final; solo se registra una fila aceptada.
owners.setdefault(key, split)
paragraphs.append(tokens)
token_count += len(tokens)
if split in limits and token_count >= limits[split]:
break
if not paragraphs:
raise ValueError('Partición sin texto: ' + split)
result[split] = paragraphs
return result, dict(excluded)
def make_vocabulary(train):
counts = Counter(token for paragraph in train for token in paragraph)
if {UNK, EOS, BOS}.intersection(counts):
raise ValueError('Colisión entre texto y marcadores')
ordered = sorted(counts, key=lambda token: (-counts[token], token))[:CAP - 2]
return [UNK, EOS, *ordered]
def encode(paragraphs, vocabulary):
ids = {word: i for i, word in enumerate(vocabulary)}
bos = len(vocabulary)
flat, positions, unknown, count = [], [], 0, 0
for paragraph in paragraphs:
start = len(flat)
flat.extend([bos] * WINDOW)
for token in paragraph:
count += 1
unknown += token not in ids
flat.append(ids.get(token, ids[UNK]))
flat.append(ids[EOS])
positions.extend(range(start + WINDOW, len(flat)))
return {'flat': torch.tensor(flat, dtype=torch.long), 'positions': torch.tensor(positions, dtype=torch.long),
'unknown': unknown, 'tokens': count, 'paragraphs': len(paragraphs)}
def batches(data, batch_size, shuffle, generator=None):
pos = data['positions']
order = torch.randperm(len(pos), generator=generator) if shuffle else torch.arange(len(pos))
offsets = torch.arange(WINDOW, 0, -1)
for start in range(0, len(order), batch_size):
selected = pos[order[start:start + batch_size]]
yield data['flat'][selected[:, None] - offsets].to(DEVICE), data['flat'][selected].to(DEVICE)
class WindowLM(nn.Module):
def __init__(self, outputs):
super().__init__()
self.embedding = nn.Embedding(outputs + 1, EMBED, sparse=SPARSE)
self.hidden = nn.Linear(WINDOW * EMBED, HIDDEN)
self.output = nn.Linear(HIDDEN, outputs)
def features(self, x):
return torch.tanh(self.hidden(self.embedding(x).reshape(x.shape[0], -1)))
def forward(self, x):
return self.output(self.features(x))
@torch.inference_mode()
def evaluate(model, data):
model.eval()
total, count = 0., 0
for x, y in batches(data, BATCH, shuffle=False):
loss = F.cross_entropy(model(x), y, reduction='sum')
if not torch.isfinite(loss):
raise ValueError('Pérdida no finita')
total += float(loss.item())
count += len(y)
if count != len(data['positions']):
raise ValueError('Faltan eventos en evaluación')
return {'events': count, 'mean_nats': total / count, 'ppl': math.exp(total / count)}
@torch.inference_mode()
def benchmark(model, data):
model.eval()
x, y = next(batches(data, BATCH, shuffle=False))
def features_only():
return model.features(x)
def full_inference():
return F.cross_entropy(model(x), y)
for _ in range(3):
features_only()
full_inference()
torch.cuda.synchronize()
timings = {}
for name, fn in [('features', features_only), ('features_logits_loss', full_inference)]:
samples = []
for _ in range(5):
torch.cuda.synchronize()
start = time.perf_counter()
fn()
torch.cuda.synchronize()
samples.append(time.perf_counter() - start)
timings[name] = samples
return {'batch': len(y), 'dtype': str(model.embedding.weight.dtype), 'samples_seconds': timings,
'limitation': 'Inferencia sin backward; rutas distintas, no entrenamientos equivalentes.'}
def main():
paragraphs, excluded = read_data()
vocabulary = make_vocabulary(paragraphs['train'])
data = {split: encode(paragraphs[split], vocabulary) for split in paragraphs}
del paragraphs
model = WindowLM(len(vocabulary)).to(DEVICE)
if SPARSE:
optimizers = [torch.optim.SparseAdam(model.embedding.parameters(), lr=.001),
torch.optim.AdamW(list(model.hidden.parameters()) + list(model.output.parameters()),
lr=.001, weight_decay=0.)]
else:
optimizers = [torch.optim.AdamW(model.parameters(), lr=.001, weight_decay=0.)]
generator = torch.Generator().manual_seed(SEED)
history = []
torch.cuda.reset_peak_memory_stats()
for epoch in range(EPOCHS):
model.train()
torch.cuda.synchronize()
start = time.perf_counter()
total, count, steps = 0., 0, 0
for x, y in batches(data['train'], BATCH, shuffle=True, generator=generator):
for opt in optimizers:
opt.zero_grad(set_to_none=True)
loss = F.cross_entropy(model(x), y)
if not torch.isfinite(loss):
raise ValueError('Pérdida de entrenamiento no finita')
loss.backward()
if SPARSE and not model.embedding.weight.grad.is_sparse:
raise ValueError('Se esperaba gradiente sparse del embedding')
for param in model.parameters():
if param.grad is not None:
values = param.grad.coalesce().values() if param.grad.is_sparse else param.grad
if not torch.isfinite(values).all():
raise ValueError('Gradiente no finito antes de la actualización')
for opt in optimizers:
opt.step()
total += float(loss.item()) * len(y)
count += len(y)
steps += 1
if MAX_STEPS is not None and steps >= MAX_STEPS:
break
torch.cuda.synchronize()
seconds = time.perf_counter() - start
validation = evaluate(model, data['validation'])
history.append({'epoch': epoch + 1, 'steps': steps, 'train_events': count,
'train_mean_nats': total / count, 'train_seconds': seconds,
'validation': validation})
print('Época', history[-1])
test = evaluate(model, data['test'])
timing = benchmark(model, data['validation'])
result = {'short': SHORT, 'sparse_embedding': SPARSE, 'seed': SEED,
'dataset': REPO, 'revision': REVISION, 'files': FILES,
'tokenization': 'NFC, lower, regex declarada; cada fila no vacía termina en EOS',
'vocabulary_size': len(vocabulary), 'duplicates_excluded_cross_split': excluded,
'splits': {name: {key: value for key, value in split.items() if key not in ('flat', 'positions')}
for name, split in data.items()},
'window': WINDOW, 'embedding': EMBED, 'hidden': HIDDEN, 'batch': BATCH,
'history': history, 'test': test, 'benchmark': timing,
'gpu': torch.cuda.get_device_name(), 'torch': torch.__version__, 'cuda': torch.version.cuda,
'peak_allocated_bytes': torch.cuda.max_memory_allocated(),
'limitations': 'Semillas fijas sin promesa de reproducibilidad bit a bit entre versiones; '
'los tiempos dependen de la carga. Se excluyen entre splits las filas '
'normalizadas completas con hash repetido; el modo corto puede recortar '
'el final de una fila aceptada. No se detectan solapamientos parciales.'}
OUT.mkdir(parents=True, exist_ok=True)
(OUT / 'metrics.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
print('Test:', test, '| benchmark de inferencia:', timing)
print('Resultado:', OUT / 'metrics.json')
del model, optimizers
torch.cuda.empty_cache()
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
Step 1 of 3. What derivative does occurrence j contribute to the matrix?
import numpy as np
def embedding_backward(ids, dout, V):
passFurther connections
The hidden network and its backward pass revisit Multilayer perceptron and Backpropagation. The input table also appears in later models; output organization, weight sharing and how much history the model can access are distinct choices. Cost or quality comparison makes sense only after fixing those choices and evaluated events.