LeRobot 入门教程(十五)从Hub加载环境
系列文章目录
目录
系列文章目录
前言
一、快速入门
二、什么是 EnvHub?
三、仓库结构
3.1 必备文件
3.1.1 env.py(或自定义 Python 文件)
3.2 可选文件
3.2.1 requirements.txt
3.2.2 README.md
3.2.3 .gitignore
3.3 示例仓库结构
四、创建环境仓库
4.1 定义环境
4.2 本地测试
4.3 上传至Hub
五、从Hub加载环境
5.1 基本用法
5.2 高级:固定到特定版本
5.3 自定义文件路径
5.4 异步环境
六、URL格式参考
七、多任务环境
八、安全注意事项
九、示例:来自 Hub 的 CartPole
十、EnvHub的优势
10.1 面向环境作者
10.2 面向研究人员
10.3 面向社区
十一、故障排除
11.1 “拒绝执行远程代码” “Refusing to execute remote code”
11.2 “未找到模块 X” “Module X not found”
11.3 “在模块中找不到 make_env” “make_env not found in module”
11.4 环境返回类型错误
十二、最佳实践
十三、未来方向
前言
EnvHub功能让您只需一行代码,即可直接从Hugging Face Hub加载模拟环境。这开创了一种强大的协作新模式:环境不再被封锁在单一库中,任何人都能发布自定义环境并与社区共享。
借助EnvHub,您可以:
- 立即从Hub加载环境
- 与社区共享自定义模拟任务
- 使用Git对环境进行版本控制
- 无需繁琐打包即可分发复杂物理模拟
一、快速入门
从 Hub 加载环境只需简单几步:
from lerobot.envs.factory import make_env# Load a hub environment (requires explicit consent to run remote code)
env = make_env("lerobot/cartpole-env", trust_remote_code=True)
**安全提示**:从 Hub 加载环境会执行第三方仓库的 Python 代码。仅对可信赖的仓库使用 `trust_remote_code=True`。为确保可重复性和安全性,强烈建议固定到特定提交哈希值。
二、什么是 EnvHub?
EnvHub 是一个框架,可让研究人员和开发者:
- 将环境以Git仓库形式发布至Hugging Face Hub
- 无需安装包即可动态加载环境
- 使用Git语义管理环境版本与变更
- 探索社区共享的新仿真任务
该设计使您能在Hub发现有趣环境后秒级启动实验,无需担心依赖冲突或复杂安装流程。
三、仓库结构
要使环境可从 Hub 加载,仓库至少需包含:
3.1 必备文件
3.1.1 env.py(或自定义 Python 文件)
- 必须暴露 make_env(n_envs: int, use_async_envs: bool) 函数
- 该函数应返回以下类型之一:
- gym.vector.VectorEnv(最常见)
- 单个 gym.Env 对象(将自动封装)
- 映射 {suite_name: {task_id: VectorEnv}} 的字典(适用于多任务基准测试)
3.2 可选文件
3.2.1 requirements.txt
- 列出环境所需的额外依赖项
- 用户需在加载环境前手动安装这些依赖
3.2.2 README.md
- 记录环境文档:实现的任务、观察/动作空间、奖励机制等
- 包含使用示例及特殊配置说明
3.2.3 .gitignore
- 从仓库中排除非必要文件
3.3 示例仓库结构
my-environment-repo/
├── env.py # Main environment definition (required)
├── requirements.txt # Dependencies (optional)
├── README.md # Documentation (recommended)
├── assets/ # Images, videos, etc. (optional)
│ └── demo.gif
└── configs/ # Config files if needed (optional)└── task_config.yaml
四、创建环境仓库
4.1 定义环境
创建一个包含 make_env 函数的 env.py 文件:
# env.py
import gymnasium as gymdef make_env(n_envs: int = 1, use_async_envs: bool = False):"""Create vectorized environments for your custom task.Args:n_envs: Number of parallel environmentsuse_async_envs: Whether to use AsyncVectorEnv or SyncVectorEnvReturns:gym.vector.VectorEnv or dict mapping suite names to vectorized envs"""def _make_single_env():# Create your custom environmentreturn gym.make("CartPole-v1")# Choose vector environment typeenv_cls = gym.vector.AsyncVectorEnv if use_async_envs else gym.vector.SyncVectorEnv# Create vectorized environmentvec_env = env_cls([_make_single_env for _ in range(n_envs)])return vec_env
4.2 本地测试
上传前,请在本地环境进行测试:
from lerobot.envs.utils import _load_module_from_path, _call_make_env, _normalize_hub_result# Load your module
module = _load_module_from_path("./env.py")# Test the make_env function
result = _call_make_env(module, n_envs=2, use_async_envs=False)
normalized = _normalize_hub_result(result)# Verify it works
suite_name = next(iter(normalized))
env = normalized[suite_name][0]
obs, info = env.reset()
print(f"Observation shape: {obs.shape if hasattr(obs, 'shape') else type(obs)}")
env.close()
4.3 上传至Hub
将您的存储库上传至Hugging Face:
# Install huggingface_hub if needed
pip install huggingface_hub# Login to Hugging Face
huggingface-cli login# Create a new repository
huggingface-cli repo create my-custom-env --type space --org my-org# Initialize git and push
git init
git add .
git commit -m "Initial environment implementation"
git remote add origin https://huggingface.co/my-org/my-custom-env
git push -u origin main
或者,使用 huggingface_hub Python API:
from huggingface_hub import HfApiapi = HfApi()# Create repository
api.create_repo("my-custom-env", repo_type="space")# Upload files
api.upload_folder(folder_path="./my-env-folder",repo_id="username/my-custom-env",repo_type="space",
)
五、从Hub加载环境
5.1 基本用法
from lerobot.envs.factory import make_env# Load from the hub
envs_dict = make_env("username/my-custom-env",n_envs=4,trust_remote_code=True
)# Access the environment
suite_name = next(iter(envs_dict))
env = envs_dict[suite_name][0]# Use it like any gym environment
obs, info = env.reset()
action = env.action_space.sample()
obs, reward, terminated, truncated, info = env.step(action)
5.2 高级:固定到特定版本
为确保可重复性和安全性,请固定到特定的Git修订版本:
# Pin to a specific branch
env = make_env("username/my-env@main", trust_remote_code=True)# Pin to a specific commit (recommended for papers/experiments)
env = make_env("username/my-env@abc123def456", trust_remote_code=True)# Pin to a tag
env = make_env("username/my-env@v1.0.0", trust_remote_code=True)
5.3 自定义文件路径
如果您的环境定义不在 env.py 中:
# Load from a custom file
env = make_env("username/my-env:custom_env.py", trust_remote_code=True)# Combine with version pinning
env = make_env("username/my-env@v1.0:envs/task_a.py", trust_remote_code=True)
5.4 异步环境
为在多环境中获得更佳性能:
envs_dict = make_env("username/my-env",n_envs=8,use_async_envs=True, # Use AsyncVectorEnv for parallel executiontrust_remote_code=True
)
六、URL格式参考
Hub URL格式支持多种模式:
| Pattern | Description | Example |
|---|---|---|
user/repo | Load env.py from main branch | make_env("lerobot/pusht-env") |
user/repo@revision | Load from specific revision | make_env("lerobot/pusht-env@main") |
user/repo:path | Load custom file | make_env("lerobot/envs:pusht.py") |
user/repo@rev:path | Revision + custom file | make_env("lerobot/envs@v1:pusht.py") |
七、多任务环境
对于包含多个任务的基准测试(如LIBERO),返回一个嵌套字典:
def make_env(n_envs: int = 1, use_async_envs: bool = False):env_cls = gym.vector.AsyncVectorEnv if use_async_envs else gym.vector.SyncVectorEnv# Return dict: {suite_name: {task_id: VectorEnv}}return {"suite_1": {0: env_cls([lambda: gym.make("Task1-v0") for _ in range(n_envs)]),1: env_cls([lambda: gym.make("Task2-v0") for _ in range(n_envs)]),},"suite_2": {0: env_cls([lambda: gym.make("Task3-v0") for _ in range(n_envs)]),}}
八、安全注意事项
**重要提示**:从 Hub 执行环境代码时必须设置 `trust_remote_code=True` 标志。此设计出于安全考虑。
从 Hub 加载环境时:
- 首先审查代码:访问仓库并检查 env.py 文件后再加载
- 绑定至提交记录:使用特定提交哈希值确保可复现性
- 检查依赖项:审查 requirements.txt 文件中的可疑包
- 使用可信来源:优先选择官方组织或知名研究者
- 必要时使用沙箱:在隔离环境(容器/虚拟机)中运行不可信代码
安全使用示例:
# ❌ BAD: Loading without inspection
env = make_env("random-user/untrusted-env", trust_remote_code=True)# ✅ GOOD: Review code, then pin to specific commit
# 1. Visit https://huggingface.co/trusted-org/verified-env
# 2. Review the env.py file
# 3. Copy the commit hash
env = make_env("trusted-org/verified-env@a1b2c3d4", trust_remote_code=True)
九、示例:来自 Hub 的 CartPole
以下是一个使用参考 CartPole 环境的完整示例:
from lerobot.envs.factory import make_env
import numpy as np# Load the environment
envs_dict = make_env("lerobot/cartpole-env", n_envs=4, trust_remote_code=True)# Get the vectorized environment
suite_name = next(iter(envs_dict))
env = envs_dict[suite_name][0]# Run a simple episode
obs, info = env.reset()
done = np.zeros(env.num_envs, dtype=bool)
total_reward = np.zeros(env.num_envs)while not done.all():# Random policyaction = env.action_space.sample()obs, reward, terminated, truncated, info = env.step(action)total_reward += rewarddone = terminated | truncatedprint(f"Average reward: {total_reward.mean():.2f}")
env.close()
十、EnvHub的优势
10.1 面向环境作者
- 轻松分发:无需PyPI打包
- 版本控制:使用Git管理环境版本
- 快速迭代:即时推送更新
- 文档呈现:Hub的README文件美观渲染
- 社区覆盖:直接触达LeRobot用户
10.2 面向研究人员
- 快速实验:一行代码加载任意环境
- 可重复性:固定至特定提交版本
- 探索:在Hub浏览环境
- 零冲突:无需安装冲突包
10.3 面向社区
- 生态扩展:支持更多元化的模拟任务
- 标准化:通用make_env API
- 协作:分叉并改进现有环境
- 易用性:降低研究成果共享门槛
十一、故障排除
11.1 “拒绝执行远程代码” “Refusing to execute remote code”
必须显式传递trust_remote_code=True参数:
env = make_env("user/repo", trust_remote_code=True)
11.2 “未找到模块 X” “Module X not found”
集线器环境存在您需要安装的依赖项:
# Check the repo's requirements.txt and install dependencies
pip install gymnasium numpy
11.3 “在模块中找不到 make_env” “make_env not found in module”
您的 env.py 必须暴露一个 make_env 函数:
def make_env(n_envs: int, use_async_envs: bool):# Your implementationpass
11.4 环境返回类型错误
make_env函数必须返回:
- 一个gym.vector.VectorEnv对象,或
- 一个单一的gym.Env对象,或
- 一个字典{suite_name: {task_id: VectorEnv}}
十二、最佳实践
- 文档化环境:在README中包含观察/动作空间描述、奖励结构和终止条件
- 添加 requirements.txt:列出所有依赖项及其版本
- 全面测试:提交前验证环境在本地运行正常
- 采用语义化版本控制:为版本发布添加标签
- 添加示例:在 README 中包含使用示例
- 保持简洁:尽可能减少依赖项
- 授权作品:添加 LICENSE 文件明确使用条款
十三、未来方向
EnvHub 生态系统开启无限可能:
- GPU加速物理引擎:共享Isaac Gym或Brax环境
- 真实感渲染:分发具备高级图形处理能力的环境
- 多智能体场景:复杂交互任务
- 真实世界模拟器:物理装置的数字孪生
- 过程化生成:无限任务变体
- 领域随机化:预配置的DR管道
随着更多研究者和开发者的贡献,可用环境的多样性与质量将持续提升,惠及整个机器人学习社区。
