|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# Copyright 2023 The OpenRL Authors. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +"""""" |
| 18 | +from typing import Union |
| 19 | + |
| 20 | +import numpy as np |
| 21 | +import torch |
| 22 | +from torch.nn.parallel import DistributedDataParallel |
| 23 | + |
| 24 | +from openrl.algorithms.ppo import PPOAlgorithm |
| 25 | + |
| 26 | + |
| 27 | +class A2CAlgorithm(PPOAlgorithm): |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + cfg, |
| 31 | + init_module, |
| 32 | + agent_num: int = 1, |
| 33 | + device: Union[str, torch.device] = "cpu", |
| 34 | + ) -> None: |
| 35 | + super(A2CAlgorithm, self).__init__(cfg, init_module, agent_num, device) |
| 36 | + |
| 37 | + self.num_mini_batch = 1 |
| 38 | + |
| 39 | + def prepare_loss( |
| 40 | + self, |
| 41 | + critic_obs_batch, |
| 42 | + obs_batch, |
| 43 | + rnn_states_batch, |
| 44 | + rnn_states_critic_batch, |
| 45 | + actions_batch, |
| 46 | + masks_batch, |
| 47 | + action_masks_batch, |
| 48 | + old_action_log_probs_batch, |
| 49 | + adv_targ, |
| 50 | + value_preds_batch, |
| 51 | + return_batch, |
| 52 | + active_masks_batch, |
| 53 | + turn_on, |
| 54 | + ): |
| 55 | + if self.use_joint_action_loss: |
| 56 | + critic_obs_batch = self.to_single_np(critic_obs_batch) |
| 57 | + rnn_states_critic_batch = self.to_single_np(rnn_states_critic_batch) |
| 58 | + critic_masks_batch = self.to_single_np(masks_batch) |
| 59 | + value_preds_batch = self.to_single_np(value_preds_batch) |
| 60 | + return_batch = self.to_single_np(return_batch) |
| 61 | + adv_targ = adv_targ.reshape(-1, self.agent_num, 1) |
| 62 | + adv_targ = adv_targ[:, 0, :] |
| 63 | + |
| 64 | + else: |
| 65 | + critic_masks_batch = masks_batch |
| 66 | + |
| 67 | + ( |
| 68 | + values, |
| 69 | + action_log_probs, |
| 70 | + dist_entropy, |
| 71 | + policy_values, |
| 72 | + ) = self.algo_module.evaluate_actions( |
| 73 | + critic_obs_batch, |
| 74 | + obs_batch, |
| 75 | + rnn_states_batch, |
| 76 | + rnn_states_critic_batch, |
| 77 | + actions_batch, |
| 78 | + masks_batch, |
| 79 | + action_masks_batch, |
| 80 | + active_masks_batch, |
| 81 | + critic_masks_batch=critic_masks_batch, |
| 82 | + ) |
| 83 | + |
| 84 | + if self.use_joint_action_loss: |
| 85 | + active_masks_batch = active_masks_batch.reshape(-1, self.agent_num, 1) |
| 86 | + active_masks_batch = active_masks_batch[:, 0, :] |
| 87 | + |
| 88 | + policy_gradient_loss = -adv_targ.detach() * action_log_probs |
| 89 | + if self._use_policy_active_masks: |
| 90 | + policy_action_loss = ( |
| 91 | + torch.sum(policy_gradient_loss, dim=-1, keepdim=True) |
| 92 | + * active_masks_batch |
| 93 | + ).sum() / active_masks_batch.sum() |
| 94 | + else: |
| 95 | + policy_action_loss = torch.sum( |
| 96 | + policy_gradient_loss, dim=-1, keepdim=True |
| 97 | + ).mean() |
| 98 | + |
| 99 | + if self._use_policy_vhead: |
| 100 | + if isinstance(self.algo_module.models["actor"], DistributedDataParallel): |
| 101 | + policy_value_normalizer = self.algo_module.models[ |
| 102 | + "actor" |
| 103 | + ].module.value_normalizer |
| 104 | + else: |
| 105 | + policy_value_normalizer = self.algo_module.models[ |
| 106 | + "actor" |
| 107 | + ].value_normalizer |
| 108 | + policy_value_loss = self.cal_value_loss( |
| 109 | + policy_value_normalizer, |
| 110 | + policy_values, |
| 111 | + value_preds_batch, |
| 112 | + return_batch, |
| 113 | + active_masks_batch, |
| 114 | + ) |
| 115 | + policy_loss = ( |
| 116 | + policy_action_loss + policy_value_loss * self.policy_value_loss_coef |
| 117 | + ) |
| 118 | + else: |
| 119 | + policy_loss = policy_action_loss |
| 120 | + |
| 121 | + # critic update |
| 122 | + if self._use_share_model: |
| 123 | + value_normalizer = self.algo_module.models["model"].value_normalizer |
| 124 | + elif isinstance(self.algo_module.models["critic"], DistributedDataParallel): |
| 125 | + value_normalizer = self.algo_module.models["critic"].module.value_normalizer |
| 126 | + else: |
| 127 | + value_normalizer = self.algo_module.get_critic_value_normalizer() |
| 128 | + value_loss = self.cal_value_loss( |
| 129 | + value_normalizer, |
| 130 | + values, |
| 131 | + value_preds_batch, |
| 132 | + return_batch, |
| 133 | + active_masks_batch, |
| 134 | + ) |
| 135 | + |
| 136 | + loss_list = self.construct_loss_list( |
| 137 | + policy_loss, dist_entropy, value_loss, turn_on |
| 138 | + ) |
| 139 | + ratio = np.zeros(1) |
| 140 | + return loss_list, value_loss, policy_loss, dist_entropy, ratio |
| 141 | + |
| 142 | + def train(self, buffer, turn_on: bool = True): |
| 143 | + train_info = super(A2CAlgorithm, self).train(buffer, turn_on) |
| 144 | + train_info.pop("ratio", None) |
| 145 | + return train_info |
0 commit comments