File size: 12,850 Bytes
9897e20 | 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 331 332 | """
This implementation is adapted from the demo in PufferLib by Joseph Suarez,
which in turn is adapted from Costa Huang's CleanRL PPO + LSTM implementation.
Links
- PufferLib: https://github.com/PufferAI/PufferLib/blob/dev/demo.py
- Cleanrl: https://github.com/vwxyzjn/cleanrl/blob/master/cleanrl/ppo.py
"""
import os
from typing import Optional
from typing_extensions import Annotated
import yaml
from datetime import datetime
import torch
import numpy as np
import wandb
from box import Box
from gpudrive.integrations.puffer import ppo
from gpudrive.env.env_puffer import PufferGPUDrive
from gpudrive.networks.late_fusion import NeuralNet
from gpudrive.env.dataset import SceneDataLoader
import pufferlib
import pufferlib.vector
from rich.console import Console
import typer
from typer import Typer
app = Typer()
def get_model_parameters(policy):
"""Helper function to count the number of trainable parameters."""
params = filter(lambda p: p.requires_grad, policy.parameters())
return sum([np.prod(p.size()) for p in params])
def load_config(config_path):
"""Load the configuration file."""
with open(config_path, "r") as f:
config = Box(yaml.safe_load(f))
return pufferlib.namespace(**config)
def make_agent(env, config):
"""Create a policy based on the environment."""
if config.continue_training:
print("Loading checkpoint...")
# Load checkpoint
saved_cpt = torch.load(
f=config.model_cpt,
map_location=config.train.device,
weights_only=False,
)
policy = NeuralNet(
input_dim=saved_cpt["model_arch"]["input_dim"],
action_dim=saved_cpt["action_dim"],
hidden_dim=saved_cpt["model_arch"]["hidden_dim"],
config=config.environment,
)
# Load the model parameters
policy.load_state_dict(saved_cpt["parameters"])
return policy
else:
# Start from scratch
return NeuralNet(
input_dim=config.train.network.input_dim,
action_dim=env.single_action_space.n,
hidden_dim=config.train.network.hidden_dim,
dropout=config.train.network.dropout,
config=config.environment,
)
def train(args, vecenv):
"""Main training loop for the PPO agent."""
policy = make_agent(env=vecenv.driver_env, config=args).to(
args.train.device
)
args.train.network.num_parameters = get_model_parameters(policy)
args.train.env = args.environment.name
args.wandb = init_wandb(args, args.train.exp_id, id=args.train.exp_id)
args.train.__dict__.update(dict(args.wandb.config.train))
data = ppo.create(args.train, vecenv, policy, wandb=args.wandb)
while data.global_step < args.train.total_timesteps:
try:
ppo.evaluate(data) # Rollout
ppo.train(data) # Update policy
except KeyboardInterrupt:
ppo.close(data)
os._exit(0)
except Exception as e:
print(f"An error occurred: {e}") # Log the error
Console().print_exception()
os._exit(1) # Exit with a non-zero status to indicate an error
ppo.evaluate(data)
ppo.close(data)
def init_wandb(args, name, id=None, resume=True):
wandb.init(
id=id or wandb.util.generate_id(),
project=args.wandb.project,
entity=args.wandb.entity,
group=args.wandb.group,
mode=args.wandb.mode,
tags=args.wandb.tags,
config={
"environment": dict(args.environment),
"train": dict(args.train),
"vec": dict(args.vec),
},
name=name,
save_code=True,
resume=False,
)
return wandb
def sweep(args, project="PPO", sweep_name="my_sweep"):
"""Initialize a WandB sweep with hyperparameters."""
sweep_id = wandb.sweep(
sweep=dict(
method="random",
name=sweep_name,
metric={"goal": "maximize", "name": "environment/episode_return"},
parameters={
"learning_rate": {
"distribution": "log_uniform_values",
"min": 1e-4,
"max": 1e-1,
},
"batch_size": {"values": [512, 1024, 2048]},
"minibatch_size": {"values": [128, 256, 512]},
},
),
project=project,
)
wandb.agent(sweep_id, lambda: train(args), count=100)
@app.command()
def run(
config_path: Annotated[
str, typer.Argument(help="The path to the default configuration file")
] = "baselines/ppo/config/ppo_base_puffer.yaml",
*,
# fmt: off
data_dir: Annotated[Optional[str], typer.Option(help="Directory containing GPUDrive JSON scenes")] = None,
# Environment options
num_worlds: Annotated[Optional[int], typer.Option(help="Number of parallel envs")] = None,
k_unique_scenes: Annotated[Optional[int], typer.Option(help="The number of unique scenes to sample")] = None,
collision_weight: Annotated[Optional[float], typer.Option(help="The weight for collision penalty")] = None,
off_road_weight: Annotated[Optional[float], typer.Option(help="The weight for off-road penalty")] = None,
goal_achieved_weight: Annotated[Optional[float], typer.Option(help="The weight for goal-achieved reward")] = None,
dist_to_goal_threshold: Annotated[Optional[float], typer.Option(help="The distance threshold for goal-achieved")] = None,
polyline_reduction_threshold: Annotated[Optional[float], typer.Option(help="Road polyline reduction threshold")] = None,
sampling_seed: Annotated[Optional[int], typer.Option(help="The seed for sampling scenes")] = None,
obs_radius: Annotated[Optional[float], typer.Option(help="The radius for the observation")] = None,
collision_behavior: Annotated[Optional[str], typer.Option(help="The collision behavior; 'ignore' or 'remove'")] = None,
remove_non_vehicles: Annotated[Optional[int], typer.Option(help="Remove non-vehicles from the scene; 0 or 1")] = None,
use_vbd: Annotated[Optional[bool], typer.Option(help="Use VBD model for trajectory predictions")] = False,
vbd_model_path: Annotated[Optional[str], typer.Option(help="Path to VBD model checkpoint")] = None,
vbd_trajectory_weight: Annotated[Optional[float], typer.Option(help="Weight for VBD trajectory deviation penalty")] = 0.1,
vbd_in_obs: Annotated[Optional[bool], typer.Option(help="Include VBD predictions in the observation")] = False,
init_steps: Annotated[Optional[int], typer.Option(help="Environment warmup steps")] = 0,
# Train options
seed: Annotated[Optional[int], typer.Option(help="The seed for training")] = None,
learning_rate: Annotated[Optional[float], typer.Option(help="The learning rate for training")] = None,
anneal_lr: Annotated[Optional[int], typer.Option(help="Whether to anneal the learning rate over time; 0 or 1")] = None,
resample_scenes: Annotated[Optional[int], typer.Option(help="Whether to resample scenes during training; 0 or 1")] = None,
resample_interval: Annotated[Optional[int], typer.Option(help="The interval for resampling scenes")] = None,
resample_dataset_size: Annotated[Optional[int], typer.Option(help="The size of the dataset to sample from")] = None,
total_timesteps: Annotated[Optional[int], typer.Option(help="The total number of training steps")] = None,
ent_coef: Annotated[Optional[float], typer.Option(help="Entropy coefficient")] = None,
update_epochs: Annotated[Optional[int], typer.Option(help="The number of epochs for updating the policy")] = None,
batch_size: Annotated[Optional[int], typer.Option(help="The batch size for training")] = None,
minibatch_size: Annotated[Optional[int], typer.Option(help="The minibatch size for training")] = None,
gamma: Annotated[Optional[float], typer.Option(help="The discount factor for rewards")] = None,
vf_coef: Annotated[Optional[float], typer.Option(help="Weight for vf_loss")] = None,
# Wandb logging options
project: Annotated[Optional[str], typer.Option(help="WandB project name")] = None,
entity: Annotated[Optional[str], typer.Option(help="WandB entity name")] = None,
group: Annotated[Optional[str], typer.Option(help="WandB group name")] = None,
render: Annotated[Optional[int], typer.Option(help="Whether to render the environment; 0 or 1")] = None,
):
"""Run PPO training with the given configuration."""
# fmt: on
# Load default configs
config = load_config(config_path)
# Override configs with command-line arguments
if data_dir is not None:
config.data_dir = data_dir
env_config = {
"num_worlds": num_worlds,
"k_unique_scenes": k_unique_scenes,
"collision_weight": collision_weight,
"off_road_weight": off_road_weight,
"goal_achieved_weight": goal_achieved_weight,
"dist_to_goal_threshold": dist_to_goal_threshold,
"polyline_reduction_threshold": polyline_reduction_threshold,
"sampling_seed": sampling_seed,
"obs_radius": obs_radius,
"collision_behavior": collision_behavior,
"remove_non_vehicles": None
if remove_non_vehicles is None
else bool(remove_non_vehicles),
"use_vbd": use_vbd,
"vbd_model_path": vbd_model_path,
"vbd_trajectory_weight": vbd_trajectory_weight,
"vbd_in_obs": vbd_in_obs,
"init_steps": init_steps,
}
config.environment.update(
{k: v for k, v in env_config.items() if v is not None}
)
train_config = {
"seed": seed,
"learning_rate": learning_rate,
"anneal_lr": None if anneal_lr is None else bool(anneal_lr),
"resample_scenes": None
if resample_scenes is None
else bool(resample_scenes),
"resample_interval": resample_interval,
"resample_dataset_size": resample_dataset_size,
"total_timesteps": total_timesteps,
"ent_coef": ent_coef,
"update_epochs": update_epochs,
"batch_size": batch_size,
"minibatch_size": minibatch_size,
"render": None if render is None else bool(render),
"gamma": gamma,
"vf_coef": vf_coef,
}
config.train.update(
{k: v for k, v in train_config.items() if v is not None}
)
wandb_config = {
"project": project,
"entity": entity,
"group": group,
}
config.wandb.update(
{k: v for k, v in wandb_config.items() if v is not None}
)
datetime_ = datetime.now().strftime("%m_%d_%H_%M_%S_%f")[:-3]
if config["continue_training"]:
cont_train = "C"
else:
cont_train = ""
if config["train"]["resample_scenes"]:
if config["train"]["resample_scenes"]:
dataset_size = config["train"]["resample_dataset_size"]
config["train"][
"exp_id"
] = f'{config["train"]["exp_id"]}__{cont_train}__R_{dataset_size}__{datetime_}'
else:
dataset_size = str(config["environment"]["k_unique_scenes"])
config["train"][
"exp_id"
] = f'{config["train"]["exp_id"]}__{cont_train}__S_{dataset_size}__{datetime_}'
config["environment"]["dataset_size"] = dataset_size
config["train"]["device"] = config["train"].get(
"device", "cpu"
) # Default to 'cpu' if not set
if torch.cuda.is_available():
config["train"]["device"] = "cuda" # Set to 'cuda' if available
# Make dataloader
train_loader = SceneDataLoader(
root=config.data_dir,
batch_size=config.environment.num_worlds,
dataset_size=config.train.resample_dataset_size
if config.train.resample_scenes
else config.environment.k_unique_scenes,
sample_with_replacement=config.train.sample_with_replacement,
shuffle=config.train.shuffle_dataset,
seed=config.train.seed,
)
print(
"[GPUDrive] Data loader ready: "
f"data_dir={train_loader.root}, "
f"scenes={len(train_loader.dataset)}, "
f"batch_size={train_loader.batch_size}, "
f"sample_with_replacement={train_loader.sample_with_replacement}, "
f"seed={train_loader.seed}",
flush=True,
)
# Make environment
print("[GPUDrive] Creating PufferGPUDrive environment...", flush=True)
vecenv = PufferGPUDrive(
data_loader=train_loader,
**config.environment,
**config.train,
)
print(
"[GPUDrive] Environment ready: "
f"num_worlds={vecenv.num_worlds}, "
f"controlled_agents={vecenv.num_agents}, "
f"max_controlled_agents_per_world={vecenv.max_cont_agents_per_env}",
flush=True,
)
train(config, vecenv)
if __name__ == "__main__":
app()
|