Module contents
Lesson 3 of 26Core 120 min

Byte Pair Encoding from scratch

Build a complete byte-level BPE tokenizer, including pretokenization, merge training, rank-based encoding and decoding, and special-token handling. Accelerate training and compare its output with existing tokenizers.

After this lesson you can

  • Implement byte-level BPE training and explain how nonoverlapping replacements reduce corpus length.
  • Implement rank-based merge encoding and decoding, and demonstrate byte-level reversibility.
  • Design and justify a pretokenization regular expression for contractions, letters, numbers, punctuation, and spaces.
  • Handle special tokens through an explicit boundary between ordinary input and control tokens.
  • Accelerate training with incremental pair counts and a priority queue, measuring empirical complexity.
  • Verify the encoder against exact tiktoken encodings using a loaded vocabulary.

Before you start

A dictionary built through merges

A byte tokenizer can represent any valid UTF-8 string, but often produces long sequences. If de occurs frequently, we can introduce one unit representing its two bytes and replace its occurrences. Repeating this creates frequent units without an entry for every possible word.

The tokenizer fixes the representation received by the model. Its rules are learned or chosen before network training and are not updated by that network’s gradient in the scheme studied here. Changing an existing model’s tokenizer changes the meaning of its IDs and requires adapting its embeddings. Replacing a file alone is insufficient.

Gage described byte pair encoding as compression by pair substitution. Sennrich and colleagues adapted subword merges to neural translation. A shorter ID sequence is not itself a compressed file. Measuring actual bits also requires counting the dictionary representation, IDs, and any entropy coding.

Training: counting and merging

In BPE training, start with base symbols, count adjacent pairs within permitted fragments, choose one under the stated criterion, create a unit, and replace nonoverlapping occurrences. Repeat until reaching the vocabulary budget or running out of pairs. Save the merge order and a deterministic tie-breaking rule. Repeated fragments must weight counts by their frequencies.

In aaa, the pair aa appears at positions 1-2 and 2-3: two adjacent windows but only one simultaneous nonoverlapping replacement. Length goes from three to two, not one. In general, if mm disjoint occurrences are replaced, each turns two symbols into one and total length decreases by exactly mm.

Choosing the most frequent pair is greedy with respect to the counting criterion. If the count includes overlapping windows, frequency need not equal the number of possible replacements, so it guarantees neither the greatest immediate reduction nor a globally optimal vocabulary. The formal analysis by Zouhar and colleagues studies an optimization formulation and its assumptions; it does not make every practical variant optimal.

InteractiveBPE one merge at a time

Teaching pretokenization with JavaScript regex: letters, digits, spaces and punctuation remain in separate fragments. Merges do not cross fragments. Ties select the smallest ID pair; each initial byte has ID 0 to 255.

a · 61a · 61a · 61
20
a · 61a · 61a · 61b · 62d · 64a · 61a · 61a · 61b · 62a · 61c · 63

Next: a · 61 + a · 61. There are 6 adjacent positions, but are applied 3 replacements without overlap.

Current frequencies
  1. a · 61 + a · 61: 6
  2. a · 61 + b · 62: 2
  3. a · 61 + c · 63: 1
  4. b · 62 + a · 61: 1
  5. b · 62 + d · 64: 1
Completed merge tree

    Hexadecimal values show bytes even when a token contains only part of a UTF-8 character. Text accepts up to 256 UTF-16 units.

    0
    Current tokens
    15
    Next pair frequency
    6
    Non-overlapping replacements
    3
    Step through merges and compare counts, replacements, and length.

    Bytes, fragments, and ranks

    In byte-level BPE, all 256 possible values are base units. Each merge preserves the concatenation of its children’s bytes. If all rules are saved, any valid UTF-8 text can be represented by a sequence of those IDs. A token may contain only part of a multibyte character. To reconstruct a string, first concatenate every token’s bytes and decode at the end using the stated error policy.

    The original GPT-2 encoder uses a reversible mapping between bytes and visible characters to store its vocabulary. This is an auxiliary representation of bytes, not a claim that every token is a complete Unicode character.

    Pretokenization splits text before BPE. A regular expression can distinguish letters, contractions, numbers, punctuation, and spaces; merges cannot cross the boundaries it creates. This avoids requiring a separate entry for each word and punctuation combination. The exact patterns matter. For example, cl100k_base groups digits into fragments of at most three in its published definition. Expressions and options depend on the regex engine, so verify an adaptation instead of assuming equivalence.

    In cl100k_base, the token for dog has ID 18964, while dog uses ID 5679: the leading space is part of the piece. Strings dog., dog!, and dog? share ID 18964 for dog and are distinguished by the subsequent punctuation token in this measurement. These are properties of this vocabulary and pattern, not a rule for all tokenizers.

    InteractivePretokenization lab

    ␠ denotes a space, ↵ a newline and ⇥ a tab. The count uses a byte BPE trained here on 28 fixed fragments: " Hello", " world", " the", " cat", " dog", " cat", " dog", " can", " can", " can", "'t", "123", "123", "456", " code", " code", " texto", " texto", " de", " de", " de", "ción", "ción", "ción", "ción", "!", ".", "\n". It breaks ties by IDs and never merges across fragments. This is a teaching model, not the GPT-2 or cl100k vocabulary.

    Initial expressions are JavaScript adaptations of patterns published in tiktoken. cl100k uses local case groups and possessive quantifiers substituted here; JavaScript and the original engine do not necessarily agree on Unicode spaces, backtracking or edge cases. The space option also retains separators; edited patterns may leave portions unmatched.

    Initial pattern
    Fragments
    0
    Teaching BPE tokens
    0
    Learned merges
    37
    Edit the pattern and compare fragments under the specified engine.

    During BPE encoding, the vocabulary is already fixed. Within each fragment, apply the available pair with the lowest merge rank and repeat until none remains. Corpus frequencies are not counted again, and the longest token matching the prefix is not necessarily chosen.

    Consider ordered merges a+b→ab, b+c→bc, bc+d→bcd and input abcd. By rank, ab appears first and the result is [ab,c,d]. The longest match from each position can instead choose [a,bcd]. Both segmentations use vocabulary pieces, but only the first respects those merges. Order, pretokenization, and tie-breaking are part of the tokenizer.

    InteractiveEncoding by rank

    A shared explicit vocabulary shows why always choosing the longest token differs from applying merges by rank.

    Ranked BPE
    abc
    Next: rank 0, b + c → bc
    Longest match
    abc
    At each position choose the longest available token.

    Fixed merges: rank 0, b+c→bc; rank 1, a+b→ab; rank 2, ab+c→abc. Vocabulary also includes a, b and c. On “abc”, BPE ends in [a, bc], although the vocabulary contains abc; greedy longest match chooses [abc]. The vocabulary and ranks define this explicit example and do not come from a published model.

    0
    Final BPE tokens
    2
    Longest-match tokens
    1
    Compare ranked merges with longest-match encoding.

    Control tokens require an explicit boundary

    Special tokens can represent end of text or chat structure. Their ID has meaning for the model and template. A literal string with the same appearance should become control only if the sequence-building code explicitly permits it. A policy can reject reserved markers in untrusted text or encode them as ordinary text; legitimate instructions and delimiters are added through a controlled channel.

    InteractiveText and special tokens
    Text · 31 UTF-8 bytes
    Mensaje: hola <|endoftext|> fin

    Ordinary text is represented here as bytes to show the boundary; these bytes are not production BPE IDs. Allow means recognizing all registered markers in this demonstration. An implementation can allow only an explicit subset.

    Markers and IDs come from the tiktoken registries. For example, <|im_start|> does not appear in these two registries and is treated as ordinary text; other templates may define different controls. Rejection is the API pre-check; text mode is ordinary handling without recognizing special markers.

    In an application, the trusted template must insert controls separately from received content; treating content as ordinary text or rejecting markers prevents their recognition as control IDs. This alone does not prevent the model from following instructions written in the content.

    Special-token registry
    Text handling
    Registered markers found
    1
    Special IDs emitted
    0
    Ordinary text bytes
    31
    Compare policies on a harmless marker and observe the resulting IDs.

    This separation prevents text from accidentally becoming a special ID under that policy. It does not by itself solve every instruction-injection problem: a model may also follow instructions written in ordinary language. Defense includes delimiting sources, restricting tools, validating actions, and evaluating system behavior.

    Avoiding a full recount at each step

    The direct implementation revisits every fragment to count pairs after each merge. It is easy to check, but its cost grows with corpus size and merge count. Incremental counting maintains frequencies and an index of fragments containing each pair; merging updates only affected fragments. A priority queue proposes the most frequent pair. Since stale entries can remain in the heap, verify that an extracted priority is still current before using it.

    The index consumes memory and ties must be resolved exactly as in the reference. A measurement on repetitive corpora favors fragment reuse and does not establish the same improvement for every collection. Compare both implementations on the same inputs and check that they choose exactly the same merges. The labs measure total training time. As an extension, instrument memory and index construction separately, which are not measured here.

    Lab: a complete tokenizer

    This pretokenizer separates spaces, letters, digits, underscores, and other symbols using Python’s re. It is a teaching recipe, not the exact GPT-2 or cl100k pattern. Merges never cross these boundaries. Each initial symbol is a UTF-8 byte. Ties choose the smallest ID pair. Frequency counts overlapping adjacent positions, while each replacement is simultaneous and nonoverlapping. Here different IDs can decode to the same byte sequence; identity is preserved by ID and rank, without claiming that this is tiktoken’s format.

    The two-MiB corpus is generated by repeating one Spanish sentence and compressed into unique fragments with weights before training. The timing ratio depends on that repetition, machine, and load; it is not a general benchmark. Both versions must select identical merges and return the same vocabulary. To recover Unicode, concatenate every token’s bytes before decoding.

    [ ]Byte BPE and incremental countingBrowser
    """BPE didáctico por bytes, con pretokenización explícita y desempate estable."""
    from collections import Counter, defaultdict
    import heapq
    import random
    import re
    import time
    
    
    PATTERN = r'\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')
    
    
    def encode_with_special(text, merges, vocab, special, policy='ordinary'):
        if policy not in ('ordinary', 'reject'):
            raise ValueError('Política desconocida')
        if any(not s for s in special) or len(set(special.values())) != len(special):
            raise ValueError('Marcadores vacíos o IDs especiales repetidos')
        if set(special.values()) & set(vocab):
            raise ValueError('Un ID especial colisiona con el vocabulario ordinario')
        if policy == 'reject' and any(marker in text for marker in special):
            raise ValueError('El texto contiene un marcador reservado')
        return encode(text, merges)
    
    
    def control_token(marker, special, vocab):
        if marker not in special or not marker or special[marker] in vocab:
            raise ValueError('Marcador no autorizado o ID en conflicto')
        return special[marker]
    
    
    assert pairs([97, 97, 97])[(97, 97)] == 2
    assert merge([97, 97, 97], (97, 97), 256) == [256, 97]
    sample = 'aaabdaaabac'
    vocab, merges, history = train(sample, 259)
    assert [entry[1:] for entry in history] == [(4, 2), (2, 2), (2, 2)]
    assert len(encode(sample, merges)) == 5
    marker = {'<|endoftext|>': 10000}
    literal = 'hola <|endoftext|>'
    ordinary = encode_with_special(literal, merges, vocab, marker)
    assert 10000 not in ordinary and decode(ordinary, vocab) == literal
    assert ordinary + [control_token('<|endoftext|>', marker, vocab)] == ordinary + [10000]
    try:
        encode_with_special(literal, merges, vocab, marker, 'reject')
    except ValueError:
        pass
    else:
        raise AssertionError('El marcador reservado debe rechazarse')
    print('Marcador literal reversible; token de control insertado explícitamente')
    
    # El corpus repetido pesa 2 MiB, pero los fragmentos únicos se cuentan con pesos.
    sentence = 'El aprendizaje de máquinas y la predicción del lenguaje cambian la ciencia. '
    text = (sentence * (2 * 1024 * 1024 // len(sentence.encode('utf-8')) + 1))
    print('Corpus generado:', len(text.encode('utf-8')), 'bytes; fragmentos únicos:', len(set(pretokenize(text))))
    start = time.perf_counter()
    base_vocab, base_merges, base_history = train(text, 288, incremental=False)
    base_time = time.perf_counter() - start
    start = time.perf_counter()
    fast_vocab, fast_merges, fast_history = train(text, 288, incremental=True)
    fast_time = time.perf_counter() - start
    assert base_merges == fast_merges and base_history == fast_history and base_vocab == fast_vocab
    print('Fusiones idénticas:', len(base_merges), '| primeros pares frecuencia/reemplazos:', base_history[:3])
    print('Tiempo relativo incremental/recuento completo:', round(fast_time / base_time, 3))
    randomizer = random.Random(2003)
    for _ in range(300):
        points = []
        for _ in range(randomizer.randrange(20)):
            point = randomizer.randrange(0x110000)
            while 0xD800 <= point <= 0xDFFF:
                point = randomizer.randrange(0x110000)
            points.append(chr(point))
        source = ''.join(points)
        assert decode(encode(source, base_merges), base_vocab) == source
    print('300 textos Unicode reproducibles recuperados exactamente; semilla 2003')

    Local lab: comparing with existing tokenizers

    The first experiment loads from tiktoken the pattern and rank table for cl100k_base. The custom encoder splits text with the same pattern, starts from its bytes, and repeatedly merges the lowest-rank pair. It then compares all its IDs with encode_ordinary. It decodes by concatenating each token’s bytes and checks equality with the original UTF-8 bytes. This check treats markers written by a person as ordinary text, not instructions or control tokens.

    The test uses aligned devtest sentences from FLORES-200, CC BY-SA 4.0, in English, Spanish, simplified Chinese, Modern Standard Arabic, and Hindi. The short version checks 256 sentences per language. In our run the IDs matched on 1,280 sentences and 6 additional cases, with 84,793 tokens and 244,381 recovered bytes. It separately shows fragments and IDs for dog, dog, dog., dog!, dog?, and 1234567 so you can see punctuation separated and numbers split into groups of at most three digits.

    The second experiment trains this lesson’s teaching BPE in two ways on the same Spanish dev sentences: full recount and incremental updates with a fragment index and heap. It checks exact equality of vocabulary, merges, and history. It then trains Hugging Face tokenizers on the same corpus and fragments from the teaching pretokenizer. HF can resolve ties or training details differently, so compare compression and cost without assuming equal IDs or merges. In the short run the two custom implementations agreed on 128 merges. On 256 held-out Spanish sentences both tokenizers produced 26,466 tokens, equal counts that do not prove equal sequences. Printed timing ratios depend on machine, load, and sample size; they are not speed guarantees.

    Install tiktoken, regex, and tokenizers. The official FLORES-200 file is about 26 MB and downloads to ORYON_OUTPUT_DIR unless an existing path is supplied through ORYON_FLORES_ARCHIVE. The program checks its SHA-256 and saves the report, versions, and rank-table hash. ORYON_QUICK=1 uses 256 sentences per language for validation, 64 Spanish training sentences, and vocabulary 384. Normal mode uses all 1,012 held-out sentences per language, 997 training sentences, and vocabulary 512. You can adjust ORYON_LIMIT, ORYON_TRAIN_LIMIT, and ORYON_BPE_VOCAB. The table and pattern are read from internal tiktoken attributes; the report pins version and hash to detect changes.

    [ ]Real BPE validation against cl100k and Hugging FaceLocal GPU
    """BPE didáctico por bytes, con pretokenización explícita y desempate estable."""
    from collections import Counter, defaultdict
    import heapq
    import random
    import re
    import time
    
    
    PATTERN = r'\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')
    
    
    # Segunda parte: validación con rangos y expresión regular reales de cl100k_base.
    import hashlib
    import json
    import os
    import platform
    import tarfile
    import urllib.request
    from importlib.metadata import version
    from pathlib import Path
    import regex
    import tiktoken
    from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders
    
    URL = 'https://dl.fbaipublicfiles.com/nllb/flores200_dataset.tar.gz'
    EXPECTED_SHA = 'b8b0b76783024b85797e5cc75064eb83fc5288b41e9654dabc7be6ae944011f6'
    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', 256 if QUICK else 1012))
    TRAIN_LIMIT = int(os.environ.get('ORYON_TRAIN_LIMIT', 64 if QUICK else 997))
    VOCAB_SIZE = int(os.environ.get('ORYON_BPE_VOCAB', 384 if QUICK else 512))
    OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', './bpe-validation-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(URL, ARCHIVE)
    with ARCHIVE.open('rb') as f:
        sha = hashlib.file_digest(f, 'sha256').hexdigest()
    assert sha == EXPECTED_SHA, 'El hash del corpus no coincide con la versión declarada'
    assert LIMIT > 0 and TRAIN_LIMIT > 0 and VOCAB_SIZE >= 256
    with tarfile.open(ARCHIVE, 'r:gz') as archive:
        data = {lang: archive.extractfile(f'./flores200_dataset/devtest/{lang}.devtest')
                .read().decode('utf-8').splitlines()[:LIMIT] for lang in LANGS}
        train_rows = archive.extractfile('./flores200_dataset/dev/spa_Latn.dev').read().decode('utf-8').splitlines()[:TRAIN_LIMIT]
    assert all(len(data[lang]) == min(LIMIT, 1012) for lang in LANGS)
    assert len(train_rows) == min(TRAIN_LIMIT, 997)
    
    reference = tiktoken.get_encoding('cl100k_base')
    # Atributos internos: se fijan la versión y el hash de toda la tabla usada.
    ranks = reference._mergeable_ranks
    pattern = reference._pat_str
    splitter = regex.compile(pattern)
    rank_hash = hashlib.sha256()
    for piece, rank in sorted(ranks.items(), key=lambda item: item[1]):
        rank_hash.update(rank.to_bytes(4, 'big'))
        rank_hash.update(len(piece).to_bytes(4, 'big'))
        rank_hash.update(piece)
    assert all(bytes([i]) in ranks for i in range(256))
    
    
    def encode_cl100k(text):
        """BPE por rango mínimo y posición izquierda; especiales son texto ordinario."""
        output = []
        pieces = [match.group() for match in splitter.finditer(text)]
        if ''.join(pieces) != text:
            raise ValueError('El patrón no cubre la entrada')
        for piece in pieces:
            symbols = [bytes([byte]) for byte in piece.encode('utf-8')]
            while len(symbols) > 1:
                candidates = [(ranks[symbols[i] + symbols[i + 1]], i)
                              for i in range(len(symbols) - 1)
                              if symbols[i] + symbols[i + 1] in ranks]
                if not candidates:
                    break
                _, i = min(candidates)
                symbols[i:i + 2] = [symbols[i] + symbols[i + 1]]
            output.extend(ranks[symbol] for symbol in symbols)
        return output
    
    
    edge_cases = ['', 'aaa', 'dog. dog! dog?', "I'm 1234567\n café é e\u0301 😀",
                  'texto literal <|endoftext|> y <|fim_prefix|>', ' ' * 20]
    edge_checks = 0
    for text in edge_cases:
        own = encode_cl100k(text)
        assert own == reference.encode_ordinary(text)
        assert b''.join(reference.decode_single_token_bytes(i) for i in own) == text.encode('utf-8')
        edge_checks += 1
    examples = []
    print('Patrón cl100k:', pattern, flush=True)
    for text in ('dog', ' dog', 'dog.', 'dog!', 'dog?', '1234567'):
        fragments = [match.group() for match in splitter.finditer(text)]
        ids = encode_cl100k(text)
        assert ids == reference.encode_ordinary(text)
        examples.append({'text': text, 'fragments': fragments, 'token_ids': ids})
        print('cl100k', repr(text), '| fragmentos', fragments, '| IDs', ids, flush=True)
    document_count = token_count = byte_count = 0
    for lang, rows in data.items():
        for text in rows:
            own = encode_cl100k(text)
            expected = reference.encode_ordinary(text)
            if own != expected:
                raise AssertionError(f'Diferencia en {lang}, entrada {document_count}')
            recovered = b''.join(reference.decode_single_token_bytes(i) for i in own)
            assert recovered == text.encode('utf-8')
            document_count += 1
            token_count += len(own)
            byte_count += len(recovered)
    print('cl100k: documentos idénticos', document_count, 'casos adicionales', edge_checks,
          'tokens', token_count, 'bytes', byte_count, flush=True)
    
    # Las dos variantes propias comparten fragmentos, conteos solapados y desempate.
    train_text = '\n'.join(train_rows)
    started = time.perf_counter()
    vocab_slow, merges_slow, hist_slow = train(train_text, VOCAB_SIZE, incremental=False)
    slow_seconds = time.perf_counter() - started
    started = time.perf_counter()
    vocab_fast, merges_fast, hist_fast = train(train_text, VOCAB_SIZE, incremental=True)
    fast_seconds = time.perf_counter() - started
    assert vocab_slow == vocab_fast and merges_slow == merges_fast and hist_slow == hist_fast
    print('BPE propio: fusiones idénticas', len(merges_fast),
          'cociente tiempo incremental/completo', round(fast_seconds / slow_seconds, 3), flush=True)
    
    # HF recibe exactamente los mismos fragmentos del pretokenizador didáctico.
    hf = Tokenizer(models.BPE())
    hf.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=False)
    hf.decoder = decoders.ByteLevel()
    trainer = trainers.BpeTrainer(vocab_size=VOCAB_SIZE, initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
                                  min_frequency=1, show_progress=False)
    started = time.perf_counter()
    hf.train_from_iterator(pretokenize(train_text), trainer=trainer)
    hf_seconds = time.perf_counter() - started
    test_spanish = data['spa_Latn']
    own_lengths, hf_lengths, bytes_per_line = [], [], []
    for text in test_spanish:
        own_ids = encode(text, merges_fast)
        assert decode(own_ids, vocab_fast) == text
        fragments = pretokenize(text)
        hf_ids = [i for fragment in fragments for i in hf.encode(fragment, add_special_tokens=False).ids]
        assert hf.decode(hf_ids, skip_special_tokens=False) == text
        own_lengths.append(len(own_ids))
        hf_lengths.append(len(hf_ids))
        bytes_per_line.append(len(text.encode('utf-8')))
    assert sum(own_lengths) and sum(hf_lengths)
    print('Retenido español: frases', len(test_spanish), '| bytes', sum(bytes_per_line),
          '| tokens propio/HF', sum(own_lengths), sum(hf_lengths), flush=True)
    print('Vocabulario propio/HF:', len(vocab_fast), hf.get_vocab_size(),
          '| tiempo relativo HF/recuento completo:', round(hf_seconds / slow_seconds, 3), flush=True)
    
    report = {'source': URL, 'dataset_sha256': sha, 'license': 'CC BY-SA 4.0',
              'evaluation_split': 'devtest', 'languages': LANGS,
              'selection': 'primeras líneas, alineadas por índice',
              'documents_each_language': {k: len(v) for k, v in data.items()},
              'training_split': 'dev, solo español', 'training_documents': len(train_rows),
              'training_bytes': len(train_text.encode('utf-8')), 'quick': QUICK,
              'python': platform.python_version(),
              'versions': {'tiktoken': version('tiktoken'), 'regex': version('regex'), 'tokenizers': version('tokenizers')},
              'cl100k': {'documents_checked': document_count, 'extra_cases': edge_checks,
                         'tokens_checked': token_count, 'bytes_checked': byte_count,
                         'mergeable_ranks_sha256': rank_hash.hexdigest(), 'pattern': pattern,
                         'examples': examples, 'special_policy': 'texto ordinario, encode_ordinary'},
              'training': {'requested_vocab': VOCAB_SIZE, 'own_vocab': len(vocab_fast),
                           'hf_vocab': hf.get_vocab_size(), 'merges': len(merges_fast),
                           'own_algorithms_equal': True, 'incremental_over_naive': fast_seconds / slow_seconds,
                           'hf_over_naive': hf_seconds / slow_seconds,
                           'implementation_note': 'HF y propia tienen pretokenización idéntica, pero pueden diferir en desempates y reglas de entrenamiento',
                           'heldout_spanish_documents': len(test_spanish), 'heldout_bytes': sum(bytes_per_line),
                           'own_tokens': sum(own_lengths), 'hf_tokens': sum(hf_lengths),
                           'own_bytes_per_token': sum(bytes_per_line) / sum(own_lengths),
                           'hf_bytes_per_token': sum(bytes_per_line) / sum(hf_lengths)}}
    with (OUT / 'validation-report.json').open('w', encoding='utf-8') as f:
        json.dump(report, f, ensure_ascii=False, indent=2)
    print('Informe:', OUT / 'validation-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

    CodeCount overlapping windows, replace without overlap
    Implement get_pair_counts(ids), returning a frequency dictionary of adjacent pairs counting overlapping windows, and merge(ids, pair, new_id), returning a new list replacing nonoverlapping occurrences from left to right. Do not modify the input.
    def get_pair_counts(ids):
      pass
    
    def merge(ids, pair, new_id):
      pass
    
    Shift+Enter to run
    ProofHow much a merge reduces
    Prove: Prove a merge's length reduction and state in what sense its choice is greedy.
    0
    A pair is replaced by a new symbol at m disjoint positions in a fragmented corpus.

    Step 1 of 3. What happens to each selected occurrence?

    NumericThree BPE steps
    For aaabdaaabac, count adjacent windows including overlaps, choose the most frequent pair with lexicographic ID tie-breaking, and replace left to right without overlap. How many tokens remain after three merges?
    QuizPretokenization boundaries
    Why can separating punctuation before learning or applying merges help for ‘dog.’, ‘dog!’, and ‘dog?’?
    CodeApply ranks to each fragment
    Implement encode_ordinary(text, merges, pattern). pattern is a Python expression without capturing groups whose nonempty matches cover exactly text in order; reject with ValueError any pattern or text that fails that coverage. merges is an ordered list of (left_id,right_id,new_id) tuples, with base IDs 0 to 255 for bytes and distinct new IDs. For each fragment start from its UTF-8 bytes and repeatedly merge the present pair with lowest index in merges, replacing nonoverlapping occurrences left to right. Return the ID list; do not recognize special markers.
    import re
    
    def encode_ordinary(text, merges, pattern):
      pass
    
    Shift+Enter to run
    Key idea

    BPE learns a merge order over fragments; encoding applies ranks and decoding concatenates bytes. A reproducible result includes pretokenization, tie-breaking, and the special-token policy.