Upload gct_tokenizer.py
Browse files- gct_tokenizer.py +141 -0
gct_tokenizer.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
GCTokenizer-v1 reference implementation.
|
| 3 |
+
|
| 4 |
+
Deterministic longest-match segmentation over UTF-8 bytes with
|
| 5 |
+
universal single-byte fallback tokens of the form <0xXX>.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import re
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
_BYTE_TOKEN_RE = re.compile(r"^<0x([0-9A-Fa-f]{2})>$")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class _TrieNode:
|
| 20 |
+
__slots__ = ("children", "token_id")
|
| 21 |
+
|
| 22 |
+
def __init__(self) -> None:
|
| 23 |
+
self.children: Dict[int, "_TrieNode"] = {}
|
| 24 |
+
self.token_id: Optional[int] = None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class GCTokenizer:
|
| 28 |
+
"""Lossless longest-match tokenizer with byte fallback."""
|
| 29 |
+
|
| 30 |
+
def __init__(self, vocab: Dict[str, int], *, name: str = "GCT") -> None:
|
| 31 |
+
self.name = name
|
| 32 |
+
self.token_to_id: Dict[str, int] = dict(vocab)
|
| 33 |
+
self.id_to_token: Dict[int, str] = {i: t for t, i in vocab.items()}
|
| 34 |
+
|
| 35 |
+
# id -> raw bytes emitted on decode / matched on encode
|
| 36 |
+
self.id_to_bytes: Dict[int, bytes] = {}
|
| 37 |
+
self.byte_id: List[Optional[int]] = [None] * 256
|
| 38 |
+
|
| 39 |
+
root = _TrieNode()
|
| 40 |
+
for token, tid in vocab.items():
|
| 41 |
+
m = _BYTE_TOKEN_RE.match(token)
|
| 42 |
+
if m:
|
| 43 |
+
b = int(m.group(1), 16)
|
| 44 |
+
bb = bytes([b])
|
| 45 |
+
self.id_to_bytes[tid] = bb
|
| 46 |
+
self.byte_id[b] = tid
|
| 47 |
+
else:
|
| 48 |
+
bb = token.encode("utf-8")
|
| 49 |
+
self.id_to_bytes[tid] = bb
|
| 50 |
+
|
| 51 |
+
node = root
|
| 52 |
+
for byte in bb:
|
| 53 |
+
nxt = node.children.get(byte)
|
| 54 |
+
if nxt is None:
|
| 55 |
+
nxt = _TrieNode()
|
| 56 |
+
node.children[byte] = nxt
|
| 57 |
+
node = nxt
|
| 58 |
+
# Prefer keeping an existing terminal if somehow duplicated;
|
| 59 |
+
# vocab ids are unique so this just records the token.
|
| 60 |
+
node.token_id = tid
|
| 61 |
+
|
| 62 |
+
self._root = root
|
| 63 |
+
|
| 64 |
+
missing = [i for i, tid in enumerate(self.byte_id) if tid is None]
|
| 65 |
+
if missing:
|
| 66 |
+
raise ValueError(
|
| 67 |
+
f"{name}: byte fallback incomplete, missing bytes {missing[:8]}..."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
@classmethod
|
| 71 |
+
def from_dir(cls, path: str | Path) -> "GCTokenizer":
|
| 72 |
+
path = Path(path)
|
| 73 |
+
data = json.loads((path / "tokenizer.json").read_text(encoding="utf-8"))
|
| 74 |
+
if data.get("type") not in (None, "GCT"):
|
| 75 |
+
# Still accept; GCT is the expected type.
|
| 76 |
+
pass
|
| 77 |
+
vocab = data["vocab"]
|
| 78 |
+
name = path.name
|
| 79 |
+
return cls(vocab, name=name)
|
| 80 |
+
|
| 81 |
+
# ------------------------------------------------------------------
|
| 82 |
+
# Core API
|
| 83 |
+
# ------------------------------------------------------------------
|
| 84 |
+
def encode_bytes(self, data: bytes) -> List[int]:
|
| 85 |
+
"""Greedy longest-match encode over raw bytes."""
|
| 86 |
+
root = self._root
|
| 87 |
+
ids: List[int] = []
|
| 88 |
+
n = len(data)
|
| 89 |
+
i = 0
|
| 90 |
+
while i < n:
|
| 91 |
+
node = root
|
| 92 |
+
last_id: Optional[int] = None
|
| 93 |
+
last_j = i
|
| 94 |
+
j = i
|
| 95 |
+
while j < n:
|
| 96 |
+
nxt = node.children.get(data[j])
|
| 97 |
+
if nxt is None:
|
| 98 |
+
break
|
| 99 |
+
node = nxt
|
| 100 |
+
j += 1
|
| 101 |
+
if node.token_id is not None:
|
| 102 |
+
last_id = node.token_id
|
| 103 |
+
last_j = j
|
| 104 |
+
if last_id is not None:
|
| 105 |
+
ids.append(last_id)
|
| 106 |
+
i = last_j
|
| 107 |
+
else:
|
| 108 |
+
# Single-byte fallback (always present).
|
| 109 |
+
ids.append(self.byte_id[data[i]]) # type: ignore[arg-type]
|
| 110 |
+
i += 1
|
| 111 |
+
return ids
|
| 112 |
+
|
| 113 |
+
def decode_bytes(self, ids: Sequence[int]) -> bytes:
|
| 114 |
+
parts = self.id_to_bytes
|
| 115 |
+
out = bytearray()
|
| 116 |
+
for tid in ids:
|
| 117 |
+
b = parts.get(tid)
|
| 118 |
+
if b is None:
|
| 119 |
+
raise KeyError(f"unknown token id: {tid}")
|
| 120 |
+
out.extend(b)
|
| 121 |
+
return bytes(out)
|
| 122 |
+
|
| 123 |
+
def encode(self, text: str) -> List[int]:
|
| 124 |
+
return self.encode_bytes(text.encode("utf-8"))
|
| 125 |
+
|
| 126 |
+
def decode(self, ids: Sequence[int]) -> str:
|
| 127 |
+
return self.decode_bytes(ids).decode("utf-8")
|
| 128 |
+
|
| 129 |
+
def tokenize(self, text: str) -> List[str]:
|
| 130 |
+
return [self.id_to_token[i] for i in self.encode(text)]
|
| 131 |
+
|
| 132 |
+
def roundtrip_bytes(self, data: bytes) -> bool:
|
| 133 |
+
return self.decode_bytes(self.encode_bytes(data)) == data
|
| 134 |
+
|
| 135 |
+
def __len__(self) -> int:
|
| 136 |
+
return len(self.token_to_id)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def load_all(root: str | Path = "GCTokenizer-v1") -> Dict[str, GCTokenizer]:
|
| 140 |
+
root = Path(root)
|
| 141 |
+
return {tier: GCTokenizer.from_dir(root / tier) for tier in ("S", "M", "L", "XL")}
|