Environment

Vectorized Environment

class rsl_rl.env.vec_env.VecEnv[source]

Abstract class for a vectorized environment.

The vectorized environment is a collection of environments that are synchronized. This means that the same type of action is applied to all environments and the same type of observation is returned from all environments.

num_envs: int

Number of environments.

num_actions: int

Number of actions.

max_episode_length: int | torch.Tensor

Maximum episode length.

The maximum episode length can be a scalar or a tensor. If it is a scalar, it is the same for all environments. If it is a tensor, it is the maximum episode length for each environment. This is useful for dynamic episode lengths.

episode_length_buf: torch.Tensor

Buffer for current episode lengths.

device: torch.device | str

Device to use.

cfg: dict | object

Configuration object.

abstractmethod get_observations()[source]

Return the current observations.

Returns:

The observations from the environment.

Return type:

tensordict.TensorDict

Note

The returned TensorDict and its tensors must remain unchanged until the transition associated with the next environment step has been copied into rollout storage.

abstractmethod step(actions)[source]

Apply input action to the environment.

Parameters:

actions (torch.Tensor) – Input actions to apply. Shape: (num_envs, num_actions)

Returns:

  • observations: Observations from the environment.

  • rewards: Rewards from the environment. Shape: (num_envs,)

  • dones: Done flags from the environment. Shape: (num_envs,)

  • extras: Extra information from the environment.

Return type:

A tuple containing

Observations:

The observations TensorDict usually contains multiple observation groups. The obs_groups dictionary of the runner configuration specifies which observation groups are used for which purpose, i.e., it maps from required observation sets (e.g. actor) to lists of observation groups. The observation sets (keys of the obs_groups dictionary) currently used by rsl_rl are:

  • “actor”: Specified observation groups are used as input to the actor model.

  • “critic”: Specified observation groups are used as input to the critic model.

  • “student”: Specified observation groups are used as input to the student model.

  • “teacher”: Specified observation groups are used as input to the teacher model.

  • “rnd_state”: Specified observation groups are used as input to the RND extension.

  • “state”, “goal”, “context”, “labels”, “prev_action”, “prev_prev_action”: Used by SHAC, see the configuration guide.

Incomplete or incorrect configurations are handled in the resolve_obs_groups() function in rsl_rl/utils/utils.py, which provides detailed information on the expected configuration.

Note

Do not modify the TensorDict or tensors returned by the previous step() call in place. The algorithm retains that observation reference until process_env_step() copies it into rollout storage after this method returns.

Extras:

The extras dictionary provides additional transition data and optional metrics for logging. rsl_rl uses the following keys:

  • “time_outs” (torch.Tensor): Boolean flags of shape (num_envs,). True when an episode ends because it reaches a time limit without reaching a terminal state. This distinguishes timeouts from terminal states.

  • “final_obs” (TensorDict): Observations after the final action of each episode, before resets, post-step events, or command resampling. SAC requires this key whenever an environment is done, so it can store the correct next observation for that transition. Include the groups used by the actor and critics, with the same shapes and device as the returned observations. Keep the tensors unchanged until process_env_step() has recorded the transition.

  • “final_obs_every_step” (bool): Set to True when final_obs contains pre-event successors from every environment on every step. The learned dynamics extension then cuts model-fitting windows after interval edits such as pushes. By default, only the final observations of finished environments are read, and the learned dynamics extension takes the returned observations as the successors of the others.

  • “log” (dict[str, float | torch.Tensor]): Additional information for logging and debugging purposes.

    The key should be a string and start with “/” for namespacing. The value can be a scalar or a tensor. If it is a tensor, the mean of the tensor is used for logging.

Differentiable Task

Task-owned differentiable state coordinates and heads for SHAC.

class rsl_rl.env.differentiable_task.RolloutState[source]

Physical state and feature histories at one step of a differentiable rollout.

state: tuple[torch.Tensor, ...]

Alias for field number 0

goal: torch.Tensor

Alias for field number 1

context: torch.Tensor

Alias for field number 2

action_history: torch.Tensor

Alias for field number 3

obs_history: torch.Tensor

Alias for field number 4

observations: tensordict.TensorDict

Alias for field number 5

property actor_obs: tensordict.TensorDict

Return policy inputs for this rollout step, including its noisy observation history.

static __new__(_cls, state, goal, context, action_history, obs_history, observations)

Create new instance of RolloutState(state, goal, context, action_history, obs_history, observations)

Parameters:
  • state (State)

  • goal (torch.Tensor)

  • context (torch.Tensor)

  • action_history (torch.Tensor)

  • obs_history (torch.Tensor)

  • observations (TensorDict)

rsl_rl.env.differentiable_task.prepare_actor_obs(observations, history)[source]

Replace the policy frame with the current noisy frame and expose any preceding frames oldest first.

Parameters:
  • observations (tensordict.TensorDict)

  • history (torch.Tensor)

Return type:

tensordict.TensorDict

rsl_rl.env.differentiable_task.concatenate_observation_set(obs, obs_groups, name)[source]

Concatenate one explicitly mapped observation set, using an empty tensor for absent optional sets.

Parameters:
  • obs (tensordict.TensorDict)

  • obs_groups (dict[str, list[str]])

  • name (str)

Return type:

torch.Tensor

class rsl_rl.env.differentiable_task.StateRepresentation[source]

Convert between task observations and differentiable physical coordinates.

increment_dim: int

Number of coordinates predicted by the world model.

error_floor: torch.Tensor

Positive minimum loss scale for each increment coordinate.

unflatten(flat)[source]

Decode the last dimension of a physical observation, preserving leading batch dimensions.

Parameters:

flat (torch.Tensor)

Return type:

tuple[torch.Tensor, …]

features(state)[source]

Encode physical dynamics inputs.

Parameters:

state (tuple[torch.Tensor, ...])

Return type:

torch.Tensor

increments(state, next_state)[source]

Encode the per-step successor-minus-current increment in integration coordinates.

Parameters:
  • state (tuple[torch.Tensor, ...])

  • next_state (tuple[torch.Tensor, ...])

Return type:

torch.Tensor

integrate(state, increment)[source]

Apply a per-step physical increment; the algorithm performs no time-step scaling.

Parameters:
  • state (tuple[torch.Tensor, ...])

  • increment (torch.Tensor)

Return type:

tuple[torch.Tensor, …]

error(prediction, target)[source]

Return prediction errors in increment coordinates.

Parameters:
  • prediction (tuple[torch.Tensor, ...])

  • target (tuple[torch.Tensor, ...])

Return type:

torch.Tensor

__init__(*args, **kwargs)
class rsl_rl.env.differentiable_task.EuclideanStateRepresentation[source]

Flat Euclidean coordinates for systems without manifold state components.

__init__(dimension, error_floor=0.001)[source]

Set state width and the minimum per-coordinate model-loss scale.

Parameters:
  • dimension (int)

  • error_floor (float)

Return type:

None

unflatten(flat)[source]

Keep the flat vector as one structured component.

Parameters:

flat (torch.Tensor)

Return type:

tuple[torch.Tensor, …]

features(state)[source]

Return the physical vector.

Parameters:

state (tuple[torch.Tensor, ...])

Return type:

torch.Tensor

increments(state, next_state)[source]

Subtract successive physical vectors.

Parameters:
  • state (tuple[torch.Tensor, ...])

  • next_state (tuple[torch.Tensor, ...])

Return type:

torch.Tensor

integrate(state, increment)[source]

Add the predicted physical increment.

Parameters:
  • state (tuple[torch.Tensor, ...])

  • increment (torch.Tensor)

Return type:

tuple[torch.Tensor, …]

error(prediction, target)[source]

Subtract the target physical vector.

Parameters:
  • prediction (tuple[torch.Tensor, ...])

  • target (tuple[torch.Tensor, ...])

Return type:

torch.Tensor

class rsl_rl.env.differentiable_task.DifferentiableTask[source]

Provide task features, rewards and state updates for SHAC.

prev_actions has shape [..., action_history_length, num_actions], oldest first. Actor observations and goals must use deployable inputs. Privileged context is available separately to dynamics and critic heads. Heads and the representation need finite gradients as well as finite values, e.g. torch.linalg.vector_norm instead of sqrt(sum(x**2)) at zero: an optimizer step with a nonfinite gradient is skipped and shows as a nonfinite gradient norm in the logs.

representation: StateRepresentation
action_history_length: int = 2
num_labels: int = 0
start_rollout(batch_size)[source]

Provide initial states and actor histories when using task dynamics directly.

Parameters:

batch_size (int)

Return type:

RolloutState

step(rollout, actions, survival)[source]

Advance task dynamics and return the next rollout state, reward and termination probability.

Preserve action derivatives and leave unreachable rows at their last reachable state.

Parameters:
  • rollout (RolloutState)

  • actions (torch.Tensor)

  • survival (torch.Tensor)

Return type:

tuple[RolloutState, torch.Tensor, torch.Tensor]

actor_obs(state, goal, context, prev_actions)[source]

Return named deployable observations for this state, preserving its leading batch dimensions and gradients.

Match the groups the environment exposes to the actor. Learned dynamics applies noise to the policy frame and constructs its history. A command can be part of the frame or a separate group.

Parameters:
  • state (tuple[torch.Tensor, ...])

  • goal (torch.Tensor)

  • context (torch.Tensor)

  • prev_actions (torch.Tensor)

Return type:

tensordict.TensorDict

advance(next_state, goal, context)[source]

Advance exogenous goals and privileged context after an imagined physical transition.

Imagined rollouts ignore the environment’s time limit: they run horizon steps from any stored step, so goals must stay valid that far past the last one the environment shows, e.g. by clamping a reference-frame index.

Parameters:
  • next_state (tuple[torch.Tensor, ...])

  • goal (torch.Tensor)

  • context (torch.Tensor)

Return type:

tuple[torch.Tensor, torch.Tensor]

dynamics_actions(actions)[source]

Map policy outputs to physical commands before world-model normalization, e.g. scaled joint targets.

Parameters:

actions (torch.Tensor)

Return type:

torch.Tensor

dynamics_context(state, context, prev_actions)[source]

Return normalized privileged dynamics inputs, e.g. log-scaled randomized masses and the recent actions.

Parameters:
  • state (tuple[torch.Tensor, ...])

  • context (torch.Tensor)

  • prev_actions (torch.Tensor)

Return type:

torch.Tensor

critic_obs(state, goal, context, prev_actions, history)[source]

Build privileged value features for the synthetic critic observation set.

history is the observation history the actor acts on at state, including add_noise(), with shape [..., history_length, obs_dim], oldest first. During imagination it carries gradients: detach it if the critic must not shape the actor through it.

Parameters:
  • state (tuple[torch.Tensor, ...])

  • goal (torch.Tensor)

  • context (torch.Tensor)

  • prev_actions (torch.Tensor)

  • history (torch.Tensor)

Return type:

torch.Tensor

reward(state, actions, next_state, goal, prev_actions, labels=None)[source]

Return transition rewards from the pre_dynamics() start, pre-transition goal and successor labels.

Parameters:
  • state (State)

  • actions (torch.Tensor)

  • next_state (State)

  • goal (torch.Tensor)

  • prev_actions (torch.Tensor)

  • labels (torch.Tensor | None)

Return type:

torch.Tensor

termination_prob(next_state, goal, labels=None)[source]

Return successor termination probabilities in [0,1].

For example from predicted contact labels at illegal bodies, or from a soft threshold on a tracking error.

Parameters:
  • next_state (State)

  • goal (torch.Tensor)

  • labels (torch.Tensor | None)

Return type:

torch.Tensor

pre_dynamics(state, context)[source]

Apply an exogenous edit to a transition start after the actor has acted, e.g. a scheduled velocity impulse.

The edit must be a deterministic function of state and context without random draws, because it runs wherever the world-model inputs of a transition are built: for the world-model statistics during collection, in each step of the world-model fit and in each imagined step. Replay keeps the state the actor observed, and the actor and critic_obs() see that state. dynamics_context(), the world model, post_dynamics() and reward() receive the edited start. Imagined returns are differentiated through the edit, so it must preserve state derivatives.

Parameters:
  • state (tuple[torch.Tensor, ...])

  • context (torch.Tensor)

Return type:

tuple[torch.Tensor, …]

post_dynamics(state, next_state, labels, actions, context)[source]

Advance task-owned analytic state after integration and successor-label prediction.

state is the transition start returned by pre_dynamics(). actions are the policy actions applied in the transition, before dynamics_actions(), and context is its privileged context, for analytic state that they drive, such as filters, delay buffers or estimators.

Parameters:
  • state (State)

  • next_state (State)

  • labels (torch.Tensor | None)

  • actions (torch.Tensor)

  • context (torch.Tensor)

Return type:

State

label_activation(logits)[source]

Map successor-label logits to the labels read by rewards, terminations and post-dynamics.

The default yields event probabilities. Override it together with label_loss(), e.g. to regress labels.

Parameters:

logits (torch.Tensor)

Return type:

torch.Tensor

label_loss(logits, labels)[source]

Return one successor-label loss per replay position; the default treats labels as binary events.

Reduce the label dimension only: the learner masks invalid replay positions and rejects any other shape.

Parameters:
  • logits (torch.Tensor)

  • labels (torch.Tensor)

Return type:

torch.Tensor

reference_action(state, goal)[source]

Return the action that the policy output corrects when the actor uses use_reference_action.

The environment adds this reference to the correction returned by the actor. SHAC uses the same reference to record applied actions in replay and to step the imagined dynamics.

Parameters:
  • state (tuple[torch.Tensor, ...])

  • goal (torch.Tensor)

Return type:

torch.Tensor

mirror_state(state)[source]

Return the left-right mirror image of flat physical states for world-model mirror augmentation.

The mirror hooks map each replayed quantity with arbitrary leading dimensions. Together they must yield physically valid transitions for the robot, e.g. by swapping left and right joints and negating lateral motion.

Parameters:

state (torch.Tensor)

Return type:

torch.Tensor

mirror_actions(actions)[source]

Return the mirror image of policy actions, also applied to each previous action.

Parameters:

actions (torch.Tensor)

Return type:

torch.Tensor

mirror_context(context)[source]

Return the mirror image of flat privileged context, e.g. by swapping left and right body masses.

Parameters:

context (torch.Tensor)

Return type:

torch.Tensor

mirror_labels(labels)[source]

Return the mirror image of successor labels; required only for tasks with labels.

Parameters:

labels (torch.Tensor)

Return type:

torch.Tensor

world_model_loss(prediction, target, scale)[source]

Return one dynamics loss per replay position, including any integrated state coordinates.

Reduce the state dimensions only: the learner masks invalid replay positions and rejects any other shape.

Parameters:
  • prediction (tuple[torch.Tensor, ...])

  • target (tuple[torch.Tensor, ...])

  • scale (torch.Tensor)

Return type:

torch.Tensor

add_noise(observation)[source]

Add task observation noise while retaining imagined state derivatives.

This is the only source of actor observation noise: it is applied in training-mode collection and imagination, not in eval mode; the observation sets from the environment are expected to be noise-free.

Parameters:

observation (torch.Tensor)

Return type:

torch.Tensor

update_curriculum(goal, rewards, dones, extras)[source]

Update task-owned curricula from a completed physical step and its pre-step goal.

For example the sampling weights of reference motions.

Parameters:
  • goal (torch.Tensor)

  • rewards (torch.Tensor)

  • dones (torch.Tensor)

  • extras (dict)

Return type:

None