Module contents
Lesson 2 of 26Core 75 min

Text as bytes: Unicode, UTF-8 and the vocabulary problem

Study Unicode code points, UTF-8, and normalization before comparing tokenization units by coverage, vocabulary size, sequence length, and computational cost.

After this lesson you can

  • Encode and decode UTF-8 code points by hand and explain self-synchronization and ASCII compatibility.
  • Apply NFC and NFKC and anticipate their effects on tokenizing code, formulas, and multilingual text.
  • Compare byte, character, word, and subword tokenization by vocabulary size, sequence length, and out-of-vocabulary coverage.
  • Measure tokenizer fertility and bytes per token across languages and domains.
  • Calculate the parameter and FLOP costs of embeddings and the output head as a function of vocabulary size.

Before you start

A sequence of bytes comes before the token

A new proper name, a formula, or an emoji may not appear in the training word vocabulary. A general model needs a way to represent them without assigning an entry to every imaginable string. To design one, first distinguish what you see on screen from the numbers and bytes used to store it.

The text é can consist of one code point or of e followed by a combining accent. They look similar, but their sequences and bytes differ until normalized. A family emoji may appear as one unit while containing several people and invisible connectors. Its length depends on what you count.

Code points and graphemes

Unicode assigns values called code points between U+0000 and U+10FFFF. The range is divided into 17 planes of 65,536 positions. Not every point is an assigned character, and surrogates U+D800 through U+DFFF are not Unicode scalar values. They form pairs in UTF-16 but are not encoded as isolated characters in UTF-8.

An extended grapheme approximates a unit of text perceived as one character and can contain several code points. For example, e plus U+0301 combines two points in one grapheme, and the sequence 👨‍👩‍👧‍👦 contains four people and three U+200D connectors: seven code points and 25 UTF-8 bytes. Specific segmentation follows UAX #29 and may depend on the Unicode version.

InteractiveFrom character to bytes

Up to 512 UTF-16 units. Text is kept as entered, without normalization.

é
U+00E9
C3
11000011
A9
10101001
Space
U+0020
20
00100000
e
U+0065
65
01100101
́
U+0301
CC
11001100
81
10000001
Space
U+0020
20
00100000
中
U+4E2D
E4
11100100
B8
10111000
AD
10101101
Space
U+0020
20
00100000
👨
U+1F468
F0
11110000
9F
10011111
91
10010001
A8
10101000
‍
U+200D · ZWJ
E2
11100010
80
10000000
8D
10001101
👩
U+1F469
F0
11110000
9F
10011111
91
10010001
A9
10101001
‍
U+200D · ZWJ
E2
11100010
80
10000000
8D
10001101
👧
U+1F467
F0
11110000
9F
10011111
91
10010001
A7
10100111
‍
U+200D · ZWJ
E2
11100010
80
10000000
8D
10001101
👦
U+1F466
F0
11110000
9F
10011111
91
10010001
A6
10100110

Blue marks the first byte of each scalar; gray marks its continuations 10xxxxxx. ASCII occupies one byte. Color identifies position, not a probability.

Extended graphemes
é␠é␠中␠👨‍👩‍👧‍👦

Graphemes follow the browser’s extended segmentation and may depend on its Unicode version; they are approximate editing units, not necessarily glyphs.

Code points
14
Bytes UTF-8
36
Extended graphemes
7
Inspect the code points, bytes, and graphemes of the text you enter.

How UTF-8 is encoded

UTF-8 represents each scalar value with one to four bytes. Its patterns, specified by RFC 3629, are:

Scalar valueByte pattern
U+0000 to U+007F0xxxxxxx
U+0080 to U+07FF110xxxxx 10xxxxxx
U+0800 to U+FFFF, excluding surrogates1110xxxx 10xxxxxx 10xxxxxx
U+10000 to U+10FFFF11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

The x contain the value’s bits, most significant first. ASCII retains exactly its bytes because U+0000 through U+007F use 0xxxxxxx. For example, U+20AC is 0010 0000 1010 1100; grouping its bits as 0010 000010 101100 and adding headers produces E2 82 AC.

Headers determine the length of a valid encoding, and continuation bytes start with 10. Thus no valid scalar encoding is a prefix of another. In a valid sequence, starting inside a character leaves at most three continuation bytes before the next start or the end. If you are already at the start of a four-byte character, the next start, if any, is four positions later. Distinguish that offset from the maximum number of continuations.

Checking the bit pattern alone is insufficient. C0 80 is an overlong representation of U+0000, ED A0 80 would encode a surrogate, and F4 90 80 80 would exceed U+10FFFF. All three are invalid. A decoder must also reject orphan continuation bytes and truncated sequences. Replacement with U+FFFD is a different decoder policy from strict decoding and does not make the original bytes valid UTF-8.

Normalization does not always preserve meaning

Unicode normalization defines equivalences and a canonical form. NFD decomposes canonical equivalents and orders combining marks; NFC recomposes where appropriate. NFKD and NFKC add compatibility equivalences, using decomposition and, for NFKC, recomposition. UAX #15 specifies the rules and their limits.

For example, NFC can convert e plus U+0301 to U+00E9. NFKC also transforms ① into 1, the ligature fi into fi, and x² into x2. The last transformation can change a formula or code meaning. NFKC is not a reversible cleanup. Keep the original for reproducibility and state normalization before training or evaluation.

[ ]Normalization and vocabulary costBrowser
import unicodedata
for original in ('e\u0301', '①', 'fi', 'x²'):
    print(repr(original), 'NFC:', repr(unicodedata.normalize('NFC', original)),
          'NFKC:', repr(unicodedata.normalize('NFKC', original)))
d, layers, vocab = 2048, 16, 128000
fraction = (2*vocab*d)/(12*layers*d*d+2*vocab*d)
print('Fracción de embedding y cabeza sin atar:', round(fraction, 8))

Units and open vocabulary

The open-vocabulary problem arises when evaluation text contains a form absent from the dictionary. A word vocabulary often needs an unknown symbol or an alternative strategy. Characters cover new combinations of previously seen characters, but not necessarily unseen characters. A vocabulary of the 256 byte values can represent any valid UTF-8 string, although individual tokens need not coincide with characters or grapheme boundaries.

Subwords group frequent sequences and retain a way to split others if the tokenizer includes byte coverage or an equivalent fallback. There is no universal optimum. Smaller units increase sequence length; a larger vocabulary makes tables and output more expensive, and rare entries receive fewer training examples.

InteractiveFrom byte to word

Each bar summarizes the same held-out set: mean length per sentence. Click a row to select its granularity.

The T² readout compares mean squared sentence lengths against bytes. It indicates quadratic full-attention work, not measured time or total model cost.

Training uses the first 256 sentences of each language in FLORES-200 dev and evaluation the first 256 in devtest. ByteLevel BPEs were actually trained on all five languages and start from 256 bytes; actual vocabularies can differ from requested sizes. Characters and words also use a shared five-language vocabulary with UNK. “Fragment” means a space-separated sequence: an approximation, especially poor for Chinese.

A fragment is unreproducible if it contains a character absent from the character vocabulary or is not entirely in the word vocabulary. The word control discards separators: it is not a reversible codec. Bytes and BPE cover bytes, even for unseen fragments; coverage does not imply learned meaning. See FLORES-200, CC BY-SA 4.0; the measurement script and splits accompany the interactive data.

Bytes UTF-8
Actual vocabulary
256
Tokens per sentence
130.71
Unreproducible fragments
0.00 %
Mean T² / bytes
1.000 ×
Compare granularities and measurements under the stated corpus and protocol.

Measuring length and coverage

Tokenizer compression metrics depend on the corpus. Bytes per token is total text bytes divided by total produced tokens. For parallel sentences across languages, also calculate tokens per sentence and each language’s ratio to English on the same sentences. Fertility is often tokens per word under a particular definition of word; scripts without spaces require special care. Separate training from evaluation and document treatment of spaces, normalization, and special symbols.

A tokenizer with more bytes per token yields shorter sequences on that corpus. This alone measures neither bits of information nor model performance. The source coding theorem concerns bit lengths under assumptions about a distribution and code. It does not automatically turn a variable-vocabulary token count into entropy. Rust and colleagues study multilingual tokenization differences and their relationship to downstream tasks under their protocols.

Vocabulary, parameters, and compute

For a transformer of width dd and vocabulary VV, an embedding table has VdVd parameters. An untied dense output head adds another VdVd; tied weights share that matrix, though the output projection is still computed. If each of LL blocks is approximated by 12d212d^2 parameters and biases and norms are omitted, the parameter fraction in both untied matrices is

2Vd12Ld2+2Vd.\frac{2Vd}{12Ld^2+2Vd}.

The choice of vocabulary size also affects compute. A dense vector multiplication by the head costs approximately 2Vd2Vd FLOPs per token if one multiplication and one addition count as two operations. With materialized logits, a batch of BB sequences of length TT needs BTVBTV logit values. Memory depends on dtype and whether the implementation materializes them. Full attention has components quadratic in TT; cache, mask, and kernel optimizations change effective costs. Fewer tokens can save attention work even when VV is larger, but no single quantity determines total cost.

InteractiveWhat does the vocabulary cost?

The vocabulary adds a V × d table and d × V projection. Tying weights saves parameters, but output multiplication is still computed. The bars compare forward costs per token; they do not measure real time.

Output projection77.2 M FLOPs · 29.0 %
Block projections and MLP170 M FLOPs · 63.9 %
QK and attention × V products18.9 M FLOPs · 7.1 %

With this configuration: 38.6 M vocabulary parameters and 84.9 M in block matrices; the full logits tensor contains B × T × V = 51.5 M elements.

Estimate: one multiplication and one addition count as 2 FLOPs. Per layer GPT-2 uses 12d² matrix parameters; Llama 3 8B uses 13d² with grouped attention (KV width d/4) and SwiGLU MLP width 3.5d. Changing d preserves these proportions. Block matrices cost 2L·P per token; the two causal-attention products cost 2Ld(T+1) per token averaged over all T prefixes. The head costs 2Vd. Normalization, activations, softmax, biases, positional embeddings, temporary storage and backward are excluded. This is an operations model, not an exact count or actual peak memory.

BF16 logits: 2BTV bytes if all are materialized; some fused implementations avoid that matrix, and generation needs less when only the last token is used. Initial values: GPT-2 small y Llama 3; its matrices follow the official code and sizes from the Llama 3 8B configuration file. After changing controls values are hypothetical and may exceed the checkpoint’s supported context.

Reference architecture
50257
768
12
1024
1
Input and output weights
Vocabulary parameters
38.6 M
Estimated fraction
31.2 %
Batch BF16 logits
98.2 MiB
Change vocabulary and architecture under the stated approximations.

The GPT-2 configuration declares 50,257 entries. Llama 3 combines about 128,000 base tokens with 256 reserved special tokens; Gemma-7B uses approximately 256,000 according to Tao and colleagues. These authors study vocabulary, parameters, and compute together. In an experiment with 2.3·10²¹ FLOPs, changing from 32,000 to 43,000 entries accompanies an ARC-Challenge accuracy increase from 29.1% to 32.0%. The optimum changes with scale under their assumptions and corpus; this is not a rule to always choose the largest vocabulary.

Lab: encoding and validating UTF-8

Each scalar is divided into bit groups and prefixed with the headers required by RFC 3629. The decoder checks headers, continuations, minimum length, surrogates, and the U+10FFFF maximum. It does not reject noncharacters such as U+FDD0: they are valid scalars even though their uses are restricted. Compare both functions with Python’s strict codecs at boundaries and on reproducible samples. Random testing helps find errors but does not prove correctness for every possible sequence.

[ ]UTF-8 using bit operationsBrowser
"""Codificación y decodificación UTF-8 estrictas a partir de escalares Unicode."""
import random


def utf8_encode(codepoints):
    result = bytearray()
    for cp in codepoints:
        if not isinstance(cp, int) or not 0 <= cp <= 0x10FFFF or 0xD800 <= cp <= 0xDFFF:
            raise ValueError('Se requieren valores escalares Unicode')
        if cp <= 0x7F:
            result.append(cp)
        elif cp <= 0x7FF:
            result.extend((0xC0 | (cp >> 6), 0x80 | (cp & 0x3F)))
        elif cp <= 0xFFFF:
            result.extend((0xE0 | (cp >> 12), 0x80 | ((cp >> 6) & 0x3F),
                           0x80 | (cp & 0x3F)))
        else:
            result.extend((0xF0 | (cp >> 18), 0x80 | ((cp >> 12) & 0x3F),
                           0x80 | ((cp >> 6) & 0x3F), 0x80 | (cp & 0x3F)))
    return bytes(result)


def utf8_decode(data):
    result = []
    data = bytes(data)
    i = 0
    while i < len(data):
        first = data[i]
        if first <= 0x7F:
            n, cp, minimum = 1, first, 0
        elif 0xC2 <= first <= 0xDF:
            n, cp, minimum = 2, first & 0x1F, 0x80
        elif 0xE0 <= first <= 0xEF:
            n, cp, minimum = 3, first & 0x0F, 0x800
        elif 0xF0 <= first <= 0xF4:
            n, cp, minimum = 4, first & 0x07, 0x10000
        else:
            raise ValueError('Cabecera inválida o continuación huérfana')
        if i + n > len(data):
            raise ValueError('Secuencia truncada')
        for byte in data[i + 1:i + n]:
            if not 0x80 <= byte <= 0xBF:
                raise ValueError('Continuación inválida')
            cp = (cp << 6) | (byte & 0x3F)
        if cp < minimum or cp > 0x10FFFF or 0xD800 <= cp <= 0xDFFF:
            raise ValueError('Secuencia sobrelarga o escalar inválido')
        result.append(cp)
        i += n
    return result


boundaries = [0, 0x7F, 0x80, 0x7FF, 0x800, 0xD7FF, 0xE000,
              0xFDD0, 0xFFFF, 0x10000, 0x10FFFF]
invalid = ['80', 'C0 80', 'C1 BF', 'C2', 'C2 41', 'E0 80 AF',
           'ED A0 80', 'ED BF BF', 'E1 80', 'F0 8F BF BF',
           'F4 90 80 80', 'F5 80 80 80', 'FF']
for cp in boundaries:
    encoded = utf8_encode([cp])
    assert encoded == chr(cp).encode('utf-8')
    assert utf8_decode(encoded) == [cp]
for cp in [-1, 0xD800, 0xDFFF, 0x110000]:
    try:
        utf8_encode([cp])
    except ValueError:
        pass
    else:
        raise AssertionError(cp)
for case in invalid:
    raw = bytes.fromhex(case)
    try:
        utf8_decode(raw)
    except ValueError:
        pass
    else:
        raise AssertionError(case)
    try:
        raw.decode('utf-8', errors='strict')
    except UnicodeDecodeError:
        pass
    else:
        raise AssertionError('Python aceptó ' + case)

randomizer = random.Random(2002)
for _ in range(1500):
    cps = []
    for _ in range(randomizer.randrange(9)):
        cp = randomizer.randrange(0x110000)
        while 0xD800 <= cp <= 0xDFFF:
            cp = randomizer.randrange(0x110000)
        cps.append(cp)
    expected = ''.join(map(chr, cps)).encode('utf-8')
    assert utf8_encode(cps) == expected and utf8_decode(expected) == cps
for _ in range(1500):
    raw = bytes(randomizer.randrange(256) for _ in range(randomizer.randrange(9)))
    try:
        ours = utf8_decode(raw)
    except ValueError:
        ours = None
    try:
        reference = list(map(ord, raw.decode('utf-8', errors='strict')))
    except UnicodeDecodeError:
        reference = None
    assert ours == reference

# Comprueba exhaustivamente toda secuencia de uno y dos bytes.
for size in (1, 2):
    for value in range(256 ** size):
        raw = value.to_bytes(size, 'big')
        try:
            ours = utf8_decode(raw)
        except ValueError:
            ours = None
        try:
            reference = list(map(ord, raw.decode('utf-8', errors='strict')))
        except UnicodeDecodeError:
            reference = None
        assert ours == reference

family = '👨‍👩‍👧‍👦'
print('Fronteras válidas:', len(boundaries), '| secuencias inválidas:', len(invalid))
print('Pruebas aleatorias: 1500 de escalares y 1500 de bytes, semilla 2002')
print('Comprobadas exhaustivamente las 65 792 secuencias de uno o dos bytes')
print('Familia: puntos de código', len(family), '| bytes', len(utf8_encode(map(ord, family))))
print('añ€😀: bytes', len(utf8_encode(map(ord, 'añ€😀'))))

Local lab: comparing tokenizers across languages

Compare the GPT-2, SmolLM2-135M base, and Qwen2.5-0.5B-Instruct tokenizers on Spanish, English, simplified Chinese, Modern Standard Arabic, and Hindi. The corpus is FLORES-200, released under CC BY-SA 4.0, with sentences aligned across languages by index. dev has 997 sentences per language and devtest has 1,012. The program checks the file’s SHA-256 hash and uses the same prefix of indices for each language. It makes no random choices or additional normalization.

For each language and tokenizer, sum tokens and UTF-8 bytes of the original sentences without added special tokens. Compute tokens per sentence, bytes per token, and the ratio of tokens per sentence to English. To approximate fertility, it also reports tokens per whitespace-separated fragment. That rule is not a linguistic segmenter: in Chinese and texts without spaces between words, the denominator should not be interpreted as a reliable word count. The figures depend on sentences, their domain, the tokenizer, and its preprocessing. They do not by themselves measure linguistic quality or model accuracy.

The program checks what happens when each sentence is encoded and decoded again. The Qwen tokenizer used includes NFC in its own configuration, although the lab does not normalize text before passing it in. In our short sample, GPT-2 and SmolLM2 recovered every sentence exactly; Qwen changed 4 of 256 Arabic sentences and 20 of 256 Hindi sentences, all to NFC form. Arabic bytes changed although the total remained 53,399. Reconstructed Hindi bytes totaled 85,128 versus 85,044 original bytes. Special tokens appeared zero times. Bytes per token uses the original input; when reconstructed bytes differ, it does not represent lossless compression of the original.

The same program trains three small byte-level BPE models on the dev sentences from the five languages and evaluates on devtest, alongside byte, code-point, and whitespace-fragment controls. Each control’s vocabulary is fitted only on training data. The BPE models include the complete 256-byte alphabet and check that decoding reproduces the original sentences. The fragment control discards separators and is not a reversible codec. The OOV indicator counts test fragments that cannot be represented by the trained vocabulary, not fragments the model has never seen. Bytes and BPE cover any UTF-8 text even if they have not seen a complete word. The displayed relative attention cost is the mean of squared lengths, not the square of the mean.

Install transformers and tokenizers; model weights and a GPU are unnecessary. By default the program downloads the official file of about 26 MB to ORYON_OUTPUT_DIR, or uses ORYON_FLORES_ARCHIVE if it already exists. Published tokenizers are pinned to identified revisions and downloaded if missing. ORYON_QUICK=1 limits each language to 64 lines per split, while ORYON_LIMIT changes that number. The figure was checked with 256 per split. In that run GPT-2, SmolLM2, and Qwen produced 26.867, 28.238, and 27.812 tokens per English sentence, versus 197.496, 140.508, and 120.035 for Hindi. This is a specific sample, not a universal ranking.

[ ]Tokenizer fertility with FLORES-200Local GPU
"""FLORES-200: fertilidad de tokenizadores y granularidades reproducibles."""
import hashlib
import json
import os
import platform
import re
import tarfile
import unicodedata
import urllib.request
from pathlib import Path
from importlib.metadata import version

from transformers import AutoTokenizer
from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders

SOURCE = 'https://dl.fbaipublicfiles.com/nllb/flores200_dataset.tar.gz'
SHA256 = 'b8b0b76783024b85797e5cc75064eb83fc5288b41e9654dabc7be6ae944011f6'
LANGS = {'eng_Latn': 'inglés', 'spa_Latn': 'español', 'zho_Hans': 'chino simplificado',
         'arb_Arab': 'árabe estándar', 'hin_Deva': 'hindi'}
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', './fertilidad-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)
    print('Descargando archivo oficial FLORES-200:', SOURCE, flush=True)
    urllib.request.urlretrieve(SOURCE, archive)
with archive.open('rb') as f:
    digest = hashlib.file_digest(f, 'sha256').hexdigest()
if digest != SHA256:
    raise ValueError('El hash del archivo FLORES-200 no coincide con la versión declarada')

corpus = {}
with tarfile.open(archive, 'r:gz') as t:
    for part in ('dev', 'devtest'):
        corpus[part] = {}
        for lang in LANGS:
            member = f'./flores200_dataset/{part}/{lang}.{part}'
            rows = t.extractfile(member).read().decode('utf-8').splitlines()
            assert all(rows), 'Hay una línea vacía inesperada'
            corpus[part][lang] = rows[:LIMIT] if LIMIT else rows
        assert len({len(x) for x in corpus[part].values()}) == 1

train = corpus['dev']
test = corpus['devtest']
print('FLORES-200, líneas por idioma dev / devtest:', len(train['eng_Latn']), len(test['eng_Latn']), flush=True)
# Fragmentos no vacíos separados por espacios: no pretende segmentar palabras del chino.
fragments = lambda text: re.findall(r'\S+', text)
all_train = [line for lang in LANGS for line in train[lang]]
word_vocab = {w for line in all_train for w in fragments(line)}
char_vocab = {ch for line in all_train for ch in line}


def summarize(lengths, texts):
    total = sum(lengths)
    total_bytes = sum(len(text.encode('utf-8')) for text in texts)
    fragment_count = sum(len(fragments(text)) for text in texts)
    assert total > 0
    return {'sentences': len(texts), 'tokens_total': total, 'bytes_total': total_bytes,
            'mean_tokens': total / len(texts), 'bytes_per_token': total_bytes / total,
            'whitespace_fragments': fragment_count,
            'tokens_per_whitespace_fragment': total / fragment_count if fragment_count else None,
            'mean_attention_quadratic': sum(n * n for n in lengths) / len(lengths),
            'tokens_per_sentence': lengths}


def unknown_fraction(texts, kind):
    all_words = [word for line in texts for word in fragments(line)]
    if kind == 'byte':
        missing = 0
    elif kind == 'char':
        missing = sum(any(ch not in char_vocab for ch in word) for word in all_words)
    elif kind == 'word':
        missing = sum(word not in word_vocab for word in all_words)
    else:
        raise ValueError(kind)
    return {'unknown_words': missing, 'words': len(all_words),
            'unknown_word_fraction': missing / len(all_words) if all_words else 0.}


def collect(id, label, vocab_size, encode, unknown_kind):
    langs = {}
    for lang, texts in test.items():
        lengths = [len(encode(line)) for line in texts]
        stats = summarize(lengths, texts)
        stats.update(unknown_fraction(texts, unknown_kind))
        langs[lang] = stats
    base = langs['eng_Latn']['mean_tokens']
    for stats in langs.values():
        stats['tokens_per_sentence_vs_english'] = stats['mean_tokens'] / base
        stats['attention_quadratic_vs_english'] = stats['mean_attention_quadratic'] / langs['eng_Latn']['mean_attention_quadratic']
    return {'id': id, 'label': label, 'vocab_size': vocab_size, 'by_language': langs}


units = [
    collect('bytes', 'Bytes UTF-8', 256, lambda x: list(x.encode('utf-8')), 'byte'),
    collect('caracteres', 'Puntos de código', len(char_vocab) + 1, list, 'char'),
    collect('palabras', 'Fragmentos por espacios', len(word_vocab) + 1, fragments, 'word'),
]
for size in (512, 1024, 2048):
    tokenizer = Tokenizer(models.BPE())
    tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
    tokenizer.decoder = decoders.ByteLevel()
    trainer = trainers.BpeTrainer(vocab_size=size, initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
                                  show_progress=False, min_frequency=2)
    tokenizer.train_from_iterator(all_train, trainer=trainer)
    def encode(text, tok=tokenizer):
        ids = tok.encode(text, add_special_tokens=False).ids
        assert tok.decode(ids, skip_special_tokens=False) == text
        return ids
    units.append(collect(f'bpe-{size}', f'BPE por bytes, objetivo {size}', tokenizer.get_vocab_size(), encode, 'byte'))

print('Granularidades sobre devtest, por idioma:', flush=True)
for unit in units:
    print(unit['label'], '| vocabulario', unit['vocab_size'], flush=True)
    for lang, values in unit['by_language'].items():
        byte_t2 = units[0]['by_language'][lang]['mean_attention_quadratic']
        print(LANGS[lang], '| tokens/frase', round(values['mean_tokens'], 8),
              '| OOV por fragmento', round(values['unknown_word_fraction'], 8),
              '| media T²', round(values['mean_attention_quadratic'], 8),
              '| media T² / bytes', round(values['mean_attention_quadratic'] / byte_t2, 8), flush=True)

models = [
    ('GPT-2', 'gpt2', '607a30d783dfa663caf39e06633721c8d4cfcd7e'),
    ('SmolLM2-135M base', 'HuggingFaceTB/SmolLM2-135M', '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'),
    ('Qwen2.5-0.5B-Instruct', 'Qwen/Qwen2.5-0.5B-Instruct', '7ae557604adf67be50417f59c2c2f167def9a775'),
]
pretrained = []
for label, repo, revision in models:
    tokenizer = AutoTokenizer.from_pretrained(repo, revision=revision)
    langs = {}
    for lang, texts in test.items():
        counts = []
        mismatch_count, first_mismatch = 0, None
        nfc_matches, decoded_bytes, special_occurrences = 0, 0, 0
        for text in texts:
            ids = tokenizer(text, add_special_tokens=False)['input_ids']
            decoded = tokenizer.decode(ids, clean_up_tokenization_spaces=False)
            decoded_bytes += len(decoded.encode('utf-8'))
            special_occurrences += sum(i in tokenizer.all_special_ids for i in ids)
            if decoded != text:
                mismatch_count += 1
                nfc_matches += int(decoded == unicodedata.normalize('NFC', text))
                if first_mismatch is None:
                    first_mismatch = {'original': text, 'decodificado': decoded,
                                      'bytes_original': len(text.encode('utf-8')),
                                      'bytes_decodificado': len(decoded.encode('utf-8'))}
            counts.append(len(ids))
        langs[lang] = summarize(counts, texts)
        langs[lang]['roundtrip_mismatches'] = mismatch_count
        langs[lang]['roundtrip_mismatches_equal_nfc'] = nfc_matches
        langs[lang]['decoded_bytes_total'] = decoded_bytes
        langs[lang]['special_token_occurrences'] = special_occurrences
        langs[lang]['first_roundtrip_mismatch'] = first_mismatch
    english = langs['eng_Latn']['mean_tokens']
    for stats in langs.values():
        stats['tokens_per_sentence_vs_english'] = stats['mean_tokens'] / english
    normalizer = json.loads(tokenizer.backend_tokenizer.to_str()).get('normalizer')
    pretrained.append({'label': label, 'repo': repo, 'revision': revision,
                       'vocab_base': tokenizer.vocab_size, 'vocab_total': len(tokenizer),
                       'normalizer': normalizer, 'by_language': langs})
    print(label, {LANGS[k]: round(v['mean_tokens'], 3) for k, v in langs.items()},
          'round-trip distinto', {LANGS[k]: v['roundtrip_mismatches'] for k, v in langs.items()}, flush=True)
    for lang, values in langs.items():
        print(LANGS[lang], '| bytes entrada/decodificados', values['bytes_total'], values['decoded_bytes_total'],
              '| diferencias / iguales a NFC', values['roundtrip_mismatches'],
              values['roundtrip_mismatches_equal_nfc'],
              '| tokens especiales', values['special_token_occurrences'], flush=True)

report = {'source': SOURCE, 'source_card': 'https://github.com/facebookresearch/flores/blob/main/flores200/README.md',
          'license': 'CC BY-SA 4.0', 'sha256': digest, 'split_train': 'dev', 'split_test': 'devtest',
          'selection': 'primeras líneas por índice de cada idioma, sin normalización Unicode',
          'train_per_language': len(train['eng_Latn']), 'test_per_language': len(test['eng_Latn']),
          'language_names': LANGS, 'python': platform.python_version(),
          'versions': {'transformers': version('transformers'), 'tokenizers': version('tokenizers')},
          'word_definition': 'fragmento no vacío separado por espacios; no es segmentación lingüística china',
          'word_unrepresentable_definition': 'byte/BPE 0; carácter si incluye código ausente de dev; palabra si el fragmento está ausente de dev',
          'vocabulary_scope': 'vocabulario conjunto de dev de los cinco idiomas; +1 UNK para caracteres y palabras',
          'warning': 'El tokenizador de palabras descarta separadores; longitud y OOV son controles ilustrativos, no un codec reversible.',
          'units': units, 'pretrained': pretrained}
with (OUT / 'fertility-report.json').open('w', encoding='utf-8') as f:
    json.dump(report, f, ensure_ascii=False, indent=2)
print('Informe:', OUT / 'fertility-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

NumericFour scalars
How many bytes does ‘añ€😀’ occupy in UTF-8, without quotation marks?
CodeStrict UTF-8
Implement utf8_encode(codepoints), which receives a sequence of integers and returns bytes, and utf8_decode(data), which receives bytes and returns a list of code points. Accept the empty string and all Unicode scalars, including noncharacters; reject surrogates, out-of-range values, and malformed UTF-8 with ValueError. Do not modify the inputs. Use bit operations without encode or decode to implement the functions.
def utf8_encode(codepoints):
  pass

def utf8_decode(data):
  pass
Shift+Enter to run
NumericTwo large matrices
A model with d=2048, 16 blocks of approximately 12d² parameters each, and vocabulary V=128,000 has untied embedding and output head weights. Ignoring biases and norms, what fraction of parameters is in those two matrices? Enter a number between 0 and 1.
QuizNormalizing a formula
What does NFKC produce for ‘①’, ‘fi’, and ‘x²’ respectively, and what risk does it pose?
ProofSelf-synchronization
Prove: Justify that valid UTF-8 scalar encodings are prefix-free and bound resynchronization in a valid string.
0
Consider only valid UTF-8 of one to four bytes; continuations have the form 10xxxxxx.

Step 1 of 4. How does the first byte determine the length of a valid encoding?

Key idea

A grapheme, code point, byte, and token are distinct units. Tokenizer choice changes coverage, length, and cost; normalization and protocol are part of the result.