|
| 1 | +import os |
| 2 | +from itertools import chain |
| 3 | + |
| 4 | +import torch |
| 5 | +import torch.nn.functional as F |
| 6 | +from torch.utils.tensorboard import SummaryWriter |
| 7 | + |
| 8 | +from td3.utils import ReplayBuffer |
| 9 | +from td3.networks import Actor, Critic |
| 10 | + |
| 11 | + |
| 12 | +class Agent: |
| 13 | + def __init__(self, env, alpha, beta, hidden_dims, tau, |
| 14 | + batch_size, gamma, d, warmup, max_size, c, |
| 15 | + sigma, one_device, log_dir, checkpoint_dir): |
| 16 | + state_space = env.observation_space.shape[0] |
| 17 | + n_actions = env.action_space.shape[0] |
| 18 | + |
| 19 | + # training params |
| 20 | + self.gamma = gamma |
| 21 | + self.tau = tau |
| 22 | + self.max_action = env.action_space.high[0] |
| 23 | + self.min_action = env.action_space.low[0] |
| 24 | + self.buffer = ReplayBuffer(max_size, state_space, n_actions) |
| 25 | + self.batch_size = batch_size |
| 26 | + self.learn_step_counter = 0 |
| 27 | + self.time_step = 0 |
| 28 | + self.warmup = warmup |
| 29 | + self.n_actions = n_actions |
| 30 | + self.d = d |
| 31 | + self.c = c |
| 32 | + self.sigma = sigma |
| 33 | + |
| 34 | + # training device |
| 35 | + if one_device: |
| 36 | + os.environ["CUDA_VISIBLE_DEVICES"] = "0" |
| 37 | + self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') |
| 38 | + |
| 39 | + # logging/checkpointing |
| 40 | + self.writer = SummaryWriter(log_dir) |
| 41 | + self.checkpoint_dir = checkpoint_dir |
| 42 | + |
| 43 | + # networks & optimizers |
| 44 | + self.actor = Actor(state_space, hidden_dims, n_actions, 'actor').to(self.device) |
| 45 | + self.critic_1 = Critic(state_space, hidden_dims, n_actions, 'critic_1').to(self.device) |
| 46 | + self.critic_2 = Critic(state_space, hidden_dims, n_actions, 'critic_2').to(self.device) |
| 47 | + |
| 48 | + self.critic_optimizer = torch.optim.Adam( |
| 49 | + chain(self.critic_1.parameters(), self.critic_2.parameters()), lr=beta) |
| 50 | + self.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=alpha) |
| 51 | + |
| 52 | + self.target_actor = Actor(state_space, hidden_dims, n_actions, 'target_actor').to(self.device) |
| 53 | + self.target_critic_1 = Critic(state_space, hidden_dims, n_actions, 'target_critic_1').to(self.device) |
| 54 | + self.target_critic_2 = Critic(state_space, hidden_dims, n_actions, 'target_critic_2').to(self.device) |
| 55 | + |
| 56 | + # copy weights |
| 57 | + self.update_network_parameters(tau=1) |
| 58 | + |
| 59 | + def _get_noise(self, clip=True): |
| 60 | + noise = torch.randn(self.n_actions, dtype=torch.float, device=self.device) * self.sigma |
| 61 | + if clip: |
| 62 | + noise = noise.clamp(-self.c, self.c) |
| 63 | + return noise |
| 64 | + |
| 65 | + def _clamp_action_bound(self, action): |
| 66 | + return action.clamp(self.min_action, self.max_action) |
| 67 | + |
| 68 | + def choose_action(self, observation): |
| 69 | + if self.time_step < self.warmup: |
| 70 | + mu = self._get_noise(clip=False) |
| 71 | + else: |
| 72 | + state = torch.tensor(observation, dtype=torch.float).to(self.device) |
| 73 | + mu = self.actor(state) + self._get_noise(clip=False) |
| 74 | + self.time_step += 1 |
| 75 | + return self._clamp_action_bound(mu).cpu().detach().numpy() |
| 76 | + |
| 77 | + def remember(self, state, action, reward, state_, done): |
| 78 | + self.buffer.store_transition(state, action, reward, state_, done) |
| 79 | + |
| 80 | + def critic_step(self, state, action, reward, state_, done): |
| 81 | + # get target actions w/ noise |
| 82 | + target_actions = self.target_actor(state_) + self._get_noise() |
| 83 | + target_actions = self._clamp_action_bound(target_actions) |
| 84 | + |
| 85 | + # target & online values |
| 86 | + q1_ = self.target_critic_1(state_, target_actions) |
| 87 | + q2_ = self.target_critic_2(state_, target_actions) |
| 88 | + |
| 89 | + # done mask |
| 90 | + q1_[done], q2_[done] = 0.0, 0.0 |
| 91 | + |
| 92 | + q1 = self.critic_1(state, action) |
| 93 | + q2 = self.critic_2(state, action) |
| 94 | + |
| 95 | + q1_ = q1_.view(-1) |
| 96 | + q2_ = q2_.view(-1) |
| 97 | + |
| 98 | + critic_value_ = torch.min(q1_, q2_) |
| 99 | + |
| 100 | + target = reward + self.gamma * critic_value_ |
| 101 | + target = target.unsqueeze(1) |
| 102 | + |
| 103 | + self.critic_optimizer.zero_grad() |
| 104 | + |
| 105 | + q1_loss = F.mse_loss(target, q1) |
| 106 | + q2_loss = F.mse_loss(target, q2) |
| 107 | + critic_loss = q1_loss + q2_loss |
| 108 | + critic_loss.backward() |
| 109 | + self.critic_optimizer.step() |
| 110 | + |
| 111 | + self.writer.add_scalar('Critic loss', critic_loss.item(), global_step=self.learn_step_counter) |
| 112 | + |
| 113 | + def actor_step(self, state): |
| 114 | + # calculate loss, update actor params |
| 115 | + self.actor_optimizer.zero_grad() |
| 116 | + actor_loss = -torch.mean(self.critic_1(state, self.actor(state))) |
| 117 | + actor_loss.backward() |
| 118 | + self.actor_optimizer.step() |
| 119 | + |
| 120 | + # update & log |
| 121 | + self.update_network_parameters() |
| 122 | + self.writer.add_scalar('Actor loss', actor_loss.item(), global_step=self.learn_step_counter) |
| 123 | + |
| 124 | + def learn(self): |
| 125 | + self.learn_step_counter += 1 |
| 126 | + |
| 127 | + # if the buffer is not yet filled w/ enough samples |
| 128 | + if self.buffer.counter < self.batch_size: |
| 129 | + return |
| 130 | + |
| 131 | + # transitions |
| 132 | + state, action, reward, state_, done = self.buffer.sample_buffer(self.batch_size) |
| 133 | + reward = torch.tensor(reward, dtype=torch.float).to(self.device) |
| 134 | + done = torch.tensor(done).to(self.device) |
| 135 | + state = torch.tensor(state, dtype=torch.float).to(self.device) |
| 136 | + state_ = torch.tensor(state_, dtype=torch.float).to(self.device) |
| 137 | + action = torch.tensor(action, dtype=torch.float).to(self.device) |
| 138 | + |
| 139 | + self.critic_step(state, action, reward, state_, done) |
| 140 | + if self.learn_step_counter % self.d == 0: |
| 141 | + self.actor_step(state) |
| 142 | + |
| 143 | + def momentum_update(self, online_network, target_network, tau): |
| 144 | + for param_o, param_t in zip(online_network.parameters(), target_network.parameters()): |
| 145 | + param_t.data = param_t.data * tau + param_o.data * (1. - tau) |
| 146 | + |
| 147 | + def update_network_parameters(self, tau=None): |
| 148 | + if tau is None: |
| 149 | + tau = self.tau |
| 150 | + self.momentum_update(self.critic_1, self.target_critic_1, tau) |
| 151 | + self.momentum_update(self.critic_2, self.target_critic_2, tau) |
| 152 | + self.momentum_update(self.actor, self.target_actor, tau) |
| 153 | + |
| 154 | + def add_scalar(self, tag, scalar_value, global_step=None): |
| 155 | + self.writer.add_scalar(tag, scalar_value, global_step=global_step) |
| 156 | + |
| 157 | + def save_networks(self): |
| 158 | + torch.save({ |
| 159 | + 'actor': self.actor.state_dict(), |
| 160 | + 'target_actor': self.target_actor.state_dict(), |
| 161 | + 'critic_1': self.critic_1.state_dict(), |
| 162 | + 'critic_2': self.critic_2.state_dict(), |
| 163 | + 'target_critic_1': self.target_critic_1.state_dict(), |
| 164 | + 'target_critic_2': self.target_critic_2.state_dict(), |
| 165 | + 'critic_optimizer': self.critic_optimizer.state_dict(), |
| 166 | + 'actor_optimizer': self.actor_optimizer.state_dict(), |
| 167 | + }, self.checkpoint_dir) |
| 168 | + |
| 169 | + def load_state_dicts(self): |
| 170 | + state_dict = torch.load(self.checkpoint_dir) |
| 171 | + self.actor.load_state_dict(state_dict['actor']) |
| 172 | + self.target_actor.load_state_dict(state_dict['target_actor']) |
| 173 | + self.critic_1.load_state_dict(state_dict['critic_1']) |
| 174 | + self.critic_2.load_state_dict(state_dict['critic_2']) |
| 175 | + self.target_critic_1.load_state_dict(state_dict['target_critic_1']) |
| 176 | + self.target_critic_2.load_state_dict(state_dict['target_critic_2']) |
| 177 | + self.critic_optimizer.load_state_dict(state_dict['critic_optimizer']) |
| 178 | + self.actor_optimizer.load_state_dict(state_dict['actor_optimizer']) |
0 commit comments