-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathoption_critic.py
243 lines (193 loc) · 8.45 KB
/
option_critic.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
import torch
import torch.nn as nn
from torch.distributions import Categorical, Bernoulli
from math import exp
import numpy as np
from utils import to_tensor
class OptionCriticConv(nn.Module):
def __init__(self,
in_features,
num_actions,
num_options,
temperature=1.0,
eps_start=1.0,
eps_min=0.1,
eps_decay=int(1e6),
eps_test=0.05,
device='cpu',
testing=False):
super(OptionCriticConv, self).__init__()
self.in_channels = in_features
self.num_actions = num_actions
self.num_options = num_options
self.magic_number = 7 * 7 * 64
self.device = device
self.testing = testing
self.temperature = temperature
self.eps_min = eps_min
self.eps_start = eps_start
self.eps_decay = eps_decay
self.eps_test = eps_test
self.num_steps = 0
self.features = nn.Sequential(
nn.Conv2d(self.in_channels, 32, kernel_size=8, stride=4),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=4, stride=2),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3, stride=1),
nn.ReLU(),
nn.modules.Flatten(),
nn.Linear(self.magic_number, 512),
nn.ReLU()
)
self.Q = nn.Linear(512, num_options) # Policy-Over-Options
self.terminations = nn.Linear(512, num_options) # Option-Termination
self.options_W = nn.Parameter(torch.zeros(num_options, 512, num_actions))
self.options_b = nn.Parameter(torch.zeros(num_options, num_actions))
self.to(device)
self.train(not testing)
def get_state(self, obs):
if obs.ndim < 4:
obs = obs.unsqueeze(0)
obs = obs.to(self.device)
state = self.features(obs)
return state
def get_Q(self, state):
return self.Q(state)
def predict_option_termination(self, state, current_option):
termination = self.terminations(state)[:, current_option].sigmoid()
option_termination = Bernoulli(termination).sample()
Q = self.get_Q(state)
next_option = Q.argmax(dim=-1)
return bool(option_termination.item()), next_option.item()
def get_terminations(self, state):
return self.terminations(state).sigmoid()
def get_action(self, state, option):
logits = state.data @ self.options_W[option] + self.options_b[option]
action_dist = (logits / self.temperature).softmax(dim=-1)
action_dist = Categorical(action_dist)
action = action_dist.sample()
logp = action_dist.log_prob(action)
entropy = action_dist.entropy()
return action.item(), logp, entropy
def greedy_option(self, state):
Q = self.get_Q(state)
return Q.argmax(dim=-1).item()
@property
def epsilon(self):
if not self.testing:
eps = self.eps_min + (self.eps_start - self.eps_min) * exp(-self.num_steps / self.eps_decay)
self.num_steps += 1
else:
eps = self.eps_test
return eps
class OptionCriticFeatures(nn.Module):
def __init__(self,
in_features,
num_actions,
num_options,
temperature=1.0,
eps_start=1.0,
eps_min=0.1,
eps_decay=int(1e6),
eps_test=0.05,
device='cpu',
testing=False):
super(OptionCriticFeatures, self).__init__()
self.in_features = in_features
self.num_actions = num_actions
self.num_options = num_options
self.device = device
self.testing = testing
self.temperature = temperature
self.eps_min = eps_min
self.eps_start = eps_start
self.eps_decay = eps_decay
self.eps_test = eps_test
self.num_steps = 0
self.features = nn.Sequential(
nn.Linear(in_features, 32),
nn.ReLU(),
nn.Linear(32, 64),
nn.ReLU()
)
self.Q = nn.Linear(64, num_options) # Policy-Over-Options
self.terminations = nn.Linear(64, num_options) # Option-Termination
self.options_W = nn.Parameter(torch.zeros(num_options, 64, num_actions))
self.options_b = nn.Parameter(torch.zeros(num_options, num_actions))
self.to(device)
self.train(not testing)
def get_state(self, obs):
if obs.ndim < 4:
obs = obs.unsqueeze(0)
obs = obs.to(self.device)
state = self.features(obs)
return state
def get_Q(self, state):
return self.Q(state)
def predict_option_termination(self, state, current_option):
termination = self.terminations(state)[:, current_option].sigmoid()
option_termination = Bernoulli(termination).sample()
Q = self.get_Q(state)
next_option = Q.argmax(dim=-1)
return bool(option_termination.item()), next_option.item()
def get_terminations(self, state):
return self.terminations(state).sigmoid()
def get_action(self, state, option):
logits = state.data @ self.options_W[option] + self.options_b[option]
action_dist = (logits / self.temperature).softmax(dim=-1)
action_dist = Categorical(action_dist)
action = action_dist.sample()
logp = action_dist.log_prob(action)
entropy = action_dist.entropy()
return action.item(), logp, entropy
def greedy_option(self, state):
Q = self.get_Q(state)
return Q.argmax(dim=-1).item()
@property
def epsilon(self):
if not self.testing:
eps = self.eps_min + (self.eps_start - self.eps_min) * exp(-self.num_steps / self.eps_decay)
self.num_steps += 1
else:
eps = self.eps_test
return eps
def critic_loss(model, model_prime, data_batch, args):
obs, options, rewards, next_obs, dones = data_batch
batch_idx = torch.arange(len(options)).long()
options = torch.LongTensor(options).to(model.device)
rewards = torch.FloatTensor(rewards).to(model.device)
masks = 1 - torch.FloatTensor(dones).to(model.device)
# The loss is the TD loss of Q and the update target, so we need to calculate Q
states = model.get_state(to_tensor(obs)).squeeze(0)
Q = model.get_Q(states)
# the update target contains Q_next, but for stable learning we use prime network for this
next_states_prime = model_prime.get_state(to_tensor(next_obs)).squeeze(0)
next_Q_prime = model_prime.get_Q(next_states_prime) # detach?
# Additionally, we need the beta probabilities of the next state
next_states = model.get_state(to_tensor(next_obs)).squeeze(0)
next_termination_probs = model.get_terminations(next_states).detach()
next_options_term_prob = next_termination_probs[batch_idx, options]
# Now we can calculate the update target gt
gt = rewards + masks * args.gamma * \
((1 - next_options_term_prob) * next_Q_prime[batch_idx, options] + next_options_term_prob * next_Q_prime.max(dim=-1)[0])
# to update Q we want to use the actual network, not the prime
td_err = (Q[batch_idx, options] - gt.detach()).pow(2).mul(0.5).mean()
return td_err
def actor_loss(obs, option, logp, entropy, reward, done, next_obs, model, model_prime, args):
state = model.get_state(to_tensor(obs))
next_state = model.get_state(to_tensor(next_obs))
next_state_prime = model_prime.get_state(to_tensor(next_obs))
option_term_prob = model.get_terminations(state)[:, option]
next_option_term_prob = model.get_terminations(next_state)[:, option].detach()
Q = model.get_Q(state).detach().squeeze()
next_Q_prime = model_prime.get_Q(next_state_prime).detach().squeeze()
# Target update gt
gt = reward + (1 - done) * args.gamma * \
((1 - next_option_term_prob) * next_Q_prime[option] + next_option_term_prob * next_Q_prime.max(dim=-1)[0])
# The termination loss
termination_loss = option_term_prob * (Q[option].detach() - Q.max(dim=-1)[0].detach() + args.termination_reg) * (1 - done)
# actor-critic policy gradient with entropy regularization
policy_loss = -logp * (gt.detach() - Q[option]) - args.entropy_reg * entropy
actor_loss = termination_loss + policy_loss
return actor_loss