WordPiece, Unigram, SentencePiece and tokenization pathologies
Study WordPiece, Unigram, SentencePiece, and subword regularization, then examine numerical tokenization, language disparities, under-trained tokens, vocabulary extension, and byte-based models.
After this lesson you can
- Implement Unigram segmentation with Viterbi, forward-backward EM, and vocabulary pruning.
- Compare the WordPiece and BPE merge criteria and bottom-up BPE with top-down Unigram.
- Train SentencePiece with byte fallback and apply subword regularization and BPE dropout.
- Diagnose tokenization problems involving digits, spaces, languages, and under-trained tokens.
- Extend a pretrained model's vocabulary and initialize new embeddings using a justified method.
Before you start
- 20BPE trainingMerge-rank BPE encodingByte-level BPETokenizer compression metricsUnicode normalizationVocabulary size trade-off
- 12Expectation-maximization algorithmEM lower bound
- 14Viterbi algorithmForward-backward algorithm (smoothing)
- 08Dynamic programmingEdit distance and sequence alignment
- 18Token embedding layerWeight tying
One word, many paths
The word aba can be represented as aba, ab · a, a · ba, or a · b · a if those pieces are in the vocabulary. The choice changes how many steps the network sees and how it shares information with other words. In the figure, follow the paths and compare the best with the sum of all paths: they answer different questions.
In BPE we start from small units and add merges. A Unigram tokenizer starts from a large candidate vocabulary and reduces it. For a string and segmentation , it assigns weight , with and . We consider only paths whose concatenation is ; there are no empty pieces. The string’s marginal score is and the posterior probability of a path given is . Without a stopping rule, these products alone do not define a normalized distribution over all finite strings. This is a segmentation model, not an LLM’s contextual probability.
Viterbi versus forward and backward
For deterministic segmentation, we want . Represent each position between characters by a node and each piece by an arc . If , the log recurrence is
Each arc consumes at least one character. Save the predecessor maximizing each position and follow those pointers backward. If no path reaches the end, report missing coverage. See Viterbi for the same principle in hidden sequences.
For learning, the best path is insufficient. In probability, and over valid arcs; similarly and . Then and the posterior probability of using a particular arc is . Sum that quantity over all arcs labeled and all sentences to obtain its expected count . The M-step of EM updates . In practical implementations use log-sum-exp to avoid underflow and define how to handle zero counts and coverage.
For a fixed vocabulary and exact E and M steps, EM does not decrease the sum of log marginal scores of observed fragments. Removing a piece changes the model, so that guarantee no longer applies. Kudo starts with frequent candidates, estimates the cost of removing each piece, and retains single-character units for coverage. Our lab explicitly calculates pruning losses on a small corpus. It is a teaching implementation, not a replica of all production optimizations.
WordPiece and construction direction
WordPiece also builds subword units. Wu and colleagues describe likelihood-based selection. A common educational reconstruction scores a pair by , favoring strong associations rather than merely the most frequent pair. Hugging Face notes that Google’s original trainer was not published. Do not confuse this explanatory heuristic with a complete historical specification.
For example, if the corpus contains five aa fragments and three bc fragments, pair aa occurs five times and bc three. With symbol frequencies , , frequency BPE chooses aa. The heuristic above compares with and chooses bc. In BERT, prefix ## marks a continuation within a word in its WordPiece representation; it is not always a literal character in the text.
Spaces, bytes, and multiple segmentations
SentencePiece is a library that trains and applies both Unigram and BPE to text, not a third segmentation algorithm. Its visible representation of a space uses ▁. Configured normalization is applied first and can change the text. With byte fallback, reserved byte symbols can represent characters not covered by other pieces after normalization. Reversibility of the normalized sequence does not imply preservation of all original bytes. Configuration, model, and version are part of the experiment. Kudo and Richardson describe the system.
Subword regularization presents different segmentations of the same string during training. In Unigram we can sample a path with weight proportional to . For , all possible complete paths have equal probability; as increases, the distribution favors higher-probability paths. Under the positive-temperature convention , here . Sampling each arc uniformly does not generally yield uniform complete paths: suffix mass must be taken into account.
BPE dropout stochastically omits candidate merges when segmenting during training. A conventional evaluation fixes a deterministic segmentation for comparison. Provilkov and colleagues study translation and robustness with this procedure. It does not follow that every task improves or that sampling at inference is impossible.
Numbers and cost by language
Number segmentation affects which decimal positions share a piece. A tokenizer can split individual digits or group up to three from the beginning or from the units position. In addition, observe the boundaries after aligning digits by place value: left grouping can shift its boundaries when the number of digits changes. The figure shows explicit groupings, not proof of a network’s arithmetic ability.
In the experiment by Singh and Strouse, with gpt-3.5-turbo-0301, 90 additions of 7 to 9 digits, and eight examples, reported accuracy was 75.6% for left-to-right grouping versus 97.8% for grouping from the right, forced with commas. The paper’s controls and analysis support an alignment effect in that setup. They do not prove that every arithmetic error comes from the tokenizer. The study also found no clear trend with the number of carries in the filtered set.
Tokenization disparity across languages arises when the same content occupies different numbers of tokens depending on language or script. With a fixed context window or per-token price, that difference can reduce the text that fits or increase cost. Tokens per sentence also depend on translation, normalization, and corpus. In the 256 parallel-sentence run of the metrics lesson, GPT-2 averaged 26.867 tokens per English sentence and 197.496 per Hindi sentence. These are results for that sample, not properties of all texts. Petrov and colleagues studied specific differences in their data and tokenizers; do not attribute their ratios to any current model. Compare parallel sentences, report the distribution, and also measure bytes per token.
Under-trained candidates
An under-trained token may exist in the vocabulary and have received few effective training opportunities. A small norm or low frequency in a sample corpus is a signal to investigate, not proof of its pretraining frequency or a failure. Input and output matrices may share weights. If tied, their row norms coincide and the scatter lies on the diagonal.
Land and Bartolo study geometric signals and behavioral tests. The appropriate indicator depends on whether matrices are tied. Their table 1 includes InstoreAndOnline among verified examples for GPT-2 Medium and GPT-2 XL. In our GPT-2 base it appears as a candidate near the reference, but verification of one checkpoint does not automatically transfer to another. A useful check uses several contexts and probabilities, not one repetition attempt. These observations support defensive diagnosis and careful input handling; geometry alone does not establish a vulnerability.
Extending a vocabulary without disturbing the distribution
Vocabulary extension changes tokenization and adds rows to the input and output head. Let be the number of old logits for a prefix whose representation remains fixed, and . Add output rows exactly equal to the mean of the old rows; if biases exist, average them too. Each new logit is then and Jensen implies . Total mass on new tokens is bounded by .
Extending the old distribution with zeros to the expanded vocabulary and calling the new one ,
This is the direction . The reverse is infinite if gives positive mass to tokens whose old probability was zero. Hewitt’s bound requires the same hidden state and unchanged old logits before retraining. It does not cover prefixes that tokenize differently or perturbed new rows. Initializing near zero can concentrate excessive mass when old logits are very negative, although not every random initialization fails. After adding and sizing rows, adapt the model with continued pretraining on suitable data and evaluate both new and old domains.
Beyond a fixed vocabulary
ByT5 processes bytes instead of relying on a learned subword vocabulary. MEGABYTE and Byte Latent Transformer explore hierarchical structures or patches for byte sequences. Avoiding a subword tokenizer does not eliminate encoding, normalization, or compute decisions: sequences can be much longer and architectures address that cost differently.
Lab: learning and segmenting
The first block reproduces the previous lesson’s current BPE functions and pretokenization. Unigram assigns positive probabilities to substrings and sums the weights of every path for each fragment; Viterbi takes the best. Training uses short Spanish sentences and retains characters for coverage. The two test texts are different combinations of previously seen fragments. They check the flow rather than estimate general performance. The punctuation marker belongs to the corpus.
At each EM step probabilities are updated from posterior counts; the monotonicity check applies only to a fixed vocabulary. Pruning calculates the exact difference in this corpus after removing one token and renormalizing the rest, before another EM step. This is an explicit policy for this example, not a reproduction of optimized SentencePiece. The model has no end-of-word probability: the displayed sum is over segmentations of each observed fragment.
# Funciones BPE de la lección m20-l03.
from collections import Counter, defaultdict
import heapq
import random
import re
import time
PATTERN = '\\s+|[^\\W\\d_]+|\\d+|_|[^\\w\\s]'
def pretokenize(text):
pieces = re.findall(PATTERN, text, flags=re.UNICODE)
assert ''.join(pieces) == text
return pieces
def pairs(ids):
return Counter(zip(ids, ids[1:]))
def merge(ids, pair, new_id):
out, i = ([], 0)
while i < len(ids):
if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair:
out.append(new_id)
i += 2
else:
out.append(ids[i])
i += 1
return out
def train(text, vocab_size, incremental=False):
if vocab_size < 256:
raise ValueError('El vocabulario debe incluir los 256 bytes')
weighted = Counter((tuple(piece.encode('utf-8')) for piece in pretokenize(text)))
chunks = [list(chunk) for chunk in weighted]
weights = list(weighted.values())
vocab = {i: bytes([i]) for i in range(256)}
merges, history = ([], [])
counts = Counter()
positions = defaultdict(set)
for i, chunk in enumerate(chunks):
for pair, occurrences in pairs(chunk).items():
counts[pair] += occurrences * weights[i]
positions[pair].add(i)
heap = [(-count, *pair) for pair, count in counts.items()]
heapq.heapify(heap)
for new_id in range(256, vocab_size):
if incremental:
while heap and counts[heap[0][1], heap[0][2]] != -heap[0][0]:
heapq.heappop(heap)
if not heap:
break
neg_count, left, right = heapq.heappop(heap)
pair, count = ((left, right), -neg_count)
affected = sorted(positions[pair])
else:
counts = Counter()
for chunk, weight in zip(chunks, weights):
for pair, occurrences in pairs(chunk).items():
counts[pair] += occurrences * weight
if not counts:
break
pair = min(counts, key=lambda p: (-counts[p], p))
count = counts[pair]
affected = range(len(chunks))
substitutions = 0
for i in affected:
old = chunks[i]
new = merge(old, pair, new_id)
if len(new) == len(old):
continue
substitutions += (len(old) - len(new)) * weights[i]
if incremental:
before, after = (pairs(old), pairs(new))
for p in set(before) | set(after):
counts[p] += (after[p] - before[p]) * weights[i]
if after[p]:
positions[p].add(i)
else:
positions[p].discard(i)
if counts[p] > 0:
heapq.heappush(heap, (-counts[p], *p))
chunks[i] = new
assert substitutions > 0 and substitutions <= count
vocab[new_id] = vocab[pair[0]] + vocab[pair[1]]
merges.append((pair[0], pair[1], new_id))
history.append((pair, count, substitutions))
return (vocab, merges, history)
def encode(text, merges):
ranks = {(left, right): (rank, new_id) for rank, (left, right, new_id) in enumerate(merges)}
output = []
for piece in pretokenize(text):
ids = list(piece.encode('utf-8'))
while True:
candidates = [pair for pair in pairs(ids) if pair in ranks]
if not candidates:
break
chosen = min(candidates, key=lambda p: ranks[p][0])
ids = merge(ids, chosen, ranks[chosen][1])
output.extend(ids)
return output
def decode(ids, vocab):
return b''.join((vocab[i] for i in ids)).decode('utf-8', errors='strict')
"""Unigram por caminos: Viterbi, forward-backward, EM y poda explícita."""
from collections import Counter
import itertools
import math
import random
def logsumexp(values):
values = list(values)
if not values:
return -math.inf
largest = max(values)
if largest == -math.inf:
return -math.inf
return largest + math.log(sum(math.exp(v - largest) for v in values))
def lattice(text, probabilities):
if any(not token or p <= 0 or not math.isfinite(p) for token, p in probabilities.items()):
raise ValueError('Cada token debe ser no vacío y tener probabilidad positiva finita')
if not math.isclose(sum(probabilities.values()), 1.0, rel_tol=1e-10, abs_tol=1e-12):
raise ValueError('Las probabilidades deben sumar uno')
entries = sorted(probabilities)
return [[(i + len(token), token, math.log(probabilities[token]))
for token in entries if text.startswith(token, i)] for i in range(len(text))]
def forward_backward(text, probabilities):
edges = lattice(text, probabilities)
length = len(text)
forward = [-math.inf] * (length + 1)
forward[0] = 0.0
for i in range(length):
for j, token, lp in edges[i]:
forward[j] = logsumexp((forward[j], forward[i] + lp))
backward = [-math.inf] * (length + 1)
backward[length] = 0.0
for i in range(length - 1, -1, -1):
backward[i] = logsumexp(lp + backward[j] for j, token, lp in edges[i])
if forward[length] == -math.inf:
raise ValueError('La palabra no tiene segmentación con este vocabulario')
counts = Counter()
for i in range(length):
for j, token, lp in edges[i]:
counts[token] += math.exp(forward[i] + lp + backward[j] - forward[length])
return forward[length], counts, forward, backward
def viterbi(text, probabilities):
edges = lattice(text, probabilities)
scores = [-math.inf] * (len(text) + 1)
paths = [None] * (len(text) + 1)
scores[0], paths[0] = 0.0, ()
for i in range(len(text)):
if paths[i] is None:
continue
for j, token, lp in edges[i]:
candidate, path = scores[i] + lp, paths[i] + (token,)
if candidate > scores[j] or (candidate == scores[j] and (paths[j] is None or path < paths[j])):
scores[j], paths[j] = candidate, path
if paths[-1] is None:
raise ValueError('La palabra no tiene segmentación con este vocabulario')
return list(paths[-1]), scores[-1]
def corpus_log_likelihood(words, probabilities):
return math.fsum(weight * forward_backward(word, probabilities)[0] for word, weight in words.items())
def em_step(words, probabilities):
expected = Counter()
for word, weight in words.items():
_, counts, _, _ = forward_backward(word, probabilities)
for token, count in counts.items():
expected[token] += weight * count
total = sum(expected.values())
if total <= 0:
raise ValueError('No hay tokens observados en el corpus')
return {token: expected[token] / total for token in probabilities if expected[token] > 0}
def prune_one(words, probabilities, protected):
before = corpus_log_likelihood(words, probabilities)
candidates = []
for token, p in probabilities.items():
if token in protected or p >= 1:
continue
trial = {s: q / (1 - p) for s, q in probabilities.items() if s != token}
try:
after = corpus_log_likelihood(words, trial)
except ValueError:
continue
candidates.append((before - after, token, trial))
if not candidates:
raise ValueError('No hay candidato de poda sin perder cobertura')
loss, token, trial = min(candidates, key=lambda item: (item[0], item[1]))
return token, loss, trial
def sample(text, probabilities, alpha, randomizer):
if alpha < 0 or not math.isfinite(alpha):
raise ValueError('α debe ser finito y no negativo')
edges = lattice(text, probabilities)
backward = [-math.inf] * (len(text) + 1)
backward[-1] = 0.0
for i in range(len(text) - 1, -1, -1):
backward[i] = logsumexp(alpha * lp + backward[j] for j, token, lp in edges[i])
if backward[0] == -math.inf:
raise ValueError('La palabra no tiene segmentación con este vocabulario')
result, i = [], 0
while i < len(text):
options = [(j, token, math.exp(alpha * lp + backward[j] - backward[i]))
for j, token, lp in edges[i] if backward[j] > -math.inf]
draw, accumulated = randomizer.random(), 0.0
for j, token, p in options:
accumulated += p
if draw < accumulated:
break
result.append(token)
i = j
return result
toy = {'a': .20, 'b': .10, 'ab': .25, 'ba': .15, 'aba': .20, 'c': .10}
score, counts, _, _ = forward_backward('aba', toy)
enumerated = [(['aba'], .20), (['ab', 'a'], .05), (['a', 'ba'], .03), (['a', 'b', 'a'], .004)]
assert math.isclose(math.exp(score), sum(p for _, p in enumerated), abs_tol=1e-12)
best, best_log = viterbi('aba', toy)
assert best == ['aba'] and math.isclose(math.exp(best_log), .2)
assert math.isclose(counts['a'], .088 / .284) and math.isclose(counts['aba'], .2 / .284)
assert sample('', toy, 0, random.Random(1)) == []
for alpha, expected in ((0, .25), (1, .20 / .284)):
generator = random.Random(2004)
draws = Counter(tuple(sample('aba', toy, alpha, generator)) for _ in range(1600))
assert len(draws) == 4 and abs(draws[('aba',)] / 1600 - expected) < .05
print('Muestreo α =', alpha, '| frecuencia de [aba]:', round(draws[('aba',)] / 1600, 5),
'| probabilidad exacta:', round(expected, 6), '| semilla 2004')
try:
forward_backward('z', toy)
except ValueError:
pass
else:
raise AssertionError('Cobertura inexistente')
print('aba: mejor', best, round(math.exp(best_log), 6), '| marginal', round(math.exp(score), 6))
print('Esperanzas: a', round(counts['a'], 6), '| aba', round(counts['aba'], 6))
training_text = 'la casa canta la canción. la casa cambia y canta. la canción cambia la casa.'
test_texts = ['la canción canta.', 'la casa cambia.']
words = Counter(pretokenize(training_text))
substring_counts = Counter()
for word, frequency in words.items():
for start in range(len(word)):
for end in range(start + 1, min(len(word), start + 4) + 1):
substring_counts[word[start:end]] += frequency
protected = {char for word in words for char in word}
extras = sorted((s for s in substring_counts if len(s) > 1), key=lambda s: (-substring_counts[s], s))[:20]
initial = {s: float(substring_counts[s]) for s in sorted(protected | set(extras))}
total = sum(initial.values())
model = {s: count / total for s, count in initial.items()}
initial_likelihood = corpus_log_likelihood(words, model)
for _ in range(5):
updated = em_step(words, model)
assert protected <= updated.keys()
assert corpus_log_likelihood(words, updated) >= corpus_log_likelihood(words, model) - 1e-10
model = updated
em_likelihood = corpus_log_likelihood(words, model)
removed, loss, pruned = prune_one(words, model, protected)
assert protected <= pruned.keys()
assert math.isclose(corpus_log_likelihood(words, pruned), em_likelihood - loss, abs_tol=1e-10)
post_em = em_step(words, pruned)
assert corpus_log_likelihood(words, post_em) >= corpus_log_likelihood(words, pruned) - 1e-10
bpe_vocab, bpe_merges, _ = train(training_text, 256 + len(post_em))
for text in test_texts:
unigram_tokens = sum(len(viterbi(piece, post_em)[0]) for piece in pretokenize(text))
bpe_tokens = len(encode(text, bpe_merges))
assert decode(encode(text, bpe_merges), bpe_vocab) == text
print('Test:', repr(text), '| Unigram', unigram_tokens, '| BPE', bpe_tokens)
print('Vocabulario inicial/final:', len(initial), len(post_em), '| retirado:', repr(removed))
print('Log-verosimilitud inicial/tras EM/tras poda/tras EM:',
*(round(v, 6) for v in (initial_likelihood, em_likelihood,
corpus_log_likelihood(words, pruned), corpus_log_likelihood(words, post_em))))
print('Pérdida al podar:', round(loss, 6), '| caracteres protegidos:', len(protected))Local lab: segmenting, inspecting, and extending
Run the cell locally with Python and libraries sentencepiece, tiktoken, transformers, and torch. Download the official FLORES-200 file if absent and verify its SHA-256. To reuse a copy, specify ORYON_FLORES_ARCHIVE; ORYON_OUTPUT_DIR selects the output directory. Training uses dev sentences in English, Spanish, Chinese, Arabic, and Hindi and records row count and text hash. In ORYON_QUICK=1 it uses only 64 sentences per language and a vocabulary of 2,048 pieces; normal mode requests 8,000 and uses all sentences. The effective vocabulary may be smaller. identity normalization does not guarantee preservation of every separator: check reconstructed strings before claiming reversibility.
Unigram and BPE are trained on the same text and reserve 256 byte-fallback pieces. A sampling seed is requested, but SentencePiece 0.2.2 does not necessarily reproduce the same samples after resetting it in a process; do not expect identical segmentations across runs. The arena allows text editing and offers four examples with deterministic encoding. GPT-2 and cl100k bytes are joined before decoding because an individual piece may split a character. The demonstration corpus is licensed CC BY-SA 4.0.
GPT-2 and SmolLM2-135M base checkpoints are loaded sequentially at pinned revisions. Input and output norms are recorded per row. These matrices are tied in both checkpoints, so equal norms are structural. The GPT-2 reference center is the mean of rows for the eleven bytes F5 through FF, which do not appear in valid UTF-8. This follows the idea of Land and Bartolo, but does not replicate their full protocol. SmolLM2 lacks those eleven rows: its global mean is a different exploratory control, not an equivalent detector. Do not compare their cosines directly. For five nearby pieces, three harmless repetition requests are evaluated and probabilities printed. These are clues, not evidence of under-training, since the format may require a different first token.
Finally, add one new piece to each tokenizer and set its input row, output row, and bias if present to the mean of the old rows. Check that the prefix retains its IDs, old logits remain unchanged, and divergence is below the Jensen bound. The demonstration does not cover prefixes whose tokenization changes. Continued training is optional. With ORYON_CONTINUE_TRAIN=1 in normal mode, specify ORYON_CONTINUE_CORPUS with a real UTF-8 file whose token appears in both initial and held-out portions. The program prints the occurrence count and saves the expanded model. ORYON_TRAIN_STEPS changes the budget. The split is sequential, so construct a file with an appropriate partition for your task. In the quick test without a file, an artificial marker is deliberately added to the corpus to check the flow. Two steps do not prove the model learned its meaning.
"""SentencePiece y diagnóstico de embeddings de modelos causales cacheados."""
import gc
import hashlib
import json
import math
import os
import platform
import tarfile
import urllib.request
from pathlib import Path
from importlib.metadata import version
import sentencepiece as spm
import tiktoken
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
def bytes_to_unicode():
"""Alfabeto reversible ByteLevel publicado con GPT-2."""
bs = list(range(ord('!'), ord('~') + 1)) + list(range(ord('¡'), ord('¬') + 1)) + list(range(ord('®'), ord('ÿ') + 1))
cs = list(bs)
extra = 0
for byte in range(256):
if byte not in bs:
bs.append(byte)
cs.append(256 + extra)
extra += 1
return dict(zip(bs, map(chr, cs)))
SOURCE = 'https://dl.fbaipublicfiles.com/nllb/flores200_dataset.tar.gz'
SHA256 = 'b8b0b76783024b85797e5cc75064eb83fc5288b41e9654dabc7be6ae944011f6'
REVISIONS = {'gpt2': '607a30d783dfa663caf39e06633721c8d4cfcd7e',
'HuggingFaceTB/SmolLM2-135M': '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'}
LANGS = ('eng_Latn', 'spa_Latn', 'zho_Hans', 'arb_Arab', 'hin_Deva')
QUICK = os.environ.get('ORYON_QUICK') == '1'
LIMIT = int(os.environ.get('ORYON_LIMIT', '64' if QUICK else '0'))
OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', './unigram-output'))
OUT.mkdir(parents=True, exist_ok=True)
archive = Path(os.environ.get('ORYON_FLORES_ARCHIVE', str(OUT / 'flores200_dataset.tar.gz')))
if not archive.exists():
archive.parent.mkdir(parents=True, exist_ok=True)
urllib.request.urlretrieve(SOURCE, archive)
with archive.open('rb') as f:
assert hashlib.file_digest(f, 'sha256').hexdigest() == SHA256, 'Hash de FLORES incorrecto'
corpus = []
with tarfile.open(archive, 'r:gz') as tar:
for language in LANGS:
rows = tar.extractfile(f'./flores200_dataset/dev/{language}.dev').read().decode('utf-8').splitlines()
corpus.extend(rows[:LIMIT] if LIMIT else rows)
corpus_path = OUT / 'flores-train.txt'
corpus_path.write_text('\n'.join(corpus) + '\n', encoding='utf-8')
print('Corpus FLORES dev, frases:', len(corpus), 'SHA256:', hashlib.sha256(corpus_path.read_bytes()).hexdigest(), flush=True)
cases = {'aritmetica': '123456789 + 987654321 =', 'espanol': 'El niño aprende español.',
'chino': '机器学习改变世界。', 'codigo': 'def suma(a, b):\n return a + b'}
tokenizers = {}
for kind in ('unigram', 'bpe'):
prefix = str(OUT / ('sp-' + kind))
spm.set_random_generator_seed(2004)
spm.SentencePieceTrainer.train(input=str(corpus_path), model_prefix=prefix, model_type=kind,
vocab_size=2048 if QUICK else 8000, character_coverage=1.0, byte_fallback=True,
hard_vocab_limit=False, shuffle_input_sentence=False, num_threads=1,
normalization_rule_name='identity', remove_extra_whitespaces=False,
add_dummy_prefix=True, minloglevel=2)
sp = spm.SentencePieceProcessor(model_file=prefix + '.model')
tokenizers[kind] = sp
text = cases['espanol']
spm.set_random_generator_seed(2004)
samples = [sp.encode(text, out_type=str, enable_sampling=True, nbest_size=-1, alpha=0.25) for _ in range(3)]
print(kind, 'vocabulario efectivo:', sp.vocab_size(), 'muestras estocásticas:', samples, flush=True)
print('Semilla solicitada 2004; SentencePiece no garantiza reproducir cada muestra al reiniciarla en el mismo proceso.', flush=True)
arena = {'source': SOURCE, 'archive_sha256': SHA256, 'partition': 'dev',
'languages': LANGS, 'limit_per_language': LIMIT,
'corpus_sha256': hashlib.sha256(corpus_path.read_bytes()).hexdigest(),
'sentencepiece_version': version('sentencepiece'), 'tiktoken_version': version('tiktoken'),
'sentencepiece_options': {'normalization': 'identity', 'remove_extra_whitespaces': False,
'add_dummy_prefix': True, 'byte_fallback': True, 'vocab_requested': 2048 if QUICK else 8000,
'training': 'sin barajado, un hilo'}, 'cases': []}
for label, text in cases.items():
encodings = {}
for kind, sp in tokenizers.items():
ids = sp.encode(text, out_type=int)
decoded = sp.decode(ids)
encodings['sp_' + kind] = {'ids': ids, 'pieces': sp.encode(text, out_type=str),
'decoded': decoded, 'roundtrip_exact': decoded == text, 'vocab_size': sp.vocab_size()}
for name in ('gpt2', 'cl100k_base'):
enc = tiktoken.get_encoding(name)
ids = enc.encode_ordinary(text)
encodings[name] = {'ids': ids, 'token_bytes_hex': [enc.decode_single_token_bytes(i).hex() for i in ids],
'decoded': enc.decode(ids)}
assert b''.join(enc.decode_single_token_bytes(i) for i in ids) == text.encode('utf-8')
assert all(encodings[name]['decoded'] == text for name in ('gpt2', 'cl100k_base'))
arena['cases'].append({'id': label, 'text': text, 'utf8_hex': text.encode('utf-8').hex(),
'characters': list(text), 'encodings': encodings})
(OUT / 'arena-data.json').write_text(json.dumps(arena, ensure_ascii=False, indent=2), encoding='utf-8')
torch.manual_seed(2004)
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
models = []
for name, revision in REVISIONS.items():
print('Analizando', name, flush=True)
tokenizer = AutoTokenizer.from_pretrained(name, revision=revision)
model = AutoModelForCausalLM.from_pretrained(name, revision=revision, torch_dtype=torch.float32).to(device).eval()
ein = model.get_input_embeddings().weight
eout = model.get_output_embeddings().weight
tied = ein is eout
with torch.inference_mode():
a = ein.float(); b = eout.float()
ni = torch.linalg.vector_norm(a, dim=1)
no = torch.linalg.vector_norm(b, dim=1)
# F5..FF no pueden iniciar ningún escalar Unicode válido. Son controles
# de byte del vocabulario ByteLevel, no una prueba de frecuencia de entrenamiento.
vocab = tokenizer.get_vocab(); alphabet = bytes_to_unicode()
refs = [vocab[alphabet[i]] for i in range(0xF5, 0x100) if alphabet[i] in vocab]
# SmolLM2 carece de esas once filas; su media global es otro control,
# no el detector propuesto para pesos atados en el artículo.
reference_kind = 'bytes_invalidos' if len(refs) == 11 else 'media_global'
center = b[refs].mean(dim=0) if len(refs) == 11 else b.mean(dim=0)
cosine = torch.nn.functional.cosine_similarity(b, center[None, :], dim=1, eps=1e-12)
ni_cpu, no_cpu, cos_cpu = ni.cpu(), no.cpu(), cosine.cpu()
assert len(ni_cpu) == len(tokenizer) and torch.isfinite(cos_cpu).all()
if tied:
assert torch.equal(ni_cpu, no_cpu)
order = torch.argsort(cos_cpu, descending=True).tolist()
chosen = []
for idx in order:
if idx in tokenizer.all_special_ids or idx in refs:
continue
token = tokenizer.decode([idx], clean_up_tokenization_spaces=False)
if not token.strip() or '\ufffd' in token or any(ord(c) < 32 for c in token):
continue
if tokenizer(token, add_special_tokens=False)['input_ids'] != [idx]:
continue
chosen.append((idx, token))
if len(chosen) == 5:
break
probes = []
for idx, token in chosen:
prompts = [f'Repeat exactly: {token}\nAnswer:', f'Copy this text: {token}\nCopy:',
f'Write again: {token}\nAgain:']
probabilities, greedy = [], []
for prompt in prompts:
ids = tokenizer(prompt, return_tensors='pt', add_special_tokens=False).input_ids.to(device)
logits = model(ids).logits[0, -1].float()
probabilities.append(float(logits.softmax(-1)[idx].item()))
greedy.append(int(logits.argmax().item()))
probes.append({'id': idx, 'token': token, 'input_norm': float(ni_cpu[idx]),
'reference_cosine': float(cos_cpu[idx]), 'prompts': prompts,
'next_token_probabilities': probabilities, 'greedy_next_ids': greedy,
'max_probability': max(probabilities)})
points = [[round(float(ni_cpu[i]), 5), round(float(no_cpu[i]), 5), round(float(cos_cpu[i]), 5)]
for i in range(len(ni_cpu))]
result = {'name': name, 'revision': revision, 'vocab_size': len(points), 'tied': tied,
'reference_ids': refs, 'reference_kind': reference_kind,
'reference_bytes_hex': [f'{i:02x}' for i in range(0xF5, 0x100)] if len(refs) == 11 else [],
'points_columns': ['input_l2', 'output_l2', 'cosine_output_to_reference_mean'],
'tokens_bytelevel': tokenizer.convert_ids_to_tokens(list(range(len(tokenizer)))),
'points': points, 'probes': probes}
print(name, 'filas:', len(points), 'compartidos:', tied, 'referencia:', refs, flush=True)
for p in probes:
print(' candidato', p['id'], repr(p['token']), 'coseno', round(p['reference_cosine'], 5),
'máxima probabilidad en tres prefijos:', f"{p['max_probability']:.8g}", flush=True)
# La cota requiere que el prefijo siga tokenizado igual y que cada nueva
# fila y sesgo sean exactamente la media de las antiguas.
prefix = 'The meaning of life is'
old_ids = tokenizer(prefix, return_tensors='pt', add_special_tokens=False).input_ids.to(device)
with torch.inference_mode():
before = model(old_ids).logits[0, -1].float()
old_v = before.numel()
input_mean = model.get_input_embeddings().weight.detach().float().mean(dim=0)
output_layer = model.get_output_embeddings()
output_mean = output_layer.weight.detach().float().mean(dim=0)
bias_mean = output_layer.bias.detach().float().mean() if output_layer.bias is not None else None
assert tokenizer.add_tokens(['oryon_token_nuevo_zz42']) == 1
model.resize_token_embeddings(len(tokenizer), mean_resizing=False)
with torch.no_grad():
model.get_input_embeddings().weight[old_v].copy_(input_mean)
output_layer = model.get_output_embeddings()
output_layer.weight[old_v].copy_(output_mean)
if bias_mean is not None:
output_layer.bias[old_v].copy_(bias_mean)
new_ids = tokenizer(prefix, return_tensors='pt', add_special_tokens=False).input_ids.to(device)
assert torch.equal(old_ids, new_ids)
with torch.inference_mode():
after = model(new_ids).logits[0, -1].float()
max_delta = float((before - after[:old_v]).abs().max())
kl = float(torch.logsumexp(after.double(), 0) - torch.logsumexp(before.double(), 0))
bound = math.log1p(1 / old_v)
assert max_delta < 2e-4 and -1e-6 <= kl <= bound + 2e-6
result['vocab_expansion'] = {'new_token': 'oryon_token_nuevo_zz42', 'old_vocab': old_v,
'new_vocab': len(tokenizer), 'unchanged_prefix': prefix, 'max_old_logit_delta': max_delta,
'kl_nats': kl, 'jensen_bound_nats': bound, 'bias_averaged': bias_mean is not None}
print(' expansión: KL', kl, 'cota', bound, 'error logits anteriores', max_delta, flush=True)
# Entrenamiento continuo opcional para el lector. La prueba rápida reduce
# deliberadamente el presupuesto y no demuestra adaptación del token.
if name.endswith('SmolLM2-135M') and os.environ.get('ORYON_CONTINUE_TRAIN') == '1':
training_path = os.environ.get('ORYON_CONTINUE_CORPUS')
if training_path:
lines = Path(training_path).read_text(encoding='utf-8').splitlines()
corpus_kind = 'archivo del lector'
elif QUICK:
# Solo para probar el flujo: el sufijo es artificial y no mide adaptación útil.
lines = [line + ' oryon_token_nuevo_zz42' for line in corpus]
corpus_kind = 'FLORES con marcador artificial en cada línea, solo prueba rápida'
else:
raise ValueError('Indica ORYON_CONTINUE_CORPUS: archivo UTF-8 real para adaptación')
lines = [line for line in lines if line.strip()]
if len(lines) < 10:
raise ValueError('El corpus continuo necesita al menos diez líneas')
cut = max(1, int(len(lines) * 0.8))
train_lines, heldout = lines[:cut], lines[cut:]
new_id = old_v
occurrences = sum(tokenizer(line, add_special_tokens=False).input_ids.count(new_id) for line in train_lines)
heldout_occurrences = sum(tokenizer(line, add_special_tokens=False).input_ids.count(new_id) for line in heldout)
if not occurrences or not heldout_occurrences:
raise ValueError('El token añadido debe aparecer tanto en entrenamiento como en retención')
steps = int(os.environ.get('ORYON_TRAIN_STEPS', '2' if QUICK else '1000'))
accumulation = 1 if QUICK else 4
optim = torch.optim.AdamW(model.parameters(), lr=2e-5)
model.train()
for step in range(steps):
optim.zero_grad(set_to_none=True)
losses = []
for micro in range(accumulation):
line = train_lines[(step * accumulation + micro) % len(train_lines)]
batch = tokenizer(line, return_tensors='pt', add_special_tokens=False,
truncation=True, max_length=128).input_ids.to(device)
if batch.shape[1] < 2:
continue
loss = model(batch, labels=batch).loss
(loss / accumulation).backward()
losses.append(float(loss.detach()))
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optim.step()
if step == 0 or step == steps - 1:
print(' adaptación paso', step + 1, 'loss', sum(losses) / max(1, len(losses)), flush=True)
model.eval()
with torch.inference_mode():
val_losses = []
for line in heldout[:8 if QUICK else 128]:
batch = tokenizer(line, return_tensors='pt', add_special_tokens=False,
truncation=True, max_length=128).input_ids.to(device)
if batch.shape[1] >= 2:
val_losses.append(float(model(batch, labels=batch).loss))
print(' corpus:', corpus_kind, '; token nuevo en entrenamiento / retención:', occurrences,
'/', heldout_occurrences, 'loss media por frase retenida:',
sum(val_losses) / len(val_losses) if val_losses else None, flush=True)
save_dir = OUT / 'modelo-ampliado'
model.save_pretrained(save_dir)
tokenizer.save_pretrained(save_dir)
result['continuous_training'] = {'steps': steps, 'gradient_accumulation': accumulation,
'train_lines': len(train_lines), 'heldout_lines': len(heldout),
'corpus_kind': corpus_kind,
'corpus_sha256': hashlib.sha256(('\n'.join(lines) + '\n').encode('utf-8')).hexdigest(),
'new_token_occurrences_in_train': occurrences, 'new_token_occurrences_heldout': heldout_occurrences,
'heldout_mean_sentence_loss':
sum(val_losses) / len(val_losses) if val_losses else None, 'checkpoint': str(save_dir)}
del optim
if 'loss' in locals(): del loss
if 'batch' in locals(): del batch
models.append(result)
del model, tokenizer, ein, eout, a, b, center, ni, no, cosine
del output_layer, input_mean, output_mean, bias_mean, before, after, old_ids, new_ids, logits, ids
gc.collect()
if device.type == 'cuda': torch.cuda.empty_cache()
report = {'seed': 2004, 'device': str(device), 'python': platform.python_version(),
'torch': version('torch'), 'transformers': version('transformers'),
'reference': 'https://arxiv.org/abs/2405.05417', 'models': models}
(OUT / 'embedding-data.json').write_text(json.dumps(report, ensure_ascii=False, separators=(',', ':')), encoding='utf-8')
print('Datos guardados en', OUT, flush=True)
npm run lab and open the connection link.Exercises
Check the counts and path sum before solving:
from collections import Counter
from math import prod
corpus = ['aa'] * 5 + ['bc'] * 3
symbols = Counter(c for fragment in corpus for c in fragment)
pairs = Counter(pair for fragment in corpus for pair in zip(fragment, fragment[1:]))
scores = {''.join(pair): count / (symbols[pair[0]] * symbols[pair[1]])
for pair, count in pairs.items()}
print('Símbolos:', dict(symbols), '| pares:', {''.join(k): v for k, v in pairs.items()})
print('Heurística WordPiece:', scores)
p = {'a': .20, 'b': .10, 'ab': .25, 'ba': .15, 'aba': .20, 'c': .10}
paths = [('aba',), ('ab', 'a'), ('a', 'ba'), ('a', 'b', 'a')]
weights = [prod(p[t] for t in path) for path in paths]
print('Pesos de aba:', weights, '| marginal:', round(sum(weights), 6))def viterbi_segment(word, logp):
pass
Step 1 of 3. What bound does convexity of the exponential give for a new logit?
def candidates(norms, counts, max_norm, max_count):
pass
Unigram sums or maximizes paths in a lattice. Segmentation changes representation and cost. Evaluate tokenizer and model together, preserve data provenance, and treat anomalous candidates as hypotheses requiring tests.