| 1 | import os |
| 2 | import glob |
| 3 | import argparse |
| 4 | |
| 5 | import torch |
| 6 | import numpy as np |
| 7 | from tqdm import tqdm |
| 8 | from threading import Thread |
| 9 | from transformers import AutoTokenizer, AutoModelForCausalLM |
| 10 | from transformers import TextIteratorStreamer, set_seed |
| 11 | |
| 12 | from spatiallm import Layout |
| 13 | from spatiallm.pcd import load_o3d_pcd, get_points_and_colors, cleanup_pcd, Compose |
| 14 | |
| 15 | DETECT_TYPE_PROMPT = { |
| 16 | "all": "Detect walls, doors, windows, boxes.", |
| 17 | "arch": "Detect walls, doors, windows.", |
| 18 | "object": "Detect boxes.", |
| 19 | } |
| 20 | |
| 21 | |
| 22 | def 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 | |
| 52 | def 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 | conversation = [{"role": "user", "content": prompt}] |
| 82 | |
| 83 | input_ids = tokenizer.apply_chat_template( |
| 84 | conversation, add_generation_prompt=True, return_tensors="pt" |
| 85 | ) |
| 86 | input_ids = input_ids.to(model.device) |
| 87 | |
| 88 | streamer = TextIteratorStreamer( |
| 89 | tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True |
| 90 | ) |
| 91 | |
| 92 | generate_kwargs = dict( |
| 93 | {"input_ids": input_ids, "point_clouds": point_cloud}, |
| 94 | streamer=streamer, |
| 95 | max_new_tokens=max_new_tokens, |
| 96 | do_sample=True, |
| 97 | use_cache=True, |
| 98 | temperature=temperature, |
| 99 | top_p=top_p, |
| 100 | top_k=top_k, |
| 101 | num_beams=num_beams, |
| 102 | ) |
| 103 | t = Thread(target=model.generate, kwargs=generate_kwargs) |
| 104 | t.start() |
| 105 | |
| 106 | print("Generating layout...\n") |
| 107 | generate_texts = [] |
| 108 | for text in streamer: |
| 109 | generate_texts.append(text) |
| 110 | print(text, end="", flush=True) |
| 111 | print("\nDone!") |
| 112 | |
| 113 | layout_str = "".join(generate_texts) |
| 114 | layout = Layout(layout_str) |
| 115 | layout.undiscretize_and_unnormalize(num_bins=model.config.point_config["num_bins"]) |
| 116 | return layout |
| 117 | |
| 118 | |
| 119 | if __name__ == "__main__": |
| 120 | parser = argparse.ArgumentParser("SpatialLM inference script") |
| 121 | parser.add_argument( |
| 122 | "-p", |
| 123 | "--point_cloud", |
| 124 | type=str, |
| 125 | required=True, |
| 126 | help="Path to the input point cloud file or a folder containing multiple point cloud files", |
| 127 | ) |
| 128 | parser.add_argument( |
| 129 | "-o", |
| 130 | "--output", |
| 131 | type=str, |
| 132 | required=True, |
| 133 | help="Path to the output layout txt file or a folder to save multiple layout txt files", |
| 134 | ) |
| 135 | parser.add_argument( |
| 136 | "-m", |
| 137 | "--model_path", |
| 138 | type=str, |
| 139 | default="manycore-research/SpatialLM-Llama-1B", |
| 140 | help="Path to the model checkpoint", |
| 141 | ) |
| 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 | ) |
| 218 | parser.add_argument( |
| 219 | "-t", |
| 220 | "--code_template_file", |
| 221 | type=str, |
| 222 | default="code_template.txt", |
| 223 | help="Path to the code template file", |
| 224 | ) |
| 225 | parser.add_argument( |
| 226 | "--top_k", |
| 227 | type=int, |
| 228 | default=10, |
| 229 | help="The number of highest probability vocabulary tokens to keep for top-k filtering", |
| 230 | ) |
| 231 | parser.add_argument( |
| 232 | "--top_p", |
| 233 | type=float, |
| 234 | default=0.95, |
| 235 | help="The smallest set of most probable tokens with probabilities that add up to top_p or higher are kept", |
| 236 | ) |
| 237 | parser.add_argument( |
| 238 | "--temperature", |
| 239 | type=float, |
| 240 | default=0.6, |
| 241 | help="The value used to module the next token probabilities", |
| 242 | ) |
| 243 | parser.add_argument( |
| 244 | "--num_beams", |
| 245 | type=int, |
| 246 | default=1, |
| 247 | help="The number of beams for beam search", |
| 248 | ) |
| 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 | ) |
| 267 | args = parser.parse_args() |
| 268 | |
| 269 | # load the model |
| 270 | tokenizer = AutoTokenizer.from_pretrained(args.model_path) |
| 271 | model = AutoModelForCausalLM.from_pretrained( |
| 272 | args.model_path, torch_dtype=getattr(torch, args.inference_dtype) |
| 273 | ) |
| 274 | model.to("cuda") |
| 275 | model.set_point_backbone_dtype(torch.float32) |
| 276 | model.eval() |
| 277 | |
| 278 | # number of bins used for discretization |
| 279 | num_bins = model.config.point_config["num_bins"] |
| 280 | |
| 281 | # check if the input is a single point cloud file or a folder containing multiple point cloud files |
| 282 | if os.path.isfile(args.point_cloud): |
| 283 | point_cloud_files = [args.point_cloud] |
| 284 | else: |
| 285 | point_cloud_files = glob.glob(os.path.join(args.point_cloud, "*.ply")) |
| 286 | |
| 287 | for point_cloud_file in tqdm(point_cloud_files): |
| 288 | # load the point cloud |
| 289 | point_cloud = load_o3d_pcd(point_cloud_file) |
| 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 | |
| 295 | points, colors = get_points_and_colors(point_cloud) |
| 296 | min_extent = np.min(points, axis=0) |
| 297 | |
| 298 | # preprocess the point cloud to tensor features |
| 299 | input_pcd = preprocess_point_cloud(points, colors, grid_size, num_bins) |
| 300 | |
| 301 | # generate the layout |
| 302 | layout = generate_layout( |
| 303 | model, |
| 304 | input_pcd, |
| 305 | tokenizer, |
| 306 | args.code_template_file, |
| 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, |
| 314 | ) |
| 315 | layout.translate(min_extent) |
| 316 | pred_language_string = layout.to_language_string() |
| 317 | |
| 318 | # check if the output path is a file or directory |
| 319 | if os.path.splitext(args.output)[-1]: |
| 320 | with open(args.output, "w") as f: |
| 321 | f.write(pred_language_string) |
| 322 | else: |
| 323 | output_filename = os.path.basename(point_cloud_file).replace(".ply", ".txt") |
| 324 | os.makedirs(args.output, exist_ok=True) |
| 325 | with open(os.path.join(args.output, output_filename), "w") as f: |
| 326 | f.write(pred_language_string) |