-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
156 lines (124 loc) · 4.55 KB
/
main.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
import os
import gym
import numpy as np
import gym_boxworld
from gym_boxworld.envs.boxworld_env import BoxworldEnv, RandomBoxworldEnv
from stable_baselines3 import PPO
from stable_baselines3.common.policies import ActorCriticPolicy
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
from stable_baselines3.common.monitor import Monitor
from typing import Callable, Dict, List, Optional, Tuple, Type, Union
from stable_baselines3.common.vec_env import (
SubprocVecEnv,
VecVideoRecorder,
DummyVecEnv,
)
import argparse
import PIL
import imageio
from stable_baselines3 import A2C
import torch.nn as nn
import torch as th
def make_env(seed: int, log_dir: str, random: bool = False) -> Callable[[], gym.Env]:
"""Create custom minigrid environment
Args:
env_name (str): name of the minigrid
Returns:
init: function that when called instantiate a gym environment
"""
def init():
env = BoxworldEnv()
# default is partially observable
env.seed(seed)
env = Monitor(env, log_dir)
# env = DummyVecEnv([lambda: env])
# env = VecNormalize(env)
return env
return init
def set_env(config, log_dir):
env = SubprocVecEnv(
[make_env(i, log_dir, random=True) for i in range(config.num_cpu)]
)
return env
class CustomCNN(BaseFeaturesExtractor):
"""
:param observation_space: (gym.Space)
:param features_dim: (int) Number of features extracted.
This corresponds to the number of unit for the last layer.
"""
def __init__(self, observation_space: gym.spaces.Box, features_dim: int = 256):
super(CustomCNN, self).__init__(observation_space, features_dim)
# We assume CxHxW images (channels first)
# Re-ordering will be done by pre-preprocessing or wrapper
n_input_channels = observation_space.shape[0]
self.cnn = nn.Sequential(
nn.Conv2d(n_input_channels, 12, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.Conv2d(12, 24, kernel_size=3, stride=1, padding=0),
nn.ReLU(),
nn.Flatten(),
)
# Compute shape by doing one forward pass
with th.no_grad():
n_flatten = self.cnn(
th.as_tensor(observation_space.sample()[None]).float()
).shape[1]
self.linear = nn.Sequential(nn.Linear(n_flatten, features_dim), nn.ReLU())
def forward(self, observations: th.Tensor) -> th.Tensor:
return self.linear(self.cnn(observations))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-num_cpu", default=12, type=int, help="whether use frame_stack, default=False"
)
config = parser.parse_args()
log_dir = "tmp/"
video_dir = log_dir + "video/"
video_length = 30
os.makedirs(log_dir, exist_ok=True)
envs = set_env(config, log_dir)
env = make_env(0, log_dir)()
# env = VecVideoRecorder(env, video_dir,
# record_video_trigger=lambda x: x == 0, video_length=video_length,
# name_prefix="random-agent-{}".format("boxworld"))
# env.reset()
# for _ in range(1):
# obs, rewards, dones, info = env.step(np.random.randint(0, 3))
# env.render()
# env.close()
model = PPO(
"CnnPolicy",
env=envs,
policy_kwargs=dict(
features_extractor_class=CustomCNN,
features_extractor_kwargs=dict(features_dim=128),
),
verbose=1,
).learn(1000000)
# model.save("ppo_boxworld")
# model = PPO.load("ppo_boxworld", env=envs)
# model.learn(1000000, reset_num_timesteps=True)
model.save("ppo_boxworld")
# env = DummyVecEnv([lambda: )])
# env = VecVideoRecorder(env, video_dir,
# record_video_trigger=lambda x: x == 0, video_length=video_length,
# name_prefix="random-agent-{}".format("boxworld"))
# env.reset()
# for _ in range(1):
# obs, rewards, dones, info = env.step(np.random.randint(0, 3))
# env.render()
# env.close()
obs = env.reset()
images = []
img = env.render(mode="return")
for i in range(35):
# img = PIL.Image.fromarray(img)
# img = img.resize((128, 128), PIL.Image.ANTIALIAS)
images.append(img)
action, _ = model.predict(obs)
obs, _, done, _ = env.step(action)
img = env.render(mode="return")
if i % 5 == 0:
env.reset()
img = env.render(mode="return")
imageio.mimsave("boxworld_a2c.gif", images, fps=2)