-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrainer.py
238 lines (186 loc) · 8.51 KB
/
trainer.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
from collections import namedtuple
from inspect import getargspec
import numpy as np
import torch
from torch import optim
import torch.nn as nn
from utils import *
from action_utils import *
import itertools
Transition = namedtuple('Transition', ('state', 'action', 'action_out', 'value', 'episode_mask', 'episode_mini_mask', 'next_state', 'reward', 'misc'))
class Trainer(object):
def __init__(self, args, policy_net, env):
self.args = args
self.policy_net = policy_net
self.env = env
self.display = False
self.last_step = False
self.optimizer = optim.RMSprop(policy_net.parameters(),
lr = args.lrate, alpha=0.97, eps=1e-6)
self.params = [p for p in self.policy_net.parameters()]
def get_episode(self, epoch):
episode = []
reset_args = getargspec(self.env.reset).args
if 'epoch' in reset_args:
state = self.env.reset(epoch)
else:
state = self.env.reset()
should_display = self.display and self.last_step
if should_display:
self.env.display()
stat = dict()
info = dict()
switch_t = -1
prev_hid = torch.zeros(1, self.args.nagents, self.args.hid_size)
for t in range(self.args.max_steps):
misc = dict()
if t == 0:
prev_hid = self.policy_net.init_hidden(batch_size=state.shape[0])
x = [state, prev_hid]
action_out, value, prev_hid = self.policy_net(x, info)
if (t + 1) % self.args.detach_gap == 0:
prev_hid = (prev_hid[0].detach(), prev_hid[1].detach())
action = select_action(self.args, action_out)
action, actual = translate_action(self.args, self.env, action)
next_state, reward, done, info = self.env.step(actual)
if 'alive_mask' in info:
misc['alive_mask'] = info['alive_mask'].reshape(reward.shape)
else:
misc['alive_mask'] = np.ones_like(reward)
stat['reward'] = stat.get('reward', 0) + reward[:self.args.nfriendly]
if hasattr(self.args, 'enemy_comm') and self.args.enemy_comm:
stat['enemy_reward'] = stat.get('enemy_reward', 0) + reward[self.args.nfriendly:]
done = done or t == self.args.max_steps - 1
episode_mask = np.ones(reward.shape)
episode_mini_mask = np.ones(reward.shape)
if done:
episode_mask = np.zeros(reward.shape)
else:
if 'is_completed' in info:
episode_mini_mask = 1 - info['is_completed'].reshape(-1)
if should_display:
self.env.display()
trans = Transition(state, action, action_out, value, episode_mask, episode_mini_mask, next_state, reward, misc)
episode.append(trans)
state = next_state
if done:
break
stat['num_steps'] = t + 1
stat['steps_taken'] = stat['num_steps']
if hasattr(self.env, 'reward_terminal'):
reward = self.env.reward_terminal()
episode[-1] = episode[-1]._replace(reward = episode[-1].reward + reward)
stat['reward'] = stat.get('reward', 0) + reward[:self.args.nfriendly]
if hasattr(self.args, 'enemy_comm') and self.args.enemy_comm:
stat['enemy_reward'] = stat.get('enemy_reward', 0) + reward[self.args.nfriendly:]
if hasattr(self.env, 'get_stat'):
merge_stat(self.env.get_stat(), stat)
return (episode, stat)
def compute_grad(self, batch):
stat = dict()
# num_actions: number of discrete actions in the action space
num_actions = self.args.num_actions
# dim_actions: number of action heads
dim_actions = self.args.dim_actions
n = self.args.nagents
batch_size = len(batch.state)
# rewards: [batch_size * n]
rewards = torch.Tensor(batch.reward)
# episode_mask: [batch_size * n]
episode_masks = torch.Tensor(batch.episode_mask)
# episode_mini_mask: [batch_size * n]
episode_mini_masks = torch.Tensor(batch.episode_mini_mask)
actions = torch.Tensor(batch.action)
# actions: [batch_size * n * dim_actions] have been detached
actions = actions.transpose(1, 2).view(-1, n, dim_actions)
values = torch.cat(batch.value, dim=0)
action_out = list(zip(*batch.action_out))
action_out = [torch.cat(a, dim=0) for a in action_out]
# alive_masks: [batch_size * n]
alive_masks = torch.Tensor(np.concatenate([item['alive_mask'] for item in batch.misc])).view(-1)
coop_returns = torch.Tensor(batch_size, n)
ncoop_returns = torch.Tensor(batch_size, n)
returns = torch.Tensor(batch_size, n)
deltas = torch.Tensor(batch_size, n)
advantages = torch.Tensor(batch_size, n)
values = values.view(batch_size, n)
prev_coop_return = 0
prev_ncoop_return = 0
prev_value = 0
prev_advantage = 0
for i in reversed(range(rewards.size(0))):
coop_returns[i] = rewards[i] + self.args.gamma * prev_coop_return * episode_masks[i]
ncoop_returns[i] = rewards[i] + self.args.gamma * prev_ncoop_return * episode_masks[i] * episode_mini_masks[i]
prev_coop_return = coop_returns[i].clone()
prev_ncoop_return = ncoop_returns[i].clone()
returns[i] = (self.args.mean_ratio * coop_returns[i].mean()) \
+ ((1 - self.args.mean_ratio) * ncoop_returns[i])
for i in reversed(range(rewards.size(0))):
advantages[i] = returns[i] - values.data[i]
if self.args.normalize_rewards:
advantages = (advantages - advantages.mean()) / advantages.std()
# element of log_p_a: [(batch_size*n) * num_actions[i]]
log_p_a = [action_out[i].view(-1, num_actions[i]) for i in range(dim_actions)]
# actions: [(batch_size*n) * dim_actions]
actions = actions.contiguous().view(-1, dim_actions)
if self.args.advantages_per_action:
# log_prob: [(batch_size*n) * dim_actions]
log_prob = multinomials_log_densities(actions, log_p_a)
# the log prob of each action head is multiplied by the advantage
action_loss = -advantages.view(-1).unsqueeze(-1) * log_prob
action_loss *= alive_masks.unsqueeze(-1)
else:
# log_prob: [(batch_size*n) * 1]
log_prob = multinomials_log_density(actions, log_p_a)
action_loss = -advantages.view(-1) * log_prob.squeeze()
action_loss *= alive_masks
action_loss = action_loss.sum()
stat['action_loss'] = action_loss.item()
# value loss term
targets = returns
value_loss = (values - targets).pow(2).view(-1)
value_loss *= alive_masks
value_loss = value_loss.sum()
stat['value_loss'] = value_loss.item()
loss = action_loss + self.args.value_coeff * value_loss
# entropy regularization term
entropy = 0
for i in range(len(log_p_a)):
entropy -= (log_p_a[i] * log_p_a[i].exp()).sum()
stat['entropy'] = entropy.item()
if self.args.entr > 0:
loss -= self.args.entr * entropy
loss.backward()
return stat
def run_batch(self, epoch):
batch = []
self.stats = dict()
self.stats['num_episodes'] = 0
while len(batch) < self.args.batch_size:
if self.args.batch_size - len(batch) <= self.args.max_steps:
self.last_step = True
episode, episode_stat = self.get_episode(epoch)
merge_stat(episode_stat, self.stats)
self.stats['num_episodes'] += 1
batch += episode
self.last_step = False
self.stats['num_steps'] = len(batch)
batch = Transition(*zip(*batch))
return batch, self.stats
def train_batch(self, epoch):
batch, stat = self.run_batch(epoch)
self.optimizer.zero_grad()
s = self.compute_grad(batch)
merge_stat(s, stat)
# for name, param in self.policy_net.named_parameters():
# print(name)
# print(param.grad)
for p in self.params:
if p._grad is not None:
p._grad.data /= stat['num_steps']
self.optimizer.step()
return stat
def state_dict(self):
return self.optimizer.state_dict()
def load_state_dict(self, state):
self.optimizer.load_state_dict(state)