| 1 | import os |
| 2 | import glob |
| 3 | import argparse |
| 4 | |
| 5 | import torch |
| 6 | import numpy as np |
| 7 | from tqdm import tqdm |
| 8 | from threading import Thread |
| 9 | from transformers import AutoTokenizer, AutoModelForCausalLM |
| 10 | from transformers import TextIteratorStreamer |
| 11 | |
| 12 | from spatiallm import Layout |
| 13 | from spatiallm import SpatialLMLlamaForCausalLM, SpatialLMQwenForCausalLM |
| 14 | from spatiallm.pcd import load_o3d_pcd, get_points_and_colors, cleanup_pcd, Compose |
| 15 | |
| 16 | |
| 17 | def preprocess_point_cloud(points, colors, grid_size, num_bins): |
| 18 | transform = Compose( |
| 19 | [ |
| 20 | dict(type="PositiveShift"), |
| 21 | dict(type="NormalizeColor"), |
| 22 | dict( |
| 23 | type="GridSample", |
| 24 | grid_size=grid_size, |
| 25 | hash_type="fnv", |
| 26 | mode="test", |
| 27 | keys=("coord", "color"), |
| 28 | return_grid_coord=True, |
| 29 | max_grid_coord=num_bins, |
| 30 | ), |
| 31 | ] |
| 32 | ) |
| 33 | point_cloud = transform( |
| 34 | { |
| 35 | "name": "pcd", |
| 36 | "coord": points.copy(), |
| 37 | "color": colors.copy(), |
| 38 | } |
| 39 | ) |
| 40 | coord = point_cloud["grid_coord"] |
| 41 | xyz = point_cloud["coord"] |
| 42 | rgb = point_cloud["color"] |
| 43 | point_cloud = np.concatenate([coord, xyz, rgb], axis=1) |
| 44 | return torch.as_tensor(np.stack([point_cloud], axis=0)) |
| 45 | |
| 46 | |
| 47 | def generate_layout( |
| 48 | model, |
| 49 | point_cloud, |
| 50 | tokenizer, |
| 51 | code_template_file, |
| 52 | top_k=10, |
| 53 | top_p=0.95, |
| 54 | temperature=0.6, |
| 55 | num_beams=1, |
| 56 | max_new_tokens=4096, |
| 57 | ): |
| 58 | # load the code template |
| 59 | with open(code_template_file, "r") as f: |
| 60 | code_template = f.read() |
| 61 | |
| 62 | prompt = f"<|point_start|><|point_pad|><|point_end|>Detect walls, doors, windows, boxes. The reference code is as followed: {code_template}" |
| 63 | |
| 64 | # prepare the conversation data |
| 65 | if model.config.model_type == SpatialLMLlamaForCausalLM.config_class.model_type: |
| 66 | conversation = [{"role": "user", "content": prompt}] |
| 67 | elif model.config.model_type == SpatialLMQwenForCausalLM.config_class.model_type: |
| 68 | conversation = [ |
| 69 | {"role": "system", "content": "You are a helpful assistant."}, |
| 70 | {"role": "user", "content": prompt}, |
| 71 | ] |
| 72 | else: |
| 73 | raise ValueError(f"Unsupported model type: {model.config.model_type}") |
| 74 | |
| 75 | input_ids = tokenizer.apply_chat_template( |
| 76 | conversation, add_generation_prompt=True, return_tensors="pt" |
| 77 | ) |
| 78 | input_ids = input_ids.to(model.device) |
| 79 | |
| 80 | streamer = TextIteratorStreamer( |
| 81 | tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True |
| 82 | ) |
| 83 | |
| 84 | generate_kwargs = dict( |
| 85 | {"input_ids": input_ids, "point_clouds": point_cloud}, |
| 86 | streamer=streamer, |
| 87 | max_new_tokens=max_new_tokens, |
| 88 | do_sample=True, |
| 89 | use_cache=True, |
| 90 | temperature=temperature, |
| 91 | top_p=top_p, |
| 92 | top_k=top_k, |
| 93 | num_beams=num_beams, |
| 94 | ) |
| 95 | t = Thread(target=model.generate, kwargs=generate_kwargs) |
| 96 | t.start() |
| 97 | |
| 98 | print("Generating layout...\n") |
| 99 | generate_texts = [] |
| 100 | for text in streamer: |
| 101 | generate_texts.append(text) |
| 102 | print(text, end="", flush=True) |
| 103 | print("\nDone!") |
| 104 | |
| 105 | layout_str = "".join(generate_texts) |
| 106 | layout = Layout(layout_str) |
| 107 | layout.undiscretize_and_unnormalize() |
| 108 | return layout |
| 109 | |
| 110 | |
| 111 | if __name__ == "__main__": |
| 112 | parser = argparse.ArgumentParser("SpatialLM inference script") |
| 113 | parser.add_argument( |
| 114 | "-p", |
| 115 | "--point_cloud", |
| 116 | type=str, |
| 117 | required=True, |
| 118 | help="Path to the input point cloud file or a folder containing multiple point cloud files", |
| 119 | ) |
| 120 | parser.add_argument( |
| 121 | "-o", |
| 122 | "--output", |
| 123 | type=str, |
| 124 | required=True, |
| 125 | help="Path to the output layout txt file or a folder to save multiple layout txt files", |
| 126 | ) |
| 127 | parser.add_argument( |
| 128 | "-m", |
| 129 | "--model_path", |
| 130 | type=str, |
| 131 | default="manycore-research/SpatialLM-Llama-1B", |
| 132 | help="Path to the model checkpoint", |
| 133 | ) |
| 134 | parser.add_argument( |
| 135 | "-t", |
| 136 | "--code_template_file", |
| 137 | type=str, |
| 138 | default="code_template.txt", |
| 139 | help="Path to the code template file", |
| 140 | ) |
| 141 | parser.add_argument( |
| 142 | "--top_k", |
| 143 | type=int, |
| 144 | default=10, |
| 145 | help="The number of highest probability vocabulary tokens to keep for top-k filtering", |
| 146 | ) |
| 147 | parser.add_argument( |
| 148 | "--top_p", |
| 149 | type=float, |
| 150 | default=0.95, |
| 151 | help="The smallest set of most probable tokens with probabilities that add up to top_p or higher are kept", |
| 152 | ) |
| 153 | parser.add_argument( |
| 154 | "--temperature", |
| 155 | type=float, |
| 156 | default=0.6, |
| 157 | help="The value used to module the next token probabilities", |
| 158 | ) |
| 159 | parser.add_argument( |
| 160 | "--num_beams", |
| 161 | type=int, |
| 162 | default=1, |
| 163 | help="The number of beams for beam search", |
| 164 | ) |
| 165 | args = parser.parse_args() |
| 166 | |
| 167 | # load the model |
| 168 | tokenizer = AutoTokenizer.from_pretrained(args.model_path) |
| 169 | model = AutoModelForCausalLM.from_pretrained(args.model_path) |
| 170 | model.to("cuda") |
| 171 | model.set_point_backbone_dtype(torch.float32) |
| 172 | model.eval() |
| 173 | |
| 174 | # check if the input is a single point cloud file or a folder containing multiple point cloud files |
| 175 | if os.path.isfile(args.point_cloud): |
| 176 | point_cloud_files = [args.point_cloud] |
| 177 | else: |
| 178 | point_cloud_files = glob.glob(os.path.join(args.point_cloud, "*.ply")) |
| 179 | |
| 180 | for point_cloud_file in tqdm(point_cloud_files): |
| 181 | # load the point cloud |
| 182 | point_cloud = load_o3d_pcd(point_cloud_file) |
| 183 | point_cloud = cleanup_pcd(point_cloud) |
| 184 | points, colors = get_points_and_colors(point_cloud) |
| 185 | min_extent = np.min(points, axis=0) |
| 186 | |
| 187 | # preprocess the point cloud to tensor features |
| 188 | grid_size = Layout.get_grid_size() |
| 189 | num_bins = Layout.get_num_bins() |
| 190 | input_pcd = preprocess_point_cloud(points, colors, grid_size, num_bins) |
| 191 | |
| 192 | # generate the layout |
| 193 | layout = generate_layout( |
| 194 | model, |
| 195 | input_pcd, |
| 196 | tokenizer, |
| 197 | args.code_template_file, |
| 198 | args.top_k, |
| 199 | args.top_p, |
| 200 | args.temperature, |
| 201 | args.num_beams, |
| 202 | ) |
| 203 | layout.translate(min_extent) |
| 204 | pred_language_string = layout.to_language_string() |
| 205 | |
| 206 | # check if the output path is a file or directory |
| 207 | if os.path.splitext(args.output)[-1]: |
| 208 | with open(args.output, "w") as f: |
| 209 | f.write(pred_language_string) |
| 210 | else: |
| 211 | output_filename = os.path.basename(point_cloud_file).replace(".ply", ".txt") |
| 212 | os.makedirs(args.output, exist_ok=True) |
| 213 | with open(os.path.join(args.output, output_filename), "w") as f: |
| 214 | f.write(pred_language_string) |