0 or 1.0 to 255.ord() and chr() convert between a one-character string and its code point.ord("a") == 97ord("你") == 20320,16 进制就是 U+4F60。list("a".encode("utf-8")) == [97]list("你".encode("utf-8")) == [228, 189, 160]20320(十进制 Decimal)= 0x4F60(十六进制 Hexadecimal)= 0100 1111 0110 0000(二进制 Binary)。1110xxxx 10xxxxxx 10xxxxxx,二进制从后到前填进去,11100100 | 10111101 | 10100000 = 228, 189, 160 in decimal。str.encode("utf-8") turns text into bytes; bytes.decode("utf-8") reconstructs text.0–255.256, 257, …aaabcaa你😉97 97 97 98 99 97 97
228 189 160
240 159 152 137(97,97) × 3(97,97) → 256256 97 98 99 256
228 189 160
240 159 152 137Repeat with new pair counts until the vocabulary budget is filled.
def get_stats(ids):
"""Count adjacent pairs: [1, 2, 1] -> {(1, 2): 1, (2, 1): 1}."""
counts = {}
for pair in zip(ids, ids[1:]):
counts[pair] = counts.get(pair, 0) + 1
return counts
def merge(ids, pair, new_id):
"""Replace every non-overlapping `pair` with `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 # the merge consumes two old tokens
else:
out.append(ids[i])
i += 1
return out
def train(text, vocab_size):
"""Learn `(left_id, right_id) -> new_id` merge rules."""
assert vocab_size >= 256
ids = list(text.encode("utf-8"))
merges = {}
for i in range(vocab_size - 256):
stats = get_stats(ids)
if not stats:
break
pair = max(stats, key=stats.get) # training: highest frequency
new_id = 256 + i
ids = merge(ids, pair, new_id)
merges[pair] = new_id
return merges
def encode(text, merges):
"""Apply learned rules by rank: smaller ID = earlier learned = higher priority."""
ids = list(text.encode("utf-8"))
while len(ids) >= 2:
stats = get_stats(ids)
# Iterating over `stats` gives every adjacent pair currently in `ids`.
# During training, `merges` was filled in order:
# {(first_pair): 256, (second_pair): 257, ...}
# Therefore a smaller merged token ID is also an earlier learned rank,
# and earlier rules must be applied first when encoding new text.
#
# `merges.get(p, float("inf"))` gives learned pairs their rank and
# gives an unlearned pair infinity, placing it after every valid rule.
# For example, if the current pairs score as
# {(97, 97): 256, (98, 99): infinity},
# `min(..., key=...)` selects (97, 97).
# If all current pairs are unlearned, `min` still returns one of them;
# the following membership check detects that case and stops cleanly.
# Pair frequencies in `stats` are deliberately ignored here: frequency
# chooses rules during training, while learned rank chooses at encoding.
pair = min(stats, key=lambda p: merges.get(p, float("inf")))
if pair not in merges:
break
ids = merge(ids, pair, merges[pair])
return ids
def encode_explicit(text, merges):
"""Equivalent encode implementation with the rank search written out."""
ids = list(text.encode("utf-8"))
while len(ids) >= 2:
# Get every adjacent pair that exists in the current token sequence.
stats = get_stats(ids)
# Among pairs present in both `stats` and the learned merge table,
# choose the smallest ID: it was learned earliest and has top priority.
pair_to_merge = None
min_rank = float("inf")
for pair in stats:
if pair in merges:
rank = merges[pair]
if rank < min_rank:
min_rank = rank
pair_to_merge = pair
# No current adjacent pair matches a learned rule, so encoding is done.
if pair_to_merge is None:
break
ids = merge(ids, pair_to_merge, min_rank)
return ids
def build_vocab(merges):
"""Reconstruct each token ID as the byte sequence it represents."""
vocab = {idx: bytes([idx]) for idx in range(256)}
for (left, right), new_id in merges.items():
vocab[new_id] = vocab[left] + vocab[right]
return vocab
def decode(ids, merges):
"""Token IDs -> bytes -> UTF-8 text."""
vocab = build_vocab(merges)
raw = b"".join(vocab[token_id] for token_id in ids)
return raw.decode("utf-8", errors="replace")
# Tiny training example: `aa` is the first merge because it is most frequent.
merges = train("aaabdaaabac", vocab_size=259)
assert next(iter(merges)) == (ord("a"), ord("a"))
ids = encode("aaab", merges)
assert decode(ids, merges) == "aaab" # round tripSource: You could have designed state-of-the-art positional encoding.