embodichain.learning.rl#
On-policy reinforcement learning pipeline.
Algorithms (PPO/GRPO), rollout buffers, collectors, policy/model builders, and the training entry point; rollout data flows as TensorDict objects.
Overview#
The embodichain.learning.rl package contains algorithm registries, rollout
collection logic, policy/model builders, and training entry points.
Submodules
Algorithm registry and construction helpers (
BaseAlgorithm,PPO,GRPO,compute_gae,build_algo).On-policy rollout buffer (
RolloutBuffer) owning preallocatedTensorDictstorage, plus minibatch iteration helpers.Collectors that step vectorized environments and assemble rollout data into a preallocated
TensorDictlayout.Policy-network registration and model construction (
ActorCritic,ActorOnly,MLP,Policy).RL helper utilities: algorithm config, optimizers, and observation helpers.
Top-level APIs
Coordinate APG updates and truncated-backpropagation boundaries.
Configuration for graph-preserving segmented training.
Batched env that preserves the autograd path through
step.Structural interface shared by lightweight vector environments.
build_learning_env(name, *, num_envs, ...)Build a registered lightweight vector environment.
evaluate_episodes(*, policy, env, ...[, ...])Evaluate exactly
num_episodescompleted asynchronous episodes.
get_trainer_class(algorithm)Return the trainer compatible with
algorithm.
register_learning_env(name[, factory, override])Register a lightweight vector-environment factory.
Algorithms#
Algorithm registry and construction helpers (BaseAlgorithm, PPO, GRPO, compute_gae, build_algo).
Classes:
Optimize policy parameters through differentiable rollout rewards. |
|
Analytic policy-gradient config. |
|
Base class for RL algorithms. |
|
Group Relative Policy Optimization on top of TensorDict rollouts. |
|
Configuration for GRPO. |
|
PPO algorithm consuming TensorDict rollouts. |
|
Configuration for the PPO algorithm. |
|
Rollout semantics required by an algorithm. |
Functions:
|
|
|
Compute GAE over a rollout stored as [num_envs, time + 1]. |
|
Compute one discounted return per environment within a rollout segment. |
- class embodichain.learning.rl.algo.APG[source]#
Bases:
BaseAlgorithm[DifferentiableRollout]Optimize policy parameters through differentiable rollout rewards.
Methods:
__init__(cfg, policy)accumulate_segment(rollout)Accumulate gradients from one TBPTT segment without stepping the optimizer.
Clip gradients and apply one optimizer step.
update(rollout)Apply one pathwise-gradient update from a rollout segment.
Attributes:
- accumulate_segment(rollout)[source]#
Accumulate gradients from one TBPTT segment without stepping the optimizer.
- Return type:
None
-
device:
device#
-
lr_scheduler:
LRScheduler|None#
-
optimizer:
Optimizer#
- rollout_kind = 'differentiable'#
- class embodichain.learning.rl.algo.APGCfg[source]#
Bases:
AlgorithmCfgAnalytic policy-gradient config.
gammaapplies within each TBPTT segment and restarts after done.Methods:
__init__([device, optimizer, lr_scheduler, ...])copy(**kwargs)Return a new object replacing specified fields with new values.
replace(**kwargs)Return a new object replacing specified fields with new values.
to_dict()Convert an object into dictionary recursively.
validate([prefix])Check the validity of configclass object.
Attributes:
- __init__(device=<factory>, optimizer=<factory>, lr_scheduler=<factory>, batch_size=<factory>, gamma=<factory>, gae_lambda=<factory>, max_grad_norm=<factory>, ent_coef=<factory>, skip_nonfinite_updates=<factory>)#
- batch_size: int#
- copy(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
- device: str#
- ent_coef: float#
- gae_lambda: float#
- gamma: float#
- lr_scheduler: LRSchedulerCfg#
- max_grad_norm: float#
- optimizer: OptimizerCfg#
- replace(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
- skip_nonfinite_updates: bool#
- to_dict()#
Convert an object into dictionary recursively.
Note
Ignores all names starting with “__” (i.e. built-in methods).
- Parameters:
obj (
object) – An instance of a class to convert.- Raises:
ValueError – When input argument is not an object.
- Return type:
dict[str,Any]- Returns:
Converted dictionary mapping.
- validate(prefix='')#
Check the validity of configclass object.
This function checks if the object is a valid configclass object. A valid configclass object contains no MISSING entries.
- Parameters:
obj (
object) – The object to check.prefix (
str) – The prefix to add to the missing fields. Defaults to ‘’.
- Return type:
list[str]- Returns:
A list of missing fields.
- Raises:
TypeError – When the object is not a valid configuration object.
- class embodichain.learning.rl.algo.BaseAlgorithm[source]#
Bases:
ABC,Generic[RolloutT]Base class for RL algorithms.
Methods:
bind_schedule(*, total_updates)Bind horizon-dependent LR schedules from the training budget.
update(rollout)Update policy using collected data and return training losses.
Attributes:
- bind_schedule(*, total_updates)[source]#
Bind horizon-dependent LR schedules from the training budget.
- Return type:
None
-
device:
device#
-
lr_scheduler:
LRScheduler|None#
-
optimizer:
Optimizer#
- rollout_kind = 'standard'#
- class embodichain.learning.rl.algo.GRPO[source]#
Bases:
BaseAlgorithm[TensorDict]Group Relative Policy Optimization on top of TensorDict rollouts.
Methods:
- class embodichain.learning.rl.algo.GRPOCfg[source]#
Bases:
AlgorithmCfgConfiguration for GRPO.
Methods:
__init__([device, optimizer, lr_scheduler, ...])copy(**kwargs)Return a new object replacing specified fields with new values.
replace(**kwargs)Return a new object replacing specified fields with new values.
to_dict()Convert an object into dictionary recursively.
validate([prefix])Check the validity of configclass object.
Attributes:
- __init__(device=<factory>, optimizer=<factory>, lr_scheduler=<factory>, batch_size=<factory>, gamma=<factory>, gae_lambda=<factory>, max_grad_norm=<factory>, n_epochs=<factory>, clip_coef=<factory>, ent_coef=<factory>, kl_coef=<factory>, group_size=<factory>, eps=<factory>, reset_every_rollout=<factory>, truncate_at_first_done=<factory>)#
- batch_size: int#
- clip_coef: float#
- copy(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
- device: str#
- ent_coef: float#
- eps: float#
- gae_lambda: float#
- gamma: float#
- group_size: int#
- kl_coef: float#
- lr_scheduler: LRSchedulerCfg#
- max_grad_norm: float#
- n_epochs: int#
- optimizer: OptimizerCfg#
- replace(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
- reset_every_rollout: bool#
- to_dict()#
Convert an object into dictionary recursively.
Note
Ignores all names starting with “__” (i.e. built-in methods).
- Parameters:
obj (
object) – An instance of a class to convert.- Raises:
ValueError – When input argument is not an object.
- Return type:
dict[str,Any]- Returns:
Converted dictionary mapping.
- truncate_at_first_done: bool#
- validate(prefix='')#
Check the validity of configclass object.
This function checks if the object is a valid configclass object. A valid configclass object contains no MISSING entries.
- Parameters:
obj (
object) – The object to check.prefix (
str) – The prefix to add to the missing fields. Defaults to ‘’.
- Return type:
list[str]- Returns:
A list of missing fields.
- Raises:
TypeError – When the object is not a valid configuration object.
- class embodichain.learning.rl.algo.PPO[source]#
Bases:
BaseAlgorithm[TensorDict]PPO algorithm consuming TensorDict rollouts.
Methods:
- class embodichain.learning.rl.algo.PPOCfg[source]#
Bases:
AlgorithmCfgConfiguration for the PPO algorithm.
Methods:
__init__([device, optimizer, lr_scheduler, ...])copy(**kwargs)Return a new object replacing specified fields with new values.
replace(**kwargs)Return a new object replacing specified fields with new values.
to_dict()Convert an object into dictionary recursively.
validate([prefix])Check the validity of configclass object.
Attributes:
- __init__(device=<factory>, optimizer=<factory>, lr_scheduler=<factory>, batch_size=<factory>, gamma=<factory>, gae_lambda=<factory>, max_grad_norm=<factory>, n_epochs=<factory>, clip_coef=<factory>, ent_coef=<factory>, vf_coef=<factory>)#
- batch_size: int#
- clip_coef: float#
- copy(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
- device: str#
- ent_coef: float#
- gae_lambda: float#
- gamma: float#
- lr_scheduler: LRSchedulerCfg#
- max_grad_norm: float#
- n_epochs: int#
- optimizer: OptimizerCfg#
- replace(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
- to_dict()#
Convert an object into dictionary recursively.
Note
Ignores all names starting with “__” (i.e. built-in methods).
- Parameters:
obj (
object) – An instance of a class to convert.- Raises:
ValueError – When input argument is not an object.
- Return type:
dict[str,Any]- Returns:
Converted dictionary mapping.
- validate(prefix='')#
Check the validity of configclass object.
This function checks if the object is a valid configclass object. A valid configclass object contains no MISSING entries.
- Parameters:
obj (
object) – The object to check.prefix (
str) – The prefix to add to the missing fields. Defaults to ‘’.
- Return type:
list[str]- Returns:
A list of missing fields.
- Raises:
TypeError – When the object is not a valid configuration object.
- vf_coef: float#
- class embodichain.learning.rl.algo.RolloutKind[source]#
Bases:
str,EnumRollout semantics required by an algorithm.
Attributes:
Methods:
__new__(value)- DIFFERENTIABLE = 'differentiable'#
- STANDARD = 'standard'#
- __new__(value)#
- embodichain.learning.rl.algo.build_algo(name, cfg_kwargs, policy, device, *, distributed=False)[source]#
- embodichain.learning.rl.algo.compute_gae(rollout, gamma, gae_lambda)[source]#
Compute GAE over a rollout stored as [num_envs, time + 1].
- Parameters:
rollout (
TensorDict) – Rollout TensorDict where value[:, -1] stores the bootstrap value for the final observation and transition-only fields reserve their last slot as padding.gamma (
float) – Discount factor.gae_lambda (
float) – GAE lambda coefficient.
- Return type:
tuple[Tensor,Tensor]- Returns:
Tuple of (advantages, returns), both shaped [num_envs, time].
Environments#
Contracts and registration helpers for lightweight learning environments.
Classes:
Batched env that preserves the autograd path through |
|
Structural interface shared by lightweight vector environments. |
Functions:
|
Build a registered lightweight vector environment. |
Return registered lightweight environment names. |
|
|
Register a lightweight vector-environment factory. |
- class embodichain.learning.rl.env.DifferentiableVecEnv[source]#
Bases:
LearningVecEnv,ProtocolBatched env that preserves the autograd path through
step.detach_stateis the truncated-backpropagation boundary: detach differentiable internal state and return the current observation without resetting or resampling the episode. Finished rows must auto-reset insidestep, returning the terminal reward/done with the next initial observation.Methods:
Detach internal state and return its current detached observation.
- class embodichain.learning.rl.env.LearningVecEnv[source]#
Bases:
ProtocolStructural interface shared by lightweight vector environments.
Methods:
__init__(*args, **kwargs)close()Release owned resources.
reset(*[, seed, options])Reset all environments and return the initial observation.
step(action)Advance all environments by one step.
Attributes:
- __init__(*args, **kwargs)#
-
device:
device#
-
num_envs:
int#
- reset(*, seed=None, options=None)[source]#
Reset all environments and return the initial observation.
- Return type:
tuple[Tensor|TensorDict,dict[str,Any]]
-
single_action_space:
Space#
-
single_observation_space:
Space#
- embodichain.learning.rl.env.build_learning_env(name, *, num_envs, device, **cfg)[source]#
Build a registered lightweight vector environment.
- Return type:
- embodichain.learning.rl.env.get_registered_learning_env_names()[source]#
Return registered lightweight environment names.
- Return type:
list[str]
- embodichain.learning.rl.env.register_learning_env(name, factory=None, *, override=False)[source]#
Register a lightweight vector-environment factory.
The function supports both
@register_learning_env("Name")and directregister_learning_env("Name", Factory)use.- Return type:
Callable[[Callable[...,LearningVecEnv]],Callable[...,LearningVecEnv]] |Callable[...,LearningVecEnv]
Evaluation#
Shared deterministic episode evaluation for all RL trainers.
Functions:
|
Evaluate exactly |
Routing#
Trainer routing based on an algorithm’s rollout semantics.
Functions:
|
Return the trainer compatible with |
- embodichain.learning.rl.routing.get_trainer_class(algorithm)[source]#
Return the trainer compatible with
algorithm.- Return type:
type[Trainer] |type[DifferentiableTrainer]
Differentiable Trainer#
Training orchestration for truncated differentiable rollouts.
Classes:
Coordinate APG updates and truncated-backpropagation boundaries. |
|
Configuration for graph-preserving segmented training. |
- class embodichain.learning.rl.differentiable_trainer.DifferentiableTrainer[source]#
Bases:
objectCoordinate APG updates and truncated-backpropagation boundaries.
Methods:
__init__(cfg, env, policy, algorithm[, ...])Return the current in-memory training summary.
load_checkpoint(path)Restore policy, optimizer, and trainer counters.
save_checkpoint([path])Save policy, optimizer, and trainer counters.
train(total_timesteps)Train until at least
total_timestepsvector transitions exist.
- class embodichain.learning.rl.differentiable_trainer.DifferentiableTrainerCfg[source]#
Bases:
objectConfiguration for graph-preserving segmented training.
Methods:
__init__([segment_length, update_horizon, ...])copy(**kwargs)Return a new object replacing specified fields with new values.
replace(**kwargs)Return a new object replacing specified fields with new values.
to_dict()Convert an object into dictionary recursively.
validate([prefix])Check the validity of configclass object.
Attributes:
- __init__(segment_length=<factory>, update_horizon=<factory>, deterministic_actions=<factory>, checkpoint_dir=<factory>, experiment_name=<factory>, save_frequency_updates=<factory>, eval_frequency_steps=<factory>, num_eval_episodes=<factory>, eval_seed=<factory>, use_wandb=<factory>, best_eval_metric=<factory>, best_eval_mode=<factory>)#
-
best_eval_metric:
str#
-
best_eval_mode:
str#
-
checkpoint_dir:
str#
- copy(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
-
deterministic_actions:
bool#
-
eval_frequency_steps:
int#
-
eval_seed:
int|None#
-
experiment_name:
str#
-
num_eval_episodes:
int#
- replace(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
-
save_frequency_updates:
int#
-
segment_length:
int#
- to_dict()#
Convert an object into dictionary recursively.
Note
Ignores all names starting with “__” (i.e. built-in methods).
- Parameters:
obj (
object) – An instance of a class to convert.- Raises:
ValueError – When input argument is not an object.
- Return type:
dict[str,Any]- Returns:
Converted dictionary mapping.
-
update_horizon:
int|None#
-
use_wandb:
bool#
- validate(prefix='')#
Check the validity of configclass object.
This function checks if the object is a valid configclass object. A valid configclass object contains no MISSING entries.
- Parameters:
obj (
object) – The object to check.prefix (
str) – The prefix to add to the missing fields. Defaults to ‘’.
- Return type:
list[str]- Returns:
A list of missing fields.
- Raises:
TypeError – When the object is not a valid configuration object.
Rollout Buffer#
On-policy rollout buffer (RolloutBuffer) owning preallocated TensorDict storage, plus minibatch iteration helpers.
Classes:
Single-rollout buffer backed by a preallocated TensorDict. |
Functions:
|
Yield shuffled minibatches from a flattened rollout. |
|
Build a transition-aligned TensorDict from a rollout. |
- class embodichain.learning.rl.buffer.RolloutBuffer[source]#
Bases:
objectSingle-rollout buffer backed by a preallocated TensorDict.
The shared rollout uses a uniform [num_envs, time + 1] layout. For transition-only fields such as action, reward, and done, the final time index is reused as padding so the collector, environment, and algorithms can share a single TensorDict batch shape.
Methods:
__init__(num_envs, rollout_len, obs_dim, ...)add(rollout)Mark the shared rollout as ready for consumption.
get([flatten])Return the stored rollout and clear the buffer.
is_full()Return whether a rollout is waiting to be consumed.
Return the shared rollout TensorDict for collector write-in.
Attributes:
- property buffer: TensorDict#
- embodichain.learning.rl.buffer.iterate_minibatches(rollout, batch_size, device)[source]#
Yield shuffled minibatches from a flattened rollout.
- Return type:
Iterator[TensorDict]
- embodichain.learning.rl.buffer.transition_view(rollout, flatten=False)[source]#
Build a transition-aligned TensorDict from a rollout.
The shared rollout uses a uniform [num_envs, time + 1] layout. For transition-only fields such as action, reward, and done, the final slot is reserved as padding so that all rollout fields share the same batch shape. This helper drops that padded slot and exposes the valid transition slices as a TensorDict with batch shape [num_envs, time].
- Parameters:
rollout (
TensorDict) – Rollout TensorDict with root batch shape [num_envs, time + 1].flatten (
bool) – If True, return a flattened [num_envs * time] view.
- Return type:
TensorDict- Returns:
TensorDict containing transition-aligned fields.
Collectors#
Collectors that step vectorized environments and assemble rollout data into a preallocated TensorDict layout.
Classes:
Base class for rollout collectors. |
|
Collect graph-preserving rollouts without a preallocated buffer. |
|
An immutable sequence of graph-preserving transitions. |
|
One graph-preserving environment transition. |
|
Synchronously collect rollouts from a vectorized environment. |
- class embodichain.learning.rl.collector.BaseCollector[source]#
Bases:
ABCBase class for rollout collectors.
Methods:
collect(num_steps[, rollout, on_step_callback])Collect a rollout and return it as a TensorDict.
- class embodichain.learning.rl.collector.DifferentiableCollector[source]#
Bases:
objectCollect graph-preserving rollouts without a preallocated buffer.
Methods:
__init__(env, policy, device)collect(num_steps, *[, deterministic, ...])Collect a graph-preserving rollout segment.
Start a new truncated-backpropagation segment.
reset(*[, seed])Reset the environment and collector state.
- collect(num_steps, *, deterministic=False, on_step_callback=None)[source]#
Collect a graph-preserving rollout segment.
- Parameters:
num_steps (
int) – Number of differentiable environment steps.deterministic (
bool) – Whether to use deterministic policy actions.on_step_callback (
Optional[Callable[[DifferentiableTransition],None]]) – Optional callback invoked with each transition.
- Return type:
- Returns:
An immutable differentiable rollout.
- Raises:
ValueError – If
num_stepsis not positive.
- class embodichain.learning.rl.collector.DifferentiableRollout[source]#
Bases:
objectAn immutable sequence of graph-preserving transitions.
Methods:
__init__(initial_observation, transitions)Attributes:
Return the observation after the final transition.
Return the number of collected transitions.
Stack rewards as
[time, num_envs]without detaching them.- __init__(initial_observation, transitions)#
- property final_observation: Tensor#
Return the observation after the final transition.
-
initial_observation:
Tensor#
- property num_steps: int#
Return the number of collected transitions.
- property rewards: Tensor#
Stack rewards as
[time, num_envs]without detaching them.
-
transitions:
tuple[DifferentiableTransition,...]#
- class embodichain.learning.rl.collector.DifferentiableTransition[source]#
Bases:
objectOne graph-preserving environment transition.
Methods:
__init__(observation, policy_output, reward, ...)Attributes:
Return the differentiable policy action.
Return the combined termination mask.
- __init__(observation, policy_output, reward, terminated, truncated, next_observation, info)#
- property action: Tensor#
Return the differentiable policy action.
- property done: Tensor#
Return the combined termination mask.
-
info:
dict[str,Any]#
-
next_observation:
Tensor#
-
observation:
Tensor#
-
policy_output:
TensorDict#
-
reward:
Tensor#
-
terminated:
Tensor#
-
truncated:
Tensor#
- class embodichain.learning.rl.collector.SyncCollector[source]#
Bases:
BaseCollectorSynchronously collect rollouts from a vectorized environment.
Methods:
Policy Models#
Policy-network registration and model construction (ActorCritic, ActorOnly, MLP, Policy).
Classes:
Actor-Critic with learnable log_std for Gaussian policy. |
|
Actor-only policy for algorithms that do not use a value function (e.g., GRPO). |
|
General MLP supporting custom last activation, orthogonal init, and output reshape. |
|
Abstract base class that all RL policies must implement. |
Functions:
|
Construct an MLP module from a minimal json-like config. |
|
Build a policy from config using spaces for extensibility. |
|
|
|
- class embodichain.learning.rl.models.ActorCritic[source]#
Bases:
PolicyActor-Critic with learnable log_std for Gaussian policy.
This is a placeholder implementation of the Policy interface that: - Encapsulates MLP networks (actor + critic) that need to be trained by RL algorithms - Handles internal computation: MLP output → mean + learnable log_std → Normal distribution - Provides a uniform interface for RL algorithms (PPO, SAC, etc.)
This allows seamless swapping with other policy implementations (e.g., VLAPolicy) without modifying RL algorithm code.
Implements TensorDict-native interfaces while preserving get_action() compatibility for evaluation and legacy call-sites.
Methods:
__init__(obs_dim, action_dim, device, actor, ...)Initialize internal Module state, shared by both nn.Module and ScriptModule.
evaluate_actions(tensordict)Evaluate actions and return current policy outputs.
forward(tensordict[, deterministic])Write sampled actions and value estimates into the TensorDict.
get_differentiable_action(tensordict[, ...])Sample an action with pathwise gradients.
get_value(tensordict)Write value estimate for the given observations into the TensorDict.
- __init__(obs_dim, action_dim, device, actor, critic)[source]#
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- evaluate_actions(tensordict)[source]#
Evaluate actions and return current policy outputs.
- Parameters:
tensordict (
TensorDict) – TensorDict containing obs and action.- Return type:
TensorDict- Returns:
A new TensorDict containing sample_log_prob, entropy, and value.
- forward(tensordict, deterministic=False)[source]#
Write sampled actions and value estimates into the TensorDict.
- Return type:
TensorDict
- class embodichain.learning.rl.models.ActorOnly[source]#
Bases:
PolicyActor-only policy for algorithms that do not use a value function (e.g., GRPO).
Same interface as ActorCritic: get_action and evaluate_actions return (action, log_prob, value), but value is always zeros since no critic is used.
Methods:
__init__(obs_dim, action_dim, device, actor)Initialize internal Module state, shared by both nn.Module and ScriptModule.
evaluate_actions(tensordict)Evaluate actions and return current policy outputs.
forward(tensordict[, deterministic])Write sampled actions and value estimates into the TensorDict.
get_differentiable_action(tensordict[, ...])Sample an action with pathwise gradients.
get_value(tensordict)Write value estimate for the given observations into the TensorDict.
- __init__(obs_dim, action_dim, device, actor)[source]#
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- evaluate_actions(tensordict)[source]#
Evaluate actions and return current policy outputs.
- Parameters:
tensordict (
TensorDict) – TensorDict containing obs and action.- Return type:
TensorDict- Returns:
A new TensorDict containing sample_log_prob, entropy, and value.
- forward(tensordict, deterministic=False)[source]#
Write sampled actions and value estimates into the TensorDict.
- Return type:
TensorDict
- class embodichain.learning.rl.models.MLP[source]#
Bases:
SequentialGeneral MLP supporting custom last activation, orthogonal init, and output reshape.
- Parameters:
input_dim (-) – input dimension
output_dim (-) – output dimension (int or shape tuple/list)
hidden_dims (-) – hidden layer sizes, e.g. [256, 256]
activation (-) – hidden layer activation name (relu/elu/tanh/gelu/silu)
last_activation (-) – last-layer activation name or None for linear
use_layernorm (-) – whether to add LayerNorm after each hidden linear layer
dropout_p (-) – dropout probability for hidden layers (0 disables)
Methods:
__init__(input_dim, output_dim, hidden_dims)Initialize internal Module state, shared by both nn.Module and ScriptModule.
init_orthogonal([scales])Orthogonal-initialize linear layers and zero the bias.
- class embodichain.learning.rl.models.Policy[source]#
Bases:
Module,ABCAbstract base class that all RL policies must implement.
A Policy: - Encapsulates neural networks that are trained by RL algorithms - Handles internal computations (e.g., network output → distribution) - Provides a uniform interface for algorithms (PPO, SAC, etc.)
Methods:
__init__()Initialize internal Module state, shared by both nn.Module and ScriptModule.
evaluate_actions(tensordict)Evaluate actions and return current policy outputs.
forward(tensordict[, deterministic])Write sampled actions and value estimates into the TensorDict.
get_action(tensordict[, deterministic])Sample actions into the provided TensorDict without gradients.
get_differentiable_action(tensordict[, ...])Sample actions while preserving gradients to policy parameters.
get_value(tensordict)Write value estimate for the given observations into the TensorDict.
Attributes:
Device where the policy parameters are located.
- device: torch.device#
Device where the policy parameters are located.
- abstract evaluate_actions(tensordict)[source]#
Evaluate actions and return current policy outputs.
- Parameters:
tensordict (
TensorDict) – TensorDict containing obs and action.- Return type:
TensorDict- Returns:
A new TensorDict containing sample_log_prob, entropy, and value.
- abstract forward(tensordict, deterministic=False)[source]#
Write sampled actions and value estimates into the TensorDict.
- Return type:
TensorDict
- get_action(tensordict, deterministic=False)[source]#
Sample actions into the provided TensorDict without gradients.
- Parameters:
tensordict (
TensorDict) – Input TensorDict containing obs.deterministic (
bool) – If True, return the mean action; otherwise sample
- Return type:
TensorDict- Returns:
TensorDict with action, sample_log_prob, and value populated.
- get_differentiable_action(tensordict, deterministic=False)[source]#
Sample actions while preserving gradients to policy parameters.
Stochastic implementations must use a reparameterized sample such as
torch.distributions.Distribution.rsample(). The base implementation fails explicitly to prevent a non-reparameterizedsample()call from silently producing zero pathwise gradients.- Parameters:
tensordict (
TensorDict) – Input TensorDict containingobs.deterministic (
bool) – If True, return a differentiable deterministic action.
- Return type:
TensorDict- Returns:
TensorDict with differentiable policy outputs populated.
- Raises:
NotImplementedError – If the policy has no differentiable sampling implementation.
- abstract get_value(tensordict)[source]#
Write value estimate for the given observations into the TensorDict.
- Parameters:
tensordict (
TensorDict) – Input TensorDict containing obs.- Return type:
TensorDict- Returns:
TensorDict with value populated.
- training: bool#
- embodichain.learning.rl.models.build_mlp_from_cfg(module_cfg, in_dim, out_dim)[source]#
Construct an MLP module from a minimal json-like config.
- Return type:
- Expected schema:
- module_cfg = {
“type”: “mlp”, “hidden_sizes”: [256, 256], “activation”: “relu”,
}
- embodichain.learning.rl.models.build_policy(policy_block, obs_space, action_space, device, actor=None, critic=None)[source]#
Build a policy from config using spaces for extensibility.
Built-in MLP policies still resolve flattened obs_dim / action_dim, while custom policies may accept richer obs_space / action_space inputs.
- Return type:
Training#
Functions:
|
Command-line interface for RL training. |
|
Parse command-line arguments. |
|
Run training from a config file path. |
- embodichain.learning.rl.train.cli(argv=None)[source]#
Command-line interface for RL training.
Parses CLI arguments and launches training from a config file.
Task packages are discovered (and init hooks executed) before training so that task environments registered in separate packages (e.g.
embodichain_tasks) are available tobuild_env. This mirrors therun_envCLI.- Return type:
None
- embodichain.learning.rl.train.parse_args(argv=None)[source]#
Parse command-line arguments.
- Parameters:
argv (
Sequence[str] |None) – Arguments excluding the command name. Usessys.argvwhen omitted.- Return type:
Namespace- Returns:
Parsed training arguments.
- embodichain.learning.rl.train.train_from_config(config_path, distributed=None, *, profile=False, profile_output=None)[source]#
Run training from a config file path.
- Parameters:
config_path (
str) – Path to the training config file (.json, .yaml, or .yml).distributed (
bool|None) – If True, run multi-GPU distributed training. If None, use trainer.distributed from config.profile (
bool) – Enable gymEnvProfileron the training environment.profile_output (
str|None) – Optional JSON dump path for the profiling report.
Utilities#
RL helper utilities: algorithm config, optimizers, and observation helpers.
Classes:
Shared fields for RL algorithm configs. |
|
Optional LR scheduler. |
|
Policy optimizer configuration. |
Functions:
|
Fill |
|
Build a scheduler, or |
|
|
|
|
|
|
|
Convert an environment observation mapping into a TensorDict. |
Flatten a hierarchical observation TensorDict into a 2D tensor. |
|
- class embodichain.learning.rl.utils.AlgorithmCfg[source]#
Bases:
objectShared fields for RL algorithm configs.
Methods:
__init__([device, optimizer, lr_scheduler, ...])copy(**kwargs)Return a new object replacing specified fields with new values.
replace(**kwargs)Return a new object replacing specified fields with new values.
to_dict()Convert an object into dictionary recursively.
validate([prefix])Check the validity of configclass object.
Attributes:
- __init__(device=<factory>, optimizer=<factory>, lr_scheduler=<factory>, batch_size=<factory>, gamma=<factory>, gae_lambda=<factory>, max_grad_norm=<factory>)#
-
batch_size:
int#
- copy(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
-
device:
str#
-
gae_lambda:
float#
-
gamma:
float#
-
lr_scheduler:
LRSchedulerCfg#
-
max_grad_norm:
float#
-
optimizer:
OptimizerCfg#
- replace(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
- to_dict()#
Convert an object into dictionary recursively.
Note
Ignores all names starting with “__” (i.e. built-in methods).
- Parameters:
obj (
object) – An instance of a class to convert.- Raises:
ValueError – When input argument is not an object.
- Return type:
dict[str,Any]- Returns:
Converted dictionary mapping.
- validate(prefix='')#
Check the validity of configclass object.
This function checks if the object is a valid configclass object. A valid configclass object contains no MISSING entries.
- Parameters:
obj (
object) – The object to check.prefix (
str) – The prefix to add to the missing fields. Defaults to ‘’.
- Return type:
list[str]- Returns:
A list of missing fields.
- Raises:
TypeError – When the object is not a valid configuration object.
- class embodichain.learning.rl.utils.LRSchedulerCfg[source]#
Bases:
objectOptional LR scheduler.
name=Nonedisables scheduling.Horizon keys (
total_iters/T_max) may be omitted and bound later byBaseAlgorithm.bind_schedule.Methods:
__init__([name, kwargs])copy(**kwargs)Return a new object replacing specified fields with new values.
replace(**kwargs)Return a new object replacing specified fields with new values.
to_dict()Convert an object into dictionary recursively.
validate([prefix])Check the validity of configclass object.
Attributes:
- __init__(name=<factory>, kwargs=<factory>)#
- copy(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
-
kwargs:
dict[str,Any]#
-
name:
str|None#
- replace(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
- to_dict()#
Convert an object into dictionary recursively.
Note
Ignores all names starting with “__” (i.e. built-in methods).
- Parameters:
obj (
object) – An instance of a class to convert.- Raises:
ValueError – When input argument is not an object.
- Return type:
dict[str,Any]- Returns:
Converted dictionary mapping.
- validate(prefix='')#
Check the validity of configclass object.
This function checks if the object is a valid configclass object. A valid configclass object contains no MISSING entries.
- Parameters:
obj (
object) – The object to check.prefix (
str) – The prefix to add to the missing fields. Defaults to ‘’.
- Return type:
list[str]- Returns:
A list of missing fields.
- Raises:
TypeError – When the object is not a valid configuration object.
- class embodichain.learning.rl.utils.OptimizerCfg[source]#
Bases:
objectPolicy optimizer configuration.
Methods:
__init__([name, learning_rate, kwargs])copy(**kwargs)Return a new object replacing specified fields with new values.
replace(**kwargs)Return a new object replacing specified fields with new values.
to_dict()Convert an object into dictionary recursively.
validate([prefix])Check the validity of configclass object.
Attributes:
- __init__(name=<factory>, learning_rate=<factory>, kwargs=<factory>)#
- copy(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
-
kwargs:
dict[str,Any]#
-
learning_rate:
float#
-
name:
str#
- replace(**kwargs)#
Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@configclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = c.replace(x=3) assert c1.x == 3 and c1.y == 2
- Parameters:
obj (
object) – The object to replace.**kwargs – The fields to replace and their new values.
- Return type:
object- Returns:
The new object.
- to_dict()#
Convert an object into dictionary recursively.
Note
Ignores all names starting with “__” (i.e. built-in methods).
- Parameters:
obj (
object) – An instance of a class to convert.- Raises:
ValueError – When input argument is not an object.
- Return type:
dict[str,Any]- Returns:
Converted dictionary mapping.
- validate(prefix='')#
Check the validity of configclass object.
This function checks if the object is a valid configclass object. A valid configclass object contains no MISSING entries.
- Parameters:
obj (
object) – The object to check.prefix (
str) – The prefix to add to the missing fields. Defaults to ‘’.
- Return type:
list[str]- Returns:
A list of missing fields.
- Raises:
TypeError – When the object is not a valid configuration object.
- embodichain.learning.rl.utils.bind_scheduler_horizon(cfg, total_updates)[source]#
Fill
total_iters/T_maxfrom the training update budget.- Return type:
- embodichain.learning.rl.utils.build_lr_scheduler(optimizer, cfg)[source]#
Build a scheduler, or
Nonewhennameis unset.- Return type:
LRScheduler|None
- embodichain.learning.rl.utils.dict_to_tensordict(obs_dict, device)[source]#
Convert an environment observation mapping into a TensorDict.
- Parameters:
obs_dict (
Tensor|TensorDict|Mapping[str,Any]) – Tensor or mapping returned byreset()orstep().device (
device|str) – Target device for the resulting TensorDict.
- Return type:
TensorDict- Returns:
Observation TensorDict moved onto the target device.
- embodichain.learning.rl.utils.flatten_dict_observation(obs)[source]#
Flatten a hierarchical observation TensorDict into a 2D tensor.
- Parameters:
obs (
TensorDict) – Observation TensorDict with batch dimension [num_envs].- Return type:
Tensor- Returns:
Flattened observation tensor of shape [num_envs, obs_dim].