forked from facebookresearch/habitat-lab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathppo_agents.py
172 lines (142 loc) · 5.08 KB
/
ppo_agents.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import random
import numpy as np
import torch
from gym.spaces import Box, Dict, Discrete
import habitat
from habitat.config import Config
from habitat.config.default import get_config
from habitat.core.agent import Agent
from habitat_baselines.common.utils import batch_obs
from habitat_baselines.rl.ppo import PointNavBaselinePolicy
def get_default_config():
c = Config()
c.INPUT_TYPE = "blind"
c.MODEL_PATH = "data/checkpoints/blind.pth"
c.RESOLUTION = 256
c.HIDDEN_SIZE = 512
c.RANDOM_SEED = 7
c.PTH_GPU_ID = 0
c.GOAL_SENSOR_UUID = "pointgoal_with_gps_compass"
return c
class PPOAgent(Agent):
def __init__(self, config: Config):
self.goal_sensor_uuid = config.GOAL_SENSOR_UUID
spaces = {
self.goal_sensor_uuid: Box(
low=np.finfo(np.float32).min,
high=np.finfo(np.float32).max,
shape=(2,),
dtype=np.float32,
)
}
if config.INPUT_TYPE in ["depth", "rgbd"]:
spaces["depth"] = Box(
low=0,
high=1,
shape=(config.RESOLUTION, config.RESOLUTION, 1),
dtype=np.float32,
)
if config.INPUT_TYPE in ["rgb", "rgbd"]:
spaces["rgb"] = Box(
low=0,
high=255,
shape=(config.RESOLUTION, config.RESOLUTION, 3),
dtype=np.uint8,
)
observation_spaces = Dict(spaces)
action_spaces = Discrete(4)
self.device = (
torch.device("cuda:{}".format(config.PTH_GPU_ID))
if torch.cuda.is_available()
else torch.device("cpu")
)
self.hidden_size = config.HIDDEN_SIZE
random.seed(config.RANDOM_SEED)
torch.random.manual_seed(config.RANDOM_SEED)
if torch.cuda.is_available():
torch.backends.cudnn.deterministic = True
self.actor_critic = PointNavBaselinePolicy(
observation_space=observation_spaces,
action_space=action_spaces,
hidden_size=self.hidden_size,
goal_sensor_uuid=self.goal_sensor_uuid,
)
self.actor_critic.to(self.device)
if config.MODEL_PATH:
ckpt = torch.load(config.MODEL_PATH, map_location=self.device)
# Filter only actor_critic weights
self.actor_critic.load_state_dict(
{
k[len("actor_critic.") :]: v
for k, v in ckpt["state_dict"].items()
if "actor_critic" in k
}
)
else:
habitat.logger.error(
"Model checkpoint wasn't loaded, evaluating " "a random model."
)
self.test_recurrent_hidden_states = None
self.not_done_masks = None
self.prev_actions = None
def reset(self):
self.test_recurrent_hidden_states = torch.zeros(
self.actor_critic.net.num_recurrent_layers,
1,
self.hidden_size,
device=self.device,
)
self.not_done_masks = torch.zeros(1, 1, device=self.device)
self.prev_actions = torch.zeros(
1, 1, dtype=torch.long, device=self.device
)
def act(self, observations):
batch = batch_obs([observations])
for sensor in batch:
batch[sensor] = batch[sensor].to(self.device)
with torch.no_grad():
(
_,
actions,
_,
self.test_recurrent_hidden_states,
) = self.actor_critic.act(
batch,
self.test_recurrent_hidden_states,
self.prev_actions,
self.not_done_masks,
deterministic=False,
)
# Make masks not done till reset (end of episode) will be called
self.not_done_masks = torch.ones(1, 1, device=self.device)
self.prev_actions.copy_(actions)
return {"action": actions[0][0].item()}
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--input-type",
default="blind",
choices=["blind", "rgb", "depth", "rgbd"],
)
parser.add_argument("--model-path", default="", type=str)
parser.add_argument(
"--task-config", type=str, default="configs/tasks/pointnav.yaml"
)
args = parser.parse_args()
config = get_config(args.task_config)
agent_config = get_default_config()
agent_config.INPUT_TYPE = args.input_type
agent_config.MODEL_PATH = args.model_path
agent_config.GOAL_SENSOR_UUID = config.TASK.GOAL_SENSOR_UUID
agent = PPOAgent(agent_config)
benchmark = habitat.Benchmark(config_paths=args.task_config)
metrics = benchmark.evaluate(agent)
for k, v in metrics.items():
habitat.logger.info("{}: {:.3f}".format(k, v))
if __name__ == "__main__":
main()