1import copy 2import torch 3from collections import namedtuple 4from typing import List, Dict, Any, Tuple, Union, Optional 5 6from ding.model import model_wrap 7from ding.rl_utils import q_nstep_td_data, q_nstep_td_error, q_nstep_td_error_with_rescale, get_nstep_return_data, \ 8 get_train_sample 9from ding.torch_utils import Adam, to_device 10from ding.utils import POLICY_REGISTRY 11from ding.utils.data import timestep_collate, default_collate, default_decollate 12from .base_policy import Policy 13 14 15@POLICY_REGISTRY.register('r2d2_gtrxl') 16class R2D2GTrXLPolicy(Policy): 17 r""" 18 Overview: 19 Policy class of R2D2 adopting the Transformer architecture GTrXL as backbone. 20 21 Config: 22 == ==================== ======== ============== ======================================== ======================= 23 ID Symbol Type Default Value Description Other(Shape) 24 == ==================== ======== ============== ======================================== ======================= 25 1 ``type`` str r2d2_gtrxl | RL policy register name, refer to | This arg is optional, 26 | registry ``POLICY_REGISTRY`` | a placeholder 27 2 ``cuda`` bool False | Whether to use cuda for network | This arg can be diff- 28 | erent from modes 29 3 ``on_policy`` bool False | Whether the RL algorithm is on-policy 30 | or off-policy 31 4 ``priority`` bool False | Whether use priority(PER) | Priority sample, 32 | update priority 33 5 | ``priority_IS`` bool False | Whether use Importance Sampling Weight 34 | ``_weight`` | to correct biased update. If True, 35 | priority must be True. 36 6 | ``discount_`` float 0.99, | Reward's future discount factor, aka. | May be 1 when sparse 37 | ``factor`` [0.95, 0.999] | gamma | reward env 38 7 | ``nstep`` int 5, | N-step reward discount sum for target 39 [3, 5] | q_value estimation 40 8 | ``burnin_step`` int 1 | The timestep of burnin operation, 41 | which is designed to warm-up GTrXL 42 | memory difference caused by off-policy 43 9 | ``learn.update`` int 1 | How many updates(iterations) to train | This args can be vary 44 | ``per_collect`` | after collector's one collection. Only | from envs. Bigger val 45 | valid in serial training | means more off-policy 46 10 | ``learn.batch_`` int 64 | The number of samples of an iteration 47 | ``size`` 48 11 | ``learn.learning`` float 0.001 | Gradient step length of an iteration. 49 | ``_rate`` 50 12 | ``learn.value_`` bool True | Whether use value_rescale function for 51 | ``rescale`` | predicted value 52 13 | ``learn.target_`` int 100 | Frequence of target network update. | Hard(assign) update 53 | ``update_freq`` 54 14 | ``learn.ignore_`` bool False | Whether ignore done for target value | Enable it for some 55 | ``done`` | calculation. | fake termination env 56 15 ``collect.n_sample`` int [8, 128] | The number of training samples of a | It varies from 57 | call of collector. | different envs 58 16 | ``collect.seq`` int 20 | Training sequence length | unroll_len>=seq_len>1 59 | ``_len`` 60 17 | ``learn.init_`` str zero | 'zero' or 'old', how to initialize the | 61 | ``memory`` | memory before each training iteration. | 62 == ==================== ======== ============== ======================================== ======================= 63 """ 64 config = dict( 65 # (str) RL policy register name (refer to function "POLICY_REGISTRY"). 66 type='r2d2_gtrxl', 67 # (bool) Whether to use cuda for network. 68 cuda=False, 69 # (bool) Whether the RL algorithm is on-policy or off-policy. 70 on_policy=False, 71 # (bool) Whether use priority(priority sample, IS weight, update priority) 72 priority=True, 73 # (bool) Whether use Importance Sampling Weight to correct biased update. If True, priority must be True. 74 priority_IS_weight=True, 75 # ============================================================== 76 # The following configs are algorithm-specific 77 # ============================================================== 78 # (float) Reward's future discount factor, aka. gamma. 79 discount_factor=0.99, 80 # (int) N-step reward for target q_value estimation 81 nstep=5, 82 # (int) How many steps to use in burnin phase 83 burnin_step=1, 84 # (int) trajectory length 85 unroll_len=25, 86 # (int) training sequence length 87 seq_len=20, 88 learn=dict( 89 update_per_collect=1, 90 batch_size=64, 91 learning_rate=0.0001, 92 # ============================================================== 93 # The following configs are algorithm-specific 94 # ============================================================== 95 # (int) Frequence of target network update. 96 # target_update_freq=100, 97 target_update_theta=0.001, 98 ignore_done=False, 99 # (bool) whether use value_rescale function for predicted value 100 value_rescale=False, 101 # 'zero' or 'old', how to initialize the memory in training 102 init_memory='zero' 103 ), 104 collect=dict( 105 # NOTE it is important that don't include key n_sample here, to make sure self._traj_len=INF 106 each_iter_n_sample=32, 107 # `env_num` is used in hidden state, should equal to that one in env config. 108 # User should specify this value in user config. 109 env_num=None, 110 ), 111 eval=dict( 112 # `env_num` is used in hidden state, should equal to that one in env config. 113 # User should specify this value in user config. 114 env_num=None, 115 ), 116 other=dict( 117 eps=dict( 118 type='exp', 119 start=0.95, 120 end=0.05, 121 decay=10000, 122 ), 123 replay_buffer=dict(replay_buffer_size=10000, ), 124 ), 125 ) 126 127 def default_model(self) -> Tuple[str, List[str]]: 128 return 'gtrxldqn', ['ding.model.template.q_learning'] 129 130 def _init_learn(self) -> None: 131 """ 132 Overview: 133 Init the learner model of GTrXLR2D2Policy. \ 134 Target model has 2 wrappers: 'target' for weights update and 'transformer_segment' to split trajectories \ 135 in segments. Learn model has 2 wrappers: 'argmax' to select the best action and 'transformer_segment'. 136 137 Arguments: 138 - learning_rate (:obj:`float`): The learning rate fo the optimizer 139 - gamma (:obj:`float`): The discount factor 140 - nstep (:obj:`int`): The num of n step return 141 - value_rescale (:obj:`bool`): Whether to use value rescaled loss in algorithm 142 - burnin_step (:obj:`int`): The num of step of burnin 143 - seq_len (:obj:`int`): Training sequence length 144 - init_memory (:obj:`str`): 'zero' or 'old', how to initialize the memory before each training iteration. 145 146 .. note:: 147 The ``_init_learn`` method takes the argument from the self._cfg.learn in the config file 148 """ 149 self._priority = self._cfg.priority 150 self._priority_IS_weight = self._cfg.priority_IS_weight 151 self._optimizer = Adam(self._model.parameters(), lr=self._cfg.learn.learning_rate) 152 self._gamma = self._cfg.discount_factor 153 self._nstep = self._cfg.nstep 154 self._burnin_step = self._cfg.burnin_step 155 self._batch_size = self._cfg.learn.batch_size 156 self._seq_len = self._cfg.seq_len 157 self._value_rescale = self._cfg.learn.value_rescale 158 self._init_memory = self._cfg.learn.init_memory 159 assert self._init_memory in ['zero', 'old'], self._init_memory 160 161 self._target_model = copy.deepcopy(self._model) 162 163 self._target_model = model_wrap( 164 self._target_model, 165 wrapper_name='target', 166 update_type='momentum', 167 update_kwargs={'theta': self._cfg.learn.target_update_theta} 168 ) 169 self._target_model = model_wrap(self._target_model, seq_len=self._seq_len, wrapper_name='transformer_segment') 170 171 self._learn_model = model_wrap(self._model, wrapper_name='argmax_sample') 172 self._learn_model = model_wrap(self._learn_model, seq_len=self._seq_len, wrapper_name='transformer_segment') 173 self._learn_model.reset() 174 self._target_model.reset() 175 176 def _data_preprocess_learn(self, data: List[Dict[str, Any]]) -> dict: 177 r""" 178 Overview: 179 Preprocess the data to fit the required data format for learning 180 Arguments: 181 - data (:obj:`List[Dict[str, Any]]`): the data collected from collect function 182 Returns: 183 - data (:obj:`Dict[str, Any]`): the processed data, including at least \ 184 ['main_obs', 'target_obs', 'burnin_obs', 'action', 'reward', 'done', 'weight'] 185 - data_info (:obj:`dict`): the data info, such as replay_buffer_idx, replay_unique_id 186 """ 187 if self._init_memory == 'old' and 'prev_memory' in data[0].keys(): 188 # retrieve the memory corresponding to the first and n_step(th) element in each trajectory and remove it 189 # from 'data' 190 prev_mem = [b['prev_memory'][0] for b in data] 191 prev_mem_target = [b['prev_memory'][self._nstep] for b in data] 192 # stack the memory entries along the batch dimension, 193 # reshape the new memory to have shape (layer_num+1, memory_len, bs, embedding_dim) compatible with GTrXL 194 prev_mem_batch = torch.stack(prev_mem, 0).permute(1, 2, 0, 3) 195 prev_mem_target_batch = torch.stack(prev_mem_target, 0).permute(1, 2, 0, 3) 196 data = timestep_collate(data) 197 data['prev_memory_batch'] = prev_mem_batch 198 data['prev_memory_target_batch'] = prev_mem_target_batch 199 else: 200 data = timestep_collate(data) 201 if self._cuda: 202 data = to_device(data, self._device) 203 204 if self._priority_IS_weight: 205 assert self._priority, "Use IS Weight correction, but Priority is not used." 206 if self._priority and self._priority_IS_weight: 207 data['weight'] = data['IS'] 208 else: 209 data['weight'] = data.get('weight', None) 210 211 # data['done'], data['weight'], data['value_gamma'] is used in def _forward_learn() to calculate 212 # the q_nstep_td_error, should be length of [self._unroll_len] 213 ignore_done = self._cfg.learn.ignore_done 214 if ignore_done: 215 data['done'] = [None for _ in range(self._unroll_len)] 216 else: 217 data['done'] = data['done'].float() # for computation of online model self._learn_model 218 # NOTE that after the proprocessing of get_nstep_return_data() in _get_train_sample 219 # the data['done'][t] is already the n-step done 220 221 # if the data don't include 'weight' or 'value_gamma' then fill in None in a list 222 # with length of [self._unroll_len_add_burnin_step-self._burnin_step], 223 # below is two different implementation ways 224 if 'value_gamma' not in data: 225 data['value_gamma'] = [None for _ in range(self._unroll_len)] 226 else: 227 data['value_gamma'] = data['value_gamma'] 228 229 if 'weight' not in data or data['weight'] is None: 230 data['weight'] = [None for _ in range(self._unroll_len)] 231 else: 232 data['weight'] = data['weight'] * torch.ones_like(data['done']) 233 # every timestep in sequence has same weight, which is the _priority_IS_weight in PER 234 235 data['action'] = data['action'][:-self._nstep] 236 data['reward'] = data['reward'][:-self._nstep] 237 238 data['main_obs'] = data['obs'][:-self._nstep] 239 # the target_obs is used to calculate the target_q_value 240 data['target_obs'] = data['obs'][self._nstep:] 241 242 return data 243 244 def _forward_learn(self, data: dict) -> Dict[str, Any]: 245 r""" 246 Overview: 247 Forward and backward function of learn mode. 248 Acquire the data, calculate the loss and optimize learner model. 249 Arguments: 250 - data (:obj:`dict`): Dict type data, including at least \ 251 ['main_obs', 'target_obs', 'burnin_obs', 'action', 'reward', 'done', 'weight'] 252 Returns: 253 - info_dict (:obj:`Dict[str, Any]`): Including cur_lr and total_loss 254 - cur_lr (:obj:`float`): Current learning rate 255 - total_loss (:obj:`float`): The calculated loss 256 """ 257 data = self._data_preprocess_learn(data) # shape (seq_len, bs, obs_dim) 258 self._learn_model.train() 259 self._target_model.train() 260 if self._init_memory == 'old': 261 # use the previous hidden state memory 262 self._learn_model.reset_memory(state=data['prev_memory_batch']) 263 self._target_model.reset_memory(state=data['prev_memory_target_batch']) 264 elif self._init_memory == 'zero': 265 # use the zero-initialized state memory 266 self._learn_model.reset_memory() 267 self._target_model.reset_memory() 268 269 inputs = data['main_obs'] 270 q_value = self._learn_model.forward(inputs)['logit'] # shape (seq_len, bs, act_dim) 271 next_inputs = data['target_obs'] 272 with torch.no_grad(): 273 target_q_value = self._target_model.forward(next_inputs)['logit'] 274 if self._init_memory == 'old': 275 self._learn_model.reset_memory(state=data['prev_memory_target_batch']) 276 elif self._init_memory == 'zero': 277 self._learn_model.reset_memory() 278 target_q_action = self._learn_model.forward(next_inputs)['action'] # argmax_action double_dqn 279 280 action, reward, done, weight = data['action'], data['reward'], data['done'], data['weight'] 281 value_gamma = data['value_gamma'] 282 # T, B, nstep -> T, nstep, B 283 reward = reward.permute(0, 2, 1).contiguous() 284 loss = [] 285 td_error = [] 286 for t in range(self._burnin_step, self._unroll_len - self._nstep): 287 # here skip the first 'burnin_step' steps because we only needed that to initialize the memory, and 288 # skip the last 'nstep' steps because we don't have their target obs 289 td_data = q_nstep_td_data( 290 q_value[t], target_q_value[t], action[t], target_q_action[t], reward[t], done[t], weight[t] 291 ) 292 if self._value_rescale: 293 l, e = q_nstep_td_error_with_rescale(td_data, self._gamma, self._nstep, value_gamma=value_gamma[t]) 294 else: 295 l, e = q_nstep_td_error(td_data, self._gamma, self._nstep, value_gamma=value_gamma[t]) 296 loss.append(l) 297 td_error.append(e.abs()) 298 loss = sum(loss) / (len(loss) + 1e-8) 299 300 # using the mixture of max and mean absolute n-step TD-errors as the priority of the sequence 301 td_error_per_sample = 0.9 * torch.max( 302 torch.stack(td_error), dim=0 303 )[0] + (1 - 0.9) * (torch.sum(torch.stack(td_error), dim=0) / (len(td_error) + 1e-8)) 304 # td_error shape list(<self._unroll_len_add_burnin_step-self._burnin_step-self._nstep>, B), for example, (75,64) 305 # torch.sum(torch.stack(td_error), dim=0) can also be replaced with sum(td_error) 306 307 # update 308 self._optimizer.zero_grad() 309 loss.backward() 310 self._optimizer.step() 311 # after update 312 self._target_model.update(self._learn_model.state_dict()) 313 314 # the information for debug 315 batch_range = torch.arange(action[0].shape[0]) 316 q_s_a_t0 = q_value[0][batch_range, action[0]] 317 target_q_s_a_t0 = target_q_value[0][batch_range, target_q_action[0]] 318 319 ret = { 320 'cur_lr': self._optimizer.defaults['lr'], 321 'total_loss': loss.item(), 322 'priority': td_error_per_sample.abs().tolist(), 323 # the first timestep in the sequence, may not be the start of episode 324 'q_s_taken-a_t0': q_s_a_t0.mean().item(), 325 'target_q_s_max-a_t0': target_q_s_a_t0.mean().item(), 326 'q_s_a-mean_t0': q_value[0].mean().item(), 327 } 328 329 return ret 330 331 def _reset_learn(self, data_id: Optional[List[int]] = None) -> None: 332 self._learn_model.reset(data_id=data_id) 333 self._target_model.reset(data_id=data_id) 334 self._learn_model.reset_memory() 335 self._target_model.reset_memory() 336 337 def _state_dict_learn(self) -> Dict[str, Any]: 338 return { 339 'model': self._learn_model.state_dict(), 340 'optimizer': self._optimizer.state_dict(), 341 } 342 343 def _load_state_dict_learn(self, state_dict: Dict[str, Any]) -> None: 344 self._learn_model.load_state_dict(state_dict['model']) 345 self._optimizer.load_state_dict(state_dict['optimizer']) 346 347 def _init_collect(self) -> None: 348 r""" 349 Overview: 350 Collect mode init method. Called by ``self.__init__``. 351 Init unroll length and sequence len, collect model. 352 """ 353 self._nstep = self._cfg.nstep 354 self._gamma = self._cfg.discount_factor 355 self._unroll_len = self._cfg.unroll_len 356 self._seq_len = self._cfg.seq_len 357 self._collect_model = model_wrap(self._model, wrapper_name='transformer_input', seq_len=self._seq_len) 358 self._collect_model = model_wrap(self._collect_model, wrapper_name='eps_greedy_sample') 359 self._collect_model = model_wrap( 360 self._collect_model, wrapper_name='transformer_memory', batch_size=self.cfg.collect.env_num 361 ) 362 self._collect_model.reset() 363 364 def _forward_collect(self, data: dict, eps: float) -> dict: 365 r""" 366 Overview: 367 Forward function for collect mode with eps_greedy 368 Arguments: 369 - data (:obj:`Dict[str, Any]`): Dict type data, stacked env data for predicting policy_output(action), \ 370 values are torch.Tensor or np.ndarray or dict/list combinations, keys are env_id indicated by integer. 371 - eps (:obj:`float`): epsilon value for exploration, which is decayed by collected env step. 372 Returns: 373 - output (:obj:`Dict[int, Any]`): Dict type data, including at least inferred action according to input obs. 374 ReturnsKeys 375 - necessary: ``action`` 376 """ 377 data_id = list(data.keys()) 378 data = default_collate(list(data.values())) 379 if self._cuda: 380 data = to_device(data, self._device) 381 self._collect_model.eval() 382 with torch.no_grad(): 383 output = self._collect_model.forward(data, eps=eps, data_id=data_id) 384 # These keys are sequence-major (seq_len first) and cannot be decollated by env batch dimension. 385 output.pop('input_seq', None) 386 output.pop('transformer_out', None) 387 if self._cuda: 388 output = to_device(output, 'cpu') 389 output = default_decollate(output) 390 return {i: d for i, d in zip(data_id, output)} 391 392 def _reset_collect(self, data_id: Optional[List[int]] = None) -> None: 393 # data_id is ID of env to be reset 394 self._collect_model.reset(data_id=data_id) 395 396 def _process_transition(self, obs: Any, model_output: dict, timestep: namedtuple) -> dict: 397 r""" 398 Overview: 399 Generate dict type transition data from inputs. 400 Arguments: 401 - obs (:obj:`Any`): Env observation 402 - model_output (:obj:`dict`): Output of collect model, including at least ['action', 'prev_state'] 403 - timestep (:obj:`namedtuple`): Output after env step, including at least ['reward', 'done'] \ 404 (here 'obs' indicates obs after env step). 405 Returns: 406 - transition (:obj:`dict`): Dict type transition data. 407 """ 408 transition = { 409 'obs': obs, 410 'action': model_output['action'], 411 'prev_memory': model_output['memory'], # state of the memory before taking the 'action' 412 'prev_state': None, 413 'reward': timestep.reward, 414 'done': timestep.done, 415 } 416 return transition 417 418 def _get_train_sample(self, data: list) -> Union[None, List[Any]]: 419 r""" 420 Overview: 421 Get the trajectory and the n step return data, then sample from the n_step return data 422 Arguments: 423 - data (:obj:`list`): The trajectory's cache 424 Returns: 425 - samples (:obj:`dict`): The training samples generated 426 """ 427 self._seq_len = self._cfg.seq_len 428 data = get_nstep_return_data(data, self._nstep, gamma=self._gamma) 429 return get_train_sample(data, self._unroll_len) 430 431 def _init_eval(self) -> None: 432 r""" 433 Overview: 434 Evaluate mode init method. Called by ``self.__init__``. 435 Init eval model with argmax strategy. 436 """ 437 self._eval_model = model_wrap(self._model, wrapper_name='transformer_input', seq_len=self._seq_len) 438 self._eval_model = model_wrap(self._eval_model, wrapper_name='argmax_sample') 439 self._eval_model = model_wrap( 440 self._eval_model, wrapper_name='transformer_memory', batch_size=self.cfg.eval.env_num 441 ) 442 self._eval_model.reset() 443 444 def _forward_eval(self, data: dict) -> dict: 445 r""" 446 Overview: 447 Forward function of eval mode, similar to ``self._forward_collect``. 448 Arguments: 449 - data (:obj:`Dict[str, Any]`): Dict type data, stacked env data for predicting policy_output(action), \ 450 values are torch.Tensor or np.ndarray or dict/list combinations, keys are env_id indicated by integer. 451 Returns: 452 - output (:obj:`Dict[int, Any]`): The dict of predicting action for the interaction with env. 453 ReturnsKeys 454 - necessary: ``action`` 455 """ 456 data_id = list(data.keys()) 457 data = default_collate(list(data.values())) 458 if self._cuda: 459 data = to_device(data, self._device) 460 self._eval_model.eval() 461 with torch.no_grad(): 462 output = self._eval_model.forward(data, data_id=data_id) 463 # These keys are sequence-major (seq_len first) and cannot be decollated by env batch dimension. 464 output.pop('input_seq', None) 465 output.pop('transformer_out', None) 466 if self._cuda: 467 output = to_device(output, 'cpu') 468 output = default_decollate(output) 469 return {i: d for i, d in zip(data_id, output)} 470 471 def _reset_eval(self, data_id: Optional[List[int]] = None) -> None: 472 self._eval_model.reset(data_id=data_id) 473 474 def _monitor_vars_learn(self) -> List[str]: 475 return super()._monitor_vars_learn() + [ 476 'total_loss', 'priority', 'q_s_taken-a_t0', 'target_q_s_max-a_t0', 'q_s_a-mean_t0' 477 ]