Changesets · Branches · Tags · Compare
| Changeset | 8363059ddafe9d4b8c345a4564ae49f65fe26bad3aca9f020a32a0577e4b281f |
|---|---|
| Author | Yongsen Mao <sammaoys@gmail.com> · 2025-03-17 12:04 +08:00 |
| Committer | Yongsen Mao <sammaoys@gmail.com> · 2025-03-17 12:04 +08:00 |
| Parents | None: the first changeset |
22 files changed
added .gitignore +168 −0
| @@ -0,0 +1,168 @@ | ||
| 1 | +# Byte-compiled / optimized / DLL files | |
| 2 | +__pycache__/ | |
| 3 | +*.py[cod] | |
| 4 | +*$py.class | |
| 5 | + | |
| 6 | +# C extensions | |
| 7 | +*.so | |
| 8 | + | |
| 9 | +# Distribution / packaging | |
| 10 | +.Python | |
| 11 | +build/ | |
| 12 | +develop-eggs/ | |
| 13 | +dist/ | |
| 14 | +downloads/ | |
| 15 | +eggs/ | |
| 16 | +.eggs/ | |
| 17 | +lib/ | |
| 18 | +lib64/ | |
| 19 | +parts/ | |
| 20 | +sdist/ | |
| 21 | +var/ | |
| 22 | +wheels/ | |
| 23 | +share/python-wheels/ | |
| 24 | +*.egg-info/ | |
| 25 | +.installed.cfg | |
| 26 | +*.egg | |
| 27 | +MANIFEST | |
| 28 | + | |
| 29 | +# PyInstaller | |
| 30 | +# Usually these files are written by a python script from a template | |
| 31 | +# before PyInstaller builds the exe, so as to inject date/other infos into it. | |
| 32 | +*.manifest | |
| 33 | +*.spec | |
| 34 | + | |
| 35 | +# Installer logs | |
| 36 | +pip-log.txt | |
| 37 | +pip-delete-this-directory.txt | |
| 38 | + | |
| 39 | +# Unit test / coverage reports | |
| 40 | +htmlcov/ | |
| 41 | +.tox/ | |
| 42 | +.nox/ | |
| 43 | +.coverage | |
| 44 | +.coverage.* | |
| 45 | +.cache | |
| 46 | +nosetests.xml | |
| 47 | +coverage.xml | |
| 48 | +*.cover | |
| 49 | +*.py,cover | |
| 50 | +.hypothesis/ | |
| 51 | +.pytest_cache/ | |
| 52 | +cover/ | |
| 53 | + | |
| 54 | +# Translations | |
| 55 | +*.mo | |
| 56 | +*.pot | |
| 57 | + | |
| 58 | +# Django stuff: | |
| 59 | +*.log | |
| 60 | +local_settings.py | |
| 61 | +db.sqlite3 | |
| 62 | +db.sqlite3-journal | |
| 63 | + | |
| 64 | +# Flask stuff: | |
| 65 | +instance/ | |
| 66 | +.webassets-cache | |
| 67 | + | |
| 68 | +# Scrapy stuff: | |
| 69 | +.scrapy | |
| 70 | + | |
| 71 | +# Sphinx documentation | |
| 72 | +docs/_build/ | |
| 73 | + | |
| 74 | +# PyBuilder | |
| 75 | +.pybuilder/ | |
| 76 | +target/ | |
| 77 | + | |
| 78 | +# Jupyter Notebook | |
| 79 | +.ipynb_checkpoints | |
| 80 | + | |
| 81 | +# IPython | |
| 82 | +profile_default/ | |
| 83 | +ipython_config.py | |
| 84 | + | |
| 85 | +# pyenv | |
| 86 | +# For a library or package, you might want to ignore these files since the code is | |
| 87 | +# intended to run in multiple environments; otherwise, check them in: | |
| 88 | +# .python-version | |
| 89 | + | |
| 90 | +# pipenv | |
| 91 | +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. | |
| 92 | +# However, in case of collaboration, if having platform-specific dependencies or dependencies | |
| 93 | +# having no cross-platform support, pipenv may install dependencies that don't work, or not | |
| 94 | +# install all needed dependencies. | |
| 95 | +#Pipfile.lock | |
| 96 | + | |
| 97 | +# poetry | |
| 98 | +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. | |
| 99 | +# This is especially recommended for binary packages to ensure reproducibility, and is more | |
| 100 | +# commonly ignored for libraries. | |
| 101 | +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control | |
| 102 | +#poetry.lock | |
| 103 | + | |
| 104 | +# pdm | |
| 105 | +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. | |
| 106 | +#pdm.lock | |
| 107 | +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it | |
| 108 | +# in version control. | |
| 109 | +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control | |
| 110 | +.pdm.toml | |
| 111 | +.pdm-python | |
| 112 | +.pdm-build/ | |
| 113 | + | |
| 114 | +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm | |
| 115 | +__pypackages__/ | |
| 116 | + | |
| 117 | +# Celery stuff | |
| 118 | +celerybeat-schedule | |
| 119 | +celerybeat.pid | |
| 120 | + | |
| 121 | +# SageMath parsed files | |
| 122 | +*.sage.py | |
| 123 | + | |
| 124 | +# Environments | |
| 125 | +.env | |
| 126 | +.venv | |
| 127 | +env/ | |
| 128 | +venv/ | |
| 129 | +ENV/ | |
| 130 | +env.bak/ | |
| 131 | +venv.bak/ | |
| 132 | + | |
| 133 | +# Spyder project settings | |
| 134 | +.spyderproject | |
| 135 | +.spyproject | |
| 136 | + | |
| 137 | +# Rope project settings | |
| 138 | +.ropeproject | |
| 139 | + | |
| 140 | +# mkdocs documentation | |
| 141 | +/site | |
| 142 | + | |
| 143 | +# mypy | |
| 144 | +.mypy_cache/ | |
| 145 | +.dmypy.json | |
| 146 | +dmypy.json | |
| 147 | + | |
| 148 | +# Pyre type checker | |
| 149 | +.pyre/ | |
| 150 | + | |
| 151 | +# pytype static type analyzer | |
| 152 | +.pytype/ | |
| 153 | + | |
| 154 | +# Cython debug symbols | |
| 155 | +cython_debug/ | |
| 156 | + | |
| 157 | +# PyCharm | |
| 158 | +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can | |
| 159 | +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore | |
| 160 | +# and can be added to the global gitignore or merged into this file. For a more nuclear | |
| 161 | +# option (not recommended) you can uncomment the following to ignore the entire idea folder. | |
| 162 | +#.idea/ | |
| 163 | + | |
| 164 | +# Output files | |
| 165 | +*.lock | |
| 166 | +*.txt | |
| 167 | +*.rrd | |
| 168 | +*.ply | |
| No newline at the end of the file |
added LICENSE.txt +111 −0
| @@ -0,0 +1,111 @@ | ||
| 1 | +LLAMA 3.2 COMMUNITY LICENSE AGREEMENT | |
| 2 | +Llama 3.2 Version Release Date: September 25, 2024 | |
| 3 | + | |
| 4 | +“Agreement” means the terms and conditions for use, reproduction, distribution | |
| 5 | +and modification of the Llama Materials set forth herein. | |
| 6 | + | |
| 7 | +“Documentation” means the specifications, manuals and documentation accompanying Llama 3.2 | |
| 8 | +distributed by Meta at https://llama.meta.com/doc/overview. | |
| 9 | + | |
| 10 | +“Licensee” or “you” means you, or your employer or any other person or entity (if you are | |
| 11 | +entering into this Agreement on such person or entity’s behalf), of the age required under | |
| 12 | +applicable laws, rules or regulations to provide legal consent and that has legal authority | |
| 13 | +to bind your employer or such other person or entity if you are entering in this Agreement | |
| 14 | +on their behalf. | |
| 15 | + | |
| 16 | +“Llama 3.2” means the foundational large language models and software and algorithms, including | |
| 17 | +machine-learning model code, trained model weights, inference-enabling code, training-enabling code, | |
| 18 | +fine-tuning enabling code and other elements of the foregoing distributed by Meta at | |
| 19 | +https://www.llama.com/llama-downloads. | |
| 20 | + | |
| 21 | +“Llama Materials” means, collectively, Meta’s proprietary Llama 3.2 and Documentation (and | |
| 22 | +any portion thereof) made available under this Agreement. | |
| 23 | + | |
| 24 | +“Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, | |
| 25 | +if you are an entity, your principal place of business is in the EEA or Switzerland) | |
| 26 | +and Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland). | |
| 27 | + | |
| 28 | + | |
| 29 | +By clicking “I Accept” below or by using or distributing any portion or element of the Llama Materials, | |
| 30 | +you agree to be bound by this Agreement. | |
| 31 | + | |
| 32 | + | |
| 33 | +1. License Rights and Redistribution. | |
| 34 | + | |
| 35 | + a. Grant of Rights. You are granted a non-exclusive, worldwide, | |
| 36 | +non-transferable and royalty-free limited license under Meta’s intellectual property or other rights | |
| 37 | +owned by Meta embodied in the Llama Materials to use, reproduce, distribute, copy, create derivative works | |
| 38 | +of, and make modifications to the Llama Materials. | |
| 39 | + | |
| 40 | + b. Redistribution and Use. | |
| 41 | + | |
| 42 | + i. If you distribute or make available the Llama Materials (or any derivative works thereof), | |
| 43 | +or a product or service (including another AI model) that contains any of them, you shall (A) provide | |
| 44 | +a copy of this Agreement with any such Llama Materials; and (B) prominently display “Built with Llama” | |
| 45 | +on a related website, user interface, blogpost, about page, or product documentation. If you use the | |
| 46 | +Llama Materials or any outputs or results of the Llama Materials to create, train, fine tune, or | |
| 47 | +otherwise improve an AI model, which is distributed or made available, you shall also include “Llama” | |
| 48 | +at the beginning of any such AI model name. | |
| 49 | + | |
| 50 | + ii. If you receive Llama Materials, or any derivative works thereof, from a Licensee as part | |
| 51 | +of an integrated end user product, then Section 2 of this Agreement will not apply to you. | |
| 52 | + | |
| 53 | + iii. You must retain in all copies of the Llama Materials that you distribute the | |
| 54 | +following attribution notice within a “Notice” text file distributed as a part of such copies: | |
| 55 | +“Llama 3.2 is licensed under the Llama 3.2 Community License, Copyright © Meta Platforms, | |
| 56 | +Inc. All Rights Reserved.” | |
| 57 | + | |
| 58 | + iv. Your use of the Llama Materials must comply with applicable laws and regulations | |
| 59 | +(including trade compliance laws and regulations) and adhere to the Acceptable Use Policy for | |
| 60 | +the Llama Materials (available at https://www.llama.com/llama3_2/use-policy), which is hereby | |
| 61 | +incorporated by reference into this Agreement. | |
| 62 | + | |
| 63 | +2. Additional Commercial Terms. If, on the Llama 3.2 version release date, the monthly active users | |
| 64 | +of the products or services made available by or for Licensee, or Licensee’s affiliates, | |
| 65 | +is greater than 700 million monthly active users in the preceding calendar month, you must request | |
| 66 | +a license from Meta, which Meta may grant to you in its sole discretion, and you are not authorized to | |
| 67 | +exercise any of the rights under this Agreement unless or until Meta otherwise expressly grants you such rights. | |
| 68 | + | |
| 69 | +3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE LLAMA MATERIALS AND ANY OUTPUT AND | |
| 70 | +RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS | |
| 71 | +ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES | |
| 72 | +OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE | |
| 73 | +FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE LLAMA MATERIALS AND ASSUME ANY RISKS ASSOCIATED | |
| 74 | +WITH YOUR USE OF THE LLAMA MATERIALS AND ANY OUTPUT AND RESULTS. | |
| 75 | + | |
| 76 | +4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, | |
| 77 | +WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, | |
| 78 | +FOR ANY LOST PROFITS OR ANY INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN | |
| 79 | +IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING. | |
| 80 | + | |
| 81 | +5. Intellectual Property. | |
| 82 | + | |
| 83 | + a. No trademark licenses are granted under this Agreement, and in connection with the Llama Materials, | |
| 84 | +neither Meta nor Licensee may use any name or mark owned by or associated with the other or any of its affiliates, | |
| 85 | +except as required for reasonable and customary use in describing and redistributing the Llama Materials or as | |
| 86 | +set forth in this Section 5(a). Meta hereby grants you a license to use “Llama” (the “Mark”) solely as required | |
| 87 | +to comply with the last sentence of Section 1.b.i. You will comply with Meta’s brand guidelines (currently accessible | |
| 88 | +at https://about.meta.com/brand/resources/meta/company-brand/). All goodwill arising out of your use of the Mark | |
| 89 | +will inure to the benefit of Meta. | |
| 90 | + | |
| 91 | + b. Subject to Meta’s ownership of Llama Materials and derivatives made by or for Meta, with respect to any | |
| 92 | + derivative works and modifications of the Llama Materials that are made by you, as between you and Meta, | |
| 93 | + you are and will be the owner of such derivative works and modifications. | |
| 94 | + | |
| 95 | + c. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or | |
| 96 | + counterclaim in a lawsuit) alleging that the Llama Materials or Llama 3.2 outputs or results, or any portion | |
| 97 | + of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable | |
| 98 | + by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or | |
| 99 | + claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third | |
| 100 | + party arising out of or related to your use or distribution of the Llama Materials. | |
| 101 | + | |
| 102 | +6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access | |
| 103 | +to the Llama Materials and will continue in full force and effect until terminated in accordance with the terms | |
| 104 | +and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this | |
| 105 | +Agreement. Upon termination of this Agreement, you shall delete and cease use of the Llama Materials. Sections 3, | |
| 106 | +4 and 7 shall survive the termination of this Agreement. | |
| 107 | + | |
| 108 | +7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of | |
| 109 | +California without regard to choice of law principles, and the UN Convention on Contracts for the International | |
| 110 | +Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of | |
| 111 | +any dispute arising out of this Agreement. | |
| No newline at the end of the file |
added README.md +192 −0
| @@ -0,0 +1,192 @@ | ||
| 1 | +# SpatialLM | |
| 2 | + | |
| 3 | +<!-- markdownlint-disable first-line-h1 --> | |
| 4 | +<!-- markdownlint-disable html --> | |
| 5 | +<!-- markdownlint-disable no-duplicate-header --> | |
| 6 | + | |
| 7 | +<div align="center"> | |
| 8 | + <img src="figures/logo_light.png#gh-light-mode-only" width="60%" alt="SpatialLM" /> | |
| 9 | + <img src="figures/logo_dark.png#gh-dark-mode-only" width="60%" alt="SpatialLM" /> | |
| 10 | +</div> | |
| 11 | +<hr style="margin-top: 0; margin-bottom: 8px;"> | |
| 12 | +<div align="center" style="margin-top: 0; padding-top: 0; line-height: 1;"> | |
| 13 | + <a href="https://manycore-research.github.io/SpatialLM" target="_blank" style="margin: 2px;"><img alt="Project" | |
| 14 | + src="https://img.shields.io/badge/🌐%20Website-SpatialLM-ffc107?color=42a5f5&logoColor=white" style="display: inline-block; vertical-align: middle;"/></a> | |
| 15 | + <a href="https://github.com/manycore-research/SpatialLM" target="_blank" style="margin: 2px;"><img alt="GitHub" | |
| 16 | + src="https://img.shields.io/badge/GitHub-SpatialLM-24292e?logo=github&logoColor=white" style="display: inline-block; vertical-align: middle;"/></a> | |
| 17 | +</div> | |
| 18 | +<div align="center" style="line-height: 1;"> | |
| 19 | + <a href="https://huggingface.co/manycore-research/SpatialLM-Llama-1B" target="_blank" style="margin: 2px;"><img alt="Hugging Face" | |
| 20 | + src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-SpatialLM%201B-ffc107?color=ffc107&logoColor=white" style="display: inline-block; vertical-align: middle;"/></a> | |
| 21 | + <a href="https://huggingface.co/datasets/manycore-research/SpatialLM-Testset" target="_blank" style="margin: 2px;"><img alt="Dataset" | |
| 22 | + src="https://img.shields.io/badge/%F0%9F%A4%97%20Dataset-SpatialLM-ffc107?color=ffc107&logoColor=white" style="display: inline-block; vertical-align: middle;"/></a> | |
| 23 | +</div> | |
| 24 | + | |
| 25 | +## Introduction | |
| 26 | + | |
| 27 | +SpatialLM is a 3D large language model designed to process 3D point cloud data and generate structured 3D scene understanding outputs. These outputs include architectural elements like walls, doors, windows, and oriented object bounding boxes with their semantic categories. Unlike previous methods that require specialized equipment for data collection, SpatialLM can handle point clouds from diverse sources such as monocular video sequences, RGBD images, and LiDAR sensors. This multimodal architecture effectively bridges the gap between unstructured 3D geometric data and structured 3D representations, offering high-level semantic understanding. It enhances spatial reasoning capabilities for applications in embodied robotics, autonomous navigation, and other complex 3D scene analysis tasks. | |
| 28 | + | |
| 29 | +<div align="center"> | |
| 30 | + <video src="https://github.com/user-attachments/assets/c0218d6a-f676-41f8-ae76-bba228866306" poster="figures/cover.png"> </video> | |
| 31 | +</div> | |
| 32 | + | |
| 33 | +## SpatialLM Models | |
| 34 | + | |
| 35 | +<div align="center"> | |
| 36 | + | |
| 37 | +| **Model** | **Download** | | |
| 38 | +| :-----------------: | ------------------------------------------------------------------------------ | | |
| 39 | +| SpatialLM-Llama-1B | [🤗 HuggingFace](https://huggingface.co/manycore-research/SpatialLM-Llama-1B) | | |
| 40 | +| SpatialLM-Qwen-0.5B | [🤗 HuggingFace](https://huggingface.co/manycore-research/SpatialLM-Qwen-0.5B) | | |
| 41 | + | |
| 42 | +</div> | |
| 43 | + | |
| 44 | +## Usage | |
| 45 | + | |
| 46 | +### Installation | |
| 47 | + | |
| 48 | +Tested with the following environment: | |
| 49 | + | |
| 50 | +- Python 3.11 | |
| 51 | +- Pytorch 2.4.1 | |
| 52 | +- CUDA Version 12.4 | |
| 53 | + | |
| 54 | +```bash | |
| 55 | +# clone the repository | |
| 56 | +git clone https://github.com/manycore-research/SpatialLM.git | |
| 57 | +cd SpatialLM | |
| 58 | + | |
| 59 | +# create a conda environment with cuda 12.4 | |
| 60 | +conda create -n spatiallm python=3.11 | |
| 61 | +conda activate spatiallm | |
| 62 | +conda install -y nvidia/label/cuda-12.4.0::cuda-toolkit conda-forge::sparsehash | |
| 63 | + | |
| 64 | +# Install dependencies with poetry | |
| 65 | +pip install poetry && poetry config virtualenvs.create false --local | |
| 66 | +poetry install | |
| 67 | +poe install-torchsparse # Building wheel for torchsparse will take a while | |
| 68 | +``` | |
| 69 | + | |
| 70 | +### Inference | |
| 71 | + | |
| 72 | +In the current version of SpatialLM, input point clouds are considered axis-aligned where the z-axis is the up axis. This orientation is crucial for maintaining consistency in spatial understanding and scene interpretation across different datasets and applications. | |
| 73 | +Example preprocessed point clouds, reconstructed from RGB videos using [MASt3R-SLAM](https://github.com/rmurai0610/MASt3R-SLAM), are available in [SpatialLM-Testset](#spatiallm-testset). | |
| 74 | + | |
| 75 | +Download an example point cloud: | |
| 76 | + | |
| 77 | +```bash | |
| 78 | +huggingface-cli download manycore-research/SpatialLM-Testset pcd/scene0000_00.ply --repo-type dataset --local-dir . | |
| 79 | +``` | |
| 80 | + | |
| 81 | +Run inference: | |
| 82 | + | |
| 83 | +```bash | |
| 84 | +python inference.py --point_cloud pcd/scene0000_00.ply --output scene0000_00.txt --model_path manycore-research/SpatialLM-Llama-1B | |
| 85 | +``` | |
| 86 | + | |
| 87 | +### Visualization | |
| 88 | + | |
| 89 | +Use `rerun` to visualize the point cloud and the predicted structured 3D layout output: | |
| 90 | + | |
| 91 | +```bash | |
| 92 | +# Convert the predicted layout to Rerun format | |
| 93 | +python visualize.py --point_cloud pcd/scene0000_00.ply --layout scene0000_00.txt --save scene0000_00.rrd | |
| 94 | + | |
| 95 | +# Visualize the point cloud and the predicted layout | |
| 96 | +rerun scene0000_00.rrd | |
| 97 | +``` | |
| 98 | + | |
| 99 | +### Evaluation | |
| 100 | + | |
| 101 | +To evaluate the performance of SpatialLM, we provide `eval.py` script that reports the benchmark results on the SpatialLM-Testset in the table below in section [Benchmark Results](#benchmark-results). | |
| 102 | + | |
| 103 | +Download the testset: | |
| 104 | + | |
| 105 | +```bash | |
| 106 | +huggingface-cli download manycore-research/SpatialLM-Testset --repo-type dataset --local-dir SpatialLM-Testset | |
| 107 | +``` | |
| 108 | + | |
| 109 | +Run evaluation: | |
| 110 | + | |
| 111 | +```bash | |
| 112 | +# Run inference on the PLY point clouds in folder SpatialLM-Testset/pcd with SpatialLM-Llama-1B model | |
| 113 | +python inference.py --point_cloud SpatialLM-Testset/pcd --output SpatialLM-Testset/pred --model_path manycore-research/SpatialLM-Llama-1B | |
| 114 | + | |
| 115 | +# Evaluate the predicted layouts | |
| 116 | +python eval.py --metadata SpatialLM-Testset/test.csv --gt_dir SpatialLM-Testset/layout --pred_dir SpatialLM-Testset/pred --label_mapping SpatialLM-Testset/benchmark_categories.tsv | |
| 117 | +``` | |
| 118 | + | |
| 119 | +## SpatialLM Testset | |
| 120 | + | |
| 121 | +We provide a test set of 107 preprocessed point clouds, reconstructed from RGB videos using [MASt3R-SLAM](https://github.com/rmurai0610/MASt3R-SLAM). SpatialLM-Testset is quite challenging compared to prior clean RGBD scans datasets due to the noises and occlusions in the point clouds reconstructed from monocular RGB videos. | |
| 122 | + | |
| 123 | +<div align="center"> | |
| 124 | + | |
| 125 | +| **Dataset** | **Download** | | |
| 126 | +| :---------------: | ---------------------------------------------------------------------------------- | | |
| 127 | +| SpatialLM-Testset | [🤗 Datasets](https://huggingface.co/datasets/manycore-research/SpatialLM-TestSet) | | |
| 128 | + | |
| 129 | +</div> | |
| 130 | + | |
| 131 | +## Benchmark Results | |
| 132 | + | |
| 133 | +Benchmark results on the challenging SpatialLM-Testset are reported in the following table: | |
| 134 | + | |
| 135 | +<div align="center"> | |
| 136 | + | |
| 137 | +| **Method** | **SpatialLM-Llama-1B** | **SpatialLM-Qwen-0.5B** | | |
| 138 | +| ---------------- | ---------------------- | ----------------------- | | |
| 139 | +| **Floorplan** | **mean IoU** | | | |
| 140 | +| wall | 78.62 | 74.81 | | |
| 141 | +| | | | | |
| 142 | +| **Objects** | **F1 @.25 IoU (3D)** | | | |
| 143 | +| curtain | 27.35 | 28.59 | | |
| 144 | +| nightstand | 57.47 | 54.39 | | |
| 145 | +| chandelier | 38.92 | 40.12 | | |
| 146 | +| wardrobe | 23.33 | 30.60 | | |
| 147 | +| bed | 95.24 | 93.75 | | |
| 148 | +| sofa | 65.50 | 66.15 | | |
| 149 | +| chair | 21.26 | 14.94 | | |
| 150 | +| cabinet | 8.47 | 8.44 | | |
| 151 | +| dining table | 54.26 | 56.10 | | |
| 152 | +| plants | 20.68 | 26.46 | | |
| 153 | +| tv cabinet | 33.33 | 10.26 | | |
| 154 | +| coffee table | 50.00 | 55.56 | | |
| 155 | +| side table | 7.60 | 2.17 | | |
| 156 | +| air conditioner | 20.00 | 13.04 | | |
| 157 | +| dresser | 46.67 | 23.53 | | |
| 158 | +| | | | | |
| 159 | +| **Thin Objects** | **F1 @.25 IoU (2D)** | | | |
| 160 | +| painting | 50.04 | 53.81 | | |
| 161 | +| carpet | 31.76 | 45.31 | | |
| 162 | +| tv | 67.31 | 52.29 | | |
| 163 | +| door | 50.35 | 42.15 | | |
| 164 | +| window | 45.4 | 45.9 | | |
| 165 | + | |
| 166 | +</div> | |
| 167 | + | |
| 168 | +## License | |
| 169 | + | |
| 170 | +SpatialLM-Llama-1B is derived from Llama3.2-1B-Instruct, which is licensed under the Llama3.2 license. | |
| 171 | +SpatialLM-Qwen-0.5B is derived from the Qwen-2.5 series, originally licensed under the Apache 2.0 License. | |
| 172 | + | |
| 173 | +All models are built upon the SceneScript point cloud encoder, licensed under the CC-BY-NC-4.0 License. TorchSparse, utilized in this project, is licensed under the MIT License. | |
| 174 | + | |
| 175 | +## Citation | |
| 176 | + | |
| 177 | +If you find this work useful, please consider citing: | |
| 178 | + | |
| 179 | +```bibtex | |
| 180 | +@misc{spatiallm, | |
| 181 | + title = {SpatialLM: Large Language Model for Spatial Understanding}, | |
| 182 | + author = {ManyCore Research Team}, | |
| 183 | + howpublished = {\url{https://github.com/manycore-research/SpatialLM}}, | |
| 184 | + year = {2025} | |
| 185 | +} | |
| 186 | +``` | |
| 187 | + | |
| 188 | +## Acknowledgements | |
| 189 | + | |
| 190 | +We would like to thank the following projects that made this work possible: | |
| 191 | + | |
| 192 | +[Llama3.2](https://github.com/meta-llama) | [Qwen2.5](https://github.com/QwenLM/Qwen2.5) | [Transformers](https://github.com/huggingface/transformers) | [SceneScript](https://github.com/facebookresearch/scenescript) | [TorchSparse](https://github.com/mit-han-lab/torchsparse) |
added code_template.txt +39 −0
| @@ -0,0 +1,39 @@ | ||
| 1 | +@dataclass | |
| 2 | +class Wall: | |
| 3 | + ax: int | |
| 4 | + ay: int | |
| 5 | + az: int | |
| 6 | + bx: int | |
| 7 | + by: int | |
| 8 | + bz: int | |
| 9 | + height: int | |
| 10 | + thickness: int | |
| 11 | + | |
| 12 | +@dataclass | |
| 13 | +class Door: | |
| 14 | + wall_id: str | |
| 15 | + position_x: int | |
| 16 | + position_y: int | |
| 17 | + position_z: int | |
| 18 | + width: int | |
| 19 | + height: int | |
| 20 | + | |
| 21 | +@dataclass | |
| 22 | +class Window: | |
| 23 | + wall_id: str | |
| 24 | + position_x: int | |
| 25 | + position_y: int | |
| 26 | + position_z: int | |
| 27 | + width: int | |
| 28 | + height: int | |
| 29 | + | |
| 30 | +@dataclass | |
| 31 | +class Bbox: | |
| 32 | + class: str | |
| 33 | + position_x: int | |
| 34 | + position_y: int | |
| 35 | + position_z: int | |
| 36 | + angle_z: int | |
| 37 | + scale_x: int | |
| 38 | + scale_y: int | |
| 39 | + scale_z: int | |
| No newline at the end of the file |
added eval.py +510 −0
| @@ -0,0 +1,510 @@ | ||
| 1 | +import os | |
| 2 | +import argparse | |
| 3 | +import math | |
| 4 | +import csv | |
| 5 | +import itertools | |
| 6 | +import logging | |
| 7 | +from typing import Dict, List | |
| 8 | +from collections import defaultdict | |
| 9 | +from dataclasses import dataclass | |
| 10 | + | |
| 11 | +import torch | |
| 12 | +import pandas as pd | |
| 13 | +import numpy as np | |
| 14 | +from scipy.optimize import linear_sum_assignment | |
| 15 | +from shapely import Polygon, LineString, polygonize, polygonize_full, make_valid | |
| 16 | +from bbox import BBox3D | |
| 17 | +from bbox.metrics import iou_3d | |
| 18 | +from terminaltables import AsciiTable | |
| 19 | + | |
| 20 | +from spatiallm import Layout | |
| 21 | +from spatiallm.layout.entity import Wall, Door, Window, Bbox | |
| 22 | + | |
| 23 | +log = logging.getLogger(__name__) | |
| 24 | + | |
| 25 | +ZERO_TOLERANCE = 1e-6 | |
| 26 | +LARGE_COST_VALUE = 1e6 | |
| 27 | +OBJECTS = [ | |
| 28 | + "curtain", | |
| 29 | + "nightstand", | |
| 30 | + "chandelier", | |
| 31 | + "wardrobe", | |
| 32 | + "bed", | |
| 33 | + "sofa", | |
| 34 | + "chair", | |
| 35 | + "cabinet", | |
| 36 | + "dining table", | |
| 37 | + "plants", | |
| 38 | + "tv cabinet", | |
| 39 | + "coffee table", | |
| 40 | + "side table", | |
| 41 | + "air conditioner", | |
| 42 | + "dresser", | |
| 43 | +] | |
| 44 | +THIN_OBJECTS = [ | |
| 45 | + "painting", | |
| 46 | + "carpet", | |
| 47 | + "tv", | |
| 48 | + "door", | |
| 49 | + "window", | |
| 50 | +] | |
| 51 | + | |
| 52 | + | |
| 53 | +@dataclass | |
| 54 | +class EvalTuple: | |
| 55 | + tp: int | |
| 56 | + num_pred: int | |
| 57 | + num_gt: int | |
| 58 | + | |
| 59 | + @property | |
| 60 | + def precision(self): | |
| 61 | + return self.tp / self.num_pred if self.num_pred > 0 else 0 | |
| 62 | + | |
| 63 | + @property | |
| 64 | + def recall(self): | |
| 65 | + return self.tp / self.num_gt if self.num_gt > 0 else 0 | |
| 66 | + | |
| 67 | + @property | |
| 68 | + def f1(self): | |
| 69 | + return ( | |
| 70 | + (2 * self.precision * self.recall) / (self.precision + self.recall) | |
| 71 | + if (self.precision + self.recall) > 0 | |
| 72 | + else 0 | |
| 73 | + ) | |
| 74 | + | |
| 75 | + @property | |
| 76 | + def masked(self): | |
| 77 | + return self.num_pred == 0 and self.num_gt == 0 | |
| 78 | + | |
| 79 | + | |
| 80 | +def calc_poly_iou(poly1, poly2): | |
| 81 | + if poly1.intersects(poly2): | |
| 82 | + inter_area = poly1.intersection(poly2).area | |
| 83 | + union_area = poly1.union(poly2).area | |
| 84 | + poly_iou = inter_area / union_area if union_area > 0 else 0 | |
| 85 | + else: | |
| 86 | + poly_iou = 0 | |
| 87 | + return poly_iou | |
| 88 | + | |
| 89 | + | |
| 90 | +def construct_polygon(lines: List[LineString]): | |
| 91 | + try: | |
| 92 | + poly = polygonize(lines) | |
| 93 | + if poly.is_empty: | |
| 94 | + candidates = [] | |
| 95 | + for p in polygonize_full(lines): | |
| 96 | + if p.is_empty: | |
| 97 | + continue | |
| 98 | + | |
| 99 | + candidate = p.geoms[0] | |
| 100 | + if isinstance(candidate, Polygon): | |
| 101 | + candidates.append(candidate) | |
| 102 | + elif isinstance(candidate, LineString): | |
| 103 | + candidates.append(Polygon(candidate)) | |
| 104 | + else: | |
| 105 | + log.warning( | |
| 106 | + f"Unsupported geom_type {candidate.geom_type} to construct polygon." | |
| 107 | + ) | |
| 108 | + | |
| 109 | + candidates.sort(key=lambda x: x.area, reverse=True) | |
| 110 | + poly = candidates[0] | |
| 111 | + if not poly.is_valid: | |
| 112 | + poly = make_valid(poly) | |
| 113 | + return poly | |
| 114 | + except Exception as e: | |
| 115 | + log.error(f"Fail to construct polygon by lines {lines}", e) | |
| 116 | + return Polygon() | |
| 117 | + | |
| 118 | + | |
| 119 | +def read_label_mapping( | |
| 120 | + label_path: str, label_from="spatiallm59", label_to="spatiallm18" | |
| 121 | +): | |
| 122 | + assert os.path.isfile(label_path), f"Label mapping file {label_path} does not exist" | |
| 123 | + mapping = dict() | |
| 124 | + with open(label_path) as csvfile: | |
| 125 | + reader = csv.DictReader(csvfile, delimiter="\t") | |
| 126 | + for row in reader: | |
| 127 | + label_from_value = row[label_from] | |
| 128 | + label_to_value = row[label_to] | |
| 129 | + if label_from_value == "" or label_to_value == "": | |
| 130 | + continue | |
| 131 | + mapping[label_from_value] = label_to_value | |
| 132 | + return mapping | |
| 133 | + | |
| 134 | + | |
| 135 | +def assign_class_map(entities: List[Bbox], class_map=Dict[str, str]): | |
| 136 | + res_entities = list() | |
| 137 | + for entity in entities: | |
| 138 | + mapping_to_class = class_map.get(entity.class_name.replace("_", " ")) | |
| 139 | + if mapping_to_class: | |
| 140 | + entity.class_name = mapping_to_class | |
| 141 | + res_entities.append(entity) | |
| 142 | + return res_entities | |
| 143 | + | |
| 144 | + | |
| 145 | +def get_entity_class(entity): | |
| 146 | + try: | |
| 147 | + return entity.class_name | |
| 148 | + except: | |
| 149 | + return entity.entity_label | |
| 150 | + | |
| 151 | + | |
| 152 | +def get_BBox3D(entity: Bbox): | |
| 153 | + return BBox3D( | |
| 154 | + entity.position_x, | |
| 155 | + entity.position_y, | |
| 156 | + entity.position_z, | |
| 157 | + entity.scale_x, | |
| 158 | + entity.scale_y, | |
| 159 | + entity.scale_z, | |
| 160 | + euler_angles=[0, 0, entity.angle_z], | |
| 161 | + is_center=True, | |
| 162 | + ) | |
| 163 | + | |
| 164 | + | |
| 165 | +def calc_bbox_tp( | |
| 166 | + pred_entities: List[Bbox], gt_entities: List[Bbox], iou_threshold: float = 0.25 | |
| 167 | +): | |
| 168 | + num_pred = len(pred_entities) | |
| 169 | + num_gt = len(gt_entities) | |
| 170 | + if num_pred == 0 or num_gt == 0: | |
| 171 | + return EvalTuple(0, num_pred, num_gt) | |
| 172 | + | |
| 173 | + iou_matrix = torch.as_tensor( | |
| 174 | + [ | |
| 175 | + iou_3d(bbox_1, bbox_2) | |
| 176 | + for bbox_1, bbox_2 in itertools.product( | |
| 177 | + [get_BBox3D(entity) for entity in pred_entities], | |
| 178 | + [get_BBox3D(entity) for entity in gt_entities], | |
| 179 | + ) | |
| 180 | + ] | |
| 181 | + ).resize(num_pred, num_gt) | |
| 182 | + | |
| 183 | + cost_matrix = torch.full((num_pred, num_gt), LARGE_COST_VALUE) | |
| 184 | + cost_matrix[iou_matrix > iou_threshold] = -1 | |
| 185 | + | |
| 186 | + indices = linear_sum_assignment(cost_matrix.numpy()) | |
| 187 | + | |
| 188 | + tp_percent = iou_matrix[ | |
| 189 | + torch.as_tensor(indices[0], dtype=torch.int64), | |
| 190 | + torch.as_tensor(indices[1], dtype=torch.int64), | |
| 191 | + ] | |
| 192 | + tp = torch.sum(tp_percent >= iou_threshold).item() | |
| 193 | + | |
| 194 | + return EvalTuple(tp, num_pred, num_gt) | |
| 195 | + | |
| 196 | + | |
| 197 | +def is_valid_dw(entity: Door | Window, wall_id_lookup: Dict[int, Wall]): | |
| 198 | + attach_wall = wall_id_lookup.get(entity.id, None) | |
| 199 | + if attach_wall is None: | |
| 200 | + return False | |
| 201 | + | |
| 202 | + wall_extent_x = max( | |
| 203 | + max(attach_wall.ax, attach_wall.bx) - min(attach_wall.ax, attach_wall.bx), 0 | |
| 204 | + ) | |
| 205 | + wall_extent_y = max( | |
| 206 | + max(attach_wall.ay, attach_wall.by) - min(attach_wall.ay, attach_wall.by), 0 | |
| 207 | + ) | |
| 208 | + return wall_extent_x > ZERO_TOLERANCE or wall_extent_y > ZERO_TOLERANCE | |
| 209 | + | |
| 210 | + | |
| 211 | +def get_corners(entity: Door | Window | Bbox, wall_id_lookup: Dict[int, Wall]): | |
| 212 | + if isinstance(entity, (Door, Window)): | |
| 213 | + attach_wall = wall_id_lookup.get(entity.id, None) | |
| 214 | + if attach_wall is None: | |
| 215 | + log.error(f"{entity} attach wall is None") | |
| 216 | + return | |
| 217 | + | |
| 218 | + wall_start = np.array([attach_wall.ax, attach_wall.ay]) | |
| 219 | + wall_end = np.array([attach_wall.bx, attach_wall.by]) | |
| 220 | + wall_length = np.linalg.norm(wall_end - wall_start) | |
| 221 | + wall_xy_unit_vec = (wall_end - wall_start) / wall_length | |
| 222 | + wall_xy_unit_vec = np.nan_to_num(wall_xy_unit_vec, nan=0) | |
| 223 | + | |
| 224 | + door_center = np.array( | |
| 225 | + [entity.position_x, entity.position_y, entity.position_z] | |
| 226 | + ) | |
| 227 | + offset = 0.5 * np.concatenate( | |
| 228 | + [wall_xy_unit_vec * entity.width, np.array([entity.height])] | |
| 229 | + ) | |
| 230 | + door_start_xyz = door_center - offset | |
| 231 | + door_end_xyz = door_center + offset | |
| 232 | + | |
| 233 | + return np.array( | |
| 234 | + [ | |
| 235 | + [door_start_xyz[0], door_start_xyz[1], door_start_xyz[2]], | |
| 236 | + [door_end_xyz[0], door_end_xyz[1], door_start_xyz[2]], | |
| 237 | + [door_end_xyz[0], door_end_xyz[1], door_end_xyz[2]], | |
| 238 | + [door_start_xyz[0], door_start_xyz[1], door_end_xyz[2]], | |
| 239 | + ] | |
| 240 | + ) | |
| 241 | + elif isinstance(entity, Bbox): | |
| 242 | + bbox_points = get_BBox3D(entity).p | |
| 243 | + scale_key = ["scale_x", "scale_y", "scale_z"] | |
| 244 | + match min(scale_key, key=lambda k: abs(getattr(entity, k))): | |
| 245 | + case "scale_x": | |
| 246 | + return np.array( | |
| 247 | + [ | |
| 248 | + (bbox_points[0] + bbox_points[1]) / 2, | |
| 249 | + (bbox_points[2] + bbox_points[3]) / 2, | |
| 250 | + (bbox_points[6] + bbox_points[7]) / 2, | |
| 251 | + (bbox_points[4] + bbox_points[5]) / 2, | |
| 252 | + ] | |
| 253 | + ) | |
| 254 | + case "scale_y": | |
| 255 | + return np.array( | |
| 256 | + [ | |
| 257 | + (bbox_points[0] + bbox_points[3]) / 2, | |
| 258 | + (bbox_points[4] + bbox_points[7]) / 2, | |
| 259 | + (bbox_points[5] + bbox_points[6]) / 2, | |
| 260 | + (bbox_points[1] + bbox_points[2]) / 2, | |
| 261 | + ] | |
| 262 | + ) | |
| 263 | + case "scale_z": | |
| 264 | + return np.array( | |
| 265 | + [ | |
| 266 | + (bbox_points[0] + bbox_points[4]) / 2, | |
| 267 | + (bbox_points[1] + bbox_points[5]) / 2, | |
| 268 | + (bbox_points[2] + bbox_points[6]) / 2, | |
| 269 | + (bbox_points[3] + bbox_points[7]) / 2, | |
| 270 | + ] | |
| 271 | + ) | |
| 272 | + case _: | |
| 273 | + log.error(f"Unrecognized named attribute for {entity} in get_corners") | |
| 274 | + return | |
| 275 | + | |
| 276 | + | |
| 277 | +def are_planes_parallel_and_close( | |
| 278 | + corners_1: np.ndarray, | |
| 279 | + corners_2: np.ndarray, | |
| 280 | + parallel_tolerance: float, | |
| 281 | + dist_tolerance: float, | |
| 282 | +): | |
| 283 | + p1, p2, p3, _ = corners_1 | |
| 284 | + q1, q2, q3, _ = corners_2 | |
| 285 | + n1 = np.cross(np.subtract(p2, p1), np.subtract(p3, p1)) | |
| 286 | + n2 = np.cross(np.subtract(q2, q1), np.subtract(q3, q1)) | |
| 287 | + n1_length = np.linalg.norm(n1) | |
| 288 | + n2_length = np.linalg.norm(n2) | |
| 289 | + assert ( | |
| 290 | + n1_length * n2_length > ZERO_TOLERANCE | |
| 291 | + ), f"Invalid plane corners, corners_1: {corners_1}, corners_2: {corners_2}" | |
| 292 | + | |
| 293 | + return ( | |
| 294 | + np.linalg.norm(np.cross(n1, n2)) / (n1_length * n2_length) < parallel_tolerance | |
| 295 | + and np.dot(np.subtract(q1, p1), n1) / n1_length < dist_tolerance | |
| 296 | + ) | |
| 297 | + | |
| 298 | + | |
| 299 | +def calc_thin_bbox_iou_2d( | |
| 300 | + corners_1: np.ndarray, | |
| 301 | + corners_2: np.ndarray, | |
| 302 | + parallel_tolerance: float, | |
| 303 | + dist_tolerance: float, | |
| 304 | +): | |
| 305 | + if are_planes_parallel_and_close( | |
| 306 | + corners_1, corners_2, parallel_tolerance, dist_tolerance | |
| 307 | + ): | |
| 308 | + p1, p2, _, p4 = corners_1 | |
| 309 | + v1 = np.subtract(p2, p1) | |
| 310 | + v2 = np.subtract(p4, p1) | |
| 311 | + basis1 = v1 / np.linalg.norm(v1) | |
| 312 | + basis1_orth = v2 - np.dot(v2, basis1) * basis1 | |
| 313 | + basis2 = basis1_orth / np.linalg.norm(basis1_orth) | |
| 314 | + | |
| 315 | + projected_corners_1 = [ | |
| 316 | + [ | |
| 317 | + np.dot(np.subtract(point, p1), basis1), | |
| 318 | + np.dot(np.subtract(point, p1), basis2), | |
| 319 | + ] | |
| 320 | + for point in corners_1 | |
| 321 | + ] | |
| 322 | + projected_corners_2 = [ | |
| 323 | + [ | |
| 324 | + np.dot(np.subtract(point, p1), basis1), | |
| 325 | + np.dot(np.subtract(point, p1), basis2), | |
| 326 | + ] | |
| 327 | + for point in corners_2 | |
| 328 | + ] | |
| 329 | + box1 = Polygon(projected_corners_1) | |
| 330 | + box2 = Polygon(projected_corners_2) | |
| 331 | + | |
| 332 | + return calc_poly_iou(box1, box2) | |
| 333 | + else: | |
| 334 | + return 0 | |
| 335 | + | |
| 336 | + | |
| 337 | +def calc_thin_bbox_tp( | |
| 338 | + pred_entities: List[Door | Window | Bbox], | |
| 339 | + gt_entities: List[Door | Window | Bbox], | |
| 340 | + pred_wall_id_lookup: Dict[int, Wall], | |
| 341 | + gt_wall_id_lookup: Dict[int, Wall], | |
| 342 | + iou_threshold: float = 0.25, | |
| 343 | + parallel_tolerance: float = math.sin(math.radians(5)), | |
| 344 | + dist_tolerance: float = 0.2, | |
| 345 | +): | |
| 346 | + num_pred = len(pred_entities) | |
| 347 | + num_gt = len(gt_entities) | |
| 348 | + if num_pred == 0 or num_gt == 0: | |
| 349 | + return EvalTuple(0, num_pred, num_gt) | |
| 350 | + | |
| 351 | + iou_matrix = torch.as_tensor( | |
| 352 | + [ | |
| 353 | + calc_thin_bbox_iou_2d( | |
| 354 | + corners_1, corners_2, parallel_tolerance, dist_tolerance | |
| 355 | + ) | |
| 356 | + for corners_1, corners_2 in itertools.product( | |
| 357 | + [get_corners(entity, pred_wall_id_lookup) for entity in pred_entities], | |
| 358 | + [get_corners(entity, gt_wall_id_lookup) for entity in gt_entities], | |
| 359 | + ) | |
| 360 | + ] | |
| 361 | + ).resize(num_pred, num_gt) | |
| 362 | + | |
| 363 | + cost_matrix = torch.full((num_pred, num_gt), LARGE_COST_VALUE) | |
| 364 | + cost_matrix[iou_matrix > iou_threshold] = -1 | |
| 365 | + | |
| 366 | + indices = linear_sum_assignment(cost_matrix.numpy()) | |
| 367 | + | |
| 368 | + tp_percent = iou_matrix[ | |
| 369 | + torch.as_tensor(indices[0], dtype=torch.int64), | |
| 370 | + torch.as_tensor(indices[1], dtype=torch.int64), | |
| 371 | + ] | |
| 372 | + tp = torch.sum(tp_percent >= iou_threshold).item() | |
| 373 | + | |
| 374 | + return EvalTuple(tp, num_pred, num_gt) | |
| 375 | + | |
| 376 | + | |
| 377 | +if __name__ == "__main__": | |
| 378 | + parser = argparse.ArgumentParser("SpatialLM evaluation script") | |
| 379 | + parser.add_argument( | |
| 380 | + "--metadata", | |
| 381 | + type=str, | |
| 382 | + required=True, | |
| 383 | + help="metadata CSV file with columns id, pcd, layout", | |
| 384 | + ) | |
| 385 | + parser.add_argument( | |
| 386 | + "--gt_dir", | |
| 387 | + type=str, | |
| 388 | + required=True, | |
| 389 | + help="Path to the gt layout txt directory", | |
| 390 | + ) | |
| 391 | + parser.add_argument( | |
| 392 | + "--pred_dir", | |
| 393 | + type=str, | |
| 394 | + required=True, | |
| 395 | + help="Path to the pred layout txt directory", | |
| 396 | + ) | |
| 397 | + parser.add_argument( | |
| 398 | + "--label_mapping", | |
| 399 | + type=str, | |
| 400 | + required=True, | |
| 401 | + help="Path to the label mapping file", | |
| 402 | + ) | |
| 403 | + args = parser.parse_args() | |
| 404 | + | |
| 405 | + df = pd.read_csv(args.metadata) | |
| 406 | + scene_id_list = df["id"].tolist() | |
| 407 | + class_map = read_label_mapping(args.label_mapping) | |
| 408 | + | |
| 409 | + floorplan_ious = list() | |
| 410 | + classwise_eval_tuples: Dict[str, List[EvalTuple]] = defaultdict(list) | |
| 411 | + for scene_id in scene_id_list: | |
| 412 | + log.info(f"Evaluating scene {scene_id}") | |
| 413 | + with open(os.path.join(args.pred_dir, f"{scene_id}.txt"), "r") as f: | |
| 414 | + pred_layout = Layout(f.read()) | |
| 415 | + with open(os.path.join(args.gt_dir, f"{scene_id}.txt"), "r") as f: | |
| 416 | + gt_layout = Layout(f.read()) | |
| 417 | + pred_layout.bboxes = assign_class_map(pred_layout.bboxes, class_map) | |
| 418 | + gt_layout.bboxes = assign_class_map(gt_layout.bboxes, class_map) | |
| 419 | + | |
| 420 | + # Floorplan, IoU | |
| 421 | + pred_poly = construct_polygon( | |
| 422 | + [LineString([(w.ax, w.ay), (w.bx, w.by)]) for w in pred_layout.walls] | |
| 423 | + ) | |
| 424 | + gt_poly = construct_polygon( | |
| 425 | + [LineString([(w.ax, w.ay), (w.bx, w.by)]) for w in gt_layout.walls] | |
| 426 | + ) | |
| 427 | + floorplan_ious.append(calc_poly_iou(pred_poly, gt_poly)) | |
| 428 | + | |
| 429 | + # Normal Objects, F1 | |
| 430 | + pred_normal_objects = [ | |
| 431 | + b for b in pred_layout.bboxes if b.class_name in OBJECTS | |
| 432 | + ] | |
| 433 | + gt_normal_objects = [ | |
| 434 | + b for b in gt_layout.bboxes if b.class_name in OBJECTS | |
| 435 | + ] | |
| 436 | + for class_name in OBJECTS: | |
| 437 | + classwise_eval_tuples[class_name].append( | |
| 438 | + calc_bbox_tp( | |
| 439 | + pred_entities=[ | |
| 440 | + b | |
| 441 | + for b in pred_normal_objects | |
| 442 | + if get_entity_class(b) == class_name | |
| 443 | + ], | |
| 444 | + gt_entities=[ | |
| 445 | + b | |
| 446 | + for b in gt_normal_objects | |
| 447 | + if get_entity_class(b) == class_name | |
| 448 | + ], | |
| 449 | + ) | |
| 450 | + ) | |
| 451 | + | |
| 452 | + # Thin Objects, F1 | |
| 453 | + pred_thin_objects = [ | |
| 454 | + b for b in pred_layout.bboxes if b.class_name in THIN_OBJECTS | |
| 455 | + ] | |
| 456 | + gt_thin_objects = [b for b in gt_layout.bboxes if b.class_name in THIN_OBJECTS] | |
| 457 | + pred_wall_id_lookup = {w.id: w for w in pred_layout.walls} | |
| 458 | + gt_wall_id_lookup = {w.id: w for w in gt_layout.walls} | |
| 459 | + pred_thin_objects += [ | |
| 460 | + e | |
| 461 | + for e in pred_layout.doors + pred_layout.windows | |
| 462 | + if is_valid_dw(e, pred_wall_id_lookup) | |
| 463 | + ] | |
| 464 | + gt_thin_objects += [ | |
| 465 | + e | |
| 466 | + for e in gt_layout.doors + gt_layout.windows | |
| 467 | + if is_valid_dw(e, gt_wall_id_lookup) | |
| 468 | + ] | |
| 469 | + | |
| 470 | + for class_name in THIN_OBJECTS: | |
| 471 | + classwise_eval_tuples[class_name].append( | |
| 472 | + calc_thin_bbox_tp( | |
| 473 | + pred_entities=[ | |
| 474 | + b | |
| 475 | + for b in pred_thin_objects | |
| 476 | + if get_entity_class(b) == class_name | |
| 477 | + ], | |
| 478 | + gt_entities=[ | |
| 479 | + b for b in gt_thin_objects if get_entity_class(b) == class_name | |
| 480 | + ], | |
| 481 | + pred_wall_id_lookup=pred_wall_id_lookup, | |
| 482 | + gt_wall_id_lookup=gt_wall_id_lookup, | |
| 483 | + ) | |
| 484 | + ) | |
| 485 | + | |
| 486 | + # table print | |
| 487 | + headers = ["Floorplan", "mean IoU"] | |
| 488 | + table_data = [headers] | |
| 489 | + table_data += [["wall", np.mean(floorplan_ious)]] | |
| 490 | + print("\n" + AsciiTable(table_data).table) | |
| 491 | + | |
| 492 | + headers = ["Objects", "F1 @.25 IoU"] | |
| 493 | + table_data = [headers] | |
| 494 | + for class_name in OBJECTS: | |
| 495 | + tuples = classwise_eval_tuples[class_name] | |
| 496 | + f1 = np.ma.masked_where( | |
| 497 | + [t.masked for t in tuples], [t.f1 for t in tuples] | |
| 498 | + ).mean() | |
| 499 | + table_data.append([class_name, f1]) | |
| 500 | + print("\n" + AsciiTable(table_data).table) | |
| 501 | + | |
| 502 | + headers = ["Thin Objects", "F1 @.25 IoU"] | |
| 503 | + table_data = [headers] | |
| 504 | + for class_name in THIN_OBJECTS: | |
| 505 | + tuples = classwise_eval_tuples[class_name] | |
| 506 | + f1 = np.ma.masked_where( | |
| 507 | + [t.masked for t in tuples], [t.f1 for t in tuples] | |
| 508 | + ).mean() | |
| 509 | + table_data.append([class_name, f1]) | |
| 510 | + print("\n" + AsciiTable(table_data).table) |
added figures/cover.png +0 −0
Binary content is not shown. View the file.
added figures/logo_dark.png +0 −0
Binary content is not shown. View the file.
added figures/logo_light.png +0 −0
Binary content is not shown. View the file.
added inference.py +214 −0
| @@ -0,0 +1,214 @@ | ||
| 1 | +import os | |
| 2 | +import glob | |
| 3 | +import argparse | |
| 4 | + | |
| 5 | +import torch | |
| 6 | +import numpy as np | |
| 7 | +from tqdm import tqdm | |
| 8 | +from threading import Thread | |
| 9 | +from transformers import AutoTokenizer, AutoModelForCausalLM | |
| 10 | +from transformers import TextIteratorStreamer | |
| 11 | + | |
| 12 | +from spatiallm import Layout | |
| 13 | +from spatiallm import SpatialLMLlamaForCausalLM, SpatialLMQwenForCausalLM | |
| 14 | +from spatiallm.pcd import load_o3d_pcd, get_points_and_colors, cleanup_pcd, Compose | |
| 15 | + | |
| 16 | + | |
| 17 | +def preprocess_point_cloud(points, colors, grid_size, num_bins): | |
| 18 | + transform = Compose( | |
| 19 | + [ | |
| 20 | + dict(type="PositiveShift"), | |
| 21 | + dict(type="NormalizeColor"), | |
| 22 | + dict( | |
| 23 | + type="GridSample", | |
| 24 | + grid_size=grid_size, | |
| 25 | + hash_type="fnv", | |
| 26 | + mode="test", | |
| 27 | + keys=("coord", "color"), | |
| 28 | + return_grid_coord=True, | |
| 29 | + max_grid_coord=num_bins, | |
| 30 | + ), | |
| 31 | + ] | |
| 32 | + ) | |
| 33 | + point_cloud = transform( | |
| 34 | + { | |
| 35 | + "name": "pcd", | |
| 36 | + "coord": points.copy(), | |
| 37 | + "color": colors.copy(), | |
| 38 | + } | |
| 39 | + ) | |
| 40 | + coord = point_cloud["grid_coord"] | |
| 41 | + xyz = point_cloud["coord"] | |
| 42 | + rgb = point_cloud["color"] | |
| 43 | + point_cloud = np.concatenate([coord, xyz, rgb], axis=1) | |
| 44 | + return torch.as_tensor(np.stack([point_cloud], axis=0)) | |
| 45 | + | |
| 46 | + | |
| 47 | +def generate_layout( | |
| 48 | + model, | |
| 49 | + point_cloud, | |
| 50 | + tokenizer, | |
| 51 | + code_template_file, | |
| 52 | + top_k=10, | |
| 53 | + top_p=0.95, | |
| 54 | + temperature=0.6, | |
| 55 | + num_beams=1, | |
| 56 | + max_new_tokens=4096, | |
| 57 | +): | |
| 58 | + # load the code template | |
| 59 | + with open(code_template_file, "r") as f: | |
| 60 | + code_template = f.read() | |
| 61 | + | |
| 62 | + prompt = f"<|point_start|><|point_pad|><|point_end|>Detect walls, doors, windows, boxes. The reference code is as followed: {code_template}" | |
| 63 | + | |
| 64 | + # prepare the conversation data | |
| 65 | + if model.config.model_type == SpatialLMLlamaForCausalLM.config_class.model_type: | |
| 66 | + conversation = [{"role": "user", "content": prompt}] | |
| 67 | + elif model.config.model_type == SpatialLMQwenForCausalLM.config_class.model_type: | |
| 68 | + conversation = [ | |
| 69 | + {"role": "system", "content": "You are a helpful assistant."}, | |
| 70 | + {"role": "user", "content": prompt}, | |
| 71 | + ] | |
| 72 | + else: | |
| 73 | + raise ValueError(f"Unsupported model type: {model.config.model_type}") | |
| 74 | + | |
| 75 | + input_ids = tokenizer.apply_chat_template( | |
| 76 | + conversation, add_generation_prompt=True, return_tensors="pt" | |
| 77 | + ) | |
| 78 | + input_ids = input_ids.to(model.device) | |
| 79 | + | |
| 80 | + streamer = TextIteratorStreamer( | |
| 81 | + tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True | |
| 82 | + ) | |
| 83 | + | |
| 84 | + generate_kwargs = dict( | |
| 85 | + {"input_ids": input_ids, "point_clouds": point_cloud}, | |
| 86 | + streamer=streamer, | |
| 87 | + max_new_tokens=max_new_tokens, | |
| 88 | + do_sample=True, | |
| 89 | + use_cache=True, | |
| 90 | + temperature=temperature, | |
| 91 | + top_p=top_p, | |
| 92 | + top_k=top_k, | |
| 93 | + num_beams=num_beams, | |
| 94 | + ) | |
| 95 | + t = Thread(target=model.generate, kwargs=generate_kwargs) | |
| 96 | + t.start() | |
| 97 | + | |
| 98 | + print("Generating layout...\n") | |
| 99 | + generate_texts = [] | |
| 100 | + for text in streamer: | |
| 101 | + generate_texts.append(text) | |
| 102 | + print(text, end="", flush=True) | |
| 103 | + print("\nDone!") | |
| 104 | + | |
| 105 | + layout_str = "".join(generate_texts) | |
| 106 | + layout = Layout(layout_str) | |
| 107 | + layout.undiscretize_and_unnormalize() | |
| 108 | + return layout | |
| 109 | + | |
| 110 | + | |
| 111 | +if __name__ == "__main__": | |
| 112 | + parser = argparse.ArgumentParser("SpatialLM inference script") | |
| 113 | + parser.add_argument( | |
| 114 | + "-p", | |
| 115 | + "--point_cloud", | |
| 116 | + type=str, | |
| 117 | + required=True, | |
| 118 | + help="Path to the input point cloud file or a folder containing multiple point cloud files", | |
| 119 | + ) | |
| 120 | + parser.add_argument( | |
| 121 | + "-o", | |
| 122 | + "--output", | |
| 123 | + type=str, | |
| 124 | + required=True, | |
| 125 | + help="Path to the output layout txt file or a folder to save multiple layout txt files", | |
| 126 | + ) | |
| 127 | + parser.add_argument( | |
| 128 | + "-m", | |
| 129 | + "--model_path", | |
| 130 | + type=str, | |
| 131 | + default="manycore-research/SpatialLM-Llama-1B", | |
| 132 | + help="Path to the model checkpoint", | |
| 133 | + ) | |
| 134 | + parser.add_argument( | |
| 135 | + "-t", | |
| 136 | + "--code_template_file", | |
| 137 | + type=str, | |
| 138 | + default="code_template.txt", | |
| 139 | + help="Path to the code template file", | |
| 140 | + ) | |
| 141 | + parser.add_argument( | |
| 142 | + "--top_k", | |
| 143 | + type=int, | |
| 144 | + default=10, | |
| 145 | + help="The number of highest probability vocabulary tokens to keep for top-k filtering", | |
| 146 | + ) | |
| 147 | + parser.add_argument( | |
| 148 | + "--top_p", | |
| 149 | + type=float, | |
| 150 | + default=0.95, | |
| 151 | + help="The smallest set of most probable tokens with probabilities that add up to top_p or higher are kept", | |
| 152 | + ) | |
| 153 | + parser.add_argument( | |
| 154 | + "--temperature", | |
| 155 | + type=float, | |
| 156 | + default=0.6, | |
| 157 | + help="The value used to module the next token probabilities", | |
| 158 | + ) | |
| 159 | + parser.add_argument( | |
| 160 | + "--num_beams", | |
| 161 | + type=int, | |
| 162 | + default=1, | |
| 163 | + help="The number of beams for beam search", | |
| 164 | + ) | |
| 165 | + args = parser.parse_args() | |
| 166 | + | |
| 167 | + # load the model | |
| 168 | + tokenizer = AutoTokenizer.from_pretrained(args.model_path) | |
| 169 | + model = AutoModelForCausalLM.from_pretrained(args.model_path) | |
| 170 | + model.to("cuda") | |
| 171 | + model.set_point_backbone_dtype(torch.float32) | |
| 172 | + model.eval() | |
| 173 | + | |
| 174 | + # check if the input is a single point cloud file or a folder containing multiple point cloud files | |
| 175 | + if os.path.isfile(args.point_cloud): | |
| 176 | + point_cloud_files = [args.point_cloud] | |
| 177 | + else: | |
| 178 | + point_cloud_files = glob.glob(os.path.join(args.point_cloud, "*.ply")) | |
| 179 | + | |
| 180 | + for point_cloud_file in tqdm(point_cloud_files): | |
| 181 | + # load the point cloud | |
| 182 | + point_cloud = load_o3d_pcd(point_cloud_file) | |
| 183 | + point_cloud = cleanup_pcd(point_cloud) | |
| 184 | + points, colors = get_points_and_colors(point_cloud) | |
| 185 | + min_extent = np.min(points, axis=0) | |
| 186 | + | |
| 187 | + # preprocess the point cloud to tensor features | |
| 188 | + grid_size = Layout.get_grid_size() | |
| 189 | + num_bins = Layout.get_num_bins() | |
| 190 | + input_pcd = preprocess_point_cloud(points, colors, grid_size, num_bins) | |
| 191 | + | |
| 192 | + # generate the layout | |
| 193 | + layout = generate_layout( | |
| 194 | + model, | |
| 195 | + input_pcd, | |
| 196 | + tokenizer, | |
| 197 | + args.code_template_file, | |
| 198 | + args.top_k, | |
| 199 | + args.top_p, | |
| 200 | + args.temperature, | |
| 201 | + args.num_beams, | |
| 202 | + ) | |
| 203 | + layout.translate(min_extent) | |
| 204 | + pred_language_string = layout.to_language_string() | |
| 205 | + | |
| 206 | + # check if the output path is a file or directory | |
| 207 | + if os.path.splitext(args.output)[-1]: | |
| 208 | + with open(args.output, "w") as f: | |
| 209 | + f.write(pred_language_string) | |
| 210 | + else: | |
| 211 | + output_filename = os.path.basename(point_cloud_file).replace(".ply", ".txt") | |
| 212 | + os.makedirs(args.output, exist_ok=True) | |
| 213 | + with open(os.path.join(args.output, output_filename), "w") as f: | |
| 214 | + f.write(pred_language_string) |
added pyproject.toml +44 −0
| @@ -0,0 +1,44 @@ | ||
| 1 | +[tool.poetry] | |
| 2 | +name = "spatiallm" | |
| 3 | +version = "0.0.1" | |
| 4 | +description = "SpatialLM: Large Language Model for Spatial Understanding" | |
| 5 | +authors = ["ManyCore Research Team"] | |
| 6 | +license = "Llama3.2" | |
| 7 | +readme = "README.md" | |
| 8 | + | |
| 9 | +[tool.poetry.dependencies] | |
| 10 | +python = ">=3.10,<3.12" | |
| 11 | +torch = { version = "^2.4.1+cu124", source = "pytorch" } | |
| 12 | +torchvision = { version = "^0.19.1+cu124", source = "pytorch" } | |
| 13 | +torchaudio = { version = "^2.4.1+cu124", source = "pytorch" } | |
| 14 | +transformers = ">=4.41.2,<=4.46.1" | |
| 15 | +safetensors = "^0.4.5" | |
| 16 | +pandas = "^2.2.3" | |
| 17 | +einops = "^0.8.1" | |
| 18 | +numpy = "^1.26" | |
| 19 | +scipy = "^1.15.2" | |
| 20 | +scikit-learn = "^1.6.1" | |
| 21 | +toml = "^0.10.2" | |
| 22 | +tokenizers = ">=0.19.0,<0.20.4" | |
| 23 | +huggingface_hub = ">=0.25.0" | |
| 24 | +rerun-sdk = ">=0.21.0" | |
| 25 | +shapely = "^2.0.7" | |
| 26 | +bbox = "^0.9.4" | |
| 27 | +terminaltables = "^3.1.10" | |
| 28 | +open3d = "^0.18.0" | |
| 29 | +nvidia-cudnn-cu12 = "*" | |
| 30 | +nvidia-nccl-cu12 = "*" | |
| 31 | +poethepoet = {extras = ["poetry-plugin"], version = "^0.33.1"} | |
| 32 | +addict = "^2.4.0" | |
| 33 | + | |
| 34 | +[tool.poe.tasks] | |
| 35 | +install-torchsparse = "pip install git+https://github.com/mit-han-lab/torchsparse.git" | |
| 36 | + | |
| 37 | +[build-system] | |
| 38 | +requires = ["poetry-core", "setuptools", "wheel", "torch"] | |
| 39 | +build-backend = "poetry.core.masonry.api" | |
| 40 | + | |
| 41 | +[[tool.poetry.source]] | |
| 42 | +priority = "supplemental" | |
| 43 | +name = "pytorch" | |
| 44 | +url = "https://download.pytorch.org/whl/cu124" |
added spatiallm/__init__.py +18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +from .layout.layout import Layout | |
| 2 | +from .layout.entity import Wall, Door, Window, Bbox | |
| 3 | +from .model.pcd_encoder import PointCloudEncoder | |
| 4 | +from .model.spatiallm_llama import SpatialLMLlamaForCausalLM, SpatialLMLlamaConfig | |
| 5 | +from .model.spatiallm_qwen import SpatialLMQwenForCausalLM, SpatialLMQwenConfig | |
| 6 | + | |
| 7 | +__all__ = [ | |
| 8 | + "Layout", | |
| 9 | + "Wall", | |
| 10 | + "Door", | |
| 11 | + "Window", | |
| 12 | + "Bbox", | |
| 13 | + "PointCloudEncoder", | |
| 14 | + "SpatialLMLlamaForCausalLM", | |
| 15 | + "SpatialLMLlamaConfig", | |
| 16 | + "SpatialLMQwenForCausalLM", | |
| 17 | + "SpatialLMQwenConfig", | |
| 18 | +] |
added spatiallm/layout/__init__.py +0 −0
added spatiallm/layout/entity.py +346 −0
| @@ -0,0 +1,346 @@ | ||
| 1 | +# Copyright (c) Manycore Tech Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | + | |
| 4 | +""" | |
| 5 | +This code is derived from the SceneScript language sequence and entity parameters. | |
| 6 | + | |
| 7 | +Reference: https://github.com/facebookresearch/scenescript/blob/main/src/data/language_sequence.py | |
| 8 | +""" | |
| 9 | + | |
| 10 | +from dataclasses import dataclass | |
| 11 | + | |
| 12 | +import numpy as np | |
| 13 | +from scipy.spatial.transform import Rotation as R | |
| 14 | + | |
| 15 | +NORMALIZATION_PRESET = { | |
| 16 | + "world": (0.0, 32.0), | |
| 17 | + "height": (0.0, 25.6), | |
| 18 | + "width": (0.0, 25.6), | |
| 19 | + "scale": (0.0, 20.0), | |
| 20 | + "angle": (-6.2832, 6.2832), | |
| 21 | + "num_bins": 640, | |
| 22 | +} | |
| 23 | + | |
| 24 | + | |
| 25 | +@dataclass | |
| 26 | +class Wall: | |
| 27 | + id: int | |
| 28 | + ax: float | |
| 29 | + ay: float | |
| 30 | + az: float | |
| 31 | + bx: float | |
| 32 | + by: float | |
| 33 | + bz: float | |
| 34 | + height: float | |
| 35 | + thickness: float | |
| 36 | + entity_label: str = "wall" | |
| 37 | + | |
| 38 | + def __post_init__(self): | |
| 39 | + self.id = int(self.id) | |
| 40 | + self.ax = float(self.ax) | |
| 41 | + self.ay = float(self.ay) | |
| 42 | + self.az = float(self.az) | |
| 43 | + self.bx = float(self.bx) | |
| 44 | + self.by = float(self.by) | |
| 45 | + self.bz = float(self.bz) | |
| 46 | + self.height = float(self.height) | |
| 47 | + self.thickness = float(self.thickness) | |
| 48 | + | |
| 49 | + def rotate(self, angle: float): | |
| 50 | + wall_start = np.array([self.ax, self.ay, self.az]) | |
| 51 | + wall_end = np.array([self.bx, self.by, self.bz]) | |
| 52 | + rotmat = R.from_rotvec([0, 0, angle]).as_matrix() | |
| 53 | + wall_start = rotmat @ wall_start | |
| 54 | + wall_end = rotmat @ wall_end | |
| 55 | + | |
| 56 | + self.ax = wall_start[0] | |
| 57 | + self.ay = wall_start[1] | |
| 58 | + self.az = wall_start[2] | |
| 59 | + self.bx = wall_end[0] | |
| 60 | + self.by = wall_end[1] | |
| 61 | + self.bz = wall_end[2] | |
| 62 | + | |
| 63 | + def translate(self, translation: np.ndarray): | |
| 64 | + self.ax += translation[0] | |
| 65 | + self.ay += translation[1] | |
| 66 | + self.az += translation[2] | |
| 67 | + self.bx += translation[0] | |
| 68 | + self.by += translation[1] | |
| 69 | + self.bz += translation[2] | |
| 70 | + | |
| 71 | + def scale(self, scaling: float): | |
| 72 | + self.height *= scaling | |
| 73 | + self.thickness *= scaling | |
| 74 | + self.ax *= scaling | |
| 75 | + self.ay *= scaling | |
| 76 | + self.az *= scaling | |
| 77 | + self.bx *= scaling | |
| 78 | + | |
| 79 | + def normalize_and_discretize(self): | |
| 80 | + height_min, height_max = NORMALIZATION_PRESET["height"] | |
| 81 | + world_min, world_max = NORMALIZATION_PRESET["world"] | |
| 82 | + num_bins = NORMALIZATION_PRESET["num_bins"] | |
| 83 | + | |
| 84 | + self.height = (self.height - height_min) / (height_max - height_min) * num_bins | |
| 85 | + self.thickness = ( | |
| 86 | + (self.thickness - height_min) / (height_max - height_min) * num_bins | |
| 87 | + ) | |
| 88 | + self.ax = (self.ax - world_min) / (world_max - world_min) * num_bins | |
| 89 | + self.ay = (self.ay - world_min) / (world_max - world_min) * num_bins | |
| 90 | + self.az = (self.az - world_min) / (world_max - world_min) * num_bins | |
| 91 | + self.bx = (self.bx - world_min) / (world_max - world_min) * num_bins | |
| 92 | + self.by = (self.by - world_min) / (world_max - world_min) * num_bins | |
| 93 | + self.bz = (self.bz - world_min) / (world_max - world_min) * num_bins | |
| 94 | + | |
| 95 | + self.height = np.clip(self.height, 0, num_bins - 1) | |
| 96 | + self.thickness = np.clip(self.thickness, 0, num_bins - 1) | |
| 97 | + self.ax = np.clip(self.ax, 0, num_bins - 1) | |
| 98 | + self.ay = np.clip(self.ay, 0, num_bins - 1) | |
| 99 | + self.az = np.clip(self.az, 0, num_bins - 1) | |
| 100 | + self.bx = np.clip(self.bx, 0, num_bins - 1) | |
| 101 | + self.by = np.clip(self.by, 0, num_bins - 1) | |
| 102 | + self.bz = np.clip(self.bz, 0, num_bins - 1) | |
| 103 | + | |
| 104 | + def undiscretize_and_unnormalize(self): | |
| 105 | + num_bins = NORMALIZATION_PRESET["num_bins"] | |
| 106 | + height_min, height_max = NORMALIZATION_PRESET["height"] | |
| 107 | + world_min, world_max = NORMALIZATION_PRESET["world"] | |
| 108 | + | |
| 109 | + # undiscretize | |
| 110 | + self.height = self.height / num_bins | |
| 111 | + self.thickness = self.thickness / num_bins | |
| 112 | + self.ax = self.ax / num_bins | |
| 113 | + self.ay = self.ay / num_bins | |
| 114 | + self.az = self.az / num_bins | |
| 115 | + self.bx = self.bx / num_bins | |
| 116 | + self.by = self.by / num_bins | |
| 117 | + self.bz = self.bz / num_bins | |
| 118 | + | |
| 119 | + # unnormalize | |
| 120 | + self.height = self.height * (height_max - height_min) + height_min | |
| 121 | + self.thickness = self.thickness * (height_max - height_min) + height_min | |
| 122 | + self.ax = self.ax * (world_max - world_min) + world_min | |
| 123 | + self.ay = self.ay * (world_max - world_min) + world_min | |
| 124 | + self.az = self.az * (world_max - world_min) + world_min | |
| 125 | + self.bx = self.bx * (world_max - world_min) + world_min | |
| 126 | + self.by = self.by * (world_max - world_min) + world_min | |
| 127 | + self.bz = self.bz * (world_max - world_min) + world_min | |
| 128 | + | |
| 129 | + def to_language_string(self): | |
| 130 | + capitalized_label = self.entity_label.capitalize() | |
| 131 | + # wall_0=Wall(a_x,a_y,a_z,b_x,b_y,b_z,height,thickness) | |
| 132 | + language_string = f"{self.entity_label}_{self.id}={capitalized_label}({self.ax},{self.ay},{self.az},{self.bx},{self.by},{self.bz},{self.height},{self.thickness})" | |
| 133 | + return language_string | |
| 134 | + | |
| 135 | + | |
| 136 | +@dataclass | |
| 137 | +class Door: | |
| 138 | + id: int | |
| 139 | + wall_id: int | |
| 140 | + position_x: float | |
| 141 | + position_y: float | |
| 142 | + position_z: float | |
| 143 | + width: float | |
| 144 | + height: float | |
| 145 | + entity_label: str = "door" | |
| 146 | + | |
| 147 | + def __post_init__(self): | |
| 148 | + self.id = int(self.id) | |
| 149 | + self.wall_id = int(self.wall_id) | |
| 150 | + self.position_x = float(self.position_x) | |
| 151 | + self.position_y = float(self.position_y) | |
| 152 | + self.position_z = float(self.position_z) | |
| 153 | + self.width = float(self.width) | |
| 154 | + self.height = float(self.height) | |
| 155 | + | |
| 156 | + def rotate(self, angle: float): | |
| 157 | + center = np.array([self.position_x, self.position_y, self.position_z]) | |
| 158 | + rotmat = R.from_rotvec([0, 0, angle]).as_matrix() | |
| 159 | + new_center = rotmat @ center | |
| 160 | + | |
| 161 | + self.position_x = new_center[0] | |
| 162 | + self.position_y = new_center[1] | |
| 163 | + self.position_z = new_center[2] | |
| 164 | + | |
| 165 | + def translate(self, translation: np.ndarray): | |
| 166 | + self.position_x += translation[0] | |
| 167 | + self.position_y += translation[1] | |
| 168 | + self.position_z += translation[2] | |
| 169 | + | |
| 170 | + def scale(self, scaling: float): | |
| 171 | + self.width *= scaling | |
| 172 | + self.height *= scaling | |
| 173 | + self.position_x *= scaling | |
| 174 | + self.position_y *= scaling | |
| 175 | + self.position_z *= scaling | |
| 176 | + | |
| 177 | + def normalize_and_discretize(self): | |
| 178 | + width_min, width_max = NORMALIZATION_PRESET["width"] | |
| 179 | + height_min, height_max = NORMALIZATION_PRESET["height"] | |
| 180 | + world_min, world_max = NORMALIZATION_PRESET["world"] | |
| 181 | + num_bins = NORMALIZATION_PRESET["num_bins"] | |
| 182 | + | |
| 183 | + self.width = (self.width - width_min) / (width_max - width_min) * num_bins | |
| 184 | + self.height = (self.height - height_min) / (height_max - height_min) * num_bins | |
| 185 | + self.position_x = ( | |
| 186 | + (self.position_x - world_min) / (world_max - world_min) * num_bins | |
| 187 | + ) | |
| 188 | + self.position_y = ( | |
| 189 | + (self.position_y - world_min) / (world_max - world_min) * num_bins | |
| 190 | + ) | |
| 191 | + self.position_z = ( | |
| 192 | + (self.position_z - world_min) / (world_max - world_min) * num_bins | |
| 193 | + ) | |
| 194 | + | |
| 195 | + self.width = np.clip(self.width, 0, num_bins - 1) | |
| 196 | + self.height = np.clip(self.height, 0, num_bins - 1) | |
| 197 | + self.position_x = np.clip(self.position_x, 0, num_bins - 1) | |
| 198 | + self.position_y = np.clip(self.position_y, 0, num_bins - 1) | |
| 199 | + self.position_z = np.clip(self.position_z, 0, num_bins - 1) | |
| 200 | + | |
| 201 | + def undiscretize_and_unnormalize(self): | |
| 202 | + num_bins = NORMALIZATION_PRESET["num_bins"] | |
| 203 | + width_min, width_max = NORMALIZATION_PRESET["width"] | |
| 204 | + height_min, height_max = NORMALIZATION_PRESET["height"] | |
| 205 | + world_min, world_max = NORMALIZATION_PRESET["world"] | |
| 206 | + | |
| 207 | + # undiscretize | |
| 208 | + self.width = self.width / num_bins | |
| 209 | + self.height = self.height / num_bins | |
| 210 | + self.position_x = self.position_x / num_bins | |
| 211 | + self.position_y = self.position_y / num_bins | |
| 212 | + self.position_z = self.position_z / num_bins | |
| 213 | + | |
| 214 | + # unnormalize | |
| 215 | + self.width = self.width * (width_max - width_min) + width_min | |
| 216 | + self.height = self.height * (height_max - height_min) + height_min | |
| 217 | + self.position_x = self.position_x * (world_max - world_min) + world_min | |
| 218 | + self.position_y = self.position_y * (world_max - world_min) + world_min | |
| 219 | + self.position_z = self.position_z * (world_max - world_min) + world_min | |
| 220 | + | |
| 221 | + def to_language_string(self): | |
| 222 | + capitalized_label = self.entity_label.capitalize() | |
| 223 | + self.id = self.id % 1000 | |
| 224 | + # door_0=Door(wall_id,position_x,position_y,position_z,width,height) | |
| 225 | + language_string = f"{self.entity_label}_{self.id}={capitalized_label}(wall_{self.wall_id},{self.position_x},{self.position_y},{self.position_z},{self.width},{self.height})" | |
| 226 | + return language_string | |
| 227 | + | |
| 228 | + | |
| 229 | +@dataclass | |
| 230 | +class Window(Door): | |
| 231 | + entity_label: str = "window" | |
| 232 | + | |
| 233 | + | |
| 234 | +@dataclass | |
| 235 | +class Bbox: | |
| 236 | + id: int | |
| 237 | + class_name: str | |
| 238 | + position_x: float | |
| 239 | + position_y: float | |
| 240 | + position_z: float | |
| 241 | + angle_z: float | |
| 242 | + scale_x: float | |
| 243 | + scale_y: float | |
| 244 | + scale_z: float | |
| 245 | + entity_label: str = "bbox" | |
| 246 | + | |
| 247 | + def __post_init__(self): | |
| 248 | + self.id = int(self.id) | |
| 249 | + self.class_name = str(self.class_name) | |
| 250 | + self.position_x = float(self.position_x) | |
| 251 | + self.position_y = float(self.position_y) | |
| 252 | + self.position_z = float(self.position_z) | |
| 253 | + self.angle_z = float(self.angle_z) | |
| 254 | + self.scale_x = abs(float(self.scale_x)) | |
| 255 | + self.scale_y = abs(float(self.scale_y)) | |
| 256 | + self.scale_z = abs(float(self.scale_z)) | |
| 257 | + | |
| 258 | + def rotate(self, angle: float): | |
| 259 | + augment_rot_mat = R.from_rotvec([0, 0, angle]).as_matrix() | |
| 260 | + bbox_rot_mat = R.from_rotvec([0, 0, self.angle_z]).as_matrix() | |
| 261 | + new_bbox_rot_mat = augment_rot_mat @ bbox_rot_mat | |
| 262 | + new_angle_z = R.from_matrix(new_bbox_rot_mat).as_euler("ZYX")[0] | |
| 263 | + new_angle_z = (new_angle_z + np.pi) % (2 * np.pi) - np.pi # Range: [-pi, pi) | |
| 264 | + | |
| 265 | + # Bbox is symmetric | |
| 266 | + symmetry = np.pi | |
| 267 | + if np.isclose(self.scale_x, self.scale_y, atol=1e-3): | |
| 268 | + symmetry = np.pi / 2 | |
| 269 | + new_angle_z = (new_angle_z + np.pi) % symmetry - np.pi | |
| 270 | + self.angle_z = new_angle_z | |
| 271 | + | |
| 272 | + bbox_center = np.array([self.position_x, self.position_y, self.position_z]) | |
| 273 | + bbox_center = augment_rot_mat @ bbox_center | |
| 274 | + self.position_x = bbox_center[0] | |
| 275 | + self.position_y = bbox_center[1] | |
| 276 | + self.position_z = bbox_center[2] | |
| 277 | + | |
| 278 | + def translate(self, translation: np.ndarray): | |
| 279 | + self.position_x += translation[0] | |
| 280 | + self.position_y += translation[1] | |
| 281 | + self.position_z += translation[2] | |
| 282 | + | |
| 283 | + def scale(self, scaling: float): | |
| 284 | + self.scale_x *= scaling | |
| 285 | + self.scale_y *= scaling | |
| 286 | + self.scale_z *= scaling | |
| 287 | + self.position_x *= scaling | |
| 288 | + self.position_y *= scaling | |
| 289 | + self.position_z *= scaling | |
| 290 | + | |
| 291 | + def normalize_and_discretize(self): | |
| 292 | + world_min, world_max = NORMALIZATION_PRESET["world"] | |
| 293 | + scale_min, scale_max = NORMALIZATION_PRESET["scale"] | |
| 294 | + angle_min, angle_max = NORMALIZATION_PRESET["angle"] | |
| 295 | + num_bins = NORMALIZATION_PRESET["num_bins"] | |
| 296 | + | |
| 297 | + self.position_x = ( | |
| 298 | + (self.position_x - world_min) / (world_max - world_min) * num_bins | |
| 299 | + ) | |
| 300 | + self.position_y = ( | |
| 301 | + (self.position_y - world_min) / (world_max - world_min) * num_bins | |
| 302 | + ) | |
| 303 | + self.position_z = ( | |
| 304 | + (self.position_z - world_min) / (world_max - world_min) * num_bins | |
| 305 | + ) | |
| 306 | + self.angle_z = (self.angle_z - angle_min) / (angle_max - angle_min) * num_bins | |
| 307 | + self.scale_x = (self.scale_x - scale_min) / (scale_max - scale_min) * num_bins | |
| 308 | + self.scale_y = (self.scale_y - scale_min) / (scale_max - scale_min) * num_bins | |
| 309 | + self.scale_z = (self.scale_z - scale_min) / (scale_max - scale_min) * num_bins | |
| 310 | + | |
| 311 | + self.position_x = np.clip(self.position_x, 0, num_bins - 1) | |
| 312 | + self.position_y = np.clip(self.position_y, 0, num_bins - 1) | |
| 313 | + self.position_z = np.clip(self.position_z, 0, num_bins - 1) | |
| 314 | + self.angle_z = np.clip(self.angle_z, 0, num_bins - 1) | |
| 315 | + self.scale_x = np.clip(self.scale_x, 0, num_bins - 1) | |
| 316 | + self.scale_y = np.clip(self.scale_y, 0, num_bins - 1) | |
| 317 | + self.scale_z = np.clip(self.scale_z, 0, num_bins - 1) | |
| 318 | + | |
| 319 | + def undiscretize_and_unnormalize(self): | |
| 320 | + world_min, world_max = NORMALIZATION_PRESET["world"] | |
| 321 | + scale_min, scale_max = NORMALIZATION_PRESET["scale"] | |
| 322 | + angle_min, angle_max = NORMALIZATION_PRESET["angle"] | |
| 323 | + num_bins = NORMALIZATION_PRESET["num_bins"] | |
| 324 | + | |
| 325 | + self.position_x = self.position_x / num_bins | |
| 326 | + self.position_y = self.position_y / num_bins | |
| 327 | + self.position_z = self.position_z / num_bins | |
| 328 | + self.angle_z = self.angle_z / num_bins | |
| 329 | + self.scale_x = self.scale_x / num_bins | |
| 330 | + self.scale_y = self.scale_y / num_bins | |
| 331 | + self.scale_z = self.scale_z / num_bins | |
| 332 | + | |
| 333 | + self.position_x = self.position_x * (world_max - world_min) + world_min | |
| 334 | + self.position_y = self.position_y * (world_max - world_min) + world_min | |
| 335 | + self.position_z = self.position_z * (world_max - world_min) + world_min | |
| 336 | + self.angle_z = self.angle_z * (angle_max - angle_min) + angle_min | |
| 337 | + self.scale_x = self.scale_x * (scale_max - scale_min) + scale_min | |
| 338 | + self.scale_y = self.scale_y * (scale_max - scale_min) + scale_min | |
| 339 | + self.scale_z = self.scale_z * (scale_max - scale_min) + scale_min | |
| 340 | + | |
| 341 | + def to_language_string(self): | |
| 342 | + capitalized_label = self.entity_label.capitalize() | |
| 343 | + self.id = self.id % 1000 | |
| 344 | + # bbox_0=Bbox(class_name,position_x,position_y,position_z,angle_z,scale_x,scale_y,scale_z) | |
| 345 | + language_string = f"{self.entity_label}_{self.id}={capitalized_label}({self.class_name},{self.position_x},{self.position_y},{self.position_z},{self.angle_z},{self.scale_x},{self.scale_y},{self.scale_z})" | |
| 346 | + return language_string |
added spatiallm/layout/layout.py +211 −0
| @@ -0,0 +1,211 @@ | ||
| 1 | +import numpy as np | |
| 2 | +from scipy.spatial.transform import Rotation as R | |
| 3 | +from spatiallm.layout.entity import Wall, Door, Window, Bbox, NORMALIZATION_PRESET | |
| 4 | + | |
| 5 | + | |
| 6 | +class Layout: | |
| 7 | + def __init__(self, str: str = None): | |
| 8 | + self.walls = [] | |
| 9 | + self.doors = [] | |
| 10 | + self.windows = [] | |
| 11 | + self.bboxes = [] | |
| 12 | + | |
| 13 | + if str: | |
| 14 | + self.from_str(str) | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def get_grid_size(): | |
| 18 | + world_min, world_max = NORMALIZATION_PRESET["world"] | |
| 19 | + return (world_max - world_min) / NORMALIZATION_PRESET["num_bins"] | |
| 20 | + | |
| 21 | + @staticmethod | |
| 22 | + def get_num_bins(): | |
| 23 | + return NORMALIZATION_PRESET["num_bins"] | |
| 24 | + | |
| 25 | + def from_str(self, s: str): | |
| 26 | + s = s.lstrip("\n") | |
| 27 | + lines = s.split("\n") | |
| 28 | + # wall lookup table | |
| 29 | + existing_walls = [] | |
| 30 | + for line in lines: | |
| 31 | + try: | |
| 32 | + label = line.split("=")[0] | |
| 33 | + entity_id = int(label.split("_")[1]) | |
| 34 | + entity_label = label.split("_")[0] | |
| 35 | + | |
| 36 | + # extract params | |
| 37 | + start_pos = line.find("(") | |
| 38 | + end_pos = line.find(")") | |
| 39 | + params = line[start_pos + 1 : end_pos].split(",") | |
| 40 | + | |
| 41 | + if entity_label == Wall.entity_label: | |
| 42 | + wall_args = [ | |
| 43 | + "ax", | |
| 44 | + "ay", | |
| 45 | + "az", | |
| 46 | + "bx", | |
| 47 | + "by", | |
| 48 | + "bz", | |
| 49 | + "height", | |
| 50 | + "thickness", | |
| 51 | + ] | |
| 52 | + wall_params = dict(zip(wall_args, params[0:8])) | |
| 53 | + entity = Wall(id=entity_id, **wall_params) | |
| 54 | + existing_walls.append(entity_id) | |
| 55 | + self.walls.append(entity) | |
| 56 | + elif entity_label == Door.entity_label: | |
| 57 | + wall_id = int(params[0].split("_")[1]) | |
| 58 | + if wall_id not in existing_walls: | |
| 59 | + continue | |
| 60 | + | |
| 61 | + door_args = [ | |
| 62 | + "position_x", | |
| 63 | + "position_y", | |
| 64 | + "position_z", | |
| 65 | + "width", | |
| 66 | + "height", | |
| 67 | + ] | |
| 68 | + door_params = dict(zip(door_args, params[1:6])) | |
| 69 | + entity = Door( | |
| 70 | + id=entity_id, | |
| 71 | + wall_id=wall_id, | |
| 72 | + **door_params, | |
| 73 | + ) | |
| 74 | + self.doors.append(entity) | |
| 75 | + elif entity_label == Window.entity_label: | |
| 76 | + wall_id = int(params[0].split("_")[1]) | |
| 77 | + if wall_id not in existing_walls: | |
| 78 | + continue | |
| 79 | + | |
| 80 | + window_args = [ | |
| 81 | + "position_x", | |
| 82 | + "position_y", | |
| 83 | + "position_z", | |
| 84 | + "width", | |
| 85 | + "height", | |
| 86 | + ] | |
| 87 | + window_params = dict(zip(window_args, params[1:6])) | |
| 88 | + entity = Window( | |
| 89 | + id=entity_id, | |
| 90 | + wall_id=wall_id, | |
| 91 | + **window_params, | |
| 92 | + ) | |
| 93 | + self.windows.append(entity) | |
| 94 | + elif entity_label == Bbox.entity_label: | |
| 95 | + class_name = params[0] | |
| 96 | + bbox_args = [ | |
| 97 | + "position_x", | |
| 98 | + "position_y", | |
| 99 | + "position_z", | |
| 100 | + "angle_z", | |
| 101 | + "scale_x", | |
| 102 | + "scale_y", | |
| 103 | + "scale_z", | |
| 104 | + ] | |
| 105 | + bbox_params = dict(zip(bbox_args, params[1:8])) | |
| 106 | + entity = Bbox( | |
| 107 | + id=entity_id, | |
| 108 | + class_name=class_name, | |
| 109 | + **bbox_params, | |
| 110 | + ) | |
| 111 | + self.bboxes.append(entity) | |
| 112 | + except Exception as e: | |
| 113 | + continue | |
| 114 | + | |
| 115 | + def to_boxes(self): | |
| 116 | + boxes = [] | |
| 117 | + lookup = {} | |
| 118 | + for wall in self.walls: | |
| 119 | + # assume the walls has a thickness of 0.0 for now | |
| 120 | + thickness = 0.0 | |
| 121 | + corner_a = np.array([wall.ax, wall.ay, wall.az]) | |
| 122 | + corner_b = np.array([wall.bx, wall.by, wall.bz]) | |
| 123 | + length = np.linalg.norm(corner_a - corner_b) | |
| 124 | + direction = corner_b - corner_a | |
| 125 | + angle = np.arctan2(direction[1], direction[0]) | |
| 126 | + lookup[wall.id] = {"wall": wall, "angle": angle} | |
| 127 | + | |
| 128 | + center = (corner_a + corner_b) * 0.5 + np.array([0, 0, 0.5 * wall.height]) | |
| 129 | + scale = np.array([length, thickness, wall.height]) | |
| 130 | + rotation = R.from_rotvec([0, 0, angle]).as_matrix() | |
| 131 | + box = { | |
| 132 | + "id": wall.id, | |
| 133 | + "class": Wall.entity_label, | |
| 134 | + "label": Wall.entity_label, | |
| 135 | + "center": center, | |
| 136 | + "rotation": rotation, | |
| 137 | + "scale": scale, | |
| 138 | + } | |
| 139 | + boxes.append(box) | |
| 140 | + | |
| 141 | + for fixture in self.doors + self.windows: | |
| 142 | + wall_id = fixture.wall_id | |
| 143 | + wall_info = lookup.get(wall_id, None) | |
| 144 | + if wall_info is None: | |
| 145 | + continue | |
| 146 | + | |
| 147 | + wall = wall_info["wall"] | |
| 148 | + angle = wall_info["angle"] | |
| 149 | + thickness = wall.thickness | |
| 150 | + | |
| 151 | + center = np.array( | |
| 152 | + [fixture.position_x, fixture.position_y, fixture.position_z] | |
| 153 | + ) | |
| 154 | + scale = np.array([fixture.width, thickness, fixture.height]) | |
| 155 | + rotation = R.from_rotvec([0, 0, angle]).as_matrix() | |
| 156 | + class_prefix = 1000 if fixture.entity_label == Door.entity_label else 2000 | |
| 157 | + box = { | |
| 158 | + "id": fixture.id + class_prefix, | |
| 159 | + "class": fixture.entity_label, | |
| 160 | + "label": fixture.entity_label, | |
| 161 | + "center": center, | |
| 162 | + "rotation": rotation, | |
| 163 | + "scale": scale, | |
| 164 | + } | |
| 165 | + boxes.append(box) | |
| 166 | + | |
| 167 | + for bbox in self.bboxes: | |
| 168 | + center = np.array([bbox.position_x, bbox.position_y, bbox.position_z]) | |
| 169 | + scale = np.array([bbox.scale_x, bbox.scale_y, bbox.scale_z]) | |
| 170 | + rotation = R.from_rotvec([0, 0, bbox.angle_z]).as_matrix() | |
| 171 | + class_name = bbox.class_name | |
| 172 | + box = { | |
| 173 | + "id": bbox.id + 3000, | |
| 174 | + "class": Bbox.entity_label, | |
| 175 | + "label": class_name, | |
| 176 | + "center": center, | |
| 177 | + "rotation": rotation, | |
| 178 | + "scale": scale, | |
| 179 | + } | |
| 180 | + boxes.append(box) | |
| 181 | + | |
| 182 | + return boxes | |
| 183 | + | |
| 184 | + def get_entities(self): | |
| 185 | + return self.walls + self.doors + self.windows + self.bboxes | |
| 186 | + | |
| 187 | + def normalize_and_discretize(self): | |
| 188 | + for entity in self.get_entities(): | |
| 189 | + entity.normalize_and_discretize() | |
| 190 | + | |
| 191 | + def undiscretize_and_unnormalize(self): | |
| 192 | + for entity in self.get_entities(): | |
| 193 | + entity.undiscretize_and_unnormalize() | |
| 194 | + | |
| 195 | + def translate(self, translation: np.ndarray): | |
| 196 | + for entity in self.get_entities(): | |
| 197 | + entity.translate(translation) | |
| 198 | + | |
| 199 | + def rotate(self, angle: float): | |
| 200 | + for entity in self.get_entities(): | |
| 201 | + entity.rotate(angle) | |
| 202 | + | |
| 203 | + def scale(self, scale: float): | |
| 204 | + for entity in self.get_entities(): | |
| 205 | + entity.scale(scale) | |
| 206 | + | |
| 207 | + def to_language_string(self): | |
| 208 | + entity_strings = [] | |
| 209 | + for entity in self.get_entities(): | |
| 210 | + entity_strings.append(entity.to_language_string()) | |
| 211 | + return "\n".join(entity_strings) |
added spatiallm/model/__init__.py +0 −0
added spatiallm/model/pcd_encoder.py +299 −0
| @@ -0,0 +1,299 @@ | ||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | +# | |
| 4 | +# This source code is licensed under the license found in the | |
| 5 | +# LICENSE file in the root directory of this source tree. | |
| 6 | + | |
| 7 | +""" | |
| 8 | +SceneScript Point Cloud Encoder | |
| 9 | + | |
| 10 | +Reference: https://github.com/facebookresearch/scenescript/blob/main/src/networks/encoder.py | |
| 11 | + | |
| 12 | +@inproceedings{avetisyan2024scenescript, | |
| 13 | + title = {SceneScript: Reconstructing Scenes With An Autoregressive Structured Language Model}, | |
| 14 | + author = {Avetisyan, Armen and Xie, Christopher and Howard-Jenkins, Henry and Yang, Tsun-Yi and Aroudj, Samir and Patra, Suvam and Zhang, Fuyang and Frost, Duncan and Holland, Luke and Orme, Campbell and Engel, Jakob and Miller, Edward and Newcombe, Richard and Balntas, Vasileios}, | |
| 15 | + booktitle = {European Conference on Computer Vision (ECCV)}, | |
| 16 | + year = {2024}, | |
| 17 | +} | |
| 18 | +""" | |
| 19 | + | |
| 20 | +import torch | |
| 21 | +import torchsparse | |
| 22 | +import torchsparse.nn as spnn | |
| 23 | +from einops import repeat | |
| 24 | + | |
| 25 | +from torch import nn | |
| 26 | +from torch.nn import functional as F | |
| 27 | + | |
| 28 | + | |
| 29 | +def make_conv3d_sparse( | |
| 30 | + channels_in, | |
| 31 | + channels_out, | |
| 32 | + kernel_size=3, | |
| 33 | + num_groups=8, | |
| 34 | + activation=spnn.ReLU, | |
| 35 | +): | |
| 36 | + num_groups = min(num_groups, channels_out) | |
| 37 | + block = nn.Sequential( | |
| 38 | + spnn.Conv3d(channels_in, channels_out, kernel_size=kernel_size, stride=1), | |
| 39 | + spnn.GroupNorm(num_groups, channels_out), | |
| 40 | + activation(inplace=True), | |
| 41 | + ) | |
| 42 | + return block | |
| 43 | + | |
| 44 | + | |
| 45 | +def make_conv3d_downscale_sparse( | |
| 46 | + channels_in, | |
| 47 | + channels_out, | |
| 48 | + num_groups=8, | |
| 49 | + activation=spnn.ReLU, | |
| 50 | +): | |
| 51 | + num_groups = min(num_groups, channels_out) | |
| 52 | + block = nn.Sequential( | |
| 53 | + spnn.Conv3d(channels_in, channels_out, kernel_size=2, stride=2), | |
| 54 | + spnn.GroupNorm(num_groups, channels_out), | |
| 55 | + activation(inplace=True), | |
| 56 | + ) | |
| 57 | + return block | |
| 58 | + | |
| 59 | + | |
| 60 | +class ResBlockSparse(nn.Module): | |
| 61 | + def __init__( | |
| 62 | + self, | |
| 63 | + channels, | |
| 64 | + num_groups=8, | |
| 65 | + activation=spnn.ReLU, | |
| 66 | + ): | |
| 67 | + super().__init__() | |
| 68 | + | |
| 69 | + self.block0 = make_conv3d_sparse( | |
| 70 | + channels, channels, num_groups=num_groups, activation=activation | |
| 71 | + ) | |
| 72 | + self.block1 = make_conv3d_sparse( | |
| 73 | + channels, channels, num_groups=num_groups, activation=activation | |
| 74 | + ) | |
| 75 | + | |
| 76 | + def forward(self, x): | |
| 77 | + out = self.block0(x) | |
| 78 | + out = self.block1(out) | |
| 79 | + return x + out | |
| 80 | + | |
| 81 | + | |
| 82 | +def index_batched_sparse_tensor(sparse_tensor, index): | |
| 83 | + """Index into a batched torchsparse.SparseTensor. | |
| 84 | + | |
| 85 | + Args: | |
| 86 | + sparse_tensor: a torchsparse.SparseTensor that is the output of | |
| 87 | + torchsparse.utils.collate.sparse_collate(). | |
| 88 | + index: int. | |
| 89 | + | |
| 90 | + Returns: | |
| 91 | + torchsparse.SparseTensor with no batch dimension. | |
| 92 | + """ | |
| 93 | + batch_mask = sparse_tensor.C[:, 0] == index | |
| 94 | + coords = sparse_tensor.C[batch_mask, 1:] # Get rid of batch dim | |
| 95 | + feats = sparse_tensor.F[batch_mask] | |
| 96 | + return torchsparse.SparseTensor( | |
| 97 | + coords=coords, | |
| 98 | + feats=feats, | |
| 99 | + stride=sparse_tensor.s, | |
| 100 | + ) | |
| 101 | + | |
| 102 | + | |
| 103 | +def sparse_uncollate(sparse_tensor): | |
| 104 | + """Un-Collate a batched torchsparse.SparseTensor. | |
| 105 | + | |
| 106 | + Args: | |
| 107 | + sparse_tensor: a torchsparse.SparseTensor that is the output of | |
| 108 | + torchsparse.utils.collate.sparse_collate(). | |
| 109 | + | |
| 110 | + Returns: | |
| 111 | + List[torchsparse.SparseTensor]. | |
| 112 | + """ | |
| 113 | + batch_size = sparse_tensor.C[:, 0].max() + 1 | |
| 114 | + | |
| 115 | + sparse_tensor_list = [] | |
| 116 | + for b in range(batch_size): | |
| 117 | + sparse_tensor_list.append(index_batched_sparse_tensor(sparse_tensor, b)) | |
| 118 | + return sparse_tensor_list | |
| 119 | + | |
| 120 | + | |
| 121 | +def vox_to_sequence(sparse_tensor): | |
| 122 | + """Compute sequence from sparse point cloud. | |
| 123 | + | |
| 124 | + Args: | |
| 125 | + sparse_tensor: torchsparse.SparseTensor. | |
| 126 | + | |
| 127 | + Returns: | |
| 128 | + Dict with the following keys: | |
| 129 | + seq: [B, maxlen, C] torch.FloatTensor. | |
| 130 | + coords: [B, maxlen, 3] torch.IntTensor. To be used with embeddings for Transformers. | |
| 131 | + mask: [B, maxlen] torch.BoolTensor. To be used with Transformers. | |
| 132 | + """ | |
| 133 | + sparse_tensor_list = sparse_uncollate(sparse_tensor) | |
| 134 | + batch_size = len(sparse_tensor_list) | |
| 135 | + channels = sparse_tensor_list[0].F.shape[-1] | |
| 136 | + maxlen = max([x.C.shape[0] for x in sparse_tensor_list]) | |
| 137 | + | |
| 138 | + seq = torch.zeros( | |
| 139 | + (batch_size, maxlen, channels), | |
| 140 | + dtype=sparse_tensor.F.dtype, | |
| 141 | + device=sparse_tensor.F.device, | |
| 142 | + ) | |
| 143 | + coords = torch.zeros( | |
| 144 | + (batch_size, maxlen, 3), | |
| 145 | + dtype=sparse_tensor.C.dtype, | |
| 146 | + device=sparse_tensor.C.device, | |
| 147 | + ) | |
| 148 | + mask = torch.ones( | |
| 149 | + (batch_size, maxlen), | |
| 150 | + dtype=torch.bool, | |
| 151 | + device=sparse_tensor.F.device, | |
| 152 | + ) | |
| 153 | + for i in range(batch_size): | |
| 154 | + sparse_tensor = sparse_tensor_list[i] | |
| 155 | + | |
| 156 | + # Get coords (divided by stride, so its in {0, 1, ...}) | |
| 157 | + coords_i = sparse_tensor.C # [N_points_i, 3] | |
| 158 | + coords_num = coords_i.shape[0] | |
| 159 | + assert coords_num <= maxlen, f"coords_num: {coords_num} is too high..." | |
| 160 | + | |
| 161 | + # Get features | |
| 162 | + feats = sparse_tensor.F # [N_points_i, C] | |
| 163 | + | |
| 164 | + # Pad and save | |
| 165 | + pad = maxlen - coords_num | |
| 166 | + | |
| 167 | + feats = F.pad(feats.T, (0, pad), value=0).T # [maxlen, C] | |
| 168 | + seq[i] = feats | |
| 169 | + | |
| 170 | + coords_i = F.pad(coords_i.T, (0, pad), value=0).T # [maxlen, 3] | |
| 171 | + coords[i] = coords_i | |
| 172 | + | |
| 173 | + mask[i, :coords_num] = False | |
| 174 | + | |
| 175 | + return { | |
| 176 | + "seq": seq, | |
| 177 | + "coords": coords, | |
| 178 | + "mask": mask, | |
| 179 | + } | |
| 180 | + | |
| 181 | + | |
| 182 | +def fourier_encode_vector(vec, num_bands=10, sample_rate=60): | |
| 183 | + """Fourier encode a vector. | |
| 184 | + | |
| 185 | + Args: | |
| 186 | + vec: [B, N, D] torch.FloatTensor. | |
| 187 | + num_bands: int. | |
| 188 | + sample_rate: int. | |
| 189 | + | |
| 190 | + Returns: | |
| 191 | + [B, N, (2 * num_bands + 1) * D] torch.FloatTensor. | |
| 192 | + """ | |
| 193 | + b, n, d = vec.shape | |
| 194 | + samples = torch.linspace(1, sample_rate / 2, num_bands).to(vec.device) * torch.pi | |
| 195 | + sines = torch.sin(samples[None, None, :, None] * vec[:, :, None, :]) | |
| 196 | + cosines = torch.cos(samples[None, None, :, None] * vec[:, :, None, :]) | |
| 197 | + | |
| 198 | + encoding = torch.stack([sines, cosines], dim=3).reshape(b, n, 2 * num_bands, d) | |
| 199 | + encoding = torch.cat([vec[:, :, None, :], encoding], dim=2) | |
| 200 | + return encoding.flatten(2) | |
| 201 | + | |
| 202 | + | |
| 203 | +class ResNet3DSparse(nn.Module): | |
| 204 | + def __init__(self, dim_in, dim_out, layers): | |
| 205 | + super().__init__() | |
| 206 | + | |
| 207 | + self.stem = nn.Sequential( | |
| 208 | + make_conv3d_sparse(dim_in, layers[0], kernel_size=7), | |
| 209 | + ResBlockSparse(layers[0]), | |
| 210 | + ) | |
| 211 | + | |
| 212 | + # Number of down-convs is len(layers) - 1 | |
| 213 | + blocks = [] | |
| 214 | + for i in range(len(layers) - 1): | |
| 215 | + blocks.append( | |
| 216 | + nn.Sequential( | |
| 217 | + make_conv3d_downscale_sparse(layers[i], layers[i + 1]), | |
| 218 | + ResBlockSparse(layers[i + 1]), | |
| 219 | + ResBlockSparse(layers[i + 1]), | |
| 220 | + ) | |
| 221 | + ) | |
| 222 | + self.blocks = nn.Sequential(*blocks) | |
| 223 | + | |
| 224 | + self.bottleneck = nn.Sequential( | |
| 225 | + nn.Linear(layers[-1], 2 * layers[-1]), | |
| 226 | + nn.GroupNorm(8, 2 * layers[-1]), # 8 is default num_groups for GroupNorm | |
| 227 | + nn.ReLU(inplace=True), | |
| 228 | + nn.Linear(2 * layers[-1], dim_out), | |
| 229 | + ) | |
| 230 | + | |
| 231 | + def forward(self, x): | |
| 232 | + out = self.stem(x) | |
| 233 | + out = self.blocks(out) | |
| 234 | + out.F = self.bottleneck(out.F) # bottleneck applied to features only | |
| 235 | + return out | |
| 236 | + | |
| 237 | + | |
| 238 | +class PointCloudEncoder(nn.Module): | |
| 239 | + def __init__( | |
| 240 | + self, | |
| 241 | + input_channels, | |
| 242 | + d_model, | |
| 243 | + conv_layers, | |
| 244 | + num_bins, | |
| 245 | + ): | |
| 246 | + """Point Cloud Encoder. | |
| 247 | + | |
| 248 | + Args: | |
| 249 | + input_channels: int. | |
| 250 | + d_model: int. | |
| 251 | + conv_layers: List[int]. | |
| 252 | + num_bins: int. | |
| 253 | + """ | |
| 254 | + | |
| 255 | + super().__init__() | |
| 256 | + | |
| 257 | + self.sparse_resnet = ResNet3DSparse( | |
| 258 | + dim_in=input_channels, | |
| 259 | + dim_out=d_model, | |
| 260 | + layers=conv_layers, | |
| 261 | + ) | |
| 262 | + downconvs = len(conv_layers) - 1 | |
| 263 | + res_reduction = 2**downconvs # voxel resolution reduction | |
| 264 | + self.reduced_grid_size = int(num_bins / res_reduction) | |
| 265 | + self.input_proj = nn.Linear(d_model + 63, d_model) # 63 for fourier encoding | |
| 266 | + | |
| 267 | + # the following is a legacy parameter | |
| 268 | + self.extra_embedding = nn.Parameter(torch.empty(d_model).normal_(std=0.02)) | |
| 269 | + | |
| 270 | + def forward(self, point_cloud: torchsparse.SparseTensor): | |
| 271 | + """Forward function. | |
| 272 | + | |
| 273 | + Args: | |
| 274 | + point_cloud: torchsparse.SparseTensor. | |
| 275 | + | |
| 276 | + Returns: a Dict with the following keys: | |
| 277 | + context: [B, maxlen, d_model] torch.FloatTensor. | |
| 278 | + context_mask: [B, maxlen] torch.BoolTensor. True means ignore. | |
| 279 | + """ | |
| 280 | + outputs = self.sparse_resnet(point_cloud) | |
| 281 | + outputs = vox_to_sequence(outputs) | |
| 282 | + | |
| 283 | + context = outputs["seq"] | |
| 284 | + context_mask = outputs["mask"] | |
| 285 | + | |
| 286 | + coords = outputs["coords"] | |
| 287 | + coords_normalised = coords / (self.reduced_grid_size - 1) | |
| 288 | + encoded_coords = fourier_encode_vector(coords_normalised) | |
| 289 | + | |
| 290 | + context = torch.cat([context, encoded_coords], dim=-1) | |
| 291 | + context = self.input_proj(context) | |
| 292 | + | |
| 293 | + # legacy parameter | |
| 294 | + context = context + repeat(self.extra_embedding, "d -> 1 1 d") | |
| 295 | + | |
| 296 | + return { | |
| 297 | + "context": context, | |
| 298 | + "context_mask": context_mask, | |
| 299 | + } |
added spatiallm/model/spatiallm_llama.py +365 −0
| @@ -0,0 +1,365 @@ | ||
| 1 | +# Copyright (c) Manycore Tech Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | + | |
| 4 | +from enum import Enum | |
| 5 | +from typing import List, Optional, Tuple, Union | |
| 6 | + | |
| 7 | +import torch | |
| 8 | +import torchsparse | |
| 9 | +import torch.utils.checkpoint | |
| 10 | +import torch.nn.functional as F | |
| 11 | +from torch import nn | |
| 12 | +from transformers import ( | |
| 13 | + LlamaModel, | |
| 14 | + LlamaForCausalLM, | |
| 15 | + AutoConfig, | |
| 16 | + AutoModelForCausalLM, | |
| 17 | +) | |
| 18 | +from torchsparse.utils.collate import sparse_collate | |
| 19 | +from transformers.utils import logging | |
| 20 | +from transformers.cache_utils import Cache | |
| 21 | +from transformers.modeling_outputs import CausalLMOutputWithPast | |
| 22 | +from transformers.models.llama.configuration_llama import LlamaConfig | |
| 23 | + | |
| 24 | +IGNORE_INDEX = -100 | |
| 25 | +logger = logging.get_logger(__name__) | |
| 26 | + | |
| 27 | + | |
| 28 | +class PointBackboneType(Enum): | |
| 29 | + SCENESCRIPT = "scenescript" | |
| 30 | + | |
| 31 | + | |
| 32 | +class SpatialLMLlamaConfig(LlamaConfig): | |
| 33 | + model_type = "spatiallm_llama" | |
| 34 | + | |
| 35 | + | |
| 36 | +class SpatialLMLlamaForCausalLM(LlamaForCausalLM): | |
| 37 | + config_class = SpatialLMLlamaConfig | |
| 38 | + | |
| 39 | + def __init__(self, config): | |
| 40 | + super().__init__(config) | |
| 41 | + self.model = LlamaModel(config) | |
| 42 | + self.vocab_size = config.vocab_size | |
| 43 | + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) | |
| 44 | + | |
| 45 | + self.point_backbone_type = PointBackboneType(config.point_backbone) | |
| 46 | + self.point_backbone = None | |
| 47 | + point_config = config.point_config | |
| 48 | + if self.point_backbone_type == PointBackboneType.SCENESCRIPT: | |
| 49 | + from spatiallm.model.pcd_encoder import PointCloudEncoder | |
| 50 | + | |
| 51 | + self.point_backbone = PointCloudEncoder( | |
| 52 | + input_channels=point_config["input_channels"], | |
| 53 | + d_model=point_config["embed_channels"], | |
| 54 | + conv_layers=point_config["conv_layers"], | |
| 55 | + num_bins=point_config["num_bins"], | |
| 56 | + ) | |
| 57 | + embed_channels = point_config["embed_channels"] | |
| 58 | + else: | |
| 59 | + raise ValueError(f"Unknown point backbone type: {self.point_backbone_type}") | |
| 60 | + | |
| 61 | + self.point_proj = nn.Linear(embed_channels, config.hidden_size) | |
| 62 | + | |
| 63 | + self.point_start_token_id = self.config.point_start_token_id | |
| 64 | + self.point_end_token_id = self.config.point_end_token_id | |
| 65 | + self.point_token_id = self.config.point_token_id | |
| 66 | + | |
| 67 | + # Initialize weights and apply final processing | |
| 68 | + self.post_init() | |
| 69 | + | |
| 70 | + def forward_point_cloud(self, point_cloud, device, dtype): | |
| 71 | + # point cloud has shape (n_points, n_features) | |
| 72 | + # find the points that have nan values | |
| 73 | + self.point_backbone.to(torch.float32) | |
| 74 | + nan_mask = torch.isnan(point_cloud).any(dim=1) | |
| 75 | + point_cloud = point_cloud[~nan_mask] | |
| 76 | + coords = point_cloud[:, :3].int() | |
| 77 | + feats = point_cloud[:, 3:].float() | |
| 78 | + if self.point_backbone_type == PointBackboneType.SCENESCRIPT: | |
| 79 | + pc_sparse_tensor = torchsparse.SparseTensor(coords=coords, feats=feats) | |
| 80 | + pc_sparse_tensor = sparse_collate([pc_sparse_tensor]) # batch_size = 1 | |
| 81 | + pc_sparse_tensor = pc_sparse_tensor.to(device) | |
| 82 | + encoded_features = self.point_backbone(pc_sparse_tensor) | |
| 83 | + return self.point_proj(encoded_features["context"].to(dtype)) | |
| 84 | + else: | |
| 85 | + raise ValueError(f"Unknown point backbone type: {self.point_backbone_type}") | |
| 86 | + | |
| 87 | + def set_point_backbone_dtype(self, dtype: torch.dtype): | |
| 88 | + for param in self.point_backbone.parameters(): | |
| 89 | + param.data = param.data.to(dtype) | |
| 90 | + | |
| 91 | + def get_model(self): | |
| 92 | + return self.model | |
| 93 | + | |
| 94 | + def forward( | |
| 95 | + self, | |
| 96 | + input_ids: torch.LongTensor = None, | |
| 97 | + attention_mask: Optional[torch.Tensor] = None, | |
| 98 | + position_ids: Optional[torch.LongTensor] = None, | |
| 99 | + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, | |
| 100 | + inputs_embeds: Optional[torch.FloatTensor] = None, | |
| 101 | + labels: Optional[torch.LongTensor] = None, | |
| 102 | + use_cache: Optional[bool] = None, | |
| 103 | + output_attentions: Optional[bool] = None, | |
| 104 | + output_hidden_states: Optional[bool] = None, | |
| 105 | + return_dict: Optional[bool] = None, | |
| 106 | + cache_position: Optional[torch.LongTensor] = None, | |
| 107 | + num_logits_to_keep: int = 0, | |
| 108 | + point_clouds: Optional[torch.Tensor] = None, | |
| 109 | + **loss_kwargs, | |
| 110 | + ) -> Union[Tuple, CausalLMOutputWithPast]: | |
| 111 | + r""" | |
| 112 | + Args: | |
| 113 | + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): | |
| 114 | + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., | |
| 115 | + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored | |
| 116 | + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. | |
| 117 | + | |
| 118 | + point_clouds (`torch.Tensor` of shape `(batch_size, n_points, n_features)`, *optional*): | |
| 119 | + Point clouds to be used for the point cloud encoder. | |
| 120 | + | |
| 121 | + num_logits_to_keep (`int`, *optional*): | |
| 122 | + Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all | |
| 123 | + `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that | |
| 124 | + token can save memory, which becomes pretty significant for long sequences or large vocabulary size. | |
| 125 | + | |
| 126 | + Returns: | |
| 127 | + | |
| 128 | + Example: | |
| 129 | + | |
| 130 | + ```python | |
| 131 | + >>> from transformers import AutoTokenizer, AutoModelForCausalLM | |
| 132 | + | |
| 133 | + >>> model = AutoModelForCausalLM.from_pretrained("manycore-research/SpatialLM-Llama-1B") | |
| 134 | + >>> tokenizer = AutoTokenizer.from_pretrained("manycore-research/SpatialLM-Llama-1B") | |
| 135 | + | |
| 136 | + >>> prompt = "<|point_start|><|point_pad|><|point_end|>Detect walls, doors, windows, boxes. The reference code is as followed: {code_template}" | |
| 137 | + >>> conversation = [{"role": "user", "content": prompt}] | |
| 138 | + >>> input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt") | |
| 139 | + | |
| 140 | + >>> # Generate | |
| 141 | + >>> generate_ids = model.generate(input_ids, point_clouds=point_clouds, max_length=4096) | |
| 142 | + >>> tokenizer.batch_decode(generate_ids, skip_prompt=True, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] | |
| 143 | + ```""" | |
| 144 | + output_attentions = ( | |
| 145 | + output_attentions | |
| 146 | + if output_attentions is not None | |
| 147 | + else self.config.output_attentions | |
| 148 | + ) | |
| 149 | + output_hidden_states = ( | |
| 150 | + output_hidden_states | |
| 151 | + if output_hidden_states is not None | |
| 152 | + else self.config.output_hidden_states | |
| 153 | + ) | |
| 154 | + return_dict = ( | |
| 155 | + return_dict if return_dict is not None else self.config.use_return_dict | |
| 156 | + ) | |
| 157 | + | |
| 158 | + # compute point cloud embeddings | |
| 159 | + if inputs_embeds is None: | |
| 160 | + inputs_embeds = self.model.embed_tokens(input_ids) | |
| 161 | + | |
| 162 | + if ( | |
| 163 | + self.point_backbone is not None | |
| 164 | + and (input_ids.shape[1] != 1 or self.training) | |
| 165 | + and point_clouds is not None | |
| 166 | + ): | |
| 167 | + n_point_clouds = point_clouds.shape[0] | |
| 168 | + point_features = [] | |
| 169 | + for i in range(n_point_clouds): # * iterate over batch | |
| 170 | + point_cloud = point_clouds[i] | |
| 171 | + point_feature = self.forward_point_cloud( | |
| 172 | + point_cloud, inputs_embeds.device, inputs_embeds.dtype | |
| 173 | + ) | |
| 174 | + point_features.append(point_feature) | |
| 175 | + | |
| 176 | + # Insert point cloud features into the input ids | |
| 177 | + point_start_end_token_pos = [] | |
| 178 | + new_input_embeds = [] | |
| 179 | + new_attention_mask = [] | |
| 180 | + cur_point_idx = 0 | |
| 181 | + max_num_tokens = 0 | |
| 182 | + for cur_input_ids, cur_input_embeds, cur_attention_mask in zip( | |
| 183 | + input_ids, inputs_embeds, attention_mask | |
| 184 | + ): # * input_ids: B, L; input_embeds: B, L, C | |
| 185 | + cur_point_features = ( | |
| 186 | + point_features[cur_point_idx] | |
| 187 | + .to(device=cur_input_embeds.device) | |
| 188 | + .squeeze(0) | |
| 189 | + ) | |
| 190 | + num_patches = cur_point_features.shape[0] # * number of point tokens | |
| 191 | + num_point_start_tokens = ( | |
| 192 | + (cur_input_ids == self.config.point_start_token_id).sum().item() | |
| 193 | + ) | |
| 194 | + num_point_end_tokens = ( | |
| 195 | + (cur_input_ids == self.config.point_end_token_id).sum().item() | |
| 196 | + ) | |
| 197 | + # currently, we only support one point start and one point end token | |
| 198 | + assert num_point_start_tokens == num_point_end_tokens == 1, ( | |
| 199 | + "The number of point start tokens and point end tokens should be 1, " | |
| 200 | + f"but got {num_point_start_tokens} and {num_point_end_tokens}." | |
| 201 | + ) | |
| 202 | + point_start_token_pos = torch.where( | |
| 203 | + cur_input_ids == self.config.point_start_token_id | |
| 204 | + )[0][0] | |
| 205 | + point_end_token_pos = torch.where( | |
| 206 | + cur_input_ids == self.config.point_end_token_id | |
| 207 | + )[0][0] | |
| 208 | + cur_new_input_embeds = torch.cat( | |
| 209 | + ( | |
| 210 | + cur_input_embeds[: point_start_token_pos + 1], | |
| 211 | + cur_point_features, | |
| 212 | + cur_input_embeds[point_end_token_pos:], | |
| 213 | + ), | |
| 214 | + dim=0, | |
| 215 | + ) | |
| 216 | + cur_new_attention_mask = torch.cat( | |
| 217 | + ( | |
| 218 | + cur_attention_mask[: point_start_token_pos + 1], | |
| 219 | + torch.ones(num_patches, device=cur_attention_mask.device), | |
| 220 | + cur_attention_mask[point_end_token_pos:], | |
| 221 | + ), | |
| 222 | + dim=0, | |
| 223 | + ) | |
| 224 | + | |
| 225 | + cur_point_idx += 1 | |
| 226 | + new_input_embeds.append(cur_new_input_embeds) | |
| 227 | + new_attention_mask.append(cur_new_attention_mask) | |
| 228 | + point_start_end_token_pos.append( | |
| 229 | + (point_start_token_pos, num_patches, point_end_token_pos) | |
| 230 | + ) | |
| 231 | + if cur_new_input_embeds.shape[0] > max_num_tokens: | |
| 232 | + max_num_tokens = cur_new_input_embeds.shape[0] | |
| 233 | + # pad the new input embeds and attention mask to the max dimension | |
| 234 | + for i in range(len(new_input_embeds)): | |
| 235 | + cur_input_embeds = new_input_embeds[i] | |
| 236 | + last_row = cur_input_embeds[-1] | |
| 237 | + padding = last_row.repeat(max_num_tokens - cur_input_embeds.shape[0], 1) | |
| 238 | + new_input_embeds[i] = torch.cat([cur_input_embeds, padding], dim=0) | |
| 239 | + | |
| 240 | + cur_attention_mask = new_attention_mask[i] | |
| 241 | + new_attention_mask[i] = F.pad( | |
| 242 | + cur_attention_mask, | |
| 243 | + (0, max_num_tokens - cur_attention_mask.shape[0]), | |
| 244 | + value=0, | |
| 245 | + ) | |
| 246 | + inputs_embeds = torch.stack(new_input_embeds, dim=0) | |
| 247 | + attention_mask = torch.stack(new_attention_mask, dim=0) | |
| 248 | + | |
| 249 | + assert ( | |
| 250 | + attention_mask.shape[1] == inputs_embeds.shape[1] | |
| 251 | + ), "The length of attention mask and inputs embeds should be the same" | |
| 252 | + | |
| 253 | + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) | |
| 254 | + outputs = self.model( | |
| 255 | + input_ids=None, | |
| 256 | + attention_mask=attention_mask, | |
| 257 | + position_ids=position_ids, | |
| 258 | + past_key_values=past_key_values, | |
| 259 | + inputs_embeds=inputs_embeds, | |
| 260 | + use_cache=use_cache, | |
| 261 | + output_attentions=output_attentions, | |
| 262 | + output_hidden_states=output_hidden_states, | |
| 263 | + return_dict=return_dict, | |
| 264 | + cache_position=cache_position, | |
| 265 | + ) | |
| 266 | + | |
| 267 | + hidden_states = outputs[0] | |
| 268 | + if self.config.pretraining_tp > 1: | |
| 269 | + lm_head_slices = self.lm_head.weight.split( | |
| 270 | + self.vocab_size // self.config.pretraining_tp, dim=0 | |
| 271 | + ) | |
| 272 | + logits = [ | |
| 273 | + F.linear(hidden_states, lm_head_slices[i]) | |
| 274 | + for i in range(self.config.pretraining_tp) | |
| 275 | + ] | |
| 276 | + logits = torch.cat(logits, dim=-1) | |
| 277 | + else: | |
| 278 | + # Only compute necessary logits, and do not upcast them to float if we are not computing the loss | |
| 279 | + logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]) | |
| 280 | + | |
| 281 | + loss = None | |
| 282 | + if labels is not None: | |
| 283 | + # prepare new labels | |
| 284 | + new_labels = [] | |
| 285 | + max_num_tokens = logits.shape[1] | |
| 286 | + for i in range(len(point_start_end_token_pos)): | |
| 287 | + cur_labels = labels[i] | |
| 288 | + ( | |
| 289 | + cur_point_start_token_pos, | |
| 290 | + num_patches, | |
| 291 | + cur_point_end_token_pos, | |
| 292 | + ) = point_start_end_token_pos[i] | |
| 293 | + cur_new_labels = torch.cat( | |
| 294 | + ( | |
| 295 | + cur_labels[: cur_point_start_token_pos + 1], | |
| 296 | + torch.full( | |
| 297 | + (num_patches,), | |
| 298 | + IGNORE_INDEX, | |
| 299 | + device=cur_labels.device, | |
| 300 | + ), | |
| 301 | + cur_labels[cur_point_end_token_pos:], | |
| 302 | + ), | |
| 303 | + dim=0, | |
| 304 | + ) | |
| 305 | + cur_new_labels = F.pad( | |
| 306 | + cur_new_labels, | |
| 307 | + (0, max_num_tokens - cur_new_labels.shape[0]), | |
| 308 | + value=IGNORE_INDEX, | |
| 309 | + ) | |
| 310 | + new_labels.append(cur_new_labels) | |
| 311 | + labels = torch.stack(new_labels, dim=0) | |
| 312 | + | |
| 313 | + assert ( | |
| 314 | + labels.shape[1] == logits.shape[1] | |
| 315 | + ), "The length of labels and logits should be the same" | |
| 316 | + | |
| 317 | + loss = self.loss_function( | |
| 318 | + logits=logits, | |
| 319 | + labels=labels, | |
| 320 | + vocab_size=self.config.vocab_size, | |
| 321 | + **loss_kwargs, | |
| 322 | + ) | |
| 323 | + | |
| 324 | + if not return_dict: | |
| 325 | + output = (logits,) + outputs[1:] | |
| 326 | + return (loss,) + output if loss is not None else output | |
| 327 | + | |
| 328 | + return CausalLMOutputWithPast( | |
| 329 | + loss=loss, | |
| 330 | + logits=logits, | |
| 331 | + past_key_values=outputs.past_key_values, | |
| 332 | + hidden_states=outputs.hidden_states, | |
| 333 | + attentions=outputs.attentions, | |
| 334 | + ) | |
| 335 | + | |
| 336 | + def prepare_inputs_for_generation( | |
| 337 | + self, | |
| 338 | + input_ids, | |
| 339 | + past_key_values=None, | |
| 340 | + attention_mask=None, | |
| 341 | + inputs_embeds=None, | |
| 342 | + **kwargs, | |
| 343 | + ): | |
| 344 | + if past_key_values: | |
| 345 | + input_ids = input_ids[:, -1:] | |
| 346 | + | |
| 347 | + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step | |
| 348 | + if inputs_embeds is not None and past_key_values is None: | |
| 349 | + model_inputs = {"inputs_embeds": inputs_embeds} | |
| 350 | + else: | |
| 351 | + model_inputs = {"input_ids": input_ids} | |
| 352 | + | |
| 353 | + model_inputs.update( | |
| 354 | + { | |
| 355 | + "past_key_values": past_key_values, | |
| 356 | + "use_cache": kwargs.get("use_cache"), | |
| 357 | + "attention_mask": attention_mask, | |
| 358 | + "point_clouds": kwargs.get("point_clouds", None), | |
| 359 | + } | |
| 360 | + ) | |
| 361 | + return model_inputs | |
| 362 | + | |
| 363 | + | |
| 364 | +AutoConfig.register("spatiallm_llama", SpatialLMLlamaConfig) | |
| 365 | +AutoModelForCausalLM.register(SpatialLMLlamaConfig, SpatialLMLlamaForCausalLM) |
added spatiallm/model/spatiallm_qwen.py +355 −0
| @@ -0,0 +1,355 @@ | ||
| 1 | +# Copyright (c) Manycore Tech Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | + | |
| 4 | +from enum import Enum | |
| 5 | +from typing import List, Optional, Tuple, Union | |
| 6 | + | |
| 7 | +import torch | |
| 8 | +import torchsparse | |
| 9 | +import torch.utils.checkpoint | |
| 10 | +import torch.nn.functional as F | |
| 11 | +from torch import nn | |
| 12 | +from transformers import ( | |
| 13 | + Qwen2Model, | |
| 14 | + Qwen2ForCausalLM, | |
| 15 | + AutoConfig, | |
| 16 | + AutoModelForCausalLM, | |
| 17 | +) | |
| 18 | +from torchsparse.utils.collate import sparse_collate | |
| 19 | +from transformers.utils import logging | |
| 20 | +from transformers.cache_utils import Cache | |
| 21 | +from transformers.modeling_outputs import CausalLMOutputWithPast | |
| 22 | +from transformers.models.qwen2.configuration_qwen2 import Qwen2Config | |
| 23 | + | |
| 24 | +IGNORE_INDEX = -100 | |
| 25 | +logger = logging.get_logger(__name__) | |
| 26 | + | |
| 27 | + | |
| 28 | +class PointBackboneType(Enum): | |
| 29 | + SCENESCRIPT = "scenescript" | |
| 30 | + | |
| 31 | + | |
| 32 | +class SpatialLMQwenConfig(Qwen2Config): | |
| 33 | + model_type = "spatiallm_qwen" | |
| 34 | + | |
| 35 | + | |
| 36 | +class SpatialLMQwenForCausalLM(Qwen2ForCausalLM): | |
| 37 | + config_class = SpatialLMQwenConfig | |
| 38 | + | |
| 39 | + def __init__(self, config): | |
| 40 | + super().__init__(config) | |
| 41 | + self.model = Qwen2Model(config) | |
| 42 | + self.vocab_size = config.vocab_size | |
| 43 | + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) | |
| 44 | + | |
| 45 | + self.point_backbone_type = PointBackboneType(config.point_backbone) | |
| 46 | + self.point_backbone = None | |
| 47 | + point_config = config.point_config | |
| 48 | + if self.point_backbone_type == PointBackboneType.SCENESCRIPT: | |
| 49 | + from spatiallm.model.pcd_encoder import PointCloudEncoder | |
| 50 | + | |
| 51 | + self.point_backbone = PointCloudEncoder( | |
| 52 | + input_channels=point_config["input_channels"], | |
| 53 | + d_model=point_config["embed_channels"], | |
| 54 | + conv_layers=point_config["conv_layers"], | |
| 55 | + num_bins=point_config["num_bins"], | |
| 56 | + ) | |
| 57 | + embed_channels = point_config["embed_channels"] | |
| 58 | + else: | |
| 59 | + raise ValueError(f"Unknown point backbone type: {self.point_backbone_type}") | |
| 60 | + | |
| 61 | + self.point_proj = nn.Linear(embed_channels, config.hidden_size) | |
| 62 | + | |
| 63 | + self.point_start_token_id = self.config.point_start_token_id | |
| 64 | + self.point_end_token_id = self.config.point_end_token_id | |
| 65 | + self.point_token_id = self.config.point_token_id | |
| 66 | + | |
| 67 | + # Initialize weights and apply final processing | |
| 68 | + self.post_init() | |
| 69 | + | |
| 70 | + def forward_point_cloud(self, point_cloud, device, dtype): | |
| 71 | + # point cloud has shape (n_points, n_features) | |
| 72 | + # find the points that have nan values | |
| 73 | + self.point_backbone.to(torch.float32) | |
| 74 | + nan_mask = torch.isnan(point_cloud).any(dim=1) | |
| 75 | + point_cloud = point_cloud[~nan_mask] | |
| 76 | + coords = point_cloud[:, :3].int() | |
| 77 | + feats = point_cloud[:, 3:].float() | |
| 78 | + if self.point_backbone_type == PointBackboneType.SCENESCRIPT: | |
| 79 | + pc_sparse_tensor = torchsparse.SparseTensor(coords=coords, feats=feats) | |
| 80 | + pc_sparse_tensor = sparse_collate([pc_sparse_tensor]) # batch_size = 1 | |
| 81 | + pc_sparse_tensor = pc_sparse_tensor.to(device) | |
| 82 | + encoded_features = self.point_backbone(pc_sparse_tensor) | |
| 83 | + return self.point_proj(encoded_features["context"].to(dtype)) | |
| 84 | + else: | |
| 85 | + raise ValueError(f"Unknown point backbone type: {self.point_backbone_type}") | |
| 86 | + | |
| 87 | + def set_point_backbone_dtype(self, dtype: torch.dtype): | |
| 88 | + for param in self.point_backbone.parameters(): | |
| 89 | + param.data = param.data.to(dtype) | |
| 90 | + | |
| 91 | + def get_model(self): | |
| 92 | + return self.model | |
| 93 | + | |
| 94 | + def forward( | |
| 95 | + self, | |
| 96 | + input_ids: torch.LongTensor = None, | |
| 97 | + attention_mask: Optional[torch.Tensor] = None, | |
| 98 | + position_ids: Optional[torch.LongTensor] = None, | |
| 99 | + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, | |
| 100 | + inputs_embeds: Optional[torch.FloatTensor] = None, | |
| 101 | + labels: Optional[torch.LongTensor] = None, | |
| 102 | + use_cache: Optional[bool] = None, | |
| 103 | + output_attentions: Optional[bool] = None, | |
| 104 | + output_hidden_states: Optional[bool] = None, | |
| 105 | + return_dict: Optional[bool] = None, | |
| 106 | + cache_position: Optional[torch.LongTensor] = None, | |
| 107 | + num_logits_to_keep: int = 0, | |
| 108 | + point_clouds: Optional[torch.Tensor] = None, | |
| 109 | + **loss_kwargs, | |
| 110 | + ) -> Union[Tuple, CausalLMOutputWithPast]: | |
| 111 | + r""" | |
| 112 | + Args: | |
| 113 | + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): | |
| 114 | + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., | |
| 115 | + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored | |
| 116 | + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. | |
| 117 | + | |
| 118 | + point_clouds (`torch.Tensor` of shape `(batch_size, n_points, n_features)`, *optional*): | |
| 119 | + Point clouds to be used for the point cloud encoder. | |
| 120 | + | |
| 121 | + num_logits_to_keep (`int`, *optional*): | |
| 122 | + Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all | |
| 123 | + `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that | |
| 124 | + token can save memory, which becomes pretty significant for long sequences or large vocabulary size. | |
| 125 | + | |
| 126 | + Returns: | |
| 127 | + | |
| 128 | + Example: | |
| 129 | + | |
| 130 | + ```python | |
| 131 | + >>> from transformers import AutoTokenizer, AutoModelForCausalLM | |
| 132 | + | |
| 133 | + >>> model = AutoModelForCausalLM.from_pretrained("manycore-research/SpatialLM-Qwen-0.5B") | |
| 134 | + >>> tokenizer = AutoTokenizer.from_pretrained("manycore-research/SpatialLM-Qwen-0.5B") | |
| 135 | + | |
| 136 | + >>> prompt = "<|point_start|><|point_pad|><|point_end|>Detect walls, doors, windows, boxes. The reference code is as followed: {code_template}" | |
| 137 | + >>> conversation = [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": prompt}] | |
| 138 | + >>> input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt") | |
| 139 | + | |
| 140 | + >>> # Generate | |
| 141 | + >>> generate_ids = model.generate(input_ids, point_clouds=point_clouds, max_length=4096) | |
| 142 | + >>> tokenizer.batch_decode(generate_ids, skip_prompt=True, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] | |
| 143 | + ```""" | |
| 144 | + output_attentions = ( | |
| 145 | + output_attentions | |
| 146 | + if output_attentions is not None | |
| 147 | + else self.config.output_attentions | |
| 148 | + ) | |
| 149 | + output_hidden_states = ( | |
| 150 | + output_hidden_states | |
| 151 | + if output_hidden_states is not None | |
| 152 | + else self.config.output_hidden_states | |
| 153 | + ) | |
| 154 | + return_dict = ( | |
| 155 | + return_dict if return_dict is not None else self.config.use_return_dict | |
| 156 | + ) | |
| 157 | + | |
| 158 | + # compute point cloud embeddings | |
| 159 | + if inputs_embeds is None: | |
| 160 | + inputs_embeds = self.model.embed_tokens(input_ids) | |
| 161 | + | |
| 162 | + if ( | |
| 163 | + self.point_backbone is not None | |
| 164 | + and (input_ids.shape[1] != 1 or self.training) | |
| 165 | + and point_clouds is not None | |
| 166 | + ): | |
| 167 | + n_point_clouds = point_clouds.shape[0] | |
| 168 | + point_features = [] | |
| 169 | + for i in range(n_point_clouds): # * iterate over batch | |
| 170 | + point_cloud = point_clouds[i] | |
| 171 | + point_feature = self.forward_point_cloud( | |
| 172 | + point_cloud, inputs_embeds.device, inputs_embeds.dtype | |
| 173 | + ) | |
| 174 | + point_features.append(point_feature) | |
| 175 | + | |
| 176 | + # Insert point cloud features into the input ids | |
| 177 | + point_start_end_token_pos = [] | |
| 178 | + new_input_embeds = [] | |
| 179 | + new_attention_mask = [] | |
| 180 | + cur_point_idx = 0 | |
| 181 | + max_num_tokens = 0 | |
| 182 | + for cur_input_ids, cur_input_embeds, cur_attention_mask in zip( | |
| 183 | + input_ids, inputs_embeds, attention_mask | |
| 184 | + ): # * input_ids: B, L; input_embeds: B, L, C | |
| 185 | + cur_point_features = ( | |
| 186 | + point_features[cur_point_idx] | |
| 187 | + .to(device=cur_input_embeds.device) | |
| 188 | + .squeeze(0) | |
| 189 | + ) | |
| 190 | + num_patches = cur_point_features.shape[0] # * number of point tokens | |
| 191 | + num_point_start_tokens = ( | |
| 192 | + (cur_input_ids == self.config.point_start_token_id).sum().item() | |
| 193 | + ) | |
| 194 | + num_point_end_tokens = ( | |
| 195 | + (cur_input_ids == self.config.point_end_token_id).sum().item() | |
| 196 | + ) | |
| 197 | + # currently, we only support one point start and one point end token | |
| 198 | + assert num_point_start_tokens == num_point_end_tokens == 1, ( | |
| 199 | + "The number of point start tokens and point end tokens should be 1, " | |
| 200 | + f"but got {num_point_start_tokens} and {num_point_end_tokens}." | |
| 201 | + ) | |
| 202 | + point_start_token_pos = torch.where( | |
| 203 | + cur_input_ids == self.config.point_start_token_id | |
| 204 | + )[0][0] | |
| 205 | + point_end_token_pos = torch.where( | |
| 206 | + cur_input_ids == self.config.point_end_token_id | |
| 207 | + )[0][0] | |
| 208 | + cur_new_input_embeds = torch.cat( | |
| 209 | + ( | |
| 210 | + cur_input_embeds[: point_start_token_pos + 1], | |
| 211 | + cur_point_features, | |
| 212 | + cur_input_embeds[point_end_token_pos:], | |
| 213 | + ), | |
| 214 | + dim=0, | |
| 215 | + ) | |
| 216 | + cur_new_attention_mask = torch.cat( | |
| 217 | + ( | |
| 218 | + cur_attention_mask[: point_start_token_pos + 1], | |
| 219 | + torch.ones(num_patches, device=cur_attention_mask.device), | |
| 220 | + cur_attention_mask[point_end_token_pos:], | |
| 221 | + ), | |
| 222 | + dim=0, | |
| 223 | + ) | |
| 224 | + | |
| 225 | + cur_point_idx += 1 | |
| 226 | + new_input_embeds.append(cur_new_input_embeds) | |
| 227 | + new_attention_mask.append(cur_new_attention_mask) | |
| 228 | + point_start_end_token_pos.append( | |
| 229 | + (point_start_token_pos, num_patches, point_end_token_pos) | |
| 230 | + ) | |
| 231 | + if cur_new_input_embeds.shape[0] > max_num_tokens: | |
| 232 | + max_num_tokens = cur_new_input_embeds.shape[0] | |
| 233 | + # pad the new input embeds and attention mask to the max dimension | |
| 234 | + for i in range(len(new_input_embeds)): | |
| 235 | + cur_input_embeds = new_input_embeds[i] | |
| 236 | + last_row = cur_input_embeds[-1] | |
| 237 | + padding = last_row.repeat(max_num_tokens - cur_input_embeds.shape[0], 1) | |
| 238 | + new_input_embeds[i] = torch.cat([cur_input_embeds, padding], dim=0) | |
| 239 | + | |
| 240 | + cur_attention_mask = new_attention_mask[i] | |
| 241 | + new_attention_mask[i] = F.pad( | |
| 242 | + cur_attention_mask, | |
| 243 | + (0, max_num_tokens - cur_attention_mask.shape[0]), | |
| 244 | + value=0, | |
| 245 | + ) | |
| 246 | + inputs_embeds = torch.stack(new_input_embeds, dim=0) | |
| 247 | + attention_mask = torch.stack(new_attention_mask, dim=0) | |
| 248 | + | |
| 249 | + assert ( | |
| 250 | + attention_mask.shape[1] == inputs_embeds.shape[1] | |
| 251 | + ), "The length of attention mask and inputs embeds should be the same" | |
| 252 | + | |
| 253 | + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) | |
| 254 | + outputs = self.model( | |
| 255 | + input_ids=None, | |
| 256 | + attention_mask=attention_mask, | |
| 257 | + position_ids=position_ids, | |
| 258 | + past_key_values=past_key_values, | |
| 259 | + inputs_embeds=inputs_embeds, | |
| 260 | + use_cache=use_cache, | |
| 261 | + output_attentions=output_attentions, | |
| 262 | + output_hidden_states=output_hidden_states, | |
| 263 | + return_dict=return_dict, | |
| 264 | + cache_position=cache_position, | |
| 265 | + ) | |
| 266 | + | |
| 267 | + hidden_states = outputs[0] | |
| 268 | + # Only compute necessary logits, and do not upcast them to float if we are not computing the loss | |
| 269 | + logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]) | |
| 270 | + | |
| 271 | + loss = None | |
| 272 | + if labels is not None: | |
| 273 | + # prepare new labels | |
| 274 | + new_labels = [] | |
| 275 | + max_num_tokens = logits.shape[1] | |
| 276 | + for i in range(len(point_start_end_token_pos)): | |
| 277 | + cur_labels = labels[i] | |
| 278 | + ( | |
| 279 | + cur_point_start_token_pos, | |
| 280 | + num_patches, | |
| 281 | + cur_point_end_token_pos, | |
| 282 | + ) = point_start_end_token_pos[i] | |
| 283 | + cur_new_labels = torch.cat( | |
| 284 | + ( | |
| 285 | + cur_labels[: cur_point_start_token_pos + 1], | |
| 286 | + torch.full( | |
| 287 | + (num_patches,), | |
| 288 | + IGNORE_INDEX, | |
| 289 | + device=cur_labels.device, | |
| 290 | + ), | |
| 291 | + cur_labels[cur_point_end_token_pos:], | |
| 292 | + ), | |
| 293 | + dim=0, | |
| 294 | + ) | |
| 295 | + cur_new_labels = F.pad( | |
| 296 | + cur_new_labels, | |
| 297 | + (0, max_num_tokens - cur_new_labels.shape[0]), | |
| 298 | + value=IGNORE_INDEX, | |
| 299 | + ) | |
| 300 | + new_labels.append(cur_new_labels) | |
| 301 | + labels = torch.stack(new_labels, dim=0) | |
| 302 | + | |
| 303 | + assert ( | |
| 304 | + labels.shape[1] == logits.shape[1] | |
| 305 | + ), "The length of labels and logits should be the same" | |
| 306 | + | |
| 307 | + loss = self.loss_function( | |
| 308 | + logits=logits, | |
| 309 | + labels=labels, | |
| 310 | + vocab_size=self.config.vocab_size, | |
| 311 | + **loss_kwargs, | |
| 312 | + ) | |
| 313 | + | |
| 314 | + if not return_dict: | |
| 315 | + output = (logits,) + outputs[1:] | |
| 316 | + return (loss,) + output if loss is not None else output | |
| 317 | + | |
| 318 | + return CausalLMOutputWithPast( | |
| 319 | + loss=loss, | |
| 320 | + logits=logits, | |
| 321 | + past_key_values=outputs.past_key_values, | |
| 322 | + hidden_states=outputs.hidden_states, | |
| 323 | + attentions=outputs.attentions, | |
| 324 | + ) | |
| 325 | + | |
| 326 | + def prepare_inputs_for_generation( | |
| 327 | + self, | |
| 328 | + input_ids, | |
| 329 | + past_key_values=None, | |
| 330 | + attention_mask=None, | |
| 331 | + inputs_embeds=None, | |
| 332 | + **kwargs, | |
| 333 | + ): | |
| 334 | + if past_key_values: | |
| 335 | + input_ids = input_ids[:, -1:] | |
| 336 | + | |
| 337 | + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step | |
| 338 | + if inputs_embeds is not None and past_key_values is None: | |
| 339 | + model_inputs = {"inputs_embeds": inputs_embeds} | |
| 340 | + else: | |
| 341 | + model_inputs = {"input_ids": input_ids} | |
| 342 | + | |
| 343 | + model_inputs.update( | |
| 344 | + { | |
| 345 | + "past_key_values": past_key_values, | |
| 346 | + "use_cache": kwargs.get("use_cache"), | |
| 347 | + "attention_mask": attention_mask, | |
| 348 | + "point_clouds": kwargs.get("point_clouds", None), | |
| 349 | + } | |
| 350 | + ) | |
| 351 | + return model_inputs | |
| 352 | + | |
| 353 | + | |
| 354 | +AutoConfig.register("spatiallm_qwen", SpatialLMQwenConfig) | |
| 355 | +AutoModelForCausalLM.register(SpatialLMQwenConfig, SpatialLMQwenForCausalLM) |
added spatiallm/pcd/__init__.py +8 −0
| @@ -0,0 +1,8 @@ | ||
| 1 | +from .pcd_loader import load_o3d_pcd, get_points_and_colors, cleanup_pcd, Compose | |
| 2 | + | |
| 3 | +__all__ = [ | |
| 4 | + "load_o3d_pcd", | |
| 5 | + "get_points_and_colors", | |
| 6 | + "cleanup_pcd", | |
| 7 | + "Compose", | |
| 8 | +] |
added spatiallm/pcd/pcd_loader.py +216 −0
| @@ -0,0 +1,216 @@ | ||
| 1 | +import logging | |
| 2 | +import numpy as np | |
| 3 | +import open3d as o3d | |
| 4 | + | |
| 5 | +from spatiallm.pcd.registry import Registry | |
| 6 | + | |
| 7 | +TRANSFORMS = Registry("transforms") | |
| 8 | +log = logging.getLogger(__name__) | |
| 9 | + | |
| 10 | +""" | |
| 11 | +3D Point Cloud Preprocessing | |
| 12 | + | |
| 13 | +Reference: PointCept | |
| 14 | + | |
| 15 | +@misc{pointcept2023, | |
| 16 | + title={Pointcept: A Codebase for Point Cloud Perception Research}, | |
| 17 | + author={Pointcept Contributors}, | |
| 18 | + year={2023} | |
| 19 | +} | |
| 20 | +""" | |
| 21 | + | |
| 22 | + | |
| 23 | +class Compose(object): | |
| 24 | + def __init__(self, cfg=None): | |
| 25 | + self.cfg = cfg if cfg is not None else [] | |
| 26 | + self.transforms = [] | |
| 27 | + for t_cfg in self.cfg: | |
| 28 | + self.transforms.append(TRANSFORMS.build(t_cfg)) | |
| 29 | + | |
| 30 | + def __call__(self, data_dict): | |
| 31 | + for t in self.transforms: | |
| 32 | + data_dict = t(data_dict) | |
| 33 | + return data_dict | |
| 34 | + | |
| 35 | + | |
| 36 | +@TRANSFORMS.register_module() | |
| 37 | +class PositiveShift(object): | |
| 38 | + def __call__(self, data_dict): | |
| 39 | + if "coord" in data_dict.keys(): | |
| 40 | + coord_min = np.min(data_dict["coord"], 0) | |
| 41 | + data_dict["coord"] -= coord_min | |
| 42 | + return data_dict | |
| 43 | + | |
| 44 | + | |
| 45 | +@TRANSFORMS.register_module() | |
| 46 | +class NormalizeColor(object): | |
| 47 | + def __call__(self, data_dict): | |
| 48 | + if "color" in data_dict.keys(): | |
| 49 | + data_dict["color"] = data_dict["color"] / 127.5 - 1 | |
| 50 | + return data_dict | |
| 51 | + | |
| 52 | + | |
| 53 | +@TRANSFORMS.register_module() | |
| 54 | +class GridSample(object): | |
| 55 | + def __init__( | |
| 56 | + self, | |
| 57 | + grid_size=0.05, | |
| 58 | + hash_type="fnv", | |
| 59 | + mode="train", | |
| 60 | + keys=("coord", "color", "normal", "segment"), | |
| 61 | + return_inverse=False, | |
| 62 | + return_grid_coord=False, | |
| 63 | + return_min_coord=False, | |
| 64 | + return_displacement=False, | |
| 65 | + project_displacement=False, | |
| 66 | + max_grid_coord=None, | |
| 67 | + ): | |
| 68 | + self.grid_size = grid_size | |
| 69 | + self.hash = self.fnv_hash_vec if hash_type == "fnv" else self.ravel_hash_vec | |
| 70 | + assert mode in ["train", "test"] | |
| 71 | + self.mode = mode | |
| 72 | + self.keys = keys | |
| 73 | + self.return_inverse = return_inverse | |
| 74 | + self.return_grid_coord = return_grid_coord | |
| 75 | + self.return_min_coord = return_min_coord | |
| 76 | + self.return_displacement = return_displacement | |
| 77 | + self.project_displacement = project_displacement | |
| 78 | + self.max_grid_coord = max_grid_coord | |
| 79 | + | |
| 80 | + def __call__(self, data_dict): | |
| 81 | + assert "coord" in data_dict.keys() | |
| 82 | + scaled_coord = data_dict["coord"] / np.array(self.grid_size) | |
| 83 | + grid_coord = np.floor(scaled_coord).astype(int) | |
| 84 | + min_coord = grid_coord.min(0) | |
| 85 | + grid_coord -= min_coord | |
| 86 | + scaled_coord -= min_coord | |
| 87 | + min_coord = min_coord * np.array(self.grid_size) | |
| 88 | + if self.max_grid_coord is not None: | |
| 89 | + grid_coord = np.clip(grid_coord, 0, self.max_grid_coord - 1) | |
| 90 | + key = self.hash(grid_coord) | |
| 91 | + idx_sort = np.argsort(key) | |
| 92 | + key_sort = key[idx_sort] | |
| 93 | + _, inverse, count = np.unique(key_sort, return_inverse=True, return_counts=True) | |
| 94 | + if self.mode == "train": # train mode | |
| 95 | + idx_select = ( | |
| 96 | + np.cumsum(np.insert(count, 0, 0)[0:-1]) | |
| 97 | + + np.random.randint(0, count.max(), count.size) % count | |
| 98 | + ) | |
| 99 | + idx_unique = idx_sort[idx_select] | |
| 100 | + if "sampled_index" in data_dict: | |
| 101 | + # for ScanNet data efficient, we need to make sure labeled point is sampled. | |
| 102 | + idx_unique = np.unique( | |
| 103 | + np.append(idx_unique, data_dict["sampled_index"]) | |
| 104 | + ) | |
| 105 | + mask = np.zeros_like(data_dict["segment"]).astype(bool) | |
| 106 | + mask[data_dict["sampled_index"]] = True | |
| 107 | + data_dict["sampled_index"] = np.where(mask[idx_unique])[0] | |
| 108 | + if self.return_inverse: | |
| 109 | + data_dict["inverse"] = np.zeros_like(inverse) | |
| 110 | + data_dict["inverse"][idx_sort] = inverse | |
| 111 | + if self.return_grid_coord: | |
| 112 | + data_dict["grid_coord"] = grid_coord[idx_unique] | |
| 113 | + if self.return_min_coord: | |
| 114 | + data_dict["min_coord"] = min_coord.reshape([1, 3]) | |
| 115 | + if self.return_displacement: | |
| 116 | + displacement = ( | |
| 117 | + scaled_coord - grid_coord - 0.5 | |
| 118 | + ) # [0, 1] -> [-0.5, 0.5] displacement to center | |
| 119 | + if self.project_displacement: | |
| 120 | + displacement = np.sum( | |
| 121 | + displacement * data_dict["normal"], axis=-1, keepdims=True | |
| 122 | + ) | |
| 123 | + data_dict["displacement"] = displacement[idx_unique] | |
| 124 | + for key in self.keys: | |
| 125 | + data_dict[key] = data_dict[key][idx_unique] | |
| 126 | + return data_dict | |
| 127 | + | |
| 128 | + elif self.mode == "test": # test mode | |
| 129 | + idx_select = ( | |
| 130 | + np.cumsum(np.insert(count, 0, 0)[0:-1]) + (count.max() // 2) % count | |
| 131 | + ) | |
| 132 | + idx_part = idx_sort[idx_select] | |
| 133 | + data_part = dict(index=idx_part) | |
| 134 | + if self.return_inverse: | |
| 135 | + data_dict["inverse"] = np.zeros_like(inverse) | |
| 136 | + data_dict["inverse"][idx_sort] = inverse | |
| 137 | + if self.return_grid_coord: | |
| 138 | + data_part["grid_coord"] = grid_coord[idx_part] | |
| 139 | + if self.return_min_coord: | |
| 140 | + data_part["min_coord"] = min_coord.reshape([1, 3]) | |
| 141 | + for key in data_dict.keys(): | |
| 142 | + if key in self.keys: | |
| 143 | + data_part[key] = data_dict[key][idx_part] | |
| 144 | + else: | |
| 145 | + data_part[key] = data_dict[key] | |
| 146 | + return data_part | |
| 147 | + else: | |
| 148 | + raise NotImplementedError | |
| 149 | + | |
| 150 | + @staticmethod | |
| 151 | + def ravel_hash_vec(arr): | |
| 152 | + """ | |
| 153 | + Ravel the coordinates after subtracting the min coordinates. | |
| 154 | + """ | |
| 155 | + assert arr.ndim == 2 | |
| 156 | + arr = arr.copy() | |
| 157 | + arr -= arr.min(0) | |
| 158 | + arr = arr.astype(np.uint64, copy=False) | |
| 159 | + arr_max = arr.max(0).astype(np.uint64) + 1 | |
| 160 | + | |
| 161 | + keys = np.zeros(arr.shape[0], dtype=np.uint64) | |
| 162 | + # Fortran style indexing | |
| 163 | + for j in range(arr.shape[1] - 1): | |
| 164 | + keys += arr[:, j] | |
| 165 | + keys *= arr_max[j + 1] | |
| 166 | + keys += arr[:, -1] | |
| 167 | + return keys | |
| 168 | + | |
| 169 | + @staticmethod | |
| 170 | + def fnv_hash_vec(arr): | |
| 171 | + """ | |
| 172 | + FNV64-1A | |
| 173 | + """ | |
| 174 | + assert arr.ndim == 2 | |
| 175 | + # Floor first for negative coordinates | |
| 176 | + arr = arr.copy() | |
| 177 | + arr = arr.astype(np.uint64, copy=False) | |
| 178 | + hashed_arr = np.uint64(14695981039346656037) * np.ones( | |
| 179 | + arr.shape[0], dtype=np.uint64 | |
| 180 | + ) | |
| 181 | + for j in range(arr.shape[1]): | |
| 182 | + hashed_arr *= np.uint64(1099511628211) | |
| 183 | + hashed_arr = np.bitwise_xor(hashed_arr, arr[:, j]) | |
| 184 | + return hashed_arr | |
| 185 | + | |
| 186 | + | |
| 187 | +# Load a point cloud from a file | |
| 188 | +def load_o3d_pcd(file_path: str): | |
| 189 | + return o3d.io.read_point_cloud(file_path) | |
| 190 | + | |
| 191 | + | |
| 192 | +# Get points and colors from a Open3D point cloud | |
| 193 | +def get_points_and_colors(pcd: o3d.geometry.PointCloud): | |
| 194 | + points = np.asarray(pcd.points) | |
| 195 | + colors = np.zeros_like(points, dtype=np.uint8) | |
| 196 | + if pcd.has_colors(): | |
| 197 | + colors = np.asarray(pcd.colors) | |
| 198 | + if colors.shape[1] == 4: | |
| 199 | + colors = colors[:, :3] | |
| 200 | + if colors.max() < 1.1: | |
| 201 | + colors = (colors * 255).astype(np.uint8) | |
| 202 | + return points, colors | |
| 203 | + | |
| 204 | + | |
| 205 | +# Preprocess a point cloud | |
| 206 | +def cleanup_pcd( | |
| 207 | + pcd: o3d.geometry.PointCloud, | |
| 208 | + voxel_size: float = 0.02, | |
| 209 | + num_nb: int = 3, | |
| 210 | + radius: float = 0.05, | |
| 211 | +): | |
| 212 | + # voxelize the point cloud | |
| 213 | + pcd = pcd.voxel_down_sample(voxel_size) | |
| 214 | + # remove outliers | |
| 215 | + pcd, _ = pcd.remove_radius_outlier(num_nb, radius) | |
| 216 | + return pcd |
added spatiallm/pcd/registry.py +350 −0
| @@ -0,0 +1,350 @@ | ||
| 1 | +# Copyright (c) OpenMMLab. All rights reserved. | |
| 2 | + | |
| 3 | +""" | |
| 4 | +Reference: PointCept | |
| 5 | + | |
| 6 | +@misc{pointcept2023, | |
| 7 | + title={Pointcept: A Codebase for Point Cloud Perception Research}, | |
| 8 | + author={Pointcept Contributors}, | |
| 9 | + year={2023} | |
| 10 | +} | |
| 11 | +""" | |
| 12 | + | |
| 13 | +import inspect | |
| 14 | +import warnings | |
| 15 | +from collections import abc | |
| 16 | +from functools import partial | |
| 17 | + | |
| 18 | + | |
| 19 | +def is_seq_of(seq, expected_type, seq_type=None): | |
| 20 | + """Check whether it is a sequence of some type. | |
| 21 | + | |
| 22 | + Args: | |
| 23 | + seq (Sequence): The sequence to be checked. | |
| 24 | + expected_type (type): Expected type of sequence items. | |
| 25 | + seq_type (type, optional): Expected sequence type. | |
| 26 | + | |
| 27 | + Returns: | |
| 28 | + bool: Whether the sequence is valid. | |
| 29 | + """ | |
| 30 | + if seq_type is None: | |
| 31 | + exp_seq_type = abc.Sequence | |
| 32 | + else: | |
| 33 | + assert isinstance(seq_type, type) | |
| 34 | + exp_seq_type = seq_type | |
| 35 | + if not isinstance(seq, exp_seq_type): | |
| 36 | + return False | |
| 37 | + for item in seq: | |
| 38 | + if not isinstance(item, expected_type): | |
| 39 | + return False | |
| 40 | + return True | |
| 41 | + | |
| 42 | + | |
| 43 | +def build_from_cfg(cfg, registry, default_args=None): | |
| 44 | + """Build a module from configs dict. | |
| 45 | + | |
| 46 | + Args: | |
| 47 | + cfg (dict): Config dict. It should at least contain the key "type". | |
| 48 | + registry (:obj:`Registry`): The registry to search the type from. | |
| 49 | + default_args (dict, optional): Default initialization arguments. | |
| 50 | + | |
| 51 | + Returns: | |
| 52 | + object: The constructed object. | |
| 53 | + """ | |
| 54 | + if not isinstance(cfg, dict): | |
| 55 | + raise TypeError(f"cfg must be a dict, but got {type(cfg)}") | |
| 56 | + if "type" not in cfg: | |
| 57 | + if default_args is None or "type" not in default_args: | |
| 58 | + raise KeyError( | |
| 59 | + '`cfg` or `default_args` must contain the key "type", ' | |
| 60 | + f"but got {cfg}\n{default_args}" | |
| 61 | + ) | |
| 62 | + if not isinstance(registry, Registry): | |
| 63 | + raise TypeError( | |
| 64 | + "registry must be an mmcv.Registry object, " f"but got {type(registry)}" | |
| 65 | + ) | |
| 66 | + if not (isinstance(default_args, dict) or default_args is None): | |
| 67 | + raise TypeError( | |
| 68 | + "default_args must be a dict or None, " f"but got {type(default_args)}" | |
| 69 | + ) | |
| 70 | + | |
| 71 | + args = cfg.copy() | |
| 72 | + | |
| 73 | + if default_args is not None: | |
| 74 | + for name, value in default_args.items(): | |
| 75 | + args.setdefault(name, value) | |
| 76 | + | |
| 77 | + obj_type = args.pop("type") | |
| 78 | + if isinstance(obj_type, str): | |
| 79 | + obj_cls = registry.get(obj_type) | |
| 80 | + if obj_cls is None: | |
| 81 | + raise KeyError(f"{obj_type} is not in the {registry.name} registry") | |
| 82 | + elif inspect.isclass(obj_type): | |
| 83 | + obj_cls = obj_type | |
| 84 | + else: | |
| 85 | + raise TypeError(f"type must be a str or valid type, but got {type(obj_type)}") | |
| 86 | + try: | |
| 87 | + return obj_cls(**args) | |
| 88 | + except Exception as e: | |
| 89 | + # Normal TypeError does not print class name. | |
| 90 | + raise type(e)(f"{obj_cls.__name__}: {e}") | |
| 91 | + | |
| 92 | + | |
| 93 | +class Registry: | |
| 94 | + """A registry to map strings to classes. | |
| 95 | + | |
| 96 | + Registered object could be built from registry. | |
| 97 | + Example: | |
| 98 | + >>> MODELS = Registry('models') | |
| 99 | + >>> @MODELS.register_module() | |
| 100 | + >>> class ResNet: | |
| 101 | + >>> pass | |
| 102 | + >>> resnet = MODELS.build(dict(type='ResNet')) | |
| 103 | + | |
| 104 | + Please refer to | |
| 105 | + https://mmcv.readthedocs.io/en/latest/understand_mmcv/registry.html for | |
| 106 | + advanced usage. | |
| 107 | + | |
| 108 | + Args: | |
| 109 | + name (str): Registry name. | |
| 110 | + build_func(func, optional): Build function to construct instance from | |
| 111 | + Registry, func:`build_from_cfg` is used if neither ``parent`` or | |
| 112 | + ``build_func`` is specified. If ``parent`` is specified and | |
| 113 | + ``build_func`` is not given, ``build_func`` will be inherited | |
| 114 | + from ``parent``. Default: None. | |
| 115 | + parent (Registry, optional): Parent registry. The class registered in | |
| 116 | + children registry could be built from parent. Default: None. | |
| 117 | + scope (str, optional): The scope of registry. It is the key to search | |
| 118 | + for children registry. If not specified, scope will be the name of | |
| 119 | + the package where class is defined, e.g. mmdet, mmcls, mmseg. | |
| 120 | + Default: None. | |
| 121 | + """ | |
| 122 | + | |
| 123 | + def __init__(self, name, build_func=None, parent=None, scope=None): | |
| 124 | + self._name = name | |
| 125 | + self._module_dict = dict() | |
| 126 | + self._children = dict() | |
| 127 | + self._scope = self.infer_scope() if scope is None else scope | |
| 128 | + | |
| 129 | + # self.build_func will be set with the following priority: | |
| 130 | + # 1. build_func | |
| 131 | + # 2. parent.build_func | |
| 132 | + # 3. build_from_cfg | |
| 133 | + if build_func is None: | |
| 134 | + if parent is not None: | |
| 135 | + self.build_func = parent.build_func | |
| 136 | + else: | |
| 137 | + self.build_func = build_from_cfg | |
| 138 | + else: | |
| 139 | + self.build_func = build_func | |
| 140 | + if parent is not None: | |
| 141 | + assert isinstance(parent, Registry) | |
| 142 | + parent._add_children(self) | |
| 143 | + self.parent = parent | |
| 144 | + else: | |
| 145 | + self.parent = None | |
| 146 | + | |
| 147 | + def __len__(self): | |
| 148 | + return len(self._module_dict) | |
| 149 | + | |
| 150 | + def __contains__(self, key): | |
| 151 | + return self.get(key) is not None | |
| 152 | + | |
| 153 | + def __repr__(self): | |
| 154 | + format_str = ( | |
| 155 | + self.__class__.__name__ + f"(name={self._name}, " | |
| 156 | + f"items={self._module_dict})" | |
| 157 | + ) | |
| 158 | + return format_str | |
| 159 | + | |
| 160 | + @staticmethod | |
| 161 | + def infer_scope(): | |
| 162 | + """Infer the scope of registry. | |
| 163 | + | |
| 164 | + The name of the package where registry is defined will be returned. | |
| 165 | + | |
| 166 | + Example: | |
| 167 | + # in mmdet/models/backbone/resnet.py | |
| 168 | + >>> MODELS = Registry('models') | |
| 169 | + >>> @MODELS.register_module() | |
| 170 | + >>> class ResNet: | |
| 171 | + >>> pass | |
| 172 | + The scope of ``ResNet`` will be ``mmdet``. | |
| 173 | + | |
| 174 | + | |
| 175 | + Returns: | |
| 176 | + scope (str): The inferred scope name. | |
| 177 | + """ | |
| 178 | + # inspect.stack() trace where this function is called, the index-2 | |
| 179 | + # indicates the frame where `infer_scope()` is called | |
| 180 | + filename = inspect.getmodule(inspect.stack()[2][0]).__name__ | |
| 181 | + split_filename = filename.split(".") | |
| 182 | + return split_filename[0] | |
| 183 | + | |
| 184 | + @staticmethod | |
| 185 | + def split_scope_key(key): | |
| 186 | + """Split scope and key. | |
| 187 | + | |
| 188 | + The first scope will be split from key. | |
| 189 | + | |
| 190 | + Examples: | |
| 191 | + >>> Registry.split_scope_key('mmdet.ResNet') | |
| 192 | + 'mmdet', 'ResNet' | |
| 193 | + >>> Registry.split_scope_key('ResNet') | |
| 194 | + None, 'ResNet' | |
| 195 | + | |
| 196 | + Return: | |
| 197 | + scope (str, None): The first scope. | |
| 198 | + key (str): The remaining key. | |
| 199 | + """ | |
| 200 | + split_index = key.find(".") | |
| 201 | + if split_index != -1: | |
| 202 | + return key[:split_index], key[split_index + 1 :] | |
| 203 | + else: | |
| 204 | + return None, key | |
| 205 | + | |
| 206 | + @property | |
| 207 | + def name(self): | |
| 208 | + return self._name | |
| 209 | + | |
| 210 | + @property | |
| 211 | + def scope(self): | |
| 212 | + return self._scope | |
| 213 | + | |
| 214 | + @property | |
| 215 | + def module_dict(self): | |
| 216 | + return self._module_dict | |
| 217 | + | |
| 218 | + @property | |
| 219 | + def children(self): | |
| 220 | + return self._children | |
| 221 | + | |
| 222 | + def get(self, key): | |
| 223 | + """Get the registry record. | |
| 224 | + | |
| 225 | + Args: | |
| 226 | + key (str): The class name in string format. | |
| 227 | + | |
| 228 | + Returns: | |
| 229 | + class: The corresponding class. | |
| 230 | + """ | |
| 231 | + scope, real_key = self.split_scope_key(key) | |
| 232 | + if scope is None or scope == self._scope: | |
| 233 | + # get from self | |
| 234 | + if real_key in self._module_dict: | |
| 235 | + return self._module_dict[real_key] | |
| 236 | + else: | |
| 237 | + # get from self._children | |
| 238 | + if scope in self._children: | |
| 239 | + return self._children[scope].get(real_key) | |
| 240 | + else: | |
| 241 | + # goto root | |
| 242 | + parent = self.parent | |
| 243 | + while parent.parent is not None: | |
| 244 | + parent = parent.parent | |
| 245 | + return parent.get(key) | |
| 246 | + | |
| 247 | + def build(self, *args, **kwargs): | |
| 248 | + return self.build_func(*args, **kwargs, registry=self) | |
| 249 | + | |
| 250 | + def _add_children(self, registry): | |
| 251 | + """Add children for a registry. | |
| 252 | + | |
| 253 | + The ``registry`` will be added as children based on its scope. | |
| 254 | + The parent registry could build objects from children registry. | |
| 255 | + | |
| 256 | + Example: | |
| 257 | + >>> models = Registry('models') | |
| 258 | + >>> mmdet_models = Registry('models', parent=models) | |
| 259 | + >>> @mmdet_models.register_module() | |
| 260 | + >>> class ResNet: | |
| 261 | + >>> pass | |
| 262 | + >>> resnet = models.build(dict(type='mmdet.ResNet')) | |
| 263 | + """ | |
| 264 | + | |
| 265 | + assert isinstance(registry, Registry) | |
| 266 | + assert registry.scope is not None | |
| 267 | + assert ( | |
| 268 | + registry.scope not in self.children | |
| 269 | + ), f"scope {registry.scope} exists in {self.name} registry" | |
| 270 | + self.children[registry.scope] = registry | |
| 271 | + | |
| 272 | + def _register_module(self, module_class, module_name=None, force=False): | |
| 273 | + if not inspect.isclass(module_class): | |
| 274 | + raise TypeError("module must be a class, " f"but got {type(module_class)}") | |
| 275 | + | |
| 276 | + if module_name is None: | |
| 277 | + module_name = module_class.__name__ | |
| 278 | + if isinstance(module_name, str): | |
| 279 | + module_name = [module_name] | |
| 280 | + for name in module_name: | |
| 281 | + if not force and name in self._module_dict: | |
| 282 | + raise KeyError(f"{name} is already registered " f"in {self.name}") | |
| 283 | + self._module_dict[name] = module_class | |
| 284 | + | |
| 285 | + def deprecated_register_module(self, cls=None, force=False): | |
| 286 | + warnings.warn( | |
| 287 | + "The old API of register_module(module, force=False) " | |
| 288 | + "is deprecated and will be removed, please use the new API " | |
| 289 | + "register_module(name=None, force=False, module=None) instead." | |
| 290 | + ) | |
| 291 | + if cls is None: | |
| 292 | + return partial(self.deprecated_register_module, force=force) | |
| 293 | + self._register_module(cls, force=force) | |
| 294 | + return cls | |
| 295 | + | |
| 296 | + def register_module(self, name=None, force=False, module=None): | |
| 297 | + """Register a module. | |
| 298 | + | |
| 299 | + A record will be added to `self._module_dict`, whose key is the class | |
| 300 | + name or the specified name, and value is the class itself. | |
| 301 | + It can be used as a decorator or a normal function. | |
| 302 | + | |
| 303 | + Example: | |
| 304 | + >>> backbones = Registry('backbone') | |
| 305 | + >>> @backbones.register_module() | |
| 306 | + >>> class ResNet: | |
| 307 | + >>> pass | |
| 308 | + | |
| 309 | + >>> backbones = Registry('backbone') | |
| 310 | + >>> @backbones.register_module(name='mnet') | |
| 311 | + >>> class MobileNet: | |
| 312 | + >>> pass | |
| 313 | + | |
| 314 | + >>> backbones = Registry('backbone') | |
| 315 | + >>> class ResNet: | |
| 316 | + >>> pass | |
| 317 | + >>> backbones.register_module(ResNet) | |
| 318 | + | |
| 319 | + Args: | |
| 320 | + name (str | None): The module name to be registered. If not | |
| 321 | + specified, the class name will be used. | |
| 322 | + force (bool, optional): Whether to override an existing class with | |
| 323 | + the same name. Default: False. | |
| 324 | + module (type): Module class to be registered. | |
| 325 | + """ | |
| 326 | + if not isinstance(force, bool): | |
| 327 | + raise TypeError(f"force must be a boolean, but got {type(force)}") | |
| 328 | + # NOTE: This is a walkaround to be compatible with the old api, | |
| 329 | + # while it may introduce unexpected bugs. | |
| 330 | + if isinstance(name, type): | |
| 331 | + return self.deprecated_register_module(name, force=force) | |
| 332 | + | |
| 333 | + # raise the error ahead of time | |
| 334 | + if not (name is None or isinstance(name, str) or is_seq_of(name, str)): | |
| 335 | + raise TypeError( | |
| 336 | + "name must be either of None, an instance of str or a sequence" | |
| 337 | + f" of str, but got {type(name)}" | |
| 338 | + ) | |
| 339 | + | |
| 340 | + # use it as a normal method: x.register_module(module=SomeClass) | |
| 341 | + if module is not None: | |
| 342 | + self._register_module(module_class=module, module_name=name, force=force) | |
| 343 | + return module | |
| 344 | + | |
| 345 | + # use it as a decorator: @x.register_module() | |
| 346 | + def _register(cls): | |
| 347 | + self._register_module(module_class=cls, module_name=name, force=force) | |
| 348 | + return cls | |
| 349 | + | |
| 350 | + return _register |
added visualize.py +94 −0
| @@ -0,0 +1,94 @@ | ||
| 1 | +import argparse | |
| 2 | +import numpy as np | |
| 3 | +import rerun as rr | |
| 4 | +import rerun.blueprint as rrb | |
| 5 | + | |
| 6 | +from spatiallm import Layout | |
| 7 | +from spatiallm.pcd import load_o3d_pcd, get_points_and_colors | |
| 8 | + | |
| 9 | +if __name__ == "__main__": | |
| 10 | + parser = argparse.ArgumentParser("Layout Visualization with rerun") | |
| 11 | + parser.add_argument( | |
| 12 | + "-p", | |
| 13 | + "--point_cloud", | |
| 14 | + type=str, | |
| 15 | + required=True, | |
| 16 | + help="Path to the input point cloud file", | |
| 17 | + ) | |
| 18 | + parser.add_argument( | |
| 19 | + "-l", | |
| 20 | + "--layout", | |
| 21 | + type=str, | |
| 22 | + required=True, | |
| 23 | + help="Path to the layout txt file", | |
| 24 | + ) | |
| 25 | + parser.add_argument( | |
| 26 | + "--radius", | |
| 27 | + type=float, | |
| 28 | + default=0.01, | |
| 29 | + help="The radius of the points for visualization", | |
| 30 | + ) | |
| 31 | + parser.add_argument( | |
| 32 | + "--max_points", | |
| 33 | + type=int, | |
| 34 | + default=1000000, | |
| 35 | + help="The maximum number of points for visualization", | |
| 36 | + ) | |
| 37 | + rr.script_add_args(parser) | |
| 38 | + args = parser.parse_args() | |
| 39 | + | |
| 40 | + with open(args.layout, "r") as f: | |
| 41 | + layout_content = f.read() | |
| 42 | + | |
| 43 | + pcd = load_o3d_pcd(args.point_cloud) | |
| 44 | + points, colors = get_points_and_colors(pcd) | |
| 45 | + | |
| 46 | + # parse layout_content | |
| 47 | + layout = Layout(layout_content) | |
| 48 | + floor_plan = layout.to_boxes() | |
| 49 | + | |
| 50 | + # ReRun visualization | |
| 51 | + blueprint = rrb.Blueprint( | |
| 52 | + rrb.Spatial3DView(name="3D", origin="/world", background=[255, 255, 255]), | |
| 53 | + collapse_panels=True, | |
| 54 | + ) | |
| 55 | + rr.script_setup(args, "rerun_spatiallm", default_blueprint=blueprint) | |
| 56 | + | |
| 57 | + rr.log("world", rr.ViewCoordinates.RIGHT_HAND_Z_UP, static=True) | |
| 58 | + point_indices = np.arange(points.shape[0]) | |
| 59 | + np.random.shuffle(point_indices) | |
| 60 | + point_indices = point_indices[: args.max_points] | |
| 61 | + points = points[point_indices] | |
| 62 | + colors = colors[point_indices] | |
| 63 | + rr.log( | |
| 64 | + "world/points", | |
| 65 | + rr.Points3D( | |
| 66 | + positions=points, | |
| 67 | + colors=colors, | |
| 68 | + radii=args.radius, | |
| 69 | + ), | |
| 70 | + static=True, | |
| 71 | + ) | |
| 72 | + | |
| 73 | + num_entities = len(floor_plan) | |
| 74 | + seconds = 0.5 | |
| 75 | + for ti in range(num_entities + 1): | |
| 76 | + sub_floor_plan = floor_plan[:ti] | |
| 77 | + | |
| 78 | + rr.set_time_seconds("time_sec", ti * seconds) | |
| 79 | + for box in sub_floor_plan: | |
| 80 | + uid = box["id"] | |
| 81 | + group = box["class"] | |
| 82 | + label = box["label"] | |
| 83 | + | |
| 84 | + rr.log( | |
| 85 | + f"world/pred/{group}/{uid}", | |
| 86 | + rr.Boxes3D( | |
| 87 | + centers=box["center"], | |
| 88 | + half_sizes=0.5 * box["scale"], | |
| 89 | + labels=label, | |
| 90 | + ), | |
| 91 | + rr.InstancePoses3D(mat3x3=box["rotation"]), | |
| 92 | + static=False, | |
| 93 | + ) | |
| 94 | + rr.script_teardown(args) |