File size: 4,191 Bytes
c399dd1 | 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 | """Evaluate a policy pool on a goal set under nominal ROM and TR variants (Sim2Sim, ROM side).
Usage: python run_rom.py --set A --pool explore --variants all
Writes results/rom_<set>/<variant>.npz (success, time_s, terminal/min distance [policy, goal, trial]; sampled
parameters [goal, trial]) and results/rom_<set>/<variant>.json (manifest: spec, K, seeds, policies, hashes).
Common random numbers: the same sampled parameters and noise stream for every policy.
"""
import argparse
import json
import time
import zlib
import numpy as np
import torch
import rom_batch
import variants as V
from common import RESULTS, Actor, make_goal_set, policy_registry, rel_path, sha256
POOLS = {
'explore': ['rel1', 'rel2', 'rel3', 'rel4'] + [f'{c}_s{s}' for c in ('nonoise', 'release', 'robust') for s in (1001, 1002, 1003, 1004)],
'confirm': [f'{c}_s{s}' for c in ('nonoise', 'release', 'robust') for s in (2001, 2002, 2003, 2004)],
'released': ['rel1', 'rel2', 'rel3', 'rel4'],
}
POOLS['confirm16'] = POOLS['confirm'] + POOLS['released'] # set B: primary = confirm (12 held-out), secondary = all 16
N_PER_RANGE = {'A': 50, 'B': 75}
def seed_of(*parts):
return zlib.crc32(':'.join(map(str, parts)).encode())
def run_variant(name, K, spec, goals, policies, reg, out_dir, set_name, device):
G = len(goals)
rng = np.random.default_rng(seed_of(set_name, name, 'params'))
params = V.sample(spec, G * K, rng)
noise_seed = seed_of(set_name, name, 'noise')
gxy = np.repeat(np.array([[g['x'], g['y']] for g in goals]), K, axis=0)
shape = (len(policies), G, K)
res = {k: np.zeros(shape, dtype=np.float32) for k in ('time_s', 'terminal_distance_m', 'min_distance_m')}
res['success'] = np.zeros(shape, dtype=bool)
t0 = time.time()
for i, p in enumerate(policies):
actor = Actor(reg[p]['path']).to_device(device)
o = rom_batch.simulate(actor, gxy, params, noise_seed=noise_seed, device=device)
for k in res:
res[k][i] = o[k].reshape(G, K)
np.savez_compressed(out_dir / f'{name}.npz', policies=np.array(policies), goal_ids=np.array([g['goal_id'] for g in goals]),
**res, **{f'param_{k}': v.reshape(G, K).astype(np.float32) for k, v in params.items()})
man = dict(variant=name, trials_per_goal=K, spec={k: list(v) for k, v in spec.items()}, goal_set=set_name, goals=G,
param_seed=seed_of(set_name, name, 'params'), noise_seed=noise_seed, device=device,
policies={p: dict(path=rel_path(reg[p]['path']), sha256=sha256(reg[p]['path'])) for p in policies},
wall_s=time.time() - t0)
(out_dir / f'{name}.json').write_text(json.dumps(man, indent=1) + '\n')
return res
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--set', choices=['A', 'B'], required=True)
ap.add_argument('--pool', choices=list(POOLS), required=True)
ap.add_argument('--variants', default='all', help='comma list or all (EXPLORE table, or the fixed design with --table fixed)')
ap.add_argument('--device', default='cpu')
ap.add_argument('--tag', default='')
ap.add_argument('--table', choices=['explore', 'fixed'], default='explore')
a = ap.parse_args()
torch.set_num_threads(2)
if a.set == 'B' and a.table != 'fixed':
raise SystemExit('goal set B is the held-out set: use --table fixed')
if a.table == 'fixed':
import fixed_design
table = fixed_design.CONDITIONS
else:
table = V.EXPLORE
names = list(table) if a.variants == 'all' else a.variants.split(',')
goals = make_goal_set(a.set, N_PER_RANGE[a.set])
reg = policy_registry()
policies = POOLS[a.pool]
out_dir = RESULTS / f'rom_{a.set}_{a.pool}{a.tag}'
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / 'goals.json').write_text(json.dumps(goals, indent=1) + '\n')
for n in names:
K, spec = table[n]
r = run_variant(n, K, spec, goals, policies, reg, out_dir, a.set, a.device)
sr = r['success'].mean((1, 2))
print(f'{n:18s} K={K:2d} success ' + ' '.join(f'{p}:{s:.2f}' for p, s in zip(policies, sr)), flush=True)
if __name__ == '__main__':
main()
|