You're aiming to leverage the MLX framework on your Apple M1 machine to potentially speed up training with the LeRobot repository. Currently, training with device=mps is slow, and you believe MLX could offer a significant performance boost. Let's explore the necessary modifications to integrate MLX.
It's important to understand that completely replacing PyTorch with MLX in this repository would require a substantial rewrite. The core components of train.py and the policy models rely heavily on PyTorch's API (including torch.nn, torch.optim, etc.). MLX, while designed for accelerated machine learning on Apple silicon, is not a direct drop-in replacement for the entirety of PyTorch's functionality. Therefore, a full port to MLX is beyond the scope of a quick proof of concept.
However, we can explore offloading specific compute-intensive parts to MLX while keeping the rest of the training pipeline in PyTorch. The most promising area for this is the vision backbone of your ACT policy.
Here's a strategy to integrate MLX into the ResNet backbone of the ACT policy:
-
Identify PyTorch ResNet Layers for Replacement: Pinpoint the ResNet layers within lerobot/common/policies/act/modeling_act.py that can be swapped with their MLX counterparts. Focus on convolutional and potentially normalization layers.
-
MLX Integration within the Backbone: Introduce MLX equivalents of the targeted ResNet layers. This will involve using MLX's own convolution and potentially other operations.
-
Data Transfer: Implement efficient data transfer between PyTorch and MLX. This is crucial for performance and will likely involve converting tensors between the two frameworks.
-
Mixed Training Loop: Adapt the training loop in train.py to accommodate this hybrid approach. The forward pass will involve transferring data to MLX for the backbone computation, retrieving the results, and continuing the rest of the computation in PyTorch.
Code Modifications:
- File:
lerobot/common/policies/act/modeling_act.py
--- a/lerobot/common/policies/act/modeling_act.py
+++ b/lerobot/common/policies/act/modeling_act.py
@@ -16,6 +16,8 @@
import einops
import numpy as np
import torch
+import mlx.core as mx
+import mlx.nn as nn
import torch.nn.functional as F # noqa: N812
import torchvision
from huggingface_hub import PyTorchModelHubMixin
@@ -271,6 +273,45 @@
)
# Backbone for image feature extraction.
+ if mx.is_mlx_available():
+ try:
+ import mlx.vision.models as mlx_models
+
+ mlx_backbone = getattr(mlx_models, config.vision_backbone)(pretrained=True).features
+ self.backbone_mlx = _replace_submodules(
+ root_module=mlx_backbone,
+ predicate=lambda x: isinstance(x, (nn.[Redacted Person], nn.ReLU)),
+ func=lambda x: (nn.LayerNorm2d(x.num_features) if isinstance(x, nn.BatchNorm2d) else nn.Mish())
+ )
+
+ dummy_input_h_w = (config.crop_shape if config.crop_shape is not None else config.input_shapes[image_key][1:])
+ dummy_input = mx.zeros((1, config.input_shapes[image_key][0], *dummy_input_h_w), dtype=mx.float32)
+
+ with mx.eval_mode():
+ dummy_feature_map = self.backbone_mlx(dummy_input)
+
+ feature_map_shape = tuple(dummy_feature_map.shape[1:])
+ self.backbone_mlx_out_channels = feature_map_shape[0]
+ self.backbone_mlx_out_size = feature_map_shape[1] * feature_map_shape[2]
+
+ print(f"Using MLX backbone for {config.vision_backbone}")
+ except (ImportError, AttributeError):
+ print(f"MLX backbone for {config.vision_backbone} not found, falling back to PyTorch")
+ self.backbone_mlx = None
+ else:
+ self.backbone_mlx = None
+
+
if self.use_images:
+ if self.backbone_mlx:
+ pass # MLX backbone already initialized
+ else:
+ backbone_model = getattr(torchvision.models, config.vision_backbone)(
+ replace_stride_with_dilation=[False, False, config.replace_final_stride_with_dilation],
+ weights=config.pretrained_backbone_weights,
+ norm_layer=FrozenBatchNorm2d,
+ )
+ # Note: The assumption here is that we are using a ResNet model (and hence layer4 is the final
+ # feature map).
+ # Note: The forward method of this returns a dict: {"feature_map": output}.
+ self.backbone = IntermediateLayerGetter(backbone_model, return_layers={"layer4": "feature_map"})
# Transformer (acts as VAE decoder when training with the variational objective).
self.encoder = ACTEncoder(config)
@@ -374,7 +415,12 @@
all_cam_pos_embeds = []
for cam_index in range(batch["observation.images"].shape[-4]):
- cam_features = self.backbone(batch["observation.images"][:, cam_index])["feature_map"]
+ if self.backbone_mlx:
+ images = batch["observation.images"][:, cam_index].to(mx.array)
+ cam_features = self.backbone_mlx(images).to(torch.Tensor)
+ else:
+ images = batch["observation.images"][:, cam_index]
+ cam_features = self.backbone(images)["feature_map"]
# TODO([Redacted Person], [Redacted Person]): remove call to `.to` to speedup forward ; precompute and use
# buffer
cam_pos_embed = self.encoder_cam_feat_pos_embed(cam_features).to(dtype=cam_features.dtype)
- File:
lerobot/scripts/train.py
Modify the device selection logic to include "mlx" as a possibility:
--- a/lerobot/scripts/train.py
+++ b/lerobot/scripts/train.py
@@ -52,7 +52,7 @@
format_big_number,
get_safe_torch_device,
init_hydra_config,
- init_logging,
+ init_logging, is_mlx_available,
set_global_seed,
)
from lerobot.scripts.eval import eval_policy
@@ -274,7 +274,7 @@
set_global_seed(cfg.seed)
# Check device is available
- device = get_safe_torch_device(cfg.device, log=True)
+ device = get_safe_torch_device(cfg.device if not is_mlx_available() else "cpu", log=True)
torch.backends.cudnn.benchmark = True
torch.backends.cuda.matmul.allow_tf32 = True
@@ -451,7 +451,7 @@
dataloading_s = time.perf_counter() - start_time
for key in batch:
- batch[key] = batch[key].to(device, non_blocking=True)
+ batch[key] = batch[key].to(device if not is_mlx_available() else batch[key].device, non_blocking=True)
train_info = update_policy(
policy,
Explanation and Further Considerations:
-
Partial MLX Integration: This approach focuses on using MLX for the ResNet backbone, which is likely a computationally intensive part of your model. This minimizes the required code changes.
-
Data Transfer Overhead: Be aware of the potential overhead of transferring data between PyTorch and MLX. Profile your code to assess the impact and explore optimization strategies if necessary. For example, if the overhead is minimal, you could consider offloading more parts of the model to MLX.
-
MLX Model Availability: Ensure the desired ResNet variant is available in MLX. If not, you might need to implement it yourself or explore alternative architectures. I have added a fallback mechanism to use the PyTorch backbone if the MLX equivalent isn't available.
-
Normalization Layers: I have replaced BatchNorm layers with LayerNorm in the MLX backbone, as BatchNorm is not currently supported well in MLX. You may need to experiment with different normalization techniques for optimal performance.
This modified approach provides a starting point for your POC. Remember to thoroughly test and benchmark to accurately measure the performance difference. If the results are promising, you can consider extending MLX usage to other parts of the model gradually.