Task layer#

TaskLayer defines a Markov Decision Process (MDP): processing actions into device commands, extracting task features from device measurements, and computing rewards, terminations, metrics, and observations.

Importantly, TaskLayer has no direct access to privileged simulation information and operates strictly on information provided via the layer interface. This information boundary enables unmodified TaskLayer code to directly interface with different simulation backends or physical robot hardware.

Task Layer Architecture

Figure 1: Information flow in TaskLayer. Actions map to device commands; device measurements expand into features, which construct rewards, terminations, and observations.#

Task Layer Architecture

Figure 1: Information flow in TaskLayer. Actions map to device commands; device measurements expand into features, which construct rewards, terminations, and observations.#

The REAF documentation provides additional details about the task layer design.

Commands#

Before policy actions reach devices, CommandsProcessor components (such as DeltaActions and TransformActions) can intercept, transform, scale, or buffer them.

Features#

FeatureProducer components compute derived physical quantities from raw device measurements. These are collected into a consolidated features bus, ensuring geometric calculations (such as end-effector frames, relative distances, or filtered velocities) are performed exactly once per step.

Lifecycle#

Feature producers and observation adapters follow one contract: hooks advance state, reads are pure, and resets only touch the reset environments.

  • on_step(features) runs once per Environment.step(), after the physics step and right before the read. Advance per-step state here (e.g. previous velocities, history buffers, per-step noise).

  • on_begin_stepping(features, env_mask) runs after a reset, for the env_mask environments only. Seed post-reset state here (e.g. fill history buffers with the reset value).

  • produce_features(features) and observations_from_features(features) are pure reads. After a partial reset, the environment calls them again for all environments, and the recomputed features of every environment are the ones observers and loggers record. Since the reads are pure, these are the same values for the environments that were not reset.

Components that wrap another producer or adapter must forward both hooks to it.

Commands processors need no hooks: the task layer runs them exactly once per Environment.step(), and never again after a reset, so they can advance their state in process_commands.

Features observers and loggers record once per timestep returned by step(). After an auto-reset, reset environments are recorded with their reset (FIRST) features.

Rewards#

Rewards are configured declaratively using Reward.

By default, FunctionalRewardProvider computes the scalar reward as the weighted sum of terms scaled by the control timestep:

r_t = control_timestep * sum(weight_i * term_func_i(features))

Metrics#

Diagnostic metrics are configured declaratively using Metric with an explicit per-episode reduction mode (reduce="mean" | "last" | "max" | "sum"):

metrics = {
    "tracking_error": flat_scene.Metric(pose_error, reduce="mean"),
    "peak_height": flat_scene.Metric(object_height, reduce="max"),
    "contact_events": flat_scene.Metric(new_contact_event, reduce="sum"),
    "success": flat_scene.Metric(goal_reached, threshold=0.02, reduce="last"),
}
  • Per-episode metrics: env.task_layer.get_episode_metrics(env_mask) returns dict[str, torch.Tensor] of 0-D scalar means over the masked worlds without host-device synchronization.

Curriculum#

reaf-sim keeps curricula declarative and stateless. ClockDevice exposes the monotonic control step as the simulation-only global_step feature (any FeatureProducer consuming it should call .mark_privileged() if you want to deploy on a real robot, since global_step does not generally translate to the real world). reaf.simulation.torch.curriculum provides serializable schedule dataclasses (such as Stages) evaluated on device via curriculum.evaluate(...).

On Term and Reward, call .curriculum(**schedules) to attach schedules to any keyword parameter (and weight on Reward; the base value acts as the initial default before the first threshold). Schedules are resolved for rewards, terminations, and domain randomization resetters:

from reaf.simulation.torch import curriculum
from reaf.simulation.torch import flat_scene

# Reward
flat_scene.Reward(tracking_reward, weight=1.0, std=0.5).curriculum(
    weight=curriculum.Stages([(24_000, 2.0)]),
    std=curriculum.Stages([(24_000, 0.25)]),
)

# Termination
flat_scene.Term(bad_object_pos, threshold=0.5).curriculum(
    threshold=curriculum.Stages([(24_000, 0.25)]),
)

# Domain randomization resetter param (requires trigger="reset")
flat_scene.Term(randomize_mass, scale=0.05, trigger="reset").curriculum(
    scale=curriculum.Stages([(24_000, 0.2)]),
)

Resetters (DomainRandomizationResetter with trigger="reset" and TerminationResetter) only support schedules keyed on global_step, since they run outside the task layer.

To resume training from a checkpoint, restore the step via env.device_layer.clock.set_global_step(step).

  • When to use curriculum: stateless schedules driven by global_step (e.g. staged reward weight ramps) or by any per-world feature emitted by another producer (pass key="my_producer/metric" to Stages).

  • When not to use curriculum: stateful per-world performance-based curricula that accumulate history across episodes (e.g. widening goal angles after consecutive successes, or promoting/demoting terrain levels). Implement those in a custom FeatureProducer or EnvironmentReset; they can still emit a feature that curriculum.Stages(..., key=...) consumes.

Terminations and discounts#

Episode endings distinguish between task failure/completion (termination) and time limits (truncation).

  • Task terminations: Evaluated by FunctionalTerminationChecker based on criteria from features.

  • Timeouts: Handled automatically by TimeoutTerminationChecker based on episode_length_secs in the environment configuration. Truncation is checked against elapsed time rather than step count so the same task layer works on hardware (where a wall-clock ClockDevice measures elapsed seconds); call checker.max_steps(env.device_layer.control_timestep) to get the exact simulated truncation step count.

  • Discounts: Computed by DefaultDiscountProvider, emitting gamma = 0.0 on termination (task failure/success) and gamma = 1.0 on truncation (timeout) or continuation.

Observation adapters#

FunctionalObservationAdapter organizes features into named ObsGroup dictionaries (e.g., "policy", "critic", "proprioception"). Each Obs term supports declarative data transformations evaluated in order: func -> bias -> noise -> scale -> offset -> clip -> history. When history_length > 0, past and current frames are stacked oldest-to-newest ([t - H, ..., t - 1, t]). Per-step noise is drawn and the history advances in on_step; after a reset, every history slot holds the reset observation.

Task layer assembly#

Task components assemble inside Environment:

from reaf.simulation.torch import flat_scene

config = flat_scene.Environment(
    base_scene=spec,
    device_layer=device_layer_config,
    task_layer=flat_scene.TaskLayer(
        command_processors=command_processors,
        feature_producers=feature_producers,
        command_feature_producers=command_feature_producers,
        rewards=rewards_dict,
        metrics=metrics_dict,
        terminations=terminations_dict,
    ),
    observation_adapter=observation_adapter,
    episode_length_secs=10.0,
)

env = flat_scene.build_env(config)

For full class signatures and details, see reaf.simulation.torch.TaskLayer in the API reference.