Skip to content

Gym interop

Vectorized Gymnasium-compatible environments over DynaPlex MDPs — see the user guide. Requires the optional gymnasium dependency (pip install "dynaplex[gym]").

VectorEnv

VectorEnv(mdp: MDPProtocol, *, features: type[Featurizer], num_envs: int = 256, max_episode_steps: int | None = None, autoreset_mode: AutoresetMode | str = AutoresetMode.NEXT_STEP, workers: int = 0, backend: str = 'engine', jit: bool | None = None, checks: bool | Literal['rehearsal'] | None = None, max_steps: int = 1 << 20)

Bases: _GymnasiumVectorEnv

Vectorized Gymnasium environment over a DynaPlex MDP.

Parameters:

Name Type Description Default
mdp MDPProtocol

the MDP instance. Observations come from features, actions are Discrete(mdp.num_actions) with the validity mask riding in infos["action_mask"].

required
features type[Featurizer]

the featurizer CLASS (@featurizer-decorated). Observations are BUNDLES: the observation space is a spaces.Dict with one Box per spec tensor (keyed by writer field name), and reset/step return dicts of batched arrays (SB3's CombinedExtractor / gym Dict-space convention).

required
num_envs int

number of parallel environments (kernel slots). Hundreds is the intended regime — per-step overhead is per STEP, not per env.

256
max_episode_steps int | None

time-based truncation cap in units of context.time_elapsed (None = 2048 for infinite-horizon MDPs, never for finite-horizon ones).

None
autoreset_mode AutoresetMode | str

a gymnasium.vector.AutoresetMode (or its string value): NEXT_STEP (the default, as in Gymnasium), SAME_STEP or DISABLED. What each does at an episode's end is in the module docstring. Also in metadata["autoreset_mode"].

AutoresetMode.NEXT_STEP
workers int

worker worlds of the engine backend. 0 = auto (cpu_count - 2, capped at num_envs). Pure throughput knob: trajectories are worker-count-invariant bit-for-bit.

0
backend str

"engine" (default) | "python" | "auto" (explicit fallback), see the module docstring.

'engine'
jit bool | None

passed through to Engine (None = auto). Engine backend only.

None
checks bool | Literal['rehearsal'] | None

runtime checks in the compiled kernels (roadmap/checks_mode.md). "rehearsal" (default): a small CHECKED twin env first runs a short seeded pass with uniformly random valid actions, then the real env compiles FAST. True = checked throughout; False = fast, no rehearsal; None = DYNAPLEX_CHECKS=0|1 if set, else "rehearsal".

None
max_steps int

per-episode raw-step safety cap (events + actions), guarding MDPs that stall without advancing time or reaching FINAL.

1 << 20

reset

reset(seed: int | None = None, options: dict[str, Any] | None = None, env_id: NDArray[np.int_] | None = None) -> tuple[dict[str, np.ndarray], dict[str, Any]]

Start fresh episodes and return (observations, infos).

Full-width (env_id=None): every slot restarts. seed re-derives all episode streams (a later reset(seed=s) with the same s replays byte-identically); without a seed the streams CONTINUE — current episodes are abandoned and each slot starts its next one.

Subset (AutoresetMode.DISABLED only): exactly the named envs start their NEXT episode. env_id=... is tianshou's form: the return covers only those rows, in the given order. options={"reset_mask": mask} (one bool per env) is Gymnasium's form: the return is full width. The streams keep their seeding, so a park-and-revive run reproduces the autoreset runs' episodes exactly.

step

step(actions, ready_env_ids: NDArray[np.int_] | None = None, *, id: NDArray[np.int_] | None = None) -> tuple[dict[str, np.ndarray], NDArray[np.float32], NDArray[np.bool_], NDArray[np.bool_], dict[str, Any]]

Advance envs by one action each to their next decision point.

Full-width (no ids): actions has one entry per env and every return is full width. With ready_env_ids (tianshou passes it positionally; id= is the same argument) only those envs advance, actions may be either full width or one entry per id, and every return covers exactly the addressed rows in the given order.

Rewards are -(cost incurred during the step). What an env whose episode ended returns depends on autoreset_mode (module docstring): its end state, with the next step() starting the next episode (NEXT_STEP); the NEW episode's observation, with the end state in infos["final_obs"] and infos["_final_obs"] marking the rows (SAME_STEP); or its end state, parked until it is reset (DISABLED, infos["live"] False).

seed

seed(seed: int | None = None) -> None

Tianshou-style seeding: equivalent to reset(seed=seed).

TianshouVectorEnv

TianshouVectorEnv(mdp: MDPProtocol, *, features: type[Featurizer], num_envs: int = 256, max_episode_steps: int | None = None, workers: int = 0, backend: str = 'engine', jit: bool | None = None, checks: bool | Literal['rehearsal'] | None = None, max_steps: int = 1 << 20)

Tianshou-shaped vectorized environment over a DynaPlex MDP.

Takes the same arguments as dynaplex.gym.VectorEnv except autoreset_mode, which is AutoresetMode.DISABLED (park mode). See the module docstring for the contract differences this adapter absorbs, and VectorEnv for what the arguments mean.

Raises:

Type Description
ValueError

if the featurizer declares a tensor named mask — the adapter needs that key in the observation for the action mask.

reset

reset(env_id: int | list[int] | np.ndarray | None = None, **kwargs: Any) -> tuple[Batch, NDArray[np.object_]]

Reset all envs (env_id=None) or exactly the given ones.

A seed in the reset kwargs applies to a FULL reset only — it re-derives every episode stream. On a subset reset it is IGNORED (with no error, so a collector's gym_reset_kwargs keeps working): the streams are seeded per (env, episode index) from the experiment seed, and a revived env simply continues its own stream.

step

step(action: np.ndarray | Any, id: int | list[int] | np.ndarray | None = None) -> tuple[Batch, NDArray[np.float64], NDArray[np.bool_], NDArray[np.bool_], NDArray[np.object_]]

Step all envs (id=None) or exactly the given ones, one action each.

Every return covers the addressed envs, in the given order. An env whose episode ends returns its TERMINAL observation and then stands parked until the caller resets it — tianshou's collector does exactly that.

seed

seed(seed: int | list[int] | None = None) -> list[list[int] | None]

Set the experiment seed used by the NEXT full reset (tianshou seeds, then resets). A list is not supported — episode streams are derived from one experiment seed plus the env index — so its first entry is used.

get_env_attr

get_env_attr(key: str, id: int | list[int] | np.ndarray | None = None) -> list[Any]

Read an attribute of the underlying MDP, once per addressed env (all envs share one MDP instance, so the entries are identical).