File size: 19,223 Bytes
36b714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/env python3
"""One RoboTwin task/setting process: shared expert seed preparation or policy eval.

Uses the pinned official task classes, configuration, instructions, action mapping,
chunk loop and success check. The adapter adds fixed seeds, timing and resumption.
"""
import argparse
import importlib
import json
import os
from pathlib import Path
import random
import signal
import sys
import time
import traceback

from eval_common import ROOT, Telemetry, append_json, save_json
from eval_diagnostics import emit_startup, record_startup_failure

ROBOTWIN = ROOT / 'third_party/RoboTwin'
LINGBOT = ROOT / 'third_party/lingbot-vla-v2'
os.environ['XDG_CACHE_HOME'] = str(ROOT / '.cache')
os.environ['MPLCONFIGDIR'] = str(ROOT / '.cache/matplotlib')
os.environ['TORCH_EXTENSIONS_DIR'] = str(ROOT / '.cache/torch_extensions_sim')


def config(task, setting):
    import yaml
    root = ROBOTWIN / 'task_config'
    cfg = yaml.safe_load((root / f'demo_{setting}.yml').read_text())
    embodiment = yaml.safe_load((root / '_embodiment_config.yml').read_text())
    cameras = yaml.safe_load((root / '_camera_config.yml').read_text())
    assert cfg['embodiment'] == ['aloha-agilex']
    robot_dir = embodiment['aloha-agilex']['file_path']
    robot_cfg = yaml.safe_load((ROBOTWIN / robot_dir / 'config.yml').read_text())
    camera = cameras[cfg['camera']['head_camera_type']]
    cfg.update(task_name=task, task_config=f'demo_{setting}', eval_mode=True,
               collect_data=False, save_data=False, render_freq=0, eval_video_log=False,
               left_robot_file=robot_dir, right_robot_file=robot_dir, dual_arm_embodied=True,
               left_embodiment_config=robot_cfg, right_embodiment_config=robot_cfg,
               head_camera_h=camera['h'], head_camera_w=camera['w'])
    return cfg


def observation(env):
    import numpy as np
    obs = env.get_obs()
    for name in ('head_camera', 'left_camera', 'right_camera'):
        image = np.asarray(obs['observation'][name]['rgb'])
        if image.shape != (240, 320, 3) or not np.isfinite(image).all() or image.std() == 0:
            raise RuntimeError(f'Invalid camera observation: {name}, {image.shape}')
    return {'observation.images.cam_high': obs['observation']['head_camera']['rgb'],
            'observation.images.cam_left_wrist': obs['observation']['left_camera']['rgb'],
            'observation.images.cam_right_wrist': obs['observation']['right_camera']['rgb'],
            'observation.state': obs['joint_action']['vector'], 'task': env.get_instruction()}


def restore_scene_sequence(env, row):
    """Make resumed v1 scenes match the original uninterrupted 0..9 sequence.

    Upstream get_cluttered_table mutates its x/y default lists in place on each
    setup. Only these two tasks use a nonzero table offset. Passing fresh,
    explicitly replayed bounds preserves the existing BF16 reference scenes,
    including their upstream clutter drift, without depending on worker age.
    This is v1 compatibility, NOT a correction of upstream scene generation.
    """
    if row['task'] not in ('dump_bin_bigbin', 'put_bottles_dustbin') or row['setting'] != 'randomized':
        return {}
    sequence_index = row.get('scene_sequence_index', row['index'])
    if not 0 <= sequence_index < 10:
        raise ValueError('Invalid frozen episode index')
    # Addition order matters: reproduce each preceding setup's exact floats.
    xlim, ylim = [-0.59, 0.59], [-0.34, 0.34]
    for _ in range(sequence_index):
        xlim[0] += 0.3
        xlim[1] += 0.3
    from envs._base_task import Base_Task
    def frozen_clutter():
        if list(env.table_xy_bias) != [0.3, 0]:
            raise RuntimeError('Unexpected table offset for v1 scene restoration')
        return Base_Task.get_cluttered_table(env, xlim=xlim.copy(), ylim=ylim.copy(), zlim=[0.741])
    env.get_cluttered_table = frozen_clutter
    return {'protocol': 'v1_uninterrupted_cell_sequence',
            'prior_setups': sequence_index, 'xlim_before_setup': xlim, 'ylim_before_setup': ylim}


def restore_task_state(env, row):
    """Restore deterministic pre-action fields normally left by play_once.

    The official client reuses its expert environment for policy evaluation.
    Our separate workers must recreate these three tasks' success-check inputs
    after EVERY setup, including later episodes in the same worker.
    """
    task = row['task']
    if task not in ('open_laptop', 'place_object_scale', 'put_object_cabinet'):
        return {}
    from envs.utils import ArmTag, get_face_prod
    if task == 'open_laptop':
        face_prod = get_face_prod(env.laptop.get_pose().q, [1, 0, 0], [1, 0, 0])
        arm = 'left' if face_prod > 0 else 'right'
    else:
        arm = 'right' if env.object.get_pose().p[0] > 0 else 'left'
    if arm != row['scene_info']['{a}']:
        raise RuntimeError(f'Expert/policy scene arm mismatch: {task}, seed {row["seed"]}')
    env.arm_tag = ArmTag(arm)
    state = {'arm_tag': arm}
    if task == 'put_object_cabinet':
        env.origin_z = env.object.get_pose().p[2]
        state['origin_z'] = float(env.origin_z)
    return state


def release_unused_cuda_cache(env):
    # Return expert-only allocations before Vulkan allocates render targets.
    import gc
    import pickle
    import torch
    import numpy as np
    def snapshot():
        return pickle.dumps((env.robot.get_left_arm_jointState(), env.robot.get_right_arm_jointState(),
                             [(a.get_name(), a.get_pose().p.tolist(), a.get_pose().q.tolist())
                              for a in env.scene.get_all_actors()], np.random.get_state(), random.getstate()))
    initial = snapshot()
    before = torch.cuda.memory_reserved()
    # All experts ran in a separate preparation process. Joint-position policy
    # execution needs MPlib TOPP and the CPU gripper interpolation only, not
    # CuRobo MotionGen or its CUDA graphs. Preserve planner objects/metadata so
    # Robot.reset and the exact official gripper function remain unchanged.
    if env.robot.communication_flag:
        raise RuntimeError('Expert-engine release is only validated for in-process Aloha planners')
    def unavailable(*a, **kw):
        raise RuntimeError('Policy rollout unexpectedly requested expert GPU planning')
    for planner in (env.robot.left_planner, env.robot.right_planner):
        for key in ('motion_gen', 'motion_gen_batch'):
            if hasattr(planner, key):
                delattr(planner, key)
        planner.plan_path = unavailable
        planner.plan_batch = unavailable
    gc.collect()
    torch.cuda.empty_cache()
    if snapshot() != initial:
        raise RuntimeError('Expert-engine release changed scene, joints or random state')
    print(json.dumps({'event': 'release_unused_sim_cache',
                      'reserved_before_mib': before/1024**2,
                      'reserved_after_mib': torch.cuda.memory_reserved()/1024**2,
                      'scene_joint_rng_unchanged': True}), flush=True)


def prepare(args, env, cfg):
    from envs.utils.create_actor import UnStableError
    from generate_episode_instructions import generate_episode_descriptions
    import numpy as np
    path = args.manifest_dir / f'{args.task}__{args.setting}.json'
    if path.exists():
        previous = json.loads(path.read_text())
        if previous['status'] == 'ready' and len(previous['episodes']) == 10:
            print('Reusing frozen seed manifest', path, flush=True)
            return
        raise RuntimeError('Partial manifest exists; inspect before replacing')
    result = {'task': args.task, 'setting': args.setting, 'status': 'preparing',
              'start_seed': args.start_seed, 'candidate_limit': 200,
              'instruction_type': 'unseen', 'episodes': [], 'rejections': [],
              'policy_evaluation_during_selection': False}
    started = time.monotonic()
    try:
        for seed in range(args.start_seed, args.start_seed+200):
            signal.alarm(240)
            t = time.monotonic()
            random.seed(seed)
            expert_error = None
            try:
                env.setup_demo(now_ep_num=len(result['episodes']), seed=seed, is_test=True, **cfg)
                try:
                    info = env.play_once()
                except (TypeError, ValueError, IndexError, AssertionError) as error:
                    # The official client rejects candidates when expert planning
                    # raises (e.g. no feasible grasp returns None). Keep setup,
                    # asset, timeout, CUDA and Vulkan errors fatal; bound candidate
                    # selection and retain the exact expert failure for audit.
                    expert_error = {'type': type(error).__name__, 'message': str(error),
                                    'traceback': traceback.format_exc()}
                env.close_env()
                accepted = expert_error is None and bool(env.plan_success and env.check_success())
                reason = ('expert_exception' if expert_error is not None else
                          None if accepted else 'expert_plan_or_success_failed')
            except UnStableError as error:
                accepted, reason = False, str(error)
                env.close_env()
            if accepted:
                # Instruction draw is fixed independently from policy inference RNG.
                random.seed(seed+9107)
                descriptions = generate_episode_descriptions(args.task, [info['info']], 10)
                if not descriptions or not descriptions[0]['unseen']:
                    raise RuntimeError('No unseen instructions')
                instruction = str(np.random.RandomState(seed+9107).choice(descriptions[0]['unseen']))
                row = {'task': args.task, 'setting': args.setting, 'index': len(result['episodes']),
                       'seed': seed, 'policy_seed': seed+42, 'instruction': instruction,
                       'scene_info': info['info'], 'precheck_seconds': time.monotonic()-t}
                result['episodes'].append(row)
            else:
                result['rejections'].append({'seed': seed, 'reason': reason, 'seconds': time.monotonic()-t,
                                             **({'expert_error': expert_error} if expert_error else {})})
            signal.alarm(0)
            print(json.dumps({'seed': seed, 'accepted': accepted, 'count': len(result['episodes']),
                              'seconds': time.monotonic()-t}), flush=True)
            save_json(args.output / 'precheck_progress.json', result)
            if len(result['episodes']) == 10:
                break
        if len(result['episodes']) != 10:
            raise RuntimeError('Fewer than 10 valid seeds within 200 candidates')
        result['status'] = 'ready'
        result['seconds'] = time.monotonic()-started
        save_json(path, result)
    finally:
        signal.alarm(0)


def evaluate(args, env, cfg):
    emit_startup(args.output, 'evaluation_imports_started')
    import numpy as np
    from deploy.websocket_client_policy import WebsocketClientPolicy
    emit_startup(args.output, 'evaluation_imports_complete')
    manifest = json.loads((args.manifest_dir / f'{args.task}__{args.setting}.json').read_text())
    assert manifest['status'] == 'ready' and len(manifest['episodes']) == 10
    rows = manifest['episodes']
    if args.indices:
        wanted = {int(i) for i in args.indices.split(',')}
        rows = [r for r in rows if r['index'] in wanted]
    emit_startup(args.output, 'policy_client_connecting', port=args.port)
    model = WebsocketClientPolicy(host='127.0.0.1', port=args.port)
    metadata = model.get_server_metadata()
    assert metadata['model'] == args.model and metadata['precision'] == args.precision, metadata
    save_json(args.output / 'server_metadata.json', metadata)
    emit_startup(args.output, 'policy_client_ready', model=args.model, precision=args.precision)
    emit_startup(args.output, 'telemetry_initializing')
    telemetry = Telemetry(args.output / 'gpu_samples.jsonl')
    completed = []
    try:
        emit_startup(args.output, 'worker_ready', startup_complete=True)
        for row in rows:
            args.output.mkdir(parents=True, exist_ok=True)
            record_path = args.results_dir / f"{args.model}_{args.precision}" / f"{args.task}__{args.setting}__{row['index']:02d}.json"
            if record_path.exists():
                saved = json.loads(record_path.read_text())
                assert saved['seed'] == row['seed'] and saved['status'] == 'completed'
                continue
            signal.alarm(900)
            random.seed(row['seed'])
            boundary = telemetry.sample()
            start = boundary['monotonic']
            append_json(args.output / 'events.jsonl', {'event': 'episode_started', 'timestamp': time.time(), **row})
            scene_sequence = restore_scene_sequence(env, row)
            env.setup_demo(now_ep_num=row['index'], seed=row['seed'], is_test=True, **cfg)
            restored_state = restore_task_state(env, row)
            release_unused_cuda_cache(env)
            env.set_instruction(instruction=row['instruction'])
            model.infer(dict(reset=True, robo_name='robotwin', policy_seed=row['policy_seed']))
            rollout_start = time.monotonic()
            success = False
            calls = 0
            latencies = []
            while env.take_action_cnt < env.step_lim and not success:
                obs = observation(env)
                call_start = time.monotonic()
                response = model.infer(obs)
                latencies.append(time.monotonic()-call_start)
                calls += 1
                actions = np.asarray(response['action'])
                if actions.shape != (50, 14) or not np.isfinite(actions).all():
                    raise RuntimeError(f'Invalid actions: {actions.shape}')
                for action in actions:
                    if env.take_action_cnt >= env.step_lim:
                        break
                    env.take_action(action)
                    if env.eval_success:
                        success = True
                        break
            rollout_seconds = time.monotonic()-rollout_start
            action_count, step_limit = env.take_action_cnt, env.step_lim
            env.close_env(clear_cache=((row['index']+1) % cfg['clear_cache_freq'] == 0))
            end = telemetry.sample()['monotonic']
            result = {**row, 'model': args.model, 'precision': args.precision,
                      'status': 'completed', 'success': success,
                      'episode_wall_seconds': end-start, 'rollout_seconds': rollout_seconds,
                      'actions': action_count, 'step_limit': step_limit, 'policy_calls': calls,
                      'mean_policy_request_seconds': sum(latencies)/len(latencies),
                      'monotonic_start': start, 'monotonic_end': end,
                      'finished_at': time.time(), 'attempt_dir': str(args.output),
                      'video': False, 'expert_gpu_engines_released': True,
                      'render_shader': os.environ.get('EVAL_RENDER_SHADER', 'rt'),
                      'evaluation_protocol': os.environ.get('EVAL_PROTOCOL', 'local_v1_rt'),
                      'restored_task_state': restored_state,
                      'restored_scene_sequence': scene_sequence,
                      **telemetry.summary(start, end)}
            if result['memory_coverage'] < 0.98:
                raise RuntimeError(f'Insufficient telemetry coverage: {result["memory_coverage"]}')
            save_json(record_path, result)
            append_json(args.output / 'events.jsonl', {'event': 'episode_finished', **result})
            completed.append(result)
            print(json.dumps({'event': 'episode_finished', **result}), flush=True)
            signal.alarm(0)
        save_json(args.output / 'result.json', {'status': 'completed', 'episodes': completed})
    finally:
        telemetry.close()
        signal.alarm(0)


def main():
    p = argparse.ArgumentParser()
    p.add_argument('--mode', choices=['prepare', 'evaluate'], required=True)
    p.add_argument('--task', required=True)
    p.add_argument('--setting', choices=['clean', 'randomized'], required=True)
    p.add_argument('--start-seed', type=int, default=300000)
    p.add_argument('--output', type=Path, required=True)
    p.add_argument('--manifest-dir', type=Path, required=True)
    p.add_argument('--results-dir', type=Path)
    p.add_argument('--model', choices=['base', 'robotwin'])
    p.add_argument('--precision', choices=['bf16', 'fp32'])
    p.add_argument('--port', type=int, default=9340)
    p.add_argument('--indices')
    args = p.parse_args()
    args.output = args.output.resolve()
    args.manifest_dir = args.manifest_dir.resolve()
    args.results_dir = args.results_dir.resolve() if args.results_dir else None
    args.output.mkdir(parents=True, exist_ok=True)
    args.manifest_dir.mkdir(parents=True, exist_ok=True)
    def timeout(signum, frame):
        raise TimeoutError('Per-seed/precheck or episode timeout')
    env = None
    try:
        emit_startup(args.output, 'python_entry', role='worker', task=args.task,
                     setting=args.setting, mode=args.mode)
        signal.signal(signal.SIGALRM, timeout)
        os.chdir(ROBOTWIN)
        sys.path[:0] = [str(ROBOTWIN), str(ROBOTWIN/'description/utils'), str(LINGBOT)]
        emit_startup(args.output, 'sapien_binding_started')
        from eval_device import bind_sapien
        bind_sapien()
        emit_startup(args.output, 'sapien_binding_complete')
        emit_startup(args.output, 'task_import_started', task=args.task)
        cls = getattr(importlib.import_module('envs.'+args.task), args.task)
        emit_startup(args.output, 'task_import_complete')
        emit_startup(args.output, 'environment_constructing')
        env = cls()
        emit_startup(args.output, 'environment_constructed')
        emit_startup(args.output, 'config_loading')
        cfg = config(args.task, args.setting)
        emit_startup(args.output, 'config_loaded')
        if args.mode == 'prepare':
            emit_startup(args.output, 'preparation_ready', startup_complete=True)
            prepare(args, env, cfg)
        else:
            evaluate(args, env, cfg)
    except BaseException as error:
        record_startup_failure(args.output, error)
        save_json(args.output / 'error.json', {'type': type(error).__name__, 'message': str(error),
                                             'traceback': traceback.format_exc(), 'timestamp': time.time()})
        raise
    finally:
        signal.alarm(0)
        try:
            env.close_env()
        except Exception:
            pass
        robot = getattr(env, 'robot', None)
        for key in ('left_proc', 'right_proc'):
            process = getattr(robot, key, None)
            if process is not None and process.is_alive():
                process.terminate()
                process.join(timeout=5)
                if process.is_alive():
                    process.kill()
                    process.join()


if __name__ == '__main__':
    main()