File size: 3,385 Bytes
dfeab58 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | import json
import os
from dataclasses import dataclass
from typing import Dict, List, Sequence
TOKENIZER_NAME = "tokenizer.json"
@dataclass
class DigitTokenizer:
num_digits: int = 10
pad_id: int = 10
eos_id: int = 11
pad_token: str = "<pad>"
eos_token: str = "<eos>"
@property
def vocab_size(self) -> int:
return self.num_digits + 2
@property
def id_to_token(self) -> List[str]:
return [str(d) for d in range(self.num_digits)] + [self.pad_token, self.eos_token]
def token_to_id(self, token: str) -> int:
tokens = self.id_to_token
if token not in tokens:
raise KeyError(f"unknown token: {token!r}")
return tokens.index(token)
def encode(self, digits: Sequence[int], add_eos: bool = True) -> List[int]:
for d in digits:
if not 0 <= int(d) < self.num_digits:
raise ValueError(f"digit out of range: {d}")
ids = [int(d) for d in digits]
if add_eos:
ids.append(self.eos_id)
return ids
def decode(self, ids: Sequence[int], skip_special: bool = True) -> str:
out = []
for i in ids:
i = int(i)
if i == self.eos_id:
if not skip_special:
out.append(self.eos_token)
break
if i == self.pad_id:
if not skip_special:
out.append(self.pad_token)
continue
if 0 <= i < self.num_digits:
out.append(str(i))
return "".join(out)
def pad_batch(self, sequences: Sequence[Sequence[int]]) -> List[List[int]]:
max_len = max((len(s) for s in sequences), default=0)
return [list(s) + [self.pad_id] * (max_len - len(s)) for s in sequences]
@classmethod
def from_config(cls, cfg: Dict) -> "DigitTokenizer":
m = cfg["model"]
return cls(
num_digits=int(m["vocab_size"]) - 2,
pad_id=int(m["pad_id"]),
eos_id=int(m["eos_id"]),
)
def to_dict(self) -> Dict:
return {
"class": "DigitTokenizer",
"num_digits": self.num_digits,
"vocab_size": self.vocab_size,
"pad_id": self.pad_id,
"eos_id": self.eos_id,
"pad_token": self.pad_token,
"eos_token": self.eos_token,
"vocab": {str(i): t for i, t in enumerate(self.id_to_token)},
"id_to_token": self.id_to_token,
}
@classmethod
def from_dict(cls, d: Dict) -> "DigitTokenizer":
if d.get("class") != "DigitTokenizer":
raise ValueError(f"unexpected tokenizer class: {d.get('class')!r}")
return cls(
num_digits=int(d["num_digits"]),
pad_id=int(d["pad_id"]),
eos_id=int(d["eos_id"]),
pad_token=d.get("pad_token", "<pad>"),
eos_token=d.get("eos_token", "<eos>"),
)
def save(self, path: str) -> str:
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(self.to_dict(), f, ensure_ascii=False, indent=2)
return path
@classmethod
def load(cls, path: str) -> "DigitTokenizer":
with open(path, "r", encoding="utf-8") as f:
return cls.from_dict(json.load(f)) |