-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcircleGame.py
143 lines (117 loc) · 5.47 KB
/
circleGame.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
import time
import torch
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import yaml
import utils
class CircleGame(torch.nn.Module):
def __init__(self, n_players):
super().__init__()
self.n_players = n_players
self.action_dim = 1
self.action_space = torch.linspace(-np.pi, np.pi, 100)
self.register_parameter('x', torch.nn.Parameter(torch.randn(n_players, 2)))
self.register_parameter('log_s', torch.nn.Parameter(torch.randn(n_players)))
def get_strategy(self):
mus = torch.atan2(self.x[:, 1], self.x[:, 0])
sigmas = torch.exp(self.log_s)
strategies = torch.zeros(self.n_players, self.action_dim)
for i in range(self.n_players):
strategies[i] = torch.distributions.von_mises.VonMises(mus[i], sigmas[i]).sample().requires_grad_()
return strategies
def dist(self, a, b):
diff = torch.clamp(torch.abs(a-b), 0, np.pi)/2
return 2*torch.sin(diff)
def forward(self, actions):
rotated_actions = torch.cat((actions[:,1:],actions[:,:1]),dim=1)
rewards = - self.dist(actions,rotated_actions)
rewards[:,-1] *= -1
return rewards
def init_actions(self, n_ensembles):
actions = torch.zeros((n_ensembles, self.n_players, self.action_dim))
for i in range(n_ensembles):
actions[i] = self.get_strategy()
# self.register_parameter('actions', torch.nn.Parameter(actions))
return actions
def mix(strategy, epsilon):
return (1 - epsilon) * strategy.max(dim=1).values + epsilon * strategy.sum(dim=1)
def train(game,n_iter=1000, lr=1e-3, eps=1e-3, n_ensembles=500):
strategies = game.get_strategy().requires_grad_()
strategies = torch.nn.Parameter(strategies)
action_samples = game.init_actions(n_ensembles).requires_grad_()
action_samples = torch.nn.Parameter(action_samples)
optimizer_strat = torch.optim.Adam([strategies], lr=lr)
optimizer_action = torch.optim.Adam([action_samples], lr=lr)
scheduler_strat = torch.optim.lr_scheduler.StepLR(optimizer_strat, step_size=config['hyperparameters']['step_size'], gamma=config['hyperparameters']['gamma'])
scheduler_action = torch.optim.lr_scheduler.StepLR(optimizer_action, step_size=config['hyperparameters']['step_size'], gamma=config['hyperparameters']['gamma'])
plot=utils.Plotter()
logger=utils.Logger(['Exploitability'])
iter_exploitabilities = []
progress_bar = tqdm(range(n_iter), desc='Training', unit='iter', unit_scale=True)
for j in progress_bar:
optimizer_action.zero_grad()
optimizer_strat.zero_grad()
strategies_ = torch.pi* torch.tanh(strategies)
action_samples_ = torch.pi* torch.tanh(action_samples)
reward_strategy = game.forward(strategies_).to(device)
ensemble_reward = torch.zeros((game.n_players,n_ensembles,game.action_dim), device=device)
for i in range(game.n_players):
repeated_strategies = strategies_.repeat(n_ensembles, 1, 1)
repeated_strategies[:, i, :] = action_samples_[:, i, :]
ensemble_reward[i] = game.forward(repeated_strategies)[:,i,:]
max_strategy = ensemble_reward.max(dim=1).values.to(device)
mix_strategy = mix(ensemble_reward, eps)
loss_max = - torch.mean(torch.abs(max_strategy - reward_strategy))
loss_mix = torch.mean(torch.abs(mix_strategy - reward_strategy.detach()))
(loss_max + loss_mix).backward()
loss_max = - loss_max.detach()
optimizer_strat.step()
optimizer_action.step()
scheduler_strat.step()
scheduler_action.step()
iter_exploitabilities.append([loss_max.item(),loss_mix.item()])
logger.lossLog({'Exploitability': loss_max.item()})
progress_bar.set_postfix({'time': time.time() - progress_bar.start_t, 'loss_max': loss_max.item()})
return torch.pi*torch.tanh(strategies), iter_exploitabilities
# import config.yaml to set hyperparameters
with open('config.yaml') as f:
config = yaml.load(f, Loader=yaml.FullLoader)
torch.manual_seed(config['hyperparameters']['seed'])
np.random.seed(config['hyperparameters']['seed'])
n_iter = config['hyperparameters']['epochs']
lr = config['hyperparameters']['learning_rate']
n_ensembles = config['hyperparameters']['n_ensembles']
eps = config['hyperparameters']['eps']
players = config['hyperparameters']['players']
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
game = CircleGame(n_players=players).to(device)
t = time.time()
strategies, exploitabilities = train(game, n_iter=n_iter, lr=lr, eps =eps, n_ensembles=n_ensembles)
t = time.time() - t
# print strategies
print(f"strategies: {strategies.detach().numpy()}")
max_loss = [x[0] for x in exploitabilities]
mix_loss = [x[1] for x in exploitabilities]
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title("Exploitability Max Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.plot(max_loss)
plt.subplot(1, 2, 2)
plt.title("Mix Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.plot(mix_loss)
name = f"circleGame {n_iter} {players} {n_ensembles} {lr} {eps}".replace(".", "_")
plt.savefig(f"Results/rpaper/{name}.png")
# save results
with open(f"Results/rpaper/{name}.txt", "w") as f:
# write config
f.write(f"config: {config}\n")
f.write(f"max_loss: {max_loss[-1]}\n")
f.write(f"mix_loss: {mix_loss[-1]}\n")
f.write(f"strategies: {strategies.detach().numpy()}")
f.write(f"Time taken: {t:.4f} seconds\n")