File size: 15,621 Bytes
80a8599 | 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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | """One fresh world per trial: verified clean-handoff source replay, then model-only control.
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 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]
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); 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')},
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'); tsrc = Path(case['training_source_dir'])
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']
assert digest(tsrc/'training.hdf5') == case['training_hdf5_sha256']
b = case['storage_steps']; h = case['handoff_step']
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)
io = read(OLD/'io.json'); env = module.make(g['scenario'], out/'assets'); 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')
command = [str(E/'policy-venv/bin/python'), str(OLD/'policy_entry.py'), '--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')]
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_storage = {c: 0 for c in CAMERAS}; checkpoint_rgb = {}; hidden = []
progress('replaying_source', boundary=b, handoff=h)
with h5py.File(src/'trajectory.hdf5') as trajectory, h5py.File(tsrc/'training.hdf5') as training:
assert trajectory['actions'].dtype == np.float64 and len(trajectory['actions']) == h
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 = camera_frames(env, io, KEYS)
assert all(v.shape == (256, 256, 3) and v.std() > 5 for v in images.values()), ('invalid_rgb', i)
if i <= b:
for c in CAMERAS:
d = int(np.abs(images['observation.images.'+c].astype(np.int16)-training['rgb/'+c][i].astype(np.int16)).max())
rgb_storage[c] = max(rgb_storage[c], d); assert d == 0, ('storage_rgb', i, c, d)
for label, step in (('initial', 0), ('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':
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}
assert all(v == 0 for v in checkpoint_rgb[label].values()), (label, checkpoint_rgb[label])
if i > b: hidden.append(concealed(env, family))
if i < h:
policy.observe(images); 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)
assert all(hidden), 'target became visible before handoff'
assert env.session.phase == Phase.RECALL, env.session.phase
chores_done = env.session.request_index; 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, max_state_error=maxerr, storage_rgb_max_difference=rgb_storage, checkpoint_rgb_max_difference=checkpoint_rgb,
checked_steps=h+1, concealed_steps_checked=len(hidden), chores_done_before_handoff=chores_done)
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) <= 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 = camera_frames(env, io, KEYS)
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 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()
|