Elffuss BraidHub

kikocis/SpatialLM public

update with SpatialLM1.1
Changeset5ec8f267b45b663039aa9d376f352dccf409c8a2aaaa7641221588ba25c2eec2
AuthorYongsen Mao <sammaoys@gmail.com> · 2025-06-10 10:56 +08:00
CommitterYongsen Mao <sammaoys@gmail.com> · 2025-06-10 10:58 +08:00
Parents787e1c6f3e69

Browse the files at this changeset

21 files changed

modified README.md +121 −47
@@ -12,16 +12,25 @@
1212 <div align="center" style="margin-top: 0; padding-top: 0; line-height: 1;">
1313 <a href="https://manycore-research.github.io/SpatialLM" target="_blank" style="margin: 2px;"><img alt="Project"
1414 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://arxiv.org/abs/2506.07491" target="_blank" style="margin: 2px;"><img alt="arXiv"
16+ src="https://img.shields.io/badge/arXiv-Techreport-b31b1b?logo=arxiv&logoColor=white" style="display: inline-block; vertical-align: middle;"/></a>
1517 <a href="https://github.com/manycore-research/SpatialLM" target="_blank" style="margin: 2px;"><img alt="GitHub"
1618 src="https://img.shields.io/badge/GitHub-SpatialLM-24292e?logo=github&logoColor=white" style="display: inline-block; vertical-align: middle;"/></a>
1719 </div>
1820 <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/manycore-research/SpatialLM1.1-Qwen-0.5B" target="_blank" style="margin: 2px;"><img alt="Hugging Face"
22+ src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-SpatialLM-ffc107?color=ffc107&logoColor=white" style="display: inline-block; vertical-align: middle;"/></a>
2123 <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>
24+ src="https://img.shields.io/badge/%F0%9F%A4%97%20Dataset-Testset-ffc107?color=ffc107&logoColor=white" style="display: inline-block; vertical-align: middle;"/></a>
2325 </div>
2426
27+## ✨ News
28+
29+- [Jun, 2025] Check out our new models: [SpatialLM1.1-Llama-1B](https://huggingface.co/manycore-research/SpatialLM1.1-Llama-1B) and [SpatialLM1.1-Qwen-0.5B](https://huggingface.co/manycore-research/SpatialLM1.1-Qwen-0.5B), now available on Hugging Face. SpatialLM1.1 doubles the point cloud resolution, incorporates a more powerful point cloud encoder [Sonata](https://xywu.me/sonata/) and supports detection with user-specified categories.
30+- [Jun, 2025] SpatialLM [Technical Report](https://arxiv.org/abs/2506.07491) is now on arXiv.
31+- [Mar, 2025] We're excited to release the [SpatialLM-Llama-1B](https://huggingface.co/manycore-research/SpatialLM-Llama-1B) and [SpatialLM-Qwen-0.5B](https://huggingface.co/manycore-research/SpatialLM-Qwen-0.5B) on Hugging Face.
32+- [Mar, 2025] Initial release of SpatialLM!
33+
2534 ## Introduction
2635
2736 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.
@@ -35,10 +44,12 @@
3544
3645 <div align="center">
3746
38-| **Model** | **Download** |
39-| :-----------------: | ------------------------------------------------------------------------------ |
40-| SpatialLM-Llama-1B | [🤗 HuggingFace](https://huggingface.co/manycore-research/SpatialLM-Llama-1B) |
41-| SpatialLM-Qwen-0.5B | [🤗 HuggingFace](https://huggingface.co/manycore-research/SpatialLM-Qwen-0.5B) |
47+| **Model** | **Download** |
48+| :--------------------: | --------------------------------------------------------------------------------- |
49+| SpatialLM1.1-Llama-1B | [🤗 HuggingFace](https://huggingface.co/manycore-research/SpatialLM1.1-Llama-1B) |
50+| SpatialLM1.1-Qwen-0.5B | [🤗 HuggingFace](https://huggingface.co/manycore-research/SpatialLM1.1-Qwen-0.5B) |
51+| SpatialLM1.0-Llama-1B | [🤗 HuggingFace](https://huggingface.co/manycore-research/SpatialLM-Llama-1B) |
52+| SpatialLM1.0-Qwen-0.5B | [🤗 HuggingFace](https://huggingface.co/manycore-research/SpatialLM-Qwen-0.5B) |
4253
4354 </div>
4455
@@ -60,12 +71,15 @@
6071 # create a conda environment with cuda 12.4
6172 conda create -n spatiallm python=3.11
6273 conda activate spatiallm
63-conda install -y nvidia/label/cuda-12.4.0::cuda-toolkit conda-forge::sparsehash
74+conda install -y -c nvidia/label/cuda-12.4.0 cuda-toolkit conda-forge::sparsehash
6475
6576 # Install dependencies with poetry
6677 pip install poetry && poetry config virtualenvs.create false --local
6778 poetry install
79+# SpatialLM1.0 dependency
6880 poe install-torchsparse # Building wheel for torchsparse will take a while
81+# SpatialLM1.1 dependency
82+poe install-sonata # Building wheel for flash-attn will take a while
6983 ```
7084
7185 ### Inference
@@ -82,7 +96,23 @@
8296 Run inference:
8397
8498 ```bash
85-python inference.py --point_cloud pcd/scene0000_00.ply --output scene0000_00.txt --model_path manycore-research/SpatialLM-Llama-1B
99+python inference.py --point_cloud pcd/scene0000_00.ply --output scene0000_00.txt --model_path manycore-research/SpatialLM1.1-Qwen-0.5B
100+```
101+
102+### Detection with user-specified categories
103+
104+SpatialLM1.1 supports object detection conditioned on user-specified categories by leveraging the flexibility of LLMs.
105+
106+SpatialLM1.1 offers three variants of structured indoor modeling tasks:
107+
108+- **Structured Reconstruction**: Detect walls, doors, windows, boxes.
109+- **Layout Estimation**: Detect walls, doors, windows.
110+- **3D Object Detection**: Detect boxes.
111+
112+For tasks that include object box estimation, you can specify a subset of the 59 furniture categories, and the model will only predict objects within those specified categories. For example:
113+
114+```bash
115+python inference.py --point_cloud pcd/scene0000_00.ply --output scene0000_00.txt --model_path manycore-research/SpatialLM1.1-Qwen-0.5B --detect_type object --category bed nightstand
86116 ```
87117
88118 ### Visualization
@@ -110,8 +140,8 @@
110140 Run evaluation:
111141
112142 ```bash
113-# Run inference on the PLY point clouds in folder SpatialLM-Testset/pcd with SpatialLM-Llama-1B model
114-python inference.py --point_cloud SpatialLM-Testset/pcd --output SpatialLM-Testset/pred --model_path manycore-research/SpatialLM-Llama-1B
143+# Run inference on the PLY point clouds in folder SpatialLM-Testset/pcd with SpatialLM1.1-Qwen-0.5B model
144+python inference.py --point_cloud SpatialLM-Testset/pcd --output SpatialLM-Testset/pred --model_path manycore-research/SpatialLM1.1-Qwen-0.5B
115145
116146 # Evaluate the predicted layouts
117147 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
@@ -135,38 +165,77 @@
135165
136166 ## Benchmark Results
137167
138-Benchmark results on the challenging SpatialLM-Testset are reported in the following table:
168+### Layout Estimation
169+
170+Layout estimation focuses on predicting architectural elements, i.e., walls, doors, and windows, within an indoor scene. We evaluated this task on the [Structured3D](https://structured3d-dataset.org) dataset. For [RoomFormer](https://github.com/ywyue/RoomFormer), we directly downloaded the model checkpoint. SceneScript and SpatialLM were first trained on our dataset, and further fine-tuned on Structured3D.
171+
172+<div align="center">
173+
174+| **Method** | **RoomFormer** | **SceneScript (finetuned)** | **SpatialLM1.1-Qwen-0.5B (finetuned)** |
175+| :-------------: | :------------: | :-------------------------: | :------------------------------------: |
176+| **F1 @.25 IoU** | 70.4 | 83.1 | 86.5 |
177+| **F1 @.5 IoU** | 67.2 | 80.8 | 84.6 |
178+
179+</div>
180+
181+### 3D Object Detection
182+
183+We evaluate 3D object detection on [ScanNet](http://www.scan-net.org) with annotations of 18 object categories. For [V-DETR](https://github.com/V-DETR/V-DETR), we directly download the model checkpoint. SceneScript and SpatialLM were first trained on our dataset, and further fine-tuned on ScanNet.
184+
185+<div align="center">
186+
187+| **Method** | **V-DETR** | **SceneScript (finetuned)** | **SpatialLM1.1-Qwen-0.5B (finetuned)** |
188+| :-------------: | :--------: | :-------------------------: | :------------------------------------: |
189+| **F1 @.25 IoU** | 65.1 | 49.1 | 65.6 |
190+| **F1 @.5 IoU** | 56.8 | 36.8 | 52.6 |
191+
192+</div>
193+
194+### Zero-shot Detection on Videos
195+
196+Zero-shot detection results on the challenging SpatialLM-Testset are reported in the following table:
197+
198+<div align="center">
199+
200+| **Method** | **SpatialLM1.1-Llama-1B** | **SpatialLM1.1-Qwen-0.5B** |
201+| :-------------: | :-----------------------: | :------------------------: |
202+| **Layout** | **F1 @.25 IoU (2D)** | **F1 @.25 IoU (2D)** |
203+| wall | 68.9 | 68.2 |
204+| door | 46.3 | 43.1 |
205+| window | 43.8 | 47.4 |
206+| | | |
207+| **Objects** | **F1 @.25 IoU (3D)** | **F1 @.25 IoU (2D)** |
208+| curtain | 34.9 | 37.0 |
209+| nightstand | 62.8 | 67.0 |
210+| chandelier | 53.5 | 36.8 |
211+| wardrobe | 29.4 | 39.6 |
212+| bed | 96.8 | 95.2 |
213+| sofa | 66.9 | 69.1 |
214+| chair | 20.8 | 32.3 |
215+| cabinet | 15.2 | 11.2 |
216+| dining table | 40.7 | 24.2 |
217+| plants | 29.5 | 26.3 |
218+| tv cabinet | 34.4 | 27.3 |
219+| coffee table | 56.4 | 64.9 |
220+| side table | 14.6 | 9.7 |
221+| air conditioner | 16.7 | 24.0 |
222+| dresser | 46.7 | 46.7 |
223+| stool | 17.6 | 30.8 |
224+| refrigerator | 0.0 | 16.7 |
225+| painting | 34.9 | 38.2 |
226+| carpet | 40.3 | 24.1 |
227+| tv | 16.0 | 18.0 |
228+
229+</div>
230+
231+### Result Visualizations
139232
140233 <div align="center">
141234
142-| **Method** | **SpatialLM-Llama-1B** | **SpatialLM-Qwen-0.5B** |
143-| ---------------- | ---------------------- | ----------------------- |
144-| **Floorplan** | **mean IoU** | |
145-| wall | 78.62 | 74.81 |
146-| | | |
147-| **Objects** | **F1 @.25 IoU (3D)** | |
148-| curtain | 27.35 | 28.59 |
149-| nightstand | 57.47 | 54.39 |
150-| chandelier | 38.92 | 40.12 |
151-| wardrobe | 23.33 | 30.60 |
152-| bed | 95.24 | 93.75 |
153-| sofa | 65.50 | 66.15 |
154-| chair | 21.26 | 14.94 |
155-| cabinet | 8.47 | 8.44 |
156-| dining table | 54.26 | 56.10 |
157-| plants | 20.68 | 26.46 |
158-| tv cabinet | 33.33 | 10.26 |
159-| coffee table | 50.00 | 55.56 |
160-| side table | 7.60 | 2.17 |
161-| air conditioner | 20.00 | 13.04 |
162-| dresser | 46.67 | 23.53 |
163-| | | |
164-| **Thin Objects** | **F1 @.25 IoU (2D)** | |
165-| painting | 50.04 | 53.81 |
166-| carpet | 31.76 | 45.31 |
167-| tv | 67.31 | 52.29 |
168-| door | 50.35 | 42.15 |
169-| window | 45.4 | 45.9 |
235+| Layout Estimation | Object Detection | Zero-shot Reconstruction |
236+| :-------------------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------------------------------------------: |
237+| ![Structured3D](./figures/stru3d.jpg) | ![ScanNet](./figures/scannet.jpg) | ![Zero-shot](./figures/zeroshot.jpg) |
238+| [Structured3D Results](https://manycore-research-azure.kujiale.com/manycore-research/SpatialLM/supplementary/visualization_layout.html) | [ScanNet Results](https://manycore-research-azure.kujiale.com/manycore-research/SpatialLM/supplementary/visualization_object.html) | [Zeroshot Results](https://manycore-research-azure.kujiale.com/manycore-research/SpatialLM/supplementary/visualization_zeroshot.html) |
170239
171240 </div>
172241
@@ -175,18 +244,23 @@
175244 SpatialLM-Llama-1B is derived from Llama3.2-1B-Instruct, which is licensed under the Llama3.2 license.
176245 SpatialLM-Qwen-0.5B is derived from the Qwen-2.5 series, originally licensed under the Apache 2.0 License.
177246
178-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.
247+SpatialLM1.0 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.
248+
249+SpatialLM1.1 are built upon Sonata point cloud encoder, model weight is licensed under the CC-BY-NC-4.0 License. Code built on Pointcept is licensed under the Apache 2.0 License.
179250
180251 ## Citation
181252
182253 If you find this work useful, please consider citing:
183254
184255 ```bibtex
185-@misc{spatiallm,
186- title = {SpatialLM: Large Language Model for Spatial Understanding},
187- author = {ManyCore Research Team},
188- howpublished = {\url{https://github.com/manycore-research/SpatialLM}},
189- year = {2025}
256+@article{SpatialLM,
257+ title = {SpatialLM: Training Large Language Models for Structured Indoor Modeling},
258+ author = {Mao, Yongsen and Zhong, Junhao and Fang, Chuan and Zheng, Jia and Tang, Rui and Zhu, Hao and Tan, Ping and Zhou, Zihan},
259+ journal = {arXiv preprint},
260+ year = {2025},
261+ eprint = {2506.07491},
262+ archivePrefix = {arXiv},
263+ primaryClass = {cs.CV}
190264 }
191265 ```
192266
@@ -194,4 +268,4 @@
194268
195269 We would like to thank the following projects that made this work possible:
196270
197-[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)
271+[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) | [Sonata](https://xywu.me/sonata/) | [Pointcept](https://github.com/Pointcept/Pointcept)
modified eval.py +128 −104
@@ -12,7 +12,7 @@
1212 import pandas as pd
1313 import numpy as np
1414 from scipy.optimize import linear_sum_assignment
15-from shapely import Polygon, LineString, polygonize, polygonize_full, make_valid
15+from shapely import Polygon
1616 from bbox import BBox3D
1717 from bbox.metrics import iou_3d
1818 from terminaltables import AsciiTable
@@ -24,6 +24,7 @@
2424
2525 ZERO_TOLERANCE = 1e-6
2626 LARGE_COST_VALUE = 1e6
27+LAYOUTS = ["wall", "door", "window"]
2728 OBJECTS = [
2829 "curtain",
2930 "nightstand",
@@ -40,13 +41,11 @@
4041 "side table",
4142 "air conditioner",
4243 "dresser",
43-]
44-THIN_OBJECTS = [
44+ "stool",
45+ "refrigerator",
4546 "painting",
4647 "carpet",
4748 "tv",
48- "door",
49- "window",
5049 ]
5150
5251
@@ -87,37 +86,8 @@
8786 return poly_iou
8887
8988
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-
11989 def read_label_mapping(
120- label_path: str, label_from="spatiallm59", label_to="spatiallm18"
90+ label_path: str, label_from="spatiallm59", label_to="spatiallm23"
12191 ):
12292 assert os.path.isfile(label_path), f"Label mapping file {label_path} does not exist"
12393 mapping = dict()
@@ -142,6 +112,13 @@
142112 return res_entities
143113
144114
115+def assign_minimum_scale(entities: List[Bbox], minimum_scale: float = 0.1):
116+ for entity in entities:
117+ entity.scale_x = max(entity.scale_x, minimum_scale)
118+ entity.scale_y = max(entity.scale_y, minimum_scale)
119+ entity.scale_z = max(entity.scale_z, minimum_scale)
120+
121+
145122 def get_entity_class(entity):
146123 try:
147124 return entity.class_name
@@ -194,22 +171,32 @@
194171 return EvalTuple(tp, num_pred, num_gt)
195172
196173
174+def is_valid_wall(entity: Wall):
175+ wall_extent_x = max(max(entity.ax, entity.bx) - min(entity.ax, entity.bx), 0)
176+ wall_extent_y = max(max(entity.ay, entity.by) - min(entity.ay, entity.by), 0)
177+ return wall_extent_x > ZERO_TOLERANCE or wall_extent_y > ZERO_TOLERANCE
178+
179+
197180 def is_valid_dw(entity: Door | Window, wall_id_lookup: Dict[int, Wall]):
198181 attach_wall = wall_id_lookup.get(entity.id, None)
199182 if attach_wall is None:
200183 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
184+ return is_valid_wall(attach_wall)
209185
210186
211-def get_corners(entity: Door | Window | Bbox, wall_id_lookup: Dict[int, Wall]):
212- if isinstance(entity, (Door, Window)):
187+def get_corners(
188+ entity: Wall | Door | Window | Bbox, wall_id_lookup: Dict[int, Wall] = None
189+):
190+ if isinstance(entity, Wall):
191+ return np.array(
192+ [
193+ [entity.ax, entity.ay, entity.az],
194+ [entity.bx, entity.by, entity.bz],
195+ [entity.bx, entity.by, entity.bz + entity.height],
196+ [entity.ax, entity.ay, entity.az + entity.height],
197+ ]
198+ )
199+ elif isinstance(entity, (Door, Window)):
213200 attach_wall = wall_id_lookup.get(entity.id, None)
214201 if attach_wall is None:
215202 log.error(f"{entity} attach wall is None")
@@ -305,7 +292,7 @@
305292 if are_planes_parallel_and_close(
306293 corners_1, corners_2, parallel_tolerance, dist_tolerance
307294 ):
308- p1, p2, _, p4 = corners_1
295+ p1, p2, _, p4 = corners_2
309296 v1 = np.subtract(p2, p1)
310297 v2 = np.subtract(p4, p1)
311298 basis1 = v1 / np.linalg.norm(v1)
@@ -334,9 +321,9 @@
334321 return 0
335322
336323
337-def calc_thin_bbox_tp(
338- pred_entities: List[Door | Window | Bbox],
339- gt_entities: List[Door | Window | Bbox],
324+def calc_layout_tp(
325+ pred_entities: List[Wall | Door | Window],
326+ gt_entities: List[Wall | Door | Window],
340327 pred_wall_id_lookup: Dict[int, Wall],
341328 gt_wall_id_lookup: Dict[int, Wall],
342329 iou_threshold: float = 0.25,
@@ -400,14 +387,16 @@
400387 required=True,
401388 help="Path to the label mapping file",
402389 )
390+ parser.add_argument("--label_from", type=str, default="spatiallm59")
391+ parser.add_argument("--label_to", type=str, default="spatiallm20")
403392 args = parser.parse_args()
404393
405394 df = pd.read_csv(args.metadata)
406395 scene_id_list = df["id"].tolist()
407- class_map = read_label_mapping(args.label_mapping)
396+ class_map = read_label_mapping(args.label_mapping, args.label_from, args.label_to)
408397
409- floorplan_ious = list()
410- classwise_eval_tuples: Dict[str, List[EvalTuple]] = defaultdict(list)
398+ classwise_eval_tuples_25: Dict[str, List[EvalTuple]] = defaultdict(list)
399+ classwise_eval_tuples_50: Dict[str, List[EvalTuple]] = defaultdict(list)
411400 for scene_id in scene_id_list:
412401 log.info(f"Evaluating scene {scene_id}")
413402 with open(os.path.join(args.pred_dir, f"{scene_id}.txt"), "r") as f:
@@ -416,25 +405,71 @@
416405 gt_layout = Layout(f.read())
417406 pred_layout.bboxes = assign_class_map(pred_layout.bboxes, class_map)
418407 gt_layout.bboxes = assign_class_map(gt_layout.bboxes, class_map)
408+ assign_minimum_scale(pred_layout.bboxes, minimum_scale=0.1)
409+ assign_minimum_scale(gt_layout.bboxes, minimum_scale=0.1)
410+
411+ # Layout, F1
412+ pred_wall_id_lookup = {w.id: w for w in pred_layout.walls}
413+ gt_wall_id_lookup = {w.id: w for w in gt_layout.walls}
419414
420- # Floorplan, IoU
421- pred_poly = construct_polygon(
422- [LineString([(w.ax, w.ay), (w.bx, w.by)]) for w in pred_layout.walls]
415+ pred_layout_instances = list(
416+ filter(lambda e: is_valid_wall(e), pred_layout.walls)
417+ ) + list(
418+ filter(
419+ lambda e: is_valid_dw(e, pred_wall_id_lookup),
420+ pred_layout.doors + pred_layout.windows,
421+ )
423422 )
424- gt_poly = construct_polygon(
425- [LineString([(w.ax, w.ay), (w.bx, w.by)]) for w in gt_layout.walls]
423+ gt_layout_instances = list(
424+ filter(lambda e: is_valid_wall(e), gt_layout.walls)
425+ ) + list(
426+ filter(
427+ lambda e: is_valid_dw(e, gt_wall_id_lookup),
428+ gt_layout.doors + gt_layout.windows,
429+ )
426430 )
427- floorplan_ious.append(calc_poly_iou(pred_poly, gt_poly))
431+ for class_name in LAYOUTS:
432+ classwise_eval_tuples_25[class_name].append(
433+ calc_layout_tp(
434+ pred_entities=[
435+ b
436+ for b in pred_layout_instances
437+ if get_entity_class(b) == class_name
438+ ],
439+ gt_entities=[
440+ b
441+ for b in gt_layout_instances
442+ if get_entity_class(b) == class_name
443+ ],
444+ pred_wall_id_lookup=pred_wall_id_lookup,
445+ gt_wall_id_lookup=gt_wall_id_lookup,
446+ iou_threshold=0.25,
447+ )
448+ )
449+
450+ classwise_eval_tuples_50[class_name].append(
451+ calc_layout_tp(
452+ pred_entities=[
453+ b
454+ for b in pred_layout_instances
455+ if get_entity_class(b) == class_name
456+ ],
457+ gt_entities=[
458+ b
459+ for b in gt_layout_instances
460+ if get_entity_class(b) == class_name
461+ ],
462+ pred_wall_id_lookup=pred_wall_id_lookup,
463+ gt_wall_id_lookup=gt_wall_id_lookup,
464+ iou_threshold=0.50,
465+ )
466+ )
428467
429468 # 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- ]
469+ pred_normal_objects = [b for b in pred_layout.bboxes if b.class_name in OBJECTS]
470+ gt_normal_objects = [b for b in gt_layout.bboxes if b.class_name in OBJECTS]
436471 for class_name in OBJECTS:
437- classwise_eval_tuples[class_name].append(
472+ classwise_eval_tuples_25[class_name].append(
438473 calc_bbox_tp(
439474 pred_entities=[
440475 b
@@ -446,65 +481,54 @@
446481 for b in gt_normal_objects
447482 if get_entity_class(b) == class_name
448483 ],
484+ iou_threshold=0.25,
449485 )
450486 )
451487
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(
488+ classwise_eval_tuples_50[class_name].append(
489+ calc_bbox_tp(
473490 pred_entities=[
474491 b
475- for b in pred_thin_objects
492+ for b in pred_normal_objects
476493 if get_entity_class(b) == class_name
477494 ],
478495 gt_entities=[
479- b for b in gt_thin_objects if get_entity_class(b) == class_name
496+ b
497+ for b in gt_normal_objects
498+ if get_entity_class(b) == class_name
480499 ],
481- pred_wall_id_lookup=pred_wall_id_lookup,
482- gt_wall_id_lookup=gt_wall_id_lookup,
500+ iou_threshold=0.50,
483501 )
484502 )
485503
486- # table print
487- headers = ["Floorplan", "mean IoU"]
504+ headers = ["Layouts", "F1 @.25 IoU", "F1 @.50 IoU"]
488505 table_data = [headers]
489- table_data += [["wall", np.mean(floorplan_ious)]]
506+ for class_name in LAYOUTS:
507+ tuples = classwise_eval_tuples_25[class_name]
508+ f1_25 = np.ma.masked_where(
509+ [t.masked for t in tuples], [t.f1 for t in tuples]
510+ ).mean()
511+
512+ tuples = classwise_eval_tuples_50[class_name]
513+ f1_50 = np.ma.masked_where(
514+ [t.masked for t in tuples], [t.f1 for t in tuples]
515+ ).mean()
516+
517+ table_data.append([class_name, f1_25, f1_50])
490518 print("\n" + AsciiTable(table_data).table)
491519
492- headers = ["Objects", "F1 @.25 IoU"]
520+ headers = ["Objects", "F1 @.25 IoU", "F1 @.50 IoU"]
493521 table_data = [headers]
494522 for class_name in OBJECTS:
495- tuples = classwise_eval_tuples[class_name]
496- f1 = np.ma.masked_where(
523+ tuples = classwise_eval_tuples_25[class_name]
524+ f1_25 = np.ma.masked_where(
497525 [t.masked for t in tuples], [t.f1 for t in tuples]
498526 ).mean()
499- table_data.append([class_name, f1])
500- print("\n" + AsciiTable(table_data).table)
501527
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(
528+ tuples = classwise_eval_tuples_50[class_name]
529+ f1_50 = np.ma.masked_where(
507530 [t.masked for t in tuples], [t.f1 for t in tuples]
508531 ).mean()
509- table_data.append([class_name, f1])
532+
533+ table_data.append([class_name, f1_25, f1_50])
510534 print("\n" + AsciiTable(table_data).table)
added figures/scannet.jpg +0 −0

Binary content is not shown. View the file.

added figures/stru3d.jpg +0 −0

Binary content is not shown. View the file.

added figures/zeroshot.jpg +0 −0

Binary content is not shown. View the file.

modified inference.py +133 −21
@@ -7,12 +7,17 @@
77 from tqdm import tqdm
88 from threading import Thread
99 from transformers import AutoTokenizer, AutoModelForCausalLM
10-from transformers import TextIteratorStreamer
10+from transformers import TextIteratorStreamer, set_seed
1111
1212 from spatiallm import Layout
13-from spatiallm import SpatialLMLlamaForCausalLM, SpatialLMQwenForCausalLM
1413 from spatiallm.pcd import load_o3d_pcd, get_points_and_colors, cleanup_pcd, Compose
1514
15+DETECT_TYPE_PROMPT = {
16+ "all": "Detect walls, doors, windows, boxes.",
17+ "arch": "Detect walls, doors, windows.",
18+ "object": "Detect boxes.",
19+}
20+
1621
1722 def preprocess_point_cloud(points, colors, grid_size, num_bins):
1823 transform = Compose(
@@ -53,24 +58,27 @@
5358 top_p=0.95,
5459 temperature=0.6,
5560 num_beams=1,
61+ seed=-1,
5662 max_new_tokens=4096,
63+ detect_type="all",
64+ categories=[],
5765 ):
66+ if seed >= 0:
67+ set_seed(seed)
68+
5869 # load the code template
5970 with open(code_template_file, "r") as f:
6071 code_template = f.read()
6172
62- prompt = f"<|point_start|><|point_pad|><|point_end|>Detect walls, doors, windows, boxes. The reference code is as followed: {code_template}"
73+ task_prompt = DETECT_TYPE_PROMPT[detect_type]
74+ if detect_type != "arch" and categories:
75+ task_prompt = task_prompt.replace("boxes", ", ".join(categories))
76+ print("Task prompt: ", task_prompt)
77+
78+ prompt = f"<|point_start|><|point_pad|><|point_end|>{task_prompt} The reference code is as followed: {code_template}"
6379
6480 # 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}")
81+ conversation = [{"role": "user", "content": prompt}]
7482
7583 input_ids = tokenizer.apply_chat_template(
7684 conversation, add_generation_prompt=True, return_tensors="pt"
@@ -104,7 +112,7 @@
104112
105113 layout_str = "".join(generate_texts)
106114 layout = Layout(layout_str)
107- layout.undiscretize_and_unnormalize()
115+ layout.undiscretize_and_unnormalize(num_bins=model.config.point_config["num_bins"])
108116 return layout
109117
110118
@@ -131,6 +139,82 @@
131139 default="manycore-research/SpatialLM-Llama-1B",
132140 help="Path to the model checkpoint",
133141 )
142+ parser.add_argument(
143+ "-d",
144+ "--detect_type",
145+ type=str,
146+ default="all",
147+ choices=["all", "arch", "object"],
148+ help="The type of indoor elements to detect. all: (wall, door, window, box), arch: (wall, door, window), object: (box)",
149+ )
150+ parser.add_argument(
151+ "-c",
152+ "--category",
153+ nargs="+",
154+ default=[],
155+ choices=[
156+ "sofa",
157+ "chair",
158+ "dining_chair",
159+ "bar_chair",
160+ "stool",
161+ "bed",
162+ "pillow",
163+ "wardrobe",
164+ "nightstand",
165+ "tv_cabinet",
166+ "wine_cabinet",
167+ "bathroom_cabinet",
168+ "shoe_cabinet",
169+ "entrance_cabinet",
170+ "decorative_cabinet",
171+ "washing_cabinet",
172+ "wall_cabinet",
173+ "sideboard",
174+ "cupboard",
175+ "coffee_table",
176+ "dining_table",
177+ "side_table",
178+ "dressing_table",
179+ "desk",
180+ "integrated_stove",
181+ "gas_stove",
182+ "range_hood",
183+ "micro-wave_oven",
184+ "sink",
185+ "stove",
186+ "refrigerator",
187+ "hand_sink",
188+ "shower",
189+ "shower_room",
190+ "toilet",
191+ "tub",
192+ "illumination",
193+ "chandelier",
194+ "floor-standing_lamp",
195+ "wall_decoration",
196+ "painting",
197+ "curtain",
198+ "carpet",
199+ "plants",
200+ "potted_bonsai",
201+ "tv",
202+ "computer",
203+ "air_conditioner",
204+ "washing_machine",
205+ "clothes_rack",
206+ "mirror",
207+ "bookcase",
208+ "cushion",
209+ "bar",
210+ "screen",
211+ "combination_sofa",
212+ "dining_table_combination",
213+ "leisure_table_and_chair_combination",
214+ "multifunctional_combination_bed",
215+ ],
216+ help="A list of categories of objects to detect. If not specified, all categories will be detected.",
217+ )
134218 parser.add_argument(
135219 "-t",
136220 "--code_template_file",
@@ -162,15 +246,38 @@
162246 default=1,
163247 help="The number of beams for beam search",
164248 )
249+ parser.add_argument(
250+ "--inference_dtype",
251+ type=str,
252+ default="bfloat16",
253+ help="The torch dtype to use for inference, bfloat16 or float32",
254+ )
255+ parser.add_argument(
256+ "--no_cleanup",
257+ default=False,
258+ action="store_true",
259+ help="Whether to not cleanup the point cloud",
260+ )
261+ parser.add_argument(
262+ "--seed",
263+ type=int,
264+ default=-1,
265+ help="The seed to use during inference, negative value means no seed",
266+ )
165267 args = parser.parse_args()
166268
167269 # load the model
168270 tokenizer = AutoTokenizer.from_pretrained(args.model_path)
169- model = AutoModelForCausalLM.from_pretrained(args.model_path)
271+ model = AutoModelForCausalLM.from_pretrained(
272+ args.model_path, torch_dtype=getattr(torch, args.inference_dtype)
273+ )
170274 model.to("cuda")
171275 model.set_point_backbone_dtype(torch.float32)
172276 model.eval()
173277
278+ # number of bins used for discretization
279+ num_bins = model.config.point_config["num_bins"]
280+
174281 # check if the input is a single point cloud file or a folder containing multiple point cloud files
175282 if os.path.isfile(args.point_cloud):
176283 point_cloud_files = [args.point_cloud]
@@ -180,13 +287,15 @@
180287 for point_cloud_file in tqdm(point_cloud_files):
181288 # load the point cloud
182289 point_cloud = load_o3d_pcd(point_cloud_file)
183- point_cloud = cleanup_pcd(point_cloud)
290+ grid_size = Layout.get_grid_size(num_bins)
291+
292+ if not args.no_cleanup:
293+ point_cloud = cleanup_pcd(point_cloud, voxel_size=grid_size)
294+
184295 points, colors = get_points_and_colors(point_cloud)
185296 min_extent = np.min(points, axis=0)
186297
187298 # preprocess the point cloud to tensor features
188- grid_size = Layout.get_grid_size()
189- num_bins = Layout.get_num_bins()
190299 input_pcd = preprocess_point_cloud(points, colors, grid_size, num_bins)
191300
192301 # generate the layout
@@ -195,10 +304,13 @@
195304 input_pcd,
196305 tokenizer,
197306 args.code_template_file,
198- args.top_k,
199- args.top_p,
200- args.temperature,
201- args.num_beams,
307+ top_k=args.top_k,
308+ top_p=args.top_p,
309+ temperature=args.temperature,
310+ num_beams=args.num_beams,
311+ seed=args.seed,
312+ detect_type=args.detect_type,
313+ categories=args.category,
202314 )
203315 layout.translate(min_extent)
204316 pred_language_string = layout.to_language_string()
modified pyproject.toml +12 −4
@@ -1,13 +1,13 @@
11 [tool.poetry]
22 name = "spatiallm"
3-version = "0.1.0"
4-description = "SpatialLM: Large Language Model for Spatial Understanding"
3+version = "0.1.1"
4+description = "SpatialLM: Training Large Language Models for Structured Indoor Modeling"
55 authors = ["ManyCore Research Team"]
66 license = "Llama3.2"
77 readme = "README.md"
88
99 [tool.poetry.dependencies]
10-python = ">=3.10,<3.12"
10+python = ">=3.10,<=3.12"
1111 torch = { version = "^2.4.1+cu124", source = "pytorch" }
1212 torchvision = { version = "^0.19.1+cu124", source = "pytorch" }
1313 torchaudio = { version = "^2.4.1+cu124", source = "pytorch" }
@@ -21,7 +21,7 @@
2121 toml = "^0.10.2"
2222 tokenizers = ">=0.19.0,<0.20.4"
2323 huggingface_hub = ">=0.25.0"
24-rerun-sdk = ">=0.21.0"
24+rerun-sdk = "^0.21.0"
2525 shapely = "^2.0.7"
2626 bbox = "^0.9.4"
2727 terminaltables = "^3.1.10"
@@ -33,6 +33,14 @@
3333
3434 [tool.poe.tasks]
3535 install-torchsparse = "pip install git+https://github.com/mit-han-lab/torchsparse.git"
36+install-flash-attn = "pip install ninja flash-attn --no-build-isolation"
37+install-torch-scatter = "pip install torch-scatter -f https://data.pyg.org/whl/torch-2.4.0+cu124.html"
38+install-spconv = "pip install timm spconv-cu120"
39+install-sonata = [
40+ "install-flash-attn",
41+ "install-torch-scatter",
42+ "install-spconv",
43+]
3644
3745 [build-system]
3846 requires = ["poetry-core", "setuptools", "wheel", "torch"]
modified spatiallm/__init__.py +0 −2
@@ -1,6 +1,5 @@
11 from .layout.layout import Layout
22 from .layout.entity import Wall, Door, Window, Bbox
3-from .model.pcd_encoder import PointCloudEncoder
43 from .model.spatiallm_llama import SpatialLMLlamaForCausalLM, SpatialLMLlamaConfig
54 from .model.spatiallm_qwen import SpatialLMQwenForCausalLM, SpatialLMQwenConfig
65
@@ -10,7 +9,6 @@
109 "Door",
1110 "Window",
1211 "Bbox",
13- "PointCloudEncoder",
1412 "SpatialLMLlamaForCausalLM",
1513 "SpatialLMLlamaConfig",
1614 "SpatialLMQwenForCausalLM",
modified spatiallm/layout/entity.py +6 −13
@@ -18,7 +18,6 @@
1818 "width": (0.0, 25.6),
1919 "scale": (0.0, 20.0),
2020 "angle": (-6.2832, 6.2832),
21- "num_bins": 640,
2221 }
2322
2423
@@ -76,10 +75,9 @@
7675 self.az *= scaling
7776 self.bx *= scaling
7877
79- def normalize_and_discretize(self):
78+ def normalize_and_discretize(self, num_bins):
8079 height_min, height_max = NORMALIZATION_PRESET["height"]
8180 world_min, world_max = NORMALIZATION_PRESET["world"]
82- num_bins = NORMALIZATION_PRESET["num_bins"]
8381
8482 self.height = (self.height - height_min) / (height_max - height_min) * num_bins
8583 self.thickness = (
@@ -101,8 +99,7 @@
10199 self.by = np.clip(self.by, 0, num_bins - 1)
102100 self.bz = np.clip(self.bz, 0, num_bins - 1)
103101
104- def undiscretize_and_unnormalize(self):
105- num_bins = NORMALIZATION_PRESET["num_bins"]
102+ def undiscretize_and_unnormalize(self, num_bins):
106103 height_min, height_max = NORMALIZATION_PRESET["height"]
107104 world_min, world_max = NORMALIZATION_PRESET["world"]
108105
@@ -174,11 +171,10 @@
174171 self.position_y *= scaling
175172 self.position_z *= scaling
176173
177- def normalize_and_discretize(self):
174+ def normalize_and_discretize(self, num_bins):
178175 width_min, width_max = NORMALIZATION_PRESET["width"]
179176 height_min, height_max = NORMALIZATION_PRESET["height"]
180177 world_min, world_max = NORMALIZATION_PRESET["world"]
181- num_bins = NORMALIZATION_PRESET["num_bins"]
182178
183179 self.width = (self.width - width_min) / (width_max - width_min) * num_bins
184180 self.height = (self.height - height_min) / (height_max - height_min) * num_bins
@@ -198,8 +194,7 @@
198194 self.position_y = np.clip(self.position_y, 0, num_bins - 1)
199195 self.position_z = np.clip(self.position_z, 0, num_bins - 1)
200196
201- def undiscretize_and_unnormalize(self):
202- num_bins = NORMALIZATION_PRESET["num_bins"]
197+ def undiscretize_and_unnormalize(self, num_bins):
203198 width_min, width_max = NORMALIZATION_PRESET["width"]
204199 height_min, height_max = NORMALIZATION_PRESET["height"]
205200 world_min, world_max = NORMALIZATION_PRESET["world"]
@@ -288,11 +283,10 @@
288283 self.position_y *= scaling
289284 self.position_z *= scaling
290285
291- def normalize_and_discretize(self):
286+ def normalize_and_discretize(self, num_bins):
292287 world_min, world_max = NORMALIZATION_PRESET["world"]
293288 scale_min, scale_max = NORMALIZATION_PRESET["scale"]
294289 angle_min, angle_max = NORMALIZATION_PRESET["angle"]
295- num_bins = NORMALIZATION_PRESET["num_bins"]
296290
297291 self.position_x = (
298292 (self.position_x - world_min) / (world_max - world_min) * num_bins
@@ -316,11 +310,10 @@
316310 self.scale_y = np.clip(self.scale_y, 0, num_bins - 1)
317311 self.scale_z = np.clip(self.scale_z, 0, num_bins - 1)
318312
319- def undiscretize_and_unnormalize(self):
313+ def undiscretize_and_unnormalize(self, num_bins):
320314 world_min, world_max = NORMALIZATION_PRESET["world"]
321315 scale_min, scale_max = NORMALIZATION_PRESET["scale"]
322316 angle_min, angle_max = NORMALIZATION_PRESET["angle"]
323- num_bins = NORMALIZATION_PRESET["num_bins"]
324317
325318 self.position_x = self.position_x / num_bins
326319 self.position_y = self.position_y / num_bins
modified spatiallm/layout/layout.py +6 −10
@@ -14,13 +14,9 @@
1414 self.from_str(str)
1515
1616 @staticmethod
17- def get_grid_size():
17+ def get_grid_size(num_bins):
1818 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"]
19+ return (world_max - world_min) / num_bins
2420
2521 def from_str(self, s: str):
2622 s = s.lstrip("\n")
@@ -184,13 +180,13 @@
184180 def get_entities(self):
185181 return self.walls + self.doors + self.windows + self.bboxes
186182
187- def normalize_and_discretize(self):
183+ def normalize_and_discretize(self, num_bins):
188184 for entity in self.get_entities():
189- entity.normalize_and_discretize()
185+ entity.normalize_and_discretize(num_bins)
190186
191- def undiscretize_and_unnormalize(self):
187+ def undiscretize_and_unnormalize(self, num_bins):
192188 for entity in self.get_entities():
193- entity.undiscretize_and_unnormalize()
189+ entity.undiscretize_and_unnormalize(num_bins)
194190
195191 def translate(self, translation: np.ndarray):
196192 for entity in self.get_entities():
modified spatiallm/model/__init__.py +11 −0
@@ -0,0 +1,11 @@
1+from enum import Enum
2+
3+
4+class PointBackboneType(Enum):
5+ SCENESCRIPT = "scenescript"
6+ SONATA = "sonata"
7+
8+
9+class ProjectorType(Enum):
10+ LINEAR = "linear"
11+ MLP = "mlp"
deleted spatiallm/model/pcd_encoder.py +0 −299
@@ -1,299 +0,0 @@
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/scenescript_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/serialization/__init__.py +8 −0
@@ -0,0 +1,8 @@
1+from .default import (
2+ encode,
3+ decode,
4+ z_order_encode,
5+ z_order_decode,
6+ hilbert_encode,
7+ hilbert_decode,
8+)
added spatiallm/model/serialization/default.py +59 −0
@@ -0,0 +1,59 @@
1+import torch
2+from .z_order import xyz2key as z_order_encode_
3+from .z_order import key2xyz as z_order_decode_
4+from .hilbert import encode as hilbert_encode_
5+from .hilbert import decode as hilbert_decode_
6+
7+
8+@torch.inference_mode()
9+def encode(grid_coord, batch=None, depth=16, order="z"):
10+ assert order in {"z", "z-trans", "hilbert", "hilbert-trans"}
11+ if order == "z":
12+ code = z_order_encode(grid_coord, depth=depth)
13+ elif order == "z-trans":
14+ code = z_order_encode(grid_coord[:, [1, 0, 2]], depth=depth)
15+ elif order == "hilbert":
16+ code = hilbert_encode(grid_coord, depth=depth)
17+ elif order == "hilbert-trans":
18+ code = hilbert_encode(grid_coord[:, [1, 0, 2]], depth=depth)
19+ else:
20+ raise NotImplementedError
21+ if batch is not None:
22+ batch = batch.long()
23+ code = batch << depth * 3 | code
24+ return code
25+
26+
27+@torch.inference_mode()
28+def decode(code, depth=16, order="z"):
29+ assert order in {"z", "hilbert"}
30+ batch = code >> depth * 3
31+ code = code & ((1 << depth * 3) - 1)
32+ if order == "z":
33+ grid_coord = z_order_decode(code, depth=depth)
34+ elif order == "hilbert":
35+ grid_coord = hilbert_decode(code, depth=depth)
36+ else:
37+ raise NotImplementedError
38+ return grid_coord, batch
39+
40+
41+def z_order_encode(grid_coord: torch.Tensor, depth: int = 16):
42+ x, y, z = grid_coord[:, 0].long(), grid_coord[:, 1].long(), grid_coord[:, 2].long()
43+ # we block the support to batch, maintain batched code in Point class
44+ code = z_order_encode_(x, y, z, b=None, depth=depth)
45+ return code
46+
47+
48+def z_order_decode(code: torch.Tensor, depth):
49+ x, y, z = z_order_decode_(code, depth=depth)
50+ grid_coord = torch.stack([x, y, z], dim=-1) # (N, 3)
51+ return grid_coord
52+
53+
54+def hilbert_encode(grid_coord: torch.Tensor, depth: int = 16):
55+ return hilbert_encode_(grid_coord, num_dims=3, num_bits=depth)
56+
57+
58+def hilbert_decode(code: torch.Tensor, depth: int = 16):
59+ return hilbert_decode_(code, num_dims=3, num_bits=depth)
added spatiallm/model/serialization/hilbert.py +303 −0
@@ -0,0 +1,303 @@
1+"""
2+Hilbert Order
3+Modified from https://github.com/PrincetonLIPS/numpy-hilbert-curve
4+
5+Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com), Kaixin Xu
6+Please cite our work if the code is helpful to you.
7+"""
8+
9+import torch
10+
11+
12+def right_shift(binary, k=1, axis=-1):
13+ """Right shift an array of binary values.
14+
15+ Parameters:
16+ -----------
17+ binary: An ndarray of binary values.
18+
19+ k: The number of bits to shift. Default 1.
20+
21+ axis: The axis along which to shift. Default -1.
22+
23+ Returns:
24+ --------
25+ Returns an ndarray with zero prepended and the ends truncated, along
26+ whatever axis was specified."""
27+
28+ # If we're shifting the whole thing, just return zeros.
29+ if binary.shape[axis] <= k:
30+ return torch.zeros_like(binary)
31+
32+ # Determine the padding pattern.
33+ # padding = [(0,0)] * len(binary.shape)
34+ # padding[axis] = (k,0)
35+
36+ # Determine the slicing pattern to eliminate just the last one.
37+ slicing = [slice(None)] * len(binary.shape)
38+ slicing[axis] = slice(None, -k)
39+ shifted = torch.nn.functional.pad(
40+ binary[tuple(slicing)], (k, 0), mode="constant", value=0
41+ )
42+
43+ return shifted
44+
45+
46+def binary2gray(binary, axis=-1):
47+ """Convert an array of binary values into Gray codes.
48+
49+ This uses the classic X ^ (X >> 1) trick to compute the Gray code.
50+
51+ Parameters:
52+ -----------
53+ binary: An ndarray of binary values.
54+
55+ axis: The axis along which to compute the gray code. Default=-1.
56+
57+ Returns:
58+ --------
59+ Returns an ndarray of Gray codes.
60+ """
61+ shifted = right_shift(binary, axis=axis)
62+
63+ # Do the X ^ (X >> 1) trick.
64+ gray = torch.logical_xor(binary, shifted)
65+
66+ return gray
67+
68+
69+def gray2binary(gray, axis=-1):
70+ """Convert an array of Gray codes back into binary values.
71+
72+ Parameters:
73+ -----------
74+ gray: An ndarray of gray codes.
75+
76+ axis: The axis along which to perform Gray decoding. Default=-1.
77+
78+ Returns:
79+ --------
80+ Returns an ndarray of binary values.
81+ """
82+
83+ # Loop the log2(bits) number of times necessary, with shift and xor.
84+ shift = 2 ** (torch.Tensor([gray.shape[axis]]).log2().ceil().int() - 1)
85+ while shift > 0:
86+ gray = torch.logical_xor(gray, right_shift(gray, shift))
87+ shift = torch.div(shift, 2, rounding_mode="floor")
88+ return gray
89+
90+
91+def encode(locs, num_dims, num_bits):
92+ """Decode an array of locations in a hypercube into a Hilbert integer.
93+
94+ This is a vectorized-ish version of the Hilbert curve implementation by John
95+ Skilling as described in:
96+
97+ Skilling, J. (2004, April). Programming the Hilbert curve. In AIP Conference
98+ Proceedings (Vol. 707, No. 1, pp. 381-387). American Institute of Physics.
99+
100+ Params:
101+ -------
102+ locs - An ndarray of locations in a hypercube of num_dims dimensions, in
103+ which each dimension runs from 0 to 2**num_bits-1. The shape can
104+ be arbitrary, as long as the last dimension of the same has size
105+ num_dims.
106+
107+ num_dims - The dimensionality of the hypercube. Integer.
108+
109+ num_bits - The number of bits for each dimension. Integer.
110+
111+ Returns:
112+ --------
113+ The output is an ndarray of uint64 integers with the same shape as the
114+ input, excluding the last dimension, which needs to be num_dims.
115+ """
116+
117+ # Keep around the original shape for later.
118+ orig_shape = locs.shape
119+ bitpack_mask = 1 << torch.arange(0, 8).to(locs.device)
120+ bitpack_mask_rev = bitpack_mask.flip(-1)
121+
122+ if orig_shape[-1] != num_dims:
123+ raise ValueError(
124+ """
125+ The shape of locs was surprising in that the last dimension was of size
126+ %d, but num_dims=%d. These need to be equal.
127+ """
128+ % (orig_shape[-1], num_dims)
129+ )
130+
131+ if num_dims * num_bits > 63:
132+ raise ValueError(
133+ """
134+ num_dims=%d and num_bits=%d for %d bits total, which can't be encoded
135+ into a int64. Are you sure you need that many points on your Hilbert
136+ curve?
137+ """
138+ % (num_dims, num_bits, num_dims * num_bits)
139+ )
140+
141+ # Treat the location integers as 64-bit unsigned and then split them up into
142+ # a sequence of uint8s. Preserve the association by dimension.
143+ locs_uint8 = locs.long().view(torch.uint8).reshape((-1, num_dims, 8)).flip(-1)
144+
145+ # Now turn these into bits and truncate to num_bits.
146+ gray = (
147+ locs_uint8.unsqueeze(-1)
148+ .bitwise_and(bitpack_mask_rev)
149+ .ne(0)
150+ .byte()
151+ .flatten(-2, -1)[..., -num_bits:]
152+ )
153+
154+ # Run the decoding process the other way.
155+ # Iterate forwards through the bits.
156+ for bit in range(0, num_bits):
157+ # Iterate forwards through the dimensions.
158+ for dim in range(0, num_dims):
159+ # Identify which ones have this bit active.
160+ mask = gray[:, dim, bit]
161+
162+ # Where this bit is on, invert the 0 dimension for lower bits.
163+ gray[:, 0, bit + 1 :] = torch.logical_xor(
164+ gray[:, 0, bit + 1 :], mask[:, None]
165+ )
166+
167+ # Where the bit is off, exchange the lower bits with the 0 dimension.
168+ to_flip = torch.logical_and(
169+ torch.logical_not(mask[:, None]).repeat(1, gray.shape[2] - bit - 1),
170+ torch.logical_xor(gray[:, 0, bit + 1 :], gray[:, dim, bit + 1 :]),
171+ )
172+ gray[:, dim, bit + 1 :] = torch.logical_xor(
173+ gray[:, dim, bit + 1 :], to_flip
174+ )
175+ gray[:, 0, bit + 1 :] = torch.logical_xor(gray[:, 0, bit + 1 :], to_flip)
176+
177+ # Now flatten out.
178+ gray = gray.swapaxes(1, 2).reshape((-1, num_bits * num_dims))
179+
180+ # Convert Gray back to binary.
181+ hh_bin = gray2binary(gray)
182+
183+ # Pad back out to 64 bits.
184+ extra_dims = 64 - num_bits * num_dims
185+ padded = torch.nn.functional.pad(hh_bin, (extra_dims, 0), "constant", 0)
186+
187+ # Convert binary values into uint8s.
188+ hh_uint8 = (
189+ (padded.flip(-1).reshape((-1, 8, 8)) * bitpack_mask)
190+ .sum(2)
191+ .squeeze()
192+ .type(torch.uint8)
193+ )
194+
195+ # Convert uint8s into uint64s.
196+ hh_uint64 = hh_uint8.view(torch.int64).squeeze()
197+
198+ return hh_uint64
199+
200+
201+def decode(hilberts, num_dims, num_bits):
202+ """Decode an array of Hilbert integers into locations in a hypercube.
203+
204+ This is a vectorized-ish version of the Hilbert curve implementation by John
205+ Skilling as described in:
206+
207+ Skilling, J. (2004, April). Programming the Hilbert curve. In AIP Conference
208+ Proceedings (Vol. 707, No. 1, pp. 381-387). American Institute of Physics.
209+
210+ Params:
211+ -------
212+ hilberts - An ndarray of Hilbert integers. Must be an integer dtype and
213+ cannot have fewer bits than num_dims * num_bits.
214+
215+ num_dims - The dimensionality of the hypercube. Integer.
216+
217+ num_bits - The number of bits for each dimension. Integer.
218+
219+ Returns:
220+ --------
221+ The output is an ndarray of unsigned integers with the same shape as hilberts
222+ but with an additional dimension of size num_dims.
223+ """
224+
225+ if num_dims * num_bits > 64:
226+ raise ValueError(
227+ """
228+ num_dims=%d and num_bits=%d for %d bits total, which can't be encoded
229+ into a uint64. Are you sure you need that many points on your Hilbert
230+ curve?
231+ """
232+ % (num_dims, num_bits)
233+ )
234+
235+ # Handle the case where we got handed a naked integer.
236+ hilberts = torch.atleast_1d(hilberts)
237+
238+ # Keep around the shape for later.
239+ orig_shape = hilberts.shape
240+ bitpack_mask = 2 ** torch.arange(0, 8).to(hilberts.device)
241+ bitpack_mask_rev = bitpack_mask.flip(-1)
242+
243+ # Treat each of the hilberts as a s equence of eight uint8.
244+ # This treats all of the inputs as uint64 and makes things uniform.
245+ hh_uint8 = (
246+ hilberts.ravel().type(torch.int64).view(torch.uint8).reshape((-1, 8)).flip(-1)
247+ )
248+
249+ # Turn these lists of uints into lists of bits and then truncate to the size
250+ # we actually need for using Skilling's procedure.
251+ hh_bits = (
252+ hh_uint8.unsqueeze(-1)
253+ .bitwise_and(bitpack_mask_rev)
254+ .ne(0)
255+ .byte()
256+ .flatten(-2, -1)[:, -num_dims * num_bits :]
257+ )
258+
259+ # Take the sequence of bits and Gray-code it.
260+ gray = binary2gray(hh_bits)
261+
262+ # There has got to be a better way to do this.
263+ # I could index them differently, but the eventual packbits likes it this way.
264+ gray = gray.reshape((-1, num_bits, num_dims)).swapaxes(1, 2)
265+
266+ # Iterate backwards through the bits.
267+ for bit in range(num_bits - 1, -1, -1):
268+ # Iterate backwards through the dimensions.
269+ for dim in range(num_dims - 1, -1, -1):
270+ # Identify which ones have this bit active.
271+ mask = gray[:, dim, bit]
272+
273+ # Where this bit is on, invert the 0 dimension for lower bits.
274+ gray[:, 0, bit + 1 :] = torch.logical_xor(
275+ gray[:, 0, bit + 1 :], mask[:, None]
276+ )
277+
278+ # Where the bit is off, exchange the lower bits with the 0 dimension.
279+ to_flip = torch.logical_and(
280+ torch.logical_not(mask[:, None]),
281+ torch.logical_xor(gray[:, 0, bit + 1 :], gray[:, dim, bit + 1 :]),
282+ )
283+ gray[:, dim, bit + 1 :] = torch.logical_xor(
284+ gray[:, dim, bit + 1 :], to_flip
285+ )
286+ gray[:, 0, bit + 1 :] = torch.logical_xor(gray[:, 0, bit + 1 :], to_flip)
287+
288+ # Pad back out to 64 bits.
289+ extra_dims = 64 - num_bits
290+ padded = torch.nn.functional.pad(gray, (extra_dims, 0), "constant", 0)
291+
292+ # Now chop these up into blocks of 8.
293+ locs_chopped = padded.flip(-1).reshape((-1, num_dims, 8, 8))
294+
295+ # Take those blocks and turn them unto uint8s.
296+ # from IPython import embed; embed()
297+ locs_uint8 = (locs_chopped * bitpack_mask).sum(3).squeeze().type(torch.uint8)
298+
299+ # Finally, treat these as uint64s.
300+ flat_locs = locs_uint8.view(torch.int64)
301+
302+ # Return them in the expected shape.
303+ return flat_locs.reshape((*orig_shape, num_dims))
added spatiallm/model/serialization/z_order.py +126 −0
@@ -0,0 +1,126 @@
1+# --------------------------------------------------------
2+# Octree-based Sparse Convolutional Neural Networks
3+# Copyright (c) 2022 Peng-Shuai Wang <wangps@hotmail.com>
4+# Licensed under The MIT License [see LICENSE for details]
5+# Written by Peng-Shuai Wang
6+# --------------------------------------------------------
7+
8+import torch
9+from typing import Optional, Union
10+
11+
12+class KeyLUT:
13+ def __init__(self):
14+ r256 = torch.arange(256, dtype=torch.int64)
15+ r512 = torch.arange(512, dtype=torch.int64)
16+ zero = torch.zeros(256, dtype=torch.int64)
17+ device = torch.device("cpu")
18+
19+ self._encode = {
20+ device: (
21+ self.xyz2key(r256, zero, zero, 8),
22+ self.xyz2key(zero, r256, zero, 8),
23+ self.xyz2key(zero, zero, r256, 8),
24+ )
25+ }
26+ self._decode = {device: self.key2xyz(r512, 9)}
27+
28+ def encode_lut(self, device=torch.device("cpu")):
29+ if device not in self._encode:
30+ cpu = torch.device("cpu")
31+ self._encode[device] = tuple(e.to(device) for e in self._encode[cpu])
32+ return self._encode[device]
33+
34+ def decode_lut(self, device=torch.device("cpu")):
35+ if device not in self._decode:
36+ cpu = torch.device("cpu")
37+ self._decode[device] = tuple(e.to(device) for e in self._decode[cpu])
38+ return self._decode[device]
39+
40+ def xyz2key(self, x, y, z, depth):
41+ key = torch.zeros_like(x)
42+ for i in range(depth):
43+ mask = 1 << i
44+ key = (
45+ key
46+ | ((x & mask) << (2 * i + 2))
47+ | ((y & mask) << (2 * i + 1))
48+ | ((z & mask) << (2 * i + 0))
49+ )
50+ return key
51+
52+ def key2xyz(self, key, depth):
53+ x = torch.zeros_like(key)
54+ y = torch.zeros_like(key)
55+ z = torch.zeros_like(key)
56+ for i in range(depth):
57+ x = x | ((key & (1 << (3 * i + 2))) >> (2 * i + 2))
58+ y = y | ((key & (1 << (3 * i + 1))) >> (2 * i + 1))
59+ z = z | ((key & (1 << (3 * i + 0))) >> (2 * i + 0))
60+ return x, y, z
61+
62+
63+_key_lut = KeyLUT()
64+
65+
66+def xyz2key(
67+ x: torch.Tensor,
68+ y: torch.Tensor,
69+ z: torch.Tensor,
70+ b: Optional[Union[torch.Tensor, int]] = None,
71+ depth: int = 16,
72+):
73+ r"""Encodes :attr:`x`, :attr:`y`, :attr:`z` coordinates to the shuffled keys
74+ based on pre-computed look up tables. The speed of this function is much
75+ faster than the method based on for-loop.
76+
77+ Args:
78+ x (torch.Tensor): The x coordinate.
79+ y (torch.Tensor): The y coordinate.
80+ z (torch.Tensor): The z coordinate.
81+ b (torch.Tensor or int): The batch index of the coordinates, and should be
82+ smaller than 32768. If :attr:`b` is :obj:`torch.Tensor`, the size of
83+ :attr:`b` must be the same as :attr:`x`, :attr:`y`, and :attr:`z`.
84+ depth (int): The depth of the shuffled key, and must be smaller than 17 (< 17).
85+ """
86+
87+ EX, EY, EZ = _key_lut.encode_lut(x.device)
88+ x, y, z = x.long(), y.long(), z.long()
89+
90+ mask = 255 if depth > 8 else (1 << depth) - 1
91+ key = EX[x & mask] | EY[y & mask] | EZ[z & mask]
92+ if depth > 8:
93+ mask = (1 << (depth - 8)) - 1
94+ key16 = EX[(x >> 8) & mask] | EY[(y >> 8) & mask] | EZ[(z >> 8) & mask]
95+ key = key16 << 24 | key
96+
97+ if b is not None:
98+ b = b.long()
99+ key = b << 48 | key
100+
101+ return key
102+
103+
104+def key2xyz(key: torch.Tensor, depth: int = 16):
105+ r"""Decodes the shuffled key to :attr:`x`, :attr:`y`, :attr:`z` coordinates
106+ and the batch index based on pre-computed look up tables.
107+
108+ Args:
109+ key (torch.Tensor): The shuffled key.
110+ depth (int): The depth of the shuffled key, and must be smaller than 17 (< 17).
111+ """
112+
113+ DX, DY, DZ = _key_lut.decode_lut(key.device)
114+ x, y, z = torch.zeros_like(key), torch.zeros_like(key), torch.zeros_like(key)
115+
116+ b = key >> 48
117+ key = key & ((1 << 48) - 1)
118+
119+ n = (depth + 2) // 3
120+ for i in range(n):
121+ k = key >> (i * 9) & 511
122+ x = x | (DX[k] << (i * 3))
123+ y = y | (DY[k] << (i * 3))
124+ z = z | (DZ[k] << (i * 3))
125+
126+ return x, y, z, b
added spatiallm/model/sonata_encoder.py +937 −0
@@ -0,0 +1,937 @@
1+"""
2+Point Transformer - V3 Mode2 - Sonata
3+Pointcept detached version
4+
5+Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
6+"""
7+
8+# Copyright (c) Meta Platforms, Inc. and affiliates.
9+#
10+# Licensed under the Apache License, Version 2.0 (the "License");
11+# you may not use this file except in compliance with the License.
12+# You may obtain a copy of the License at
13+#
14+# http://www.apache.org/licenses/LICENSE-2.0
15+#
16+# Unless required by applicable law or agreed to in writing, software
17+# distributed under the License is distributed on an "AS IS" BASIS,
18+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19+# See the License for the specific language governing permissions and
20+# limitations under the License.
21+
22+import sys
23+from collections import OrderedDict
24+
25+from huggingface_hub import PyTorchModelHubMixin
26+from addict import Dict
27+import torch
28+import torch.nn as nn
29+import spconv.pytorch as spconv
30+import torch_scatter
31+from timm.layers import DropPath
32+
33+try:
34+ import flash_attn
35+except ImportError:
36+ flash_attn = None
37+
38+from .serialization import encode
39+
40+
41+@torch.inference_mode()
42+def offset2bincount(offset):
43+ return torch.diff(
44+ offset, prepend=torch.tensor([0], device=offset.device, dtype=torch.long)
45+ )
46+
47+
48+@torch.inference_mode()
49+def offset2batch(offset):
50+ bincount = offset2bincount(offset)
51+ return torch.arange(
52+ len(bincount), device=offset.device, dtype=torch.long
53+ ).repeat_interleave(bincount)
54+
55+
56+@torch.inference_mode()
57+def batch2offset(batch):
58+ return torch.cumsum(batch.bincount(), dim=0).long()
59+
60+
61+class Point(Dict):
62+ """
63+ Point Structure of Pointcept
64+
65+ A Point (point cloud) in Pointcept is a dictionary that contains various properties of
66+ a batched point cloud. The property with the following names have a specific definition
67+ as follows:
68+
69+ - "coord": original coordinate of point cloud;
70+ - "grid_coord": grid coordinate for specific grid size (related to GridSampling);
71+ Point also support the following optional attributes:
72+ - "offset": if not exist, initialized as batch size is 1;
73+ - "batch": if not exist, initialized as batch size is 1;
74+ - "feat": feature of point cloud, default input of model;
75+ - "grid_size": Grid size of point cloud (related to GridSampling);
76+ (related to Serialization)
77+ - "serialized_depth": depth of serialization, 2 ** depth * grid_size describe the maximum of point cloud range;
78+ - "serialized_code": a list of serialization codes;
79+ - "serialized_order": a list of serialization order determined by code;
80+ - "serialized_inverse": a list of inverse mapping determined by code;
81+ (related to Sparsify: SpConv)
82+ - "sparse_shape": Sparse shape for Sparse Conv Tensor;
83+ - "sparse_conv_feat": SparseConvTensor init with information provide by Point;
84+ """
85+
86+ def __init__(self, *args, **kwargs):
87+ super().__init__(*args, **kwargs)
88+ # If one of "offset" or "batch" do not exist, generate by the existing one
89+ if "batch" not in self.keys() and "offset" in self.keys():
90+ self["batch"] = offset2batch(self.offset)
91+ elif "offset" not in self.keys() and "batch" in self.keys():
92+ self["offset"] = batch2offset(self.batch)
93+
94+ def serialization(self, order="z", depth=None, shuffle_orders=False):
95+ """
96+ Point Cloud Serialization
97+
98+ relay on ["grid_coord" or "coord" + "grid_size", "batch", "feat"]
99+ """
100+ self["order"] = order
101+ assert "batch" in self.keys()
102+ if "grid_coord" not in self.keys():
103+ # if you don't want to operate GridSampling in data augmentation,
104+ # please add the following augmentation into your pipeline:
105+ # dict(type="Copy", keys_dict={"grid_size": 0.01}),
106+ # (adjust `grid_size` to what your want)
107+ assert {"grid_size", "coord"}.issubset(self.keys())
108+
109+ self["grid_coord"] = torch.div(
110+ self.coord - self.coord.min(0)[0], self.grid_size, rounding_mode="trunc"
111+ ).int()
112+
113+ if depth is None:
114+ # Adaptive measure the depth of serialization cube (length = 2 ^ depth)
115+ depth = int(self.grid_coord.max() + 1).bit_length()
116+ self["serialized_depth"] = depth
117+ # Maximum bit length for serialization code is 63 (int64)
118+ assert depth * 3 + len(self.offset).bit_length() <= 63
119+ # Here we follow OCNN and set the depth limitation to 16 (48bit) for the point position.
120+ # Although depth is limited to less than 16, we can encode a 655.36^3 (2^16 * 0.01) meter^3
121+ # cube with a grid size of 0.01 meter. We consider it is enough for the current stage.
122+ # We can unlock the limitation by optimizing the z-order encoding function if necessary.
123+ assert depth <= 16
124+
125+ # The serialization codes are arranged as following structures:
126+ # [Order1 ([n]),
127+ # Order2 ([n]),
128+ # ...
129+ # OrderN ([n])] (k, n)
130+ code = [
131+ encode(self.grid_coord, self.batch, depth, order=order_) for order_ in order
132+ ]
133+ code = torch.stack(code)
134+ order = torch.argsort(code)
135+ inverse = torch.zeros_like(order).scatter_(
136+ dim=1,
137+ index=order,
138+ src=torch.arange(0, code.shape[1], device=order.device).repeat(
139+ code.shape[0], 1
140+ ),
141+ )
142+
143+ if shuffle_orders:
144+ perm = torch.randperm(code.shape[0])
145+ code = code[perm]
146+ order = order[perm]
147+ inverse = inverse[perm]
148+
149+ self["serialized_code"] = code
150+ self["serialized_order"] = order
151+ self["serialized_inverse"] = inverse
152+
153+ def sparsify(self, pad=96):
154+ """
155+ Point Cloud Serialization
156+
157+ Point cloud is sparse, here we use "sparsify" to specifically refer to
158+ preparing "spconv.SparseConvTensor" for SpConv.
159+
160+ relay on ["grid_coord" or "coord" + "grid_size", "batch", "feat"]
161+
162+ pad: padding sparse for sparse shape.
163+ """
164+ assert {"feat", "batch"}.issubset(self.keys())
165+ if "grid_coord" not in self.keys():
166+ # if you don't want to operate GridSampling in data augmentation,
167+ # please add the following augmentation into your pipeline:
168+ # dict(type="Copy", keys_dict={"grid_size": 0.01}),
169+ # (adjust `grid_size` to what your want)
170+ assert {"grid_size", "coord"}.issubset(self.keys())
171+ self["grid_coord"] = torch.div(
172+ self.coord - self.coord.min(0)[0], self.grid_size, rounding_mode="trunc"
173+ ).int()
174+ if "sparse_shape" in self.keys():
175+ sparse_shape = self.sparse_shape
176+ else:
177+ sparse_shape = torch.add(
178+ torch.max(self.grid_coord, dim=0).values, pad
179+ ).tolist()
180+ sparse_conv_feat = spconv.SparseConvTensor(
181+ features=self.feat,
182+ indices=torch.cat(
183+ [self.batch.unsqueeze(-1).int(), self.grid_coord.int()], dim=1
184+ ).contiguous(),
185+ spatial_shape=sparse_shape,
186+ batch_size=self.batch[-1].tolist() + 1,
187+ )
188+ self["sparse_shape"] = sparse_shape
189+ self["sparse_conv_feat"] = sparse_conv_feat
190+
191+
192+class PointModule(nn.Module):
193+ r"""PointModule
194+ placeholder, all module subclass from this will take Point in PointSequential.
195+ """
196+
197+ def __init__(self, *args, **kwargs):
198+ super().__init__(*args, **kwargs)
199+
200+
201+class PointSequential(PointModule):
202+ r"""A sequential container.
203+ Modules will be added to it in the order they are passed in the constructor.
204+ Alternatively, an ordered dict of modules can also be passed in.
205+ """
206+
207+ def __init__(self, *args, **kwargs):
208+ super().__init__()
209+ if len(args) == 1 and isinstance(args[0], OrderedDict):
210+ for key, module in args[0].items():
211+ self.add_module(key, module)
212+ else:
213+ for idx, module in enumerate(args):
214+ self.add_module(str(idx), module)
215+ for name, module in kwargs.items():
216+ if sys.version_info < (3, 6):
217+ raise ValueError("kwargs only supported in py36+")
218+ if name in self._modules:
219+ raise ValueError("name exists.")
220+ self.add_module(name, module)
221+
222+ def __getitem__(self, idx):
223+ if not (-len(self) <= idx < len(self)):
224+ raise IndexError("index {} is out of range".format(idx))
225+ if idx < 0:
226+ idx += len(self)
227+ it = iter(self._modules.values())
228+ for i in range(idx):
229+ next(it)
230+ return next(it)
231+
232+ def __len__(self):
233+ return len(self._modules)
234+
235+ def add(self, module, name=None):
236+ if name is None:
237+ name = str(len(self._modules))
238+ if name in self._modules:
239+ raise KeyError("name exists")
240+ self.add_module(name, module)
241+
242+ def forward(self, input):
243+ for k, module in self._modules.items():
244+ # Point module
245+ if isinstance(module, PointModule):
246+ input = module(input)
247+ # Spconv module
248+ elif spconv.modules.is_spconv_module(module):
249+ if isinstance(input, Point):
250+ input.sparse_conv_feat = module(input.sparse_conv_feat)
251+ input.feat = input.sparse_conv_feat.features
252+ else:
253+ input = module(input)
254+ # PyTorch module
255+ else:
256+ if isinstance(input, Point):
257+ input.feat = module(input.feat)
258+ if "sparse_conv_feat" in input.keys():
259+ input.sparse_conv_feat = input.sparse_conv_feat.replace_feature(
260+ input.feat
261+ )
262+ elif isinstance(input, spconv.SparseConvTensor):
263+ if input.indices.shape[0] != 0:
264+ input = input.replace_feature(module(input.features))
265+ else:
266+ input = module(input)
267+ return input
268+
269+
270+class LayerScale(nn.Module):
271+ def __init__(
272+ self,
273+ dim: int,
274+ init_values: float = 1e-5,
275+ inplace: bool = False,
276+ ) -> None:
277+ super().__init__()
278+ self.inplace = inplace
279+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
280+
281+ def forward(self, x: torch.Tensor) -> torch.Tensor:
282+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
283+
284+
285+class RPE(torch.nn.Module):
286+ def __init__(self, patch_size, num_heads):
287+ super().__init__()
288+ self.patch_size = patch_size
289+ self.num_heads = num_heads
290+ self.pos_bnd = int((4 * patch_size) ** (1 / 3) * 2)
291+ self.rpe_num = 2 * self.pos_bnd + 1
292+ self.rpe_table = torch.nn.Parameter(torch.zeros(3 * self.rpe_num, num_heads))
293+ torch.nn.init.trunc_normal_(self.rpe_table, std=0.02)
294+
295+ def forward(self, coord):
296+ idx = (
297+ coord.clamp(-self.pos_bnd, self.pos_bnd) # clamp into bnd
298+ + self.pos_bnd # relative position to positive index
299+ + torch.arange(3, device=coord.device) * self.rpe_num # x, y, z stride
300+ )
301+ out = self.rpe_table.index_select(0, idx.reshape(-1))
302+ out = out.view(idx.shape + (-1,)).sum(3)
303+ out = out.permute(0, 3, 1, 2) # (N, K, K, H) -> (N, H, K, K)
304+ return out
305+
306+
307+class SerializedAttention(PointModule):
308+ def __init__(
309+ self,
310+ channels,
311+ num_heads,
312+ patch_size,
313+ qkv_bias=True,
314+ qk_scale=None,
315+ attn_drop=0.0,
316+ proj_drop=0.0,
317+ order_index=0,
318+ enable_rpe=False,
319+ enable_flash=True,
320+ upcast_attention=True,
321+ upcast_softmax=True,
322+ ):
323+ super().__init__()
324+ assert channels % num_heads == 0
325+ self.channels = channels
326+ self.num_heads = num_heads
327+ self.scale = qk_scale or (channels // num_heads) ** -0.5
328+ self.order_index = order_index
329+ self.upcast_attention = upcast_attention
330+ self.upcast_softmax = upcast_softmax
331+ self.enable_rpe = enable_rpe
332+ self.enable_flash = enable_flash
333+ if enable_flash:
334+ assert (
335+ enable_rpe is False
336+ ), "Set enable_rpe to False when enable Flash Attention"
337+ assert (
338+ upcast_attention is False
339+ ), "Set upcast_attention to False when enable Flash Attention"
340+ assert (
341+ upcast_softmax is False
342+ ), "Set upcast_softmax to False when enable Flash Attention"
343+ assert flash_attn is not None, "Make sure flash_attn is installed."
344+ self.patch_size = patch_size
345+ self.attn_drop = attn_drop
346+ else:
347+ # when disable flash attention, we still don't want to use mask
348+ # consequently, patch size will auto set to the
349+ # min number of patch_size_max and number of points
350+ self.patch_size_max = patch_size
351+ self.patch_size = 0
352+ self.attn_drop = torch.nn.Dropout(attn_drop)
353+
354+ self.qkv = torch.nn.Linear(channels, channels * 3, bias=qkv_bias)
355+ self.proj = torch.nn.Linear(channels, channels)
356+ self.proj_drop = torch.nn.Dropout(proj_drop)
357+ self.softmax = torch.nn.Softmax(dim=-1)
358+ self.rpe = RPE(patch_size, num_heads) if self.enable_rpe else None
359+
360+ @torch.no_grad()
361+ def get_rel_pos(self, point, order):
362+ K = self.patch_size
363+ rel_pos_key = f"rel_pos_{self.order_index}"
364+ if rel_pos_key not in point.keys():
365+ grid_coord = point.grid_coord[order]
366+ grid_coord = grid_coord.reshape(-1, K, 3)
367+ point[rel_pos_key] = grid_coord.unsqueeze(2) - grid_coord.unsqueeze(1)
368+ return point[rel_pos_key]
369+
370+ @torch.no_grad()
371+ def get_padding_and_inverse(self, point):
372+ pad_key = "pad"
373+ unpad_key = "unpad"
374+ cu_seqlens_key = "cu_seqlens_key"
375+ if (
376+ pad_key not in point.keys()
377+ or unpad_key not in point.keys()
378+ or cu_seqlens_key not in point.keys()
379+ ):
380+ offset = point.offset
381+ bincount = offset2bincount(offset)
382+ bincount_pad = (
383+ torch.div(
384+ bincount + self.patch_size - 1,
385+ self.patch_size,
386+ rounding_mode="trunc",
387+ )
388+ * self.patch_size
389+ )
390+ # only pad point when num of points larger than patch_size
391+ mask_pad = bincount > self.patch_size
392+ bincount_pad = ~mask_pad * bincount + mask_pad * bincount_pad
393+ _offset = nn.functional.pad(offset, (1, 0))
394+ _offset_pad = nn.functional.pad(torch.cumsum(bincount_pad, dim=0), (1, 0))
395+ pad = torch.arange(_offset_pad[-1], device=offset.device)
396+ unpad = torch.arange(_offset[-1], device=offset.device)
397+ cu_seqlens = []
398+ for i in range(len(offset)):
399+ unpad[_offset[i] : _offset[i + 1]] += _offset_pad[i] - _offset[i]
400+ if bincount[i] != bincount_pad[i]:
401+ pad[
402+ _offset_pad[i + 1]
403+ - self.patch_size
404+ + (bincount[i] % self.patch_size) : _offset_pad[i + 1]
405+ ] = pad[
406+ _offset_pad[i + 1]
407+ - 2 * self.patch_size
408+ + (bincount[i] % self.patch_size) : _offset_pad[i + 1]
409+ - self.patch_size
410+ ]
411+ pad[_offset_pad[i] : _offset_pad[i + 1]] -= _offset_pad[i] - _offset[i]
412+ cu_seqlens.append(
413+ torch.arange(
414+ _offset_pad[i],
415+ _offset_pad[i + 1],
416+ step=self.patch_size,
417+ dtype=torch.int32,
418+ device=offset.device,
419+ )
420+ )
421+ point[pad_key] = pad
422+ point[unpad_key] = unpad
423+ point[cu_seqlens_key] = nn.functional.pad(
424+ torch.concat(cu_seqlens), (0, 1), value=_offset_pad[-1]
425+ )
426+ return point[pad_key], point[unpad_key], point[cu_seqlens_key]
427+
428+ def forward(self, point):
429+ if not self.enable_flash:
430+ self.patch_size = min(
431+ offset2bincount(point.offset).min().tolist(), self.patch_size_max
432+ )
433+
434+ H = self.num_heads
435+ K = self.patch_size
436+ C = self.channels
437+
438+ pad, unpad, cu_seqlens = self.get_padding_and_inverse(point)
439+
440+ order = point.serialized_order[self.order_index][pad]
441+ inverse = unpad[point.serialized_inverse[self.order_index]]
442+
443+ # padding and reshape feat and batch for serialized point patch
444+ qkv = self.qkv(point.feat)[order]
445+
446+ if not self.enable_flash:
447+ # encode and reshape qkv: (N', K, 3, H, C') => (3, N', H, K, C')
448+ q, k, v = (
449+ qkv.reshape(-1, K, 3, H, C // H).permute(2, 0, 3, 1, 4).unbind(dim=0)
450+ )
451+ # attn
452+ if self.upcast_attention:
453+ q = q.float()
454+ k = k.float()
455+ attn = (q * self.scale) @ k.transpose(-2, -1) # (N', H, K, K)
456+ if self.enable_rpe:
457+ attn = attn + self.rpe(self.get_rel_pos(point, order))
458+ if self.upcast_softmax:
459+ attn = attn.float()
460+ attn = self.softmax(attn)
461+ attn = self.attn_drop(attn).to(qkv.dtype)
462+ feat = (attn @ v).transpose(1, 2).reshape(-1, C)
463+ else:
464+ feat = flash_attn.flash_attn_varlen_qkvpacked_func(
465+ qkv.half().reshape(-1, 3, H, C // H),
466+ cu_seqlens,
467+ max_seqlen=self.patch_size,
468+ dropout_p=self.attn_drop if self.training else 0,
469+ softmax_scale=self.scale,
470+ ).reshape(-1, C)
471+ feat = feat.to(qkv.dtype)
472+ feat = feat[inverse]
473+
474+ # ffn
475+ feat = self.proj(feat)
476+ feat = self.proj_drop(feat)
477+ point.feat = feat
478+ return point
479+
480+
481+class MLP(nn.Module):
482+ def __init__(
483+ self,
484+ in_channels,
485+ hidden_channels=None,
486+ out_channels=None,
487+ act_layer=nn.GELU,
488+ drop=0.0,
489+ ):
490+ super().__init__()
491+ out_channels = out_channels or in_channels
492+ hidden_channels = hidden_channels or in_channels
493+ self.fc1 = nn.Linear(in_channels, hidden_channels)
494+ self.act = act_layer()
495+ self.fc2 = nn.Linear(hidden_channels, out_channels)
496+ self.drop = nn.Dropout(drop)
497+
498+ def forward(self, x):
499+ x = self.fc1(x)
500+ x = self.act(x)
501+ x = self.drop(x)
502+ x = self.fc2(x)
503+ x = self.drop(x)
504+ return x
505+
506+
507+class Block(PointModule):
508+ def __init__(
509+ self,
510+ channels,
511+ num_heads,
512+ patch_size=48,
513+ mlp_ratio=4.0,
514+ qkv_bias=True,
515+ qk_scale=None,
516+ attn_drop=0.0,
517+ proj_drop=0.0,
518+ drop_path=0.0,
519+ layer_scale=None,
520+ norm_layer=nn.LayerNorm,
521+ act_layer=nn.GELU,
522+ pre_norm=True,
523+ order_index=0,
524+ cpe_indice_key=None,
525+ enable_rpe=False,
526+ enable_flash=True,
527+ upcast_attention=True,
528+ upcast_softmax=True,
529+ ):
530+ super().__init__()
531+ self.channels = channels
532+ self.pre_norm = pre_norm
533+
534+ self.cpe = PointSequential(
535+ spconv.SubMConv3d(
536+ channels,
537+ channels,
538+ kernel_size=3,
539+ bias=True,
540+ indice_key=cpe_indice_key,
541+ ),
542+ nn.Linear(channels, channels),
543+ norm_layer(channels),
544+ )
545+
546+ self.norm1 = PointSequential(norm_layer(channels))
547+ self.ls1 = PointSequential(
548+ LayerScale(channels, init_values=layer_scale)
549+ if layer_scale is not None
550+ else nn.Identity()
551+ )
552+ self.attn = SerializedAttention(
553+ channels=channels,
554+ patch_size=patch_size,
555+ num_heads=num_heads,
556+ qkv_bias=qkv_bias,
557+ qk_scale=qk_scale,
558+ attn_drop=attn_drop,
559+ proj_drop=proj_drop,
560+ order_index=order_index,
561+ enable_rpe=enable_rpe,
562+ enable_flash=enable_flash,
563+ upcast_attention=upcast_attention,
564+ upcast_softmax=upcast_softmax,
565+ )
566+ self.norm2 = PointSequential(norm_layer(channels))
567+ self.ls2 = PointSequential(
568+ LayerScale(channels, init_values=layer_scale)
569+ if layer_scale is not None
570+ else nn.Identity()
571+ )
572+ self.mlp = PointSequential(
573+ MLP(
574+ in_channels=channels,
575+ hidden_channels=int(channels * mlp_ratio),
576+ out_channels=channels,
577+ act_layer=act_layer,
578+ drop=proj_drop,
579+ )
580+ )
581+ self.drop_path = PointSequential(
582+ DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
583+ )
584+
585+ def forward(self, point: Point):
586+ shortcut = point.feat
587+ point = self.cpe(point)
588+ point.feat = shortcut + point.feat
589+ shortcut = point.feat
590+ if self.pre_norm:
591+ point = self.norm1(point)
592+ point = self.drop_path(self.ls1(self.attn(point)))
593+ point.feat = shortcut + point.feat
594+ if not self.pre_norm:
595+ point = self.norm1(point)
596+
597+ shortcut = point.feat
598+ if self.pre_norm:
599+ point = self.norm2(point)
600+ point = self.drop_path(self.ls2(self.mlp(point)))
601+ point.feat = shortcut + point.feat
602+ if not self.pre_norm:
603+ point = self.norm2(point)
604+ point.sparse_conv_feat = point.sparse_conv_feat.replace_feature(point.feat)
605+ return point
606+
607+
608+class GridPooling(PointModule):
609+ def __init__(
610+ self,
611+ in_channels,
612+ out_channels,
613+ stride=2,
614+ norm_layer=None,
615+ act_layer=None,
616+ reduce="max",
617+ shuffle_orders=True,
618+ traceable=True, # record parent and cluster
619+ ):
620+ super().__init__()
621+ self.in_channels = in_channels
622+ self.out_channels = out_channels
623+
624+ self.stride = stride
625+ assert reduce in ["sum", "mean", "min", "max"]
626+ self.reduce = reduce
627+ self.shuffle_orders = shuffle_orders
628+ self.traceable = traceable
629+
630+ self.proj = nn.Linear(in_channels, out_channels)
631+ if norm_layer is not None:
632+ self.norm = PointSequential(norm_layer(out_channels))
633+ if act_layer is not None:
634+ self.act = PointSequential(act_layer())
635+
636+ def forward(self, point: Point):
637+ if "grid_coord" in point.keys():
638+ grid_coord = point.grid_coord
639+ elif {"coord", "grid_size"}.issubset(point.keys()):
640+ grid_coord = torch.div(
641+ point.coord - point.coord.min(0)[0],
642+ point.grid_size,
643+ rounding_mode="trunc",
644+ ).int()
645+ else:
646+ raise AssertionError(
647+ "[gird_coord] or [coord, grid_size] should be include in the Point"
648+ )
649+ grid_coord = torch.div(grid_coord, self.stride, rounding_mode="trunc")
650+ grid_coord = grid_coord | point.batch.view(-1, 1) << 48
651+ grid_coord, cluster, counts = torch.unique(
652+ grid_coord,
653+ sorted=True,
654+ return_inverse=True,
655+ return_counts=True,
656+ dim=0,
657+ )
658+ grid_coord = grid_coord & ((1 << 48) - 1)
659+ # indices of point sorted by cluster, for torch_scatter.segment_csr
660+ _, indices = torch.sort(cluster)
661+ # index pointer for sorted point, for torch_scatter.segment_csr
662+ idx_ptr = torch.cat([counts.new_zeros(1), torch.cumsum(counts, dim=0)])
663+ # head_indices of each cluster, for reduce attr e.g. code, batch
664+ head_indices = indices[idx_ptr[:-1]]
665+ point_dict = Dict(
666+ feat=torch_scatter.segment_csr(
667+ self.proj(point.feat)[indices], idx_ptr, reduce=self.reduce
668+ ),
669+ coord=torch_scatter.segment_csr(
670+ point.coord[indices], idx_ptr, reduce="mean"
671+ ),
672+ grid_coord=grid_coord,
673+ batch=point.batch[head_indices],
674+ )
675+ if "origin_coord" in point.keys():
676+ point_dict["origin_coord"] = torch_scatter.segment_csr(
677+ point.origin_coord[indices], idx_ptr, reduce="mean"
678+ )
679+ if "condition" in point.keys():
680+ point_dict["condition"] = point.condition
681+ if "context" in point.keys():
682+ point_dict["context"] = point.context
683+ if "name" in point.keys():
684+ point_dict["name"] = point.name
685+ if "split" in point.keys():
686+ point_dict["split"] = point.split
687+ if "color" in point.keys():
688+ point_dict["color"] = torch_scatter.segment_csr(
689+ point.color[indices], idx_ptr, reduce="mean"
690+ )
691+ if "grid_size" in point.keys():
692+ point_dict["grid_size"] = point.grid_size * self.stride
693+
694+ if self.traceable:
695+ point_dict["pooling_inverse"] = cluster
696+ point_dict["pooling_parent"] = point
697+ order = point.order
698+ point = Point(point_dict)
699+ if self.norm is not None:
700+ point = self.norm(point)
701+ if self.act is not None:
702+ point = self.act(point)
703+ point.serialization(order=order, shuffle_orders=self.shuffle_orders)
704+ point.sparsify()
705+ return point
706+
707+
708+class GridUnpooling(PointModule):
709+ def __init__(
710+ self,
711+ in_channels,
712+ skip_channels,
713+ out_channels,
714+ norm_layer=None,
715+ act_layer=None,
716+ traceable=False, # record parent and cluster
717+ ):
718+ super().__init__()
719+ self.proj = PointSequential(nn.Linear(in_channels, out_channels))
720+ self.proj_skip = PointSequential(nn.Linear(skip_channels, out_channels))
721+
722+ if norm_layer is not None:
723+ self.proj.add(norm_layer(out_channels))
724+ self.proj_skip.add(norm_layer(out_channels))
725+
726+ if act_layer is not None:
727+ self.proj.add(act_layer())
728+ self.proj_skip.add(act_layer())
729+
730+ self.traceable = traceable
731+
732+ def forward(self, point):
733+ assert "pooling_parent" in point.keys()
734+ assert "pooling_inverse" in point.keys()
735+ parent = point.pop("pooling_parent")
736+ inverse = point.pooling_inverse
737+ feat = point.feat
738+
739+ parent = self.proj_skip(parent)
740+ parent.feat = parent.feat + self.proj(point).feat[inverse]
741+ parent.sparse_conv_feat = parent.sparse_conv_feat.replace_feature(parent.feat)
742+
743+ if self.traceable:
744+ point.feat = feat
745+ parent["unpooling_parent"] = point
746+ return parent
747+
748+
749+class Embedding(PointModule):
750+ def __init__(
751+ self,
752+ in_channels,
753+ embed_channels,
754+ norm_layer=None,
755+ act_layer=None,
756+ mask_token=False,
757+ ):
758+ super().__init__()
759+ self.in_channels = in_channels
760+ self.embed_channels = embed_channels
761+
762+ self.stem = PointSequential(linear=nn.Linear(in_channels, embed_channels))
763+ if norm_layer is not None:
764+ self.stem.add(norm_layer(embed_channels), name="norm")
765+ if act_layer is not None:
766+ self.stem.add(act_layer(), name="act")
767+
768+ # BUG Parameters which did not receive grad for rank 0: point_backbone.embedding.mask_token
769+ # if mask_token:
770+ # self.mask_token = nn.Parameter(torch.zeros(1, embed_channels))
771+ # else:
772+ # self.mask_token = None
773+
774+ def forward(self, point: Point):
775+ point = self.stem(point)
776+ # if "mask" in point.keys():
777+ # point.feat = torch.where(
778+ # point.mask.unsqueeze(-1),
779+ # self.mask_token.to(point.feat.dtype),
780+ # point.feat,
781+ # )
782+ return point
783+
784+
785+def fourier_encode_vector(vec, num_bands=10, sample_rate=60):
786+ """Fourier encode a vector.
787+
788+ Args:
789+ vec: [N, D] torch.FloatTensor.
790+ num_bands: int.
791+ sample_rate: int.
792+
793+ Returns:
794+ [N, (2 * num_bands + 1) * D] torch.FloatTensor.
795+ """
796+ n, d = vec.shape
797+ samples = torch.linspace(1, sample_rate / 2, num_bands).to(vec.device) * torch.pi
798+ sines = torch.sin(samples[None, :, None] * vec[:, None, :])
799+ cosines = torch.cos(samples[None, :, None] * vec[:, None, :])
800+
801+ encoding = torch.stack([sines, cosines], dim=2).reshape(n, 2 * num_bands, d)
802+ encoding = torch.cat([vec[:, None, :], encoding], dim=1)
803+ return encoding.flatten(1)
804+
805+
806+class Sonata(PointModule, PyTorchModelHubMixin):
807+ def __init__(
808+ self,
809+ in_channels=6,
810+ order=("z", "z-trans"),
811+ stride=(2, 2, 2, 2),
812+ enc_depths=(3, 3, 3, 12, 3),
813+ enc_channels=(48, 96, 192, 384, 512),
814+ enc_num_head=(3, 6, 12, 24, 32),
815+ enc_patch_size=(1024, 1024, 1024, 1024, 1024),
816+ mlp_ratio=4,
817+ qkv_bias=True,
818+ qk_scale=None,
819+ attn_drop=0.0,
820+ proj_drop=0.0,
821+ drop_path=0.3,
822+ layer_scale=None,
823+ pre_norm=True,
824+ shuffle_orders=True,
825+ enable_rpe=False,
826+ enable_flash=True,
827+ upcast_attention=False,
828+ upcast_softmax=False,
829+ mask_token=False,
830+ enc_mode=True,
831+ enable_fourier_encode=False,
832+ num_bins=1280,
833+ ):
834+ super().__init__()
835+ self.num_stages = len(enc_depths)
836+ self.order = [order] if isinstance(order, str) else order
837+ self.enc_mode = enc_mode
838+ self.shuffle_orders = shuffle_orders
839+
840+ assert self.num_stages == len(stride) + 1
841+ assert self.num_stages == len(enc_depths)
842+ assert self.num_stages == len(enc_channels)
843+ assert self.num_stages == len(enc_num_head)
844+ assert self.num_stages == len(enc_patch_size)
845+
846+ # normalization layer
847+ ln_layer = nn.LayerNorm
848+ # activation layers
849+ act_layer = nn.GELU
850+
851+ self.embedding = Embedding(
852+ in_channels=in_channels,
853+ embed_channels=enc_channels[0],
854+ norm_layer=ln_layer,
855+ act_layer=act_layer,
856+ mask_token=mask_token,
857+ )
858+
859+ # encoder
860+ enc_drop_path = [
861+ x.item() for x in torch.linspace(0, drop_path, sum(enc_depths))
862+ ]
863+ self.enc = PointSequential()
864+ for s in range(self.num_stages):
865+ enc_drop_path_ = enc_drop_path[
866+ sum(enc_depths[:s]) : sum(enc_depths[: s + 1])
867+ ]
868+ enc = PointSequential()
869+ if s > 0:
870+ enc.add(
871+ GridPooling(
872+ in_channels=enc_channels[s - 1],
873+ out_channels=enc_channels[s],
874+ stride=stride[s - 1],
875+ norm_layer=ln_layer,
876+ act_layer=act_layer,
877+ ),
878+ name="down",
879+ )
880+ for i in range(enc_depths[s]):
881+ enc.add(
882+ Block(
883+ channels=enc_channels[s],
884+ num_heads=enc_num_head[s],
885+ patch_size=enc_patch_size[s],
886+ mlp_ratio=mlp_ratio,
887+ qkv_bias=qkv_bias,
888+ qk_scale=qk_scale,
889+ attn_drop=attn_drop,
890+ proj_drop=proj_drop,
891+ drop_path=enc_drop_path_[i],
892+ layer_scale=layer_scale,
893+ norm_layer=ln_layer,
894+ act_layer=act_layer,
895+ pre_norm=pre_norm,
896+ order_index=i % len(self.order),
897+ cpe_indice_key=f"stage{s}",
898+ enable_rpe=enable_rpe,
899+ enable_flash=enable_flash,
900+ upcast_attention=upcast_attention,
901+ upcast_softmax=upcast_softmax,
902+ ),
903+ name=f"block{i}",
904+ )
905+ if len(enc) != 0:
906+ self.enc.add(module=enc, name=f"enc{s}")
907+
908+ # fourier encode positional embedding inaddition to Sonata
909+ self.enable_fourier_encode = enable_fourier_encode
910+ downconvs = len(enc_channels) - 1
911+ res_reduction = 2**downconvs # voxel resolution reduction
912+ self.reduced_grid_size = int(num_bins / res_reduction)
913+ self.input_proj = (
914+ nn.Linear(enc_channels[-1] + 63, enc_channels[-1])
915+ if self.enable_fourier_encode
916+ else None
917+ ) # 63 for fourier encoding
918+
919+ def forward(self, data_dict):
920+ point = Point(data_dict)
921+ point = self.embedding(point)
922+
923+ point.serialization(order=self.order, shuffle_orders=self.shuffle_orders)
924+ point.sparsify()
925+
926+ point = self.enc(point)
927+ context = point["sparse_conv_feat"].features
928+
929+ if self.enable_fourier_encode:
930+ coords = point["grid_coord"]
931+ coords_normalised = coords / (self.reduced_grid_size - 1)
932+ encoded_coords = fourier_encode_vector(coords_normalised)
933+
934+ context = torch.cat([context, encoded_coords], dim=-1)
935+ context = self.input_proj(context)
936+
937+ return context
modified spatiallm/model/spatiallm_llama.py +49 −9
@@ -1,11 +1,9 @@
11 # Copyright (c) Manycore Tech Inc. and affiliates.
22 # All rights reserved.
33
4-from enum import Enum
54 from typing import List, Optional, Tuple, Union
65
76 import torch
8-import torchsparse
97 import torch.utils.checkpoint
108 import torch.nn.functional as F
119 from torch import nn
@@ -15,18 +13,21 @@
1513 AutoConfig,
1614 AutoModelForCausalLM,
1715 )
18-from torchsparse.utils.collate import sparse_collate
1916 from transformers.utils import logging
2017 from transformers.cache_utils import Cache
2118 from transformers.modeling_outputs import CausalLMOutputWithPast
2219 from transformers.models.llama.configuration_llama import LlamaConfig
2320
24-IGNORE_INDEX = -100
25-logger = logging.get_logger(__name__)
21+try:
22+ import torchsparse
23+ from torchsparse.utils.collate import sparse_collate
24+except ImportError:
25+ pass # Ignore the import error if torchsparse is not installed for SpatialLM1.1
2626
27+from spatiallm.model import PointBackboneType, ProjectorType
2728
28-class PointBackboneType(Enum):
29- SCENESCRIPT = "scenescript"
29+IGNORE_INDEX = -100
30+logger = logging.get_logger(__name__)
3031
3132
3233 class SpatialLMLlamaConfig(LlamaConfig):
@@ -46,7 +47,7 @@
4647 self.point_backbone = None
4748 point_config = config.point_config
4849 if self.point_backbone_type == PointBackboneType.SCENESCRIPT:
49- from spatiallm.model.pcd_encoder import PointCloudEncoder
50+ from spatiallm.model.scenescript_encoder import PointCloudEncoder
5051
5152 self.point_backbone = PointCloudEncoder(
5253 input_channels=point_config["input_channels"],
@@ -55,10 +56,38 @@
5556 num_bins=point_config["num_bins"],
5657 )
5758 embed_channels = point_config["embed_channels"]
59+ elif self.point_backbone_type == PointBackboneType.SONATA:
60+ from spatiallm.model.sonata_encoder import Sonata
61+
62+ self.point_backbone = Sonata(
63+ in_channels=point_config["in_channels"],
64+ order=point_config["order"],
65+ stride=point_config["stride"],
66+ enc_depths=point_config["enc_depths"],
67+ enc_channels=point_config["enc_channels"],
68+ enc_num_head=point_config["enc_num_head"],
69+ enc_patch_size=point_config["enc_patch_size"],
70+ mlp_ratio=point_config["mlp_ratio"],
71+ mask_token=point_config["mask_token"],
72+ enc_mode=point_config["enc_mode"],
73+ enable_fourier_encode=True,
74+ num_bins=point_config["num_bins"],
75+ )
76+ embed_channels = point_config["enc_channels"][-1]
5877 else:
5978 raise ValueError(f"Unknown point backbone type: {self.point_backbone_type}")
6079
61- self.point_proj = nn.Linear(embed_channels, config.hidden_size)
80+ self.projector_type = ProjectorType(getattr(config, "projector", "linear"))
81+ if self.projector_type == ProjectorType.LINEAR:
82+ self.point_proj = nn.Linear(embed_channels, config.hidden_size)
83+ elif self.projector_type == ProjectorType.MLP:
84+ self.point_proj = nn.Sequential(
85+ nn.Linear(embed_channels, embed_channels),
86+ nn.GELU(),
87+ nn.Linear(embed_channels, config.hidden_size),
88+ )
89+ else:
90+ raise ValueError(f"Unknown projector type: {self.projector_type}")
6291
6392 self.point_start_token_id = self.config.point_start_token_id
6493 self.point_end_token_id = self.config.point_end_token_id
@@ -81,6 +110,17 @@
81110 pc_sparse_tensor = pc_sparse_tensor.to(device)
82111 encoded_features = self.point_backbone(pc_sparse_tensor)
83112 return self.point_proj(encoded_features["context"].to(dtype))
113+ elif self.point_backbone_type == PointBackboneType.SONATA:
114+ input_dict = {
115+ "coord": feats[:, :3].to(device),
116+ "grid_coord": coords.to(device),
117+ "feat": feats.to(device),
118+ "batch": torch.zeros(coords.shape[0], dtype=torch.long).to(device),
119+ }
120+ encoded_features = self.point_backbone(input_dict)
121+ # add the batch dimension
122+ encoded_features = encoded_features.unsqueeze(0)
123+ return self.point_proj(encoded_features.to(dtype))
84124 else:
85125 raise ValueError(f"Unknown point backbone type: {self.point_backbone_type}")
86126
modified spatiallm/model/spatiallm_qwen.py +49 −9
@@ -1,11 +1,9 @@
11 # Copyright (c) Manycore Tech Inc. and affiliates.
22 # All rights reserved.
33
4-from enum import Enum
54 from typing import List, Optional, Tuple, Union
65
76 import torch
8-import torchsparse
97 import torch.utils.checkpoint
108 import torch.nn.functional as F
119 from torch import nn
@@ -15,18 +13,21 @@
1513 AutoConfig,
1614 AutoModelForCausalLM,
1715 )
18-from torchsparse.utils.collate import sparse_collate
1916 from transformers.utils import logging
2017 from transformers.cache_utils import Cache
2118 from transformers.modeling_outputs import CausalLMOutputWithPast
2219 from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
2320
24-IGNORE_INDEX = -100
25-logger = logging.get_logger(__name__)
21+try:
22+ import torchsparse
23+ from torchsparse.utils.collate import sparse_collate
24+except ImportError:
25+ pass # Ignore the import error if torchsparse is not installed for SpatialLM1.1
2626
27+from spatiallm.model import PointBackboneType, ProjectorType
2728
28-class PointBackboneType(Enum):
29- SCENESCRIPT = "scenescript"
29+IGNORE_INDEX = -100
30+logger = logging.get_logger(__name__)
3031
3132
3233 class SpatialLMQwenConfig(Qwen2Config):
@@ -46,7 +47,7 @@
4647 self.point_backbone = None
4748 point_config = config.point_config
4849 if self.point_backbone_type == PointBackboneType.SCENESCRIPT:
49- from spatiallm.model.pcd_encoder import PointCloudEncoder
50+ from spatiallm.model.scenescript_encoder import PointCloudEncoder
5051
5152 self.point_backbone = PointCloudEncoder(
5253 input_channels=point_config["input_channels"],
@@ -55,10 +56,38 @@
5556 num_bins=point_config["num_bins"],
5657 )
5758 embed_channels = point_config["embed_channels"]
59+ elif self.point_backbone_type == PointBackboneType.SONATA:
60+ from spatiallm.model.sonata_encoder import Sonata
61+
62+ self.point_backbone = Sonata(
63+ in_channels=point_config["in_channels"],
64+ order=point_config["order"],
65+ stride=point_config["stride"],
66+ enc_depths=point_config["enc_depths"],
67+ enc_channels=point_config["enc_channels"],
68+ enc_num_head=point_config["enc_num_head"],
69+ enc_patch_size=point_config["enc_patch_size"],
70+ mlp_ratio=point_config["mlp_ratio"],
71+ mask_token=point_config["mask_token"],
72+ enc_mode=point_config["enc_mode"],
73+ enable_fourier_encode=True,
74+ num_bins=point_config["num_bins"],
75+ )
76+ embed_channels = point_config["enc_channels"][-1]
5877 else:
5978 raise ValueError(f"Unknown point backbone type: {self.point_backbone_type}")
6079
61- self.point_proj = nn.Linear(embed_channels, config.hidden_size)
80+ self.projector_type = ProjectorType(getattr(config, "projector", "linear"))
81+ if self.projector_type == ProjectorType.LINEAR:
82+ self.point_proj = nn.Linear(embed_channels, config.hidden_size)
83+ elif self.projector_type == ProjectorType.MLP:
84+ self.point_proj = nn.Sequential(
85+ nn.Linear(embed_channels, embed_channels),
86+ nn.GELU(),
87+ nn.Linear(embed_channels, config.hidden_size),
88+ )
89+ else:
90+ raise ValueError(f"Unknown projector type: {self.projector_type}")
6291
6392 self.point_start_token_id = self.config.point_start_token_id
6493 self.point_end_token_id = self.config.point_end_token_id
@@ -81,6 +110,17 @@
81110 pc_sparse_tensor = pc_sparse_tensor.to(device)
82111 encoded_features = self.point_backbone(pc_sparse_tensor)
83112 return self.point_proj(encoded_features["context"].to(dtype))
113+ elif self.point_backbone_type == PointBackboneType.SONATA:
114+ input_dict = {
115+ "coord": feats[:, :3].to(device),
116+ "grid_coord": coords.to(device),
117+ "feat": feats.to(device),
118+ "batch": torch.zeros(coords.shape[0], dtype=torch.long).to(device),
119+ }
120+ encoded_features = self.point_backbone(input_dict)
121+ # add the batch dimension
122+ encoded_features = encoded_features.unsqueeze(0)
123+ return self.point_proj(encoded_features.to(dtype))
84124 else:
85125 raise ValueError(f"Unknown point backbone type: {self.point_backbone_type}")
86126
modified spatiallm/pcd/pcd_loader.py +4 −4
@@ -205,12 +205,12 @@
205205 # Preprocess a point cloud
206206 def cleanup_pcd(
207207 pcd: o3d.geometry.PointCloud,
208- voxel_size: float = 0.02,
209- num_nb: int = 3,
210- radius: float = 0.05,
208+ voxel_size: float,
209+ num_nb: int = 15,
210+ std_ratio: float = 2.0,
211211 ):
212212 # voxelize the point cloud
213213 pcd = pcd.voxel_down_sample(voxel_size)
214214 # remove outliers
215- pcd, _ = pcd.remove_radius_outlier(num_nb, radius)
215+ pcd, _ = pcd.remove_statistical_outlier(num_nb, std_ratio=std_ratio)
216216 return pcd