-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrql.py
More file actions
executable file
·483 lines (442 loc) · 23.2 KB
/
Copy pathrql.py
File metadata and controls
executable file
·483 lines (442 loc) · 23.2 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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
from typing import List, Dict, Any, Tuple, Union
from collections import namedtuple
import copy
import numpy as np
import torch
import torch.nn.functional as F
from torch.distributions import Normal, Independent
from ding.torch_utils import Adam, to_device
from ding.rl_utils import v_1step_td_data, v_1step_td_error, get_train_sample
from ding.model import model_wrap
from ding.utils import POLICY_REGISTRY
from ding.utils.data import default_collate, default_decollate
from .base_policy import Policy
from .common_utils import default_preprocess_learn
@POLICY_REGISTRY.register('rql')
class RQLPolicy(Policy):
r"""
Overview:
Policy class of SAC algorithm.
https://arxiv.org/pdf/1801.01290.pdf
Config:
== ==================== ======== ============= ================================= =======================
ID Symbol Type Default Value Description Other(Shape)
== ==================== ======== ============= ================================= =======================
1 ``type`` str td3 | RL policy register name, refer | this arg is optional,
| to registry ``POLICY_REGISTRY`` | a placeholder
2 ``cuda`` bool True | Whether to use cuda for network |
3 | ``random_`` int 10000 | Number of randomly collected | Default to 10000 for
| ``collect_size`` | training samples in replay | SAC, 25000 for DDPG/
| | buffer when training starts. | TD3.
4 | ``model.policy_`` int 256 | Linear layer size for policy |
| ``embedding_size`` | network. |
5 | ``model.soft_q_`` int 256 | Linear layer size for soft q |
| ``embedding_size`` | network. |
6 | ``model.value_`` int 256 | Linear layer size for value | Defalut to None when
| ``embedding_size`` | network. | model.value_network
| | | is False.
7 | ``learn.learning`` float 3e-4 | Learning rate for soft q | Defalut to 1e-3, when
| ``_rate_q`` | network. | model.value_network
| | | is True.
8 | ``learn.learning`` float 3e-4 | Learning rate for policy | Defalut to 1e-3, when
| ``_rate_policy`` | network. | model.value_network
| | | is True.
9 | ``learn.learning`` float 3e-4 | Learning rate for policy | Defalut to None when
| ``_rate_value`` | network. | model.value_network
| | | is False.
10 | ``learn.alpha`` float 0.2 | Entropy regularization | alpha is initiali-
| | coefficient. | zation for auto
| | | `\alpha`, when
| | | auto_alpha is True
11 | ``learn.repara_`` bool True | Determine whether to use |
| ``meterization`` | reparameterization trick. |
12 | ``learn.`` bool False | Determine whether to use | Temperature parameter
| ``auto_alpha`` | auto temperature parameter | determines the
| | `\alpha`. | relative importance
| | | of the entropy term
| | | against the reward.
13 | ``learn.-`` bool False | Determine whether to ignore | Use ignore_done only
| ``ignore_done`` | done flag. | in halfcheetah env.
14 | ``learn.-`` float 0.005 | Used for soft update of the | aka. Interpolation
| ``target_theta`` | target network. | factor in polyak aver
| | | aging for target
| | | networks.
== ==================== ======== ============= ================================= =======================
"""
config = dict(
# (str) RL policy register name (refer to function "POLICY_REGISTRY").
type='rql',
# (bool) Whether to use cuda for network.
cuda=True,
# (bool type) on_policy: Determine whether on-policy or off-policy.
# on-policy setting influences the behaviour of buffer.
# Default False in SAC.
on_policy=False,
# (bool type) priority: Determine whether to use priority in buffer sample.
# Default False in SAC.
priority=False,
# (bool) Whether use Importance Sampling Weight to correct biased update. If True, priority must be True.
priority_IS_weight=False,
# (int) Number of training samples(randomly collected) in replay buffer when training starts.
# Default 10000 in SAC.
random_collect_size=10000,
model=dict(
# (bool type) twin_critic: Determine whether to use double-soft-q-net for target q computation.
# Please refer to TD3 about Clipped Double-Q Learning trick, which learns two Q-functions instead of one .
# Default to True.
twin_critic=True,
# (bool type) value_network: Determine whether to use value network as the
# original SAC paper (arXiv 1801.01290).
# using value_network needs to set learning_rate_value, learning_rate_q,
# and learning_rate_policy in `cfg.policy.learn`.
# Default to False.
# value_network=False,
actor_head_type='reparameterization',
),
learn=dict(
# (bool) Whether to use multi gpu
multi_gpu=False,
# How many updates(iterations) to train after collector's one collection.
# Bigger "update_per_collect" means bigger off-policy.
# collect data -> update policy-> collect data -> ...
update_per_collect=1,
# (int) Minibatch size for gradient descent.
batch_size=256,
# (float type) learning_rate_q: Learning rate for soft q network.
# Default to 3e-4.
# Please set to 1e-3, when model.value_network is True.
learning_rate_q=3e-4,
# (float type) learning_rate_policy: Learning rate for policy network.
# Default to 3e-4.
# Please set to 1e-3, when model.value_network is True.
learning_rate_policy=3e-4,
# (float type) learning_rate_value: Learning rate for value network.
# `learning_rate_value` should be initialized, when model.value_network is True.
# Please set to 3e-4, when model.value_network is True.
learning_rate_value=3e-4,
# (float type) target_theta: Used for soft update of the target network,
# aka. Interpolation factor in polyak averaging for target networks.
# Default to 0.005.
target_theta=0.005,
# (float) discount factor for the discounted sum of rewards, aka. gamma.
discount_factor=0.99,
alpha=0.2,
dist_threshold=0.1,
beta=0.5, # the temprature only used for 'softmax' policy type,
# (bool) Whether ignore done(usually for max step termination env. e.g. pendulum)
# Note: Gym wraps the MuJoCo envs by default with TimeLimit environment wrappers.
# These limit HalfCheetah, and several other MuJoCo envs, to max length of 1000.
# However, interaction with HalfCheetah always gets done with False,
# Since we inplace done==True with done==False to keep
# TD-error accurate computation(``gamma * (1 - done) * next_v + reward``),
# when the episode step is greater than max episode step.
ignore_done=False,
# (float) Weight uniform initialization range in the last output layer
init_w=3e-3,
),
collect=dict(
# You can use either "n_sample" or "n_episode" in actor.collect.
# Get "n_sample" samples per collect.
# Default n_sample to 1.
n_sample=1,
# (int) Cut trajectories into pieces with length "unroll_len".
unroll_len=1,
),
eval=dict(
evaluator=dict(
# (int) Evaluate every "eval_freq" training iterations.
eval_freq=5000,
),
),
other=dict(
replay_buffer=dict(
# (int type) replay_buffer_size: Max size of replay buffer.
replay_buffer_size=1000000,
# (int type) max_use: Max use times of one data in the buffer.
# Data will be removed once used for too many times.
# Default to infinite.
# max_use=256,
),
),
)
def _init_learn(self) -> None:
r"""
Overview:
Learn mode init method. Called by ``self.__init__``.
Init q, value and policy's optimizers, algorithm config, main and target models.
"""
# Init
self._priority = self._cfg.priority
self._priority_IS_weight = self._cfg.priority_IS_weight
self._twin_critic = self._cfg.model.twin_critic
# Weight Init for the last output layer
init_w = self._cfg.learn.init_w
self._model.actor[2].mu.weight.data.uniform_(-init_w, init_w)
self._model.actor[2].mu.bias.data.uniform_(-init_w, init_w)
self._model.actor[2].log_sigma_layer.weight.data.uniform_(-init_w, init_w)
self._model.actor[2].log_sigma_layer.bias.data.uniform_(-init_w, init_w)
# Optimizers
self._optimizer_q = Adam(
self._model.critic.parameters(),
lr=self._cfg.learn.learning_rate_q,
)
self._optimizer_policy = Adam(
self._model.actor.parameters(),
lr=self._cfg.learn.learning_rate_policy,
)
# Parameters
self._alpha = self._cfg.learn.alpha
self._beta = self._cfg.learn.beta
self._gamma = self._cfg.learn.discount_factor
self._dist_threshold = self._cfg.learn.dist_threshold
# Main and target models
self._target_model = copy.deepcopy(self._model)
self._target_model = model_wrap(
self._target_model,
wrapper_name='target',
update_type='momentum',
update_kwargs={'theta': self._cfg.learn.target_theta}
)
self._learn_model = model_wrap(self._model, wrapper_name='base')
self._learn_model.reset()
self._target_model.reset()
self._forward_learn_cnt = 0
def _forward_learn(self, data: dict) -> Dict[str, Any]:
"""
Overview:
Forward and backward function of learn mode.
Arguments:
- data (:obj:`dict`): Dict type data, including at least ['obs', 'action', 'reward', 'next_obs']
Returns:
- info_dict (:obj:`Dict[str, Any]`): Including current lr, loss, target_q_value and other \
running information.
"""
loss_dict = {}
data = default_preprocess_learn(
data,
use_priority=self._priority,
use_priority_IS_weight=self._cfg.priority_IS_weight,
ignore_done=self._cfg.learn.ignore_done,
use_nstep=False
)
if self._cuda:
data = to_device(data, self._device)
self._learn_model.train()
self._target_model.train()
obs = data['obs']
action_space = data['action_space']
dist_space = data['dist_space']
action_mask = (dist_space > self._dist_threshold).float()
action = data['action']
reward = data['reward']
next_obs = data['next_obs']
next_action_space = data['next_action_space']
next_dist_space = data['next_dist_space']
next_action_mask = (next_dist_space > self._dist_threshold).float()
done = data['done']
batch_size, k, action_shape = action_space.shape
obs_shape = obs.shape[1]
# 1. predict q value
q_value = self._learn_model.forward(data, mode='compute_critic')['q_value'] # [batch, ]
# 2. predict target q value.
with torch.no_grad():
# q in next action space
next_data = {'obs': next_obs.unsqueeze(1).expand(-1, k, -1).reshape(-1, obs_shape), 'action': next_action_space.reshape(-1, action_shape)}
next_q_value = self._learn_model.forward(next_data, mode='compute_critic')['q_value']
if self._twin_critic:
next_q_value = torch.min(next_q_value[0], next_q_value[1])
target_q_value = self._target_model.forward(next_data, mode='compute_critic')['q_value']
if self._twin_critic:
target_q_value = torch.min(target_q_value[0], target_q_value[1])
# max action in next action space
next_policy = (next_q_value.reshape(-1, k) / self._beta - 1e9 * next_action_mask).softmax(1)
target_q_value = (target_q_value.reshape(-1, k) * next_policy).sum(1)
target_q_value_mask = (1 - next_action_mask).bool().any(-1).float() # mask the value of states whose action space is empty
target_q_value = target_q_value * target_q_value_mask
# 3. compute q loss
if self._twin_critic:
q_data0 = v_1step_td_data(q_value[0], target_q_value, reward, done, data['weight'])
loss_dict['critic_loss'], td_error_per_sample0 = v_1step_td_error(q_data0, self._gamma)
q_data1 = v_1step_td_data(q_value[1], target_q_value, reward, done, data['weight'])
loss_dict['twin_critic_loss'], td_error_per_sample1 = v_1step_td_error(q_data1, self._gamma)
td_error_per_sample = (td_error_per_sample0 + td_error_per_sample1) / 2
else:
q_data = v_1step_td_data(q_value, target_q_value, reward, done, data['weight'])
loss_dict['critic_loss'], td_error_per_sample = v_1step_td_error(q_data, self._gamma)
# 4. update q network
self._optimizer_q.zero_grad()
loss_dict['critic_loss'].backward()
if self._twin_critic:
loss_dict['twin_critic_loss'].backward()
self._optimizer_q.step()
# 5. sample action
(mu, sigma) = self._learn_model.forward(data['obs'], mode='compute_actor')['logit']
dist = Independent(Normal(mu, sigma), 1)
pred = dist.rsample()
log_prob_d = dist.log_prob(pred)
log_prob_t = 2 * pred.cosh().log().sum(-1)
log_prob = log_prob_d + log_prob_t
mu = mu.unsqueeze(1) # [b,1,a]
var = sigma.unsqueeze(1).pow(2) # [b,1,a]
pred = 0.5 * ((1 + action_space + 1e-6) / (1 - action_space + 1e-6)).log() # [b,k,a]
neg_log_prob = ((pred - mu).pow(2).div(var) + var.log()).sum(-1)
# 6. max action in action space
with torch.no_grad():
data = {'obs': obs.unsqueeze(1).expand(-1, k, -1).reshape(-1, obs_shape), 'action': action_space.reshape(-1, action_shape)}
q_value = self._learn_model.forward(data, mode='compute_critic')['q_value']
if self._twin_critic:
q_value = torch.min(q_value[0], q_value[1])
policy = (q_value.reshape(-1, k) / self._beta - 1e9 * action_mask).softmax(1)
# 7. compute policy loss
entropy_loss = self._alpha * log_prob.mean()
ce_loss = (policy * neg_log_prob).sum(-1).mean()
policy_loss = entropy_loss + ce_loss
loss_dict['policy_loss'] = policy_loss
# 8. update policy network
self._optimizer_policy.zero_grad()
loss_dict['policy_loss'].backward()
self._optimizer_policy.step()
loss_dict['total_loss'] = sum(loss_dict.values())
# =============
# after update
# =============
self._forward_learn_cnt += 1
# target update
self._target_model.update(self._learn_model.state_dict())
return {
'cur_lr_q': self._optimizer_q.defaults['lr'],
'cur_lr_p': self._optimizer_policy.defaults['lr'],
'priority': td_error_per_sample.abs().tolist(),
'td_error': td_error_per_sample.detach().mean().item(),
'alpha': self._alpha,
'target_q_value': target_q_value.detach().mean().item(),
'entropy_loss': entropy_loss,
'ce_loss': ce_loss,
**loss_dict
}
def _state_dict_learn(self) -> Dict[str, Any]:
ret = {
'model': self._learn_model.state_dict(),
'target_model': self._target_model.state_dict(),
'optimizer_q': self._optimizer_q.state_dict(),
'optimizer_policy': self._optimizer_policy.state_dict(),
}
return ret
def _load_state_dict_learn(self, state_dict: Dict[str, Any]) -> None:
self._learn_model.load_state_dict(state_dict['model'])
self._target_model.load_state_dict(state_dict['target_model'])
self._optimizer_q.load_state_dict(state_dict['optimizer_q'])
def _init_collect(self) -> None:
r"""
Overview:
Collect mode init method. Called by ``self.__init__``.
Init traj and unroll length, collect model.
Use action noise for exploration.
"""
self._unroll_len = self._cfg.collect.unroll_len
self._collect_model = model_wrap(self._model, wrapper_name='base')
self._collect_model.reset()
def _forward_collect(self, data: dict) -> dict:
r"""
Overview:
Forward function of collect mode.
Arguments:
- data (:obj:`Dict[str, Any]`): Dict type data, stacked env data for predicting policy_output(action), \
values are torch.Tensor or np.ndarray or dict/list combinations, keys are env_id indicated by integer.
Returns:
- output (:obj:`Dict[int, Any]`): Dict type data, including at least inferred action according to input obs.
ReturnsKeys
- necessary: ``action``
- optional: ``logit``
"""
data_id = list(data.keys())
data = default_collate(list(data.values()))
if self._cuda:
data = to_device(data, self._device)
self._collect_model.eval()
with torch.no_grad():
(mu, sigma) = self._collect_model.forward(data, mode='compute_actor')['logit']
dist = Independent(Normal(mu, sigma), 1)
action = torch.tanh(dist.rsample())
output = {'logit': (mu, sigma), 'action': action}
if self._cuda:
output = to_device(output, 'cpu')
output = default_decollate(output)
return {i: d for i, d in zip(data_id, output)}
def _process_transition(self, obs: Any, policy_output: dict, timestep: namedtuple) -> dict:
r"""
Overview:
Generate dict type transition data from inputs.
Arguments:
- obs (:obj:`Any`): Env observation
- policy_output (:obj:`dict`): Output of policy collect model, including at least ['action']
- timestep (:obj:`namedtuple`): Output after env step, including at least ['obs', 'reward', 'done'] \
(here 'obs' indicates obs after env step, i.e. next_obs).
Return:
- transition (:obj:`Dict[str, Any]`): Dict type transition data.
"""
transition = {
'obs': obs,
'next_obs': timestep.obs,
'action': policy_output['action'],
'reward': timestep.reward,
'done': timestep.done,
}
return transition
def _get_train_sample(self, data: list) -> Union[None, List[Any]]:
return get_train_sample(data, self._unroll_len)
def _init_eval(self) -> None:
r"""
Overview:
Evaluate mode init method. Called by ``self.__init__``.
Init eval model. Unlike learn and collect model, eval model does not need noise.
"""
self._eval_model = model_wrap(self._model, wrapper_name='base')
self._eval_model.reset()
def _forward_eval(self, data: dict) -> dict:
r"""
Overview:
Forward function of eval mode, similar to ``self._forward_collect``.
Arguments:
- data (:obj:`Dict[str, Any]`): Dict type data, stacked env data for predicting policy_output(action), \
values are torch.Tensor or np.ndarray or dict/list combinations, keys are env_id indicated by integer.
Returns:
- output (:obj:`Dict[int, Any]`): The dict of predicting action for the interaction with env.
ReturnsKeys
- necessary: ``action``
- optional: ``logit``
"""
data_id = list(data.keys())
data = default_collate(list(data.values()))
if self._cuda:
data = to_device(data, self._device)
self._eval_model.eval()
with torch.no_grad():
(mu, sigma) = self._eval_model.forward(data, mode='compute_actor')['logit']
action = torch.tanh(mu) # deterministic_eval
output = {'action': action}
if self._cuda:
output = to_device(output, 'cpu')
output = default_decollate(output)
return {i: d for i, d in zip(data_id, output)}
def default_model(self) -> Tuple[str, List[str]]:
return 'qac', ['ding.model.template.qac']
def _monitor_vars_learn(self) -> List[str]:
r"""
Overview:
Return variables' name if variables are to used in monitor.
Returns:
- vars (:obj:`List[str]`): Variables' name list.
"""
twin_critic = ['twin_critic_loss'] if self._twin_critic else []
return [
'policy_loss',
'entropy_loss',
'ce_loss',
'critic_loss',
'cur_lr_q',
'cur_lr_p',
'target_q_value',
'alpha',
'td_error',
] + twin_critic