-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreplay_buffer.py
More file actions
57 lines (49 loc) · 1.67 KB
/
Copy pathreplay_buffer.py
File metadata and controls
57 lines (49 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import numpy as np
import jax
from typing import Tuple
class ReplayBuffer(object):
"""A simple container for maintaining the history of the agent."""
def __init__(
self,
state_dim: int,
action_dim: int,
max_size: int
):
self.max_size = max_size
self.ptr = 0
self.size = 0
self.state = np.zeros((max_size, state_dim))
self.action = np.zeros((max_size, action_dim))
self.next_state = np.zeros((max_size, state_dim))
self.reward = np.zeros((max_size, 1))
self.not_done = np.zeros((max_size, 1))
def add(
self,
state: np.ndarray,
action: np.ndarray,
next_state: np.ndarray,
reward: float,
done: float
) -> None:
"""Memory built for per-transition interaction, does not handle batch updates."""
self.state[self.ptr] = state
self.action[self.ptr] = action
self.next_state[self.ptr] = next_state
self.reward[self.ptr] = reward
self.not_done[self.ptr] = 1. - done
self.ptr = (self.ptr + 1) % self.max_size
self.size = min(self.size + 1, self.max_size)
def sample(
self,
batch_size: int,
rng: jax.numpy.ndarray
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Given a JAX PRNG key, sample batch from memory."""
ind = jax.random.randint(rng, (batch_size, ), 0, self.size)
return (
self.state[ind],
self.action[ind],
self.next_state[ind],
self.reward[ind],
self.not_done[ind]
)