Module contents
Lesson 6 of 26Core 100 min

Bidirectional and denoising objectives: MLM, span corruption and FIM

Study BERT masked language modeling, pseudo-log-likelihood, T5 span corruption, UL2 denoisers, ELECTRA, and fill-in-the-middle. Compare a mini BERT and mini GPT with probes and generation under a comparable budget.

After this lesson you can

  • Implement BERT's 80/10/10 masking rule and explain its relationship to the pretraining-to-use mismatch.
  • Implement sentinel-based span corruption and calculate target length compared with MLM.
  • Transform documents to fill-in-the-middle PSM and SPM formats and justify the transformation rate.
  • Compare causal and masked objectives under the same compute using linear probes, pseudo-log-likelihood, and generation.
  • Choose objectives and architectures for representations, generation, or infilling in light of empirical evidence.

Before you start

The question determines the mask

If you hide a word in the middle of a sentence, context on the right helps recover it. If you want to continue a conversation, that future does not yet exist. The same text, presented with different masks and objectives, teaches the network different tasks. Change the figure’s scheme and observe both visible positions and positions receiving loss.

InteractiveMasking lab

The sentence uses 12 teaching units, not a real tokenizer. MLM cells with · do not contribute to loss.

Input
Thenetworkreads[MASK]textandlearnstopredicttheword.

Labels by position

···the·····the··

In this sample: 1 MASK, 0 random replacements and 1 unchanged. Among chosen positions probabilities are 80%, 10% and 10%, not exact per-sentence quotas. Uniform replacement uses units from this sentence and may match the original.

Bidirectional encoder. Row: query; column: key. On mobile scroll horizontally. ✓ indicates allowed access.

i / j01234567891011
0✓✓✓✓✓✓✓✓✓✓✓✓
1✓✓✓✓✓✓✓✓✓✓✓✓
2✓✓✓✓✓✓✓✓✓✓✓✓
3✓✓✓✓✓✓✓✓✓✓✓✓
4✓✓✓✓✓✓✓✓✓✓✓✓
5✓✓✓✓✓✓✓✓✓✓✓✓
6✓✓✓✓✓✓✓✓✓✓✓✓
7✓✓✓✓✓✓✓✓✓✓✓✓
8✓✓✓✓✓✓✓✓✓✓✓✓
9✓✓✓✓✓✓✓✓✓✓✓✓
10✓✓✓✓✓✓✓✓✓✓✓✓
11✓✓✓✓✓✓✓✓✓✓✓✓

For T5, the decoder receives the shifted target with a start token: its queries are causal and can attend to all encoder positions. Sentinels represent distinct IDs; counts use these example units and exclude padding and T5 EOS.

Sources: BERT, T5 y FIM. A bidirectional mask does not imply that an MLM produces coherent autoregressive generation.

15 %
3
Supervised targets
2
Represented inputs
12
Seed
606
Compare inputs, targets, and attention under explicit corruption conventions.

BERT masked language modeling, or MLM, selects 15% of candidate tokens. Of those selected, 80% are replaced by [MASK], 10% by a random token, and 10% left unchanged. Reconstruction loss applies to all selected positions, including those left intact, and not to the rest. A random replacement can match the original token: selection and visible change are different facts.

The unchanged branch brings part of training closer to inputs without [MASK] that the encoder sees when its representations are used. Random replacement and masking prevent simply copying every input from sufficing. This motivates the design but does not guarantee every mismatch disappears. Selection supervises only part of the positions on each presentation; a 15% selection rate does not mean supervising 80% of the sequence.

Representations and pseudo-log-likelihood

In BERT, each contextual representation can use information from both sides through bidirectional attention. That access is useful for classification, retrieval, and reranking, but learned distributions for masked tokens do not automatically form the causal factorization of an autoregressive model. An iterative filling procedure can be built with an MLM; it is not the same operation as left-to-right generation from an already specified causal joint distribution.

Pseudo-log-likelihood scores a sequence by masking each position separately:

PLL⁡(x)=∑i=1Tlog⁡q(xi∣x∖i).\operatorname{PLL}(x)=\sum_{i=1}^{T}\log q(x_i\mid x_{\setminus i}).

Each term sees the remaining observations, including that position’s future. Even if those conditionals come from a consistent joint distribution, their product need not sum to one over sequences. Do not interpret exp⁡(PLL⁡)\exp(\operatorname{PLL}) as a normalized probability or directly compare its value with causal perplexity. Salazar and colleagues study this score for masked models. Tokenization, handling of special tokens, and length change the result.

RoBERTa studied a recipe including dynamic masking, more data and training, and removal of the next-sentence objective; its ablations must be read within that setup. ModernBERT shows that bidirectional encoders remain a relevant family. Choice depends on the application and its evaluation, not a universal architecture ranking.

Spans and sentinels

Span corruption replaces each selected contiguous span with a different sentinel. In T5 the encoder receives retained text and sentinels; the decoder generates removed spans, each preceded by the corresponding sentinel. Encoder attention is bidirectional and decoder attention is causal over its target. Reconstruction requires preserving order and avoiding collisions with system sentinels.

With NN original tokens, corrupted fraction rr, and mean span length μ\mu, an approximation uses rNrN removed tokens and rN/μrN/\mu spans. If the target contains removed tokens and one sentinel per span, its approximate length is rN(1+1/μ)rN(1+1/\mu), excluding a possible final sentinel or EOS. The actual count is integer and depends on rounding, document boundaries, and sampled spans. T5 studies 15% corruption and compares mean span lengths. Do not confuse this short target with MLM predicting at the original positions.

Objective mixtures and discrimination

UL2 mixture of denoisers combines regular R, sequential S, and extreme X corruption. R includes short spans at a 15% rate; S hides a suffix and resembles prefix LM with a visible prefix; X increases span length and/or corrupted proportion. The paper defines seven specific configurations and uses mode markers to identify the task. Implementations need not all use those same proportions or marker names.

In replaced-token detection, ELECTRA uses a generator to propose substitutions and a discriminator to decide at every position whether the observed token matches the original. If the generator chooses the original token again, that position is not labeled an effective replacement. The discriminator also receives signal at unselected positions. This does not make the generator free or make its cost per step equal to BERT’s.

Fill-in-the-middle for code

In fill-in-the-middle, or FIM, a document is divided into prefix PP, middle MM, and suffix SS. A causal model receives a transformation placing available text before the span to complete. In PSM the logical order is P,S,MP,S,M; in SPM it is S,P,MS,P,M. Exact markers depend on tokenizer and implementation: they must be inserted as controls rather than confused with ordinary text. In SPM, PP and MM can be adjacent; recovering where the prompt ended and answer began requires saving that boundary, although concatenating the final document remains possible.

InteractiveFill-in-the-middle for code

Cuts mark the content to complete in the original document. A code point does not split a UTF-16 surrogate pair, though it can separate a compound grapheme.

Prefix
def saludo(nombre):
Middle
    mensaje = "Hola, " + nombre
    return mensaje
Suffix

print(saludo("Ana"))

Inference context supplied to the model:

<PRE>def saludo(nombre):
<SUF>
print(saludo("Ana"))
<MID>

Target continuation, not a measured generation:

    mensaje = "Hola, " + nombre
    return mensaje
<EOT>

PSM uses PRE, prefix, SUF, suffix, MID and middle. In the SPM variant of FIM appendix D, PRE and SUF precede the suffix, MID precedes the prefix, and the middle is concatenated after the prefix. Their boundary is known because the prefix is part of the context; the stream alone does not mark it. EOT marks the continuation end.

Here PRE, SUF, MID and EOT represent special tokens distinct from text; reconstruction uses all three parts and their known boundary. Line cuts preserve newlines and code-point cuts are not presented as actual tokenizer cuts.

Format
Cut unit
1
3
Middle
2 lines
Cut seed
601
Reconstruction
Exact
Compare character or line cuts and the two orderings before generating the middle span.

Bavarian and colleagues apply the transformation per document before tokenization and use a 50% rate in their main series. They also study higher rates. In their experiments, FIM models retained left-to-right losses similar to controls on code and language, without guaranteeing no cost for every corpus or budget. Cuts in Unicode text must respect character boundaries; arbitrary cuts in UTF-8 bytes or IDs pose different problems. For a code task, line-based and random gap distributions may assess different skills.

Evidence depends on the task

Wang and colleagues compare architecture-objective combinations with 168,000 million pretraining tokens and, where applicable, 13,000 million multitask fine-tuning tokens. In their table 3, after causal or prefix language-model pretraining, the causal decoder achieved 44.2 average EAI-Eval accuracy versus 43.5 for the noncausal decoder and 39.9 for the encoder-decoder; MLM is not included in that direct comparison without adaptation. After multitask fine-tuning, the encoder-decoder pretrained with masked corruption stood out in their evaluations. This is not a universal model ranking: protocols, prompts, and tasks differ.

A linear probe trains a classifier on frozen representations and measures information accessible to that classifier family; it does not prove the network uses that information when generating. The next interactive uses results from an identified short run. Check the split, uncertainty, and budget before interpreting small differences; the observed direction need not match a theoretical expectation.

InteractiveRepresenting versus generating

Linear probes trained on SST-2 train and evaluated on the same validation sample. Models are frozen and content-token representations averaged. Layer zero is the embedding before the first block.

0 %25 %50 %75 %100 %mini BERT (MLM), layer 0: 150/256mini BERT (MLM), layer 1: 137/256mini BERT (MLM), layer 2: 140/256mini BERT (MLM), layer 3: 146/256mini GPT (causal), layer 0: 145/256mini GPT (causal), layer 1: 122/256mini GPT (causal), layer 2: 139/256mini GPT (causal), layer 3: 147/2560123Layer
● Mini BERT, MLM● Mini GPT, causal╌ Training majority class

In this short test neither probe beats the majority baseline at every layer. One seed and 256 examples do not establish a general advantage between objectives. Results must not be confused with full BERT or GPT models.

mini BERT (MLM)

Prefix "The movie"; simultaneous filling of eight masks, externally fixed length:

" = = = = = = = ="
mini GPT (causal)

Prefix "The movie"; greedy continuation, up to eight tokens:

" , the the the the the the the"

MLM filling uses eight simultaneous masks and externally fixed length: it is not autoregressive generation comparable to causal continuation. One sample does not measure quality either. Evaluation computes MLM pseudo-NLL masking one piece at a time and causal NLL over 406 pieces; the former is not a normalized joint likelihood.

Both models have 538464 parameters and start from the same weights, batches and 160 steps on WikiText train. The dense estimate is 555.7 GFLOPs per model; it omits softmax, normalization and optimizer costs and does not measure real time. Steps supervise 18695 MLM targets and 126429 causal targets including EOS. A shared tokenizer was trained without SST-2 data. Code, samples, seeds and corpus hashes accompany the local cell.

The MLM procedure is based on BERT and scoring on Salazar and colleagues. These are small self-contained networks; the m18 architecture is not yet available.

0 · embeddings
MLM · layer 0
58.6 % (150/256)
Causal · layer 0
56.6 % (145/256)
Majority class
59.4 % (152/256)
Compare probes and outputs from both models in the stated run, without generalizing from a short test.

Lab: building corruptions

Nonnegative IDs are ordinary tokens; controls have negative IDs, so literal text resembling a marker does not become a special token. This byte representation is deliberately small and does not claim to be BERT’s WordPiece vocabulary. The RNG is passed as an argument so each example is reproducible.

[ ]Reproducible collatorsBrowser
"""Collators didácticos, autocontenidos y reproducibles para Pyodide."""
import random

# Los IDs negativos representan controles que nunca provienen de texto ordinario.
MASK, PAD, IGNORE = -1, -2, -100
PRE, SUF, MID, EOT = -3, -4, -5, -6
SENTINEL_BASE = -1000


def mlm(tokens, rng, rate=0.15, vocab=range(256), special=(PAD,)):
    """Bernoulli por posición ordinaria; loss solo en posiciones seleccionadas."""
    if not 0 <= rate <= 1:
        raise ValueError('tasa fuera de [0, 1]')
    vocab = tuple(vocab)
    if not vocab or any(x < 0 for x in vocab):
        raise ValueError('el vocabulario ordinario debe ser no vacío y no negativo')
    output, labels, decisions = list(tokens), [IGNORE] * len(tokens), []
    for i, token in enumerate(tokens):
        if token in special or token < 0 or rng.random() >= rate:
            continue
        labels[i] = token
        u = rng.random()
        if u < .8:
            output[i], action = MASK, 'mask'
        elif u < .9:
            output[i], action = rng.choice(vocab), 'random'
        else:
            action = 'unchanged'
        decisions.append((i, action))
    return output, labels, decisions


def restore_mlm(corrupted, labels):
    if len(corrupted) != len(labels):
        raise ValueError('longitudes distintas')
    return [original if original != IGNORE else token
            for token, original in zip(corrupted, labels)]


def composition(total, parts, rng):
    """Composición positiva uniforme: fronteras escogidas sin repetición."""
    if not 1 <= parts <= total:
        raise ValueError('composición imposible')
    cuts = [0] + sorted(rng.sample(range(1, total), parts - 1)) + [total]
    return [b - a for a, b in zip(cuts, cuts[1:])]


def span_corrupt(tokens, rng, rate=.15, mean_span=3):
    """Alterna segmentos limpios y corruptos; termina en un segmento corrupto."""
    if not 0 <= rate <= 1 or mean_span <= 0:
        raise ValueError('parámetros no válidos')
    if any(t < 0 for t in tokens):
        raise ValueError('se esperan IDs ordinarios no negativos')
    n = len(tokens)
    if n < 2 or rate == 0:
        return list(tokens), [], []
    n_noise = max(1, min(n - 1, round(n * rate)))
    n_spans = max(1, min(n_noise, n - n_noise, round(n_noise / mean_span)))
    clean = composition(n - n_noise, n_spans, rng)
    noise = composition(n_noise, n_spans, rng)
    source, target, bounds = [], [], []
    cursor = 0
    for k, (a, b) in enumerate(zip(clean, noise)):
        source.extend(tokens[cursor:cursor+a])
        cursor += a
        sentinel = SENTINEL_BASE - k
        source.append(sentinel)
        target.extend([sentinel, *tokens[cursor:cursor+b]])
        bounds.append((cursor, cursor+b))
        cursor += b
    # La tabla 3 del paper termina el objetivo con otro centinela.
    target.append(SENTINEL_BASE - n_spans)
    return source, target, bounds


def restore_spans(source, target):
    """Sustituye cada centinela de entrada por su tramo objetivo asociado."""
    spans, i, expected = {}, 0, SENTINEL_BASE
    while i < len(target):
        sentinel = target[i]
        if sentinel != expected:
            raise ValueError('centinelas del objetivo fuera de orden')
        i += 1
        if i == len(target):
            break
        j = i
        while j < len(target) and target[j] >= 0:
            j += 1
        if j == i:
            raise ValueError('tramo vacío')
        spans[sentinel] = target[i:j]
        expected -= 1
        i = j
    else:
        if target:
            raise ValueError('falta centinela final')
    result, seen = [], []
    for token in source:
        if token in spans:
            result.extend(spans[token])
            seen.append(token)
        elif token < 0:
            raise ValueError('centinela desconocido')
        else:
            result.append(token)
    if seen != list(spans):
        raise ValueError('centinelas de entrada no coinciden')
    return result


def fim(doc, rng, rate=.5, mode='PSM'):
    """Texto a escala de documento; UTF-8 de cada fragmento por separado."""
    if not 0 <= rate <= 1 or mode not in ('PSM', 'SPM'):
        raise ValueError('tasa o modo inválido')
    if rng.random() >= rate:
        return {'mode': 'AR', 'ids': list(doc.encode('utf-8')) + [EOT]}
    a, b = sorted((rng.randrange(len(doc) + 1), rng.randrange(len(doc) + 1)))
    p, m, s = (list(part.encode('utf-8')) for part in (doc[:a], doc[a:b], doc[b:]))
    if mode == 'PSM':
        ids = [PRE, *p, SUF, *s, MID, *m, EOT]
    else:
        ids = [PRE, SUF, *s, MID, *p, *m, EOT]
    # En SPM no hay frontera en la secuencia entre prefix y middle.
    return {'mode': mode, 'ids': ids, 'prefix_bytes': len(p)}


def restore_fim(example):
    mode, ids = example['mode'], example['ids']
    if not ids or ids[-1] != EOT:
        raise ValueError('falta fin de documento')
    if mode == 'AR':
        return bytes(ids[:-1]).decode('utf-8')
    if mode not in ('PSM', 'SPM') or ids[0] != PRE:
        raise ValueError('formato inválido')
    s, m = ids.index(SUF), ids.index(MID)
    if not 0 < s < m < len(ids)-1:
        raise ValueError('marcadores fuera de orden')
    if mode == 'PSM':
        prefix, suffix, middle = ids[1:s], ids[s+1:m], ids[m+1:-1]
    else:
        if s != 1:
            raise ValueError('SPM exige PRE seguido de SUF')
        # La frontera no es necesaria para reconstruir prefix+middle+suffix.
        # Se conserva cuando también se desea recuperar qué parte era middle.
        size = example.get('prefix_bytes', 0)
        joined = ids[m+1:-1]
        if not 0 <= size <= len(joined):
            raise ValueError('longitud de prefijo inválida')
        prefix, suffix, middle = joined[:size], ids[s+1:m], joined[size:]
    return bytes(prefix + middle + suffix).decode('utf-8')

In MLM each ordinary position is chosen with probability 0.15. Among chosen positions, mask, random, and unchanged branches have probabilities 0.8, 0.1, and 0.1; labels supervise only those positions. The random token can match the original, so proportions are calculated by selected branch rather than visible changes.

[ ]MLMBrowser
import random

original = [PAD, 0, 1, 2, 3, 4, 5, PAD]
for seed in range(100):
    corrupted, labels, decisions = mlm(original, random.Random(seed), rate=.75, vocab=range(8))
    assert restore_mlm(corrupted, labels) == original
    assert labels[0] == labels[-1] == IGNORE
    assert {i for i, _ in decisions} == {i for i, value in enumerate(labels) if value != IGNORE}
    assert original == [PAD, 0, 1, 2, 3, 4, 5, PAD]
assert mlm([1, 2], random.Random(1), rate=0)[1] == [IGNORE, IGNORE]
assert mlm([1, 2], random.Random(1), rate=1)[1] == [1, 2]

# Medimos ramas elegidas, no cambios visibles: el token aleatorio puede coincidir.
rng = random.Random(2026)
_, labels, decisions = mlm([17] * 100000, rng, vocab=range(32))
counts = {name: sum(a == name for _, a in decisions) for name in ('mask', 'random', 'unchanged')}
total = len(decisions)
assert abs(total / 100000 - .15) < .01
assert all(abs(counts[name] / total - target) < .02
           for name, target in [('mask', .8), ('random', .1), ('unchanged', .1)])
print('MLM: seleccionados', total, 'ramas', counts)

In span corruption the number of hidden tokens is fixed and distributed into positive-length spans separated by visible spans. The target contains one sentinel per span, hidden content, and a final sentinel, as in T5 table 3; it does not include an additional EOS. The example’s rounding is explicit. The rule for very short sequences requires at least one visible and one hidden token, and achieved mean length can differ from the parameter.

[ ]SPANBrowser
for n in range(0, 100):
    original = list(range(n))
    for seed in range(5):
        source, target, bounds = span_corrupt(original, random.Random(seed))
        assert restore_spans(source, target) == original
        assert all(a < b for a, b in bounds)
        assert all(bounds[i][1] < bounds[i+1][0] for i in range(len(bounds)-1))
        assert len(target) == (sum(b-a for a, b in bounds) + len(bounds) + bool(bounds))
        assert len(source) == n - sum(b-a for a, b in bounds) + len(bounds)
        assert original == list(range(n))
source, target, bounds = span_corrupt(list(range(512)), random.Random(2026))
print('Spans: entrada original 512, corruptos', sum(b-a for a, b in bounds),
      'tramos', len(bounds), 'entrada', len(source), 'objetivo', len(target))
assert (sum(b-a for a, b in bounds), len(bounds), len(source), len(target)) == (77, 26, 461, 104)
for invalid in ([SENTINEL_BASE, 1], [SENTINEL_BASE, 1, SENTINEL_BASE-2],
                [SENTINEL_BASE, SENTINEL_BASE-1]):
    try:
        restore_spans([SENTINEL_BASE], invalid)
    except ValueError:
        pass
    else:
        raise AssertionError('objetivo inválido aceptado')

FIM cuts the document at Unicode character positions before separately encoding the three fragments as UTF-8. PSM uses PRE, prefix, SUF, suffix, MID, middle; SPM uses PRE, SUF, suffix, MID, prefix, middle, as in the paper’s appendix D. Both strings reconstruct the full document. Separately identifying prefix and middle in SPM requires preserving their boundary as metadata, not a model token. A zero rate leaves the document in causal order.

[ ]FIMBrowser
documents = ['', 'a', 'café 🧠\nπ', '<pre> no es control', 'def suma(a, b):\n    return a + b\n']
for doc in documents:
    for seed in range(60):
        for mode in ('PSM', 'SPM'):
            encoded = fim(doc, random.Random(seed), rate=1, mode=mode)
            assert restore_fim(encoded) == doc
            if mode == 'SPM':
                assert restore_fim({'mode': mode, 'ids': encoded['ids']}) == doc
            assert encoded['ids'].count(PRE) == encoded['ids'].count(SUF) == encoded['ids'].count(MID) == 1
        plain = fim(doc, random.Random(seed), rate=0, mode='PSM')
        assert plain['mode'] == 'AR' and restore_fim(plain) == doc

# El mismo SPM puede corresponder a dos particiones distintas del mismo documento.
spm_a = {'mode': 'SPM', 'ids': [PRE, SUF, ord('x'), MID, ord('a'), ord('b'), EOT], 'prefix_bytes': 0}
spm_b = dict(spm_a, prefix_bytes=1)
assert restore_fim(spm_a) == 'abx' and restore_fim(spm_b) == 'abx'
# La secuencia y el texto completo son idénticos, pero difiere qué parte falta.
assert spm_a['ids'] == spm_b['ids'] and spm_a['prefix_bytes'] != spm_b['prefix_bytes']

rng = random.Random(2026)
transformed = sum(fim('café', rng, rate=.5, mode='PSM')['mode'] != 'AR' for _ in range(10000))
assert abs(transformed / 10000 - .5) < .02
print('FIM: documentos transformados', transformed, 'de 10000')
print('Round-trip probado para AR, PSM y SPM, incluidos UTF-8 y marcadores literales')

Local lab: mini BERT and mini GPT with comparable budgets

This cell trains two self-contained transformers from scratch; the m18 GPT was not available. Both share a ByteLevel BPE tokenizer and have position embeddings, blocks, and a tied head with the same parameter count and initial weights. The causal model uses a triangular mask; the bidirectional model uses full attention and selects 15% of content tokens for MLM under the 80/10/10 rule. Both heads materialize dense logits at every position, although MLM loss counts only selected positions. The causal head also supervises EOS. Record both counts: the same number of steps does not mean the same number of supervised targets.

The pretraining corpus is the train split of WikiText-2 raw; BPE is trained only on that text. Scoring evaluation uses its validation split and excludes lines identical to the training subset before selecting examples. This does not detect near duplicates or identical prefixes after truncation. For sentiment, freeze each network and train an independent linear probe per layer on SST-2 train; evaluate on SST-2 validation against a majority-class baseline calculated from train only. Each probe’s input is the mean content-token representation, excluding BOS, EOS, and padding. Layer zero consists of token and position embeddings. The causal average combines representations at all positions, each built only from its past. The published split separates this experiment’s train and validation sets but does not guarantee absence of duplicates or contamination in other sources.

Causal scoring sums content-piece log probabilities in order; MLM pseudo-NLL masks each piece separately and sums its log probabilities. Both use the same retained pieces, but pseudo-NLL generally does not define a normalized joint probability and should not be compared as causal NLL. For generation the causal model continues greedily, while MLM fills eight masks simultaneously with externally fixed length. That demonstration is not an autoregressive generator and cannot establish general quality from one sample.

The same batch and step count are fixed. The cell estimates dense FLOPs with two operations per multiplication and addition, including projections, MLP, attention products, and logits, and approximates forward plus backward as three times forward. The estimate is equal for both dense forms and excludes softmax, normalization, optimizer, and implementation differences in kernels. It is neither an executed-operation counter nor a timing measurement. Missing files and weights are downloaded to the shared cache; revisions and hashes are printed and models and tokenizer saved to ORYON_OUTPUT_DIR.

You need torch, tokenizers, huggingface_hub, pyarrow, numpy, and scikit-learn. With ORYON_QUICK=1, verification uses 160 steps per model, three blocks of width 96, 4,000 WikiText lines, and 256 examples from each SST-2 split. Normal mode supplies six blocks of width 256, 2,000 steps, and up to 5,000 probe training examples. You can modify ORYON_STEPS; a short run tests the flow and does not promise to reproduce an advantage of large models. In the shown run, the majority-class control gets 152 of 256 examples and no probe beats it; the sample does not support superiority of an objective.

[ ]Mini BERT and mini GPT: probing and generationLocal GPU
"""Comparación controlada de atención causal y bidireccional desde cero."""
import gc
import hashlib
import json
import math
import os
import platform
import random
from importlib.metadata import version
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
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers

SEED = 2006
QUICK = os.environ.get('ORYON_QUICK') == '1'
OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', './bert-gpt-output'))
OUT.mkdir(parents=True, exist_ok=True)
WIKI_REV = 'b08601e04326c79dfdd32d625aee71d232d685c3'
SST_REV = '8a5c65785cdc5a2668e3dc7369986b0a4d50b5c5'
STEPS = int(os.environ.get('ORYON_STEPS', '160' if QUICK else '2000'))
BATCH = 16
T = 64 if QUICK else 96
D = 96 if QUICK else 256
LAYERS = 3 if QUICK else 6
HEADS = 4 if QUICK else 8
VOCAB_REQUEST = 2048 if QUICK else 8192
N_WIKI = 4000 if QUICK else 30000
N_PROBE_TRAIN = 256 if QUICK else 5000
N_PROBE_EVAL = 256 if QUICK else 872
N_PLL = 8 if QUICK else 40
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(1)
torch.manual_seed(SEED)
np.random.seed(SEED)
random.seed(SEED)

def download(repo, revision, filename):
    path = hf_hub_download(repo, filename, revision=revision, repo_type='dataset')
    with open(path, 'rb') as f:
        digest = hashlib.file_digest(f, 'sha256').hexdigest()
    return path, {'repo':repo, 'revision':revision, 'file':filename, 'sha256':digest}

wiki_train_path, wiki_train_source = download('Salesforce/wikitext', WIKI_REV, 'wikitext-2-raw-v1/train-00000-of-00001.parquet')
wiki_val_path, wiki_val_source = download('Salesforce/wikitext', WIKI_REV, 'wikitext-2-raw-v1/validation-00000-of-00001.parquet')
sst_train_path, sst_train_source = download('stanfordnlp/sst2', SST_REV, 'default/sst2-train.parquet')
sst_val_path, sst_val_source = download('stanfordnlp/sst2', SST_REV, 'default/sst2-validation.parquet')
wiki_train = [s for s in pq.read_table(wiki_train_path, columns=['text']).column('text').to_pylist() if len(s.strip()) >= 20][:N_WIKI]
wiki_train_set = set(wiki_train)
wiki_val_candidates = [s for s in pq.read_table(wiki_val_path, columns=['text']).column('text').to_pylist() if len(s.strip()) >= 20]
wiki_val_duplicates = sum(s in wiki_train_set for s in wiki_val_candidates)
wiki_val = [s for s in wiki_val_candidates if s not in wiki_train_set][:N_PLL]
train_rows = pq.read_table(sst_train_path, columns=['sentence','label','idx']).to_pylist()
val_rows = pq.read_table(sst_val_path, columns=['sentence','label','idx']).to_pylist()
random.Random(SEED).shuffle(train_rows)
random.Random(SEED + 1).shuffle(val_rows)
train_rows, val_rows = train_rows[:N_PROBE_TRAIN], val_rows[:N_PROBE_EVAL]
assert len(wiki_train) and len(wiki_val) and {r['label'] for r in train_rows} == {0,1}
print('WikiText train/validación:',len(wiki_train),len(wiki_val),
      'SST-2 sonda train/validación:',len(train_rows),len(val_rows),flush=True)
print('Líneas de validación idénticas a train descartadas:',wiki_val_duplicates,flush=True)
for source in (wiki_train_source,wiki_val_source,sst_train_source,sst_val_source):
    print('  fuente:',source['repo'],source['file'],'revisión:',source['revision'],'SHA-256:',source['sha256'],flush=True)

special = ['[PAD]','[UNK]','[BOS]','[EOS]','[MASK]']
tokenizer = Tokenizer(models.BPE(unk_token='[UNK]'))
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tokenizer.decoder = decoders.ByteLevel()
trainer = trainers.BpeTrainer(vocab_size=VOCAB_REQUEST, min_frequency=2,
    special_tokens=special, initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), show_progress=False)
tokenizer.train_from_iterator(wiki_train, trainer)
tokenizer.enable_truncation(max_length=T-2)
tokenizer.save(str(OUT/'tokenizer.json'))
tokenizer_sha256 = hashlib.sha256((OUT/'tokenizer.json').read_bytes()).hexdigest()
print('Tokenizador entrenado con WikiText train, SHA-256:', tokenizer_sha256, flush=True)
pad, unk, bos, eos, mask = [tokenizer.token_to_id(x) for x in special]
V = tokenizer.get_vocab_size()
assert V >= 261 and len({pad,unk,bos,eos,mask}) == 5

def encode(text):
    ids = [bos] + tokenizer.encode(text).ids + [eos]
    assert 2 <= len(ids) <= T
    return ids + [pad]*(T-len(ids))

train_tokens = torch.tensor([encode(s) for s in wiki_train], dtype=torch.long)
val_tokens = torch.tensor([encode(s) for s in wiki_val], dtype=torch.long)
probe_train = torch.tensor([encode(r['sentence']) for r in train_rows], dtype=torch.long)
probe_val = torch.tensor([encode(r['sentence']) for r in val_rows], dtype=torch.long)
y_train = np.array([r['label'] for r in train_rows], dtype=np.int64)
y_val = np.array([r['label'] for r in val_rows], dtype=np.int64)
majority = int(np.bincount(y_train, minlength=2).argmax())
majority_accuracy = float(np.mean(y_val == majority))

class MiniTransformer(nn.Module):
    def __init__(self, causal):
        super().__init__()
        self.causal = causal
        self.word = nn.Embedding(V,D)
        self.pos = nn.Embedding(T,D)
        self.blocks = nn.ModuleList([nn.TransformerEncoderLayer(D,HEADS,4*D,dropout=0.0,
            activation='gelu',batch_first=True,norm_first=True) for _ in range(LAYERS)])
        self.norm = nn.LayerNorm(D)
        self.apply(self.initialize)

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

    def forward(self, x, return_hidden=False):
        length = x.shape[1]
        h = self.word(x) + self.pos(torch.arange(length,device=x.device))[None,:,:]
        layers = [h]
        causal_mask = torch.ones((length,length),device=x.device,dtype=torch.bool).triu(1) if self.causal else None
        key_padding = x.eq(pad)
        for block in self.blocks:
            h = block(h, src_mask=causal_mask, src_key_padding_mask=key_padding)
            layers.append(h)
        logits = F.linear(self.norm(h),self.word.weight)
        return (logits, layers) if return_hidden else logits

def mlm_batch(x):
    eligible = x.ne(pad) & x.ne(bos) & x.ne(eos)
    chosen = (torch.rand(x.shape,device=x.device) < 0.15) & eligible
    # Si un lote entero no tiene destinos elegibles, no hay media definida.
    if not chosen.any():
        raise ValueError('Lote MLM sin destinos seleccionados; aumenta el tamaño o el texto')
    choice = torch.rand(x.shape,device=x.device)
    corrupted = x.clone()
    corrupted[chosen & (choice < .8)] = mask
    replaced = chosen & (choice >= .8) & (choice < .9)
    random_ids = torch.randint(5,V,x.shape,device=x.device)
    corrupted[replaced] = random_ids[replaced]
    labels = x.masked_fill(~chosen,-100)
    return corrupted, labels, int(chosen.sum())

def make_features(model, tokens):
    all_layers = [[] for _ in range(LAYERS+1)]
    with torch.inference_mode():
        for first in range(0,len(tokens),BATCH):
            x = tokens[first:first+BATCH].to(DEVICE)
            _, hidden = model(x,return_hidden=True)
            selected = x.ne(pad) & x.ne(bos) & x.ne(eos)
            denominator = selected.sum(dim=1,keepdim=True).clamp_min(1)
            for i,h in enumerate(hidden):
                pooled = (h * selected[:,:,None]).sum(dim=1) / denominator
                all_layers[i].append(pooled.cpu().numpy())
    return [np.concatenate(parts) for parts in all_layers]

def probes(model):
    x_train = make_features(model, probe_train)
    x_val = make_features(model, probe_val)
    results=[]
    for layer, (a,b) in enumerate(zip(x_train,x_val)):
        probe = make_pipeline(StandardScaler(),LogisticRegression(max_iter=300,random_state=SEED))
        probe.fit(a,y_train)
        predicted = probe.predict(b)
        results.append({'layer':layer, 'correct':int((predicted==y_val).sum()),
            'total':len(y_val), 'accuracy':float(np.mean(predicted==y_val))})
    return results

def evaluate(model, causal):
    total_loss = 0.
    n = 0
    with torch.inference_mode():
        for row in val_tokens:
            # Solo piezas de contenido, sin BOS/EOS. PLL no es una probabilidad conjunta.
            end = int((row != pad).sum()) - 1
            if end <= 1: continue
            if causal:
                x = row[None,:end].to(DEVICE)
                target = row[1:end].to(DEVICE)
                logits = model(x)[0,:end-1]
                total_loss += float(F.cross_entropy(logits,target,reduction='sum'))
                n += len(target)
            else:
                for first in range(1,end,8):
                    positions = list(range(first,min(first+8,end)))
                    batch = row[None,:end+1].repeat(len(positions),1).to(DEVICE)
                    target = batch[torch.arange(len(positions),device=DEVICE),positions].clone()
                    batch[torch.arange(len(positions),device=DEVICE),positions] = mask
                    logits = model(batch)[torch.arange(len(positions),device=DEVICE),positions]
                    total_loss += float(F.cross_entropy(logits,target,reduction='sum'))
                    n += len(positions)
    assert n > 0
    return {'documents':len(val_tokens), 'tokens':n, 'negative_sum_nats':total_loss,
            'mean_negative_nats_per_token':total_loss/n,
            'kind':'NLL causal' if causal else 'pseudo-NLL con una máscara a la vez'}

def sample(model, causal):
    prompt = 'The movie'
    prefix = [bos] + tokenizer.encode(prompt).ids
    requested = 8
    if len(prefix) + requested > T: raise ValueError('Prefijo demasiado largo')
    with torch.inference_mode():
        if causal:
            sequence = prefix[:]
            for _ in range(requested):
                x = torch.tensor([sequence],device=DEVICE)
                new_id = int(model(x)[0,-1].argmax())
                sequence.append(new_id)
                if new_id == eos: break
            continuation = sequence[len(prefix):]
            method = 'continuación greedy, hasta ocho tokens'
        else:
            x = torch.tensor([prefix + [mask]*requested],device=DEVICE)
            predictions = model(x)[0,len(prefix):].argmax(dim=-1).tolist()
            continuation = [int(i) for i in predictions]
            method = 'relleno simultáneo de ocho máscaras, longitud fijada externamente'
    return {'prompt':prompt, 'method':method, 'token_ids':continuation,
            'text':tokenizer.decode(continuation,skip_special_tokens=False)}

results = []
for causal, name in [(False,'mini BERT (MLM)'),(True,'mini GPT (causal)')]:
    torch.manual_seed(SEED)
    if DEVICE.type == 'cuda': torch.cuda.manual_seed_all(SEED)
    model = MiniTransformer(causal).to(DEVICE)
    parameter_count = sum(p.numel() for p in model.parameters())
    init_hash = hashlib.sha256(b''.join(p.detach().cpu().numpy().tobytes() for p in model.parameters())).hexdigest()
    optim = torch.optim.AdamW(model.parameters(), lr=3e-4)
    sequence_rng = np.random.default_rng(SEED)
    supervised = 0
    valid = 0
    loss_first = loss_last = None
    model.train()
    for step in range(STEPS):
        chosen = sequence_rng.integers(0,len(train_tokens),size=BATCH)
        x = train_tokens[chosen].to(DEVICE)
        valid += int((x.ne(pad)&x.ne(bos)&x.ne(eos)).sum())
        optim.zero_grad(set_to_none=True)
        if causal:
            logits = model(x)
            labels = x[:,1:].masked_fill(x[:,1:].eq(pad),-100)
            loss = F.cross_entropy(logits[:,:-1].reshape(-1,V),labels.reshape(-1),ignore_index=-100)
            supervised += int(labels.ne(-100).sum())
        else:
            corrupted, labels, n = mlm_batch(x)
            logits = model(corrupted)
            loss = F.cross_entropy(logits.reshape(-1,V),labels.reshape(-1),ignore_index=-100)
            supervised += n
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(),1.)
        optim.step()
        if step == 0: loss_first = float(loss.detach())
        if step == STEPS-1: loss_last = float(loss.detach())
        if (step+1) % 50 == 0 or step+1 == STEPS:
            print(name,'paso',step+1,'loss',float(loss.detach()),'supervisados',supervised,flush=True)
    model.eval()
    del optim, loss, logits, x, labels
    if not causal: del corrupted
    score = evaluate(model,causal)
    classifications = probes(model)
    generated = sample(model,causal)
    torch.save(model.state_dict(),OUT/('gpt.pt' if causal else 'bert.pt'))
    result = {'name':name, 'causal':causal, 'parameters':parameter_count, 'initial_state_sha256':init_hash,
              'steps':STEPS, 'valid_content_positions_seen':valid, 'supervised_positions':supervised,
              'first_batch_loss':loss_first, 'last_batch_loss':loss_last,
              'score':score, 'probes':classifications, 'sample':generated}
    print(name,'parámetros',parameter_count,'contenido',valid,'supervisados',supervised,flush=True)
    print('  SHA-256 del estado inicial:',init_hash,flush=True)
    print(' ',score,'sondas:',[(p['layer'],p['correct'],p['total']) for p in classifications],flush=True)
    print(' ',generated,flush=True)
    results.append(result)
    del model
    gc.collect()
    if DEVICE.type == 'cuda': torch.cuda.empty_cache()
assert results[0]['parameters'] == results[1]['parameters']
assert results[0]['initial_state_sha256'] == results[1]['initial_state_sha256']
assert results[0]['valid_content_positions_seen'] == results[1]['valid_content_positions_seen']
# Aproximación densa: multiplicación+suma = 2 FLOPs; 24Td² por bloque
# para QKV, salida y MLP 4d; 4T²d para productos de atención; 2TdV para logits.
# Tres veces el forward aproxima forward+backward y omite softmax, normas,
# enmascarado, optimizador y diferencias del kernel causal.
estimated_forward = BATCH * (LAYERS*(24*T*D*D + 4*T*T*D) + 2*T*D*V)
estimated_train = 3 * estimated_forward * STEPS
report = {'seed':SEED,'quick':QUICK,'device':str(DEVICE),'python':platform.python_version(),
          'torch':version('torch'),'tokenizers':version('tokenizers'),'sklearn':version('scikit-learn'),
          'sources':{'wiki_train':wiki_train_source,'wiki_validation':wiki_val_source,
                     'sst_train':sst_train_source,'sst_validation':sst_val_source},
          'settings':{'steps':STEPS,'batch':BATCH,'length':T,'width':D,'layers':LAYERS,'heads':HEADS,
              'vocab_requested':VOCAB_REQUEST,'vocab_actual':V,'wiki_train_lines':len(wiki_train),
              'tokenizer_sha256':tokenizer_sha256,
              'wiki_validation_lines':len(wiki_val),'wiki_validation_duplicates_excluded':wiki_val_duplicates,
              'sst_train_n':len(train_rows),'sst_validation_n':len(val_rows),
              'sst_train_row_ids':[r['idx'] for r in train_rows],'sst_validation_row_ids':[r['idx'] for r in val_rows],
              'mask_rate':0.15,'mask_rule':'80 % máscara, 10 % aleatorio, 10 % sin cambiar',
              'estimated_forward_flops_per_step':estimated_forward,'estimated_train_flops_per_model':estimated_train,
              'flops_note':'Estimación densa con 3x forward; omite softmax, normalización y optimizador; no es medición de tiempo.'},
          'majority_baseline':{'class':majority,'correct':int((y_val==majority).sum()),
                               'total':len(y_val),'accuracy':majority_accuracy},
          'models':results}
(OUT/'probe-data.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
print('FLOPs densos estimados por modelo:',estimated_train,'base mayoritaria:',majority_accuracy,flush=True)
print('Salida:',OUT/'probe-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.

Exercises

NumericTarget budget
Approximate an input of 512 tokens with corrupted fraction 0.15 and mean span length 3. Assuming the expected number of spans is corrupted tokens divided by 3, how many target tokens are expected if you count corrupted tokens and one sentinel per span, without EOS or a final sentinel?
QuizWhy leave tokens unchanged?
In BERT MLM, what does the 10% of selected positions left unchanged represent?
ProofA pseudo-probability need not sum to one
Prove: Construct a normalization counterexample for the product of conditionals of two binary tokens.
0
Use a consistent joint distribution: P(00)=P(11)=0.4 and P(01)=P(10)=0.1.

Step 1 of 3. What is the marginal probability of each value of each token?

CodeTransform and invert FIM
Implement fim_transform(doc, rate, mode, seed) and fim_inverse(example). doc is a Unicode string; rate is between 0 and 1 and mode is PSM or SPM. Use random.Random(seed) to decide whether to transform; otherwise return mode AR and UTF-8 byte IDs followed by EOT=259. If transforming, choose two character-position cuts with randrange(len(doc)+1), sort them, and encode prefix, middle, and suffix as bytes. Use PRE=256, SUF=257, MID=258, and EOT=259. PSM emits PRE,prefix,SUF,suffix,MID,middle,EOT; SPM emits PRE,SUF,suffix,MID,prefix,middle,EOT. Return a dictionary with mode and ids. The inverse returns the original document; special IDs are outside the byte range.
import random

def fim_transform(doc, rate, mode, seed):
  pass

def fim_inverse(example):
  pass
Shift+Enter to run

After solving, check the continuous-scale estimates and counterexample:

[ ]Mean length and pseudo-likelihoodBrowser
from itertools import product

tokens = 512 * 0.15
spans = tokens / 3
print('Tokens corruptos:', tokens, '| spans aproximados:', spans,
      '| objetivo sin final:', tokens + spans)
joint = {(0,0): .4, (0,1): .1, (1,0): .1, (1,1): .4}
weights = []
for a, b in product((0,1), repeat=2):
    marginal_a = sum(joint[a,j] for j in (0,1))
    marginal_b = sum(joint[i,b] for i in (0,1))
    weights.append((joint[a,b]/marginal_b)*(joint[a,b]/marginal_a))
print('Productos de condicionales:', weights, '| suma:', round(sum(weights), 6))
Key idea

MLM, span corruption, and FIM pose different prediction problems. The mask, target construction, and evaluation protocol form part of the experiment’s definition.