"""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()