robocasa-delayed-recall-eval / code-original /evaluate_delayed_v2.py
luca0621's picture
Delayed-recall memory eval environments (immediate, 1/5/15/30/60 min; cup/spice), evaluation code, results so far
80a8599 verified
Raw History Blame Contribute Delete
22.2 kB
"""v2: one fresh world per trial: verified clean-handoff source replay, then model-only control.
Policy I/O loop is unchanged from v1 (delay-01min). v2 adds source kinds: short sources whose cup scheduler
used a chore subset (DelayCup, exactly as gen_delay_source.py), and sources-long (earlier env from ep_meta,
float32 actions, EGL-cached left-agentview frames as the RGB reference).
Adapted from the frozen cotrain-ck3000-20261114 evaluate_case.py (the rollout path the
atomic harness check reproduced). No privileged state reaches the policy process.
"""
import argparse
import hashlib
import gc
import importlib.util
import json
import os
import sys
import time
from pathlib import Path
E = Path('/data/robo_ttt/robocasa_memory_20261103/evaluation-ck30000-20261108')
R = E.parent
OLD = E/'cotrain-ck3000-20261114'
N = E/'cotrain-delay-n10-20261115'
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(OLD/'code'))
gc.disable() # Do not collect old EGL contexts while this fresh world is live.
import h5py
import numpy as np
from PIL import Image
from experiments.robocasa_memory.evaluation.manifest import read, write, digest, encode_state, native_action, CAMERAS
from experiments.robocasa_memory.evaluation.driver import camera_frames, check_pause, UserPaused
from experiments.robocasa_memory.evaluation.task_matched_controls import facts, target_position
from experiments.robocasa_memory.evaluation.policy_process import PolicyProcess
from experiments.robocasa_memory.evaluation.video_recording import EvaluationVideo
from experiments.robocasa_memory.evaluation.post_storage_contract import require_complete_history
from experiments.robocasa_memory.dynamic_v2.protocol import Phase
TASKS = {'cup': 'OpenCabinetAndReturnCup', 'spice': 'UncoverAndRetrieveSpice'}
KEYS = ['observation.images.'+c for c in CAMERAS]
WRIST = 'robot0_eye_in_hand'
WRIST_NEAR_DIVISOR = 10 # wrist near plane 0.001*extent (29 mm in these kitchens) -> 2.9 mm
def render_frames(env, io, wrist_near_fix):
"""camera_frames(), except (optionally) the wrist camera is rendered with a 10x closer near plane.
MuJoCo's near plane is vis.map.znear * stat.extent; the ~29 m kitchen extent puts it at 2.9 cm, so geometry within
2.9 cm of the wrist camera is clipped (see-through). The agent-view cameras (the left one is the policy history) are
rendered with the unchanged global setting, so they stay bit-identical to camera_frames()."""
if not wrist_near_fix:
return camera_frames(env, io, KEYS)
m = env.sim.model._model; z0 = m.vis.map.znear; frames = {}
for key in KEYS:
cam = key.split('.')[-1]
try:
if cam == WRIST: m.vis.map.znear = z0/WRIST_NEAR_DIVISOR
frames[key] = np.ascontiguousarray(env.sim.render(width=io['render_width'], height=io['render_height'], camera_name=cam)[::-1])
finally:
m.vis.map.znear = z0
return frames
def delayed_recall_success(env, task, chores_done):
"""immediate_recall.recall_success with request_index == chores completed before handoff."""
if not env._check_success():
return False
if task == 'UncoverAndRetrieveSpice':
return bool(env.first_cover == env.target_slot and
np.linalg.norm(env.position(f'jar_{env.target}') - env.marker) < .04 and
env.covered(1-env.target_slot) and not env.session.violations and
not env.violations and env.session.request_index == chores_done)
return bool(env.final_arrangement_correct() and env.session.request_index == chores_done)
def flags(env, family, origin, chores_done):
result = facts(env, TASKS[family], origin)
if family == 'cup':
first = env.occlusion_gate.first_opened_side; expected = env.occlusion_gate.expected_side
result['target_at_goal_and_released'] = bool(result['target_on_original_tray'] and result['gripper_clear'])
violations = list(env.session.violations)+list(env.occlusion_gate.violations)
else:
first = env.first_cover; expected = env.target_slot
grip = env.sim.data.site_xpos[env.robots[0].eef_site_id['right']]
released = bool(np.linalg.norm(grip-env.position(f'jar_{env.target}')) > .08)
result.update(gripper_clear=released, target_at_goal_and_released=bool(result['target_at_marker'] and released))
violations = list(env.session.violations)+list(env.violations)
result.pop('native_storage_success', None)
result.update(first_choice=first, first_choice_observed=first is not None,
first_choice_correct=None if first is None else first == expected, violations=violations,
strict_task_success=delayed_recall_success(env, TASKS[family], chores_done))
return result
def concealed(env, family):
if family == 'spice': return bool(env.armed and all(env.covered(i) for i in range(2)))
f = env.privileged_facts()
return bool(env.occlusion_gate.armed and f.cabinet_closed and len(f.cups_in_cabinet) == 3)
def main():
p = argparse.ArgumentParser(); p.add_argument('--stage', required=True); p.add_argument('--trial', required=True)
p.add_argument('--gpu', type=int, choices=[0, 1], required=True)
p.add_argument('--bounded-history', action='store_true', help='disk-backed policy history buffers (I/O only; inputs bit-identical)')
p.add_argument('--wrist-near-fix', action='store_true', help='render the wrist camera with a 2.9 mm near plane (no see-through); agent views unchanged')
a = p.parse_args()
stage = N/a.stage; pauses = [N/'USER_PAUSED.json', N/'STOP', HERE/'STOP', stage/'STOP', stage/'USER_PAUSED.json']
plan = read(stage/'plan.json'); case = next(x for x in plan['cases'] if x['trial_id'] == a.trial)
out = stage/'episodes'/a.trial; out.mkdir(parents=True, exist_ok=False)
start = time.monotonic(); steps = 0; env = policy = video = None; family = case['family']
result = dict({k: case[k] for k in ('case', 'family', 'condition', 'trial_id', 'policy_seed', 'storage_steps', 'handoff_step',
'storage_complete_event_step', 'chores', 'post_storage_seconds_from_event', 'post_storage_seconds_from_immediate_handoff',
'handoff_residual', 'expert_retrieval_seconds', 'max_policy_steps', 'paired_immediate_trial', 'paired_immediate_success',
'paired_immediate_first_choice_correct', 'instruction', 'source_dir', 'source_trajectory_sha256', 'source_kind')},
stage=a.stage, valid_episode=False, evaluation_complete=False, task_success=None, model_revision=plan['model']['revision'],
model_weights_changed=False, old_results_pooled=False, live_pose_setters_after_reset=0, expert_actions_after_handoff=0,
memory_condition=case['memory_condition'])
def progress(status, **kw): write(out/'status.json', dict(status=status, updated_unix=time.time(), trial=a.trial, policy_steps=steps, **kw))
try:
check_pause(pauses)
src = Path(case['source_dir']); g = read(src/'result.json'); kind = case['source_kind']
assert g['status'] == 'verified' and g['trajectory_sha256'] == case['source_trajectory_sha256']
progress('checking_source_hashes')
assert digest(src/'trajectory.hdf5') == case['source_trajectory_sha256']
b = case['storage_steps']; h = case['handoff_step']
if kind == 'short':
tsrc = Path(case['training_source_dir']); assert digest(tsrc/'training.hdf5') == case['training_hdf5_sha256']
spec = importlib.util.spec_from_file_location('frozen_data_env', E/case['generator_version']/'data_env.py')
module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
if family == 'cup' and case['chores'] != ['pack_drink']:
# Exactly gen_delay_source.py: same constructor/reset, scheduler chore list = the generated subset.
import random
from dataclasses import replace
from experiments.robocasa_memory.dynamic_v2.kitchen_demo import make_env as kitchen, program as base_program
from experiments.robocasa_memory.dynamic_v2.protocol import Program
pool = {r.key: replace(r, instruction=r.instruction.split(' Leave ')[0]) for r in base_program().chores}
chosen = list(case['chores'])
class DelayCup(module.DatasetCup):
def build_program(self):
base = super().build_program()
return Program(5, base.family, base.initial_instruction, base.recall_instruction,
tuple(pool[k] for k in chosen), base.reserved_objects)
sc = g['scenario']; random.seed(sc['scene_seed']); np.random.seed(sc['scene_seed'])
env = kitchen(DelayCup, minutes=1, scenario=sc, scene_seed=0, target_cup=1)
else:
env = module.make(g['scenario'], out/'assets')
else:
from experiments.robocasa_memory.evaluation.driver import make_environment
with h5py.File(src/'trajectory.hdf5') as f: meta = json.loads(f.attrs['ep_meta'])
env = make_environment(dict(metadata=meta, minutes=case['env_minutes']), meta['memory_task'].get('asset_dir') or out/'assets')
cache = h5py.File(case['frame_cache'], 'r'); assert int(cache.attrs['handoff_step']) == h
io = read(OLD/'io.json'); obs = env.reset()
assert read(OLD/'download-status.json')['status'] == 'verified'
penv = dict(os.environ, CUDA_VISIBLE_DEVICES=str(a.gpu), PYTHONPATH=str(OLD/'code')+':'+str(OLD/'author-code'), SM_L2NORM_ROW_PAD='65536')
history_dir = Path('/tmp/sm-history')/(a.stage.replace('/', '_')+'__'+a.trial)
if a.bounded_history: penv['SM_HISTORY_DIR'] = str(history_dir)
entry = HERE/'policy_entry_bounded.py' if a.bounded_history else OLD/'policy_entry.py'
result.update(policy_entry=str(entry), bounded_history=a.bounded_history, history_cut=bool(case.get('history_cut')),
wrist_near_fix=dict(enabled=a.wrist_near_fix, wrist_near_plane_m=float(env.sim.model._model.vis.map.znear*env.sim.model._model.stat.extent)/(WRIST_NEAR_DIVISOR if a.wrist_near_fix else 1),
agent_view_near_plane_m=float(env.sim.model._model.vis.map.znear*env.sim.model._model.stat.extent)))
command = [str(E/'policy-venv/bin/python'), str(entry), '--checkpoint', str(OLD/'checkpoint/model'),
'--io-config', str(OLD/'io.json'), '--repo', str(E/'SimpleMemVLA'), '--max-subtask-tokens', '256',
'--denoising-steps', '10', '--attention-output', str(out/'attention')]
# Host-RAM bound: one policy checkpoint load at a time across all trials (I/O scheduling only).
import fcntl
progress('waiting_policy_load_slot')
with open(N/'eval'/'policy-load.lock', 'a') as load_lock:
fcntl.flock(load_lock, fcntl.LOCK_EX)
progress('loading_policy')
policy = PolicyProcess(command, penv, out/'policy.log', timeout=900)
assert policy.identity['history_video_sec'] == 100 and policy.identity['history_video_fps'] == 2
assert policy.identity['action_dim'] == 12 and policy.identity['action_horizon'] == 16
settings = case['memory_condition']
if settings:
configured = policy.configure_memory(settings)
assert configured['configured'] and configured['memory_condition'] == settings
write(out/'policy-identity.json', policy.identity); policy.reset(case['policy_seed'])
video = EvaluationVideo(out)
maxerr = 0.; rgb_ref = {c: 0 for c in CAMERAS}; checkpoint_rgb = {}; hidden = []; observed_hashes = []
progress('replaying_source', boundary=b, handoff=h)
training = h5py.File(tsrc/'training.hdf5', 'r') if kind == 'short' else None
with h5py.File(src/'trajectory.hdf5') as trajectory:
assert len(trajectory['actions']) == h
assert trajectory['actions'].dtype == (np.float64 if kind == 'short' else np.float32)
for i in range(h+1):
check_pause(pauses)
error = float(np.max(np.abs(env.sim.get_state().flatten()-trajectory['states'][i])))
assert np.isfinite(error) and error <= 1e-8, ('state_replay', i, error); maxerr = max(maxerr, error)
assert np.array_equal(encode_state(obs, io), trajectory['observation.state'][i]), ('proprio_replay', i)
images = render_frames(env, io, a.wrist_near_fix)
assert all(v.shape == (256, 256, 3) and v.std() > 5 for v in images.values()), ('invalid_rgb', i)
# EGL reference: training frames through storage (short), or the EGL-rendered left-agentview cache (long).
if kind == 'short' and i <= b:
refs = {c: training['rgb/'+c][i] for c in CAMERAS}
elif kind == 'long':
refs = {'robot0_agentview_left': cache['robot0_agentview_left'][i]}
if i == h: refs.update({c: cache[c+'_at_handoff'][()] for c in CAMERAS})
else: refs = {}
for c, ref in refs.items():
d = int(np.abs(images['observation.images.'+c].astype(np.int16)-np.asarray(ref).astype(np.int16)).max())
rgb_ref[c] = max(rgb_ref[c], d)
# With --wrist-near-fix the wrist frame intentionally differs where the old near plane clipped; recorded, not asserted.
assert d == 0 or (a.wrist_near_fix and c == WRIST), ('reference_rgb', i, c, d)
for label, step in (('initial', 0), ('storage-end' if kind == 'long' else 'immediate-handoff', b), ('delayed-handoff', h)):
if i == step:
for c in CAMERAS: Image.fromarray(images['observation.images.'+c]).save(out/f'{label}-{c}.png')
if label != 'initial' and (src/f'{label}-robot0_agentview_left.png').exists():
# Generator-renderer PNGs (CPU-pod Mesa for cup 5 min): recorded, not asserted.
checkpoint_rgb[label] = {c: int(np.abs(np.asarray(Image.open(src/f'{label}-{c}.png')).astype(np.int16)
- images['observation.images.'+c].astype(np.int16)).max()) for c in CAMERAS}
if i > b: hidden.append(concealed(env, family))
if i < h:
# DIAGNOSTIC history cut: the chore segment [b, h) is not shown to the policy (contiguous clock).
if not (case.get('history_cut') and i >= b): policy.observe(images)
if case.get('history_cut') and i < b: observed_hashes.append(hashlib.sha256(images['observation.images.robot0_agentview_left'].tobytes()).hexdigest())
video.append_reference(images, i)
obs = env.step(trajectory['actions'][i])[0]
if i % 200 == 0: progress('replaying_source', native_step=i, boundary=b, handoff=h)
if training: training.close()
if kind == 'long': cache.close()
first_hidden = next((j for j, x in enumerate(hidden) if x), None)
assert first_hidden is not None and all(hidden[first_hidden:]), 'target became visible before handoff'
if kind == 'short': assert first_hidden == 0, 'short sources must be concealed from the storage boundary on'
assert env.session.phase == Phase.RECALL, env.session.phase
chores_done = env.session.request_index
if kind == 'short': assert chores_done == len(case['chores']), (chores_done, case['chores'])
assert not env.session.violations
assert (env.first_cover is None) if family == 'spice' else (env.occlusion_gate.first_opened_side is None)
replay = dict(passed=True, source_kind=kind, max_state_error=maxerr, reference_rgb_max_difference=rgb_ref,
generator_png_rgb_max_difference=checkpoint_rgb, checked_steps=h+1, concealed_steps_checked=len(hidden),
first_concealed_offset=first_hidden, chores_done_before_handoff=chores_done)
if case.get('history_cut'):
replay.update(history_cut=dict(observed_prefix_steps=b, cut_steps=[b, h], live_from_step=h,
left_frame_sha256_first_last=[observed_hashes[0], observed_hashes[-1]], observed_prefix_frames=len(observed_hashes)))
write(out/'history-cut-observed-left-sha256.json', observed_hashes)
write(out/'replay.json', replay); result.update(replay=replay)
policy.observe(images)
origin = target_position(env, TASKS[family]); initial = flags(env, family, origin, chores_done)
pending = []; clip = []; ever = dict(initial); actions = []; states = []; observations = []; decisions = 0
with (out/'decisions.jsonl').open('x') as decisions_file, (out/'facts.jsonl').open('x') as factfile:
for step in range(case['max_policy_steps']):
check_pause(pauses)
if not pending:
progress('policy_inference', decision=decisions, native_step=h+step)
predicted, subtask = policy.predict(case['instruction'], encode_state(obs, io))
predicted = np.asarray(predicted); assert predicted.shape == (16, 12)
audit = policy.last_input_audit
assert audit['history_implementation'] == 'unmodified_upstream_policy'
if settings: require_complete_history(audit, native_step=h+step, history_seconds=settings['history_video_sec'])
else: assert audit['configured_history_seconds'] == 100
assert all(max(v) <= (b if case.get('history_cut') else h)+step for v in audit['sampled_native_steps'].values())
record = dict(decision=decisions, policy_step=step, physical_native_step=h+step, instruction=case['instruction'],
generated_subtask=subtask, action_chunk=predicted.tolist(), input_audit=audit)
decisions_file.write(json.dumps(record)+'\n'); decisions_file.flush()
if decisions == 0:
write(out/'first-input-audit.json', record)
left = [v for k, v in audit['sampled_native_steps'].items() if k.endswith('robot0_agentview_left')][0]
result.update(first_input=dict(min_sampled_native_step_left=min(left), max_sampled_native_step_left=max(left),
sampled_frames_left=len(left), input_tokens=audit.get('input_tokens'),
storage_frames_in_input_left=sum(x < b for x in left),
storage_event_frames_in_input_left=sum(x <= case['storage_complete_event_step'] for x in left),
cue_in_input=bool(min(left) < case['storage_complete_event_step'])))
pending = list(predicted[:plan['execute_steps']]); decisions += 1
action = native_action(pending.pop(0), io, env.action_spec, clip).astype(np.float64)
states.append(env.sim.get_state().flatten().copy()); observations.append(encode_state(obs, io)); actions.append(action)
video.append_action(images, step, case['instruction'])
obs = env.step(action)[0]; steps = step+1
images = render_frames(env, io, a.wrist_near_fix)
assert all(v.shape == (256, 256, 3) and v.dtype == np.uint8 and v.std() > 5 for v in images.values())
policy.observe(images)
current = flags(env, family, origin, chores_done)
for k, v in current.items():
if isinstance(v, bool): ever[k] = ever.get(k, False) or v
factfile.write(json.dumps(dict(step=steps, physical_native_step=h+steps, **current))+'\n')
if steps % 8 == 0: factfile.flush(); progress('executing_policy', facts=current)
if current['strict_task_success']: break
for c in CAMERAS: Image.fromarray(images['observation.images.'+c]).save(out/f'final-{c}.png')
with h5py.File(out/'rollout.hdf5', 'x') as f:
f['actions_native'] = np.asarray(actions, dtype=np.float64)
f['states'] = np.asarray(states+[env.sim.get_state().flatten().copy()])
f['observation.state'] = np.asarray(observations+[encode_state(obs, io)])
f.attrs.update(storage_boundary=b, handoff_step=h, control_hz=20, source_sha256=case['source_trajectory_sha256'])
result.update(status='success' if current['strict_task_success'] else 'timeout', valid_episode=True, evaluation_complete=True,
task_success=current['strict_task_success'], initial_facts=initial, final_facts=current, ever_facts=ever,
first_choice_observed=current['first_choice_observed'], first_choice_correct=current['first_choice_correct'],
first_choice=current['first_choice'], target_at_goal_and_released=ever['target_at_goal_and_released'],
policy_action_seconds=steps/20, clipping=clip, decisions=decisions, video=video.verify())
except BaseException as exc:
import traceback
traceback.print_exc()
result.update(status='USER_PAUSED' if isinstance(exc, UserPaused) else 'technical_failure', error=repr(exc),
valid_episode=False, evaluation_complete=False, task_success=None,
failure_class=getattr(exc, 'failure_class', 'environment_or_evaluation_error'), interpreted_as_model_failure=False)
if video and video.writer:
try: result['video'] = video.verify()
except BaseException as video_error: result['video_error'] = repr(video_error)
raise
finally:
if policy: policy.close()
if a.bounded_history and history_dir.exists():
import shutil; shutil.rmtree(history_dir, ignore_errors=True)
if video and not video.closed: video.close()
if env: env.close()
result.update(steps=steps, wall_seconds=time.monotonic()-start, finished_unix=time.time())
write(out/'result.json', result); progress(result['status'])
if __name__ == '__main__':
main()