Module contents
Lesson 5 of 26Core 95 min

Next-token prediction: the causal objective at scale

Formalize causal pretraining as maximum likelihood and implement shifted labels, loss masks, document boundaries, and correct token normalization under gradient accumulation. Analyze loss, exposure bias, planning, and multi-token prediction.

After this lesson you can

  • Derive the causal objective and show that its optimum matches the data conditional, with excess loss equal to mean KL divergence.
  • Implement causal loss with shifted labels, masks, ignore_index, and correct per-token normalization during gradient accumulation.
  • Analyze real-model loss by context position, token frequency, and domain, and interpret the curves.
  • Explain exposure bias and Bachmann and Nagarajan's argument about teacher forcing in planning tasks.
  • Implement multiple-token prediction heads on a small GPT and measure their effect.

Before you start

One text becomes many predictions

A story has no class label, but each position offers a problem: given the prefix, assign probability to the next observed token. The same network can process positions in parallel during training if each position attends only to its past. During generation, each new token extends the prefix and requires another prediction. In the figure, change the boundary and prompt before counting the labels that actually contribute to loss.

InteractiveOne sequence, T classification problems

Each logit at position i predicts the next label, not the input token. The final PAD label is always excluded from loss. A and C represent prompt tokens in this example. On narrow screens, scroll the tables horizontally.

Position i0123456
InputBOSABEOSBOSCEOS
LabelABEOSBOSCEOSPAD
LossNoYesYesNoNoYesNo

Select a query to see available inputs. The column is key j; an allowed cell satisfies j ≤ i and, in isolated mode, belongs to the same document.

Query i / key j0123456
✓××××××
✓✓×××××
✓✓✓××××
✓✓✓✓×××
××××✓××
××××✓✓×
××××✓✓✓

Document 1: BOS A B EOS. Document 2: BOS C EOS. “Isolated” blocks earlier keys from another document; by itself it does not remove EOS → BOS from loss. That transition, prompt tokens, answer B and EOS have independent controls. A prompt excluded from loss remains available as context when the attention mask permits it.

In a typical implementation excluded labels are replaced by ignore_index = -100. If none remain, do not divide by zero or make an update based on that mean. The sequence is an explicit example, not trained-model output.

Attention
Predict across boundary
Prompt A and C labels
EOS labels
Answer B label
Supervised targets
3 / 7
Mean loss
Divide by 3
Selected query
4: BOS
Distinguish the attention mask from the decision to supervise each target.

Maximum likelihood and excess loss

Next-token prediction fits a distribution qθ(xt∣x<t)q_\theta(x_t\mid x_{<t}). In causal language modeling, sequence probability with defined start and length factorizes as qθ(x1:T)=∏t=1Tqθ(xt∣x<t)q_\theta(x_{1:T})=\prod_{t=1}^{T}q_\theta(x_t\mid x_{<t}). The product needs a length or stopping convention if we want a distribution over sequences of different lengths.

For supervised positions MM, maximizing log-likelihood is equivalent to minimizing

L(θ)=−1∣M∣∑(i,t)∈Mlog⁡qθ(xi,t∣xi,<t).\mathcal{L}(\theta)=-\frac{1}{|M|}\sum_{(i,t)\in M}\log q_\theta(x_{i,t}\mid x_{i,<t}).

Suppose PP describes the evaluated contexts and targets, and qq has support where PP needs it. For context cc with P(c)>0P(c)>0, the definition of cross-entropy gives

Ex∼P(⋅∣c)[−log⁡q(x∣c)]=H(P(⋅∣c))+DKL(P(⋅∣c)∥q(⋅∣c)).\mathbb E_{x\sim P(\cdot\mid c)}[-\log q(x\mid c)] =H(P(\cdot\mid c))+D_{\mathrm{KL}}(P(\cdot\mid c)\Vert q(\cdot\mid c)).

Averaged over contexts, excess over conditional entropy is a mean of nonnegative KL divergences. In a family able to represent every required conditional, the minimum matches P(⋅∣c)P(\cdot\mid c) for almost every positive-probability context. Loss does not identify what the model does on prefixes outside that support. A limited architecture or imperfect optimizer also does not guarantee the minimum is reached. If qq assigns zero to a positive-probability target, loss is infinite.

The objective can reward syntactic regularities, facts, and solution patterns when they help predict text. It does not force a unique representation or guarantee each fact is true. GPT-2 studied the emergence of tasks through text and in-context examples. You can also interpret summed loss in bits as ideal code length under a probabilistic model, subject to the start and stopping convention. See likelihood and cross-entropy.

Shift once and choose boundaries

If tokens has shape (B,T) and logits has shape (B,T,V), position tt of logits[:, :-1] predicts tokens[:, 1:] at the corresponding position. The causal mask blocks future keys; the loss mask decides which targets to score. Apply ignore_index to an unsupervised target and check the library’s shift: some implementations perform it inside their loss function. Shifting in the dataset and again in the model changes the problem.

EOS may be supervised as a target and padding is usually excluded. A document’s first token can only be scored from a declared start: its own BOS, the previous EOS if a continuous stream is allowed, or another explicit context. Excluding the EOS→BOS label avoids charging that transition but does not prevent positions in the next document attending to the previous one. Real isolation also requires a segment mask or separate processing. Prompt tokens may be in context and excluded from loss.

What a correct mean means

Per-token loss accounting divides the sum of negative log probabilities by the number of valid targets, not by the number of microbatches. If microbatch jj has sum SjS_j, count njn_j, and gradient Gj=∇SjG_j=\nabla S_j, the concatenated-batch gradient is ∑jGj/∑jnj\sum_jG_j/\sum_jn_j. Averaging Gj/njG_j/n_j weights every microbatch equally and therefore weights each token in the shorter microbatch more. A per-sequence mean is another legitimate choice, but optimizes a different weighting.

InteractiveThe gradient accumulation error

Two microbatches share scalar parameter θ = ln 3: the Bernoulli model assigns p(1) = 0.75. In the first all targets are 1; in the second they are 0. Per-token gradients are −0.25 and +0.75 respectively.

Microbatch 1 token1 token · individual weight 0.50000
Microbatch 2 token9 tokens · individual weight 0.05556

Bars compare one token’s weight with the larger of the two groups’ weights; their size does not represent the microbatch’s total token count.

CalculationLossGradient
Mean of two means0.83700.2500
Mean of all tokens1.27640.6500

The first option assigns weight 1/(2n₁) or 1/(2n₂) to each token; the second assigns 1/(n₁+n₂) to all. To accumulate correctly, sum valid-token losses across both microbatches and divide by the global token count; then accumulate gradients with that shared denominator. The comparison assumes the same θ in both calculations and no intermediate update.

Here, with 1 and 9 tokens, the mean of means gives loss 0.8370 and gradient 0.2500; the global mean gives loss 1.2764 and gradient 0.6500. With equal sizes the two match. The difference also depends on group gradients: unequal lengths alone do not guarantee nonzero error.

1
9
Normalization
Selected loss
0.8370 nats / token
Selected gradient
0.2500
Full-batch gradient
0.6500
Change lengths and compare the accumulated gradient with the full-batch gradient.

For accumulation, calculate the global denominator of valid tokens in the update and divide each local sum by it before accumulating. A microbatch with no targets contributes zero if the global total is positive; if the entire total is zero, the mean is undefined. In distributed training, account for reduction: if WW processes average gradients, scaling each local sum by W/NglobalW/N_{\mathrm{global}} compensates for that average. Do not confuse this rule with a simple mean of local means.

Where surprise is concentrated

Per-token loss analysis keeps each target’s position, ID, negative log loss, and experimental context. Aggregate loss sums and token counts before calculating means. A rare piece can have high mean loss but contribute little to the total sum; a very frequent easy piece can dominate the total. Frequency measured on a reference corpus is not necessarily its pretraining frequency.

InteractiveWhere loss occurs

Each bar represents mean per-token loss in nats. Counts and examples come from a real short run; click or focus a bar to inspect it.

Positions 1 to 16

Sum 12839.76 nats over 2930 tokens from 192 documents. These pieces contribute most to the sum, not necessarily the highest mean loss.

"header" #12476380.41 nats · 42 occurrences
"title" #7260278.41 nats · 41 occurrences
"[" #75272.87 nats · 42 occurrences
"ĠHow" #1073221.19 nats · 42 occurrences
"A" #49218.04 nats · 41 occurrences

Position starts at one and uses blocks of 16; short documents do not contribute to later positions, so the curve does not isolate context effects. Frequency means occurrences in a separate sample of train splits, not pretraining frequency. Pieces are internal tokenizer representations: an isolated fragment may not be complete UTF-8.

Same text and bytes after NFC for both models, with each document scored separately. HellaSwag retains markers such as [header] and WikiText contains markers such as @-@: formatting also affects loss. The start is BOS if present and EOS otherwise; Qwen is the instruct variant used for continuation without a template. Bits/byte is comparable on this selection conditioned on those starts; per-token losses use different vocabularies. Validation splits do not guarantee the text was absent from pretraining. Check provenance and seeds in the lab.

Scored tokens
8461
Bytes of common text
36345
Bits per byte
1.138
Explore mean loss and token counts by position, reference frequency, or corpus.

Late positions include only sufficiently long documents and may belong to a different population from early ones. A decline in their loss can be consistent with use of context, but the aggregated plot alone does not identify the cause. Inherent ambiguity in data also produces irreducible loss. Compare formats and splits across corpora; repetitive text can lower the mean without improvement on tasks of interest. To compare different tokenizers, use the same strings and a common unit such as bits per byte, with declared start and reconstruction conditions.

Teacher forcing and planning

During teacher forcing the true prefix is supplied; during generation the model conditions on its own outputs. This difference, called exposure bias, allows an error to change subsequent contexts. It does not imply every sequence must degrade or that all failures are explained by accumulated errors.

InteractiveThe star graph

Explicit graph: three directed arms from S. The target is G. You make the first choice; the predictor then follows the only outgoing edge of the received vertex.

SADGBEHCFI

The dashed outline marks the target. After each step: ● outline of the received vertex and ● outline of the predicted vertex.

Teacher forcing supplies the previous correct vertex at each step, even after an incorrect prediction; the prediction row is not a generated trajectory.

Deterministic teaching model, not a trained network. Blindly choosing among three equally likely branches gives first-decision accuracy 1/3. This example illustrates the mechanism studied by Bachmann y Nagarajan; it does not prove every model fails on every graph.

Prefix received by predictor
Predictions made
0 / 3
Correct predictions shown
0 / 0
In the conditioned regime the previous true vertex is shown; in autoregression the next decision uses the model's own trajectory.

In the task of Bachmann and Nagarajan, a graph has several directed arms from a center and the target lies at a leaf. Choosing the first neighbor requires identifying the arm leading to the target. Once teacher forcing reveals the previous correct vertex, following its only outgoing edge can solve later steps without learning to choose the initial arm. In the topologies studied, autoregressive accuracy approaches 1/d1/d, where dd is the number of arms. This is a result for that family and learning procedure, not an impossibility theorem for every LLM or proof that the exact probabilistic objective cannot represent the solution.

Predicting multiple horizons

Multi-token prediction adds targets for xt+1,xt+2,…x_{t+1},x_{t+2},\ldots from the same prefix. With parallel heads, a joint loss can average cross-entropies over valid horizons. The last part of each document needs a mask to avoid predicting beyond its end; head weights affect the objective. Gloeckle and colleagues study this strategy. The sequential modules of DeepSeek-V3 use a different architecture.

In autodraft, extra heads propose multiple tokens and the main head verifies each proposal under the prefix accepted so far. On a greedy disagreement, the main head’s token is used and the remaining proposal discarded. Comparing the entire output with ordinary greedy generation checks equivalence for that deterministic procedure. The lab also reports auxiliary-head acceptance separately: the first proposal is from the main head itself and necessarily matches. This alone does not demonstrate speedup: naive verification can do more work. Preserving a stochastic sampling distribution requires an appropriate acceptance-rejection algorithm, not just comparing argmax.

Lab: causal loss from scratch

The loss mask is applied to target positions after shifting labels. In the example ID 3 represents EOS and −100 represents padding. Isolated mode excludes the first token of the second document when no separate start position is provided; stream mode scores it from the previous document’s end. Both supervise EOS and other valid targets. Random logits verify accounting; they are not outputs of a trained model.

The second test computes explicit causal attention. Blocking a boundary target in the loss does not isolate documents, so the attention mask is tested separately. The final test uses a shared Bernoulli variable and checks the global gradient by finite differences, as well as summing microbatch gradients with the same denominator. If no global denominator is provided and no valid target exists, ValueError is raised; with a positive denominator, an empty microbatch contributes zero.

[ ]Causal loss and per-token accumulationBrowser
"""Pérdida causal y gradientes, con máscaras y normalización explícitas."""
import math
import numpy as np


def causal_loss(logits, tokens, loss_mask, doc_ids=None, isolate=False, n_global=None):
    logits = np.asarray(logits, dtype=np.float64)
    tokens = np.asarray(tokens)
    loss_mask = np.asarray(loss_mask, dtype=bool)
    if logits.ndim != 3 or tokens.shape != logits.shape[:2] or loss_mask.shape != tokens.shape:
        raise ValueError('Formas incompatibles')
    if isolate and doc_ids is None:
        raise ValueError('El aislamiento requiere IDs de documento')
    target = tokens[:, 1:]
    valid = loss_mask[:, 1:] & (target != -100)
    if doc_ids is not None:
        doc_ids = np.asarray(doc_ids)
        if doc_ids.shape != tokens.shape:
            raise ValueError('Forma incorrecta de doc_ids')
        valid &= (doc_ids[:, :-1] >= 0) & (doc_ids[:, 1:] >= 0)
        if isolate:
            valid &= doc_ids[:, :-1] == doc_ids[:, 1:]
    count = int(valid.sum())
    denominator = count if n_global is None else int(n_global)
    if denominator <= 0 or denominator < count:
        raise ValueError('El denominador global debe cubrir los tokens válidos')
    vocab = logits.shape[-1]
    if np.any((target[valid] < 0) | (target[valid] >= vocab)):
        raise ValueError('Una etiqueta válida queda fuera del vocabulario')
    shifted = logits[:, :-1, :]
    maximum = shifted.max(axis=-1, keepdims=True)
    logp = shifted - maximum - np.log(np.exp(shifted - maximum).sum(axis=-1, keepdims=True))
    b, t = np.nonzero(valid)
    labels = target[b, t].astype(int)
    loss = -float(logp[b, t, labels].sum()) / denominator
    gradient = np.zeros_like(logits)
    probs = np.exp(logp[b, t])
    probs[np.arange(len(labels)), labels] -= 1
    gradient[b, t] = probs / denominator
    return loss, gradient, count, valid


def causal_attention(x, doc_ids, isolate):
    """Atención causal de juguete; cada fila válida usa solo claves permitidas."""
    x = np.asarray(x, dtype=float)
    docs = np.asarray(doc_ids)
    scores = x @ x.T / math.sqrt(x.shape[1])
    output = np.zeros_like(x)
    for i in range(len(x)):
        if docs[i] < 0:
            continue
        mask = (np.arange(len(x)) <= i) & (docs >= 0)
        if isolate:
            mask &= docs == docs[i]
        selected = scores[i, mask]
        p = np.exp(selected - selected.max())
        p /= p.sum()
        output[i] = p @ x[mask]
    return output


rng = np.random.default_rng(2005)
# ID 3 es EOS en ambos documentos; -100 marca la posición de relleno.
tokens = np.array([[1, 2, 3, 1, 3, -100]])
docs = np.array([[0, 0, 0, 1, 1, -1]])
loss_mask = np.array([[1, 1, 1, 1, 1, 0]], dtype=bool)
logits = rng.normal(size=(1, 6, 5))
packed, grad, n_packed, selected = causal_loss(logits, tokens, loss_mask, docs, isolate=True)
stream, _, n_stream, stream_mask = causal_loss(logits, tokens, loss_mask, docs, isolate=False)
assert n_packed == 3 and selected.tolist() == [[True, True, False, True, False]]
assert n_stream == 4 and stream_mask.tolist() == [[True, True, True, True, False]]
assert np.all(grad[:, -1] == 0)
prompt_mask = loss_mask.copy(); prompt_mask[0, 1] = False
assert causal_loss(logits, tokens, prompt_mask, docs, isolate=True)[2] == 2
empty_mask = np.zeros_like(loss_mask)
empty_loss, empty_grad, empty_count, _ = causal_loss(logits, tokens, empty_mask, docs, n_global=4)
assert empty_loss == 0 and empty_count == 0 and not np.any(empty_grad)
try:
    causal_loss(logits, tokens, empty_mask, docs)
except ValueError:
    pass
else:
    raise AssertionError('No existe una media con cero tokens')
eps = 1e-5
for index in np.ndindex(logits.shape):
    delta = np.zeros_like(logits)
    delta[index] = eps
    plus = causal_loss(logits + delta, tokens, loss_mask, docs, isolate=True)[0]
    minus = causal_loss(logits - delta, tokens, loss_mask, docs, isolate=True)[0]
    assert abs((plus - minus) / (2 * eps) - grad[index]) < 1e-9
print('Tokens puntuados: aislado', n_packed, '| flujo', n_stream,
      '| máscara aislada', selected.astype(int).tolist())
print('Pérdida aislada:', round(packed, 6), '| flujo:', round(stream, 6))

x = rng.normal(size=(6, 4))
original = causal_attention(x, docs[0], isolate=True)
future_changed = x.copy(); future_changed[3:] += 20
assert np.allclose(original[:3], causal_attention(future_changed, docs[0], True)[:3], atol=1e-12)
other_doc_changed = x.copy(); other_doc_changed[:3] += 20
isolated_delta = np.max(np.abs(original[3:5] - causal_attention(other_doc_changed, docs[0], True)[3:5]))
stream_delta = np.max(np.abs(causal_attention(x, docs[0], False)[3:5] - causal_attention(other_doc_changed, docs[0], False)[3:5]))
assert isolated_delta < 1e-12 and stream_delta > 1e-6
print('Atención: diferencia tras cambiar documento previo, aislado', round(isolated_delta, 6),
      '| flujo', round(stream_delta, 6))

theta = math.log(4)
def bernoulli(labels, theta):
    p = 1 / (1 + math.exp(-theta))
    losses = [-math.log(p if y else 1-p) for y in labels]
    return sum(losses), sum(p-y for y in labels)

left = bernoulli([1], theta)
right = bernoulli([0, 0, 0], theta)
wrong_loss = (left[0] + right[0] / 3) / 2
wrong_grad = (left[1] + right[1] / 3) / 2
correct_loss = (left[0] + right[0]) / 4
correct_grad = (left[1] + right[1]) / 4
joined = bernoulli([1, 0, 0, 0], theta)
micro_a = np.tile(np.array([0., theta]), (1, 2, 1))
micro_b = np.tile(np.array([0., theta]), (1, 4, 1))
loss_a, grad_a, count_a, _ = causal_loss(micro_a, np.array([[0, 1]]), np.ones((1, 2), bool), n_global=4)
loss_b, grad_b, count_b, _ = causal_loss(micro_b, np.array([[0, 0, 0, 0]]), np.ones((1, 4), bool), n_global=4)
assert count_a == 1 and count_b == 3
assert abs(loss_a + loss_b - correct_loss) < 1e-12
assert abs(grad_a[..., 1].sum() + grad_b[..., 1].sum() - correct_grad) < 1e-12
numeric = (bernoulli([1, 0, 0, 0], theta + eps)[0] - bernoulli([1, 0, 0, 0], theta - eps)[0]) / (8*eps)
assert abs(joined[0] / 4 - correct_loss) < 1e-12
assert abs(joined[1] / 4 - correct_grad) < 1e-12
assert abs(numeric - correct_grad) < 1e-10
print('Media de medias: pérdida', round(wrong_loss, 6), 'gradiente', round(wrong_grad, 6))
print('Media por token: pérdida', round(correct_loss, 6), 'gradiente', round(correct_grad, 6))

Local lab: where loss occurs

The next cell measures SmolLM2-135M base and Qwen2.5-0.5B Instruct sequentially at pinned revisions. You need torch, transformers, huggingface_hub, and pyarrow. Missing weights or parquet files are downloaded to the Hugging Face cache. GPU weights use float16 precision; CPU uses float32. Results can vary slightly by device and library version. ORYON_OUTPUT_DIR chooses the destination, and ORYON_QUICK=1 reduces the sample to 64 validation texts and 500 reference texts per corpus. Normal mode uses up to 200 and 3,000 respectively; adjust ORYON_EVAL_PER_DOMAIN, ORYON_REFERENCE_PER_DOMAIN, ORYON_MAX_CHARS, and ORYON_MAX_TOKENS.

Texts come from validation splits of WikiText-2 raw, HellaSwag, and ARC Easy. They are prose, activity contexts, and multiple-choice questions, not a controlled domain comparison. HellaSwag retains markers such as [header] and WikiText contains markers such as @-@. They are part of evaluated text and affect loss. Rows are selected with explicit seeds, outer whitespace is stripped, a common character prefix taken, and NFC applied before tokenization. Only strings exactly reconstructed by both tokenizers and fitting both models are accepted. Revisions, parquet hashes, row indices, rejections, and text hashes are recorded. Validation is separate from published training splits, but we do not know whether the models saw those texts during pretraining.

Each text is scored separately, without attention to other documents and without adding final EOS to labels. The first prediction is conditioned on BOS if available, otherwise EOS; Qwen instruct receives continuous text without a chat template. Losses over all text tokens are summed and divided by their common UTF-8 bytes and the natural logarithm of two. Bits per byte compare the same strings under those declared starts. Mean token losses use different vocabulary units and are not directly comparable. The model materializes sequence logits, and the cell computes log-sum-exp in blocks to avoid another full single-precision copy.

Each ID’s frequency is counted in a separate sample of the three train splits, not in model pretraining data. Losses are grouped by position, frequency band, and corpus, with token and document counts printed. For each group, examples are pieces contributing most to the sum, not necessarily those with highest mean loss. Late positions include only sufficiently long documents. Differences between bars alone do not prove improvement from context. Internal ByteLevel pieces should not be decoded separately as though each were complete UTF-8.

[ ]Anatomy of loss in two modelsLocal GPU
"""Pérdida causal por posición, frecuencia de referencia y corpus."""
import gc
import hashlib
import json
import math
import os
import platform
import random
import unicodedata
from collections import Counter, defaultdict
from importlib.metadata import version
from pathlib import Path

import pyarrow.parquet as pq
import torch
from huggingface_hub import hf_hub_download
from transformers import AutoModelForCausalLM, AutoTokenizer

SEED = 2005
QUICK = os.environ.get('ORYON_QUICK') == '1'
N_EVAL = int(os.environ.get('ORYON_EVAL_PER_DOMAIN', '64' if QUICK else '200'))
N_REFERENCE = int(os.environ.get('ORYON_REFERENCE_PER_DOMAIN', '500' if QUICK else '3000'))
MAX_CHARS = int(os.environ.get('ORYON_MAX_CHARS', '256' if QUICK else '512'))
MAX_TOKENS = int(os.environ.get('ORYON_MAX_TOKENS', '256' if QUICK else '512'))
OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', './anatomia-perdida-output'))
OUT.mkdir(parents=True, exist_ok=True)
torch.manual_seed(SEED)
torch.set_num_threads(1)
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
DTYPE = torch.float16 if DEVICE.type == 'cuda' else torch.float32
MODELS = [
    ('HuggingFaceTB/SmolLM2-135M', '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'),
    ('Qwen/Qwen2.5-0.5B-Instruct', '7ae557604adf67be50417f59c2c2f167def9a775'),
]
CORPORA = [
    {'label':'WikiText-2', 'repo':'Salesforce/wikitext',
     'revision':'b08601e04326c79dfdd32d625aee71d232d685c3',
     'folder':'wikitext-2-raw-v1', 'columns':['text'],
     'url':'https://huggingface.co/datasets/Salesforce/wikitext'},
    {'label':'HellaSwag', 'repo':'Rowan/hellaswag',
     'revision':'218ec52e09a7e7462a5400043bb9a69a41d06b76',
     'folder':'data', 'columns':['ctx'],
     'url':'https://huggingface.co/datasets/Rowan/hellaswag'},
    {'label':'ARC Easy', 'repo':'allenai/ai2_arc',
     'revision':'210d026faf9955653af8916fad021475a3f00453',
     'folder':'ARC-Easy', 'columns':['question','choices'],
     'url':'https://huggingface.co/datasets/allenai/ai2_arc'},
]

def sha(path):
    with open(path, 'rb') as f:
        return hashlib.file_digest(f, 'sha256').hexdigest()

def text_of(row, label):
    if label == 'WikiText-2':
        text = row['text']
    elif label == 'HellaSwag':
        text = row['ctx']
    else:
        choices = row['choices']
        text = row['question'] + '\n' + '\n'.join(
            f'{tag}. {value}' for tag, value in zip(choices['label'], choices['text']))
    # Corta la misma cadena por caracteres antes de tokenizar; no se añaden
    # respuestas de referencia ni se separan documentos con atención compartida.
    return unicodedata.normalize('NFC', text.strip()[:MAX_CHARS])

def load_rows(spec, split):
    filename = spec['folder'] + '/' + split + '-00000-of-00001.parquet'
    path = hf_hub_download(spec['repo'], filename, revision=spec['revision'], repo_type='dataset')
    rows = pq.read_table(path, columns=spec['columns']).to_pylist()
    return rows, {'filename':filename, 'sha256':sha(path), 'rows':len(rows)}

tokenizers = [AutoTokenizer.from_pretrained(name, revision=revision) for name, revision in MODELS]
reference_docs, selected_docs, provenance = [], [], []
for domain_index, spec in enumerate(CORPORA):
    train_rows, train_meta = load_rows(spec, 'train')
    eval_rows, eval_meta = load_rows(spec, 'validation')
    train_order = list(range(len(train_rows)))
    eval_order = list(range(len(eval_rows)))
    random.Random(SEED + domain_index).shuffle(train_order)
    random.Random(SEED + 100 + domain_index).shuffle(eval_order)
    ref = []
    for row_id in train_order:
        text = text_of(train_rows[row_id], spec['label'])
        if len(text) >= 5:
            ref.append((domain_index, row_id, text))
        if len(ref) >= N_REFERENCE:
            break
    chosen, rejected = [], Counter()
    for row_id in eval_order:
        text = text_of(eval_rows[row_id], spec['label'])
        if len(text) < 5:
            rejected['corta'] += 1
            continue
        all_ids = [t(text, add_special_tokens=False)['input_ids'] for t in tokenizers]
        if any(not ids or len(ids) > MAX_TOKENS for ids in all_ids):
            rejected['sin_tokens_o_excede_limite'] += 1
            continue
        if any(t.decode(ids, clean_up_tokenization_spaces=False) != text for t, ids in zip(tokenizers, all_ids)):
            rejected['roundtrip_distinto'] += 1
            continue
        chosen.append({'domain':domain_index, 'row':row_id, 'text':text, 'ids':all_ids})
        if len(chosen) >= N_EVAL:
            break
    if len(chosen) < N_EVAL:
        raise ValueError(f'No hay suficientes cadenas válidas en {spec["label"]}')
    reference_docs.extend(ref)
    selected_docs.extend(chosen)
    provenance.append({**spec, 'train':train_meta, 'validation':eval_meta,
        'reference_rows':[i for _, i, _ in ref], 'evaluation_rows':[x['row'] for x in chosen],
        'rejected':dict(rejected)})
    print(spec['label'], 'referencia train:', len(ref), 'validación:', len(chosen),
          'rechazos:', dict(rejected), flush=True)
    del train_rows, eval_rows

def frequency_group(n):
    if n == 0: return '0'
    if n == 1: return '1'
    if n <= 5: return '2 a 5'
    if n <= 20: return '6 a 20'
    if n <= 100: return '21 a 100'
    return 'más de 100'

def summarize(records, tokenizer):
    groups = {'position':defaultdict(list), 'frequency':defaultdict(list), 'domain':defaultdict(list)}
    for record in records:
        domain, row, position, token_id, loss, reference_count = record
        groups['position'][str((position - 1) // 16)].append(record)
        groups['frequency'][frequency_group(reference_count)].append(record)
        groups['domain'][str(domain)].append(record)
    output = {}
    for mode, mapping in groups.items():
        results = []
        for key, items in mapping.items():
            total = math.fsum(r[4] for r in items)
            by_token = defaultdict(lambda:[0., 0])
            for r in items:
                by_token[r[3]][0] += r[4]
                by_token[r[3]][1] += 1
            top = sorted(by_token.items(), key=lambda x:(-x[1][0], x[0]))[:5]
            results.append({'key':key, 'count':len(items), 'loss_sum':total, 'mean_loss':total/len(items),
                'documents':len({(r[0],r[1]) for r in items}),
                'top':[{'id':int(i), 'piece':tokenizer.convert_ids_to_tokens(int(i)),
                        'loss_sum':v[0], 'count':v[1]} for i,v in top]})
        if mode == 'position': results.sort(key=lambda x:int(x['key']))
        if mode == 'domain': results.sort(key=lambda x:int(x['key']))
        if mode == 'frequency':
            order = ['0','1','2 a 5','6 a 20','21 a 100','más de 100']
            results.sort(key=lambda x:order.index(x['key']))
        output[mode] = results
    return output

reports = []
for model_index, (name, revision) in enumerate(MODELS):
    tokenizer = tokenizers[model_index]
    frequencies = Counter()
    for _, _, text in reference_docs:
        frequencies.update(tokenizer(text, add_special_tokens=False)['input_ids'])
    print('Modelo:', name, 'tokens de referencia:', sum(frequencies.values()), flush=True)
    model = AutoModelForCausalLM.from_pretrained(name, revision=revision, dtype=DTYPE).to(DEVICE).eval()
    start_id = tokenizer.bos_token_id if tokenizer.bos_token_id is not None else tokenizer.eos_token_id
    if start_id is None: raise ValueError('Se necesita un token inicial declarado')
    records, document_results = [], []
    with torch.inference_mode():
        for doc in selected_docs:
            ids = doc['ids'][model_index]
            x = torch.tensor([[start_id] + ids[:-1]], device=DEVICE)
            target = torch.tensor(ids, device=DEVICE)
            logits = model(x, use_cache=False).logits[0]
            losses = []
            for first in range(0, len(ids), 16):
                last = min(first+16, len(ids))
                chunk = logits[first:last].float()
                true = chunk.gather(1, target[first:last,None]).squeeze(1)
                losses.extend((torch.logsumexp(chunk,dim=1)-true).cpu().tolist())
            assert len(losses) == len(ids) and all(math.isfinite(v) and v >= 0 for v in losses)
            document_results.append({'domain':doc['domain'], 'row':doc['row'], 'bytes':len(doc['text'].encode('utf-8')),
                'tokens':len(ids), 'nll_nats':math.fsum(losses),
                'text_sha256':hashlib.sha256(doc['text'].encode('utf-8')).hexdigest()})
            records.extend([[doc['domain'], doc['row'], i+1, token_id, float(loss), frequencies[token_id]]
                            for i, (token_id,loss) in enumerate(zip(ids,losses))])
            del x, target, logits, chunk, true
    total_loss = math.fsum(x['nll_nats'] for x in document_results)
    total_bytes = sum(x['bytes'] for x in document_results)
    total_tokens = sum(x['tokens'] for x in document_results)
    assert total_bytes > 0 and total_tokens == len(records)
    summary = summarize(records, tokenizer)
    for mode in summary.values():
        assert sum(x['count'] for x in mode) == total_tokens
        assert math.isclose(math.fsum(x['loss_sum'] for x in mode), total_loss, rel_tol=1e-10, abs_tol=1e-8)
    result = {'name':name, 'revision':revision, 'tokenizer_revision':revision,
        'start_id':start_id, 'start_kind':'BOS' if tokenizer.bos_token_id is not None else 'EOS',
        'reference_tokens':sum(frequencies.values()), 'tokens':total_tokens,
        'bytes':total_bytes, 'nll_nats':total_loss, 'mean_nll_nats_per_token':total_loss/total_tokens,
        'bits_per_byte':total_loss/(math.log(2)*total_bytes), 'documents':document_results,
        'record_columns':['domain','row','position_1_based','token_id','nll_nats','reference_frequency'],
        'records':records, 'groups':summary}
    print('  tokens:', total_tokens, 'bytes:', total_bytes, 'NLL/token:', total_loss/total_tokens,
          'bits/byte:', result['bits_per_byte'], flush=True)
    for mode, bins in summary.items():
        for item in bins:
            print(' ', mode, item['key'], 'n:', item['count'], 'documentos:', item['documents'],
                  'NLL media:', item['mean_loss'], 'suma:', item['loss_sum'],
                  'piezas que más suman:', [(t['id'], t['piece'], t['count'], t['loss_sum']) for t in item['top']], flush=True)
    reports.append(result)
    del model
    gc.collect()
    if DEVICE.type == 'cuda': torch.cuda.empty_cache()
assert [[(d['domain'],d['row'],d['bytes'],d['text_sha256']) for d in m['documents']] for m in reports][0] == \
       [[(d['domain'],d['row'],d['bytes'],d['text_sha256']) for d in m['documents']] for m in reports][1]
report = {'seed':SEED, 'quick':QUICK, 'device':str(DEVICE), 'dtype':str(DTYPE),
    'python':platform.python_version(), 'torch':version('torch'), 'transformers':version('transformers'),
    'pyarrow':version('pyarrow'), 'selection':{'max_chars':MAX_CHARS, 'max_tokens_per_model':MAX_TOKENS,
    'normalization':'NFC', 'context':'BOS si existe, si no EOS; sin plantilla, cada documento separado',
    'cut':'prefijo común de caracteres antes de codificar; EOS final no puntuado',
    'reference':'train, frecuencias observadas en muestra separada, no datos de preentrenamiento'},
    'corpora':provenance, 'models':reports}
(OUT / 'loss-data.json').write_text(json.dumps(report, ensure_ascii=False, separators=(',',':')), encoding='utf-8')
print('Datos:', OUT / 'loss-data.json', flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: heads on a small GPT

The original design links to the GPT from m18. As its implementation was not available here, this cell supplies a self-contained causal byte decoder with masked attention, learned positions, and a main head tied to embeddings. It does not claim to be that lesson’s checkpoint. Documents are segmented separately, with no windows crossing boundaries. We train one-head and three-head variants, checking that the initial trunk and windows match. Joint loss averages horizons and validation compares only the next byte. Extra heads add parameters, so the comparison does not hold the exact parameter budget constant.

You need torch and pyarrow. The cell downloads TinyStories parquet with pinned revision and SHA-256. Normal mode uses the first official training file and official validation split, removing exact duplicates between them. ORYON_QUICK=1 splits the official validation file into two subsets only for a flow test: do not confuse them with official splits. ORYON_DATA_DIR and ORYON_OUTPUT_DIR control storage; ORYON_MTP_STEPS adjusts the budget. Four test steps cannot establish that one variant is better.

[ ]Multiple heads and greedy autodraftLocal GPU
"""GPT causal autocontenido, cabezas paralelas y autodraft greedy."""
import gc
import hashlib
import json
import math
import os
import random
import urllib.request
from pathlib import Path

import pyarrow.parquet as pq
import torch
from torch import nn
from torch.nn import functional as F

REVISION = 'f54c09fd23315a6f9c86f9dc80f725de7d8f9c64'
BASE = f'https://huggingface.co/datasets/roneneldan/TinyStories/resolve/{REVISION}/data/'
FILES = {
    'train': ('train-00000-of-00004-2d5a1467fff1081b.parquet', 248731111,
              '77cf780cebe52b6e83e3a2ac84bc56d8059363113e41d17a023f1d8b2ed0fc0b'),
    'validation': ('validation-00000-of-00001-869c898b519ad725.parquet', 9989127,
                   '33406a6206554cfc279c29c11f4df51528af487aa1a602b075566fc83c49dcab'),
}
QUICK = os.environ.get('ORYON_QUICK') == '1'
OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', './mtp-output'))
OUT.mkdir(parents=True, exist_ok=True)
DATA = Path(os.environ.get('ORYON_DATA_DIR', str(OUT / 'data')))
DATA.mkdir(parents=True, exist_ok=True)


def file_hash(path):
    with path.open('rb') as stream:
        return hashlib.file_digest(stream, 'sha256').hexdigest()


def parquet_file(split):
    filename, size, digest = FILES[split]
    path = DATA / filename
    if not path.exists() or path.stat().st_size != size or file_hash(path) != digest:
        tmp = path.with_suffix(path.suffix + '.part')
        print('Descargando', split, 'a', tmp, flush=True)
        urllib.request.urlretrieve(BASE + filename, tmp)
        if tmp.stat().st_size != size or file_hash(tmp) != digest:
            tmp.unlink(missing_ok=True)
            raise ValueError('Tamaño o SHA-256 del parquet incorrectos')
        tmp.replace(path)
    return path


def documents(path, limit, seen):
    """Recorre filas y descarta duplicados exactos entre particiones."""
    result = []
    for batch in pq.ParquetFile(path).iter_batches(batch_size=512, columns=['text']):
        for text in batch.column(0).to_pylist():
            if not isinstance(text, str):
                continue
            raw = text.encode('utf-8')
            digest = hashlib.sha256(raw).digest()
            if digest in seen or len(raw) < 64:
                continue
            seen.add(digest)
            result.append(raw)
            if len(result) >= limit:
                return result
    return result


def prepare():
    seen = set()
    if QUICK:
        # El fichero oficial de validación se divide solo para la prueba de flujo.
        # Ningún resultado de esa división debe llamarse validación oficial.
        pool = documents(parquet_file('validation'), 96, seen)
        train, val = pool[:64], pool[64:96]
        provenance = 'validación oficial dividida en dos para la prueba corta'
    else:
        train = documents(parquet_file('train'), 20000, seen)
        val = documents(parquet_file('validation'), 512, seen)
        provenance = 'train y validation oficiales, deduplicación exacta'
    if not train or not val:
        raise ValueError('La preparación necesita documentos en ambas particiones')
    return train, val, provenance


class Block(nn.Module):
    def __init__(self, width, heads):
        super().__init__()
        self.norm1 = nn.LayerNorm(width)
        self.attn = nn.MultiheadAttention(width, heads, batch_first=True, dropout=0.0)
        self.norm2 = nn.LayerNorm(width)
        self.mlp = nn.Sequential(nn.Linear(width, 4 * width), nn.GELU(), nn.Linear(4 * width, width))

    def forward(self, x):
        n = x.shape[1]
        mask = torch.ones(n, n, dtype=torch.bool, device=x.device).triu(1)
        a = self.norm1(x)
        x = x + self.attn(a, a, a, attn_mask=mask, need_weights=False)[0]
        return x + self.mlp(self.norm2(x))


class ByteGPT(nn.Module):
    def __init__(self, context, width, layers, heads, horizons):
        super().__init__()
        self.context = context
        self.tokens = nn.Embedding(256, width)
        self.positions = nn.Embedding(context, width)
        self.blocks = nn.ModuleList(Block(width, heads) for _ in range(layers))
        self.norm = nn.LayerNorm(width)
        self.apply(self.initialize)
        self.aux = nn.ModuleList(nn.Linear(width, 256, bias=False) for _ in range(horizons - 1))
        self.aux.apply(self.initialize)

    @staticmethod
    def initialize(module):
        if isinstance(module, (nn.Linear, nn.Embedding)):
            nn.init.normal_(module.weight, mean=0.0, std=0.02)
            if isinstance(module, nn.Linear) and module.bias is not None:
                nn.init.zeros_(module.bias)

    def forward(self, tokens):
        n = tokens.shape[1]
        if not 0 < n <= self.context:
            raise ValueError('Longitud fuera del contexto')
        x = self.tokens(tokens) + self.positions(torch.arange(n, device=tokens.device))
        for block in self.blocks:
            x = block(x)
        x = self.norm(x)
        return [F.linear(x, self.tokens.weight)] + [head(x) for head in self.aux]


def batches(docs, count, context, horizon, seed, device):
    generator = random.Random(seed)
    eligible = [doc for doc in docs if len(doc) >= context + horizon]
    if not eligible:
        raise ValueError('No hay documentos suficientes para la ventana elegida')
    while True:
        samples = []
        for _ in range(count):
            doc = generator.choice(eligible)
            start = generator.randrange(len(doc) - context - horizon + 1)
            samples.append(list(doc[start:start + context + horizon]))
        yield torch.tensor(samples, dtype=torch.long, device=device)


def loss_by_head(model, batch, horizon):
    n = model.context
    logits = model(batch[:, :n])
    return [F.cross_entropy(logits[k - 1].reshape(-1, 256), batch[:, k:k + n].reshape(-1))
            for k in range(1, horizon + 1)]


@torch.inference_mode()
def evaluate(model, docs, horizon, device, count):
    model.eval()
    # Compartimos los mismos comienzos de ventana para ambas variantes.
    generator = batches(docs, 2, model.context, 3, 5005, device)
    values = [float(loss_by_head(model, next(generator), horizon)[0]) for _ in range(count)]
    return sum(values) / len(values)


@torch.inference_mode()
def greedy(model, prefix, length, device):
    generated = list(prefix)
    for _ in range(length):
        x = torch.tensor([generated[-model.context:]], dtype=torch.long, device=device)
        generated.append(int(model(x)[0][0, -1].argmax()))
    return generated


@torch.inference_mode()
def autodraft(model, prefix, length, device):
    """Verifica cada propuesta frente a la cabeza principal, sin suponer speedup."""
    generated = list(prefix)
    proposed = accepted = aux_proposed = aux_accepted = 0
    while len(generated) < len(prefix) + length:
        x = torch.tensor([generated[-model.context:]], dtype=torch.long, device=device)
        guesses = [int(logits[0, -1].argmax()) for logits in model(x)]
        for index, guess in enumerate(guesses):
            if len(generated) >= len(prefix) + length:
                break
            x = torch.tensor([generated[-model.context:]], dtype=torch.long, device=device)
            actual = int(model(x)[0][0, -1].argmax())
            proposed += 1
            if index > 0:
                aux_proposed += 1
            if guess != actual:
                generated.append(actual)
                break
            accepted += 1
            if index > 0:
                aux_accepted += 1
            generated.append(guess)
    return generated, accepted, proposed, aux_accepted, aux_proposed


torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train, validation, provenance = prepare()
context, width, layers, attention_heads = (32, 48, 2, 4) if QUICK else (128, 192, 4, 6)
steps = int(os.environ.get('ORYON_MTP_STEPS', '4' if QUICK else '1000'))
if steps < 1:
    raise ValueError('ORYON_MTP_STEPS debe ser positivo')
batch_size = 2 if QUICK else 12
evaluation_batches = 3 if QUICK else 64
results = []
initial_trunk_hash = None
for horizon in (1, 3):
    torch.manual_seed(2005)
    if device.type == 'cuda':
        torch.cuda.manual_seed_all(2005)
    model = ByteGPT(context, width, layers, attention_heads, horizon).to(device)
    initial = hashlib.sha256()
    for name, value in model.state_dict().items():
        if not name.startswith('aux.'):
            initial.update(value.detach().cpu().contiguous().numpy().tobytes())
    if initial_trunk_hash is None:
        initial_trunk_hash = initial.hexdigest()
    else:
        assert initial.hexdigest() == initial_trunk_hash, 'Los troncos iniciales no coinciden'
    # Las ventanas de las dos variantes proceden del mismo flujo y tienen la
    # longitud de la variante de tres horizontes para mantenerlas idénticas.
    generator = batches(train, batch_size, context, 3, 5004, device)
    optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
    model.train()
    for step in range(steps):
        batch = next(generator)
        optimizer.zero_grad(set_to_none=True)
        losses = loss_by_head(model, batch, horizon)
        loss = torch.stack(losses).mean()
        loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()
    val_loss = evaluate(model, validation, horizon, device, evaluation_batches)
    record = {'horizons': horizon, 'steps': steps, 'heldout_next_byte_nll': val_loss}
    if horizon > 1:
        prefix = list(validation[0][:min(16, context)])
        expected = greedy(model, prefix, 12, device)
        actual, accepted, proposed, aux_accepted, aux_proposed = autodraft(model, prefix, 12, device)
        assert actual == expected
        record.update({'accepted': accepted, 'proposed': proposed,
                       'acceptance': accepted / proposed if proposed else None,
                       'aux_accepted': aux_accepted, 'aux_proposed': aux_proposed,
                       'aux_acceptance': aux_accepted / aux_proposed if aux_proposed else None,
                       'greedy_equal': actual == expected})
    print('Horizontes:', horizon, '| pasos:', steps, '| NLL retenida:', round(val_loss, 6),
          '| autodraft:', {k: record[k] for k in ('accepted', 'proposed', 'aux_accepted', 'aux_proposed', 'greedy_equal') if k in record}, flush=True)
    results.append(record)
    del loss, losses, batch, optimizer, model
    gc.collect()
    if device.type == 'cuda':
        torch.cuda.empty_cache()

report = {'revision': REVISION, 'quick': QUICK, 'provenance': provenance, 'seed': 2005,
          'initial_trunk_sha256': initial_trunk_hash,
          'train_documents': len(train), 'validation_documents': len(validation),
          'context': context, 'width': width, 'layers': layers, 'attention_heads': attention_heads,
          'batch_size': batch_size, 'results': results}
(OUT / 'mtp-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print('Informe:', OUT / 'mtp-report.json', flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofThe causal-loss optimum
Prove: Prove the expected per-token loss decomposition for positive-probability contexts.
0
Assume a family capable of expressing the data conditional; if q is zero where P is positive, loss is infinite.

Step 1 of 3. What results from adding and subtracting the log of the true conditional?

NumericOne denominator for all
Two microbatches have 100 and 900 valid tokens, with mean losses 3.0 and 2.0 respectively. What is the correct mean loss per token for the combined batch?
QuizEOS, start, and padding
Documents are packed with EOS. You want to score them independently, keeping EOS as a target and excluding padding. Which option correctly expresses the decision?
CodeLocal sum, global denominator
Implement causal_lm_loss(logits, tokens, loss_mask, n_tokens_global). logits has shape (B,T,V), and tokens and loss_mask have shape (B,T); the mask refers to the target. Compare logits[:, :-1] with tokens[:, 1:], exclude targets with ID -100 or a false mask, and return the local cross-entropy sum divided by n_tokens_global. The global denominator is positive even if the local microbatch has no targets. Use stable log-sum-exp.
import numpy as np

def causal_lm_loss(logits, tokens, loss_mask, n_tokens_global):
  pass
Shift+Enter to run
Key idea

Next-token prediction turns text into causal supervision. Statistical interpretation depends on support and training quality; implementation depends on shifting, masking, and normalizing exactly the intended positions.