1from typing import List, Dict, Any, Tuple, Optional 2from collections import namedtuple 3import copy 4import torch 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 12 13 14@POLICY_REGISTRY.register('qmix') 15class QMIXPolicy(Policy): 16 """ 17 Overview: 18 Policy class of QMIX algorithm. QMIX is a multi-agent reinforcement learning algorithm, \ 19 you can view the paper in the following link https://arxiv.org/abs/1803.11485. 20 Config: 21 == ==================== ======== ============== ======================================== ======================= 22 ID Symbol Type Default Value Description Other(Shape) 23 == ==================== ======== ============== ======================================== ======================= 24 1 ``type`` str qmix | RL policy register name, refer to | this arg is optional, 25 | registry ``POLICY_REGISTRY`` | a placeholder 26 2 ``cuda`` bool True | Whether to use cuda for network | this arg can be diff- 27 | erent from modes 28 3 ``on_policy`` bool False | Whether the RL algorithm is on-policy 29 | or off-policy 30 4. ``priority`` bool False | Whether use priority(PER) | priority sample, 31 | update priority 32 5 | ``priority_`` bool False | Whether use Importance Sampling | IS weight 33 | ``IS_weight`` | Weight to correct biased update. 34 6 | ``learn.update_`` int 20 | How many updates(iterations) to train | this args can be vary 35 | ``per_collect`` | after collector's one collection. Only | from envs. Bigger val 36 | valid in serial training | means more off-policy 37 7 | ``learn.target_`` float 0.001 | Target network update momentum | between[0,1] 38 | ``update_theta`` | parameter. 39 8 | ``learn.discount`` float 0.99 | Reward's future discount factor, aka. | may be 1 when sparse 40 | ``_factor`` | gamma | reward env 41 == ==================== ======== ============== ======================================== ======================= 42 """ 43 config = dict( 44 # (str) RL policy register name (refer to function "POLICY_REGISTRY"). 45 type='qmix', 46 # (bool) Whether to use cuda for network. 47 cuda=True, 48 # (bool) Whether the RL algorithm is on-policy or off-policy. 49 on_policy=False, 50 # (bool) Whether use priority(priority sample, IS weight, update priority) 51 priority=False, 52 # (bool) Whether use Importance Sampling Weight to correct biased update. If True, priority must be True. 53 priority_IS_weight=False, 54 # learn_mode config 55 learn=dict( 56 # (int) How many updates(iterations) to train after collector's one collection. 57 # Bigger "update_per_collect" means bigger off-policy. 58 # collect data -> update policy-> collect data -> ... 59 update_per_collect=20, 60 # (int) How many samples in a training batch. 61 batch_size=32, 62 # (float) The step size of gradient descent. 63 learning_rate=0.0005, 64 clip_value=100, 65 # (float) Target network update momentum parameter, in [0, 1]. 66 target_update_theta=0.008, 67 # (float) The discount factor for future rewards, in [0, 1]. 68 discount_factor=0.99, 69 # (bool) Whether to use double DQN mechanism(target q for surpassing over estimation). 70 double_q=False, 71 ), 72 # collect_mode config 73 collect=dict( 74 # (int) How many training samples collected in one collection procedure. 75 # In each collect phase, we collect a total of <n_sample> sequence samples, a sample with length unroll_len. 76 # n_sample=32, 77 # (int) Split trajectories into pieces with length ``unroll_len``, the length of timesteps 78 # in each forward when training. In qmix, it is greater than 1 because there is RNN. 79 unroll_len=10, 80 ), 81 eval=dict(), # for compatibility 82 other=dict( 83 eps=dict( 84 # (str) Type of epsilon decay. 85 type='exp', 86 # (float) Start value for epsilon decay, in [0, 1]. 87 start=1, 88 # (float) Start value for epsilon decay, in [0, 1]. 89 end=0.05, 90 # (int) Decay length(env step). 91 decay=50000, 92 ), 93 replay_buffer=dict( 94 # (int) Maximum size of replay buffer. Usually, larger buffer size is better. 95 replay_buffer_size=5000, 96 ), 97 ), 98 ) 99 100 def default_model(self) -> Tuple[str, List[str]]: 101 """ 102 Overview: 103 Return this algorithm default model setting for demonstration. 104 Returns: 105 - model_info (:obj:`Tuple[str, List[str]]`): model name and mode import_names 106 107 .. note:: 108 The user can define and use customized network model but must obey the same inferface definition indicated \ 109 by import_names path. For QMIX, ``ding.model.qmix.qmix`` 110 """ 111 return 'qmix', ['ding.model.template.qmix'] 112 113 def _init_learn(self) -> None: 114 """ 115 Overview: 116 Initialize the learn mode of policy, including some attributes and modules. For QMIX, it mainly contains \ 117 optimizer, algorithm-specific arguments such as gamma, main and target model. Because of the use of RNN, \ 118 all the models should be wrappered with ``hidden_state`` which needs to be initialized with proper size. 119 This method will be called in ``__init__`` method if ``learn`` field is in ``enable_field``. 120 121 .. tip:: 122 For multi-agent algorithm, we often need to use ``agent_num`` to initialize some necessary variables. 123 124 .. note:: 125 For the member variables that need to be saved and loaded, please refer to the ``_state_dict_learn`` \ 126 and ``_load_state_dict_learn`` methods. 127 128 .. note:: 129 For the member variables that need to be monitored, please refer to the ``_monitor_vars_learn`` method. 130 131 .. note:: 132 If you want to set some spacial member variables in ``_init_learn`` method, you'd better name them \ 133 with prefix ``_learn_`` to avoid conflict with other modes, such as ``self._learn_attr1``. 134 - agent_num (:obj:`int`): Since this is a multi-agent algorithm, we need to input the agent num. 135 """ 136 self._priority = self._cfg.priority 137 self._priority_IS_weight = self._cfg.priority_IS_weight 138 assert not self._priority and not self._priority_IS_weight, "Priority is not implemented in QMIX" 139 self._optimizer = RMSprop( 140 params=self._model.parameters(), 141 lr=self._cfg.learn.learning_rate, 142 alpha=0.99, 143 eps=0.00001, 144 weight_decay=1e-5 145 ) 146 self._gamma = self._cfg.learn.discount_factor 147 148 self._target_model = copy.deepcopy(self._model) 149 self._target_model = model_wrap( 150 self._target_model, 151 wrapper_name='target', 152 update_type='momentum', 153 update_kwargs={'theta': self._cfg.learn.target_update_theta} 154 ) 155 self._target_model = model_wrap( 156 self._target_model, 157 wrapper_name='hidden_state', 158 state_num=self._cfg.learn.batch_size, 159 init_fn=lambda: [None for _ in range(self._cfg.model.agent_num)] 160 ) 161 self._learn_model = model_wrap( 162 self._model, 163 wrapper_name='hidden_state', 164 state_num=self._cfg.learn.batch_size, 165 init_fn=lambda: [None for _ in range(self._cfg.model.agent_num)] 166 ) 167 self._learn_model.reset() 168 self._target_model.reset() 169 170 def _data_preprocess_learn(self, data: List[Dict[str, Any]]) -> Dict[str, Any]: 171 """ 172 Overview: 173 Preprocess the data to fit the required data format for learning 174 Arguments: 175 - data (:obj:`List[Dict[str, Any]]`): the data collected from collect function 176 Returns: 177 - data (:obj:`Dict[str, Any]`): the processed data, from \ 178 [len=B, ele={dict_key: [len=T, ele=Tensor(any_dims)]}] -> {dict_key: Tensor([T, B, any_dims])} 179 """ 180 # data preprocess 181 data = timestep_collate(data) 182 if self._cuda: 183 data = to_device(data, self._device) 184 data['weight'] = data.get('weight', None) 185 data['done'] = data['done'].float() 186 return data 187 188 def _forward_learn(self, data: List[List[Dict[str, Any]]]) -> Dict[str, Any]: 189 """ 190 Overview: 191 Policy forward function of learn mode (training policy and updating parameters). Forward means \ 192 that the policy inputs some training batch data (trajectory for QMIX) from the replay buffer and then \ 193 returns the output result, including various training information such as loss, q value, grad_norm. 194 Arguments: 195 - data (:obj:`List[List[Dict[int, Any]]]`): The input data used for policy forward, including a batch of \ 196 training samples. For each dict element, the key of the dict is the name of data items and the \ 197 value is the corresponding data. Usually, the value is torch.Tensor or np.ndarray or there dict/list \ 198 combinations. In the ``_forward_learn`` method, data often need to first be stacked in the time and \ 199 batch dimension by the utility functions ``self._data_preprocess_learn``. \ 200 For QMIX, each element in list is a trajectory with the length of ``unroll_len``, and the element in \ 201 trajectory list is a dict containing at least the following keys: ``obs``, ``action``, ``prev_state``, \ 202 ``reward``, ``next_obs``, ``done``. Sometimes, it also contains other keys such as ``weight`` \ 203 and ``value_gamma``. 204 Returns: 205 - info_dict (:obj:`Dict[str, Any]`): The information dict that indicated training result, which will be \ 206 recorded in text log and tensorboard, values must be python scalar or a list of scalars. For the \ 207 detailed definition of the dict, refer to the code of ``_monitor_vars_learn`` method. 208 209 .. note:: 210 The input value can be torch.Tensor or dict/list combinations and current policy supports all of them. \ 211 For the data type that not supported, the main reason is that the corresponding model does not support it. \ 212 You can implement you own model rather than use the default model. For more information, please raise an \ 213 issue in GitHub repo and we will continue to follow up. 214 215 .. note:: 216 For more detailed examples, please refer to our unittest for QMIXPolicy: ``ding.policy.tests.test_qmix``. 217 """ 218 data = self._data_preprocess_learn(data) 219 # ==================== 220 # Q-mix forward 221 # ==================== 222 self._learn_model.train() 223 self._target_model.train() 224 # for hidden_state plugin, we need to reset the main model and target model 225 self._learn_model.reset(state=data['prev_state'][0]) 226 self._target_model.reset(state=data['prev_state'][0]) 227 inputs = {'obs': data['obs'], 'action': data['action']} 228 total_q = self._learn_model.forward(inputs, single_step=False)['total_q'] 229 230 if self._cfg.learn.double_q: 231 next_inputs = {'obs': data['next_obs']} 232 self._learn_model.reset(state=data['prev_state'][1]) 233 logit_detach = self._learn_model.forward(next_inputs, single_step=False)['logit'].clone().detach() 234 next_inputs = {'obs': data['next_obs'], 'action': logit_detach.argmax(dim=-1)} 235 else: 236 next_inputs = {'obs': data['next_obs']} 237 with torch.no_grad(): 238 target_total_q = self._target_model.forward(next_inputs, single_step=False)['total_q'] 239 240 with torch.no_grad(): 241 if data['done'] is not None: 242 target_v = self._gamma * (1 - data['done']) * target_total_q + data['reward'] 243 else: 244 target_v = self._gamma * target_total_q + data['reward'] 245 246 data = v_1step_td_data(total_q, target_total_q, data['reward'], data['done'], data['weight']) 247 loss, td_error_per_sample = v_1step_td_error(data, self._gamma) 248 # ==================== 249 # Q-mix update 250 # ==================== 251 self._optimizer.zero_grad() 252 loss.backward() 253 grad_norm = torch.nn.utils.clip_grad_norm_(self._model.parameters(), self._cfg.learn.clip_value) 254 self._optimizer.step() 255 # ============= 256 # after update 257 # ============= 258 self._target_model.update(self._learn_model.state_dict()) 259 return { 260 'cur_lr': self._optimizer.defaults['lr'], 261 'total_loss': loss.item(), 262 'total_q': total_q.mean().item() / self._cfg.model.agent_num, 263 'target_reward_total_q': target_v.mean().item() / self._cfg.model.agent_num, 264 'target_total_q': target_total_q.mean().item() / self._cfg.model.agent_num, 265 'grad_norm': grad_norm, 266 } 267 268 def _reset_learn(self, data_id: Optional[List[int]] = None) -> None: 269 """ 270 Overview: 271 Reset some stateful variables for learn mode when necessary, such as the hidden state of RNN or the \ 272 memory bank of some special algortihms. If ``data_id`` is None, it means to reset all the stateful \ 273 varaibles. Otherwise, it will reset the stateful variables according to the ``data_id``. For example, \ 274 different trajectories in ``data_id`` will have different hidden state in RNN. 275 Arguments: 276 - data_id (:obj:`Optional[List[int]]`): The id of the data, which is used to reset the stateful variables \ 277 (i.e. RNN hidden_state in QMIX) specified by ``data_id``. 278 """ 279 self._learn_model.reset(data_id=data_id) 280 281 def _state_dict_learn(self) -> Dict[str, Any]: 282 """ 283 Overview: 284 Return the state_dict of learn mode, usually including model, target_model and optimizer. 285 Returns: 286 - state_dict (:obj:`Dict[str, Any]`): The dict of current policy learn state, for saving and restoring. 287 """ 288 return { 289 'model': self._learn_model.state_dict(), 290 'target_model': self._target_model.state_dict(), 291 'optimizer': self._optimizer.state_dict(), 292 } 293 294 def _load_state_dict_learn(self, state_dict: Dict[str, Any]) -> None: 295 """ 296 Overview: 297 Load the state_dict variable into policy learn mode. 298 Arguments: 299 - state_dict (:obj:`Dict[str, Any]`): The dict of policy learn state saved before. 300 301 .. tip:: 302 If you want to only load some parts of model, you can simply set the ``strict`` argument in \ 303 load_state_dict to ``False``, or refer to ``ding.torch_utils.checkpoint_helper`` for more \ 304 complicated operation. 305 """ 306 self._learn_model.load_state_dict(state_dict['model']) 307 self._target_model.load_state_dict(state_dict['target_model']) 308 self._optimizer.load_state_dict(state_dict['optimizer']) 309 310 def _init_collect(self) -> None: 311 """ 312 Overview: 313 Initialize the collect mode of policy, including related attributes and modules. For QMIX, it contains the \ 314 collect_model to balance the exploration and exploitation with epsilon-greedy sample mechanism and \ 315 maintain the hidden state of rnn. Besides, there are some initialization operations about other \ 316 algorithm-specific arguments such as burnin_step, unroll_len and nstep. 317 This method will be called in ``__init__`` method if ``collect`` field is in ``enable_field``. 318 319 .. note:: 320 If you want to set some spacial member variables in ``_init_collect`` method, you'd better name them \ 321 with prefix ``_collect_`` to avoid conflict with other modes, such as ``self._collect_attr1``. 322 """ 323 self._unroll_len = self._cfg.collect.unroll_len 324 self._collect_model = model_wrap( 325 self._model, 326 wrapper_name='hidden_state', 327 state_num=self._cfg.collect.env_num, 328 save_prev_state=True, 329 init_fn=lambda: [None for _ in range(self._cfg.model.agent_num)] 330 ) 331 self._collect_model = model_wrap(self._collect_model, wrapper_name='eps_greedy_sample') 332 self._collect_model.reset() 333 334 def _forward_collect(self, data: Dict[int, Any], eps: float) -> Dict[int, Any]: 335 """ 336 Overview: 337 Policy forward function of collect mode (collecting training data by interacting with envs). Forward means \ 338 that the policy gets some necessary data (mainly observation) from the envs and then returns the output \ 339 data, such as the action to interact with the envs. Besides, this policy also needs ``eps`` argument for \ 340 exploration, i.e., classic epsilon-greedy exploration strategy. 341 Arguments: 342 - data (:obj:`Dict[int, Any]`): The input data used for policy forward, including at least the obs. The \ 343 key of the dict is environment id and the value is the corresponding data of the env. 344 - eps (:obj:`float`): The epsilon value for exploration. 345 Returns: 346 - output (:obj:`Dict[int, Any]`): The output data of policy forward, including at least the action and \ 347 other necessary data (prev_state) for learn mode defined in ``self._process_transition`` method. The \ 348 key of the dict is the same as the input data, i.e. environment id. 349 350 .. note:: 351 RNN's hidden states are maintained in the policy, so we don't need pass them into data but to reset the \ 352 hidden states with ``_reset_collect`` method when episode ends. Besides, the previous hidden states are \ 353 necessary for training, so we need to return them in ``_process_transition`` method. 354 .. note:: 355 The input value can be torch.Tensor or dict/list combinations and current policy supports all of them. \ 356 For the data type that not supported, the main reason is that the corresponding model does not support it. \ 357 You can implement you own model rather than use the default model. For more information, please raise an \ 358 issue in GitHub repo and we will continue to follow up. 359 360 .. note:: 361 For more detailed examples, please refer to our unittest for QMIXPolicy: ``ding.policy.tests.test_qmix``. 362 """ 363 data_id = list(data.keys()) 364 data = default_collate(list(data.values())) 365 if self._cuda: 366 data = to_device(data, self._device) 367 data = {'obs': data} 368 self._collect_model.eval() 369 with torch.no_grad(): 370 output = self._collect_model.forward(data, eps=eps, data_id=data_id) 371 if self._cuda: 372 output = to_device(output, 'cpu') 373 output = default_decollate(output) 374 return {i: d for i, d in zip(data_id, output)} 375 376 def _reset_collect(self, data_id: Optional[List[int]] = None) -> None: 377 """ 378 Overview: 379 Reset some stateful variables for eval mode when necessary, such as the hidden state of RNN or the \ 380 memory bank of some special algortihms. If ``data_id`` is None, it means to reset all the stateful \ 381 varaibles. Otherwise, it will reset the stateful variables according to the ``data_id``. For example, \ 382 different environments/episodes in evaluation in ``data_id`` will have different hidden state in RNN. 383 Arguments: 384 - data_id (:obj:`Optional[List[int]]`): The id of the data, which is used to reset the stateful variables \ 385 (i.e., RNN hidden_state in QMIX) specified by ``data_id``. 386 """ 387 self._collect_model.reset(data_id=data_id) 388 389 def _process_transition(self, obs: torch.Tensor, policy_output: Dict[str, torch.Tensor], 390 timestep: namedtuple) -> Dict[str, torch.Tensor]: 391 """ 392 Overview: 393 Process and pack one timestep transition data into a dict, which can be directly used for training and \ 394 saved in replay buffer. For QMIX, it contains obs, next_obs, action, prev_state, reward, done. 395 Arguments: 396 - obs (:obj:`torch.Tensor`): The env observation of current timestep, usually including ``agent_obs`` \ 397 and ``global_obs`` in multi-agent environment like MPE and SMAC. 398 - policy_output (:obj:`Dict[str, torch.Tensor]`): The output of the policy network with the observation \ 399 as input. For QMIX, it contains the action and the prev_state of RNN. 400 - timestep (:obj:`namedtuple`): The execution result namedtuple returned by the environment step method, \ 401 except all the elements have been transformed into tensor data. Usually, it contains the next obs, \ 402 reward, done, info, etc. 403 Returns: 404 - transition (:obj:`Dict[str, torch.Tensor]`): The processed transition data of the current timestep. 405 """ 406 transition = { 407 'obs': obs, 408 'next_obs': timestep.obs, 409 'prev_state': policy_output['prev_state'], 410 'action': policy_output['action'], 411 'reward': timestep.reward, 412 'done': timestep.done, 413 } 414 return transition 415 416 def _get_train_sample(self, transitions: List[Dict[str, Any]]) -> List[Dict[str, Any]]: 417 """ 418 Overview: 419 For a given trajectory (transitions, a list of transition) data, process it into a list of sample that \ 420 can be used for training directly. In QMIX, a train sample is processed transitions with unroll_len \ 421 length. This method is usually used in collectors to execute necessary \ 422 RL data preprocessing before training, which can help learner amortize revelant time consumption. \ 423 In addition, you can also implement this method as an identity function and do the data processing \ 424 in ``self._forward_learn`` method. 425 Arguments: 426 - transitions (:obj:`List[Dict[str, Any]`): The trajectory data (a list of transition), each element is \ 427 the same format as the return value of ``self._process_transition`` method. 428 Returns: 429 - samples (:obj:`List[Dict[str, Any]]`): The processed train samples, each sample is a fixed-length \ 430 trajectory, and each element in a sample is the similar format as input transitions. 431 """ 432 return get_train_sample(transitions, self._unroll_len) 433 434 def _init_eval(self) -> None: 435 """ 436 Overview: 437 Initialize the eval mode of policy, including related attributes and modules. For QMIX, it contains the \ 438 eval model to greedily select action with argmax q_value mechanism and main the hidden state. 439 This method will be called in ``__init__`` method if ``eval`` field is in ``enable_field``. 440 441 .. note:: 442 If you want to set some spacial member variables in ``_init_eval`` method, you'd better name them \ 443 with prefix ``_eval_`` to avoid conflict with other modes, such as ``self._eval_attr1``. 444 """ 445 self._eval_model = model_wrap( 446 self._model, 447 wrapper_name='hidden_state', 448 state_num=self._cfg.eval.env_num, 449 save_prev_state=True, 450 init_fn=lambda: [None for _ in range(self._cfg.model.agent_num)] 451 ) 452 self._eval_model = model_wrap(self._eval_model, wrapper_name='argmax_sample') 453 self._eval_model.reset() 454 455 def _forward_eval(self, data: dict) -> dict: 456 """ 457 Overview: 458 Policy forward function of eval mode (evaluation policy performance by interacting with envs). Forward \ 459 means that the policy gets some necessary data (mainly observation) from the envs and then returns the \ 460 action to interact with the envs. ``_forward_eval`` often use argmax sample method to get actions that \ 461 q_value is the highest. 462 Arguments: 463 - data (:obj:`Dict[int, Any]`): The input data used for policy forward, including at least the obs. The \ 464 key of the dict is environment id and the value is the corresponding data of the env. 465 Returns: 466 - output (:obj:`Dict[int, Any]`): The output data of policy forward, including at least the action. The \ 467 key of the dict is the same as the input data, i.e. environment id. 468 469 .. note:: 470 RNN's hidden states are maintained in the policy, so we don't need pass them into data but to reset the \ 471 hidden states with ``_reset_eval`` method when the episode ends. 472 473 .. note:: 474 The input value can be torch.Tensor or dict/list combinations and current policy supports all of them. \ 475 For the data type that not supported, the main reason is that the corresponding model does not support it. \ 476 You can implement you own model rather than use the default model. For more information, please raise an \ 477 issue in GitHub repo and we will continue to follow up. 478 479 .. note:: 480 For more detailed examples, please refer to our unittest for QMIXPolicy: ``ding.policy.tests.test_qmix``. 481 """ 482 data_id = list(data.keys()) 483 data = default_collate(list(data.values())) 484 if self._cuda: 485 data = to_device(data, self._device) 486 data = {'obs': data} 487 self._eval_model.eval() 488 with torch.no_grad(): 489 output = self._eval_model.forward(data, data_id=data_id) 490 if self._cuda: 491 output = to_device(output, 'cpu') 492 output = default_decollate(output) 493 return {i: d for i, d in zip(data_id, output)} 494 495 def _reset_eval(self, data_id: Optional[List[int]] = None) -> None: 496 """ 497 Overview: 498 Reset some stateful variables for eval mode when necessary, such as the hidden state of RNN or the \ 499 memory bank of some special algortihms. If ``data_id`` is None, it means to reset all the stateful \ 500 varaibles. Otherwise, it will reset the stateful variables according to the ``data_id``. For example, \ 501 different environments/episodes in evaluation in ``data_id`` will have different hidden state in RNN. 502 Arguments: 503 - data_id (:obj:`Optional[List[int]]`): The id of the data, which is used to reset the stateful variables \ 504 (i.e., RNN hidden_state in QMIX) specified by ``data_id``. 505 """ 506 self._eval_model.reset(data_id=data_id) 507 508 def _monitor_vars_learn(self) -> List[str]: 509 """ 510 Overview: 511 Return the necessary keys for logging the return dict of ``self._forward_learn``. The logger module, such \ 512 as text logger, tensorboard logger, will use these keys to save the corresponding data. 513 Returns: 514 - necessary_keys (:obj:`List[str]`): The list of the necessary keys to be logged. 515 """ 516 return ['cur_lr', 'total_loss', 'total_q', 'target_total_q', 'grad_norm', 'target_reward_total_q']