SPA三维空间感知具身表征代码库

SPA是一个面向具身表征的三维空间感知项目代码库,基于PyTorch Lightning与Hydra组织训练流程,提供预训练ViT编码器用于特征提取,并给出在ScanNet v2上预训练及在VC-1多项基准上评估的示例。

# ![查看原文配图](<https://raw.githubusercontent.com/HaoyiZhu/SPA/HEAD/assets/>) alt="Logo"宽度="35"/ > span样式="颜色:#FF7096;" > SPA :3D span样式="颜色:#FF7096;" 警惕允许有效的表情. [![蟒蛇](https://img.shields.io/badge/-Python_3.9_%7C_3.10_%7C_3.11-blue?logo=python&logoColor=white)](https://github.com/pre-commit/pre-commit) [![烟火](https://img.shields.io/badge/PyTorch_2.0+-ee4c2c?logo=pytorch&logoColor=white)](https://pytorch.org/get-started/locally/) [![闪电](https://img.shields.io/badge/-Lightning_2.0+-792ee5?logo=pytorchlightning&logoColor=white)](https://pytorchlightning.ai/) [![氢化物](https://img.shields.io/badge/Config-Hydra_1.3-89b8cd)](https://hydra.cc/) [![黑色](https://img.shields.io/badge/Code%20Style-Black-black.svg?labelColor=gray)](https://black.readthedocs.io/en/stable/) [![绝对值](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/) [![许可证](https://img.shields.io/badge/License-MIT-green.svg?labelColor=gray)](https://github.com/ashleve/lightning-hydra-template#license) [**项目页**](https://haoyizhu.github.io/spa/) | [**纸张**](https://haoyizhu.github.io/spa/static/images/paper.pdf) | [**arXiv**](https://arxiv.org/abs/2410.08208) | [**HuggingFace 型号**](https://huggingface.co/HaoyiZhu/SPA) | [**现实世界守则库**](https://github.com/HaoyiZhu/RealRobot) | [**Twitter/X**](https://x.com/HaoyiZhu/status/1844675411760013471) | [**YouTube 视频**](https://www.youtube.com/watch?v=LS2R-kBxxwY) [朱孝义](https://www.haoyizhu.site/), [杨洪辉](https://hhyangcs.github.io/), [汪大叶](https://scholar.google.com/citations?hl=zh-CN&user=5SuBWh0AAAAJ), [杨江](https://yangjiangeyjg.github.io/), [林明王 林明王](https://wanglimin.github.io/), [汤贺](http://tonghe90.github.io/) ![笑话](<https://raw.githubusercontent.com/HaoyiZhu/SPA/HEAD/assets/teaser.gif>) **SPA** 这是一种新的代表学习框架,强调 **包含的 AI 中的 3D 空间意识**。它发挥杠杆作用 **不同的神经渲染** 在多视图图像上,我们将给一个具有内在空间理解的香草视觉变换器(ViT),我们也介绍了迄今为止对体现的表达式学习的最全面的评价,涵盖 **268 任务** 横跨 **8模拟器** 在单一任务和基于语言条件的多任务设想中都有不同的政策。 :partying_face: **NEWS**: - *Jan. 2025: (英语).* SPA被ICLR接受 2025! - *十月 2024号:* 已解除密码基地和经过预先训练的检查站。 [arXiv](https://arxiv.org/abs/2410.08208). ## : 剪贴板: 目录 - [项目结构](#telescope-project-structure) - [安装](#installation) - [使用量](#star2-usage) - [培训前](#rocket-pre-training) - [SPA 大型评价](#bulb-spa-large-scale-evaluation) - [抓到他们了](#tada-gotchas) - [许可证](#books-license) - [致谢](#sparkles-acknowledgement) - [引用](#pencil-citation) ## : 望远镜: 项目结构 我们的密码库从优秀的 [闪电海德拉模板](https://github.com/ashleve/lightning-hydra-template)本项目的目录结构如下: < 细节> b > 显示目录结构 < > / summary > ``` ├── .github <- Github Actions workflows │ ├── configs <- Hydra configs │ ├── callbacks <- Callbacks configs │ ├── data <- Data configs │ ├── debug <- Debugging configs │ ├── experiment <- Experiment configs │ ├── extras <- Extra utilities configs │ ├── hydra <- Hydra configs │ ├── local <- Local configs │ ├── logger <- Logger configs │ ├── model <- Model configs │ ├── paths <- Project paths configs │ ├── trainer <- Trainer configs | | │ └── train.yaml <- Main config for training │ ├── data <- Project data │ ├── logs <- Logs generated by hydra and lightning loggers │ ├── scripts <- Shell or Python scripts | ├── spa <- Source code of SPA │ ├── data <- Data scripts │ ├── models <- Model scripts │ ├── utils <- Utility scripts │ │ │ └── train.py <- Run SPA pre-training │ ├── .gitignore <- List of files ignored by git ├── .project-root <- File for inferring the position of project root directory ├── requirements.txt <- File for installing python dependencies ├── setup.py <- File for installing project as a package └── README.md ``` </详情> ## :hammer: 安装 > ⚠️ *3⁄4 ̄ ̧漯B*:我们观察到,使用最新的PyTorch版本(例如PyTorch 2.6)可以导致与我们最初的实验相比不同的特征图. 目前,我们不知道这些差异的确切原因,也无法确认这些差异是否会影响最后的评价结果。 为: **可复制目的**我们强烈建议使用 **PyTorch 2.2.1**,这是在我们最初的开发与测试中使用的版本. 如果您选择使用较新的版本,请注意这个潜在的问题,并谨慎行事. < 细节> b> 基本内容 ```console # clone project git clone https://github.com/HaoyiZhu/SPA.git cd SPA # crerate conda environment conda create -n spa python=3.11 -y conda activate spa # install PyTorch, please refer to https://pytorch.org/ for other CUDA versions # e.g. cuda 11.8: pip3 install torch==2.2.1 torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 # install basic packages pip3 install -r requirements.txt ``` </详情> < 细节> @b> SPA ```console # (optional) if you want to use SPA's volume decoder cd libs/spa-ops pip install -e . cd ../.. # install SPA, so that you can import from anywhere pip install -e . ``` </详情> ## : star2: 用法 < 细节打开> <摘要}>b> 使用 SPA 预训编码器的例子 我们提供经过预先训练的SPA重物,以便提取特征。 [🤗Hugging Face](https://huggingface.co/HaoyiZhu/SPA)。不需要手动下载权重,因为如果需要,SPA会自动处理。 ```python import torch from spa.models import spa_vit_base_patch16, spa_vit_large_patch16 image = torch.rand((1, 3, 224, 224)) # range in [0, 1] # Example usage of SPA-Large (recommended) # or you can use `spa_vit_base_patch16` for SPA-base model = spa_vit_large_patch16(pretrained=True) model.eval() # Freeze the model model.freeze() # (Recommended) move to CUDA image = image.cuda() model = model.cuda() # Obtain the [CLS] token cls_token = model(image) # torch.Size([1, 1024]) # Obtain the reshaped feature map concatenated with [CLS] token feature_map_cat_cls = model( image, feature_map=True, cat_cls=True ) # torch.Size([1, 2048, 14, 14]) # Obtain the reshaped feature map without [CLS] token feature_map_wo_cls = model( image, feature_map=True, cat_cls=False ) # torch.Size([1, 1024, 14, 14]) ``` > **说明:** 输入将自动调整为 `224 x 224` 并实现正常化。 [SPA ViT 编码器](<https://github.com/HaoyiZhu/SPA/blob/HEAD/spa/models/components/img_backbones/vit.py#L69>). </详情> ## :火箭:预训 < 细节> >b>关于ScanNet的预训实例 我们举出一个例子,说明如何在培训前培训SPA。 [ScanNet](http://www.scan-net.org/) v2数据集. 1) 准备数据集 - 下载 [ScanNet](http://www.scan-net.org/) v2数据集. - 随后进行预处理并提取 RGB- D 图像 [PonderV2](https://github.com/OpenGVLab/PonderV2/blob/main/docs/data_preparation.md#scannet-v2)。预处理数据应放入 `data/scannet/`. - 用于快速数据加载的先生成元数据。 以下命令将生成以下元数据 。 `data/scannet/metadata`. ```console python scripts/generate_scannet_metadata.py ``` 2) 运行以下用于预训的命令。 请记住根据您的机器修改超参数, 如节点数和 GPU 设备 。 ```console python spa/train.py experiment=spa_pretrain_vitl trainer.num_nodes=5 trainer.devices=8 ``` </详情> ## :bulb: SPA 大型评价 < 细节> b> VC-1 评价 我们评价了VC-1的MetaWorld、Adroit、DM Control和TriFinger的基准。 [仓库的预留版本](https://github.com/xiaoxiao0406/eai-vc.git) 包括用于评价SPA的代码和配置。 1) 切开 [预留的 VC-1 repo](https://github.com/xiaoxiao0406/eai-vc.git),或者您可以使用 [子模块](<https://github.com/HaoyiZhu/SPA/blob/HEAD/evaluation/eai-vc>) 由 `git submodule update --init --recursive` 财务报告和财务报告 `cd evaluation/eai-vc`. 那么,请遵循指示 在其中 [CortexBench README](https://github.com/facebookresearch/eai-vc/blob/main/cortexbench/README.md) 设置 MuJoCo 和 TriFinger 环境,以及下载所需的数据集. 2) 创建 spar 配置 `<spa_model>.yaml`(例如,使用SPA-Large,如: [spa_vit_large .亚姆尔](https://github.com/xiaoxiao0406/eai-vc/blob/main/vc_models/src/vc_models/conf/model/spa_vit_large.yaml)(单位:千美元) [<vc-1_path>/vc_models/src/vc_models/conf/型号](https://github.com/xiaoxiao0406/eai-vc/tree/main/vc_models/src/vc_models/conf/model). 3) 要运行 Spar 的 VC-1 评估, 请指定模型配置为参数( 嵌入%%% spa_model > ) , 用于每个参数 [皮层](https://github.com/xiaoxiao0406/eai-vc/tree/main/cortexbench). </详情> < 细节> b> LIBERO 评价 请先跑 `git submodule update --init --recursive`。然后安装 LIBERO 侵犯: ```console cd evaluations/LIBERO pip3 install -r requirements.txt pip3 install -e . ``` 然后您必须下载 LIBERO 数据集 : ```console python benchmark_scripts/download_libero_datasets.py ``` 然后,你可以选择: - `BENCHMARK` 从 `[LIBERO_SPATIAL, LIBERO_OBJECT, LIBERO_GOAL, LIBERO_90, LIBERO_10]` 然后运行如下: ```console export CUDA_VISIBLE_DEVICES=GPU_ID && \ export MUJOCO_EGL_DEVICE_ID=GPU_ID && \ python libero/lifelong/main.py seed=SEED \ benchmark_name=BENCHMARK \ policy=bc_transformer_policy \ lifelong=multitask \ policy/image_encoder=spa_encoder.yaml ``` 请注意,在SPA文件中,我们删除了所有的数据增量,因为我们的目标是制作一个简单而公平的环境,而不是培训SOTA政策。为此,您可以运行以下程序: ```console export CUDA_VISIBLE_DEVICES=GPU_ID && \ export MUJOCO_EGL_DEVICE_ID=GPU_ID && \ python libero/lifelong/main.py seed=SEED \ benchmark_name=BENCHMARK \ policy=bc_transformer_policy \ lifelong=multitask \ policy/image_encoder=spa_encoder.yaml \ policy/data_augmentation@policy.color_aug=identity_aug.yaml \ policy/data_augmentation@policy.translation_aug=identity_aug.yaml ``` > 实际上,在SPA的实验中,为了速度考虑,我们每个任务只使用20演示。要这样做,可能需要手动修改数据集。此外,SPA只为25 epochs运行列车. 如果您遇到这个错误, 是因为 LIBERO 的 numpy 版本 。 ``` AttributeError: module 'numpy' has no attribute 'bool'. `np.bool` was a deprecated alias for the builtin `bool`. To avoid this error in existing code, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here. The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations ``` 您可以降低您的数字版本 : ```console pip install "numpy<1.24" ``` 详见LIBERO的正式文件. </详情> < 细节> b>Camera Pose评价 为了复制相机进行评估 我们打开了密码源 [evaluations/probe3d](<https://github.com/HaoyiZhu/SPA/blob/HEAD/evaluations/probe3d>)请先运行 `git submodule update --init --recursive` 财务报告和财务报告 `cd evaluations/probe3d`。然后遵循指令输入 [探测器3d](https://github.com/HaoyiZhu/probe3d/blob/main/data_processing/README.md) 筹备《公约》 **NAVI** 数据集。最后,运行以下命令来评价SPA : ```console python evaluate_navi_camera_pose.py ``` </详情> < 细节> b>Featuremap可视化 > ⚠️ *3⁄4 ̄ ̧漯B*:我们观察到,使用最新的PyTorch版本(例如PyTorch 2.6)可以导致与我们最初的实验相比不同的特征图. 目前,我们不知道这些差异的确切原因,也无法确认这些差异是否会影响最后的评价结果。 为: **可复制目的**我们强烈建议使用 **PyTorch 2.2.1**,这是在我们最初的开发与测试中使用的版本. 如果您选择使用较新的版本,请注意这个潜在的问题,并谨慎行事. 要复制特性映射可视化结果,可以使用: ```console python scripts/visualize_featuremap.py --image_folder assets/feature_map_vis ``` </详情> ## :tada: 抓到他们了 < 细节> 覆盖命令行中的任何配置参数 这个代码库基于 [海德拉语Name](https://github.com/facebookresearch/hydra),允许方便的配置压倒: ```console python src/train.py trainer.max_epochs=20 seed=300 ``` > **说明**:您也可以添加新的参数。 `+` 签名。 ```console python src/train.py +some_new_param=some_new_value ``` </详情> < 细节> b>关于CPU、GPU、多功能的GPU和TPU的列车 ```console # train on CPU python src/train.py trainer=cpu # train on 1 GPU python src/train.py trainer=gpu # train on TPU python src/train.py +trainer.tpu_cores=8 # train with DDP (Distributed Data Parallel) (4 GPUs) python src/train.py trainer=ddp trainer.devices=4 # train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes) python src/train.py trainer=ddp trainer.devices=4 trainer.num_nodes=2 # simulate DDP on CPU processes python src/train.py trainer=ddp_sim trainer.devices=2 # accelerate training on mac python src/train.py trainer=mps ``` </详情> < 细节> b> 混合精度的火车 ```console # train with pytorch native automatic mixed precision (AMP) python src/train.py trainer=gpu +trainer.precision=16 ``` </详情> < 细节> b> 使用 Pytorch Lightning 中可用的不同技巧 ```yaml # gradient clipping may be enabled to avoid exploding gradients python src/train.py trainer.gradient_clip_val=0.5 # run validation loop 4 times during a training epoch python src/train.py +trainer.val_check_interval=0.25 # accumulate gradients python src/train.py trainer.accumulate_grad_batches=10 # terminate training after 12 hours python src/train.py +trainer.max_time="00:12:00:00" ``` > **说明**: PyTorch 闪电提供 [40 + 有用的教练旗帜](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags). </详情> < 细节> b > 轻松调试 ```console # runs 1 epoch in default debugging mode # changes logging directory to `logs/debugs/...` # sets level of all command line loggers to 'DEBUG' # enforces debug-friendly configuration python src/train.py debug=default # run 1 train, val and test loop, using only 1 batch python src/train.py debug=fdr # print execution time profiling python src/train.py debug=profiler # try overfitting to 1 batch python src/train.py debug=overfit # raise exception if there are any numerical anomalies in tensors, like NaN or +/-inf python src/train.py +trainer.detect_anomaly=true # use only 20% of the data python src/train.py +trainer.limit_train_batches=0.2 \ +trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2 ``` > **说明**: 访问 [configs/debug/](<https://github.com/HaoyiZhu/SPA/blob/HEAD/configs/debug/>) 用于不同的调试配置。 </详情> < 细节> b>从检查站恢复培训 ```yaml python src/train.py ckpt_path="/path/to/ckpt/name.ckpt" ``` > **说明**:检查点可以是路径,也可以是URL. > **说明**:目前加载ckpt并不恢复日志实验,但在未来的闪电发布中会支持它. </详情> < 细节> b> 创建超参数上的扫描 ```console # this will run 9 experiments one after the other, # each with different combination of seed and learning rate python src/train.py -m seed=100,200,300 model.optimizer.lr=0.0001,0.00005,0.00001 ``` > **说明**: Hydra 在工作启动时间懒散地编造配置。 如果您在启动任务/ sweep 后更改了代码或配置, 最终构成的配置可能会受到影响 。 </详情> < 细节> >b> 执行文件夹中的所有实验 ```console python src/train.py -m 'exp_maniskill2_act_policy/maniskill2_task@maniskill2_task=glob(*)' ``` > **说明**: Hydra 为控制多运行行为提供了特殊的语法。 学习更多 [这儿](https://hydra.cc/docs/next/tutorials/basic/running_your_app/multi-run)。上面的命令执行所有任务实验 [configs/exp_maniskill2_act_policy/maniskill2_task](<https://github.com/HaoyiZhu/SPA/blob/HEAD/configs/experiment/>). </详情> < 细节> b> 执行多个不同种子的运行 ```console python src/train.py -m seed=100,200,300 trainer.deterministic=True ``` > **说明**: `trainer.deterministic=True` 使烟火更具决定性,但影响性能。 </详情> 更多信息,请参考官方文件: [点火灯](https://github.com/Lightning-AI/pytorch-lightning), [海德拉语Name](https://github.com/facebookresearch/hydra),以及 [闪电海德拉模板](https://github.com/ashleve/lightning-hydra-template). ## : 书籍:许可证 此寄存器在 [MIT许可证](<https://github.com/HaoyiZhu/SPA/blob/HEAD/LICENSE>). ## : sparkles: 致谢 我们的工作主要是建立在 [PointCloudMatters](https://github.com/HaoyiZhu/PointCloudMatters), [PonderV2](https://github.com/OpenGVLab/PonderV2), [UniPAD](https://github.com/Nightmare-n/UniPAD), [点火灯](https://github.com/Lightning-AI/pytorch-lightning), [海德拉语Name](https://github.com/facebookresearch/hydra), [闪电海德拉模板](https://github.com/ashleve/lightning-hydra-template), [RL 奔驰](https://github.com/stepjam/RLBench), [PerAct](https://github.com/peract/peract), [LIBERO](https://github.com/Lifelong-Robot-Learning/LIBERO), [梅塔- 沃尔德](https://github.com/Farama-Foundation/Metaworld), [ACT](https://github.com/tonyzhaozh/act), [传播政策](https://github.com/real-stanford/diffusion_policy), [DP3](https://github.com/YanjieZe/3D-Diffusion-Policy), [TIMM](https://github.com/huggingface/pytorch-image-models), [VC1](https://github.com/facebookresearch/eai-vc), [R3M](https://github.com/facebookresearch/r3m)我们感谢所有这些作者慷慨解囊的开放源代码及其对社区的重大贡献。 联系人 [朱孝义](https://www.haoyizhu.site/) 如果你有任何问题或建议。 ## : pencil: 引用 ```bib @article{zhu2024spa, title = {SPA: 3D Spatial-Awareness Enables Effective Embodied Representation}, author = {Zhu, Haoyi and and Yang, Honghui and Wang, Yating and Yang, Jiange and Wang, Limin and He, Tong}, journal = {arXiv preprint arxiv:2410.08208}, year = {2024}, } ```

查看原始来源