File size: 12,413 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
"""Skip unused expert CUDA engines in the supported hybrid evaluation path.

This does not replace CuRobo's planner class or its CPU gripper interpolation.
Only construction is temporarily changed; MPlib TOPP and the simulation are
untouched. Expert seed selection must continue to use the legacy constructor.

CuRobo warmup consumes CUDA random numbers. Omitting it intentionally changes
the local CUDA RNG state, so the optimized path is restricted to RGB/qpos
rollouts with policy inference in a separate process. It is not a general
replacement for the planner, nor a claim that all RNG states are identical.
"""
from contextlib import contextmanager
import hashlib
import importlib
import inspect
from pathlib import Path
import threading
import time


PLANNER_SETUP_MODES = ('legacy', 'skip_unused')
OPTIMIZATION_VERSION = 'hybrid_rgb_qpos_skip_curobo_v1'
_PATCH_LOCK = threading.Lock()


def _expert_planning_unavailable(*args, **kwargs):
    raise RuntimeError('Expert CuRobo planning is unavailable in optimized RGB/qpos '
                       'evaluation; use planner setup mode legacy for expert planning')


def _validate_configuration(cfg, action_type, policy_execution):
    """Reject unvalidated paths before touching the upstream planner class."""
    if cfg.get('eval_mode') is not True:
        raise ValueError('Planner optimization requires eval_mode=True')
    if cfg.get('collect_data') is not False or cfg.get('save_data') is not False:
        raise ValueError('Planner optimization cannot be used for expert data collection')
    if action_type != 'qpos':
        raise ValueError('Planner optimization only supports qpos actions')
    if policy_execution != 'remote':
        raise ValueError('Planner optimization requires separate-process remote policy inference')
    if cfg.get('embodiment') != ['aloha-agilex'] or cfg.get('dual_arm_embodied') is not True:
        raise ValueError('Planner optimization only supports dual-arm aloha-agilex')
    if cfg.get('domain_randomization', {}).get('random_embodiment', False):
        raise ValueError('Random embodiment is unsupported by planner optimization')
    left_path, right_path = cfg.get('left_robot_file'), cfg.get('right_robot_file')
    # Robot.set_planner compares the original path strings to choose IPC, before
    # appending the arm-specific YAML name. Match that exact decision here.
    if not isinstance(left_path, str) or left_path != right_path:
        raise ValueError('Planner optimization requires identical in-process robot paths')
    robot_path = Path(left_path).resolve()
    if robot_path.name != 'aloha-agilex':
        raise ValueError('Planner optimization requires the aloha-agilex robot directory')
    left = cfg.get('left_embodiment_config', {})
    right = cfg.get('right_embodiment_config', {})
    if left != right or left.get('planner') != 'curobo' or left.get('dual_arm') is not True:
        raise ValueError('Planner optimization requires matching official Aloha CuRobo configurations')
    expected_joints = [[f'{prefix}_joint{i}' for i in range(1, 7)]
                       for prefix in ('fl', 'fr')]
    if left.get('arm_joints_name') != expected_joints:
        raise ValueError('Unsupported Aloha arm joint configuration')
    data = cfg.get('data_type', {})
    if data.get('rgb') is not True or data.get('qpos') is not True:
        raise ValueError('Planner optimization requires RGB and qpos observations')
    if data.get('pointcloud') is not False:
        raise ValueError('Pointcloud observations are unsupported by planner optimization')
    for key in ('depth', 'third_view', 'observer', 'mesh_segmentation', 'actor_segmentation'):
        if data.get(key, False):
            raise ValueError(f'Unsupported observation channel for planner optimization: {key}')
    return robot_path, expected_joints


class _PlannerSetupEvidence:
    def __init__(self, mode):
        self.mode = mode
        self.instances = []
        self.initializations = []
        self.verified = False
        self.class_restored = mode == 'legacy'
        self.source_sha256 = None
        self.planner_class = None
        self.gripper_method = None
        self.reused_instances = 0

    def verify_environment(self, env):
        """Check the actual setup, including IPC and the retained TOPP engines."""
        if self.mode == 'legacy':
            if any(getattr(getattr(env.robot, f'{side}_planner', None),
                           '_hybrid_planner_optimization_version', None)
                   for side in ('left', 'right')):
                raise RuntimeError('Legacy mode requires a fresh environment after optimized setup')
            self.verified = True
            return
        robot = env.robot
        if getattr(env, 'eval_mode', None) is not True:
            raise RuntimeError('Environment left evaluation mode during setup')
        if getattr(robot, 'communication_flag', None) is not False:
            raise RuntimeError('Optimized evaluation unexpectedly used planner IPC')
        if getattr(robot, 'is_dual_arm', None) is not True:
            raise RuntimeError('Optimized evaluation requires the dual-arm robot')
        if getattr(robot, 'need_topp', None) is not True:
            raise RuntimeError('Optimized qpos evaluation requires official MPlib TOPP')
        planners = (robot.left_planner, robot.right_planner)
        if planners[0] is planners[1]:
            raise RuntimeError('Expected exactly two distinct CuRobo planners')
        if self.instances and (len(self.instances) != 2 or
                               set(map(id, planners)) != set(map(id, self.instances))):
            raise RuntimeError('Expected exactly two initialized in-process CuRobo planners')
        for planner in planners:
            if type(planner) is not self.planner_class:
                raise RuntimeError('Upstream CuRobo planner type changed during setup')
            if hasattr(planner, 'motion_gen') or hasattr(planner, 'motion_gen_batch'):
                raise RuntimeError('Expert CUDA engine was unexpectedly initialized')
            if getattr(planner, '_hybrid_planner_optimization_version', None) != OPTIMIZATION_VERSION:
                raise RuntimeError('Existing planner was not constructed by this optimization')
            if planner.plan_path is not _expert_planning_unavailable or planner.plan_batch is not _expert_planning_unavailable:
                raise RuntimeError('Expert planning guard was replaced during setup')
            if 'plan_grippers' in vars(planner) or type(planner).plan_grippers is not self.gripper_method:
                raise RuntimeError('Official gripper interpolation changed during setup')
        for side in ('left', 'right'):
            if not callable(getattr(getattr(robot, f'{side}_mplib_planner', None), 'TOPP', None)):
                raise RuntimeError(f'Missing official {side} MPlib TOPP engine')
        if not self.instances:
            self.reused_instances = 2
        self.verified = True

    def provenance(self):
        return {
            'mode': self.mode,
            'version': OPTIMIZATION_VERSION,
            'scope': 'remote_policy_rgb_qpos_aloha_evaluation',
            'environment_verified': self.verified,
            'constructor_restored': self.class_restored,
            'planner_instances_skipped': len(self.instances),
            'planner_instances_reused': self.reused_instances,
            'expert_motiongen_engines_skipped': len(self.instances) * 2,
            'initializations': list(self.initializations),
            'upstream_planner_source_sha256': self.source_sha256,
            'local_cuda_rng_matches_legacy': self.mode == 'legacy',
            'cuda_rng_note': ('Unchanged legacy constructor' if self.mode == 'legacy' else
                             'CuRobo warmup CUDA RNG draws are omitted; remote policy noise is independent'),
            'gripper_interpolation': 'official_unchanged',
            'qpos_trajectory': 'official_MPlib_TOPP_unchanged',
        }


@contextmanager
def evaluation_planner_setup(cfg, *, mode, action_type='qpos', policy_execution='remote',
                             _planner_module=None):
    """Scope constructor substitution to one fresh hybrid environment setup.

    Call ``evidence.verify_environment(env)`` after ``env.setup_demo`` inside
    this context. A normal exit without verification is an error. Exceptions
    always restore the original constructor, but the created planner instances
    retain fail-closed expert planning guards for their entire lifetime.

    ``_planner_module`` is a CPU-test seam, not a production configuration flag.
    The explicit ``legacy`` mode performs no import or patch and is suitable for
    comparisons and rollback.
    """
    if mode not in PLANNER_SETUP_MODES:
        raise ValueError(f'Unknown planner setup mode: {mode}')
    evidence = _PlannerSetupEvidence(mode)
    if mode == 'legacy':
        yield evidence
        return
    robot_path, expected_joints = _validate_configuration(cfg, action_type, policy_execution)
    if threading.current_thread() is not threading.main_thread():
        raise RuntimeError('Planner setup substitution is only supported in the main thread')
    if not _PATCH_LOCK.acquire(blocking=False):
        raise RuntimeError('Nested or concurrent planner setup substitution is unsupported')
    original_init = planner_class = None
    try:
        module = _planner_module or importlib.import_module('envs.robot.planner')
        planner_class = module.CuroboPlanner
        original_init = planner_class.__init__
        evidence.planner_class = planner_class
        evidence.gripper_method = planner_class.plan_grippers
        source = inspect.getsourcefile(planner_class)
        if source and Path(source).is_file():
            evidence.source_sha256 = hashlib.sha256(Path(source).read_bytes()).hexdigest()

        def minimal_init(self, robot_origion_pose, active_joints_name, all_joints, yml_path=None):
            started = time.monotonic()
            if yml_path is None:
                raise ValueError('Optimized planner requires its official arm YAML path')
            yaml_path = Path(yml_path).resolve()
            filenames = ('curobo_left.yml', 'curobo_right.yml')
            if yaml_path.parent != robot_path or yaml_path.name not in filenames:
                raise ValueError(f'Unexpected optimized planner configuration: {yaml_path}')
            arm_index = filenames.index(yaml_path.name)
            if list(active_joints_name) != expected_joints[arm_index]:
                raise ValueError('Unexpected active joints in optimized planner construction')
            if not set(active_joints_name).issubset(all_joints):
                raise ValueError('Optimized planner joint names are absent from the robot')
            if len(evidence.instances) >= 2:
                raise RuntimeError('Unexpected extra CuRobo planner initialization')
            # Keep original class identity and official CPU-only methods. Guard
            # expert calls immediately, including ones accidentally made by setup.
            self.plan_path = _expert_planning_unavailable
            self.plan_batch = _expert_planning_unavailable
            self._hybrid_planner_optimization_version = OPTIMIZATION_VERSION
            module.ta.setup_logging('CRITICAL')
            module.logger.setup_logger(level='error', logger_name="'curobo")
            self.yml_path = yml_path
            self.robot_origion_pose = robot_origion_pose
            self.active_joints_name = active_joints_name
            self.all_joints = all_joints
            with open(yml_path) as stream:
                self.frame_bias = module.yaml.safe_load(stream)['planner']['frame_bias']
            evidence.instances.append(self)
            evidence.initializations.append({'arm': ('left', 'right')[arm_index],
                                             'yml_path': str(yaml_path),
                                             'seconds': time.monotonic() - started})

        planner_class.__init__ = minimal_init
        yield evidence
        if not evidence.verified:
            raise RuntimeError('Optimized environment was not verified after setup')
    finally:
        if original_init is not None:
            planner_class.__init__ = original_init
            evidence.class_restored = True
        _PATCH_LOCK.release()