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

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

nllb_tokenizer.py255 lines · 10.5 KiBRaw
1#!/usr/bin/env python3
2"""NLLB-200's SentencePiece vocabulary to the flat table `post::sentencepiece` reads.
3
4# It is BPE, and the "scores" are merge ranks
5
6|`sentencepiece.bpe.model`'s `trainer_spec.model_type` is 2, BPE (asserted by `read_spm`
7below). Its pieces carry scores 0, -1, -2, ... -255996,
8the **negative merge rank**, not a log probability. Encoding is therefore greedy pairwise
9merging by highest score, leftmost on a tie — exactly the loop `post::sentencepiece`
10already implements for SMaLL-100. No Rust change needed; this was the hard blocker and
11it is cleared.
12
13# Inventory: 256,206 ids, and where each comes from
14
15* `tokenizer.json`'s `model.vocab` decides ids: it is the fairseq order, 256,204 entries,
16 ids 0..256203. The `.model` supplies merge ranks only.
17* The `.model` holds 256,000 pieces. All 256,000 appear in `vocab` (`only_spm == 0`, so
18 unlike small100 there are no scoreless-at-runtime pieces hiding behind `<unk>`).
19* 204 `vocab` entries have no `.model` score: `<pad>` (id 1; SPM models never hold it),
20 the 202 flores language codes (`ace_Arab` .. `zul_Latn`, ids 256001..256202) and
21 `<mask>` (id 256203). They all get one below the lowest real rank, so a merge only
22 ever reaches them when no genuine merge applies.
23* Total: 256,204 `vocab` entries (ids 0..256203), but `config.json`'s `vocab_size` is
24 256,206 and the checkpoint embedding is 256,206 rows. Ids 256204 and 256205 appear
25 in NEITHER file: `madeupword`-style padding slots, same as small100's 8 (here 2).
26 They are written as zero-length records so ids stay aligned with embedding rows.
27
28# Normalisation happens in Kotlin
29
30Same as small100: `normalizer_spec` is `nmt_nfkc` with a precompiled charsmap, so the
31app calls `java.text.Normalizer.normalize(text, Form.NFKC)` first and
32`post::sentencepiece` takes it from there (whitespace collapsing + metaspace prefix).
33
34# The format
35
36Identical SPM1 to `small100_tokenizer.py`:
37
38 "SPM1" magic
39 count u32 vocab entries, so an id indexes directly
40 count records, in id order:
41 score i32 the negative merge rank, exact as an integer
42 length u16 the piece's UTF-8 length
43 piece length bytes
44
45# The language map
46
47`--langs-out` writes `nllb_langs.json`: the 202 flores codes in id order with their
48token ids, for app-eng's 202-language picker. Each entry is
49`{"flores": "eng_Latn", "id": 256130}`. The app joins its own UI codes (BCP-47 etc.)
50to `flores`; the token id is what goes on the wire (source-lang prefix + forced-BOS
51target — see `fetch_nllb600.py`'s docstring, shared with rust-eng).
52
53Usage:
54 ./scripts/ml/nllb_tokenizer.py --spm sentencepiece.bpe.model \
55 --tokenizer tokenizer.json -o out/tokenizer.bin --langs-out out/nllb_langs.json
56"""
57
58import argparse
59import json
60import os
61import struct
62import sys
63
64sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
65
66# `trainer_spec.model_type`, from sentencepiece's ModelType enum. Encoding is greedy pairwise
67# merging only because this is BPE; a Unigram model would need Viterbi over the same table.
68MODEL_TYPE_BPE = 2
69
70
71def read_varint(blob, at):
72 """One protobuf varint, returning the value and the offset past it."""
73 value = 0
74 shift = 0
75 while True:
76 if at >= len(blob):
77 raise SystemExit("a varint runs off the end of the model")
78 byte = blob[at]
79 at += 1
80 value |= (byte & 0x7F) << shift
81 if not byte & 0x80:
82 return value, at
83 shift += 7
84
85
86def fields(blob):
87 """Every top-level protobuf field as `(number, wire_type, payload)`.
88
89 Hand-decoded rather than generated, because the alternative is depending on the
90 `sentencepiece` wheel to read three fields out of a file we already have. Only the two wire
91 types this model uses are handled; anything else is a format change worth stopping on.
92 """
93 at = 0
94 while at < len(blob):
95 tag, at = read_varint(blob, at)
96 number, wire = tag >> 3, tag & 7
97 if wire == 2:
98 length, at = read_varint(blob, at)
99 yield number, wire, blob[at : at + length]
100 at += length
101 elif wire == 5:
102 yield number, wire, blob[at : at + 4]
103 at += 4
104 elif wire == 0:
105 value, at = read_varint(blob, at)
106 yield number, wire, value
107 else:
108 raise SystemExit(f"unhandled protobuf wire type {wire} in the model")
109
110
111def read_spm(path):
112 """`piece -> merge rank` from a `sentencepiece.bpe.model`, asserting it is the BPE we expect.
113
114 `ModelProto` numbers `pieces` 1, `trainer_spec` 2 and `normalizer_spec` 3; inside a piece,
115 `piece` is 1 and `score` is 2 as a fixed32 float. Scores are whole numbers because they are
116 ranks, and that is asserted rather than rounded - a fractional score would mean the file is
117 Unigram after all, and the Rust merge loop would be the wrong algorithm.
118 """
119 blob = open(path, "rb").read()
120 scores = {}
121 checked_type = False
122 for number, _, payload in fields(blob):
123 if number == 1:
124 piece, score = None, 0.0
125 for inner, wire, value in fields(payload):
126 if inner == 1:
127 piece = value.decode("utf-8")
128 elif inner == 2 and wire == 5:
129 score = struct.unpack("<f", value)[0]
130 if piece is None:
131 raise SystemExit(f"{path}: a piece with no `piece` field")
132 if score != int(score):
133 raise SystemExit(f"{path}: {piece!r} scores {score}, which is not a merge rank")
134 scores.setdefault(piece, int(score))
135 elif number == 2:
136 for inner, _, value in fields(payload):
137 if inner == 3:
138 checked_type = True
139 if value != MODEL_TYPE_BPE:
140 raise SystemExit(
141 f"{path}: trainer_spec.model_type is {value}, not BPE"
142 f" ({MODEL_TYPE_BPE}); the merge loop in post::sentencepiece only"
143 " applies to BPE"
144 )
145 elif number == 3:
146 for inner, _, value in fields(payload):
147 if inner == 1 and value.decode("utf-8") != "nmt_nfkc":
148 raise SystemExit(
149 f"{path}: normalizer is {value.decode('utf-8')!r}, not nmt_nfkc;"
150 " the Kotlin caller normalises with Form.NFKC"
151 )
152 if not checked_type:
153 raise SystemExit(f"{path}: no trainer_spec.model_type, so this may not be BPE")
154 return scores
155
156MAGIC = b"SPM1"
157
158# fairseq's four, which the Rust checks rather than assumes.
159SPECIALS = ["<s>", "<pad>", "</s>", "<unk>"]
160
161# `config.json`'s vocab_size, and therefore the embedding width the converter reads.
162VOCAB_SIZE = 256_206
163
164# Ids in neither the .model nor tokenizer.json: padding so the table covers every
165# embedding row. Same role as small100's 8 madeupwords.
166TRAILING_PADS = VOCAB_SIZE - 256_204
167LANG_LO, LANG_HI = 256_001, 256_202
168MASK_ID = 256_203
169
170
171def build(spm_path, tokenizer_path):
172 """`[(piece, score)]` in id order, plus the lang-code inventory for `--langs-out`."""
173 scores = read_spm(spm_path)
174 held = json.load(open(tokenizer_path, encoding="utf-8"))
175 vocab = held["model"]["vocab"]
176
177 by_id = {}
178 for piece, id_ in vocab.items():
179 if id_ in by_id:
180 raise SystemExit(f"{tokenizer_path}: id {id_} is both {by_id[id_]!r} and {piece!r}")
181 by_id[id_] = piece
182 if sorted(by_id) != list(range(len(by_id))):
183 raise SystemExit(f"{tokenizer_path}: ids are not 0..{len(by_id) - 1}")
184
185 names = [by_id[i] for i in range(4)]
186 if names != SPECIALS:
187 raise SystemExit(f"ids 0..3 are {names}, not fairseq's specials in fairseq's order")
188
189 added = {a["content"]: a["id"] for a in held.get("added_tokens", [])}
190 langs = sorted(
191 ((code, id_) for code, id_ in added.items() if LANG_LO <= id_ <= LANG_HI),
192 key=lambda pair: pair[1],
193 )
194 if len(langs) != 202 or [id_ for _, id_ in langs] != list(range(LANG_LO, LANG_HI + 1)):
195 raise SystemExit(
196 f"{tokenizer_path}: {len(langs)} language tokens in "
197 f"{LANG_LO}..{LANG_HI}, not the contiguous 202 flores200 codes"
198 )
199 if added.get("<mask>") != MASK_ID:
200 raise SystemExit(f"{tokenizer_path}: <mask> is {added.get('<mask>')}, not {MASK_ID}")
201
202 # One below the lowest real rank, so these lose every merge they are in.
203 floor = min(scores.values()) - 1
204 shared = sum(1 for piece in by_id.values() if piece in scores)
205 table = [(by_id[id_], scores.get(by_id[id_], floor)) for id_ in range(len(by_id))]
206 table += [("", floor)] * TRAILING_PADS
207 if len(table) != VOCAB_SIZE:
208 raise SystemExit(f"{len(table)} ids against config.json's vocab_size {VOCAB_SIZE}")
209 return table, shared, langs
210
211
212def pack(vocab):
213 """The `SPM1` blob for `[(piece, score)]` in id order."""
214 out = bytearray(MAGIC)
215 out += struct.pack("<I", len(vocab))
216 empty = 0
217 for piece, score in vocab:
218 encoded = piece.encode("utf-8")
219 if len(encoded) > 0xFFFF:
220 raise SystemExit(f"a piece of {len(encoded)} bytes does not fit a u16 length")
221 if score != int(score):
222 raise SystemExit(f"{piece!r} scores {score}, which is not a merge rank")
223 empty += not encoded
224 out += struct.pack("<iH", int(score), len(encoded))
225 out += encoded
226 return bytes(out), len(vocab), empty
227
228
229def main():
230 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
231 parser.add_argument("--spm", required=True, help="sentencepiece.bpe.model")
232 parser.add_argument("--tokenizer", required=True, help="tokenizer.json, the fairseq id order")
233 parser.add_argument("-o", "--out", required=True)
234 parser.add_argument("--langs-out", required=True, help="where to write nllb_langs.json")
235 args = parser.parse_args()
236
237 vocab, shared, langs = build(args.spm, args.tokenizer)
238 blob, count, empty = pack(vocab)
239 directory = os.path.dirname(os.path.abspath(args.out))
240 os.makedirs(directory, exist_ok=True)
241 with open(args.out, "wb") as f:
242 f.write(blob)
243 print(f"{os.path.basename(args.out)}: {count} pieces ({empty} empty), {len(blob)} bytes, "
244 f"{shared} scores from the .model")
245
246 mapping = [{"flores": code, "id": id_} for code, id_ in langs]
247 with open(args.langs_out, "w", encoding="utf-8") as f:
248 json.dump(mapping, f, indent=2)
249 f.write("\n")
250 print(f"{os.path.basename(args.langs_out)}: {len(mapping)} flores codes "
251 f"{langs[0][1]}..{langs[-1][1]}")
252
253
254if __name__ == "__main__":
255 main()