From 8bed0fc46510ed37b24f1d23ae633b7248aae769 Mon Sep 17 00:00:00 2001 From: Cadene Date: Tue, 19 Mar 2024 16:29:25 +0000 Subject: [PATCH 1/7] WIP --- LICENSE | 204 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 22 ++++-- 2 files changed, 220 insertions(+), 6 deletions(-) diff --git a/LICENSE b/LICENSE index e41fa9fd..26534b46 100644 --- a/LICENSE +++ b/LICENSE @@ -276,3 +276,207 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## Some of lerobot's code is derived from DETR, which is subject to the following copyright notice: + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020 - present, Facebook, Inc + + 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. diff --git a/README.md b/README.md index dc51fec2..d6bc653e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,19 @@ -# LeRobot +# Le Robot + +#### State-of-the-art meaching learning for real-world robotics + +Le Robot aims to provide models, datasets, and tools for real-world robotics in pytorch. The goal is to lower the barrier for entry to robotics so that everyone can contribute and benefit from sharing datasets and pretrained models. + +Le Robot contains state-of-the-art approaches that have been shown to transfer to the real-world with a focus on imitation learning and reinforcement learning. + +Le Robot already provides a set of pretrained models, datasets with human collected demonstrations, and simulated environments so that everyone can get started. In the coming weeks, the plan is to add more and more supports for real-world robotics on the most affordable robots out there. + +## Acknowledgment + +- Our ACT policy and ALOHA environment are adapted from [ALOHA](https://tonyzhaozh.github.io/aloha/) +- Our Diffusion policy and Pusht environment are adapted from [Diffusion Policy](https://diffusion-policy.cs.columbia.edu/) +- Our TDMPC policy and Simxarm environment are adapted from [FOWM](https://www.yunhaifeng.com/FOWM/) + ## Installation @@ -207,8 +222,3 @@ Finally, you might want to mock the dataset if you need to update the unit tests python tests/scripts/mock_dataset.py --in-data-dir data/$DATASET --out-data-dir tests/data/$DATASET ``` - -## Acknowledgment -- Our Diffusion policy and Pusht environment are adapted from [Diffusion Policy](https://diffusion-policy.cs.columbia.edu/) -- Our TDMPC policy and Simxarm environment are adapted from [FOWM](https://www.yunhaifeng.com/FOWM/) -- Our ACT policy and ALOHA environment are adapted from [ALOHA](https://tonyzhaozh.github.io/aloha/) From 45a4a02b7ed7a9d039bc361927de0641490e54f8 Mon Sep 17 00:00:00 2001 From: Cadene Date: Wed, 20 Mar 2024 10:19:55 +0000 Subject: [PATCH 2/7] WIP --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d6bc653e..0c54cf14 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,14 @@ #### State-of-the-art meaching learning for real-world robotics -Le Robot aims to provide models, datasets, and tools for real-world robotics in pytorch. The goal is to lower the barrier for entry to robotics so that everyone can contribute and benefit from sharing datasets and pretrained models. +Le Robot aims to provide models, datasets, and tools for real-world robotics in PyTorch. The goal is to lower the barrier for entry to robotics so that everyone can contribute and benefit from sharing datasets and pretrained models. Le Robot contains state-of-the-art approaches that have been shown to transfer to the real-world with a focus on imitation learning and reinforcement learning. Le Robot already provides a set of pretrained models, datasets with human collected demonstrations, and simulated environments so that everyone can get started. In the coming weeks, the plan is to add more and more supports for real-world robotics on the most affordable robots out there. +Le Robot is built upon [TorchRL](https://github.com/pytorch/rl) which provides abstrations and utilities for Reinforcement Learning. + ## Acknowledgment - Our ACT policy and ALOHA environment are adapted from [ALOHA](https://tonyzhaozh.github.io/aloha/) @@ -221,4 +223,3 @@ Finally, you might want to mock the dataset if you need to update the unit tests ``` python tests/scripts/mock_dataset.py --in-data-dir data/$DATASET --out-data-dir tests/data/$DATASET ``` - From 98a816f0f86721483706caae54f14b0027476b4e Mon Sep 17 00:00:00 2001 From: Cadene Date: Wed, 20 Mar 2024 14:47:27 +0000 Subject: [PATCH 3/7] WIP --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0c54cf14..18af3242 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ # Le Robot -#### State-of-the-art meaching learning for real-world robotics +#### State-of-the-art machine learning for real-world robotics Le Robot aims to provide models, datasets, and tools for real-world robotics in PyTorch. The goal is to lower the barrier for entry to robotics so that everyone can contribute and benefit from sharing datasets and pretrained models. Le Robot contains state-of-the-art approaches that have been shown to transfer to the real-world with a focus on imitation learning and reinforcement learning. -Le Robot already provides a set of pretrained models, datasets with human collected demonstrations, and simulated environments so that everyone can get started. In the coming weeks, the plan is to add more and more supports for real-world robotics on the most affordable robots out there. +Le Robot already provides a set of pretrained models, datasets with human collected demonstrations, and simulated environments so that everyone can get started. In the coming weeks, the plan is to add more and more supports for real-world robotics on the most affordable and capable robots out there. -Le Robot is built upon [TorchRL](https://github.com/pytorch/rl) which provides abstrations and utilities for Reinforcement Learning. +Le Robot is built upon [TorchRL](https://github.com/pytorch/rl) which provides abstractions and utilities for Reinforcement Learning. ## Acknowledgment From 4b7ec81dde7c4c567bae2b0e70d7d1508f753863 Mon Sep 17 00:00:00 2001 From: Alexander Soare Date: Wed, 20 Mar 2024 14:49:41 +0000 Subject: [PATCH 4/7] remove abstracmethods, fix online training --- lerobot/common/envs/abstract.py | 19 ++++++------------- lerobot/common/policies/abstract.py | 7 +++---- lerobot/scripts/train.py | 6 ++++-- 3 files changed, 13 insertions(+), 19 deletions(-) diff --git a/lerobot/common/envs/abstract.py b/lerobot/common/envs/abstract.py index 8d1a09de..a449e23f 100644 --- a/lerobot/common/envs/abstract.py +++ b/lerobot/common/envs/abstract.py @@ -1,4 +1,3 @@ -import abc from collections import deque from typing import Optional @@ -44,26 +43,20 @@ class AbstractEnv(EnvBase): raise NotImplementedError() # self._prev_action_queue = deque(maxlen=self.num_prev_action) - @abc.abstractmethod def render(self, mode="rgb_array", width=640, height=480): - raise NotImplementedError() + raise NotImplementedError("Abstract method") - @abc.abstractmethod def _reset(self, tensordict: Optional[TensorDict] = None): - raise NotImplementedError() + raise NotImplementedError("Abstract method") - @abc.abstractmethod def _step(self, tensordict: TensorDict): - raise NotImplementedError() + raise NotImplementedError("Abstract method") - @abc.abstractmethod def _make_env(self): - raise NotImplementedError() + raise NotImplementedError("Abstract method") - @abc.abstractmethod def _make_spec(self): - raise NotImplementedError() + raise NotImplementedError("Abstract method") - @abc.abstractmethod def _set_seed(self, seed: Optional[int]): - raise NotImplementedError() + raise NotImplementedError("Abstract method") diff --git a/lerobot/common/policies/abstract.py b/lerobot/common/policies/abstract.py index 1c300dbe..e9c331a0 100644 --- a/lerobot/common/policies/abstract.py +++ b/lerobot/common/policies/abstract.py @@ -1,11 +1,10 @@ -from abc import ABC, abstractmethod from collections import deque import torch from torch import Tensor, nn -class AbstractPolicy(nn.Module, ABC): +class AbstractPolicy(nn.Module): """Base policy which all policies should be derived from. The forward method should generally not be overriden as it plays the role of handling multi-step policies. See its @@ -22,9 +21,9 @@ class AbstractPolicy(nn.Module, ABC): self.n_action_steps = n_action_steps self.clear_action_queue() - @abstractmethod def update(self, replay_buffer, step): """One step of the policy's learning algorithm.""" + raise NotImplementedError("Abstract method") def save(self, fp): torch.save(self.state_dict(), fp) @@ -33,13 +32,13 @@ class AbstractPolicy(nn.Module, ABC): d = torch.load(fp) self.load_state_dict(d) - @abstractmethod def select_actions(self, observation) -> Tensor: """Select an action (or trajectory of actions) based on an observation during rollout. If n_action_steps was provided at initialization, this should return a (batch_size, n_action_steps, *) tensor of actions. Otherwise if n_actions_steps is None, this should return a (batch_size, *) tensor of actions. """ + raise NotImplementedError("Abstract method") def clear_action_queue(self): """This should be called whenever the environment is reset.""" diff --git a/lerobot/scripts/train.py b/lerobot/scripts/train.py index 5ecd616d..242c77bc 100644 --- a/lerobot/scripts/train.py +++ b/lerobot/scripts/train.py @@ -112,6 +112,8 @@ def train(cfg: dict, out_dir=None, job_name=None): raise NotImplementedError() if job_name is None: raise NotImplementedError() + if cfg.online_steps > 0: + assert cfg.rollout_batch_size == 1, "rollout_batch_size > 1 not supported for online training steps" init_logging() @@ -218,11 +220,11 @@ def train(cfg: dict, out_dir=None, job_name=None): # TODO: add configurable number of rollout? (default=1) with torch.no_grad(): rollout = env.rollout( - max_steps=cfg.env.episode_length // cfg.n_action_steps, + max_steps=cfg.env.episode_length, policy=td_policy, auto_cast_to_device=True, ) - assert len(rollout) <= cfg.env.episode_length // cfg.n_action_steps + assert len(rollout) <= cfg.env.episode_length # set same episode index for all time steps contained in this rollout rollout["episode"] = torch.tensor([env_step] * len(rollout), dtype=torch.int) online_buffer.extend(rollout) From 82e6e01651950b3215ce77276c97de9ed353b710 Mon Sep 17 00:00:00 2001 From: Cadene Date: Wed, 20 Mar 2024 17:04:04 +0000 Subject: [PATCH 5/7] v1.1 --- lerobot/common/datasets/aloha.py | 2 +- lerobot/common/datasets/pusht.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lerobot/common/datasets/aloha.py b/lerobot/common/datasets/aloha.py index ec58e701..e891ccdd 100644 --- a/lerobot/common/datasets/aloha.py +++ b/lerobot/common/datasets/aloha.py @@ -84,7 +84,7 @@ class AlohaExperienceReplay(AbstractExperienceReplay): def __init__( self, dataset_id: str, - version: str | None = "v1.0", + version: str | None = "v1.1", batch_size: int = None, *, shuffle: bool = True, diff --git a/lerobot/common/datasets/pusht.py b/lerobot/common/datasets/pusht.py index 3ad6371f..a8a47da8 100644 --- a/lerobot/common/datasets/pusht.py +++ b/lerobot/common/datasets/pusht.py @@ -87,7 +87,7 @@ class PushtExperienceReplay(AbstractExperienceReplay): def __init__( self, dataset_id: str, - version: str | None = "v1.0", + version: str | None = "v1.1", batch_size: int = None, *, shuffle: bool = True, From f23a53c3e4eb1fdb6f9ad84a59d1e7eda1889665 Mon Sep 17 00:00:00 2001 From: Cadene Date: Wed, 20 Mar 2024 17:26:15 +0000 Subject: [PATCH 6/7] update stats.pth --- .../aloha_sim_insertion_scripted/stats.pth | Bin 4434 -> 4434 bytes .../aloha_sim_transfer_cube_human/stats.pth | Bin 4434 -> 4434 bytes .../stats.pth | Bin 4434 -> 4434 bytes 3 files changed, 0 insertions(+), 0 deletions(-) diff --git a/tests/data/aloha_sim_insertion_scripted/stats.pth b/tests/data/aloha_sim_insertion_scripted/stats.pth index 0f3f9d2f19a42274b1627a80bab0de242a430228..4e1c1884488d7dcf6aaac1174d2415ac0f97f5c9 100644 GIT binary patch delta 818 zcmYL{ZAepL6vvm{>2$l!GL)HbTa8GH)NNO1_qoqa%hXcrgD!^(NhoAyqD2Oxi3*wT zcST#NOH(WptyDt*VUR5Vfx%fO)^vs(AwKKOik9)9QipL5Rt*km@@K!rQG zst5vIU$@PpZRs$}E!Sk66~bf5eW2>H9Nw;J7_ENpGC$yJV0Z8kZo1$Nb?Xw-ars{& z^_+*`bAU-hS=>ny4_&~Uiml+CJqfh8DM5(c6R2COLCzO{uu|^8OP40V{Lc(1T!}C$#R!Yms$qYjgLvKW z6ugMn!;$Y=c(^tNCU>^M8}~{fDDNy-M6&1V9wwEW@%k@@3)6@iF>PAHoM zPN&ms$E`Gn=YO%YrryaaY8&A)*>Z zLDaBkl4L7pkhtD3OdOaQ;{4z{$GUeTFt1eK{5T%3JdVxoZ8SXDWy4+*WY-@QM85xR z?qb|MTBb22=L+FsK_?I`^$~mUs?iSz-Duq-4Xkzc;A={6_$$oa#4=WGG5=05Wf78O zt#KZI^=%T^%TmBbx(XCV@<7l1Dv&o`1uUoo|Fk#(j;v$>{$m`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C(>#Fv_IpJo82_uKKN>=ZCFXaKoEZ-8Fc zF3`Pwv4!hYYE^19;krnzPOa92Ya${dby1P(V?5{i!_OxuwX6{n7R({@q--*OOjs0$ zOp6Iak9N~x!thGCi!guzH!UWJ=#Y6ml&dgaH|n$8lZux6W4uJ%!;3265MC1j>62$* ZLQ8y&0C#^(pvJ{h=iM_ffyQh1mj4KwQ(OQ5 delta 811 zcmYLHYe*DP6kgf!?Y^{pq~n%K8BJMtZ!y8~Qq0=xl=OWQ&UJC3)!DUBKiy0F zd0nC-zjj0YyEAlmTOgDk?0^pbts;vUU85E8_9EYJUT2%0RdQ9QV&KEY0z5XE#kC#i z#}fOwuzLW*2N$_~!#o`@H^R*{Tev9o04HDqlW47f9b#M=zb%8Idq6{o7y{6+xop|P zp5%d=JOa_MtKKgyTu#4;kcc5`+D$bTnV(59L9C?cd)Ib0*@@Yi<3@FPHjTG zJHu!{DRhffC&1ik0(6;Hbsw6Ssk|Fks4{&q=x=SM6i*YupK2+njyC}F#d5G@oB&@A zwTO=2Jr}keF&@(avGE#pEJ?U_xA! zbs0&BrfcO1glL}Gei02Al#_%g;=0VIMG-^@x}iyhH_|GC2|*(J!v~q|h@gpxSQSP> Z97*UAq6{WPYWDvqUuh&n8c&pM{{gSlKjZ)a diff --git a/tests/data/aloha_sim_transfer_cube_scripted/stats.pth b/tests/data/aloha_sim_transfer_cube_scripted/stats.pth index b00756e6ca73299de068ca8e72fb9c809d771666..836b29cf59c61c1053796cf2454161d964dd0b0c 100644 GIT binary patch delta 757 zcmcblbV+GL1DnJB#&x@Ax-jg2HL1z|{kfgH9VD6ei=OPWH+C?vcX3!^bLI8QeH|iy z?Vgof+VjKO*`8~wtnGJQQ~LmKc8=>)!mdv~z~;Sp4;rU|I*y8LuVD* za;?8;yLFwu?M&7+HuLXqwl&sWWVVt=02wU z#Qh*SkmhxoJK82YaJblX$aq)@w6C^reY@6HSmcCV$C6X_LOb&8_doh}{eIsLd!wK(`>3`Sa2Uu|XZ@U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0100 Subject: [PATCH 7/7] Add get_safe_torch_device in policies --- lerobot/common/policies/act/policy.py | 3 ++- lerobot/common/policies/diffusion/policy.py | 6 +++--- lerobot/common/policies/tdmpc/policy.py | 6 ++++-- lerobot/common/utils.py | 20 ++++++++++++++++++++ lerobot/scripts/eval.py | 14 +++++++------- lerobot/scripts/train.py | 8 +++----- 6 files changed, 39 insertions(+), 18 deletions(-) diff --git a/lerobot/common/policies/act/policy.py b/lerobot/common/policies/act/policy.py index 539cdcf5..0a0ee405 100644 --- a/lerobot/common/policies/act/policy.py +++ b/lerobot/common/policies/act/policy.py @@ -7,6 +7,7 @@ import torchvision.transforms as transforms from lerobot.common.policies.abstract import AbstractPolicy from lerobot.common.policies.act.detr_vae import build +from lerobot.common.utils import get_safe_torch_device def build_act_model_and_optimizer(cfg): @@ -45,7 +46,7 @@ class ActionChunkingTransformerPolicy(AbstractPolicy): super().__init__(n_action_steps) self.cfg = cfg self.n_action_steps = n_action_steps - self.device = device + self.device = get_safe_torch_device(device) self.model, self.optimizer = build_act_model_and_optimizer(cfg) self.kl_weight = self.cfg.kl_weight logging.info(f"KL Weight {self.kl_weight}") diff --git a/lerobot/common/policies/diffusion/policy.py b/lerobot/common/policies/diffusion/policy.py index 2c47f172..dee5aa64 100644 --- a/lerobot/common/policies/diffusion/policy.py +++ b/lerobot/common/policies/diffusion/policy.py @@ -8,6 +8,7 @@ from lerobot.common.policies.abstract import AbstractPolicy from lerobot.common.policies.diffusion.diffusion_unet_image_policy import DiffusionUnetImagePolicy from lerobot.common.policies.diffusion.model.lr_scheduler import get_scheduler from lerobot.common.policies.diffusion.model.multi_image_obs_encoder import MultiImageObsEncoder +from lerobot.common.utils import get_safe_torch_device class DiffusionPolicy(AbstractPolicy): @@ -62,9 +63,8 @@ class DiffusionPolicy(AbstractPolicy): **kwargs, ) - self.device = torch.device(cfg_device) - if torch.cuda.is_available() and cfg_device == "cuda": - self.diffusion.cuda() + self.device = get_safe_torch_device(cfg_device) + self.diffusion.to(self.device) self.ema = None if self.cfg.use_ema: diff --git a/lerobot/common/policies/tdmpc/policy.py b/lerobot/common/policies/tdmpc/policy.py index 320f6f2b..5bb0da43 100644 --- a/lerobot/common/policies/tdmpc/policy.py +++ b/lerobot/common/policies/tdmpc/policy.py @@ -10,6 +10,7 @@ import torch.nn as nn import lerobot.common.policies.tdmpc.helper as h from lerobot.common.policies.abstract import AbstractPolicy +from lerobot.common.utils import get_safe_torch_device FIRST_FRAME = 0 @@ -94,9 +95,10 @@ class TDMPC(AbstractPolicy): self.action_dim = cfg.action_dim self.cfg = cfg - self.device = torch.device(device) + self.device = get_safe_torch_device(device) self.std = h.linear_schedule(cfg.std_schedule, 0) - self.model = TOLD(cfg).cuda() if torch.cuda.is_available() and device == "cuda" else TOLD(cfg) + self.model = TOLD(cfg) + self.model.to(self.device) self.model_target = deepcopy(self.model) self.optim = torch.optim.Adam(self.model.parameters(), lr=self.cfg.lr) self.pi_optim = torch.optim.Adam(self.model._pi.parameters(), lr=self.cfg.lr) diff --git a/lerobot/common/utils.py b/lerobot/common/utils.py index d174d4b5..a56543b7 100644 --- a/lerobot/common/utils.py +++ b/lerobot/common/utils.py @@ -6,6 +6,26 @@ import numpy as np import torch +def get_safe_torch_device(cfg_device: str, log: bool = False) -> torch.device: + match cfg_device: + case "cuda": + assert torch.cuda.is_available() + device = torch.device("cuda") + case "mps": + assert torch.backends.mps.is_available() + device = torch.device("mps") + case "cpu": + device = torch.device("cpu") + if log: + logging.warning("Using CPU, this will be slow.") + case _: + device = torch.device(cfg_device) + if log: + logging.warning(f"Using custom {cfg_device} device.") + + return device + + def set_seed(seed): """Set seed for reproducibility.""" random.seed(seed) diff --git a/lerobot/scripts/eval.py b/lerobot/scripts/eval.py index 41d58b91..76deb2fe 100644 --- a/lerobot/scripts/eval.py +++ b/lerobot/scripts/eval.py @@ -18,7 +18,7 @@ from lerobot.common.envs.factory import make_env from lerobot.common.logger import log_output_dir from lerobot.common.policies.abstract import AbstractPolicy from lerobot.common.policies.factory import make_policy -from lerobot.common.utils import init_logging, set_seed +from lerobot.common.utils import get_safe_torch_device, init_logging, set_seed def write_video(video_path, stacked_frames, fps): @@ -35,7 +35,8 @@ def eval_policy( fps: int = 15, return_first_video: bool = False, ): - policy.eval() + if policy is not None: + policy.eval() start = time.time() sum_rewards = [] max_rewards = [] @@ -55,7 +56,8 @@ def eval_policy( with torch.inference_mode(): # TODO(alexander-soare): When `break_when_any_done == False` this rolls out for max_steps even when all # envs are done the first time. But we only use the first rollout. This is a waste of compute. - policy.clear_action_queue() + if policy is not None: + policy.clear_action_queue() rollout = env.rollout( max_steps=max_steps, policy=policy, @@ -128,10 +130,8 @@ def eval(cfg: dict, out_dir=None): init_logging() - if cfg.device == "cuda": - assert torch.cuda.is_available() - else: - logging.warning("Using CPU, this will be slow.") + # Check device is available + get_safe_torch_device(cfg.device, log=True) torch.backends.cudnn.benchmark = True torch.backends.cuda.matmul.allow_tf32 = True diff --git a/lerobot/scripts/train.py b/lerobot/scripts/train.py index 242c77bc..872b80df 100644 --- a/lerobot/scripts/train.py +++ b/lerobot/scripts/train.py @@ -12,7 +12,7 @@ from lerobot.common.datasets.factory import make_offline_buffer from lerobot.common.envs.factory import make_env from lerobot.common.logger import Logger, log_output_dir from lerobot.common.policies.factory import make_policy -from lerobot.common.utils import format_big_number, init_logging, set_seed +from lerobot.common.utils import format_big_number, get_safe_torch_device, init_logging, set_seed from lerobot.scripts.eval import eval_policy @@ -117,10 +117,8 @@ def train(cfg: dict, out_dir=None, job_name=None): init_logging() - if cfg.device == "cuda": - assert torch.cuda.is_available() - else: - logging.warning("Using CPU, this will be slow.") + # Check device is available + get_safe_torch_device(cfg.device, log=True) torch.backends.cudnn.benchmark = True torch.backends.cuda.matmul.allow_tf32 = True