Chess Challenge submission by Oceane28
Browse files- README.md +12 -7
- config.json +11 -7
- model.py +396 -0
- model.safetensors +2 -2
- tokenizer.py +168 -0
- tokenizer_config.json +8 -2
- training_args.bin +3 -0
README.md
CHANGED
|
@@ -14,13 +14,18 @@ Chess model submitted to the LLM Course Chess Challenge.
|
|
| 14 |
## Submission Info
|
| 15 |
|
| 16 |
- **Submitted by**: [Oceane28](https://huggingface.co/Oceane28)
|
| 17 |
-
- **Parameters**:
|
| 18 |
- **Organization**: LLM-course
|
| 19 |
|
| 20 |
-
##
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
## Submission Info
|
| 15 |
|
| 16 |
- **Submitted by**: [Oceane28](https://huggingface.co/Oceane28)
|
| 17 |
+
- **Parameters**: 973,544
|
| 18 |
- **Organization**: LLM-course
|
| 19 |
|
| 20 |
+
## Usage
|
| 21 |
|
| 22 |
+
```python
|
| 23 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 24 |
+
|
| 25 |
+
model = AutoModelForCausalLM.from_pretrained("LLM-course/chess-6-Oceane28", trust_remote_code=True)
|
| 26 |
+
tokenizer = AutoTokenizer.from_pretrained("LLM-course/chess-6-Oceane28", trust_remote_code=True)
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
## Evaluation
|
| 30 |
+
|
| 31 |
+
This model is evaluated at the [Chess Challenge Arena](https://huggingface.co/spaces/LLM-course/Chess1MChallenge).
|
config.json
CHANGED
|
@@ -9,12 +9,16 @@
|
|
| 9 |
"layer_norm_epsilon": 1e-05,
|
| 10 |
"model_type": "chess_transformer",
|
| 11 |
"n_ctx": 256,
|
| 12 |
-
"n_embd":
|
| 13 |
-
"n_head":
|
| 14 |
-
"n_inner":
|
| 15 |
-
"n_layer":
|
| 16 |
"pad_token_id": 0,
|
| 17 |
"tie_weights": true,
|
| 18 |
-
"transformers_version": "4.57.
|
| 19 |
-
"vocab_size": 72
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
"layer_norm_epsilon": 1e-05,
|
| 10 |
"model_type": "chess_transformer",
|
| 11 |
"n_ctx": 256,
|
| 12 |
+
"n_embd": 92,
|
| 13 |
+
"n_head": 4,
|
| 14 |
+
"n_inner": 276,
|
| 15 |
+
"n_layer": 11,
|
| 16 |
"pad_token_id": 0,
|
| 17 |
"tie_weights": true,
|
| 18 |
+
"transformers_version": "4.57.6",
|
| 19 |
+
"vocab_size": 72,
|
| 20 |
+
"auto_map": {
|
| 21 |
+
"AutoConfig": "model.ChessConfig",
|
| 22 |
+
"AutoModelForCausalLM": "model.ChessForCausalLM"
|
| 23 |
+
}
|
| 24 |
+
}
|
model.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Modèle Transformer pour le Chess Challenge (1M paramètres).
|
| 3 |
+
|
| 4 |
+
Ce module fournit une architecture transformer de style GPT conçue
|
| 5 |
+
pour respecter la contrainte stricte de moins de 1 million de paramètres.
|
| 6 |
+
|
| 7 |
+
Composants clés :
|
| 8 |
+
- ChessConfig : Configuration des hyperparamètres.
|
| 9 |
+
- ChessForCausalLM : Le modèle principal pour la prédiction du prochain coup.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import math
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
from typing import Optional, Tuple, Union
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
from transformers import PretrainedConfig, PreTrainedModel, AutoConfig, AutoModelForCausalLM
|
| 19 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 20 |
+
|
| 21 |
+
# -----------------------------------------------------------------------------
|
| 22 |
+
# Configuration
|
| 23 |
+
# -----------------------------------------------------------------------------
|
| 24 |
+
|
| 25 |
+
class ChessConfig(PretrainedConfig):
|
| 26 |
+
"""
|
| 27 |
+
Classe de configuration pour le modèle Chess Transformer.
|
| 28 |
+
|
| 29 |
+
Conçue pour un budget de paramètres très serré (< 1M).
|
| 30 |
+
|
| 31 |
+
Répartition du budget (avec les valeurs par défaut de ton ami) :
|
| 32 |
+
- Vocabulaire (Embeddings) : 72 * 92 = ~6,6k
|
| 33 |
+
- Embeddings de position : 256 * 92 = ~23,5k
|
| 34 |
+
- Couches Transformer : 11 couches * (~85k par couche) = ~935k
|
| 35 |
+
- Tête LM (liée aux embeddings) : 0 paramètre supplémentaire
|
| 36 |
+
- Total : ~970k paramètres (juste en dessous de 1M).
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
model_type = "chess_transformer"
|
| 40 |
+
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
vocab_size: int = 1200,
|
| 44 |
+
n_embd: int = 128,
|
| 45 |
+
n_layer: int = 6,
|
| 46 |
+
n_head: int = 4,
|
| 47 |
+
n_ctx: int = 256,
|
| 48 |
+
n_inner: Optional[int] = None,
|
| 49 |
+
dropout: float = 0.1,
|
| 50 |
+
layer_norm_epsilon: float = 1e-5,
|
| 51 |
+
tie_weights: bool = True,
|
| 52 |
+
pad_token_id: int = 0,
|
| 53 |
+
bos_token_id: int = 1,
|
| 54 |
+
eos_token_id: int = 2,
|
| 55 |
+
**kwargs,
|
| 56 |
+
):
|
| 57 |
+
super().__init__(
|
| 58 |
+
pad_token_id=pad_token_id,
|
| 59 |
+
bos_token_id=bos_token_id,
|
| 60 |
+
eos_token_id=eos_token_id,
|
| 61 |
+
**kwargs,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
self.vocab_size = vocab_size
|
| 65 |
+
self.n_embd = n_embd
|
| 66 |
+
self.n_layer = n_layer
|
| 67 |
+
self.n_head = n_head
|
| 68 |
+
self.n_ctx = n_ctx
|
| 69 |
+
self.n_inner = n_inner if n_inner is not None else 3 * n_embd
|
| 70 |
+
self.dropout = dropout
|
| 71 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 72 |
+
self.tie_weights = tie_weights
|
| 73 |
+
self.tie_word_embeddings = bool(tie_weights)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# -----------------------------------------------------------------------------
|
| 77 |
+
# Modules du Transformer
|
| 78 |
+
# -----------------------------------------------------------------------------
|
| 79 |
+
|
| 80 |
+
class MultiHeadAttention(nn.Module):
|
| 81 |
+
"""
|
| 82 |
+
Module d'attention multi-têtes standard.
|
| 83 |
+
Inclut le masquage causal pour empêcher le modèle de "voir le futur".
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(self, config: ChessConfig):
|
| 87 |
+
super().__init__()
|
| 88 |
+
|
| 89 |
+
assert config.n_embd % config.n_head == 0, \
|
| 90 |
+
f"n_embd ({config.n_embd}) doit être divisible par n_head ({config.n_head})"
|
| 91 |
+
|
| 92 |
+
self.n_head = config.n_head
|
| 93 |
+
self.n_embd = config.n_embd
|
| 94 |
+
self.head_dim = config.n_embd // config.n_head
|
| 95 |
+
|
| 96 |
+
# Projection combinée Q, K, V pour l'efficacité
|
| 97 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
| 98 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
| 99 |
+
|
| 100 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 101 |
+
|
| 102 |
+
# Masque causal (registre persistent=False pour ne pas le sauvegarder dans le checkpoint)
|
| 103 |
+
self.register_buffer(
|
| 104 |
+
"bias",
|
| 105 |
+
torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
|
| 106 |
+
1, 1, config.n_ctx, config.n_ctx
|
| 107 |
+
),
|
| 108 |
+
persistent=False,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def forward(
|
| 112 |
+
self,
|
| 113 |
+
x: torch.Tensor,
|
| 114 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 115 |
+
) -> torch.Tensor:
|
| 116 |
+
batch_size, seq_len, _ = x.size()
|
| 117 |
+
|
| 118 |
+
# Calcul de Q, K, V
|
| 119 |
+
qkv = self.c_attn(x)
|
| 120 |
+
q, k, v = qkv.split(self.n_embd, dim=2)
|
| 121 |
+
|
| 122 |
+
# Remodelage pour l'attention multi-têtes
|
| 123 |
+
# (batch, seq_len, n_head, head_dim) -> (batch, n_head, seq_len, head_dim)
|
| 124 |
+
q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 125 |
+
k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 126 |
+
v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 127 |
+
|
| 128 |
+
# Attention produit scalaire (Scaled Dot-Product Attention)
|
| 129 |
+
attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 130 |
+
|
| 131 |
+
# Application du masque causal (le futur est masqué avec -inf)
|
| 132 |
+
causal_mask = self.bias[:, :, :seq_len, :seq_len]
|
| 133 |
+
attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
|
| 134 |
+
|
| 135 |
+
# Application du masque d'attention (pour le padding)
|
| 136 |
+
if attention_mask is not None:
|
| 137 |
+
# attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
|
| 138 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 139 |
+
attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
|
| 140 |
+
|
| 141 |
+
attn_weights = F.softmax(attn_weights, dim=-1)
|
| 142 |
+
attn_weights = self.dropout(attn_weights)
|
| 143 |
+
|
| 144 |
+
# Application de l'attention aux valeurs
|
| 145 |
+
attn_output = torch.matmul(attn_weights, v)
|
| 146 |
+
|
| 147 |
+
# Remise en forme
|
| 148 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(
|
| 149 |
+
batch_size, seq_len, self.n_embd
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# Projection de sortie
|
| 153 |
+
attn_output = self.c_proj(attn_output)
|
| 154 |
+
|
| 155 |
+
return attn_output
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class FeedForward(nn.Module):
|
| 159 |
+
"""
|
| 160 |
+
Réseau de neurones Feed-Forward (MLP).
|
| 161 |
+
Deux couches linéaires avec une activation GELU entre les deux.
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
def __init__(self, config: ChessConfig):
|
| 165 |
+
super().__init__()
|
| 166 |
+
self.c_fc = nn.Linear(config.n_embd, config.n_inner)
|
| 167 |
+
self.c_proj = nn.Linear(config.n_inner, config.n_embd)
|
| 168 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 169 |
+
|
| 170 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 171 |
+
x = self.c_fc(x)
|
| 172 |
+
x = F.gelu(x)
|
| 173 |
+
x = self.c_proj(x)
|
| 174 |
+
x = self.dropout(x)
|
| 175 |
+
return x
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class TransformerBlock(nn.Module):
|
| 179 |
+
"""
|
| 180 |
+
Un bloc transformer unique contenant Attention et Feed-Forward.
|
| 181 |
+
Utilise la "Pre-normalization" (LayerNorm avant l'attention/FFN) pour la stabilité.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
def __init__(self, config: ChessConfig):
|
| 185 |
+
super().__init__()
|
| 186 |
+
self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 187 |
+
self.attn = MultiHeadAttention(config)
|
| 188 |
+
self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 189 |
+
self.mlp = FeedForward(config)
|
| 190 |
+
|
| 191 |
+
def forward(
|
| 192 |
+
self,
|
| 193 |
+
x: torch.Tensor,
|
| 194 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 195 |
+
) -> torch.Tensor:
|
| 196 |
+
# Connexion résiduelle + Pre-norm Attention
|
| 197 |
+
x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
|
| 198 |
+
# Connexion résiduelle + Pre-norm FFN
|
| 199 |
+
x = x + self.mlp(self.ln_2(x))
|
| 200 |
+
return x
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# -----------------------------------------------------------------------------
|
| 204 |
+
# Modèle Principal
|
| 205 |
+
# -----------------------------------------------------------------------------
|
| 206 |
+
|
| 207 |
+
class ChessForCausalLM(PreTrainedModel):
|
| 208 |
+
"""
|
| 209 |
+
Modèle final pour la prédiction de coups (Causal Language Modeling).
|
| 210 |
+
|
| 211 |
+
Architecture :
|
| 212 |
+
1. Embeddings (Tokens + Position)
|
| 213 |
+
2. Empilement de blocs Transformer
|
| 214 |
+
3. Tête linéaire finale (Projection vers le vocabulaire)
|
| 215 |
+
"""
|
| 216 |
+
|
| 217 |
+
config_class = ChessConfig
|
| 218 |
+
base_model_prefix = "transformer"
|
| 219 |
+
supports_gradient_checkpointing = True
|
| 220 |
+
|
| 221 |
+
# Ignore l'avertissement de clé manquante car lm_head partage les poids avec wte
|
| 222 |
+
keys_to_ignore_on_load_missing = ["lm_head.weight"]
|
| 223 |
+
|
| 224 |
+
def __init__(self, config: ChessConfig):
|
| 225 |
+
super().__init__(config)
|
| 226 |
+
|
| 227 |
+
# Embeddings
|
| 228 |
+
self.wte = nn.Embedding(config.vocab_size, config.n_embd)
|
| 229 |
+
self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
|
| 230 |
+
|
| 231 |
+
self.drop = nn.Dropout(config.dropout)
|
| 232 |
+
|
| 233 |
+
# Blocs Transformer
|
| 234 |
+
self.h = nn.ModuleList([
|
| 235 |
+
TransformerBlock(config) for _ in range(config.n_layer)
|
| 236 |
+
])
|
| 237 |
+
|
| 238 |
+
# LayerNorm final
|
| 239 |
+
self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 240 |
+
|
| 241 |
+
# Tête de sortie (sans biais pour économiser des paramètres)
|
| 242 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 243 |
+
|
| 244 |
+
# Gestion du partage de poids (Weight Tying)
|
| 245 |
+
if config.tie_weights:
|
| 246 |
+
self._tied_weights_keys = ["lm_head.weight"]
|
| 247 |
+
|
| 248 |
+
# Initialisation des poids
|
| 249 |
+
self.post_init()
|
| 250 |
+
|
| 251 |
+
# Forcer le lien des poids si configuré
|
| 252 |
+
if config.tie_weights:
|
| 253 |
+
self.tie_weights()
|
| 254 |
+
|
| 255 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 256 |
+
return self.wte
|
| 257 |
+
|
| 258 |
+
def set_input_embeddings(self, new_embeddings: nn.Module):
|
| 259 |
+
self.wte = new_embeddings
|
| 260 |
+
if getattr(self.config, "tie_weights", False):
|
| 261 |
+
self.tie_weights()
|
| 262 |
+
|
| 263 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 264 |
+
return self.lm_head
|
| 265 |
+
|
| 266 |
+
def set_output_embeddings(self, new_embeddings: nn.Module):
|
| 267 |
+
self.lm_head = new_embeddings
|
| 268 |
+
|
| 269 |
+
def tie_weights(self):
|
| 270 |
+
"""Lie les poids de l'embedding d'entrée et de la tête de sortie."""
|
| 271 |
+
if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
|
| 272 |
+
self._tie_or_clone_weights(self.lm_head, self.wte)
|
| 273 |
+
|
| 274 |
+
def _init_weights(self, module: nn.Module):
|
| 275 |
+
"""Initialisation des poids style GPT-2."""
|
| 276 |
+
if isinstance(module, nn.Linear):
|
| 277 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 278 |
+
if module.bias is not None:
|
| 279 |
+
torch.nn.init.zeros_(module.bias)
|
| 280 |
+
elif isinstance(module, nn.Embedding):
|
| 281 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 282 |
+
elif isinstance(module, nn.LayerNorm):
|
| 283 |
+
torch.nn.init.ones_(module.weight)
|
| 284 |
+
torch.nn.init.zeros_(module.bias)
|
| 285 |
+
|
| 286 |
+
def forward(
|
| 287 |
+
self,
|
| 288 |
+
input_ids: torch.LongTensor,
|
| 289 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 290 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 291 |
+
labels: Optional[torch.LongTensor] = None,
|
| 292 |
+
return_dict: Optional[bool] = None,
|
| 293 |
+
**kwargs,
|
| 294 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 295 |
+
"""
|
| 296 |
+
Passe avant (Forward pass).
|
| 297 |
+
Calcule les logits et, si des étiquettes (labels) sont fournies, la perte (loss).
|
| 298 |
+
"""
|
| 299 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 300 |
+
|
| 301 |
+
batch_size, seq_len = input_ids.size()
|
| 302 |
+
device = input_ids.device
|
| 303 |
+
|
| 304 |
+
# Création des IDs de position s'ils ne sont pas fournis
|
| 305 |
+
if position_ids is None:
|
| 306 |
+
position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
|
| 307 |
+
|
| 308 |
+
# Calcul des embeddings (Token + Position)
|
| 309 |
+
token_embeds = self.wte(input_ids)
|
| 310 |
+
position_embeds = self.wpe(position_ids)
|
| 311 |
+
hidden_states = self.drop(token_embeds + position_embeds)
|
| 312 |
+
|
| 313 |
+
# Passage dans les blocs Transformer
|
| 314 |
+
for block in self.h:
|
| 315 |
+
hidden_states = block(hidden_states, attention_mask=attention_mask)
|
| 316 |
+
|
| 317 |
+
# Normalisation finale
|
| 318 |
+
hidden_states = self.ln_f(hidden_states)
|
| 319 |
+
|
| 320 |
+
# Calcul des logits (prédiction du prochain token)
|
| 321 |
+
logits = self.lm_head(hidden_states)
|
| 322 |
+
|
| 323 |
+
# Calcul de la perte (Training Loss)
|
| 324 |
+
loss = None
|
| 325 |
+
if labels is not None:
|
| 326 |
+
# On décale les logits et les labels d'un cran
|
| 327 |
+
# (le modèle doit prédire le token t+1 à partir du token t)
|
| 328 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 329 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 330 |
+
|
| 331 |
+
# Perte CrossEntropy standard
|
| 332 |
+
loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
|
| 333 |
+
loss = loss_fct(
|
| 334 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 335 |
+
shift_labels.view(-1),
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
if not return_dict:
|
| 339 |
+
output = (logits,)
|
| 340 |
+
return ((loss,) + output) if loss is not None else output
|
| 341 |
+
|
| 342 |
+
return CausalLMOutputWithPast(
|
| 343 |
+
loss=loss,
|
| 344 |
+
logits=logits,
|
| 345 |
+
past_key_values=None,
|
| 346 |
+
hidden_states=None,
|
| 347 |
+
attentions=None,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
@torch.no_grad()
|
| 351 |
+
def generate_move(
|
| 352 |
+
self,
|
| 353 |
+
input_ids: torch.LongTensor,
|
| 354 |
+
temperature: float = 1.0,
|
| 355 |
+
top_k: Optional[int] = None,
|
| 356 |
+
top_p: Optional[float] = None,
|
| 357 |
+
) -> int:
|
| 358 |
+
"""
|
| 359 |
+
Génère le prochain coup pour une séquence donnée.
|
| 360 |
+
Utilisé pour l'inférence en jeu réel.
|
| 361 |
+
"""
|
| 362 |
+
self.eval()
|
| 363 |
+
|
| 364 |
+
# Récupère les logits pour la dernière position uniquement
|
| 365 |
+
outputs = self(input_ids)
|
| 366 |
+
logits = outputs.logits[:, -1, :] / temperature
|
| 367 |
+
|
| 368 |
+
# Filtrage Top-K
|
| 369 |
+
if top_k is not None:
|
| 370 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
| 371 |
+
logits[indices_to_remove] = float("-inf")
|
| 372 |
+
|
| 373 |
+
# Filtrage Top-P (Nucleus Sampling)
|
| 374 |
+
if top_p is not None:
|
| 375 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 376 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 377 |
+
|
| 378 |
+
# On retire les tokens qui sont au-dessus du seuil cumulatif
|
| 379 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 380 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 381 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 382 |
+
|
| 383 |
+
indices_to_remove = sorted_indices_to_remove.scatter(
|
| 384 |
+
dim=-1, index=sorted_indices, src=sorted_indices_to_remove
|
| 385 |
+
)
|
| 386 |
+
logits[indices_to_remove] = float("-inf")
|
| 387 |
+
|
| 388 |
+
# Échantillonnage final
|
| 389 |
+
probs = F.softmax(logits, dim=-1)
|
| 390 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 391 |
+
|
| 392 |
+
return next_token.item()
|
| 393 |
+
|
| 394 |
+
# Enregistrement pour chargement automatique via AutoModel
|
| 395 |
+
AutoConfig.register("chess_transformer", ChessConfig)
|
| 396 |
+
AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
|
model.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
from typing import Dict, List, Optional
|
| 6 |
+
from transformers import PreTrainedTokenizer
|
| 7 |
+
|
| 8 |
+
class ChessTokenizer(PreTrainedTokenizer):
|
| 9 |
+
"""
|
| 10 |
+
Tokenizer personnalisé pour le défi 'Chess 1M'.
|
| 11 |
+
Ce tokenizer découpe les coups d'échecs en cases individuelles (ex: 'e2e4' -> 'e2', 'e4').
|
| 12 |
+
Cela permet de réduire la taille du vocabulaire à ~72 tokens (cases + promotions).
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 16 |
+
|
| 17 |
+
# Définition des tokens spéciaux
|
| 18 |
+
PAD_TOKEN = "[PAD]"
|
| 19 |
+
BOS_TOKEN = "[BOS]"
|
| 20 |
+
EOS_TOKEN = "[EOS]"
|
| 21 |
+
UNK_TOKEN = "[UNK]"
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
vocab_file: Optional[str] = None,
|
| 26 |
+
vocab: Optional[Dict[str, int]] = None,
|
| 27 |
+
**kwargs,
|
| 28 |
+
):
|
| 29 |
+
# Initialisation des attributs de tokens spéciaux
|
| 30 |
+
self._pad_token = self.PAD_TOKEN
|
| 31 |
+
self._bos_token = self.BOS_TOKEN
|
| 32 |
+
self._eos_token = self.EOS_TOKEN
|
| 33 |
+
self._unk_token = self.UNK_TOKEN
|
| 34 |
+
|
| 35 |
+
# Nettoyage des arguments pour éviter les doublons avec la classe mère
|
| 36 |
+
for token in ("pad_token", "bos_token", "eos_token", "unk_token"):
|
| 37 |
+
kwargs.pop(token, None)
|
| 38 |
+
|
| 39 |
+
# Regex cruciale : Elle capture soit une case (a1..h8), soit une pièce de promotion (q,r,b,n)
|
| 40 |
+
self.token_pattern = re.compile(r"[a-h][1-8]|[qrbn]")
|
| 41 |
+
|
| 42 |
+
# Chargement du vocabulaire
|
| 43 |
+
if vocab is not None:
|
| 44 |
+
self._vocab = vocab
|
| 45 |
+
elif vocab_file is not None and os.path.exists(vocab_file):
|
| 46 |
+
with open(vocab_file, "r", encoding="utf-8") as f:
|
| 47 |
+
self._vocab = json.load(f)
|
| 48 |
+
else:
|
| 49 |
+
# Création par défaut si aucun fichier n'est fourni
|
| 50 |
+
self._vocab = self._create_default_vocab()
|
| 51 |
+
|
| 52 |
+
# Création du dictionnaire inverse (ID -> Token) pour le décodage
|
| 53 |
+
self._ids_to_tokens = {idx: tok for tok, idx in self._vocab.items()}
|
| 54 |
+
|
| 55 |
+
super().__init__(
|
| 56 |
+
pad_token=self._pad_token,
|
| 57 |
+
bos_token=self._bos_token,
|
| 58 |
+
eos_token=self._eos_token,
|
| 59 |
+
unk_token=self._unk_token,
|
| 60 |
+
**kwargs,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
def _create_default_vocab(self) -> Dict[str, int]:
|
| 64 |
+
"""
|
| 65 |
+
Génère le vocabulaire par défaut si 'vocab.json' est absent.
|
| 66 |
+
Ordre : Tokens spéciaux -> Cases (a1..h8) -> Promotions (q,r,b,n).
|
| 67 |
+
"""
|
| 68 |
+
special_tokens = [
|
| 69 |
+
self.PAD_TOKEN,
|
| 70 |
+
self.BOS_TOKEN,
|
| 71 |
+
self.EOS_TOKEN,
|
| 72 |
+
self.UNK_TOKEN,
|
| 73 |
+
]
|
| 74 |
+
vocab = {token: idx for idx, token in enumerate(special_tokens)}
|
| 75 |
+
idx = len(vocab)
|
| 76 |
+
|
| 77 |
+
# Ajout des 64 cases de l'échiquier
|
| 78 |
+
for file in "abcdefgh":
|
| 79 |
+
for rank in "12345678":
|
| 80 |
+
vocab[f"{file}{rank}"] = idx
|
| 81 |
+
idx += 1
|
| 82 |
+
|
| 83 |
+
# Ajout des pièces de promotion (minuscules)
|
| 84 |
+
for piece in ("q", "r", "b", "n"):
|
| 85 |
+
vocab[piece] = idx
|
| 86 |
+
idx += 1
|
| 87 |
+
|
| 88 |
+
return vocab
|
| 89 |
+
|
| 90 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 91 |
+
"""
|
| 92 |
+
Découpe une chaîne de coups (PGN brut) en liste de tokens.
|
| 93 |
+
Exemple : "e2e4 c7c5" -> ["e2", "e4", "c7", "c5"]
|
| 94 |
+
"""
|
| 95 |
+
text = text.replace("(Q)", "q").replace("(R)", "r").replace("(B)", "b").replace("(N)", "n")
|
| 96 |
+
return self.token_pattern.findall(text)
|
| 97 |
+
|
| 98 |
+
def _convert_token_to_id(self, token: str) -> int:
|
| 99 |
+
"""Transforme un token (str) en son ID (int)."""
|
| 100 |
+
return self._vocab.get(token, self._vocab[self.UNK_TOKEN])
|
| 101 |
+
|
| 102 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 103 |
+
"""Transforme un ID (int) en son token (str)."""
|
| 104 |
+
return self._ids_to_tokens.get(index, self.UNK_TOKEN)
|
| 105 |
+
|
| 106 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
| 107 |
+
"""
|
| 108 |
+
Reconstruit une chaîne lisible à partir d'une liste de tokens.
|
| 109 |
+
C'est l'opération inverse de la tokenization.
|
| 110 |
+
Fusionne ["e2", "e4"] en "e2e4".
|
| 111 |
+
"""
|
| 112 |
+
special_tokens = {
|
| 113 |
+
self.PAD_TOKEN,
|
| 114 |
+
self.BOS_TOKEN,
|
| 115 |
+
self.EOS_TOKEN,
|
| 116 |
+
self.UNK_TOKEN,
|
| 117 |
+
}
|
| 118 |
+
# On filtre les tokens spéciaux pour ne garder que les coups
|
| 119 |
+
filtered_tokens = [t for t in tokens if t not in special_tokens]
|
| 120 |
+
|
| 121 |
+
output: List[str] = []
|
| 122 |
+
for token in filtered_tokens:
|
| 123 |
+
# Cas 1 : C'est une promotion (ex: 'q'), on l'attache au coup précédent
|
| 124 |
+
if token in {"q", "r", "b", "n"} and output:
|
| 125 |
+
output[-1] += token
|
| 126 |
+
|
| 127 |
+
# Cas 2 : C'est une case de destination.
|
| 128 |
+
# Si le dernier élément ajouté est une case seule (len==2), on fusionne.
|
| 129 |
+
# Ex: output=['e2'], token='e4' -> output=['e2e4']
|
| 130 |
+
elif output and len(output[-1]) == 2 and output[-1][0] in "abcdefgh":
|
| 131 |
+
output[-1] += token
|
| 132 |
+
|
| 133 |
+
# Cas 3 : C'est une nouvelle case de départ
|
| 134 |
+
else:
|
| 135 |
+
output.append(token)
|
| 136 |
+
|
| 137 |
+
return " ".join(output)
|
| 138 |
+
|
| 139 |
+
def save_vocabulary(
|
| 140 |
+
self,
|
| 141 |
+
save_directory: str,
|
| 142 |
+
filename_prefix: Optional[str] = None,
|
| 143 |
+
) -> tuple:
|
| 144 |
+
"""Sauvegarde le vocabulaire au format JSON."""
|
| 145 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 146 |
+
vocab_file = os.path.join(
|
| 147 |
+
save_directory,
|
| 148 |
+
f"{filename_prefix + '-' if filename_prefix else ''}vocab.json",
|
| 149 |
+
)
|
| 150 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 151 |
+
json.dump(self._vocab, f, ensure_ascii=False, indent=2)
|
| 152 |
+
return (vocab_file,)
|
| 153 |
+
|
| 154 |
+
# Méthodes requises par Hugging Face mais non utilisées ici
|
| 155 |
+
@classmethod
|
| 156 |
+
def build_vocab_from_iterator(cls, iterator, min_frequency: int = 1):
|
| 157 |
+
return cls()
|
| 158 |
+
|
| 159 |
+
@classmethod
|
| 160 |
+
def build_vocab_from_dataset(cls, **kwargs):
|
| 161 |
+
return cls()
|
| 162 |
+
|
| 163 |
+
@property
|
| 164 |
+
def vocab_size(self) -> int:
|
| 165 |
+
return len(self._vocab)
|
| 166 |
+
|
| 167 |
+
def get_vocab(self) -> Dict[str, int]:
|
| 168 |
+
return dict(self._vocab)
|
tokenizer_config.json
CHANGED
|
@@ -40,5 +40,11 @@
|
|
| 40 |
"model_max_length": 1000000000000000019884624838656,
|
| 41 |
"pad_token": "[PAD]",
|
| 42 |
"tokenizer_class": "ChessTokenizer",
|
| 43 |
-
"unk_token": "[UNK]"
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
"model_max_length": 1000000000000000019884624838656,
|
| 41 |
"pad_token": "[PAD]",
|
| 42 |
"tokenizer_class": "ChessTokenizer",
|
| 43 |
+
"unk_token": "[UNK]",
|
| 44 |
+
"auto_map": {
|
| 45 |
+
"AutoTokenizer": [
|
| 46 |
+
"tokenizer.ChessTokenizer",
|
| 47 |
+
null
|
| 48 |
+
]
|
| 49 |
+
}
|
| 50 |
+
}
|
training_args.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ec6c6db070ca0aa85d93dca4ffcb5042e5b5e2c627b7c0e8fab6a5a0e89a4067
|
| 3 |
+
size 5777
|