Text Generation
Transformers
Safetensors
chess_transformer
chess
llm-course
chess-challenge
custom_code
Run this model with HF Jobs
Run LLM-course/chesschess 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/chesschess. 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/chesschess 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/chesschess. 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/chesschess. 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/chesschess with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use LLM-course/chesschess with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="LLM-course/chesschess", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("LLM-course/chesschess", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use LLM-course/chesschess with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "LLM-course/chesschess" # 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/chesschess", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/LLM-course/chesschess
- SGLang
How to use LLM-course/chesschess 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/chesschess" \ --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/chesschess", "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/chesschess" \ --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/chesschess", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use LLM-course/chesschess with Docker Model Runner:
docker model run hf.co/LLM-course/chesschess
Chess Challenge submission by alexandreduplessis
Browse filesFiles changed (7)
- README.mdAdded+26
- config.jsonAdded+20
- model.safetensorsAdded+3
- special_tokens_map.jsonAdded+6
- tokenizer.pyAdded+356
- tokenizer_config.jsonAdded+50
- vocab.jsonAdded+155
1234567891011121314151617181920212223242526---library_name: transformerstags:- chess- llm-course- chess-challengelicense: mit---
# chesschess
Chess model submitted to the LLM Course Chess Challenge.
## Submission Info
- **Submitted by**: [alexandreduplessis](https://huggingface.co/alexandreduplessis)- **Parameters**: 992,436- **Organization**: LLM-course
## Model Details
- **Architecture**: Chess Transformer (GPT-style)- **Vocab size**: 153- **Embedding dim**: 128- **Layers**: 6- **Heads**: 41234567891011121314151617181920{ "architectures": [ "ChessForCausalLM" ], "bos_token_id": 1, "dropout": 0.1, "eos_token_id": 2, "layer_norm_epsilon": 1e-05, "model_type": "chess_transformer", "n_ctx": 256, "n_embd": 128, "n_head": 4, "n_inner": 350, "n_layer": 6, "pad_token_id": 0, "tie_weights": true, "torch_dtype": "float32", "transformers_version": "4.55.0", "vocab_size": 153}123version https://git-lfs.github.com/spec/v1oid sha256:27e1f99779a1cf3e3af10baf524df21e19b49515f77937d534319c5f79e7d7a2size 3976192123456{ "bos_token": "[BOS]", "eos_token": "[EOS]", "pad_token": "[PAD]", "unk_token": "[UNK]"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356"""Custom Chess Tokenizer for the Chess Challenge.
This tokenizer treats each move as a single token using the extended UCI notationfrom 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 jsonimport osfrom pathlib import Pathfrom typing import Dict, List, Optional
from transformers import PreTrainedTokenizer
import re
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]" _MOVE_RE = re.compile( r'^(?P<color>[WB])(?P<piece>[PNBRQK])(?P<from>[a-h][1-8])(?P<to>[a-h][1-8])(?P<rest>.*)$' )
_SUFFIX_MAP = { "(x)": "cap", "(+)": "check", "(+*)": "mate", "(o)": "castle_k", "(O)": "castle_q", }
_PROMO_RE = re.compile(r'=?([QRBNqrbn])') # accepts "=Q" or "q" style
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 _decompose_move(self, tok: str) -> List[str]: """ Convert e.g. 'WPe2e4(x)' -> ['WP', 'e2_f', 'e4_t', 'cap'] """ m = self._MOVE_RE.match(tok) if not m: return [self.UNK_TOKEN]
color = m.group("color") piece = m.group("piece") from_sq = m.group("from") to_sq = m.group("to") rest = m.group("rest") or ""
out = [f"{color}{piece}", f"{from_sq}_f", f"{to_sq}_t"]
for raw, mapped in self._SUFFIX_MAP.items(): if raw in rest: out.append(mapped)
# Promotion (rare depending on dataset formatting, but safe) pm = self._PROMO_RE.search(rest) if pm: p = pm.group(1).lower() if p in ("q", "r", "b", "n"): out.append(f"promo_{p}")
return out 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 _tokenize(self, text: str) -> List[str]: parts = text.strip().split() out: List[str] = [] special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
for p in parts: if p in special: out.append(p) else: out.extend(self._decompose_move(p)) return out
@classmethod def build_structured_vocab(cls) -> "ChessTokenizer": special = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
# 12 color+piece tokens cp = [f"{c}{p}" for c in ("W", "B") for p in ("P", "N", "B", "R", "Q", "K")]
files = "abcdefgh" ranks = "12345678"
from_tokens = [f"{f}{r}_f" for f in files for r in ranks] # 64 to_tokens = [f"{f}{r}_t" for f in files for r in ranks] # 64
suffix = ["cap", "check", "mate", "castle_k", "castle_q"] promo = [f"promo_{p}" for p in ("q", "r", "b", "n")]
tokens = special + cp + from_tokens + to_tokens + suffix + promo vocab = {t: i for i, t in enumerate(tokens)} return cls(vocab=vocab)
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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950{ "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 } }, "auto_map": { "AutoTokenizer": [ "tokenizer.ChessTokenizer", null ] }, "bos_token": "[BOS]", "clean_up_tokenization_spaces": false, "eos_token": "[EOS]", "extra_special_tokens": {}, "model_max_length": 1000000000000000019884624838656, "pad_token": "[PAD]", "tokenizer_class": "ChessTokenizer", "unk_token": "[UNK]"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155{ "[PAD]": 0, "[BOS]": 1, "[EOS]": 2, "[UNK]": 3, "WP": 4, "WN": 5, "WB": 6, "WR": 7, "WQ": 8, "WK": 9, "BP": 10, "BN": 11, "BB": 12, "BR": 13, "BQ": 14, "BK": 15, "a1_f": 16, "a2_f": 17, "a3_f": 18, "a4_f": 19, "a5_f": 20, "a6_f": 21, "a7_f": 22, "a8_f": 23, "b1_f": 24, "b2_f": 25, "b3_f": 26, "b4_f": 27, "b5_f": 28, "b6_f": 29, "b7_f": 30, "b8_f": 31, "c1_f": 32, "c2_f": 33, "c3_f": 34, "c4_f": 35, "c5_f": 36, "c6_f": 37, "c7_f": 38, "c8_f": 39, "d1_f": 40, "d2_f": 41, "d3_f": 42, "d4_f": 43, "d5_f": 44, "d6_f": 45, "d7_f": 46, "d8_f": 47, "e1_f": 48, "e2_f": 49, "e3_f": 50, "e4_f": 51, "e5_f": 52, "e6_f": 53, "e7_f": 54, "e8_f": 55, "f1_f": 56, "f2_f": 57, "f3_f": 58, "f4_f": 59, "f5_f": 60, "f6_f": 61, "f7_f": 62, "f8_f": 63, "g1_f": 64, "g2_f": 65, "g3_f": 66, "g4_f": 67, "g5_f": 68, "g6_f": 69, "g7_f": 70, "g8_f": 71, "h1_f": 72, "h2_f": 73, "h3_f": 74, "h4_f": 75, "h5_f": 76, "h6_f": 77, "h7_f": 78, "h8_f": 79, "a1_t": 80, "a2_t": 81, "a3_t": 82, "a4_t": 83, "a5_t": 84, "a6_t": 85, "a7_t": 86, "a8_t": 87, "b1_t": 88, "b2_t": 89, "b3_t": 90, "b4_t": 91, "b5_t": 92, "b6_t": 93, "b7_t": 94, "b8_t": 95, "c1_t": 96, "c2_t": 97, "c3_t": 98, "c4_t": 99, "c5_t": 100, "c6_t": 101, "c7_t": 102, "c8_t": 103, "d1_t": 104, "d2_t": 105, "d3_t": 106, "d4_t": 107, "d5_t": 108, "d6_t": 109, "d7_t": 110, "d8_t": 111, "e1_t": 112, "e2_t": 113, "e3_t": 114, "e4_t": 115, "e5_t": 116, "e6_t": 117, "e7_t": 118, "e8_t": 119, "f1_t": 120, "f2_t": 121, "f3_t": 122, "f4_t": 123, "f5_t": 124, "f6_t": 125, "f7_t": 126, "f8_t": 127, "g1_t": 128, "g2_t": 129, "g3_t": 130, "g4_t": 131, "g5_t": 132, "g6_t": 133, "g7_t": 134, "g8_t": 135, "h1_t": 136, "h2_t": 137, "h3_t": 138, "h4_t": 139, "h5_t": 140, "h6_t": 141, "h7_t": 142, "h8_t": 143, "cap": 144, "check": 145, "mate": 146, "castle_k": 147, "castle_q": 148, "promo_q": 149, "promo_r": 150, "promo_b": 151, "promo_n": 152}README.mdAdded+26
config.jsonAdded+20
model.safetensorsAdded+3
special_tokens_map.jsonAdded+6
tokenizer.pyAdded+356
tokenizer_config.jsonAdded+50
vocab.jsonAdded+155