|
| 1 | +from model import Critic, Actor |
| 2 | +import torch as th |
| 3 | +from copy import deepcopy |
| 4 | +from memory import ReplayMemory, Experience |
| 5 | +from torch.optim import Adam |
| 6 | +from randomProcess import OrnsteinUhlenbeckProcess |
| 7 | +from torch.autograd import Variable |
| 8 | +import torch.nn as nn |
| 9 | +import numpy as np |
| 10 | +from params import scale_reward |
| 11 | + |
| 12 | + |
| 13 | +def soft_update(target, source, t): |
| 14 | + for target_param, source_param in zip(target.parameters(), |
| 15 | + source.parameters()): |
| 16 | + target_param.data.copy_( |
| 17 | + (1 - t) * target_param.data + t * source_param.data) |
| 18 | + |
| 19 | + |
| 20 | +def hard_update(target, source): |
| 21 | + for target_param, source_param in zip(target.parameters(), |
| 22 | + source.parameters()): |
| 23 | + target_param.data.copy_(source_param.data) |
| 24 | + |
| 25 | + |
| 26 | +class MADDPG: |
| 27 | + def __init__(self, n_agents, dim_obs, dim_act, batch_size, |
| 28 | + capacity, episodes_before_train): |
| 29 | + self.actors = [Actor(dim_obs, dim_act) for i in range(n_agents)] |
| 30 | + self.critics = [Critic(n_agents, dim_obs, |
| 31 | + dim_act) for i in range(n_agents)] |
| 32 | + self.actors_target = deepcopy(self.actors) |
| 33 | + self.critics_target = deepcopy(self.critics) |
| 34 | + |
| 35 | + self.n_agents = n_agents |
| 36 | + self.n_states = dim_obs |
| 37 | + self.n_actions = dim_act |
| 38 | + self.memory = ReplayMemory(capacity) |
| 39 | + self.batch_size = batch_size |
| 40 | + self.use_cuda = th.cuda.is_available() |
| 41 | + self.episodes_before_train = episodes_before_train |
| 42 | + |
| 43 | + self.GAMMA = 0.95 |
| 44 | + self.tau = 0.01 |
| 45 | + |
| 46 | + self.var = [1.0 for i in range(n_agents)] |
| 47 | + self.critic_optimizer = [Adam(x.parameters(), |
| 48 | + lr=0.001) for x in self.critics] |
| 49 | + self.actor_optimizer = [Adam(x.parameters(), |
| 50 | + lr=0.0001) for x in self.actors] |
| 51 | + |
| 52 | + if self.use_cuda: |
| 53 | + for x in self.actors: |
| 54 | + x.cuda() |
| 55 | + for x in self.critics: |
| 56 | + x.cuda() |
| 57 | + for x in self.actors_target: |
| 58 | + x.cuda() |
| 59 | + for x in self.critics_target: |
| 60 | + x.cuda() |
| 61 | + |
| 62 | + self.steps_done = 0 |
| 63 | + self.episode_done = 0 |
| 64 | + |
| 65 | + def update_policy(self): |
| 66 | + # do not train until exploration is enough |
| 67 | + if self.episode_done <= self.episodes_before_train: |
| 68 | + return None, None |
| 69 | + |
| 70 | + ByteTensor = th.cuda.ByteTensor if self.use_cuda else th.ByteTensor |
| 71 | + FloatTensor = th.cuda.FloatTensor if self.use_cuda else th.FloatTensor |
| 72 | + |
| 73 | + c_loss = [] |
| 74 | + a_loss = [] |
| 75 | + for agent in range(self.n_agents): |
| 76 | + transitions = self.memory.sample(self.batch_size) |
| 77 | + batch = Experience(*zip(*transitions)) |
| 78 | + non_final_mask = ByteTensor(list(map(lambda s: s is not None, |
| 79 | + batch.next_states))) |
| 80 | + # state_batch: batch_size x n_agents x dim_obs |
| 81 | + state_batch = Variable(th.stack(batch.states).type(FloatTensor)) |
| 82 | + action_batch = Variable(th.stack(batch.actions).type(FloatTensor)) |
| 83 | + reward_batch = Variable(th.stack(batch.rewards).type(FloatTensor)) |
| 84 | + # : (batch_size_non_final) x n_agents x dim_obs |
| 85 | + non_final_next_states = Variable(th.stack( |
| 86 | + [s for s in batch.next_states |
| 87 | + if s is not None]).type(FloatTensor)) |
| 88 | + |
| 89 | + # for current agent |
| 90 | + whole_state = state_batch.view(self.batch_size, -1) |
| 91 | + whole_action = action_batch.view(self.batch_size, -1) |
| 92 | + self.critic_optimizer[agent].zero_grad() |
| 93 | + current_Q = self.critics[agent](whole_state, whole_action) |
| 94 | + |
| 95 | + non_final_next_actions = [ |
| 96 | + self.actors_target[i](non_final_next_states[:, |
| 97 | + i, |
| 98 | + :]) for i in range( |
| 99 | + self.n_agents)] |
| 100 | + non_final_next_actions = th.stack(non_final_next_actions) |
| 101 | +# non_final_next_actions = Variable(non_final_next_actions) |
| 102 | + non_final_next_actions = ( |
| 103 | + non_final_next_actions.transpose(0, |
| 104 | + 1).contiguous()) |
| 105 | + |
| 106 | + target_Q = Variable(th.zeros( |
| 107 | + self.batch_size).type(FloatTensor)) |
| 108 | + target_Q[non_final_mask] = self.critics_target[agent]( |
| 109 | + non_final_next_states.view(-1, self.n_agents * self.n_states), |
| 110 | + non_final_next_actions.view(-1, |
| 111 | + self.n_agents * self.n_actions)) |
| 112 | + |
| 113 | + # scale_reward: to scale reward in Q functions |
| 114 | + target_Q = (target_Q * self.GAMMA) + ( |
| 115 | + reward_batch[:, agent] * scale_reward) |
| 116 | + |
| 117 | + loss_Q = nn.MSELoss()(current_Q, target_Q.detach()) |
| 118 | + loss_Q.backward() |
| 119 | + self.critic_optimizer[agent].step() |
| 120 | + |
| 121 | + self.actor_optimizer[agent].zero_grad() |
| 122 | + state_i = state_batch[:, agent, :] |
| 123 | + action_i = self.actors[agent](state_i) |
| 124 | + ac = action_batch.clone() |
| 125 | + ac[:, agent, :] = action_i |
| 126 | + whole_action = ac.view(self.batch_size, -1) |
| 127 | + actor_loss = -self.critics[agent](whole_state, whole_action) |
| 128 | + actor_loss = actor_loss.mean() |
| 129 | + actor_loss.backward() |
| 130 | + self.actor_optimizer[agent].step() |
| 131 | + c_loss.append(loss_Q) |
| 132 | + a_loss.append(actor_loss) |
| 133 | + |
| 134 | + if self.steps_done % 100 == 0 and self.steps_done > 0: |
| 135 | + for i in range(self.n_agents): |
| 136 | + soft_update(self.critics_target[i], self.critics[i], self.tau) |
| 137 | + soft_update(self.actors_target[i], self.actors[i], self.tau) |
| 138 | + |
| 139 | + return c_loss, a_loss |
| 140 | + |
| 141 | + def select_action(self, state_batch): |
| 142 | + # state_batch: n_agents x state_dim |
| 143 | + actions = Variable(th.zeros( |
| 144 | + self.n_agents, |
| 145 | + self.n_actions)) |
| 146 | + FloatTensor = th.cuda.FloatTensor if self.use_cuda else th.FloatTensor |
| 147 | + for i in range(self.n_agents): |
| 148 | + sb = state_batch[i, :].detach() |
| 149 | + act = self.actors[i](sb.unsqueeze(0)).squeeze() |
| 150 | + |
| 151 | + act += Variable( |
| 152 | + th.from_numpy( |
| 153 | + np.random.randn(2) * self.var[i]).type(FloatTensor)) |
| 154 | + |
| 155 | + if self.episode_done > self.episodes_before_train and\ |
| 156 | + self.var[i] > 0.05: |
| 157 | + self.var[i] *= 0.999998 |
| 158 | + act = th.clamp(act, -1.0, 1.0) |
| 159 | + |
| 160 | + actions[i, :] = act |
| 161 | + self.steps_done += 1 |
| 162 | + |
| 163 | + return actions |
0 commit comments