File size: 14,541 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
#!/usr/bin/env python3
"""A bounded RT episode for hybrid_v1; never writes the original v1 results."""
import argparse
import faulthandler
import hashlib
import importlib
import json
import os
from pathlib import Path
import pickle
import random
import re
import signal
import sys
import time
import traceback

from eval_common import ROOT, Telemetry, save_json
from eval_model_registry import MODEL_NAMES, validate_server_identity, validate_lora_identity
from eval_planner_optimization import evaluation_planner_setup
from eval_official_worker import (ROBOTWIN, LINGBOT, config, observation,
                                 restore_scene_sequence, restore_task_state,
                                 release_unused_cuda_cache)


def scene_hash(env):
    """Check exposed physical state and action counter around a blocking RPC."""
    value = (env.take_action_cnt, env.robot.get_left_arm_jointState(),
             env.robot.get_right_arm_jointState(),
             env.robot.left_entity.get_qpos().tolist(), env.robot.left_entity.get_qvel().tolist(),
             env.robot.right_entity.get_qpos().tolist(), env.robot.right_entity.get_qvel().tolist(),
             [(a.get_name(), a.get_pose().p.tolist(), a.get_pose().q.tolist())
              for a in env.scene.get_all_actors()])
    return hashlib.sha256(pickle.dumps(value)).hexdigest()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--mode', choices=['capture', 'evaluate'], required=True)
    parser.add_argument('--task', default='adjust_bottle')
    parser.add_argument('--setting', choices=['clean', 'randomized'], required=True)
    parser.add_argument('--index', type=int, default=0)
    parser.add_argument('--condition', choices=['local', 'ssh_loopback', 'a100'], default='local')
    parser.add_argument('--model', choices=MODEL_NAMES, default='robotwin')
    parser.add_argument('--precision', choices=['bf16', 'fp32'], default='bf16')
    parser.add_argument('--planner-initialization', choices=['skip_unused', 'legacy'],
                        default='skip_unused',
                        help='Skip unused expert GPU planners; legacy retains original setup for comparisons')
    parser.add_argument('--evaluation-protocol', default='hybrid_v1_rt')
    parser.add_argument('--subset-id', default='')
    parser.add_argument('--subset-commit', default='')
    parser.add_argument('--manifest-dir', type=Path, default=ROOT / 'manifests/official_eval_1000')
    parser.add_argument('--port', type=int, default=19530)
    parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args()
    if not re.fullmatch(r'hybrid_[a-z0-9_]+_rt', args.evaluation_protocol):
        parser.error('Expected a named hybrid RT evaluation protocol')
    if bool(args.subset_id) != bool(args.subset_commit) or (args.subset_commit and
            not re.fullmatch('[0-9a-f]{40}', args.subset_commit)):
        parser.error('A frozen subset requires both its subset ID and full Git commit')
    args.output = args.output.resolve()
    args.output.mkdir(parents=True, exist_ok=True)
    if (args.output / 'result.json').exists():
        raise RuntimeError('Choose a new output directory; completed results are immutable')
    faulthandler.register(signal.SIGUSR1, all_threads=True)
    save_json(args.output / 'diagnostics_ready.json', {'pid': os.getpid(), 'signal': 'SIGUSR1'})
    if os.environ.get('EVAL_RENDER_SHADER', 'rt') != 'rt':
        raise RuntimeError('Hybrid evaluation requires the original local RT rendering')
    manifest_path = args.manifest_dir / f'{args.task}__{args.setting}.json'
    manifest = json.loads(manifest_path.read_text())
    row = next(r for r in manifest['episodes'] if r['index'] == args.index)
    if manifest['status'] != 'ready':
        raise RuntimeError('Manifest is not ready')
    env = client = telemetry = None
    def timeout(*_):
        raise TimeoutError('Hybrid episode exceeded its wall-time deadline')
    signal.signal(signal.SIGALRM, timeout)
    # The eager LoRA service is slower and six sessions share its serial GPU.
    # Keep exactly the same environment action limits and frozen episode seeds.
    signal.alarm(2400 if args.model == 'lora8' else 1200)
    try:
        import numpy as np
        os.chdir(ROBOTWIN)
        sys.path[:0] = [str(ROBOTWIN), str(ROBOTWIN / 'description/utils'), str(LINGBOT)]
        from eval_device import bind_sapien
        bind_sapien()
        cls = getattr(importlib.import_module('envs.' + args.task), args.task)
        env = cls()
        cfg = config(args.task, args.setting)
        telemetry = Telemetry(args.output / 'gpu_samples.jsonl')
        start = telemetry.sample()['monotonic']
        random.seed(row['seed'])
        scene_sequence = restore_scene_sequence(env, row)
        with evaluation_planner_setup(cfg, mode=args.planner_initialization,
                                      action_type='qpos', policy_execution='remote') as planner_setup:
            env.setup_demo(now_ep_num=row['index'], seed=row['seed'], is_test=True, **cfg)
            planner_setup.verify_environment(env)
        restored_state = restore_task_state(env, row)
        release_unused_cuda_cache(env)
        env.set_instruction(instruction=row['instruction'])
        setup_seconds = time.monotonic() - start
        import sapien
        shader_getter = getattr(sapien.render, 'get_camera_shader_dir', None)
        provenance = {**row, 'evaluation_protocol': args.evaluation_protocol,
                      'planner_initialization': args.planner_initialization,
                      'planner_setup': planner_setup.provenance(),
                      'noise_protocol': 'numpy_PCG64_SeedSequence_policy_seed_sequence_float32',
                      'condition': args.condition, 'model': args.model, 'precision': args.precision,
                      'manifest_sha256': hashlib.sha256(manifest_path.read_bytes()).hexdigest(),
                      'render_shader_requested': 'rt',
                      'render_shader_actual': str(shader_getter()) if shader_getter else 'getter_unavailable',
                      'render_device': str(env.scene.render_system.device),
                      'local_gpu_uuid': os.environ.get('EVAL_GPU_UUID'),
                      'restored_scene_sequence': scene_sequence, 'restored_task_state': restored_state,
                      'memory_scope': 'whole local GPU, includes desktop and any colocated policy',
                      'transport_route': ('local -> NSCC sshd -> local policy (double tunnel)' if
                                          args.condition == 'ssh_loopback' else args.condition)}
        if args.subset_id:
            provenance.update(subset_id=args.subset_id, subset_commit=args.subset_commit)
        save_json(args.output / 'provenance.json', provenance)
        first_observation_start = time.monotonic()
        first_obs = observation(env)
        first_observation_seconds = time.monotonic() - first_observation_start
        np.savez(args.output / 'initial_observation.npz', **first_obs)
        obs_hashes = {key: hashlib.sha256(np.ascontiguousarray(value).tobytes()).hexdigest()
                      for key, value in first_obs.items() if key != 'task'}
        save_json(args.output / 'observation_hashes.json', obs_hashes)
        if args.mode == 'capture':
            end = telemetry.sample()['monotonic']
            result = {**provenance, 'status': 'captured', 'setup_seconds': setup_seconds,
                      'observation_hashes': obs_hashes, **telemetry.summary(start, end)}
        else:
            from hybrid_transport import HybridClient, InfrastructureError
            client = HybridClient(port=args.port, timeout=120, log_path=args.output / 'requests.jsonl')
            metadata = client.get_server_metadata()
            if metadata['model'] != args.model or metadata['precision'] != args.precision:
                raise InfrastructureError('Server model/precision mismatch')
            if args.model == 'e5':
                validate_server_identity(metadata, ROOT)
            if args.model == 'lora8':
                validate_lora_identity(metadata, ROOT)
            if args.condition == 'a100' and 'A100' not in metadata.get('gpu_name', ''):
                raise InfrastructureError('A100 condition requires an actual A100 policy device')
            if (args.evaluation_protocol != 'hybrid_v1_rt' and
                    metadata.get('concurrency_protocol') != 'hybrid_concurrency_v1'):
                raise InfrastructureError('Capacity evaluation requires isolated concurrent server')
            save_json(args.output / 'server_metadata.json', metadata)
            client.reset(f'{args.task}/{args.setting}/{args.index}', row['policy_seed'])
            from e5_rollout_history import RolloutCombinedHistory
            episode_id = f'{args.task}/{args.setting}/{args.index}'
            history = RolloutCombinedHistory(episode_id, args.output, session_id=client._session_id) if args.model == 'e5' else None
            rollout_start = time.monotonic()
            success, calls = False, 0
            observation_seconds, action_seconds = first_observation_seconds, 0.0
            unchanged_waits = 0
            while env.take_action_cnt < env.step_lim and not success:
                tick = time.monotonic()
                obs = first_obs if calls == 0 else observation(env)
                observation_seconds += time.monotonic() - tick
                before = scene_hash(env)
                if history is not None:
                    obs = history.observe(obs, env.take_action_cnt, calls, session_id=client._session_id)
                response = client.infer(obs)
                if scene_hash(env) != before:
                    raise InfrastructureError('Physical state advanced during a blocking policy request')
                unchanged_waits += 1
                actions = np.asarray(response['action'])
                if actions.shape != (50, 14) or not np.isfinite(actions).all():
                    raise InfrastructureError(f'Invalid action chunk: {actions.shape}')
                np.save(args.output / f'actions_{calls:03d}.npy', actions)
                calls += 1
                tick = time.monotonic()
                for action in actions:
                    if env.take_action_cnt >= env.step_lim:
                        break
                    before_counter = env.take_action_cnt
                    env.take_action(action)
                    if history is not None:
                        history.record_completed(np.asarray(action)[None], before_counter=before_counter,
                            after_counter=env.take_action_cnt, episode_id=episode_id, session_id=client._session_id)
                    if env.eval_success:
                        success = True
                        break
                action_seconds += time.monotonic() - tick
                print(json.dumps({'event': 'chunk', 'calls': calls, 'actions': env.take_action_cnt,
                                  'success': success, 'rtt_ms': client.last_metrics['client_rtt_ms']}), flush=True)
            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']
            metrics = [m for m in client.metrics if m['operation'] == 'infer']
            means = {f'mean_{key}': sum(m[key] for m in metrics) / len(metrics)
                     for key in ('client_pack_ms', 'client_rtt_ms', 'client_unpack_ms',
                                 'server_infer_ms', 'request_bytes', 'response_bytes')}
            if args.evaluation_protocol != 'hybrid_v1_rt':
                for key in ('server_queue_ms', 'server_state_switch_ms', 'server_session_init_ms'):
                    means[f'mean_{key}'] = sum(m[key] for m in metrics) / len(metrics)
                    means[f'p95_{key}'] = float(np.percentile([m[key] for m in metrics], 95))
                means['p95_client_rtt_ms'] = float(np.percentile([m['client_rtt_ms'] for m in metrics], 95))
            result = {**provenance, 'status': 'completed', 'success': success,
                      'setup_seconds': setup_seconds, 'rollout_seconds': rollout_seconds,
                      'episode_wall_seconds': end - start, 'actions': action_count, 'step_limit': step_limit,
                      'policy_calls': calls, 'physical_state_unchanged_during_requests': unchanged_waits,
                      'observation_seconds': observation_seconds, 'action_execution_seconds': action_seconds,
                      'first_observation_seconds': first_observation_seconds,
                      'rollout_timing_scope': 'after initial observation/save/reset; includes state checks and action saves',
                      'observation_hashes': obs_hashes, **means, **telemetry.summary(start, end)}
            result['mean_transport_serialization_residual_ms'] = (
                means['mean_client_rtt_ms'] - means['mean_server_infer_ms'])
            if result['memory_coverage'] < 0.98:
                raise InfrastructureError('Insufficient GPU telemetry coverage')
        save_json(args.output / 'result.json', result)
        print(json.dumps({'event': 'finished', **result}), flush=True)
    except BaseException as error:
        save_json(args.output / 'infrastructure_error.json',
                  {'status': 'infrastructure_error', 'type': type(error).__name__, 'message': str(error),
                   'traceback': traceback.format_exc(), 'timestamp': time.time()})
        raise
    finally:
        signal.alarm(0)
        if client is not None:
            client.close()
        if telemetry is not None:
            try:
                telemetry.close()
            except Exception as error:
                save_json(args.output / 'telemetry_cleanup_error.json', {'message': str(error)})
        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(timeout=5)


if __name__ == '__main__':
    main()