← Back to Pull requests

refactor: import other lerobot packages through their package API #5215

Open
CarolinePascal opened this pull request with 1664 lines diff across 217 files
View on GitHub
CarolinePascal CarolinePascal commented on Nov 02, 2026 17:37 UTC
Author

Summary / Motivation

This PR states one import convention in AGENTS.md and applies it across src/lerobot. Every top-level package now exposes the symbols other packages use through its __init__.py, and code outside a package imports them from there.

Rules now in AGENTS.md

  • Package __init__.py: each top-level package's __init__.py imports every symbol other packages use and lists it in __all__. A symbol deliberately left out gets a comment there naming the module to import it from.

  • Imports: prefer module-level imports. Within a package, use relative imports (from .sibling import X). Across packages, import from the package (from lerobot.policies import PreTrainedPolicy), never from its files or subpackages.

  • Exceptions:

  • - tests/;
    - lerobot.utils and lerobot.common;
    - symbols left out of a package's __init__.py, which you import from the module its comment names.
  • lerobot.utils: importing it pulls in only base dependencies and no other lerobot package. Import from its modules, not from the package (from lerobot.utils.constants import ACTION).

  • lerobot.common: code that bridges packages. It may import other lerobot packages and optional extras. Import from its modules, not from the package (from lerobot.common.train_utils import save_checkpoint).
  • Symbols left out of an __init__.py are documented with a uniform comment placed right before __all__:

    # NOTE: <what> is/are intentionally NOT re-exported here <reason>.
    # Import from submodules: ``from lerobot.<pkg>.<module> import <Symbol>``
    

    Main changes needed to follow the rules

    Breaking the configs ↔ optim import cycle

  • configs.policies and configs.rewards now import OptimizerConfig and LRSchedulerConfig only for type checking.

  • optim.factory does the same for TrainPipelineConfig and PreTrainedPolicy, so make_optimizer_and_scheduler can be re-exported from lerobot.optim.

  • datasets.factory imports TrainPipelineConfig only for type checking.

  • TrainPipelineConfig, CheckpointFormat, TRAIN_CONFIG_NAME and EvalPipelineConfig stay out of lerobot.configs because they would create a cycle. Import them from lerobot.configs.train and lerobot.configs.eval.
  • Keeping lerobot.utils base-only

  • LANGUAGE_COLUMNS is now defined in lerobot.utils.constants, so utils.collate no longer imports lerobot.datasets.

  • lerobot.utils.doctest_utils moved to tests/doctest_utils.py because it depends on pytest. conftest.py, the Makefile and quality.yml are updated to the new path.
  • lerobot.streaming requires the dataset extra

  • lerobot.streaming only exists to feed LeRobotDataset, so its __init__ now checks for the dataset extra, as lerobot.datasets does.

  • StreamingSamplingStrategy moved to lerobot.configs.types, so lerobot.configs no longer imports lerobot.streaming.

  • lerobot-build-mp4-sidecar --help still works on a base install: the script imports lerobot.streaming under the existing _datasets_available guard.

  • Streaming tests are marked dataset, and test_streaming_core_imports.py is removed.
  • Symbols deliberately not re-exported (each one documented with a NOTE)

    | Package | Left out | Reason |
    | --- | --- | --- |
    | policies | modeling classes and policy-specific helpers | they pull heavy optional dependencies; get_policy_class() loads them lazily |
    | rewards | reward model classes and reward-specific helpers | same; get_reward_model_class() loads them lazily |
    | robots | robot implementations, so_follower.robot_kinematic_processor | device-specific dependencies, and the processor pulls lerobot.processor (TODO: move it to a robot-agnostic location) |
    | robots.unitree_g1 | kinematics helpers | config_unitree_g1 imports lerobot.envs, which imports lerobot.robots |
    | sim | simulator integrations (lerobot.sim.integrations.<type>) | each simulator package is imported only when used |
    | rl | gym_manipulator | it pulls the camera, robot and teleoperator stacks |
    | transport | RL gRPC modules | they require lerobot[grpcio-dep] |
    | utils, common | everything | callers load only the modules they need; existing re-exports are kept for backward compatibility |

    Other

  • __version__ is imported through the lerobot package.

  • Tests patch the distributed helpers on lerobot.distributed, where callers now look them up.

  • Imports of lerobot.datasets are guarded on _datasets_available and _av_available, since the package requires both at import time. fit_fast_tokenizer guards pyarrow on a new _pyarrow_available flag.

  • The envs/ line in AGENTS.md now says env configs define sim_settings(), which names the lerobot.sim integration that create_envs() runs.
  • Breaking changes

  • lerobot.utils.doctest_utils is removed. It now lives in tests/doctest_utils.py, which only pytest uses.

  • import lerobot.streaming now fails without the dataset extra (pip install 'lerobot[dataset]').

  • Follow-up

  • Several classes share a name with another lerobot class. TODOs in policies/__init__.py, motors/__init__.py and envs/__init__.py list the ones to rename:

  • - the MLP classes in gaussian_actor, vqbet and vla_jepa;
    - the MotorState classes in damiao, robstride and unitree_g1;
    - the two RewardClassifierConfig classes, in envs.configs and rewards.classifier.
  • Imports in examples/ and docs/ that still take re-exported symbols from submodules (for example lerobot.model.kinematics.RobotKinematics and lerobot.rollout.strategies.BaseStrategy) are fixed in #5216, which is stacked on this PR.
  • How was this tested

  • pre-commit (ruff check and format, mypy) passes.

  • An AST check finds no cross-package import of a file or subpackage outside the documented NOTEs, and no absolute import within a package.

  • The robots, envs, sim, env_server, transport, remote_inference, rollout, inference, utils, scripts and policies tests pass.

  • At every commit, all lerobot packages and CLI entry points import successfully.
  • Diff: 1664 lines (+1008 / -656) across 217 files Reviewer: None requested Review duration: 48651m
    All Vouch review confidence checks passed
    Residual risk 0.32 = Change Risk (0.91) × (1 − Review Confidence (0.65)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.91 · 1664 lines diff across 217 files
    0.91
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.58 · 4 substantive comment(s)
    0.58
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 10%
    64%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    No Reviewer Assigned no_reviewer_assigned
    0.120
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    5 items
    zhangyue19921010 zhangyue19921010 commented on code on Nov 03, 2026 02:42 UTC
    Code Review
    src/lerobot/streaming/__init__.py:1
    @@ -7,3 +7,30 @@
     #     http://www.apache.org/licenses/LICENSE-2.0
     
     """Low-level primitives for training-time dataset streaming."""
    +
    +from lerobot.utils.import_utils import require_package
    +
    +require_package("datasets", extra="dataset")

    The base CI job fails to collect test_streaming_mp4_timing.py and test_streaming_sync_cache.py because both import lerobot.streaming at module scope and hit the new dependency check. Could we add pytest.importorskip guards before those imports and mark both modules as dataset, as the other streaming tests do?

    zhangyue19921010 zhangyue19921010 commented on code on Nov 03, 2026 02:44 UTC
    Code Review
    src/lerobot/policies/pretrained.py:1
    @@ -139,8 +139,7 @@ def _save_pretrained(self, save_directory: Path) -> None:
                     safetensors weight file(s).
             """
             # Lazy imports: the persistence layer pulls in lerobot.distributed only when saving.
    -        from lerobot.distributed.checkpoint import full_model_state_dict, is_sharded_module
    -        from lerobot.distributed.utils import is_main_process
    +        from lerobot.distributed import full_model_state_dict, is_main_process, is_sharded_module

    This method now looks up full_model_state_dict and is_main_process on lerobot.distributed, while the Wall-OSS save test still patches the original submodules. Both cases pass on the base revision and fail at assert gathered == [policy] on this PR. Could we update both patch targets to lerobot.distributed, as the DM05 test does?

    CarolinePascal CarolinePascal commented on code on Nov 03, 2026 18:08 UTC
    Code Review
    src/lerobot/streaming/__init__.py:1
    @@ -7,3 +7,30 @@
     #     http://www.apache.org/licenses/LICENSE-2.0
     
     """Low-level primitives for training-time dataset streaming."""
    +
    +from lerobot.utils.import_utils import require_package
    +
    +require_package("datasets", extra="dataset")
    CarolinePascal CarolinePascal commented on code on Nov 03, 2026 18:08 UTC
    Code Review
    src/lerobot/policies/pretrained.py:1
    @@ -139,8 +139,7 @@ def _save_pretrained(self, save_directory: Path) -> None:
                     safetensors weight file(s).
             """
             # Lazy imports: the persistence layer pulls in lerobot.distributed only when saving.
    -        from lerobot.distributed.checkpoint import full_model_state_dict, is_sharded_module
    -        from lerobot.distributed.utils import is_main_process
    +        from lerobot.distributed import full_model_state_dict, is_main_process, is_sharded_module
    Reviewers
    None requested
    Assignees
    CarolinePascal CarolinePascal
    Labels
    risk: low confidence: 64.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 90.5% (HIGH) · Higher = larger blast radius
    90.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 64.7% · Lower = rushed or shallow review
    64.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 31.9% · Safe to merge
    31.9%