venvs#


class BaseVectorEnv(env_fns: Sequence[Callable[[], Env | PettingZooEnv]], worker_fn: Callable[[Callable[[], Env | PettingZooEnv]], EnvWorker], wait_num: int | None = None, timeout: float | None = None)[source]#

Base class for vectorized environments.

Usage:

env_num = 8
envs = DummyVectorEnv([lambda: gym.make(task) for _ in range(env_num)])
assert len(envs) == env_num

It accepts a list of environment generators. In other words, an environment generator efn of a specific task means that efn() returns the environment of the given task, for example, gym.make(task).

All of the VectorEnv must inherit BaseVectorEnv. Here are some other usages:

envs.seed(2)  # which is equal to the next line
envs.seed([2, 3, 4, 5, 6, 7, 8, 9])  # set specific seed for each env
obs = envs.reset()  # reset all environments
obs = envs.reset([0, 5, 7])  # reset 3 specific environments
obs, rew, done, info = envs.step([1] * 8)  # step synchronously
envs.render()  # render all environments
envs.close()  # close all environments

Warning

If you use your own environment, please make sure the seed method is set up properly, e.g.,

def seed(self, seed):
    np.random.seed(seed)

Otherwise, the outputs of these envs may be the same with each other.

Parameters:
  • env_fns – a list of callable envs, env_fns[i]() generates the i-th env.

  • worker_fn – a callable worker, worker_fn(env_fns[i]) generates a worker which contains the i-th env.

  • wait_num – use in asynchronous simulation if the time cost of env.step varies with time and synchronously waiting for all environments to finish a step is time-wasting. In that case, we can return when wait_num environments finish a step and keep on simulation in these environments. If None, asynchronous simulation is disabled; else, 1 <= wait_num <= env_num.

  • timeout – use in asynchronous simulation same as above, in each vectorized step it only deal with those environments spending time within timeout seconds.

close() None[source]#

Close all of the environments.

This function will be called only once (if not, it will be called during garbage collected). This way, close of all workers can be assured.

get_env_attr(key: str, id: int | list[int] | ndarray | None = None) list[Any][source]#

Get an attribute from the underlying environments.

If id is an int, retrieve the attribute denoted by key from the environment underlying the worker at index id. The result is returned as a list with one element. Otherwise, retrieve the attribute for all workers at indices id and return a list that is ordered correspondingly to id.

Parameters:
  • key (str) – The key of the desired attribute.

  • id – Indice(s) of the desired worker(s). Default to None for all env_id.

Return list:

The list of environment attributes.

render(**kwargs: Any) list[Any][source]#

Render all of the environments.

reset(id: int | list[int] | ndarray | None = None, **kwargs: Any) tuple[ndarray, dict | list[dict]][source]#

Reset the state of some envs and return initial observations.

If id is None, reset the state of all the environments and return initial observations, otherwise reset the specific environments with the given id, either an int or a list.

seed(seed: int | list[int] | None = None) list[list[int] | None][source]#

Set the seed for all environments.

Accept None, an int (which will extend i to [i, i + 1, i + 2, ...]) or a list.

Returns:

The list of seeds used in this env’s random number generators. The first value in the list should be the “main” seed, or the value which a reproducer pass to “seed”.

set_env_attr(key: str, value: Any, id: int | list[int] | ndarray | None = None) None[source]#

Set an attribute in the underlying environments.

If id is an int, set the attribute denoted by key from the environment underlying the worker at index id to value. Otherwise, set the attribute for all workers at indices id.

Parameters:
  • key (str) – The key of the desired attribute.

  • value (Any) – The new value of the attribute.

  • id – Indice(s) of the desired worker(s). Default to None for all env_id.

step(action: ndarray | Tensor, id: int | list[int] | ndarray | None = None) tuple[ndarray, ndarray, ndarray, ndarray, ndarray][source]#

Run one timestep of some environments’ dynamics.

If id is None, run one timestep of all the environments` dynamics; otherwise run one timestep for some environments with given id, either an int or a list. When the end of episode is reached, you are responsible for calling reset(id) to reset this environment`s state.

Accept a batch of action and return a tuple (batch_obs, batch_rew, batch_done, batch_info) in numpy format.

Parameters:

action (numpy.ndarray) – a batch of action provided by the agent.

Returns:

A tuple consisting of either:

  • obs a numpy.ndarray, the agent’s observation of current environments

  • rew a numpy.ndarray, the amount of rewards returned after previous actions

  • terminated a numpy.ndarray, whether these episodes have been terminated

  • truncated a numpy.ndarray, whether these episodes have been truncated

  • info a numpy.ndarray, contains auxiliary diagnostic information (helpful for debugging, and sometimes learning)

For the async simulation:

Provide the given action to the environments. The action sequence should correspond to the id argument, and the id argument should be a subset of the env_id in the last returned info (initially they are env_ids of all the environments). If action is None, fetch unfinished step() calls instead.

class DummyVectorEnv(env_fns: Sequence[Callable[[], Env | PettingZooEnv]], wait_num: int | None = None, timeout: float | None = None)[source]#

Dummy vectorized environment wrapper, implemented in for-loop.

This has the same interface as true vectorized environment, but the rollout does not happen in parallel. So, all workers just wait for each other and the environment is as efficient as using a single environment. This can be useful for testing or for demonstration purposes.

A rare use-case would be using vector based interface, but parallelization is not desired (e.g. because of too much overhead). However, in such cases one should consider using a single environment.

See also

Please refer to BaseVectorEnv for other APIs’ usage.

class RayVectorEnv(env_fns: Sequence[Callable[[], Env | PettingZooEnv]], wait_num: int | None = None, timeout: float | None = None)[source]#

Vectorized environment wrapper based on ray.

This is a choice to run distributed environments in a cluster.

See also

Please refer to BaseVectorEnv for other APIs’ usage.

class ShmemVectorEnv(env_fns: Sequence[Callable[[], Env | PettingZooEnv]], wait_num: int | None = None, timeout: float | None = None)[source]#

Optimized SubprocVectorEnv with shared buffers to exchange observations.

ShmemVectorEnv has exactly the same API as SubprocVectorEnv.

See also

Please refer to BaseVectorEnv for other APIs’ usage.

class SubprocVectorEnv(env_fns: Sequence[Callable[[], Env | PettingZooEnv]], wait_num: int | None = None, timeout: float | None = None, share_memory: bool = False, context: Literal['fork', 'spawn'] | None = None)[source]#

Vectorized environment wrapper based on subprocess.

See also

Please refer to BaseVectorEnv for other APIs’ usage.

Additional arguments are:

param share_memory:

whether to share memory between the main process and the worker process. Allows for shared buffers to exchange observations

param context:

the context to use for multiprocessing. Usually it’s fine to use the default context, but spawn as well as fork can have non-obvious side effects, see for example google-deepmind/mujoco#742, or Farama-Foundation/Gymnasium#222. Consider using ‘fork’ when using macOS and additional parallelization, for example via joblib. Defaults to None, which will use the default system context.