91 lines
3.5 kB
1"""Learning which bytes hide behind every token id.
2
3The model scores token ids, but the rules in grammar.py judge bytes, so the
4decoder needs to know what bytes a candidate token would print before accepting
5it. The model ships that in vocab.json, with one catch: tokens are stored with
6every byte mapped to a printable character, so that the file stays readable
7text. That mapping is undone here.
8
9The table is enough to turn ids back into text, which is what decode does. The
10SDK offers that too, but nothing here uses it: everything below is built from
11the vocabulary file alone.
12"""
13
14import json
15from pathlib import Path
16from typing import Dict, Iterable, List, Sequence
17
18
19def byte_to_character() -> Dict[int, str]:
20 """Build the mapping the vocabulary file uses to stay printable.
21
22 Bytes that are already printable stand for themselves; the other 68 are
23 given an unused character above them, in order.
24
25 Returns:
26 One character for each of the 256 byte values.
27 """
28 printable = (
29 list(range(ord("!"), ord("~") + 1))
30 + list(range(ord("¡"), ord("¬") + 1))
31 + list(range(ord("®"), ord("ÿ") + 1))
32 )
33 mapping = {byte: chr(byte) for byte in printable}
34 for offset, byte in enumerate(byte for byte in range(256) if byte not in mapping):
35 mapping[byte] = chr(256 + offset)
36 return mapping
37
38
39def load_token_bytes(vocab_path: Path) -> List[bytes]:
40 """Read the vocabulary and return the bytes each token id prints.
41
42 Both shapes a model may ship are accepted: a vocab.json, which is the table
43 itself, and a tokenizer.json, which keeps the same table under "model".
44 Ids the file does not describe, such as markers added on top of the
45 vocabulary, are left empty; the decoder treats those as unusable.
46
47 Args:
48 vocab_path: The vocab.json or tokenizer.json file of the model.
49
50 Returns:
51 A table indexed by token id.
52
53 Raises:
54 ValueError: If the file holds no vocabulary at all.
55 """
56 payload = json.loads(vocab_path.read_text(encoding="utf-8"))
57 if isinstance(payload.get("model"), dict):
58 payload = payload["model"].get("vocab")
59 if not isinstance(payload, dict) or not payload:
60 raise ValueError(f"no vocabulary found in {vocab_path}")
61
62 vocabulary: Dict[str, int] = payload
63 character_to_byte = {character: byte for byte, character in byte_to_character().items()}
64
65 table = [b""] * (max(vocabulary.values(), default=-1) + 1)
66 for token, token_id in vocabulary.items():
67 if all(character in character_to_byte for character in token):
68 table[token_id] = bytes(character_to_byte[character] for character in token)
69 return table
70
71
72def decode(token_bytes: Sequence[bytes], token_ids: Iterable[int]) -> str:
73 """Turn token ids back into the text they write.
74
75 Ids the table does not describe write nothing, which is what a marker such
76 as an end of turn does. A token may also carry half of a character, so the
77 bytes are gathered first and read as text once, at the end.
78
79 Args:
80 token_bytes: The bytes of every token id, as load_token_bytes returns.
81 token_ids: The ids to read.
82
83 Returns:
84 The text those ids spell, with any byte that ends up incomplete shown
85 as the replacement character rather than raising.
86 """
87 written = bytearray()
88 for token_id in token_ids:
89 if 0 <= token_id < len(token_bytes):
90 written.extend(token_bytes[token_id])
91 return written.decode("utf-8", errors="replace")