def train(args, n_actors, batch_queue, prios_queue, param_queue): env = wrapper.make_atari(args.env) env = wrapper.wrap_atari_dqn(env, args) utils.set_global_seeds(args.seed, use_torch=True) model = DuelingDQN(env, args).to(args.device) # model.load_state_dict(torch.load('model_30h.pth')) tgt_model = DuelingDQN(env, args).to(args.device) tgt_model.load_state_dict(model.state_dict()) writer = SummaryWriter(comment="-{}-learner".format(args.env)) optimizer = torch.optim.Adam(model.parameters(), args.lr) # optimizer = torch.optim.RMSprop(model.parameters(), args.lr, alpha=0.95, eps=1.5e-7, centered=True) check_connection(n_actors) param_queue.put(model.state_dict()) learn_idx = 0 ts = time.time() tb_dict = { k: [] for k in ['loss', 'grad_norm', 'max_q', 'mean_q', 'min_q'] } while True: *batch, idxes = batch_queue.get() loss, prios, q_values = utils.compute_loss(model, tgt_model, batch, args.n_steps, args.gamma) grad_norm = utils.update_parameters(loss, model, optimizer, args.max_norm) prios_queue.put((idxes, prios)) batch, idxes, prios = None, None, None learn_idx += 1 tb_dict["loss"].append(float(loss)) tb_dict["grad_norm"].append(float(grad_norm)) tb_dict["max_q"].append(float(torch.max(q_values))) tb_dict["mean_q"].append(float(torch.mean(q_values))) tb_dict["min_q"].append(float(torch.min(q_values))) if args.soft_target_update: tau = args.tau for p_tgt, p in zip(tgt_model.parameters(), model.parameters()): p_tgt.data *= 1 - tau p_tgt.data += tau * p elif learn_idx % args.target_update_interval == 0: print("Updating Target Network..") tgt_model.load_state_dict(model.state_dict()) if learn_idx % args.save_interval == 0: print("Saving Model..") torch.save(model.state_dict(), "model.pth") if learn_idx % args.publish_param_interval == 0: param_queue.put(model.state_dict()) if learn_idx % args.tb_interval == 0: bps = args.tb_interval / (time.time() - ts) print("Step: {:8} / BPS: {:.2f}".format(learn_idx, bps)) writer.add_scalar("learner/BPS", bps, learn_idx) for k, v in tb_dict.items(): writer.add_scalar(f'learner/{k}', np.mean(v), learn_idx) v.clear() ts = time.time()
def train(args, n_actors, batch_queue, prios_queue, param_queue): env = RunTagEnv(width=5, height=5, number_of_subordinates=1, max_steps=1000) #env = wrapper.make_atari(args.env) #env = wrapper.wrap_atari_dqn(env, args) utils.set_global_seeds(args.seed, use_torch=True) model = DuelingDQN(env).to(args.device) tgt_model = DuelingDQN(env).to(args.device) tgt_model.load_state_dict(model.state_dict()) writer = SummaryWriter(comment="-{}-learner".format(args.env)) # optimizer = torch.optim.Adam(model.parameters(), args.lr) optimizer = torch.optim.RMSprop(model.parameters(), args.lr, alpha=0.95, eps=1.5e-7, centered=True) check_connection(n_actors) param_queue.put(model.state_dict()) learn_idx = 0 ts = time.time() while True: *batch, idxes = batch_queue.get() loss, prios = utils.compute_loss(model, tgt_model, batch, args.n_steps, args.gamma) grad_norm = utils.update_parameters(loss, model, optimizer, args.max_norm) print('Updated parameters!') prios_queue.put((idxes, prios)) batch, idxes, prios = None, None, None learn_idx += 1 writer.add_scalar("learner/loss", loss, learn_idx) writer.add_scalar("learner/grad_norm", grad_norm, learn_idx) if learn_idx % args.target_update_interval == 0: print("Updating Target Network..") tgt_model.load_state_dict(model.state_dict()) if learn_idx % args.save_interval == 0: print("Saving Model..") torch.save(model.state_dict(), "model.pth") if learn_idx % args.publish_param_interval == 0: param_queue.put(model.state_dict()) if learn_idx % args.bps_interval == 0: bps = args.bps_interval / (time.time() - ts) print("Step: {:8} / BPS: {:.2f}".format(learn_idx, bps)) writer.add_scalar("learner/BPS", bps, learn_idx) ts = time.time()
class DoubleDuelingDQNAgent(DoubleDQNAgent): """ Interacts with and learns from the environment. Double Dueling DQN. """ def __init__(self, state_size, action_size, seed): """ Initialize an Agent object. :param state_size: dimension of each state; :param action_size: dimension of each action; :param seed: random seed. """ super().__init__(state_size, action_size, seed) # Q-Network self.network_local = DuelingDQN(state_size, action_size, seed).to(DEVICE) self.network_target = DuelingDQN(state_size, action_size, seed).to(DEVICE) self.optimizer = optim.Adam(self.network_local.parameters(), lr=LR)
class Agent(): """Interacts with and learns from the environment.""" def __init__(self, state_size, action_size, seed, model="QNetwork"): """Initialize an Agent object. Params ====== state_size (int): dimension of each state action_size (int): dimension of each action seed (int): random seed """ self.state_size = state_size self.action_size = action_size self.seed = random.seed(seed) # Q-Network if model == "QNetwork": self.qnetwork_local = QNetwork(state_size, action_size, seed).to(device) self.qnetwork_target = QNetwork(state_size, action_size, seed).to(device) if model == "QNetworkConvolutional": self.qnetwork_local = QNetworkConvolutional( state_size, action_size, seed).to(device) self.qnetwork_target = QNetworkConvolutional( state_size, action_size, seed).to(device) if model == "DuelingDQN": self.qnetwork_local = DuelingDQN(state_size, action_size, seed).to(device) self.qnetwork_target = DuelingDQN(state_size, action_size, seed).to(device) print("Model: " + model) self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR) # Replay memory self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed) # Initialize time step (for updating every UPDATE_EVERY steps) self.t_step = 0 def step(self, state, action, reward, next_state, done): # Save experience in replay memory self.memory.add(state, action, reward, next_state, done) # Learn every UPDATE_EVERY time steps. self.t_step = (self.t_step + 1) % UPDATE_EVERY if self.t_step == 0: # If enough samples are available in memory, get random subset and learn if len(self.memory) > BATCH_SIZE: experiences = self.memory.sample() self.learn(experiences, GAMMA) def act(self, state, eps=0.): """Returns actions for given state as per current policy. Params ====== state (array_like): current state eps (float): epsilon, for epsilon-greedy action selection """ state = torch.from_numpy(state).float().unsqueeze(0).to(device) self.qnetwork_local.eval() with torch.no_grad(): action_values = self.qnetwork_local(state) self.qnetwork_local.train() # Epsilon-greedy action selection if random.random() > eps: return np.argmax(action_values.cpu().data.numpy()) else: return random.choice(np.arange(self.action_size)) def learn(self, experiences, gamma): """Update value parameters using given batch of experience tuples. Params ====== experiences (Tuple[torch.Variable]): tuple of (s, a, r, s', done) tuples gamma (float): discount factor """ states, actions, rewards, next_states, dones = experiences # Get max predicted Q values (for next states) from target model Q_targets_next = self.qnetwork_target(next_states).detach().max( 1)[0].unsqueeze(1) # Compute Q targets for current states Q_targets = rewards + (gamma * Q_targets_next * (1 - dones)) # Get expected Q values from local model Q_expected = self.qnetwork_local(states).gather(1, actions) # Compute loss loss = F.mse_loss(Q_expected, Q_targets) # Minimize the loss self.optimizer.zero_grad() loss.backward() self.optimizer.step() # ------------------- update target network ------------------- # self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU) def soft_update(self, local_model, target_model, tau): """Soft update model parameters. θ_target = τ*θ_local + (1 - τ)*θ_target Params ====== local_model (PyTorch model): weights will be copied from target_model (PyTorch model): weights will be copied to tau (float): interpolation parameter """ for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): target_param.data.copy_(tau * local_param.data + (1.0 - tau) * target_param.data)
def learner(args): comm_cross = global_dict['comm_cross'] hvd.init(comm=comm_cross) torch.cuda.set_device(hvd.local_rank()) env = wrap_atari_dqn(make_atari(args['env']), args) # utils.set_global_seeds(args['seed'], use_torch=True) device = args['device'] model = DuelingDQN(env, args).to(device) if os.path.exists('model.pth'): # model.load_state_dict(torch.load('model.pth')) pass tgt_model = DuelingDQN(env, args).to(device) del env writer = SummaryWriter(log_dir=os.path.join( args['log_dir'], f'{global_dict["unit_idx"]}-learner')) # optimizer = torch.optim.SGD(model.parameters(), 1e-5 * args['num_units'], momentum=0.8) # optimizer = torch.optim.RMSprop(model.parameters(), args['lr'], alpha=0.95, eps=1.5e-7, centered=True) optimizer = torch.optim.Adam(model.parameters(), args['lr'] * args['num_units']) optimizer = hvd.DistributedOptimizer( optimizer, named_parameters=model.named_parameters()) hvd.broadcast_parameters(model.state_dict(), root_rank=0) tgt_model.load_state_dict(model.state_dict()) if args['dynamic_gradient_clip']: grad_norm_running_mean = args['gradient_norm_running_mean'] grad_norm_lambda = args['gradient_norm_lambda'] batch_queue = queue.Queue(maxsize=3) prios_queue = queue.Queue(maxsize=4) param_queue = queue.Queue(maxsize=3) threading.Thread(target=recv_batch, args=(batch_queue, )).start() threading.Thread(target=send_prios, args=(prios_queue, )).start() threading.Thread(target=send_param, args=(param_queue, )).start() if global_dict['unit_idx'] == 0: threading.Thread(target=send_param_evaluator, args=(param_queue, )).start() prefetcher = data_prefetcher(batch_queue, args['cuda']) learn_idx = 0 ts = time.time() tb_dict = { k: [] for k in [ 'loss', 'grad_norm', 'max_q', 'mean_q', 'min_q', 'batch_queue_size', 'prios_queue_size' ] } first_rount = True while True: (*batch, idxes) = prefetcher.next() if first_rount: print("start training") sys.stdout.flush() first_rount = False loss, prios, q_values = utils.compute_loss(model, tgt_model, batch, args['n_steps'], args['gamma']) optimizer.zero_grad() loss.backward() if args['dynamic_gradient_clip']: grad_norm = torch.nn.utils.clip_grad_norm_( model.parameters(), grad_norm_running_mean * args['clipping_threshold']) grad_norm_running_mean = grad_norm_running_mean * grad_norm_lambda + \ min(grad_norm, grad_norm_running_mean * args['clipping_threshold']) * (1-grad_norm_lambda) else: grad_norm = torch.norm( torch.stack([ torch.norm(p.grad.detach(), 2) for p in model.parameters() ]), 2) # global_prios_sum = np.array(prios_sum) # comm_cross.Allreduce(MPI.IN_PLACE, global_prios_sum.data) # global_prios_sum = float(global_prios_sum) # scale = prios_sum / global_prios_sum if args['dynamic_gradient_clip'] and args[ 'dropping_threshold'] and grad_norm > grad_norm_running_mean * args[ 'dropping_threshold']: pass else: optimizer.step() prios_queue.put((idxes, prios)) learn_idx += 1 tb_dict["loss"].append(float(loss)) tb_dict["grad_norm"].append(float(grad_norm)) tb_dict["max_q"].append(float(torch.max(q_values))) tb_dict["mean_q"].append(float(torch.mean(q_values))) tb_dict["min_q"].append(float(torch.min(q_values))) tb_dict["batch_queue_size"].append(batch_queue.qsize()) tb_dict["prios_queue_size"].append(prios_queue.qsize()) if learn_idx % args['target_update_interval'] == 0: tgt_model.load_state_dict(model.state_dict()) if learn_idx % args['save_interval'] == 0 and global_dict[ 'unit_idx'] == 0: torch.save(model.state_dict(), "model.pth") if learn_idx % args['publish_param_interval'] == 0: param_queue.put(model.state_dict()) if learn_idx % args['tb_interval'] == 0: bps = args['tb_interval'] / (time.time() - ts) for i, (k, v) in enumerate(tb_dict.items()): writer.add_scalar(f'learner/{i+1}_{k}', np.mean(v), learn_idx) v.clear() writer.add_scalar(f"learner/{i+2}_BPS", bps, learn_idx) ts = time.time()
class PERDoubleDuelingDQNAgent(DoubleDuelingDQNAgent): """ Interacts with and learns from the environment. Double Dueling DQN with prioritized experience replay. """ def __init__(self, state_size, action_size, seed): """ Initialize an Agent object. :param state_size: dimension of each state; :param action_size: dimension of each action; :param seed: random seed. """ super().__init__(state_size, action_size, seed) # Replay memory self.memory = PrioritizedReplayBuffer(BUFFER_SIZE, BATCH_SIZE, state_size, seed) # Q-Network self.network_local = DuelingDQN(state_size, action_size, seed).to(DEVICE) self.network_target = DuelingDQN(state_size, action_size, seed).to(DEVICE) self.optimizer = optim.Adam(self.network_local.parameters(), lr=LR) def learn(self, experiences, gamma): """ Update value parameters using given batch of experience tuples. :param experiences: (Tuple[torch.Tensor]) tuple of (s, a, r, s', done) tuples; :param gamma: discount factor. """ tree_idx, states, actions, rewards, next_states, dones, ISWeights = experiences # Get expected Q values from local model Q_expected = self.network_local(states).gather(1, actions) # Get next actions based on local network next_actions = self.network_local(next_states).detach().max( 1)[1].unsqueeze(1) # Get max predicted Q values (for next states) from target model based on local model next actions Q_targets_next = self.network_target(next_states).detach().gather( 1, next_actions) # Compute Q targets for current states Q_targets = rewards + (gamma * Q_targets_next * (1 - dones)) # Update transition priorities self.memory.batch_update(tree_idx, np.ravel(np.abs(Q_targets.numpy()))) # Compute loss loss = (torch.Tensor(ISWeights).float().to(DEVICE) * F.mse_loss(Q_expected, Q_targets)).mean() # Minimize the loss self.optimizer.zero_grad() loss.backward() self.optimizer.step() # ------------------- update target network ------------------- # self.soft_update(self.network_local, self.network_target, TAU)
class train_DQN(): def __init__(self, env_id, max_step = 1e5, prior_alpha = 0.6, prior_beta_start = 0.4, epsilon_start = 1.0, epsilon_final = 0.01, epsilon_decay = 500, batch_size = 32, gamma = 0.99, target_update_interval=1000, save_interval = 1e4, ): self.prior_beta_start = prior_beta_start self.max_step = int(max_step) self.batch_size = batch_size self.gamma = gamma self.target_update_interval = target_update_interval self.save_interval = save_interval self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") self.env = gym.make(env_id) self.model = DuelingDQN(self.env).to(self.device) self.target_model = DuelingDQN(self.env).to(self.device) self.target_model.load_state_dict(self.model.state_dict()) self.replay_buffer = PrioritizedReplayBuffer(100000,alpha=prior_alpha) self.optimizer = optim.Adam(self.model.parameters()) self.writer = SummaryWriter(comment="-{}-learner".format(self.env.unwrapped.spec.id)) # decay function self.scheduler = optim.lr_scheduler.StepLR(self.optimizer,step_size=1000,gamma=0.99) self.beta_by_frame = lambda frame_idx: min(1.0, self.prior_beta_start + frame_idx * (1.0 - self.prior_beta_start) / 1000) self.epsilon_by_frame = lambda frame_idx: epsilon_final + (epsilon_start - epsilon_final) * math.exp(-1. * frame_idx / epsilon_decay) def update_target(self,current_model, target_model): target_model.load_state_dict(current_model.state_dict()) def compute_td_loss(self,batch_size, beta): state, action, reward, next_state, done, weights, indices = self.replay_buffer.sample(batch_size, beta) state = torch.FloatTensor(state).to(self.device) next_state = torch.FloatTensor(next_state).to(self.device) action = torch.LongTensor(action).to(self.device) reward = torch.FloatTensor(reward).to(self.device) done = torch.FloatTensor(done).to(self.device) weights = torch.FloatTensor(weights).to(self.device) batch = (state, action, reward, next_state, done, weights) # q_values = self.model(state) # next_q_values = self.target_model(next_state) # q_value = q_values.gather(1, action.unsqueeze(1)).squeeze(1) # next_q_value = next_q_values.max(1)[0] # expected_q_value = reward + self.gamma * next_q_value * (1 - done) # td_error = torch.abs(expected_q_value.detach() - q_value) # loss = (td_error).pow(2) * weights # prios = loss+1e-5#0.9 * torch.max(td_error)+(1-0.9)*td_error # loss = loss.mean() loss, prios = utils.compute_loss(self.model,self.target_model, batch,1) self.optimizer.zero_grad() loss.backward() self.scheduler.step() self.replay_buffer.update_priorities(indices, prios) self.optimizer.step() return loss def train(self): losses = [] all_rewards = [] episode_reward = 0 episode_idx = 0 episode_length = 0 state = self.env.reset() for frame_idx in range(self.max_step): epsilon = self.epsilon_by_frame(frame_idx) action,_ = self.model.act(torch.FloatTensor((state)).to(self.device), epsilon) next_state, reward, done, _ = self.env.step(action) self.replay_buffer.add(state, action, reward, next_state, done) state = next_state episode_reward += reward episode_length += 1 if done: state = self.env.reset() all_rewards.append(episode_reward) self.writer.add_scalar("actor/episode_reward", episode_reward, episode_idx) self.writer.add_scalar("actor/episode_length", episode_length, episode_idx) # print("episode: ",episode_idx, " reward: ", episode_reward) episode_reward = 0 episode_length = 0 episode_idx += 1 if len(self.replay_buffer) > self.batch_size: beta = self.beta_by_frame(frame_idx) loss = self.compute_td_loss(self.batch_size, beta) losses.append(loss.item()) self.writer.add_scalar("learner/loss", loss, frame_idx) if frame_idx % self.target_update_interval == 0: print("update target...") self.update_target(self.model, self.target_model) if frame_idx % self.save_interval == 0 or frame_idx == self.max_step-1: print("save model...") self.save_model(frame_idx) def save_model(self, idx): torch.save(self.model.state_dict(), "./model{}.pth".format(idx)) def load_model(self,idx): with open("model{}.pth".format(idx), "rb") as f: print("loading weights_{}".format(idx)) self.model.load_state_dict(torch.load(f,map_location="cpu"))
class Agent(): """Interacts with and learns from the environment.""" def __init__(self, state_size, action_size, seed, max_t=1000): """Initialize an Agent object. Params ====== state_size (int): dimension of each state action_size (int): dimension of each action seed (int): random seed """ self.state_size = state_size self.action_size = action_size self.seed = random.seed(seed) # Q-Network self.qnetwork_local = DuelingDQN(state_size, action_size, seed).to(device) self.qnetwork_target = DuelingDQN(state_size, action_size, seed).to(device) self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR) # Replay memory self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed) # Initialize time step (for updating every UPDATE_EVERY steps) self.t_step = 0 self.prio_b = PRIO_B self.b_step = 0 self.max_b_step = 2000 self.learnFirst = True def step(self, state, action, reward, next_state, done): # Save experience in replay memory #self.memory.add(state, action, reward, next_state, done) # Hassan : Save the experience in prioritized replay memory self.memory.prio_add(state, action, reward, next_state, done) # Learn every UPDATE_EVERY time steps. self.t_step = (self.t_step + 1) % UPDATE_EVERY if self.t_step == 0: # If enough samples are available in memory, get random subset and learn if len(self.memory) > BATCH_SIZE: #experiences = self.memory.sample() #self.learn(experiences, GAMMA) # Hassan : prioritized replay memory self.b_step = self.b_step + 1 experiences, indices = self.memory.prio_sample() self.learn(experiences, GAMMA, indices) def act(self, state, eps=0.): """Returns actions for given state as per current policy. Params ====== state (array_like): current state eps (float): epsilon, for epsilon-greedy action selection """ state = torch.from_numpy(state).float().unsqueeze(0).to(device) self.qnetwork_local.eval() with torch.no_grad(): action_values = self.qnetwork_local(state) self.qnetwork_local.train() # Epsilon-greedy action selection if random.random() > eps: return np.argmax(action_values.cpu().data.numpy()) else: return random.choice(np.arange(self.action_size)) def get_beta(self, t): ''' Return the current exponent β based on its schedul. Linearly anneal β from its initial value β0 to 1, at the end of learning. :param t: integer. Current time step in the episode :return current_beta: float. Current exponent beta ''' #f_frac = min(float(t) / self.max_b_step, 1.0) #current_beta = self.prio_b + f_frac * (1. - self.prio_b) #current_beta = min(1,current_beta) self.prio_b = min(1, self.prio_b + PRIO_B_INC) return self.prio_b def learn(self, experiences, gamma, indices): """Update value parameters using given batch of experience tuples. Params ====== experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples gamma (float): discount factor """ states, actions, rewards, next_states, dones, probabilities = experiences ## TODO: compute and minimize the loss "*** YOUR CODE HERE ***" # Get max predicted Q values (for next states) from target model # Hassan : Action is selected using greedy policy #Q_targets_next = self.qnetwork_target(next_states).detach().max(1)[0].unsqueeze(1) # Hassan : Double DQN # Selecting actions which maximizes while taking w (qnetwork_local) next_actions = self.qnetwork_local(next_states).detach().argmax( dim=1).unsqueeze(1) #next_actions_test = self.qnetwork_local(next_states).detach().max(1)[1].unsqueeze(1) # Hassan : from the example #print(torch.sum(next_actions-next_actions_test)) # Hassan : no difference found # Selecting q values of these actions using w' (qnetwork_target) Q_targets_next = self.qnetwork_target(next_states).gather( 1, next_actions) # Compute Q targets for current states # Hassan : This is TD Target Q_targets = rewards + (gamma * Q_targets_next * (1 - dones)) # Get expected Q values from local model # Hassan : This is current value Q_expected = self.qnetwork_local(states).gather(1, actions) #Hassan : Compute the td_error td_error = Q_targets - Q_expected #print(td_error.detach().numpy()) #self.prio_b = min(1, PRIO_B_INC+self.prio_b) f_currbeta = self.get_beta(0) #print(f_currbeta) #f_currbeta = self.get_beta(self.b_step) #print(self.b_step) #print(t) #print(self.prio_b) weights_importance = probabilities.mul_( self.memory.__len__()).pow_(-f_currbeta) # Hassan : calculate max_weights_importance #probabilities_min = min(self.memory.priorities)/self.memory.cum_priorities probabilities_min = self.memory.min_priority / self.memory.cum_priorities max_weights_importance = (probabilities_min * self.memory.__len__())**(-f_currbeta) # Hassan : divide the weights importance with the max_weights_importance # Hassan : Improvement why not calculating the max_weights_importance = max(weights_importance)?? # Hassan : this will only calculating on the current list not the complete one #print(weights_importance) #print(weights_importance.max(0)[0]) #print(max_weights_importance) #if self.learnFirst: # self.learnFirst = False #else : # max_weights_importance = max_weights_importance[0] weights_final = weights_importance.div_(max_weights_importance) square_weighted_error = td_error.pow_(2).mul_(weights_final) loss = square_weighted_error.mean() # Hassan : after the observations observation from example, update was done after the weights calculation if self.prio_b > 0.5: self.memory.prio_update(indices, td_error.detach().numpy(), PRIO_E, PRIO_A) # Compute loss #loss = F.mse_loss(Q_expected, Q_targets) # Minimize the loss self.optimizer.zero_grad() loss.backward() self.optimizer.step() # ------------------- update target network ------------------- # # Hassan : Here not after C steps w is changed though cahnged slightly after every learn step # Hassan : We can modify to change this after ever C steps self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU) def soft_update(self, local_model, target_model, tau): """Soft update model parameters. θ_target = τ*θ_local + (1 - τ)*θ_target Params ====== local_model (PyTorch model): weights will be copied from target_model (PyTorch model): weights will be copied to tau (float): interpolation parameter """ for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): target_param.data.copy_(tau * local_param.data + (1.0 - tau) * target_param.data)
class Agent(): """Interacts with and learns from the environment.""" def __init__(self, state_size, action_size, seed): """Initialize an Agent object. Params ====== state_size (int): dimension of each state action_size (int): dimension of each action seed (int): random seed """ self.state_size = state_size self.action_size = action_size self.seed = random.seed(seed) # Q-Network self.qnetwork_local = DuelingDQN(state_size, action_size, seed).to(device) self.qnetwork_target = DuelingDQN(state_size, action_size, seed).to(device) self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR) self.priority_alpha = 0.0 #current best: 03 self.priority_beta_start = 0.4 self.priority_beta_frames = BUFFER_SIZE # Replay memory self.memory = PrioritizedReplayMemory(BUFFER_SIZE, self.priority_alpha, self.priority_beta_start, self.priority_beta_frames) # Initialize time step (for updating every UPDATE_EVERY steps) self.t_step = 0 def step(self, state, action, reward, next_state, done): # Save experience in replay memory self.memory.push((state, action, reward, next_state, done)) # Learn every UPDATE_EVERY time steps. self.t_step = (self.t_step + 1) % UPDATE_EVERY if self.t_step == 0: # If enough samples are available in memory, get random subset and learn if self.memory.storage_size() > BATCH_SIZE: #print("storage == ", self.memory.storage_size()) experiences, idxes, weights = self.memory.sample(BATCH_SIZE) self.learn(experiences, idxes, weights, GAMMA) def act(self, state, eps=0.): """Returns actions for given state as per current policy. Params ====== state (array_like): current state eps (float): epsilon, for epsilon-greedy action selection """ state = torch.from_numpy(state).float().unsqueeze(0).to(device) self.qnetwork_local.eval() with torch.no_grad(): action_values = self.qnetwork_local(state) self.qnetwork_local.train() # Epsilon-greedy action selection if random.random() > eps: return np.argmax(action_values.cpu().data.numpy()) else: return random.choice(np.arange(self.action_size)) def learn(self, experiences, idxes, weights, gamma): """Update value parameters using given batch of experience tuples. Params ====== experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples gamma (float): discount factor """ states, actions, rewards, next_states, dones = zip(*experiences) states = torch.from_numpy( np.vstack([state for state in states if state is not None])).float().to(device) actions = torch.from_numpy( np.vstack([action for action in actions if action is not None])).long().to(device) rewards = torch.from_numpy( np.vstack([reward for reward in rewards if reward is not None])).float().to(device) next_states = torch.from_numpy( np.vstack([ next_state for next_state in next_states if next_state is not None ])).float().to(device) dones = torch.from_numpy( np.vstack([done for done in dones if done is not None ]).astype(np.uint8)).float().to(device) # Get max predicted Q values (for next states) from target model #print("state-action values:") #print(self.qnetwork_target(next_states).detach()) #print(next_states) next_target_Q = self.qnetwork_target.forward(next_states) #print("next_target_Q == ", next_target_Q) _, next_local_Q_index = torch.max( self.qnetwork_local.forward(next_states), axis=1) #Q_targets_next = self.qnetwork_target(next_states).detach().max(1)[0].unsqueeze(1) Q_targets_next = next_target_Q[range(next_target_Q.shape[0]), next_local_Q_index] Q_targets_next1 = Q_targets_next.reshape((len(Q_targets_next), 1)) # Compute Q targets for current states Q_targets = rewards + (gamma * Q_targets_next1 * (1 - dones)) # Get expected Q values from local model Q_expected = self.qnetwork_local(states).gather(1, actions) #print(Q_expected) #print(Q_targets) diff = Q_expected - Q_targets #print(diff) #diff = diff.mean() #print(idxes) #print(diff.detach().squeeze().abs().cpu().numpy().tolist()) #update the priority of the replay buffer self.memory.update_priorities( idxes, diff.detach().squeeze().abs().cpu().numpy().tolist()) # Compute loss loss = F.mse_loss(Q_expected, Q_targets) * weights loss = loss.mean() # Minimize the loss self.optimizer.zero_grad() loss.backward() self.optimizer.step() # ------------------- update target network ------------------- # self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU) def soft_update(self, local_model, target_model, tau): """Soft update model parameters. θ_target = τ*θ_local + (1 - τ)*θ_target Params ====== local_model (PyTorch model): weights will be copied from target_model (PyTorch model): weights will be copied to tau (float): interpolation parameter """ for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): target_param.data.copy_(tau * local_param.data + (1.0 - tau) * target_param.data)
class Agent(): """Interacts with and learns from the environment.""" def __init__(self, state_size, action_size, seed,max_t=1000): """Initialize an Agent object. Params ====== state_size (int): dimension of each state action_size (int): dimension of each action seed (int): random seed """ self.state_size = state_size self.action_size = action_size self.seed = random.seed(seed) # Q-Network self.qnetwork_local = DuelingDQN(state_size, action_size, seed).to(device) self.qnetwork_target = DuelingDQN(state_size, action_size, seed).to(device) self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR) # Replay memory self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed) # Initialize time step (for updating every UPDATE_EVERY steps) self.t_step = 0 self.prio_b = PRIO_B self.b_step = 0 self.max_b_step = 2000 self.learnFirst = True def step(self, state, action, reward, next_state, done): # Hassan : Save the experience in prioritized replay memory self.memory.prio_add(state, action, reward, next_state, done) # Learn every UPDATE_EVERY time steps. self.t_step = (self.t_step + 1) % UPDATE_EVERY if self.t_step == 0: # If enough samples are available in memory, get random subset and learn if len(self.memory) > BATCH_SIZE: self.b_step = self.b_step + 1 experiences, indices = self.memory.prio_sample() self.learn(experiences, GAMMA, indices) def act(self, state, eps=0.): """Returns actions for given state as per current policy. Params ====== state (array_like): current state eps (float): epsilon, for epsilon-greedy action selection """ state = torch.from_numpy(state).float().unsqueeze(0).to(device) self.qnetwork_local.eval() with torch.no_grad(): action_values = self.qnetwork_local(state) self.qnetwork_local.train() # Epsilon-greedy action selection if random.random() > eps: return np.argmax(action_values.cpu().data.numpy()) else: return random.choice(np.arange(self.action_size)) def get_beta(self, t): ''' Return the current exponent β based on its schedul. Linearly anneal β from its initial value β0 to 1, at the end of learning. :param t: integer. Current time step in the episode :return current_beta: float. Current exponent beta ''' #f_frac = min(float(t) / self.max_b_step, 1.0) #current_beta = self.prio_b + f_frac * (1. - self.prio_b) #current_beta = min(1,current_beta) self.prio_b = min(1,self.prio_b + PRIO_B_INC) return self.prio_b def learn(self, experiences, gamma, indices): """Update value parameters using given batch of experience tuples. Params ====== experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples gamma (float): discount factor """ states, actions, rewards, next_states, dones, probabilities = experiences "*** YOUR CODE HERE ***" # Double DQN implementation # Selecting actions which maximizes while taking w (qnetwork_local) next_actions = self.qnetwork_local(next_states).detach().argmax(dim=1).unsqueeze(1) # evluate best actions using w' (qnetwork_target) Q_targets_next = self.qnetwork_target(next_states).gather(1, next_actions) # Compute Q targets for current states (TD Target) Q_targets = rewards + (gamma * Q_targets_next * (1 - dones)) # Get expected Q values from local model Q_expected = self.qnetwork_local(states).gather(1, actions) # Compute the td_error td_error = Q_targets - Q_expected f_currbeta = self.get_beta(0) # Prioritized experience replay : calculating the final weights for calculating loss function weights_importance = probabilities.mul_(self.memory.__len__()).pow_(-f_currbeta) probabilities_min = self.memory.min_priority/self.memory.cum_priorities max_weights_importance = (probabilities_min * self.memory.__len__())**(-f_currbeta) weights_final = weights_importance.div_(max_weights_importance) # Compute mean squared weighted error square_weighted_error = td_error.pow_(2).mul_(weights_final) loss = square_weighted_error.mean() self.optimizer.zero_grad() loss.backward() self.optimizer.step() # Prioritized experience replay : updating the priority of experience tuple in replay buffer self.memory.prio_update(indices,td_error.detach().numpy(),PRIO_E,PRIO_A) # ------------------- update target network ------------------- # self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU) def soft_update(self, local_model, target_model, tau): """Soft update model parameters. θ_target = τ*θ_local + (1 - τ)*θ_target Params ====== local_model (PyTorch model): weights will be copied from target_model (PyTorch model): weights will be copied to tau (float): interpolation parameter """ for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)
class Agent: """Interacts with and learns from the environment.""" def __init__(self, config): """Initialize an Agent object""" self.seed = random.seed(config["general"]["seed"]) self.config = config # Q-Network self.q = DuelingDQN(config).to(DEVICE) self.q_target = DuelingDQN(config).to(DEVICE) self.optimizer = optim.RMSprop(self.q.parameters(), lr=config["agent"]["learning_rate"]) self.criterion = F.mse_loss self.memory = ReplayBuffer(config) # Initialize time step (for updating every UPDATE_EVERY steps) self.t_step = 0 def save_experiences(self, state, action, reward, next_state, done): """Prepare and save experience in replay memory""" reward = np.clip(reward, -1.0, 1.0) self.memory.add(state, action, reward, next_state, done) def _current_step_is_a_learning_step(self): """Check if the current step is an update step""" self.t_step = (self.t_step + 1) % self.config["agent"]["update_rate"] return self.t_step == 0 def _enough_samples_in_memory(self): """Check if minimum amount of samples are in memory""" return len(self.memory) > self.config["train"]["batch_size"] def epsilon_greedy_action_selection(self, action_values, eps): """Epsilon-greedy action selection""" if random.random() > eps: return np.argmax(action_values.cpu().data.numpy()) else: return random.choice( np.arange(self.config["general"]["action_size"])) def act(self, state, eps=0.0): """Returns actions for given state as per current policy""" state = torch.from_numpy(state).float().unsqueeze(0).to(DEVICE) self.q.eval() with torch.no_grad(): action_values = self.q(state) self.q.train() return self.epsilon_greedy_action_selection(action_values, eps) def _calc_loss(self, states, actions, rewards, next_states, dones): """Calculates loss for a given experience batch""" q_eval = self.q(states).gather(1, actions) q_eval_next = self.q(next_states) _, q_argmax = q_eval_next.detach().max(1) q_next = self.q_target(next_states) q_next = q_next.gather(1, q_argmax.unsqueeze(1)) q_target = rewards + (self.config["agent"]["gamma"] * q_next * (1 - dones)) loss = self.criterion(q_eval, q_target) return loss def _update_weights(self, loss): """update the q network weights""" torch.nn.utils.clip_grad.clip_grad_value_(self.q.parameters(), 1.0) self.optimizer.zero_grad() loss.backward() self.optimizer.step() def learn(self): """Update network using one sample of experience from memory""" if self._current_step_is_a_learning_step( ) and self._enough_samples_in_memory(): states, actions, rewards, next_states, dones = self.memory.sample( self.config["train"]["batch_size"]) loss = self._calc_loss(states, actions, rewards, next_states, dones) self._update_weights(loss) self._soft_update(self.q, self.q_target) def _soft_update(self, local_model, target_model): """Soft update target network parameters: θ_target = τ*θ_local + (1 - τ)*θ_target""" for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): target_param.data.copy_( self.config["agent"]["tau"] * local_param.data + (1.0 - self.config["agent"]["tau"]) * target_param.data) def save(self): """Save the network weights""" helper.mkdir( os.path.join(".", *self.config["general"]["checkpoint_dir"], self.config["general"]["env_name"])) current_date_time = helper.get_current_date_time() current_date_time = current_date_time.replace(" ", "__").replace( "/", "_").replace(":", "_") torch.save( self.q.state_dict(), os.path.join(".", *self.config["general"]["checkpoint_dir"], self.config["general"]["env_name"], "ckpt_" + current_date_time)) def load(self): """Load latest available network weights""" list_of_files = glob.glob( os.path.join(".", *self.config["general"]["checkpoint_dir"], self.config["general"]["env_name"], "*")) latest_file = max(list_of_files, key=os.path.getctime) self.q.load_state_dict(torch.load(latest_file)) self.q_target.load_state_dict(torch.load(latest_file))
class train_DQN(): def __init__(self, env_id, seed=0, lr=1e-5, n_step=3, gamma=0.99, n_workers=20, max_norm=40, target_update_interval=2500, save_interval=5000, batch_size=64, buffer_size=1e6, prior_alpha=0.6, prior_beta=0.4, publish_param_interval=32, max_step=1e5): self.env = gym.make(env_id) self.seed = seed self.lr = lr self.n_step = n_step self.gamma = gamma self.max_norm = max_norm self.target_update_interval = target_update_interval self.save_interval = save_interval self.publish_param_interval = publish_param_interval self.batch_size = batch_size self.prior_beta = prior_beta self.max_step = max_step self.buffer = CustomPrioritizedReplayBuffer(size=buffer_size, alpha=prior_alpha) self.device = torch.device( "cuda:0" if torch.cuda.is_available() else "cpu") self.model = DuelingDQN(self.env).to(self.device) self.tgt_model = DuelingDQN(self.env).to(self.device) self.tgt_model.load_state_dict(self.model.state_dict()) self.optimizer = torch.optim.RMSprop(self.model.parameters(), self.lr, alpha=0.95, eps=1.5e-7, centered=True) self.scheduler = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=1000, gamma=0.99) self.beta_by_frame = lambda frame_idx: min( 1.0, self.prior_beta + frame_idx * (1.0 - self.prior_beta) / 1000) self.batch_recorder = BatchRecorder(env_id=env_id, env_seed=seed, n_workers=n_workers, buffer=self.buffer, n_steps=n_step, gamma=gamma, max_episode_length=50000) self.writer = SummaryWriter( comment="-{}-learner".format(self.env.unwrapped.spec.id)) def train(self): utils.set_global_seeds(self.seed, use_torch=True) learn_idx = 0 while True: beta = self.beta_by_frame(learn_idx) states, actions, rewards, next_states, dones, weights, idxes = self.buffer.sample( self.batch_size, beta) states = torch.FloatTensor(states).to(self.device) actions = torch.LongTensor(actions).to(self.device) rewards = torch.FloatTensor(rewards).to(self.device) next_states = torch.FloatTensor(next_states).to(self.device) dones = torch.FloatTensor(dones).to(self.device) weights = torch.FloatTensor(weights).to(self.device) batch = (states, actions, rewards, next_states, dones, weights) loss, prios = utils.compute_loss(self.model, self.tgt_model, batch, self.n_step, self.gamma) self.scheduler.step() grad_norm = utils.update_parameters(loss, self.model, self.optimizer, self.max_norm) self.buffer.update_priorities(idxes, prios) batch, idxes, prios = None, None, None learn_idx += 1 self.writer.add_scalar("learner/loss", loss, learn_idx) self.writer.add_scalar("learner/grad_norm", grad_norm, learn_idx) if learn_idx % self.target_update_interval == 0: print("Updating Target Network..") self.tgt_model.load_state_dict(self.model.state_dict()) if learn_idx % self.save_interval == 0: print("Saving Model..") torch.save(self.model.state_dict(), "model{}.pth".format(learn_idx)) if learn_idx % self.publish_param_interval == 0: self.batch_recorder.set_worker_weights( copy.deepcopy(self.model)) if learn_idx >= self.max_step: torch.save(self.model.state_dict(), "model{}.pth".format(learn_idx)) self.batch_recorder.cleanup() break def load_model(self, idx): with open("model{}.pth".format(idx), "rb") as f: print("loading weights_{}".format(idx)) self.model.load_state_dict(torch.load(f, map_location="cpu")) def sampling_data(self): self.batch_recorder.record_batch()
class Agent(): """Interacts with and learns from the environment.""" def __init__(self, state_size, action_size, seed, gamma=GAMMA, buffer_size=BUFFER_SIZE, batch_size=BATCH_SIZE, update_every=UPDATE_EVERY, lr=LR, tau=TAU ): """Initialize an Agent object. Params ====== state_size (int): dimension of each state action_size (int): dimension of each action seed (int): random seed """ self.state_size = state_size self.action_size = action_size self.seed = random.seed(seed) self.gamma = gamma self.batch_size = batch_size # Q-Network self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") self.model_local = DuelingDQN(state_size, action_size, seed).to(self.device) self.model_target = DuelingDQN(state_size, action_size, seed).to(self.device) self.optimizer = optim.Adam(self.model_local.parameters(), lr=LR) # Replay memory self.memory = ReplayBuffer( action_size=action_size, buffer_size=BUFFER_SIZE, batch_size=BATCH_SIZE, seed=seed, device=self.device ) # Initialize time step (for updating every UPDATE_EVERY steps) self.t_step = 0 def step(self, state, action, reward, next_state, done): # Save experience in replay memory self.memory.add(state, action, reward, next_state, done) # Learn every UPDATE_EVERY time steps. self.t_step = (self.t_step + 1) % UPDATE_EVERY if self.t_step == 0: # If enough samples are available in memory, get random subset and learn if len(self.memory) > self.batch_size: experiences = self.memory.sample() self.update(experiences) def act(self, state, eps=0.): """Returns actions for given state as per current policy. Params ====== state (array_like): current state eps (float): epsilon, for epsilon-greedy action selection """ state = torch.FloatTensor(state).float().unsqueeze(0).to(self.device) self.model_local.eval() with torch.no_grad(): qvals = self.model_local.forward(state) self.model_local.train() # Epsilon-greedy action selection if random.random() > eps: action = np.argmax(qvals.cpu().detach().numpy()) return action else: return random.choice(np.arange(self.action_size)) def update(self, batch): """Update value parameters using given batch of experience tuples. Params ====== batch (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples gamma (float): discount factor """ states, actions, rewards, next_states, dones = batch # Get expected Q values from local model curr_Q = self.model_local.forward(states).gather(1, actions) # curr_Q = curr_Q.squeeze(1) # Get max predicted Q values (for next states) from target model max_next_Q = self.model_target.forward(next_states).detach().max(1)[0].unsqueeze(1) expected_Q = rewards + (self.gamma * max_next_Q * (1 - dones)) loss = F.mse_loss(curr_Q, expected_Q) self.optimizer.zero_grad() loss.backward() self.optimizer.step() # update target model self.update_target(self.model_local, self.model_target, TAU) def update_target(self, local_model, target_model, tau): """Soft update model parameters. θ_target = τ*θ_local + (1 - τ)*θ_target Params ====== local_model (PyTorch model): weights will be copied from target_model (PyTorch model): weights will be copied to tau (float): interpolation parameter """ for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)
def train(args, n_actors, batch_queue, prios_queue, param_queue): """ thread to fill parameter queue """ def _fill_param(): while True: model_dict = {} state_dict = model.state_dict() for k, v in state_dict.items(): model_dict[k] = v.cpu().numpy() param_queue.put(model_dict) env = wrapper.make_atari(args.env) env = wrapper.wrap_atari_dqn(env, args) utils.set_global_seeds(args.seed, use_torch=True) model = DuelingDQN(env).to(args.device) tgt_model = DuelingDQN(env).to(args.device) tgt_model.load_state_dict(model.state_dict()) writer = SummaryWriter(comment="-{}-learner".format(args.env)) # optimizer = torch.optim.Adam(model.parameters(), args.lr) optimizer = torch.optim.RMSprop(model.parameters(), args.lr, alpha=0.95, eps=1.5e-7, centered=True) model_dict = {} state_dict = model.state_dict() for k, v in state_dict.items(): model_dict[k] = v.cpu().numpy() param_queue.put(model_dict) threading.Thread(target=_fill_param).start() learn_idx = 0 ts = time.time() while True: #if batch_queue.empty(): # print("batch queue size:{}".format(batch_queue.qsize())) *batch, idxes = batch_queue.get() loss, prios = utils.compute_loss(model, tgt_model, batch, args.n_steps, args.gamma) grad_norm = utils.update_parameters(loss, model, optimizer, args.max_norm) prios_queue.put((idxes, prios)) batch, idxes, prios = None, None, None learn_idx += 1 if learn_idx % args.tensorboard_update_interval == 0: writer.add_scalar("learner/loss", loss, learn_idx) writer.add_scalar("learner/grad_norm", grad_norm, learn_idx) if learn_idx % args.target_update_interval == 0: print("Updating Target Network..") tgt_model.load_state_dict(model.state_dict()) if learn_idx % args.save_interval == 0: print("Saving Model..") torch.save(model.state_dict(), "model.pth") if learn_idx % args.publish_param_interval == 0: param_queue.get() if learn_idx % args.bps_interval == 0: bps = args.bps_interval / (time.time() - ts) print("Step: {:8} / BPS: {:.2f}".format(learn_idx, bps)) writer.add_scalar("learner/BPS", bps, learn_idx) ts = time.time()