From 8c80e7bf14d0c85558d3a6dedfb03cdaf3ac303c Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:22:30 -0800 Subject: [PATCH 01/30] Run the tutorial on the Isaac Lab main branch On Isaac Lab main, NewtonBuilderCfg moved out of newton_manager_cfg and physics callbacks register on a manager instance. A NewtonManager subclass now applies the workshop contact model when its own simulation builds the model. The configuration references it by name, so loading a task still does not import the Newton runtime. --- .../tasks/place_vial/config/so101/env_cfg.py | 34 +++++-------------- .../place_vial/config/so101/newton_manager.py | 24 +++++++++++++ 2 files changed, 33 insertions(+), 25 deletions(-) create mode 100644 src/isaaclab_tutorial/tasks/place_vial/config/so101/newton_manager.py diff --git a/src/isaaclab_tutorial/tasks/place_vial/config/so101/env_cfg.py b/src/isaaclab_tutorial/tasks/place_vial/config/so101/env_cfg.py index 6799fc0..2ad2f9d 100644 --- a/src/isaaclab_tutorial/tasks/place_vial/config/so101/env_cfg.py +++ b/src/isaaclab_tutorial/tasks/place_vial/config/so101/env_cfg.py @@ -21,14 +21,13 @@ from isaaclab.managers import RewardTermCfg as RewTerm from isaaclab.managers import SceneEntityCfg from isaaclab.managers import TerminationTermCfg as DoneTerm -from isaaclab.physics import PhysicsEvent, PhysicsManager, PhysxAutoCfg +from isaaclab.physics import PhysxAutoCfg from isaaclab.scene import InteractiveSceneCfg from isaaclab.sensors import ContactSensorCfg from isaaclab.sim.utils import bind_physics_material, clone from isaaclab.utils.configclass import configclass from isaaclab.visualizers import VisualizerCfg from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg, NewtonCollisionPipelineCfg -from isaaclab_newton.physics.newton_manager_cfg import NewtonBuilderCfg from isaaclab_ov.physics import OvPhysxCfg from isaaclab_physx.physics import PhysxCfg from isaaclab_physx.sim.schemas import PhysxRigidBodyCfg @@ -75,7 +74,6 @@ _CONDIM = 3 _SOLIMP = (0.7, 0.95, 0.0001, 0.5, 2.0) _SOLREF = (0.002, 1.5) -_contact_model_registered = False # Bound to every collider so both backends see the same friction. PhysX also uses it as a compliant contact matching @@ -152,12 +150,12 @@ class SupportSpawnCfg(sim_utils.CuboidCfg): torsional_friction_range: tuple[float, float] = (0.001, 0.005) -def _initialize_contacts(_event: PhysicsEvent) -> None: - """Apply the workshop-validated contact model to every Newton shape.""" - sim = sim_utils.SimulationContext.instance() - builder = sim.get_or_create_backend(NewtonBuilderCfg(physics_cfg=sim.cfg.physics)) +def initialize_contacts(builder: Any, stage: Any) -> None: + """Apply the workshop-validated contact model to every shape of a Newton model builder. - vial_prim = sim.stage.GetPrimAtPath("/World/envs/env_0/Vial") + :class:`~.newton_manager.ContactModelNewtonManager` calls this when its simulation builds the model. + """ + vial_prim = stage.GetPrimAtPath("/World/envs/env_0/Vial") body_range = vial_prim.GetAttribute("tutorial:bodyDiameterRange").Get() if vial_prim else None cap_range = vial_prim.GetAttribute("tutorial:capDiameterRange").Get() if vial_prim else None if body_range is not None and cap_range is not None: @@ -203,7 +201,7 @@ def _initialize_contacts(_event: PhysicsEvent) -> None: # The vial's cap is wider than its body, so on its side it rolls in circles unless the desk resists rolling. rolling = (_ROLLING_FRICTION, _ROLLING_FRICTION) torsional = (_TORSIONAL_FRICTION, _TORSIONAL_FRICTION) - support = sim.stage.GetPrimAtPath("/World/envs/env_0/Support") + support = stage.GetPrimAtPath("/World/envs/env_0/Support") if support: support_rolling = support.GetAttribute("tutorial:rollingFrictionRange").Get() support_torsional = support.GetAttribute("tutorial:torsionalFrictionRange").Get() @@ -235,22 +233,6 @@ def configure_support_rolling_contacts(builder, rolling_range, torsional_range) condim[index] = 6 -def _register_contact_model() -> None: - """Register the contact initializer once per process.""" - global _contact_model_registered - if _contact_model_registered: - return - PhysicsManager.register_callback( - _initialize_contacts, - PhysicsEvent.MODEL_INIT, - name="so101_workshop_contact_model", - ) - _contact_model_registered = True - - -_register_contact_model() - - def _remove_non_gripper_colliders(robot_prim: Any) -> None: """Keep fixed jaw, moving jaw and camera-mount contacts; retain all link dynamics/visuals.""" from pxr import Usd, UsdPhysics @@ -755,6 +737,8 @@ class TerminationsCfg: @configclass class PhysicsCfg(PresetCfg): newton_mjwarp = NewtonCfg( + # Referenced by name: the manager imports the Newton runtime, which configurations must not. + class_type="isaaclab_tutorial.tasks.place_vial.config.so101.newton_manager:ContactModelNewtonManager", solver_cfg=MJWarpSolverCfg( solver="newton", integrator="implicitfast", diff --git a/src/isaaclab_tutorial/tasks/place_vial/config/so101/newton_manager.py b/src/isaaclab_tutorial/tasks/place_vial/config/so101/newton_manager.py new file mode 100644 index 0000000..b720ca0 --- /dev/null +++ b/src/isaaclab_tutorial/tasks/place_vial/config/so101/newton_manager.py @@ -0,0 +1,24 @@ +"""Newton physics manager that applies the workshop contact model to its own simulation.""" + +from __future__ import annotations + +from typing import Any + +from isaaclab.physics import PhysicsEvent +from isaaclab_newton.physics import NewtonManager + +from .env_cfg import initialize_contacts + + +class ContactModelNewtonManager(NewtonManager): + """Writes the workshop contact model when this manager's simulation builds its Newton model. + + Registering on the manager, not process-wide, leaves other simulations in the same process untouched. + """ + + def initialize(self, sim_context: Any) -> None: + super().initialize(sim_context) + self.register_callback(self._apply_contact_model, PhysicsEvent.MODEL_INIT, name="so101_workshop_contact_model") + + def _apply_contact_model(self, _event: Any) -> None: + initialize_contacts(self.builder, self._sim.stage) From 28d4fea778818a886e761b61ef243a058e32f279 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:23:05 -0800 Subject: [PATCH 02/30] Build Isaac Lab from the isaaclab_fovi pull request and add a fovi extra The ActiveGaze task needs the foveated camera from Isaac Lab's isaaclab_fovi package, which is still under review. Until it merges, Isaac Lab is built from that pull request's branch. The fovi extra installs isaaclab[fovi] and the transformers release that has the Cosmos3-Edge text model; an override lifts Isaac Lab's older transformers pin. uv.lock is regenerated once the Isaac Lab branch is published. --- pyproject.toml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 6779279..c718166 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,6 +26,8 @@ generate-so101-resets = "isaaclab_tutorial.tasks.place_vial.reset.generator:gene view-so101-resets = "isaaclab_tutorial.tasks.place_vial.reset.generator:view_main" [project.optional-dependencies] +# The foveated camera (isaaclab_fovi) and the libraries of the ActiveGaze task. +fovi = ["isaaclab[fovi]", "transformers==5.19.0"] leapp = ["leapp==0.7.2"] ovphysx = ["ovphysx"] ovrtx = ["ovrtx==0.5.0.377615", "ovstage==0.1.1.355824"] @@ -39,10 +41,14 @@ wandb = ["isaaclab[wandb]", "wandb==0.26.1"] dev = ["codespell>=2.4", "pre-commit>=4.2", "pytest>=8.3", "ruff>=0.11"] [tool.uv] -environments = ["sys_platform == 'linux' and platform_machine == 'x86_64'", "sys_platform == 'win32' and platform_machine == 'AMD64'", "sys_platform == 'linux' and platform_machine == 'aarch64'"] +# Isaac Lab pins transformers 5.10.4; the ActiveGaze language encoder (Cosmos3-Edge) first ships in 5.19.0. +override-dependencies = ["transformers==5.19.0"] +environments =["sys_platform == 'linux' and platform_machine == 'x86_64'", "sys_platform == 'win32' and platform_machine == 'AMD64'", "sys_platform == 'linux' and platform_machine == 'aarch64'"] [tool.uv.sources] -isaaclab = { git = "https://github.com/isaac-sim/IsaacLab.git", branch = "release/3.0.0", subdirectory = "tools/wheel_builder" } +# The ActiveGaze task needs isaaclab_fovi, which is under review in Isaac Lab. Until it merges, the tutorial builds +# Isaac Lab from that pull request's branch. +isaaclab = { git = "https://github.com/nblauch/IsaacLab.git", branch = "feat/isaaclab-fovi-sensors", subdirectory = "tools/wheel_builder" } ovphysx = { index = "nvidia" } ovrtx = { index = "nvidia" } torch = { index = "pytorch-cu130" } From fdb2c558eb2d77bbd62f73738034d1e661c00f10 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:25:30 -0800 Subject: [PATCH 03/30] Import the ActiveGaze task code from isaaclab_fovi Copies the task, gaze action, learning and training modules, the number decals and their tests from the original isaaclab_fovi package (IsaacLab fork commit 6fa2e0c61). Only file locations, license headers and package import paths change here, so the next commits show each adaptation on its own. The code does not run yet. --- src/isaaclab_tutorial/active_gaze/agents.py | 181 ++++++ .../active_gaze/calibrate.py | 215 ++++++ .../active_gaze/camera_geometry.py | 53 ++ .../active_gaze/configuration.py | 97 +++ .../active_gaze/distributed.py | 37 ++ src/isaaclab_tutorial/active_gaze/env_cfg.py | 428 ++++++++++++ .../active_gaze/fixation/__init__.py | 1 + .../active_gaze/fixation/actions.py | 93 +++ .../active_gaze/fixation/oracle.py | 30 + .../active_gaze/fixation/parameterization.py | 93 +++ src/isaaclab_tutorial/active_gaze/gaze.py | 296 +++++++++ src/isaaclab_tutorial/active_gaze/goals.py | 380 +++++++++++ src/isaaclab_tutorial/active_gaze/language.py | 9 + .../active_gaze/learning/__init__.py | 1 + .../active_gaze/learning/chunks.py | 143 ++++ .../active_gaze/learning/config.py | 25 + .../active_gaze/learning/dino.py | 109 ++++ .../active_gaze/learning/distributions.py | 72 +++ .../active_gaze/learning/fusion.py | 103 +++ .../active_gaze/learning/language.py | 157 +++++ .../active_gaze/learning/models.py | 94 +++ .../active_gaze/learning/observations.py | 22 + .../active_gaze/learning/oracle_ppo.py | 250 +++++++ .../active_gaze/learning/rnd.py | 39 ++ .../active_gaze/learning/runner.py | 211 ++++++ src/isaaclab_tutorial/active_gaze/pose_ppo.py | 21 + .../active_gaze/render_options.py | 70 ++ .../active_gaze/robot_geometry.py | 28 + src/isaaclab_tutorial/active_gaze/runner.py | 73 +++ src/isaaclab_tutorial/active_gaze/sampling.py | 201 ++++++ src/isaaclab_tutorial/active_gaze/sim2real.py | 250 +++++++ src/isaaclab_tutorial/active_gaze/train.py | 611 ++++++++++++++++++ .../active_gaze/training/__init__.py | 1 + .../active_gaze/training/calibrate.py | 116 ++++ .../active_gaze/training/evaluation.py | 238 +++++++ .../active_gaze/training/memory.py | 138 ++++ .../active_gaze/training/tracking.py | 106 +++ .../active_gaze/training/video.py | 75 +++ .../active_gaze/transfer_options.py | 32 + .../assets/numbers/__init__.py | 5 + .../assets/numbers/generate.py | 103 +++ .../assets/numbers/number_1.png | 3 + .../assets/numbers/number_1.usda | 3 + .../assets/numbers/number_2.png | 3 + .../assets/numbers/number_2.usda | 3 + .../assets/numbers/number_3.png | 3 + .../assets/numbers/number_3.usda | 3 + .../assets/numbers/number_4.png | 3 + .../assets/numbers/number_4.usda | 3 + tests/active_gaze/test_action_chunks.py | 174 +++++ .../active_gaze/test_clipped_distribution.py | 85 +++ tests/active_gaze/test_distributed.py | 120 ++++ tests/active_gaze/test_evaluation.py | 551 ++++++++++++++++ tests/active_gaze/test_fixation_geometry.py | 40 ++ tests/active_gaze/test_language.py | 94 +++ tests/active_gaze/test_numbered.py | 246 +++++++ tests/active_gaze/test_presets.py | 94 +++ tests/active_gaze/test_rendering.py | 159 +++++ tests/active_gaze/test_robot_geometry.py | 38 ++ tests/active_gaze/test_sampling.py | 165 +++++ tests/active_gaze/test_sim2real.py | 319 +++++++++ tests/active_gaze/test_training_utilities.py | 35 + tests/active_gaze/test_vial.py | 230 +++++++ 63 files changed, 7581 insertions(+) create mode 100644 src/isaaclab_tutorial/active_gaze/agents.py create mode 100644 src/isaaclab_tutorial/active_gaze/calibrate.py create mode 100644 src/isaaclab_tutorial/active_gaze/camera_geometry.py create mode 100644 src/isaaclab_tutorial/active_gaze/configuration.py create mode 100644 src/isaaclab_tutorial/active_gaze/distributed.py create mode 100644 src/isaaclab_tutorial/active_gaze/env_cfg.py create mode 100644 src/isaaclab_tutorial/active_gaze/fixation/__init__.py create mode 100644 src/isaaclab_tutorial/active_gaze/fixation/actions.py create mode 100644 src/isaaclab_tutorial/active_gaze/fixation/oracle.py create mode 100644 src/isaaclab_tutorial/active_gaze/fixation/parameterization.py create mode 100644 src/isaaclab_tutorial/active_gaze/gaze.py create mode 100644 src/isaaclab_tutorial/active_gaze/goals.py create mode 100644 src/isaaclab_tutorial/active_gaze/language.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/__init__.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/chunks.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/config.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/dino.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/distributions.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/fusion.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/language.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/models.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/observations.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/oracle_ppo.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/rnd.py create mode 100644 src/isaaclab_tutorial/active_gaze/learning/runner.py create mode 100644 src/isaaclab_tutorial/active_gaze/pose_ppo.py create mode 100644 src/isaaclab_tutorial/active_gaze/render_options.py create mode 100644 src/isaaclab_tutorial/active_gaze/robot_geometry.py create mode 100644 src/isaaclab_tutorial/active_gaze/runner.py create mode 100644 src/isaaclab_tutorial/active_gaze/sampling.py create mode 100644 src/isaaclab_tutorial/active_gaze/sim2real.py create mode 100644 src/isaaclab_tutorial/active_gaze/train.py create mode 100644 src/isaaclab_tutorial/active_gaze/training/__init__.py create mode 100644 src/isaaclab_tutorial/active_gaze/training/calibrate.py create mode 100644 src/isaaclab_tutorial/active_gaze/training/evaluation.py create mode 100644 src/isaaclab_tutorial/active_gaze/training/memory.py create mode 100644 src/isaaclab_tutorial/active_gaze/training/tracking.py create mode 100644 src/isaaclab_tutorial/active_gaze/training/video.py create mode 100644 src/isaaclab_tutorial/active_gaze/transfer_options.py create mode 100644 src/isaaclab_tutorial/assets/numbers/__init__.py create mode 100644 src/isaaclab_tutorial/assets/numbers/generate.py create mode 100644 src/isaaclab_tutorial/assets/numbers/number_1.png create mode 100644 src/isaaclab_tutorial/assets/numbers/number_1.usda create mode 100644 src/isaaclab_tutorial/assets/numbers/number_2.png create mode 100644 src/isaaclab_tutorial/assets/numbers/number_2.usda create mode 100644 src/isaaclab_tutorial/assets/numbers/number_3.png create mode 100644 src/isaaclab_tutorial/assets/numbers/number_3.usda create mode 100644 src/isaaclab_tutorial/assets/numbers/number_4.png create mode 100644 src/isaaclab_tutorial/assets/numbers/number_4.usda create mode 100644 tests/active_gaze/test_action_chunks.py create mode 100644 tests/active_gaze/test_clipped_distribution.py create mode 100644 tests/active_gaze/test_distributed.py create mode 100644 tests/active_gaze/test_evaluation.py create mode 100644 tests/active_gaze/test_fixation_geometry.py create mode 100644 tests/active_gaze/test_language.py create mode 100644 tests/active_gaze/test_numbered.py create mode 100644 tests/active_gaze/test_presets.py create mode 100644 tests/active_gaze/test_rendering.py create mode 100644 tests/active_gaze/test_robot_geometry.py create mode 100644 tests/active_gaze/test_sampling.py create mode 100644 tests/active_gaze/test_sim2real.py create mode 100644 tests/active_gaze/test_training_utilities.py create mode 100644 tests/active_gaze/test_vial.py diff --git a/src/isaaclab_tutorial/active_gaze/agents.py b/src/isaaclab_tutorial/active_gaze/agents.py new file mode 100644 index 0000000..9c1ad88 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/agents.py @@ -0,0 +1,181 @@ +"""Class-based SO-101 policy, loss, and optimizer presets.""" + +from isaaclab.utils import configclass +from isaaclab_rl.rsl_rl import RslRlCNNModelCfg, RslRlMLPModelCfg, RslRlOnPolicyRunnerCfg, RslRlPpoAlgorithmCfg +from isaaclab_tasks.utils import PresetCfg + +from isaaclab_tutorial.active_gaze.learning.config import LanguageVisionActorCfg + +from .language import INSTRUCTIONS + + +@configclass +class LearningRateCfg(PresetCfg): + default = 3e-4 + finetune = 3e-5 + + +@configclass +class FineTuneCfg(PresetCfg): + default = False + finetune = True + + +@configclass +class PPOCfg(RslRlPpoAlgorithmCfg): + value_loss_coef = 1.0 + use_clipped_value_loss = True + clip_param = 0.2 + entropy_coef = 0.005 + num_learning_epochs = 5 + num_mini_batches = 8 + learning_rate = LearningRateCfg() + schedule = "adaptive" + gamma = 0.995 + lam = 0.95 + desired_kl = 0.01 + max_grad_norm = 1.0 + + +@configclass +class ActionChunkSizeCfg(PresetCfg): + """Number of control actions predicted by each policy invocation.""" + + default = 1 + chunking = 3 + + +@configclass +class RolloutLengthCfg(PresetCfg): + """Keep the rollout near the default control horizon with three-action chunks.""" + + default = 64 + chunking = 21 + + +@configclass +class OraclePPOCfg(PPOCfg): + class_name = "isaaclab_tutorial.active_gaze.learning.oracle_ppo:OraclePPO" + oracle_weight: float = 1.0 + oracle_std: float = 1e-4 + action_chunk_size = ActionChunkSizeCfg() + schedule = "fixed" + + +@configclass +class GazeWeightCfg(PresetCfg): + grasp_gated = 1.0 + no_gaze_supervision = 0.0 + default = grasp_gated + + +@configclass +class ExtrinsicsPPOCfg(OraclePPOCfg): + class_name = "isaaclab_tutorial.active_gaze.pose_ppo:ExtrinsicsPPO" + oracle_weight = GazeWeightCfg() + extrinsics_weight: float = 0.05 + + +@configclass +class UnsupervisedAlgorithmCfg(PresetCfg): + default = PPOCfg() + chunking = OraclePPOCfg(oracle_weight=0.0) + + +@configclass +class GazeAlgorithmCfg(PresetCfg): + grasp_gated = OraclePPOCfg() + no_gaze_supervision = UnsupervisedAlgorithmCfg() + default = grasp_gated + + +@configclass +class AlgorithmCfg(PresetCfg): + default = GazeAlgorithmCfg() + extrinsics = ExtrinsicsPPOCfg() + + +@configclass +class ExtrinsicsHeadCfg(PresetCfg): + default = False + extrinsics = True + + +@configclass +class SO101FoveatedPPORunnerCfg(RslRlOnPolicyRunnerCfg): + seed = 42 + num_steps_per_env = RolloutLengthCfg() + run_name = "" + clip_actions = 1.0 + critic = RslRlMLPModelCfg(hidden_dims=[256, 256, 128], activation="elu", obs_normalization=True) + finetune = FineTuneCfg() + experiment_name = "so101_vial_foveated" + max_iterations = 5000 + save_interval = 100 + obs_groups = {"actor": ["scene_rgb", "proprioception", "gaze"], "critic": ["critic"]} + algorithm = AlgorithmCfg() + actor = RslRlCNNModelCfg( + cnn_cfg=RslRlCNNModelCfg.CNNCfg( + output_channels=[16, 32, 32], + kernel_size=[5, 3, 3], + stride=[2, 2, 2], + activation="elu", + ), + hidden_dims=[256, 128], + activation="elu", + obs_normalization=True, + distribution_cfg=RslRlCNNModelCfg.GaussianDistributionCfg( + init_std=0.2, + std_type="log", + std_range=(0.05, 0.3), + ), + ) + + +@configclass +class SO101LanguageActorCfg(LanguageVisionActorCfg): + instructions = INSTRUCTIONS + distribution_cfg = SO101FoveatedPPORunnerCfg().actor.distribution_cfg + extrinsics_head = ExtrinsicsHeadCfg() + + +@configclass +class LanguageUnsupervisedAlgorithmCfg(PresetCfg): + default = PPOCfg(use_mixed_precision=True) + chunking = OraclePPOCfg(oracle_weight=0.0, use_mixed_precision=True) + + +@configclass +class LanguageGazeAlgorithmCfg(GazeAlgorithmCfg): + grasp_gated = OraclePPOCfg(use_mixed_precision=True) + no_gaze_supervision = LanguageUnsupervisedAlgorithmCfg() + default = grasp_gated + + +@configclass +class LanguageAlgorithmCfg(AlgorithmCfg): + default = LanguageGazeAlgorithmCfg() + extrinsics = ExtrinsicsPPOCfg(use_mixed_precision=True) + + +@configclass +class SO101LanguagePPORunnerCfg(SO101FoveatedPPORunnerCfg): + actor = SO101LanguageActorCfg() + algorithm = LanguageAlgorithmCfg() + obs_groups = {"actor": ["proprio", "vision", "instruction"], "critic": ["critic"]} + + +@configclass +class SO101Sim2RealPPORunnerCfg(SO101LanguagePPORunnerCfg): + actor = SO101LanguageActorCfg(extrinsics_head=True) + algorithm = ExtrinsicsPPOCfg(use_mixed_precision=True) + + +@configclass +class SO101AgentCfg(PresetCfg): + nearest = SO101FoveatedPPORunnerCfg() + numbered = nearest + dino_language = SO101LanguagePPORunnerCfg() + planar = dino_language + sim2real = SO101Sim2RealPPORunnerCfg() + default = numbered diff --git a/src/isaaclab_tutorial/active_gaze/calibrate.py b/src/isaaclab_tutorial/active_gaze/calibrate.py new file mode 100644 index 0000000..0329499 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/calibrate.py @@ -0,0 +1,215 @@ +"""Measure SO-101 PPO batch capacity on every GPU, then confirm the selected recipe.""" + +import argparse +import json +import math +from pathlib import Path + +from isaaclab_tutorial.active_gaze.training.calibrate import run_trial, valid_measurement +from isaaclab_tutorial.active_gaze.training.memory import minibatch_count + +from .distributed import read_measurement, training_command + + +def budget_ok(data, measured, budget): + return bool(data) and valid_measurement(data, measured, budget / data["total_bytes"]) + + +def propose_environments(samples, budget, maximum, initial, quantum=128): + """Propose a new trial; only measured configurations can qualify.""" + feasible = [(envs, peak) for envs, peak in samples if 0 < peak <= budget] + low = max((envs for envs, _ in feasible), default=0) + high = min((envs for envs, peak in samples if peak > budget), default=maximum + quantum) + if high - low <= quantum or low >= maximum: + return None + if not samples: + return min(initial, maximum) + if not feasible: + return max(quantum, (high // 2) // quantum * quantum) if high > quantum else None + latest = sorted((envs, peak) for envs, peak in samples if math.isfinite(peak)) + if len(latest) >= 2: + first, last = latest[0], latest[-1] + slope = (last[1] - first[1]) / (last[0] - first[0]) + estimate = last[0] + (budget * 0.995 - last[1]) / slope if slope > 0 else low + quantum + else: + estimate = low * 1.25 + proposed = int(estimate) // quantum * quantum + return max(low + quantum, min(high - quantum, maximum, proposed)) + + +def calibrate(args, recipe, rollout_steps): + root = args.output.resolve() + root.mkdir(parents=True, exist_ok=args.resume) + identity = dict( + rollout_steps=rollout_steps, + num_gpus=args.num_gpus, + memory_budget_gb=args.memory_budget_gb, + minibatch_sizes=args.minibatch_sizes, + max_envs=args.max_envs, + warmup=args.warmup, + measure=args.measure, + confirm=args.confirm, + recipe=recipe, + ) + result = dict(complete=False, **identity, trials=[], selected=None) + if args.resume: + previous = json.loads((root / "calibration.json").read_text()) + if any(previous.get(key) != value for key, value in identity.items()): + raise ValueError("Cannot reuse calibration with different settings or task recipe") + result["trials"] = previous["trials"] + if "gpu_identity" in previous: + result["gpu_identity"] = previous["gpu_identity"] + budget = args.memory_budget_gb * 1e9 + + def save(): + (root / "calibration.json").write_text(json.dumps(result, indent=2) + "\n") + + def trial(envs, batch, measured): + for entry in result["trials"]: + if (entry["num_envs"], entry["minibatch_size"], entry["measured_updates"]) == (envs, batch, measured): + return entry["measurement"] + name = f"trial-{len(result['trials']):02d}-env{envs}-mb{batch}" + output = root / name + command = [ + *training_command(args.num_gpus), + "train", + *recipe, + "--num_envs", + str(envs), + "--minibatches", + str(minibatch_count(envs, rollout_steps, batch)), + "--iterations", + str(args.warmup + measured), + "--measure_memory", + "--memory_warmup", + str(args.warmup), + "--output", + str(output), + ] + print(f"SO101_CALIBRATION start {name} ranks={args.num_gpus}", flush=True) + code = run_trial(command, root / f"{name}.log", args.timeout) + data = read_measurement(output, args.num_gpus) if code == 0 else {} + entry = dict( + name=name, + command=command, + returncode=code, + measurement=data, + num_envs=envs, + minibatch_size=batch, + measured_updates=measured, + ) + result["trials"].append(entry) + save() + if code: + log = (root / f"{name}.log").read_text(errors="replace").lower() + if any(word in log for word in ("out of memory", "cuda_error_out_of_memory")): + print(f"SO101_CALIBRATION OOM {name}", flush=True) + return {} + raise RuntimeError(f"Trial {name} failed with exit {code}; inspect its log") + if not data or not data["complete"] or data["measured_updates"] != measured: + raise RuntimeError(f"Trial {name} did not complete its measured window on every rank") + if budget >= data["total_bytes"]: + raise ValueError("Memory budget must leave headroom below physical GPU capacity") + identity_gpu = dict(name=data["gpu"], uuids=data["gpu_uuid"]) + if result.get("gpu_identity", identity_gpu) != identity_gpu: + raise RuntimeError("GPUs changed between calibration trials") + result["gpu_identity"] = identity_gpu + print( + f"SO101_CALIBRATION measured {name}: peak={data['peak_conservative_bytes'] / 1e9:.3f} GB " + f"global_fps={data['mean_total_fps']:.0f} qualifies={budget_ok(data, measured, budget)}", + flush=True, + ) + return data + + save() + try: + candidates = [] + initial = args.initial_envs + for batch in args.minibatch_sizes: + samples = [] + best = None + for _ in range(12): + envs = propose_environments(samples, budget, args.max_envs, initial) + if envs is None: + break + data = trial(envs, batch, args.measure) + peak = data.get("peak_conservative_bytes", math.inf) + samples.append((envs, peak)) + if budget_ok(data, args.measure, budget): + best = data + if peak >= budget * 0.985: + break + if best is not None: + candidates.append(best) + initial = best["num_envs"] + # Each batch size reaches the measured memory boundary before comparing speed. + candidates.sort(key=lambda row: row["mean_total_fps"], reverse=True) + for candidate in candidates: + envs = candidate["num_envs"] + while envs >= 128: + confirmed = trial(envs, candidate["minibatch_size"], args.confirm) + if budget_ok(confirmed, args.confirm, budget): + result["selected"] = confirmed | dict( + minibatches=minibatch_count(envs, rollout_steps, candidate["minibatch_size"]), + total_environments=envs * args.num_gpus, + ) + result["complete"] = True + break + envs -= 128 + if result["complete"]: + break + if not result["complete"]: + raise RuntimeError("No candidate passed the longer confirmation on every GPU") + print("SO101_CALIBRATION_SELECTED " + json.dumps(result["selected"]), flush=True) + return result + except BaseException as exc: + result["error"] = f"{type(exc).__name__}: {exc}" + raise + finally: + save() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--num_gpus", type=int, choices=(1, 2, 4, 8), default=1) + parser.add_argument("--memory_budget_gb", type=float, default=45.0) + parser.add_argument("--initial_envs", type=int, default=2048) + parser.add_argument("--max_envs", type=int, default=8192) + parser.add_argument("--minibatch_sizes", type=int, nargs="+", default=None) + parser.add_argument("--warmup", type=int, default=2) + parser.add_argument("--measure", type=int, default=2) + parser.add_argument("--confirm", type=int, default=8) + parser.add_argument("--timeout", type=int, default=3600) + parser.add_argument("--resume", action="store_true") + parser.add_argument("--checkpoint", type=Path) + args, recipe = parser.parse_known_args() + from .configuration import compose + + saved = json.loads(args.checkpoint.with_name("example.json").read_text()) if args.checkpoint else None + try: + _, agent, recipe = compose(recipe, saved) + except ValueError as exc: + parser.error(str(exc)) + rollout_steps = agent.num_steps_per_env + if args.checkpoint: + recipe += ["--checkpoint", str(args.checkpoint)] + if args.minibatch_sizes is None: + args.minibatch_sizes = [batch for batch in (1024, 2048, 4096) if 128 * rollout_steps % batch == 0] + if not args.minibatch_sizes: + args.minibatch_sizes = [128 * rollout_steps] + if not math.isfinite(args.memory_budget_gb) or args.memory_budget_gb <= 0: + parser.error("memory_budget_gb must be positive and finite") + if min(args.initial_envs, args.max_envs) < 128 or any(n % 128 for n in (args.initial_envs, args.max_envs)): + parser.error("Environment counts must be positive multiples of 128") + if min(args.warmup, args.measure, args.confirm, args.timeout) < 1 or args.confirm < args.measure: + parser.error("Require positive windows and confirmation at least as long as measurement") + if any(batch <= 0 or 128 * rollout_steps % batch for batch in args.minibatch_sizes): + parser.error("Minibatch sizes must divide a 128-environment rollout") + if any(flag in recipe for flag in ("--iterations", "--minibatches", "--num_envs", "--logger")): + parser.error("Calibration controls trial batches, fresh weights and local logging") + calibrate(args, recipe, rollout_steps) + + +if __name__ == "__main__": + main() diff --git a/src/isaaclab_tutorial/active_gaze/camera_geometry.py b/src/isaaclab_tutorial/active_gaze/camera_geometry.py new file mode 100644 index 0000000..843d3c6 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/camera_geometry.py @@ -0,0 +1,53 @@ +"""Batched pinhole lens visibility and camera-pose auxiliary targets.""" + +import torch +from torch.nn import functional as F + +TRANSLATION_SCALE = 0.03 +ROTATION_SCALE = 0.1 + + +def lens_visibility(rays, intrinsics, radial, image_size): + """OpenCV rays against the nominal physical raster (shared fixed optics).""" + xy = rays[..., :2] / rays[..., 2:].clamp_min(1e-7) + xy = xy * (1 + radial[:, None, None] * xy.square().sum(-1, keepdim=True)) + pixels = xy * intrinsics[:, None, :2] + intrinsics[:, None, 2:] + h, w = image_size + return ( + (rays[..., 2] > 0) + & (pixels[..., 0] >= -0.5) + & (pixels[..., 0] < w - 0.5) + & (pixels[..., 1] >= -0.5) + & (pixels[..., 1] < h - 0.5) + ) + + +def pose_targets(translation_delta, rotation_delta): + identity = torch.eye(3, device=rotation_delta.device, dtype=rotation_delta.dtype) + return torch.cat( + ( + translation_delta / TRANSLATION_SCALE, + ((rotation_delta[..., :2, :] - identity[:2]) / ROTATION_SCALE).flatten(-2), + ), + -1, + ) + + +def pose_loss(prediction, target): + """Dimensionless robust translation/rotation supervision, with physical diagnostics.""" + prediction, target = prediction.float(), target.float() + translation = F.smooth_l1_loss(prediction[..., :3], target[..., :3]) + rotation = F.smooth_l1_loss(prediction[..., 3:], target[..., 3:]) + identity = torch.eye(3, device=prediction.device)[:2] + + def matrix(value): + rows = value[..., 3:].reshape(-1, 2, 3) * ROTATION_SCALE + identity + first = F.normalize(rows[:, 0], dim=-1) + second = F.normalize(rows[:, 1] - (first * rows[:, 1]).sum(-1, keepdim=True) * first, dim=-1) + return torch.stack((first, second, torch.cross(first, second, dim=-1)), -2) + + with torch.no_grad(), torch.autocast(prediction.device.type, enabled=False): + position_error = (prediction[..., :3] - target[..., :3]).norm(dim=-1).mean() * TRANSLATION_SCALE * 100 + relative = matrix(prediction) @ matrix(target).transpose(-1, -2) + angle = ((relative.diagonal(dim1=-2, dim2=-1).sum(-1) - 1) / 2).clamp(-1, 1).acos().rad2deg().mean() + return translation + rotation, dict(extrinsics_translation_cm=position_error, extrinsics_rotation_deg=angle) diff --git a/src/isaaclab_tutorial/active_gaze/configuration.py b/src/isaaclab_tutorial/active_gaze/configuration.py new file mode 100644 index 0000000..1155186 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/configuration.py @@ -0,0 +1,97 @@ +"""Compose saved recipes with Isaac Lab's task registry and preset resolver.""" + +from collections.abc import Sequence + +from isaaclab_tasks.utils import resolve_task_config + +from . import TASK_ID + + +def compose(overrides: Sequence[str] = (), saved: dict | None = None): + """Resolve the same env/agent classes used by the standard Isaac Lab CLI. + + A new value replaces the saved value at the same override path. An explicit + ``presets=`` replaces the saved preset list, matching native selector semantics. + """ + saved = saved or {} + if saved and "configuration" not in saved: + raise ValueError("Checkpoint requires a native configuration recipe") + previous = saved.get("configuration", []) + merged = {} + for override in [*previous, *overrides]: + key, separator, value = override.partition("=") + if not separator: + raise ValueError(f"Expected an Isaac Lab configuration override, got {override!r}") + merged[key] = value + recipe = [f"{key}={value}" for key, value in merged.items()] + env, agent = resolve_task_config(TASK_ID, "rsl_rl_cfg_entry_point", overrides=recipe) + env.validate() + agent.validate() + if saved and saved.get("policy", {}).get("name", "cnn") != env.policy: + raise ValueError("Changing policy architecture requires a fresh run") + chunk_size = getattr(agent.algorithm, "action_chunk_size", 1) + if type(chunk_size) is not int or chunk_size < 1: + raise ValueError("Action chunk size must be a positive integer") + if saved and saved.get("action_chunk_size", 1) != chunk_size: + raise ValueError("Changing action chunk size requires a fresh run") + return env, agent, recipe + + +def checkpoint_configuration(overrides: Sequence[str], agent) -> list[str]: + """Save task settings without repeating a one-time fine-tune on resume. + + Preserve the selected fine-tune learning rate as a native scalar override. + A subsequent fine-tune can select its rate explicitly in the new run. + """ + recipe = [] + for override in overrides: + key, _, value = override.partition("=") + if key == "agent.finetune": + continue + if key == "presets": + names = [name for name in value.split(",") if name != "finetune"] + if not names: + continue + override = "presets=" + ",".join(names) + if key != "agent.algorithm.learning_rate" or not agent.finetune: + recipe.append(override) + if agent.finetune: + recipe.append(f"agent.algorithm.learning_rate={agent.algorithm.learning_rate!r}") + return recipe + + +def metadata(env, agent): + """Keep the deployment/checkpoint metadata derived from the resolved config.""" + algorithm = agent.algorithm + result = dict( + action_chunk_size=getattr(algorithm, "action_chunk_size", 1), + goal_mode=env.goal_mode, + renderer=env.renderer_backend(), + render_mode=env.render_mode(), + resolution=env.resolution(), + retinal_geometry=env.retinal_geometry(), + camera=dict( + camera_position=env.camera_position(), + camera_hfov=env.camera_hfov(), + gaze_limit=env.gaze_limit(), + gaze_max_delta=env.gaze_max_delta(), + mixed_gaze_resets=env.mixed_gaze_resets, + cmf_a=env.cmf_a(), + ), + robot=dict(wrist_camera=env.wrist_camera()), + gaze_supervision=dict( + mode="grasp_gated" if env.observations.oracle is not None else "none", + weight=getattr(algorithm, "oracle_weight", 0.0), + std=getattr(algorithm, "oracle_std", 1e-4), + ), + reset_sampling=dict(env.curriculum.reset_sampling.params), + sim2real=env.sim2real.to_dict() if env.sim2real is not None else None, + extrinsics_weight=getattr(algorithm, "extrinsics_weight", 0.0), + policy=dict(name=env.policy, extrinsics_head=env.extrinsics_head()), + ) + if env.policy == "dino_language": + tokens = env.observations.vision.tokens.params + result["policy"].update( + dino_checkpoint=tokens["reference"], dino_checksum=tokens["checksum"], dino_batch_size=tokens["batch_size"] + ) + return result diff --git a/src/isaaclab_tutorial/active_gaze/distributed.py b/src/isaaclab_tutorial/active_gaze/distributed.py new file mode 100644 index 0000000..aeb6b63 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/distributed.py @@ -0,0 +1,37 @@ +"""Single-node SO-101 launch commands and complete per-rank memory reports.""" + +import hashlib +import json +from pathlib import Path + +from isaaclab_tutorial.active_gaze.training.calibrate import aggregate_ranks +from isaaclab_tutorial.active_gaze.training.calibrate import training_command as native_command + + +def training_command(num_gpus: int) -> list[str]: + return native_command(num_gpus, "isaaclab_tutorial.active_gaze.train") + + +def read_measurement(output: Path, num_gpus: int) -> dict: + paths = [output / "memory.json"] + [output / f"rank_{rank}" / "memory.json" for rank in range(1, num_gpus)] + if not all(path.is_file() for path in paths): + return {} + reports = [json.loads(path.read_text()) for path in paths] + return aggregate_ranks(reports) + + +def verify_replicas(runner, output: Path): + """Verify PPO synchronized learned parameters, excluding local running statistics.""" + import torch + + digest = hashlib.sha256() + for model in (runner.alg.actor, runner.alg.critic): + for name, value in model.named_parameters(): + digest.update(name.encode()) + digest.update(value.detach().cpu().contiguous().view(torch.uint8).numpy().tobytes()) + hashes = [None] * runner.gpu_world_size + torch.distributed.all_gather_object(hashes, digest.hexdigest()) + result = dict(world_size=runner.gpu_world_size, parameter_sha256=hashes, synchronized=len(set(hashes)) == 1) + output.write_text(json.dumps(result, indent=2) + "\n") + if not result["synchronized"]: + raise RuntimeError("Learned actor/critic parameters differ across distributed ranks") diff --git a/src/isaaclab_tutorial/active_gaze/env_cfg.py b/src/isaaclab_tutorial/active_gaze/env_cfg.py new file mode 100644 index 0000000..01deccd --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/env_cfg.py @@ -0,0 +1,428 @@ +"""A fixed, calibrated scene camera on the stock SO-101 task.""" + +import math +from typing import ClassVar + +from isaaclab.assets import AssetBaseCfg +from isaaclab.managers import CurriculumTermCfg, ManagerTermBase, ObservationGroupCfg, ObservationTermCfg +from isaaclab.sensors import CameraCfg +from isaaclab.sim import DomeLightCfg, PinholeCameraCfg +from isaaclab.utils import configclass +from isaaclab_tasks.utils import PresetCfg, resolve_presets + +from isaaclab_tutorial.assets.numbers import LABEL_ASSETS +from isaaclab_tutorial.active_gaze.learning.dino import DEFAULT_CHECKPOINT, DEFAULT_MD5 +from isaaclab_tutorial.active_gaze.learning.observations import DinoTokens +from isaaclab_fovi.sensors import FoveatedTiledCameraCfg +from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import ( + ActionsCfg, + CriticStateGroupCfg, + EventsCfg, + SO101VialEnvCfg, +) + +from .env_cfg import ProprioceptionCfg +from .gaze import CachedGazeActionCfg, oracle_labels +from .language import instruction_index +from .render_options import CameraOutputCfg, CameraOutputNameCfg, CameraRenderSettingsCfg, FoviRendererCfg +from .robot_geometry import spawn_without_wrist_camera +from .sampling import ResetSampling, validate_settings +from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import SO101SceneCfg +from .transfer_options import CameraRandomizationCfg + +# Front view along the robot's working axis, centered on the arm and vial board. +CAMERA_POSITION = (0.52, 0.0, 0.36) +CAMERA_TARGET = (0.12, 0.0, 0.12) +SOURCE_SIZE = 640 +HORIZONTAL_FOV = 80.0 +FOCAL_PIXELS = SOURCE_SIZE / (2 * math.tan(math.radians(HORIZONTAL_FOV / 2))) +CALIBRATION = dict( + model="pinhole", + image_size=(SOURCE_SIZE, SOURCE_SIZE), + intrinsics=(FOCAL_PIXELS, FOCAL_PIXELS, 319.5, 319.5), +) + + +def camera_rotation(position=CAMERA_POSITION, target=CAMERA_TARGET): + """OpenGL look-at orientation, XYZW, computed without a simulator.""" + import numpy as np + from scipy.spatial.transform import Rotation + + back = np.asarray(position) - np.asarray(target) + back /= np.linalg.norm(back) + right = np.cross([0.0, 0.0, 1.0], back) + right /= np.linalg.norm(right) + up = np.cross(back, right) + return tuple(float(v) for v in Rotation.from_matrix(np.stack([right, up, back], axis=1)).as_quat()) + + +class SceneRGB(ManagerTermBase): + """Read the camera at policy boundaries while native control steps continue.""" + + def __init__(self, cfg, env): + super().__init__(cfg, env) + self.cached = None + + def __call__(self, env): + if not getattr(env, "refresh_policy_vision", True) and self.cached is not None: + return self.cached + image = env.scene["eye"].data.output[env.scene["eye"].cfg.data_types[0]] + image = image.torch if hasattr(image, "torch") else image + self.cached = image[..., :3].float().permute(0, 3, 1, 2).contiguous() / 255.0 + return self.cached + + +def gaze_state(env): + return env.action_manager.get_term("gaze").proprioception() + + +def motor_action_rate(env): + # Preserve the stock penalty on the six motor increments only. + return (env.action_manager.action[:, :6] - env.action_manager.prev_action[:, :6]).square().sum(-1) + + +@configclass +class FoveatedActionsCfg(ActionsCfg): + """Preserve the pretrained motor contract across camera/randomization variants.""" + + arm_action = resolve_presets(ActionsCfg()).arm_action + gaze = CachedGazeActionCfg(angle_limit=math.radians(HORIZONTAL_FOV / 2 - 1), max_delta=0.12) + + +@configclass +class ImageCfg(ObservationGroupCfg): + image = ObservationTermCfg(func=SceneRGB) + concatenate_dim = 0 + enable_corruption = False + + +@configclass +class GazeCfg(ObservationGroupCfg): + state = ObservationTermCfg(func=gaze_state) + enable_corruption = False + + +@configclass +class OracleCfg(ObservationGroupCfg): + labels = ObservationTermCfg(func=oracle_labels) + enable_corruption = False + + +@configclass +class LanguageProprioceptionCfg(ProprioceptionCfg): + gaze = ObservationTermCfg(func=gaze_state) + + +@configclass +class VisionCfg(ObservationGroupCfg): + tokens = ObservationTermCfg( + func=DinoTokens, + params=dict( + reference=DEFAULT_CHECKPOINT, checksum=DEFAULT_MD5, batch_size=128, data_type=CameraOutputNameCfg() + ), + ) + concatenate_dim = 0 + enable_corruption = False + + +@configclass +class InstructionCfg(ObservationGroupCfg): + index = ObservationTermCfg(func=instruction_index) + enable_corruption = False + + +@configclass +class OracleObservationCfg(PresetCfg): + """Training-only gaze labels; never part of the actor observation group.""" + + grasp_gated = OracleCfg() + no_gaze_supervision = None + default = grasp_gated + + +@configclass +class AuxiliaryObservationCfg(PresetCfg): + from .sim2real import ExtrinsicsObservations as _ExtrinsicsObservations + + default = None + extrinsics = _ExtrinsicsObservations() + + +@configclass +class ObservationsCfg: + scene_rgb = ImageCfg() + proprioception = ProprioceptionCfg() + gaze = GazeCfg() + # Stock state and contacts, with last_action naturally including gaze. + critic = CriticStateGroupCfg() + oracle = OracleObservationCfg() + proprio: LanguageProprioceptionCfg | None = None + vision: VisionCfg | None = None + instruction: InstructionCfg | None = None + extrinsics = AuxiliaryObservationCfg() + + +@configclass +class ResetModeCfg(PresetCfg): + default = "sgs" + uniform = "uniform" + sgs = "sgs" + + +@configclass +class CurriculumCfg: + reset_sampling = CurriculumTermCfg( + func=ResetSampling, + params=dict(mode=ResetModeCfg(), history=100, target=0.5, concentration=1.0, temperature=2.0, epsilon=1e-4), + ) + + +@configclass +class RobotSpawnCfg(PresetCfg): + _stock = SO101SceneCfg().robot.spawn.replace(shoulder_response=None, elbow_response=None) + stock_wrist_camera = _stock + default = _stock.replace(func=spawn_without_wrist_camera) + + +def scene_camera(position=CAMERA_POSITION, target=CAMERA_TARGET, hfov=HORIZONTAL_FOV): + """Construct one calibrated camera; scalar overrides address its native fields.""" + focal = SOURCE_SIZE / (2 * math.tan(math.radians(hfov / 2))) + return FoveatedTiledCameraCfg( + prim_path="{ENV_REGEX_NS}/SceneEye", + data_types=CameraOutputCfg(), + renderer_cfg=FoviRendererCfg(), + render_settings=CameraRenderSettingsCfg(), + spawn=PinholeCameraCfg( + focal_length=24.0, + horizontal_aperture=48.0 * math.tan(math.radians(hfov / 2)), + clipping_range=(0.01, 5.0), + ), + offset=CameraCfg.OffsetCfg(pos=position, rot=camera_rotation(position, target), convention="opengl"), + foveated_res=64, + foveated_style="warped_cartesian_as_grid", + ndc_layout="native_grid", + field_geometry="spherical", + camera_calibration=dict( + model="pinhole", image_size=(SOURCE_SIZE, SOURCE_SIZE), intrinsics=(focal, focal, 319.5, 319.5) + ), + cmf_a=0.036021, + fixed_software_fov=True, + software_fov_image_height=SOURCE_SIZE, + software_fov_image_width=SOURCE_SIZE, + update_period=0.0, + ) + + +@configclass +class SceneCfg(SO101SceneCfg): + robot = SO101SceneCfg().robot.replace( + spawn=RobotSpawnCfg(), + init_state=resolve_presets(SO101SceneCfg().robot.init_state), + ) + eye = scene_camera() + light = AssetBaseCfg(prim_path="/World/Light", spawn=DomeLightCfg(intensity=2000)) + diagnostic_camera: CameraCfg | None = None + + +@configclass +class NumberedSceneCfg(SceneCfg): + eye = scene_camera((0.46, 0.015, 0.34), (0.17, 0.025, 0.12), 78.0).replace( + cmf_a=0.015, + ) + + +@configclass +class LanguageObservationsCfg(ObservationsCfg): + scene_rgb = None + proprioception = None + gaze = None + proprio = LanguageProprioceptionCfg() + vision = VisionCfg() + instruction = InstructionCfg() + + +@configclass +class FinalObservationCfg(PresetCfg): + """Capture pre-reset critic state for timeouts inside an action chunk.""" + + default = False + chunking = True + + +@configclass +class SO101FoveatedEnvCfg(SO101VialEnvCfg): + """Nearest-slot CNN task with a calibrated foveated scene camera.""" + + compute_final_obs = FinalObservationCfg() + + scene = SceneCfg(num_envs=128, env_spacing=0.9) + observations = ObservationsCfg() + actions = FoveatedActionsCfg() + curriculum = CurriculumCfg() + events = EventsCfg() + mixed_gaze_resets: bool = True + reset_sampling_evaluation: bool = False + sim2real: CameraRandomizationCfg | None = None + goal_mode: ClassVar[str] = "nearest" + policy: ClassVar[str] = "cnn" + number_label_assets: str = str(LABEL_ASSETS) + + def __post_init__(self): + super().__post_init__() + # The imported actor and mid-task reset dataset use the nominal SO-101 + # geometry, action scales, rewards, and horizon in every camera variant. + self.episode_length_s = 20.0 + self.rewards = resolve_presets(self.rewards) + self.rewards.action_rate.func = motor_action_rate + self.num_rerenders_on_reset = 1 + + def validate_config(self): + """Validate the final config after presets and scalar overrides are applied.""" + if self.resolution() not in (64, 128): + raise ValueError("SO-101 foveated resolution must be 64 or 128") + if not math.isfinite(self.cmf_a()) or self.cmf_a() <= 0: + raise ValueError("cmf_a must be positive and finite") + if self.scene.eye.data_types != ["rgb"] and self.renderer_backend() != "ovrtx": + raise ValueError("Minimal render modes require renderer=ovrtx") + if self.policy == "dino_language": + if self.resolution() != 128: + raise ValueError("The pretrained foveated DINO policy requires native 128px input") + tokens = self.observations.vision.tokens.params + if tokens["data_type"] not in self.scene.eye.data_types: + raise ValueError("The DINO observation must use an output produced by the scene camera") + if tokens["batch_size"] <= 0: + raise ValueError("DINO batch_size must be positive") + if self.extrinsics_head() and self.policy != "dino_language": + raise ValueError("Extrinsics supervision requires the DINO/language preset") + validate_settings(**self.curriculum.reset_sampling.params) + + def resolution(self): + return self.scene.eye.foveated_res + + def cmf_a(self): + return self.scene.eye.cmf_a + + def camera_position(self): + return self.scene.eye.offset.pos + + def camera_hfov(self): + camera = self.scene.eye.spawn + return math.degrees(2 * math.atan(camera.horizontal_aperture / (2 * camera.focal_length))) + + def gaze_limit(self): + return self.actions.gaze.angle_limit + + def gaze_max_delta(self): + return self.actions.gaze.max_delta + + def renderer_backend(self): + renderer = self.scene.eye.renderer_cfg + renderer = renderer.default if isinstance(renderer, PresetCfg) else renderer + return "ovrtx" if renderer.renderer_type == "ovrtx" else "warp" + + def render_mode(self): + from .render_options import RENDER_MODES + + if self.renderer_backend() == "warp": + return "rgb" + outputs = self.scene.eye.data_types + output = (outputs.default if isinstance(outputs, PresetCfg) else outputs)[0] + renderer = self.scene.eye.renderer_cfg + renderer = renderer.default if isinstance(renderer, PresetCfg) else renderer + shadows = getattr(renderer, "enable_shadows", False) + shadows = shadows.default if isinstance(shadows, PresetCfg) else shadows + return next( + name for name, value in RENDER_MODES.items() if value == (output, shadows if output != "rgb" else False) + ) + + def wrist_camera(self): + spawn = self.scene.robot.spawn + spawn = spawn.default if isinstance(spawn, PresetCfg) else spawn + return "removed" if spawn.func == spawn_without_wrist_camera else "stock" + + def retinal_geometry(self): + return self.scene.eye.field_geometry + + def extrinsics_head(self): + return self.observations.extrinsics is not None + + def play_mode(self): + super().play_mode() + self.reset_sampling_evaluation = True + self.curriculum.reset_sampling.params["mode"] = "uniform" + if self.sim2real is not None: + self.sim2real.ramp_steps = 0 + + def enable_diagnostics(self): + camera = self.scene.eye + self.scene.diagnostic_camera = CameraCfg( + prim_path="{ENV_REGEX_NS}/DiagnosticCamera", + data_types=list(camera.data_types), + width=640, + height=640, + renderer_cfg=camera.renderer_cfg.copy(), + render_settings=camera.render_settings.copy(), + spawn=camera.spawn.copy(), + offset=camera.offset.copy(), + ) + + +@configclass +class SO101NumberedEnvCfg(SO101FoveatedEnvCfg): + """Match a vial's number to its rack slot using textured camera observations.""" + + goal_mode: ClassVar[str] = "numbered" + scene = NumberedSceneCfg(num_envs=128, env_spacing=0.9) + actions = FoveatedActionsCfg(gaze=CachedGazeActionCfg(angle_limit=math.radians(38.0), max_delta=0.12)) + + def __post_init__(self): + super().__post_init__() + from .goals import configure_numbered_scene + + configure_numbered_scene(self) + + +@configclass +class SO101LanguageEnvCfg(SO101NumberedEnvCfg): + """Numbered placement using frozen DINO and language features.""" + + policy: ClassVar[str] = "dino_language" + observations = LanguageObservationsCfg() + scene = NumberedSceneCfg(num_envs=128, env_spacing=0.9, eye=NumberedSceneCfg().eye.replace(foveated_res=128)) + + +@configclass +class SO101PlanarEnvCfg(SO101LanguageEnvCfg): + """Language policy with the same planar software retina used on the robot.""" + + def __post_init__(self): + super().__post_init__() + from .sim2real import configure_planar_camera + + configure_planar_camera(self) + + +@configclass +class SO101Sim2RealEnvCfg(SO101PlanarEnvCfg): + """Planar camera, physical randomization, and auxiliary camera-pose labels.""" + + sim2real = CameraRandomizationCfg() + + def __post_init__(self): + super().__post_init__() + from .sim2real import ExtrinsicsObservations, configure + + configure(self) + self.observations.extrinsics = ExtrinsicsObservations() + + +@configclass +class SO101EnvCfg(PresetCfg): + """Registered task variants; shared names also select the matching agent.""" + + nearest = SO101FoveatedEnvCfg() + numbered = SO101NumberedEnvCfg() + dino_language = SO101LanguageEnvCfg() + planar = SO101PlanarEnvCfg() + sim2real = SO101Sim2RealEnvCfg() + default = numbered diff --git a/src/isaaclab_tutorial/active_gaze/fixation/__init__.py b/src/isaaclab_tutorial/active_gaze/fixation/__init__.py new file mode 100644 index 0000000..8cdf79d --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/fixation/__init__.py @@ -0,0 +1 @@ +"""Binocular fixation geometry and parameterizations.""" diff --git a/src/isaaclab_tutorial/active_gaze/fixation/actions.py b/src/isaaclab_tutorial/active_gaze/fixation/actions.py new file mode 100644 index 0000000..9a8a2a9 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/fixation/actions.py @@ -0,0 +1,93 @@ +"""One gaze-action interface for physical and calibrated hybrid cameras.""" + +import torch +from fovi.sensing.projection import CameraModel +from isaaclab.managers import ActionTerm, ActionTermCfg +from isaaclab.utils import configclass +from isaaclab.utils.math import quat_apply_inverse + +from isaaclab_tutorial.active_gaze.fixation.oracle import fixation_action_target +from isaaclab_fovi.rigs import PanTiltRig + + +class GazeAction(ActionTerm): + """Bounded angular target increments in (tilt, pan) order.""" + + def __init__(self, cfg, env): + super().__init__(cfg, env) + self.camera = env.scene["eye"] + self.rig = PanTiltRig(env.scene["camera_rig"]) if cfg.mode == "hardware" else None + self.calibration = CameraModel(**self.camera.cfg.camera_calibration) + self._raw = torch.zeros(self.num_envs, 2, device=self.device) + self._target = torch.zeros_like(self._raw) + self._velocity = torch.zeros_like(self._raw) + self.base_rotation = torch.tensor(cfg.base_rotation, device=self.device).expand(self.num_envs, -1) + + @property + def action_dim(self): + return 2 + + @property + def raw_actions(self): + return self._raw + + @property + def processed_actions(self): + return self._target + + def process_actions(self, actions): + self._raw.copy_(actions) + previous = self._target.clone() + self._target.add_(actions.clamp(-1, 1) * self.cfg.max_delta).clamp_(-self.cfg.angle_limit, self.cfg.angle_limit) + self._velocity.copy_((self._target - previous) / self._env.step_dt) + if self.rig is None: + self.camera.set_calibrated_angles(self._target) + + def apply_actions(self): + if self.rig is not None: + self.rig.set_fixation_targets(self._target) + + def reset(self, env_ids=None): + selection = slice(None) if env_ids is None else env_ids + self._raw[selection] = 0 + self._target[selection] = 0 + self._velocity[selection] = 0 + if self.rig is not None: + self.rig.reset(env_ids) + else: + self.camera.set_calibrated_angles(self._target) + + def proprioception(self): + if self.rig is not None: + self.rig.update() + actual = self.rig.joint_positions_to_angles(self.rig.joint_pos) + velocity = self.rig.joint_positions_to_angles(self.rig.joint_vel) + else: + actual, velocity = self._target, self._velocity + return torch.cat((actual, velocity, self._target), dim=-1) + + def oracle(self, position): + origin = self.camera.get_world_positions() + direction = quat_apply_inverse(self.base_rotation, position - origin) + visible = None + if self.rig is None: + # Fixed neutral camera: ROS right/down/forward from mount +X/+Y/+Z. + source_direction = torch.stack((direction[:, 0], -direction[:, 2], direction[:, 1]), -1) + _, visible = self.calibration.project(source_direction) + return fixation_action_target( + direction, + self._target, + max_delta=self.cfg.max_delta, + angle_limit=self.cfg.angle_limit, + visible=visible, + ) + + +@configclass +class GazeActionCfg(ActionTermCfg): + class_type: type = GazeAction + asset_name: str = "robot" + mode: str = "hybrid" + max_delta: float = 0.12 + angle_limit: float = 1.2 + base_rotation: tuple = (0.0, 0.0, 0.0, 1.0) diff --git a/src/isaaclab_tutorial/active_gaze/fixation/oracle.py b/src/isaaclab_tutorial/active_gaze/fixation/oracle.py new file mode 100644 index 0000000..5c5e01e --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/fixation/oracle.py @@ -0,0 +1,30 @@ +"""Geometric pan/tilt targets in the same bounded delta space as policy actions.""" + +import torch + + +def fixation_action_target( + direction: torch.Tensor, + commanded: torch.Tensor, + *, + max_delta: float, + angle_limit: float, + visible: torch.Tensor | None = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """Return normalized (tilt, pan) deltas for mount-frame target vectors. + + The neutral rig faces +Y with +Z up. Positive pan turns left and positive + tilt turns up. Hardware targets may lie outside the *current* image; hybrid + callers additionally supply fixed physical-sensor visibility. The desired + joint target is bounded before converting to the executable action scale. + """ + if max_delta <= 0 or angle_limit <= 0: + raise ValueError("Gaze scale and joint limit must be positive.") + x, y, z = direction.unbind(-1) + desired = torch.stack((torch.atan2(z, torch.sqrt(x.square() + y.square())), torch.atan2(-x, y)), dim=-1) + valid = torch.isfinite(direction).all(-1) & (direction.norm(dim=-1) > 1e-6) + valid &= (desired.abs() <= angle_limit).all(-1) + if visible is not None: + valid &= visible + action = ((desired.clamp(-angle_limit, angle_limit) - commanded) / max_delta).clamp(-1, 1) + return torch.where(valid[:, None], action, 0.0), valid diff --git a/src/isaaclab_tutorial/active_gaze/fixation/parameterization.py b/src/isaaclab_tutorial/active_gaze/fixation/parameterization.py new file mode 100644 index 0000000..5bd8cd6 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/fixation/parameterization.py @@ -0,0 +1,93 @@ +"""Binocular fixation parameterizations shared by rendering and control.""" + +from __future__ import annotations + +import math + +import torch + +LEFT_RIGHT = "left_right" +LEFT_RIGHT_SHARED = "left_right_shared" +VERSION_VERGENCE = "version_vergence" +BINOCULAR_PARAMETERIZATIONS = ( + LEFT_RIGHT, + LEFT_RIGHT_SHARED, + VERSION_VERGENCE, +) + + +def validate_fixation_parameterization(parameterization: str, eye_mode: str) -> None: + """Validate one learned-fixation parameterization selection.""" + if eye_mode not in ("left", "binocular"): + raise ValueError(f"Learned fixation eye_mode must be 'left' or 'binocular', got {eye_mode!r}.") + if parameterization not in BINOCULAR_PARAMETERIZATIONS: + raise ValueError( + f"Learned fixation parameterization must be one of {BINOCULAR_PARAMETERIZATIONS}, got {parameterization!r}." + ) + if eye_mode != "binocular" and parameterization != LEFT_RIGHT: + raise ValueError(f"parameterization={parameterization!r} requires eye_mode='binocular'.") + + +def fixation_action_dim(parameterization: str, eye_mode: str) -> int: + """Return the learned-fixation suffix dimension.""" + validate_fixation_parameterization(parameterization, eye_mode) + if eye_mode == "left": + return 2 + if parameterization in (LEFT_RIGHT, LEFT_RIGHT_SHARED): + return 4 + if parameterization == VERSION_VERGENCE: + return 3 + raise ValueError(f"Unsupported fixation parameterization {parameterization!r}.") + + +def validate_vergence_axis(axis: tuple[float, ...]) -> None: + """Validate the configured axis used for version/vergence conversion.""" + if len(axis) != 2 or not all(math.isfinite(value) for value in axis): + raise ValueError("version_vergence requires a finite two-dimensional vergence_axis.") + if not math.isclose(math.hypot(*axis), 1.0, rel_tol=1.0e-5, abs_tol=1.0e-5): + raise ValueError("version_vergence requires a unit-length vergence_axis.") + + +def _aligned_axis(axis: torch.Tensor, reference: torch.Tensor) -> torch.Tensor: + if axis.shape != (2,) and axis.shape != reference.shape: + raise ValueError( + "Vergence axis must have shape (2,) or match the reference tensor; " + f"got {tuple(axis.shape)} versus {tuple(reference.shape)}." + ) + return axis.to(device=reference.device, dtype=reference.dtype) + + +def version_vergence_to_eyes( + version: torch.Tensor, + vergence: torch.Tensor, + axis: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + """Decode two-dimensional version and scalar vergence into eye vectors.""" + if version.shape[-1:] != (2,): + raise ValueError(f"Version must end in dimension 2, got {tuple(version.shape)}.") + if vergence.shape != (*version.shape[:-1], 1): + raise ValueError( + "Vergence must match the version batch shape and end in dimension 1; " + f"got {tuple(vergence.shape)} versus {tuple(version.shape)}." + ) + axis = _aligned_axis(axis, version) + half_disparity = 0.5 * vergence * axis + return version + half_disparity, version - half_disparity + + +def eyes_to_version_vergence( + left: torch.Tensor, + right: torch.Tensor, + axis: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Encode eye vectors and report discarded cross-baseline disparity.""" + if left.shape != right.shape or left.shape[-1:] != (2,): + raise ValueError( + "Left and right fixation tensors must have the same shape ending in 2; " + f"got {tuple(left.shape)} and {tuple(right.shape)}." + ) + axis = _aligned_axis(axis, left) + difference = left - right + vergence = (difference * axis).sum(dim=-1, keepdim=True) + residual = difference - vergence * axis + return 0.5 * (left + right), vergence, residual.norm(dim=-1) diff --git a/src/isaaclab_tutorial/active_gaze/gaze.py b/src/isaaclab_tutorial/active_gaze/gaze.py new file mode 100644 index 0000000..b79f70c --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/gaze.py @@ -0,0 +1,296 @@ +"""Physical-row-aligned gaze resets and optional grasp-gated training labels.""" + +import hashlib +import json +import math +from pathlib import Path + +import torch +from fovi.sensing.projection import CameraModel +from isaaclab.utils import configclass +from isaaclab.utils.math import quat_apply, quat_apply_inverse + +from isaaclab_tutorial.active_gaze.fixation.actions import GazeAction, GazeActionCfg +from isaaclab_tutorial.active_gaze.fixation.oracle import fixation_action_target +from isaaclab_tutorial.tasks.place_vial.mdp.geometry import RACK_HOLE_CENTERS +from isaaclab_tutorial.tasks.place_vial.mdp.progress import placement_progress +from isaaclab_tutorial.tasks.place_vial.mdp.task import ( + RACK_RIM_HEIGHT, + VIAL_AXIS_MAX, + VIAL_AXIS_MIN, +) +from isaaclab_tutorial.active_gaze.reset import load_reset_dataset + +RESET_MODES = ("random", "object", "goal", "near_object", "near_goal") + + +def oracle_target(env): + """Switch from vial center to opening after the stock confirmed grasp. + + The milestone is restored by stock resets and stays latched through release. + It is a training label only, never an actor input or an executed action. + """ + poses = [ + torch.cat((env.scene[name].data.root_pos_w.torch, env.scene[name].data.root_quat_w.torch), dim=-1) + for name in ("vial", "rack") + ] + object_center, goal_center = target_centers(*poses) + if getattr(env.cfg, "goal_mode", "nearest") == "numbered": + from .goals import CAP_LABEL_POSITION, selected_goal_center + + object_center = poses[0][:, :3] + quat_apply( + poses[0][:, 3:], poses[0].new_tensor(CAP_LABEL_POSITION).expand(env.num_envs, -1) + ) + goal_center = selected_goal_center(env, label=True) + return torch.where(placement_progress(env).grasped[:, None], goal_center, object_center) + + +def oracle_labels(env): + gaze = env.action_manager.get_term("gaze") + position = oracle_target(env) + target, valid = gaze.oracle(position) + error = gaze.fixation_error(position).rad2deg() + log = env.extras.setdefault("log", {}) + log["Gaze/target_error_deg"] = torch.where(valid, error, 0).sum() / valid.sum().clamp_min(1) + log["Gaze/within_1deg"] = (valid & (error <= 1)).float().mean() + log["Gaze/goal_target_fraction"] = placement_progress(env).grasped.float().mean() + log["Gaze/valid_target_fraction"] = valid.float().mean() + return torch.cat((target, valid[:, None].float()), dim=-1) + + +def calibrated_oracle(direction, commanded, calibration, *, max_delta, angle_limit): + """Convert ROS camera rays to executable actions with physical-frustum masking.""" + _, visible = calibration.project(direction) + # Shared fixation geometry expects mount right/forward/up, not ROS right/down/forward. + mount = torch.stack((direction[:, 0], direction[:, 2], -direction[:, 1]), dim=-1) + return fixation_action_target(mount, commanded, max_delta=max_delta, angle_limit=angle_limit, visible=visible) + + +def angles_to_direction(angles): + tilt, pan = angles.unbind(-1) + return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) + + +def direction_to_angles(direction): + x, y, z = direction.unbind(-1) + return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1) + + +def target_centers(vial_pose, rack_pose, target_holes=None, object_offset=None, goal_offsets=None): + """Vial geometric center and the closest admissible opening's rim center.""" + object_center = vial_pose[:, :3] + quat_apply( + vial_pose[:, 3:], + vial_pose.new_tensor(object_offset or (0, 0, (VIAL_AXIS_MIN + VIAL_AXIS_MAX) / 2)).expand(len(vial_pose), -1), + ) + holes = vial_pose.new_tensor(RACK_HOLE_CENTERS).expand(len(vial_pose), -1, -1).clone() + holes[..., 2] = RACK_RIM_HEIGHT + if goal_offsets is not None: + holes[..., :2] += holes.new_tensor(goal_offsets) + holes[..., 2] += 0.0002 + world_holes = rack_pose[:, None, :3] + quat_apply(rack_pose[:, None, 3:].expand(-1, 4, -1), holes) + nearest = (world_holes[..., :2] - vial_pose[:, None, :2]).square().sum(-1).argmin(-1) + if target_holes is not None: + nearest = target_holes + return object_center, world_holes[torch.arange(len(vial_pose), device=vial_pose.device), nearest] + + +def camera_directions(points, position, rotation): + directions = quat_apply_inverse(rotation.expand(len(points), -1), points - position) + directions = directions * directions.new_tensor((1, -1, -1)) + return torch.nn.functional.normalize(directions, dim=-1) + + +def near_directions(direction, generator, variants=16): + """Sample a true spherical annulus, two to five degrees from the center.""" + direction = direction[:, None].expand(-1, variants, -1) + reference = direction.new_tensor((0, 1, 0)).expand_as(direction) + tangent = torch.nn.functional.normalize(torch.cross(direction, reference, dim=-1), dim=-1) + bitangent = torch.cross(direction, tangent, dim=-1) + theta = torch.empty(direction.shape[:2]).uniform_(math.radians(2), math.radians(5), generator=generator) + phi = torch.empty_like(theta).uniform_(0, 2 * math.pi, generator=generator) + return theta.cos()[..., None] * direction + theta.sin()[..., None] * ( + phi.cos()[..., None] * tangent + phi.sin()[..., None] * bitangent + ) + + +def build_reset_cache(dataset_path, camera_cfg, rack_pose, angle_limit, seed=42, numbered=False): + """Keep stock physical rows intact and add diverse absolute gaze targets.""" + artifact = load_reset_dataset(dataset_path) + states = artifact["states"] + if numbered: + from .goals import CAP_LABEL_POSITION, RACK_LABEL_OFFSETS, expand_numbered_resets + + states, _, _, _ = expand_numbered_resets(states, rack_pose) + vial = states["vial_pose"] + rack = torch.tensor(rack_pose, dtype=vial.dtype).expand(len(vial), -1) + centers = target_centers( + vial, + rack, + states.get("target_hole"), + CAP_LABEL_POSITION if numbered else None, + RACK_LABEL_OFFSETS if numbered else None, + ) + position, rotation = ( + vial.new_tensor(camera_cfg.offset.pos), + vial.new_tensor(camera_cfg.offset.rot), + ) + directions = [camera_directions(center, position, rotation) for center in centers] + generator = torch.Generator().manual_seed(seed) + variants = 16 + random = torch.empty(len(vial), variants, 2).uniform_(-angle_limit, angle_limit, generator=generator) + object_angles, goal_angles = [direction_to_angles(d)[:, None].expand(-1, variants, -1) for d in directions] + near_object, near_goal = [direction_to_angles(near_directions(d, generator, variants)) for d in directions] + gaze = torch.stack((random, object_angles, goal_angles, near_object, near_goal), dim=1) + model = CameraModel(**camera_cfg.camera_calibration) + _, valid = model.project(angles_to_direction(gaze)) + valid &= (gaze.abs() <= angle_limit).all(-1) + # Resample random entries against the physical frustum, never clip aligned targets. + for _ in range(100): + bad = ~valid[:, 0] + if not bad.any(): + break + gaze[:, 0][bad] = torch.empty(int(bad.sum()), 2).uniform_(-angle_limit, angle_limit, generator=generator) + _, valid[:, 0] = model.project(angles_to_direction(gaze[:, 0])) + if not valid.all(): + raise ValueError("Reset gaze targets exceed the physical camera frustum or gaze limits") + identity = dict( + version=1, + source_sha256=artifact["content_sha256"], + calibration=camera_cfg.camera_calibration, + position=camera_cfg.offset.pos, + rotation=camera_cfg.offset.rot, + rack_pose=rack_pose, + angle_limit=angle_limit, + seed=seed, + modes=RESET_MODES, + vision_action_units="absolute_tilt_pan_radians", + near_degrees=[2, 5], + goal_mode="numbered" if numbered else "nearest", + ) + return dict( + identity=identity, + identity_sha256=hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest(), + states=states, + vision_action=gaze, + object_direction=directions[0], + goal_direction=directions[1], + ) + + +class CachedGazeAction(GazeAction): + def __init__(self, cfg, env): + super().__init__(cfg, env) + self.reset_mode = torch.zeros(env.num_envs, dtype=torch.long, device=self.device) + self.reset_variant = torch.zeros_like(self.reset_mode) + self.source_rotation = self._target.new_tensor(self.camera.cfg.offset.rot) + self.cache = None + if env.cfg.mixed_gaze_resets and getattr(env.cfg, "retinal_geometry", "spherical") != "planar": + params = env.event_manager.get_term_cfg("reset_from_dataset").params + rack = env.cfg.scene.rack.init_state + cache = build_reset_cache( + params["dataset_path"], + self.camera.cfg, + (*rack.pos, *rack.rot), + cfg.angle_limit, + numbered=getattr(env.cfg, "goal_mode", "nearest") == "numbered", + ) + output = Path(env.cfg.log_dir or Path.home() / ".cache/isaaclab_fovi/so101") + output.mkdir(parents=True, exist_ok=True) + torch.save(cache, output / "gaze_reset_cache.pt") + self.cache = cache["vision_action"].to(self.device) + + def oracle(self, position): + state = getattr(self._env, "so101_camera_randomization", None) + direction = camera_directions( + position, self.camera.get_world_positions(), self.source_rotation if state is None else state.rotation + ) + if state is not None: + visible = state.visibility(direction) + direction = angles_to_direction(state.gaze_direction(direction)) + mount = torch.stack((direction[:, 0], direction[:, 2], -direction[:, 1]), -1) + return fixation_action_target( + mount, self._target, max_delta=self.cfg.max_delta, angle_limit=self.cfg.angle_limit, visible=visible + ) + return calibrated_oracle( + direction, + self._target, + self.calibration, + max_delta=self.cfg.max_delta, + angle_limit=self.cfg.angle_limit, + ) + + def fixation_error(self, position): + state = getattr(self._env, "so101_camera_randomization", None) + direction = camera_directions( + position, self.camera.get_world_positions(), self.source_rotation if state is None else state.rotation + ) + if state is not None: + direction = angles_to_direction(state.gaze_direction(direction)) + actual = angles_to_direction(self._target) + # atan2 remains accurate near perfect alignment, unlike acos(dot). + return torch.atan2( + torch.cross(actual, direction, dim=-1).norm(dim=-1), + (actual * direction).sum(-1), + ) + + def reset(self, env_ids=None): + super().reset(env_ids) + state = getattr(self._env, "so101_camera_randomization", None) + if state is not None and self._env.cfg.mixed_gaze_resets: + self._reset_randomized_camera(env_ids, state) + return + if self.cache is None or not hasattr(self._env, "_so101_reset_row"): + return + ids = slice(None) if env_ids is None else env_ids + rows = self._env._so101_reset_row[ids] + modes = torch.randint(5, rows.shape, device=self.device) + variants = torch.randint(self.cache.shape[2], rows.shape, device=self.device) + self._target[ids] = self.cache[rows, modes, variants] + self.reset_mode[ids], self.reset_variant[ids] = modes, variants + # The cache contains absolute gaze state. The last incremental action and + # velocity stay zero: reset is not a policy-generated camera movement. + self.camera.set_calibrated_angles(self._target) + + def _reset_randomized_camera(self, env_ids, state): + """Retain the cached mixture, deriving angles from the actual reset geometry.""" + from .goals import CAP_LABEL_POSITION, RACK_LABEL_OFFSETS + + env = self._env + ids = torch.arange(env.num_envs, device=self.device)[slice(None) if env_ids is None else env_ids] + if not len(ids) or not hasattr(env, "_so101_reset_vial_pose"): + return + vial = env._so101_reset_vial_pose[ids].clone() + rack = env._so101_reset_rack_pose[ids].clone() + vial[:, :3] += env.scene.env_origins[ids] + rack[:, :3] += env.scene.env_origins[ids] + obj, goal = target_centers(vial, rack, env.numbered_target_hole[ids], CAP_LABEL_POSITION, RACK_LABEL_OFFSETS) + position = state.position[ids] + env.scene.env_origins[ids] + modes = torch.randint(5, (len(ids),), device=self.device) + target = torch.where(((modes == 2) | (modes == 4))[:, None], goal, obj) + direction = camera_directions(target, position, state.rotation[ids]) + reference = direction.new_tensor((0, 1, 0)).expand_as(direction) + tangent = torch.nn.functional.normalize(torch.cross(direction, reference, dim=-1), dim=-1) + bitangent = torch.cross(direction, tangent, dim=-1) + theta = torch.empty(len(ids), 1, device=self.device).uniform_(math.radians(2), math.radians(5)) + phi = torch.rand_like(theta) * (2 * math.pi) + nearby = theta.cos() * direction + theta.sin() * (phi.cos() * tangent + phi.sin() * bitangent) + direction = torch.where((modes >= 3)[:, None], nearby, direction) + aligned = state.gaze_direction(direction, ids) + random = torch.empty_like(aligned).uniform_(-self.cfg.angle_limit, self.cfg.angle_limit) + from .camera_geometry import lens_visibility + + visible = lens_visibility(direction[:, None], state.intrinsics[ids], state.radial[ids], (640, 640)).squeeze(-1) + valid = visible & (aligned.abs() <= self.cfg.angle_limit).all(-1) + modes = torch.where(valid, modes, 0) + # Random starts are bounded by the real source sensor too; a neutral + # fallback prevents out-of-frame initialization at perturbed lens edges. + _, random_valid = self.calibration.project(angles_to_direction(random)) + random = torch.where(random_valid[:, None], random, 0) + self._target[ids] = torch.where((modes == 0)[:, None], random, aligned) + self.reset_mode[ids], self.reset_variant[ids] = modes, 0 + self.camera.set_calibrated_angles(self._target) + + +@configclass +class CachedGazeActionCfg(GazeActionCfg): + class_type: type = CachedGazeAction diff --git a/src/isaaclab_tutorial/active_gaze/goals.py b/src/isaaclab_tutorial/active_gaze/goals.py new file mode 100644 index 0000000..c4e61d6 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/goals.py @@ -0,0 +1,380 @@ +"""Numbered vial goals, target-aware stock rewards, and expanded reset bins.""" + +from copy import deepcopy +from dataclasses import fields +from pathlib import Path + +import numpy as np +import torch +from isaaclab.managers import ObservationTermCfg +from isaaclab.sim import MultiAssetSpawnerCfg +from isaaclab.sim.utils import clone +from isaaclab.utils import configclass +from isaaclab.utils.math import quat_apply + +from isaaclab_tutorial.tasks.place_vial.mdp.events import ( + ResetFromDataset, + phase_balanced_row_weights, +) +from isaaclab_tutorial.tasks.place_vial.mdp.geometry import ( + RACK_HOLE_CENTERS, + hole_relative_positions, + symmetric_axial_keypoint_error, +) +from isaaclab_tutorial.tasks.place_vial.mdp.progress import placement_progress +from isaaclab_tutorial.tasks.place_vial.mdp.rewards import HELD_INSERTION_TARGET +from isaaclab_tutorial.tasks.place_vial.mdp.task import ( + RACK_RIM_HEIGHT, + VIAL_AXIS_MAX, + VIAL_AXIS_MIN, + vial_in_rack, + vial_upright, +) +from isaaclab_tutorial.tasks.place_vial.mdp.terminations import placement_success +from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import ( + VialSpawnCfg, + spawn_usd_with_contact_material, +) + +from .sampling import PHASE_NAMES + +NEAR_GOAL_DISTANCE = 0.045 +CAP_LABEL_POSITION = (0.0, 0.0, 0.1002) +CAP_LABEL_SIZE = 0.022 +RACK_LABEL_SIZE = 0.013 +RACK_LABEL_OFFSETS = ((-0.023, -0.023), (0.023, -0.023), (0.023, 0.023), (-0.023, 0.023)) + + +def _attach_label(stage, path, asset_path, position, size, rotation=0.0): + from pxr import UsdGeom + + label = UsdGeom.Xform.Define(stage, path) + label.GetPrim().GetReferences().AddReference(str(asset_path)) + label.AddTranslateOp().Set(position) + label.AddRotateZOp().Set(rotation) + label.AddScaleOp().Set((size, size, size)) + + +@clone +def spawn_numbered(prim_path, cfg, translation=None, orientation=None, **kwargs): + """Add render-only decals; preserve every stock collision and contact parameter.""" + prim = spawn_usd_with_contact_material(prim_path, cfg, translation=translation, orientation=orientation, **kwargs) + if cfg.numbered_kind == "vial": + from pxr import Sdf + + prim.CreateAttribute("isaaclab_fovi:vialNumber", Sdf.ValueTypeNames.Int).Set(cfg.vial_number) + _attach_label( + prim.GetStage(), + f"{prim_path}/Number", + Path(cfg.number_label_assets) / f"number_{cfg.vial_number}.usda", + CAP_LABEL_POSITION, + CAP_LABEL_SIZE, + 90.0, + ) + else: + for i, (center, offset) in enumerate(zip(RACK_HOLE_CENTERS, RACK_LABEL_OFFSETS, strict=True)): + _attach_label( + prim.GetStage(), + f"{prim_path}/Number{i}", + Path(cfg.number_label_assets) / f"number_{i + 1}.usda", + (center[0] + offset[0], center[1] + offset[1], RACK_RIM_HEIGHT + 0.0002), + RACK_LABEL_SIZE, + 90.0, + ) + return prim + + +@configclass +class NumberedSpawnCfg(VialSpawnCfg): + func = spawn_numbered + numbered_kind: str = "vial" + number_label_assets: str = "" + vial_number: int = 1 + + +def balanced_shuffled_clones(weights, num_clones): + """Keep equal variant counts, shuffled by Isaac Lab's seeded NumPy RNG.""" + from isaaclab.cloner.cloner_strategies import sequential + + layout = np.random.permutation(sequential(weights, num_clones)) + # OVRTX's camera source contract expects the first prototype at env_0. + # Pin one representative there; all remaining assignments stay shuffled. + first = int(np.flatnonzero(layout == layout.min())[0]) + layout[0], layout[first] = layout[first], layout[0] + return layout + + +def scene_vial_numbers(env): + """Read immutable cap identities from the actual native clone plan.""" + from isaaclab.cloner import path as cloner_path + + plan = env.scene.clone_plan + topology = plan.topology + paths = cloner_path.get_asset_prototype_paths(plan) + numbers = {} + for world in np.unique(topology.world_prototype_layout): + start, end = topology.world_prototype_starts[world + 1 : world + 3] + candidates = [] + for asset in topology.world_prototypes[start:end]: + prim = env.scene.stage.GetPrimAtPath(paths[asset]) + number = prim.GetAttribute("isaaclab_fovi:vialNumber").Get() + if number is not None: + candidates.append(number) + if len(candidates) != 1 or candidates[0] not in (1, 2, 3, 4): + raise ValueError(f"Expected one numbered vial in world prototype {world}: {candidates}") + numbers[world] = candidates[0] + return torch.tensor( + [numbers[world] for world in topology.world_prototype_layout], + device=env.device, + dtype=torch.long, + ) + + +def configure_numbered_scene(cfg): + """Clone four prebuilt cap variants with unchanged stock physical properties.""" + for name in ("vial", "rack"): + asset = getattr(cfg.scene, name) + asset.spawn = NumberedSpawnCfg( + **{ + field.name: deepcopy(getattr(asset.spawn, field.name)) + for field in fields(asset.spawn) + if field.init and field.name != "func" + }, + numbered_kind=name, + number_label_assets=cfg.number_label_assets, + ) + original = cfg.scene.vial.spawn + variants = [] + for number in range(1, 5): + variant = original.copy() + variant.vial_number = number + variants.append(variant) + cfg.scene.vial.spawn = MultiAssetSpawnerCfg( + assets_cfg=variants, activate_contact_sensors=original.activate_contact_sensors + ) + cfg.scene.clone_cfg.clone_strategy = balanced_shuffled_clones + cfg.events.reset_from_dataset.func = NumberedResetFromDataset + cfg.terminations.success.func = TargetPlacementSuccess + cfg.rewards.held_goal.func = held_target_goal + cfg.observations.critic.placement.func = target_placement_features + cfg.observations.critic.numbered_goal = ObservationTermCfg(func=critic_goal_state) + + +def expand_numbered_resets(states, rack_pose): + """Cross every physical row with every target; split geometrically nearby starts. + + Each original phase retains its base probability mass, with uniform physical + rows and target numbers before SGS adapts the far/target/non-target bins. + Physical joint targets and vial poses remain byte-for-byte stock states. + """ + from isaaclab_tutorial.tasks.place_vial.mdp.geometry import rack_local_position + + expanded = {k: v.repeat_interleave(4, dim=0) for k, v in states.items()} + target = torch.arange(4, device=states["phase"].device).repeat(len(states["phase"])) + rack = expanded["vial_pose"].new_tensor(rack_pose).expand(len(target), -1) + local = rack_local_position(expanded["vial_pose"][:, :3], rack[:, :3], rack[:, 3:]) + distance, nearest = hole_relative_positions(local)[..., :2].norm(dim=-1).min(-1) + near = distance <= NEAR_GOAL_DISTANCE + names, bin_phases, bins = [], [], torch.empty_like(target) + for phase, name in enumerate(PHASE_NAMES): + masks = ( + (name, ~near), + (f"{name}_target", near & (target == nearest)), + (f"{name}_non_target", near & (target != nearest)), + ) + for label, mask in masks: + mask = mask & (expanded["phase"] == phase) + if mask.any(): + bins[mask] = len(names) + names.append(label) + bin_phases.append(phase) + expanded["target_hole"] = target + # A released vial in the wrong opening needs a fresh pickup before goal fixation. + regrasp = (expanded["phase"] == 7) & (target != nearest) + expanded["grasped"] = expanded["grasped"] & ~regrasp + return expanded, bins, tuple(names), torch.tensor(bin_phases, device=target.device) + + +def conditional_row_probabilities(row_weights, target_fractions): + """Actual row probabilities under fixed cap assignments and conditional SGS.""" + weights = row_weights.reshape(-1, 4) + return (weights / weights.sum(0).clamp_min(1e-30) * target_fractions).flatten() + + +def sample_matching_rows(row_weights, targets): + """Sample a physical row for each fixed cap; expanded row order is row x cap.""" + weights = row_weights.reshape(-1, 4).T.contiguous() + if (weights.sum(-1)[targets] <= 0).any(): + raise ValueError("No enabled reset rows for an assigned cap number") + # Absent cap groups can have zero mass in targeted diagnostic sampling. + weights = torch.where(weights.sum(-1, keepdim=True) > 0, weights, torch.ones_like(weights)) + draws = torch.multinomial(weights, len(targets), replacement=True) + physical = draws[targets, torch.arange(len(targets), device=targets.device)] + return 4 * physical + targets + + +class NumberedResetFromDataset(ResetFromDataset): + def __init__(self, cfg, env): + super().__init__(cfg, env) + rack = env.cfg.scene.rack.init_state + self.states, self.bin_ids, self.bin_names, phases = expand_numbered_resets(self.states, (*rack.pos, *rack.rot)) + self.bin_phase_ids = phases + self.row_weights = phase_balanced_row_weights(self.states["phase"], cfg.params["phase_weights"]) + self.sequential_rows = self.row_weights.nonzero().flatten() + self.cursor = 0 + env.vial_number = scene_vial_numbers(env) + env.numbered_target_hole = env.vial_number - 1 + env.hole_numbers = torch.arange(1, 5, device=env.device).expand(env.num_envs, -1).clone() + self.target_fractions = torch.bincount(env.numbered_target_hole, minlength=4) / env.num_envs + + def sampling_row_probabilities(self): + return conditional_row_probabilities(self.row_weights, self.target_fractions) + + def __call__( + self, + env, + env_ids, + dataset_path, + phase_weights, + sequential=False, + home_position_noise=0.0, + home_heading_noise=0.0, + home_rack_clearance=0.0, + home_rack_position_noise=0.0, + home_rack_yaw_noise=0.0, + support_height_range=(0.0, 0.0), + ): + ids = torch.arange(env.num_envs, device=env.device)[slice(None) if env_ids is None else env_ids] + if not len(ids): + return + targets = env.numbered_target_hole[ids] + saved_rows, saved_cursor = self.sequential_rows, self.cursor + if sequential: + rows = torch.empty_like(ids) + for target in targets.unique(): + available = saved_rows[self.states["target_hole"][saved_rows] == target] + if not len(available): + raise ValueError(f"No sequential reset rows for cap {int(target) + 1}") + mask = targets == target + ranks = torch.arange(int(mask.sum()), device=env.device) + saved_cursor + rows[mask] = available[ranks % len(available)] + else: + rows = sample_matching_rows(self.row_weights, targets) + # Delegate all physical restoration to the stock task via its explicit-row path. + self.sequential_rows, self.cursor = rows, 0 + try: + self._restore_rows( + env, + ids, + dataset_path, + phase_weights, + home_position_noise, + home_heading_noise, + home_rack_clearance, + home_rack_position_noise, + home_rack_yaw_noise, + support_height_range, + ) + finally: + self.sequential_rows = saved_rows + self.cursor = saved_cursor + len(ids) if sequential else saved_cursor + + def _restore_rows( + self, + env, + ids, + dataset_path, + phase_weights, + home_position_noise, + home_heading_noise, + home_rack_clearance, + home_rack_position_noise, + home_rack_yaw_noise, + support_height_range, + ): + super().__call__( + env, + ids, + dataset_path, + phase_weights, + True, + home_position_noise, + home_heading_noise, + home_rack_clearance, + home_rack_position_noise, + home_rack_yaw_noise, + support_height_range, + ) + + +def target_relative_position(env): + position, axis, lowest = vial_in_rack(env) + center = position.new_tensor(RACK_HOLE_CENTERS)[env.numbered_target_hole] + return position - center, axis, lowest + + +def selected_goal_center(env, label=False): + rack = env.scene["rack"].data + local = rack.root_pos_w.torch.new_tensor(RACK_HOLE_CENTERS)[env.numbered_target_hole].clone() + local[:, 2] = RACK_RIM_HEIGHT + if label: + local[:, :2] += local.new_tensor(RACK_LABEL_OFFSETS)[env.numbered_target_hole] + local[:, 2] += 0.0002 + return rack.root_pos_w.torch + quat_apply(rack.root_quat_w.torch, local) + + +def target_placement_features(env): + position, _, lowest = target_relative_position(env) + speed = env.scene["vial"].data.root_lin_vel_w.torch.norm(dim=-1) + return torch.stack((position[:, :2].norm(dim=-1), lowest, vial_upright(env), speed), dim=-1) + + +def critic_goal_state(env): + """Privileged target position and identity, excluded from actor groups.""" + local = env.scene["vial"].data.root_pos_w.torch.new_tensor(RACK_HOLE_CENTERS)[env.numbered_target_hole] + number = torch.nn.functional.one_hot(env.vial_number - 1, 4) + return torch.cat((local, number), dim=-1).float() + + +def held_target_goal(env, std=0.10): + position, axis, _ = target_relative_position(env) + error = symmetric_axial_keypoint_error( + position, + axis, + position.new_tensor(HELD_INSERTION_TARGET), + position.new_tensor((0, 0, 1)), + VIAL_AXIS_MIN, + VIAL_AXIS_MAX, + ) + progress = placement_progress(env) + return torch.where(progress.grasped & ~progress.inserted, torch.exp(-error / std), 0.0) + + +class TargetPlacementSuccess(placement_success): + """Retain stock contact/stability logic, accepting only the selected opening. + + Stock success boxes and insertion cylinders are disjoint across openings. + Outside the target opening's nearest-hole region, roll back only insertion + and success updates; grasp/lift, contacts, and safety bookkeeping stay stock. + """ + + def __call__(self, env): + position, _, _ = vial_in_rack(env) + nearest = hole_relative_positions(position)[..., :2].square().sum(-1).argmin(-1) + wrong = nearest != env.numbered_target_hole + inserted, success, time = ( + v.clone() for v in (self.progress.inserted, self.progress.success, self.progress.time_to_success) + ) + super().__call__(env) + self.progress.inserted[wrong] = inserted[wrong] + self.progress.success[wrong] = success[wrong] + self.progress.time_to_success[wrong] = time[wrong] + self.progress.stable_count[wrong] = 0 + success = self.progress.success.clone() + log = env.extras.setdefault("log", {}) + log["Metrics/insertion_rate"] = self.progress.inserted.float().mean() + log["Metrics/success_rate"] = success.float().mean() + env._so101_terminal_progress[:, 2] = self.progress.inserted + env._so101_terminal_time_to_success_s = self.progress.time_to_success.float() * env.step_dt + env._so101_terminal_hole = torch.where(success, env.numbered_target_hole, -1) + return success diff --git a/src/isaaclab_tutorial/active_gaze/language.py b/src/isaaclab_tutorial/active_gaze/language.py new file mode 100644 index 0000000..ad0a876 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/language.py @@ -0,0 +1,9 @@ +"""The same instruction is used for every cap and every SO-101 reset.""" + +INSTRUCTIONS = ("Place the vial in the slot with the matching number",) + + +def instruction_index(env): + import torch + + return torch.zeros(env.num_envs, 1, device=env.device, dtype=torch.long) diff --git a/src/isaaclab_tutorial/active_gaze/learning/__init__.py b/src/isaaclab_tutorial/active_gaze/learning/__init__.py new file mode 100644 index 0000000..d59079b --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/__init__.py @@ -0,0 +1 @@ +"""Optional perception and RSL-RL components for the standalone examples.""" diff --git a/src/isaaclab_tutorial/active_gaze/learning/chunks.py b/src/isaaclab_tutorial/active_gaze/learning/chunks.py new file mode 100644 index 0000000..5812d84 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/chunks.py @@ -0,0 +1,143 @@ +"""Chunk-level policy transitions over native Isaac Lab control steps.""" + +import torch +from rsl_rl.env import VecEnv +from tensordict import TensorDict + +from .distributions import clipped_gaussian_statistics + + +def chunk_gaussian_statistics(mean, std, actions, valid, *, clipped=False): + """Marginalize unexecuted action suffixes from joint likelihood and entropy.""" + shape = (*valid.shape, -1) + # Replace discarded suffixes before evaluating densities (including infinities). + mask = valid[..., None].expand(shape[:-1] + (mean.shape[-1] // valid.shape[-1],)).reshape_as(mean) + mean = torch.where(mask, mean.float(), 0.0) + std = torch.where(mask, std.float(), 1.0) + actions = torch.where(mask, actions.float(), 0.0) + if clipped: + log_prob, entropy = clipped_gaussian_statistics(mean, std, actions) + else: + distribution = torch.distributions.Normal(mean, std, validate_args=False) + log_prob, entropy = distribution.log_prob(actions), distribution.entropy() + log_prob = log_prob.reshape(shape).sum(-1) + entropy = entropy.reshape(shape).sum(-1) + return torch.where(valid, log_prob, 0.0).sum(-1), torch.where(valid, entropy, 0.0).sum(-1) + + +class ActionChunkWrapper(VecEnv): + """Execute an open-loop action plan; refresh RGB/DINO only at its boundary. + + Native control stepping, rewards, proprioceptive history and autoresets remain + live. Once a row terminates, discard its remaining plan and use the task's + idle actions (zero deltas and held absolute joints) until the next decision. + Its reset state can settle during these idle steps. Idle rewards and actions + never enter the completed transition. Timeout values use the final state, + before autoreset, discounted by the actual executed prefix length. + """ + + def __init__(self, env, chunk_size: int, control_gamma: float, *, critic_groups: list[str]): + if type(chunk_size) is not int or chunk_size < 1 or not 0 < control_gamma <= 1: + raise ValueError("Expected a positive chunk size and discount in (0, 1].") + if not critic_groups: + raise ValueError("Chunking requires the critic observation group names") + self.env = env + self.chunk_size = chunk_size + self.control_gamma = control_gamma + self.control_action_dim = env.num_actions + self.num_actions = env.num_actions * chunk_size + self.num_envs, self.device = env.num_envs, env.device + self.max_episode_length = env.max_episode_length + self._obs = env.get_observations() + self.critic_groups = tuple(critic_groups) + self.unwrapped.cfg.compute_final_obs = True + + def __getattr__(self, name): + return getattr(self.env, name) + + @property + def episode_length_buf(self): + return self.env.episode_length_buf + + @episode_length_buf.setter + def episode_length_buf(self, value): + self.env.episode_length_buf = value + + @property + def decision_dt(self): + return self.unwrapped.step_dt * self.chunk_size + + def _decorate(self, obs): + obs = obs.clone(recurse=False) + obs["chunk_oracle"] = torch.zeros(self.num_envs, self.chunk_size, 3, device=self.device) + obs["chunk_valid"] = torch.ones(self.num_envs, self.chunk_size, device=self.device, dtype=torch.bool) + return obs + + def get_observations(self): + return self._decorate(self._obs) + + def reset(self): + self._obs, extras = self.env.reset() + return self.get_observations(), extras + + def step(self, actions, *, control_steps=None, render_every_step=False, observer=None): + """Execute a plan, optionally observing each control step during evaluation. + + Extra renders never add policy decisions or DINO evaluations. A shorter + final plan lets evaluation stop at its exact control-step duration. + """ + steps = self.chunk_size if control_steps is None else control_steps + if not 1 <= steps <= self.chunk_size: + raise ValueError("control_steps must be between one and the chunk size") + plan = actions.reshape(self.num_envs, self.chunk_size, self.control_action_dim) + active = torch.ones(self.num_envs, device=self.device, dtype=torch.bool) + rewards = torch.zeros(self.num_envs, device=self.device) + timeout_discount = torch.zeros_like(rewards) + timeout_obs = TensorDict( + {key: torch.zeros_like(self._obs[key]) for key in self.critic_groups}, + batch_size=[self.num_envs], + ) + labels, valid = [], [] + rendering = self.unwrapped.render_enabled + try: + for index in range(steps): + valid.append(active.clone()) + label = self._obs.get("oracle") + label = torch.zeros(self.num_envs, 3, device=self.device) if label is None else label.clone() + label[:, 2] *= active + labels.append(label) + refresh = index == steps - 1 + self.unwrapped.refresh_policy_vision = refresh + self.unwrapped.render_enabled = render_every_step or (rendering and refresh) + idle = self.unwrapped.idle_actions() if hasattr(self.unwrapped, "idle_actions") else 0.0 + action = torch.where(active[:, None], plan[:, index], idle) + self._obs, reward, done, extras = self.env.step(action) + if observer is not None: + observer(self._obs, reward, done, extras) + rewards += self.control_gamma**index * torch.where(active, reward, 0.0) + timed_out = active & extras.get("time_outs", torch.zeros_like(active)).bool() + # A true terminal event takes precedence over an overlapping time limit. + terminated = getattr(self.unwrapped, "reset_terminated", torch.zeros_like(active)) + timed_out &= ~terminated + timeout_discount += timed_out * self.control_gamma ** (index + 1) + if "final_obs" in extras: + for key in timeout_obs.keys(): + mask = timed_out.reshape(-1, *([1] * (timeout_obs[key].ndim - 1))) + timeout_obs[key] = torch.where(mask, extras["final_obs"][key], timeout_obs[key]) + active &= ~done.bool() + finally: + self.unwrapped.refresh_policy_vision = True + self.unwrapped.render_enabled = rendering + extras = dict(extras) + extras.pop("time_outs", None) + extras.pop("final_obs", None) + extras.update( + chunk_valid=torch.stack(valid, dim=1), + chunk_oracle=torch.stack(labels, dim=1), + chunk_timeout_discount=timeout_discount, + chunk_timeout_observations=timeout_obs, + ) + return self.get_observations(), rewards, (~active).long(), extras + + def close(self): + return self.env.close() diff --git a/src/isaaclab_tutorial/active_gaze/learning/config.py b/src/isaaclab_tutorial/active_gaze/learning/config.py new file mode 100644 index 0000000..1b3157a --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/config.py @@ -0,0 +1,25 @@ +"""Configuration for language-conditioned visual actors.""" + +from isaaclab.utils import configclass +from isaaclab_rl.rsl_rl import RslRlMLPModelCfg + + +@configclass +class LanguageVisionActorCfg(RslRlMLPModelCfg): + class_name: str = "isaaclab_tutorial.active_gaze.learning.models:LanguageVisionActor" + hidden_dims: list = [512, 256, 128] + activation: str = "elu" + obs_normalization: bool = True + distribution_cfg = RslRlMLPModelCfg.GaussianDistributionCfg( + class_name="isaaclab_tutorial.active_gaze.learning.distributions:ClippedGaussianDistribution", + init_std=0.5, + std_type="log", + ) + instructions: tuple = () + instruction_table_path: str | None = None + language_device: str = "cpu" + fusion_dim: int = 128 + fusion_width: int = 256 + fusion_heads: int = 4 + fusion_blocks: int = 2 + spatial_channels: int = 4 diff --git a/src/isaaclab_tutorial/active_gaze/learning/dino.py b/src/isaaclab_tutorial/active_gaze/learning/dino.py new file mode 100644 index 0000000..47f8724 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/dino.py @@ -0,0 +1,109 @@ +"""Frozen omni-foveated DINOv3 with the checkpoint's trained patch geometry.""" + +import json + +import torch +from torch import nn + +DEFAULT_CHECKPOINT = "wandb://nvidia/knnconv/5mgxp8y3#final_weights.pth" +DEFAULT_MD5 = "jsCUwCzwnDd1RRBPk8OVhQ==" + + +def load_backbone(reference: str, checksum: str | None) -> nn.Module: + """Restore Fovi weights, including trained parametrizations, then fold LoRA.""" + from fovi.models import resolve_model_path + from fovi.models.dinov3 import build_fovi_dinov3 + from fovi.models.loading import load_config + from omegaconf import open_dict + from torch.nn.utils import parametrize + + remote = reference.startswith("wandb:") + path = resolve_model_path(reference, expected_checkpoint_md5=checksum if remote else None) + if not path.is_dir(): + raise ValueError("Pass a Fovi model bundle directory, including its configuration and source.json.") + if not remote and checksum is not None: + # Fovi reserializes downloaded weights, so their file hash differs from + # W&B's original. Preserve the bundle's original source identity and sizes, + # following Fovi's cached-bundle validation contract. + source = json.loads((path / "source.json").read_text()) + if ( + source["md5"] != checksum + or source["state_dict_size"] != (path / "state_dict.pth").stat().st_size + or source["config_size"] != (path / "resolved_config.yaml").stat().st_size + ): + raise ValueError(f"DINO bundle provenance or size mismatch: {path}") + cfg, packed, key = load_config(path.name, True, path.parent, device="cpu") + if cfg.model.arch != "fovi_dinov3" or cfg.saccades.mode != "warped_cartesian_as_grid": + raise ValueError("Expected a Fovi DINOv3 warped_cartesian_as_grid checkpoint.") + if ( + cfg.saccades.resize_size != 128 + or cfg.model.vit.patch_size != 16 + or cfg.saccades.get("radius_norm", 2.0) != 2.0 + or cfg.model.vit.position_coordinate_space != "cortical" + ): + raise ValueError("This example requires the 128px, patch16, circular cortical checkpoint.") + with open_dict(cfg): + cfg.model.output_mode = "patch_tokens" + # The complete fine-tuned state below replaces every base-model weight. + # Only the base architecture/processor configuration is needed here. + cfg.pretrained_model.load_weights = False + if (path / "base_model").is_dir(): + cfg.pretrained_model.path = str(path / "base_model") + backbone = build_fovi_dinov3(cfg, device="cpu") + prefix = "network.backbone." + state = { + name.removeprefix("module.").removeprefix(prefix): value + for name, value in packed[key].items() + if name.removeprefix("module.").startswith(prefix) + } + # Transformers moved encoder layers under model in newer releases. + nested = any(name.startswith("model.layer.") for name in backbone.state_dict()) + state = { + ( + ("model." + name) + if nested and name.startswith("layer.") + else name.removeprefix("model.") + if not nested and name.startswith("model.layer.") + else name + ): value + for name, value in state.items() + } + backbone.load_state_dict(state, strict=True) + for child in backbone.modules(): + if parametrize.is_parametrized(child): + for name in tuple(child.parametrizations): + parametrize.remove_parametrizations(child, name, leave_parametrized=True) + return backbone.requires_grad_(False).eval() + + +class FrozenDino(nn.Module): + """Encode upright uint8 BHWC retinal images into unpooled patch tokens.""" + + def __init__( + self, + reference: str = DEFAULT_CHECKPOINT, + checksum: str | None = DEFAULT_MD5, + batch_size: int = 128, + ): + super().__init__() + if batch_size <= 0: + raise ValueError("DINO batch size must be positive.") + self.backbone = load_backbone(reference, checksum) + self.batch_size = batch_size + self.register_buffer("mean", torch.tensor((0.485, 0.456, 0.406))[None, :, None, None]) + self.register_buffer("std", torch.tensor((0.229, 0.224, 0.225))[None, :, None, None]) + + def train(self, mode: bool = True): + return super().train(False) + + @torch.no_grad() + def forward(self, images: torch.Tensor) -> torch.Tensor: + if images.dtype != torch.uint8 or images.shape[1:] != (128, 128, 3): + raise ValueError("DINO expects upright uint8 RGB images of shape (B,128,128,3).") + outputs = [] + for chunk in images.split(self.batch_size): + pixels = (chunk.permute(0, 3, 1, 2).float() / 255 - self.mean) / self.std + with torch.autocast(images.device.type, dtype=torch.bfloat16, enabled=images.device.type == "cuda"): + tokens = self.backbone(pixel_values=pixels) + outputs.append(tokens.float()) + return torch.cat(outputs) diff --git a/src/isaaclab_tutorial/active_gaze/learning/distributions.py b/src/isaaclab_tutorial/active_gaze/learning/distributions.py new file mode 100644 index 0000000..a58f7c5 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/distributions.py @@ -0,0 +1,72 @@ +"""The pushforward of a Gaussian through the normalized action clamp.""" + +import math + +import torch +from rsl_rl.modules.distribution import GaussianDistribution +from torch import nn + + +def _log_cdf(value): + # erfcx avoids cancellation in the log-CDF gradient deep in the left tail. + negative = value.clamp_max(0) + left = math.log(0.5) + torch.special.erfcx(-negative / math.sqrt(2)).log() - negative.square() / 2 + right = torch.log1p(-0.5 * torch.erfc(value.clamp_min(0) / math.sqrt(2))) + return torch.where(value < 0, left, right) + + +def clipped_gaussian_statistics(mean, std, actions): + """Elementwise log likelihood and mixed entropy on [-1, 1]. + + Boundary atoms use counting measure; the interior uses Lebesgue measure in + normalized action units. All latent tail samples have the same boundary + likelihood. Entropy is bounded above by log(4), and tends to log(2) as a + centered Gaussian spreads without bound. This is neither a truncated + Gaussian nor the differential entropy of the latent Gaussian. + """ + dtype = torch.float64 if mean.dtype == torch.float64 else torch.float32 + mean, std, actions = mean.to(dtype), std.to(dtype), actions.to(dtype) + lower, upper = (-1 - mean) / std, (1 - mean) / std + log_left, log_right = _log_cdf(lower), _log_cdf(-upper) + interior_log_prob = -0.5 * ((actions - mean) / std).square() - std.log() - 0.5 * math.log(2 * math.pi) + log_prob = torch.where(actions <= -1, log_left, torch.where(actions >= 1, log_right, interior_log_prob)) + log_prob = torch.where(actions.abs() > 1, -torch.inf, log_prob) + interior_mass = 0.5 * (torch.erf(upper / math.sqrt(2)) - torch.erf(lower / math.sqrt(2))) + edge_moment = (lower * torch.exp(-0.5 * lower.square()) - upper * torch.exp(-0.5 * upper.square())) / math.sqrt( + 2 * math.pi + ) + entropy = ( + -log_left.exp() * log_left + - log_right.exp() * log_right + + interior_mass * (std.log() + 0.5 * math.log(2 * math.pi) + 0.5) + + 0.5 * edge_moment + ) + return log_prob, entropy + + +class ClippedGaussianDistribution(GaussianDistribution): + """Gaussian parameters, but samples and likelihoods describe executed commands. + + ``mean``, ``std`` and ``params`` retain the latent Gaussian parameters for + gaze supervision and checkpoint compatibility. Deterministic playback uses + the clipped latent mean, matching the existing robot action adapter. + """ + + def sample(self): + return super().sample().clamp(-1, 1) + + def deterministic_output(self, mlp_output): + return mlp_output.clamp(-1, 1) + + def log_prob(self, outputs): + return clipped_gaussian_statistics(self.mean, self.std, outputs)[0].sum(-1) + + @property + def entropy(self): + return clipped_gaussian_statistics(self.mean, self.std, self.mean.clamp(-1, 1))[1].sum(-1) + + def kl_divergence(self, old_params, new_params): + raise NotImplementedError("Clipped Gaussian PPO requires the fixed learning-rate schedule") + + def as_deterministic_output_module(self): + return nn.Hardtanh(-1, 1) diff --git a/src/isaaclab_tutorial/active_gaze/learning/fusion.py b/src/isaaclab_tutorial/active_gaze/learning/fusion.py new file mode 100644 index 0000000..6fae1d5 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/fusion.py @@ -0,0 +1,103 @@ +"""Trainable language/vision attention with CLS and spatial readout.""" + +import torch +from torch import nn +from torch.nn import functional as F + + +class FusionLayer(nn.Module): + """Pre-normalized attention followed by a residual feedforward layer.""" + + def __init__(self, width: int, heads: int): + super().__init__() + self.heads = heads + self.norm1 = nn.LayerNorm(width) + self.qkv = nn.Linear(width, 3 * width) + self.projection = nn.Linear(width, width) + self.norm2 = nn.LayerNorm(width) + self.mlp = nn.Sequential(nn.Linear(width, 4 * width), nn.GELU(), nn.Linear(4 * width, width)) + + def forward(self, tokens: torch.Tensor, allowed: torch.Tensor) -> torch.Tensor: + batch, count, width = tokens.shape + qkv = self.qkv(self.norm1(tokens)).reshape(batch, count, 3, self.heads, width // self.heads) + query, key, value = qkv.permute(2, 0, 3, 1, 4).unbind(0) + value = F.scaled_dot_product_attention(query, key, value, attn_mask=allowed) + tokens = tokens + self.projection(value.transpose(1, 2).reshape(batch, count, width)) + return tokens + self.mlp(self.norm2(tokens)) + + +class LanguageVisionFusion(nn.Module): + """Monocular CoRL fusion preserving CLS and the ordered spatial token readout. + + Visual queries attend to language and CLS, while language and CLS attend to + all valid keys. Spatial tokens are projected independently before flattening, + preserving their grid positions. Neither text projections nor fusion outputs + are cached: both are trainable during every PPO minibatch. + """ + + def __init__( + self, + vision_dim: int, + language_dim: int, + vision_tokens: int, + language_tokens: int, + width: int = 256, + heads: int = 4, + blocks: int = 2, + spatial_channels: int = 4, + output_dim: int = 128, + ): + super().__init__() + if ( + min( + vision_dim, + language_dim, + vision_tokens, + language_tokens, + width, + heads, + blocks, + spatial_channels, + output_dim, + ) + <= 0 + or width % heads + ): + raise ValueError("Fusion dimensions must be positive and width divisible by heads.") + self.vision_tokens = vision_tokens + self.vision_projection = nn.Linear(vision_dim, width) + self.text_projection = nn.Linear(language_dim, width) + self.position_embedding = nn.Parameter(torch.empty(vision_tokens, width)) + nn.init.normal_(self.position_embedding) + self.cls = nn.Parameter(torch.zeros(1, 1, width)) + self.blocks = nn.ModuleList(FusionLayer(width, heads) for _ in range(blocks)) + self.norm = nn.LayerNorm(width) + allowed = torch.ones( + 1 + vision_tokens + language_tokens, + 1 + vision_tokens + language_tokens, + dtype=torch.bool, + ) + allowed[1 : 1 + vision_tokens, 1 : 1 + vision_tokens] = False + self.register_buffer("allowed", allowed) + self.spatial_projection = nn.Linear(width, spatial_channels) + self.readout = nn.Sequential(nn.Linear(width + vision_tokens * spatial_channels, output_dim), nn.GELU()) + + def forward(self, vision: torch.Tensor, language: torch.Tensor, padding: torch.Tensor) -> torch.Tensor: + visual = self.vision_projection(vision.float()) + self.position_embedding + if not torch.is_autocast_enabled(language.device.type): + language = language.to(self.text_projection.weight.dtype) + text = self.text_projection(language) + tokens = torch.cat((self.cls.expand(len(vision), -1, -1), visual, text), dim=1) + valid = torch.cat( + ( + torch.ones(len(vision), 1 + self.vision_tokens, device=vision.device, dtype=torch.bool), + ~padding.bool(), + ), + dim=1, + ) + allowed = self.allowed[None, None] & valid[:, None, None, :] + for block in self.blocks: + tokens = block(tokens, allowed) + tokens = self.norm(tokens) + spatial = self.spatial_projection(tokens[:, 1 : 1 + self.vision_tokens]).flatten(1) + return self.readout(torch.cat((tokens[:, 0], spatial), dim=-1)) diff --git a/src/isaaclab_tutorial/active_gaze/learning/language.py b/src/isaaclab_tutorial/active_gaze/learning/language.py new file mode 100644 index 0000000..b5aadc7 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/language.py @@ -0,0 +1,157 @@ +"""Frozen Cosmos3-Edge instruction tokens for visual policies.""" + +import hashlib +import json +import os +import tempfile +from pathlib import Path + +import torch +from filelock import FileLock + +COSMOS_MODEL = "nvidia/Cosmos3-Edge" +COSMOS_REVISION = "6f58f6b4c91288838e60b6bcb2cc45d997e961de" + + +def trim_instruction_padding(features: torch.Tensor, padding: torch.Tensor): + """Drop columns padded in the entire frozen vocabulary, preserving token order. + + Resolve this once on CPU before moving the table to the policy device. Shorter + prompts retain their masks; no per-minibatch synchronization or shape change + is needed. Cached contextual embeddings are never re-encoded or truncated. + """ + keep = (~padding).any(dim=0) + if not keep.any(): + raise ValueError("Instruction table contains no valid language tokens.") + return features[:, keep].contiguous(), padding[:, keep].contiguous() + + +def encode_instructions( + instructions: tuple[str, ...], *, checkpoint: str, revision: str, max_tokens: int, device: str +) -> tuple[torch.Tensor, torch.Tensor]: + """Load only the text backbone and return contextual tokens and padding.""" + from transformers import AutoConfig, AutoTokenizer, Cosmos3EdgeTextModel + from transformers.conversion_mapping import ( + get_checkpoint_conversion_mapping, + register_checkpoint_conversion_mapping, + ) + from transformers.models.cosmos3_edge.modeling_cosmos3_edge import Cosmos3EdgePreTrainedModel + + class FoviCosmosTextBackbone(Cosmos3EdgePreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.language_model = Cosmos3EdgeTextModel(config.text_config) + self.post_init() + + register_checkpoint_conversion_mapping( + "FoviCosmosTextBackbone", + get_checkpoint_conversion_mapping("cosmos3_edge"), + overwrite=True, + ) + config = AutoConfig.from_pretrained(checkpoint, revision=revision) + if config.model_type != "cosmos3_edge": + raise ValueError("Expected a Cosmos3-Edge checkpoint.") + tokenizer = AutoTokenizer.from_pretrained(checkpoint, revision=revision) + encoded = tokenizer( + list(instructions), + padding="max_length", + max_length=max_tokens, + truncation=False, + return_tensors=None, + ) + if any(len(ids) > max_tokens for ids in encoded["input_ids"]): + raise ValueError("Instruction exceeds max_tokens; refusing to truncate it.") + model, info = FoviCosmosTextBackbone.from_pretrained( + checkpoint, + revision=revision, + config=config, + dtype=torch.bfloat16, + device_map={"": device}, + attn_implementation="sdpa", + output_loading_info=True, + ) + unexpected = [ + key for key in info["unexpected_keys"] if not key.startswith(("model.visual.", "model.projector.", "lm_head.")) + ] + if info["missing_keys"] or info["mismatched_keys"] or info["error_msgs"] or unexpected: + raise ValueError(f"Incomplete Cosmos text weights: {info}") + model.requires_grad_(False).eval() + ids = torch.tensor(encoded["input_ids"], device=device) + mask = torch.tensor(encoded["attention_mask"], device=device) + features = [] + with torch.no_grad(): + for start in range(0, len(ids), 16): + output = model.language_model( + input_ids=ids[start : start + 16], + attention_mask=mask[start : start + 16], + use_cache=False, + ) + features.append(output.last_hidden_state.to(device="cpu", dtype=torch.bfloat16)) + return torch.cat(features), ~mask.cpu().bool() + + +def instruction_table( + instructions: tuple[str, ...], + *, + path: str | None = None, + checkpoint: str = COSMOS_MODEL, + revision: str = COSMOS_REVISION, + max_tokens: int = 128, + device: str = "cpu", +) -> dict: + """Read or atomically build a portable token table with checked vocabulary identity. + + Explicit paths allow preparing language weights on another machine. A loaded + table includes all encoder provenance; its instruction ordering must agree. + The table is checkpointed as buffers by the actor, not repeated in rollouts. + """ + if not instructions or len(set(instructions)) != len(instructions): + raise ValueError("Instructions must be nonempty and unique.") + identity = dict( + format=1, + instructions=list(instructions), + checkpoint=checkpoint, + revision=revision, + max_tokens=max_tokens, + ) + if path is not None: + saved = torch.load(Path(path).expanduser(), map_location="cpu", weights_only=True) + else: + digest = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() + cache = Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "isaaclab_fovi/instructions" + cache.mkdir(parents=True, exist_ok=True) + destination = cache / f"{digest}.pt" + with FileLock(str(destination) + ".lock"): + if destination.exists(): + saved = torch.load(destination, map_location="cpu", weights_only=True) + else: + devices = [torch.device(device)] if torch.device(device).type == "cuda" else [] + with torch.random.fork_rng(devices=devices): + features, padding = encode_instructions( + instructions, + checkpoint=checkpoint, + revision=revision, + max_tokens=max_tokens, + device=device, + ) + saved = dict(identity=identity, features=features, padding=padding) + with tempfile.NamedTemporaryFile(dir=cache, suffix=".tmp", delete=False) as handle: + temporary = Path(handle.name) + try: + torch.save(saved, temporary) + os.replace(temporary, destination) + finally: + temporary.unlink(missing_ok=True) + if saved["identity"] != identity: + raise ValueError("Instruction table vocabulary or encoder identity mismatch.") + features, padding = saved["features"], saved["padding"] + if ( + features.ndim != 3 + or features.shape[:2] != (len(instructions), max_tokens) + or features.dtype != torch.bfloat16 + or padding.dtype != torch.bool + or padding.shape != features.shape[:2] + or not torch.isfinite(features).all() + ): + raise ValueError("Invalid instruction table shape, dtype, or nonfinite features.") + return saved diff --git a/src/isaaclab_tutorial/active_gaze/learning/models.py b/src/isaaclab_tutorial/active_gaze/learning/models.py new file mode 100644 index 0000000..39ae81f --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/models.py @@ -0,0 +1,94 @@ +"""Native RSL-RL feedforward actor with the CoRL language/vision readout.""" + +import torch +from rsl_rl.models import MLPModel + +from .fusion import LanguageVisionFusion +from .language import instruction_table, trim_instruction_padding + + +class LanguageVisionActor(MLPModel): + """Frozen retinal tokens and instruction tokens, trainable fusion and motor/gaze MLP. + + Only proprioception is empirically normalized. The instruction integer is a + lookup index, never a numeric MLP feature. Privileged and oracle groups are + excluded explicitly. Frozen DINO runs in the environment observation term. + """ + + def __init__( + self, + obs, + obs_groups, + obs_set, + output_dim, + *, + instructions, + instruction_table_path=None, + language_device="cpu", + fusion_dim=128, + fusion_width=256, + fusion_heads=4, + fusion_blocks=2, + spatial_channels=4, + extrinsics_head=False, + **kwargs, + ): + self.fusion_dim = fusion_dim + self.instructions = tuple(instructions) + saved = instruction_table(self.instructions, path=instruction_table_path, device=language_device) + super().__init__(obs, obs_groups, obs_set, output_dim, **kwargs) + features, padding = trim_instruction_padding(saved["features"], saved["padding"]) + self.register_buffer("language_features", features) + self.register_buffer("language_padding", padding) + self.fusion = LanguageVisionFusion( + obs["vision"].shape[-1], + self.language_features.shape[-1], + obs["vision"].shape[-2], + self.language_features.shape[-2], + width=fusion_width, + heads=fusion_heads, + blocks=fusion_blocks, + spatial_channels=spatial_channels, + output_dim=fusion_dim, + ) + self.extrinsics_head = None + self.extrinsics_prediction = None + if extrinsics_head: + self.extrinsics_head = torch.nn.Sequential( + torch.nn.Linear(self._get_latent_dim(), 128), torch.nn.ELU(), torch.nn.Linear(128, 9) + ) + torch.nn.init.zeros_(self.extrinsics_head[-1].weight) + torch.nn.init.zeros_(self.extrinsics_head[-1].bias) + + def _get_obs_dim(self, obs, obs_groups, obs_set): + if set(obs_groups[obs_set]) != {"proprio", "vision", "instruction"}: + raise ValueError("Actor inputs must be proprio, vision, instruction only.") + if obs["vision"].ndim != 3 or obs["instruction"].shape[-1] != 1: + raise ValueError("Expected spatial vision tokens and one instruction lookup index.") + return ["proprio"], obs["proprio"].shape[-1] + + def _get_latent_dim(self): + return self.obs_dim + self.fusion_dim + + def get_latent(self, obs, masks=None, hidden_state=None): + indices = obs["instruction"].squeeze(-1).long() + features = self.language_features.index_select(0, indices) + padding = self.language_padding.index_select(0, indices) + visual = self.fusion(obs["vision"], features, padding) + latent = torch.cat((super().get_latent(obs), visual), dim=-1) + if self.extrinsics_head is not None: + self.extrinsics_prediction = self.extrinsics_head(latent) + return latent + + def get_extra_state(self): + return self.instructions + + def set_extra_state(self, state): + if tuple(state) != self.instructions: + raise ValueError("Checkpoint instruction vocabulary does not match the task.") + + def as_jit(self): + raise NotImplementedError("Use the example play entry point for the full DINO/fusion pipeline.") + + def as_onnx(self, verbose=False): + raise NotImplementedError("Use the example play entry point for the full DINO/fusion pipeline.") diff --git a/src/isaaclab_tutorial/active_gaze/learning/observations.py b/src/isaaclab_tutorial/active_gaze/learning/observations.py new file mode 100644 index 0000000..bdfede4 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/observations.py @@ -0,0 +1,22 @@ +"""Shared frozen visual preprocessing for native manager-based tasks.""" + +from isaaclab.managers import ManagerTermBase + +from .dino import FrozenDino + + +class DinoTokens(ManagerTermBase): + """Encode the monocular eye once per observation, outside PPO minibatches.""" + + def __init__(self, cfg, env): + super().__init__(cfg, env) + self.camera = env.scene["eye"] + self.encoder = FrozenDino(**{k: v for k, v in cfg.params.items() if k != "data_type"}).to(env.device).eval() + self.cached = None + + def __call__(self, env, reference: str, checksum: str | None, batch_size: int, data_type: str = "rgb"): + if not getattr(env, "refresh_policy_vision", True) and self.cached is not None: + return self.cached + image = self.camera.data.output[data_type] + self.cached = self.encoder(image.torch if hasattr(image, "torch") else image) + return self.cached diff --git a/src/isaaclab_tutorial/active_gaze/learning/oracle_ppo.py b/src/isaaclab_tutorial/active_gaze/learning/oracle_ppo.py new file mode 100644 index 0000000..9a00b4c --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/oracle_ppo.py @@ -0,0 +1,250 @@ +# Copyright (c) 2021-2026, ETH Zurich and NVIDIA CORPORATION +# All rights reserved. +# SPDX-License-Identifier: BSD-3-Clause + +"""RSL-RL 5.5 PPO with RND and constant-weight Gaussian gaze supervision. + +The update follows rsl_rl.algorithms.PPO (BSD-3-Clause). The native runner, +storage, GAE, optimizer, and checkpointing are retained. Chunk transitions add +executed-prefix likelihoods, per-control oracle targets, and final-state timeout +bootstrapping. The auxiliary targets never enter the actor. +""" + +import math +from datetime import timedelta + +import torch +from rsl_rl.algorithms import PPO +from torch import nn + +from .chunks import chunk_gaussian_statistics +from .distributions import ClippedGaussianDistribution +from .rnd import ClippedInputRND + + +def gaze_loss(mean: torch.Tensor, std: torch.Tensor, labels: torch.Tensor, teacher_std=1e-4): + """Unweighted mean-distance plus smooth-L1 standard-deviation loss. + + Labels contain two normalized gaze actions and a validity bit. Select valid + rows before subtraction so an invalid, nonfinite target cannot poison grads. + """ + valid = labels[:, 2] > 0.5 + residual = torch.where(valid[:, None], mean - torch.nan_to_num(labels[:, :2]), 0.0) + std_error = nn.functional.smooth_l1_loss(std, torch.full_like(std, teacher_std), reduction="none").mean(dim=-1) + return (residual.norm(dim=-1) + torch.where(valid, std_error, 0.0)).sum() / valid.sum().clamp_min(1) + + +class OraclePPO(PPO): + """Single-critic joint PPO for feedforward policies plus gaze-only distillation.""" + + def __init__( + self, + actor, + critic, + storage, + *, + oracle_weight=1.0, + oracle_std=1e-4, + action_chunk_size=1, + rnd_cfg=None, + **kwargs, + ): + if not math.isfinite(oracle_weight) or oracle_weight < 0: + raise ValueError("oracle_weight must be finite and nonnegative.") + if not math.isfinite(oracle_std) or oracle_std <= 0: + raise ValueError("oracle_std must be finite and positive.") + if actor.is_recurrent or critic.is_recurrent or kwargs.get("symmetry_cfg"): + raise ValueError("This example supports feedforward PPO without symmetry.") + if kwargs.get("schedule", "adaptive") != "fixed": + raise ValueError("Use the native camera task's fixed learning-rate schedule.") + super().__init__(actor, critic, storage, **kwargs) + self.rnd = ClippedInputRND(device=self.device, **rnd_cfg) if rnd_cfg else None + self.oracle_weight = float(oracle_weight) + self.oracle_std = float(oracle_std) + if type(action_chunk_size) is not int or action_chunk_size < 1: + raise ValueError("Action chunk size must be positive.") + self.action_chunk_size = action_chunk_size + self.clipped_actions = isinstance(self._raw_actor.distribution, ClippedGaussianDistribution) + + def act(self, obs): + if self.action_chunk_size > 1 and ( + "chunk_valid" not in obs or obs["chunk_valid"].shape[-1] != self.action_chunk_size + ): + raise ValueError("Use ActionChunkWrapper with the configured action_chunk_size") + with torch.autocast(torch.device(self.device).type, dtype=torch.bfloat16, enabled=self.use_mixed_precision): + return super().act(obs) + + def broadcast_parameters(self): + """Synchronize tensor state and validate the checkpointed vocabulary. + + Native RSL-RL assumes every state_dict entry is a tensor. The language + actor also checkpoints its instruction ordering through get_extra_state. + """ + # OVRTX initializes CUDA contexts on peer GPUs. Keep early ranks off + # NCCL until every renderer is ready, so its GPU work cannot obstruct + # another rank's remaining startup work. Cold shader builds can be slow. + startup_group = torch.distributed.new_group(backend="gloo", timeout=timedelta(minutes=30)) + try: + torch.distributed.monitored_barrier(group=startup_group, wait_all_ranks=True) + finally: + torch.distributed.destroy_process_group(startup_group) + models = [self._raw_actor, self._raw_critic] + if self.rnd is not None: + models.append(self.rnd) + for model in models: + for value in model.state_dict().values(): + if isinstance(value, torch.Tensor): + torch.distributed.broadcast(value, src=0) + else: + objects = [value] + torch.distributed.broadcast_object_list(objects, src=0, device=torch.device(self.device)) + if objects[0] != value: + raise ValueError("Distributed instruction vocabularies do not match") + + def process_env_step(self, obs, rewards, dones, extras): + if self.rnd is not None: + # Train on the same next-state stream that earns the novelty bonus. + # These dedicated groups are not inputs to the actor or critic. + self.transition.observations = self.transition.observations.clone(recurse=False) + for key in self.rnd.obs_groups["rnd_state"]: + self.transition.observations[key] = obs[key] + if "chunk_valid" in extras: + transition = self.transition + transition.observations = transition.observations.clone(recurse=False) + for key in ("chunk_valid", "chunk_oracle"): + transition.observations[key] = extras[key] + transition.actions_log_prob, _ = chunk_gaussian_statistics( + *transition.distribution_params, + transition.actions, + extras["chunk_valid"], + clipped=self.clipped_actions, + ) + with ( + torch.no_grad(), + torch.autocast( + torch.device(self.device).type, + dtype=torch.bfloat16, + enabled=self.use_mixed_precision, + ), + ): + final_values = self.critic(extras["chunk_timeout_observations"]).squeeze(-1) + rewards = rewards + extras["chunk_timeout_discount"] * final_values.float() + super().process_env_step(obs, rewards, dones, extras) + + def update(self): + totals = torch.zeros(6, device=self.device) + auxiliary_totals = {} + updates = 0 + for batch in self.storage.mini_batch_generator(self.num_mini_batches, self.num_learning_epochs): + if self.normalize_advantage_per_mini_batch: + with torch.no_grad(): + batch.advantages = (batch.advantages - batch.advantages.mean()) / (batch.advantages.std() + 1e-8) + with torch.autocast( + torch.device(self.device).type, + enabled=self.use_mixed_precision, + dtype=torch.bfloat16, + ): + self.actor(batch.observations, stochastic_output=True) + if "chunk_valid" in batch.observations: + log_prob, entropy = chunk_gaussian_statistics( + self.actor.output_mean, + self.actor.output_std, + batch.actions, + batch.observations["chunk_valid"], + clipped=self.clipped_actions, + ) + entropy = entropy.mean() + labels = batch.observations["chunk_oracle"].flatten(0, 1) + else: + log_prob = self.actor.get_output_log_prob(batch.actions) + entropy = self.actor.output_entropy.mean() + labels = batch.observations.get("oracle") + if labels is None: + if self.oracle_weight: + raise ValueError("Gaze supervision requires oracle labels") + labels = torch.zeros(len(batch.actions), 3, device=self.device) + values = self.critic(batch.observations).float() + ratio = torch.exp(log_prob - batch.old_actions_log_prob.squeeze(-1)) + advantages = batch.advantages.squeeze(-1) + surrogate = torch.maximum( + -advantages * ratio, + -advantages * ratio.clamp(1 - self.clip_param, 1 + self.clip_param), + ).mean() + value_error = (values - batch.returns).square() + if self.use_clipped_value_loss: + clipped = batch.values + (values - batch.values).clamp(-self.clip_param, self.clip_param) + value_error = torch.maximum(value_error, (clipped - batch.returns).square()) + value_loss = value_error.mean() + oracle = gaze_loss( + self.actor.output_mean.reshape( + -1, + self.action_chunk_size, + self.actor.output_mean.shape[-1] // self.action_chunk_size, + )[..., -2:] + .flatten(0, 1) + .float(), + self.actor.output_std.reshape( + -1, + self.action_chunk_size, + self.actor.output_mean.shape[-1] // self.action_chunk_size, + )[..., -2:] + .flatten(0, 1) + .float(), + labels, + self.oracle_std, + ) + loss = ( + surrogate + + self.value_loss_coef * value_loss + - self.entropy_coef * entropy + + self.oracle_weight * oracle + ) + auxiliary, metrics = self.auxiliary_loss(batch.observations) + loss = loss + auxiliary + for name, value in metrics.items(): + auxiliary_totals[name] = auxiliary_totals.get(name, 0) + value.detach() + self.optimizer.zero_grad() + loss.backward() + # Keep the small novelty networks in FP32, independently of actor AMP. + rnd_loss = torch.zeros((), device=self.device) + if self.rnd is not None: + rnd_loss = self.rnd.compute_loss(batch.observations) + self.rnd.optimizer.zero_grad() + rnd_loss.backward() + if self.is_multi_gpu: + self.reduce_parameters() + nn.utils.clip_grad_norm_(self.actor.parameters(), self.max_grad_norm) + nn.utils.clip_grad_norm_(self.critic.parameters(), self.max_grad_norm) + self.optimizer.step() + if self.rnd is not None: + self.rnd.optimizer.step() + totals += torch.stack( + ( + value_loss, + surrogate, + entropy, + oracle, + (labels[:, 2] > 0.5).float().mean(), + rnd_loss, + ) + ).detach() + updates += 1 + obs = self.storage.observations.flatten(0, 1) + self.actor.update_normalization(obs) + self.critic.update_normalization(obs) + if self.rnd is not None: + self.rnd.update_normalization(obs) + self.storage.clear() + result = dict( + zip( + ("value", "surrogate", "entropy", "oracle", "oracle_valid", "rnd"), + (totals / updates).tolist(), + strict=True, + ) + ) + result.update({key: (value / updates).item() for key, value in auxiliary_totals.items()}) + return result + + def auxiliary_loss(self, observations): + """Optional task-supervised loss on the shared actor forward pass.""" + return torch.zeros((), device=self.device), {} diff --git a/src/isaaclab_tutorial/active_gaze/learning/rnd.py b/src/isaaclab_tutorial/active_gaze/learning/rnd.py new file mode 100644 index 0000000..046dbb0 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/rnd.py @@ -0,0 +1,39 @@ +"""Native RSL-RL RND with clipped state inputs and no scalar CUDA readbacks.""" + +import torch +from rsl_rl.extensions import RandomNetworkDistillation +from rsl_rl.modules import EmpiricalDiscountedVariationNormalization, EmpiricalNormalization + + +class ClippedStateNormalization(EmpiricalNormalization): + def forward(self, state): + return super().forward(state).clamp(-5.0, 5.0) + + +class DiscountedRewardNormalization(EmpiricalDiscountedVariationNormalization): + def forward(self, reward): + # Same native discounted-return statistics, without a Python branch on + # CUDA std. No sample-count cutoff that reads a device scalar each call. + if self.training: + self.emp_norm.update(self.disc_avg.update(reward)) + std = self.emp_norm._std + return reward / torch.where(std > 0, std, torch.ones_like(std)) + + +class ClippedInputRND(RandomNetworkDistillation): + """Keep native rewards, optimizer and checkpointing with clipped normalized inputs. + + State statistics update once per PPO update. Reward statistics follow the + native per-decision discounted stream (gamma=0.99, no episode resets). + Like native RSL-RL, a checkpoint restores the moments and networks, while + restarting the per-environment return filter for the new simulator rollout. + """ + + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.target.requires_grad_(False) + self.weight = self.initial_weight + if self.state_normalization: + self.state_normalizer = ClippedStateNormalization(shape=[self.num_states], until=None).to(self.device) + if self.reward_normalization: + self.reward_normalizer = DiscountedRewardNormalization(shape=[], until=None).to(self.device) diff --git a/src/isaaclab_tutorial/active_gaze/learning/runner.py b/src/isaaclab_tutorial/active_gaze/learning/runner.py new file mode 100644 index 0000000..4269b23 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/learning/runner.py @@ -0,0 +1,211 @@ +# Copyright (c) 2021-2026, ETH Zurich and NVIDIA CORPORATION +# All rights reserved. +# SPDX-License-Identifier: BSD-3-Clause + +"""Native RSL-RL training with periodic rollout-only evaluation blocks. + +The learning loop is adapted from RSL-RL 5.5.1 (BSD-3-Clause) to insert +evaluation between updates and explicitly replace the post-reset observation. +""" + +import os +import time + +import torch +from rsl_rl.runners import OnPolicyRunner +from rsl_rl.utils import check_nan + +from isaaclab_tutorial.active_gaze.training.evaluation import PeriodicEvaluation, coordinated_errors + + +def initialize_distributed(): + """Bind NCCL explicitly and validate communication before expensive RTX startup.""" + world_size = int(os.environ.get("WORLD_SIZE", "1")) + if world_size == 1: + return + rank = int(os.environ["RANK"]) + local_rank = int(os.environ["LOCAL_RANK"]) + torch.cuda.set_device(local_rank) + if not torch.distributed.is_initialized(): + torch.distributed.init_process_group( + backend="nccl", + rank=rank, + world_size=world_size, + device_id=torch.device(f"cuda:{local_rank}"), + ) + probe = torch.ones(1, device=f"cuda:{local_rank}") + torch.distributed.all_reduce(probe) + if probe.item() != world_size: + raise RuntimeError("Distributed startup collective failed") + print( + f"ISAACLAB_FOVI_DISTRIBUTED rank={rank} local_rank={local_rank} world_size={world_size} ready", + flush=True, + ) + if torch.distributed.get_rank() != rank or torch.distributed.get_world_size() != world_size: + raise ValueError("Existing process group differs from the requested ranks") + + +class DistributedOnPolicyRunner(OnPolicyRunner): + """Native runner with explicit, reusable NCCL initialization.""" + + def _configure_multi_gpu(self): + self.gpu_world_size = int(os.environ.get("WORLD_SIZE", "1")) + self.is_distributed = self.gpu_world_size > 1 + if not self.is_distributed: + return super()._configure_multi_gpu() + self.gpu_global_rank = int(os.environ["RANK"]) + self.gpu_local_rank = int(os.environ["LOCAL_RANK"]) + if self.device != f"cuda:{self.gpu_local_rank}": + raise ValueError("Runner device does not match the distributed local rank") + initialize_distributed() + self.cfg["multi_gpu"] = { + "global_rank": self.gpu_global_rank, + "local_rank": self.gpu_local_rank, + "world_size": self.gpu_world_size, + } + + +class EvaluationOnPolicyRunner(DistributedOnPolicyRunner): + """Native PPO and gradient reduction, with evaluation between updates.""" + + def __init__(self, env, train_cfg, log_dir=None, device="cpu"): + super().__init__(env, train_cfg, log_dir, device) + self.current_learning_iteration = -1 + self.evaluation = PeriodicEvaluation(env, self.cfg.get("evaluation", {})) + + def _log_action_diagnostics(self, iteration): + """Separate motor/gaze saturation; aggregate only executed chunk prefixes.""" + writer = self.logger.writer + if writer is None and not self.is_distributed: + return + storage = self.alg.storage + mean, std = storage.distribution_params + shape = (*storage.actions.shape[:2], self.env.chunk_size, -1) + actions, mean, std = (value.reshape(shape) for value in (storage.actions, mean, std)) + valid = storage.observations.get("chunk_valid") + if valid is None: + valid = torch.ones(actions.shape[:-1], device=actions.device, dtype=torch.bool) + motor = self.env.unwrapped.action_manager.get_term("motor") + groups = { + "arm": slice(0, motor.arm_action_dim), + "hand": slice(motor.arm_action_dim, motor.action_dim), + "gaze": slice(motor.action_dim, motor.action_dim + 2), + } + names, sums, counts = [], [], [] + for name, selection in groups.items(): + count = valid.sum() * actions[..., selection].shape[-1] + mask = valid[..., None] + measures = { + "latent_std": std[..., selection], + "latent_mean_abs": mean[..., selection].abs(), + "saturation": (actions[..., selection].abs() >= 1).float(), + } + for measure, value in measures.items(): + names.append(f"Policy/{name}/{measure}") + sums.append(torch.where(mask, value, 0.0).sum()) + counts.append(count) + totals = torch.stack((torch.stack(sums), torch.stack(counts))) + if self.is_distributed: + torch.distributed.all_reduce(totals) + values = totals[0] / totals[1].clamp_min(1) + if writer is not None: + for name, value in zip(names, values.tolist(), strict=True): + writer.add_scalar(name, value, iteration) + + @property + def training_control_steps(self): + """Derive cadence from native checkpoint progress; no second saved counter.""" + return (self.current_learning_iteration + 1) * self.cfg["num_steps_per_env"] * self.env.chunk_size + + def learn(self, num_learning_iterations: int, init_at_random_ep_len: bool = False) -> None: + """Run the learning loop for the specified number of iterations.""" + # Randomize initial episode lengths (for exploration) + if init_at_random_ep_len: + self.env.episode_length_buf = torch.randint_like( + self.env.episode_length_buf, high=int(self.env.max_episode_length) + ) + + # Start learning + obs = self.env.get_observations().to(self.device) + self.alg.train_mode() # switch to train mode (for dropout for example) + + # Ensure all parameters are in-synced + if self.is_distributed: + print(f"Synchronizing parameters for rank {self.gpu_global_rank}...") + self.alg.broadcast_parameters() + + # Initialize the logging writer + self.logger.init_logging_writer() + + # Start training + start_it = self.current_learning_iteration + 1 + self.logger.tot_timesteps = start_it * self.cfg["num_steps_per_env"] * self.env.num_envs * self.gpu_world_size + total_it = start_it + num_learning_iterations + for it in range(start_it, total_it): + start = time.time() + # Rollout + with torch.inference_mode(): + for _ in range(self.cfg["num_steps_per_env"]): + # Sample actions + actions = self.alg.act(obs) + # Step the environment + obs, rewards, dones, extras = self.env.step(actions.to(self.env.device)) + # Check for NaN values from the environment + if self.cfg.get("check_for_nan", True): + check_nan(obs, rewards, dones) + # Move to device + obs, rewards, dones = ( + obs.to(self.device), + rewards.to(self.device), + dones.to(self.device), + ) + # Process the step + self.alg.process_env_step(obs, rewards, dones, extras) + # Extract intrinsic rewards if RND is used (only for logging) + intrinsic_rewards = self.alg.intrinsic_rewards if self.cfg["algorithm"].get("rnd_cfg") else None + # Book keeping + self.logger.process_env_step(rewards, dones, extras, intrinsic_rewards) + + stop = time.time() + collect_time = stop - start + start = stop + + # Compute returns + self.alg.compute_returns(obs) + + # Update policy + self._log_action_diagnostics(it) + loss_dict = self.alg.update() + + stop = time.time() + learn_time = stop - start + self.current_learning_iteration = it + + # Log information + self.logger.log( + it=it, + start_it=start_it, + total_it=total_it, + collect_time=collect_time, + learn_time=learn_time, + loss_dict=loss_dict, + learning_rate=self.alg.learning_rate, + action_std=self.alg.get_policy().output_std, + rnd_weight=self.alg.rnd.weight if self.cfg["algorithm"].get("rnd_cfg") else None, + ) + + previous_steps = self.training_control_steps - self.cfg["num_steps_per_env"] * self.env.chunk_size + evaluate = self.evaluation.due(previous_steps, self.training_control_steps) + # Preserve the exact policy shown in each evaluation video, including + # early blocks that fall between the regular checkpoint intervals. + if evaluate or it % self.cfg["save_interval"] == 0: + with coordinated_errors(self): + if self.logger.writer is not None: + self.save(os.path.join(self.logger.log_dir, f"model_{it}.pt")) # type: ignore + if evaluate: + obs = self.evaluation.run(self) + + # Save the final model after training and stop the logging writer + if self.logger.writer is not None: + self.save(os.path.join(self.logger.log_dir, f"model_{self.current_learning_iteration}.pt")) # type: ignore + self.logger.stop_logging_writer() diff --git a/src/isaaclab_tutorial/active_gaze/pose_ppo.py b/src/isaaclab_tutorial/active_gaze/pose_ppo.py new file mode 100644 index 0000000..bd11051 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/pose_ppo.py @@ -0,0 +1,21 @@ +"""Camera-pose supervision trains the actor representation without a reward.""" + +import math + +from isaaclab_tutorial.active_gaze.learning.oracle_ppo import OraclePPO + +from .camera_geometry import pose_loss + + +class ExtrinsicsPPO(OraclePPO): + def __init__(self, *args, extrinsics_weight=0.05, **kwargs): + if not math.isfinite(extrinsics_weight) or extrinsics_weight < 0: + raise ValueError("extrinsics_weight must be finite and nonnegative") + super().__init__(*args, **kwargs) + self.extrinsics_weight = extrinsics_weight + if self._raw_actor.extrinsics_head is None: + raise ValueError("Extrinsics PPO requires the actor's auxiliary head") + + def auxiliary_loss(self, observations): + loss, metrics = pose_loss(self._raw_actor.extrinsics_prediction, observations["extrinsics"]) + return self.extrinsics_weight * loss, dict(metrics, extrinsics=loss) diff --git a/src/isaaclab_tutorial/active_gaze/render_options.py b/src/isaaclab_tutorial/active_gaze/render_options.py new file mode 100644 index 0000000..ccdf473 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/render_options.py @@ -0,0 +1,70 @@ +"""Declarative OVRTX shading and renderer presets.""" + +from isaaclab.utils import configclass +from isaaclab_newton.renderers import NewtonWarpRendererCfg +from isaaclab_ov.renderers import OVRTXRendererCfg +from isaaclab_tasks.utils import PresetCfg + +RENDER_MODES = { + "rtpt": ("rgb", False), + "minimal_diffuse_mdl": ("simple_shading_diffuse_mdl", False), + "minimal_diffuse_mdl_shadows": ("simple_shading_diffuse_mdl", True), + "minimal_full_mdl": ("simple_shading_full_mdl", False), + "minimal_full_mdl_shadows": ("simple_shading_full_mdl", True), +} + + +@configclass +class CameraOutputCfg(PresetCfg): + default = ["simple_shading_full_mdl"] + newton_renderer = ["rgb"] + rtpt = ["rgb"] + minimal_diffuse_mdl = ["simple_shading_diffuse_mdl"] + minimal_diffuse_mdl_shadows = minimal_diffuse_mdl + minimal_full_mdl = ["simple_shading_full_mdl"] + minimal_full_mdl_shadows = minimal_full_mdl + + +@configclass +class CameraOutputNameCfg(PresetCfg): + default = "simple_shading_full_mdl" + newton_renderer = "rgb" + rtpt = "rgb" + minimal_diffuse_mdl = "simple_shading_diffuse_mdl" + minimal_diffuse_mdl_shadows = minimal_diffuse_mdl + minimal_full_mdl = "simple_shading_full_mdl" + minimal_full_mdl_shadows = minimal_full_mdl + + +@configclass +class ShadowsCfg(PresetCfg): + default = True + rtpt = False + minimal_diffuse_mdl = False + minimal_diffuse_mdl_shadows = True + minimal_full_mdl = False + minimal_full_mdl_shadows = True + + +@configclass +class CameraRenderSettingsCfg(PresetCfg): + """Author native sample settings directly on each camera's render product.""" + + newton_renderer = {} + _minimal = { + "omni:rtx:post:aa:op": ("Token", "none"), + "omni:rtx:newDenoiser:enabled": ("Bool", True), + } + rtpt = {**_minimal, "omni:rtx:rtpt:spp": ("Int", 4)} + minimal_diffuse_mdl = _minimal + minimal_diffuse_mdl_shadows = _minimal + minimal_full_mdl = _minimal + minimal_full_mdl_shadows = _minimal + default = minimal_full_mdl_shadows + + +@configclass +class FoviRendererCfg(PresetCfg): + newton_renderer = NewtonWarpRendererCfg(render_order="pixel_priority") + ovrtx = OVRTXRendererCfg(enable_shadows=ShadowsCfg()) + default = ovrtx diff --git a/src/isaaclab_tutorial/active_gaze/robot_geometry.py b/src/isaaclab_tutorial/active_gaze/robot_geometry.py new file mode 100644 index 0000000..4f23827 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/robot_geometry.py @@ -0,0 +1,28 @@ +"""Remove the unused wrist camera without altering the stock arm or jaw dynamics.""" + +from isaaclab.sim.utils import clone + +from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import spawn_so101 + +WRIST_CAMERA_PARTS = ( + "gripper/wowrobo_2MP_camera", + "gripper/visuals/camera_mount", + "gripper/collisions/camera_mount", +) + + +def remove_wrist_camera(robot_prim): + """Deactivate the sensor, housing, and its colliders in this scene's USD layer.""" + stage = robot_prim.GetStage() + parts = [stage.GetPrimAtPath(robot_prim.GetPath().AppendPath(path)) for path in WRIST_CAMERA_PARTS] + if not all(parts): + raise ValueError("SO-101 asset no longer contains the expected wrist camera components") + for prim in parts: + prim.SetActive(False) + + +@clone +def spawn_without_wrist_camera(prim_path, cfg, translation=None, orientation=None, **kwargs): + prim = spawn_so101(prim_path, cfg, translation=translation, orientation=orientation, **kwargs) + remove_wrist_camera(prim) + return prim diff --git a/src/isaaclab_tutorial/active_gaze/runner.py b/src/isaaclab_tutorial/active_gaze/runner.py new file mode 100644 index 0000000..06d308a --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/runner.py @@ -0,0 +1,73 @@ +"""Native PPO runner with checkpointed reset statistics and episode-weighted logs.""" + +from isaaclab_tutorial.active_gaze.learning.runner import DistributedOnPolicyRunner + +from .sampling import iteration_metrics + + +class SO101Runner(DistributedOnPolicyRunner): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.sampler = self.env.unwrapped.reset_sampling + self._previous_counts = None + original_log = self.logger.log + + def log(**kwargs): + original_log(**kwargs) + metrics, self._previous_counts = iteration_metrics( + self.sampler, self._previous_counts, distributed=self.is_distributed + ) + if self.logger.writer is not None: + for key, value in metrics.items(): + self.logger.writer.add_scalar(key, value, kwargs["it"]) + + self.logger.log = log + + def learn(self, num_learning_iterations, init_at_random_ep_len=False): + import torch + + self._previous_counts = torch.stack( + ( + self.sampler.history.episodes, + self.sampler.history.successes, + self.sampler.sampled, + ) + ).clone() + if init_at_random_ep_len: + # The staggered first episodes have shortened horizons; exclude their outcomes. + self.sampler.eligible.zero_() + return super().learn(num_learning_iterations, init_at_random_ep_len) + + def save(self, path, infos=None): + infos = dict(infos or {}, reset_sampling=self.sampler.state_dict()) + infos["sim2real_control_steps"] = self.env.unwrapped.common_step_counter + super().save(path, infos) + + def load(self, path, load_cfg=None, strict=True, map_location=None): + infos = super().load(path, load_cfg, strict, map_location) + if infos and "sim2real_control_steps" in infos: + self.env.unwrapped.common_step_counter = infos["sim2real_control_steps"] + # Playback uses canonical home starts and must not restore/adapt training sampling. + if not self.env.unwrapped.cfg.reset_sampling_evaluation and infos and "reset_sampling" in infos: + self.sampler.load_state_dict(infos["reset_sampling"]) + return infos + + def finetune(self, path, map_location=None): + """Warm-start all learned state, permitting only a new camera-pose head. + + The changed environment starts fresh optimizer and SGS histories. Shape + mismatches or unrelated missing weights still fail strictly. + """ + import torch + + packed = torch.load(path, map_location=map_location, weights_only=False) + actor = self.alg._raw_actor + target = actor.state_dict() + source = packed["actor_state_dict"] + missing = set(target) - set(source) + if any(not name.startswith("extrinsics_head.") for name in missing): + raise ValueError(f"Unexpected missing fine-tune weights: {sorted(missing)}") + actor.load_state_dict({**{name: target[name] for name in missing}, **source}, strict=True) + self.alg._raw_critic.load_state_dict(packed["critic_state_dict"], strict=True) + self.current_learning_iteration = packed["iter"] + return sorted(missing) diff --git a/src/isaaclab_tutorial/active_gaze/sampling.py b/src/isaaclab_tutorial/active_gaze/sampling.py new file mode 100644 index 0000000..6733a95 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/sampling.py @@ -0,0 +1,201 @@ +"""Phase-binned Success Guided Sampling and completed-episode accounting. + +SGS: https://arxiv.org/html/2610.12465v1#S3.SS2 and appendix B.2. +We use the eight stock reset phases as bins, with uniform rows within each bin. +""" + +import math + +import torch +from isaaclab.managers import ManagerTermBase + +PHASE_NAMES = ("home", "pregrasp", "grasp", "lift", "reorient", "transport", "insert", "release") +SGS_DEFAULTS = dict(history=100, target=0.5, concentration=1.0, temperature=2.0, epsilon=1e-4) + + +def validate_settings(mode="uniform", **settings): + if mode not in ("uniform", "sgs"): + raise ValueError("reset_sampling must be 'uniform' or 'sgs'") + values = SGS_DEFAULTS | settings + if not isinstance(values["history"], int) or values["history"] <= 0: + raise ValueError("sgs_history must be a positive integer") + for name in ("target", "concentration", "temperature", "epsilon"): + if not math.isfinite(values[name]): + raise ValueError(f"sgs_{name} must be finite") + if not 0 <= values["target"] <= 1 or values["concentration"] < 0: + raise ValueError("SGS requires target in [0, 1] and nonnegative concentration") + if values["temperature"] <= 0 or not 0 < values["epsilon"] < 1: + raise ValueError("SGS requires positive temperature and epsilon in (0, 1)") + return dict(mode=mode, **values) + + +class SuccessHistory: + """Batched circular histories, including multiple endings in the same bin.""" + + def __init__(self, num_bins, device="cpu", **settings): + self.settings = validate_settings(**settings) + self.history = torch.zeros(num_bins, self.settings["history"], device=device) + self.episodes = torch.zeros(num_bins, dtype=torch.long, device=device) + self.successes = torch.zeros_like(self.episodes) + + def update(self, bins, outcomes): + if not len(bins): + return + # Stable ordering gives simultaneous endings a reproducible env-index order. + order = bins.argsort(stable=True) + bins, outcomes = bins[order], outcomes[order] + counts = torch.bincount(bins, minlength=len(self.episodes)) + offsets = counts.cumsum(0) - counts + ranks = torch.arange(len(bins), device=bins.device) - offsets[bins] + size = self.history.shape[1] + keep = ranks >= (counts[bins] - size) + slots = (self.episodes[bins] + ranks) % size + self.history[bins[keep], slots[keep]] = outcomes[keep].float() + self.episodes += counts + self.successes.scatter_add_(0, bins, outcomes.long()) + + @property + def counts(self): + return self.episodes.clamp_max(self.history.shape[1]) + + @property + def rates(self): + # No fabricated observations: unvisited bins have a zero estimate until sampled. + return self.history.sum(-1) / self.counts.clamp_min(1) + + def probabilities(self, base): + p = self.rates + cfg = self.settings + eps, k, t = cfg["epsilon"], cfg["concentration"], cfg["target"] + weight = (p + eps).pow(k * t) * (1 - p + eps).pow(k * (1 - t)) + # Appendix B.2: floor before logarithm and clamp effective temperature to one. + logits = (weight.clamp_min(eps) + eps).log() / max(cfg["temperature"], 1.0) + logits += base.log() # zero base weight excludes disabled phases (e.g. home-only play) + return logits.softmax(0) + + def state_dict(self): + return {name: getattr(self, name).clone() for name in ("history", "episodes", "successes")} + + def load_state_dict(self, state): + for name in ("history", "episodes", "successes"): + target = getattr(self, name) + if state[name].shape != target.shape: + raise ValueError(f"Incompatible reset sampler {name} shape") + target.copy_(state[name]) + + +class ResetSampling(ManagerTermBase): + """Observe terminal outcomes before stock resets replace rows and milestones.""" + + def __init__(self, cfg, env): + super().__init__(cfg, env) + self.settings = validate_settings(**cfg.params) + self.reset_term = env.event_manager.get_term_cfg("reset_from_dataset").func + self.phases = getattr(self.reset_term, "bin_ids", self.reset_term.states["phase"]) + self.bin_names = getattr(self.reset_term, "bin_names", PHASE_NAMES) + self.history = SuccessHistory(len(self.bin_names), env.device, **self.settings) + self.base = self.phase_probabilities() + self.phase_sizes = torch.bincount(self.phases, minlength=len(self.bin_names)) + self.eligible = torch.zeros(env.num_envs, dtype=torch.bool, device=env.device) + self.sampled = torch.zeros_like(self.history.episodes) + env.reset_sampling = self + + def phase_probabilities(self): + conditional = getattr(self.reset_term, "sampling_row_probabilities", None) + weights = conditional() if conditional else self.reset_term.row_weights + totals = weights.new_zeros(len(self.bin_names)).scatter_add_(0, self.phases, weights) + return totals / totals.sum() + + def apply_distribution(self): + if self.settings["mode"] == "sgs": + probabilities = self.history.probabilities(self.base) + self.reset_term.row_weights = probabilities[self.phases] / self.phase_sizes[self.phases] + + def __call__( + self, + env, + env_ids, + mode="uniform", + history=100, + target=0.5, + concentration=1.0, + temperature=2.0, + epsilon=1e-4, + ): + ids = torch.arange(env.num_envs, device=env.device)[env_ids] + if hasattr(env, "_so101_reset_row"): + # Manual/initial resets are not failures. A repeated reset has length zero. + completed = self.eligible[ids] & env.reset_buf[ids] & (env.episode_length_buf[ids] > 0) + ended = ids[completed] + bins = self.phases[env._so101_reset_row[ended]] + outcomes = env.termination_manager.get_term("success")[ended] + self.history.update(bins, outcomes) + self.eligible[ids] = True + self.apply_distribution() + + def reset(self, env_ids=None): + # Called by CurriculumManager after the stock physical row has been sampled. + ids = slice(None) if env_ids is None else env_ids + bins = self.phases[self._env._so101_reset_row[ids]] + self.sampled += torch.bincount(bins, minlength=len(self.bin_names)) + + def state_dict(self): + return dict( + version=1, + phases=self.bin_names, + settings=self.settings, + row_phases=self.phases.clone(), + states=self.reset_term.states, + history=self.history.state_dict(), + sampled=self.sampled.clone(), + ) + + def load_state_dict(self, state): + if state["version"] != 1 or tuple(state["phases"]) != self.bin_names: + raise ValueError("Incompatible reset sampler schema") + if state["settings"] != self.settings: + raise ValueError("Resume requires the saved SGS settings") + if not torch.equal(state["row_phases"].to(self.phases.device), self.phases): + raise ValueError("Reset sampler dataset phases changed") + for name, value in self.reset_term.states.items(): + if not torch.equal(state["states"][name].to(value.device), value): + raise ValueError("Reset sampler dataset changed") + self.history.load_state_dict(state["history"]) + self.sampled.copy_(state["sampled"]) + self.apply_distribution() + + +def iteration_metrics(sampler, previous, *, distributed=False): + """Reduce counts once per PPO update, never average per-step success ratios.""" + h = sampler.history + current = torch.stack((h.episodes, h.successes, sampler.sampled)).clone() + delta = current - previous + reported_current = current.clone() + history = torch.stack((h.history.sum(-1), h.counts, sampler.phase_probabilities())) + if distributed: + # Each rank adapts its own SGS history; report pooled episode numerators + # and denominators, rather than averaging rates with unequal sample counts. + for value in (delta, reported_current, history): + torch.distributed.all_reduce(value) + history[2] /= torch.distributed.get_world_size() + metrics = {} + probabilities = history[2].tolist() + rates, counts = (history[0] / history[1].clamp_min(1)).tolist(), history[1].tolist() + episodes, successes, sampled = delta.tolist() + total_draws = sum(sampled) + for i, name in enumerate(sampler.bin_names): + metrics[f"Reset/episodes/{name}"] = episodes[i] + metrics[f"Reset/successes/{name}"] = successes[i] + metrics[f"Reset/episodes_total/{name}"] = int(reported_current[0, i]) + metrics[f"Reset/sampled_fraction/{name}"] = sampled[i] / max(total_draws, 1) + metrics[f"SGS/probability/{name}"] = probabilities[i] + metrics[f"SGS/history_count/{name}"] = counts[i] + if counts[i]: + metrics[f"Reset/success_rate_rolling/{name}"] = rates[i] + if episodes[i]: + metrics[f"Reset/success_rate/{name}"] = successes[i] / episodes[i] + if sum(episodes): + metrics["Reset/success_rate/overall"] = sum(successes) / sum(episodes) + if all(counts): + metrics["Reset/success_rate_balanced_rolling"] = sum(rates) / len(rates) + return metrics, current diff --git a/src/isaaclab_tutorial/active_gaze/sim2real.py b/src/isaaclab_tutorial/active_gaze/sim2real.py new file mode 100644 index 0000000..4be308a --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/sim2real.py @@ -0,0 +1,250 @@ +"""Opt-in physics and appearance randomizations and uncalibrated planar software gaze.""" + +import math +from copy import deepcopy + +import torch +from isaaclab.managers import EventTermCfg, ManagerTermBase, ObservationGroupCfg, ObservationTermCfg +from isaaclab.sensors import Camera +from isaaclab.utils import configclass +from isaaclab.utils.math import ( + matrix_from_quat, + quat_apply_inverse, + quat_from_euler_xyz, + quat_from_matrix, + quat_mul, +) + +from isaaclab_fovi.deployment.so101.planar import PlanarRetina, gaze_basis, project_pinhole_rays +from isaaclab_tutorial.active_gaze.learning.observations import DinoTokens +from isaaclab_fovi.sensors.calibrated_geometry import compose_rotations, rotate_camera_rays +from isaaclab_fovi.sensors.foveated_rtx_tiled_camera import FoveatedRTXTiledCamera + +from .camera_geometry import lens_visibility, pose_targets +from .transfer_options import settings + + +class PlanarSceneCamera(FoveatedRTXTiledCamera): + """Direct RTX foveation with one shared planar LUT and per-scene poses.""" + + def _initialize_impl(self): + super()._initialize_impl() + position, orientation = self._view.get_world_poses() + self.physical_position = position.torch.clone() + self.physical_rotation = orientation.torch.clone() + self.gaze = torch.zeros(len(position.torch), 2, device=self.device) + self.retina = PlanarRetina(self._camera_hfov_deg, self.cfg.cmf_a, self.cfg.foveated_res).to(self.device) + self._physical_rays = self._fixed_fov_ray_directions * self.gaze.new_tensor((1, -1, -1)) + + def set_calibrated_angles(self, angles): + # Keep the shared action API. These are software angles using a fixed + # nominal pinhole convention, not measured physical camera intrinsics. + self.gaze = angles.clone() + self._write_gaze_pose() + + def set_physical_poses(self, position, rotation, env_ids): + self.physical_position[env_ids] = position + self.physical_rotation[env_ids] = rotation + self._write_gaze_pose(env_ids) + + def _write_gaze_pose(self, env_ids=None): + ids = slice(None) if env_ids is None else env_ids + basis = self.gaze.new_tensor((1, -1, -1)) + relative = gaze_basis(self.gaze[ids]) * basis[None, :, None] * basis[None, None, :] + rotation = quat_from_matrix(compose_rotations(matrix_from_quat(self.physical_rotation[ids]), relative)) + Camera.set_world_poses(self, self.physical_position[ids], rotation, env_ids=env_ids, convention="opengl") + + def get_world_positions(self): + return self.physical_position + + def _apply_fixed_fov_mask(self): + rotated = rotate_camera_rays(self._physical_rays, gaze_basis(self.gaze)) + _, valid = project_pinhole_rays( + rotated, + self.retina.focal_pixels, + self.retina.center_pixels, + self.retina.width, + ) + for name, output in self._foveated_output.items(): + if name == "rgb" and "rgba" in self._foveated_output: + continue + output.masked_fill_(~valid[:, :, None, None], 0) + self._fixed_fov_valid_fraction = valid.float().mean(1) + valid = valid & self._ray_coords.valid_mask + self.public_valid = valid[:, self._grid_indices].reshape(-1, self.cfg.foveated_res, self.cfg.foveated_res, 1) + + +class RandomizedDinoTokens(DinoTokens): + def __call__(self, env, reference, checksum, batch_size=128, data_type="rgb"): + if not getattr(env, "refresh_policy_vision", True) and self.cached is not None: + return self.cached + image = env.scene["eye"].data.output[data_type] + image = image.torch if hasattr(image, "torch") else image + image = env.so101_camera_randomization.image(image) + self.cached = self.encoder(image) + return self.cached + + +class CameraRandomization(ManagerTermBase): + def __init__(self, cfg, env): + super().__init__(cfg, env) + self.camera = env.scene["eye"] + self.camera.gaze = torch.zeros(self.num_envs, 2, device=self.device) + self.retina = PlanarRetina(env.cfg.camera_hfov(), env.cfg.cmf_a(), env.cfg.resolution()).to(self.device) + self.options = settings(env.cfg.sim2real if env.cfg.sim2real is not None else {"nominal_fraction": 1.0}) + self.position = torch.tensor(self.camera.cfg.offset.pos, device=self.device).expand(self.num_envs, -1).clone() + self.rotation = torch.tensor(self.camera.cfg.offset.rot, device=self.device).expand(self.num_envs, -1).clone() + self.nominal_position, self.nominal_rotation = self.position.clone(), self.rotation.clone() + self.intrinsics = ( + torch.tensor(self.camera.cfg.camera_calibration["intrinsics"], device=self.device) + .expand(self.num_envs, -1) + .clone() + ) + self.nominal_intrinsics = self.intrinsics.clone() + self.radial = torch.zeros(self.num_envs, device=self.device) + self.targets = torch.zeros(self.num_envs, 9, device=self.device) + self.nominal = torch.ones(self.num_envs, dtype=torch.bool, device=self.device) + self.photo = torch.ones(self.num_envs, 7, device=self.device) + self.photo[:, 5:] = 0 + env.so101_camera_randomization = self + + def __call__(self, env, env_ids): + ids = torch.arange(self.num_envs, device=self.device)[slice(None) if env_ids is None else env_ids] + n = len(ids) + if n == 0: + return + cfg = self.options + strength = self.strength + env.extras.setdefault("log", {})["Randomization/camera_strength"] = strength + nominal = torch.rand(n, device=self.device) < cfg["nominal_fraction"] + self.nominal[ids] = nominal + active = (~nominal).float()[:, None] + + def uniform(width, bound): + return torch.empty(n, width, device=self.device).uniform_(-bound, bound) * active * strength + + delta = uniform(3, cfg["position_range"]) + perturb = quat_from_euler_xyz(*uniform(3, math.radians(cfg["rotation_deg"])).T) + self.position[ids] = self.nominal_position[ids] + delta + self.rotation[ids] = quat_mul(self.nominal_rotation[ids], perturb) + robot_rotation = env.scene["robot"].data.root_quat_w.torch[ids] + # Translation in the robot-base frame; rotation relative to its nominal + # camera mount. Neither label includes environment-grid coordinates. + self.targets[ids] = pose_targets(quat_apply_inverse(robot_rotation, delta), matrix_from_quat(perturb)) + self.camera.set_physical_poses(self.position[ids] + env.scene.env_origins[ids], self.rotation[ids], env_ids=ids) + self.camera.reset(env_ids=ids) + if "diagnostic_camera" in env.scene.sensors: + diagnostic = env.scene["diagnostic_camera"] + diagnostic.set_world_poses( + self.position[ids] + env.scene.env_origins[ids], + self.rotation[ids], + env_ids=ids, + convention="opengl", + ) + diagnostic.reset(env_ids=ids) + # Tutorial photometric families, held fixed for the whole episode. + # exposure, contrast, gamma, white-balance R/B, brightness, blur mix. + for index, (lo, hi) in enumerate( + ( + (0.75, 1.25), + (0.85, 1.15), + (0.85, 1.15), + (0.9, 1.1), + (0.9, 1.1), + (-0.05, 0.05), + (0, 0.5), + ) + ): + base = 0.0 if index >= 5 else 1.0 + self.photo[ids, index] = ( + base + (torch.empty(n, device=self.device).uniform_(lo, hi) - base) * active[:, 0] * strength + ) + + def visibility(self, directions): + return lens_visibility(directions[:, None], self.intrinsics, self.radial, (640, 640)).squeeze(-1) + + def gaze_direction(self, directions, ids=None): + """True scene ray -> physical pixel -> uncalibrated action coordinates.""" + selection = slice(None) if ids is None else ids + pixels = ( + directions[:, :2] / directions[:, 2:].clamp_min(1e-7) * self.intrinsics[selection, :2] + + self.intrinsics[selection, 2:] + ) + return self.retina.angles(pixels) + + @property + def strength(self): + ramp = self.options["ramp_steps"] + return min(1.0, max(0.1, self._env.common_step_counter / ramp)) if ramp else 1.0 + + def image(self, images): + from torch.nn import functional as F + + valid = self.camera.public_valid + rgb = images[..., :3].permute(0, 3, 1, 2).float() / 255 + values = self.photo[:, :, None, None] + blurred = F.avg_pool2d(rgb, 3, stride=1, padding=1, count_include_pad=False) + rgb = rgb.lerp(blurred, values[:, 6:7]).pow(values[:, 2:3]) + rgb = (rgb - 0.5) * values[:, 1:2] + 0.5 + white = torch.cat((values[:, 3:4], torch.ones_like(values[:, :1]), values[:, 4:5]), 1) + rgb = (rgb * values[:, :1] * white + values[:, 5:6]).clamp(0, 1) + # Preserve the physical camera/retinal footprint after color transforms. + return (rgb.permute(0, 2, 3, 1) * 255).round().to(torch.uint8).masked_fill(~valid, 0) + + +def extrinsics_labels(env): + state = getattr(env, "so101_camera_randomization", None) + if state is None: + return torch.zeros(env.num_envs, 9, device=env.device) + return state.targets.clone() + + +@configclass +class ExtrinsicsObservations(ObservationGroupCfg): + pose = ObservationTermCfg(func=extrinsics_labels) + enable_corruption = False + + +def configure(cfg): + """Apply physical and appearance randomization while retaining numbered SGS resets.""" + from isaaclab_tutorial.active_gaze.randomization_cfg import ( + AppearanceRandomizationEventsCfg, + RandomizedSceneAssetsCfg, + ) + + # Keep the calibrated geometry, controller scales, and mid-task reset + # distribution used by the pretrained actor. + reset = deepcopy(cfg.events.reset_from_dataset) + events = AppearanceRandomizationEventsCfg() + reset.params.update( + { + key: value + for key, value in events.reset_from_dataset.params.items() + if key not in ("dataset_path", "phase_weights", "sequential") + } + ) + events.reset_from_dataset = reset + cfg.events = events + appearance = RandomizedSceneAssetsCfg() + cfg.scene.support = appearance.support + cfg.scene.fixed_jaw_support = appearance.fixed_jaw_support + cfg.scene.moving_jaw_support = appearance.moving_jaw_support + for name in ( + "robot_visual", + "desk_visual", + "rack_visual", + "vial_body_visual", + "vial_cap_visual", + ): + setattr(cfg.scene, name, deepcopy(getattr(appearance, name))) + for spawn in cfg.scene.vial.spawn.assets_cfg: + spawn.randomize_diameters = True + configure_planar_camera(cfg) + + +def configure_planar_camera(cfg): + cfg.events.scene_camera = EventTermCfg(func=CameraRandomization, mode="reset") + cfg.scene.eye.class_type = PlanarSceneCamera + cfg.scene.eye.field_geometry = "planar" + cfg.scene.eye.update_latest_camera_pose = True + cfg.observations.vision.tokens.func = RandomizedDinoTokens diff --git a/src/isaaclab_tutorial/active_gaze/train.py b/src/isaaclab_tutorial/active_gaze/train.py new file mode 100644 index 0000000..5c858df --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/train.py @@ -0,0 +1,611 @@ +"""Train, evaluate, and visually inspect the SO-101 foveated PPO task.""" + +import argparse +import hashlib +import json +import os +from contextlib import nullcontext +from pathlib import Path + + +def main(): + import warp as wp + + wp.config.enable_backward = False + from isaaclab.app import add_launcher_args, launch_simulation + from isaaclab_tasks.utils import setup_preset_cli + + from . import TASK_ID + from .configuration import checkpoint_configuration, compose + from .configuration import metadata as config_metadata + from .sampling import iteration_metrics + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--task", default=TASK_ID) + parser.add_argument("mode", choices=("train", "play", "inspect")) + parser.add_argument("--num_envs", type=int, default=None) + parser.add_argument("--iterations", type=int, default=None) + parser.add_argument("--steps", type=int, default=600) + parser.add_argument("--seed", type=int, default=None) + parser.add_argument("--checkpoint", type=Path) + parser.add_argument("--deployment_bundle", type=Path, help="Play through an exported LEAPP bundle") + parser.add_argument("--deployment_camera", action="store_true", help="Feed the dense diagnostic camera to LEAPP") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--save_interval", type=int, default=None) + parser.add_argument("--minibatches", type=int, default=None) + parser.add_argument("--logger", choices=("tensorboard", "wandb"), default="tensorboard") + parser.add_argument("--diagnostics", action="store_true") + parser.add_argument("--measure_memory", action="store_true") + parser.add_argument("--memory_warmup", type=int, default=4) + add_launcher_args(parser) + args, overrides = setup_preset_cli(parser) + if args.task != TASK_ID: + parser.error(f"This recorder supports {TASK_ID}; use the standard Isaac Lab CLI for other tasks") + saved_settings = {} + if args.checkpoint: + saved_path = args.checkpoint.parent / "example.json" + if not saved_path.is_file(): + parser.error("Checkpoint requires its companion example.json settings") + saved_settings = json.loads(saved_path.read_text()) + try: + cfg, agent_cfg, overrides = compose(overrides, saved_settings) + except ValueError as exc: + parser.error(str(exc)) + args.num_envs = args.num_envs if args.num_envs is not None else cfg.scene.num_envs + args.iterations = args.iterations if args.iterations is not None else agent_cfg.max_iterations + args.seed = args.seed if args.seed is not None else agent_cfg.seed + args.save_interval = args.save_interval if args.save_interval is not None else agent_cfg.save_interval + args.minibatches = args.minibatches if args.minibatches is not None else agent_cfg.algorithm.num_mini_batches + args.finetune = agent_cfg.finetune + policy = cfg.policy + chunk_size = getattr(agent_cfg.algorithm, "action_chunk_size", 1) + control_gamma = agent_cfg.algorithm.gamma + + if min(args.num_envs, args.iterations, args.steps, args.save_interval, args.minibatches) <= 0: + parser.error("Environment, update, step, save, and minibatch counts must be positive") + if args.num_envs * agent_cfg.num_steps_per_env % args.minibatches: + parser.error("Minibatches must divide the rollout") + world_size = int(os.environ.get("WORLD_SIZE", "1")) + rank = int(os.environ.get("RANK", "0")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + args.distributed = world_size > 1 + if args.distributed and args.mode != "train": + parser.error("Distributed execution is supported for training only") + if args.measure_memory and not 1 <= args.memory_warmup < args.iterations: + parser.error("Memory recording needs positive warmup and subsequent updates") + if args.mode == "play" and args.checkpoint is None: + parser.error("play requires --checkpoint") + if args.deployment_bundle and chunk_size != 1: + parser.error("Deployment playback currently requires single-step actions") + if args.deployment_bundle and args.mode != "play": + parser.error("deployment_bundle is supported only for play") + if args.deployment_camera and not args.deployment_bundle: + parser.error("deployment_camera requires deployment_bundle") + if args.finetune and (args.mode != "train" or args.checkpoint is None): + parser.error("finetune requires train with a checkpoint") + shared_output = args.output.resolve() + if rank == 0 and shared_output.exists(): + parser.error("Use a new output directory for each run") + if args.distributed: + import torch + + from isaaclab_tutorial.active_gaze.learning.runner import initialize_distributed + + args.device = f"cuda:{local_rank}" + initialize_distributed() + if rank == 0: + shared_output.mkdir(parents=True) + torch.distributed.barrier() + args.output = shared_output if rank == 0 else shared_output / f"rank_{rank}" + args.output.mkdir(parents=True, exist_ok=args.distributed and rank == 0) + args.seed += rank + (args.output / "example.json").write_text( + json.dumps( + { + "task": "so101_vial", + "physics": type(cfg.sim.physics).__name__, + "distributed": { + "world_size": world_size, + "rank": rank, + "local_rank": local_rank, + "environments_per_rank": args.num_envs, + "total_environments": args.num_envs * world_size, + "minibatches_per_rank": args.minibatches, + "minibatch_size_per_rank": args.num_envs * agent_cfg.num_steps_per_env // args.minibatches, + "sgs_history": "independent per rank; metrics reduced across ranks", + }, + }, + indent=2, + ) + ) + if os.environ.get("ISAACLAB_FOVI_PROVENANCE"): + (args.output / "provenance.json").write_bytes(Path(os.environ["ISAACLAB_FOVI_PROVENANCE"]).read_bytes()) + if os.environ.get("ISAACLAB_FOVI_CALIBRATION"): + (args.output / "calibration.json").write_bytes(Path(os.environ["ISAACLAB_FOVI_CALIBRATION"]).read_bytes()) + + metadata = json.loads((args.output / "example.json").read_text()) + metadata.update(config_metadata(cfg, agent_cfg), configuration=checkpoint_configuration(overrides, agent_cfg)) + agent = agent_cfg.to_dict() + arm_scale = cfg.actions.arm_action.scale + from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import ARM_JOINTS + + metadata["control"] = { + "action_scale": [arm_scale[n] if isinstance(arm_scale, dict) else arm_scale for n in ARM_JOINTS] + + [cfg.actions.gripper_action.scale], + "physics_hz": 1.0 / cfg.sim.dt, + "control_hz": 1.0 / (cfg.sim.dt * cfg.decimation), + "policy_hz": 1.0 / (cfg.sim.dt * cfg.decimation * chunk_size), + } + if policy == "dino_language": + import torch + + from isaaclab_tutorial.active_gaze.learning.language import instruction_table + + from .language import INSTRUCTIONS + + tokens = cfg.observations.vision.tokens.params + reference, batch_size = tokens["reference"], tokens["batch_size"] + if args.deployment_bundle and batch_size != 1: + parser.error("Deployment parity requires env.observations.vision.tokens.params.batch_size=1") + if batch_size <= 0: + parser.error("DINO batch size must be positive") + canonical_reference = reference + source = Path(reference) / "source.json" + if source.is_file(): + canonical_reference = json.loads(source.read_text())["uri"] + table_path = agent_cfg.actor.instruction_table_path + if table_path is None and args.checkpoint: + table_path = args.checkpoint.parent / "instructions.pt" + table = instruction_table( + INSTRUCTIONS, + path=str(table_path) if table_path else None, + device=args.device or "cuda:0", + ) + output_table = args.output.resolve() / "instructions.pt" + torch.save(table, output_table) + agent["actor"]["instruction_table_path"] = str(output_table) + metadata["policy"].update( + dino_checkpoint=canonical_reference, + dino_checksum=tokens["checksum"], + dino_batch_size=batch_size, + instructions=list(INSTRUCTIONS), + frozen_encoders=True, + extrinsics_head=cfg.extrinsics_head(), + ) + del table + torch.cuda.empty_cache() + if cfg.goal_mode == "numbered": + from .goals import CAP_LABEL_SIZE, NEAR_GOAL_DISTANCE, RACK_LABEL_SIZE + + metadata["numbered_goals"] = dict( + rack_numbering="fixed indices 1 through 4", + vial_number="fixed per environment; balanced and shuffled at scene creation", + reset_selection="SGS conditioned on the environment's fixed cap number", + near_goal_distance=NEAR_GOAL_DISTANCE, + cap_label_size=CAP_LABEL_SIZE, + rack_label_size=RACK_LABEL_SIZE, + antialiasing="none" if cfg.renderer_backend() == "ovrtx" else None, + temporal_denoising=cfg.renderer_backend() == "ovrtx", + samples_per_pixel=4 if cfg.render_mode() == "rtpt" else None, + cmf_a=cfg.scene.eye.cmf_a, + ovstage=os.environ.get("ISAAC_LAB_OVRTX_USE_OVSTAGE"), + ) + (args.output / "example.json").write_text(json.dumps(metadata, indent=2)) + cfg.scene.num_envs = args.num_envs + cfg.seed = args.seed + cfg.log_dir = str(args.output.resolve()) + if cfg.renderer_backend() == "ovrtx": + cfg.scene.eye.renderer_cfg.log_file_path = str(args.output.resolve() / "ovrtx.log") + if args.mode == "play": + cfg.play_mode() + cfg.scene.num_envs = args.num_envs + elif args.mode == "inspect": + cfg.reset_sampling_evaluation = True + cfg.curriculum.reset_sampling.params["mode"] = "uniform" + if args.diagnostics or args.mode == "inspect" or args.deployment_camera: + cfg.enable_diagnostics() + if args.deployment_camera and cfg.sim2real is not None: + parser.error( + "deployment_camera requires the planar preset without sim2real so both policy paths use identical appearance" + ) + agent["algorithm"]["gamma"] = control_gamma**chunk_size + agent["algorithm"]["lam"] = agent_cfg.algorithm.lam**chunk_size + agent["seed"] = args.seed + agent["save_interval"] = args.save_interval + agent["algorithm"]["num_mini_batches"] = args.minibatches + agent["logger"] = ( + { + "class_name": "isaaclab_tutorial.active_gaze.training.tracking:FoviWandbWriter", + "project_name": "fovi_isaaclab_native", + "entity": "nvidia", + "group": "so101-foveated-ppo", + } + if args.logger == "wandb" + else "tensorboard" + ) + with launch_simulation(cfg, args): + from isaaclab.envs import ManagerBasedRLEnv + from isaaclab.utils.io import dump_yaml + from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper + + from .runner import SO101Runner + + env = RslRlVecEnvWrapper(ManagerBasedRLEnv(cfg), clip_actions=1.0) + if chunk_size > 1: + from isaaclab_tutorial.active_gaze.learning.chunks import ActionChunkWrapper + + env = ActionChunkWrapper(env, chunk_size, control_gamma, critic_groups=agent_cfg.obs_groups["critic"]) + else: + env.chunk_size = 1 + try: + if cfg.goal_mode == "numbered": + import torch + + counts = torch.bincount(env.unwrapped.vial_number, minlength=5)[1:].tolist() + metadata["numbered_goals"]["cap_counts"] = dict(zip(range(1, 5), counts, strict=True)) + metadata["numbered_goals"]["assignment_seed"] = cfg.seed + (args.output / "example.json").write_text(json.dumps(metadata, indent=2)) + print(f"Static cap counts (1 through 4): {counts}", flush=True) + dump_yaml(str(args.output / "env.yaml"), cfg) + (args.output / "agent.json").write_text(json.dumps(agent, indent=2)) + runner = SO101Runner(env, agent, log_dir=str(args.output), device=cfg.sim.device) + if args.checkpoint: + initialized = [] + if args.finetune: + initialized = runner.finetune(str(args.checkpoint.resolve()), map_location=cfg.sim.device) + else: + runner.load(str(args.checkpoint.resolve()), map_location=cfg.sim.device) + if args.mode == "train": + resume = { + "checkpoint": args.checkpoint.name, + "sha256": hashlib.sha256(args.checkpoint.read_bytes()).hexdigest(), + "loaded_update": runner.current_learning_iteration, + "next_update": runner.current_learning_iteration + 1, + "optimizer_state_entries": len(runner.alg.optimizer.state), + "sampler_completed_episodes": int(runner.sampler.history.episodes.sum()), + "finetune": args.finetune, + "initialized_parameters": initialized, + } + source = args.checkpoint.parent / "source.json" + if source.is_file(): + resume["source"] = json.loads(source.read_text()) + metadata["resume"] = resume + (args.output / "example.json").write_text(json.dumps(metadata, indent=2)) + (args.output / "resume.json").write_text(json.dumps(resume, indent=2)) + print("SO101_RESUME " + json.dumps(resume), flush=True) + runner.current_learning_iteration += 1 + if args.mode == "train": + before = {name: value.detach().clone() for name, value in runner.alg.actor.named_parameters()} + from isaaclab_tutorial.active_gaze.training.memory import TrainingMemoryRecorder + from isaaclab_tutorial.active_gaze.training.tracking import install_performance_metrics + + install_performance_metrics(runner) + recorder = ( + TrainingMemoryRecorder(runner, args.output / "memory.json", args.memory_warmup) + if args.measure_memory + else nullcontext() + ) + with recorder: + runner.learn(args.iterations, init_at_random_ep_len=True) + if args.distributed and args.measure_memory: + from .distributed import verify_replicas + + verify_replicas(runner, args.output / "distributed_validation.json") + changes = { + name: (value.detach() - before[name]).abs().max().item() + for name, value in runner.alg.actor.named_parameters() + } + (args.output / "parameter_updates.json").write_text(json.dumps(changes, indent=2)) + else: + record(env, runner, args) + metrics, _ = iteration_metrics(runner.sampler, 0) + (args.output / "reset_sampling.json").write_text(json.dumps(metrics, indent=2)) + finally: + env.close() + if args.distributed: + torch.distributed.destroy_process_group() + + +def record(env, runner, args): + import imageio.v2 as imageio + import numpy as np + import torch + from PIL import Image, ImageDraw + + raw = env.unwrapped + reset_checks = {} + if args.mode == "inspect" and env.num_envs > 1: + gaze = raw.action_manager.get_term("gaze") + gaze.process_actions(torch.full((env.num_envs, 2), 0.2, device=env.device)) + other_gaze = gaze.processed_actions[1:].clone() + other_vials = raw.scene["vial"].data.root_pos_w.torch[1:].clone() + camera_state = getattr(raw, "so101_camera_randomization", None) + if camera_state is not None: + other_camera = [ + getattr(camera_state, name)[1:].clone() + for name in ("position", "rotation", "intrinsics", "targets", "photo") + ] + raw.reset(env_ids=torch.tensor([0], device=env.device)) + assert torch.equal(gaze.processed_actions[1:], other_gaze) + if gaze.cache is not None: + row = raw._so101_reset_row[0] + expected = gaze.cache[row, gaze.reset_mode[0], gaze.reset_variant[0]] + assert torch.equal(gaze.processed_actions[0], expected) + elif camera_state is None: + assert not gaze.processed_actions[0].any() + else: + for name, before in zip( + ("position", "rotation", "intrinsics", "targets", "photo"), other_camera, strict=True + ): + assert torch.equal(getattr(camera_state, name)[1:], before), name + from .gaze import angles_to_direction + + assert gaze.calibration.project(angles_to_direction(gaze.processed_actions))[1].all() + torch.testing.assert_close(gaze.camera.get_world_positions(), camera_state.position + raw.scene.env_origins) + torch.testing.assert_close( + gaze.camera._view.get_world_poses()[0].torch, camera_state.position + raw.scene.env_origins + ) + assert torch.equal(raw.scene["vial"].data.root_pos_w.torch[1:], other_vials) + reset_checks = { + "selected_gaze_reset": True, + "other_gaze_preserved": True, + "other_vials_preserved": True, + "other_camera_state_preserved": camera_state is not None, + } + policy = runner.get_inference_policy(device=env.device) + deployment = None + deployment_retina = None + deployment_error = 0.0 + if args.deployment_bundle: + from isaaclab_fovi.deployment.so101.runtime import PolicyRuntime + + deployment = PolicyRuntime(args.deployment_bundle, str(env.device), retinal=not args.deployment_camera) + if deployment.contract["source_sha256"] != hashlib.sha256(args.checkpoint.read_bytes()).hexdigest(): + raise ValueError("Deployment bundle and playback checkpoint differ") + if args.deployment_camera: + from fovi.sensing.projection import CameraModel + + from isaaclab_fovi.deployment.so101.planar import PlanarRetina + from isaaclab_fovi.deployment.so101.retina import SoftwareRetina + + expected = CameraModel(**raw.scene["eye"].cfg.camera_calibration) + actual = CameraModel(**deployment.contract["camera_calibration"]) + if actual != expected: + raise ValueError("Dense simulator playback requires the nominal source-camera calibration") + deployment_retina = ( + PlanarRetina(deployment.contract["camera_hfov"], deployment.contract["cmf_a"]) + if raw.cfg.retinal_geometry() == "planar" + else SoftwareRetina( + deployment.contract["camera_calibration"], + deployment.contract["camera_hfov"], + deployment.contract["cmf_a"], + ) + ).to(env.device) + obs = env.get_observations() + frames = [] + episodes = successes = 0 + writers = [ + imageio.get_writer(str(args.output / f"env_{i}.mp4"), fps=1.0 / raw.step_dt) + for i in range(min(4, env.num_envs)) + ] + step = 0 + phase = None + + def capture(obs, reward, done, info): + nonlocal step, episodes, successes + episodes += int(done.sum()) + successes += int(raw.termination_manager.get_term("success").sum()) + retinal = raw.scene["eye"].data.output[raw.scene["eye"].cfg.data_types[0]] + retinal = retinal.torch if hasattr(retinal, "torch") else retinal + camera_state = getattr(raw, "so101_camera_randomization", None) + if camera_state is not None: + retinal = camera_state.image(retinal) + dense = None + if "diagnostic_camera" in raw.scene.sensors: + dense = raw.scene["diagnostic_camera"].data.output[raw.scene["diagnostic_camera"].cfg.data_types[0]] + dense = dense.torch if hasattr(dense, "torch") else dense + if deployment_retina is not None: + retinal = deployment_retina(dense[..., :3], raw.action_manager.get_term("gaze").processed_actions) + from .gaze import RESET_MODES + + markers = diagnostic_markers(raw) if dense is not None else None + for i, writer in enumerate(writers): + eye = Image.fromarray(retinal[i, ..., :3].cpu().numpy()).resize((384, 384), Image.Resampling.NEAREST) + canvas = Image.new("RGB", (768 if dense is not None else 384, 416)) + if dense is not None: + canvas.paste( + Image.fromarray(dense[i, ..., :3].cpu().numpy()).resize((384, 384)), + (0, 32), + ) + canvas.paste(eye, (384 if dense is not None else 0, 32)) + draw = ImageDraw.Draw(canvas) + if markers is not None: + for xy, color in zip(markers[i], ("cyan", "magenta", "lime"), strict=True): + x, y = xy[0] * 384 / 640, xy[1] * 384 / 640 + 32 + draw.ellipse((x - 3, y - 3, x + 3, y + 3), outline=color, width=2) + mode = RESET_MODES[int(raw.action_manager.get_term("gaze").reset_mode[i])] + goal_text = ( + f" vial={int(raw.vial_number[i])} target={int(raw.numbered_target_hole[i]) + 1}" + if raw.cfg.goal_mode == "numbered" + else "" + ) + draw.text( + (8, 8), + f"step={step} env={i} reset={bool(done[i])} gaze reset={mode}{goal_text} cyan:object magenta:goal green:gaze", + fill="white", + ) + if raw.cfg.policy == "dino_language": + from .language import INSTRUCTIONS + + draw.text((8, 20), INSTRUCTIONS[0], fill="white") + writer.append_data(np.asarray(canvas)) + if i == 0 and step % 90 == 0: + canvas.save(args.output / f"frame_{step:04d}.png") + elif step % 90 == 0: + canvas.save(args.output / f"frame_{step:04d}_env_{i}.png") + if step % 90 == 0: + frames.append( + { + "step": step, + "gaze": raw.action_manager.get_term("gaze").processed_actions[0].tolist(), + "phase": phase if args.mode == "inspect" else None, + "reset_category": raw.reset_sampling.bin_names[phase] if args.mode == "inspect" else None, + "vial_number": raw.vial_number.tolist() if raw.cfg.goal_mode == "numbered" else None, + "gaze_reset_mode": int(raw.action_manager.get_term("gaze").reset_mode[0]), + "vial": raw.scene["vial"].data.root_pos_w.torch[0].tolist(), + "source_coverage": source_coverage(raw), + "camera_randomization": { + name: getattr(camera_state, name).tolist() + for name in ("position", "rotation", "intrinsics", "radial", "targets", "photo") + } + if camera_state is not None + else None, + } + ) + step += 1 + + with torch.inference_mode(): + try: + while step < args.steps: + if args.mode == "inspect": + if step % 90 == 0: + reset = raw.event_manager.get_term_cfg("reset_from_dataset").func + phase = (step // 90) % len(raw.reset_sampling.bin_names) + reset.row_weights = (raw.reset_sampling.phases == phase).float() + if raw.cfg.goal_mode == "numbered": + # Stock late-stage rows mostly surround slot 1. Some bins + # therefore cannot exist for every immutable cap identity. + missing = reset.row_weights.reshape(-1, 4).sum(0) == 0 + fallback = missing[reset.states["target_hole"]] & (reset.states["phase"] == 0) + reset.row_weights[fallback] = 1.0 + obs, _ = env.reset() + actions = torch.zeros(env.num_envs, env.num_actions, device=env.device) + # Sweep electronically, leaving robot commands neutral. + plan = actions.reshape(env.num_envs, env.chunk_size, -1) + plan[..., -2] = 0.10 * np.sin(step * 0.08) + plan[..., -1] = 0.10 * np.cos(step * 0.08) + if step % 90 == 0: + actions.zero_() + else: + # Match the deployed single-robot batch. BF16 DINO and GPU + # GEMM kernels can change numerics at different batch sizes. + actions = ( + torch.cat([policy(obs[i : i + 1]) for i in range(env.num_envs)]) + if deployment is not None + else policy(obs) + ) + if deployment is not None: + sensor = raw.scene["diagnostic_camera" if args.deployment_camera else "eye"] + image = sensor.data.output[sensor.cfg.data_types[0]] + image = image.torch if hasattr(image, "torch") else image + camera_state = getattr(raw, "so101_camera_randomization", None) + if camera_state is not None and not args.deployment_camera: + image = camera_state.image(image) + exported = torch.stack( + [ + torch.as_tensor( + deployment.infer(obs["proprio"][i], image[i, ..., :3]), device=env.device + ) + for i in range(env.num_envs) + ] + ) + deployment_error = max(deployment_error, (exported - actions).abs().max().item()) + if not args.deployment_camera: + torch.testing.assert_close(exported, actions, atol=2e-4, rtol=2e-4) + actions = exported + if env.chunk_size > 1: + remaining = args.steps - step + if args.mode == "inspect": + remaining = min(remaining, 90 - step % 90) + obs, _, _, _ = env.step( + actions, + control_steps=min(env.chunk_size, remaining), + render_every_step=True, + observer=capture, + ) + else: + obs, reward, done, info = env.step(actions) + capture(obs, reward, done, info) + finally: + for writer in writers: + writer.close() + (args.output / "evaluation.json").write_text( + json.dumps( + { + "mode": args.mode, + "steps": args.steps, + "episodes": episodes, + "successes": successes, + "frames": frames, + "checkpoint": str(args.checkpoint), + "reset_checks": reset_checks, + "deployment_bundle": str(args.deployment_bundle) if args.deployment_bundle else None, + "deployment_input": "dense_camera" if args.deployment_camera else "retinal", + "deployment_max_action_difference": deployment_error if deployment is not None else None, + }, + indent=2, + ) + ) + + +def source_coverage(env): + """Project task body centers through the fixed physical pinhole camera.""" + import torch + from fovi.sensing.projection import CameraModel + from isaaclab.utils.math import quat_apply_inverse + + cfg = env.cfg.scene.eye + state = getattr(env, "so101_camera_randomization", None) + robot = env.scene["robot"].data.body_pos_w.torch + points = torch.cat( + [ + robot, + env.scene["vial"].data.root_pos_w.torch[:, None], + env.scene["rack"].data.root_pos_w.torch[:, None], + ], + dim=1, + ) + origins = env.scene.env_origins + origins = origins.torch if hasattr(origins, "torch") else origins + position = origins + (points.new_tensor(cfg.offset.pos) if state is None else state.position) + rotation = points.new_tensor(cfg.offset.rot).expand(len(points), 4) if state is None else state.rotation + rotation = rotation[:, None].expand(*points.shape[:2], 4) + directions = quat_apply_inverse(rotation.reshape(-1, 4), (points - position[:, None]).reshape(-1, 3)) + directions *= directions.new_tensor((1, -1, -1)) + if state is None: + _, visible = CameraModel(**cfg.camera_calibration).project(directions) + else: + from .camera_geometry import lens_visibility + + visible = lens_visibility(directions.reshape(*points.shape), state.intrinsics, state.radial, (640, 640)) + return float(visible.float().mean()) + + +def diagnostic_markers(env): + import torch + + from .gaze import angles_to_direction, camera_directions, target_centers + + cfg = env.cfg.scene.eye + gaze = env.action_manager.get_term("gaze") + poses = [ + torch.cat((env.scene[name].data.root_pos_w.torch, env.scene[name].data.root_quat_w.torch), -1) + for name in ("vial", "rack") + ] + if getattr(env.cfg, "goal_mode", "nearest") == "numbered": + from .goals import CAP_LABEL_POSITION, RACK_LABEL_OFFSETS + + points = target_centers(*poses, env.numbered_target_hole, CAP_LABEL_POSITION, RACK_LABEL_OFFSETS) + else: + points = target_centers(*poses) + position = gaze.camera.get_world_positions() + state = getattr(env, "so101_camera_randomization", None) + rotation = position.new_tensor(cfg.offset.rot) if state is None else state.rotation + directions = [camera_directions(point, position, rotation) for point in points] + directions.append(angles_to_direction(gaze.processed_actions)) + pixels = [gaze.calibration.project(direction)[0] for direction in directions] + return torch.stack(pixels, dim=1).cpu().numpy() + + +if __name__ == "__main__": + main() diff --git a/src/isaaclab_tutorial/active_gaze/training/__init__.py b/src/isaaclab_tutorial/active_gaze/training/__init__.py new file mode 100644 index 0000000..6dbb75e --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/training/__init__.py @@ -0,0 +1 @@ +"""Training evaluation, recording, and memory calibration utilities.""" diff --git a/src/isaaclab_tutorial/active_gaze/training/calibrate.py b/src/isaaclab_tutorial/active_gaze/training/calibrate.py new file mode 100644 index 0000000..5cd44d8 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/training/calibrate.py @@ -0,0 +1,116 @@ +"""Training process launch and distributed memory measurement helpers.""" + +import math +import os +import signal +import subprocess +import sys +from pathlib import Path + + +def memory_budget(total: int, fraction: float, limit: int | None = None) -> float: + return min(total * fraction, limit) if limit is not None else total * fraction + + +def valid_measurement(data: dict, measured: int, fraction: float, limit: int | None = None) -> bool: + """An estimate, incomplete update window, or nonfinite result cannot qualify.""" + return ( + measured > 0 + and data.get("complete") is True + and not data.get("error") + and data.get("measured_updates") == measured + and 0 < data.get("peak_conservative_bytes", 0) <= memory_budget(data.get("total_bytes", 0), fraction, limit) + and math.isfinite(data.get("mean_total_fps", math.nan)) + and data["mean_total_fps"] > 0 + and all(valid_measurement(row, measured, fraction, limit) for row in data.get("ranks", [])) + ) + + +def aggregate_ranks(reports: list[dict]) -> dict: + """Require every rank and retain its evidence; qualify the worst memory peak.""" + first = reports[0] + expected = len(reports) + if {row["rank"] for row in reports} != set(range(expected)): + raise ValueError("Distributed measurement is missing or duplicates a rank") + for key in ( + "gpu", + "world_size", + "num_envs", + "rollout_steps", + "action_chunk_size", + "minibatch_size", + "measured_updates", + ): + if any(row[key] != first[key] for row in reports): + raise ValueError(f"Distributed measurement differs across ranks: {key}") + if first["world_size"] != expected: + raise ValueError("Distributed measurement world size does not match reports") + result = first | { + "ranks": reports, + "complete": all(row["complete"] for row in reports), + "error": next((row["error"] for row in reports if row.get("error")), None), + "gpu_uuid": [row["gpu_uuid"] for row in reports], + "total_bytes": min(row["total_bytes"] for row in reports), + } + for key in ( + "peak_device_bytes", + "peak_conservative_bytes", + "peak_torch_allocated_bytes", + "peak_torch_reserved_bytes", + ): + result[key] = max(row[key] for row in reports) + updates = [] + for index in range(first["measured_updates"]): + rows = [row["updates"][index] for row in reports] + if len({row["iteration"] for row in rows}) != 1: + raise ValueError("Distributed updates are not aligned") + collect = max(row["collection_time"] for row in rows) + total = max(row["collection_time"] + row["learning_time"] for row in rows) + learn = total - collect + decisions = first["num_envs"] * first["rollout_steps"] * expected + updates.append( + rows[0] + | { + "total_fps": decisions / (collect + learn), + "rollout_fps": decisions / collect, + "collection_time": collect, + "learning_time": learn, + } + ) + result["updates"] = updates + result["mean_total_fps"] = ( + decisions * len(updates) / sum(row["collection_time"] + row["learning_time"] for row in updates) + ) + result["mean_control_fps"] = result["mean_total_fps"] * first["action_chunk_size"] + return result + + +def training_command(num_gpus: int, module: str) -> list[str]: + """One simulator and native RSL-RL rank per GPU on a single node.""" + if num_gpus < 1: + raise ValueError("num_gpus must be positive") + command = [sys.executable, "-m"] + if num_gpus > 1: + command += [ + "torch.distributed.run", + "--standalone", + "--nnodes=1", + f"--nproc_per_node={num_gpus}", + "--module", + ] + return command + [module] + + +def run_trial(command: list[str], log: Path, timeout: int) -> int: + with log.open("w") as handle: + process = subprocess.Popen(command, stdout=handle, stderr=subprocess.STDOUT, start_new_session=True) + try: + return process.wait(timeout=timeout) + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() diff --git a/src/isaaclab_tutorial/active_gaze/training/evaluation.py b/src/isaaclab_tutorial/active_gaze/training/evaluation.py new file mode 100644 index 0000000..b9f217e --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/training/evaluation.py @@ -0,0 +1,238 @@ +"""Periodic deterministic rollout blocks, isolated from PPO collection and updates.""" + +import json +import math +import time +from contextlib import contextmanager +from dataclasses import dataclass, field +from pathlib import Path + +import torch +from rsl_rl.utils import check_nan + + +@dataclass(frozen=True) +class EvaluationConfig: + enabled: bool = True + frequency_episodes: float = 100.0 + duration_episodes: float = 1.0 + early_episodes: list[float] = field(default_factory=list) + video: bool = True + video_envs: int = 3 + + def __post_init__(self): + for name in ("frequency_episodes", "duration_episodes"): + value = getattr(self, name) + if isinstance(value, bool) or not math.isfinite(value) or value <= 0: + raise ValueError(f"evaluation.{name} must be finite and positive") + if type(self.enabled) is not bool or type(self.video) is not bool: + raise ValueError("evaluation.enabled and video must be booleans") + if type(self.video_envs) is not int or self.video_envs < 1: + raise ValueError("evaluation.video_envs must be a positive integer") + if not isinstance(self.early_episodes, (list, tuple)) or any( + isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0 + for value in self.early_episodes + ): + raise ValueError("evaluation.early_episodes must contain finite positive numbers") + object.__setattr__(self, "early_episodes", sorted(set(self.early_episodes))) + + def control_steps(self, episode_length: int) -> tuple[int, int]: + steps = [] + for value in (self.frequency_episodes, self.duration_episodes, *self.early_episodes): + exact = value * episode_length + count = round(exact) + if count < 1 or not math.isclose(exact, count, rel_tol=0, abs_tol=1e-6): + raise ValueError("Evaluation durations must resolve to whole control steps") + steps.append(count) + return tuple(steps[:2]) + + +class PeriodicEvaluation: + """Use training control steps for cadence, independent of GPU or environment count.""" + + def __init__(self, env, cfg: dict): + self.cfg = EvaluationConfig(**cfg) + self.frequency, self.duration = self.cfg.control_steps(env.max_episode_length) + self.early_steps = tuple(round(value * env.max_episode_length) for value in self.cfg.early_episodes) + + def due(self, previous: int, current: int) -> bool: + return self.cfg.enabled and ( + current // self.frequency > previous // self.frequency + or any(previous < step <= current for step in self.early_steps) + ) + + def run(self, runner): + env = runner.env + with coordinated_errors(runner): + obs, totals, elapsed, output, recorder = self._rollout(runner) + if runner.is_distributed: + torch.distributed.all_reduce(totals) + torch.distributed.all_reduce(elapsed, op=torch.distributed.ReduceOp.MAX) + episodes, reward_sum, length_sum, successes = totals.tolist() + metrics = { + "Eval/completed_episodes": episodes, + "Eval/control_steps_per_env": self.duration, + "Eval/duration_episodes": self.duration / env.max_episode_length, + "Eval/wall_seconds": elapsed.item(), + } + if episodes: + metrics.update( + { + "Eval/mean_return": reward_sum / episodes, + "Eval/mean_episode_control_steps": length_sum / episodes, + "Eval/success_rate": successes / episodes, + } + ) + with coordinated_errors(runner): + if output is not None: + metadata = { + "training_iteration": runner.current_learning_iteration, + "training_control_steps_per_env": runner.training_control_steps, + "policy": "deterministic actor mean; no oracle action substitution", + "control_fps": 1 / env.unwrapped.step_dt, + "policy_fps": 1 / env.decision_dt, + "action_chunk_size": env.chunk_size, + "metrics": metrics, + } + if recorder is not None: + metadata.update( + frame_count=recorder.frames, + videos={f"env_{i}": path.name for i, path in enumerate(recorder.paths)}, + recorded_envs=recorder.num_envs, + instruction_segments=recorder.segments, + video_fps=1 / env.decision_dt, + source="post-chunk native foveated RGB; no intermediate camera captures", + ) + (output / "evaluation.json").write_text(json.dumps(metadata, indent=2) + "\n") + writer = runner.logger.writer + if writer is not None: + for key, value in metrics.items(): + writer.add_scalar(key, value, runner.current_learning_iteration) + if recorder is not None: + from .tracking import FoviWandbWriter + + if isinstance(writer, FoviWandbWriter): + for path in recorder.paths: + writer.save_video(path, runner.current_learning_iteration) + print( + f"ISAACLAB_FOVI_EVAL complete rank={runner.gpu_global_rank} " + json.dumps(metrics), + flush=True, + ) + return obs.to(runner.device) + + def _rollout(self, runner): + env = runner.env + policy = runner.alg.get_policy() + instructions = getattr(runner.alg.actor, "instructions", ()) + returns = torch.zeros(env.num_envs, device=env.device) + lengths = torch.zeros_like(returns) + # Completed episodes, returns, lengths, successes. Reduce sums, not rank means. + totals = torch.zeros(4, device=env.device, dtype=torch.float64) + recorder = None + output = None + count = min(self.cfg.video_envs, env.num_envs) + if runner.gpu_global_rank == 0 and runner.logger.log_dir is not None: + output = Path(runner.logger.log_dir) / "evaluation" / f"step_{runner.training_control_steps:09d}" + output.mkdir(parents=True, exist_ok=True) + if self.cfg.video: + from .video import ObservationVideoRecorder + + recorder = ObservationVideoRecorder(output, 1 / env.decision_dt, count) + + def observe(obs, reward, done, extras): + if runner.cfg.get("check_for_nan", True): + check_nan(obs, reward, done) + returns.add_(reward) + lengths.add_(1) + finished = done.bool() + totals[0].add_(finished.sum()) + totals[1].add_(returns[finished].sum()) + totals[2].add_(lengths[finished].sum()) + totals[3].add_((env.unwrapped.termination_manager.get_term("success") & finished).sum()) + returns[finished] = 0 + lengths[finished] = 0 + + print( + f"ISAACLAB_FOVI_EVAL start rank={runner.gpu_global_rank} training_control_steps={runner.training_control_steps} control_steps={self.duration}", + flush=True, + ) + start = time.perf_counter() + # Restore nested module modes exactly, including deliberately frozen children. + models = [runner.alg.actor, runner.alg.critic] + if runner.alg.rnd is not None: + models.append(runner.alg.rnd) + modes = {module: module.training for model in models for module in model.modules()} + rendering = env.unwrapped.render_enabled + try: + runner.alg.eval_mode() + env.unwrapped.render_enabled = True + with torch.inference_mode(): + obs, _ = env.reset() + policy.reset() + for step in range(0, self.duration, env.chunk_size): + with torch.autocast( + torch.device(runner.device).type, + dtype=torch.bfloat16, + enabled=runner.alg.use_mixed_precision, + ): + actions = policy(obs.to(runner.device)) + obs, _, done, _ = env.step( + actions.to(env.device), + control_steps=min(env.chunk_size, self.duration - step), + observer=observe, + ) + if recorder is not None: + # Vision already refreshed at this boundary. Reading it + # in the per-control-step observer would trigger a lazy + # render of the entire tiled camera between decisions. + rgb = env.unwrapped.scene["eye"].data.output["rgb"] + rgb = rgb.torch if hasattr(rgb, "torch") else rgb + captions = [""] * count + if instructions: + indices = obs["instruction"][:count, 0].long().cpu().tolist() + captions = [instructions[i] for i in indices] + recorder.capture(rgb[:count].cpu().numpy(), captions) + policy.reset(done) + finally: + try: + if recorder is not None: + recorder.close() + finally: + for module, training in modes.items(): + module.training = training + # Discard evaluation state and partial training episodes. The caller + # must collect from this fresh observation, never its pre-eval buffer. + env.unwrapped.render_enabled = rendering + with torch.inference_mode(): + obs, _ = env.reset() + policy.reset() + runner.logger.cur_reward_sum.zero_() + runner.logger.cur_episode_length.zero_() + runner.logger.ep_extras.clear() + if runner.alg.rnd is not None: + # Match the discarded training episodes in native RND logging. + runner.logger.cur_ereward_sum.zero_() + runner.logger.cur_ireward_sum.zero_() + elapsed = torch.tensor(time.perf_counter() - start, device=env.device) + return obs, totals, elapsed, output, recorder + + +@contextmanager +def coordinated_errors(runner): + """Let every rank leave an evaluation phase before any rank resumes PPO. + + A rank-zero encoder/upload failure must not strand peers in the next gradient + collective. Healthy ranks finish this bounded phase, then all ranks raise. + """ + error = None + try: + yield + except Exception as exc: + error = exc + failed = torch.tensor(int(error is not None), device=runner.device) + if runner.is_distributed: + torch.distributed.all_reduce(failed, op=torch.distributed.ReduceOp.MAX) + if error is not None: + raise error + if failed.item(): + raise RuntimeError("Evaluation failed on another rank; stopping training") diff --git a/src/isaaclab_tutorial/active_gaze/training/memory.py b/src/isaaclab_tutorial/active_gaze/training/memory.py new file mode 100644 index 0000000..2dcbd7d --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/training/memory.py @@ -0,0 +1,138 @@ +"""Measure real rollout/update memory, including allocations outside PyTorch.""" + +import json +import math +import threading +from pathlib import Path + + +def minibatch_count(num_envs: int, rollout_steps: int, minibatch_size: int) -> int: + """Translate a sample count into RSL-RL's batch count without dropping transitions.""" + total = num_envs * rollout_steps + if min(num_envs, rollout_steps, minibatch_size) <= 0 or total % minibatch_size: + raise ValueError("Minibatch size must be positive and divide the complete rollout.") + return total // minibatch_size + + +class TrainingMemoryRecorder: + """Post-warmup device-wide NVML usage plus exact PyTorch allocator peaks. + + Use a dedicated GPU: device-wide memory includes RTX, PhysX, Warp, and any + other process on that GPU. NVML UUID lookup respects CUDA device remapping. + The runner's logging callback marks completed updates, not printed log lines. + """ + + def __init__(self, runner, output: Path, warmup: int = 4, interval: float = 0.02): + import pynvml + import torch + + if warmup < 1 or interval <= 0: + raise ValueError("Memory recording requires positive warmup and polling interval.") + self.runner, self.output, self.warmup = runner, output, warmup + self.torch, self.nvml = torch, pynvml + self.device = runner.device + self.properties = torch.cuda.get_device_properties(self.device) + pynvml.nvmlInit() + self.handle = pynvml.nvmlDeviceGetHandleByUUID(str(self.properties.uuid)) + self.interval = interval + self.stop_event = threading.Event() + self.lock = threading.Lock() + self.active = False + self.peak = 0 + self.allocator_adjusted_peak = 0 + self.completed = 0 + self.samples = [] + self.error = None + self.original_log = runner.logger.log + self.thread = threading.Thread(target=self._poll, name="isaaclab_fovi-memory", daemon=True) + + def _sample(self): + with self.lock: + if self.active: + used = self.nvml.nvmlDeviceGetMemoryInfo(self.handle).used + self.peak = max(self.peak, used) + # Add any allocator peak missed between NVML polls. This is conservative: + # non-Torch and allocator maxima need not occur at the same instant. + reserved = self.torch.cuda.memory_reserved(self.device) + allocator_peak = self.torch.cuda.max_memory_reserved(self.device) + self.allocator_adjusted_peak = max( + self.allocator_adjusted_peak, used + max(0, allocator_peak - reserved) + ) + + def _poll(self): + try: + while not self.stop_event.wait(self.interval): + self._sample() + except Exception as exc: + self.error = f"{type(exc).__name__}: {exc}" + + def _log(self, **kwargs): + self.original_log(**kwargs) + if not all(math.isfinite(float(v)) for v in kwargs["loss_dict"].values()): + raise RuntimeError("Nonfinite training loss during memory measurement.") + self.completed += 1 + if self.completed == self.warmup: + self.torch.cuda.synchronize(self.device) + with self.lock: + self.torch.cuda.reset_peak_memory_stats(self.device) + self.active = True + self._sample() + elif self.completed > self.warmup: + self._sample() + steps = self.runner.env.num_envs * self.runner.cfg["num_steps_per_env"] + self.samples.append( + { + "iteration": kwargs["it"], + "rollout_fps": steps / kwargs["collect_time"], + "total_fps": steps / (kwargs["collect_time"] + kwargs["learn_time"]), + "collection_time": kwargs["collect_time"], + "learning_time": kwargs["learn_time"], + } + ) + + def __enter__(self): + self.runner.logger.log = self._log + self.thread.start() + return self + + def __exit__(self, exc_type, exc, traceback): + self.stop_event.set() + self.thread.join(timeout=5) + self.runner.logger.log = self.original_log + try: + self._sample() + info = self.nvml.nvmlDeviceGetMemoryInfo(self.handle) + decisions = self.runner.env.num_envs * self.runner.cfg["num_steps_per_env"] * len(self.samples) + total_time = sum(s["collection_time"] + s["learning_time"] for s in self.samples) + mean_fps = decisions / total_time if total_time else 0.0 + data = { + "complete": exc_type is None and not self.error and bool(self.samples), + "error": str(exc) if exc else self.error, + "gpu": self.properties.name, + "gpu_uuid": str(self.properties.uuid), + "total_bytes": info.total, + "peak_device_bytes": self.peak, + "peak_conservative_bytes": self.allocator_adjusted_peak, + "peak_torch_allocated_bytes": self.torch.cuda.max_memory_allocated(self.device), + "peak_torch_reserved_bytes": self.torch.cuda.max_memory_reserved(self.device), + "warmup_updates": self.warmup, + "measured_updates": len(self.samples), + "num_envs": self.runner.env.num_envs, + "action_chunk_size": self.runner.env.chunk_size, + "world_size": self.runner.gpu_world_size, + "rank": self.runner.gpu_global_rank, + "rollout_steps": self.runner.cfg["num_steps_per_env"], + "minibatch_size": self.runner.env.num_envs + * self.runner.cfg["num_steps_per_env"] + // self.runner.alg.num_mini_batches, + "mean_total_fps": mean_fps, + "mean_control_fps": mean_fps * self.runner.env.chunk_size, + "updates": self.samples, + } + self.output.parent.mkdir(parents=True, exist_ok=True) + self.output.write_text(json.dumps(data, indent=2) + "\n") + print("ISAACLAB_FOVI_MEMORY " + json.dumps(data), flush=True) + finally: + self.nvml.nvmlShutdown() + if exc_type is None and not data["complete"]: + raise RuntimeError(f"Memory measurement incomplete: {data['error']}") diff --git a/src/isaaclab_tutorial/active_gaze/training/tracking.py b/src/isaaclab_tutorial/active_gaze/training/tracking.py new file mode 100644 index 0000000..3bf750e --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/training/tracking.py @@ -0,0 +1,106 @@ +"""Native RSL-RL W&B logging with portable task inputs and source provenance.""" + +import json +import os +from dataclasses import asdict +from pathlib import Path + +from rsl_rl.utils.wandb_log_writer import WandbLogWriter + + +def install_performance_metrics(runner): + """Keep native decision FPS and add explicit, distributed control-step FPS.""" + import torch + + original = runner.logger.log + + def log(**kwargs): + collect = kwargs["collect_time"] + total = collect + kwargs["learn_time"] + if runner.is_distributed: + timings = torch.tensor([collect, total], device=runner.device) + torch.distributed.all_reduce(timings, op=torch.distributed.ReduceOp.MAX) + collect, total = timings.tolist() + learn = total - collect + kwargs = kwargs | {"collect_time": collect, "learn_time": learn} + original(**kwargs) + writer = runner.logger.writer + if writer is not None: + decisions = runner.env.num_envs * runner.cfg["num_steps_per_env"] * runner.gpu_world_size + controls = decisions * runner.env.chunk_size + for key, value in { + "Perf/decision_fps": decisions / (collect + learn), + "Perf/control_fps": controls / (collect + learn), + "Perf/control_fps_per_gpu": controls / (collect + learn) / runner.gpu_world_size, + "Perf/rollout_control_fps": controls / collect, + "Perf/world_size": runner.gpu_world_size, + "Train/control_steps": runner.logger.tot_timesteps * runner.env.chunk_size, + }.items(): + writer.add_scalar(key, value, kwargs["it"]) + + runner.logger.log = log + + +class FoviWandbWriter(WandbLogWriter): + def store_config(self, env_cfg, train_cfg): + """Record the active configuration when an existing W&B run resumes.""" + import wandb + + env = env_cfg.to_dict() if hasattr(env_cfg, "to_dict") else asdict(env_cfg) + wandb.config.update({"train_cfg": train_cfg, "env_cfg": env}, allow_val_change=wandb.run.resumed) + + def save_video(self, path: Path, it: int): + """Log each block once, including native RSL-RL's subsequent video scan.""" + import wandb + + identity = str(path.resolve()) + if identity not in self.logged_videos: + wandb.log({f"Eval/observations/{path.stem}": wandb.Video(identity, format="mp4")}, step=it) + self.logged_videos.add(identity) + + def __init__(self, log_dir: str, project_name: str, entity: str, group: str | None = None): + # RSL-RL's writer currently reads WANDB_USERNAME, while W&B reads WANDB_ENTITY. + os.environ["WANDB_USERNAME"] = os.environ["WANDB_ENTITY"] = entity + if group: + os.environ["WANDB_RUN_GROUP"] = group + super().__init__(log_dir=log_dir, project_name=project_name) + import wandb + + settings_path = Path(log_dir) / "config.json" + if not settings_path.is_file(): + # The standalone SO-101 launcher preserves its existing checkpoint metadata. + settings_path = Path(log_dir) / "example.json" + settings = json.loads(settings_path.read_text()) + wandb.config.update({"isaaclab_fovi": settings}, allow_val_change=wandb.run.resumed) + provenance_path = Path(log_dir) / "provenance.json" + if provenance_path.is_file(): + provenance = json.loads(provenance_path.read_text()) + wandb.config.update( + { + "source": { + key: provenance.get(key) + for key in ( + "bundle_id", + "isaaclab_commit", + "image", + "runtime", + "workflow_id", + ) + } + }, + allow_val_change=wandb.run.resumed, + ) + for name in ( + "config.json", + "example.json", + "agent.json", + "env.yaml", + "instructions.pt", + "gaze_reset_cache.pt", + "calibration.json", + "provenance.json", + ): + path = Path(log_dir) / name + if path.is_file(): + self.save_file(str(path)) + print(f"ISAACLAB_FOVI_WANDB {wandb.run.url}", flush=True) diff --git a/src/isaaclab_tutorial/active_gaze/training/video.py b/src/isaaclab_tutorial/active_gaze/training/video.py new file mode 100644 index 0000000..5ec8e90 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/training/video.py @@ -0,0 +1,75 @@ +"""Record native 2D observations with instruction captions. + +Record each environment separately, with its instruction caption. Frames stream +into FFmpeg processes without a plotting runtime or whole-video frame buffers. +""" + +import textwrap +from contextlib import ExitStack +from pathlib import Path + +import imageio.v2 as imageio +import numpy as np +from PIL import Image, ImageDraw, ImageFont + + +class ObservationVideoRecorder: + """One captioned native RGB video per recorded environment.""" + + def __init__(self, directory: Path, fps: float, num_envs: int): + self.num_envs = num_envs + self.frames = 0 + self.segments = [] + self._instructions = None + self._font = ImageFont.load_default(size=16) + directory.mkdir(parents=True, exist_ok=True) + self.paths = [directory / f"env_{index}.mp4" for index in range(num_envs)] + self._stack = ExitStack() + try: + self.writers = [ + self._stack.enter_context( + imageio.get_writer( + str(path), + fps=fps, + codec="libx264", + pixelformat="yuv420p", + quality=None, + ffmpeg_params=["-crf", "18", "-threads", "1", "-movflags", "+faststart"], + ) + ) + for path in self.paths + ] + except Exception: + self._stack.close() + raise + + def capture(self, images, instructions): + """Images are uint8 NHWC camera output; captions sit outside the image.""" + if images.ndim != 4 or images.shape[0] != self.num_envs or images.shape[-1] != 3: + raise ValueError("Expected one native HWC RGB observation per recorded environment") + if images.dtype != np.uint8 or len(instructions) != self.num_envs: + raise ValueError("Observation video requires uint8 RGB and matching instructions") + instructions = tuple(instructions) + if instructions != self._instructions: + self.segments.append({"start_frame": self.frames, "instructions": instructions}) + self._instructions = instructions + for index, (rgb, instruction, writer) in enumerate(zip(images, instructions, self.writers, strict=True)): + frame = Image.new("RGB", (320, 320), "#f4f5f1") + draw = ImageDraw.Draw(frame) + draw.multiline_text( + (12, 6), + textwrap.fill(f"Env {index}: {instruction}", width=32), + font=self._font, + fill="#182c27", + spacing=2, + ) + # Nearest-neighbor enlargement preserves the native pixel grid. + image = Image.fromarray(rgb) + scale = 256 / max(image.size) + image = image.resize(tuple(round(x * scale) for x in image.size), Image.Resampling.NEAREST) + frame.paste(image, ((320 - image.width) // 2, 60)) + writer.append_data(np.asarray(frame)) + self.frames += 1 + + def close(self): + self._stack.close() diff --git a/src/isaaclab_tutorial/active_gaze/transfer_options.py b/src/isaaclab_tutorial/active_gaze/transfer_options.py new file mode 100644 index 0000000..5a6975f --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/transfer_options.py @@ -0,0 +1,32 @@ +"""Typed camera randomization settings for the SO-101 transfer preset.""" + +import math + +from isaaclab.utils import configclass + + +@configclass +class CameraRandomizationCfg: + position_range: float = 0.03 + rotation_deg: float = 7.0 + nominal_fraction: float = 0.2 + ramp_steps: int = 30000 + + def validate_config(self): + settings(self) + + +DEFAULTS = CameraRandomizationCfg().to_dict() + + +def settings(overrides=None): + if isinstance(overrides, CameraRandomizationCfg): + overrides = overrides.to_dict() + result = DEFAULTS | (overrides or {}) + if set(result) != set(DEFAULTS): + raise ValueError("Unknown SO-101 sim2real setting") + if any(not math.isfinite(v) or v < 0 for v in result.values()): + raise ValueError("Sim2real ranges must be finite and nonnegative") + if result["nominal_fraction"] > 1: + raise ValueError("Invalid nominal sampling fraction") + return result diff --git a/src/isaaclab_tutorial/assets/numbers/__init__.py b/src/isaaclab_tutorial/assets/numbers/__init__.py new file mode 100644 index 0000000..c1babd6 --- /dev/null +++ b/src/isaaclab_tutorial/assets/numbers/__init__.py @@ -0,0 +1,5 @@ +"""Prebuilt number decals for the SO-101 task.""" + +from pathlib import Path + +LABEL_ASSETS = Path(__file__).parent diff --git a/src/isaaclab_tutorial/assets/numbers/generate.py b/src/isaaclab_tutorial/assets/numbers/generate.py new file mode 100644 index 0000000..142901d --- /dev/null +++ b/src/isaaclab_tutorial/assets/numbers/generate.py @@ -0,0 +1,103 @@ +"""Generate four static, reusable number decals; consumers set their physical size. + +Each numeral has its own texture and USD asset, with no runtime material writes. +No rigid body or collider is authored. Z is the surface normal, Y is text-up. +""" + +import argparse +from pathlib import Path + +from PIL import Image, ImageDraw, ImageFont +from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdPhysics, UsdShade + +CELL = 256 +FONT_SIZE = 260 + + +def generate(output: Path, font: Path): + output.mkdir(parents=True, exist_ok=True) + face = ImageFont.truetype(str(font), FONT_SIZE) + for number in range(1, 5): + image = Image.new("RGB", (CELL, CELL), "white") + draw = ImageDraw.Draw(image) + text = str(number) + left, top, right, bottom = draw.textbbox((0, 0), text, font=face) + draw.text( + ((CELL - right + left) / 2 - left, (CELL - bottom + top) / 2 - top), + text, + font=face, + fill="black", + ) + image.save(output / f"number_{number}.png") + generate_label(output, number) + generate_review(output) + + +def generate_label(output, number): + stage = Usd.Stage.CreateNew(str(output / f"number_{number}.usda")) + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + UsdGeom.SetStageMetersPerUnit(stage, 1) + root = UsdGeom.Xform.Define(stage, "/NumberLabel") + stage.SetDefaultPrim(root.GetPrim()) + mesh = UsdGeom.Mesh.Define(stage, "/NumberLabel/Decal") + mesh.CreatePointsAttr([(-0.5, -0.5, 0), (0.5, -0.5, 0), (0.5, 0.5, 0), (-0.5, 0.5, 0)]) + mesh.CreateFaceVertexCountsAttr([4]) + mesh.CreateFaceVertexIndicesAttr([0, 1, 2, 3]) + mesh.CreateSubdivisionSchemeAttr("none") + mesh.CreateDoubleSidedAttr(False) + uv = UsdGeom.PrimvarsAPI(mesh).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, "vertex") + uv.Set([(0, 0), (1, 0), (1, 1), (0, 1)]) + material = UsdShade.Material.Define(stage, "/NumberLabel/Looks/Ink") + shader = UsdShade.Shader.Define(stage, "/NumberLabel/Looks/Ink/Shader") + shader.SetSourceAsset(Sdf.AssetPath("OmniPBR.mdl"), "mdl") + shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") + out = shader.CreateOutput("out", Sdf.ValueTypeNames.Token) + out.SetRenderType("material") + material.CreateSurfaceOutput("mdl").ConnectToSource(out) + shader.CreateInput("diffuse_texture", Sdf.ValueTypeNames.Asset).Set(Sdf.AssetPath(f"number_{number}.png")) + shader.CreateInput("diffuse_color_constant", Sdf.ValueTypeNames.Color3f).Set((1, 1, 1)) + shader.CreateInput("reflection_roughness_constant", Sdf.ValueTypeNames.Float).Set(0.85) + shader.CreateInput("specular_level", Sdf.ValueTypeNames.Float).Set(0.05) + shader.CreateInput("project_uvw", Sdf.ValueTypeNames.Bool).Set(False) + UsdShade.MaterialBindingAPI.Apply(mesh.GetPrim()).Bind(material) + stage.GetRootLayer().Save() + + check = Usd.Stage.Open(str(output / f"number_{number}.usda")) + assert check.GetDefaultPrim().GetPath() == "/NumberLabel" + bounds = ( + UsdGeom.BBoxCache(Usd.TimeCode.Default(), ["default"]) + .ComputeWorldBound(check.GetDefaultPrim()) + .ComputeAlignedRange() + ) + assert bounds.GetSize() == Gf.Vec3d(1, 1, 0) + assert not any(p.HasAPI(UsdPhysics.CollisionAPI) for p in check.Traverse()) + + +def generate_review(output): + # Reusable-reference check, plus a review stage with all four static assets. + for name, count in (("preview", 1), ("review", 4)): + review = Usd.Stage.CreateNew(str(output / f"{name}.usda")) + UsdGeom.SetStageUpAxis(review, UsdGeom.Tokens.z) + UsdGeom.SetStageMetersPerUnit(review, 1) + scene = UsdGeom.Xform.Define(review, "/Review") + review.SetDefaultPrim(scene.GetPrim()) + for i in range(count): + label = UsdGeom.Xform.Define(review, f"/Review/Label{i}") + label.GetPrim().GetReferences().AddReference(f"number_{i + 1}.usda") + label.AddTranslateOp().Set((i * 0.03, 0, 0)) + label.AddScaleOp().Set((0.022, 0.022, 0.022)) + light = UsdLux.DomeLight.Define(review, "/Review/Light") + light.CreateIntensityAttr(1500) + camera = UsdGeom.Camera.Define(review, "/Review/Camera") + camera.AddTranslateOp().Set(((count - 1) * 0.015, 0, 0.15)) + camera.CreateClippingRangeAttr((0.001, 10)) + review.GetRootLayer().Save() + print(f"Validated {output}: four static unit decals, relative textures, no colliders") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--font", type=Path, default=Path("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf")) + args = parser.parse_args() + generate(args.output, args.font) diff --git a/src/isaaclab_tutorial/assets/numbers/number_1.png b/src/isaaclab_tutorial/assets/numbers/number_1.png new file mode 100644 index 0000000..355de5c --- /dev/null +++ b/src/isaaclab_tutorial/assets/numbers/number_1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85b6299d8241b494e8df4f380dba917e4bb848a304d208bd33b9bae2311685de +size 1194 diff --git a/src/isaaclab_tutorial/assets/numbers/number_1.usda b/src/isaaclab_tutorial/assets/numbers/number_1.usda new file mode 100644 index 0000000..28f601e --- /dev/null +++ b/src/isaaclab_tutorial/assets/numbers/number_1.usda @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:564ffe3fdbd59108cd1648bee4266c55159ef1b1e4cae87e51d0d741f321c3dd +size 1474 diff --git a/src/isaaclab_tutorial/assets/numbers/number_2.png b/src/isaaclab_tutorial/assets/numbers/number_2.png new file mode 100644 index 0000000..4487820 --- /dev/null +++ b/src/isaaclab_tutorial/assets/numbers/number_2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42653c0af34f20b0976f0d5d3196f3e8384d167f390e017f86cea6c4d593fbbf +size 4517 diff --git a/src/isaaclab_tutorial/assets/numbers/number_2.usda b/src/isaaclab_tutorial/assets/numbers/number_2.usda new file mode 100644 index 0000000..802180f --- /dev/null +++ b/src/isaaclab_tutorial/assets/numbers/number_2.usda @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b991b102e624af1c6dbd9ead5356a45cd17440cb468aa00a2225ea1331a2cbb1 +size 1474 diff --git a/src/isaaclab_tutorial/assets/numbers/number_3.png b/src/isaaclab_tutorial/assets/numbers/number_3.png new file mode 100644 index 0000000..bec3631 --- /dev/null +++ b/src/isaaclab_tutorial/assets/numbers/number_3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6d4b53087e1e0d85d047ab1c5f5490655764c336084b2b39090b17c50d30058 +size 5297 diff --git a/src/isaaclab_tutorial/assets/numbers/number_3.usda b/src/isaaclab_tutorial/assets/numbers/number_3.usda new file mode 100644 index 0000000..9e32b43 --- /dev/null +++ b/src/isaaclab_tutorial/assets/numbers/number_3.usda @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6991ffd72ecb6f9e1d552e59f3415472fa974e8e96320094a1a648d9320c15da +size 1474 diff --git a/src/isaaclab_tutorial/assets/numbers/number_4.png b/src/isaaclab_tutorial/assets/numbers/number_4.png new file mode 100644 index 0000000..5a20e2e --- /dev/null +++ b/src/isaaclab_tutorial/assets/numbers/number_4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20f34838694e673d465842ace1744818f1404e7dd10984a24eb5e0e11263b818 +size 2924 diff --git a/src/isaaclab_tutorial/assets/numbers/number_4.usda b/src/isaaclab_tutorial/assets/numbers/number_4.usda new file mode 100644 index 0000000..5201105 --- /dev/null +++ b/src/isaaclab_tutorial/assets/numbers/number_4.usda @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8dede0ca8e90a1e476e3ff72e371589203687ecccc0355d6edf933e5bdf14b9c +size 1474 diff --git a/tests/active_gaze/test_action_chunks.py b/tests/active_gaze/test_action_chunks.py new file mode 100644 index 0000000..a2ef67e --- /dev/null +++ b/tests/active_gaze/test_action_chunks.py @@ -0,0 +1,174 @@ +"""Chunk boundaries must preserve rewards, timeout values and executed-action gradients.""" + +from types import SimpleNamespace + +import pytest +import torch +from tensordict import TensorDict + +from isaaclab_tutorial.active_gaze.learning.chunks import ( + ActionChunkWrapper, + chunk_gaussian_statistics, +) +from isaaclab_tutorial.active_gaze.learning.fusion import LanguageVisionFusion +from isaaclab_tutorial.active_gaze.learning.language import trim_instruction_padding + + +class ControlEnv: + num_envs, num_actions, device, max_episode_length = 3, 5, "cpu", 100 + step_dt = 0.02 + + def __init__(self): + self.unwrapped = self + self.cfg = SimpleNamespace(compute_final_obs=False) + self.render_enabled = True + self.episode_length_buf = torch.zeros(3, dtype=torch.long) + self.index = 0 + self.calls = [] + + def get_observations(self): + return TensorDict( + dict( + proprio=torch.full((3, 2), float(self.index)), + privileged=torch.full((3, 3), float(self.index)), + oracle=torch.tensor([[self.index / 10, 0.0, 1.0]]).expand(3, -1).clone(), + ), + batch_size=[3], + ) + + def step(self, action): + self.calls.append((action.clone(), self.render_enabled, self.refresh_policy_vision)) + self.index += 1 + # Row 0 terminates after one action; row 1 times out after two. + self.reset_terminated = torch.tensor([self.index == 1, False, False]) + timeouts = torch.tensor([False, self.index == 2, False]) + done = self.reset_terminated | timeouts + final = self.get_observations() + obs = final.clone() + obs["proprio"][done] = -100 # Distinguish the reset state from the final state. + return obs, torch.ones(3), done.long(), {"time_outs": timeouts, "final_obs": final} + + +def test_chunk_boundary_discounts_timeouts_idle_suffixes_and_fresh_oracle_targets(): + control = ControlEnv() + env = ActionChunkWrapper(control, chunk_size=4, control_gamma=0.5, critic_groups=["proprio", "privileged"]) + obs, reward, done, info = env.step(torch.ones(3, 20)) + torch.testing.assert_close(reward, torch.tensor([1.0, 1.5, 1.875])) + assert done.tolist() == [1, 1, 0] + assert info["chunk_valid"].tolist() == [ + [True, False, False, False], + [True, True, False, False], + [True] * 4, + ] + torch.testing.assert_close(info["chunk_timeout_discount"], torch.tensor([0.0, 0.25, 0.0])) + assert info["chunk_timeout_observations"]["proprio"][1, 0] == 2 + torch.testing.assert_close(info["chunk_oracle"][2, :, 0], torch.arange(4) / 10) + assert info["chunk_oracle"][0, 1:, 2].sum() == 0 + assert "time_outs" not in info # No second, native one-step timeout bootstrap. + assert [(render, fresh) for _, render, fresh in control.calls] == [(False, False)] * 3 + [(True, True)] + assert torch.count_nonzero(control.calls[1][0][0]) == 0 + assert torch.count_nonzero(control.calls[2][0][:2]) == 0 + assert torch.equal(control.calls[3][0][2], torch.ones(5)) + assert obs["chunk_valid"].all() # Next decision starts a fresh plan for every row. + assert control.render_enabled and control.refresh_policy_vision + + +def test_unexecuted_actions_have_no_likelihood_or_entropy_gradient(): + mean = torch.zeros(2, 12, requires_grad=True) + log_std = torch.zeros(2, 12, requires_grad=True) + actions = torch.ones_like(mean) + valid = torch.tensor([[True, False, False, False], [True, True, True, True]]) + log_prob, entropy = chunk_gaussian_statistics(mean, log_std.exp(), actions, valid) + expected = torch.distributions.Normal(0.0, 1.0).log_prob(torch.tensor(1.0)) + torch.testing.assert_close(log_prob, expected * torch.tensor([3.0, 12.0])) + (log_prob.sum() + entropy.sum()).backward() + assert torch.count_nonzero(mean.grad[0, 3:]) == 0 + assert torch.count_nonzero(log_std.grad[0, 3:]) == 0 + assert mean.grad[1].abs().sum() > 0 + + +def test_compact_cached_language_matches_masked_full_fusion_for_variable_lengths(): + torch.manual_seed(7) + features = torch.randn(3, 16, 12).bfloat16() + padding = torch.arange(16)[None, :] >= torch.tensor([3, 5, 8])[:, None] + compact, mask = trim_instruction_padding(features, padding) + assert compact.shape == (3, 8, 12) + assert (~mask).sum(1).tolist() == [3, 5, 8] + full = LanguageVisionFusion(8, 12, 4, 16, width=16, heads=2, output_dim=8) + short = LanguageVisionFusion(8, 12, 4, 8, width=16, heads=2, output_dim=8) + weights = full.state_dict() + weights["allowed"] = short.allowed + short.load_state_dict(weights) + vision = torch.randn(3, 4, 8) + torch.testing.assert_close(full(vision, features, padding), short(vision, compact, mask)) + # Frozen contextual features stay byte-identical: no encoder or trainable projection caching. + assert torch.equal(compact, features[:, :8]) + + +@pytest.mark.parametrize("oracle", [True, False]) +def test_chunk_ppo_stores_executed_prefix_and_bootstraps_final_timeout_state(oracle): + from rsl_rl.models import MLPModel + from rsl_rl.storage import RolloutStorage + + from isaaclab_tutorial.active_gaze.learning.oracle_ppo import OraclePPO + + env = ActionChunkWrapper(ControlEnv(), 4, 0.5, critic_groups=["proprio"]) + if not oracle: + env._obs.pop("oracle") + get_observations = env.unwrapped.get_observations + + def without_oracle(): + return get_observations().exclude("oracle") + + env.unwrapped.get_observations = without_oracle + obs = env.get_observations() + actor = MLPModel( + obs, + {"actor": ["proprio"]}, + "actor", + 20, + hidden_dims=[16], + distribution_cfg=dict(class_name="GaussianDistribution", init_std=0.5, std_type="log"), + ) + critic = MLPModel(obs, {"critic": ["proprio"]}, "critic", 1, hidden_dims=[16]) + critic.forward = lambda observation: observation["proprio"][:, :1] + alg = OraclePPO( + actor, + critic, + RolloutStorage("rl", 3, 2, obs, [20]), + action_chunk_size=4, + oracle_weight=float(oracle), + gamma=0.5**4, + lam=0.95**4, + schedule="fixed", + num_learning_epochs=1, + num_mini_batches=1, + ) + with torch.no_grad(): + for _ in range(2): + actions = alg.act(obs) + following, rewards, dones, extras = env.step(actions) + alg.process_env_step(following, rewards, dones, extras) + obs = following + alg.compute_returns(obs) + torch.testing.assert_close(alg.storage.rewards[0, :, 0], torch.tensor([1.0, 2.0, 1.875])) + torch.testing.assert_close(alg.storage.returns[0, :2, 0], torch.tensor([1.0, 2.0])) + torch.testing.assert_close(alg.storage.returns[1, 2, 0], torch.tensor(1.875 + 0.5**4 * 8)) + assert alg.storage.observations[0]["chunk_valid"][0].tolist() == [True, False, False, False] + if oracle: + torch.testing.assert_close(alg.storage.observations[0]["chunk_oracle"][2, :, 0], torch.arange(4) / 10) + else: + assert not alg.storage.observations["chunk_oracle"].any() + result = alg.update() + assert all(torch.isfinite(torch.tensor(value)) for value in result.values()) + + +def test_discarded_chunk_suffix_holds_absolute_hand_targets(): + control = ControlEnv() + # An absolute gripper target has a nonzero idle encoding after reset. + control.idle_actions = lambda: torch.tensor([0.0, 0.0, -0.8, 0.0, 0.0]).expand(3, -1) + env = ActionChunkWrapper(control, chunk_size=4, control_gamma=0.5, critic_groups=["proprio", "privileged"]) + env.step(torch.ones(3, 20)) + torch.testing.assert_close(control.calls[1][0][0], control.idle_actions()[0]) + torch.testing.assert_close(control.calls[2][0][:2], control.idle_actions()[:2]) + torch.testing.assert_close(control.calls[3][0][2], torch.ones(5)) diff --git a/tests/active_gaze/test_clipped_distribution.py b/tests/active_gaze/test_clipped_distribution.py new file mode 100644 index 0000000..55a2ff2 --- /dev/null +++ b/tests/active_gaze/test_clipped_distribution.py @@ -0,0 +1,85 @@ +"""Executed-action probabilities, entropy, gradients and chunk marginalization.""" + +import math + +import numpy as np +import pytest +import torch +from scipy.integrate import quad +from scipy.stats import norm + +from isaaclab_tutorial.active_gaze.learning.chunks import chunk_gaussian_statistics +from isaaclab_tutorial.active_gaze.learning.distributions import ClippedGaussianDistribution, clipped_gaussian_statistics + + +@pytest.mark.parametrize("mean,std", [(0, 0.5), (0.9, 0.3), (-2, 0.4), (0, 1000)]) +def test_likelihood_and_entropy_match_quadrature(mean, std): + x = torch.tensor([-1.0, -0.25, 0.75, 1.0], dtype=torch.float64) + logp, entropy = clipped_gaussian_statistics(torch.full_like(x, mean), torch.full_like(x, std), x) + reference = norm(mean, std) + expected = [ + reference.logcdf(-1), + reference.logpdf(-0.25), + reference.logpdf(0.75), + reference.logsf(1), + ] + np.testing.assert_allclose(logp.numpy(), expected, atol=1e-10) + left, right = reference.cdf(-1), reference.sf(1) + integral = quad(lambda v: -reference.pdf(v) * reference.logpdf(v), -1, 1)[0] + expected_entropy = integral - sum(p * math.log(p) for p in (left, right) if p > 0) + torch.testing.assert_close(entropy, torch.full_like(x, expected_entropy), atol=1e-10, rtol=1e-10) + + +def test_excess_noise_has_no_unbounded_entropy_bonus(): + log_std = torch.tensor([math.log(v) for v in (10, 100, 1000, 1e6)], dtype=torch.float64, requires_grad=True) + _, entropy = clipped_gaussian_statistics(torch.zeros(4, dtype=torch.float64), log_std.exp(), torch.zeros(4)) + assert (entropy[:-1] > entropy[1:]).all() + assert entropy[-1].item() == pytest.approx(math.log(2), abs=2e-5) + entropy.sum().backward() + assert (log_std.grad < 0).all() + + +@pytest.mark.parametrize("mean", [-10000.0, -1.0, 0.0, 1.0, 10000.0]) +@pytest.mark.parametrize("std", [1e-6, 0.5, 1e6]) +def test_extreme_parameters_have_finite_gradients(mean, std): + mu = torch.full((3,), mean, requires_grad=True) + sigma = torch.full((3,), std, requires_grad=True) + logp, entropy = clipped_gaussian_statistics(mu, sigma, torch.tensor([-1.0, 0.0, 1.0])) + assert torch.isfinite(logp).all() and torch.isfinite(entropy).all() + (logp + entropy).sum().backward() + assert torch.isfinite(mu.grad).all() and torch.isfinite(sigma.grad).all() + + +def test_sampling_has_expected_boundary_masses_and_export_matches(): + torch.manual_seed(123) + dist = ClippedGaussianDistribution(1, init_std=2, std_type="log") + means = torch.full((100000, 1), 0.5) + dist.update(means) + samples = dist.sample() + assert samples.abs().max() <= 1 + assert (samples == -1).float().mean().item() == pytest.approx(norm.cdf(-0.75), abs=0.005) + assert (samples == 1).float().mean().item() == pytest.approx(norm.sf(0.25), abs=0.005) + means = torch.tensor([[-4.0], [0.2], [3.0]]) + torch.testing.assert_close(dist.deterministic_output(means), dist.as_deterministic_output_module()(means)) + + +def test_chunk_prefix_ignores_nonfinite_discarded_suffix_and_gradients(): + mean = torch.tensor([[0.2, -0.3, float("nan"), float("inf")]], requires_grad=True) + std = torch.tensor([[0.5, 2.0, float("inf"), float("nan")]], requires_grad=True) + actions = torch.tensor([[1.0, -1.0, float("nan"), float("inf")]]) + valid = torch.tensor([[True, False]]) + logp, entropy = chunk_gaussian_statistics(mean, std, actions, valid, clipped=True) + reference = clipped_gaussian_statistics(mean[:, :2], std[:, :2], actions[:, :2]) + torch.testing.assert_close(logp, reference[0].sum(-1)) + torch.testing.assert_close(entropy, reference[1].sum(-1)) + (logp + entropy).sum().backward() + assert torch.isfinite(mean.grad).all() and torch.isfinite(std.grad).all() + assert not mean.grad[:, 2:].any() and not std.grad[:, 2:].any() + + +def test_unchanged_boundary_policy_has_unit_ppo_ratio(): + mean, std = torch.tensor([[2.0, -3.0]]), torch.tensor([[0.5, 1.0]]) + actions, valid = torch.tensor([[1.0, -1.0]]), torch.tensor([[True]]) + old, _ = chunk_gaussian_statistics(mean, std, actions, valid, clipped=True) + new, _ = chunk_gaussian_statistics(mean.clone(), std.clone(), actions, valid, clipped=True) + torch.testing.assert_close((new - old).exp(), torch.ones(1)) diff --git a/tests/active_gaze/test_distributed.py b/tests/active_gaze/test_distributed.py new file mode 100644 index 0000000..2865644 --- /dev/null +++ b/tests/active_gaze/test_distributed.py @@ -0,0 +1,120 @@ +"""Distributed calibration must qualify every GPU and train the measured recipe.""" + +import json +from pathlib import Path +from types import SimpleNamespace + +from isaaclab_tutorial.active_gaze import calibrate, distributed + + +def test_launch_and_memory_boundary_proposals(): + command = distributed.training_command(8) + assert "--nproc_per_node=8" in command + assert command[-1] == "isaaclab_tutorial.active_gaze.train" + assert "torch.distributed.run" not in distributed.training_command(1) + propose = calibrate.propose_environments + assert propose([], 45, 8192, 2048) == 2048 + assert propose([(2048, float("inf"))], 45, 8192, 2048) == 1024 + assert propose([(2560, 44), (2688, 46)], 45, 8192, 2048) is None + assert propose([(2048, 35), (2560, 40)], 45, 8192, 2048) == 2944 + + +def report(rank=0, world=8, envs=2048, batch=1024, measured=2, peak=44e9): + return dict( + complete=True, + error=None, + gpu="L40", + gpu_uuid=f"gpu-{rank}", + rank=rank, + world_size=world, + num_envs=envs, + rollout_steps=64, + action_chunk_size=1, + minibatch_size=batch, + measured_updates=measured, + total_bytes=48e9, + peak_device_bytes=peak, + peak_conservative_bytes=peak, + peak_torch_allocated_bytes=peak / 2, + peak_torch_reserved_bytes=peak / 2, + mean_total_fps=1000, + updates=[dict(iteration=i, collection_time=1, learning_time=1) for i in range(measured)], + ) + + +def test_missing_or_over_budget_rank_cannot_qualify(tmp_path): + for rank in range(8): + directory = tmp_path if rank == 0 else tmp_path / f"rank_{rank}" + directory.mkdir(exist_ok=True) + if rank == 7: + assert distributed.read_measurement(tmp_path, 8) == {} + (directory / "memory.json").write_text(json.dumps(report(rank, peak=(46e9 if rank == 7 else 44e9)))) + data = distributed.read_measurement(tmp_path, 8) + assert data["peak_conservative_bytes"] == 46e9 + assert not calibrate.budget_ok(data, 2, 45e9) + + +def test_distributed_reset_metrics_pool_unequal_episode_counts(monkeypatch): + import torch + + from isaaclab_tutorial.active_gaze.sampling import SuccessHistory, iteration_metrics + + local, remote = SuccessHistory(1), SuccessHistory(1) + local.update(torch.tensor([0]), torch.tensor([True])) + remote.update(torch.tensor([0, 0, 0]), torch.tensor([False, False, False])) + sampler = SimpleNamespace( + history=local, sampled=torch.tensor([1]), bin_names=["home"], phase_probabilities=lambda: torch.tensor([1.0]) + ) + other = torch.stack((remote.episodes, remote.successes, torch.tensor([3]))) + other_history = torch.stack((remote.history.sum(-1), remote.counts, torch.tensor([1.0]))) + additions = iter((other, other, other_history)) + monkeypatch.setattr(torch.distributed, "all_reduce", lambda value: value.add_(next(additions))) + monkeypatch.setattr(torch.distributed, "get_world_size", lambda: 2) + metrics, previous = iteration_metrics(sampler, 0, distributed=True) + assert metrics["Reset/success_rate/home"] == 0.25 + assert metrics["Reset/success_rate_rolling/home"] == 0.25 + assert metrics["Reset/episodes/home"] == 4 + assert previous[:, 0].tolist() == [1, 1, 1] + assert local.episodes.tolist() == [1] + + +def test_calibration_confirms_real_trials_and_backs_off(tmp_path, monkeypatch): + def run(command, log, timeout): + def option(name): + return command[command.index(name) + 1] + + envs = int(option("--num_envs")) + batch = envs * 16 // int(option("--minibatches")) + measured = int(option("--iterations")) - int(option("--memory_warmup")) + output = Path(option("--output")) + output.mkdir() + peak = 9e9 + envs * 1e7 + batch * 3e6 + (1e9 if measured == 8 else 0) + for rank in range(8): + path = output if rank == 0 else output / f"rank_{rank}" + path.mkdir(exist_ok=True) + (path / "memory.json").write_text( + json.dumps(report(rank, envs=envs, batch=batch, measured=measured, peak=peak)) + ) + log.write_text("completed") + return 0 + + monkeypatch.setattr(calibrate, "run_trial", run) + args = SimpleNamespace( + output=tmp_path / "calibration", + resume=False, + num_gpus=8, + memory_budget_gb=45, + minibatch_sizes=[1024, 2048], + max_envs=8192, + initial_envs=2048, + warmup=2, + measure=2, + confirm=8, + timeout=10, + ) + result = calibrate.calibrate(args, ["presets=dino_language,chunking"], rollout_steps=16) + selected = result["selected"] + assert result["complete"] and selected["world_size"] == 8 + assert selected["measured_updates"] == 8 and selected["peak_conservative_bytes"] <= 45e9 + assert selected["total_environments"] == selected["num_envs"] * 8 + assert len([t for t in result["trials"] if t["measured_updates"] == 8]) > 1 diff --git a/tests/active_gaze/test_evaluation.py b/tests/active_gaze/test_evaluation.py new file mode 100644 index 0000000..1303e20 --- /dev/null +++ b/tests/active_gaze/test_evaluation.py @@ -0,0 +1,551 @@ +"""Evaluation stays isolated from training and captures RGB only at chunk boundaries.""" + +import copy +import json +from dataclasses import asdict +from types import SimpleNamespace + +import imageio.v2 as imageio +import pytest +import torch +from tensordict import TensorDict + +from isaaclab_tutorial.active_gaze.learning.chunks import ActionChunkWrapper +from isaaclab_tutorial.active_gaze.learning.runner import EvaluationOnPolicyRunner +from isaaclab_tutorial.active_gaze.training.evaluation import EvaluationConfig, PeriodicEvaluation, coordinated_errors +from isaaclab_tutorial.active_gaze.training.video import ObservationVideoRecorder + + +class CountingCamera: + def __init__(self): + self.rgb = torch.zeros(3, 16, 16, 3, dtype=torch.uint8) + self.reads = 0 + + @property + def data(self): + self.reads += 1 + return SimpleNamespace(output={"rgb": self.rgb}) + + +class EvaluationEnv: + num_envs, num_actions, device, max_episode_length = 3, 3, "cpu", 5 + step_dt = 0.1 + + def __init__(self): + self.unwrapped = self + self.cfg = SimpleNamespace(compute_final_obs=False, to_dict=lambda: {}) + self.render_enabled = True + self.episode_length_buf = torch.zeros(3, dtype=torch.long) + self.resets = 0 + self.steps = 0 + self.calls = [] + self.action_manager = SimpleNamespace( + get_term=lambda _: SimpleNamespace(arm_action_dim=1, motor_action_dim=1, action_dim=1) + ) + self.termination_manager = SimpleNamespace(get_term=lambda _: torch.zeros(3, dtype=torch.bool)) + self.scene = {"eye": CountingCamera()} + + def get_observations(self): + state = torch.stack((torch.full((3,), self.resets), self.episode_length_buf), dim=-1).float() + return TensorDict( + dict( + proprio=state, + rnd_state=state.clone(), + privileged=state.clone(), + instruction=torch.arange(3)[:, None], + oracle=torch.tensor([[0.0, 0.0, 1.0]]).expand(3, -1).clone(), + ), + batch_size=[3], + ) + + def reset(self): + self.resets += 1 + self.episode_length_buf.zero_() + return self.get_observations(), {} + + def step(self, action): + self.calls.append((action.clone(), self.render_enabled, self.refresh_policy_vision)) + self.steps += 1 + self.episode_length_buf += 1 + done = self.episode_length_buf >= self.max_episode_length + final = self.get_observations() + self.episode_length_buf[done] = 0 + self.reset_terminated = torch.zeros(3, dtype=torch.bool) + self.scene["eye"].rgb.fill_(self.steps % 250) + return ( + self.get_observations(), + torch.ones(3), + done.long(), + {"time_outs": done, "final_obs": final}, + ) + + +def make_runner(tmp_path, *, rnd=False, **evaluation): + env = ActionChunkWrapper(EvaluationEnv(), 4, 0.99, critic_groups=["proprio", "privileged"]) + cfg = { + "actor": dict( + class_name="rsl_rl.models:MLPModel", + hidden_dims=[8], + obs_normalization=True, + distribution_cfg=dict(class_name="GaussianDistribution", init_std=0.5, std_type="log"), + ), + "critic": dict(class_name="rsl_rl.models:MLPModel", hidden_dims=[8], obs_normalization=True), + "obs_groups": {"actor": ["proprio"], "critic": ["proprio", "privileged"]}, + "algorithm": dict( + class_name="isaaclab_tutorial.active_gaze.learning.oracle_ppo:OraclePPO", + num_learning_epochs=1, + num_mini_batches=1, + schedule="fixed", + action_chunk_size=4, + ), + "num_steps_per_env": 2, + "save_interval": 100, + "logger": "tensorboard", + "evaluation": asdict(EvaluationConfig(frequency_episodes=4)) | evaluation, + } + if rnd: + cfg["obs_groups"]["rnd_state"] = ["rnd_state"] + cfg["algorithm"]["rnd_cfg"] = dict( + num_outputs=8, + predictor_hidden_dims=[16, 16], + target_hidden_dims=[16], + state_normalization=True, + reward_normalization=True, + weight=1.0, + ) + runner = EvaluationOnPolicyRunner(env, cfg, str(tmp_path), "cpu") + runner.alg.actor.instructions = ("Place the vial.", "Move to the rack.", "Release the vial.") + return runner + + +def assert_state_equal(before, after): + if isinstance(before, torch.Tensor): + assert torch.equal(before, after) + elif isinstance(before, dict): + assert before.keys() == after.keys() + for key in before: + assert_state_equal(before[key], after[key]) + elif isinstance(before, (tuple, list)): + assert len(before) == len(after) + for left, right in zip(before, after, strict=True): + assert_state_equal(left, right) + else: + assert before == after + + +def test_default_schedule_uses_training_time_and_crosses_rollout_boundaries(): + schedule = PeriodicEvaluation(SimpleNamespace(max_episode_length=360), {}) + assert (schedule.frequency, schedule.duration) == (36000, 360) + assert not schedule.due(35936, 35968) + assert schedule.due(35968, 36000) + assert not schedule.due(36000, 36032) + # An interval that doesn't divide PPO's horizon runs at the following boundary. + schedule = PeriodicEvaluation(SimpleNamespace(max_episode_length=5), {"frequency_episodes": 4}) + assert schedule.due(16, 24) + assert not schedule.due(24, 32) + assert schedule.due(32, 40) + assert not PeriodicEvaluation(SimpleNamespace(max_episode_length=5), {"enabled": False}).due(16, 24) + for kwargs in ( + {"duration_episodes": 0}, + {"frequency_episodes": float("nan")}, + {"video_envs": 0}, + ): + with pytest.raises(ValueError): + EvaluationConfig(**kwargs) + with pytest.raises(ValueError, match="whole control steps"): + EvaluationConfig(duration_episodes=0.25).control_steps(5) + + +def test_early_schedule_coalesces_thresholds_and_does_not_replay_on_resume(): + schedule = PeriodicEvaluation( + SimpleNamespace(max_episode_length=5), + {"frequency_episodes": 4, "early_episodes": [4, 2, 1, 1]}, + ) + assert schedule.early_steps == (5, 10, 20) + assert [schedule.due(step, step + 8) for step in range(0, 40, 8)] == [ + True, + True, + True, + False, + True, + ] + assert not schedule.due(24, 32) + assert not PeriodicEvaluation( + SimpleNamespace(max_episode_length=5), + {"enabled": False, "frequency_episodes": 4, "early_episodes": [1]}, + ).due(0, 8) + for values in ([0], [-1], [float("nan")], [True], ["1"], "1"): + with pytest.raises(ValueError, match="early_episodes"): + EvaluationConfig(early_episodes=values) + with pytest.raises(ValueError, match="whole control steps"): + EvaluationConfig(early_episodes=[0.25]).control_steps(5) + + +def test_early_blocks_record_video_save_matching_policy_and_resume_without_replay(tmp_path): + runner = make_runner(tmp_path, early_episodes=[1, 2]) + evaluated_iterations = [] + original_run = runner.evaluation.run + + def run(active): + iteration = active.current_learning_iteration + checkpoint = tmp_path / f"model_{iteration}.pt" + assert checkpoint.is_file() + saved = torch.load(checkpoint, weights_only=False) + assert saved["iter"] == iteration + for key, value in active.alg.save().items(): + assert_state_equal(value, saved[key]) + evaluated_iterations.append(iteration) + return original_run(active) + + runner.evaluation.run = run + runner.learn(4) + assert evaluated_iterations == [0, 1, 2] + blocks = list((tmp_path / "evaluation").glob("*/evaluation.json")) + assert len(blocks) == 3 + assert len(list((tmp_path / "evaluation").glob("*/env_*.mp4"))) == 9 + assert runner.env.unwrapped.steps == 32 + 3 * 5 + resumed = make_runner(tmp_path / "resumed", video=False, early_episodes=[1, 2]) + resumed.load(str(tmp_path / "model_1.pt")) + assert resumed.training_control_steps == 16 + resumed.learn(1) + assert resumed.env.unwrapped.steps == 8 + 5 + assert (tmp_path / "resumed/evaluation/step_000000024/evaluation.json").exists() + + +def test_checkpoint_failure_stops_before_evaluation(tmp_path, monkeypatch): + runner = make_runner(tmp_path, early_episodes=[1]) + + def fail_save(*args): + raise OSError("checkpoint storage unavailable") + + monkeypatch.setattr(runner, "save", fail_save) + with pytest.raises(OSError, match="checkpoint storage unavailable"): + runner.learn(1) + assert not (tmp_path / "evaluation").exists() + assert runner.env.unwrapped.steps == 8 + + +@pytest.mark.parametrize("rnd", [False, True]) +def test_eval_freezes_learning_resets_all_envs_and_records_at_chunk_rate(tmp_path, rnd): + runner = make_runner(tmp_path, rnd=rnd) + # Seed real PPO/Adam and normalization state before taking the snapshot. + runner.learn(1) + runner.logger.cur_reward_sum.fill_(20) + runner.logger.cur_episode_length.fill_(3) + runner.alg.actor.mlp.eval() # Deliberately frozen nested mode must also survive. + modes = {module: module.training for model in (runner.alg.actor, runner.alg.critic) for module in model.modules()} + before = copy.deepcopy(runner.alg.save()) + if rnd: + rnd_modes = {module: module.training for module in runner.alg.rnd.modules()} + rnd_returns = runner.alg.rnd.reward_normalizer.disc_avg.avg.clone() + runner.logger.cur_ereward_sum.fill_(20) + runner.logger.cur_ireward_sum.fill_(3) + storage = runner.alg.storage.step + control = runner.env.unwrapped + reset_count, control_count = control.resets, control.steps + obs = runner.evaluation.run(runner) + assert_state_equal(before, runner.alg.save()) + if rnd: + assert all(module.training == value for module, value in rnd_modes.items()) + torch.testing.assert_close(rnd_returns, runner.alg.rnd.reward_normalizer.disc_avg.avg) + assert not runner.logger.cur_ereward_sum.any() and not runner.logger.cur_ireward_sum.any() + assert runner.alg.storage.step == storage + assert all(module.training == value for module, value in modes.items()) + assert control.resets == reset_count + 2 + assert control.steps == control_count + 5 + assert runner.training_control_steps == 8 # Evaluation isn't training progress. + assert [(render, fresh) for _, render, fresh in control.calls[-5:]] == [ + (False, False), + (False, False), + (False, False), + (True, True), + (True, True), + ] + assert (obs["proprio"][:, 0] == control.resets).all() + assert (obs["proprio"][:, 1] == 0).all() + assert not runner.logger.cur_reward_sum.any() + assert not runner.logger.cur_episode_length.any() + folder = tmp_path / "evaluation/step_000000008" + meta = json.loads((folder / "evaluation.json").read_text()) + assert len(list(folder.glob("env_*.mp4"))) == 3 + assert meta["videos"] == {f"env_{i}": f"env_{i}.mp4" for i in range(3)} + assert control.scene["eye"].reads == 2 # No lazy camera reads inside a chunk. + assert meta["frame_count"] == 2 + assert meta["instruction_segments"][0]["instructions"] == list(runner.alg.actor.instructions) + assert meta["control_fps"] == 10 + assert meta["policy_fps"] == 2.5 + assert meta["video_fps"] == 2.5 + assert meta["metrics"]["Eval/completed_episodes"] == 3 + assert meta["metrics"]["Eval/mean_return"] == 5 + with imageio.get_reader(folder / "env_0.mp4") as reader: + frames = [frame for frame in reader] + assert reader.get_meta_data()["fps"] == 2.5 + assert len(frames) == 2 + assert frames[0].shape == (320, 320, 3) + assert frames[0][100, 100, 0] < frames[-1][100, 100, 0] + + +@pytest.mark.parametrize("video,rank", [(False, 0), (True, 1)]) +def test_eval_without_recording_never_requests_intermediate_rgb(tmp_path, video, rank): + runner = make_runner(tmp_path, video=video) + runner.gpu_global_rank = rank + runner.evaluation.run(runner) + control = runner.env.unwrapped + assert control.scene["eye"].reads == 0 + assert [(render, fresh) for _, render, fresh in control.calls] == [ + (False, False), + (False, False), + (False, False), + (True, True), + (True, True), + ] + + +def test_training_uses_fresh_observations_after_eval_and_resumes_schedule(tmp_path): + runner = make_runner(tmp_path, video=False) + original_act = runner.alg.act + actions = [] + + def act(obs): + torch.testing.assert_close(obs["proprio"], runner.env.get_observations()["proprio"]) + actions.append(obs["proprio"].clone()) + return original_act(obs) + + runner.alg.act = act + runner.learn(4) + assert len(actions) == 8 + assert runner.training_control_steps == 32 + assert runner.env.unwrapped.steps == 37 # Four PPO rollouts plus one five-step eval. + assert actions[-1][0, 0] == 2 # Both full resets happened before training resumed. + assert len(list((tmp_path / "evaluation").glob("*/evaluation.json"))) == 1 + resumed = make_runner(tmp_path / "resumed", video=False) + resumed.load(str(tmp_path / "model_3.pt")) + assert resumed.training_control_steps == 32 + resumed.learn(1) + assert resumed.current_learning_iteration == 4 + assert resumed.training_control_steps == 40 + assert resumed.logger.tot_timesteps == 5 * 2 * resumed.env.num_envs + assert (tmp_path / "resumed/evaluation/step_000000040/evaluation.json").exists() + assert resumed.env.unwrapped.steps == 13 + + +def test_recorder_failure_restores_state_and_does_not_continue_training(tmp_path, monkeypatch): + runner = make_runner(tmp_path) + modes = [runner.alg.actor.training, runner.alg.critic.training] + + def fail(*args): + raise RuntimeError("encoder failed") + + monkeypatch.setattr(ObservationVideoRecorder, "capture", fail) + with pytest.raises(RuntimeError, match="encoder failed"): + runner.evaluation.run(runner) + assert [runner.alg.actor.training, runner.alg.critic.training] == modes + assert runner.env.unwrapped.resets == 2 + assert runner.env.unwrapped.render_enabled and runner.env.unwrapped.refresh_policy_vision + + +def test_peer_evaluation_failure_is_propagated_before_training(monkeypatch): + runner = SimpleNamespace(is_distributed=True, device="cpu") + monkeypatch.setattr(torch.distributed, "all_reduce", lambda failed, **kwargs: failed.fill_(1)) + with pytest.raises(RuntimeError, match="another rank"): + with coordinated_errors(runner): + pass + + +def _distributed_evaluation_worker(rank, rendezvous, directory, fail_encoder): + from datetime import timedelta + from pathlib import Path + + torch.set_num_threads(1) + torch.distributed.init_process_group( + "gloo", init_method=rendezvous, rank=rank, world_size=2, timeout=timedelta(seconds=30) + ) + try: + runner = make_runner(Path(directory) / f"rank{rank}", video=fail_encoder) + runner.is_distributed = True + runner.gpu_global_rank = rank + if fail_encoder and rank == 0: + + def fail(*args): + raise RuntimeError("encoder failed") + + ObservationVideoRecorder.capture = fail + if fail_encoder: + with pytest.raises(RuntimeError, match="encoder failed|another rank"): + runner.evaluation.run(runner) + else: + runner.evaluation.run(runner) + assert runner.env.unwrapped.resets == 2 + finally: + torch.distributed.destroy_process_group() + + +@pytest.mark.parametrize("fail_encoder", [False, True]) +def test_distributed_evaluation_reduces_metrics_and_coordinates_rank_zero_failure(tmp_path, fail_encoder): + torch.multiprocessing.spawn( + _distributed_evaluation_worker, + args=(f"file://{tmp_path / 'rendezvous'}", str(tmp_path), fail_encoder), + nprocs=2, + join=True, + ) + if not fail_encoder: + data = json.loads((tmp_path / "rank0/evaluation/step_000000000/evaluation.json").read_text()) + assert data["metrics"]["Eval/completed_episodes"] == 6 + assert data["metrics"]["Eval/mean_return"] == 5 + assert not (tmp_path / "rank1/evaluation").exists() + + +def _distributed_rnd_worker(rank, rendezvous, directory): + from datetime import timedelta + from pathlib import Path + + torch.set_num_threads(1) + torch.distributed.init_process_group( + "gloo", init_method=rendezvous, rank=rank, world_size=2, timeout=timedelta(seconds=60) + ) + try: + torch.manual_seed(10 + rank) + runner = make_runner(Path(directory) / f"rank{rank}", rnd=True, enabled=False) + runner.is_distributed = runner.alg.is_multi_gpu = True + runner.gpu_global_rank = runner.alg.gpu_global_rank = rank + runner.gpu_world_size = runner.alg.gpu_world_size = 2 + # Different local novelty streams must still produce shared models/moments. + runner.env.unwrapped.resets = rank + 1 + runner.learn(1) + for model in (runner.alg.actor, runner.alg.critic, runner.alg.rnd): + for value in model.state_dict().values(): + if isinstance(value, torch.Tensor): + reference = value.clone() + torch.distributed.broadcast(reference, 0) + torch.testing.assert_close(value, reference) + assert all(p.grad is None for p in runner.alg.rnd.target.parameters()) + finally: + torch.distributed.destroy_process_group() + + +def test_distributed_rnd_synchronizes_target_predictor_gradients_and_moments(tmp_path): + torch.multiprocessing.spawn( + _distributed_rnd_worker, + args=(f"file://{tmp_path / 'rnd-rendezvous'}", str(tmp_path)), + nprocs=2, + join=True, + ) + + +def test_wandb_records_each_block_once_despite_native_video_scan(tmp_path, monkeypatch): + import wandb + + from isaaclab_tutorial.active_gaze.training.tracking import FoviWandbWriter + + writer = object.__new__(FoviWandbWriter) + writer.logged_videos = set() + logged = [] + monkeypatch.setattr(wandb, "Video", lambda path, **kwargs: path) + monkeypatch.setattr(wandb, "log", lambda values, **kwargs: logged.append((values, kwargs))) + first = tmp_path / "step_001/env_0.mp4" + second = tmp_path / "step_002/env_0.mp4" + writer.save_video(first, 1) + writer.save_video(first, 2) # Native logger scans old and new MP4 files. + writer.save_video(second, 2) + third = tmp_path / "step_002/env_1.mp4" + writer.save_video(third, 2) + assert logged[-1][0]["Eval/observations/env_1"] == str(third.resolve()) + assert len(logged) == 3 + assert logged[0][0]["Eval/observations/env_0"] == str(first.resolve()) + assert logged[1][0]["Eval/observations/env_0"] == str(second.resolve()) + + +@pytest.mark.parametrize("settings_file", ["config.json", "example.json"]) +def test_resumed_wandb_writer_updates_active_configuration(tmp_path, monkeypatch, settings_file): + import wandb + from rsl_rl.utils.wandb_log_writer import WandbLogWriter + + from isaaclab_tutorial.active_gaze.training.tracking import FoviWandbWriter + + updates = [] + saved = [] + monkeypatch.setattr(wandb, "run", SimpleNamespace(resumed=True, url="test")) + monkeypatch.setattr(wandb, "config", SimpleNamespace(update=lambda data, **kw: updates.append((data, kw)))) + monkeypatch.setattr(WandbLogWriter, "__init__", lambda *args, **kwargs: None) + monkeypatch.setattr(FoviWandbWriter, "save_file", lambda self, path: saved.append(path)) + (tmp_path / settings_file).write_text('{"camera": "hybrid"}') + (tmp_path / "gaze_reset_cache.pt").write_bytes(b"test cache") + (tmp_path / "provenance.json").write_text('{"workflow_id": "resumed-workflow"}') + writer = FoviWandbWriter(str(tmp_path), "test", "nvidia") + config = SimpleNamespace(to_dict=lambda: {"num_envs": 4}) + writer.store_config(config, {"evaluation": {"enabled": True}}) + assert len(updates) == 3 + assert updates[0][0]["isaaclab_fovi"] == {"camera": "hybrid"} + assert str(tmp_path / settings_file) in saved + assert str(tmp_path / "gaze_reset_cache.pt") in saved + assert all(kwargs == {"allow_val_change": True} for _, kwargs in updates) + assert updates[-1][0]["train_cfg"]["evaluation"]["enabled"] + + +@pytest.mark.parametrize("rnd", [False, True]) +def test_eval_resets_cannot_cross_gae_rollout_boundaries(tmp_path, rnd): + """Check real PPO targets on both sides of eval against an independent GAE. + + Evaluation changes the reset generation and reward scale. Any leaked eval + transition, stale bootstrap observation or carried advantage is observable. + """ + runner = make_runner(tmp_path, rnd=rnd, video=False, frequency_episodes=1.6) + control = runner.env.unwrapped + step = control.step + + def distinct_reward(action): + obs, reward, done, extras = step(action) + return obs, reward * (1 + 100 * control.resets), done, extras + + control.step = distinct_reward + compute = runner.alg.compute_returns + evaluate = runner.evaluation.run + records = [] + eval_count = 0 + + def checked_returns(obs): + st = runner.alg.storage + assert st.step == runner.cfg["num_steps_per_env"] + torch.testing.assert_close(obs["proprio"], runner.env.get_observations()["proprio"]) + assert (st.observations["proprio"][..., 0] == 2 * eval_count).all() + bootstrap = runner.alg.critic(obs).detach() + rewards, values, dones = (x.clone() for x in (st.rewards, st.values, st.dones)) + expected = torch.empty_like(values) + # Explicit sum of future TD residuals within this rollout only. + next_values = torch.cat((values[1:], bootstrap.unsqueeze(0))) + alive = 1 - dones.float() + deltas = rewards + runner.alg.gamma * alive * next_values - values + for t in range(st.num_transitions_per_env): + advantage = torch.zeros_like(bootstrap) + discount = torch.ones_like(bootstrap) + for k in range(t, st.num_transitions_per_env): + advantage += discount * deltas[k] + discount *= runner.alg.gamma * runner.alg.lam * alive[k] + expected[t] = advantage + values[t] + compute(obs) + torch.testing.assert_close(st.returns, expected) + advantages = expected - values + if not runner.alg.normalize_advantage_per_mini_batch: + advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8) + torch.testing.assert_close(st.advantages, advantages) + records.append((st.returns.clone(), st.advantages.clone())) + + def checked_evaluation(current): + nonlocal eval_count + st = runner.alg.storage + assert st.step == 0 # Optimizer consumed the completed rollout first. + assert current.alg.transition.observations is None + before = (st.returns.clone(), st.advantages.clone()) + fresh = evaluate(current) + assert st.step == 0 + for saved, actual in zip(before, (st.returns, st.advantages), strict=True): + torch.testing.assert_close(actual, saved, rtol=0, atol=0) + eval_count += 1 + assert (fresh["proprio"][:, 0] == 2 * eval_count).all() + return fresh + + runner.alg.compute_returns = checked_returns + runner.evaluation.run = checked_evaluation + runner.learn(3) + assert len(records) == eval_count == 3 + assert not torch.allclose(records[0][0], records[1][0]) diff --git a/tests/active_gaze/test_fixation_geometry.py b/tests/active_gaze/test_fixation_geometry.py new file mode 100644 index 0000000..97898f6 --- /dev/null +++ b/tests/active_gaze/test_fixation_geometry.py @@ -0,0 +1,40 @@ +"""Binocular parameterization geometry without task or policy dependencies.""" + +import pytest +import torch + +from isaaclab_tutorial.active_gaze.fixation.parameterization import ( + eyes_to_version_vergence, + validate_vergence_axis, + version_vergence_to_eyes, +) + + +def test_version_vergence_round_trip_with_per_eye_baseline_axes() -> None: + axes = torch.tensor([[0.6, 0.8], [1.0, 0.0]]) + version = torch.tensor([[0.2, -0.1], [-0.3, 0.4]]) + vergence = torch.tensor([[0.5], [-0.25]]) + left, right = version_vergence_to_eyes(version, vergence, axes) + recovered_version, recovered_vergence, residual = eyes_to_version_vergence(left, right, axes) + torch.testing.assert_close(left - right, vergence * axes) + torch.testing.assert_close(recovered_version, version) + torch.testing.assert_close(recovered_vergence, vergence) + torch.testing.assert_close(residual, torch.zeros(2)) + + +def test_cross_baseline_disparity_is_reported() -> None: + axis = torch.tensor([0.6, 0.8]) + orthogonal = torch.tensor([-0.8, 0.6]) + version = torch.tensor([[0.4, -0.2]]) + left = version + 0.25 * axis + 0.1 * orthogonal + right = version - 0.25 * axis - 0.1 * orthogonal + recovered, vergence, residual = eyes_to_version_vergence(left, right, axis) + torch.testing.assert_close(recovered, version) + torch.testing.assert_close(vergence, torch.tensor([[0.5]])) + torch.testing.assert_close(residual, torch.tensor([0.2])) + + +@pytest.mark.parametrize("axis", [(1.0,), (float("nan"), 0.0), (1.0, 1.0)]) +def test_invalid_vergence_axis_fails(axis: tuple[float, ...]) -> None: + with pytest.raises(ValueError, match="vergence_axis"): + validate_vergence_axis(axis) diff --git a/tests/active_gaze/test_language.py b/tests/active_gaze/test_language.py new file mode 100644 index 0000000..393d98e --- /dev/null +++ b/tests/active_gaze/test_language.py @@ -0,0 +1,94 @@ +"""SO-101 language policy boundaries, gradients, and portable configuration.""" + +from copy import deepcopy +from types import SimpleNamespace + +import pytest +import torch +from tensordict import TensorDict + + +def test_language_configuration_keeps_numbered_task_and_critic(): + from isaaclab_tutorial.active_gaze.configuration import compose + from isaaclab_tutorial.active_gaze.language import instruction_index + + cnn = compose(["presets=numbered", "env.scene.eye.cmf_a=0.0075"])[0] + cfg = compose(["presets=dino_language", "env.scene.eye.cmf_a=0.0075"])[0] + assert cfg.scene.eye.foveated_res == 128 + assert cfg.observations.scene_rgb is None + assert cfg.observations.proprioception is None + assert cfg.observations.gaze is None + assert cfg.observations.critic.to_dict() == cnn.observations.critic.to_dict() + assert cfg.terminations.to_dict() == cnn.terminations.to_dict() + assert cfg.rewards.to_dict() == cnn.rewards.to_dict() + assert cfg.events.to_dict() == cnn.events.to_dict() + for key, value in cnn.observations.proprioception.to_dict().items(): + assert cfg.observations.proprio.to_dict()[key] == value + env = SimpleNamespace(num_envs=4, device="cpu", vial_number=torch.arange(1, 5)) + assert torch.equal(instruction_index(env), torch.zeros(4, 1, dtype=torch.long)) + with pytest.raises(ValueError, match="128px"): + compose(["presets=dino_language", "env.scene.eye.foveated_res=64"]) + assert cfg.goal_mode == "numbered" + + +@pytest.mark.parametrize("gaze_supervision", ["none", "grasp_gated"]) +def test_language_actor_uses_vision_excludes_state_and_round_trips(tmp_path, gaze_supervision): + from isaaclab_tutorial.active_gaze.learning.config import LanguageVisionActorCfg + from isaaclab_tutorial.active_gaze.learning.language import COSMOS_MODEL, COSMOS_REVISION + from isaaclab_tutorial.active_gaze.learning.models import LanguageVisionActor + from isaaclab_tutorial.active_gaze.configuration import compose + from isaaclab_tutorial.active_gaze.language import INSTRUCTIONS + + suffix = ",grasp_gated" if gaze_supervision == "grasp_gated" else ",no_gaze_supervision" + cfg = compose([f"presets=dino_language{suffix}"])[1].to_dict() + baseline = compose([f"presets=nearest{suffix}"])[1].to_dict() + assert cfg["critic"] == baseline["critic"] + assert cfg["obs_groups"]["critic"] == ["critic"] + assert cfg["algorithm"].get("rnd_cfg") is None + for key in ("hidden_dims", "fusion_dim", "fusion_width", "fusion_heads", "fusion_blocks", "spatial_channels"): + assert cfg["actor"][key] == getattr(LanguageVisionActorCfg(), key) + table_path = tmp_path / "instructions.pt" + torch.save( + dict( + identity=dict( + format=1, + instructions=list(INSTRUCTIONS), + checkpoint=COSMOS_MODEL, + revision=COSMOS_REVISION, + max_tokens=128, + ), + features=torch.randn(1, 128, 12).bfloat16(), + padding=(torch.arange(128) >= 11)[None], + ), + table_path, + ) + actor_cfg = cfg["actor"].copy() + actor_cfg.pop("class_name") + actor_cfg["instruction_table_path"] = str(table_path) + obs = TensorDict( + dict( + proprio=torch.randn(4, 32), + vision=torch.randn(4, 8, 16), + instruction=torch.zeros(4, 1, dtype=torch.long), + critic=torch.randn(4, 72), + oracle=torch.randn(4, 3), + ), + batch_size=[4], + ) + actor = LanguageVisionActor(obs, cfg["obs_groups"], "actor", 8, **actor_cfg) + output = actor(obs) + assert output.shape == (4, 8) + changed = obs.clone() + changed["critic"].fill_(float("nan")) + changed["oracle"].fill_(float("nan")) + torch.testing.assert_close(actor(changed), output) + changed["vision"].zero_() + assert not torch.allclose(actor(changed), output) + output.square().sum().backward() + assert actor.fusion.text_projection.weight.grad.abs().sum() > 0 + assert actor.fusion.vision_projection.weight.grad.abs().sum() > 0 + assert actor.mlp[-1].weight.grad[-2:].abs().sum() > 0 + assert not actor.language_features.requires_grad + restored = LanguageVisionActor(obs, cfg["obs_groups"], "actor", 8, **actor_cfg) + restored.load_state_dict(deepcopy(actor.state_dict())) + torch.testing.assert_close(restored(obs), output) diff --git a/tests/active_gaze/test_numbered.py b/tests/active_gaze/test_numbered.py new file mode 100644 index 0000000..5c0d725 --- /dev/null +++ b/tests/active_gaze/test_numbered.py @@ -0,0 +1,246 @@ +"""Number matching, wrong-hole rejection, reset coverage, and privileged inputs.""" + +from types import SimpleNamespace + +import torch + + +def test_numbered_resets_preserve_physics_and_cover_all_goals(): + from isaaclab_fovi.assets.so101_vial import RESET_DATASET + from isaaclab_tutorial.active_gaze.goals import expand_numbered_resets + from isaaclab_tutorial.tasks.place_vial.mdp.events import phase_balanced_row_weights + from isaaclab_tutorial.active_gaze.reset import load_reset_dataset + + source = load_reset_dataset(RESET_DATASET)["states"] + states, bins, names, phases = expand_numbered_resets(source, (0.18, 0.08, 0.04, 0, 0, 0, 1)) + for key in ("joint_position", "joint_target", "vial_pose", "phase", "lifted"): + torch.testing.assert_close(states[key], source[key].repeat_interleave(4, 0), rtol=0, atol=0) + assert torch.equal(states["target_hole"].reshape(-1, 4), torch.arange(4).expand(1024, -1)) + assert len(names) == 14 + assert set(names) == { + "home", + "pregrasp", + "grasp", + "lift", + *[ + f"{phase}_{kind}" + for phase in ("lift", "reorient", "transport", "insert", "release") + for kind in ("target", "non_target") + ], + } + assert torch.bincount(bins).min() > 0 + assert (states["grasped"][bins == names.index("release_non_target")] == 0).all() + # Preserve phase mass and uniform target numbers before SGS adaptation. + row_weights = phase_balanced_row_weights(states["phase"], [1.0] * 8) + torch.testing.assert_close(torch.zeros(8).scatter_add_(0, states["phase"], row_weights), torch.ones(8)) + torch.testing.assert_close( + torch.zeros(4).scatter_add_(0, states["target_hole"], row_weights), torch.full((4,), 2.0) + ) + + +def test_fixed_cap_sampling_is_balanced_shuffled_and_conditional(): + import numpy as np + + from isaaclab_tutorial.active_gaze.goals import ( + balanced_shuffled_clones, + conditional_row_probabilities, + sample_matching_rows, + ) + + np.random.seed(91) + targets = torch.tensor(balanced_shuffled_clones(np.ones(4), 4096)) + assert torch.equal(torch.bincount(targets), torch.full((4,), 1024)) + assert not torch.equal(targets, targets.sort().values) + torch.manual_seed(91) + weights = torch.tensor([[0.0, 1.0, 2.0, 3.0], [4.0, 3.0, 2.0, 0.0]]) + draws = sample_matching_rows(weights.flatten(), targets) + assert torch.equal(draws % 4, targets) + assert not (draws == 0).any() + assert not (draws == 7).any() + expected = conditional_row_probabilities(weights.flatten(), torch.full((4,), 0.25)) + empirical = torch.bincount(draws, minlength=8) / len(draws) + torch.testing.assert_close(empirical, expected, atol=0.015, rtol=0) + + +def test_partial_resets_preserve_cap_and_restore_matching_stock_rows(monkeypatch): + from isaaclab_tutorial.active_gaze.goals import NumberedResetFromDataset, ResetFromDataset + + numbers = torch.tensor([4, 1, 3, 2]) + env = SimpleNamespace( + num_envs=4, + device="cpu", + vial_number=numbers.clone(), + numbered_target_hole=numbers - 1, + _so101_reset_row=torch.full((4,), -1), + ) + reset = object.__new__(NumberedResetFromDataset) + reset.states = {"target_hole": torch.arange(4).repeat(8)} + reset.row_weights = torch.ones(32) + reset.sequential_rows = torch.arange(32) + reset.cursor = 0 + + def restore(self, env, ids, path, phases, sequential, *args): + assert sequential + env._so101_reset_row[ids] = self.sequential_rows + + monkeypatch.setattr(ResetFromDataset, "__call__", restore) + for sequential in (False, True): + for _ in range(10): + reset(env, torch.tensor([0, 2]), "unused", [], sequential=sequential) + assert torch.equal(env.vial_number, numbers) + assert torch.equal(env.numbered_target_hole, numbers - 1) + assert env._so101_reset_row[[1, 3]].tolist() == [-1, -1] + assert torch.equal(env._so101_reset_row[[0, 2]] % 4, numbers[[0, 2]] - 1) + + +def test_numbered_configuration_keeps_target_in_critic_only(): + from isaaclab.sim import MultiAssetSpawnerCfg + from isaaclab_tasks.utils import resolve_presets + + from isaaclab_tutorial.active_gaze.env_cfg import SO101NumberedEnvCfg + from isaaclab_tutorial.active_gaze.configuration import compose + + plain = compose(["presets=nearest", "renderer=newton_renderer"])[0] + numbered = resolve_presets(SO101NumberedEnvCfg()) + assert plain.renderer_backend() == "warp" + assert numbered.renderer_backend() == "ovrtx" + assert numbered.scene.eye.offset.pos[0] < plain.scene.eye.offset.pos[0] + assert numbered.camera_hfov() < plain.camera_hfov() + assert numbered.observations.scene_rgb.to_dict() == plain.observations.scene_rgb.to_dict() + assert numbered.observations.proprioception.to_dict() == plain.observations.proprioception.to_dict() + assert numbered.observations.gaze.to_dict() == plain.observations.gaze.to_dict() + assert not hasattr(plain.observations.critic, "numbered_goal") + assert numbered.observations.critic.numbered_goal is not None + assert isinstance(numbered.scene.vial.spawn, MultiAssetSpawnerCfg) + assert [v.vial_number for v in numbered.scene.vial.spawn.assets_cfg] == [1, 2, 3, 4] + assert not hasattr(numbered.scene, "vial_number") + for mode in ("none", "grasp_gated"): + assert compose(["presets=nearest" + (",grasp_gated" if mode == "grasp_gated" else "")])[1].to_dict()[ + "obs_groups" + ]["actor"] == ["scene_rgb", "proprioception", "gaze"] + warp, _, _ = compose(["presets=dino_language", "renderer=newton_renderer"]) + assert warp.goal_mode == "numbered" + assert warp.scene.eye.data_types == ["rgb"] + assert warp.observations.vision.tokens.params["data_type"] == "rgb" + assert warp.scene.eye.render_settings == {} + assert warp.render_mode() == "rgb" + + +def test_wrong_hole_never_pays_insert_or_success(monkeypatch): + from isaaclab.managers import TerminationTermCfg + + from isaaclab_tutorial.active_gaze import goals + from isaaclab_tutorial.tasks.place_vial.mdp import terminations as stock + from isaaclab_tutorial.tasks.place_vial.mdp.geometry import RACK_HOLE_CENTERS + + position = torch.tensor(RACK_HOLE_CENTERS) + position[:, 2] = 0.031 + axis = torch.tensor([0.0, 0.0, 1.0]).expand(4, -1) + + def coordinates(_): + return position, axis, torch.full((4,), 0.014) + + monkeypatch.setattr(stock, "vial_in_rack", coordinates) + monkeypatch.setattr(goals, "vial_in_rack", coordinates) + monkeypatch.setattr(stock, "vial_upright", lambda _: torch.ones(4)) + monkeypatch.setattr(stock, "vial_height", lambda _: torch.full((4,), 0.071)) + monkeypatch.setattr(stock, "jaw_contacts", lambda _: (torch.zeros(4, dtype=torch.bool),) * 2) + monkeypatch.setattr(stock, "gripper_openness", lambda _: torch.ones(4)) + monkeypatch.setattr(stock, "contact_force", lambda *_: torch.zeros(4)) + vial = SimpleNamespace( + data=SimpleNamespace( + root_lin_vel_w=SimpleNamespace(torch=torch.zeros(4, 3)), + root_ang_vel_w=SimpleNamespace(torch=torch.zeros(4, 3)), + ) + ) + + class Scene(dict): + sensors = {} + + env = SimpleNamespace( + num_envs=4, + device="cpu", + scene=Scene(vial=vial), + extras={}, + numbered_target_hole=torch.tensor([0, 0, 2, 1]), + episode_length_buf=torch.ones(4, dtype=torch.long), + step_dt=1 / 30, + ) + term = goals.TargetPlacementSuccess(TerminationTermCfg(func=goals.TargetPlacementSuccess), env) + for step in range(12): + env.episode_length_buf[:] = step + result = term(env) + assert result.tolist() == [True, False, True, False] + assert term.progress.inserted.tolist() == [True, False, True, False] + assert term.progress.stable_count[[1, 3]].tolist() == [0, 0] + assert env._so101_terminal_hole.tolist() == [0, -1, 2, -1] + # Moving the vial from a wrong opening into its target earns normal stable success. + position[1] = position[0] + for _ in range(10): + result = term(env) + assert result.tolist() == [True, True, True, False] + + +def test_gaze_cache_tracks_selected_target_and_cap(): + from fovi.sensing.projection import CameraModel + from isaaclab_tasks.utils import resolve_presets + + from isaaclab_tutorial.active_gaze.env_cfg import SO101NumberedEnvCfg + from isaaclab_tutorial.active_gaze.gaze import angles_to_direction, build_reset_cache + + cfg = resolve_presets(SO101NumberedEnvCfg()) + rack = cfg.scene.rack.init_state + cache = build_reset_cache( + cfg.events.reset_from_dataset.params["dataset_path"], + cfg.scene.eye, + (*rack.pos, *rack.rot), + cfg.actions.gaze.angle_limit, + numbered=True, + ) + gaze = cache["vision_action"] + assert gaze.shape == (4096, 5, 16, 2) + assert CameraModel(**cfg.scene.eye.camera_calibration).project(angles_to_direction(gaze))[1].all() + # A single physical reset has four distinct exact goal fixations, one per opening. + assert torch.unique(gaze[:4, 2, 0], dim=0).shape[0] == 4 + assert torch.unique(gaze[:4, 1, 0], dim=0).shape[0] == 1 + + +def test_numbered_sgs_tracks_and_restores_each_reset_category(): + from isaaclab.managers import CurriculumTermCfg + + from isaaclab_fovi.assets.so101_vial import RESET_DATASET + from isaaclab_tutorial.active_gaze.goals import expand_numbered_resets + from isaaclab_tutorial.tasks.place_vial.mdp.events import phase_balanced_row_weights + from isaaclab_tutorial.active_gaze.reset import load_reset_dataset + from isaaclab_tutorial.active_gaze.sampling import ResetSampling, iteration_metrics + + source = load_reset_dataset(RESET_DATASET)["states"] + + def make_sampler(): + states, bins, names, _ = expand_numbered_resets(source, (0.18, 0.08, 0.04, 0, 0, 0, 1)) + reset = SimpleNamespace( + states=states, + bin_ids=bins, + bin_names=names, + row_weights=phase_balanced_row_weights(states["phase"], [1.0] * 8), + ) + env = SimpleNamespace( + device="cpu", + num_envs=4, + event_manager=SimpleNamespace(get_term_cfg=lambda _: SimpleNamespace(func=reset)), + ) + return ResetSampling(CurriculumTermCfg(func=ResetSampling, params={"mode": "sgs"}), env) + + sampler = make_sampler() + for i in range(len(sampler.bin_names)): + sampler.history.update(torch.full((10,), i), torch.arange(10) < i % 11) + sampler.apply_distribution() + metrics, _ = iteration_metrics(sampler, 0) + for i, name in enumerate(sampler.bin_names): + assert metrics[f"Reset/episodes/{name}"] == 10 + assert metrics[f"Reset/success_rate/{name}"] == (i % 11) / 10 + assert metrics[f"SGS/probability/{name}"] > 0 + restored = make_sampler() + restored.load_state_dict(sampler.state_dict()) + torch.testing.assert_close(restored.phase_probabilities(), sampler.phase_probabilities()) + torch.testing.assert_close(restored.history.episodes, sampler.history.episodes) diff --git a/tests/active_gaze/test_presets.py b/tests/active_gaze/test_presets.py new file mode 100644 index 0000000..b01e974 --- /dev/null +++ b/tests/active_gaze/test_presets.py @@ -0,0 +1,94 @@ +"""Native registry composition, default recipe, and checkpoint configuration.""" + +from copy import deepcopy + +import pytest + + +def test_default_recipe_matches_explicit_presets_and_native_registry(): + from isaaclab_tasks.utils import resolve_task_config + + from isaaclab_tutorial.active_gaze import TASK_ID + from isaaclab_tutorial.active_gaze.env_cfg import SO101NumberedEnvCfg + from isaaclab_tutorial.active_gaze.configuration import compose + + env, agent = resolve_task_config(TASK_ID, "rsl_rl_cfg_entry_point", overrides=[]) + explicit, explicit_agent, _ = compose(["presets=numbered,grasp_gated,sgs,minimal_full_mdl_shadows"]) + assert isinstance(env, SO101NumberedEnvCfg) + assert env.to_dict() == explicit.to_dict() + assert agent.to_dict() == explicit_agent.to_dict() + assert env.observations.oracle is not None + assert "oracle" not in agent.obs_groups["actor"] + assert agent.algorithm.class_name.endswith(":OraclePPO") + assert agent.algorithm.oracle_weight == 1.0 + assert env.curriculum.reset_sampling.params["mode"] == "sgs" + assert env.scene.eye.data_types == ["simple_shading_full_mdl"] + assert env.scene.eye.renderer_cfg.enable_shadows + + +def test_native_scalar_overrides_and_resume_preserve_typed_variants(): + from isaaclab_tutorial.active_gaze.agents import SO101Sim2RealPPORunnerCfg + from isaaclab_tutorial.active_gaze.env_cfg import SO101Sim2RealEnvCfg + from isaaclab_tutorial.active_gaze.configuration import checkpoint_configuration, compose, metadata + from isaaclab_tutorial.active_gaze.transfer_options import CameraRandomizationCfg + + env, agent, recipe = compose( + [ + "presets=sim2real,finetune", + "env.scene.eye.cmf_a=0.0075", + "env.sim2real.rotation_deg=4.0", + "agent.algorithm.oracle_weight=2.5", + ] + ) + saved = dict(metadata(env, agent), configuration=checkpoint_configuration(recipe, agent)) + before = deepcopy(saved) + restored, restored_agent, _ = compose(saved=saved) + assert isinstance(restored, SO101Sim2RealEnvCfg) + assert isinstance(restored_agent, SO101Sim2RealPPORunnerCfg) + assert isinstance(restored.sim2real, CameraRandomizationCfg) + assert restored.to_dict() == env.to_dict() + assert not restored_agent.finetune + assert restored_agent.algorithm.learning_rate == 3e-5 + expected_agent = agent.replace(finetune=False) + assert restored_agent.to_dict() == expected_agent.to_dict() + changed, changed_agent, _ = compose(["env.sim2real.rotation_deg=2.0", "agent.algorithm.oracle_weight=0.5"], saved) + assert changed.sim2real.rotation_deg == 2.0 + assert changed.scene.eye.cmf_a == 0.0075 + assert changed_agent.algorithm.oracle_weight == 0.5 + assert saved == before + with pytest.raises(ValueError, match="policy architecture"): + compose(["presets=numbered"], dict(configuration=[], policy={"name": "dino_language"})) + + +def test_checkpoint_requires_native_recipe_and_preserves_explicit_opt_outs(): + from isaaclab_tutorial.active_gaze.configuration import compose, metadata + + explicit, agent, recipe = compose(["presets=nearest,no_gaze_supervision,uniform", "renderer=newton_renderer"]) + restored, restored_agent, _ = compose(saved=dict(metadata(explicit, agent), configuration=recipe)) + assert explicit.to_dict() == restored.to_dict() + assert agent.to_dict() == restored_agent.to_dict() + assert explicit.observations.oracle is None + assert explicit.scene.eye.data_types == ["rgb"] + assert explicit.curriculum.reset_sampling.params["mode"] == "uniform" + assert agent.algorithm.class_name == "PPO" + with pytest.raises(ValueError, match="native configuration recipe"): + compose(saved={"goal_mode": "nearest"}) + + +def test_chunked_checkpoint_restores_recipe_and_rejects_incompatible_action_heads(): + from isaaclab_tasks.utils.hydra import PresetTarget, enumerate_task_presets + + from isaaclab_tutorial.active_gaze import TASK_ID + from isaaclab_tutorial.active_gaze.configuration import compose, metadata + + assert "chunking" in enumerate_task_presets(TASK_ID)[PresetTarget.DOMAIN] + env, agent, recipe = compose(["presets=chunking,no_gaze_supervision"]) + saved = dict(metadata(env, agent), configuration=recipe) + restored, restored_agent, _ = compose(saved=saved) + assert restored.to_dict() == env.to_dict() + assert restored_agent.to_dict() == agent.to_dict() + assert agent.algorithm.action_chunk_size == 3 + assert agent.algorithm.oracle_weight == 0.0 + assert agent.algorithm.class_name.endswith(":OraclePPO") + with pytest.raises(ValueError, match="chunk size"): + compose(["agent.algorithm.action_chunk_size=2"], saved) diff --git a/tests/active_gaze/test_rendering.py b/tests/active_gaze/test_rendering.py new file mode 100644 index 0000000..ea167d4 --- /dev/null +++ b/tests/active_gaze/test_rendering.py @@ -0,0 +1,159 @@ +"""RTX minimal selection preserves numbered-task physics and policy image inputs.""" + +from types import SimpleNamespace + +import pytest +import torch + +MODES = [ + ("rtpt", "rgb", False), + ("minimal_diffuse_mdl", "simple_shading_diffuse_mdl", False), + ("minimal_diffuse_mdl_shadows", "simple_shading_diffuse_mdl", True), + ("minimal_full_mdl", "simple_shading_full_mdl", False), + ("minimal_full_mdl_shadows", "simple_shading_full_mdl", True), +] + + +@pytest.mark.parametrize("mode, output, shadows", MODES) +@pytest.mark.parametrize("policy", ["cnn", "dino_language"]) +def test_mode_reaches_policy_and_diagnostic_cameras(mode, output, shadows, policy): + from isaaclab_tutorial.active_gaze.env_cfg import SceneRGB + from isaaclab_tutorial.active_gaze.configuration import compose + + variant = "dino_language" if policy == "dino_language" else "numbered" + baseline, _, _ = compose([f"presets={variant}"]) + cfg, _, _ = compose([f"presets={variant},{mode}"]) + cfg.enable_diagnostics() + assert cfg.render_mode() == mode + assert cfg.scene.eye.data_types == cfg.scene.diagnostic_camera.data_types == [output] + assert cfg.scene.eye.renderer_cfg.enable_shadows is shadows + assert cfg.scene.diagnostic_camera.renderer_cfg.enable_shadows is shadows + assert cfg.sim.physics.to_dict() == baseline.sim.physics.to_dict() + assert cfg.scene.eye.camera_calibration == baseline.scene.eye.camera_calibration + assert cfg.scene.eye.cmf_a == baseline.scene.eye.cmf_a + image = torch.full((2, cfg.scene.eye.foveated_res, cfg.scene.eye.foveated_res, 3), 127, dtype=torch.uint8) + camera = SimpleNamespace(cfg=cfg.scene.eye, data=SimpleNamespace(output={output: image})) + env = SimpleNamespace(scene={"eye": camera}) + actual = SceneRGB(SimpleNamespace(), env)(env) + torch.testing.assert_close(actual, image.float().permute(0, 3, 1, 2) / 255) + if policy == "dino_language": + assert cfg.observations.vision.tokens.params["data_type"] == output + + +def test_dino_consumes_selected_minimal_output_without_changing_encoder_arguments(monkeypatch): + from isaaclab_tutorial.active_gaze.learning import observations + + image = torch.full((2, 128, 128, 3), 127, dtype=torch.uint8) + received = {} + + class Encoder: + def __init__(self, **kwargs): + received.update(kwargs) + + def to(self, device): + return self + + def eval(self): + return self + + def __call__(self, value): + assert value is image + return value + + monkeypatch.setattr(observations, "FrozenDino", Encoder) + output = "simple_shading_full_mdl" + cfg = SimpleNamespace(params=dict(reference="local", checksum=None, batch_size=8, data_type=output)) + env = SimpleNamespace(device="cpu", scene={"eye": SimpleNamespace(data=SimpleNamespace(output={output: image}))}) + term = observations.DinoTokens(cfg, env) + assert "data_type" not in received + assert term(env, **cfg.params) is image + + +def test_minimal_requires_ovrtx(): + from isaaclab_tutorial.active_gaze.configuration import compose + + with pytest.raises(ValueError, match="unsupported types"): + compose(["presets=minimal_full_mdl", "env.scene.eye.renderer_cfg=newton_renderer"]) + + +@pytest.mark.parametrize("mode, output, shadows", [MODES[0], MODES[-1]]) +def test_numbered_products_request_denoising_without_aa(mode, output, shadows): + from isaaclab.renderers import CameraRenderSpec + from isaaclab_ov.renderers.ovrtx_renderer import OVRTXCameraRenderData + from isaaclab_ov.renderers.ovrtx_usd import build_render_product_as_string + from pxr import Usd + + from isaaclab_tutorial.active_gaze.configuration import compose + + # Exercise the configured camera at the USD authoring boundary without a CUDA engine. + cfg, _, _ = compose([f"presets=numbered,{mode}"]) + spec = CameraRenderSpec( + cfg=cfg.scene.eye, + camera_prim_paths=("/World/Camera",), + num_instances=1, + view_count=1, + device="cpu", + ) + data = OVRTXCameraRenderData(spec, "TestCamera", list(spec.camera_prim_paths)) + layer = build_render_product_as_string(spec, data, device_id=0, enable_shadows=shadows) + stage = Usd.Stage.CreateInMemory() + stage.GetRootLayer().ImportFromString(layer) + product = stage.GetPrimAtPath("/TestCamera/RenderProduct") + assert product.GetAttribute("omni:rtx:post:aa:op").Get() == "none" + assert product.GetAttribute("omni:rtx:newDenoiser:enabled").Get() is True + samples = product.GetAttribute("omni:rtx:rtpt:spp") + assert bool(samples) is (mode == "rtpt") + if samples: + assert samples.Get() == 4 + + +@pytest.mark.parametrize("kind", ["cnn", "dino", "randomized_dino"]) +def test_visual_observations_refresh_only_at_policy_boundaries(monkeypatch, kind): + from isaaclab_tutorial.active_gaze.learning import observations + from isaaclab_tutorial.active_gaze.env_cfg import SceneRGB + from isaaclab_tutorial.active_gaze.sim2real import RandomizedDinoTokens + + reads = [] + encodes = [] + image = torch.full((2, 4, 4, 3), 127, dtype=torch.uint8) + + class Camera: + cfg = SimpleNamespace(data_types=["rgb"]) + + @property + def data(self): + reads.append(True) + return SimpleNamespace(output={"rgb": image}) + + class Encoder: + def __init__(self, **kwargs): + pass + + def to(self, device): + return self + + def eval(self): + return self + + def __call__(self, image): + encodes.append(True) + return image.float().mean(dim=(1, 2)) + + monkeypatch.setattr(observations, "FrozenDino", Encoder) + env = SimpleNamespace( + device="cpu", + scene={"eye": Camera()}, + refresh_policy_vision=False, + so101_camera_randomization=SimpleNamespace(image=lambda value: value), + ) + params = {} if kind == "cnn" else dict(reference="local", checksum=None, batch_size=2) + term_type = {"cnn": SceneRGB, "dino": observations.DinoTokens, "randomized_dino": RandomizedDinoTokens}[kind] + term = term_type(SimpleNamespace(params=params), env) + first = term(env, **params).clone() # Empty cache must populate even during a chunk. + image.fill_(255) + torch.testing.assert_close(term(env, **params), first) + assert len(reads) == 1 + env.refresh_policy_vision = True + assert not torch.equal(term(env, **params), first) + assert len(reads) == 2 + assert len(encodes) == (0 if kind == "cnn" else 2) diff --git a/tests/active_gaze/test_robot_geometry.py b/tests/active_gaze/test_robot_geometry.py new file mode 100644 index 0000000..c83a1ff --- /dev/null +++ b/tests/active_gaze/test_robot_geometry.py @@ -0,0 +1,38 @@ +"""Camera removal must preserve grasp geometry and support portable continuation.""" + +import pytest + + +def test_camera_removal_disables_sensor_visuals_and_contacts_only(): + from pxr import Usd, UsdPhysics + + from isaaclab_tutorial.active_gaze.robot_geometry import WRIST_CAMERA_PARTS, remove_wrist_camera + + stage = Usd.Stage.CreateInMemory() + robot = stage.DefinePrim("/Robot", "Xform") + gripper = stage.DefinePrim("/Robot/gripper", "Xform") + mass = UsdPhysics.MassAPI.Apply(gripper) + mass.CreateMassAttr(0.087) + jaw = stage.DefinePrim("/Robot/gripper/collisions/fixed_jaw", "Cube") + UsdPhysics.CollisionAPI.Apply(jaw) + moving = stage.DefinePrim("/Robot/moving_jaw_so101_v1", "Xform") + for part in WRIST_CAMERA_PARTS: + stage.DefinePrim(robot.GetPath().AppendPath(part), "Xform") + housing = stage.DefinePrim("/Robot/gripper/collisions/camera_mount/collider", "Cube") + UsdPhysics.CollisionAPI.Apply(housing) + remove_wrist_camera(robot) + assert all(not stage.GetPrimAtPath(robot.GetPath().AppendPath(p)).IsActive() for p in WRIST_CAMERA_PARTS) + assert jaw.IsActive() and jaw.HasAPI(UsdPhysics.CollisionAPI) + assert moving.IsActive() + assert mass.GetMassAttr().Get() == pytest.approx(0.087) + active_colliders = [p for p in stage.Traverse() if p.HasAPI(UsdPhysics.CollisionAPI)] + assert active_colliders == [jaw] + + +def test_camera_variant_keeps_policy_spaces_and_other_task_settings(): + from isaaclab_tutorial.active_gaze.configuration import compose + + stock = compose(["presets=numbered,stock_wrist_camera"])[0].to_dict() + removed = compose(["presets=numbered"])[0].to_dict() + assert removed["scene"]["robot"]["spawn"].pop("func") != stock["scene"]["robot"]["spawn"].pop("func") + assert removed == stock diff --git a/tests/active_gaze/test_sampling.py b/tests/active_gaze/test_sampling.py new file mode 100644 index 0000000..df2fd04 --- /dev/null +++ b/tests/active_gaze/test_sampling.py @@ -0,0 +1,165 @@ +"""SGS math, batched histories, terminal attribution, and logging contracts.""" + +from collections import deque +from types import SimpleNamespace + +import pytest +import torch + +from isaaclab_tutorial.active_gaze.sampling import ( + PHASE_NAMES, + ResetSampling, + SuccessHistory, + iteration_metrics, +) + + +def test_sgs_matches_paper_and_keeps_extremes_sampleable(): + import math + + sampler = SuccessHistory(3, history=10) + sampler.update(torch.arange(3).repeat_interleave(10), torch.tensor([0] * 10 + [0, 1] * 5 + [1] * 10)) + expected = torch.tensor([math.sqrt(max(math.sqrt((p + 1e-4) * (1 - p + 1e-4)), 1e-4) + 1e-4) for p in (0, 0.5, 1)]) + actual = sampler.probabilities(torch.ones(3) / 3) + torch.testing.assert_close(actual, expected / expected.sum()) + assert actual[1] > actual[0] > 0 + assert actual[0] == actual[2] + sampler.settings["concentration"] = 0 + torch.testing.assert_close(sampler.probabilities(torch.ones(3) / 3), torch.ones(3) / 3) + base = torch.tensor([1.0, 0.0, 0.0]) + torch.testing.assert_close(sampler.probabilities(base), base) + + +@pytest.mark.parametrize( + "device", + [ + "cpu", + pytest.param( + "cuda:0", + marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable"), + ), + ], +) +def test_batched_ring_matches_sequential_reference(device): + generator = torch.Generator().manual_seed(9) + sampler = SuccessHistory(8, device, history=7) + reference = [deque(maxlen=7) for _ in range(8)] + total = torch.zeros(8, dtype=torch.long) + success = torch.zeros_like(total) + for size in (0, 3, 100, 2, 800, 17): + bins = torch.randint(8, (size,), generator=generator) + outcomes = torch.rand(size, generator=generator) > 0.4 + sampler.update(bins.to(device), outcomes.to(device)) + for b, outcome in zip(bins.tolist(), outcomes.tolist(), strict=True): + reference[b].append(outcome) + total[b] += 1 + success[b] += outcome + torch.testing.assert_close(sampler.episodes.cpu(), total) + torch.testing.assert_close(sampler.successes.cpu(), success) + expected = torch.tensor([sum(items) / max(len(items), 1) for items in reference]) + torch.testing.assert_close(sampler.rates.cpu(), expected) + restored = SuccessHistory(8, device, history=7) + restored.load_state_dict(sampler.state_dict()) + torch.testing.assert_close(restored.history, sampler.history) + bins, outcomes = ( + torch.tensor([1, 1, 7], device=device), + torch.tensor([True, False, True], device=device), + ) + sampler.update(bins, outcomes) + restored.update(bins, outcomes) + torch.testing.assert_close(restored.history, sampler.history) + + +def make_sampler(mode="sgs"): + from isaaclab.managers import CurriculumTermCfg + + phase = torch.arange(8).repeat_interleave(2) + reset = SimpleNamespace(states={"phase": phase}, row_weights=torch.ones(16) / 16) + success = torch.zeros(4, dtype=torch.bool) + env = SimpleNamespace( + device="cpu", + num_envs=4, + event_manager=SimpleNamespace(get_term_cfg=lambda _: SimpleNamespace(func=reset)), + termination_manager=SimpleNamespace(get_term=lambda _: success), + reset_buf=torch.zeros(4, dtype=torch.bool), + episode_length_buf=torch.zeros(4, dtype=torch.long), + ) + sampler = ResetSampling(CurriculumTermCfg(func=ResetSampling, params={"mode": mode}), env) + return sampler, env, success + + +def test_terminal_attribution_excludes_initial_manual_and_repeated_resets(): + sampler, env, success = make_sampler() + sampler(env, slice(None)) # initial reset before a physical row exists + env._so101_reset_row = torch.tensor([0, 2, 4, 6]) + sampler.reset() + assert sampler.sampled.tolist() == [1, 1, 1, 1, 0, 0, 0, 0] + assert not sampler.history.episodes.any() + env.episode_length_buf[:] = 20 + env.reset_buf[:] = torch.tensor([True, True, False, True]) + success[0] = True + sampler.eligible[3] = False # shortened, staggered initial episode + sampler(env, torch.tensor([0, 1, 2, 3])) + # Success, timeout/failure, explicit manual reset, excluded initial episode. + assert sampler.history.episodes.tolist() == [1, 1, 0, 0, 0, 0, 0, 0] + assert sampler.history.successes.tolist() == [1, 0, 0, 0, 0, 0, 0, 0] + env._so101_reset_row[:] = 15 # stock event replaces rows AFTER curriculum accounting + sampler.reset() + env.episode_length_buf.zero_() + sampler(env, slice(None)) + assert sampler.history.episodes.sum() == 2 + assert sampler.sampled[-1] == 4 + + +def test_adaptation_uses_phase_mass_and_checkpoint_round_trip(): + sampler, _, _ = make_sampler() + bins = torch.arange(8).repeat_interleave(100) + outcomes = torch.zeros(800, dtype=torch.bool) + outcomes[100:150] = True + outcomes[200:300] = True + sampler.history.update(bins, outcomes) + sampler.apply_distribution() + probabilities = sampler.phase_probabilities() + assert probabilities[1] > probabilities[0] + assert probabilities[1] > probabilities[2] + assert (sampler.reset_term.row_weights > 0).all() + torch.testing.assert_close(sampler.reset_term.row_weights[::2], sampler.reset_term.row_weights[1::2]) + restored, _, _ = make_sampler() + restored.load_state_dict(sampler.state_dict()) + torch.testing.assert_close(restored.phase_probabilities(), probabilities) + restored.reset_term.states["phase"][0] = 1 + with pytest.raises(ValueError, match="dataset"): + restored.load_state_dict(sampler.state_dict()) + + +def test_uniform_sampling_only_tracks_and_metrics_weight_episodes(): + sampler, _, _ = make_sampler("uniform") + original = sampler.reset_term.row_weights.clone() + sampler.history.update(torch.zeros(1, dtype=torch.long), torch.ones(1, dtype=torch.bool)) + sampler.history.update(torch.zeros(9, dtype=torch.long), torch.zeros(9, dtype=torch.bool)) + sampler.history.update(torch.ones(2, dtype=torch.long), torch.tensor([True, False])) + sampler.apply_distribution() + torch.testing.assert_close(sampler.reset_term.row_weights, original) + metrics, previous = iteration_metrics(sampler, 0) + assert metrics["Reset/success_rate/home"] == 0.1 # not mean(1/1, 0/9) + assert metrics["Reset/success_rate/overall"] == 2 / 12 + assert "Reset/success_rate/grasp" not in metrics # no data must not be logged as a failure + metrics, _ = iteration_metrics(sampler, previous) + assert metrics["Reset/episodes/home"] == 0 + assert "Reset/success_rate/home" not in metrics + assert "Reset/success_rate_rolling/home" in metrics + + +def test_saved_settings_and_canonical_evaluation(): + from isaaclab_tutorial.active_gaze.configuration import compose + + saved = dict(configuration=["presets=sgs"]) + cfg, _, _ = compose(saved=saved) + assert cfg.curriculum.reset_sampling.params["mode"] == "sgs" + uniform, _, _ = compose(["env.curriculum.reset_sampling.params.mode=uniform"], saved) + assert uniform.curriculum.reset_sampling.params["mode"] == "uniform" + cfg.play_mode() + assert cfg.curriculum.reset_sampling.params["mode"] == "uniform" + assert cfg.reset_sampling_evaluation + assert cfg.events.reset_from_dataset.params["phase_weights"] == (1, 0, 0, 0, 0, 0, 0, 0) + assert len(PHASE_NAMES) == 8 diff --git a/tests/active_gaze/test_sim2real.py b/tests/active_gaze/test_sim2real.py new file mode 100644 index 0000000..c4b81f1 --- /dev/null +++ b/tests/active_gaze/test_sim2real.py @@ -0,0 +1,319 @@ +"""Transfer preserves learned state and keeps camera supervision out of actions.""" + +from copy import deepcopy +from types import SimpleNamespace + +import pytest +import torch +from tensordict import TensorDict + +from isaaclab_fovi.deployment.so101.planar import PlanarRetina, gaze_basis, project_gaze_rays +from isaaclab_tutorial.active_gaze.camera_geometry import pose_loss, pose_targets +from isaaclab_tutorial.active_gaze.configuration import compose + + +def test_planar_coordinates_do_not_require_physical_intrinsics(): + retina = PlanarRetina(resolution=16) + gaze = torch.tensor([[0.0, 0.0], [0.2, -0.3]]) + pixels, valid = retina.pixels(gaze) + center_rays = torch.tensor([[0.0, 0.0, 1.0]]) + center, _ = project_gaze_rays(center_rays, gaze, retina.focal_pixels, retina.center_pixels, 640) + torch.testing.assert_close(retina.angles(center[:, 0]), gaze) + # Reproduce the actual renderer's shared canonical LUT and upright permutation. + from isaaclab_fovi.sensors.native_grid import native_grid_directions + from isaaclab_fovi.sensors.pooling import build_lowres_coords + + cfg = compose(["presets=sim2real", "env.scene.eye.cmf_a=0.0075"])[0] + cfg.scene.eye.foveated_res = 16 + coords, _ = build_lowres_coords(cfg.scene.eye, device="cpu") + rays = native_grid_directions(coords, tangent_scale=320 / retina.focal) + rays *= torch.tensor((1, -1, -1)) + torch.testing.assert_close(coords.as_grid(rays, sample_dim=0).reshape(-1, 3), retina.rays) + expected, visible = project_gaze_rays(rays, gaze, retina.focal_pixels, retina.center_pixels, 640) + torch.testing.assert_close(coords.as_grid(expected, sample_dim=1), pixels) + assert torch.equal(coords.as_grid(visible & coords.valid_mask, sample_dim=1)[..., None], valid) + image = torch.arange(640).view(1, 1, 640, 1).expand(2, 640, 640, 3).remainder(256).byte() + output = retina(image, gaze) + assert output.shape == (2, 16, 16, 3) and output.dtype == torch.uint8 + assert (output[~valid.expand_as(output)] == 0).all() + + +@pytest.mark.gpu +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA sampler export") +def test_planar_export_keeps_uint8_rounding_after_cuda_mapping(tmp_path): + model = PlanarRetina(resolution=128).cuda().eval() + rgb = torch.randint(0, 256, (1, 640, 640, 3), device="cuda", dtype=torch.uint8) + gaze = torch.zeros(1, 2, device="cuda") + with torch.inference_mode(), torch.jit.optimized_execution(False): + path = tmp_path / "retina.pt" + torch.jit.trace(model, (rgb, gaze), check_trace=False).save(str(path)) + restored = torch.jit.load(str(path), map_location="cuda").to("cuda").eval() + for angles in ((0.0, 0.0), (0.2, -0.3), (-0.6, 0.5)): + gaze[:] = torch.tensor(angles, device="cuda") + assert torch.equal(restored(rgb, gaze), model(rgb, gaze)) + + +def test_pose_metrics_remain_accurate_under_mixed_precision(): + from isaaclab.utils.math import matrix_from_quat, quat_from_euler_xyz + + angle = torch.tensor([torch.pi / 180]) + rotation = matrix_from_quat(quat_from_euler_xyz(angle, angle * 0, angle * 0)) + targets = pose_targets(torch.tensor([[0.01, 0.0, 0.0]]), rotation) + with torch.autocast("cpu", dtype=torch.bfloat16): + loss, metrics = pose_loss(torch.zeros_like(targets), targets) + assert loss > 0 + assert metrics["extrinsics_translation_cm"].item() == pytest.approx(1, abs=1e-5) + assert metrics["extrinsics_rotation_deg"].item() == pytest.approx(1, abs=1e-3) + + +def test_transfer_presets_inherit_without_mutating_saved_metadata(): + from isaaclab_tutorial.active_gaze.transfer_options import CameraRandomizationCfg + + saved = dict(configuration=["presets=sim2real", "env.sim2real.rotation_deg=3.0"], policy={"name": "dino_language"}) + before = deepcopy(saved) + env, agent, _ = compose(["presets=sim2real,finetune", "env.sim2real.rotation_deg=7.0"], saved) + assert isinstance(env.sim2real, CameraRandomizationCfg) + assert env.sim2real.rotation_deg == 7 + assert agent.algorithm.extrinsics_weight == 0.05 + assert agent.finetune and agent.algorithm.learning_rate == 3e-5 + assert saved == before + with pytest.raises(ValueError, match="nominal sampling fraction"): + compose(["presets=sim2real", "env.sim2real.nominal_fraction=2.0"]) + + +def test_randomizations_preserve_numbered_reset_and_control_contract(): + base = compose(["presets=dino_language"])[0] + varied = compose(["presets=sim2real"])[0] + assert base.actions.to_dict() == varied.actions.to_dict() + assert base.scene.robot.init_state.to_dict() == varied.scene.robot.init_state.to_dict() + assert base.scene.robot.spawn.shoulder_response == varied.scene.robot.spawn.shoulder_response + assert base.scene.robot.spawn.elbow_response == varied.scene.robot.spawn.elbow_response + assert base.rewards.to_dict() == varied.rewards.to_dict() + assert base.episode_length_s == varied.episode_length_s + assert base.observations.critic.to_dict() == varied.observations.critic.to_dict() + assert varied.observations.proprio.to_dict() == base.observations.proprio.to_dict() + assert base.observations.extrinsics is None and varied.observations.extrinsics is not None + assert varied.scene.eye.field_geometry == "planar" and base.scene.eye.field_geometry == "spherical" + from isaaclab_fovi.sensors.foveated_rtx_tiled_camera import FoveatedRTXTiledCamera + + assert issubclass(varied.scene.eye.class_type, FoveatedRTXTiledCamera) + assert varied.scene.eye.spawn.horizontal_aperture == base.scene.eye.spawn.horizontal_aperture + assert varied.scene.diagnostic_camera is None # Training allocates no dense camera. + assert varied.events.reset_from_dataset.func == base.events.reset_from_dataset.func + for key in ("dataset_path", "phase_weights", "sequential"): + assert varied.events.reset_from_dataset.params.get(key) == base.events.reset_from_dataset.params.get(key) + assert varied.scene.support is not None and varied.events.to_dict().get("camera_mount") is None + assert all(asset.randomize_diameters for asset in varied.scene.vial.spawn.assets_cfg) + + +def test_partial_camera_reset_preserves_other_scenes_and_ignores_grid_origin(): + from isaaclab_tutorial.active_gaze.sim2real import CameraRandomization + + cfg = compose(["presets=sim2real", "env.sim2real.nominal_fraction=0.0", "env.sim2real.ramp_steps=0"])[0] + camera = SimpleNamespace(cfg=cfg.scene.eye, reset=lambda **kwargs: None) + + def set_pose(position, rotation, env_ids): + camera.world = position.clone() + + camera.set_physical_poses = set_pose + + class Scene(dict): + env_origins = torch.tensor([[3.0, 4.0, 0.0], [-5.0, 7.0, 0.0], [9.0, 2.0, 0.0]]) + sensors = {"eye": camera} + + scene = Scene( + eye=camera, + robot=SimpleNamespace( + data=SimpleNamespace(root_quat_w=SimpleNamespace(torch=torch.tensor([[0.0, 0.0, 0.0, 1.0]]).expand(3, -1))) + ), + ) + env = SimpleNamespace(scene=scene, cfg=cfg, device="cpu", num_envs=3, common_step_counter=0, extras={}) + state = CameraRandomization(None, env) + torch.manual_seed(7) + state(env, None) + assert torch.equal(state.intrinsics, state.nominal_intrinsics) + assert not state.radial.any() + torch.testing.assert_close(camera.world, state.position + scene.env_origins) + before = { + name: getattr(state, name).clone() + for name in ("position", "rotation", "intrinsics", "radial", "targets", "photo") + } + torch.manual_seed(91) + state(env, torch.tensor([1])) + expected_target = state.targets[1].clone() + for name, value in before.items(): + assert torch.equal(getattr(state, name)[[0, 2]], value[[0, 2]]) + scene.env_origins += 1000 + torch.manual_seed(91) + state(env, torch.tensor([1])) + torch.testing.assert_close(expected_target, state.targets[1]) + torch.testing.assert_close(camera.world, state.position[1:2] + scene.env_origins[1:2]) + + +def make_actor(tmp_path, head): + from isaaclab_tutorial.active_gaze.learning.language import COSMOS_MODEL, COSMOS_REVISION + from isaaclab_tutorial.active_gaze.learning.models import LanguageVisionActor + + path = tmp_path / "instructions.pt" + if not path.exists(): + torch.save( + dict( + identity=dict( + format=1, + instructions=["place"], + checkpoint=COSMOS_MODEL, + revision=COSMOS_REVISION, + max_tokens=128, + ), + features=torch.randn(1, 128, 12).bfloat16(), + padding=(torch.arange(128) >= 6)[None], + ), + path, + ) + obs = TensorDict( + dict( + proprio=torch.randn(4, 32), + vision=torch.randn(4, 4, 8), + instruction=torch.zeros(4, 1, dtype=torch.long), + critic=torch.randn(4, 72), + extrinsics=torch.randn(4, 9), + ), + [4], + ) + actor = LanguageVisionActor( + obs, + {"actor": ["proprio", "vision", "instruction"]}, + "actor", + 8, + instructions=("place",), + instruction_table_path=str(path), + fusion_width=16, + fusion_heads=2, + fusion_blocks=1, + fusion_dim=8, + spatial_channels=2, + hidden_dims=[16], + obs_normalization=True, + distribution_cfg=dict(class_name="GaussianDistribution", init_std=0.2, std_type="log"), + extrinsics_head=head, + ) + return actor, obs + + +def test_auxiliary_updates_shared_vision_without_leaking_labels(tmp_path): + from rsl_rl.models import MLPModel + from rsl_rl.storage import RolloutStorage + + from isaaclab_tutorial.active_gaze.pose_ppo import ExtrinsicsPPO + + actor, obs = make_actor(tmp_path, True) + actions = actor(obs) + corrupted = obs.clone() + corrupted["extrinsics"].fill_(float("nan")) + corrupted["critic"].fill_(float("nan")) + torch.testing.assert_close(actor(corrupted), actions) + optimizer = torch.optim.Adam(actor.parameters(), lr=0.001) + # Zero-initialized output starts at the nominal pose. The second update + # must propagate useful pose gradients into the shared visual fusion. + for _ in range(2): + optimizer.zero_grad() + actor(obs) + loss, _ = pose_loss(actor.extrinsics_prediction, obs["extrinsics"]) + loss.backward() + optimizer.step() + assert actor.fusion.vision_projection.weight.grad.abs().sum() > 0 + critic = MLPModel(obs, {"critic": ["critic"]}, "critic", 1, hidden_dims=[16]) + algorithm = ExtrinsicsPPO( + actor, + critic, + RolloutStorage("rl", 4, 2, obs, [8]), + oracle_weight=0, + extrinsics_weight=0.05, + num_learning_epochs=1, + num_mini_batches=1, + schedule="fixed", + ) + with torch.no_grad(): + for _ in range(2): + algorithm.act(obs) + algorithm.process_env_step(obs, torch.ones(4), torch.zeros(4), {}) + algorithm.compute_returns(obs) + metrics = algorithm.update() + assert metrics["extrinsics"] > 0 and metrics["oracle_valid"] == 0 + + +def test_finetune_permits_only_new_head_and_preserves_normalization(tmp_path): + from isaaclab_tutorial.active_gaze.runner import SO101Runner + + old, obs = make_actor(tmp_path, False) + old.obs_normalizer.update(obs["proprio"]) + new, _ = make_actor(tmp_path, True) + critic = torch.nn.Linear(72, 1) + checkpoint = dict( + actor_state_dict=deepcopy(old.state_dict()), + critic_state_dict=critic.state_dict(), + iter=4999, + ) + path = tmp_path / "model.pt" + torch.save(checkpoint, path) + runner = SimpleNamespace(alg=SimpleNamespace(_raw_actor=new, _raw_critic=deepcopy(critic))) + initialized = SO101Runner.finetune(runner, path) + assert initialized and all(key.startswith("extrinsics_head.") for key in initialized) + assert runner.current_learning_iteration == 4999 + torch.testing.assert_close(old(obs), new(obs)) + checkpoint["actor_state_dict"].pop("mlp.0.weight") + torch.save(checkpoint, path) + with pytest.raises(ValueError, match="Unexpected missing"): + SO101Runner.finetune(runner, path) + + +def test_planar_virtual_gaze_preserves_physical_camera_and_partial_resets(monkeypatch): + from isaaclab.sensors import Camera + from isaaclab.utils.math import matrix_from_quat + + from isaaclab_tutorial.active_gaze.sim2real import PlanarSceneCamera + + monkeypatch.setattr(PlanarSceneCamera, "__del__", lambda self: None) + camera = object.__new__(PlanarSceneCamera) + camera.physical_position = torch.randn(3, 3) + camera.physical_rotation = torch.tensor([[0.0, 0.0, 0.0, 1.0]]).expand(3, -1).clone() + camera.gaze = torch.tensor([[0.2, -0.3], [-0.4, 0.5], [0.6, -0.1]]) + captured = {} + + def capture(self, position, rotation, env_ids, convention): + assert convention == "opengl" + captured.update(position=position.clone(), rotation=rotation.clone(), ids=env_ids) + + monkeypatch.setattr(Camera, "set_world_poses", capture) + camera.set_calibrated_angles(camera.gaze) + torch.testing.assert_close(captured["position"], camera.physical_position) + basis = torch.tensor((1, -1, -1)) + expected = gaze_basis(camera.gaze) * basis[None, :, None] * basis[None, None, :] + torch.testing.assert_close(matrix_from_quat(captured["rotation"]), expected) + before = camera.physical_position.clone() + gaze = camera.gaze.clone() + camera.set_physical_poses(torch.zeros(1, 3), torch.tensor([[0.0, 0.0, 0.0, 1.0]]), torch.tensor([1])) + torch.testing.assert_close(camera.physical_position[[0, 2]], before[[0, 2]]) + torch.testing.assert_close(camera.gaze, gaze) + assert captured["position"].shape == (1, 3) + + +@pytest.mark.gpu +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA direct-render visibility") +def test_direct_visibility_matches_export_without_broadcast_allocation(): + from isaaclab_fovi.deployment.so101.planar import project_pinhole_rays + from isaaclab_fovi.sensors.calibrated_geometry import rotate_camera_rays + + retina = PlanarRetina().cuda() + gaze = torch.tensor([[0.0, 0.0], [0.2, -0.3], [-0.6, 0.5]], device="cuda") + expected_pixels, expected_valid = project_gaze_rays( + retina.rays, gaze, retina.focal_pixels, retina.center_pixels, 640 + ) + pixels, valid = project_pinhole_rays( + rotate_camera_rays(retina.rays, gaze_basis(gaze)), + retina.focal_pixels, + retina.center_pixels, + 640, + ) + assert torch.equal(valid, expected_valid) + torch.testing.assert_close(pixels[valid], expected_pixels[valid], atol=1e-3, rtol=1e-5) diff --git a/tests/active_gaze/test_training_utilities.py b/tests/active_gaze/test_training_utilities.py new file mode 100644 index 0000000..3d3e74a --- /dev/null +++ b/tests/active_gaze/test_training_utilities.py @@ -0,0 +1,35 @@ +"""Local training measurement contracts.""" + +import pytest + +from isaaclab_tutorial.active_gaze.training.calibrate import valid_measurement +from isaaclab_tutorial.active_gaze.training.memory import minibatch_count + + +def test_minibatches_preserve_every_transition(): + assert minibatch_count(256, 32, 1024) == 8 + for envs, steps, batch in ((0, 32, 512), (128, 32, 0), (127, 32, 512), (4, 32, 256)): + with pytest.raises(ValueError): + minibatch_count(envs, steps, batch) + + +def test_measurement_rejects_incomplete_nonfinite_and_over_budget(): + measured = dict( + complete=True, + measured_updates=20, + peak_conservative_bytes=70, + total_bytes=100, + mean_total_fps=123.0, + ) + assert valid_measurement(measured, 20, 0.8) + for changed in ( + dict(complete=False), + dict(measured_updates=19), + dict(peak_conservative_bytes=81), + dict(peak_conservative_bytes=0), + dict(mean_total_fps=float("nan")), + dict(mean_total_fps=0), + dict(error="NVML unavailable"), + ): + assert not valid_measurement(measured | changed, 20, 0.8) + assert not valid_measurement(measured | dict(measured_updates=0), 0, 0.8) diff --git a/tests/active_gaze/test_vial.py b/tests/active_gaze/test_vial.py new file mode 100644 index 0000000..5522b5c --- /dev/null +++ b/tests/active_gaze/test_vial.py @@ -0,0 +1,230 @@ +"""Contracts for direct visual PPO, without launching physics.""" + +from types import SimpleNamespace + +import pytest +import torch +from tensordict import TensorDict + + +@pytest.mark.parametrize("resolution", [64, 128]) +def test_encoder_and_gaze_receive_gradients(resolution): + from rsl_rl.models import CNNModel + + from isaaclab_tutorial.active_gaze.agents import SO101FoveatedPPORunnerCfg + + cfg = SO101FoveatedPPORunnerCfg().to_dict() + actor_cfg = cfg["actor"].copy() + actor_cfg.pop("class_name") + obs = TensorDict( + { + "scene_rgb": torch.rand(4, 3, resolution, resolution), + "proprioception": torch.randn(4, 26), + "gaze": torch.randn(4, 6), + }, + batch_size=[4], + ) + actor = CNNModel(obs, cfg["obs_groups"], "actor", 8, **actor_cfg) + result = actor(obs) + result.square().sum().backward() + assert any(p.grad is not None and p.grad.abs().sum() > 0 for p in actor.cnns.parameters()) + assert result.shape == (4, 8) + + +def test_stock_critic_and_motor_penalty(): + from isaaclab_tasks.utils import resolve_presets + + from isaaclab_tutorial.active_gaze.env_cfg import SO101FoveatedEnvCfg, motor_action_rate + from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import SO101VialEnvCfg + + stock = resolve_presets(SO101VialEnvCfg()) + cfg = resolve_presets(SO101FoveatedEnvCfg()) + assert cfg.observations.critic.to_dict() == stock.observations.critic.to_dict() + assert cfg.terminations.to_dict() == stock.terminations.to_dict() + assert cfg.events.to_dict() == stock.events.to_dict() + assert set(cfg.rewards.to_dict()) == set(stock.rewards.to_dict()) + assert not hasattr(cfg.scene, "wrist_camera") + action = torch.zeros(2, 8) + action[:, -2:] = 1 + env = SimpleNamespace(action_manager=SimpleNamespace(action=action, prev_action=torch.zeros_like(action))) + assert torch.equal(motor_action_rate(env), torch.zeros(2)) + action[:, 0] = 2 + assert torch.equal(motor_action_rate(env), torch.full((2,), 4.0)) + + +@pytest.mark.parametrize("hfov", [65.0, 80.0]) +@pytest.mark.parametrize("resolution", [64, 128]) +def test_pinhole_calibration_agrees_with_spawn(hfov, resolution): + import math + + from isaaclab_tasks.utils import resolve_presets + + from isaaclab_tutorial.active_gaze.env_cfg import SOURCE_SIZE, SO101FoveatedEnvCfg, scene_camera + + cfg = SO101FoveatedEnvCfg() + cfg.scene.eye = scene_camera(hfov=hfov).replace(foveated_res=resolution) + cfg = resolve_presets(cfg) + cfg.enable_diagnostics() + camera = cfg.scene.eye + expected = SOURCE_SIZE / (2 * math.tan(math.radians(hfov / 2))) + assert math.isclose(SOURCE_SIZE * camera.spawn.focal_length / camera.spawn.horizontal_aperture, expected) + assert math.isclose(camera.camera_calibration["intrinsics"][0], expected) + assert cfg.scene.diagnostic_camera.spawn.horizontal_aperture == camera.spawn.horizontal_aperture + assert camera.foveated_res == resolution + assert camera.fixed_software_fov + + +def test_stronger_foveation_increases_central_density_at_fixed_camera(): + import math + + from isaaclab_fovi.sensors.native_grid import native_grid_directions + from isaaclab_fovi.sensors.pooling import build_lowres_coords + from isaaclab_tutorial.active_gaze.configuration import compose + + baseline = compose(["presets=numbered"])[0] + stronger = compose(["presets=numbered", "env.scene.eye.cmf_a=0.0075"])[0] + assert baseline.scene.eye.cmf_a == 0.015 + assert stronger.scene.eye.camera_calibration == baseline.scene.eye.camera_calibration + assert stronger.scene.eye.offset.pos == baseline.scene.eye.offset.pos + assert stronger.scene.eye.offset.rot == baseline.scene.eye.offset.rot + counts = [] + for cfg in (baseline, stronger): + coords, _ = build_lowres_coords(cfg.scene.eye, "cpu") + rays = native_grid_directions(coords, tangent_scale=math.tan(math.radians(cfg.camera_hfov() / 2))) + assert len(rays) == 64 * 64 + counts.append(int((-rays[:, 2] >= math.cos(math.radians(1))).sum())) + assert counts[1] > 1.5 * counts[0] + + +def test_reset_cache_preserves_physics_and_alignment(): + import math + + from fovi.sensing.projection import CameraModel + from isaaclab_tasks.utils import resolve_presets + + from isaaclab_tutorial.active_gaze.env_cfg import SO101FoveatedEnvCfg + from isaaclab_tutorial.active_gaze.gaze import angles_to_direction, build_reset_cache + from isaaclab_tutorial.active_gaze.reset import load_reset_dataset + + cfg = resolve_presets(SO101FoveatedEnvCfg()) + path = cfg.events.reset_from_dataset.params["dataset_path"] + rack = cfg.scene.rack.init_state + cache = build_reset_cache(path, cfg.scene.eye, (*rack.pos, *rack.rot), cfg.actions.gaze.angle_limit) + source = load_reset_dataset(path)["states"] + for name, tensor in source.items(): + assert torch.equal(cache["states"][name], tensor) + angles = cache["vision_action"] + assert angles.shape == (len(source["phase"]), 5, 16, 2) + rays = angles_to_direction(angles) + _, valid = CameraModel(**cfg.scene.eye.camera_calibration).project(rays) + assert valid.all() + for exact_index, near_index, direction in ( + (1, 3, cache["object_direction"]), + (2, 4, cache["goal_direction"]), + ): + exact_cos = (rays[:, exact_index] * direction[:, None]).sum(-1) + assert (exact_cos > math.cos(math.radians(0.1))).all() + near_cos = (rays[:, near_index] * direction[:, None]).sum(-1) + assert (near_cos <= math.cos(math.radians(1.99))).all() + assert (near_cos >= math.cos(math.radians(5.01))).all() + assert (angles[:, 0].abs() > math.radians(25)).any() + + +def test_optional_oracle_keeps_actor_and_critic_inputs_and_plain_ppo(): + from rsl_rl.models import CNNModel + + from isaaclab_tutorial.active_gaze.learning.oracle_ppo import gaze_loss + from isaaclab_tutorial.active_gaze.configuration import compose + + baseline, base_agent, _ = compose(["presets=no_gaze_supervision"]) + supervised, agent, _ = compose(["presets=grasp_gated"]) + assert base_agent.algorithm.class_name == "PPO" + assert baseline.observations.oracle is None + assert supervised.observations.oracle is not None + cfg = agent.to_dict() + assert cfg["obs_groups"] == base_agent.to_dict()["obs_groups"] + assert cfg["algorithm"]["class_name"].endswith(":OraclePPO") + actor_cfg = cfg["actor"].copy() + actor_cfg.pop("class_name") + obs = TensorDict( + dict( + scene_rgb=torch.rand(4, 3, 64, 64), + proprioception=torch.randn(4, 26), + gaze=torch.randn(4, 6), + critic=torch.randn(4, 65), + oracle=torch.tensor([[0.7, -0.5, 1.0]]).expand(4, -1).clone(), + ), + [4], + ) + actor = CNNModel(obs, cfg["obs_groups"], "actor", 8, **actor_cfg) + expected = actor(obs) + changed = obs.clone() + changed["oracle"].fill_(float("nan")) + changed["critic"].fill_(float("nan")) + torch.testing.assert_close(actor(changed), expected) + actor(obs, stochastic_output=True) + gaze_loss(actor.output_mean[:, -2:], actor.output_std[:, -2:], obs["oracle"]).backward() + output = actor.mlp[-1] + assert torch.count_nonzero(output.weight.grad[:6]) == 0 + assert output.weight.grad[-2:].abs().sum() > 0 + assert any(p.grad is not None and p.grad.abs().sum() > 0 for p in actor.cnns.parameters()) + + +def test_oracle_switches_with_stock_grasp_and_selective_resets(): + from isaaclab_tutorial.active_gaze.gaze import oracle_target, target_centers + from isaaclab_tutorial.tasks.place_vial.mdp.progress import PlacementProgress + + vial = torch.tensor([[0.2, 0.0, 0.1, 0, 0, 0, 1.0]]).expand(3, -1).clone() + rack = torch.tensor([[0.12, 0.0, 0.0, 0, 0, 0, 1.0]]).expand(3, -1).clone() + + def asset(pose): + return SimpleNamespace( + data=SimpleNamespace( + root_pos_w=SimpleNamespace(torch=pose[:, :3]), + root_quat_w=SimpleNamespace(torch=pose[:, 3:]), + ) + ) + + progress = PlacementProgress(3, "cpu") + env = SimpleNamespace( + scene={"vial": asset(vial), "rack": asset(rack)}, + _so101_placement_progress=progress, + cfg=SimpleNamespace(goal_mode="nearest"), + ) + object_center, goal = target_centers(vial, rack) + torch.testing.assert_close(oracle_target(env), object_center) + holding = torch.tensor([True, True, False]) + absent = torch.zeros(3, dtype=torch.bool) + for step in range(2): + progress.update(holding, absent, absent, absent, torch.full((3,), step)) + torch.testing.assert_close(oracle_target(env), torch.stack((goal[0], goal[1], object_center[2]))) + # Releasing the vial does not switch back to object fixation. + progress.update(absent, absent, absent, absent, torch.full((3,), 3)) + assert progress.grasped[:2].all() + progress.reset(torch.tensor([0])) + torch.testing.assert_close(oracle_target(env), torch.stack((object_center[0], goal[1], object_center[2]))) + + +@pytest.mark.parametrize("hfov,limit", [(65.0, 31.5), (80.0, 39.0)]) +def test_calibrated_oracle_reaches_target_from_extreme_gaze(hfov, limit): + import math + + from fovi.sensing.projection import CameraModel + + from isaaclab_tutorial.active_gaze.env_cfg import scene_camera + from isaaclab_tutorial.active_gaze.gaze import angles_to_direction, calibrated_oracle + + calibration = CameraModel(**scene_camera(hfov=hfov).camera_calibration) + target = torch.tensor([[0.15, -0.2], [-0.3, 0.25]]) + commanded = torch.tensor([[-1.0, 1.0], [1.0, -1.0]]) * math.radians(limit) + direction = angles_to_direction(target) + for _ in range(20): + actions, valid = calibrated_oracle( + direction, commanded, calibration, max_delta=0.12, angle_limit=math.radians(limit) + ) + assert valid.all() and (actions.abs() <= 1).all() + commanded = (commanded + actions * 0.12).clamp(-math.radians(limit), math.radians(limit)) + torch.testing.assert_close(commanded, target) + invalid = torch.tensor([[0.0, 0.0, -1.0], [float("nan"), 0.0, 1.0]]) + actions, valid = calibrated_oracle(invalid, commanded, calibration, max_delta=0.12, angle_limit=math.radians(limit)) + assert not valid.any() and torch.isfinite(actions).all() From 8d35c3588fb65a8d8d0799df282a69521818b4fb Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:32:08 -0800 Subject: [PATCH 04/30] Rebuild the gaze action and numbered goals around single owners The gaze action now owns the gaze: its step and limit are given in field radii of the retina and converted to radians once, the limit is radial, and it moves the camera through set_gaze_angles. Episodes start at a gaze drawn from the five reset modes using that episode's vial and rack, which replaces the saved reset cache. The teacher's gaze labels come from one method of the action term. The numbered reset term owns each vial's number and target opening, read through target_holes(); the env attributes vial_number, numbered_target_hole and hole_numbers, the reset sampler's env attribute and the goal_mode switch in the gaze code are gone. The pan-tilt rig mode and the binocular parameterization are removed. Registers IsaacTutorial-Place-Vial-SO101-ActiveGaze with string entry points. --- src/isaaclab_tutorial/active_gaze/__init__.py | 8 + .../active_gaze/fixation/__init__.py | 1 - .../active_gaze/fixation/actions.py | 93 ---- .../active_gaze/fixation/oracle.py | 30 -- .../active_gaze/fixation/parameterization.py | 93 ---- src/isaaclab_tutorial/active_gaze/gaze.py | 465 ++++++++---------- src/isaaclab_tutorial/active_gaze/goals.py | 209 +++----- .../active_gaze/robot_geometry.py | 2 +- src/isaaclab_tutorial/active_gaze/sampling.py | 1 - .../tasks/place_vial/config/so101/__init__.py | 19 +- tests/active_gaze/test_fixation_geometry.py | 40 -- 11 files changed, 316 insertions(+), 645 deletions(-) create mode 100644 src/isaaclab_tutorial/active_gaze/__init__.py delete mode 100644 src/isaaclab_tutorial/active_gaze/fixation/__init__.py delete mode 100644 src/isaaclab_tutorial/active_gaze/fixation/actions.py delete mode 100644 src/isaaclab_tutorial/active_gaze/fixation/oracle.py delete mode 100644 src/isaaclab_tutorial/active_gaze/fixation/parameterization.py delete mode 100644 tests/active_gaze/test_fixation_geometry.py diff --git a/src/isaaclab_tutorial/active_gaze/__init__.py b/src/isaaclab_tutorial/active_gaze/__init__.py new file mode 100644 index 0000000..ff4c52a --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/__init__.py @@ -0,0 +1,8 @@ +"""Active gaze for SO-101 vial placement: a foveated scene camera whose gaze the policy moves. + +The retina samples the scene densely where it looks and sparsely in the periphery. A matched non-foveated model is +the same task with a large ``env.scene.eye.cmf_a_deg``. This package needs the ``fovi`` extra, which installs Isaac +Lab's ``isaaclab_fovi`` camera and the policy libraries. +""" + +TASK_ID = "IsaacTutorial-Place-Vial-SO101-ActiveGaze" diff --git a/src/isaaclab_tutorial/active_gaze/fixation/__init__.py b/src/isaaclab_tutorial/active_gaze/fixation/__init__.py deleted file mode 100644 index 8cdf79d..0000000 --- a/src/isaaclab_tutorial/active_gaze/fixation/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Binocular fixation geometry and parameterizations.""" diff --git a/src/isaaclab_tutorial/active_gaze/fixation/actions.py b/src/isaaclab_tutorial/active_gaze/fixation/actions.py deleted file mode 100644 index 9a8a2a9..0000000 --- a/src/isaaclab_tutorial/active_gaze/fixation/actions.py +++ /dev/null @@ -1,93 +0,0 @@ -"""One gaze-action interface for physical and calibrated hybrid cameras.""" - -import torch -from fovi.sensing.projection import CameraModel -from isaaclab.managers import ActionTerm, ActionTermCfg -from isaaclab.utils import configclass -from isaaclab.utils.math import quat_apply_inverse - -from isaaclab_tutorial.active_gaze.fixation.oracle import fixation_action_target -from isaaclab_fovi.rigs import PanTiltRig - - -class GazeAction(ActionTerm): - """Bounded angular target increments in (tilt, pan) order.""" - - def __init__(self, cfg, env): - super().__init__(cfg, env) - self.camera = env.scene["eye"] - self.rig = PanTiltRig(env.scene["camera_rig"]) if cfg.mode == "hardware" else None - self.calibration = CameraModel(**self.camera.cfg.camera_calibration) - self._raw = torch.zeros(self.num_envs, 2, device=self.device) - self._target = torch.zeros_like(self._raw) - self._velocity = torch.zeros_like(self._raw) - self.base_rotation = torch.tensor(cfg.base_rotation, device=self.device).expand(self.num_envs, -1) - - @property - def action_dim(self): - return 2 - - @property - def raw_actions(self): - return self._raw - - @property - def processed_actions(self): - return self._target - - def process_actions(self, actions): - self._raw.copy_(actions) - previous = self._target.clone() - self._target.add_(actions.clamp(-1, 1) * self.cfg.max_delta).clamp_(-self.cfg.angle_limit, self.cfg.angle_limit) - self._velocity.copy_((self._target - previous) / self._env.step_dt) - if self.rig is None: - self.camera.set_calibrated_angles(self._target) - - def apply_actions(self): - if self.rig is not None: - self.rig.set_fixation_targets(self._target) - - def reset(self, env_ids=None): - selection = slice(None) if env_ids is None else env_ids - self._raw[selection] = 0 - self._target[selection] = 0 - self._velocity[selection] = 0 - if self.rig is not None: - self.rig.reset(env_ids) - else: - self.camera.set_calibrated_angles(self._target) - - def proprioception(self): - if self.rig is not None: - self.rig.update() - actual = self.rig.joint_positions_to_angles(self.rig.joint_pos) - velocity = self.rig.joint_positions_to_angles(self.rig.joint_vel) - else: - actual, velocity = self._target, self._velocity - return torch.cat((actual, velocity, self._target), dim=-1) - - def oracle(self, position): - origin = self.camera.get_world_positions() - direction = quat_apply_inverse(self.base_rotation, position - origin) - visible = None - if self.rig is None: - # Fixed neutral camera: ROS right/down/forward from mount +X/+Y/+Z. - source_direction = torch.stack((direction[:, 0], -direction[:, 2], direction[:, 1]), -1) - _, visible = self.calibration.project(source_direction) - return fixation_action_target( - direction, - self._target, - max_delta=self.cfg.max_delta, - angle_limit=self.cfg.angle_limit, - visible=visible, - ) - - -@configclass -class GazeActionCfg(ActionTermCfg): - class_type: type = GazeAction - asset_name: str = "robot" - mode: str = "hybrid" - max_delta: float = 0.12 - angle_limit: float = 1.2 - base_rotation: tuple = (0.0, 0.0, 0.0, 1.0) diff --git a/src/isaaclab_tutorial/active_gaze/fixation/oracle.py b/src/isaaclab_tutorial/active_gaze/fixation/oracle.py deleted file mode 100644 index 5c5e01e..0000000 --- a/src/isaaclab_tutorial/active_gaze/fixation/oracle.py +++ /dev/null @@ -1,30 +0,0 @@ -"""Geometric pan/tilt targets in the same bounded delta space as policy actions.""" - -import torch - - -def fixation_action_target( - direction: torch.Tensor, - commanded: torch.Tensor, - *, - max_delta: float, - angle_limit: float, - visible: torch.Tensor | None = None, -) -> tuple[torch.Tensor, torch.Tensor]: - """Return normalized (tilt, pan) deltas for mount-frame target vectors. - - The neutral rig faces +Y with +Z up. Positive pan turns left and positive - tilt turns up. Hardware targets may lie outside the *current* image; hybrid - callers additionally supply fixed physical-sensor visibility. The desired - joint target is bounded before converting to the executable action scale. - """ - if max_delta <= 0 or angle_limit <= 0: - raise ValueError("Gaze scale and joint limit must be positive.") - x, y, z = direction.unbind(-1) - desired = torch.stack((torch.atan2(z, torch.sqrt(x.square() + y.square())), torch.atan2(-x, y)), dim=-1) - valid = torch.isfinite(direction).all(-1) & (direction.norm(dim=-1) > 1e-6) - valid &= (desired.abs() <= angle_limit).all(-1) - if visible is not None: - valid &= visible - action = ((desired.clamp(-angle_limit, angle_limit) - commanded) / max_delta).clamp(-1, 1) - return torch.where(valid[:, None], action, 0.0), valid diff --git a/src/isaaclab_tutorial/active_gaze/fixation/parameterization.py b/src/isaaclab_tutorial/active_gaze/fixation/parameterization.py deleted file mode 100644 index 5bd8cd6..0000000 --- a/src/isaaclab_tutorial/active_gaze/fixation/parameterization.py +++ /dev/null @@ -1,93 +0,0 @@ -"""Binocular fixation parameterizations shared by rendering and control.""" - -from __future__ import annotations - -import math - -import torch - -LEFT_RIGHT = "left_right" -LEFT_RIGHT_SHARED = "left_right_shared" -VERSION_VERGENCE = "version_vergence" -BINOCULAR_PARAMETERIZATIONS = ( - LEFT_RIGHT, - LEFT_RIGHT_SHARED, - VERSION_VERGENCE, -) - - -def validate_fixation_parameterization(parameterization: str, eye_mode: str) -> None: - """Validate one learned-fixation parameterization selection.""" - if eye_mode not in ("left", "binocular"): - raise ValueError(f"Learned fixation eye_mode must be 'left' or 'binocular', got {eye_mode!r}.") - if parameterization not in BINOCULAR_PARAMETERIZATIONS: - raise ValueError( - f"Learned fixation parameterization must be one of {BINOCULAR_PARAMETERIZATIONS}, got {parameterization!r}." - ) - if eye_mode != "binocular" and parameterization != LEFT_RIGHT: - raise ValueError(f"parameterization={parameterization!r} requires eye_mode='binocular'.") - - -def fixation_action_dim(parameterization: str, eye_mode: str) -> int: - """Return the learned-fixation suffix dimension.""" - validate_fixation_parameterization(parameterization, eye_mode) - if eye_mode == "left": - return 2 - if parameterization in (LEFT_RIGHT, LEFT_RIGHT_SHARED): - return 4 - if parameterization == VERSION_VERGENCE: - return 3 - raise ValueError(f"Unsupported fixation parameterization {parameterization!r}.") - - -def validate_vergence_axis(axis: tuple[float, ...]) -> None: - """Validate the configured axis used for version/vergence conversion.""" - if len(axis) != 2 or not all(math.isfinite(value) for value in axis): - raise ValueError("version_vergence requires a finite two-dimensional vergence_axis.") - if not math.isclose(math.hypot(*axis), 1.0, rel_tol=1.0e-5, abs_tol=1.0e-5): - raise ValueError("version_vergence requires a unit-length vergence_axis.") - - -def _aligned_axis(axis: torch.Tensor, reference: torch.Tensor) -> torch.Tensor: - if axis.shape != (2,) and axis.shape != reference.shape: - raise ValueError( - "Vergence axis must have shape (2,) or match the reference tensor; " - f"got {tuple(axis.shape)} versus {tuple(reference.shape)}." - ) - return axis.to(device=reference.device, dtype=reference.dtype) - - -def version_vergence_to_eyes( - version: torch.Tensor, - vergence: torch.Tensor, - axis: torch.Tensor, -) -> tuple[torch.Tensor, torch.Tensor]: - """Decode two-dimensional version and scalar vergence into eye vectors.""" - if version.shape[-1:] != (2,): - raise ValueError(f"Version must end in dimension 2, got {tuple(version.shape)}.") - if vergence.shape != (*version.shape[:-1], 1): - raise ValueError( - "Vergence must match the version batch shape and end in dimension 1; " - f"got {tuple(vergence.shape)} versus {tuple(version.shape)}." - ) - axis = _aligned_axis(axis, version) - half_disparity = 0.5 * vergence * axis - return version + half_disparity, version - half_disparity - - -def eyes_to_version_vergence( - left: torch.Tensor, - right: torch.Tensor, - axis: torch.Tensor, -) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """Encode eye vectors and report discarded cross-baseline disparity.""" - if left.shape != right.shape or left.shape[-1:] != (2,): - raise ValueError( - "Left and right fixation tensors must have the same shape ending in 2; " - f"got {tuple(left.shape)} and {tuple(right.shape)}." - ) - axis = _aligned_axis(axis, left) - difference = left - right - vergence = (difference * axis).sum(dim=-1, keepdim=True) - residual = difference - vergence * axis - return 0.5 * (left + right), vergence, residual.norm(dim=-1) diff --git a/src/isaaclab_tutorial/active_gaze/gaze.py b/src/isaaclab_tutorial/active_gaze/gaze.py index b79f70c..c846037 100644 --- a/src/isaaclab_tutorial/active_gaze/gaze.py +++ b/src/isaaclab_tutorial/active_gaze/gaze.py @@ -1,296 +1,253 @@ -"""Physical-row-aligned gaze resets and optional grasp-gated training labels.""" +"""Gaze action of the active-gaze task, its reset, and the teacher's gaze labels. + +Gaze angles are (tilt, pan) [rad] from the scene camera's optical axis: positive tilt looks up and positive pan looks +left, as for :meth:`isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles`. Camera-frame directions use the OpenCV +convention: x right, y down, z forward. +""" + +from __future__ import annotations -import hashlib -import json import math -from pathlib import Path import torch -from fovi.sensing.projection import CameraModel +from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model, sampling_geometry + +from isaaclab.managers import ActionTerm, ActionTermCfg from isaaclab.utils import configclass from isaaclab.utils.math import quat_apply, quat_apply_inverse -from isaaclab_tutorial.active_gaze.fixation.actions import GazeAction, GazeActionCfg -from isaaclab_tutorial.active_gaze.fixation.oracle import fixation_action_target from isaaclab_tutorial.tasks.place_vial.mdp.geometry import RACK_HOLE_CENTERS from isaaclab_tutorial.tasks.place_vial.mdp.progress import placement_progress -from isaaclab_tutorial.tasks.place_vial.mdp.task import ( - RACK_RIM_HEIGHT, - VIAL_AXIS_MAX, - VIAL_AXIS_MIN, -) -from isaaclab_tutorial.active_gaze.reset import load_reset_dataset +from isaaclab_tutorial.tasks.place_vial.mdp.task import RACK_RIM_HEIGHT, VIAL_AXIS_MAX, VIAL_AXIS_MIN -RESET_MODES = ("random", "object", "goal", "near_object", "near_goal") +from .goals import CAP_LABEL_POSITION, RACK_LABEL_OFFSETS, target_holes - -def oracle_target(env): - """Switch from vial center to opening after the stock confirmed grasp. - - The milestone is restored by stock resets and stays latched through release. - It is a training label only, never an actor input or an executed action. - """ - poses = [ - torch.cat((env.scene[name].data.root_pos_w.torch, env.scene[name].data.root_quat_w.torch), dim=-1) - for name in ("vial", "rack") - ] - object_center, goal_center = target_centers(*poses) - if getattr(env.cfg, "goal_mode", "nearest") == "numbered": - from .goals import CAP_LABEL_POSITION, selected_goal_center - - object_center = poses[0][:, :3] + quat_apply( - poses[0][:, 3:], poses[0].new_tensor(CAP_LABEL_POSITION).expand(env.num_envs, -1) - ) - goal_center = selected_goal_center(env, label=True) - return torch.where(placement_progress(env).grasped[:, None], goal_center, object_center) - - -def oracle_labels(env): - gaze = env.action_manager.get_term("gaze") - position = oracle_target(env) - target, valid = gaze.oracle(position) - error = gaze.fixation_error(position).rad2deg() - log = env.extras.setdefault("log", {}) - log["Gaze/target_error_deg"] = torch.where(valid, error, 0).sum() / valid.sum().clamp_min(1) - log["Gaze/within_1deg"] = (valid & (error <= 1)).float().mean() - log["Gaze/goal_target_fraction"] = placement_progress(env).grasped.float().mean() - log["Gaze/valid_target_fraction"] = valid.float().mean() - return torch.cat((target, valid[:, None].float()), dim=-1) - - -def calibrated_oracle(direction, commanded, calibration, *, max_delta, angle_limit): - """Convert ROS camera rays to executable actions with physical-frustum masking.""" - _, visible = calibration.project(direction) - # Shared fixation geometry expects mount right/forward/up, not ROS right/down/forward. - mount = torch.stack((direction[:, 0], direction[:, 2], -direction[:, 1]), dim=-1) - return fixation_action_target(mount, commanded, max_delta=max_delta, angle_limit=angle_limit, visible=visible) +RESET_MODES = ("random", "object", "goal", "near_object", "near_goal") +"""Where the gaze starts an episode: anywhere in the camera's view, at the vial or the goal, or 2 to 5 degrees off +either.""" -def angles_to_direction(angles): +def angles_to_direction(angles: torch.Tensor) -> torch.Tensor: + """Camera-frame unit directions of gaze angles, shape (..., 2) to (..., 3).""" tilt, pan = angles.unbind(-1) return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) -def direction_to_angles(direction): +def direction_to_angles(direction: torch.Tensor) -> torch.Tensor: + """Gaze angles of camera-frame directions, shape (..., 3) to (..., 2).""" x, y, z = direction.unbind(-1) return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1) -def target_centers(vial_pose, rack_pose, target_holes=None, object_offset=None, goal_offsets=None): - """Vial geometric center and the closest admissible opening's rim center.""" - object_center = vial_pose[:, :3] + quat_apply( - vial_pose[:, 3:], - vial_pose.new_tensor(object_offset or (0, 0, (VIAL_AXIS_MIN + VIAL_AXIS_MAX) / 2)).expand(len(vial_pose), -1), - ) - holes = vial_pose.new_tensor(RACK_HOLE_CENTERS).expand(len(vial_pose), -1, -1).clone() - holes[..., 2] = RACK_RIM_HEIGHT - if goal_offsets is not None: - holes[..., :2] += holes.new_tensor(goal_offsets) - holes[..., 2] += 0.0002 - world_holes = rack_pose[:, None, :3] + quat_apply(rack_pose[:, None, 3:].expand(-1, 4, -1), holes) - nearest = (world_holes[..., :2] - vial_pose[:, None, :2]).square().sum(-1).argmin(-1) - if target_holes is not None: - nearest = target_holes - return object_center, world_holes[torch.arange(len(vial_pose), device=vial_pose.device), nearest] +def clamp_gaze(angles: torch.Tensor, limit: float) -> torch.Tensor: + """Scale gaze angles back onto the circle of radius ``limit`` [rad] when they leave it.""" + return angles * (limit / angles.norm(dim=-1, keepdim=True).clamp_min(limit)) + + +def random_gaze(count: int, limit: float, device=None) -> torch.Tensor: + """Gaze angles drawn uniformly over the disc of radius ``limit`` [rad], shape (count, 2).""" + radius = limit * torch.rand(count, device=device).sqrt() + angle = 2 * math.pi * torch.rand(count, device=device) + return torch.stack((radius * angle.sin(), radius * angle.cos()), dim=-1) -def camera_directions(points, position, rotation): +def camera_directions(points: torch.Tensor, position: torch.Tensor, rotation: torch.Tensor) -> torch.Tensor: + """Camera-frame unit directions to world points, for a camera at ``position`` with OpenGL ``rotation`` (xyzw).""" directions = quat_apply_inverse(rotation.expand(len(points), -1), points - position) - directions = directions * directions.new_tensor((1, -1, -1)) - return torch.nn.functional.normalize(directions, dim=-1) + return torch.nn.functional.normalize(directions * directions.new_tensor((1, -1, -1)), dim=-1) -def near_directions(direction, generator, variants=16): - """Sample a true spherical annulus, two to five degrees from the center.""" - direction = direction[:, None].expand(-1, variants, -1) +def nearby_directions(direction: torch.Tensor) -> torch.Tensor: + """Directions 2 to 5 degrees from each given direction, in a uniformly drawn azimuth.""" reference = direction.new_tensor((0, 1, 0)).expand_as(direction) tangent = torch.nn.functional.normalize(torch.cross(direction, reference, dim=-1), dim=-1) bitangent = torch.cross(direction, tangent, dim=-1) - theta = torch.empty(direction.shape[:2]).uniform_(math.radians(2), math.radians(5), generator=generator) - phi = torch.empty_like(theta).uniform_(0, 2 * math.pi, generator=generator) - return theta.cos()[..., None] * direction + theta.sin()[..., None] * ( - phi.cos()[..., None] * tangent + phi.sin()[..., None] * bitangent - ) + theta = torch.empty(len(direction), 1, device=direction.device).uniform_(math.radians(2), math.radians(5)) + phi = torch.rand_like(theta) * (2 * math.pi) + return theta.cos() * direction + theta.sin() * (phi.cos() * tangent + phi.sin() * bitangent) -def build_reset_cache(dataset_path, camera_cfg, rack_pose, angle_limit, seed=42, numbered=False): - """Keep stock physical rows intact and add diverse absolute gaze targets.""" - artifact = load_reset_dataset(dataset_path) - states = artifact["states"] - if numbered: - from .goals import CAP_LABEL_POSITION, RACK_LABEL_OFFSETS, expand_numbered_resets - - states, _, _, _ = expand_numbered_resets(states, rack_pose) - vial = states["vial_pose"] - rack = torch.tensor(rack_pose, dtype=vial.dtype).expand(len(vial), -1) - centers = target_centers( - vial, - rack, - states.get("target_hole"), - CAP_LABEL_POSITION if numbered else None, - RACK_LABEL_OFFSETS if numbered else None, - ) - position, rotation = ( - vial.new_tensor(camera_cfg.offset.pos), - vial.new_tensor(camera_cfg.offset.rot), - ) - directions = [camera_directions(center, position, rotation) for center in centers] - generator = torch.Generator().manual_seed(seed) - variants = 16 - random = torch.empty(len(vial), variants, 2).uniform_(-angle_limit, angle_limit, generator=generator) - object_angles, goal_angles = [direction_to_angles(d)[:, None].expand(-1, variants, -1) for d in directions] - near_object, near_goal = [direction_to_angles(near_directions(d, generator, variants)) for d in directions] - gaze = torch.stack((random, object_angles, goal_angles, near_object, near_goal), dim=1) - model = CameraModel(**camera_cfg.camera_calibration) - _, valid = model.project(angles_to_direction(gaze)) - valid &= (gaze.abs() <= angle_limit).all(-1) - # Resample random entries against the physical frustum, never clip aligned targets. - for _ in range(100): - bad = ~valid[:, 0] - if not bad.any(): - break - gaze[:, 0][bad] = torch.empty(int(bad.sum()), 2).uniform_(-angle_limit, angle_limit, generator=generator) - _, valid[:, 0] = model.project(angles_to_direction(gaze[:, 0])) - if not valid.all(): - raise ValueError("Reset gaze targets exceed the physical camera frustum or gaze limits") - identity = dict( - version=1, - source_sha256=artifact["content_sha256"], - calibration=camera_cfg.camera_calibration, - position=camera_cfg.offset.pos, - rotation=camera_cfg.offset.rot, - rack_pose=rack_pose, - angle_limit=angle_limit, - seed=seed, - modes=RESET_MODES, - vision_action_units="absolute_tilt_pan_radians", - near_degrees=[2, 5], - goal_mode="numbered" if numbered else "nearest", - ) - return dict( - identity=identity, - identity_sha256=hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest(), - states=states, - vision_action=gaze, - object_direction=directions[0], - goal_direction=directions[1], +def target_centers(vial_pose, rack_pose, holes=None, object_offset=None, goal_offsets=None): + """World points of the vial and of the goal opening. + + The goal is the given hole of each rack, or the opening nearest the vial. Offsets move the points from the vial's + center and the openings' rim centers, for example onto the number labels. + """ + object_center = vial_pose[:, :3] + quat_apply( + vial_pose[:, 3:], + vial_pose.new_tensor(object_offset or (0, 0, (VIAL_AXIS_MIN + VIAL_AXIS_MAX) / 2)).expand(len(vial_pose), -1), ) + openings = vial_pose.new_tensor(RACK_HOLE_CENTERS).expand(len(vial_pose), -1, -1).clone() + openings[..., 2] = RACK_RIM_HEIGHT + if goal_offsets is not None: + openings[..., :2] += openings.new_tensor(goal_offsets) + openings[..., 2] += 0.0002 + world = rack_pose[:, None, :3] + quat_apply(rack_pose[:, None, 3:].expand(-1, 4, -1), openings) + if holes is None: + holes = (world[..., :2] - vial_pose[:, None, :2]).square().sum(-1).argmin(-1) + return object_center, world[torch.arange(len(vial_pose), device=vial_pose.device), holes] + + +def gaze_targets(env, vial_pose: torch.Tensor, rack_pose: torch.Tensor, env_ids=slice(None)): + """World points the gaze should find: the vial and the goal, on their number labels when the vial is numbered.""" + holes = target_holes(env) + if holes is None: + return target_centers(vial_pose, rack_pose) + return target_centers(vial_pose, rack_pose, holes[env_ids], CAP_LABEL_POSITION, RACK_LABEL_OFFSETS) + + +class GazeAction(ActionTerm): + """Moves the scene camera's gaze by bounded increments in (tilt, pan) order. + + An action of 1 changes an angle by ``step_size`` field radii, and the gaze stays within ``gaze_limit`` field radii + of the optical axis. The field radius is half the retina's field of view. At reset the gaze starts at one of + :data:`RESET_MODES`, drawn uniformly, or on the optical axis when ``mixed_resets`` is off. + """ + cfg: GazeActionCfg -class CachedGazeAction(GazeAction): - def __init__(self, cfg, env): + def __init__(self, cfg: GazeActionCfg, env): super().__init__(cfg, env) - self.reset_mode = torch.zeros(env.num_envs, dtype=torch.long, device=self.device) - self.reset_variant = torch.zeros_like(self.reset_mode) - self.source_rotation = self._target.new_tensor(self.camera.cfg.offset.rot) - self.cache = None - if env.cfg.mixed_gaze_resets and getattr(env.cfg, "retinal_geometry", "spherical") != "planar": - params = env.event_manager.get_term_cfg("reset_from_dataset").params - rack = env.cfg.scene.rack.init_state - cache = build_reset_cache( - params["dataset_path"], - self.camera.cfg, - (*rack.pos, *rack.rot), - cfg.angle_limit, - numbered=getattr(env.cfg, "goal_mode", "nearest") == "numbered", - ) - output = Path(env.cfg.log_dir or Path.home() / ".cache/isaaclab_fovi/so101") - output.mkdir(parents=True, exist_ok=True) - torch.save(cache, output / "gaze_reset_cache.pt") - self.cache = cache["vision_action"].to(self.device) - - def oracle(self, position): - state = getattr(self._env, "so101_camera_randomization", None) - direction = camera_directions( - position, self.camera.get_world_positions(), self.source_rotation if state is None else state.rotation - ) - if state is not None: - visible = state.visibility(direction) - direction = angles_to_direction(state.gaze_direction(direction)) - mount = torch.stack((direction[:, 0], direction[:, 2], -direction[:, 1]), -1) - return fixation_action_target( - mount, self._target, max_delta=self.cfg.max_delta, angle_limit=self.cfg.angle_limit, visible=visible - ) - return calibrated_oracle( - direction, - self._target, - self.calibration, - max_delta=self.cfg.max_delta, - angle_limit=self.cfg.angle_limit, - ) - - def fixation_error(self, position): - state = getattr(self._env, "so101_camera_randomization", None) - direction = camera_directions( - position, self.camera.get_world_positions(), self.source_rotation if state is None else state.rotation - ) - if state is not None: - direction = angles_to_direction(state.gaze_direction(direction)) - actual = angles_to_direction(self._target) - # atan2 remains accurate near perfect alignment, unlike acos(dot). - return torch.atan2( - torch.cross(actual, direction, dim=-1).norm(dim=-1), - (actual * direction).sum(-1), - ) + self.camera = env.scene[cfg.camera_name] + self.camera_model = resolve_camera_model(self.camera.cfg) + self.field_radius = math.radians(sampling_geometry(self.camera.cfg)[0] / 2) + """Half the retina's field of view [rad].""" + self.max_step = cfg.step_size * self.field_radius + """Largest change of each gaze angle per step [rad].""" + self.limit = cfg.gaze_limit * self.field_radius + """Largest angle between the gaze and the optical axis [rad].""" + self.base_rotation = torch.tensor(self.camera.cfg.offset.rot, device=self.device) + self._raw = torch.zeros(self.num_envs, 2, device=self.device) + self._angles = torch.zeros_like(self._raw) + self._velocity = torch.zeros_like(self._raw) + self.reset_mode = torch.zeros(self.num_envs, dtype=torch.long, device=self.device) + """Index into :data:`RESET_MODES` of each environment's last reset.""" + + @property + def action_dim(self) -> int: + return 2 + + @property + def raw_actions(self) -> torch.Tensor: + return self._raw + + @property + def processed_actions(self) -> torch.Tensor: + return self._angles + + @property + def angles(self) -> torch.Tensor: + """Current gaze angles [rad], shape (num_envs, 2).""" + return self._angles + + def process_actions(self, actions: torch.Tensor): + self._raw.copy_(actions) + previous = self._angles.clone() + self._angles.copy_(clamp_gaze(self._angles + actions.clamp(-1, 1) * self.max_step, self.limit)) + self._velocity.copy_((self._angles - previous) / self._env.step_dt) + self.camera.set_gaze_angles(self._angles) + + def apply_actions(self): + pass def reset(self, env_ids=None): - super().reset(env_ids) - state = getattr(self._env, "so101_camera_randomization", None) - if state is not None and self._env.cfg.mixed_gaze_resets: - self._reset_randomized_camera(env_ids, state) - return - if self.cache is None or not hasattr(self._env, "_so101_reset_row"): - return - ids = slice(None) if env_ids is None else env_ids - rows = self._env._so101_reset_row[ids] - modes = torch.randint(5, rows.shape, device=self.device) - variants = torch.randint(self.cache.shape[2], rows.shape, device=self.device) - self._target[ids] = self.cache[rows, modes, variants] - self.reset_mode[ids], self.reset_variant[ids] = modes, variants - # The cache contains absolute gaze state. The last incremental action and - # velocity stay zero: reset is not a policy-generated camera movement. - self.camera.set_calibrated_angles(self._target) - - def _reset_randomized_camera(self, env_ids, state): - """Retain the cached mixture, deriving angles from the actual reset geometry.""" - from .goals import CAP_LABEL_POSITION, RACK_LABEL_OFFSETS - + ids = torch.arange(self.num_envs, device=self.device)[slice(None) if env_ids is None else env_ids] + self._raw[ids] = 0 + self._velocity[ids] = 0 + self.reset_mode[ids] = 0 + self._angles[ids] = 0 + if self.cfg.mixed_resets and len(ids): + self._reset_mixed(ids) + self.camera.set_gaze_angles(self._angles) + + def _reset_mixed(self, ids: torch.Tensor): + """Start each gaze at one of :data:`RESET_MODES` for this episode's vial and rack.""" env = self._env - ids = torch.arange(env.num_envs, device=self.device)[slice(None) if env_ids is None else env_ids] - if not len(ids) or not hasattr(env, "_so101_reset_vial_pose"): + if not hasattr(env, "_so101_reset_vial_pose"): return - vial = env._so101_reset_vial_pose[ids].clone() - rack = env._so101_reset_rack_pose[ids].clone() - vial[:, :3] += env.scene.env_origins[ids] - rack[:, :3] += env.scene.env_origins[ids] - obj, goal = target_centers(vial, rack, env.numbered_target_hole[ids], CAP_LABEL_POSITION, RACK_LABEL_OFFSETS) - position = state.position[ids] + env.scene.env_origins[ids] - modes = torch.randint(5, (len(ids),), device=self.device) - target = torch.where(((modes == 2) | (modes == 4))[:, None], goal, obj) - direction = camera_directions(target, position, state.rotation[ids]) - reference = direction.new_tensor((0, 1, 0)).expand_as(direction) - tangent = torch.nn.functional.normalize(torch.cross(direction, reference, dim=-1), dim=-1) - bitangent = torch.cross(direction, tangent, dim=-1) - theta = torch.empty(len(ids), 1, device=self.device).uniform_(math.radians(2), math.radians(5)) - phi = torch.rand_like(theta) * (2 * math.pi) - nearby = theta.cos() * direction + theta.sin() * (phi.cos() * tangent + phi.sin() * bitangent) - direction = torch.where((modes >= 3)[:, None], nearby, direction) - aligned = state.gaze_direction(direction, ids) - random = torch.empty_like(aligned).uniform_(-self.cfg.angle_limit, self.cfg.angle_limit) - from .camera_geometry import lens_visibility - - visible = lens_visibility(direction[:, None], state.intrinsics[ids], state.radial[ids], (640, 640)).squeeze(-1) - valid = visible & (aligned.abs() <= self.cfg.angle_limit).all(-1) - modes = torch.where(valid, modes, 0) - # Random starts are bounded by the real source sensor too; a neutral - # fallback prevents out-of-frame initialization at perturbed lens edges. - _, random_valid = self.calibration.project(angles_to_direction(random)) - random = torch.where(random_valid[:, None], random, 0) - self._target[ids] = torch.where((modes == 0)[:, None], random, aligned) - self.reset_mode[ids], self.reset_variant[ids] = modes, 0 - self.camera.set_calibrated_angles(self._target) + origins = env.scene.env_origins[ids] + vial, rack = env._so101_reset_vial_pose[ids].clone(), env._so101_reset_rack_pose[ids].clone() + vial[:, :3] += origins + rack[:, :3] += origins + vial_point, goal_point = gaze_targets(env, vial, rack, ids) + modes = torch.randint(len(RESET_MODES), (len(ids),), device=self.device) + point = torch.where(((modes == 2) | (modes == 4))[:, None], goal_point, vial_point) + direction = self.directions(point, ids) + direction = torch.where((modes >= 3)[:, None], nearby_directions(direction), direction) + aligned = direction_to_angles(direction) + modes = torch.where(self.visible(direction) & (aligned.norm(dim=-1) <= self.limit), modes, 0) + # A random start lies inside the physical image too; the optical axis is the fallback. + random = random_gaze(len(ids), self.limit, self.device) + random = torch.where(self.visible(angles_to_direction(random))[:, None], random, 0) + self._angles[ids] = torch.where((modes == 0)[:, None], random, aligned) + self.reset_mode[ids] = modes + + def directions(self, points: torch.Tensor, env_ids=slice(None)) -> torch.Tensor: + """Camera-frame unit directions from the camera to world points.""" + return camera_directions(points, self.camera.data.pos_w.torch[env_ids], self.base_rotation) + + def visible(self, direction: torch.Tensor) -> torch.Tensor: + """Whether camera-frame directions fall inside the physical camera's image.""" + return self.camera_model.project(direction)[1] + + def teacher_action(self, points: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """The action that moves the gaze toward world points, and whether each point is a valid target. + + A point is valid when the physical camera sees it and the gaze can reach it within the limit. + """ + direction = self.directions(points) + desired = direction_to_angles(direction) + valid = self.visible(direction) & (desired.norm(dim=-1) <= self.limit) + action = ((clamp_gaze(desired, self.limit) - self._angles) / self.max_step).clamp(-1, 1) + return torch.where(valid[:, None], action, 0.0), valid + + def fixation_error(self, points: torch.Tensor) -> torch.Tensor: + """Angle [rad] between the gaze and the direction to world points.""" + direction = self.directions(points) + gaze = angles_to_direction(self._angles) + # atan2 stays accurate near perfect alignment, unlike acos of the dot product. + return torch.atan2(torch.cross(gaze, direction, dim=-1).norm(dim=-1), (gaze * direction).sum(-1)) + + def proprioception(self) -> torch.Tensor: + """Gaze angles, their velocity and the command. The virtual gaze reaches its command at once.""" + return torch.cat((self._angles, self._velocity, self._angles), dim=-1) @configclass -class CachedGazeActionCfg(GazeActionCfg): - class_type: type = CachedGazeAction +class GazeActionCfg(ActionTermCfg): + """Configuration of :class:`GazeAction`.""" + + class_type: type = GazeAction + asset_name: str = "robot" + camera_name: str = "eye" + """Scene name of the foveated camera whose gaze the action moves.""" + step_size: float = 0.17 + """Change of each gaze angle per step at an action of 1, in field radii.""" + gaze_limit: float = 0.975 + """Largest angle between the gaze and the camera's optical axis, in field radii.""" + mixed_resets: bool = True + """Start episodes at a gaze drawn from :data:`RESET_MODES`; otherwise on the optical axis.""" + + +def teacher_target(env) -> torch.Tensor: + """World point the teacher looks at: the vial until it is grasped, then the goal.""" + vial, rack = ( + torch.cat((env.scene[name].data.root_pos_w.torch, env.scene[name].data.root_quat_w.torch), dim=-1) + for name in ("vial", "rack") + ) + vial_point, goal_point = gaze_targets(env, vial, rack) + return torch.where(placement_progress(env).grasped[:, None], goal_point, vial_point) + + +def oracle_labels(env) -> torch.Tensor: + """The teacher's gaze action and its validity, shape (num_envs, 3). A training label, never a policy input.""" + gaze: GazeAction = env.action_manager.get_term("gaze") + point = teacher_target(env) + action, valid = gaze.teacher_action(point) + error = gaze.fixation_error(point).rad2deg() + log = env.extras.setdefault("log", {}) + log["Gaze/target_error_deg"] = torch.where(valid, error, 0).sum() / valid.sum().clamp_min(1) + log["Gaze/within_1deg"] = (valid & (error <= 1)).float().mean() + log["Gaze/goal_target_fraction"] = placement_progress(env).grasped.float().mean() + log["Gaze/valid_target_fraction"] = valid.float().mean() + return torch.cat((action, valid[:, None].float()), dim=-1) diff --git a/src/isaaclab_tutorial/active_gaze/goals.py b/src/isaaclab_tutorial/active_gaze/goals.py index c4e61d6..9df0d18 100644 --- a/src/isaaclab_tutorial/active_gaze/goals.py +++ b/src/isaaclab_tutorial/active_gaze/goals.py @@ -1,4 +1,10 @@ -"""Numbered vial goals, target-aware stock rewards, and expanded reset bins.""" +"""Numbered vials: each vial carries a number from 1 to 4 and belongs in the rack opening with the same number. + +The vial's number is fixed per environment when the scene is cloned. :class:`NumberedResetFromDataset` owns it, and +:func:`target_holes` reads it; without a numbered reset any opening is a goal. +""" + +from __future__ import annotations from copy import deepcopy from dataclasses import fields @@ -6,19 +12,20 @@ import numpy as np import torch -from isaaclab.managers import ObservationTermCfg + from isaaclab.sim import MultiAssetSpawnerCfg from isaaclab.sim.utils import clone from isaaclab.utils import configclass -from isaaclab.utils.math import quat_apply -from isaaclab_tutorial.tasks.place_vial.mdp.events import ( - ResetFromDataset, - phase_balanced_row_weights, +from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import VialSpawnCfg +from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import ( + _spawn_usd_with_contact_material as spawn_usd_with_contact_material, ) +from isaaclab_tutorial.tasks.place_vial.mdp.events import ResetFromDataset, phase_balanced_row_weights from isaaclab_tutorial.tasks.place_vial.mdp.geometry import ( RACK_HOLE_CENTERS, hole_relative_positions, + rack_local_position, symmetric_axial_keypoint_error, ) from isaaclab_tutorial.tasks.place_vial.mdp.progress import placement_progress @@ -31,18 +38,21 @@ vial_upright, ) from isaaclab_tutorial.tasks.place_vial.mdp.terminations import placement_success -from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import ( - VialSpawnCfg, - spawn_usd_with_contact_material, -) from .sampling import PHASE_NAMES NEAR_GOAL_DISTANCE = 0.045 +"""Distance [m] within which a reset vial counts as near an opening.""" CAP_LABEL_POSITION = (0.0, 0.0, 0.1002) +"""Center of the number label on the vial's cap, in the vial frame [m].""" CAP_LABEL_SIZE = 0.022 +"""Side of the cap label [m].""" RACK_LABEL_SIZE = 0.013 +"""Side of an opening's label [m].""" RACK_LABEL_OFFSETS = ((-0.023, -0.023), (0.023, -0.023), (0.023, 0.023), (-0.023, 0.023)) +"""Position of each opening's label relative to the opening, in the rack frame [m].""" +VIAL_NUMBER_ATTRIBUTE = "tutorial:vialNumber" +"""USD attribute that records a vial prototype's number.""" def _attach_label(stage, path, asset_path, position, size, rotation=0.0): @@ -57,12 +67,12 @@ def _attach_label(stage, path, asset_path, position, size, rotation=0.0): @clone def spawn_numbered(prim_path, cfg, translation=None, orientation=None, **kwargs): - """Add render-only decals; preserve every stock collision and contact parameter.""" + """Add render-only number labels; keep every collision and contact parameter of the plain asset.""" prim = spawn_usd_with_contact_material(prim_path, cfg, translation=translation, orientation=orientation, **kwargs) if cfg.numbered_kind == "vial": from pxr import Sdf - prim.CreateAttribute("isaaclab_fovi:vialNumber", Sdf.ValueTypeNames.Int).Set(cfg.vial_number) + prim.CreateAttribute(VIAL_NUMBER_ATTRIBUTE, Sdf.ValueTypeNames.Int).Set(cfg.vial_number) _attach_label( prim.GetStage(), f"{prim_path}/Number", @@ -86,10 +96,29 @@ def spawn_numbered(prim_path, cfg, translation=None, orientation=None, **kwargs) @configclass class NumberedSpawnCfg(VialSpawnCfg): + """A vial or rack asset with number labels.""" + func = spawn_numbered numbered_kind: str = "vial" + """``"vial"`` for one label on the cap, ``"rack"`` for one label beside each opening.""" number_label_assets: str = "" + """Directory of the ``number_.usda`` label assets.""" vial_number: int = 1 + """Number on a vial's cap, from 1 to 4.""" + + +def numbered_spawn(spawn, kind: str, label_assets: str) -> NumberedSpawnCfg: + """The numbered version of a vial or rack spawn configuration, with the same physical fields.""" + values = {field.name: deepcopy(getattr(spawn, field.name)) for field in fields(spawn) if field.init} + values.pop("func", None) + return NumberedSpawnCfg(**values, numbered_kind=kind, number_label_assets=label_assets) + + +def numbered_vials(spawn, label_assets: str) -> MultiAssetSpawnerCfg: + """Four vial variants numbered 1 to 4, cloned in equal shares.""" + vial = numbered_spawn(spawn, "vial", label_assets) + variants = [vial.replace(vial_number=number) for number in range(1, 5)] + return MultiAssetSpawnerCfg(assets_cfg=variants, activate_contact_sensors=vial.activate_contact_sensors) def balanced_shuffled_clones(weights, num_clones): @@ -104,8 +133,8 @@ def balanced_shuffled_clones(weights, num_clones): return layout -def scene_vial_numbers(env): - """Read immutable cap identities from the actual native clone plan.""" +def scene_vial_numbers(env) -> torch.Tensor: + """Read each environment's vial number from the scene's clone plan, shape (num_envs,).""" from isaaclab.cloner import path as cloner_path plan = env.scene.clone_plan @@ -116,48 +145,13 @@ def scene_vial_numbers(env): start, end = topology.world_prototype_starts[world + 1 : world + 3] candidates = [] for asset in topology.world_prototypes[start:end]: - prim = env.scene.stage.GetPrimAtPath(paths[asset]) - number = prim.GetAttribute("isaaclab_fovi:vialNumber").Get() + number = env.scene.stage.GetPrimAtPath(paths[asset]).GetAttribute(VIAL_NUMBER_ATTRIBUTE).Get() if number is not None: candidates.append(number) if len(candidates) != 1 or candidates[0] not in (1, 2, 3, 4): raise ValueError(f"Expected one numbered vial in world prototype {world}: {candidates}") numbers[world] = candidates[0] - return torch.tensor( - [numbers[world] for world in topology.world_prototype_layout], - device=env.device, - dtype=torch.long, - ) - - -def configure_numbered_scene(cfg): - """Clone four prebuilt cap variants with unchanged stock physical properties.""" - for name in ("vial", "rack"): - asset = getattr(cfg.scene, name) - asset.spawn = NumberedSpawnCfg( - **{ - field.name: deepcopy(getattr(asset.spawn, field.name)) - for field in fields(asset.spawn) - if field.init and field.name != "func" - }, - numbered_kind=name, - number_label_assets=cfg.number_label_assets, - ) - original = cfg.scene.vial.spawn - variants = [] - for number in range(1, 5): - variant = original.copy() - variant.vial_number = number - variants.append(variant) - cfg.scene.vial.spawn = MultiAssetSpawnerCfg( - assets_cfg=variants, activate_contact_sensors=original.activate_contact_sensors - ) - cfg.scene.clone_cfg.clone_strategy = balanced_shuffled_clones - cfg.events.reset_from_dataset.func = NumberedResetFromDataset - cfg.terminations.success.func = TargetPlacementSuccess - cfg.rewards.held_goal.func = held_target_goal - cfg.observations.critic.placement.func = target_placement_features - cfg.observations.critic.numbered_goal = ObservationTermCfg(func=critic_goal_state) + return torch.tensor([numbers[world] for world in topology.world_prototype_layout], device=env.device) def expand_numbered_resets(states, rack_pose): @@ -167,8 +161,6 @@ def expand_numbered_resets(states, rack_pose): rows and target numbers before SGS adapts the far/target/non-target bins. Physical joint targets and vial poses remain byte-for-byte stock states. """ - from isaaclab_tutorial.tasks.place_vial.mdp.geometry import rack_local_position - expanded = {k: v.repeat_interleave(4, dim=0) for k, v in states.items()} target = torch.arange(4, device=states["phase"].device).repeat(len(states["phase"])) rack = expanded["vial_pose"].new_tensor(rack_pose).expand(len(target), -1) @@ -214,40 +206,35 @@ def sample_matching_rows(row_weights, targets): class NumberedResetFromDataset(ResetFromDataset): + """Reset to dataset rows that match each environment's vial number. + + Every physical row is crossed with each target opening, and rows near an opening are binned by whether that + opening is the target, so the reset curriculum can balance them. + """ + def __init__(self, cfg, env): super().__init__(cfg, env) rack = env.cfg.scene.rack.init_state - self.states, self.bin_ids, self.bin_names, phases = expand_numbered_resets(self.states, (*rack.pos, *rack.rot)) - self.bin_phase_ids = phases + self.states, self.bin_ids, self.bin_names, self.bin_phase_ids = expand_numbered_resets( + self.states, (*rack.pos, *rack.rot) + ) self.row_weights = phase_balanced_row_weights(self.states["phase"], cfg.params["phase_weights"]) self.sequential_rows = self.row_weights.nonzero().flatten() self.cursor = 0 - env.vial_number = scene_vial_numbers(env) - env.numbered_target_hole = env.vial_number - 1 - env.hole_numbers = torch.arange(1, 5, device=env.device).expand(env.num_envs, -1).clone() - self.target_fractions = torch.bincount(env.numbered_target_hole, minlength=4) / env.num_envs + self.vial_number = scene_vial_numbers(env) + """Number on each environment's vial, from 1 to 4, shape (num_envs,).""" + self.target_hole = self.vial_number - 1 + """Index of the opening each environment's vial belongs in, shape (num_envs,).""" + self.target_fractions = torch.bincount(self.target_hole, minlength=4) / env.num_envs def sampling_row_probabilities(self): return conditional_row_probabilities(self.row_weights, self.target_fractions) - def __call__( - self, - env, - env_ids, - dataset_path, - phase_weights, - sequential=False, - home_position_noise=0.0, - home_heading_noise=0.0, - home_rack_clearance=0.0, - home_rack_position_noise=0.0, - home_rack_yaw_noise=0.0, - support_height_range=(0.0, 0.0), - ): + def __call__(self, env, env_ids, dataset_path, phase_weights, sequential=False, **kwargs): ids = torch.arange(env.num_envs, device=env.device)[slice(None) if env_ids is None else env_ids] if not len(ids): return - targets = env.numbered_target_hole[ids] + targets = self.target_hole[ids] saved_rows, saved_cursor = self.sequential_rows, self.cursor if sequential: rows = torch.empty_like(ids) @@ -260,83 +247,43 @@ def __call__( rows[mask] = available[ranks % len(available)] else: rows = sample_matching_rows(self.row_weights, targets) - # Delegate all physical restoration to the stock task via its explicit-row path. + # The stock reset restores the chosen rows through its sequential path. self.sequential_rows, self.cursor = rows, 0 try: - self._restore_rows( - env, - ids, - dataset_path, - phase_weights, - home_position_noise, - home_heading_noise, - home_rack_clearance, - home_rack_position_noise, - home_rack_yaw_noise, - support_height_range, - ) + super().__call__(env, ids, dataset_path, phase_weights, True, **kwargs) finally: self.sequential_rows = saved_rows self.cursor = saved_cursor + len(ids) if sequential else saved_cursor - def _restore_rows( - self, - env, - ids, - dataset_path, - phase_weights, - home_position_noise, - home_heading_noise, - home_rack_clearance, - home_rack_position_noise, - home_rack_yaw_noise, - support_height_range, - ): - super().__call__( - env, - ids, - dataset_path, - phase_weights, - True, - home_position_noise, - home_heading_noise, - home_rack_clearance, - home_rack_position_noise, - home_rack_yaw_noise, - support_height_range, - ) + +def target_holes(env) -> torch.Tensor | None: + """Index of each environment's target opening, shape (num_envs,), or None when any opening is a goal.""" + reset = env.event_manager.get_term_cfg("reset_from_dataset").func + return reset.target_hole if isinstance(reset, NumberedResetFromDataset) else None def target_relative_position(env): position, axis, lowest = vial_in_rack(env) - center = position.new_tensor(RACK_HOLE_CENTERS)[env.numbered_target_hole] + center = position.new_tensor(RACK_HOLE_CENTERS)[target_holes(env)] return position - center, axis, lowest -def selected_goal_center(env, label=False): - rack = env.scene["rack"].data - local = rack.root_pos_w.torch.new_tensor(RACK_HOLE_CENTERS)[env.numbered_target_hole].clone() - local[:, 2] = RACK_RIM_HEIGHT - if label: - local[:, :2] += local.new_tensor(RACK_LABEL_OFFSETS)[env.numbered_target_hole] - local[:, 2] += 0.0002 - return rack.root_pos_w.torch + quat_apply(rack.root_quat_w.torch, local) - - def target_placement_features(env): + """Placement features against the target opening rather than the nearest one.""" position, _, lowest = target_relative_position(env) speed = env.scene["vial"].data.root_lin_vel_w.torch.norm(dim=-1) return torch.stack((position[:, :2].norm(dim=-1), lowest, vial_upright(env), speed), dim=-1) def critic_goal_state(env): - """Privileged target position and identity, excluded from actor groups.""" - local = env.scene["vial"].data.root_pos_w.torch.new_tensor(RACK_HOLE_CENTERS)[env.numbered_target_hole] - number = torch.nn.functional.one_hot(env.vial_number - 1, 4) - return torch.cat((local, number), dim=-1).float() + """Privileged target position and number, excluded from the actor's observations.""" + holes = target_holes(env) + local = env.scene["vial"].data.root_pos_w.torch.new_tensor(RACK_HOLE_CENTERS)[holes] + return torch.cat((local, torch.nn.functional.one_hot(holes, 4)), dim=-1).float() def held_target_goal(env, std=0.10): + """The stock held-goal reward, measured against the target opening.""" position, axis, _ = target_relative_position(env) error = symmetric_axial_keypoint_error( position, @@ -359,9 +306,9 @@ class TargetPlacementSuccess(placement_success): """ def __call__(self, env): + holes = target_holes(env) position, _, _ = vial_in_rack(env) - nearest = hole_relative_positions(position)[..., :2].square().sum(-1).argmin(-1) - wrong = nearest != env.numbered_target_hole + wrong = hole_relative_positions(position)[..., :2].square().sum(-1).argmin(-1) != holes inserted, success, time = ( v.clone() for v in (self.progress.inserted, self.progress.success, self.progress.time_to_success) ) @@ -376,5 +323,5 @@ def __call__(self, env): log["Metrics/success_rate"] = success.float().mean() env._so101_terminal_progress[:, 2] = self.progress.inserted env._so101_terminal_time_to_success_s = self.progress.time_to_success.float() * env.step_dt - env._so101_terminal_hole = torch.where(success, env.numbered_target_hole, -1) + env._so101_terminal_hole = torch.where(success, holes, -1) return success diff --git a/src/isaaclab_tutorial/active_gaze/robot_geometry.py b/src/isaaclab_tutorial/active_gaze/robot_geometry.py index 4f23827..320c2d8 100644 --- a/src/isaaclab_tutorial/active_gaze/robot_geometry.py +++ b/src/isaaclab_tutorial/active_gaze/robot_geometry.py @@ -2,7 +2,7 @@ from isaaclab.sim.utils import clone -from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import spawn_so101 +from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import _spawn_so101 as spawn_so101 WRIST_CAMERA_PARTS = ( "gripper/wowrobo_2MP_camera", diff --git a/src/isaaclab_tutorial/active_gaze/sampling.py b/src/isaaclab_tutorial/active_gaze/sampling.py index 6733a95..a9865af 100644 --- a/src/isaaclab_tutorial/active_gaze/sampling.py +++ b/src/isaaclab_tutorial/active_gaze/sampling.py @@ -98,7 +98,6 @@ def __init__(self, cfg, env): self.phase_sizes = torch.bincount(self.phases, minlength=len(self.bin_names)) self.eligible = torch.zeros(env.num_envs, dtype=torch.bool, device=env.device) self.sampled = torch.zeros_like(self.history.episodes) - env.reset_sampling = self def phase_probabilities(self): conditional = getattr(self.reset_term, "sampling_row_probabilities", None) diff --git a/src/isaaclab_tutorial/tasks/place_vial/config/so101/__init__.py b/src/isaaclab_tutorial/tasks/place_vial/config/so101/__init__.py index a289111..05acac1 100644 --- a/src/isaaclab_tutorial/tasks/place_vial/config/so101/__init__.py +++ b/src/isaaclab_tutorial/tasks/place_vial/config/so101/__init__.py @@ -1,7 +1,13 @@ -"""SO-101 state and wrist-camera tasks. Add ``presets=sim2real`` to either for robot-transfer randomization.""" +"""SO-101 state and wrist-camera tasks. Add ``presets=sim2real`` to either for robot-transfer randomization. + +The active-gaze task lives in :mod:`isaaclab_tutorial.active_gaze` and needs the ``fovi`` extra. Its entry points are +strings, so registering it here imports nothing from that extra. +""" import gymnasium as gym +from isaaclab_tutorial.active_gaze import TASK_ID as ACTIVE_GAZE_TASK_ID + _PACKAGE = "isaaclab_tutorial.tasks.place_vial.config.so101" gym.register( @@ -26,3 +32,14 @@ "default_agent": "rsl_rl", }, ) + +gym.register( + id=ACTIVE_GAZE_TASK_ID, + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": "isaaclab_tutorial.active_gaze.env_cfg:ActiveGazeEnvCfg", + "rsl_rl_cfg_entry_point": "isaaclab_tutorial.active_gaze.agents:ActiveGazeAgentCfg", + "default_agent": "rsl_rl", + }, +) diff --git a/tests/active_gaze/test_fixation_geometry.py b/tests/active_gaze/test_fixation_geometry.py deleted file mode 100644 index 97898f6..0000000 --- a/tests/active_gaze/test_fixation_geometry.py +++ /dev/null @@ -1,40 +0,0 @@ -"""Binocular parameterization geometry without task or policy dependencies.""" - -import pytest -import torch - -from isaaclab_tutorial.active_gaze.fixation.parameterization import ( - eyes_to_version_vergence, - validate_vergence_axis, - version_vergence_to_eyes, -) - - -def test_version_vergence_round_trip_with_per_eye_baseline_axes() -> None: - axes = torch.tensor([[0.6, 0.8], [1.0, 0.0]]) - version = torch.tensor([[0.2, -0.1], [-0.3, 0.4]]) - vergence = torch.tensor([[0.5], [-0.25]]) - left, right = version_vergence_to_eyes(version, vergence, axes) - recovered_version, recovered_vergence, residual = eyes_to_version_vergence(left, right, axes) - torch.testing.assert_close(left - right, vergence * axes) - torch.testing.assert_close(recovered_version, version) - torch.testing.assert_close(recovered_vergence, vergence) - torch.testing.assert_close(residual, torch.zeros(2)) - - -def test_cross_baseline_disparity_is_reported() -> None: - axis = torch.tensor([0.6, 0.8]) - orthogonal = torch.tensor([-0.8, 0.6]) - version = torch.tensor([[0.4, -0.2]]) - left = version + 0.25 * axis + 0.1 * orthogonal - right = version - 0.25 * axis - 0.1 * orthogonal - recovered, vergence, residual = eyes_to_version_vergence(left, right, axis) - torch.testing.assert_close(recovered, version) - torch.testing.assert_close(vergence, torch.tensor([[0.5]])) - torch.testing.assert_close(residual, torch.tensor([0.2])) - - -@pytest.mark.parametrize("axis", [(1.0,), (float("nan"), 0.0), (1.0, 1.0)]) -def test_invalid_vergence_axis_fails(axis: tuple[float, ...]) -> None: - with pytest.raises(ValueError, match="vergence_axis"): - validate_vergence_axis(axis) From fb8e2db860355c5a14fa6d38de33ecce7191363d Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:34:36 -0800 Subject: [PATCH 05/30] Define the ActiveGaze variants as plain configuration classes nearest, numbered and dino_language are subclasses of the tutorial's state task whose fields say what differs: the numbered spawners, reset, success, held-goal reward and critic goal are set as fields instead of being patched in __post_init__, and the goal_mode and policy class flags and the checkpoint-metadata helpers are gone. The scene camera is an ideal square pinhole given by its spawn optics, with the default 0.591 degree CMF constant and sensor masking; the tutorial's own task defaults now apply, since training starts from scratch. Agent classes drop the robot name and the variants without an environment yet. --- src/isaaclab_tutorial/active_gaze/agents.py | 26 +- src/isaaclab_tutorial/active_gaze/env_cfg.py | 479 ++++++++----------- src/isaaclab_tutorial/active_gaze/runner.py | 2 +- src/isaaclab_tutorial/active_gaze/train.py | 4 +- tests/active_gaze/test_presets.py | 4 +- tests/active_gaze/test_sim2real.py | 6 +- tests/active_gaze/test_vial.py | 4 +- 7 files changed, 225 insertions(+), 300 deletions(-) diff --git a/src/isaaclab_tutorial/active_gaze/agents.py b/src/isaaclab_tutorial/active_gaze/agents.py index 9c1ad88..e36d6b3 100644 --- a/src/isaaclab_tutorial/active_gaze/agents.py +++ b/src/isaaclab_tutorial/active_gaze/agents.py @@ -102,14 +102,14 @@ class ExtrinsicsHeadCfg(PresetCfg): @configclass -class SO101FoveatedPPORunnerCfg(RslRlOnPolicyRunnerCfg): +class ActiveGazePPORunnerCfg(RslRlOnPolicyRunnerCfg): seed = 42 num_steps_per_env = RolloutLengthCfg() run_name = "" clip_actions = 1.0 critic = RslRlMLPModelCfg(hidden_dims=[256, 256, 128], activation="elu", obs_normalization=True) finetune = FineTuneCfg() - experiment_name = "so101_vial_foveated" + experiment_name = "so101_vial_active_gaze" max_iterations = 5000 save_interval = 100 obs_groups = {"actor": ["scene_rgb", "proprioception", "gaze"], "critic": ["critic"]} @@ -133,9 +133,9 @@ class SO101FoveatedPPORunnerCfg(RslRlOnPolicyRunnerCfg): @configclass -class SO101LanguageActorCfg(LanguageVisionActorCfg): +class LanguageActorCfg(LanguageVisionActorCfg): instructions = INSTRUCTIONS - distribution_cfg = SO101FoveatedPPORunnerCfg().actor.distribution_cfg + distribution_cfg = ActiveGazePPORunnerCfg().actor.distribution_cfg extrinsics_head = ExtrinsicsHeadCfg() @@ -159,23 +159,23 @@ class LanguageAlgorithmCfg(AlgorithmCfg): @configclass -class SO101LanguagePPORunnerCfg(SO101FoveatedPPORunnerCfg): - actor = SO101LanguageActorCfg() +class LanguagePPORunnerCfg(ActiveGazePPORunnerCfg): + actor = LanguageActorCfg() algorithm = LanguageAlgorithmCfg() obs_groups = {"actor": ["proprio", "vision", "instruction"], "critic": ["critic"]} @configclass -class SO101Sim2RealPPORunnerCfg(SO101LanguagePPORunnerCfg): - actor = SO101LanguageActorCfg(extrinsics_head=True) +class Sim2RealPPORunnerCfg(LanguagePPORunnerCfg): + actor = LanguageActorCfg(extrinsics_head=True) algorithm = ExtrinsicsPPOCfg(use_mixed_precision=True) @configclass -class SO101AgentCfg(PresetCfg): - nearest = SO101FoveatedPPORunnerCfg() +class ActiveGazeAgentCfg(PresetCfg): + """Agents of the task variants in :class:`~.env_cfg.ActiveGazeEnvCfg`, selected by the same names.""" + + nearest = ActiveGazePPORunnerCfg() numbered = nearest - dino_language = SO101LanguagePPORunnerCfg() - planar = dino_language - sim2real = SO101Sim2RealPPORunnerCfg() + dino_language = LanguagePPORunnerCfg() default = numbered diff --git a/src/isaaclab_tutorial/active_gaze/env_cfg.py b/src/isaaclab_tutorial/active_gaze/env_cfg.py index 01deccd..40c7348 100644 --- a/src/isaaclab_tutorial/active_gaze/env_cfg.py +++ b/src/isaaclab_tutorial/active_gaze/env_cfg.py @@ -1,50 +1,68 @@ -"""A fixed, calibrated scene camera on the stock SO-101 task.""" +"""SO-101 vial placement seen through a foveated scene camera whose gaze the policy moves. + +The task is the tutorial's state task with the actor's state replaced by the camera's retina, the gaze and +proprioception. The critic keeps the full state. Select a variant with ``presets=``; the same name selects its agent +in :mod:`.agents`: + +* ``nearest``: place the vial in any opening, with a CNN policy. +* ``numbered``: place each vial in the opening with its number, with a CNN policy (default). +* ``dino_language``: numbered, with frozen foveated DINO tokens and a language instruction. + +A matched non-foveated model is any variant with a large CMF constant, for example ``env.scene.eye.cmf_a_deg=1000``. +""" + +from __future__ import annotations import math -from typing import ClassVar + +import torch +from isaaclab_fovi.sensors import FoveatedCameraCfg from isaaclab.assets import AssetBaseCfg from isaaclab.managers import CurriculumTermCfg, ManagerTermBase, ObservationGroupCfg, ObservationTermCfg from isaaclab.sensors import CameraCfg from isaaclab.sim import DomeLightCfg, PinholeCameraCfg from isaaclab.utils import configclass -from isaaclab_tasks.utils import PresetCfg, resolve_presets + +from isaaclab_tasks.utils import PresetCfg from isaaclab_tutorial.assets.numbers import LABEL_ASSETS -from isaaclab_tutorial.active_gaze.learning.dino import DEFAULT_CHECKPOINT, DEFAULT_MD5 -from isaaclab_tutorial.active_gaze.learning.observations import DinoTokens -from isaaclab_fovi.sensors import FoveatedTiledCameraCfg +from isaaclab_tutorial.tasks.place_vial.config.so101.camera_env_cfg import ProprioceptionCfg from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import ( ActionsCfg, CriticStateGroupCfg, EventsCfg, + RewardsCfg, + SO101SceneCfg, SO101VialEnvCfg, + TerminationsCfg, ) -from .env_cfg import ProprioceptionCfg -from .gaze import CachedGazeActionCfg, oracle_labels +from .gaze import GazeActionCfg, oracle_labels +from .goals import ( + NumberedResetFromDataset, + TargetPlacementSuccess, + balanced_shuffled_clones, + critic_goal_state, + held_target_goal, + numbered_spawn, + numbered_vials, + target_placement_features, +) from .language import instruction_index +from .learning.dino import DEFAULT_CHECKPOINT, DEFAULT_MD5 +from .learning.observations import DinoTokens from .render_options import CameraOutputCfg, CameraOutputNameCfg, CameraRenderSettingsCfg, FoviRendererCfg from .robot_geometry import spawn_without_wrist_camera -from .sampling import ResetSampling, validate_settings -from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import SO101SceneCfg -from .transfer_options import CameraRandomizationCfg - -# Front view along the robot's working axis, centered on the arm and vial board. -CAMERA_POSITION = (0.52, 0.0, 0.36) -CAMERA_TARGET = (0.12, 0.0, 0.12) -SOURCE_SIZE = 640 -HORIZONTAL_FOV = 80.0 -FOCAL_PIXELS = SOURCE_SIZE / (2 * math.tan(math.radians(HORIZONTAL_FOV / 2))) -CALIBRATION = dict( - model="pinhole", - image_size=(SOURCE_SIZE, SOURCE_SIZE), - intrinsics=(FOCAL_PIXELS, FOCAL_PIXELS, 319.5, 319.5), -) +from .sampling import ResetSampling + +## +# Scene camera +## -def camera_rotation(position=CAMERA_POSITION, target=CAMERA_TARGET): - """OpenGL look-at orientation, XYZW, computed without a simulator.""" +def camera_rotation(position, target) -> tuple[float, float, float, float]: + """OpenGL look-at orientation (x, y, z, w) with world +Z up, computed without a simulator.""" import numpy as np from scipy.spatial.transform import Rotation @@ -56,8 +74,74 @@ def camera_rotation(position=CAMERA_POSITION, target=CAMERA_TARGET): return tuple(float(v) for v in Rotation.from_matrix(np.stack([right, up, back], axis=1)).as_quat()) +def scene_camera(position, target, field_of_view_deg: float, resolution: int = 64) -> FoveatedCameraCfg: + """A fixed foveated camera at ``position`` looking at ``target``. + + The physical camera is an ideal square pinhole with the given field of view, and the retina spans it. + """ + aperture = 48.0 * math.tan(math.radians(field_of_view_deg / 2)) + return FoveatedCameraCfg( + prim_path="{ENV_REGEX_NS}/SceneEye", + data_types=CameraOutputCfg(), + renderer_cfg=FoviRendererCfg(), + render_settings=CameraRenderSettingsCfg(), + spawn=PinholeCameraCfg( + focal_length=24.0, + horizontal_aperture=aperture, + vertical_aperture=aperture, + clipping_range=(0.01, 5.0), + ), + offset=CameraCfg.OffsetCfg(pos=position, rot=camera_rotation(position, target), convention="opengl"), + foveated_res=resolution, + mask_to_sensor_fov=True, + update_period=0.0, + ) + + +# A front view along the robot's working axis, centered on the arm and the rack. +NEAREST_CAMERA = scene_camera((0.52, 0.0, 0.36), (0.12, 0.0, 0.12), 80.0) +# Closer, so the number labels cover more samples. +NUMBERED_CAMERA = scene_camera((0.46, 0.015, 0.34), (0.17, 0.025, 0.12), 78.0) + + +@configclass +class RobotSpawnCfg(PresetCfg): + """The tutorial's SO-101; its wrist camera is removed unless ``stock_wrist_camera`` is selected.""" + + stock_wrist_camera = SO101SceneCfg().robot.spawn + default = stock_wrist_camera.replace(func=spawn_without_wrist_camera) + + +@configclass +class SceneCfg(SO101SceneCfg): + robot = SO101SceneCfg().robot.replace(spawn=RobotSpawnCfg()) + eye = NEAREST_CAMERA + light = AssetBaseCfg(prim_path="/World/Light", spawn=DomeLightCfg(intensity=2000)) + + +@configclass +class NumberedSceneCfg(SceneCfg): + """Vials numbered 1 to 4 in equal shares, and a rack with a number beside each opening.""" + + eye = NUMBERED_CAMERA + vial = SceneCfg().vial.replace(spawn=numbered_vials(SceneCfg().vial.spawn, str(LABEL_ASSETS))) + rack = SceneCfg().rack.replace(spawn=numbered_spawn(SceneCfg().rack.spawn, "rack", str(LABEL_ASSETS))) + + def __post_init__(self): + super().__post_init__() + self.clone_cfg.clone_strategy = balanced_shuffled_clones + + +## +# MDP +## + + class SceneRGB(ManagerTermBase): - """Read the camera at policy boundaries while native control steps continue.""" + """The scene camera's retina as RGB in [0, 1], shape (num_envs, 3, H, W). + + The image is read again only when the policy decides, so an action chunk's native steps reuse it. + """ def __init__(self, cfg, env): super().__init__(cfg, env) @@ -66,27 +150,25 @@ def __init__(self, cfg, env): def __call__(self, env): if not getattr(env, "refresh_policy_vision", True) and self.cached is not None: return self.cached - image = env.scene["eye"].data.output[env.scene["eye"].cfg.data_types[0]] - image = image.torch if hasattr(image, "torch") else image + camera = env.scene["eye"] + image = camera.data.output[camera.cfg.data_types[0]].torch self.cached = image[..., :3].float().permute(0, 3, 1, 2).contiguous() / 255.0 return self.cached -def gaze_state(env): +def gaze_state(env) -> torch.Tensor: return env.action_manager.get_term("gaze").proprioception() -def motor_action_rate(env): - # Preserve the stock penalty on the six motor increments only. - return (env.action_manager.action[:, :6] - env.action_manager.prev_action[:, :6]).square().sum(-1) +def motor_action_rate(env) -> torch.Tensor: + """The stock action-rate penalty on the six motor actions only; gaze moves freely.""" + actions = env.action_manager + return (actions.action[:, :6] - actions.prev_action[:, :6]).square().sum(-1) @configclass -class FoveatedActionsCfg(ActionsCfg): - """Preserve the pretrained motor contract across camera/randomization variants.""" - - arm_action = resolve_presets(ActionsCfg()).arm_action - gaze = CachedGazeActionCfg(angle_limit=math.radians(HORIZONTAL_FOV / 2 - 1), max_delta=0.12) +class ActiveGazeActionsCfg(ActionsCfg): + gaze = GazeActionCfg() @configclass @@ -104,10 +186,45 @@ class GazeCfg(ObservationGroupCfg): @configclass class OracleCfg(ObservationGroupCfg): + """The teacher's gaze action, used to supervise the gaze during training.""" + labels = ObservationTermCfg(func=oracle_labels) enable_corruption = False +@configclass +class OracleObservationCfg(PresetCfg): + """Gaze supervision labels; never part of the actor's observations.""" + + grasp_gated = OracleCfg() + no_gaze_supervision = None + default = grasp_gated + + +@configclass +class NumberedCriticCfg(CriticStateGroupCfg): + """The stock critic state, measured against the target opening, plus the target's position and number.""" + + placement = CriticStateGroupCfg().placement.replace(func=target_placement_features) + numbered_goal = ObservationTermCfg(func=critic_goal_state) + + +@configclass +class ObservationsCfg: + """Retina, proprioception and gaze for the CNN actor; the stock state for the critic.""" + + scene_rgb = ImageCfg() + proprioception = ProprioceptionCfg() + gaze = GazeCfg() + critic = CriticStateGroupCfg() + oracle = OracleObservationCfg() + + +@configclass +class NumberedObservationsCfg(ObservationsCfg): + critic = NumberedCriticCfg() + + @configclass class LanguageProprioceptionCfg(ProprioceptionCfg): gaze = ObservationTermCfg(func=gaze_state) @@ -117,9 +234,7 @@ class LanguageProprioceptionCfg(ProprioceptionCfg): class VisionCfg(ObservationGroupCfg): tokens = ObservationTermCfg( func=DinoTokens, - params=dict( - reference=DEFAULT_CHECKPOINT, checksum=DEFAULT_MD5, batch_size=128, data_type=CameraOutputNameCfg() - ), + params=dict(reference=DEFAULT_CHECKPOINT, checksum=DEFAULT_MD5, batch_size=128, data_type=CameraOutputNameCfg()), ) concatenate_dim = 0 enable_corruption = False @@ -132,34 +247,14 @@ class InstructionCfg(ObservationGroupCfg): @configclass -class OracleObservationCfg(PresetCfg): - """Training-only gaze labels; never part of the actor observation group.""" - - grasp_gated = OracleCfg() - no_gaze_supervision = None - default = grasp_gated - - -@configclass -class AuxiliaryObservationCfg(PresetCfg): - from .sim2real import ExtrinsicsObservations as _ExtrinsicsObservations - - default = None - extrinsics = _ExtrinsicsObservations() +class LanguageObservationsCfg: + """Frozen DINO tokens of the retina, an instruction, and proprioception with the gaze for the actor.""" - -@configclass -class ObservationsCfg: - scene_rgb = ImageCfg() - proprioception = ProprioceptionCfg() - gaze = GazeCfg() - # Stock state and contacts, with last_action naturally including gaze. - critic = CriticStateGroupCfg() + proprio = LanguageProprioceptionCfg() + vision = VisionCfg() + instruction = InstructionCfg() + critic = NumberedCriticCfg() oracle = OracleObservationCfg() - proprio: LanguageProprioceptionCfg | None = None - vision: VisionCfg | None = None - instruction: InstructionCfg | None = None - extrinsics = AuxiliaryObservationCfg() @configclass @@ -171,6 +266,8 @@ class ResetModeCfg(PresetCfg): @configclass class CurriculumCfg: + """Success-guided sampling of the reset dataset's phases.""" + reset_sampling = CurriculumTermCfg( func=ResetSampling, params=dict(mode=ResetModeCfg(), history=100, target=0.5, concentration=1.0, temperature=2.0, epsilon=1e-4), @@ -178,251 +275,79 @@ class CurriculumCfg: @configclass -class RobotSpawnCfg(PresetCfg): - _stock = SO101SceneCfg().robot.spawn.replace(shoulder_response=None, elbow_response=None) - stock_wrist_camera = _stock - default = _stock.replace(func=spawn_without_wrist_camera) - - -def scene_camera(position=CAMERA_POSITION, target=CAMERA_TARGET, hfov=HORIZONTAL_FOV): - """Construct one calibrated camera; scalar overrides address its native fields.""" - focal = SOURCE_SIZE / (2 * math.tan(math.radians(hfov / 2))) - return FoveatedTiledCameraCfg( - prim_path="{ENV_REGEX_NS}/SceneEye", - data_types=CameraOutputCfg(), - renderer_cfg=FoviRendererCfg(), - render_settings=CameraRenderSettingsCfg(), - spawn=PinholeCameraCfg( - focal_length=24.0, - horizontal_aperture=48.0 * math.tan(math.radians(hfov / 2)), - clipping_range=(0.01, 5.0), - ), - offset=CameraCfg.OffsetCfg(pos=position, rot=camera_rotation(position, target), convention="opengl"), - foveated_res=64, - foveated_style="warped_cartesian_as_grid", - ndc_layout="native_grid", - field_geometry="spherical", - camera_calibration=dict( - model="pinhole", image_size=(SOURCE_SIZE, SOURCE_SIZE), intrinsics=(focal, focal, 319.5, 319.5) - ), - cmf_a=0.036021, - fixed_software_fov=True, - software_fov_image_height=SOURCE_SIZE, - software_fov_image_width=SOURCE_SIZE, - update_period=0.0, - ) +class ActiveGazeRewardsCfg(RewardsCfg): + action_rate = RewardsCfg().action_rate.replace(func=motor_action_rate) @configclass -class SceneCfg(SO101SceneCfg): - robot = SO101SceneCfg().robot.replace( - spawn=RobotSpawnCfg(), - init_state=resolve_presets(SO101SceneCfg().robot.init_state), - ) - eye = scene_camera() - light = AssetBaseCfg(prim_path="/World/Light", spawn=DomeLightCfg(intensity=2000)) - diagnostic_camera: CameraCfg | None = None +class NumberedRewardsCfg(ActiveGazeRewardsCfg): + held_goal = RewardsCfg().held_goal.replace(func=held_target_goal) @configclass -class NumberedSceneCfg(SceneCfg): - eye = scene_camera((0.46, 0.015, 0.34), (0.17, 0.025, 0.12), 78.0).replace( - cmf_a=0.015, - ) +class NumberedEventsCfg(EventsCfg): + reset_from_dataset = EventsCfg().reset_from_dataset.replace(func=NumberedResetFromDataset) @configclass -class LanguageObservationsCfg(ObservationsCfg): - scene_rgb = None - proprioception = None - gaze = None - proprio = LanguageProprioceptionCfg() - vision = VisionCfg() - instruction = InstructionCfg() +class NumberedTerminationsCfg(TerminationsCfg): + success = TerminationsCfg().success.replace(func=TargetPlacementSuccess) @configclass class FinalObservationCfg(PresetCfg): - """Capture pre-reset critic state for timeouts inside an action chunk.""" + """Capture the critic's pre-reset state, which timeouts inside an action chunk need.""" default = False chunking = True -@configclass -class SO101FoveatedEnvCfg(SO101VialEnvCfg): - """Nearest-slot CNN task with a calibrated foveated scene camera.""" +## +# Environments +## - compute_final_obs = FinalObservationCfg() - scene = SceneCfg(num_envs=128, env_spacing=0.9) - observations = ObservationsCfg() - actions = FoveatedActionsCfg() - curriculum = CurriculumCfg() - events = EventsCfg() - mixed_gaze_resets: bool = True - reset_sampling_evaluation: bool = False - sim2real: CameraRandomizationCfg | None = None - goal_mode: ClassVar[str] = "nearest" - policy: ClassVar[str] = "cnn" - number_label_assets: str = str(LABEL_ASSETS) - - def __post_init__(self): - super().__post_init__() - # The imported actor and mid-task reset dataset use the nominal SO-101 - # geometry, action scales, rewards, and horizon in every camera variant. - self.episode_length_s = 20.0 - self.rewards = resolve_presets(self.rewards) - self.rewards.action_rate.func = motor_action_rate - self.num_rerenders_on_reset = 1 - - def validate_config(self): - """Validate the final config after presets and scalar overrides are applied.""" - if self.resolution() not in (64, 128): - raise ValueError("SO-101 foveated resolution must be 64 or 128") - if not math.isfinite(self.cmf_a()) or self.cmf_a() <= 0: - raise ValueError("cmf_a must be positive and finite") - if self.scene.eye.data_types != ["rgb"] and self.renderer_backend() != "ovrtx": - raise ValueError("Minimal render modes require renderer=ovrtx") - if self.policy == "dino_language": - if self.resolution() != 128: - raise ValueError("The pretrained foveated DINO policy requires native 128px input") - tokens = self.observations.vision.tokens.params - if tokens["data_type"] not in self.scene.eye.data_types: - raise ValueError("The DINO observation must use an output produced by the scene camera") - if tokens["batch_size"] <= 0: - raise ValueError("DINO batch_size must be positive") - if self.extrinsics_head() and self.policy != "dino_language": - raise ValueError("Extrinsics supervision requires the DINO/language preset") - validate_settings(**self.curriculum.reset_sampling.params) - - def resolution(self): - return self.scene.eye.foveated_res - - def cmf_a(self): - return self.scene.eye.cmf_a - - def camera_position(self): - return self.scene.eye.offset.pos - - def camera_hfov(self): - camera = self.scene.eye.spawn - return math.degrees(2 * math.atan(camera.horizontal_aperture / (2 * camera.focal_length))) - - def gaze_limit(self): - return self.actions.gaze.angle_limit - - def gaze_max_delta(self): - return self.actions.gaze.max_delta - - def renderer_backend(self): - renderer = self.scene.eye.renderer_cfg - renderer = renderer.default if isinstance(renderer, PresetCfg) else renderer - return "ovrtx" if renderer.renderer_type == "ovrtx" else "warp" - - def render_mode(self): - from .render_options import RENDER_MODES - - if self.renderer_backend() == "warp": - return "rgb" - outputs = self.scene.eye.data_types - output = (outputs.default if isinstance(outputs, PresetCfg) else outputs)[0] - renderer = self.scene.eye.renderer_cfg - renderer = renderer.default if isinstance(renderer, PresetCfg) else renderer - shadows = getattr(renderer, "enable_shadows", False) - shadows = shadows.default if isinstance(shadows, PresetCfg) else shadows - return next( - name for name, value in RENDER_MODES.items() if value == (output, shadows if output != "rgb" else False) - ) - - def wrist_camera(self): - spawn = self.scene.robot.spawn - spawn = spawn.default if isinstance(spawn, PresetCfg) else spawn - return "removed" if spawn.func == spawn_without_wrist_camera else "stock" - - def retinal_geometry(self): - return self.scene.eye.field_geometry - - def extrinsics_head(self): - return self.observations.extrinsics is not None +@configclass +class NearestEnvCfg(SO101VialEnvCfg): + """Place the vial in any opening, seen through the foveated scene camera.""" + + scene: SceneCfg = SceneCfg(num_envs=128, env_spacing=0.9) + actions: ActiveGazeActionsCfg = ActiveGazeActionsCfg() + observations: ObservationsCfg = ObservationsCfg() + rewards: ActiveGazeRewardsCfg = ActiveGazeRewardsCfg() + curriculum: CurriculumCfg = CurriculumCfg() + compute_final_obs = FinalObservationCfg() + num_rerenders_on_reset = 1 def play_mode(self): super().play_mode() - self.reset_sampling_evaluation = True self.curriculum.reset_sampling.params["mode"] = "uniform" - if self.sim2real is not None: - self.sim2real.ramp_steps = 0 - - def enable_diagnostics(self): - camera = self.scene.eye - self.scene.diagnostic_camera = CameraCfg( - prim_path="{ENV_REGEX_NS}/DiagnosticCamera", - data_types=list(camera.data_types), - width=640, - height=640, - renderer_cfg=camera.renderer_cfg.copy(), - render_settings=camera.render_settings.copy(), - spawn=camera.spawn.copy(), - offset=camera.offset.copy(), - ) @configclass -class SO101NumberedEnvCfg(SO101FoveatedEnvCfg): - """Match a vial's number to its rack slot using textured camera observations.""" +class NumberedEnvCfg(NearestEnvCfg): + """Place each vial in the opening with its number.""" - goal_mode: ClassVar[str] = "numbered" - scene = NumberedSceneCfg(num_envs=128, env_spacing=0.9) - actions = FoveatedActionsCfg(gaze=CachedGazeActionCfg(angle_limit=math.radians(38.0), max_delta=0.12)) - - def __post_init__(self): - super().__post_init__() - from .goals import configure_numbered_scene - - configure_numbered_scene(self) + scene: NumberedSceneCfg = NumberedSceneCfg(num_envs=128, env_spacing=0.9) + observations: NumberedObservationsCfg = NumberedObservationsCfg() + events: NumberedEventsCfg = NumberedEventsCfg() + rewards: NumberedRewardsCfg = NumberedRewardsCfg() + terminations: NumberedTerminationsCfg = NumberedTerminationsCfg() @configclass -class SO101LanguageEnvCfg(SO101NumberedEnvCfg): - """Numbered placement using frozen DINO and language features.""" +class LanguageEnvCfg(NumberedEnvCfg): + """Numbered placement from frozen foveated DINO tokens and a language instruction.""" - policy: ClassVar[str] = "dino_language" - observations = LanguageObservationsCfg() - scene = NumberedSceneCfg(num_envs=128, env_spacing=0.9, eye=NumberedSceneCfg().eye.replace(foveated_res=128)) + scene: NumberedSceneCfg = NumberedSceneCfg(num_envs=128, env_spacing=0.9, eye=NUMBERED_CAMERA.replace(foveated_res=128)) + observations: LanguageObservationsCfg = LanguageObservationsCfg() @configclass -class SO101PlanarEnvCfg(SO101LanguageEnvCfg): - """Language policy with the same planar software retina used on the robot.""" +class ActiveGazeEnvCfg(PresetCfg): + """Task variants; each name also selects its agent.""" - def __post_init__(self): - super().__post_init__() - from .sim2real import configure_planar_camera - - configure_planar_camera(self) - - -@configclass -class SO101Sim2RealEnvCfg(SO101PlanarEnvCfg): - """Planar camera, physical randomization, and auxiliary camera-pose labels.""" - - sim2real = CameraRandomizationCfg() - - def __post_init__(self): - super().__post_init__() - from .sim2real import ExtrinsicsObservations, configure - - configure(self) - self.observations.extrinsics = ExtrinsicsObservations() - - -@configclass -class SO101EnvCfg(PresetCfg): - """Registered task variants; shared names also select the matching agent.""" - - nearest = SO101FoveatedEnvCfg() - numbered = SO101NumberedEnvCfg() - dino_language = SO101LanguageEnvCfg() - planar = SO101PlanarEnvCfg() - sim2real = SO101Sim2RealEnvCfg() + nearest = NearestEnvCfg() + numbered = NumberedEnvCfg() + dino_language = LanguageEnvCfg() default = numbered diff --git a/src/isaaclab_tutorial/active_gaze/runner.py b/src/isaaclab_tutorial/active_gaze/runner.py index 06d308a..449c223 100644 --- a/src/isaaclab_tutorial/active_gaze/runner.py +++ b/src/isaaclab_tutorial/active_gaze/runner.py @@ -5,7 +5,7 @@ from .sampling import iteration_metrics -class SO101Runner(DistributedOnPolicyRunner): +class ResetSamplingRunner(DistributedOnPolicyRunner): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.sampler = self.env.unwrapped.reset_sampling diff --git a/src/isaaclab_tutorial/active_gaze/train.py b/src/isaaclab_tutorial/active_gaze/train.py index 5c858df..6ccfa7e 100644 --- a/src/isaaclab_tutorial/active_gaze/train.py +++ b/src/isaaclab_tutorial/active_gaze/train.py @@ -228,7 +228,7 @@ def main(): from isaaclab.utils.io import dump_yaml from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper - from .runner import SO101Runner + from .runner import ResetSamplingRunner env = RslRlVecEnvWrapper(ManagerBasedRLEnv(cfg), clip_actions=1.0) if chunk_size > 1: @@ -248,7 +248,7 @@ def main(): print(f"Static cap counts (1 through 4): {counts}", flush=True) dump_yaml(str(args.output / "env.yaml"), cfg) (args.output / "agent.json").write_text(json.dumps(agent, indent=2)) - runner = SO101Runner(env, agent, log_dir=str(args.output), device=cfg.sim.device) + runner = ResetSamplingRunner(env, agent, log_dir=str(args.output), device=cfg.sim.device) if args.checkpoint: initialized = [] if args.finetune: diff --git a/tests/active_gaze/test_presets.py b/tests/active_gaze/test_presets.py index b01e974..3158745 100644 --- a/tests/active_gaze/test_presets.py +++ b/tests/active_gaze/test_presets.py @@ -27,7 +27,7 @@ def test_default_recipe_matches_explicit_presets_and_native_registry(): def test_native_scalar_overrides_and_resume_preserve_typed_variants(): - from isaaclab_tutorial.active_gaze.agents import SO101Sim2RealPPORunnerCfg + from isaaclab_tutorial.active_gaze.agents import Sim2RealPPORunnerCfg from isaaclab_tutorial.active_gaze.env_cfg import SO101Sim2RealEnvCfg from isaaclab_tutorial.active_gaze.configuration import checkpoint_configuration, compose, metadata from isaaclab_tutorial.active_gaze.transfer_options import CameraRandomizationCfg @@ -44,7 +44,7 @@ def test_native_scalar_overrides_and_resume_preserve_typed_variants(): before = deepcopy(saved) restored, restored_agent, _ = compose(saved=saved) assert isinstance(restored, SO101Sim2RealEnvCfg) - assert isinstance(restored_agent, SO101Sim2RealPPORunnerCfg) + assert isinstance(restored_agent, Sim2RealPPORunnerCfg) assert isinstance(restored.sim2real, CameraRandomizationCfg) assert restored.to_dict() == env.to_dict() assert not restored_agent.finetune diff --git a/tests/active_gaze/test_sim2real.py b/tests/active_gaze/test_sim2real.py index c4b81f1..85fa63b 100644 --- a/tests/active_gaze/test_sim2real.py +++ b/tests/active_gaze/test_sim2real.py @@ -243,7 +243,7 @@ def test_auxiliary_updates_shared_vision_without_leaking_labels(tmp_path): def test_finetune_permits_only_new_head_and_preserves_normalization(tmp_path): - from isaaclab_tutorial.active_gaze.runner import SO101Runner + from isaaclab_tutorial.active_gaze.runner import ResetSamplingRunner old, obs = make_actor(tmp_path, False) old.obs_normalizer.update(obs["proprio"]) @@ -257,14 +257,14 @@ def test_finetune_permits_only_new_head_and_preserves_normalization(tmp_path): path = tmp_path / "model.pt" torch.save(checkpoint, path) runner = SimpleNamespace(alg=SimpleNamespace(_raw_actor=new, _raw_critic=deepcopy(critic))) - initialized = SO101Runner.finetune(runner, path) + initialized = ResetSamplingRunner.finetune(runner, path) assert initialized and all(key.startswith("extrinsics_head.") for key in initialized) assert runner.current_learning_iteration == 4999 torch.testing.assert_close(old(obs), new(obs)) checkpoint["actor_state_dict"].pop("mlp.0.weight") torch.save(checkpoint, path) with pytest.raises(ValueError, match="Unexpected missing"): - SO101Runner.finetune(runner, path) + ResetSamplingRunner.finetune(runner, path) def test_planar_virtual_gaze_preserves_physical_camera_and_partial_resets(monkeypatch): diff --git a/tests/active_gaze/test_vial.py b/tests/active_gaze/test_vial.py index 5522b5c..90f5fd4 100644 --- a/tests/active_gaze/test_vial.py +++ b/tests/active_gaze/test_vial.py @@ -11,9 +11,9 @@ def test_encoder_and_gaze_receive_gradients(resolution): from rsl_rl.models import CNNModel - from isaaclab_tutorial.active_gaze.agents import SO101FoveatedPPORunnerCfg + from isaaclab_tutorial.active_gaze.agents import ActiveGazePPORunnerCfg - cfg = SO101FoveatedPPORunnerCfg().to_dict() + cfg = ActiveGazePPORunnerCfg().to_dict() actor_cfg = cfg["actor"].copy() actor_cfg.pop("class_name") obs = TensorDict( From 44d496f90c95a986923a4b32dc44cebf090cd039 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:42:22 -0800 Subject: [PATCH 06/30] Move the gaze in field radii and pass degrees to the camera The gaze action, its limit and the observed gaze are in field radii of the retina, with simpler defaults: an action of 1 moves the gaze by 0.1 field radii, and the gaze stays within one field radius of the optical axis. Angles are in degrees, as the camera's set_gaze_angles now takes them. The observed gaze state is the gaze and its velocity; the commanded copy existed for the physical rig. --- src/isaaclab_tutorial/active_gaze/agents.py | 2 + src/isaaclab_tutorial/active_gaze/env_cfg.py | 8 +- src/isaaclab_tutorial/active_gaze/gaze.py | 99 ++++++++++---------- 3 files changed, 58 insertions(+), 51 deletions(-) diff --git a/src/isaaclab_tutorial/active_gaze/agents.py b/src/isaaclab_tutorial/active_gaze/agents.py index e36d6b3..8f4877c 100644 --- a/src/isaaclab_tutorial/active_gaze/agents.py +++ b/src/isaaclab_tutorial/active_gaze/agents.py @@ -1,7 +1,9 @@ """Class-based SO-101 policy, loss, and optimizer presets.""" from isaaclab.utils import configclass + from isaaclab_rl.rsl_rl import RslRlCNNModelCfg, RslRlMLPModelCfg, RslRlOnPolicyRunnerCfg, RslRlPpoAlgorithmCfg + from isaaclab_tasks.utils import PresetCfg from isaaclab_tutorial.active_gaze.learning.config import LanguageVisionActorCfg diff --git a/src/isaaclab_tutorial/active_gaze/env_cfg.py b/src/isaaclab_tutorial/active_gaze/env_cfg.py index 40c7348..6641900 100644 --- a/src/isaaclab_tutorial/active_gaze/env_cfg.py +++ b/src/isaaclab_tutorial/active_gaze/env_cfg.py @@ -234,7 +234,9 @@ class LanguageProprioceptionCfg(ProprioceptionCfg): class VisionCfg(ObservationGroupCfg): tokens = ObservationTermCfg( func=DinoTokens, - params=dict(reference=DEFAULT_CHECKPOINT, checksum=DEFAULT_MD5, batch_size=128, data_type=CameraOutputNameCfg()), + params=dict( + reference=DEFAULT_CHECKPOINT, checksum=DEFAULT_MD5, batch_size=128, data_type=CameraOutputNameCfg() + ), ) concatenate_dim = 0 enable_corruption = False @@ -339,7 +341,9 @@ class NumberedEnvCfg(NearestEnvCfg): class LanguageEnvCfg(NumberedEnvCfg): """Numbered placement from frozen foveated DINO tokens and a language instruction.""" - scene: NumberedSceneCfg = NumberedSceneCfg(num_envs=128, env_spacing=0.9, eye=NUMBERED_CAMERA.replace(foveated_res=128)) + scene: NumberedSceneCfg = NumberedSceneCfg( + num_envs=128, env_spacing=0.9, eye=NUMBERED_CAMERA.replace(foveated_res=128) + ) observations: LanguageObservationsCfg = LanguageObservationsCfg() diff --git a/src/isaaclab_tutorial/active_gaze/gaze.py b/src/isaaclab_tutorial/active_gaze/gaze.py index c846037..ad081e8 100644 --- a/src/isaaclab_tutorial/active_gaze/gaze.py +++ b/src/isaaclab_tutorial/active_gaze/gaze.py @@ -1,8 +1,8 @@ """Gaze action of the active-gaze task, its reset, and the teacher's gaze labels. -Gaze angles are (tilt, pan) [rad] from the scene camera's optical axis: positive tilt looks up and positive pan looks -left, as for :meth:`isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles`. Camera-frame directions use the OpenCV -convention: x right, y down, z forward. +Gaze angles are (tilt, pan) [deg] from the scene camera's optical axis: positive tilt looks up and positive pan looks +left, as for :meth:`isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles`. The policy sees and moves the gaze in field +radii, half the retina's field of view. Camera-frame directions use the OpenCV convention: x right, y down, z forward. """ from __future__ import annotations @@ -27,25 +27,25 @@ either.""" -def angles_to_direction(angles: torch.Tensor) -> torch.Tensor: - """Camera-frame unit directions of gaze angles, shape (..., 2) to (..., 3).""" - tilt, pan = angles.unbind(-1) +def angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: + """Camera-frame unit directions of gaze angles [deg], shape (..., 2) to (..., 3).""" + tilt, pan = angles_deg.deg2rad().unbind(-1) return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) def direction_to_angles(direction: torch.Tensor) -> torch.Tensor: - """Gaze angles of camera-frame directions, shape (..., 3) to (..., 2).""" + """Gaze angles [deg] of camera-frame directions, shape (..., 3) to (..., 2).""" x, y, z = direction.unbind(-1) - return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1) + return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1).rad2deg() def clamp_gaze(angles: torch.Tensor, limit: float) -> torch.Tensor: - """Scale gaze angles back onto the circle of radius ``limit`` [rad] when they leave it.""" + """Scale gaze angles back onto the circle of radius ``limit`` when they leave it.""" return angles * (limit / angles.norm(dim=-1, keepdim=True).clamp_min(limit)) def random_gaze(count: int, limit: float, device=None) -> torch.Tensor: - """Gaze angles drawn uniformly over the disc of radius ``limit`` [rad], shape (count, 2).""" + """Gaze angles drawn uniformly over the disc of radius ``limit``, shape (count, 2).""" radius = limit * torch.rand(count, device=device).sqrt() angle = 2 * math.pi * torch.rand(count, device=device) return torch.stack((radius * angle.sin(), radius * angle.cos()), dim=-1) @@ -99,9 +99,9 @@ def gaze_targets(env, vial_pose: torch.Tensor, rack_pose: torch.Tensor, env_ids= class GazeAction(ActionTerm): """Moves the scene camera's gaze by bounded increments in (tilt, pan) order. - An action of 1 changes an angle by ``step_size`` field radii, and the gaze stays within ``gaze_limit`` field radii - of the optical axis. The field radius is half the retina's field of view. At reset the gaze starts at one of - :data:`RESET_MODES`, drawn uniformly, or on the optical axis when ``mixed_resets`` is off. + Actions, limits and the observed gaze are in field radii. An action of 1 changes an angle by ``step_size`` and the + gaze stays within ``gaze_limit`` of the optical axis. At reset the gaze starts at one of :data:`RESET_MODES`, drawn + uniformly, or on the optical axis when ``mixed_resets`` is off. """ cfg: GazeActionCfg @@ -110,15 +110,11 @@ def __init__(self, cfg: GazeActionCfg, env): super().__init__(cfg, env) self.camera = env.scene[cfg.camera_name] self.camera_model = resolve_camera_model(self.camera.cfg) - self.field_radius = math.radians(sampling_geometry(self.camera.cfg)[0] / 2) - """Half the retina's field of view [rad].""" - self.max_step = cfg.step_size * self.field_radius - """Largest change of each gaze angle per step [rad].""" - self.limit = cfg.gaze_limit * self.field_radius - """Largest angle between the gaze and the optical axis [rad].""" + self.field_radius_deg = sampling_geometry(self.camera.cfg)[0] / 2 + """Half the retina's field of view [deg].""" self.base_rotation = torch.tensor(self.camera.cfg.offset.rot, device=self.device) self._raw = torch.zeros(self.num_envs, 2, device=self.device) - self._angles = torch.zeros_like(self._raw) + self._gaze = torch.zeros_like(self._raw) self._velocity = torch.zeros_like(self._raw) self.reset_mode = torch.zeros(self.num_envs, dtype=torch.long, device=self.device) """Index into :data:`RESET_MODES` of each environment's last reset.""" @@ -133,19 +129,24 @@ def raw_actions(self) -> torch.Tensor: @property def processed_actions(self) -> torch.Tensor: - return self._angles + return self._gaze @property - def angles(self) -> torch.Tensor: - """Current gaze angles [rad], shape (num_envs, 2).""" - return self._angles + def gaze(self) -> torch.Tensor: + """Current gaze in field radii, shape (num_envs, 2).""" + return self._gaze + + @property + def angles_deg(self) -> torch.Tensor: + """Current gaze angles [deg], shape (num_envs, 2).""" + return self._gaze * self.field_radius_deg def process_actions(self, actions: torch.Tensor): self._raw.copy_(actions) - previous = self._angles.clone() - self._angles.copy_(clamp_gaze(self._angles + actions.clamp(-1, 1) * self.max_step, self.limit)) - self._velocity.copy_((self._angles - previous) / self._env.step_dt) - self.camera.set_gaze_angles(self._angles) + previous = self._gaze.clone() + self._gaze.copy_(clamp_gaze(self._gaze + actions.clamp(-1, 1) * self.cfg.step_size, self.cfg.gaze_limit)) + self._velocity.copy_((self._gaze - previous) / self._env.step_dt) + self.camera.set_gaze_angles(self.angles_deg) def apply_actions(self): pass @@ -154,11 +155,11 @@ def reset(self, env_ids=None): ids = torch.arange(self.num_envs, device=self.device)[slice(None) if env_ids is None else env_ids] self._raw[ids] = 0 self._velocity[ids] = 0 + self._gaze[ids] = 0 self.reset_mode[ids] = 0 - self._angles[ids] = 0 if self.cfg.mixed_resets and len(ids): self._reset_mixed(ids) - self.camera.set_gaze_angles(self._angles) + self.camera.set_gaze_angles(self.angles_deg) def _reset_mixed(self, ids: torch.Tensor): """Start each gaze at one of :data:`RESET_MODES` for this episode's vial and rack.""" @@ -174,12 +175,12 @@ def _reset_mixed(self, ids: torch.Tensor): point = torch.where(((modes == 2) | (modes == 4))[:, None], goal_point, vial_point) direction = self.directions(point, ids) direction = torch.where((modes >= 3)[:, None], nearby_directions(direction), direction) - aligned = direction_to_angles(direction) - modes = torch.where(self.visible(direction) & (aligned.norm(dim=-1) <= self.limit), modes, 0) + aligned = direction_to_angles(direction) / self.field_radius_deg + modes = torch.where(self.visible(direction) & (aligned.norm(dim=-1) <= self.cfg.gaze_limit), modes, 0) # A random start lies inside the physical image too; the optical axis is the fallback. - random = random_gaze(len(ids), self.limit, self.device) - random = torch.where(self.visible(angles_to_direction(random))[:, None], random, 0) - self._angles[ids] = torch.where((modes == 0)[:, None], random, aligned) + random = random_gaze(len(ids), self.cfg.gaze_limit, self.device) + random = torch.where(self.visible(angles_to_direction(random * self.field_radius_deg))[:, None], random, 0) + self._gaze[ids] = torch.where((modes == 0)[:, None], random, aligned) self.reset_mode[ids] = modes def directions(self, points: torch.Tensor, env_ids=slice(None)) -> torch.Tensor: @@ -196,21 +197,21 @@ def teacher_action(self, points: torch.Tensor) -> tuple[torch.Tensor, torch.Tens A point is valid when the physical camera sees it and the gaze can reach it within the limit. """ direction = self.directions(points) - desired = direction_to_angles(direction) - valid = self.visible(direction) & (desired.norm(dim=-1) <= self.limit) - action = ((clamp_gaze(desired, self.limit) - self._angles) / self.max_step).clamp(-1, 1) + desired = direction_to_angles(direction) / self.field_radius_deg + valid = self.visible(direction) & (desired.norm(dim=-1) <= self.cfg.gaze_limit) + action = ((clamp_gaze(desired, self.cfg.gaze_limit) - self._gaze) / self.cfg.step_size).clamp(-1, 1) return torch.where(valid[:, None], action, 0.0), valid - def fixation_error(self, points: torch.Tensor) -> torch.Tensor: - """Angle [rad] between the gaze and the direction to world points.""" + def fixation_error_deg(self, points: torch.Tensor) -> torch.Tensor: + """Angle [deg] between the gaze and the direction to world points.""" direction = self.directions(points) - gaze = angles_to_direction(self._angles) + gaze = angles_to_direction(self.angles_deg) # atan2 stays accurate near perfect alignment, unlike acos of the dot product. - return torch.atan2(torch.cross(gaze, direction, dim=-1).norm(dim=-1), (gaze * direction).sum(-1)) + return torch.atan2(torch.cross(gaze, direction, dim=-1).norm(dim=-1), (gaze * direction).sum(-1)).rad2deg() def proprioception(self) -> torch.Tensor: - """Gaze angles, their velocity and the command. The virtual gaze reaches its command at once.""" - return torch.cat((self._angles, self._velocity, self._angles), dim=-1) + """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4).""" + return torch.cat((self._gaze, self._velocity), dim=-1) @configclass @@ -221,10 +222,10 @@ class GazeActionCfg(ActionTermCfg): asset_name: str = "robot" camera_name: str = "eye" """Scene name of the foveated camera whose gaze the action moves.""" - step_size: float = 0.17 - """Change of each gaze angle per step at an action of 1, in field radii.""" - gaze_limit: float = 0.975 - """Largest angle between the gaze and the camera's optical axis, in field radii.""" + step_size: float = 0.1 + """Change of each gaze coordinate per step at an action of 1, in field radii.""" + gaze_limit: float = 1.0 + """Largest distance of the gaze from the camera's optical axis, in field radii.""" mixed_resets: bool = True """Start episodes at a gaze drawn from :data:`RESET_MODES`; otherwise on the optical axis.""" @@ -244,7 +245,7 @@ def oracle_labels(env) -> torch.Tensor: gaze: GazeAction = env.action_manager.get_term("gaze") point = teacher_target(env) action, valid = gaze.teacher_action(point) - error = gaze.fixation_error(point).rad2deg() + error = gaze.fixation_error_deg(point) log = env.extras.setdefault("log", {}) log["Gaze/target_error_deg"] = torch.where(valid, error, 0).sum() / valid.sum().clamp_min(1) log["Gaze/within_1deg"] = (valid & (error <= 1)).float().mean() From bc4b72e5dee2d11b5ef3b7b9d4e6db56c0e664ca Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:42:49 -0800 Subject: [PATCH 07/30] Import the ActiveGaze robot deployment from isaaclab_fovi Copies the SO-101 LEAPP export, the real-robot runtime and the software retina from the original isaaclab_fovi package, with their tests. The planar software retina is not copied: the camera samples only in spherical coordinates. Only file locations, license headers and import paths change here. --- .../active_gaze/deployment/__init__.py | 1 + .../active_gaze/deployment/control.py | 79 +++++ .../active_gaze/deployment/export.py | 168 +++++++++++ .../active_gaze/deployment/hardware.py | 67 +++++ .../active_gaze/deployment/model.py | 87 ++++++ .../active_gaze/deployment/retina.py | 75 +++++ .../active_gaze/deployment/run.py | 254 ++++++++++++++++ .../active_gaze/deployment/runtime.py | 88 ++++++ tests/active_gaze/test_deployment.py | 279 ++++++++++++++++++ tests/active_gaze/test_hardware.py | 86 ++++++ 10 files changed, 1184 insertions(+) create mode 100644 src/isaaclab_tutorial/active_gaze/deployment/__init__.py create mode 100644 src/isaaclab_tutorial/active_gaze/deployment/control.py create mode 100644 src/isaaclab_tutorial/active_gaze/deployment/export.py create mode 100644 src/isaaclab_tutorial/active_gaze/deployment/hardware.py create mode 100644 src/isaaclab_tutorial/active_gaze/deployment/model.py create mode 100644 src/isaaclab_tutorial/active_gaze/deployment/retina.py create mode 100644 src/isaaclab_tutorial/active_gaze/deployment/run.py create mode 100644 src/isaaclab_tutorial/active_gaze/deployment/runtime.py create mode 100644 tests/active_gaze/test_deployment.py create mode 100644 tests/active_gaze/test_hardware.py diff --git a/src/isaaclab_tutorial/active_gaze/deployment/__init__.py b/src/isaaclab_tutorial/active_gaze/deployment/__init__.py new file mode 100644 index 0000000..4337ab1 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/deployment/__init__.py @@ -0,0 +1 @@ +"""Monocular foveated SO-101 deployment through LEAPP.""" diff --git a/src/isaaclab_tutorial/active_gaze/deployment/control.py b/src/isaaclab_tutorial/active_gaze/deployment/control.py new file mode 100644 index 0000000..91864a6 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/deployment/control.py @@ -0,0 +1,79 @@ +"""Explicit policy-step state and measured-position-relative motor targets.""" + +import math + +import numpy as np + +JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper") +PROPRIOCEPTION = ( + "joint_pos:6", + "joint_vel:6", + "joint_target:6", + "previous_action:8", + "gaze_angles:2", + "gaze_velocity:2", + "gaze_target:2", +) + + +def advance_policy_deadline(deadline: float, now: float) -> tuple[float, int]: + """Preserve the policy clock's phase despite bus wakeup jitter, without bursts.""" + periods = max(1, math.floor((now - deadline) * 30) + 1) + return deadline + periods / 30, periods - 1 + + +def validate_contract(contract: dict) -> None: + if ( + contract.get("format") != "isaaclab_fovi.so101.leapp.v1" + or contract.get("joint_order") != list(JOINTS) + or contract.get("joint_units") != "radians" + or contract.get("proprioception") != list(PROPRIOCEPTION) + or contract.get("policy_hz") != 30 + or contract.get("relative_target_hz") != 120 + ): + raise ValueError("Unsupported SO-101 deployment contract") + scale = np.asarray(contract["action_scale"]) + if scale.shape != (6,) or not np.isfinite(scale).all() or (scale <= 0).any(): + raise ValueError("Expected six finite positive action scales") + for name in ("gaze_limit", "gaze_max_delta"): + if not math.isfinite(contract[name]) or contract[name] <= 0: + raise ValueError(f"Invalid {name}") + + +class PolicyState: + """Only commit gaze/action history when a policy result is accepted by control.""" + + def __init__(self, contract: dict): + validate_contract(contract) + self.scale = np.asarray(contract["action_scale"], dtype=np.float64) + self.limit = contract["gaze_limit"] + self.delta = contract["gaze_max_delta"] + self.reset() + + def reset(self, gaze=None): + self.action = np.zeros(8, dtype=np.float32) + self.gaze = np.zeros(2, dtype=np.float32) if gaze is None else np.asarray(gaze, dtype=np.float32).copy() + if self.gaze.shape != (2,) or not np.isfinite(self.gaze).all() or (np.abs(self.gaze) > self.limit).any(): + raise ValueError("Initial gaze must be finite and inside the trained range") + self.gaze_velocity = np.zeros(2, dtype=np.float32) + + def observation(self, position, velocity, target): + # Training observations are raw encoder values, not deployment-specific clipping. + proprio = np.concatenate( + (position, velocity, target, self.action, self.gaze, self.gaze_velocity, self.gaze) + ).astype(np.float32) + if proprio.shape != (32,) or not np.isfinite(proprio).all(): + raise ValueError("Expected finite SO-101 proprioception") + return proprio + + def commit(self, action): + action = np.asarray(action, dtype=np.float32) + if action.shape != (8,) or not np.isfinite(action).all(): + raise ValueError("Expected eight finite policy actions") + self.action = action.clip(-1, 1) + gaze = (self.gaze + self.action[-2:] * self.delta).clip(-self.limit, self.limit) + self.gaze_velocity = (gaze - self.gaze) * 30 + self.gaze = gaze + + def target(self, measured, limits): + return np.clip(np.asarray(measured) + self.scale * self.action[:6], limits[:, 0], limits[:, 1]) diff --git a/src/isaaclab_tutorial/active_gaze/deployment/export.py b/src/isaaclab_tutorial/active_gaze/deployment/export.py new file mode 100644 index 0000000..051f2fc --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/deployment/export.py @@ -0,0 +1,168 @@ +"""Export a complete monocular SO-101 DINO policy and validate LEAPP parity.""" + +import argparse +import hashlib +import importlib.metadata +import json +from pathlib import Path + +import torch + +from .control import JOINTS, PROPRIOCEPTION, validate_contract +from .model import load_policy +from .retina import nominal_calibration + + +def export_node(model, inputs: dict, output: Path): + """Annotate and compile the explicit policy model with LEAPP.""" + import leapp + + # The encoder already traces explicit BF16 casts. The JIT autocast pass can + # otherwise insert a second mixed-precision conversion after its warmup run. + torch._C._jit_set_autocast_mode(False) + output.mkdir(parents=True) + with torch.inference_mode(), torch.jit.optimized_execution(False): + traced = torch.jit.trace(model, tuple(inputs.values()), check_trace=False) + model_path = output / "policy.pt" + traced.save(str(model_path)) + expected = model(*inputs.values()) + leapp.start(str(output)) + try: + annotated = leapp.annotate.input_tensors("policy", inputs) + values = [annotated] if len(inputs) == 1 else annotated + representative = expected + for value in values: + representative = representative + 0 * value.float().sum() + leapp.annotate.output_tensors( + "policy", + {"action": representative}, + export_with=None, + backend_params={"model_path": str(model_path), "copy_original_model": True}, + ) + finally: + leapp.stop() + leapp.compile_graph(visualize=False, validate=True) + yaml = output / f"{output.name}.yaml" + return leapp.InferenceManager(str(yaml)), yaml + + +def export(checkpoint: Path, dino: str, output: Path, calibration=None, device="cuda:0"): + if device != "cuda:0": + raise ValueError("Export on cuda:0; select the physical GPU with CUDA_VISIBLE_DEVICES") + if output.exists(): + raise FileExistsError(f"Use a new export directory: {output}") + settings = json.loads(checkpoint.with_name("example.json").read_text()) + planar = settings.get("retinal_geometry") == "planar" + if planar and calibration is not None: + raise ValueError("Planar deployment uses an uncalibrated square crop; omit --calibration") + calibrated = calibration is not None + calibration = calibration or nominal_calibration(settings["camera"]["camera_hfov"]) + dense, original, settings = load_policy(checkpoint, dino, calibration, device) + output.mkdir(parents=True) + camera = settings["camera"] + scale = settings.get("control", {}).get("action_scale") + if scale is None: + raise ValueError("Checkpoint must record control.action_scale") + contract = dict( + format="isaaclab_fovi.so101.leapp.v1", + joint_order=list(JOINTS), + joint_units="radians", + proprioception=list(PROPRIOCEPTION), + policy_hz=30, + relative_target_hz=120, + action_scale=scale, + gaze_limit=camera["gaze_limit"], + gaze_max_delta=camera["gaze_max_delta"], + camera_calibration=calibration, + calibrated_capture=calibrated, + retinal_geometry="planar" if planar else "spherical", + capture_preprocessing="center_square_resize_640" if planar else "calibrated_raster", + retinal_resolution=128, + camera_hfov=camera["camera_hfov"], + cmf_a=camera["cmf_a"], + instruction=settings["policy"]["instructions"][0], + source_sha256=hashlib.sha256(checkpoint.read_bytes()).hexdigest(), + source_checkpoint=checkpoint.name, + dino_checksum=settings["policy"]["dino_checksum"], + versions={name: importlib.metadata.version(name) for name in ("torch", "fovi", "leapp")}, + rgb_layout="BHWC_uint8", + retinal_sampling="bilinear_border_mask_round_uint8", + initial_gaze="neutral", + output="eight_unclipped_normalized_actions", + ) + validate_contract(contract) + generator = torch.Generator(device=device).manual_seed(71) + h, w = calibration["image_size"] + proprio = torch.zeros(1, 32, device=device) + rgb = torch.randint(0, 256, (1, h, w, 3), dtype=torch.uint8, device=device, generator=generator) + retina = dense.retina(rgb, proprio[:, 26:28]) + camera_runtime, camera_yaml = export_node(dense, dict(proprio=proprio, rgb=rgb), output / "camera") + retinal_runtime, retinal_yaml = export_node( + dense.policy, dict(proprio=proprio, retinal_rgb=retina), output / "retinal" + ) + maximum = dict(camera=0.0, retinal=0.0, original_actor=0.0) + # Repeated-inference validation matters: the profiling executor changes this + # BF16 encoder's numerics after its first invocation in PyTorch 2.11. + with torch.inference_mode(), torch.jit.optimized_execution(False): + for _ in range(8): + proprio = torch.randn(1, 32, device=device, generator=generator) + proprio[:, 26:28].clamp_(-camera["gaze_limit"], camera["gaze_limit"]) + rgb.random_(0, 256, generator=generator) + retina = dense.retina(rgb, proprio[:, 26:28]) + tokens = dense.policy.encoder(retina) + expected = original( + dict( + proprio=proprio, + vision=tokens, + instruction=torch.zeros(1, 1, dtype=torch.long, device=device), + ) + ) + candidates = dict( + original_actor=dense.policy(proprio, retina), + camera=camera_runtime.run_policy({"policy/proprio": proprio, "policy/rgb": rgb})["policy/action"], + retinal=retinal_runtime.run_policy({"policy/proprio": proprio, "policy/retinal_rgb": retina})[ + "policy/action" + ], + ) + for name, actual in candidates.items(): + torch.testing.assert_close(actual.to(expected), expected, atol=2e-4, rtol=2e-4, msg=name) + maximum[name] = max(maximum[name], (actual.to(expected) - expected).abs().max().item()) + contract.update( + camera_graph=str(camera_yaml.relative_to(output)), + retinal_graph=str(retinal_yaml.relative_to(output)), + ) + # Every executable and graph is covered; the contract itself is the root manifest. + contract["files"] = { + str(p.relative_to(output)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(output.rglob("*")) + if p.is_file() + } + (output / "contract.json").write_text(json.dumps(contract, indent=2)) + (output / "parity.json").write_text(json.dumps(dict(device=device, samples=8, max_action_error=maximum), indent=2)) + print(json.dumps(dict(bundle=str(output), max_action_error=maximum), indent=2)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--dino", required=True, help="Local Fovi bundle or pinned model URI") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument( + "--calibration", + type=Path, + help="Actual capture CameraModel JSON for spherical policies; omit for planar policies", + ) + parser.add_argument("--device", default="cuda:0") + args = parser.parse_args() + torch.set_num_threads(4) + export( + args.checkpoint.resolve(), + args.dino, + args.output.resolve(), + json.loads(args.calibration.read_text()) if args.calibration else None, + args.device, + ) + + +if __name__ == "__main__": + main() diff --git a/src/isaaclab_tutorial/active_gaze/deployment/hardware.py b/src/isaaclab_tutorial/active_gaze/deployment/hardware.py new file mode 100644 index 0000000..db3c687 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/deployment/hardware.py @@ -0,0 +1,67 @@ +"""Calibrated joint mapping and motor shutdown for SO-101 deployment.""" + +import math + +import numpy as np + +from .control import JOINTS + + +def finish_motor_control(robot, *, hold: bool) -> None: + """Hold fresh measured encoder positions only after a normal diagnostic stop.""" + holding = False + try: + if hold: + position = robot.bus.sync_read("Present_Position", normalize=False) + robot.bus.sync_write("Goal_Position", position, normalize=False) + holding = True + finally: + robot.bus.disconnect(disable_torque=not holding) + + +def require_start_pose(measured: np.ndarray, reference: dict) -> None: + expected = np.asarray(reference["position"], dtype=float) + tolerance = float(reference["tolerance_rad"]) + if expected.shape != (6,) or not np.isfinite(expected).all() or not math.isfinite(tolerance) or tolerance <= 0: + raise ValueError("Invalid starting-pose reference") + error = np.abs(measured - expected) + if not np.isfinite(measured).all() or (error > tolerance).any(): + raise ValueError(f"Move to the training home pose before execution; errors in degrees: {np.degrees(error)}") + + +class JointMap: + """Explicit affine maps from LeRobot degrees/gripper percent to simulation radians.""" + + def __init__(self, data: dict): + if data.get("units") != "lerobot_degrees_and_gripper_percent": + raise ValueError("Joint map must declare LeRobot degrees and gripper percent") + entries = [data["joints"][name] for name in JOINTS] + self.scale = np.array([entry["scale"] for entry in entries], dtype=np.float64) + self.offset = np.array([entry["offset"] for entry in entries], dtype=np.float64) + self.limits = np.array([entry["limits"] for entry in entries], dtype=np.float64) + if self.limits.shape != (6, 2) or not all( + np.isfinite(value).all() for value in (self.scale, self.offset, self.limits) + ): + raise ValueError("Joint map needs six finite scales, offsets and limit pairs") + if (self.scale == 0).any() or (self.limits[:, 0] >= self.limits[:, 1]).any(): + raise ValueError("Joint scales must be nonzero and limits increasing") + self.verified = data.get("verified") is True + + def positions(self, native: dict) -> np.ndarray: + values = np.array([native[name] for name in JOINTS]) * self.scale + self.offset + if not np.isfinite(values).all(): + raise ValueError("Non-finite measured joint position") + return values + + def require_in_limits(self, measured: np.ndarray) -> None: + """Reject a starting pose that clipping could turn into a large first movement.""" + outside = (measured < self.limits[:, 0]) | (measured > self.limits[:, 1]) + if not np.isfinite(measured).all() or outside.any(): + names = [name for name, invalid in zip(JOINTS, outside, strict=True) if invalid] + raise ValueError(f"Measured pose is outside the verified simulation/hardware limits: {names}") + + def commands(self, target: np.ndarray) -> dict: + if target.shape != (6,) or not np.isfinite(target).all(): + raise ValueError("Expected six finite joint targets") + native = (np.clip(target, self.limits[:, 0], self.limits[:, 1]) - self.offset) / self.scale + return {f"{name}.pos": float(value) for name, value in zip(JOINTS, native, strict=True)} diff --git a/src/isaaclab_tutorial/active_gaze/deployment/model.py b/src/isaaclab_tutorial/active_gaze/deployment/model.py new file mode 100644 index 0000000..abf7baa --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/deployment/model.py @@ -0,0 +1,87 @@ +"""Restore the trained actor without starting Isaac Lab or loading a text model.""" + +import copy +import json +from pathlib import Path + +import torch +from torch import nn + +from isaaclab_tutorial.active_gaze.learning.dino import FrozenDino +from isaaclab_tutorial.active_gaze.learning.models import LanguageVisionActor + +from .retina import SoftwareRetina + + +class FlatActor(nn.Module): + def __init__(self, actor): + super().__init__() + self.normalizer = copy.deepcopy(actor.obs_normalizer) + self.fusion = copy.deepcopy(actor.fusion) + self.mlp = copy.deepcopy(actor.mlp) + self.output = actor.distribution.as_deterministic_output_module() + self.register_buffer("language", actor.language_features.clone()) + self.register_buffer("padding", actor.language_padding.clone()) + + def forward(self, proprio: torch.Tensor, vision: torch.Tensor) -> torch.Tensor: + visual = self.fusion(vision, self.language.expand(len(vision), -1, -1), self.padding.expand(len(vision), -1)) + return self.output(self.mlp(torch.cat((self.normalizer(proprio), visual), -1))) + + +class RetinalPolicy(nn.Module): + def __init__(self, encoder, actor): + super().__init__() + self.encoder, self.actor = encoder, actor + + def forward(self, proprio: torch.Tensor, retinal_rgb: torch.Tensor) -> torch.Tensor: + return self.actor(proprio, self.encoder(retinal_rgb)) + + +class CameraPolicy(nn.Module): + def __init__(self, retina, policy): + super().__init__() + self.retina, self.policy = retina, policy + + def forward(self, proprio: torch.Tensor, rgb: torch.Tensor) -> torch.Tensor: + return self.policy(proprio, self.retina(rgb, proprio[:, 26:28])) + + +def load_policy(checkpoint: Path, dino: str, calibration: dict, device: str): + """Load trusted local training artifacts and validate their supported contract.""" + settings = json.loads(checkpoint.with_name("example.json").read_text()) + config = json.loads(checkpoint.with_name("agent.json").read_text()) + if settings["policy"]["name"] != "dino_language" or settings["resolution"] != 128: + raise ValueError("This exporter supports the SO-101 128px DINO/language policy") + if config["obs_groups"]["actor"] != ["proprio", "vision", "instruction"]: + raise ValueError("Unsupported actor observation contract") + if config["algorithm"].get("action_chunk_size", 1) != 1: + raise ValueError("Hardware export currently requires single-step actions") + if config.get("clip_actions") != 1.0: + raise ValueError("Unsupported action clipping") + packed = torch.load(checkpoint, map_location="cpu", weights_only=False) + state = packed["actor_state_dict"] + if state["obs_normalizer._mean"].shape != (1, 32): + raise ValueError("Expected the SO-101 32-value proprioceptive contract") + options = dict(config["actor"]) + if options.pop("class_name") != "isaaclab_tutorial.active_gaze.learning.models:LanguageVisionActor": + raise ValueError("Unsupported actor class") + options["instruction_table_path"] = str(checkpoint.with_name("instructions.pt")) + options["language_device"] = "cpu" + obs = dict( + proprio=torch.zeros(1, 32), + vision=torch.zeros(1, 64, 384), + instruction=torch.zeros(1, 1, dtype=torch.long), + ) + actor = LanguageVisionActor(obs, config["obs_groups"], "actor", 8, **options).eval() + actor.load_state_dict(state, strict=True) + encoder = FrozenDino(dino, settings["policy"]["dino_checksum"], batch_size=1) + camera = settings["camera"] + retinal = RetinalPolicy(encoder, FlatActor(actor)).to(device).eval() + if settings.get("retinal_geometry") == "planar": + from .planar import PlanarRetina + + retina = PlanarRetina(camera["camera_hfov"], camera["cmf_a"]) + else: + retina = SoftwareRetina(calibration, camera["camera_hfov"], camera["cmf_a"]) + dense = CameraPolicy(retina, retinal) + return dense.to(device).eval(), actor.to(device).eval(), settings diff --git a/src/isaaclab_tutorial/active_gaze/deployment/retina.py b/src/isaaclab_tutorial/active_gaze/deployment/retina.py new file mode 100644 index 0000000..13ee86c --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/deployment/retina.py @@ -0,0 +1,75 @@ +"""Sample real RGB images using the simulator's calibrated, upright ray grid.""" + +import math + +import torch +from fovi.sensing.coords import SamplingCoords +from fovi.sensing.projection import CameraModel, gaze_rotation +from torch import nn +from torch.nn import functional as F + +from isaaclab_fovi.sensors.native_grid import native_grid_directions + + +def nominal_calibration(hfov: float, size: int = 640) -> dict: + focal = size / (2 * math.tan(math.radians(hfov / 2))) + return dict( + model="pinhole", + image_size=[size, size], + intrinsics=[focal, focal, (size - 1) / 2, (size - 1) / 2], + ) + + +class SoftwareRetina(nn.Module): + """Bilinear dense-image sampling with the exact native-grid permutation. + + Calibration describes the actual capture raster, without implicit resizing. + Angular coverage and CMF describe the trained retina independently of it. + Inputs are uint8 BHWC RGB and (tilt, pan) radians. Output is uint8 BHWC. + """ + + def __init__(self, calibration: dict, hfov: float, cmf_a: float, resolution: int = 128): + super().__init__() + self.camera = CameraModel(**calibration) + if self.camera.model != "pinhole": + raise ValueError("SO-101 deployment requires a calibrated pinhole camera") + self.height, self.width = self.camera.image_size + self.resolution = resolution + coords = SamplingCoords( + fov=hfov, + cmf_a=cmf_a * hfov, + res=resolution, + style="warped_cartesian_as_grid", + fov_type="circular", + radius_norm=2.0, + field_geometry="spherical", + device="cpu", + ) + rays = native_grid_directions(coords, tangent_scale=1.0) + # Renderer OpenGL rays -> upright OpenCV rays, then public image ordering. + rays = coords.as_grid(rays * rays.new_tensor((1, -1, -1)), sample_dim=0) + self.register_buffer("rays", rays.reshape(-1, 3)) + self.register_buffer("valid", coords.as_grid(coords.valid_mask).reshape(1, resolution, resolution, 1)) + + def grid(self, gaze: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + tilt, pan = gaze.float().unbind(-1) + direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) + rotation = gaze_rotation(direction, "pan_tilt") + # Explicit reductions avoid TF32 errors in camera geometry. + rays = (self.rays[None, :, None, :] * rotation[:, None, :, :]).sum(-1) + pixels, visible = self.camera.project(rays) + extent = pixels.new_tensor((self.width, self.height)) + grid = (2 * (pixels + 0.5) / extent - 1).reshape(-1, self.resolution, self.resolution, 2) + visible = visible.reshape(-1, self.resolution, self.resolution, 1) & self.valid + return grid, visible + + def forward(self, rgb: torch.Tensor, gaze: torch.Tensor) -> torch.Tensor: + grid, valid = self.grid(gaze) + sampled = F.grid_sample( + rgb.permute(0, 3, 1, 2).float(), + grid, + mode="bilinear", + padding_mode="border", + align_corners=False, + ) + return sampled.permute(0, 2, 3, 1).masked_fill(~valid, 0).round().clamp(0, 255).to(torch.uint8) diff --git a/src/isaaclab_tutorial/active_gaze/deployment/run.py b/src/isaaclab_tutorial/active_gaze/deployment/run.py new file mode 100644 index 0000000..7e974a1 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/deployment/run.py @@ -0,0 +1,254 @@ +"""Run the foveated LEAPP policy with a calibrated LeRobot interface. + +Default operation is read-only. Inference and capture run outside the joint bus +loop; only that loop may commit actions or write motors. No simulator is loaded. +""" + +import argparse +import hashlib +import json +import math +import threading +import time +from pathlib import Path + +import numpy as np +import torch + +from .control import JOINTS, PolicyState, advance_policy_deadline +from .hardware import ( + JointMap, + finish_motor_control, + require_start_pose, +) +from .runtime import InferenceWorker, PolicyRuntime + + +class SceneCamera: + """Capture the latest frame using the calibrated raster size.""" + + def __init__(self, device, image_size, planar=False): + import cv2 + + self.capture = cv2.VideoCapture(device, cv2.CAP_V4L2) + if not self.capture.isOpened(): + raise RuntimeError(f"Cannot open camera {device}") + h, w = image_size + self.planar = planar + self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, w) + self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, h) + self.capture.set(cv2.CAP_PROP_FPS, 30) + self.capture.set(cv2.CAP_PROP_BUFFERSIZE, 1) + self.latest, self.error = None, None + self.stop = threading.Event() + self.thread = threading.Thread(target=self._read, daemon=True) + self.thread.start() + + def timestamped_frame(self): + if self.error: + raise self.error + latest = self.latest + if latest is None or time.monotonic() - latest[0] > 0.1: + raise RuntimeError("No fresh camera frame") + stamp, rgb = latest + if self.planar: + import cv2 + + h, w = rgb.shape[:2] + side = min(h, w) + top, left = (h - side) // 2, (w - side) // 2 + rgb = cv2.resize(rgb[top : top + side, left : left + side], (640, 640), interpolation=cv2.INTER_AREA) + return stamp, rgb + + def _read(self): + import cv2 + + while not self.stop.is_set(): + ok, bgr = self.capture.read() + if not ok: + self.error = RuntimeError("Camera capture failed") + return + self.latest = (time.monotonic(), cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)) + + def close(self): + self.stop.set() + self.thread.join(timeout=1) + self.capture.release() + + +def intersect_limits(mapping, calibration): + for index, name in enumerate(JOINTS): + item = calibration[name] + half_range = (item.range_max - item.range_min) * 180 / 4095 + native = [0, 100] if name == "gripper" else [-half_range, half_range] + physical = sorted(np.asarray(native) * mapping.scale[index] + mapping.offset[index]) + mapping.limits[index] = [ + max(mapping.limits[index, 0], physical[0]), + min(mapping.limits[index, 1], physical[1]), + ] + if mapping.limits[index, 0] >= mapping.limits[index, 1]: + raise ValueError(f"No common simulation/hardware travel for {name}") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--bundle", type=Path, required=True) + parser.add_argument("--joint-map", type=Path, required=True) + parser.add_argument("--port", required=True) + parser.add_argument("--camera", default="/dev/video0") + parser.add_argument("--id", default="wowrobo_follower") + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--duration", type=float, default=30) + parser.add_argument("--execute", action="store_true") + parser.add_argument("--start-pose", type=Path) + parser.add_argument("--trace", type=Path, help="Save policy inputs/actions and bus targets to a new NPZ") + args = parser.parse_args() + if not math.isfinite(args.duration) or args.duration <= 0: + parser.error("duration must be positive and finite") + if args.trace and args.trace.exists(): + parser.error("Choose a new trace filename") + map_data = json.loads(args.joint_map.read_text()) + mapping = JointMap(map_data) + start_pose = json.loads(args.start_pose.read_text()) if args.start_pose else None + if args.execute and (not mapping.verified or not map_data.get("calibration_sha256") or start_pose is None): + parser.error("Execution requires a verified calibration-bound joint map and start pose") + from lerobot.robots.so_follower import SO101Follower, SO101FollowerConfig + + torch.set_num_threads(1) + runtime = PolicyRuntime(args.bundle, args.device) + planar = runtime.contract.get("retinal_geometry") == "planar" + if args.execute and not planar and not runtime.contract["calibrated_capture"]: + parser.error("Export with the actual camera --calibration before hardware execution") + state = PolicyState(runtime.contract) + robot = SO101Follower(SO101FollowerConfig(port=args.port, id=args.id, use_degrees=True)) + camera = SceneCamera(args.camera, runtime.contract["camera_calibration"]["image_size"], planar) + worker = InferenceWorker(runtime) + configured = False + traces, inputs, actions, images, timings = [], [], [], [], [] + missed = policy_missed = 0 + try: + robot.bus.connect() + if not robot.is_calibrated: + raise RuntimeError("Robot calibration must already match its motors") + digest = map_data.get("calibration_sha256") + if digest and hashlib.sha256(robot.calibration_fpath.read_bytes()).hexdigest() != digest: + raise RuntimeError("Robot calibration changed; reverify the joint map") + intersect_limits(mapping, robot.calibration) + deadline = time.monotonic() + 3 + while camera.latest is None and camera.error is None and time.monotonic() < deadline: + time.sleep(0.01) + native = robot.bus.sync_read("Present_Position") + previous = mapping.positions(native) + target = mapping.positions(robot.bus.sync_read("Goal_Position")) + if args.execute: + mapping.require_in_limits(previous) + require_start_pose(previous, start_pose) + target = previous.copy() + # Warm the CUDA/LEAPP path before enabling motors; discard its action. + runtime.infer(state.observation(previous, np.zeros(6), target), camera.timestamped_frame()[1]) + if args.execute: + # Warmup can take seconds. Re-read both the pose check and the goal + # seed immediately before torque configuration. + native = robot.bus.sync_read("Present_Position") + previous = mapping.positions(native) + mapping.require_in_limits(previous) + require_start_pose(previous, start_pose) + target = previous.copy() + configured = True + robot.bus.disable_torque() + robot.bus.sync_write("Goal_Position", native) + robot.configure() + start = next_policy = next_tick = time.monotonic() + previous_time = None + last_action_time = start + last_frame_time = -math.inf + while time.monotonic() - start < args.duration: + tick = time.monotonic() + measured = mapping.positions(robot.bus.sync_read("Present_Position")) + sample_time = time.monotonic() + if args.execute: + mapping.require_in_limits(measured) + velocity = ( + np.zeros(6) if previous_time is None else (measured - previous) / max(sample_time - previous_time, 1e-6) + ) + action = worker.poll() + if action is not None: + state.commit(action) + last_action_time = time.monotonic() + timings.append(1000 * (last_action_time - worker.started)) + if args.trace: + actions.append(state.action.copy()) + if tick >= next_policy and worker.future is None: + stamp, image = camera.timestamped_frame() + if stamp > last_frame_time: + if not args.execute: + target = mapping.positions(robot.bus.sync_read("Goal_Position")) + observation = state.observation(measured, velocity, target) + worker.submit(observation, image, stamp) + last_frame_time = stamp + next_policy, skipped = advance_policy_deadline(next_policy, tick) + policy_missed += skipped + if args.trace: + inputs.append(observation) + images.append(image.copy()) + if time.monotonic() - last_action_time > 0.1 or time.monotonic() - tick > 0.1: + raise RuntimeError("Control/inference deadline exceeded; refusing a stale command") + target = state.target(measured, mapping.limits) + if args.execute: + sent = robot.send_action(mapping.commands(target)) + target = mapping.positions({name: sent[f"{name}.pos"] for name in JOINTS}) + previous, previous_time = measured, sample_time + if args.trace: + traces.append(np.concatenate(([tick - start], measured, target, state.action))) + next_tick += 1 / 120 + remaining = next_tick - time.monotonic() + if remaining > 0: + time.sleep(remaining) + else: + missed += 1 + next_tick = time.monotonic() + finally: + # Release motors before waiting for any capture/inference thread. + try: + if robot.bus.is_connected: + if configured: + finish_motor_control(robot, hold=False) + else: + robot.bus.disconnect(disable_torque=False) + finally: + try: + camera.close() + finally: + worker.close() + if args.trace: + args.trace.parent.mkdir(parents=True, exist_ok=True) + with args.trace.open("xb") as handle: + np.savez_compressed( + handle, + steps=np.asarray(traces), + proprio=np.asarray(inputs), + actions=np.asarray(actions), + rgb=np.asarray(images), + metadata=json.dumps( + dict( + contract=runtime.contract, + joint_map=map_data, + execute=args.execute, + ) + ), + ) + print( + json.dumps( + dict( + execute=args.execute, + missed_control_deadlines=missed, + missed_policy_deadlines=policy_missed, + inference_ms_p50_p95=np.percentile(timings, [50, 95]).tolist() if timings else [], + ), + indent=2, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/src/isaaclab_tutorial/active_gaze/deployment/runtime.py b/src/isaaclab_tutorial/active_gaze/deployment/runtime.py new file mode 100644 index 0000000..be2f715 --- /dev/null +++ b/src/isaaclab_tutorial/active_gaze/deployment/runtime.py @@ -0,0 +1,88 @@ +"""Validated portable bundle loading and one in-flight inference worker.""" + +import hashlib +import json +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import numpy as np +import torch + +from .control import validate_contract + + +class PolicyRuntime: + def __init__(self, bundle: Path, device="cuda:0", *, retinal=False): + from leapp import InferenceManager + + torch._C._jit_set_autocast_mode(False) + self.bundle = bundle.resolve() + self.contract = json.loads((self.bundle / "contract.json").read_text()) + validate_contract(self.contract) + for name, digest in self.contract["files"].items(): + path = (self.bundle / name).resolve() + if not path.is_relative_to(self.bundle) or hashlib.sha256(path.read_bytes()).hexdigest() != digest: + raise ValueError(f"Bundle integrity check failed: {name}") + self.device = torch.device(device) + if str(self.device) != "cuda:0": + raise ValueError("Use cuda:0 and select the physical GPU with CUDA_VISIBLE_DEVICES") + self.retinal = retinal + self.image_key = "retinal_rgb" if retinal else "rgb" + size = [128, 128] if retinal else self.contract["camera_calibration"]["image_size"] + self.image_shape = (1, *size, 3) + graph = self.bundle / self.contract["retinal_graph" if retinal else "camera_graph"] + if self.device.type == "cuda": + torch.cuda.set_device(self.device) + self.runtime = InferenceManager(str(graph)) + + @torch.inference_mode() + def infer(self, proprio, rgb): + proprio = torch.as_tensor(proprio, device=self.device, dtype=torch.float32).reshape(1, -1) + image = torch.as_tensor(rgb, device=self.device) + if image.ndim == 3: + image = image.unsqueeze(0) + if image.shape != self.image_shape or image.dtype != torch.uint8: + raise ValueError(f"Expected uint8 RGB {self.image_shape}; never resize an uncalibrated image") + if proprio.shape != (1, 32) or not torch.isfinite(proprio).all(): + raise ValueError("Expected 32 finite proprioceptive values") + # The profiling executor misoptimizes the traced BF16 DINO graph after + # warmup on PyTorch 2.11. Preserve the validated eager-trace numerics. + with torch.jit.optimized_execution(False): + action = self.runtime.run_policy({"policy/proprio": proprio, f"policy/{self.image_key}": image})[ + "policy/action" + ] + result = action.detach().float().cpu().numpy() + if result.shape != (1, 8) or not np.isfinite(result).all(): + raise ValueError("Invalid policy action") + return result[0] + + +class InferenceWorker: + """Inference owns no motor or gaze state; control commits completed results.""" + + def __init__(self, runtime): + self.runtime = runtime + self.executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="so101-inference") + self.future = None + + def submit(self, proprio, image, frame_time): + if self.future is not None: + raise RuntimeError("An inference is already in flight") + self.started = time.monotonic() + self.frame_time = frame_time + self.future = self.executor.submit(self.runtime.infer, proprio.copy(), image.copy()) + + def poll(self, max_age=0.1): + if self.future is None: + return None + if time.monotonic() - min(self.started, self.frame_time) > max_age: + raise RuntimeError("Inference/camera result is stale; refusing a stale command") + if not self.future.done(): + return None + result = self.future.result() + self.future = None + return result + + def close(self): + self.executor.shutdown(wait=True, cancel_futures=True) diff --git a/tests/active_gaze/test_deployment.py b/tests/active_gaze/test_deployment.py new file mode 100644 index 0000000..2279ef3 --- /dev/null +++ b/tests/active_gaze/test_deployment.py @@ -0,0 +1,279 @@ +"""Deployment geometry, action-state transitions, and delayed-result handling.""" + +import time + +import numpy as np +import pytest +import torch + +from isaaclab_tutorial.active_gaze.deployment.control import ( + JOINTS, + PROPRIOCEPTION, + PolicyState, + advance_policy_deadline, +) +from isaaclab_tutorial.active_gaze.deployment.retina import SoftwareRetina, nominal_calibration +from isaaclab_tutorial.active_gaze.deployment.runtime import InferenceWorker + + +def contract(): + return dict( + format="isaaclab_fovi.so101.leapp.v1", + joint_order=list(JOINTS), + joint_units="radians", + proprioception=list(PROPRIOCEPTION), + policy_hz=30, + relative_target_hz=120, + action_scale=[0.033] * 5 + [0.02], + gaze_limit=0.66, + gaze_max_delta=0.12, + ) + + +def test_state_matches_motor_and_gaze_timing_and_reset(): + state = PolicyState(contract()) + state.reset([0.65, -0.65]) + state.commit([2, 0, 0, 0, 0, -2, 1, -1]) + np.testing.assert_allclose(state.gaze, [0.66, -0.66]) + np.testing.assert_allclose(state.gaze_velocity, [0.3, -0.3], atol=1e-5) + observed = state.observation(np.ones(6), np.ones(6) * 13, np.ones(6) * 2) + np.testing.assert_array_equal(observed[6:12], [13] * 6) + np.testing.assert_array_equal(observed[18:26], state.action) + np.testing.assert_array_equal(observed[26:28], observed[30:32]) + limits = np.array([[-4, 4]] * 6) + first = state.target(np.zeros(6), limits) + second = state.target(np.ones(6), limits) + np.testing.assert_allclose(second - first, np.ones(6)) + state.reset() + np.testing.assert_array_equal(state.observation(np.zeros(6), np.zeros(6), np.zeros(6)), np.zeros(32)) + with pytest.raises(ValueError): + state.commit([float("nan")] * 8) + with pytest.raises(ValueError): + state.reset([0.8, 0]) + + +def test_policy_clock_preserves_rate_with_bus_jitter_and_skips_missed_periods(): + deadline, ticks = 0.0, [] + for index in range(1200): + now = index / 120 + (index % 7) * 0.00003 + if now >= deadline: + deadline, missed = advance_policy_deadline(deadline, now) + assert missed == 0 + ticks.append(now) + assert len(ticks) == 300 + assert deadline == pytest.approx(10) + deadline, missed = advance_policy_deadline(1, 1.11) + assert deadline > 1.11 + assert missed == 3 + + +def test_dense_sampling_orientation_calibration_and_visibility_match_sensor(): + from fovi.sensing.projection import gaze_rotation + + from isaaclab_fovi.sensors.calibrated_geometry import calibrated_visibility + + retina = SoftwareRetina(nominal_calibration(78), 78, 0.0075) + yy, xx = torch.meshgrid(torch.arange(640), torch.arange(640), indexing="ij") + rgb = torch.stack((xx / 3, yy / 3, torch.full_like(xx, 100)), -1).to(torch.uint8)[None] + gaze = torch.tensor([[0.0, 0.0], [0.3, -0.4]]) + grid, valid = retina.grid(gaze) + image = retina(rgb.expand(2, -1, -1, -1), gaze) + assert image.shape == (2, 128, 128, 3) + # Upright public raster: right means larger source x, down means larger source y. + assert image[0, 64, 80, 0] > image[0, 64, 48, 0] + assert image[0, 80, 64, 1] > image[0, 48, 64, 1] + assert image[1, 64, 64, 0] > image[0, 64, 64, 0] + assert image[1, 64, 64, 1] < image[0, 64, 64, 1] + assert (image[~valid.expand_as(image)] == 0).all() + tilt, pan = gaze.unbind(-1) + direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) + reference = calibrated_visibility(retina.camera, retina.rays, gaze_rotation(direction, "pan_tilt")) + assert torch.equal(valid, reference.reshape_as(valid) & retina.valid) + assert torch.isfinite(grid).all() + + +def test_worker_does_not_accept_stale_or_overlapping_results(): + class Runtime: + def infer(self, proprio, rgb): + return np.arange(8, dtype=np.float32) + + worker = InferenceWorker(Runtime()) + try: + worker.submit(np.zeros(32), np.zeros((2, 2, 3)), time.monotonic() - 1) + with pytest.raises(RuntimeError, match="already"): + worker.submit(np.zeros(32), np.zeros((2, 2, 3)), time.monotonic()) + with pytest.raises(RuntimeError, match="stale"): + worker.poll() + finally: + worker.close() + + +@pytest.mark.parametrize("execute,fail", [(False, False), (True, False), (True, True)]) +@pytest.mark.parametrize("planar", [False, True]) +def test_hardware_adapter_read_only_startup_and_error_shutdown(tmp_path, monkeypatch, execute, fail, planar): + import hashlib + import json + import sys + from types import ModuleType, SimpleNamespace + + from isaaclab_tutorial.active_gaze.deployment import run + + clock = SimpleNamespace(now=0.0) + monkeypatch.setattr(run.time, "monotonic", lambda: clock.now) + monkeypatch.setattr(run.time, "sleep", lambda delay: setattr(clock, "now", clock.now + delay)) + calls, observations = [], [] + position = np.full(6, 0.2) + + class Bus: + is_connected = False + + def connect(self): + self.is_connected = True + + def sync_read(self, name, **kwargs): + clock.now += 0.001 + return dict(zip(JOINTS, position.tolist(), strict=True)) + + def sync_write(self, name, value, **kwargs): + calls.append(("write", name, value)) + + def disable_torque(self): + calls.append(("disable",)) + + def disconnect(self, disable_torque): + calls.append(("disconnect", disable_torque)) + self.is_connected = False + + calibration = tmp_path / "calibration.json" + calibration.write_text("{}") + + class Robot: + def __init__(self, cfg): + self.bus = Bus() + self.is_calibrated = True + self.calibration_fpath = calibration + self.calibration = {n: SimpleNamespace(range_min=0, range_max=4095) for n in JOINTS} + + def configure(self): + calls.append(("configure",)) + + def send_action(self, action): + calls.append(("action", action)) + return action + + module = ModuleType("lerobot.robots.so_follower") + module.SO101Follower, module.SO101FollowerConfig = Robot, lambda **kwargs: kwargs + monkeypatch.setitem(sys.modules, "lerobot.robots.so_follower", module) + + class Runtime: + def __init__(self, *args): + self.contract = dict( + contract(), + camera_calibration={"image_size": [2, 2]}, + calibrated_capture=not planar, + retinal_geometry="planar" if planar else "spherical", + ) + + def infer(self, *args): + clock.now += 2 # Long warmup while someone moves the arm. + position[:] = 0.3 + return np.zeros(8) + + class Camera: + latest, error = True, None + + def __init__(self, *args): + pass + + def timestamped_frame(self): + return clock.now, np.zeros((2, 2, 3), dtype=np.uint8) + + def close(self): + calls.append(("camera_close",)) + + class Worker: + future = None + + def __init__(self, *args): + pass + + def poll(self): + if self.future is None: + return None + if fail: + raise RuntimeError("stale inference") + self.future = None + return np.zeros(8) + + def submit(self, proprio, image, stamp): + observations.append(proprio.copy()) + self.future, self.started = True, stamp + + def close(self): + calls.append(("worker_close",)) + + monkeypatch.setattr(run, "PolicyRuntime", Runtime) + monkeypatch.setattr(run, "SceneCamera", Camera) + monkeypatch.setattr(run, "InferenceWorker", Worker) + mapping = tmp_path / "map.json" + mapping.write_text( + json.dumps( + dict( + units="lerobot_degrees_and_gripper_percent", + verified=True, + calibration_sha256=hashlib.sha256(calibration.read_bytes()).hexdigest(), + joints={n: dict(scale=1, offset=0, limits=[-4, 4]) for n in JOINTS}, + ) + ) + ) + start = tmp_path / "start.json" + start.write_text(json.dumps(dict(position=[0.2] * 6, tolerance_rad=0.5))) + argv = [ + "run", + "--bundle", + str(tmp_path), + "--joint-map", + str(mapping), + "--port", + "fake", + "--duration", + "0.15", + ] + if execute: + argv += ["--execute", "--start-pose", str(start)] + monkeypatch.setattr(sys, "argv", argv) + if fail: + with pytest.raises(RuntimeError, match="stale"): + run.main() + else: + run.main() + np.testing.assert_array_equal(observations[0][6:12], np.zeros(6)) + if execute: + np.testing.assert_allclose(observations[0][12:18], [0.3] * 6) + names = [call[0] for call in calls] + assert names.index("write") < names.index("configure") < names.index("disconnect") + seeded = next(call[2] for call in calls if call[0] == "write") + assert list(seeded.values()) == pytest.approx([0.3] * 6) + assert ("disconnect", True) in calls + else: + assert not any(call[0] in ("write", "disable", "configure", "action") for call in calls) + assert ("disconnect", False) in calls + assert next(i for i, call in enumerate(calls) if call[0] == "disconnect") < calls.index(("worker_close",)) + + +def test_export_rejects_chunked_actor_before_loading_weights(tmp_path): + import json + + from isaaclab_tutorial.active_gaze.deployment.model import load_policy + + (tmp_path / "example.json").write_text(json.dumps({"policy": {"name": "dino_language"}, "resolution": 128})) + (tmp_path / "agent.json").write_text( + json.dumps( + { + "obs_groups": {"actor": ["proprio", "vision", "instruction"]}, + "algorithm": {"action_chunk_size": 4}, + } + ) + ) + with pytest.raises(ValueError, match="single-step actions"): + load_policy(tmp_path / "model.pt", "unused", {}, "cpu") diff --git a/tests/active_gaze/test_hardware.py b/tests/active_gaze/test_hardware.py new file mode 100644 index 0000000..3b1af79 --- /dev/null +++ b/tests/active_gaze/test_hardware.py @@ -0,0 +1,86 @@ +"""Hardware unit conversions, travel checks, and torque shutdown without a robot.""" + +from types import SimpleNamespace + +import numpy as np +import pytest + +from isaaclab_tutorial.active_gaze.deployment.control import JOINTS +from isaaclab_tutorial.active_gaze.deployment.hardware import JointMap, require_start_pose + +pytestmark = pytest.mark.kitless + + +def mapping(): + return JointMap( + { + "units": "lerobot_degrees_and_gripper_percent", + "verified": False, + "joints": {name: {"scale": -0.02, "offset": 0.1, "limits": [-1, 1]} for name in JOINTS}, + } + ) + + +def test_joint_mapping_roundtrip_negative_direction_and_limits(): + m = mapping() + native = dict.fromkeys(JOINTS, 4.0) + commands = m.commands(m.positions(native)) + np.testing.assert_allclose(list(commands.values()), [4] * 6) + clipped = m.commands(np.full(6, 2.0)) + np.testing.assert_allclose(m.positions({name: clipped[f"{name}.pos"] for name in JOINTS}), [1] * 6) + with pytest.raises(ValueError, match="finite"): + m.commands(np.full(6, np.nan)) + + +def test_execution_rejects_pose_outside_common_travel_before_clipping(): + m = mapping() + m.require_in_limits(np.zeros(6)) + measured = np.zeros(6) + measured[2] = 1.2 + with pytest.raises(ValueError, match="elbow_flex"): + m.require_in_limits(measured) + with pytest.raises(ValueError, match="Measured pose"): + m.require_in_limits(np.full(6, np.nan)) + + +def test_start_pose_rejects_wrong_home_and_invalid_reference(): + reference = {"position": [0.1] * 6, "tolerance_rad": 0.035} + require_start_pose(np.full(6, 0.12), reference) + with pytest.raises(ValueError, match="home pose"): + require_start_pose(np.zeros(6), reference) + with pytest.raises(ValueError, match="home pose"): + require_start_pose(np.full(6, np.nan), reference) + with pytest.raises(ValueError, match="reference"): + require_start_pose(np.zeros(6), {"position": [0] * 5, "tolerance_rad": 0.1}) + + +@pytest.mark.parametrize("hold", [False, True]) +def test_diagnostic_stop_holds_measured_raw_position_only_when_requested(hold): + from unittest.mock import Mock + + from isaaclab_tutorial.active_gaze.deployment.hardware import finish_motor_control + + robot = SimpleNamespace(bus=Mock()) + position = {name: 2048 for name in JOINTS} + robot.bus.sync_read.return_value = position + finish_motor_control(robot, hold=hold) + if hold: + robot.bus.sync_read.assert_called_once_with("Present_Position", normalize=False) + robot.bus.sync_write.assert_called_once_with("Goal_Position", position, normalize=False) + else: + robot.bus.sync_read.assert_not_called() + robot.bus.sync_write.assert_not_called() + robot.bus.disconnect.assert_called_once_with(disable_torque=not hold) + + +@pytest.mark.parametrize("operation", ["sync_read", "sync_write"]) +def test_diagnostic_hold_failure_releases_torque(operation): + from unittest.mock import Mock + + from isaaclab_tutorial.active_gaze.deployment.hardware import finish_motor_control + + robot = SimpleNamespace(bus=Mock()) + getattr(robot.bus, operation).side_effect = RuntimeError("Bus failed") + with pytest.raises(RuntimeError, match="Bus failed"): + finish_motor_control(robot, hold=True) + robot.bus.disconnect.assert_called_once_with(disable_torque=True) From 6fec14dc9384ed3462e6170be29c21919ab8c321 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:51:42 -0800 Subject: [PATCH 08/30] Build Isaac Lab from its pull request ref and lock the fovi extra Isaac Lab now comes from refs/pull/9074/head of isaac-sim/IsaacLab, which reviewers can see and which carries upstream's Git LFS objects. Isaac Lab main requires pre-release hydra-core and omegaconf, so pre-releases are allowed as in Isaac Lab itself. uv.lock is regenerated. Isaac Lab main references a Git LFS object its server does not have (docs/source/_static/actuators/delay-clip.webp, from isaac-sim/IsaacLab#6839); until that is fixed, install with GIT_LFS_SKIP_SMUDGE=1. --- pyproject.toml | 8 +- uv.lock | 1377 +++++++++++++++++++++++++++++------------------- 2 files changed, 836 insertions(+), 549 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c718166..aaa256f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,12 +43,14 @@ dev = ["codespell>=2.4", "pre-commit>=4.2", "pytest>=8.3", "ruff>=0.11"] [tool.uv] # Isaac Lab pins transformers 5.10.4; the ActiveGaze language encoder (Cosmos3-Edge) first ships in 5.19.0. override-dependencies = ["transformers==5.19.0"] +# Isaac Lab main requires pre-release hydra-core and omegaconf, and allows pre-releases the same way. +prerelease = "allow" environments =["sys_platform == 'linux' and platform_machine == 'x86_64'", "sys_platform == 'win32' and platform_machine == 'AMD64'", "sys_platform == 'linux' and platform_machine == 'aarch64'"] [tool.uv.sources] -# The ActiveGaze task needs isaaclab_fovi, which is under review in Isaac Lab. Until it merges, the tutorial builds -# Isaac Lab from that pull request's branch. -isaaclab = { git = "https://github.com/nblauch/IsaacLab.git", branch = "feat/isaaclab-fovi-sensors", subdirectory = "tools/wheel_builder" } +# The ActiveGaze task needs isaaclab_fovi, which is under review in Isaac Lab (isaac-sim/IsaacLab#9074). Until it +# merges, the tutorial builds Isaac Lab from that pull request. +isaaclab = { git = "https://github.com/isaac-sim/IsaacLab.git", rev = "refs/pull/9074/head", subdirectory = "tools/wheel_builder" } ovphysx = { index = "nvidia" } ovrtx = { index = "nvidia" } torch = { index = "pytorch-cu130" } diff --git a/uv.lock b/uv.lock index 4fbe63f..41db44e 100644 --- a/uv.lock +++ b/uv.lock @@ -12,6 +12,12 @@ supported-markers = [ "platform_machine == 'aarch64' and sys_platform == 'linux'", ] +[options] +prerelease-mode = "allow" + +[manifest] +overrides = [{ name = "transformers", specifier = "==5.19.0" }] + [[package]] name = "absl-py" version = "2.5.0" @@ -35,14 +41,14 @@ name = "alphashape" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "click" }, - { name = "click-log" }, - { name = "networkx" }, - { name = "numpy" }, - { name = "rtree" }, - { name = "scipy" }, - { name = "shapely" }, - { name = "trimesh" }, + { name = "click", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "click-log", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "networkx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "rtree", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "scipy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "shapely", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "trimesh", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/2e/83/67ff905694df5b34a777123b59fdfd05998d5a31766f188aafbf5b340055/alphashape-1.3.1.tar.gz", hash = "sha256:7a27340afc5f8ed301577acec46bb0cf2bada5410045f7289142e735ef6977ec", size = 26316, upload-time = "2021-04-16T17:47:19.486Z" } wheels = [ @@ -67,25 +73,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, ] -[[package]] -name = "antlr4-python3-runtime" -version = "4.9.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/3e/38/7859ff46355f76f8d19459005ca000b6e7012f2f1ca597746cbcd1fbfe5e/antlr4-python3-runtime-4.9.3.tar.gz", hash = "sha256:f224469b4168294902bb1efa80a8bf7855f24c99aef99cbefc1bcd3cce77881b", size = 117034, upload-time = "2021-11-06T17:52:23.524Z" } - [[package]] name = "anyio" version = "4.15.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "idna" }, - { name = "typing-extensions" }, + { name = "idna", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ea/9a/c15a60547004a3f3cea20296c934f827ddd7bdba225a2e7e9fcb5ec48c80/anyio-4.15.0.tar.gz", hash = "sha256:b5c620ed540725e2579c31b17bb995b3bf02c9281c9cace04c7d186380bab85e", size = 276504, upload-time = "2026-09-02T21:46:36.957Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/21/a6/2b21ce5ebe4d8938a247c9b0dbb7271566ae559b01795c83ea4bb2660ed7/anyio-4.15.0-py3-none-any.whl", hash = "sha256:7ecd9937369ffce8bba0b5ccb9b3a9507b101b0ed50256aecfbab27e6c2acb99", size = 131908, upload-time = "2026-09-02T21:46:35.485Z" }, ] +[[package]] +name = "asttokens" +version = "3.0.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/25/1e/faf0f247f6f881b98fc4d6d07e14085cb89d13665084e6d6ac1dc2c03d0b/asttokens-3.0.2.tar.gz", hash = "sha256:3ecdbd8f2cc195f53ccada3a613538bb5f9ef6f6869129f13e03c30a677b8fe2", size = 63136, upload-time = "2026-07-12T03:31:49.084Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/2b/04b8a15f3a1c77bc79ddf5c73875327f34b4fa75982df2b76e45e402d364/asttokens-3.0.2-py3-none-any.whl", hash = "sha256:9da13157f5b28becde0bd374fc677dcd3c290614264eff096f167c469cd9f933", size = 28702, upload-time = "2026-07-12T03:31:47.542Z" }, +] + [[package]] name = "attrs" version = "26.1.0" @@ -95,6 +104,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, ] +[[package]] +name = "beartype" +version = "0.23.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/79/34/c0cfdaee9c796c8381439fed0fcab62810753b8b0adb1ec88fa7f41eaa5d/beartype-0.23.1.tar.gz", hash = "sha256:8b805f246b32931c74f2b321ea0939fe5bb2ff43c12a3eff19cc4c854b832e1d", size = 1993714, upload-time = "2026-10-11T05:36:55.251Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1c/cb/2f6aa982e2860c1156830db3da7f823b71784ed7d533ca289ea9b6c6347a/beartype-0.23.1-py3-none-any.whl", hash = "sha256:4461b4dc57e3fdd6c8a8464b22cf118002eea107c33e9fef651c69068ab3cce3", size = 1582101, upload-time = "2026-10-11T05:36:52.431Z" }, +] + [[package]] name = "blinker" version = "1.9.0" @@ -109,9 +127,9 @@ name = "botocore" version = "1.43.88" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "jmespath" }, - { name = "python-dateutil" }, - { name = "urllib3" }, + { name = "jmespath", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "python-dateutil", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "urllib3", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/49/16/8944ffdbd6df92c463b77e933bae41a46fb1ec903c48a286e855761ce115/botocore-1.43.88.tar.gz", hash = "sha256:3c8a6e2292f05c590c5d5299934dd23c81d19a2b6dd70b9eb724f79bd432d04f", size = 16072325, upload-time = "2026-09-03T19:24:01.045Z" } wheels = [ @@ -143,13 +161,29 @@ source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/e5/3f/143b048436775b0f76ac3eec145c019e8173ccc2885c8f20319b996d5e83/charset_normalizer-3.5.1.tar.gz", hash = "sha256:6117b84ea48435e5356dc737f5121485c30920ba43375fa7b434fd753df0eac3", size = 171764, upload-time = "2026-08-15T08:20:44.807Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/9a/4c/be49ada26b1f0232d57aa89bbebf997a5cc2332a5616b6eca26ff680044d/charset_normalizer-3.5.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4582c27e8c889d64811987b5967fbd3ae0c823fe1fd933b543d55ac20bb475fa", size = 238530, upload-time = "2026-08-15T08:17:11.563Z" }, + { url = "https://files.pythonhosted.org/packages/76/84/6f1290fa07ae6978d3960caa3eb1b8019bf9284ab7c2297b00c099ef4250/charset_normalizer-3.5.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1d1c7a53a6c2103925cdd6d7229f8c567379f211c869793df679f2e9f738c369", size = 230200, upload-time = "2026-08-15T08:17:12.919Z" }, + { url = "https://files.pythonhosted.org/packages/e7/a0/47b18adeed31c8f16ba9700f32c1b18594cfa09f47eb672a488c273c22bf/charset_normalizer-3.5.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e6621fb2a4988d6e53eedc455e5903e2679f3967b8acb3d639f1b63c14a2e893", size = 262222, upload-time = "2026-08-15T08:17:14.571Z" }, + { url = "https://files.pythonhosted.org/packages/38/fe/341861ac118dae06f3ec0eb487488af52128f2ef2faf0b11003944d22259/charset_normalizer-3.5.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7c0c10730342b0c9b35dd1d619beb8214e520bd96a1f870f452680b238aab3e0", size = 258951, upload-time = "2026-08-15T08:17:16.158Z" }, { url = "https://files.pythonhosted.org/packages/6f/89/bb5108dc6c3651dca963f2b0a3ba19bbcb370c94e1b6d3e0e844a58e6dca/charset_normalizer-3.5.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b9af956078716df40d985fb0dfeb2c2120c5ca92ba4ff4b388acfd01cdc14d08", size = 248801, upload-time = "2026-08-15T08:17:17.683Z" }, + { url = "https://files.pythonhosted.org/packages/b1/ba/ef83ae3aca816393decfa3530976f38a79812d707b80b580ac33b83f9877/charset_normalizer-3.5.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f9f8405c2c758532c74fed975dbee57be1f31a6e865c031870c79a6ed3212ada", size = 244070, upload-time = "2026-08-15T08:17:19.191Z" }, { url = "https://files.pythonhosted.org/packages/f6/0b/c5292a2462d69b7378ea89793bbb5b2b6fcf6f7dd6d1667f9619094ad553/charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:96fef3e886d6a9874b14f27fc193fbdc69d5d8035783d86aa4e1cea594e695f9", size = 240110, upload-time = "2026-08-15T08:17:20.547Z" }, + { url = "https://files.pythonhosted.org/packages/46/22/111e5be3b740d5c2a5bfcedb3d237b6591e5c2e82ae9d6ffcb121fe0909c/charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:5d8531a6569d025f68e2321e7638fb7978f23db58e5f69f56913837aae03816e", size = 232836, upload-time = "2026-08-15T08:17:21.895Z" }, + { url = "https://files.pythonhosted.org/packages/f9/d2/d2aad6fe0dbb44b194bf3becb60f5a0ac48446ade999a47fe7bb41eb09a7/charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:aae2ee51122d3ae968a3837d97dc24a0aeebb0dea23694422cd172bd30017cd6", size = 262712, upload-time = "2026-08-15T08:17:23.727Z" }, + { url = "https://files.pythonhosted.org/packages/35/5a/337e4663a5eae6de99db940ee8066d4145caafb61327db62deda15313cce/charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:7235dc28fc6dd9d832ac7c7bce95367dedb85929f17368a0c2bee1e080b9acbf", size = 242977, upload-time = "2026-08-15T08:17:25.157Z" }, + { url = "https://files.pythonhosted.org/packages/ca/85/f82f8a92e31c7519410e2e1afdc630f28ec47490ce2c09a11c1a43cbb459/charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:4abdc5f9ad448c1ecbfae2974b820535d6bc6e7eef63babbab3d81cf46968c71", size = 260207, upload-time = "2026-08-15T08:17:26.602Z" }, { url = "https://files.pythonhosted.org/packages/b7/52/643d11ffd60e9ac2fd1fb87e167a19285b9eefeff4a40e63c87cbfbeab36/charset_normalizer-3.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ba501e667c17d8411f98e67a022d9604ef179aff0e459b7e292c796837c13573", size = 250562, upload-time = "2026-08-15T08:17:27.971Z" }, { url = "https://files.pythonhosted.org/packages/9d/7a/4c6c298171e6b3e745633180ff59350fc0ca0db1ffd28df1e369e0579f71/charset_normalizer-3.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:3617ac3cfd8b9888f145ad89dd6e692285834b0201c6074a5eeaad3fd4d668c2", size = 200551, upload-time = "2026-08-15T08:17:30.668Z" }, { url = "https://files.pythonhosted.org/packages/9f/2f/fe3f187327aac18e2d54e9d2b08e15d27bf9b642d9e51c219f130fc34d1a/charset_normalizer-3.5.1-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a6dac12ff6b846103483683f60c5f8fee205121adc58ffd87e90a90a3af69e99", size = 253057, upload-time = "2026-08-15T08:19:52.654Z" }, { url = "https://files.pythonhosted.org/packages/d7/c7/9e48cee5c161fe24da823b61bf381921d77cb994a0a4de148e95018c1984/charset_normalizer-3.5.1-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cee5dd7c6fb5dd52a0fe2a740f9bc6e3593f5f8b1788bde49de02086f30182b2", size = 240930, upload-time = "2026-08-15T08:19:54.163Z" }, + { url = "https://files.pythonhosted.org/packages/49/e0/716601f3cc69be7b198951150c75ead1ece33c3c8036ff6ffa46029659a0/charset_normalizer-3.5.1-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:343fb4f2821043bd87095f7b08a1a181febc8e36ac64212143bbfd0a0e1bc235", size = 230822, upload-time = "2026-08-15T08:19:55.807Z" }, + { url = "https://files.pythonhosted.org/packages/d3/05/71bfc5caa0abcc45aea1f6a4d50ac68e59605ddc7666fe8494f4cd229665/charset_normalizer-3.5.1-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ae4a097991662cd4fff0ddc74e0fe7874f82e00042fa0ea00855645ed0c79598", size = 260037, upload-time = "2026-08-15T08:19:57.312Z" }, + { url = "https://files.pythonhosted.org/packages/c3/92/de7e32ed05341e7a9c4c877c318418197b7f2d66a3b68d561bf2ac57ca3e/charset_normalizer-3.5.1-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4b599739b93b2cbeded49645ae3c8d1405c29ddfbceac1545c87a3f9580a9e96", size = 255097, upload-time = "2026-08-15T08:19:59.056Z" }, + { url = "https://files.pythonhosted.org/packages/f5/7b/ade0a122600319dfa0b1000ab0f9731c94a817904cf3c5de408c73a4ede7/charset_normalizer-3.5.1-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b39b69b347e5e47a3b5b8cfc005c68c1ba347474e3960236c4944a8ecd174962", size = 250166, upload-time = "2026-08-15T08:20:00.612Z" }, { url = "https://files.pythonhosted.org/packages/75/9c/019fbb9f4834491a160951349b1a3714439376f66e5f7cf18b4f18f0c7aa/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a2028475ba855475b8b4d3cfeb4994269c967aea8b9892dfba907f4263a863a3", size = 241821, upload-time = "2026-08-15T08:20:02.321Z" }, + { url = "https://files.pythonhosted.org/packages/2b/b8/11d4840bfc99330cc7fbcc2681ee5a044553a6e77655508d8f9b2bff7b34/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:36047af20e17097c3bb9476c2b7655f2f7aa51322c0ba58c07695bedf755a950", size = 232529, upload-time = "2026-08-15T08:20:04.008Z" }, + { url = "https://files.pythonhosted.org/packages/18/96/2b3a21492d9f65171ac75d872f5018260013d00bfa0ff70ec9f179148cbd/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:4c4fb141a727957c93edfe5c32a26ceb6b5f6461d67146e2d39f51e16170bea8", size = 260348, upload-time = "2026-08-15T08:20:05.877Z" }, + { url = "https://files.pythonhosted.org/packages/d6/aa/a69a2028e8bd052476c245460ab19d7de595de084dd968f2d75cd50c3e25/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:2f293479cce755c75f1697e87c409b7ae4c555c7dfecb6e988ad13abba943031", size = 247234, upload-time = "2026-08-15T08:20:07.487Z" }, + { url = "https://files.pythonhosted.org/packages/35/8a/3d130aeabcaf3d2466af76b7b141c08d9e89c9016ab4b7cdd0f7dc2d1c62/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:3588e376b3ea2eea84976f67273d679f229e24c66dce7b82ae45aef04ff6e072", size = 256917, upload-time = "2026-08-15T08:20:09.142Z" }, { url = "https://files.pythonhosted.org/packages/80/c2/a7379b840292d0c1ab9fbd17d1f3967aa81794dc95bc74be8999d7fedcf7/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e199fb99720074809a7720f1c0b4d919eea8b87e88713e0f8f602f7bef543d9d", size = 254846, upload-time = "2026-08-15T08:20:10.727Z" }, { url = "https://files.pythonhosted.org/packages/35/4f/b911ed898b26a09789eba9c9200c999aff6c61b4bafaf4838e56d1a1e1a3/charset_normalizer-3.5.1-cp37-abi3-win_amd64.whl", hash = "sha256:70055ff39b97c99e7ae40ea3e393fb62aa2e44dbd9b29f8d14f42fb0025c3959", size = 199764, upload-time = "2026-08-15T08:20:13.908Z" }, { url = "https://files.pythonhosted.org/packages/cc/61/d01fc49b8dea277640b55a9e15960dbca9fdc8c9fde18e572d39c59f4019/charset_normalizer-3.5.1-py3-none-any.whl", hash = "sha256:6df0ec430f9a831772c23ca5a224cba36517a58a84bb32c32bb59a9fa67c47f6", size = 68658, upload-time = "2026-08-15T08:20:43.306Z" }, @@ -169,7 +203,7 @@ name = "click-log" version = "0.4.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "click" }, + { name = "click", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/32/32/228be4f971e4bd556c33d52a22682bfe318ffe57a1ddb7a546f347a90260/click-log-0.4.0.tar.gz", hash = "sha256:3970f8570ac54491237bcdb3d8ab5e3eef6c057df29f8c3d1151a51a9c23b975", size = 9985, upload-time = "2022-03-13T11:10:15.262Z" } wheels = [ @@ -199,8 +233,8 @@ name = "cmeel-assimp" version = "6.0.5" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, - { name = "cmeel-zlib" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-zlib", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/77/37/11de8f263a5cde3cde4796e344ff034674bdbb7a2381f6b5303d49b24def/cmeel_assimp-6.0.5-0-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:db6fe58f8bd633cb05ab9f390c576a4e774927ed8c343083fad4f939e834bf6e", size = 13709230, upload-time = "2026-05-20T16:36:25.497Z" }, @@ -212,8 +246,8 @@ name = "cmeel-boost" version = "1.90.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, - { name = "numpy" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/e4/01/ab2ea5b1ceae6283eb68be8beac529f294c70ac49d40b7873b0b639a7784/cmeel_boost-1.90.0.tar.gz", hash = "sha256:747d6d932838df26f50cdcb5983fa7532cad1d9ccce46c9f9d8b27b20a115981", size = 4085, upload-time = "2026-05-20T15:19:13.113Z" } wheels = [ @@ -226,7 +260,7 @@ name = "cmeel-console-bridge" version = "1.0.2.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/83/13/2e9e9d23db8548aef975564055bdb4fb6da8a397a1e7df8cb61f5afebefb/cmeel_console_bridge-1.0.2.3.tar.gz", hash = "sha256:3b2837da7ab408e9d1a775c83c0a7772356062b3a3672e4ce247f2da71a8ecd9", size = 262061, upload-time = "2025-03-19T18:22:06.845Z" } wheels = [ @@ -241,7 +275,7 @@ name = "cmeel-octomap" version = "1.10.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/89/ab/2fed2dbee13e4b39949591685419f1dbb691295e32a6bbbaf87edc005922/cmeel_octomap-1.10.0.tar.gz", hash = "sha256:bd79d1d17adede534de242e42e13ef0d9f04bdd27daf7d56c57f7c43670c9b05", size = 1694189, upload-time = "2025-01-06T17:57:05.477Z" } wheels = [ @@ -259,7 +293,7 @@ name = "cmeel-qhull" version = "8.0.2.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/51/dd/8d0bcfb18771b2ea02bf85dfbbc587c97b274496fb5419b72134eb69430b/cmeel_qhull-8.0.2.1.tar.gz", hash = "sha256:68e8d41d95f61830f2d460af1e4d760f0dbe4d46413d7c736f0ed701153ebe52", size = 1308055, upload-time = "2023-11-17T14:21:06.003Z" } wheels = [ @@ -277,7 +311,7 @@ name = "cmeel-tinyxml2" version = "11.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/9b/96/4311533fee0a364bb605b585762f04c249f47857b33548a8ea837a7eb860/cmeel_tinyxml2-11.0.0.tar.gz", hash = "sha256:85d9c7680b3369af4c6b40a0dce70bbd84aa67832755622e57eb260cd95abe40", size = 645900, upload-time = "2026-05-21T11:49:32.652Z" } wheels = [ @@ -290,9 +324,9 @@ name = "cmeel-urdfdom" version = "6.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, - { name = "cmeel-console-bridge" }, - { name = "cmeel-tinyxml2" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-console-bridge", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-tinyxml2", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/21/75/4e8aff079e98582aeeb8e752805081da0c2dea405e79bafeefb555defe9f/cmeel_urdfdom-6.0.0.tar.gz", hash = "sha256:65c0fdc6021300fc55b2d0c03ab64dedc328034a74e40498e671bc894bb1dcf7", size = 303688, upload-time = "2026-05-21T12:08:56.663Z" } wheels = [ @@ -305,7 +339,7 @@ name = "cmeel-zlib" version = "1.3.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ef/85/9c6b77d5c49b363b17ba974271d58730bd26cbe00b1c576596339bb624ea/cmeel_zlib-1.3.2.tar.gz", hash = "sha256:6e31f2956c334de9a7e19a4e4f8eed030ed8c8016c841ea57226ce8bed443712", size = 3200, upload-time = "2026-05-20T16:24:37.87Z" } wheels = [ @@ -320,7 +354,7 @@ name = "coacd" version = "1.0.14" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/d6/3e/e930a366ec69a966f1a55307b52d036d266314e2f6c58e72e212fdc09182/coacd-1.0.14-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1242941fc9d49ebcb0368c68f31c86e278b9a6f1a255d11da2f1668797e2626e", size = 2584591, upload-time = "2026-08-28T21:53:33.537Z" }, @@ -333,13 +367,13 @@ name = "coal" version = "3.0.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, - { name = "cmeel-assimp" }, - { name = "cmeel-boost" }, - { name = "cmeel-octomap" }, - { name = "cmeel-qhull" }, - { name = "eigenpy" }, - { name = "libcoal" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-assimp", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-boost", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-octomap", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-qhull", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "eigenpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "libcoal", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f0/14/8cb072a3e5fb85cac4d8d1234351ca3eb4ecf100b87901ab912ec7e5135e/coal-3.0.3.tar.gz", hash = "sha256:18660bde4021af496343646fa0a0d1bcf0be392f432641e772dc423be5075f64", size = 1464421, upload-time = "2026-05-21T12:30:20.812Z" } wheels = [ @@ -388,11 +422,13 @@ name = "contourpy" version = "1.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/d4/1c/a12359b9b2ca3a845e8f7f9ac08bdf776114eb931392fcad91743e2ea17b/contourpy-1.3.3-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92d9abc807cf7d0e047b95ca5d957cf4792fcd04e920ca70d48add15c1a90ea7", size = 332653, upload-time = "2025-07-26T12:01:24.155Z" }, + { url = "https://files.pythonhosted.org/packages/63/12/897aeebfb475b7748ea67b61e045accdfcf0d971f8a588b67108ed7f5512/contourpy-1.3.3-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b2e8faa0ed68cb29af51edd8e24798bb661eac3bd9f65420c1887b6ca89987c8", size = 379536, upload-time = "2025-07-26T12:01:25.91Z" }, + { url = "https://files.pythonhosted.org/packages/43/8a/a8c584b82deb248930ce069e71576fc09bd7174bbd35183b7943fb1064fd/contourpy-1.3.3-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:626d60935cf668e70a5ce6ff184fd713e9683fb458898e4249b63be9e28286ea", size = 384397, upload-time = "2025-07-26T12:01:27.152Z" }, { url = "https://files.pythonhosted.org/packages/cc/8f/ec6289987824b29529d0dfda0d74a07cec60e54b9c92f3c9da4c0ac732de/contourpy-1.3.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4d00e655fcef08aba35ec9610536bfe90267d7ab5ba944f7032549c55a146da1", size = 362601, upload-time = "2025-07-26T12:01:28.808Z" }, { url = "https://files.pythonhosted.org/packages/05/0a/a3fe3be3ee2dceb3e615ebb4df97ae6f3828aa915d3e10549ce016302bd1/contourpy-1.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:451e71b5a7d597379ef572de31eeb909a87246974d960049a9848c3bc6c41bf7", size = 1331288, upload-time = "2025-07-26T12:01:31.198Z" }, { url = "https://files.pythonhosted.org/packages/33/1d/acad9bd4e97f13f3e2b18a3977fe1b4a37ecf3d38d815333980c6c72e963/contourpy-1.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:459c1f020cd59fcfe6650180678a9993932d80d44ccde1fa1868977438f0b411", size = 1403386, upload-time = "2025-07-26T12:01:33.947Z" }, @@ -404,7 +440,7 @@ name = "cuda-bindings" version = "13.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cuda-pathfinder" }, + { name = "cuda-pathfinder", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/ce/67/5e7dba1ba576dd73da5dee894ca076ca5e959450dfff66d6d510a255d1f7/cuda_bindings-13.3.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c7855c4868aabc0cfae28abbe83d56734bdfbd08f08fc234ac1912a12858bf49", size = 6025351, upload-time = "2026-05-29T23:11:49.685Z" }, @@ -429,37 +465,51 @@ wheels = [ [package.optional-dependencies] cublas = [ - { name = "nvidia-cublas" }, + { name = "nvidia-cublas", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cudart = [ - { name = "nvidia-cuda-runtime" }, + { name = "nvidia-cuda-runtime", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cufft = [ - { name = "nvidia-cufft" }, + { name = "nvidia-cufft", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cufile = [ - { name = "nvidia-cufile" }, + { name = "nvidia-cufile", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cupti = [ - { name = "nvidia-cuda-cupti" }, + { name = "nvidia-cuda-cupti", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] curand = [ - { name = "nvidia-curand" }, + { name = "nvidia-curand", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cusolver = [ - { name = "nvidia-cusolver" }, + { name = "nvidia-cusolver", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cusparse = [ - { name = "nvidia-cusparse" }, + { name = "nvidia-cusparse", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] nvjitlink = [ - { name = "nvidia-nvjitlink" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] nvrtc = [ - { name = "nvidia-cuda-nvrtc" }, + { name = "nvidia-cuda-nvrtc", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] nvtx = [ - { name = "nvidia-nvtx" }, + { name = "nvidia-nvtx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, +] + +[[package]] +name = "cupy-cuda12x" +version = "14.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-pathfinder", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/d3/8c/5fe3f6719c2d4560c79c62ef6d9b7d6c34d145879ddc0c1a41f8153ad0a6/cupy_cuda12x-14.2.0-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:b74340aa7271f0f081f77e2e5107bac75af19b86df29213db7ada90e14428efe", size = 147490427, upload-time = "2026-08-20T02:40:00.196Z" }, + { url = "https://files.pythonhosted.org/packages/7c/5b/65124de2dbaf2e85109f611a41947e39acd6dd938751c04b4c4d7bf6fc82/cupy_cuda12x-14.2.0-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:f82141761f2c81905d49387464ae29438887956d99063381c93a1d5d1b7d32e8", size = 136111459, upload-time = "2026-08-20T02:40:04.909Z" }, + { url = "https://files.pythonhosted.org/packages/e9/18/ddea819204701024bef7fa748730702245d803847c841b737723b94fd091/cupy_cuda12x-14.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:c9571d3b5f2e65758137e210f7fb3c3b34767f0af6b6ca04035a244b6141ee12", size = 98780018, upload-time = "2026-08-20T02:40:09.465Z" }, ] [[package]] @@ -487,18 +537,18 @@ name = "dash" version = "4.4.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "comm" }, - { name = "flask" }, - { name = "importlib-metadata" }, - { name = "janus" }, - { name = "nest-asyncio" }, - { name = "plotly" }, - { name = "pydantic" }, - { name = "requests" }, - { name = "retrying" }, - { name = "setuptools" }, - { name = "typing-extensions" }, - { name = "werkzeug" }, + { name = "comm", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "flask", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "importlib-metadata", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "janus", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "nest-asyncio", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "plotly", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pydantic", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "requests", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "retrying", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "setuptools", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "werkzeug", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/5a/67/d5cea6dedfbfde4165436fb58154480ea6358a9e71a739d3366575b5b724/dash-4.4.1.tar.gz", hash = "sha256:9356ca7856bc496c12c5b6de5978aaf783e090d07450ee395ade1c0c2cbdf816", size = 8536482, upload-time = "2026-07-21T18:58:19.72Z" } wheels = [ @@ -528,8 +578,8 @@ name = "eigenpy" version = "3.13.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, - { name = "cmeel-boost" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-boost", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/6e/04/15aadcaf4141c791217724c3edc103cd66c5444987cb897a2e7112bb94ee/eigenpy-3.13.0.tar.gz", hash = "sha256:49d3cb46b85696baf5445ac707b48aade07c21579c188dfc1c8ad2f92e05fab5", size = 229750, upload-time = "2026-05-21T11:01:28.805Z" } wheels = [ @@ -557,9 +607,18 @@ wheels = [ [package.optional-dependencies] epath = [ - { name = "fsspec" }, - { name = "typing-extensions" }, - { name = "zipp" }, + { name = "fsspec", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "zipp", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] + +[[package]] +name = "executing" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/52/92/8a611141e42930c0f194f7504063ab87dfe970cf1a5af28e7703df448734/executing-2.3.0.tar.gz", hash = "sha256:15919cb5d667e5cb4e099511971d00d659573fff2dd5c4e6cd8b71636c7858d2", size = 1338003, upload-time = "2026-10-10T14:06:04.64Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4d/dd/8bc67e7d5ffc1d88aa5af511189dfb76dc4e1e5b808fab186146ef2663e5/executing-2.3.0-py3-none-any.whl", hash = "sha256:736e859c9f8701f11fcf516856f26f562e04776387824b43a35a1dfe21c84122", size = 29393, upload-time = "2026-10-10T14:06:02.777Z" }, ] [[package]] @@ -576,7 +635,7 @@ name = "fast-simplification" version = "0.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f3/0a/b943887803aefecd01d30cd150bd2a6f03d90b96886e3befdcc5d4276c98/fast_simplification-0.2.0.tar.gz", hash = "sha256:ed02ea6f4968ec98f963f2d3665dbafd0297ec12aea9e4d0a87c4b3c14d608a8", size = 31865, upload-time = "2026-08-12T19:53:50.49Z" } wheels = [ @@ -596,6 +655,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4a/b9/98c6cad41de1023055c5d4bae7191ef258b192a36a1d3497bc9a12777abb/fast_sugiyama-0.5.3-cp311-abi3-win_amd64.whl", hash = "sha256:a222fecca64a9db6b60dcf02fb9b3b8d69b9e9e7f592f70e830965899d612d78", size = 231425, upload-time = "2026-03-10T16:51:22.42Z" }, ] +[[package]] +name = "fastcore" +version = "2.2.44" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ff/3e/4922745d9221efe50bbc3c4e9a8e23879305ac512b89d248e9d7cb2dd86c/fastcore-2.2.44.tar.gz", hash = "sha256:65503dc894e0c75e37fd22ccfdebd2a708f911cb20bcb22983f1516e23b75850", size = 144872, upload-time = "2026-11-16T05:10:47.345Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ac/3f/2f21fb6b00d41fdcb173d10cc9c651e6d70dc3815ae34dc468e870f2fa38/fastcore-2.2.44-py3-none-any.whl", hash = "sha256:978eda3ecbdffb7b4b83b4cfaef54391b5497343138d22d6f11cf3711015222c", size = 151666, upload-time = "2026-11-16T05:10:45.813Z" }, +] + [[package]] name = "fastjsonschema" version = "2.22.2" @@ -619,12 +687,12 @@ name = "flask" version = "3.1.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "blinker" }, - { name = "click" }, - { name = "itsdangerous" }, - { name = "jinja2" }, - { name = "markupsafe" }, - { name = "werkzeug" }, + { name = "blinker", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "click", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "itsdangerous", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "jinja2", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "markupsafe", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "werkzeug", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz", hash = "sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb", size = 759004, upload-time = "2026-02-19T05:00:57.678Z" } wheels = [ @@ -653,6 +721,32 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/82/f8/7188153c4b265c899cd035de6a062677d51f67118a4ba640902bd9683e90/fonttools-4.64.0-py3-none-any.whl", hash = "sha256:4a05783ff54ce4c7a28f18e5772efdf63c219374bd9ffc55452182e1cef8be60", size = 1195327, upload-time = "2026-08-31T15:44:31.741Z" }, ] +[[package]] +name = "fovi" +version = "2.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cupy-cuda12x", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "einops", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "fastcore", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "ipython", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pillow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "plum-dispatch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pygeodesic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "scikit-image", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "scipy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "torchvision", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tqdm", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "trimesh", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "warp-lang", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9f/bc/14afdf090c412a543a939051f83a26fa50e46f407100d20707b5d34f8316/fovi-2.6.0.tar.gz", hash = "sha256:9bda8baedbd28e29c679e545dd1813e911667d3dd2c6fb1802c4a92c564d3625", size = 67577289, upload-time = "2026-11-14T18:14:09.39Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/6c/45b6d1948a23ee352ec63612e0b94a76e7dfa5427b6ff8ddc72b8864b297/fovi-2.6.0-py3-none-any.whl", hash = "sha256:d39b88f4654832b875e4197906e23043edb3dbedbb4a07798e59fd852ce0c42e", size = 312591, upload-time = "2026-11-14T18:14:07.165Z" }, +] + [[package]] name = "fsspec" version = "2026.7.0" @@ -667,7 +761,7 @@ name = "gitdb" version = "4.0.12" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "smmap" }, + { name = "smmap", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/72/94/63b0fc47eb32792c7ba1fe1b694daec9a63620db1e313033d18140c2320a/gitdb-4.0.12.tar.gz", hash = "sha256:5ef71f855d191a3326fcfbc0d5da835f26b13fbcba60c32c21091c349ffdb571", size = 394684, upload-time = "2025-01-02T07:20:46.413Z" } wheels = [ @@ -679,7 +773,7 @@ name = "gitpython" version = "3.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "gitdb" }, + { name = "gitdb", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/6e/2d/6f6e649818da44d4499604802c89329b8d9799687a124e3a5e467a643336/gitpython-3.2.0.tar.gz", hash = "sha256:fb92310af6844d96adc95ca066ed2e617c00e1dbd146a326626c81e72e18cc2e", size = 238091, upload-time = "2026-09-30T09:10:32.65Z" } wheels = [ @@ -704,10 +798,11 @@ name = "grpcio" version = "1.83.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/0c/98/304898ac4e04e2d5e4e4c2eadc178b1f2a16d5f4bc2f91306c87d64680b9/grpcio-1.83.0.tar.gz", hash = "sha256:7674587248fbbb2ac6e4eecf83a8a0f3d91a928f941de571acfd3a2f007fbc24", size = 13428824, upload-time = "2026-07-23T15:20:37.759Z" } wheels = [ + { url = "https://files.pythonhosted.org/packages/15/2b/51e32514a4e9b715375c99721aadff0f24164cc2049b8269eda4de82a814/grpcio-1.83.0-cp312-cp312-linux_armv7l.whl", hash = "sha256:28f6c35ac8fcf10e4594f138e468f194360089dde40d126a7033e863fc479930", size = 6303167, upload-time = "2026-07-23T15:19:33.78Z" }, { url = "https://files.pythonhosted.org/packages/7b/5f/734e72e7b9f79bcf0b2c270b8d3bca0e4ebb97a27a50d06240b145f6d41e/grpcio-1.83.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6fb8a1dd0c6f0f931e69e9d0dc6d1c406ed2a44fa963414eafba07b7fb685d16", size = 6869310, upload-time = "2026-07-23T15:19:38.607Z" }, { url = "https://files.pythonhosted.org/packages/b2/78/c9e81f806ac704b6b145cb01628db398985b1f8dfdc10e23b55fb0902b3d/grpcio-1.83.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeb339838db07600481ef869507279b75326c75eac6d10f7afa62a0da1d2bcdd", size = 7040616, upload-time = "2026-07-23T15:19:42.349Z" }, { url = "https://files.pythonhosted.org/packages/9a/ba/94cd5af859876049d340480acbb61a959096c84b567f215534faa78d0424/grpcio-1.83.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f47d62808b4c0a97b78bff88a6d4ca283a2a492b9a04a87d814af95ca3b9c19c", size = 7570491, upload-time = "2026-07-23T15:19:44.357Z" }, @@ -720,10 +815,10 @@ name = "gymnasium" version = "1.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cloudpickle" }, - { name = "farama-notifications" }, - { name = "numpy" }, - { name = "typing-extensions" }, + { name = "cloudpickle", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "farama-notifications", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/4d/ff/14b6880d703dfaca204490979d3254ccd280c99550798993319902873658/gymnasium-1.3.0.tar.gz", hash = "sha256:6939e86e835d6b71b6ba6bfd360487420876deafc79bfb7bacba83a7c446bcf3", size = 830646, upload-time = "2026-04-22T13:47:14.155Z" } wheels = [ @@ -744,7 +839,7 @@ name = "h5py" version = "3.16.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/db/33/acd0ce6863b6c0d7735007df01815403f5589a21ff8c2e1ee2587a38f548/h5py-3.16.0.tar.gz", hash = "sha256:a0dbaad796840ccaa67a4c144a0d0c8080073c34c76d5a6941d6818678ef2738", size = 446526, upload-time = "2026-03-06T13:49:08.07Z" } wheels = [ @@ -768,26 +863,13 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/98/b7/8c59a66d15205024662f1d66968136f13893f96df1ddc5087e2e281fc95f/hf_xet-1.6.0-cp38-abi3-win_amd64.whl", hash = "sha256:fb4fadde1b2b70bf4c0c14a6dccbe7194b1c28947fefd5bbe3fed9d940676c3b", size = 4033128, upload-time = "2026-08-03T22:33:10.171Z" }, ] -[[package]] -name = "hidapi" -version = "0.15.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/74/f6/caad9ed701fbb9223eb9e0b41a5514390769b4cb3084a2704ab69e9df0fe/hidapi-0.15.0.tar.gz", hash = "sha256:ecbc265cbe8b7b88755f421e0ba25f084091ec550c2b90ff9e8ddd4fcd540311", size = 184995, upload-time = "2025-12-09T09:48:54.129Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/de/bc/0eb92f4f238adc8edc3decb859662cf87e302b0a6ecdabe0e4d0560eb5fd/hidapi-0.15.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cfdbc74d5c4b5fdeef58a246d80f7dbf4ca33fe741c889505a4a350dd2eb54fb", size = 1082139, upload-time = "2025-12-09T09:45:32.799Z" }, - { url = "https://files.pythonhosted.org/packages/03/04/856827cfecaa89091ed470f697e3f9cfb172fc852960e6b902e765d7d650/hidapi-0.15.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:4b7b6207c1c7df3524e9d4019c7196547327636e9924010b9b0bf0c40029e329", size = 1620074, upload-time = "2025-12-09T09:45:28.573Z" }, - { url = "https://files.pythonhosted.org/packages/84/08/28ce99698e14bb6bdf9d0dcf7ab45ab86d8bade894885aa15bb3fa43bcc1/hidapi-0.15.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f9356fffebf723ccfbf0f9370d3725de37b3e2f1f6bffc40c3466f854542861c", size = 713596, upload-time = "2025-12-09T09:45:34.564Z" }, - { url = "https://files.pythonhosted.org/packages/af/ef/e2fa4d795235eb09951f806bbfdbd766d1be805df448d67918e828b7cb31/hidapi-0.15.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:35eb5797d86306bd67aee80ad8973ab0a0b4e6d54018d3efb328767d0e8c9373", size = 717599, upload-time = "2025-12-09T09:45:37.825Z" }, - { url = "https://files.pythonhosted.org/packages/7f/35/f9e2d3ead60b573140546b041dd41c78a48c0e6b573d61a03130adccd32e/hidapi-0.15.0-cp312-cp312-win_amd64.whl", hash = "sha256:9abc71a62bf8a8f1d70a6fd3613f86feb37ddb67e05ed934e734df79e27bf4f6", size = 67073, upload-time = "2025-12-09T09:45:39.261Z" }, -] - [[package]] name = "httpcore" version = "1.0.9" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "certifi" }, - { name = "h11" }, + { name = "certifi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "h11", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } wheels = [ @@ -799,10 +881,10 @@ name = "httpx" version = "0.28.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, - { name = "certifi" }, - { name = "httpcore" }, - { name = "idna" }, + { name = "anyio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "certifi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "httpcore", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "idna", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } wheels = [ @@ -814,15 +896,15 @@ name = "huggingface-hub" version = "1.33.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "click" }, - { name = "filelock" }, - { name = "fsspec" }, - { name = "hf-xet" }, - { name = "httpx" }, - { name = "packaging" }, - { name = "pyyaml" }, - { name = "tqdm" }, - { name = "typing-extensions" }, + { name = "click", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "filelock", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "fsspec", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "hf-xet", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "httpx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyyaml", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tqdm", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/25/2a/484d112c0d8fc5f665d7b65137ac9cdb2953c982391598c3597968a12ee7/huggingface_hub-1.33.0.tar.gz", hash = "sha256:367be21a201db9523eddf8aeac7048f2602c1b308691c97640d5e72ed188007e", size = 1043548, upload-time = "2026-09-24T09:49:29.971Z" } wheels = [ @@ -831,16 +913,14 @@ wheels = [ [[package]] name = "hydra-core" -version = "1.3.5" +version = "1.4.0rc3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "antlr4-python3-runtime" }, - { name = "omegaconf" }, - { name = "packaging" }, + { name = "omegaconf", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/3e/e4/69a522676faf88994d93d8a5e69e0666c61cae7f73d1bbcc483222023e74/hydra_core-1.3.5.tar.gz", hash = "sha256:71c441eabbde086062045e4d3fce9e26015244f1a4ac721cf3e444c7edf10633", size = 3264337, upload-time = "2026-08-05T18:33:21.394Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/3c/74eef117ed30f7d35b85c7b4027560da6059e6d0c18f3a214301af4c45a3/hydra_core-1.4.0rc3.tar.gz", hash = "sha256:c9cae4b6cd21e86cb9f4095f5d7f276115c1a92448936ca48aad8f02a5feccc1", size = 3375483, upload-time = "2026-10-25T15:25:53.562Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9c/97/f9d463a6f3c7d0955753eca5cbbf35b596ac471dd13fe357211a53fd37be/hydra_core-1.3.5-py3-none-any.whl", hash = "sha256:a3ff35b4ea6794e4c83d993016f4bde4ac35797ebe7a08f30e83ed9341880331", size = 155768, upload-time = "2026-08-05T18:33:19.834Z" }, + { url = "https://files.pythonhosted.org/packages/11/27/6c832963c39a2d09dd83972992bcd32b625eb9d91769753e8bf3a16aae0a/hydra_core-1.4.0rc3-py3-none-any.whl", hash = "sha256:96c4fe930b14d944f63a13161c32adf2d6728391a2038cc70a0c996766c5ea38", size = 198282, upload-time = "2026-10-25T15:25:42.949Z" }, ] [[package]] @@ -866,8 +946,8 @@ name = "imageio" version = "2.38.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, - { name = "pillow" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pillow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f3/cd/69e4ac55b6dafdd2b5f32075236841a3945dea7323d0232d80f28c37cea8/imageio-2.38.1.tar.gz", hash = "sha256:6769f1f01c4dd46448307863a787c9a22fa4dbe11c0c88f525c6e410fdfd7983", size = 403667, upload-time = "2026-10-08T14:35:32.961Z" } wheels = [ @@ -903,7 +983,7 @@ name = "importlib-metadata" version = "9.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "zipp" }, + { name = "zipp", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a9/01/15bb152d77b21318514a96f43af312635eb2500c96b55398d020c93d86ea/importlib_metadata-9.0.0.tar.gz", hash = "sha256:a4f57ab599e6a2e3016d7595cfd72eb4661a5106e787a95bcc90c7105b831efc", size = 56405, upload-time = "2026-03-20T06:42:56.999Z" } wheels = [ @@ -919,73 +999,106 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] +[[package]] +name = "ipython" +version = "9.17.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "platform_machine == 'AMD64' and sys_platform == 'win32'" }, + { name = "ipython-pygments-lexers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "jedi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "matplotlib-inline", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pexpect", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "prompt-toolkit", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "psutil", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pygments", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "stack-data", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "traitlets", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b9/32/99451b1283ec5d92ad77073f12e1c667dc10775384d8f15c2914207149dd/ipython-9.17.1.tar.gz", hash = "sha256:8919be8c27f20a6f4423145028063f6637b42a03ce57665bb12015ee1f073529", size = 4539289, upload-time = "2026-09-01T08:29:32.6Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2d/1e/65b59cf518c106aa755e7f7da3099027738687a862ec785060702a481320/ipython-9.17.1-py3-none-any.whl", hash = "sha256:6d1645743cfd1a07eb695d85aa2b5fa66721f8cbae9431d4049f7084bbf06509", size = 639038, upload-time = "2026-09-01T08:29:30.673Z" }, +] + +[[package]] +name = "ipython-pygments-lexers" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pygments", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393, upload-time = "2025-01-17T11:24:34.505Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/33/1f075bf72b0b747cb3288d011319aaf64083cf2efef8354174e3ed4540e2/ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c", size = 8074, upload-time = "2025-01-17T11:24:33.271Z" }, +] + [[package]] name = "isaaclab" version = "3.0.0" -source = { git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&branch=release%2F3.0.0#d061bf35a58273ef0cc8aceae76392166f9b7d15" } -dependencies = [ - { name = "alphashape" }, - { name = "botocore" }, - { name = "coacd" }, - { name = "daqp", marker = "sys_platform != 'win32'" }, - { name = "einops" }, - { name = "fast-simplification" }, - { name = "filelock" }, - { name = "gitpython" }, - { name = "gymnasium" }, - { name = "h5py" }, - { name = "hf-xet" }, - { name = "hidapi" }, - { name = "hydra-core" }, - { name = "imgui-bundle" }, - { name = "jinja2" }, - { name = "lazy-loader" }, - { name = "matplotlib" }, - { name = "meshio" }, - { name = "newton", extra = ["sim"] }, - { name = "newton-usd-schemas" }, - { name = "numba" }, - { name = "numpy" }, - { name = "omniverseclient" }, - { name = "onnx" }, - { name = "open3d", marker = "platform_machine == 'x86_64' or sys_platform == 'win32'" }, - { name = "packaging" }, - { name = "pillow" }, - { name = "pin", marker = "sys_platform != 'win32'" }, - { name = "pin-pink", marker = "sys_platform != 'win32'" }, - { name = "prettytable" }, - { name = "protobuf" }, - { name = "psutil" }, - { name = "pycollada" }, - { name = "pyglet" }, - { name = "pyopengl-accelerate" }, - { name = "requests" }, - { name = "resolve-robotics-uri-py" }, - { name = "rich" }, - { name = "rsl-rl-lib" }, - { name = "scipy" }, - { name = "starlette" }, - { name = "tensorboard" }, - { name = "torch" }, - { name = "torchvision" }, - { name = "tqdm" }, - { name = "transformers" }, - { name = "trimesh" }, - { name = "typing-extensions" }, - { name = "urllib3" }, - { name = "usd-exchange" }, - { name = "warp-lang" }, +source = { git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead#d1822a7dfa9b565dd6f5b2445ea35b01cb982283" } +dependencies = [ + { name = "alphashape", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "botocore", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "coacd", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "daqp", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "einops", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "fast-simplification", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "filelock", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "gitpython", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "gymnasium", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "h5py", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "hf-xet", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "hydra-core", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "imgui-bundle", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "jinja2", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "lazy-loader", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "matplotlib", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "meshio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "newton", extra = ["sim"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "newton-usd-schemas", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numba", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "onnx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "open3d", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "ovstorage", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pillow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pin", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "pin-pink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "prettytable", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "protobuf", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "psutil", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pycollada", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyglet", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyopengl-accelerate", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "requests", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "resolve-robotics-uri-py", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "rich", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "rsl-rl-lib", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "scipy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "starlette", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tensorboard", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "torchvision", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tqdm", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "transformers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "trimesh", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "urllib3", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "usd-exchange", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "warp-lang", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] [package.optional-dependencies] -video = [ - { name = "moviepy" }, +fovi = [ + { name = "fovi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "openexr", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -viser = [ - { name = "viser" }, +video = [ + { name = "moviepy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wandb = [ - { name = "wandb" }, + { name = "wandb", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] [[package]] @@ -993,56 +1106,58 @@ name = "isaaclab-tutorial" version = "0.1.0" source = { editable = "." } dependencies = [ - { name = "isaaclab" }, - { name = "torch" }, - { name = "torchvision" }, + { name = "isaaclab", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "torchvision", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] [package.optional-dependencies] +fovi = [ + { name = "isaaclab", extra = ["fovi"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "transformers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] leapp = [ - { name = "leapp" }, + { name = "leapp", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] ovphysx = [ - { name = "ovphysx" }, + { name = "ovphysx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] ovrtx = [ - { name = "ovrtx" }, - { name = "ovstage" }, + { name = "ovrtx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "ovstage", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] video = [ - { name = "isaaclab", extra = ["video"] }, -] -viser = [ - { name = "isaaclab", extra = ["viser"] }, + { name = "isaaclab", extra = ["video"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wandb = [ - { name = "isaaclab", extra = ["wandb"] }, - { name = "wandb" }, + { name = "isaaclab", extra = ["wandb"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "wandb", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] [package.dev-dependencies] dev = [ - { name = "codespell" }, - { name = "pre-commit" }, - { name = "pytest" }, - { name = "ruff" }, + { name = "codespell", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pre-commit", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pytest", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "ruff", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] [package.metadata] requires-dist = [ - { name = "isaaclab", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&branch=release%2F3.0.0" }, - { name = "isaaclab", extras = ["video"], marker = "extra == 'video'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&branch=release%2F3.0.0" }, - { name = "isaaclab", extras = ["viser"], marker = "extra == 'viser'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&branch=release%2F3.0.0" }, - { name = "isaaclab", extras = ["wandb"], marker = "extra == 'wandb'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&branch=release%2F3.0.0" }, + { name = "isaaclab", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead" }, + { name = "isaaclab", extras = ["fovi"], marker = "extra == 'fovi'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead" }, + { name = "isaaclab", extras = ["video"], marker = "extra == 'video'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead" }, + { name = "isaaclab", extras = ["wandb"], marker = "extra == 'wandb'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead" }, { name = "leapp", marker = "extra == 'leapp'", specifier = "==0.7.2" }, { name = "ovphysx", marker = "extra == 'ovphysx'", index = "https://pypi.nvidia.com/" }, { name = "ovrtx", marker = "extra == 'ovrtx'", specifier = "==0.5.0.377615", index = "https://pypi.nvidia.com/" }, { name = "ovstage", marker = "extra == 'ovrtx'", specifier = "==0.1.1.355824" }, { name = "torch", specifier = "==2.11.0", index = "https://download.pytorch.org/whl/cu130" }, { name = "torchvision", specifier = "==0.26.0", index = "https://download.pytorch.org/whl/cu130" }, + { name = "transformers", marker = "extra == 'fovi'", specifier = "==5.19.0" }, { name = "wandb", marker = "extra == 'wandb'", specifier = "==0.26.1" }, ] -provides-extras = ["leapp", "ovphysx", "ovrtx", "video", "viser", "wandb"] +provides-extras = ["fovi", "leapp", "ovphysx", "ovrtx", "video", "wandb"] [package.metadata.requires-dev] dev = [ @@ -1070,12 +1185,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/68/34/65604740edcb20e1bda6a890348ed7d282e7dd23aa00401cbe36fd0edbd9/janus-2.0.0-py3-none-any.whl", hash = "sha256:7e6449d34eab04cd016befbd7d8c0d8acaaaab67cb59e076a69149f9031745f9", size = 12161, upload-time = "2024-12-13T12:59:06.106Z" }, ] +[[package]] +name = "jedi" +version = "0.20.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "parso", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a3/a4/4692ecd7fa700ac1066b1c1f6cadef60aa2e01e5e364710235137d823e0a/jedi-0.20.1.tar.gz", hash = "sha256:2f71208c3f9c1bca057c0e90d3f272aba44ace88fc4067d7587e9e069331b7e5", size = 3121738, upload-time = "2026-10-12T17:42:24.361Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/c7/71eb0d51cdcbb63b857c931aa4e9218b078b5d9f8ecd383b234f28fe7b0f/jedi-0.20.1-py2.py3-none-any.whl", hash = "sha256:0fb16d86c4a4c73c37ba518c77419975e30fcc620658a8d14fbb5720cdd34142", size = 4885980, upload-time = "2026-10-12T17:42:21.585Z" }, +] + [[package]] name = "jinja2" version = "3.1.6" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "markupsafe" }, + { name = "markupsafe", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } wheels = [ @@ -1096,7 +1223,7 @@ name = "joblib" version = "1.6.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cloudpickle" }, + { name = "cloudpickle", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/d5/1d/537ab090f302b838943a1b56497dd53059b9a9b46a074936470173a2e207/joblib-1.6.0.tar.gz", hash = "sha256:2ccc96785b12046c08fd6d55839c12857831b54a3c1673ffadd2f04bfc4eda03", size = 327903, upload-time = "2026-08-31T09:39:04.122Z" } wheels = [ @@ -1108,10 +1235,10 @@ name = "jsonschema" version = "4.26.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "attrs" }, - { name = "jsonschema-specifications" }, - { name = "referencing" }, - { name = "rpds-py" }, + { name = "attrs", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "jsonschema-specifications", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "referencing", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "rpds-py", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } wheels = [ @@ -1123,7 +1250,7 @@ name = "jsonschema-specifications" version = "2025.9.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "referencing" }, + { name = "referencing", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } wheels = [ @@ -1135,8 +1262,8 @@ name = "jupyter-core" version = "5.9.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "platformdirs" }, - { name = "traitlets" }, + { name = "platformdirs", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "traitlets", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/02/49/9d1284d0dc65e2c757b74c6687b6d319b02f822ad039e5c512df9194d9dd/jupyter_core-5.9.1.tar.gz", hash = "sha256:4d09aaff303b9566c3ce657f580bd089ff5c91f5f89cf7d8846c3cdf465b5508", size = 89814, upload-time = "2025-10-16T19:19:18.444Z" } wheels = [ @@ -1151,7 +1278,13 @@ sdist = { url = "https://files.pythonhosted.org/packages/ba/07/bd78e6a8fae171ea0 wheels = [ { url = "https://files.pythonhosted.org/packages/fc/f4/dadfec469313c7f428efa7e84b4aba9732f813c13ea7131a24b7b008ef57/kiwisolver-1.5.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34633ecf50d16187ab8e5528b7a2530f2feb4e23f300db4672538b51cfc5cd38", size = 1477929, upload-time = "2026-08-28T10:25:31.495Z" }, { url = "https://files.pythonhosted.org/packages/6f/35/09c58daac34e6f6ea5c6dee0094b422118e5a7c265586008a95fd135ac5f/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d27c2123977cb9269c30a49ba45f03a4323017ef693e19db4ec9dbe1299a3002", size = 1278499, upload-time = "2026-08-28T10:25:33.375Z" }, + { url = "https://files.pythonhosted.org/packages/19/32/739765e24fbad29d13f83e546ea4abc215a78cea9d677ca09025b027724d/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6a797a1cefc8b9c93170db580337e1fe3d011ad18b1299943231279406342048", size = 1296677, upload-time = "2026-08-28T10:25:35.059Z" }, + { url = "https://files.pythonhosted.org/packages/df/32/03304d1010e2cc45e5b3b52cef7e43fed3a2a5cd6c87a89b4a88e1d85b5d/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2551cf9917af48ee7c4b29cc82320489508cf96fd26a51f6fc124de661cd44c7", size = 1346037, upload-time = "2026-08-28T10:25:36.705Z" }, + { url = "https://files.pythonhosted.org/packages/3e/57/4c49377bfd274450dd72ecaa13eaac32ea804a03363e4d1db0c5aa999ceb/kiwisolver-1.5.1-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:38f6e0deb4d0a4615efe0c4efc5990b06ae450ab50a0b321c0b078b6d238c083", size = 988248, upload-time = "2026-08-28T10:25:38.299Z" }, { url = "https://files.pythonhosted.org/packages/cb/c3/38df144a08b6c5d75ca4504e5cc3141bb3bfef64c04f4ef48204f42711b6/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:bfd1de989b3330420e29de39352f5c049905c9e3ee67233a50d550e3d652c148", size = 2228722, upload-time = "2026-08-28T10:25:40.038Z" }, + { url = "https://files.pythonhosted.org/packages/e7/11/3221838a89cd64d9b386353e000cd8a296069a20fbe3584507fdfd5bebae/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1209042a623ddfda5497e4066c7b77651dde8e1d3a9dd97599dc7e97f3b9b78c", size = 2325216, upload-time = "2026-08-28T10:25:41.699Z" }, + { url = "https://files.pythonhosted.org/packages/83/d4/075c219230697bb5db910d37262b9bacf880f92b4811a02ab81ed073a253/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:26e8268480be5061d509e29669d59103c067a26377a56491630ece11762e3858", size = 1977689, upload-time = "2026-08-28T10:25:43.559Z" }, + { url = "https://files.pythonhosted.org/packages/bb/08/1d219c3c2dd960983d0d4da623d916e9de6385df2b0bab3d1af0e9b8fccc/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:d79308fa689fac89cbcfbd4dbfc80b5f95c54c5a7fd4d194be221f9d33d026e6", size = 2491443, upload-time = "2026-08-28T10:25:45.242Z" }, { url = "https://files.pythonhosted.org/packages/ba/d3/024208ec1079d273f1047468d1bdffbf38bb75b7b268090fd3a0301b9d9a/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b03af77d77e50edba2030fd5f7c352ff209314b09030a3cba7c14edf9a09a444", size = 2295200, upload-time = "2026-08-28T10:25:46.984Z" }, { url = "https://files.pythonhosted.org/packages/6e/7c/7b210498f9f92e1cd7855f260fa69ef056881087b199ee20c208f0e4189a/kiwisolver-1.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:06a6917674de9e0fe3f66f5430787f59a9f2ddb64af9b714eaec547e29ef5c19", size = 70748, upload-time = "2026-08-28T10:25:48.444Z" }, { url = "https://files.pythonhosted.org/packages/16/45/c37a21ad5c0ab581a93c55ad544721aaa1f0ae94edb29c6a678a23d013e6/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:072bdb15a3c19a5b5dbc8f8fb1f4e1884bf4f3507eeb4cc6334401274d37a5c0", size = 194292, upload-time = "2026-08-28T10:28:11.06Z" }, @@ -1163,7 +1296,7 @@ name = "lazy-loader" version = "0.5" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "packaging" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/49/ac/21a1f8aa3777f5658576777ea76bfb124b702c520bbe90edf4ae9915eafa/lazy_loader-0.5.tar.gz", hash = "sha256:717f9179a0dbed357012ddad50a5ad3d5e4d9a0b8712680d4e687f5e6e6ed9b3", size = 15294, upload-time = "2026-03-06T15:45:09.054Z" } wheels = [ @@ -1175,14 +1308,14 @@ name = "leapp" version = "0.7.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "fast-sugiyama" }, - { name = "onnx" }, - { name = "onnxruntime" }, - { name = "onnxscript" }, - { name = "pillow" }, - { name = "pyyaml" }, - { name = "safetensors" }, - { name = "torch" }, + { name = "fast-sugiyama", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "onnx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "onnxruntime", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "onnxscript", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pillow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyyaml", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "safetensors", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f7/7e/73deb04c334f3f18eb886d3d8d447f8f278bcf0a624c3e86f2031da32c88/leapp-0.7.2-py3-none-any.whl", hash = "sha256:86c1581eb09ba1f4b98cd980e19e771682ce3a7ac6766ec087d37496bf5579e0", size = 222176, upload-time = "2026-10-08T20:43:15.66Z" }, @@ -1193,11 +1326,11 @@ name = "libcoal" version = "3.0.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, - { name = "cmeel-assimp" }, - { name = "cmeel-boost" }, - { name = "cmeel-octomap" }, - { name = "cmeel-qhull" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-assimp", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-boost", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-octomap", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-qhull", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/05/44/d59b10af87165def48bf55fcb3f0591274a39322d48cb92d608d17ed86b5/libcoal-3.0.3.tar.gz", hash = "sha256:fd0f887682c73ef2d429caa09721993acb596b9e529c4f37761fe34faa7675ed", size = 1464501, upload-time = "2026-05-21T08:41:47.216Z" } wheels = [ @@ -1210,10 +1343,10 @@ name = "libpinocchio" version = "4.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, - { name = "cmeel-boost" }, - { name = "cmeel-urdfdom" }, - { name = "libcoal" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-boost", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-urdfdom", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "libcoal", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/39/28/1b46cc98bba7411a57cb20c7a7c2fdf959dceb31d2c5131a29bd3fc649e9/libpinocchio-4.1.0.tar.gz", hash = "sha256:968bb7dff8aa7c25b1f879c0d9808b3e7686a1140eeb6372c003aba0d423772e", size = 4441987, upload-time = "2026-07-08T12:53:02.806Z" } wheels = [ @@ -1255,7 +1388,7 @@ name = "markdown-it-py" version = "4.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "mdurl" }, + { name = "mdurl", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" } wheels = [ @@ -1270,7 +1403,9 @@ sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95 wheels = [ { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" }, { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" }, + { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" }, { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" }, { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" }, { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" }, ] @@ -1280,15 +1415,15 @@ name = "matplotlib" version = "3.11.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "contourpy" }, - { name = "cycler" }, - { name = "fonttools" }, - { name = "kiwisolver" }, - { name = "numpy" }, - { name = "packaging" }, - { name = "pillow" }, - { name = "pyparsing" }, - { name = "python-dateutil" }, + { name = "contourpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "cycler", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "fonttools", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "kiwisolver", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pillow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyparsing", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "python-dateutil", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/49/64/f9a391af28f518b11ad45a8a712353c94a0aefce09d3703200e5c54b610a/matplotlib-3.11.1.tar.gz", hash = "sha256:69647db5746941c793d6e445a4cd349323ffb87d9cc958c2ad84a659b4832d30", size = 32612045, upload-time = "2026-07-18T03:39:46.63Z" } wheels = [ @@ -1298,6 +1433,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/89/56649bbaa2fd12e20f3be03dbcc135b0c8676d88bac17977599e3eb442a0/matplotlib-3.11.1-cp312-cp312-win_amd64.whl", hash = "sha256:88a2a27dd9691ae448dfae4b26f59036be90c3c28757edd3553a29559d00859f", size = 9333886, upload-time = "2026-07-18T03:38:30.477Z" }, ] +[[package]] +name = "matplotlib-inline" +version = "0.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "traitlets", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bd/c0/9f7c9a46090390368a4d7bcb76bb87a4a36c421e4c0792cdb53486ffac7a/matplotlib_inline-0.2.2.tar.gz", hash = "sha256:72f3fe8fce36b70d4a5b612f899090cd0401deddc4ea90e1572b9f4bfb058c79", size = 8150, upload-time = "2026-05-08T17:33:33.49Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/09/5b161152e2d90f7b87f781c2e1267494aef9c32498df793f73ad0a0a494a/matplotlib_inline-0.2.2-py3-none-any.whl", hash = "sha256:3c821cf1c209f59fb2d2d64abbf5b23b67bcb2210d663f9918dd851c6da1fcf6", size = 9534, upload-time = "2026-05-08T17:33:32.055Z" }, +] + [[package]] name = "mdurl" version = "0.1.2" @@ -1312,8 +1459,8 @@ name = "meshio" version = "5.3.5" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, - { name = "rich" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "rich", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/20/1e/caa4f15c020de3e3486b4133ca689236bd3863a3d6dd0f58e97ce86a296a/meshio-5.3.5.tar.gz", hash = "sha256:f21f01abd9f29ba06ea119304b3d39e610421cfe93b9dd23362834919f87586d", size = 490922, upload-time = "2024-01-31T15:09:41.731Z" } wheels = [ @@ -1325,7 +1472,7 @@ name = "ml-dtypes" version = "0.6.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/12/72/307d7c4bd0600601c7133fba5cb78af7db968152951c1cd473abb1cda782/ml_dtypes-0.6.0.tar.gz", hash = "sha256:5e60251d32ced5598972e4d5e06a2f044341f9291402551a3f6f0ec44f9299b0", size = 3032327, upload-time = "2026-08-13T14:14:40.215Z" } wheels = [ @@ -1339,13 +1486,13 @@ name = "moviepy" version = "1.0.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "decorator" }, - { name = "imageio" }, - { name = "imageio-ffmpeg" }, - { name = "numpy" }, - { name = "proglog" }, - { name = "requests" }, - { name = "tqdm" }, + { name = "decorator", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "imageio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "imageio-ffmpeg", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "proglog", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "requests", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tqdm", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/18/54/01a8c4e35c75ca9724d19a7e4de9dc23f0ceb8769102c7de056113af61c3/moviepy-1.0.3.tar.gz", hash = "sha256:2884e35d1788077db3ff89e763c5ba7bfddbd7ae9108c9bc809e7ba58fa433f5", size = 388311, upload-time = "2020-05-07T16:27:46.856Z" } @@ -1358,51 +1505,39 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, ] -[[package]] -name = "msgspec" -version = "0.22.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d0/e6/6dcf9306ff3c5e486578f3bf29ed11dfbdbbc2a8bf0caf7e07d392887fda/msgspec-0.22.0.tar.gz", hash = "sha256:0a13624a4969159fe35d8c2a3d377b2b61bbd8585e327440d5e52725affcce38", size = 343188, upload-time = "2026-09-29T14:14:11.422Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/54/a5/65de05f8804492f76ea121b21a125cdf1d97ec461c677bfa0ba354d6fbdd/msgspec-0.22.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b5a169b5b03f0f2c7a296c002647db1dab75d2cd501bca34e32b71cab0261b56", size = 224035, upload-time = "2026-09-29T14:12:40.876Z" }, - { url = "https://files.pythonhosted.org/packages/4a/cc/aa1a47f8c92280d37498a5ea56a2a36606d034383e3e6472d64cbb56cf85/msgspec-0.22.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:99c401861c5bb3a57f7d6423ea7ed4352cd57aa3f04f4fbe9f3e3e4564a10f08", size = 230377, upload-time = "2026-09-29T14:12:42.796Z" }, - { url = "https://files.pythonhosted.org/packages/cf/8a/473fa423f8fdd1b810b8652594323d7301df6920b62844d860daa0feff34/msgspec-0.22.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:21460f54cee9208239b1a8421fdf25bffc77293e1daba88f585711ad839b9758", size = 227733, upload-time = "2026-09-29T14:12:45.839Z" }, - { url = "https://files.pythonhosted.org/packages/f6/26/29e0b9a8605c8819a3c718158e345a616ac42c092dd7d7ab248c2f2b0a72/msgspec-0.22.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0b25dcbc108783cb72503ed705b9fbb8c3cb02ee5801923f44b5f038c91cc365", size = 232728, upload-time = "2026-09-29T14:12:48.792Z" }, - { url = "https://files.pythonhosted.org/packages/e1/a6/99597c281d716da6c662b48dcc3f734669f716b41d5df2af367dac9e7c21/msgspec-0.22.0-cp312-cp312-win_amd64.whl", hash = "sha256:6ad64f5c260866b0d543f89f50cee43628989c1433c5de7ce820281fa28a2611", size = 192885, upload-time = "2026-09-29T14:12:50.274Z" }, -] - [[package]] name = "mujoco" -version = "3.12.0" +version = "3.17.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "absl-py" }, - { name = "etils", extra = ["epath"] }, - { name = "glfw" }, - { name = "numpy" }, - { name = "pyopengl" }, + { name = "absl-py", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "etils", extra = ["epath"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "glfw", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyopengl", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "websockets", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a6/cd/40c929fa073d6b25d44c9f32b3dbbfcb025053cba54f57f8d46d84cdc034/mujoco-3.12.0.tar.gz", hash = "sha256:38bb3eaf4251937a85d58b25f55b1679297155bc4f4e964490d1fd9f42f8bf93", size = 1209771, upload-time = "2026-08-20T11:01:09.106Z" } +sdist = { url = "https://files.pythonhosted.org/packages/40/10/dde0a84f2c4552729540c3e19431177e6e1b4c20dc536e19169e575d0e94/mujoco-3.17.0.tar.gz", hash = "sha256:5e49c15905e7a39eaa1efb1cae809a81c5f5c2439467f23e7e6e383624d957be", size = 7145175, upload-time = "2026-10-22T23:58:49.331Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/51/d9/f3cb98d7e37439ffa912b8c63f63e065473523d958cc9eebf40bf8cf9c96/mujoco-3.12.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b10fd3040f5c71504f25a560d8e2fea881f0dc27a9cfd22b4b0a79e65c942f20", size = 18506697, upload-time = "2026-08-20T11:47:55.661Z" }, - { url = "https://files.pythonhosted.org/packages/b7/2e/389e8aaa3ce75e21f97ac9e7c48235b6b7acbfb1f370fd3ffb334f77b905/mujoco-3.12.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7ec16ce408871a0a9157cc556958ab66cd34db9fc1dccd3ef07717170163a4e0", size = 19816226, upload-time = "2026-08-20T11:47:58.602Z" }, - { url = "https://files.pythonhosted.org/packages/18/2e/7c42bb3c57b0ae6c37f55f47af94bcc7ea1fe9c39d76df99fb55c3d28591/mujoco-3.12.0-cp312-cp312-win_amd64.whl", hash = "sha256:d575c455829c8b8d2ffeff4eb3341115623f2e10a250271e73ad94219b707a35", size = 16733176, upload-time = "2026-08-20T11:48:01.552Z" }, + { url = "https://files.pythonhosted.org/packages/a9/a5/d83393779c81fe1807442844254fe71b9182f1f2b64e865dfe8534db1620/mujoco-3.17.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:525e09a00ecd964f06582773d9eeb03bb0e5a1675edf296a6868024759b3b235", size = 25231702, upload-time = "2026-10-22T23:34:54.582Z" }, + { url = "https://files.pythonhosted.org/packages/66/33/9e329714eefc47dfbedefe6ea3809f055acbf58279799d635b1a18510924/mujoco-3.17.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:42371356efe53a5f5f73ed03fcb967bdf04048017f80e2fca01e71a360e42da2", size = 26654565, upload-time = "2026-10-22T23:34:57.762Z" }, + { url = "https://files.pythonhosted.org/packages/c1/16/609b306f340fbc58fb0a75a5aac7cb4bc8f9d60155ebebc22043a4526069/mujoco-3.17.0-cp312-cp312-win_amd64.whl", hash = "sha256:17ab707e86b0a5da13582a5335d3ea585a5ac4cce2e814e15b203530d1bf16e3", size = 16311296, upload-time = "2026-10-22T23:57:32.433Z" }, ] [[package]] name = "mujoco-warp" -version = "3.12.0" +version = "3.17.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "absl-py" }, - { name = "etils", extra = ["epath"] }, - { name = "mujoco" }, - { name = "numpy" }, - { name = "warp-lang" }, + { name = "absl-py", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "etils", extra = ["epath"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "mujoco", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "warp-lang", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b2/4f/41acd8a084dc8f140594fcca74f2dda61f89705505df20885bd6e65c0146/mujoco_warp-3.12.0.tar.gz", hash = "sha256:6937b83e9eb1632446a70104867d2b0c0ff028613ebc377eee992d30640d6554", size = 2085022, upload-time = "2026-08-20T11:58:15.742Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/82/846dc011598bcb3e6ea8949c1fc7519584a86241b50c62fab4e631519200/mujoco_warp-3.17.0.tar.gz", hash = "sha256:2a5391f9d4d7a4d0e2908e0be80ee77ad12dbf27c76a2b9724099441360b5de7", size = 2266308, upload-time = "2026-10-22T23:39:12.206Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/47/24/d60f407b469be023566c8e149eb1598ff7d8f9b16332cdadc4fa45ebee3a/mujoco_warp-3.12.0-py3-none-any.whl", hash = "sha256:a0d5d5df854dbf49727cbe2463f8b1c44117cc979cf17ae91d81f291ae0a3b62", size = 2164496, upload-time = "2026-08-20T11:58:13.887Z" }, + { url = "https://files.pythonhosted.org/packages/df/81/f651b9f3ee97786f375c879c2386734da1d0aba257b654c6c181edb824fd/mujoco_warp-3.17.0-py3-none-any.whl", hash = "sha256:3c7d4a6c27e60c61679d3746c6fa32e55803d22dd2f3faf79bcc3b643d61ae0a", size = 2348047, upload-time = "2026-10-22T23:39:10.383Z" }, ] [[package]] @@ -1419,10 +1554,10 @@ name = "nbformat" version = "5.11.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "fastjsonschema" }, - { name = "jsonschema" }, - { name = "jupyter-core" }, - { name = "traitlets" }, + { name = "fastjsonschema", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "jsonschema", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "jupyter-core", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "traitlets", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/31/72/b3446efab8756e7df4b8ec587f8e611cb5a7249e4323db480802f1d3be04/nbformat-5.11.1.tar.gz", hash = "sha256:32d4521c68c6e7d5b29c76defaeed9f42ea733142b9b19f88277ce10390b9c4d", size = 147775, upload-time = "2026-08-17T08:10:51.942Z" } wheels = [ @@ -1449,19 +1584,16 @@ wheels = [ [[package]] name = "newton" -version = "1.6.1" -source = { registry = "https://pypi.org/simple" } +version = "1.9.0.dev0" +source = { git = "https://github.com/newton-physics/newton.git?rev=3f428bf1a7183d3d9a10cc17241e8a9eac3841eb#3f428bf1a7183d3d9a10cc17241e8a9eac3841eb" } dependencies = [ - { name = "warp-lang" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/0b/53/fff564a78d53da69821cf75ccd6fecde0c218380671cd117628c5fdd957f/newton-1.6.1-py3-none-any.whl", hash = "sha256:0dbabb85228eeac9f2750347a3f4ce502ad41a9bf19d43f55c6c8e4458b7e318", size = 6194171, upload-time = "2026-10-05T22:18:10.567Z" }, + { name = "warp-lang", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] [package.optional-dependencies] sim = [ - { name = "mujoco" }, - { name = "mujoco-warp" }, + { name = "mujoco", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "mujoco-warp", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] [[package]] @@ -1487,8 +1619,8 @@ name = "numba" version = "0.67.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "llvmlite" }, - { name = "numpy" }, + { name = "llvmlite", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/7a/90/2544f4e3a61e501d6c9a5418fd4b905323222693d54a02cab0106a0af865/numba-0.67.0.tar.gz", hash = "sha256:cd75aa535b33fa05d9d930b1ae8af9f97a2881e96d72dfb38ec9b78284d9f851", size = 2836515, upload-time = "2026-08-11T23:04:00.174Z" } wheels = [ @@ -1551,7 +1683,7 @@ name = "nvidia-cudnn-cu13" version = "9.19.0.56" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas" }, + { name = "nvidia-cublas", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f1/84/26025437c1e6b61a707442184fa0c03d083b661adf3a3eecfd6d21677740/nvidia_cudnn_cu13-9.19.0.56-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:6ed29ffaee1176c612daf442e4dd6cfeb6a0caa43ddcbeb59da94953030b1be4", size = 433781201, upload-time = "2026-02-03T20:40:53.805Z" }, @@ -1563,7 +1695,7 @@ name = "nvidia-cufft" version = "12.0.0.61" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, @@ -1593,9 +1725,9 @@ name = "nvidia-cusolver" version = "12.0.4.66" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas" }, - { name = "nvidia-cusparse" }, - { name = "nvidia-nvjitlink" }, + { name = "nvidia-cublas", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cusparse", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, @@ -1607,7 +1739,7 @@ name = "nvidia-cusparse" version = "12.6.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, @@ -1661,25 +1793,14 @@ wheels = [ [[package]] name = "omegaconf" -version = "2.3.1" +version = "2.4.1rc2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "antlr4-python3-runtime" }, - { name = "pyyaml" }, + { name = "pyyaml", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ce/3d/e4b57b8d9008c6ebe0d5eff901f91d5700cf7bdb8c8863df817463a7fd5e/omegaconf-2.3.1.tar.gz", hash = "sha256:e5e7de64aeebeddaf8e6d3f7a783b32ac2a01c0fbd9c878012caecb891a1f42a", size = 3298472, upload-time = "2026-06-11T05:05:12.885Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a4/0e/152509871bf30df6fc38569f52a2db9b55dd41aae957adae50a053ac7778/omegaconf-2.3.1-py3-none-any.whl", hash = "sha256:3d701d14e9a8828f1edd28bb70b725908b34277cdd72cf7d6a83f94dadc6b6a0", size = 79502, upload-time = "2026-06-11T05:05:09.954Z" }, -] - -[[package]] -name = "omniverseclient" -version = "2.74.0" -source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/40/11/1cd1b9135e1ccef7bf7438bc1a527846037381b3720f301a2b845fc8d97a/omegaconf-2.4.1rc2.tar.gz", hash = "sha256:5d44556d785cd6df60419ea1bca74740517e54877d5a50daed92a3c2a478f922", size = 3545933, upload-time = "2026-10-28T12:22:06.364Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/cf/a4/f99608e58ab90602eea23a30ce5d754466151fa5d8765678ddcc4385ceaf/omniverseclient-2.74.0-cp312-cp312-manylinux_2_35_aarch64.whl", hash = "sha256:2071be85b5932b787df280e569078ed9274739da865f14d777a41a4b5e767fc4", size = 17028603, upload-time = "2026-09-17T15:18:48.114Z" }, - { url = "https://files.pythonhosted.org/packages/74/eb/ff9e3c27e44f3502f1df05ee1598ccbe8f0e86747f82a8efe8bd9f6d42e3/omniverseclient-2.74.0-cp312-cp312-manylinux_2_35_x86_64.whl", hash = "sha256:20ede072259d6912aa2176349b74aae71c0f56c4b7ff26f6885e4a84980cc2cc", size = 17070196, upload-time = "2026-09-17T15:18:31.408Z" }, - { url = "https://files.pythonhosted.org/packages/00/a6/b8adbe167c854ca8c775c554b4e779dd34f860e06021a6c3b9175b89a7cf/omniverseclient-2.74.0-cp312-cp312-win_amd64.whl", hash = "sha256:a4138c3c17502176b8fab3a0e0f4c8a4aab22006e7a6f4ee7d57a1a44906ee6f", size = 12215440, upload-time = "2026-09-17T15:19:02.933Z" }, + { url = "https://files.pythonhosted.org/packages/0c/0f/eea98e0a6c516c4d5f28ab9de29bf6dc00bb68e334d1f22e2af1bd1cb499/omegaconf-2.4.1rc2-py3-none-any.whl", hash = "sha256:4c7dbb92683503480617be4378b61df3d2765ccd1d2035dbe0d795325c10c143", size = 259143, upload-time = "2026-10-28T12:22:03.622Z" }, ] [[package]] @@ -1687,10 +1808,10 @@ name = "onnx" version = "1.22.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ml-dtypes" }, - { name = "numpy" }, - { name = "protobuf" }, - { name = "typing-extensions" }, + { name = "ml-dtypes", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "protobuf", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/04/19/8ea73a64b368b75fe339771a20a02bc61ea1f551484c9e3d9d0bfbd0450f/onnx-1.22.0.tar.gz", hash = "sha256:ef40c0aaf0b643857ea9306fc7eddce17eaf9fb0407e4801f1fc5758443a38e0", size = 12024721, upload-time = "2026-06-15T12:50:05.354Z" } wheels = [ @@ -1705,11 +1826,11 @@ name = "onnx-ir" version = "1.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ml-dtypes" }, - { name = "numpy" }, - { name = "onnx" }, - { name = "sympy" }, - { name = "typing-extensions" }, + { name = "ml-dtypes", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "onnx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "sympy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/d6/c2/61194cec0dbc5622273c0ebd592d37cc1dca0d7f1a744f02edd45ac905a3/onnx_ir-1.0.0.tar.gz", hash = "sha256:9e261f25fde8da9612ae5cb43b3b374d5ff469c04af0363cad588b2bb000b812", size = 163121, upload-time = "2026-08-11T14:49:46.895Z" } wheels = [ @@ -1721,10 +1842,10 @@ name = "onnxruntime" version = "1.30.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "flatbuffers" }, - { name = "numpy" }, - { name = "packaging" }, - { name = "protobuf" }, + { name = "flatbuffers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "protobuf", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/16/bd/cbc5b8f91963689fdd622f463508c01d0aa95d3f944747b1e0b1eb2160b8/onnxruntime-1.30.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:6c32a000d5139a38ba9349030b0032e3331acb559d596b22738d9d2b343a2b83", size = 21345202, upload-time = "2026-09-10T16:31:23.361Z" }, @@ -1737,12 +1858,12 @@ name = "onnxscript" version = "0.7.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ml-dtypes" }, - { name = "numpy" }, - { name = "onnx" }, - { name = "onnx-ir" }, - { name = "packaging" }, - { name = "typing-extensions" }, + { name = "ml-dtypes", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "onnx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "onnx-ir", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/c4/3a/4d79bce3f460e0df7fed54a92ce80827f25da66511da368bb00783ad8d20/onnxscript-0.7.1.tar.gz", hash = "sha256:309fb86484b11fa4ded90dba580e0d63f1a0827588e521cecaf2eeddb46d6e86", size = 618160, upload-time = "2026-06-29T23:33:21.526Z" } wheels = [ @@ -1754,32 +1875,49 @@ name = "open3d" version = "0.19.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "addict" }, - { name = "configargparse" }, - { name = "dash" }, - { name = "flask" }, - { name = "matplotlib" }, - { name = "nbformat" }, - { name = "numpy" }, - { name = "pandas" }, - { name = "pillow" }, - { name = "pyquaternion" }, - { name = "pyyaml" }, - { name = "scikit-learn" }, - { name = "tqdm" }, - { name = "werkzeug" }, + { name = "addict", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "configargparse", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "dash", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "flask", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "matplotlib", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "nbformat", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pandas", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pillow", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyquaternion", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyyaml", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "scikit-learn", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tqdm", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "werkzeug", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/2b/95/3723e5ade77c234a1650db11cbe59fe25c4f5af6c224f8ea22ff088bb36a/open3d-0.19.0-cp312-cp312-manylinux_2_31_x86_64.whl", hash = "sha256:01e4590dc2209040292ebe509542fbf2bf869ea60bcd9be7a3fe77b65bad3192", size = 447665185, upload-time = "2025-01-08T07:23:39.769Z" }, { url = "https://files.pythonhosted.org/packages/9f/c4/35a6e0a35aa72420e75dc28d54b24beaff79bcad150423e47c67d2ad8773/open3d-0.19.0-cp312-cp312-win_amd64.whl", hash = "sha256:665839837e1d3a62524804c31031462c3b548a2b6ed55214e6deb91522844f97", size = 69169961, upload-time = "2025-01-08T07:27:35.392Z" }, ] +[[package]] +name = "openexr" +version = "3.5.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5f/c0/422dd868e5f94f7885bd9c12f2dc6fabbeb4a8cd0b002bc097024dae861d/openexr-3.5.4.tar.gz", hash = "sha256:8b5b06f08b05d512fe52fa18c5c2f27c2141938149da23d056094bc392f15db8", size = 26300935, upload-time = "2026-11-12T16:45:00.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/b9/c9e228497d81cb810c277116ab4cbeb3d3d1826b1b21fcc2f8aafa771ec6/openexr-3.5.4-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:116adcc66a9601048d0ffa7387990bb9d510d1dd0e8cb0ab999b825c1e717277", size = 1593447, upload-time = "2026-11-12T16:44:02.944Z" }, + { url = "https://files.pythonhosted.org/packages/3c/3e/4b08275770fffcb57202762e2f023bfac39754290ba4727198b02d76bf74/openexr-3.5.4-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:6f9644dd8b96eb314498c9849684f57adf67bde72f8b0193929bf29adff03b70", size = 1786567, upload-time = "2026-11-12T16:44:05.014Z" }, + { url = "https://files.pythonhosted.org/packages/17/b3/4a25166ed8bc29aee9d01f2d9f007ef15f9d3ea4075b19667879c149e30b/openexr-3.5.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b1c2658516cc199fb31baf0565e422dfa6df8077ba2336c3acc170c45e251a08", size = 2607932, upload-time = "2026-11-12T16:44:06.641Z" }, + { url = "https://files.pythonhosted.org/packages/76/37/a0e9a6a8a1cf7ec7efcb2cb7fbdaf55cd2a4349a26343a75fb7ac83e3e54/openexr-3.5.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a586a32ebb01fd87a54286ec9f29f5583a5176c019ebbbe6fd832a7188cefcd1", size = 2825749, upload-time = "2026-11-12T16:44:08.373Z" }, + { url = "https://files.pythonhosted.org/packages/68/15/7ff3e6a17444d70669085e21487e546fd6fe298b2eb653eccbd4e0c3b6a1/openexr-3.5.4-cp312-cp312-win_amd64.whl", hash = "sha256:d55fe6b60e923917bc5104808df2d515a82b0fb053b0e038788626f0fd2b780f", size = 1186933, upload-time = "2026-11-12T16:44:10.017Z" }, +] + [[package]] name = "orjson" version = "3.12.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/0f/f3/742fb1f62b825f2c010697eaf4e828004bc2a81e7e806666989c132c7c42/orjson-3.12.0.tar.gz", hash = "sha256:d14203fb1aae2ad9b3d52f8a0e82aeb10197ef1c9bc61da7f358bd70b00123d5", size = 4142915, upload-time = "2026-08-14T16:13:30.607Z" } wheels = [ + { url = "https://files.pythonhosted.org/packages/32/b5/5b934d251f8651f7e41df180ad0c57a6e1cabe15c7bd331638413a50ebc9/orjson-3.12.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:2d3a9da945a4d96ae758fdaaca56742e6b73b6fd554c5d8876f252a6dad70b83", size = 113375, upload-time = "2026-08-14T16:12:31.209Z" }, { url = "https://files.pythonhosted.org/packages/50/22/0644b87c73f13e0092df8f35a1fe280d991e5e90072087411e0dd7e44e0c/orjson-3.12.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bf44e374aadde77b1f6109f1030be51433eb61984379852766b6f4e187db7b1e", size = 130629, upload-time = "2026-08-14T16:12:34.084Z" }, { url = "https://files.pythonhosted.org/packages/8c/57/80b986ebfecd9c6a177ddf1c2319717f0cd8feffb2b78946595a18a2fc88/orjson-3.12.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1192a7021b6d071aaf909864f6e924d6a2675ca360485b972b8401749311750b", size = 131245, upload-time = "2026-08-14T16:12:35.713Z" }, { url = "https://files.pythonhosted.org/packages/80/3d/75c5ac5a69161f44492a68fbdde66f4cc4ce48cd5e1fb05918e46f0c8848/orjson-3.12.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:53c0c474a9d9aff9aebfc0c88de1f28f843d940e6e3a80729abdf6a20274356f", size = 135397, upload-time = "2026-08-14T16:12:37.128Z" }, @@ -1792,8 +1930,8 @@ name = "ovphysx" version = "0.5.11" source = { registry = "https://pypi.nvidia.com/" } dependencies = [ - { name = "ovstage" }, - { name = "packaging" }, + { name = "ovstage", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wheels = [ { url = "https://pypi.nvidia.com/ovphysx/ovphysx-0.5.11-py3-none-manylinux_2_35_aarch64.whl", hash = "sha256:fff7e648fe14989e6ae51b7c6e6c516beab0b4f0749110c32c5a142b31525946" }, @@ -1821,6 +1959,16 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fb/d0/ff9124f524ffadc87f8893e99de1679e7c517ca6ceb60e0b870a284b71a3/ovstage-0.1.1.355824-py3-none-win_amd64.whl", hash = "sha256:fc8ae7fe950aa2ff8fd24643047f7156ffa1b9b384ce3f024ee2193929e21a3b", size = 35031430, upload-time = "2026-08-05T20:05:29.88Z" }, ] +[[package]] +name = "ovstorage" +version = "0.3.0" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/01/f7/ddb5bb88c2322d78e44479e0440cb55b2c58a6e2a6f1d6c68121aacc37eb/ovstorage-0.3.0-cp310-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:e7e4bdcd25256c8e5b8f06eed2fd8807c3ce25b52f35d56bbe87f9d56fc7840d", size = 66230840, upload-time = "2026-09-22T19:01:15.768Z" }, + { url = "https://files.pythonhosted.org/packages/db/92/c4b66bf2dbe67263366e5ba0b4750b906bd9b48595cbbdfb7995a482d1e5/ovstorage-0.3.0-cp310-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:59bfd5d9382d9615a75a10f505ce9adb88b51766fecd861d3da7b1a597b2ea15", size = 66390101, upload-time = "2026-09-22T19:00:25.824Z" }, + { url = "https://files.pythonhosted.org/packages/ea/d2/69bb2e7b8176213122baa54aaa350ef614f4d9f447a59e74ac0ac263884d/ovstorage-0.3.0-cp310-abi3-win_amd64.whl", hash = "sha256:149a9fece5fc4a48ce18846acdb0d815778fe6fb62ca9719820278ef38eaf421", size = 60547671, upload-time = "2026-09-22T19:01:46.902Z" }, +] + [[package]] name = "packaging" version = "23.2" @@ -1835,9 +1983,9 @@ name = "pandas" version = "3.0.5" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, - { name = "python-dateutil" }, - { name = "tzdata", marker = "sys_platform == 'win32'" }, + { name = "numpy", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "python-dateutil", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tzdata", marker = "platform_machine == 'AMD64' and sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/be/4f/5f3422a2afec5ffc46308b79e53291365a93748b498ac2e58bead0197916/pandas-3.0.5.tar.gz", hash = "sha256:dca3734d6ab7c906e6730f0788b0a1dbb9f2467731f9711f77995c8e9d62d712", size = 4658219, upload-time = "2026-07-22T22:19:28.819Z" } wheels = [ @@ -1847,6 +1995,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/70/b5/d2d3e9ae73362ba4229651b0ee1455cf78073a1ce585f6ff693782ce263e/pandas-3.0.5-cp312-cp312-win_amd64.whl", hash = "sha256:80a611068e8a3ac23f7398c6c14eb46dc974e5cc9997f653e2dcfd1da74edd41", size = 9831691, upload-time = "2026-07-22T22:18:24.534Z" }, ] +[[package]] +name = "parso" +version = "0.8.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/30/4b/90c937815137d43ce71ba043cd3566221e9df6b9c805f24b5d138c9d40a7/parso-0.8.7.tar.gz", hash = "sha256:eaaac4c9fdd5e9e8852dc778d2d7405897ec510f2a298071453e5e3a07914bb1", size = 401824, upload-time = "2026-05-01T23:13:02.138Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/5d/8268b644392ee874ee82a635cd0df1773de230bde356c38de28e298392cc/parso-0.8.7-py2.py3-none-any.whl", hash = "sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c", size = 107025, upload-time = "2026-05-01T23:12:58.867Z" }, +] + +[[package]] +name = "pexpect" +version = "4.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ptyprocess", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" }, +] + [[package]] name = "pillow" version = "12.3.0" @@ -1865,11 +2034,11 @@ name = "pin" version = "4.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cmeel" }, - { name = "cmeel-boost" }, - { name = "cmeel-urdfdom" }, - { name = "coal" }, - { name = "libpinocchio" }, + { name = "cmeel", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-boost", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cmeel-urdfdom", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "coal", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "libpinocchio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/5e/e0/db25edcac11b2bf2664c5160b56287c5ec386e772c3a2a1ea40faa51afaf/pin-4.1.0.tar.gz", hash = "sha256:f59681eb1dc08d9e959c172ff2e7a34efbc464dfd38af30f1af2874a9800ee5d", size = 4441202, upload-time = "2026-07-08T14:12:12.892Z" } wheels = [ @@ -1882,10 +2051,10 @@ name = "pin-pink" version = "3.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "loop-rate-limiters" }, - { name = "numpy" }, - { name = "pin" }, - { name = "qpsolvers" }, + { name = "loop-rate-limiters", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "pin", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "qpsolvers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f3/6a/ffac93504d5ea1a201400d64f79ad17c487435937301b7eba1b4bf9731b0/pin_pink-3.3.0.tar.gz", hash = "sha256:a92018ab21e36a8c07d510ccc5cd37d16b01f1a79a6b16c29c0529388cc48dcd", size = 212281, upload-time = "2025-05-15T10:55:03.018Z" } wheels = [ @@ -1906,8 +2075,8 @@ name = "plotly" version = "7.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "narwhals" }, - { name = "packaging" }, + { name = "narwhals", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ec/9e/8894e8eae20a5b2a44aa568b1d2d80291e8eea6ce7bc75cdc7a152aef0ac/plotly-7.0.0.tar.gz", hash = "sha256:08b21f1244a97e7a1a699833c4bb2678475aa108b3f1989886ed0b038ebfd849", size = 6218668, upload-time = "2026-08-25T17:47:29.088Z" } wheels = [ @@ -1923,16 +2092,32 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] +[[package]] +name = "plum-dispatch" +version = "2.10.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "beartype", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "rich", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/dc/75/807b02f339906867de07baaecd3519fe8704df013a27ae0a57250ed461d3/plum_dispatch-2.10.1.tar.gz", hash = "sha256:93aa1ec5c4683c0777b9d7d1ccc0b31e0e82f38399116345b4ed8d0fb67cc66e", size = 250842, upload-time = "2026-09-07T17:38:44.9Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b9/c3/d8793642ce7d29ea15cc39c10185ef126a27fcb8ea230154978221deb4b2/plum_dispatch-2.10.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a5b6a2474f53b23cd07254c2ad286fc8371a3c4ed17dee72794eac9c3a6873db", size = 334557, upload-time = "2026-09-07T17:38:34.857Z" }, + { url = "https://files.pythonhosted.org/packages/41/c7/3544b2bf05aa9e1a1b45981d21da5e5d5c135fcc2da0ee1040f73512662f/plum_dispatch-2.10.1-cp312-cp312-win_amd64.whl", hash = "sha256:ae2f76ce97bcbf1d7038e7c352180cbb35c90c23ea0848e2924f35133fb0f223", size = 245830, upload-time = "2026-09-07T17:38:36.228Z" }, + { url = "https://files.pythonhosted.org/packages/55/9f/0adfb5a90d65233b764cb1b07244b72ded1db7cfc66955418544d0da2e38/plum_dispatch-2.10.1-py3-none-any.whl", hash = "sha256:dac63fd5ada8ae8045aefed127dacda0ba02db2635876b12f4e1dfaf6db73f39", size = 49430, upload-time = "2026-09-07T17:38:43.589Z" }, +] + [[package]] name = "pre-commit" version = "4.6.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cfgv" }, - { name = "identify" }, - { name = "nodeenv" }, - { name = "pyyaml" }, - { name = "virtualenv" }, + { name = "cfgv", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "identify", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "nodeenv", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyyaml", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "virtualenv", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/74/89/1f3e8e1fc3e97de0fa963495832f581f025f29471602a309e48808244292/pre_commit-4.6.2.tar.gz", hash = "sha256:8f5d7bfb021ecdbcd9d49d89847082dd24172ccde534390081a679ad046e2441", size = 198670, upload-time = "2026-08-10T22:07:18.421Z" } wheels = [ @@ -1944,7 +2129,7 @@ name = "prettytable" version = "3.18.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "wcwidth" }, + { name = "wcwidth", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/81/74/ba08d81e668ccfe8658d7520a307e63c19862c08eb4ccb26f356c5239a7a/prettytable-3.18.0.tar.gz", hash = "sha256:439217116152244369caf3d9f1caf2f9fe29b03bd79e88d2928c8e718c95d680", size = 76373, upload-time = "2026-06-22T16:07:50.174Z" } wheels = [ @@ -1956,13 +2141,25 @@ name = "proglog" version = "0.1.12" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "tqdm" }, + { name = "tqdm", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/c2/af/c108866c452eda1132f3d6b3cb6be2ae8430c97e9309f38ca9dbd430af37/proglog-0.1.12.tar.gz", hash = "sha256:361ee074721c277b89b75c061336cb8c5f287c92b043efa562ccf7866cda931c", size = 8794, upload-time = "2025-05-09T14:36:18.316Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/c1/1b/f7ea6cde25621cd9236541c66ff018f4268012a534ec31032bcb187dc5e7/proglog-0.1.12-py3-none-any.whl", hash = "sha256:ccaafce51e80a81c65dc907a460c07ccb8ec1f78dc660cfd8f9ec3a22f01b84c", size = 6337, upload-time = "2025-05-09T14:36:16.798Z" }, ] +[[package]] +name = "prompt-toolkit" +version = "3.0.53" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "wcwidth", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7d/ea/39b988c938f75cb75d7045b5c69f8bfed47ee2152c8837fb403de29d6fb8/prompt_toolkit-3.0.53.tar.gz", hash = "sha256:9ec8a0ad96d5c56148b3f914aa79c1564c3fde5d2e6b876e7bc327e353cf8fa6", size = 435492, upload-time = "2026-07-26T20:56:14.758Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/6f/84908cad2d6aa5144abcf7b42709fe4fdb459bc640ec7ac5786e7693dabc/prompt_toolkit-3.0.53-py3-none-any.whl", hash = "sha256:01c0891d7f9237d5e339f7d3e42cdae80b7534abb1c7c0e3352efba6231492f2", size = 392288, upload-time = "2026-07-26T20:56:12.512Z" }, +] + [[package]] name = "protobuf" version = "7.35.1" @@ -1970,6 +2167,7 @@ source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/da/01/9ef0afd7999eb9badb3a768b4aedd78c86d4c65cfaf1958ab276199e76b4/protobuf-7.35.1.tar.gz", hash = "sha256:ce115a26fe0c39a2c29973d914d327e516a6455464489fe3cd1e51a1b354f81a", size = 458717, upload-time = "2026-06-11T21:55:40.257Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/37/4b/dfb89eb0e652a1ff073c39a59fb5e3a83cfe9b57a2c83fa6d78270101767/protobuf-7.35.1-cp310-abi3-manylinux2014_aarch64.whl", hash = "sha256:11d6b0ec246892d85215b0a13ca6e0233cf5284b68f0ac02646427f4ff88a799", size = 328847, upload-time = "2026-06-11T21:55:34.035Z" }, + { url = "https://files.pythonhosted.org/packages/0f/58/dc12f2cd484951524af6e3382c785869b9b3fb5e52ee95ae23add53ee8f9/protobuf-7.35.1-cp310-abi3-manylinux2014_s390x.whl", hash = "sha256:b73f9489a4b8b1c9cb1f8ed951c736392592edb24b9d6819f36d2e10b171d5b4", size = 344030, upload-time = "2026-06-11T21:55:34.941Z" }, { url = "https://files.pythonhosted.org/packages/e4/be/5b3cfe508bfab6761414ff944e3366eb13be4fd71efcd69450f89ba39f43/protobuf-7.35.1-cp310-abi3-manylinux2014_x86_64.whl", hash = "sha256:74758715c53d7158fb76caf4f0cfdacc5329a4b1bb994f865d6cf302d413a1c4", size = 327130, upload-time = "2026-06-11T21:55:35.921Z" }, { url = "https://files.pythonhosted.org/packages/0a/19/8d0cb6f20a1ef7b18f1c8986ad5783f22f84cce39c6ce9a6e645ea55192e/protobuf-7.35.1-cp310-abi3-win_amd64.whl", hash = "sha256:230a75ddfc2de4806e56696ce9640c1cdfdb6543b7cfce98d42a4c0a0e7bdb87", size = 439996, upload-time = "2026-06-11T21:55:38.123Z" }, { url = "https://files.pythonhosted.org/packages/19/c7/5f7c636ec43e0c545e28d1f1db71990108306f7bdcb89f069ba97e428e7f/protobuf-7.35.1-py3-none-any.whl", hash = "sha256:4bc97768d8fe4ad6743c8a19403e314511ed9f6d13205b687e52421c023ac1b9", size = 171659, upload-time = "2026-06-11T21:55:39.155Z" }, @@ -1988,13 +2186,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" }, ] +[[package]] +name = "ptyprocess" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/20/e5/16ff212c1e452235a90aeb09066144d0c5a6a8c0834397e03f5224495c4e/ptyprocess-0.7.0.tar.gz", hash = "sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220", size = 70762, upload-time = "2020-12-28T15:15:30.155Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/a6/858897256d0deac81a172289110f31629fc4cee19b6f01283303e18c8db3/ptyprocess-0.7.0-py2.py3-none-any.whl", hash = "sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35", size = 13993, upload-time = "2020-12-28T15:15:28.35Z" }, +] + +[[package]] +name = "pure-eval" +version = "0.2.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/da/9f/abfd2959e9261dd5217ca8551d4de211ca6ab26fe9b72cf44731ff6c4442/pure_eval-0.2.4.tar.gz", hash = "sha256:260c2774686e651b79f8b8e7fc9d80b3599ea6a66334b47d5f4abb69fc2c0ea1", size = 20563, upload-time = "2026-09-10T21:41:22.836Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/18/83376915176eb058cb86470eb7396388a13350b09a8f233a79303bbcbc5b/pure_eval-0.2.4-py3-none-any.whl", hash = "sha256:96cae060a313cfaad51bb761278bfb0e62dc0248d9315a81173752dc546cd37a", size = 11893, upload-time = "2026-09-10T21:41:21.532Z" }, +] + [[package]] name = "pycollada" version = "0.9.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, - { name = "python-dateutil" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "python-dateutil", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/5a/8d/52a5364a17eb96129962cae8d3ee7658775e085ad0ba38388684ad5944e9/pycollada-0.9.3.tar.gz", hash = "sha256:c34d6dcf0fe2eba5896f71c96d37a1c0fe1a61f08440fa0cfcec3dc2895d3302", size = 110826, upload-time = "2026-01-24T15:45:23.625Z" } wheels = [ @@ -2006,10 +2222,10 @@ name = "pydantic" version = "2.13.5" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "annotated-types" }, - { name = "pydantic-core" }, - { name = "typing-extensions" }, - { name = "typing-inspection" }, + { name = "annotated-types", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pydantic-core", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-inspection", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/53/ef/fc4f868f4e2cee79f863883abffceff107875f569b848507319842d2a681/pydantic-2.13.5.tar.gz", hash = "sha256:51a9c5f7b2f8e636f04c6cada605d9b6a3bf1348fdf945a3d8869b19bba0ee08", size = 845750, upload-time = "2026-08-28T14:04:00.916Z" } wheels = [ @@ -2021,19 +2237,37 @@ name = "pydantic-core" version = "2.46.5" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/af/f9/8a06bea35ef8daf588f707784c973a7046e0034c8d8cfb08828eeffb8b75/pydantic_core-2.46.5.tar.gz", hash = "sha256:10416c15b8839ecc4ef4d0885da76da6fd0f67333a0eb8aff6d93c4b8f2910fc", size = 472262, upload-time = "2026-08-28T10:01:31.677Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/09/f0/2a8ce3849e299d44e2d2c196b6082643a3235565a735cb51db7a6261f614/pydantic_core-2.46.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4fdc8b93a41521988916eeaa271173fcca7fa0803d62f87675aac8dcec1c8e29", size = 1951772, upload-time = "2026-08-28T09:58:25.435Z" }, + { url = "https://files.pythonhosted.org/packages/87/46/ac0dc8bdd9e6048183a14eb127764e7ad9240021c17513074a4711b0e31e/pydantic_core-2.46.5-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:b98134087d9de723658d17a42c7d0da8d6e2ef08015dee7dc93889047315f5e4", size = 2031832, upload-time = "2026-08-28T09:58:27.102Z" }, + { url = "https://files.pythonhosted.org/packages/c4/c2/339de5bef7be36301a2231eaa52e62163742c2281f11b5f4892bc79785cd/pydantic_core-2.46.5-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e652ab17569c94bff5475520f907b7148b8c24036a8ebbe5cf7cf7493d28579a", size = 2208645, upload-time = "2026-08-28T09:58:28.948Z" }, + { url = "https://files.pythonhosted.org/packages/7b/a0/9ff22b797724262da14427abaed4dd1d864a139693fc5e7809114376a716/pydantic_core-2.46.5-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d925f3d9afd05a8c0fb3a1031463a8d59ebe5e2afad297e29c78be19e13b4e62", size = 2265935, upload-time = "2026-08-28T09:58:30.625Z" }, { url = "https://files.pythonhosted.org/packages/c0/a4/eb9409ec0736e50aa70a412f16c204ed149516846912f7e6724d4c73ee53/pydantic_core-2.46.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0fc5be0abd4a407e200d844b404e33639a554e7bd0d448e7b9ae181be4789ac2", size = 2066284, upload-time = "2026-08-28T09:58:32.289Z" }, + { url = "https://files.pythonhosted.org/packages/c0/02/7f6156ffc926857f1c37c07d9a388682865a81830ab6a1b637082c25e399/pydantic_core-2.46.5-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:816ff0a6550ffc06c098ccd2e0698600f9aa7da192a79eaa6f9af504a35db869", size = 2105889, upload-time = "2026-08-28T09:58:33.986Z" }, { url = "https://files.pythonhosted.org/packages/70/0a/644597d84ab400e50609c192120b85c9681c22d3a20461b9060a79be0a7a/pydantic_core-2.46.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:efd62a42486f1bda5d24cb4f63d15a3c7768375fe83d36f9417b4ad7a2fb20b3", size = 2158408, upload-time = "2026-08-28T09:58:37.38Z" }, + { url = "https://files.pythonhosted.org/packages/1e/ee/ca3b7b3a4b3769ffe9ce9432a7c9be755de9593a46d3b0d54d0409323e44/pydantic_core-2.46.5-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:2bc9419666990c06d7397831f2126a1ecc3594aaa3ff7de5bf2d066802f4e07b", size = 2309609, upload-time = "2026-08-28T09:58:39.22Z" }, { url = "https://files.pythonhosted.org/packages/ce/52/39fa1f451486019524ca685020390e7ca351832fd874530ba30c8628e6dc/pydantic_core-2.46.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:18a09e1e1011b462f2e32774f25859ef1223d5c2b0546a633cf56654710721e0", size = 2342618, upload-time = "2026-08-28T09:58:40.89Z" }, { url = "https://files.pythonhosted.org/packages/cf/c9/4c19f41b84cf6b622a72fbeed7665b25d47a187d68d47d0d430c07f23268/pydantic_core-2.46.5-cp312-cp312-win_amd64.whl", hash = "sha256:5e81740c09e310f5aa5cbd3e434a01c154d4bef93241c7877b39f211d2b78ba8", size = 2043140, upload-time = "2026-08-28T09:58:44.272Z" }, { url = "https://files.pythonhosted.org/packages/b7/13/01d40f9d07ce8a779fd6e0bd8ad4fba91309500dd67b869e2e219d261a6d/pydantic_core-2.46.5-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:347ec774390c87326a2e4929d58d3f7e8763a104d5d35f4cd595a4c952366433", size = 1967479, upload-time = "2026-08-28T10:01:05.004Z" }, { url = "https://files.pythonhosted.org/packages/fa/04/c81d4841331c2178b6fb09ae225425e110ed72d990c9fe556c4ec03d1013/pydantic_core-2.46.5-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e24d8f05fa2d28513d94e877e9c75ad66175376209b3977f916e240e623193c", size = 2111034, upload-time = "2026-08-28T10:01:07.345Z" }, ] +[[package]] +name = "pygeodesic" +version = "0.1.11" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/33/174106049bdea633e537f14fc39ebc68f2f97994591911b4e64e4870803c/pygeodesic-0.1.11.tar.gz", hash = "sha256:a9b54eb20d57f5499d8b2a4a67ece675a44c6fc8d00b11e8c14c8c99edeee5ed", size = 36275, upload-time = "2024-11-26T20:54:23.088Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6b/3d/972e2207d5845b6129f553376010b0bddecc2b1b74799e186d97e0f326d6/pygeodesic-0.1.11-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:495101cd634df7afe108a63419a864c77098c490608934c642b9d6eabc946ec1", size = 1016926, upload-time = "2024-11-26T20:54:10.904Z" }, + { url = "https://files.pythonhosted.org/packages/e6/0b/03af381ad00eaf56dde8156d48c0c4b7c5b928dd128221619d8b3cfea901/pygeodesic-0.1.11-cp312-cp312-win_amd64.whl", hash = "sha256:585e6fd35babbda2fa9b87f23d05e0ec26e1e416e069997ed137ac04b94f05b9", size = 1335932, upload-time = "2024-11-26T20:54:12.072Z" }, +] + [[package]] name = "pyglet" version = "2.1.16" @@ -2086,7 +2320,7 @@ name = "pyquaternion" version = "0.9.9" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, + { name = "numpy", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/7d/0d/3d092aa20efaedacb89c3221a92c6491be5b28f618a2c36b52b53e7446c2/pyquaternion-0.9.9.tar.gz", hash = "sha256:b1f61af219cb2fe966b5fb79a192124f2e63a3f7a777ac3cadf2957b1a81bea8", size = 15530, upload-time = "2020-10-05T01:31:30.327Z" } wheels = [ @@ -2098,11 +2332,11 @@ name = "pytest" version = "9.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "iniconfig" }, - { name = "packaging" }, - { name = "pluggy" }, - { name = "pygments" }, + { name = "colorama", marker = "platform_machine == 'AMD64' and sys_platform == 'win32'" }, + { name = "iniconfig", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pluggy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pygments", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } wheels = [ @@ -2114,7 +2348,7 @@ name = "python-dateutil" version = "2.9.0.post0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "six" }, + { name = "six", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } wheels = [ @@ -2126,7 +2360,7 @@ name = "python-discovery" version = "1.5.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "filelock" }, + { name = "filelock", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/38/b7/ac44da2cf0e53ada0e419033c2d058219c95dc1403126f163304c9e814b1/python_discovery-1.5.2.tar.gz", hash = "sha256:45fd4f20a4e3f9b7bf2e0817870bc8e3b320a19658da177af800768c82dbf354", size = 82350, upload-time = "2026-08-12T14:05:26.419Z" } wheels = [ @@ -2149,6 +2383,7 @@ source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" }, + { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" }, { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" }, { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" }, { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" }, @@ -2160,8 +2395,8 @@ name = "qpsolvers" version = "4.13.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, - { name = "scipy" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "scipy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/d1/aa/4d60a7065de30f07d7ead935eed364cf94fb0ad5607ddf1461f2bdf7ba17/qpsolvers-4.13.0.tar.gz", hash = "sha256:e86c4c16bf7c16fdbb8e6c0e4050bc1bfef72a25755211be66a492ac4c939a1c", size = 77317, upload-time = "2026-07-19T07:46:03.087Z" } wheels = [ @@ -2173,9 +2408,9 @@ name = "referencing" version = "0.37.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "attrs" }, - { name = "rpds-py" }, - { name = "typing-extensions" }, + { name = "attrs", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "rpds-py", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } wheels = [ @@ -2189,8 +2424,14 @@ source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/19/c1/6b30b775c7bcc6cf6506a4d4741c2123e8d99cd50f3fe8cbd731f5fef526/regex-2026.9.3.tar.gz", hash = "sha256:aabd43208e335f4c3f0b56de3464b066dd425983a58f6eeb5738bcd7465403db", size = 416720, upload-time = "2026-09-01T00:53:43.821Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b4/4987bf0f17604669b4ea5aef219886d0a73188c4716ff3a7d275d4d15c15/regex-2026.9.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:233662cf8cfdfe3c0e58aa8f7bbefc579b5be0ac34546f123c159804179e8687", size = 796101, upload-time = "2026-09-01T00:50:32.486Z" }, + { url = "https://files.pythonhosted.org/packages/0b/95/2a9ab02a68c8a61dc0b4882ed643b1a95740d9dc291dc26c77d19af79691/regex-2026.9.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7d2eed2e4d231278a2ccab3f4bfa2c1e39855f336475f7756a281d767d2b1753", size = 865435, upload-time = "2026-09-01T00:50:34.171Z" }, + { url = "https://files.pythonhosted.org/packages/04/92/0570d41559b446c97c1148cb9ebc1df09f2949b03c7c9bfee09976b3465f/regex-2026.9.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5e674cecb61cb160be392da07fd8a71509ef927f437fbf3215432692ed385151", size = 911828, upload-time = "2026-09-01T00:50:35.72Z" }, { url = "https://files.pythonhosted.org/packages/4b/8b/9cc6d4123033f7cb82df6cd8ce19eb0fc18a964afe060a03c9b26757c9f3/regex-2026.9.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:665207e41bacd435db001099eeab44103197c2c1a729d73ade74688a905ed4ce", size = 801965, upload-time = "2026-09-01T00:50:37.701Z" }, + { url = "https://files.pythonhosted.org/packages/c9/98/39262e91aa87a67c82cbe90a0df4c3d382c7a44811fe80067904085211b4/regex-2026.9.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7a7ddc9a8ca1795166a1ca80364b8ce74187fc210e112d3fb048b711b934f36c", size = 776192, upload-time = "2026-09-01T00:50:39.57Z" }, { url = "https://files.pythonhosted.org/packages/24/e9/3bb93fe4ee4b6f8ce7ba69b527c4a63cfa3393fc425ab26486041fe441c8/regex-2026.9.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e3037d02425863ce9501afbaa04ba967162810004bacde39a53ea9a5b740eb32", size = 785053, upload-time = "2026-09-01T00:50:41.156Z" }, + { url = "https://files.pythonhosted.org/packages/f9/05/31d5bc2553a700c0dfc6b5b6a13c61cdcd1210fde1e304cfa18a33f138b2/regex-2026.9.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:3de4eab8c763393b75bbb26f81934ab2cc8794f48f79e90622e3ab7ea57f3d14", size = 860546, upload-time = "2026-09-01T00:50:42.746Z" }, + { url = "https://files.pythonhosted.org/packages/65/a3/2e1e854d80becda0f061093805bbfc037a5849448f46d0a2b71a070d45e2/regex-2026.9.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:98620c9c4c22568ad70f57b80527c780b6f8fd26e36507bf8e2273262a228275", size = 765841, upload-time = "2026-09-01T00:50:44.5Z" }, + { url = "https://files.pythonhosted.org/packages/6a/d6/43d02948cedde2e8476ac893ea02755ee5ee1b21c531fda92d80e114f0bc/regex-2026.9.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:0b1ba3aaaf5776de473ee16625ac60ac195abb0343afb273575a8201d99be089", size = 852147, upload-time = "2026-09-01T00:50:46.474Z" }, { url = "https://files.pythonhosted.org/packages/21/ff/adb4e2d08afe8f4c6df004d94604257e1f72af7ba328af7715601585aba4/regex-2026.9.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:56d8659c65166641d8f1b5efccc391c62c8a899eff4d528b981cc62b7b402a4b", size = 789761, upload-time = "2026-09-01T00:50:48.749Z" }, { url = "https://files.pythonhosted.org/packages/d5/49/4c40cf722d84d60e807a08ef4c3f579216bf97df60c4a1b10be49655d302/regex-2026.9.3-cp312-cp312-win_amd64.whl", hash = "sha256:1ba1dbbb93c5c5629c1861763aec5bfa9f05ad24ef450694130e25029ce7bc36", size = 277773, upload-time = "2026-09-01T00:50:51.963Z" }, ] @@ -2200,10 +2441,10 @@ name = "requests" version = "2.34.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "certifi" }, - { name = "charset-normalizer" }, - { name = "idna" }, - { name = "urllib3" }, + { name = "certifi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "charset-normalizer", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "idna", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "urllib3", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } wheels = [ @@ -2230,15 +2471,15 @@ wheels = [ [[package]] name = "rich" -version = "14.3.4" +version = "15.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "markdown-it-py" }, - { name = "pygments" }, + { name = "markdown-it-py", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pygments", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e9/67/cae617f1351490c25a4b8ac3b8b63a4dda609295d8222bad12242dfdc629/rich-14.3.4.tar.gz", hash = "sha256:817e02727f2b25b40ef56f5aa2217f400c8489f79ca8f46ea2b70dd5e14558a9", size = 230524, upload-time = "2026-04-11T02:57:45.419Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b3/76/6d163cfac87b632216f71879e6b2cf17163f773ff59c00b5ff4900a80fa3/rich-14.3.4-py3-none-any.whl", hash = "sha256:07e7adb4690f68864777b1450859253bed81a99a31ac321ac1817b2313558952", size = 310480, upload-time = "2026-04-11T02:57:47.484Z" }, + { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, ] [[package]] @@ -2247,7 +2488,11 @@ version = "2026.6.3" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/aa/2a/9618a122aeb2a169a28b03889a2995fe297588964333d4a7d67bdf46e147/rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4", size = 64051, upload-time = "2026-06-30T07:17:53.009Z" } wheels = [ + { url = "https://files.pythonhosted.org/packages/1c/ca/9c5de382225234ceb37b1844ebdb140db12b2a278bb9efe2fcd19f6c82ce/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f56f1695bc5c0871cbc33dc0130fcf503aab0c57dcc5a6700a4f49eba4f2652e", size = 375067, upload-time = "2026-06-30T07:15:18.952Z" }, + { url = "https://files.pythonhosted.org/packages/87/dc/863f69d1bf04ade34b7fe0d59b9fdf6f0135fe2d7cbca74f1d665589559d/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:270b293dae9058fc9fcedab50f13cebf46fb8ed1d1d54e0521a9da5d6b211975", size = 490509, upload-time = "2026-06-30T07:15:20.434Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ef/eac16a12048b45ec7c7fa94f2be3438a5f26bf9cc8580b18a1cfd609b7f6/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:127565fead0a10943b282957bd5447804ff3160ad79f2ad2635e6d249e380680", size = 382754, upload-time = "2026-06-30T07:15:21.831Z" }, { url = "https://files.pythonhosted.org/packages/04/8f/d2f3f532616be4d06c316ef119683e832bd3d41e112bf3a88f4151c95b17/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ecabd69db66de867690f9797f2f8fa27ba501bbc24540cbdbdc649cd15888ba6", size = 366189, upload-time = "2026-06-30T07:15:23.371Z" }, + { url = "https://files.pythonhosted.org/packages/e3/29/41a7b0e98a4b44cd676ab7598419623373eb43b20be68c084935c1a8cf88/rpds_py-2026.6.3-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:58eadac9cd119677b60e1cf8ac4052f35949d71b8a9e5556efccbe82533cf22a", size = 377750, upload-time = "2026-06-30T07:15:24.659Z" }, { url = "https://files.pythonhosted.org/packages/f1/31/774212ed989c62f7f310220089f9b0a3fb8f40f5443d1727abd5d9f52bc9/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a214c993455f99a89aaeadc9b21241900037adc9d97203e374d75513c5911822", size = 573030, upload-time = "2026-06-30T07:15:30.553Z" }, { url = "https://files.pythonhosted.org/packages/04/3a/f0ee4d4dde9d3b69dedf1b5f74e7a40017046d55052d173e418c6a94f960/rpds_py-2026.6.3-cp312-cp312-win_amd64.whl", hash = "sha256:2c958bf94822e9290a40aaf2a822d4bc5c88099093e3948ad6c571eca9272e5f", size = 220394, upload-time = "2026-06-30T07:15:33.359Z" }, ] @@ -2257,13 +2502,13 @@ name = "rsl-rl-lib" version = "5.5.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "gitpython" }, - { name = "numpy" }, - { name = "onnx" }, - { name = "onnxscript" }, - { name = "tensorboard" }, - { name = "tensordict" }, - { name = "torch" }, + { name = "gitpython", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "onnx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "onnxscript", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tensorboard", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tensordict", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/97/0e/142a31e8124255ec9276516c49c6fbe1497f2146ea384a92b81d23e3c525/rsl_rl_lib-5.5.1.tar.gz", hash = "sha256:50129065b35c69735ea197343321145a400af8c1b5fe9a28116fdaf1890fab43", size = 68077, upload-time = "2026-09-09T11:28:51.656Z" } wheels = [ @@ -2289,9 +2534,15 @@ version = "0.16.3" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/61/b3/3213589383f8f1b3938781bd1278713f6d18621a14992b3e81fefb8a5ef9/ruff-0.16.3.tar.gz", hash = "sha256:e76d33a347661a84b5be6d043d0347fdc745dfdcf825a8f4fed64b5e26eebdf2", size = 4891904, upload-time = "2026-08-13T15:17:13.381Z" } wheels = [ + { url = "https://files.pythonhosted.org/packages/bf/96/493770daebd68c0a67f1549fdf519f53be51fc435186c0585bcc272fd76c/ruff-0.16.3-py3-none-linux_armv6l.whl", hash = "sha256:0c5710e247a58a4521e66e124ba9a74655b414f61ba3a2e9e3811e11098f48f7", size = 10902799, upload-time = "2026-08-13T15:16:27.382Z" }, { url = "https://files.pythonhosted.org/packages/92/32/2201fa49ba1f6c101ee321e83f051ac7a4b8d07b0ef6b4d3f2772b302275/ruff-0.16.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9e0b1da805eb043654645d74d5de1e5ce2edc686e40790d2b86f56d71cc06a84", size = 10668771, upload-time = "2026-08-13T15:16:35.65Z" }, + { url = "https://files.pythonhosted.org/packages/c3/66/4afc5c8363bd04d45effce1b7c8713ca037d7a6740b7451a2403a6e3a972/ruff-0.16.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a37bdea0bbe21780f590bf437d6412c8c4e1b6cd010f91a65c2c40c5e5f5f870", size = 10699568, upload-time = "2026-08-13T15:16:38.195Z" }, + { url = "https://files.pythonhosted.org/packages/67/0b/00ecbceb99a263af7b12f6f05ac3c92bc47b905e91adc3f207a836e3bc01/ruff-0.16.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2c18c5a101eb540010638cc1ff3c84944d3adb3df62b8d98ca8f22ba484d3413", size = 12311728, upload-time = "2026-08-13T15:16:43.564Z" }, + { url = "https://files.pythonhosted.org/packages/54/b2/b7b3bb54f4d3f7db504e476ad4ab8de530dceebe2c061384b2757ee419e8/ruff-0.16.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8457c44f15033c85ddbb77b15d451df9e24e4bd03b628396dd3610cedc3b8f82", size = 11699896, upload-time = "2026-08-13T15:16:46.209Z" }, { url = "https://files.pythonhosted.org/packages/c7/30/4c468429ac195addc5ee1b717b6ab1b66632786737ca3b2ed3443fb0c26a/ruff-0.16.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:294b95c4ae0cda9388525c2047778aa758d6b8d4bb876fd4e9eaa3ebc92343eb", size = 11058736, upload-time = "2026-08-13T15:16:48.823Z" }, + { url = "https://files.pythonhosted.org/packages/43/67/7a113cdaddf24b64d7f75b1242a99d04c82fcef4f6921fdbb832beaffb5f/ruff-0.16.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:3d0c7c40c87c2a820509c31ba007968da6e1306468c067b2d82fbfdbcd0e8474", size = 11586911, upload-time = "2026-08-13T15:16:51.913Z" }, { url = "https://files.pythonhosted.org/packages/f1/c1/2e66f24c0f3ead25a5e660111778685e505e5da353c82802bf49f0cbe7b9/ruff-0.16.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:9f738c0fdfa8eed0b2ce7fb27ee7258208a92a68d7949e62aa15164bc7b389da", size = 10954265, upload-time = "2026-08-13T15:16:54.763Z" }, + { url = "https://files.pythonhosted.org/packages/c2/ba/4cee23bf52cba9a058d3726de623624daf50ef9638868edd86f4126157f6/ruff-0.16.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:fb785f0be25abe69d320415cd4f833b59e17ba7613d9ba6a958023b6bceb0a50", size = 10709886, upload-time = "2026-08-13T15:16:57.339Z" }, { url = "https://files.pythonhosted.org/packages/35/85/7795f6e817af050e7517bf3e7aa9b061cce70ef33d280aad902c956c1ecf/ruff-0.16.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:a2d85c02f9b8e165d85e6779184d38c4132de12603dab59c51c28e22584f9e4d", size = 11626910, upload-time = "2026-08-13T15:17:03.299Z" }, { url = "https://files.pythonhosted.org/packages/b2/99/e2a2bfc4fbf0a1e8a916bc9ebe6fe6c58cc34c28e0ffc6ce281d572d1c2e/ruff-0.16.3-py3-none-win_amd64.whl", hash = "sha256:e80a7d69ca2a6d1c4d352ec91458cdca6e56c83cdbcabd93e4abe1e53591d948", size = 11445993, upload-time = "2026-08-13T15:17:08.353Z" }, ] @@ -2303,22 +2554,50 @@ source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/09/7d/65a7de0af421317bb36a067241e4235fff194eed60b961ed6d3f59a3fc60/safetensors-0.8.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235", size = 502844, upload-time = "2026-06-09T07:52:07.624Z" }, + { url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823, upload-time = "2026-06-09T07:52:09.565Z" }, + { url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461, upload-time = "2026-06-09T07:52:11.128Z" }, + { url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148, upload-time = "2026-06-09T07:52:13.603Z" }, { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" }, + { url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832, upload-time = "2026-06-09T07:52:12.37Z" }, { url = "https://files.pythonhosted.org/packages/2a/43/bf38443278eab4b1be1fce2931e2b012ad9cb7df52ada751d0aab8f7659a/safetensors-0.8.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4", size = 678670, upload-time = "2026-06-09T07:52:20.032Z" }, + { url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679, upload-time = "2026-06-09T07:52:21.322Z" }, { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" }, { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" }, ] +[[package]] +name = "scikit-image" +version = "0.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "imageio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "lazy-loader", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "networkx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pillow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "scipy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tifffile", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a1/b4/2528bb43c67d48053a7a649a9666432dc307d66ba02e3a6d5c40f46655df/scikit_image-0.26.0.tar.gz", hash = "sha256:f5f970ab04efad85c24714321fcc91613fcb64ef2a892a13167df2f3e59199fa", size = 22729739, upload-time = "2025-12-20T17:12:21.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/2b/c70120a6880579fb42b91567ad79feb4772f7be72e8d52fec403a3dde0c6/scikit_image-0.26.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4c717490cec9e276afb0438dd165b7c3072d6c416709cc0f9f5a4c1070d23a44", size = 13084214, upload-time = "2025-12-20T17:10:57.468Z" }, + { url = "https://files.pythonhosted.org/packages/f4/a2/70401a107d6d7466d64b466927e6b96fcefa99d57494b972608e2f8be50f/scikit_image-0.26.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7df650e79031634ac90b11e64a9eedaf5a5e06fcd09bcd03a34be01745744466", size = 13561683, upload-time = "2025-12-20T17:10:59.49Z" }, + { url = "https://files.pythonhosted.org/packages/13/a5/48bdfd92794c5002d664e0910a349d0a1504671ef5ad358150f21643c79a/scikit_image-0.26.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cefd85033e66d4ea35b525bb0937d7f42d4cdcfed2d1888e1570d5ce450d3932", size = 14112147, upload-time = "2025-12-20T17:11:02.083Z" }, + { url = "https://files.pythonhosted.org/packages/ee/b5/ac71694da92f5def5953ca99f18a10fe98eac2dd0a34079389b70b4d0394/scikit_image-0.26.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3f5bf622d7c0435884e1e141ebbe4b2804e16b2dd23ae4c6183e2ea99233be70", size = 14661625, upload-time = "2025-12-20T17:11:04.528Z" }, + { url = "https://files.pythonhosted.org/packages/23/4d/a3cc1e96f080e253dad2251bfae7587cf2b7912bcd76fd43fd366ff35a87/scikit_image-0.26.0-cp312-cp312-win_amd64.whl", hash = "sha256:abed017474593cd3056ae0fe948d07d0747b27a085e92df5474f4955dd65aec0", size = 11911059, upload-time = "2025-12-20T17:11:06.61Z" }, +] + [[package]] name = "scikit-learn" version = "1.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "joblib" }, - { name = "narwhals" }, - { name = "numpy" }, - { name = "scipy" }, - { name = "threadpoolctl" }, + { name = "joblib", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "narwhals", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "scipy", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "threadpoolctl", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/fa/6f/37092bdb25f712817231799fc5674d8e704066a8a70c1d2d40517e18b4ab/scikit_learn-1.9.0.tar.gz", hash = "sha256:8833266989d3a5110178a9fae30783675460724d0e1efb13b14901d2c660c557", size = 7750767, upload-time = "2026-06-02T11:54:32.706Z" } wheels = [ @@ -2331,7 +2610,7 @@ name = "scipy" version = "1.18.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a7/25/c2700dfaf6442b4effaa91af24ebce5dc9d31bb4a69706313aae70d72cd0/scipy-1.18.0.tar.gz", hash = "sha256:67b2ad2ad54c72ca6d04975a9b2df8c3638c34ddd5b28738e94fc2b57929d378", size = 30774447, upload-time = "2026-06-19T15:01:43.456Z" } wheels = [ @@ -2347,8 +2626,8 @@ name = "sentry-sdk" version = "2.72.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "certifi" }, - { name = "urllib3" }, + { name = "certifi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "urllib3", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/26/c1/d2bbb2b03bdc2ef14b35e02b647b8489156c50b6e0b8bacc5fa303902e23/sentry_sdk-2.72.0.tar.gz", hash = "sha256:0d2ffbc28ee2e63cbaf3d015e93b448cffcc3ef3be03a44704ad36ade72faa95", size = 1069699, upload-time = "2026-10-12T13:08:11.195Z" } wheels = [ @@ -2369,7 +2648,7 @@ name = "shapely" version = "2.1.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/4d/bc/0989043118a27cccb4e906a46b7565ce36ca7b57f5a18b78f4f1b0f72d9d/shapely-2.1.2.tar.gz", hash = "sha256:2ed4ecb28320a433db18a5bf029986aa8afcfd740745e78847e330d5d94922a9", size = 315489, upload-time = "2025-09-24T13:51:41.432Z" } wheels = [ @@ -2407,13 +2686,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c1/d4/59e74daffcb57a07668852eeeb6035af9f32cbfd7a1d2511f17d2fe6a738/smmap-5.0.3-py3-none-any.whl", hash = "sha256:c106e05d5a61449cf6ba9a1e650227ecfb141590d2a98412103ff35d89fc7b2f", size = 24390, upload-time = "2026-03-09T03:43:24.361Z" }, ] +[[package]] +name = "stack-data" +version = "0.6.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "asttokens", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "executing", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pure-eval", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/28/e3/55dcc2cfbc3ca9c29519eb6884dd1415ecb53b0e934862d3559ddcb7e20b/stack_data-0.6.3.tar.gz", hash = "sha256:836a778de4fec4dcd1dcd89ed8abff8a221f58308462e1c4aa2a3cf30148f0b9", size = 44707, upload-time = "2023-09-30T13:58:05.479Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl", hash = "sha256:d5558e0c25a4cb0853cddad3d77da9891a08cb85dd9f9f91b9f8cd66e511e695", size = 24521, upload-time = "2023-09-30T13:58:03.53Z" }, +] + [[package]] name = "starlette" version = "1.7.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, - { name = "typing-extensions" }, + { name = "anyio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/7b/2b/3850dc6bf7ef71b088962eba31dafc6cffd2f96e577ebb0bb316df96da3e/starlette-1.7.0.tar.gz", hash = "sha256:c79f74ea63cff761804fbbfb182f1e0b440c2d07b164d24700c5a1bab5d6ff5d", size = 2736246, upload-time = "2026-09-23T07:30:26.35Z" } wheels = [ @@ -2425,7 +2718,7 @@ name = "sympy" version = "1.14.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "mpmath" }, + { name = "mpmath", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } wheels = [ @@ -2437,16 +2730,16 @@ name = "tensorboard" version = "2.21.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "absl-py" }, - { name = "grpcio" }, - { name = "markdown" }, - { name = "numpy" }, - { name = "packaging" }, - { name = "pillow" }, - { name = "protobuf" }, - { name = "setuptools" }, - { name = "tensorboard-data-server" }, - { name = "werkzeug" }, + { name = "absl-py", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "grpcio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "markdown", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pillow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "protobuf", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "setuptools", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tensorboard-data-server", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "werkzeug", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/37/4b/cd2eec9642781a8f5b2fb9994e3933a7b259ab18e9d49aeede9b5acf6311/tensorboard-2.21.0-py3-none-any.whl", hash = "sha256:7279316dcb6bd5bc391d623dea841531299cde1887310e8133bc34a996d32255", size = 5516204, upload-time = "2026-06-29T20:48:04.472Z" }, @@ -2466,13 +2759,13 @@ name = "tensordict" version = "0.14.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cloudpickle" }, - { name = "importlib-metadata" }, - { name = "numpy" }, - { name = "orjson" }, - { name = "packaging" }, - { name = "pyvers" }, - { name = "torch" }, + { name = "cloudpickle", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "importlib-metadata", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "orjson", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyvers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/b4/da/2fe7c405b954e9ceb6ae4142574af9cda0e0486b2f12f4f992389c07cfc8/tensordict-0.14.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:ace655721c5b36108b13d1826ad741ad72ed50984444ffade6dc9ad8558014e1", size = 588429, upload-time = "2026-08-14T21:27:53.784Z" }, @@ -2489,20 +2782,37 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/32/d5/f9a850d79b0851d1d4ef6456097579a9005b31fea68726a4ae5f2d82ddd9/threadpoolctl-3.6.0-py3-none-any.whl", hash = "sha256:43a0b8fd5a2928500110039e43a5eed8480b918967083ea48dc3ab9f13c4a7fb", size = 18638, upload-time = "2025-03-13T13:49:21.846Z" }, ] +[[package]] +name = "tifffile" +version = "2026.11.16" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d6/e1/f09384869bcf78bae3a794a86d8a90753fb2a6f4646c07ec941ff629cd33/tifffile-2026.11.16.tar.gz", hash = "sha256:d9c246d464f1c3ca9ab62c5225b3ff45578f33629029dbbd9f62f4e901702726", size = 462802, upload-time = "2026-11-17T03:35:19.648Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cf/3a/483491be6f7eb070d1c22b1182bbbc0243e85bf5903fafe3f80b6aeb3dba/tifffile-2026.11.16-py3-none-any.whl", hash = "sha256:d2103c2537f185868f0a880eceba590b316aa1981bd76d91028e5f2eb0e1a6e6", size = 279737, upload-time = "2026-11-17T03:35:18.375Z" }, +] + [[package]] name = "tokenizers" -version = "0.22.2" +version = "0.23.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "huggingface-hub" }, + { name = "huggingface-hub", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115, upload-time = "2026-01-05T10:45:15.988Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/7c/2cabb2174e772636683008f2c5621949b645da7d303c596589e84516a184/tokenizers-0.23.3.tar.gz", hash = "sha256:cded33237c77caeef62944d32aa9a7ef42bdce2b3497e18d137e072a8c4be438", size = 385286, upload-time = "2026-10-09T10:16:55.759Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d6/84/7990e799f1309a8b87af6b948f31edaa12a3ed22d11b352eaf4f4b2e5753/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2249487018adec45d6e3554c71d46eb39fa8ea67156c640f7513eb26f318cec7", size = 3290736, upload-time = "2026-01-05T10:40:32.165Z" }, - { url = "https://files.pythonhosted.org/packages/2e/76/932be4b50ef6ccedf9d3c6639b056a967a86258c6d9200643f01269211ca/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:369cc9fc8cc10cb24143873a0d95438bb8ee257bb80c71989e3ee290e8d72c67", size = 3274982, upload-time = "2026-01-05T10:40:58.331Z" }, - { url = "https://files.pythonhosted.org/packages/1d/28/5f9f5a4cc211b69e89420980e483831bcc29dade307955cc9dc858a40f01/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:29c30b83d8dcd061078b05ae0cb94d3c710555fbb44861139f9f83dcca3dc3e4", size = 9478245, upload-time = "2026-01-05T10:41:04.053Z" }, - { url = "https://files.pythonhosted.org/packages/05/a1/d62dfe7376beaaf1394917e0f8e93ee5f67fea8fcf4107501db35996586b/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:38337540fbbddff8e999d59970f3c6f35a82de10053206a7562f1ea02d046fa5", size = 10033429, upload-time = "2026-01-05T10:45:14.333Z" }, - { url = "https://files.pythonhosted.org/packages/65/71/0670843133a43d43070abeb1949abfdef12a86d490bea9cd9e18e37c5ff7/tokenizers-0.22.2-cp39-abi3-win_amd64.whl", hash = "sha256:c9ea31edff2968b44a88f97d784c2f16dc0729b8b143ed004699ebca91f05c48", size = 2747786, upload-time = "2026-01-05T10:45:18.411Z" }, + { url = "https://files.pythonhosted.org/packages/15/fc/ae987741829b1cd547668c4c94be732ae3eefd1d74344e64c3d2ca714acd/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec82e80e65a862275b97c3d90b7a523df8d9519ee48aeb4e9625b2cc909274e0", size = 3519944, upload-time = "2026-10-09T10:00:55.885Z" }, + { url = "https://files.pythonhosted.org/packages/1c/da/cc8f6c030afaf05fbddc608158fbb761dca46913cbeba6b112e59fc82e2a/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c64a0713180ff16829d4e7f39a658b77ea11443af4e1aa46523692943c9b1414", size = 3397695, upload-time = "2026-10-09T10:00:57.444Z" }, + { url = "https://files.pythonhosted.org/packages/60/93/eee007ac2fcbf4ecfce7fbc354826cf3611f56bdb886f3e91b1f7dd06b8f/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2a89614730d7b80940a5d2ed9320e1ec8add5a745c6151d8d05071b7215505b6", size = 4018598, upload-time = "2026-10-09T10:01:02.05Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f9/0c96c4739461fce9d8d865b416728081bf6230022d7163bd6244f35f4b31/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e88646b8580c5ad7f4361477f1298e9cc01771a1ee9aecfe32c47b8ff614cc38", size = 3602442, upload-time = "2026-10-09T10:01:03.77Z" }, + { url = "https://files.pythonhosted.org/packages/3a/40/6706b82693715581457c6d5423eaa7faae576bb0526c5738a57085eb4449/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:376851d22bcf9d650a5c3090bb83e6cf9e895fbf0595369fa4cd43c1f69b5f87", size = 3396193, upload-time = "2026-10-09T10:01:05.48Z" }, + { url = "https://files.pythonhosted.org/packages/fe/0c/85946de40e25b7364b8f1bcf56def129069acd5bb364b7c86a32919e1a23/tokenizers-0.23.3-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:bf501c40b72d2d5c8623620210430e9cac1ce47a46e45b34107b70a1557d46b0", size = 3553483, upload-time = "2026-10-09T10:01:07.387Z" }, + { url = "https://files.pythonhosted.org/packages/f1/6b/8d615d92cad1d511ca5ab188d1c7c167f0b3d295cc0d96207f9f82d486d8/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:114e2b55ed177179d59f4ab98200a4471e11e78f9e4b5a922d146740f96fcf52", size = 9972248, upload-time = "2026-10-09T10:01:09.437Z" }, + { url = "https://files.pythonhosted.org/packages/c9/7d/a922e37ddd58d1b463bbc2ad08120c8f59c60b814cd353519a116b24f8ba/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:d3407fb7b9c4d75dd68850ffd7180bc0a5d2dbaf0762d888e612f31fec3f9c6b", size = 9802957, upload-time = "2026-10-09T10:01:11.869Z" }, + { url = "https://files.pythonhosted.org/packages/26/e5/065625317690ea3548d834dad81f48ea1fd32e4964610e658e195d7fe28e/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e05ab7baf7f47b406a95fea6f3b0a484b2ddcd9e1d14b68844c457eb755085a3", size = 10266026, upload-time = "2026-10-09T10:16:33.054Z" }, + { url = "https://files.pythonhosted.org/packages/d1/6c/24f074c9a0efb98e61b20aafe6b2641922d5db24e447d5d6daffd9e17555/tokenizers-0.23.3-cp310-abi3-win_amd64.whl", hash = "sha256:1f0823bb00c5fdc98e487354d54dd55a03848d61a1a0bf29a68c77f24f3b26c3", size = 2872101, upload-time = "2026-10-09T10:16:37.533Z" }, ] [[package]] @@ -2510,20 +2820,20 @@ name = "torch" version = "2.11.0+cu130" source = { registry = "https://download.pytorch.org/whl/cu130" } dependencies = [ - { name = "cuda-bindings", marker = "sys_platform != 'win32'" }, - { name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform != 'win32'" }, - { name = "filelock" }, - { name = "fsspec" }, - { name = "jinja2" }, - { name = "networkx" }, - { name = "nvidia-cudnn-cu13", marker = "sys_platform != 'win32'" }, - { name = "nvidia-cusparselt-cu13", marker = "sys_platform != 'win32'" }, - { name = "nvidia-nccl-cu13", marker = "sys_platform != 'win32'" }, - { name = "nvidia-nvshmem-cu13", marker = "sys_platform != 'win32'" }, - { name = "setuptools" }, - { name = "sympy" }, - { name = "triton", marker = "sys_platform != 'win32'" }, - { name = "typing-extensions" }, + { name = "cuda-bindings", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "filelock", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "fsspec", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "jinja2", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "networkx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "nvidia-cudnn-cu13", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cusparselt-cu13", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-nccl-cu13", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-nvshmem-cu13", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "setuptools", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "sympy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "triton", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wheels = [ { url = "https://download-r2.pytorch.org/whl/cu130/torch-2.11.0%2Bcu130-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:252f237d417fac3ba59b1635815c1f035a8241f2af038f2c076ed430932d89f1", upload-time = "2026-04-27T20:01:46Z" }, @@ -2536,9 +2846,9 @@ name = "torchvision" version = "0.26.0+cu130" source = { registry = "https://download.pytorch.org/whl/cu130" } dependencies = [ - { name = "numpy" }, - { name = "pillow" }, - { name = "torch" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pillow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wheels = [ { url = "https://download-r2.pytorch.org/whl/cu130/torchvision-0.26.0%2Bcu130-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:e2b39db78be674ee4ce7e921f54b70e5c281594c9267d981c061684ed38df936", upload-time = "2026-03-23T15:36:26Z" }, @@ -2551,7 +2861,7 @@ name = "tqdm" version = "4.70.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "colorama", marker = "platform_machine == 'AMD64' and sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/21/3b/6c24bec5be5e743ffd99576daa5cc077722fc7d5bbc00bd133fa0c698dc6/tqdm-4.70.0.tar.gz", hash = "sha256:55b0b0dbd97462d06ebee91e4dac24ed4d4702be82b24f07e6c1d27e08cea220", size = 795438, upload-time = "2026-07-27T11:33:15.271Z" } wheels = [ @@ -2569,22 +2879,22 @@ wheels = [ [[package]] name = "transformers" -version = "5.10.4" +version = "5.19.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "huggingface-hub" }, - { name = "numpy" }, - { name = "packaging" }, - { name = "pyyaml" }, - { name = "regex" }, - { name = "safetensors" }, - { name = "tokenizers" }, - { name = "tqdm" }, - { name = "typer" }, + { name = "huggingface-hub", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyyaml", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "regex", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "safetensors", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tokenizers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tqdm", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typer", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f7/5d/1df789ca27a436ce09de67c8fee6acd2a528d34c28685991f8203e5418ae/transformers-5.10.4.tar.gz", hash = "sha256:de37741509e64ccb88f7f5708beaf5b1914df447f5fe659f9c0fd95950413168", size = 8799021, upload-time = "2026-06-15T17:28:29.306Z" } +sdist = { url = "https://files.pythonhosted.org/packages/65/4c/70012ed0795235fb6bd7806fafd4a1842f03e49ebbfa3bb9580e451948ce/transformers-5.19.0.tar.gz", hash = "sha256:87f38dd25e4521151b97e94520ac457f44a0ae8a8358a5b112daff6c64a822d6", size = 10032022, upload-time = "2026-10-06T16:39:00.229Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d7/f1/d66881f28d3e64002a21d043c7c8db306c0ad5a711c85337ff551bfbc040/transformers-5.10.4-py3-none-any.whl", hash = "sha256:8c5b99b141b53619435a76629b0284f04d27ff46d788b463fc0ecb23b8ff130e", size = 11004075, upload-time = "2026-06-15T17:28:26.21Z" }, + { url = "https://files.pythonhosted.org/packages/b9/59/1e7f1212c215c73690ae6cab4678efe1555ff985953e145d88cc212859b0/transformers-5.19.0-py3-none-any.whl", hash = "sha256:afcd2dd5f603ed28c1e1fcb00a338ccbb4ef5f878ed289635df8b58187afb518", size = 12599123, upload-time = "2026-10-06T16:38:56.794Z" }, ] [[package]] @@ -2592,7 +2902,7 @@ name = "trimesh" version = "5.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a8/45/5b9943631f265073bb96ca4cc2a9de05d151cd8c1a6896fcbaac132a1355/trimesh-5.0.0.tar.gz", hash = "sha256:0195003198baaf2550aebe612254ba2f01c385cec46c37ecc5beca8291f79a13", size = 864019, upload-time = "2026-08-01T00:05:25.042Z" } wheels = [ @@ -2613,10 +2923,10 @@ name = "typer" version = "0.27.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "annotated-doc" }, - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "rich" }, - { name = "shellingham" }, + { name = "annotated-doc", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "colorama", marker = "platform_machine == 'AMD64' and sys_platform == 'win32'" }, + { name = "rich", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "shellingham", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/03/51/d33db42cc72ffd8c30777547b42d01f0cbf9d95a770457698d0174b3ed71/typer-0.27.3.tar.gz", hash = "sha256:d0396f770a560ab1b0a8504e13b5f254b728cedb05c61cf0359e944e50ce8901", size = 205303, upload-time = "2026-10-06T17:24:16.61Z" } wheels = [ @@ -2637,7 +2947,7 @@ name = "typing-inspection" version = "0.4.4" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a3/26/b09b8010994eccc3c09092e6b34058f36a460eea2d4c3e8b910c695975a0/typing_inspection-0.4.4.tar.gz", hash = "sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47", size = 76928, upload-time = "2026-08-12T12:37:25.997Z" } wheels = [ @@ -2677,52 +2987,31 @@ name = "virtualenv" version = "21.7.4" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "distlib" }, - { name = "filelock" }, - { name = "platformdirs" }, - { name = "python-discovery" }, + { name = "distlib", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "filelock", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "platformdirs", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "python-discovery", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/2d/dc/a6eb1ddfa7f1e390fa599b078453c97edb3f6f846b34fb4eac3e8ea16401/virtualenv-21.7.4.tar.gz", hash = "sha256:c9d960c95fa458171e58222a5ccab7465298e4b6559977865e627c4719f1e825", size = 5345511, upload-time = "2026-08-10T22:54:33.316Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/40/4c/eb2f52aeeaf30dbd073d315a251a63ae2b8263171ec4428c135140cb0802/virtualenv-21.7.4-py3-none-any.whl", hash = "sha256:376ec93cd6aab3044fa395d7db226db38043b7b5748948044b2a87168525e843", size = 5324444, upload-time = "2026-08-10T22:54:31.515Z" }, ] -[[package]] -name = "viser" -version = "1.1.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "imageio" }, - { name = "msgspec" }, - { name = "numpy" }, - { name = "requests" }, - { name = "rich" }, - { name = "tqdm" }, - { name = "trimesh" }, - { name = "typing-extensions" }, - { name = "websockets" }, - { name = "zstandard" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/6a/e5/493ae325f825e9853c2be91b31a35ef8ae54aa229b5082fc8b2372314425/viser-1.1.1.tar.gz", hash = "sha256:0a7ba97dab32b8a7106a2dd216fe1373f2e66e17529b5b43502d33d9b9ac9352", size = 3462064, upload-time = "2026-09-15T08:02:05.297Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/70/6f/6a07b4c90451d6dcd40e1d6e5264f93ff4a03d92c071b1e8a06ec8da5004/viser-1.1.1-py3-none-any.whl", hash = "sha256:f528877553c56e1c01d43b861a1434920a2e7ba4fdc7b2e7ff03721e3c3f5b3d", size = 3623619, upload-time = "2026-09-15T08:02:03.635Z" }, -] - [[package]] name = "wandb" version = "0.26.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "click" }, - { name = "gitpython" }, - { name = "packaging" }, - { name = "platformdirs" }, - { name = "protobuf" }, - { name = "pydantic" }, - { name = "pyyaml" }, - { name = "requests" }, - { name = "sentry-sdk" }, - { name = "typing-extensions" }, + { name = "click", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "gitpython", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "platformdirs", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "protobuf", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pydantic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "pyyaml", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "requests", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "sentry-sdk", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/6a/a4/72a6640e1f566e81f184a426e3e45298d4c6672664de41adb7eb6f64370a/wandb-0.26.1.tar.gz", hash = "sha256:eef2dbaea06f0b1c0cdc5d76f544ae4c2b8848fc512442a00bd59f0502fc8aa1", size = 42159814, upload-time = "2026-04-23T16:27:34.033Z" } wheels = [ @@ -2736,14 +3025,14 @@ wheels = [ [[package]] name = "warp-lang" version = "1.17.0" -source = { registry = "https://pypi.org/simple" } +source = { registry = "https://pypi.nvidia.com/" } dependencies = [ - { name = "numpy" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wheels = [ - { url = "https://files.pythonhosted.org/packages/a6/a1/e11aa6898e8bbb6910e89fe31a3338fb2566f038912010875c072e6dafd1/warp_lang-1.17.0-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:47cd93636828dd16e55eeb4e77a0e3547b5fb0f383000a3d228629df68f28fd8", size = 164347636, upload-time = "2026-08-31T05:53:14.441Z" }, - { url = "https://files.pythonhosted.org/packages/6e/4f/a17b1f0ebfeabe37326f01afb6109961f20a0165c1258242f46d10a554f5/warp_lang-1.17.0-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:5051271048da956a8b94e2db9771ce60ce9591a3ac5bb49037f3d6812d1eea00", size = 172665443, upload-time = "2026-08-31T05:53:52.47Z" }, - { url = "https://files.pythonhosted.org/packages/ff/7a/36306a503085cbfc79c35a28e441c59dd1d8070d2dd65152345ebf2dfec2/warp_lang-1.17.0-py3-none-win_amd64.whl", hash = "sha256:ca35c82242a7553046f09023bbe56750b5c3d9af72625bd1a905a56d3189771d", size = 151236515, upload-time = "2026-08-31T05:54:27.944Z" }, + { url = "https://pypi.nvidia.com/warp-lang/warp_lang-1.17.0-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:47cd93636828dd16e55eeb4e77a0e3547b5fb0f383000a3d228629df68f28fd8" }, + { url = "https://pypi.nvidia.com/warp-lang/warp_lang-1.17.0-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:5051271048da956a8b94e2db9771ce60ce9591a3ac5bb49037f3d6812d1eea00" }, + { url = "https://pypi.nvidia.com/warp-lang/warp_lang-1.17.0-py3-none-win_amd64.whl", hash = "sha256:ca35c82242a7553046f09023bbe56750b5c3d9af72625bd1a905a56d3189771d" }, ] [[package]] @@ -2757,16 +3046,27 @@ wheels = [ [[package]] name = "websockets" -version = "16.1.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/21/f7/bc3a25c5ec26ce62ce487690becc2f3710bbc7b33338f005ad390db0b986/websockets-16.1.1.tar.gz", hash = "sha256:db234eda965dcce15df96bb9709f587cd87d4d52aaf0e80e2f34ec04c7670c57", size = 182204, upload-time = "2026-07-17T22:51:05.858Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fe/ed/f1831681fce0e3242346e5458486003c5f124ed69e5e0b847fd029db4973/websockets-16.1.1-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:0f62863e8a00a6d33c3d6566ec0b89f23787b747ffe0c3bc71ec0e76b82c94b1", size = 187137, upload-time = "2026-07-17T22:49:18.323Z" }, - { url = "https://files.pythonhosted.org/packages/6f/79/4ff9dcc1bb46f6b4c536936dde1fd60f9b564f3304307274db97f4c9496d/websockets-16.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8087e82f842609734c9b5a1330464f8e94e346ba0e18c832c08bafa4b0d63c15", size = 188374, upload-time = "2026-07-17T22:49:19.65Z" }, - { url = "https://files.pythonhosted.org/packages/1d/5b/14af3cd4ee69d8ea9baca58f3dc3cfb1ba78332a347fd478cb096549d60e/websockets-16.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2a636ff1e7a5c4edf71ef0e79adae7f25dba93b4fcbe3dc958733477ffeb0eaf", size = 187809, upload-time = "2026-07-17T22:49:27.147Z" }, - { url = "https://files.pythonhosted.org/packages/9d/0b/f78de76ff446f1e66af12b43c48a35f31744de93cfdec2f4ea67d5d7bbf1/websockets-16.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:53260c8930da5771cec89439bff99c20c8cb03ddb9588b980697355a83cd4bd3", size = 187102, upload-time = "2026-07-17T22:49:34.616Z" }, - { url = "https://files.pythonhosted.org/packages/d9/de/6abe251d28c3a3f217096575400b27750b18e0b1d2fff3a2a239960fea07/websockets-16.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:b436f6ec4fc3a6b4237c84d3f83170ed2b40bb584222f0ac47a0c8a5921980c7", size = 180243, upload-time = "2026-07-17T22:49:37.626Z" }, - { url = "https://files.pythonhosted.org/packages/be/4d/2d0d67834092e354d2b0498f014a41249a89556bc406cf86f3e1557bb463/websockets-16.1.1-py3-none-any.whl", hash = "sha256:6abbd3e82c731c8e531714466acd5d87b5e88ac3243465337ba71d68e23ae7e3", size = 173814, upload-time = "2026-07-17T22:51:04.184Z" }, +version = "17.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/75/79/590c5f0cc7d1661195aeefccb0e342b79f4c77d368d526d028821a390332/websockets-17.4.tar.gz", hash = "sha256:09d3939b70df0c8ad2da145ebd50978bccaee1d565e838b0e7921a34d38571eb", size = 191391, upload-time = "2026-10-30T15:10:35.873Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/18/6229d6583031ca81d092a0cd887a13a57b402fb555acc323d39b45967eb7/websockets-17.4-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9ae1429ee9e52b139167ed0169757806a27ed7307e942e8c62037a9184e9843b", size = 226321, upload-time = "2026-10-30T15:07:17.563Z" }, + { url = "https://files.pythonhosted.org/packages/b8/61/7aba018fd53873e792a25afe1f4c005518133477b727d7455f2f7550c425/websockets-17.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:51adfc30f467077293a6695d8149bcef501c0728386f3a491054f835dadb60b2", size = 227559, upload-time = "2026-10-30T15:07:18.998Z" }, + { url = "https://files.pythonhosted.org/packages/fb/66/37b207df9cdacaa017aa4487f3a9f2fcd668f6f7cfbafdac5b95ea258ee0/websockets-17.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c564d1e6531611bf87078c28780456ecc75459dcca189629fff2fe7c020d8e67", size = 230386, upload-time = "2026-10-30T15:07:20.431Z" }, + { url = "https://files.pythonhosted.org/packages/ad/f6/87507e11fbae53817a435945273953b5b020589e309fac4fd60527ee5999/websockets-17.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4c792e6cce24d08f92199d907785c9e64f74c357deeed3dbaf7d699ed5930b64", size = 228193, upload-time = "2026-10-30T15:07:22.112Z" }, + { url = "https://files.pythonhosted.org/packages/2f/3d/90a04f0aa989b68fbd2efcd38237420afe2abe5a1cab0b5d7c2aa4f0dbb6/websockets-17.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c44776f82b04e623eb9e1b81fcd17ac6e9808ae1ba5cdf8edce1f7c869a95a9b", size = 226952, upload-time = "2026-10-30T15:07:23.643Z" }, + { url = "https://files.pythonhosted.org/packages/ad/3e/50952af22b8e3e2d03f7e83f0e335851c6b484c3fd88586626fb1c2a34b3/websockets-17.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4d2636a5b61c69e32db0e74b57073dd4a66f1ad195e9398c5f01bba41090deea", size = 224183, upload-time = "2026-10-30T15:07:25.507Z" }, + { url = "https://files.pythonhosted.org/packages/c4/73/2a4a5d9c6bca1127f24af7bf08f406a69052d7f341bc81f08d9e8eb446b4/websockets-17.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cfbbba4597f19ad717f79fd3f2a67ae7efae647bd6a61e14554e1b5ad242a5bf", size = 226991, upload-time = "2026-10-30T15:07:27.355Z" }, + { url = "https://files.pythonhosted.org/packages/68/de/90d96a579839bfe541ef214315df81d2bd519d952847c303328518ffdd02/websockets-17.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:c7b996c02de5e032cb63dc65482b73693b7ecaa586654126be2749ddea239c40", size = 225600, upload-time = "2026-10-30T15:07:28.973Z" }, + { url = "https://files.pythonhosted.org/packages/9d/73/cb4c927e806a73a0377696e031ef3c0db409028cdb2373f96ee863e8df8e/websockets-17.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8c00c5c49f80a588a2c4f99d519d2abed4ce26cdca11273041bc8b7e60af60de", size = 227470, upload-time = "2026-10-30T15:07:32.122Z" }, + { url = "https://files.pythonhosted.org/packages/33/b3/e682b3ea069933044f4bf4809eea0cd83e3a5bdbdff601d1777a9ae90795/websockets-17.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:52c31d123f5adf14dec694c2a4036bf42c523df7cefc641d31cd05653de56e49", size = 225026, upload-time = "2026-10-30T15:07:33.544Z" }, + { url = "https://files.pythonhosted.org/packages/2d/e9/d039757260705e5a265a31c9fff36b0d4567b842ce2b54e5d14369f200bd/websockets-17.4-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:d0acd8191c0e5a61d1c27bfa33b6ec8431982299f5d71c02129aa4f16f182ad0", size = 226007, upload-time = "2026-10-30T15:07:34.954Z" }, + { url = "https://files.pythonhosted.org/packages/db/e7/cb9907fac6f9b28f93beded6efda2953960cd02b633d432acf3451590859/websockets-17.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2a9cb5bbfc33b4ebd3c8d3714d6e09805437f60a14977774e4bd11b5ace46c23", size = 226286, upload-time = "2026-10-30T15:07:36.292Z" }, + { url = "https://files.pythonhosted.org/packages/59/31/d1636ba67ee9232a60033d90483e48686aa3856014e59110f29015f97bd2/websockets-17.4-cp312-cp312-win_amd64.whl", hash = "sha256:dde9cd67f18803949ebf96de8aba12b8ec5ee3115e34c75a2db85a3b0a6c20d5", size = 219561, upload-time = "2026-10-30T15:07:39.19Z" }, + { url = "https://files.pythonhosted.org/packages/56/6f/2e8d5610f6184a2e1720bf8ce256402ed99ad30ea87c461fba5bc4d651d9/websockets-17.4-pp312-pypy312_pp80-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:88ba8a439b2bad97bb69c38db5bf0ec16a061ee834cf0f244089186ee803e899", size = 217489, upload-time = "2026-10-30T15:10:29.999Z" }, + { url = "https://files.pythonhosted.org/packages/29/3a/a05bc57eadcd7e8e072d917888128e6d22e1203984afb21a8da3198982fe/websockets-17.4-pp312-pypy312_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:868744c68e9342768888c7326604da2228c19bb6946aa46b5f9e1ac32ea8d40b", size = 218356, upload-time = "2026-10-30T15:10:31.432Z" }, + { url = "https://files.pythonhosted.org/packages/b2/49/eed86bfb8863093a82cbaa52c9159be1ce2374d5ace6fe1f8e8031567e7d/websockets-17.4-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:829bcaa90be8737c132d9515d6a466e8528e3b3d050d3f3466f36ea94d3beb48", size = 306838, upload-time = "2026-10-30T15:10:32.954Z" }, + { url = "https://files.pythonhosted.org/packages/eb/27/9db924cb0dbf22eade78d98fbae77790f9bf6bc729e6ab29aef9d68e4156/websockets-17.4-py3-none-any.whl", hash = "sha256:c6bd2c9781915592b209160d0f017d4c7c82ad53075e6b0c24d2a89299e7f9e9", size = 212900, upload-time = "2026-10-30T15:10:34.482Z" }, ] [[package]] @@ -2774,7 +3074,7 @@ name = "werkzeug" version = "3.1.8" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "markupsafe" }, + { name = "markupsafe", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/dd/b2/381be8cfdee792dd117872481b6e378f85c957dd7c5bca38897b08f765fd/werkzeug-3.1.8.tar.gz", hash = "sha256:9bad61a4268dac112f1c5cd4630a56ede601b6ed420300677a869083d70a4c44", size = 875852, upload-time = "2026-04-02T18:49:14.268Z" } wheels = [ @@ -2789,18 +3089,3 @@ sdist = { url = "https://files.pythonhosted.org/packages/b9/d8/eab98a517c14134c0 wheels = [ { url = "https://files.pythonhosted.org/packages/3a/13/547360d81e6d88d58492968ffda9f9542854f11310ee556fef14260cc886/zipp-4.1.0-py3-none-any.whl", hash = "sha256:25ad4e16390cd314347dd8f1de67a2ac538ae658ed4ab9db16029c07c188e97f", size = 10238, upload-time = "2026-05-18T20:08:57.045Z" }, ] - -[[package]] -name = "zstandard" -version = "0.25.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fd/aa/3e0508d5a5dd96529cdc5a97011299056e14c6505b678fd58938792794b1/zstandard-0.25.0.tar.gz", hash = "sha256:7713e1179d162cf5c7906da876ec2ccb9c3a9dcbdffef0cc7f70c3667a205f0b", size = 711513, upload-time = "2025-09-14T22:15:54.002Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/15/efef5a2f204a64bdb5571e6161d49f7ef0fffdbca953a615efbec045f60f/zstandard-0.25.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dffecc361d079bb48d7caef5d673c88c8988d3d33fb74ab95b7ee6da42652ea", size = 5063012, upload-time = "2025-09-14T22:17:01.156Z" }, - { url = "https://files.pythonhosted.org/packages/53/60/7be26e610767316c028a2cbedb9a3beabdbe33e2182c373f71a1c0b88f36/zstandard-0.25.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5a56ba0db2d244117ed744dfa8f6f5b366e14148e00de44723413b2f3938a902", size = 5546993, upload-time = "2025-09-14T22:17:06.781Z" }, - { url = "https://files.pythonhosted.org/packages/85/c7/3483ad9ff0662623f3648479b0380d2de5510abf00990468c286c6b04017/zstandard-0.25.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:10ef2a79ab8e2974e2075fb984e5b9806c64134810fac21576f0668e7ea19f8f", size = 5046806, upload-time = "2025-09-14T22:17:08.415Z" }, - { url = "https://files.pythonhosted.org/packages/08/b3/206883dd25b8d1591a1caa44b54c2aad84badccf2f1de9e2d60a446f9a25/zstandard-0.25.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aaf21ba8fb76d102b696781bddaa0954b782536446083ae3fdaa6f16b25a1c4b", size = 5576659, upload-time = "2025-09-14T22:17:10.164Z" }, - { url = "https://files.pythonhosted.org/packages/9d/31/76c0779101453e6c117b0ff22565865c54f48f8bd807df2b00c2c404b8e0/zstandard-0.25.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1869da9571d5e94a85a5e8d57e4e8807b175c9e4a6294e3b66fa4efb074d90f6", size = 4953933, upload-time = "2025-09-14T22:17:11.857Z" }, - { url = "https://files.pythonhosted.org/packages/fc/5f/75aafd4b9d11b5407b641b8e41a57864097663699f23e9ad4dbb91dc6bfe/zstandard-0.25.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:474d2596a2dbc241a556e965fb76002c1ce655445e4e3bf38e5477d413165ffa", size = 5360237, upload-time = "2025-09-14T22:17:19.954Z" }, - { url = "https://files.pythonhosted.org/packages/79/3b/fa54d9015f945330510cb5d0b0501e8253c127cca7ebe8ba46a965df18c5/zstandard-0.25.0-cp312-cp312-win_amd64.whl", hash = "sha256:ffef5a74088f1e09947aecf91011136665152e0b4b359c42be3373897fb39b01", size = 506276, upload-time = "2025-09-14T22:17:21.429Z" }, -] From dd97e6091175e259866bdc9e6c4c3f42dca80880 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:53:25 -0800 Subject: [PATCH 09/30] Sample real images with the trained retina in degrees The software retina takes the real camera as fovi CameraModel fields and the trained retina's field of view and CMF constant in degrees, and gaze in degrees. Any calibrated camera works, not only a pinhole. --- .../active_gaze/deployment/retina.py | 50 ++++++------------- 1 file changed, 15 insertions(+), 35 deletions(-) diff --git a/src/isaaclab_tutorial/active_gaze/deployment/retina.py b/src/isaaclab_tutorial/active_gaze/deployment/retina.py index 13ee86c..0ced441 100644 --- a/src/isaaclab_tutorial/active_gaze/deployment/retina.py +++ b/src/isaaclab_tutorial/active_gaze/deployment/retina.py @@ -1,58 +1,38 @@ -"""Sample real RGB images using the simulator's calibrated, upright ray grid.""" - -import math +"""Sample a real camera's images the way the simulator's foveated camera samples the scene.""" import torch from fovi.sensing.coords import SamplingCoords from fovi.sensing.projection import CameraModel, gaze_rotation +from isaaclab_fovi.sensors.native_grid import GRID_STYLE, native_grid_directions from torch import nn from torch.nn import functional as F -from isaaclab_fovi.sensors.native_grid import native_grid_directions - - -def nominal_calibration(hfov: float, size: int = 640) -> dict: - focal = size / (2 * math.tan(math.radians(hfov / 2))) - return dict( - model="pinhole", - image_size=[size, size], - intrinsics=[focal, focal, (size - 1) / 2, (size - 1) / 2], - ) - class SoftwareRetina(nn.Module): - """Bilinear dense-image sampling with the exact native-grid permutation. + """Bilinear sampling of dense images on the simulator's retinal ray grid, in its upright image order. - Calibration describes the actual capture raster, without implicit resizing. - Angular coverage and CMF describe the trained retina independently of it. - Inputs are uint8 BHWC RGB and (tilt, pan) radians. Output is uint8 BHWC. + The retina is the trained one: its field of view and CMF constant [deg] and its resolution. ``camera_model`` + describes the real camera's capture raster as :class:`fovi.sensing.projection.CameraModel` fields, without any + implicit resizing. Inputs are uint8 (B, H, W, 3) RGB images and gaze (tilt, pan) [deg]; the output is uint8 + (B, R, R, 3), zero where the real camera does not see. """ - def __init__(self, calibration: dict, hfov: float, cmf_a: float, resolution: int = 128): + def __init__(self, camera_model: dict, fov_deg: float, cmf_a_deg: float, resolution: int): super().__init__() - self.camera = CameraModel(**calibration) - if self.camera.model != "pinhole": - raise ValueError("SO-101 deployment requires a calibrated pinhole camera") + self.camera = CameraModel(**camera_model) self.height, self.width = self.camera.image_size self.resolution = resolution coords = SamplingCoords( - fov=hfov, - cmf_a=cmf_a * hfov, - res=resolution, - style="warped_cartesian_as_grid", - fov_type="circular", - radius_norm=2.0, - field_geometry="spherical", - device="cpu", + fov=fov_deg, cmf_a=cmf_a_deg, res=resolution, style=GRID_STYLE, field_geometry="spherical", device="cpu" ) - rays = native_grid_directions(coords, tangent_scale=1.0) + rays = native_grid_directions(coords) # Renderer OpenGL rays -> upright OpenCV rays, then public image ordering. rays = coords.as_grid(rays * rays.new_tensor((1, -1, -1)), sample_dim=0) self.register_buffer("rays", rays.reshape(-1, 3)) self.register_buffer("valid", coords.as_grid(coords.valid_mask).reshape(1, resolution, resolution, 1)) - def grid(self, gaze: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - tilt, pan = gaze.float().unbind(-1) + def grid(self, gaze_deg: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + tilt, pan = gaze_deg.float().deg2rad().unbind(-1) direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) rotation = gaze_rotation(direction, "pan_tilt") # Explicit reductions avoid TF32 errors in camera geometry. @@ -63,8 +43,8 @@ def grid(self, gaze: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: visible = visible.reshape(-1, self.resolution, self.resolution, 1) & self.valid return grid, visible - def forward(self, rgb: torch.Tensor, gaze: torch.Tensor) -> torch.Tensor: - grid, valid = self.grid(gaze) + def forward(self, rgb: torch.Tensor, gaze_deg: torch.Tensor) -> torch.Tensor: + grid, valid = self.grid(gaze_deg) sampled = F.grid_sample( rgb.permute(0, 3, 1, 2).float(), grid, From a9480efc6deaf2cb9e6ef6feb811afe7c6a10fe6 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:53:25 -0800 Subject: [PATCH 10/30] Rebuild sim2real on the spherical camera and the tutorial's sim2real preset presets=sim2real now adds, to the tutorial's own physical randomization: the scene's colours from the wrist-camera task, an episode-wise photometric variation of the retina, and a per-episode move of the camera's mount. The mount term owns the mount pose and the extrinsics labels; the gaze action reads the mount from it, and the camera follows through set_world_poses. Every reset phase stays in use, so the reset curriculum still applies. The planar camera, the env-wide camera-randomization attribute and the unused lens-visibility model are gone. Agents: gaze supervision is one weight on the same gaze-supervised PPO (no_gaze_supervision sets it to 0), so the unsupervised baseline differs only in that loss. With sim2real the language agent adds the extrinsics head and its loss. --- src/isaaclab_tutorial/active_gaze/agents.py | 150 ++------ .../active_gaze/camera_geometry.py | 19 +- src/isaaclab_tutorial/active_gaze/env_cfg.py | 78 ++++- src/isaaclab_tutorial/active_gaze/gaze.py | 7 +- .../active_gaze/learning/observations.py | 30 +- src/isaaclab_tutorial/active_gaze/sim2real.py | 325 ++++++------------ .../active_gaze/transfer_options.py | 32 -- 7 files changed, 241 insertions(+), 400 deletions(-) delete mode 100644 src/isaaclab_tutorial/active_gaze/transfer_options.py diff --git a/src/isaaclab_tutorial/active_gaze/agents.py b/src/isaaclab_tutorial/active_gaze/agents.py index 8f4877c..a5a1c2c 100644 --- a/src/isaaclab_tutorial/active_gaze/agents.py +++ b/src/isaaclab_tutorial/active_gaze/agents.py @@ -1,136 +1,77 @@ -"""Class-based SO-101 policy, loss, and optimizer presets.""" +"""PPO agents of the active-gaze variants, with gaze supervision by the teacher. + +Presets: ``no_gaze_supervision`` turns the teacher's gaze loss off, ``chunking`` makes each decision a plan of three +control actions, ``finetune`` lowers the learning rate to warm-start from a checkpoint, and ``sim2real`` adds the +extrinsics head to the language agent. +""" from isaaclab.utils import configclass from isaaclab_rl.rsl_rl import RslRlCNNModelCfg, RslRlMLPModelCfg, RslRlOnPolicyRunnerCfg, RslRlPpoAlgorithmCfg -from isaaclab_tasks.utils import PresetCfg - -from isaaclab_tutorial.active_gaze.learning.config import LanguageVisionActorCfg +from isaaclab_tasks.utils import PresetCfg, preset from .language import INSTRUCTIONS +from .learning.config import LanguageVisionActorCfg @configclass -class LearningRateCfg(PresetCfg): - default = 3e-4 - finetune = 3e-5 +class GazeSupervisedPPOCfg(RslRlPpoAlgorithmCfg): + """PPO with a loss that pulls the gaze actions toward the teacher's.""" - -@configclass -class FineTuneCfg(PresetCfg): - default = False - finetune = True - - -@configclass -class PPOCfg(RslRlPpoAlgorithmCfg): + class_name = "isaaclab_tutorial.active_gaze.learning.oracle_ppo:OraclePPO" value_loss_coef = 1.0 use_clipped_value_loss = True clip_param = 0.2 entropy_coef = 0.005 num_learning_epochs = 5 num_mini_batches = 8 - learning_rate = LearningRateCfg() - schedule = "adaptive" + learning_rate = preset(default=3e-4, finetune=3e-5) + schedule = "fixed" gamma = 0.995 lam = 0.95 desired_kl = 0.01 max_grad_norm = 1.0 - - -@configclass -class ActionChunkSizeCfg(PresetCfg): - """Number of control actions predicted by each policy invocation.""" - - default = 1 - chunking = 3 - - -@configclass -class RolloutLengthCfg(PresetCfg): - """Keep the rollout near the default control horizon with three-action chunks.""" - - default = 64 - chunking = 21 - - -@configclass -class OraclePPOCfg(PPOCfg): - class_name = "isaaclab_tutorial.active_gaze.learning.oracle_ppo:OraclePPO" - oracle_weight: float = 1.0 + oracle_weight: float = preset(default=1.0, no_gaze_supervision=0.0) + """Weight of the teacher's gaze loss.""" oracle_std: float = 1e-4 - action_chunk_size = ActionChunkSizeCfg() - schedule = "fixed" + action_chunk_size: int = preset(default=1, chunking=3) + """Control actions planned by each policy decision.""" @configclass -class GazeWeightCfg(PresetCfg): - grasp_gated = 1.0 - no_gaze_supervision = 0.0 - default = grasp_gated - +class ExtrinsicsPPOCfg(GazeSupervisedPPOCfg): + """Gaze-supervised PPO that also trains the actor's head to predict the camera mount's move.""" -@configclass -class ExtrinsicsPPOCfg(OraclePPOCfg): class_name = "isaaclab_tutorial.active_gaze.pose_ppo:ExtrinsicsPPO" - oracle_weight = GazeWeightCfg() extrinsics_weight: float = 0.05 -@configclass -class UnsupervisedAlgorithmCfg(PresetCfg): - default = PPOCfg() - chunking = OraclePPOCfg(oracle_weight=0.0) - - -@configclass -class GazeAlgorithmCfg(PresetCfg): - grasp_gated = OraclePPOCfg() - no_gaze_supervision = UnsupervisedAlgorithmCfg() - default = grasp_gated - - -@configclass -class AlgorithmCfg(PresetCfg): - default = GazeAlgorithmCfg() - extrinsics = ExtrinsicsPPOCfg() - - -@configclass -class ExtrinsicsHeadCfg(PresetCfg): - default = False - extrinsics = True - - @configclass class ActiveGazePPORunnerCfg(RslRlOnPolicyRunnerCfg): + """A CNN actor on the retina, proprioception and gaze; an MLP critic on the full state.""" + seed = 42 - num_steps_per_env = RolloutLengthCfg() + # Keeps the rollout near the same control horizon when each decision plans three actions. + num_steps_per_env = preset(default=64, chunking=21) run_name = "" clip_actions = 1.0 - critic = RslRlMLPModelCfg(hidden_dims=[256, 256, 128], activation="elu", obs_normalization=True) - finetune = FineTuneCfg() + finetune: bool = preset(default=False, finetune=True) + """Warm-start from a checkpoint, allowing the extrinsics head to be new.""" experiment_name = "so101_vial_active_gaze" max_iterations = 5000 save_interval = 100 obs_groups = {"actor": ["scene_rgb", "proprioception", "gaze"], "critic": ["critic"]} - algorithm = AlgorithmCfg() + algorithm = GazeSupervisedPPOCfg() + critic = RslRlMLPModelCfg(hidden_dims=[256, 256, 128], activation="elu", obs_normalization=True) actor = RslRlCNNModelCfg( cnn_cfg=RslRlCNNModelCfg.CNNCfg( - output_channels=[16, 32, 32], - kernel_size=[5, 3, 3], - stride=[2, 2, 2], - activation="elu", + output_channels=[16, 32, 32], kernel_size=[5, 3, 3], stride=[2, 2, 2], activation="elu" ), hidden_dims=[256, 128], activation="elu", obs_normalization=True, - distribution_cfg=RslRlCNNModelCfg.GaussianDistributionCfg( - init_std=0.2, - std_type="log", - std_range=(0.05, 0.3), - ), + distribution_cfg=RslRlCNNModelCfg.GaussianDistributionCfg(init_std=0.2, std_type="log", std_range=(0.05, 0.3)), ) @@ -138,41 +79,20 @@ class ActiveGazePPORunnerCfg(RslRlOnPolicyRunnerCfg): class LanguageActorCfg(LanguageVisionActorCfg): instructions = INSTRUCTIONS distribution_cfg = ActiveGazePPORunnerCfg().actor.distribution_cfg - extrinsics_head = ExtrinsicsHeadCfg() - - -@configclass -class LanguageUnsupervisedAlgorithmCfg(PresetCfg): - default = PPOCfg(use_mixed_precision=True) - chunking = OraclePPOCfg(oracle_weight=0.0, use_mixed_precision=True) - - -@configclass -class LanguageGazeAlgorithmCfg(GazeAlgorithmCfg): - grasp_gated = OraclePPOCfg(use_mixed_precision=True) - no_gaze_supervision = LanguageUnsupervisedAlgorithmCfg() - default = grasp_gated - - -@configclass -class LanguageAlgorithmCfg(AlgorithmCfg): - default = LanguageGazeAlgorithmCfg() - extrinsics = ExtrinsicsPPOCfg(use_mixed_precision=True) + extrinsics_head: bool = preset(default=False, sim2real=True) @configclass class LanguagePPORunnerCfg(ActiveGazePPORunnerCfg): + """A frozen-DINO and language actor; the extrinsics head and its loss come with ``sim2real``.""" + actor = LanguageActorCfg() - algorithm = LanguageAlgorithmCfg() + algorithm = preset( + default=GazeSupervisedPPOCfg(use_mixed_precision=True), sim2real=ExtrinsicsPPOCfg(use_mixed_precision=True) + ) obs_groups = {"actor": ["proprio", "vision", "instruction"], "critic": ["critic"]} -@configclass -class Sim2RealPPORunnerCfg(LanguagePPORunnerCfg): - actor = LanguageActorCfg(extrinsics_head=True) - algorithm = ExtrinsicsPPOCfg(use_mixed_precision=True) - - @configclass class ActiveGazeAgentCfg(PresetCfg): """Agents of the task variants in :class:`~.env_cfg.ActiveGazeEnvCfg`, selected by the same names.""" diff --git a/src/isaaclab_tutorial/active_gaze/camera_geometry.py b/src/isaaclab_tutorial/active_gaze/camera_geometry.py index 843d3c6..d3c5f5b 100644 --- a/src/isaaclab_tutorial/active_gaze/camera_geometry.py +++ b/src/isaaclab_tutorial/active_gaze/camera_geometry.py @@ -1,25 +1,12 @@ -"""Batched pinhole lens visibility and camera-pose auxiliary targets.""" +"""Labels and loss of the camera mount's move, for the actor's extrinsics head.""" import torch from torch.nn import functional as F TRANSLATION_SCALE = 0.03 +"""Translation [m] that maps to a label of 1.""" ROTATION_SCALE = 0.1 - - -def lens_visibility(rays, intrinsics, radial, image_size): - """OpenCV rays against the nominal physical raster (shared fixed optics).""" - xy = rays[..., :2] / rays[..., 2:].clamp_min(1e-7) - xy = xy * (1 + radial[:, None, None] * xy.square().sum(-1, keepdim=True)) - pixels = xy * intrinsics[:, None, :2] + intrinsics[:, None, 2:] - h, w = image_size - return ( - (rays[..., 2] > 0) - & (pixels[..., 0] >= -0.5) - & (pixels[..., 0] < w - 0.5) - & (pixels[..., 1] >= -0.5) - & (pixels[..., 1] < h - 0.5) - ) +"""Rotation-matrix entry change that maps to a label of 1.""" def pose_targets(translation_delta, rotation_delta): diff --git a/src/isaaclab_tutorial/active_gaze/env_cfg.py b/src/isaaclab_tutorial/active_gaze/env_cfg.py index 6641900..cc6528a 100644 --- a/src/isaaclab_tutorial/active_gaze/env_cfg.py +++ b/src/isaaclab_tutorial/active_gaze/env_cfg.py @@ -18,25 +18,27 @@ import torch from isaaclab_fovi.sensors import FoveatedCameraCfg -from isaaclab.assets import AssetBaseCfg -from isaaclab.managers import CurriculumTermCfg, ManagerTermBase, ObservationGroupCfg, ObservationTermCfg +from isaaclab.assets import AssetBaseCfg, VisualMaterialCfg +from isaaclab.managers import CurriculumTermCfg, EventTermCfg, ManagerTermBase, ObservationGroupCfg, ObservationTermCfg from isaaclab.sensors import CameraCfg from isaaclab.sim import DomeLightCfg, PinholeCameraCfg from isaaclab.utils import configclass -from isaaclab_tasks.utils import PresetCfg +from isaaclab_tasks.utils import PresetCfg, preset from isaaclab_tutorial.assets.numbers import LABEL_ASSETS -from isaaclab_tutorial.tasks.place_vial.config.so101.camera_env_cfg import ProprioceptionCfg +from isaaclab_tutorial.tasks.place_vial.config.so101.camera_env_cfg import CameraSim2RealEventsCfg, ProprioceptionCfg from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import ( ActionsCfg, CriticStateGroupCfg, EventsCfg, RewardsCfg, + Sim2RealEventsCfg, SO101SceneCfg, SO101VialEnvCfg, TerminationsCfg, ) +from isaaclab_tutorial.tasks.place_vial.reset.curriculum import ALL_PHASES from .gaze import GazeActionCfg, oracle_labels from .goals import ( @@ -55,6 +57,7 @@ from .render_options import CameraOutputCfg, CameraOutputNameCfg, CameraRenderSettingsCfg, FoviRendererCfg from .robot_geometry import spawn_without_wrist_camera from .sampling import ResetSampling +from .sim2real import PHOTOMETRIC_RANGES, ExtrinsicsObservations, PhotometricVariation, randomize_camera_mount ## # Scene camera @@ -118,6 +121,13 @@ class SceneCfg(SO101SceneCfg): eye = NEAREST_CAMERA light = AssetBaseCfg(prim_path="/World/Light", spawn=DomeLightCfg(intensity=2000)) + # Materials that the sim2real colour events vary; the Newton renderer only reads material colour. + robot_visual = VisualMaterialCfg(prim_path="{ENV_REGEX_NS}/Robot/Looks/material_a_d_printed", spawn=None) + desk_visual = VisualMaterialCfg(prim_path="{ENV_REGEX_NS}/Desk/Looks/Wood", spawn=None) + rack_visual = VisualMaterialCfg(prim_path="{ENV_REGEX_NS}/Rack/WorkshopVisual/Looks/OmniPBR", spawn=None) + vial_body_visual = VisualMaterialCfg(prim_path="{ENV_REGEX_NS}/Vial/Looks/Vial_plastic", spawn=None) + vial_cap_visual = VisualMaterialCfg(prim_path="{ENV_REGEX_NS}/Vial/Looks/Vial_cap", spawn=None) + @configclass class NumberedSceneCfg(SceneCfg): @@ -140,19 +150,28 @@ def __post_init__(self): class SceneRGB(ManagerTermBase): """The scene camera's retina as RGB in [0, 1], shape (num_envs, 3, H, W). - The image is read again only when the policy decides, so an action chunk's native steps reuse it. + The image is read again only when the policy decides, so an action chunk's native steps reuse it. With + ``photometric`` ranges the retina's appearance varies per episode. """ def __init__(self, cfg, env): super().__init__(cfg, env) + ranges = cfg.params.get("photometric") + self.photometric = PhotometricVariation(env.num_envs, env.device, ranges) if ranges is not None else None self.cached = None - def __call__(self, env): + def reset(self, env_ids=None): + if self.photometric is not None: + self.photometric.reset(env_ids) + + def __call__(self, env, photometric=None): if not getattr(env, "refresh_policy_vision", True) and self.cached is not None: return self.cached camera = env.scene["eye"] - image = camera.data.output[camera.cfg.data_types[0]].torch - self.cached = image[..., :3].float().permute(0, 3, 1, 2).contiguous() / 255.0 + image = camera.data.output[camera.cfg.data_types[0]].torch[..., :3] + if self.photometric is not None: + image = self.photometric(image) + self.cached = image.float().permute(0, 3, 1, 2).contiguous() / 255.0 return self.cached @@ -171,9 +190,13 @@ class ActiveGazeActionsCfg(ActionsCfg): gaze = GazeActionCfg() +PHOTOMETRIC = preset(default=None, sim2real=PHOTOMETRIC_RANGES) +"""Episode-wise photometric variation of the retina, on with ``presets=sim2real``.""" + + @configclass class ImageCfg(ObservationGroupCfg): - image = ObservationTermCfg(func=SceneRGB) + image = ObservationTermCfg(func=SceneRGB, params=dict(photometric=PHOTOMETRIC)) concatenate_dim = 0 enable_corruption = False @@ -235,7 +258,11 @@ class VisionCfg(ObservationGroupCfg): tokens = ObservationTermCfg( func=DinoTokens, params=dict( - reference=DEFAULT_CHECKPOINT, checksum=DEFAULT_MD5, batch_size=128, data_type=CameraOutputNameCfg() + reference=DEFAULT_CHECKPOINT, + checksum=DEFAULT_MD5, + batch_size=128, + data_type=CameraOutputNameCfg(), + photometric=PHOTOMETRIC, ), ) concatenate_dim = 0 @@ -257,6 +284,7 @@ class LanguageObservationsCfg: instruction = InstructionCfg() critic = NumberedCriticCfg() oracle = OracleObservationCfg() + extrinsics = preset(default=None, sim2real=ExtrinsicsObservations()) @configclass @@ -291,6 +319,33 @@ class NumberedEventsCfg(EventsCfg): reset_from_dataset = EventsCfg().reset_from_dataset.replace(func=NumberedResetFromDataset) +@configclass +class ActiveGazeSim2RealEventsCfg(Sim2RealEventsCfg): + """The tutorial's physical sim2real randomization, the scene's colours and the camera's mount. + + The colours are those of the tutorial's wrist-camera task. Unlike the tutorial's sim2real resets, every reset + phase stays in use, so the reset curriculum still applies. + """ + + robot_color = CameraSim2RealEventsCfg().robot_color + desk_color = CameraSim2RealEventsCfg().desk_color + rack_color = CameraSim2RealEventsCfg().rack_color + vial_body_color = CameraSim2RealEventsCfg().vial_body_color + vial_cap_color = CameraSim2RealEventsCfg().vial_cap_color + camera_mount = EventTermCfg(func=randomize_camera_mount, mode="reset", params=dict(camera_name="eye")) + + def __post_init__(self): + super().__post_init__() + self.reset_from_dataset.params["phase_weights"] = ALL_PHASES + + +@configclass +class NumberedSim2RealEventsCfg(ActiveGazeSim2RealEventsCfg): + def __post_init__(self): + super().__post_init__() + self.reset_from_dataset.func = NumberedResetFromDataset + + @configclass class NumberedTerminationsCfg(TerminationsCfg): success = TerminationsCfg().success.replace(func=TargetPlacementSuccess) @@ -316,6 +371,7 @@ class NearestEnvCfg(SO101VialEnvCfg): scene: SceneCfg = SceneCfg(num_envs=128, env_spacing=0.9) actions: ActiveGazeActionsCfg = ActiveGazeActionsCfg() observations: ObservationsCfg = ObservationsCfg() + events = preset(default=EventsCfg(), sim2real=ActiveGazeSim2RealEventsCfg()) rewards: ActiveGazeRewardsCfg = ActiveGazeRewardsCfg() curriculum: CurriculumCfg = CurriculumCfg() compute_final_obs = FinalObservationCfg() @@ -332,7 +388,7 @@ class NumberedEnvCfg(NearestEnvCfg): scene: NumberedSceneCfg = NumberedSceneCfg(num_envs=128, env_spacing=0.9) observations: NumberedObservationsCfg = NumberedObservationsCfg() - events: NumberedEventsCfg = NumberedEventsCfg() + events = preset(default=NumberedEventsCfg(), sim2real=NumberedSim2RealEventsCfg()) rewards: NumberedRewardsCfg = NumberedRewardsCfg() terminations: NumberedTerminationsCfg = NumberedTerminationsCfg() diff --git a/src/isaaclab_tutorial/active_gaze/gaze.py b/src/isaaclab_tutorial/active_gaze/gaze.py index ad081e8..b43d94c 100644 --- a/src/isaaclab_tutorial/active_gaze/gaze.py +++ b/src/isaaclab_tutorial/active_gaze/gaze.py @@ -21,6 +21,7 @@ from isaaclab_tutorial.tasks.place_vial.mdp.task import RACK_RIM_HEIGHT, VIAL_AXIS_MAX, VIAL_AXIS_MIN from .goals import CAP_LABEL_POSITION, RACK_LABEL_OFFSETS, target_holes +from .sim2real import mount_randomization RESET_MODES = ("random", "object", "goal", "near_object", "near_goal") """Where the gaze starts an episode: anywhere in the camera's view, at the vial or the goal, or 2 to 5 degrees off @@ -184,8 +185,10 @@ def _reset_mixed(self, ids: torch.Tensor): self.reset_mode[ids] = modes def directions(self, points: torch.Tensor, env_ids=slice(None)) -> torch.Tensor: - """Camera-frame unit directions from the camera to world points.""" - return camera_directions(points, self.camera.data.pos_w.torch[env_ids], self.base_rotation) + """Camera-frame unit directions from the camera's mount to world points.""" + mount = mount_randomization(self._env) + rotation = self.base_rotation if mount is None else mount.rotation[env_ids] + return camera_directions(points, self.camera.data.pos_w.torch[env_ids], rotation) def visible(self, direction: torch.Tensor) -> torch.Tensor: """Whether camera-frame directions fall inside the physical camera's image.""" diff --git a/src/isaaclab_tutorial/active_gaze/learning/observations.py b/src/isaaclab_tutorial/active_gaze/learning/observations.py index bdfede4..1406fa7 100644 --- a/src/isaaclab_tutorial/active_gaze/learning/observations.py +++ b/src/isaaclab_tutorial/active_gaze/learning/observations.py @@ -1,4 +1,4 @@ -"""Shared frozen visual preprocessing for native manager-based tasks.""" +"""Frozen DINO tokens of the foveated scene camera's retina.""" from isaaclab.managers import ManagerTermBase @@ -6,17 +6,35 @@ class DinoTokens(ManagerTermBase): - """Encode the monocular eye once per observation, outside PPO minibatches.""" + """Encode the retina once per policy decision, outside PPO minibatches. + + With ``photometric`` ranges (see :mod:`isaaclab_tutorial.active_gaze.sim2real`), the retina's appearance varies + per episode before encoding. + """ def __init__(self, cfg, env): super().__init__(cfg, env) self.camera = env.scene["eye"] - self.encoder = FrozenDino(**{k: v for k, v in cfg.params.items() if k != "data_type"}).to(env.device).eval() + encoder_args = {k: v for k, v in cfg.params.items() if k not in ("data_type", "photometric")} + self.encoder = FrozenDino(**encoder_args).to(env.device).eval() + self.photometric = None + if cfg.params.get("photometric") is not None: + from isaaclab_tutorial.active_gaze.sim2real import PhotometricVariation + + self.photometric = PhotometricVariation(env.num_envs, env.device, cfg.params["photometric"]) self.cached = None - def __call__(self, env, reference: str, checksum: str | None, batch_size: int, data_type: str = "rgb"): + def reset(self, env_ids=None): + if self.photometric is not None: + self.photometric.reset(env_ids) + + def __call__( + self, env, reference: str, checksum: str | None, batch_size: int, data_type: str = "rgb", photometric=None + ): if not getattr(env, "refresh_policy_vision", True) and self.cached is not None: return self.cached - image = self.camera.data.output[data_type] - self.cached = self.encoder(image.torch if hasattr(image, "torch") else image) + image = self.camera.data.output[data_type].torch + if self.photometric is not None: + image = self.photometric(image) + self.cached = self.encoder(image) return self.cached diff --git a/src/isaaclab_tutorial/active_gaze/sim2real.py b/src/isaaclab_tutorial/active_gaze/sim2real.py index 4be308a..61b1933 100644 --- a/src/isaaclab_tutorial/active_gaze/sim2real.py +++ b/src/isaaclab_tutorial/active_gaze/sim2real.py @@ -1,250 +1,139 @@ -"""Opt-in physics and appearance randomizations and uncalibrated planar software gaze.""" +"""Robot-transfer randomization of the active-gaze task: the scene camera's mount and the retina's appearance. + +``presets=sim2real`` adds these to the tutorial's physical sim2real randomization. The camera's mount moves every +episode, and the ``extrinsics`` observation group labels that move for the actor's auxiliary head. Retinal images get +an episode-wise photometric variation. +""" + +from __future__ import annotations import math -from copy import deepcopy import torch -from isaaclab.managers import EventTermCfg, ManagerTermBase, ObservationGroupCfg, ObservationTermCfg -from isaaclab.sensors import Camera +from torch.nn import functional as F + +from isaaclab.managers import ManagerTermBase, ObservationGroupCfg, ObservationTermCfg from isaaclab.utils import configclass -from isaaclab.utils.math import ( - matrix_from_quat, - quat_apply_inverse, - quat_from_euler_xyz, - quat_from_matrix, - quat_mul, +from isaaclab.utils.math import matrix_from_quat, quat_apply_inverse, quat_from_euler_xyz, quat_mul + +from .camera_geometry import pose_targets + +PHOTOMETRIC_RANGES = dict( + exposure=(0.75, 1.25), + contrast=(0.85, 1.15), + gamma=(0.85, 1.15), + white_balance=(0.9, 1.1), + brightness=(-0.05, 0.05), + blur=(0.0, 0.5), ) +"""Ranges of the episode-wise photometric variation, as in the tutorial's wrist-camera task.""" + -from isaaclab_fovi.deployment.so101.planar import PlanarRetina, gaze_basis, project_pinhole_rays -from isaaclab_tutorial.active_gaze.learning.observations import DinoTokens -from isaaclab_fovi.sensors.calibrated_geometry import compose_rotations, rotate_camera_rays -from isaaclab_fovi.sensors.foveated_rtx_tiled_camera import FoveatedRTXTiledCamera +class PhotometricVariation: + """Episode-wise exposure, contrast, gamma, white balance, brightness and blur of uint8 retinal images. -from .camera_geometry import lens_visibility, pose_targets -from .transfer_options import settings + Samples the physical camera does not see are zero and stay zero. + """ + def __init__(self, num_envs: int, device, ranges: dict[str, tuple[float, float]]): + self.ranges = ranges + self.values = { + name: torch.zeros(num_envs, 3 if name == "white_balance" else 1, device=device) for name in ranges + } + self.reset() + + def reset(self, env_ids=None): + ids = slice(None) if env_ids is None else env_ids + for name, (low, high) in self.ranges.items(): + self.values[name][ids] = torch.empty_like(self.values[name][ids]).uniform_(low, high) -class PlanarSceneCamera(FoveatedRTXTiledCamera): - """Direct RTX foveation with one shared planar LUT and per-scene poses.""" + def __call__(self, images: torch.Tensor) -> torch.Tensor: + """Vary (num_envs, H, W, 3) uint8 images.""" + unseen = (images[..., :3] == 0).all(-1, keepdim=True) + rgb = images[..., :3].permute(0, 3, 1, 2).float() / 255 - def _initialize_impl(self): - super()._initialize_impl() - position, orientation = self._view.get_world_poses() - self.physical_position = position.torch.clone() - self.physical_rotation = orientation.torch.clone() - self.gaze = torch.zeros(len(position.torch), 2, device=self.device) - self.retina = PlanarRetina(self._camera_hfov_deg, self.cfg.cmf_a, self.cfg.foveated_res).to(self.device) - self._physical_rays = self._fixed_fov_ray_directions * self.gaze.new_tensor((1, -1, -1)) + def value(name): + return self.values[name][:, :, None, None] - def set_calibrated_angles(self, angles): - # Keep the shared action API. These are software angles using a fixed - # nominal pinhole convention, not measured physical camera intrinsics. - self.gaze = angles.clone() - self._write_gaze_pose() + blurred = F.avg_pool2d(rgb, 3, stride=1, padding=1, count_include_pad=False) + rgb = rgb.lerp(blurred, value("blur")).pow(value("gamma")) + rgb = (rgb - 0.5) * value("contrast") + 0.5 + rgb = (rgb * value("exposure") * value("white_balance") + value("brightness")).clamp(0, 1) + return (rgb.permute(0, 2, 3, 1) * 255).round().to(torch.uint8).masked_fill(unseen, 0) - def set_physical_poses(self, position, rotation, env_ids): - self.physical_position[env_ids] = position - self.physical_rotation[env_ids] = rotation - self._write_gaze_pose(env_ids) - def _write_gaze_pose(self, env_ids=None): - ids = slice(None) if env_ids is None else env_ids - basis = self.gaze.new_tensor((1, -1, -1)) - relative = gaze_basis(self.gaze[ids]) * basis[None, :, None] * basis[None, None, :] - rotation = quat_from_matrix(compose_rotations(matrix_from_quat(self.physical_rotation[ids]), relative)) - Camera.set_world_poses(self, self.physical_position[ids], rotation, env_ids=env_ids, convention="opengl") - - def get_world_positions(self): - return self.physical_position - - def _apply_fixed_fov_mask(self): - rotated = rotate_camera_rays(self._physical_rays, gaze_basis(self.gaze)) - _, valid = project_pinhole_rays( - rotated, - self.retina.focal_pixels, - self.retina.center_pixels, - self.retina.width, - ) - for name, output in self._foveated_output.items(): - if name == "rgb" and "rgba" in self._foveated_output: - continue - output.masked_fill_(~valid[:, :, None, None], 0) - self._fixed_fov_valid_fraction = valid.float().mean(1) - valid = valid & self._ray_coords.valid_mask - self.public_valid = valid[:, self._grid_indices].reshape(-1, self.cfg.foveated_res, self.cfg.foveated_res, 1) - - -class RandomizedDinoTokens(DinoTokens): - def __call__(self, env, reference, checksum, batch_size=128, data_type="rgb"): - if not getattr(env, "refresh_policy_vision", True) and self.cached is not None: - return self.cached - image = env.scene["eye"].data.output[data_type] - image = image.torch if hasattr(image, "torch") else image - image = env.so101_camera_randomization.image(image) - self.cached = self.encoder(image) - return self.cached - - -class CameraRandomization(ManagerTermBase): +class randomize_camera_mount(ManagerTermBase): + """Move the scene camera's mount by up to ``position_range`` [m] and ``rotation_range_deg`` [deg] each episode. + + A fraction ``nominal_fraction`` of episodes keep the nominal mount. The ranges ramp up from 10 % over + ``ramp_steps`` control steps. This term owns the camera's mount pose and the move's extrinsics labels. + """ + def __init__(self, cfg, env): super().__init__(cfg, env) - self.camera = env.scene["eye"] - self.camera.gaze = torch.zeros(self.num_envs, 2, device=self.device) - self.retina = PlanarRetina(env.cfg.camera_hfov(), env.cfg.cmf_a(), env.cfg.resolution()).to(self.device) - self.options = settings(env.cfg.sim2real if env.cfg.sim2real is not None else {"nominal_fraction": 1.0}) - self.position = torch.tensor(self.camera.cfg.offset.pos, device=self.device).expand(self.num_envs, -1).clone() - self.rotation = torch.tensor(self.camera.cfg.offset.rot, device=self.device).expand(self.num_envs, -1).clone() - self.nominal_position, self.nominal_rotation = self.position.clone(), self.rotation.clone() - self.intrinsics = ( - torch.tensor(self.camera.cfg.camera_calibration["intrinsics"], device=self.device) - .expand(self.num_envs, -1) - .clone() - ) - self.nominal_intrinsics = self.intrinsics.clone() - self.radial = torch.zeros(self.num_envs, device=self.device) - self.targets = torch.zeros(self.num_envs, 9, device=self.device) - self.nominal = torch.ones(self.num_envs, dtype=torch.bool, device=self.device) - self.photo = torch.ones(self.num_envs, 7, device=self.device) - self.photo[:, 5:] = 0 - env.so101_camera_randomization = self - - def __call__(self, env, env_ids): + self.camera = env.scene[cfg.params["camera_name"]] + offset = self.camera.cfg.offset + self.nominal_position = torch.tensor(offset.pos, device=self.device).expand(self.num_envs, -1).clone() + """Nominal mount position in the environment frame [m].""" + self.nominal_rotation = torch.tensor(offset.rot, device=self.device).expand(self.num_envs, -1).clone() + """Nominal mount orientation (x, y, z, w), OpenGL convention.""" + self.position = self.nominal_position.clone() + self.rotation = self.nominal_rotation.clone() + self.labels = torch.zeros(self.num_envs, 9, device=self.device) + """The move of each mount in the robot base frame, scaled for the extrinsics head, shape (num_envs, 9).""" + + def strength(self, ramp_steps: int) -> float: + return min(1.0, max(0.1, self._env.common_step_counter / ramp_steps)) if ramp_steps else 1.0 + + def __call__( + self, + env, + env_ids, + camera_name: str = "eye", + position_range: float = 0.03, + rotation_range_deg: float = 7.0, + nominal_fraction: float = 0.2, + ramp_steps: int = 30000, + ): ids = torch.arange(self.num_envs, device=self.device)[slice(None) if env_ids is None else env_ids] - n = len(ids) - if n == 0: + if not len(ids): return - cfg = self.options - strength = self.strength + strength = self.strength(ramp_steps) env.extras.setdefault("log", {})["Randomization/camera_strength"] = strength - nominal = torch.rand(n, device=self.device) < cfg["nominal_fraction"] - self.nominal[ids] = nominal - active = (~nominal).float()[:, None] + moved = (torch.rand(len(ids), device=self.device) >= nominal_fraction).float()[:, None] * strength - def uniform(width, bound): - return torch.empty(n, width, device=self.device).uniform_(-bound, bound) * active * strength + def uniform(bound): + return torch.empty(len(ids), 3, device=self.device).uniform_(-bound, bound) * moved - delta = uniform(3, cfg["position_range"]) - perturb = quat_from_euler_xyz(*uniform(3, math.radians(cfg["rotation_deg"])).T) + delta = uniform(position_range) + perturb = quat_from_euler_xyz(*uniform(math.radians(rotation_range_deg)).T) self.position[ids] = self.nominal_position[ids] + delta self.rotation[ids] = quat_mul(self.nominal_rotation[ids], perturb) robot_rotation = env.scene["robot"].data.root_quat_w.torch[ids] - # Translation in the robot-base frame; rotation relative to its nominal - # camera mount. Neither label includes environment-grid coordinates. - self.targets[ids] = pose_targets(quat_apply_inverse(robot_rotation, delta), matrix_from_quat(perturb)) - self.camera.set_physical_poses(self.position[ids] + env.scene.env_origins[ids], self.rotation[ids], env_ids=ids) - self.camera.reset(env_ids=ids) - if "diagnostic_camera" in env.scene.sensors: - diagnostic = env.scene["diagnostic_camera"] - diagnostic.set_world_poses( - self.position[ids] + env.scene.env_origins[ids], - self.rotation[ids], - env_ids=ids, - convention="opengl", - ) - diagnostic.reset(env_ids=ids) - # Tutorial photometric families, held fixed for the whole episode. - # exposure, contrast, gamma, white-balance R/B, brightness, blur mix. - for index, (lo, hi) in enumerate( - ( - (0.75, 1.25), - (0.85, 1.15), - (0.85, 1.15), - (0.9, 1.1), - (0.9, 1.1), - (-0.05, 0.05), - (0, 0.5), - ) - ): - base = 0.0 if index >= 5 else 1.0 - self.photo[ids, index] = ( - base + (torch.empty(n, device=self.device).uniform_(lo, hi) - base) * active[:, 0] * strength - ) - - def visibility(self, directions): - return lens_visibility(directions[:, None], self.intrinsics, self.radial, (640, 640)).squeeze(-1) - - def gaze_direction(self, directions, ids=None): - """True scene ray -> physical pixel -> uncalibrated action coordinates.""" - selection = slice(None) if ids is None else ids - pixels = ( - directions[:, :2] / directions[:, 2:].clamp_min(1e-7) * self.intrinsics[selection, :2] - + self.intrinsics[selection, 2:] - ) - return self.retina.angles(pixels) - - @property - def strength(self): - ramp = self.options["ramp_steps"] - return min(1.0, max(0.1, self._env.common_step_counter / ramp)) if ramp else 1.0 - - def image(self, images): - from torch.nn import functional as F - - valid = self.camera.public_valid - rgb = images[..., :3].permute(0, 3, 1, 2).float() / 255 - values = self.photo[:, :, None, None] - blurred = F.avg_pool2d(rgb, 3, stride=1, padding=1, count_include_pad=False) - rgb = rgb.lerp(blurred, values[:, 6:7]).pow(values[:, 2:3]) - rgb = (rgb - 0.5) * values[:, 1:2] + 0.5 - white = torch.cat((values[:, 3:4], torch.ones_like(values[:, :1]), values[:, 4:5]), 1) - rgb = (rgb * values[:, :1] * white + values[:, 5:6]).clamp(0, 1) - # Preserve the physical camera/retinal footprint after color transforms. - return (rgb.permute(0, 2, 3, 1) * 255).round().to(torch.uint8).masked_fill(~valid, 0) + # Translation in the robot base frame, rotation relative to the nominal mount; no environment-grid offset. + self.labels[ids] = pose_targets(quat_apply_inverse(robot_rotation, delta), matrix_from_quat(perturb)) + world = self.position[ids] + env.scene.env_origins[ids] + self.camera.set_world_poses(world, self.rotation[ids], env_ids=ids, convention="opengl") + +def mount_randomization(env) -> randomize_camera_mount | None: + """The episode's camera-mount randomization, or None when the camera stays on its nominal mount.""" + for name in env.event_manager.active_terms.get("reset", []): + term = env.event_manager.get_term_cfg(name).func + if isinstance(term, randomize_camera_mount): + return term + return None -def extrinsics_labels(env): - state = getattr(env, "so101_camera_randomization", None) - if state is None: - return torch.zeros(env.num_envs, 9, device=env.device) - return state.targets.clone() + +def extrinsics_labels(env) -> torch.Tensor: + """Labels of the camera mount's move for the actor's extrinsics head, shape (num_envs, 9).""" + term = mount_randomization(env) + return term.labels.clone() if term is not None else torch.zeros(env.num_envs, 9, device=env.device) @configclass class ExtrinsicsObservations(ObservationGroupCfg): + """Training labels of the camera mount's move; never part of the actor's observations.""" + pose = ObservationTermCfg(func=extrinsics_labels) enable_corruption = False - - -def configure(cfg): - """Apply physical and appearance randomization while retaining numbered SGS resets.""" - from isaaclab_tutorial.active_gaze.randomization_cfg import ( - AppearanceRandomizationEventsCfg, - RandomizedSceneAssetsCfg, - ) - - # Keep the calibrated geometry, controller scales, and mid-task reset - # distribution used by the pretrained actor. - reset = deepcopy(cfg.events.reset_from_dataset) - events = AppearanceRandomizationEventsCfg() - reset.params.update( - { - key: value - for key, value in events.reset_from_dataset.params.items() - if key not in ("dataset_path", "phase_weights", "sequential") - } - ) - events.reset_from_dataset = reset - cfg.events = events - appearance = RandomizedSceneAssetsCfg() - cfg.scene.support = appearance.support - cfg.scene.fixed_jaw_support = appearance.fixed_jaw_support - cfg.scene.moving_jaw_support = appearance.moving_jaw_support - for name in ( - "robot_visual", - "desk_visual", - "rack_visual", - "vial_body_visual", - "vial_cap_visual", - ): - setattr(cfg.scene, name, deepcopy(getattr(appearance, name))) - for spawn in cfg.scene.vial.spawn.assets_cfg: - spawn.randomize_diameters = True - configure_planar_camera(cfg) - - -def configure_planar_camera(cfg): - cfg.events.scene_camera = EventTermCfg(func=CameraRandomization, mode="reset") - cfg.scene.eye.class_type = PlanarSceneCamera - cfg.scene.eye.field_geometry = "planar" - cfg.scene.eye.update_latest_camera_pose = True - cfg.observations.vision.tokens.func = RandomizedDinoTokens diff --git a/src/isaaclab_tutorial/active_gaze/transfer_options.py b/src/isaaclab_tutorial/active_gaze/transfer_options.py deleted file mode 100644 index 5a6975f..0000000 --- a/src/isaaclab_tutorial/active_gaze/transfer_options.py +++ /dev/null @@ -1,32 +0,0 @@ -"""Typed camera randomization settings for the SO-101 transfer preset.""" - -import math - -from isaaclab.utils import configclass - - -@configclass -class CameraRandomizationCfg: - position_range: float = 0.03 - rotation_deg: float = 7.0 - nominal_fraction: float = 0.2 - ramp_steps: int = 30000 - - def validate_config(self): - settings(self) - - -DEFAULTS = CameraRandomizationCfg().to_dict() - - -def settings(overrides=None): - if isinstance(overrides, CameraRandomizationCfg): - overrides = overrides.to_dict() - result = DEFAULTS | (overrides or {}) - if set(result) != set(DEFAULTS): - raise ValueError("Unknown SO-101 sim2real setting") - if any(not math.isfinite(v) or v < 0 for v in result.values()): - raise ValueError("Sim2real ranges must be finite and nonnegative") - if result["nominal_fraction"] > 1: - raise ValueError("Invalid nominal sampling fraction") - return result From 2678465ddd6ea0742620556db0da611ad5c25c5d Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:06:42 -0800 Subject: [PATCH 11/30] Exit DINO after a configurable number of layers env.observations.vision.tokens.params.num_layers keeps the first transformer layers of the frozen encoder and its final normalization, cutting the cost of perception while keeping pretrained features. None runs every layer. --- src/isaaclab_tutorial/active_gaze/env_cfg.py | 2 ++ .../active_gaze/learning/dino.py | 27 +++++++++++++++++-- .../active_gaze/learning/observations.py | 9 ++++++- tests/active_gaze/test_language.py | 22 +++++++++++++++ 4 files changed, 57 insertions(+), 3 deletions(-) diff --git a/src/isaaclab_tutorial/active_gaze/env_cfg.py b/src/isaaclab_tutorial/active_gaze/env_cfg.py index cc6528a..e656925 100644 --- a/src/isaaclab_tutorial/active_gaze/env_cfg.py +++ b/src/isaaclab_tutorial/active_gaze/env_cfg.py @@ -261,6 +261,8 @@ class VisionCfg(ObservationGroupCfg): reference=DEFAULT_CHECKPOINT, checksum=DEFAULT_MD5, batch_size=128, + # Transformer layers to run before exiting; None runs all of them. + num_layers=None, data_type=CameraOutputNameCfg(), photometric=PHOTOMETRIC, ), diff --git a/src/isaaclab_tutorial/active_gaze/learning/dino.py b/src/isaaclab_tutorial/active_gaze/learning/dino.py index 47f8724..30d7fd4 100644 --- a/src/isaaclab_tutorial/active_gaze/learning/dino.py +++ b/src/isaaclab_tutorial/active_gaze/learning/dino.py @@ -76,19 +76,42 @@ def load_backbone(reference: str, checksum: str | None) -> nn.Module: return backbone.requires_grad_(False).eval() +def keep_layers(backbone: nn.Module, num_layers: int | None) -> nn.Module: + """Exit after the first ``num_layers`` transformer layers; None keeps them all. + + The final normalization still applies, as for DINO's intermediate-layer features. + """ + if num_layers is None: + return backbone + # Transformers keeps the layers at "layer" or "model.layer", depending on its release. + layers = next( + module + for name, module in backbone.named_modules() + if name.rpartition(".")[2] == "layer" and isinstance(module, nn.ModuleList) + ) + if not 1 <= num_layers <= len(layers): + raise ValueError(f"DINO num_layers must be in [1, {len(layers)}], got {num_layers}.") + del layers[num_layers:] + return backbone + + class FrozenDino(nn.Module): - """Encode upright uint8 BHWC retinal images into unpooled patch tokens.""" + """Encode upright uint8 BHWC retinal images into unpooled patch tokens. + + ``num_layers`` exits early, after that many transformer layers, to cut the cost of perception. + """ def __init__( self, reference: str = DEFAULT_CHECKPOINT, checksum: str | None = DEFAULT_MD5, batch_size: int = 128, + num_layers: int | None = None, ): super().__init__() if batch_size <= 0: raise ValueError("DINO batch size must be positive.") - self.backbone = load_backbone(reference, checksum) + self.backbone = keep_layers(load_backbone(reference, checksum), num_layers) self.batch_size = batch_size self.register_buffer("mean", torch.tensor((0.485, 0.456, 0.406))[None, :, None, None]) self.register_buffer("std", torch.tensor((0.229, 0.224, 0.225))[None, :, None, None]) diff --git a/src/isaaclab_tutorial/active_gaze/learning/observations.py b/src/isaaclab_tutorial/active_gaze/learning/observations.py index 1406fa7..f5986c2 100644 --- a/src/isaaclab_tutorial/active_gaze/learning/observations.py +++ b/src/isaaclab_tutorial/active_gaze/learning/observations.py @@ -29,7 +29,14 @@ def reset(self, env_ids=None): self.photometric.reset(env_ids) def __call__( - self, env, reference: str, checksum: str | None, batch_size: int, data_type: str = "rgb", photometric=None + self, + env, + reference: str, + checksum: str | None, + batch_size: int, + num_layers: int | None = None, + data_type: str = "rgb", + photometric=None, ): if not getattr(env, "refresh_policy_vision", True) and self.cached is not None: return self.cached diff --git a/tests/active_gaze/test_language.py b/tests/active_gaze/test_language.py index 393d98e..0aa6b69 100644 --- a/tests/active_gaze/test_language.py +++ b/tests/active_gaze/test_language.py @@ -8,6 +8,28 @@ from tensordict import TensorDict +def test_dino_early_exit_keeps_the_pretrained_layers(): + from transformers import DINOv3ViTConfig, DINOv3ViTModel + + from isaaclab_tutorial.active_gaze.learning.dino import keep_layers + + def config(layers): + return DINOv3ViTConfig( + hidden_size=32, intermediate_size=64, num_attention_heads=2, num_hidden_layers=layers, image_size=32 + ) + + torch.manual_seed(0) + full = DINOv3ViTModel(config(4)).eval() + short = DINOv3ViTModel(config(2)).eval() + short.load_state_dict(full.state_dict(), strict=False) + pixels = torch.randn(2, 3, 32, 32) + with torch.no_grad(): + expected = short(pixel_values=pixels).last_hidden_state + assert torch.equal(keep_layers(full, 2)(pixel_values=pixels).last_hidden_state, expected) + with pytest.raises(ValueError, match="num_layers"): + keep_layers(full, 3) + + def test_language_configuration_keeps_numbered_task_and_critic(): from isaaclab_tutorial.active_gaze.configuration import compose from isaaclab_tutorial.active_gaze.language import instruction_index From 22b0796895ca896068d1b009424d516f2746d848 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:08:53 -0800 Subject: [PATCH 12/30] Describe each run in run.json and drive training from the resolved configuration train.py composes the task from Isaac Lab overrides and writes run.json: retina in degrees and its camera model, gaze in field radii, control rates, gaze supervision, extrinsics and DINO settings. Resuming replays the saved overrides. The runner finds the reset sampler through the curriculum manager and checkpoints the control-step count. The W&B writer takes an optional entity and uploads run.json. The unused periodic-evaluation runner is removed. --- .../active_gaze/calibrate.py | 4 +- .../active_gaze/configuration.py | 116 ++-- .../active_gaze/learning/runner.py | 161 +---- src/isaaclab_tutorial/active_gaze/runner.py | 50 +- src/isaaclab_tutorial/active_gaze/train.py | 555 +++++++----------- .../active_gaze/training/__init__.py | 2 +- .../active_gaze/training/evaluation.py | 238 -------- .../active_gaze/training/tracking.py | 71 +-- tests/active_gaze/test_evaluation.py | 551 ----------------- 9 files changed, 336 insertions(+), 1412 deletions(-) delete mode 100644 src/isaaclab_tutorial/active_gaze/training/evaluation.py delete mode 100644 tests/active_gaze/test_evaluation.py diff --git a/src/isaaclab_tutorial/active_gaze/calibrate.py b/src/isaaclab_tutorial/active_gaze/calibrate.py index 0329499..3dee7c9 100644 --- a/src/isaaclab_tutorial/active_gaze/calibrate.py +++ b/src/isaaclab_tutorial/active_gaze/calibrate.py @@ -184,9 +184,9 @@ def main(): parser.add_argument("--resume", action="store_true") parser.add_argument("--checkpoint", type=Path) args, recipe = parser.parse_known_args() - from .configuration import compose + from .configuration import RUN_FILE, compose - saved = json.loads(args.checkpoint.with_name("example.json").read_text()) if args.checkpoint else None + saved = json.loads(args.checkpoint.with_name(RUN_FILE).read_text()) if args.checkpoint else None try: _, agent, recipe = compose(recipe, saved) except ValueError as exc: diff --git a/src/isaaclab_tutorial/active_gaze/configuration.py b/src/isaaclab_tutorial/active_gaze/configuration.py index 1155186..f8cdc14 100644 --- a/src/isaaclab_tutorial/active_gaze/configuration.py +++ b/src/isaaclab_tutorial/active_gaze/configuration.py @@ -1,24 +1,33 @@ -"""Compose saved recipes with Isaac Lab's task registry and preset resolver.""" +"""Compose a run's configuration and describe what it trained, for resuming and for robot deployment.""" +from __future__ import annotations + +import dataclasses from collections.abc import Sequence +from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model, sampling_geometry + from isaaclab_tasks.utils import resolve_task_config +from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import ARM_JOINTS + from . import TASK_ID +from .goals import NumberedResetFromDataset +from .language import INSTRUCTIONS + +RUN_FILE = "run.json" +"""Name of the file, next to a run's checkpoints, that describes what the run trained.""" def compose(overrides: Sequence[str] = (), saved: dict | None = None): - """Resolve the same env/agent classes used by the standard Isaac Lab CLI. + """Resolve the environment and agent the standard Isaac Lab CLI would build. - A new value replaces the saved value at the same override path. An explicit - ``presets=`` replaces the saved preset list, matching native selector semantics. + A resumed run starts from its saved overrides; a new value replaces the saved value at the same path, and an + explicit ``presets=`` replaces the saved preset list. """ saved = saved or {} - if saved and "configuration" not in saved: - raise ValueError("Checkpoint requires a native configuration recipe") - previous = saved.get("configuration", []) merged = {} - for override in [*previous, *overrides]: + for override in [*saved.get("overrides", []), *overrides]: key, separator, value = override.partition("=") if not separator: raise ValueError(f"Expected an Isaac Lab configuration override, got {override!r}") @@ -27,21 +36,20 @@ def compose(overrides: Sequence[str] = (), saved: dict | None = None): env, agent = resolve_task_config(TASK_ID, "rsl_rl_cfg_entry_point", overrides=recipe) env.validate() agent.validate() - if saved and saved.get("policy", {}).get("name", "cnn") != env.policy: - raise ValueError("Changing policy architecture requires a fresh run") - chunk_size = getattr(agent.algorithm, "action_chunk_size", 1) - if type(chunk_size) is not int or chunk_size < 1: - raise ValueError("Action chunk size must be a positive integer") - if saved and saved.get("action_chunk_size", 1) != chunk_size: - raise ValueError("Changing action chunk size requires a fresh run") + if saved: + current = describe(env, agent) + for name in ("policy", "action_chunk_size"): + if saved[name] != current[name]: + raise ValueError(f"Changing {name} requires a fresh run") + if saved.get("dino", {}).get("num_layers") != current.get("dino", {}).get("num_layers"): + raise ValueError("Changing the DINO exit layer requires a fresh run") return env, agent, recipe -def checkpoint_configuration(overrides: Sequence[str], agent) -> list[str]: - """Save task settings without repeating a one-time fine-tune on resume. +def resume_overrides(overrides: Sequence[str], agent) -> list[str]: + """The overrides to save for resuming, without a one-time fine-tune. - Preserve the selected fine-tune learning rate as a native scalar override. - A subsequent fine-tune can select its rate explicitly in the new run. + A fine-tuned run resumes at the fine-tuning learning rate, as an explicit value. """ recipe = [] for override in overrides: @@ -60,38 +68,56 @@ def checkpoint_configuration(overrides: Sequence[str], agent) -> list[str]: return recipe -def metadata(env, agent): - """Keep the deployment/checkpoint metadata derived from the resolved config.""" +def describe(env, agent) -> dict: + """What a run trains: task, policy, retina, gaze and control, read from its resolved configuration.""" + eye = env.scene.eye + fov_deg, cmf_a_deg = sampling_geometry(eye) + gaze = env.actions.gaze algorithm = agent.algorithm + language = getattr(env.observations, "vision", None) is not None + scale = env.actions.arm_action.scale + chunk = algorithm.action_chunk_size + control_hz = 1.0 / (env.sim.dt * env.decimation) result = dict( - action_chunk_size=getattr(algorithm, "action_chunk_size", 1), - goal_mode=env.goal_mode, - renderer=env.renderer_backend(), - render_mode=env.render_mode(), - resolution=env.resolution(), - retinal_geometry=env.retinal_geometry(), - camera=dict( - camera_position=env.camera_position(), - camera_hfov=env.camera_hfov(), - gaze_limit=env.gaze_limit(), - gaze_max_delta=env.gaze_max_delta(), - mixed_gaze_resets=env.mixed_gaze_resets, - cmf_a=env.cmf_a(), + task=TASK_ID, + goal="numbered" if env.events.reset_from_dataset.func is NumberedResetFromDataset else "nearest", + policy="dino_language" if language else "cnn", + sim2real="camera_mount" in vars(env.events), + retina=dict( + fov_deg=fov_deg, + cmf_a_deg=cmf_a_deg, + resolution=eye.foveated_res, + camera_model=dataclasses.asdict(resolve_camera_model(eye)), + mount_position=eye.offset.pos, + mount_rotation=eye.offset.rot, ), - robot=dict(wrist_camera=env.wrist_camera()), - gaze_supervision=dict( - mode="grasp_gated" if env.observations.oracle is not None else "none", - weight=getattr(algorithm, "oracle_weight", 0.0), - std=getattr(algorithm, "oracle_std", 1e-4), + gaze=dict( + step_size=gaze.step_size, + limit=gaze.gaze_limit, + field_radius_deg=fov_deg / 2, + mixed_resets=gaze.mixed_resets, ), - reset_sampling=dict(env.curriculum.reset_sampling.params), - sim2real=env.sim2real.to_dict() if env.sim2real is not None else None, + control=dict( + action_scale=[scale[name] if isinstance(scale, dict) else scale for name in ARM_JOINTS] + + [env.actions.gripper_action.scale], + physics_hz=1.0 / env.sim.dt, + control_hz=control_hz, + policy_hz=control_hz / chunk, + ), + action_chunk_size=chunk, + gaze_supervision_weight=algorithm.oracle_weight, extrinsics_weight=getattr(algorithm, "extrinsics_weight", 0.0), - policy=dict(name=env.policy, extrinsics_head=env.extrinsics_head()), + reset_sampling=dict(env.curriculum.reset_sampling.params), ) - if env.policy == "dino_language": + if language: tokens = env.observations.vision.tokens.params - result["policy"].update( - dino_checkpoint=tokens["reference"], dino_checksum=tokens["checksum"], dino_batch_size=tokens["batch_size"] + result.update( + dino=dict( + reference=tokens["reference"], + checksum=tokens["checksum"], + batch_size=tokens["batch_size"], + num_layers=tokens["num_layers"], + ), + instructions=list(INSTRUCTIONS), ) return result diff --git a/src/isaaclab_tutorial/active_gaze/learning/runner.py b/src/isaaclab_tutorial/active_gaze/learning/runner.py index 4269b23..65b718a 100644 --- a/src/isaaclab_tutorial/active_gaze/learning/runner.py +++ b/src/isaaclab_tutorial/active_gaze/learning/runner.py @@ -2,20 +2,12 @@ # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause -"""Native RSL-RL training with periodic rollout-only evaluation blocks. - -The learning loop is adapted from RSL-RL 5.5.1 (BSD-3-Clause) to insert -evaluation between updates and explicitly replace the post-reset observation. -""" +"""Native RSL-RL training across GPUs, with NCCL bound before the simulator starts.""" import os -import time import torch from rsl_rl.runners import OnPolicyRunner -from rsl_rl.utils import check_nan - -from isaaclab_tutorial.active_gaze.training.evaluation import PeriodicEvaluation, coordinated_errors def initialize_distributed(): @@ -37,10 +29,7 @@ def initialize_distributed(): torch.distributed.all_reduce(probe) if probe.item() != world_size: raise RuntimeError("Distributed startup collective failed") - print( - f"ISAACLAB_FOVI_DISTRIBUTED rank={rank} local_rank={local_rank} world_size={world_size} ready", - flush=True, - ) + print(f"Distributed rank={rank} local_rank={local_rank} world_size={world_size} ready", flush=True) if torch.distributed.get_rank() != rank or torch.distributed.get_world_size() != world_size: raise ValueError("Existing process group differs from the requested ranks") @@ -63,149 +52,3 @@ def _configure_multi_gpu(self): "local_rank": self.gpu_local_rank, "world_size": self.gpu_world_size, } - - -class EvaluationOnPolicyRunner(DistributedOnPolicyRunner): - """Native PPO and gradient reduction, with evaluation between updates.""" - - def __init__(self, env, train_cfg, log_dir=None, device="cpu"): - super().__init__(env, train_cfg, log_dir, device) - self.current_learning_iteration = -1 - self.evaluation = PeriodicEvaluation(env, self.cfg.get("evaluation", {})) - - def _log_action_diagnostics(self, iteration): - """Separate motor/gaze saturation; aggregate only executed chunk prefixes.""" - writer = self.logger.writer - if writer is None and not self.is_distributed: - return - storage = self.alg.storage - mean, std = storage.distribution_params - shape = (*storage.actions.shape[:2], self.env.chunk_size, -1) - actions, mean, std = (value.reshape(shape) for value in (storage.actions, mean, std)) - valid = storage.observations.get("chunk_valid") - if valid is None: - valid = torch.ones(actions.shape[:-1], device=actions.device, dtype=torch.bool) - motor = self.env.unwrapped.action_manager.get_term("motor") - groups = { - "arm": slice(0, motor.arm_action_dim), - "hand": slice(motor.arm_action_dim, motor.action_dim), - "gaze": slice(motor.action_dim, motor.action_dim + 2), - } - names, sums, counts = [], [], [] - for name, selection in groups.items(): - count = valid.sum() * actions[..., selection].shape[-1] - mask = valid[..., None] - measures = { - "latent_std": std[..., selection], - "latent_mean_abs": mean[..., selection].abs(), - "saturation": (actions[..., selection].abs() >= 1).float(), - } - for measure, value in measures.items(): - names.append(f"Policy/{name}/{measure}") - sums.append(torch.where(mask, value, 0.0).sum()) - counts.append(count) - totals = torch.stack((torch.stack(sums), torch.stack(counts))) - if self.is_distributed: - torch.distributed.all_reduce(totals) - values = totals[0] / totals[1].clamp_min(1) - if writer is not None: - for name, value in zip(names, values.tolist(), strict=True): - writer.add_scalar(name, value, iteration) - - @property - def training_control_steps(self): - """Derive cadence from native checkpoint progress; no second saved counter.""" - return (self.current_learning_iteration + 1) * self.cfg["num_steps_per_env"] * self.env.chunk_size - - def learn(self, num_learning_iterations: int, init_at_random_ep_len: bool = False) -> None: - """Run the learning loop for the specified number of iterations.""" - # Randomize initial episode lengths (for exploration) - if init_at_random_ep_len: - self.env.episode_length_buf = torch.randint_like( - self.env.episode_length_buf, high=int(self.env.max_episode_length) - ) - - # Start learning - obs = self.env.get_observations().to(self.device) - self.alg.train_mode() # switch to train mode (for dropout for example) - - # Ensure all parameters are in-synced - if self.is_distributed: - print(f"Synchronizing parameters for rank {self.gpu_global_rank}...") - self.alg.broadcast_parameters() - - # Initialize the logging writer - self.logger.init_logging_writer() - - # Start training - start_it = self.current_learning_iteration + 1 - self.logger.tot_timesteps = start_it * self.cfg["num_steps_per_env"] * self.env.num_envs * self.gpu_world_size - total_it = start_it + num_learning_iterations - for it in range(start_it, total_it): - start = time.time() - # Rollout - with torch.inference_mode(): - for _ in range(self.cfg["num_steps_per_env"]): - # Sample actions - actions = self.alg.act(obs) - # Step the environment - obs, rewards, dones, extras = self.env.step(actions.to(self.env.device)) - # Check for NaN values from the environment - if self.cfg.get("check_for_nan", True): - check_nan(obs, rewards, dones) - # Move to device - obs, rewards, dones = ( - obs.to(self.device), - rewards.to(self.device), - dones.to(self.device), - ) - # Process the step - self.alg.process_env_step(obs, rewards, dones, extras) - # Extract intrinsic rewards if RND is used (only for logging) - intrinsic_rewards = self.alg.intrinsic_rewards if self.cfg["algorithm"].get("rnd_cfg") else None - # Book keeping - self.logger.process_env_step(rewards, dones, extras, intrinsic_rewards) - - stop = time.time() - collect_time = stop - start - start = stop - - # Compute returns - self.alg.compute_returns(obs) - - # Update policy - self._log_action_diagnostics(it) - loss_dict = self.alg.update() - - stop = time.time() - learn_time = stop - start - self.current_learning_iteration = it - - # Log information - self.logger.log( - it=it, - start_it=start_it, - total_it=total_it, - collect_time=collect_time, - learn_time=learn_time, - loss_dict=loss_dict, - learning_rate=self.alg.learning_rate, - action_std=self.alg.get_policy().output_std, - rnd_weight=self.alg.rnd.weight if self.cfg["algorithm"].get("rnd_cfg") else None, - ) - - previous_steps = self.training_control_steps - self.cfg["num_steps_per_env"] * self.env.chunk_size - evaluate = self.evaluation.due(previous_steps, self.training_control_steps) - # Preserve the exact policy shown in each evaluation video, including - # early blocks that fall between the regular checkpoint intervals. - if evaluate or it % self.cfg["save_interval"] == 0: - with coordinated_errors(self): - if self.logger.writer is not None: - self.save(os.path.join(self.logger.log_dir, f"model_{it}.pt")) # type: ignore - if evaluate: - obs = self.evaluation.run(self) - - # Save the final model after training and stop the logging writer - if self.logger.writer is not None: - self.save(os.path.join(self.logger.log_dir, f"model_{self.current_learning_iteration}.pt")) # type: ignore - self.logger.stop_logging_writer() diff --git a/src/isaaclab_tutorial/active_gaze/runner.py b/src/isaaclab_tutorial/active_gaze/runner.py index 449c223..e363e5f 100644 --- a/src/isaaclab_tutorial/active_gaze/runner.py +++ b/src/isaaclab_tutorial/active_gaze/runner.py @@ -1,14 +1,22 @@ -"""Native PPO runner with checkpointed reset statistics and episode-weighted logs.""" +"""PPO runner that checkpoints the reset sampler and the control-step count, and logs episode-weighted reset metrics.""" -from isaaclab_tutorial.active_gaze.learning.runner import DistributedOnPolicyRunner +import torch +from .learning.runner import DistributedOnPolicyRunner from .sampling import iteration_metrics class ResetSamplingRunner(DistributedOnPolicyRunner): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.sampler = self.env.unwrapped.reset_sampling + """Gaze-supervised PPO with the curriculum's reset sampler saved in every checkpoint. + + Args: + restore_sampler: Restore the checkpoint's reset statistics on load. Playback and inspection keep their own. + """ + + def __init__(self, env, train_cfg, log_dir=None, device="cpu", restore_sampler: bool = True): + super().__init__(env, train_cfg, log_dir, device) + self.sampler = env.unwrapped.curriculum_manager.get_term_cfg("reset_sampling").func + self.restore_sampler = restore_sampler self._previous_counts = None original_log = self.logger.log @@ -24,42 +32,32 @@ def log(**kwargs): self.logger.log = log def learn(self, num_learning_iterations, init_at_random_ep_len=False): - import torch - - self._previous_counts = torch.stack( - ( - self.sampler.history.episodes, - self.sampler.history.successes, - self.sampler.sampled, - ) - ).clone() + history = self.sampler.history + self._previous_counts = torch.stack((history.episodes, history.successes, self.sampler.sampled)).clone() if init_at_random_ep_len: # The staggered first episodes have shortened horizons; exclude their outcomes. self.sampler.eligible.zero_() return super().learn(num_learning_iterations, init_at_random_ep_len) def save(self, path, infos=None): - infos = dict(infos or {}, reset_sampling=self.sampler.state_dict()) - infos["sim2real_control_steps"] = self.env.unwrapped.common_step_counter + env = self.env.unwrapped + # The control-step count drives step-based ramps, such as the camera mount's randomization. + infos = dict(infos or {}, reset_sampling=self.sampler.state_dict(), control_steps=env.common_step_counter) super().save(path, infos) def load(self, path, load_cfg=None, strict=True, map_location=None): - infos = super().load(path, load_cfg, strict, map_location) - if infos and "sim2real_control_steps" in infos: - self.env.unwrapped.common_step_counter = infos["sim2real_control_steps"] - # Playback uses canonical home starts and must not restore/adapt training sampling. - if not self.env.unwrapped.cfg.reset_sampling_evaluation and infos and "reset_sampling" in infos: + infos = super().load(path, load_cfg, strict, map_location) or {} + if "control_steps" in infos: + self.env.unwrapped.common_step_counter = infos["control_steps"] + if self.restore_sampler and "reset_sampling" in infos: self.sampler.load_state_dict(infos["reset_sampling"]) return infos def finetune(self, path, map_location=None): - """Warm-start all learned state, permitting only a new camera-pose head. + """Warm-start the actor and critic, allowing only a new extrinsics head. - The changed environment starts fresh optimizer and SGS histories. Shape - mismatches or unrelated missing weights still fail strictly. + The optimizer and the reset statistics start fresh. Shape mismatches or other missing weights fail. """ - import torch - packed = torch.load(path, map_location=map_location, weights_only=False) actor = self.alg._raw_actor target = actor.state_dict() diff --git a/src/isaaclab_tutorial/active_gaze/train.py b/src/isaaclab_tutorial/active_gaze/train.py index 6ccfa7e..9c4ed44 100644 --- a/src/isaaclab_tutorial/active_gaze/train.py +++ b/src/isaaclab_tutorial/active_gaze/train.py @@ -1,4 +1,10 @@ -"""Train, evaluate, and visually inspect the SO-101 foveated PPO task.""" +"""Train, play and inspect the active-gaze task. + +``train`` runs gaze-supervised PPO, with action chunking when the ``chunking`` preset is selected. ``play`` records +videos of a checkpoint, optionally through an exported LEAPP bundle to check that it matches. ``inspect`` sweeps the +gaze through every reset category. Every run writes ``run.json`` (see :func:`.configuration.describe`) next to its +checkpoints. Remaining arguments are Isaac Lab configuration overrides, for example ``presets=dino_language``. +""" import argparse import hashlib @@ -13,42 +19,41 @@ def main(): wp.config.enable_backward = False from isaaclab.app import add_launcher_args, launch_simulation + from isaaclab_tasks.utils import setup_preset_cli - from . import TASK_ID - from .configuration import checkpoint_configuration, compose - from .configuration import metadata as config_metadata + from .configuration import RUN_FILE, compose, describe, resume_overrides from .sampling import iteration_metrics parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--task", default=TASK_ID) parser.add_argument("mode", choices=("train", "play", "inspect")) parser.add_argument("--num_envs", type=int, default=None) parser.add_argument("--iterations", type=int, default=None) - parser.add_argument("--steps", type=int, default=600) + parser.add_argument("--steps", type=int, default=600, help="Control steps to record in play and inspect.") parser.add_argument("--seed", type=int, default=None) parser.add_argument("--checkpoint", type=Path) - parser.add_argument("--deployment_bundle", type=Path, help="Play through an exported LEAPP bundle") - parser.add_argument("--deployment_camera", action="store_true", help="Feed the dense diagnostic camera to LEAPP") + parser.add_argument("--deployment_bundle", type=Path, help="Play through an exported LEAPP bundle.") + parser.add_argument("--deployment_camera", action="store_true", help="Feed the dense camera to the bundle.") parser.add_argument("--output", type=Path, required=True) parser.add_argument("--save_interval", type=int, default=None) parser.add_argument("--minibatches", type=int, default=None) parser.add_argument("--logger", choices=("tensorboard", "wandb"), default="tensorboard") - parser.add_argument("--diagnostics", action="store_true") + parser.add_argument("--wandb_entity", help="W&B entity; defaults to the W&B login's.") + parser.add_argument("--wandb_project", default="isaaclab_tutorial_active_gaze") + parser.add_argument("--wandb_group") + parser.add_argument("--diagnostics", action="store_true", help="Also record a dense camera at the eye's pose.") parser.add_argument("--measure_memory", action="store_true") parser.add_argument("--memory_warmup", type=int, default=4) add_launcher_args(parser) args, overrides = setup_preset_cli(parser) - if args.task != TASK_ID: - parser.error(f"This recorder supports {TASK_ID}; use the standard Isaac Lab CLI for other tasks") - saved_settings = {} + saved = {} if args.checkpoint: - saved_path = args.checkpoint.parent / "example.json" + saved_path = args.checkpoint.parent / RUN_FILE if not saved_path.is_file(): - parser.error("Checkpoint requires its companion example.json settings") - saved_settings = json.loads(saved_path.read_text()) + parser.error(f"A checkpoint needs the {RUN_FILE} written next to it") + saved = json.loads(saved_path.read_text()) try: - cfg, agent_cfg, overrides = compose(overrides, saved_settings) + cfg, agent_cfg, overrides = compose(overrides, saved) except ValueError as exc: parser.error(str(exc)) args.num_envs = args.num_envs if args.num_envs is not None else cfg.scene.num_envs @@ -56,10 +61,9 @@ def main(): args.seed = args.seed if args.seed is not None else agent_cfg.seed args.save_interval = args.save_interval if args.save_interval is not None else agent_cfg.save_interval args.minibatches = args.minibatches if args.minibatches is not None else agent_cfg.algorithm.num_mini_batches - args.finetune = agent_cfg.finetune - policy = cfg.policy - chunk_size = getattr(agent_cfg.algorithm, "action_chunk_size", 1) + chunk_size = agent_cfg.algorithm.action_chunk_size control_gamma = agent_cfg.algorithm.gamma + description = describe(cfg, agent_cfg) if min(args.num_envs, args.iterations, args.steps, args.save_interval, args.minibatches) <= 0: parser.error("Environment, update, step, save, and minibatch counts must be positive") @@ -75,13 +79,13 @@ def main(): parser.error("Memory recording needs positive warmup and subsequent updates") if args.mode == "play" and args.checkpoint is None: parser.error("play requires --checkpoint") - if args.deployment_bundle and chunk_size != 1: - parser.error("Deployment playback currently requires single-step actions") - if args.deployment_bundle and args.mode != "play": - parser.error("deployment_bundle is supported only for play") + if args.deployment_bundle and (args.mode != "play" or chunk_size != 1): + parser.error("deployment_bundle plays single-step policies only") + if args.deployment_bundle and description["sim2real"]: + parser.error("Deployment playback compares against the unvaried retina; play it without sim2real") if args.deployment_camera and not args.deployment_bundle: parser.error("deployment_camera requires deployment_bundle") - if args.finetune and (args.mode != "train" or args.checkpoint is None): + if agent_cfg.finetune and (args.mode != "train" or args.checkpoint is None): parser.error("finetune requires train with a checkpoint") shared_output = args.output.resolve() if rank == 0 and shared_output.exists(): @@ -89,7 +93,7 @@ def main(): if args.distributed: import torch - from isaaclab_tutorial.active_gaze.learning.runner import initialize_distributed + from .learning.runner import initialize_distributed args.device = f"cuda:{local_rank}" initialize_distributed() @@ -99,185 +103,116 @@ def main(): args.output = shared_output if rank == 0 else shared_output / f"rank_{rank}" args.output.mkdir(parents=True, exist_ok=args.distributed and rank == 0) args.seed += rank - (args.output / "example.json").write_text( - json.dumps( - { - "task": "so101_vial", - "physics": type(cfg.sim.physics).__name__, - "distributed": { - "world_size": world_size, - "rank": rank, - "local_rank": local_rank, - "environments_per_rank": args.num_envs, - "total_environments": args.num_envs * world_size, - "minibatches_per_rank": args.minibatches, - "minibatch_size_per_rank": args.num_envs * agent_cfg.num_steps_per_env // args.minibatches, - "sgs_history": "independent per rank; metrics reduced across ranks", - }, - }, - indent=2, - ) - ) - if os.environ.get("ISAACLAB_FOVI_PROVENANCE"): - (args.output / "provenance.json").write_bytes(Path(os.environ["ISAACLAB_FOVI_PROVENANCE"]).read_bytes()) - if os.environ.get("ISAACLAB_FOVI_CALIBRATION"): - (args.output / "calibration.json").write_bytes(Path(os.environ["ISAACLAB_FOVI_CALIBRATION"]).read_bytes()) - metadata = json.loads((args.output / "example.json").read_text()) - metadata.update(config_metadata(cfg, agent_cfg), configuration=checkpoint_configuration(overrides, agent_cfg)) + run = dict( + description, + overrides=resume_overrides(overrides, agent_cfg), + physics=type(cfg.sim.physics).__name__, + distributed=dict( + world_size=world_size, + environments_per_rank=args.num_envs, + minibatches_per_rank=args.minibatches, + reset_sampling="independent per rank; metrics reduced across ranks", + ), + ) agent = agent_cfg.to_dict() - arm_scale = cfg.actions.arm_action.scale - from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import ARM_JOINTS - - metadata["control"] = { - "action_scale": [arm_scale[n] if isinstance(arm_scale, dict) else arm_scale for n in ARM_JOINTS] - + [cfg.actions.gripper_action.scale], - "physics_hz": 1.0 / cfg.sim.dt, - "control_hz": 1.0 / (cfg.sim.dt * cfg.decimation), - "policy_hz": 1.0 / (cfg.sim.dt * cfg.decimation * chunk_size), - } - if policy == "dino_language": + if description["policy"] == "dino_language": import torch - from isaaclab_tutorial.active_gaze.learning.language import instruction_table - from .language import INSTRUCTIONS + from .learning.language import instruction_table - tokens = cfg.observations.vision.tokens.params - reference, batch_size = tokens["reference"], tokens["batch_size"] - if args.deployment_bundle and batch_size != 1: - parser.error("Deployment parity requires env.observations.vision.tokens.params.batch_size=1") - if batch_size <= 0: - parser.error("DINO batch size must be positive") - canonical_reference = reference - source = Path(reference) / "source.json" - if source.is_file(): - canonical_reference = json.loads(source.read_text())["uri"] table_path = agent_cfg.actor.instruction_table_path if table_path is None and args.checkpoint: table_path = args.checkpoint.parent / "instructions.pt" table = instruction_table( - INSTRUCTIONS, - path=str(table_path) if table_path else None, - device=args.device or "cuda:0", + INSTRUCTIONS, path=str(table_path) if table_path else None, device=args.device or "cuda:0" ) output_table = args.output.resolve() / "instructions.pt" torch.save(table, output_table) agent["actor"]["instruction_table_path"] = str(output_table) - metadata["policy"].update( - dino_checkpoint=canonical_reference, - dino_checksum=tokens["checksum"], - dino_batch_size=batch_size, - instructions=list(INSTRUCTIONS), - frozen_encoders=True, - extrinsics_head=cfg.extrinsics_head(), - ) + if args.deployment_bundle and description["dino"]["batch_size"] != 1: + parser.error("Deployment parity requires env.observations.vision.tokens.params.batch_size=1") del table torch.cuda.empty_cache() - if cfg.goal_mode == "numbered": - from .goals import CAP_LABEL_SIZE, NEAR_GOAL_DISTANCE, RACK_LABEL_SIZE - - metadata["numbered_goals"] = dict( - rack_numbering="fixed indices 1 through 4", - vial_number="fixed per environment; balanced and shuffled at scene creation", - reset_selection="SGS conditioned on the environment's fixed cap number", - near_goal_distance=NEAR_GOAL_DISTANCE, - cap_label_size=CAP_LABEL_SIZE, - rack_label_size=RACK_LABEL_SIZE, - antialiasing="none" if cfg.renderer_backend() == "ovrtx" else None, - temporal_denoising=cfg.renderer_backend() == "ovrtx", - samples_per_pixel=4 if cfg.render_mode() == "rtpt" else None, - cmf_a=cfg.scene.eye.cmf_a, - ovstage=os.environ.get("ISAAC_LAB_OVRTX_USE_OVSTAGE"), - ) - (args.output / "example.json").write_text(json.dumps(metadata, indent=2)) + (args.output / RUN_FILE).write_text(json.dumps(run, indent=2)) + cfg.scene.num_envs = args.num_envs cfg.seed = args.seed cfg.log_dir = str(args.output.resolve()) - if cfg.renderer_backend() == "ovrtx": - cfg.scene.eye.renderer_cfg.log_file_path = str(args.output.resolve() / "ovrtx.log") if args.mode == "play": cfg.play_mode() cfg.scene.num_envs = args.num_envs elif args.mode == "inspect": - cfg.reset_sampling_evaluation = True cfg.curriculum.reset_sampling.params["mode"] = "uniform" if args.diagnostics or args.mode == "inspect" or args.deployment_camera: - cfg.enable_diagnostics() - if args.deployment_camera and cfg.sim2real is not None: - parser.error( - "deployment_camera requires the planar preset without sim2real so both policy paths use identical appearance" - ) + add_diagnostic_camera(cfg) + # A decision spans the chunk's control steps. agent["algorithm"]["gamma"] = control_gamma**chunk_size agent["algorithm"]["lam"] = agent_cfg.algorithm.lam**chunk_size agent["seed"] = args.seed agent["save_interval"] = args.save_interval agent["algorithm"]["num_mini_batches"] = args.minibatches - agent["logger"] = ( - { - "class_name": "isaaclab_tutorial.active_gaze.training.tracking:FoviWandbWriter", - "project_name": "fovi_isaaclab_native", - "entity": "nvidia", - "group": "so101-foveated-ppo", - } - if args.logger == "wandb" - else "tensorboard" - ) + agent["logger"] = "tensorboard" + if args.logger == "wandb": + agent["logger"] = dict( + class_name="isaaclab_tutorial.active_gaze.training.tracking:WandbWriter", + project_name=args.wandb_project, + entity=args.wandb_entity, + group=args.wandb_group, + ) with launch_simulation(cfg, args): from isaaclab.envs import ManagerBasedRLEnv from isaaclab.utils.io import dump_yaml + from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper from .runner import ResetSamplingRunner env = RslRlVecEnvWrapper(ManagerBasedRLEnv(cfg), clip_actions=1.0) if chunk_size > 1: - from isaaclab_tutorial.active_gaze.learning.chunks import ActionChunkWrapper + from .learning.chunks import ActionChunkWrapper env = ActionChunkWrapper(env, chunk_size, control_gamma, critic_groups=agent_cfg.obs_groups["critic"]) else: env.chunk_size = 1 try: - if cfg.goal_mode == "numbered": + from .goals import target_holes + + holes = target_holes(env.unwrapped) + if holes is not None: import torch - counts = torch.bincount(env.unwrapped.vial_number, minlength=5)[1:].tolist() - metadata["numbered_goals"]["cap_counts"] = dict(zip(range(1, 5), counts, strict=True)) - metadata["numbered_goals"]["assignment_seed"] = cfg.seed - (args.output / "example.json").write_text(json.dumps(metadata, indent=2)) - print(f"Static cap counts (1 through 4): {counts}", flush=True) + counts = torch.bincount(holes, minlength=4).tolist() + run["vial_numbers"] = dict(zip(range(1, 5), counts, strict=True)) + (args.output / RUN_FILE).write_text(json.dumps(run, indent=2)) + print(f"Vials numbered 1 to 4: {counts}", flush=True) dump_yaml(str(args.output / "env.yaml"), cfg) (args.output / "agent.json").write_text(json.dumps(agent, indent=2)) - runner = ResetSamplingRunner(env, agent, log_dir=str(args.output), device=cfg.sim.device) + runner = ResetSamplingRunner( + env, agent, log_dir=str(args.output), device=cfg.sim.device, restore_sampler=args.mode == "train" + ) if args.checkpoint: - initialized = [] - if args.finetune: - initialized = runner.finetune(str(args.checkpoint.resolve()), map_location=cfg.sim.device) + new_parameters = [] + if agent_cfg.finetune: + new_parameters = runner.finetune(str(args.checkpoint.resolve()), map_location=cfg.sim.device) else: runner.load(str(args.checkpoint.resolve()), map_location=cfg.sim.device) if args.mode == "train": - resume = { - "checkpoint": args.checkpoint.name, - "sha256": hashlib.sha256(args.checkpoint.read_bytes()).hexdigest(), - "loaded_update": runner.current_learning_iteration, - "next_update": runner.current_learning_iteration + 1, - "optimizer_state_entries": len(runner.alg.optimizer.state), - "sampler_completed_episodes": int(runner.sampler.history.episodes.sum()), - "finetune": args.finetune, - "initialized_parameters": initialized, - } - source = args.checkpoint.parent / "source.json" - if source.is_file(): - resume["source"] = json.loads(source.read_text()) - metadata["resume"] = resume - (args.output / "example.json").write_text(json.dumps(metadata, indent=2)) - (args.output / "resume.json").write_text(json.dumps(resume, indent=2)) - print("SO101_RESUME " + json.dumps(resume), flush=True) + resume = dict( + checkpoint=args.checkpoint.name, + sha256=hashlib.sha256(args.checkpoint.read_bytes()).hexdigest(), + loaded_update=runner.current_learning_iteration, + finetune=agent_cfg.finetune, + new_parameters=new_parameters, + ) + run["resume"] = resume + (args.output / RUN_FILE).write_text(json.dumps(run, indent=2)) + print("Resuming " + json.dumps(resume), flush=True) runner.current_learning_iteration += 1 if args.mode == "train": - before = {name: value.detach().clone() for name, value in runner.alg.actor.named_parameters()} - from isaaclab_tutorial.active_gaze.training.memory import TrainingMemoryRecorder - from isaaclab_tutorial.active_gaze.training.tracking import install_performance_metrics + from .training.memory import TrainingMemoryRecorder + from .training.tracking import install_performance_metrics install_performance_metrics(runner) recorder = ( @@ -291,11 +226,6 @@ def main(): from .distributed import verify_replicas verify_replicas(runner, args.output / "distributed_validation.json") - changes = { - name: (value.detach() - before[name]).abs().max().item() - for name, value in runner.alg.actor.named_parameters() - } - (args.output / "parameter_updates.json").write_text(json.dumps(changes, indent=2)) else: record(env, runner, args) metrics, _ = iteration_metrics(runner.sampler, 0) @@ -303,83 +233,79 @@ def main(): finally: env.close() if args.distributed: + import torch + torch.distributed.destroy_process_group() +def add_diagnostic_camera(cfg): + """Add a dense 640 x 640 camera at the scene camera's mount, for videos and deployment checks.""" + from isaaclab.sensors import CameraCfg + + eye = cfg.scene.eye + cfg.scene.diagnostic_camera = CameraCfg( + prim_path="{ENV_REGEX_NS}/DiagnosticCamera", + data_types=list(eye.data_types), + width=640, + height=640, + renderer_cfg=eye.renderer_cfg.copy(), + render_settings=eye.render_settings.copy(), + spawn=eye.spawn.copy(), + offset=eye.offset.copy(), + ) + + def record(env, runner, args): import imageio.v2 as imageio import numpy as np import torch from PIL import Image, ImageDraw + from .gaze import RESET_MODES + from .goals import target_holes + from .sim2real import mount_randomization + raw = env.unwrapped + gaze = raw.action_manager.get_term("gaze") + sampler = runner.sampler reset_checks = {} if args.mode == "inspect" and env.num_envs > 1: - gaze = raw.action_manager.get_term("gaze") + # Resetting one environment must leave the others' gaze, vial and camera mount alone. gaze.process_actions(torch.full((env.num_envs, 2), 0.2, device=env.device)) - other_gaze = gaze.processed_actions[1:].clone() - other_vials = raw.scene["vial"].data.root_pos_w.torch[1:].clone() - camera_state = getattr(raw, "so101_camera_randomization", None) - if camera_state is not None: - other_camera = [ - getattr(camera_state, name)[1:].clone() - for name in ("position", "rotation", "intrinsics", "targets", "photo") - ] + mount = mount_randomization(raw) + before = dict( + gaze=gaze.gaze[1:].clone(), + vials=raw.scene["vial"].data.root_pos_w.torch[1:].clone(), + **({} if mount is None else dict(mount_position=mount.position[1:].clone())), + ) raw.reset(env_ids=torch.tensor([0], device=env.device)) - assert torch.equal(gaze.processed_actions[1:], other_gaze) - if gaze.cache is not None: - row = raw._so101_reset_row[0] - expected = gaze.cache[row, gaze.reset_mode[0], gaze.reset_variant[0]] - assert torch.equal(gaze.processed_actions[0], expected) - elif camera_state is None: - assert not gaze.processed_actions[0].any() - else: - for name, before in zip( - ("position", "rotation", "intrinsics", "targets", "photo"), other_camera, strict=True - ): - assert torch.equal(getattr(camera_state, name)[1:], before), name - from .gaze import angles_to_direction - - assert gaze.calibration.project(angles_to_direction(gaze.processed_actions))[1].all() - torch.testing.assert_close(gaze.camera.get_world_positions(), camera_state.position + raw.scene.env_origins) - torch.testing.assert_close( - gaze.camera._view.get_world_poses()[0].torch, camera_state.position + raw.scene.env_origins - ) - assert torch.equal(raw.scene["vial"].data.root_pos_w.torch[1:], other_vials) - reset_checks = { - "selected_gaze_reset": True, - "other_gaze_preserved": True, - "other_vials_preserved": True, - "other_camera_state_preserved": camera_state is not None, - } + after = dict( + gaze=gaze.gaze[1:], + vials=raw.scene["vial"].data.root_pos_w.torch[1:], + **({} if mount is None else dict(mount_position=mount.position[1:])), + ) + reset_checks = {name: bool(torch.equal(before[name], after[name])) for name in before} + # The reset gaze lies inside the physical camera's image. + reset_checks["reset_gaze_visible"] = bool( + gaze.visible(gaze.directions(gaze_points(gaze)[:1], slice(0, 1))).all() + ) + if not all(reset_checks.values()): + raise AssertionError(f"Single-environment reset changed other environments: {reset_checks}") policy = runner.get_inference_policy(device=env.device) - deployment = None - deployment_retina = None + deployment = deployment_retina = None deployment_error = 0.0 if args.deployment_bundle: - from isaaclab_fovi.deployment.so101.runtime import PolicyRuntime + from .deployment.runtime import PolicyRuntime deployment = PolicyRuntime(args.deployment_bundle, str(env.device), retinal=not args.deployment_camera) if deployment.contract["source_sha256"] != hashlib.sha256(args.checkpoint.read_bytes()).hexdigest(): raise ValueError("Deployment bundle and playback checkpoint differ") if args.deployment_camera: - from fovi.sensing.projection import CameraModel - - from isaaclab_fovi.deployment.so101.planar import PlanarRetina - from isaaclab_fovi.deployment.so101.retina import SoftwareRetina - - expected = CameraModel(**raw.scene["eye"].cfg.camera_calibration) - actual = CameraModel(**deployment.contract["camera_calibration"]) - if actual != expected: - raise ValueError("Dense simulator playback requires the nominal source-camera calibration") - deployment_retina = ( - PlanarRetina(deployment.contract["camera_hfov"], deployment.contract["cmf_a"]) - if raw.cfg.retinal_geometry() == "planar" - else SoftwareRetina( - deployment.contract["camera_calibration"], - deployment.contract["camera_hfov"], - deployment.contract["cmf_a"], - ) + from .deployment.retina import SoftwareRetina + + retina = deployment.contract["retina"] + deployment_retina = SoftwareRetina( + deployment.contract["camera_model"], retina["fov_deg"], retina["cmf_a_deg"], retina["resolution"] ).to(env.device) obs = env.get_observations() frames = [] @@ -389,78 +315,58 @@ def record(env, runner, args): for i in range(min(4, env.num_envs)) ] step = 0 - phase = None + bin_index = None + holes = target_holes(raw) + + def image(sensor_name): + sensor = raw.scene[sensor_name] + return sensor.data.output[sensor.cfg.data_types[0]].torch def capture(obs, reward, done, info): nonlocal step, episodes, successes episodes += int(done.sum()) successes += int(raw.termination_manager.get_term("success").sum()) - retinal = raw.scene["eye"].data.output[raw.scene["eye"].cfg.data_types[0]] - retinal = retinal.torch if hasattr(retinal, "torch") else retinal - camera_state = getattr(raw, "so101_camera_randomization", None) - if camera_state is not None: - retinal = camera_state.image(retinal) - dense = None - if "diagnostic_camera" in raw.scene.sensors: - dense = raw.scene["diagnostic_camera"].data.output[raw.scene["diagnostic_camera"].cfg.data_types[0]] - dense = dense.torch if hasattr(dense, "torch") else dense + retinal = image("eye") + dense = image("diagnostic_camera") if "diagnostic_camera" in raw.scene.sensors else None if deployment_retina is not None: - retinal = deployment_retina(dense[..., :3], raw.action_manager.get_term("gaze").processed_actions) - from .gaze import RESET_MODES - - markers = diagnostic_markers(raw) if dense is not None else None + retinal = deployment_retina(dense[..., :3], gaze.angles_deg) + markers = diagnostic_markers(gaze) if dense is not None else None for i, writer in enumerate(writers): eye = Image.fromarray(retinal[i, ..., :3].cpu().numpy()).resize((384, 384), Image.Resampling.NEAREST) canvas = Image.new("RGB", (768 if dense is not None else 384, 416)) if dense is not None: - canvas.paste( - Image.fromarray(dense[i, ..., :3].cpu().numpy()).resize((384, 384)), - (0, 32), - ) + canvas.paste(Image.fromarray(dense[i, ..., :3].cpu().numpy()).resize((384, 384)), (0, 32)) canvas.paste(eye, (384 if dense is not None else 0, 32)) draw = ImageDraw.Draw(canvas) if markers is not None: for xy, color in zip(markers[i], ("cyan", "magenta", "lime"), strict=True): - x, y = xy[0] * 384 / 640, xy[1] * 384 / 640 + 32 + x, y = xy[0] * 384, xy[1] * 384 + 32 draw.ellipse((x - 3, y - 3, x + 3, y + 3), outline=color, width=2) - mode = RESET_MODES[int(raw.action_manager.get_term("gaze").reset_mode[i])] - goal_text = ( - f" vial={int(raw.vial_number[i])} target={int(raw.numbered_target_hole[i]) + 1}" - if raw.cfg.goal_mode == "numbered" - else "" - ) + goal = f" vial={int(holes[i]) + 1}" if holes is not None else "" draw.text( (8, 8), - f"step={step} env={i} reset={bool(done[i])} gaze reset={mode}{goal_text} cyan:object magenta:goal green:gaze", + f"step={step} env={i} reset={bool(done[i])} gaze start={RESET_MODES[int(gaze.reset_mode[i])]}{goal}" + " cyan:vial magenta:goal green:gaze", fill="white", ) - if raw.cfg.policy == "dino_language": - from .language import INSTRUCTIONS - - draw.text((8, 20), INSTRUCTIONS[0], fill="white") writer.append_data(np.asarray(canvas)) - if i == 0 and step % 90 == 0: - canvas.save(args.output / f"frame_{step:04d}.png") - elif step % 90 == 0: - canvas.save(args.output / f"frame_{step:04d}_env_{i}.png") + if step % 90 == 0: + canvas.save(args.output / (f"frame_{step:04d}.png" if i == 0 else f"frame_{step:04d}_env_{i}.png")) if step % 90 == 0: + mount = mount_randomization(raw) frames.append( - { - "step": step, - "gaze": raw.action_manager.get_term("gaze").processed_actions[0].tolist(), - "phase": phase if args.mode == "inspect" else None, - "reset_category": raw.reset_sampling.bin_names[phase] if args.mode == "inspect" else None, - "vial_number": raw.vial_number.tolist() if raw.cfg.goal_mode == "numbered" else None, - "gaze_reset_mode": int(raw.action_manager.get_term("gaze").reset_mode[0]), - "vial": raw.scene["vial"].data.root_pos_w.torch[0].tolist(), - "source_coverage": source_coverage(raw), - "camera_randomization": { - name: getattr(camera_state, name).tolist() - for name in ("position", "rotation", "intrinsics", "radial", "targets", "photo") - } - if camera_state is not None - else None, - } + dict( + step=step, + gaze_deg=gaze.angles_deg[0].tolist(), + gaze_start=RESET_MODES[int(gaze.reset_mode[0])], + reset_category=sampler.bin_names[bin_index] if bin_index is not None else None, + vial_numbers=(holes + 1).tolist() if holes is not None else None, + vial=raw.scene["vial"].data.root_pos_w.torch[0].tolist(), + task_visible_fraction=task_visible_fraction(raw, gaze), + camera_mount=None + if mount is None + else dict(position=mount.position[0].tolist(), rotation=mount.rotation[0].tolist()), + ) ) step += 1 @@ -470,41 +376,35 @@ def capture(obs, reward, done, info): if args.mode == "inspect": if step % 90 == 0: reset = raw.event_manager.get_term_cfg("reset_from_dataset").func - phase = (step // 90) % len(raw.reset_sampling.bin_names) - reset.row_weights = (raw.reset_sampling.phases == phase).float() - if raw.cfg.goal_mode == "numbered": - # Stock late-stage rows mostly surround slot 1. Some bins - # therefore cannot exist for every immutable cap identity. + bin_index = (step // 90) % len(sampler.bin_names) + reset.row_weights = (sampler.phases == bin_index).float() + if holes is not None: + # Late-stage rows mostly surround opening 1, so some bins cannot exist for every vial. missing = reset.row_weights.reshape(-1, 4).sum(0) == 0 fallback = missing[reset.states["target_hole"]] & (reset.states["phase"] == 0) reset.row_weights[fallback] = 1.0 obs, _ = env.reset() actions = torch.zeros(env.num_envs, env.num_actions, device=env.device) - # Sweep electronically, leaving robot commands neutral. + # Sweep the gaze, leaving the robot's commands neutral. plan = actions.reshape(env.num_envs, env.chunk_size, -1) - plan[..., -2] = 0.10 * np.sin(step * 0.08) - plan[..., -1] = 0.10 * np.cos(step * 0.08) + plan[..., -2] = np.sin(step * 0.08) + plan[..., -1] = np.cos(step * 0.08) if step % 90 == 0: actions.zero_() else: - # Match the deployed single-robot batch. BF16 DINO and GPU - # GEMM kernels can change numerics at different batch sizes. + # Match the deployed single-robot batch: BF16 DINO and GEMM kernels can change numerics with + # the batch size. actions = ( torch.cat([policy(obs[i : i + 1]) for i in range(env.num_envs)]) if deployment is not None else policy(obs) ) if deployment is not None: - sensor = raw.scene["diagnostic_camera" if args.deployment_camera else "eye"] - image = sensor.data.output[sensor.cfg.data_types[0]] - image = image.torch if hasattr(image, "torch") else image - camera_state = getattr(raw, "so101_camera_randomization", None) - if camera_state is not None and not args.deployment_camera: - image = camera_state.image(image) + frame = image("diagnostic_camera" if args.deployment_camera else "eye") exported = torch.stack( [ torch.as_tensor( - deployment.infer(obs["proprio"][i], image[i, ..., :3]), device=env.device + deployment.infer(obs["proprio"][i], frame[i, ..., :3]), device=env.device ) for i in range(env.num_envs) ] @@ -518,10 +418,7 @@ def capture(obs, reward, done, info): if args.mode == "inspect": remaining = min(remaining, 90 - step % 90) obs, _, _, _ = env.step( - actions, - control_steps=min(env.chunk_size, remaining), - render_every_step=True, - observer=capture, + actions, control_steps=min(env.chunk_size, remaining), render_every_step=True, observer=capture ) else: obs, reward, done, info = env.step(actions) @@ -531,79 +428,65 @@ def capture(obs, reward, done, info): writer.close() (args.output / "evaluation.json").write_text( json.dumps( - { - "mode": args.mode, - "steps": args.steps, - "episodes": episodes, - "successes": successes, - "frames": frames, - "checkpoint": str(args.checkpoint), - "reset_checks": reset_checks, - "deployment_bundle": str(args.deployment_bundle) if args.deployment_bundle else None, - "deployment_input": "dense_camera" if args.deployment_camera else "retinal", - "deployment_max_action_difference": deployment_error if deployment is not None else None, - }, + dict( + mode=args.mode, + steps=args.steps, + episodes=episodes, + successes=successes, + frames=frames, + checkpoint=str(args.checkpoint), + reset_checks=reset_checks, + deployment_bundle=str(args.deployment_bundle) if args.deployment_bundle else None, + deployment_input="dense_camera" if args.deployment_camera else "retinal", + deployment_max_action_difference=deployment_error if deployment is not None else None, + ), indent=2, ) ) -def source_coverage(env): - """Project task body centers through the fixed physical pinhole camera.""" +def gaze_points(gaze): + """World points of the vial and the goal, shape (2, num_envs, 3).""" + import torch + + from .gaze import gaze_targets + + env = gaze._env + vial, rack = ( + torch.cat((env.scene[name].data.root_pos_w.torch, env.scene[name].data.root_quat_w.torch), -1) + for name in ("vial", "rack") + ) + return torch.stack(gaze_targets(env, vial, rack)) + + +def task_visible_fraction(env, gaze) -> float: + """Fraction of the robot's bodies, the vial and the rack that the physical camera sees.""" import torch - from fovi.sensing.projection import CameraModel - from isaaclab.utils.math import quat_apply_inverse - cfg = env.cfg.scene.eye - state = getattr(env, "so101_camera_randomization", None) - robot = env.scene["robot"].data.body_pos_w.torch points = torch.cat( - [ - robot, + ( + env.scene["robot"].data.body_pos_w.torch, env.scene["vial"].data.root_pos_w.torch[:, None], env.scene["rack"].data.root_pos_w.torch[:, None], - ], + ), dim=1, ) - origins = env.scene.env_origins - origins = origins.torch if hasattr(origins, "torch") else origins - position = origins + (points.new_tensor(cfg.offset.pos) if state is None else state.position) - rotation = points.new_tensor(cfg.offset.rot).expand(len(points), 4) if state is None else state.rotation - rotation = rotation[:, None].expand(*points.shape[:2], 4) - directions = quat_apply_inverse(rotation.reshape(-1, 4), (points - position[:, None]).reshape(-1, 3)) - directions *= directions.new_tensor((1, -1, -1)) - if state is None: - _, visible = CameraModel(**cfg.camera_calibration).project(directions) - else: - from .camera_geometry import lens_visibility - - visible = lens_visibility(directions.reshape(*points.shape), state.intrinsics, state.radial, (640, 640)) + visible = torch.stack([gaze.visible(gaze.directions(points[:, k])) for k in range(points.shape[1])], dim=1) return float(visible.float().mean()) -def diagnostic_markers(env): +def diagnostic_markers(gaze): + """Image positions of the vial, the goal and the gaze, as fractions of the camera image, shape (num_envs, 3, 2).""" import torch - from .gaze import angles_to_direction, camera_directions, target_centers + from .gaze import angles_to_direction - cfg = env.cfg.scene.eye - gaze = env.action_manager.get_term("gaze") - poses = [ - torch.cat((env.scene[name].data.root_pos_w.torch, env.scene[name].data.root_quat_w.torch), -1) - for name in ("vial", "rack") - ] - if getattr(env.cfg, "goal_mode", "nearest") == "numbered": - from .goals import CAP_LABEL_POSITION, RACK_LABEL_OFFSETS - - points = target_centers(*poses, env.numbered_target_hole, CAP_LABEL_POSITION, RACK_LABEL_OFFSETS) - else: - points = target_centers(*poses) - position = gaze.camera.get_world_positions() - state = getattr(env, "so101_camera_randomization", None) - rotation = position.new_tensor(cfg.offset.rot) if state is None else state.rotation - directions = [camera_directions(point, position, rotation) for point in points] - directions.append(angles_to_direction(gaze.processed_actions)) - pixels = [gaze.calibration.project(direction)[0] for direction in directions] + directions = [gaze.directions(point) for point in gaze_points(gaze)] + directions.append(angles_to_direction(gaze.angles_deg)) + height, width = gaze.camera_model.image_size + size = torch.tensor((width, height), dtype=torch.float32, device=gaze.device) + # Pixel coordinates have integer centres. + pixels = [(gaze.camera_model.project(direction)[0] + 0.5) / size for direction in directions] return torch.stack(pixels, dim=1).cpu().numpy() diff --git a/src/isaaclab_tutorial/active_gaze/training/__init__.py b/src/isaaclab_tutorial/active_gaze/training/__init__.py index 6dbb75e..402da58 100644 --- a/src/isaaclab_tutorial/active_gaze/training/__init__.py +++ b/src/isaaclab_tutorial/active_gaze/training/__init__.py @@ -1 +1 @@ -"""Training evaluation, recording, and memory calibration utilities.""" +"""Training logging, recording, and memory calibration utilities.""" diff --git a/src/isaaclab_tutorial/active_gaze/training/evaluation.py b/src/isaaclab_tutorial/active_gaze/training/evaluation.py deleted file mode 100644 index b9f217e..0000000 --- a/src/isaaclab_tutorial/active_gaze/training/evaluation.py +++ /dev/null @@ -1,238 +0,0 @@ -"""Periodic deterministic rollout blocks, isolated from PPO collection and updates.""" - -import json -import math -import time -from contextlib import contextmanager -from dataclasses import dataclass, field -from pathlib import Path - -import torch -from rsl_rl.utils import check_nan - - -@dataclass(frozen=True) -class EvaluationConfig: - enabled: bool = True - frequency_episodes: float = 100.0 - duration_episodes: float = 1.0 - early_episodes: list[float] = field(default_factory=list) - video: bool = True - video_envs: int = 3 - - def __post_init__(self): - for name in ("frequency_episodes", "duration_episodes"): - value = getattr(self, name) - if isinstance(value, bool) or not math.isfinite(value) or value <= 0: - raise ValueError(f"evaluation.{name} must be finite and positive") - if type(self.enabled) is not bool or type(self.video) is not bool: - raise ValueError("evaluation.enabled and video must be booleans") - if type(self.video_envs) is not int or self.video_envs < 1: - raise ValueError("evaluation.video_envs must be a positive integer") - if not isinstance(self.early_episodes, (list, tuple)) or any( - isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0 - for value in self.early_episodes - ): - raise ValueError("evaluation.early_episodes must contain finite positive numbers") - object.__setattr__(self, "early_episodes", sorted(set(self.early_episodes))) - - def control_steps(self, episode_length: int) -> tuple[int, int]: - steps = [] - for value in (self.frequency_episodes, self.duration_episodes, *self.early_episodes): - exact = value * episode_length - count = round(exact) - if count < 1 or not math.isclose(exact, count, rel_tol=0, abs_tol=1e-6): - raise ValueError("Evaluation durations must resolve to whole control steps") - steps.append(count) - return tuple(steps[:2]) - - -class PeriodicEvaluation: - """Use training control steps for cadence, independent of GPU or environment count.""" - - def __init__(self, env, cfg: dict): - self.cfg = EvaluationConfig(**cfg) - self.frequency, self.duration = self.cfg.control_steps(env.max_episode_length) - self.early_steps = tuple(round(value * env.max_episode_length) for value in self.cfg.early_episodes) - - def due(self, previous: int, current: int) -> bool: - return self.cfg.enabled and ( - current // self.frequency > previous // self.frequency - or any(previous < step <= current for step in self.early_steps) - ) - - def run(self, runner): - env = runner.env - with coordinated_errors(runner): - obs, totals, elapsed, output, recorder = self._rollout(runner) - if runner.is_distributed: - torch.distributed.all_reduce(totals) - torch.distributed.all_reduce(elapsed, op=torch.distributed.ReduceOp.MAX) - episodes, reward_sum, length_sum, successes = totals.tolist() - metrics = { - "Eval/completed_episodes": episodes, - "Eval/control_steps_per_env": self.duration, - "Eval/duration_episodes": self.duration / env.max_episode_length, - "Eval/wall_seconds": elapsed.item(), - } - if episodes: - metrics.update( - { - "Eval/mean_return": reward_sum / episodes, - "Eval/mean_episode_control_steps": length_sum / episodes, - "Eval/success_rate": successes / episodes, - } - ) - with coordinated_errors(runner): - if output is not None: - metadata = { - "training_iteration": runner.current_learning_iteration, - "training_control_steps_per_env": runner.training_control_steps, - "policy": "deterministic actor mean; no oracle action substitution", - "control_fps": 1 / env.unwrapped.step_dt, - "policy_fps": 1 / env.decision_dt, - "action_chunk_size": env.chunk_size, - "metrics": metrics, - } - if recorder is not None: - metadata.update( - frame_count=recorder.frames, - videos={f"env_{i}": path.name for i, path in enumerate(recorder.paths)}, - recorded_envs=recorder.num_envs, - instruction_segments=recorder.segments, - video_fps=1 / env.decision_dt, - source="post-chunk native foveated RGB; no intermediate camera captures", - ) - (output / "evaluation.json").write_text(json.dumps(metadata, indent=2) + "\n") - writer = runner.logger.writer - if writer is not None: - for key, value in metrics.items(): - writer.add_scalar(key, value, runner.current_learning_iteration) - if recorder is not None: - from .tracking import FoviWandbWriter - - if isinstance(writer, FoviWandbWriter): - for path in recorder.paths: - writer.save_video(path, runner.current_learning_iteration) - print( - f"ISAACLAB_FOVI_EVAL complete rank={runner.gpu_global_rank} " + json.dumps(metrics), - flush=True, - ) - return obs.to(runner.device) - - def _rollout(self, runner): - env = runner.env - policy = runner.alg.get_policy() - instructions = getattr(runner.alg.actor, "instructions", ()) - returns = torch.zeros(env.num_envs, device=env.device) - lengths = torch.zeros_like(returns) - # Completed episodes, returns, lengths, successes. Reduce sums, not rank means. - totals = torch.zeros(4, device=env.device, dtype=torch.float64) - recorder = None - output = None - count = min(self.cfg.video_envs, env.num_envs) - if runner.gpu_global_rank == 0 and runner.logger.log_dir is not None: - output = Path(runner.logger.log_dir) / "evaluation" / f"step_{runner.training_control_steps:09d}" - output.mkdir(parents=True, exist_ok=True) - if self.cfg.video: - from .video import ObservationVideoRecorder - - recorder = ObservationVideoRecorder(output, 1 / env.decision_dt, count) - - def observe(obs, reward, done, extras): - if runner.cfg.get("check_for_nan", True): - check_nan(obs, reward, done) - returns.add_(reward) - lengths.add_(1) - finished = done.bool() - totals[0].add_(finished.sum()) - totals[1].add_(returns[finished].sum()) - totals[2].add_(lengths[finished].sum()) - totals[3].add_((env.unwrapped.termination_manager.get_term("success") & finished).sum()) - returns[finished] = 0 - lengths[finished] = 0 - - print( - f"ISAACLAB_FOVI_EVAL start rank={runner.gpu_global_rank} training_control_steps={runner.training_control_steps} control_steps={self.duration}", - flush=True, - ) - start = time.perf_counter() - # Restore nested module modes exactly, including deliberately frozen children. - models = [runner.alg.actor, runner.alg.critic] - if runner.alg.rnd is not None: - models.append(runner.alg.rnd) - modes = {module: module.training for model in models for module in model.modules()} - rendering = env.unwrapped.render_enabled - try: - runner.alg.eval_mode() - env.unwrapped.render_enabled = True - with torch.inference_mode(): - obs, _ = env.reset() - policy.reset() - for step in range(0, self.duration, env.chunk_size): - with torch.autocast( - torch.device(runner.device).type, - dtype=torch.bfloat16, - enabled=runner.alg.use_mixed_precision, - ): - actions = policy(obs.to(runner.device)) - obs, _, done, _ = env.step( - actions.to(env.device), - control_steps=min(env.chunk_size, self.duration - step), - observer=observe, - ) - if recorder is not None: - # Vision already refreshed at this boundary. Reading it - # in the per-control-step observer would trigger a lazy - # render of the entire tiled camera between decisions. - rgb = env.unwrapped.scene["eye"].data.output["rgb"] - rgb = rgb.torch if hasattr(rgb, "torch") else rgb - captions = [""] * count - if instructions: - indices = obs["instruction"][:count, 0].long().cpu().tolist() - captions = [instructions[i] for i in indices] - recorder.capture(rgb[:count].cpu().numpy(), captions) - policy.reset(done) - finally: - try: - if recorder is not None: - recorder.close() - finally: - for module, training in modes.items(): - module.training = training - # Discard evaluation state and partial training episodes. The caller - # must collect from this fresh observation, never its pre-eval buffer. - env.unwrapped.render_enabled = rendering - with torch.inference_mode(): - obs, _ = env.reset() - policy.reset() - runner.logger.cur_reward_sum.zero_() - runner.logger.cur_episode_length.zero_() - runner.logger.ep_extras.clear() - if runner.alg.rnd is not None: - # Match the discarded training episodes in native RND logging. - runner.logger.cur_ereward_sum.zero_() - runner.logger.cur_ireward_sum.zero_() - elapsed = torch.tensor(time.perf_counter() - start, device=env.device) - return obs, totals, elapsed, output, recorder - - -@contextmanager -def coordinated_errors(runner): - """Let every rank leave an evaluation phase before any rank resumes PPO. - - A rank-zero encoder/upload failure must not strand peers in the next gradient - collective. Healthy ranks finish this bounded phase, then all ranks raise. - """ - error = None - try: - yield - except Exception as exc: - error = exc - failed = torch.tensor(int(error is not None), device=runner.device) - if runner.is_distributed: - torch.distributed.all_reduce(failed, op=torch.distributed.ReduceOp.MAX) - if error is not None: - raise error - if failed.item(): - raise RuntimeError("Evaluation failed on another rank; stopping training") diff --git a/src/isaaclab_tutorial/active_gaze/training/tracking.py b/src/isaaclab_tutorial/active_gaze/training/tracking.py index 3bf750e..de0d480 100644 --- a/src/isaaclab_tutorial/active_gaze/training/tracking.py +++ b/src/isaaclab_tutorial/active_gaze/training/tracking.py @@ -41,66 +41,29 @@ def log(**kwargs): runner.logger.log = log -class FoviWandbWriter(WandbLogWriter): - def store_config(self, env_cfg, train_cfg): - """Record the active configuration when an existing W&B run resumes.""" - import wandb - - env = env_cfg.to_dict() if hasattr(env_cfg, "to_dict") else asdict(env_cfg) - wandb.config.update({"train_cfg": train_cfg, "env_cfg": env}, allow_val_change=wandb.run.resumed) - - def save_video(self, path: Path, it: int): - """Log each block once, including native RSL-RL's subsequent video scan.""" - import wandb - - identity = str(path.resolve()) - if identity not in self.logged_videos: - wandb.log({f"Eval/observations/{path.stem}": wandb.Video(identity, format="mp4")}, step=it) - self.logged_videos.add(identity) +class WandbWriter(WandbLogWriter): + """RSL-RL's W&B writer, with a configurable entity and group, and the run's description and inputs uploaded.""" - def __init__(self, log_dir: str, project_name: str, entity: str, group: str | None = None): - # RSL-RL's writer currently reads WANDB_USERNAME, while W&B reads WANDB_ENTITY. - os.environ["WANDB_USERNAME"] = os.environ["WANDB_ENTITY"] = entity + def __init__(self, log_dir: str, project_name: str, entity: str | None = None, group: str | None = None): + # RSL-RL's writer reads the entity from WANDB_USERNAME; without one, W&B uses the login's default. + if entity: + os.environ["WANDB_USERNAME"] = entity if group: os.environ["WANDB_RUN_GROUP"] = group super().__init__(log_dir=log_dir, project_name=project_name) import wandb - settings_path = Path(log_dir) / "config.json" - if not settings_path.is_file(): - # The standalone SO-101 launcher preserves its existing checkpoint metadata. - settings_path = Path(log_dir) / "example.json" - settings = json.loads(settings_path.read_text()) - wandb.config.update({"isaaclab_fovi": settings}, allow_val_change=wandb.run.resumed) - provenance_path = Path(log_dir) / "provenance.json" - if provenance_path.is_file(): - provenance = json.loads(provenance_path.read_text()) - wandb.config.update( - { - "source": { - key: provenance.get(key) - for key in ( - "bundle_id", - "isaaclab_commit", - "image", - "runtime", - "workflow_id", - ) - } - }, - allow_val_change=wandb.run.resumed, - ) - for name in ( - "config.json", - "example.json", - "agent.json", - "env.yaml", - "instructions.pt", - "gaze_reset_cache.pt", - "calibration.json", - "provenance.json", - ): + from ..configuration import RUN_FILE + + wandb.config.update({"run": json.loads((Path(log_dir) / RUN_FILE).read_text())}, allow_val_change=True) + for name in (RUN_FILE, "agent.json", "env.yaml", "instructions.pt"): path = Path(log_dir) / name if path.is_file(): self.save_file(str(path)) - print(f"ISAACLAB_FOVI_WANDB {wandb.run.url}", flush=True) + print(f"W&B run: {wandb.run.url}", flush=True) + + def store_config(self, env_cfg, train_cfg): + import wandb + + env = env_cfg.to_dict() if hasattr(env_cfg, "to_dict") else asdict(env_cfg) + wandb.config.update({"train_cfg": train_cfg, "env_cfg": env}, allow_val_change=True) diff --git a/tests/active_gaze/test_evaluation.py b/tests/active_gaze/test_evaluation.py deleted file mode 100644 index 1303e20..0000000 --- a/tests/active_gaze/test_evaluation.py +++ /dev/null @@ -1,551 +0,0 @@ -"""Evaluation stays isolated from training and captures RGB only at chunk boundaries.""" - -import copy -import json -from dataclasses import asdict -from types import SimpleNamespace - -import imageio.v2 as imageio -import pytest -import torch -from tensordict import TensorDict - -from isaaclab_tutorial.active_gaze.learning.chunks import ActionChunkWrapper -from isaaclab_tutorial.active_gaze.learning.runner import EvaluationOnPolicyRunner -from isaaclab_tutorial.active_gaze.training.evaluation import EvaluationConfig, PeriodicEvaluation, coordinated_errors -from isaaclab_tutorial.active_gaze.training.video import ObservationVideoRecorder - - -class CountingCamera: - def __init__(self): - self.rgb = torch.zeros(3, 16, 16, 3, dtype=torch.uint8) - self.reads = 0 - - @property - def data(self): - self.reads += 1 - return SimpleNamespace(output={"rgb": self.rgb}) - - -class EvaluationEnv: - num_envs, num_actions, device, max_episode_length = 3, 3, "cpu", 5 - step_dt = 0.1 - - def __init__(self): - self.unwrapped = self - self.cfg = SimpleNamespace(compute_final_obs=False, to_dict=lambda: {}) - self.render_enabled = True - self.episode_length_buf = torch.zeros(3, dtype=torch.long) - self.resets = 0 - self.steps = 0 - self.calls = [] - self.action_manager = SimpleNamespace( - get_term=lambda _: SimpleNamespace(arm_action_dim=1, motor_action_dim=1, action_dim=1) - ) - self.termination_manager = SimpleNamespace(get_term=lambda _: torch.zeros(3, dtype=torch.bool)) - self.scene = {"eye": CountingCamera()} - - def get_observations(self): - state = torch.stack((torch.full((3,), self.resets), self.episode_length_buf), dim=-1).float() - return TensorDict( - dict( - proprio=state, - rnd_state=state.clone(), - privileged=state.clone(), - instruction=torch.arange(3)[:, None], - oracle=torch.tensor([[0.0, 0.0, 1.0]]).expand(3, -1).clone(), - ), - batch_size=[3], - ) - - def reset(self): - self.resets += 1 - self.episode_length_buf.zero_() - return self.get_observations(), {} - - def step(self, action): - self.calls.append((action.clone(), self.render_enabled, self.refresh_policy_vision)) - self.steps += 1 - self.episode_length_buf += 1 - done = self.episode_length_buf >= self.max_episode_length - final = self.get_observations() - self.episode_length_buf[done] = 0 - self.reset_terminated = torch.zeros(3, dtype=torch.bool) - self.scene["eye"].rgb.fill_(self.steps % 250) - return ( - self.get_observations(), - torch.ones(3), - done.long(), - {"time_outs": done, "final_obs": final}, - ) - - -def make_runner(tmp_path, *, rnd=False, **evaluation): - env = ActionChunkWrapper(EvaluationEnv(), 4, 0.99, critic_groups=["proprio", "privileged"]) - cfg = { - "actor": dict( - class_name="rsl_rl.models:MLPModel", - hidden_dims=[8], - obs_normalization=True, - distribution_cfg=dict(class_name="GaussianDistribution", init_std=0.5, std_type="log"), - ), - "critic": dict(class_name="rsl_rl.models:MLPModel", hidden_dims=[8], obs_normalization=True), - "obs_groups": {"actor": ["proprio"], "critic": ["proprio", "privileged"]}, - "algorithm": dict( - class_name="isaaclab_tutorial.active_gaze.learning.oracle_ppo:OraclePPO", - num_learning_epochs=1, - num_mini_batches=1, - schedule="fixed", - action_chunk_size=4, - ), - "num_steps_per_env": 2, - "save_interval": 100, - "logger": "tensorboard", - "evaluation": asdict(EvaluationConfig(frequency_episodes=4)) | evaluation, - } - if rnd: - cfg["obs_groups"]["rnd_state"] = ["rnd_state"] - cfg["algorithm"]["rnd_cfg"] = dict( - num_outputs=8, - predictor_hidden_dims=[16, 16], - target_hidden_dims=[16], - state_normalization=True, - reward_normalization=True, - weight=1.0, - ) - runner = EvaluationOnPolicyRunner(env, cfg, str(tmp_path), "cpu") - runner.alg.actor.instructions = ("Place the vial.", "Move to the rack.", "Release the vial.") - return runner - - -def assert_state_equal(before, after): - if isinstance(before, torch.Tensor): - assert torch.equal(before, after) - elif isinstance(before, dict): - assert before.keys() == after.keys() - for key in before: - assert_state_equal(before[key], after[key]) - elif isinstance(before, (tuple, list)): - assert len(before) == len(after) - for left, right in zip(before, after, strict=True): - assert_state_equal(left, right) - else: - assert before == after - - -def test_default_schedule_uses_training_time_and_crosses_rollout_boundaries(): - schedule = PeriodicEvaluation(SimpleNamespace(max_episode_length=360), {}) - assert (schedule.frequency, schedule.duration) == (36000, 360) - assert not schedule.due(35936, 35968) - assert schedule.due(35968, 36000) - assert not schedule.due(36000, 36032) - # An interval that doesn't divide PPO's horizon runs at the following boundary. - schedule = PeriodicEvaluation(SimpleNamespace(max_episode_length=5), {"frequency_episodes": 4}) - assert schedule.due(16, 24) - assert not schedule.due(24, 32) - assert schedule.due(32, 40) - assert not PeriodicEvaluation(SimpleNamespace(max_episode_length=5), {"enabled": False}).due(16, 24) - for kwargs in ( - {"duration_episodes": 0}, - {"frequency_episodes": float("nan")}, - {"video_envs": 0}, - ): - with pytest.raises(ValueError): - EvaluationConfig(**kwargs) - with pytest.raises(ValueError, match="whole control steps"): - EvaluationConfig(duration_episodes=0.25).control_steps(5) - - -def test_early_schedule_coalesces_thresholds_and_does_not_replay_on_resume(): - schedule = PeriodicEvaluation( - SimpleNamespace(max_episode_length=5), - {"frequency_episodes": 4, "early_episodes": [4, 2, 1, 1]}, - ) - assert schedule.early_steps == (5, 10, 20) - assert [schedule.due(step, step + 8) for step in range(0, 40, 8)] == [ - True, - True, - True, - False, - True, - ] - assert not schedule.due(24, 32) - assert not PeriodicEvaluation( - SimpleNamespace(max_episode_length=5), - {"enabled": False, "frequency_episodes": 4, "early_episodes": [1]}, - ).due(0, 8) - for values in ([0], [-1], [float("nan")], [True], ["1"], "1"): - with pytest.raises(ValueError, match="early_episodes"): - EvaluationConfig(early_episodes=values) - with pytest.raises(ValueError, match="whole control steps"): - EvaluationConfig(early_episodes=[0.25]).control_steps(5) - - -def test_early_blocks_record_video_save_matching_policy_and_resume_without_replay(tmp_path): - runner = make_runner(tmp_path, early_episodes=[1, 2]) - evaluated_iterations = [] - original_run = runner.evaluation.run - - def run(active): - iteration = active.current_learning_iteration - checkpoint = tmp_path / f"model_{iteration}.pt" - assert checkpoint.is_file() - saved = torch.load(checkpoint, weights_only=False) - assert saved["iter"] == iteration - for key, value in active.alg.save().items(): - assert_state_equal(value, saved[key]) - evaluated_iterations.append(iteration) - return original_run(active) - - runner.evaluation.run = run - runner.learn(4) - assert evaluated_iterations == [0, 1, 2] - blocks = list((tmp_path / "evaluation").glob("*/evaluation.json")) - assert len(blocks) == 3 - assert len(list((tmp_path / "evaluation").glob("*/env_*.mp4"))) == 9 - assert runner.env.unwrapped.steps == 32 + 3 * 5 - resumed = make_runner(tmp_path / "resumed", video=False, early_episodes=[1, 2]) - resumed.load(str(tmp_path / "model_1.pt")) - assert resumed.training_control_steps == 16 - resumed.learn(1) - assert resumed.env.unwrapped.steps == 8 + 5 - assert (tmp_path / "resumed/evaluation/step_000000024/evaluation.json").exists() - - -def test_checkpoint_failure_stops_before_evaluation(tmp_path, monkeypatch): - runner = make_runner(tmp_path, early_episodes=[1]) - - def fail_save(*args): - raise OSError("checkpoint storage unavailable") - - monkeypatch.setattr(runner, "save", fail_save) - with pytest.raises(OSError, match="checkpoint storage unavailable"): - runner.learn(1) - assert not (tmp_path / "evaluation").exists() - assert runner.env.unwrapped.steps == 8 - - -@pytest.mark.parametrize("rnd", [False, True]) -def test_eval_freezes_learning_resets_all_envs_and_records_at_chunk_rate(tmp_path, rnd): - runner = make_runner(tmp_path, rnd=rnd) - # Seed real PPO/Adam and normalization state before taking the snapshot. - runner.learn(1) - runner.logger.cur_reward_sum.fill_(20) - runner.logger.cur_episode_length.fill_(3) - runner.alg.actor.mlp.eval() # Deliberately frozen nested mode must also survive. - modes = {module: module.training for model in (runner.alg.actor, runner.alg.critic) for module in model.modules()} - before = copy.deepcopy(runner.alg.save()) - if rnd: - rnd_modes = {module: module.training for module in runner.alg.rnd.modules()} - rnd_returns = runner.alg.rnd.reward_normalizer.disc_avg.avg.clone() - runner.logger.cur_ereward_sum.fill_(20) - runner.logger.cur_ireward_sum.fill_(3) - storage = runner.alg.storage.step - control = runner.env.unwrapped - reset_count, control_count = control.resets, control.steps - obs = runner.evaluation.run(runner) - assert_state_equal(before, runner.alg.save()) - if rnd: - assert all(module.training == value for module, value in rnd_modes.items()) - torch.testing.assert_close(rnd_returns, runner.alg.rnd.reward_normalizer.disc_avg.avg) - assert not runner.logger.cur_ereward_sum.any() and not runner.logger.cur_ireward_sum.any() - assert runner.alg.storage.step == storage - assert all(module.training == value for module, value in modes.items()) - assert control.resets == reset_count + 2 - assert control.steps == control_count + 5 - assert runner.training_control_steps == 8 # Evaluation isn't training progress. - assert [(render, fresh) for _, render, fresh in control.calls[-5:]] == [ - (False, False), - (False, False), - (False, False), - (True, True), - (True, True), - ] - assert (obs["proprio"][:, 0] == control.resets).all() - assert (obs["proprio"][:, 1] == 0).all() - assert not runner.logger.cur_reward_sum.any() - assert not runner.logger.cur_episode_length.any() - folder = tmp_path / "evaluation/step_000000008" - meta = json.loads((folder / "evaluation.json").read_text()) - assert len(list(folder.glob("env_*.mp4"))) == 3 - assert meta["videos"] == {f"env_{i}": f"env_{i}.mp4" for i in range(3)} - assert control.scene["eye"].reads == 2 # No lazy camera reads inside a chunk. - assert meta["frame_count"] == 2 - assert meta["instruction_segments"][0]["instructions"] == list(runner.alg.actor.instructions) - assert meta["control_fps"] == 10 - assert meta["policy_fps"] == 2.5 - assert meta["video_fps"] == 2.5 - assert meta["metrics"]["Eval/completed_episodes"] == 3 - assert meta["metrics"]["Eval/mean_return"] == 5 - with imageio.get_reader(folder / "env_0.mp4") as reader: - frames = [frame for frame in reader] - assert reader.get_meta_data()["fps"] == 2.5 - assert len(frames) == 2 - assert frames[0].shape == (320, 320, 3) - assert frames[0][100, 100, 0] < frames[-1][100, 100, 0] - - -@pytest.mark.parametrize("video,rank", [(False, 0), (True, 1)]) -def test_eval_without_recording_never_requests_intermediate_rgb(tmp_path, video, rank): - runner = make_runner(tmp_path, video=video) - runner.gpu_global_rank = rank - runner.evaluation.run(runner) - control = runner.env.unwrapped - assert control.scene["eye"].reads == 0 - assert [(render, fresh) for _, render, fresh in control.calls] == [ - (False, False), - (False, False), - (False, False), - (True, True), - (True, True), - ] - - -def test_training_uses_fresh_observations_after_eval_and_resumes_schedule(tmp_path): - runner = make_runner(tmp_path, video=False) - original_act = runner.alg.act - actions = [] - - def act(obs): - torch.testing.assert_close(obs["proprio"], runner.env.get_observations()["proprio"]) - actions.append(obs["proprio"].clone()) - return original_act(obs) - - runner.alg.act = act - runner.learn(4) - assert len(actions) == 8 - assert runner.training_control_steps == 32 - assert runner.env.unwrapped.steps == 37 # Four PPO rollouts plus one five-step eval. - assert actions[-1][0, 0] == 2 # Both full resets happened before training resumed. - assert len(list((tmp_path / "evaluation").glob("*/evaluation.json"))) == 1 - resumed = make_runner(tmp_path / "resumed", video=False) - resumed.load(str(tmp_path / "model_3.pt")) - assert resumed.training_control_steps == 32 - resumed.learn(1) - assert resumed.current_learning_iteration == 4 - assert resumed.training_control_steps == 40 - assert resumed.logger.tot_timesteps == 5 * 2 * resumed.env.num_envs - assert (tmp_path / "resumed/evaluation/step_000000040/evaluation.json").exists() - assert resumed.env.unwrapped.steps == 13 - - -def test_recorder_failure_restores_state_and_does_not_continue_training(tmp_path, monkeypatch): - runner = make_runner(tmp_path) - modes = [runner.alg.actor.training, runner.alg.critic.training] - - def fail(*args): - raise RuntimeError("encoder failed") - - monkeypatch.setattr(ObservationVideoRecorder, "capture", fail) - with pytest.raises(RuntimeError, match="encoder failed"): - runner.evaluation.run(runner) - assert [runner.alg.actor.training, runner.alg.critic.training] == modes - assert runner.env.unwrapped.resets == 2 - assert runner.env.unwrapped.render_enabled and runner.env.unwrapped.refresh_policy_vision - - -def test_peer_evaluation_failure_is_propagated_before_training(monkeypatch): - runner = SimpleNamespace(is_distributed=True, device="cpu") - monkeypatch.setattr(torch.distributed, "all_reduce", lambda failed, **kwargs: failed.fill_(1)) - with pytest.raises(RuntimeError, match="another rank"): - with coordinated_errors(runner): - pass - - -def _distributed_evaluation_worker(rank, rendezvous, directory, fail_encoder): - from datetime import timedelta - from pathlib import Path - - torch.set_num_threads(1) - torch.distributed.init_process_group( - "gloo", init_method=rendezvous, rank=rank, world_size=2, timeout=timedelta(seconds=30) - ) - try: - runner = make_runner(Path(directory) / f"rank{rank}", video=fail_encoder) - runner.is_distributed = True - runner.gpu_global_rank = rank - if fail_encoder and rank == 0: - - def fail(*args): - raise RuntimeError("encoder failed") - - ObservationVideoRecorder.capture = fail - if fail_encoder: - with pytest.raises(RuntimeError, match="encoder failed|another rank"): - runner.evaluation.run(runner) - else: - runner.evaluation.run(runner) - assert runner.env.unwrapped.resets == 2 - finally: - torch.distributed.destroy_process_group() - - -@pytest.mark.parametrize("fail_encoder", [False, True]) -def test_distributed_evaluation_reduces_metrics_and_coordinates_rank_zero_failure(tmp_path, fail_encoder): - torch.multiprocessing.spawn( - _distributed_evaluation_worker, - args=(f"file://{tmp_path / 'rendezvous'}", str(tmp_path), fail_encoder), - nprocs=2, - join=True, - ) - if not fail_encoder: - data = json.loads((tmp_path / "rank0/evaluation/step_000000000/evaluation.json").read_text()) - assert data["metrics"]["Eval/completed_episodes"] == 6 - assert data["metrics"]["Eval/mean_return"] == 5 - assert not (tmp_path / "rank1/evaluation").exists() - - -def _distributed_rnd_worker(rank, rendezvous, directory): - from datetime import timedelta - from pathlib import Path - - torch.set_num_threads(1) - torch.distributed.init_process_group( - "gloo", init_method=rendezvous, rank=rank, world_size=2, timeout=timedelta(seconds=60) - ) - try: - torch.manual_seed(10 + rank) - runner = make_runner(Path(directory) / f"rank{rank}", rnd=True, enabled=False) - runner.is_distributed = runner.alg.is_multi_gpu = True - runner.gpu_global_rank = runner.alg.gpu_global_rank = rank - runner.gpu_world_size = runner.alg.gpu_world_size = 2 - # Different local novelty streams must still produce shared models/moments. - runner.env.unwrapped.resets = rank + 1 - runner.learn(1) - for model in (runner.alg.actor, runner.alg.critic, runner.alg.rnd): - for value in model.state_dict().values(): - if isinstance(value, torch.Tensor): - reference = value.clone() - torch.distributed.broadcast(reference, 0) - torch.testing.assert_close(value, reference) - assert all(p.grad is None for p in runner.alg.rnd.target.parameters()) - finally: - torch.distributed.destroy_process_group() - - -def test_distributed_rnd_synchronizes_target_predictor_gradients_and_moments(tmp_path): - torch.multiprocessing.spawn( - _distributed_rnd_worker, - args=(f"file://{tmp_path / 'rnd-rendezvous'}", str(tmp_path)), - nprocs=2, - join=True, - ) - - -def test_wandb_records_each_block_once_despite_native_video_scan(tmp_path, monkeypatch): - import wandb - - from isaaclab_tutorial.active_gaze.training.tracking import FoviWandbWriter - - writer = object.__new__(FoviWandbWriter) - writer.logged_videos = set() - logged = [] - monkeypatch.setattr(wandb, "Video", lambda path, **kwargs: path) - monkeypatch.setattr(wandb, "log", lambda values, **kwargs: logged.append((values, kwargs))) - first = tmp_path / "step_001/env_0.mp4" - second = tmp_path / "step_002/env_0.mp4" - writer.save_video(first, 1) - writer.save_video(first, 2) # Native logger scans old and new MP4 files. - writer.save_video(second, 2) - third = tmp_path / "step_002/env_1.mp4" - writer.save_video(third, 2) - assert logged[-1][0]["Eval/observations/env_1"] == str(third.resolve()) - assert len(logged) == 3 - assert logged[0][0]["Eval/observations/env_0"] == str(first.resolve()) - assert logged[1][0]["Eval/observations/env_0"] == str(second.resolve()) - - -@pytest.mark.parametrize("settings_file", ["config.json", "example.json"]) -def test_resumed_wandb_writer_updates_active_configuration(tmp_path, monkeypatch, settings_file): - import wandb - from rsl_rl.utils.wandb_log_writer import WandbLogWriter - - from isaaclab_tutorial.active_gaze.training.tracking import FoviWandbWriter - - updates = [] - saved = [] - monkeypatch.setattr(wandb, "run", SimpleNamespace(resumed=True, url="test")) - monkeypatch.setattr(wandb, "config", SimpleNamespace(update=lambda data, **kw: updates.append((data, kw)))) - monkeypatch.setattr(WandbLogWriter, "__init__", lambda *args, **kwargs: None) - monkeypatch.setattr(FoviWandbWriter, "save_file", lambda self, path: saved.append(path)) - (tmp_path / settings_file).write_text('{"camera": "hybrid"}') - (tmp_path / "gaze_reset_cache.pt").write_bytes(b"test cache") - (tmp_path / "provenance.json").write_text('{"workflow_id": "resumed-workflow"}') - writer = FoviWandbWriter(str(tmp_path), "test", "nvidia") - config = SimpleNamespace(to_dict=lambda: {"num_envs": 4}) - writer.store_config(config, {"evaluation": {"enabled": True}}) - assert len(updates) == 3 - assert updates[0][0]["isaaclab_fovi"] == {"camera": "hybrid"} - assert str(tmp_path / settings_file) in saved - assert str(tmp_path / "gaze_reset_cache.pt") in saved - assert all(kwargs == {"allow_val_change": True} for _, kwargs in updates) - assert updates[-1][0]["train_cfg"]["evaluation"]["enabled"] - - -@pytest.mark.parametrize("rnd", [False, True]) -def test_eval_resets_cannot_cross_gae_rollout_boundaries(tmp_path, rnd): - """Check real PPO targets on both sides of eval against an independent GAE. - - Evaluation changes the reset generation and reward scale. Any leaked eval - transition, stale bootstrap observation or carried advantage is observable. - """ - runner = make_runner(tmp_path, rnd=rnd, video=False, frequency_episodes=1.6) - control = runner.env.unwrapped - step = control.step - - def distinct_reward(action): - obs, reward, done, extras = step(action) - return obs, reward * (1 + 100 * control.resets), done, extras - - control.step = distinct_reward - compute = runner.alg.compute_returns - evaluate = runner.evaluation.run - records = [] - eval_count = 0 - - def checked_returns(obs): - st = runner.alg.storage - assert st.step == runner.cfg["num_steps_per_env"] - torch.testing.assert_close(obs["proprio"], runner.env.get_observations()["proprio"]) - assert (st.observations["proprio"][..., 0] == 2 * eval_count).all() - bootstrap = runner.alg.critic(obs).detach() - rewards, values, dones = (x.clone() for x in (st.rewards, st.values, st.dones)) - expected = torch.empty_like(values) - # Explicit sum of future TD residuals within this rollout only. - next_values = torch.cat((values[1:], bootstrap.unsqueeze(0))) - alive = 1 - dones.float() - deltas = rewards + runner.alg.gamma * alive * next_values - values - for t in range(st.num_transitions_per_env): - advantage = torch.zeros_like(bootstrap) - discount = torch.ones_like(bootstrap) - for k in range(t, st.num_transitions_per_env): - advantage += discount * deltas[k] - discount *= runner.alg.gamma * runner.alg.lam * alive[k] - expected[t] = advantage + values[t] - compute(obs) - torch.testing.assert_close(st.returns, expected) - advantages = expected - values - if not runner.alg.normalize_advantage_per_mini_batch: - advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8) - torch.testing.assert_close(st.advantages, advantages) - records.append((st.returns.clone(), st.advantages.clone())) - - def checked_evaluation(current): - nonlocal eval_count - st = runner.alg.storage - assert st.step == 0 # Optimizer consumed the completed rollout first. - assert current.alg.transition.observations is None - before = (st.returns.clone(), st.advantages.clone()) - fresh = evaluate(current) - assert st.step == 0 - for saved, actual in zip(before, (st.returns, st.advantages), strict=True): - torch.testing.assert_close(actual, saved, rtol=0, atol=0) - eval_count += 1 - assert (fresh["proprio"][:, 0] == 2 * eval_count).all() - return fresh - - runner.alg.compute_returns = checked_returns - runner.evaluation.run = checked_evaluation - runner.learn(3) - assert len(records) == eval_count == 3 - assert not torch.allclose(records[0][0], records[1][0]) From a70cfa912e58cb1a76b29463ef564c8fe6a099ca Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:11:10 -0800 Subject: [PATCH 13/30] Deploy from run.json with gaze in field radii The deployment contract carries the real camera's model, the retina in degrees and the gaze step, limit and field radius. The controller integrates the gaze in field radii with the simulator's radial limit, and the proprioception matches simulation: 30 values ending with gaze and gaze velocity. The planar crop is gone. Export defaults to the simulated camera and to the run's DINO checkpoint and exit layer. --- src/isaaclab_tutorial/active_gaze/__init__.py | 3 + .../active_gaze/configuration.py | 5 +- .../active_gaze/deployment/control.py | 63 ++++++++++----- .../active_gaze/deployment/export.py | 77 +++++++++---------- .../active_gaze/deployment/model.py | 51 ++++++------ .../active_gaze/deployment/run.py | 28 +++---- .../active_gaze/deployment/runtime.py | 9 ++- 7 files changed, 127 insertions(+), 109 deletions(-) diff --git a/src/isaaclab_tutorial/active_gaze/__init__.py b/src/isaaclab_tutorial/active_gaze/__init__.py index ff4c52a..a29f3ca 100644 --- a/src/isaaclab_tutorial/active_gaze/__init__.py +++ b/src/isaaclab_tutorial/active_gaze/__init__.py @@ -6,3 +6,6 @@ """ TASK_ID = "IsaacTutorial-Place-Vial-SO101-ActiveGaze" + +RUN_FILE = "run.json" +"""Name of the file, next to a run's checkpoints, that describes what the run trained.""" diff --git a/src/isaaclab_tutorial/active_gaze/configuration.py b/src/isaaclab_tutorial/active_gaze/configuration.py index f8cdc14..51d623e 100644 --- a/src/isaaclab_tutorial/active_gaze/configuration.py +++ b/src/isaaclab_tutorial/active_gaze/configuration.py @@ -11,12 +11,11 @@ from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import ARM_JOINTS -from . import TASK_ID +from . import RUN_FILE, TASK_ID from .goals import NumberedResetFromDataset from .language import INSTRUCTIONS -RUN_FILE = "run.json" -"""Name of the file, next to a run's checkpoints, that describes what the run trained.""" +__all__ = ["RUN_FILE", "compose", "describe", "resume_overrides"] def compose(overrides: Sequence[str] = (), saved: dict | None = None): diff --git a/src/isaaclab_tutorial/active_gaze/deployment/control.py b/src/isaaclab_tutorial/active_gaze/deployment/control.py index 91864a6..583685c 100644 --- a/src/isaaclab_tutorial/active_gaze/deployment/control.py +++ b/src/isaaclab_tutorial/active_gaze/deployment/control.py @@ -4,65 +4,86 @@ import numpy as np +FORMAT = "isaaclab_tutorial.active_gaze.leapp.v1" JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper") PROPRIOCEPTION = ( "joint_pos:6", "joint_vel:6", "joint_target:6", "previous_action:8", - "gaze_angles:2", + "gaze:2", "gaze_velocity:2", - "gaze_target:2", ) +"""The actor's proprioception, as in simulation. Gaze is in field radii, its velocity in field radii per second.""" +PROPRIOCEPTION_SIZE = 30 +GAZE = slice(26, 28) +"""Where the gaze sits in the proprioception.""" +POLICY_HZ = 30 +"""Policy decisions per second; the simulator's control rate.""" +TARGET_HZ = 120 +"""Motor target updates per second; the simulator's physics rate, at which relative targets follow the joints.""" + + +def clamp_gaze(gaze: np.ndarray, limit: float) -> np.ndarray: + """Scale the gaze back onto the circle of radius ``limit`` when it leaves it, as in simulation.""" + return gaze * (limit / max(float(np.linalg.norm(gaze)), limit)) def advance_policy_deadline(deadline: float, now: float) -> tuple[float, int]: """Preserve the policy clock's phase despite bus wakeup jitter, without bursts.""" - periods = max(1, math.floor((now - deadline) * 30) + 1) - return deadline + periods / 30, periods - 1 + periods = max(1, math.floor((now - deadline) * POLICY_HZ) + 1) + return deadline + periods / POLICY_HZ, periods - 1 def validate_contract(contract: dict) -> None: if ( - contract.get("format") != "isaaclab_fovi.so101.leapp.v1" + contract.get("format") != FORMAT or contract.get("joint_order") != list(JOINTS) or contract.get("joint_units") != "radians" or contract.get("proprioception") != list(PROPRIOCEPTION) - or contract.get("policy_hz") != 30 - or contract.get("relative_target_hz") != 120 + or contract.get("policy_hz") != POLICY_HZ + or contract.get("relative_target_hz") != TARGET_HZ ): raise ValueError("Unsupported SO-101 deployment contract") scale = np.asarray(contract["action_scale"]) if scale.shape != (6,) or not np.isfinite(scale).all() or (scale <= 0).any(): raise ValueError("Expected six finite positive action scales") - for name in ("gaze_limit", "gaze_max_delta"): - if not math.isfinite(contract[name]) or contract[name] <= 0: - raise ValueError(f"Invalid {name}") + for name in ("step_size", "limit", "field_radius_deg"): + value = contract["gaze"][name] + if not math.isfinite(value) or value <= 0: + raise ValueError(f"Invalid gaze {name}") class PolicyState: - """Only commit gaze/action history when a policy result is accepted by control.""" + """Only commit gaze and action history when control accepts a policy result.""" def __init__(self, contract: dict): validate_contract(contract) self.scale = np.asarray(contract["action_scale"], dtype=np.float64) - self.limit = contract["gaze_limit"] - self.delta = contract["gaze_max_delta"] + self.step_size = contract["gaze"]["step_size"] + self.limit = contract["gaze"]["limit"] + self.field_radius_deg = contract["gaze"]["field_radius_deg"] self.reset() def reset(self, gaze=None): + """Start with no action history and the gaze [field radii] on the optical axis, or at ``gaze``.""" self.action = np.zeros(8, dtype=np.float32) self.gaze = np.zeros(2, dtype=np.float32) if gaze is None else np.asarray(gaze, dtype=np.float32).copy() - if self.gaze.shape != (2,) or not np.isfinite(self.gaze).all() or (np.abs(self.gaze) > self.limit).any(): - raise ValueError("Initial gaze must be finite and inside the trained range") + if self.gaze.shape != (2,) or not np.isfinite(self.gaze).all() or np.linalg.norm(self.gaze) > self.limit: + raise ValueError("Initial gaze must be finite and inside the trained limit") self.gaze_velocity = np.zeros(2, dtype=np.float32) + @property + def angles_deg(self) -> np.ndarray: + """Gaze (tilt, pan) [deg].""" + return self.gaze * self.field_radius_deg + def observation(self, position, velocity, target): # Training observations are raw encoder values, not deployment-specific clipping. - proprio = np.concatenate( - (position, velocity, target, self.action, self.gaze, self.gaze_velocity, self.gaze) - ).astype(np.float32) - if proprio.shape != (32,) or not np.isfinite(proprio).all(): + proprio = np.concatenate((position, velocity, target, self.action, self.gaze, self.gaze_velocity)).astype( + np.float32 + ) + if proprio.shape != (PROPRIOCEPTION_SIZE,) or not np.isfinite(proprio).all(): raise ValueError("Expected finite SO-101 proprioception") return proprio @@ -71,8 +92,8 @@ def commit(self, action): if action.shape != (8,) or not np.isfinite(action).all(): raise ValueError("Expected eight finite policy actions") self.action = action.clip(-1, 1) - gaze = (self.gaze + self.action[-2:] * self.delta).clip(-self.limit, self.limit) - self.gaze_velocity = (gaze - self.gaze) * 30 + gaze = clamp_gaze(self.gaze + self.action[-2:] * self.step_size, self.limit).astype(np.float32) + self.gaze_velocity = (gaze - self.gaze) * POLICY_HZ self.gaze = gaze def target(self, measured, limits): diff --git a/src/isaaclab_tutorial/active_gaze/deployment/export.py b/src/isaaclab_tutorial/active_gaze/deployment/export.py index 051f2fc..2522504 100644 --- a/src/isaaclab_tutorial/active_gaze/deployment/export.py +++ b/src/isaaclab_tutorial/active_gaze/deployment/export.py @@ -8,9 +8,10 @@ import torch -from .control import JOINTS, PROPRIOCEPTION, validate_contract +from isaaclab_tutorial.active_gaze import RUN_FILE + +from .control import FORMAT, GAZE, JOINTS, POLICY_HZ, PROPRIOCEPTION, PROPRIOCEPTION_SIZE, TARGET_HZ, validate_contract from .model import load_policy -from .retina import nominal_calibration def export_node(model, inputs: dict, output: Path): @@ -46,56 +47,50 @@ def export_node(model, inputs: dict, output: Path): return leapp.InferenceManager(str(yaml)), yaml -def export(checkpoint: Path, dino: str, output: Path, calibration=None, device="cuda:0"): +def export(checkpoint: Path, output: Path, camera_model: dict | None = None, dino: str | None = None, device="cuda:0"): + """Export a checkpoint for the real camera ``camera_model``; without one, for the simulated camera.""" if device != "cuda:0": raise ValueError("Export on cuda:0; select the physical GPU with CUDA_VISIBLE_DEVICES") if output.exists(): raise FileExistsError(f"Use a new export directory: {output}") - settings = json.loads(checkpoint.with_name("example.json").read_text()) - planar = settings.get("retinal_geometry") == "planar" - if planar and calibration is not None: - raise ValueError("Planar deployment uses an uncalibrated square crop; omit --calibration") - calibrated = calibration is not None - calibration = calibration or nominal_calibration(settings["camera"]["camera_hfov"]) - dense, original, settings = load_policy(checkpoint, dino, calibration, device) + run = json.loads(checkpoint.with_name(RUN_FILE).read_text()) + control = run["control"] + if (control["policy_hz"], control["physics_hz"]) != (POLICY_HZ, TARGET_HZ): + raise ValueError(f"Deployment runs the policy at {POLICY_HZ} Hz and motor targets at {TARGET_HZ} Hz") + calibrated = camera_model is not None + camera_model = camera_model or run["retina"]["camera_model"] + dense, original, run = load_policy(checkpoint, camera_model, device, dino) output.mkdir(parents=True) - camera = settings["camera"] - scale = settings.get("control", {}).get("action_scale") - if scale is None: - raise ValueError("Checkpoint must record control.action_scale") + retina = run["retina"] + gaze = run["gaze"] contract = dict( - format="isaaclab_fovi.so101.leapp.v1", + format=FORMAT, joint_order=list(JOINTS), joint_units="radians", proprioception=list(PROPRIOCEPTION), - policy_hz=30, - relative_target_hz=120, - action_scale=scale, - gaze_limit=camera["gaze_limit"], - gaze_max_delta=camera["gaze_max_delta"], - camera_calibration=calibration, + policy_hz=POLICY_HZ, + relative_target_hz=TARGET_HZ, + action_scale=control["action_scale"], + gaze=dict(step_size=gaze["step_size"], limit=gaze["limit"], field_radius_deg=gaze["field_radius_deg"]), + camera_model=camera_model, calibrated_capture=calibrated, - retinal_geometry="planar" if planar else "spherical", - capture_preprocessing="center_square_resize_640" if planar else "calibrated_raster", - retinal_resolution=128, - camera_hfov=camera["camera_hfov"], - cmf_a=camera["cmf_a"], - instruction=settings["policy"]["instructions"][0], + retina=dict(fov_deg=retina["fov_deg"], cmf_a_deg=retina["cmf_a_deg"], resolution=retina["resolution"]), + instruction=run["instructions"][0], source_sha256=hashlib.sha256(checkpoint.read_bytes()).hexdigest(), source_checkpoint=checkpoint.name, - dino_checksum=settings["policy"]["dino_checksum"], + dino=dict(checksum=run["dino"]["checksum"], num_layers=run["dino"]["num_layers"]), versions={name: importlib.metadata.version(name) for name in ("torch", "fovi", "leapp")}, rgb_layout="BHWC_uint8", retinal_sampling="bilinear_border_mask_round_uint8", - initial_gaze="neutral", + initial_gaze="optical_axis", output="eight_unclipped_normalized_actions", ) validate_contract(contract) generator = torch.Generator(device=device).manual_seed(71) - h, w = calibration["image_size"] - proprio = torch.zeros(1, 32, device=device) + h, w = camera_model["image_size"] + proprio = torch.zeros(1, PROPRIOCEPTION_SIZE, device=device) rgb = torch.randint(0, 256, (1, h, w, 3), dtype=torch.uint8, device=device, generator=generator) - retina = dense.retina(rgb, proprio[:, 26:28]) + retina = dense.retina(rgb, proprio[:, GAZE] * dense.field_radius_deg) camera_runtime, camera_yaml = export_node(dense, dict(proprio=proprio, rgb=rgb), output / "camera") retinal_runtime, retinal_yaml = export_node( dense.policy, dict(proprio=proprio, retinal_rgb=retina), output / "retinal" @@ -105,10 +100,12 @@ def export(checkpoint: Path, dino: str, output: Path, calibration=None, device=" # BF16 encoder's numerics after its first invocation in PyTorch 2.11. with torch.inference_mode(), torch.jit.optimized_execution(False): for _ in range(8): - proprio = torch.randn(1, 32, device=device, generator=generator) - proprio[:, 26:28].clamp_(-camera["gaze_limit"], camera["gaze_limit"]) + proprio = torch.randn(1, PROPRIOCEPTION_SIZE, device=device, generator=generator) + # Keep the gaze inside the trained limit, as the controller does. + norm = proprio[:, GAZE].norm(dim=-1, keepdim=True).clamp_min(gaze["limit"]) + proprio[:, GAZE] *= gaze["limit"] / norm rgb.random_(0, 256, generator=generator) - retina = dense.retina(rgb, proprio[:, 26:28]) + retina = dense.retina(rgb, proprio[:, GAZE] * dense.field_radius_deg) tokens = dense.policy.encoder(retina) expected = original( dict( @@ -145,21 +142,21 @@ def export(checkpoint: Path, dino: str, output: Path, calibration=None, device=" def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--checkpoint", type=Path, required=True) - parser.add_argument("--dino", required=True, help="Local Fovi bundle or pinned model URI") parser.add_argument("--output", type=Path, required=True) parser.add_argument( - "--calibration", + "--camera_model", type=Path, - help="Actual capture CameraModel JSON for spherical policies; omit for planar policies", + help="The real camera's CameraModel fields as JSON. Required on hardware; defaults to the simulated camera.", ) + parser.add_argument("--dino", help="Local Fovi bundle of the run's DINO checkpoint; defaults to the run's.") parser.add_argument("--device", default="cuda:0") args = parser.parse_args() torch.set_num_threads(4) export( args.checkpoint.resolve(), - args.dino, args.output.resolve(), - json.loads(args.calibration.read_text()) if args.calibration else None, + json.loads(args.camera_model.read_text()) if args.camera_model else None, + args.dino, args.device, ) diff --git a/src/isaaclab_tutorial/active_gaze/deployment/model.py b/src/isaaclab_tutorial/active_gaze/deployment/model.py index abf7baa..52c2bd5 100644 --- a/src/isaaclab_tutorial/active_gaze/deployment/model.py +++ b/src/isaaclab_tutorial/active_gaze/deployment/model.py @@ -7,9 +7,11 @@ import torch from torch import nn +from isaaclab_tutorial.active_gaze import RUN_FILE from isaaclab_tutorial.active_gaze.learning.dino import FrozenDino from isaaclab_tutorial.active_gaze.learning.models import LanguageVisionActor +from .control import GAZE, PROPRIOCEPTION_SIZE from .retina import SoftwareRetina @@ -38,50 +40,55 @@ def forward(self, proprio: torch.Tensor, retinal_rgb: torch.Tensor) -> torch.Ten class CameraPolicy(nn.Module): - def __init__(self, retina, policy): + """Sample the retina from the camera image at the proprioception's gaze, then run the policy.""" + + def __init__(self, retina, policy, field_radius_deg: float): super().__init__() self.retina, self.policy = retina, policy + self.field_radius_deg = field_radius_deg def forward(self, proprio: torch.Tensor, rgb: torch.Tensor) -> torch.Tensor: - return self.policy(proprio, self.retina(rgb, proprio[:, 26:28])) + return self.policy(proprio, self.retina(rgb, proprio[:, GAZE] * self.field_radius_deg)) + +def load_policy(checkpoint: Path, camera_model: dict, device: str, dino: str | None = None): + """Load trusted local training artifacts and validate their supported contract. -def load_policy(checkpoint: Path, dino: str, calibration: dict, device: str): - """Load trusted local training artifacts and validate their supported contract.""" - settings = json.loads(checkpoint.with_name("example.json").read_text()) + ``camera_model`` describes the real camera as :class:`fovi.sensing.projection.CameraModel` fields. ``dino`` + overrides the run's DINO reference, for example with a local bundle of the same checkpoint. + """ + run = json.loads(checkpoint.with_name(RUN_FILE).read_text()) config = json.loads(checkpoint.with_name("agent.json").read_text()) - if settings["policy"]["name"] != "dino_language" or settings["resolution"] != 128: - raise ValueError("This exporter supports the SO-101 128px DINO/language policy") + retina = run["retina"] + if run["policy"] != "dino_language" or retina["resolution"] != 128: + raise ValueError("Deployment supports the 128px DINO and language policy") + if run["action_chunk_size"] != 1: + raise ValueError("Deployment requires single-step actions") if config["obs_groups"]["actor"] != ["proprio", "vision", "instruction"]: raise ValueError("Unsupported actor observation contract") - if config["algorithm"].get("action_chunk_size", 1) != 1: - raise ValueError("Hardware export currently requires single-step actions") if config.get("clip_actions") != 1.0: raise ValueError("Unsupported action clipping") packed = torch.load(checkpoint, map_location="cpu", weights_only=False) state = packed["actor_state_dict"] - if state["obs_normalizer._mean"].shape != (1, 32): - raise ValueError("Expected the SO-101 32-value proprioceptive contract") + if state["obs_normalizer._mean"].shape != (1, PROPRIOCEPTION_SIZE): + raise ValueError(f"Expected {PROPRIOCEPTION_SIZE} proprioceptive values") options = dict(config["actor"]) if options.pop("class_name") != "isaaclab_tutorial.active_gaze.learning.models:LanguageVisionActor": raise ValueError("Unsupported actor class") options["instruction_table_path"] = str(checkpoint.with_name("instructions.pt")) options["language_device"] = "cpu" obs = dict( - proprio=torch.zeros(1, 32), + proprio=torch.zeros(1, PROPRIOCEPTION_SIZE), vision=torch.zeros(1, 64, 384), instruction=torch.zeros(1, 1, dtype=torch.long), ) actor = LanguageVisionActor(obs, config["obs_groups"], "actor", 8, **options).eval() actor.load_state_dict(state, strict=True) - encoder = FrozenDino(dino, settings["policy"]["dino_checksum"], batch_size=1) - camera = settings["camera"] + settings = run["dino"] + encoder = FrozenDino( + dino or settings["reference"], settings["checksum"], batch_size=1, num_layers=settings["num_layers"] + ) retinal = RetinalPolicy(encoder, FlatActor(actor)).to(device).eval() - if settings.get("retinal_geometry") == "planar": - from .planar import PlanarRetina - - retina = PlanarRetina(camera["camera_hfov"], camera["cmf_a"]) - else: - retina = SoftwareRetina(calibration, camera["camera_hfov"], camera["cmf_a"]) - dense = CameraPolicy(retina, retinal) - return dense.to(device).eval(), actor.to(device).eval(), settings + sampler = SoftwareRetina(camera_model, retina["fov_deg"], retina["cmf_a_deg"], retina["resolution"]) + dense = CameraPolicy(sampler, retinal, run["gaze"]["field_radius_deg"]) + return dense.to(device).eval(), actor.to(device).eval(), run diff --git a/src/isaaclab_tutorial/active_gaze/deployment/run.py b/src/isaaclab_tutorial/active_gaze/deployment/run.py index 7e974a1..9bd554c 100644 --- a/src/isaaclab_tutorial/active_gaze/deployment/run.py +++ b/src/isaaclab_tutorial/active_gaze/deployment/run.py @@ -15,7 +15,7 @@ import numpy as np import torch -from .control import JOINTS, PolicyState, advance_policy_deadline +from .control import JOINTS, POLICY_HZ, TARGET_HZ, PolicyState, advance_policy_deadline from .hardware import ( JointMap, finish_motor_control, @@ -25,19 +25,18 @@ class SceneCamera: - """Capture the latest frame using the calibrated raster size.""" + """Capture the latest frame at the camera model's raster size.""" - def __init__(self, device, image_size, planar=False): + def __init__(self, device, image_size): import cv2 self.capture = cv2.VideoCapture(device, cv2.CAP_V4L2) if not self.capture.isOpened(): raise RuntimeError(f"Cannot open camera {device}") h, w = image_size - self.planar = planar self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, w) self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, h) - self.capture.set(cv2.CAP_PROP_FPS, 30) + self.capture.set(cv2.CAP_PROP_FPS, POLICY_HZ) self.capture.set(cv2.CAP_PROP_BUFFERSIZE, 1) self.latest, self.error = None, None self.stop = threading.Event() @@ -50,15 +49,7 @@ def timestamped_frame(self): latest = self.latest if latest is None or time.monotonic() - latest[0] > 0.1: raise RuntimeError("No fresh camera frame") - stamp, rgb = latest - if self.planar: - import cv2 - - h, w = rgb.shape[:2] - side = min(h, w) - top, left = (h - side) // 2, (w - side) // 2 - rgb = cv2.resize(rgb[top : top + side, left : left + side], (640, 640), interpolation=cv2.INTER_AREA) - return stamp, rgb + return latest def _read(self): import cv2 @@ -116,12 +107,11 @@ def main(): torch.set_num_threads(1) runtime = PolicyRuntime(args.bundle, args.device) - planar = runtime.contract.get("retinal_geometry") == "planar" - if args.execute and not planar and not runtime.contract["calibrated_capture"]: - parser.error("Export with the actual camera --calibration before hardware execution") + if args.execute and not runtime.contract["calibrated_capture"]: + parser.error("Export with the real camera's --camera_model before hardware execution") state = PolicyState(runtime.contract) robot = SO101Follower(SO101FollowerConfig(port=args.port, id=args.id, use_degrees=True)) - camera = SceneCamera(args.camera, runtime.contract["camera_calibration"]["image_size"], planar) + camera = SceneCamera(args.camera, runtime.contract["camera_model"]["image_size"]) worker = InferenceWorker(runtime) configured = False traces, inputs, actions, images, timings = [], [], [], [], [] @@ -200,7 +190,7 @@ def main(): previous, previous_time = measured, sample_time if args.trace: traces.append(np.concatenate(([tick - start], measured, target, state.action))) - next_tick += 1 / 120 + next_tick += 1 / TARGET_HZ remaining = next_tick - time.monotonic() if remaining > 0: time.sleep(remaining) diff --git a/src/isaaclab_tutorial/active_gaze/deployment/runtime.py b/src/isaaclab_tutorial/active_gaze/deployment/runtime.py index be2f715..425f9f2 100644 --- a/src/isaaclab_tutorial/active_gaze/deployment/runtime.py +++ b/src/isaaclab_tutorial/active_gaze/deployment/runtime.py @@ -9,7 +9,7 @@ import numpy as np import torch -from .control import validate_contract +from .control import PROPRIOCEPTION_SIZE, validate_contract class PolicyRuntime: @@ -29,7 +29,8 @@ def __init__(self, bundle: Path, device="cuda:0", *, retinal=False): raise ValueError("Use cuda:0 and select the physical GPU with CUDA_VISIBLE_DEVICES") self.retinal = retinal self.image_key = "retinal_rgb" if retinal else "rgb" - size = [128, 128] if retinal else self.contract["camera_calibration"]["image_size"] + resolution = self.contract["retina"]["resolution"] + size = [resolution, resolution] if retinal else self.contract["camera_model"]["image_size"] self.image_shape = (1, *size, 3) graph = self.bundle / self.contract["retinal_graph" if retinal else "camera_graph"] if self.device.type == "cuda": @@ -44,8 +45,8 @@ def infer(self, proprio, rgb): image = image.unsqueeze(0) if image.shape != self.image_shape or image.dtype != torch.uint8: raise ValueError(f"Expected uint8 RGB {self.image_shape}; never resize an uncalibrated image") - if proprio.shape != (1, 32) or not torch.isfinite(proprio).all(): - raise ValueError("Expected 32 finite proprioceptive values") + if proprio.shape != (1, PROPRIOCEPTION_SIZE) or not torch.isfinite(proprio).all(): + raise ValueError(f"Expected {PROPRIOCEPTION_SIZE} finite proprioceptive values") # The profiling executor misoptimizes the traced BF16 DINO graph after # warmup on PyTorch 2.11. Preserve the validated eager-trace numerics. with torch.jit.optimized_execution(False): From e6ebebfb962f38b7d57ab1d9722e6da03f48064f Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:23:45 -0800 Subject: [PATCH 14/30] Fix issues found by training and inspecting in simulation The numbered reset spells out the base reset's parameters, which the event manager checks against the configuration. The runner reads the reset sampler from the curriculum manager's resolved configuration. Inspection checks that env 0's reset gaze is inside the camera image, and diagnostic markers are placed in fractions of the camera image. The video helper of the removed periodic evaluation is deleted. --- src/isaaclab_tutorial/active_gaze/goals.py | 26 ++++++- src/isaaclab_tutorial/active_gaze/runner.py | 3 +- src/isaaclab_tutorial/active_gaze/train.py | 6 +- .../active_gaze/training/video.py | 75 ------------------- 4 files changed, 28 insertions(+), 82 deletions(-) delete mode 100644 src/isaaclab_tutorial/active_gaze/training/video.py diff --git a/src/isaaclab_tutorial/active_gaze/goals.py b/src/isaaclab_tutorial/active_gaze/goals.py index 9df0d18..9096fa9 100644 --- a/src/isaaclab_tutorial/active_gaze/goals.py +++ b/src/isaaclab_tutorial/active_gaze/goals.py @@ -230,7 +230,29 @@ def __init__(self, cfg, env): def sampling_row_probabilities(self): return conditional_row_probabilities(self.row_weights, self.target_fractions) - def __call__(self, env, env_ids, dataset_path, phase_weights, sequential=False, **kwargs): + def __call__( + self, + env, + env_ids, + dataset_path, + phase_weights, + sequential=False, + home_position_noise=0.0, + home_heading_noise=0.0, + home_rack_clearance=0.0, + home_rack_position_noise=0.0, + home_rack_yaw_noise=0.0, + support_height_range=(0.0, 0.0), + ): + # The base term's parameters, spelled out so the event manager can check the configuration against them. + perturbation = dict( + home_position_noise=home_position_noise, + home_heading_noise=home_heading_noise, + home_rack_clearance=home_rack_clearance, + home_rack_position_noise=home_rack_position_noise, + home_rack_yaw_noise=home_rack_yaw_noise, + support_height_range=support_height_range, + ) ids = torch.arange(env.num_envs, device=env.device)[slice(None) if env_ids is None else env_ids] if not len(ids): return @@ -250,7 +272,7 @@ def __call__(self, env, env_ids, dataset_path, phase_weights, sequential=False, # The stock reset restores the chosen rows through its sequential path. self.sequential_rows, self.cursor = rows, 0 try: - super().__call__(env, ids, dataset_path, phase_weights, True, **kwargs) + super().__call__(env, ids, dataset_path, phase_weights, True, **perturbation) finally: self.sequential_rows = saved_rows self.cursor = saved_cursor + len(ids) if sequential else saved_cursor diff --git a/src/isaaclab_tutorial/active_gaze/runner.py b/src/isaaclab_tutorial/active_gaze/runner.py index e363e5f..04b1aed 100644 --- a/src/isaaclab_tutorial/active_gaze/runner.py +++ b/src/isaaclab_tutorial/active_gaze/runner.py @@ -15,7 +15,8 @@ class ResetSamplingRunner(DistributedOnPolicyRunner): def __init__(self, env, train_cfg, log_dir=None, device="cpu", restore_sampler: bool = True): super().__init__(env, train_cfg, log_dir, device) - self.sampler = env.unwrapped.curriculum_manager.get_term_cfg("reset_sampling").func + # The curriculum manager resolves its own copy of the configuration, where the term is an instance. + self.sampler = env.unwrapped.curriculum_manager.cfg.reset_sampling.func self.restore_sampler = restore_sampler self._previous_counts = None original_log = self.logger.log diff --git a/src/isaaclab_tutorial/active_gaze/train.py b/src/isaaclab_tutorial/active_gaze/train.py index 9c4ed44..098056c 100644 --- a/src/isaaclab_tutorial/active_gaze/train.py +++ b/src/isaaclab_tutorial/active_gaze/train.py @@ -261,7 +261,7 @@ def record(env, runner, args): import torch from PIL import Image, ImageDraw - from .gaze import RESET_MODES + from .gaze import RESET_MODES, angles_to_direction from .goals import target_holes from .sim2real import mount_randomization @@ -286,9 +286,7 @@ def record(env, runner, args): ) reset_checks = {name: bool(torch.equal(before[name], after[name])) for name in before} # The reset gaze lies inside the physical camera's image. - reset_checks["reset_gaze_visible"] = bool( - gaze.visible(gaze.directions(gaze_points(gaze)[:1], slice(0, 1))).all() - ) + reset_checks["reset_gaze_visible"] = bool(gaze.visible(angles_to_direction(gaze.angles_deg[:1])).all()) if not all(reset_checks.values()): raise AssertionError(f"Single-environment reset changed other environments: {reset_checks}") policy = runner.get_inference_policy(device=env.device) diff --git a/src/isaaclab_tutorial/active_gaze/training/video.py b/src/isaaclab_tutorial/active_gaze/training/video.py deleted file mode 100644 index 5ec8e90..0000000 --- a/src/isaaclab_tutorial/active_gaze/training/video.py +++ /dev/null @@ -1,75 +0,0 @@ -"""Record native 2D observations with instruction captions. - -Record each environment separately, with its instruction caption. Frames stream -into FFmpeg processes without a plotting runtime or whole-video frame buffers. -""" - -import textwrap -from contextlib import ExitStack -from pathlib import Path - -import imageio.v2 as imageio -import numpy as np -from PIL import Image, ImageDraw, ImageFont - - -class ObservationVideoRecorder: - """One captioned native RGB video per recorded environment.""" - - def __init__(self, directory: Path, fps: float, num_envs: int): - self.num_envs = num_envs - self.frames = 0 - self.segments = [] - self._instructions = None - self._font = ImageFont.load_default(size=16) - directory.mkdir(parents=True, exist_ok=True) - self.paths = [directory / f"env_{index}.mp4" for index in range(num_envs)] - self._stack = ExitStack() - try: - self.writers = [ - self._stack.enter_context( - imageio.get_writer( - str(path), - fps=fps, - codec="libx264", - pixelformat="yuv420p", - quality=None, - ffmpeg_params=["-crf", "18", "-threads", "1", "-movflags", "+faststart"], - ) - ) - for path in self.paths - ] - except Exception: - self._stack.close() - raise - - def capture(self, images, instructions): - """Images are uint8 NHWC camera output; captions sit outside the image.""" - if images.ndim != 4 or images.shape[0] != self.num_envs or images.shape[-1] != 3: - raise ValueError("Expected one native HWC RGB observation per recorded environment") - if images.dtype != np.uint8 or len(instructions) != self.num_envs: - raise ValueError("Observation video requires uint8 RGB and matching instructions") - instructions = tuple(instructions) - if instructions != self._instructions: - self.segments.append({"start_frame": self.frames, "instructions": instructions}) - self._instructions = instructions - for index, (rgb, instruction, writer) in enumerate(zip(images, instructions, self.writers, strict=True)): - frame = Image.new("RGB", (320, 320), "#f4f5f1") - draw = ImageDraw.Draw(frame) - draw.multiline_text( - (12, 6), - textwrap.fill(f"Env {index}: {instruction}", width=32), - font=self._font, - fill="#182c27", - spacing=2, - ) - # Nearest-neighbor enlargement preserves the native pixel grid. - image = Image.fromarray(rgb) - scale = 256 / max(image.size) - image = image.resize(tuple(round(x * scale) for x in image.size), Image.Resampling.NEAREST) - frame.paste(image, ((320 - image.width) // 2, 60)) - writer.append_data(np.asarray(frame)) - self.frames += 1 - - def close(self): - self._stack.close() From 593341dbec03483683dcf63e10d9bad7a07d04cd Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:24:10 -0800 Subject: [PATCH 15/30] Record play and inspection videos with imageio-ffmpeg The fovi extra now installs imageio's ffmpeg backend; without it imageio falls back to a TIFF writer and mp4 recording fails. --- pyproject.toml | 2 +- uv.lock | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index aaa256f..20bdf34 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,7 +27,7 @@ view-so101-resets = "isaaclab_tutorial.tasks.place_vial.reset.generator:view_mai [project.optional-dependencies] # The foveated camera (isaaclab_fovi) and the libraries of the ActiveGaze task. -fovi = ["isaaclab[fovi]", "transformers==5.19.0"] +fovi = ["isaaclab[fovi]", "transformers==5.19.0", "imageio-ffmpeg>=0.5"] leapp = ["leapp==0.7.2"] ovphysx = ["ovphysx"] ovrtx = ["ovrtx==0.5.0.377615", "ovstage==0.1.1.355824"] diff --git a/uv.lock b/uv.lock index 41db44e..42ca131 100644 --- a/uv.lock +++ b/uv.lock @@ -1113,6 +1113,7 @@ dependencies = [ [package.optional-dependencies] fovi = [ + { name = "imageio-ffmpeg", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "isaaclab", extra = ["fovi"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "transformers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] @@ -1144,6 +1145,7 @@ dev = [ [package.metadata] requires-dist = [ + { name = "imageio-ffmpeg", marker = "extra == 'fovi'", specifier = ">=0.5" }, { name = "isaaclab", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead" }, { name = "isaaclab", extras = ["fovi"], marker = "extra == 'fovi'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead" }, { name = "isaaclab", extras = ["video"], marker = "extra == 'video'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead" }, From 9d7d55e808cb73fc3f67e1f79cab1ad360b44a15 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:24:10 -0800 Subject: [PATCH 16/30] Apply the tutorial's lint rules to the imported active-gaze code --- src/isaaclab_tutorial/active_gaze/learning/chunks.py | 2 +- src/isaaclab_tutorial/active_gaze/learning/config.py | 1 + src/isaaclab_tutorial/active_gaze/render_options.py | 1 + src/isaaclab_tutorial/active_gaze/sampling.py | 1 + tests/active_gaze/test_clipped_distribution.py | 5 ++++- 5 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/isaaclab_tutorial/active_gaze/learning/chunks.py b/src/isaaclab_tutorial/active_gaze/learning/chunks.py index 5812d84..19feb61 100644 --- a/src/isaaclab_tutorial/active_gaze/learning/chunks.py +++ b/src/isaaclab_tutorial/active_gaze/learning/chunks.py @@ -121,7 +121,7 @@ def step(self, actions, *, control_steps=None, render_every_step=False, observer timed_out &= ~terminated timeout_discount += timed_out * self.control_gamma ** (index + 1) if "final_obs" in extras: - for key in timeout_obs.keys(): + for key in list(timeout_obs.keys()): mask = timed_out.reshape(-1, *([1] * (timeout_obs[key].ndim - 1))) timeout_obs[key] = torch.where(mask, extras["final_obs"][key], timeout_obs[key]) active &= ~done.bool() diff --git a/src/isaaclab_tutorial/active_gaze/learning/config.py b/src/isaaclab_tutorial/active_gaze/learning/config.py index 1b3157a..9ce63f3 100644 --- a/src/isaaclab_tutorial/active_gaze/learning/config.py +++ b/src/isaaclab_tutorial/active_gaze/learning/config.py @@ -1,6 +1,7 @@ """Configuration for language-conditioned visual actors.""" from isaaclab.utils import configclass + from isaaclab_rl.rsl_rl import RslRlMLPModelCfg diff --git a/src/isaaclab_tutorial/active_gaze/render_options.py b/src/isaaclab_tutorial/active_gaze/render_options.py index ccdf473..c4ed1e1 100644 --- a/src/isaaclab_tutorial/active_gaze/render_options.py +++ b/src/isaaclab_tutorial/active_gaze/render_options.py @@ -3,6 +3,7 @@ from isaaclab.utils import configclass from isaaclab_newton.renderers import NewtonWarpRendererCfg from isaaclab_ov.renderers import OVRTXRendererCfg + from isaaclab_tasks.utils import PresetCfg RENDER_MODES = { diff --git a/src/isaaclab_tutorial/active_gaze/sampling.py b/src/isaaclab_tutorial/active_gaze/sampling.py index a9865af..70ae8cc 100644 --- a/src/isaaclab_tutorial/active_gaze/sampling.py +++ b/src/isaaclab_tutorial/active_gaze/sampling.py @@ -7,6 +7,7 @@ import math import torch + from isaaclab.managers import ManagerTermBase PHASE_NAMES = ("home", "pregrasp", "grasp", "lift", "reorient", "transport", "insert", "release") diff --git a/tests/active_gaze/test_clipped_distribution.py b/tests/active_gaze/test_clipped_distribution.py index 55a2ff2..c408677 100644 --- a/tests/active_gaze/test_clipped_distribution.py +++ b/tests/active_gaze/test_clipped_distribution.py @@ -9,7 +9,10 @@ from scipy.stats import norm from isaaclab_tutorial.active_gaze.learning.chunks import chunk_gaussian_statistics -from isaaclab_tutorial.active_gaze.learning.distributions import ClippedGaussianDistribution, clipped_gaussian_statistics +from isaaclab_tutorial.active_gaze.learning.distributions import ( + ClippedGaussianDistribution, + clipped_gaussian_statistics, +) @pytest.mark.parametrize("mean,std", [(0, 0.5), (0.9, 0.3), (-2, 0.4), (0, 1000)]) From 113568a615d513a57579a2c8b911e239bc20bb87 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:24:10 -0800 Subject: [PATCH 17/30] Update the tests to the active-gaze redesign Tests cover the gaze action in field radii and its teacher, run.json resume, the spawn-derived pinhole camera, the deployment contract and software retina, the camera-mount and photometric sim2real randomization, and the numbered reset that owns each environment's target. Planar and reset-cache tests are removed with their code. The tutorial's task-list and asset tests now include the ActiveGaze task and its built-in MDL label material. --- tests/active_gaze/test_deployment.py | 86 +++++----- tests/active_gaze/test_language.py | 29 ++-- tests/active_gaze/test_numbered.py | 140 ++++++---------- tests/active_gaze/test_presets.py | 89 ++++------ tests/active_gaze/test_rendering.py | 51 +++--- tests/active_gaze/test_sampling.py | 8 +- tests/active_gaze/test_sim2real.py | 241 +++++++++------------------ tests/active_gaze/test_vial.py | 201 +++++++++++----------- tests/test_assets.py | 4 +- tests/test_config.py | 10 +- 10 files changed, 367 insertions(+), 492 deletions(-) diff --git a/tests/active_gaze/test_deployment.py b/tests/active_gaze/test_deployment.py index 2279ef3..82b6736 100644 --- a/tests/active_gaze/test_deployment.py +++ b/tests/active_gaze/test_deployment.py @@ -1,5 +1,6 @@ """Deployment geometry, action-state transitions, and delayed-result handling.""" +import math import time import numpy as np @@ -7,49 +8,64 @@ import torch from isaaclab_tutorial.active_gaze.deployment.control import ( + FORMAT, + GAZE, JOINTS, PROPRIOCEPTION, + PROPRIOCEPTION_SIZE, PolicyState, advance_policy_deadline, ) -from isaaclab_tutorial.active_gaze.deployment.retina import SoftwareRetina, nominal_calibration +from isaaclab_tutorial.active_gaze.deployment.retina import SoftwareRetina from isaaclab_tutorial.active_gaze.deployment.runtime import InferenceWorker def contract(): return dict( - format="isaaclab_fovi.so101.leapp.v1", + format=FORMAT, joint_order=list(JOINTS), joint_units="radians", proprioception=list(PROPRIOCEPTION), policy_hz=30, relative_target_hz=120, action_scale=[0.033] * 5 + [0.02], - gaze_limit=0.66, - gaze_max_delta=0.12, + gaze=dict(step_size=0.1, limit=1.0, field_radius_deg=39.0), ) -def test_state_matches_motor_and_gaze_timing_and_reset(): +def pinhole(fov_deg=78.0, size=640): + """An ideal square pinhole camera's model.""" + focal = size / 2 / math.tan(math.radians(fov_deg / 2)) + center = (size - 1) / 2 + return dict(model="pinhole", image_size=(size, size), intrinsics=(focal, focal, center, center)) + + +def test_state_moves_the_gaze_in_field_radii_within_the_simulators_radial_limit(): state = PolicyState(contract()) - state.reset([0.65, -0.65]) + state.reset([0.7, -0.7]) state.commit([2, 0, 0, 0, 0, -2, 1, -1]) - np.testing.assert_allclose(state.gaze, [0.66, -0.66]) - np.testing.assert_allclose(state.gaze_velocity, [0.3, -0.3], atol=1e-5) + # The step leaves the unit circle, so the gaze is scaled back onto it, as in simulation. + np.testing.assert_allclose(state.gaze, [0.5**0.5, -(0.5**0.5)], atol=1e-6) + np.testing.assert_allclose(state.gaze_velocity, (state.gaze - [0.7, -0.7]) * 30, atol=1e-5) + np.testing.assert_allclose(state.angles_deg, state.gaze * 39.0) observed = state.observation(np.ones(6), np.ones(6) * 13, np.ones(6) * 2) + assert observed.shape == (PROPRIOCEPTION_SIZE,) np.testing.assert_array_equal(observed[6:12], [13] * 6) np.testing.assert_array_equal(observed[18:26], state.action) - np.testing.assert_array_equal(observed[26:28], observed[30:32]) + np.testing.assert_array_equal(observed[GAZE], state.gaze) + np.testing.assert_array_equal(observed[28:30], state.gaze_velocity) limits = np.array([[-4, 4]] * 6) first = state.target(np.zeros(6), limits) second = state.target(np.ones(6), limits) np.testing.assert_allclose(second - first, np.ones(6)) state.reset() - np.testing.assert_array_equal(state.observation(np.zeros(6), np.zeros(6), np.zeros(6)), np.zeros(32)) + np.testing.assert_array_equal( + state.observation(np.zeros(6), np.zeros(6), np.zeros(6)), np.zeros(PROPRIOCEPTION_SIZE) + ) with pytest.raises(ValueError): state.commit([float("nan")] * 8) with pytest.raises(ValueError): - state.reset([0.8, 0]) + state.reset([0.8, 0.8]) def test_policy_clock_preserves_rate_with_bus_jitter_and_skips_missed_periods(): @@ -67,28 +83,26 @@ def test_policy_clock_preserves_rate_with_bus_jitter_and_skips_missed_periods(): assert missed == 3 -def test_dense_sampling_orientation_calibration_and_visibility_match_sensor(): - from fovi.sensing.projection import gaze_rotation - - from isaaclab_fovi.sensors.calibrated_geometry import calibrated_visibility - - retina = SoftwareRetina(nominal_calibration(78), 78, 0.0075) +def test_software_retina_is_upright_follows_the_gaze_and_blanks_what_the_camera_misses(): + retina = SoftwareRetina(pinhole(), 78.0, 0.591, 128) yy, xx = torch.meshgrid(torch.arange(640), torch.arange(640), indexing="ij") rgb = torch.stack((xx / 3, yy / 3, torch.full_like(xx, 100)), -1).to(torch.uint8)[None] - gaze = torch.tensor([[0.0, 0.0], [0.3, -0.4]]) + # Gaze (tilt, pan) [deg]: positive tilt looks up, positive pan looks left. + gaze = torch.tensor([[0.0, 0.0], [17.0, -23.0]]) grid, valid = retina.grid(gaze) image = retina(rgb.expand(2, -1, -1, -1), gaze) assert image.shape == (2, 128, 128, 3) # Upright public raster: right means larger source x, down means larger source y. assert image[0, 64, 80, 0] > image[0, 64, 48, 0] assert image[0, 80, 64, 1] > image[0, 48, 64, 1] + # Looking up and right moves the fixation to smaller source y and larger source x. assert image[1, 64, 64, 0] > image[0, 64, 64, 0] assert image[1, 64, 64, 1] < image[0, 64, 64, 1] + # Looking straight ahead, the square 78 degree camera sees the whole circular 78 degree retina; looking away, it + # cuts part of it off. + assert torch.equal(valid[0], retina.valid[0]) + assert valid[1].sum() < valid[0].sum() assert (image[~valid.expand_as(image)] == 0).all() - tilt, pan = gaze.unbind(-1) - direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) - reference = calibrated_visibility(retina.camera, retina.rays, gaze_rotation(direction, "pan_tilt")) - assert torch.equal(valid, reference.reshape_as(valid) & retina.valid) assert torch.isfinite(grid).all() @@ -99,9 +113,9 @@ def infer(self, proprio, rgb): worker = InferenceWorker(Runtime()) try: - worker.submit(np.zeros(32), np.zeros((2, 2, 3)), time.monotonic() - 1) + worker.submit(np.zeros(PROPRIOCEPTION_SIZE), np.zeros((2, 2, 3)), time.monotonic() - 1) with pytest.raises(RuntimeError, match="already"): - worker.submit(np.zeros(32), np.zeros((2, 2, 3)), time.monotonic()) + worker.submit(np.zeros(PROPRIOCEPTION_SIZE), np.zeros((2, 2, 3)), time.monotonic()) with pytest.raises(RuntimeError, match="stale"): worker.poll() finally: @@ -109,8 +123,7 @@ def infer(self, proprio, rgb): @pytest.mark.parametrize("execute,fail", [(False, False), (True, False), (True, True)]) -@pytest.mark.parametrize("planar", [False, True]) -def test_hardware_adapter_read_only_startup_and_error_shutdown(tmp_path, monkeypatch, execute, fail, planar): +def test_hardware_adapter_read_only_startup_and_error_shutdown(tmp_path, monkeypatch, execute, fail): import hashlib import json import sys @@ -167,12 +180,7 @@ def send_action(self, action): class Runtime: def __init__(self, *args): - self.contract = dict( - contract(), - camera_calibration={"image_size": [2, 2]}, - calibrated_capture=not planar, - retinal_geometry="planar" if planar else "spherical", - ) + self.contract = dict(contract(), camera_model={"image_size": [2, 2]}, calibrated_capture=True) def infer(self, *args): clock.now += 2 # Long warmup while someone moves the arm. @@ -266,14 +274,8 @@ def test_export_rejects_chunked_actor_before_loading_weights(tmp_path): from isaaclab_tutorial.active_gaze.deployment.model import load_policy - (tmp_path / "example.json").write_text(json.dumps({"policy": {"name": "dino_language"}, "resolution": 128})) - (tmp_path / "agent.json").write_text( - json.dumps( - { - "obs_groups": {"actor": ["proprio", "vision", "instruction"]}, - "algorithm": {"action_chunk_size": 4}, - } - ) - ) + run = dict(policy="dino_language", retina=dict(resolution=128), action_chunk_size=3) + (tmp_path / "run.json").write_text(json.dumps(run)) + (tmp_path / "agent.json").write_text(json.dumps({"obs_groups": {"actor": ["proprio", "vision", "instruction"]}})) with pytest.raises(ValueError, match="single-step actions"): - load_policy(tmp_path / "model.pt", "unused", {}, "cpu") + load_policy(tmp_path / "model.pt", pinhole(), "cpu") diff --git a/tests/active_gaze/test_language.py b/tests/active_gaze/test_language.py index 0aa6b69..3202f89 100644 --- a/tests/active_gaze/test_language.py +++ b/tests/active_gaze/test_language.py @@ -31,35 +31,34 @@ def config(layers): def test_language_configuration_keeps_numbered_task_and_critic(): - from isaaclab_tutorial.active_gaze.configuration import compose + from isaaclab_tutorial.active_gaze.configuration import compose, describe from isaaclab_tutorial.active_gaze.language import instruction_index - cnn = compose(["presets=numbered", "env.scene.eye.cmf_a=0.0075"])[0] - cfg = compose(["presets=dino_language", "env.scene.eye.cmf_a=0.0075"])[0] - assert cfg.scene.eye.foveated_res == 128 - assert cfg.observations.scene_rgb is None - assert cfg.observations.proprioception is None - assert cfg.observations.gaze is None + cnn = compose(["presets=numbered", "env.scene.eye.cmf_a_deg=10.0"])[0] + cfg, agent, _ = compose(["presets=dino_language", "env.scene.eye.cmf_a_deg=10.0"]) + assert cfg.scene.eye.foveated_res == 128 and cfg.scene.eye.cmf_a_deg == 10.0 + assert not hasattr(cfg.observations, "scene_rgb") and not hasattr(cfg.observations, "gaze") assert cfg.observations.critic.to_dict() == cnn.observations.critic.to_dict() assert cfg.terminations.to_dict() == cnn.terminations.to_dict() assert cfg.rewards.to_dict() == cnn.rewards.to_dict() assert cfg.events.to_dict() == cnn.events.to_dict() + # The language actor's proprioception is the CNN actor's, followed by the gaze state. + proprio = cfg.observations.proprio.to_dict() for key, value in cnn.observations.proprioception.to_dict().items(): - assert cfg.observations.proprio.to_dict()[key] == value - env = SimpleNamespace(num_envs=4, device="cpu", vial_number=torch.arange(1, 5)) + assert proprio[key] == value + assert list(proprio)[-1] == "gaze" + env = SimpleNamespace(num_envs=4, device="cpu") assert torch.equal(instruction_index(env), torch.zeros(4, 1, dtype=torch.long)) - with pytest.raises(ValueError, match="128px"): - compose(["presets=dino_language", "env.scene.eye.foveated_res=64"]) - assert cfg.goal_mode == "numbered" + assert describe(cfg, agent)["goal"] == "numbered" @pytest.mark.parametrize("gaze_supervision", ["none", "grasp_gated"]) def test_language_actor_uses_vision_excludes_state_and_round_trips(tmp_path, gaze_supervision): + from isaaclab_tutorial.active_gaze.configuration import compose + from isaaclab_tutorial.active_gaze.language import INSTRUCTIONS from isaaclab_tutorial.active_gaze.learning.config import LanguageVisionActorCfg from isaaclab_tutorial.active_gaze.learning.language import COSMOS_MODEL, COSMOS_REVISION from isaaclab_tutorial.active_gaze.learning.models import LanguageVisionActor - from isaaclab_tutorial.active_gaze.configuration import compose - from isaaclab_tutorial.active_gaze.language import INSTRUCTIONS suffix = ",grasp_gated" if gaze_supervision == "grasp_gated" else ",no_gaze_supervision" cfg = compose([f"presets=dino_language{suffix}"])[1].to_dict() @@ -89,7 +88,7 @@ def test_language_actor_uses_vision_excludes_state_and_round_trips(tmp_path, gaz actor_cfg["instruction_table_path"] = str(table_path) obs = TensorDict( dict( - proprio=torch.randn(4, 32), + proprio=torch.randn(4, 30), vision=torch.randn(4, 8, 16), instruction=torch.zeros(4, 1, dtype=torch.long), critic=torch.randn(4, 72), diff --git a/tests/active_gaze/test_numbered.py b/tests/active_gaze/test_numbered.py index 5c0d725..cecbff1 100644 --- a/tests/active_gaze/test_numbered.py +++ b/tests/active_gaze/test_numbered.py @@ -4,30 +4,37 @@ import torch +from isaaclab_tutorial.assets import RESET_DATASET +from isaaclab_tutorial.tasks.place_vial.reset.dataset import load_reset_dataset + +RACK_POSE = (0.18, 0.08, 0.04, 0, 0, 0, 1) + + +def numbered_reset(target_hole): + """A numbered reset term that only knows each environment's target opening.""" + from isaaclab_tutorial.active_gaze.goals import NumberedResetFromDataset + + reset = object.__new__(NumberedResetFromDataset) + reset.target_hole = target_hole + return reset + + +def with_reset(reset, **attributes): + """A stand-in environment whose event manager holds ``reset`` as its dataset reset.""" + manager = SimpleNamespace(get_term_cfg=lambda name: SimpleNamespace(func=reset)) + return SimpleNamespace(event_manager=manager, **attributes) + def test_numbered_resets_preserve_physics_and_cover_all_goals(): - from isaaclab_fovi.assets.so101_vial import RESET_DATASET from isaaclab_tutorial.active_gaze.goals import expand_numbered_resets from isaaclab_tutorial.tasks.place_vial.mdp.events import phase_balanced_row_weights - from isaaclab_tutorial.active_gaze.reset import load_reset_dataset source = load_reset_dataset(RESET_DATASET)["states"] - states, bins, names, phases = expand_numbered_resets(source, (0.18, 0.08, 0.04, 0, 0, 0, 1)) + states, bins, names, phases = expand_numbered_resets(source, RACK_POSE) for key in ("joint_position", "joint_target", "vial_pose", "phase", "lifted"): torch.testing.assert_close(states[key], source[key].repeat_interleave(4, 0), rtol=0, atol=0) - assert torch.equal(states["target_hole"].reshape(-1, 4), torch.arange(4).expand(1024, -1)) - assert len(names) == 14 - assert set(names) == { - "home", - "pregrasp", - "grasp", - "lift", - *[ - f"{phase}_{kind}" - for phase in ("lift", "reorient", "transport", "insert", "release") - for kind in ("target", "non_target") - ], - } + assert torch.equal(states["target_hole"].reshape(-1, 4), torch.arange(4).expand(len(source["phase"]), -1)) + assert set(names) >= {"home", "pregrasp", "grasp", "insert_target", "insert_non_target", "release_non_target"} assert torch.bincount(bins).min() > 0 assert (states["grasped"][bins == names.index("release_non_target")] == 0).all() # Preserve phase mass and uniform target numbers before SGS adaptation. @@ -63,23 +70,17 @@ def test_fixed_cap_sampling_is_balanced_shuffled_and_conditional(): def test_partial_resets_preserve_cap_and_restore_matching_stock_rows(monkeypatch): - from isaaclab_tutorial.active_gaze.goals import NumberedResetFromDataset, ResetFromDataset + from isaaclab_tutorial.active_gaze.goals import ResetFromDataset numbers = torch.tensor([4, 1, 3, 2]) - env = SimpleNamespace( - num_envs=4, - device="cpu", - vial_number=numbers.clone(), - numbered_target_hole=numbers - 1, - _so101_reset_row=torch.full((4,), -1), - ) - reset = object.__new__(NumberedResetFromDataset) + env = SimpleNamespace(num_envs=4, device="cpu", _so101_reset_row=torch.full((4,), -1)) + reset = numbered_reset(numbers - 1) reset.states = {"target_hole": torch.arange(4).repeat(8)} reset.row_weights = torch.ones(32) reset.sequential_rows = torch.arange(32) reset.cursor = 0 - def restore(self, env, ids, path, phases, sequential, *args): + def restore(self, env, ids, path, phases, sequential, **perturbation): assert sequential env._so101_reset_row[ids] = self.sequential_rows @@ -87,43 +88,38 @@ def restore(self, env, ids, path, phases, sequential, *args): for sequential in (False, True): for _ in range(10): reset(env, torch.tensor([0, 2]), "unused", [], sequential=sequential) - assert torch.equal(env.vial_number, numbers) - assert torch.equal(env.numbered_target_hole, numbers - 1) + assert torch.equal(reset.target_hole, numbers - 1) assert env._so101_reset_row[[1, 3]].tolist() == [-1, -1] assert torch.equal(env._so101_reset_row[[0, 2]] % 4, numbers[[0, 2]] - 1) -def test_numbered_configuration_keeps_target_in_critic_only(): +def test_numbered_configuration_keeps_the_target_in_the_critic_only(): + from isaaclab_fovi.sensors.calibrated_geometry import sampling_geometry + from isaaclab.sim import MultiAssetSpawnerCfg - from isaaclab_tasks.utils import resolve_presets - from isaaclab_tutorial.active_gaze.env_cfg import SO101NumberedEnvCfg - from isaaclab_tutorial.active_gaze.configuration import compose + from isaaclab_tutorial.active_gaze.configuration import compose, describe - plain = compose(["presets=nearest", "renderer=newton_renderer"])[0] - numbered = resolve_presets(SO101NumberedEnvCfg()) - assert plain.renderer_backend() == "warp" - assert numbered.renderer_backend() == "ovrtx" + plain, plain_agent, _ = compose(["presets=nearest,newton_renderer"]) + numbered, numbered_agent, _ = compose(["presets=numbered,newton_renderer"]) + assert ( + describe(plain, plain_agent)["goal"] == "nearest" and describe(numbered, numbered_agent)["goal"] == "numbered" + ) + # The numbered scene's camera sits closer and narrower, so the labels stay legible. assert numbered.scene.eye.offset.pos[0] < plain.scene.eye.offset.pos[0] - assert numbered.camera_hfov() < plain.camera_hfov() - assert numbered.observations.scene_rgb.to_dict() == plain.observations.scene_rgb.to_dict() - assert numbered.observations.proprioception.to_dict() == plain.observations.proprioception.to_dict() - assert numbered.observations.gaze.to_dict() == plain.observations.gaze.to_dict() + assert sampling_geometry(numbered.scene.eye)[0] < sampling_geometry(plain.scene.eye)[0] + for group in ("scene_rgb", "proprioception", "gaze"): + assert getattr(numbered.observations, group).to_dict() == getattr(plain.observations, group).to_dict() + assert ( + numbered_agent.obs_groups["actor"] == plain_agent.obs_groups["actor"] == ["scene_rgb", "proprioception", "gaze"] + ) assert not hasattr(plain.observations.critic, "numbered_goal") assert numbered.observations.critic.numbered_goal is not None assert isinstance(numbered.scene.vial.spawn, MultiAssetSpawnerCfg) - assert [v.vial_number for v in numbered.scene.vial.spawn.assets_cfg] == [1, 2, 3, 4] - assert not hasattr(numbered.scene, "vial_number") - for mode in ("none", "grasp_gated"): - assert compose(["presets=nearest" + (",grasp_gated" if mode == "grasp_gated" else "")])[1].to_dict()[ - "obs_groups" - ]["actor"] == ["scene_rgb", "proprioception", "gaze"] - warp, _, _ = compose(["presets=dino_language", "renderer=newton_renderer"]) - assert warp.goal_mode == "numbered" - assert warp.scene.eye.data_types == ["rgb"] - assert warp.observations.vision.tokens.params["data_type"] == "rgb" - assert warp.scene.eye.render_settings == {} - assert warp.render_mode() == "rgb" + assert [vial.vial_number for vial in numbered.scene.vial.spawn.assets_cfg] == [1, 2, 3, 4] + language = compose(["presets=dino_language,newton_renderer"])[0] + assert language.scene.eye.data_types == ["rgb"] + assert language.observations.vision.tokens.params["data_type"] == "rgb" def test_wrong_hole_never_pays_insert_or_success(monkeypatch): @@ -157,12 +153,12 @@ def coordinates(_): class Scene(dict): sensors = {} - env = SimpleNamespace( + env = with_reset( + numbered_reset(torch.tensor([0, 0, 2, 1])), num_envs=4, device="cpu", scene=Scene(vial=vial), extras={}, - numbered_target_hole=torch.tensor([0, 0, 2, 1]), episode_length_buf=torch.ones(4, dtype=torch.long), step_dt=1 / 30, ) @@ -181,54 +177,24 @@ class Scene(dict): assert result.tolist() == [True, True, True, False] -def test_gaze_cache_tracks_selected_target_and_cap(): - from fovi.sensing.projection import CameraModel - from isaaclab_tasks.utils import resolve_presets - - from isaaclab_tutorial.active_gaze.env_cfg import SO101NumberedEnvCfg - from isaaclab_tutorial.active_gaze.gaze import angles_to_direction, build_reset_cache - - cfg = resolve_presets(SO101NumberedEnvCfg()) - rack = cfg.scene.rack.init_state - cache = build_reset_cache( - cfg.events.reset_from_dataset.params["dataset_path"], - cfg.scene.eye, - (*rack.pos, *rack.rot), - cfg.actions.gaze.angle_limit, - numbered=True, - ) - gaze = cache["vision_action"] - assert gaze.shape == (4096, 5, 16, 2) - assert CameraModel(**cfg.scene.eye.camera_calibration).project(angles_to_direction(gaze))[1].all() - # A single physical reset has four distinct exact goal fixations, one per opening. - assert torch.unique(gaze[:4, 2, 0], dim=0).shape[0] == 4 - assert torch.unique(gaze[:4, 1, 0], dim=0).shape[0] == 1 - - def test_numbered_sgs_tracks_and_restores_each_reset_category(): from isaaclab.managers import CurriculumTermCfg - from isaaclab_fovi.assets.so101_vial import RESET_DATASET from isaaclab_tutorial.active_gaze.goals import expand_numbered_resets - from isaaclab_tutorial.tasks.place_vial.mdp.events import phase_balanced_row_weights - from isaaclab_tutorial.active_gaze.reset import load_reset_dataset from isaaclab_tutorial.active_gaze.sampling import ResetSampling, iteration_metrics + from isaaclab_tutorial.tasks.place_vial.mdp.events import phase_balanced_row_weights source = load_reset_dataset(RESET_DATASET)["states"] def make_sampler(): - states, bins, names, _ = expand_numbered_resets(source, (0.18, 0.08, 0.04, 0, 0, 0, 1)) + states, bins, names, _ = expand_numbered_resets(source, RACK_POSE) reset = SimpleNamespace( states=states, bin_ids=bins, bin_names=names, row_weights=phase_balanced_row_weights(states["phase"], [1.0] * 8), ) - env = SimpleNamespace( - device="cpu", - num_envs=4, - event_manager=SimpleNamespace(get_term_cfg=lambda _: SimpleNamespace(func=reset)), - ) + env = with_reset(reset, device="cpu", num_envs=4) return ResetSampling(CurriculumTermCfg(func=ResetSampling, params={"mode": "sgs"}), env) sampler = make_sampler() diff --git a/tests/active_gaze/test_presets.py b/tests/active_gaze/test_presets.py index 3158745..a67c177 100644 --- a/tests/active_gaze/test_presets.py +++ b/tests/active_gaze/test_presets.py @@ -1,20 +1,27 @@ -"""Native registry composition, default recipe, and checkpoint configuration.""" +"""Registry composition, the default variant, and resuming a run from its saved description.""" from copy import deepcopy import pytest +from isaaclab_tutorial.active_gaze.configuration import compose, describe, resume_overrides -def test_default_recipe_matches_explicit_presets_and_native_registry(): + +def saved_run(overrides): + """What train.py saves in run.json for a run composed from ``overrides``.""" + env, agent, recipe = compose(overrides) + return env, agent, dict(describe(env, agent), overrides=resume_overrides(recipe, agent)) + + +def test_default_variant_is_numbered_with_gaze_supervision_and_reset_sampling(): from isaaclab_tasks.utils import resolve_task_config from isaaclab_tutorial.active_gaze import TASK_ID - from isaaclab_tutorial.active_gaze.env_cfg import SO101NumberedEnvCfg - from isaaclab_tutorial.active_gaze.configuration import compose + from isaaclab_tutorial.active_gaze.env_cfg import NumberedEnvCfg env, agent = resolve_task_config(TASK_ID, "rsl_rl_cfg_entry_point", overrides=[]) - explicit, explicit_agent, _ = compose(["presets=numbered,grasp_gated,sgs,minimal_full_mdl_shadows"]) - assert isinstance(env, SO101NumberedEnvCfg) + explicit, explicit_agent, _ = compose(["presets=numbered"]) + assert isinstance(env, NumberedEnvCfg) assert env.to_dict() == explicit.to_dict() assert agent.to_dict() == explicit_agent.to_dict() assert env.observations.oracle is not None @@ -22,73 +29,49 @@ def test_default_recipe_matches_explicit_presets_and_native_registry(): assert agent.algorithm.class_name.endswith(":OraclePPO") assert agent.algorithm.oracle_weight == 1.0 assert env.curriculum.reset_sampling.params["mode"] == "sgs" - assert env.scene.eye.data_types == ["simple_shading_full_mdl"] - assert env.scene.eye.renderer_cfg.enable_shadows - - -def test_native_scalar_overrides_and_resume_preserve_typed_variants(): - from isaaclab_tutorial.active_gaze.agents import Sim2RealPPORunnerCfg - from isaaclab_tutorial.active_gaze.env_cfg import SO101Sim2RealEnvCfg - from isaaclab_tutorial.active_gaze.configuration import checkpoint_configuration, compose, metadata - from isaaclab_tutorial.active_gaze.transfer_options import CameraRandomizationCfg - - env, agent, recipe = compose( - [ - "presets=sim2real,finetune", - "env.scene.eye.cmf_a=0.0075", - "env.sim2real.rotation_deg=4.0", - "agent.algorithm.oracle_weight=2.5", - ] + + +def test_resume_replays_saved_overrides_and_lets_new_values_replace_them(): + env, agent, saved = saved_run( + ["presets=numbered,sim2real,finetune", "env.scene.eye.cmf_a_deg=1.0", "agent.algorithm.oracle_weight=2.5"] ) - saved = dict(metadata(env, agent), configuration=checkpoint_configuration(recipe, agent)) before = deepcopy(saved) restored, restored_agent, _ = compose(saved=saved) - assert isinstance(restored, SO101Sim2RealEnvCfg) - assert isinstance(restored_agent, Sim2RealPPORunnerCfg) - assert isinstance(restored.sim2real, CameraRandomizationCfg) assert restored.to_dict() == env.to_dict() - assert not restored_agent.finetune - assert restored_agent.algorithm.learning_rate == 3e-5 - expected_agent = agent.replace(finetune=False) - assert restored_agent.to_dict() == expected_agent.to_dict() - changed, changed_agent, _ = compose(["env.sim2real.rotation_deg=2.0", "agent.algorithm.oracle_weight=0.5"], saved) - assert changed.sim2real.rotation_deg == 2.0 - assert changed.scene.eye.cmf_a == 0.0075 + # Fine-tuning happens once; the resumed run keeps its learning rate. + assert not restored_agent.finetune and restored_agent.algorithm.learning_rate == 3e-5 + assert restored_agent.to_dict() == agent.replace(finetune=False).to_dict() + changed, changed_agent, _ = compose(["agent.algorithm.oracle_weight=0.5"], saved) + assert changed.scene.eye.cmf_a_deg == 1.0 assert changed_agent.algorithm.oracle_weight == 0.5 assert saved == before - with pytest.raises(ValueError, match="policy architecture"): - compose(["presets=numbered"], dict(configuration=[], policy={"name": "dino_language"})) - -def test_checkpoint_requires_native_recipe_and_preserves_explicit_opt_outs(): - from isaaclab_tutorial.active_gaze.configuration import compose, metadata - explicit, agent, recipe = compose(["presets=nearest,no_gaze_supervision,uniform", "renderer=newton_renderer"]) - restored, restored_agent, _ = compose(saved=dict(metadata(explicit, agent), configuration=recipe)) +def test_resume_preserves_explicit_opt_outs(): + explicit, agent, saved = saved_run(["presets=nearest,no_gaze_supervision,uniform,newton_renderer"]) + restored, restored_agent, _ = compose(saved=saved) assert explicit.to_dict() == restored.to_dict() assert agent.to_dict() == restored_agent.to_dict() assert explicit.observations.oracle is None assert explicit.scene.eye.data_types == ["rgb"] assert explicit.curriculum.reset_sampling.params["mode"] == "uniform" - assert agent.algorithm.class_name == "PPO" - with pytest.raises(ValueError, match="native configuration recipe"): - compose(saved={"goal_mode": "nearest"}) + assert agent.algorithm.oracle_weight == 0.0 -def test_chunked_checkpoint_restores_recipe_and_rejects_incompatible_action_heads(): +def test_resume_rejects_a_different_policy_action_chunk_or_dino_exit_layer(): from isaaclab_tasks.utils.hydra import PresetTarget, enumerate_task_presets from isaaclab_tutorial.active_gaze import TASK_ID - from isaaclab_tutorial.active_gaze.configuration import compose, metadata assert "chunking" in enumerate_task_presets(TASK_ID)[PresetTarget.DOMAIN] - env, agent, recipe = compose(["presets=chunking,no_gaze_supervision"]) - saved = dict(metadata(env, agent), configuration=recipe) + env, agent, saved = saved_run(["presets=chunking,no_gaze_supervision"]) restored, restored_agent, _ = compose(saved=saved) - assert restored.to_dict() == env.to_dict() assert restored_agent.to_dict() == agent.to_dict() - assert agent.algorithm.action_chunk_size == 3 - assert agent.algorithm.oracle_weight == 0.0 - assert agent.algorithm.class_name.endswith(":OraclePPO") - with pytest.raises(ValueError, match="chunk size"): + assert agent.algorithm.action_chunk_size == 3 and agent.algorithm.oracle_weight == 0.0 + with pytest.raises(ValueError, match="action_chunk_size"): compose(["agent.algorithm.action_chunk_size=2"], saved) + with pytest.raises(ValueError, match="policy"): + compose(["presets=dino_language"], saved) + _, _, language = saved_run(["presets=dino_language"]) + with pytest.raises(ValueError, match="exit layer"): + compose(["env.observations.vision.tokens.params.num_layers=6"], language) diff --git a/tests/active_gaze/test_rendering.py b/tests/active_gaze/test_rendering.py index ea167d4..8cb08eb 100644 --- a/tests/active_gaze/test_rendering.py +++ b/tests/active_gaze/test_rendering.py @@ -17,30 +17,30 @@ @pytest.mark.parametrize("mode, output, shadows", MODES) @pytest.mark.parametrize("policy", ["cnn", "dino_language"]) def test_mode_reaches_policy_and_diagnostic_cameras(mode, output, shadows, policy): - from isaaclab_tutorial.active_gaze.env_cfg import SceneRGB from isaaclab_tutorial.active_gaze.configuration import compose + from isaaclab_tutorial.active_gaze.env_cfg import SceneRGB + from isaaclab_tutorial.active_gaze.train import add_diagnostic_camera variant = "dino_language" if policy == "dino_language" else "numbered" baseline, _, _ = compose([f"presets={variant}"]) cfg, _, _ = compose([f"presets={variant},{mode}"]) - cfg.enable_diagnostics() - assert cfg.render_mode() == mode + add_diagnostic_camera(cfg) assert cfg.scene.eye.data_types == cfg.scene.diagnostic_camera.data_types == [output] assert cfg.scene.eye.renderer_cfg.enable_shadows is shadows assert cfg.scene.diagnostic_camera.renderer_cfg.enable_shadows is shadows assert cfg.sim.physics.to_dict() == baseline.sim.physics.to_dict() - assert cfg.scene.eye.camera_calibration == baseline.scene.eye.camera_calibration - assert cfg.scene.eye.cmf_a == baseline.scene.eye.cmf_a + assert cfg.scene.eye.spawn.to_dict() == baseline.scene.eye.spawn.to_dict() + assert cfg.scene.eye.cmf_a_deg == baseline.scene.eye.cmf_a_deg image = torch.full((2, cfg.scene.eye.foveated_res, cfg.scene.eye.foveated_res, 3), 127, dtype=torch.uint8) - camera = SimpleNamespace(cfg=cfg.scene.eye, data=SimpleNamespace(output={output: image})) - env = SimpleNamespace(scene={"eye": camera}) - actual = SceneRGB(SimpleNamespace(), env)(env) + camera = SimpleNamespace(cfg=cfg.scene.eye, data=SimpleNamespace(output={output: SimpleNamespace(torch=image)})) + env = SimpleNamespace(scene={"eye": camera}, num_envs=2, device="cpu") + actual = SceneRGB(SimpleNamespace(params={}), env)(env) torch.testing.assert_close(actual, image.float().permute(0, 3, 1, 2) / 255) if policy == "dino_language": assert cfg.observations.vision.tokens.params["data_type"] == output -def test_dino_consumes_selected_minimal_output_without_changing_encoder_arguments(monkeypatch): +def test_dino_consumes_the_selected_output_and_receives_only_encoder_arguments(monkeypatch): from isaaclab_tutorial.active_gaze.learning import observations image = torch.full((2, 128, 128, 3), 127, dtype=torch.uint8) @@ -62,11 +62,12 @@ def __call__(self, value): monkeypatch.setattr(observations, "FrozenDino", Encoder) output = "simple_shading_full_mdl" - cfg = SimpleNamespace(params=dict(reference="local", checksum=None, batch_size=8, data_type=output)) - env = SimpleNamespace(device="cpu", scene={"eye": SimpleNamespace(data=SimpleNamespace(output={output: image}))}) - term = observations.DinoTokens(cfg, env) - assert "data_type" not in received - assert term(env, **cfg.params) is image + params = dict(reference="local", checksum=None, batch_size=8, num_layers=6, data_type=output, photometric=None) + eye = SimpleNamespace(data=SimpleNamespace(output={output: SimpleNamespace(torch=image)})) + env = SimpleNamespace(device="cpu", num_envs=2, scene={"eye": eye}) + term = observations.DinoTokens(SimpleNamespace(params=params), env) + assert received == dict(reference="local", checksum=None, batch_size=8, num_layers=6) + assert term(env, **params) is image def test_minimal_requires_ovrtx(): @@ -78,10 +79,11 @@ def test_minimal_requires_ovrtx(): @pytest.mark.parametrize("mode, output, shadows", [MODES[0], MODES[-1]]) def test_numbered_products_request_denoising_without_aa(mode, output, shadows): + from pxr import Usd + from isaaclab.renderers import CameraRenderSpec from isaaclab_ov.renderers.ovrtx_renderer import OVRTXCameraRenderData from isaaclab_ov.renderers.ovrtx_usd import build_render_product_as_string - from pxr import Usd from isaaclab_tutorial.active_gaze.configuration import compose @@ -107,11 +109,11 @@ def test_numbered_products_request_denoising_without_aa(mode, output, shadows): assert samples.Get() == 4 -@pytest.mark.parametrize("kind", ["cnn", "dino", "randomized_dino"]) +@pytest.mark.parametrize("kind", ["cnn", "dino", "varied_dino"]) def test_visual_observations_refresh_only_at_policy_boundaries(monkeypatch, kind): - from isaaclab_tutorial.active_gaze.learning import observations from isaaclab_tutorial.active_gaze.env_cfg import SceneRGB - from isaaclab_tutorial.active_gaze.sim2real import RandomizedDinoTokens + from isaaclab_tutorial.active_gaze.learning import observations + from isaaclab_tutorial.active_gaze.sim2real import PHOTOMETRIC_RANGES reads = [] encodes = [] @@ -123,7 +125,7 @@ class Camera: @property def data(self): reads.append(True) - return SimpleNamespace(output={"rgb": image}) + return SimpleNamespace(output={"rgb": SimpleNamespace(torch=image)}) class Encoder: def __init__(self, **kwargs): @@ -140,14 +142,11 @@ def __call__(self, image): return image.float().mean(dim=(1, 2)) monkeypatch.setattr(observations, "FrozenDino", Encoder) - env = SimpleNamespace( - device="cpu", - scene={"eye": Camera()}, - refresh_policy_vision=False, - so101_camera_randomization=SimpleNamespace(image=lambda value: value), - ) + env = SimpleNamespace(device="cpu", num_envs=2, scene={"eye": Camera()}, refresh_policy_vision=False) params = {} if kind == "cnn" else dict(reference="local", checksum=None, batch_size=2) - term_type = {"cnn": SceneRGB, "dino": observations.DinoTokens, "randomized_dino": RandomizedDinoTokens}[kind] + if kind == "varied_dino": + params["photometric"] = PHOTOMETRIC_RANGES + term_type = SceneRGB if kind == "cnn" else observations.DinoTokens term = term_type(SimpleNamespace(params=params), env) first = term(env, **params).clone() # Empty cache must populate even during a chunk. image.fill_(255) diff --git a/tests/active_gaze/test_sampling.py b/tests/active_gaze/test_sampling.py index df2fd04..019881e 100644 --- a/tests/active_gaze/test_sampling.py +++ b/tests/active_gaze/test_sampling.py @@ -151,15 +151,15 @@ def test_uniform_sampling_only_tracks_and_metrics_weight_episodes(): def test_saved_settings_and_canonical_evaluation(): - from isaaclab_tutorial.active_gaze.configuration import compose + from isaaclab_tutorial.active_gaze.configuration import compose, describe - saved = dict(configuration=["presets=sgs"]) - cfg, _, _ = compose(saved=saved) + cfg, agent, _ = compose(["presets=sgs"]) assert cfg.curriculum.reset_sampling.params["mode"] == "sgs" + saved = dict(describe(cfg, agent), overrides=["presets=sgs"]) uniform, _, _ = compose(["env.curriculum.reset_sampling.params.mode=uniform"], saved) assert uniform.curriculum.reset_sampling.params["mode"] == "uniform" + # Playback starts from home and does not adapt the reset distribution. cfg.play_mode() assert cfg.curriculum.reset_sampling.params["mode"] == "uniform" - assert cfg.reset_sampling_evaluation assert cfg.events.reset_from_dataset.params["phase_weights"] == (1, 0, 0, 0, 0, 0, 0, 0) assert len(PHASE_NAMES) == 8 diff --git a/tests/active_gaze/test_sim2real.py b/tests/active_gaze/test_sim2real.py index 85fa63b..3493238 100644 --- a/tests/active_gaze/test_sim2real.py +++ b/tests/active_gaze/test_sim2real.py @@ -1,4 +1,4 @@ -"""Transfer preserves learned state and keeps camera supervision out of actions.""" +"""Robot-transfer randomization keeps the task, the controls and the actor's inputs; extrinsics labels stay out.""" from copy import deepcopy from types import SimpleNamespace @@ -7,52 +7,10 @@ import torch from tensordict import TensorDict -from isaaclab_fovi.deployment.so101.planar import PlanarRetina, gaze_basis, project_gaze_rays from isaaclab_tutorial.active_gaze.camera_geometry import pose_loss, pose_targets from isaaclab_tutorial.active_gaze.configuration import compose -def test_planar_coordinates_do_not_require_physical_intrinsics(): - retina = PlanarRetina(resolution=16) - gaze = torch.tensor([[0.0, 0.0], [0.2, -0.3]]) - pixels, valid = retina.pixels(gaze) - center_rays = torch.tensor([[0.0, 0.0, 1.0]]) - center, _ = project_gaze_rays(center_rays, gaze, retina.focal_pixels, retina.center_pixels, 640) - torch.testing.assert_close(retina.angles(center[:, 0]), gaze) - # Reproduce the actual renderer's shared canonical LUT and upright permutation. - from isaaclab_fovi.sensors.native_grid import native_grid_directions - from isaaclab_fovi.sensors.pooling import build_lowres_coords - - cfg = compose(["presets=sim2real", "env.scene.eye.cmf_a=0.0075"])[0] - cfg.scene.eye.foveated_res = 16 - coords, _ = build_lowres_coords(cfg.scene.eye, device="cpu") - rays = native_grid_directions(coords, tangent_scale=320 / retina.focal) - rays *= torch.tensor((1, -1, -1)) - torch.testing.assert_close(coords.as_grid(rays, sample_dim=0).reshape(-1, 3), retina.rays) - expected, visible = project_gaze_rays(rays, gaze, retina.focal_pixels, retina.center_pixels, 640) - torch.testing.assert_close(coords.as_grid(expected, sample_dim=1), pixels) - assert torch.equal(coords.as_grid(visible & coords.valid_mask, sample_dim=1)[..., None], valid) - image = torch.arange(640).view(1, 1, 640, 1).expand(2, 640, 640, 3).remainder(256).byte() - output = retina(image, gaze) - assert output.shape == (2, 16, 16, 3) and output.dtype == torch.uint8 - assert (output[~valid.expand_as(output)] == 0).all() - - -@pytest.mark.gpu -@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA sampler export") -def test_planar_export_keeps_uint8_rounding_after_cuda_mapping(tmp_path): - model = PlanarRetina(resolution=128).cuda().eval() - rgb = torch.randint(0, 256, (1, 640, 640, 3), device="cuda", dtype=torch.uint8) - gaze = torch.zeros(1, 2, device="cuda") - with torch.inference_mode(), torch.jit.optimized_execution(False): - path = tmp_path / "retina.pt" - torch.jit.trace(model, (rgb, gaze), check_trace=False).save(str(path)) - restored = torch.jit.load(str(path), map_location="cuda").to("cuda").eval() - for angles in ((0.0, 0.0), (0.2, -0.3), (-0.6, 0.5)): - gaze[:] = torch.tensor(angles, device="cuda") - assert torch.equal(restored(rgb, gaze), model(rgb, gaze)) - - def test_pose_metrics_remain_accurate_under_mixed_precision(): from isaaclab.utils.math import matrix_from_quat, quat_from_euler_xyz @@ -66,88 +24,101 @@ def test_pose_metrics_remain_accurate_under_mixed_precision(): assert metrics["extrinsics_rotation_deg"].item() == pytest.approx(1, abs=1e-3) -def test_transfer_presets_inherit_without_mutating_saved_metadata(): - from isaaclab_tutorial.active_gaze.transfer_options import CameraRandomizationCfg +def test_sim2real_adds_camera_randomization_and_extrinsics_labels_but_keeps_the_eye_and_actor_inputs(): + # The tutorial's own sim2real preset also retunes arm action scales and rewards; this covers what active gaze adds. + base, base_agent, _ = compose(["presets=dino_language"]) + varied, varied_agent, _ = compose(["presets=dino_language,sim2real"]) + assert base.actions.gaze.to_dict() == varied.actions.gaze.to_dict() + assert base.scene.eye.to_dict() == varied.scene.eye.to_dict() + assert base.observations.critic.to_dict() == varied.observations.critic.to_dict() + assert base.observations.proprio.to_dict() == varied.observations.proprio.to_dict() + assert base.observations.extrinsics is None and varied.observations.extrinsics is not None + assert varied.events.reset_from_dataset.func is base.events.reset_from_dataset.func + assert "camera_mount" not in vars(base.events) and "camera_mount" in vars(varied.events) + assert base.observations.vision.tokens.params["photometric"] is None + assert varied.observations.vision.tokens.params["photometric"] + assert not hasattr(base_agent.algorithm, "extrinsics_weight") and not base_agent.actor.extrinsics_head + assert varied_agent.algorithm.extrinsics_weight == 0.05 and varied_agent.actor.extrinsics_head + - saved = dict(configuration=["presets=sim2real", "env.sim2real.rotation_deg=3.0"], policy={"name": "dino_language"}) +def test_resumed_fine_tune_keeps_the_saved_overrides_without_mutating_them(): + saved = dict(overrides=["presets=dino_language,sim2real"], policy="dino_language", action_chunk_size=1) before = deepcopy(saved) - env, agent, _ = compose(["presets=sim2real,finetune", "env.sim2real.rotation_deg=7.0"], saved) - assert isinstance(env.sim2real, CameraRandomizationCfg) - assert env.sim2real.rotation_deg == 7 - assert agent.algorithm.extrinsics_weight == 0.05 + env, agent, recipe = compose(["presets=dino_language,sim2real,finetune"], saved) + assert "camera_mount" in vars(env.events) assert agent.finetune and agent.algorithm.learning_rate == 3e-5 + assert recipe == ["presets=dino_language,sim2real,finetune"] assert saved == before - with pytest.raises(ValueError, match="nominal sampling fraction"): - compose(["presets=sim2real", "env.sim2real.nominal_fraction=2.0"]) - - -def test_randomizations_preserve_numbered_reset_and_control_contract(): - base = compose(["presets=dino_language"])[0] - varied = compose(["presets=sim2real"])[0] - assert base.actions.to_dict() == varied.actions.to_dict() - assert base.scene.robot.init_state.to_dict() == varied.scene.robot.init_state.to_dict() - assert base.scene.robot.spawn.shoulder_response == varied.scene.robot.spawn.shoulder_response - assert base.scene.robot.spawn.elbow_response == varied.scene.robot.spawn.elbow_response - assert base.rewards.to_dict() == varied.rewards.to_dict() - assert base.episode_length_s == varied.episode_length_s - assert base.observations.critic.to_dict() == varied.observations.critic.to_dict() - assert varied.observations.proprio.to_dict() == base.observations.proprio.to_dict() - assert base.observations.extrinsics is None and varied.observations.extrinsics is not None - assert varied.scene.eye.field_geometry == "planar" and base.scene.eye.field_geometry == "spherical" - from isaaclab_fovi.sensors.foveated_rtx_tiled_camera import FoveatedRTXTiledCamera - - assert issubclass(varied.scene.eye.class_type, FoveatedRTXTiledCamera) - assert varied.scene.eye.spawn.horizontal_aperture == base.scene.eye.spawn.horizontal_aperture - assert varied.scene.diagnostic_camera is None # Training allocates no dense camera. - assert varied.events.reset_from_dataset.func == base.events.reset_from_dataset.func - for key in ("dataset_path", "phase_weights", "sequential"): - assert varied.events.reset_from_dataset.params.get(key) == base.events.reset_from_dataset.params.get(key) - assert varied.scene.support is not None and varied.events.to_dict().get("camera_mount") is None - assert all(asset.randomize_diameters for asset in varied.scene.vial.spawn.assets_cfg) -def test_partial_camera_reset_preserves_other_scenes_and_ignores_grid_origin(): - from isaaclab_tutorial.active_gaze.sim2real import CameraRandomization +def make_mount_randomization(num_envs=3): + from isaaclab_tutorial.active_gaze.sim2real import randomize_camera_mount - cfg = compose(["presets=sim2real", "env.sim2real.nominal_fraction=0.0", "env.sim2real.ramp_steps=0"])[0] - camera = SimpleNamespace(cfg=cfg.scene.eye, reset=lambda **kwargs: None) + eye = compose(["presets=numbered,sim2real"])[0].scene.eye + camera = SimpleNamespace(cfg=eye) - def set_pose(position, rotation, env_ids): + def set_world_poses(position, rotation, env_ids, convention): + assert convention == "opengl" camera.world = position.clone() - camera.set_physical_poses = set_pose + camera.set_world_poses = set_world_poses class Scene(dict): - env_origins = torch.tensor([[3.0, 4.0, 0.0], [-5.0, 7.0, 0.0], [9.0, 2.0, 0.0]]) - sensors = {"eye": camera} + env_origins = torch.tensor([[3.0, 4.0, 0.0], [-5.0, 7.0, 0.0], [9.0, 2.0, 0.0]])[:num_envs] - scene = Scene( - eye=camera, - robot=SimpleNamespace( - data=SimpleNamespace(root_quat_w=SimpleNamespace(torch=torch.tensor([[0.0, 0.0, 0.0, 1.0]]).expand(3, -1))) - ), - ) - env = SimpleNamespace(scene=scene, cfg=cfg, device="cpu", num_envs=3, common_step_counter=0, extras={}) - state = CameraRandomization(None, env) + identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]]).expand(num_envs, -1) + robot = SimpleNamespace(data=SimpleNamespace(root_quat_w=SimpleNamespace(torch=identity))) + scene = Scene(eye=camera, robot=robot) + env = SimpleNamespace(scene=scene, device="cpu", num_envs=num_envs, common_step_counter=0, extras={}) + term = randomize_camera_mount(SimpleNamespace(params=dict(camera_name="eye")), env) + return term, env, camera + + +def test_partial_mount_reset_preserves_other_scenes_and_ignores_the_grid_origin(): + term, env, camera = make_mount_randomization() + params = dict(nominal_fraction=0.0, ramp_steps=0) torch.manual_seed(7) - state(env, None) - assert torch.equal(state.intrinsics, state.nominal_intrinsics) - assert not state.radial.any() - torch.testing.assert_close(camera.world, state.position + scene.env_origins) - before = { - name: getattr(state, name).clone() - for name in ("position", "rotation", "intrinsics", "radial", "targets", "photo") - } + term(env, None, **params) + assert not torch.equal(term.position, term.nominal_position) + torch.testing.assert_close(camera.world, term.position + env.scene.env_origins) + before = {name: getattr(term, name).clone() for name in ("position", "rotation", "labels")} torch.manual_seed(91) - state(env, torch.tensor([1])) - expected_target = state.targets[1].clone() + term(env, torch.tensor([1]), **params) + labels = term.labels[1].clone() for name, value in before.items(): - assert torch.equal(getattr(state, name)[[0, 2]], value[[0, 2]]) - scene.env_origins += 1000 + assert torch.equal(getattr(term, name)[[0, 2]], value[[0, 2]]) + env.scene.env_origins += 1000 torch.manual_seed(91) - state(env, torch.tensor([1])) - torch.testing.assert_close(expected_target, state.targets[1]) - torch.testing.assert_close(camera.world, state.position[1:2] + scene.env_origins[1:2]) + term(env, torch.tensor([1]), **params) + torch.testing.assert_close(term.labels[1], labels) + torch.testing.assert_close(camera.world, term.position[1:2] + env.scene.env_origins[1:2]) + + +def test_mount_moves_ramp_up_and_nominal_episodes_keep_the_mount(): + term, env, _ = make_mount_randomization() + env.common_step_counter = 0 + assert term.strength(ramp_steps=1000) == pytest.approx(0.1) + env.common_step_counter = 2000 + assert term.strength(ramp_steps=1000) == 1.0 + term(env, None, nominal_fraction=1.0, ramp_steps=0) + assert torch.equal(term.position, term.nominal_position) + assert not term.labels.any() + + +def test_photometric_variation_keeps_unseen_samples_black_and_resets_per_environment(): + from isaaclab_tutorial.active_gaze.sim2real import PHOTOMETRIC_RANGES, PhotometricVariation + + torch.manual_seed(3) + variation = PhotometricVariation(2, "cpu", PHOTOMETRIC_RANGES) + images = torch.randint(1, 256, (2, 8, 8, 3), dtype=torch.uint8) + images[:, :2] = 0 + varied = variation(images) + assert varied.dtype == torch.uint8 and varied.shape == images.shape + assert not varied[:, :2].any() + first = {name: value[0].clone() for name, value in variation.values.items()} + variation.reset(torch.tensor([1])) + for name, value in variation.values.items(): + assert torch.equal(value[0], first[name]) def make_actor(tmp_path, head): @@ -172,7 +143,7 @@ def make_actor(tmp_path, head): ) obs = TensorDict( dict( - proprio=torch.randn(4, 32), + proprio=torch.randn(4, 30), vision=torch.randn(4, 4, 8), instruction=torch.zeros(4, 1, dtype=torch.long), critic=torch.randn(4, 72), @@ -265,55 +236,3 @@ def test_finetune_permits_only_new_head_and_preserves_normalization(tmp_path): torch.save(checkpoint, path) with pytest.raises(ValueError, match="Unexpected missing"): ResetSamplingRunner.finetune(runner, path) - - -def test_planar_virtual_gaze_preserves_physical_camera_and_partial_resets(monkeypatch): - from isaaclab.sensors import Camera - from isaaclab.utils.math import matrix_from_quat - - from isaaclab_tutorial.active_gaze.sim2real import PlanarSceneCamera - - monkeypatch.setattr(PlanarSceneCamera, "__del__", lambda self: None) - camera = object.__new__(PlanarSceneCamera) - camera.physical_position = torch.randn(3, 3) - camera.physical_rotation = torch.tensor([[0.0, 0.0, 0.0, 1.0]]).expand(3, -1).clone() - camera.gaze = torch.tensor([[0.2, -0.3], [-0.4, 0.5], [0.6, -0.1]]) - captured = {} - - def capture(self, position, rotation, env_ids, convention): - assert convention == "opengl" - captured.update(position=position.clone(), rotation=rotation.clone(), ids=env_ids) - - monkeypatch.setattr(Camera, "set_world_poses", capture) - camera.set_calibrated_angles(camera.gaze) - torch.testing.assert_close(captured["position"], camera.physical_position) - basis = torch.tensor((1, -1, -1)) - expected = gaze_basis(camera.gaze) * basis[None, :, None] * basis[None, None, :] - torch.testing.assert_close(matrix_from_quat(captured["rotation"]), expected) - before = camera.physical_position.clone() - gaze = camera.gaze.clone() - camera.set_physical_poses(torch.zeros(1, 3), torch.tensor([[0.0, 0.0, 0.0, 1.0]]), torch.tensor([1])) - torch.testing.assert_close(camera.physical_position[[0, 2]], before[[0, 2]]) - torch.testing.assert_close(camera.gaze, gaze) - assert captured["position"].shape == (1, 3) - - -@pytest.mark.gpu -@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA direct-render visibility") -def test_direct_visibility_matches_export_without_broadcast_allocation(): - from isaaclab_fovi.deployment.so101.planar import project_pinhole_rays - from isaaclab_fovi.sensors.calibrated_geometry import rotate_camera_rays - - retina = PlanarRetina().cuda() - gaze = torch.tensor([[0.0, 0.0], [0.2, -0.3], [-0.6, 0.5]], device="cuda") - expected_pixels, expected_valid = project_gaze_rays( - retina.rays, gaze, retina.focal_pixels, retina.center_pixels, 640 - ) - pixels, valid = project_pinhole_rays( - rotate_camera_rays(retina.rays, gaze_basis(gaze)), - retina.focal_pixels, - retina.center_pixels, - 640, - ) - assert torch.equal(valid, expected_valid) - torch.testing.assert_close(pixels[valid], expected_pixels[valid], atol=1e-3, rtol=1e-5) diff --git a/tests/active_gaze/test_vial.py b/tests/active_gaze/test_vial.py index 90f5fd4..ab65ef5 100644 --- a/tests/active_gaze/test_vial.py +++ b/tests/active_gaze/test_vial.py @@ -1,11 +1,31 @@ -"""Contracts for direct visual PPO, without launching physics.""" +"""Contracts of the visual actor, the scene camera, the gaze action and its teacher, without launching physics.""" +import math from types import SimpleNamespace import pytest import torch from tensordict import TensorDict +from isaaclab_tutorial.active_gaze.configuration import compose + + +def gaze_term(field_of_view_deg=78.0, gaze=None): + """A gaze action term on an ideal pinhole scene camera, without an environment.""" + from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model + + from isaaclab_tutorial.active_gaze.env_cfg import scene_camera + from isaaclab_tutorial.active_gaze.gaze import GazeAction, GazeActionCfg + + term = object.__new__(GazeAction) + term.cfg = GazeActionCfg() + term.camera_model = resolve_camera_model(scene_camera((0.5, 0.0, 0.4), (0.0, 0.0, 0.0), field_of_view_deg)) + term.field_radius_deg = field_of_view_deg / 2 + term._gaze = torch.zeros(2, 2) if gaze is None else gaze.clone() + # Points are given as camera-frame directions. + term.directions = lambda points, env_ids=slice(None): torch.nn.functional.normalize(points, dim=-1) + return term + @pytest.mark.parametrize("resolution", [64, 128]) def test_encoder_and_gaze_receive_gradients(resolution): @@ -20,7 +40,7 @@ def test_encoder_and_gaze_receive_gradients(resolution): { "scene_rgb": torch.rand(4, 3, resolution, resolution), "proprioception": torch.randn(4, 26), - "gaze": torch.randn(4, 6), + "gaze": torch.randn(4, 4), }, batch_size=[4], ) @@ -34,11 +54,11 @@ def test_encoder_and_gaze_receive_gradients(resolution): def test_stock_critic_and_motor_penalty(): from isaaclab_tasks.utils import resolve_presets - from isaaclab_tutorial.active_gaze.env_cfg import SO101FoveatedEnvCfg, motor_action_rate + from isaaclab_tutorial.active_gaze.env_cfg import motor_action_rate from isaaclab_tutorial.tasks.place_vial.config.so101.env_cfg import SO101VialEnvCfg stock = resolve_presets(SO101VialEnvCfg()) - cfg = resolve_presets(SO101FoveatedEnvCfg()) + cfg = compose(["presets=nearest"])[0] assert cfg.observations.critic.to_dict() == stock.observations.critic.to_dict() assert cfg.terminations.to_dict() == stock.terminations.to_dict() assert cfg.events.to_dict() == stock.events.to_dict() @@ -52,93 +72,79 @@ def test_stock_critic_and_motor_penalty(): assert torch.equal(motor_action_rate(env), torch.full((2,), 4.0)) -@pytest.mark.parametrize("hfov", [65.0, 80.0]) -@pytest.mark.parametrize("resolution", [64, 128]) -def test_pinhole_calibration_agrees_with_spawn(hfov, resolution): - import math +@pytest.mark.parametrize("field_of_view_deg", [65.0, 80.0]) +def test_scene_camera_is_an_ideal_square_pinhole_that_the_retina_spans(field_of_view_deg): + from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model, sampling_geometry - from isaaclab_tasks.utils import resolve_presets - - from isaaclab_tutorial.active_gaze.env_cfg import SOURCE_SIZE, SO101FoveatedEnvCfg, scene_camera + from isaaclab_tutorial.active_gaze.env_cfg import scene_camera + from isaaclab_tutorial.active_gaze.train import add_diagnostic_camera - cfg = SO101FoveatedEnvCfg() - cfg.scene.eye = scene_camera(hfov=hfov).replace(foveated_res=resolution) - cfg = resolve_presets(cfg) - cfg.enable_diagnostics() - camera = cfg.scene.eye - expected = SOURCE_SIZE / (2 * math.tan(math.radians(hfov / 2))) - assert math.isclose(SOURCE_SIZE * camera.spawn.focal_length / camera.spawn.horizontal_aperture, expected) - assert math.isclose(camera.camera_calibration["intrinsics"][0], expected) - assert cfg.scene.diagnostic_camera.spawn.horizontal_aperture == camera.spawn.horizontal_aperture - assert camera.foveated_res == resolution - assert camera.fixed_software_fov + camera = scene_camera((0.5, 0.0, 0.4), (0.0, 0.0, 0.0), field_of_view_deg, resolution=128) + model = resolve_camera_model(camera) + height, width = model.image_size + fx, fy, cx, cy = model.intrinsics + assert model.model == "pinhole" and height == width and fx == pytest.approx(fy) + assert fx == pytest.approx(width / 2 / math.tan(math.radians(field_of_view_deg / 2))) + assert sampling_geometry(camera)[0] == pytest.approx(field_of_view_deg) + cfg = compose(["presets=numbered"])[0] + add_diagnostic_camera(cfg) + assert cfg.scene.diagnostic_camera.spawn.to_dict() == cfg.scene.eye.spawn.to_dict() + assert cfg.scene.diagnostic_camera.offset.to_dict() == cfg.scene.eye.offset.to_dict() def test_stronger_foveation_increases_central_density_at_fixed_camera(): - import math - - from isaaclab_fovi.sensors.native_grid import native_grid_directions - from isaaclab_fovi.sensors.pooling import build_lowres_coords - from isaaclab_tutorial.active_gaze.configuration import compose + from fovi.sensing.coords import SamplingCoords + from isaaclab_fovi.sensors.calibrated_geometry import sampling_geometry + from isaaclab_fovi.sensors.native_grid import GRID_STYLE, native_grid_directions baseline = compose(["presets=numbered"])[0] - stronger = compose(["presets=numbered", "env.scene.eye.cmf_a=0.0075"])[0] - assert baseline.scene.eye.cmf_a == 0.015 - assert stronger.scene.eye.camera_calibration == baseline.scene.eye.camera_calibration - assert stronger.scene.eye.offset.pos == baseline.scene.eye.offset.pos - assert stronger.scene.eye.offset.rot == baseline.scene.eye.offset.rot + stronger = compose(["presets=numbered", "env.scene.eye.cmf_a_deg=0.3"])[0] + assert baseline.scene.eye.cmf_a_deg == 0.591 + assert stronger.scene.eye.spawn.to_dict() == baseline.scene.eye.spawn.to_dict() + assert stronger.scene.eye.offset.to_dict() == baseline.scene.eye.offset.to_dict() counts = [] for cfg in (baseline, stronger): - coords, _ = build_lowres_coords(cfg.scene.eye, "cpu") - rays = native_grid_directions(coords, tangent_scale=math.tan(math.radians(cfg.camera_hfov() / 2))) - assert len(rays) == 64 * 64 + fov_deg, cmf_a_deg = sampling_geometry(cfg.scene.eye) + coords = SamplingCoords( + fov=fov_deg, cmf_a=cmf_a_deg, res=64, style=GRID_STYLE, field_geometry="spherical", device="cpu" + ) + rays = native_grid_directions(coords) counts.append(int((-rays[:, 2] >= math.cos(math.radians(1))).sum())) assert counts[1] > 1.5 * counts[0] -def test_reset_cache_preserves_physics_and_alignment(): - import math - - from fovi.sensing.projection import CameraModel - from isaaclab_tasks.utils import resolve_presets +def test_gaze_angle_helpers_round_trip_and_stay_inside_their_limits(): + from isaaclab_tutorial.active_gaze.gaze import ( + angles_to_direction, + clamp_gaze, + direction_to_angles, + nearby_directions, + random_gaze, + ) - from isaaclab_tutorial.active_gaze.env_cfg import SO101FoveatedEnvCfg - from isaaclab_tutorial.active_gaze.gaze import angles_to_direction, build_reset_cache - from isaaclab_tutorial.active_gaze.reset import load_reset_dataset - - cfg = resolve_presets(SO101FoveatedEnvCfg()) - path = cfg.events.reset_from_dataset.params["dataset_path"] - rack = cfg.scene.rack.init_state - cache = build_reset_cache(path, cfg.scene.eye, (*rack.pos, *rack.rot), cfg.actions.gaze.angle_limit) - source = load_reset_dataset(path)["states"] - for name, tensor in source.items(): - assert torch.equal(cache["states"][name], tensor) - angles = cache["vision_action"] - assert angles.shape == (len(source["phase"]), 5, 16, 2) - rays = angles_to_direction(angles) - _, valid = CameraModel(**cfg.scene.eye.camera_calibration).project(rays) - assert valid.all() - for exact_index, near_index, direction in ( - (1, 3, cache["object_direction"]), - (2, 4, cache["goal_direction"]), - ): - exact_cos = (rays[:, exact_index] * direction[:, None]).sum(-1) - assert (exact_cos > math.cos(math.radians(0.1))).all() - near_cos = (rays[:, near_index] * direction[:, None]).sum(-1) - assert (near_cos <= math.cos(math.radians(1.99))).all() - assert (near_cos >= math.cos(math.radians(5.01))).all() - assert (angles[:, 0].abs() > math.radians(25)).any() - - -def test_optional_oracle_keeps_actor_and_critic_inputs_and_plain_ppo(): + torch.manual_seed(5) + angles = torch.tensor([[0.0, 0.0], [20.0, -30.0], [-35.0, 10.0]]) + torch.testing.assert_close(direction_to_angles(angles_to_direction(angles)), angles, atol=1e-4, rtol=0) + # Positive tilt looks up (-y in the OpenCV camera frame), positive pan looks left (-x). + up_left = angles_to_direction(torch.tensor([[10.0, 10.0]]))[0] + assert up_left[0] < 0 and up_left[1] < 0 and up_left[2] > 0 + gaze = random_gaze(1000, 0.8) + assert (gaze.norm(dim=-1) <= 0.8 + 1e-6).all() + clamped = clamp_gaze(torch.tensor([[3.0, 4.0], [0.3, 0.4]]), 1.0) + torch.testing.assert_close(clamped, torch.tensor([[0.6, 0.8], [0.3, 0.4]])) + direction = angles_to_direction(angles) + offset = torch.acos((nearby_directions(direction) * direction).sum(-1).clamp(-1, 1)).rad2deg() + assert ((offset >= 2 - 1e-3) & (offset <= 5 + 1e-3)).all() + + +def test_gaze_supervision_keeps_actor_and_critic_inputs(): from rsl_rl.models import CNNModel from isaaclab_tutorial.active_gaze.learning.oracle_ppo import gaze_loss - from isaaclab_tutorial.active_gaze.configuration import compose baseline, base_agent, _ = compose(["presets=no_gaze_supervision"]) supervised, agent, _ = compose(["presets=grasp_gated"]) - assert base_agent.algorithm.class_name == "PPO" + assert base_agent.algorithm.oracle_weight == 0.0 and agent.algorithm.oracle_weight == 1.0 assert baseline.observations.oracle is None assert supervised.observations.oracle is not None cfg = agent.to_dict() @@ -150,7 +156,7 @@ def test_optional_oracle_keeps_actor_and_critic_inputs_and_plain_ppo(): dict( scene_rgb=torch.rand(4, 3, 64, 64), proprioception=torch.randn(4, 26), - gaze=torch.randn(4, 6), + gaze=torch.randn(4, 4), critic=torch.randn(4, 65), oracle=torch.tensor([[0.7, -0.5, 1.0]]).expand(4, -1).clone(), ), @@ -170,8 +176,8 @@ def test_optional_oracle_keeps_actor_and_critic_inputs_and_plain_ppo(): assert any(p.grad is not None and p.grad.abs().sum() > 0 for p in actor.cnns.parameters()) -def test_oracle_switches_with_stock_grasp_and_selective_resets(): - from isaaclab_tutorial.active_gaze.gaze import oracle_target, target_centers +def test_teacher_looks_at_the_vial_until_the_grasp_then_at_the_goal(): + from isaaclab_tutorial.active_gaze.gaze import target_centers, teacher_target from isaaclab_tutorial.tasks.place_vial.mdp.progress import PlacementProgress vial = torch.tensor([[0.2, 0.0, 0.1, 0, 0, 0, 1.0]]).expand(3, -1).clone() @@ -180,51 +186,44 @@ def test_oracle_switches_with_stock_grasp_and_selective_resets(): def asset(pose): return SimpleNamespace( data=SimpleNamespace( - root_pos_w=SimpleNamespace(torch=pose[:, :3]), - root_quat_w=SimpleNamespace(torch=pose[:, 3:]), + root_pos_w=SimpleNamespace(torch=pose[:, :3]), root_quat_w=SimpleNamespace(torch=pose[:, 3:]) ) ) progress = PlacementProgress(3, "cpu") + # Any opening is the goal: the event manager holds the stock dataset reset. + events = SimpleNamespace(get_term_cfg=lambda name: SimpleNamespace(func=object())) env = SimpleNamespace( - scene={"vial": asset(vial), "rack": asset(rack)}, - _so101_placement_progress=progress, - cfg=SimpleNamespace(goal_mode="nearest"), + scene={"vial": asset(vial), "rack": asset(rack)}, _so101_placement_progress=progress, event_manager=events ) object_center, goal = target_centers(vial, rack) - torch.testing.assert_close(oracle_target(env), object_center) + torch.testing.assert_close(teacher_target(env), object_center) holding = torch.tensor([True, True, False]) absent = torch.zeros(3, dtype=torch.bool) for step in range(2): progress.update(holding, absent, absent, absent, torch.full((3,), step)) - torch.testing.assert_close(oracle_target(env), torch.stack((goal[0], goal[1], object_center[2]))) + torch.testing.assert_close(teacher_target(env), torch.stack((goal[0], goal[1], object_center[2]))) # Releasing the vial does not switch back to object fixation. progress.update(absent, absent, absent, absent, torch.full((3,), 3)) assert progress.grasped[:2].all() progress.reset(torch.tensor([0])) - torch.testing.assert_close(oracle_target(env), torch.stack((object_center[0], goal[1], object_center[2]))) + torch.testing.assert_close(teacher_target(env), torch.stack((object_center[0], goal[1], object_center[2]))) -@pytest.mark.parametrize("hfov,limit", [(65.0, 31.5), (80.0, 39.0)]) -def test_calibrated_oracle_reaches_target_from_extreme_gaze(hfov, limit): - import math +@pytest.mark.parametrize("field_of_view_deg", [65.0, 80.0]) +def test_teacher_reaches_its_target_from_the_edge_of_the_gaze_range(field_of_view_deg): + from isaaclab_tutorial.active_gaze.gaze import angles_to_direction, clamp_gaze - from fovi.sensing.projection import CameraModel - - from isaaclab_tutorial.active_gaze.env_cfg import scene_camera - from isaaclab_tutorial.active_gaze.gaze import angles_to_direction, calibrated_oracle - - calibration = CameraModel(**scene_camera(hfov=hfov).camera_calibration) + radius = field_of_view_deg / 2 target = torch.tensor([[0.15, -0.2], [-0.3, 0.25]]) - commanded = torch.tensor([[-1.0, 1.0], [1.0, -1.0]]) * math.radians(limit) - direction = angles_to_direction(target) + term = gaze_term(field_of_view_deg, gaze=torch.tensor([[-0.7, 0.7], [0.7, -0.7]])) + direction = angles_to_direction(target * radius) for _ in range(20): - actions, valid = calibrated_oracle( - direction, commanded, calibration, max_delta=0.12, angle_limit=math.radians(limit) - ) + actions, valid = term.teacher_action(direction) assert valid.all() and (actions.abs() <= 1).all() - commanded = (commanded + actions * 0.12).clamp(-math.radians(limit), math.radians(limit)) - torch.testing.assert_close(commanded, target) - invalid = torch.tensor([[0.0, 0.0, -1.0], [float("nan"), 0.0, 1.0]]) - actions, valid = calibrated_oracle(invalid, commanded, calibration, max_delta=0.12, angle_limit=math.radians(limit)) - assert not valid.any() and torch.isfinite(actions).all() + term._gaze = clamp_gaze(term._gaze + actions * term.cfg.step_size, term.cfg.gaze_limit) + torch.testing.assert_close(term._gaze, target, atol=1e-5, rtol=0) + assert (term.fixation_error_deg(direction) < 1e-2).all() + # Behind the camera or undefined: no valid target and no action. + actions, valid = term.teacher_action(torch.tensor([[0.0, 0.0, -1.0], [float("nan"), 0.0, 1.0]])) + assert not valid.any() and torch.equal(actions, torch.zeros(2, 2)) diff --git a/tests/test_assets.py b/tests/test_assets.py index b1fdc1d..7b8a305 100644 --- a/tests/test_assets.py +++ b/tests/test_assets.py @@ -32,7 +32,9 @@ def test_text_usd_dependencies_resolve(): for usd in ASSET_ROOT.rglob("*.usda"): text = usd.read_text(errors="ignore") for reference in re.findall(r"@([^@\n]+)@", text): - if "://" not in reference and not (usd.parent / reference).resolve().exists(): + # A bare MDL name, such as OmniPBR.mdl, is a core material the renderer resolves from its search path. + builtin_mdl = reference.endswith(".mdl") and "/" not in reference + if "://" not in reference and not builtin_mdl and not (usd.parent / reference).resolve().exists(): missing.append(f"{usd}: {reference}") assert missing == [] diff --git a/tests/test_config.py b/tests/test_config.py index 0a5b809..df66c1c 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -42,10 +42,16 @@ def _camera(*presets): def test_tasks_are_registered_with_rsl_rl_entry_points(): ids = sorted(task for task in gym.registry if task.startswith("IsaacTutorial-")) - assert ids == ["IsaacTutorial-Place-Vial-SO101", "IsaacTutorial-Place-Vial-SO101-Camera"] - state, camera = (gym.spec(task).kwargs for task in ids) + assert ids == [ + "IsaacTutorial-Place-Vial-SO101", + "IsaacTutorial-Place-Vial-SO101-ActiveGaze", + "IsaacTutorial-Place-Vial-SO101-Camera", + ] + state, active_gaze, camera = (gym.spec(task).kwargs for task in ids) assert state["env_cfg_entry_point"].endswith("env_cfg:SO101VialEnvCfg") assert state["rsl_rl_cfg_entry_point"].endswith("rsl_rl_ppo_cfg:SO101StatePPORunnerCfg") + assert active_gaze["env_cfg_entry_point"].endswith("active_gaze.env_cfg:ActiveGazeEnvCfg") + assert active_gaze["rsl_rl_cfg_entry_point"].endswith("active_gaze.agents:ActiveGazeAgentCfg") assert camera["env_cfg_entry_point"].endswith("camera_env_cfg:SO101VialCameraEnvCfg") assert camera["rsl_rl_cfg_entry_point"].endswith("rsl_rl_distillation_cfg:SO101CameraDistillationRunnerCfg") From 772678304f3e6ada1375ac3b7b6e5e5c37a3d83f Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:25:52 -0800 Subject: [PATCH 18/30] Document the ActiveGaze task docs/ACTIVE_GAZE.md covers installing the fovi extra, the variants, the gaze action and its teacher, training, resuming, playback, inspection and deployment. The README lists the task. --- README.md | 3 ++ docs/ACTIVE_GAZE.md | 89 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 docs/ACTIVE_GAZE.md diff --git a/README.md b/README.md index 48608ea..e722736 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ uv run isaaclab zero_agent --task IsaacTutorial-Place-Vial-SO101 --num_envs 8 -- | --- | --- | --- | | `IsaacTutorial-Place-Vial-SO101` | Full state | PPO | | `IsaacTutorial-Place-Vial-SO101-Camera` | Wrist RGB (2 frames, 64×48) + proprioception | Distillation from a state teacher, or PPO from scratch | +| `IsaacTutorial-Place-Vial-SO101-ActiveGaze` | Foveated scene camera whose gaze the policy moves + proprioception | PPO with a gaze teacher; see [docs/ACTIVE_GAZE.md](docs/ACTIVE_GAZE.md) | Add `presets=sim2real` to either task to enable robot-transfer randomization. The physical randomization is identical in both tasks, so a teacher and its student train under the same physics. See @@ -201,9 +202,11 @@ src/isaaclab_tutorial/ tasks/velocity/config/microduck/ Microduck environment, controls, and training configs tasks/velocity/mdp/ walking commands, rewards, and task terms utils/ evaluation, LEAPP export, real-robot scripts + active_gaze/ ActiveGaze task, training script and deployment (fovi extra) checkpoints/microduck/ pretrained balance and walking policies scripts/ Microduck evaluation and inspection tools docs/SIM2REAL.md training for and deploying to the real robot +docs/ACTIVE_GAZE.md the ActiveGaze task, from install to the real robot ``` PhysX and OVRTX are available for sim-to-sim checks: install them with `uv sync --extra ovphysx --extra ovrtx` diff --git a/docs/ACTIVE_GAZE.md b/docs/ACTIVE_GAZE.md new file mode 100644 index 0000000..1a1fcfc --- /dev/null +++ b/docs/ACTIVE_GAZE.md @@ -0,0 +1,89 @@ +# Active gaze + +`IsaacTutorial-Place-Vial-SO101-ActiveGaze` sees the scene through a fixed, foveated scene camera from Isaac Lab's +`isaaclab_fovi` package. Its retina samples densely where it looks and sparsely in the periphery, and the policy +moves the gaze while it moves the arm. + +The task needs the `fovi` extra. Until the `isaaclab_fovi` pull request merges, the tutorial is pinned to that pull +request's branch of Isaac Lab, and one of that branch's Git LFS files is missing, so skip LFS downloads when +syncing: + +```bash +GIT_LFS_SKIP_SMUDGE=1 uv sync --locked --extra fovi +``` + +In PowerShell, run `$env:GIT_LFS_SKIP_SMUDGE=1` first, then `uv sync --locked --extra fovi`. + +## Variants + +| Preset | Goal | Actor | +| --- | --- | --- | +| `numbered` (default) | The opening with the vial's number | CNN on the 64×64 retina, proprioception and gaze | +| `nearest` | Any opening, as in the state task | CNN on the 64×64 retina, proprioception and gaze | +| `dino_language` | The opening with the vial's number | Frozen foveated DINOv3 on the 128×128 retina, fused with an instruction | + +The critic sees the privileged state, including the target opening, in every variant. + +## Gaze + +- The camera is an ideal square pinhole; the retina spans its field of view, so the gaze can reach anything the + camera sees. +- Two of the eight actions move the gaze (tilt, pan). An action of 1 moves an angle by 0.1 field radii, a field + radius being half the retina's field of view, and the gaze stays within 1 field radius of the optical axis. + The actor observes the gaze and its velocity in the same units. +- A teacher supervises the gaze actions: it looks at the vial until the grasp, then at the goal. The PPO loss adds + the teacher's gaze actions as labels (`agent.algorithm.oracle_weight`, 1.0); `presets=no_gaze_supervision` + turns this off. +- Episodes start the gaze at random, on the vial or the goal, or a few degrees off either. + +## Train + +The task trains with its own script, because action chunking wraps the environment and the reset curriculum +needs its own runner: + +```bash +uv run --extra fovi python -m isaaclab_tutorial.active_gaze.train train --output runs/numbered presets=numbered,newton_renderer +``` + +Every argument that is not a script option is an Isaac Lab configuration override, as with `isaaclab train`. +Useful presets and overrides: + +- `newton_renderer` renders with Newton; the default is OVRTX (`--extra ovrtx`). +- `sim2real` adds the tutorial's physical randomization, scene colours, a camera mount that moves each episode, + and photometric variation of the retina. On `dino_language`, the actor also learns to predict the mount's move. +- `chunking` makes each policy decision a plan of three control steps. +- `env.observations.vision.tokens.params.num_layers=N` runs only the first `N` DINO layers, to cut the cost of + perception while keeping pretrained features. +- `env.scene.eye.cmf_a_deg=…` changes how strongly the retina is foveated; a large value makes it nearly uniform. + +Each run writes `run.json` next to its checkpoints. It records the overrides, the retina, the gaze and the control +rates. `--checkpoint path/model_N.pt` resumes a run with its saved overrides. A new override replaces the saved +value, and `presets=…,finetune` warm-starts at a lower learning rate. Add `--logger wandb` for W&B. + +## Play and inspect + +```bash +uv run --extra fovi python -m isaaclab_tutorial.active_gaze.train play --checkpoint runs/numbered/model_4999.pt --output runs/numbered_play +uv run --extra fovi python -m isaaclab_tutorial.active_gaze.train inspect --num_envs 4 --output runs/inspect presets=numbered,newton_renderer +``` + +`play` builds the run's saved configuration; a `presets=` argument would replace the saved preset list. Both write +videos and frames that show a dense camera at the scene camera's pose next to the retina. `inspect` +sweeps the gaze through every reset category without a policy, and checks that resetting one environment leaves the +others alone. + +## Deploy + +The `dino_language` policy runs on the real robot through a LEAPP bundle. The bundle samples the real camera's +images on the simulator's retinal grid, so describe that camera as a `fovi.sensing.projection.CameraModel` in +JSON: `model` (`pinhole` or `fisheye`), `image_size` (height, width), `intrinsics` (fx, fy, cx, cy) and OpenCV +`distortion` coefficients. + +```bash +uv run --extra fovi --extra leapp python -m isaaclab_tutorial.active_gaze.deployment.export --checkpoint runs/language/model_4999.pt --camera_model camera.json --output bundles/language +uv run --extra fovi --extra leapp --with "lerobot[feetech]==0.6.1" python -m isaaclab_tutorial.active_gaze.deployment.run --bundle bundles/language --joint-map joint_map.json --port /dev/ttyACM0 +``` + +`run` drives the arm through LeRobot, the version the tutorial's own robot scripts use. It stays read-only unless `--execute` is given with a verified joint map and a start pose, as described in +[SIM2REAL.md](SIM2REAL.md). Without `--camera_model`, the export uses the simulated camera; such a bundle can be +checked in simulation with `train.py play --deployment_bundle`, but `run` refuses to execute it. From f845c3b9756518c0357c9cdaaefab6535d7efa5b Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:31:15 -0800 Subject: [PATCH 19/30] Render OVRTX path-traced with a white background and a key light from above OVRTX now defaults to path-traced RGB; its Minimal modes draw no background, so they stay available as presets. The scene and diagnostic cameras share a white background, matching Newton. A dim dome and a distant key light from above, tilted 25 degrees, replace the bright dome so objects cast visible shadows. Newton's renderer ignores scene lights and is unchanged. --- docs/ACTIVE_GAZE.md | 3 ++- src/isaaclab_tutorial/active_gaze/env_cfg.py | 15 ++++++++++++--- .../active_gaze/render_options.py | 18 ++++++------------ src/isaaclab_tutorial/active_gaze/train.py | 1 + tests/active_gaze/test_vial.py | 2 ++ 5 files changed, 23 insertions(+), 16 deletions(-) diff --git a/docs/ACTIVE_GAZE.md b/docs/ACTIVE_GAZE.md index 1a1fcfc..decd758 100644 --- a/docs/ACTIVE_GAZE.md +++ b/docs/ACTIVE_GAZE.md @@ -48,7 +48,8 @@ uv run --extra fovi python -m isaaclab_tutorial.active_gaze.train train --output Every argument that is not a script option is an Isaac Lab configuration override, as with `isaaclab train`. Useful presets and overrides: -- `newton_renderer` renders with Newton; the default is OVRTX (`--extra ovrtx`). +- `newton_renderer` renders with Newton; the default is OVRTX path-traced RGB (`--extra ovrtx`). The faster + OVRTX Minimal modes (`minimal_full_mdl`, `minimal_diffuse_mdl`, with `_shadows` variants) draw no background. - `sim2real` adds the tutorial's physical randomization, scene colours, a camera mount that moves each episode, and photometric variation of the retina. On `dino_language`, the actor also learns to predict the mount's move. - `chunking` makes each policy decision a plan of three control steps. diff --git a/src/isaaclab_tutorial/active_gaze/env_cfg.py b/src/isaaclab_tutorial/active_gaze/env_cfg.py index e656925..6a04a0a 100644 --- a/src/isaaclab_tutorial/active_gaze/env_cfg.py +++ b/src/isaaclab_tutorial/active_gaze/env_cfg.py @@ -21,7 +21,7 @@ from isaaclab.assets import AssetBaseCfg, VisualMaterialCfg from isaaclab.managers import CurriculumTermCfg, EventTermCfg, ManagerTermBase, ObservationGroupCfg, ObservationTermCfg from isaaclab.sensors import CameraCfg -from isaaclab.sim import DomeLightCfg, PinholeCameraCfg +from isaaclab.sim import DistantLightCfg, DomeLightCfg, PinholeCameraCfg from isaaclab.utils import configclass from isaaclab_tasks.utils import PresetCfg, preset @@ -80,7 +80,8 @@ def camera_rotation(position, target) -> tuple[float, float, float, float]: def scene_camera(position, target, field_of_view_deg: float, resolution: int = 64) -> FoveatedCameraCfg: """A fixed foveated camera at ``position`` looking at ``target``. - The physical camera is an ideal square pinhole with the given field of view, and the retina spans it. + The physical camera is an ideal square pinhole with the given field of view, and the retina spans it. Pixels that + miss the scene are white on every renderer. """ aperture = 48.0 * math.tan(math.radians(field_of_view_deg / 2)) return FoveatedCameraCfg( @@ -96,6 +97,7 @@ def scene_camera(position, target, field_of_view_deg: float, resolution: int = 6 ), offset=CameraCfg.OffsetCfg(pos=position, rot=camera_rotation(position, target), convention="opengl"), foveated_res=resolution, + background_color=(1.0, 1.0, 1.0), mask_to_sensor_fov=True, update_period=0.0, ) @@ -119,7 +121,14 @@ class RobotSpawnCfg(PresetCfg): class SceneCfg(SO101SceneCfg): robot = SO101SceneCfg().robot.replace(spawn=RobotSpawnCfg()) eye = NEAREST_CAMERA - light = AssetBaseCfg(prim_path="/World/Light", spawn=DomeLightCfg(intensity=2000)) + # A dim dome fills the shadows that a key light from above casts. The key light leans 25 degrees toward +y, so + # the shadows fall sideways in the scene camera's view. + light = AssetBaseCfg(prim_path="/World/Light", spawn=DomeLightCfg(intensity=250)) + key_light = AssetBaseCfg( + prim_path="/World/KeyLight", + spawn=DistantLightCfg(intensity=1500, angle=5.0), + init_state=AssetBaseCfg.InitialStateCfg(rot=(0.2164396, 0.0, 0.0, 0.9762960)), + ) # Materials that the sim2real colour events vary; the Newton renderer only reads material colour. robot_visual = VisualMaterialCfg(prim_path="{ENV_REGEX_NS}/Robot/Looks/material_a_d_printed", spawn=None) diff --git a/src/isaaclab_tutorial/active_gaze/render_options.py b/src/isaaclab_tutorial/active_gaze/render_options.py index c4ed1e1..88c7dbf 100644 --- a/src/isaaclab_tutorial/active_gaze/render_options.py +++ b/src/isaaclab_tutorial/active_gaze/render_options.py @@ -6,18 +6,11 @@ from isaaclab_tasks.utils import PresetCfg -RENDER_MODES = { - "rtpt": ("rgb", False), - "minimal_diffuse_mdl": ("simple_shading_diffuse_mdl", False), - "minimal_diffuse_mdl_shadows": ("simple_shading_diffuse_mdl", True), - "minimal_full_mdl": ("simple_shading_full_mdl", False), - "minimal_full_mdl_shadows": ("simple_shading_full_mdl", True), -} - @configclass class CameraOutputCfg(PresetCfg): - default = ["simple_shading_full_mdl"] + # Path-traced RGB by default: RTX Minimal mode draws no background or dome light. + default = ["rgb"] newton_renderer = ["rgb"] rtpt = ["rgb"] minimal_diffuse_mdl = ["simple_shading_diffuse_mdl"] @@ -28,7 +21,7 @@ class CameraOutputCfg(PresetCfg): @configclass class CameraOutputNameCfg(PresetCfg): - default = "simple_shading_full_mdl" + default = "rgb" newton_renderer = "rgb" rtpt = "rgb" minimal_diffuse_mdl = "simple_shading_diffuse_mdl" @@ -39,7 +32,8 @@ class CameraOutputNameCfg(PresetCfg): @configclass class ShadowsCfg(PresetCfg): - default = True + # Only Minimal mode reads this switch; path tracing always traces shadows. + default = False rtpt = False minimal_diffuse_mdl = False minimal_diffuse_mdl_shadows = True @@ -61,7 +55,7 @@ class CameraRenderSettingsCfg(PresetCfg): minimal_diffuse_mdl_shadows = _minimal minimal_full_mdl = _minimal minimal_full_mdl_shadows = _minimal - default = minimal_full_mdl_shadows + default = rtpt @configclass diff --git a/src/isaaclab_tutorial/active_gaze/train.py b/src/isaaclab_tutorial/active_gaze/train.py index 098056c..c65ca09 100644 --- a/src/isaaclab_tutorial/active_gaze/train.py +++ b/src/isaaclab_tutorial/active_gaze/train.py @@ -250,6 +250,7 @@ def add_diagnostic_camera(cfg): height=640, renderer_cfg=eye.renderer_cfg.copy(), render_settings=eye.render_settings.copy(), + background_color=eye.background_color, spawn=eye.spawn.copy(), offset=eye.offset.copy(), ) diff --git a/tests/active_gaze/test_vial.py b/tests/active_gaze/test_vial.py index ab65ef5..87dc8bf 100644 --- a/tests/active_gaze/test_vial.py +++ b/tests/active_gaze/test_vial.py @@ -90,6 +90,8 @@ def test_scene_camera_is_an_ideal_square_pinhole_that_the_retina_spans(field_of_ add_diagnostic_camera(cfg) assert cfg.scene.diagnostic_camera.spawn.to_dict() == cfg.scene.eye.spawn.to_dict() assert cfg.scene.diagnostic_camera.offset.to_dict() == cfg.scene.eye.offset.to_dict() + # Both renderers draw the same white background. + assert cfg.scene.eye.background_color == cfg.scene.diagnostic_camera.background_color == (1.0, 1.0, 1.0) def test_stronger_foveation_increases_central_density_at_fixed_camera(): From 7e6c2ca8bfc4e60518b729ae98f48ca1e6268a04 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:43:16 -0800 Subject: [PATCH 20/30] Cast the same shadows on Newton and OVRTX Newton ignores USD lights and lights the scene with its own directional light along (-1, 1, -1); its shadow rays are now on, at about 10% of training throughput. The OVRTX key light keeps the tutorial's rotation, which shines along the same direction, and is sharper and stronger over a dimmer dome, so both renderers cast matching, visible shadows. --- src/isaaclab_tutorial/active_gaze/env_cfg.py | 12 ++++-------- src/isaaclab_tutorial/active_gaze/render_options.py | 3 ++- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/isaaclab_tutorial/active_gaze/env_cfg.py b/src/isaaclab_tutorial/active_gaze/env_cfg.py index 6a04a0a..8a960e4 100644 --- a/src/isaaclab_tutorial/active_gaze/env_cfg.py +++ b/src/isaaclab_tutorial/active_gaze/env_cfg.py @@ -121,14 +121,10 @@ class RobotSpawnCfg(PresetCfg): class SceneCfg(SO101SceneCfg): robot = SO101SceneCfg().robot.replace(spawn=RobotSpawnCfg()) eye = NEAREST_CAMERA - # A dim dome fills the shadows that a key light from above casts. The key light leans 25 degrees toward +y, so - # the shadows fall sideways in the scene camera's view. - light = AssetBaseCfg(prim_path="/World/Light", spawn=DomeLightCfg(intensity=250)) - key_light = AssetBaseCfg( - prim_path="/World/KeyLight", - spawn=DistantLightCfg(intensity=1500, angle=5.0), - init_state=AssetBaseCfg.InitialStateCfg(rot=(0.2164396, 0.0, 0.0, 0.9762960)), - ) + # A dim dome fills the shadows that a sharp key light casts. The tutorial's key light shines along (-1, 1, -1), + # the direction of the Newton renderer's own light, so both renderers cast the same shadows. + light = AssetBaseCfg(prim_path="/World/Light", spawn=DomeLightCfg(intensity=150)) + key_light = SO101SceneCfg().key_light.replace(spawn=DistantLightCfg(intensity=2000, angle=1.0)) # Materials that the sim2real colour events vary; the Newton renderer only reads material colour. robot_visual = VisualMaterialCfg(prim_path="{ENV_REGEX_NS}/Robot/Looks/material_a_d_printed", spawn=None) diff --git a/src/isaaclab_tutorial/active_gaze/render_options.py b/src/isaaclab_tutorial/active_gaze/render_options.py index 88c7dbf..06cb94f 100644 --- a/src/isaaclab_tutorial/active_gaze/render_options.py +++ b/src/isaaclab_tutorial/active_gaze/render_options.py @@ -60,6 +60,7 @@ class CameraRenderSettingsCfg(PresetCfg): @configclass class FoviRendererCfg(PresetCfg): - newton_renderer = NewtonWarpRendererCfg(render_order="pixel_priority") + # Newton ignores USD lights and lights the scene with its own directional light; shadow rays are opt-in. + newton_renderer = NewtonWarpRendererCfg(render_order="pixel_priority", enable_shadows=True) ovrtx = OVRTXRendererCfg(enable_shadows=ShadowsCfg()) default = ovrtx From 072efe3be49652145dc8dc410cb079e3a86fdb49 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:46:41 -0800 Subject: [PATCH 21/30] Light the ActiveGaze scene with the tutorial's own lights The scene inherits the tutorial's dome and key light, whose direction is the Newton renderer's light direction, instead of defining its own. --- src/isaaclab_tutorial/active_gaze/env_cfg.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/isaaclab_tutorial/active_gaze/env_cfg.py b/src/isaaclab_tutorial/active_gaze/env_cfg.py index 8a960e4..9af0de7 100644 --- a/src/isaaclab_tutorial/active_gaze/env_cfg.py +++ b/src/isaaclab_tutorial/active_gaze/env_cfg.py @@ -18,10 +18,10 @@ import torch from isaaclab_fovi.sensors import FoveatedCameraCfg -from isaaclab.assets import AssetBaseCfg, VisualMaterialCfg +from isaaclab.assets import VisualMaterialCfg from isaaclab.managers import CurriculumTermCfg, EventTermCfg, ManagerTermBase, ObservationGroupCfg, ObservationTermCfg from isaaclab.sensors import CameraCfg -from isaaclab.sim import DistantLightCfg, DomeLightCfg, PinholeCameraCfg +from isaaclab.sim import PinholeCameraCfg from isaaclab.utils import configclass from isaaclab_tasks.utils import PresetCfg, preset @@ -121,10 +121,6 @@ class RobotSpawnCfg(PresetCfg): class SceneCfg(SO101SceneCfg): robot = SO101SceneCfg().robot.replace(spawn=RobotSpawnCfg()) eye = NEAREST_CAMERA - # A dim dome fills the shadows that a sharp key light casts. The tutorial's key light shines along (-1, 1, -1), - # the direction of the Newton renderer's own light, so both renderers cast the same shadows. - light = AssetBaseCfg(prim_path="/World/Light", spawn=DomeLightCfg(intensity=150)) - key_light = SO101SceneCfg().key_light.replace(spawn=DistantLightCfg(intensity=2000, angle=1.0)) # Materials that the sim2real colour events vary; the Newton renderer only reads material colour. robot_visual = VisualMaterialCfg(prim_path="{ENV_REGEX_NS}/Robot/Looks/material_a_d_printed", spawn=None) From e61b0236ca518fbe0ef4284c1a26cd5c418d6698 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 16:51:06 -0800 Subject: [PATCH 22/30] Lock Isaac Lab at the pull request's latest commit It keeps an RTX foveated camera's gaze relative to its mount when sim2real moves the mount. --- uv.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uv.lock b/uv.lock index 42ca131..d46e800 100644 --- a/uv.lock +++ b/uv.lock @@ -1035,7 +1035,7 @@ wheels = [ [[package]] name = "isaaclab" version = "3.0.0" -source = { git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead#d1822a7dfa9b565dd6f5b2445ea35b01cb982283" } +source = { git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead#0e4303ab467a9ceb7ae3afd507a9b810e513a09f" } dependencies = [ { name = "alphashape", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "botocore", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, From 885b2835b6a726e806f6bbbd9f051b617cada62b Mon Sep 17 00:00:00 2001 From: nblauch Date: Mon, 23 Nov 2026 22:59:41 -0800 Subject: [PATCH 23/30] Import the PhysX configuration from isaaclab_isaacsim Isaac Lab renamed isaaclab_physx to isaaclab_isaacsim; the old name is a deprecated alias. --- pyproject.toml | 2 +- .../tasks/place_vial/config/so101/env_cfg.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 20bdf34..22584c7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -91,7 +91,7 @@ section-order = [ ] [tool.ruff.lint.isort.sections] -isaaclab = ["isaaclab", "isaaclab_newton", "isaaclab_ov", "isaaclab_physx"] +isaaclab = ["isaaclab", "isaaclab_isaacsim", "isaaclab_newton", "isaaclab_ov"] "isaaclab-rl" = ["isaaclab_rl"] "isaaclab-tasks" = ["isaaclab_tasks"] "isaaclab-assets" = ["isaaclab_assets"] diff --git a/src/isaaclab_tutorial/tasks/place_vial/config/so101/env_cfg.py b/src/isaaclab_tutorial/tasks/place_vial/config/so101/env_cfg.py index 2ad2f9d..67772f6 100644 --- a/src/isaaclab_tutorial/tasks/place_vial/config/so101/env_cfg.py +++ b/src/isaaclab_tutorial/tasks/place_vial/config/so101/env_cfg.py @@ -27,11 +27,11 @@ from isaaclab.sim.utils import bind_physics_material, clone from isaaclab.utils.configclass import configclass from isaaclab.visualizers import VisualizerCfg +from isaaclab_isaacsim.physics import PhysxCfg +from isaaclab_isaacsim.sim.schemas import PhysxRigidBodyCfg +from isaaclab_isaacsim.sim.spawners.materials import PhysxRigidBodyMaterialCfg from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg, NewtonCollisionPipelineCfg from isaaclab_ov.physics import OvPhysxCfg -from isaaclab_physx.physics import PhysxCfg -from isaaclab_physx.sim.schemas import PhysxRigidBodyCfg -from isaaclab_physx.sim.spawners.materials import PhysxRigidBodyMaterialCfg from isaaclab_tasks.utils import PresetCfg, preset From 7b4ea9710a91dc04cbb031137bf1d521a676cd1d Mon Sep 17 00:00:00 2001 From: nblauch Date: Mon, 23 Nov 2026 22:59:48 -0800 Subject: [PATCH 24/30] Follow RSL-RL's reworked PPO interfaces Isaac Lab now pins RSL-RL ea39cc2, where PPO.update returns losses and statistics and process_env_step returns the values the logger sums over each episode. OraclePPO returns the same pair and reports the entropy loss as native PPO does. Episode logging keeps the environment's rewards, without the value estimate added for chunk timeouts. --- .../active_gaze/learning/oracle_ppo.py | 35 ++++++++++++++----- tests/active_gaze/test_action_chunks.py | 9 +++-- tests/active_gaze/test_sim2real.py | 2 +- 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/src/isaaclab_tutorial/active_gaze/learning/oracle_ppo.py b/src/isaaclab_tutorial/active_gaze/learning/oracle_ppo.py index 9a00b4c..4c223ef 100644 --- a/src/isaaclab_tutorial/active_gaze/learning/oracle_ppo.py +++ b/src/isaaclab_tutorial/active_gaze/learning/oracle_ppo.py @@ -2,9 +2,9 @@ # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause -"""RSL-RL 5.5 PPO with RND and constant-weight Gaussian gaze supervision. +"""RSL-RL PPO with RND and constant-weight Gaussian gaze supervision. -The update follows rsl_rl.algorithms.PPO (BSD-3-Clause). The native runner, +The update follows rsl_rl.algorithms.PPO at ea39cc2 (5.5.2 development, BSD-3-Clause). The native runner, storage, GAE, optimizer, and checkpointing are retained. Chunk transitions add executed-prefix likelihoods, per-control oracle targets, and final-state timeout bootstrapping. The auxiliary targets never enter the actor. @@ -108,6 +108,7 @@ def process_env_step(self, obs, rewards, dones, extras): self.transition.observations = self.transition.observations.clone(recurse=False) for key in self.rnd.obs_groups["rnd_state"]: self.transition.observations[key] = obs[key] + bootstrap = None if "chunk_valid" in extras: transition = self.transition transition.observations = transition.observations.clone(recurse=False) @@ -128,15 +129,24 @@ def process_env_step(self, obs, rewards, dones, extras): ), ): final_values = self.critic(extras["chunk_timeout_observations"]).squeeze(-1) - rewards = rewards + extras["chunk_timeout_discount"] * final_values.float() - super().process_env_step(obs, rewards, dones, extras) + bootstrap = extras["chunk_timeout_discount"] * final_values.float() + rewards = rewards + bootstrap + step_dict = super().process_env_step(obs, rewards, dones, extras) + if bootstrap is not None: + # The logger sums these over each episode. Report the environment's rewards, without the value estimate + # added for chunk timeouts. + for key in ("Training/mean_reward", "Rnd/mean_extrinsic_reward"): + if key in step_dict: + step_dict[key] = step_dict[key] - bootstrap + return step_dict def update(self): + """Return mean losses and logger statistics, as the native PPO update does.""" totals = torch.zeros(6, device=self.device) auxiliary_totals = {} updates = 0 for batch in self.storage.mini_batch_generator(self.num_mini_batches, self.num_learning_epochs): - if self.normalize_advantage_per_mini_batch: + if self.normalize_advantage_per_mini_batch and batch.advantages.numel() > 1: with torch.no_grad(): batch.advantages = (batch.advantages - batch.advantages.mean()) / (batch.advantages.std() + 1e-8) with torch.autocast( @@ -222,7 +232,8 @@ def update(self): ( value_loss, surrogate, - entropy, + # Native PPO reports the entropy loss, the negated entropy. + -entropy, oracle, (labels[:, 2] > 0.5).float().mean(), rnd_loss, @@ -235,15 +246,21 @@ def update(self): if self.rnd is not None: self.rnd.update_normalization(obs) self.storage.clear() - result = dict( + loss_dict = dict( zip( ("value", "surrogate", "entropy", "oracle", "oracle_valid", "rnd"), (totals / updates).tolist(), strict=True, ) ) - result.update({key: (value / updates).item() for key, value in auxiliary_totals.items()}) - return result + loss_dict.update({key: (value / updates).item() for key, value in auxiliary_totals.items()}) + stats_dict = { + "Optimizer/learning_rate": self.learning_rate, + "Model/mean_policy_std": self.actor.output_std.mean().item(), + } + if self.rnd is not None: + stats_dict["Rnd/rnd_weight"] = self.rnd.weight + return loss_dict, stats_dict def auxiliary_loss(self, observations): """Optional task-supervised loss on the shared actor forward pass.""" diff --git a/tests/active_gaze/test_action_chunks.py b/tests/active_gaze/test_action_chunks.py index a2ef67e..b7b1bfd 100644 --- a/tests/active_gaze/test_action_chunks.py +++ b/tests/active_gaze/test_action_chunks.py @@ -148,7 +148,9 @@ def without_oracle(): for _ in range(2): actions = alg.act(obs) following, rewards, dones, extras = env.step(actions) - alg.process_env_step(following, rewards, dones, extras) + logged = alg.process_env_step(following, rewards, dones, extras) + # Episode logging excludes the value estimate added for chunk timeouts. + torch.testing.assert_close(logged["Training/mean_reward"], rewards) obs = following alg.compute_returns(obs) torch.testing.assert_close(alg.storage.rewards[0, :, 0], torch.tensor([1.0, 2.0, 1.875])) @@ -159,8 +161,9 @@ def without_oracle(): torch.testing.assert_close(alg.storage.observations[0]["chunk_oracle"][2, :, 0], torch.arange(4) / 10) else: assert not alg.storage.observations["chunk_oracle"].any() - result = alg.update() - assert all(torch.isfinite(torch.tensor(value)) for value in result.values()) + losses, stats = alg.update() + assert all(torch.isfinite(torch.tensor(value)) for value in losses.values()) + assert set(stats) == {"Optimizer/learning_rate", "Model/mean_policy_std"} def test_discarded_chunk_suffix_holds_absolute_hand_targets(): diff --git a/tests/active_gaze/test_sim2real.py b/tests/active_gaze/test_sim2real.py index 3493238..7ff549e 100644 --- a/tests/active_gaze/test_sim2real.py +++ b/tests/active_gaze/test_sim2real.py @@ -209,7 +209,7 @@ def test_auxiliary_updates_shared_vision_without_leaking_labels(tmp_path): algorithm.act(obs) algorithm.process_env_step(obs, torch.ones(4), torch.zeros(4), {}) algorithm.compute_returns(obs) - metrics = algorithm.update() + metrics, _ = algorithm.update() assert metrics["extrinsics"] > 0 and metrics["oracle_valid"] == 0 From 61e4ba24407eac3a6cb64f64c11548eaf1f25e87 Mon Sep 17 00:00:00 2001 From: nblauch Date: Mon, 23 Nov 2026 23:06:35 -0800 Subject: [PATCH 25/30] Move the gaze onto isaaclab_fovi's gaze action The task had its own gaze action, observation and teacher, written against an earlier isaaclab_fovi. It now uses isaaclab_fovi's: GazeAction for the action, gaze_state for the observation and gaze_teacher_labels, aimed at the world point the task picks, for the teacher. What stays here is the task's own: the point the teacher looks at, the mixed start of each episode's gaze, and the within-1-degree and goal-target logs. MixedResetGazeAction extends GazeAction's reset, which runs after the reset events and so cannot be set from one. The sim2real preset moves the camera's mount, so there the gaze tracks the mount. The retina's field of view and the physical camera now come from the camera's configuration through fovi's CameraModel; isaaclab_fovi's resolve_camera_model and sampling_geometry are gone. Needs isaaclab_fovi's teacher to accept world points and its image-free pose read, which are not in Isaac Lab yet. --- pyproject.toml | 2 +- .../active_gaze/configuration.py | 24 +- .../active_gaze/deployment/retina.py | 3 +- src/isaaclab_tutorial/active_gaze/env_cfg.py | 12 +- src/isaaclab_tutorial/active_gaze/gaze.py | 252 +++++++----------- src/isaaclab_tutorial/active_gaze/sim2real.py | 3 +- src/isaaclab_tutorial/active_gaze/train.py | 13 +- tests/active_gaze/test_numbered.py | 6 +- tests/active_gaze/test_sim2real.py | 3 +- tests/active_gaze/test_vial.py | 116 ++++---- 10 files changed, 194 insertions(+), 240 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 22584c7..c02ebc6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -91,7 +91,7 @@ section-order = [ ] [tool.ruff.lint.isort.sections] -isaaclab = ["isaaclab", "isaaclab_isaacsim", "isaaclab_newton", "isaaclab_ov"] +isaaclab = ["isaaclab", "isaaclab_fovi", "isaaclab_isaacsim", "isaaclab_newton", "isaaclab_ov"] "isaaclab-rl" = ["isaaclab_rl"] "isaaclab-tasks" = ["isaaclab_tasks"] "isaaclab-assets" = ["isaaclab_assets"] diff --git a/src/isaaclab_tutorial/active_gaze/configuration.py b/src/isaaclab_tutorial/active_gaze/configuration.py index 51d623e..e7ef634 100644 --- a/src/isaaclab_tutorial/active_gaze/configuration.py +++ b/src/isaaclab_tutorial/active_gaze/configuration.py @@ -5,7 +5,10 @@ import dataclasses from collections.abc import Sequence -from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model, sampling_geometry +from fovi.sensing.projection import CameraModel + +from isaaclab_fovi.sensors import FoveatedCameraCfg +from isaaclab_fovi.sensors.calibrated_geometry import camera_model_from_spawn from isaaclab_tasks.utils import resolve_task_config @@ -15,7 +18,18 @@ from .goals import NumberedResetFromDataset from .language import INSTRUCTIONS -__all__ = ["RUN_FILE", "compose", "describe", "resume_overrides"] +__all__ = ["RUN_FILE", "camera_model", "compose", "describe", "field_of_view_deg", "resume_overrides"] + + +def camera_model(eye: FoveatedCameraCfg) -> CameraModel: + """The physical camera a configured eye looks through, as its sensor resolves it: its ``camera_model``, or the + camera its ``spawn`` creates.""" + return CameraModel(**(eye.camera_model or camera_model_from_spawn(eye.spawn))) + + +def field_of_view_deg(eye: FoveatedCameraCfg) -> float: + """Field of view [deg] of a configured eye's retina: the window its sensor takes from the physical camera.""" + return camera_model(eye).field_of_view(eye.retinal_window_reference_side, eye.retinal_window_fraction) def compose(overrides: Sequence[str] = (), saved: dict | None = None): @@ -70,7 +84,7 @@ def resume_overrides(overrides: Sequence[str], agent) -> list[str]: def describe(env, agent) -> dict: """What a run trains: task, policy, retina, gaze and control, read from its resolved configuration.""" eye = env.scene.eye - fov_deg, cmf_a_deg = sampling_geometry(eye) + fov_deg = field_of_view_deg(eye) gaze = env.actions.gaze algorithm = agent.algorithm language = getattr(env.observations, "vision", None) is not None @@ -84,9 +98,9 @@ def describe(env, agent) -> dict: sim2real="camera_mount" in vars(env.events), retina=dict( fov_deg=fov_deg, - cmf_a_deg=cmf_a_deg, + cmf_a_deg=eye.cmf_a_deg, resolution=eye.foveated_res, - camera_model=dataclasses.asdict(resolve_camera_model(eye)), + camera_model=dataclasses.asdict(camera_model(eye)), mount_position=eye.offset.pos, mount_rotation=eye.offset.rot, ), diff --git a/src/isaaclab_tutorial/active_gaze/deployment/retina.py b/src/isaaclab_tutorial/active_gaze/deployment/retina.py index 0ced441..fe78db2 100644 --- a/src/isaaclab_tutorial/active_gaze/deployment/retina.py +++ b/src/isaaclab_tutorial/active_gaze/deployment/retina.py @@ -3,10 +3,11 @@ import torch from fovi.sensing.coords import SamplingCoords from fovi.sensing.projection import CameraModel, gaze_rotation -from isaaclab_fovi.sensors.native_grid import GRID_STYLE, native_grid_directions from torch import nn from torch.nn import functional as F +from isaaclab_fovi.sensors.native_grid import GRID_STYLE, native_grid_directions + class SoftwareRetina(nn.Module): """Bilinear sampling of dense images on the simulator's retinal ray grid, in its upright image order. diff --git a/src/isaaclab_tutorial/active_gaze/env_cfg.py b/src/isaaclab_tutorial/active_gaze/env_cfg.py index 9af0de7..cfdaba8 100644 --- a/src/isaaclab_tutorial/active_gaze/env_cfg.py +++ b/src/isaaclab_tutorial/active_gaze/env_cfg.py @@ -16,13 +16,14 @@ import math import torch -from isaaclab_fovi.sensors import FoveatedCameraCfg from isaaclab.assets import VisualMaterialCfg from isaaclab.managers import CurriculumTermCfg, EventTermCfg, ManagerTermBase, ObservationGroupCfg, ObservationTermCfg from isaaclab.sensors import CameraCfg from isaaclab.sim import PinholeCameraCfg from isaaclab.utils import configclass +from isaaclab_fovi.mdp import gaze_state +from isaaclab_fovi.sensors import FoveatedCameraCfg from isaaclab_tasks.utils import PresetCfg, preset @@ -40,7 +41,7 @@ ) from isaaclab_tutorial.tasks.place_vial.reset.curriculum import ALL_PHASES -from .gaze import GazeActionCfg, oracle_labels +from .gaze import MixedResetGazeActionCfg, oracle_labels from .goals import ( NumberedResetFromDataset, TargetPlacementSuccess, @@ -176,10 +177,6 @@ def __call__(self, env, photometric=None): return self.cached -def gaze_state(env) -> torch.Tensor: - return env.action_manager.get_term("gaze").proprioception() - - def motor_action_rate(env) -> torch.Tensor: """The stock action-rate penalty on the six motor actions only; gaze moves freely.""" actions = env.action_manager @@ -188,7 +185,8 @@ def motor_action_rate(env) -> torch.Tensor: @configclass class ActiveGazeActionsCfg(ActionsCfg): - gaze = GazeActionCfg() + # The sim2real preset moves the camera's mount every episode, so the gaze's teacher follows the mount. + gaze = MixedResetGazeActionCfg(asset_name="eye", mount=preset(default="fixed", sim2real="tracked")) PHOTOMETRIC = preset(default=None, sim2real=PHOTOMETRIC_RANGES) diff --git a/src/isaaclab_tutorial/active_gaze/gaze.py b/src/isaaclab_tutorial/active_gaze/gaze.py index b43d94c..851e426 100644 --- a/src/isaaclab_tutorial/active_gaze/gaze.py +++ b/src/isaaclab_tutorial/active_gaze/gaze.py @@ -1,8 +1,10 @@ -"""Gaze action of the active-gaze task, its reset, and the teacher's gaze labels. +"""What the active-gaze task adds to :mod:`isaaclab_fovi.mdp`'s gaze action: where the gaze starts an episode, the +world point its teacher looks at, and the teacher's task logs. -Gaze angles are (tilt, pan) [deg] from the scene camera's optical axis: positive tilt looks up and positive pan looks -left, as for :meth:`isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles`. The policy sees and moves the gaze in field -radii, half the retina's field of view. Camera-frame directions use the OpenCV convention: x right, y down, z forward. +The action, its observation and the teacher's labels are isaaclab_fovi's. Gaze angles are (tilt, pan) [deg] from the +scene camera's optical axis: positive tilt looks up and positive pan looks left. The policy sees and moves the gaze in +field radii, half the retina's field of view. Camera-frame directions use the ROS (OpenCV) convention: x right, y +down, z forward. """ from __future__ import annotations @@ -10,18 +12,16 @@ import math import torch -from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model, sampling_geometry -from isaaclab.managers import ActionTerm, ActionTermCfg from isaaclab.utils import configclass from isaaclab.utils.math import quat_apply, quat_apply_inverse +from isaaclab_fovi.mdp import GazeAction, GazeActionCfg, gaze_teacher_labels from isaaclab_tutorial.tasks.place_vial.mdp.geometry import RACK_HOLE_CENTERS from isaaclab_tutorial.tasks.place_vial.mdp.progress import placement_progress from isaaclab_tutorial.tasks.place_vial.mdp.task import RACK_RIM_HEIGHT, VIAL_AXIS_MAX, VIAL_AXIS_MIN from .goals import CAP_LABEL_POSITION, RACK_LABEL_OFFSETS, target_holes -from .sim2real import mount_randomization RESET_MODES = ("random", "object", "goal", "near_object", "near_goal") """Where the gaze starts an episode: anywhere in the camera's view, at the vial or the goal, or 2 to 5 degrees off @@ -40,24 +40,6 @@ def direction_to_angles(direction: torch.Tensor) -> torch.Tensor: return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1).rad2deg() -def clamp_gaze(angles: torch.Tensor, limit: float) -> torch.Tensor: - """Scale gaze angles back onto the circle of radius ``limit`` when they leave it.""" - return angles * (limit / angles.norm(dim=-1, keepdim=True).clamp_min(limit)) - - -def random_gaze(count: int, limit: float, device=None) -> torch.Tensor: - """Gaze angles drawn uniformly over the disc of radius ``limit``, shape (count, 2).""" - radius = limit * torch.rand(count, device=device).sqrt() - angle = 2 * math.pi * torch.rand(count, device=device) - return torch.stack((radius * angle.sin(), radius * angle.cos()), dim=-1) - - -def camera_directions(points: torch.Tensor, position: torch.Tensor, rotation: torch.Tensor) -> torch.Tensor: - """Camera-frame unit directions to world points, for a camera at ``position`` with OpenGL ``rotation`` (xyzw).""" - directions = quat_apply_inverse(rotation.expand(len(points), -1), points - position) - return torch.nn.functional.normalize(directions * directions.new_tensor((1, -1, -1)), dim=-1) - - def nearby_directions(direction: torch.Tensor) -> torch.Tensor: """Directions 2 to 5 degrees from each given direction, in a uniformly drawn azimuth.""" reference = direction.new_tensor((0, 1, 0)).expand_as(direction) @@ -97,161 +79,119 @@ def gaze_targets(env, vial_pose: torch.Tensor, rack_pose: torch.Tensor, env_ids= return target_centers(vial_pose, rack_pose, holes[env_ids], CAP_LABEL_POSITION, RACK_LABEL_OFFSETS) -class GazeAction(ActionTerm): - """Moves the scene camera's gaze by bounded increments in (tilt, pan) order. - - Actions, limits and the observed gaze are in field radii. An action of 1 changes an angle by ``step_size`` and the - gaze stays within ``gaze_limit`` of the optical axis. At reset the gaze starts at one of :data:`RESET_MODES`, drawn - uniformly, or on the optical axis when ``mixed_resets`` is off. - """ - - cfg: GazeActionCfg +def teacher_target(env) -> torch.Tensor: + """World point the teacher looks at: the vial until it is grasped, then the goal.""" + vial, rack = ( + torch.cat((env.scene[name].data.root_pos_w.torch, env.scene[name].data.root_quat_w.torch), dim=-1) + for name in ("vial", "rack") + ) + vial_point, goal_point = gaze_targets(env, vial, rack) + return torch.where(placement_progress(env).grasped[:, None], goal_point, vial_point) - def __init__(self, cfg: GazeActionCfg, env): - super().__init__(cfg, env) - self.camera = env.scene[cfg.camera_name] - self.camera_model = resolve_camera_model(self.camera.cfg) - self.field_radius_deg = sampling_geometry(self.camera.cfg)[0] / 2 - """Half the retina's field of view [deg].""" - self.base_rotation = torch.tensor(self.camera.cfg.offset.rot, device=self.device) - self._raw = torch.zeros(self.num_envs, 2, device=self.device) - self._gaze = torch.zeros_like(self._raw) - self._velocity = torch.zeros_like(self._raw) - self.reset_mode = torch.zeros(self.num_envs, dtype=torch.long, device=self.device) - """Index into :data:`RESET_MODES` of each environment's last reset.""" - @property - def action_dim(self) -> int: - return 2 +def target_directions(gaze: GazeAction, points: torch.Tensor, env_ids=slice(None)) -> torch.Tensor: + """Camera-frame unit directions from the gaze's camera, as it stands now, to world points. - @property - def raw_actions(self) -> torch.Tensor: - return self._raw + The scene camera has no image roll, so its frame is the upright frame in which gazes are measured. + """ + mounts = gaze.teacher_mounts().torch[env_ids] + # Reading the mounts refreshed the camera's position without capturing an image. + position = gaze.camera.mount_pos_w.torch[env_ids] + return torch.nn.functional.normalize(quat_apply_inverse(mounts, points - position), dim=-1) + + +def fixation_error_deg(gaze: GazeAction, points: torch.Tensor) -> torch.Tensor: + """Angle [deg] between the gaze and the direction to world points.""" + direction = target_directions(gaze, points) + looking = angles_to_direction(gaze.angles_deg) + # atan2 stays accurate near perfect alignment, unlike acos of the dot product. + return torch.atan2(torch.cross(looking, direction, dim=-1).norm(dim=-1), (looking * direction).sum(-1)).rad2deg() + + +def mixed_reset_gaze( + vial_direction: torch.Tensor, goal_direction: torch.Tensor, visible, field_radius_deg: float, gaze_limit: float +) -> tuple[torch.Tensor, torch.Tensor]: + """Draw where each gaze starts an episode. + + Args: + vial_direction: Camera-frame directions to each environment's vial, shape (N, 3). + goal_direction: Camera-frame directions to each environment's goal, shape (N, 3). + visible: Whether camera-frame directions fall inside the physical camera's image. + field_radius_deg: Half the retina's field of view [deg]. + gaze_limit: Largest distance of the gaze from the optical axis, in field radii. + + Returns: + Each environment's index into :data:`RESET_MODES`, drawn uniformly, and its start gaze in field radii, shape + (N, 2). A start the camera does not see or the gaze cannot reach becomes mode 0, whose gaze is not used. + """ + modes = torch.randint(len(RESET_MODES), (len(vial_direction),), device=vial_direction.device) + direction = torch.where(((modes == 2) | (modes == 4))[:, None], goal_direction, vial_direction) + direction = torch.where((modes >= 3)[:, None], nearby_directions(direction), direction) + gaze = direction_to_angles(direction) / field_radius_deg + reachable = visible(direction) & (gaze.norm(dim=-1) <= gaze_limit) + return torch.where(reachable, modes, 0), gaze - @property - def processed_actions(self) -> torch.Tensor: - return self._gaze - @property - def gaze(self) -> torch.Tensor: - """Current gaze in field radii, shape (num_envs, 2).""" - return self._gaze +class MixedResetGazeAction(GazeAction): + """isaaclab_fovi's gaze action, with episodes that start at one of :data:`RESET_MODES`, drawn uniformly. - @property - def angles_deg(self) -> torch.Tensor: - """Current gaze angles [deg], shape (num_envs, 2).""" - return self._gaze * self.field_radius_deg + The ``random`` mode is isaaclab_fovi's own reset: a random gaze the camera sees with ``random_reset``, else the + optical axis. + """ - def process_actions(self, actions: torch.Tensor): - self._raw.copy_(actions) - previous = self._gaze.clone() - self._gaze.copy_(clamp_gaze(self._gaze + actions.clamp(-1, 1) * self.cfg.step_size, self.cfg.gaze_limit)) - self._velocity.copy_((self._gaze - previous) / self._env.step_dt) - self.camera.set_gaze_angles(self.angles_deg) + cfg: MixedResetGazeActionCfg - def apply_actions(self): - pass + def __init__(self, cfg: MixedResetGazeActionCfg, env): + super().__init__(cfg, env) + self.reset_mode = torch.zeros(self.num_envs, dtype=torch.long, device=self.device) + """Index into :data:`RESET_MODES` of each environment's last reset.""" def reset(self, env_ids=None): + super().reset(env_ids) ids = torch.arange(self.num_envs, device=self.device)[slice(None) if env_ids is None else env_ids] - self._raw[ids] = 0 - self._velocity[ids] = 0 - self._gaze[ids] = 0 self.reset_mode[ids] = 0 - if self.cfg.mixed_resets and len(ids): - self._reset_mixed(ids) - self.camera.set_gaze_angles(self.angles_deg) - - def _reset_mixed(self, ids: torch.Tensor): - """Start each gaze at one of :data:`RESET_MODES` for this episode's vial and rack.""" env = self._env - if not hasattr(env, "_so101_reset_vial_pose"): + # The dataset reset records each episode's vial and rack; before the first one there is nothing to look at. + if not self.cfg.mixed_resets or not len(ids) or not hasattr(env, "_so101_reset_vial_pose"): return origins = env.scene.env_origins[ids] vial, rack = env._so101_reset_vial_pose[ids].clone(), env._so101_reset_rack_pose[ids].clone() vial[:, :3] += origins rack[:, :3] += origins - vial_point, goal_point = gaze_targets(env, vial, rack, ids) - modes = torch.randint(len(RESET_MODES), (len(ids),), device=self.device) - point = torch.where(((modes == 2) | (modes == 4))[:, None], goal_point, vial_point) - direction = self.directions(point, ids) - direction = torch.where((modes >= 3)[:, None], nearby_directions(direction), direction) - aligned = direction_to_angles(direction) / self.field_radius_deg - modes = torch.where(self.visible(direction) & (aligned.norm(dim=-1) <= self.cfg.gaze_limit), modes, 0) - # A random start lies inside the physical image too; the optical axis is the fallback. - random = random_gaze(len(ids), self.cfg.gaze_limit, self.device) - random = torch.where(self.visible(angles_to_direction(random * self.field_radius_deg))[:, None], random, 0) - self._gaze[ids] = torch.where((modes == 0)[:, None], random, aligned) + directions = (target_directions(self, point, ids) for point in gaze_targets(env, vial, rack, ids)) + modes, gaze = mixed_reset_gaze(*directions, self.visible, self.field_radius_deg, self.cfg.gaze_limit) self.reset_mode[ids] = modes - - def directions(self, points: torch.Tensor, env_ids=slice(None)) -> torch.Tensor: - """Camera-frame unit directions from the camera's mount to world points.""" - mount = mount_randomization(self._env) - rotation = self.base_rotation if mount is None else mount.rotation[env_ids] - return camera_directions(points, self.camera.data.pos_w.torch[env_ids], rotation) - - def visible(self, direction: torch.Tensor) -> torch.Tensor: - """Whether camera-frame directions fall inside the physical camera's image.""" - return self.camera_model.project(direction)[1] - - def teacher_action(self, points: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - """The action that moves the gaze toward world points, and whether each point is a valid target. - - A point is valid when the physical camera sees it and the gaze can reach it within the limit. - """ - direction = self.directions(points) - desired = direction_to_angles(direction) / self.field_radius_deg - valid = self.visible(direction) & (desired.norm(dim=-1) <= self.cfg.gaze_limit) - action = ((clamp_gaze(desired, self.cfg.gaze_limit) - self._gaze) / self.cfg.step_size).clamp(-1, 1) - return torch.where(valid[:, None], action, 0.0), valid - - def fixation_error_deg(self, points: torch.Tensor) -> torch.Tensor: - """Angle [deg] between the gaze and the direction to world points.""" - direction = self.directions(points) - gaze = angles_to_direction(self.angles_deg) - # atan2 stays accurate near perfect alignment, unlike acos of the dot product. - return torch.atan2(torch.cross(gaze, direction, dim=-1).norm(dim=-1), (gaze * direction).sum(-1)).rad2deg() - - def proprioception(self) -> torch.Tensor: - """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4).""" - return torch.cat((self._gaze, self._velocity), dim=-1) + aimed = ids[modes > 0] + # The camera's stored angles own the gaze, and the observed state starts there, at rest. + angles = self.camera.gaze_angles.torch + angles[aimed] = gaze[modes > 0] * self.field_radius_deg + self.state[aimed, :2] = gaze[modes > 0] + self.camera.set_gaze_angles(angles) @configclass -class GazeActionCfg(ActionTermCfg): - """Configuration of :class:`GazeAction`.""" - - class_type: type = GazeAction - asset_name: str = "robot" - camera_name: str = "eye" - """Scene name of the foveated camera whose gaze the action moves.""" - step_size: float = 0.1 - """Change of each gaze coordinate per step at an action of 1, in field radii.""" - gaze_limit: float = 1.0 - """Largest distance of the gaze from the camera's optical axis, in field radii.""" +class MixedResetGazeActionCfg(GazeActionCfg): + """Configuration of :class:`MixedResetGazeAction`.""" + + class_type: type = MixedResetGazeAction + random_reset: bool = True mixed_resets: bool = True - """Start episodes at a gaze drawn from :data:`RESET_MODES`; otherwise on the optical axis.""" + """Start episodes at a gaze drawn from :data:`RESET_MODES`; otherwise as isaaclab_fovi's gaze action does.""" -def teacher_target(env) -> torch.Tensor: - """World point the teacher looks at: the vial until it is grasped, then the goal.""" - vial, rack = ( - torch.cat((env.scene[name].data.root_pos_w.torch, env.scene[name].data.root_quat_w.torch), dim=-1) - for name in ("vial", "rack") - ) - vial_point, goal_point = gaze_targets(env, vial, rack) - return torch.where(placement_progress(env).grasped[:, None], goal_point, vial_point) +class oracle_labels(gaze_teacher_labels): + """The teacher's gaze action toward :func:`teacher_target` and its validity, shape (num_envs, 3). + A training label, never a policy input. Next to isaaclab_fovi's logs, it logs the fraction of environments whose + gaze is within one degree of a valid target, and the fraction whose target is the goal. + """ -def oracle_labels(env) -> torch.Tensor: - """The teacher's gaze action and its validity, shape (num_envs, 3). A training label, never a policy input.""" - gaze: GazeAction = env.action_manager.get_term("gaze") - point = teacher_target(env) - action, valid = gaze.teacher_action(point) - error = gaze.fixation_error_deg(point) - log = env.extras.setdefault("log", {}) - log["Gaze/target_error_deg"] = torch.where(valid, error, 0).sum() / valid.sum().clamp_min(1) - log["Gaze/within_1deg"] = (valid & (error <= 1)).float().mean() - log["Gaze/goal_target_fraction"] = placement_progress(env).grasped.float().mean() - log["Gaze/valid_target_fraction"] = valid.float().mean() - return torch.cat((action, valid[:, None].float()), dim=-1) + def __call__(self, env) -> torch.Tensor: + points = teacher_target(env) + labels = super().__call__(env, target_w=lambda _: points) + valid = labels[:, 2] > 0.5 + error = fixation_error_deg(env.action_manager.get_term("gaze"), points) + log = env.extras.setdefault("log", {}) + log["Gaze/within_1deg"] = (valid & (error <= 1)).float().mean() + log["Gaze/goal_target_fraction"] = placement_progress(env).grasped.float().mean() + return labels diff --git a/src/isaaclab_tutorial/active_gaze/sim2real.py b/src/isaaclab_tutorial/active_gaze/sim2real.py index 61b1933..4e042b1 100644 --- a/src/isaaclab_tutorial/active_gaze/sim2real.py +++ b/src/isaaclab_tutorial/active_gaze/sim2real.py @@ -66,7 +66,8 @@ class randomize_camera_mount(ManagerTermBase): """Move the scene camera's mount by up to ``position_range`` [m] and ``rotation_range_deg`` [deg] each episode. A fraction ``nominal_fraction`` of episodes keep the nominal mount. The ranges ramp up from 10 % over - ``ramp_steps`` control steps. This term owns the camera's mount pose and the move's extrinsics labels. + ``ramp_steps`` control steps. This term owns the camera's mount pose and the move's extrinsics labels. The gaze + stays relative to the moved mount, and a gaze action with ``mount="tracked"`` aims its teacher from it. """ def __init__(self, cfg, env): diff --git a/src/isaaclab_tutorial/active_gaze/train.py b/src/isaaclab_tutorial/active_gaze/train.py index c65ca09..8721edd 100644 --- a/src/isaaclab_tutorial/active_gaze/train.py +++ b/src/isaaclab_tutorial/active_gaze/train.py @@ -462,6 +462,8 @@ def task_visible_fraction(env, gaze) -> float: """Fraction of the robot's bodies, the vial and the rack that the physical camera sees.""" import torch + from .gaze import target_directions + points = torch.cat( ( env.scene["robot"].data.body_pos_w.torch, @@ -470,7 +472,7 @@ def task_visible_fraction(env, gaze) -> float: ), dim=1, ) - visible = torch.stack([gaze.visible(gaze.directions(points[:, k])) for k in range(points.shape[1])], dim=1) + visible = torch.stack([gaze.visible(target_directions(gaze, points[:, k])) for k in range(points.shape[1])], dim=1) return float(visible.float().mean()) @@ -478,14 +480,15 @@ def diagnostic_markers(gaze): """Image positions of the vial, the goal and the gaze, as fractions of the camera image, shape (num_envs, 3, 2).""" import torch - from .gaze import angles_to_direction + from .gaze import angles_to_direction, target_directions - directions = [gaze.directions(point) for point in gaze_points(gaze)] + directions = [target_directions(gaze, point) for point in gaze_points(gaze)] directions.append(angles_to_direction(gaze.angles_deg)) - height, width = gaze.camera_model.image_size + camera = gaze.camera.camera_model + height, width = camera.image_size size = torch.tensor((width, height), dtype=torch.float32, device=gaze.device) # Pixel coordinates have integer centres. - pixels = [(gaze.camera_model.project(direction)[0] + 0.5) / size for direction in directions] + pixels = [(camera.project(direction)[0] + 0.5) / size for direction in directions] return torch.stack(pixels, dim=1).cpu().numpy() diff --git a/tests/active_gaze/test_numbered.py b/tests/active_gaze/test_numbered.py index cecbff1..cd9b796 100644 --- a/tests/active_gaze/test_numbered.py +++ b/tests/active_gaze/test_numbered.py @@ -94,11 +94,9 @@ def restore(self, env, ids, path, phases, sequential, **perturbation): def test_numbered_configuration_keeps_the_target_in_the_critic_only(): - from isaaclab_fovi.sensors.calibrated_geometry import sampling_geometry - from isaaclab.sim import MultiAssetSpawnerCfg - from isaaclab_tutorial.active_gaze.configuration import compose, describe + from isaaclab_tutorial.active_gaze.configuration import compose, describe, field_of_view_deg plain, plain_agent, _ = compose(["presets=nearest,newton_renderer"]) numbered, numbered_agent, _ = compose(["presets=numbered,newton_renderer"]) @@ -107,7 +105,7 @@ def test_numbered_configuration_keeps_the_target_in_the_critic_only(): ) # The numbered scene's camera sits closer and narrower, so the labels stay legible. assert numbered.scene.eye.offset.pos[0] < plain.scene.eye.offset.pos[0] - assert sampling_geometry(numbered.scene.eye)[0] < sampling_geometry(plain.scene.eye)[0] + assert field_of_view_deg(numbered.scene.eye) < field_of_view_deg(plain.scene.eye) for group in ("scene_rgb", "proprioception", "gaze"): assert getattr(numbered.observations, group).to_dict() == getattr(plain.observations, group).to_dict() assert ( diff --git a/tests/active_gaze/test_sim2real.py b/tests/active_gaze/test_sim2real.py index 7ff549e..0668206 100644 --- a/tests/active_gaze/test_sim2real.py +++ b/tests/active_gaze/test_sim2real.py @@ -28,7 +28,8 @@ def test_sim2real_adds_camera_randomization_and_extrinsics_labels_but_keeps_the_ # The tutorial's own sim2real preset also retunes arm action scales and rewards; this covers what active gaze adds. base, base_agent, _ = compose(["presets=dino_language"]) varied, varied_agent, _ = compose(["presets=dino_language,sim2real"]) - assert base.actions.gaze.to_dict() == varied.actions.gaze.to_dict() + # The gaze changes only in where its teacher takes the camera's mount from. + assert base.actions.gaze.to_dict() == varied.actions.gaze.replace(mount="fixed").to_dict() assert base.scene.eye.to_dict() == varied.scene.eye.to_dict() assert base.observations.critic.to_dict() == varied.observations.critic.to_dict() assert base.observations.proprio.to_dict() == varied.observations.proprio.to_dict() diff --git a/tests/active_gaze/test_vial.py b/tests/active_gaze/test_vial.py index 87dc8bf..8311053 100644 --- a/tests/active_gaze/test_vial.py +++ b/tests/active_gaze/test_vial.py @@ -1,4 +1,5 @@ -"""Contracts of the visual actor, the scene camera, the gaze action and its teacher, without launching physics.""" +"""Contracts of the visual actor, the scene camera, the gaze's start and its teacher's target, without launching +physics.""" import math from types import SimpleNamespace @@ -7,24 +8,7 @@ import torch from tensordict import TensorDict -from isaaclab_tutorial.active_gaze.configuration import compose - - -def gaze_term(field_of_view_deg=78.0, gaze=None): - """A gaze action term on an ideal pinhole scene camera, without an environment.""" - from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model - - from isaaclab_tutorial.active_gaze.env_cfg import scene_camera - from isaaclab_tutorial.active_gaze.gaze import GazeAction, GazeActionCfg - - term = object.__new__(GazeAction) - term.cfg = GazeActionCfg() - term.camera_model = resolve_camera_model(scene_camera((0.5, 0.0, 0.4), (0.0, 0.0, 0.0), field_of_view_deg)) - term.field_radius_deg = field_of_view_deg / 2 - term._gaze = torch.zeros(2, 2) if gaze is None else gaze.clone() - # Points are given as camera-frame directions. - term.directions = lambda points, env_ids=slice(None): torch.nn.functional.normalize(points, dim=-1) - return term +from isaaclab_tutorial.active_gaze.configuration import camera_model, compose, field_of_view_deg @pytest.mark.parametrize("resolution", [64, 128]) @@ -72,20 +56,18 @@ def test_stock_critic_and_motor_penalty(): assert torch.equal(motor_action_rate(env), torch.full((2,), 4.0)) -@pytest.mark.parametrize("field_of_view_deg", [65.0, 80.0]) -def test_scene_camera_is_an_ideal_square_pinhole_that_the_retina_spans(field_of_view_deg): - from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model, sampling_geometry - +@pytest.mark.parametrize("fov_deg", [65.0, 80.0]) +def test_scene_camera_is_an_ideal_square_pinhole_that_the_retina_spans(fov_deg): from isaaclab_tutorial.active_gaze.env_cfg import scene_camera from isaaclab_tutorial.active_gaze.train import add_diagnostic_camera - camera = scene_camera((0.5, 0.0, 0.4), (0.0, 0.0, 0.0), field_of_view_deg, resolution=128) - model = resolve_camera_model(camera) + camera = scene_camera((0.5, 0.0, 0.4), (0.0, 0.0, 0.0), fov_deg, resolution=128) + model = camera_model(camera) height, width = model.image_size fx, fy, cx, cy = model.intrinsics assert model.model == "pinhole" and height == width and fx == pytest.approx(fy) - assert fx == pytest.approx(width / 2 / math.tan(math.radians(field_of_view_deg / 2))) - assert sampling_geometry(camera)[0] == pytest.approx(field_of_view_deg) + assert fx == pytest.approx(width / 2 / math.tan(math.radians(fov_deg / 2))) + assert field_of_view_deg(camera) == pytest.approx(fov_deg) cfg = compose(["presets=numbered"])[0] add_diagnostic_camera(cfg) assert cfg.scene.diagnostic_camera.spawn.to_dict() == cfg.scene.eye.spawn.to_dict() @@ -96,7 +78,7 @@ def test_scene_camera_is_an_ideal_square_pinhole_that_the_retina_spans(field_of_ def test_stronger_foveation_increases_central_density_at_fixed_camera(): from fovi.sensing.coords import SamplingCoords - from isaaclab_fovi.sensors.calibrated_geometry import sampling_geometry + from isaaclab_fovi.sensors.native_grid import GRID_STYLE, native_grid_directions baseline = compose(["presets=numbered"])[0] @@ -106,23 +88,22 @@ def test_stronger_foveation_increases_central_density_at_fixed_camera(): assert stronger.scene.eye.offset.to_dict() == baseline.scene.eye.offset.to_dict() counts = [] for cfg in (baseline, stronger): - fov_deg, cmf_a_deg = sampling_geometry(cfg.scene.eye) + eye = cfg.scene.eye coords = SamplingCoords( - fov=fov_deg, cmf_a=cmf_a_deg, res=64, style=GRID_STYLE, field_geometry="spherical", device="cpu" + fov=field_of_view_deg(eye), + cmf_a=eye.cmf_a_deg, + res=64, + style=GRID_STYLE, + field_geometry="spherical", + device="cpu", ) rays = native_grid_directions(coords) counts.append(int((-rays[:, 2] >= math.cos(math.radians(1))).sum())) assert counts[1] > 1.5 * counts[0] -def test_gaze_angle_helpers_round_trip_and_stay_inside_their_limits(): - from isaaclab_tutorial.active_gaze.gaze import ( - angles_to_direction, - clamp_gaze, - direction_to_angles, - nearby_directions, - random_gaze, - ) +def test_gaze_angles_and_directions_round_trip_in_the_camera_frame(): + from isaaclab_tutorial.active_gaze.gaze import angles_to_direction, direction_to_angles, nearby_directions torch.manual_seed(5) angles = torch.tensor([[0.0, 0.0], [20.0, -30.0], [-35.0, 10.0]]) @@ -130,15 +111,35 @@ def test_gaze_angle_helpers_round_trip_and_stay_inside_their_limits(): # Positive tilt looks up (-y in the OpenCV camera frame), positive pan looks left (-x). up_left = angles_to_direction(torch.tensor([[10.0, 10.0]]))[0] assert up_left[0] < 0 and up_left[1] < 0 and up_left[2] > 0 - gaze = random_gaze(1000, 0.8) - assert (gaze.norm(dim=-1) <= 0.8 + 1e-6).all() - clamped = clamp_gaze(torch.tensor([[3.0, 4.0], [0.3, 0.4]]), 1.0) - torch.testing.assert_close(clamped, torch.tensor([[0.6, 0.8], [0.3, 0.4]])) direction = angles_to_direction(angles) offset = torch.acos((nearby_directions(direction) * direction).sum(-1).clamp(-1, 1)).rad2deg() assert ((offset >= 2 - 1e-3) & (offset <= 5 + 1e-3)).all() +def test_mixed_resets_start_on_or_near_the_vial_or_the_goal_when_the_gaze_can_reach_them(): + from isaaclab_tutorial.active_gaze.gaze import RESET_MODES, angles_to_direction, mixed_reset_gaze + + torch.manual_seed(11) + radius, limit, count = 39.0, 1.0, 4000 + vial_gaze, goal_gaze = torch.tensor([0.3, -0.4]), torch.tensor([-0.2, 0.5]) + vial = angles_to_direction(vial_gaze * radius).expand(count, -1) + goal = angles_to_direction(goal_gaze * radius).expand(count, -1) + # A camera that sees everything in front of it. + modes, gaze = mixed_reset_gaze(vial, goal, lambda direction: direction[:, 2] > 0, radius, limit) + assert torch.bincount(modes, minlength=len(RESET_MODES)).min() > count / len(RESET_MODES) / 2 + torch.testing.assert_close(gaze[modes == 1], vial_gaze.expand(int((modes == 1).sum()), -1), atol=1e-5, rtol=0) + torch.testing.assert_close(gaze[modes == 2], goal_gaze.expand(int((modes == 2).sum()), -1), atol=1e-5, rtol=0) + for mode, target in ((3, vial), (4, goal)): + chosen = modes == mode + offset = torch.acos((angles_to_direction(gaze[chosen] * radius) * target[chosen]).sum(-1).clamp(-1, 1)) + assert ((offset.rad2deg() >= 2 - 1e-2) & (offset.rad2deg() <= 5 + 1e-2)).all() + # A target the camera does not see, or beyond the gaze limit, leaves the episode to the random start. + modes, _ = mixed_reset_gaze(vial, goal, lambda direction: torch.zeros(count, dtype=torch.bool), radius, limit) + assert not modes.any() + modes, _ = mixed_reset_gaze(vial, goal, lambda direction: direction[:, 2] > 0, radius, 0.1) + assert not modes.any() + + def test_gaze_supervision_keeps_actor_and_critic_inputs(): from rsl_rl.models import CNNModel @@ -212,20 +213,17 @@ def asset(pose): torch.testing.assert_close(teacher_target(env), torch.stack((object_center[0], goal[1], object_center[2]))) -@pytest.mark.parametrize("field_of_view_deg", [65.0, 80.0]) -def test_teacher_reaches_its_target_from_the_edge_of_the_gaze_range(field_of_view_deg): - from isaaclab_tutorial.active_gaze.gaze import angles_to_direction, clamp_gaze - - radius = field_of_view_deg / 2 - target = torch.tensor([[0.15, -0.2], [-0.3, 0.25]]) - term = gaze_term(field_of_view_deg, gaze=torch.tensor([[-0.7, 0.7], [0.7, -0.7]])) - direction = angles_to_direction(target * radius) - for _ in range(20): - actions, valid = term.teacher_action(direction) - assert valid.all() and (actions.abs() <= 1).all() - term._gaze = clamp_gaze(term._gaze + actions * term.cfg.step_size, term.cfg.gaze_limit) - torch.testing.assert_close(term._gaze, target, atol=1e-5, rtol=0) - assert (term.fixation_error_deg(direction) < 1e-2).all() - # Behind the camera or undefined: no valid target and no action. - actions, valid = term.teacher_action(torch.tensor([[0.0, 0.0, -1.0], [float("nan"), 0.0, 1.0]])) - assert not valid.any() and torch.equal(actions, torch.zeros(2, 2)) +def test_gaze_is_isaaclab_fovis_action_with_a_teacher_that_follows_the_sim2real_mount(): + from isaaclab_fovi.mdp import GazeAction, gaze_state, gaze_teacher_labels + + from isaaclab_tutorial.active_gaze.gaze import MixedResetGazeAction, oracle_labels + + base, varied = (compose([f"presets={names}"])[0] for names in ("numbered", "numbered,sim2real")) + gaze = base.actions.gaze + assert issubclass(MixedResetGazeAction, GazeAction) and gaze.class_type is MixedResetGazeAction + assert (gaze.asset_name, gaze.mode, gaze.step_size, gaze.gaze_limit) == ("eye", "software", 0.1, 1.0) + assert base.observations.gaze.state.func is gaze_state + assert base.observations.oracle.labels.func is oracle_labels and issubclass(oracle_labels, gaze_teacher_labels) + # A fixed-mount teacher rejects a camera whose mount turns, as the sim2real camera's does every episode. + assert gaze.mount == "fixed" and varied.actions.gaze.mount == "tracked" + assert varied.actions.gaze.replace(mount="fixed").to_dict() == gaze.to_dict() From 34aa66654276ff792b3c64a06481dee36533105f Mon Sep 17 00:00:00 2001 From: nblauch Date: Mon, 23 Nov 2026 23:07:13 -0800 Subject: [PATCH 26/30] Select the Newton renderer as newton_warp Isaac Lab renamed the newton_renderer preset to newton_warp; the old name is a deprecated alias. The ActiveGaze presets and the wrist-camera task's commands and shadow setting use the new name. --- README.md | 6 +++--- docs/SIM2REAL.md | 4 ++-- src/isaaclab_tutorial/active_gaze/render_options.py | 8 ++++---- .../tasks/place_vial/config/so101/camera_env_cfg.py | 2 +- tests/active_gaze/test_numbered.py | 6 +++--- tests/active_gaze/test_presets.py | 2 +- tests/active_gaze/test_rendering.py | 2 +- tests/test_config.py | 2 +- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index e722736..6c3ab16 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ identical in both tasks, so a teacher and its student train under the same physi uv run isaaclab train --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101 --num_envs 4096 --visualizer none presets=newton_mjwarp # Camera student, distilled from the teacher checkpoint -uv run isaaclab train --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101-Camera --num_envs 1024 --checkpoint /abs/path/to/state/model_799.pt --visualizer none presets=newton_mjwarp,newton_renderer +uv run isaaclab train --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101-Camera --num_envs 1024 --checkpoint /abs/path/to/state/model_799.pt --visualizer none presets=newton_mjwarp,newton_warp ``` During distillation the student acts and the frozen teacher labels every state it visits. The labels are @@ -117,7 +117,7 @@ images and proprioception as the student; the critic sees the privileged state. iterations. ```bash -uv run isaaclab train --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101-Camera --agent rsl_rl_ppo_cfg_entry_point --num_envs 1024 --visualizer none presets=newton_mjwarp,newton_renderer +uv run isaaclab train --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101-Camera --agent rsl_rl_ppo_cfg_entry_point --num_envs 1024 --visualizer none presets=newton_mjwarp,newton_warp ``` ### Evaluate @@ -130,7 +130,7 @@ per-episode outcomes. uv run isaaclab play --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101 --num_envs 1024 --checkpoint /abs/path/to/model.pt --visualizer none --external_callback isaaclab_tutorial.utils.evaluation.install_episode_counter presets=newton_mjwarp ``` -To evaluate a camera policy, use the `-Camera` task with `presets=newton_mjwarp,newton_renderer`, and add +To evaluate a camera policy, use the `-Camera` task with `presets=newton_mjwarp,newton_warp`, and add `--agent rsl_rl_ppo_cfg_entry_point` for one trained from scratch. Do not pass `--deterministic`. On this pin it also enables Warp-wide deterministic physics, which overflows a diff --git a/docs/SIM2REAL.md b/docs/SIM2REAL.md index 6763cca..fad7ffe 100644 --- a/docs/SIM2REAL.md +++ b/docs/SIM2REAL.md @@ -41,14 +41,14 @@ uv run isaaclab train --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101 uv run isaaclab train --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101 --num_envs 4096 --checkpoint /abs/path/state/model_799.pt --visualizer none presets=newton_mjwarp,sim2real # 3. Distill a camera student from that teacher under the same randomization. -uv run isaaclab train --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101-Camera --num_envs 1024 --checkpoint /abs/path/sim2real_state/model_XXX.pt --visualizer none presets=newton_mjwarp,newton_renderer,sim2real +uv run isaaclab train --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101-Camera --num_envs 1024 --checkpoint /abs/path/sim2real_state/model_XXX.pt --visualizer none presets=newton_mjwarp,newton_warp,sim2real ``` To evaluate in simulation, run play from home starts and count exactly one episode per environment. The sim2real preset keeps its physics randomization during evaluation. ```bash -uv run isaaclab play --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101-Camera --num_envs 1024 --checkpoint /abs/path/distillation/model_XXX.pt --visualizer none --external_callback isaaclab_tutorial.utils.evaluation.install_episode_counter presets=newton_mjwarp,newton_renderer,sim2real +uv run isaaclab play --rl_library rsl_rl --task IsaacTutorial-Place-Vial-SO101-Camera --num_envs 1024 --checkpoint /abs/path/distillation/model_XXX.pt --visualizer none --external_callback isaaclab_tutorial.utils.evaluation.install_episode_counter presets=newton_mjwarp,newton_warp,sim2real ``` ## 2. Physical setup diff --git a/src/isaaclab_tutorial/active_gaze/render_options.py b/src/isaaclab_tutorial/active_gaze/render_options.py index 06cb94f..06dec43 100644 --- a/src/isaaclab_tutorial/active_gaze/render_options.py +++ b/src/isaaclab_tutorial/active_gaze/render_options.py @@ -11,7 +11,7 @@ class CameraOutputCfg(PresetCfg): # Path-traced RGB by default: RTX Minimal mode draws no background or dome light. default = ["rgb"] - newton_renderer = ["rgb"] + newton_warp = ["rgb"] rtpt = ["rgb"] minimal_diffuse_mdl = ["simple_shading_diffuse_mdl"] minimal_diffuse_mdl_shadows = minimal_diffuse_mdl @@ -22,7 +22,7 @@ class CameraOutputCfg(PresetCfg): @configclass class CameraOutputNameCfg(PresetCfg): default = "rgb" - newton_renderer = "rgb" + newton_warp = "rgb" rtpt = "rgb" minimal_diffuse_mdl = "simple_shading_diffuse_mdl" minimal_diffuse_mdl_shadows = minimal_diffuse_mdl @@ -45,7 +45,7 @@ class ShadowsCfg(PresetCfg): class CameraRenderSettingsCfg(PresetCfg): """Author native sample settings directly on each camera's render product.""" - newton_renderer = {} + newton_warp = {} _minimal = { "omni:rtx:post:aa:op": ("Token", "none"), "omni:rtx:newDenoiser:enabled": ("Bool", True), @@ -61,6 +61,6 @@ class CameraRenderSettingsCfg(PresetCfg): @configclass class FoviRendererCfg(PresetCfg): # Newton ignores USD lights and lights the scene with its own directional light; shadow rays are opt-in. - newton_renderer = NewtonWarpRendererCfg(render_order="pixel_priority", enable_shadows=True) + newton_warp = NewtonWarpRendererCfg(render_order="pixel_priority", enable_shadows=True) ovrtx = OVRTXRendererCfg(enable_shadows=ShadowsCfg()) default = ovrtx diff --git a/src/isaaclab_tutorial/tasks/place_vial/config/so101/camera_env_cfg.py b/src/isaaclab_tutorial/tasks/place_vial/config/so101/camera_env_cfg.py index 7a31f36..b5e643c 100644 --- a/src/isaaclab_tutorial/tasks/place_vial/config/so101/camera_env_cfg.py +++ b/src/isaaclab_tutorial/tasks/place_vial/config/so101/camera_env_cfg.py @@ -35,7 +35,7 @@ def _camera_renderer_cfg() -> MultiBackendRendererCfg: """Enable the supported shadow settings on both standalone renderers.""" cfg = MultiBackendRendererCfg() - cfg.newton_renderer.enable_shadows = True + cfg.newton_warp.enable_shadows = True cfg.default.enable_shadows = True cfg.ovrtx.enable_shadows = True return cfg diff --git a/tests/active_gaze/test_numbered.py b/tests/active_gaze/test_numbered.py index cd9b796..0d7b83f 100644 --- a/tests/active_gaze/test_numbered.py +++ b/tests/active_gaze/test_numbered.py @@ -98,8 +98,8 @@ def test_numbered_configuration_keeps_the_target_in_the_critic_only(): from isaaclab_tutorial.active_gaze.configuration import compose, describe, field_of_view_deg - plain, plain_agent, _ = compose(["presets=nearest,newton_renderer"]) - numbered, numbered_agent, _ = compose(["presets=numbered,newton_renderer"]) + plain, plain_agent, _ = compose(["presets=nearest,newton_warp"]) + numbered, numbered_agent, _ = compose(["presets=numbered,newton_warp"]) assert ( describe(plain, plain_agent)["goal"] == "nearest" and describe(numbered, numbered_agent)["goal"] == "numbered" ) @@ -115,7 +115,7 @@ def test_numbered_configuration_keeps_the_target_in_the_critic_only(): assert numbered.observations.critic.numbered_goal is not None assert isinstance(numbered.scene.vial.spawn, MultiAssetSpawnerCfg) assert [vial.vial_number for vial in numbered.scene.vial.spawn.assets_cfg] == [1, 2, 3, 4] - language = compose(["presets=dino_language,newton_renderer"])[0] + language = compose(["presets=dino_language,newton_warp"])[0] assert language.scene.eye.data_types == ["rgb"] assert language.observations.vision.tokens.params["data_type"] == "rgb" diff --git a/tests/active_gaze/test_presets.py b/tests/active_gaze/test_presets.py index a67c177..46a2d36 100644 --- a/tests/active_gaze/test_presets.py +++ b/tests/active_gaze/test_presets.py @@ -48,7 +48,7 @@ def test_resume_replays_saved_overrides_and_lets_new_values_replace_them(): def test_resume_preserves_explicit_opt_outs(): - explicit, agent, saved = saved_run(["presets=nearest,no_gaze_supervision,uniform,newton_renderer"]) + explicit, agent, saved = saved_run(["presets=nearest,no_gaze_supervision,uniform,newton_warp"]) restored, restored_agent, _ = compose(saved=saved) assert explicit.to_dict() == restored.to_dict() assert agent.to_dict() == restored_agent.to_dict() diff --git a/tests/active_gaze/test_rendering.py b/tests/active_gaze/test_rendering.py index 8cb08eb..18cc01e 100644 --- a/tests/active_gaze/test_rendering.py +++ b/tests/active_gaze/test_rendering.py @@ -74,7 +74,7 @@ def test_minimal_requires_ovrtx(): from isaaclab_tutorial.active_gaze.configuration import compose with pytest.raises(ValueError, match="unsupported types"): - compose(["presets=minimal_full_mdl", "env.scene.eye.renderer_cfg=newton_renderer"]) + compose(["presets=minimal_full_mdl", "env.scene.eye.renderer_cfg=newton_warp"]) @pytest.mark.parametrize("mode, output, shadows", [MODES[0], MODES[-1]]) diff --git a/tests/test_config.py b/tests/test_config.py index df66c1c..49f0d5f 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -37,7 +37,7 @@ def _state(*presets): def _camera(*presets): - return resolve_presets(SO101VialCameraEnvCfg(), ["newton_mjwarp", "newton_renderer", *presets]) + return resolve_presets(SO101VialCameraEnvCfg(), ["newton_mjwarp", "newton_warp", *presets]) def test_tasks_are_registered_with_rsl_rl_entry_points(): From 1eda8a130f9737013cca446ed820b41aad9bb770 Mon Sep 17 00:00:00 2001 From: nblauch Date: Mon, 23 Nov 2026 23:08:35 -0800 Subject: [PATCH 27/30] Pin OVRTX to the release Isaac Lab uses Isaac Lab moved to ovrtx 0.7.0 and ovstage 0.4.0. --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index c02ebc6..3c85d00 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,7 +30,7 @@ view-so101-resets = "isaaclab_tutorial.tasks.place_vial.reset.generator:view_mai fovi = ["isaaclab[fovi]", "transformers==5.19.0", "imageio-ffmpeg>=0.5"] leapp = ["leapp==0.7.2"] ovphysx = ["ovphysx"] -ovrtx = ["ovrtx==0.5.0.377615", "ovstage==0.1.1.355824"] +ovrtx = ["ovrtx==0.7.0.1794596436", "ovstage==0.4.0.1794520352"] video = ["isaaclab[video]"] viser = ["isaaclab[viser]"] # Temporary compatibility pin: Isaac Lab's logger calls wandb.util.generate_id, From b1f7100a7ca745ab5ffda23ece74996f388bfbf6 Mon Sep 17 00:00:00 2001 From: nblauch Date: Mon, 23 Nov 2026 23:08:46 -0800 Subject: [PATCH 28/30] Describe the gaze as isaaclab_fovi's in the ActiveGaze guide The guide names the action, observation and teacher the task now takes from isaaclab_fovi, the tracked mount of the sim2real preset, and the Newton renderer's current preset name. --- docs/ACTIVE_GAZE.md | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/ACTIVE_GAZE.md b/docs/ACTIVE_GAZE.md index decd758..1ab3c1e 100644 --- a/docs/ACTIVE_GAZE.md +++ b/docs/ACTIVE_GAZE.md @@ -28,13 +28,16 @@ The critic sees the privileged state, including the target opening, in every var - The camera is an ideal square pinhole; the retina spans its field of view, so the gaze can reach anything the camera sees. +- The gaze is `isaaclab_fovi`'s: `GazeAction` moves it in software, turning the retina within the fixed camera's + image, `gaze_state` observes it, and `gaze_teacher_labels` supervises it. - Two of the eight actions move the gaze (tilt, pan). An action of 1 moves an angle by 0.1 field radii, a field radius being half the retina's field of view, and the gaze stays within 1 field radius of the optical axis. The actor observes the gaze and its velocity in the same units. -- A teacher supervises the gaze actions: it looks at the vial until the grasp, then at the goal. The PPO loss adds - the teacher's gaze actions as labels (`agent.algorithm.oracle_weight`, 1.0); `presets=no_gaze_supervision` - turns this off. -- Episodes start the gaze at random, on the vial or the goal, or a few degrees off either. +- The teacher looks at a point in the world that the task picks: the vial until the grasp, then the goal. The PPO + loss adds the teacher's gaze actions as labels (`agent.algorithm.oracle_weight`, 1.0); + `presets=no_gaze_supervision` turns this off. +- Episodes start the gaze at random, on the vial or the goal, or a few degrees off either + (`env.actions.gaze.mixed_resets`). ## Train @@ -42,16 +45,17 @@ The task trains with its own script, because action chunking wraps the environme needs its own runner: ```bash -uv run --extra fovi python -m isaaclab_tutorial.active_gaze.train train --output runs/numbered presets=numbered,newton_renderer +uv run --extra fovi python -m isaaclab_tutorial.active_gaze.train train --output runs/numbered presets=numbered,newton_warp ``` Every argument that is not a script option is an Isaac Lab configuration override, as with `isaaclab train`. Useful presets and overrides: -- `newton_renderer` renders with Newton; the default is OVRTX path-traced RGB (`--extra ovrtx`). The faster +- `newton_warp` renders with Newton; the default is OVRTX path-traced RGB (`--extra ovrtx`). The faster OVRTX Minimal modes (`minimal_full_mdl`, `minimal_diffuse_mdl`, with `_shadows` variants) draw no background. - `sim2real` adds the tutorial's physical randomization, scene colours, a camera mount that moves each episode, - and photometric variation of the retina. On `dino_language`, the actor also learns to predict the mount's move. + and photometric variation of the retina. The gaze stays relative to the moved mount, and its teacher aims from + it (`mount="tracked"`). On `dino_language`, the actor also learns to predict the mount's move. - `chunking` makes each policy decision a plan of three control steps. - `env.observations.vision.tokens.params.num_layers=N` runs only the first `N` DINO layers, to cut the cost of perception while keeping pretrained features. @@ -65,7 +69,7 @@ value, and `presets=…,finetune` warm-starts at a lower learning rate. Add `--l ```bash uv run --extra fovi python -m isaaclab_tutorial.active_gaze.train play --checkpoint runs/numbered/model_4999.pt --output runs/numbered_play -uv run --extra fovi python -m isaaclab_tutorial.active_gaze.train inspect --num_envs 4 --output runs/inspect presets=numbered,newton_renderer +uv run --extra fovi python -m isaaclab_tutorial.active_gaze.train inspect --num_envs 4 --output runs/inspect presets=numbered,newton_warp ``` `play` builds the run's saved configuration; a `presets=` argument would replace the saved preset list. Both write From 00a9570e8b1b43a664bfb9d9ef133e41c8775bc2 Mon Sep 17 00:00:00 2001 From: nblauch Date: Mon, 23 Nov 2026 23:15:32 -0800 Subject: [PATCH 29/30] Build Isaac Lab from the binocular gaze pull request isaaclab_fovi merged into Isaac Lab's main branch. The gaze teacher's world-point target, which this task uses, is under review in isaac-sim/IsaacLab#9183, so Isaac Lab is built from that pull request, and uv.lock is regenerated. The lock holds the pull request's head as of now (030f94b), which does not yet have the teacher's world-point target or the camera's image-free pose read. Until they land there and the lock is refreshed, the ActiveGaze environment does not build from this lock. The Microduck tasks target Isaac Lab 3.0.0 and do not run on this Isaac Lab. --- docs/ACTIVE_GAZE.md | 9 +- pyproject.toml | 6 +- uv.lock | 267 ++++++++++++++++++-------------------------- 3 files changed, 119 insertions(+), 163 deletions(-) diff --git a/docs/ACTIVE_GAZE.md b/docs/ACTIVE_GAZE.md index 1ab3c1e..5936639 100644 --- a/docs/ACTIVE_GAZE.md +++ b/docs/ACTIVE_GAZE.md @@ -4,9 +4,12 @@ `isaaclab_fovi` package. Its retina samples densely where it looks and sparsely in the periphery, and the policy moves the gaze while it moves the arm. -The task needs the `fovi` extra. Until the `isaaclab_fovi` pull request merges, the tutorial is pinned to that pull -request's branch of Isaac Lab, and one of that branch's Git LFS files is missing, so skip LFS downloads when -syncing: +The task needs the `fovi` extra. `isaaclab_fovi` is on Isaac Lab's main branch, and the gaze teacher's world-point +target is still under review there (isaac-sim/IsaacLab#9183). Until that merges, the tutorial builds Isaac Lab from +that pull request. Two things follow: + +- The Microduck tasks, written for Isaac Lab 3.0.0, do not run in this environment. +- Isaac Lab's main branch references a Git LFS file its server does not have, so skip LFS downloads when syncing: ```bash GIT_LFS_SKIP_SMUDGE=1 uv sync --locked --extra fovi diff --git a/pyproject.toml b/pyproject.toml index 3c85d00..07763e4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,9 +48,9 @@ prerelease = "allow" environments =["sys_platform == 'linux' and platform_machine == 'x86_64'", "sys_platform == 'win32' and platform_machine == 'AMD64'", "sys_platform == 'linux' and platform_machine == 'aarch64'"] [tool.uv.sources] -# The ActiveGaze task needs isaaclab_fovi, which is under review in Isaac Lab (isaac-sim/IsaacLab#9074). Until it -# merges, the tutorial builds Isaac Lab from that pull request. -isaaclab = { git = "https://github.com/isaac-sim/IsaacLab.git", rev = "refs/pull/9074/head", subdirectory = "tools/wheel_builder" } +# The ActiveGaze task aims isaaclab_fovi's gaze teacher at a world point, which is under review in Isaac Lab +# (isaac-sim/IsaacLab#9183, on top of #9181). Until it merges, the tutorial builds Isaac Lab from that pull request. +isaaclab = { git = "https://github.com/isaac-sim/IsaacLab.git", rev = "refs/pull/9183/head", subdirectory = "tools/wheel_builder" } ovphysx = { index = "nvidia" } ovrtx = { index = "nvidia" } torch = { index = "pytorch-cu130" } diff --git a/uv.lock b/uv.lock index d46e800..daa764a 100644 --- a/uv.lock +++ b/uv.lock @@ -104,15 +104,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, ] -[[package]] -name = "beartype" -version = "0.23.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/79/34/c0cfdaee9c796c8381439fed0fcab62810753b8b0adb1ec88fa7f41eaa5d/beartype-0.23.1.tar.gz", hash = "sha256:8b805f246b32931c74f2b321ea0939fe5bb2ff43c12a3eff19cc4c854b832e1d", size = 1993714, upload-time = "2026-10-11T05:36:55.251Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1c/cb/2f6aa982e2860c1156830db3da7f823b71784ed7d533ca289ea9b6c6347a/beartype-0.23.1-py3-none-any.whl", hash = "sha256:4461b4dc57e3fdd6c8a8464b22cf118002eea107c33e9fef651c69068ab3cce3", size = 1582101, upload-time = "2026-10-11T05:36:52.431Z" }, -] - [[package]] name = "blinker" version = "1.9.0" @@ -655,15 +646,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4a/b9/98c6cad41de1023055c5d4bae7191ef258b192a36a1d3497bc9a12777abb/fast_sugiyama-0.5.3-cp311-abi3-win_amd64.whl", hash = "sha256:a222fecca64a9db6b60dcf02fb9b3b8d69b9e9e7f592f70e830965899d612d78", size = 231425, upload-time = "2026-03-10T16:51:22.42Z" }, ] -[[package]] -name = "fastcore" -version = "2.2.44" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ff/3e/4922745d9221efe50bbc3c4e9a8e23879305ac512b89d248e9d7cb2dd86c/fastcore-2.2.44.tar.gz", hash = "sha256:65503dc894e0c75e37fd22ccfdebd2a708f911cb20bcb22983f1516e23b75850", size = 144872, upload-time = "2026-11-16T05:10:47.345Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ac/3f/2f21fb6b00d41fdcb173d10cc9c651e6d70dc3815ae34dc468e870f2fa38/fastcore-2.2.44-py3-none-any.whl", hash = "sha256:978eda3ecbdffb7b4b83b4cfaef54391b5497343138d22d6f11cf3711015222c", size = 151666, upload-time = "2026-11-16T05:10:45.813Z" }, -] - [[package]] name = "fastjsonschema" version = "2.22.2" @@ -723,18 +705,14 @@ wheels = [ [[package]] name = "fovi" -version = "2.6.0" +version = "2.7.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cupy-cuda12x", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "einops", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "fastcore", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "ipython", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "pillow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "plum-dispatch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "pygeodesic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "scikit-image", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "scipy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "torchvision", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, @@ -742,9 +720,9 @@ dependencies = [ { name = "trimesh", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "warp-lang", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/9f/bc/14afdf090c412a543a939051f83a26fa50e46f407100d20707b5d34f8316/fovi-2.6.0.tar.gz", hash = "sha256:9bda8baedbd28e29c679e545dd1813e911667d3dd2c6fb1802c4a92c564d3625", size = 67577289, upload-time = "2026-11-14T18:14:09.39Z" } +sdist = { url = "https://files.pythonhosted.org/packages/b8/0f/787082f650d1ae57a420b868edb4e25953eadc569793003fe5257848b674/fovi-2.7.0.tar.gz", hash = "sha256:506faffe547f31db4a4e4ea24b124d918ad8fc7fc2cdcab6822f6f960b75b74a", size = 67610838, upload-time = "2026-11-23T22:02:14.2Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0b/6c/45b6d1948a23ee352ec63612e0b94a76e7dfa5427b6ff8ddc72b8864b297/fovi-2.6.0-py3-none-any.whl", hash = "sha256:d39b88f4654832b875e4197906e23043edb3dbedbb4a07798e59fd852ce0c42e", size = 312591, upload-time = "2026-11-14T18:14:07.165Z" }, + { url = "https://files.pythonhosted.org/packages/02/e8/70ec00f724b8df673c5b50eb3e9f3de729f09aa4fb5e71caa1cd642fcd50/fovi-2.7.0-py3-none-any.whl", hash = "sha256:46ec4c489af8925bdcf2dc4017847f1cfa34b6eb0ad5378771ba105a451278ec", size = 330543, upload-time = "2026-11-23T22:02:10.796Z" }, ] [[package]] @@ -1035,7 +1013,7 @@ wheels = [ [[package]] name = "isaaclab" version = "3.0.0" -source = { git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead#0e4303ab467a9ceb7ae3afd507a9b810e513a09f" } +source = { git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9183%2Fhead#030f94b2511cac2ac45dd76b134f53a624c2066c" } dependencies = [ { name = "alphashape", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "botocore", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, @@ -1092,11 +1070,13 @@ dependencies = [ [package.optional-dependencies] fovi = [ { name = "fovi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "openexr", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] video = [ { name = "moviepy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] +viser = [ + { name = "viser", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] wandb = [ { name = "wandb", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] @@ -1130,6 +1110,9 @@ ovrtx = [ video = [ { name = "isaaclab", extra = ["video"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] +viser = [ + { name = "isaaclab", extra = ["viser"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] wandb = [ { name = "isaaclab", extra = ["wandb"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "wandb", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, @@ -1146,20 +1129,21 @@ dev = [ [package.metadata] requires-dist = [ { name = "imageio-ffmpeg", marker = "extra == 'fovi'", specifier = ">=0.5" }, - { name = "isaaclab", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead" }, - { name = "isaaclab", extras = ["fovi"], marker = "extra == 'fovi'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead" }, - { name = "isaaclab", extras = ["video"], marker = "extra == 'video'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead" }, - { name = "isaaclab", extras = ["wandb"], marker = "extra == 'wandb'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9074%2Fhead" }, + { name = "isaaclab", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9183%2Fhead" }, + { name = "isaaclab", extras = ["fovi"], marker = "extra == 'fovi'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9183%2Fhead" }, + { name = "isaaclab", extras = ["video"], marker = "extra == 'video'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9183%2Fhead" }, + { name = "isaaclab", extras = ["viser"], marker = "extra == 'viser'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9183%2Fhead" }, + { name = "isaaclab", extras = ["wandb"], marker = "extra == 'wandb'", git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9183%2Fhead" }, { name = "leapp", marker = "extra == 'leapp'", specifier = "==0.7.2" }, { name = "ovphysx", marker = "extra == 'ovphysx'", index = "https://pypi.nvidia.com/" }, - { name = "ovrtx", marker = "extra == 'ovrtx'", specifier = "==0.5.0.377615", index = "https://pypi.nvidia.com/" }, - { name = "ovstage", marker = "extra == 'ovrtx'", specifier = "==0.1.1.355824" }, + { name = "ovrtx", marker = "extra == 'ovrtx'", specifier = "==0.7.0.1794596436", index = "https://pypi.nvidia.com/" }, + { name = "ovstage", marker = "extra == 'ovrtx'", specifier = "==0.4.0.1794520352" }, { name = "torch", specifier = "==2.11.0", index = "https://download.pytorch.org/whl/cu130" }, { name = "torchvision", specifier = "==0.26.0", index = "https://download.pytorch.org/whl/cu130" }, { name = "transformers", marker = "extra == 'fovi'", specifier = "==5.19.0" }, { name = "wandb", marker = "extra == 'wandb'", specifier = "==0.26.1" }, ] -provides-extras = ["fovi", "leapp", "ovphysx", "ovrtx", "video", "wandb"] +provides-extras = ["fovi", "leapp", "ovphysx", "ovrtx", "video", "viser", "wandb"] [package.metadata.requires-dev] dev = [ @@ -1507,6 +1491,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, ] +[[package]] +name = "msgspec" +version = "0.22.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d0/e6/6dcf9306ff3c5e486578f3bf29ed11dfbdbbc2a8bf0caf7e07d392887fda/msgspec-0.22.0.tar.gz", hash = "sha256:0a13624a4969159fe35d8c2a3d377b2b61bbd8585e327440d5e52725affcce38", size = 343188, upload-time = "2026-09-29T14:14:11.422Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/a5/65de05f8804492f76ea121b21a125cdf1d97ec461c677bfa0ba354d6fbdd/msgspec-0.22.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b5a169b5b03f0f2c7a296c002647db1dab75d2cd501bca34e32b71cab0261b56", size = 224035, upload-time = "2026-09-29T14:12:40.876Z" }, + { url = "https://files.pythonhosted.org/packages/4a/cc/aa1a47f8c92280d37498a5ea56a2a36606d034383e3e6472d64cbb56cf85/msgspec-0.22.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:99c401861c5bb3a57f7d6423ea7ed4352cd57aa3f04f4fbe9f3e3e4564a10f08", size = 230377, upload-time = "2026-09-29T14:12:42.796Z" }, + { url = "https://files.pythonhosted.org/packages/61/50/f8bcdb3d613a4a4b92704297a12eba5c985cf572a64ee1a004d265759c69/msgspec-0.22.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:08826f5e5b0fa2f7a88592c396a243cfcc63d37e19f9d4fbe3b3f1be2fbdc404", size = 237390, upload-time = "2026-09-29T14:12:44.282Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8a/473fa423f8fdd1b810b8652594323d7301df6920b62844d860daa0feff34/msgspec-0.22.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:21460f54cee9208239b1a8421fdf25bffc77293e1daba88f585711ad839b9758", size = 227733, upload-time = "2026-09-29T14:12:45.839Z" }, + { url = "https://files.pythonhosted.org/packages/03/1d/272ce23adae6c71b3f763aed3ee6e115cccc56124ed8ee0e3e3d2681e2c8/msgspec-0.22.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:cfc3d9557de9c806318725b702f3e664db33167bb42892079b693c69893fd33b", size = 236783, upload-time = "2026-09-29T14:12:47.234Z" }, + { url = "https://files.pythonhosted.org/packages/f6/26/29e0b9a8605c8819a3c718158e345a616ac42c092dd7d7ab248c2f2b0a72/msgspec-0.22.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0b25dcbc108783cb72503ed705b9fbb8c3cb02ee5801923f44b5f038c91cc365", size = 232728, upload-time = "2026-09-29T14:12:48.792Z" }, + { url = "https://files.pythonhosted.org/packages/e1/a6/99597c281d716da6c662b48dcc3f734669f716b41d5df2af367dac9e7c21/msgspec-0.22.0-cp312-cp312-win_amd64.whl", hash = "sha256:6ad64f5c260866b0d543f89f50cee43628989c1433c5de7ce820281fa28a2611", size = 192885, upload-time = "2026-09-29T14:12:50.274Z" }, +] + [[package]] name = "mujoco" version = "3.17.0" @@ -1587,7 +1586,7 @@ wheels = [ [[package]] name = "newton" version = "1.9.0.dev0" -source = { git = "https://github.com/newton-physics/newton.git?rev=3f428bf1a7183d3d9a10cc17241e8a9eac3841eb#3f428bf1a7183d3d9a10cc17241e8a9eac3841eb" } +source = { git = "https://github.com/newton-physics/newton.git?rev=d31603ff5e8389d1d6b2a5daef6ea2cb074c26ff#d31603ff5e8389d1d6b2a5daef6ea2cb074c26ff" } dependencies = [ { name = "warp-lang", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] @@ -1897,22 +1896,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9f/c4/35a6e0a35aa72420e75dc28d54b24beaff79bcad150423e47c67d2ad8773/open3d-0.19.0-cp312-cp312-win_amd64.whl", hash = "sha256:665839837e1d3a62524804c31031462c3b548a2b6ed55214e6deb91522844f97", size = 69169961, upload-time = "2025-01-08T07:27:35.392Z" }, ] -[[package]] -name = "openexr" -version = "3.5.4" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5f/c0/422dd868e5f94f7885bd9c12f2dc6fabbeb4a8cd0b002bc097024dae861d/openexr-3.5.4.tar.gz", hash = "sha256:8b5b06f08b05d512fe52fa18c5c2f27c2141938149da23d056094bc392f15db8", size = 26300935, upload-time = "2026-11-12T16:45:00.975Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/b9/c9e228497d81cb810c277116ab4cbeb3d3d1826b1b21fcc2f8aafa771ec6/openexr-3.5.4-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:116adcc66a9601048d0ffa7387990bb9d510d1dd0e8cb0ab999b825c1e717277", size = 1593447, upload-time = "2026-11-12T16:44:02.944Z" }, - { url = "https://files.pythonhosted.org/packages/3c/3e/4b08275770fffcb57202762e2f023bfac39754290ba4727198b02d76bf74/openexr-3.5.4-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:6f9644dd8b96eb314498c9849684f57adf67bde72f8b0193929bf29adff03b70", size = 1786567, upload-time = "2026-11-12T16:44:05.014Z" }, - { url = "https://files.pythonhosted.org/packages/17/b3/4a25166ed8bc29aee9d01f2d9f007ef15f9d3ea4075b19667879c149e30b/openexr-3.5.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b1c2658516cc199fb31baf0565e422dfa6df8077ba2336c3acc170c45e251a08", size = 2607932, upload-time = "2026-11-12T16:44:06.641Z" }, - { url = "https://files.pythonhosted.org/packages/76/37/a0e9a6a8a1cf7ec7efcb2cb7fbdaf55cd2a4349a26343a75fb7ac83e3e54/openexr-3.5.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a586a32ebb01fd87a54286ec9f29f5583a5176c019ebbbe6fd832a7188cefcd1", size = 2825749, upload-time = "2026-11-12T16:44:08.373Z" }, - { url = "https://files.pythonhosted.org/packages/68/15/7ff3e6a17444d70669085e21487e546fd6fe298b2eb653eccbd4e0c3b6a1/openexr-3.5.4-cp312-cp312-win_amd64.whl", hash = "sha256:d55fe6b60e923917bc5104808df2d515a82b0fb053b0e038788626f0fd2b780f", size = 1186933, upload-time = "2026-11-12T16:44:10.017Z" }, -] - [[package]] name = "orjson" version = "3.12.0" @@ -1929,36 +1912,37 @@ wheels = [ [[package]] name = "ovphysx" -version = "0.5.11" +version = "0.8.0.43443703471" source = { registry = "https://pypi.nvidia.com/" } dependencies = [ { name = "ovstage", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "warp-lang", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] wheels = [ - { url = "https://pypi.nvidia.com/ovphysx/ovphysx-0.5.11-py3-none-manylinux_2_35_aarch64.whl", hash = "sha256:fff7e648fe14989e6ae51b7c6e6c516beab0b4f0749110c32c5a142b31525946" }, - { url = "https://pypi.nvidia.com/ovphysx/ovphysx-0.5.11-py3-none-manylinux_2_35_x86_64.whl", hash = "sha256:4e6f904d9858674ecf4fccc2a462d048f9eeb7d20724a7eafd294bf5ccac9a2c" }, - { url = "https://pypi.nvidia.com/ovphysx/ovphysx-0.5.11-py3-none-win_amd64.whl", hash = "sha256:409637574296f2f4c9a377444c2072c5539a8a5adf88b9536c02fdff6af387be" }, + { url = "https://pypi.nvidia.com/ovphysx/ovphysx-0.8.0.43443703471-py3-none-manylinux_2_35_aarch64.whl", hash = "sha256:97823201da0cbe73014ae5218fdcb2bbd22bd6b48ce4e27b0fba39a07771835e" }, + { url = "https://pypi.nvidia.com/ovphysx/ovphysx-0.8.0.43443703471-py3-none-manylinux_2_35_x86_64.whl", hash = "sha256:0b3186bae349e003a5e4e70641c2b349935ceb1d67342e2fcfe19960bab43ddd" }, + { url = "https://pypi.nvidia.com/ovphysx/ovphysx-0.8.0.43443703471-py3-none-win_amd64.whl", hash = "sha256:25d9004bcb6b649e673cd0a96ea704bb3ad3c3b7a4178b521f716faa76eab841" }, ] [[package]] name = "ovrtx" -version = "0.5.0.377615" +version = "0.7.0.1794596436" source = { registry = "https://pypi.nvidia.com/" } wheels = [ - { url = "https://pypi.nvidia.com/ovrtx/ovrtx-0.5.0.377615-py3-none-manylinux_2_35_aarch64.whl", hash = "sha256:77371fc8cfa6aceb660abe0a11978a4c7b608da7214ca22a5df1a3dd64111258" }, - { url = "https://pypi.nvidia.com/ovrtx/ovrtx-0.5.0.377615-py3-none-manylinux_2_35_x86_64.whl", hash = "sha256:e57c266a3a0b7b8a7e17dbecf75f559caf5f1dac2c9f58c1424b0e7ac10a16a2" }, - { url = "https://pypi.nvidia.com/ovrtx/ovrtx-0.5.0.377615-py3-none-win_amd64.whl", hash = "sha256:36a79af1f9613e0a66fe10d59e0ab5b2e0c8552bdbf0f930a9ec5282875fdc4b" }, + { url = "https://pypi.nvidia.com/ovrtx/ovrtx-0.7.0.1794596436-py3-none-manylinux_2_35_aarch64.whl", hash = "sha256:15f588d2deeaa0643a013074b57e1b62ea81138d5118da7c38f07e5a5767a833" }, + { url = "https://pypi.nvidia.com/ovrtx/ovrtx-0.7.0.1794596436-py3-none-manylinux_2_35_x86_64.whl", hash = "sha256:1e36c2e6d892650cdc46edb58ebfd668addb5b7fd3b0b15fe9f32b1b9b12c0ee" }, + { url = "https://pypi.nvidia.com/ovrtx/ovrtx-0.7.0.1794596436-py3-none-win_amd64.whl", hash = "sha256:fc5407494f95c91d01692913d7424b6cbe00d64242589989352971aebfc4170b" }, ] [[package]] name = "ovstage" -version = "0.1.1.355824" +version = "0.4.0.1794520352" source = { registry = "https://pypi.org/simple" } wheels = [ - { url = "https://files.pythonhosted.org/packages/05/fd/a1650d436b3c304720236178848d4e7ad523a2b9f2b76918d7b902934cac/ovstage-0.1.1.355824-py3-none-manylinux_2_35_aarch64.whl", hash = "sha256:046aa360959bf5344d912470aaa11d3ec1fc750e28816e5239ce0438864c9863", size = 59799282, upload-time = "2026-08-05T20:07:10.538Z" }, - { url = "https://files.pythonhosted.org/packages/8d/2e/e5d03719d9ab8e412187be84efe11bc6b912eca02bd8dfb09a1bf522bbe4/ovstage-0.1.1.355824-py3-none-manylinux_2_35_x86_64.whl", hash = "sha256:b4affd9e5b23620ec71901a164df4ae373d25de2c76b9fae4d193d97aa2df0ec", size = 64302147, upload-time = "2026-08-05T20:06:18.013Z" }, - { url = "https://files.pythonhosted.org/packages/fb/d0/ff9124f524ffadc87f8893e99de1679e7c517ca6ceb60e0b870a284b71a3/ovstage-0.1.1.355824-py3-none-win_amd64.whl", hash = "sha256:fc8ae7fe950aa2ff8fd24643047f7156ffa1b9b384ce3f024ee2193929e21a3b", size = 35031430, upload-time = "2026-08-05T20:05:29.88Z" }, + { url = "https://files.pythonhosted.org/packages/c4/5f/68eb2aa9649d3fc46391b3f08bd7f93e86c4d4c0c51f9b2ab048caecf619/ovstage-0.4.0.1794520352-py3-none-manylinux_2_35_aarch64.whl", hash = "sha256:b63c91a11d04e07c30b7ee31647e2a00918f0b1ded3dd4e939326d31cda4e462", size = 59678093, upload-time = "2026-11-13T07:22:36.065Z" }, + { url = "https://files.pythonhosted.org/packages/19/26/add7902c6f0d78358a736d4cd993cb1cfb6e5e627d0b4c3c9d90b14e8192/ovstage-0.4.0.1794520352-py3-none-manylinux_2_35_x86_64.whl", hash = "sha256:7473a79763af4f8fe8dc70cbd4d99468d822a8f96a0c58891c25801390958f0a", size = 62435549, upload-time = "2026-11-13T07:22:03.287Z" }, + { url = "https://files.pythonhosted.org/packages/2f/05/b1792a891ebda88345716f01e7260410063e9bdbd955a5b3dffb0bd513ae/ovstage-0.4.0.1794520352-py3-none-win_amd64.whl", hash = "sha256:c611727f27ba21222649137ffaed83c35ece44374e8e6686c660d1fa21b2d4ab", size = 37822368, upload-time = "2026-11-13T07:23:03.906Z" }, ] [[package]] @@ -2094,22 +2078,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] -[[package]] -name = "plum-dispatch" -version = "2.10.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "beartype", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "rich", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/dc/75/807b02f339906867de07baaecd3519fe8704df013a27ae0a57250ed461d3/plum_dispatch-2.10.1.tar.gz", hash = "sha256:93aa1ec5c4683c0777b9d7d1ccc0b31e0e82f38399116345b4ed8d0fb67cc66e", size = 250842, upload-time = "2026-09-07T17:38:44.9Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b9/c3/d8793642ce7d29ea15cc39c10185ef126a27fcb8ea230154978221deb4b2/plum_dispatch-2.10.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a5b6a2474f53b23cd07254c2ad286fc8371a3c4ed17dee72794eac9c3a6873db", size = 334557, upload-time = "2026-09-07T17:38:34.857Z" }, - { url = "https://files.pythonhosted.org/packages/41/c7/3544b2bf05aa9e1a1b45981d21da5e5d5c135fcc2da0ee1040f73512662f/plum_dispatch-2.10.1-cp312-cp312-win_amd64.whl", hash = "sha256:ae2f76ce97bcbf1d7038e7c352180cbb35c90c23ea0848e2924f35133fb0f223", size = 245830, upload-time = "2026-09-07T17:38:36.228Z" }, - { url = "https://files.pythonhosted.org/packages/55/9f/0adfb5a90d65233b764cb1b07244b72ded1db7cfc66955418544d0da2e38/plum_dispatch-2.10.1-py3-none-any.whl", hash = "sha256:dac63fd5ada8ae8045aefed127dacda0ba02db2635876b12f4e1dfaf6db73f39", size = 49430, upload-time = "2026-09-07T17:38:43.589Z" }, -] - [[package]] name = "pre-commit" version = "4.6.2" @@ -2257,19 +2225,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fa/04/c81d4841331c2178b6fb09ae225425e110ed72d990c9fe556c4ec03d1013/pydantic_core-2.46.5-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e24d8f05fa2d28513d94e877e9c75ad66175376209b3977f916e240e623193c", size = 2111034, upload-time = "2026-08-28T10:01:07.345Z" }, ] -[[package]] -name = "pygeodesic" -version = "0.1.11" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/66/33/174106049bdea633e537f14fc39ebc68f2f97994591911b4e64e4870803c/pygeodesic-0.1.11.tar.gz", hash = "sha256:a9b54eb20d57f5499d8b2a4a67ece675a44c6fc8d00b11e8c14c8c99edeee5ed", size = 36275, upload-time = "2024-11-26T20:54:23.088Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6b/3d/972e2207d5845b6129f553376010b0bddecc2b1b74799e186d97e0f326d6/pygeodesic-0.1.11-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:495101cd634df7afe108a63419a864c77098c490608934c642b9d6eabc946ec1", size = 1016926, upload-time = "2024-11-26T20:54:10.904Z" }, - { url = "https://files.pythonhosted.org/packages/e6/0b/03af381ad00eaf56dde8156d48c0c4b7c5b928dd128221619d8b3cfea901/pygeodesic-0.1.11-cp312-cp312-win_amd64.whl", hash = "sha256:585e6fd35babbda2fa9b87f23d05e0ec26e1e416e069997ed137ac04b94f05b9", size = 1335932, upload-time = "2024-11-26T20:54:12.072Z" }, -] - [[package]] name = "pyglet" version = "2.1.16" @@ -2473,15 +2428,15 @@ wheels = [ [[package]] name = "rich" -version = "15.0.0" +version = "14.3.4" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "markdown-it-py", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "pygments", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e9/67/cae617f1351490c25a4b8ac3b8b63a4dda609295d8222bad12242dfdc629/rich-14.3.4.tar.gz", hash = "sha256:817e02727f2b25b40ef56f5aa2217f400c8489f79ca8f46ea2b70dd5e14558a9", size = 230524, upload-time = "2026-04-11T02:57:45.419Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, + { url = "https://files.pythonhosted.org/packages/b3/76/6d163cfac87b632216f71879e6b2cf17163f773ff59c00b5ff4900a80fa3/rich-14.3.4-py3-none-any.whl", hash = "sha256:07e7adb4690f68864777b1450859253bed81a99a31ac321ac1817b2313558952", size = 310480, upload-time = "2026-04-11T02:57:47.484Z" }, ] [[package]] @@ -2501,8 +2456,8 @@ wheels = [ [[package]] name = "rsl-rl-lib" -version = "5.5.1" -source = { registry = "https://pypi.org/simple" } +version = "5.5.2" +source = { git = "https://github.com/leggedrobotics/rsl_rl.git?rev=ea39cc2ae4a615c3d70d4ed9055d8b6e3b4c8acd#ea39cc2ae4a615c3d70d4ed9055d8b6e3b4c8acd" } dependencies = [ { name = "gitpython", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, @@ -2512,10 +2467,6 @@ dependencies = [ { name = "tensordict", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/97/0e/142a31e8124255ec9276516c49c6fbe1497f2146ea384a92b81d23e3c525/rsl_rl_lib-5.5.1.tar.gz", hash = "sha256:50129065b35c69735ea197343321145a400af8c1b5fe9a28116fdaf1890fab43", size = 68077, upload-time = "2026-09-09T11:28:51.656Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f7/d3/0d4d446c61cb61377802c9e4366cfab8a6c378b9dbcaaad376dcc152c03c/rsl_rl_lib-5.5.1-py3-none-any.whl", hash = "sha256:bdb6382e21c62ddc2b47a37f39318486d0dfde234c7d446bfd42be482ecbd6ea", size = 100035, upload-time = "2026-09-09T11:28:50.331Z" }, -] [[package]] name = "rtree" @@ -2567,29 +2518,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" }, ] -[[package]] -name = "scikit-image" -version = "0.26.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "imageio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "lazy-loader", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "networkx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "pillow", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "scipy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, - { name = "tifffile", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a1/b4/2528bb43c67d48053a7a649a9666432dc307d66ba02e3a6d5c40f46655df/scikit_image-0.26.0.tar.gz", hash = "sha256:f5f970ab04efad85c24714321fcc91613fcb64ef2a892a13167df2f3e59199fa", size = 22729739, upload-time = "2025-12-20T17:12:21.824Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b3/2b/c70120a6880579fb42b91567ad79feb4772f7be72e8d52fec403a3dde0c6/scikit_image-0.26.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4c717490cec9e276afb0438dd165b7c3072d6c416709cc0f9f5a4c1070d23a44", size = 13084214, upload-time = "2025-12-20T17:10:57.468Z" }, - { url = "https://files.pythonhosted.org/packages/f4/a2/70401a107d6d7466d64b466927e6b96fcefa99d57494b972608e2f8be50f/scikit_image-0.26.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7df650e79031634ac90b11e64a9eedaf5a5e06fcd09bcd03a34be01745744466", size = 13561683, upload-time = "2025-12-20T17:10:59.49Z" }, - { url = "https://files.pythonhosted.org/packages/13/a5/48bdfd92794c5002d664e0910a349d0a1504671ef5ad358150f21643c79a/scikit_image-0.26.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cefd85033e66d4ea35b525bb0937d7f42d4cdcfed2d1888e1570d5ce450d3932", size = 14112147, upload-time = "2025-12-20T17:11:02.083Z" }, - { url = "https://files.pythonhosted.org/packages/ee/b5/ac71694da92f5def5953ca99f18a10fe98eac2dd0a34079389b70b4d0394/scikit_image-0.26.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3f5bf622d7c0435884e1e141ebbe4b2804e16b2dd23ae4c6183e2ea99233be70", size = 14661625, upload-time = "2025-12-20T17:11:04.528Z" }, - { url = "https://files.pythonhosted.org/packages/23/4d/a3cc1e96f080e253dad2251bfae7587cf2b7912bcd76fd43fd366ff35a87/scikit_image-0.26.0-cp312-cp312-win_amd64.whl", hash = "sha256:abed017474593cd3056ae0fe948d07d0747b27a085e92df5474f4955dd65aec0", size = 11911059, upload-time = "2025-12-20T17:11:06.61Z" }, -] - [[package]] name = "scikit-learn" version = "1.9.0" @@ -2784,18 +2712,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/32/d5/f9a850d79b0851d1d4ef6456097579a9005b31fea68726a4ae5f2d82ddd9/threadpoolctl-3.6.0-py3-none-any.whl", hash = "sha256:43a0b8fd5a2928500110039e43a5eed8480b918967083ea48dc3ab9f13c4a7fb", size = 18638, upload-time = "2025-03-13T13:49:21.846Z" }, ] -[[package]] -name = "tifffile" -version = "2026.11.16" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d6/e1/f09384869bcf78bae3a794a86d8a90753fb2a6f4646c07ec941ff629cd33/tifffile-2026.11.16.tar.gz", hash = "sha256:d9c246d464f1c3ca9ab62c5225b3ff45578f33629029dbbd9f62f4e901702726", size = 462802, upload-time = "2026-11-17T03:35:19.648Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cf/3a/483491be6f7eb070d1c22b1182bbbc0243e85bf5903fafe3f80b6aeb3dba/tifffile-2026.11.16-py3-none-any.whl", hash = "sha256:d2103c2537f185868f0a880eceba590b316aa1981bd76d91028e5f2eb0e1a6e6", size = 279737, upload-time = "2026-11-17T03:35:18.375Z" }, -] - [[package]] name = "tokenizers" version = "0.23.3" @@ -2999,6 +2915,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/40/4c/eb2f52aeeaf30dbd073d315a251a63ae2b8263171ec4428c135140cb0802/virtualenv-21.7.4-py3-none-any.whl", hash = "sha256:376ec93cd6aab3044fa395d7db226db38043b7b5748948044b2a87168525e843", size = 5324444, upload-time = "2026-08-10T22:54:31.515Z" }, ] +[[package]] +name = "viser" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "imageio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "msgspec", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "numpy", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "requests", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "rich", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "tqdm", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "trimesh", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "websockets", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, + { name = "zstandard", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6a/e5/493ae325f825e9853c2be91b31a35ef8ae54aa229b5082fc8b2372314425/viser-1.1.1.tar.gz", hash = "sha256:0a7ba97dab32b8a7106a2dd216fe1373f2e66e17529b5b43502d33d9b9ac9352", size = 3462064, upload-time = "2026-09-15T08:02:05.297Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/70/6f/6a07b4c90451d6dcd40e1d6e5264f93ff4a03d92c071b1e8a06ec8da5004/viser-1.1.1-py3-none-any.whl", hash = "sha256:f528877553c56e1c01d43b861a1434920a2e7ba4fdc7b2e7ff03721e3c3f5b3d", size = 3623619, upload-time = "2026-09-15T08:02:03.635Z" }, +] + [[package]] name = "wandb" version = "0.26.1" @@ -3048,27 +2985,24 @@ wheels = [ [[package]] name = "websockets" -version = "17.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/75/79/590c5f0cc7d1661195aeefccb0e342b79f4c77d368d526d028821a390332/websockets-17.4.tar.gz", hash = "sha256:09d3939b70df0c8ad2da145ebd50978bccaee1d565e838b0e7921a34d38571eb", size = 191391, upload-time = "2026-10-30T15:10:35.873Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cb/18/6229d6583031ca81d092a0cd887a13a57b402fb555acc323d39b45967eb7/websockets-17.4-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9ae1429ee9e52b139167ed0169757806a27ed7307e942e8c62037a9184e9843b", size = 226321, upload-time = "2026-10-30T15:07:17.563Z" }, - { url = "https://files.pythonhosted.org/packages/b8/61/7aba018fd53873e792a25afe1f4c005518133477b727d7455f2f7550c425/websockets-17.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:51adfc30f467077293a6695d8149bcef501c0728386f3a491054f835dadb60b2", size = 227559, upload-time = "2026-10-30T15:07:18.998Z" }, - { url = "https://files.pythonhosted.org/packages/fb/66/37b207df9cdacaa017aa4487f3a9f2fcd668f6f7cfbafdac5b95ea258ee0/websockets-17.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c564d1e6531611bf87078c28780456ecc75459dcca189629fff2fe7c020d8e67", size = 230386, upload-time = "2026-10-30T15:07:20.431Z" }, - { url = "https://files.pythonhosted.org/packages/ad/f6/87507e11fbae53817a435945273953b5b020589e309fac4fd60527ee5999/websockets-17.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4c792e6cce24d08f92199d907785c9e64f74c357deeed3dbaf7d699ed5930b64", size = 228193, upload-time = "2026-10-30T15:07:22.112Z" }, - { url = "https://files.pythonhosted.org/packages/2f/3d/90a04f0aa989b68fbd2efcd38237420afe2abe5a1cab0b5d7c2aa4f0dbb6/websockets-17.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c44776f82b04e623eb9e1b81fcd17ac6e9808ae1ba5cdf8edce1f7c869a95a9b", size = 226952, upload-time = "2026-10-30T15:07:23.643Z" }, - { url = "https://files.pythonhosted.org/packages/ad/3e/50952af22b8e3e2d03f7e83f0e335851c6b484c3fd88586626fb1c2a34b3/websockets-17.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4d2636a5b61c69e32db0e74b57073dd4a66f1ad195e9398c5f01bba41090deea", size = 224183, upload-time = "2026-10-30T15:07:25.507Z" }, - { url = "https://files.pythonhosted.org/packages/c4/73/2a4a5d9c6bca1127f24af7bf08f406a69052d7f341bc81f08d9e8eb446b4/websockets-17.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cfbbba4597f19ad717f79fd3f2a67ae7efae647bd6a61e14554e1b5ad242a5bf", size = 226991, upload-time = "2026-10-30T15:07:27.355Z" }, - { url = "https://files.pythonhosted.org/packages/68/de/90d96a579839bfe541ef214315df81d2bd519d952847c303328518ffdd02/websockets-17.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:c7b996c02de5e032cb63dc65482b73693b7ecaa586654126be2749ddea239c40", size = 225600, upload-time = "2026-10-30T15:07:28.973Z" }, - { url = "https://files.pythonhosted.org/packages/9d/73/cb4c927e806a73a0377696e031ef3c0db409028cdb2373f96ee863e8df8e/websockets-17.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8c00c5c49f80a588a2c4f99d519d2abed4ce26cdca11273041bc8b7e60af60de", size = 227470, upload-time = "2026-10-30T15:07:32.122Z" }, - { url = "https://files.pythonhosted.org/packages/33/b3/e682b3ea069933044f4bf4809eea0cd83e3a5bdbdff601d1777a9ae90795/websockets-17.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:52c31d123f5adf14dec694c2a4036bf42c523df7cefc641d31cd05653de56e49", size = 225026, upload-time = "2026-10-30T15:07:33.544Z" }, - { url = "https://files.pythonhosted.org/packages/2d/e9/d039757260705e5a265a31c9fff36b0d4567b842ce2b54e5d14369f200bd/websockets-17.4-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:d0acd8191c0e5a61d1c27bfa33b6ec8431982299f5d71c02129aa4f16f182ad0", size = 226007, upload-time = "2026-10-30T15:07:34.954Z" }, - { url = "https://files.pythonhosted.org/packages/db/e7/cb9907fac6f9b28f93beded6efda2953960cd02b633d432acf3451590859/websockets-17.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2a9cb5bbfc33b4ebd3c8d3714d6e09805437f60a14977774e4bd11b5ace46c23", size = 226286, upload-time = "2026-10-30T15:07:36.292Z" }, - { url = "https://files.pythonhosted.org/packages/59/31/d1636ba67ee9232a60033d90483e48686aa3856014e59110f29015f97bd2/websockets-17.4-cp312-cp312-win_amd64.whl", hash = "sha256:dde9cd67f18803949ebf96de8aba12b8ec5ee3115e34c75a2db85a3b0a6c20d5", size = 219561, upload-time = "2026-10-30T15:07:39.19Z" }, - { url = "https://files.pythonhosted.org/packages/56/6f/2e8d5610f6184a2e1720bf8ce256402ed99ad30ea87c461fba5bc4d651d9/websockets-17.4-pp312-pypy312_pp80-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:88ba8a439b2bad97bb69c38db5bf0ec16a061ee834cf0f244089186ee803e899", size = 217489, upload-time = "2026-10-30T15:10:29.999Z" }, - { url = "https://files.pythonhosted.org/packages/29/3a/a05bc57eadcd7e8e072d917888128e6d22e1203984afb21a8da3198982fe/websockets-17.4-pp312-pypy312_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:868744c68e9342768888c7326604da2228c19bb6946aa46b5f9e1ac32ea8d40b", size = 218356, upload-time = "2026-10-30T15:10:31.432Z" }, - { url = "https://files.pythonhosted.org/packages/b2/49/eed86bfb8863093a82cbaa52c9159be1ce2374d5ace6fe1f8e8031567e7d/websockets-17.4-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:829bcaa90be8737c132d9515d6a466e8528e3b3d050d3f3466f36ea94d3beb48", size = 306838, upload-time = "2026-10-30T15:10:32.954Z" }, - { url = "https://files.pythonhosted.org/packages/eb/27/9db924cb0dbf22eade78d98fbae77790f9bf6bc729e6ab29aef9d68e4156/websockets-17.4-py3-none-any.whl", hash = "sha256:c6bd2c9781915592b209160d0f017d4c7c82ad53075e6b0c24d2a89299e7f9e9", size = 212900, upload-time = "2026-10-30T15:10:34.482Z" }, +version = "16.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/21/f7/bc3a25c5ec26ce62ce487690becc2f3710bbc7b33338f005ad390db0b986/websockets-16.1.1.tar.gz", hash = "sha256:db234eda965dcce15df96bb9709f587cd87d4d52aaf0e80e2f34ec04c7670c57", size = 182204, upload-time = "2026-07-17T22:51:05.858Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fe/ed/f1831681fce0e3242346e5458486003c5f124ed69e5e0b847fd029db4973/websockets-16.1.1-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:0f62863e8a00a6d33c3d6566ec0b89f23787b747ffe0c3bc71ec0e76b82c94b1", size = 187137, upload-time = "2026-07-17T22:49:18.323Z" }, + { url = "https://files.pythonhosted.org/packages/6f/79/4ff9dcc1bb46f6b4c536936dde1fd60f9b564f3304307274db97f4c9496d/websockets-16.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8087e82f842609734c9b5a1330464f8e94e346ba0e18c832c08bafa4b0d63c15", size = 188374, upload-time = "2026-07-17T22:49:19.65Z" }, + { url = "https://files.pythonhosted.org/packages/62/c3/5c49b6efb36cab733d23773f6de575e1dba65736ead17d5d2b2a1daef779/websockets-16.1.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2bb5d041a8307d2e18782e7ce777f6fdb1e8c2f5d09291484b18c294b789d9aa", size = 191155, upload-time = "2026-07-17T22:49:21.331Z" }, + { url = "https://files.pythonhosted.org/packages/6e/f6/56ccceda3a4838d18f1d40821480da4775397e8b1eecf4031e20c50e2e90/websockets-16.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1db4de4a0e95673f7545d393c49eeb0c2f18ac1ef93073218c79d5cdb2ee75ab", size = 189011, upload-time = "2026-07-17T22:49:22.889Z" }, + { url = "https://files.pythonhosted.org/packages/86/d6/ad5286241a2bce1107e2798d3bfbd62cf79aee167bdb654f8cb1e9dbf949/websockets-16.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f17dbe07eb3ea7f99e4df9b7e0efefe80fbf30d37a8cc4d561a0aed310bc8847", size = 187766, upload-time = "2026-07-17T22:49:24.339Z" }, + { url = "https://files.pythonhosted.org/packages/bc/67/d65c970b7e347fdca69479beb7811c2060529956730a7a4e3ae7c66b0e31/websockets-16.1.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4b57693728576d84ede0a77987ab16881b783d2cd9f1dc180a8fbbc3f79c4428", size = 185173, upload-time = "2026-07-17T22:49:25.743Z" }, + { url = "https://files.pythonhosted.org/packages/1d/5b/14af3cd4ee69d8ea9baca58f3dc3cfb1ba78332a347fd478cb096549d60e/websockets-16.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2a636ff1e7a5c4edf71ef0e79adae7f25dba93b4fcbe3dc958733477ffeb0eaf", size = 187809, upload-time = "2026-07-17T22:49:27.147Z" }, + { url = "https://files.pythonhosted.org/packages/7b/11/be301710d70de97e3e7b3586e6d492c9c06d6a61bf1c2202c36cf0c75607/websockets-16.1.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:d6bec75c290fe484a8ba4cacdf838501e17c06ecfbbf31eede81a9e431bd7751", size = 186412, upload-time = "2026-07-17T22:49:28.611Z" }, + { url = "https://files.pythonhosted.org/packages/db/07/fe1435bf6fe738a3d3b54dbe0c18dabf12cba4d909ac8b58b539ce27c1f4/websockets-16.1.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:54509b8e92fee4453e152b7558ddef37ce9705a044922f2095a6105e3f80c96f", size = 188290, upload-time = "2026-07-17T22:49:29.965Z" }, + { url = "https://files.pythonhosted.org/packages/8a/0a/81f394aff8efcbb01208c1ced77df0a3c7fcce584a88c7273663697946c2/websockets-16.1.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:f0aa4aad3b1b69ad3fd85a0fd0952ec64331c762bd77ec51cc814170873890b2", size = 185844, upload-time = "2026-07-17T22:49:31.447Z" }, + { url = "https://files.pythonhosted.org/packages/39/5c/dd485b995473f415510251fe9bd708f2d24458f439fce958daf8d66dc7c6/websockets-16.1.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:42290eb6db4ccaca7012656738214f8514082fb6fa40cdeb61bb9a471b52e383", size = 186823, upload-time = "2026-07-17T22:49:33.104Z" }, + { url = "https://files.pythonhosted.org/packages/9d/0b/f78de76ff446f1e66af12b43c48a35f31744de93cfdec2f4ea67d5d7bbf1/websockets-16.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:53260c8930da5771cec89439bff99c20c8cb03ddb9588b980697355a83cd4bd3", size = 187102, upload-time = "2026-07-17T22:49:34.616Z" }, + { url = "https://files.pythonhosted.org/packages/d9/de/6abe251d28c3a3f217096575400b27750b18e0b1d2fff3a2a239960fea07/websockets-16.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:b436f6ec4fc3a6b4237c84d3f83170ed2b40bb584222f0ac47a0c8a5921980c7", size = 180243, upload-time = "2026-07-17T22:49:37.626Z" }, + { url = "https://files.pythonhosted.org/packages/be/4d/2d0d67834092e354d2b0498f014a41249a89556bc406cf86f3e1557bb463/websockets-16.1.1-py3-none-any.whl", hash = "sha256:6abbd3e82c731c8e531714466acd5d87b5e88ac3243465337ba71d68e23ae7e3", size = 173814, upload-time = "2026-07-17T22:51:04.184Z" }, ] [[package]] @@ -3091,3 +3025,22 @@ sdist = { url = "https://files.pythonhosted.org/packages/b9/d8/eab98a517c14134c0 wheels = [ { url = "https://files.pythonhosted.org/packages/3a/13/547360d81e6d88d58492968ffda9f9542854f11310ee556fef14260cc886/zipp-4.1.0-py3-none-any.whl", hash = "sha256:25ad4e16390cd314347dd8f1de67a2ac538ae658ed4ab9db16029c07c188e97f", size = 10238, upload-time = "2026-05-18T20:08:57.045Z" }, ] + +[[package]] +name = "zstandard" +version = "0.25.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/aa/3e0508d5a5dd96529cdc5a97011299056e14c6505b678fd58938792794b1/zstandard-0.25.0.tar.gz", hash = "sha256:7713e1179d162cf5c7906da876ec2ccb9c3a9dcbdffef0cc7f70c3667a205f0b", size = 711513, upload-time = "2025-09-14T22:15:54.002Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/15/efef5a2f204a64bdb5571e6161d49f7ef0fffdbca953a615efbec045f60f/zstandard-0.25.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dffecc361d079bb48d7caef5d673c88c8988d3d33fb74ab95b7ee6da42652ea", size = 5063012, upload-time = "2025-09-14T22:17:01.156Z" }, + { url = "https://files.pythonhosted.org/packages/b7/37/a6ce629ffdb43959e92e87ebdaeebb5ac81c944b6a75c9c47e300f85abdf/zstandard-0.25.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:7149623bba7fdf7e7f24312953bcf73cae103db8cae49f8154dd1eadc8a29ecb", size = 5394148, upload-time = "2025-09-14T22:17:03.091Z" }, + { url = "https://files.pythonhosted.org/packages/e3/79/2bf870b3abeb5c070fe2d670a5a8d1057a8270f125ef7676d29ea900f496/zstandard-0.25.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:6a573a35693e03cf1d67799fd01b50ff578515a8aeadd4595d2a7fa9f3ec002a", size = 5451652, upload-time = "2025-09-14T22:17:04.979Z" }, + { url = "https://files.pythonhosted.org/packages/53/60/7be26e610767316c028a2cbedb9a3beabdbe33e2182c373f71a1c0b88f36/zstandard-0.25.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5a56ba0db2d244117ed744dfa8f6f5b366e14148e00de44723413b2f3938a902", size = 5546993, upload-time = "2025-09-14T22:17:06.781Z" }, + { url = "https://files.pythonhosted.org/packages/85/c7/3483ad9ff0662623f3648479b0380d2de5510abf00990468c286c6b04017/zstandard-0.25.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:10ef2a79ab8e2974e2075fb984e5b9806c64134810fac21576f0668e7ea19f8f", size = 5046806, upload-time = "2025-09-14T22:17:08.415Z" }, + { url = "https://files.pythonhosted.org/packages/08/b3/206883dd25b8d1591a1caa44b54c2aad84badccf2f1de9e2d60a446f9a25/zstandard-0.25.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aaf21ba8fb76d102b696781bddaa0954b782536446083ae3fdaa6f16b25a1c4b", size = 5576659, upload-time = "2025-09-14T22:17:10.164Z" }, + { url = "https://files.pythonhosted.org/packages/9d/31/76c0779101453e6c117b0ff22565865c54f48f8bd807df2b00c2c404b8e0/zstandard-0.25.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1869da9571d5e94a85a5e8d57e4e8807b175c9e4a6294e3b66fa4efb074d90f6", size = 4953933, upload-time = "2025-09-14T22:17:11.857Z" }, + { url = "https://files.pythonhosted.org/packages/1e/73/316e4010de585ac798e154e88fd81bb16afc5c5cb1a72eeb16dd37e8024a/zstandard-0.25.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:f27662e4f7dbf9f9c12391cb37b4c4c3cb90ffbd3b1fb9284dadbbb8935fa708", size = 5433517, upload-time = "2025-09-14T22:17:16.103Z" }, + { url = "https://files.pythonhosted.org/packages/5b/60/dd0f8cfa8129c5a0ce3ea6b7f70be5b33d2618013a161e1ff26c2b39787c/zstandard-0.25.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:99c0c846e6e61718715a3c9437ccc625de26593fea60189567f0118dc9db7512", size = 5814292, upload-time = "2025-09-14T22:17:17.827Z" }, + { url = "https://files.pythonhosted.org/packages/fc/5f/75aafd4b9d11b5407b641b8e41a57864097663699f23e9ad4dbb91dc6bfe/zstandard-0.25.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:474d2596a2dbc241a556e965fb76002c1ce655445e4e3bf38e5477d413165ffa", size = 5360237, upload-time = "2025-09-14T22:17:19.954Z" }, + { url = "https://files.pythonhosted.org/packages/79/3b/fa54d9015f945330510cb5d0b0501e8253c127cca7ebe8ba46a965df18c5/zstandard-0.25.0-cp312-cp312-win_amd64.whl", hash = "sha256:ffef5a74088f1e09947aecf91011136665152e0b4b359c42be3373897fb39b01", size = 506276, upload-time = "2025-09-14T22:17:21.429Z" }, +] From 8135c96937866897eada1dc7545a2db2d469e5c3 Mon Sep 17 00:00:00 2001 From: nblauch Date: Mon, 23 Nov 2026 23:25:36 -0800 Subject: [PATCH 30/30] Lock Isaac Lab at the pull request's latest commit It adds the gaze teacher's world-point target and the camera's image-free pose read, which the ActiveGaze task uses. --- uv.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uv.lock b/uv.lock index daa764a..d45897d 100644 --- a/uv.lock +++ b/uv.lock @@ -1013,7 +1013,7 @@ wheels = [ [[package]] name = "isaaclab" version = "3.0.0" -source = { git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9183%2Fhead#030f94b2511cac2ac45dd76b134f53a624c2066c" } +source = { git = "https://github.com/isaac-sim/IsaacLab.git?subdirectory=tools%2Fwheel_builder&rev=refs%2Fpull%2F9183%2Fhead#a5fb082b02702b35b453bed9c8ee9b0f9cb8675a" } dependencies = [ { name = "alphashape", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" }, { name = "botocore", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32')" },