Changesets · Branches · Tags · Compare
| Changeset | 32905fee50a8f3b1b04c2b70a4357b172583db8d927088c30d6308d98472717a |
|---|---|
| Author | Yongsen Mao <36813656+SamMaoYS@users.noreply.github.com> · 2025-09-01 00:31 +08:00 |
| Committer | GitHub <noreply@github.com> · 2025-09-01 00:31 +08:00 |
| Parents | 5ec8f267b45b, 656e8eb08351 |
46 files changed
added FINETUNE.md +100 −0
| @@ -0,0 +1,100 @@ | ||
| 1 | +# Finetune SpatialLM | |
| 2 | + | |
| 3 | +Here we provide a simple example of how to finetune SpatialLM. In this example, we finetune SpatialLM on [ARKitScenes](https://github.com/apple/ARKitScenes) using a new set of object categories and enable random, gravity-aligned scene orientations. During inference, only the z-axis needs to be kept as the up axis; the x and y axes do not need to be aligned. | |
| 4 | + | |
| 5 | +## Installation | |
| 6 | + | |
| 7 | +First, follow the installation instructions in [README.md](./README.md#installation). Then, install the training dependencies: | |
| 8 | + | |
| 9 | +```bash | |
| 10 | +poe install-training | |
| 11 | +``` | |
| 12 | + | |
| 13 | +## Dataset | |
| 14 | + | |
| 15 | +Download the preprocessed [ARKitScenes-SpatialLM](https://huggingface.co/datasets/ysmao/arkitscenes-spatiallm) dataset from Hugging Face. For details about the dataset format and structure, refer to the dataset repository. | |
| 16 | + | |
| 17 | +```bash | |
| 18 | +huggingface-cli download ysmao/arkitscenes-spatiallm --repo-type dataset --local-dir arkitscenes-spatiallm | |
| 19 | +``` | |
| 20 | + | |
| 21 | +After downloading the dataset, extract the files from the compressed chunks: | |
| 22 | + | |
| 23 | +```bash | |
| 24 | +cd arkitscenes-spatiallm | |
| 25 | +chmod +x extract.sh | |
| 26 | +./extract.sh | |
| 27 | +``` | |
| 28 | + | |
| 29 | +The GT oriented bounding boxes are stored as TXT files in the `layout` folder, and the point clouds are stored in PLY format in the `pcd` folder. The script `spatiallm/tuner/create_dataset.py` is used to convert the raw data into training data in the ShareGPT format. The downloaded dataset contains the preprocessed training data in ShareGPT format already. | |
| 30 | + | |
| 31 | +## Training | |
| 32 | + | |
| 33 | +The training script is adapted from [LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory), a great open-source project for LLM finetuning. For SpatialLM, we included a minimum subset of features focused on SFT finetuning. Refer to LLaMA-Factory for additional features and broader support. | |
| 34 | + | |
| 35 | +Refer to [configs/spatiallm_sft.yaml](./configs/spatiallm_sft.yaml) to ensure the configuration settings match your requirements. Key options include: | |
| 36 | + | |
| 37 | +- `model_name_or_path`: Path to the pretrained SpatialLM model weights | |
| 38 | +- `template`: Select either `spatiallm_qwen` or `spatiallm_llama` as appropriate | |
| 39 | +- `dataset_dir`: Path to the downloaded ARKitScenes-SpatialLM dataset | |
| 40 | +- `save_dir`: Directory to save the preprocessed training dataset | |
| 41 | +- `output_dir`: Directory for saving model checkpoints | |
| 42 | +- `learning_rate`: Learning rate for finetuning | |
| 43 | +- `num_train_epochs`: Number of training epochs for finetuning | |
| 44 | + | |
| 45 | +### Running Finetuning | |
| 46 | + | |
| 47 | +To start finetuning, run the following command. Note that full finetuning requires approximately 60GB of CUDA VRAM. More efficient finetuning options, such as LoRA or quantized finetuning are not yet implemented. | |
| 48 | + | |
| 49 | +```bash | |
| 50 | +python train.py configs/spatiallm_sft.yaml | |
| 51 | +``` | |
| 52 | + | |
| 53 | +If you are training on distributed systems, please set the following environment variables as appropriate for your setup: | |
| 54 | + | |
| 55 | +- `MASTER_ADDR`: The IP address or hostname of the master node (e.g., `127.0.0.1` for single node or the address of the main node in a cluster). | |
| 56 | +- `MASTER_PORT`: A free port on the master node for communication (e.g., `29500`). | |
| 57 | +- `NNODES`: Total number of nodes participating in training. | |
| 58 | +- `NODE_RANK`: Rank of the current node (integer in `[0, NNODES-1]`). | |
| 59 | +- `NPROC_PER_NODE`: Number of processes (usually GPUs) to launch on each node. | |
| 60 | + | |
| 61 | +Example for a single-node (multi-GPU) setup: | |
| 62 | + | |
| 63 | +```bash | |
| 64 | +export MASTER_ADDR=127.0.0.1 | |
| 65 | +export MASTER_PORT=29500 | |
| 66 | +export NNODES=1 | |
| 67 | +export NODE_RANK=0 | |
| 68 | +export NPROC_PER_NODE=4 # Adjust to the number of GPUs available | |
| 69 | +``` | |
| 70 | + | |
| 71 | +For multi-node training, set `MASTER_ADDR` to the address of the master node, and adjust `NNODES` and `NODE_RANK` accordingly. | |
| 72 | + | |
| 73 | +## Testing | |
| 74 | + | |
| 75 | +Once training is complete, you can use the inference and visualization script to view the prediction results from your finetuned model checkpoints. For more details, please refer to [README.md](./README.md#inference). | |
| 76 | + | |
| 77 | +For example here we used finetuned model [SpatialLM1.1-Qwen-0.5B-ARKitScenes-SFT](https://huggingface.co/ysmao/SpatialLM1.1-Qwen-0.5B-ARKitScenes-SFT). | |
| 78 | + | |
| 79 | +```bash | |
| 80 | +# Inference | |
| 81 | +python inference.py -d object -p arkitscenes-spatiallm/pcd/42446137.ply -o 42446137.txt --model_path ysmao/SpatialLM1.1-Qwen-0.5B-ARKitScenes-SFT | |
| 82 | +# Visualization | |
| 83 | +python visualize.py -p arkitscenes-spatiallm/pcd/42446137.ply -l 42446137.txt --save 42446137.rrd | |
| 84 | +# Open Rerun Window | |
| 85 | +rerun 42446137.rrd | |
| 86 | +``` | |
| 87 | + | |
| 88 | +## Results | |
| 89 | + | |
| 90 | +Here are some example results comparing ground truth (GT) layouts with predictions (Pred) from the finetuned SpatialLM1.1-Qwen-0.5B model on the ARKitScenes dataset. | |
| 91 | + | |
| 92 | +<div align="center"> | |
| 93 | + | |
| 94 | +| GT | Pred | | |
| 95 | +| :---------------------------------------: | :-------------------------------------------: | | |
| 96 | +|  |  | | |
| 97 | +|  |  | | |
| 98 | +|  |  | | |
| 99 | + | |
| 100 | +</div> |
modified README.md +5 −0
| @@ -26,6 +26,7 @@ | ||
| 26 | 26 | |
| 27 | 27 | ## ✨ News |
| 28 | 28 | |
| 29 | +- [Jun, 2025] Added finetuning instructions in [FINETUNE.md](./FINETUNE.md). | |
| 29 | 30 | - [Jun, 2025] Check out our new models: [SpatialLM1.1-Llama-1B](https://huggingface.co/manycore-research/SpatialLM1.1-Llama-1B) and [SpatialLM1.1-Qwen-0.5B](https://huggingface.co/manycore-research/SpatialLM1.1-Qwen-0.5B), now available on Hugging Face. SpatialLM1.1 doubles the point cloud resolution, incorporates a more powerful point cloud encoder [Sonata](https://xywu.me/sonata/) and supports detection with user-specified categories. |
| 30 | 31 | - [Jun, 2025] SpatialLM [Technical Report](https://arxiv.org/abs/2506.07491) is now on arXiv. |
| 31 | 32 | - [Mar, 2025] We're excited to release the [SpatialLM-Llama-1B](https://huggingface.co/manycore-research/SpatialLM-Llama-1B) and [SpatialLM-Qwen-0.5B](https://huggingface.co/manycore-research/SpatialLM-Qwen-0.5B) on Hugging Face. |
| @@ -151,6 +152,10 @@ | ||
| 151 | 152 | |
| 152 | 153 | We provide an example of how to use our model to estimate scene layout starting from a RGB video with the newly released [SLAM3R](https://github.com/PKU-VCL-3DV/SLAM3R) in [EXAMPLE.md](EXAMPLE.md). These steps work for MASt3R-SLAM, and other reconstruction methods as well. |
| 153 | 154 | |
| 155 | +### Finetune on Custom Data | |
| 156 | + | |
| 157 | +For instructions on fine-tuning SpatialLM on your own data, please refer to [FINETUNE.md](./FINETUNE.md). We provide an example using the [ARKitScenes](https://github.com/apple/ARKitScenes) dataset. | |
| 158 | + | |
| 154 | 159 | ## SpatialLM Testset |
| 155 | 160 | |
| 156 | 161 | We provide a test set of 107 preprocessed point clouds, reconstructed from RGB videos using [MASt3R-SLAM](https://github.com/rmurai0610/MASt3R-SLAM). SpatialLM-Testset is quite challenging compared to prior clean RGBD scans datasets due to the noises and occlusions in the point clouds reconstructed from monocular RGB videos. |
added configs/spatiallm_sft.yaml +50 −0
| @@ -0,0 +1,50 @@ | ||
| 1 | +### model | |
| 2 | +model_name_or_path: manycore-research/SpatialLM1.1-Qwen-0.5B | |
| 3 | +trust_remote_code: true | |
| 4 | + | |
| 5 | +### method | |
| 6 | +do_train: true | |
| 7 | +freeze_language_tower: false | |
| 8 | +freeze_point_tower: false | |
| 9 | +train_proj_only: false | |
| 10 | + | |
| 11 | +### dataset | |
| 12 | +dataset: arkitscenes_train # arkitscenes_train,arkitscenes_val | |
| 13 | +dataset_dir: arkitscenes-spatiallm # arkitscenes-spatiallm | |
| 14 | +template: spatiallm_qwen # spatiallm_qwen, spatiallm_llama | |
| 15 | +num_bins: 1280 | |
| 16 | +do_augmentation: false | |
| 17 | +random_rotation: true | |
| 18 | +cutoff_len: 8192 | |
| 19 | +overwrite_cache: true | |
| 20 | +preprocessing_num_workers: 8 | |
| 21 | +dataloader_num_workers: 8 | |
| 22 | +save_dir: saves/arkitscenes | |
| 23 | + | |
| 24 | +### output | |
| 25 | +output_dir: saves | |
| 26 | +logging_steps: 10 | |
| 27 | +save_steps: 500 | |
| 28 | +overwrite_output_dir: false | |
| 29 | +save_total_limit: 5 | |
| 30 | + | |
| 31 | +### train | |
| 32 | +per_device_train_batch_size: 1 | |
| 33 | +gradient_accumulation_steps: 1 | |
| 34 | +learning_rate: 1.0e-5 # to be more aggressive: try to change the learning rate to 5.0e-5 or 1.0e-4 | |
| 35 | +num_train_epochs: 10 | |
| 36 | +lr_scheduler_type: cosine | |
| 37 | +warmup_ratio: 0.03 | |
| 38 | +pure_bf16: false | |
| 39 | +bf16: false | |
| 40 | +fp16: false | |
| 41 | +tf32: true | |
| 42 | +ddp_timeout: 180000000 | |
| 43 | +report_to: wandb # choices: [none, wandb, tensorboard, swanlab] | |
| 44 | +max_new_tokens: 4096 | |
| 45 | + | |
| 46 | +### eval | |
| 47 | +val_size: 0.0001 | |
| 48 | +per_device_eval_batch_size: 1 | |
| 49 | +eval_strategy: steps | |
| 50 | +eval_steps: 500 |
modified eval.py +2 −2
| @@ -178,7 +178,7 @@ | ||
| 178 | 178 | |
| 179 | 179 | |
| 180 | 180 | def is_valid_dw(entity: Door | Window, wall_id_lookup: Dict[int, Wall]): |
| 181 | - attach_wall = wall_id_lookup.get(entity.id, None) | |
| 181 | + attach_wall = wall_id_lookup.get(entity.wall_id, None) | |
| 182 | 182 | if attach_wall is None: |
| 183 | 183 | return False |
| 184 | 184 | return is_valid_wall(attach_wall) |
| @@ -197,7 +197,7 @@ | ||
| 197 | 197 | ] |
| 198 | 198 | ) |
| 199 | 199 | elif isinstance(entity, (Door, Window)): |
| 200 | - attach_wall = wall_id_lookup.get(entity.id, None) | |
| 200 | + attach_wall = wall_id_lookup.get(entity.wall_id, None) | |
| 201 | 201 | if attach_wall is None: |
| 202 | 202 | log.error(f"{entity} attach wall is None") |
| 203 | 203 | return |
added figures/42446137_gt.jpg +0 −0
Binary content is not shown. View the file.
added figures/42446137_pred.jpg +0 −0
Binary content is not shown. View the file.
added figures/47334109_gt.jpg +0 −0
Binary content is not shown. View the file.
added figures/47334109_pred.jpg +0 −0
Binary content is not shown. View the file.
added figures/47430470_gt.jpg +0 −0
Binary content is not shown. View the file.
added figures/47430470_pred.jpg +0 −0
Binary content is not shown. View the file.
modified inference.py +7 −1
| @@ -78,7 +78,13 @@ | ||
| 78 | 78 | prompt = f"<|point_start|><|point_pad|><|point_end|>{task_prompt} The reference code is as followed: {code_template}" |
| 79 | 79 | |
| 80 | 80 | # prepare the conversation data |
| 81 | - conversation = [{"role": "user", "content": prompt}] | |
| 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}] | |
| 82 | 88 | |
| 83 | 89 | input_ids = tokenizer.apply_chat_template( |
| 84 | 90 | conversation, add_generation_prompt=True, return_tensors="pt" |
modified pyproject.toml +1 −0
| @@ -41,6 +41,7 @@ | ||
| 41 | 41 | "install-torch-scatter", |
| 42 | 42 | "install-spconv", |
| 43 | 43 | ] |
| 44 | +install-training = "pip install omegaconf datasets<=3.6.0 accelerate<=1.7.0 wandb" | |
| 44 | 45 | |
| 45 | 46 | [build-system] |
| 46 | 47 | requires = ["poetry-core", "setuptools", "wheel", "torch"] |
modified spatiallm/layout/entity.py +43 −20
| @@ -74,6 +74,8 @@ | ||
| 74 | 74 | self.ay *= scaling |
| 75 | 75 | self.az *= scaling |
| 76 | 76 | self.bx *= scaling |
| 77 | + self.by *= scaling | |
| 78 | + self.bz *= scaling | |
| 77 | 79 | |
| 78 | 80 | def normalize_and_discretize(self, num_bins): |
| 79 | 81 | height_min, height_max = NORMALIZATION_PRESET["height"] |
| @@ -90,14 +92,14 @@ | ||
| 90 | 92 | self.by = (self.by - world_min) / (world_max - world_min) * num_bins |
| 91 | 93 | self.bz = (self.bz - world_min) / (world_max - world_min) * num_bins |
| 92 | 94 | |
| 93 | - self.height = np.clip(self.height, 0, num_bins - 1) | |
| 94 | - self.thickness = np.clip(self.thickness, 0, num_bins - 1) | |
| 95 | - self.ax = np.clip(self.ax, 0, num_bins - 1) | |
| 96 | - self.ay = np.clip(self.ay, 0, num_bins - 1) | |
| 97 | - self.az = np.clip(self.az, 0, num_bins - 1) | |
| 98 | - self.bx = np.clip(self.bx, 0, num_bins - 1) | |
| 99 | - self.by = np.clip(self.by, 0, num_bins - 1) | |
| 100 | - self.bz = np.clip(self.bz, 0, num_bins - 1) | |
| 95 | + self.height = np.clip(int(self.height), 0, num_bins - 1) | |
| 96 | + self.thickness = np.clip(int(self.thickness), 0, num_bins - 1) | |
| 97 | + self.ax = np.clip(int(self.ax), 0, num_bins - 1) | |
| 98 | + self.ay = np.clip(int(self.ay), 0, num_bins - 1) | |
| 99 | + self.az = np.clip(int(self.az), 0, num_bins - 1) | |
| 100 | + self.bx = np.clip(int(self.bx), 0, num_bins - 1) | |
| 101 | + self.by = np.clip(int(self.by), 0, num_bins - 1) | |
| 102 | + self.bz = np.clip(int(self.bz), 0, num_bins - 1) | |
| 101 | 103 | |
| 102 | 104 | def undiscretize_and_unnormalize(self, num_bins): |
| 103 | 105 | height_min, height_max = NORMALIZATION_PRESET["height"] |
| @@ -129,6 +131,21 @@ | ||
| 129 | 131 | language_string = f"{self.entity_label}_{self.id}={capitalized_label}({self.ax},{self.ay},{self.az},{self.bx},{self.by},{self.bz},{self.height},{self.thickness})" |
| 130 | 132 | return language_string |
| 131 | 133 | |
| 134 | + def sort_key(self): | |
| 135 | + # Lex-sort corners | |
| 136 | + wall_start = np.array([self.ax, self.ay, self.az]) | |
| 137 | + wall_end = np.array([self.bx, self.by, self.bz]) | |
| 138 | + corners = np.stack([wall_start, wall_end]) # [2, 3] | |
| 139 | + | |
| 140 | + idx = np.lexsort(corners.T) # [2]. Sorts by z, y, x. | |
| 141 | + corner_1_ordered, corner_2_ordered = corners[idx] | |
| 142 | + | |
| 143 | + # Sort wall-corners | |
| 144 | + self.ax, self.ay, self.az = corner_1_ordered | |
| 145 | + self.bx, self.by, self.bz = corner_2_ordered | |
| 146 | + | |
| 147 | + return np.concatenate([corner_2_ordered, corner_1_ordered]) | |
| 148 | + | |
| 132 | 149 | |
| 133 | 150 | @dataclass |
| 134 | 151 | class Door: |
| @@ -188,11 +205,11 @@ | ||
| 188 | 205 | (self.position_z - world_min) / (world_max - world_min) * num_bins |
| 189 | 206 | ) |
| 190 | 207 | |
| 191 | - self.width = np.clip(self.width, 0, num_bins - 1) | |
| 192 | - self.height = np.clip(self.height, 0, num_bins - 1) | |
| 193 | - self.position_x = np.clip(self.position_x, 0, num_bins - 1) | |
| 194 | - self.position_y = np.clip(self.position_y, 0, num_bins - 1) | |
| 195 | - self.position_z = np.clip(self.position_z, 0, num_bins - 1) | |
| 208 | + self.width = np.clip(int(self.width), 0, num_bins - 1) | |
| 209 | + self.height = np.clip(int(self.height), 0, num_bins - 1) | |
| 210 | + self.position_x = np.clip(int(self.position_x), 0, num_bins - 1) | |
| 211 | + self.position_y = np.clip(int(self.position_y), 0, num_bins - 1) | |
| 212 | + self.position_z = np.clip(int(self.position_z), 0, num_bins - 1) | |
| 196 | 213 | |
| 197 | 214 | def undiscretize_and_unnormalize(self, num_bins): |
| 198 | 215 | width_min, width_max = NORMALIZATION_PRESET["width"] |
| @@ -220,6 +237,9 @@ | ||
| 220 | 237 | language_string = f"{self.entity_label}_{self.id}={capitalized_label}(wall_{self.wall_id},{self.position_x},{self.position_y},{self.position_z},{self.width},{self.height})" |
| 221 | 238 | return language_string |
| 222 | 239 | |
| 240 | + def sort_key(self): | |
| 241 | + return np.array([self.position_x, self.position_y]) | |
| 242 | + | |
| 223 | 243 | |
| 224 | 244 | @dataclass |
| 225 | 245 | class Window(Door): |
| @@ -302,13 +322,13 @@ | ||
| 302 | 322 | self.scale_y = (self.scale_y - scale_min) / (scale_max - scale_min) * num_bins |
| 303 | 323 | self.scale_z = (self.scale_z - scale_min) / (scale_max - scale_min) * num_bins |
| 304 | 324 | |
| 305 | - self.position_x = np.clip(self.position_x, 0, num_bins - 1) | |
| 306 | - self.position_y = np.clip(self.position_y, 0, num_bins - 1) | |
| 307 | - self.position_z = np.clip(self.position_z, 0, num_bins - 1) | |
| 308 | - self.angle_z = np.clip(self.angle_z, 0, num_bins - 1) | |
| 309 | - self.scale_x = np.clip(self.scale_x, 0, num_bins - 1) | |
| 310 | - self.scale_y = np.clip(self.scale_y, 0, num_bins - 1) | |
| 311 | - self.scale_z = np.clip(self.scale_z, 0, num_bins - 1) | |
| 325 | + self.position_x = np.clip(int(self.position_x), 0, num_bins - 1) | |
| 326 | + self.position_y = np.clip(int(self.position_y), 0, num_bins - 1) | |
| 327 | + self.position_z = np.clip(int(self.position_z), 0, num_bins - 1) | |
| 328 | + self.angle_z = np.clip(int(self.angle_z), 0, num_bins - 1) | |
| 329 | + self.scale_x = np.clip(int(self.scale_x), 0, num_bins - 1) | |
| 330 | + self.scale_y = np.clip(int(self.scale_y), 0, num_bins - 1) | |
| 331 | + self.scale_z = np.clip(int(self.scale_z), 0, num_bins - 1) | |
| 312 | 332 | |
| 313 | 333 | def undiscretize_and_unnormalize(self, num_bins): |
| 314 | 334 | world_min, world_max = NORMALIZATION_PRESET["world"] |
| @@ -337,3 +357,6 @@ | ||
| 337 | 357 | # bbox_0=Bbox(class_name,position_x,position_y,position_z,angle_z,scale_x,scale_y,scale_z) |
| 338 | 358 | language_string = f"{self.entity_label}_{self.id}={capitalized_label}({self.class_name},{self.position_x},{self.position_y},{self.position_z},{self.angle_z},{self.scale_x},{self.scale_y},{self.scale_z})" |
| 339 | 359 | return language_string |
| 360 | + | |
| 361 | + def sort_key(self): | |
| 362 | + return np.array([self.position_x, self.position_y]) |
modified spatiallm/layout/layout.py +76 −3
| @@ -4,14 +4,14 @@ | ||
| 4 | 4 | |
| 5 | 5 | |
| 6 | 6 | class Layout: |
| 7 | - def __init__(self, str: str = None): | |
| 7 | + def __init__(self, s: str = None): | |
| 8 | 8 | self.walls = [] |
| 9 | 9 | self.doors = [] |
| 10 | 10 | self.windows = [] |
| 11 | 11 | self.bboxes = [] |
| 12 | 12 | |
| 13 | - if str: | |
| 14 | - self.from_str(str) | |
| 13 | + if s: | |
| 14 | + self.from_str(s) | |
| 15 | 15 | |
| 16 | 16 | @staticmethod |
| 17 | 17 | def get_grid_size(num_bins): |
| @@ -205,3 +205,76 @@ | ||
| 205 | 205 | for entity in self.get_entities(): |
| 206 | 206 | entity_strings.append(entity.to_language_string()) |
| 207 | 207 | return "\n".join(entity_strings) |
| 208 | + | |
| 209 | + def filter_empty_bboxes(self, points, num_points=100, margin=0.15): | |
| 210 | + filtered_bboxes = [] | |
| 211 | + for bbox in self.bboxes: | |
| 212 | + box_center = np.array([bbox.position_x, bbox.position_y, bbox.position_z]) | |
| 213 | + box_size = np.array([bbox.scale_x, bbox.scale_y, bbox.scale_z]) | |
| 214 | + rot_mat = R.from_rotvec(np.array([0, 0, bbox.angle_z])).as_matrix() | |
| 215 | + | |
| 216 | + translated_points = points - np.array(box_center) | |
| 217 | + rotated_points = translated_points @ rot_mat.T | |
| 218 | + box_min = -box_size / 2 - margin | |
| 219 | + box_max = box_size / 2 + margin | |
| 220 | + points_mask = np.all(rotated_points >= box_min, axis=1) & np.all( | |
| 221 | + rotated_points <= box_max, axis=1 | |
| 222 | + ) | |
| 223 | + if np.sum(points_mask) > num_points: | |
| 224 | + filtered_bboxes.append(bbox) | |
| 225 | + | |
| 226 | + self.bboxes = filtered_bboxes | |
| 227 | + return filtered_bboxes | |
| 228 | + | |
| 229 | + @staticmethod | |
| 230 | + def sort_entities(entities, wall_lookup=None): | |
| 231 | + if not entities: | |
| 232 | + return [] | |
| 233 | + sort_keys = [entity.sort_key() for entity in entities] | |
| 234 | + sorted_idx = np.lexsort(np.stack(sort_keys).T) | |
| 235 | + sorted_entities = [entities[i] for i in sorted_idx] | |
| 236 | + for i, entity in enumerate(sorted_entities): | |
| 237 | + entity.id = i | |
| 238 | + if wall_lookup is not None and hasattr(entity, "wall_id"): | |
| 239 | + entity.wall_id = wall_lookup[entity.wall_id] | |
| 240 | + return sorted_entities | |
| 241 | + | |
| 242 | + def reorder_entities( | |
| 243 | + self, | |
| 244 | + filter_small_objects=True, | |
| 245 | + filter_unknown=True, | |
| 246 | + size_threshold=0.15, | |
| 247 | + ): | |
| 248 | + bboxes = [] | |
| 249 | + # filter invalid bboxes | |
| 250 | + for bbox in self.bboxes: | |
| 251 | + if filter_small_objects and ( | |
| 252 | + bbox.scale_x < size_threshold | |
| 253 | + and bbox.scale_y < size_threshold | |
| 254 | + and bbox.scale_z < size_threshold | |
| 255 | + ): | |
| 256 | + continue | |
| 257 | + if filter_unknown and (not bbox.class_name or bbox.class_name == "unknown"): | |
| 258 | + continue | |
| 259 | + bboxes.append(bbox) | |
| 260 | + | |
| 261 | + wall_lookup = {} | |
| 262 | + sorted_walls = [] | |
| 263 | + if len(self.walls) > 0: | |
| 264 | + sort_keys = [] | |
| 265 | + for wi, wall in enumerate(self.walls): | |
| 266 | + sort_keys.append(wall.sort_key()) | |
| 267 | + sorted_idx = np.lexsort(np.stack(sort_keys).T) | |
| 268 | + sorted_walls = [self.walls[i] for i in sorted_idx] | |
| 269 | + for wi, wall in enumerate(sorted_walls): | |
| 270 | + wall_lookup[wall.id] = wi | |
| 271 | + wall.id = wi | |
| 272 | + | |
| 273 | + sorted_doors = self.sort_entities(self.doors, wall_lookup) | |
| 274 | + sorted_windows = self.sort_entities(self.windows, wall_lookup) | |
| 275 | + sorted_bboxes = self.sort_entities(bboxes) | |
| 276 | + | |
| 277 | + self.walls = sorted_walls | |
| 278 | + self.doors = sorted_doors | |
| 279 | + self.windows = sorted_windows | |
| 280 | + self.bboxes = sorted_bboxes |
modified spatiallm/pcd/__init__.py +2 −1
| @@ -1,4 +1,5 @@ | ||
| 1 | -from .pcd_loader import load_o3d_pcd, get_points_and_colors, cleanup_pcd, Compose | |
| 1 | +from .pcd_loader import load_o3d_pcd, get_points_and_colors, cleanup_pcd | |
| 2 | +from .transform import Compose | |
| 2 | 3 | |
| 3 | 4 | __all__ = [ |
| 4 | 5 | "load_o3d_pcd", |
modified spatiallm/pcd/pcd_loader.py +0 −179
| @@ -2,187 +2,8 @@ | ||
| 2 | 2 | import numpy as np |
| 3 | 3 | import open3d as o3d |
| 4 | 4 | |
| 5 | -from spatiallm.pcd.registry import Registry | |
| 6 | - | |
| 7 | -TRANSFORMS = Registry("transforms") | |
| 8 | 5 | log = logging.getLogger(__name__) |
| 9 | 6 | |
| 10 | -""" | |
| 11 | -3D Point Cloud Preprocessing | |
| 12 | - | |
| 13 | -Reference: PointCept | |
| 14 | - | |
| 15 | -@misc{pointcept2023, | |
| 16 | - title={Pointcept: A Codebase for Point Cloud Perception Research}, | |
| 17 | - author={Pointcept Contributors}, | |
| 18 | - year={2023} | |
| 19 | -} | |
| 20 | -""" | |
| 21 | - | |
| 22 | - | |
| 23 | -class Compose(object): | |
| 24 | - def __init__(self, cfg=None): | |
| 25 | - self.cfg = cfg if cfg is not None else [] | |
| 26 | - self.transforms = [] | |
| 27 | - for t_cfg in self.cfg: | |
| 28 | - self.transforms.append(TRANSFORMS.build(t_cfg)) | |
| 29 | - | |
| 30 | - def __call__(self, data_dict): | |
| 31 | - for t in self.transforms: | |
| 32 | - data_dict = t(data_dict) | |
| 33 | - return data_dict | |
| 34 | - | |
| 35 | - | |
| 36 | -@TRANSFORMS.register_module() | |
| 37 | -class PositiveShift(object): | |
| 38 | - def __call__(self, data_dict): | |
| 39 | - if "coord" in data_dict.keys(): | |
| 40 | - coord_min = np.min(data_dict["coord"], 0) | |
| 41 | - data_dict["coord"] -= coord_min | |
| 42 | - return data_dict | |
| 43 | - | |
| 44 | - | |
| 45 | -@TRANSFORMS.register_module() | |
| 46 | -class NormalizeColor(object): | |
| 47 | - def __call__(self, data_dict): | |
| 48 | - if "color" in data_dict.keys(): | |
| 49 | - data_dict["color"] = data_dict["color"] / 127.5 - 1 | |
| 50 | - return data_dict | |
| 51 | - | |
| 52 | - | |
| 53 | -@TRANSFORMS.register_module() | |
| 54 | -class GridSample(object): | |
| 55 | - def __init__( | |
| 56 | - self, | |
| 57 | - grid_size=0.05, | |
| 58 | - hash_type="fnv", | |
| 59 | - mode="train", | |
| 60 | - keys=("coord", "color", "normal", "segment"), | |
| 61 | - return_inverse=False, | |
| 62 | - return_grid_coord=False, | |
| 63 | - return_min_coord=False, | |
| 64 | - return_displacement=False, | |
| 65 | - project_displacement=False, | |
| 66 | - max_grid_coord=None, | |
| 67 | - ): | |
| 68 | - self.grid_size = grid_size | |
| 69 | - self.hash = self.fnv_hash_vec if hash_type == "fnv" else self.ravel_hash_vec | |
| 70 | - assert mode in ["train", "test"] | |
| 71 | - self.mode = mode | |
| 72 | - self.keys = keys | |
| 73 | - self.return_inverse = return_inverse | |
| 74 | - self.return_grid_coord = return_grid_coord | |
| 75 | - self.return_min_coord = return_min_coord | |
| 76 | - self.return_displacement = return_displacement | |
| 77 | - self.project_displacement = project_displacement | |
| 78 | - self.max_grid_coord = max_grid_coord | |
| 79 | - | |
| 80 | - def __call__(self, data_dict): | |
| 81 | - assert "coord" in data_dict.keys() | |
| 82 | - scaled_coord = data_dict["coord"] / np.array(self.grid_size) | |
| 83 | - grid_coord = np.floor(scaled_coord).astype(int) | |
| 84 | - min_coord = grid_coord.min(0) | |
| 85 | - grid_coord -= min_coord | |
| 86 | - scaled_coord -= min_coord | |
| 87 | - min_coord = min_coord * np.array(self.grid_size) | |
| 88 | - if self.max_grid_coord is not None: | |
| 89 | - grid_coord = np.clip(grid_coord, 0, self.max_grid_coord - 1) | |
| 90 | - key = self.hash(grid_coord) | |
| 91 | - idx_sort = np.argsort(key) | |
| 92 | - key_sort = key[idx_sort] | |
| 93 | - _, inverse, count = np.unique(key_sort, return_inverse=True, return_counts=True) | |
| 94 | - if self.mode == "train": # train mode | |
| 95 | - idx_select = ( | |
| 96 | - np.cumsum(np.insert(count, 0, 0)[0:-1]) | |
| 97 | - + np.random.randint(0, count.max(), count.size) % count | |
| 98 | - ) | |
| 99 | - idx_unique = idx_sort[idx_select] | |
| 100 | - if "sampled_index" in data_dict: | |
| 101 | - # for ScanNet data efficient, we need to make sure labeled point is sampled. | |
| 102 | - idx_unique = np.unique( | |
| 103 | - np.append(idx_unique, data_dict["sampled_index"]) | |
| 104 | - ) | |
| 105 | - mask = np.zeros_like(data_dict["segment"]).astype(bool) | |
| 106 | - mask[data_dict["sampled_index"]] = True | |
| 107 | - data_dict["sampled_index"] = np.where(mask[idx_unique])[0] | |
| 108 | - if self.return_inverse: | |
| 109 | - data_dict["inverse"] = np.zeros_like(inverse) | |
| 110 | - data_dict["inverse"][idx_sort] = inverse | |
| 111 | - if self.return_grid_coord: | |
| 112 | - data_dict["grid_coord"] = grid_coord[idx_unique] | |
| 113 | - if self.return_min_coord: | |
| 114 | - data_dict["min_coord"] = min_coord.reshape([1, 3]) | |
| 115 | - if self.return_displacement: | |
| 116 | - displacement = ( | |
| 117 | - scaled_coord - grid_coord - 0.5 | |
| 118 | - ) # [0, 1] -> [-0.5, 0.5] displacement to center | |
| 119 | - if self.project_displacement: | |
| 120 | - displacement = np.sum( | |
| 121 | - displacement * data_dict["normal"], axis=-1, keepdims=True | |
| 122 | - ) | |
| 123 | - data_dict["displacement"] = displacement[idx_unique] | |
| 124 | - for key in self.keys: | |
| 125 | - data_dict[key] = data_dict[key][idx_unique] | |
| 126 | - return data_dict | |
| 127 | - | |
| 128 | - elif self.mode == "test": # test mode | |
| 129 | - idx_select = ( | |
| 130 | - np.cumsum(np.insert(count, 0, 0)[0:-1]) + (count.max() // 2) % count | |
| 131 | - ) | |
| 132 | - idx_part = idx_sort[idx_select] | |
| 133 | - data_part = dict(index=idx_part) | |
| 134 | - if self.return_inverse: | |
| 135 | - data_dict["inverse"] = np.zeros_like(inverse) | |
| 136 | - data_dict["inverse"][idx_sort] = inverse | |
| 137 | - if self.return_grid_coord: | |
| 138 | - data_part["grid_coord"] = grid_coord[idx_part] | |
| 139 | - if self.return_min_coord: | |
| 140 | - data_part["min_coord"] = min_coord.reshape([1, 3]) | |
| 141 | - for key in data_dict.keys(): | |
| 142 | - if key in self.keys: | |
| 143 | - data_part[key] = data_dict[key][idx_part] | |
| 144 | - else: | |
| 145 | - data_part[key] = data_dict[key] | |
| 146 | - return data_part | |
| 147 | - else: | |
| 148 | - raise NotImplementedError | |
| 149 | - | |
| 150 | - @staticmethod | |
| 151 | - def ravel_hash_vec(arr): | |
| 152 | - """ | |
| 153 | - Ravel the coordinates after subtracting the min coordinates. | |
| 154 | - """ | |
| 155 | - assert arr.ndim == 2 | |
| 156 | - arr = arr.copy() | |
| 157 | - arr -= arr.min(0) | |
| 158 | - arr = arr.astype(np.uint64, copy=False) | |
| 159 | - arr_max = arr.max(0).astype(np.uint64) + 1 | |
| 160 | - | |
| 161 | - keys = np.zeros(arr.shape[0], dtype=np.uint64) | |
| 162 | - # Fortran style indexing | |
| 163 | - for j in range(arr.shape[1] - 1): | |
| 164 | - keys += arr[:, j] | |
| 165 | - keys *= arr_max[j + 1] | |
| 166 | - keys += arr[:, -1] | |
| 167 | - return keys | |
| 168 | - | |
| 169 | - @staticmethod | |
| 170 | - def fnv_hash_vec(arr): | |
| 171 | - """ | |
| 172 | - FNV64-1A | |
| 173 | - """ | |
| 174 | - assert arr.ndim == 2 | |
| 175 | - # Floor first for negative coordinates | |
| 176 | - arr = arr.copy() | |
| 177 | - arr = arr.astype(np.uint64, copy=False) | |
| 178 | - hashed_arr = np.uint64(14695981039346656037) * np.ones( | |
| 179 | - arr.shape[0], dtype=np.uint64 | |
| 180 | - ) | |
| 181 | - for j in range(arr.shape[1]): | |
| 182 | - hashed_arr *= np.uint64(1099511628211) | |
| 183 | - hashed_arr = np.bitwise_xor(hashed_arr, arr[:, j]) | |
| 184 | - return hashed_arr | |
| 185 | - | |
| 186 | 7 | |
| 187 | 8 | # Load a point cloud from a file |
| 188 | 9 | def load_o3d_pcd(file_path: str): |
added spatiallm/pcd/transform.py +437 −0
| @@ -0,0 +1,437 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import scipy | |
| 3 | +import scipy.ndimage | |
| 4 | +import scipy.interpolate | |
| 5 | +import scipy.stats | |
| 6 | + | |
| 7 | +from spatiallm.pcd.registry import Registry | |
| 8 | + | |
| 9 | +TRANSFORMS = Registry("transforms") | |
| 10 | + | |
| 11 | +""" | |
| 12 | +3D Point Cloud Preprocessing | |
| 13 | + | |
| 14 | +Reference: PointCept | |
| 15 | + | |
| 16 | +@misc{pointcept2023, | |
| 17 | + title={Pointcept: A Codebase for Point Cloud Perception Research}, | |
| 18 | + author={Pointcept Contributors}, | |
| 19 | + year={2023} | |
| 20 | +} | |
| 21 | +""" | |
| 22 | + | |
| 23 | + | |
| 24 | +class Compose(object): | |
| 25 | + def __init__(self, cfg=None): | |
| 26 | + self.cfg = cfg if cfg is not None else [] | |
| 27 | + self.transforms = [] | |
| 28 | + for t_cfg in self.cfg: | |
| 29 | + self.transforms.append(TRANSFORMS.build(t_cfg)) | |
| 30 | + | |
| 31 | + def __call__(self, data_dict): | |
| 32 | + for t in self.transforms: | |
| 33 | + data_dict = t(data_dict) | |
| 34 | + return data_dict | |
| 35 | + | |
| 36 | + | |
| 37 | +@TRANSFORMS.register_module() | |
| 38 | +class PositiveShift(object): | |
| 39 | + def __call__(self, data_dict): | |
| 40 | + if "coord" in data_dict.keys(): | |
| 41 | + coord_min = np.min(data_dict["coord"], 0) | |
| 42 | + data_dict["coord"] -= coord_min | |
| 43 | + return data_dict | |
| 44 | + | |
| 45 | + | |
| 46 | +@TRANSFORMS.register_module() | |
| 47 | +class NormalizeColor(object): | |
| 48 | + def __call__(self, data_dict): | |
| 49 | + if "color" in data_dict.keys(): | |
| 50 | + data_dict["color"] = data_dict["color"] / 127.5 - 1 | |
| 51 | + return data_dict | |
| 52 | + | |
| 53 | + | |
| 54 | +@TRANSFORMS.register_module() | |
| 55 | +class RandomColorGrayScale(object): | |
| 56 | + def __init__(self, p): | |
| 57 | + self.p = p | |
| 58 | + | |
| 59 | + @staticmethod | |
| 60 | + def rgb_to_grayscale(color, num_output_channels=1): | |
| 61 | + if color.shape[-1] < 3: | |
| 62 | + raise TypeError( | |
| 63 | + "Input color should have at least 3 dimensions, but found {}".format( | |
| 64 | + color.shape[-1] | |
| 65 | + ) | |
| 66 | + ) | |
| 67 | + | |
| 68 | + if num_output_channels not in (1, 3): | |
| 69 | + raise ValueError("num_output_channels should be either 1 or 3") | |
| 70 | + | |
| 71 | + r, g, b = color[..., 0], color[..., 1], color[..., 2] | |
| 72 | + gray = (0.2989 * r + 0.587 * g + 0.114 * b).astype(color.dtype) | |
| 73 | + gray = np.expand_dims(gray, axis=-1) | |
| 74 | + | |
| 75 | + if num_output_channels == 3: | |
| 76 | + gray = np.broadcast_to(gray, color.shape) | |
| 77 | + | |
| 78 | + return gray | |
| 79 | + | |
| 80 | + def __call__(self, data_dict): | |
| 81 | + if np.random.rand() < self.p: | |
| 82 | + data_dict["color"] = self.rgb_to_grayscale(data_dict["color"], 3).copy() | |
| 83 | + return data_dict | |
| 84 | + | |
| 85 | + | |
| 86 | +@TRANSFORMS.register_module() | |
| 87 | +class ChromaticAutoContrast(object): | |
| 88 | + def __init__(self, p=0.2, blend_factor=None): | |
| 89 | + self.p = p | |
| 90 | + self.blend_factor = blend_factor | |
| 91 | + | |
| 92 | + def __call__(self, data_dict): | |
| 93 | + if "color" in data_dict.keys() and np.random.rand() < self.p: | |
| 94 | + lo = np.min(data_dict["color"], 0, keepdims=True) | |
| 95 | + hi = np.max(data_dict["color"], 0, keepdims=True) | |
| 96 | + scale = 255 / (hi - lo) | |
| 97 | + contrast_feat = (data_dict["color"][:, :3] - lo) * scale | |
| 98 | + blend_factor = ( | |
| 99 | + np.random.rand() if self.blend_factor is None else self.blend_factor | |
| 100 | + ) | |
| 101 | + data_dict["color"][:, :3] = (1 - blend_factor) * data_dict["color"][ | |
| 102 | + :, :3 | |
| 103 | + ] + blend_factor * contrast_feat | |
| 104 | + return data_dict | |
| 105 | + | |
| 106 | + | |
| 107 | +@TRANSFORMS.register_module() | |
| 108 | +class ChromaticTranslation(object): | |
| 109 | + def __init__(self, p=0.95, ratio=0.05): | |
| 110 | + self.p = p | |
| 111 | + self.ratio = ratio | |
| 112 | + | |
| 113 | + def __call__(self, data_dict): | |
| 114 | + if "color" in data_dict.keys() and np.random.rand() < self.p: | |
| 115 | + tr = (np.random.rand(1, 3) - 0.5) * 255 * 2 * self.ratio | |
| 116 | + data_dict["color"][:, :3] = np.clip(tr + data_dict["color"][:, :3], 0, 255) | |
| 117 | + return data_dict | |
| 118 | + | |
| 119 | + | |
| 120 | +@TRANSFORMS.register_module() | |
| 121 | +class ChromaticJitter(object): | |
| 122 | + def __init__(self, p=0.95, std=0.005): | |
| 123 | + self.p = p | |
| 124 | + self.std = std | |
| 125 | + | |
| 126 | + def __call__(self, data_dict): | |
| 127 | + if "color" in data_dict.keys() and np.random.rand() < self.p: | |
| 128 | + noise = np.random.randn(data_dict["color"].shape[0], 3) | |
| 129 | + noise *= self.std * 255 | |
| 130 | + data_dict["color"][:, :3] = np.clip( | |
| 131 | + noise + data_dict["color"][:, :3], 0, 255 | |
| 132 | + ) | |
| 133 | + return data_dict | |
| 134 | + | |
| 135 | + | |
| 136 | +@TRANSFORMS.register_module() | |
| 137 | +class HueSaturationTranslation(object): | |
| 138 | + @staticmethod | |
| 139 | + def rgb_to_hsv(rgb): | |
| 140 | + # Translated from source of colorsys.rgb_to_hsv | |
| 141 | + # r,g,b should be a numpy arrays with values between 0 and 255 | |
| 142 | + # rgb_to_hsv returns an array of floats between 0.0 and 1.0. | |
| 143 | + rgb = rgb.astype("float") | |
| 144 | + hsv = np.zeros_like(rgb) | |
| 145 | + # in case an RGBA array was passed, just copy the A channel | |
| 146 | + hsv[..., 3:] = rgb[..., 3:] | |
| 147 | + r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2] | |
| 148 | + maxc = np.max(rgb[..., :3], axis=-1) | |
| 149 | + minc = np.min(rgb[..., :3], axis=-1) | |
| 150 | + hsv[..., 2] = maxc | |
| 151 | + mask = maxc != minc | |
| 152 | + hsv[mask, 1] = (maxc - minc)[mask] / maxc[mask] | |
| 153 | + rc = np.zeros_like(r) | |
| 154 | + gc = np.zeros_like(g) | |
| 155 | + bc = np.zeros_like(b) | |
| 156 | + rc[mask] = (maxc - r)[mask] / (maxc - minc)[mask] | |
| 157 | + gc[mask] = (maxc - g)[mask] / (maxc - minc)[mask] | |
| 158 | + bc[mask] = (maxc - b)[mask] / (maxc - minc)[mask] | |
| 159 | + hsv[..., 0] = np.select( | |
| 160 | + [r == maxc, g == maxc], [bc - gc, 2.0 + rc - bc], default=4.0 + gc - rc | |
| 161 | + ) | |
| 162 | + hsv[..., 0] = (hsv[..., 0] / 6.0) % 1.0 | |
| 163 | + return hsv | |
| 164 | + | |
| 165 | + @staticmethod | |
| 166 | + def hsv_to_rgb(hsv): | |
| 167 | + # Translated from source of colorsys.hsv_to_rgb | |
| 168 | + # h,s should be a numpy arrays with values between 0.0 and 1.0 | |
| 169 | + # v should be a numpy array with values between 0.0 and 255.0 | |
| 170 | + # hsv_to_rgb returns an array of uints between 0 and 255. | |
| 171 | + rgb = np.empty_like(hsv) | |
| 172 | + rgb[..., 3:] = hsv[..., 3:] | |
| 173 | + h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2] | |
| 174 | + i = (h * 6.0).astype("uint8") | |
| 175 | + f = (h * 6.0) - i | |
| 176 | + p = v * (1.0 - s) | |
| 177 | + q = v * (1.0 - s * f) | |
| 178 | + t = v * (1.0 - s * (1.0 - f)) | |
| 179 | + i = i % 6 | |
| 180 | + conditions = [s == 0.0, i == 1, i == 2, i == 3, i == 4, i == 5] | |
| 181 | + rgb[..., 0] = np.select(conditions, [v, q, p, p, t, v], default=v) | |
| 182 | + rgb[..., 1] = np.select(conditions, [v, v, v, q, p, p], default=t) | |
| 183 | + rgb[..., 2] = np.select(conditions, [v, p, t, v, v, q], default=p) | |
| 184 | + return rgb.astype("uint8") | |
| 185 | + | |
| 186 | + def __init__(self, hue_max=0.5, saturation_max=0.2): | |
| 187 | + self.hue_max = hue_max | |
| 188 | + self.saturation_max = saturation_max | |
| 189 | + | |
| 190 | + def __call__(self, data_dict): | |
| 191 | + if "color" in data_dict.keys(): | |
| 192 | + # Assume color[:, :3] is rgb | |
| 193 | + hsv = HueSaturationTranslation.rgb_to_hsv(data_dict["color"][:, :3]) | |
| 194 | + hue_val = (np.random.rand() - 0.5) * 2 * self.hue_max | |
| 195 | + sat_ratio = 1 + (np.random.rand() - 0.5) * 2 * self.saturation_max | |
| 196 | + hsv[..., 0] = np.remainder(hue_val + hsv[..., 0] + 1, 1) | |
| 197 | + hsv[..., 1] = np.clip(sat_ratio * hsv[..., 1], 0, 1) | |
| 198 | + data_dict["color"][:, :3] = np.clip( | |
| 199 | + HueSaturationTranslation.hsv_to_rgb(hsv), 0, 255 | |
| 200 | + ) | |
| 201 | + return data_dict | |
| 202 | + | |
| 203 | + | |
| 204 | +@TRANSFORMS.register_module() | |
| 205 | +class RandomColorDrop(object): | |
| 206 | + def __init__(self, p=0.2, color_augment=0.0): | |
| 207 | + self.p = p | |
| 208 | + self.color_augment = color_augment | |
| 209 | + | |
| 210 | + def __call__(self, data_dict): | |
| 211 | + if "color" in data_dict.keys() and np.random.rand() < self.p: | |
| 212 | + data_dict["color"] = data_dict["color"].astype(np.float64) | |
| 213 | + data_dict["color"] *= self.color_augment | |
| 214 | + return data_dict | |
| 215 | + | |
| 216 | + def __repr__(self): | |
| 217 | + return "RandomColorDrop(color_augment: {}, p: {})".format( | |
| 218 | + self.color_augment, self.p | |
| 219 | + ) | |
| 220 | + | |
| 221 | + | |
| 222 | +@TRANSFORMS.register_module() | |
| 223 | +class RandomJitter(object): | |
| 224 | + def __init__(self, sigma=0.01, clip=0.05, ratio=0.5, p=0.5): | |
| 225 | + assert clip > 0 | |
| 226 | + self.sigma = sigma | |
| 227 | + self.clip = clip | |
| 228 | + self.ratio = ratio | |
| 229 | + self.p = p | |
| 230 | + | |
| 231 | + def __call__(self, data_dict): | |
| 232 | + if "coord" in data_dict.keys() and np.random.rand() < self.p: | |
| 233 | + jitter = np.clip( | |
| 234 | + self.sigma * np.random.randn(data_dict["coord"].shape[0], 3), | |
| 235 | + -self.clip, | |
| 236 | + self.clip, | |
| 237 | + ) | |
| 238 | + idx = np.random.rand(data_dict["coord"].shape[0]) < self.ratio | |
| 239 | + data_dict["coord"][idx] += jitter[idx] | |
| 240 | + return data_dict | |
| 241 | + | |
| 242 | + | |
| 243 | +@TRANSFORMS.register_module() | |
| 244 | +class ElasticDistortion(object): | |
| 245 | + def __init__(self, distortion_params=None, p=[0.8, 0.5]): | |
| 246 | + self.distortion_params = ( | |
| 247 | + [[0.2, 0.4], [0.8, 1.6]] if distortion_params is None else distortion_params | |
| 248 | + ) | |
| 249 | + self.p = p | |
| 250 | + | |
| 251 | + @staticmethod | |
| 252 | + def elastic_distortion(coords, granularity, magnitude): | |
| 253 | + """ | |
| 254 | + Apply elastic distortion on sparse coordinate space. | |
| 255 | + pointcloud: numpy array of (number of points, at least 3 spatial dims) | |
| 256 | + granularity: size of the noise grid (in same scale[m/cm] as the voxel grid) | |
| 257 | + magnitude: noise multiplier | |
| 258 | + """ | |
| 259 | + blurx = np.ones((3, 1, 1, 1)).astype("float32") / 3 | |
| 260 | + blury = np.ones((1, 3, 1, 1)).astype("float32") / 3 | |
| 261 | + blurz = np.ones((1, 1, 3, 1)).astype("float32") / 3 | |
| 262 | + coords_min = coords.min(0) | |
| 263 | + | |
| 264 | + # Create Gaussian noise tensor of the size given by granularity. | |
| 265 | + noise_dim = ((coords - coords_min).max(0) // granularity).astype(int) + 3 | |
| 266 | + noise = np.random.randn(*noise_dim, 3).astype(np.float32) | |
| 267 | + | |
| 268 | + # Smoothing. | |
| 269 | + for _ in range(2): | |
| 270 | + noise = scipy.ndimage.convolve(noise, blurx, mode="constant", cval=0) | |
| 271 | + noise = scipy.ndimage.convolve(noise, blury, mode="constant", cval=0) | |
| 272 | + noise = scipy.ndimage.convolve(noise, blurz, mode="constant", cval=0) | |
| 273 | + | |
| 274 | + # Trilinear interpolate noise filters for each spatial dimensions. | |
| 275 | + ax = [ | |
| 276 | + np.linspace(d_min, d_max, d) | |
| 277 | + for d_min, d_max, d in zip( | |
| 278 | + coords_min - granularity, | |
| 279 | + coords_min + granularity * (noise_dim - 2), | |
| 280 | + noise_dim, | |
| 281 | + ) | |
| 282 | + ] | |
| 283 | + interp = scipy.interpolate.RegularGridInterpolator( | |
| 284 | + ax, noise, bounds_error=False, fill_value=0 | |
| 285 | + ) | |
| 286 | + coords += interp(coords) * magnitude | |
| 287 | + return coords | |
| 288 | + | |
| 289 | + def __call__(self, data_dict): | |
| 290 | + if "coord" in data_dict.keys() and self.distortion_params is not None: | |
| 291 | + count = 0 | |
| 292 | + for granularity, magnitude in self.distortion_params: | |
| 293 | + if np.random.rand() > self.p[count]: | |
| 294 | + continue | |
| 295 | + data_dict["coord"] = self.elastic_distortion( | |
| 296 | + data_dict["coord"], granularity, magnitude | |
| 297 | + ) | |
| 298 | + if "normal" in data_dict.keys(): | |
| 299 | + data_dict["normal"] = self.elastic_distortion( | |
| 300 | + data_dict["normal"], granularity, magnitude | |
| 301 | + ) | |
| 302 | + count += 1 | |
| 303 | + return data_dict | |
| 304 | + | |
| 305 | + | |
| 306 | +@TRANSFORMS.register_module() | |
| 307 | +class GridSample(object): | |
| 308 | + def __init__( | |
| 309 | + self, | |
| 310 | + grid_size=0.05, | |
| 311 | + hash_type="fnv", | |
| 312 | + mode="train", | |
| 313 | + keys=("coord", "color", "normal", "segment"), | |
| 314 | + return_inverse=False, | |
| 315 | + return_grid_coord=False, | |
| 316 | + return_min_coord=False, | |
| 317 | + return_displacement=False, | |
| 318 | + project_displacement=False, | |
| 319 | + max_grid_coord=None, | |
| 320 | + ): | |
| 321 | + self.grid_size = grid_size | |
| 322 | + self.hash = self.fnv_hash_vec if hash_type == "fnv" else self.ravel_hash_vec | |
| 323 | + assert mode in ["train", "test"] | |
| 324 | + self.mode = mode | |
| 325 | + self.keys = keys | |
| 326 | + self.return_inverse = return_inverse | |
| 327 | + self.return_grid_coord = return_grid_coord | |
| 328 | + self.return_min_coord = return_min_coord | |
| 329 | + self.return_displacement = return_displacement | |
| 330 | + self.project_displacement = project_displacement | |
| 331 | + self.max_grid_coord = max_grid_coord | |
| 332 | + | |
| 333 | + def __call__(self, data_dict): | |
| 334 | + assert "coord" in data_dict.keys() | |
| 335 | + scaled_coord = data_dict["coord"] / np.array(self.grid_size) | |
| 336 | + grid_coord = np.floor(scaled_coord).astype(int) | |
| 337 | + min_coord = grid_coord.min(0) | |
| 338 | + grid_coord -= min_coord | |
| 339 | + scaled_coord -= min_coord | |
| 340 | + min_coord = min_coord * np.array(self.grid_size) | |
| 341 | + if self.max_grid_coord is not None: | |
| 342 | + grid_coord = np.clip(grid_coord, 0, self.max_grid_coord - 1) | |
| 343 | + key = self.hash(grid_coord) | |
| 344 | + idx_sort = np.argsort(key) | |
| 345 | + key_sort = key[idx_sort] | |
| 346 | + _, inverse, count = np.unique(key_sort, return_inverse=True, return_counts=True) | |
| 347 | + if self.mode == "train": # train mode | |
| 348 | + idx_select = ( | |
| 349 | + np.cumsum(np.insert(count, 0, 0)[0:-1]) | |
| 350 | + + np.random.randint(0, count.max(), count.size) % count | |
| 351 | + ) | |
| 352 | + idx_unique = idx_sort[idx_select] | |
| 353 | + if "sampled_index" in data_dict: | |
| 354 | + # for ScanNet data efficient, we need to make sure labeled point is sampled. | |
| 355 | + idx_unique = np.unique( | |
| 356 | + np.append(idx_unique, data_dict["sampled_index"]) | |
| 357 | + ) | |
| 358 | + mask = np.zeros_like(data_dict["segment"]).astype(bool) | |
| 359 | + mask[data_dict["sampled_index"]] = True | |
| 360 | + data_dict["sampled_index"] = np.where(mask[idx_unique])[0] | |
| 361 | + if self.return_inverse: | |
| 362 | + data_dict["inverse"] = np.zeros_like(inverse) | |
| 363 | + data_dict["inverse"][idx_sort] = inverse | |
| 364 | + if self.return_grid_coord: | |
| 365 | + data_dict["grid_coord"] = grid_coord[idx_unique] | |
| 366 | + if self.return_min_coord: | |
| 367 | + data_dict["min_coord"] = min_coord.reshape([1, 3]) | |
| 368 | + if self.return_displacement: | |
| 369 | + displacement = ( | |
| 370 | + scaled_coord - grid_coord - 0.5 | |
| 371 | + ) # [0, 1] -> [-0.5, 0.5] displacement to center | |
| 372 | + if self.project_displacement: | |
| 373 | + displacement = np.sum( | |
| 374 | + displacement * data_dict["normal"], axis=-1, keepdims=True | |
| 375 | + ) | |
| 376 | + data_dict["displacement"] = displacement[idx_unique] | |
| 377 | + for key in self.keys: | |
| 378 | + data_dict[key] = data_dict[key][idx_unique] | |
| 379 | + return data_dict | |
| 380 | + | |
| 381 | + elif self.mode == "test": # test mode | |
| 382 | + idx_select = ( | |
| 383 | + np.cumsum(np.insert(count, 0, 0)[0:-1]) + (count.max() // 2) % count | |
| 384 | + ) | |
| 385 | + idx_part = idx_sort[idx_select] | |
| 386 | + data_part = dict(index=idx_part) | |
| 387 | + if self.return_inverse: | |
| 388 | + data_dict["inverse"] = np.zeros_like(inverse) | |
| 389 | + data_dict["inverse"][idx_sort] = inverse | |
| 390 | + if self.return_grid_coord: | |
| 391 | + data_part["grid_coord"] = grid_coord[idx_part] | |
| 392 | + if self.return_min_coord: | |
| 393 | + data_part["min_coord"] = min_coord.reshape([1, 3]) | |
| 394 | + for key in data_dict.keys(): | |
| 395 | + if key in self.keys: | |
| 396 | + data_part[key] = data_dict[key][idx_part] | |
| 397 | + else: | |
| 398 | + data_part[key] = data_dict[key] | |
| 399 | + return data_part | |
| 400 | + else: | |
| 401 | + raise NotImplementedError | |
| 402 | + | |
| 403 | + @staticmethod | |
| 404 | + def ravel_hash_vec(arr): | |
| 405 | + """ | |
| 406 | + Ravel the coordinates after subtracting the min coordinates. | |
| 407 | + """ | |
| 408 | + assert arr.ndim == 2 | |
| 409 | + arr = arr.copy() | |
| 410 | + arr -= arr.min(0) | |
| 411 | + arr = arr.astype(np.uint64, copy=False) | |
| 412 | + arr_max = arr.max(0).astype(np.uint64) + 1 | |
| 413 | + | |
| 414 | + keys = np.zeros(arr.shape[0], dtype=np.uint64) | |
| 415 | + # Fortran style indexing | |
| 416 | + for j in range(arr.shape[1] - 1): | |
| 417 | + keys += arr[:, j] | |
| 418 | + keys *= arr_max[j + 1] | |
| 419 | + keys += arr[:, -1] | |
| 420 | + return keys | |
| 421 | + | |
| 422 | + @staticmethod | |
| 423 | + def fnv_hash_vec(arr): | |
| 424 | + """ | |
| 425 | + FNV64-1A | |
| 426 | + """ | |
| 427 | + assert arr.ndim == 2 | |
| 428 | + # Floor first for negative coordinates | |
| 429 | + arr = arr.copy() | |
| 430 | + arr = arr.astype(np.uint64, copy=False) | |
| 431 | + hashed_arr = np.uint64(14695981039346656037) * np.ones( | |
| 432 | + arr.shape[0], dtype=np.uint64 | |
| 433 | + ) | |
| 434 | + for j in range(arr.shape[1]): | |
| 435 | + hashed_arr *= np.uint64(1099511628211) | |
| 436 | + hashed_arr = np.bitwise_xor(hashed_arr, arr[:, j]) | |
| 437 | + return hashed_arr |
added spatiallm/tuner/__init__.py +0 −0
added spatiallm/tuner/create_dataset.py +147 −0
| @@ -0,0 +1,147 @@ | ||
| 1 | +import os | |
| 2 | +import argparse | |
| 3 | +import json | |
| 4 | +from glob import glob | |
| 5 | + | |
| 6 | +import pandas as pd | |
| 7 | +from tqdm import tqdm | |
| 8 | + | |
| 9 | +from spatiallm.tuner.data import ( | |
| 10 | + LAYOUT_S_PLACEHOLDER, | |
| 11 | + LAYOUT_E_PLACEHOLDER, | |
| 12 | + POINT_CLOUD_PLACEHOLDER, | |
| 13 | +) | |
| 14 | +from spatiallm.layout.layout import Layout | |
| 15 | + | |
| 16 | +if __name__ == "__main__": | |
| 17 | + parser = argparse.ArgumentParser() | |
| 18 | + parser.add_argument( | |
| 19 | + "-d", | |
| 20 | + "--dataset_dir", | |
| 21 | + type=str, | |
| 22 | + required=True, | |
| 23 | + help="Path to the input point cloud directory", | |
| 24 | + ) | |
| 25 | + parser.add_argument( | |
| 26 | + "-s", | |
| 27 | + "--split_csv", | |
| 28 | + type=str, | |
| 29 | + required=True, | |
| 30 | + help="Path to the split csv file", | |
| 31 | + ) | |
| 32 | + parser.add_argument( | |
| 33 | + "--code_template_file", | |
| 34 | + type=str, | |
| 35 | + default="code_template.txt", | |
| 36 | + ) | |
| 37 | + parser.add_argument( | |
| 38 | + "-n", | |
| 39 | + "--dataset_name", | |
| 40 | + type=str, | |
| 41 | + required=True, | |
| 42 | + help="Name of the dataset", | |
| 43 | + ) | |
| 44 | + args = parser.parse_args() | |
| 45 | + | |
| 46 | + pcd_dir = os.path.join(args.dataset_dir, "pcd") | |
| 47 | + layout_dir = os.path.join(args.dataset_dir, "layout") | |
| 48 | + | |
| 49 | + pcd_files = glob(os.path.join(pcd_dir, "*.ply")) | |
| 50 | + pcd_scene_ids = [os.path.basename(pcd_file).split(".")[0] for pcd_file in pcd_files] | |
| 51 | + layout_files = glob(os.path.join(layout_dir, "*.txt")) | |
| 52 | + layout_scene_ids = [ | |
| 53 | + os.path.basename(layout_file).split(".")[0] for layout_file in layout_files | |
| 54 | + ] | |
| 55 | + | |
| 56 | + # find the common filenames between pcd_filenames and layout_filenames | |
| 57 | + scene_ids = set(pcd_scene_ids) & set(layout_scene_ids) | |
| 58 | + scene_ids = list(scene_ids) | |
| 59 | + | |
| 60 | + df = pd.read_csv(args.split_csv, dtype=str) | |
| 61 | + df.set_index("id", inplace=True) | |
| 62 | + | |
| 63 | + print(f"Creating dataset with {len(scene_ids)} scenes...") | |
| 64 | + | |
| 65 | + with open(args.code_template_file, "r") as f: | |
| 66 | + code_template = f.read() | |
| 67 | + | |
| 68 | + dataset = { | |
| 69 | + "train": [], | |
| 70 | + "val": [], | |
| 71 | + } | |
| 72 | + for si, scene_id in enumerate(tqdm(scene_ids)): | |
| 73 | + try: | |
| 74 | + if scene_id not in df.index: | |
| 75 | + continue | |
| 76 | + split = df.loc[scene_id, "split"] | |
| 77 | + | |
| 78 | + # load txt file | |
| 79 | + with open(os.path.join(layout_dir, f"{scene_id}.txt"), "r") as f: | |
| 80 | + layout_content = f.read() | |
| 81 | + | |
| 82 | + layout = Layout(layout_content) | |
| 83 | + language_string = layout.to_language_string() | |
| 84 | + | |
| 85 | + conversation_data = { | |
| 86 | + "conversations": [ | |
| 87 | + { | |
| 88 | + "from": "human", | |
| 89 | + "value": f"{POINT_CLOUD_PLACEHOLDER}Detect boxes. The reference code is as followed: {code_template}", | |
| 90 | + }, | |
| 91 | + { | |
| 92 | + "from": "gpt", | |
| 93 | + "value": f"{LAYOUT_S_PLACEHOLDER}{language_string}{LAYOUT_E_PLACEHOLDER}", | |
| 94 | + }, | |
| 95 | + ], | |
| 96 | + "point_clouds": [ | |
| 97 | + os.path.join(os.path.basename(pcd_dir), f"{scene_id}.ply"), | |
| 98 | + ], | |
| 99 | + } | |
| 100 | + dataset[split].append(conversation_data) | |
| 101 | + except Exception as e: | |
| 102 | + print(f"Error processing scene {scene_id}: {e}") | |
| 103 | + continue | |
| 104 | + | |
| 105 | + # save train set to train.json | |
| 106 | + print(f"Saving train set with {len(dataset['train'])} samples...") | |
| 107 | + with open( | |
| 108 | + os.path.join(args.dataset_dir, f"{args.dataset_name}_train.json"), "w" | |
| 109 | + ) as f: | |
| 110 | + json.dump(dataset["train"], f, indent=2) | |
| 111 | + | |
| 112 | + # save val set to val.json | |
| 113 | + print(f"Saving val set with {len(dataset['val'])} samples...") | |
| 114 | + with open( | |
| 115 | + os.path.join(args.dataset_dir, f"{args.dataset_name}_val.json"), "w" | |
| 116 | + ) as f: | |
| 117 | + json.dump(dataset["val"], f, indent=2) | |
| 118 | + | |
| 119 | + # update dataset_info.json | |
| 120 | + dataset_info = { | |
| 121 | + f"{args.dataset_name}_train": { | |
| 122 | + "file_name": f"{args.dataset_name}_train.json", | |
| 123 | + "formatting": "sharegpt", | |
| 124 | + "columns": { | |
| 125 | + "messages": "conversations", | |
| 126 | + "point_clouds": "point_clouds", | |
| 127 | + }, | |
| 128 | + }, | |
| 129 | + f"{args.dataset_name}_val": { | |
| 130 | + "file_name": f"{args.dataset_name}_val.json", | |
| 131 | + "formatting": "sharegpt", | |
| 132 | + "columns": { | |
| 133 | + "messages": "conversations", | |
| 134 | + "point_clouds": "point_clouds", | |
| 135 | + }, | |
| 136 | + }, | |
| 137 | + } | |
| 138 | + | |
| 139 | + if not os.path.exists(os.path.join(args.dataset_dir, "dataset_info.json")): | |
| 140 | + with open(os.path.join(args.dataset_dir, "dataset_info.json"), "w") as f: | |
| 141 | + json.dump(dataset_info, f, indent=2) | |
| 142 | + else: | |
| 143 | + with open(os.path.join(args.dataset_dir, "dataset_info.json"), "r") as f: | |
| 144 | + original_dataset_info = json.load(f) | |
| 145 | + original_dataset_info.update(dataset_info) | |
| 146 | + with open(os.path.join(args.dataset_dir, "dataset_info.json"), "w") as f: | |
| 147 | + json.dump(original_dataset_info, f, indent=2) |
added spatiallm/tuner/data/__init__.py +48 −0
| @@ -0,0 +1,48 @@ | ||
| 1 | +# Copyright 2025 the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 | +# you may not use this file except in compliance with the License. | |
| 5 | +# You may obtain a copy of the License at | |
| 6 | +# | |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 | +# | |
| 9 | +# Unless required by applicable law or agreed to in writing, software | |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 | +# See the License for the specific language governing permissions and | |
| 13 | +# limitations under the License. | |
| 14 | + | |
| 15 | + | |
| 16 | +from .loader import get_dataset | |
| 17 | +from .template import ( | |
| 18 | + IGNORE_INDEX, | |
| 19 | + TEMPLATES, | |
| 20 | + Role, | |
| 21 | + Template, | |
| 22 | + get_template_and_fix_tokenizer, | |
| 23 | + register_spatiallm_templates, | |
| 24 | +) | |
| 25 | +from .collator import SFTDataCollatorWith4DAttentionMask | |
| 26 | +from .mm_plugin import ( | |
| 27 | + LAYOUT_S_PLACEHOLDER, | |
| 28 | + LAYOUT_E_PLACEHOLDER, | |
| 29 | + POINT_S_TOKEN, | |
| 30 | + POINT_E_TOKEN, | |
| 31 | + POINT_CLOUD_PLACEHOLDER, | |
| 32 | +) | |
| 33 | + | |
| 34 | +__all__ = [ | |
| 35 | + "IGNORE_INDEX", | |
| 36 | + "TEMPLATES", | |
| 37 | + "LAYOUT_S_PLACEHOLDER", | |
| 38 | + "LAYOUT_E_PLACEHOLDER", | |
| 39 | + "POINT_S_TOKEN", | |
| 40 | + "POINT_E_TOKEN", | |
| 41 | + "POINT_CLOUD_PLACEHOLDER", | |
| 42 | + "Role", | |
| 43 | + "Template", | |
| 44 | + "get_dataset", | |
| 45 | + "get_template_and_fix_tokenizer", | |
| 46 | + "register_spatiallm_templates", | |
| 47 | + "SFTDataCollatorWith4DAttentionMask", | |
| 48 | +] |
added spatiallm/tuner/data/collator.py +200 −0
| @@ -0,0 +1,200 @@ | ||
| 1 | +# Copyright 2025 OpenAccess AI Collective and the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# This code is inspired by the OpenAccess AI Collective's axolotl library. | |
| 4 | +# https://github.com/OpenAccess-AI-Collective/axolotl/blob/main/src/axolotl/monkeypatch/utils.py | |
| 5 | +# | |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 7 | +# you may not use this file except in compliance with the License. | |
| 8 | +# You may obtain a copy of the License at | |
| 9 | +# | |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 11 | +# | |
| 12 | +# Unless required by applicable law or agreed to in writing, software | |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 15 | +# See the License for the specific language governing permissions and | |
| 16 | +# limitations under the License. | |
| 17 | + | |
| 18 | +from dataclasses import dataclass | |
| 19 | +from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Sequence, Tuple | |
| 20 | + | |
| 21 | +import torch | |
| 22 | +import torch.nn.functional as F | |
| 23 | +from transformers import DataCollatorForSeq2Seq | |
| 24 | + | |
| 25 | +from .template import IGNORE_INDEX | |
| 26 | + | |
| 27 | +if TYPE_CHECKING: | |
| 28 | + from transformers import PreTrainedTokenizer | |
| 29 | + | |
| 30 | + from .template import Template | |
| 31 | + from .mm_plugin import PointCloudInput | |
| 32 | + | |
| 33 | + | |
| 34 | +def prepare_4d_attention_mask( | |
| 35 | + attention_mask_with_indices: "torch.Tensor", dtype: "torch.dtype" | |
| 36 | +) -> "torch.Tensor": | |
| 37 | + r"""Expand 2d attention mask to 4d attention mask. | |
| 38 | + | |
| 39 | + Expand the attention mask with indices from (batch_size, seq_len) to (batch_size, 1, seq_len, seq_len), | |
| 40 | + handle packed sequences and transforms the mask to lower triangular form to prevent future peeking. | |
| 41 | + | |
| 42 | + e.g. | |
| 43 | + ```python | |
| 44 | + # input | |
| 45 | + [[1, 1, 2, 2, 2, 0]] | |
| 46 | + # output | |
| 47 | + [ | |
| 48 | + [ | |
| 49 | + [ | |
| 50 | + [o, x, x, x, x, x], | |
| 51 | + [o, o, x, x, x, x], | |
| 52 | + [x, x, o, x, x, x], | |
| 53 | + [x, x, o, o, x, x], | |
| 54 | + [x, x, o, o, o, x], | |
| 55 | + [x, x, x, x, x, x], | |
| 56 | + ] | |
| 57 | + ] | |
| 58 | + ] | |
| 59 | + ``` | |
| 60 | + where `o` equals to `0.0`, `x` equals to `min_dtype`. | |
| 61 | + """ | |
| 62 | + _, seq_len = attention_mask_with_indices.size() | |
| 63 | + min_dtype = torch.finfo(dtype).min | |
| 64 | + zero_tensor = torch.tensor(0, dtype=dtype) | |
| 65 | + | |
| 66 | + # Create a non-padding mask. | |
| 67 | + non_padding_mask = (attention_mask_with_indices != 0).unsqueeze(1).unsqueeze(2) | |
| 68 | + # Create indices for comparison. | |
| 69 | + indices = attention_mask_with_indices.unsqueeze(1).unsqueeze( | |
| 70 | + 2 | |
| 71 | + ) # [bsz, 1, 1, seq_len] | |
| 72 | + indices_t = attention_mask_with_indices.unsqueeze(1).unsqueeze( | |
| 73 | + 3 | |
| 74 | + ) # [bsz, 1, seq_len, 1] | |
| 75 | + # Create a lower triangular mask. | |
| 76 | + tril_mask = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool)) | |
| 77 | + attention_mask_4d = (indices == indices_t) & non_padding_mask & tril_mask | |
| 78 | + # Invert the attention mask. | |
| 79 | + attention_mask_4d = torch.where(attention_mask_4d, zero_tensor, min_dtype) | |
| 80 | + return attention_mask_4d | |
| 81 | + | |
| 82 | + | |
| 83 | +def infer_seqlen(source_len: int, target_len: int, cutoff_len: int) -> Tuple[int, int]: | |
| 84 | + r""" | |
| 85 | + Computes the real sequence length after truncation by the cutoff_len. | |
| 86 | + """ | |
| 87 | + if target_len * 2 < cutoff_len: # truncate source | |
| 88 | + max_target_len = cutoff_len | |
| 89 | + elif source_len * 2 < cutoff_len: # truncate target | |
| 90 | + max_target_len = cutoff_len - source_len | |
| 91 | + else: # truncate both | |
| 92 | + max_target_len = int(cutoff_len * (target_len / (source_len + target_len))) | |
| 93 | + | |
| 94 | + new_target_len = min(max_target_len, target_len) | |
| 95 | + max_source_len = max(cutoff_len - new_target_len, 0) | |
| 96 | + new_source_len = min(max_source_len, source_len) | |
| 97 | + return new_source_len, new_target_len | |
| 98 | + | |
| 99 | + | |
| 100 | +def _encode_messages_example( | |
| 101 | + messages: Sequence[Dict[str, str]], | |
| 102 | + system: Optional[str], | |
| 103 | + point_clouds: Sequence["PointCloudInput"], | |
| 104 | + template: "Template", | |
| 105 | + tokenizer: "PreTrainedTokenizer", | |
| 106 | + cutoff_len: int, | |
| 107 | +) -> Tuple[List[int], List[int]]: | |
| 108 | + input_ids, labels = template.mm_plugin.process_token_ids( | |
| 109 | + [], [], point_clouds, tokenizer | |
| 110 | + ) | |
| 111 | + encoded_pairs = template.encode_multiturn(tokenizer, messages, system) | |
| 112 | + total_length = len(input_ids) | |
| 113 | + | |
| 114 | + for turn_idx, (source_ids, target_ids) in enumerate(encoded_pairs): | |
| 115 | + if total_length >= cutoff_len: | |
| 116 | + break | |
| 117 | + | |
| 118 | + source_len, target_len = infer_seqlen( | |
| 119 | + len(source_ids), len(target_ids), cutoff_len - total_length | |
| 120 | + ) | |
| 121 | + source_ids = source_ids[:source_len] | |
| 122 | + target_ids = target_ids[:target_len] | |
| 123 | + total_length += source_len + target_len | |
| 124 | + source_label = [IGNORE_INDEX] * source_len | |
| 125 | + | |
| 126 | + target_label = target_ids | |
| 127 | + input_ids += source_ids + target_ids | |
| 128 | + labels += source_label + target_label | |
| 129 | + | |
| 130 | + return input_ids, labels | |
| 131 | + | |
| 132 | + | |
| 133 | +@dataclass | |
| 134 | +class MultiModalDataCollatorForSeq2Seq(DataCollatorForSeq2Seq): | |
| 135 | + r""" | |
| 136 | + Data collator that supports VLMs. | |
| 137 | + | |
| 138 | + Features should contain input_ids, attention_mask, labels, and optionally contain images and videos. | |
| 139 | + """ | |
| 140 | + | |
| 141 | + template: Optional["Template"] = None | |
| 142 | + | |
| 143 | + def __post_init__(self): | |
| 144 | + if self.template is None: | |
| 145 | + raise ValueError("Template is required for MultiModalDataCollator.") | |
| 146 | + | |
| 147 | + def __call__(self, features: Sequence[Dict[str, Any]]) -> Dict[str, "torch.Tensor"]: | |
| 148 | + batch_point_clouds, batch_input_prompts = [], [] | |
| 149 | + for feature in features: | |
| 150 | + prompts = feature.pop("_prompt") | |
| 151 | + responses = feature.pop("_response") | |
| 152 | + point_clouds = feature.pop("_point_clouds", None) or [] | |
| 153 | + batch_point_clouds.extend(point_clouds) | |
| 154 | + batch_input_prompts.append(prompts + responses) | |
| 155 | + | |
| 156 | + mm_inputs = self.template.mm_plugin.get_mm_inputs( | |
| 157 | + batch_point_clouds, batch_input_prompts | |
| 158 | + ) | |
| 159 | + batched_messages = mm_inputs.pop("messages") | |
| 160 | + | |
| 161 | + for mi, messages in enumerate(batched_messages): | |
| 162 | + feature = features[mi] | |
| 163 | + input_ids, labels = _encode_messages_example( | |
| 164 | + messages=messages, | |
| 165 | + system=feature.pop("_system", ""), | |
| 166 | + point_clouds=batch_point_clouds[mi] if batch_point_clouds else [], | |
| 167 | + template=self.template, | |
| 168 | + tokenizer=self.tokenizer, | |
| 169 | + cutoff_len=self.template.cutoff_len, | |
| 170 | + ) | |
| 171 | + feature["input_ids"] = input_ids | |
| 172 | + feature["attention_mask"] = [1] * len(input_ids) | |
| 173 | + feature["labels"] = labels | |
| 174 | + | |
| 175 | + features: Dict[str, "torch.Tensor"] = super().__call__(features) | |
| 176 | + features.update(mm_inputs) | |
| 177 | + | |
| 178 | + return features | |
| 179 | + | |
| 180 | + | |
| 181 | +@dataclass | |
| 182 | +class SFTDataCollatorWith4DAttentionMask(MultiModalDataCollatorForSeq2Seq): | |
| 183 | + r"""Data collator for 4d attention mask.""" | |
| 184 | + | |
| 185 | + block_diag_attn: bool = False | |
| 186 | + attn_implementation: Literal["eager", "sdpa", "flash_attention_2"] = "eager" | |
| 187 | + compute_dtype: "torch.dtype" = torch.float32 | |
| 188 | + | |
| 189 | + def __call__(self, features: list[dict[str, Any]]) -> dict[str, "torch.Tensor"]: | |
| 190 | + features = super().__call__(features) | |
| 191 | + if self.block_diag_attn and self.attn_implementation != "flash_attention_2": | |
| 192 | + features["attention_mask"] = prepare_4d_attention_mask( | |
| 193 | + features["attention_mask"], self.compute_dtype | |
| 194 | + ) | |
| 195 | + | |
| 196 | + for key, value in features.items(): # cast data dtype | |
| 197 | + if torch.is_tensor(value) and torch.is_floating_point(value): | |
| 198 | + features[key] = value.to(self.compute_dtype) | |
| 199 | + | |
| 200 | + return features |
added spatiallm/tuner/data/converter.py +256 −0
| @@ -0,0 +1,256 @@ | ||
| 1 | +# Copyright 2025 the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 | +# you may not use this file except in compliance with the License. | |
| 5 | +# You may obtain a copy of the License at | |
| 6 | +# | |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 | +# | |
| 9 | +# Unless required by applicable law or agreed to in writing, software | |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 | +# See the License for the specific language governing permissions and | |
| 13 | +# limitations under the License. | |
| 14 | + | |
| 15 | +import os | |
| 16 | +from abc import abstractmethod | |
| 17 | +from dataclasses import dataclass | |
| 18 | +from typing import TYPE_CHECKING, Any, Optional, Union | |
| 19 | + | |
| 20 | +from ..framework import logging | |
| 21 | +from .template import Role | |
| 22 | + | |
| 23 | + | |
| 24 | +if TYPE_CHECKING: | |
| 25 | + from datasets import Dataset, IterableDataset | |
| 26 | + from transformers import Seq2SeqTrainingArguments | |
| 27 | + | |
| 28 | + from ..hparams import DataArguments | |
| 29 | + from .mm_plugin import PointCloudInput | |
| 30 | + from .loader import DatasetAttr | |
| 31 | + | |
| 32 | + MediaType = Union[PointCloudInput] | |
| 33 | + | |
| 34 | + | |
| 35 | +logger = logging.get_logger(__name__) | |
| 36 | + | |
| 37 | + | |
| 38 | +@dataclass | |
| 39 | +class DatasetConverter: | |
| 40 | + dataset_attr: "DatasetAttr" | |
| 41 | + data_args: "DataArguments" | |
| 42 | + | |
| 43 | + def _find_medias( | |
| 44 | + self, medias: Union["MediaType", list["MediaType"], None] | |
| 45 | + ) -> Optional[list["MediaType"]]: | |
| 46 | + r"""Optionally concatenate media path to media dir when loading from local disk.""" | |
| 47 | + if medias is None: | |
| 48 | + return None | |
| 49 | + elif not isinstance(medias, list): | |
| 50 | + medias = [medias] | |
| 51 | + elif len(medias) == 0: | |
| 52 | + return None | |
| 53 | + else: | |
| 54 | + medias = medias[:] | |
| 55 | + | |
| 56 | + if self.dataset_attr.load_from in ["file"]: | |
| 57 | + if isinstance(medias[0], str): | |
| 58 | + for i in range(len(medias)): | |
| 59 | + media_path = os.path.join(self.data_args.media_dir, medias[i]) | |
| 60 | + if os.path.isfile(media_path): | |
| 61 | + medias[i] = media_path | |
| 62 | + else: | |
| 63 | + logger.warning_rank0_once( | |
| 64 | + f"Media {medias[i]} does not exist in `media_dir`. Use original path." | |
| 65 | + ) | |
| 66 | + elif isinstance(medias[0], list): # for processed video frames | |
| 67 | + # medias is a list of lists, e.g., [[frame1.jpg, frame2.jpg], [frame3.jpg, frame4.jpg]] | |
| 68 | + for i in range(len(medias)): | |
| 69 | + for j in range(len(medias[i])): | |
| 70 | + media_path = os.path.join( | |
| 71 | + self.data_args.media_dir, medias[i][j] | |
| 72 | + ) | |
| 73 | + if os.path.isfile(media_path): | |
| 74 | + medias[i][j] = media_path | |
| 75 | + else: | |
| 76 | + logger.warning_rank0_once( | |
| 77 | + f"Media {medias[i][j]} does not exist in `media_dir`. Use original path." | |
| 78 | + ) | |
| 79 | + | |
| 80 | + return medias | |
| 81 | + | |
| 82 | + @abstractmethod | |
| 83 | + def __call__(self, example: dict[str, Any]) -> dict[str, Any]: | |
| 84 | + r"""Convert a single example in the dataset to the standard format.""" | |
| 85 | + ... | |
| 86 | + | |
| 87 | + | |
| 88 | +@dataclass | |
| 89 | +class AlpacaDatasetConverter(DatasetConverter): | |
| 90 | + def __call__(self, example: dict[str, Any]) -> dict[str, Any]: | |
| 91 | + prompt = [] | |
| 92 | + if self.dataset_attr.history and isinstance( | |
| 93 | + example[self.dataset_attr.history], list | |
| 94 | + ): | |
| 95 | + for old_prompt, old_response in example[self.dataset_attr.history]: | |
| 96 | + prompt.append({"role": Role.USER.value, "content": old_prompt}) | |
| 97 | + prompt.append({"role": Role.ASSISTANT.value, "content": old_response}) | |
| 98 | + | |
| 99 | + query = [] | |
| 100 | + if self.dataset_attr.prompt and example[self.dataset_attr.prompt]: | |
| 101 | + query.append(example[self.dataset_attr.prompt]) | |
| 102 | + | |
| 103 | + if self.dataset_attr.query and example[self.dataset_attr.query]: | |
| 104 | + query.append(example[self.dataset_attr.query]) | |
| 105 | + | |
| 106 | + prompt.append( | |
| 107 | + {"role": Role.USER.value, "content": "\n".join(query)} | |
| 108 | + ) # "prompt\nquery" | |
| 109 | + | |
| 110 | + if self.dataset_attr.response and isinstance( | |
| 111 | + example[self.dataset_attr.response], str | |
| 112 | + ): # normal example | |
| 113 | + response = [ | |
| 114 | + { | |
| 115 | + "role": Role.ASSISTANT.value, | |
| 116 | + "content": example[self.dataset_attr.response], | |
| 117 | + } | |
| 118 | + ] | |
| 119 | + else: # unsupervised | |
| 120 | + response = [] | |
| 121 | + | |
| 122 | + output = { | |
| 123 | + "_prompt": prompt, | |
| 124 | + "_response": response, | |
| 125 | + "_system": ( | |
| 126 | + example[self.dataset_attr.system] if self.dataset_attr.system else "" | |
| 127 | + ), | |
| 128 | + "_point_clouds": ( | |
| 129 | + self._find_medias(example[self.dataset_attr.point_clouds]) | |
| 130 | + if self.dataset_attr.point_clouds | |
| 131 | + else None | |
| 132 | + ), | |
| 133 | + } | |
| 134 | + return output | |
| 135 | + | |
| 136 | + | |
| 137 | +@dataclass | |
| 138 | +class SharegptDatasetConverter(DatasetConverter): | |
| 139 | + def __call__(self, example: dict[str, Any]) -> dict[str, Any]: | |
| 140 | + tag_mapping = { | |
| 141 | + self.dataset_attr.user_tag: Role.USER.value, | |
| 142 | + self.dataset_attr.assistant_tag: Role.ASSISTANT.value, | |
| 143 | + self.dataset_attr.system_tag: Role.SYSTEM.value, | |
| 144 | + } | |
| 145 | + odd_tags = (self.dataset_attr.user_tag,) | |
| 146 | + even_tags = (self.dataset_attr.assistant_tag,) | |
| 147 | + accept_tags = (odd_tags, even_tags) | |
| 148 | + messages = example[self.dataset_attr.messages] | |
| 149 | + if ( | |
| 150 | + self.dataset_attr.system_tag | |
| 151 | + and len(messages) != 0 | |
| 152 | + and messages[0][self.dataset_attr.role_tag] == self.dataset_attr.system_tag | |
| 153 | + ): | |
| 154 | + system = messages[0][self.dataset_attr.content_tag] | |
| 155 | + messages = messages[1:] | |
| 156 | + else: | |
| 157 | + system = ( | |
| 158 | + example[self.dataset_attr.system] if self.dataset_attr.system else "" | |
| 159 | + ) | |
| 160 | + | |
| 161 | + aligned_messages = [] | |
| 162 | + broken_data = False | |
| 163 | + for turn_idx, message in enumerate(messages): | |
| 164 | + if message[self.dataset_attr.role_tag] not in accept_tags[turn_idx % 2]: | |
| 165 | + logger.warning_rank0(f"Invalid role tag in {messages}.") | |
| 166 | + broken_data = True | |
| 167 | + break | |
| 168 | + | |
| 169 | + aligned_messages.append( | |
| 170 | + { | |
| 171 | + "role": tag_mapping[message[self.dataset_attr.role_tag]], | |
| 172 | + "content": message[self.dataset_attr.content_tag], | |
| 173 | + } | |
| 174 | + ) | |
| 175 | + | |
| 176 | + if len(aligned_messages) % 2 != 0: | |
| 177 | + logger.warning_rank0(f"Invalid message count in {messages}.") | |
| 178 | + broken_data = True | |
| 179 | + | |
| 180 | + if broken_data: | |
| 181 | + logger.warning_rank0("Skipping this abnormal example.") | |
| 182 | + prompt, response = [], [] | |
| 183 | + else: # normal example | |
| 184 | + prompt = aligned_messages[:-1] | |
| 185 | + response = aligned_messages[-1:] | |
| 186 | + | |
| 187 | + output = { | |
| 188 | + "_prompt": prompt, | |
| 189 | + "_response": response, | |
| 190 | + "_system": system, | |
| 191 | + "_point_clouds": ( | |
| 192 | + self._find_medias(example[self.dataset_attr.point_clouds]) | |
| 193 | + if self.dataset_attr.point_clouds | |
| 194 | + else None | |
| 195 | + ), | |
| 196 | + } | |
| 197 | + return output | |
| 198 | + | |
| 199 | + | |
| 200 | +DATASET_CONVERTERS = { | |
| 201 | + "alpaca": AlpacaDatasetConverter, | |
| 202 | + "sharegpt": SharegptDatasetConverter, | |
| 203 | +} | |
| 204 | + | |
| 205 | + | |
| 206 | +def register_dataset_converter( | |
| 207 | + name: str, dataset_converter: type["DatasetConverter"] | |
| 208 | +) -> None: | |
| 209 | + r"""Register a new dataset converter.""" | |
| 210 | + if name in DATASET_CONVERTERS: | |
| 211 | + raise ValueError(f"Dataset converter {name} already exists.") | |
| 212 | + | |
| 213 | + DATASET_CONVERTERS[name] = dataset_converter | |
| 214 | + | |
| 215 | + | |
| 216 | +def get_dataset_converter( | |
| 217 | + name: str, dataset_attr: "DatasetAttr", data_args: "DataArguments" | |
| 218 | +) -> "DatasetConverter": | |
| 219 | + r"""Get a dataset converter.""" | |
| 220 | + if name not in DATASET_CONVERTERS: | |
| 221 | + raise ValueError(f"Dataset converter {name} not found.") | |
| 222 | + | |
| 223 | + return DATASET_CONVERTERS[name](dataset_attr, data_args) | |
| 224 | + | |
| 225 | + | |
| 226 | +def align_dataset( | |
| 227 | + dataset: Union["Dataset", "IterableDataset"], | |
| 228 | + dataset_attr: "DatasetAttr", | |
| 229 | + data_args: "DataArguments", | |
| 230 | + training_args: "Seq2SeqTrainingArguments", | |
| 231 | +) -> Union["Dataset", "IterableDataset"]: | |
| 232 | + r"""Align the dataset to a specific format. | |
| 233 | + | |
| 234 | + Aligned dataset: | |
| 235 | + _prompt: [{"role": "user", "content": "..."}] * (2T - 1) | |
| 236 | + _response: [{"role": "assistant", "content": "..."}] * N | |
| 237 | + _system: "..." | |
| 238 | + _point_clouds: [] | |
| 239 | + """ | |
| 240 | + column_names = list(next(iter(dataset)).keys()) | |
| 241 | + kwargs = dict( | |
| 242 | + num_proc=data_args.preprocessing_num_workers, | |
| 243 | + load_from_cache_file=(not data_args.overwrite_cache) | |
| 244 | + or (training_args.local_process_index != 0), | |
| 245 | + desc="Converting format of dataset", | |
| 246 | + ) | |
| 247 | + | |
| 248 | + dataset_converter = get_dataset_converter( | |
| 249 | + dataset_attr.formatting, dataset_attr, data_args | |
| 250 | + ) | |
| 251 | + return dataset.map( | |
| 252 | + dataset_converter, | |
| 253 | + batched=False, | |
| 254 | + remove_columns=column_names, | |
| 255 | + **kwargs, | |
| 256 | + ) |
added spatiallm/tuner/data/formatter.py +66 −0
| @@ -0,0 +1,66 @@ | ||
| 1 | +import re | |
| 2 | +from abc import ABC, abstractmethod | |
| 3 | +from dataclasses import dataclass, field | |
| 4 | +from typing import Union | |
| 5 | + | |
| 6 | +from typing_extensions import override | |
| 7 | + | |
| 8 | +SLOTS = list[Union[str, set[str], dict[str, str]]] | |
| 9 | + | |
| 10 | + | |
| 11 | +@dataclass | |
| 12 | +class Formatter(ABC): | |
| 13 | + slots: SLOTS = field(default_factory=list) | |
| 14 | + | |
| 15 | + @abstractmethod | |
| 16 | + def apply(self, **kwargs) -> SLOTS: | |
| 17 | + r"""Forms a list of slots according to the inputs to encode.""" | |
| 18 | + ... | |
| 19 | + | |
| 20 | + | |
| 21 | +@dataclass | |
| 22 | +class EmptyFormatter(Formatter): | |
| 23 | + def __post_init__(self): | |
| 24 | + has_placeholder = False | |
| 25 | + for slot in filter(lambda s: isinstance(s, str), self.slots): | |
| 26 | + if re.search(r"\{\{[a-zA-Z_][a-zA-Z0-9_]*\}\}", slot): | |
| 27 | + has_placeholder = True | |
| 28 | + | |
| 29 | + if has_placeholder: | |
| 30 | + raise ValueError("Empty formatter should not contain any placeholder.") | |
| 31 | + | |
| 32 | + @override | |
| 33 | + def apply(self, **kwargs) -> SLOTS: | |
| 34 | + return self.slots | |
| 35 | + | |
| 36 | + | |
| 37 | +@dataclass | |
| 38 | +class StringFormatter(Formatter): | |
| 39 | + def __post_init__(self): | |
| 40 | + has_placeholder = False | |
| 41 | + for slot in filter(lambda s: isinstance(s, str), self.slots): | |
| 42 | + if re.search(r"\{\{[a-zA-Z_][a-zA-Z0-9_]*\}\}", slot): | |
| 43 | + has_placeholder = True | |
| 44 | + | |
| 45 | + if not has_placeholder: | |
| 46 | + raise ValueError("A placeholder is required in the string formatter.") | |
| 47 | + | |
| 48 | + @override | |
| 49 | + def apply(self, **kwargs) -> SLOTS: | |
| 50 | + elements = [] | |
| 51 | + for slot in self.slots: | |
| 52 | + if isinstance(slot, str): | |
| 53 | + for name, value in kwargs.items(): | |
| 54 | + if not isinstance(value, str): | |
| 55 | + raise RuntimeError(f"Expected a string, got {value}") | |
| 56 | + | |
| 57 | + slot = slot.replace("{{" + name + "}}", value, 1) | |
| 58 | + elements.append(slot) | |
| 59 | + elif isinstance(slot, (dict, set)): | |
| 60 | + elements.append(slot) | |
| 61 | + else: | |
| 62 | + raise RuntimeError( | |
| 63 | + f"Input must be string, set[str] or dict[str, str], got {type(slot)}." | |
| 64 | + ) | |
| 65 | + | |
| 66 | + return elements |
added spatiallm/tuner/data/loader.py +461 −0
| @@ -0,0 +1,461 @@ | ||
| 1 | +import os | |
| 2 | +import sys | |
| 3 | +import json | |
| 4 | +from dataclasses import dataclass | |
| 5 | +from typing import TYPE_CHECKING, Any, Literal, Optional, TypedDict, Union | |
| 6 | + | |
| 7 | +import numpy as np | |
| 8 | +from datasets import ( | |
| 9 | + Dataset, | |
| 10 | + DatasetDict, | |
| 11 | + load_dataset, | |
| 12 | + load_from_disk, | |
| 13 | + concatenate_datasets, | |
| 14 | +) | |
| 15 | +from huggingface_hub import hf_hub_download | |
| 16 | + | |
| 17 | +from ..framework import logging | |
| 18 | +from ..framework.loader import use_modelscope | |
| 19 | +from ..framework.utils import check_version | |
| 20 | +from .converter import align_dataset | |
| 21 | + | |
| 22 | +if TYPE_CHECKING: | |
| 23 | + from datasets import IterableDataset | |
| 24 | + from transformers import Seq2SeqTrainingArguments | |
| 25 | + | |
| 26 | + from ..hparams import DataArguments, ModelArguments | |
| 27 | + | |
| 28 | + | |
| 29 | +logger = logging.get_logger(__name__) | |
| 30 | + | |
| 31 | +DATA_CONFIG = "dataset_info.json" | |
| 32 | +FILEEXT2TYPE = { | |
| 33 | + "arrow": "arrow", | |
| 34 | + "csv": "csv", | |
| 35 | + "json": "json", | |
| 36 | + "jsonl": "json", | |
| 37 | + "parquet": "parquet", | |
| 38 | + "txt": "text", | |
| 39 | +} | |
| 40 | + | |
| 41 | + | |
| 42 | +class DatasetModule(TypedDict): | |
| 43 | + train_dataset: Optional[Union["Dataset", "IterableDataset"]] | |
| 44 | + eval_dataset: Optional[Union["Dataset", "IterableDataset", dict[str, "Dataset"]]] | |
| 45 | + | |
| 46 | + | |
| 47 | +@dataclass | |
| 48 | +class DatasetAttr: | |
| 49 | + r"""Dataset attributes.""" | |
| 50 | + | |
| 51 | + # basic configs | |
| 52 | + load_from: Literal["hf_hub", "ms_hub", "file"] | |
| 53 | + dataset_name: str | |
| 54 | + formatting: Literal["alpaca", "sharegpt"] = "alpaca" | |
| 55 | + # extra configs | |
| 56 | + subset: Optional[str] = None | |
| 57 | + split: str = "train" | |
| 58 | + folder: Optional[str] = None | |
| 59 | + num_samples: Optional[int] = None | |
| 60 | + # common columns | |
| 61 | + system: Optional[str] = None | |
| 62 | + point_clouds: Optional[str] = None | |
| 63 | + # alpaca columns | |
| 64 | + prompt: Optional[str] = "instruction" | |
| 65 | + query: Optional[str] = "input" | |
| 66 | + response: Optional[str] = "output" | |
| 67 | + history: Optional[str] = None | |
| 68 | + # sharegpt columns | |
| 69 | + messages: Optional[str] = "conversations" | |
| 70 | + # sharegpt tags | |
| 71 | + role_tag: Optional[str] = "from" | |
| 72 | + content_tag: Optional[str] = "value" | |
| 73 | + user_tag: Optional[str] = "human" | |
| 74 | + assistant_tag: Optional[str] = "gpt" | |
| 75 | + system_tag: Optional[str] = "system" | |
| 76 | + | |
| 77 | + def __repr__(self) -> str: | |
| 78 | + return self.dataset_name | |
| 79 | + | |
| 80 | + def set_attr( | |
| 81 | + self, key: str, obj: dict[str, Any], default: Optional[Any] = None | |
| 82 | + ) -> None: | |
| 83 | + setattr(self, key, obj.get(key, default)) | |
| 84 | + | |
| 85 | + def join(self, attr: dict[str, Any]) -> None: | |
| 86 | + self.set_attr("formatting", attr, default="alpaca") | |
| 87 | + self.set_attr("subset", attr) | |
| 88 | + self.set_attr("split", attr, default="train") | |
| 89 | + self.set_attr("folder", attr) | |
| 90 | + self.set_attr("num_samples", attr) | |
| 91 | + | |
| 92 | + if "columns" in attr: | |
| 93 | + column_names = [ | |
| 94 | + "prompt", | |
| 95 | + "query", | |
| 96 | + "response", | |
| 97 | + "history", | |
| 98 | + "messages", | |
| 99 | + "system", | |
| 100 | + "point_clouds", | |
| 101 | + ] | |
| 102 | + for column_name in column_names: | |
| 103 | + self.set_attr(column_name, attr["columns"]) | |
| 104 | + | |
| 105 | + if "tags" in attr: | |
| 106 | + tag_names = ["role_tag", "content_tag"] | |
| 107 | + tag_names += ["user_tag", "assistant_tag", "system_tag"] | |
| 108 | + for tag in tag_names: | |
| 109 | + self.set_attr(tag, attr["tags"]) | |
| 110 | + | |
| 111 | + | |
| 112 | +def has_preprocessed_data(path: "os.PathLike") -> bool: | |
| 113 | + r"""Check if the path has a preprocessed dataset.""" | |
| 114 | + return os.path.isdir(path) and len(os.listdir(path)) > 0 | |
| 115 | + | |
| 116 | + | |
| 117 | +def get_dataset_module(dataset: Union["Dataset", "DatasetDict"]) -> "DatasetModule": | |
| 118 | + r"""Convert dataset or dataset dict to dataset module.""" | |
| 119 | + dataset_module: DatasetModule = {} | |
| 120 | + if isinstance(dataset, DatasetDict): # dataset dict | |
| 121 | + if "train" in dataset: | |
| 122 | + dataset_module["train_dataset"] = dataset["train"] | |
| 123 | + | |
| 124 | + if "validation" in dataset: | |
| 125 | + dataset_module["eval_dataset"] = dataset["validation"] | |
| 126 | + else: | |
| 127 | + eval_dataset = {} | |
| 128 | + for key in dataset.keys(): | |
| 129 | + if key.startswith("validation_"): | |
| 130 | + eval_dataset[key[len("validation_") :]] = dataset[key] | |
| 131 | + | |
| 132 | + if len(eval_dataset): | |
| 133 | + dataset_module["eval_dataset"] = eval_dataset | |
| 134 | + | |
| 135 | + else: # single dataset | |
| 136 | + dataset_module["train_dataset"] = dataset | |
| 137 | + | |
| 138 | + return dataset_module | |
| 139 | + | |
| 140 | + | |
| 141 | +def split_dataset( | |
| 142 | + dataset: Optional[Union["Dataset", "IterableDataset"]], | |
| 143 | + eval_dataset: Optional[Union["Dataset", "IterableDataset", dict[str, "Dataset"]]], | |
| 144 | + data_args: "DataArguments", | |
| 145 | + seed: int, | |
| 146 | +) -> "DatasetDict": | |
| 147 | + r"""Split the dataset and returns a dataset dict containing train set and validation set. | |
| 148 | + | |
| 149 | + Support both map dataset and iterable dataset. | |
| 150 | + """ | |
| 151 | + if eval_dataset is not None and data_args.val_size > 1e-6: | |
| 152 | + raise ValueError("Cannot specify `val_size` if `eval_dataset` is not None.") | |
| 153 | + | |
| 154 | + dataset_dict = {} | |
| 155 | + if dataset is not None: | |
| 156 | + if data_args.val_size > 1e-6: | |
| 157 | + | |
| 158 | + val_size = ( | |
| 159 | + int(data_args.val_size) | |
| 160 | + if data_args.val_size > 1 | |
| 161 | + else data_args.val_size | |
| 162 | + ) | |
| 163 | + dataset = dataset.train_test_split(test_size=val_size, seed=seed) | |
| 164 | + dataset_dict = { | |
| 165 | + "train": dataset["train"], | |
| 166 | + "validation": dataset["test"], | |
| 167 | + } | |
| 168 | + else: | |
| 169 | + dataset_dict["train"] = dataset | |
| 170 | + | |
| 171 | + if eval_dataset is not None: | |
| 172 | + if isinstance(eval_dataset, dict): | |
| 173 | + dataset_dict.update( | |
| 174 | + {f"validation_{name}": data for name, data in eval_dataset.items()} | |
| 175 | + ) | |
| 176 | + else: | |
| 177 | + dataset_dict["validation"] = eval_dataset | |
| 178 | + | |
| 179 | + return DatasetDict(dataset_dict) | |
| 180 | + | |
| 181 | + | |
| 182 | +def get_dataset_list( | |
| 183 | + dataset_names: Optional[list[str]], dataset_dir: str | |
| 184 | +) -> list["DatasetAttr"]: | |
| 185 | + r"""Get the attributes of the datasets.""" | |
| 186 | + if dataset_names is None: | |
| 187 | + dataset_names = [] | |
| 188 | + | |
| 189 | + if dataset_dir == "ONLINE": | |
| 190 | + dataset_info = None | |
| 191 | + else: | |
| 192 | + if dataset_dir.startswith("REMOTE:"): | |
| 193 | + config_path = hf_hub_download( | |
| 194 | + repo_id=dataset_dir[7:], filename=DATA_CONFIG, repo_type="dataset" | |
| 195 | + ) | |
| 196 | + else: | |
| 197 | + config_path = os.path.join(dataset_dir, DATA_CONFIG) | |
| 198 | + | |
| 199 | + try: | |
| 200 | + with open(config_path) as f: | |
| 201 | + dataset_info = json.load(f) | |
| 202 | + except Exception as err: | |
| 203 | + if len(dataset_names) != 0: | |
| 204 | + raise ValueError(f"Cannot open {config_path} due to {str(err)}.") | |
| 205 | + | |
| 206 | + dataset_info = None | |
| 207 | + | |
| 208 | + dataset_list: list[DatasetAttr] = [] | |
| 209 | + for name in dataset_names: | |
| 210 | + if dataset_info is None: # dataset_dir is ONLINE | |
| 211 | + load_from = "ms_hub" if use_modelscope() else "hf_hub" | |
| 212 | + dataset_attr = DatasetAttr(load_from, dataset_name=name) | |
| 213 | + dataset_list.append(dataset_attr) | |
| 214 | + continue | |
| 215 | + | |
| 216 | + if name not in dataset_info: | |
| 217 | + raise ValueError(f"Undefined dataset {name} in {DATA_CONFIG}.") | |
| 218 | + | |
| 219 | + has_hf_url = "hf_hub_url" in dataset_info[name] | |
| 220 | + has_ms_url = "ms_hub_url" in dataset_info[name] | |
| 221 | + | |
| 222 | + if has_hf_url or has_ms_url: | |
| 223 | + if has_ms_url and (use_modelscope() or not has_hf_url): | |
| 224 | + dataset_attr = DatasetAttr( | |
| 225 | + "ms_hub", dataset_name=dataset_info[name]["ms_hub_url"] | |
| 226 | + ) | |
| 227 | + else: | |
| 228 | + dataset_attr = DatasetAttr( | |
| 229 | + "hf_hub", dataset_name=dataset_info[name]["hf_hub_url"] | |
| 230 | + ) | |
| 231 | + else: | |
| 232 | + dataset_attr = DatasetAttr( | |
| 233 | + "file", dataset_name=dataset_info[name]["file_name"] | |
| 234 | + ) | |
| 235 | + | |
| 236 | + dataset_attr.join(dataset_info[name]) | |
| 237 | + dataset_list.append(dataset_attr) | |
| 238 | + | |
| 239 | + return dataset_list | |
| 240 | + | |
| 241 | + | |
| 242 | +def _load_single_dataset( | |
| 243 | + dataset_attr: "DatasetAttr", | |
| 244 | + model_args: "ModelArguments", | |
| 245 | + data_args: "DataArguments", | |
| 246 | + training_args: "Seq2SeqTrainingArguments", | |
| 247 | +) -> Union["Dataset", "IterableDataset"]: | |
| 248 | + r"""Load a single dataset and aligns it to the standard format.""" | |
| 249 | + logger.info_rank0(f"Loading dataset {dataset_attr}...") | |
| 250 | + data_path, data_name, data_dir, data_files = None, None, None, None | |
| 251 | + if dataset_attr.load_from in ["hf_hub", "ms_hub"]: | |
| 252 | + data_path = dataset_attr.dataset_name | |
| 253 | + data_name = dataset_attr.subset | |
| 254 | + data_dir = dataset_attr.folder | |
| 255 | + | |
| 256 | + elif dataset_attr.load_from == "file": | |
| 257 | + data_files = [] | |
| 258 | + local_path = os.path.join(data_args.dataset_dir, dataset_attr.dataset_name) | |
| 259 | + if os.path.isdir(local_path): # is directory | |
| 260 | + for file_name in os.listdir(local_path): | |
| 261 | + data_files.append(os.path.join(local_path, file_name)) | |
| 262 | + elif os.path.isfile(local_path): # is file | |
| 263 | + data_files.append(local_path) | |
| 264 | + else: | |
| 265 | + raise ValueError(f"File {local_path} not found.") | |
| 266 | + | |
| 267 | + data_path = FILEEXT2TYPE.get(os.path.splitext(data_files[0])[-1][1:], None) | |
| 268 | + if data_path is None: | |
| 269 | + raise ValueError( | |
| 270 | + "Allowed file types: {}.".format(",".join(FILEEXT2TYPE.keys())) | |
| 271 | + ) | |
| 272 | + | |
| 273 | + if any( | |
| 274 | + data_path != FILEEXT2TYPE.get(os.path.splitext(data_file)[-1][1:], None) | |
| 275 | + for data_file in data_files | |
| 276 | + ): | |
| 277 | + raise ValueError("File types should be identical.") | |
| 278 | + else: | |
| 279 | + raise NotImplementedError(f"Unknown load type: {dataset_attr.load_from}.") | |
| 280 | + | |
| 281 | + if dataset_attr.load_from == "ms_hub": | |
| 282 | + check_version("modelscope>=1.11.0", mandatory=True) | |
| 283 | + from modelscope import MsDataset # type: ignore | |
| 284 | + from modelscope.utils.config_ds import MS_DATASETS_CACHE # type: ignore | |
| 285 | + | |
| 286 | + cache_dir = model_args.cache_dir or MS_DATASETS_CACHE | |
| 287 | + dataset = MsDataset.load( | |
| 288 | + dataset_name=data_path, | |
| 289 | + subset_name=data_name, | |
| 290 | + data_dir=data_dir, | |
| 291 | + data_files=data_files, | |
| 292 | + split=dataset_attr.split, | |
| 293 | + cache_dir=cache_dir, | |
| 294 | + token=model_args.ms_hub_token, | |
| 295 | + use_streaming=data_args.streaming, | |
| 296 | + ) | |
| 297 | + if isinstance(dataset, MsDataset): | |
| 298 | + dataset = dataset.to_hf_dataset() | |
| 299 | + else: | |
| 300 | + dataset = load_dataset( | |
| 301 | + path=data_path, | |
| 302 | + name=data_name, | |
| 303 | + data_dir=data_dir, | |
| 304 | + data_files=data_files, | |
| 305 | + split=dataset_attr.split, | |
| 306 | + cache_dir=model_args.cache_dir, | |
| 307 | + token=model_args.hf_hub_token, | |
| 308 | + num_proc=data_args.preprocessing_num_workers, | |
| 309 | + trust_remote_code=model_args.trust_remote_code, | |
| 310 | + ) | |
| 311 | + | |
| 312 | + if dataset_attr.num_samples is not None: | |
| 313 | + target_num = dataset_attr.num_samples | |
| 314 | + indexes = np.random.permutation(len(dataset))[ | |
| 315 | + :target_num | |
| 316 | + ] # all samples should be included | |
| 317 | + target_num -= len(indexes) | |
| 318 | + if target_num > 0: | |
| 319 | + expand_indexes = np.random.choice(len(dataset), target_num) | |
| 320 | + indexes = np.concatenate((indexes, expand_indexes), axis=0) | |
| 321 | + | |
| 322 | + assert len(indexes) == dataset_attr.num_samples, "Sample num mismatched." | |
| 323 | + dataset = dataset.select(indexes) | |
| 324 | + logger.info_rank0( | |
| 325 | + f"Sampled {dataset_attr.num_samples} examples from dataset {dataset_attr}." | |
| 326 | + ) | |
| 327 | + | |
| 328 | + if data_args.max_samples is not None: # truncate dataset | |
| 329 | + max_samples = min(data_args.max_samples, len(dataset)) | |
| 330 | + dataset = dataset.select(range(max_samples)) | |
| 331 | + | |
| 332 | + return align_dataset(dataset, dataset_attr, data_args, training_args) | |
| 333 | + | |
| 334 | + | |
| 335 | +def merge_dataset( | |
| 336 | + all_datasets: list[Union["Dataset", "IterableDataset"]], | |
| 337 | + data_args: "DataArguments", | |
| 338 | +) -> Union["Dataset", "IterableDataset"]: | |
| 339 | + r"""Merge multiple datasets to a unified dataset.""" | |
| 340 | + if len(all_datasets) == 1: | |
| 341 | + return all_datasets[0] | |
| 342 | + | |
| 343 | + return concatenate_datasets(all_datasets) | |
| 344 | + | |
| 345 | + | |
| 346 | +def _get_merged_dataset( | |
| 347 | + dataset_names: Optional[list[str]], | |
| 348 | + model_args: "ModelArguments", | |
| 349 | + data_args: "DataArguments", | |
| 350 | + training_args: "Seq2SeqTrainingArguments", | |
| 351 | + return_dict: bool = False, | |
| 352 | +) -> Optional[Union["Dataset", "IterableDataset", dict[str, "Dataset"]]]: | |
| 353 | + r"""Return the merged datasets in the standard format.""" | |
| 354 | + if dataset_names is None: | |
| 355 | + return None | |
| 356 | + | |
| 357 | + datasets = {} | |
| 358 | + for dataset_name, dataset_attr in zip( | |
| 359 | + dataset_names, get_dataset_list(dataset_names, data_args.dataset_dir) | |
| 360 | + ): | |
| 361 | + datasets[dataset_name] = _load_single_dataset( | |
| 362 | + dataset_attr, model_args, data_args, training_args | |
| 363 | + ) | |
| 364 | + | |
| 365 | + if return_dict: | |
| 366 | + return datasets | |
| 367 | + else: | |
| 368 | + return merge_dataset(list(datasets.values()), data_args) | |
| 369 | + | |
| 370 | + | |
| 371 | +def _get_unprocessed_dataset( | |
| 372 | + dataset: Optional[Union["Dataset", "IterableDataset"]], | |
| 373 | + training_args: "Seq2SeqTrainingArguments", | |
| 374 | + is_eval: bool = False, | |
| 375 | +) -> Optional[Union["Dataset", "IterableDataset"]]: | |
| 376 | + r"""Preprocesses the dataset, including format checking and tokenization.""" | |
| 377 | + if dataset is None: | |
| 378 | + return None | |
| 379 | + | |
| 380 | + if training_args.should_log: | |
| 381 | + try: | |
| 382 | + print("eval example:" if is_eval else "training example:") | |
| 383 | + print(next(iter(dataset))) | |
| 384 | + except StopIteration: | |
| 385 | + raise RuntimeError( | |
| 386 | + "Cannot find valid samples, check `data/README.md` for the data format." | |
| 387 | + ) | |
| 388 | + | |
| 389 | + return dataset | |
| 390 | + | |
| 391 | + | |
| 392 | +def get_dataset( | |
| 393 | + model_args: "ModelArguments", | |
| 394 | + data_args: "DataArguments", | |
| 395 | + training_args: "Seq2SeqTrainingArguments", | |
| 396 | +) -> "DatasetModule": | |
| 397 | + r"""Get the train dataset and optionally gets the evaluation dataset.""" | |
| 398 | + # Load preprocessed dataset if path exists | |
| 399 | + if data_args.save_dir is not None: | |
| 400 | + if has_preprocessed_data(data_args.save_dir): | |
| 401 | + logger.warning_rank0( | |
| 402 | + "Loading dataset from disk will ignore other data arguments." | |
| 403 | + ) | |
| 404 | + preprocessed_data = load_from_disk(data_args.save_dir) | |
| 405 | + dataset_module = get_dataset_module(preprocessed_data) | |
| 406 | + | |
| 407 | + logger.info_rank0(f"Loaded preprocessed dataset from {data_args.save_dir}.") | |
| 408 | + return dataset_module | |
| 409 | + | |
| 410 | + # Load and preprocess dataset | |
| 411 | + with training_args.main_process_first( | |
| 412 | + desc="load dataset", local=(not data_args.data_shared_file_system) | |
| 413 | + ): | |
| 414 | + dataset = _get_merged_dataset( | |
| 415 | + data_args.dataset, model_args, data_args, training_args | |
| 416 | + ) | |
| 417 | + eval_dataset = _get_merged_dataset( | |
| 418 | + data_args.eval_dataset, | |
| 419 | + model_args, | |
| 420 | + data_args, | |
| 421 | + training_args, | |
| 422 | + return_dict=data_args.eval_on_each_dataset, | |
| 423 | + ) | |
| 424 | + | |
| 425 | + with training_args.main_process_first( | |
| 426 | + desc="pre-process dataset", local=(not data_args.data_shared_file_system) | |
| 427 | + ): | |
| 428 | + dataset = _get_unprocessed_dataset( | |
| 429 | + dataset, | |
| 430 | + training_args, | |
| 431 | + is_eval=False, | |
| 432 | + ) | |
| 433 | + if isinstance(eval_dataset, dict): | |
| 434 | + for eval_name, eval_data in eval_dataset.items(): | |
| 435 | + eval_dataset[eval_name] = _get_unprocessed_dataset( | |
| 436 | + eval_data, | |
| 437 | + training_args, | |
| 438 | + is_eval=True, | |
| 439 | + ) | |
| 440 | + else: | |
| 441 | + eval_dataset = _get_unprocessed_dataset( | |
| 442 | + eval_dataset, | |
| 443 | + training_args, | |
| 444 | + is_eval=True, | |
| 445 | + ) | |
| 446 | + | |
| 447 | + dataset_dict = split_dataset( | |
| 448 | + dataset, eval_dataset, data_args, seed=training_args.seed | |
| 449 | + ) | |
| 450 | + if data_args.save_dir is not None: # save preprocessed dataset to disk | |
| 451 | + if training_args.should_save: | |
| 452 | + dataset_dict.save_to_disk(data_args.save_dir) | |
| 453 | + logger.info_rank0( | |
| 454 | + f"Preprocessed dataset is saved at {data_args.save_dir}." | |
| 455 | + ) | |
| 456 | + logger.info_rank0( | |
| 457 | + f"Please launch the training with `save_dir: {data_args.save_dir}`." | |
| 458 | + ) | |
| 459 | + sys.exit(0) | |
| 460 | + | |
| 461 | + return get_dataset_module(dataset_dict) |
added spatiallm/tuner/data/mm_plugin.py +279 −0
| @@ -0,0 +1,279 @@ | ||
| 1 | +import os | |
| 2 | +from copy import deepcopy | |
| 3 | +from typing import TYPE_CHECKING, Dict, List, Union, Sequence, Optional, Tuple | |
| 4 | + | |
| 5 | +import torch | |
| 6 | +import numpy as np | |
| 7 | +from scipy.spatial.transform import Rotation as R | |
| 8 | + | |
| 9 | +from spatiallm.layout.layout import Layout | |
| 10 | +from spatiallm.layout.entity import NORMALIZATION_PRESET | |
| 11 | +from spatiallm.pcd import load_o3d_pcd, get_points_and_colors | |
| 12 | +from spatiallm.pcd.transform import Compose | |
| 13 | + | |
| 14 | +if TYPE_CHECKING: | |
| 15 | + from numpy.typing import NDArray | |
| 16 | + from transformers import PreTrainedTokenizer | |
| 17 | + | |
| 18 | + PointCloudInput = Union[str, dict, NDArray] | |
| 19 | + | |
| 20 | +LAYOUT_S_PLACEHOLDER = os.environ.get("LAYOUT_S_PLACEHOLDER", "<|layout_s|>") | |
| 21 | +LAYOUT_E_PLACEHOLDER = os.environ.get("LAYOUT_E_PLACEHOLDER", "<|layout_e|>") | |
| 22 | +POINT_S_TOKEN = os.environ.get("POINT_S_TOKEN", "<|point_start|>") | |
| 23 | +POINT_E_TOKEN = os.environ.get("POINT_E_TOKEN", "<|point_end|>") | |
| 24 | +POINT_CLOUD_PLACEHOLDER = os.environ.get("POINT_CLOUD_PLACEHOLDER", "<point_cloud>") | |
| 25 | + | |
| 26 | + | |
| 27 | +class 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 | + | |
| 275 | +def get_mm_plugin( | |
| 276 | + point_token: str = "<|point_pad|>", | |
| 277 | + **kwargs, | |
| 278 | +) -> "SpatialLMPlugin": | |
| 279 | + return SpatialLMPlugin(point_token, **kwargs) |
added spatiallm/tuner/data/template.py +365 −0
| @@ -0,0 +1,365 @@ | ||
| 1 | +from enum import Enum, unique | |
| 2 | +from dataclasses import dataclass | |
| 3 | +from typing import TYPE_CHECKING, Optional | |
| 4 | + | |
| 5 | +from ..framework import logging | |
| 6 | +from .formatter import EmptyFormatter, StringFormatter | |
| 7 | +from .mm_plugin import get_mm_plugin | |
| 8 | + | |
| 9 | +if TYPE_CHECKING: | |
| 10 | + from transformers import PreTrainedTokenizer | |
| 11 | + | |
| 12 | + from ..hparams import DataArguments | |
| 13 | + from .formatter import SLOTS, Formatter | |
| 14 | + from .mm_plugin import SpatialLMPlugin | |
| 15 | + | |
| 16 | + | |
| 17 | +logger = logging.get_logger(__name__) | |
| 18 | + | |
| 19 | + | |
| 20 | +IGNORE_INDEX = -100 | |
| 21 | + | |
| 22 | + | |
| 23 | +@unique | |
| 24 | +class Role(str, Enum): | |
| 25 | + USER = "user" | |
| 26 | + ASSISTANT = "assistant" | |
| 27 | + SYSTEM = "system" | |
| 28 | + | |
| 29 | + | |
| 30 | +@dataclass | |
| 31 | +class Template: | |
| 32 | + format_user: "Formatter" | |
| 33 | + format_assistant: "Formatter" | |
| 34 | + format_system: "Formatter" | |
| 35 | + format_prefix: "Formatter" | |
| 36 | + default_system: str | |
| 37 | + stop_words: list[str] | |
| 38 | + replace_eos: bool | |
| 39 | + mm_plugin: "SpatialLMPlugin" | |
| 40 | + cutoff_len: int | |
| 41 | + | |
| 42 | + def encode_oneturn( | |
| 43 | + self, | |
| 44 | + tokenizer: "PreTrainedTokenizer", | |
| 45 | + messages: list[dict[str, str]], | |
| 46 | + system: Optional[str] = None, | |
| 47 | + ) -> tuple[list[int], list[int]]: | |
| 48 | + r"""Return a single pair of token ids representing prompt and response respectively.""" | |
| 49 | + encoded_messages = self._encode(tokenizer, messages, system) | |
| 50 | + prompt_ids = [] | |
| 51 | + for encoded_ids in encoded_messages[:-1]: | |
| 52 | + prompt_ids += encoded_ids | |
| 53 | + | |
| 54 | + response_ids = encoded_messages[-1] | |
| 55 | + return prompt_ids, response_ids | |
| 56 | + | |
| 57 | + def encode_multiturn( | |
| 58 | + self, | |
| 59 | + tokenizer: "PreTrainedTokenizer", | |
| 60 | + messages: list[dict[str, str]], | |
| 61 | + system: Optional[str] = None, | |
| 62 | + ) -> list[tuple[list[int], list[int]]]: | |
| 63 | + r"""Return multiple pairs of token ids representing prompts and responses respectively.""" | |
| 64 | + encoded_messages = self._encode(tokenizer, messages, system) | |
| 65 | + return [ | |
| 66 | + (encoded_messages[i], encoded_messages[i + 1]) | |
| 67 | + for i in range(0, len(encoded_messages), 2) | |
| 68 | + ] | |
| 69 | + | |
| 70 | + def _convert_elements_to_ids( | |
| 71 | + self, tokenizer: "PreTrainedTokenizer", elements: "SLOTS" | |
| 72 | + ) -> list[int]: | |
| 73 | + r"""Convert elements to token ids.""" | |
| 74 | + token_ids = [] | |
| 75 | + for elem in elements: | |
| 76 | + if isinstance(elem, str): | |
| 77 | + if len(elem) != 0: | |
| 78 | + token_ids += tokenizer.encode(elem, add_special_tokens=False) | |
| 79 | + elif isinstance(elem, dict): | |
| 80 | + token_ids += [tokenizer.convert_tokens_to_ids(elem.get("token"))] | |
| 81 | + elif isinstance(elem, set): | |
| 82 | + if "bos_token" in elem and tokenizer.bos_token_id is not None: | |
| 83 | + token_ids += [tokenizer.bos_token_id] | |
| 84 | + elif "eos_token" in elem and tokenizer.eos_token_id is not None: | |
| 85 | + token_ids += [tokenizer.eos_token_id] | |
| 86 | + else: | |
| 87 | + raise ValueError( | |
| 88 | + f"Input must be string, set[str] or dict[str, str], got {type(elem)}" | |
| 89 | + ) | |
| 90 | + | |
| 91 | + return token_ids | |
| 92 | + | |
| 93 | + def _encode( | |
| 94 | + self, | |
| 95 | + tokenizer: "PreTrainedTokenizer", | |
| 96 | + messages: list[dict[str, str]], | |
| 97 | + system: Optional[str], | |
| 98 | + ) -> list[list[int]]: | |
| 99 | + r"""Encode formatted inputs to pairs of token ids. | |
| 100 | + | |
| 101 | + Turn 0: prefix + system + query resp | |
| 102 | + Turn t: query resp. | |
| 103 | + """ | |
| 104 | + system = system or self.default_system | |
| 105 | + encoded_messages = [] | |
| 106 | + for i, message in enumerate(messages): | |
| 107 | + elements = [] | |
| 108 | + | |
| 109 | + if i == 0: | |
| 110 | + elements += self.format_prefix.apply() | |
| 111 | + if system: | |
| 112 | + elements += self.format_system.apply(content=system) | |
| 113 | + | |
| 114 | + if message["role"] == Role.USER: | |
| 115 | + elements += self.format_user.apply( | |
| 116 | + content=message["content"], idx=str(i // 2) | |
| 117 | + ) | |
| 118 | + elif message["role"] == Role.ASSISTANT: | |
| 119 | + elements += self.format_assistant.apply(content=message["content"]) | |
| 120 | + else: | |
| 121 | + raise NotImplementedError("Unexpected role: {}".format(message["role"])) | |
| 122 | + | |
| 123 | + encoded_messages.append(self._convert_elements_to_ids(tokenizer, elements)) | |
| 124 | + | |
| 125 | + return encoded_messages | |
| 126 | + | |
| 127 | + @staticmethod | |
| 128 | + def _add_or_replace_eos_token( | |
| 129 | + tokenizer: "PreTrainedTokenizer", eos_token: str | |
| 130 | + ) -> None: | |
| 131 | + r"""Add or replace eos token to the tokenizer.""" | |
| 132 | + if tokenizer.eos_token == eos_token: | |
| 133 | + return | |
| 134 | + | |
| 135 | + is_added = tokenizer.eos_token_id is None | |
| 136 | + num_added_tokens = tokenizer.add_special_tokens({"eos_token": eos_token}) | |
| 137 | + | |
| 138 | + if is_added: | |
| 139 | + logger.info_rank0(f"Add eos token: {tokenizer.eos_token}.") | |
| 140 | + else: | |
| 141 | + logger.info_rank0(f"Replace eos token: {tokenizer.eos_token}.") | |
| 142 | + | |
| 143 | + if num_added_tokens > 0: | |
| 144 | + logger.warning_rank0( | |
| 145 | + "New tokens have been added, make sure `resize_vocab` is True." | |
| 146 | + ) | |
| 147 | + | |
| 148 | + def fix_special_tokens(self, tokenizer: "PreTrainedTokenizer") -> None: | |
| 149 | + r"""Add eos token and pad token to the tokenizer.""" | |
| 150 | + stop_words = self.stop_words | |
| 151 | + if self.replace_eos: | |
| 152 | + if not stop_words: | |
| 153 | + raise ValueError("Stop words are required to replace the EOS token.") | |
| 154 | + | |
| 155 | + self._add_or_replace_eos_token(tokenizer, eos_token=stop_words[0]) | |
| 156 | + stop_words = stop_words[1:] | |
| 157 | + | |
| 158 | + if tokenizer.eos_token_id is None: | |
| 159 | + self._add_or_replace_eos_token(tokenizer, eos_token="<|endoftext|>") | |
| 160 | + | |
| 161 | + if tokenizer.pad_token_id is None: | |
| 162 | + tokenizer.pad_token = tokenizer.eos_token | |
| 163 | + logger.info_rank0(f"Add pad token: {tokenizer.pad_token}") | |
| 164 | + | |
| 165 | + if stop_words: | |
| 166 | + num_added_tokens = tokenizer.add_special_tokens( | |
| 167 | + dict(additional_special_tokens=stop_words), | |
| 168 | + replace_additional_special_tokens=False, | |
| 169 | + ) | |
| 170 | + logger.info_rank0("Add {} to stop words.".format(",".join(stop_words))) | |
| 171 | + if num_added_tokens > 0: | |
| 172 | + logger.warning_rank0( | |
| 173 | + "New tokens have been added, make sure `resize_vocab` is True." | |
| 174 | + ) | |
| 175 | + | |
| 176 | + @staticmethod | |
| 177 | + def _jinja_escape(content: str) -> str: | |
| 178 | + r"""Escape single quotes in content.""" | |
| 179 | + return content.replace("'", r"\'") | |
| 180 | + | |
| 181 | + @staticmethod | |
| 182 | + def _convert_slots_to_jinja( | |
| 183 | + slots: "SLOTS", tokenizer: "PreTrainedTokenizer", placeholder: str = "content" | |
| 184 | + ) -> str: | |
| 185 | + r"""Convert slots to jinja template.""" | |
| 186 | + slot_items = [] | |
| 187 | + for slot in slots: | |
| 188 | + if isinstance(slot, str): | |
| 189 | + slot_pieces = slot.split("{{content}}") | |
| 190 | + if slot_pieces[0]: | |
| 191 | + slot_items.append( | |
| 192 | + "'" + Template._jinja_escape(slot_pieces[0]) + "'" | |
| 193 | + ) | |
| 194 | + if len(slot_pieces) > 1: | |
| 195 | + slot_items.append(placeholder) | |
| 196 | + if slot_pieces[1]: | |
| 197 | + slot_items.append( | |
| 198 | + "'" + Template._jinja_escape(slot_pieces[1]) + "'" | |
| 199 | + ) | |
| 200 | + elif isinstance( | |
| 201 | + slot, set | |
| 202 | + ): # do not use {{ eos_token }} since it may be replaced | |
| 203 | + if "bos_token" in slot and tokenizer.bos_token_id is not None: | |
| 204 | + slot_items.append("'" + tokenizer.bos_token + "'") | |
| 205 | + elif "eos_token" in slot and tokenizer.eos_token_id is not None: | |
| 206 | + slot_items.append("'" + tokenizer.eos_token + "'") | |
| 207 | + elif isinstance(slot, dict): | |
| 208 | + raise ValueError("Dict is not supported.") | |
| 209 | + | |
| 210 | + return " + ".join(slot_items) | |
| 211 | + | |
| 212 | + def _get_jinja_template(self, tokenizer: "PreTrainedTokenizer") -> str: | |
| 213 | + r"""Return the jinja template.""" | |
| 214 | + prefix = self._convert_slots_to_jinja(self.format_prefix.apply(), tokenizer) | |
| 215 | + system = self._convert_slots_to_jinja( | |
| 216 | + self.format_system.apply(), tokenizer, placeholder="system_message" | |
| 217 | + ) | |
| 218 | + user = self._convert_slots_to_jinja(self.format_user.apply(), tokenizer) | |
| 219 | + assistant = self._convert_slots_to_jinja( | |
| 220 | + self.format_assistant.apply(), tokenizer | |
| 221 | + ) | |
| 222 | + jinja_template = "" | |
| 223 | + if prefix: | |
| 224 | + jinja_template += "{{ " + prefix + " }}" | |
| 225 | + | |
| 226 | + if self.default_system: | |
| 227 | + jinja_template += ( | |
| 228 | + "{% set system_message = '" | |
| 229 | + + self._jinja_escape(self.default_system) | |
| 230 | + + "' %}" | |
| 231 | + ) | |
| 232 | + | |
| 233 | + jinja_template += ( | |
| 234 | + "{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}" | |
| 235 | + "{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% endif %}" | |
| 236 | + "{% if system_message is defined %}{{ " + system + " }}{% endif %}" | |
| 237 | + "{% for message in loop_messages %}" | |
| 238 | + "{% set content = message['content'] %}" | |
| 239 | + "{% if message['role'] == 'user' %}" | |
| 240 | + "{{ " + user + " }}" | |
| 241 | + "{% elif message['role'] == 'assistant' %}" | |
| 242 | + "{{ " + assistant + " }}" | |
| 243 | + "{% endif %}" | |
| 244 | + "{% endfor %}" | |
| 245 | + ) | |
| 246 | + return jinja_template | |
| 247 | + | |
| 248 | + def fix_jinja_template(self, tokenizer: "PreTrainedTokenizer") -> None: | |
| 249 | + r"""Replace the jinja template in the tokenizer.""" | |
| 250 | + if tokenizer.chat_template is None: | |
| 251 | + try: | |
| 252 | + tokenizer.chat_template = self._get_jinja_template(tokenizer) | |
| 253 | + except ValueError as e: | |
| 254 | + logger.info_rank0(f"Cannot add this chat template to tokenizer: {e}.") | |
| 255 | + | |
| 256 | + | |
| 257 | +TEMPLATES: dict[str, "Template"] = {} | |
| 258 | + | |
| 259 | + | |
| 260 | +def get_template_and_fix_tokenizer( | |
| 261 | + tokenizer: "PreTrainedTokenizer", data_args: "DataArguments" | |
| 262 | +) -> "Template": | |
| 263 | + r"""Get chat template and fixes the tokenizer.""" | |
| 264 | + if data_args.template is None: | |
| 265 | + raise ValueError("`template` is required.") | |
| 266 | + | |
| 267 | + if data_args.template not in TEMPLATES: | |
| 268 | + raise ValueError(f"Template {data_args.template} does not exist.") | |
| 269 | + | |
| 270 | + template = TEMPLATES[data_args.template] | |
| 271 | + | |
| 272 | + if data_args.default_system is not None: | |
| 273 | + logger.info_rank0(f"Using default system message: {data_args.default_system}.") | |
| 274 | + template.default_system = data_args.default_system | |
| 275 | + | |
| 276 | + template.fix_special_tokens(tokenizer) | |
| 277 | + template.fix_jinja_template(tokenizer) | |
| 278 | + return template | |
| 279 | + | |
| 280 | + | |
| 281 | +def register_template( | |
| 282 | + name: str, | |
| 283 | + format_user: Optional["Formatter"] = None, | |
| 284 | + format_assistant: Optional["Formatter"] = None, | |
| 285 | + format_system: Optional["Formatter"] = None, | |
| 286 | + format_prefix: Optional["Formatter"] = None, | |
| 287 | + default_system: str = "", | |
| 288 | + stop_words: Optional[list[str]] = None, | |
| 289 | + replace_eos: bool = False, | |
| 290 | + mm_plugin: "SpatialLMPlugin" = get_mm_plugin(), | |
| 291 | + cutoff_len: int = 8192, | |
| 292 | +) -> None: | |
| 293 | + r"""Register a chat template.""" | |
| 294 | + if name in TEMPLATES: | |
| 295 | + raise ValueError(f"Template {name} already exists.") | |
| 296 | + | |
| 297 | + default_slots = ["{{content}}", {"eos_token"}] | |
| 298 | + default_user_formatter = StringFormatter(slots=["{{content}}"]) | |
| 299 | + default_assistant_formatter = StringFormatter(slots=default_slots) | |
| 300 | + | |
| 301 | + default_prefix_formatter = EmptyFormatter() | |
| 302 | + TEMPLATES[name] = Template( | |
| 303 | + format_user=format_user or default_user_formatter, | |
| 304 | + format_assistant=format_assistant or default_assistant_formatter, | |
| 305 | + format_system=format_system or default_user_formatter, | |
| 306 | + format_prefix=format_prefix or default_prefix_formatter, | |
| 307 | + default_system=default_system, | |
| 308 | + stop_words=stop_words or [], | |
| 309 | + replace_eos=replace_eos, | |
| 310 | + mm_plugin=mm_plugin, | |
| 311 | + cutoff_len=cutoff_len, | |
| 312 | + ) | |
| 313 | + | |
| 314 | + | |
| 315 | +def register_spatiallm_templates( | |
| 316 | + cutoff_len: int = 8192, | |
| 317 | + num_bins: int = 1280, | |
| 318 | + do_augmentation: bool = False, | |
| 319 | + random_rotation: bool = False, | |
| 320 | +): | |
| 321 | + register_template( | |
| 322 | + name="spatiallm_llama", | |
| 323 | + format_user=StringFormatter( | |
| 324 | + slots=[ | |
| 325 | + ( | |
| 326 | + "<|start_header_id|>user<|end_header_id|>\n\n{{content}}<|eot_id|>" | |
| 327 | + "<|start_header_id|>assistant<|end_header_id|>\n\n" | |
| 328 | + ) | |
| 329 | + ] | |
| 330 | + ), | |
| 331 | + format_system=StringFormatter( | |
| 332 | + slots=[ | |
| 333 | + "<|start_header_id|>system<|end_header_id|>\n\n{{content}}<|eot_id|>" | |
| 334 | + ] | |
| 335 | + ), | |
| 336 | + format_prefix=EmptyFormatter(slots=[{"bos_token"}]), | |
| 337 | + stop_words=["<|eot_id|>", "<|eom_id|>"], | |
| 338 | + mm_plugin=get_mm_plugin( | |
| 339 | + point_token="<|point_pad|>", | |
| 340 | + num_bins=num_bins, | |
| 341 | + do_augmentation=do_augmentation, | |
| 342 | + random_rotation=random_rotation, | |
| 343 | + ), | |
| 344 | + cutoff_len=cutoff_len, | |
| 345 | + ) | |
| 346 | + | |
| 347 | + register_template( | |
| 348 | + name="spatiallm_qwen", | |
| 349 | + format_user=StringFormatter( | |
| 350 | + slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"] | |
| 351 | + ), | |
| 352 | + format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]), | |
| 353 | + format_system=StringFormatter( | |
| 354 | + slots=["<|im_start|>system\n{{content}}<|im_end|>\n"] | |
| 355 | + ), | |
| 356 | + default_system="You are a helpful assistant.", | |
| 357 | + stop_words=["<|im_end|>"], | |
| 358 | + mm_plugin=get_mm_plugin( | |
| 359 | + point_token="<|point_pad|>", | |
| 360 | + num_bins=num_bins, | |
| 361 | + do_augmentation=do_augmentation, | |
| 362 | + random_rotation=random_rotation, | |
| 363 | + ), | |
| 364 | + cutoff_len=cutoff_len, | |
| 365 | + ) |
added spatiallm/tuner/framework/__init__.py +0 −0
added spatiallm/tuner/framework/adapter.py +98 −0
| @@ -0,0 +1,98 @@ | ||
| 1 | +# Copyright 2025 the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 | +# you may not use this file except in compliance with the License. | |
| 5 | +# You may obtain a copy of the License at | |
| 6 | +# | |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 | +# | |
| 9 | +# Unless required by applicable law or agreed to in writing, software | |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 | +# See the License for the specific language governing permissions and | |
| 13 | +# limitations under the License. | |
| 14 | + | |
| 15 | +from typing import TYPE_CHECKING, Set | |
| 16 | + | |
| 17 | +import torch | |
| 18 | + | |
| 19 | +from ..framework import logging | |
| 20 | + | |
| 21 | + | |
| 22 | +if TYPE_CHECKING: | |
| 23 | + from transformers import PreTrainedModel | |
| 24 | + | |
| 25 | + from ..hparams import FinetuningArguments | |
| 26 | + | |
| 27 | + | |
| 28 | +logger = logging.get_logger(__name__) | |
| 29 | + | |
| 30 | + | |
| 31 | +def get_forbidden_modules(finetuning_args: "FinetuningArguments") -> Set[str]: | |
| 32 | + r""" | |
| 33 | + Freezes network modules for tuning. | |
| 34 | + """ | |
| 35 | + forbidden_modules = set() | |
| 36 | + if finetuning_args.train_proj_only: | |
| 37 | + forbidden_modules.update({"point_backbone", "model", "lm_head"}) | |
| 38 | + elif finetuning_args.freeze_point_tower: | |
| 39 | + forbidden_modules.add("point_backbone") | |
| 40 | + elif finetuning_args.freeze_language_tower: | |
| 41 | + forbidden_modules.update({"model", "lm_head"}) | |
| 42 | + | |
| 43 | + return forbidden_modules | |
| 44 | + | |
| 45 | + | |
| 46 | +def _setup_full_tuning( | |
| 47 | + model: "PreTrainedModel", | |
| 48 | + finetuning_args: "FinetuningArguments", | |
| 49 | + is_trainable: bool, | |
| 50 | + cast_trainable_params_to_fp32: bool, | |
| 51 | +) -> None: | |
| 52 | + if not is_trainable: | |
| 53 | + return | |
| 54 | + | |
| 55 | + logger.info_rank0("Fine-tuning method: Full") | |
| 56 | + forbidden_modules = get_forbidden_modules(finetuning_args) | |
| 57 | + for name, param in model.named_parameters(): | |
| 58 | + if not any(forbidden_module in name for forbidden_module in forbidden_modules): | |
| 59 | + if cast_trainable_params_to_fp32: | |
| 60 | + param.data = param.data.to(torch.float32) | |
| 61 | + else: | |
| 62 | + param.data = param.data.to(torch.float32) | |
| 63 | + param.requires_grad_(False) | |
| 64 | + | |
| 65 | + # force point_backbone to have float32 | |
| 66 | + model.set_point_backbone_dtype(torch.float32) | |
| 67 | + | |
| 68 | + | |
| 69 | +def init_adapter( | |
| 70 | + model: "PreTrainedModel", | |
| 71 | + finetuning_args: "FinetuningArguments", | |
| 72 | + is_trainable: bool, | |
| 73 | +) -> "PreTrainedModel": | |
| 74 | + r"""Initialize the adapters. | |
| 75 | + | |
| 76 | + Support only full-parameter training for now. | |
| 77 | + | |
| 78 | + Note that the trainable parameters must be cast to float32. | |
| 79 | + """ | |
| 80 | + | |
| 81 | + # cast trainable parameters to float32 if: | |
| 82 | + # 1. is_trainable and not pure_bf16 | |
| 83 | + cast_trainable_params_to_fp32 = False | |
| 84 | + if not is_trainable: | |
| 85 | + pass | |
| 86 | + elif finetuning_args.pure_bf16: | |
| 87 | + logger.info_rank0( | |
| 88 | + "Pure bf16 detected, remaining trainable params in half precision." | |
| 89 | + ) | |
| 90 | + else: | |
| 91 | + logger.info_rank0("Upcasting trainable params to float32.") | |
| 92 | + cast_trainable_params_to_fp32 = True | |
| 93 | + | |
| 94 | + _setup_full_tuning( | |
| 95 | + model, finetuning_args, is_trainable, cast_trainable_params_to_fp32 | |
| 96 | + ) | |
| 97 | + | |
| 98 | + return model |
added spatiallm/tuner/framework/callbacks.py +350 −0
| @@ -0,0 +1,350 @@ | ||
| 1 | +import os | |
| 2 | +import sys | |
| 3 | +import json | |
| 4 | +import time | |
| 5 | +from datetime import timedelta | |
| 6 | +from typing import TYPE_CHECKING, Any, Optional | |
| 7 | +from concurrent.futures import ThreadPoolExecutor | |
| 8 | +from typing_extensions import override | |
| 9 | + | |
| 10 | +from transformers import PreTrainedModel, TrainerCallback | |
| 11 | + | |
| 12 | +from . import logging | |
| 13 | +from .utils import has_length | |
| 14 | + | |
| 15 | +if TYPE_CHECKING: | |
| 16 | + from transformers import ( | |
| 17 | + ProcessorMixin, | |
| 18 | + TrainingArguments, | |
| 19 | + TrainerState, | |
| 20 | + TrainerControl, | |
| 21 | + ) | |
| 22 | + | |
| 23 | + from ..hparams import ( | |
| 24 | + DataArguments, | |
| 25 | + FinetuningArguments, | |
| 26 | + GeneratingArguments, | |
| 27 | + ModelArguments, | |
| 28 | + ) | |
| 29 | + | |
| 30 | +logger = logging.get_logger(__name__) | |
| 31 | + | |
| 32 | +TRAINER_LOG = "trainer_log.jsonl" | |
| 33 | + | |
| 34 | + | |
| 35 | +class LogCallback(TrainerCallback): | |
| 36 | + r"""A callback for logging training and evaluation status.""" | |
| 37 | + | |
| 38 | + def __init__(self) -> None: | |
| 39 | + # Progress | |
| 40 | + self.start_time = 0 | |
| 41 | + self.cur_steps = 0 | |
| 42 | + self.max_steps = 0 | |
| 43 | + self.elapsed_time = "" | |
| 44 | + self.remaining_time = "" | |
| 45 | + self.thread_pool: Optional[ThreadPoolExecutor] = None | |
| 46 | + # Status | |
| 47 | + self.aborted = False | |
| 48 | + self.do_train = False | |
| 49 | + | |
| 50 | + def _set_abort(self, signum, frame) -> None: | |
| 51 | + self.aborted = True | |
| 52 | + | |
| 53 | + def _reset(self, max_steps: int = 0) -> None: | |
| 54 | + self.start_time = time.time() | |
| 55 | + self.cur_steps = 0 | |
| 56 | + self.max_steps = max_steps | |
| 57 | + self.elapsed_time = "" | |
| 58 | + self.remaining_time = "" | |
| 59 | + | |
| 60 | + def _timing(self, cur_steps: int) -> None: | |
| 61 | + cur_time = time.time() | |
| 62 | + elapsed_time = cur_time - self.start_time | |
| 63 | + avg_time_per_step = elapsed_time / cur_steps if cur_steps != 0 else 0 | |
| 64 | + remaining_time = (self.max_steps - cur_steps) * avg_time_per_step | |
| 65 | + self.cur_steps = cur_steps | |
| 66 | + self.elapsed_time = str(timedelta(seconds=int(elapsed_time))) | |
| 67 | + self.remaining_time = str(timedelta(seconds=int(remaining_time))) | |
| 68 | + | |
| 69 | + def _write_log(self, output_dir: str, logs: dict[str, Any]) -> None: | |
| 70 | + with open(os.path.join(output_dir, TRAINER_LOG), "a", encoding="utf-8") as f: | |
| 71 | + f.write(json.dumps(logs) + "\n") | |
| 72 | + | |
| 73 | + def _create_thread_pool(self, output_dir: str) -> None: | |
| 74 | + os.makedirs(output_dir, exist_ok=True) | |
| 75 | + self.thread_pool = ThreadPoolExecutor(max_workers=1) | |
| 76 | + | |
| 77 | + def _close_thread_pool(self) -> None: | |
| 78 | + if self.thread_pool is not None: | |
| 79 | + self.thread_pool.shutdown(wait=True) | |
| 80 | + self.thread_pool = None | |
| 81 | + | |
| 82 | + @override | |
| 83 | + def on_init_end( | |
| 84 | + self, | |
| 85 | + args: "TrainingArguments", | |
| 86 | + state: "TrainerState", | |
| 87 | + control: "TrainerControl", | |
| 88 | + **kwargs, | |
| 89 | + ): | |
| 90 | + if ( | |
| 91 | + args.should_save | |
| 92 | + and os.path.exists(os.path.join(args.output_dir, TRAINER_LOG)) | |
| 93 | + and args.overwrite_output_dir | |
| 94 | + ): | |
| 95 | + logger.warning_rank0_once( | |
| 96 | + "Previous trainer log in this folder will be deleted." | |
| 97 | + ) | |
| 98 | + os.remove(os.path.join(args.output_dir, TRAINER_LOG)) | |
| 99 | + | |
| 100 | + @override | |
| 101 | + def on_train_begin( | |
| 102 | + self, | |
| 103 | + args: "TrainingArguments", | |
| 104 | + state: "TrainerState", | |
| 105 | + control: "TrainerControl", | |
| 106 | + **kwargs, | |
| 107 | + ): | |
| 108 | + if args.should_save: | |
| 109 | + self.do_train = True | |
| 110 | + self._reset(max_steps=state.max_steps) | |
| 111 | + self._create_thread_pool(output_dir=args.output_dir) | |
| 112 | + | |
| 113 | + @override | |
| 114 | + def on_train_end( | |
| 115 | + self, | |
| 116 | + args: "TrainingArguments", | |
| 117 | + state: "TrainerState", | |
| 118 | + control: "TrainerControl", | |
| 119 | + **kwargs, | |
| 120 | + ): | |
| 121 | + self._close_thread_pool() | |
| 122 | + | |
| 123 | + @override | |
| 124 | + def on_substep_end( | |
| 125 | + self, | |
| 126 | + args: "TrainingArguments", | |
| 127 | + state: "TrainerState", | |
| 128 | + control: "TrainerControl", | |
| 129 | + **kwargs, | |
| 130 | + ): | |
| 131 | + if self.aborted: | |
| 132 | + control.should_epoch_stop = True | |
| 133 | + control.should_training_stop = True | |
| 134 | + | |
| 135 | + @override | |
| 136 | + def on_step_end( | |
| 137 | + self, | |
| 138 | + args: "TrainingArguments", | |
| 139 | + state: "TrainerState", | |
| 140 | + control: "TrainerControl", | |
| 141 | + **kwargs, | |
| 142 | + ): | |
| 143 | + if self.aborted: | |
| 144 | + control.should_epoch_stop = True | |
| 145 | + control.should_training_stop = True | |
| 146 | + | |
| 147 | + @override | |
| 148 | + def on_evaluate( | |
| 149 | + self, | |
| 150 | + args: "TrainingArguments", | |
| 151 | + state: "TrainerState", | |
| 152 | + control: "TrainerControl", | |
| 153 | + **kwargs, | |
| 154 | + ): | |
| 155 | + if not self.do_train: | |
| 156 | + self._close_thread_pool() | |
| 157 | + | |
| 158 | + @override | |
| 159 | + def on_predict( | |
| 160 | + self, | |
| 161 | + args: "TrainingArguments", | |
| 162 | + state: "TrainerState", | |
| 163 | + control: "TrainerControl", | |
| 164 | + **kwargs, | |
| 165 | + ): | |
| 166 | + if not self.do_train: | |
| 167 | + self._close_thread_pool() | |
| 168 | + | |
| 169 | + @override | |
| 170 | + def on_log( | |
| 171 | + self, | |
| 172 | + args: "TrainingArguments", | |
| 173 | + state: "TrainerState", | |
| 174 | + control: "TrainerControl", | |
| 175 | + **kwargs, | |
| 176 | + ): | |
| 177 | + if not args.should_save: | |
| 178 | + return | |
| 179 | + | |
| 180 | + self._timing(cur_steps=state.global_step) | |
| 181 | + logs = dict( | |
| 182 | + current_steps=self.cur_steps, | |
| 183 | + total_steps=self.max_steps, | |
| 184 | + loss=state.log_history[-1].get("loss"), | |
| 185 | + eval_loss=state.log_history[-1].get("eval_loss"), | |
| 186 | + predict_loss=state.log_history[-1].get("predict_loss"), | |
| 187 | + lr=state.log_history[-1].get("learning_rate"), | |
| 188 | + epoch=state.log_history[-1].get("epoch"), | |
| 189 | + percentage=( | |
| 190 | + round(self.cur_steps / self.max_steps * 100, 2) | |
| 191 | + if self.max_steps != 0 | |
| 192 | + else 100 | |
| 193 | + ), | |
| 194 | + elapsed_time=self.elapsed_time, | |
| 195 | + remaining_time=self.remaining_time, | |
| 196 | + ) | |
| 197 | + if state.num_input_tokens_seen: | |
| 198 | + logs["throughput"] = round( | |
| 199 | + state.num_input_tokens_seen / (time.time() - self.start_time), 2 | |
| 200 | + ) | |
| 201 | + logs["total_tokens"] = state.num_input_tokens_seen | |
| 202 | + | |
| 203 | + logs = {k: v for k, v in logs.items() if v is not None} | |
| 204 | + | |
| 205 | + if self.thread_pool is not None: | |
| 206 | + self.thread_pool.submit(self._write_log, args.output_dir, logs) | |
| 207 | + | |
| 208 | + @override | |
| 209 | + def on_prediction_step( | |
| 210 | + self, | |
| 211 | + args: "TrainingArguments", | |
| 212 | + state: "TrainerState", | |
| 213 | + control: "TrainerControl", | |
| 214 | + **kwargs, | |
| 215 | + ): | |
| 216 | + if self.do_train: | |
| 217 | + return | |
| 218 | + | |
| 219 | + if self.aborted: | |
| 220 | + sys.exit(0) | |
| 221 | + | |
| 222 | + if not args.should_save: | |
| 223 | + return | |
| 224 | + | |
| 225 | + eval_dataloader = kwargs.pop("eval_dataloader", None) | |
| 226 | + if has_length(eval_dataloader): | |
| 227 | + if self.max_steps == 0: | |
| 228 | + self._reset(max_steps=len(eval_dataloader)) | |
| 229 | + self._create_thread_pool(output_dir=args.output_dir) | |
| 230 | + | |
| 231 | + self._timing(cur_steps=self.cur_steps + 1) | |
| 232 | + if self.cur_steps % 5 == 0 and self.thread_pool is not None: | |
| 233 | + logs = dict( | |
| 234 | + current_steps=self.cur_steps, | |
| 235 | + total_steps=self.max_steps, | |
| 236 | + percentage=( | |
| 237 | + round(self.cur_steps / self.max_steps * 100, 2) | |
| 238 | + if self.max_steps != 0 | |
| 239 | + else 100 | |
| 240 | + ), | |
| 241 | + elapsed_time=self.elapsed_time, | |
| 242 | + remaining_time=self.remaining_time, | |
| 243 | + ) | |
| 244 | + self.thread_pool.submit(self._write_log, args.output_dir, logs) | |
| 245 | + | |
| 246 | + | |
| 247 | +class ReporterCallback(TrainerCallback): | |
| 248 | + r"""A callback for reporting training status to external logger.""" | |
| 249 | + | |
| 250 | + def __init__( | |
| 251 | + self, | |
| 252 | + model_args: "ModelArguments", | |
| 253 | + data_args: "DataArguments", | |
| 254 | + finetuning_args: "FinetuningArguments", | |
| 255 | + generating_args: "GeneratingArguments", | |
| 256 | + ) -> None: | |
| 257 | + self.model_args = model_args | |
| 258 | + self.data_args = data_args | |
| 259 | + self.finetuning_args = finetuning_args | |
| 260 | + self.generating_args = generating_args | |
| 261 | + os.environ["WANDB_PROJECT"] = os.getenv("WANDB_PROJECT", "spatiallm") | |
| 262 | + | |
| 263 | + @override | |
| 264 | + def on_train_begin( | |
| 265 | + self, | |
| 266 | + args: "TrainingArguments", | |
| 267 | + state: "TrainerState", | |
| 268 | + control: "TrainerControl", | |
| 269 | + **kwargs, | |
| 270 | + ): | |
| 271 | + if not state.is_world_process_zero: | |
| 272 | + return | |
| 273 | + | |
| 274 | + if "wandb" in args.report_to: | |
| 275 | + import wandb | |
| 276 | + | |
| 277 | + wandb.config.update( | |
| 278 | + { | |
| 279 | + "model_args": self.model_args.to_dict(), | |
| 280 | + "data_args": self.data_args.to_dict(), | |
| 281 | + "finetuning_args": self.finetuning_args.to_dict(), | |
| 282 | + "generating_args": self.generating_args.to_dict(), | |
| 283 | + } | |
| 284 | + ) | |
| 285 | + | |
| 286 | + if self.finetuning_args.use_swanlab: | |
| 287 | + import swanlab # type: ignore | |
| 288 | + | |
| 289 | + swanlab.config.update( | |
| 290 | + { | |
| 291 | + "model_args": self.model_args.to_dict(), | |
| 292 | + "data_args": self.data_args.to_dict(), | |
| 293 | + "finetuning_args": self.finetuning_args.to_dict(), | |
| 294 | + "generating_args": self.generating_args.to_dict(), | |
| 295 | + } | |
| 296 | + ) | |
| 297 | + | |
| 298 | + | |
| 299 | +def get_swanlab_callback(finetuning_args: "FinetuningArguments") -> "TrainerCallback": | |
| 300 | + r"""Get the callback for logging to SwanLab.""" | |
| 301 | + import swanlab # type: ignore | |
| 302 | + from swanlab.integration.transformers import SwanLabCallback # type: ignore | |
| 303 | + | |
| 304 | + if finetuning_args.swanlab_api_key is not None: | |
| 305 | + swanlab.login(api_key=finetuning_args.swanlab_api_key) | |
| 306 | + | |
| 307 | + if finetuning_args.swanlab_lark_webhook_url is not None: | |
| 308 | + from swanlab.plugin.notification import LarkCallback # type: ignore | |
| 309 | + | |
| 310 | + lark_callback = LarkCallback( | |
| 311 | + webhook_url=finetuning_args.swanlab_lark_webhook_url, | |
| 312 | + secret=finetuning_args.swanlab_lark_secret, | |
| 313 | + ) | |
| 314 | + swanlab.register_callbacks([lark_callback]) | |
| 315 | + | |
| 316 | + class SwanLabCallbackExtension(SwanLabCallback): | |
| 317 | + def setup( | |
| 318 | + self, | |
| 319 | + args: "TrainingArguments", | |
| 320 | + state: "TrainerState", | |
| 321 | + model: "PreTrainedModel", | |
| 322 | + **kwargs, | |
| 323 | + ): | |
| 324 | + if not state.is_world_process_zero: | |
| 325 | + return | |
| 326 | + | |
| 327 | + super().setup(args, state, model, **kwargs) | |
| 328 | + try: | |
| 329 | + if hasattr(self, "_swanlab"): | |
| 330 | + swanlab_public_config = self._swanlab.get_run().public.json() | |
| 331 | + else: # swanlab <= 0.4.9 | |
| 332 | + swanlab_public_config = self._experiment.get_run().public.json() | |
| 333 | + except Exception: | |
| 334 | + swanlab_public_config = {} | |
| 335 | + | |
| 336 | + with open( | |
| 337 | + os.path.join(args.output_dir, "swanlab_public_config.json"), "w" | |
| 338 | + ) as f: | |
| 339 | + f.write(json.dumps(swanlab_public_config, indent=2)) | |
| 340 | + | |
| 341 | + swanlab_callback = SwanLabCallbackExtension( | |
| 342 | + project=finetuning_args.swanlab_project, | |
| 343 | + workspace=finetuning_args.swanlab_workspace, | |
| 344 | + experiment_name=finetuning_args.swanlab_run_name, | |
| 345 | + mode=finetuning_args.swanlab_mode, | |
| 346 | + config={"Framework": "SpatialLM"}, | |
| 347 | + logdir=finetuning_args.swanlab_logdir, | |
| 348 | + tags=["SpatialLM"], | |
| 349 | + ) | |
| 350 | + return swanlab_callback |
added spatiallm/tuner/framework/loader.py +189 −0
| @@ -0,0 +1,189 @@ | ||
| 1 | +import os | |
| 2 | +from typing import TYPE_CHECKING, Any, Optional, TypedDict | |
| 3 | + | |
| 4 | +import torch | |
| 5 | +import transformers.dynamic_module_utils | |
| 6 | +from transformers.dynamic_module_utils import get_relative_imports | |
| 7 | +from transformers import ( | |
| 8 | + AutoConfig, | |
| 9 | + AutoModelForCausalLM, | |
| 10 | + AutoModelForSeq2SeqLM, | |
| 11 | + AutoModelForTextToWaveform, | |
| 12 | + AutoModelForVision2Seq, | |
| 13 | + AutoProcessor, | |
| 14 | + AutoTokenizer, | |
| 15 | +) | |
| 16 | + | |
| 17 | +from . import logging | |
| 18 | +from .utils import check_version, count_parameters, is_env_enabled | |
| 19 | +from .patcher import patch_config, patch_model, patch_tokenizer, patch_processor | |
| 20 | +from .adapter import init_adapter | |
| 21 | + | |
| 22 | +if TYPE_CHECKING: | |
| 23 | + from transformers import ( | |
| 24 | + PretrainedConfig, | |
| 25 | + PreTrainedModel, | |
| 26 | + PreTrainedTokenizer, | |
| 27 | + ProcessorMixin, | |
| 28 | + ) | |
| 29 | + | |
| 30 | + from ..hparams import DataArguments, ModelArguments, FinetuningArguments | |
| 31 | + | |
| 32 | +logger = logging.get_logger(__name__) | |
| 33 | + | |
| 34 | + | |
| 35 | +class TokenizerModule(TypedDict): | |
| 36 | + tokenizer: "PreTrainedTokenizer" | |
| 37 | + processor: Optional["ProcessorMixin"] | |
| 38 | + | |
| 39 | + | |
| 40 | +def skip_check_imports() -> None: | |
| 41 | + r"""Avoid flash attention import error in custom model files.""" | |
| 42 | + if not is_env_enabled("FORCE_CHECK_IMPORTS"): | |
| 43 | + transformers.dynamic_module_utils.check_imports = get_relative_imports | |
| 44 | + | |
| 45 | + | |
| 46 | +def use_modelscope() -> bool: | |
| 47 | + return is_env_enabled("USE_MODELSCOPE_HUB") | |
| 48 | + | |
| 49 | + | |
| 50 | +def try_download_model_from_other_hub(model_args: "ModelArguments") -> str: | |
| 51 | + if not use_modelscope() or os.path.exists(model_args.model_name_or_path): | |
| 52 | + return model_args.model_name_or_path | |
| 53 | + | |
| 54 | + if use_modelscope(): | |
| 55 | + check_version("modelscope>=1.11.0", mandatory=True) | |
| 56 | + from modelscope import snapshot_download # type: ignore | |
| 57 | + | |
| 58 | + revision = ( | |
| 59 | + "master" | |
| 60 | + if model_args.model_revision == "main" | |
| 61 | + else model_args.model_revision | |
| 62 | + ) | |
| 63 | + return snapshot_download( | |
| 64 | + model_args.model_name_or_path, | |
| 65 | + revision=revision, | |
| 66 | + cache_dir=model_args.cache_dir, | |
| 67 | + ) | |
| 68 | + | |
| 69 | + | |
| 70 | +def _get_init_kwargs(model_args: "ModelArguments") -> dict[str, Any]: | |
| 71 | + r"""Get arguments to load config/tokenizer/model. | |
| 72 | + | |
| 73 | + Note: including inplace operation of model_args. | |
| 74 | + """ | |
| 75 | + model_args.model_name_or_path = try_download_model_from_other_hub(model_args) | |
| 76 | + return { | |
| 77 | + "trust_remote_code": model_args.trust_remote_code, | |
| 78 | + "cache_dir": model_args.cache_dir, | |
| 79 | + "revision": model_args.model_revision, | |
| 80 | + "token": model_args.hf_hub_token, | |
| 81 | + } | |
| 82 | + | |
| 83 | + | |
| 84 | +def load_config(model_args: "ModelArguments") -> "PretrainedConfig": | |
| 85 | + r"""Load model config.""" | |
| 86 | + init_kwargs = _get_init_kwargs(model_args) | |
| 87 | + return AutoConfig.from_pretrained(model_args.model_name_or_path, **init_kwargs) | |
| 88 | + | |
| 89 | + | |
| 90 | +def load_tokenizer(model_args: "ModelArguments") -> "TokenizerModule": | |
| 91 | + r"""Load pretrained tokenizer and optionally loads processor. | |
| 92 | + | |
| 93 | + Note: including inplace operation of model_args. | |
| 94 | + """ | |
| 95 | + init_kwargs = _get_init_kwargs(model_args) | |
| 96 | + try: | |
| 97 | + tokenizer = AutoTokenizer.from_pretrained( | |
| 98 | + model_args.model_name_or_path, | |
| 99 | + use_fast=model_args.use_fast_tokenizer, | |
| 100 | + split_special_tokens=model_args.split_special_tokens, | |
| 101 | + padding_side="right", | |
| 102 | + **init_kwargs, | |
| 103 | + ) | |
| 104 | + except ValueError: # try the fast one | |
| 105 | + tokenizer = AutoTokenizer.from_pretrained( | |
| 106 | + model_args.model_name_or_path, | |
| 107 | + use_fast=True, | |
| 108 | + padding_side="right", | |
| 109 | + **init_kwargs, | |
| 110 | + ) | |
| 111 | + except Exception as e: | |
| 112 | + raise OSError("Failed to load tokenizer.") from e | |
| 113 | + | |
| 114 | + patch_tokenizer(tokenizer, model_args) | |
| 115 | + | |
| 116 | + return {"tokenizer": tokenizer} | |
| 117 | + | |
| 118 | + | |
| 119 | +def register_autoclass( | |
| 120 | + config: "PretrainedConfig", | |
| 121 | + model: "PreTrainedModel", | |
| 122 | + tokenizer: "PreTrainedTokenizer", | |
| 123 | +): | |
| 124 | + if "AutoConfig" in getattr(config, "auto_map", {}): | |
| 125 | + config.__class__.register_for_auto_class() | |
| 126 | + if "AutoModelForCausalLM" in getattr(config, "auto_map", {}): | |
| 127 | + model.__class__.register_for_auto_class() | |
| 128 | + if "AutoTokenizer" in tokenizer.init_kwargs.get("auto_map", {}): | |
| 129 | + tokenizer.__class__.register_for_auto_class() | |
| 130 | + | |
| 131 | + | |
| 132 | +def load_model( | |
| 133 | + tokenizer: "PreTrainedTokenizer", | |
| 134 | + data_args: "DataArguments", | |
| 135 | + model_args: "ModelArguments", | |
| 136 | + finetuning_args: "FinetuningArguments", | |
| 137 | + is_trainable: bool = False, | |
| 138 | +) -> "PreTrainedModel": | |
| 139 | + r"""Load pretrained model.""" | |
| 140 | + init_kwargs = _get_init_kwargs(model_args) | |
| 141 | + config = load_config(model_args) | |
| 142 | + config.point_config["num_bins"] = data_args.num_bins | |
| 143 | + patch_config(config, model_args, init_kwargs, is_trainable) | |
| 144 | + | |
| 145 | + init_kwargs["config"] = config | |
| 146 | + init_kwargs["pretrained_model_name_or_path"] = model_args.model_name_or_path | |
| 147 | + | |
| 148 | + if model_args.train_from_scratch: | |
| 149 | + model = AutoModelForCausalLM.from_config( | |
| 150 | + config, trust_remote_code=model_args.trust_remote_code | |
| 151 | + ) | |
| 152 | + else: | |
| 153 | + model = AutoModelForCausalLM.from_pretrained(**init_kwargs) | |
| 154 | + | |
| 155 | + patch_model(model, model_args, is_trainable) | |
| 156 | + register_autoclass(config, model, tokenizer) | |
| 157 | + model = init_adapter(model, finetuning_args, is_trainable) | |
| 158 | + | |
| 159 | + if not is_trainable: | |
| 160 | + model.requires_grad_(False) | |
| 161 | + for param in model.parameters(): | |
| 162 | + if ( | |
| 163 | + param.data.dtype == torch.float32 | |
| 164 | + and model_args.compute_dtype != torch.float32 | |
| 165 | + ): | |
| 166 | + param.data = param.data.to(model_args.compute_dtype) | |
| 167 | + | |
| 168 | + model.eval() | |
| 169 | + else: | |
| 170 | + model.train() | |
| 171 | + | |
| 172 | + trainable_params, all_param = count_parameters(model) | |
| 173 | + if is_trainable: | |
| 174 | + param_stats = ( | |
| 175 | + f"trainable params: {trainable_params:,} || " | |
| 176 | + f"all params: {all_param:,} || trainable%: {100 * trainable_params / all_param:.4f}" | |
| 177 | + ) | |
| 178 | + else: | |
| 179 | + param_stats = f"all params: {all_param:,}" | |
| 180 | + | |
| 181 | + logger.info_rank0(param_stats) | |
| 182 | + | |
| 183 | + if model_args.print_param_status and int(os.getenv("LOCAL_RANK", "0")) == 0: | |
| 184 | + for name, param in model.named_parameters(): | |
| 185 | + print( | |
| 186 | + f"name: {name}, dtype: {param.dtype}, device: {param.device}, trainable: {param.requires_grad}" | |
| 187 | + ) | |
| 188 | + | |
| 189 | + return model |
added spatiallm/tuner/framework/logging.py +159 −0
| @@ -0,0 +1,159 @@ | ||
| 1 | +# Copyright 2025 Optuna, HuggingFace Inc. and the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# This code is inspired by the HuggingFace's transformers library. | |
| 4 | +# https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/utils/logging.py | |
| 5 | +# | |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 7 | +# you may not use this file except in compliance with the License. | |
| 8 | +# You may obtain a copy of the License at | |
| 9 | +# | |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 11 | +# | |
| 12 | +# Unless required by applicable law or agreed to in writing, software | |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 15 | +# See the License for the specific language governing permissions and | |
| 16 | +# limitations under the License. | |
| 17 | + | |
| 18 | +import logging | |
| 19 | +import os | |
| 20 | +import sys | |
| 21 | +import threading | |
| 22 | +from concurrent.futures import ThreadPoolExecutor | |
| 23 | +from functools import lru_cache | |
| 24 | +from typing import Optional | |
| 25 | + | |
| 26 | +RUNNING_LOG = "running_log.txt" | |
| 27 | + | |
| 28 | + | |
| 29 | +_thread_lock = threading.RLock() | |
| 30 | +_default_handler: Optional["logging.Handler"] = None | |
| 31 | +_default_log_level: "logging._Level" = logging.INFO | |
| 32 | + | |
| 33 | + | |
| 34 | +class LoggerHandler(logging.Handler): | |
| 35 | + r"""Redirect the logging output to the logging file for LLaMA Board.""" | |
| 36 | + | |
| 37 | + def __init__(self, output_dir: str) -> None: | |
| 38 | + super().__init__() | |
| 39 | + self._formatter = logging.Formatter( | |
| 40 | + fmt="[%(levelname)s|%(asctime)s] %(filename)s:%(lineno)s >> %(message)s", | |
| 41 | + datefmt="%Y-%m-%d %H:%M:%S", | |
| 42 | + ) | |
| 43 | + self.setLevel(logging.INFO) | |
| 44 | + os.makedirs(output_dir, exist_ok=True) | |
| 45 | + self.running_log = os.path.join(output_dir, RUNNING_LOG) | |
| 46 | + if os.path.exists(self.running_log): | |
| 47 | + os.remove(self.running_log) | |
| 48 | + | |
| 49 | + self.thread_pool = ThreadPoolExecutor(max_workers=1) | |
| 50 | + | |
| 51 | + def _write_log(self, log_entry: str) -> None: | |
| 52 | + with open(self.running_log, "a", encoding="utf-8") as f: | |
| 53 | + f.write(log_entry + "\n\n") | |
| 54 | + | |
| 55 | + def emit(self, record) -> None: | |
| 56 | + if record.name == "httpx": | |
| 57 | + return | |
| 58 | + | |
| 59 | + log_entry = self._formatter.format(record) | |
| 60 | + self.thread_pool.submit(self._write_log, log_entry) | |
| 61 | + | |
| 62 | + def close(self) -> None: | |
| 63 | + self.thread_pool.shutdown(wait=True) | |
| 64 | + return super().close() | |
| 65 | + | |
| 66 | + | |
| 67 | +class _Logger(logging.Logger): | |
| 68 | + r"""A logger that supports rank0 logging.""" | |
| 69 | + | |
| 70 | + def info_rank0(self, *args, **kwargs) -> None: | |
| 71 | + self.info(*args, **kwargs) | |
| 72 | + | |
| 73 | + def warning_rank0(self, *args, **kwargs) -> None: | |
| 74 | + self.warning(*args, **kwargs) | |
| 75 | + | |
| 76 | + def warning_rank0_once(self, *args, **kwargs) -> None: | |
| 77 | + self.warning(*args, **kwargs) | |
| 78 | + | |
| 79 | + | |
| 80 | +def _get_default_logging_level() -> "logging._Level": | |
| 81 | + r"""Return the default logging level.""" | |
| 82 | + env_level_str = os.getenv("SPATIALLM_VERBOSITY", None) | |
| 83 | + if env_level_str: | |
| 84 | + if env_level_str.upper() in logging._nameToLevel: | |
| 85 | + return logging._nameToLevel[env_level_str.upper()] | |
| 86 | + else: | |
| 87 | + raise ValueError(f"Unknown logging level: {env_level_str}.") | |
| 88 | + | |
| 89 | + return _default_log_level | |
| 90 | + | |
| 91 | + | |
| 92 | +def _get_library_name() -> str: | |
| 93 | + return __name__.split(".")[0] | |
| 94 | + | |
| 95 | + | |
| 96 | +def _get_library_root_logger() -> "_Logger": | |
| 97 | + return logging.getLogger(_get_library_name()) | |
| 98 | + | |
| 99 | + | |
| 100 | +def _configure_library_root_logger() -> None: | |
| 101 | + r"""Configure root logger using a stdout stream handler with an explicit format.""" | |
| 102 | + global _default_handler | |
| 103 | + | |
| 104 | + with _thread_lock: | |
| 105 | + if _default_handler: # already configured | |
| 106 | + return | |
| 107 | + | |
| 108 | + formatter = logging.Formatter( | |
| 109 | + fmt="[%(levelname)s|%(asctime)s] %(name)s:%(lineno)s >> %(message)s", | |
| 110 | + datefmt="%Y-%m-%d %H:%M:%S", | |
| 111 | + ) | |
| 112 | + _default_handler = logging.StreamHandler(sys.stdout) | |
| 113 | + _default_handler.setFormatter(formatter) | |
| 114 | + library_root_logger = _get_library_root_logger() | |
| 115 | + library_root_logger.addHandler(_default_handler) | |
| 116 | + library_root_logger.setLevel(_get_default_logging_level()) | |
| 117 | + library_root_logger.propagate = False | |
| 118 | + | |
| 119 | + | |
| 120 | +def get_logger(name: Optional[str] = None) -> "_Logger": | |
| 121 | + r"""Return a logger with the specified name. It it not supposed to be accessed externally.""" | |
| 122 | + if name is None: | |
| 123 | + name = _get_library_name() | |
| 124 | + | |
| 125 | + _configure_library_root_logger() | |
| 126 | + return logging.getLogger(name) | |
| 127 | + | |
| 128 | + | |
| 129 | +def add_handler(handler: "logging.Handler") -> None: | |
| 130 | + r"""Add a handler to the root logger.""" | |
| 131 | + _configure_library_root_logger() | |
| 132 | + _get_library_root_logger().addHandler(handler) | |
| 133 | + | |
| 134 | + | |
| 135 | +def remove_handler(handler: logging.Handler) -> None: | |
| 136 | + r"""Remove a handler to the root logger.""" | |
| 137 | + _configure_library_root_logger() | |
| 138 | + _get_library_root_logger().removeHandler(handler) | |
| 139 | + | |
| 140 | + | |
| 141 | +def info_rank0(self: "logging.Logger", *args, **kwargs) -> None: | |
| 142 | + if int(os.getenv("LOCAL_RANK", "0")) == 0: | |
| 143 | + self.info(*args, **kwargs) | |
| 144 | + | |
| 145 | + | |
| 146 | +def warning_rank0(self: "logging.Logger", *args, **kwargs) -> None: | |
| 147 | + if int(os.getenv("LOCAL_RANK", "0")) == 0: | |
| 148 | + self.warning(*args, **kwargs) | |
| 149 | + | |
| 150 | + | |
| 151 | +@lru_cache(None) | |
| 152 | +def warning_rank0_once(self: "logging.Logger", *args, **kwargs) -> None: | |
| 153 | + if int(os.getenv("LOCAL_RANK", "0")) == 0: | |
| 154 | + self.warning(*args, **kwargs) | |
| 155 | + | |
| 156 | + | |
| 157 | +logging.Logger.info_rank0 = info_rank0 | |
| 158 | +logging.Logger.warning_rank0 = warning_rank0 | |
| 159 | +logging.Logger.warning_rank0_once = warning_rank0_once |
added spatiallm/tuner/framework/patcher.py +153 −0
| @@ -0,0 +1,153 @@ | ||
| 1 | +# Copyright 2025 the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 | +# you may not use this file except in compliance with the License. | |
| 5 | +# You may obtain a copy of the License at | |
| 6 | +# | |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 | +# | |
| 9 | +# Unless required by applicable law or agreed to in writing, software | |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 | +# See the License for the specific language governing permissions and | |
| 13 | +# limitations under the License. | |
| 14 | + | |
| 15 | +from types import MethodType | |
| 16 | +from typing import TYPE_CHECKING, Any | |
| 17 | + | |
| 18 | +import torch | |
| 19 | +from transformers import GenerationMixin, PreTrainedModel, PreTrainedTokenizerBase | |
| 20 | +from transformers.integrations import is_deepspeed_zero3_enabled | |
| 21 | +from transformers.utils import is_torch_bf16_gpu_available, is_torch_npu_available | |
| 22 | + | |
| 23 | +from . import logging | |
| 24 | + | |
| 25 | +try: | |
| 26 | + _is_bf16_available = is_torch_bf16_gpu_available() or ( | |
| 27 | + is_torch_npu_available() and torch.npu.is_bf16_supported() | |
| 28 | + ) | |
| 29 | +except Exception: | |
| 30 | + _is_bf16_available = False | |
| 31 | + | |
| 32 | +from ..network.attention import configure_attn_implementation | |
| 33 | +from ..network.checkpointing import prepare_model_for_training | |
| 34 | +from ..network.rope import configure_rope | |
| 35 | + | |
| 36 | +if TYPE_CHECKING: | |
| 37 | + from transformers import PretrainedConfig, PreTrainedTokenizer, ProcessorMixin | |
| 38 | + | |
| 39 | + from ..hparams import ModelArguments | |
| 40 | + | |
| 41 | + | |
| 42 | +logger = logging.get_logger(__name__) | |
| 43 | + | |
| 44 | + | |
| 45 | +def patch_tokenizer( | |
| 46 | + tokenizer: "PreTrainedTokenizer", model_args: "ModelArguments" | |
| 47 | +) -> None: | |
| 48 | + if "PreTrainedTokenizerBase" not in str(tokenizer._pad.__func__): | |
| 49 | + tokenizer._pad = MethodType(PreTrainedTokenizerBase._pad, tokenizer) | |
| 50 | + | |
| 51 | + if ( | |
| 52 | + model_args.model_max_length is not None | |
| 53 | + and tokenizer.model_max_length < model_args.model_max_length | |
| 54 | + ): | |
| 55 | + tokenizer.model_max_length = ( | |
| 56 | + model_args.model_max_length | |
| 57 | + ) # enlarge the tokenizer max length | |
| 58 | + | |
| 59 | + if model_args.add_tokens is not None: | |
| 60 | + num_added_tokens = tokenizer.add_tokens( | |
| 61 | + new_tokens=model_args.add_tokens, special_tokens=False | |
| 62 | + ) | |
| 63 | + logger.info_rank0( | |
| 64 | + "Add tokens {} to tokenizer's vocabulary.".format( | |
| 65 | + ",".join(model_args.add_tokens) | |
| 66 | + ) | |
| 67 | + ) | |
| 68 | + if num_added_tokens > 0 and not model_args.resize_vocab: | |
| 69 | + model_args.resize_vocab = True | |
| 70 | + logger.warning_rank0( | |
| 71 | + "New tokens have been added, changed `resize_vocab` to True." | |
| 72 | + ) | |
| 73 | + | |
| 74 | + if model_args.add_special_tokens is not None: | |
| 75 | + num_added_special_tokens = tokenizer.add_tokens( | |
| 76 | + new_tokens=model_args.add_special_tokens, special_tokens=True | |
| 77 | + ) | |
| 78 | + logger.info_rank0( | |
| 79 | + "Add special tokens {} to tokenizer's vocabulary.".format( | |
| 80 | + ",".join(model_args.add_special_tokens) | |
| 81 | + ) | |
| 82 | + ) | |
| 83 | + if num_added_special_tokens > 0 and not model_args.resize_vocab: | |
| 84 | + model_args.resize_vocab = True | |
| 85 | + logger.warning_rank0( | |
| 86 | + "New special tokens have been added, changed `resize_vocab` to True." | |
| 87 | + ) | |
| 88 | + | |
| 89 | + | |
| 90 | +def patch_processor( | |
| 91 | + processor: "ProcessorMixin", | |
| 92 | + tokenizer: "PreTrainedTokenizer", | |
| 93 | +) -> None: | |
| 94 | + setattr(processor, "tokenizer", tokenizer) | |
| 95 | + | |
| 96 | + | |
| 97 | +def patch_config( | |
| 98 | + config: "PretrainedConfig", | |
| 99 | + model_args: "ModelArguments", | |
| 100 | + init_kwargs: dict[str, Any], | |
| 101 | + is_trainable: bool, | |
| 102 | +) -> None: | |
| 103 | + if model_args.compute_dtype is None: # priority: bf16 > fp32 | |
| 104 | + if model_args.infer_dtype != "auto" and not is_trainable: | |
| 105 | + model_args.compute_dtype = getattr(torch, model_args.infer_dtype) | |
| 106 | + elif ( | |
| 107 | + _is_bf16_available | |
| 108 | + and getattr(config, "torch_dtype", None) == torch.bfloat16 | |
| 109 | + ): | |
| 110 | + model_args.compute_dtype = torch.bfloat16 | |
| 111 | + else: | |
| 112 | + model_args.compute_dtype = torch.float32 | |
| 113 | + | |
| 114 | + configure_attn_implementation(config, model_args) | |
| 115 | + configure_rope(config, model_args) | |
| 116 | + | |
| 117 | + if getattr(config, "model_type", None) == "qwen": | |
| 118 | + setattr(config, "use_flash_attn", model_args.flash_attn == "fa2") | |
| 119 | + for dtype_name, dtype in [ | |
| 120 | + ("bf16", torch.bfloat16), | |
| 121 | + ("fp32", torch.float32), | |
| 122 | + ]: | |
| 123 | + setattr(config, dtype_name, model_args.compute_dtype == dtype) | |
| 124 | + | |
| 125 | + # deepspeed zero3 is not compatible with low_cpu_mem_usage | |
| 126 | + init_kwargs["low_cpu_mem_usage"] = model_args.low_cpu_mem_usage and ( | |
| 127 | + not is_deepspeed_zero3_enabled() | |
| 128 | + ) | |
| 129 | + | |
| 130 | + | |
| 131 | +def patch_model( | |
| 132 | + model: "PreTrainedModel", | |
| 133 | + model_args: "ModelArguments", | |
| 134 | + is_trainable: bool, | |
| 135 | +) -> None: | |
| 136 | + gen_config = model.generation_config # check and fix generation config | |
| 137 | + if not gen_config.do_sample and ( | |
| 138 | + (gen_config.temperature is not None and gen_config.temperature != 1.0) | |
| 139 | + or (gen_config.top_p is not None and gen_config.top_p != 1.0) | |
| 140 | + or (gen_config.typical_p is not None and gen_config.typical_p != 1.0) | |
| 141 | + ): | |
| 142 | + gen_config.do_sample = True | |
| 143 | + | |
| 144 | + if "GenerationMixin" not in str(model.generate.__func__): | |
| 145 | + model.generate = MethodType(GenerationMixin.generate, model) | |
| 146 | + | |
| 147 | + if is_trainable: | |
| 148 | + prepare_model_for_training(model, model_args) | |
| 149 | + | |
| 150 | + try: | |
| 151 | + model.add_model_tags(["spatiallm"]) | |
| 152 | + except Exception: | |
| 153 | + logger.warning_rank0("Cannot properly tag the model.") |
added spatiallm/tuner/framework/utils.py +125 −0
| @@ -0,0 +1,125 @@ | ||
| 1 | +import os | |
| 2 | +import importlib.metadata | |
| 3 | +import importlib.util | |
| 4 | +from functools import lru_cache | |
| 5 | +from typing import TYPE_CHECKING | |
| 6 | + | |
| 7 | +import torch | |
| 8 | +from packaging import version | |
| 9 | +from transformers.utils import ( | |
| 10 | + is_torch_cuda_available, | |
| 11 | + is_torch_mps_available, | |
| 12 | + is_torch_npu_available, | |
| 13 | + is_torch_xpu_available, | |
| 14 | +) | |
| 15 | +from transformers.utils.versions import require_version | |
| 16 | + | |
| 17 | +from ..framework import logging | |
| 18 | + | |
| 19 | +if TYPE_CHECKING: | |
| 20 | + from packaging.version import Version | |
| 21 | + | |
| 22 | +logger = logging.get_logger(__name__) | |
| 23 | + | |
| 24 | + | |
| 25 | +def has_length(dataset): | |
| 26 | + """ | |
| 27 | + Checks if the dataset implements __len__() and it doesn't raise an error | |
| 28 | + """ | |
| 29 | + try: | |
| 30 | + return len(dataset) is not None | |
| 31 | + except TypeError: | |
| 32 | + # TypeError: len() of unsized object | |
| 33 | + return False | |
| 34 | + | |
| 35 | + | |
| 36 | +def is_env_enabled(env_var: str, default: str = "0") -> bool: | |
| 37 | + r"""Check if the environment variable is enabled.""" | |
| 38 | + return os.getenv(env_var, default).lower() in ["true", "y", "1"] | |
| 39 | + | |
| 40 | + | |
| 41 | +def check_version(requirement: str, mandatory: bool = False) -> None: | |
| 42 | + r"""Optionally check the package version.""" | |
| 43 | + if is_env_enabled("DISABLE_VERSION_CHECK") and not mandatory: | |
| 44 | + logger.warning_rank0_once( | |
| 45 | + "Version checking has been disabled, may lead to unexpected behaviors." | |
| 46 | + ) | |
| 47 | + return | |
| 48 | + | |
| 49 | + if "gptmodel" in requirement or "autoawq" in requirement: | |
| 50 | + pip_command = f"pip install {requirement} --no-build-isolation" | |
| 51 | + else: | |
| 52 | + pip_command = f"pip install {requirement}" | |
| 53 | + | |
| 54 | + if mandatory: | |
| 55 | + hint = f"To fix: run `{pip_command}`." | |
| 56 | + else: | |
| 57 | + hint = f"To fix: run `{pip_command}` or set `DISABLE_VERSION_CHECK=1` to skip this check." | |
| 58 | + | |
| 59 | + require_version(requirement, hint) | |
| 60 | + | |
| 61 | + | |
| 62 | +def count_parameters(model: "torch.nn.Module") -> tuple[int, int]: | |
| 63 | + r"""Return the number of trainable parameters and number of all parameters in the model.""" | |
| 64 | + trainable_params, all_param = 0, 0 | |
| 65 | + for param in model.parameters(): | |
| 66 | + num_params = param.numel() | |
| 67 | + | |
| 68 | + all_param += num_params | |
| 69 | + if param.requires_grad: | |
| 70 | + trainable_params += num_params | |
| 71 | + | |
| 72 | + return trainable_params, all_param | |
| 73 | + | |
| 74 | + | |
| 75 | +def _get_package_version(name: str) -> "Version": | |
| 76 | + try: | |
| 77 | + return version.parse(importlib.metadata.version(name)) | |
| 78 | + except Exception: | |
| 79 | + return version.parse("0.0.0") | |
| 80 | + | |
| 81 | + | |
| 82 | +@lru_cache | |
| 83 | +def is_transformers_version_greater_than(content: str): | |
| 84 | + return _get_package_version("transformers") >= version.parse(content) | |
| 85 | + | |
| 86 | + | |
| 87 | +def get_current_device() -> "torch.device": | |
| 88 | + r""" | |
| 89 | + Gets the current available device. | |
| 90 | + """ | |
| 91 | + if is_torch_xpu_available(): | |
| 92 | + device = "xpu:{}".format(os.environ.get("LOCAL_RANK", "0")) | |
| 93 | + elif is_torch_npu_available(): | |
| 94 | + device = "npu:{}".format(os.environ.get("LOCAL_RANK", "0")) | |
| 95 | + elif is_torch_mps_available(): | |
| 96 | + device = "mps:{}".format(os.environ.get("LOCAL_RANK", "0")) | |
| 97 | + elif is_torch_cuda_available(): | |
| 98 | + device = "cuda:{}".format(os.environ.get("LOCAL_RANK", "0")) | |
| 99 | + else: | |
| 100 | + device = "cpu" | |
| 101 | + | |
| 102 | + return torch.device(device) | |
| 103 | + | |
| 104 | + | |
| 105 | +def get_device_count() -> int: | |
| 106 | + r"""Get the number of available devices.""" | |
| 107 | + if is_torch_xpu_available(): | |
| 108 | + return torch.xpu.device_count() | |
| 109 | + elif is_torch_npu_available(): | |
| 110 | + return torch.npu.device_count() | |
| 111 | + elif is_torch_mps_available(): | |
| 112 | + return torch.mps.device_count() | |
| 113 | + elif is_torch_cuda_available(): | |
| 114 | + return torch.cuda.device_count() | |
| 115 | + else: | |
| 116 | + return 0 | |
| 117 | + | |
| 118 | + | |
| 119 | +def check_dependencies() -> None: | |
| 120 | + r""" | |
| 121 | + Checks the version of the required packages. | |
| 122 | + """ | |
| 123 | + check_version("transformers>=4.41.2,<=4.46.1") | |
| 124 | + check_version("datasets>=2.16.0,<=3.6.0") | |
| 125 | + check_version("accelerate>=0.34.0,<=1.7.0") |
added spatiallm/tuner/hparams/__init__.py +34 −0
| @@ -0,0 +1,34 @@ | ||
| 1 | +# Copyright 2025 the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 | +# you may not use this file except in compliance with the License. | |
| 5 | +# You may obtain a copy of the License at | |
| 6 | +# | |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 | +# | |
| 9 | +# Unless required by applicable law or agreed to in writing, software | |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 | +# See the License for the specific language governing permissions and | |
| 13 | +# limitations under the License. | |
| 14 | + | |
| 15 | +from .data_args import DataArguments | |
| 16 | +from .finetuning_args import FinetuningArguments | |
| 17 | +from .generating_args import GeneratingArguments | |
| 18 | +from .model_args import ModelArguments | |
| 19 | +from .parser import ( | |
| 20 | + get_train_args, | |
| 21 | + read_args, | |
| 22 | +) | |
| 23 | +from .training_args import TrainingArguments | |
| 24 | + | |
| 25 | + | |
| 26 | +__all__ = [ | |
| 27 | + "DataArguments", | |
| 28 | + "FinetuningArguments", | |
| 29 | + "GeneratingArguments", | |
| 30 | + "ModelArguments", | |
| 31 | + "TrainingArguments", | |
| 32 | + "get_train_args", | |
| 33 | + "read_args", | |
| 34 | +] |
added spatiallm/tuner/hparams/data_args.py +150 −0
| @@ -0,0 +1,150 @@ | ||
| 1 | +# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# This code is inspired by the HuggingFace's transformers library. | |
| 4 | +# https://github.com/huggingface/transformers/blob/v4.40.0/examples/pytorch/language-modeling/run_clm.py | |
| 5 | +# | |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 7 | +# you may not use this file except in compliance with the License. | |
| 8 | +# You may obtain a copy of the License at | |
| 9 | +# | |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 11 | +# | |
| 12 | +# Unless required by applicable law or agreed to in writing, software | |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 15 | +# See the License for the specific language governing permissions and | |
| 16 | +# limitations under the License. | |
| 17 | + | |
| 18 | +from dataclasses import asdict, dataclass, field | |
| 19 | +from typing import Any, Literal, Optional | |
| 20 | + | |
| 21 | + | |
| 22 | +@dataclass | |
| 23 | +class DataArguments: | |
| 24 | + r"""Arguments pertaining to what data we are going to input our model for training and evaluation.""" | |
| 25 | + | |
| 26 | + template: Optional[str] = field( | |
| 27 | + default=None, | |
| 28 | + metadata={ | |
| 29 | + "help": "Which template to use for constructing prompts in training and inference." | |
| 30 | + }, | |
| 31 | + ) | |
| 32 | + dataset: Optional[str] = field( | |
| 33 | + default=None, | |
| 34 | + metadata={ | |
| 35 | + "help": "The name of dataset(s) to use for training. Use commas to separate multiple datasets." | |
| 36 | + }, | |
| 37 | + ) | |
| 38 | + eval_dataset: Optional[str] = field( | |
| 39 | + default=None, | |
| 40 | + metadata={ | |
| 41 | + "help": "The name of dataset(s) to use for evaluation. Use commas to separate multiple datasets." | |
| 42 | + }, | |
| 43 | + ) | |
| 44 | + dataset_dir: str = field( | |
| 45 | + default="data", | |
| 46 | + metadata={"help": "Path to the folder containing the datasets."}, | |
| 47 | + ) | |
| 48 | + media_dir: Optional[str] = field( | |
| 49 | + default=None, | |
| 50 | + metadata={ | |
| 51 | + "help": "Path to the folder containing the images, videos or audios. Defaults to `dataset_dir`." | |
| 52 | + }, | |
| 53 | + ) | |
| 54 | + cutoff_len: int = field( | |
| 55 | + default=8192, | |
| 56 | + metadata={"help": "The cutoff length of the tokenized inputs in the dataset."}, | |
| 57 | + ) | |
| 58 | + overwrite_cache: bool = field( | |
| 59 | + default=False, | |
| 60 | + metadata={"help": "Overwrite the cached training and evaluation sets."}, | |
| 61 | + ) | |
| 62 | + preprocessing_batch_size: int = field( | |
| 63 | + default=1000, | |
| 64 | + metadata={"help": "The number of examples in one group in pre-processing."}, | |
| 65 | + ) | |
| 66 | + preprocessing_num_workers: Optional[int] = field( | |
| 67 | + default=None, | |
| 68 | + metadata={"help": "The number of processes to use for the pre-processing."}, | |
| 69 | + ) | |
| 70 | + max_samples: Optional[int] = field( | |
| 71 | + default=None, | |
| 72 | + metadata={ | |
| 73 | + "help": "For debugging purposes, truncate the number of examples for each dataset." | |
| 74 | + }, | |
| 75 | + ) | |
| 76 | + eval_num_beams: Optional[int] = field( | |
| 77 | + default=None, | |
| 78 | + metadata={ | |
| 79 | + "help": "Number of beams to use for evaluation. This argument will be passed to `model.generate`" | |
| 80 | + }, | |
| 81 | + ) | |
| 82 | + ignore_pad_token_for_loss: bool = field( | |
| 83 | + default=True, | |
| 84 | + metadata={ | |
| 85 | + "help": "Whether or not to ignore the tokens corresponding to the pad label in loss computation." | |
| 86 | + }, | |
| 87 | + ) | |
| 88 | + val_size: float = field( | |
| 89 | + default=0.0, | |
| 90 | + metadata={ | |
| 91 | + "help": "Size of the validation set, should be an integer or a float in range `[0,1)`." | |
| 92 | + }, | |
| 93 | + ) | |
| 94 | + eval_on_each_dataset: bool = field( | |
| 95 | + default=False, | |
| 96 | + metadata={"help": "Whether or not to evaluate on each dataset separately."}, | |
| 97 | + ) | |
| 98 | + default_system: Optional[str] = field( | |
| 99 | + default=None, | |
| 100 | + metadata={"help": "Override the default system message in the template."}, | |
| 101 | + ) | |
| 102 | + save_dir: Optional[str] = field( | |
| 103 | + default=None, | |
| 104 | + metadata={ | |
| 105 | + "help": ( | |
| 106 | + "Path to save or load the preprocessed datasets. " | |
| 107 | + "If save_dir not exists, it will save the preprocessed datasets. " | |
| 108 | + "If save_dir exists, it will load the preprocessed datasets." | |
| 109 | + ) | |
| 110 | + }, | |
| 111 | + ) | |
| 112 | + data_shared_file_system: bool = field( | |
| 113 | + default=False, | |
| 114 | + metadata={ | |
| 115 | + "help": "Whether or not to use a shared file system for the datasets." | |
| 116 | + }, | |
| 117 | + ) | |
| 118 | + num_bins: int = field( | |
| 119 | + default=1280, | |
| 120 | + metadata={"help": "The number of bins for point cloud quantization."}, | |
| 121 | + ) | |
| 122 | + do_augmentation: bool = field( | |
| 123 | + default=False, | |
| 124 | + metadata={"help": "Whether or not to do data augmentation."}, | |
| 125 | + ) | |
| 126 | + random_rotation: bool = field( | |
| 127 | + default=False, | |
| 128 | + metadata={"help": "Whether or not to do non axis-aligned random rotation."}, | |
| 129 | + ) | |
| 130 | + | |
| 131 | + def __post_init__(self): | |
| 132 | + def split_arg(arg): | |
| 133 | + if isinstance(arg, str): | |
| 134 | + return [item.strip() for item in arg.split(",")] | |
| 135 | + return arg | |
| 136 | + | |
| 137 | + self.dataset = split_arg(self.dataset) | |
| 138 | + self.eval_dataset = split_arg(self.eval_dataset) | |
| 139 | + | |
| 140 | + if self.media_dir is None: | |
| 141 | + self.media_dir = self.dataset_dir | |
| 142 | + | |
| 143 | + if self.dataset is None and self.val_size > 1e-6: | |
| 144 | + raise ValueError("Cannot specify `val_size` if `dataset` is None.") | |
| 145 | + | |
| 146 | + if self.eval_dataset is not None and self.val_size > 1e-6: | |
| 147 | + raise ValueError("Cannot specify `val_size` if `eval_dataset` is not None.") | |
| 148 | + | |
| 149 | + def to_dict(self) -> dict[str, Any]: | |
| 150 | + return asdict(self) |
added spatiallm/tuner/hparams/finetuning_args.py +89 −0
| @@ -0,0 +1,89 @@ | ||
| 1 | +# Copyright 2025 the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 | +# you may not use this file except in compliance with the License. | |
| 5 | +# You may obtain a copy of the License at | |
| 6 | +# | |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 | +# | |
| 9 | +# Unless required by applicable law or agreed to in writing, software | |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 | +# See the License for the specific language governing permissions and | |
| 13 | +# limitations under the License. | |
| 14 | + | |
| 15 | +from dataclasses import asdict, dataclass, field | |
| 16 | +from typing import Any, Literal, Optional | |
| 17 | + | |
| 18 | + | |
| 19 | +@dataclass | |
| 20 | +class SwanLabArguments: | |
| 21 | + use_swanlab: bool = field( | |
| 22 | + default=False, | |
| 23 | + metadata={ | |
| 24 | + "help": "Whether or not to use the SwanLab (an experiment tracking and visualization tool)." | |
| 25 | + }, | |
| 26 | + ) | |
| 27 | + swanlab_project: Optional[str] = field( | |
| 28 | + default="llamafactory", | |
| 29 | + metadata={"help": "The project name in SwanLab."}, | |
| 30 | + ) | |
| 31 | + swanlab_workspace: Optional[str] = field( | |
| 32 | + default=None, | |
| 33 | + metadata={"help": "The workspace name in SwanLab."}, | |
| 34 | + ) | |
| 35 | + swanlab_run_name: Optional[str] = field( | |
| 36 | + default=None, | |
| 37 | + metadata={"help": "The experiment name in SwanLab."}, | |
| 38 | + ) | |
| 39 | + swanlab_mode: Literal["cloud", "local"] = field( | |
| 40 | + default="cloud", | |
| 41 | + metadata={"help": "The mode of SwanLab."}, | |
| 42 | + ) | |
| 43 | + swanlab_api_key: Optional[str] = field( | |
| 44 | + default=None, | |
| 45 | + metadata={"help": "The API key for SwanLab."}, | |
| 46 | + ) | |
| 47 | + swanlab_logdir: Optional[str] = field( | |
| 48 | + default=None, | |
| 49 | + metadata={"help": "The log directory for SwanLab."}, | |
| 50 | + ) | |
| 51 | + swanlab_lark_webhook_url: Optional[str] = field( | |
| 52 | + default=None, | |
| 53 | + metadata={"help": "The Lark(飞书) webhook URL for SwanLab."}, | |
| 54 | + ) | |
| 55 | + swanlab_lark_secret: Optional[str] = field( | |
| 56 | + default=None, | |
| 57 | + metadata={"help": "The Lark(飞书) secret for SwanLab."}, | |
| 58 | + ) | |
| 59 | + | |
| 60 | + | |
| 61 | +@dataclass | |
| 62 | +class FinetuningArguments(SwanLabArguments): | |
| 63 | + r"""Arguments pertaining to which techniques we are going to fine-tuning with.""" | |
| 64 | + | |
| 65 | + pure_bf16: bool = field( | |
| 66 | + default=False, | |
| 67 | + metadata={ | |
| 68 | + "help": "Whether or not to train model in purely bf16 precision (without AMP)." | |
| 69 | + }, | |
| 70 | + ) | |
| 71 | + freeze_language_tower: bool = field( | |
| 72 | + default=False, | |
| 73 | + metadata={"help": "Whether ot not to freeze language tower in training."}, | |
| 74 | + ) | |
| 75 | + freeze_point_tower: bool = field( | |
| 76 | + default=False, | |
| 77 | + metadata={"help": "Whether ot not to freeze point tower in training."}, | |
| 78 | + ) | |
| 79 | + train_proj_only: bool = field( | |
| 80 | + default=False, | |
| 81 | + metadata={"help": "Whether or not to train the projector only."}, | |
| 82 | + ) | |
| 83 | + | |
| 84 | + def to_dict(self) -> dict[str, Any]: | |
| 85 | + args = asdict(self) | |
| 86 | + args = { | |
| 87 | + k: f"<{k.upper()}>" if k.endswith("api_key") else v for k, v in args.items() | |
| 88 | + } | |
| 89 | + return args |
added spatiallm/tuner/hparams/generating_args.py +83 −0
| @@ -0,0 +1,83 @@ | ||
| 1 | +# Copyright 2025 the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 | +# you may not use this file except in compliance with the License. | |
| 5 | +# You may obtain a copy of the License at | |
| 6 | +# | |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 | +# | |
| 9 | +# Unless required by applicable law or agreed to in writing, software | |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 | +# See the License for the specific language governing permissions and | |
| 13 | +# limitations under the License. | |
| 14 | + | |
| 15 | +from dataclasses import asdict, dataclass, field | |
| 16 | +from typing import Any | |
| 17 | + | |
| 18 | +from transformers import GenerationConfig | |
| 19 | + | |
| 20 | + | |
| 21 | +@dataclass | |
| 22 | +class GeneratingArguments: | |
| 23 | + r"""Arguments pertaining to specify the decoding parameters.""" | |
| 24 | + | |
| 25 | + do_sample: bool = field( | |
| 26 | + default=True, | |
| 27 | + metadata={"help": "Whether or not to use sampling, use greedy decoding otherwise."}, | |
| 28 | + ) | |
| 29 | + temperature: float = field( | |
| 30 | + default=0.95, | |
| 31 | + metadata={"help": "The value used to modulate the next token probabilities."}, | |
| 32 | + ) | |
| 33 | + top_p: float = field( | |
| 34 | + default=0.7, | |
| 35 | + metadata={ | |
| 36 | + "help": ( | |
| 37 | + "The smallest set of most probable tokens with probabilities that add up to top_p or higher are kept." | |
| 38 | + ) | |
| 39 | + }, | |
| 40 | + ) | |
| 41 | + top_k: int = field( | |
| 42 | + default=50, | |
| 43 | + metadata={"help": "The number of highest probability vocabulary tokens to keep for top-k filtering."}, | |
| 44 | + ) | |
| 45 | + num_beams: int = field( | |
| 46 | + default=1, | |
| 47 | + metadata={"help": "Number of beams for beam search. 1 means no beam search."}, | |
| 48 | + ) | |
| 49 | + max_length: int = field( | |
| 50 | + default=1024, | |
| 51 | + metadata={"help": "The maximum length the generated tokens can have. It can be overridden by max_new_tokens."}, | |
| 52 | + ) | |
| 53 | + max_new_tokens: int = field( | |
| 54 | + default=1024, | |
| 55 | + metadata={"help": "The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt."}, | |
| 56 | + ) | |
| 57 | + repetition_penalty: float = field( | |
| 58 | + default=1.0, | |
| 59 | + metadata={"help": "The parameter for repetition penalty. 1.0 means no penalty."}, | |
| 60 | + ) | |
| 61 | + length_penalty: float = field( | |
| 62 | + default=1.0, | |
| 63 | + metadata={"help": "Exponential penalty to the length that is used with beam-based generation."}, | |
| 64 | + ) | |
| 65 | + skip_special_tokens: bool = field( | |
| 66 | + default=True, | |
| 67 | + metadata={"help": "Whether or not to remove special tokens in the decoding."}, | |
| 68 | + ) | |
| 69 | + | |
| 70 | + def to_dict(self, obey_generation_config: bool = False) -> dict[str, Any]: | |
| 71 | + args = asdict(self) | |
| 72 | + if args.get("max_new_tokens", -1) > 0: | |
| 73 | + args.pop("max_length", None) | |
| 74 | + else: | |
| 75 | + args.pop("max_new_tokens", None) | |
| 76 | + | |
| 77 | + if obey_generation_config: | |
| 78 | + generation_config = GenerationConfig() | |
| 79 | + for key in list(args.keys()): | |
| 80 | + if not hasattr(generation_config, key): | |
| 81 | + args.pop(key) | |
| 82 | + | |
| 83 | + return args |
added spatiallm/tuner/hparams/model_args.py +239 −0
| @@ -0,0 +1,239 @@ | ||
| 1 | +# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# This code is inspired by the HuggingFace's transformers library. | |
| 4 | +# https://github.com/huggingface/transformers/blob/v4.40.0/examples/pytorch/language-modeling/run_clm.py | |
| 5 | +# | |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 7 | +# you may not use this file except in compliance with the License. | |
| 8 | +# You may obtain a copy of the License at | |
| 9 | +# | |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 11 | +# | |
| 12 | +# Unless required by applicable law or agreed to in writing, software | |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 15 | +# See the License for the specific language governing permissions and | |
| 16 | +# limitations under the License. | |
| 17 | + | |
| 18 | +from dataclasses import asdict, dataclass, field, fields | |
| 19 | +from typing import Any, Literal, Optional, Union | |
| 20 | + | |
| 21 | +import torch | |
| 22 | +from typing_extensions import Self | |
| 23 | + | |
| 24 | +from ..network import AttentionFunction, RopeScaling | |
| 25 | + | |
| 26 | + | |
| 27 | +@dataclass | |
| 28 | +class BaseModelArguments: | |
| 29 | + r"""Arguments pertaining to the model.""" | |
| 30 | + | |
| 31 | + model_name_or_path: Optional[str] = field( | |
| 32 | + default=None, | |
| 33 | + metadata={ | |
| 34 | + "help": "Path to the model weight or identifier from huggingface.co/models or modelscope.cn/models." | |
| 35 | + }, | |
| 36 | + ) | |
| 37 | + cache_dir: Optional[str] = field( | |
| 38 | + default=None, | |
| 39 | + metadata={ | |
| 40 | + "help": "Where to store the pre-trained models downloaded from huggingface.co or modelscope.cn." | |
| 41 | + }, | |
| 42 | + ) | |
| 43 | + use_fast_tokenizer: bool = field( | |
| 44 | + default=True, | |
| 45 | + metadata={ | |
| 46 | + "help": "Whether or not to use one of the fast tokenizer (backed by the tokenizers library)." | |
| 47 | + }, | |
| 48 | + ) | |
| 49 | + resize_vocab: bool = field( | |
| 50 | + default=False, | |
| 51 | + metadata={ | |
| 52 | + "help": "Whether or not to resize the tokenizer vocab and the embedding layers." | |
| 53 | + }, | |
| 54 | + ) | |
| 55 | + split_special_tokens: bool = field( | |
| 56 | + default=False, | |
| 57 | + metadata={ | |
| 58 | + "help": "Whether or not the special tokens should be split during the tokenization process." | |
| 59 | + }, | |
| 60 | + ) | |
| 61 | + add_tokens: Optional[str] = field( | |
| 62 | + default=None, | |
| 63 | + metadata={ | |
| 64 | + "help": "Non-special tokens to be added into the tokenizer. Use commas to separate multiple tokens." | |
| 65 | + }, | |
| 66 | + ) | |
| 67 | + add_special_tokens: Optional[str] = field( | |
| 68 | + default=None, | |
| 69 | + metadata={ | |
| 70 | + "help": "Special tokens to be added into the tokenizer. Use commas to separate multiple tokens." | |
| 71 | + }, | |
| 72 | + ) | |
| 73 | + model_revision: str = field( | |
| 74 | + default="main", | |
| 75 | + metadata={ | |
| 76 | + "help": "The specific model version to use (can be a branch name, tag name or commit id)." | |
| 77 | + }, | |
| 78 | + ) | |
| 79 | + low_cpu_mem_usage: bool = field( | |
| 80 | + default=True, | |
| 81 | + metadata={"help": "Whether or not to use memory-efficient model loading."}, | |
| 82 | + ) | |
| 83 | + rope_scaling: Optional[RopeScaling] = field( | |
| 84 | + default=None, | |
| 85 | + metadata={ | |
| 86 | + "help": "Which scaling strategy should be adopted for the RoPE embeddings." | |
| 87 | + }, | |
| 88 | + ) | |
| 89 | + flash_attn: AttentionFunction = field( | |
| 90 | + default=AttentionFunction.AUTO, | |
| 91 | + metadata={"help": "Enable FlashAttention for faster training and inference."}, | |
| 92 | + ) | |
| 93 | + disable_gradient_checkpointing: bool = field( | |
| 94 | + default=False, | |
| 95 | + metadata={"help": "Whether or not to disable gradient checkpointing."}, | |
| 96 | + ) | |
| 97 | + use_reentrant_gc: bool = field( | |
| 98 | + default=True, | |
| 99 | + metadata={"help": "Whether or not to use reentrant gradient checkpointing."}, | |
| 100 | + ) | |
| 101 | + train_from_scratch: bool = field( | |
| 102 | + default=False, | |
| 103 | + metadata={"help": "Whether or not to randomly initialize the model weights."}, | |
| 104 | + ) | |
| 105 | + offload_folder: str = field( | |
| 106 | + default="offload", | |
| 107 | + metadata={"help": "Path to offload model weights."}, | |
| 108 | + ) | |
| 109 | + use_cache: bool = field( | |
| 110 | + default=True, | |
| 111 | + metadata={"help": "Whether or not to use KV cache in generation."}, | |
| 112 | + ) | |
| 113 | + infer_dtype: Literal["auto", "float16", "bfloat16", "float32"] = field( | |
| 114 | + default="auto", | |
| 115 | + metadata={"help": "Data type for model weights and activations at inference."}, | |
| 116 | + ) | |
| 117 | + hf_hub_token: Optional[str] = field( | |
| 118 | + default=None, | |
| 119 | + metadata={"help": "Auth token to log in with Hugging Face Hub."}, | |
| 120 | + ) | |
| 121 | + ms_hub_token: Optional[str] = field( | |
| 122 | + default=None, | |
| 123 | + metadata={"help": "Auth token to log in with ModelScope Hub."}, | |
| 124 | + ) | |
| 125 | + print_param_status: bool = field( | |
| 126 | + default=False, | |
| 127 | + metadata={ | |
| 128 | + "help": "For debugging purposes, print the status of the parameters in the model." | |
| 129 | + }, | |
| 130 | + ) | |
| 131 | + trust_remote_code: bool = field( | |
| 132 | + default=False, | |
| 133 | + metadata={ | |
| 134 | + "help": "Whether to trust the execution of code from datasets/models defined on the Hub or not." | |
| 135 | + }, | |
| 136 | + ) | |
| 137 | + | |
| 138 | + def __post_init__(self): | |
| 139 | + if self.model_name_or_path is None: | |
| 140 | + raise ValueError("Please provide `model_name_or_path`.") | |
| 141 | + | |
| 142 | + if self.split_special_tokens and self.use_fast_tokenizer: | |
| 143 | + raise ValueError( | |
| 144 | + "`split_special_tokens` is only supported for slow tokenizers." | |
| 145 | + ) | |
| 146 | + | |
| 147 | + if self.add_tokens is not None: # support multiple tokens | |
| 148 | + self.add_tokens = [token.strip() for token in self.add_tokens.split(",")] | |
| 149 | + | |
| 150 | + if self.add_special_tokens is not None: # support multiple special tokens | |
| 151 | + self.add_special_tokens = [ | |
| 152 | + token.strip() for token in self.add_special_tokens.split(",") | |
| 153 | + ] | |
| 154 | + | |
| 155 | + | |
| 156 | +@dataclass | |
| 157 | +class ExportArguments: | |
| 158 | + r"""Arguments pertaining to the model export.""" | |
| 159 | + | |
| 160 | + export_dir: Optional[str] = field( | |
| 161 | + default=None, | |
| 162 | + metadata={"help": "Path to the directory to save the exported model."}, | |
| 163 | + ) | |
| 164 | + export_size: int = field( | |
| 165 | + default=5, | |
| 166 | + metadata={"help": "The file shard size (in GB) of the exported model."}, | |
| 167 | + ) | |
| 168 | + export_device: Literal["cpu", "auto"] = field( | |
| 169 | + default="cpu", | |
| 170 | + metadata={ | |
| 171 | + "help": "The device used in model export, use `auto` to accelerate exporting." | |
| 172 | + }, | |
| 173 | + ) | |
| 174 | + | |
| 175 | + | |
| 176 | +@dataclass | |
| 177 | +class ModelArguments( | |
| 178 | + ExportArguments, | |
| 179 | + BaseModelArguments, | |
| 180 | +): | |
| 181 | + r"""Arguments pertaining to which model/config/tokenizer we are going to fine-tune or infer. | |
| 182 | + | |
| 183 | + The class on the most right will be displayed first. | |
| 184 | + """ | |
| 185 | + | |
| 186 | + compute_dtype: Optional[torch.dtype] = field( | |
| 187 | + default=None, | |
| 188 | + init=False, | |
| 189 | + metadata={ | |
| 190 | + "help": "Torch data type for computing model outputs, derived from `fp/bf16`. Do not specify it." | |
| 191 | + }, | |
| 192 | + ) | |
| 193 | + device_map: Optional[Union[str, dict[str, Any]]] = field( | |
| 194 | + default=None, | |
| 195 | + init=False, | |
| 196 | + metadata={ | |
| 197 | + "help": "Device map for model placement, derived from training stage. Do not specify it." | |
| 198 | + }, | |
| 199 | + ) | |
| 200 | + model_max_length: Optional[int] = field( | |
| 201 | + default=None, | |
| 202 | + init=False, | |
| 203 | + metadata={ | |
| 204 | + "help": "The maximum input length for model, derived from `cutoff_len`. Do not specify it." | |
| 205 | + }, | |
| 206 | + ) | |
| 207 | + block_diag_attn: bool = field( | |
| 208 | + default=False, | |
| 209 | + init=False, | |
| 210 | + metadata={ | |
| 211 | + "help": "Whether use block diag attention or not, derived from `neat_packing`. Do not specify it." | |
| 212 | + }, | |
| 213 | + ) | |
| 214 | + | |
| 215 | + def __post_init__(self): | |
| 216 | + BaseModelArguments.__post_init__(self) | |
| 217 | + | |
| 218 | + @classmethod | |
| 219 | + def copyfrom(cls, source: "Self", **kwargs) -> "Self": | |
| 220 | + init_args, lazy_args = {}, {} | |
| 221 | + for attr in fields(source): | |
| 222 | + if attr.init: | |
| 223 | + init_args[attr.name] = getattr(source, attr.name) | |
| 224 | + else: | |
| 225 | + lazy_args[attr.name] = getattr(source, attr.name) | |
| 226 | + | |
| 227 | + init_args.update(kwargs) | |
| 228 | + result = cls(**init_args) | |
| 229 | + for name, value in lazy_args.items(): | |
| 230 | + setattr(result, name, value) | |
| 231 | + | |
| 232 | + return result | |
| 233 | + | |
| 234 | + def to_dict(self) -> dict[str, Any]: | |
| 235 | + args = asdict(self) | |
| 236 | + args = { | |
| 237 | + k: f"<{k.upper()}>" if k.endswith("token") else v for k, v in args.items() | |
| 238 | + } | |
| 239 | + return args |
added spatiallm/tuner/hparams/parser.py +240 −0
| @@ -0,0 +1,240 @@ | ||
| 1 | +# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# This code is inspired by the HuggingFace's transformers library. | |
| 4 | +# https://github.com/huggingface/transformers/blob/v4.40.0/examples/pytorch/language-modeling/run_clm.py | |
| 5 | +# | |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 7 | +# you may not use this file except in compliance with the License. | |
| 8 | +# You may obtain a copy of the License at | |
| 9 | +# | |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 11 | +# | |
| 12 | +# Unless required by applicable law or agreed to in writing, software | |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 15 | +# See the License for the specific language governing permissions and | |
| 16 | +# limitations under the License. | |
| 17 | + | |
| 18 | +import json | |
| 19 | +import os | |
| 20 | +import sys | |
| 21 | +from pathlib import Path | |
| 22 | +from typing import Any, Optional, Union | |
| 23 | + | |
| 24 | +import torch | |
| 25 | +import transformers | |
| 26 | +import yaml | |
| 27 | +from omegaconf import OmegaConf | |
| 28 | +from transformers import HfArgumentParser | |
| 29 | +from transformers.integrations import is_deepspeed_zero3_enabled | |
| 30 | +from transformers.trainer_utils import get_last_checkpoint | |
| 31 | +from transformers.training_args import ParallelMode | |
| 32 | +from transformers.utils import is_torch_bf16_gpu_available, is_torch_npu_available | |
| 33 | +from transformers.utils import ( | |
| 34 | + SAFE_WEIGHTS_INDEX_NAME, | |
| 35 | + SAFE_WEIGHTS_NAME, | |
| 36 | + WEIGHTS_INDEX_NAME, | |
| 37 | + WEIGHTS_NAME, | |
| 38 | +) | |
| 39 | + | |
| 40 | +from ..framework import logging | |
| 41 | +from ..framework.utils import ( | |
| 42 | + check_dependencies, | |
| 43 | + get_current_device, | |
| 44 | + is_env_enabled, | |
| 45 | +) | |
| 46 | +from .data_args import DataArguments | |
| 47 | +from .finetuning_args import FinetuningArguments | |
| 48 | +from .generating_args import GeneratingArguments | |
| 49 | +from .model_args import ModelArguments | |
| 50 | +from .training_args import TrainingArguments | |
| 51 | + | |
| 52 | +CHECKPOINT_NAMES = { | |
| 53 | + SAFE_WEIGHTS_INDEX_NAME, | |
| 54 | + SAFE_WEIGHTS_NAME, | |
| 55 | + WEIGHTS_INDEX_NAME, | |
| 56 | + WEIGHTS_NAME, | |
| 57 | +} | |
| 58 | +logger = logging.get_logger(__name__) | |
| 59 | + | |
| 60 | +check_dependencies() | |
| 61 | + | |
| 62 | + | |
| 63 | +_TRAIN_ARGS = [ | |
| 64 | + ModelArguments, | |
| 65 | + DataArguments, | |
| 66 | + TrainingArguments, | |
| 67 | + FinetuningArguments, | |
| 68 | + GeneratingArguments, | |
| 69 | +] | |
| 70 | +_TRAIN_CLS = tuple[ | |
| 71 | + ModelArguments, | |
| 72 | + DataArguments, | |
| 73 | + TrainingArguments, | |
| 74 | + FinetuningArguments, | |
| 75 | + GeneratingArguments, | |
| 76 | +] | |
| 77 | + | |
| 78 | + | |
| 79 | +def read_args( | |
| 80 | + args: Optional[Union[dict[str, Any], list[str]]] = None, | |
| 81 | +) -> Union[dict[str, Any], list[str]]: | |
| 82 | + r"""Get arguments from the command line or a config file.""" | |
| 83 | + if args is not None: | |
| 84 | + return args | |
| 85 | + | |
| 86 | + if sys.argv[1].endswith(".yaml") or sys.argv[1].endswith(".yml"): | |
| 87 | + override_config = OmegaConf.from_cli(sys.argv[2:]) | |
| 88 | + dict_config = yaml.safe_load(Path(sys.argv[1]).absolute().read_text()) | |
| 89 | + return OmegaConf.to_container(OmegaConf.merge(dict_config, override_config)) | |
| 90 | + elif sys.argv[1].endswith(".json"): | |
| 91 | + override_config = OmegaConf.from_cli(sys.argv[2:]) | |
| 92 | + dict_config = json.loads(Path(sys.argv[1]).absolute().read_text()) | |
| 93 | + return OmegaConf.to_container(OmegaConf.merge(dict_config, override_config)) | |
| 94 | + else: | |
| 95 | + return sys.argv[1:] | |
| 96 | + | |
| 97 | + | |
| 98 | +def _parse_args( | |
| 99 | + parser: "HfArgumentParser", | |
| 100 | + args: Optional[Union[dict[str, Any], list[str]]] = None, | |
| 101 | + allow_extra_keys: bool = False, | |
| 102 | +) -> tuple[Any]: | |
| 103 | + args = read_args(args) | |
| 104 | + if isinstance(args, dict): | |
| 105 | + return parser.parse_dict(args, allow_extra_keys=allow_extra_keys) | |
| 106 | + | |
| 107 | + (*parsed_args, unknown_args) = parser.parse_args_into_dataclasses( | |
| 108 | + args=args, return_remaining_strings=True | |
| 109 | + ) | |
| 110 | + | |
| 111 | + if unknown_args and not allow_extra_keys: | |
| 112 | + print(parser.format_help()) | |
| 113 | + print(f"Got unknown args, potentially deprecated arguments: {unknown_args}") | |
| 114 | + raise ValueError( | |
| 115 | + f"Some specified arguments are not used by the HfArgumentParser: {unknown_args}" | |
| 116 | + ) | |
| 117 | + | |
| 118 | + return tuple(parsed_args) | |
| 119 | + | |
| 120 | + | |
| 121 | +def _set_transformers_logging() -> None: | |
| 122 | + if os.getenv("LLAMAFACTORY_VERBOSITY", "INFO") in ["DEBUG", "INFO"]: | |
| 123 | + transformers.utils.logging.set_verbosity_info() | |
| 124 | + transformers.utils.logging.enable_default_handler() | |
| 125 | + transformers.utils.logging.enable_explicit_format() | |
| 126 | + | |
| 127 | + | |
| 128 | +def _set_env_vars() -> None: | |
| 129 | + if is_torch_npu_available(): | |
| 130 | + # avoid JIT compile on NPU devices, see https://zhuanlan.zhihu.com/p/660875458 | |
| 131 | + torch.npu.set_compile_mode(jit_compile=is_env_enabled("NPU_JIT_COMPILE")) | |
| 132 | + | |
| 133 | + | |
| 134 | +def _parse_train_args( | |
| 135 | + args: Optional[Union[dict[str, Any], list[str]]] = None, | |
| 136 | +) -> _TRAIN_CLS: | |
| 137 | + parser = HfArgumentParser(_TRAIN_ARGS) | |
| 138 | + allow_extra_keys = is_env_enabled("ALLOW_EXTRA_ARGS") | |
| 139 | + return _parse_args(parser, args, allow_extra_keys=allow_extra_keys) | |
| 140 | + | |
| 141 | + | |
| 142 | +def get_train_args( | |
| 143 | + args: Optional[Union[dict[str, Any], list[str]]] = None, | |
| 144 | +) -> _TRAIN_CLS: | |
| 145 | + model_args, data_args, training_args, finetuning_args, generating_args = ( | |
| 146 | + _parse_train_args(args) | |
| 147 | + ) | |
| 148 | + | |
| 149 | + # Setup logging | |
| 150 | + if training_args.should_log: | |
| 151 | + _set_transformers_logging() | |
| 152 | + | |
| 153 | + if training_args.parallel_mode == ParallelMode.NOT_DISTRIBUTED: | |
| 154 | + raise ValueError( | |
| 155 | + "Please launch distributed training with `llamafactory-cli` or `torchrun`." | |
| 156 | + ) | |
| 157 | + | |
| 158 | + if ( | |
| 159 | + training_args.deepspeed | |
| 160 | + and training_args.parallel_mode != ParallelMode.DISTRIBUTED | |
| 161 | + ): | |
| 162 | + raise ValueError("Please use `FORCE_TORCHRUN=1` to launch DeepSpeed training.") | |
| 163 | + | |
| 164 | + if training_args.do_train and data_args.dataset is None: | |
| 165 | + raise ValueError("Please specify dataset for training.") | |
| 166 | + | |
| 167 | + if training_args.do_eval and ( | |
| 168 | + data_args.eval_dataset is None and data_args.val_size < 1e-6 | |
| 169 | + ): | |
| 170 | + raise ValueError("Please specify dataset for evaluation.") | |
| 171 | + | |
| 172 | + if finetuning_args.pure_bf16: | |
| 173 | + if not ( | |
| 174 | + is_torch_bf16_gpu_available() | |
| 175 | + or (is_torch_npu_available() and torch.npu.is_bf16_supported()) | |
| 176 | + ): | |
| 177 | + raise ValueError("This device does not support `pure_bf16`.") | |
| 178 | + | |
| 179 | + if is_deepspeed_zero3_enabled(): | |
| 180 | + raise ValueError("`pure_bf16` is incompatible with DeepSpeed ZeRO-3.") | |
| 181 | + | |
| 182 | + _set_env_vars() | |
| 183 | + | |
| 184 | + if training_args.do_train and (not training_args.fp16) and (not training_args.bf16): | |
| 185 | + logger.warning_rank0("We recommend enable mixed precision training.") | |
| 186 | + | |
| 187 | + # Post-process training arguments | |
| 188 | + training_args.generation_max_length = ( | |
| 189 | + training_args.generation_max_length or data_args.cutoff_len | |
| 190 | + ) | |
| 191 | + training_args.generation_num_beams = ( | |
| 192 | + data_args.eval_num_beams or training_args.generation_num_beams | |
| 193 | + ) | |
| 194 | + training_args.remove_unused_columns = False # important for multimodal dataset | |
| 195 | + can_resume_from_checkpoint = True | |
| 196 | + | |
| 197 | + if ( | |
| 198 | + training_args.resume_from_checkpoint is None | |
| 199 | + and training_args.do_train | |
| 200 | + and os.path.isdir(training_args.output_dir) | |
| 201 | + and not training_args.overwrite_output_dir | |
| 202 | + and can_resume_from_checkpoint | |
| 203 | + ): | |
| 204 | + last_checkpoint = get_last_checkpoint(training_args.output_dir) | |
| 205 | + if last_checkpoint is None and any( | |
| 206 | + os.path.isfile(os.path.join(training_args.output_dir, name)) | |
| 207 | + for name in CHECKPOINT_NAMES | |
| 208 | + ): | |
| 209 | + raise ValueError( | |
| 210 | + "Output directory already exists and is not empty. Please set `overwrite_output_dir`." | |
| 211 | + ) | |
| 212 | + | |
| 213 | + if last_checkpoint is not None: | |
| 214 | + training_args.resume_from_checkpoint = last_checkpoint | |
| 215 | + logger.info_rank0( | |
| 216 | + f"Resuming training from {training_args.resume_from_checkpoint}." | |
| 217 | + ) | |
| 218 | + logger.info_rank0( | |
| 219 | + "Change `output_dir` or use `overwrite_output_dir` to avoid." | |
| 220 | + ) | |
| 221 | + | |
| 222 | + # Post-process model arguments | |
| 223 | + if training_args.bf16 or finetuning_args.pure_bf16: | |
| 224 | + model_args.compute_dtype = torch.bfloat16 | |
| 225 | + elif training_args.fp16: | |
| 226 | + model_args.compute_dtype = torch.float16 | |
| 227 | + | |
| 228 | + model_args.device_map = {"": get_current_device()} | |
| 229 | + model_args.model_max_length = data_args.cutoff_len | |
| 230 | + | |
| 231 | + # Log on each process the small summary | |
| 232 | + logger.info( | |
| 233 | + f"Process rank: {training_args.process_index}, " | |
| 234 | + f"world size: {training_args.world_size}, device: {training_args.device}, " | |
| 235 | + f"distributed training: {training_args.parallel_mode == ParallelMode.DISTRIBUTED}, " | |
| 236 | + f"compute dtype: {str(model_args.compute_dtype)}" | |
| 237 | + ) | |
| 238 | + transformers.set_seed(training_args.seed) | |
| 239 | + | |
| 240 | + return model_args, data_args, training_args, finetuning_args, generating_args |
added spatiallm/tuner/hparams/training_args.py +26 −0
| @@ -0,0 +1,26 @@ | ||
| 1 | +# Copyright 2025 the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 | +# you may not use this file except in compliance with the License. | |
| 5 | +# You may obtain a copy of the License at | |
| 6 | +# | |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 | +# | |
| 9 | +# Unless required by applicable law or agreed to in writing, software | |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 | +# See the License for the specific language governing permissions and | |
| 13 | +# limitations under the License. | |
| 14 | + | |
| 15 | + | |
| 16 | +from dataclasses import dataclass | |
| 17 | + | |
| 18 | +from transformers import Seq2SeqTrainingArguments | |
| 19 | + | |
| 20 | + | |
| 21 | +@dataclass | |
| 22 | +class TrainingArguments(Seq2SeqTrainingArguments): | |
| 23 | + r"""Arguments pertaining to the trainer.""" | |
| 24 | + | |
| 25 | + def __post_init__(self): | |
| 26 | + Seq2SeqTrainingArguments.__post_init__(self) |
added spatiallm/tuner/network/__init__.py +22 −0
| @@ -0,0 +1,22 @@ | ||
| 1 | +# Copyright 2025 the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 | +# you may not use this file except in compliance with the License. | |
| 5 | +# You may obtain a copy of the License at | |
| 6 | +# | |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 | +# | |
| 9 | +# Unless required by applicable law or agreed to in writing, software | |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 | +# See the License for the specific language governing permissions and | |
| 13 | +# limitations under the License. | |
| 14 | + | |
| 15 | +from .attention import AttentionFunction | |
| 16 | +from .rope import RopeScaling | |
| 17 | + | |
| 18 | + | |
| 19 | +__all__ = [ | |
| 20 | + "AttentionFunction", | |
| 21 | + "RopeScaling", | |
| 22 | +] |
added spatiallm/tuner/network/attention.py +61 −0
| @@ -0,0 +1,61 @@ | ||
| 1 | +# Copyright 2025 the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 | +# you may not use this file except in compliance with the License. | |
| 5 | +# You may obtain a copy of the License at | |
| 6 | +# | |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 | +# | |
| 9 | +# Unless required by applicable law or agreed to in writing, software | |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 | +# See the License for the specific language governing permissions and | |
| 13 | +# limitations under the License. | |
| 14 | + | |
| 15 | +from enum import Enum | |
| 16 | +from typing import TYPE_CHECKING | |
| 17 | + | |
| 18 | +from transformers.utils import is_flash_attn_2_available, is_torch_sdpa_available | |
| 19 | + | |
| 20 | +from ..framework import logging | |
| 21 | + | |
| 22 | +if TYPE_CHECKING: | |
| 23 | + from transformers import PretrainedConfig | |
| 24 | + | |
| 25 | + from ..hparams import ModelArguments | |
| 26 | + | |
| 27 | +logger = logging.get_logger(__name__) | |
| 28 | + | |
| 29 | + | |
| 30 | +class AttentionFunction(str, Enum): | |
| 31 | + AUTO = "auto" | |
| 32 | + DISABLED = "disabled" | |
| 33 | + SDPA = "sdpa" | |
| 34 | + FA2 = "fa2" | |
| 35 | + | |
| 36 | + | |
| 37 | +def configure_attn_implementation( | |
| 38 | + config: "PretrainedConfig", model_args: "ModelArguments" | |
| 39 | +) -> None: | |
| 40 | + if model_args.flash_attn == AttentionFunction.AUTO: | |
| 41 | + return | |
| 42 | + | |
| 43 | + elif model_args.flash_attn == AttentionFunction.DISABLED: | |
| 44 | + requested_attn_implementation = "eager" | |
| 45 | + | |
| 46 | + elif model_args.flash_attn == AttentionFunction.SDPA: | |
| 47 | + if not is_torch_sdpa_available(): | |
| 48 | + logger.warning_rank0("torch>=2.1.1 is required for SDPA attention.") | |
| 49 | + return | |
| 50 | + | |
| 51 | + requested_attn_implementation = "sdpa" | |
| 52 | + elif model_args.flash_attn == AttentionFunction.FA2: | |
| 53 | + if not is_flash_attn_2_available(): | |
| 54 | + logger.warning_rank0("FlashAttention-2 is not installed.") | |
| 55 | + return | |
| 56 | + | |
| 57 | + requested_attn_implementation = "flash_attention_2" | |
| 58 | + else: | |
| 59 | + raise NotImplementedError(f"Unknown attention type: {model_args.flash_attn}") | |
| 60 | + | |
| 61 | + setattr(config, "_attn_implementation", requested_attn_implementation) |
added spatiallm/tuner/network/checkpointing.py +129 −0
| @@ -0,0 +1,129 @@ | ||
| 1 | +# Copyright 2025 HuggingFace Inc., Daniel Han-Chen & the Unsloth team and the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# This code is inspired by the HuggingFace's Transformers and PEFT library, | |
| 4 | +# https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/modeling_utils.py | |
| 5 | +# https://github.com/huggingface/peft/blob/v0.10.0/src/peft/utils/other.py | |
| 6 | +# and the Unsloth library. | |
| 7 | +# https://github.com/unslothai/unsloth/blob/July-2024/unsloth/models/_utils.py | |
| 8 | +# | |
| 9 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 10 | +# you may not use this file except in compliance with the License. | |
| 11 | +# You may obtain a copy of the License at | |
| 12 | +# | |
| 13 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 14 | +# | |
| 15 | +# Unless required by applicable law or agreed to in writing, software | |
| 16 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 17 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 18 | +# See the License for the specific language governing permissions and | |
| 19 | +# limitations under the License. | |
| 20 | + | |
| 21 | +import inspect | |
| 22 | +from functools import WRAPPER_ASSIGNMENTS, partial, wraps | |
| 23 | +from types import MethodType | |
| 24 | +from typing import TYPE_CHECKING, Any, Callable, Optional, Union | |
| 25 | + | |
| 26 | +import torch | |
| 27 | + | |
| 28 | +from ..framework import logging | |
| 29 | + | |
| 30 | +if TYPE_CHECKING: | |
| 31 | + from transformers import PreTrainedModel | |
| 32 | + | |
| 33 | + from ..hparams import ModelArguments | |
| 34 | + | |
| 35 | +logger = logging.get_logger(__name__) | |
| 36 | + | |
| 37 | + | |
| 38 | +def get_custom_gradient_checkpointing_func( | |
| 39 | + gradient_checkpointing_func: Callable, | |
| 40 | +) -> Callable: | |
| 41 | + r"""Only applies gradient checkpointing to trainable layers.""" | |
| 42 | + | |
| 43 | + @wraps(gradient_checkpointing_func, assigned=WRAPPER_ASSIGNMENTS + ("__self__",)) | |
| 44 | + def custom_gradient_checkpointing_func( | |
| 45 | + func: Callable, *args: Union["torch.Tensor", Any], **kwargs | |
| 46 | + ): | |
| 47 | + if isinstance(func, partial): | |
| 48 | + module: torch.nn.Module = func.func.__self__ | |
| 49 | + else: | |
| 50 | + module: torch.nn.Module = func.__self__ | |
| 51 | + | |
| 52 | + has_grad = False | |
| 53 | + if any(param.requires_grad for param in module.parameters()): | |
| 54 | + has_grad = True | |
| 55 | + for arg in args: | |
| 56 | + if torch.is_tensor(arg) and torch.is_floating_point(arg): | |
| 57 | + arg.requires_grad_(True) | |
| 58 | + break # assume the first tensor is always the hidden states | |
| 59 | + | |
| 60 | + if has_grad: | |
| 61 | + return gradient_checkpointing_func(func, *args, **kwargs) | |
| 62 | + else: | |
| 63 | + return func(*args, **kwargs) | |
| 64 | + | |
| 65 | + return custom_gradient_checkpointing_func | |
| 66 | + | |
| 67 | + | |
| 68 | +def _gradient_checkpointing_enable( | |
| 69 | + self: "PreTrainedModel", | |
| 70 | + gradient_checkpointing_kwargs: Optional[dict[str, Any]] = None, | |
| 71 | +) -> None: | |
| 72 | + r"""Activates gradient checkpointing for the current model. | |
| 73 | + | |
| 74 | + Modification of the original method to enable gradient checkpointing for block-wise optimizer. | |
| 75 | + """ | |
| 76 | + from torch.utils.checkpoint import checkpoint | |
| 77 | + | |
| 78 | + if not self.supports_gradient_checkpointing: | |
| 79 | + raise ValueError( | |
| 80 | + f"{self.__class__.__name__} does not support gradient checkpointing." | |
| 81 | + ) | |
| 82 | + | |
| 83 | + if gradient_checkpointing_kwargs is None: | |
| 84 | + gradient_checkpointing_kwargs = {"use_reentrant": True} | |
| 85 | + | |
| 86 | + gradient_checkpointing_func = partial(checkpoint, **gradient_checkpointing_kwargs) | |
| 87 | + | |
| 88 | + gradient_checkpointing_func = get_custom_gradient_checkpointing_func( | |
| 89 | + gradient_checkpointing_func | |
| 90 | + ) | |
| 91 | + if ( | |
| 92 | + "value" in inspect.signature(self._set_gradient_checkpointing).parameters | |
| 93 | + ): # old GC format | |
| 94 | + self.apply(partial(self._set_gradient_checkpointing, value=True)) | |
| 95 | + self.enable_input_require_grads() | |
| 96 | + logger.warning_rank0_once( | |
| 97 | + "You are using the old GC format, some features (e.g. BAdam) will be invalid." | |
| 98 | + ) | |
| 99 | + else: # have already enabled input require gradients | |
| 100 | + self._set_gradient_checkpointing( | |
| 101 | + enable=True, gradient_checkpointing_func=gradient_checkpointing_func | |
| 102 | + ) | |
| 103 | + | |
| 104 | + | |
| 105 | +def prepare_model_for_training( | |
| 106 | + model: "PreTrainedModel", model_args: "ModelArguments" | |
| 107 | +) -> None: | |
| 108 | + r"""Prepare the model before training.""" | |
| 109 | + if not model_args.disable_gradient_checkpointing: | |
| 110 | + if not getattr(model, "supports_gradient_checkpointing", False): | |
| 111 | + logger.warning_rank0( | |
| 112 | + "Current model does not support gradient checkpointing." | |
| 113 | + ) | |
| 114 | + else: | |
| 115 | + # use_reentrant=False might increase VRAM usage (have not been empirically verified yet) | |
| 116 | + # According to: https://github.com/huggingface/transformers/issues/28339 | |
| 117 | + gradient_checkpointing_enable = partial(_gradient_checkpointing_enable) | |
| 118 | + model.gradient_checkpointing_enable = MethodType( | |
| 119 | + gradient_checkpointing_enable, model | |
| 120 | + ) | |
| 121 | + model.gradient_checkpointing_enable( | |
| 122 | + gradient_checkpointing_kwargs={ | |
| 123 | + "use_reentrant": model_args.use_reentrant_gc | |
| 124 | + } | |
| 125 | + ) | |
| 126 | + setattr( | |
| 127 | + model.config, "use_cache", False | |
| 128 | + ) # turn off when gradient checkpointing is enabled | |
| 129 | + logger.info_rank0("Gradient checkpointing enabled.") |
added spatiallm/tuner/network/rope.py +93 −0
| @@ -0,0 +1,93 @@ | ||
| 1 | +# Copyright 2025 LMSYS and the LlamaFactory team. | |
| 2 | +# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li | |
| 3 | +# | |
| 4 | +# This code is inspired by the LMSYS's FastChat library. | |
| 5 | +# https://github.com/lm-sys/FastChat/blob/v0.2.30/fastchat/train/train.py | |
| 6 | +# | |
| 7 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 8 | +# you may not use this file except in compliance with the License. | |
| 9 | +# You may obtain a copy of the License at | |
| 10 | +# | |
| 11 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 12 | +# | |
| 13 | +# Unless required by applicable law or agreed to in writing, software | |
| 14 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 15 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 16 | +# See the License for the specific language governing permissions and | |
| 17 | +# limitations under the License. | |
| 18 | + | |
| 19 | +import math | |
| 20 | +from enum import Enum | |
| 21 | +from typing import TYPE_CHECKING | |
| 22 | + | |
| 23 | +from ..framework import logging | |
| 24 | + | |
| 25 | +if TYPE_CHECKING: | |
| 26 | + from transformers import PretrainedConfig | |
| 27 | + | |
| 28 | + from ..hparams import ModelArguments | |
| 29 | + | |
| 30 | + | |
| 31 | +class RopeScaling(str, Enum): | |
| 32 | + LINEAR = "linear" | |
| 33 | + DYNAMIC = "dynamic" | |
| 34 | + YARN = "yarn" | |
| 35 | + LLAMA3 = "llama3" | |
| 36 | + | |
| 37 | + | |
| 38 | +logger = logging.get_logger(__name__) | |
| 39 | + | |
| 40 | + | |
| 41 | +def configure_rope(config: "PretrainedConfig", model_args: "ModelArguments") -> None: | |
| 42 | + if model_args.rope_scaling is None: | |
| 43 | + return | |
| 44 | + | |
| 45 | + if not hasattr(config, "rope_scaling"): | |
| 46 | + logger.warning_rank0("Current model does not support RoPE scaling.") | |
| 47 | + return | |
| 48 | + | |
| 49 | + if hasattr(config, "max_position_embeddings"): | |
| 50 | + old_max_length = getattr(config, "max_position_embeddings", None) | |
| 51 | + else: | |
| 52 | + logger.warning_rank0("Cannot find the max position embeddings in the config.") | |
| 53 | + return | |
| 54 | + | |
| 55 | + if model_args.model_max_length is not None: # training | |
| 56 | + if model_args.model_max_length <= old_max_length: | |
| 57 | + logger.warning_rank0( | |
| 58 | + "Input length is smaller than max length. Disabling rope scaling." | |
| 59 | + ) | |
| 60 | + return | |
| 61 | + | |
| 62 | + if model_args.rope_scaling == RopeScaling.DYNAMIC: | |
| 63 | + logger.warning_rank0( | |
| 64 | + "Dynamic NTK scaling may not work well with fine-tuning. " | |
| 65 | + "See: https://github.com/huggingface/transformers/pull/24653" | |
| 66 | + ) | |
| 67 | + | |
| 68 | + rope_factor = float(math.ceil(model_args.model_max_length / old_max_length)) | |
| 69 | + else: # inference | |
| 70 | + rope_factor = 2.0 | |
| 71 | + | |
| 72 | + rope_kwargs = { | |
| 73 | + "rope_type": getattr( | |
| 74 | + model_args.rope_scaling, "value", model_args.rope_scaling | |
| 75 | + ), # handle enum | |
| 76 | + "factor": rope_factor, | |
| 77 | + } | |
| 78 | + setattr(config, "max_position_embeddings", old_max_length * rope_factor) | |
| 79 | + logger.info_rank0( | |
| 80 | + f"Enlarge max model length from {old_max_length} to {old_max_length * rope_factor}." | |
| 81 | + ) | |
| 82 | + | |
| 83 | + if model_args.rope_scaling in [RopeScaling.DYNAMIC, RopeScaling.YARN]: | |
| 84 | + rope_kwargs["original_max_position_embeddings"] = old_max_length | |
| 85 | + elif model_args.rope_scaling == RopeScaling.LLAMA3: | |
| 86 | + rope_kwargs["original_max_position_embeddings"] = old_max_length | |
| 87 | + rope_kwargs["low_freq_factor"] = 1.0 | |
| 88 | + rope_kwargs["high_freq_factor"] = 4.0 | |
| 89 | + | |
| 90 | + setattr(config, "rope_scaling", rope_kwargs) | |
| 91 | + logger.info_rank0( | |
| 92 | + f"Using {rope_kwargs['rope_type']} scaling strategy and setting scaling factor to {rope_kwargs['factor']}." | |
| 93 | + ) |
added spatiallm/tuner/trainer.py +217 −0
| @@ -0,0 +1,217 @@ | ||
| 1 | +from typing import TYPE_CHECKING, Any, Optional, Union | |
| 2 | + | |
| 3 | +import torch | |
| 4 | +import torch.distributed as dist | |
| 5 | +from transformers import Seq2SeqTrainer | |
| 6 | +from typing_extensions import override | |
| 7 | + | |
| 8 | +from spatiallm.tuner.framework import logging | |
| 9 | +from spatiallm.tuner.framework.utils import is_transformers_version_greater_than | |
| 10 | +from spatiallm.tuner.framework.callbacks import ( | |
| 11 | + LogCallback, | |
| 12 | + ReporterCallback, | |
| 13 | + get_swanlab_callback, | |
| 14 | +) | |
| 15 | +from spatiallm.tuner.framework.loader import load_tokenizer, load_model | |
| 16 | +from spatiallm.tuner.hparams import get_train_args, read_args | |
| 17 | +from spatiallm.tuner.data import ( | |
| 18 | + IGNORE_INDEX, | |
| 19 | + get_dataset, | |
| 20 | + get_template_and_fix_tokenizer, | |
| 21 | + register_spatiallm_templates, | |
| 22 | + SFTDataCollatorWith4DAttentionMask, | |
| 23 | +) | |
| 24 | + | |
| 25 | + | |
| 26 | +if TYPE_CHECKING: | |
| 27 | + from transformers import ( | |
| 28 | + PreTrainedTokenizer, | |
| 29 | + ProcessorMixin, | |
| 30 | + Seq2SeqTrainingArguments, | |
| 31 | + TrainerCallback, | |
| 32 | + ) | |
| 33 | + | |
| 34 | + from spatiallm.tuner.hparams import ( | |
| 35 | + DataArguments, | |
| 36 | + FinetuningArguments, | |
| 37 | + GeneratingArguments, | |
| 38 | + ModelArguments, | |
| 39 | + ) | |
| 40 | + | |
| 41 | +logger = logging.get_logger(__name__) | |
| 42 | + | |
| 43 | + | |
| 44 | +class CustomSeq2SeqTrainer(Seq2SeqTrainer): | |
| 45 | + r"""Inherits Seq2SeqTrainer to compute generative metrics such as BLEU and ROUGE.""" | |
| 46 | + | |
| 47 | + def __init__( | |
| 48 | + self, | |
| 49 | + finetuning_args: "FinetuningArguments", | |
| 50 | + gen_kwargs: Optional[dict[str, Any]] = None, | |
| 51 | + **kwargs, | |
| 52 | + ) -> None: | |
| 53 | + if is_transformers_version_greater_than("4.46"): | |
| 54 | + kwargs["processing_class"] = kwargs.pop("tokenizer") | |
| 55 | + else: | |
| 56 | + self.processing_class: PreTrainedTokenizer = kwargs.get("tokenizer") | |
| 57 | + | |
| 58 | + super().__init__(**kwargs) | |
| 59 | + | |
| 60 | + self.finetuning_args = finetuning_args | |
| 61 | + if gen_kwargs is not None: | |
| 62 | + # https://github.com/huggingface/transformers/blob/v4.45.0/src/transformers/trainer_seq2seq.py#L287 | |
| 63 | + self._gen_kwargs = gen_kwargs | |
| 64 | + | |
| 65 | + @override | |
| 66 | + def prediction_step( | |
| 67 | + self, | |
| 68 | + model: "torch.nn.Module", | |
| 69 | + inputs: dict[str, Union["torch.Tensor", Any]], | |
| 70 | + prediction_loss_only: bool, | |
| 71 | + ignore_keys: Optional[list[str]] = None, | |
| 72 | + **gen_kwargs, | |
| 73 | + ) -> tuple[Optional[float], Optional["torch.Tensor"], Optional["torch.Tensor"]]: | |
| 74 | + r"""Remove the prompt part in the generated tokens. | |
| 75 | + | |
| 76 | + Subclass and override to inject custom behavior. | |
| 77 | + """ | |
| 78 | + if self.args.predict_with_generate: # do not pass labels to model when generate | |
| 79 | + labels = inputs.pop("labels", None) | |
| 80 | + else: | |
| 81 | + labels = inputs.get("labels") | |
| 82 | + | |
| 83 | + loss, generated_tokens, _ = super().prediction_step( | |
| 84 | + model, | |
| 85 | + inputs, | |
| 86 | + prediction_loss_only=prediction_loss_only, | |
| 87 | + ignore_keys=ignore_keys, | |
| 88 | + **gen_kwargs, | |
| 89 | + ) | |
| 90 | + if generated_tokens is not None and self.args.predict_with_generate: | |
| 91 | + generated_tokens[:, : inputs["input_ids"].size(-1)] = ( | |
| 92 | + self.processing_class.pad_token_id | |
| 93 | + ) | |
| 94 | + generated_tokens = generated_tokens.contiguous() | |
| 95 | + | |
| 96 | + return loss, generated_tokens, labels | |
| 97 | + | |
| 98 | + | |
| 99 | +def run_sft( | |
| 100 | + model_args: "ModelArguments", | |
| 101 | + data_args: "DataArguments", | |
| 102 | + training_args: "Seq2SeqTrainingArguments", | |
| 103 | + finetuning_args: "FinetuningArguments", | |
| 104 | + generating_args: "GeneratingArguments", | |
| 105 | + callbacks: Optional[list["TrainerCallback"]] = None, | |
| 106 | +): | |
| 107 | + tokenizer_module = load_tokenizer(model_args) | |
| 108 | + tokenizer = tokenizer_module["tokenizer"] | |
| 109 | + | |
| 110 | + register_spatiallm_templates( | |
| 111 | + cutoff_len=data_args.cutoff_len, | |
| 112 | + num_bins=data_args.num_bins, | |
| 113 | + do_augmentation=data_args.do_augmentation, | |
| 114 | + random_rotation=data_args.random_rotation, | |
| 115 | + ) | |
| 116 | + | |
| 117 | + template = get_template_and_fix_tokenizer(tokenizer, data_args) | |
| 118 | + dataset_module = get_dataset(model_args, data_args, training_args) | |
| 119 | + model = load_model( | |
| 120 | + tokenizer, data_args, model_args, finetuning_args, training_args.do_train | |
| 121 | + ) | |
| 122 | + | |
| 123 | + data_collator = SFTDataCollatorWith4DAttentionMask( | |
| 124 | + template=template, | |
| 125 | + model=model if not training_args.predict_with_generate else None, | |
| 126 | + pad_to_multiple_of=( | |
| 127 | + 8 if training_args.do_train else None | |
| 128 | + ), # for shift short attention | |
| 129 | + label_pad_token_id=( | |
| 130 | + IGNORE_INDEX | |
| 131 | + if data_args.ignore_pad_token_for_loss | |
| 132 | + else tokenizer.pad_token_id | |
| 133 | + ), | |
| 134 | + block_diag_attn=model_args.block_diag_attn, | |
| 135 | + attn_implementation=getattr(model.config, "_attn_implementation", None), | |
| 136 | + compute_dtype=model_args.compute_dtype, | |
| 137 | + **tokenizer_module, | |
| 138 | + ) | |
| 139 | + | |
| 140 | + # Keyword arguments for `model.generate` | |
| 141 | + gen_kwargs = generating_args.to_dict(obey_generation_config=True) | |
| 142 | + gen_kwargs["eos_token_id"] = [ | |
| 143 | + tokenizer.eos_token_id | |
| 144 | + ] + tokenizer.additional_special_tokens_ids | |
| 145 | + gen_kwargs["pad_token_id"] = tokenizer.pad_token_id | |
| 146 | + | |
| 147 | + # Initialize our Trainer | |
| 148 | + trainer = CustomSeq2SeqTrainer( | |
| 149 | + model=model, | |
| 150 | + args=training_args, | |
| 151 | + finetuning_args=finetuning_args, | |
| 152 | + data_collator=data_collator, | |
| 153 | + callbacks=callbacks, | |
| 154 | + gen_kwargs=gen_kwargs, | |
| 155 | + **dataset_module, | |
| 156 | + **tokenizer_module, | |
| 157 | + ) | |
| 158 | + | |
| 159 | + # Training | |
| 160 | + if training_args.do_train: | |
| 161 | + train_result = trainer.train( | |
| 162 | + resume_from_checkpoint=training_args.resume_from_checkpoint | |
| 163 | + ) | |
| 164 | + trainer.save_model() | |
| 165 | + | |
| 166 | + trainer.log_metrics("train", train_result.metrics) | |
| 167 | + trainer.save_metrics("train", train_result.metrics) | |
| 168 | + trainer.save_state() | |
| 169 | + | |
| 170 | + # Evaluation | |
| 171 | + if training_args.do_eval: | |
| 172 | + metrics = trainer.evaluate(metric_key_prefix="eval", **gen_kwargs) | |
| 173 | + trainer.log_metrics("eval", metrics) | |
| 174 | + trainer.save_metrics("eval", metrics) | |
| 175 | + | |
| 176 | + | |
| 177 | +def _training_function(config: dict[str, Any]) -> None: | |
| 178 | + args = config.get("args") | |
| 179 | + model_args, data_args, training_args, finetuning_args, generating_args = ( | |
| 180 | + get_train_args(args) | |
| 181 | + ) | |
| 182 | + | |
| 183 | + callbacks: list[Any] = [] | |
| 184 | + callbacks.append(LogCallback()) | |
| 185 | + if finetuning_args.use_swanlab: | |
| 186 | + callbacks.append(get_swanlab_callback(finetuning_args)) | |
| 187 | + | |
| 188 | + callbacks.append( | |
| 189 | + ReporterCallback(model_args, data_args, finetuning_args, generating_args) | |
| 190 | + ) # add to last | |
| 191 | + | |
| 192 | + run_sft( | |
| 193 | + model_args, | |
| 194 | + data_args, | |
| 195 | + training_args, | |
| 196 | + finetuning_args, | |
| 197 | + generating_args, | |
| 198 | + callbacks, | |
| 199 | + ) | |
| 200 | + | |
| 201 | + try: | |
| 202 | + if dist.is_initialized(): | |
| 203 | + dist.destroy_process_group() | |
| 204 | + except Exception as e: | |
| 205 | + logger.warning(f"Failed to destroy process group: {e}.") | |
| 206 | + | |
| 207 | + | |
| 208 | +def run_exp(args: Optional[dict[str, Any]] = None) -> None: | |
| 209 | + args = read_args(args) | |
| 210 | + if "-h" in args or "--help" in args: | |
| 211 | + get_train_args(args) | |
| 212 | + | |
| 213 | + _training_function(config={"args": args}) | |
| 214 | + | |
| 215 | + | |
| 216 | +if __name__ == "__main__": | |
| 217 | + run_exp() |
added train.py +68 −0
| @@ -0,0 +1,68 @@ | ||
| 1 | +# Copyright 2024 the LlamaFactory team. | |
| 2 | +# | |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 | +# you may not use this file except in compliance with the License. | |
| 5 | +# You may obtain a copy of the License at | |
| 6 | +# | |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 | +# | |
| 9 | +# Unless required by applicable law or agreed to in writing, software | |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 | +# See the License for the specific language governing permissions and | |
| 13 | +# limitations under the License. | |
| 14 | + | |
| 15 | +import os | |
| 16 | +import sys | |
| 17 | +import random | |
| 18 | +import subprocess | |
| 19 | +from copy import deepcopy | |
| 20 | + | |
| 21 | +from spatiallm.tuner import trainer | |
| 22 | +from spatiallm.tuner.framework import logging | |
| 23 | +from spatiallm.tuner.framework.utils import get_device_count, is_env_enabled | |
| 24 | +from spatiallm.tuner.trainer import run_exp # use absolute import | |
| 25 | + | |
| 26 | +logger = logging.get_logger(__name__) | |
| 27 | + | |
| 28 | + | |
| 29 | +def main(): | |
| 30 | + force_torchrun = os.getenv("FORCE_TORCHRUN", "0").lower() in ["true", "1"] | |
| 31 | + if force_torchrun or get_device_count() > 1: | |
| 32 | + master_addr = os.getenv("MASTER_ADDR", "127.0.0.1") | |
| 33 | + master_port = os.getenv("MASTER_PORT", str(random.randint(20001, 29999))) | |
| 34 | + logger.info_rank0( | |
| 35 | + f"Initializing distributed tasks at: {master_addr}:{master_port}" | |
| 36 | + ) | |
| 37 | + standalone = os.getenv("STANDALONE", "0").lower() in ["true", "1"] | |
| 38 | + | |
| 39 | + env = deepcopy(os.environ) | |
| 40 | + if is_env_enabled("OPTIM_TORCH", "1"): | |
| 41 | + # optimize DDP, see https://zhuanlan.zhihu.com/p/671834539 | |
| 42 | + env["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" | |
| 43 | + env["TORCH_NCCL_AVOID_RECORD_STREAMS"] = "1" | |
| 44 | + | |
| 45 | + command = ( | |
| 46 | + "torchrun {standalone} --nnodes {nnodes} --node_rank {node_rank} --nproc_per_node {nproc_per_node} " | |
| 47 | + "--master_addr {master_addr} --master_port {master_port} {file_name} {args}" | |
| 48 | + ).format( | |
| 49 | + standalone="--standalone" if standalone else "", | |
| 50 | + nnodes=os.getenv("NNODES", "1"), | |
| 51 | + node_rank=os.getenv("NODE_RANK", "0"), | |
| 52 | + nproc_per_node=os.getenv("NPROC_PER_NODE", str(get_device_count())), | |
| 53 | + master_addr=master_addr, | |
| 54 | + master_port=master_port, | |
| 55 | + file_name=trainer.__file__, | |
| 56 | + args=" ".join(sys.argv[1:]), | |
| 57 | + env=env, | |
| 58 | + check=True, | |
| 59 | + ) | |
| 60 | + logger.info_rank0(f"Running command: {command}") | |
| 61 | + process = subprocess.run(command.split()) | |
| 62 | + sys.exit(process.returncode) | |
| 63 | + else: | |
| 64 | + run_exp() | |
| 65 | + | |
| 66 | + | |
| 67 | +if __name__ == "__main__": | |
| 68 | + main() |