Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / ml / gemma4_tokenizer.py

gemma4_tokenizer.py133 lines · 5.3 KiBRaw
1#!/usr/bin/env python3
2"""gemma4_tokenizer.py - Gemma 4's `tokenizer.json` as the `SPM1` table `post::sentencepiece` reads.
3
4# It is BPE, and that is the whole reason this is short
5
6Gemma 4's tokenizer is a **BPE** model with 262144 pieces and 514906 merges, which is exactly the
7algorithm `post::sentencepiece` already implements: greedy pairwise merging, highest score first,
8leftmost on a tie. There is no Viterbi and no unigram lattice. So this script is a format
9translation and not a new tokenizer.
10
11# Scores are merge ranks, inverted
12
13`SPM1` stores one score per *piece* and the Rust merges the pair with the highest score.
14`tokenizer.json` stores an ordered `merges` list where **earlier means merges first**. So a
15piece's score is `len(merges) - rank`, which turns "first in the list" into "largest number".
16
17A piece produced by no merge - the base characters and the 256 byte pieces - keeps a score of 0.
18It never participates as a merge *result*, so its score is never read by the merge loop; only its
19id is, at the end.
20
21# Byte fallback
22
23The vocabulary holds all 256 `<0xNN>` pieces and `byte_fallback` is true, so any byte round-trips
24and no text is ever lost to `<unk>`. `Table::parse_with` detects them by name; this script only
25has to check they are all present, because a partial set would be worse than none.
26
27# The specials are not fairseq's
28
29`<pad>` 0, `<eos>` 1, `<bos>` 2, `<unk>` 3 - note `eos` **before** `bos`, the reverse of fairseq.
30`post::sentencepiece::GEMMA` states the same, and `Table::parse_with` asserts it.
31
32Run:
33
34 python3 scripts/ml/gemma4_tokenizer.py \\
35 --tokenizer tokenizer.json -o assets/gemma4_tokenizer.spm1
36"""
37
38from __future__ import annotations
39
40import argparse
41import json
42import struct
43
44MAGIC = b"SPM1"
45
46# What `config.json`'s `vocab_size` says, and what `nets::gemma4::VOCAB` hardcodes.
47VOCAB_SIZE = 262_144
48
49# `post::sentencepiece::GEMMA`'s `names`, in id order from 0. Asserted rather than assumed: a
50# table whose specials are elsewhere decodes every sequence off by one and looks almost right.
51SPECIALS = ["<pad>", "<eos>", "<bos>", "<unk>"]
52
53
54def build(tokenizer_path):
55 """`[(piece, score)]` in id order, from a HuggingFace `tokenizer.json`."""
56 with open(tokenizer_path, encoding="utf-8") as f:
57 spec = json.load(f)
58 model = spec["model"]
59 if model.get("type") != "BPE":
60 raise SystemExit(
61 f"the tokenizer is {model.get('type')}, not BPE. `post::sentencepiece` merges "
62 "pairwise by rank; a unigram model needs a Viterbi decode this does not have."
63 )
64 if not model.get("byte_fallback"):
65 raise SystemExit("byte_fallback is off, so some bytes would have no spelling at all")
66
67 vocab = model["vocab"]
68 if len(vocab) != VOCAB_SIZE:
69 raise SystemExit(f"{len(vocab)} pieces against a vocab_size of {VOCAB_SIZE}")
70
71 merges = model["merges"]
72 # `merges` is either ["a b", ...] or [["a", "b"], ...] depending on the version that wrote it.
73 ranks = {}
74 for rank, merge in enumerate(merges):
75 pair = merge.split(" ", 1) if isinstance(merge, str) else list(merge)
76 if len(pair) != 2:
77 raise SystemExit(f"merge {rank} is {merge!r}, which is not a pair")
78 # Earlier in the list merges first, so it must score higher.
79 ranks.setdefault(pair[0] + pair[1], len(merges) - rank)
80
81 table = [None] * VOCAB_SIZE
82 for piece, index in vocab.items():
83 if not 0 <= index < VOCAB_SIZE:
84 raise SystemExit(f"{piece!r} has id {index}, outside the vocabulary")
85 if table[index] is not None:
86 raise SystemExit(f"id {index} is claimed by {table[index][0]!r} and {piece!r}")
87 table[index] = (piece, ranks.get(piece, 0))
88 missing = [i for i, entry in enumerate(table) if entry is None]
89 if missing:
90 raise SystemExit(f"{len(missing)} ids have no piece, the first being {missing[0]}")
91
92 for index, name in enumerate(SPECIALS):
93 if table[index][0] != name:
94 raise SystemExit(f"id {index} is {table[index][0]!r}, not {name}")
95
96 byte_pieces = [f"<0x{b:02X}>" for b in range(256)]
97 held = {piece for piece, _ in table}
98 absent = [p for p in byte_pieces if p not in held]
99 if absent:
100 raise SystemExit(f"{len(absent)} byte pieces are missing, the first being {absent[0]}")
101
102 return table, len(ranks)
103
104
105def pack(vocab):
106 """The `SPM1` blob for `[(piece, score)]` in id order. Identical to `nllb_tokenizer.py`'s."""
107 out = bytearray(MAGIC)
108 out += struct.pack("<I", len(vocab))
109 for piece, score in vocab:
110 encoded = piece.encode("utf-8")
111 if len(encoded) > 0xFFFF:
112 raise SystemExit(f"a piece of {len(encoded)} bytes does not fit a u16 length")
113 out += struct.pack("<iH", int(score), len(encoded))
114 out += encoded
115 return bytes(out)
116
117
118def main():
119 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
120 parser.add_argument("--tokenizer", required=True, help="tokenizer.json")
121 parser.add_argument("-o", "--out", required=True)
122 args = parser.parse_args()
123
124 table, merged = build(args.tokenizer)
125 blob = pack(table)
126 with open(args.out, "wb") as f:
127 f.write(blob)
128 print(f"{len(table)} pieces, {merged} of them merge results")
129 print(f"wrote {args.out} {len(blob) / 1e6:.2f} MB")
130
131
132if __name__ == "__main__":
133 raise SystemExit(main())