gbl1357 commited on
Commit
b5a4b32
·
verified ·
1 Parent(s): dc1c518

Update tokenizer.py

Browse files
Files changed (1) hide show
  1. tokenizer.py +214 -0
tokenizer.py CHANGED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom Chess Tokenizer for the Chess Challenge.
3
+ This tokenizer treats each move as a sequence of structured tokens derived from the
4
+ extended UCI notation from the Lichess dataset (e.g., WPe2e4, BNg8f6).
5
+ The dataset format uses:
6
+ - W/B prefix for White/Black
7
+ - Piece letter: P=Pawn, N=Knight, B=Bishop, R=Rook, Q=Queen, K=King
8
+ - Source and destination squares (e.g., e2e4)
9
+ - Special suffixes: (x)=capture, (+)=check, (+*)=checkmate, (o)/(O)=castling
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import re
17
+ from typing import Dict, List, Optional, Sequence, Union
18
+
19
+ from transformers import PreTrainedTokenizer
20
+
21
+
22
+ _MOVE_RE = re.compile(
23
+ r"^(?P<side>[WB])"
24
+ r"(?P<piece>[PNBRQK])"
25
+ r"(?P<src>[a-h][1-8])"
26
+ r"(?P<dst>[a-h][1-8])"
27
+ r"(?P<rest>.*)$"
28
+ )
29
+
30
+
31
+ class ChessTokenizer(PreTrainedTokenizer):
32
+ """
33
+ A structured tokenizer for chess moves.
34
+ Each move is decomposed into:
35
+ SIDE_(W/B), PIECE_(P/N/B/R/Q/K), SQ_<src>, SQ_<dst>,
36
+ and optional flags: CAPTURE, CHECK, MATE, CASTLE, PROMO_(Q/R/B/N).
37
+ This avoids UNK explosions when using a move-as-token vocabulary.
38
+ """
39
+
40
+ model_input_names = ["input_ids", "attention_mask"]
41
+ vocab_files_names = {"vocab_file": "vocab.json"}
42
+
43
+ # Special tokens
44
+ PAD_TOKEN = "[PAD]"
45
+ BOS_TOKEN = "[BOS]"
46
+ EOS_TOKEN = "[EOS]"
47
+ UNK_TOKEN = "[UNK]"
48
+
49
+ # Fixed token set
50
+ SIDE_W = "SIDE_W"
51
+ SIDE_B = "SIDE_B"
52
+
53
+ PIECES = ["P", "N", "B", "R", "Q", "K"]
54
+
55
+ PROMO_PREFIX = "PROMO_"
56
+ CAPTURE = "CAPTURE"
57
+ CHECK = "CHECK"
58
+ MATE = "MATE"
59
+ CASTLE = "CASTLE"
60
+
61
+ def __init__(
62
+ self,
63
+ vocab_file: Optional[str] = None,
64
+ vocab: Optional[Dict[str, int]] = None,
65
+ **kwargs,
66
+ ):
67
+ kwargs.pop("pad_token", None)
68
+ kwargs.pop("bos_token", None)
69
+ kwargs.pop("eos_token", None)
70
+ kwargs.pop("unk_token", None)
71
+
72
+ self._pad_token = self.PAD_TOKEN
73
+ self._bos_token = self.BOS_TOKEN
74
+ self._eos_token = self.EOS_TOKEN
75
+ self._unk_token = self.UNK_TOKEN
76
+
77
+ if vocab is not None:
78
+ self._vocab = vocab
79
+ elif vocab_file is not None and os.path.exists(vocab_file):
80
+ with open(vocab_file, "r", encoding="utf-8") as f:
81
+ self._vocab = json.load(f)
82
+ else:
83
+ self._vocab = self._build_fixed_vocab()
84
+
85
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
86
+
87
+ super().__init__(
88
+ pad_token=self._pad_token,
89
+ bos_token=self._bos_token,
90
+ eos_token=self._eos_token,
91
+ unk_token=self._unk_token,
92
+ **kwargs,
93
+ )
94
+
95
+ def _build_fixed_vocab(self) -> Dict[str, int]:
96
+ special = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
97
+ sides = [self.SIDE_W, self.SIDE_B]
98
+ pieces = [f"PIECE_{p}" for p in self.PIECES]
99
+ squares = [f"SQ_{file}{rank}" for file in "abcdefgh" for rank in "12345678"]
100
+ promos = [f"{self.PROMO_PREFIX}{p}" for p in ["Q", "R", "B", "N"]]
101
+ flags = [self.CAPTURE, self.CHECK, self.MATE, self.CASTLE]
102
+ tokens = special + sides + pieces + squares + promos + flags
103
+ return {tok: i for i, tok in enumerate(tokens)}
104
+
105
+ @classmethod
106
+ def build_vocab_from_dataset(cls, *args, **kwargs) -> "ChessTokenizer":
107
+ """
108
+ Kept for API compatibility with the template training script.
109
+ This tokenizer uses a fixed vocabulary (no dataset-dependent pruning).
110
+ """
111
+ return cls()
112
+
113
+ @classmethod
114
+ def build_vocab_from_iterator(cls, *args, **kwargs) -> "ChessTokenizer":
115
+ """
116
+ Kept for API compatibility. This tokenizer uses a fixed vocabulary.
117
+ """
118
+ return cls()
119
+
120
+ @property
121
+ def vocab_size(self) -> int:
122
+ return len(self._vocab)
123
+
124
+ def get_vocab(self) -> Dict[str, int]:
125
+ return dict(self._vocab)
126
+
127
+ def _tokenize(self, text: str) -> List[str]:
128
+ tokens: List[str] = []
129
+ moves = text.strip().split()
130
+ for mv in moves:
131
+ tokens.extend(self._tokenize_move(mv))
132
+ return tokens
133
+
134
+ def _tokenize_move(self, move: str) -> List[str]:
135
+ m = _MOVE_RE.match(move)
136
+ if not m:
137
+ return [self.UNK_TOKEN]
138
+
139
+ side = m.group("side")
140
+ piece = m.group("piece")
141
+ src = m.group("src")
142
+ dst = m.group("dst")
143
+ rest = m.group("rest") or ""
144
+
145
+ out: List[str] = []
146
+ out.append(self.SIDE_W if side == "W" else self.SIDE_B)
147
+ out.append(f"PIECE_{piece}")
148
+ out.append(f"SQ_{src}")
149
+ out.append(f"SQ_{dst}")
150
+
151
+ promo = self._parse_promotion(rest)
152
+ if promo is not None:
153
+ out.append(f"{self.PROMO_PREFIX}{promo}")
154
+
155
+ if "(x)" in rest or "x" in rest:
156
+ out.append(self.CAPTURE)
157
+
158
+ if "(+*)" in rest or "++" in rest or "#" in rest:
159
+ out.append(self.MATE)
160
+ elif "(+)" in rest or "+" in rest:
161
+ out.append(self.CHECK)
162
+
163
+ if "(o)" in rest or "(O)" in rest or "O-O" in rest:
164
+ out.append(self.CASTLE)
165
+
166
+ return out
167
+
168
+ def _parse_promotion(self, rest: str) -> Optional[str]:
169
+ m = re.search(r"=([QRBNqrbn])", rest)
170
+ if m:
171
+ return m.group(1).upper()
172
+ return None
173
+
174
+ def _convert_token_to_id(self, token: str) -> int:
175
+ return self._vocab.get(token, self._vocab[self.UNK_TOKEN])
176
+
177
+ def _convert_id_to_token(self, index: int) -> str:
178
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
179
+
180
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
181
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
182
+ out: List[str] = []
183
+ for t in tokens:
184
+ if t in special:
185
+ continue
186
+ out.append(t)
187
+ return " ".join(out)
188
+
189
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple:
190
+ if not os.path.isdir(save_directory):
191
+ os.makedirs(save_directory, exist_ok=True)
192
+
193
+ vocab_file = os.path.join(
194
+ save_directory,
195
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
196
+ )
197
+ with open(vocab_file, "w", encoding="utf-8") as f:
198
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
199
+
200
+ return (vocab_file,)
201
+
202
+ def decode(self, token_ids: Union[int, Sequence[int]], skip_special_tokens: bool = False, **kwargs) -> str:
203
+ if isinstance(token_ids, int):
204
+ ids = [token_ids]
205
+ elif "torch" in str(type(token_ids)):
206
+ ids = token_ids.detach().cpu().flatten().tolist()
207
+ else:
208
+ ids = list(token_ids)
209
+
210
+ toks = [self._convert_id_to_token(i) for i in ids]
211
+ if skip_special_tokens:
212
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
213
+ toks = [t for t in toks if t not in special]
214
+ return self.convert_tokens_to_string(toks)