Elffuss BraidHub

kikocis/SpatialLM public

main · 10.9 KiBRawPermalink
1import os
2from copy import deepcopy
3from typing import TYPE_CHECKING, Dict, List, Union, Sequence, Optional, Tuple
4
5import torch
6import numpy as np
7from scipy.spatial.transform import Rotation as R
8
9from spatiallm.layout.layout import Layout
10from spatiallm.layout.entity import NORMALIZATION_PRESET
11from spatiallm.pcd import load_o3d_pcd, get_points_and_colors
12from spatiallm.pcd.transform import Compose
13
14if TYPE_CHECKING:
15 from numpy.typing import NDArray
16 from transformers import PreTrainedTokenizer
17
18 PointCloudInput = Union[str, dict, NDArray]
19
20LAYOUT_S_PLACEHOLDER = os.environ.get("LAYOUT_S_PLACEHOLDER", "<|layout_s|>")
21LAYOUT_E_PLACEHOLDER = os.environ.get("LAYOUT_E_PLACEHOLDER", "<|layout_e|>")
22POINT_S_TOKEN = os.environ.get("POINT_S_TOKEN", "<|point_start|>")
23POINT_E_TOKEN = os.environ.get("POINT_E_TOKEN", "<|point_end|>")
24POINT_CLOUD_PLACEHOLDER = os.environ.get("POINT_CLOUD_PLACEHOLDER", "<point_cloud>")
25
26
27class SpatialLMPlugin:
28 def __init__(
29 self,
30 point_token: str = "<|point_pad|>",
31 num_bins: int = 1280,
32 do_augmentation: bool = False,
33 random_rotation: bool = False,
34 ):
35 self.point_token = point_token
36
37 global_extent = NORMALIZATION_PRESET["world"]
38 self.num_bins = num_bins
39 self.grid_size = (global_extent[1] - global_extent[0]) / self.num_bins
40 self.do_augmentation = do_augmentation
41 self.random_rotation = random_rotation
42 self.augmentation = Compose(
43 [
44 dict(type="RandomColorGrayScale", p=0.05),
45 dict(type="ChromaticAutoContrast", p=0.2, blend_factor=None),
46 dict(type="ChromaticTranslation", p=0.75, ratio=0.1),
47 dict(type="ChromaticJitter", p=0.8, std=0.05),
48 dict(type="HueSaturationTranslation", hue_max=0.2, saturation_max=0.2),
49 dict(type="RandomColorDrop", p=0.1, color_augment=0.0),
50 dict(type="RandomJitter", sigma=0.025, clip=0.05, ratio=0.8, p=0.9),
51 dict(type="RandomJitter", sigma=0.2, clip=0.2, ratio=0.05, p=0.85),
52 dict(type="RandomJitter", sigma=0.4, clip=1.0, ratio=0.001, p=0.75),
53 dict(type="RandomJitter", sigma=0.5, clip=4.0, ratio=0.0005, p=0.7),
54 dict(
55 type="ElasticDistortion",
56 distortion_params=[[0.2, 0.4], [0.8, 1.6]],
57 p=[0.85, 0.5],
58 ),
59 ]
60 )
61
62 self.transform = Compose(
63 [
64 dict(type="PositiveShift"),
65 dict(type="NormalizeColor"),
66 dict(
67 type="GridSample",
68 grid_size=self.grid_size,
69 hash_type="fnv",
70 mode="train",
71 keys=("coord", "color"),
72 return_grid_coord=True,
73 max_grid_coord=self.num_bins,
74 ),
75 ]
76 )
77
78 def _preprocess_point_cloud(self, point_cloud: dict) -> np.ndarray:
79 r"""
80 Pre-processes a single point cloud.
81 """
82 point_cloud = self.transform(point_cloud)
83 coord = point_cloud["grid_coord"]
84 xyz = point_cloud["coord"]
85 color = point_cloud["color"]
86 assert len(coord) == len(xyz) == len(color)
87 return np.concatenate([coord, xyz, color], axis=1)
88
89 def _regularize_point_clouds(
90 self, point_clouds: Sequence["PointCloudInput"], **kwargs
91 ) -> torch.Tensor:
92 points_list = []
93 max_len = 0
94 for point_cloud in point_clouds:
95 if not isinstance(point_cloud, dict):
96 raise ValueError(
97 "Point cloud input must be a dictionary with 'name' and 'coord' keys."
98 )
99 point_feats = self._preprocess_point_cloud(point_cloud, **kwargs)
100 max_len = max(max_len, len(point_feats))
101 points_list.append(point_feats)
102
103 for i in range(len(points_list)):
104 points_list[i] = np.pad(
105 points_list[i],
106 ((0, max_len - len(points_list[i])), (0, 0)),
107 mode="constant",
108 constant_values=np.nan,
109 )
110
111 # convert list of point clouds to batch with shape (batch_size, max_len, 3)
112 return torch.as_tensor(np.stack(points_list, axis=0))
113
114 def _get_mm_inputs(
115 self,
116 batched_messages: Sequence[Dict[str, str]],
117 point_clouds: Sequence["PointCloudInput"],
118 ) -> dict:
119 input_dict = {"point_clouds": None} # default key
120
121 point_clouds_data = []
122 transformations = []
123 for pcd_path in point_clouds:
124 pcd = load_o3d_pcd(pcd_path)
125 points, colors = get_points_and_colors(pcd)
126
127 if self.do_augmentation:
128 data_aug = {"name": "pcd", "coord": points, "color": colors}
129 data_aug = self.augmentation(data_aug)
130 points = data_aug["coord"]
131 colors = data_aug["color"]
132
133 # randomly apply scale and rotation transformation to the point cloud
134 if self.random_rotation:
135 angle_z = np.random.random() * 2 * np.pi
136 else:
137 angle_z = np.random.choice(np.array([0, 0.5, 1.0, 1.5]) * np.pi)
138
139 scaling = np.random.uniform(0.75, 1.25)
140 rotmat = R.from_rotvec(np.array([0, 0, angle_z])).as_matrix()
141 min_bound = points.min(axis=0)
142 max_bound = points.max(axis=0)
143 center_pt = (min_bound + max_bound) / 2
144 scaled_points = (points - center_pt) * scaling
145 transformed_points = (rotmat @ scaled_points.T).T + center_pt
146 # store transformation parameters for sync the augmentation to the layout
147 transformations.append(
148 {
149 "angle_z": angle_z,
150 "center_pt": center_pt,
151 "scaling": scaling,
152 "min_bound": np.min(transformed_points, axis=0),
153 "transformed_points": transformed_points,
154 }
155 )
156
157 point_cloud = {"name": "pcd", "coord": transformed_points, "color": colors}
158 point_clouds_data.append(point_cloud)
159
160 # Here we assume each conversation has exactly one point cloud
161 assert len(batched_messages) == len(point_clouds_data)
162 processed_messages = []
163 for mi, messages in enumerate(batched_messages):
164 processed_messages.append(
165 self.process_messages(messages, [transformations[mi]])
166 )
167
168 if len(processed_messages) != 0:
169 input_dict["messages"] = processed_messages
170 if len(point_clouds_data) != 0:
171 # convert point clouds to batched tensors with shape (batch_size, max_len, 9)
172 input_dict["point_clouds"] = self._regularize_point_clouds(
173 point_clouds_data
174 )
175 return input_dict
176
177 def _validate_input(
178 self,
179 point_clouds: Sequence["PointCloudInput"],
180 ) -> None:
181 r"""
182 Validates if this model accepts the input modalities.
183 """
184 if len(point_clouds) != 0 and self.point_token is None:
185 raise ValueError(
186 "This model does not support point cloud input. Please check whether the correct `template` is used."
187 )
188
189 def process_token_ids(
190 self,
191 input_ids: List[int],
192 labels: Optional[List[int]],
193 point_clouds: Sequence["PointCloudInput"],
194 tokenizer: "PreTrainedTokenizer",
195 ) -> Tuple[List[int], Optional[List[int]]]:
196 self._validate_input(point_clouds)
197 return input_ids, labels
198
199 def process_messages(
200 self,
201 messages: Sequence[Dict[str, str]],
202 transformations: Sequence[dict],
203 ) -> List[Dict[str, str]]:
204 r"""
205 Pre-processes input messages to sync the transformation between point cloud and layout.
206 """
207 self._validate_input(transformations)
208 messages = deepcopy(messages)
209 num_point_tokens = 0
210
211 for message in messages:
212 content = message["content"]
213 if LAYOUT_S_PLACEHOLDER in content and LAYOUT_E_PLACEHOLDER in content:
214 transformation = transformations[num_point_tokens - 1]
215 min_bound = transformation["min_bound"]
216 center_pt = transformation["center_pt"]
217 scaling = transformation["scaling"]
218 transformed_points = transformation["transformed_points"]
219 layout_start_pos = content.index(LAYOUT_S_PLACEHOLDER)
220 layout_end_pos = content.index(LAYOUT_E_PLACEHOLDER)
221 layout_content = content[
222 layout_start_pos + len(LAYOUT_S_PLACEHOLDER) : layout_end_pos
223 ]
224 # parse layout_content
225 layout = Layout(layout_content)
226 # transformation augmentation
227 layout.translate(-center_pt)
228 layout.scale(scaling)
229 layout.rotate(transformation["angle_z"])
230 layout.translate(center_pt)
231 layout.filter_empty_bboxes(transformed_points, num_points=100)
232 layout.reorder_entities()
233 layout.translate(-min_bound)
234 layout.normalize_and_discretize(self.num_bins)
235 new_layout_content = layout.to_language_string()
236 content = content.replace(
237 f"{LAYOUT_S_PLACEHOLDER}{layout_content}{LAYOUT_E_PLACEHOLDER}",
238 new_layout_content,
239 )
240 message["content"] = content
241
242 if POINT_CLOUD_PLACEHOLDER in content:
243 content = content.replace(
244 POINT_CLOUD_PLACEHOLDER,
245 f"{POINT_S_TOKEN}{self.point_token}{POINT_E_TOKEN}",
246 1,
247 )
248 num_point_tokens += 1
249 message["content"] = content
250
251 if len(transformations) != num_point_tokens:
252 raise ValueError(
253 f"The number of point clouds does not match the number of {POINT_CLOUD_PLACEHOLDER} tokens."
254 )
255 return messages
256
257 def get_mm_inputs(
258 self,
259 point_clouds: Sequence["PointCloudInput"],
260 batch_prompts: Sequence[List[int]],
261 ) -> Dict[str, Union[List[dict]]]:
262 r"""
263 Builds batched multimodal inputs for VLMs.
264
265 Arguments:
266 point_clouds: a list of point cloud inputs, shape (num_point_clouds,)
267 pointlens: number of point clouds in each sample, shape (batch_size,)
268 batch_ids: token ids of input samples, shape (batch_size, seq_len)
269 processor: a processor for pre-processing images and videos
270 """
271 self._validate_input(point_clouds)
272 return self._get_mm_inputs(batch_prompts, point_clouds)
273
274
275def get_mm_plugin(
276 point_token: str = "<|point_pad|>",
277 **kwargs,
278) -> "SpatialLMPlugin":
279 return SpatialLMPlugin(point_token, **kwargs)