mirror of
https://github.com/huggingface/lerobot.git
synced 2026-05-23 12:40:08 +00:00
e670ac5daf
* Add basic support for PEFT adapter methods This changes adds support for training policies with much less parameters by applying adapter methods such as LoRA on specific parts of the policies and therefore possibly higher learning rates / batch sizes. To make this as accessible as possible I thought it useful to provide defaults for `target_modules` and `modules_to_save`. Currently only SmolVLA has such defaults but when we agree that this change is useful I will set out to generate more such defaults. While the user can override these settings, they are expected to only change the peft_method, rank and init_type parameters. * Implement loading of PEFT adapters Loading a PEFT adapter is currently done by initializing a policy with default config and then applying the adapter on the resulting model. This has the obvious drawback that any configurations done during training are not applied in the adapted model. Currently the `use_peft` attribute of `PreTrainedConfig` is only set during loading to signal the following code that it has to deal with a PEFT adapter. However we could imagine a scenario where this is already set at training time and stored alongside the adapter. * Store policy config alongside PEFT checkpoint Before this change the PEFT-wrapped policy did not save the policy's config alongside the adapter config / weights which prevented us from changing the policy config. Now the policy config is saved both in full training and PEFT training. This change makes loading the PEFT policy adapter much easier as well. * Add default config for ACT * Support targets like `all-linear` * Formatting * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix failing tests * Remove PEFT compatibility changes in config We'll wait for the PEFT release that fixes this for good. * Remove `use_peft` parameter from training script Instead we make the PEFT config optional which has the same effect. * Log adapter config to WandB * Better documentation for CLI arguments * Don't unload & merge the PEFT model This can make things hard when using quantized layers (user expects quantized base layers with unquantized adapters for example, merging defaults to upcast the layers leading to higher memory). * Correct way of identifying when to save config * Add CLI end-to-end tests Currently there don't seem to be any way to test the CLI commands. Since this change mostly happens in those I thought it best to add a way to test these commands end-to-end. More integrated commands like `lerobot-record` need patching but standalone commands like training seem to work fine. * Update default targets Removed ACT since it doesn't make sense to fine-tune ACT without having it pretrained beforehand. SmolVLA and Pi0/0.5 are much more senseful targets. * Clean up loading code - Centralized instantiation of the PEFT wrapper in `make_policy` for inference (e.g. in `lerobot-record`) - Training a PEFT policy also sets `cfg.use_peft` so that all inference code loading the policy can rely on that attribute to identify if PEFT loading is needed - Modified RTC example to also include PEFT policies. Mostly because this is an example I'm currently exploring. * Make sure push_to_hub works Since PEFT only wraps `push_to_hub` and not `push_model_to_hub`, the reference to `self` in `policy.push_model_to_hub` is the unwrapped policy which, of course, doesn't know anything about PEFT. To make the upload process aware of PEFT, we pass the unwrapped policy down to `push_model_to_hub` as a kwarg. This is not ideal but I think it is the best way for now. * formatting * Warn when encountering from-scratch-training * Revamp pretrained model loading There were quite a few factors that convinced me that the status quo is able to load pretrained models from the PEFT adapter config but in fact that didn't work. This commit fixes the following things: - policies wrapped in PEFT will now have a `name_or_path` attribute containing the name or path of the pretrained model we're fine-tuning - we further assume that SmolVLA without `pretrained_path` and `load_vlm_weights==False` must be an user-side error - we assume that using PEFT on from-scratch-policies must be an user-side-error * Make it possible to unset policy features This is necessary to train pre-trained policies on new datasets so that the features are inferred from the new dataset and not from the pretrained policy. * Use correct loading for PEFT in RTC example * Make it possible to use PeftModels in eval * Add test checking that PEFT actually reduces params * Adapt state/action projections instead of full-finetuning There doesn't seem to be a benefit to fully fine-tune these layers over just adapting them, so we do that instead. * Disallow PEFT training on non-pretrained policies At first I thought it would make sense to have this feature in case you want to fine-tune a pre-trained section but in the end it makes more trouble than it's worth. It's still possible to allow this in the future when a concrete need arises. * Add basic documentation * Formatting * Add peft as extra dependency, mark tests Fast tests currently fail because of the missing dependency. * Fix pre-commit issues * Add walx <> peft conflict for uv * Exclude peft from pi install for now --------- Co-authored-by: nemo <git@ningu.net> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Pepijn <138571049+pkooij@users.noreply.github.com>
227 lines
8.8 KiB
Python
227 lines
8.8 KiB
Python
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
import abc
|
|
import builtins
|
|
import json
|
|
import os
|
|
import tempfile
|
|
from dataclasses import dataclass, field
|
|
from logging import getLogger
|
|
from pathlib import Path
|
|
from typing import Any, TypeVar
|
|
|
|
import draccus
|
|
from huggingface_hub import hf_hub_download
|
|
from huggingface_hub.constants import CONFIG_NAME
|
|
from huggingface_hub.errors import HfHubHTTPError
|
|
|
|
from lerobot.configs.types import FeatureType, PolicyFeature
|
|
from lerobot.optim.optimizers import OptimizerConfig
|
|
from lerobot.optim.schedulers import LRSchedulerConfig
|
|
from lerobot.utils.constants import ACTION, OBS_STATE
|
|
from lerobot.utils.hub import HubMixin
|
|
from lerobot.utils.utils import auto_select_torch_device, is_amp_available, is_torch_device_available
|
|
|
|
T = TypeVar("T", bound="PreTrainedConfig")
|
|
logger = getLogger(__name__)
|
|
|
|
|
|
@dataclass
|
|
class PreTrainedConfig(draccus.ChoiceRegistry, HubMixin, abc.ABC): # type: ignore[misc,name-defined] #TODO: draccus issue
|
|
"""
|
|
Base configuration class for policy models.
|
|
|
|
Args:
|
|
n_obs_steps: Number of environment steps worth of observations to pass to the policy (takes the
|
|
current step and additional steps going back).
|
|
input_shapes: A dictionary defining the shapes of the input data for the policy.
|
|
output_shapes: A dictionary defining the shapes of the output data for the policy.
|
|
input_normalization_modes: A dictionary with key representing the modality and the value specifies the
|
|
normalization mode to apply.
|
|
output_normalization_modes: Similar dictionary as `input_normalization_modes`, but to unnormalize to
|
|
the original scale.
|
|
"""
|
|
|
|
n_obs_steps: int = 1
|
|
|
|
# `input_features` can be set to None/null in order to infer those values from the dataset.
|
|
input_features: dict[str, PolicyFeature] | None = field(default_factory=dict)
|
|
output_features: dict[str, PolicyFeature] | None = field(default_factory=dict)
|
|
|
|
device: str | None = None # e.g. "cuda", "cuda:0", "cpu", or "mps"
|
|
# `use_amp` determines whether to use Automatic Mixed Precision (AMP) for training and evaluation. With AMP,
|
|
# automatic gradient scaling is used.
|
|
use_amp: bool = False
|
|
|
|
# Whether the policy employed PEFT for training.
|
|
use_peft: bool = False
|
|
|
|
push_to_hub: bool = True # type: ignore[assignment] # TODO: use a different name to avoid override
|
|
repo_id: str | None = None
|
|
|
|
# Upload on private repository on the Hugging Face hub.
|
|
private: bool | None = None
|
|
# Add tags to your policy on the hub.
|
|
tags: list[str] | None = None
|
|
# Add tags to your policy on the hub.
|
|
license: str | None = None
|
|
# Either the repo ID of a model hosted on the Hub or a path to a directory containing weights
|
|
# saved using `Policy.save_pretrained`. If not provided, the policy is initialized from scratch.
|
|
pretrained_path: Path | None = None
|
|
|
|
def __post_init__(self) -> None:
|
|
if not self.device or not is_torch_device_available(self.device):
|
|
auto_device = auto_select_torch_device()
|
|
logger.warning(f"Device '{self.device}' is not available. Switching to '{auto_device}'.")
|
|
self.device = auto_device.type
|
|
|
|
# Automatically deactivate AMP if necessary
|
|
if self.use_amp and not is_amp_available(self.device):
|
|
logger.warning(
|
|
f"Automatic Mixed Precision (amp) is not available on device '{self.device}'. Deactivating AMP."
|
|
)
|
|
self.use_amp = False
|
|
|
|
@property
|
|
def type(self) -> str:
|
|
choice_name = self.get_choice_name(self.__class__)
|
|
if not isinstance(choice_name, str):
|
|
raise TypeError(f"Expected string from get_choice_name, got {type(choice_name)}")
|
|
return choice_name
|
|
|
|
@property
|
|
@abc.abstractmethod
|
|
def observation_delta_indices(self) -> list | None: # type: ignore[type-arg] #TODO: No implementation
|
|
raise NotImplementedError
|
|
|
|
@property
|
|
@abc.abstractmethod
|
|
def action_delta_indices(self) -> list | None: # type: ignore[type-arg] #TODO: No implementation
|
|
raise NotImplementedError
|
|
|
|
@property
|
|
@abc.abstractmethod
|
|
def reward_delta_indices(self) -> list | None: # type: ignore[type-arg] #TODO: No implementation
|
|
raise NotImplementedError
|
|
|
|
@abc.abstractmethod
|
|
def get_optimizer_preset(self) -> OptimizerConfig:
|
|
raise NotImplementedError
|
|
|
|
@abc.abstractmethod
|
|
def get_scheduler_preset(self) -> LRSchedulerConfig | None:
|
|
raise NotImplementedError
|
|
|
|
@abc.abstractmethod
|
|
def validate_features(self) -> None:
|
|
raise NotImplementedError
|
|
|
|
@property
|
|
def robot_state_feature(self) -> PolicyFeature | None:
|
|
if not self.input_features:
|
|
return None
|
|
for ft_name, ft in self.input_features.items():
|
|
if ft.type is FeatureType.STATE and ft_name == OBS_STATE:
|
|
return ft
|
|
return None
|
|
|
|
@property
|
|
def env_state_feature(self) -> PolicyFeature | None:
|
|
if not self.input_features:
|
|
return None
|
|
for _, ft in self.input_features.items():
|
|
if ft.type is FeatureType.ENV:
|
|
return ft
|
|
return None
|
|
|
|
@property
|
|
def image_features(self) -> dict[str, PolicyFeature]:
|
|
if not self.input_features:
|
|
return {}
|
|
return {key: ft for key, ft in self.input_features.items() if ft.type is FeatureType.VISUAL}
|
|
|
|
@property
|
|
def action_feature(self) -> PolicyFeature | None:
|
|
if not self.output_features:
|
|
return None
|
|
for ft_name, ft in self.output_features.items():
|
|
if ft.type is FeatureType.ACTION and ft_name == ACTION:
|
|
return ft
|
|
return None
|
|
|
|
def _save_pretrained(self, save_directory: Path) -> None:
|
|
with open(save_directory / CONFIG_NAME, "w") as f, draccus.config_type("json"):
|
|
draccus.dump(self, f, indent=4)
|
|
|
|
@classmethod
|
|
def from_pretrained(
|
|
cls: builtins.type[T],
|
|
pretrained_name_or_path: str | Path,
|
|
*,
|
|
force_download: bool = False,
|
|
resume_download: bool | None = None,
|
|
proxies: dict[Any, Any] | None = None,
|
|
token: str | bool | None = None,
|
|
cache_dir: str | Path | None = None,
|
|
local_files_only: bool = False,
|
|
revision: str | None = None,
|
|
**policy_kwargs: Any,
|
|
) -> T:
|
|
model_id = str(pretrained_name_or_path)
|
|
config_file: str | None = None
|
|
if Path(model_id).is_dir():
|
|
if CONFIG_NAME in os.listdir(model_id):
|
|
config_file = os.path.join(model_id, CONFIG_NAME)
|
|
else:
|
|
logger.error(f"{CONFIG_NAME} not found in {Path(model_id).resolve()}")
|
|
else:
|
|
try:
|
|
config_file = hf_hub_download(
|
|
repo_id=model_id,
|
|
filename=CONFIG_NAME,
|
|
revision=revision,
|
|
cache_dir=cache_dir,
|
|
force_download=force_download,
|
|
proxies=proxies,
|
|
resume_download=resume_download,
|
|
token=token,
|
|
local_files_only=local_files_only,
|
|
)
|
|
except HfHubHTTPError as e:
|
|
raise FileNotFoundError(
|
|
f"{CONFIG_NAME} not found on the HuggingFace Hub in {model_id}"
|
|
) from e
|
|
|
|
# HACK: Parse the original config to get the config subclass, so that we can
|
|
# apply cli overrides.
|
|
# This is very ugly, ideally we'd like to be able to do that natively with draccus
|
|
# something like --policy.path (in addition to --policy.type)
|
|
with draccus.config_type("json"):
|
|
orig_config = draccus.parse(cls, config_file, args=[])
|
|
|
|
if config_file is None:
|
|
raise FileNotFoundError(f"{CONFIG_NAME} not found in {model_id}")
|
|
|
|
with open(config_file) as f:
|
|
config = json.load(f)
|
|
|
|
config.pop("type")
|
|
with tempfile.NamedTemporaryFile("w+", delete=False, suffix=".json") as f:
|
|
json.dump(config, f)
|
|
config_file = f.name
|
|
|
|
cli_overrides = policy_kwargs.pop("cli_overrides", [])
|
|
with draccus.config_type("json"):
|
|
return draccus.parse(orig_config.__class__, config_file, args=cli_overrides)
|