Elffuss BraidHub

kikocis/SpatialLM public

main · 9.7 KiBRawPermalink
1import os
2import glob
3import argparse
4
5import torch
6import numpy as np
7from tqdm import tqdm
8from threading import Thread
9from transformers import AutoTokenizer, AutoModelForCausalLM
10from transformers import TextIteratorStreamer, set_seed
11
12from spatiallm import Layout
13from spatiallm.pcd import load_o3d_pcd, get_points_and_colors, cleanup_pcd, Compose
14
15DETECT_TYPE_PROMPT = {
16 "all": "Detect walls, doors, windows, boxes.",
17 "arch": "Detect walls, doors, windows.",
18 "object": "Detect boxes.",
19}
20
21
22def preprocess_point_cloud(points, colors, grid_size, num_bins):
23 transform = Compose(
24 [
25 dict(type="PositiveShift"),
26 dict(type="NormalizeColor"),
27 dict(
28 type="GridSample",
29 grid_size=grid_size,
30 hash_type="fnv",
31 mode="test",
32 keys=("coord", "color"),
33 return_grid_coord=True,
34 max_grid_coord=num_bins,
35 ),
36 ]
37 )
38 point_cloud = transform(
39 {
40 "name": "pcd",
41 "coord": points.copy(),
42 "color": colors.copy(),
43 }
44 )
45 coord = point_cloud["grid_coord"]
46 xyz = point_cloud["coord"]
47 rgb = point_cloud["color"]
48 point_cloud = np.concatenate([coord, xyz, rgb], axis=1)
49 return torch.as_tensor(np.stack([point_cloud], axis=0))
50
51
52def generate_layout(
53 model,
54 point_cloud,
55 tokenizer,
56 code_template_file,
57 top_k=10,
58 top_p=0.95,
59 temperature=0.6,
60 num_beams=1,
61 seed=-1,
62 max_new_tokens=4096,
63 detect_type="all",
64 categories=[],
65):
66 if seed >= 0:
67 set_seed(seed)
68
69 # load the code template
70 with open(code_template_file, "r") as f:
71 code_template = f.read()
72
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}"
79
80 # prepare the conversation data
81 if model.config.model_type == "spatiallm_qwen":
82 conversation = [
83 {"role": "system", "content": "You are a helpful assistant."},
84 {"role": "user", "content": prompt},
85 ]
86 else:
87 conversation = [{"role": "user", "content": prompt}]
88
89 input_ids = tokenizer.apply_chat_template(
90 conversation, add_generation_prompt=True, return_tensors="pt"
91 )
92 input_ids = input_ids.to(model.device)
93
94 streamer = TextIteratorStreamer(
95 tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True
96 )
97
98 generate_kwargs = dict(
99 {"input_ids": input_ids, "point_clouds": point_cloud},
100 streamer=streamer,
101 max_new_tokens=max_new_tokens,
102 do_sample=True,
103 use_cache=True,
104 temperature=temperature,
105 top_p=top_p,
106 top_k=top_k,
107 num_beams=num_beams,
108 )
109 t = Thread(target=model.generate, kwargs=generate_kwargs)
110 t.start()
111
112 print("Generating layout...\n")
113 generate_texts = []
114 for text in streamer:
115 generate_texts.append(text)
116 print(text, end="", flush=True)
117 print("\nDone!")
118
119 layout_str = "".join(generate_texts)
120 layout = Layout(layout_str)
121 layout.undiscretize_and_unnormalize(num_bins=model.config.point_config["num_bins"])
122 return layout
123
124
125if __name__ == "__main__":
126 parser = argparse.ArgumentParser("SpatialLM inference script")
127 parser.add_argument(
128 "-p",
129 "--point_cloud",
130 type=str,
131 required=True,
132 help="Path to the input point cloud file or a folder containing multiple point cloud files",
133 )
134 parser.add_argument(
135 "-o",
136 "--output",
137 type=str,
138 required=True,
139 help="Path to the output layout txt file or a folder to save multiple layout txt files",
140 )
141 parser.add_argument(
142 "-m",
143 "--model_path",
144 type=str,
145 default="manycore-research/SpatialLM-Llama-1B",
146 help="Path to the model checkpoint",
147 )
148 parser.add_argument(
149 "-d",
150 "--detect_type",
151 type=str,
152 default="all",
153 choices=["all", "arch", "object"],
154 help="The type of indoor elements to detect. all: (wall, door, window, box), arch: (wall, door, window), object: (box)",
155 )
156 parser.add_argument(
157 "-c",
158 "--category",
159 nargs="+",
160 default=[],
161 choices=[
162 "sofa",
163 "chair",
164 "dining_chair",
165 "bar_chair",
166 "stool",
167 "bed",
168 "pillow",
169 "wardrobe",
170 "nightstand",
171 "tv_cabinet",
172 "wine_cabinet",
173 "bathroom_cabinet",
174 "shoe_cabinet",
175 "entrance_cabinet",
176 "decorative_cabinet",
177 "washing_cabinet",
178 "wall_cabinet",
179 "sideboard",
180 "cupboard",
181 "coffee_table",
182 "dining_table",
183 "side_table",
184 "dressing_table",
185 "desk",
186 "integrated_stove",
187 "gas_stove",
188 "range_hood",
189 "micro-wave_oven",
190 "sink",
191 "stove",
192 "refrigerator",
193 "hand_sink",
194 "shower",
195 "shower_room",
196 "toilet",
197 "tub",
198 "illumination",
199 "chandelier",
200 "floor-standing_lamp",
201 "wall_decoration",
202 "painting",
203 "curtain",
204 "carpet",
205 "plants",
206 "potted_bonsai",
207 "tv",
208 "computer",
209 "air_conditioner",
210 "washing_machine",
211 "clothes_rack",
212 "mirror",
213 "bookcase",
214 "cushion",
215 "bar",
216 "screen",
217 "combination_sofa",
218 "dining_table_combination",
219 "leisure_table_and_chair_combination",
220 "multifunctional_combination_bed",
221 ],
222 help="A list of categories of objects to detect. If not specified, all categories will be detected.",
223 )
224 parser.add_argument(
225 "-t",
226 "--code_template_file",
227 type=str,
228 default="code_template.txt",
229 help="Path to the code template file",
230 )
231 parser.add_argument(
232 "--top_k",
233 type=int,
234 default=10,
235 help="The number of highest probability vocabulary tokens to keep for top-k filtering",
236 )
237 parser.add_argument(
238 "--top_p",
239 type=float,
240 default=0.95,
241 help="The smallest set of most probable tokens with probabilities that add up to top_p or higher are kept",
242 )
243 parser.add_argument(
244 "--temperature",
245 type=float,
246 default=0.6,
247 help="The value used to module the next token probabilities",
248 )
249 parser.add_argument(
250 "--num_beams",
251 type=int,
252 default=1,
253 help="The number of beams for beam search",
254 )
255 parser.add_argument(
256 "--inference_dtype",
257 type=str,
258 default="bfloat16",
259 help="The torch dtype to use for inference, bfloat16 or float32",
260 )
261 parser.add_argument(
262 "--no_cleanup",
263 default=False,
264 action="store_true",
265 help="Whether to not cleanup the point cloud",
266 )
267 parser.add_argument(
268 "--seed",
269 type=int,
270 default=-1,
271 help="The seed to use during inference, negative value means no seed",
272 )
273 args = parser.parse_args()
274
275 # load the model
276 tokenizer = AutoTokenizer.from_pretrained(args.model_path)
277 model = AutoModelForCausalLM.from_pretrained(
278 args.model_path, torch_dtype=getattr(torch, args.inference_dtype)
279 )
280 model.to("cuda")
281 model.set_point_backbone_dtype(torch.float32)
282 model.eval()
283
284 # number of bins used for discretization
285 num_bins = model.config.point_config["num_bins"]
286
287 # check if the input is a single point cloud file or a folder containing multiple point cloud files
288 if os.path.isfile(args.point_cloud):
289 point_cloud_files = [args.point_cloud]
290 else:
291 point_cloud_files = glob.glob(os.path.join(args.point_cloud, "*.ply"))
292
293 for point_cloud_file in tqdm(point_cloud_files):
294 # load the point cloud
295 point_cloud = load_o3d_pcd(point_cloud_file)
296 grid_size = Layout.get_grid_size(num_bins)
297
298 if not args.no_cleanup:
299 point_cloud = cleanup_pcd(point_cloud, voxel_size=grid_size)
300
301 points, colors = get_points_and_colors(point_cloud)
302 min_extent = np.min(points, axis=0)
303
304 # preprocess the point cloud to tensor features
305 input_pcd = preprocess_point_cloud(points, colors, grid_size, num_bins)
306
307 # generate the layout
308 layout = generate_layout(
309 model,
310 input_pcd,
311 tokenizer,
312 args.code_template_file,
313 top_k=args.top_k,
314 top_p=args.top_p,
315 temperature=args.temperature,
316 num_beams=args.num_beams,
317 seed=args.seed,
318 detect_type=args.detect_type,
319 categories=args.category,
320 )
321 layout.translate(min_extent)
322 pred_language_string = layout.to_language_string()
323
324 # check if the output path is a file or directory
325 if os.path.splitext(args.output)[-1]:
326 with open(args.output, "w") as f:
327 f.write(pred_language_string)
328 else:
329 output_filename = os.path.basename(point_cloud_file).replace(".ply", ".txt")
330 os.makedirs(args.output, exist_ok=True)
331 with open(os.path.join(args.output, output_filename), "w") as f:
332 f.write(pred_language_string)