1from typing import List, Dict, Any, Tuple, Union 2import copy 3import torch 4 5from ding.torch_utils import Adam, to_device 6from ding.rl_utils import qrdqn_nstep_td_data, qrdqn_nstep_td_error, get_train_sample, get_nstep_return_data 7from ding.model import model_wrap 8from ding.utils import POLICY_REGISTRY 9from ding.utils.data import default_collate, default_decollate 10from .dqn import DQNPolicy 11from .common_utils import default_preprocess_learn 12 13 14@POLICY_REGISTRY.register('qrdqn') 15class QRDQNPolicy(DQNPolicy): 16 r""" 17 Overview: 18 Policy class of QRDQN algorithm. QRDQN (https://arxiv.org/pdf/1710.10044.pdf) is a distributional RL \ 19 algorithm, which is an extension of DQN. The main idea of QRDQN is to use quantile regression to \ 20 estimate the quantile of the distribution of the return value, and then use the quantile to calculate \ 21 the quantile loss. 22 23 Config: 24 == ==================== ======== ============== ======================================== ======================= 25 ID Symbol Type Default Value Description Other(Shape) 26 == ==================== ======== ============== ======================================== ======================= 27 1 ``type`` str qrdqn | RL policy register name, refer to | this arg is optional, 28 | registry ``POLICY_REGISTRY`` | a placeholder 29 2 ``cuda`` bool False | Whether to use cuda for network | this arg can be diff- 30 | erent from modes 31 3 ``on_policy`` bool False | Whether the RL algorithm is on-policy 32 | or off-policy 33 4 ``priority`` bool True | Whether use priority(PER) | priority sample, 34 | update priority 35 6 | ``other.eps`` float 0.05 | Start value for epsilon decay. It's 36 | ``.start`` | small because rainbow use noisy net. 37 7 | ``other.eps`` float 0.05 | End value for epsilon decay. 38 | ``.end`` 39 8 | ``discount_`` float 0.97, | Reward's future discount factor, aka. | may be 1 when sparse 40 | ``factor`` [0.95, 0.999] | gamma | reward env 41 9 ``nstep`` int 3, | N-step reward discount sum for target 42 [3, 5] | q_value estimation 43 10 | ``learn.update`` int 3 | 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 11 ``learn.kappa`` float / | Threshold of Huber loss 47 == ==================== ======== ============== ======================================== ======================= 48 """ 49 50 config = dict( 51 # (str) RL policy register name (refer to function "POLICY_REGISTRY"). 52 type='qrdqn', 53 # (bool) Whether to use cuda for network. 54 cuda=False, 55 # (bool) Whether the RL algorithm is on-policy or off-policy. 56 on_policy=False, 57 # (bool) Whether use priority(priority sample, IS weight, update priority) 58 priority=False, 59 # (float) Reward's future discount factor, aka. gamma. 60 discount_factor=0.97, 61 # (int) N-step reward for target q_value estimation 62 nstep=1, 63 learn=dict( 64 65 # How many updates(iterations) to train after collector's one collection. 66 # Bigger "update_per_collect" means bigger off-policy. 67 # collect data -> update policy-> collect data -> ... 68 update_per_collect=3, 69 batch_size=64, 70 learning_rate=0.001, 71 # ============================================================== 72 # The following configs are algorithm-specific 73 # ============================================================== 74 # (int) Frequence of target network update. 75 target_update_freq=100, 76 # (bool) Whether ignore done(usually for max step termination env) 77 ignore_done=False, 78 ), 79 # collect_mode config 80 collect=dict( 81 # (int) Only one of [n_sample, n_step, n_episode] shoule be set 82 # n_sample=8, 83 # (int) Cut trajectories into pieces with length "unroll_len". 84 unroll_len=1, 85 ), 86 eval=dict(), 87 # other config 88 other=dict( 89 # Epsilon greedy with decay. 90 eps=dict( 91 # (str) Decay type. Support ['exp', 'linear']. 92 type='exp', 93 start=0.95, 94 end=0.1, 95 # (int) Decay length(env step) 96 decay=10000, 97 ), 98 replay_buffer=dict(replay_buffer_size=10000, ) 99 ), 100 ) 101 102 def default_model(self) -> Tuple[str, List[str]]: 103 """ 104 Overview: 105 Return this algorithm default neural network model setting for demonstration. ``__init__`` method will \ 106 automatically call this method to get the default model setting and create model. 107 108 Returns: 109 - model_info (:obj:`Tuple[str, List[str]]`): The registered model name and model's import_names. 110 """ 111 return 'qrdqn', ['ding.model.template.q_learning'] 112 113 def _init_learn(self) -> None: 114 """ 115 Overview: 116 Initialize the learn mode of policy, including related attributes and modules. For QRDQN, it mainly \ 117 contains optimizer, algorithm-specific arguments such as nstep and gamma. This method \ 118 also executes some special network initializations and prepares running mean/std monitor for value. 119 This method will be called in ``__init__`` method if ``learn`` field is in ``enable_field``. 120 121 .. note:: 122 For the member variables that need to be saved and loaded, please refer to the ``_state_dict_learn`` \ 123 and ``_load_state_dict_learn`` methods. 124 125 .. note:: 126 If you want to set some spacial member variables in ``_init_learn`` method, you'd better name them \ 127 with prefix ``_learn_`` to avoid conflict with other modes, such as ``self._learn_attr1``. 128 """ 129 self._priority = self._cfg.priority 130 # Optimizer 131 self._optimizer = Adam(self._model.parameters(), lr=self._cfg.learn.learning_rate) 132 133 self._gamma = self._cfg.discount_factor 134 self._nstep = self._cfg.nstep 135 136 # use model_wrapper for specialized demands of different modes 137 self._target_model = copy.deepcopy(self._model) 138 self._target_model = model_wrap( 139 self._target_model, 140 wrapper_name='target', 141 update_type='assign', 142 update_kwargs={'freq': self._cfg.learn.target_update_freq} 143 ) 144 self._learn_model = model_wrap(self._model, wrapper_name='argmax_sample') 145 self._learn_model.reset() 146 self._target_model.reset() 147 148 def _forward_learn(self, data: dict) -> Dict[str, Any]: 149 """ 150 Overview: 151 Policy forward function of learn mode (training policy and updating parameters). Forward means \ 152 that the policy inputs some training batch data from the replay buffer and then returns the output \ 153 result, including various training information such as loss, current lr. 154 155 Arguments: 156 - data (:obj:`dict`): Input data used for policy forward, including the \ 157 collected training samples from replay buffer. For each element in dict, the key of the \ 158 dict is the name of data items and the value is the corresponding data. Usually, the value is \ 159 torch.Tensor or np.ndarray or there dict/list combinations. In the ``_forward_learn`` method, data \ 160 often need to first be stacked in the batch dimension by some utility functions such as \ 161 ``default_preprocess_learn``. \ 162 For QRDQN, each element in list is a dict containing at least the following keys: ``obs``, \ 163 ``action``, ``reward``, ``next_obs``. Sometimes, it also contains other keys such as ``weight``. 164 165 Returns: 166 - info_dict (:obj:`Dict[str, Any]`): The output result dict of forward learn, \ 167 containing current lr, total_loss and priority. When discrete action satisfying \ 168 len(data['action'])==1, it also could contain ``action_distribution`` which is used \ 169 to draw histogram on tensorboard. For more information, please refer to the :class:`DQNPolicy`. 170 171 .. note:: 172 The input value can be torch.Tensor or dict/list combinations and current policy supports all of them. \ 173 For the data type that not supported, the main reason is that the corresponding model does not support it. \ 174 You can implement you own model rather than use the default model. For more information, please raise an \ 175 issue in GitHub repo and we will continue to follow up. 176 177 .. note:: 178 For more detailed examples, please refer to our unittest for QRDQNPolicy: ``ding.policy.tests.test_qrdqn``. 179 """ 180 181 data = default_preprocess_learn( 182 data, use_priority=self._priority, ignore_done=self._cfg.learn.ignore_done, use_nstep=True 183 ) 184 if self._cuda: 185 data = to_device(data, self._device) 186 # ==================== 187 # Q-learning forward 188 # ==================== 189 self._learn_model.train() 190 self._target_model.train() 191 # Current q value (main model) 192 ret = self._learn_model.forward(data['obs']) 193 q_value, tau = ret['q'], ret['tau'] 194 # Target q value 195 with torch.no_grad(): 196 target_q_value = self._target_model.forward(data['next_obs'])['q'] 197 # Max q value action (main model) 198 target_q_action = self._learn_model.forward(data['next_obs'])['action'] 199 200 data_n = qrdqn_nstep_td_data( 201 q_value, target_q_value, data['action'], target_q_action, data['reward'], data['done'], tau, data['weight'] 202 ) 203 value_gamma = data.get('value_gamma') 204 loss, td_error_per_sample = qrdqn_nstep_td_error( 205 data_n, self._gamma, nstep=self._nstep, value_gamma=value_gamma 206 ) 207 208 # ==================== 209 # Q-learning update 210 # ==================== 211 self._optimizer.zero_grad() 212 loss.backward() 213 if self._cfg.multi_gpu: 214 self.sync_gradients(self._learn_model) 215 self._optimizer.step() 216 217 # ============= 218 # after update 219 # ============= 220 self._target_model.update(self._learn_model.state_dict()) 221 return { 222 'cur_lr': self._optimizer.defaults['lr'], 223 'total_loss': loss.item(), 224 'priority': td_error_per_sample.abs().tolist(), 225 # Only discrete action satisfying len(data['action'])==1 can return this and draw histogram on tensorboard. 226 # '[histogram]action_distribution': data['action'], 227 } 228 229 def _state_dict_learn(self) -> Dict[str, Any]: 230 return { 231 'model': self._learn_model.state_dict(), 232 'target_model': self._target_model.state_dict(), 233 'optimizer': self._optimizer.state_dict(), 234 } 235 236 def _load_state_dict_learn(self, state_dict: Dict[str, Any]) -> None: 237 self._learn_model.load_state_dict(state_dict['model']) 238 self._target_model.load_state_dict(state_dict['target_model']) 239 self._optimizer.load_state_dict(state_dict['optimizer'])