davidwdw's picture
Upload Task 00, Task 01 and Task 02 code, datasets and evaluation results (part 20)
9befad5 verified
Raw History Blame Contribute Delete
9.29 kB
"""Sequential, resumable official evaluations. Default: one official-horizon instance.
Run through the Python/environment configured by env.sh. --all is explicit to
avoid launching twenty expensive simulations during development.
"""
import argparse
import hashlib
import importlib.metadata
import json
import os
from pathlib import Path
import shutil
import socket
import subprocess
import sys
import time
import urllib.request
ROOT = Path(__file__).resolve().parent
def main():
p = argparse.ArgumentParser()
p.add_argument('--indices', nargs='+', type=int, default=[0])
p.add_argument('--all', action='store_true')
p.add_argument('--output', required=True)
p.add_argument('--max-steps', type=int)
p.add_argument('--port', type=int, help='Local port; default selects a free loopback port for this run')
p.add_argument('--scan-only', action='store_true')
p.add_argument('--write-video', action='store_true', help='Also encode full rollout videos; sensor snapshots are always saved')
p.add_argument('--navigation', choices=('validated', 'visual', 'prior'), default='prior')
args = p.parse_args()
automatic_port = args.port is None
if automatic_port:
with socket.socket() as listener:
listener.bind(('127.0.0.1', 0))
args.port = listener.getsockname()[1]
indices = list(range(20)) if args.all else args.indices
if len(set(indices)) != len(indices) or any(i < 0 or i >= 20 for i in indices):
p.error('Indices must be distinct integers in 0–19')
root = Path(args.output).resolve()
root.mkdir(parents=True, exist_ok=True)
hashes = {str(f.relative_to(ROOT)): hashlib.sha256(f.read_bytes()).hexdigest()
for f in (ROOT / 'gpt6_b1k').glob('*.py')}
for f in (ROOT/'config').iterdir():
if f.is_file():
hashes[str(f.relative_to(ROOT))] = hashlib.sha256(f.read_bytes()).hexdigest()
extras = ('assets', 'third_party') if args.navigation == 'prior' else ()
for directory in extras:
for f in sorted((ROOT/directory).rglob('*')):
if f.is_file() and not any(p in ('.git', '__pycache__') for p in f.parts):
hashes[str(f.relative_to(ROOT))] = hashlib.sha256(f.read_bytes()).hexdigest()
benchmark_files = {}
repository = os.environ.get('B1K_REPO')
if repository:
for name in ('eval.py', 'evaluator.py', 'r1pro.yaml'):
f = Path(repository)/'OmniGibson/omnigibson/eval'/name
benchmark_files[name] = hashlib.sha256(f.read_bytes()).hexdigest()
manifest = dict(task='picking_up_trash', indices=indices, instance_ids=[301+i for i in indices],
max_steps=args.max_steps, scan_only=args.scan_only, navigation=args.navigation, source_sha256=hashes,
write_video=args.write_video,
python=sys.executable, repository=os.environ.get('B1K_REPO'), seed=0,
benchmark_sha256=benchmark_files,
dependencies={name: importlib.metadata.version(name) for name in
(('numpy', 'scipy', 'opencv-python', 'msgpack', 'websockets')+
(('torch', 'torchvision') if args.navigation == 'prior' else ()))},
diagnostic=args.max_steps is not None or args.scan_only)
mf = root / 'manifest.json'
if mf.exists() and json.loads(mf.read_text()) != manifest:
p.error('Output already belongs to different code/settings; choose a new directory')
mf.write_text(json.dumps(manifest, indent=2))
source = root / 'source'
for directory in ('gpt6_b1k', 'config', *extras):
shutil.copytree(ROOT/directory, source/directory, dirs_exist_ok=True,
ignore=shutil.ignore_patterns('__pycache__', '.git'))
child_env = os.environ.copy()
child_env['PYTHONPATH'] = str(source)+os.pathsep+child_env.get('PYTHONPATH', '')
child_env['PYTHONHASHSEED'] = '0'
completed = {r['instance_id'] for r in read_results(root)}
missing = [i for i in indices if 301+i not in completed]
if not missing:
summarize(root)
return
# The official evaluator already supports multiple instance indices and
# resets between them. Reuse its simulator instead of loading the house 20 times.
out = root / f'batch_{len(list(root.glob("batch_*"))):03d}'
out.mkdir()
(out/'transport.json').write_text(json.dumps(dict(host='127.0.0.1', port=args.port,
automatically_selected=automatic_port), indent=2))
with (out / 'policy.log').open('w') as log:
command = [sys.executable, '-m', 'gpt6_b1k.server', '--port', str(args.port), '--output', str(out / 'policy')]
if args.scan_only:
command += ['--scan-only']
command += ['--navigation', args.navigation]
policy = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, env=child_env, cwd=source)
try:
health_client = urllib.request.build_opener(urllib.request.ProxyHandler({}))
for _ in range(60):
if policy.poll() is not None:
raise RuntimeError('Policy exited before health check')
try:
with health_client.open(f'http://127.0.0.1:{args.port}/healthz', timeout=1):
break
except OSError:
time.sleep(1)
else:
raise RuntimeError('Policy did not become healthy')
command = [sys.executable, '-m', 'omnigibson.eval.eval', '--task-name', 'picking_up_trash',
'--mode', 'public_test', '--instance-indices', *map(str, missing), '--num-rollouts', '1',
'--host', '127.0.0.1', '--port', str(args.port), '--env-wrapper',
'omnigibson.eval.wrappers.RGBDFullResWrapper', '--output-dir', str(out / 'evaluation'),
'--headless']
if args.write_video:
command += ['--write-video']
if args.max_steps is not None:
command += ['--max-steps', str(args.max_steps)]
(out / 'command.json').write_text(json.dumps(command, indent=2))
print('START public indices', missing, flush=True)
with (out / 'evaluator.log').open('w') as evlog:
evaluator = subprocess.Popen(command, stdout=evlog, stderr=subprocess.STDOUT, env=child_env, cwd=source)
try:
previous = len(completed)
while evaluator.poll() is None:
time.sleep(5)
count = len(read_results(root))
if count != previous:
summarize(root)
previous = count
code = evaluator.returncode
finally:
if evaluator.poll() is None:
evaluator.terminate()
try:
evaluator.wait(timeout=20)
except subprocess.TimeoutExpired:
evaluator.kill()
evaluator.wait()
(out / 'exit_code.txt').write_text(str(code))
if code:
raise RuntimeError(f'Evaluator exited {code}; completed results remain resumable')
finally:
policy.terminate()
try:
policy.wait(timeout=10)
except subprocess.TimeoutExpired:
policy.kill()
policy.wait()
summarize(root)
def read_results(root):
rows = []
for f in root.glob('*/evaluation/json/*.json'):
try:
rows.append(json.loads(f.read_text()))
except json.JSONDecodeError:
# The official evaluator may still be writing this result while
# the progress monitor reads it. It remains incomplete meanwhile.
continue
ids = [r['instance_id'] for r in rows]
if len(ids) != len(set(ids)):
raise ValueError('Duplicate results: cannot count repeated instances as independent outcomes')
return sorted(rows, key=lambda r: r['instance_id'])
def summarize(root):
mf = json.loads((root / 'manifest.json').read_text())
rows = read_results(root)
complete = len(rows) == len(mf['instance_ids']) and {r['instance_id'] for r in rows} == set(mf['instance_ids'])
result = dict(completed=len(rows), expected=len(mf['indices']), complete=complete,
diagnostic=mf['diagnostic'], mean_q=sum(r['q_score']['final'] for r in rows)/len(rows) if rows else None,
successes=sum(r['success'] for r in rows),
instances=[dict(id=r['instance_id'], q=r['q_score']['final'], steps=r['steps']) for r in rows])
# Q is a fraction of predicates; floating-point summation at exactly 0.7
# must not be mistaken for a score strictly above the requested threshold.
result['target_achieved'] = (complete and len(rows) == 20 and not mf['diagnostic']
and result['mean_q'] > .7+1e-9)
(root / 'summary.json').write_text(json.dumps(result, indent=2))
print(json.dumps(result, indent=2))
if __name__ == '__main__':
main()