Download code/case2/common.py from harryzhang1018/TestRandomization: direct link, hf CLI and curl.
- Browser
- Download file 4.28 kB
-
https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/common.py
- Command line
-
hf download hf://datasets/harryzhang1018/TestRandomization/code/case2/common.py
-
curl -L -o common.py https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/common.py
4.28 kB
| """Shared paths, goal sets, policy loading and hashing for Case 2 (Sim2Sim only). | |
| Policies are read from checkpoint zips: the 24 trained policies in policies/<config>_s<seed>/ckpt_4.zip and the | |
| four released checkpoints of the original hmmwv_goal_reach repository in policies/released/ppo_<k>.zip. | |
| """ | |
| import hashlib | |
| import io | |
| import json | |
| import zipfile | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| BASE = Path(__file__).resolve().parent | |
| POLICY_DIR = BASE / 'policies' | |
| RELEASED_DIR = POLICY_DIR / 'released' # copies of hmmwv_goal_reach/data/rl_model/ppo_<k>.zip (BSD-3-Clause) | |
| RESULTS = BASE / 'results' | |
| DT = 0.1 # control period, ROM integration step (s) | |
| MAX_STEPS = 400 # 40 s horizon, as in training and the release ROM evaluation | |
| HORIZON_S = 40.0 # common horizon for ROM and Chrono; failure score = horizon | |
| GOAL_RADIUS = 3.0 # release evaluation success radius (m) | |
| # Goal sets. Set A = exploration (TR design), set B = held-out evaluation. Different seeds, never mixed. | |
| GOAL_SET_SEEDS = {'A': 2026110401, 'B': 2026110499} | |
| GOAL_RANGES = {'id': (10.0, 20.0), 'ood': (20.0, 40.0)} | |
| def sha256(path): | |
| return hashlib.sha256(Path(path).read_bytes()).hexdigest() | |
| def make_goal_set(name, n_per_range): | |
| """Uniform radius in each range, uniform bearing. Returns list of dicts.""" | |
| rng = np.random.default_rng(GOAL_SET_SEEDS[name]) | |
| goals = [] | |
| for label, (lo, hi) in GOAL_RANGES.items(): | |
| r = rng.uniform(lo, hi, n_per_range) | |
| b = rng.uniform(-np.pi, np.pi, n_per_range) | |
| for i in range(n_per_range): | |
| goals.append(dict(goal_id=f'{name}_{label}_{i:03d}', goal_set=name, goal_range=label, | |
| x=float(r[i] * np.cos(b[i])), y=float(r[i] * np.sin(b[i])), | |
| radius_m=float(r[i]), bearing_rad=float(b[i]))) | |
| return goals | |
| def rel_path(path): | |
| """Path relative to the package directory (as stored in the registry and the ROM manifests).""" | |
| return Path(path).resolve().relative_to(BASE).as_posix() | |
| def policy_registry(): | |
| """name -> dict(path, origin, config, seed, step). Released checkpoints + trained ones. Paths are absolute.""" | |
| reg = {} | |
| for k in range(1, 5): | |
| reg[f'rel{k}'] = dict(path=str(RELEASED_DIR / f'ppo_{k}.zip'), origin='released', | |
| config='release (single PPO run)', seed=None, step=k * 500_000) | |
| meta = POLICY_DIR / 'registry.json' | |
| if meta.exists(): | |
| for name, entry in json.loads(meta.read_text()).items(): | |
| reg[name] = dict(entry, path=str(BASE / entry['path'])) | |
| return reg | |
| class Actor(torch.nn.Module): | |
| """Deterministic SB3 PPO actor: 4 ReLU layers, linear action head, clip to the action box.""" | |
| def __init__(self, zip_path): | |
| super().__init__() | |
| with zipfile.ZipFile(zip_path) as archive: | |
| state = torch.load(io.BytesIO(archive.read('policy.pth')), map_location='cpu', weights_only=True) | |
| self.layers = [] | |
| i = 0 | |
| while f'mlp_extractor.policy_net.{i}.weight' in state: | |
| self.layers.append((state[f'mlp_extractor.policy_net.{i}.weight'], state[f'mlp_extractor.policy_net.{i}.bias'])) | |
| i += 2 | |
| self.head = (state['action_net.weight'], state['action_net.bias']) | |
| self.low = torch.tensor([0.2, -1.0]) | |
| self.high = torch.tensor([0.5, 1.0]) | |
| def forward(self, obs): | |
| x = torch.as_tensor(obs, dtype=torch.float32) | |
| for w, b in self.layers: | |
| x = torch.relu(torch.nn.functional.linear(x, w, b)) | |
| a = torch.nn.functional.linear(x, *self.head) | |
| return torch.clamp(a, self.low, self.high) | |
| def to_device(self, device): | |
| self.layers = [(w.to(device), b.to(device)) for w, b in self.layers] | |
| self.head = tuple(t.to(device) for t in self.head) | |
| self.low, self.high = self.low.to(device), self.high.to(device) | |
| return self | |
| def relative_obs(x, y, theta, v, gx, gy): | |
| """Release relative_state_to_goal, vectorized (float64 in, float32 out).""" | |
| c, s = np.cos(theta), np.sin(theta) | |
| dx, dy = gx - x, gy - y | |
| rx = c * dx + s * dy | |
| ry = -s * dx + c * dy | |
| return np.stack([rx, ry, np.arctan2(ry, rx), v], axis=-1).astype(np.float32) | |