def finish_path(self, last_val=0): """ Call this at the end of a trajectory, or when one gets cut off by an epoch ending. This looks back in the buffer to where the trajectory started, and uses rewards and value estimates from the whole trajectory to compute advantage estimates with GAE-Lambda, as well as compute the rewards-to-go for each state, to use as the targets for the value function. The "last_val" argument should be 0 if the trajectory ended because the agent reached a terminal state (died), and otherwise should be V(s_T), the value function estimated for the last state. This allows us to bootstrap the reward-to-go calculation to account for timesteps beyond the arbitrary episode horizon (or epoch cutoff). """ path_slice = slice(self.path_start_idx, self.ptr) rews = np.append(self.rew_buf[path_slice], last_val) vals = np.append(self.val_buf[path_slice], last_val) # the next two lines implement GAE-Lambda advantage calculation deltas = rews[:-1] + self.gamma * vals[1:] - vals[:-1] self.adv_buf[path_slice] = core.discount_cumsum(deltas, self.gamma * self.lam) # the next line computes rewards-to-go, to be targets for the value function self.ret_buf[path_slice] = core.discount_cumsum(rews, self.gamma)[:-1] self.path_start_idx = self.ptr
def update_adv(data): data = core.to_numpy(data) obs, act, rew, start_ptrs, last_d, last_o, ret, adv = data['obs'], data['act'], data['rew'], data['start_ptrs'], data['last_d'], data['last_o'], data['ret'], data['adv'] # the next two lines implement GAE-Lambda advantage calculation num_paths = start_ptrs.shape[0]-1 for i in range(num_paths): path_slice = slice(int(start_ptrs[i]), int(start_ptrs[i+1])) rew_path = rew[path_slice] obs_path = obs[path_slice] _, val_path, _ = ac.step(torch.as_tensor(obs_path, dtype=torch.float32)) if i==num_paths-1 and last_d: _, last_val, _ = ac.step(torch.as_tensor(last_o, dtype=torch.float32)) else: last_val = 0 rew_path = np.append(rew_path, last_val) val_path = np.append(val_path, last_val) # the next two lines implement GAE-Lambda advantage calculation delta_path = rew_path[:-1] + gamma * val_path[1:] - val_path[:-1] adv_path = core.discount_cumsum(delta_path, gamma * lam) # the next line computes rewards-to-go, to be targets for the value function ret_path = core.discount_cumsum(rew_path, gamma)[:-1] delta_path = rew_path[:-1] + gamma * val_path[1:] - val_path[:-1] adv_path = core.discount_cumsum(delta_path, gamma * lam) ret_path = core.discount_cumsum(rew_path, gamma)[:-1] ret[path_slice] = ret_path adv[path_slice] = adv_path data = core.to_torch(data) return(data)