Chess Challenge submission by tlemagny
Browse files- README.md +26 -0
- config.json +20 -0
- model.safetensors +3 -0
- special_tokens_map.json +6 -0
- tokenizer.py +405 -0
- tokenizer_config.json +50 -0
- vocab.json +80 -0
README.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
tags:
|
| 4 |
+
- chess
|
| 5 |
+
- llm-course
|
| 6 |
+
- chess-challenge
|
| 7 |
+
license: mit
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
# chess_tlemagny_4.2
|
| 11 |
+
|
| 12 |
+
Chess model submitted to the LLM Course Chess Challenge.
|
| 13 |
+
|
| 14 |
+
## Submission Info
|
| 15 |
+
|
| 16 |
+
- **Submitted by**: [tlemagny](https://huggingface.co/tlemagny)
|
| 17 |
+
- **Parameters**: 999,220
|
| 18 |
+
- **Organization**: LLM-course
|
| 19 |
+
|
| 20 |
+
## Model Details
|
| 21 |
+
|
| 22 |
+
- **Architecture**: Chess Transformer (GPT-style)
|
| 23 |
+
- **Vocab size**: 78
|
| 24 |
+
- **Embedding dim**: 128
|
| 25 |
+
- **Layers**: 6
|
| 26 |
+
- **Heads**: 8
|
config.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"ChessForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"bos_token_id": 1,
|
| 6 |
+
"dropout": 0.1,
|
| 7 |
+
"dtype": "float32",
|
| 8 |
+
"eos_token_id": 2,
|
| 9 |
+
"layer_norm_epsilon": 1e-05,
|
| 10 |
+
"model_type": "chess_transformer",
|
| 11 |
+
"n_ctx": 384,
|
| 12 |
+
"n_embd": 128,
|
| 13 |
+
"n_head": 8,
|
| 14 |
+
"n_inner": 350,
|
| 15 |
+
"n_layer": 6,
|
| 16 |
+
"pad_token_id": 0,
|
| 17 |
+
"tie_weights": true,
|
| 18 |
+
"transformers_version": "4.57.5",
|
| 19 |
+
"vocab_size": 78
|
| 20 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:719d98cd6453b72198b921ffc9dc70344b0694f5255b89aaf11eb157c15f3ca5
|
| 3 |
+
size 4003328
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": "[BOS]",
|
| 3 |
+
"eos_token": "[EOS]",
|
| 4 |
+
"pad_token": "[PAD]",
|
| 5 |
+
"unk_token": "[UNK]"
|
| 6 |
+
}
|
tokenizer.py
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Custom Chess Tokenizer for the Chess Challenge.
|
| 3 |
+
|
| 4 |
+
This tokenizer treats each move as a single token using the extended UCI notation
|
| 5 |
+
from the Lichess dataset (e.g., WPe2e4, BNg8f6).
|
| 6 |
+
|
| 7 |
+
The dataset format uses:
|
| 8 |
+
- W/B prefix for White/Black
|
| 9 |
+
- Piece letter: P=Pawn, N=Knight, B=Bishop, R=Rook, Q=Queen, K=King
|
| 10 |
+
- Source and destination squares (e.g., e2e4)
|
| 11 |
+
- Special suffixes: (x)=capture, (+)=check, (+*)=checkmate, (o)/(O)=castling
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Dict, List, Optional
|
| 20 |
+
|
| 21 |
+
from transformers import PreTrainedTokenizer
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ChessTokenizer(PreTrainedTokenizer):
|
| 25 |
+
"""
|
| 26 |
+
A custom tokenizer for chess moves using extended UCI notation.
|
| 27 |
+
|
| 28 |
+
This tokenizer maps each possible chess move to a unique token ID.
|
| 29 |
+
The vocabulary is built from the training dataset to ensure all moves
|
| 30 |
+
encountered during training have a corresponding token.
|
| 31 |
+
|
| 32 |
+
Example:
|
| 33 |
+
>>> tokenizer = ChessTokenizer()
|
| 34 |
+
>>> tokenizer.encode("WPe2e4 BPe7e5")
|
| 35 |
+
[1, 42, 87, 2] # [BOS, e2e4, e7e5, EOS]
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 39 |
+
vocab_files_names = {"vocab_file": "vocab.json"}
|
| 40 |
+
|
| 41 |
+
# Special tokens
|
| 42 |
+
PAD_TOKEN = "[PAD]"
|
| 43 |
+
BOS_TOKEN = "[BOS]"
|
| 44 |
+
EOS_TOKEN = "[EOS]"
|
| 45 |
+
UNK_TOKEN = "[UNK]"
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
vocab_file: Optional[str] = None,
|
| 50 |
+
vocab: Optional[Dict[str, int]] = None,
|
| 51 |
+
**kwargs,
|
| 52 |
+
):
|
| 53 |
+
"""
|
| 54 |
+
Initialize the chess tokenizer.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
vocab_file: Path to a JSON file containing the vocabulary mapping.
|
| 58 |
+
vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
|
| 59 |
+
**kwargs: Additional arguments passed to PreTrainedTokenizer.
|
| 60 |
+
"""
|
| 61 |
+
# Initialize special tokens
|
| 62 |
+
self._pad_token = self.PAD_TOKEN
|
| 63 |
+
self._bos_token = self.BOS_TOKEN
|
| 64 |
+
self._eos_token = self.EOS_TOKEN
|
| 65 |
+
self._unk_token = self.UNK_TOKEN
|
| 66 |
+
|
| 67 |
+
# Remove any duplicate special-token entries passed through kwargs
|
| 68 |
+
# to avoid "multiple values for keyword" errors when loading from disk.
|
| 69 |
+
kwargs.pop("pad_token", None)
|
| 70 |
+
kwargs.pop("bos_token", None)
|
| 71 |
+
kwargs.pop("eos_token", None)
|
| 72 |
+
kwargs.pop("unk_token", None)
|
| 73 |
+
|
| 74 |
+
# Load or create vocabulary
|
| 75 |
+
if vocab is not None:
|
| 76 |
+
self._vocab = vocab
|
| 77 |
+
elif vocab_file is not None and os.path.exists(vocab_file):
|
| 78 |
+
with open(vocab_file, "r", encoding="utf-8") as f:
|
| 79 |
+
self._vocab = json.load(f)
|
| 80 |
+
else:
|
| 81 |
+
# Create a minimal vocabulary with just special tokens
|
| 82 |
+
# The full vocabulary should be built from the dataset
|
| 83 |
+
self._vocab = self._create_default_vocab()
|
| 84 |
+
|
| 85 |
+
# Create reverse mapping
|
| 86 |
+
self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
|
| 87 |
+
|
| 88 |
+
# Call parent init AFTER setting up vocab
|
| 89 |
+
super().__init__(
|
| 90 |
+
pad_token=self._pad_token,
|
| 91 |
+
bos_token=self._bos_token,
|
| 92 |
+
eos_token=self._eos_token,
|
| 93 |
+
unk_token=self._unk_token,
|
| 94 |
+
**kwargs,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _create_default_vocab(self) -> Dict[str, int]:
|
| 99 |
+
"""
|
| 100 |
+
Create a minimal default vocabulary with just special tokens.
|
| 101 |
+
|
| 102 |
+
For the full vocabulary, use `build_vocab_from_dataset()`.
|
| 103 |
+
This minimal vocab is just a placeholder - you should build from data.
|
| 104 |
+
"""
|
| 105 |
+
special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
|
| 106 |
+
vocab = {token: idx for idx, token in enumerate(special_tokens)}
|
| 107 |
+
return vocab
|
| 108 |
+
|
| 109 |
+
@classmethod
|
| 110 |
+
def build_vocab_from_iterator(
|
| 111 |
+
cls,
|
| 112 |
+
iterator,
|
| 113 |
+
min_frequency: int = 1,
|
| 114 |
+
) -> "ChessTokenizer":
|
| 115 |
+
"""
|
| 116 |
+
Build a tokenizer vocabulary from an iterator of game strings.
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
iterator: An iterator yielding game strings (space-separated moves).
|
| 120 |
+
min_frequency: Minimum frequency for a token to be included.
|
| 121 |
+
|
| 122 |
+
Returns:
|
| 123 |
+
A ChessTokenizer with the built vocabulary.
|
| 124 |
+
"""
|
| 125 |
+
from collections import Counter
|
| 126 |
+
|
| 127 |
+
token_counts = Counter()
|
| 128 |
+
|
| 129 |
+
for game in iterator:
|
| 130 |
+
moves = game.strip().split()
|
| 131 |
+
token_counts.update(moves)
|
| 132 |
+
|
| 133 |
+
# Filter by frequency
|
| 134 |
+
tokens = [
|
| 135 |
+
token for token, count in token_counts.items()
|
| 136 |
+
if count >= min_frequency
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
# Sort for reproducibility
|
| 140 |
+
tokens = sorted(tokens)
|
| 141 |
+
|
| 142 |
+
# Build vocabulary
|
| 143 |
+
special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
|
| 144 |
+
vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
|
| 145 |
+
|
| 146 |
+
return cls(vocab=vocab)
|
| 147 |
+
|
| 148 |
+
@classmethod
|
| 149 |
+
def build_vocab_from_dataset(
|
| 150 |
+
cls,
|
| 151 |
+
dataset_name: str = "dlouapre/lichess_2025-01_1M",
|
| 152 |
+
split: str = "train",
|
| 153 |
+
column: str = "text",
|
| 154 |
+
min_frequency: int = 500,
|
| 155 |
+
max_samples: Optional[int] = 100000,
|
| 156 |
+
) -> "ChessTokenizer":
|
| 157 |
+
"""
|
| 158 |
+
Build a tokenizer vocabulary from a Hugging Face dataset.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
dataset_name: Name of the dataset on Hugging Face Hub.
|
| 162 |
+
split: Dataset split to use.
|
| 163 |
+
column: Column containing the game strings.
|
| 164 |
+
min_frequency: Minimum frequency for a token to be included (default: 500).
|
| 165 |
+
max_samples: Maximum number of samples to process (default: 100k).
|
| 166 |
+
|
| 167 |
+
Returns:
|
| 168 |
+
A ChessTokenizer with the built vocabulary.
|
| 169 |
+
"""
|
| 170 |
+
from datasets import load_dataset
|
| 171 |
+
|
| 172 |
+
dataset = load_dataset(dataset_name, split=split)
|
| 173 |
+
|
| 174 |
+
if max_samples is not None:
|
| 175 |
+
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 176 |
+
|
| 177 |
+
def game_iterator():
|
| 178 |
+
for example in dataset:
|
| 179 |
+
yield example[column]
|
| 180 |
+
|
| 181 |
+
return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
|
| 182 |
+
|
| 183 |
+
@classmethod
|
| 184 |
+
def build_vocab_static(cls) -> "ChessTokenizer":
|
| 185 |
+
"""
|
| 186 |
+
Build a minimal static vocabulary:
|
| 187 |
+
- 64 board squares (a1-h8)
|
| 188 |
+
- promotion pieces (q, r, b, n)
|
| 189 |
+
- special tokens
|
| 190 |
+
"""
|
| 191 |
+
special_tokens = [
|
| 192 |
+
cls.PAD_TOKEN,
|
| 193 |
+
cls.BOS_TOKEN,
|
| 194 |
+
cls.EOS_TOKEN,
|
| 195 |
+
cls.UNK_TOKEN,
|
| 196 |
+
]
|
| 197 |
+
|
| 198 |
+
squares = [
|
| 199 |
+
f"{file}{rank}"
|
| 200 |
+
for file in "abcdefgh"
|
| 201 |
+
for rank in "12345678"
|
| 202 |
+
]
|
| 203 |
+
|
| 204 |
+
promotion_pieces = ["q", "r", "b", "n"]
|
| 205 |
+
|
| 206 |
+
vocab_tokens = special_tokens + squares + promotion_pieces
|
| 207 |
+
vocab = {tok: idx for idx, tok in enumerate(vocab_tokens)}
|
| 208 |
+
|
| 209 |
+
return cls(vocab=vocab)
|
| 210 |
+
|
| 211 |
+
@classmethod
|
| 212 |
+
def build_vocab_static_2(cls):
|
| 213 |
+
special = [
|
| 214 |
+
cls.PAD_TOKEN,
|
| 215 |
+
cls.BOS_TOKEN,
|
| 216 |
+
cls.EOS_TOKEN,
|
| 217 |
+
cls.UNK_TOKEN,
|
| 218 |
+
]
|
| 219 |
+
|
| 220 |
+
pieces = ["p", "n", "b", "r", "q", "k"]
|
| 221 |
+
promotions = ["p_q", "p_r", "p_b", "p_n"]
|
| 222 |
+
|
| 223 |
+
squares = [f"{f}{r}" for f in "abcdefgh" for r in "12345678"]
|
| 224 |
+
|
| 225 |
+
vocab_tokens = special + pieces + promotions + squares
|
| 226 |
+
vocab = {tok: i for i, tok in enumerate(vocab_tokens)}
|
| 227 |
+
|
| 228 |
+
return cls(vocab=vocab)
|
| 229 |
+
|
| 230 |
+
@property
|
| 231 |
+
def vocab_size(self) -> int:
|
| 232 |
+
"""Return the size of the vocabulary."""
|
| 233 |
+
return len(self._vocab)
|
| 234 |
+
|
| 235 |
+
def get_vocab(self) -> Dict[str, int]:
|
| 236 |
+
"""Return the vocabulary as a dictionary."""
|
| 237 |
+
return dict(self._vocab)
|
| 238 |
+
|
| 239 |
+
'''def _tokenize(self, text: str) -> List[str]:
|
| 240 |
+
"""
|
| 241 |
+
Tokenize a string of moves into a list of tokens.
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
text: A string of space-separated moves.
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
List of move tokens.
|
| 248 |
+
"""
|
| 249 |
+
return text.strip().split()'''
|
| 250 |
+
|
| 251 |
+
'''def _tokenize(self, text: str) -> List[str]:
|
| 252 |
+
"""
|
| 253 |
+
Tokenize extended UCI moves into square-level tokens.
|
| 254 |
+
Example:
|
| 255 |
+
WPe2e4 -> ["e2", "e4"]
|
| 256 |
+
WPe7e8q -> ["e7", "e8", "q"]
|
| 257 |
+
WBb5c6(x) -> ["b5", "c6"]
|
| 258 |
+
WKe1g1(O) -> ["e1", "g1"]
|
| 259 |
+
"""
|
| 260 |
+
tokens = []
|
| 261 |
+
|
| 262 |
+
moves = text.strip().split()
|
| 263 |
+
for move in moves:
|
| 264 |
+
# Remove annotations
|
| 265 |
+
move = move.replace("(x)", "")
|
| 266 |
+
move = move.replace("(+*)", "")
|
| 267 |
+
move = move.replace("(+)", "")
|
| 268 |
+
move = move.replace("(o)", "")
|
| 269 |
+
move = move.replace("(O)", "")
|
| 270 |
+
|
| 271 |
+
# Promotion
|
| 272 |
+
promo = None
|
| 273 |
+
if len(move) >= 2 and move[-1] in "qrbn":
|
| 274 |
+
promo = move[-1]
|
| 275 |
+
move = move[:-1]
|
| 276 |
+
|
| 277 |
+
# Extract squares (always last 4 chars)
|
| 278 |
+
if len(move) >= 4:
|
| 279 |
+
from_sq = move[-4:-2]
|
| 280 |
+
to_sq = move[-2:]
|
| 281 |
+
|
| 282 |
+
tokens.append(from_sq)
|
| 283 |
+
tokens.append(to_sq)
|
| 284 |
+
|
| 285 |
+
if promo:
|
| 286 |
+
tokens.append(promo)
|
| 287 |
+
|
| 288 |
+
return tokens'''
|
| 289 |
+
|
| 290 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 291 |
+
"""
|
| 292 |
+
Tokenize moves into 3 tokens:
|
| 293 |
+
[piece_or_promo] [from_square] [to_square]
|
| 294 |
+
"""
|
| 295 |
+
tokens = []
|
| 296 |
+
moves = text.strip().split()
|
| 297 |
+
|
| 298 |
+
for move in moves:
|
| 299 |
+
# Remove annotations
|
| 300 |
+
for s in ["(x)", "(+*)", "(+)", "(o)", "(O)"]:
|
| 301 |
+
move = move.replace(s, "")
|
| 302 |
+
|
| 303 |
+
# Color is first char (W/B), ignore
|
| 304 |
+
color = move[0]
|
| 305 |
+
|
| 306 |
+
# Piece letter
|
| 307 |
+
piece = move[1].lower() # p n b r q k
|
| 308 |
+
|
| 309 |
+
# Promotion
|
| 310 |
+
promo = None
|
| 311 |
+
if piece == "p" and move[-1] in "qrbn":
|
| 312 |
+
promo = move[-1]
|
| 313 |
+
move = move[:-1]
|
| 314 |
+
|
| 315 |
+
# Extract squares
|
| 316 |
+
from_sq = move[-4:-2]
|
| 317 |
+
to_sq = move[-2:]
|
| 318 |
+
|
| 319 |
+
# Piece token
|
| 320 |
+
if promo:
|
| 321 |
+
piece_token = f"p_{promo}" # p_q, p_r, p_b, p_n
|
| 322 |
+
else:
|
| 323 |
+
piece_token = piece
|
| 324 |
+
|
| 325 |
+
tokens.extend([piece_token, from_sq, to_sq])
|
| 326 |
+
|
| 327 |
+
return tokens
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _convert_token_to_id(self, token: str) -> int:
|
| 331 |
+
"""Convert a token to its ID."""
|
| 332 |
+
return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
|
| 333 |
+
|
| 334 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 335 |
+
"""Convert an ID to its token."""
|
| 336 |
+
return self._ids_to_tokens.get(index, self.UNK_TOKEN)
|
| 337 |
+
|
| 338 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
| 339 |
+
"""Convert a list of tokens back to a string."""
|
| 340 |
+
# Filter out special tokens for cleaner output
|
| 341 |
+
special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
|
| 342 |
+
return " ".join(t for t in tokens if t not in special)
|
| 343 |
+
|
| 344 |
+
def save_vocabulary(
|
| 345 |
+
self,
|
| 346 |
+
save_directory: str,
|
| 347 |
+
filename_prefix: Optional[str] = None,
|
| 348 |
+
) -> tuple:
|
| 349 |
+
"""
|
| 350 |
+
Save the vocabulary to a JSON file.
|
| 351 |
+
|
| 352 |
+
Args:
|
| 353 |
+
save_directory: Directory to save the vocabulary.
|
| 354 |
+
filename_prefix: Optional prefix for the filename.
|
| 355 |
+
|
| 356 |
+
Returns:
|
| 357 |
+
Tuple containing the path to the saved vocabulary file.
|
| 358 |
+
"""
|
| 359 |
+
if not os.path.isdir(save_directory):
|
| 360 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 361 |
+
|
| 362 |
+
vocab_file = os.path.join(
|
| 363 |
+
save_directory,
|
| 364 |
+
(filename_prefix + "-" if filename_prefix else "") + "vocab.json",
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 368 |
+
json.dump(self._vocab, f, ensure_ascii=False, indent=2)
|
| 369 |
+
|
| 370 |
+
return (vocab_file,)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def count_vocab_from_dataset(
|
| 374 |
+
dataset_name: str = "dlouapre/lichess_2025-01_1M",
|
| 375 |
+
split: str = "train",
|
| 376 |
+
column: str = "text",
|
| 377 |
+
max_samples: Optional[int] = 10000,
|
| 378 |
+
) -> Dict[str, int]:
|
| 379 |
+
"""
|
| 380 |
+
Count token frequencies in a dataset (useful for vocabulary analysis).
|
| 381 |
+
|
| 382 |
+
Args:
|
| 383 |
+
dataset_name: Name of the dataset on Hugging Face Hub.
|
| 384 |
+
split: Dataset split to use.
|
| 385 |
+
column: Column containing the game strings.
|
| 386 |
+
max_samples: Maximum number of samples to process.
|
| 387 |
+
|
| 388 |
+
Returns:
|
| 389 |
+
Dictionary mapping tokens to their frequencies.
|
| 390 |
+
"""
|
| 391 |
+
from collections import Counter
|
| 392 |
+
from datasets import load_dataset
|
| 393 |
+
|
| 394 |
+
dataset = load_dataset(dataset_name, split=split)
|
| 395 |
+
|
| 396 |
+
if max_samples is not None:
|
| 397 |
+
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 398 |
+
|
| 399 |
+
token_counts = Counter()
|
| 400 |
+
|
| 401 |
+
for example in dataset:
|
| 402 |
+
moves = example[column].strip().split()
|
| 403 |
+
token_counts.update(moves)
|
| 404 |
+
|
| 405 |
+
return dict(token_counts)
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"added_tokens_decoder": {
|
| 3 |
+
"0": {
|
| 4 |
+
"content": "[PAD]",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false,
|
| 9 |
+
"special": true
|
| 10 |
+
},
|
| 11 |
+
"1": {
|
| 12 |
+
"content": "[BOS]",
|
| 13 |
+
"lstrip": false,
|
| 14 |
+
"normalized": false,
|
| 15 |
+
"rstrip": false,
|
| 16 |
+
"single_word": false,
|
| 17 |
+
"special": true
|
| 18 |
+
},
|
| 19 |
+
"2": {
|
| 20 |
+
"content": "[EOS]",
|
| 21 |
+
"lstrip": false,
|
| 22 |
+
"normalized": false,
|
| 23 |
+
"rstrip": false,
|
| 24 |
+
"single_word": false,
|
| 25 |
+
"special": true
|
| 26 |
+
},
|
| 27 |
+
"3": {
|
| 28 |
+
"content": "[UNK]",
|
| 29 |
+
"lstrip": false,
|
| 30 |
+
"normalized": false,
|
| 31 |
+
"rstrip": false,
|
| 32 |
+
"single_word": false,
|
| 33 |
+
"special": true
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
"auto_map": {
|
| 37 |
+
"AutoTokenizer": [
|
| 38 |
+
"tokenizer.ChessTokenizer",
|
| 39 |
+
null
|
| 40 |
+
]
|
| 41 |
+
},
|
| 42 |
+
"bos_token": "[BOS]",
|
| 43 |
+
"clean_up_tokenization_spaces": false,
|
| 44 |
+
"eos_token": "[EOS]",
|
| 45 |
+
"extra_special_tokens": {},
|
| 46 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 47 |
+
"pad_token": "[PAD]",
|
| 48 |
+
"tokenizer_class": "ChessTokenizer",
|
| 49 |
+
"unk_token": "[UNK]"
|
| 50 |
+
}
|
vocab.json
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"[PAD]": 0,
|
| 3 |
+
"[BOS]": 1,
|
| 4 |
+
"[EOS]": 2,
|
| 5 |
+
"[UNK]": 3,
|
| 6 |
+
"p": 4,
|
| 7 |
+
"n": 5,
|
| 8 |
+
"b": 6,
|
| 9 |
+
"r": 7,
|
| 10 |
+
"q": 8,
|
| 11 |
+
"k": 9,
|
| 12 |
+
"p_q": 10,
|
| 13 |
+
"p_r": 11,
|
| 14 |
+
"p_b": 12,
|
| 15 |
+
"p_n": 13,
|
| 16 |
+
"a1": 14,
|
| 17 |
+
"a2": 15,
|
| 18 |
+
"a3": 16,
|
| 19 |
+
"a4": 17,
|
| 20 |
+
"a5": 18,
|
| 21 |
+
"a6": 19,
|
| 22 |
+
"a7": 20,
|
| 23 |
+
"a8": 21,
|
| 24 |
+
"b1": 22,
|
| 25 |
+
"b2": 23,
|
| 26 |
+
"b3": 24,
|
| 27 |
+
"b4": 25,
|
| 28 |
+
"b5": 26,
|
| 29 |
+
"b6": 27,
|
| 30 |
+
"b7": 28,
|
| 31 |
+
"b8": 29,
|
| 32 |
+
"c1": 30,
|
| 33 |
+
"c2": 31,
|
| 34 |
+
"c3": 32,
|
| 35 |
+
"c4": 33,
|
| 36 |
+
"c5": 34,
|
| 37 |
+
"c6": 35,
|
| 38 |
+
"c7": 36,
|
| 39 |
+
"c8": 37,
|
| 40 |
+
"d1": 38,
|
| 41 |
+
"d2": 39,
|
| 42 |
+
"d3": 40,
|
| 43 |
+
"d4": 41,
|
| 44 |
+
"d5": 42,
|
| 45 |
+
"d6": 43,
|
| 46 |
+
"d7": 44,
|
| 47 |
+
"d8": 45,
|
| 48 |
+
"e1": 46,
|
| 49 |
+
"e2": 47,
|
| 50 |
+
"e3": 48,
|
| 51 |
+
"e4": 49,
|
| 52 |
+
"e5": 50,
|
| 53 |
+
"e6": 51,
|
| 54 |
+
"e7": 52,
|
| 55 |
+
"e8": 53,
|
| 56 |
+
"f1": 54,
|
| 57 |
+
"f2": 55,
|
| 58 |
+
"f3": 56,
|
| 59 |
+
"f4": 57,
|
| 60 |
+
"f5": 58,
|
| 61 |
+
"f6": 59,
|
| 62 |
+
"f7": 60,
|
| 63 |
+
"f8": 61,
|
| 64 |
+
"g1": 62,
|
| 65 |
+
"g2": 63,
|
| 66 |
+
"g3": 64,
|
| 67 |
+
"g4": 65,
|
| 68 |
+
"g5": 66,
|
| 69 |
+
"g6": 67,
|
| 70 |
+
"g7": 68,
|
| 71 |
+
"g8": 69,
|
| 72 |
+
"h1": 70,
|
| 73 |
+
"h2": 71,
|
| 74 |
+
"h3": 72,
|
| 75 |
+
"h4": 73,
|
| 76 |
+
"h5": 74,
|
| 77 |
+
"h6": 75,
|
| 78 |
+
"h7": 76,
|
| 79 |
+
"h8": 77
|
| 80 |
+
}
|