Skip to content

ding.policy.wqmix

ding.policy.wqmix

WQMIXPolicy

Bases: QMIXPolicy

Overview

Policy class of WQMIX algorithm. WQMIX is a reinforcement learning algorithm modified from Qmix, \ you can view the paper in the following link https://arxiv.org/abs/2006.10800

Interface: _init_learn, _data_preprocess_learn, _forward_learn, _reset_learn, _state_dict_learn, _load_state_dict_learn\ _init_collect, _forward_collect, _reset_collect, _process_transition, _init_eval, _forward_eval\ _reset_eval, _get_train_sample, default_model Config: == ==================== ======== ============== ======================================== ======================= ID Symbol Type Default Value Description Other(Shape) == ==================== ======== ============== ======================================== ======================= 1 type str qmix | RL policy register name, refer to | this arg is optional, | registry POLICY_REGISTRY | a placeholder 2 cuda bool True | Whether to use cuda for network | this arg can be diff- | erent from modes 3 on_policy bool False | Whether the RL algorithm is on-policy | or off-policy 4. priority bool False | Whether use priority(PER) | priority sample, | update priority 5 | priority_ bool False | Whether use Importance Sampling | IS weight | IS_weight | Weight to correct biased update. 6 | learn.update_ int 20 | How many updates(iterations) to train | this args can be vary | per_collect | after collector's one collection. Only | from envs. Bigger val | valid in serial training | means more off-policy 7 | learn.target_ float 0.001 | Target network update momentum | between[0,1] | update_theta | parameter. 8 | learn.discount float 0.99 | Reward's future discount factor, aka. | may be 1 when sparse | _factor | gamma | reward env == ==================== ======== ============== ======================================== =======================

default_model()

Overview

Return this algorithm default model setting for demonstration.

Returns: - model_info (:obj:Tuple[str, List[str]]): model name and mode import_names .. note:: The user can define and use customized network model but must obey the same inferface definition indicated by import_names path. For WQMIX, ding.model.template.wqmix

Full Source Code

../ding/policy/wqmix.py

1from typing import List, Dict, Any, Tuple, Union, Optional 2from collections import namedtuple 3import torch 4import copy 5 6from ding.torch_utils import RMSprop, to_device 7from ding.rl_utils import v_1step_td_data, v_1step_td_error, get_train_sample 8from ding.model import model_wrap 9from ding.utils import POLICY_REGISTRY 10from ding.utils.data import timestep_collate, default_collate, default_decollate 11from .base_policy import Policy 12from ding.policy.qmix import QMIXPolicy 13 14 15@POLICY_REGISTRY.register('wqmix') 16class WQMIXPolicy(QMIXPolicy): 17 r""" 18 Overview: 19 Policy class of WQMIX algorithm. WQMIX is a reinforcement learning algorithm modified from Qmix, \ 20 you can view the paper in the following link https://arxiv.org/abs/2006.10800 21 Interface: 22 _init_learn, _data_preprocess_learn, _forward_learn, _reset_learn, _state_dict_learn, _load_state_dict_learn\ 23 _init_collect, _forward_collect, _reset_collect, _process_transition, _init_eval, _forward_eval\ 24 _reset_eval, _get_train_sample, default_model 25 Config: 26 == ==================== ======== ============== ======================================== ======================= 27 ID Symbol Type Default Value Description Other(Shape) 28 == ==================== ======== ============== ======================================== ======================= 29 1 ``type`` str qmix | RL policy register name, refer to | this arg is optional, 30 | registry ``POLICY_REGISTRY`` | a placeholder 31 2 ``cuda`` bool True | Whether to use cuda for network | this arg can be diff- 32 | erent from modes 33 3 ``on_policy`` bool False | Whether the RL algorithm is on-policy 34 | or off-policy 35 4. ``priority`` bool False | Whether use priority(PER) | priority sample, 36 | update priority 37 5 | ``priority_`` bool False | Whether use Importance Sampling | IS weight 38 | ``IS_weight`` | Weight to correct biased update. 39 6 | ``learn.update_`` int 20 | How many updates(iterations) to train | this args can be vary 40 | ``per_collect`` | after collector's one collection. Only | from envs. Bigger val 41 | valid in serial training | means more off-policy 42 7 | ``learn.target_`` float 0.001 | Target network update momentum | between[0,1] 43 | ``update_theta`` | parameter. 44 8 | ``learn.discount`` float 0.99 | Reward's future discount factor, aka. | may be 1 when sparse 45 | ``_factor`` | gamma | reward env 46 == ==================== ======== ============== ======================================== ======================= 47 """ 48 config = dict( 49 # (str) RL policy register name (refer to function "POLICY_REGISTRY"). 50 type='wqmix', 51 # (bool) Whether to use cuda for network. 52 cuda=True, 53 # (bool) Whether the RL algorithm is on-policy or off-policy. 54 on_policy=False, 55 # (bool) Whether use priority(priority sample, IS weight, update priority) 56 priority=False, 57 # (bool) Whether use Importance Sampling Weight to correct biased update. If True, priority must be True. 58 priority_IS_weight=False, 59 learn=dict( 60 update_per_collect=20, 61 batch_size=32, 62 learning_rate=0.0005, 63 clip_value=100, 64 # ============================================================== 65 # The following configs is algorithm-specific 66 # ============================================================== 67 # (float) Target network update momentum parameter. 68 # in [0, 1]. 69 target_update_theta=0.008, 70 # (float) The discount factor for future rewards, 71 # in [0, 1]. 72 discount_factor=0.99, 73 w=0.5, # for OW 74 # w = 0.75, # for CW 75 wqmix_ow=True, 76 ), 77 collect=dict( 78 # (int) Only one of [n_sample, n_episode] shoule be set 79 # n_episode=32, 80 # (int) Cut trajectories into pieces with length "unroll_len", the length of timesteps 81 # in each forward when training. In qmix, it is greater than 1 because there is RNN. 82 unroll_len=10, 83 ), 84 eval=dict(), 85 other=dict( 86 eps=dict( 87 # (str) Type of epsilon decay 88 type='exp', 89 # (float) Start value for epsilon decay, in [0, 1]. 90 # 0 means not use epsilon decay. 91 start=1, 92 # (float) Start value for epsilon decay, in [0, 1]. 93 end=0.05, 94 # (int) Decay length(env step) 95 decay=50000, 96 ), 97 replay_buffer=dict( 98 replay_buffer_size=5000, 99 # (int) The maximum reuse times of each data 100 max_reuse=1e+9, 101 max_staleness=1e+9, 102 ), 103 ), 104 ) 105 106 def default_model(self) -> Tuple[str, List[str]]: 107 """ 108 Overview: 109 Return this algorithm default model setting for demonstration. 110 Returns: 111 - model_info (:obj:`Tuple[str, List[str]]`): model name and mode import_names 112 .. note:: 113 The user can define and use customized network model but must obey the same inferface definition indicated \ 114 by import_names path. For WQMIX, ``ding.model.template.wqmix`` 115 """ 116 return 'wqmix', ['ding.model.template.wqmix'] 117 118 def _init_learn(self) -> None: 119 """ 120 Overview: 121 Learn mode init method. Called by ``self.__init__``. 122 Init the learner model of WQMIXPolicy 123 Arguments: 124 .. note:: 125 126 The _init_learn method takes the argument from the self._cfg.learn in the config file 127 128 - learning_rate (:obj:`float`): The learning rate fo the optimizer 129 - gamma (:obj:`float`): The discount factor 130 - agent_num (:obj:`int`): Since this is a multi-agent algorithm, we need to input the agent num. 131 - batch_size (:obj:`int`): Need batch size info to init hidden_state plugins 132 """ 133 self._priority = self._cfg.priority 134 self._priority_IS_weight = self._cfg.priority_IS_weight 135 assert not self._priority and not self._priority_IS_weight, "Priority is not implemented in WQMIX" 136 self._optimizer = RMSprop( 137 params=list(self._model._q_network.parameters()) + list(self._model._mixer.parameters()), 138 lr=self._cfg.learn.learning_rate, 139 alpha=0.99, 140 eps=0.00001 141 ) 142 self._gamma = self._cfg.learn.discount_factor 143 self._optimizer_star = RMSprop( 144 params=list(self._model._q_network_star.parameters()) + list(self._model._mixer_star.parameters()), 145 lr=self._cfg.learn.learning_rate, 146 alpha=0.99, 147 eps=0.00001 148 ) 149 self._learn_model = model_wrap( 150 self._model, 151 wrapper_name='hidden_state', 152 state_num=self._cfg.learn.batch_size, 153 init_fn=lambda: [None for _ in range(self._cfg.model.agent_num)] 154 ) 155 self._learn_model.reset() 156 157 def _data_preprocess_learn(self, data: List[Any]) -> dict: 158 r""" 159 Overview: 160 Preprocess the data to fit the required data format for learning 161 Arguments: 162 - data (:obj:`List[Dict[str, Any]]`): the data collected from collect function 163 Returns: 164 - data (:obj:`Dict[str, Any]`): the processed data, from \ 165 [len=B, ele={dict_key: [len=T, ele=Tensor(any_dims)]}] -> {dict_key: Tensor([T, B, any_dims])} 166 """ 167 # data preprocess 168 data = timestep_collate(data) 169 if self._cuda: 170 data = to_device(data, self._device) 171 data['weight'] = data.get('weight', None) 172 data['done'] = data['done'].float() 173 return data 174 175 def _forward_learn(self, data: dict) -> Dict[str, Any]: 176 r""" 177 Overview: 178 Forward and backward function of learn mode. 179 Arguments: 180 - data (:obj:`Dict[str, Any]`): Dict type data, a batch of data for training, values are torch.Tensor or \ 181 np.ndarray or dict/list combinations. 182 Returns: 183 - info_dict (:obj:`Dict[str, Any]`): Dict type data, a info dict indicated training result, which will be \ 184 recorded in text log and tensorboard, values are python scalar or a list of scalars. 185 ArgumentsKeys: 186 - necessary: ``obs``, ``next_obs``, ``action``, ``reward``, ``weight``, ``prev_state``, ``done`` 187 ReturnsKeys: 188 - necessary: ``cur_lr``, ``total_loss`` 189 - cur_lr (:obj:`float`): Current learning rate 190 - total_loss (:obj:`float`): The calculated loss 191 """ 192 data = self._data_preprocess_learn(data) 193 # ==================== 194 # forward 195 # ==================== 196 self._learn_model.train() 197 198 inputs = {'obs': data['obs'], 'action': data['action']} 199 200 # for hidden_state plugin, we need to reset the main model and target model 201 self._learn_model.reset(state=data['prev_state'][0]) 202 total_q = self._learn_model.forward(inputs, single_step=False, q_star=False)['total_q'] 203 204 self._learn_model.reset(state=data['prev_state'][0]) 205 total_q_star = self._learn_model.forward(inputs, single_step=False, q_star=True)['total_q'] 206 207 next_inputs = {'obs': data['next_obs']} 208 self._learn_model.reset(state=data['prev_state'][1]) # TODO(pu) 209 next_logit_detach = self._learn_model.forward( 210 next_inputs, single_step=False, q_star=False 211 )['logit'].clone().detach() 212 213 next_inputs = {'obs': data['next_obs'], 'action': next_logit_detach.argmax(dim=-1)} 214 with torch.no_grad(): 215 self._learn_model.reset(state=data['prev_state'][1]) # TODO(pu) 216 target_total_q = self._learn_model.forward(next_inputs, single_step=False, q_star=True)['total_q'] 217 218 with torch.no_grad(): 219 if data['done'] is not None: 220 target_v = self._gamma * (1 - data['done']) * target_total_q + data['reward'] 221 else: 222 target_v = self._gamma * target_total_q + data['reward'] 223 224 td_error = (total_q - target_v).clone().detach() 225 data_ = v_1step_td_data(total_q, target_total_q, data['reward'], data['done'], data['weight']) 226 _, td_error_per_sample = v_1step_td_error(data_, self._gamma) 227 228 data_star = v_1step_td_data(total_q_star, target_total_q, data['reward'], data['done'], data['weight']) 229 loss_star, td_error_per_sample_star_ = v_1step_td_error(data_star, self._gamma) 230 231 # our implemention is based on the https://github.com/oxwhirl/wqmix 232 # Weighting 233 alpha_to_use = self._cfg.learn.alpha 234 if self._cfg.learn.wqmix_ow: # Optimistically-Weighted 235 ws = torch.full_like(td_error, alpha_to_use) 236 # if td_error < 0, i.e. Q < y_i, then w =1; if not, w = alpha_to_use 237 ws = torch.where(td_error < 0, torch.ones_like(td_error), ws) 238 else: # Centrally-Weighted 239 inputs = {'obs': data['obs']} 240 self._learn_model.reset(state=data['prev_state'][0]) # TODO(pu) 241 logit_detach = self._learn_model.forward(inputs, single_step=False, q_star=False)['logit'].clone().detach() 242 cur_max_actions = logit_detach.argmax(dim=-1) 243 inputs = {'obs': data['obs'], 'action': cur_max_actions} 244 self._learn_model.reset(state=data['prev_state'][0]) # TODO(pu) 245 max_action_qtot = self._learn_model.forward(inputs, single_step=False, q_star=True)['total_q'] # Q_star 246 # Only if the action of each agent is optimal, then the joint action is optimal 247 is_max_action = (data['action'] == cur_max_actions).min(dim=2)[0] # shape (H,B,N) -> (H,B) 248 qtot_larger = target_v > max_action_qtot 249 ws = torch.full_like(td_error, alpha_to_use) 250 # if y_i > Q_star or u = u_star, then w =1; if not, w = alpha_to_use 251 ws = torch.where(is_max_action | qtot_larger, torch.ones_like(td_error), ws) 252 253 if data['weight'] is None: 254 data['weight'] = torch.ones_like(data['reward']) 255 loss_weighted = (ws.detach() * td_error_per_sample * data['weight']).mean() 256 257 # ==================== 258 # Q and Q_star update 259 # ==================== 260 self._optimizer.zero_grad() 261 self._optimizer_star.zero_grad() 262 loss_weighted.backward(retain_graph=True) 263 loss_star.backward() 264 grad_norm_q = torch.nn.utils.clip_grad_norm_( 265 list(self._model._q_network.parameters()) + list(self._model._mixer.parameters()), 266 self._cfg.learn.clip_value 267 ) # Q 268 grad_norm_q_star = torch.nn.utils.clip_grad_norm_( 269 list(self._model._q_network_star.parameters()) + list(self._model._mixer_star.parameters()), 270 self._cfg.learn.clip_value 271 ) # Q_star 272 self._optimizer.step() # Q update 273 self._optimizer_star.step() # Q_star update 274 275 # ============= 276 # after update 277 # ============= 278 return { 279 'cur_lr': self._optimizer.defaults['lr'], 280 'total_loss': loss_weighted.item(), 281 'total_q': total_q.mean().item() / self._cfg.model.agent_num, 282 'target_reward_total_q': target_v.mean().item() / self._cfg.model.agent_num, 283 'target_total_q': target_total_q.mean().item() / self._cfg.model.agent_num, 284 'grad_norm_q': grad_norm_q, 285 'grad_norm_q_star': grad_norm_q_star, 286 } 287 288 def _state_dict_learn(self) -> Dict[str, Any]: 289 r""" 290 Overview: 291 Return the state_dict of learn mode, usually including model and optimizer. 292 Returns: 293 - state_dict (:obj:`Dict[str, Any]`): the dict of current policy learn state, for saving and restoring. 294 """ 295 return { 296 'model': self._learn_model.state_dict(), 297 'optimizer': self._optimizer.state_dict(), 298 'optimizer_star': self._optimizer_star.state_dict(), 299 } 300 301 def _load_state_dict_learn(self, state_dict: Dict[str, Any]) -> None: 302 r""" 303 Overview: 304 Load the state_dict variable into policy learn mode. 305 Arguments: 306 - state_dict (:obj:`Dict[str, Any]`): the dict of policy learn state saved before. 307 .. tip:: 308 If you want to only load some parts of model, you can simply set the ``strict`` argument in \ 309 load_state_dict to ``False``, or refer to ``ding.torch_utils.checkpoint_helper`` for more \ 310 complicated operation. 311 """ 312 self._learn_model.load_state_dict(state_dict['model']) 313 self._optimizer.load_state_dict(state_dict['optimizer']) 314 self._optimizer_star.load_state_dict(state_dict['optimizer_star'])