| 1 | # Copyright (c) Manycore Tech Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | |
| 4 | from typing import List, Optional, Tuple, Union |
| 5 | |
| 6 | import torch |
| 7 | import torch.utils.checkpoint |
| 8 | import torch.nn.functional as F |
| 9 | from torch import nn |
| 10 | from transformers import ( |
| 11 | LlamaModel, |
| 12 | LlamaForCausalLM, |
| 13 | AutoConfig, |
| 14 | AutoModelForCausalLM, |
| 15 | ) |
| 16 | from transformers.utils import logging |
| 17 | from transformers.cache_utils import Cache |
| 18 | from transformers.modeling_outputs import CausalLMOutputWithPast |
| 19 | from transformers.models.llama.configuration_llama import LlamaConfig |
| 20 | |
| 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 |
| 26 | |
| 27 | from spatiallm.model import PointBackboneType, ProjectorType |
| 28 | |
| 29 | IGNORE_INDEX = -100 |
| 30 | logger = logging.get_logger(__name__) |
| 31 | |
| 32 | |
| 33 | class SpatialLMLlamaConfig(LlamaConfig): |
| 34 | model_type = "spatiallm_llama" |
| 35 | |
| 36 | |
| 37 | class SpatialLMLlamaForCausalLM(LlamaForCausalLM): |
| 38 | config_class = SpatialLMLlamaConfig |
| 39 | |
| 40 | def __init__(self, config): |
| 41 | super().__init__(config) |
| 42 | self.model = LlamaModel(config) |
| 43 | self.vocab_size = config.vocab_size |
| 44 | self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) |
| 45 | |
| 46 | self.point_backbone_type = PointBackboneType(config.point_backbone) |
| 47 | self.point_backbone = None |
| 48 | point_config = config.point_config |
| 49 | if self.point_backbone_type == PointBackboneType.SCENESCRIPT: |
| 50 | from spatiallm.model.scenescript_encoder import PointCloudEncoder |
| 51 | |
| 52 | self.point_backbone = PointCloudEncoder( |
| 53 | input_channels=point_config["input_channels"], |
| 54 | d_model=point_config["embed_channels"], |
| 55 | conv_layers=point_config["conv_layers"], |
| 56 | num_bins=point_config["num_bins"], |
| 57 | ) |
| 58 | 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] |
| 77 | else: |
| 78 | raise ValueError(f"Unknown point backbone type: {self.point_backbone_type}") |
| 79 | |
| 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}") |
| 91 | |
| 92 | self.point_start_token_id = self.config.point_start_token_id |
| 93 | self.point_end_token_id = self.config.point_end_token_id |
| 94 | self.point_token_id = self.config.point_token_id |
| 95 | |
| 96 | # Initialize weights and apply final processing |
| 97 | self.post_init() |
| 98 | |
| 99 | def forward_point_cloud(self, point_cloud, device, dtype): |
| 100 | # point cloud has shape (n_points, n_features) |
| 101 | # find the points that have nan values |
| 102 | self.point_backbone.to(torch.float32) |
| 103 | nan_mask = torch.isnan(point_cloud).any(dim=1) |
| 104 | point_cloud = point_cloud[~nan_mask] |
| 105 | coords = point_cloud[:, :3].int() |
| 106 | feats = point_cloud[:, 3:].float() |
| 107 | if self.point_backbone_type == PointBackboneType.SCENESCRIPT: |
| 108 | pc_sparse_tensor = torchsparse.SparseTensor(coords=coords, feats=feats) |
| 109 | pc_sparse_tensor = sparse_collate([pc_sparse_tensor]) # batch_size = 1 |
| 110 | pc_sparse_tensor = pc_sparse_tensor.to(device) |
| 111 | encoded_features = self.point_backbone(pc_sparse_tensor) |
| 112 | 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)) |
| 124 | else: |
| 125 | raise ValueError(f"Unknown point backbone type: {self.point_backbone_type}") |
| 126 | |
| 127 | def set_point_backbone_dtype(self, dtype: torch.dtype): |
| 128 | for param in self.point_backbone.parameters(): |
| 129 | param.data = param.data.to(dtype) |
| 130 | |
| 131 | def get_model(self): |
| 132 | return self.model |
| 133 | |
| 134 | def forward( |
| 135 | self, |
| 136 | input_ids: torch.LongTensor = None, |
| 137 | attention_mask: Optional[torch.Tensor] = None, |
| 138 | position_ids: Optional[torch.LongTensor] = None, |
| 139 | past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, |
| 140 | inputs_embeds: Optional[torch.FloatTensor] = None, |
| 141 | labels: Optional[torch.LongTensor] = None, |
| 142 | use_cache: Optional[bool] = None, |
| 143 | output_attentions: Optional[bool] = None, |
| 144 | output_hidden_states: Optional[bool] = None, |
| 145 | return_dict: Optional[bool] = None, |
| 146 | cache_position: Optional[torch.LongTensor] = None, |
| 147 | num_logits_to_keep: int = 0, |
| 148 | point_clouds: Optional[torch.Tensor] = None, |
| 149 | **loss_kwargs, |
| 150 | ) -> Union[Tuple, CausalLMOutputWithPast]: |
| 151 | r""" |
| 152 | Args: |
| 153 | labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): |
| 154 | Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., |
| 155 | config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored |
| 156 | (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. |
| 157 | |
| 158 | point_clouds (`torch.Tensor` of shape `(batch_size, n_points, n_features)`, *optional*): |
| 159 | Point clouds to be used for the point cloud encoder. |
| 160 | |
| 161 | num_logits_to_keep (`int`, *optional*): |
| 162 | Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all |
| 163 | `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that |
| 164 | token can save memory, which becomes pretty significant for long sequences or large vocabulary size. |
| 165 | |
| 166 | Returns: |
| 167 | |
| 168 | Example: |
| 169 | |
| 170 | ```python |
| 171 | >>> from transformers import AutoTokenizer, AutoModelForCausalLM |
| 172 | |
| 173 | >>> model = AutoModelForCausalLM.from_pretrained("manycore-research/SpatialLM-Llama-1B") |
| 174 | >>> tokenizer = AutoTokenizer.from_pretrained("manycore-research/SpatialLM-Llama-1B") |
| 175 | |
| 176 | >>> prompt = "<|point_start|><|point_pad|><|point_end|>Detect walls, doors, windows, boxes. The reference code is as followed: {code_template}" |
| 177 | >>> conversation = [{"role": "user", "content": prompt}] |
| 178 | >>> input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt") |
| 179 | |
| 180 | >>> # Generate |
| 181 | >>> generate_ids = model.generate(input_ids, point_clouds=point_clouds, max_length=4096) |
| 182 | >>> tokenizer.batch_decode(generate_ids, skip_prompt=True, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] |
| 183 | ```""" |
| 184 | output_attentions = ( |
| 185 | output_attentions |
| 186 | if output_attentions is not None |
| 187 | else self.config.output_attentions |
| 188 | ) |
| 189 | output_hidden_states = ( |
| 190 | output_hidden_states |
| 191 | if output_hidden_states is not None |
| 192 | else self.config.output_hidden_states |
| 193 | ) |
| 194 | return_dict = ( |
| 195 | return_dict if return_dict is not None else self.config.use_return_dict |
| 196 | ) |
| 197 | |
| 198 | # compute point cloud embeddings |
| 199 | if inputs_embeds is None: |
| 200 | inputs_embeds = self.model.embed_tokens(input_ids) |
| 201 | |
| 202 | if ( |
| 203 | self.point_backbone is not None |
| 204 | and (input_ids.shape[1] != 1 or self.training) |
| 205 | and point_clouds is not None |
| 206 | ): |
| 207 | n_point_clouds = point_clouds.shape[0] |
| 208 | point_features = [] |
| 209 | for i in range(n_point_clouds): # * iterate over batch |
| 210 | point_cloud = point_clouds[i] |
| 211 | point_feature = self.forward_point_cloud( |
| 212 | point_cloud, inputs_embeds.device, inputs_embeds.dtype |
| 213 | ) |
| 214 | point_features.append(point_feature) |
| 215 | |
| 216 | # Insert point cloud features into the input ids |
| 217 | point_start_end_token_pos = [] |
| 218 | new_input_embeds = [] |
| 219 | new_attention_mask = [] |
| 220 | cur_point_idx = 0 |
| 221 | max_num_tokens = 0 |
| 222 | for cur_input_ids, cur_input_embeds, cur_attention_mask in zip( |
| 223 | input_ids, inputs_embeds, attention_mask |
| 224 | ): # * input_ids: B, L; input_embeds: B, L, C |
| 225 | cur_point_features = ( |
| 226 | point_features[cur_point_idx] |
| 227 | .to(device=cur_input_embeds.device) |
| 228 | .squeeze(0) |
| 229 | ) |
| 230 | num_patches = cur_point_features.shape[0] # * number of point tokens |
| 231 | num_point_start_tokens = ( |
| 232 | (cur_input_ids == self.config.point_start_token_id).sum().item() |
| 233 | ) |
| 234 | num_point_end_tokens = ( |
| 235 | (cur_input_ids == self.config.point_end_token_id).sum().item() |
| 236 | ) |
| 237 | # currently, we only support one point start and one point end token |
| 238 | assert num_point_start_tokens == num_point_end_tokens == 1, ( |
| 239 | "The number of point start tokens and point end tokens should be 1, " |
| 240 | f"but got {num_point_start_tokens} and {num_point_end_tokens}." |
| 241 | ) |
| 242 | point_start_token_pos = torch.where( |
| 243 | cur_input_ids == self.config.point_start_token_id |
| 244 | )[0][0] |
| 245 | point_end_token_pos = torch.where( |
| 246 | cur_input_ids == self.config.point_end_token_id |
| 247 | )[0][0] |
| 248 | cur_new_input_embeds = torch.cat( |
| 249 | ( |
| 250 | cur_input_embeds[: point_start_token_pos + 1], |
| 251 | cur_point_features, |
| 252 | cur_input_embeds[point_end_token_pos:], |
| 253 | ), |
| 254 | dim=0, |
| 255 | ) |
| 256 | cur_new_attention_mask = torch.cat( |
| 257 | ( |
| 258 | cur_attention_mask[: point_start_token_pos + 1], |
| 259 | torch.ones(num_patches, device=cur_attention_mask.device), |
| 260 | cur_attention_mask[point_end_token_pos:], |
| 261 | ), |
| 262 | dim=0, |
| 263 | ) |
| 264 | |
| 265 | cur_point_idx += 1 |
| 266 | new_input_embeds.append(cur_new_input_embeds) |
| 267 | new_attention_mask.append(cur_new_attention_mask) |
| 268 | point_start_end_token_pos.append( |
| 269 | (point_start_token_pos, num_patches, point_end_token_pos) |
| 270 | ) |
| 271 | if cur_new_input_embeds.shape[0] > max_num_tokens: |
| 272 | max_num_tokens = cur_new_input_embeds.shape[0] |
| 273 | # pad the new input embeds and attention mask to the max dimension |
| 274 | for i in range(len(new_input_embeds)): |
| 275 | cur_input_embeds = new_input_embeds[i] |
| 276 | last_row = cur_input_embeds[-1] |
| 277 | padding = last_row.repeat(max_num_tokens - cur_input_embeds.shape[0], 1) |
| 278 | new_input_embeds[i] = torch.cat([cur_input_embeds, padding], dim=0) |
| 279 | |
| 280 | cur_attention_mask = new_attention_mask[i] |
| 281 | new_attention_mask[i] = F.pad( |
| 282 | cur_attention_mask, |
| 283 | (0, max_num_tokens - cur_attention_mask.shape[0]), |
| 284 | value=0, |
| 285 | ) |
| 286 | inputs_embeds = torch.stack(new_input_embeds, dim=0) |
| 287 | attention_mask = torch.stack(new_attention_mask, dim=0) |
| 288 | |
| 289 | assert ( |
| 290 | attention_mask.shape[1] == inputs_embeds.shape[1] |
| 291 | ), "The length of attention mask and inputs embeds should be the same" |
| 292 | |
| 293 | # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) |
| 294 | outputs = self.model( |
| 295 | input_ids=None, |
| 296 | attention_mask=attention_mask, |
| 297 | position_ids=position_ids, |
| 298 | past_key_values=past_key_values, |
| 299 | inputs_embeds=inputs_embeds, |
| 300 | use_cache=use_cache, |
| 301 | output_attentions=output_attentions, |
| 302 | output_hidden_states=output_hidden_states, |
| 303 | return_dict=return_dict, |
| 304 | cache_position=cache_position, |
| 305 | ) |
| 306 | |
| 307 | hidden_states = outputs[0] |
| 308 | if self.config.pretraining_tp > 1: |
| 309 | lm_head_slices = self.lm_head.weight.split( |
| 310 | self.vocab_size // self.config.pretraining_tp, dim=0 |
| 311 | ) |
| 312 | logits = [ |
| 313 | F.linear(hidden_states, lm_head_slices[i]) |
| 314 | for i in range(self.config.pretraining_tp) |
| 315 | ] |
| 316 | logits = torch.cat(logits, dim=-1) |
| 317 | else: |
| 318 | # Only compute necessary logits, and do not upcast them to float if we are not computing the loss |
| 319 | logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]) |
| 320 | |
| 321 | loss = None |
| 322 | if labels is not None: |
| 323 | # prepare new labels |
| 324 | new_labels = [] |
| 325 | max_num_tokens = logits.shape[1] |
| 326 | for i in range(len(point_start_end_token_pos)): |
| 327 | cur_labels = labels[i] |
| 328 | ( |
| 329 | cur_point_start_token_pos, |
| 330 | num_patches, |
| 331 | cur_point_end_token_pos, |
| 332 | ) = point_start_end_token_pos[i] |
| 333 | cur_new_labels = torch.cat( |
| 334 | ( |
| 335 | cur_labels[: cur_point_start_token_pos + 1], |
| 336 | torch.full( |
| 337 | (num_patches,), |
| 338 | IGNORE_INDEX, |
| 339 | device=cur_labels.device, |
| 340 | ), |
| 341 | cur_labels[cur_point_end_token_pos:], |
| 342 | ), |
| 343 | dim=0, |
| 344 | ) |
| 345 | cur_new_labels = F.pad( |
| 346 | cur_new_labels, |
| 347 | (0, max_num_tokens - cur_new_labels.shape[0]), |
| 348 | value=IGNORE_INDEX, |
| 349 | ) |
| 350 | new_labels.append(cur_new_labels) |
| 351 | labels = torch.stack(new_labels, dim=0) |
| 352 | |
| 353 | assert ( |
| 354 | labels.shape[1] == logits.shape[1] |
| 355 | ), "The length of labels and logits should be the same" |
| 356 | |
| 357 | loss = self.loss_function( |
| 358 | logits=logits, |
| 359 | labels=labels, |
| 360 | vocab_size=self.config.vocab_size, |
| 361 | **loss_kwargs, |
| 362 | ) |
| 363 | |
| 364 | if not return_dict: |
| 365 | output = (logits,) + outputs[1:] |
| 366 | return (loss,) + output if loss is not None else output |
| 367 | |
| 368 | return CausalLMOutputWithPast( |
| 369 | loss=loss, |
| 370 | logits=logits, |
| 371 | past_key_values=outputs.past_key_values, |
| 372 | hidden_states=outputs.hidden_states, |
| 373 | attentions=outputs.attentions, |
| 374 | ) |
| 375 | |
| 376 | def prepare_inputs_for_generation( |
| 377 | self, |
| 378 | input_ids, |
| 379 | past_key_values=None, |
| 380 | attention_mask=None, |
| 381 | inputs_embeds=None, |
| 382 | **kwargs, |
| 383 | ): |
| 384 | if past_key_values: |
| 385 | input_ids = input_ids[:, -1:] |
| 386 | |
| 387 | # if `inputs_embeds` are passed, we only want to use them in the 1st generation step |
| 388 | if inputs_embeds is not None and past_key_values is None: |
| 389 | model_inputs = {"inputs_embeds": inputs_embeds} |
| 390 | else: |
| 391 | model_inputs = {"input_ids": input_ids} |
| 392 | |
| 393 | model_inputs.update( |
| 394 | { |
| 395 | "past_key_values": past_key_values, |
| 396 | "use_cache": kwargs.get("use_cache"), |
| 397 | "attention_mask": attention_mask, |
| 398 | "point_clouds": kwargs.get("point_clouds", None), |
| 399 | } |
| 400 | ) |
| 401 | return model_inputs |
| 402 | |
| 403 | |
| 404 | AutoConfig.register("spatiallm_llama", SpatialLMLlamaConfig) |
| 405 | AutoModelForCausalLM.register(SpatialLMLlamaConfig, SpatialLMLlamaForCausalLM) |