-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.py
329 lines (278 loc) · 9.46 KB
/
utils.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import functools
import numpy as np
import torch
# Environment import from BricksRL
from bricksrl.environments.walker_v0.WalkerEnvSim import WalkerEnvSim_v0
from tensordict.nn import InteractionType, TensorDictModule
from tensordict.nn.distributions import NormalParamExtractor
from torch import nn, optim
from torchrl.collectors import SyncDataCollector
from torchrl.data import TensorDictPrioritizedReplayBuffer, TensorDictReplayBuffer
from torchrl.data.replay_buffers.storages import LazyMemmapStorage
from torchrl.envs import (
CatFrames,
Compose,
DeviceCastTransform,
DMControlEnv,
DoubleToFloat,
EnvCreator,
ObservationNorm,
ParallelEnv,
TransformedEnv,
)
from torchrl.envs.libs.gym import GymEnv, GymWrapper, set_gym_backend
from torchrl.envs.transforms import InitTracker, RewardSum, StepCounter
from torchrl.envs.utils import ExplorationType, set_exploration_type
from torchrl.modules import MLP, ProbabilisticActor, ValueOperator
from torchrl.modules.distributions import TanhNormal
from torchrl.objectives import SoftUpdate
from torchrl.objectives.sac import SACLoss
from torchrl.record import VideoRecorder
# ====================================================================
# Make BricksRL Environment
# -----------------
def env_maker(cfg, device="cpu", from_pixels=False):
# We use the WalkerEnvSim_v0 environment from BricksRL as an example
# as it is easy to test as it does not require a robot at hand or to connect to the hub.
# Users can replace this with any other environment from BricksRL or custom environments.
env = WalkerEnvSim_v0(max_episode_steps=cfg.env.max_episode_steps)
observation_keys = [key for key in env.observation_spec.keys()]
transforms = []
if cfg.env.frame_stack > 1:
transforms.append(
CatFrames(
N=cfg.env.frame_stack,
in_keys=observation_keys,
out_key=observation_keys,
)
)
normalize_keys = [key for key in observation_keys if key != "pixels"]
obs_ranges = np.array(list(env.observation_ranges.values()))
obs_mean = obs_ranges.mean(axis=-1)
obs_std = obs_ranges.std(axis=-1)
transforms.append(
ObservationNorm(
in_keys=normalize_keys, loc=obs_mean, scale=obs_std, standard_normal=True
)
)
transforms.append(DeviceCastTransform(device))
return TransformedEnv(env, Compose(*transforms))
def apply_env_transforms(env, max_episode_steps=1000):
transformed_env = TransformedEnv(
env,
Compose(
InitTracker(),
StepCounter(max_episode_steps),
DoubleToFloat(),
RewardSum(),
),
)
return transformed_env
def make_environment(cfg, logger=None):
"""Make environments for training and evaluation."""
partial = functools.partial(env_maker, cfg=cfg)
parallel_env = ParallelEnv(
cfg.collector.env_per_collector,
EnvCreator(partial),
serial_for_single=True,
)
parallel_env.set_seed(cfg.env.seed)
train_env = apply_env_transforms(parallel_env, cfg.env.max_episode_steps)
partial = functools.partial(env_maker, cfg=cfg, from_pixels=cfg.logger.video)
trsf_clone = train_env.transform.clone()
if cfg.logger.video:
trsf_clone.insert(
0, VideoRecorder(logger, tag="rendering/test", in_keys=["pixels"])
)
eval_env = TransformedEnv(
ParallelEnv(
cfg.collector.env_per_collector,
EnvCreator(partial),
serial_for_single=True,
),
trsf_clone,
)
return train_env, eval_env
# ====================================================================
# Collector and replay buffer
# ---------------------------
def make_collector(cfg, train_env, actor_model_explore):
"""Make collector."""
collector = SyncDataCollector(
train_env,
actor_model_explore,
init_random_frames=cfg.collector.init_random_frames,
frames_per_batch=cfg.collector.frames_per_batch,
total_frames=cfg.collector.total_frames,
device=cfg.collector.device,
)
collector.set_seed(cfg.env.seed)
return collector
def make_replay_buffer(
batch_size,
prb=False,
buffer_size=1000000,
scratch_dir=None,
device="cpu",
prefetch=3,
):
if prb:
replay_buffer = TensorDictPrioritizedReplayBuffer(
alpha=0.7,
beta=0.5,
pin_memory=False,
prefetch=prefetch,
storage=LazyMemmapStorage(
buffer_size,
scratch_dir=scratch_dir,
device=device,
),
batch_size=batch_size,
)
else:
replay_buffer = TensorDictReplayBuffer(
pin_memory=False,
prefetch=prefetch,
storage=LazyMemmapStorage(
buffer_size,
scratch_dir=scratch_dir,
device=device,
),
batch_size=batch_size,
)
return replay_buffer
# ====================================================================
# Model
# -----
def make_sac_agent(cfg, train_env, eval_env, device):
"""Make SAC agent."""
# Define Actor Network
in_keys = ["observation"]
action_spec = train_env.action_spec
if train_env.batch_size:
action_spec = action_spec[(0,) * len(train_env.batch_size)]
actor_net_kwargs = {
"num_cells": cfg.network.hidden_sizes,
"out_features": 2 * action_spec.shape[-1],
"activation_class": get_activation(cfg),
}
actor_net = MLP(**actor_net_kwargs)
dist_class = TanhNormal
dist_kwargs = {
"low": action_spec.space.low,
"high": action_spec.space.high,
"tanh_loc": False,
}
actor_extractor = NormalParamExtractor(
scale_mapping=f"biased_softplus_{cfg.network.default_policy_scale}",
scale_lb=cfg.network.scale_lb,
)
actor_net = nn.Sequential(actor_net, actor_extractor)
in_keys_actor = in_keys
actor_module = TensorDictModule(
actor_net,
in_keys=in_keys_actor,
out_keys=[
"loc",
"scale",
],
)
actor = ProbabilisticActor(
spec=action_spec,
in_keys=["loc", "scale"],
module=actor_module,
distribution_class=dist_class,
distribution_kwargs=dist_kwargs,
default_interaction_type=InteractionType.RANDOM,
return_log_prob=False,
)
# Define Critic Network
qvalue_net_kwargs = {
"num_cells": cfg.network.hidden_sizes,
"out_features": 1,
"activation_class": get_activation(cfg),
}
qvalue_net = MLP(
**qvalue_net_kwargs,
)
qvalue = ValueOperator(
in_keys=["action"] + in_keys,
module=qvalue_net,
)
model = nn.ModuleList([actor, qvalue]).to(device)
# init nets
with torch.no_grad(), set_exploration_type(ExplorationType.RANDOM):
td = eval_env.fake_tensordict()
td = td.to(device)
for net in model:
net(td)
return model, model[0]
# ====================================================================
# SAC Loss
# ---------
def make_loss_module(cfg, model):
"""Make loss module and target network updater."""
# Create SAC loss
loss_module = SACLoss(
actor_network=model[0],
qvalue_network=model[1],
num_qvalue_nets=2,
loss_function=cfg.optim.loss_function,
delay_actor=False,
delay_qvalue=True,
alpha_init=cfg.optim.alpha_init,
)
loss_module.make_value_estimator(gamma=cfg.optim.gamma)
# Define Target Network Updater
target_net_updater = SoftUpdate(loss_module, eps=cfg.optim.target_update_polyak)
return loss_module, target_net_updater
def split_critic_params(critic_params):
critic1_params = []
critic2_params = []
for param in critic_params:
data1, data2 = param.data.chunk(2, dim=0)
critic1_params.append(nn.Parameter(data1))
critic2_params.append(nn.Parameter(data2))
return critic1_params, critic2_params
def make_sac_optimizer(cfg, loss_module):
critic_params = list(loss_module.qvalue_network_params.flatten_keys().values())
actor_params = list(loss_module.actor_network_params.flatten_keys().values())
optimizer_actor = optim.Adam(
actor_params,
lr=cfg.optim.lr,
weight_decay=cfg.optim.weight_decay,
eps=cfg.optim.adam_eps,
)
optimizer_critic = optim.Adam(
critic_params,
lr=cfg.optim.lr,
weight_decay=cfg.optim.weight_decay,
eps=cfg.optim.adam_eps,
)
optimizer_alpha = optim.Adam(
[loss_module.log_alpha],
lr=3.0e-4,
)
return optimizer_actor, optimizer_critic, optimizer_alpha
# ====================================================================
# General utils
# ---------
def log_metrics(logger, metrics, step):
for metric_name, metric_value in metrics.items():
logger.log_scalar(metric_name, metric_value, step)
def get_activation(cfg):
if cfg.network.activation == "relu":
return nn.ReLU
elif cfg.network.activation == "tanh":
return nn.Tanh
elif cfg.network.activation == "leaky_relu":
return nn.LeakyReLU
else:
raise NotImplementedError
def dump_video(module):
if isinstance(module, VideoRecorder):
module.dump()