| | """ |
| | Custom Atomic Chess Tokenizer for the Chess Challenge. |
| | Strategy: Component-level tokenization (W, P, e2, e4) to save vocabulary size. |
| | """ |
| |
|
| | from __future__ import annotations |
| |
|
| | import json |
| | import os |
| | from typing import Dict, List, Optional, Tuple |
| |
|
| |
|
| | from transformers import PreTrainedTokenizer |
| |
|
| | class ChessTokenizer(PreTrainedTokenizer): |
| | model_input_names = ["input_ids", "attention_mask"] |
| | |
| | def __init__(self, vocab_file: str = None, **kwargs): |
| | |
| | self.special_tokens = ["[PAD]", "[BOS]", "[EOS]", "[UNK]"] |
| | self.colors = ["W", "B"] |
| | self.pieces = ["P", "N", "B", "R", "Q", "K"] |
| | self.squares = [f"{c}{r}" for c in "abcdefgh" for r in range(1, 9)] |
| | self.suffixes = ["x", "+", "#", "=", "O-O", "O-O-O"] |
| | |
| | |
| | all_tokens = self.special_tokens + self.colors + self.pieces + self.squares + self.suffixes |
| | |
| | |
| | self.vocab = {t: i for i, t in enumerate(all_tokens)} |
| | self.ids_to_tokens = {i: t for t, i in self.vocab.items()} |
| |
|
| | kwargs.pop("pad_token", None) |
| | kwargs.pop("bos_token", None) |
| | kwargs.pop("eos_token", None) |
| | kwargs.pop("unk_token", None) |
| | |
| | |
| | super().__init__( |
| | pad_token="[PAD]", |
| | bos_token="[BOS]", |
| | eos_token="[EOS]", |
| | unk_token="[UNK]", |
| | **kwargs |
| | ) |
| | |
| | @property |
| | def vocab_size(self) -> int: |
| | return len(self.vocab) |
| | |
| | def get_vocab(self) -> Dict[str, int]: |
| | return dict(self.vocab) |
| |
|
| | def _tokenize(self, text: str) -> List[str]: |
| | """ |
| | Input: "WPe2e4 BNg8f6" |
| | Output: ['W', 'P', 'e2', 'e4', 'B', 'N', 'g8', 'f6'] |
| | """ |
| | tokens = [] |
| | moves = text.strip().split() |
| | |
| | for move in moves: |
| | |
| | if "O-O" in move: |
| | tokens.append(move) |
| | continue |
| | |
| | |
| | |
| | remaining = move |
| | while remaining: |
| | matched = False |
| | |
| | |
| | |
| | |
| | |
| | if len(remaining) >= 2 and remaining[:2] in self.vocab: |
| | tokens.append(remaining[:2]) |
| | remaining = remaining[2:] |
| | matched = True |
| | continue |
| | |
| | |
| | if len(remaining) >= 1 and remaining[:1] in self.vocab: |
| | tokens.append(remaining[:1]) |
| | remaining = remaining[1:] |
| | matched = True |
| | continue |
| | |
| | |
| | if not matched: |
| | |
| | |
| | remaining = remaining[1:] |
| | |
| | return tokens |
| |
|
| | def _convert_token_to_id(self, token: str) -> int: |
| | return self.vocab.get(token, self.vocab.get(self.unk_token)) |
| |
|
| | def _convert_id_to_token(self, index: int) -> str: |
| | return self.ids_to_tokens.get(index, self.unk_token) |
| |
|
| | |
| | def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: |
| | """ |
| | 保存 vocab.json 到指定目录。没有这个,save_pretrained 会出问题。 |
| | """ |
| | if not os.path.isdir(save_directory): |
| | os.makedirs(save_directory, exist_ok=True) |
| | |
| | vocab_file = os.path.join( |
| | save_directory, |
| | (filename_prefix + "-" if filename_prefix else "") + "vocab.json" |
| | ) |
| | |
| | with open(vocab_file, "w", encoding="utf-8") as f: |
| | json.dump(self.vocab, f, ensure_ascii=False) |
| | |
| | return (vocab_file,) |
| |
|
| | |
| | def convert_tokens_to_string(self, tokens: List[str]) -> str: |
| | """ |
| | 将 Token 列表还原为棋谱字符串。 |
| | Input: ['W', 'P', 'e2', 'e4', 'B', 'P', 'e7', 'e5'] |
| | Output: "WPe2e4 BPe7e5" |
| | """ |
| | out_string = [] |
| | for t in tokens: |
| | |
| | if t in self.special_tokens: |
| | continue |
| | |
| | |
| | |
| | |
| | if t in self.colors or "O-O" in t: |
| | if out_string: |
| | out_string.append(" ") |
| | |
| | out_string.append(t) |
| | |
| | return "".join(out_string).strip() |
| |
|
| | |
| | @classmethod |
| | def build_vocab_from_dataset(cls, *args, **kwargs): |
| | return cls() |