DarshanScripts commited on
Commit
98aec3b
·
verified ·
1 Parent(s): 261bf61

Upload stratego\main.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. stratego//main.py +431 -0
stratego//main.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import re
4
+ import time
5
+ import random
6
+ # from stratego.prompt_optimizer import improve_prompt
7
+ from stratego.env.stratego_env import StrategoEnv
8
+ from stratego.prompts import get_prompt_pack
9
+ from stratego.utils.parsing import extract_board_block_lines, extract_legal_moves, extract_forbidden
10
+ from stratego.utils.game_move_tracker import GameMoveTracker as MoveTrackerClass
11
+ from stratego.utils.move_processor import process_move
12
+ from stratego.game_logger import GameLogger
13
+ from stratego.game_analyzer import analyze_and_update_prompt
14
+ from stratego.datasets import auto_push_after_game
15
+
16
+
17
+ #Revised to set temperature(13 Nov 2025)
18
+ def build_agent(spec: str, prompt_name: str):
19
+ """
20
+ Creates and configures an AI agent based on the input string.
21
+ Example spec: 'ollama:phi3:3.8b'
22
+ """
23
+ kind, name = spec.split(":", 1) # Split string to get model type and name
24
+
25
+ if kind == "ollama":
26
+ from stratego.models.ollama_model import OllamaAgent
27
+ # Define the temperature value explicitly
28
+ AGENT_TEMPERATURE = 0.2
29
+
30
+ # Create the Ollama agent
31
+ agent = OllamaAgent(
32
+ model_name=name,
33
+ temperature=AGENT_TEMPERATURE,
34
+ num_predict=128, # Allow enough tokens for a complete move response
35
+ prompt_pack=get_prompt_pack(prompt_name) # Load strategy prompt
36
+ )
37
+
38
+ # Store temperature for logging
39
+ agent.temperature = AGENT_TEMPERATURE
40
+
41
+ return agent
42
+ if kind == "hf":
43
+ from stratego.models.hf_model import HFLocalAgent
44
+ return HFLocalAgent(model_id=name, prompt_pack=prompt_name)
45
+ raise ValueError(f"Unknown agent spec: {spec}")
46
+
47
+ def print_board(observation: str, size: int = 10):
48
+ block = extract_board_block_lines(observation, size)
49
+ if block:
50
+ print("\n".join(block))
51
+
52
+ # --- Main Command Line Interface (CLI) ---
53
+ def cli():
54
+ DEFAULT_ENV = "Stratego-v0"
55
+ DUEL_ENV = "Stratego-duel"
56
+ CUSTOM_ENV = "Stratego-custom"
57
+ tracker = MoveTrackerClass()
58
+ p = argparse.ArgumentParser()
59
+ p.add_argument("--p0", default="ollama:deepseek-r1:32b")
60
+ p.add_argument("--p1", default="ollama:gemma3:1b")
61
+ # UPDATED HELP TEXT to explain how this parameter relates to VRAM utilization
62
+ # For large models (120B, 70B), you MUST set this value based on available VRAM(13 Nov 2025)
63
+ # UPDATED GPU arguments for VRAM control (now defaults to CPU-only)
64
+ p.add_argument("--p0-num-gpu", type=int, default=0,
65
+ help="Number of GPU layers to offload for Player 0. Default is 0 (CPU-only mode). Use a positive number (e.g., 50) to offload layers to GPU/VRAM, or 999 for maximum GPU use.")
66
+ p.add_argument("--p1-num-gpu", type=int, default=0,
67
+ help="Number of GPU layers to offload for Player 1. Default is 0 (CPU-only mode). Use a positive number (e.g., 40) to offload layers to GPU/VRAM, or 999 for maximum GPU use.")
68
+ #(13 Nov 2025) NOTE: Default env_id is used as a flag to trigger the interactive menu
69
+ p.add_argument("--prompt", default="base", help="Prompt preset name (e.g. base|concise|adaptive)")
70
+ p.add_argument("--env_id", default=DEFAULT_ENV, help="TextArena environment id")
71
+ p.add_argument("--log-dir", default="logs", help="Directory for per-game CSV logs")
72
+ p.add_argument("--game-id", default=None, help="Optional custom game id in CSV filename")
73
+ p.add_argument("--size", type=int, default=10, help="Board size NxN")
74
+ p.add_argument("--max-turns", type=int, default=None, help="Maximum turns before stopping (for testing). E.g., --max-turns 10")
75
+
76
+ args = p.parse_args()
77
+
78
+ #(13 Nov 2025) --- INTERACTIVE ENVIRONMENT SELECTION ---
79
+ if args.env_id == DEFAULT_ENV:
80
+ print("\n--- Stratego Version Selection ---")
81
+ print(f"1. Standard Game ({DEFAULT_ENV})")
82
+ print(f"2. Duel Mode ({DUEL_ENV})")
83
+ print(f"3. Custom Mode ({CUSTOM_ENV})")
84
+
85
+ while True:
86
+ choice = input("Enter your choice (1, 2, or 3): ").strip()
87
+ if not choice or choice == '1':
88
+ print(f"Selected: {DEFAULT_ENV}")
89
+ break
90
+ elif choice == '2':
91
+ args.env_id = DUEL_ENV
92
+ args.size = 6
93
+ print(f"Selected: {DUEL_ENV}")
94
+ break
95
+ elif choice == '3':
96
+ # [CHANGE] Updated prompt range description
97
+ board = input("Please enter your custom board size in range of 4~9: ").strip()
98
+ # [CHANGE] Added '4' and '5' to valid options
99
+ if board in ['4', '5', '6', '7', '8', '9']:
100
+ args.env_id = CUSTOM_ENV
101
+ args.size = int(board)
102
+ print(f"Selected: {CUSTOM_ENV} with size {args.size}x{args.size}")
103
+ break
104
+ else:
105
+ print("Invalid choice.")
106
+ else:
107
+ print("Invalid choice.")
108
+
109
+ # --- Setup Game ---
110
+ agents = {
111
+ 0: build_agent(args.p0, args.prompt),
112
+ 1: build_agent(args.p1, args.prompt),
113
+ }
114
+ # Check if it is really normal Stratego version
115
+ if (args.env_id == CUSTOM_ENV):
116
+ env = StrategoEnv(env_id=CUSTOM_ENV, size=args.size)
117
+ game_type = "custom"
118
+ elif (args.env_id == DUEL_ENV):
119
+ env = StrategoEnv(env_id=DUEL_ENV)
120
+ game_type = "duel"
121
+ args.size = 6 # Duel mode uses 6x6 board
122
+ else:
123
+ env = StrategoEnv()
124
+ game_type = "standard"
125
+ env.reset(num_players=2)
126
+
127
+ # Track game start time
128
+ game_start_time = time.time()
129
+
130
+ # Simple move history tracker (separate for each player)
131
+ move_history = {0: [], 1: []}
132
+
133
+ with GameLogger(out_dir=args.log_dir, game_id=args.game_id, prompt_name=args.prompt, game_type=game_type, board_size=args.size) as logger:
134
+ for pid in (0, 1):
135
+ if hasattr(agents[pid], "logger"):
136
+ agents[pid].logger = logger
137
+ agents[pid].player_id = pid
138
+
139
+ done = False
140
+ turn = 0
141
+ print("\n--- Stratego LLM Match Started ---")
142
+ print(f"Player 1 Agent: {agents[0].model_name}")
143
+ print(f"Player 2 Agent: {agents[1].model_name}")
144
+ if args.max_turns:
145
+ print(f"⏱️ Max turns limit: {args.max_turns} (testing mode)")
146
+ print()
147
+ while not done:
148
+ # Check max turns limit
149
+ if args.max_turns and turn >= args.max_turns:
150
+ print(f"\n⏱️ Reached max turns limit ({args.max_turns}). Stopping game early.")
151
+ break
152
+
153
+ player_id, observation = env.get_observation()
154
+ current_agent = agents[player_id]
155
+ player_display = f"Player {player_id+1}"
156
+ model_name = current_agent.model_name
157
+
158
+ # --- NEW LOGGING FOR TURN, PLAYER, AND MODEL ---
159
+ print(f"\n>>>> TURN {turn}: {player_display} ({model_name}) is moving...")
160
+
161
+ if (args.size == 10):
162
+ print_board(observation)
163
+ else:
164
+ print_board(observation, args.size)
165
+ # Pass recent move history to agent
166
+ current_agent.set_move_history(move_history[player_id][-10:])
167
+ history_str = tracker.to_prompt_string(player_id)
168
+
169
+ # --- [CHANGE] INJECT AGGRESSION WARNING ---
170
+ # If the game drags on (e.g. > 20 turns), force them to wake up
171
+ if turn > 20:
172
+ observation += "\n\n[SYSTEM MESSAGE]: The game is stalling. You MUST ATTACK or ADVANCE immediately. Passive play is forbidden."
173
+
174
+ if turn > 50:
175
+ observation += "\n[CRITICAL]: STOP MOVING BACK AND FORTH. Pick a piece and move it FORWARD now."
176
+ # ------------------------------------------
177
+
178
+ observation = observation + history_str
179
+ # print(tracker.to_prompt_string(player_id))
180
+ lines = history_str.strip().splitlines()
181
+ if len(lines) <= 1:
182
+ print(history_str)
183
+ else:
184
+ header = lines[0:1]
185
+ body = lines[1:]
186
+ tail = body[-5:] # Show only last 5 moves
187
+ print("\n".join(header + tail))
188
+
189
+ # The agent (LLM) generates the action, retry a few times; fallback to available moves
190
+ action = ""
191
+ max_agent_attempts = 3
192
+ for attempt in range(max_agent_attempts):
193
+ action = current_agent(observation)
194
+ if action:
195
+ break
196
+ print(f"[TURN {turn}] {model_name} failed to produce a move (attempt {attempt+1}/{max_agent_attempts}). Retrying...")
197
+
198
+ if not action:
199
+ legal = extract_legal_moves(observation)
200
+ forbidden = set(extract_forbidden(observation))
201
+ legal_filtered = [m for m in legal if m not in forbidden] or legal
202
+ if legal_filtered:
203
+ action = random.choice(legal_filtered)
204
+ print(f"[TURN {turn}] Fallback to random available move: {action}")
205
+ else:
206
+ print(f"[TURN {turn}] No legal moves available for fallback; ending game loop.")
207
+ break
208
+
209
+ # --- NEW LOGGING FOR STRATEGY/MODEL DECISION ---
210
+ print(f" > AGENT DECISION: {model_name} -> {action}")
211
+ print(f" > Strategy/Model: Ollama Agent (T={current_agent.temperature}, Prompt='{args.prompt}')")
212
+
213
+ # Extract move details for logging
214
+ move_pattern = r'\[([A-J]\d+)\s+([A-J]\d+)\]'
215
+ match = re.search(move_pattern, action)
216
+ # src_pos = match.group(1) if match else ""
217
+ # dst_pos = match.group(2) if match else ""
218
+
219
+ # # Get piece type from board (simplified extraction)
220
+ # piece_type = ""
221
+ # if src_pos and hasattr(env, 'game_state') and hasattr(env.game_state, 'board'):
222
+ # try:
223
+ # # Parse position like "D4" -> row=3, col=3
224
+ # col = ord(src_pos[0]) - ord('A')
225
+ # row = int(src_pos[1:]) - 1
226
+ # piece = env.game_state.board[row][col]
227
+ # if piece and hasattr(piece, 'rank_name'):
228
+ # piece_type = piece.rank_name
229
+ # except:
230
+ # piece_type = "Unknown"
231
+
232
+ # # Check if this is a repeated move (last 3 moves)
233
+ # was_repeated = False
234
+ # recent_moves = [m["move"] for m in move_history[player_id][-3:]]
235
+ # if action in recent_moves:
236
+ # was_repeated = True
237
+
238
+ # Record this move in history
239
+ move_history[player_id].append({
240
+ "turn": turn,
241
+ "move": action,
242
+ "text": f"Turn {turn}: You played {action}"
243
+ })
244
+
245
+ # Process move details for logging BEFORE making the environment step
246
+ move_details = process_move(
247
+ action=action,
248
+ board=env.env.board,
249
+ observation=observation,
250
+ player_id=player_id
251
+ )
252
+
253
+ # Execute the action exactly once in the environment
254
+ done, info = env.step(action=action)
255
+
256
+ # Determine battle outcome by checking if target piece was there
257
+ battle_outcome = ""
258
+ if move_details.target_piece:
259
+ # There was a piece at destination, so battle occurred
260
+ # Check what's at destination now to determine outcome
261
+ dst_row = ord(move_details.dst_pos[0]) - ord('A')
262
+ dst_col = int(move_details.dst_pos[1:])
263
+ cell_after = env.env.board[dst_row][dst_col]
264
+
265
+ if cell_after is None:
266
+ # Both pieces removed = draw
267
+ battle_outcome = "draw"
268
+ elif isinstance(cell_after, dict):
269
+ if cell_after.get('player') == player_id:
270
+ battle_outcome = "won"
271
+ else:
272
+ battle_outcome = "lost"
273
+
274
+ # Extract outcome from environment observation
275
+ outcome = "move"
276
+ # captured = ""
277
+ obs_text = ""
278
+ # if isinstance(info, (list, tuple)) and len(info) > 1:
279
+ # obs_text = str(info[1])
280
+ # else:
281
+ # obs_text = str(info)
282
+ if isinstance(info, (list, tuple)):
283
+ if 0 <= player_id < len(info):
284
+ obs_text = str(info[player_id])
285
+ else:
286
+ obs_text = " ".join(str(x) for x in info)
287
+ else:
288
+ obs_text = str(info)
289
+
290
+ low = obs_text.lower()
291
+ if "invalid" in low or "illegal" in low:
292
+ outcome = "invalid"
293
+ elif "captured" in low or "won the battle" in low:
294
+ outcome = "won_battle"
295
+ elif "lost the battle" in low or "defeated" in low:
296
+ outcome = "lost_battle"
297
+ elif "draw" in low or "tie" in low:
298
+ outcome = "draw"
299
+
300
+ event = info.get("event") if isinstance(info, dict) else None
301
+ extra = info.get("detail") if isinstance(info, dict) else None
302
+
303
+ if outcome != "invalid":
304
+ # Record this move in history
305
+ move_history[player_id].append({
306
+ "turn": turn,
307
+ "move": action,
308
+ "text": f"Turn {turn}: You played {action}"
309
+ })
310
+
311
+ tracker.record(
312
+ player=player_id,
313
+ move=action,
314
+ event=event,
315
+ extra=extra
316
+ )
317
+ else:
318
+ move_history[player_id].append({
319
+ "turn": turn,
320
+ "move": action,
321
+ "text": f"Turn {turn}: INVALID move {action}"
322
+ })
323
+ tracker.record(
324
+ player=player_id,
325
+ move=action,
326
+ event="invalid_move",
327
+ extra=extra
328
+ )
329
+ print(f"[HISTORY] Skipping invalid move from history: {action}")
330
+
331
+ logger.log_move(turn=turn,
332
+ player=player_id,
333
+ model_name=getattr(current_agent, "model_name", "unknown"),
334
+ move=action,
335
+ src=move_details.src_pos,
336
+ dst=move_details.dst_pos,
337
+ piece_type=move_details.piece_type,
338
+ board_state=move_details.board_state,
339
+ available_moves=move_details.available_moves,
340
+ move_direction=move_details.move_direction,
341
+ target_piece=move_details.target_piece,
342
+ battle_outcome=battle_outcome,
343
+ )
344
+ turn += 1
345
+
346
+
347
+ # --- Game Over & Winner Announcement ---
348
+ rewards, game_info = env.close()
349
+ print("\n" + "="*50)
350
+ print("--- GAME OVER ---")
351
+ game_duration = time.time() - game_start_time
352
+ # Print summary
353
+ print(f"\nGame finished. Duration: {int(game_duration // 60)}m {int(game_duration % 60)}s")
354
+ print(f"Result: {rewards} | {game_info}")
355
+
356
+ # Logic to declare the specific winner based on rewards
357
+ # Rewards are usually {0: 1, 1: -1} (P0 Wins) or {0: -1, 1: 1} (P1 Wins)
358
+ p0_score = rewards.get(0, 0)
359
+ p1_score = rewards.get(1, 0)
360
+ winner = None
361
+ game_result = ""
362
+
363
+ if p0_score > p1_score:
364
+ winner = 0
365
+ game_result = "player0"
366
+ print(f"\n🏆 * * * PLAYER 0 WINS! * * * 🏆")
367
+ print(f"Agent: {agents[0].model_name}")
368
+ elif p1_score > p0_score:
369
+ winner = 1
370
+ game_result = "player1"
371
+ print(f"\n🏆 * * * PLAYER 1 WINS! * * * 🏆")
372
+ print(f"Agent: {agents[1].model_name}")
373
+ else:
374
+ game_result = "draw"
375
+ print(f"\n🤝 * * * IT'S A DRAW! * * * 🤝")
376
+
377
+ print("\nDetails:")
378
+ print(f"Final Rewards: {rewards}")
379
+ print(f"Game Info: {game_info}")
380
+
381
+ try:
382
+ invalid_players = [
383
+ pid for pid, info_dict in (game_info or {}).items()
384
+ if isinstance(info_dict, dict) and info_dict.get("invalid_move")
385
+ ]
386
+ if invalid_players:
387
+ import csv
388
+ csv_path = logger.path
389
+ rows = []
390
+ fieldnames = None
391
+
392
+ with open(csv_path, "r", encoding="utf-8", newline="") as f:
393
+ reader = csv.DictReader(f)
394
+ fieldnames = reader.fieldnames
395
+ for r in reader:
396
+ rows.append(r)
397
+
398
+ if rows and fieldnames and "outcome" in fieldnames:
399
+ rows[-1]["outcome"] = "invalid"
400
+ with open(csv_path, "w", encoding="utf-8", newline="") as f:
401
+ writer = csv.DictWriter(f, fieldnames=fieldnames)
402
+ writer.writeheader()
403
+ writer.writerows(rows)
404
+
405
+ print("\n[LOG PATCH] Last move outcome patched to 'invalid' "
406
+ f"(player {invalid_players[0]} made an invalid move).")
407
+
408
+ except Exception as e:
409
+ print(f"[LOG PATCH] Failed to patch CSV outcome: {e}")
410
+
411
+ # Finalize the game log with winner info in every row
412
+ logger.finalize_game(winner=winner, game_result=game_result)
413
+
414
+ # LLM analyzes the game CSV and updates prompt
415
+ analyze_and_update_prompt(
416
+ csv_path=logger.path,
417
+ prompts_dir="stratego/prompts",
418
+ logs_dir=args.log_dir,
419
+ model_name="mistral:7b", # Analysis model
420
+ models_used=[agents[0].model_name, agents[1].model_name],
421
+ game_duration_seconds=game_duration,
422
+ winner=winner,
423
+ total_turns=turn - 1
424
+ )
425
+
426
+ # Auto-push game data to Hugging Face Hub
427
+ print("\nSyncing game data to Hugging Face...")
428
+ auto_push_after_game(
429
+ logs_dir=os.path.join(args.log_dir, "games"),
430
+ repo_id="STRATEGO-LLM-TRAINING/stratego",
431
+ )