LeWM visual dynamics#
LeWM predicts action-conditioned image embeddings. Its model uses normalized image tensors and raw controller actions with frozen training statistics. The sequence source reads complete HDF5 episode windows, the objective trains the encoder and predictor jointly, and the CEM planner optimizes bounded candidate controls against a target-image embedding. Portable exports include the model configuration, action statistics and caller-provided data contract.
Public package#
Action-conditioned visual latent world model and supervised recipe.
Classes:
Predict action-conditioned latent observations, independent of simulation. |
|
Configure cross-entropy model predictive control. |
|
Optimize controller actions against an encoded visual goal. |
|
Configure the reference-compatible visual encoder and predictor. |
|
Reference next-embedding objective with a Gaussian regularizer. |
|
Sample complete windows from a single immutable, split-owned corpus. |
Functions:
|
Construct a simulation-independent LeWM training run. |
|
Write portable weights, model configuration and data identity. |
|
Verify and load a weights-only export in evaluation mode. |
|
Resize uint8 RGB/RGBA frames and apply the reference ImageNet transform. |
- class embodichain.extensions.models.dynamics.lewm.LeWM[source]#
Predict action-conditioned latent observations, independent of simulation.
- Parameters:
cfg (
LeWMCfg|None) – Encoder, action and temporal dimensions.
Inputs to
encode()are normalized CHW images. Actions to prediction methods are in the recorded controller’s raw units; frozen action statistics are applied internally. The two statistics are included in checkpoints.Methods:
__init__([cfg])Initialize internal Module state, shared by both nn.Module and ScriptModule.
encode(pixels)Encode a batch of normalized image histories into latent vectors.
encode_actions(actions)Encode raw actions using the frozen train-only moments.
goal_cost(predictions, goal)Compute final latent squared distance for each candidate.
load_reference_weights(state)Strictly load a reference weights-only state dictionary.
predict(embeddings, actions)Predict the next latent for each aligned frame and outgoing action.
rollout(history, past_actions, candidates)Roll out strictly future candidate actions from observed history.
set_action_statistics(mean, std)Freeze train-only action moments used for training and planning.
- __init__(cfg=None)[source]#
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- encode(pixels)[source]#
Encode a batch of normalized image histories into latent vectors.
- Parameters:
pixels (
Tensor) – Float images shaped(B, T, 3, H, W).- Return type:
Tensor- Returns:
Latents shaped
(B, T, D).
- encode_actions(actions)[source]#
Encode raw actions using the frozen train-only moments.
- Parameters:
actions (
Tensor) – Raw action tensor of shape(B, T, A).- Return type:
Tensor- Returns:
Encoded actions of shape
(B, T, D).
- static goal_cost(predictions, goal)[source]#
Compute final latent squared distance for each candidate.
- Parameters:
predictions (
Tensor) – Predicted futures(B, S, T, D).goal (
Tensor) – Goal embeddings(B, D).
- Return type:
Tensor- Returns:
Final costs
(B, S).
- load_reference_weights(state)[source]#
Strictly load a reference weights-only state dictionary.
- Parameters:
state (
dict[str,Tensor]) – Original LeWM parameters and buffers without action moments.- Return type:
None
- predict(embeddings, actions)[source]#
Predict the next latent for each aligned frame and outgoing action.
- Parameters:
embeddings (
Tensor) – Latents shaped(B, T, D).actions (
Tensor) – Outgoing raw actions shaped(B, T, A).
- Return type:
Tensor- Returns:
Predicted next latents shaped
(B, T, D).
- rollout(history, past_actions, candidates)[source]#
Roll out strictly future candidate actions from observed history.
- Parameters:
history (
Tensor) – Observed latents(B, H, D).past_actions (
Tensor) – Executed actions between those frames(B, H-1, A).candidates (
Tensor) – Future actions(B, S, T, A).
- Return type:
Tensor- Returns:
Predicted future latents
(B, S, T, D).
- class embodichain.extensions.models.dynamics.lewm.LeWMCEMCfg[source]#
Configure cross-entropy model predictive control.
- Parameters:
horizon (
int) – Number of model-action blocks in a candidate sequence.num_samples (
int) – Candidates drawn per iteration and environment.iterations (
int) – Number of optimization iterations.topk (
int) – Number of elite sequences used to fit the next distribution.candidate_batch_size (
int) – Maximum candidates evaluated together.min_std (
float) – Minimum sampling standard deviation, in the search space’s units. Zero leaves the elite deviation without a lower bound.sampling_distribution (
str) – Initial raw-action distribution:boundsuses the action-box midpoint and half-width;traininguses the frozen training action mean and standard deviation. Model inputs and returned actions remain in raw controller units.normalizedsearches in training-standardized coordinates, starting at zero mean and unit standard deviation, as in the official LeWM example.action_selection (
str) – Return the first action of the best sampled sequence (best), or of the final elite mean sequence (mean). The latter recomputes the cost of that mean sequence.clip_candidates (
bool) – Clip candidates to the controller bounds. The official example leaves candidates unbounded; the environment owns clipping of workspace positions and gripper commands.include_mean (
bool) – Replace candidate zero with the current distribution mean at every iteration, as in the official CEM solver.std_correction (
int) – Degrees of freedom subtracted from the elite count. The original LeWM-compatible solver uses one; zero preserves the population-deviation behavior of the bounded planner.
Methods:
__init__([horizon, num_samples, iterations, ...])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.
- __init__(horizon=<factory>, num_samples=<factory>, iterations=<factory>, topk=<factory>, candidate_batch_size=<factory>, min_std=<factory>, sampling_distribution=<factory>, action_selection=<factory>, clip_candidates=<factory>, include_mean=<factory>, std_correction=<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.
- 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 string names starting with “__” (i.e. built-in methods). Non-string mapping keys retain their original type.
- Parameters:
obj (
object) – An instance of a class to convert.- Raises:
ValueError – When input argument is not an object.
- Return type:
dict[Any,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.extensions.models.dynamics.lewm.LeWMCEMPlanner[source]#
Optimize controller actions against an encoded visual goal.
- Parameters:
model (
LeWM) – Frozen evaluation-mode LeWM.low (
Tensor) – Per-component lower action bounds.high (
Tensor) – Per-component upper action bounds.cfg (
LeWMCEMCfg|None) – Candidate and optimization settings.seed (
int) – Seed for a planner-owned device RNG.
Methods:
__init__(model, low, high[, cfg, seed])plan(history, past_actions, goal)Return the first action and sequence cost for each environment.
plan_sequence(history, past_actions, goal)Return a complete sequence and its terminal goal cost.
- plan(history, past_actions, goal)[source]#
Return the first action and sequence cost for each environment.
- Parameters:
history (
Tensor) – Encoded frames(B, H, D).past_actions (
Tensor) – Raw actions between history frames(B, H-1, A).goal (
Tensor) – Encoded goal images(B, D).
- Return type:
tuple[Tensor,Tensor]- Returns:
First raw actions
(B, A)and costs(B,)of the selected complete sequences, using the configured selection rule.
- plan_sequence(history, past_actions, goal)[source]#
Return a complete sequence and its terminal goal cost.
- Parameters:
history (
Tensor) – Encoded observed frames(B, H, D).past_actions (
Tensor) – Executed model-action blocks(B, H-1, A).goal (
Tensor) – Encoded goal images(B, D).
- Return type:
tuple[Tensor,Tensor]- Returns:
Raw action blocks
(B, horizon, A)and sequence costs(B,). The host unpacks each block into consecutive controller actions.
- class embodichain.extensions.models.dynamics.lewm.LeWMCfg[source]#
Configure the reference-compatible visual encoder and predictor.
- Parameters:
action_dim (
int) – Number of scalar controls in one model step, including all concatenated raw controls whenaction_blockis greater than one.image_size (
int) – Square encoder input size.patch_size (
int) – ViT patch size.embed_dim (
int) – Latent and transformer width.history_size (
int) – Maximum number of observed frames used by the predictor, sampledaction_blockraw timesteps apart.vision_depth (
int) – Number of ViT blocks.vision_heads (
int) – Number of ViT attention heads.predictor_depth (
int) – Number of causal predictor blocks.predictor_heads (
int) – Number of predictor attention heads.predictor_head_dim (
int) – Width per predictor attention head.mlp_dim (
int) – Width of predictor and projector hidden layers.dropout (
float) – Predictor dropout probability.action_block (
int) – Number of consecutive raw controls concatenated into one model action.action_dimmust be divisible by this number.
Methods:
__init__([action_dim, image_size, ...])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.
- __init__(action_dim=<factory>, image_size=<factory>, patch_size=<factory>, embed_dim=<factory>, history_size=<factory>, vision_depth=<factory>, vision_heads=<factory>, predictor_depth=<factory>, predictor_heads=<factory>, predictor_head_dim=<factory>, mlp_dim=<factory>, dropout=<factory>, action_block=<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.
- 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 string names starting with “__” (i.e. built-in methods). Non-string mapping keys retain their original type.
- Parameters:
obj (
object) – An instance of a class to convert.- Raises:
ValueError – When input argument is not an object.
- Return type:
dict[Any,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.extensions.models.dynamics.lewm.LeWMObjective[source]#
Reference next-embedding objective with a Gaussian regularizer.
- Parameters:
sigreg_weight (
float) – Weight of the SIGReg term.knots (
int) – Number of numerical integration knots.num_proj (
int) – Number of random projection directions.
Methods:
__init__([sigreg_weight, knots, num_proj])compute_loss(model, batch)Predict all next frames in a complete aligned context window.
- compute_loss(model, batch)[source]#
Predict all next frames in a complete aligned context window.
- Parameters:
model (
Module) – LeWM model.batch (
SupervisedBatch) – uint8 HWC images and outgoing raw actions.
- Return type:
- Returns:
Joint differentiable loss and its separately reported terms.
- class embodichain.extensions.models.dynamics.lewm.LeWMSequenceSource[source]#
Sample complete windows from a single immutable, split-owned corpus.
- Parameters:
path (
str|Path) – HDF5 corpus with metadata and anepisodesgroup.split (
str) – Required corpus split: train, validation or test.history_size (
int) – Number of observed frames in each window.horizon (
int) – Number of future frames after the observed history.action_block (
int) – Raw timesteps between observed frames. All intervening actions are concatenated in time order into one model action.cache_device (
str|None) – Optional device for an immutable uint8 image/action cache.cache_max_bytes (
int) – Maximum persistent cache bytes per corpus. Required when caching; batch outputs and model activations are additional.
Each episode has
pixelsas uint8 HWC frames andactionsas raw float32 controls. It contains exactly one more frame than action, and every action leaves the corresponding frame. Windows never cross episodes.Methods:
__init__(path, split[, history_size, ...])Compute finite sample moments from raw actions in this train split.
iter_batches(batch_size)Iterate each complete window once in deterministic episode order.
sample(batch_size, *, generator)Draw independently owned windows using the caller's CPU RNG.
- __init__(path, split, history_size=3, horizon=1, *, action_block=1, cache_device=None, cache_max_bytes=0)[source]#
- action_statistics()[source]#
Compute finite sample moments from raw actions in this train split.
- Return type:
tuple[Tensor,Tensor]- Returns:
CPU float32 mean and standard deviation for each action component.
- iter_batches(batch_size)[source]#
Iterate each complete window once in deterministic episode order.
- Parameters:
batch_size (
int) – Maximum windows in one batch.- Yields:
A batch of owned image/action windows.
- Return type:
Iterator[SupervisedBatch]
- embodichain.extensions.models.dynamics.lewm.build_lewm_trainer(config)[source]#
Construct a simulation-independent LeWM training run.
- Parameters:
config (
Mapping[str,Any]) – Mapping containing model, data, objective, optimizer and trainer sections.data.train_pathanddata.validation_pathmust reference disjoint LeWM HDF5 splits with matching contracts. Optionalcache_deviceandcache_max_bytesindataenable a bounded immutable cache per corpus without changing its identity.- Return type:
- Returns:
Shared supervised trainer with train-only action normalization.
- embodichain.extensions.models.dynamics.lewm.export_lewm(path, model, metadata)[source]#
Write portable weights, model configuration and data identity.
- Parameters:
path (
str|Path) – Fresh export directory.model (
LeWM) – Model whose parameters and action moments are exported.metadata (
dict[str,Any]) – JSON-compatible source and controller contract.
- Return type:
None
- embodichain.extensions.models.dynamics.lewm.load_lewm(path, device='cpu')[source]#
Verify and load a weights-only export in evaluation mode.
- Parameters:
path (
str|Path) – Export directory produced byexport_lewm().device (
str|device) – Destination device for the model.
- Return type:
tuple[LeWM,dict[str,Any]]- Returns:
Evaluation-mode model and its JSON manifest.
- embodichain.extensions.models.dynamics.lewm.preprocess_rgb(images, image_size=224)[source]#
Resize uint8 RGB/RGBA frames and apply the reference ImageNet transform.
- Parameters:
images (
Tensor) – Tensor with shape(..., H, W, 3|4)and uint8 dtype.image_size (
int) – Square output dimension.
- Return type:
Tensor- Returns:
Float32 tensor with shape
(..., 3, image_size, image_size).
Implementation modules#
Image-conditioned LeWM dynamics with explicit action history.
Classes:
Predict action-conditioned latent observations, independent of simulation. |
|
Configure the reference-compatible visual encoder and predictor. |
Functions:
|
Resize uint8 RGB/RGBA frames and apply the reference ImageNet transform. |
- class embodichain.extensions.models.dynamics.lewm.model.LeWM[source]
Predict action-conditioned latent observations, independent of simulation.
- Parameters:
cfg (
LeWMCfg|None) – Encoder, action and temporal dimensions.
Inputs to
encode()are normalized CHW images. Actions to prediction methods are in the recorded controller’s raw units; frozen action statistics are applied internally. The two statistics are included in checkpoints.Methods:
__init__([cfg])Initialize internal Module state, shared by both nn.Module and ScriptModule.
encode(pixels)Encode a batch of normalized image histories into latent vectors.
encode_actions(actions)Encode raw actions using the frozen train-only moments.
goal_cost(predictions, goal)Compute final latent squared distance for each candidate.
load_reference_weights(state)Strictly load a reference weights-only state dictionary.
predict(embeddings, actions)Predict the next latent for each aligned frame and outgoing action.
rollout(history, past_actions, candidates)Roll out strictly future candidate actions from observed history.
set_action_statistics(mean, std)Freeze train-only action moments used for training and planning.
- __init__(cfg=None)[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- encode(pixels)[source]
Encode a batch of normalized image histories into latent vectors.
- Parameters:
pixels (
Tensor) – Float images shaped(B, T, 3, H, W).- Return type:
Tensor- Returns:
Latents shaped
(B, T, D).
- encode_actions(actions)[source]
Encode raw actions using the frozen train-only moments.
- Parameters:
actions (
Tensor) – Raw action tensor of shape(B, T, A).- Return type:
Tensor- Returns:
Encoded actions of shape
(B, T, D).
- static goal_cost(predictions, goal)[source]
Compute final latent squared distance for each candidate.
- Parameters:
predictions (
Tensor) – Predicted futures(B, S, T, D).goal (
Tensor) – Goal embeddings(B, D).
- Return type:
Tensor- Returns:
Final costs
(B, S).
- load_reference_weights(state)[source]
Strictly load a reference weights-only state dictionary.
- Parameters:
state (
dict[str,Tensor]) – Original LeWM parameters and buffers without action moments.- Return type:
None
- predict(embeddings, actions)[source]
Predict the next latent for each aligned frame and outgoing action.
- Parameters:
embeddings (
Tensor) – Latents shaped(B, T, D).actions (
Tensor) – Outgoing raw actions shaped(B, T, A).
- Return type:
Tensor- Returns:
Predicted next latents shaped
(B, T, D).
- rollout(history, past_actions, candidates)[source]
Roll out strictly future candidate actions from observed history.
- Parameters:
history (
Tensor) – Observed latents(B, H, D).past_actions (
Tensor) – Executed actions between those frames(B, H-1, A).candidates (
Tensor) – Future actions(B, S, T, A).
- Return type:
Tensor- Returns:
Predicted future latents
(B, S, T, D).
- set_action_statistics(mean, std)[source]
Freeze train-only action moments used for training and planning.
- Parameters:
mean (
Tensor) – One mean per raw action component.std (
Tensor) – Positive standard deviation per component.
- Return type:
None
- class embodichain.extensions.models.dynamics.lewm.model.LeWMCfg[source]
Configure the reference-compatible visual encoder and predictor.
- Parameters:
action_dim (
int) – Number of scalar controls in one model step, including all concatenated raw controls whenaction_blockis greater than one.image_size (
int) – Square encoder input size.patch_size (
int) – ViT patch size.embed_dim (
int) – Latent and transformer width.history_size (
int) – Maximum number of observed frames used by the predictor, sampledaction_blockraw timesteps apart.vision_depth (
int) – Number of ViT blocks.vision_heads (
int) – Number of ViT attention heads.predictor_depth (
int) – Number of causal predictor blocks.predictor_heads (
int) – Number of predictor attention heads.predictor_head_dim (
int) – Width per predictor attention head.mlp_dim (
int) – Width of predictor and projector hidden layers.dropout (
float) – Predictor dropout probability.action_block (
int) – Number of consecutive raw controls concatenated into one model action.action_dimmust be divisible by this number.
Methods:
__init__([action_dim, image_size, ...])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.
- __init__(action_dim=<factory>, image_size=<factory>, patch_size=<factory>, embed_dim=<factory>, history_size=<factory>, vision_depth=<factory>, vision_heads=<factory>, predictor_depth=<factory>, predictor_heads=<factory>, predictor_head_dim=<factory>, mlp_dim=<factory>, dropout=<factory>, action_block=<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.
- 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 string names starting with “__” (i.e. built-in methods). Non-string mapping keys retain their original type.
- Parameters:
obj (
object) – An instance of a class to convert.- Raises:
ValueError – When input argument is not an object.
- Return type:
dict[Any,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.extensions.models.dynamics.lewm.model.preprocess_rgb(images, image_size=224)[source]
Resize uint8 RGB/RGBA frames and apply the reference ImageNet transform.
- Parameters:
images (
Tensor) – Tensor with shape(..., H, W, 3|4)and uint8 dtype.image_size (
int) – Square output dimension.
- Return type:
Tensor- Returns:
Float32 tensor with shape
(..., 3, image_size, image_size).
Bounded HDF5 episode windows for visual dynamics training.
Classes:
Sample complete windows from a single immutable, split-owned corpus. |
- class embodichain.extensions.models.dynamics.lewm.data.LeWMSequenceSource[source]
Sample complete windows from a single immutable, split-owned corpus.
- Parameters:
path (
str|Path) – HDF5 corpus with metadata and anepisodesgroup.split (
str) – Required corpus split: train, validation or test.history_size (
int) – Number of observed frames in each window.horizon (
int) – Number of future frames after the observed history.action_block (
int) – Raw timesteps between observed frames. All intervening actions are concatenated in time order into one model action.cache_device (
str|None) – Optional device for an immutable uint8 image/action cache.cache_max_bytes (
int) – Maximum persistent cache bytes per corpus. Required when caching; batch outputs and model activations are additional.
Each episode has
pixelsas uint8 HWC frames andactionsas raw float32 controls. It contains exactly one more frame than action, and every action leaves the corresponding frame. Windows never cross episodes.Methods:
__init__(path, split[, history_size, ...])action_statistics()Compute finite sample moments from raw actions in this train split.
iter_batches(batch_size)Iterate each complete window once in deterministic episode order.
sample(batch_size, *, generator)Draw independently owned windows using the caller's CPU RNG.
- __init__(path, split, history_size=3, horizon=1, *, action_block=1, cache_device=None, cache_max_bytes=0)[source]
- action_statistics()[source]
Compute finite sample moments from raw actions in this train split.
- Return type:
tuple[Tensor,Tensor]- Returns:
CPU float32 mean and standard deviation for each action component.
- iter_batches(batch_size)[source]
Iterate each complete window once in deterministic episode order.
- Parameters:
batch_size (
int) – Maximum windows in one batch.- Yields:
A batch of owned image/action windows.
- Return type:
Iterator[SupervisedBatch]
- sample(batch_size, *, generator)[source]
Draw independently owned windows using the caller’s CPU RNG.
- Parameters:
batch_size (
int) – Positive number of windows.generator (
Generator) – Explicit CPU sampling generator.
- Return type:
- Returns:
A batch with images and aligned raw actions.
Joint latent prediction and single-device SIGReg objective.
Classes:
Reference next-embedding objective with a Gaussian regularizer. |
- class embodichain.extensions.models.dynamics.lewm.supervised.LeWMObjective[source]
Reference next-embedding objective with a Gaussian regularizer.
- Parameters:
sigreg_weight (
float) – Weight of the SIGReg term.knots (
int) – Number of numerical integration knots.num_proj (
int) – Number of random projection directions.
Methods:
__init__([sigreg_weight, knots, num_proj])compute_loss(model, batch)Predict all next frames in a complete aligned context window.
- __init__(sigreg_weight=0.09, knots=17, num_proj=1024)[source]
- compute_loss(model, batch)[source]
Predict all next frames in a complete aligned context window.
- Parameters:
model (
Module) – LeWM model.batch (
SupervisedBatch) – uint8 HWC images and outgoing raw actions.
- Return type:
- Returns:
Joint differentiable loss and its separately reported terms.
Installable single-device LeWM recipe for the common SL trainer.
Functions:
|
Construct a simulation-independent LeWM training run. |
- embodichain.extensions.models.dynamics.lewm.sl_recipe.build_lewm_trainer(config)[source]
Construct a simulation-independent LeWM training run.
- Parameters:
config (
Mapping[str,Any]) – Mapping containing model, data, objective, optimizer and trainer sections.data.train_pathanddata.validation_pathmust reference disjoint LeWM HDF5 splits with matching contracts. Optionalcache_deviceandcache_max_bytesindataenable a bounded immutable cache per corpus without changing its identity.- Return type:
- Returns:
Shared supervised trainer with train-only action normalization.
Bounded candidate-batched cross-entropy planning in LeWM latent space.
Classes:
Configure cross-entropy model predictive control. |
|
Optimize controller actions against an encoded visual goal. |
- class embodichain.extensions.models.dynamics.lewm.planner.LeWMCEMCfg[source]
Configure cross-entropy model predictive control.
- Parameters:
horizon (
int) – Number of model-action blocks in a candidate sequence.num_samples (
int) – Candidates drawn per iteration and environment.iterations (
int) – Number of optimization iterations.topk (
int) – Number of elite sequences used to fit the next distribution.candidate_batch_size (
int) – Maximum candidates evaluated together.min_std (
float) – Minimum sampling standard deviation, in the search space’s units. Zero leaves the elite deviation without a lower bound.sampling_distribution (
str) – Initial raw-action distribution:boundsuses the action-box midpoint and half-width;traininguses the frozen training action mean and standard deviation. Model inputs and returned actions remain in raw controller units.normalizedsearches in training-standardized coordinates, starting at zero mean and unit standard deviation, as in the official LeWM example.action_selection (
str) – Return the first action of the best sampled sequence (best), or of the final elite mean sequence (mean). The latter recomputes the cost of that mean sequence.clip_candidates (
bool) – Clip candidates to the controller bounds. The official example leaves candidates unbounded; the environment owns clipping of workspace positions and gripper commands.include_mean (
bool) – Replace candidate zero with the current distribution mean at every iteration, as in the official CEM solver.std_correction (
int) – Degrees of freedom subtracted from the elite count. The original LeWM-compatible solver uses one; zero preserves the population-deviation behavior of the bounded planner.
Methods:
__init__([horizon, num_samples, iterations, ...])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.
- __init__(horizon=<factory>, num_samples=<factory>, iterations=<factory>, topk=<factory>, candidate_batch_size=<factory>, min_std=<factory>, sampling_distribution=<factory>, action_selection=<factory>, clip_candidates=<factory>, include_mean=<factory>, std_correction=<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.
- 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 string names starting with “__” (i.e. built-in methods). Non-string mapping keys retain their original type.
- Parameters:
obj (
object) – An instance of a class to convert.- Raises:
ValueError – When input argument is not an object.
- Return type:
dict[Any,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.extensions.models.dynamics.lewm.planner.LeWMCEMPlanner[source]
Optimize controller actions against an encoded visual goal.
- Parameters:
model (
LeWM) – Frozen evaluation-mode LeWM.low (
Tensor) – Per-component lower action bounds.high (
Tensor) – Per-component upper action bounds.cfg (
LeWMCEMCfg|None) – Candidate and optimization settings.seed (
int) – Seed for a planner-owned device RNG.
Methods:
__init__(model, low, high[, cfg, seed])plan(history, past_actions, goal)Return the first action and sequence cost for each environment.
plan_sequence(history, past_actions, goal)Return a complete sequence and its terminal goal cost.
- __init__(model, low, high, cfg=None, *, seed=0)[source]
- plan(history, past_actions, goal)[source]
Return the first action and sequence cost for each environment.
- Parameters:
history (
Tensor) – Encoded frames(B, H, D).past_actions (
Tensor) – Raw actions between history frames(B, H-1, A).goal (
Tensor) – Encoded goal images(B, D).
- Return type:
tuple[Tensor,Tensor]- Returns:
First raw actions
(B, A)and costs(B,)of the selected complete sequences, using the configured selection rule.
- plan_sequence(history, past_actions, goal)[source]
Return a complete sequence and its terminal goal cost.
- Parameters:
history (
Tensor) – Encoded observed frames(B, H, D).past_actions (
Tensor) – Executed model-action blocks(B, H-1, A).goal (
Tensor) – Encoded goal images(B, D).
- Return type:
tuple[Tensor,Tensor]- Returns:
Raw action blocks
(B, horizon, A)and sequence costs(B,). The host unpacks each block into consecutive controller actions.
Weights-only LeWM exports with explicitly bound data contracts.
Functions:
|
Write portable weights, model configuration and data identity. |
|
Verify and load a weights-only export in evaluation mode. |
- embodichain.extensions.models.dynamics.lewm.checkpoint.export_lewm(path, model, metadata)[source]
Write portable weights, model configuration and data identity.
- Parameters:
path (
str|Path) – Fresh export directory.model (
LeWM) – Model whose parameters and action moments are exported.metadata (
dict[str,Any]) – JSON-compatible source and controller contract.
- Return type:
None
- embodichain.extensions.models.dynamics.lewm.checkpoint.load_lewm(path, device='cpu')[source]
Verify and load a weights-only export in evaluation mode.
- Parameters:
path (
str|Path) – Export directory produced byexport_lewm().device (
str|device) – Destination device for the model.
- Return type:
tuple[LeWM,dict[str,Any]]- Returns:
Evaluation-mode model and its JSON manifest.