Skip to content
BIASED
Back to topic

Optional

Replay the BPE merge trace

Inspect the full fictional inputs, rerun the standard-library calculations, and check the stated invariants. Optional desktop practice.

Version
v2
Minutes
~15
Evidence
Self-check in the notebook

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

Tokenization / Токенизация

Optional practice. The lesson and its phone questions are complete without running code. / Необязательная практика: урок и задания на телефоне самостоятельны.

All inputs and calculations were authored for the Fedor Pakhurov project with Codex assistance. The example is fictional and contains no external corpus, model, or copied third-party implementation. Selected first-party functions are retained from the published reviewed fixture. This notebook adds packaging and explicit self-checks; it does not claim operational quality.

Все входы вымышлены; расчёты созданы для проекта Фёдора Пахурова с помощью Codex. Внешних корпусов, моделей и сторонних реализаций здесь нет. Функции взяты из указанной опубликованной проверенной версии; добавлены оформление и самопроверки.

Saved outputs use Python 3.9.7; standard library only, no network or file writes. Floating last digits and Unicode database values can differ across runtimes. / Сохранённый запуск: Python 3.9.7, только стандартная библиотека, без сети и записи файлов. Последние разряды и версия Unicode могут зависеть от среды.

import json
import math
import re
import unicodedata
from collections import Counter
from fractions import Fraction
 
def replace_pair(sequence, pair):
    result = []
    position = 0
    while position < len(sequence):
        if tuple(sequence[position:position + 2]) == pair:
            result.append("".join(pair))
            position += 2
        else:
            result.append(sequence[position])
            position += 1
    return result
 
def train_bpe(frequencies, steps):
    if not frequencies or any(not isinstance(word, str) or not word or isinstance(count, bool)
                              or not isinstance(count, int) or count <= 0
                              for word, count in frequencies.items()):
        raise ValueError("Expected nonempty words with positive integer counts")
    sequences = {word: list(word) for word in frequencies}
    merges, trace = [], []
    for _ in range(steps):
        counts = Counter()
        for word, sequence in sequences.items():
            for pair in zip(sequence, sequence[1:]):
                counts[pair] += frequencies[word]
        if not counts:
            break
        chosen = min(counts, key=lambda pair: (-counts[pair], pair))
        before = sum(len(seq) * frequencies[word] for word, seq in sequences.items())
        sequences = {word: replace_pair(seq, chosen) for word, seq in sequences.items()}
        after = sum(len(seq) * frequencies[word] for word, seq in sequences.items())
        merges.append(chosen)
        trace.append({"pair": chosen, "adjacent_count": counts[chosen],
                      "tokens_before": before, "tokens_after": after})
        assert all("".join(seq) == word for word, seq in sequences.items())
    return merges, trace, sequences
 
def encode_bpe(word, merges, alphabet):
    if any(character not in alphabet for character in word):
        raise ValueError("Character outside this toy alphabet")
    sequence = list(word)
    for pair in merges:
        sequence = replace_pair(sequence, pair)
    assert "".join(sequence) == word
    return sequence
 
def tokenization():
    frequencies = {"lamp": 4, "lamps": 2, "clamp": 1, "camp": 2}
    merges, trace, sequences = train_bpe(frequencies, 4)
    alphabet = set("".join(frequencies))
    assert merges == [("a", "m"), ("am", "p"), ("l", "amp"), ("c", "amp")]
    assert [row["tokens_after"] for row in trace] == [30, 21, 14, 12]
    unseen = encode_bpe("clamps", merges, alphabet)
    assert unseen == ["c", "lamp", "s"]
    # The deterministic tie policy is part of the fitted tokenizer.
    assert train_bpe(dict(reversed(list(frequencies.items()))), 4) == (merges, trace, sequences)
    _, overlap, _ = train_bpe({"aaa": 1}, 1)
    assert overlap[0]["adjacent_count"] == 2 and overlap[0]["tokens_before"] - overlap[0]["tokens_after"] == 1
    try:
        encode_bpe("lampz", merges, alphabet)
    except ValueError:
        pass
    else:
        raise AssertionError("Unknown characters must not disappear")
    lengths = [2, 5, 3]
    padded = len(lengths) * max(lengths)
    real = sum(lengths)
    vocabulary = {"lamp", "cl", "##amp", "##s"}
    def wordpiece(word):
        parts, start = [], 0
        while start < len(word):
            candidates = [(end, word[start:end] if start == 0 else "##" + word[start:end])
                          for end in range(start + 1, len(word) + 1)]
            candidates = [(end, piece) for end, piece in candidates if piece in vocabulary]
            if not candidates:
                return ["[UNK]"]
            end, piece = max(candidates)
            parts.append(piece)
            start = end
        return parts
    assert wordpiece("clamps") == ["cl", "##amp", "##s"]
    assert wordpiece("lampz") == ["[UNK]"]
    return {"frequencies": frequencies, "initial_alphabet": sorted(alphabet),
            "initial_tokens": 39, "trace": trace, "final_sequences": sequences,
            "unseen_clamps": unseen, "overlapping_pair_trace": overlap,
            "wordpiece_vocabulary": sorted(vocabulary),
            "wordpiece_clamps": wordpiece("clamps"), "wordpiece_lampz": wordpiece("lampz"),
            "padding": {"lengths": lengths, "allocated_positions": padded,
                        "real_positions": real, "wasted_positions": padded - real}}
 
result = tokenization()
print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
 
assert result['unseen_clamps'] == ['c', 'lamp', 's']
assert result['trace'][-1]['tokens_after'] == 12
assert result['padding']['allocated_positions'] - result['padding']['real_positions'] == 5
print('All local checks passed; this is a constructed example, not a benchmark.')