Run this model with HF Jobs
Run LLM-course/chess-ooooooooo-9 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/LLM-course/chess-ooooooooo-9. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/LLM-course/chess-ooooooooo-9 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/LLM-course/chess-ooooooooo-9. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/LLM-course/chess-ooooooooo-9. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use LLM-course/chess-ooooooooo-9 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use LLM-course/chess-ooooooooo-9 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="LLM-course/chess-ooooooooo-9")# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("LLM-course/chess-ooooooooo-9", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use LLM-course/chess-ooooooooo-9 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "LLM-course/chess-ooooooooo-9" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "LLM-course/chess-ooooooooo-9", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/LLM-course/chess-ooooooooo-9
- SGLang
How to use LLM-course/chess-ooooooooo-9 with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "LLM-course/chess-ooooooooo-9" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "LLM-course/chess-ooooooooo-9", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "LLM-course/chess-ooooooooo-9" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "LLM-course/chess-ooooooooo-9", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use LLM-course/chess-ooooooooo-9 with Docker Model Runner:
docker model run hf.co/LLM-course/chess-ooooooooo-9
Add chess model submission v9
Browse filesFiles changed (8)
- README.mdAdded+56
- config.jsonAdded+21
- model.pyAdded+436
- model.safetensorsAdded+3
- special_tokens_map.jsonAdded+6
- tokenizer.pyAdded+278
- tokenizer_config.jsonAdded+53
- vocab.jsonAdded+87
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556---
library_name: transformers
tags:
- chess
- llm-course
- chess-challenge
license: mit
---
# chess-ooooooooo-9
A chess transformer model trained for the LLM Course Chess Challenge.
## Model Architecture
This model uses a GPT-style transformer architecture optimized for chess move prediction:
- **Parameters**: 948,352 (0.95M)
- **Vocabulary size**: 85
- **Embedding dimension**: 128
- **Number of layers**: 6
- **Attention heads**: 4
- **Feed-forward dimension**: 320
- **Context length**: 256
- **Dropout**: 0.109
## Training
The model was trained on a subset of the Lichess 2025 dataset, focusing on learning valid chess move sequences. The architecture was carefully tuned to stay within the 1M parameter constraint while maintaining reasonable performance.
## Usage
```python
from transformers import AutoModelForCausalLM
from src.tokenizer import ChessTokenizer
model = AutoModelForCausalLM.from_pretrained(
"LLM-course/chess-ooooooooo-9",
trust_remote_code=True
)
tokenizer = ChessTokenizer.from_pretrained(
"LLM-course/chess-ooooooooo-9",
trust_remote_code=True
)
# Generate moves
input_text = "[BOS] WPe2e4"
input_ids = tokenizer.encode(input_text)
outputs = model.generate(input_ids, max_length=50)
predicted_moves = tokenizer.decode(outputs[0])
```
## Submission
Submitted by [etienneLefranc](https://huggingface.co/etienneLefranc) for the LLM Course Chess Challenge.
Version 9 of chess-ooooooooo.123456789101112131415161718192021{
"architectures": [
"ChessForCausalLM"
],
"bos_token_id": 1,
"dropout": 0.10900000000000001,
"dtype": "float32",
"eos_token_id": 2,
"layer_norm_epsilon": 1e-05,
"model_type": "chess_transformer",
"n_ctx": 256,
"n_embd": 128,
"n_head": 4,
"n_inner": 320,
"n_layer": 6,
"pad_token_id": 0,
"tie_weights": false,
"tie_word_embeddings": false,
"transformers_version": "4.57.6",
"vocab_size": 85
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436"""
Chess Transformer Model for the Chess Challenge.
This module provides a simple GPT-style transformer architecture
designed to fit within the 1M parameter constraint.
Key components:
- ChessConfig: Configuration class for model hyperparameters
- ChessForCausalLM: The main model class for next-move prediction
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PretrainedConfig, PreTrainedModel
from transformers.modeling_outputs import CausalLMOutputWithPast
class ChessConfig(PretrainedConfig):
"""
Configuration class for the Chess Transformer model.
This configuration is designed for a ~1M parameter model.
Students can adjust these values to explore different architectures.
Parameter budget breakdown (with default values):
- Embeddings (vocab): 1200 x 128 = 153,600
- Position Embeddings: 256 x 128 = 32,768
- Transformer Layers: 6 x ~120,000 = ~720,000
- LM Head (with weight tying): 0 (shared with embeddings)
- Total: ~906,000 parameters
Attributes:
vocab_size: Size of the vocabulary (number of unique moves).
n_embd: Embedding dimension (d_model).
n_layer: Number of transformer layers.
n_head: Number of attention heads.
n_ctx: Maximum sequence length (context window).
n_inner: Feed-forward inner dimension (default: 3 * n_embd).
dropout: Dropout probability.
layer_norm_epsilon: Epsilon for layer normalization.
tie_weights: Whether to tie embedding and output weights.
"""
model_type = "chess_transformer"
def __init__(
self,
vocab_size: int = 1200,
n_embd: int = 128,
n_layer: int = 6,
n_head: int = 4,
n_ctx: int = 256,
n_inner: Optional[int] = None,
dropout: float = 0.1,
layer_norm_epsilon: float = 1e-5,
tie_weights: bool = True,
pad_token_id: int = 0,
bos_token_id: int = 1,
eos_token_id: int = 2,
**kwargs,
):
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
**kwargs,
)
self.vocab_size = vocab_size
self.n_embd = n_embd
self.n_layer = n_layer
self.n_head = n_head
self.n_ctx = n_ctx
self.n_inner = n_inner if n_inner is not None else 3 * n_embd # Reduced from 4x to 3x
self.dropout = dropout
self.layer_norm_epsilon = layer_norm_epsilon
self.tie_weights = tie_weights
# Inform HF base class about tying behavior
self.tie_word_embeddings = bool(tie_weights)
class MultiHeadAttention(nn.Module):
"""
Multi-head self-attention module.
This is a standard scaled dot-product attention implementation
with causal masking for autoregressive generation.
"""
def __init__(self, config: ChessConfig):
super().__init__()
assert config.n_embd % config.n_head == 0, \
f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
self.n_head = config.n_head
self.n_embd = config.n_embd
self.head_dim = config.n_embd // config.n_head
# Combined QKV projection for efficiency
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
self.dropout = nn.Dropout(config.dropout)
# Causal mask (will be created on first forward pass)
self.register_buffer(
"bias",
torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
1, 1, config.n_ctx, config.n_ctx
),
persistent=False,
)
def forward(
self,
x: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
batch_size, seq_len, _ = x.size()
# Compute Q, K, V
qkv = self.c_attn(x)
q, k, v = qkv.split(self.n_embd, dim=2)
# Reshape for multi-head attention
q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
# Scaled dot-product attention
attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
# Apply causal mask
causal_mask = self.bias[:, :, :seq_len, :seq_len]
attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
# Apply attention mask (for padding)
if attention_mask is not None:
# attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
attn_weights = F.softmax(attn_weights, dim=-1)
attn_weights = self.dropout(attn_weights)
# Apply attention to values
attn_output = torch.matmul(attn_weights, v)
# Reshape back
attn_output = attn_output.transpose(1, 2).contiguous().view(
batch_size, seq_len, self.n_embd
)
# Output projection
attn_output = self.c_proj(attn_output)
return attn_output
class FeedForward(nn.Module):
"""
Feed-forward network (MLP) module.
Standard two-layer MLP with GELU activation.
"""
def __init__(self, config: ChessConfig):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, config.n_inner)
self.c_proj = nn.Linear(config.n_inner, config.n_embd)
self.dropout = nn.Dropout(config.dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.c_fc(x)
x = F.gelu(x)
x = self.c_proj(x)
x = self.dropout(x)
return x
class TransformerBlock(nn.Module):
"""
A single transformer block with attention and feed-forward layers.
Uses pre-normalization (LayerNorm before attention/FFN) for better
training stability.
"""
def __init__(self, config: ChessConfig):
super().__init__()
self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
self.attn = MultiHeadAttention(config)
self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
self.mlp = FeedForward(config)
def forward(
self,
x: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
# Pre-norm attention
x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
# Pre-norm FFN
x = x + self.mlp(self.ln_2(x))
return x
class ChessForCausalLM(PreTrainedModel):
"""
Chess Transformer for Causal Language Modeling (next-move prediction).
This model is designed to predict the next chess move given a sequence
of previous moves. It uses a GPT-style architecture with:
- Token embeddings for chess moves
- Learned positional embeddings
- Stacked transformer blocks
- Linear head for next-token prediction
The model supports weight tying between the embedding layer and the
output projection to save parameters.
Example:
>>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
>>> model = ChessForCausalLM(config)
>>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
>>> outputs = model(**inputs)
>>> next_move_logits = outputs.logits[:, -1, :]
"""
config_class = ChessConfig
base_model_prefix = "transformer"
supports_gradient_checkpointing = True
# Suppress missing-key warning for tied lm_head when loading
keys_to_ignore_on_load_missing = ["lm_head.weight"]
def __init__(self, config: ChessConfig):
super().__init__(config)
# Token and position embeddings
self.wte = nn.Embedding(config.vocab_size, config.n_embd)
self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
self.drop = nn.Dropout(config.dropout)
# Transformer blocks
self.h = nn.ModuleList([
TransformerBlock(config) for _ in range(config.n_layer)
])
# Final layer norm
self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
# Output head
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
# Initialize weights first
self.post_init()
# Tie weights if configured (after post_init)
# transformers will handle _tied_weights_keys automatically via tie_weights()
if config.tie_weights:
self.tie_weights()
def get_input_embeddings(self) -> nn.Module:
return self.wte
def set_input_embeddings(self, new_embeddings: nn.Module):
self.wte = new_embeddings
if getattr(self.config, "tie_weights", False):
self.tie_weights()
def get_output_embeddings(self) -> nn.Module:
return self.lm_head
def set_output_embeddings(self, new_embeddings: nn.Module):
self.lm_head = new_embeddings
def tie_weights(self, recompute_mapping=False, **kwargs):
# Tie weights between embedding and output layers
if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
# Directly tie the weights
self.lm_head.weight = self.wte.weight
def _init_weights(self, module: nn.Module):
"""Initialize weights following GPT-2 style."""
if isinstance(module, nn.Linear):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
elif isinstance(module, nn.LayerNorm):
torch.nn.init.ones_(module.weight)
torch.nn.init.zeros_(module.bias)
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
labels: Optional[torch.LongTensor] = None,
return_dict: Optional[bool] = None,
**kwargs,
) -> Union[Tuple, CausalLMOutputWithPast]:
"""
Forward pass of the model.
Args:
input_ids: Token IDs of shape (batch_size, seq_len).
attention_mask: Attention mask of shape (batch_size, seq_len).
position_ids: Position IDs of shape (batch_size, seq_len).
labels: Labels for language modeling loss.
return_dict: Whether to return a ModelOutput object.
Returns:
CausalLMOutputWithPast containing loss (if labels provided) and logits.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
batch_size, seq_len = input_ids.size()
device = input_ids.device
# Create position IDs if not provided
if position_ids is None:
position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
# Get embeddings
token_embeds = self.wte(input_ids)
position_embeds = self.wpe(position_ids)
hidden_states = self.drop(token_embeds + position_embeds)
# Pass through transformer blocks
for block in self.h:
hidden_states = block(hidden_states, attention_mask=attention_mask)
# Final layer norm
hidden_states = self.ln_f(hidden_states)
# Get logits
logits = self.lm_head(hidden_states)
# Compute loss if labels are provided
loss = None
if labels is not None:
# Shift logits and labels for next-token prediction
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten for cross-entropy
loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
# loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
loss = loss_fct(
shift_logits.view(-1, shift_logits.size(-1)),
shift_labels.view(-1),
)
if not return_dict:
output = (logits,)
return ((loss,) + output) if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=None,
hidden_states=None,
attentions=None,
)
@torch.no_grad()
def generate_move(
self,
input_ids: torch.LongTensor,
temperature: float = 1.0,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
) -> int:
"""
Generate the next move given a sequence of moves.
Args:
input_ids: Token IDs of shape (1, seq_len).
temperature: Sampling temperature (1.0 = no change).
top_k: If set, only sample from top k tokens.
top_p: If set, use nucleus sampling with this threshold.
Returns:
The token ID of the predicted next move.
"""
self.eval()
# Get logits for the last position
outputs = self(input_ids)
logits = outputs.logits[:, -1, :] / temperature
# Apply top-k filtering
if top_k is not None:
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
logits[indices_to_remove] = float("-inf")
# Apply top-p (nucleus) filtering
if top_p is not None:
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
# Remove tokens with cumulative probability above the threshold
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
indices_to_remove = sorted_indices_to_remove.scatter(
dim=-1, index=sorted_indices, src=sorted_indices_to_remove
)
logits[indices_to_remove] = float("-inf")
# Sample from the distribution
probs = F.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
return next_token.item()
# Register the model with Auto classes for easy loading
from transformers import AutoConfig, AutoModelForCausalLM
AutoConfig.register("chess_transformer", ChessConfig)
AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)123version https://git-lfs.github.com/spec/v1oid sha256:eec45323a73f8c60461b30c496cb3326e229e97dfb328f562bfc121581b24068size 3799936123456{ "bos_token": "[BOS]", "eos_token": "[EOS]", "pad_token": "[PAD]", "unk_token": "[UNK]"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278"""
Custom Chess Tokenizer for the Chess Challenge.
This tokenizer treats each move as a single token using the extended UCI notation
from the Lichess dataset (e.g., WPe2e4, BNg8f6).
The dataset format uses:
- W/B prefix for White/Black
- Piece letter: P=Pawn, N=Knight, B=Bishop, R=Rook, Q=Queen, K=King
- Source and destination squares (e.g., e2e4)
- Special suffixes: (x)=capture, (+)=check, (+*)=checkmate, (o)/(O)=castling
"""
from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Dict, List, Optional
from transformers import PreTrainedTokenizer
class ChessTokenizer(PreTrainedTokenizer):
"""
A custom tokenizer for chess moves using extended UCI notation.
This tokenizer maps each possible chess move to a unique token ID.
The vocabulary is built from the training dataset to ensure all moves
encountered during training have a corresponding token.
Example:
>>> tokenizer = ChessTokenizer()
>>> tokenizer.encode("WPe2e4 BPe7e5")
[1, 42, 87, 2] # [BOS, e2e4, e7e5, EOS]
"""
model_input_names = ["input_ids", "attention_mask"]
vocab_files_names = {"vocab_file": "vocab.json"}
# Special tokens
PAD_TOKEN = "[PAD]"
BOS_TOKEN = "[BOS]"
EOS_TOKEN = "[EOS]"
UNK_TOKEN = "[UNK]"
def __init__(
self,
vocab_file: Optional[str] = None,
vocab: Optional[Dict[str, int]] = None,
**kwargs,
):
"""
Initialize the chess tokenizer.
Args:
vocab_file: Path to a JSON file containing the vocabulary mapping.
vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
**kwargs: Additional arguments passed to PreTrainedTokenizer.
"""
# Initialize special tokens
self._pad_token = self.PAD_TOKEN
self._bos_token = self.BOS_TOKEN
self._eos_token = self.EOS_TOKEN
self._unk_token = self.UNK_TOKEN
# Remove any duplicate special-token entries passed through kwargs
# to avoid "multiple values for keyword" errors when loading from disk.
kwargs.pop("pad_token", None)
kwargs.pop("bos_token", None)
kwargs.pop("eos_token", None)
kwargs.pop("unk_token", None)
# Load or create vocabulary
if vocab is not None:
self._vocab = vocab
elif vocab_file is not None and os.path.exists(vocab_file):
with open(vocab_file, "r", encoding="utf-8") as f:
self._vocab = json.load(f)
else:
# Create a minimal vocabulary with just special tokens
# The full vocabulary should be built from the dataset
self._vocab = self._create_default_vocab()
# Create reverse mapping
self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
# Call parent init AFTER setting up vocab
super().__init__(
pad_token=self._pad_token,
bos_token=self._bos_token,
eos_token=self._eos_token,
unk_token=self._unk_token,
**kwargs,
)
def _create_default_vocab(self) -> Dict[str, int]:
"""
Create a minimal default vocabulary with just special tokens.
For the full vocabulary, use `build_vocab_from_dataset()`.
This minimal vocab is just a placeholder - you should build from data.
"""
special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
vocab = {token: idx for idx, token in enumerate(special_tokens)}
return vocab
@classmethod
def build_vocab_from_iterator(
cls,
iterator,
min_frequency: int = 1,
) -> "ChessTokenizer":
"""
Build a tokenizer vocabulary from an iterator of game strings.
Args:
iterator: An iterator yielding game strings (space-separated moves).
min_frequency: Minimum frequency for a token to be included.
Returns:
A ChessTokenizer with the built vocabulary.
"""
from collections import Counter
token_counts = Counter()
for game in iterator:
moves = game.strip().split()
token_counts.update(moves)
# Filter by frequency
tokens = [
token for token, count in token_counts.items()
if count >= min_frequency
]
# Sort for reproducibility
tokens = sorted(tokens)
# Build vocabulary
special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
return cls(vocab=vocab)
@classmethod
def build_vocab_from_dataset(
cls,
dataset_name: str = "dlouapre/lichess_2025-01_1M",
split: str = "train",
column: str = "text",
min_frequency: int = 500,
max_samples: Optional[int] = 100000,
) -> "ChessTokenizer":
"""
Build a tokenizer vocabulary from a Hugging Face dataset.
Args:
dataset_name: Name of the dataset on Hugging Face Hub.
split: Dataset split to use.
column: Column containing the game strings.
min_frequency: Minimum frequency for a token to be included (default: 500).
max_samples: Maximum number of samples to process (default: 100k).
Returns:
A ChessTokenizer with the built vocabulary.
"""
from datasets import load_dataset
dataset = load_dataset(dataset_name, split=split)
if max_samples is not None:
dataset = dataset.select(range(min(max_samples, len(dataset))))
def game_iterator():
for example in dataset:
yield example[column]
return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
@property
def vocab_size(self) -> int:
"""Return the size of the vocabulary."""
return len(self._vocab)
def get_vocab(self) -> Dict[str, int]:
"""Return the vocabulary as a dictionary."""
return dict(self._vocab)
def _tokenize(self, text: str) -> List[str]:
"""
Tokenize a string of moves into a list of tokens.
Args:
text: A string of space-separated moves.
Returns:
List of move tokens.
"""
return text.strip().split()
def _convert_token_to_id(self, token: str) -> int:
"""Convert a token to its ID."""
return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
def _convert_id_to_token(self, index: int) -> str:
"""Convert an ID to its token."""
return self._ids_to_tokens.get(index, self.UNK_TOKEN)
def convert_tokens_to_string(self, tokens: List[str]) -> str:
"""Convert a list of tokens back to a string."""
# Filter out special tokens for cleaner output
special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
return " ".join(t for t in tokens if t not in special)
def save_vocabulary(
self,
save_directory: str,
filename_prefix: Optional[str] = None,
) -> tuple:
"""
Save the vocabulary to a JSON file.
Args:
save_directory: Directory to save the vocabulary.
filename_prefix: Optional prefix for the filename.
Returns:
Tuple containing the path to the saved vocabulary file.
"""
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, indent=2)
return (vocab_file,)
def count_vocab_from_dataset(
dataset_name: str = "dlouapre/lichess_2025-01_1M",
split: str = "train",
column: str = "text",
max_samples: Optional[int] = 10000,
) -> Dict[str, int]:
"""
Count token frequencies in a dataset (useful for vocabulary analysis).
Args:
dataset_name: Name of the dataset on Hugging Face Hub.
split: Dataset split to use.
column: Column containing the game strings.
max_samples: Maximum number of samples to process.
Returns:
Dictionary mapping tokens to their frequencies.
"""
from collections import Counter
from datasets import load_dataset
dataset = load_dataset(dataset_name, split=split)
if max_samples is not None:
dataset = dataset.select(range(min(max_samples, len(dataset))))
token_counts = Counter()
for example in dataset:
moves = example[column].strip().split()
token_counts.update(moves)
return dict(token_counts)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{
"added_tokens_decoder": {
"0": {
"content": "[PAD]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"1": {
"content": "[BOS]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"2": {
"content": "[EOS]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"3": {
"content": "[UNK]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
}
},
"additional_special_tokens": null,
"auto_map": {
"AutoTokenizer": [
"tokenizer.ChessTokenizer",
null
]
},
"backend": "custom",
"bos_token": "[BOS]",
"clean_up_tokenization_spaces": false,
"eos_token": "[EOS]",
"is_local": true,
"model_max_length": 1000000000000000019884624838656,
"model_specific_special_tokens": {},
"pad_token": "[PAD]",
"tokenizer_class": "ChessTokenizer",
"unk_token": "[UNK]"
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687{
"[PAD]": 0,
"[BOS]": 1,
"[EOS]": 2,
"[UNK]": 3,
"[W]": 4,
"[B]": 5,
"[P]": 6,
"[N]": 7,
"[BISHOP]": 8,
"[R]": 9,
"[Q]": 10,
"[K]": 11,
"[a1]": 12,
"[b1]": 13,
"[c1]": 14,
"[d1]": 15,
"[e1]": 16,
"[f1]": 17,
"[g1]": 18,
"[h1]": 19,
"[a2]": 20,
"[b2]": 21,
"[c2]": 22,
"[d2]": 23,
"[e2]": 24,
"[f2]": 25,
"[g2]": 26,
"[h2]": 27,
"[a3]": 28,
"[b3]": 29,
"[c3]": 30,
"[d3]": 31,
"[e3]": 32,
"[f3]": 33,
"[g3]": 34,
"[h3]": 35,
"[a4]": 36,
"[b4]": 37,
"[c4]": 38,
"[d4]": 39,
"[e4]": 40,
"[f4]": 41,
"[g4]": 42,
"[h4]": 43,
"[a5]": 44,
"[b5]": 45,
"[c5]": 46,
"[d5]": 47,
"[e5]": 48,
"[f5]": 49,
"[g5]": 50,
"[h5]": 51,
"[a6]": 52,
"[b6]": 53,
"[c6]": 54,
"[d6]": 55,
"[e6]": 56,
"[f6]": 57,
"[g6]": 58,
"[h6]": 59,
"[a7]": 60,
"[b7]": 61,
"[c7]": 62,
"[d7]": 63,
"[e7]": 64,
"[f7]": 65,
"[g7]": 66,
"[h7]": 67,
"[a8]": 68,
"[b8]": 69,
"[c8]": 70,
"[d8]": 71,
"[e8]": 72,
"[f8]": 73,
"[g8]": 74,
"[h8]": 75,
"[x]": 76,
"[+]": 77,
"[#]": 78,
"[O-O]": 79,
"[O-O-O]": 80,
"[prom_Q]": 81,
"[prom_R]": 82,
"[prom_B]": 83,
"[prom_N]": 84
}README.mdAdded+56
config.jsonAdded+21
model.pyAdded+436
model.safetensorsAdded+3
special_tokens_map.jsonAdded+6
tokenizer.pyAdded+278
tokenizer_config.jsonAdded+53
vocab.jsonAdded+87