mirror of
https://github.com/huggingface/lerobot.git
synced 2026-05-31 10:51:35 +00:00
* docs(benchmarks): add benchmark integration guide and standardize benchmark docs Add a comprehensive guide for adding new benchmarks to LeRobot, and refactor the existing LIBERO and Meta-World docs to follow the new standardized template. Made-with: Cursor * refactor(envs): move dispatch logic from factory into EnvConfig subclasses Replace hardcoded if/elif chains in factory.py with create_envs() and get_env_processors() methods on EnvConfig. New benchmarks now only need to register a config subclass — no factory.py edits required. Net -23 lines: factory.py shrinks from ~200 to ~70 lines of logic. Made-with: Cursor * docs(benchmarks): clean up adding-benchmarks guide for clarity Rewrite for simpler language, better structure, and easier navigation. Move quick-reference table to the top, fold eval explanation into architecture section, condense the doc template to a bulleted outline. Made-with: Cursor * fix link * fix task count * fix: enable SmolVLA eval on LIBERO with custom camera mappings - Thread camera_name_mapping from LiberoEnv config through to gym envs - Sync features_map with camera_name_mapping in LiberoEnv.__post_init__ - Fix render() to use first available camera instead of hardcoded "image" - Handle non-dict final_info in rollout by falling back to info["is_success"] - Add use_peft legacy field to SmolVLAConfig for checkpoint compat - Add defaults to GR00TN15Config init=False fields for transformers 5.3 Made-with: Cursor * fix: use direct AutoresetMode import for gymnasium compat Made-with: Cursor * fix: handle gymnasium < 1.0 without AutoresetMode Made-with: Cursor * refactor: revert policy changes, keep env-only camera mapping fixes - Revert GR00T N1.5 default_factory/default changes (transformers compat) - Revert SmolVLA use_peft legacy field - Apply ruff formatting fixes - camera_name_mapping stays entirely in env/eval layer (no policy changes) Made-with: Cursor * Update docs/source/env_processor.mdx Co-authored-by: Khalil Meftah <khalil.meftah@huggingface.co> Signed-off-by: Pepijn <138571049+pkooij@users.noreply.github.com> * feat(envs): lazy env init + AsyncVectorEnv as default for n_envs > 1 LiberoEnv and MetaworldEnv previously allocated GPU resources (EGL context, OpenGL framebuffer) in __init__, before AsyncVectorEnv's fork(). Worker processes inherited stale GPU handles, causing EGL_BAD_CONTEXT crashes on first render. Fix: defer OffScreenRenderEnv / MT1 construction to _ensure_env(), called on first reset() or step() inside the worker subprocess. Each worker creates its own clean context after fork(). Also fixes lerobot_eval.py:170 (add_envs_task TODO): replace with env.call("task") which works with both SyncVectorEnv and AsyncVectorEnv. AsyncVectorEnv is now the default for n_envs > 1; auto-downgraded to SyncVectorEnv when n_envs=1 (no benefit, less overhead). Expected speedup: ~15-20x for LIBERO Spatial with batch_size=50. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: close envs between tasks to prevent worker process accumulation eval_policy_all never closed environments after each task completed, causing AsyncVectorEnv worker processes to accumulate (N_tasks × n_envs). This led to OOM, BrokenPipeError and EOFError on multi-task benchmarks. Also fixes: - AsyncVectorEnv compat in envs/utils.py (use get_attr/call instead of .envs) - Tuple task handling in tokenizer_processor and lerobot_eval - _LazyAsyncVectorEnv for deferred worker spawning in LIBERO Made-with: Cursor * fix(eval): use task_description instead of task for language conditioning env.call("task") returns the LIBERO task name with underscores (e.g. "pick_up_the_black_bowl_...") instead of the natural language description ("pick up the black bowl ..."). The VLM tokenizes these completely differently, causing 0.0 reward across all episodes. Made-with: Cursor * docs: update adding_benchmarks for async env changes - Replace add_envs_task reference with env.call("task_description") - Update use_async_envs default to True - Add note about lazy GPU init for AsyncVectorEnv compatibility Made-with: Cursor * feat(eval): batch_size=auto + faster env loading - batch_size=0 (default) auto-tunes based on CPU cores, capped by n_episodes and 64. Removes the need for users to guess the right value. The old batch_size > n_episodes error is replaced by silently clamping to n_episodes. - _LazyAsyncVectorEnv accepts pre-computed spaces so only one temp env is created per suite (not per task). For libero_spatial (10 tasks) this avoids 9 redundant LiberoEnv instantiations during env setup. Made-with: Cursor * docs: add evaluation guide and update benchmarks doc - New docs/source/evaluation.mdx covering lerobot-eval usage, batch_size auto-tuning, AsyncVectorEnv performance, tuning tips, output format, multi-task evaluation, and programmatic usage. - Add evaluation page to _toctree.yml under Benchmarks section. - Update adding_benchmarks.mdx to reference batch_size auto default and link to the evaluation guide. Made-with: Cursor * docs(evaluation): remove benchmark table, rename section header Made-with: Cursor * perf(eval): shared memory, observation passthrough, task prefetch - AsyncVectorEnv now uses shared_memory=True for zero-copy observation transfer - LiberoEnvConfig.gym_kwargs passes observation_height/width to the env - eval_policy_all prefetches next task's workers while current task runs Made-with: Cursor * style: ruff format Made-with: Cursor * chore: revert env_processor.mdx changes (not part of this PR) Made-with: Cursor * ci(benchmarks): add isolated integration tests for libero and metaworld Each benchmark gets its own Docker image (lerobot[libero] / lerobot[metaworld] only) so incompatible dep trees cannot collide. A 1-episode smoke eval runs per benchmark on GPU runners. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * ci(benchmarks): pin action hashes and use uv sync --locked Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * ci(benchmarks): trigger only on envs/ or lerobot_eval.py changes Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(ci): set LIBERO_DATA_FOLDER to bypass interactive stdin prompt libero/__init__.py calls input() to ask about a custom dataset path, which raises EOFError when stdin is closed inside Docker. Setting LIBERO_DATA_FOLDER skips the prompt entirely. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * docs(benchmarks): add CI smoke test step to adding_benchmarks guide Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(ci): pre-create libero config in Dockerfile to bypass stdin prompt libero/__init__.py calls input() when ~/.libero/config.yaml is missing. We write the config at image build time (without importing libero) so the prompt never fires at runtime. Also trigger CI on pyproject.toml changes. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(ci): use shell to create libero config instead of multiline python -c The multiline RUN python -c "..." was being parsed as Dockerfile instructions. Use printf to write ~/.libero/config.yaml directly. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(ci): point libero config to bundled package init_files The config was pointing to /tmp/libero_init which doesn't exist. Use importlib.util.find_spec to locate the hf-libero package directory and write paths to the actual bundled bddl_files/init_files/assets. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(ci): add smolvla extra to benchmark Dockerfiles num2words (required by SmolVLM processor) is declared in lerobot[smolvla], not lerobot[libero/metaworld]. Install both extras together. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(eval): render_frame covers _LazyAsyncVectorEnv isinstance(env, AsyncVectorEnv) silently skipped _LazyAsyncVectorEnv, causing video rendering to produce no frames on the default async path. Switch to hasattr(env, "call") so any async-compatible env (including _LazyAsyncVectorEnv) hits the call("render") branch. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor(envs): remove unused _get_sub_env_attr helper _get_sub_env_attr was defined but never called anywhere in the codebase. _sub_env_has_attr (its sibling) is kept — it is actively used in utils.py. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore: apply prettier formatting to docs Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * docs(env_processor): remove deprecated add_envs_task from pipeline example add_envs_task is replaced by env.call("task_description") in this PR. Remove it from the pipeline walkthrough and renumber the steps (8→7). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor(envs): remove __del__ from _LazyAsyncVectorEnv __del__ is unreliable as a cleanup mechanism. close() is already called explicitly in the eval loop's finally block, so the finalizer is redundant. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(eval): prefetch next task's workers after close to avoid GPU memory overlap Previously, next task's AsyncVectorEnv workers were spawned while the current task was still running, causing both tasks' GPU contexts to coexist. Moving the prefetch start into the finally block (after env.close()) ensures workers for task N+1 only spin up once task N has released GPU memory. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor(envs): move _LazyAsyncVectorEnv to utils and apply to metaworld _LazyAsyncVectorEnv lived in libero.py but metaworld had the same OOM problem: all tasks' AsyncVectorEnv workers were spawned eagerly, wasting GPU memory for tasks not yet running. Move the class to envs/utils.py so both environments share it, then apply the same is_async + lazy wrapping pattern in create_metaworld_envs. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore: remove out-of-scope benchmark/CI/docs files from PR Benchmark CI workflow, Dockerfiles, benchmark docs, evaluation smoke-test doc, and dispatch tests belong in a separate PR. Scope this PR to the async env init changes only. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore: restore adding_benchmarks + test_dispatch, drop env_processor changes - Restore docs/source/adding_benchmarks.mdx (belongs in this PR) - Restore tests/envs/test_dispatch.py (belongs in this PR) - Revert docs/source/env_processor.mdx to main (out of scope for this PR) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * docs(adding_benchmarks): remove CI smoke test step (coming in separate PR) Step 7 (Dockerfile + benchmark_tests.yml CI job) and its table rows are out of scope for this PR. The CI infrastructure will be added on top in a follow-up PR. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor(envs): remove unused add_envs_task Replaced by env.call("task_description") in lerobot_eval.py. No callers remain in the codebase. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * style: fix prettier formatting in env_processor.mdx Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(eval): catch AttributeError and NotImplementedError explicitly for task description Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(envs): use forkserver context and close envs in test to prevent deadlock AsyncVectorEnv with default fork context leaks worker processes between test_policy parametrized cases; subsequent env creation deadlocks because new forked workers inherit stale pipe FDs from previous test's leaked workers. - configs.py: pass context="forkserver" to AsyncVectorEnv (matches _LazyAsyncVectorEnv) - test_policies.py: call close_envs(envs) at end of test_policy to clean up workers Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(envs): default use_async_envs=False in create_envs and make_env Tests that call make_env(n_envs=2) without passing use_async_envs were getting AsyncVectorEnv, whose forked workers can't resolve gym namespaces registered at runtime. Default to False (sync) so existing tests pass. lerobot_eval.py explicitly passes cfg.eval.use_async_envs, so the CLI async behaviour (controlled by EvalConfig.use_async_envs) is unchanged. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Signed-off-by: Pepijn <138571049+pkooij@users.noreply.github.com> Co-authored-by: Khalil Meftah <khalil.meftah@huggingface.co> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
377 lines
14 KiB
Python
377 lines
14 KiB
Python
#!/usr/bin/env python
|
||
|
||
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
||
#
|
||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||
# you may not use this file except in compliance with the License.
|
||
# You may obtain a copy of the License at
|
||
#
|
||
# http://www.apache.org/licenses/LICENSE-2.0
|
||
#
|
||
# Unless required by applicable law or agreed to in writing, software
|
||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||
# See the License for the specific language governing permissions and
|
||
# limitations under the License.
|
||
import importlib.util
|
||
import os
|
||
import warnings
|
||
from collections.abc import Callable, Mapping, Sequence
|
||
from functools import singledispatch
|
||
from typing import Any
|
||
|
||
import einops
|
||
import gymnasium as gym
|
||
import numpy as np
|
||
import torch
|
||
from huggingface_hub import hf_hub_download, snapshot_download
|
||
from torch import Tensor
|
||
|
||
from lerobot.configs.types import FeatureType, PolicyFeature
|
||
from lerobot.envs.configs import EnvConfig
|
||
from lerobot.utils.constants import OBS_ENV_STATE, OBS_IMAGE, OBS_IMAGES, OBS_STATE, OBS_STR
|
||
from lerobot.utils.utils import get_channel_first_image_shape
|
||
|
||
|
||
def _convert_nested_dict(d):
|
||
result = {}
|
||
for k, v in d.items():
|
||
if isinstance(v, dict):
|
||
result[k] = _convert_nested_dict(v)
|
||
elif isinstance(v, np.ndarray):
|
||
result[k] = torch.from_numpy(v)
|
||
else:
|
||
result[k] = v
|
||
return result
|
||
|
||
|
||
def preprocess_observation(observations: dict[str, np.ndarray]) -> dict[str, Tensor]:
|
||
# TODO(jadechoghari, imstevenpmwork): refactor this to use features from the environment (no hardcoding)
|
||
"""Convert environment observation to LeRobot format observation.
|
||
Args:
|
||
observation: Dictionary of observation batches from a Gym vector environment.
|
||
Returns:
|
||
Dictionary of observation batches with keys renamed to LeRobot format and values as tensors.
|
||
"""
|
||
# map to expected inputs for the policy
|
||
return_observations = {}
|
||
if "pixels" in observations:
|
||
if isinstance(observations["pixels"], dict):
|
||
imgs = {f"{OBS_IMAGES}.{key}": img for key, img in observations["pixels"].items()}
|
||
else:
|
||
imgs = {OBS_IMAGE: observations["pixels"]}
|
||
|
||
for imgkey, img in imgs.items():
|
||
# TODO(aliberts, rcadene): use transforms.ToTensor()?
|
||
img_tensor = torch.from_numpy(img)
|
||
|
||
# When preprocessing observations in a non-vectorized environment, we need to add a batch dimension.
|
||
# This is the case for human-in-the-loop RL where there is only one environment.
|
||
if img_tensor.ndim == 3:
|
||
img_tensor = img_tensor.unsqueeze(0)
|
||
# sanity check that images are channel last
|
||
_, h, w, c = img_tensor.shape
|
||
assert c < h and c < w, f"expect channel last images, but instead got {img_tensor.shape=}"
|
||
|
||
# sanity check that images are uint8
|
||
assert img_tensor.dtype == torch.uint8, f"expect torch.uint8, but instead {img_tensor.dtype=}"
|
||
|
||
# convert to channel first of type float32 in range [0,1]
|
||
img_tensor = einops.rearrange(img_tensor, "b h w c -> b c h w").contiguous()
|
||
img_tensor = img_tensor.type(torch.float32)
|
||
img_tensor /= 255
|
||
|
||
return_observations[imgkey] = img_tensor
|
||
|
||
if "environment_state" in observations:
|
||
env_state = torch.from_numpy(observations["environment_state"]).float()
|
||
if env_state.dim() == 1:
|
||
env_state = env_state.unsqueeze(0)
|
||
|
||
return_observations[OBS_ENV_STATE] = env_state
|
||
|
||
if "agent_pos" in observations:
|
||
agent_pos = torch.from_numpy(observations["agent_pos"]).float()
|
||
if agent_pos.dim() == 1:
|
||
agent_pos = agent_pos.unsqueeze(0)
|
||
return_observations[OBS_STATE] = agent_pos
|
||
|
||
if "robot_state" in observations:
|
||
return_observations[f"{OBS_STR}.robot_state"] = _convert_nested_dict(observations["robot_state"])
|
||
|
||
# Handle IsaacLab Arena format: observations have 'policy' and 'camera_obs' keys
|
||
if "policy" in observations:
|
||
return_observations[f"{OBS_STR}.policy"] = observations["policy"]
|
||
|
||
if "camera_obs" in observations:
|
||
return_observations[f"{OBS_STR}.camera_obs"] = observations["camera_obs"]
|
||
|
||
return return_observations
|
||
|
||
|
||
def env_to_policy_features(env_cfg: EnvConfig) -> dict[str, PolicyFeature]:
|
||
# TODO(jadechoghari, imstevenpmwork): remove this hardcoding of keys and just use the nested keys as is
|
||
# (need to also refactor preprocess_observation and externalize normalization from policies)
|
||
policy_features = {}
|
||
for key, ft in env_cfg.features.items():
|
||
if ft.type is FeatureType.VISUAL:
|
||
if len(ft.shape) != 3:
|
||
raise ValueError(f"Number of dimensions of {key} != 3 (shape={ft.shape})")
|
||
|
||
shape = get_channel_first_image_shape(ft.shape)
|
||
feature = PolicyFeature(type=ft.type, shape=shape)
|
||
else:
|
||
feature = ft
|
||
|
||
policy_key = env_cfg.features_map[key]
|
||
policy_features[policy_key] = feature
|
||
|
||
return policy_features
|
||
|
||
|
||
def _sub_env_has_attr(env: gym.vector.VectorEnv, attr: str) -> bool:
|
||
try:
|
||
env.get_attr(attr)
|
||
return True
|
||
except (AttributeError, Exception):
|
||
return False
|
||
|
||
|
||
class _LazyAsyncVectorEnv:
|
||
"""Defers AsyncVectorEnv creation until first use.
|
||
|
||
Creating all tasks' AsyncVectorEnvs upfront spawns N_tasks × n_envs worker
|
||
processes, all of which allocate EGL/GPU resources immediately. Since tasks
|
||
are evaluated sequentially, only one task's workers need to be alive at a
|
||
time. This wrapper stores the factory functions and creates the real
|
||
AsyncVectorEnv on first reset()/step()/call(), keeping peak process count = n_envs.
|
||
"""
|
||
|
||
def __init__(
|
||
self,
|
||
env_fns: list[Callable],
|
||
observation_space=None,
|
||
action_space=None,
|
||
):
|
||
self._env_fns = env_fns
|
||
self._env: gym.vector.AsyncVectorEnv | None = None
|
||
self.num_envs = len(env_fns)
|
||
if observation_space is not None and action_space is not None:
|
||
self.observation_space = observation_space
|
||
self.action_space = action_space
|
||
else:
|
||
tmp = env_fns[0]()
|
||
self.observation_space = tmp.observation_space
|
||
self.action_space = tmp.action_space
|
||
tmp.close()
|
||
self.single_observation_space = self.observation_space
|
||
self.single_action_space = self.action_space
|
||
|
||
def _ensure(self) -> None:
|
||
if self._env is None:
|
||
self._env = gym.vector.AsyncVectorEnv(self._env_fns, context="forkserver", shared_memory=True)
|
||
|
||
def reset(self, **kwargs):
|
||
self._ensure()
|
||
return self._env.reset(**kwargs)
|
||
|
||
def step(self, actions):
|
||
self._ensure()
|
||
return self._env.step(actions)
|
||
|
||
def call(self, name, *args, **kwargs):
|
||
self._ensure()
|
||
return self._env.call(name, *args, **kwargs)
|
||
|
||
def get_attr(self, name):
|
||
self._ensure()
|
||
return self._env.get_attr(name)
|
||
|
||
def close(self) -> None:
|
||
if self._env is not None:
|
||
self._env.close()
|
||
self._env = None
|
||
|
||
|
||
def check_env_attributes_and_types(env: gym.vector.VectorEnv) -> None:
|
||
with warnings.catch_warnings():
|
||
warnings.simplefilter("once", UserWarning)
|
||
|
||
if not (_sub_env_has_attr(env, "task_description") and _sub_env_has_attr(env, "task")):
|
||
warnings.warn(
|
||
"The environment does not have 'task_description' and 'task'. Some policies require these features.",
|
||
UserWarning,
|
||
stacklevel=2,
|
||
)
|
||
|
||
|
||
def _close_single_env(env: Any) -> None:
|
||
try:
|
||
env.close()
|
||
except Exception as exc:
|
||
print(f"Exception while closing env {env}: {exc}")
|
||
|
||
|
||
@singledispatch
|
||
def close_envs(obj: Any) -> None:
|
||
"""Default: raise if the type is not recognized."""
|
||
raise NotImplementedError(f"close_envs not implemented for type {type(obj).__name__}")
|
||
|
||
|
||
@close_envs.register
|
||
def _(env: Mapping) -> None:
|
||
for v in env.values():
|
||
if isinstance(v, Mapping):
|
||
close_envs(v)
|
||
elif hasattr(v, "close"):
|
||
_close_single_env(v)
|
||
|
||
|
||
@close_envs.register
|
||
def _(envs: Sequence) -> None:
|
||
if isinstance(envs, (str | bytes)):
|
||
return
|
||
for v in envs:
|
||
if isinstance(v, Mapping) or isinstance(v, Sequence) and not isinstance(v, (str | bytes)):
|
||
close_envs(v)
|
||
elif hasattr(v, "close"):
|
||
_close_single_env(v)
|
||
|
||
|
||
@close_envs.register
|
||
def _(env: gym.Env) -> None:
|
||
_close_single_env(env)
|
||
|
||
|
||
# helper to safely load a python file as a module
|
||
def _load_module_from_path(path: str, module_name: str | None = None):
|
||
module_name = module_name or f"hub_env_{os.path.basename(path).replace('.', '_')}"
|
||
spec = importlib.util.spec_from_file_location(module_name, path)
|
||
if spec is None:
|
||
raise ImportError(f"Could not load module spec for {module_name} from {path}")
|
||
module = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(module) # type: ignore
|
||
return module
|
||
|
||
|
||
# helper to parse hub string (supports "user/repo", "user/repo@rev", optional path)
|
||
# examples:
|
||
# "user/repo" -> will look for env.py at repo root
|
||
# "user/repo@main:envs/my_env.py" -> explicit revision and path
|
||
def _parse_hub_url(hub_uri: str):
|
||
# very small parser: [repo_id][@revision][:path]
|
||
# repo_id is required (user/repo or org/repo)
|
||
revision = None
|
||
file_path = "env.py"
|
||
if "@" in hub_uri:
|
||
repo_and_rev, *rest = hub_uri.split(":", 1)
|
||
repo_id, rev = repo_and_rev.split("@", 1)
|
||
revision = rev
|
||
if rest:
|
||
file_path = rest[0]
|
||
else:
|
||
repo_id, *rest = hub_uri.split(":", 1)
|
||
if rest:
|
||
file_path = rest[0]
|
||
return repo_id, revision, file_path
|
||
|
||
|
||
def _download_hub_file(
|
||
cfg_str: str,
|
||
trust_remote_code: bool,
|
||
hub_cache_dir: str | None,
|
||
) -> tuple[str, str, str, str]:
|
||
"""
|
||
Parse `cfg_str` (hub URL), enforce `trust_remote_code`, and return
|
||
(repo_id, file_path, local_file, revision).
|
||
"""
|
||
if not trust_remote_code:
|
||
raise RuntimeError(
|
||
f"Refusing to execute remote code from the Hub for '{cfg_str}'. "
|
||
"Executing hub env modules runs arbitrary Python code from third-party repositories. "
|
||
"If you trust this repo and understand the risks, call `make_env(..., trust_remote_code=True)` "
|
||
"and prefer pinning to a specific revision: 'user/repo@<commit-hash>:env.py'."
|
||
)
|
||
|
||
repo_id, revision, file_path = _parse_hub_url(cfg_str)
|
||
|
||
try:
|
||
local_file = hf_hub_download(
|
||
repo_id=repo_id, filename=file_path, revision=revision, cache_dir=hub_cache_dir
|
||
)
|
||
except Exception as e:
|
||
# fallback to snapshot download
|
||
snapshot_dir = snapshot_download(repo_id=repo_id, revision=revision, cache_dir=hub_cache_dir)
|
||
local_file = os.path.join(snapshot_dir, file_path)
|
||
if not os.path.exists(local_file):
|
||
raise FileNotFoundError(
|
||
f"Could not find {file_path} in repository {repo_id}@{revision or 'main'}"
|
||
) from e
|
||
|
||
return repo_id, file_path, local_file, revision
|
||
|
||
|
||
def _import_hub_module(local_file: str, repo_id: str) -> Any:
|
||
"""
|
||
Import the downloaded file as a module and surface helpful import error messages.
|
||
"""
|
||
module_name = f"hub_env_{repo_id.replace('/', '_')}"
|
||
try:
|
||
module = _load_module_from_path(local_file, module_name=module_name)
|
||
except ModuleNotFoundError as e:
|
||
missing = getattr(e, "name", None) or str(e)
|
||
raise ModuleNotFoundError(
|
||
f"Hub env '{repo_id}:{os.path.basename(local_file)}' failed to import because the dependency "
|
||
f"'{missing}' is not installed locally.\n\n"
|
||
) from e
|
||
except ImportError as e:
|
||
raise ImportError(
|
||
f"Failed to load hub env module '{repo_id}:{os.path.basename(local_file)}'. Import error: {e}\n\n"
|
||
) from e
|
||
return module
|
||
|
||
|
||
def _call_make_env(module: Any, n_envs: int, use_async_envs: bool, cfg: EnvConfig | None) -> Any:
|
||
"""
|
||
Ensure module exposes make_env and call it.
|
||
"""
|
||
if not hasattr(module, "make_env"):
|
||
raise AttributeError(
|
||
f"The hub module {getattr(module, '__name__', 'hub_module')} must expose `make_env(n_envs=int, use_async_envs=bool)`."
|
||
)
|
||
entry_fn = module.make_env
|
||
# Only pass cfg if it's not None (i.e., when an EnvConfig was provided, not a string hub ID)
|
||
if cfg is not None:
|
||
return entry_fn(n_envs=n_envs, use_async_envs=use_async_envs, cfg=cfg)
|
||
else:
|
||
return entry_fn(n_envs=n_envs, use_async_envs=use_async_envs)
|
||
|
||
|
||
def _normalize_hub_result(result: Any) -> dict[str, dict[int, gym.vector.VectorEnv]]:
|
||
"""
|
||
Normalize possible return types from hub `make_env` into the mapping:
|
||
{ suite_name: { task_id: vector_env } }
|
||
Accepts:
|
||
- dict (assumed already correct)
|
||
- gym.vector.VectorEnv
|
||
- gym.Env (will be wrapped into SyncVectorEnv)
|
||
"""
|
||
if isinstance(result, dict):
|
||
return result
|
||
|
||
# VectorEnv: use its spec.id if available
|
||
if isinstance(result, gym.vector.VectorEnv):
|
||
suite_name = getattr(result, "spec", None) and getattr(result.spec, "id", None) or "hub_env"
|
||
return {suite_name: {0: result}}
|
||
|
||
# Single Env: wrap into SyncVectorEnv
|
||
if isinstance(result, gym.Env):
|
||
vec = gym.vector.SyncVectorEnv([lambda: result])
|
||
suite_name = getattr(result, "spec", None) and getattr(result.spec, "id", None) or "hub_env"
|
||
return {suite_name: {0: vec}}
|
||
|
||
raise ValueError(
|
||
"Hub `make_env` must return either a mapping {suite: {task_id: vec_env}}, "
|
||
"a gym.vector.VectorEnv, or a single gym.Env."
|
||
)
|