""" ManiSkill StackThreeCube 向量化环境构造。 - ``sim_backend=gpu``:单进程内 ``num_envs=n``(GPU 批量仿真)。 - ``sim_backend=cpu``:禁止单进程 ``num_envs>1``,使用 ``AsyncVectorEnv`` 多进程,每进程 ``num_envs=1``。 SAC / PPO 等脚本应复用 ``make_batched_stack_threecube_env``,避免再踩坑。 """ from __future__ import annotations import os from typing import Any def single_action_space(env: Any) -> Any: """ManiSkill 批量 env 与 gymnasium.VectorEnv:用 single_action_space 表示单环境动作。""" return getattr(env, "single_action_space", env.action_space) def make_batched_stack_threecube_env( *, env_id: str, obs_mode: str, control_mode: str, sim_backend: str, render_backend: str, num_envs: int, ) -> Any: import gymnasium as gym from gymnasium.vector import AsyncVectorEnv import mani_skill.envs # noqa: F401 — 注册 ManiSkill 内置环境 import vagen.env.primitive_skill.maniskill.env # noqa: F401 — 注册 StackThreeCube n = int(num_envs) sb = str(sim_backend).lower() if sb == "cpu" and n > 1: def make_one() -> Any: # Worker 进程里强制不暴露 CUDA,避免 CPU-sim reset 触发 torch.cuda 初始化。 os.environ.setdefault("CUDA_VISIBLE_DEVICES", "") return gym.make( env_id, num_envs=1, obs_mode=obs_mode, control_mode=control_mode, render_mode="rgb_array", sim_backend=sim_backend, render_backend=render_backend, ) if n >= 32: print( f"[maniskill_vector_env] CPU 仿真 + AsyncVectorEnv:将启动 {n} 个子进程;" "大规模训练请使用 --sim-backend gpu。" ) return AsyncVectorEnv( [make_one for _ in range(n)], shared_memory=False, context="spawn", ) return gym.make( env_id, num_envs=n, obs_mode=obs_mode, control_mode=control_mode, render_mode="rgb_array", sim_backend=sim_backend, render_backend=render_backend, )