-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
75 lines (50 loc) · 2.06 KB
/
Copy pathagent.py
File metadata and controls
75 lines (50 loc) · 2.06 KB
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
import chess
import torch
import config
from mcts import MCTS
from node import Node
from model import RLModel
class Agent:
def __init__(self, player=chess.BLACK, model_path=None, compile = False, stochastic:bool=True):
if model_path is not None:
self.model = RLModel(config.INPUT_SHAPE, config.OUTPUT_SHAPE) ## intialize a model
self.model.load_state_dict(torch.load(model_path))
else:
self.model = self.build_model()
if compile:
self.model = torch.compile(self.model)
self.root = Node(chess.Board(), winner=None, terminal=False)
self.player = player
self.mcts = MCTS(self, player=self.player, exploration_weight=config.EXPLORATION_WEIGHT, stochastic=stochastic)
def set_root(self, board):
self.root = Node(board, winner=None, terminal=False)
def build_model(self):
"""
Build a new model based on the configuration in config.py
"""
self.model = RLModel(config.INPUT_SHAPE, config.OUTPUT_SHAPE)
return self.model
def run_simulations(self, n :int = 50):
'''
Run n simulations of the MCTS algorithm. This function gets called every move.
'''
print(f"Running {n} simulations...", end='\r')
self.mcts.run_simulation(n, self.root)
def get_moves(self):
return self.mcts.get_possible_moves(self.root)
def get_best_move(self):
return self.mcts.choose(self.root)
def save_model(self, path):
'''
Save the current model to the specified path
'''
torch.save(self.model.state_dict(), path)
def predict(self, data):
'''
Predict the value head an policy head for the given state
'''
# TODO: needs to properly set the model.train() and model.eval() as well as check for gradients
if not torch.is_tensor(data):
data = torch.Tensor(data)
(p, v), _, _, _ = self.model(data)
return p, v