Skip to content

env

cosmic_warp.rl.env

Vectorized RL environment.

:class:VecEnv wraps a :class:~cosmic_warp.core.pipeline.SpacecraftSimulator and adds a fused, fully on-device RL step:

action -> ingest -> physics -> reward -> done -> observation -> auto-reset

Everything stays on the GPU. The whole step is captured once into a CUDA graph and replayed, so per-step launch overhead is eliminated and there is no host synchronization inside :meth:step. Boundary tensors (action, obs, reward) are float32; the physics stays float64 internally.

The step returns (obs, reward, terminated, truncated) as Warp arrays. terminated and truncated are kept separate (never collapsed into a single done) so trainers can bootstrap truncated episodes correctly; :attr:terminal_obs holds the pre-reset observation for that.

Trainer interop is deliberately out of scope here: the arrays are exposed natively and via zero-copy *_torch() views (dlpack, same GPU memory), and trainer-specific adapters live separately so this core stays neutral.

VecEnv

VecEnv(
    sim: SpacecraftSimulator,
    task: Task,
    max_episode_steps: int,
)

Vectorized, GPU-resident RL environment over a spacecraft simulator.

Parameters:

Name Type Description Default
sim SpacecraftSimulator

A constructed simulator (e.g. from create_simulator_from_yaml). sim.num_envs environments are stepped in parallel.

required
task Task

The task defining action mapping, observation and reward.

required
max_episode_steps int

Episode length after which an environment is truncated (time limit) and auto-reset, in [1, 2**31 - 1].

required
Source code in cosmic_warp/rl/env.py
def __init__(self, sim: SpacecraftSimulator, task: Task, max_episode_steps: int):
    self.sim = sim
    self.task = task
    self._graph = None
    self.max_episode_steps = max_episode_steps

    self.num_envs = sim.num_envs
    self.num_bodies = sim.num_bodies
    self.num_entities = sim.num_entities
    self.device = sim.device

    task.bind(self)
    self.obs_dim = task.obs_dim
    self.act_dim = task.act_dim

    d = self.device
    N, E = self.num_envs, self.num_entities

    # Persistent boundary buffers (allocated once, written in place).
    self._actions = wp.zeros((N, self.act_dim), dtype=wp.float32, device=d)
    self._obs = wp.zeros((N, self.obs_dim), dtype=wp.float32, device=d)
    self._terminal_obs = wp.zeros((N, self.obs_dim), dtype=wp.float32, device=d)
    self._reward = wp.zeros(N, dtype=wp.float32, device=d)
    self._terminated = wp.zeros(N, dtype=wp.bool, device=d)
    self._truncated = wp.zeros(N, dtype=wp.bool, device=d)

    # Internal masks: per-env done (drives obs rewrite / terminal copy) and
    # per-entity done (drives the masked resets).
    self.reset_env = wp.zeros(N, dtype=wp.bool, device=d)
    self.done_mask = wp.zeros(E, dtype=wp.bool, device=d)

actions class-attribute instance-attribute

actions = _buffer('actions')

Normalized actions [N, act_dim] (f32), read by step().

obs class-attribute instance-attribute

obs = _buffer('obs')

Observations [N, obs_dim] (f32).

terminal_obs class-attribute instance-attribute

terminal_obs = _buffer('terminal_obs')

Pre-reset observations [N, obs_dim] (f32) of the last step.

reward class-attribute instance-attribute

reward = _buffer('reward')

Rewards [N] (f32) of the last step.

terminated class-attribute instance-attribute

terminated = _buffer('terminated')

Terminated flags [N] (bool) of the last step.

truncated class-attribute instance-attribute

truncated = _buffer('truncated')

Truncated (time-limit) flags [N] (bool) of the last step.

max_episode_steps property writable

max_episode_steps: int

Episode length after which an environment is truncated and auto-reset. Setting it re-captures the step graph on the next step.

reset

reset() -> array

Reset every environment and return the initial observation [N, O].

Source code in cosmic_warp/rl/env.py
def reset(self) -> wp.array:
    """Reset every environment and return the initial observation ``[N, O]``."""
    self.sim.reset()
    self.terminated.zero_()
    self.truncated.zero_()
    self.reset_env.zero_()
    self.task.write_obs(self.obs, self.reset_env, 0)
    return self.obs

step

step(
    action: Optional[array] = None,
) -> Tuple[array, array, array, array]

Advance every environment by one control step.

Parameters:

Name Type Description Default
action Optional[array]

Normalized actions [N, act_dim] (f32). If given, copied into the persistent action buffer; if None, whatever is already in :attr:actions (or its torch view) is used.

None

Raises:

Type Description
ValueError

if action is not a Warp array of the action buffer's shape, dtype and device (checked on metadata only, no device sync).

Returns:

Type Description
array

(obs, reward, terminated, truncated) as Warp arrays. All are

array

reused buffers — copy into trainer storage each step, do not retain

array

a view across steps.

Source code in cosmic_warp/rl/env.py
def step(
    self, action: Optional[wp.array] = None
) -> Tuple[wp.array, wp.array, wp.array, wp.array]:
    """Advance every environment by one control step.

    Args:
        action: Normalized actions ``[N, act_dim]`` (f32). If given, copied
            into the persistent action buffer; if ``None``, whatever is
            already in :attr:`actions` (or its torch view) is used.

    Raises:
        ValueError: if ``action`` is not a Warp array of the action
            buffer's shape, dtype and device (checked on metadata only,
            no device sync).

    Returns:
        ``(obs, reward, terminated, truncated)`` as Warp arrays. All are
        reused buffers — copy into trainer storage each step, do not retain
        a view across steps.
    """
    # A set_config(inertia=...) since the last step becomes the nominal the
    # auto-reset's inertia_scale applies to. Host-side version check,
    # outside the graph; uploads only when the inertia changed.
    self.sim.randomizer.sync_nominal()

    if action is not None:
        # wp.copy of a smaller or differently typed array would silently
        # fill the buffer partially
        if (not isinstance(action, wp.array) or action.shape != self.actions.shape
                or action.dtype != wp.float32 or action.device != self.actions.device):
            raise ValueError(
                f"action must be a float32 Warp array of shape {self.actions.shape} on "
                f"{self.actions.device}, got {validation.describe(action)}"
            )
        wp.copy(self.actions, action)

    if self._use_graph:
        if self._graph is None:
            with wp.ScopedCapture(device=self.device) as capture:
                self._step_body()
            self._graph = capture.graph
        wp.capture_launch(self._graph)
    else:
        self._step_body()

    return self.obs, self.reward, self.terminated, self.truncated

invalidate_graph

invalidate_graph() -> None

Drop the captured CUDA graph so the next :meth:step re-captures it.

The capture bakes in every scalar passed by value to a kernel launch (task parameters such as reward weights) and the randomizer.enabled branch. Call this after changing any of them mid-run; otherwise the change silently has no effect on CUDA. Setting :attr:max_episode_steps calls it for you.

Source code in cosmic_warp/rl/env.py
def invalidate_graph(self) -> None:
    """Drop the captured CUDA graph so the next :meth:`step` re-captures it.

    The capture bakes in every scalar passed by value to a kernel launch
    (task parameters such as reward weights) and the
    ``randomizer.enabled`` branch. Call this after changing any of them
    mid-run; otherwise the change silently has no effect on CUDA. Setting
    :attr:`max_episode_steps` calls it for you.
    """
    self._graph = None

observations_torch

observations_torch()

Zero-copy torch view of :attr:obs (requires torch).

Source code in cosmic_warp/rl/env.py
def observations_torch(self):
    """Zero-copy torch view of :attr:`obs` (requires torch)."""
    return self._torch(self.obs)

actions_torch

actions_torch()

Zero-copy torch view of :attr:actions; write policy output here.

Source code in cosmic_warp/rl/env.py
def actions_torch(self):
    """Zero-copy torch view of :attr:`actions`; write policy output here."""
    return self._torch(self.actions)

rewards_torch

rewards_torch()

Zero-copy torch view of :attr:reward.

Source code in cosmic_warp/rl/env.py
def rewards_torch(self):
    """Zero-copy torch view of :attr:`reward`."""
    return self._torch(self.reward)

terminated_torch

terminated_torch()

Zero-copy torch view of :attr:terminated.

Source code in cosmic_warp/rl/env.py
def terminated_torch(self):
    """Zero-copy torch view of :attr:`terminated`."""
    return self._torch(self.terminated)

truncated_torch

truncated_torch()

Zero-copy torch view of :attr:truncated.

Source code in cosmic_warp/rl/env.py
def truncated_torch(self):
    """Zero-copy torch view of :attr:`truncated`."""
    return self._torch(self.truncated)

terminal_observations_torch

terminal_observations_torch()

Zero-copy torch view of :attr:terminal_obs.

Source code in cosmic_warp/rl/env.py
def terminal_observations_torch(self):
    """Zero-copy torch view of :attr:`terminal_obs`."""
    return self._torch(self.terminal_obs)