Repository navigation
Expand file tree
/
Copy pathtrain_ppo.py
More file actions
330 lines (281 loc) · 12.3 KB
/
Copy pathtrain_ppo.py
File metadata and controls
330 lines (281 loc) · 12.3 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
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
330
import swanlab
swanlab.sync_wandb()
import inspect
import functools
import time
import os
import collections
from dataclasses import dataclass
from pathlib import Path
from datetime import datetime
from absl import logging
import tqdm
import tyro
import wandb
import numpy as np
import jax
from mujoco_playground import wrapper
from brax.training.agents.ppo.networks import make_ppo_networks
import cat_ppo
from cat_ppo import update_file_handler
from cat_ppo.constant import PATH_LOG
from cat_ppo.learning.policy.ppo import train as ppo # brax.training.agents.ppo
from cat_ppo.learning.policy.ppo.humanoid_transformer_networks import (
make_humanoid_transformer_ppo_networks,
)
from cat_ppo.learning.train.pf_utils import wrap_for_brax_training_reset
xla_flags = os.environ.get("XLA_FLAGS", "")
xla_flags += " --xla_gpu_triton_gemm_any=True"
os.environ["XLA_FLAGS"] = xla_flags
os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false"
os.environ["MUJOCO_GL"] = "egl"
WANDB_PROJECT = os.environ.get("WANDB_PROJECT")
WANDB_ENTITY = os.environ.get("WANDB_ENTITY")
_PFID_PLOT_HISTORY = collections.defaultdict(lambda: collections.defaultdict(list))
@dataclass
class Args:
task: str
exp_name: str = "debug"
num_timesteps: int = 400_000_000
num_evals: int = 0
seed: int = 42
convert_onnx: bool = True
restore_name: str = "none"
ground: float = 0
lateral: float = 0
overhead: float = 0
term_collision_threshold: float = 0.04
obs_path: str = 'data/assets/TypiObs/empty'
randomize_initial_episode_steps: bool = True
network_kind: str = "mlp"
policy_hidden_layer_sizes: list[int] | None = None
value_hidden_layer_sizes: list[int] | None = None
transformer_embed_dim: int = 256
transformer_num_heads: int = 4
transformer_ff_dim: int = 512
transformer_num_layers: int = 4
def generate_exp_name(self):
exp_name_parts = [self.exp_name]
if self.ground != 0:
exp_name_parts.append('G'+str(self.ground).replace('.', 'p'))
if self.lateral != 0:
exp_name_parts.append('L'+str(self.lateral).replace('.', 'p'))
if self.overhead != 0:
exp_name_parts.append('O'+str(self.overhead).replace('.', 'p'))
exp_name_parts.append(f"T{str(self.term_collision_threshold).replace('.', 'p')}")
if self.obs_path:
exp_name_parts.append(self.obs_path.split('/')[-1])
return "x".join(exp_name_parts)
def _prepare_exp_name(task: str, exp_name: str) -> str:
timestamp = datetime.now().strftime("%m%d%H%M")
return f"{timestamp}_{task}_{exp_name}"
def _validate_exp_name_format(exp_name: str, debug_mode: bool):
if not debug_mode and len(exp_name.split("_")) != 4:
raise ValueError(
f"exp_name should be in the format <task>_<tag>_<version>, got {exp_name}"
)
def _setup_paths(exp_name: str) -> tuple[Path, Path]:
logdir = Path(PATH_LOG) / exp_name
logdir.mkdir(parents=True, exist_ok=True)
update_file_handler(filename=f"{logdir}/info.log")
ckpt_path = logdir / "checkpoints"
ckpt_path.mkdir(parents=True, exist_ok=True)
return logdir, ckpt_path
def _log_checkpoint_path(ckpt_path: Path):
logging.info(f"Checkpoint path: {ckpt_path}")
def _apply_args_to_config(args: Args, policy_cfg, env_config, debug: bool):
policy_cfg.num_timesteps = args.num_timesteps
if debug:
policy_cfg.training_metrics_steps = 1000
policy_cfg.num_evals = 5
policy_cfg.batch_size = 8
policy_cfg.num_minibatches = 2
policy_cfg.num_envs = policy_cfg.batch_size * policy_cfg.num_minibatches
policy_cfg.episode_length = 200
policy_cfg.unroll_length = 10
policy_cfg.num_updates_per_batch = 1
policy_cfg.action_repeat = 1
policy_cfg.num_timesteps = 100_000
policy_cfg.num_resets_per_eval = 1
policy_cfg.num_eval_envs = 128
elif args.num_evals > 0:
policy_cfg.num_evals = args.num_evals
# cfg.restore_checkpoint_path = Path(args.restore_checkpoint_path)
if args.restore_name != "none":
from cat_ppo.constant import get_latest_ckpt
policy_cfg.restore_checkpoint_path = str(get_latest_ckpt(args.restore_name))
env_config.reward_config.scales.feetgf = args.ground
env_config.reward_config.scales.feetdf = args.ground
env_config.reward_config.scales.headgf = args.overhead
env_config.reward_config.scales.headdf = args.overhead
env_config.reward_config.scales.handsgf = args.lateral
env_config.reward_config.scales.handsdf = args.lateral
env_config.reward_config.scales.kneesdf = args.lateral
env_config.reward_config.scales.shldsdf = args.lateral
env_config.term_collision_threshold = args.term_collision_threshold
env_config.pf_config.path = args.obs_path
policy_cfg.randomize_initial_episode_steps = args.randomize_initial_episode_steps
policy_cfg.network_factory.network_kind = args.network_kind
if args.policy_hidden_layer_sizes:
policy_cfg.network_factory.policy_hidden_layer_sizes = tuple(args.policy_hidden_layer_sizes)
if args.value_hidden_layer_sizes:
policy_cfg.network_factory.value_hidden_layer_sizes = tuple(args.value_hidden_layer_sizes)
policy_cfg.network_factory.transformer_embed_dim = args.transformer_embed_dim
policy_cfg.network_factory.transformer_num_heads = args.transformer_num_heads
policy_cfg.network_factory.transformer_ff_dim = args.transformer_ff_dim
policy_cfg.network_factory.transformer_num_layers = args.transformer_num_layers
def _prepare_training_params(cfg, ckpt_path: Path):
params = cfg.to_dict()
params.pop("network_factory", None)
params["wrap_env_fn"] = wrap_for_brax_training_reset #wrapper.wrap_for_brax_training
network_cfg = cfg.network_factory.to_dict()
network_kind = network_cfg.pop("network_kind", "mlp")
if network_kind == "mlp":
network_fn = make_ppo_networks
for key in (
"transformer_embed_dim",
"transformer_num_heads",
"transformer_ff_dim",
"transformer_num_layers",
):
network_cfg.pop(key, None)
elif network_kind == "humanoid_transformer":
network_fn = make_humanoid_transformer_ppo_networks
else:
raise ValueError(f"Unsupported network_kind={network_kind!r}")
params["network_factory"] = (
functools.partial(network_fn, **network_cfg)
if hasattr(cfg, "network_factory")
else network_fn
)
params["save_checkpoint_path"] = ckpt_path
return params
def _init_wandb(
args: Args, exp_name, env_class, task_cfg, ckpt_path, config_fname="config.json"
):
wandb.init(
name=exp_name,
project=WANDB_PROJECT,
entity=WANDB_ENTITY,
config={
"num_timesteps": args.num_timesteps,
"task": args.task,
},
dir=PATH_LOG,
)
wandb.config.update(task_cfg.to_dict())
wandb.save(inspect.getfile(env_class))
config_path = ckpt_path / config_fname
config_path.write_text(task_cfg.to_json_best_effort(indent=4))
def _progress(num_steps, metrics, times, total_steps, debug_mode, exp_name):
now = time.monotonic()
times.append(now)
if metrics and not debug_mode:
try:
scalar_metrics = {}
pfid_groups = collections.defaultdict(dict)
for key, value in metrics.items():
prefix = "rollout/pfid/"
if key.startswith(prefix):
parts = key[len(prefix):].split("/", 1)
if len(parts) == 2:
pfid, metric_name = parts
pfid_groups[metric_name][pfid] = float(value)
continue
scalar_metrics[key] = value
grouped_plots = {}
for metric_name, values_by_pfid in pfid_groups.items():
metric_history = _PFID_PLOT_HISTORY[metric_name]
for pfid, value in values_by_pfid.items():
metric_history[pfid].append((num_steps, value))
keys = sorted(metric_history, key=lambda item: int(item) if item.isdigit() else item)
xs = [[point[0] for point in metric_history[pfid]] for pfid in keys]
ys = [[point[1] for point in metric_history[pfid]] for pfid in keys]
grouped_plots[f"rollout/pfid_grouped/{metric_name}"] = wandb.plot.line_series(
xs=xs,
ys=ys,
keys=[f"pfid/{pfid}" for pfid in keys],
title=f"rollout/pfid/{metric_name}",
xname="Step",
)
wandb.log({**scalar_metrics, **grouped_plots}, step=num_steps)
except Exception as e:
logging.warning(f"wandb.log failed: {e}")
if len(times) < 2 or num_steps == 0:
return
step_times = np.diff(times)
median_step_time = np.median(step_times)
if median_step_time <= 0:
return
steps_logged = num_steps / len(step_times)
est_seconds_left = (total_steps - num_steps) / steps_logged * median_step_time
logging.info(f"NumSteps {num_steps} - EstTimeLeft {est_seconds_left:.1f}[s]")
logging.info(exp_name)
def _report_training_time(times):
if len(times) > 1:
logging.info("Done training.")
logging.info(f"Time to JIT compile: {times[1] - times[0]:.2f}s")
logging.info(f"Time to train: {times[-1] - times[1]:.2f}s")
def train(args: Args):
env_class = cat_ppo.registry.get(args.task, "train_env_class")
task_cfg = cat_ppo.registry.get(args.task, "config")
env_cfg = task_cfg.env_config
policy_cfg = task_cfg.policy_config
exp_name = _prepare_exp_name(args.task, args.generate_exp_name())
debug_mode = "debug" in exp_name
_validate_exp_name_format(exp_name, debug_mode)
logdir, ckpt_path = _setup_paths(exp_name)
_log_checkpoint_path(ckpt_path)
_apply_args_to_config(args, policy_cfg, env_cfg, debug_mode)
task_cfg.env_config = env_cfg
policy_params = _prepare_training_params(policy_cfg, ckpt_path)
if not debug_mode:
_init_wandb(args, exp_name, env_class, task_cfg, ckpt_path)
train_fn = functools.partial(ppo.train, **policy_params)
times = [time.monotonic()]
env = env_class(task_type=env_cfg.task_type, config=env_cfg)
_eval_env = env_class(task_type=env_cfg.task_type, config=env_cfg)
# process
def policy_params_fn(current_step, make_policy, params): # pylint: disable=unused-argument
pass
make_inference_fn, params, _ = train_fn(
environment=env,
progress_fn=lambda s, m: _progress(s, m, times, policy_cfg.num_timesteps, debug_mode, exp_name),
eval_env=_eval_env,
policy_params_fn=policy_params_fn,
)
_report_training_time(times)
inference_fn = jax.jit(make_inference_fn(params, deterministic=True))
logging.info(f"Run {exp_name} Train done.")
if args.convert_onnx:
try:
from cat_ppo.eval.brax2onnx import convert_jax2onnx, get_latest_ckpt
ckpt_dir = get_latest_ckpt(ckpt_path)
obs_size = {
'privileged_state': (env_cfg.num_pri,),
'state': (env_cfg.num_obs,),
}
act_size = env_cfg.num_act
policy_obs_key = policy_cfg.network_factory.policy_obs_key
convert_jax2onnx(
ckpt_dir=ckpt_dir,
output_path=f"{ckpt_dir}/policy.onnx",
inference_fn=inference_fn,
hidden_layer_sizes=policy_cfg.network_factory.policy_hidden_layer_sizes,
obs_size=obs_size,
action_size=act_size,
policy_obs_key=policy_obs_key,
jax_params=params,
network_kind=policy_cfg.network_factory.get("network_kind", "mlp"),
transformer_embed_dim=policy_cfg.network_factory.get("transformer_embed_dim", 256),
transformer_num_heads=policy_cfg.network_factory.get("transformer_num_heads", 4),
transformer_ff_dim=policy_cfg.network_factory.get("transformer_ff_dim", 512),
transformer_num_layers=policy_cfg.network_factory.get("transformer_num_layers", 4),
activation="swish",
)
except ImportError:
logging.warning(
"TensorFlow is not installed. Please install TensorFlow to use ONNX conversion."
)
if __name__ == "__main__":
train(tyro.cli(Args))