Skip to content

diff_bridge

cosmic_warp.rl.diff_bridge

Warp <-> torch autograd bridge: differentiable sim steps as torch autograd nodes.

:class:DiffSimStepper exposes one simulator integration step as a torch.autograd.Function: flat float64 torch tensors in (state x, actuator command u), flat float64 torch tensor out (next state), with the step's warp kernels recorded on a per-call wp.Tape whose adjoint runs in the node's backward. Chaining step() calls under torch autograd yields the exact interleaved gradient through dynamics and anything torch-side in the loop (a policy a_t = pi(o_t), a reward, ...) — the foundation for first-order RL (SHAC).

sim = SpacecraftSimulator(..., differentiable=True, check_bounds=False)
stepper = DiffSimStepper(sim)
x = stepper.read_state()                     # [E, X_DIM] f64, detached
x.requires_grad_(True)
for t in range(horizon):
    u = policy(x)                            # [E, U_DIM] f64, on-graph
    x = stepper.step(x, u)                   # differentiable sim step
loss = objective(x)
loss.backward()                              # adjoints through all steps

Each differentiable step() call allocates its own tape and warp buffers (freed with the autograd graph), so any autograd pattern is safe: repeated backward with retain_graph=True, torch.autograd.gradcheck's interleaved numeric and analytic passes, and slot-free window chaining. When no gradient can flow (torch.no_grad() or detached inputs), step() switches to an untaped fast path with reused buffers — evaluation and inference loops pay no taping cost. Buffer pooling for the differentiable path is a later optimization if per-step allocation ever shows up in profiles.

Each differentiable step runs on a snapshot of the vehicle, thruster and wheel configurations, so its backward replays the parameters its forward used: resetting the simulator (which redraws randomized parameters) or calling set_config between a step and its backward does not change the gradient. A taped step copies the three arrays; inside :meth:DiffSimStepper.frozen_params the steps share one copy instead.

Gradients are first order only: the backward pass is a Warp adjoint, not a torch graph, so double backward (Hessian-vector products, gradient penalties) raises instead of treating the step Jacobian as a constant.

Same requirements as :class:~cosmic_warp.core.autodiff.DifferentiableRollout: the simulator must be built with differentiable=True and termination checks disabled, everything is float64, and taped steps cannot be CUDA-graph captured.

DiffSimStepper

DiffSimStepper(sim: SpacecraftSimulator)

Differentiable per-step interface to a simulator (torch boundary).

Parameters:

Name Type Description Default
sim SpacecraftSimulator

A :class:~cosmic_warp.core.pipeline.SpacecraftSimulator built with differentiable=True and termination checks disabled (check_bounds=False, check_planet_impact=False): the integrator freezes terminated entities, which would silently kill their gradient paths.

required

The stepper never mutates the simulator: taped steps use a scratch episode_steps counter and their own state buffers. Use :meth:read_state / :meth:write_state to move state between the simulator (resets, evaluation) and the differentiable chain.

A taped step reads the vehicle, thruster and wheel configurations from a copy taken at its forward, which its backward reuses; the simulator may be reset or reconfigured before backward().

Source code in cosmic_warp/rl/diff_bridge.py
def __init__(self, sim: SpacecraftSimulator):
    if not getattr(sim, "differentiable", False):
        raise RuntimeError(
            "Simulator was not created with differentiable=True; adjoint "
            "kernels for its integrator are not compiled."
        )
    if sim._settings["check_bounds"] or sim._settings["check_planet_impact"]:
        raise RuntimeError(
            "DiffSimStepper requires check_bounds=False and "
            "check_planet_impact=False: a terminated entity is frozen by "
            "the integrator and its gradients silently vanish."
        )
    self.sim = sim
    self.num_entities = sim.num_entities
    self.device = sim.device

    # Scratch episode counters and termination status: the integrator
    # kernels write both (the non-finite check is always on), and taped
    # steps must never mutate the simulator's own.
    self._ctx = replace(
        sim.ctx,
        episode_steps=wp.zeros(self.num_entities, dtype=wp.int32, device=self.device),
        termination_status=wp.empty_like(sim.ctx.termination_status),
    )
    # Parameter snapshot shared by the taped steps inside frozen_params()
    self._frozen_ctx = None
    # Reused (non-taped) buffer for read_state/write_state.
    self._x_io = wp.zeros(
        (self.num_entities, X_DIM), dtype=wp.float64, device=self.device
    )
    # Reused untaped buffers for the no-grad fast path (lazy: only
    # evaluation/inference loops pay for them).
    self._eval_buf = None

step

step(x: Tensor, u: Tensor) -> Tensor

Advance one step: (x, u) -> x_next, differentiable w.r.t. both.

When no gradient can flow — under torch.no_grad(), or when neither input requires grad — the step skips taping and per-call allocation entirely (same kernels, reused buffers), so evaluation and inference loops run at plain simulation cost.

Parameters:

Name Type Description Default
x Tensor

State [num_entities, X_DIM] float64 (see :data:X_DIM layout).

required
u Tensor

Actuator commands [num_entities, U_DIM] float64, physical units (see :data:U_DIM layout).

required
Source code in cosmic_warp/rl/diff_bridge.py
def step(self, x: torch.Tensor, u: torch.Tensor) -> torch.Tensor:
    """Advance one step: ``(x, u) -> x_next``, differentiable w.r.t. both.

    When no gradient can flow — under ``torch.no_grad()``, or when neither
    input requires grad — the step skips taping and per-call allocation
    entirely (same kernels, reused buffers), so evaluation and inference
    loops run at plain simulation cost.

    Args:
        x: State ``[num_entities, X_DIM]`` float64 (see :data:`X_DIM` layout).
        u: Actuator commands ``[num_entities, U_DIM]`` float64, physical
            units (see :data:`U_DIM` layout).
    """
    self._check("x", x, X_DIM)
    self._check("u", u, U_DIM)
    if torch.is_grad_enabled() and (x.requires_grad or u.requires_grad):
        return _SimStep.apply(x, u, self)
    return self._step_no_grad(x, u)

frozen_params

frozen_params()

Share one parameter snapshot across the taped steps in the block.

Every taped :meth:step otherwise copies the vehicle, thruster and wheel configurations for its backward. Inside the block they share one copy, taken on entry: cheaper for a multi-step rollout, provided nothing changes the configuration inside the block. Nested blocks share the outer snapshot.

Source code in cosmic_warp/rl/diff_bridge.py
@contextmanager
def frozen_params(self):
    """Share one parameter snapshot across the taped steps in the block.

    Every taped :meth:`step` otherwise copies the vehicle, thruster and
    wheel configurations for its backward. Inside the block they share
    one copy, taken on entry: cheaper for a multi-step rollout, provided
    nothing changes the configuration inside the block. Nested blocks
    share the outer snapshot.
    """
    if self._frozen_ctx is not None:
        yield
        return
    self._frozen_ctx = self._snapshot_ctx()
    try:
        yield
    finally:
        self._frozen_ctx = None

read_state

read_state() -> Tensor

The simulator's current state as a detached [E, X_DIM] tensor.

Source code in cosmic_warp/rl/diff_bridge.py
def read_state(self) -> torch.Tensor:
    """The simulator's current state as a detached ``[E, X_DIM]`` tensor."""
    wp.launch(_pack_x_kernel, dim=self.num_entities,
              inputs=[self.sim.ctx.states, self.sim.ctx.actuator_states, self._x_io],
              device=self.device)
    return wp.to_torch(self._x_io).clone()

write_state

write_state(x: Tensor) -> None

Write a (detached) [E, X_DIM] tensor into the simulator's state.

Source code in cosmic_warp/rl/diff_bridge.py
def write_state(self, x: torch.Tensor) -> None:
    """Write a (detached) ``[E, X_DIM]`` tensor into the simulator's state."""
    self._check("x", x, X_DIM)
    wp.to_torch(self._x_io).copy_(x.detach())
    wp.launch(_unpack_x_kernel, dim=self.num_entities,
              inputs=[self._x_io, self.sim.ctx.states, self.sim.ctx.actuator_states],
              device=self.device)