-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
322 lines (258 loc) · 9.09 KB
/
main.py
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"""
Machine trained to play TicTacToe with Alpha Monte Carlo Tree Search
"""
# Importing dependencies
import numpy as np
from montecarlo import MCTS
import torch
import matplotlib.pyplot as plt
from model import ResNet
from alphamontecarlo import AlphaMCTS
from alphazero import AlphaZero
from games import TicTacToe, ConnectFour
from parallelalphazero import AlphaZeroParallel
import kaggle_environments
from kaggle import KaggleAgent
# Setting manual seed for consistency
torch.manual_seed(0)
# Function to play tictactoe with human input
def play_tictactoe():
tictactoe = TicTacToe()
player = 1
state = tictactoe.get_initial_state()
while True:
print(state)
valid_moves = tictactoe.get_valid_moves(state)
print("valid moves", [i+1 for i in range(tictactoe.action_size) if valid_moves[i] == 1])
action = int(input(f"{player}:")) - 1
if valid_moves[action] == 0:
print("Invalid move, Try again")
continue
state = tictactoe.get_next_state(state, action, player)
value, is_terminated = tictactoe.check_win_and_termination(state, action)
if is_terminated:
print(state)
if value == 1:
print(player, "Won")
else:
print("Draw")
break
player = tictactoe.get_opponent(player)
# Play Tictactoe with the MCTS algorithm
def mcts_tictactoe():
tictactoe = TicTacToe()
player = 1
args = {
'C': 1.41,
'num_searches': 1000
}
mcts = MCTS(tictactoe, args)
state = tictactoe.get_initial_state()
while True:
print(state)
if player == 1:
valid_moves = tictactoe.get_valid_moves(state)
print("valid moves", [i+1 for i in range(tictactoe.action_size) if valid_moves[i] == 1])
action = int(input(f"{player}:")) - 1
if valid_moves[action] == 0:
print("Invalid move, Try again")
continue
# Have the action done by MCTS when it's the second player's turn
else:
neutral_state = tictactoe.change_perspective(state, player)
mcts_probs = mcts.search(neutral_state)
action = np.argmax(mcts_probs)
state = tictactoe.get_next_state(state, action, player)
value, is_terminated = tictactoe.check_win_and_termination(state, action)
if is_terminated:
print(state)
if value == 1:
print(player, "Won")
else:
print("Draw")
break
player = tictactoe.get_opponent(player)
# Function to visualize output from the model
def model_visualize():
tictactoe = TicTacToe()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
state = tictactoe.get_initial_state()
state = tictactoe.get_next_state(state, 2, 1)
state = tictactoe.get_next_state(state, 6, -1)
state = tictactoe.get_next_state(state, 8, 1)
print("State is currently", state)
tensor_state = torch.tensor(tictactoe.get_encoded_state(state), device=device).unsqueeze(0)
model = ResNet(tictactoe, 4, 64, device=device)
model.load_state_dict(torch.load('models/TicTacToe/model_colab_2.pt', map_location=device))
model.eval()
policy, value = model(tensor_state)
policy = torch.softmax(policy, axis=1).squeeze(0).detach().cpu().numpy()
plt.bar(range(tictactoe.action_size), policy)
plt.show()
# Play Tictactoe with the Alpha MCTS algorithm output
def alpha_mcts_tictactoe():
tictactoe = TicTacToe()
player = 1
args = {
'C': 2,
'num_searches': 1000
}
model = ResNet(tictactoe, 4, 64)
model.eval()
mcts = AlphaMCTS(tictactoe, args, model)
state = tictactoe.get_initial_state()
while True:
print(state)
if player == 1:
valid_moves = tictactoe.get_valid_moves(state)
print("valid moves", [i for i in range(tictactoe.action_size) if valid_moves[i] == 1])
action = int(input(f"{player}:"))
if valid_moves[action] == 0:
print("Invalid move, Try again")
continue
# Have the action done by MCTS when it's the second player's turn
else:
neutral_state = tictactoe.change_perspective(state, player)
mcts_probs = mcts.search(neutral_state)
action = np.argmax(mcts_probs)
state = tictactoe.get_next_state(state, action, player)
value, is_terminated = tictactoe.check_win_and_termination(state, action)
if is_terminated:
print(state)
if value == 1:
print(player, "Won")
else:
print("Draw")
break
player = tictactoe.get_opponent(player)
# Function to train the AlphaZero model for TicTacToe
def alphaTrainTicTacToe():
game = TicTacToe()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ResNet(game, 4, 64, device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.0001)
args = {
'C': 2,
'num_searches': 60,
'num_iterations': 4,
'num_selfPlay_iterations': 500,
'num_epochs': 4,
'batch_size': 64,
'temperature': 1.25,
'dirichlet_epsilon': 0.25,
'dirichlet_alpha': 0.3
}
alphaZero = AlphaZero(model, optimizer, game, args)
alphaZero.learn()
# Function to train the AlphaZero model for ConnectFour
def alphaTrainConnectFour():
game = ConnectFour()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ResNet(game, 9, 128, device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.0001)
args = {
'C': 2,
'num_searches': 600,
'num_iterations': 8,
'num_selfPlay_iterations': 500,
'num_epochs': 4,
'batch_size': 128,
'temperature': 1.25,
'dirichlet_epsilon': 0.25,
'dirichlet_alpha': 0.3
}
alphaZero = AlphaZero(model, optimizer, game, args)
alphaZero.learn()
# Parallel ConnectFour Trainer
def alphaTrainConnectFourParallel():
game = ConnectFour()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ResNet(game, 9, 128, device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.0001)
args = {
'C': 2,
'num_searches': 600,
'num_iterations': 8,
'num_selfPlay_iterations': 600,
'num_epochs': 4,
'num_parallel_games': 200,
'batch_size': 128,
'temperature': 1.25,
'dirichlet_epsilon': 0.25,
'dirichlet_alpha': 0.3
}
alphaZero = AlphaZeroParallel(model, optimizer, game, args)
alphaZero.learn()
# Parallel ConnectFour Trainer
def alphaTrainTicTacToeParallel():
game = TicTacToe()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ResNet(game, 4, 64, device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.0001)
args = {
'C': 2,
'num_searches': 60,
'num_iterations': 4,
'num_selfPlay_iterations': 500,
'num_parallel_games': 100,
'num_epochs': 4,
'batch_size': 64,
'temperature': 1.25,
'dirichlet_epsilon': 0.25,
'dirichlet_alpha': 0.3
}
alphaZero = AlphaZeroParallel(model, optimizer, game, args)
alphaZero.learn()
# Dynamic Visualization of ConnectFour
def ConnectFourVisualizer():
game = ConnectFour()
args = {
'C': 2,
'search': True,
'num_searches': 600,
'dirichlet_epsilon': 0.1,
'dirichlet_alpha': 0.3,
'temperature': 0,
}
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ResNet(game, 9, 128, device)
model.load_state_dict(torch.load("models/ConnectFour/model_4.pt", map_location=device))
model.eval()
env = kaggle_environments.make("connectx")
player1 = KaggleAgent(model, game, args)
player2 = KaggleAgent(model, game, args)
players = [player1.run, "random"]
env.run(players)
out = env.render(mode='html')
file = open("output_random_vs_agent.html", "w")
file.write(out)
file.close()
# Dynamic Visualization of TicTacToe
def TicTacToeVisualizer():
game = TicTacToe()
args = {
'C': 2,
'search': True,
'num_searches': 60,
'dirichlet_epsilon': 0.1,
'dirichlet_alpha': 0.3,
'temperature': 0,
}
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ResNet(game, 4, 64, device)
model.load_state_dict(torch.load("models/TicTacToe/model_3.pt", map_location=device))
model.eval()
env = kaggle_environments.make("tictactoe")
player1 = KaggleAgent(model, game, args)
player2 = KaggleAgent(model, game, args)
players = [player1.run, player2.run]
env.run(players)
out = env.render(mode='html')
file = open("output_tictactoe_agent_vs_agent.html", "w")
file.write(out)
file.close()
# Main function
def main():
ConnectFourVisualizer()
if __name__ == '__main__':
main()