File size: 10,130 Bytes
b2c1dad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""

generate.py β€” Play chess against the Liquid Chess Model (LCM).



Moves are entered in UCI format (e.g. e2e4, g1f3, e7e8q).

The model responds instantly with its chosen move.



Usage:

    python generate.py

    python generate.py --checkpoint model.safetensors --side black

    python generate.py --temperature 0.5



Commands during play:

    moves    β€” list all legal moves

    undo     β€” take back the last two moves

    resign   β€” resign the game

    quit     β€” exit



Requirements:

    pip install chess torch safetensors

"""

import argparse
import json
import sys
import torch
import torch.nn.functional as F
import chess

sys.path.insert(0, ".")
from config import ChessModelConfig
from model  import ChessModel


# ══════════════════════════════════════════════════════════════════════════════
# LOADING
# ══════════════════════════════════════════════════════════════════════════════

def load_vocab(vocab_path: str) -> tuple[dict, dict]:
    with open(vocab_path) as f:
        token_to_id = json.load(f)
    return token_to_id, {v: k for k, v in token_to_id.items()}


def load_model(checkpoint_path: str, device: torch.device) -> tuple[ChessModel, ChessModelConfig]:
    config = ChessModelConfig()
    model  = ChessModel(config)

    if checkpoint_path.endswith(".safetensors"):
        from safetensors.torch import load_model as load_safetensors
        load_safetensors(model, checkpoint_path)
    else:
        ckpt  = torch.load(checkpoint_path, map_location=device, weights_only=False)
        state = {k.replace("_orig_mod.", ""): v for k, v in ckpt["model"].items()}
        model.load_state_dict(state)

    model.to(device).eval()
    return model, config


# ══════════════════════════════════════════════════════════════════════════════
# INFERENCE
# ══════════════════════════════════════════════════════════════════════════════

def get_model_move(

    model:        ChessModel,

    config:       ChessModelConfig,

    board:        chess.Board,

    move_history: list[str],

    token_to_id:  dict,

    id_to_token:  dict,

    device:       torch.device,

    temperature:  float = 1.0,

    top_k:        int   = 0,

) -> str | None:
    """Return the model's chosen move in UCI format."""
    pov_id    = token_to_id.get("<W>" if board.turn == chess.WHITE else "<B>", 1)
    token_ids = [pov_id]

    for uci in move_history:
        tid = token_to_id.get(uci)
        if tid is not None:
            token_ids.append(tid)

    token_ids    = token_ids[-(config.max_seq_len - 1):]
    input_tensor = torch.tensor([token_ids], dtype=torch.long, device=device)

    with torch.no_grad():
        ntp_logits, _ = model(input_tensor)

    logits     = ntp_logits[0, -1, :]
    legal_ucis = [m.uci() for m in board.legal_moves]
    if not legal_ucis:
        return None

    legal_ids = [token_to_id[u] for u in legal_ucis if u in token_to_id]
    if not legal_ids:
        import random
        return random.choice(legal_ucis)

    mask            = torch.full_like(logits, float("-inf"))
    mask[legal_ids] = logits[legal_ids]
    mask            = mask / max(temperature, 1e-6)

    if top_k > 0:
        top_vals, _ = torch.topk(mask[mask != float("-inf")], min(top_k, len(legal_ids)))
        mask[mask < top_vals[-1]] = float("-inf")

    if temperature < 0.01:
        chosen_id = torch.argmax(mask).item()
    else:
        chosen_id = torch.multinomial(F.softmax(mask, dim=-1), num_samples=1).item()

    return id_to_token.get(chosen_id, legal_ucis[0])


# ══════════════════════════════════════════════════════════════════════════════
# DISPLAY
# ══════════════════════════════════════════════════════════════════════════════

PIECE_SYMBOLS = {
    'P': 'β™Ÿ', 'N': 'β™ž', 'B': '♝', 'R': 'β™œ', 'Q': 'β™›', 'K': 'β™š',
    'p': 'β™™', 'n': 'β™˜', 'b': 'β™—', 'r': 'β™–', 'q': 'β™•', 'k': 'β™”',
}

def print_board(board: chess.Board, player_is_white: bool):
    print()
    ranks = range(7, -1, -1) if player_is_white else range(8)
    files = range(8)         if player_is_white else range(7, -1, -1)

    for rank in ranks:
        row = f"  {rank + 1} "
        for file in files:
            piece = board.piece_at(chess.square(file, rank))
            row  += (PIECE_SYMBOLS.get(piece.symbol(), '?') if piece else 'Β·') + " "
        print(row)

    print("    a b c d e f g h" if player_is_white else "    h g f e d c b a")
    print()


def print_status(board: chess.Board):
    if board.is_checkmate():
        winner = "Black" if board.turn == chess.WHITE else "White"
        print(f"\n{'='*38}\n  CHECKMATE β€” {winner} wins!\n{'='*38}\n")
    elif board.is_stalemate():
        print("\nStalemate β€” draw.")
    elif board.is_insufficient_material():
        print("\nInsufficient material β€” draw.")
    elif board.is_fifty_moves():
        print("\n50-move rule β€” draw.")
    elif board.is_check():
        print("  *** CHECK ***")


# ══════════════════════════════════════════════════════════════════════════════
# GAME LOOP
# ══════════════════════════════════════════════════════════════════════════════

def play(args):
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    token_to_id, id_to_token = load_vocab(args.vocab)
    model, config            = load_model(args.checkpoint, device)

    player_is_white = args.side.lower() != "black"
    print(f"\nLiquid Chess Model β€” {sum(p.numel() for p in model.parameters())/1e6:.1f}M parameters")
    print(f"You are playing as {'White' if player_is_white else 'Black'}.")
    print("Enter moves in UCI format (e.g. e2e4, g1f3). Type 'moves', 'undo', 'resign', or 'quit'.\n")

    board        = chess.Board()
    move_history = []

    while not board.is_game_over():
        print_board(board, player_is_white)
        print_status(board)

        if board.is_game_over():
            break

        is_player_turn = (board.turn == chess.WHITE) == player_is_white

        if is_player_turn:
            while True:
                try:
                    raw = input("Your move: ").strip().lower()
                except EOFError:
                    return

                if raw == "quit":
                    print("Goodbye!")
                    return
                if raw == "resign":
                    print("You resigned.")
                    return
                if raw == "moves":
                    print("Legal moves:", ", ".join(sorted(m.uci() for m in board.legal_moves)))
                    continue
                if raw == "undo" and len(move_history) >= 2:
                    board.pop(); board.pop()
                    move_history = move_history[:-2]
                    print("Undone.")
                    break

                try:
                    move = chess.Move.from_uci(raw)
                    if move in board.legal_moves:
                        board.push(move)
                        move_history.append(raw)
                        break
                    else:
                        print(f"Illegal move: {raw}")
                except ValueError:
                    print(f"Invalid format: {raw} β€” use UCI (e.g. e2e4)")
        else:
            print("Model is thinking...")
            move_uci = get_model_move(
                model, config, board, move_history,
                token_to_id, id_to_token, device,
                temperature=args.temperature,
                top_k=args.top_k,
            )
            if move_uci is None:
                break
            board.push(chess.Move.from_uci(move_uci))
            move_history.append(move_uci)
            print(f"Model plays: {move_uci}")

    print_board(board, player_is_white)
    print_status(board)
    print(f"Result: {board.result()}")
    print(f"Moves: {' '.join(move_history)}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Play chess against the Liquid Chess Model.")
    parser.add_argument("--checkpoint",  default="model.safetensors",
                        help="Path to model checkpoint (.safetensors or .pt)")
    parser.add_argument("--vocab",       default="vocab.json",
                        help="Path to vocab.json")
    parser.add_argument("--side",        default="white", choices=["white", "black"],
                        help="Your color (default: white)")
    parser.add_argument("--temperature", type=float, default=1.0,
                        help="Sampling temperature β€” lower is more deterministic (default: 1.0)")
    parser.add_argument("--top-k",       type=int,   default=0,
                        help="Top-k filtering β€” 0 disables (default: 0)")
    play(parser.parse_args())