|
| 1 | +"""Prioritized Experience Replay.""" |
| 2 | + |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +from garage import StepType, TimeStepBatch |
| 6 | +from garage.replay_buffer.path_buffer import PathBuffer |
| 7 | + |
| 8 | + |
| 9 | +class PERReplayBuffer(PathBuffer): |
| 10 | + """Replay buffer for PER (Prioritized Experience Replay). |
| 11 | +
|
| 12 | + PER assigns priorities to transitions in the buffer. Typically |
| 13 | + these priority of each transition is proportional to the corresponding |
| 14 | + loss computed at each update step. The priorities are then used to create |
| 15 | + a probability distribution when sampling such that higher priority |
| 16 | + transitions are sampled more frequently. For more see |
| 17 | + https://arxiv.org/abs/1511.05952. |
| 18 | +
|
| 19 | + Args: |
| 20 | + capacity_in_transitions (int): total size of transitions in the buffer. |
| 21 | + env_spec (EnvSpec): Environment specification. |
| 22 | + total_timesteps (int): Total timesteps the experiment will run for. |
| 23 | + This is used to calculate the beta parameter when sampling. |
| 24 | + alpha (float): hyperparameter that controls the degree of |
| 25 | + prioritization. Typically between [0, 1], where 0 corresponds to |
| 26 | + no prioritization (uniform sampling). |
| 27 | + beta_init (float): Initial value of beta exponent in importance |
| 28 | + sampling. Beta is linearly annealed from beta_init to 1 |
| 29 | + over total_timesteps. |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__(self, |
| 33 | + capacity_in_transitions, |
| 34 | + total_timesteps, |
| 35 | + env_spec, |
| 36 | + alpha=0.6, |
| 37 | + beta_init=0.5): |
| 38 | + self._alpha = alpha |
| 39 | + self._beta_init = beta_init |
| 40 | + self._total_timesteps = total_timesteps |
| 41 | + self._curr_timestep = 0 |
| 42 | + self._priorities = np.zeros((capacity_in_transitions, ), np.float32) |
| 43 | + self._rng = np.random.default_rng() |
| 44 | + super().__init__(capacity_in_transitions, env_spec) |
| 45 | + |
| 46 | + def sample_timesteps(self, batch_size): |
| 47 | + """Sample a batch of timesteps from the buffer. |
| 48 | +
|
| 49 | + Args: |
| 50 | + batch_size (int): Number of timesteps to sample. |
| 51 | +
|
| 52 | + Returns: |
| 53 | + TimeStepBatch: The batch of timesteps. |
| 54 | + np.ndarray: Weights of the timesteps. |
| 55 | + np.ndarray: Indices of sampled timesteps |
| 56 | + in the replay buffer. |
| 57 | +
|
| 58 | + """ |
| 59 | + samples, w, idx = self.sample_transitions(batch_size) |
| 60 | + step_types = np.array([ |
| 61 | + StepType.TERMINAL if terminal else StepType.MID |
| 62 | + for terminal in samples['terminals'].reshape(-1) |
| 63 | + ], |
| 64 | + dtype=StepType) |
| 65 | + return TimeStepBatch(env_spec=self._env_spec, |
| 66 | + observations=samples['observations'], |
| 67 | + actions=samples['actions'], |
| 68 | + rewards=samples['rewards'], |
| 69 | + next_observations=samples['next_observations'], |
| 70 | + step_types=step_types, |
| 71 | + env_infos={}, |
| 72 | + agent_infos={}), w, idx |
| 73 | + |
| 74 | + def sample_transitions(self, batch_size): |
| 75 | + """Sample a batch of transitions from the buffer. |
| 76 | +
|
| 77 | + Args: |
| 78 | + batch_size (int): Number of transitions to sample. |
| 79 | +
|
| 80 | + Returns: |
| 81 | + dict: A dict of arrays of shape (batch_size, flat_dim). |
| 82 | + np.ndarray: Weights of the timesteps. |
| 83 | + np.ndarray: Indices of sampled timesteps |
| 84 | + in the replay buffer. |
| 85 | +
|
| 86 | + """ |
| 87 | + priorities = self._priorities |
| 88 | + if self._transitions_stored < self._capacity: |
| 89 | + priorities = self._priorities[:self._transitions_stored] |
| 90 | + probs = priorities**self._alpha |
| 91 | + probs /= probs.sum() |
| 92 | + idx = self._rng.choice(self._transitions_stored, |
| 93 | + size=batch_size, |
| 94 | + p=probs) |
| 95 | + |
| 96 | + beta = self._beta_init + self._curr_timestep * ( |
| 97 | + 1.0 - self._beta_init) / self._total_timesteps |
| 98 | + beta = min(1.0, beta) |
| 99 | + transitions = { |
| 100 | + key: buf_arr[idx] |
| 101 | + for key, buf_arr in self._buffer.items() |
| 102 | + } |
| 103 | + |
| 104 | + w = (self._transitions_stored * probs[idx])**(-beta) |
| 105 | + w /= w.max() |
| 106 | + w = np.array(w) |
| 107 | + |
| 108 | + return transitions, w, idx |
| 109 | + |
| 110 | + def update_priorities(self, indices, priorities): |
| 111 | + """Update priorities of timesteps. |
| 112 | +
|
| 113 | + Args: |
| 114 | + indices (np.ndarray): Array of indices corresponding to the |
| 115 | + timesteps/priorities to update. |
| 116 | + priorities (list[float]): new priorities to set. |
| 117 | +
|
| 118 | + """ |
| 119 | + for idx, priority in zip(indices, priorities): |
| 120 | + self._priorities[int(idx)] = priority |
| 121 | + |
| 122 | + def add_path(self, path): |
| 123 | + """Add a path to the buffer. |
| 124 | +
|
| 125 | + This differs from the underlying buffer's add_path method |
| 126 | + in that the priorities for the new samples are set to |
| 127 | + the maximum of all priorities in the buffer. |
| 128 | +
|
| 129 | + Args: |
| 130 | + path (dict): A dict of array of shape (path_len, flat_dim). |
| 131 | +
|
| 132 | + """ |
| 133 | + path_len = len(path['observations']) |
| 134 | + self._curr_timestep += path_len |
| 135 | + |
| 136 | + # find the indices where the path will be stored |
| 137 | + first_seg, second_seg = self._next_path_segments(path_len) |
| 138 | + |
| 139 | + # set priorities for new timesteps = max(self._priorities) |
| 140 | + # or 1 if buffer is empty |
| 141 | + max_priority = self._priorities.max() or 1. |
| 142 | + self._priorities[list(first_seg)] = max_priority |
| 143 | + if second_seg != range(0, 0): |
| 144 | + self._priorities[list(second_seg)] = max_priority |
| 145 | + super().add_path(path) |
0 commit comments