Skip to content

Index

cosmic_warp.rl

COSMIC WARP reinforcement-learning layer.

A thin, GPU-resident, framework-neutral environment over the spacecraft simulator. The core (:class:VecEnv + the :class:Task protocol) has no learning-framework dependency; PyTorch is used only for optional zero-copy tensor views. Tasks are application code: examples/attitude_task.py is a reference implementation.

from cosmic_warp.core.config import create_simulator_from_yaml
from cosmic_warp.rl import VecEnv
from attitude_task import AttitudeTask   # examples/attitude_task.py

sim = create_simulator_from_yaml("examples/rl_attitude_training.yaml")
env = VecEnv(sim, AttitudeTask(), max_episode_steps=500)
obs = env.reset()
for _ in range(horizon):
    obs, reward, terminated, truncated = env.step(action)

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)

Task

Bases: Protocol

Minimal task interface consumed by :class:~cosmic_warp.rl.env.VecEnv.

A task exposes its per-environment action/observation widths and three device-side operations. VecEnv calls bind once at construction, then ingest_actions / write_reward / write_obs every step.

bind

bind(env) -> None

Cache the simulator handles and compute act_dim / obs_dim.

Source code in cosmic_warp/rl/tasks.py
def bind(self, env) -> None:
    """Cache the simulator handles and compute ``act_dim`` / ``obs_dim``."""
    ...

ingest_actions

ingest_actions(action: array) -> None

Map normalized actions [N, act_dim] (f32) into actuator commands.

Source code in cosmic_warp/rl/tasks.py
def ingest_actions(self, action: wp.array) -> None:
    """Map normalized actions ``[N, act_dim]`` (f32) into actuator commands."""
    ...

write_obs

write_obs(
    obs: array, reset_env: array, masked: int
) -> None

Pack the observation into obs [N, obs_dim] (f32).

When masked == 1 only rows where reset_env is True are written (the post-reset rewrite for auto-reset environments); when masked == 0 every row is written.

Source code in cosmic_warp/rl/tasks.py
def write_obs(self, obs: wp.array, reset_env: wp.array, masked: int) -> None:
    """Pack the observation into ``obs`` ``[N, obs_dim]`` (f32).

    When ``masked == 1`` only rows where ``reset_env`` is True are written
    (the post-reset rewrite for auto-reset environments); when ``masked ==
    0`` every row is written.
    """
    ...

write_reward

write_reward(reward: array, action: array) -> None

Write the per-environment reward into reward [N] (f32).

action is the (already ingested) normalized action of the current step, available for control-effort penalties.

Source code in cosmic_warp/rl/tasks.py
def write_reward(self, reward: wp.array, action: wp.array) -> None:
    """Write the per-environment reward into ``reward`` ``[N]`` (f32).

    ``action`` is the (already ingested) normalized action of the current
    step, available for control-effort penalties.
    """
    ...