-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
runners.py
71 lines (58 loc) · 2.47 KB
/
runners.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from collections import defaultdict
import numpy as np
class EnvRunner:
"""Reinforcement learning runner in an environment with given policy"""
def __init__(self, env, policy, nsteps, transforms=None, step_var=None):
self.env = env
self.policy = policy
self.nsteps = nsteps
self.transforms = transforms or []
self.step_var = step_var if step_var is not None else 0
self.state = {"latest_observation": self.env.reset()[0]}
@property
def nenvs(self):
"""Returns number of batched envs or `None` if env is not batched"""
return getattr(self.env.unwrapped, "nenvs", None)
def reset(self, **kwargs):
"""Resets env and runner states."""
self.state["latest_observation"] = self.env.reset(**kwargs)[0]
self.policy.reset()
def add_summary(self, name, val):
"""Writes logs"""
add_summary = self.env.get_wrapper_attr("add_summary")
add_summary(name, val)
def get_next(self):
"""Runs the agent in the environment."""
trajectory = defaultdict(list, {"actions": []})
observations = []
rewards = []
resets = []
self.state["env_steps"] = self.nsteps
for i in range(self.nsteps):
observations.append(self.state["latest_observation"])
act = self.policy.act(self.state["latest_observation"])
if "actions" not in act:
raise ValueError(
"result of policy.act must contain 'actions' "
f"but has keys {list(act.keys())}"
)
for key, val in act.items():
trajectory[key].append(val)
obs, rew, terminated, truncated, _ = self.env.step(
trajectory["actions"][-1]
)
self.state["latest_observation"] = obs
rewards.append(rew)
reset = np.logical_or(terminated, truncated)
resets.append(reset)
self.step_var += self.nenvs or 1
# Only reset if the env is not batched. Batched envs should
# auto-reset.
if not self.nenvs and np.all(reset):
self.state["env_steps"] = i + 1
self.state["latest_observation"] = self.env.reset()[0]
trajectory.update(observations=observations, rewards=rewards, resets=resets)
trajectory["state"] = self.state
for transform in self.transforms:
transform(trajectory)
return trajectory