├── .gitignore ├── LICENSE ├── README.md ├── cfg ├── inr_mesh_fit │ ├── dataset │ │ └── manifold.yaml │ ├── main.yaml │ └── opt │ │ └── adam.yaml ├── inr_pc_fit │ ├── dataset │ │ ├── manifold.yaml │ │ ├── modelnet.yaml │ │ ├── scannet.yaml │ │ └── shapenet.yaml │ ├── main.yaml │ └── opt │ │ └── adam.yaml ├── mlp_classify │ ├── dataset │ │ └── manifold.yaml │ ├── loss │ │ └── cross_entropy.yaml │ ├── main.yaml │ ├── network │ │ └── fc.yaml │ ├── opt │ │ ├── adam.yaml │ │ └── adamW.yaml │ └── scheduler │ │ └── onecycle.yaml ├── triplane_mesh_fit │ ├── dataset │ │ └── manifold.yaml │ ├── main.yaml │ └── opt │ │ └── adam.yaml ├── triplane_pcd_fit │ ├── dataset │ │ ├── manifold.yaml │ │ ├── modelnet.yaml │ │ ├── scannet.yaml │ │ └── shapenet.yaml │ ├── main.yaml │ └── opt │ │ └── adam.yaml ├── triplane_pcd_part_fit │ ├── dataset │ │ └── shapenet_part.yaml │ ├── main.yaml │ └── opt │ │ └── adam.yaml ├── triplane_voxel_fit │ ├── dataset │ │ ├── manifold.yaml │ │ └── shapenet.yaml │ ├── main.yaml │ └── opt │ │ └── adam.yaml ├── triplanes_classify │ ├── dataset │ │ ├── manifold.yaml │ │ ├── modelnet.yaml │ │ ├── scannet.yaml │ │ ├── shapenet.yaml │ │ ├── shapenet_nerf.yaml │ │ ├── shapenet_nerf_mlp.yaml │ │ └── shapenet_vox.yaml │ ├── loss │ │ └── cross_entropy.yaml │ ├── main.yaml │ ├── network │ │ ├── cnn.yaml │ │ ├── fc_mlp.yaml │ │ ├── fc_triplane.yaml │ │ └── transformer.yaml │ ├── opt │ │ ├── adam.yaml │ │ └── adamW.yaml │ └── scheduler │ │ └── onecycle.yaml └── triplanes_part_seg │ ├── dataset │ └── shapenet_part_seg.yaml │ ├── loss │ └── cross_entropy.yaml │ ├── main.yaml │ ├── network │ ├── cnn.yaml │ ├── transformer.yaml │ └── transformer_encoder_decoder.yaml │ ├── opt │ ├── adam.yaml │ └── adamW.yaml │ └── scheduler │ └── onecycle.yaml ├── data ├── mesh_inr.py ├── pcd_inr.py ├── pcd_part_inr.py ├── triplanes.py └── voxel_inr.py ├── datamodules └── datamodule.py ├── inr_fit_mesh.py ├── inr_fit_point_cloud.py ├── networks └── networks.py ├── requirements.yaml ├── trainers ├── fit_inr_mesh.py ├── fit_inr_pc.py ├── fit_triplane_mesh.py ├── fit_triplane_pcd.py ├── fit_triplane_pcd_part.py ├── fit_triplane_voxel.py ├── triplane_classifier.py └── triplane_part_seg.py ├── triplane_cls.py ├── triplane_fit_mesh.py ├── triplane_fit_pc.py ├── triplane_fit_pc_part_seg.py ├── triplane_fit_voxel.py └── utils └── var.py /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | reconstructions 3 | experiments* 4 | */__pycache__ 5 | datasets 6 | wandb 7 | mesh_DeepSDF 8 | init 9 | test 10 | qualitatives 11 | launch.sh 12 | **.ipynb 13 | figures 14 | perm_pc 15 | test_pc 16 | reconstructions_manifold 17 | reconstruction_modelnet 18 | reconstrauctions_shapenet_vox -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # triplane_processing 2 | Official code for "Neural Processing of Tri-Plane Hybrid Neural Fields" 3 | 4 | [[Paper](https://arxiv.org/abs/2310.01140)] 5 | 6 | 1) Install conda or mamba (mamba is faster) 7 | 2) Create environment with the command ``` mamba env create -f requirements.yaml ``` 8 | 3) Activate with ``` conda activate triplane ``` 9 | 4) create a sym link to a datasets folder: 10 | ``` mkdir datasets ``` 11 | ``` ln -s path_to_ModelNet40/ datasets/ModelNet40 ``` 12 | 13 | 5) We use Weight&Biases to track our experiments, so you need to create a free acount if you want to run this code. 14 | 15 | Fit triplanes from point clouds with: 16 | ```python triplane_fit_pc.py dataset=manifold``` 17 | Also modify the cfg/triplane_pcd_fit/main.yaml accordingly (out dir folder and weights and biases parameters for example). 18 | 19 | In our case, we fit the same pre augmenred data used in [[inr2vec](https://arxiv.org/abs/2310.01140)], so you need to donwload the data from the corresponding web page. Each INR contains the augmented shape used to fit the INR. We use the augmented shapes contained in these files to fit our tri-planes. 20 | 21 | If you need pre-computed triplanes on the datasets used in the paper, please contact us. 22 | 23 | 24 | Train classifier on triplanes: 25 | ```python triplane_cls.py dataset=modelnet``` 26 | -------------------------------------------------------------------------------- /cfg/inr_mesh_fit/dataset/manifold.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.mesh_inr.MeshInrDataset 2 | inrs_root: datasets/Manifold40/manifold40_h512l4_aug/ 3 | name: Manifold40 -------------------------------------------------------------------------------- /cfg/inr_mesh_fit/main.yaml: -------------------------------------------------------------------------------- 1 | defaults: 2 | - opt: adam 3 | - _self_ 4 | - dataset: manifold 5 | - override hydra/hydra_logging: disabled 6 | - override hydra/job_logging: disabled 7 | 8 | splits: ["val", "test", "train"] 9 | 10 | trainer: 11 | module_name: fit_inr_mesh 12 | 13 | num_points_pcd: 16384 14 | num_queries_on_surface: 100_000 15 | stds: [0.003, 0.01, 0.1] 16 | num_points_per_std: [250_000, 200_000, 25_000, 25_000] 17 | 18 | batch_size: 64 19 | num_points_fitting: 10_000 20 | num_steps: 600 21 | 22 | inr_params: 23 | mlp_hidden_dim: 512 24 | mlp_num_hidden_layers: 4 25 | 26 | wandb: 27 | entity: 3dda 28 | project: triplane_fit_mesh 29 | run_name: ${dataset.name}_INR 30 | dir: experiments_fit_mesh_inr 31 | 32 | hydra: 33 | output_subdir: ${wandb.dir}/${wandb.run_name} 34 | run: 35 | dir: . 36 | 37 | out_root: datasets/${dataset.name}/mesh_INR_h${inr_params.mlp_hidden_dim}l${inr_params.mlp_num_hidden_layers} -------------------------------------------------------------------------------- /cfg/inr_mesh_fit/opt/adam.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.Adam 2 | lr: 1e-4 -------------------------------------------------------------------------------- /cfg/inr_pc_fit/dataset/manifold.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.pcd_inr.PcdInrDataset 2 | inrs_root: datasets/Manifold40/pcds_16384 3 | name: Manifold40 -------------------------------------------------------------------------------- /cfg/inr_pc_fit/dataset/modelnet.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.pcd_inr.PcdInrDataset 2 | inrs_root: datasets/ModelNet40/modelnet40_h512l4_aug/ 3 | name: ModelNet40 -------------------------------------------------------------------------------- /cfg/inr_pc_fit/dataset/scannet.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.pcd_inr.PcdInrDataset 2 | inrs_root: datasets/scannet/scannet_h512l4_aug 3 | name: scannet -------------------------------------------------------------------------------- /cfg/inr_pc_fit/dataset/shapenet.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.pcd_inr.PcdInrDataset 2 | inrs_root: datasets/shapenet/shapenet_h512l4_aug 3 | name: shapenet -------------------------------------------------------------------------------- /cfg/inr_pc_fit/main.yaml: -------------------------------------------------------------------------------- 1 | defaults: 2 | - opt: adam 3 | - _self_ 4 | - dataset: modelnet 5 | - override hydra/hydra_logging: disabled 6 | - override hydra/job_logging: disabled 7 | 8 | splits: ["val", "test", "train"] 9 | 10 | trainer: 11 | module_name: fit_inr_pc 12 | 13 | num_points_pcd: 2048 14 | num_queries_on_surface: 100_000 15 | stds: [0.003, 0.01, 0.1] 16 | num_points_per_std: [250_000, 200_000, 25_000, 25_000] 17 | 18 | batch_size: 64 19 | num_points_fitting: 10_000 20 | num_steps: 1000 21 | 22 | inr_params: 23 | mlp_hidden_dim: 512 24 | mlp_num_hidden_layers: 4 25 | 26 | wandb: 27 | entity: 3dda 28 | project: triplane_fit_pc 29 | run_name: ${dataset.name}_INR 30 | dir: experiments_fit_pc_inr 31 | 32 | hydra: 33 | output_subdir: ${wandb.dir}/${wandb.run_name} 34 | run: 35 | dir: . 36 | 37 | out_root: datasets/${dataset.name}/pcd_INR_h${inr_params.mlp_hidden_dim}l${inr_params.mlp_num_hidden_layers} -------------------------------------------------------------------------------- /cfg/inr_pc_fit/opt/adam.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.Adam 2 | lr: 1e-4 -------------------------------------------------------------------------------- /cfg/mlp_classify/dataset/manifold.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.triplanes.MLPDataset 2 | inrs_root: datasets/Manifold40/mesh_triplane_32_16_h64l3_freq_encoding 3 | name: Manifold40 4 | num_classes: 40 -------------------------------------------------------------------------------- /cfg/mlp_classify/loss/cross_entropy.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.nn.CrossEntropyLoss -------------------------------------------------------------------------------- /cfg/mlp_classify/main.yaml: -------------------------------------------------------------------------------- 1 | defaults: 2 | - opt: adamW 3 | - scheduler: onecycle 4 | - dataset: manifold 5 | - network: fc 6 | - loss: cross_entropy 7 | - _self_ 8 | - override hydra/hydra_logging: disabled 9 | - override hydra/job_logging: disabled 10 | 11 | trainer: 12 | module_name: triplane_classifier 13 | 14 | train: 15 | batch_size: 256 16 | num_epochs: 150 17 | num_workers: 16 18 | 19 | train_transform: 20 | random_crop: 30 21 | gaussian_blur: -1 22 | horizontal_flip: False 23 | vertical_flip: False 24 | 25 | val_transoform: 26 | center_crop: ${train_transform.random_crop} 27 | 28 | val: 29 | batch_size: 256 30 | checkpoint_period: 1 31 | 32 | triplane_params: 33 | hidden_dim: 16 34 | resolution: 32 35 | mlp_hidden_dim: 64 36 | mlp_num_hidden_layers: 3 37 | 38 | runtime: 39 | gpus: 1 40 | precision: 16-mixed 41 | find_unused_parameters: True 42 | 43 | wandb: 44 | entity: 3dda 45 | project: triplane_classifier 46 | run_name: ${dataset.name}-${now:%m-%d}/${now:%H-%M}_FC 47 | dir: experiments_triplane_classifier 48 | 49 | hydra: 50 | output_subdir: ${wandb.dir}/${wandb.run_name}_FC 51 | run: 52 | dir: . -------------------------------------------------------------------------------- /cfg/mlp_classify/network/fc.yaml: -------------------------------------------------------------------------------- 1 | _target_: networks.networks.FC 2 | 3 | embedding_dim: ${triplane_params.resolution} 4 | channels: 48 5 | num_classes: ${dataset.num_classes} 6 | layers_dim: 7 | - 512 8 | - 256 9 | - 128 10 | - 64 11 | -------------------------------------------------------------------------------- /cfg/mlp_classify/opt/adam.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.Adam 2 | lr: 1e-4 3 | weight_decay: 0.01 -------------------------------------------------------------------------------- /cfg/mlp_classify/opt/adamW.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.AdamW 2 | lr: 1e-4 3 | weight_decay: 1e-3 -------------------------------------------------------------------------------- /cfg/mlp_classify/scheduler/onecycle.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.lr_scheduler.OneCycleLR -------------------------------------------------------------------------------- /cfg/triplane_mesh_fit/dataset/manifold.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.mesh_inr.MeshInrDataset 2 | inrs_root: datasets/Manifold40/manifold40_h512l4_aug/ 3 | name: Manifold40 -------------------------------------------------------------------------------- /cfg/triplane_mesh_fit/main.yaml: -------------------------------------------------------------------------------- 1 | defaults: 2 | - opt: adam 3 | - _self_ 4 | - dataset: manifold 5 | - override hydra/hydra_logging: disabled 6 | - override hydra/job_logging: disabled 7 | 8 | splits: ["val", "test", "train"] 9 | 10 | trainer: 11 | module_name: fit_triplane_mesh 12 | 13 | num_points_pcd: 16384 14 | num_queries_on_surface: 100_000 15 | stds: [0.003, 0.01, 0.1] 16 | num_points_per_std: [250_000, 200_000, 25_000, 25_000] 17 | 18 | batch_size: 128 19 | num_points_fitting: 50_000 20 | num_steps: 600 21 | 22 | triplane_params: 23 | hidden_dim: 16 24 | resolution: 32 25 | mlp_hidden_dim: 64 26 | mlp_num_hidden_layers: 3 27 | 28 | wandb: 29 | entity: 3dda 30 | project: triplane_fit_mesh 31 | run_name: ${dataset.name} 32 | dir: experiments_fit_mesh 33 | 34 | hydra: 35 | output_subdir: ${wandb.dir}/${wandb.run_name} 36 | run: 37 | dir: . 38 | 39 | out_root: datasets/${dataset.name}/mesh_triplane_${triplane_params.resolution}_${triplane_params.hidden_dim}_h${triplane_params.mlp_hidden_dim}l${triplane_params.mlp_num_hidden_layers}_freq_encoding -------------------------------------------------------------------------------- /cfg/triplane_mesh_fit/opt/adam.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.Adam 2 | lr: 1e-4 -------------------------------------------------------------------------------- /cfg/triplane_pcd_fit/dataset/manifold.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.pcd_inr.PcdInrDataset 2 | inrs_root: datasets/Manifold40/pcds_16384 3 | name: Manifold40 -------------------------------------------------------------------------------- /cfg/triplane_pcd_fit/dataset/modelnet.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.pcd_inr.PcdInrDataset 2 | inrs_root: datasets/ModelNet40/modelnet40_h512l4_aug/ 3 | name: ModelNet40 -------------------------------------------------------------------------------- /cfg/triplane_pcd_fit/dataset/scannet.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.pcd_inr.PcdInrDataset 2 | inrs_root: datasets/scannet/scannet_h512l4_aug 3 | name: scannet -------------------------------------------------------------------------------- /cfg/triplane_pcd_fit/dataset/shapenet.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.pcd_inr.PcdInrDataset 2 | inrs_root: datasets/shapenet/shapenet_h512l4_aug 3 | name: shapenet -------------------------------------------------------------------------------- /cfg/triplane_pcd_fit/main.yaml: -------------------------------------------------------------------------------- 1 | defaults: 2 | - opt: adam 3 | - _self_ 4 | - dataset: modelnet 5 | - override hydra/hydra_logging: disabled 6 | - override hydra/job_logging: disabled 7 | 8 | splits: ["val", "test", "train"] 9 | 10 | trainer: 11 | module_name: fit_triplane_pcd 12 | 13 | num_points_pcd: 2048 14 | num_queries_on_surface: 100_000 15 | stds: [0.003, 0.01, 0.1] 16 | num_points_per_std: [250_000, 200_000, 25_000, 25_000] 17 | 18 | batch_size: 128 19 | num_points_fitting: 50_000 20 | num_steps: 1000 21 | 22 | triplane_params: 23 | hidden_dim: 16 24 | resolution: 32 25 | mlp_hidden_dim: 64 26 | mlp_num_hidden_layers: 3 27 | 28 | wandb: 29 | entity: 3dda 30 | project: triplane_fit_pcd 31 | run_name: ${dataset.name} 32 | dir: experiments_fit_pcd 33 | 34 | hydra: 35 | output_subdir: ${wandb.dir}/${wandb.run_name} 36 | run: 37 | dir: . 38 | 39 | out_root: datasets/${dataset.name}/pcd_triplane_${triplane_params.resolution}_${triplane_params.hidden_dim}_h${triplane_params.mlp_hidden_dim}l${triplane_params.mlp_num_hidden_layers}_freq_encoding -------------------------------------------------------------------------------- /cfg/triplane_pcd_fit/opt/adam.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.Adam 2 | lr: 1e-4 -------------------------------------------------------------------------------- /cfg/triplane_pcd_part_fit/dataset/shapenet_part.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.pcd_part_inr.PcdPartInrDataset 2 | inrs_root: datasets/shapenet_part/shapenet_partseg_h512l4 3 | name: shapenet_part -------------------------------------------------------------------------------- /cfg/triplane_pcd_part_fit/main.yaml: -------------------------------------------------------------------------------- 1 | defaults: 2 | - opt: adam 3 | - _self_ 4 | - dataset: shapenet_part 5 | - override hydra/hydra_logging: disabled 6 | - override hydra/job_logging: disabled 7 | 8 | splits: ["val", "test", "train"] 9 | 10 | trainer: 11 | module_name: fit_triplane_pcd_part 12 | 13 | num_points_pcd: 2048 14 | num_queries_on_surface: 100_000 15 | stds: [0.003, 0.01, 0.1] 16 | num_points_per_std: [250_000, 200_000, 25_000, 25_000] 17 | 18 | batch_size: 128 19 | num_points_fitting: 50_000 20 | num_steps: 1000 21 | 22 | triplane_params: 23 | hidden_dim: 16 24 | resolution: 32 25 | mlp_hidden_dim: 64 26 | mlp_num_hidden_layers: 3 27 | 28 | wandb: 29 | entity: 3dda 30 | project: triplane_fit_pcd_part 31 | run_name: ${dataset.name} 32 | dir: experiments_fit_pcd_part 33 | 34 | hydra: 35 | output_subdir: ${wandb.dir}/${wandb.run_name} 36 | run: 37 | dir: . 38 | 39 | out_root: datasets/${dataset.name}/pcd_part_triplane_${triplane_params.resolution}_${triplane_params.hidden_dim}_h${triplane_params.mlp_hidden_dim}l${triplane_params.mlp_num_hidden_layers}_freq_encoding -------------------------------------------------------------------------------- /cfg/triplane_pcd_part_fit/opt/adam.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.Adam 2 | lr: 1e-4 -------------------------------------------------------------------------------- /cfg/triplane_voxel_fit/dataset/manifold.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.voxel_inr.VoxelInrDataset 2 | inrs_root: datasets/Manifold40/pcds_16384 3 | name: Manifold40 -------------------------------------------------------------------------------- /cfg/triplane_voxel_fit/dataset/shapenet.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.voxel_inr.VoxelInrDataset 2 | inrs_root: datasets/shapenet_voxels/shapenet_vox_h512l4_aug 3 | name: shapenet -------------------------------------------------------------------------------- /cfg/triplane_voxel_fit/main.yaml: -------------------------------------------------------------------------------- 1 | defaults: 2 | - opt: adam 3 | - _self_ 4 | - dataset: shapenet 5 | - override hydra/hydra_logging: disabled 6 | - override hydra/job_logging: disabled 7 | 8 | splits: ["test", "val", "train"] 9 | 10 | trainer: 11 | module_name: fit_triplane_voxel 12 | 13 | num_points_pcd: 2048 14 | num_queries_on_surface: 100_000 15 | stds: [0.003, 0.01, 0.1] 16 | num_points_per_std: [250_000, 200_000, 25_000, 25_000] 17 | 18 | batch_size: 16 19 | num_points_fitting: 50_000 20 | num_steps: 1000 21 | vox_res: 64 22 | 23 | triplane_params: 24 | hidden_dim: 16 25 | resolution: 32 26 | mlp_hidden_dim: 64 27 | mlp_num_hidden_layers: 3 28 | 29 | wandb: 30 | entity: 3dda 31 | project: triplane_fit_voxel 32 | run_name: ${dataset.name} 33 | dir: experiments_fit_pcd 34 | 35 | hydra: 36 | output_subdir: ${wandb.dir}/${wandb.run_name} 37 | run: 38 | dir: . 39 | 40 | out_root: datasets/${dataset.name}/voxel_triplane_${triplane_params.resolution}_${triplane_params.hidden_dim}_h${triplane_params.mlp_hidden_dim}l${triplane_params.mlp_num_hidden_layers}_freq_encoding_1000_step -------------------------------------------------------------------------------- /cfg/triplane_voxel_fit/opt/adam.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.Adam 2 | lr: 1e-4 -------------------------------------------------------------------------------- /cfg/triplanes_classify/dataset/manifold.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.triplanes.TriplaneDataset 2 | inrs_root: datasets/Manifold40/mesh_triplane_32_16_h64l3_freq_encoding 3 | name: Manifold40 4 | num_classes: 40 -------------------------------------------------------------------------------- /cfg/triplanes_classify/dataset/modelnet.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.triplanes.TriplaneDataset 2 | inrs_root: datasets/ModelNet40/pcd_triplane_32_16_h64l3_freq_encoding 3 | name: modelnet 4 | num_classes: 40 -------------------------------------------------------------------------------- /cfg/triplanes_classify/dataset/scannet.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.triplanes.TriplaneDataset 2 | inrs_root: datasets/scannet/pcd_triplane_32_16_h64l3_freq_encoding 3 | name: scannet 4 | num_classes: 10 -------------------------------------------------------------------------------- /cfg/triplanes_classify/dataset/shapenet.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.triplanes.TriplaneDataset 2 | inrs_root: datasets/shapenet/pcd_triplane_32_16_h64l3_freq_encoding 3 | name: shapenet 4 | num_classes: 10 -------------------------------------------------------------------------------- /cfg/triplanes_classify/dataset/shapenet_nerf.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.triplanes.TriplaneDataset 2 | inrs_root: /media/data5/pier/nerf2vec/nerfacc_nerf2vec/triplane_dataset_h64l3_siren 3 | name: shapenet 4 | num_classes: 13 -------------------------------------------------------------------------------- /cfg/triplanes_classify/dataset/shapenet_nerf_mlp.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.triplanes.MLPDataset 2 | inrs_root: /media/data5/pier/nerf2vec/nerfacc_nerf2vec/mlp_dataset_h128l4_siren 3 | name: shapenet 4 | num_classes: 13 -------------------------------------------------------------------------------- /cfg/triplanes_classify/dataset/shapenet_vox.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.triplanes.TriplaneDataset 2 | inrs_root: datasets/shapenet/voxel_triplane_32_16_h64l3_freq_encoding 3 | name: shapenet_vox 4 | num_classes: 10 -------------------------------------------------------------------------------- /cfg/triplanes_classify/loss/cross_entropy.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.nn.CrossEntropyLoss -------------------------------------------------------------------------------- /cfg/triplanes_classify/main.yaml: -------------------------------------------------------------------------------- 1 | defaults: 2 | - opt: adamW 3 | - scheduler: onecycle 4 | - dataset: modelnet 5 | - network: transformer 6 | - loss: cross_entropy 7 | - _self_ 8 | - override hydra/hydra_logging: disabled 9 | - override hydra/job_logging: disabled 10 | 11 | trainer: 12 | module_name: triplane_classifier 13 | 14 | train: 15 | batch_size: 256 16 | num_epochs: 150 17 | num_workers: 16 18 | 19 | train_transform: 20 | random_crop: 30 21 | gaussian_blur: -1 22 | horizontal_flip: False 23 | vertical_flip: False 24 | 25 | val_transoform: 26 | center_crop: ${train_transform.random_crop} 27 | 28 | val: 29 | batch_size: 256 30 | checkpoint_period: 1 31 | 32 | triplane_params: 33 | hidden_dim: 16 34 | resolution: 32 35 | mlp_hidden_dim: 64 36 | mlp_num_hidden_layers: 3 37 | 38 | runtime: 39 | gpus: 1 40 | precision: 16-mixed 41 | find_unused_parameters: True 42 | 43 | wandb: 44 | entity: 3dda 45 | project: triplane_classifier 46 | run_name: ${dataset.name}-${now:%m-%d}/${now:%H-%M}_TEST_CODE 47 | dir: experiments_triplane_classifier 48 | 49 | hydra: 50 | output_subdir: ${wandb.dir}/${wandb.run_name} 51 | run: 52 | dir: . -------------------------------------------------------------------------------- /cfg/triplanes_classify/network/cnn.yaml: -------------------------------------------------------------------------------- 1 | _target_: networks.networks.CNNEncoder 2 | num_classes: ${dataset.num_classes} 3 | pretrained: False 4 | channels: 48 5 | embedding_dim: ${triplane_params.resolution} 6 | -------------------------------------------------------------------------------- /cfg/triplanes_classify/network/fc_mlp.yaml: -------------------------------------------------------------------------------- 1 | _target_: networks.networks.FC_mlp 2 | 3 | embedding_dim: ${triplane_params.resolution} 4 | channels: 48 5 | num_classes: ${dataset.num_classes} 6 | layers_dim: 7 | - 1024 8 | - 1024 -------------------------------------------------------------------------------- /cfg/triplanes_classify/network/fc_triplane.yaml: -------------------------------------------------------------------------------- 1 | _target_: networks.networks.FC_triplane 2 | 3 | embedding_dim: ${triplane_params.resolution} 4 | channels: 48 5 | num_classes: ${dataset.num_classes} 6 | layers_dim: 7 | - 1024 8 | - 1024 9 | - 1024 10 | - 1024 11 | - 1024 12 | - 1024 13 | - 1024 14 | - 1024 15 | - 1024 16 | - 1024 17 | - 1024 18 | - 1024 19 | - 1024 20 | - 1024 21 | - 1024 22 | - 1024 23 | - 1024 24 | - 1024 25 | - 1024 26 | - 1024 27 | - 1024 28 | - 1024 29 | - 1024 30 | - 1024 -------------------------------------------------------------------------------- /cfg/triplanes_classify/network/transformer.yaml: -------------------------------------------------------------------------------- 1 | _target_: networks.networks.TransformerEncoder 2 | 3 | embedding_dim: ${triplane_params.resolution} 4 | projection_dim: 512 5 | nhead: 4 6 | batch_first: True 7 | num_layers: 8 8 | num_classes: ${dataset.num_classes} 9 | -------------------------------------------------------------------------------- /cfg/triplanes_classify/opt/adam.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.Adam 2 | lr: 1e-4 3 | weight_decay: 0.01 -------------------------------------------------------------------------------- /cfg/triplanes_classify/opt/adamW.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.AdamW 2 | lr: 1e-4 3 | weight_decay: 1e-3 -------------------------------------------------------------------------------- /cfg/triplanes_classify/scheduler/onecycle.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.lr_scheduler.OneCycleLR -------------------------------------------------------------------------------- /cfg/triplanes_part_seg/dataset/shapenet_part_seg.yaml: -------------------------------------------------------------------------------- 1 | _target_: data.triplanes.TriplanePartDataset 2 | inrs_root: datasets/shapenet_part/pcd_part_triplane_32_16_h64l3_freq_encoding 3 | name: shapenet_part 4 | num_classes: 16 5 | num_parts: 50 -------------------------------------------------------------------------------- /cfg/triplanes_part_seg/loss/cross_entropy.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.nn.CrossEntropyLoss -------------------------------------------------------------------------------- /cfg/triplanes_part_seg/main.yaml: -------------------------------------------------------------------------------- 1 | defaults: 2 | - opt: adamW 3 | - scheduler: onecycle 4 | - dataset: shapenet_part_seg 5 | - network: transformer_encoder_decoder 6 | - loss: cross_entropy 7 | - _self_ 8 | - override hydra/hydra_logging: disabled 9 | - override hydra/job_logging: disabled 10 | 11 | mode: train 12 | ckpt_path: none 13 | 14 | trainer: 15 | module_name: triplane_part_seg 16 | 17 | train: 18 | batch_size: 32 19 | num_epochs: 75 20 | num_workers: 32 21 | 22 | train_transform: 23 | random_crop: -1 24 | gaussian_blur: -1 25 | horizontal_flip: False 26 | vertical_flip: False 27 | 28 | val_transoform: 29 | center_crop: ${train_transform.random_crop} 30 | 31 | val: 32 | batch_size: 128 33 | checkpoint_period: 1 34 | 35 | triplane_params: 36 | hidden_dim: 16 37 | resolution: 32 38 | mlp_hidden_dim: 64 39 | mlp_num_hidden_layers: 3 40 | 41 | runtime: 42 | gpus: 2 43 | precision: 16-mixed 44 | find_unused_parameters: False 45 | 46 | wandb: 47 | entity: 3dda 48 | project: triplane_part_seg 49 | run_name: ${dataset.name}-${now:%m-%d}/${now:%H-%M}_encoder_decoder 50 | dir: experiments_triplane_part_seg 51 | 52 | hydra: 53 | output_subdir: ${wandb.dir}/${wandb.run_name} 54 | run: 55 | dir: . -------------------------------------------------------------------------------- /cfg/triplanes_part_seg/network/cnn.yaml: -------------------------------------------------------------------------------- 1 | _target_: networks.networks.CNNEncoder 2 | num_classes: ${dataset.num_classes} 3 | pretrained: False 4 | channels: ${triplane_params.hidden_dim} 5 | embedding_dim: ${triplane_params.resolution} 6 | -------------------------------------------------------------------------------- /cfg/triplanes_part_seg/network/transformer.yaml: -------------------------------------------------------------------------------- 1 | _target_: networks.networks.TransformerSeg 2 | 3 | embedding_dim: ${triplane_params.resolution} 4 | projection_dim: 512 5 | nhead: 4 6 | batch_first: True 7 | num_layers: 8 8 | num_classes: ${dataset.num_classes} 9 | num_parts: ${dataset.num_parts} 10 | -------------------------------------------------------------------------------- /cfg/triplanes_part_seg/network/transformer_encoder_decoder.yaml: -------------------------------------------------------------------------------- 1 | _target_: networks.networks.Transformer_EncoderDecoder_Seg 2 | 3 | embedding_dim: ${triplane_params.resolution} 4 | projection_dim: 512 5 | nhead: 4 6 | batch_first: True 7 | num_layers: 8 8 | num_classes: ${dataset.num_classes} 9 | num_parts: ${dataset.num_parts} 10 | -------------------------------------------------------------------------------- /cfg/triplanes_part_seg/opt/adam.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.Adam 2 | lr: 1e-4 3 | weight_decay: 0.01 -------------------------------------------------------------------------------- /cfg/triplanes_part_seg/opt/adamW.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.AdamW 2 | lr: 1e-4 3 | weight_decay: 1e-3 -------------------------------------------------------------------------------- /cfg/triplanes_part_seg/scheduler/onecycle.yaml: -------------------------------------------------------------------------------- 1 | _target_: torch.optim.lr_scheduler.OneCycleLR -------------------------------------------------------------------------------- /data/mesh_inr.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import OrderedDict, Tuple 3 | 4 | import h5py 5 | import numpy as np 6 | import torch 7 | from torch import Tensor 8 | from torch.utils.data import Dataset 9 | 10 | from utils.var import get_mlp_params_as_matrix 11 | 12 | T_ITEM = Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor] 13 | 14 | 15 | class MeshInrDataset(Dataset): 16 | def __init__(self, inrs_root: Path, split: str, **args) -> None: 17 | super().__init__() 18 | 19 | self.inrs_root = Path(inrs_root) / split 20 | self.mlps_paths = sorted(self.inrs_root.glob("*.h5"), key=lambda x: int(x.stem)) 21 | # self.sample_sd = sample_sd 22 | 23 | def __len__(self) -> int: 24 | return len(self.mlps_paths) 25 | 26 | def __getitem__(self, index: int) -> T_ITEM: 27 | with h5py.File(self.mlps_paths[index], "r") as f: 28 | vertices = torch.from_numpy(np.array(f.get("vertices"))) 29 | num_vertices = torch.from_numpy(np.array(f.get("num_vertices"))) 30 | triangles = torch.from_numpy(np.array(f.get("triangles"))) 31 | num_triangles = torch.from_numpy(np.array(f.get("num_triangles"))) 32 | # params = torch.from_numpy(np.array(f.get("params"))).float() 33 | # matrix = get_mlp_params_as_matrix(params, self.sample_sd) 34 | class_id = torch.from_numpy(np.array(f.get("class_id"))).long() 35 | # coords = torch.from_numpy(np.array(f.get("coords"))) 36 | # labels = torch.from_numpy(np.array(f.get("labels"))) 37 | 38 | return vertices, num_vertices, triangles, num_triangles, class_id, class_id 39 | -------------------------------------------------------------------------------- /data/pcd_inr.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import OrderedDict, Tuple 3 | 4 | import h5py 5 | import numpy as np 6 | import torch 7 | from torch import Tensor 8 | from torch.utils.data import Dataset 9 | 10 | class PcdInrDataset(Dataset): 11 | def __init__(self, inrs_root: str, split: str, **args) -> None: 12 | super().__init__() 13 | 14 | self.inrs_root = Path(inrs_root) / split 15 | self.mlps_paths = sorted(self.inrs_root.glob("*.h5"), key=lambda x: int(x.stem)) 16 | 17 | def __len__(self) -> int: 18 | return len(self.mlps_paths) 19 | 20 | def __getitem__(self, index: int) -> Tuple[Tensor, Tensor, Tensor]: 21 | with h5py.File(self.mlps_paths[index], "r") as f: 22 | pcd = torch.from_numpy(np.array(f.get("pcd"))) 23 | # params = np.array(f.get("params")) 24 | # params = torch.from_numpy(params).float() 25 | class_id = torch.from_numpy(np.array(f.get("class_id"))).long() 26 | 27 | return pcd, class_id 28 | -------------------------------------------------------------------------------- /data/pcd_part_inr.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import OrderedDict, Tuple 3 | 4 | import h5py 5 | import numpy as np 6 | import torch 7 | from torch import Tensor 8 | from torch.utils.data import Dataset 9 | 10 | class PcdPartInrDataset(Dataset): 11 | def __init__(self, inrs_root: str, split: str, **args) -> None: 12 | super().__init__() 13 | 14 | self.inrs_root = Path(inrs_root) / split 15 | self.mlps_paths = sorted(self.inrs_root.glob("*.h5"), key=lambda x: int(x.stem)) 16 | 17 | def __len__(self) -> int: 18 | return len(self.mlps_paths) 19 | 20 | def __getitem__(self, index: int) -> Tuple[Tensor, Tensor, Tensor]: 21 | with h5py.File(self.mlps_paths[index], "r") as f: 22 | pcd = torch.from_numpy(np.array(f.get("pcd"))) 23 | part_labels = torch.from_numpy(np.array(f.get("part_labels"))).long() 24 | # params = np.array(f.get("params")) 25 | # params = torch.from_numpy(params).float() 26 | class_id = torch.from_numpy(np.array(f.get("class_id"))).long() 27 | 28 | return pcd, class_id, part_labels 29 | -------------------------------------------------------------------------------- /data/triplanes.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import OrderedDict, Tuple 3 | 4 | import h5py 5 | import numpy as np 6 | import torch 7 | from torch import Tensor 8 | from torch.utils.data import Dataset 9 | from utils.var import flatten_mlp_params 10 | 11 | class MLPDataset(Dataset): 12 | def __init__(self, inrs_root: str, split: str, transform=None, **args) -> None: 13 | super().__init__() 14 | 15 | self.inrs_root = Path(inrs_root) / split 16 | self.mlps_paths = sorted(self.inrs_root.glob("*.h5"), key=lambda x: int(x.stem)) 17 | self.transform = transform 18 | 19 | def __len__(self) -> int: 20 | return len(self.mlps_paths) 21 | 22 | def __getitem__(self, index: int) -> Tuple[Tensor, Tensor, Tensor]: 23 | with h5py.File(self.mlps_paths[index], "r") as f: 24 | params = np.array(f.get("params")) 25 | params = torch.from_numpy(params) 26 | class_id = np.array(f.get("class_id")) 27 | class_id = torch.from_numpy(class_id).long() 28 | 29 | return params, class_id 30 | 31 | class TriplaneDataset(Dataset): 32 | def __init__(self, inrs_root: str, split: str, transform=None, **args) -> None: 33 | super().__init__() 34 | 35 | self.inrs_root = Path(inrs_root) / split 36 | self.mlps_paths = sorted(self.inrs_root.glob("*.h5"), key=lambda x: int(x.stem)) 37 | self.transform = transform 38 | 39 | def __len__(self) -> int: 40 | return len(self.mlps_paths) 41 | 42 | def __getitem__(self, index: int) -> Tuple[Tensor, Tensor, Tensor]: 43 | with h5py.File(self.mlps_paths[index], "r") as f: 44 | triplane = np.array(f.get("triplane")) 45 | triplane = torch.from_numpy(triplane) 46 | class_id = np.array(f.get("class_id")) 47 | class_id = torch.from_numpy(class_id).long() 48 | triplane = torch.cat((triplane[0], triplane[1], triplane[2]), dim=0) 49 | triplane = torch.nn.functional.normalize(triplane, dim=0) 50 | 51 | if self.transform is not None: 52 | triplane = self.transform(triplane) 53 | 54 | return triplane, class_id 55 | 56 | 57 | class TriplanePartDataset(Dataset): 58 | def __init__(self, inrs_root: str, split: str, transform=None, **args) -> None: 59 | super().__init__() 60 | 61 | self.inrs_root = Path(inrs_root) / split 62 | self.mlps_paths = sorted(self.inrs_root.glob("*.h5"), key=lambda x: int(x.stem)) 63 | self.transform = transform 64 | self.class_to_parts = { 65 | "02691156": [0, 1, 2, 3], 66 | "02773838": [4, 5], 67 | "02954340": [6, 7], 68 | "02958343": [8, 9, 10, 11], 69 | "03001627": [12, 13, 14, 15], 70 | "03261776": [16, 17, 18], 71 | "03467517": [19, 20, 21], 72 | "03624134": [22, 23], 73 | "03636649": [24, 25, 26, 27], 74 | "03642806": [28, 29], 75 | "03790512": [30, 31, 32, 33, 34, 35], 76 | "03797390": [36, 37], 77 | "03948459": [38, 39, 40], 78 | "04099429": [41, 42, 43], 79 | "04225987": [44, 45, 46], 80 | "04379243": [47, 48, 49], 81 | } 82 | 83 | def __len__(self) -> int: 84 | return len(self.mlps_paths) 85 | 86 | def __getitem__(self, index: int) -> Tuple[Tensor, Tensor, Tensor]: 87 | with h5py.File(self.mlps_paths[index], "r") as f: 88 | triplane = np.array(f.get("triplane")) 89 | triplane = torch.from_numpy(triplane) 90 | pcd = np.array(f.get("pcd")) 91 | pcd = torch.from_numpy(pcd) 92 | class_id = np.array(f.get("class_id")) 93 | class_id = torch.from_numpy(class_id).long() 94 | part_label = np.array(f.get("part_label")) 95 | part_label = torch.from_numpy(part_label).long() 96 | triplane = torch.cat((triplane[0], triplane[1], triplane[2]), dim=0) 97 | triplane = torch.nn.functional.normalize(triplane, dim=0) 98 | 99 | if self.transform is not None: 100 | triplane = self.transform(triplane) 101 | 102 | return triplane, class_id, part_label, pcd 103 | 104 | -------------------------------------------------------------------------------- /data/voxel_inr.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import OrderedDict, Tuple 3 | 4 | import h5py 5 | import numpy as np 6 | import torch 7 | from torch import Tensor 8 | from torch.utils.data import Dataset 9 | from pycarus.geometry.pcd import voxelize_pcd 10 | 11 | class VoxelInrDataset(Dataset): 12 | def __init__(self, inrs_root: str, split: str, **args) -> None: 13 | super().__init__() 14 | 15 | self.inrs_root = Path(inrs_root) / split 16 | self.mlps_paths = sorted(self.inrs_root.glob("*.h5"), key=lambda x: int(x.stem)) 17 | 18 | def __len__(self) -> int: 19 | return len(self.mlps_paths) 20 | 21 | def __getitem__(self, index: int) -> Tuple[Tensor, Tensor, Tensor]: 22 | with h5py.File(self.mlps_paths[index], "r") as f: 23 | pcd = torch.from_numpy(np.array(f.get("pcd"))) 24 | # params = np.array(f.get("params")) 25 | # params = torch.from_numpy(params).float() 26 | # matrix = get_mlp_params_as_matrix(params, self.sample_sd) 27 | class_id = torch.from_numpy(np.array(f.get("class_id"))).long() 28 | 29 | # vgrid, centroids = voxelize_pcd(pcd, self.vox_res, -1, 1) 30 | 31 | return pcd, class_id 32 | -------------------------------------------------------------------------------- /datamodules/datamodule.py: -------------------------------------------------------------------------------- 1 | """ 2 | Load many available datasets 3 | """ 4 | 5 | import random 6 | from dataclasses import dataclass 7 | from functools import partial 8 | from multiprocessing import cpu_count 9 | from pathlib import Path 10 | from typing import Any, Callable 11 | from copy import deepcopy 12 | import numpy as np 13 | import pytorch_lightning as pl 14 | import torch 15 | from omegaconf.dictconfig import DictConfig 16 | from omegaconf.listconfig import ListConfig 17 | from torch.utils.data import DataLoader, Dataset 18 | from torch.utils.data.sampler import BatchSampler, RandomSampler 19 | import hydra 20 | from torchvision import transforms 21 | 22 | 23 | def set_random_seed(seed): 24 | if seed < 0: 25 | return 26 | random.seed(seed) 27 | np.random.seed(seed) 28 | torch.manual_seed(seed) 29 | torch.cuda.manual_seed_all(seed) 30 | 31 | 32 | def worker_init_fn(worker_id): 33 | """The function is designed for pytorch multi-process dataloader. 34 | Note that we use the pytorch random generator to generate a base_seed. 35 | Please try to be consistent. 36 | 37 | References: 38 | https://pytorch.org/docs/stable/notes/faq.html#dataloader-workers-random-seed 39 | 40 | """ 41 | # base_seed = torch.IntTensor(1).random_().item() 42 | # print(worker_id, base_seed) 43 | set_random_seed(worker_id) 44 | 45 | 46 | def load_datamodule( 47 | cfg, 48 | ): 49 | 50 | identity_transform = transforms.Lambda(lambda x: x) 51 | data_transforms = { 52 | 'train': transforms.Compose([ 53 | transforms.RandomResizedCrop(cfg.train_transform.random_crop, antialias=True) if cfg.train_transform.random_crop > 0 else identity_transform, 54 | transforms.RandomHorizontalFlip() if cfg.train_transform.horizontal_flip else identity_transform, 55 | transforms.RandomVerticalFlip() if cfg.train_transform.vertical_flip else identity_transform, 56 | transforms.GaussianBlur(cfg.train_transform.gaussian_blur) if cfg.train_transform.gaussian_blur > 0 else identity_transform 57 | # transforms.ToTensor(), 58 | ]), 59 | 'val': transforms.Compose([ 60 | transforms.CenterCrop(cfg.val_transoform.center_crop) if cfg.val_transoform.center_crop > 0 else identity_transform, 61 | # transforms.ToTensor(), 62 | ]), 63 | } 64 | 65 | train_ds = hydra.utils.instantiate(cfg.dataset, split="train", transform=data_transforms['train']) 66 | val_ds = hydra.utils.instantiate(cfg.dataset, split="val", transform=data_transforms['val']) 67 | 68 | 69 | # cfg2 = deepcopy(cfg.dataset) 70 | # cfg2.inrs_root = 'datasets/Manifold40/pcd_triplane_32_16_h64l3_freq_encoding' 71 | # train_ds_pc = hydra.utils.instantiate(cfg2, split="train", transform=data_transforms['train']) 72 | # cfg3 = deepcopy(cfg.dataset) 73 | # cfg3.inrs_root = 'datasets/Manifold40/voxel_triplane_32_16_h64l3_freq_encoding' 74 | # train_ds_voxels = hydra.utils.instantiate(cfg3, split="train", transform=data_transforms['train']) 75 | # train_ds = torch.utils.data.ConcatDataset([train_ds, train_ds_pc, train_ds_voxels]) 76 | 77 | # val_ds_pc = hydra.utils.instantiate(cfg2, split="val", transform=data_transforms['val']) 78 | # val_ds_voxels = hydra.utils.instantiate(cfg3, split="val", transform=data_transforms['val']) 79 | # val_ds = torch.utils.data.ConcatDataset([val_ds, val_ds_pc, val_ds_voxels]) 80 | 81 | 82 | test_ds = hydra.utils.instantiate(cfg.dataset, split="test", transform=data_transforms['val']) 83 | 84 | return _DataModule( 85 | train_ds=train_ds, 86 | val_ds=val_ds, 87 | test_ds=test_ds, 88 | train_batch_size=cfg.train.batch_size, 89 | val_batch_size=cfg.val.batch_size, 90 | num_workers=cfg.train.num_workers, 91 | ) 92 | 93 | 94 | @dataclass 95 | class _DataModule(pl.LightningDataModule): 96 | train_ds: Dataset 97 | val_ds: Dataset 98 | test_ds: Dataset 99 | train_batch_size: int = 128 100 | val_batch_size: int = 128 101 | num_workers: int = cpu_count() // 2 102 | 103 | def train_dataloader(self): 104 | 105 | train_dl = DataLoader( 106 | self.train_ds, 107 | num_workers=self.num_workers, 108 | worker_init_fn=worker_init_fn, 109 | batch_size=self.train_batch_size, 110 | drop_last=True, 111 | shuffle=True, 112 | ) 113 | 114 | return train_dl 115 | 116 | def val_dataloader(self): 117 | 118 | target_dl = DataLoader( 119 | self.val_ds, 120 | batch_size=self.val_batch_size, 121 | drop_last=False, 122 | num_workers=self.num_workers // 2, 123 | worker_init_fn=worker_init_fn, 124 | ) 125 | 126 | target_dl_test = DataLoader( 127 | self.test_ds, 128 | batch_size=self.val_batch_size, 129 | drop_last=False, 130 | num_workers=self.num_workers // 2, 131 | ) 132 | 133 | return [target_dl, target_dl_test] 134 | 135 | def test_dataloader(self): 136 | return DataLoader( 137 | self.test_ds, 138 | batch_size=self.val_batch_size, 139 | drop_last=False, 140 | num_workers=self.num_workers // 2, 141 | ) 142 | -------------------------------------------------------------------------------- /inr_fit_mesh.py: -------------------------------------------------------------------------------- 1 | import hydra 2 | from omegaconf import OmegaConf 3 | import wandb 4 | from pathlib import Path 5 | import importlib 6 | 7 | code_pos = Path(__file__) 8 | 9 | @hydra.main(config_path="cfg/inr_mesh_fit", config_name="main", version_base="1.1") 10 | def main(cfg) -> None: 11 | print("trainers/" + cfg.trainer.module_name) 12 | trainer_module = importlib.import_module("trainers." + cfg.trainer.module_name) 13 | print(OmegaConf.to_yaml(cfg, resolve=True)) 14 | wandb.config = OmegaConf.to_container( 15 | cfg, resolve=True, throw_on_missing=True 16 | ) 17 | run = wandb.init( 18 | entity=cfg.wandb.entity, 19 | project=cfg.wandb.project, 20 | name=cfg.wandb.run_name, 21 | dir=cfg.wandb.dir, 22 | config=OmegaConf.to_container( 23 | cfg, resolve=True, throw_on_missing=True 24 | ) 25 | ) 26 | artifact = wandb.Artifact("Trainer", type="code") 27 | artifact.add_file("trainers/" + cfg.trainer.module_name + ".py") 28 | run.log_artifact(artifact) 29 | 30 | trainer = trainer_module.Fitter(cfg) 31 | trainer.train() 32 | trainer.evaluate() 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /inr_fit_point_cloud.py: -------------------------------------------------------------------------------- 1 | import hydra 2 | from omegaconf import OmegaConf 3 | import wandb 4 | from pathlib import Path 5 | import importlib 6 | 7 | code_pos = Path(__file__) 8 | 9 | @hydra.main(config_path="cfg/inr_pc_fit", config_name="main", version_base="1.1") 10 | def main(cfg) -> None: 11 | print("trainers/" + cfg.trainer.module_name) 12 | trainer_module = importlib.import_module("trainers." + cfg.trainer.module_name) 13 | print(OmegaConf.to_yaml(cfg, resolve=True)) 14 | wandb.config = OmegaConf.to_container( 15 | cfg, resolve=True, throw_on_missing=True 16 | ) 17 | run = wandb.init( 18 | entity=cfg.wandb.entity, 19 | project=cfg.wandb.project, 20 | name=cfg.wandb.run_name, 21 | dir=cfg.wandb.dir, 22 | config=OmegaConf.to_container( 23 | cfg, resolve=True, throw_on_missing=True 24 | ) 25 | ) 26 | artifact = wandb.Artifact("Trainer", type="code") 27 | artifact.add_file("trainers/" + cfg.trainer.module_name + ".py") 28 | run.log_artifact(artifact) 29 | 30 | trainer = trainer_module.Fitter(cfg) 31 | trainer.train() 32 | trainer.evaluate() 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /networks/networks.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | import torch 4 | from torch import nn as nn 5 | import torchvision 6 | from einops import repeat 7 | import math 8 | 9 | 10 | class FC_mlp(nn.Module): 11 | def __init__(self, layers_dim, num_classes=10, embedding_dim=32, channels=48) -> None: 12 | super().__init__() 13 | layers = [] 14 | 15 | layers.append(nn.Linear(88064, layers_dim[0])) 16 | layers.append(nn.BatchNorm1d(layers_dim[0])) 17 | layers.append(nn.ReLU()) 18 | layers.append(nn.Dropout()) 19 | 20 | if len(layers_dim) > 1: 21 | for i in range(len(layers_dim) - 1): 22 | layers.append(nn.Linear(layers_dim[i], layers_dim[i + 1])) 23 | layers.append(nn.BatchNorm1d(layers_dim[i + 1])) 24 | layers.append(nn.ReLU()) 25 | layers.append(nn.Dropout()) 26 | layers.append(nn.Linear(layers_dim[-1], num_classes)) 27 | 28 | self.net = nn.Sequential(*layers) 29 | 30 | def forward(self, x): 31 | return self.net(x.reshape(x.shape[0], -1)) 32 | 33 | 34 | class FC_triplane(nn.Module): 35 | def __init__(self, layers_dim, num_classes=10, embedding_dim=32, channels=48) -> None: 36 | super().__init__() 37 | layers = [] 38 | 39 | layers.append(nn.Conv1d(embedding_dim*embedding_dim, layers_dim[0], 1)) 40 | layers.append(nn.BatchNorm1d(layers_dim[0])) 41 | layers.append(nn.ReLU()) 42 | # layers.append(nn.Dropout()) 43 | 44 | if len(layers_dim) > 1: 45 | for i in range(len(layers_dim) - 1): 46 | # layers.append(nn.Linear(layers_dim[i], layers_dim[i + 1])) 47 | layers.append(nn.Conv1d(layers_dim[i], layers_dim[i + 1], 1)) 48 | layers.append(nn.BatchNorm1d(layers_dim[i + 1])) 49 | layers.append(nn.ReLU()) 50 | # layers.append(nn.Dropout()) 51 | self.net = nn.Sequential(*layers) 52 | self.cls = nn.Linear(layers_dim[-1], num_classes) 53 | 54 | def forward(self, x): 55 | x = self.net(x.reshape(x.shape[0], x.shape[1], -1).permute(0,2,1)) 56 | x, _ = torch.max(x, 2) 57 | x = self.cls(x) 58 | return x 59 | 60 | 61 | class CNNEncoder(nn.Module): 62 | def __init__(self, num_classes=10, pretrained=False, channels=48, **args) -> None: 63 | super().__init__() 64 | self.encoder = torchvision.models.resnet50(num_classes=num_classes, pretrained=pretrained) 65 | self.encoder.conv1 = nn.Conv2d(channels, 64, kernel_size=7, stride=2, padding=3, bias=False) 66 | 67 | def forward(self, x: torch.Tensor) -> torch.Tensor: 68 | x = self.encoder(x) 69 | return x 70 | 71 | 72 | class TransformerEncoder(nn.Module): 73 | def __init__(self, embedding_dim: int, projection_dim:int, nhead: int, batch_first=True, num_layers=8, num_classes=10) -> None: 74 | super().__init__() 75 | 76 | self.projection_layer = nn.Linear(embedding_dim*embedding_dim, projection_dim) 77 | encoder_layer = nn.TransformerEncoderLayer(d_model=projection_dim, nhead=nhead, batch_first=batch_first) 78 | self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers) 79 | self.final_projection = nn.Linear(projection_dim, num_classes) 80 | 81 | def forward(self, x: torch.Tensor) -> torch.Tensor: 82 | x = x.reshape(x.shape[0], x.shape[1], -1) 83 | x = self.projection_layer(x) 84 | x = self.encoder(x) 85 | x, _ = torch.max(x, 1) 86 | x = self.final_projection(x) 87 | 88 | return x 89 | 90 | class Transformer_EncoderDecoder_Seg(nn.Module): 91 | def __init__(self, embedding_dim: int, projection_dim:int, nhead: int, batch_first=True, num_layers=8, num_classes=10, num_parts=50) -> None: 92 | super().__init__() 93 | 94 | self.projection_layer = nn.Linear(embedding_dim*embedding_dim, projection_dim) 95 | encoder_layer = nn.TransformerEncoderLayer(d_model=projection_dim, nhead=nhead, batch_first=batch_first, dim_feedforward=1024) 96 | self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers) 97 | 98 | self.in_layer = nn.Sequential(nn.Linear(63+num_classes, projection_dim), nn.ReLU()) 99 | decoder_layer = nn.TransformerDecoderLayer(d_model=projection_dim, nhead=nhead//2, batch_first=batch_first, dim_feedforward=1024) 100 | self.transformer_decoder = nn.TransformerDecoder(decoder_layer, num_layers=num_layers//2) 101 | 102 | self.final_layer = nn.Linear(projection_dim, num_parts) 103 | 104 | def forward(self, x: torch.Tensor, class_labels: torch.Tensor, coords: torch.Tensor) -> torch.Tensor: 105 | x = x.reshape(x.shape[0], x.shape[1], -1) 106 | x = self.projection_layer(x) 107 | x = self.encoder(x) 108 | 109 | repeated_class_labels = repeat(class_labels, "b d -> b n d", n=coords.shape[1]) 110 | 111 | tgt = torch.cat([coords, repeated_class_labels], dim=-1) 112 | tgt = self.in_layer(tgt) 113 | tgt = self.transformer_decoder(tgt, x) 114 | out = self.final_layer(tgt) 115 | 116 | return out 117 | 118 | -------------------------------------------------------------------------------- /requirements.yaml: -------------------------------------------------------------------------------- 1 | name: triplane_official 2 | channels: 3 | - pytorch 4 | - conda-forge 5 | - nvidia/label/cuda-11.8.0 6 | - fvcore 7 | - iopath 8 | - pytorch3d 9 | - pyg 10 | - defaults 11 | 12 | dependencies: 13 | # python version 14 | - python=3.8 15 | 16 | # cuda, toolkit for pytorch 17 | # other to compile with nvcc 18 | - cudatoolkit=11.8 19 | 20 | # core 21 | - pytorch=2.0.1 22 | - pytorch-lightning 23 | - torchvision 24 | - torchaudio 25 | - matplotlib 26 | - pip 27 | - fvcore 28 | - iopath 29 | - pytorch3d 30 | - pyg 31 | 32 | # dev 33 | - black 34 | 35 | - pip: 36 | # core 37 | - wandb 38 | - pycarus 39 | - pipe 40 | - plyfile 41 | - hesiod 42 | - h5py 43 | - hydra-core 44 | - matplotlib 45 | - omegaconf 46 | # dev 47 | - pytest 48 | -------------------------------------------------------------------------------- /trainers/fit_inr_mesh.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import List 3 | 4 | import torch 5 | import torch.nn.functional as F 6 | from pycarus.geometry.pcd import compute_udf_from_pcd, farthest_point_sampling 7 | from pycarus.geometry.pcd import random_point_sampling, shuffle_pcd 8 | from pycarus.learning.models.siren import SIREN 9 | from pycarus.utils import progress_bar 10 | from torch.optim import Adam 11 | from torch.utils.data import DataLoader, Dataset 12 | from torch import Tensor 13 | import open3d as o3d 14 | import hydra 15 | from utils.var import get_mlps_batched_params, mlp_batched_forward, unflatten_mlp_params 16 | from pycarus.geometry.mesh import compute_sdf_from_mesh, get_o3d_mesh_from_tensors, marching_cubes, get_tensor_mesh_from_o3d 17 | from pycarus.metrics.chamfer_distance import chamfer_t 18 | from pycarus.metrics.f_score import f_score 19 | from tqdm import tqdm 20 | import h5py 21 | import numpy as np 22 | from pycarus.geometry.pcd import get_tensor_pcd_from_o3d 23 | import wandb 24 | 25 | class Fitter: 26 | def __init__(self, cfg) -> None: 27 | self.cfg = cfg 28 | self.out_root = Path(cfg.out_root) 29 | self.out_root.mkdir(parents=True, exist_ok=True) 30 | 31 | def build_mlp(self, inr_params) -> SIREN: 32 | mlp = SIREN( 33 | input_dim=3, 34 | hidden_dim=inr_params.mlp_hidden_dim, 35 | num_hidden_layers=inr_params.mlp_num_hidden_layers, 36 | out_dim=1, 37 | ) 38 | # print(sum(p.numel() for p in mlp.parameters())) 39 | return mlp 40 | 41 | 42 | def get_dataset(self, split) -> Dataset: 43 | dset = hydra.utils.instantiate(self.cfg.dataset, split=split) 44 | return dset 45 | 46 | 47 | def train(self) -> None: 48 | 49 | 50 | for split in self.cfg.splits: 51 | 52 | dset = self.get_dataset(split) 53 | global_idx = 0 54 | 55 | loader = DataLoader( 56 | dset, 57 | batch_size=self.cfg.batch_size, 58 | shuffle=False, 59 | num_workers=8, 60 | 61 | ) 62 | desc = f"Fitting {split} set" 63 | print(desc) 64 | # c = 0 65 | for batch in progress_bar(loader, desc, 80): 66 | # if c%2 == 0: 67 | # continue 68 | 69 | vertices, num_vertices, triangles, num_triangles, _, class_ids = batch 70 | bs = len(vertices) 71 | 72 | coords = [] 73 | labels = [] 74 | 75 | for idx in range(bs): 76 | num_v = num_vertices[idx] 77 | v = vertices[idx][:num_v] 78 | num_t = num_triangles[idx] 79 | t = triangles[idx][:num_t] 80 | mesh_o3d = get_o3d_mesh_from_tensors(v, t) 81 | 82 | mesh_coords, mesh_labels = compute_sdf_from_mesh( 83 | mesh_o3d, 84 | num_surface_points=self.cfg.num_queries_on_surface, 85 | queries_stds=self.cfg.stds, 86 | num_queries_per_std=self.cfg.num_points_per_std, 87 | coords_range=(-1, 1), 88 | ) 89 | coords.append(mesh_coords) 90 | labels.append(mesh_labels) 91 | 92 | coords = torch.stack(coords, dim=0) 93 | labels = torch.stack(labels, dim=0) 94 | 95 | coords_and_labels = torch.cat((coords, labels.unsqueeze(-1)), dim=-1).cuda() 96 | coords_and_labels = shuffle_pcd(coords_and_labels) 97 | 98 | inr_params = self.cfg.inr_params 99 | mlps = [self.build_mlp(inr_params).cuda() for _ in range(bs)] 100 | batched_params = get_mlps_batched_params(mlps) 101 | optimizer = hydra.utils.instantiate(self.cfg.opt, batched_params) 102 | 103 | for _ in progress_bar(range(self.cfg.num_steps)): 104 | selected_c_and_l = random_point_sampling( 105 | coords_and_labels, 106 | self.cfg.num_points_fitting, 107 | ) 108 | 109 | selected_coords = selected_c_and_l[:, :, :3] 110 | selected_labels = selected_c_and_l[:, :, 3] 111 | pred = mlp_batched_forward(batched_params, selected_coords) 112 | 113 | selected_labels = (selected_labels + 0.1) / 0.2 114 | loss = F.binary_cross_entropy_with_logits(pred, selected_labels) 115 | optimizer.zero_grad() 116 | loss.backward() 117 | optimizer.step() 118 | 119 | 120 | for idx in range(bs): 121 | 122 | flattened_params = [p[idx].view(-1) for p in batched_params] 123 | flattened_params = torch.cat(flattened_params, dim=0) 124 | 125 | h5_path = self.out_root / split / f"{global_idx}.h5" 126 | h5_path.parent.mkdir(parents=True, exist_ok=True) 127 | 128 | with h5py.File(h5_path, "w") as f: 129 | f.create_dataset("vertices", data=vertices[idx].cpu().numpy()) 130 | f.create_dataset("num_vertices", data=num_vertices[idx]) 131 | f.create_dataset("triangles", data=triangles[idx].cpu().numpy()) 132 | f.create_dataset("num_triangles", data=num_triangles[idx]) 133 | f.create_dataset("class_id", data=class_ids[idx].cpu().numpy()) 134 | f.create_dataset("params", data=flattened_params.detach().cpu().numpy()) 135 | 136 | global_idx += 1 -------------------------------------------------------------------------------- /trainers/fit_inr_pc.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import List 3 | 4 | import torch 5 | import torch.nn.functional as F 6 | from pycarus.geometry.pcd import compute_udf_from_pcd, farthest_point_sampling 7 | from pycarus.geometry.pcd import random_point_sampling, shuffle_pcd 8 | from pycarus.learning.models.siren import SIREN 9 | from pycarus.utils import progress_bar 10 | from torch.optim import Adam 11 | from torch.utils.data import DataLoader, Dataset 12 | from torch import Tensor 13 | import open3d as o3d 14 | import hydra 15 | from utils.var import get_mlps_batched_params, mlp_batched_forward, unflatten_mlp_params 16 | from pycarus.geometry.pcd import get_o3d_pcd_from_tensor, sample_pcds_from_udfs 17 | from pycarus.metrics.chamfer_distance import chamfer_t 18 | from pycarus.metrics.f_score import f_score 19 | from tqdm import tqdm 20 | import h5py 21 | import numpy as np 22 | from pycarus.geometry.pcd import get_tensor_pcd_from_o3d 23 | import wandb 24 | 25 | class Fitter: 26 | def __init__(self, cfg) -> None: 27 | self.cfg = cfg 28 | self.out_root = Path(cfg.out_root) 29 | self.out_root.mkdir(parents=True, exist_ok=True) 30 | 31 | def build_mlp(self, inr_params) -> SIREN: 32 | mlp = SIREN( 33 | input_dim=3, 34 | hidden_dim=inr_params.mlp_hidden_dim, 35 | num_hidden_layers=inr_params.mlp_num_hidden_layers, 36 | out_dim=1, 37 | ) 38 | # print(sum(p.numel() for p in mlp.parameters())) 39 | return mlp 40 | 41 | 42 | def get_dataset(self, split) -> Dataset: 43 | dset = hydra.utils.instantiate(self.cfg.dataset, split=split) 44 | return dset 45 | 46 | 47 | def train(self) -> None: 48 | 49 | 50 | for split in self.cfg.splits: 51 | 52 | dset = self.get_dataset(split) 53 | global_idx = 0 54 | 55 | loader = DataLoader( 56 | dset, 57 | batch_size=self.cfg.batch_size, 58 | shuffle=False, 59 | num_workers=8, 60 | 61 | ) 62 | desc = f"Fitting {split} set" 63 | print(desc) 64 | 65 | for batch in progress_bar(loader, desc, 80): 66 | pcds, class_ids = batch 67 | bs = pcds.shape[0] 68 | 69 | if pcds.shape[1] != self.cfg.num_points_pcd: 70 | pcds = farthest_point_sampling(pcds, self.cfg.num_points_pcd) 71 | 72 | coords = [] 73 | labels = [] 74 | 75 | for idx in range(bs): 76 | pcd_coords, pcd_labels = compute_udf_from_pcd( 77 | pcds[idx].to("cuda"), 78 | self.cfg.num_queries_on_surface, 79 | self.cfg.stds, 80 | self.cfg.num_points_per_std, 81 | coords_range=(-1, 1), 82 | convert_to_bce_labels=True, 83 | ) 84 | coords.append(pcd_coords) 85 | labels.append(pcd_labels) 86 | 87 | coords = torch.stack(coords, dim=0) 88 | labels = torch.stack(labels, dim=0) 89 | 90 | coords_and_labels = torch.cat((coords, labels.unsqueeze(-1)), dim=-1).cuda() 91 | coords_and_labels = shuffle_pcd(coords_and_labels) 92 | 93 | inr_params = self.cfg.inr_params 94 | mlps = [self.build_mlp(inr_params).cuda() for _ in range(bs)] 95 | batched_params = get_mlps_batched_params(mlps) 96 | optimizer = hydra.utils.instantiate(self.cfg.opt, batched_params) 97 | 98 | for _ in progress_bar(range(self.cfg.num_steps)): 99 | selected_c_and_l = random_point_sampling( 100 | coords_and_labels, 101 | self.cfg.num_points_fitting, 102 | ) 103 | 104 | selected_coords = selected_c_and_l[:, :, :3] 105 | selected_labels = selected_c_and_l[:, :, 3] 106 | pred = mlp_batched_forward(batched_params, selected_coords) 107 | loss = F.binary_cross_entropy_with_logits(pred, selected_labels) 108 | optimizer.zero_grad() 109 | loss.backward() 110 | optimizer.step() 111 | 112 | for idx in range(bs): 113 | 114 | flattened_params = [p[idx].view(-1) for p in batched_params] 115 | flattened_params = torch.cat(flattened_params, dim=0) 116 | 117 | h5_path = self.out_root / split / f"{global_idx}.h5" 118 | h5_path.parent.mkdir(parents=True, exist_ok=True) 119 | 120 | with h5py.File(h5_path, "w") as f: 121 | f.create_dataset("pcd", data=pcds[idx].cpu().numpy()) 122 | f.create_dataset("class_id", data=class_ids[idx].cpu().numpy()) 123 | f.create_dataset("params", data=flattened_params.detach().cpu().numpy()) 124 | 125 | global_idx += 1 126 | -------------------------------------------------------------------------------- /trainers/fit_triplane_mesh.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import List 3 | 4 | import torch 5 | import torch.nn.functional as F 6 | from pycarus.geometry.pcd import compute_udf_from_pcd, farthest_point_sampling 7 | from pycarus.geometry.pcd import random_point_sampling, shuffle_pcd 8 | from pycarus.learning.models.siren import SIREN 9 | from pycarus.utils import progress_bar 10 | from torch.optim import Adam 11 | from torch.utils.data import DataLoader, Dataset 12 | from torch import Tensor 13 | import open3d as o3d 14 | import hydra 15 | from utils.var import get_mlps_batched_params, mlp_batched_forward, unflatten_mlp_params, CoordsEncoder 16 | from pycarus.geometry.mesh import compute_sdf_from_mesh, get_o3d_mesh_from_tensors, marching_cubes, get_tensor_mesh_from_o3d 17 | from pycarus.metrics.chamfer_distance import chamfer_t 18 | from pycarus.metrics.f_score import f_score 19 | from tqdm import tqdm 20 | import h5py 21 | import numpy as np 22 | from pycarus.geometry.pcd import get_tensor_pcd_from_o3d 23 | import wandb 24 | 25 | class Fitter: 26 | def __init__(self, cfg) -> None: 27 | self.cfg = cfg 28 | self.out_root = Path(cfg.out_root) 29 | self.out_root.mkdir(parents=True, exist_ok=True) 30 | self.coords_enc = CoordsEncoder(3) 31 | 32 | def build_mlp(self, triplane_params) -> SIREN: 33 | mlp = SIREN( 34 | input_dim=triplane_params.hidden_dim+63, 35 | hidden_dim=triplane_params.mlp_hidden_dim, 36 | num_hidden_layers=triplane_params.mlp_num_hidden_layers, 37 | out_dim=1, 38 | ) 39 | # print(sum(p.numel() for p in mlp.parameters())) 40 | 41 | return mlp 42 | 43 | 44 | def get_dataset(self, split) -> Dataset: 45 | dset = hydra.utils.instantiate(self.cfg.dataset, split=split) 46 | return dset 47 | 48 | 49 | def train(self) -> None: 50 | 51 | 52 | for split in self.cfg.splits: 53 | 54 | dset = self.get_dataset(split) 55 | global_idx = 0 56 | 57 | loader = DataLoader( 58 | dset, 59 | batch_size=self.cfg.batch_size, 60 | shuffle=False, 61 | num_workers=8, 62 | 63 | ) 64 | desc = f"Fitting {split} set" 65 | print(desc) 66 | # c = 0 67 | for batch in progress_bar(loader, desc, 80): 68 | # if c%2 == 0: 69 | # continue 70 | 71 | vertices, num_vertices, triangles, num_triangles, _, class_ids = batch 72 | bs = len(vertices) 73 | 74 | coords = [] 75 | labels = [] 76 | 77 | for idx in range(bs): 78 | num_v = num_vertices[idx] 79 | v = vertices[idx][:num_v] 80 | num_t = num_triangles[idx] 81 | t = triangles[idx][:num_t] 82 | mesh_o3d = get_o3d_mesh_from_tensors(v, t) 83 | 84 | mesh_coords, mesh_labels = compute_sdf_from_mesh( 85 | mesh_o3d, 86 | num_surface_points=self.cfg.num_queries_on_surface, 87 | queries_stds=self.cfg.stds, 88 | num_queries_per_std=self.cfg.num_points_per_std, 89 | coords_range=(-1, 1), 90 | use_cuda=True, 91 | ) 92 | coords.append(mesh_coords) 93 | labels.append(mesh_labels) 94 | 95 | coords = torch.stack(coords, dim=0) 96 | labels = torch.stack(labels, dim=0) 97 | 98 | coords_and_labels = torch.cat((coords, labels.unsqueeze(-1)), dim=-1).cuda() 99 | coords_and_labels = shuffle_pcd(coords_and_labels) 100 | 101 | triplane_params = self.cfg.triplane_params 102 | triplane = torch.nn.Parameter(torch.normal(torch.zeros(bs,3,triplane_params.resolution,triplane_params.resolution,triplane_params.hidden_dim, device="cuda"), torch.ones(bs,3,triplane_params.resolution,triplane_params.resolution,triplane_params.hidden_dim, device="cuda")*0.001)) 103 | 104 | mlps = [self.build_mlp(triplane_params).cuda() for _ in range(bs)] 105 | batched_params = get_mlps_batched_params(mlps) 106 | optimizer = hydra.utils.instantiate(self.cfg.opt, [triplane] + batched_params) 107 | 108 | for _ in progress_bar(range(self.cfg.num_steps)): 109 | selected_c_and_l = random_point_sampling( 110 | coords_and_labels, 111 | self.cfg.num_points_fitting, 112 | ) 113 | 114 | selected_coords = selected_c_and_l[:, :, :3] 115 | selected_labels = selected_c_and_l[:, :, 3] 116 | 117 | coords_xy = torch.cat((selected_coords[:, :, 0].unsqueeze(2), selected_coords[:, :, 1].unsqueeze(2)), dim=2) 118 | coords_xz = torch.cat((selected_coords[:, :, 0].unsqueeze(2), selected_coords[:, :, 2].unsqueeze(2)), dim=2) 119 | coords_zy = torch.cat((selected_coords[:, :, 1].unsqueeze(2), selected_coords[:, :, 2].unsqueeze(2)), dim=2) 120 | 121 | grid = torch.stack([coords_xy, coords_xz, coords_zy], dim=1) 122 | grid = grid.reshape(-1, self.cfg.num_points_fitting, 2).unsqueeze(1) 123 | features_sample = torch.nn.functional.grid_sample(triplane.reshape(-1, triplane_params.resolution, triplane_params.resolution, triplane_params.hidden_dim).permute(0, 3, 1, 2), grid).squeeze(2).squeeze(2).permute(0, 2, 1) 124 | features_sample = features_sample.reshape(bs, 3, self.cfg.num_points_fitting, triplane_params.hidden_dim) 125 | features_sample = features_sample.sum(1) 126 | 127 | batched_features = torch.cat([features_sample, self.coords_enc.embed(selected_coords)], dim=-1) 128 | pred = mlp_batched_forward(batched_params, batched_features) 129 | 130 | selected_labels = (selected_labels + 0.1) / 0.2 131 | loss = F.binary_cross_entropy_with_logits(pred, selected_labels) 132 | optimizer.zero_grad() 133 | loss.backward() 134 | optimizer.step() 135 | 136 | 137 | for idx in range(bs): 138 | 139 | flattened_params = [p[idx].view(-1) for p in batched_params] 140 | flattened_params = torch.cat(flattened_params, dim=0) 141 | 142 | h5_path = self.out_root / split / f"{global_idx}.h5" 143 | h5_path.parent.mkdir(parents=True, exist_ok=True) 144 | 145 | with h5py.File(h5_path, "w") as f: 146 | f.create_dataset("vertices", data=vertices[idx].cpu().numpy()) 147 | f.create_dataset("num_vertices", data=num_vertices[idx]) 148 | f.create_dataset("triangles", data=triangles[idx].cpu().numpy()) 149 | f.create_dataset("num_triangles", data=num_triangles[idx]) 150 | f.create_dataset("class_id", data=class_ids[idx].cpu().numpy()) 151 | f.create_dataset("triplane", data=triplane[idx].permute(0,3,1,2).detach().cpu().numpy()) 152 | f.create_dataset("params", data=flattened_params.detach().cpu().numpy()) 153 | 154 | global_idx += 1 155 | -------------------------------------------------------------------------------- /trainers/fit_triplane_pcd.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import List 3 | 4 | import torch 5 | import torch.nn.functional as F 6 | from pycarus.geometry.pcd import compute_udf_from_pcd, farthest_point_sampling 7 | from pycarus.geometry.pcd import random_point_sampling, shuffle_pcd 8 | from pycarus.learning.models.siren import SIREN 9 | from pycarus.utils import progress_bar 10 | from torch.optim import Adam 11 | from torch.utils.data import DataLoader, Dataset 12 | from torch import Tensor 13 | import open3d as o3d 14 | import hydra 15 | from utils.var import get_mlps_batched_params, mlp_batched_forward, unflatten_mlp_params, CoordsEncoder 16 | from pycarus.geometry.pcd import get_o3d_pcd_from_tensor, sample_pcds_from_udfs 17 | from pycarus.metrics.chamfer_distance import chamfer_t 18 | from pycarus.metrics.f_score import f_score 19 | import h5py 20 | import numpy as np 21 | import wandb 22 | class Fitter: 23 | def __init__(self, cfg) -> None: 24 | self.cfg = cfg 25 | self.out_root = Path(cfg.out_root) 26 | self.out_root.mkdir(parents=True, exist_ok=True) 27 | self.coords_enc = CoordsEncoder(3) 28 | 29 | def build_mlp(self, triplane_params) -> SIREN: 30 | mlp = SIREN( 31 | input_dim=triplane_params.hidden_dim+63, 32 | hidden_dim=triplane_params.mlp_hidden_dim, 33 | num_hidden_layers=triplane_params.mlp_num_hidden_layers, 34 | out_dim=1, 35 | ) 36 | # print(sum(p.numel() for p in mlp.parameters())) 37 | return mlp 38 | 39 | 40 | def get_dataset(self, split) -> Dataset: 41 | dset = hydra.utils.instantiate(self.cfg.dataset, split=split) 42 | return dset 43 | 44 | 45 | def train(self) -> None: 46 | 47 | for split in self.cfg.splits: 48 | 49 | dset = self.get_dataset(split) 50 | global_idx = 0 51 | 52 | loader = DataLoader( 53 | dset, 54 | batch_size=self.cfg.batch_size, 55 | shuffle=False, 56 | num_workers=8, 57 | ) 58 | desc = f"Fitting {split} set" 59 | print(desc) 60 | 61 | for batch in progress_bar(loader, desc, 80): 62 | pcds, class_ids = batch 63 | bs = pcds.shape[0] 64 | 65 | if pcds.shape[1] != self.cfg.num_points_pcd: 66 | pcds = farthest_point_sampling(pcds, self.cfg.num_points_pcd) 67 | 68 | coords = [] 69 | labels = [] 70 | 71 | for idx in range(bs): 72 | pcd_coords, pcd_labels = compute_udf_from_pcd( 73 | pcds[idx].to("cuda"), 74 | self.cfg.num_queries_on_surface, 75 | self.cfg.stds, 76 | self.cfg.num_points_per_std, 77 | coords_range=(-1, 1), 78 | convert_to_bce_labels=True, 79 | ) 80 | coords.append(pcd_coords) 81 | labels.append(pcd_labels) 82 | 83 | coords = torch.stack(coords, dim=0) 84 | labels = torch.stack(labels, dim=0) 85 | 86 | coords_and_labels = torch.cat((coords, labels.unsqueeze(-1)), dim=-1).cuda() 87 | coords_and_labels = shuffle_pcd(coords_and_labels) 88 | 89 | triplane_params = self.cfg.triplane_params 90 | triplane = torch.nn.Parameter(torch.normal(torch.zeros(bs,3,triplane_params.resolution,triplane_params.resolution,triplane_params.hidden_dim, device="cuda"), torch.ones(bs,3,triplane_params.resolution,triplane_params.resolution,triplane_params.hidden_dim, device="cuda")*0.001)) 91 | 92 | mlps = [self.build_mlp(triplane_params).cuda() for _ in range(bs)] 93 | batched_params = get_mlps_batched_params(mlps) 94 | optimizer = hydra.utils.instantiate(self.cfg.opt, [triplane] + batched_params) 95 | 96 | for _ in progress_bar(range(self.cfg.num_steps)): 97 | selected_c_and_l = random_point_sampling( 98 | coords_and_labels, 99 | self.cfg.num_points_fitting, 100 | ) 101 | 102 | selected_coords = selected_c_and_l[:, :, :3] 103 | selected_labels = selected_c_and_l[:, :, 3] 104 | 105 | coords_xy = torch.cat((selected_coords[:, :, 0].unsqueeze(2), selected_coords[:, :, 1].unsqueeze(2)), dim=2) 106 | coords_xz = torch.cat((selected_coords[:, :, 0].unsqueeze(2), selected_coords[:, :, 2].unsqueeze(2)), dim=2) 107 | coords_zy = torch.cat((selected_coords[:, :, 1].unsqueeze(2), selected_coords[:, :, 2].unsqueeze(2)), dim=2) 108 | 109 | grid = torch.stack([coords_xy, coords_xz, coords_zy], dim=1) 110 | grid = grid.reshape(-1, self.cfg.num_points_fitting, 2).unsqueeze(1) 111 | features_sample = torch.nn.functional.grid_sample(triplane.reshape(-1, triplane_params.resolution, triplane_params.resolution, triplane_params.hidden_dim).permute(0, 3, 1, 2), grid).squeeze(2).squeeze(2).permute(0, 2, 1) 112 | features_sample = features_sample.reshape(bs, 3, self.cfg.num_points_fitting, triplane_params.hidden_dim) 113 | features_sample = features_sample.sum(1) 114 | # features_sample = torch.cat([features_sample[:, 0, ...], features_sample[:, 1, ...], features_sample[:, 0, ...]], dim=-1) 115 | 116 | batched_features = torch.cat([features_sample, self.coords_enc.embed(selected_coords)], dim=-1) 117 | pred = mlp_batched_forward(batched_params, batched_features) 118 | loss = F.binary_cross_entropy_with_logits(pred, selected_labels) 119 | optimizer.zero_grad() 120 | loss.backward() 121 | optimizer.step() 122 | 123 | 124 | for idx in range(bs): 125 | 126 | pcd = pcds[idx] 127 | class_id = class_ids[idx] 128 | 129 | flattened_params = [p[idx].view(-1) for p in batched_params] 130 | flattened_params = torch.cat(flattened_params, dim=0) 131 | 132 | h5_path = self.out_root / split / f"{global_idx}.h5" 133 | h5_path.parent.mkdir(parents=True, exist_ok=True) 134 | 135 | with h5py.File(h5_path, "w") as f: 136 | f.create_dataset("pcd", data=pcd.detach().cpu().numpy()) 137 | f.create_dataset("params", data=flattened_params.detach().cpu().numpy()) 138 | f.create_dataset("triplane", data=triplane[idx].permute(0,3,1,2).detach().cpu().numpy()) 139 | f.create_dataset("class_id", data=class_id.detach().cpu().numpy()) 140 | 141 | global_idx += 1 -------------------------------------------------------------------------------- /trainers/fit_triplane_pcd_part.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import List 3 | 4 | import torch 5 | import torch.nn.functional as F 6 | from pycarus.geometry.pcd import compute_udf_from_pcd, farthest_point_sampling 7 | from pycarus.geometry.pcd import random_point_sampling, shuffle_pcd 8 | from pycarus.learning.models.siren import SIREN 9 | from pycarus.utils import progress_bar 10 | from torch.optim import Adam 11 | from torch.utils.data import DataLoader, Dataset 12 | from torch import Tensor 13 | import open3d as o3d 14 | import hydra 15 | from utils.var import get_mlps_batched_params, mlp_batched_forward, unflatten_mlp_params, CoordsEncoder 16 | from pycarus.geometry.pcd import get_o3d_pcd_from_tensor, sample_pcds_from_udfs 17 | from pycarus.metrics.chamfer_distance import chamfer_t 18 | from pycarus.metrics.f_score import f_score 19 | import h5py 20 | import numpy as np 21 | import wandb 22 | class Fitter: 23 | def __init__(self, cfg) -> None: 24 | self.cfg = cfg 25 | self.out_root = Path(cfg.out_root) 26 | self.out_root.mkdir(parents=True, exist_ok=True) 27 | self.coords_enc = CoordsEncoder(3) 28 | 29 | def build_mlp(self, triplane_params) -> SIREN: 30 | mlp = SIREN( 31 | input_dim=triplane_params.hidden_dim+63, 32 | hidden_dim=triplane_params.mlp_hidden_dim, 33 | num_hidden_layers=triplane_params.mlp_num_hidden_layers, 34 | out_dim=1, 35 | ) 36 | # print(sum(p.numel() for p in mlp.parameters())) 37 | return mlp 38 | 39 | 40 | def get_dataset(self, split) -> Dataset: 41 | dset = hydra.utils.instantiate(self.cfg.dataset, split=split) 42 | return dset 43 | 44 | 45 | def train(self) -> None: 46 | 47 | for split in self.cfg.splits: 48 | 49 | dset = self.get_dataset(split) 50 | global_idx = 0 51 | 52 | loader = DataLoader( 53 | dset, 54 | batch_size=self.cfg.batch_size, 55 | shuffle=False, 56 | num_workers=8, 57 | ) 58 | desc = f"Fitting {split} set" 59 | print(desc) 60 | 61 | for batch in progress_bar(loader, desc, 80): 62 | pcds, class_ids, part_labels = batch 63 | bs = pcds.shape[0] 64 | 65 | if pcds.shape[1] != self.cfg.num_points_pcd: 66 | pcds = farthest_point_sampling(pcds, self.cfg.num_points_pcd) 67 | 68 | coords = [] 69 | labels = [] 70 | 71 | for idx in range(bs): 72 | pcd_coords, pcd_labels = compute_udf_from_pcd( 73 | pcds[idx].to("cuda"), 74 | self.cfg.num_queries_on_surface, 75 | self.cfg.stds, 76 | self.cfg.num_points_per_std, 77 | coords_range=(-1, 1), 78 | convert_to_bce_labels=True, 79 | ) 80 | coords.append(pcd_coords) 81 | labels.append(pcd_labels) 82 | 83 | coords = torch.stack(coords, dim=0) 84 | labels = torch.stack(labels, dim=0) 85 | 86 | coords_and_labels = torch.cat((coords, labels.unsqueeze(-1)), dim=-1).cuda() 87 | coords_and_labels = shuffle_pcd(coords_and_labels) 88 | 89 | triplane_params = self.cfg.triplane_params 90 | triplane = torch.nn.Parameter(torch.normal(torch.zeros(bs,3,triplane_params.resolution,triplane_params.resolution,triplane_params.hidden_dim, device="cuda"), torch.ones(bs,3,triplane_params.resolution,triplane_params.resolution,triplane_params.hidden_dim, device="cuda")*0.001)) 91 | 92 | mlps = [self.build_mlp(triplane_params).cuda() for _ in range(bs)] 93 | batched_params = get_mlps_batched_params(mlps) 94 | optimizer = hydra.utils.instantiate(self.cfg.opt, [triplane] + batched_params) 95 | 96 | for _ in progress_bar(range(self.cfg.num_steps)): 97 | selected_c_and_l = random_point_sampling( 98 | coords_and_labels, 99 | self.cfg.num_points_fitting, 100 | ) 101 | 102 | selected_coords = selected_c_and_l[:, :, :3] 103 | selected_labels = selected_c_and_l[:, :, 3] 104 | 105 | coords_xy = torch.cat((selected_coords[:, :, 0].unsqueeze(2), selected_coords[:, :, 1].unsqueeze(2)), dim=2) 106 | coords_xz = torch.cat((selected_coords[:, :, 0].unsqueeze(2), selected_coords[:, :, 2].unsqueeze(2)), dim=2) 107 | coords_zy = torch.cat((selected_coords[:, :, 1].unsqueeze(2), selected_coords[:, :, 2].unsqueeze(2)), dim=2) 108 | 109 | grid = torch.stack([coords_xy, coords_xz, coords_zy], dim=1) 110 | grid = grid.reshape(-1, self.cfg.num_points_fitting, 2).unsqueeze(1) 111 | features_sample = torch.nn.functional.grid_sample(triplane.reshape(-1, triplane_params.resolution, triplane_params.resolution, triplane_params.hidden_dim).permute(0, 3, 1, 2), grid).squeeze(2).squeeze(2).permute(0, 2, 1) 112 | features_sample = features_sample.reshape(bs, 3, self.cfg.num_points_fitting, triplane_params.hidden_dim) 113 | features_sample = features_sample.sum(1) 114 | # features_sample = torch.cat([features_sample[:, 0, ...], features_sample[:, 1, ...], features_sample[:, 0, ...]], dim=-1) 115 | 116 | batched_features = torch.cat([features_sample, self.coords_enc.embed(selected_coords)], dim=-1) 117 | pred = mlp_batched_forward(batched_params, batched_features) 118 | loss = F.binary_cross_entropy_with_logits(pred, selected_labels) 119 | optimizer.zero_grad() 120 | loss.backward() 121 | optimizer.step() 122 | 123 | 124 | for idx in range(bs): 125 | 126 | pcd = pcds[idx] 127 | class_id = class_ids[idx] 128 | part_label = part_labels[idx] 129 | 130 | flattened_params = [p[idx].view(-1) for p in batched_params] 131 | flattened_params = torch.cat(flattened_params, dim=0) 132 | 133 | h5_path = self.out_root / split / f"{global_idx}.h5" 134 | h5_path.parent.mkdir(parents=True, exist_ok=True) 135 | 136 | with h5py.File(h5_path, "w") as f: 137 | f.create_dataset("pcd", data=pcd.detach().cpu().numpy()) 138 | f.create_dataset("params", data=flattened_params.detach().cpu().numpy()) 139 | f.create_dataset("triplane", data=triplane[idx].permute(0,3,1,2).detach().cpu().numpy()) 140 | f.create_dataset("class_id", data=class_id.detach().cpu().numpy()) 141 | f.create_dataset("part_label", data=part_label.detach().cpu().numpy()) 142 | 143 | global_idx += 1 -------------------------------------------------------------------------------- /trainers/fit_triplane_voxel.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import List 3 | 4 | import torch 5 | import torch.nn.functional as F 6 | from pycarus.geometry.pcd import compute_udf_from_pcd, farthest_point_sampling 7 | from pycarus.geometry.pcd import random_point_sampling, shuffle_pcd, voxelize_pcd 8 | from pycarus.learning.models.siren import SIREN 9 | from pycarus.utils import progress_bar 10 | from torch.optim import Adam 11 | from torch.utils.data import DataLoader, Dataset 12 | from torch import Tensor 13 | import open3d as o3d 14 | import hydra 15 | from utils.var import get_mlps_batched_params, mlp_batched_forward, unflatten_mlp_params, CoordsEncoder, focal_loss 16 | from pycarus.geometry.pcd import get_o3d_pcd_from_tensor, sample_pcds_from_udfs 17 | from pycarus.metrics.chamfer_distance import chamfer_t 18 | from pycarus.metrics.f_score import f_score 19 | import h5py 20 | import numpy as np 21 | import wandb 22 | from einops import rearrange, repeat 23 | 24 | class Fitter: 25 | def __init__(self, cfg) -> None: 26 | self.cfg = cfg 27 | self.out_root = Path(cfg.out_root) 28 | self.out_root.mkdir(parents=True, exist_ok=True) 29 | self.coords_enc = CoordsEncoder(3) 30 | 31 | def build_mlp(self, triplane_params) -> SIREN: 32 | mlp = SIREN( 33 | input_dim=triplane_params.hidden_dim+63, 34 | hidden_dim=triplane_params.mlp_hidden_dim, 35 | num_hidden_layers=triplane_params.mlp_num_hidden_layers, 36 | out_dim=1, 37 | ) 38 | # print(sum(p.numel() for p in mlp.parameters())) 39 | return mlp 40 | 41 | 42 | def get_dataset(self, split) -> Dataset: 43 | dset = hydra.utils.instantiate(self.cfg.dataset, split=split) 44 | return dset 45 | 46 | 47 | def train(self) -> None: 48 | 49 | for split in self.cfg.splits: 50 | 51 | dset = self.get_dataset(split) 52 | global_idx = 0 53 | 54 | loader = DataLoader( 55 | dset, 56 | batch_size=self.cfg.batch_size, 57 | shuffle=False, 58 | num_workers=8, 59 | ) 60 | desc = f"Fitting {split} set" 61 | print(desc) 62 | 63 | for batch in progress_bar(loader, desc, 80): 64 | pcds, class_ids = batch 65 | pcds = pcds.to("cuda") 66 | bs = pcds.shape[0] 67 | 68 | if pcds.shape[1] != self.cfg.num_points_pcd: 69 | pcds = farthest_point_sampling(pcds, self.cfg.num_points_pcd) 70 | 71 | vgrids, centroids = voxelize_pcd(pcds, self.cfg.vox_res, -1, 1) 72 | 73 | coords = repeat(centroids, "r1 r2 r3 d -> b r1 r2 r3 d", b=bs) 74 | coords = rearrange(coords, "b r1 r2 r3 d -> b (r1 r2 r3) d") 75 | labels = rearrange(vgrids, "b r1 r2 r3 -> b (r1 r2 r3)") 76 | 77 | coords_and_labels = torch.cat((coords, labels.unsqueeze(-1)), dim=-1).cuda() 78 | coords_and_labels = shuffle_pcd(coords_and_labels) 79 | 80 | triplane_params = self.cfg.triplane_params 81 | triplane = torch.nn.Parameter(torch.normal(torch.zeros(bs,3,triplane_params.resolution,triplane_params.resolution,triplane_params.hidden_dim, device="cuda"), torch.ones(bs,3,triplane_params.resolution,triplane_params.resolution,triplane_params.hidden_dim, device="cuda")*0.001)) 82 | 83 | mlps = [self.build_mlp(triplane_params).cuda() for _ in range(bs)] 84 | batched_params = get_mlps_batched_params(mlps) 85 | optimizer = hydra.utils.instantiate(self.cfg.opt, [triplane] + batched_params) 86 | 87 | for _ in progress_bar(range(self.cfg.num_steps)): 88 | selected_c_and_l = random_point_sampling( 89 | coords_and_labels, 90 | self.cfg.num_points_fitting, 91 | ) 92 | 93 | selected_coords = selected_c_and_l[:, :, :3] 94 | selected_labels = selected_c_and_l[:, :, 3] 95 | 96 | coords_xy = torch.cat((selected_coords[:, :, 0].unsqueeze(2), selected_coords[:, :, 1].unsqueeze(2)), dim=2) 97 | coords_xz = torch.cat((selected_coords[:, :, 0].unsqueeze(2), selected_coords[:, :, 2].unsqueeze(2)), dim=2) 98 | coords_zy = torch.cat((selected_coords[:, :, 1].unsqueeze(2), selected_coords[:, :, 2].unsqueeze(2)), dim=2) 99 | 100 | grid = torch.stack([coords_xy, coords_xz, coords_zy], dim=1) 101 | grid = grid.reshape(-1, self.cfg.num_points_fitting, 2).unsqueeze(1) 102 | features_sample = torch.nn.functional.grid_sample(triplane.reshape(-1, triplane_params.resolution, triplane_params.resolution, triplane_params.hidden_dim).permute(0, 3, 1, 2), grid).squeeze(2).squeeze(2).permute(0, 2, 1) 103 | features_sample = features_sample.reshape(bs, 3, self.cfg.num_points_fitting, triplane_params.hidden_dim) 104 | features_sample = features_sample.sum(1) 105 | 106 | batched_features = torch.cat([features_sample, self.coords_enc.embed(selected_coords)], dim=-1) 107 | pred = mlp_batched_forward(batched_params, batched_features) 108 | loss = focal_loss(pred, selected_labels) 109 | optimizer.zero_grad() 110 | loss.backward() 111 | optimizer.step() 112 | 113 | 114 | for idx in range(bs): 115 | 116 | pcd = pcds[idx] 117 | class_id = class_ids[idx] 118 | 119 | flattened_params = [p[idx].view(-1) for p in batched_params] 120 | flattened_params = torch.cat(flattened_params, dim=0) 121 | 122 | h5_path = self.out_root / split / f"{global_idx}.h5" 123 | h5_path.parent.mkdir(parents=True, exist_ok=True) 124 | 125 | with h5py.File(h5_path, "w") as f: 126 | f.create_dataset("pcd", data=pcd.detach().cpu().numpy()) 127 | f.create_dataset("params", data=flattened_params.detach().cpu().numpy()) 128 | f.create_dataset("triplane", data=triplane[idx].permute(0,3,1,2).detach().cpu().numpy()) 129 | f.create_dataset("class_id", data=class_id.detach().cpu().numpy()) 130 | 131 | global_idx += 1 132 | 133 | 134 | def evaluate(self) -> None: 135 | triplane_params = self.cfg.triplane_params 136 | mlp = self.build_mlp(triplane_params).cuda() 137 | 138 | for split in self.cfg.splits: 139 | 140 | print(f'evaluating {split}') 141 | 142 | cdts = [] 143 | fscores = [] 144 | 145 | dset_root = (Path(self.cfg.out_root) / split).glob("*.h5") 146 | mlps_paths = sorted(list(dset_root), key=lambda p: int(p.stem)) 147 | print(f"evaluating with {len(mlps_paths)} shapes") 148 | 149 | for idx in progress_bar(range(len(mlps_paths))): 150 | 151 | with h5py.File(mlps_paths[idx], "r") as f: 152 | gt_pc = torch.from_numpy(np.array(f.get("pcd"))) 153 | params = torch.from_numpy(np.array(f.get("params"))) 154 | triplane = torch.from_numpy(np.array(f.get("triplane"))).cuda() 155 | 156 | mlp.load_state_dict(unflatten_mlp_params(params, mlp.state_dict())) 157 | 158 | ##visualize 159 | gt_vgrid, centroids = voxelize_pcd(gt_pc, self.cfg.vox_res, -1, 1) 160 | pcd_gt = centroids[gt_vgrid == 1] 161 | 162 | centr = centroids.unsqueeze(0).cuda() 163 | centr = rearrange(centr, "b r1 r2 r3 d -> b (r1 r2 r3) d") 164 | 165 | coords = centr.squeeze(0) 166 | coords_xy = torch.cat((coords[:, 0].unsqueeze(1), coords[:, 1].unsqueeze(1)), dim=1) 167 | coords_xz = torch.cat((coords[:, 0].unsqueeze(1), coords[:, 2].unsqueeze(1)), dim=1) 168 | coords_zy = torch.cat((coords[:, 1].unsqueeze(1), coords[:, 2].unsqueeze(1)), dim=1) 169 | grid = torch.stack([coords_xy, coords_xz, coords_zy], dim=0).unsqueeze(1).cuda() 170 | features = torch.nn.functional.grid_sample(triplane, grid).squeeze(2).permute(0, 2, 1) 171 | features = features.sum(0) 172 | features = torch.cat([features, self.coords_enc.embed(coords)], dim=-1) 173 | 174 | vgrid_pred = torch.sigmoid(mlp(features)[0]) 175 | 176 | vgrid_pred = vgrid_pred.squeeze(1) 177 | centr = centr.squeeze(0) 178 | 179 | vgrid_pred_npz = torch.zeros_like(gt_vgrid) 180 | vgrid_pred_npz[vgrid_pred.reshape(64,64,64) > 0.3] = 1 181 | np.savez(f'reconstrauctions_shapenet_vox/{idx}', voxel=vgrid_pred_npz) 182 | 183 | mlp_pcd = centr[vgrid_pred > 0.3] 184 | mlp_pcd_o3d = get_o3d_pcd_from_tensor(mlp_pcd.cpu()) 185 | o3d.io.write_point_cloud(f'reconstrauctions_shapenet_vox/{idx}.pcd', mlp_pcd_o3d) 186 | 187 | cd = chamfer_t(mlp_pcd, pcd_gt.cuda()) 188 | cdts.append(cd.item()) 189 | f = f_score(mlp_pcd, pcd_gt.cuda(), threshold=0.01)[0] 190 | fscores.append(f.item()) 191 | 192 | mean_cdt = sum(cdts) / len(cdts) 193 | mean_fscore = sum(fscores) / len(fscores) 194 | print("mean CD", mean_cdt) 195 | print("mean fscore", mean_fscore) 196 | wandb.log({f"mean_cdt_{split}": mean_cdt, f"mean_fscore_{split}": mean_fscore}) -------------------------------------------------------------------------------- /trainers/triplane_classifier.py: -------------------------------------------------------------------------------- 1 | import imp 2 | import importlib 3 | import inspect 4 | from statistics import median 5 | from typing import Any 6 | 7 | import numpy as np 8 | import pytorch_lightning as pl 9 | import torch 10 | import torch.nn.functional as F 11 | from torch import nn 12 | from torch import optim 13 | import torchmetrics 14 | 15 | class TrainModel(pl.LightningModule): 16 | def __init__( 17 | self, 18 | network = None, 19 | optimizer: optim.Optimizer = None, 20 | scheduler: optim.lr_scheduler = None, 21 | loss = None, 22 | cfg = None, 23 | dm = None 24 | ): 25 | super().__init__() 26 | self.train_acc = torchmetrics.Accuracy(task='multiclass', num_classes=cfg.dataset.num_classes) 27 | self.val_acc = torchmetrics.Accuracy(task='multiclass', num_classes=cfg.dataset.num_classes) 28 | self.test_acc = torchmetrics.Accuracy(task='multiclass', num_classes=cfg.dataset.num_classes) 29 | self.optimizer = optimizer 30 | self.scheduler = scheduler 31 | self.loss = loss 32 | self.net = network 33 | self.best_valid_acc = 0 34 | self.validation_step_outputs = {} 35 | self.validation_step_outputs["loss"] = [] 36 | self.test_step_outputs = {} 37 | self.test_step_outputs["loss"] = [] 38 | self.train_step_outputs = {} 39 | self.train_step_outputs["loss"] = [] 40 | self.save_hyperparameters(cfg) 41 | 42 | def configure_optimizers(self): 43 | return [self.optimizer], [{"scheduler": self.scheduler, "interval": "step"}] 44 | 45 | def forward(self, x): 46 | output = self.net(x) 47 | return output 48 | 49 | def training_step(self, batch, batch_idx): 50 | triplanes, labels = batch 51 | 52 | predictions = self(triplanes) 53 | loss = self.loss(predictions, labels) 54 | 55 | self.train_acc(F.softmax(predictions, dim=1), labels) 56 | self.train_step_outputs["loss"].append(loss.item()) 57 | 58 | return loss 59 | 60 | def on_train_epoch_end(self): 61 | 62 | valid_acc = self.train_acc.compute().item() 63 | avg_loss_valid = np.mean(self.train_step_outputs["loss"]) 64 | 65 | self.log_dict( 66 | { 67 | "train/loss": avg_loss_valid, 68 | "train/acc": valid_acc, 69 | } 70 | ) 71 | 72 | self.train_acc.reset() 73 | self.train_step_outputs.clear() 74 | self.train_step_outputs["loss"] = [] 75 | 76 | def validation_step(self, batch, batch_idx, dataloader_idx): 77 | triplanes, labels = batch 78 | 79 | predictions = self(triplanes) 80 | loss = self.loss(predictions, labels) 81 | 82 | if dataloader_idx == 0: 83 | self.val_acc(F.softmax(predictions, dim=1), labels) 84 | self.validation_step_outputs["loss"].append(loss.item()) 85 | 86 | if dataloader_idx == 1: 87 | self.test_acc(F.softmax(predictions, dim=1), labels) 88 | self.test_step_outputs["loss"].append(loss.item()) 89 | 90 | predictions = (predictions.argmax(dim=1), labels) 91 | return predictions 92 | 93 | 94 | def on_validation_epoch_end(self): 95 | 96 | valid_acc = self.val_acc.compute().item() 97 | avg_loss_valid = np.mean(self.validation_step_outputs["loss"]) 98 | 99 | test_acc = self.test_acc.compute().item() 100 | avg_loss_test = np.mean(self.test_step_outputs["loss"]) 101 | 102 | if valid_acc > self.best_valid_acc and self.global_step != 0: 103 | self.logger.log_metrics({"best_valid_accuracy": valid_acc}) 104 | self.best_valid_acc = valid_acc 105 | 106 | self.log_dict( 107 | { 108 | "val/loss": avg_loss_valid, 109 | "val/acc": valid_acc, 110 | } 111 | ) 112 | 113 | self.log_dict( 114 | { 115 | "test/loss": avg_loss_test, 116 | "test/acc": test_acc, 117 | } 118 | ) 119 | 120 | self.val_acc.reset() 121 | self.test_acc.reset() 122 | self.validation_step_outputs.clear() 123 | self.test_step_outputs.clear() 124 | self.validation_step_outputs["loss"] = [] 125 | self.test_step_outputs["loss"] = [] 126 | 127 | def test_step(self, batch, batch_idx): 128 | self.validation_step(batch, batch_idx, 1) 129 | 130 | def on_test_epoch_end(self): 131 | 132 | test_acc = self.test_acc.compute().item() 133 | avg_loss_test = np.mean(self.test_step_outputs["loss"]) 134 | 135 | self.log_dict( 136 | { 137 | "test/final_loss": avg_loss_test, 138 | "test/final_acc": test_acc, 139 | } 140 | ) 141 | 142 | 143 | -------------------------------------------------------------------------------- /trainers/triplane_part_seg.py: -------------------------------------------------------------------------------- 1 | import imp 2 | import importlib 3 | import inspect 4 | from statistics import median 5 | from typing import Any 6 | 7 | import numpy as np 8 | import pytorch_lightning as pl 9 | import torch 10 | import torch.nn.functional as F 11 | from torch import nn 12 | from torch import optim 13 | from pycarus.metrics.partseg_iou import PartSegmentationIoU 14 | from pycarus.datasets.utils import get_shape_net_category_name_from_id 15 | from utils.var import CoordsEncoder 16 | from torch import Tensor 17 | import wandb 18 | 19 | class TrainModel(pl.LightningModule): 20 | def __init__( 21 | self, 22 | network = None, 23 | optimizer: optim.Optimizer = None, 24 | scheduler: optim.lr_scheduler = None, 25 | loss = None, 26 | cfg = None, 27 | seg_classes = None 28 | ): 29 | super().__init__() 30 | self.train_iou = PartSegmentationIoU( 31 | use_only_category_logits=True, category_to_parts_map=seg_classes 32 | ) 33 | self.val_iou = PartSegmentationIoU( 34 | use_only_category_logits=True, category_to_parts_map=seg_classes 35 | ) 36 | self.test_iou = PartSegmentationIoU( 37 | use_only_category_logits=True, category_to_parts_map=seg_classes 38 | ) 39 | self.optimizer = optimizer 40 | self.scheduler = scheduler 41 | self.loss = loss 42 | self.net = network 43 | self.best_valid_iou = 0 44 | self.validation_step_outputs = {} 45 | self.validation_step_outputs["loss"] = [] 46 | self.test_step_outputs = {} 47 | self.test_step_outputs["loss"] = [] 48 | self.train_step_outputs = {} 49 | self.train_step_outputs["loss"] = [] 50 | self.coords_enc = CoordsEncoder(3) 51 | self.save_hyperparameters(cfg) 52 | 53 | def configure_optimizers(self): 54 | return [self.optimizer], [{"scheduler": self.scheduler, "interval": "step"}] 55 | 56 | def forward(self, x, class_labels, pcd): 57 | output = self.net(x, class_labels, pcd) 58 | return output 59 | 60 | def get_one_hot_encoding(self, x: Tensor, num_classes: int) -> Tensor: 61 | one_hot = torch.eye(num_classes)[x.cpu()] 62 | one_hot = one_hot.to(x.device) 63 | return one_hot 64 | 65 | def training_step(self, batch, batch_idx): 66 | triplanes, labels, part_labels, pcds = batch 67 | 68 | rand = torch.rand(pcds.shape[0], pcds.shape[1], device="cuda") 69 | batch_rand_perm = rand.argsort(dim=1) 70 | 71 | for idx in range(pcds.shape[0]): 72 | pcds[idx] = pcds[idx, batch_rand_perm[idx], :] 73 | part_labels[idx] = part_labels[idx, batch_rand_perm[idx]] 74 | 75 | class_labels = self.get_one_hot_encoding(labels, self.hparams.dataset.num_classes) 76 | coords = self.coords_enc.embed(pcds) 77 | out = self(triplanes, class_labels, coords) 78 | 79 | predictions = out.contiguous().view(-1, self.hparams.dataset.num_parts) 80 | loss = self.loss(predictions, part_labels.view(-1) ) 81 | 82 | self.train_iou.update(out, part_labels) 83 | self.train_step_outputs["loss"].append(loss.item()) 84 | 85 | return loss 86 | 87 | def on_train_epoch_end(self): 88 | 89 | _, train_class_avg_iou, train_iou = self.train_iou.compute() 90 | avg_loss_valid = np.mean(self.train_step_outputs["loss"]) 91 | 92 | self.log_dict( 93 | { 94 | "train/loss": avg_loss_valid, 95 | "train/iou": train_iou, 96 | "train/class_iou": train_class_avg_iou, 97 | },sync_dist=True 98 | ) 99 | 100 | self.train_iou.reset() 101 | self.train_step_outputs.clear() 102 | self.train_step_outputs["loss"] = [] 103 | 104 | def validation_step(self, batch, batch_idx, dataloader_idx): 105 | triplanes, labels, part_labels, pcds = batch 106 | 107 | class_labels = self.get_one_hot_encoding(labels, self.hparams.dataset.num_classes) 108 | coords = self.coords_enc.embed(pcds) 109 | out = self(triplanes, class_labels, coords) 110 | 111 | predictions = out.contiguous().view(-1, self.hparams.dataset.num_parts) 112 | loss = self.loss(predictions, part_labels.view(-1) ) 113 | 114 | if dataloader_idx == 0: 115 | self.val_iou.update(out, part_labels) 116 | self.validation_step_outputs["loss"].append(loss.item()) 117 | 118 | if dataloader_idx == 1: 119 | self.test_iou.update(out, part_labels) 120 | self.test_step_outputs["loss"].append(loss.item()) 121 | 122 | # predictions = (predictions.argmax(dim=1), part_labels) 123 | return loss 124 | 125 | 126 | def on_validation_epoch_end(self): 127 | 128 | _, valid_class_avg_iou, valid_iou = self.val_iou.compute() 129 | avg_loss_valid = np.mean(self.validation_step_outputs["loss"]) 130 | 131 | _, test_class_avg_iou, test_iou = self.test_iou.compute() 132 | avg_loss_test = np.mean(self.test_step_outputs["loss"]) 133 | 134 | if valid_iou > self.best_valid_iou and self.global_step != 0: 135 | self.logger.log_metrics({"best_valid_iou": valid_iou}) 136 | self.best_valid_iou = valid_iou 137 | 138 | self.log_dict( 139 | { 140 | "val/loss": avg_loss_valid, 141 | "val/iou": valid_iou, 142 | "val/class_iou": valid_class_avg_iou, 143 | } ,sync_dist=True 144 | ) 145 | 146 | self.log_dict( 147 | { 148 | "test/loss": avg_loss_test, 149 | "test/iou": test_iou, 150 | "test/class_iou": test_class_avg_iou, 151 | },sync_dist=True 152 | ) 153 | 154 | self.val_iou.reset() 155 | self.test_iou.reset() 156 | self.validation_step_outputs.clear() 157 | self.test_step_outputs.clear() 158 | self.validation_step_outputs["loss"] = [] 159 | self.test_step_outputs["loss"] = [] 160 | 161 | def test_step(self, batch, batch_idx): 162 | self.validation_step(batch, batch_idx, 1) 163 | 164 | def on_test_epoch_end(self): 165 | 166 | test_mIoU_per_cat, test_class_avg_iou, test_iou = self.test_iou.compute() 167 | avg_loss_test = np.mean(self.test_step_outputs["loss"]) 168 | 169 | self.log_dict( 170 | { 171 | "test/final_loss": avg_loss_test, 172 | "test/final_iou": test_iou, 173 | "test/final_class_iou": test_class_avg_iou, 174 | },sync_dist=True 175 | ) 176 | 177 | if self.global_rank == 0: 178 | table = wandb.Table(columns=["class", "ioU"]) 179 | for cat, miou in test_mIoU_per_cat.items(): 180 | table.add_data(get_shape_net_category_name_from_id(cat), miou) 181 | wandb.log({"class IoU": table}) 182 | 183 | 184 | -------------------------------------------------------------------------------- /triplane_cls.py: -------------------------------------------------------------------------------- 1 | import hydra 2 | from omegaconf import OmegaConf 3 | import wandb 4 | from pathlib import Path 5 | import importlib 6 | import pytorch_lightning as pl 7 | from pytorch_lightning.strategies.ddp import DDPStrategy 8 | from pytorch_lightning.loggers import WandbLogger 9 | from datamodules.datamodule import load_datamodule 10 | from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint 11 | import time 12 | 13 | code_pos = Path(__file__) 14 | 15 | @hydra.main(config_path="cfg/triplanes_classify", config_name="main", version_base="1.1") 16 | def main(cfg) -> None: 17 | print("trainers/" + cfg.trainer.module_name) 18 | trainer_module = importlib.import_module("trainers." + cfg.trainer.module_name) 19 | print(OmegaConf.to_yaml(cfg, resolve=True)) 20 | wandb.config = OmegaConf.to_container( 21 | cfg, resolve=True, throw_on_missing=True 22 | ) 23 | 24 | logger = WandbLogger( 25 | entity=cfg.wandb.entity, 26 | project=cfg.wandb.project, 27 | name=cfg.wandb.run_name, 28 | dir=cfg.wandb.dir, 29 | save_dir=cfg.wandb.dir, 30 | config=OmegaConf.to_container( 31 | cfg, resolve=True, throw_on_missing=True 32 | ) 33 | ) 34 | 35 | artifact = wandb.Artifact("Trainer", type="code") 36 | artifact.add_file("trainers/" + cfg.trainer.module_name + ".py") 37 | logger.experiment.log_artifact(artifact) 38 | 39 | ckpt_callback = ModelCheckpoint( 40 | dirpath= Path(cfg.wandb.dir) / cfg.wandb.run_name / "ckpts", 41 | filename="{epoch}-{step}", 42 | monitor="val/acc", 43 | mode="max", 44 | save_top_k=1, 45 | save_last=False, 46 | ) 47 | lr_monitor = LearningRateMonitor(logging_interval='step') 48 | trainer = pl.Trainer( 49 | strategy=DDPStrategy( 50 | find_unused_parameters=cfg.runtime.get("find_unused_parameters", True) 51 | ) 52 | if cfg.runtime.gpus > 1 53 | else "auto", 54 | precision=cfg.runtime.precision, 55 | benchmark=True, 56 | logger=logger, 57 | callbacks=[ckpt_callback, lr_monitor], 58 | max_epochs=cfg.train.num_epochs, 59 | check_val_every_n_epoch=cfg.val.checkpoint_period, 60 | log_every_n_steps=200, 61 | ) 62 | 63 | dm = load_datamodule( 64 | cfg 65 | ) 66 | 67 | dl_train = dm.train_dataloader() 68 | dl_val = dm.val_dataloader() 69 | 70 | cfg.network.embedding_dim = cfg.train_transform.random_crop if cfg.train_transform.random_crop>0 else cfg.network.embedding_dim 71 | network = hydra.utils.instantiate(cfg.network) 72 | print("num_params:", sum(p.numel() for p in network.parameters())) 73 | loss = hydra.utils.instantiate(cfg.loss) 74 | optimizer = hydra.utils.instantiate(cfg.opt, network.parameters()) 75 | scheduler = hydra.utils.instantiate(cfg.scheduler, optimizer, cfg.opt.lr, total_steps=len(dl_train) * cfg.train.num_epochs) 76 | 77 | model = trainer_module.TrainModel( 78 | network=network, 79 | loss=loss, 80 | optimizer=optimizer, 81 | scheduler=scheduler, 82 | cfg=cfg 83 | # train_kwargs=train_args["params"], 84 | # model_kwargs=model_args, 85 | ) 86 | 87 | trainer.fit( 88 | model, 89 | train_dataloaders=dl_train, 90 | val_dataloaders=dl_val, 91 | ) 92 | 93 | dl_test = dm.test_dataloader() 94 | trainer.test(ckpt_path="best", dataloaders=dl_test) 95 | wandb.finish() 96 | 97 | 98 | if __name__ == "__main__": 99 | main() 100 | -------------------------------------------------------------------------------- /triplane_fit_mesh.py: -------------------------------------------------------------------------------- 1 | import hydra 2 | from omegaconf import OmegaConf 3 | import wandb 4 | from pathlib import Path 5 | import importlib 6 | 7 | code_pos = Path(__file__) 8 | 9 | @hydra.main(config_path="cfg/triplane_mesh_fit", config_name="main", version_base="1.1") 10 | def main(cfg) -> None: 11 | print("trainers/" + cfg.trainer.module_name) 12 | trainer_module = importlib.import_module("trainers." + cfg.trainer.module_name) 13 | print(OmegaConf.to_yaml(cfg, resolve=True)) 14 | wandb.config = OmegaConf.to_container( 15 | cfg, resolve=True, throw_on_missing=True 16 | ) 17 | run = wandb.init( 18 | entity=cfg.wandb.entity, 19 | project=cfg.wandb.project, 20 | name=cfg.wandb.run_name, 21 | dir=cfg.wandb.dir, 22 | config=OmegaConf.to_container( 23 | cfg, resolve=True, throw_on_missing=True 24 | ) 25 | ) 26 | artifact = wandb.Artifact("Trainer", type="code") 27 | artifact.add_file("trainers/" + cfg.trainer.module_name + ".py") 28 | run.log_artifact(artifact) 29 | 30 | trainer = trainer_module.Fitter(cfg) 31 | trainer.train() 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /triplane_fit_pc.py: -------------------------------------------------------------------------------- 1 | import hydra 2 | from omegaconf import OmegaConf 3 | import wandb 4 | from pathlib import Path 5 | import importlib 6 | 7 | code_pos = Path(__file__) 8 | 9 | @hydra.main(config_path="cfg/triplane_pcd_fit", config_name="main", version_base="1.1") 10 | def main(cfg) -> None: 11 | print("trainers/" + cfg.trainer.module_name) 12 | trainer_module = importlib.import_module("trainers." + cfg.trainer.module_name) 13 | print(OmegaConf.to_yaml(cfg, resolve=True)) 14 | wandb.config = OmegaConf.to_container( 15 | cfg, resolve=True, throw_on_missing=True 16 | ) 17 | run = wandb.init( 18 | entity=cfg.wandb.entity, 19 | project=cfg.wandb.project, 20 | name=cfg.wandb.run_name, 21 | dir=cfg.wandb.dir, 22 | config=OmegaConf.to_container( 23 | cfg, resolve=True, throw_on_missing=True 24 | ) 25 | ) 26 | artifact = wandb.Artifact("Trainer", type="code") 27 | artifact.add_file("trainers/" + cfg.trainer.module_name + ".py") 28 | run.log_artifact(artifact) 29 | 30 | trainer = trainer_module.Fitter(cfg) 31 | trainer.train() 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /triplane_fit_pc_part_seg.py: -------------------------------------------------------------------------------- 1 | import hydra 2 | from omegaconf import OmegaConf 3 | import wandb 4 | from pathlib import Path 5 | import importlib 6 | 7 | code_pos = Path(__file__) 8 | 9 | @hydra.main(config_path="cfg/triplane_pcd_part_fit", config_name="main", version_base="1.1") 10 | def main(cfg) -> None: 11 | print("trainers/" + cfg.trainer.module_name) 12 | trainer_module = importlib.import_module("trainers." + cfg.trainer.module_name) 13 | print(OmegaConf.to_yaml(cfg, resolve=True)) 14 | wandb.config = OmegaConf.to_container( 15 | cfg, resolve=True, throw_on_missing=True 16 | ) 17 | run = wandb.init( 18 | entity=cfg.wandb.entity, 19 | project=cfg.wandb.project, 20 | name=cfg.wandb.run_name, 21 | dir=cfg.wandb.dir, 22 | config=OmegaConf.to_container( 23 | cfg, resolve=True, throw_on_missing=True 24 | ) 25 | ) 26 | artifact = wandb.Artifact("Trainer", type="code") 27 | artifact.add_file("trainers/" + cfg.trainer.module_name + ".py") 28 | run.log_artifact(artifact) 29 | 30 | trainer = trainer_module.Fitter(cfg) 31 | trainer.train() 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /triplane_fit_voxel.py: -------------------------------------------------------------------------------- 1 | import hydra 2 | from omegaconf import OmegaConf 3 | import wandb 4 | from pathlib import Path 5 | import importlib 6 | 7 | code_pos = Path(__file__) 8 | 9 | @hydra.main(config_path="cfg/triplane_voxel_fit", config_name="main", version_base="1.1") 10 | def main(cfg) -> None: 11 | print("trainers/" + cfg.trainer.module_name) 12 | trainer_module = importlib.import_module("trainers." + cfg.trainer.module_name) 13 | print(OmegaConf.to_yaml(cfg, resolve=True)) 14 | wandb.config = OmegaConf.to_container( 15 | cfg, resolve=True, throw_on_missing=True 16 | ) 17 | run = wandb.init( 18 | entity=cfg.wandb.entity, 19 | project=cfg.wandb.project, 20 | name=cfg.wandb.run_name, 21 | dir=cfg.wandb.dir, 22 | config=OmegaConf.to_container( 23 | cfg, resolve=True, throw_on_missing=True 24 | ) 25 | ) 26 | artifact = wandb.Artifact("Trainer", type="code") 27 | artifact.add_file("trainers/" + cfg.trainer.module_name + ".py") 28 | run.log_artifact(artifact) 29 | 30 | trainer = trainer_module.Fitter(cfg) 31 | trainer.train() 32 | trainer.evaluate() 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /utils/var.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from typing import Dict, List, OrderedDict, Tuple 3 | 4 | import numpy as np 5 | import torch 6 | from pycarus.learning.models.siren import SIREN 7 | from pycarus.geometry.pcd import knn, sample_points_around_pcd 8 | from sklearn.neighbors import KDTree 9 | from torch import Tensor 10 | from typing import Callable, Tuple 11 | import torch.nn.functional as F 12 | 13 | class CoordsEncoder: 14 | def __init__( 15 | self, 16 | input_dims: int = 3, 17 | include_input: bool = True, 18 | max_freq_log2: int = 9, 19 | num_freqs: int = 10, 20 | log_sampling: bool = True, 21 | periodic_fns: Tuple[Callable, Callable] = (torch.sin, torch.cos), 22 | ) -> None: 23 | self.input_dims = input_dims 24 | self.include_input = include_input 25 | self.max_freq_log2 = max_freq_log2 26 | self.num_freqs = num_freqs 27 | self.log_sampling = log_sampling 28 | self.periodic_fns = periodic_fns 29 | self.create_embedding_fn() 30 | 31 | def create_embedding_fn(self) -> None: 32 | embed_fns = [] 33 | d = self.input_dims 34 | out_dim = 0 35 | if self.include_input: 36 | embed_fns.append(lambda x: x) 37 | out_dim += d 38 | 39 | if self.log_sampling: 40 | freq_bands = 2.0 ** torch.linspace(0.0, self.max_freq_log2, steps=self.num_freqs) 41 | else: 42 | freq_bands = torch.linspace(2.0**0.0, 2.0**self.max_freq_log2, steps=self.num_freqs) 43 | 44 | for freq in freq_bands: 45 | for p_fn in self.periodic_fns: 46 | embed_fns.append(lambda x, p_fn=p_fn, freq=freq: p_fn(x * freq)) 47 | out_dim += d 48 | 49 | self.embed_fns = embed_fns 50 | self.out_dim = out_dim 51 | 52 | def embed(self, inputs: Tensor) -> Tensor: 53 | return torch.cat([fn(inputs) for fn in self.embed_fns], -1) 54 | 55 | def compute_partseg_labels( 56 | pcd: Tensor, 57 | pcd_labels: Tensor, 58 | stds: List[float], 59 | num_points_per_std: List[int], 60 | coords_range: Tuple[float, float], 61 | surface_th: float, 62 | empty_label: int, 63 | ) -> Tuple[Tensor, Tensor]: 64 | coords = sample_points_around_pcd(pcd, stds, num_points_per_std, coords_range, "cuda") 65 | indices, _, distances = knn(coords, pcd.cuda(), 1) 66 | indices = indices.squeeze(-1) 67 | distances = distances.squeeze(-1) 68 | 69 | labels = torch.zeros((coords.shape[0],)).long().cuda() 70 | labels[distances > surface_th] = empty_label 71 | labels[distances <= surface_th] = pcd_labels[indices[distances <= surface_th]].cuda() 72 | 73 | return coords, labels 74 | 75 | def get_mlps_batched_params(mlps: List[SIREN]) -> List[Tensor]: 76 | params = [] 77 | for i in range(len(mlps)): 78 | params.append(list(mlps[i].parameters())) 79 | 80 | batched_params = [] 81 | for i in range(len(params[0])): 82 | p = torch.stack([p[i] for p in params], dim=0) 83 | p = torch.clone(p.detach()) 84 | p.requires_grad = True 85 | batched_params.append(p) 86 | 87 | return batched_params 88 | 89 | 90 | def flatten_mlp_params(sd: OrderedDict[str, Tensor]) -> Tensor: 91 | all_params = [] 92 | for k in sd: 93 | all_params.append(sd[k].view(-1)) 94 | all_params = torch.cat(all_params, dim=-1) 95 | return all_params 96 | 97 | 98 | def unflatten_mlp_params( 99 | params: Tensor, 100 | sample_sd: OrderedDict[str, Tensor], 101 | ) -> OrderedDict[str, Tensor]: 102 | sd = collections.OrderedDict() 103 | 104 | start = 0 105 | for k in sample_sd: 106 | end = start + sample_sd[k].numel() 107 | layer_params = params[start:end].view(sample_sd[k].shape) 108 | sd[k] = layer_params 109 | start = end 110 | 111 | return sd 112 | 113 | def get_mlp_params_as_matrix(flattened_params: Tensor, sd: OrderedDict) -> Tensor: 114 | params_shapes = [p.shape for p in sd.values()] 115 | feat_dim = params_shapes[0][0] 116 | start = params_shapes[0].numel() + params_shapes[1].numel() 117 | end = params_shapes[-1].numel() + params_shapes[-2].numel() 118 | params = flattened_params[start:-end] 119 | return params.reshape((-1, feat_dim)) 120 | 121 | 122 | def mlp_batched_forward(batched_params: List[Tensor], coords: Tensor) -> Tensor: 123 | num_layers = len(batched_params) // 2 124 | 125 | f = coords 126 | 127 | for i in range(num_layers): 128 | weights = batched_params[i * 2] 129 | biases = batched_params[i * 2 + 1] 130 | 131 | f = torch.bmm(f, weights.permute(0, 2, 1)) + biases.unsqueeze(1) 132 | 133 | if i < num_layers - 1: 134 | f = torch.sin(30 * f) 135 | 136 | return f.squeeze(-1) 137 | 138 | 139 | def get_recalls(gallery: Tensor, labels_gallery: Tensor, kk: List[int]) -> Dict[int, float]: 140 | """Computes the recall using different nearest neighbors searches. 141 | 142 | Args: 143 | gallery: the gallery containing all the embeddings for the dataset. 144 | kk: the number of nearest neighbors to use for each recall. 145 | 146 | Returns: 147 | The computed recalls with different nearest neighbors searches. 148 | """ 149 | max_nn = max(kk) 150 | recalls = {idx: 0.0 for idx in kk} 151 | targets = labels_gallery.cpu().numpy() 152 | gallery = gallery.cpu().numpy() 153 | tree = KDTree(gallery) 154 | 155 | for query, label_query in zip(gallery, targets): 156 | with torch.no_grad(): 157 | query = np.expand_dims(query, 0) 158 | _, indices_matched = tree.query(query, k=max_nn + 1) 159 | indices_matched = indices_matched[0] 160 | 161 | for k in kk: 162 | indices_matched_temp = indices_matched[1 : k + 1] 163 | classes_matched = targets[indices_matched_temp] 164 | recalls[k] += np.count_nonzero(classes_matched == label_query) > 0 165 | 166 | for key, value in recalls.items(): 167 | recalls[key] = value / (1.0 * len(gallery)) 168 | 169 | return recalls 170 | 171 | def focal_loss(pred: Tensor, gt: Tensor, alpha: float = 0.1, gamma: float = 3) -> Tensor: 172 | alpha_w = torch.tensor([alpha, 1 - alpha]).cuda() 173 | 174 | bce_loss = F.binary_cross_entropy_with_logits(pred, gt.float(), reduction="none") 175 | bce_loss = bce_loss.view(-1) 176 | 177 | gt = gt.type(torch.long) 178 | at = alpha_w.gather(0, gt.view(-1)) 179 | pt = torch.exp(-bce_loss) 180 | f_loss = at * ((1 - pt) ** gamma) * bce_loss 181 | 182 | return f_loss.mean() --------------------------------------------------------------------------------