"""The model player: lets any language model sit the chess exam. Every model gets the same fixed prompt (chess_eval/prompts/move_v1.txt), the same answer reading rule (chess_eval/prompt.py) and the same settings: greedy answers (no randomness), thinking off unless asked, one try per move. Two ways to reach a model ("backend"): 1. transformers: load the model on this machine's GPU (for example on a Kaggle notebook). Optionally add an adapter (LoRA) on top. python -m chess_eval.score --player model \\ --player-arg model=google/gemma-4-E2B-it python -m chess_eval.score --player model \\ --player-arg model=google/gemma-4-E2B-it \\ --player-arg adapter=/kaggle/input/atal-pilot-adapter 2. llamacpp: send the prompt as exact token numbers to a llama.cpp server (its /completion address). The prompt is built on this machine with the model's official tokenizer and chat template, so the model sees exactly the same tokens as in training and in the transformers exam. python -m chess_eval.score --player model \\ --player-arg backend=llamacpp \\ --player-arg base_url=http://127.0.0.1:8080 \\ --player-arg tokenizer=sarvamai/sarvam-30b \\ --player-arg reply_start=empty_thinking 3. openai: send the prompt to a running model server that speaks the common "chat completions" format (vLLM, SGLang, llama.cpp server, or a paid API later for Test 3). python -m chess_eval.score --player model \\ --player-arg backend=openai \\ --player-arg base_url=http://localhost:8000/v1 \\ --player-arg model=sarvamai/sarvam-30b If the server needs a key, put it in the ATAL_MODEL_API_KEY environment variable. Never write a key in a file in git. Settings (all passed as --player-arg key=value): model Hugging Face model name or a local folder (required) backend "transformers" (default), "llamacpp" or "openai" adapter adapter folder to add on top (transformers only) revision exact model version on Hugging Face (transformers only) name label for the report (default: made from model + adapter) thinking "off" (default) or "on" reply_start "" (default) or "empty_thinking": start the model's reply with the empty thinking block its own chat template writes for a reply with no thinking (Sarvam-30B: "\\n"). See reply_start_text(). tokenizer tokenizer name or folder (llamacpp backend; default: model) max_new_tokens longest reply we wait for (default 32 for prompt move_v1, 96 for move_v2's four-line answer, or 2048 if thinking is on) prompt_version "move_v1" (default) or "move_v2" (recipe v2: board facts in the prompt, four-line answer, the move is read from the "Move:" line), or "move_v3" (recipe v3: candidate moves with winning chances, then "Move:") dtype "auto" (default), "bfloat16", "float16" or "float32" load_in_4bit "1" to load the model squeezed to 4 bits (needs bitsandbytes) trust_remote_code "1" for models that need their own code (Sarvam-30B) base_url server address (openai backend) log file to save every prompt fingerprint, raw reply and move progress_every print a progress line every N moves (default 0 = never) """ import hashlib import json import os import re import time import urllib.error import urllib.request from typing import Dict, List, Optional from .prompt import (PROMPT_VERSION, PROMPT_VERSIONS, clean_reply, load_template, read_move, render_prompt, template_sha256) THINKING_CHOICES = ("off", "on") # Longest answer we wait for with thinking off. A v2 answer is about 40 to 60 tokens, # a v3 answer about 41 (measured with Gemma 4's and Sarvam's real tokenizers). # A v4 answer is one winning chance per legal move (about 3 tokens each, at most 64 moves), then the # Move line: about 200 tokens at most, so 224 never cuts off a real answer. DEFAULT_MAX_NEW_TOKENS = {"move_v1": 32, "move_v2": 96, "move_v3": 64, "move_v4": 224} ANSWER_RULES = { "move_v1": "first move-shaped text in the final answer (chess_eval/prompt.py)", "move_v2": "first word of the first 'Move:' line of the final answer; no readable Move line = " "no move (chess_eval/recipe_v2.py)", "move_v3": "first word of the first 'Move:' line of the final answer; no readable Move line = " "no move (the v2 rule, chess_eval/recipe_v2.py)", "move_v4": "first word of the first 'Move:' line of the final answer; no readable Move line = " "no move (the v2 rule, chess_eval/recipe_v2.py)", } def _flag(value) -> bool: return str(value).strip().lower() in ("1", "true", "yes", "on") def safe_name(text: str) -> str: """A label that is safe as a file name: "google/gemma-4-E2B-it" becomes "gemma-4-E2B-it".""" text = text.rstrip("/").split("/")[-1] return re.sub(r"[^A-Za-z0-9._-]+", "-", text).strip("-") or "model" def template_kwargs(thinking: str) -> Dict[str, object]: """Extra switches for the model's chat template. Different model families use different names for the same switch. Templates ignore names they do not know, so we send all of them: - enable_thinking: Sarvam-30B, Gemma 4 and others - reasoning_effort: gpt-oss (it always thinks a little; "low" is its least) """ on = thinking == "on" return {"enable_thinking": on, "reasoning_effort": "medium" if on else "low"} REPLY_STARTS = ("", "empty_thinking") def reply_start_text(tokenizer, reply_start: str, thinking: str = "off") -> str: """The text that starts the model's reply, before it writes anything. "" : nothing (the model starts its reply itself). Used for Gemma 4. "empty_thinking": the empty thinking block, exactly as the model's own chat template writes it for a reply with no thinking. Found by asking the template to write a reply holding a marker, and taking the text before the marker. For Sarvam-30B this is "\\n". Why: Sarvam's official "thinking off" switch (enable_thinking=False, which adds <|nothink|> to the user turn) did not stop Sarvam-30B from thinking in the first Kaggle exam: 2,498 of 2,500 replies began "We need to analyze..." and were cut off. Starting the reply with the empty thinking block, as Sarvam's template writes every reply without thinking, leaves the model only the answer to write. Both switches are used together. """ if reply_start == "": return "" if reply_start != "empty_thinking": raise ValueError(f"reply_start must be one of {REPLY_STARTS}, got {reply_start!r}") if thinking != "off": raise ValueError("reply_start=empty_thinking only makes sense with thinking off") marker = "ATALMARKER" user = [{"role": "user", "content": "x"}] kwargs = template_kwargs(thinking) prompt = tokenizer.apply_chat_template(user, add_generation_prompt=True, tokenize=False, **kwargs) full = tokenizer.apply_chat_template(user + [{"role": "assistant", "content": marker}], tokenize=False, **kwargs) if not full.startswith(prompt) or marker not in full: raise ValueError("The chat template writes the prompt differently when a reply follows; " "cannot find how it starts a reply.") start = full[len(prompt):full.index(marker)] if start.strip().replace(" ", "") != "": raise ValueError(f"This model's template does not start a reply with an empty thinking " f"block (it writes {start!r}). Do not use reply_start=empty_thinking.") return start def prompt_token_ids(tokenizer, messages: List[dict], thinking: str = "off", reply_start: str = "") -> List[int]: """The exact token numbers the model sees, in every exam and in training. The chat template's prompt (as the transformers exam always made it), then the reply start, if any, as its own tokens.""" kwargs = template_kwargs(thinking) encoded = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_dict=True, **kwargs) ids = list(encoded["input_ids"]) if ids and isinstance(ids[0], list): # some tokenizers return a batch of one ids = ids[0] start = reply_start_text(tokenizer, reply_start, thinking) if start: ids += list(tokenizer(start, add_special_tokens=False)["input_ids"]) return ids def greedy_reply(model, tokenizer, ids: List[int], max_new_tokens: int) -> str: """Greedy answer (no randomness) for one prompt, as text with special tokens kept.""" import torch device = next(model.parameters()).device input_ids = torch.tensor([ids], device=device) with torch.no_grad(): output = model.generate(input_ids=input_ids, attention_mask=torch.ones_like(input_ids), max_new_tokens=max_new_tokens, do_sample=False, top_p=None, top_k=None, temperature=None, pad_token_id=tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id) # Keep special tokens: gpt-oss marks its final answer with them. return tokenizer.decode(output[0][len(ids):], skip_special_tokens=False) class ModelPlayer: """A chess player backed by a language model. See the top of this file.""" def __init__(self, model: str, backend: str = "transformers", adapter: Optional[str] = None, name: Optional[str] = None, thinking: str = "off", max_new_tokens: Optional[str] = None, dtype: str = "auto", load_in_4bit: str = "0", trust_remote_code: str = "0", base_url: str = "http://localhost:8000/v1", log: Optional[str] = None, progress_every: str = "0", prompt_version: str = PROMPT_VERSION, revision: Optional[str] = None, reply_start: str = "", tokenizer: Optional[str] = None, generator=None): if thinking not in THINKING_CHOICES: raise ValueError(f"thinking must be one of {THINKING_CHOICES}, got {thinking!r}") self.model = model self.backend_name = backend self.adapter = adapter or None self.revision = revision or None self.thinking = thinking if reply_start not in REPLY_STARTS: raise ValueError(f"reply_start must be one of {REPLY_STARTS}, got {reply_start!r}") self.reply_start = reply_start if prompt_version not in PROMPT_VERSIONS: raise ValueError(f"prompt_version must be one of {PROMPT_VERSIONS}, got {prompt_version!r}") self.max_new_tokens = int(max_new_tokens) if max_new_tokens else ( 2048 if thinking == "on" else DEFAULT_MAX_NEW_TOKENS[prompt_version]) self.prompt_version = prompt_version self.last_reply: Optional[str] = None # the raw reply to the latest move() call self._template = load_template(prompt_version) self.name = name or (safe_name(model) + (f"+{safe_name(self.adapter)}" if self.adapter else "-base")) self.stats = {"asked": 0, "no_move_found": 0, "errors": 0} self._log = open(log, "w", encoding="utf-8") if log else None self.progress_every = int(progress_every or 0) self._started = time.time() if generator is not None: # used by tests: any object with generate(messages) -> text self._gen = generator elif backend == "transformers": self._gen = TransformersGenerator(model, adapter=self.adapter, dtype=dtype, load_in_4bit=_flag(load_in_4bit), trust_remote_code=_flag(trust_remote_code), max_new_tokens=self.max_new_tokens, thinking=thinking, revision=self.revision, reply_start=reply_start) elif backend == "llamacpp": if self.adapter: raise ValueError("adapter only works with backend=transformers") self._gen = LlamaCppGenerator(base_url, tokenizer or model, revision=self.revision, max_new_tokens=self.max_new_tokens, thinking=thinking, reply_start=reply_start) elif backend == "openai": if reply_start: raise ValueError("reply_start does not work with backend=openai; use backend=llamacpp") if self.adapter: raise ValueError("adapter only works with backend=transformers; load it in the server instead") self._gen = OpenAIChatGenerator(base_url, model, max_new_tokens=self.max_new_tokens, thinking=thinking) else: raise ValueError(f"Unknown backend {backend!r}. Use 'transformers', 'llamacpp' or 'openai'.") def messages(self, fen: str) -> List[dict]: return [{"role": "user", "content": render_prompt(fen, template=self._template)}] def move(self, fen: str) -> str: messages = self.messages(fen) self.stats["asked"] += 1 start = time.time() try: raw = self._gen.generate(messages) except Exception: self.stats["errors"] += 1 self.last_reply = None raise # the scorer counts this as an illegal move self.last_reply = raw move = read_move(raw, self.prompt_version) if not move: self.stats["no_move_found"] += 1 if self.progress_every and self.stats["asked"] % self.progress_every == 0: minutes = (time.time() - self._started) / 60 print(f" {self.stats['asked']} moves asked, {minutes:.1f} minutes so far", flush=True) if self._log: prompt = messages[0]["content"] self._log.write(json.dumps({ "fen": fen, "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(), "raw_reply": raw, "final_text": clean_reply(raw), "move": move, "seconds": round(time.time() - start, 3), }) + "\n") self._log.flush() return move def try_position(self, fen: str) -> dict: """Ask once and show everything: the prompt, the raw reply and the move we read from it. For a quick look before a full run. Not counted in the stats or the log.""" messages = self.messages(fen) raw = self._gen.generate(messages) return {"prompt": messages[0]["content"], "raw_reply": raw, "move": read_move(raw, self.prompt_version)} def last_answer(self) -> Optional[dict]: """For prompt move_v2: every part of the latest answer (Good, Bad, the If line, Move), read by chess_eval/recipe_v2.py. For move_v3: the Candidates line and the Move line (chess_eval/recipe_v3.py). The scorer uses it for the extra numbers. None for move_v1, so v1 reports do not change.""" if self.prompt_version not in ("move_v2", "move_v3") or self.last_reply is None: return None if self.prompt_version == "move_v3": from .recipe_v3 import read_answer as read_v3 return read_v3(self.last_reply) from .recipe_v2 import read_answer return read_answer(self.last_reply) def describe(self) -> dict: """Everything needed to repeat this run. Saved in the report.""" info = { "backend": self.backend_name, "model": self.model, "revision": self.revision, "adapter": self.adapter, "prompt_version": self.prompt_version, "prompt_file": f"chess_eval/prompts/{self.prompt_version}.txt", "prompt_sha256": template_sha256(self.prompt_version), "thinking": self.thinking, "reply_start": self.reply_start, "decoding": "greedy (no sampling)", "max_new_tokens": self.max_new_tokens, "answer_rule": ANSWER_RULES[self.prompt_version], "invalid_if_no_move_above": "5% of answers (chess_eval/score.py)", "stats": dict(self.stats), } if hasattr(self._gen, "describe"): info.update(self._gen.describe()) return info def close(self): if self._log: self._log.close() self._log = None if hasattr(self._gen, "close"): self._gen.close() # ---------------------------------------------------------------- backends class TransformersGenerator: """Runs the model on this machine with Hugging Face transformers.""" def __init__(self, model: str, adapter: Optional[str] = None, dtype: str = "auto", load_in_4bit: bool = False, trust_remote_code: bool = False, max_new_tokens: int = 32, thinking: str = "off", revision: Optional[str] = None, reply_start: str = ""): import torch import transformers from transformers import AutoModelForCausalLM, AutoTokenizer self.torch = torch self.max_new_tokens = max_new_tokens self.chat_kwargs = template_kwargs(thinking) self.thinking = thinking self.reply_start = reply_start self.dtype = self._pick_dtype(dtype) kwargs = {"dtype": self.dtype, "trust_remote_code": trust_remote_code} version = {"revision": revision} if revision else {} kwargs.update(version) if torch.cuda.is_available(): kwargs["device_map"] = "auto" # spread over all GPUs if one is not enough if load_in_4bit: from transformers import BitsAndBytesConfig kwargs["quantization_config"] = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=self.dtype) self.tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=trust_remote_code, **version) self.model = AutoModelForCausalLM.from_pretrained(model, **kwargs) if adapter: from peft import PeftModel self.model = PeftModel.from_pretrained(self.model, adapter) self.model.eval() self.info = { "dtype": str(self.dtype).replace("torch.", ""), "load_in_4bit": load_in_4bit, "trust_remote_code": trust_remote_code, "transformers_version": transformers.__version__, "torch_version": torch.__version__, "device": (torch.cuda.get_device_name(0) + f" x{torch.cuda.device_count()}" if torch.cuda.is_available() else "cpu"), } def _pick_dtype(self, dtype: str): torch = self.torch if dtype == "auto": # bfloat16 only on GPUs built for it (A100, H100, L4 and newer). # Older GPUs like Kaggle's T4 and P100 get float32: slower, but # float16 can overflow on some models and spoil the answers. if torch.cuda.is_available() and torch.cuda.is_bf16_supported(including_emulation=False): return torch.bfloat16 return torch.float32 return getattr(torch, dtype) def generate(self, messages: List[dict]) -> str: ids = prompt_token_ids(self.tokenizer, messages, self.thinking, self.reply_start) return greedy_reply(self.model, self.tokenizer, ids, self.max_new_tokens) def describe(self) -> dict: return dict(self.info) class LoadedModelGenerator: """A model that is already loaded (for example during training). Same prompt and same greedy answer as TransformersGenerator: both use prompt_token_ids() and greedy_reply().""" def __init__(self, model, tokenizer, max_new_tokens: int = 32, thinking: str = "off", reply_start: str = "", info: Optional[dict] = None): self.model, self.tokenizer = model, tokenizer self.max_new_tokens, self.thinking, self.reply_start = max_new_tokens, thinking, reply_start self.info = dict(info or {}) def generate(self, messages: List[dict]) -> str: ids = prompt_token_ids(self.tokenizer, messages, self.thinking, self.reply_start) return greedy_reply(self.model, self.tokenizer, ids, self.max_new_tokens) def describe(self) -> dict: return dict(self.info) class LlamaCppGenerator: """Sends exact token numbers to a llama.cpp server (/completion). The prompt is made here with the model's official tokenizer and chat template (prompt_token_ids), so llama.cpp sees the same tokens as training and the transformers exam. llama.cpp uses a list of token numbers as it is: it adds nothing (llama.cpp tools/server, tokenize_mixed).""" def __init__(self, base_url: str, tokenizer: str, revision: Optional[str] = None, max_new_tokens: int = 32, thinking: str = "off", reply_start: str = "", timeout: int = 300, retries: int = 3): from transformers import PreTrainedTokenizerFast version = {"revision": revision} if revision else {} # PreTrainedTokenizerFast directly: no model code is loaded or run. self.tokenizer = PreTrainedTokenizerFast.from_pretrained(tokenizer, **version) self.url = base_url.rstrip("/").removesuffix("/v1") + "/completion" self.max_new_tokens, self.thinking, self.reply_start = max_new_tokens, thinking, reply_start self.timeout, self.retries = timeout, retries self.tokenizer_name = tokenizer def prompt_ids(self, messages: List[dict]) -> List[int]: return prompt_token_ids(self.tokenizer, messages, self.thinking, self.reply_start) def generate(self, messages: List[dict]) -> str: body = {"prompt": self.prompt_ids(messages), "n_predict": self.max_new_tokens, "temperature": 0, "top_k": 1, "seed": 0, "cache_prompt": True} data = json.dumps(body).encode("utf-8") last_error = None for attempt in range(self.retries): try: request = urllib.request.Request(self.url, data=data, method="POST", headers={"Content-Type": "application/json"}) with urllib.request.urlopen(request, timeout=self.timeout) as response: return json.loads(response.read().decode("utf-8")).get("content") or "" except (urllib.error.URLError, TimeoutError, ConnectionError) as error: last_error = error time.sleep(2 ** attempt) raise RuntimeError(f"model server did not answer after {self.retries} tries: {last_error}") def describe(self) -> dict: return {"server": self.url, "tokenizer": self.tokenizer_name, "prompt_sent_as": "token numbers (official tokenizer and chat template)"} class OpenAIChatGenerator: """Sends the prompt to a model server in the common chat completions format.""" def __init__(self, base_url: str, model: str, max_new_tokens: int = 32, thinking: str = "off", timeout: int = 300, retries: int = 3): self.url = base_url.rstrip("/") + "/chat/completions" self.model = model self.max_new_tokens = max_new_tokens self.thinking = thinking self.timeout = timeout self.retries = retries self.api_key = os.environ.get("ATAL_MODEL_API_KEY", "") def generate(self, messages: List[dict]) -> str: body = { "model": self.model, "messages": messages, "temperature": 0, "max_tokens": self.max_new_tokens, # Read by vLLM, SGLang and llama.cpp servers; others ignore it. "chat_template_kwargs": template_kwargs(self.thinking), } headers = {"Content-Type": "application/json"} if self.api_key: headers["Authorization"] = f"Bearer {self.api_key}" data = json.dumps(body).encode("utf-8") last_error = None for attempt in range(self.retries): try: request = urllib.request.Request(self.url, data=data, headers=headers, method="POST") with urllib.request.urlopen(request, timeout=self.timeout) as response: reply = json.loads(response.read().decode("utf-8")) return reply["choices"][0]["message"].get("content") or "" except (urllib.error.URLError, TimeoutError, ConnectionError) as error: last_error = error # server busy or restarting: wait and try again time.sleep(2 ** attempt) raise RuntimeError(f"model server did not answer after {self.retries} tries: {last_error}") def describe(self) -> dict: return {"server": self.url}