Download code/case2/train_ppo.py from harryzhang1018/TestRandomization: direct link, hf CLI and curl.
- Browser
- Download file 7.74 kB
-
https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/train_ppo.py
- Command line
-
hf download hf://datasets/harryzhang1018/TestRandomization/code/case2/train_ppo.py
-
curl -L -o train_ppo.py https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/train_ppo.py
7.74 kB
| """Train new PPO goal-reaching policies on the ROM (Sim2Sim campaign, Case 2). | |
| Copies the release GoalEnv dynamics, reward and PPO hyperparameters (rl_script/rl_train_goal_reach.py) | |
| into a Gymnasium env, because SB3 2.7 needs Gymnasium. Only the training-noise config and the seed change. | |
| Configs: | |
| nonoise : no action noise; powertrain fixed at tau0=1000, omega0=2600. | |
| release : release semantics. N(0,0.05) on throttle and steering each step; tau0, omega0 drawn once | |
| at env construction with sd 50 and 100. | |
| robust : N(0,0.10) action noise; tau0, omega0 redrawn every episode with sd 100 and 200; | |
| actuation delay drawn every episode uniform from {0,1,2} control steps (0-0.2 s). | |
| Usage: python train_ppo.py --config release --seed 11 --out policies/release_s11 | |
| """ | |
| import argparse | |
| import json | |
| import platform | |
| import time | |
| from pathlib import Path | |
| import gymnasium as gym | |
| import numpy as np | |
| import torch as th | |
| from gymnasium import spaces | |
| from stable_baselines3 import PPO | |
| from stable_baselines3.common.callbacks import BaseCallback | |
| from stable_baselines3.common.vec_env import DummyVecEnv | |
| CONFIGS = { | |
| 'nonoise': dict(act_sigma=0.0, tau_sigma=0.0, omega_sigma=0.0, powertrain_redraw='never', delay_steps=[0]), | |
| 'release': dict(act_sigma=0.05, tau_sigma=50.0, omega_sigma=100.0, powertrain_redraw='construction', delay_steps=[0]), | |
| 'robust': dict(act_sigma=0.10, tau_sigma=100.0, omega_sigma=200.0, powertrain_redraw='episode', delay_steps=[0, 1, 2]), | |
| } | |
| class GoalEnvG(gym.Env): | |
| """Release GoalEnv (same constants, dynamics, reward, termination), Gymnasium API, configurable noise.""" | |
| def __init__(self, cfg, seed): | |
| super().__init__() | |
| self.cfg = cfg | |
| self.rng = np.random.default_rng(seed) | |
| self.action_space = spaces.Box(low=np.array([0.2, -1.0]), high=np.array([0.5, 1.0]), shape=(2,), dtype=np.float32) | |
| self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32) | |
| self.r_wheel, self.i_wheel, self.gamma = 0.47, 6.69, 1 / 3 | |
| self.c1, self.c0, self.car_length = 1e-4, 0.02, 1.0 | |
| self.dt, self.max_steps = 0.1, 400 | |
| self._draw_powertrain() | |
| self.old_distance = 0.0 | |
| def _draw_powertrain(self): | |
| self.tau_0 = 1000 + self.rng.normal(0, self.cfg['tau_sigma']) | |
| self.omega_0 = 2600 + self.rng.normal(0, self.cfg['omega_sigma']) | |
| def f_vdot(self, alpha, v): | |
| omega_m = v / (self.r_wheel * self.gamma) | |
| f1_m = -self.tau_0 * omega_m / self.omega_0 + self.tau_0 | |
| T_fun = alpha * f1_m - self.c1 * omega_m - self.c0 | |
| return T_fun * self.gamma / self.i_wheel * self.r_wheel | |
| def relative_state_to_goal(self): | |
| x, y, theta, v = self.state[:4] | |
| rot_mat = np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]]) | |
| relative_pos = np.dot(rot_mat, np.array(self.goal) - np.array([x, y])) | |
| relative_theta = np.arctan2(relative_pos[1], relative_pos[0]) | |
| return np.array([relative_pos[0], relative_pos[1], relative_theta, v], dtype=np.float32) | |
| def reset(self, seed=None, options=None): | |
| if self.cfg['powertrain_redraw'] == 'episode': | |
| self._draw_powertrain() | |
| self.delay = int(self.rng.choice(self.cfg['delay_steps'])) | |
| self.queue = [np.array([0.0, 0.0])] * self.delay | |
| r = self.rng.uniform(10.0, 20.0) | |
| theta = self.rng.uniform(0, 2 * np.pi) | |
| self.goal = [r * np.cos(theta), r * np.sin(theta)] | |
| self.state = np.array([0, 0, 0, 0.0], dtype=np.float32) | |
| self.steps = 0 | |
| self.old_distance = np.sqrt(self.goal[0] ** 2 + self.goal[1] ** 2) | |
| return self.relative_state_to_goal(), {} | |
| def step(self, action): | |
| self.queue.append(np.asarray(action, dtype=np.float64)) | |
| alpha, beta = self.queue.pop(0) | |
| if self.cfg['act_sigma'] > 0: | |
| alpha = alpha + self.rng.normal(0, self.cfg['act_sigma']) | |
| beta = beta + self.rng.normal(0, self.cfg['act_sigma']) | |
| x, y, theta, v = self.state | |
| x_dot = np.cos(theta) * v | |
| y_dot = np.sin(theta) * v | |
| theta_dot = v * np.tan(beta * 0.7) / self.car_length | |
| v_dot = self.f_vdot(alpha, v) | |
| x += x_dot * self.dt | |
| y += y_dot * self.dt | |
| theta += theta_dot * self.dt | |
| v += v_dot * self.dt | |
| v = np.clip(v, 0.0, 5.0) | |
| self.state = np.array([x, y, theta, v], dtype=np.float32) | |
| self.steps += 1 | |
| distance = np.sqrt((x - self.goal[0]) ** 2 + (y - self.goal[1]) ** 2) | |
| progress = self.old_distance - distance | |
| reward = 0.0 | |
| if progress > 0: | |
| reward = progress * 50 | |
| if progress < 0.1: | |
| reward -= 100 | |
| done = False | |
| if distance < 1.0: | |
| reward += self.max_steps * 15 | |
| done = True | |
| if self.steps >= self.max_steps: | |
| reward -= 1000 * distance | |
| done = True | |
| self.old_distance = distance | |
| # Release treats both goal and timeout as terminal (old Gym done=True); keep that. | |
| return self.relative_state_to_goal(), float(reward), done, False, {'velocity': float(v)} | |
| class SaveEvery(BaseCallback): | |
| def __init__(self, every, out): | |
| super().__init__() | |
| self.every, self.out, self.k = every, Path(out), 0 | |
| self.ep_returns, self.cur = [], 0.0 | |
| def _on_step(self): | |
| self.cur += float(self.locals['rewards'][0]) | |
| if self.locals['dones'][0]: | |
| self.ep_returns.append(self.cur) | |
| self.cur = 0.0 | |
| if self.n_calls % self.every == 0: | |
| self.k += 1 | |
| self.model.save(self.out / f'ckpt_{self.k}.zip') | |
| return True | |
| def main(): | |
| p = argparse.ArgumentParser() | |
| p.add_argument('--config', choices=list(CONFIGS), required=True) | |
| p.add_argument('--seed', type=int, required=True) | |
| p.add_argument('--out', required=True) | |
| p.add_argument('--timesteps', type=int, default=2_000_000) | |
| p.add_argument('--save-every', type=int, default=500_000) | |
| a = p.parse_args() | |
| th.set_num_threads(1) | |
| out = Path(a.out) | |
| out.mkdir(parents=True, exist_ok=False) | |
| cfg = CONFIGS[a.config] | |
| env = GoalEnvG(cfg, seed=a.seed + 7) | |
| vec = DummyVecEnv([lambda: env]) | |
| model = PPO('MlpPolicy', vec, learning_rate=3e-4, n_steps=env.max_steps * 3, batch_size=64, n_epochs=20, | |
| gamma=0.99, clip_range=0.2, verbose=0, seed=a.seed, device='cpu', | |
| policy_kwargs=dict(net_arch=dict(pi=[64, 128, 128, 64], vf=[64, 128, 128, 64]), activation_fn=th.nn.ReLU)) | |
| cb = SaveEvery(a.save_every, out) | |
| t0 = time.time() | |
| model.learn(total_timesteps=a.timesteps, callback=cb) | |
| rets = np.array(cb.ep_returns) | |
| meta = dict(config=a.config, config_values=cfg, seed=a.seed, env_seed=a.seed + 7, timesteps=a.timesteps, | |
| save_every=a.save_every, wall_s=time.time() - t0, | |
| fixed_construction_powertrain=dict(tau0=env.tau_0, omega0=env.omega_0) if cfg['powertrain_redraw'] == 'construction' else None, | |
| episodes=len(rets), mean_return_last100=float(rets[-100:].mean()) if len(rets) else None, | |
| hyperparameters=dict(learning_rate=3e-4, n_steps=1200, batch_size=64, n_epochs=20, gamma=0.99, clip_range=0.2, | |
| net_arch=[64, 128, 128, 64], activation='ReLU'), | |
| versions=dict(python=platform.python_version(), torch=th.__version__, numpy=np.__version__, | |
| sb3=__import__('stable_baselines3').__version__)) | |
| np.save(out / 'episode_returns.npy', rets.astype(np.float32)) | |
| (out / 'train_meta.json').write_text(json.dumps(meta, indent=2) + '\n') | |
| if __name__ == '__main__': | |
| main() | |