Datasets:
ArXiv:
License:
File size: 4,702 Bytes
bceb512 39d735b bceb512 4e06c75 bceb512 4e06c75 bceb512 | 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 | import argparse
import json
import os
import sys
import time
import traceback
import urllib.request
import imageio
import numpy as np
ap = argparse.ArgumentParser()
ap.add_argument('--policy-repo', required=True)
ap.add_argument('--specs-json', required=True)
ap.add_argument('--gl', default='egl')
ap.add_argument('--out-dir', default='/out/videos')
a = ap.parse_args()
os.environ['MUJOCO_GL'] = a.gl
import gym
import d4rl
# d4rl's __init__ wraps all domain imports in one try/except: without dm_control,
# the MuJoCo envs are silently never registered. gym_mujoco is self-contained.
import d4rl.gym_mujoco # noqa: F401
import torch
import subset_loader
out_dir = a.out_dir
os.makedirs(out_dir, exist_ok=True)
results = []
def fetch_ckpt(ckpt_dir):
base = f'https://huggingface.co/{a.policy_repo}/resolve/main/{ckpt_dir}/model'
local = '/root/ck/' + ckpt_dir.replace('/', '_')
os.makedirs(local, exist_ok=True)
names = ['actor', 'actor_target', 'actor_optimizer', 'critic', 'critic_target', 'critic_optimizer']
if ckpt_dir.startswith('stbr'):
names += ['vib', 'vib_optimizer']
for n in names:
urllib.request.urlretrieve(f'{base}/{n}_s1000000.pth', f'{local}/{n}_s1000000.pth')
return local
for spec in json.loads(a.specs_json):
t0 = time.time()
r = {'ckpt': spec['ckpt_dir'], 'gl': a.gl}
try:
local = fetch_ckpt(spec['ckpt_dir'])
env = gym.make('hopper-medium-v2')
env.seed(spec['seed'] + 100)
subset_loader.set_original(d4rl.qlearning_dataset)
subset_loader.configure(fraction=spec['fraction'], seed=spec['seed'], out_dir=None)
ql = subset_loader.patched_qlearning_dataset(env)
mean = ql['observations'].mean(0)
std = ql['observations'].std(0)
if spec['kind'] == 'stbr':
sys.path.insert(0, '/root/repos/StBR')
import StBR
from vib import VIB
# StBR.load() also restores the VIB module: construct it exactly like
# the authors' main.py does (beta=0.001, beta2=0.1, neg_sample=1e-10).
vib = VIB(11, 3, 1.0, 13, 0.001, 0.1, 1e-10, 'cuda').to('cuda')
vib_optimizer = torch.optim.Adam(vib.parameters(), lr=1e-3, weight_decay=0)
policy = StBR.StBR(device='cuda', env='hopper-medium-v2', state_dim=11,
action_dim=3, max_action=1.0, latent_dim=13,
vib=vib, vib_optimizer=vib_optimizer)
policy.load(local, 1000000)
else:
sys.path.insert(0, '/root/repos/SPOT')
from vae import VAE
import SPOT as SPOT_mod
vae = VAE(11, 3, 6, 1.0).to('cuda')
policy = SPOT_mod.SPOT_TD3(
state_dim=11, action_dim=3, max_action=1.0, discount=0.99, tau=0.005,
policy_noise=0.2, noise_clip=0.5, policy_freq=2, lambd=0.1, lr=3e-4,
actor_lr=None, without_Q_norm=False, num_samples=1, iwae=False,
actor_hidden_dim=256, critic_hidden_dim=256, actor_dropout=0.1,
actor_init_w=None, critic_init_w=None, vae=vae, beta=0.5)
policy.load(local, 1000000)
frames, ep_ret, sim_t, eps, steps = [], 0.0, 0.0, 0, 0
state = env.reset()
if isinstance(state, tuple):
state = state[0]
while sim_t < 10.0 and eps < 3 and steps < 2000:
frames.append(env.render(mode='rgb_array'))
s_n = (np.array(state).reshape(1, -1) - mean) / std
action = policy.select_action(s_n)
state, reward, done, _ = env.step(action)
ep_ret += float(reward)
sim_t += 0.008
steps += 1
if done:
env.reset()
eps += 1
if done and eps >= 3:
break
fps = max(10, int(round(len(frames) / 10)))
path = os.path.join(out_dir, spec['out_name'] + '.mp4')
imageio.mimsave(path, frames, fps=fps)
try:
env.close()
except Exception:
pass
r.update({'frames': len(frames), 'fps': fps,
'duration_s': round(len(frames) / fps, 2),
'episode_return': round(ep_ret, 1),
'status': 'completed', 'ck_sec': round(time.time() - t0, 1)})
except Exception as e:
traceback.print_exc()
r['status'] = f'failed: {type(e).__name__}: {e}'
results.append(r)
print(json.dumps(r), flush=True)
manifest = {'gl': a.gl, 'results': results}
with open(os.path.join(out_dir, f'render_manifest_{a.gl}.json'), 'w') as fh:
json.dump(manifest, fh, indent=2)
print('MANIFEST ' + json.dumps(manifest))
|