diff --git a/.gitattributes b/.gitattributes index 7e4a8e4bc8d33ce6e1e17b3774ae66ee67e40732..672d35e53dac6b109179ce4122330f7e13bbb5f6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -43,3 +43,13 @@ fp16/slat_fuse.onnx.data filter=lfs diff=lfs merge=lfs -text fp16/ss_dec.onnx.data filter=lfs diff=lfs merge=lfs -text fp16/ss_flow.onnx.data filter=lfs diff=lfs merge=lfs -text fp16/ss_fuse.onnx.data filter=lfs diff=lfs merge=lfs -text +int8/dino.onnx.data filter=lfs diff=lfs merge=lfs -text +int8/mesh_conv.onnx.data filter=lfs diff=lfs merge=lfs -text +int8/mesh_dec.onnx.data filter=lfs diff=lfs merge=lfs -text +int8/mesh_out.onnx.data filter=lfs diff=lfs merge=lfs -text +int8/moge.onnx.data filter=lfs diff=lfs merge=lfs -text +int8/slat_flow.onnx.data filter=lfs diff=lfs merge=lfs -text +int8/slat_fuse.onnx.data filter=lfs diff=lfs merge=lfs -text +int8/ss_dec.onnx.data filter=lfs diff=lfs merge=lfs -text +int8/ss_flow.onnx.data filter=lfs diff=lfs merge=lfs -text +int8/ss_fuse.onnx.data filter=lfs diff=lfs merge=lfs -text diff --git a/int8/LICENSE-FlexiCubes.txt b/int8/LICENSE-FlexiCubes.txt new file mode 100644 index 0000000000000000000000000000000000000000..9b5e4019df618fc47d429529c369f4903142669b --- /dev/null +++ b/int8/LICENSE-FlexiCubes.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/int8/LICENSE-SAM.txt b/int8/LICENSE-SAM.txt new file mode 100644 index 0000000000000000000000000000000000000000..e58d758cc3d92e6d1a57b52f7e4d203d02a67e98 --- /dev/null +++ b/int8/LICENSE-SAM.txt @@ -0,0 +1,52 @@ +SAM License +Last Updated: November 19, 2025 + +“Agreement” means the terms and conditions for use, reproduction, distribution and modification of the SAM Materials set forth herein. + +“SAM Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement. + +“Documentation” means the specifications, manuals and documentation accompanying +SAM Materials distributed by Meta. + +“Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf. + +“Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland). + +“Sanctions” means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom. + +“Trade Controls” means any of the following: Sanctions and applicable export and import controls. + +By using or distributing any portion or element of the SAM Materials, you agree to be bound by this Agreement. + +1. License Rights and Redistribution. + +a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the SAM Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the SAM Materials. + +i. Grant of Patent License. Subject to the terms and conditions of this License, you are granted a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by Meta that are necessarily infringed alone or by combination of their contribution(s) with the SAM 3 Materials. If you institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM 3 Materials incorporated within the work constitutes direct or contributory patent infringement, then any patent licenses granted to you under this License for that work shall terminate as of the date such litigation is filed. + +b. Redistribution and Use. + +i. Distribution of SAM Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the SAM Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such SAM Materials. + +ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with SAM Materials, you must acknowledge the use of SAM Materials in your publication. + +iii. Your use of the SAM Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws. +iv. Your use of the SAM Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the SAM Materials. +v. You are not the target of Trade Controls and your use of SAM Materials must comply with Trade Controls. You agree not to use, or permit others to use, SAM Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons. +2. User Support. Your use of the SAM Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the SAM Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind. + +3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE SAM MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE SAM MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE SAM MATERIALS AND ANY OUTPUT AND RESULTS. + +4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING. + +5. Intellectual Property. + +a. Subject to Meta’s ownership of SAM Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the SAM Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications. + +b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the SAM Materials. + +6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the SAM Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the SAM Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement. + +7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement. + +8. Modifications and Amendments. Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the SAM Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta. diff --git a/int8/LICENSE-TRELLIS.txt b/int8/LICENSE-TRELLIS.txt new file mode 100644 index 0000000000000000000000000000000000000000..3d8b93bc7987d14c848448c089e2ae15311380d7 --- /dev/null +++ b/int8/LICENSE-TRELLIS.txt @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/int8/__pycache__/pipeline.cpython-310.pyc b/int8/__pycache__/pipeline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a95b42076703a42b92d1a9df7441e2eea1b579b2 Binary files /dev/null and b/int8/__pycache__/pipeline.cpython-310.pyc differ diff --git a/int8/__pycache__/pipeline_tables.cpython-310.pyc b/int8/__pycache__/pipeline_tables.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39949f4f2f044a858b7be7c36e366ac76a35c7d7 Binary files /dev/null and b/int8/__pycache__/pipeline_tables.cpython-310.pyc differ diff --git a/int8/dino.onnx b/int8/dino.onnx new file mode 100644 index 0000000000000000000000000000000000000000..18fe7e5254819b4d6c1bdf9ba34bb1bb6fc5bfe7 --- /dev/null +++ b/int8/dino.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4abdace1d2457b71d31b13696c4c3ef38eee0a909aa399079b1e5fbf8335d914 +size 345956 diff --git a/int8/dino.onnx.data b/int8/dino.onnx.data new file mode 100644 index 0000000000000000000000000000000000000000..bc041636cf8898b2f8be48e4752670960c4b3bc9 --- /dev/null +++ b/int8/dino.onnx.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7dac4b145524d5245118c339b16ee1214ca0d4a972651e21874b999a5db86cd3 +size 1217486848 diff --git a/int8/flexicubes_tables.npz b/int8/flexicubes_tables.npz new file mode 100644 index 0000000000000000000000000000000000000000..ab2b9d91db2943bc510393e977903b7ad7d4aa81 --- /dev/null +++ b/int8/flexicubes_tables.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d22bf7f2ec21cf0832e550593630551071f7bd26175c896f2361f82fd44786e +size 2639 diff --git a/int8/mesh_conv.onnx b/int8/mesh_conv.onnx new file mode 100644 index 0000000000000000000000000000000000000000..2ea8b9fb30f08f0f44d3be621e490447aec31d72 --- /dev/null +++ b/int8/mesh_conv.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:011ad908aa43800f5f994f6bdac82842b1e3b15ea38cee01777d890d9e314bf4 +size 26364 diff --git a/int8/mesh_conv.onnx.data b/int8/mesh_conv.onnx.data new file mode 100644 index 0000000000000000000000000000000000000000..a437f27a8dd315489c1fd41bb7a3825b418a4ba8 --- /dev/null +++ b/int8/mesh_conv.onnx.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b039cb6b1cc1b6f32de79fda78315702e5db74bc71cc84d3ff4cdf65d1da2c82 +size 995328 diff --git a/int8/mesh_dec.onnx b/int8/mesh_dec.onnx new file mode 100644 index 0000000000000000000000000000000000000000..b300824824950d2cd511c3019e53642393b606f4 --- /dev/null +++ b/int8/mesh_dec.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f251f0f0f158639cb06c6efc098516d5f78074518a14a11a42b55e9604d4197 +size 938468 diff --git a/int8/mesh_dec.onnx.data b/int8/mesh_dec.onnx.data new file mode 100644 index 0000000000000000000000000000000000000000..0d904ef7bc257adb1f0cc4aaf6a4b73de5bc7988 --- /dev/null +++ b/int8/mesh_dec.onnx.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:747c4ef56d3d20aabba9a2a583e6372feb559d482e694b9faf652dc93d409658 +size 180317184 diff --git a/int8/mesh_gn.onnx b/int8/mesh_gn.onnx new file mode 100644 index 0000000000000000000000000000000000000000..467a791d83ee3ea3b7d24685a52cd320fdadeb75 --- /dev/null +++ b/int8/mesh_gn.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f14e6e0daeed0a83d74af1bc63b15df70916d119297891c0e52bc5b012abfae +size 3139 diff --git a/int8/mesh_out.onnx b/int8/mesh_out.onnx new file mode 100644 index 0000000000000000000000000000000000000000..4aaeceb433d9ab81f18517bf336a16edd735d9cd --- /dev/null +++ b/int8/mesh_out.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81d16b8a1ae14a98b39d6f69b2162b70ce08f3cf2a3a03174031522126eca9d8 +size 27608 diff --git a/int8/mesh_out.onnx.data b/int8/mesh_out.onnx.data new file mode 100644 index 0000000000000000000000000000000000000000..77cedc03d4d93199c9cd095f7a2985e116923420 --- /dev/null +++ b/int8/mesh_out.onnx.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7464356dda053776c20d151b45f20aa6659faeb8c3b99c8bbf4f100f2e4bf500 +size 573312 diff --git a/int8/moge.onnx b/int8/moge.onnx new file mode 100644 index 0000000000000000000000000000000000000000..a448fa496a39e3fd38dfaf8bacdb58139c55b870 --- /dev/null +++ b/int8/moge.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bed5a78f547ff24d8009161a9c61a23a55b12907318253f6a78dcf8bedaa1191 +size 468757 diff --git a/int8/moge.onnx.data b/int8/moge.onnx.data new file mode 100644 index 0000000000000000000000000000000000000000..31238f4a11b3d0a894bb903358dac04aced2a32c --- /dev/null +++ b/int8/moge.onnx.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63bcec2af5473b171329533fc7c9fad7cc8bb337e4abf4dd7a67b8f61bab392d +size 1251070464 diff --git a/int8/moge_pos_embed.npy b/int8/moge_pos_embed.npy new file mode 100644 index 0000000000000000000000000000000000000000..c52403ad143f2f44254bb32bffc45862c5bfad4a --- /dev/null +++ b/int8/moge_pos_embed.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73231693ad7d6dd37eeb9b6ab790dfa4198c68770856f1450ce348aff7da73d9 +size 5611648 diff --git a/int8/pipeline.py b/int8/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..22678a1bb91d9575572cbdb29a71c0562d3c2217 --- /dev/null +++ b/int8/pipeline.py @@ -0,0 +1,386 @@ +"""SAM 3D Objects (Meta: a picture and an object mask -> the object's 3D mesh with vertex colours and its pose in the +camera) with ONNX Runtime, reproducing InferencePipelinePointMap.run as the official notebook calls it (no mesh +post-processing, no texture baking, no layout post-optimisation, vertex colours). + + python pipeline.py image.png mask.png out.glb [--seed 42] [--cpu] + +Stages (the folder's *.onnx; `vendor/` holds the original's own preprocessing / pose code, run with torch on the CPU): + + moge MoGe-v1 point map of the whole picture (the object's depth, the camera focal length) + dino DINOv2-L/14-reg on the cropped and full picture and mask (4 passes, shared by both stages) + ss_fuse the structure stage's condition tokens (+ the point-map patch embedder) + ss_flow structure + pose: 25 Euler steps (t rescaled by 3), CFG 7 while t <= 0.5, the condition zeroed for + the unconditional pass; latents shape [4096, 8], 6D rotation, translation, scale, translation scale + ss_dec -> 64^3 occupancy; surface voxels kept (prune), downsampled past 42,000 + slat_fuse the latent stage's condition tokens + slat_flow 8 latent features per voxel: 25 Euler steps, CFG 1 while t <= 0.5 + mesh_dec the mesh decoder up to 128^3 (voxels subdivided once) + mesh_conv / mesh_gn / mesh_out + its last block at 256^3, chunk by chunk (GroupNorm statistics over all voxels in numpy) -> + FlexiCubes features; the mesh from those in numpy (FlexiCubes port, flexicubes_tables.npz) + +Needs numpy, scipy, onnxruntime-gpu, torch + torchvision (CPU is enough: the preprocessing runs the original's code), +Pillow; trimesh to write GLB. +""" +from __future__ import annotations + +import argparse +import json +import math +import sys +import time +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [p for p in (str(HERE), str(HERE / "vendor")) if p not in sys.path] # pipeline_tables, vendor/ +SEED = 42 +# MoGe-v1 infer(resolution_level=9) runs at the top of the checkpoint's token range: sam3d.json "num_tokens" +# (moge-vitl: trained_area_range [250000, 500000] -> [1275, 2551] tokens -> 2551). +SS_STEPS, SS_RESCALE, SS_CFG, CFG_INTERVAL = 25, 3.0, 7.0, (0.0, 500.0) +SLAT_STEPS, SLAT_RESCALE, SLAT_CFG = 25, 1.0, 1.0 +TIME_SCALE = 1000.0 +POSE_KEYS = ("6drotation_normalized", "translation", "scale", "translation_scale") +# R3 camera -> PyTorch3D camera (look_at_view_transform(eye=(0, 0, -1), at=0, up=(0, -1, 0))): x -> -x, y -> -y +CAM_R = np.diag([-1.0, -1.0, 1.0]).astype(np.float32) + + +# ---------------------------------------------------------------- MoGe-v1 (MoGeModel.forward / infer around the graph) +def moge_inputs(image, meta): + """MoGeModel.forward's resizes and normalisation, DINOv2's position-embedding interpolation and the head's UV + grids (the graph takes them as inputs: tracing would freeze them at one size). image: [1, 3, H, W] in [0, 1].""" + import torch + import torch.nn.functional as F + try: + from moge_min import normalized_view_plane_uv + except ImportError: # the source folder (no vendor/ yet): MoGe itself + from moge.utils.geometry_torch import normalized_view_plane_uv + H, W = image.shape[-2:] + f = ((meta["num_tokens"] * 14 ** 2) / (H * W)) ** 0.5 + rw, rh = int(W * f), int(H * f) + img = F.interpolate(image, (rh, rw), mode="bicubic", align_corners=False, antialias=True) + img = (img - torch.tensor(meta["image_mean"]).view(1, 3, 1, 1)) / torch.tensor(meta["image_std"]).view(1, 3, 1, 1) + img14 = F.interpolate(img, (rh // 14 * 14, rw // 14 * 14), mode="bilinear", align_corners=False, antialias=True) + # DinoVisionTransformer.interpolate_pos_encoding(x, w, h) with w, h = the image's dims 2 and 3 + pos = torch.from_numpy(np.load(HERE / "moge_pos_embed.npy")) + N = pos.shape[1] - 1 + M = int(math.sqrt(N)) + w0, h0 = img14.shape[2] // 14, img14.shape[3] // 14 + kw = {} + if meta["interpolate_offset"]: + kw["scale_factor"] = (float(w0 + meta["interpolate_offset"]) / M, float(h0 + meta["interpolate_offset"]) / M) + else: + kw["size"] = (w0, h0) + pp = F.interpolate(pos[:, 1:].reshape(1, M, M, -1).permute(0, 3, 1, 2), mode="bicubic", + antialias=meta["interpolate_antialias"], **kw) + pos = torch.cat([pos[:, :1], pp.permute(0, 2, 3, 1).reshape(1, -1, pos.shape[-1])], 1) + ph, pw = rh // 14, rw // 14 + uvs = [normalized_view_plane_uv(width=pw * s, height=ph * s, aspect_ratio=rw / rh, dtype=torch.float32) + for s in (1, 2, 4)] + [normalized_view_plane_uv(width=rw, height=rh, aspect_ratio=rw / rh, dtype=torch.float32)] + feed = {"image14": img14, "pos_embed": pos} + feed.update({f"uv{i}": u.permute(2, 0, 1)[None].contiguous() for i, u in enumerate(uvs)}) + return {k: v.numpy().astype(np.float32) for k, v in feed.items()} + + +def moge_outputs(points, mask, H, W, meta): + """MoGeModel.forward's resize back to the picture + infer(force_projection=False, apply_mask=True).""" + import torch + import torch.nn.functional as F + try: + from moge_min import recover_focal_shift + except ImportError: + from moge.utils.geometry_torch import recover_focal_shift + points = F.interpolate(torch.from_numpy(points), (H, W), mode="bilinear", align_corners=False, antialias=False) + mask = F.interpolate(torch.from_numpy(mask), (H, W), mode="bilinear", align_corners=False, antialias=False) + points, mask = points.permute(0, 2, 3, 1), mask.squeeze(1) + if meta["remap_output"] == "exp": + xy, z = points.split([2, 1], dim=-1) + z = torch.exp(z) + points = torch.cat([xy * z, z], dim=-1) + elif meta["remap_output"] not in ("linear", False): + raise ValueError(meta["remap_output"]) + aspect = W / H + mask_binary = mask > meta["mask_threshold"] + focal, shift = recover_focal_shift(points, mask_binary) + fx = focal / 2 * (1 + aspect ** 2) ** 0.5 / aspect + fy = focal / 2 * (1 + aspect ** 2) ** 0.5 + K = torch.zeros(1, 3, 3) + K[:, 0, 0], K[:, 1, 1], K[:, 0, 2], K[:, 1, 2], K[:, 2, 2] = fx, fy, 0.5, 0.5, 1.0 + points = points + torch.stack([torch.zeros_like(shift), torch.zeros_like(shift), shift], dim=-1)[..., None, None, :] + points = torch.where(mask_binary[..., None], points, torch.inf) + return points[0], K[0] + + +# ---------------------------------------------------------------- preprocessing (the original's code, vendor/) +U8_FLOAT = (np.arange(256) / 255).astype(np.float32) + + +def to_float(u8): + """image_to_float (image / 255 in float64, then float32) by lookup: the same values (all 256 checked), without + the float64 copy (1 GB for a 30 MP RGBA picture).""" + return U8_FLOAT[u8] + + +def preprocessors(): + """pipeline.yaml's ss_preprocessor / slat_preprocessor.""" + from functools import partial + import torchvision + from sam3d_objects.data.dataset.tdfy.preprocessor import PreProcessor + from sam3d_objects.data.dataset.tdfy.img_processing import pad_to_square_centered + from sam3d_objects.data.dataset.tdfy import img_and_mask_transforms as T + C, R = torchvision.transforms.Compose, torchvision.transforms.Resize + img = C([partial(pad_to_square_centered), R(518)]) + msk = C([partial(pad_to_square_centered), R(518, interpolation=0)]) + ss = PreProcessor(img_mask_joint_transform=[], img_mask_pointmap_joint_transform=[ + partial(T.resize_all_to_same_size), partial(T.crop_around_mask_with_padding, box_size_factor=1.2, padding_factor=0.0)], + img_transform=img, mask_transform=msk, normalize_pointmap=True, + pointmap_normalizer=T.ObjectCentricSSI(allow_scale_and_shift_override=True, use_scene_scale=True), + pointmap_transform=C([partial(pad_to_square_centered), R(518, interpolation=0)])) + slat = PreProcessor(img_transform=img, mask_transform=msk, img_mask_joint_transform=[ + partial(T.crop_around_mask_with_padding, box_size_factor=1.2, padding_factor=0.0)]) + return ss, slat + + +def preprocess(rgba, pointmap, pre): + """InferencePipelinePointMap.preprocess_image (rgba: uint8 [H, W, 4]; the mask in alpha).""" + import torch + from sam3d_objects.data.dataset.tdfy.img_and_mask_transforms import get_mask + x = torch.from_numpy(to_float(rgba)).permute(2, 0, 1).contiguous() + r = pre._process_image_mask_pointmap_mess(x[:3], get_mask(x, None, "ALPHA_CHANNEL"), pointmap) + item = {k: r[k][None] for k in ("mask", "image", "rgb_image", "rgb_image_mask")} + if pointmap is not None: + for k in ("pointmap", "rgb_pointmap", "pointmap_scale", "pointmap_shift"): + item[k] = r[k][None] + return item + + +# ---------------------------------------------------------------- the mesh decoder's 256^3 GroupNorm +MESH_CHUNK = 1 << 18 + + +def gn_stats(x, groups, eps, chunk=MESH_CHUNK): + """GroupNorm statistics over all rows of x [N, C] (float64 sums, chunk by chunk): mean, 1 / sqrt(var + eps).""" + C = x.shape[1] + s1, s2 = np.zeros(groups), np.zeros(groups) + for i in range(0, len(x), chunk): + v = x[i:i + chunk].astype(np.float64).reshape(-1, groups, C // groups) + s1 += v.sum((0, 2)) + s2 += (v * v).sum((0, 2)) + n = len(x) * (C // groups) + mean = s1 / n + return mean.astype(np.float32), (1 / np.sqrt(np.maximum(s2 / n - mean * mean, 0) + eps)).astype(np.float32) + + +# ---------------------------------------------------------------- samplers +def t_seq(steps, rescale): + t = np.linspace(0, 1, steps + 1) + return t / (1 + (rescale - 1) * (1 - t)) if rescale else t + + +def euler(model, x, steps, rescale, cfg): + """FlowMatching / ShortCut sampling with ClassifierFreeGuidance: x_{k+1} = x_k + v (t_{k+1} - t_k), v from the + model at 1000 t; inside the interval (1000 t in [0, 500]) v = (1 + s) v_cond - s v_uncond, the unconditional pass + with the condition zeroed (force_zeros_cond).""" + ts = t_seq(steps, rescale) + for t0, t1 in zip(ts[:-1], ts[1:]): + tt = np.array([t0 * TIME_SCALE], np.float32) + if cfg > 0 and CFG_INTERVAL[0] <= tt[0] <= CFG_INTERVAL[1]: + vc, vu = model(x, tt, False), model(x, tt, True) + v = {k: (1 + cfg) * vc[k] - cfg * vu[k] for k in vc} + else: + v = model(x, tt, False) + x = {k: (x[k] + v[k] * np.float32(t1 - t0)).astype(np.float32) for k in x} + return x + + +# ---------------------------------------------------------------- the pipeline +class Sam3DObjects: + def __init__(self, folder=HERE, device="cuda"): + import onnxruntime as ort + if hasattr(ort, "preload_dlls"): + ort.preload_dlls() + self.d = Path(folder) + self.meta = json.loads((self.d / "sam3d.json").read_text()) + self.so = ort.SessionOptions() + self.so.log_severity_level = 3 + self.so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC + cuda = {"use_tf32": "0", "arena_extend_strategy": "kSameAsRequested"} + self.prov = ([("CUDAExecutionProvider", cuda)] if device == "cuda" else []) + ["CPUExecutionProvider"] + self.ort = ort + + def session(self, name): + return self.ort.InferenceSession(str(self.d / f"{name}.onnx"), self.so, providers=self.prov) + + @staticmethod + def run(s, **feed): + names = {i.name for i in s.get_inputs()} + return s.run(None, {k: np.ascontiguousarray(v) for k, v in feed.items() if k in names}) + + def pointmap(self, rgba): + """compute_pointmap: MoGe on the RGB picture, the points into PyTorch3D's camera convention, [3, H, W].""" + import torch + img = torch.from_numpy(to_float(rgba[..., :3])).permute(2, 0, 1)[None] + H, W = img.shape[-2:] + s = self.session("moge") + pts, msk = self.run(s, **moge_inputs(img, self.meta["moge"])) + del s + points, K = moge_outputs(pts, msk, H, W, self.meta["moge"]) + points = points @ torch.from_numpy(CAM_R) + return points.permute(2, 0, 1).contiguous(), K + + def conditions(self, item): + """DINOv2 on the 4 pictures (mask repeated to 3 channels): norm tokens for the ss stage, prenorm tokens for + the slat stage.""" + s = self.session("dino") + out = {} + for k in ("image", "rgb_image", "mask", "rgb_image_mask"): + x = item[k].numpy() + x = np.repeat(x, 3, 1) if x.shape[1] == 1 else x + out[k] = self.run(s, pixels=x.astype(np.float32)) + del s + return out + + def structure(self, ss_item, toks, noise): + """noise: {name: array} for shape [1, 4096, 8] and the pose latents.""" + f = self.session("ss_fuse") + cond = self.run(f, **{k: toks[k][0] for k in toks}, pointmap=ss_item["pointmap"].numpy(), + rgb_pointmap=ss_item["rgb_pointmap"].numpy())[0] + del f + s = self.session("ss_flow") + zero = np.zeros_like(cond) + names = ("shape",) + POSE_KEYS + + def model(x, t, uncond): + o = self.run(s, shape=x["shape"], rotation6d=x["6drotation_normalized"], translation=x["translation"], + scale=x["scale"], translation_scale=x["translation_scale"], t=t, + d=np.zeros(1, np.float32), cond=zero if uncond else cond) + return dict(zip(names, o)) + x = euler(model, {k: noise[k].astype(np.float32) for k in names}, SS_STEPS, SS_RESCALE, SS_CFG) + del s + z = x["shape"].transpose(0, 2, 1).reshape(1, 8, 16, 16, 16) + logits = self.run(self.session("ss_dec"), z=z)[0] + return x, logits + + def voxels_and_pose(self, x, logits, ss_item): + """sample_sparse_structure's coordinates (prune, downsample) and the pose decoder.""" + import torch + from sam3d_objects.pipeline.inference_utils import (pose_decoder, prune_sparse_structure, + downsample_sparse_structure) + coords = torch.argwhere(torch.from_numpy(logits) > 0)[:, [0, 2, 3, 4]].int() + coords = prune_sparse_structure(coords, max_neighbor_axes_dist=1) + coords, factor = downsample_sparse_structure(coords) + r = {k: torch.from_numpy(v) for k, v in x.items()} + r.update(pose_decoder("ScaleShiftInvariant")(r, scene_scale=ss_item["pointmap_scale"], + scene_shift=ss_item["pointmap_shift"])) + pose = {"translation": r["translation"].numpy(), "rotation": r["rotation"].numpy(), + "scale": (r["scale"] * factor).numpy()} + return coords.numpy(), pose + + def latent(self, toks, coords, noise): + import pipeline_tables as TB + f = self.session("slat_fuse") + cond = self.run(f, **{k: toks[k][1] for k in toks})[0] + del f + s = self.session("slat_flow") + tb = dict(zip(TB.SLAT_NAMES, TB.slat_flow_tables(coords))) + zero = np.zeros_like(cond) + + def model(x, t, uncond): + return {"x": self.run(s, feats=x["x"], t=t, cond=zero if uncond else cond, **tb)[0]} + x = euler(model, {"x": noise.astype(np.float32)}, SLAT_STEPS, SLAT_RESCALE, SLAT_CFG)["x"] + del s + return x * np.array(self.meta["slat_std"], np.float32) + np.array(self.meta["slat_mean"], np.float32) + + def mesh(self, slat, coords, chunk=MESH_CHUNK): + """SLatMeshDecoder: mesh_dec to 128^3 (+ the last block's norm / SiLU); the 256^3 block chunk by chunk of its + voxels: mesh_conv (its first conv, gathering from the 128^3 parents: child k of parent k // 8), the GroupNorm + statistics of all voxels (numpy), mesh_gn (GroupNorm + SiLU), mesh_out (second conv + skip + output layer); + then FlexiCubes in numpy.""" + import pipeline_tables as TB + tb = dict(zip(TB.MESH_NAMES, TB.mesh_dec_tables(coords))) + nbr256 = tb.pop("nbr256") + s = self.session("mesh_dec") + h128, x128 = self.run(s, slat=slat.astype(np.float32), **tb) + del s, tb + M, N = len(h128), len(nbr256) + s = self.session("mesh_conv") + g = None + for i in range(0, N, chunk): + nb = nbr256[i:i + chunk] + o = self.run(s, h=h128, nbr=np.where(nb == N, M, nb // 8))[0] + if g is None: + g = np.empty((N, o.shape[1]), o.dtype) + g[i:i + chunk] = o + del s, h128 + mean, rstd = gn_stats(g, self.meta["mesh_gn"]["groups"], self.meta["mesh_gn"]["eps"], chunk) + s = self.session("mesh_gn") + for i in range(0, N, chunk): + g[i:i + chunk] = self.run(s, f=g[i:i + chunk], mean=mean, rstd=rstd)[0] + del s + s = self.session("mesh_out") + f = None + for i in range(0, N, chunk): + o = self.run(s, g=g, nbr=nbr256[i:i + chunk], xs=x128, par=np.arange(i, min(i + chunk, N), dtype=np.int64) // 8)[0] + if f is None: + f = np.empty((N, o.shape[1]), np.float32) + f[i:i + chunk] = o + del s, g, x128, nbr256 + tables = dict(np.load(self.d / "flexicubes_tables.npz")) + return TB.flexicubes(f, TB.subdivide(TB.subdivide(np.asarray(coords)[:, 1:])), tables) + + def __call__(self, image, mask, seed=SEED, log=print): + import torch + from PIL import Image + rgba = np.array(image.convert("RGB")).astype(np.uint8) + m = np.array(mask) + m = (m[..., -1] if m.ndim == 3 else m) > 0 + rgba = np.concatenate([rgba, (m.astype(np.uint8) * 255)[..., None]], -1) + times, t0 = {}, time.time() + pm, K = self.pointmap(rgba) + times["pointmap"] = time.time() - t0 + ss_pre, slat_pre = preprocessors() + ss_item, slat_item = preprocess(rgba, pm, ss_pre), preprocess(rgba, None, slat_pre) + t0 = time.time() + toks = self.conditions(slat_item) + times["conditions"] = time.time() - t0 + g = torch.Generator().manual_seed(seed) + noise = {k: torch.randn(shape, generator=g).numpy() for k, shape in + sorted({"6drotation_normalized": (1, 1, 6), "scale": (1, 1, 3), "shape": (1, 4096, 8), + "translation": (1, 1, 3), "translation_scale": (1, 1, 1)}.items())} + t0 = time.time() + x, logits = self.structure(ss_item, toks, noise) + coords, pose = self.voxels_and_pose(x, logits, ss_item) + times["structure"] = time.time() - t0 + log(f"structure: {len(coords)} voxels") + t0 = time.time() + slat = self.latent(toks, coords, torch.randn(1, len(coords), 8, generator=g).numpy()[0]) + times["latent"] = time.time() - t0 + t0 = time.time() + v, f, attrs = self.mesh(slat, coords) + times["mesh"] = time.time() - t0 + log("seconds: " + ", ".join(f"{k} {v_:.1f}" for k, v_ in times.items())) + return v, f, attrs, pose, K.numpy() + + +def save_mesh(path, v, f, attrs): + """GLB with vertex colours (y-up, as TRELLIS's to_glb writes it: rotated -90 degrees about x).""" + import trimesh + v = v @ np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]], np.float32) + col = (np.clip(attrs[:, :3], 0, 1) * 255).astype(np.uint8) + trimesh.Trimesh(v, f, vertex_colors=col, process=False).export(path) + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("image") + ap.add_argument("mask") + ap.add_argument("out") + ap.add_argument("--seed", type=int, default=SEED) + ap.add_argument("--cpu", action="store_true") + a = ap.parse_args() + from PIL import Image + p = Sam3DObjects(HERE, "cpu" if a.cpu else "cuda") + v, f, attrs, pose, K = p(Image.open(a.image), Image.open(a.mask), a.seed) + save_mesh(a.out, v, f, attrs) + print(f"{a.out}: {len(v)} vertices, {len(f)} faces; pose", {k: np.round(v_, 4).tolist() for k, v_ in pose.items()}) diff --git a/int8/pipeline_tables.py b/int8/pipeline_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..7e2a44115ee6d5f6934f7778af263f153c4ef520 --- /dev/null +++ b/int8/pipeline_tables.py @@ -0,0 +1,251 @@ +"""From the TRELLIS text ONNX build's pipeline.py (moonbox-dev/TRELLIS-text-xlarge-ONNX): the sparse-op +index tables of the latent flow and the mesh decoder (TRELLIS v1 modules, as SAM 3D Objects uses them) and +the numpy port of NVIDIA FlexiCubes (Apache-2.0, LICENSE-FlexiCubes.txt) from TRELLIS's copy (MIT).""" +from __future__ import annotations +import itertools +import numpy as np + +SLAT_NAMES = ["coords64", "nbr64", "coords32", "nbr32", "down_child", "down_cnt", "up_idx"] +MESH_NAMES = ["coords64", "win0_fwd", "win0_mask", "win0_bwd", "win4_fwd", "win4_mask", "win4_bwd", + "nbr128", "nbr256"] + + +OFF27 = np.array(list(itertools.product((-1, 0, 1), repeat=3)), np.int64) + + +SUB8 = np.array(list(itertools.product((0, 1), repeat=3)), np.int64) + + +WINDOW = 8 + + +def neighbours(xyz, offsets=OFF27): + """[N, K] index of each voxel's neighbour at each offset (N where there is none).""" + xyz = np.asarray(xyz, np.int64) + n = len(xyz) + R = int(xyz.max()) + 4 + key = lambda p: ((p[:, 0] + 1) * R + (p[:, 1] + 1)) * R + (p[:, 2] + 1) + k = key(xyz) + order = np.argsort(k, kind="stable") + ks = k[order] + out = np.full((n, len(offsets)), n, np.int64) + for j, o in enumerate(offsets): + q = key(xyz + o) + pos = np.minimum(np.searchsorted(ks, q), n - 1) + hit = ks[pos] == q + out[hit, j] = order[pos[hit]] + return out + + +def with_batch(xyz): + return np.concatenate([np.zeros((len(xyz), 1), np.int32), np.asarray(xyz, np.int32)], 1) + + +def slat_flow_tables(coords): + """coords [N, 4] (batch 0, x, y, z at 64^3) -> coords64, nbr64, coords32, nbr32, down_child, down_cnt, up_idx.""" + xyz = np.asarray(coords)[:, 1:].astype(np.int64) + coarse, inv = np.unique(xyz // 2, axis=0, return_inverse=True) # SparseDownsample's order + inv = inv.reshape(-1) + m = len(coarse) + cnt = np.bincount(inv, minlength=m) + order = np.argsort(inv, kind="stable") + start = np.concatenate([[0], np.cumsum(cnt)[:-1]]) + slot = np.arange(len(xyz)) - start[inv[order]] + child = np.full((m, 8), len(xyz), np.int64) + child[inv[order], slot] = order + return (with_batch(xyz), neighbours(xyz), with_batch(coarse), neighbours(coarse), child, + cnt.astype(np.float32)[:, None], inv.astype(np.int64)) + + +def windows(xyz, shift, size=WINDOW): + """The Swin partition (calc_window_partition): voxels grouped by window, padded to the fullest window. + Returns fwd [W, L] (index, N = padding), mask [W, L] (0 / -inf) and bwd [N] (position in the W * L layout).""" + s = np.asarray(xyz, np.int64) + shift + nw = (s.max(0) + 1 + size - 1) // size + wid = ((s[:, 0] // size) * nw[1] + s[:, 1] // size) * nw[2] + s[:, 2] // size + uw, winv, wcnt = np.unique(wid, return_inverse=True, return_counts=True) + winv = winv.reshape(-1) + L, Wn, n = int(wcnt.max()), len(uw), len(s) + order = np.argsort(winv, kind="stable") + start = np.concatenate([[0], np.cumsum(wcnt)[:-1]]) + slot = np.empty(n, np.int64) + slot[order] = np.arange(n) - start[winv[order]] + fwd = np.full((Wn, L), n, np.int64) + fwd[winv, slot] = np.arange(n) + mask = np.where(fwd < n, 0.0, -np.inf).astype(np.float32) + return fwd, mask, (winv * L + slot).astype(np.int64) + + +def subdivide(xyz): + return ((np.asarray(xyz, np.int64) * 2)[:, None] + SUB8[None]).reshape(-1, 3) + + +def mesh_dec_tables(coords): + """coords [N, 4] -> coords64, the two Swin partitions (shift 0, 4), nbr128, nbr256.""" + xyz = np.asarray(coords)[:, 1:].astype(np.int64) + x128 = subdivide(xyz) + x256 = subdivide(x128) + return (with_batch(xyz),) + windows(xyz, 0) + windows(xyz, WINDOW // 2) + (neighbours(x128), neighbours(x256)) + + +def mesh_dec_coords256(coords): + return with_batch(subdivide(subdivide(np.asarray(coords)[:, 1:]))) + + +CORNERS = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]], np.int64) + + +CUBE_EDGES = np.array([0, 1, 1, 5, 4, 5, 0, 4, 2, 3, 3, 7, 6, 7, 2, 6, 2, 0, 3, 1, 7, 5, 6, 4], np.int64) + + +QUAD_SPLIT_1, QUAD_SPLIT_2 = np.array([0, 1, 2, 0, 2, 3]), np.array([0, 1, 3, 3, 1, 2]) + + +def _interp(w, x): + """FlexiCubes._linear_interp: zero crossing along each edge (w [E, 2, 1], x [E, 2, C]).""" + w2 = np.concatenate([w[:, 1:2], -w[:, 0:1]], 1) + return (x * w2).sum(1) / w2.sum(1) + + +def _index_add(n, idx, val): + out = np.zeros((n,) + val.shape[1:], np.float32) + np.add.at(out, idx, val) + return out + + +def flexicubes(feats, xyz, tables, res=256, weight_scale=0.99): + """SparseFeatures2Mesh.__call__ (use_color) + FlexiCubes.__call__ (training=False) for one shape. + feats [N, 101] (sdf 8, deform 8 x 3, weights 21, colour 8 x 6), xyz [N, 3] at res^3. + Returns vertices [V, 3] in [-0.5, 0.5]^3, faces [F, 3], vertex attributes [V, 6] (colour, normal map).""" + f32 = np.float32 + feats = np.asarray(feats, f32) + xyz = np.asarray(xyz, np.int64) + n = len(xyz) + R = res + 1 + sdf = feats[:, 0:8] + f32(-1.0 / res) + deform = feats[:, 8:32].reshape(n, 8, 3) + weights = feats[:, 32:53] + color = feats[:, 53:101].reshape(n, 8, 6) + # sparse_cube2verts: every voxel's 8 corners, per-vertex mean over the voxels sharing it + vkey = lambda p: (p[..., 0] * R + p[..., 1]) * R + p[..., 2] + vid = vkey(xyz[:, None] + CORNERS[None]).reshape(-1) + tv, inv = np.unique(vid, return_inverse=True) + inv = inv.reshape(-1) + attrs = np.concatenate([sdf[..., None], deform, color], -1).reshape(-1, 10) + cnt = np.bincount(inv, minlength=len(tv)).astype(f32) + vattr = np.stack([np.bincount(inv, attrs[:, c], minlength=len(tv)) for c in range(10)], 1).astype(f32) + vattr /= cnt[:, None] + + def lookup(q): + pos = np.minimum(np.searchsorted(tv, q), len(tv) - 1) + return pos, tv[pos] == q + + def sdf_of(q): + pos, hit = lookup(q) + return np.where(hit, vattr[pos, 0], f32(1.0)) # untouched grid vertices: outside (1) + + def pos_of(q): + pos, hit = lookup(q) + d = np.where(hit[..., None], vattr[pos, 1:4], f32(0.0)) + g = np.stack([q // (R * R), (q // R) % R, q % R], -1).astype(f32) + return g / f32(res) - f32(0.5) + f32((1 - 1e-8) / (res * 2)) * np.tanh(d) + + def color_of(q): + pos, hit = lookup(q) + c = np.where(hit[..., None], vattr[pos, 4:10], f32(0.0)) + return (1 / (1 + np.exp(-c))).astype(f32) + # candidate cubes: those with a corner among the vertices with a negative SDF, in dense (x, y, z) order + neg = tv[vattr[:, 0] < 0] + nv = np.stack([neg // (R * R), (neg // R) % R, neg % R], -1) + cc = (nv[:, None] - CORNERS[None]).reshape(-1, 3) + cc = cc[((cc >= 0) & (cc < res)).all(1)] + ckey = np.unique((cc[:, 0] * res + cc[:, 1]) * res + cc[:, 2]) + cxyz = np.stack([ckey // (res * res), (ckey // res) % res, ckey % res], -1) + cube_v = vkey(cxyz[:, None] + CORNERS[None]) # [C, 8] + occ = sdf_of(cube_v) < 0 + s = occ.sum(1) + surf = (s > 0) & (s < 8) + ckey, cxyz, cube_v, occ = ckey[surf], cxyz[surf], cube_v[surf], occ[surf] + S = len(ckey) + if S == 0: + return np.zeros((0, 3), f32), np.zeros((0, 3), np.int64), np.zeros((0, 6), f32) + # weights: the decoder's per-voxel values where a voxel exists, 0 elsewhere (the dense grid's zeros) + ikey = (xyz[:, 0] * res + xyz[:, 1]) * res + xyz[:, 2] + io = np.argsort(ikey) + pos = np.minimum(np.searchsorted(ikey[io], ckey), n - 1) + hit = ikey[io][pos] == ckey + w = np.where(hit[:, None], weights[io[pos]], f32(0.0)) + beta = np.tanh(w[:, :12]) * f32(weight_scale) + f32(1) + alpha = np.tanh(w[:, 12:20]) * f32(weight_scale) + f32(1) + gamma = (1 / (1 + np.exp(-w[:, 20]))).astype(f32) * f32(weight_scale) + f32((1 - weight_scale) / 2) + # _get_case_id (the C16 / C19 ambiguity resolved against the adjacent cube) + case = (occ * (1 << np.arange(8))).sum(1) + pc = tables["check_table"][case] + to_check = np.nonzero(pc[:, 0] == 1)[0] + adj = cxyz[to_check] + pc[to_check, 1:4] + within = ((adj >= 0) & (adj < res)).all(1) + to_check, adj = to_check[within], adj[within] + akey = (adj[:, 0] * res + adj[:, 1]) * res + adj[:, 2] + chk_keys = np.sort(ckey[pc[:, 0] == 1]) + if len(chk_keys) and len(akey): + p = np.minimum(np.searchsorted(chk_keys, akey), len(chk_keys) - 1) + flip_case = chk_keys[p] == akey + case[to_check[flip_case]] = pc[to_check[flip_case], -1] + # _identify_surf_edges + edges = cube_v[:, CUBE_EDGES].reshape(-1, 2) + big = R ** 3 + ue_key, e_inv, e_cnt = np.unique(edges[:, 0] * big + edges[:, 1], return_inverse=True, return_counts=True) + e_inv = e_inv.reshape(-1) + ue = np.stack([ue_key // big, ue_key % big], 1) + mask_edges = (sdf_of(ue) < 0).sum(1) == 1 + surf_edges_mask = mask_edges[e_inv] + counts = e_cnt[e_inv] + mapping = np.full(len(ue), -1, np.int64) + mapping[mask_edges] = np.arange(mask_edges.sum()) + idx_map = mapping[e_inv] # [S * 12] + surf_edges = ue[mask_edges] + # _compute_vd + alpha12 = alpha[:, CUBE_EDGES].reshape(-1, 2) # [S * 12, 2] + se_x = pos_of(surf_edges.reshape(-1)).reshape(-1, 2, 3) + se_s = sdf_of(surf_edges.reshape(-1)).reshape(-1, 2, 1) + se_c = color_of(surf_edges.reshape(-1)).reshape(-1, 2, 6) + num_vd = tables["num_vd_table"][case] + eg, eg_vd, eg_cube, vd_gamma = [], [], [], [] + total = 0 + for num in np.unique(num_vd): + cur = num_vd == num + ncur = int(cur.sum()) * int(num) + g = tables["dmc_table"][case[cur], :num].reshape(-1, num * 7) + g_vd = (np.arange(ncur)[:, None].repeat(7, 1) + total).reshape(g.shape) + total += ncur + g_cube = np.nonzero(cur)[0][:, None].repeat(num * 7, 1) + m = g != -1 + eg.append(g[m]) + eg_vd.append(g_vd[m]) + eg_cube.append(g_cube[m]) + vd_gamma.append(gamma[cur][:, None].repeat(num, 1).reshape(-1)) + eg, eg_vd, eg_cube, vd_gamma = (np.concatenate(v) for v in (eg, eg_vd, eg_cube, vd_gamma)) + flat = eg_cube * 12 + eg + idx_group = idx_map[flat] + sw = se_s[idx_group] * alpha12[flat][:, :, None] + ue_group = _interp(sw, se_x[idx_group]) + beta_group = beta.reshape(-1)[flat][:, None] + beta_sum = _index_add(total, eg_vd, beta_group) + vd = _index_add(total, eg_vd, ue_group * beta_group) / beta_sum + vd_color = _index_add(total, eg_vd, _interp(sw, se_c[idx_group]) * beta_group) / beta_sum + vd_idx_map = np.zeros(S * 12, np.int64) + vd_idx_map[flat] = eg_vd + # _triangulate (inference: each quad split along the diagonal with the larger gamma product) + gm = (counts == 4) & surf_edges_mask + group = idx_map[gm] + vd_idx = vd_idx_map[gm] + order = np.argsort(group, kind="stable") + edge_indices = group[order] + quad = vd_idx[order].reshape(-1, 4) + s_e = sdf_of(surf_edges[edge_indices.reshape(-1, 4)[:, 0]].reshape(-1)).reshape(-1, 2) + flip = s_e[:, 0] > 0 + quad = np.concatenate([quad[flip][:, [0, 1, 3, 2]], quad[~flip][:, [2, 3, 1, 0]]]) + qg = vd_gamma[quad] + split = (qg[:, 0] * qg[:, 2]) > (qg[:, 1] * qg[:, 3]) + faces = np.where(split[:, None], quad[:, QUAD_SPLIT_1], quad[:, QUAD_SPLIT_2]).reshape(-1, 3) + return vd.astype(f32), faces, vd_color.astype(f32) diff --git a/int8/sam3d.json b/int8/sam3d.json new file mode 100644 index 0000000000000000000000000000000000000000..d774a564fc6bdcfd0dd399c9c721a0588622634c --- /dev/null +++ b/int8/sam3d.json @@ -0,0 +1,43 @@ +{ + "moge": { + "image_mean": [ + 0.48500001430511475, + 0.4560000002384186, + 0.4059999883174896 + ], + "image_std": [ + 0.2290000021457672, + 0.2240000069141388, + 0.22499999403953552 + ], + "interpolate_offset": 0.1, + "interpolate_antialias": false, + "remap_output": "exp", + "mask_threshold": 0.5, + "num_tokens": 2551 + }, + "slat_mean": [ + 0.12211431, + 0.37204156, + -1.26521907, + -2.05276058, + -3.10432536, + -0.11294304, + -0.85146744, + 0.45506954 + ], + "slat_std": [ + 2.37326008, + 2.13174402, + 2.2413953, + 2.30589401, + 2.1191894, + 1.8969511, + 2.41684989, + 2.08374642 + ], + "mesh_gn": { + "groups": 32, + "eps": 1e-05 + } +} \ No newline at end of file diff --git a/int8/slat_flow.onnx b/int8/slat_flow.onnx new file mode 100644 index 0000000000000000000000000000000000000000..4973fc1d85a0c4d5a2892560370c5919acddd61a --- /dev/null +++ b/int8/slat_flow.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c930ecc4a1f423c8b571a25db278ef0849c76063ce11d0c72a481e856efcd6e3 +size 2031725 diff --git a/int8/slat_flow.onnx.data b/int8/slat_flow.onnx.data new file mode 100644 index 0000000000000000000000000000000000000000..c3de887edd7e8ae8f1b70ea1a3811c536c135dc8 --- /dev/null +++ b/int8/slat_flow.onnx.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0171fc2ada14808bdd41567e47b89cd61115ef51fe97bd326fa419d6881ad2c +size 677782688 diff --git a/int8/slat_fuse.onnx b/int8/slat_fuse.onnx new file mode 100644 index 0000000000000000000000000000000000000000..470849b37ef7d4b37006c966ca0855213c6837f9 --- /dev/null +++ b/int8/slat_fuse.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7046a06fe344ca5ef7e21ef8275908cff6241bb1b88a94dba533991dc47b7606 +size 8331 diff --git a/int8/slat_fuse.onnx.data b/int8/slat_fuse.onnx.data new file mode 100644 index 0000000000000000000000000000000000000000..cd953a6fefcd827b6873240c392ff7df0c4d98b8 --- /dev/null +++ b/int8/slat_fuse.onnx.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12e4f839d54f8fc46fa608755b0056912d187be899a6e6d1d2c3b4f8b1b3fd47 +size 69230592 diff --git a/int8/ss_dec.onnx b/int8/ss_dec.onnx new file mode 100644 index 0000000000000000000000000000000000000000..0f37daa78720a37a66d8183303eab2258c1380b9 --- /dev/null +++ b/int8/ss_dec.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c972c906757750ee25fcf51570958118c6aed4d9fb651a85b61b96e942906e6b +size 38730 diff --git a/int8/ss_dec.onnx.data b/int8/ss_dec.onnx.data new file mode 100644 index 0000000000000000000000000000000000000000..8b6c9441b60ebaaebc53ec0b6c398a45e98c80c7 --- /dev/null +++ b/int8/ss_dec.onnx.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd5672e0eed77106948402a3fb3911e53f496c3e79f8dcb3efac5df21c079853 +size 294676864 diff --git a/int8/ss_flow.onnx b/int8/ss_flow.onnx new file mode 100644 index 0000000000000000000000000000000000000000..adece2d981081cb14208a1dedb57281d5e9cdbee --- /dev/null +++ b/int8/ss_flow.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc314370ada72e18c3f31f56a172f8ae16dab9d905a12c3d92f48cea2c0bdc8f +size 3012727 diff --git a/int8/ss_flow.onnx.data b/int8/ss_flow.onnx.data new file mode 100644 index 0000000000000000000000000000000000000000..0b27bfcb51014d79ad088fc4a68938fa1ea3e6b3 --- /dev/null +++ b/int8/ss_flow.onnx.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1b2ab3534475e2385735a7e6e1f4db74b3b2ee3057b1cca4a5bda08828e8157 +size 1038223722 diff --git a/int8/ss_fuse.onnx b/int8/ss_fuse.onnx new file mode 100644 index 0000000000000000000000000000000000000000..7c2403a11f2e5f565d6ce47703863761c4682aff --- /dev/null +++ b/int8/ss_fuse.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e17b0b21223e736563538ddb23a8da66a85e170838fec19bc837ca96a24223af +size 57190 diff --git a/int8/ss_fuse.onnx.data b/int8/ss_fuse.onnx.data new file mode 100644 index 0000000000000000000000000000000000000000..bc4fdf9d70f199e55bd869379d1537b7ad086975 --- /dev/null +++ b/int8/ss_fuse.onnx.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:147c69c125551f57fb830129481c374c18e916ad73964e53fd7e9a4398c406ec +size 102957056 diff --git a/int8/vendor/LICENSE-MoGe.txt b/int8/vendor/LICENSE-MoGe.txt new file mode 100644 index 0000000000000000000000000000000000000000..0fd4de04d413d30ab87033d07cbd70fab336db56 --- /dev/null +++ b/int8/vendor/LICENSE-MoGe.txt @@ -0,0 +1,224 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/int8/vendor/moge_min.py b/int8/vendor/moge_min.py new file mode 100644 index 0000000000000000000000000000000000000000..9871d181bcee3a4f18953b2d45b2a689fd912029 --- /dev/null +++ b/int8/vendor/moge_min.py @@ -0,0 +1,116 @@ +# From MoGe (microsoft/MoGe @ a8c3734, MIT; LICENSE-MoGe.txt): moge/utils/geometry_torch.py and +# geometry_numpy.py, the functions MoGeModel.infer uses to recover the focal length and z shift. +from typing import * +from functools import partial +import numpy as np +import torch +import torch.nn.functional as F + + +def solve_optimal_focal_shift(uv: np.ndarray, xyz: np.ndarray): + "Solve `min |focal * xy / (z + shift) - uv|` with respect to shift and focal" + from scipy.optimize import least_squares + uv, xy, z = uv.reshape(-1, 2), xyz[..., :2].reshape(-1, 2), xyz[..., 2].reshape(-1) + + def fn(uv: np.ndarray, xy: np.ndarray, z: np.ndarray, shift: np.ndarray): + xy_proj = xy / (z + shift)[: , None] + f = (xy_proj * uv).sum() / np.square(xy_proj).sum() + err = (f * xy_proj - uv).ravel() + return err + + solution = least_squares(partial(fn, uv, xy, z), x0=0, ftol=1e-3, method='lm') + optim_shift = solution['x'].squeeze().astype(np.float32) + + xy_proj = xy / (z + optim_shift)[: , None] + optim_focal = (xy_proj * uv).sum() / np.square(xy_proj).sum() + + return optim_shift, optim_focal + + +def solve_optimal_shift(uv: np.ndarray, xyz: np.ndarray, focal: float): + "Solve `min |focal * xy / (z + shift) - uv|` with respect to shift" + from scipy.optimize import least_squares + uv, xy, z = uv.reshape(-1, 2), xyz[..., :2].reshape(-1, 2), xyz[..., 2].reshape(-1) + + def fn(uv: np.ndarray, xy: np.ndarray, z: np.ndarray, shift: np.ndarray): + xy_proj = xy / (z + shift)[: , None] + err = (focal * xy_proj - uv).ravel() + return err + + solution = least_squares(partial(fn, uv, xy, z), x0=0, ftol=1e-3, method='lm') + optim_shift = solution['x'].squeeze().astype(np.float32) + + return optim_shift + + +def normalized_view_plane_uv(width: int, height: int, aspect_ratio: float = None, dtype: torch.dtype = None, device: torch.device = None) -> torch.Tensor: + "UV with left-top corner as (-width / diagonal, -height / diagonal) and right-bottom corner as (width / diagonal, height / diagonal)" + if aspect_ratio is None: + aspect_ratio = width / height + + span_x = aspect_ratio / (1 + aspect_ratio ** 2) ** 0.5 + span_y = 1 / (1 + aspect_ratio ** 2) ** 0.5 + + u = torch.linspace(-span_x * (width - 1) / width, span_x * (width - 1) / width, width, dtype=dtype, device=device) + v = torch.linspace(-span_y * (height - 1) / height, span_y * (height - 1) / height, height, dtype=dtype, device=device) + u, v = torch.meshgrid(u, v, indexing='xy') + uv = torch.stack([u, v], dim=-1) + return uv + + +def recover_focal_shift(points: torch.Tensor, mask: torch.Tensor = None, focal: torch.Tensor = None, downsample_size: Tuple[int, int] = (64, 64)): + """ + Recover the depth map and FoV from a point map with unknown z shift and focal. + + Note that it assumes: + - the optical center is at the center of the map + - the map is undistorted + - the map is isometric in the x and y directions + + ### Parameters: + - `points: torch.Tensor` of shape (..., H, W, 3) + - `downsample_size: Tuple[int, int]` in (height, width), the size of the downsampled map. Downsampling produces approximate solution and is efficient for large maps. + + ### Returns: + - `focal`: torch.Tensor of shape (...) the estimated focal length, relative to the half diagonal of the map + - `shift`: torch.Tensor of shape (...) Z-axis shift to translate the point map to camera space + """ + shape = points.shape + height, width = points.shape[-3], points.shape[-2] + diagonal = (height ** 2 + width ** 2) ** 0.5 + + points = points.reshape(-1, *shape[-3:]) + mask = None if mask is None else mask.reshape(-1, *shape[-3:-1]) + focal = focal.reshape(-1) if focal is not None else None + uv = normalized_view_plane_uv(width, height, dtype=points.dtype, device=points.device) # (H, W, 2) + + points_lr = F.interpolate(points.permute(0, 3, 1, 2), downsample_size, mode='nearest').permute(0, 2, 3, 1) + uv_lr = F.interpolate(uv.unsqueeze(0).permute(0, 3, 1, 2), downsample_size, mode='nearest').squeeze(0).permute(1, 2, 0) + mask_lr = None if mask is None else F.interpolate(mask.to(torch.float32).unsqueeze(1), downsample_size, mode='nearest').squeeze(1) > 0 + + uv_lr_np = uv_lr.cpu().numpy() + points_lr_np = points_lr.detach().cpu().numpy() + focal_np = focal.cpu().numpy() if focal is not None else None + mask_lr_np = None if mask is None else mask_lr.cpu().numpy() + optim_shift, optim_focal = [], [] + for i in range(points.shape[0]): + points_lr_i_np = points_lr_np[i] if mask is None else points_lr_np[i][mask_lr_np[i]] + uv_lr_i_np = uv_lr_np if mask is None else uv_lr_np[mask_lr_np[i]] + if uv_lr_i_np.shape[0] < 2: + optim_focal.append(1) + optim_shift.append(0) + continue + if focal is None: + optim_shift_i, optim_focal_i = solve_optimal_focal_shift(uv_lr_i_np, points_lr_i_np) + optim_focal.append(float(optim_focal_i)) + else: + optim_shift_i = solve_optimal_shift(uv_lr_i_np, points_lr_i_np, focal_np[i]) + optim_shift.append(float(optim_shift_i)) + optim_shift = torch.tensor(optim_shift, device=points.device, dtype=points.dtype).reshape(shape[:-3]) + + if focal is None: + optim_focal = torch.tensor(optim_focal, device=points.device, dtype=points.dtype).reshape(shape[:-3]) + else: + optim_focal = focal.reshape(shape[:-3]) + + return optim_focal, optim_shift diff --git a/int8/vendor/pytorch3d/LICENSE-pytorch3d.txt b/int8/vendor/pytorch3d/LICENSE-pytorch3d.txt new file mode 100644 index 0000000000000000000000000000000000000000..caab102f8b1bb5578bea0395d1a3c8dd62da6308 --- /dev/null +++ b/int8/vendor/pytorch3d/LICENSE-pytorch3d.txt @@ -0,0 +1,30 @@ +BSD License + +For PyTorch3D software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Meta nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/int8/vendor/pytorch3d/__init__.py b/int8/vendor/pytorch3d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5dea0a55b6c7331d15a22d0ff1647eec0645ec04 --- /dev/null +++ b/int8/vendor/pytorch3d/__init__.py @@ -0,0 +1 @@ +__version__ = "0.7.8" # vendored subset: transforms/ and common/ (BSD) diff --git a/int8/vendor/pytorch3d/common/__init__.py b/int8/vendor/pytorch3d/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..684e4d7e456ccff5ff4aa8c205a60a2263e49044 --- /dev/null +++ b/int8/vendor/pytorch3d/common/__init__.py @@ -0,0 +1 @@ +from .datatypes import Device, get_device, make_device diff --git a/int8/vendor/pytorch3d/common/datatypes.py b/int8/vendor/pytorch3d/common/datatypes.py new file mode 100644 index 0000000000000000000000000000000000000000..8dbff2dbd957f9f1ea542832ed8062dd1fdd2329 --- /dev/null +++ b/int8/vendor/pytorch3d/common/datatypes.py @@ -0,0 +1,60 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + +from typing import Optional, Union + +import torch + + +Device = Union[str, torch.device] + + +def make_device(device: Device) -> torch.device: + """ + Makes an actual torch.device object from the device specified as + either a string or torch.device object. If the device is `cuda` without + a specific index, the index of the current device is assigned. + + Args: + device: Device (as str or torch.device) + + Returns: + A matching torch.device object + """ + device = torch.device(device) if isinstance(device, str) else device + if device.type == "cuda" and device.index is None: + # If cuda but with no index, then the current cuda device is indicated. + # In that case, we fix to that device + device = torch.device(f"cuda:{torch.cuda.current_device()}") + return device + + +def get_device(x, device: Optional[Device] = None) -> torch.device: + """ + Gets the device of the specified variable x if it is a tensor, or + falls back to a default CPU device otherwise. Allows overriding by + providing an explicit device. + + Args: + x: a torch.Tensor to get the device from or another type + device: Device (as str or torch.device) to fall back to + + Returns: + A matching torch.device object + """ + + # User overrides device + if device is not None: + return make_device(device) + + # Set device based on input tensor + if torch.is_tensor(x): + return x.device + + # Default device is cpu + return torch.device("cpu") diff --git a/int8/vendor/pytorch3d/common/workaround/__init__.py b/int8/vendor/pytorch3d/common/workaround/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c16bfe4bd6491fbd818b888bdd583df207f702b --- /dev/null +++ b/int8/vendor/pytorch3d/common/workaround/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + +from .symeig3x3 import symeig3x3 +from .utils import _safe_det_3x3 diff --git a/int8/vendor/pytorch3d/common/workaround/symeig3x3.py b/int8/vendor/pytorch3d/common/workaround/symeig3x3.py new file mode 100644 index 0000000000000000000000000000000000000000..0e3b2f2d456c8187000e06d9378e018ac07428a1 --- /dev/null +++ b/int8/vendor/pytorch3d/common/workaround/symeig3x3.py @@ -0,0 +1,319 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + +import math +from typing import Optional, Tuple + +import torch +import torch.nn.functional as F +from torch import nn + + +class _SymEig3x3(nn.Module): + """ + Optimized implementation of eigenvalues and eigenvectors computation for symmetric 3x3 + matrices. + + Please see https://en.wikipedia.org/wiki/Eigenvalue_algorithm#3.C3.973_matrices + and https://www.geometrictools.com/Documentation/RobustEigenSymmetric3x3.pdf + """ + + def __init__(self, eps: Optional[float] = None) -> None: + """ + Args: + eps: epsilon to specify, if None then use torch.float eps + """ + super().__init__() + + self.register_buffer("_identity", torch.eye(3)) + self.register_buffer("_rotation_2d", torch.tensor([[0.0, -1.0], [1.0, 0.0]])) + self.register_buffer( + "_rotations_3d", self._create_rotation_matrices(self._rotation_2d) + ) + + self._eps = eps or torch.finfo(torch.float).eps + + @staticmethod + def _create_rotation_matrices(rotation_2d) -> torch.Tensor: + """ + Compute rotations for later use in U V computation + + Args: + rotation_2d: a π/2 rotation matrix. + + Returns: + a (3, 3, 3) tensor containing 3 rotation matrices around each of the coordinate axes + by π/2 + """ + + rotations_3d = torch.zeros((3, 3, 3)) + rotation_axes = set(range(3)) + for rotation_axis in rotation_axes: + rest = list(rotation_axes - {rotation_axis}) + rotations_3d[rotation_axis][rest[0], rest] = rotation_2d[0] + rotations_3d[rotation_axis][rest[1], rest] = rotation_2d[1] + + return rotations_3d + + def forward( + self, inputs: torch.Tensor, eigenvectors: bool = True + ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + """ + Compute eigenvalues and (optionally) eigenvectors + + Args: + inputs: symmetric matrices with shape of (..., 3, 3) + eigenvectors: whether should we compute only eigenvalues or eigenvectors as well + + Returns: + Either a tuple of (eigenvalues, eigenvectors) or eigenvalues only, depending on + given params. Eigenvalues are of shape (..., 3) and eigenvectors (..., 3, 3) + """ + if inputs.shape[-2:] != (3, 3): + raise ValueError("Only inputs of shape (..., 3, 3) are supported.") + + inputs_diag = inputs.diagonal(dim1=-2, dim2=-1) + inputs_trace = inputs_diag.sum(-1) + q = inputs_trace / 3.0 + + # Calculate squared sum of elements outside the main diagonal / 2 + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`. + p1 = ((inputs**2).sum(dim=(-1, -2)) - (inputs_diag**2).sum(-1)) / 2 + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`. + p2 = ((inputs_diag - q[..., None]) ** 2).sum(dim=-1) + 2.0 * p1.clamp(self._eps) + + p = torch.sqrt(p2 / 6.0) + B = (inputs - q[..., None, None] * self._identity) / p[..., None, None] + + r = torch.det(B) / 2.0 + # Keep r within (-1.0, 1.0) boundaries with a margin to prevent exploding gradients. + r = r.clamp(-1.0 + self._eps, 1.0 - self._eps) + + phi = torch.acos(r) / 3.0 + eig1 = q + 2 * p * torch.cos(phi) + eig2 = q + 2 * p * torch.cos(phi + 2 * math.pi / 3) + eig3 = 3 * q - eig1 - eig2 + # eigenvals[..., i] is the i-th eigenvalue of the input, α0 ≤ α1 ≤ α2. + eigenvals = torch.stack((eig2, eig3, eig1), dim=-1) + + # Soft dispatch between the degenerate case (diagonal A) and general. + # diag_soft_cond -> 1.0 when p1 < 6 * eps and diag_soft_cond -> 0.0 otherwise. + # We use 6 * eps to take into account the error accumulated during the p1 summation + diag_soft_cond = torch.exp(-((p1 / (6 * self._eps)) ** 2)).detach()[..., None] + + # Eigenvalues are the ordered elements of main diagonal in the degenerate case + diag_eigenvals, _ = torch.sort(inputs_diag, dim=-1) + eigenvals = diag_soft_cond * diag_eigenvals + (1.0 - diag_soft_cond) * eigenvals + + if eigenvectors: + eigenvecs = self._construct_eigenvecs_set(inputs, eigenvals) + else: + eigenvecs = None + + return eigenvals, eigenvecs + + def _construct_eigenvecs_set( + self, inputs: torch.Tensor, eigenvals: torch.Tensor + ) -> torch.Tensor: + """ + Construct orthonormal set of eigenvectors by given inputs and pre-computed eigenvalues + + Args: + inputs: tensor of symmetric matrices of shape (..., 3, 3) + eigenvals: tensor of pre-computed eigenvalues of of shape (..., 3, 3) + + Returns: + Tuple of three eigenvector tensors of shape (..., 3, 3), composing an orthonormal + set + """ + eigenvecs_tuple_for_01 = self._construct_eigenvecs( + inputs, eigenvals[..., 0], eigenvals[..., 1] + ) + eigenvecs_for_01 = torch.stack(eigenvecs_tuple_for_01, dim=-1) + + eigenvecs_tuple_for_21 = self._construct_eigenvecs( + inputs, eigenvals[..., 2], eigenvals[..., 1] + ) + eigenvecs_for_21 = torch.stack(eigenvecs_tuple_for_21[::-1], dim=-1) + + # The result will be smooth here even if both parts of comparison + # are close, because eigenvecs_01 and eigenvecs_21 would be mostly equal as well + eigenvecs_cond = ( + eigenvals[..., 1] - eigenvals[..., 0] + > eigenvals[..., 2] - eigenvals[..., 1] + ).detach() + eigenvecs = torch.where( + eigenvecs_cond[..., None, None], eigenvecs_for_01, eigenvecs_for_21 + ) + + return eigenvecs + + def _construct_eigenvecs( + self, inputs: torch.Tensor, alpha0: torch.Tensor, alpha1: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Construct an orthonormal set of eigenvectors by given pair of eigenvalues. + + Args: + inputs: tensor of symmetric matrices of shape (..., 3, 3) + alpha0: first eigenvalues of shape (..., 3) + alpha1: second eigenvalues of shape (..., 3) + + Returns: + Tuple of three eigenvector tensors of shape (..., 3, 3), composing an orthonormal + set + """ + + # Find the eigenvector corresponding to alpha0, its eigenvalue is distinct + ev0 = self._get_ev0(inputs - alpha0[..., None, None] * self._identity) + u, v = self._get_uv(ev0) + ev1 = self._get_ev1(inputs - alpha1[..., None, None] * self._identity, u, v) + # Third eigenvector is computed as the cross-product of the other two + ev2 = torch.cross(ev0, ev1, dim=-1) + + return ev0, ev1, ev2 + + def _get_ev0(self, char_poly: torch.Tensor) -> torch.Tensor: + """ + Construct the first normalized eigenvector given a characteristic polynomial + + Args: + char_poly: a characteristic polynomials of the input matrices of shape (..., 3, 3) + + Returns: + Tensor of first eigenvectors of shape (..., 3) + """ + + r01 = torch.cross(char_poly[..., 0, :], char_poly[..., 1, :], dim=-1) + r12 = torch.cross(char_poly[..., 1, :], char_poly[..., 2, :], dim=-1) + r02 = torch.cross(char_poly[..., 0, :], char_poly[..., 2, :], dim=-1) + + cross_products = torch.stack((r01, r12, r02), dim=-2) + # Regularize it with + or -eps depending on the sign of the first vector + cross_products += self._eps * self._sign_without_zero( + cross_products[..., :1, :] + ) + + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`. + norms_sq = (cross_products**2).sum(dim=-1) + max_norms_index = norms_sq.argmax(dim=-1) + + # Pick only the cross-product with highest squared norm for each input + max_cross_products = self._gather_by_index( + cross_products, max_norms_index[..., None, None], -2 + ) + # Pick corresponding squared norms for each cross-product + max_norms_sq = self._gather_by_index(norms_sq, max_norms_index[..., None], -1) + + # Normalize cross-product vectors by thier norms + return max_cross_products / torch.sqrt(max_norms_sq[..., None]) + + def _gather_by_index( + self, source: torch.Tensor, index: torch.Tensor, dim: int + ) -> torch.Tensor: + """ + Selects elements from the given source tensor by provided index tensor. + Number of dimensions should be the same for source and index tensors. + + Args: + source: input tensor to gather from + index: index tensor with indices to gather from source + dim: dimension to gather across + + Returns: + Tensor of shape same as the source with exception of specified dimension. + """ + + index_shape = list(source.shape) + index_shape[dim] = 1 + + return source.gather(dim, index.expand(index_shape)).squeeze(dim) + + def _get_uv(self, w: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Computes unit-length vectors U and V such that {U, V, W} is a right-handed + orthonormal set. + + Args: + w: eigenvector tensor of shape (..., 3) + + Returns: + Tuple of U and V unit-length vector tensors of shape (..., 3) + """ + + min_idx = w.abs().argmin(dim=-1) + rotation_2d = self._rotations_3d[min_idx].to(w) + + u = F.normalize((rotation_2d @ w[..., None])[..., 0], dim=-1) + v = torch.cross(w, u, dim=-1) + return u, v + + def _get_ev1( + self, char_poly: torch.Tensor, u: torch.Tensor, v: torch.Tensor + ) -> torch.Tensor: + """ + Computes the second normalized eigenvector given a characteristic polynomial + and U and V vectors + + Args: + char_poly: a characteristic polynomials of the input matrices of shape (..., 3, 3) + u: unit-length vectors from _get_uv method + v: unit-length vectors from _get_uv method + + Returns: + desc + """ + + j = torch.stack((u, v), dim=-1) + m = j.transpose(-1, -2) @ char_poly @ j + + # If angle between those vectors is acute, take their sum = m[..., 0, :] + m[..., 1, :], + # otherwise take the difference = m[..., 0, :] - m[..., 1, :] + # m is in theory of rank 1 (or 0), so it snaps only when one of the rows is close to 0 + is_acute_sign = self._sign_without_zero( + (m[..., 0, :] * m[..., 1, :]).sum(dim=-1) + ).detach() + + rowspace = m[..., 0, :] + is_acute_sign[..., None] * m[..., 1, :] + # rowspace will be near zero for second-order eigenvalues + # this regularization guarantees abs(rowspace[0]) >= eps in a smooth'ish way + rowspace += self._eps * self._sign_without_zero(rowspace[..., :1]) + + return ( + j + @ F.normalize(rowspace @ self._rotation_2d.to(rowspace), dim=-1)[..., None] + )[..., 0] + + @staticmethod + def _sign_without_zero(tensor): + """ + Args: + tensor: an arbitrary shaped tensor + + Returns: + Tensor of the same shape as an input, but with 1.0 if tensor > 0.0 and -1.0 + otherwise + """ + return 2.0 * (tensor > 0.0).to(tensor.dtype) - 1.0 + + +def symeig3x3( + inputs: torch.Tensor, eigenvectors: bool = True +) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + """ + Compute eigenvalues and (optionally) eigenvectors + + Args: + inputs: symmetric matrices with shape of (..., 3, 3) + eigenvectors: whether should we compute only eigenvalues or eigenvectors as well + + Returns: + Either a tuple of (eigenvalues, eigenvectors) or eigenvalues only, depending on + given params. Eigenvalues are of shape (..., 3) and eigenvectors (..., 3, 3) + """ + return _SymEig3x3().to(inputs.device)(inputs, eigenvectors=eigenvectors) diff --git a/int8/vendor/pytorch3d/common/workaround/utils.py b/int8/vendor/pytorch3d/common/workaround/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..70d5d48e4261bfec90c3a6919b5a3fa980c61559 --- /dev/null +++ b/int8/vendor/pytorch3d/common/workaround/utils.py @@ -0,0 +1,33 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + + +import torch + + +def _safe_det_3x3(t: torch.Tensor): + """ + Fast determinant calculation for a batch of 3x3 matrices. + + Note, result of this function might not be the same as `torch.det()`. + The differences might be in the last significant digit. + + Args: + t: Tensor of shape (N, 3, 3). + + Returns: + Tensor of shape (N) with determinants. + """ + + det = ( + t[..., 0, 0] * (t[..., 1, 1] * t[..., 2, 2] - t[..., 1, 2] * t[..., 2, 1]) + - t[..., 0, 1] * (t[..., 1, 0] * t[..., 2, 2] - t[..., 2, 0] * t[..., 1, 2]) + + t[..., 0, 2] * (t[..., 1, 0] * t[..., 2, 1] - t[..., 2, 0] * t[..., 1, 1]) + ) + + return det diff --git a/int8/vendor/pytorch3d/transforms/__init__.py b/int8/vendor/pytorch3d/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b1840be04994e68c154bf3295bbfb9ed95f69d53 --- /dev/null +++ b/int8/vendor/pytorch3d/transforms/__init__.py @@ -0,0 +1,41 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + +from .math import acos_linear_extrapolation +from .rotation_conversions import ( + axis_angle_to_matrix, + axis_angle_to_quaternion, + euler_angles_to_matrix, + matrix_to_axis_angle, + matrix_to_euler_angles, + matrix_to_quaternion, + matrix_to_rotation_6d, + quaternion_apply, + quaternion_invert, + quaternion_multiply, + quaternion_raw_multiply, + quaternion_to_axis_angle, + quaternion_to_matrix, + random_quaternions, + random_rotation, + random_rotations, + rotation_6d_to_matrix, + standardize_quaternion, +) +from .se3 import se3_exp_map, se3_log_map +from .so3 import ( + so3_exp_map, + so3_exponential_map, + so3_log_map, + so3_relative_angle, + so3_rotation_angle, +) +from .transform3d import Rotate, RotateAxisAngle, Scale, Transform3d, Translate + + +__all__ = [k for k in globals().keys() if not k.startswith("_")] diff --git a/int8/vendor/pytorch3d/transforms/math.py b/int8/vendor/pytorch3d/transforms/math.py new file mode 100644 index 0000000000000000000000000000000000000000..53532f365e16562cdc0d9a550ef59824adb7f84f --- /dev/null +++ b/int8/vendor/pytorch3d/transforms/math.py @@ -0,0 +1,87 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + +import math +from typing import Tuple + +import torch + + +DEFAULT_ACOS_BOUND: float = 1.0 - 1e-4 + + +def acos_linear_extrapolation( + x: torch.Tensor, + bounds: Tuple[float, float] = (-DEFAULT_ACOS_BOUND, DEFAULT_ACOS_BOUND), +) -> torch.Tensor: + """ + Implements `arccos(x)` which is linearly extrapolated outside `x`'s original + domain of `(-1, 1)`. This allows for stable backpropagation in case `x` + is not guaranteed to be strictly within `(-1, 1)`. + + More specifically:: + + bounds=(lower_bound, upper_bound) + if lower_bound <= x <= upper_bound: + acos_linear_extrapolation(x) = acos(x) + elif x <= lower_bound: # 1st order Taylor approximation + acos_linear_extrapolation(x) + = acos(lower_bound) + dacos/dx(lower_bound) * (x - lower_bound) + else: # x >= upper_bound + acos_linear_extrapolation(x) + = acos(upper_bound) + dacos/dx(upper_bound) * (x - upper_bound) + + Args: + x: Input `Tensor`. + bounds: A float 2-tuple defining the region for the + linear extrapolation of `acos`. + The first/second element of `bound` + describes the lower/upper bound that defines the lower/upper + extrapolation region, i.e. the region where + `x <= bound[0]`/`bound[1] <= x`. + Note that all elements of `bound` have to be within (-1, 1). + Returns: + acos_linear_extrapolation: `Tensor` containing the extrapolated `arccos(x)`. + """ + + lower_bound, upper_bound = bounds + + if lower_bound > upper_bound: + raise ValueError("lower bound has to be smaller or equal to upper bound.") + + if lower_bound <= -1.0 or upper_bound >= 1.0: + raise ValueError("Both lower bound and upper bound have to be within (-1, 1).") + + # init an empty tensor and define the domain sets + acos_extrap = torch.empty_like(x) + x_upper = x >= upper_bound + x_lower = x <= lower_bound + x_mid = (~x_upper) & (~x_lower) + + # acos calculation for upper_bound < x < lower_bound + acos_extrap[x_mid] = torch.acos(x[x_mid]) + # the linear extrapolation for x >= upper_bound + acos_extrap[x_upper] = _acos_linear_approximation(x[x_upper], upper_bound) + # the linear extrapolation for x <= lower_bound + acos_extrap[x_lower] = _acos_linear_approximation(x[x_lower], lower_bound) + + return acos_extrap + + +def _acos_linear_approximation(x: torch.Tensor, x0: float) -> torch.Tensor: + """ + Calculates the 1st order Taylor expansion of `arccos(x)` around `x0`. + """ + return (x - x0) * _dacos_dx(x0) + math.acos(x0) + + +def _dacos_dx(x: float) -> float: + """ + Calculates the derivative of `arccos(x)` w.r.t. `x`. + """ + return (-1.0) / math.sqrt(1.0 - x * x) diff --git a/int8/vendor/pytorch3d/transforms/rotation_conversions.py b/int8/vendor/pytorch3d/transforms/rotation_conversions.py new file mode 100644 index 0000000000000000000000000000000000000000..79e9463ebe62afdecbb549c88a05c9ea2d8a9a6a --- /dev/null +++ b/int8/vendor/pytorch3d/transforms/rotation_conversions.py @@ -0,0 +1,601 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + +from typing import Optional + +import torch +import torch.nn.functional as F + +from ..common.datatypes import Device + + +""" +The transformation matrices returned from the functions in this file assume +the points on which the transformation will be applied are column vectors. +i.e. the R matrix is structured as + + R = [ + [Rxx, Rxy, Rxz], + [Ryx, Ryy, Ryz], + [Rzx, Rzy, Rzz], + ] # (3, 3) + +This matrix can be applied to column vectors by post multiplication +by the points e.g. + + points = [[0], [1], [2]] # (3 x 1) xyz coordinates of a point + transformed_points = R * points + +To apply the same matrix to points which are row vectors, the R matrix +can be transposed and pre multiplied by the points: + +e.g. + points = [[0, 1, 2]] # (1 x 3) xyz coordinates of a point + transformed_points = points * R.transpose(1, 0) +""" + + +def quaternion_to_matrix(quaternions: torch.Tensor) -> torch.Tensor: + """ + Convert rotations given as quaternions to rotation matrices. + + Args: + quaternions: quaternions with real part first, + as tensor of shape (..., 4). + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + r, i, j, k = torch.unbind(quaternions, -1) + # pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`. + two_s = 2.0 / (quaternions * quaternions).sum(-1) + + o = torch.stack( + ( + 1 - two_s * (j * j + k * k), + two_s * (i * j - k * r), + two_s * (i * k + j * r), + two_s * (i * j + k * r), + 1 - two_s * (i * i + k * k), + two_s * (j * k - i * r), + two_s * (i * k - j * r), + two_s * (j * k + i * r), + 1 - two_s * (i * i + j * j), + ), + -1, + ) + return o.reshape(quaternions.shape[:-1] + (3, 3)) + + +def _copysign(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + """ + Return a tensor where each element has the absolute value taken from the, + corresponding element of a, with sign taken from the corresponding + element of b. This is like the standard copysign floating-point operation, + but is not careful about negative 0 and NaN. + + Args: + a: source tensor. + b: tensor whose signs will be used, of the same shape as a. + + Returns: + Tensor of the same shape as a with the signs of b. + """ + signs_differ = (a < 0) != (b < 0) + return torch.where(signs_differ, -a, a) + + +def _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor: + """ + Returns torch.sqrt(torch.max(0, x)) + but with a zero subgradient where x is 0. + """ + ret = torch.zeros_like(x) + positive_mask = x > 0 + if torch.is_grad_enabled(): + ret[positive_mask] = torch.sqrt(x[positive_mask]) + else: + ret = torch.where(positive_mask, torch.sqrt(x), ret) + return ret + + +def matrix_to_quaternion(matrix: torch.Tensor) -> torch.Tensor: + """ + Convert rotations given as rotation matrices to quaternions. + + Args: + matrix: Rotation matrices as tensor of shape (..., 3, 3). + + Returns: + quaternions with real part first, as tensor of shape (..., 4). + """ + if matrix.size(-1) != 3 or matrix.size(-2) != 3: + raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.") + + batch_dim = matrix.shape[:-2] + m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind( + matrix.reshape(batch_dim + (9,)), dim=-1 + ) + + q_abs = _sqrt_positive_part( + torch.stack( + [ + 1.0 + m00 + m11 + m22, + 1.0 + m00 - m11 - m22, + 1.0 - m00 + m11 - m22, + 1.0 - m00 - m11 + m22, + ], + dim=-1, + ) + ) + + # we produce the desired quaternion multiplied by each of r, i, j, k + quat_by_rijk = torch.stack( + [ + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1), + ], + dim=-2, + ) + + # We floor here at 0.1 but the exact level is not important; if q_abs is small, + # the candidate won't be picked. + flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device) + quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr)) + + # if not for numerical problems, quat_candidates[i] should be same (up to a sign), + # forall i; we pick the best-conditioned one (with the largest denominator) + out = quat_candidates[ + F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, : + ].reshape(batch_dim + (4,)) + return standardize_quaternion(out) + + +def _axis_angle_rotation(axis: str, angle: torch.Tensor) -> torch.Tensor: + """ + Return the rotation matrices for one of the rotations about an axis + of which Euler angles describe, for each value of the angle given. + + Args: + axis: Axis label "X" or "Y or "Z". + angle: any shape tensor of Euler angles in radians + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + + cos = torch.cos(angle) + sin = torch.sin(angle) + one = torch.ones_like(angle) + zero = torch.zeros_like(angle) + + if axis == "X": + R_flat = (one, zero, zero, zero, cos, -sin, zero, sin, cos) + elif axis == "Y": + R_flat = (cos, zero, sin, zero, one, zero, -sin, zero, cos) + elif axis == "Z": + R_flat = (cos, -sin, zero, sin, cos, zero, zero, zero, one) + else: + raise ValueError("letter must be either X, Y or Z.") + + return torch.stack(R_flat, -1).reshape(angle.shape + (3, 3)) + + +def euler_angles_to_matrix(euler_angles: torch.Tensor, convention: str) -> torch.Tensor: + """ + Convert rotations given as Euler angles in radians to rotation matrices. + + Args: + euler_angles: Euler angles in radians as tensor of shape (..., 3). + convention: Convention string of three uppercase letters from + {"X", "Y", and "Z"}. + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + if euler_angles.dim() == 0 or euler_angles.shape[-1] != 3: + raise ValueError("Invalid input euler angles.") + if len(convention) != 3: + raise ValueError("Convention must have 3 letters.") + if convention[1] in (convention[0], convention[2]): + raise ValueError(f"Invalid convention {convention}.") + for letter in convention: + if letter not in ("X", "Y", "Z"): + raise ValueError(f"Invalid letter {letter} in convention string.") + matrices = [ + _axis_angle_rotation(c, e) + for c, e in zip(convention, torch.unbind(euler_angles, -1)) + ] + # return functools.reduce(torch.matmul, matrices) + return torch.matmul(torch.matmul(matrices[0], matrices[1]), matrices[2]) + + +def _angle_from_tan( + axis: str, other_axis: str, data, horizontal: bool, tait_bryan: bool +) -> torch.Tensor: + """ + Extract the first or third Euler angle from the two members of + the matrix which are positive constant times its sine and cosine. + + Args: + axis: Axis label "X" or "Y or "Z" for the angle we are finding. + other_axis: Axis label "X" or "Y or "Z" for the middle axis in the + convention. + data: Rotation matrices as tensor of shape (..., 3, 3). + horizontal: Whether we are looking for the angle for the third axis, + which means the relevant entries are in the same row of the + rotation matrix. If not, they are in the same column. + tait_bryan: Whether the first and third axes in the convention differ. + + Returns: + Euler Angles in radians for each matrix in data as a tensor + of shape (...). + """ + + i1, i2 = {"X": (2, 1), "Y": (0, 2), "Z": (1, 0)}[axis] + if horizontal: + i2, i1 = i1, i2 + even = (axis + other_axis) in ["XY", "YZ", "ZX"] + if horizontal == even: + return torch.atan2(data[..., i1], data[..., i2]) + if tait_bryan: + return torch.atan2(-data[..., i2], data[..., i1]) + return torch.atan2(data[..., i2], -data[..., i1]) + + +def _index_from_letter(letter: str) -> int: + if letter == "X": + return 0 + if letter == "Y": + return 1 + if letter == "Z": + return 2 + raise ValueError("letter must be either X, Y or Z.") + + +def matrix_to_euler_angles(matrix: torch.Tensor, convention: str) -> torch.Tensor: + """ + Convert rotations given as rotation matrices to Euler angles in radians. + + Args: + matrix: Rotation matrices as tensor of shape (..., 3, 3). + convention: Convention string of three uppercase letters. + + Returns: + Euler angles in radians as tensor of shape (..., 3). + """ + if len(convention) != 3: + raise ValueError("Convention must have 3 letters.") + if convention[1] in (convention[0], convention[2]): + raise ValueError(f"Invalid convention {convention}.") + for letter in convention: + if letter not in ("X", "Y", "Z"): + raise ValueError(f"Invalid letter {letter} in convention string.") + if matrix.size(-1) != 3 or matrix.size(-2) != 3: + raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.") + i0 = _index_from_letter(convention[0]) + i2 = _index_from_letter(convention[2]) + tait_bryan = i0 != i2 + if tait_bryan: + central_angle = torch.asin( + matrix[..., i0, i2] * (-1.0 if i0 - i2 in [-1, 2] else 1.0) + ) + else: + central_angle = torch.acos(matrix[..., i0, i0]) + + o = ( + _angle_from_tan( + convention[0], convention[1], matrix[..., i2], False, tait_bryan + ), + central_angle, + _angle_from_tan( + convention[2], convention[1], matrix[..., i0, :], True, tait_bryan + ), + ) + return torch.stack(o, -1) + + +def random_quaternions( + n: int, dtype: Optional[torch.dtype] = None, device: Optional[Device] = None +) -> torch.Tensor: + """ + Generate random quaternions representing rotations, + i.e. versors with nonnegative real part. + + Args: + n: Number of quaternions in a batch to return. + dtype: Type to return. + device: Desired device of returned tensor. Default: + uses the current device for the default tensor type. + + Returns: + Quaternions as tensor of shape (N, 4). + """ + if isinstance(device, str): + device = torch.device(device) + o = torch.randn((n, 4), dtype=dtype, device=device) + s = (o * o).sum(1) + o = o / _copysign(torch.sqrt(s), o[:, 0])[:, None] + return o + + +def random_rotations( + n: int, dtype: Optional[torch.dtype] = None, device: Optional[Device] = None +) -> torch.Tensor: + """ + Generate random rotations as 3x3 rotation matrices. + + Args: + n: Number of rotation matrices in a batch to return. + dtype: Type to return. + device: Device of returned tensor. Default: if None, + uses the current device for the default tensor type. + + Returns: + Rotation matrices as tensor of shape (n, 3, 3). + """ + quaternions = random_quaternions(n, dtype=dtype, device=device) + return quaternion_to_matrix(quaternions) + + +def random_rotation( + dtype: Optional[torch.dtype] = None, device: Optional[Device] = None +) -> torch.Tensor: + """ + Generate a single random 3x3 rotation matrix. + + Args: + dtype: Type to return + device: Device of returned tensor. Default: if None, + uses the current device for the default tensor type + + Returns: + Rotation matrix as tensor of shape (3, 3). + """ + return random_rotations(1, dtype, device)[0] + + +def standardize_quaternion(quaternions: torch.Tensor) -> torch.Tensor: + """ + Convert a unit quaternion to a standard form: one in which the real + part is non negative. + + Args: + quaternions: Quaternions with real part first, + as tensor of shape (..., 4). + + Returns: + Standardized quaternions as tensor of shape (..., 4). + """ + return torch.where(quaternions[..., 0:1] < 0, -quaternions, quaternions) + + +def quaternion_raw_multiply(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + """ + Multiply two quaternions. + Usual torch rules for broadcasting apply. + + Args: + a: Quaternions as tensor of shape (..., 4), real part first. + b: Quaternions as tensor of shape (..., 4), real part first. + + Returns: + The product of a and b, a tensor of quaternions shape (..., 4). + """ + aw, ax, ay, az = torch.unbind(a, -1) + bw, bx, by, bz = torch.unbind(b, -1) + ow = aw * bw - ax * bx - ay * by - az * bz + ox = aw * bx + ax * bw + ay * bz - az * by + oy = aw * by - ax * bz + ay * bw + az * bx + oz = aw * bz + ax * by - ay * bx + az * bw + return torch.stack((ow, ox, oy, oz), -1) + + +def quaternion_multiply(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + """ + Multiply two quaternions representing rotations, returning the quaternion + representing their composition, i.e. the versor with nonnegative real part. + Usual torch rules for broadcasting apply. + + Args: + a: Quaternions as tensor of shape (..., 4), real part first. + b: Quaternions as tensor of shape (..., 4), real part first. + + Returns: + The product of a and b, a tensor of quaternions of shape (..., 4). + """ + ab = quaternion_raw_multiply(a, b) + return standardize_quaternion(ab) + + +def quaternion_invert(quaternion: torch.Tensor) -> torch.Tensor: + """ + Given a quaternion representing rotation, get the quaternion representing + its inverse. + + Args: + quaternion: Quaternions as tensor of shape (..., 4), with real part + first, which must be versors (unit quaternions). + + Returns: + The inverse, a tensor of quaternions of shape (..., 4). + """ + + scaling = torch.tensor([1, -1, -1, -1], device=quaternion.device) + return quaternion * scaling + + +def quaternion_apply(quaternion: torch.Tensor, point: torch.Tensor) -> torch.Tensor: + """ + Apply the rotation given by a quaternion to a 3D point. + Usual torch rules for broadcasting apply. + + Args: + quaternion: Tensor of quaternions, real part first, of shape (..., 4). + point: Tensor of 3D points of shape (..., 3). + + Returns: + Tensor of rotated points of shape (..., 3). + """ + if point.size(-1) != 3: + raise ValueError(f"Points are not in 3D, {point.shape}.") + real_parts = point.new_zeros(point.shape[:-1] + (1,)) + point_as_quaternion = torch.cat((real_parts, point), -1) + out = quaternion_raw_multiply( + quaternion_raw_multiply(quaternion, point_as_quaternion), + quaternion_invert(quaternion), + ) + return out[..., 1:] + + +def axis_angle_to_matrix(axis_angle: torch.Tensor) -> torch.Tensor: + """ + Convert rotations given as axis/angle to rotation matrices. + + Args: + axis_angle: Rotations given as a vector in axis angle form, + as a tensor of shape (..., 3), where the magnitude is + the angle turned anticlockwise in radians around the + vector's direction. + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + return quaternion_to_matrix(axis_angle_to_quaternion(axis_angle)) + + +def matrix_to_axis_angle(matrix: torch.Tensor) -> torch.Tensor: + """ + Convert rotations given as rotation matrices to axis/angle. + + Args: + matrix: Rotation matrices as tensor of shape (..., 3, 3). + + Returns: + Rotations given as a vector in axis angle form, as a tensor + of shape (..., 3), where the magnitude is the angle + turned anticlockwise in radians around the vector's + direction. + """ + return quaternion_to_axis_angle(matrix_to_quaternion(matrix)) + + +def axis_angle_to_quaternion(axis_angle: torch.Tensor) -> torch.Tensor: + """ + Convert rotations given as axis/angle to quaternions. + + Args: + axis_angle: Rotations given as a vector in axis angle form, + as a tensor of shape (..., 3), where the magnitude is + the angle turned anticlockwise in radians around the + vector's direction. + + Returns: + quaternions with real part first, as tensor of shape (..., 4). + """ + angles = torch.norm(axis_angle, p=2, dim=-1, keepdim=True) + half_angles = angles * 0.5 + eps = 1e-6 + small_angles = angles.abs() < eps + sin_half_angles_over_angles = torch.empty_like(angles) + sin_half_angles_over_angles[~small_angles] = ( + torch.sin(half_angles[~small_angles]) / angles[~small_angles] + ) + # for x small, sin(x/2) is about x/2 - (x/2)^3/6 + # so sin(x/2)/x is about 1/2 - (x*x)/48 + sin_half_angles_over_angles[small_angles] = ( + 0.5 - (angles[small_angles] * angles[small_angles]) / 48 + ) + quaternions = torch.cat( + [torch.cos(half_angles), axis_angle * sin_half_angles_over_angles], dim=-1 + ) + return quaternions + + +def quaternion_to_axis_angle(quaternions: torch.Tensor) -> torch.Tensor: + """ + Convert rotations given as quaternions to axis/angle. + + Args: + quaternions: quaternions with real part first, + as tensor of shape (..., 4). + + Returns: + Rotations given as a vector in axis angle form, as a tensor + of shape (..., 3), where the magnitude is the angle + turned anticlockwise in radians around the vector's + direction. + """ + norms = torch.norm(quaternions[..., 1:], p=2, dim=-1, keepdim=True) + half_angles = torch.atan2(norms, quaternions[..., :1]) + angles = 2 * half_angles + eps = 1e-6 + small_angles = angles.abs() < eps + sin_half_angles_over_angles = torch.empty_like(angles) + sin_half_angles_over_angles[~small_angles] = ( + torch.sin(half_angles[~small_angles]) / angles[~small_angles] + ) + # for x small, sin(x/2) is about x/2 - (x/2)^3/6 + # so sin(x/2)/x is about 1/2 - (x*x)/48 + sin_half_angles_over_angles[small_angles] = ( + 0.5 - (angles[small_angles] * angles[small_angles]) / 48 + ) + return quaternions[..., 1:] / sin_half_angles_over_angles + + +def rotation_6d_to_matrix(d6: torch.Tensor) -> torch.Tensor: + """ + Converts 6D rotation representation by Zhou et al. [1] to rotation matrix + using Gram--Schmidt orthogonalization per Section B of [1]. + Args: + d6: 6D rotation representation, of size (*, 6) + + Returns: + batch of rotation matrices of size (*, 3, 3) + + [1] Zhou, Y., Barnes, C., Lu, J., Yang, J., & Li, H. + On the Continuity of Rotation Representations in Neural Networks. + IEEE Conference on Computer Vision and Pattern Recognition, 2019. + Retrieved from http://arxiv.org/abs/1812.07035 + """ + + a1, a2 = d6[..., :3], d6[..., 3:] + b1 = F.normalize(a1, dim=-1) + b2 = a2 - (b1 * a2).sum(-1, keepdim=True) * b1 + b2 = F.normalize(b2, dim=-1) + b3 = torch.cross(b1, b2, dim=-1) + return torch.stack((b1, b2, b3), dim=-2) + + +def matrix_to_rotation_6d(matrix: torch.Tensor) -> torch.Tensor: + """ + Converts rotation matrices to 6D rotation representation by Zhou et al. [1] + by dropping the last row. Note that 6D representation is not unique. + Args: + matrix: batch of rotation matrices of size (*, 3, 3) + + Returns: + 6D rotation representation, of size (*, 6) + + [1] Zhou, Y., Barnes, C., Lu, J., Yang, J., & Li, H. + On the Continuity of Rotation Representations in Neural Networks. + IEEE Conference on Computer Vision and Pattern Recognition, 2019. + Retrieved from http://arxiv.org/abs/1812.07035 + """ + batch_dim = matrix.size()[:-2] + return matrix[..., :2, :].clone().reshape(batch_dim + (6,)) diff --git a/int8/vendor/pytorch3d/transforms/se3.py b/int8/vendor/pytorch3d/transforms/se3.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c348b1b8184e815fdc09c73ff8d38c54af402c --- /dev/null +++ b/int8/vendor/pytorch3d/transforms/se3.py @@ -0,0 +1,223 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + +import torch + +from .so3 import _so3_exp_map, hat, so3_log_map + + +def se3_exp_map(log_transform: torch.Tensor, eps: float = 1e-4) -> torch.Tensor: + """ + Convert a batch of logarithmic representations of SE(3) matrices `log_transform` + to a batch of 4x4 SE(3) matrices using the exponential map. + See e.g. [1], Sec 9.4.2. for more detailed description. + + A SE(3) matrix has the following form: + ``` + [ R 0 ] + [ T 1 ] , + ``` + where `R` is a 3x3 rotation matrix and `T` is a 3-D translation vector. + SE(3) matrices are commonly used to represent rigid motions or camera extrinsics. + + In the SE(3) logarithmic representation SE(3) matrices are + represented as 6-dimensional vectors `[log_translation | log_rotation]`, + i.e. a concatenation of two 3D vectors `log_translation` and `log_rotation`. + + The conversion from the 6D representation to a 4x4 SE(3) matrix `transform` + is done as follows: + ``` + transform = exp( [ hat(log_rotation) 0 ] + [ log_translation 1 ] ) , + ``` + where `exp` is the matrix exponential and `hat` is the Hat operator [2]. + + Note that for any `log_transform` with `0 <= ||log_rotation|| < 2pi` + (i.e. the rotation angle is between 0 and 2pi), the following identity holds: + ``` + se3_log_map(se3_exponential_map(log_transform)) == log_transform + ``` + + The conversion has a singularity around `||log(transform)|| = 0` + which is handled by clamping controlled with the `eps` argument. + + Args: + log_transform: Batch of vectors of shape `(minibatch, 6)`. + eps: A threshold for clipping the squared norm of the rotation logarithm + to avoid unstable gradients in the singular case. + + Returns: + Batch of transformation matrices of shape `(minibatch, 4, 4)`. + + Raises: + ValueError if `log_transform` is of incorrect shape. + + [1] https://jinyongjeong.github.io/Download/SE3/jlblanco2010geometry3d_techrep.pdf + [2] https://en.wikipedia.org/wiki/Hat_operator + """ + + if log_transform.ndim != 2 or log_transform.shape[1] != 6: + raise ValueError("Expected input to be of shape (N, 6).") + + N, _ = log_transform.shape + + log_translation = log_transform[..., :3] + log_rotation = log_transform[..., 3:] + + # rotation is an exponential map of log_rotation + ( + R, + rotation_angles, + log_rotation_hat, + log_rotation_hat_square, + ) = _so3_exp_map(log_rotation, eps=eps) + + # translation is V @ T + V = _se3_V_matrix( + log_rotation, + log_rotation_hat, + log_rotation_hat_square, + rotation_angles, + eps=eps, + ) + T = torch.bmm(V, log_translation[:, :, None])[:, :, 0] + + transform = torch.zeros( + N, 4, 4, dtype=log_transform.dtype, device=log_transform.device + ) + + transform[:, :3, :3] = R + transform[:, :3, 3] = T + transform[:, 3, 3] = 1.0 + + return transform.permute(0, 2, 1) + + +def se3_log_map( + transform: torch.Tensor, eps: float = 1e-4, cos_bound: float = 1e-4 +) -> torch.Tensor: + """ + Convert a batch of 4x4 transformation matrices `transform` + to a batch of 6-dimensional SE(3) logarithms of the SE(3) matrices. + See e.g. [1], Sec 9.4.2. for more detailed description. + + A SE(3) matrix has the following form: + ``` + [ R 0 ] + [ T 1 ] , + ``` + where `R` is an orthonormal 3x3 rotation matrix and `T` is a 3-D translation vector. + SE(3) matrices are commonly used to represent rigid motions or camera extrinsics. + + In the SE(3) logarithmic representation SE(3) matrices are + represented as 6-dimensional vectors `[log_translation | log_rotation]`, + i.e. a concatenation of two 3D vectors `log_translation` and `log_rotation`. + + The conversion from the 4x4 SE(3) matrix `transform` to the + 6D representation `log_transform = [log_translation | log_rotation]` + is done as follows: + ``` + log_transform = log(transform) + log_translation = log_transform[3, :3] + log_rotation = inv_hat(log_transform[:3, :3]) + ``` + where `log` is the matrix logarithm + and `inv_hat` is the inverse of the Hat operator [2]. + + Note that for any valid 4x4 `transform` matrix, the following identity holds: + ``` + se3_exp_map(se3_log_map(transform)) == transform + ``` + + The conversion has a singularity around `(transform=I)` which is handled + by clamping controlled with the `eps` and `cos_bound` arguments. + + Args: + transform: batch of SE(3) matrices of shape `(minibatch, 4, 4)`. + eps: A threshold for clipping the squared norm of the rotation logarithm + to avoid division by zero in the singular case. + cos_bound: Clamps the cosine of the rotation angle to + [-1 + cos_bound, 3 - cos_bound] to avoid non-finite outputs. + The non-finite outputs can be caused by passing small rotation angles + to the `acos` function in `so3_rotation_angle` of `so3_log_map`. + + Returns: + Batch of logarithms of input SE(3) matrices + of shape `(minibatch, 6)`. + + Raises: + ValueError if `transform` is of incorrect shape. + ValueError if `R` has an unexpected trace. + + [1] https://jinyongjeong.github.io/Download/SE3/jlblanco2010geometry3d_techrep.pdf + [2] https://en.wikipedia.org/wiki/Hat_operator + """ + + if transform.ndim != 3: + raise ValueError("Input tensor shape has to be (N, 4, 4).") + + N, dim1, dim2 = transform.shape + if dim1 != 4 or dim2 != 4: + raise ValueError("Input tensor shape has to be (N, 4, 4).") + + if not torch.allclose(transform[:, :3, 3], torch.zeros_like(transform[:, :3, 3])): + raise ValueError("All elements of `transform[:, :3, 3]` should be 0.") + + # log_rot is just so3_log_map of the upper left 3x3 block + R = transform[:, :3, :3].permute(0, 2, 1) + log_rotation = so3_log_map(R, eps=eps, cos_bound=cos_bound) + + # log_translation is V^-1 @ T + T = transform[:, 3, :3] + V = _se3_V_matrix(*_get_se3_V_input(log_rotation), eps=eps) + log_translation = torch.linalg.solve(V, T[:, :, None])[:, :, 0] + + return torch.cat((log_translation, log_rotation), dim=1) + + +def _se3_V_matrix( + log_rotation: torch.Tensor, + log_rotation_hat: torch.Tensor, + log_rotation_hat_square: torch.Tensor, + rotation_angles: torch.Tensor, + eps: float = 1e-4, +) -> torch.Tensor: + """ + A helper function that computes the "V" matrix from [1], Sec 9.4.2. + [1] https://jinyongjeong.github.io/Download/SE3/jlblanco2010geometry3d_techrep.pdf + """ + + V = ( + torch.eye(3, dtype=log_rotation.dtype, device=log_rotation.device)[None] + + log_rotation_hat + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`. + * ((1 - torch.cos(rotation_angles)) / (rotation_angles**2))[:, None, None] + + ( + log_rotation_hat_square + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + * ((rotation_angles - torch.sin(rotation_angles)) / (rotation_angles**3))[ + :, None, None + ] + ) + ) + + return V + + +def _get_se3_V_input(log_rotation: torch.Tensor, eps: float = 1e-4): + """ + A helper function that computes the input variables to the `_se3_V_matrix` + function. + """ + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`. + nrms = (log_rotation**2).sum(-1) + rotation_angles = torch.clamp(nrms, eps).sqrt() + log_rotation_hat = hat(log_rotation) + log_rotation_hat_square = torch.bmm(log_rotation_hat, log_rotation_hat) + return log_rotation, log_rotation_hat, log_rotation_hat_square, rotation_angles diff --git a/int8/vendor/pytorch3d/transforms/so3.py b/int8/vendor/pytorch3d/transforms/so3.py new file mode 100644 index 0000000000000000000000000000000000000000..e443722b0b499136e1e2d1db80714181f8d8a519 --- /dev/null +++ b/int8/vendor/pytorch3d/transforms/so3.py @@ -0,0 +1,270 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + +import warnings +from typing import Tuple + +import torch +from pytorch3d.transforms import rotation_conversions + +from ..transforms import acos_linear_extrapolation + + +def so3_relative_angle( + R1: torch.Tensor, + R2: torch.Tensor, + cos_angle: bool = False, + cos_bound: float = 1e-4, + eps: float = 1e-4, +) -> torch.Tensor: + """ + Calculates the relative angle (in radians) between pairs of + rotation matrices `R1` and `R2` with `angle = acos(0.5 * (Trace(R1 R2^T)-1))` + + .. note:: + This corresponds to a geodesic distance on the 3D manifold of rotation + matrices. + + Args: + R1: Batch of rotation matrices of shape `(minibatch, 3, 3)`. + R2: Batch of rotation matrices of shape `(minibatch, 3, 3)`. + cos_angle: If==True return cosine of the relative angle rather than + the angle itself. This can avoid the unstable calculation of `acos`. + cos_bound: Clamps the cosine of the relative rotation angle to + [-1 + cos_bound, 1 - cos_bound] to avoid non-finite outputs/gradients + of the `acos` call. Note that the non-finite outputs/gradients + are returned when the angle is requested (i.e. `cos_angle==False`) + and the rotation angle is close to 0 or π. + eps: Tolerance for the valid trace check of the relative rotation matrix + in `so3_rotation_angle`. + Returns: + Corresponding rotation angles of shape `(minibatch,)`. + If `cos_angle==True`, returns the cosine of the angles. + + Raises: + ValueError if `R1` or `R2` is of incorrect shape. + ValueError if `R1` or `R2` has an unexpected trace. + """ + R12 = torch.bmm(R1, R2.permute(0, 2, 1)) + return so3_rotation_angle(R12, cos_angle=cos_angle, cos_bound=cos_bound, eps=eps) + + +def so3_rotation_angle( + R: torch.Tensor, + eps: float = 1e-4, + cos_angle: bool = False, + cos_bound: float = 1e-4, +) -> torch.Tensor: + """ + Calculates angles (in radians) of a batch of rotation matrices `R` with + `angle = acos(0.5 * (Trace(R)-1))`. The trace of the + input matrices is checked to be in the valid range `[-1-eps,3+eps]`. + The `eps` argument is a small constant that allows for small errors + caused by limited machine precision. + + Args: + R: Batch of rotation matrices of shape `(minibatch, 3, 3)`. + eps: Tolerance for the valid trace check. + cos_angle: If==True return cosine of the rotation angles rather than + the angle itself. This can avoid the unstable + calculation of `acos`. + cos_bound: Clamps the cosine of the rotation angle to + [-1 + cos_bound, 1 - cos_bound] to avoid non-finite outputs/gradients + of the `acos` call. Note that the non-finite outputs/gradients + are returned when the angle is requested (i.e. `cos_angle==False`) + and the rotation angle is close to 0 or π. + + Returns: + Corresponding rotation angles of shape `(minibatch,)`. + If `cos_angle==True`, returns the cosine of the angles. + + Raises: + ValueError if `R` is of incorrect shape. + ValueError if `R` has an unexpected trace. + """ + + N, dim1, dim2 = R.shape + if dim1 != 3 or dim2 != 3: + raise ValueError("Input has to be a batch of 3x3 Tensors.") + + rot_trace = R[:, 0, 0] + R[:, 1, 1] + R[:, 2, 2] + + if ((rot_trace < -1.0 - eps) + (rot_trace > 3.0 + eps)).any(): + raise ValueError("A matrix has trace outside valid range [-1-eps,3+eps].") + + # phi ... rotation angle + phi_cos = (rot_trace - 1.0) * 0.5 + + if cos_angle: + return phi_cos + else: + if cos_bound > 0.0: + bound = 1.0 - cos_bound + return acos_linear_extrapolation(phi_cos, (-bound, bound)) + else: + return torch.acos(phi_cos) + + +def so3_exp_map(log_rot: torch.Tensor, eps: float = 0.0001) -> torch.Tensor: + """ + Convert a batch of logarithmic representations of rotation matrices `log_rot` + to a batch of 3x3 rotation matrices using Rodrigues formula [1]. + + In the logarithmic representation, each rotation matrix is represented as + a 3-dimensional vector (`log_rot`) who's l2-norm and direction correspond + to the magnitude of the rotation angle and the axis of rotation respectively. + + The conversion has a singularity around `log(R) = 0` + which is handled by clamping controlled with the `eps` argument. + + Args: + log_rot: Batch of vectors of shape `(minibatch, 3)`. + eps: A float constant handling the conversion singularity. + + Returns: + Batch of rotation matrices of shape `(minibatch, 3, 3)`. + + Raises: + ValueError if `log_rot` is of incorrect shape. + + [1] https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula + """ + return _so3_exp_map(log_rot, eps=eps)[0] + + +def so3_exponential_map(log_rot: torch.Tensor, eps: float = 0.0001) -> torch.Tensor: + warnings.warn( + """so3_exponential_map is deprecated, + Use so3_exp_map instead. + so3_exponential_map will be removed in future releases.""", + PendingDeprecationWarning, + ) + + return so3_exp_map(log_rot, eps) + + +def _so3_exp_map( + log_rot: torch.Tensor, eps: float = 0.0001 +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """ + A helper function that computes the so3 exponential map and, + apart from the rotation matrix, also returns intermediate variables + that can be re-used in other functions. + """ + _, dim = log_rot.shape + if dim != 3: + raise ValueError("Input tensor shape has to be Nx3.") + + nrms = (log_rot * log_rot).sum(1) + # phis ... rotation angles + rot_angles = torch.clamp(nrms, eps).sqrt() + skews = hat(log_rot) + skews_square = torch.bmm(skews, skews) + + R = rotation_conversions.axis_angle_to_matrix(log_rot) + + return R, rot_angles, skews, skews_square + + +def so3_log_map( + R: torch.Tensor, eps: float = 0.0001, cos_bound: float = 1e-4 +) -> torch.Tensor: + """ + Convert a batch of 3x3 rotation matrices `R` + to a batch of 3-dimensional matrix logarithms of rotation matrices + The conversion has a singularity around `(R=I)`. + + Args: + R: batch of rotation matrices of shape `(minibatch, 3, 3)`. + eps: (unused, for backward compatibility) + cos_bound: (unused, for backward compatibility) + + Returns: + Batch of logarithms of input rotation matrices + of shape `(minibatch, 3)`. + """ + + N, dim1, dim2 = R.shape + if dim1 != 3 or dim2 != 3: + raise ValueError("Input has to be a batch of 3x3 Tensors.") + + return rotation_conversions.matrix_to_axis_angle(R) + + +def hat_inv(h: torch.Tensor) -> torch.Tensor: + """ + Compute the inverse Hat operator [1] of a batch of 3x3 matrices. + + Args: + h: Batch of skew-symmetric matrices of shape `(minibatch, 3, 3)`. + + Returns: + Batch of 3d vectors of shape `(minibatch, 3, 3)`. + + Raises: + ValueError if `h` is of incorrect shape. + ValueError if `h` not skew-symmetric. + + [1] https://en.wikipedia.org/wiki/Hat_operator + """ + + N, dim1, dim2 = h.shape + if dim1 != 3 or dim2 != 3: + raise ValueError("Input has to be a batch of 3x3 Tensors.") + + ss_diff = torch.abs(h + h.permute(0, 2, 1)).max() + + HAT_INV_SKEW_SYMMETRIC_TOL = 1e-5 + if float(ss_diff) > HAT_INV_SKEW_SYMMETRIC_TOL: + raise ValueError("One of input matrices is not skew-symmetric.") + + x = h[:, 2, 1] + y = h[:, 0, 2] + z = h[:, 1, 0] + + v = torch.stack((x, y, z), dim=1) + + return v + + +def hat(v: torch.Tensor) -> torch.Tensor: + """ + Compute the Hat operator [1] of a batch of 3D vectors. + + Args: + v: Batch of vectors of shape `(minibatch , 3)`. + + Returns: + Batch of skew-symmetric matrices of shape + `(minibatch, 3 , 3)` where each matrix is of the form: + `[ 0 -v_z v_y ] + [ v_z 0 -v_x ] + [ -v_y v_x 0 ]` + + Raises: + ValueError if `v` is of incorrect shape. + + [1] https://en.wikipedia.org/wiki/Hat_operator + """ + + N, dim = v.shape + if dim != 3: + raise ValueError("Input vectors have to be 3-dimensional.") + + h = torch.zeros((N, 3, 3), dtype=v.dtype, device=v.device) + + x, y, z = v.unbind(1) + + h[:, 0, 1] = -z + h[:, 0, 2] = y + h[:, 1, 0] = z + h[:, 1, 2] = -x + h[:, 2, 0] = -y + h[:, 2, 1] = x + + return h diff --git a/int8/vendor/pytorch3d/transforms/transform3d.py b/int8/vendor/pytorch3d/transforms/transform3d.py new file mode 100644 index 0000000000000000000000000000000000000000..06e1b7d268d9b3a9952a2894feef4403b23625f7 --- /dev/null +++ b/int8/vendor/pytorch3d/transforms/transform3d.py @@ -0,0 +1,909 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-unsafe + +import math +import os +import warnings +from typing import List, Optional, Union + +import torch + +from ..common.datatypes import Device, get_device, make_device +from ..common.workaround import _safe_det_3x3 +from .rotation_conversions import _axis_angle_rotation +from .se3 import se3_log_map + + +class Transform3d: + """ + A Transform3d object encapsulates a batch of N 3D transformations, and knows + how to transform points and normal vectors. Suppose that t is a Transform3d; + then we can do the following: + + .. code-block:: python + + N = len(t) + points = torch.randn(N, P, 3) + normals = torch.randn(N, P, 3) + points_transformed = t.transform_points(points) # => (N, P, 3) + normals_transformed = t.transform_normals(normals) # => (N, P, 3) + + + BROADCASTING + Transform3d objects supports broadcasting. Suppose that t1 and tN are + Transform3d objects with len(t1) == 1 and len(tN) == N respectively. Then we + can broadcast transforms like this: + + .. code-block:: python + + t1.transform_points(torch.randn(P, 3)) # => (P, 3) + t1.transform_points(torch.randn(1, P, 3)) # => (1, P, 3) + t1.transform_points(torch.randn(M, P, 3)) # => (M, P, 3) + tN.transform_points(torch.randn(P, 3)) # => (N, P, 3) + tN.transform_points(torch.randn(1, P, 3)) # => (N, P, 3) + + + COMBINING TRANSFORMS + Transform3d objects can be combined in two ways: composing and stacking. + Composing is function composition. Given Transform3d objects t1, t2, t3, + the following all compute the same thing: + + .. code-block:: python + + y1 = t3.transform_points(t2.transform_points(t1.transform_points(x))) + y2 = t1.compose(t2).compose(t3).transform_points(x) + y3 = t1.compose(t2, t3).transform_points(x) + + + Composing transforms should broadcast. + + .. code-block:: python + + if len(t1) == 1 and len(t2) == N, then len(t1.compose(t2)) == N. + + We can also stack a sequence of Transform3d objects, which represents + composition along the batch dimension; then the following should compute the + same thing. + + .. code-block:: python + + N, M = len(tN), len(tM) + xN = torch.randn(N, P, 3) + xM = torch.randn(M, P, 3) + y1 = torch.cat([tN.transform_points(xN), tM.transform_points(xM)], dim=0) + y2 = tN.stack(tM).transform_points(torch.cat([xN, xM], dim=0)) + + BUILDING TRANSFORMS + We provide convenience methods for easily building Transform3d objects + as compositions of basic transforms. + + .. code-block:: python + + # Scale by 0.5, then translate by (1, 2, 3) + t1 = Transform3d().scale(0.5).translate(1, 2, 3) + + # Scale each axis by a different amount, then translate, then scale + t2 = Transform3d().scale(1, 3, 3).translate(2, 3, 1).scale(2.0) + + t3 = t1.compose(t2) + tN = t1.stack(t3, t3) + + + BACKPROP THROUGH TRANSFORMS + When building transforms, we can also parameterize them by Torch tensors; + in this case we can backprop through the construction and application of + Transform objects, so they could be learned via gradient descent or + predicted by a neural network. + + .. code-block:: python + + s1_params = torch.randn(N, requires_grad=True) + t_params = torch.randn(N, 3, requires_grad=True) + s2_params = torch.randn(N, 3, requires_grad=True) + + t = Transform3d().scale(s1_params).translate(t_params).scale(s2_params) + x = torch.randn(N, 3) + y = t.transform_points(x) + loss = compute_loss(y) + loss.backward() + + with torch.no_grad(): + s1_params -= lr * s1_params.grad + t_params -= lr * t_params.grad + s2_params -= lr * s2_params.grad + + CONVENTIONS + We adopt a right-hand coordinate system, meaning that rotation about an axis + with a positive angle results in a counter clockwise rotation. + + This class assumes that transformations are applied on inputs which + are row vectors. The internal representation of the Nx4x4 transformation + matrix is of the form: + + .. code-block:: python + + M = [ + [Rxx, Ryx, Rzx, 0], + [Rxy, Ryy, Rzy, 0], + [Rxz, Ryz, Rzz, 0], + [Tx, Ty, Tz, 1], + ] + + To apply the transformation to points, which are row vectors, the latter are + converted to homogeneous (4D) coordinates and right-multiplied by the M matrix: + + .. code-block:: python + + points = [[0, 1, 2]] # (1 x 3) xyz coordinates of a point + [transformed_points, 1] ∝ [points, 1] @ M + + """ + + def __init__( + self, + dtype: torch.dtype = torch.float32, + device: Device = "cpu", + matrix: Optional[torch.Tensor] = None, + ) -> None: + """ + Args: + dtype: The data type of the transformation matrix. + to be used if `matrix = None`. + device: The device for storing the implemented transformation. + If `matrix != None`, uses the device of input `matrix`. + matrix: A tensor of shape (4, 4) or of shape (minibatch, 4, 4) + representing the 4x4 3D transformation matrix. + If `None`, initializes with identity using + the specified `device` and `dtype`. + """ + + if matrix is None: + self._matrix = torch.eye(4, dtype=dtype, device=device).view(1, 4, 4) + else: + if matrix.ndim not in (2, 3): + raise ValueError('"matrix" has to be a 2- or a 3-dimensional tensor.') + if matrix.shape[-2] != 4 or matrix.shape[-1] != 4: + raise ValueError( + '"matrix" has to be a tensor of shape (minibatch, 4, 4) or (4, 4).' + ) + # set dtype and device from matrix + dtype = matrix.dtype + device = matrix.device + self._matrix = matrix.view(-1, 4, 4) + + self._transforms = [] # store transforms to compose + self._lu = None + self.device = make_device(device) + self.dtype = dtype + + def __len__(self) -> int: + return self.get_matrix().shape[0] + + def __getitem__( + self, index: Union[int, List[int], slice, torch.BoolTensor, torch.LongTensor] + ) -> "Transform3d": + """ + Args: + index: Specifying the index of the transform to retrieve. + Can be an int, slice, list of ints, boolean, long tensor. + Supports negative indices. + + Returns: + Transform3d object with selected transforms. The tensors are not cloned. + """ + if isinstance(index, int): + index = [index] + return self.__class__(matrix=self.get_matrix()[index]) + + def compose(self, *others: "Transform3d") -> "Transform3d": + """ + Return a new Transform3d representing the composition of self with the + given other transforms, which will be stored as an internal list. + + Args: + *others: Any number of Transform3d objects + + Returns: + A new Transform3d with the stored transforms + """ + out = Transform3d(dtype=self.dtype, device=self.device) + out._matrix = self._matrix.clone() + for other in others: + if not isinstance(other, Transform3d): + msg = "Only possible to compose Transform3d objects; got %s" + raise ValueError(msg % type(other)) + out._transforms = self._transforms + list(others) + return out + + def get_matrix(self) -> torch.Tensor: + """ + Returns a 4×4 matrix corresponding to each transform in the batch. + + If the transform was composed from others, the matrix for the composite + transform will be returned. + For example, if self.transforms contains transforms t1, t2, and t3, and + given a set of points x, the following should be true: + + .. code-block:: python + + y1 = t1.compose(t2, t3).transform(x) + y2 = t3.transform(t2.transform(t1.transform(x))) + y1.get_matrix() == y2.get_matrix() + + Where necessary, those transforms are broadcast against each other. + + Returns: + A (N, 4, 4) batch of transformation matrices representing + the stored transforms. See the class documentation for the conventions. + """ + composed_matrix = self._matrix.clone() + if len(self._transforms) > 0: + for other in self._transforms: + other_matrix = other.get_matrix() + composed_matrix = _broadcast_bmm(composed_matrix, other_matrix) + return composed_matrix + + def get_se3_log(self, eps: float = 1e-4, cos_bound: float = 1e-4) -> torch.Tensor: + """ + Returns a 6D SE(3) log vector corresponding to each transform in the batch. + + In the SE(3) logarithmic representation SE(3) matrices are + represented as 6-dimensional vectors `[log_translation | log_rotation]`, + i.e. a concatenation of two 3D vectors `log_translation` and `log_rotation`. + + The conversion from the 4x4 SE(3) matrix `transform` to the + 6D representation `log_transform = [log_translation | log_rotation]` + is done as follows:: + + log_transform = log(transform.get_matrix()) + log_translation = log_transform[3, :3] + log_rotation = inv_hat(log_transform[:3, :3]) + + where `log` is the matrix logarithm + and `inv_hat` is the inverse of the Hat operator [2]. + + See the docstring for `se3.se3_log_map` and [1], Sec 9.4.2. for more + detailed description. + + Args: + eps: A threshold for clipping the squared norm of the rotation logarithm + to avoid division by zero in the singular case. + cos_bound: Clamps the cosine of the rotation angle to + [-1 + cos_bound, 3 - cos_bound] to avoid non-finite outputs. + The non-finite outputs can be caused by passing small rotation angles + to the `acos` function in `so3_rotation_angle` of `so3_log_map`. + + Returns: + A (N, 6) tensor, rows of which represent the individual transforms + stored in the object as SE(3) logarithms. + + Raises: + ValueError if the stored transform is not Euclidean (e.g. R is not a rotation + matrix or the last column has non-zeros in the first three places). + + [1] https://jinyongjeong.github.io/Download/SE3/jlblanco2010geometry3d_techrep.pdf + [2] https://en.wikipedia.org/wiki/Hat_operator + """ + return se3_log_map(self.get_matrix(), eps, cos_bound) + + def _get_matrix_inverse(self) -> torch.Tensor: + """ + Return the inverse of self._matrix. + """ + return torch.inverse(self._matrix) + + def inverse(self, invert_composed: bool = False) -> "Transform3d": + """ + Returns a new Transform3d object that represents an inverse of the + current transformation. + + Args: + invert_composed: + - True: First compose the list of stored transformations + and then apply inverse to the result. This is + potentially slower for classes of transformations + with inverses that can be computed efficiently + (e.g. rotations and translations). + - False: Invert the individual stored transformations + independently without composing them. + + Returns: + A new Transform3d object containing the inverse of the original + transformation. + """ + + tinv = Transform3d(dtype=self.dtype, device=self.device) + + if invert_composed: + # first compose then invert + tinv._matrix = torch.inverse(self.get_matrix()) + else: + # self._get_matrix_inverse() implements efficient inverse + # of self._matrix + i_matrix = self._get_matrix_inverse() + + # 2 cases: + if len(self._transforms) > 0: + # a) Either we have a non-empty list of transforms: + # Here we take self._matrix and append its inverse at the + # end of the reverted _transforms list. After composing + # the transformations with get_matrix(), this correctly + # right-multiplies by the inverse of self._matrix + # at the end of the composition. + tinv._transforms = [t.inverse() for t in reversed(self._transforms)] + last = Transform3d(dtype=self.dtype, device=self.device) + last._matrix = i_matrix + tinv._transforms.append(last) + else: + # b) Or there are no stored transformations + # we just set inverted matrix + tinv._matrix = i_matrix + + return tinv + + def stack(self, *others: "Transform3d") -> "Transform3d": + """ + Return a new batched Transform3d representing the batch elements from + self and all the given other transforms all batched together. + + Args: + *others: Any number of Transform3d objects + + Returns: + A new Transform3d. + """ + transforms = [self] + list(others) + matrix = torch.cat([t.get_matrix() for t in transforms], dim=0) + out = Transform3d(dtype=self.dtype, device=self.device) + out._matrix = matrix + return out + + def transform_points(self, points, eps: Optional[float] = None) -> torch.Tensor: + """ + Use this transform to transform a set of 3D points. Assumes row major + ordering of the input points. + + Args: + points: Tensor of shape (P, 3) or (N, P, 3) + eps: If eps!=None, the argument is used to clamp the + last coordinate before performing the final division. + The clamping corresponds to: + last_coord := (last_coord.sign() + (last_coord==0)) * + torch.clamp(last_coord.abs(), eps), + i.e. the last coordinates that are exactly 0 will + be clamped to +eps. + + Returns: + points_out: points of shape (N, P, 3) or (P, 3) depending + on the dimensions of the transform + """ + points_batch = points.clone() + if points_batch.dim() == 2: + points_batch = points_batch[None] # (P, 3) -> (1, P, 3) + if points_batch.dim() != 3: + msg = "Expected points to have dim = 2 or dim = 3: got shape %r" + raise ValueError(msg % repr(points.shape)) + + N, P, _3 = points_batch.shape + ones = torch.ones(N, P, 1, dtype=points.dtype, device=points.device) + points_batch = torch.cat([points_batch, ones], dim=2) + + composed_matrix = self.get_matrix() + points_out = _broadcast_bmm(points_batch, composed_matrix) + denom = points_out[..., 3:] # denominator + if eps is not None: + denom_sign = denom.sign() + (denom == 0.0).type_as(denom) + denom = denom_sign * torch.clamp(denom.abs(), eps) + points_out = points_out[..., :3] / denom + + # When transform is (1, 4, 4) and points is (P, 3) return + # points_out of shape (P, 3) + if points_out.shape[0] == 1 and points.dim() == 2: + points_out = points_out.reshape(points.shape) + + return points_out + + def transform_normals(self, normals) -> torch.Tensor: + """ + Use this transform to transform a set of normal vectors. + + Args: + normals: Tensor of shape (P, 3) or (N, P, 3) + + Returns: + normals_out: Tensor of shape (P, 3) or (N, P, 3) depending + on the dimensions of the transform + """ + if normals.dim() not in [2, 3]: + msg = "Expected normals to have dim = 2 or dim = 3: got shape %r" + raise ValueError(msg % (normals.shape,)) + composed_matrix = self.get_matrix() + + # TODO: inverse is bad! Solve a linear system instead + mat = composed_matrix[:, :3, :3] + normals_out = _broadcast_bmm(normals, mat.transpose(1, 2).inverse()) + + # This doesn't pass unit tests. TODO investigate further + # if self._lu is None: + # self._lu = self._matrix[:, :3, :3].transpose(1, 2).lu() + # normals_out = normals.lu_solve(*self._lu) + + # When transform is (1, 4, 4) and normals is (P, 3) return + # normals_out of shape (P, 3) + if normals_out.shape[0] == 1 and normals.dim() == 2: + normals_out = normals_out.reshape(normals.shape) + + return normals_out + + def translate(self, *args, **kwargs) -> "Transform3d": + return self.compose( + Translate(*args, device=self.device, dtype=self.dtype, **kwargs) + ) + + def scale(self, *args, **kwargs) -> "Transform3d": + return self.compose( + Scale(*args, device=self.device, dtype=self.dtype, **kwargs) + ) + + def rotate(self, *args, **kwargs) -> "Transform3d": + return self.compose( + Rotate(*args, device=self.device, dtype=self.dtype, **kwargs) + ) + + def rotate_axis_angle(self, *args, **kwargs) -> "Transform3d": + return self.compose( + RotateAxisAngle(*args, device=self.device, dtype=self.dtype, **kwargs) + ) + + def clone(self) -> "Transform3d": + """ + Deep copy of Transforms object. All internal tensors are cloned + individually. + + Returns: + new Transforms object. + """ + other = Transform3d(dtype=self.dtype, device=self.device) + if self._lu is not None: + other._lu = [elem.clone() for elem in self._lu] + other._matrix = self._matrix.clone() + other._transforms = [t.clone() for t in self._transforms] + return other + + def to( + self, + device: Device, + copy: bool = False, + dtype: Optional[torch.dtype] = None, + ) -> "Transform3d": + """ + Match functionality of torch.Tensor.to() + If copy = True or the self Tensor is on a different device, the + returned tensor is a copy of self with the desired torch.device. + If copy = False and the self Tensor already has the correct torch.device, + then self is returned. + + Args: + device: Device (as str or torch.device) for the new tensor. + copy: Boolean indicator whether or not to clone self. Default False. + dtype: If not None, casts the internal tensor variables + to a given torch.dtype. + + Returns: + Transform3d object. + """ + device_ = make_device(device) + dtype_ = self.dtype if dtype is None else dtype + skip_to = self.device == device_ and self.dtype == dtype_ + + if not copy and skip_to: + return self + + other = self.clone() + + if skip_to: + return other + + other.device = device_ + other.dtype = dtype_ + other._matrix = other._matrix.to(device=device_, dtype=dtype_) + other._transforms = [ + t.to(device_, copy=copy, dtype=dtype_) for t in other._transforms + ] + return other + + def cpu(self) -> "Transform3d": + return self.to("cpu") + + def cuda(self) -> "Transform3d": + return self.to("cuda") + + +class Translate(Transform3d): + def __init__( + self, + x, + y=None, + z=None, + dtype: torch.dtype = torch.float32, + device: Optional[Device] = None, + ) -> None: + """ + Create a new Transform3d representing 3D translations. + + Option I: Translate(xyz, dtype=torch.float32, device='cpu') + xyz should be a tensor of shape (N, 3) + + Option II: Translate(x, y, z, dtype=torch.float32, device='cpu') + Here x, y, and z will be broadcast against each other and + concatenated to form the translation. Each can be: + - A python scalar + - A torch scalar + - A 1D torch tensor + """ + xyz = _handle_input(x, y, z, dtype, device, "Translate") + super().__init__(device=xyz.device, dtype=dtype) + N = xyz.shape[0] + + mat = torch.eye(4, dtype=dtype, device=self.device) + mat = mat.view(1, 4, 4).repeat(N, 1, 1) + mat[:, 3, :3] = xyz + self._matrix = mat + + def _get_matrix_inverse(self) -> torch.Tensor: + """ + Return the inverse of self._matrix. + """ + inv_mask = self._matrix.new_ones([1, 4, 4]) + inv_mask[0, 3, :3] = -1.0 + i_matrix = self._matrix * inv_mask + return i_matrix + + def __getitem__( + self, index: Union[int, List[int], slice, torch.BoolTensor, torch.LongTensor] + ) -> "Transform3d": + """ + Args: + index: Specifying the index of the transform to retrieve. + Can be an int, slice, list of ints, boolean, long tensor. + Supports negative indices. + + Returns: + Transform3d object with selected transforms. The tensors are not cloned. + """ + if isinstance(index, int): + index = [index] + return self.__class__(self.get_matrix()[index, 3, :3]) + + +class Scale(Transform3d): + def __init__( + self, + x, + y=None, + z=None, + dtype: torch.dtype = torch.float32, + device: Optional[Device] = None, + ) -> None: + """ + A Transform3d representing a scaling operation, with different scale + factors along each coordinate axis. + + Option I: Scale(s, dtype=torch.float32, device='cpu') + s can be one of + - Python scalar or torch scalar: Single uniform scale + - 1D torch tensor of shape (N,): A batch of uniform scale + - 2D torch tensor of shape (N, 3): Scale differently along each axis + + Option II: Scale(x, y, z, dtype=torch.float32, device='cpu') + Each of x, y, and z can be one of + - python scalar + - torch scalar + - 1D torch tensor + """ + xyz = _handle_input(x, y, z, dtype, device, "scale", allow_singleton=True) + super().__init__(device=xyz.device, dtype=dtype) + N = xyz.shape[0] + + # TODO: Can we do this all in one go somehow? + mat = torch.eye(4, dtype=dtype, device=self.device) + mat = mat.view(1, 4, 4).repeat(N, 1, 1) + mat[:, 0, 0] = xyz[:, 0] + mat[:, 1, 1] = xyz[:, 1] + mat[:, 2, 2] = xyz[:, 2] + self._matrix = mat + + def _get_matrix_inverse(self) -> torch.Tensor: + """ + Return the inverse of self._matrix. + """ + xyz = torch.stack([self._matrix[:, i, i] for i in range(4)], dim=1) + # pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`. + ixyz = 1.0 / xyz + # pyre-fixme[6]: For 1st param expected `Tensor` but got `float`. + imat = torch.diag_embed(ixyz, dim1=1, dim2=2) + return imat + + def __getitem__( + self, index: Union[int, List[int], slice, torch.BoolTensor, torch.LongTensor] + ) -> "Transform3d": + """ + Args: + index: Specifying the index of the transform to retrieve. + Can be an int, slice, list of ints, boolean, long tensor. + Supports negative indices. + + Returns: + Transform3d object with selected transforms. The tensors are not cloned. + """ + if isinstance(index, int): + index = [index] + mat = self.get_matrix()[index] + x = mat[:, 0, 0] + y = mat[:, 1, 1] + z = mat[:, 2, 2] + return self.__class__(x, y, z) + + +class Rotate(Transform3d): + def __init__( + self, + R: torch.Tensor, + dtype: torch.dtype = torch.float32, + device: Optional[Device] = None, + orthogonal_tol: float = 1e-5, + ) -> None: + """ + Create a new Transform3d representing 3D rotation using a rotation + matrix as the input. + + Args: + R: a tensor of shape (3, 3) or (N, 3, 3) + orthogonal_tol: tolerance for the test of the orthogonality of R + + """ + device_ = get_device(R, device) + super().__init__(device=device_, dtype=dtype) + if R.dim() == 2: + R = R[None] + if R.shape[-2:] != (3, 3): + msg = "R must have shape (3, 3) or (N, 3, 3); got %s" + raise ValueError(msg % repr(R.shape)) + R = R.to(device=device_, dtype=dtype) + if os.environ.get("PYTORCH3D_CHECK_ROTATION_MATRICES", "0") == "1": + # Note: aten::all_close in the check is computationally slow, so we + # only run the check when PYTORCH3D_CHECK_ROTATION_MATRICES is on. + _check_valid_rotation_matrix(R, tol=orthogonal_tol) + N = R.shape[0] + mat = torch.eye(4, dtype=dtype, device=device_) + mat = mat.view(1, 4, 4).repeat(N, 1, 1) + mat[:, :3, :3] = R + self._matrix = mat + + def _get_matrix_inverse(self) -> torch.Tensor: + """ + Return the inverse of self._matrix. + """ + return self._matrix.permute(0, 2, 1).contiguous() + + def __getitem__( + self, index: Union[int, List[int], slice, torch.BoolTensor, torch.LongTensor] + ) -> "Transform3d": + """ + Args: + index: Specifying the index of the transform to retrieve. + Can be an int, slice, list of ints, boolean, long tensor. + Supports negative indices. + + Returns: + Transform3d object with selected transforms. The tensors are not cloned. + """ + if isinstance(index, int): + index = [index] + return self.__class__(self.get_matrix()[index, :3, :3]) + + +class RotateAxisAngle(Rotate): + def __init__( + self, + angle, + axis: str = "X", + degrees: bool = True, + dtype: torch.dtype = torch.float32, + device: Optional[Device] = None, + ) -> None: + """ + Create a new Transform3d representing 3D rotation about an axis + by an angle. + + Assuming a right-hand coordinate system, positive rotation angles result + in a counter clockwise rotation. + + Args: + angle: + - A torch tensor of shape (N,) + - A python scalar + - A torch scalar + axis: + string: one of ["X", "Y", "Z"] indicating the axis about which + to rotate. + NOTE: All batch elements are rotated about the same axis. + """ + axis = axis.upper() + if axis not in ["X", "Y", "Z"]: + msg = "Expected axis to be one of ['X', 'Y', 'Z']; got %s" + raise ValueError(msg % axis) + angle = _handle_angle_input(angle, dtype, device, "RotateAxisAngle") + angle = (angle / 180.0 * math.pi) if degrees else angle + # We assume the points on which this transformation will be applied + # are row vectors. The rotation matrix returned from _axis_angle_rotation + # is for transforming column vectors. Therefore we transpose this matrix. + # R will always be of shape (N, 3, 3) + R = _axis_angle_rotation(axis, angle).transpose(1, 2) + super().__init__(device=angle.device, R=R, dtype=dtype) + + +def _handle_coord(c, dtype: torch.dtype, device: torch.device) -> torch.Tensor: + """ + Helper function for _handle_input. + + Args: + c: Python scalar, torch scalar, or 1D torch tensor + + Returns: + c_vec: 1D torch tensor + """ + if not torch.is_tensor(c): + c = torch.tensor(c, dtype=dtype, device=device) + if c.dim() == 0: + c = c.view(1) + if c.device != device or c.dtype != dtype: + c = c.to(device=device, dtype=dtype) + return c + + +def _handle_input( + x, + y, + z, + dtype: torch.dtype, + device: Optional[Device], + name: str, + allow_singleton: bool = False, +) -> torch.Tensor: + """ + Helper function to handle parsing logic for building transforms. The output + is always a tensor of shape (N, 3), but there are several types of allowed + input. + + Case I: Single Matrix + In this case x is a tensor of shape (N, 3), and y and z are None. Here just + return x. + + Case II: Vectors and Scalars + In this case each of x, y, and z can be one of the following + - Python scalar + - Torch scalar + - Torch tensor of shape (N, 1) or (1, 1) + In this case x, y and z are broadcast to tensors of shape (N, 1) + and concatenated to a tensor of shape (N, 3) + + Case III: Singleton (only if allow_singleton=True) + In this case y and z are None, and x can be one of the following: + - Python scalar + - Torch scalar + - Torch tensor of shape (N, 1) or (1, 1) + Here x will be duplicated 3 times, and we return a tensor of shape (N, 3) + + Returns: + xyz: Tensor of shape (N, 3) + """ + device_ = get_device(x, device) + # If x is actually a tensor of shape (N, 3) then just return it + if torch.is_tensor(x) and x.dim() == 2: + if x.shape[1] != 3: + msg = "Expected tensor of shape (N, 3); got %r (in %s)" + raise ValueError(msg % (x.shape, name)) + if y is not None or z is not None: + msg = "Expected y and z to be None (in %s)" % name + raise ValueError(msg) + return x.to(device=device_, dtype=dtype) + + if allow_singleton and y is None and z is None: + y = x + z = x + + # Convert all to 1D tensors + xyz = [_handle_coord(c, dtype, device_) for c in [x, y, z]] + + # Broadcast and concatenate + sizes = [c.shape[0] for c in xyz] + N = max(sizes) + for c in xyz: + if c.shape[0] != 1 and c.shape[0] != N: + msg = "Got non-broadcastable sizes %r (in %s)" % (sizes, name) + raise ValueError(msg) + xyz = [c.expand(N) for c in xyz] + xyz = torch.stack(xyz, dim=1) + return xyz + + +def _handle_angle_input( + x, dtype: torch.dtype, device: Optional[Device], name: str +) -> torch.Tensor: + """ + Helper function for building a rotation function using angles. + The output is always of shape (N,). + + The input can be one of: + - Torch tensor of shape (N,) + - Python scalar + - Torch scalar + """ + device_ = get_device(x, device) + if torch.is_tensor(x) and x.dim() > 1: + msg = "Expected tensor of shape (N,); got %r (in %s)" + raise ValueError(msg % (x.shape, name)) + else: + return _handle_coord(x, dtype, device_) + + +def _broadcast_bmm(a, b) -> torch.Tensor: + """ + Batch multiply two matrices and broadcast if necessary. + + Args: + a: torch tensor of shape (P, K) or (M, P, K) + b: torch tensor of shape (N, K, K) + + Returns: + a and b broadcast multiplied. The output batch dimension is max(N, M). + + To broadcast transforms across a batch dimension if M != N then + expect that either M = 1 or N = 1. The tensor with batch dimension 1 is + expanded to have shape N or M. + """ + if a.dim() == 2: + a = a[None] + if len(a) != len(b): + if not ((len(a) == 1) or (len(b) == 1)): + msg = "Expected batch dim for bmm to be equal or 1; got %r, %r" + raise ValueError(msg % (a.shape, b.shape)) + if len(a) == 1: + a = a.expand(len(b), -1, -1) + if len(b) == 1: + b = b.expand(len(a), -1, -1) + return a.bmm(b) + + +@torch.no_grad() +def _check_valid_rotation_matrix(R, tol: float = 1e-7) -> None: + """ + Determine if R is a valid rotation matrix by checking it satisfies the + following conditions: + + ``RR^T = I and det(R) = 1`` + + Args: + R: an (N, 3, 3) matrix + + Returns: + None + + Emits a warning if R is an invalid rotation matrix. + """ + N = R.shape[0] + eye = torch.eye(3, dtype=R.dtype, device=R.device) + eye = eye.view(1, 3, 3).expand(N, -1, -1) + orthogonal = torch.allclose(R.bmm(R.transpose(1, 2)), eye, atol=tol) + det_R = _safe_det_3x3(R) + no_distortion = torch.allclose(det_R, torch.ones_like(det_R)) + if not (orthogonal and no_distortion): + msg = "R is not a valid rotation matrix" + warnings.warn(msg) + return diff --git a/int8/vendor/sam3d_objects/LICENSE-SAM.txt b/int8/vendor/sam3d_objects/LICENSE-SAM.txt new file mode 100644 index 0000000000000000000000000000000000000000..dbf98fa028fb966e8691460b152ccc97ed72b114 --- /dev/null +++ b/int8/vendor/sam3d_objects/LICENSE-SAM.txt @@ -0,0 +1,52 @@ +SAM License +Last Updated: November 19, 2025 + +“Agreement” means the terms and conditions for use, reproduction, distribution and modification of the SAM Materials set forth herein. + +“SAM Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement. + +“Documentation” means the specifications, manuals and documentation accompanying +SAM Materials distributed by Meta. + +“Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf. + +“Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland). + +“Sanctions” means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom. + +“Trade Controls” means any of the following: Sanctions and applicable export and import controls. + +By using or distributing any portion or element of the SAM Materials, you agree to be bound by this Agreement. + +1. License Rights and Redistribution. + +a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the SAM Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the SAM Materials. + +i. Grant of Patent License. Subject to the terms and conditions of this License, you are granted a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by Meta that are necessarily infringed alone or by combination of their contribution(s) with the SAM 3 Materials. If you institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM 3 Materials incorporated within the work constitutes direct or contributory patent infringement, then any patent licenses granted to you under this License for that work shall terminate as of the date such litigation is filed. + +b. Redistribution and Use. + +i. Distribution of SAM Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the SAM Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such SAM Materials. + +ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with SAM Materials, you must acknowledge the use of SAM Materials in your publication. + +iii. Your use of the SAM Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws. +iv. Your use of the SAM Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the SAM Materials. +v. You are not the target of Trade Controls and your use of SAM Materials must comply with Trade Controls. You agree not to use, or permit others to use, SAM Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons. +2. User Support. Your use of the SAM Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the SAM Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind. + +3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE SAM MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE SAM MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE SAM MATERIALS AND ANY OUTPUT AND RESULTS. + +4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING. + +5. Intellectual Property. + +a. Subject to Meta’s ownership of SAM Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the SAM Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications. + +b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the SAM Materials. + +6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the SAM Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the SAM Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement. + +7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement. + +8. Modifications and Amendments. Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the SAM Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta. diff --git a/int8/vendor/sam3d_objects/__init__.py b/int8/vendor/sam3d_objects/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/int8/vendor/sam3d_objects/data/__init__.py b/int8/vendor/sam3d_objects/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/int8/vendor/sam3d_objects/data/dataset/__init__.py b/int8/vendor/sam3d_objects/data/dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/int8/vendor/sam3d_objects/data/dataset/tdfy/__init__.py b/int8/vendor/sam3d_objects/data/dataset/tdfy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/int8/vendor/sam3d_objects/data/dataset/tdfy/img_and_mask_transforms.py b/int8/vendor/sam3d_objects/data/dataset/tdfy/img_and_mask_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..19fd3b6577b821519d058fd361e97a0ef24c1056 --- /dev/null +++ b/int8/vendor/sam3d_objects/data/dataset/tdfy/img_and_mask_transforms.py @@ -0,0 +1,985 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +from collections import namedtuple +import random +from typing import Optional, Dict + +import numpy as np +import torchvision.transforms.functional +from sam3d_objects.data.dataset.tdfy.img_processing import pad_to_square_centered +from sam3d_objects.model.backbone.dit.embedder.point_remapper import PointRemapper +from typing import Optional, Dict +import logging; logger = logging.getLogger(__name__) +import torch +import torch.nn.functional as F +import torchvision +import torchvision.transforms as tv_transforms +import torchvision.transforms.functional +import torchvision.transforms.functional as TF + +from sam3d_objects.data.dataset.tdfy.img_processing import pad_to_square_centered + + +def UNNORMALIZE(mean, std): + mean = torch.tensor(mean).reshape((3, 1, 1)) + std = torch.tensor(std).reshape((3, 1, 1)) + + def unnormalize_img(img): + assert img.ndim == 3 and img.shape[0] == 3 + + return img * std.to(img.device) + mean.to(img.device) + + return unnormalize_img + + +IMAGENET_MEAN = (0.485, 0.456, 0.406) +IMAGENET_STD = (0.229, 0.224, 0.225) + + +IMAGENET_NORMALIZATION = tv_transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD) +IMAGENET_UNNORMALIZATION = UNNORMALIZE(IMAGENET_MEAN, IMAGENET_STD) + + +class BoundingBoxError(Exception): + pass + + +def check_bounding_box(bbox_w, bbox_h): + if bbox_w < 2 or bbox_h < 2: + raise BoundingBoxError("Bounding box dimensions must be at least 2x2.") + + +class RGBAImageProcessor: + def __init__( + self, + resize_and_make_square_kwargs: Optional[Dict] = None, + object_crop_kwargs: Optional[Dict] = None, + remove_background: bool = False, + imagenet_normalization: bool = False, + ): + self.remove_background = remove_background + self.resize_and_pad_kwargs = resize_and_make_square_kwargs + self.object_crop_kwargs = object_crop_kwargs + self.imagenet_normalization = imagenet_normalization + if resize_and_make_square_kwargs is not None: + self.transforms = resize_and_make_square(**resize_and_make_square_kwargs) + + def __call__( + self, image: torch.Tensor, mask: Optional[torch.Tensor] = None + ) -> tuple[torch.Tensor, torch.Tensor]: + if mask is None: + assert ( + image.shape[0] == 4 + ), f"Requires 4 channels (RGB + alpha), got {image.shape[0]=}" + image, mask = split_rgba(image) + else: + assert ( + image.shape[0] == 3 + ), f"Requires 3 channels (RGB), got {image.shape[0]=}" + assert mask.dim() == 2, f"Requires 2D mask, got {mask.dim()=}" + + if not self.object_crop_kwargs in [None, False]: + image, mask = crop_around_mask_with_padding( + image, mask, **self.object_crop_kwargs + ) + + if self.remove_background: + image, mask = rembg(image, mask) + + image = self.transforms["img_transform"](image) + mask = self.transforms["mask_transform"](mask.unsqueeze(0)) + + if self.imagenet_normalization: + image = IMAGENET_NORMALIZATION(image) + return image, mask + + +def load_rgb(fpath: str) -> torch.Tensor: + """ + Load a RGB(A) image from a file path. + """ + image = plt.imread(fpath) # Why use matplotlib? + if image.dtype == "uint8": + image = image / 255 + image = image.astype(np.float32) + image = torch.from_numpy(image) + image = image.permute(2, 0, 1).contiguous() + return image + + +def concat_rgba( + rgb_image: torch.Tensor, + mask: torch.Tensor, +) -> torch.Tensor: + """ + Create a 4-channel RGBA image from a 3-channel RGB image and a mask. + """ + assert rgb_image.dim() == 3, f"{rgb_image.shape=}" + assert mask.dim() == 2, f"{mask.shape=}" + assert rgb_image.shape[0] == 3, f"{rgb_image.shape[0]=}" + assert rgb_image.shape[1:] == mask.shape, f"{rgb_image.shape[1:]=} != {mask.shape=}" + return torch.cat((rgb_image, mask[None, ...]), dim=0) + + +def split_rgba(rgba_image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """ + Split a 4-channel RGBA image into a 3-channel RGB image and a 1-channel mask. + + Args: + rgba_image: A 4-channel RGBA image. + + Returns: + A tuple of (rgb_image, mask). + """ + assert rgba_image.dim() == 3, f"{rgba_image.shape=}" + assert rgba_image.shape[0] == 4, f"{rgba_image.shape[0]=}" + return rgba_image[:3], rgba_image[3] + + +def get_mask( + rgb_image: torch.Tensor, + depth_image: torch.Tensor, + mask_source: str, +) -> torch.Tensor: + """ + Extract a mask from either the alpha channel of an RGB image or a depth image. + + Args: + rgb_image: Tensor of shape (B, C, H, W) or (C, H, W) where C >= 4 if using alpha channel + depth_image: Tensor of shape (B, 1, H, W) or (1, H, W) containing depth information + mask_source: Source of the mask, either "ALPHA_CHANNEL" or "DEPTH" + + Returns: + mask: Tensor of shape (B, 1, H, W) or (1, H, W) containing the extracted mask + """ + # Handle unbatched inputs (add batch dimension if needed) + is_batched = len(rgb_image.shape) == 4 + + if not is_batched: + rgb_image = rgb_image.unsqueeze(0) + if depth_image is not None: + depth_image = depth_image.unsqueeze(0) + + if mask_source == "ALPHA_CHANNEL": + if rgb_image.shape[1] != 4: + logger.warning(f"No ALPHA CHANNEL for the image, cannot read mask.") + mask = None + else: + mask = rgb_image[:, 3:4, :, :] + elif mask_source == "DEPTH": + mask = depth_image + else: + raise ValueError(f"Invalid mask source: {mask_source}") + + # Remove batch dimension if input was unbatched + if not is_batched: + mask = mask.squeeze(0) + + return mask + + +def rembg(image, mask, pointmap=None): + """ + Remove the background from an image using a mask. + For pointmaps, sets background regions to NaN. + + This function follows the standard transform pattern: + - If called with (image, mask), returns (image, mask) + - If called with (image, mask, pointmap), returns (image, mask, pointmap) + """ + masked_image = image * mask + + if pointmap is not None: + masked_pointmap = torch.where(mask > 0, pointmap, torch.nan) + return masked_image, mask, masked_pointmap + + return masked_image, mask + + +def resize_and_make_square( + img_size: int, + make_square: bool | str = False, +): + """ + Create image and mask transforms based on configuration. + + Returns: + dict: {"img_transform": img_transform, "mask_transform": mask_transform} + """ + if isinstance(make_square, str): + make_square = make_square.lower() + assert make_square in ["pad", "crop", False] + pre_resize_transform = tv_transforms.Lambda(lambda x: x) + post_resize_transform = tv_transforms.Lambda(lambda x: x) + if make_square == "pad": + pre_resize_transform = pad_to_square_centered + elif make_square == "crop": + post_resize_transform = tv_transforms.CenterCrop(img_size) + + img_resize = tv_transforms.Resize(img_size) + mask_resize = tv_transforms.Resize( + img_size, + interpolation=tv_transforms.InterpolationMode.BILINEAR, + ) + + img_transform = tv_transforms.Compose( + [ + pre_resize_transform, + img_resize, + post_resize_transform, + ] + ) + + mask_transform = tv_transforms.Compose( + [ + pre_resize_transform, + mask_resize, + post_resize_transform, + ] + ) + + return { + "img_transform": img_transform, + "mask_transform": mask_transform, + } + + +def crop_around_mask_with_random_box_size_factor( + loaded_image: torch.Tensor, + mask: torch.Tensor, + random_box_size_factor: float = 1.0, + pointmap: Optional[torch.Tensor] = None, +) -> np.ndarray: + return crop_around_mask_with_padding( + loaded_image, + mask, + box_size_factor=1.0 + random.uniform(0, 1) * random_box_size_factor, + padding_factor=0.0, + pointmap=pointmap, + ) + + +def crop_around_mask_with_padding( + loaded_image: torch.Tensor, + mask: torch.Tensor, + box_size_factor: float = 1.6, + padding_factor: float = 0.1, + pointmap: Optional[torch.Tensor] = None, +) -> np.ndarray: + # cast to ensure the function can be called normally + cast_mask = False + if mask.dim() == 3: + assert mask.shape[0] == 1, "cannot take mask with channel dimension not 1" + mask = mask[0] + cast_mask = True + loaded_image = concat_rgba(loaded_image, mask) + + bbox = compute_mask_bbox(mask, box_size_factor) + loaded_image = torchvision.transforms.functional.crop( + loaded_image, bbox[1], bbox[0], bbox[3] - bbox[1], bbox[2] - bbox[0] + ) + + # Crop pointmap if provided + if pointmap is not None: + pointmap = torchvision.transforms.functional.crop( + pointmap, bbox[1], bbox[0], bbox[3] - bbox[1], bbox[2] - bbox[0] + ) + + C, H, W = loaded_image.shape + max_dim = max(H, W) # Get the larger dimension + + # Step 1: Pad to square shape + pad_h = (max_dim - H) // 2 + pad_w = (max_dim - W) // 2 + pad_h_extra = (max_dim - H) - pad_h # To ensure even padding + pad_w_extra = (max_dim - W) - pad_w + + loaded_image = torch.nn.functional.pad( + loaded_image, (pad_w, pad_w_extra, pad_h, pad_h_extra), mode="constant", value=0 + ) + if pointmap is not None: + pointmap = torch.nn.functional.pad( + pointmap, + (pad_w, pad_w_extra, pad_h, pad_h_extra), + mode="constant", + value=float("nan"), + ) + + # Step 2: Extend by 10% on each side; idk but this seems to have better results overall + if padding_factor > 0: + extend_size = int(max_dim * padding_factor) # 10% extension on each side + loaded_image = torch.nn.functional.pad( + loaded_image, + (extend_size, extend_size, extend_size, extend_size), + mode="constant", + value=0, + ) + + if pointmap is not None: + pointmap = torch.nn.functional.pad( + pointmap, + (extend_size, extend_size, extend_size, extend_size), + mode="constant", + value=float("nan"), + ) + + rgb_image, mask = split_rgba(loaded_image) + if cast_mask: + mask = mask[None] + + if pointmap is not None: + return rgb_image, mask, pointmap + return rgb_image, mask + + +def compute_mask_bbox( + mask: torch.Tensor, box_size_factor: float = 1.0 +) -> tuple[float, float, float, float]: + """ + Compute a bounding box around a binary mask with optional size adjustment. + + Args: + mask: A 2D binary tensor where non-zero values represent the object of interest. + box_size_factor: Factor to scale the bounding box size. Values > 1.0 create a larger box. + Default is 1.0 (tight bounding box). + + Returns: + A tuple of (x1, y1, x2, y2) coordinates representing the bounding box, + where (x1, y1) is the top-left corner and (x2, y2) is the bottom-right corner. + + Raises: + ValueError: If mask is not a torch.Tensor or not a 2D tensor. + """ + if not isinstance(mask, torch.Tensor): + raise ValueError("Mask must be a torch.Tensor") + if not mask.dim() == 2: + raise ValueError("Mask must be a 2D tensor") + bbox_indices = torch.nonzero(mask) + if bbox_indices.numel() == 0: + # Handle empty mask case + return (0, 0, 0, 0) + + y_indices = bbox_indices[:, 0] + x_indices = bbox_indices[:, 1] + + min_x = torch.min(x_indices).item() + min_y = torch.min(y_indices).item() + max_x = torch.max(x_indices).item() + max_y = torch.max(y_indices).item() + + bbox = (min_x, min_y, max_x, max_y) + + center_x = (bbox[0] + bbox[2]) / 2 + center_y = (bbox[1] + bbox[3]) / 2 + + bbox_w, bbox_h = bbox[2] - bbox[0], bbox[3] - bbox[1] + + check_bounding_box(bbox_w, bbox_h) + + size = max(bbox_w, bbox_h, 2) + size = int(size * box_size_factor) + + bbox = ( + int(center_x - size // 2), + int(center_y - size // 2), + int(center_x + size // 2), + int(center_y + size // 2), + ) + # bbox = tuple(map(int, bbox)) + return bbox + + +def crop_and_pad(image, bbox): + """ + Crop an image using a bounding box and pad with zeros if out of bounds. + + Args: + image (torch.Tensor): CxHxW image. + bbox (tuple): (x1, y1, x2, y2) bounding box. + + Returns: + torch.Tensor: Cropped and zero-padded image. + """ + C, H, W = image.shape + x1, y1, x2, y2 = bbox + + # Ensure coordinates are integers + x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) + + # Compute cropping coordinates + x1_pad, y1_pad = max(0, -x1), max(0, -y1) + x2_pad, y2_pad = max(0, x2 - W), max(0, y2 - H) + + # Compute valid region in the original image + x1_crop, y1_crop = max(0, x1), max(0, y1) + x2_crop, y2_crop = min(W, x2), min(H, y2) + + # Extract the valid part + cropped = image[:, y1_crop:y2_crop, x1_crop:x2_crop] + + # Create a zero-padded output + padded = torch.zeros((C, y2 - y1, x2 - x1), dtype=image.dtype) + + # Place the cropped image into the zero-padded array + padded[ + :, y1_pad : y1_pad + cropped.shape[1], x1_pad : x1_pad + cropped.shape[2] + ] = cropped + + return padded + + +def resize_all_to_same_size( + rgb_image: torch.Tensor, + mask: torch.Tensor, + pointmap: Optional[torch.Tensor] = None, + target_size: Optional[tuple[int, int]] = None, +) -> tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: + """ + Resize RGB image, mask, and pointmap to the same size. + + This is crucial when pointmaps have different resolution than RGB images, + which must be done BEFORE any cropping operations. + + Args: + rgb_image: RGB image tensor of shape (C, H, W) + mask: Mask tensor of shape (H, W) or (1, H, W) + pointmap: Optional pointmap tensor of shape (C_p, H_p, W_p) + target_size: Target size as (H, W). If None, uses RGB image size. + + Returns: + Tuple of (resized_rgb, resized_mask, resized_pointmap) + """ + squeeze_mask = (mask.dim() == 2) + if squeeze_mask: + mask = mask.unsqueeze(0) + + if target_size is None: + target_size = (rgb_image.shape[1], rgb_image.shape[2]) # (H, W) + + rgb_needs_resize = (rgb_image.shape[1], rgb_image.shape[2]) != target_size + if rgb_needs_resize: + rgb_image = torchvision.transforms.functional.resize( + rgb_image, target_size, interpolation=torchvision.transforms.InterpolationMode.BILINEAR + ) + mask = torchvision.transforms.functional.resize( + mask, target_size, interpolation=torchvision.transforms.InterpolationMode.NEAREST + ) + + if pointmap is not None: + pointmap_size = (pointmap.shape[1], pointmap.shape[2]) + if pointmap_size != target_size: + # Handle NaN values in pointmap during resizing + # Direct resize would propagate NaN values, so we need special handling + nan_mask = torch.isnan(pointmap).any(dim=0) + pointmap_clean = torch.where(torch.isnan(pointmap), torch.zeros_like(pointmap), pointmap) + pointmap_resized = torchvision.transforms.functional.resize( + pointmap_clean, target_size, interpolation=torchvision.transforms.InterpolationMode.BILINEAR + ) + + # Resize the nan mask to identify which regions should remain invalid + nan_mask_resized = torchvision.transforms.functional.resize( + nan_mask.unsqueeze(0).float(), target_size, + interpolation=torchvision.transforms.InterpolationMode.NEAREST + ).squeeze(0) > 0.5 + + # Restore NaN values in regions that were originally invalid + pointmap = torch.where( + nan_mask_resized.unsqueeze(0).expand_as(pointmap_resized), + torch.full_like(pointmap_resized, float('nan')), + pointmap_resized + ) + + if squeeze_mask: + mask = mask.squeeze(0) + + if pointmap is not None: + return rgb_image, mask, pointmap + return rgb_image, mask + + +SSINormalizedPointmap = namedtuple("SSINormalizedPointmap", ["pointmap", "scale", "shift"]) +class SSIPointmapNormalizer: + + def normalize(self, pointmap: torch.Tensor, mask: torch.Tensor, + scale: Optional[torch.Tensor] = None, shift: Optional[torch.Tensor] = None, + ) -> SSINormalizedPointmap: + if scale is None or shift is None: + normalized_pointmap, scale, shift = normalize_pointmap_ssi(pointmap) + else: + assert scale.shape == (3,) and shift.shape == (3,), "scale and shift must be in (3,) format" + normalized_pointmap = _apply_metric_to_ssi(pointmap, scale, shift) + return SSINormalizedPointmap(normalized_pointmap, scale, shift) + + def denormalize(self, pointmap: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor) -> torch.Tensor: + pointmap = _apply_metric_to_ssi(pointmap, scale, shift, apply_inverse=True) + return pointmap + + + +class ObjectCentricSSI(SSIPointmapNormalizer): + def __init__(self, + use_scene_scale: bool = True, + quantile_drop_threshold: float = 0.1, + clip_beyond_scale: Optional[float] = None, + # scale_factor: float = 3.8076, # e^(1.337); empirical mean of R3+Artist train + scale_factor: float = 1.0, # e^(1.337); empirical mean of R3+Artist train + allow_scale_and_shift_override: bool = False, + raise_on_no_valid_points: bool = False, + ): + self.use_scene_scale = use_scene_scale + self.quantile_drop_threshold = quantile_drop_threshold + self.clip_beyond_scale = clip_beyond_scale + self.scale_factor = scale_factor + self.allow_scale_and_shift_override = allow_scale_and_shift_override + self.raise_on_no_valid_points = raise_on_no_valid_points + + def _compute_scale_and_shift(self, pointmap: torch.Tensor, mask: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + pointmap_size = (pointmap.shape[1], pointmap.shape[2]) + + + mask_resized = torchvision.transforms.functional.resize( + mask, pointmap_size, + interpolation=torchvision.transforms.InterpolationMode.NEAREST + ).squeeze(0) + + pointmap_flat = pointmap.reshape(3, -1) + # Get valid points from the mask + mask_bool = mask_resized.reshape(-1) > 0.5 + mask_points = pointmap_flat[:, mask_bool] + + if mask_points.isfinite().max() == 0: + if self.raise_on_no_valid_points: + raise ValueError(f"No valid points found in mask") + logger.warning(f"No valid points found in mask; setting scale to {self.scale_factor} and shift to 0") + return torch.ones_like(pointmap_flat[:,0]) * self.scale_factor, torch.zeros_like(pointmap_flat[:,0]) + + # Compute median for shift + shift = mask_points.nanmedian(dim=-1).values + # logger.info(f"{pointmap.shape=} {mask_resized.shape=} {shift.shape=}") + + + if self.use_scene_scale == True: + # Normalize by the scene scale + points_centered = pointmap_flat - shift.unsqueeze(-1) + max_dims = points_centered.abs().max(dim=0).values + scale = max_dims.nanmedian(dim=-1).values + elif self.use_scene_scale == False: + # Normalize by the object scale + shifted_mask_points = mask_points - shift.unsqueeze(-1) + norm = shifted_mask_points.norm(dim=0) + quantiles = torch.nanquantile(norm, + torch.tensor([self.quantile_drop_threshold, 1. - self.quantile_drop_threshold], + device=shifted_mask_points.device), + dim=-1) + scale = (quantiles[1] - quantiles[0]).max(dim=-1).values * 2.0 + elif self.use_scene_scale.upper() == "OBJECT_NORM_MEDIAN": + # Normalize by the object scale + shifted_mask_points = mask_points - shift.unsqueeze(-1) + norm = shifted_mask_points.norm(dim=0) + scale = norm.nanmedian(dim=-1).values + else: + raise ValueError(f"Invalid use_scene_scale: {self.use_scene_scale}") + scale = scale.expand_as(shift) # per-dim scaling + scale = scale * self.scale_factor + return scale, shift + + def normalize(self, pointmap: torch.Tensor, mask: torch.Tensor, + scale: Optional[torch.Tensor] = None, shift: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + # 1. resize mask to size of pointmap using nearest interpolation + # 2. get mask points: pointmap[mask > 0.5] + # 3. shift = mask_points.median() # xyz + # 4. scale = # filter. If no points, then + # logger.info(f"{pointmap.shape=} {mask.shape=}") + assert pointmap.shape[0] == 3, "pointmap must be in (3, H, W) format" + pointmap_size = (pointmap.shape[1], pointmap.shape[2]) + + _scale, _shift = self._compute_scale_and_shift(pointmap, mask) + if scale is not None and self.allow_scale_and_shift_override: + _scale = scale + if shift is not None and self.allow_scale_and_shift_override: + _shift = shift + return_scale, return_shift = _scale, _shift + + # Apply normalization + pointmap_normalized = _apply_metric_to_ssi(pointmap, return_scale, return_shift) + + if self.clip_beyond_scale is not None and self.clip_beyond_scale > 0: + new_norm = pointmap_normalized.norm(dim=0) + pointmap_normalized = torch.where( + new_norm > self.clip_beyond_scale, + torch.full_like(pointmap_normalized, float('nan')), + pointmap_normalized + ) + + return SSINormalizedPointmap(pointmap_normalized, return_scale, return_shift) + + +class ObjectApparentSizeSSI(SSIPointmapNormalizer): + def __init__(self, + clip_beyond_scale: Optional[float] = None, + use_scene_scale: bool = True, + scale_factor: float = 1.0, # e^(1.337); empirical mean of R3+Artist train + ): + self.clip_beyond_scale = clip_beyond_scale + self.use_scene_scale = use_scene_scale + self.scale_factor = scale_factor + + def _get_scale_and_shift(self, pointmap: torch.Tensor, mask: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + pointmap_size = (pointmap.shape[1], pointmap.shape[2]) + pointmap_flat = pointmap.reshape(3, -1) + + if not self.use_scene_scale: + # Get valid points from the mask + mask_resized = torchvision.transforms.functional.resize( + mask, pointmap_size, + interpolation=torchvision.transforms.InterpolationMode.NEAREST + ).squeeze(0) + mask_bool = mask_resized.reshape(-1) > 0.5 + pointmap_flat = pointmap_flat[:, mask_bool] + + # Median z-distance + median_z = pointmap_flat[-1, ...].nanmedian().unsqueeze(0) + scale = median_z.expand(3) * self.scale_factor + shift = torch.zeros_like(scale) + # logger.info(f'median z = {median_z}') + return scale, shift + + def normalize(self, + pointmap: torch.Tensor, + mask: torch.Tensor, + scale: Optional[torch.Tensor] = None, + shift: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + assert pointmap.shape[0] == 3, "pointmap must be in (3, H, W) format" + pointmap_size = (pointmap.shape[1], pointmap.shape[2]) + + if scale is None or shift is None: + scale, shift = self._get_scale_and_shift(pointmap, mask) + else: + assert scale.shape == (3,) and shift.shape == (3,), "scale and shift must be in (3,) format" + + # Apply normalization and clip + pointmap_normalized = _apply_metric_to_ssi(pointmap, scale, shift) + # logger.info(f"{pointmap_normalized.shape=}") + + if self.clip_beyond_scale is not None and self.clip_beyond_scale > 0: + pointmap_normalized = torch.where( + pointmap_normalized[-1, ...] > self.clip_beyond_scale, + torch.full_like(pointmap_normalized, float('nan')), + pointmap_normalized + ) + + # return pointmap_normalized, scale, shift + return SSINormalizedPointmap(pointmap_normalized, scale, shift) + + +class NormalizedDisparitySpaceSSI(SSIPointmapNormalizer): + def __init__(self, + clip_beyond_scale: Optional[float] = None, + use_scene_scale: bool = True, + log_disparity_shift: float = 0.0, + ): + self.clip_beyond_scale = clip_beyond_scale + self.use_scene_scale = use_scene_scale + self.point_remapper = PointRemapper(remap_type="exp_disparity") + self.log_disparity_shift = log_disparity_shift + + def normalize(self, pointmap: torch.Tensor, mask: torch.Tensor, + scale: Optional[torch.Tensor] = None, shift: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + assert pointmap.shape[0] == 3, "pointmap must be in (3, H, W) format" + + + disparity_space_pointmap = self.point_remapper.forward(pointmap.permute(1, 2, 0)).permute(2, 0, 1) + if scale is None or shift is None: + scale, shift = self._get_scale_and_shift(disparity_space_pointmap, mask) + else: + assert scale.shape == (3,) and shift.shape == (3,), "scale and shift must be in (3,) format" + + # pointmap_normalized = pointmap.clone().detach() + pointmap_normalized = _apply_metric_to_ssi(disparity_space_pointmap, scale, shift) + # logger.info(f"{pointmap_normalized.shape=}") + + if self.clip_beyond_scale is not None and self.clip_beyond_scale > 0: + pointmap_normalized = torch.where( + pointmap_normalized[2, ...].abs() > self.clip_beyond_scale, + torch.full_like(pointmap_normalized, float('nan')), + pointmap_normalized + ) + + # return pointmap_normalized, scale, shift + return SSINormalizedPointmap(pointmap_normalized, scale, shift) + + def denormalize(self, pointmap: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor) -> torch.Tensor: + pointmap = _apply_metric_to_ssi(pointmap, scale, shift, apply_inverse=True) + pointmap = self.point_remapper.inverse(pointmap.permute(1, 2, 0)).permute(2, 0, 1) + return pointmap + + def _get_scale_and_shift(self, pointmap: torch.Tensor, mask: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + pointmap_size = (pointmap.shape[1], pointmap.shape[2]) + mask_resized = torchvision.transforms.functional.resize( + mask, pointmap_size, + interpolation=torchvision.transforms.InterpolationMode.NEAREST + ).squeeze(0) + + pointmap_flat = pointmap.reshape(3, -1) + if self.use_scene_scale: + median_z = pointmap_flat[-1, ...].nanmedian().unsqueeze(0) + shift = torch.zeros_like(median_z.expand(3)) + shift[-1, ...] = median_z[0] + self.log_disparity_shift + else: + # Get valid points from the mask (shift, x/z, y/z, log(z)) + mask_bool = mask_resized.reshape(-1) > 0.5 + pointmap_flat = pointmap_flat[:, mask_bool] + shift = pointmap_flat.nanmedian(dim=-1).values + + scale = torch.ones_like(shift) + # logger.info(f'median z = {median_z}') + return scale, shift + +def normalize_pointmap_ssi(pointmap: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Normalize pointmap using Scale-Shift Invariant (SSI) normalization. + + Args: + pointmap: Pointmap tensor of shape (H, W, 3) or (3, H, W) + + Returns: + Tuple of (normalized_pointmap, scale, shift) + """ + from sam3d_objects.data.dataset.tdfy.pose_target import ScaleShiftInvariant + + # Convert to (H, W, 3) if needed for get_scale_and_shift + if pointmap.shape[0] == 3: + pointmap_hw3 = pointmap.permute(1, 2, 0) + original_format = 'chw' + else: + pointmap_hw3 = pointmap + original_format = 'hwc' + + # Get scale and shift using existing method + scale, shift = ScaleShiftInvariant.get_scale_and_shift(pointmap_hw3) + + pointmap_normalized = _apply_metric_to_ssi(pointmap, scale, shift) + return pointmap_normalized, scale, shift + +def _apply_metric_to_ssi(pointmap: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor, apply_inverse: bool = False) -> torch.Tensor: + """ + Normalize pointmap using Scale-Shift Invariant (SSI) normalization. + + Args: + pointmap: Pointmap tensor of shape (H, W, 3) or (3, H, W) + + Returns: + Tuple of (normalized_pointmap, scale, shift) + """ + from sam3d_objects.data.dataset.tdfy.pose_target import ScaleShiftInvariant + + # Convert to (H, W, 3) if needed for get_scale_and_shift + if pointmap.shape[0] == 3: + pointmap_hw3 = pointmap.permute(1, 2, 0) + original_format = 'chw' + else: + pointmap_hw3 = pointmap + original_format = 'hwc' + + # Apply normalization + ssi_to_metric = ScaleShiftInvariant.ssi_to_metric(scale, shift) + metric_to_ssi = ssi_to_metric.inverse() + transform_to_apply = metric_to_ssi + + if apply_inverse: + transform_to_apply = ssi_to_metric + + pointmap_flat = pointmap_hw3.reshape(-1, 3) + pointmap_normalized = transform_to_apply.transform_points(pointmap_flat) + + # Reshape back to original format + if original_format == 'chw': + pointmap_normalized = pointmap_normalized.reshape(pointmap.shape[1], pointmap.shape[2], 3).permute(2, 0, 1) + else: + pointmap_normalized = pointmap_normalized.reshape(pointmap_hw3.shape) + + return pointmap_normalized + + +def perturb_mask_translation( + image: torch.Tensor, + mask: torch.Tensor, + max_px_delta: int = 5, +): + """ + Applies data augmentation to the mask by randomly translating the mask. + + Args: + image: (C, H, W) float32 [0, 1] tensor. + mask: (1, H, W) float32 [0, 1] tensor. + max_px_delta: The maximum number of pixels we will randomly shift by in each 2D direction. + """ + dx = random.randint(-max_px_delta, max_px_delta) + dy = random.randint(-max_px_delta, max_px_delta) + + mask = mask.squeeze(0) + mask = torch.roll(mask, shifts=(dy, dx), dims=(0, 1)) + + # Zero out wrapped regions + if dy > 0: + mask[:dy, :] = 0 + elif dy < 0: + mask[dy:, :] = 0 + if dx > 0: + mask[:, :dx] = 0 + elif dx < 0: + mask[:, dx:] = 0 + + mask = mask.unsqueeze(0) + return image, mask + + +def perturb_mask_boundary( + image: torch.Tensor, + mask: torch.Tensor, + kernel_range: tuple[int, int] = (2, 5), + p_erode: float = 0.1, + p_dilate: float = 0.8, + **kwargs, +): + """ + Applies data augmentation to the mask by randomly eroding or dilating the mask. + + Args: + image: (C, H, W) float32 [0, 1] tensor. + mask: (1, H, W) float32 [0, 1] tensor. + kernel_range: Range of kernel sizes to sample from. + p_erode: Probability of erosion. + p_dilate: Probability of dilation. + kwargs: Kwargs for the cv2 erode/dilate function. + """ + import cv2 + + C, H, W = image.shape + assert mask.shape == (1, H, W) + assert mask.dtype == torch.float32 + assert torch.all((mask == 0) | (mask == 1)), "Mask must be binary (0 or 1)" + + p_none = 1.0 - p_erode - p_dilate + assert 0 <= p_none <= 1, "Probabilities must sum to 1 and be valid." + + # Sample operation. + op = random.choices(["erode", "dilate", "none"], weights=[p_erode, p_dilate, p_none], k=1)[0] + + if op == "none": + pass + else: + # Sample kernel size + ksize = random.randint(*kernel_range) + kernel = np.ones((ksize, ksize), np.uint8) + + mask = mask.squeeze().cpu().numpy().astype(np.uint8) # (H, W) + + if op == "erode": + mask = cv2.erode(mask, kernel, **kwargs) + elif op == "dilate": + mask = cv2.dilate(mask, kernel, **kwargs) + else: + raise NotImplementedError + + mask = torch.from_numpy(mask).float()[None] # (1, H, W) + + return image, mask + + +def resolution_blur( + image: torch.Tensor, + mask: torch.Tensor, + scale_range=(0.05, 0.95), + interpolation_down=tv_transforms.InterpolationMode.BICUBIC, + interpolation_up=tv_transforms.InterpolationMode.BICUBIC, +): + """ + Blur the input image by applying upsample(downsample(x)). + + Args: + image (torch.Tensor): Image tensor of shape (C, H, W), float32, with values in [0, 1]. + mask (torch.Tensor): Mask tensor of shape (1, H, W), float32, with values in [0, 1]. The mask is returned unchanged. + scale_range: Tuple of (min_scale, max_scale) for downsampling. + interpolation_down: Interpolation mode for downsampling. + interpolation_up: Interpolation mode for upsampling. + """ + C, H, W = image.shape + scale = random.uniform(*scale_range) + new_H, new_W = max(1, int(H * scale)), max(1, int(W * scale)) + + # Downsample + image = TF.resize(image, size=[new_H, new_W], interpolation=interpolation_down) + + # Upsample back to original size + image = TF.resize(image, size=[H, W], interpolation=interpolation_up) + + return image, mask + + +def gaussian_blur( + image: torch.Tensor, + mask: torch.Tensor, + kernel_range: tuple[int, int] = (3, 15), + sigma_range: tuple[int, int] = (0.1, 4.0), +): + """ + Apply gaussian blur to the input image. + + Args: + image (torch.Tensor): Image tensor of shape (C, H, W), float32, with values in [0, 1]. + mask (torch.Tensor): Mask tensor of shape (1, H, W), float32, with values in [0, 1]. The mask is returned unchanged. + kernel_range (tuple): Range of odd kernel sizes to sample from for the Gaussian blur (min, max). + sigma_range (tuple): Range of sigma values (standard deviation) to sample from for the Gaussian kernel (min, max). + """ + kernel_size = random.choice([k for k in range(kernel_range[0], kernel_range[1]+1) if k % 2 == 1]) + sigma = random.uniform(*sigma_range) + pad = kernel_size // 2 + + # Step 1: Pad the image + image = F.pad(image.unsqueeze(0), (pad, pad, pad, pad), mode='replicate') + + # Step 2: Apply gaussian blur + image = TF.gaussian_blur(image, kernel_size=[kernel_size, kernel_size], sigma=sigma) + + # Step 3: Unpad to get back to original size + image = image[:, :, pad:-pad, pad:-pad] + + return image.squeeze(0), mask + + +def apply_blur_augmentation( + image: torch.Tensor, + mask: torch.Tensor, + p_resolution: float = 0.33, + p_gaussian: float = 0.33, + gaussian_kwargs: dict = None, + resolution_kwargs: dict = None, +): + """Apply blur augmentation with configurable parameters""" + + # Handle None defaults BEFORE unpacking + if gaussian_kwargs is None: + gaussian_kwargs = {} + if resolution_kwargs is None: + resolution_kwargs = {} + + p_none = 1.0 - p_gaussian - p_resolution + assert 0 <= p_none <= 1, "Probabilities must sum to 1 and be valid." + + operation = random.choices( + ["gaussian", "resolution", "none"], + weights=[p_gaussian, p_resolution, p_none], + k=1 + )[0] + + if operation == "gaussian": + return gaussian_blur(image, mask, **gaussian_kwargs) + elif operation == "resolution": + return resolution_blur(image, mask, **resolution_kwargs) + elif operation == "none": + return image, mask + else: + raise NotImplementedError diff --git a/int8/vendor/sam3d_objects/data/dataset/tdfy/img_processing.py b/int8/vendor/sam3d_objects/data/dataset/tdfy/img_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..af22c401e64773ce77bb1171699c363fe76948d8 --- /dev/null +++ b/int8/vendor/sam3d_objects/data/dataset/tdfy/img_processing.py @@ -0,0 +1,189 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +import math + +import random + +import torch +import torch.nn.functional as F + +from torchvision import transforms +from torchvision.transforms import functional as tv_F + + +class RandomResizedCrop(transforms.RandomResizedCrop): + """ + RandomResizedCrop for matching TF/TPU implementation: no for-loop is used. + This may lead to results different with torchvision's version. + Following BYOL's TF code: + https://github.com/deepmind/deepmind-research/blob/master/byol/utils/dataset.py#L206 + """ + + @staticmethod + def get_params(img, scale, ratio): + width, height = tv_F._get_image_size(img) + area = height * width + + target_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item() + log_ratio = torch.log(torch.tensor(ratio)) + aspect_ratio = torch.exp( + torch.empty(1).uniform_(log_ratio[0], log_ratio[1]) + ).item() + + w = int(round(math.sqrt(target_area * aspect_ratio))) + h = int(round(math.sqrt(target_area / aspect_ratio))) + + w = min(w, width) + h = min(h, height) + + i = torch.randint(0, height - h + 1, size=(1,)).item() + j = torch.randint(0, width - w + 1, size=(1,)).item() + + return i, j, h, w + + +# following PT3D CO3D data to pad image +def pad_to_square(image, value=0): + _, _, h, w = image.shape # Assuming image is in (B, C, H, W) format + if h == w: + return image # The image is already square + + # Calculate the padding + diff = abs(h - w) + pad2 = diff + + # Pad the image to make it square + if h > w: + padding = (0, pad2, 0, 0) # Pad width (left, right, top, bottom) + else: + padding = (0, 0, 0, pad2) # Pad height + # Apply padding + padded_image = torch.nn.functional.pad(image, padding, mode="constant", value=value) + return padded_image + + +def preprocess_img( + x, + mask=None, + img_target_shape=224, + mask_target_shape=256, + normalize=False, +): + if x.shape[1] != x.shape[2]: + x = pad_to_square(x) + if mask is not None and mask.shape[1] != mask.shape[2]: + mask = pad_to_square(mask) + if x.shape[2] != img_target_shape: + x = F.interpolate( + x, + size=(img_target_shape, img_target_shape), + # scale_factor=float(img_target_shape)/x.shape[2], + mode="bilinear", + ) + if mask is not None and mask.shape[2] != mask_target_shape: + if mask is not None: + mask = F.interpolate( + mask, + size=(mask_target_shape, mask_target_shape), + # scale_factor=float(mask_target_shape)/mask.shape[2], + mode="nearest", + ) + if normalize: + imgs_normed = resnet_img_normalization(x) + else: + imgs_normed = x + return imgs_normed, mask + + +def resnet_img_normalization(x): + resnet_mean = torch.tensor([0.485, 0.456, 0.406], device=x.device).reshape( + (3, 1, 1) + ) + resnet_std = torch.tensor([0.229, 0.224, 0.225], device=x.device).reshape((3, 1, 1)) + if x.ndim == 4: + resnet_mean = resnet_mean[None] + resnet_std = resnet_std[None] + x = (x - resnet_mean) / resnet_std + return x + + +# pad image to be centered for unprojecting depth +def pad_to_square_centered(image, value=0, pointmap=None): + h, w = image.shape[-2], image.shape[-1] # Assuming image is in (B, C, H, W) format + if h == w: + if pointmap is not None: + return image, pointmap + return image # The image is already square + + # Calculate the padding + diff = abs(h - w) + pad1 = diff // 2 + pad2 = diff - pad1 + + # Pad the image to make it square + if h > w: + padding = (pad1, pad2, 0, 0) # Pad width (left, right, top, bottom) + else: + padding = (0, 0, pad1, pad2) # Pad height + # Apply padding to image + padded_image = F.pad(image, padding, mode="constant", value=value) + + # Apply padding to pointmap if provided + if pointmap is not None: + # Pad pointmap using torch functional with NaN fill value + padded_pointmap = F.pad(pointmap, padding, mode="constant", value=float("nan")) + + return padded_image, padded_pointmap + return padded_image + + +def crop_img_to_obj(mask, context_size): + nonzeros = torch.nonzero(mask) + if len(nonzeros) > 0: + r_max, c_max = nonzeros.max(dim=0)[0] + r_min, c_min = nonzeros.min(dim=0)[0] + box_h = max(1, r_max - r_min) + box_w = max(1, c_max - c_min) + left = max(0, c_min - int(box_w * context_size)) + right = min(mask.shape[-1], c_max + int(box_w * context_size)) + top = max(0, r_min - int(box_h * context_size)) + bot = min(mask.shape[-2], r_max + int(box_h * context_size)) + return left, right, top, bot + return None, None, None, None + + +def random_pad(img, mask=None, max_ratio=0.0, pointmap=None): + max_size = int(max(img.shape) * max_ratio) + padding = tuple([random.randint(0, max_size) for _ in range(4)]) + img = F.pad(img, padding) + if mask is not None: + mask = F.pad(mask, padding) + + if pointmap is not None: + pointmap = F.pad(pointmap, padding, mode="constant", value=float("nan")) + return img, mask, pointmap + return img, mask + + +def get_img_color_augmentation( + color_jit_prob=0.5, + gaussian_blur_prob=0.1, +): + transform = transforms.Compose( + [ + # (a) Random Color Jitter + transforms.RandomApply( + [ + transforms.ColorJitter( + brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1 + ) + ], + p=color_jit_prob, + ), + # (b) Randomly apply GaussianBlur + transforms.RandomApply( + [transforms.GaussianBlur(kernel_size=3, sigma=(0.1, 2.0))], + p=gaussian_blur_prob, + ), + ] + ) + return transform diff --git a/int8/vendor/sam3d_objects/data/dataset/tdfy/pose_target.py b/int8/vendor/sam3d_objects/data/dataset/tdfy/pose_target.py new file mode 100644 index 0000000000000000000000000000000000000000..13dd87249d967a052e15ae14880e9fcea9aa5f32 --- /dev/null +++ b/int8/vendor/sam3d_objects/data/dataset/tdfy/pose_target.py @@ -0,0 +1,784 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +import torch +from typing import Dict, Optional, Tuple, Any +from dataclasses import dataclass, asdict, field +import logging; logger = logging.getLogger(__name__) + +from sam3d_objects.data.utils import expand_as_right, tree_tensor_map +from sam3d_objects.data.dataset.tdfy.transforms_3d import compose_transform, decompose_transform +from pytorch3d.transforms import Transform3d, quaternion_to_matrix, matrix_to_quaternion + + +@dataclass +class InstancePose: + """ + Stores the pose of an object. + Also, stores some information about the scene that was used to normalize the pose. + """ + + instance_scale_l2c: torch.Tensor + instance_position_l2c: torch.Tensor + instance_quaternion_l2c: torch.Tensor + scene_scale: torch.Tensor + scene_shift: torch.Tensor + + @classmethod + def _broadcast_postcompose( + cls, + scale: torch.Tensor, + rotation: torch.Tensor, + translation: torch.Tensor, + transform_to_postcompose: Transform3d, + ) -> Transform3d: + """ + Assumes scale, rotation, translation are of shape: + B, K, C + --- + B: batch size + K: number of objects + C: number of channels + + Takes a transform where + get_matrix() has shape (B, 3, 3) + + Returns pose.compose(transform_to_postcompose) + """ + scale_c = scale.shape[-1] + ndim_orig = scale.ndim + if ndim_orig == 3: + b, k, _ = scale.shape + elif ndim_orig == 2: + b = scale.shape[0] + k = 1 + elif ndim_orig == 1: + b = 1 + k = 1 + else: + raise ValueError(f"Invalid scale shape: {scale.shape}") + + # Create transform of shape (B * K) + wide = {"scale": scale, "rotation": rotation, "translation": translation} + shapes_orig = {k: v.shape for k, v in wide.items()} + long = tree_tensor_map(lambda x: x.reshape(b * k, x.shape[-1]), wide) + long["rotation"] = quaternion_to_matrix(long["rotation"]) + if scale_c == 1: + long["scale"] = long["scale"].expand(b * k, 3) + + composed = compose_transform(**long) + + # Apply transform to shape (B * K) + pc_transform = transform_to_postcompose.get_matrix() + pc_transform = pc_transform.repeat(k, 1, 1) + stacked_pc_transform = Transform3d(matrix=pc_transform) + assert stacked_pc_transform.get_matrix().shape == composed.get_matrix().shape + postcomposed = composed.compose(stacked_pc_transform) + + # Decompose transform to shape (B, K, C) + scale, rotation, translation = decompose_transform(postcomposed) + rotation = matrix_to_quaternion(rotation) + pc_long = {"scale": scale, "rotation": rotation, "translation": translation} + pc_wide = tree_tensor_map(lambda x: x.reshape(b, k, x.shape[-1]), pc_long) + if scale_c == 1: + pc_wide["scale"] = pc_wide["scale"][..., 0].unsqueeze(-1) + for k, shape in shapes_orig.items(): + pc_wide[k] = pc_wide[k].reshape(*shape) + return pc_wide["scale"], pc_wide["rotation"], pc_wide["translation"] + + +@dataclass +class PoseTarget: + x_instance_scale: torch.Tensor + x_instance_rotation: torch.Tensor + x_instance_translation: torch.Tensor + x_scene_scale: torch.Tensor + x_scene_center: torch.Tensor + x_translation_scale: torch.Tensor + pose_target_convention: str = field(default="unknown") + + +@dataclass +class InvariantPoseTarget: + """ + This is the canonical representation of pose targets, used for computing metrics. + instance_pose <-> invariant_pose_targets <-> all other pose_target_conventions + + Background: + --- + We want to estimate a transformation T: R³ → R³ despite scene scale ambiguity. + + The transformation taking object points to scene points is defined as + T(x) = s · R(q) · x + t + where: + - x is a point in the object coordinate frame, + - q is a unit quaternion representing rotation, + - s is the object-to-scene scale, and + - t is the translation. + + However, there is an inherent scale ambiguity in the scene, denoted as s_scene; + This ambiguity introduces irreducible error that complicates both evaluation and training. + + To decouple the scene scale from the invariant quantities, we define: + T(x) = s_scene · |t_rel| [ s_tilde · R(q) · x + t_unit ] + where we define + t_rel = t / s_scene + s_rel = s / s_scene + s_tilde = s_rel / |t_rel| + t_unit = t_rel / |t_rel| + + During training, you would predict (q, s_tilde, t_unit), leaving s_scene separate. + + + Hand-wavy error analysis: + --- + 1. Naive (coupled) estimate: + T(x) = s_scene [ s_rel · R(q) · x + t_rel ] + + We can define: + U = ln(s_rel) + V = ln(|t_rel|) + so that the error is governed by Var(U + V). + + 2. In the decoupled case, we have: + T(x) = s_scene · |t_rel| [ s_tilde · R(q) · x + t_unit ] + = s_scene · |t_rel| [ (s_rel / |t_rel|) R(q) · x + t_unit ] + Then ln(s_tilde) = ln(s_rel) - ln(|t_rel|) = U - V, and the error is + Var(U - V) = Var(U) + Var(V) - 2Cov(U, V). + + """ + + # These are invariant + q: torch.Tensor + t_unit: torch.Tensor + s_scene: torch.Tensor + t_scene_center: Optional[torch.Tensor] = None + t_rel_norm: Optional[torch.Tensor] = None + s_tilde: Optional[torch.Tensor] = None + s_rel: Optional[torch.Tensor] = None + + def __post_init__(self): + # Check that fields that are required always have values. + if self.q is None: + raise ValueError("Field 'q' (quaternion) must be provided.") + if self.s_scene is None: + raise ValueError("Field 's_scene' must be provided.") + if self.s_rel is None: + if self.s_tilde is not None: + self.s_rel = self.s_tilde * self.t_rel_norm + else: + raise ValueError("Field 's_rel' or 's_tilde' must be provided.") + if self.t_unit is None: + raise ValueError("Field 't_unit' must be provided.") + + if self.t_scene_center is None: + self.t_scene_center = torch.zeros_like(self.t_unit) + + # There is a simple relationship between s_tilde and t_rel_norm: + # s_tilde = s_rel / t_rel_norm + # + # If one of these is missing and the other is provided, we can compute the missing field. + if self.s_tilde is None and self.t_rel_norm is not None: + self.s_tilde = self.s_rel / self.t_rel_norm + elif self.t_rel_norm is None and self.s_tilde is not None: + self.t_rel_norm = self.s_rel / self.s_tilde + + # If both are provided, we check for consistency. + if self.s_tilde is not None and self.t_rel_norm is not None: + computed_s_tilde = self.s_rel / self.t_rel_norm + # If the provided s_tilde deviates from what is computed, update it. + if not torch.allclose(self.s_tilde, computed_s_tilde, atol=1e-6): + logger.warning( + f"s_tilde and t_rel_norm are provided, but they are not consistent. " + f"Updating s_tilde to {computed_s_tilde}." + ) + self.s_tilde = computed_s_tilde + + self._validate_fields() + + def _validate_fields(self): + for field in self.__dict__: + if self.__dict__[field] is None: + raise ValueError(f"Field '{field}' must be provided.") + + + @staticmethod + def from_instance_pose(instance_pose: InstancePose) -> "InvariantPoseTarget": + q = instance_pose.instance_quaternion_l2c + s_obj_to_scene = instance_pose.instance_scale_l2c # (..., 1) or (..., 3) + t_obj_to_scene = instance_pose.instance_position_l2c # (..., 3) + s_scene = instance_pose.scene_scale # (..., 1) or scalar-broadcastable + t_scene_center = instance_pose.scene_shift # (..., 3) + + # Normalize to scene scale (per the derivation) + if not ( s_obj_to_scene.ndim == (s_scene.ndim + 1)): + raise ValueError(f"s_scene should be ND [...,3] and s_obj_to_scene should be (N+1)D [...,K,3], but got {s_scene.shape=} {s_obj_to_scene.shape=}") + if not (t_obj_to_scene.ndim == (s_scene.ndim + 1)): + raise ValueError(f"t_scene_center should be ND [B,3] and t_obj_to_scene should be (N+1)D [B,K,3], but got {t_scene_center.shape=} {t_obj_to_scene.shape=}") + s_scene_exp = s_scene.unsqueeze(-2) + + s_rel = s_obj_to_scene / s_scene_exp + t_rel = t_obj_to_scene / s_scene_exp + + # Robust norms + eps = 1e-8 + t_rel_norm = t_rel.norm(dim=-1, keepdim=True).clamp_min(eps) + + s_tilde = s_rel / t_rel_norm + t_unit = t_rel / t_rel_norm + + return InvariantPoseTarget( + q=q, + s_scene=s_scene, + t_scene_center=t_scene_center, + s_rel=s_rel, + s_tilde=s_tilde, + t_unit=t_unit, + t_rel_norm=t_rel_norm, + ) + + + @staticmethod + def to_instance_pose(invariant_targets: "InvariantPoseTarget") -> InstancePose: + # scale factor per the derivation: s_scene * |t_rel| + # Normalize to scene scale (per the derivation) + t_rel_norm_ndim = invariant_targets.t_rel_norm.ndim + if not (invariant_targets.s_scene.ndim == (t_rel_norm_ndim - 1)) : + raise ValueError(f"s_scene should be ND [...,3] and t_rel_norm should be (N+1)D [...,K,3], but got {invariant_targets.s_scene.shape=} {invariant_targets.t_rel_norm.shape=}") + + scale = invariant_targets.s_scene.unsqueeze(-2) * invariant_targets.t_rel_norm + return InstancePose( + instance_scale_l2c=invariant_targets.s_tilde * scale, + instance_position_l2c=invariant_targets.t_unit * scale, + instance_quaternion_l2c=invariant_targets.q, + scene_scale=invariant_targets.s_scene, + scene_shift=invariant_targets.t_scene_center, + ) + + +class PoseTargetConvention: + """ + Converts pose_targets <-> instance_pose <-> invariant_pose_targets + """ + + pose_target_convention: str + + @classmethod + def from_invariant(cls, invariant_targets: InvariantPoseTarget) -> PoseTarget: + raise NotImplementedError("Implement this in a subclass") + + @classmethod + def to_invariant(cls, instance_pose: InstancePose) -> InvariantPoseTarget: + raise NotImplementedError("Implement this in a subclass") + + @classmethod + def from_instance_pose(cls, instance_pose: InstancePose) -> PoseTarget: + invariant_targets = InvariantPoseTarget.from_instance_pose(instance_pose) + return cls.from_invariant(invariant_targets) + + @classmethod + def to_instance_pose(cls, pose_target: PoseTarget) -> InstancePose: + invariant_targets = cls.to_invariant(pose_target) + return InvariantPoseTarget.to_instance_pose(invariant_targets) + + +class ScaleShiftInvariant(PoseTargetConvention): + """ + + Midas eq. (6): https://arxiv.org/pdf/1907.01341v3 + But for pointmaps (see MoGe): https://arxiv.org/pdf/2410.19115 + """ + + pose_target_convention: str = "ScaleShiftInvariant" + scale_mean = torch.tensor([1.0232692956924438, 1.0232691764831543, 1.0232692956924438]).to(torch.float32) + scale_std = torch.tensor([1.3773751258850098, 1.3773752450942993, 1.3773750066757202]).to(torch.float32) + translation_mean = torch.tensor([0.003191213821992278, 0.017236359417438507, 0.9401122331619263]).to(torch.float32) + translation_std = torch.tensor([1.341888666152954, 0.7665449380874634, 3.175130605697632]).to(torch.float32) + + @classmethod + def from_instance_pose(cls, instance_pose: InstancePose, normalize: bool = False) -> PoseTarget: + metric_to_ssi = cls.ssi_to_metric( + instance_pose.scene_scale, instance_pose.scene_shift + ).inverse() + + ssi_scale, ssi_rotation, ssi_translation = InstancePose._broadcast_postcompose( + scale=instance_pose.instance_scale_l2c, + rotation=instance_pose.instance_quaternion_l2c, + translation=instance_pose.instance_position_l2c, + transform_to_postcompose=metric_to_ssi, + ) + # logger.info(f"{normalize=} {ssi_scale.shape=} {ssi_rotation.shape=} {ssi_translation.shape=}") + if normalize: + device = ssi_scale.device + ssi_scale = (ssi_scale - cls.scale_mean.to(device)) / cls.scale_std.to(device) + ssi_translation = (ssi_translation - cls.translation_mean.to(device)) / cls.translation_std.to(device) + + return PoseTarget( + x_instance_scale=ssi_scale, + x_instance_rotation=ssi_rotation, + x_instance_translation=ssi_translation, + x_scene_scale=instance_pose.scene_scale, + x_scene_center=instance_pose.scene_shift, + x_translation_scale=torch.ones_like(ssi_scale)[..., 0].unsqueeze(-1), + pose_target_convention=cls.pose_target_convention, + ) + + @classmethod + def to_instance_pose(cls, pose_target: PoseTarget, normalize: bool = False) -> InstancePose: + scene_scale = pose_target.x_scene_scale + scene_shift = pose_target.x_scene_center + ssi_to_metric = cls.ssi_to_metric(scene_scale, scene_shift) + + if normalize: + device = pose_target.x_instance_scale.device + pose_target.x_instance_scale = pose_target.x_instance_scale * cls.scale_std.to(device) + cls.scale_mean.to(device) + pose_target.x_instance_translation = pose_target.x_instance_translation * cls.translation_std.to(device) + cls.translation_mean.to(device) + + ins_scale, ins_rotation, ins_translation = InstancePose._broadcast_postcompose( + scale=pose_target.x_instance_scale, + rotation=pose_target.x_instance_rotation, + translation=pose_target.x_instance_translation, + transform_to_postcompose=ssi_to_metric, + ) + + return InstancePose( + instance_scale_l2c=ins_scale, + instance_position_l2c=ins_translation, + instance_quaternion_l2c=ins_rotation, + scene_scale=scene_scale, + scene_shift=scene_shift, + ) + + @classmethod + def to_invariant(cls, pose_target: PoseTarget, normalize: bool = False) -> InvariantPoseTarget: + instance_pose = cls.to_instance_pose(pose_target, normalize=normalize) + return InvariantPoseTarget.from_instance_pose(instance_pose) + + @classmethod + def from_invariant(cls, invariant_targets: InvariantPoseTarget, normalize: bool = False) -> PoseTarget: + instance_pose = InvariantPoseTarget.to_instance_pose(invariant_targets) + return cls.from_instance_pose(instance_pose, normalize=normalize) + + @classmethod + def get_scale_and_shift(cls, pointmap): + shift_z = pointmap[..., -1].nanmedian().unsqueeze(0) + shift = torch.zeros_like(shift_z.expand(1, 3)) + shift[..., -1] = shift_z + + shifted_pointmap = pointmap - shift + scale = shifted_pointmap.abs().nanmean().to(shift.device) + + shift = shift.reshape(3) + scale = scale.expand(3) + + return scale, shift + + @staticmethod + def ssi_to_metric(scale: torch.Tensor, shift: torch.Tensor): + if scale.ndim == 1: + scale = scale.unsqueeze(0) + if shift.ndim == 1: + shift = shift.unsqueeze(0) + return Transform3d().scale(scale).translate(shift).to(shift.device) + + +class ScaleShiftInvariantWTranslationScale(PoseTargetConvention): + """ + + Midas eq. (6): https://arxiv.org/pdf/1907.01341v3 + But for pointmaps (see MoGe): https://arxiv.org/pdf/2410.19115 + """ + + pose_target_convention: str = "ScaleShiftInvariantWTranslationScale" + scale_mean = torch.tensor([1.0232692956924438, 1.0232691764831543, 1.0232692956924438]).to(torch.float32) + scale_std = torch.tensor([1.3773751258850098, 1.3773752450942993, 1.3773750066757202]).to(torch.float32) + translation_mean = torch.tensor([0.003191213821992278, 0.017236359417438507, 0.9401122331619263]).to(torch.float32) + translation_std = torch.tensor([1.341888666152954, 0.7665449380874634, 3.175130605697632]).to(torch.float32) + + @classmethod + def from_instance_pose(cls, instance_pose: InstancePose, normalize: bool = False) -> PoseTarget: + metric_to_ssi = cls.ssi_to_metric( + instance_pose.scene_scale, instance_pose.scene_shift + ).inverse() + + ssi_scale, ssi_rotation, ssi_translation = InstancePose._broadcast_postcompose( + scale=instance_pose.instance_scale_l2c, + rotation=instance_pose.instance_quaternion_l2c, + translation=instance_pose.instance_position_l2c, + transform_to_postcompose=metric_to_ssi, + ) + + ssi_translation_scale = ssi_translation.norm(dim=-1, keepdim=True) + ssi_translation_unit = ssi_translation / ssi_translation_scale.clamp_min(1e-7) + + return PoseTarget( + x_instance_scale=ssi_scale, + x_instance_rotation=ssi_rotation, + x_instance_translation=ssi_translation_unit, + x_scene_scale=instance_pose.scene_scale, + x_scene_center=instance_pose.scene_shift, + x_translation_scale=ssi_translation_scale, + pose_target_convention=cls.pose_target_convention, + ) + + @classmethod + def to_instance_pose(cls, pose_target: PoseTarget, normalize: bool = False) -> InstancePose: + scene_scale = pose_target.x_scene_scale + scene_shift = pose_target.x_scene_center + ssi_to_metric = cls.ssi_to_metric(scene_scale, scene_shift) + + ins_translation_unit = pose_target.x_instance_translation / pose_target.x_instance_translation.norm(dim=-1, keepdim=True) + ins_translation = ins_translation_unit * pose_target.x_translation_scale + + + ins_scale, ins_rotation, ins_translation = InstancePose._broadcast_postcompose( + scale=pose_target.x_instance_scale, + rotation=pose_target.x_instance_rotation, + translation=ins_translation, + transform_to_postcompose=ssi_to_metric, + ) + + + return InstancePose( + instance_scale_l2c=ins_scale, + instance_position_l2c=ins_translation, + instance_quaternion_l2c=ins_rotation, + scene_scale=scene_scale, + scene_shift=scene_shift, + ) + + @classmethod + def to_invariant(cls, pose_target: PoseTarget) -> InvariantPoseTarget: + instance_pose = cls.to_instance_pose(pose_target) + return InvariantPoseTarget.from_instance_pose(instance_pose) + + @classmethod + def from_invariant(cls, invariant_targets: InvariantPoseTarget) -> PoseTarget: + instance_pose = InvariantPoseTarget.to_instance_pose(invariant_targets) + return cls.from_instance_pose(instance_pose) + + @classmethod + def get_scale_and_shift(cls, pointmap): + shift_z = pointmap[..., -1].nanmedian().unsqueeze(0) + shift = torch.zeros_like(shift_z.expand(1, 3)) + shift[..., -1] = shift_z + + shifted_pointmap = pointmap - shift + scale = shifted_pointmap.abs().nanmean().to(shift.device) + + shift = shift.reshape(3) + scale = scale.expand(3) + + return scale, shift + + @staticmethod + def ssi_to_metric(scale: torch.Tensor, shift: torch.Tensor): + if scale.ndim == 1: + scale = scale.unsqueeze(0) + if shift.ndim == 1: + shift = shift.unsqueeze(0) + return Transform3d().scale(scale).translate(shift).to(shift.device) + + +class DisparitySpace(PoseTargetConvention): + pose_target_convention: str = "DisparitySpace" + + @classmethod + def from_instance_pose(cls, instance_pose: InstancePose, normalize: bool = False) -> PoseTarget: + + # x_instance_scale = orig_scale / scene_scale + # x_instance_translation = [x/z, y/z, 0] / scene_scale + # x_translation_scale = z / scene_scale + assert torch.allclose(instance_pose.scene_scale, torch.ones_like(instance_pose.scene_scale)) + + if not instance_pose.scene_shift.ndim == instance_pose.instance_position_l2c.ndim - 1: + raise ValueError(f"scene_shift must be (N+1)D and instance_position_l2c must be (N+1)D, but got {instance_pose.scene_shift.ndim} and {instance_pose.instance_position_l2c.ndim}") + shift_xy, shift_z_log = instance_pose.scene_shift.unsqueeze(-2).split([2, 1], dim=-1) + + + pose_xy, pose_z = instance_pose.instance_position_l2c.split([2, 1], dim=-1) + # Handle batch dimensions properly + if shift_xy.ndim < pose_xy.ndim: + shift_xy = shift_xy.unsqueeze(-2) + pose_xy_scaled = pose_xy / pose_z - shift_xy + + pose_z_scaled_log = torch.log(pose_z) - shift_z_log + x_instance_scale_log = torch.log(instance_pose.instance_scale_l2c) - torch.log(pose_z) + + x_instance_translation = torch.cat([pose_xy_scaled, torch.zeros_like(pose_z)], dim=-1) + x_translation_scale = torch.exp(pose_z_scaled_log) + x_instance_scale = torch.exp(x_instance_scale_log) + + + + return PoseTarget( + x_instance_scale=x_instance_scale, + x_instance_translation=x_instance_translation, + x_instance_rotation=instance_pose.instance_quaternion_l2c, + x_scene_scale=instance_pose.scene_scale, + x_scene_center=instance_pose.scene_shift, + x_translation_scale=x_translation_scale, + pose_target_convention=cls.pose_target_convention, + ) + + @classmethod + def to_instance_pose(cls, pose_target: PoseTarget, normalize: bool = False) -> InstancePose: + scene_scale = pose_target.x_scene_scale + scene_shift = pose_target.x_scene_center + + if not pose_target.x_scene_center.ndim == pose_target.x_instance_translation.ndim - 1: + raise ValueError(f"x_scene_center must be (N+1)D and x_instance_translation must be (N+1)D, but got {pose_target.x_scene_center.ndim} and {pose_target.x_instance_translation.ndim}") + shift_xy, shift_z_log = pose_target.x_scene_center.unsqueeze(-2).split([2, 1], dim=-1) + scene_z_scale = torch.exp(shift_z_log) + + z = pose_target.x_translation_scale + ins_translation = pose_target.x_instance_translation.clone() + ins_translation[...,2] = 1.0 + ins_translation[...,:2] = ins_translation[...,:2] + shift_xy + ins_translation = ins_translation * z * scene_z_scale + + ins_scale = pose_target.x_instance_scale * z * scene_z_scale + + return InstancePose( + instance_scale_l2c=ins_scale * scene_scale, + instance_position_l2c=ins_translation * scene_scale, + instance_quaternion_l2c=pose_target.x_instance_rotation, + scene_scale=scene_scale, + scene_shift=scene_shift, + ) + + @classmethod + def to_invariant(cls, pose_target: PoseTarget, normalize: bool = False) -> InvariantPoseTarget: + instance_pose = cls.to_instance_pose(pose_target, normalize=normalize) + return InvariantPoseTarget.from_instance_pose(instance_pose) + + @classmethod + def from_invariant(cls, invariant_targets: InvariantPoseTarget, normalize: bool = False) -> PoseTarget: + instance_pose = InvariantPoseTarget.to_instance_pose(invariant_targets) + return cls.from_instance_pose(instance_pose, normalize=normalize) + + + +class NormalizedSceneScale(PoseTargetConvention): + """ + x_instance_scale and x_translation_scale are normalized to x_scene_scale + """ + + pose_target_convention: str = "NormalizedSceneScale" + + @classmethod + def from_invariant(cls, invariant_targets: InvariantPoseTarget): + translation = invariant_targets.t_unit * invariant_targets.t_rel_norm + return PoseTarget( + x_instance_scale=invariant_targets.s_rel, + x_instance_rotation=invariant_targets.q, + x_instance_translation=translation, + x_scene_scale=invariant_targets.s_scene, + x_scene_center=invariant_targets.t_scene_center, + x_translation_scale=torch.ones_like(invariant_targets.t_rel_norm), + pose_target_convention=cls.pose_target_convention, + ) + + @classmethod + def to_invariant(cls, pose_target: PoseTarget): + t_rel_norm = torch.norm( + pose_target.x_instance_translation, dim=-1, keepdim=True + ) + return InvariantPoseTarget( + s_scene=pose_target.x_scene_scale, + s_rel=pose_target.x_instance_scale, + q=pose_target.x_instance_rotation, + t_unit=pose_target.x_instance_translation / t_rel_norm, + t_rel_norm=t_rel_norm, + t_scene_center=pose_target.x_scene_center, + ) + + +class Naive(PoseTargetConvention): + pose_target_convention: str = "Naive" + + @classmethod + def from_invariant(cls, invariant_targets: InvariantPoseTarget): + s_scene = invariant_targets.s_rel * invariant_targets.s_scene + t_scene = invariant_targets.t_unit * invariant_targets.t_rel_norm + return PoseTarget( + x_instance_scale=s_scene, + x_instance_rotation=invariant_targets.q, + x_instance_translation=t_scene, + x_scene_scale=invariant_targets.s_scene, + x_scene_center=invariant_targets.t_scene_center, + x_translation_scale=torch.ones_like(invariant_targets.t_rel_norm), + pose_target_convention=cls.pose_target_convention, + ) + + @classmethod + def to_invariant(cls, pose_target: PoseTarget): + s_scene = pose_target.x_scene_scale + t_rel_norm = torch.norm( + pose_target.x_instance_translation, dim=-1, keepdim=True + ) + return InvariantPoseTarget( + s_scene=s_scene, + t_scene_center=pose_target.x_scene_center, + s_rel=pose_target.x_instance_scale / s_scene, + q=pose_target.x_instance_rotation, + t_unit=pose_target.x_instance_translation / t_rel_norm, + t_rel_norm=t_rel_norm, + ) + + +class NormalizedSceneScaleAndTranslation(PoseTargetConvention): + """ + x_instance_scale and x_translation_scale are normalized to x_scene_scale + x_instance_translation is unit + """ + + pose_target_convention: str = "NormalizedSceneScaleAndTranslation" + + @classmethod + def from_invariant(cls, invariant_targets: InvariantPoseTarget): + return PoseTarget( + x_instance_scale=invariant_targets.s_rel, + x_instance_rotation=invariant_targets.q, + x_instance_translation=invariant_targets.t_unit, + x_scene_scale=invariant_targets.s_scene, + x_scene_center=invariant_targets.t_scene_center, + x_translation_scale=invariant_targets.t_rel_norm, + pose_target_convention=cls.pose_target_convention, + ) + + @classmethod + def to_invariant(cls, pose_target: PoseTarget): + return InvariantPoseTarget( + s_scene=pose_target.x_scene_scale, + t_scene_center=pose_target.x_scene_center, + s_rel=pose_target.x_instance_scale, + q=pose_target.x_instance_rotation, + t_unit=pose_target.x_instance_translation, + t_rel_norm=pose_target.x_translation_scale, + ) + + +class ApparentSize(PoseTargetConvention): + pose_target_convention: str = "ApparentSize" + + @classmethod + def from_invariant(cls, invariant_targets: InvariantPoseTarget): + return PoseTarget( + x_instance_scale=invariant_targets.s_tilde, + x_instance_rotation=invariant_targets.q, + x_instance_translation=invariant_targets.t_unit, + x_scene_scale=invariant_targets.s_scene, + x_scene_center=invariant_targets.t_scene_center, + x_translation_scale=invariant_targets.t_rel_norm, + pose_target_convention=cls.pose_target_convention, + ) + + @classmethod + def to_invariant(cls, pose_target: PoseTarget): + return InvariantPoseTarget( + s_scene=pose_target.x_scene_scale, + t_scene_center=pose_target.x_scene_center, + s_tilde=pose_target.x_instance_scale, + q=pose_target.x_instance_rotation, + t_unit=pose_target.x_instance_translation, + t_rel_norm=pose_target.x_translation_scale, + ) + + +class Identity(PoseTargetConvention): + """ + Identity convention - no transformation applied. + Direct passthrough mapping between instance pose and pose target values. + This preserves all values including scene_scale and scene_shift. + """ + + pose_target_convention: str = "Identity" + + @classmethod + def from_instance_pose(cls, instance_pose: InstancePose) -> PoseTarget: + return PoseTarget( + x_instance_scale=instance_pose.instance_scale_l2c, + x_instance_rotation=instance_pose.instance_quaternion_l2c, + x_instance_translation=instance_pose.instance_position_l2c, + x_scene_scale=instance_pose.scene_scale, + x_scene_center=instance_pose.scene_shift, + x_translation_scale=torch.ones_like(instance_pose.instance_scale_l2c)[..., 0].unsqueeze(-1), + pose_target_convention=cls.pose_target_convention, + ) + + @classmethod + def to_instance_pose(cls, pose_target: PoseTarget) -> InstancePose: + return InstancePose( + instance_scale_l2c=pose_target.x_instance_scale, + instance_position_l2c=pose_target.x_instance_translation, + instance_quaternion_l2c=pose_target.x_instance_rotation, + scene_scale=pose_target.x_scene_scale, + scene_shift=pose_target.x_scene_center, + ) + + @classmethod + def to_invariant(cls, pose_target: PoseTarget) -> InvariantPoseTarget: + instance_pose = cls.to_instance_pose(pose_target) + return InvariantPoseTarget.from_instance_pose(instance_pose) + + @classmethod + def from_invariant(cls, invariant_targets: InvariantPoseTarget) -> PoseTarget: + instance_pose = InvariantPoseTarget.to_instance_pose(invariant_targets) + return cls.from_instance_pose(instance_pose) + + +class PoseTargetConverter: + @staticmethod + def pose_target_to_instance_pose(pose_target: PoseTarget, normalize: bool = False) -> InstancePose: + _convention_class = globals()[pose_target.pose_target_convention] + if _convention_class == ScaleShiftInvariant: + return _convention_class.to_instance_pose(pose_target, normalize=normalize) + else: + return _convention_class.to_instance_pose(pose_target) + + @staticmethod + def instance_pose_to_pose_target( + instance_pose: InstancePose, pose_target_convention: str, normalize: bool = False + ) -> PoseTarget: + _convention_class = globals()[pose_target_convention] + if _convention_class == ScaleShiftInvariant: + return _convention_class.from_instance_pose(instance_pose, normalize=normalize) + else: + return _convention_class.from_instance_pose(instance_pose) + + @staticmethod + def dicts_instance_pose_to_pose_target( + pose_target_convention: str, + **kwargs, + ): + instance_pose = InstancePose(**kwargs) + pose_target = PoseTargetConverter.instance_pose_to_pose_target( + instance_pose, pose_target_convention + ) + return asdict(pose_target) + + @staticmethod + def dicts_pose_target_to_instance_pose( + **kwargs, + ): + pose_target_convention = kwargs.get("pose_target_convention") + _convention_class = globals()[pose_target_convention] + assert ( + _convention_class.pose_target_convention == pose_target_convention + ), f"Normalization name mismatch: {_convention_class.pose_target_convention} != {pose_target_convention}" + + normalize = kwargs.pop("normalize", False) + pose_target = PoseTarget(**kwargs) + instance_pose = PoseTargetConverter.pose_target_to_instance_pose(pose_target, normalize) + return asdict(instance_pose) + + +class LogScaleShiftNormalizer: + def __init__(self, shift_log: torch.Tensor = 0.0, scale_log: torch.Tensor = 1.0): + self.shift_log = shift_log + self.scale_log = scale_log + + def normalize(self, value: torch.Tensor): + return torch.log(value) - self.shift_log / self.scale_log + + def denormalize(self, value: torch.Tensor): + return torch.exp(value * self.scale_log + self.shift_log) \ No newline at end of file diff --git a/int8/vendor/sam3d_objects/data/dataset/tdfy/preprocessor.py b/int8/vendor/sam3d_objects/data/dataset/tdfy/preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..837c85d0fedf87588d0fd883eb5d366c51385e7f --- /dev/null +++ b/int8/vendor/sam3d_objects/data/dataset/tdfy/preprocessor.py @@ -0,0 +1,203 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +import warnings +import torch +import logging; logger = logging.getLogger(__name__) +from dataclasses import dataclass +from typing import Callable, Optional +import warnings + +from .img_and_mask_transforms import ( + SSIPointmapNormalizer, +) + + +# Load and process data +@dataclass +class PreProcessor: + """ + Preprocessor configuration for image, mask, and pointmap transforms. + + Transform application order: + 1. Pointmap normalization (if normalize_pointmap=True) + 2. Joint transforms (img_mask_pointmap_joint_transform or img_mask_joint_transform) + 3. Individual transforms (img_transform, mask_transform, pointmap_transform) + + For backward compatibility, img_mask_joint_transform is preserved. When both + img_mask_pointmap_joint_transform and img_mask_joint_transform are present, + img_mask_pointmap_joint_transform takes priority. + """ + + img_transform: Callable = (None,) + mask_transform: Callable = (None,) + img_mask_joint_transform: list[Callable] = (None,) + rgb_img_mask_joint_transform: list[Callable] = (None,) + + # New fields for pointmap support + pointmap_transform: Callable = (None,) + img_mask_pointmap_joint_transform: list[Callable] = (None,) + + # Pointmap normalization option + normalize_pointmap: bool = False + pointmap_normalizer: Optional[Callable] = None + rgb_pointmap_normalizer: Optional[Callable] = None + + def __post_init__(self): + if self.pointmap_normalizer is None: + self.pointmap_normalizer = SSIPointmapNormalizer() + if self.normalize_pointmap == False: + warnings.warn("normalize_pointmap is also set to False, which means we will return the moments but not normalize the pointmap. This supports old unnormalized pointmap models, but this is dangerous behavior.", DeprecationWarning, stacklevel=2) + + if self.rgb_pointmap_normalizer is None: + logger.warning("No rgb pointmap normalizer provided, using scale + shift ") + self.rgb_pointmap_normalizer = self.pointmap_normalizer + + + def _normalize_pointmap( + self, pointmap: torch.Tensor, + mask: torch.Tensor, + pointmap_normalizer: Callable, + scale: Optional[torch.Tensor] = None, + shift: Optional[torch.Tensor] = None, + ): + if pointmap is None: + return pointmap, None, None + + if self.normalize_pointmap == False: + # old behavior: Pose is normalized to the pointmap center, but pointmap is not + _, pointmap_scale, pointmap_shift = pointmap_normalizer.normalize(pointmap, mask) + return pointmap, pointmap_scale, pointmap_shift + + if scale is not None or shift is not None: + return pointmap_normalizer.normalize(pointmap, mask, scale, shift) + + return pointmap_normalizer.normalize(pointmap, mask) + + def _process_image_mask_pointmap_mess( + self, rgb_image, rgb_image_mask, pointmap=None + ): + """Extended version that handles pointmaps""" + + # Apply pointmap normalization if enabled + pointmap_for_crop, pointmap_scale, pointmap_shift = self._normalize_pointmap( + pointmap, rgb_image_mask, self.pointmap_normalizer + ) + + # Apply transforms to the original full rgb image and mask. + rgb_image, rgb_image_mask = self._preprocess_rgb_image_mask(rgb_image, rgb_image_mask) + + # These two are typically used for getting cropped images of the object + # : first apply joint transforms + processed_rgb_image, processed_mask, processed_pointmap = ( + self._preprocess_image_mask_pointmap(rgb_image, rgb_image_mask, pointmap_for_crop) + ) + # : then apply individual transforms on top of the joint transforms + processed_rgb_image = self._apply_transform( + processed_rgb_image, self.img_transform + ) + processed_mask = self._apply_transform(processed_mask, self.mask_transform) + if processed_pointmap is not None: + processed_pointmap = self._apply_transform( + processed_pointmap, self.pointmap_transform + ) + + # This version is typically the full version of the image + # : apply individual transforms only + rgb_image = self._apply_transform(rgb_image, self.img_transform) + rgb_image_mask = self._apply_transform(rgb_image_mask, self.mask_transform) + + rgb_pointmap, rgb_pointmap_scale, rgb_pointmap_shift = self._normalize_pointmap( + pointmap, rgb_image_mask, self.rgb_pointmap_normalizer, pointmap_scale, pointmap_shift + ) + + if rgb_pointmap is not None: + rgb_pointmap = self._apply_transform(rgb_pointmap, self.pointmap_transform) + + result = { + "mask": processed_mask, + "image": processed_rgb_image, + "rgb_image": rgb_image, + "rgb_image_mask": rgb_image_mask, + } + + # Add pointmap results if available + if processed_pointmap is not None: + result.update( + { + "pointmap": processed_pointmap, + "rgb_pointmap": rgb_pointmap, + } + ) + + # Add normalization parameters if normalization was applied + if pointmap_scale is not None and pointmap_shift is not None: + result.update( + { + "pointmap_scale": pointmap_scale, + "pointmap_shift": pointmap_shift, + "rgb_pointmap_scale": rgb_pointmap_scale, + "rgb_pointmap_shift": rgb_pointmap_shift, + } + ) + + return result + + def _process_image_and_mask_mess(self, rgb_image, rgb_image_mask): + """Original method - calls extended version without pointmap""" + return self._process_image_mask_pointmap_mess(rgb_image, rgb_image_mask, None) + + def _preprocess_rgb_image_mask(self, rgb_image: torch.Tensor, rgb_image_mask: torch.Tensor): + """Apply joint transforms to rgb_image and rgb_image_mask.""" + if ( + self.rgb_img_mask_joint_transform != (None,) + and self.rgb_img_mask_joint_transform is not None + ): + for trans in self.rgb_img_mask_joint_transform: + rgb_image, rgb_image_mask = trans(rgb_image, rgb_image_mask) + return rgb_image, rgb_image_mask + + def _preprocess_image_mask_pointmap(self, rgb_image, mask_image, pointmap=None): + """Apply joint transforms with priority: triple transforms > dual transforms.""" + # Priority: img_mask_pointmap_joint_transform when pointmap is provided + if ( + self.img_mask_pointmap_joint_transform != (None,) + and self.img_mask_pointmap_joint_transform is not None + and pointmap is not None + ): + for trans in self.img_mask_pointmap_joint_transform: + rgb_image, mask_image, pointmap = trans( + rgb_image, mask_image, pointmap=pointmap + ) + return rgb_image, mask_image, pointmap + + # Fallback: img_mask_joint_transform (existing behavior) + elif ( + self.img_mask_joint_transform != (None,) + and self.img_mask_joint_transform is not None + ): + for trans in self.img_mask_joint_transform: + rgb_image, mask_image = trans(rgb_image, mask_image) + return rgb_image, mask_image, pointmap + + return rgb_image, mask_image, pointmap + + def _preprocess_image_and_mask(self, rgb_image, mask_image): + """Backward compatibility wrapper - only applies dual transforms""" + rgb_image, mask_image, _ = self._preprocess_image_mask_pointmap( + rgb_image, mask_image, None + ) + return rgb_image, mask_image + + # keep here for backward compatibility + def _preprocess_image_and_mask_inference(self, rgb_image, mask_image): + warnings.warn( + "The _preprocess_image_and_mask_inference is deprecated! Please use _preprocess_image_and_mask", + category=DeprecationWarning, + stacklevel=2, + ) + return self._preprocess_image_and_mask(rgb_image, mask_image) + + def _apply_transform(self, input: torch.Tensor, transform): + if input is not None and transform is not None and transform != (None,): + input = transform(input) + + return input \ No newline at end of file diff --git a/int8/vendor/sam3d_objects/data/dataset/tdfy/transforms_3d.py b/int8/vendor/sam3d_objects/data/dataset/tdfy/transforms_3d.py new file mode 100644 index 0000000000000000000000000000000000000000..af8aace24fadbb510dd194d2c954063d45b9725d --- /dev/null +++ b/int8/vendor/sam3d_objects/data/dataset/tdfy/transforms_3d.py @@ -0,0 +1,50 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +from collections import namedtuple +import math +import torch + +from pytorch3d.transforms import ( + Rotate, + Translate, + Scale, + Transform3d, + quaternion_to_matrix, + axis_angle_to_quaternion, +) + +DecomposedTransform = namedtuple( + "DecomposedTransform", ["scale", "rotation", "translation"] +) + + +def compose_transform( + scale: torch.Tensor, rotation: torch.Tensor, translation: torch.Tensor +) -> Transform3d: + """ + Args: + scale: (..., 3) tensor of scale factors + rotation: (..., 3, 3) tensor of rotation matrices + translation: (..., 3) tensor of translation vectors + """ + tfm = Transform3d(dtype=scale.dtype, device=scale.device) + return tfm.scale(scale).rotate(rotation).translate(translation) + + +def decompose_transform(transform: Transform3d) -> DecomposedTransform: + """ + Returns: + scale: (..., 3) tensor of scale factors + rotation: (..., 3, 3) tensor of rotation matrices + translation: (..., 3) tensor of translation vectors + """ + matrices = transform.get_matrix() + scale = torch.norm(matrices[:, :3, :3], dim=-1) + rotation = matrices[:, :3, :3] / scale.unsqueeze(-1) # Normalize rotation matrix + translation = matrices[:, 3, :3] # Extract translation vector + return DecomposedTransform(scale, rotation, translation) + + +def get_rotation_about_x_axis(angle: float = math.pi / 2) -> torch.Tensor: + axis = torch.tensor([1.0, 0.0, 0.0]) + axis_angle = axis * angle + return axis_angle_to_quaternion(axis_angle) diff --git a/int8/vendor/sam3d_objects/data/utils.py b/int8/vendor/sam3d_objects/data/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9ce8e9e2d2604a16b05c2ece22c7834ddaed6e40 --- /dev/null +++ b/int8/vendor/sam3d_objects/data/utils.py @@ -0,0 +1,28 @@ +# From sam3d_objects/data/utils.py (SAM License): expand_right / expand_as_right as they are; +# tree_tensor_map on torch.utils._pytree instead of optree. +import torch +from torch.utils import _pytree + + +def tree_tensor_map(fn, tree, *rest): + return _pytree.tree_map(fn, tree, *rest) + + +def expand_right(tensor, target_shape): + """ + e.g. Takes tensor of (a, b, c) and returns a tensor of (a, b, c, 1, 1, ...) + """ + current_shape = tensor.shape + dims_to_add = len(target_shape) - len(current_shape) + result = tensor + for _ in range(dims_to_add): + result = result.unsqueeze(-1) + expand_shape = list(current_shape) + [-1] * dims_to_add + for i in range(len(target_shape)): + if i < len(expand_shape) and expand_shape[i] == -1: + expand_shape[i] = target_shape[i] + return result.expand(*expand_shape) + + +def expand_as_right(tensor, target): + return expand_right(tensor, target.shape) diff --git a/int8/vendor/sam3d_objects/model/__init__.py b/int8/vendor/sam3d_objects/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/int8/vendor/sam3d_objects/model/backbone/__init__.py b/int8/vendor/sam3d_objects/model/backbone/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/int8/vendor/sam3d_objects/model/backbone/dit/__init__.py b/int8/vendor/sam3d_objects/model/backbone/dit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/int8/vendor/sam3d_objects/model/backbone/dit/embedder/__init__.py b/int8/vendor/sam3d_objects/model/backbone/dit/embedder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/int8/vendor/sam3d_objects/model/backbone/dit/embedder/point_remapper.py b/int8/vendor/sam3d_objects/model/backbone/dit/embedder/point_remapper.py new file mode 100644 index 0000000000000000000000000000000000000000..0cb68814411591473cf11b47c1338cda74a278c2 --- /dev/null +++ b/int8/vendor/sam3d_objects/model/backbone/dit/embedder/point_remapper.py @@ -0,0 +1,78 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +import torch +import torch.nn as nn + + +class PointRemapper(nn.Module): + """Handles remapping of 3D point coordinates and their inverse transformations.""" + + VALID_TYPES = ["linear", "sinh", "exp", "sinh_exp", "exp_disparity"] + + def __init__(self, remap_type: str = "exp"): + super().__init__() + self.remap_type = remap_type + + if remap_type not in self.VALID_TYPES: + raise ValueError( + f"Invalid remap type: {remap_type}. Must be one of {self.VALID_TYPES}" + ) + + def forward(self, points: torch.Tensor) -> torch.Tensor: + """Apply remapping to point coordinates.""" + if self.remap_type == "linear": + return points + + elif self.remap_type == "sinh": + return torch.asinh(points) + + elif self.remap_type == "exp": + xy_scaled, z_exp = points.split([2, 1], dim=-1) + # Use log1p for better numerical stability near zero + z = torch.log1p(z_exp) + xy = xy_scaled / (1 + z_exp) + return torch.cat([xy, z], dim=-1) + + elif self.remap_type == "exp_disparity": + xy_scaled, z_exp = points.split([2, 1], dim=-1) + xy = xy_scaled / z_exp + z = torch.log(z_exp) + return torch.cat([xy, z], dim=-1) + + elif self.remap_type == "sinh_exp": + xy_sinh, z_exp = points.split([2, 1], dim=-1) + xy = torch.asinh(xy_sinh) + z = torch.log(z_exp.clamp(min=1e-8)) + return torch.cat([xy, z], dim=-1) + + else: + raise ValueError(f"Unknown remap type: {self.remap_type}") + + def inverse(self, points: torch.Tensor) -> torch.Tensor: + """Apply inverse remapping to recover original point coordinates.""" + if self.remap_type == "linear": + return points + + elif self.remap_type == "sinh": + return torch.sinh(points) + + elif self.remap_type == "exp": + xy, z = points.split([2, 1], dim=-1) + # Inverse of log1p is expm1(z) = exp(z) - 1 + z_exp = torch.expm1(z) + # Inverse of xy/(1+z_exp) is xy*(1+z_exp) + return torch.cat([xy * (1 + z_exp), z_exp], dim=-1) + + elif self.remap_type == "exp_disparity": + xy, z = points.split([2, 1], dim=-1) + z_exp = torch.exp(z) + return torch.cat([xy * z_exp, z_exp], dim=-1) + + elif self.remap_type == "sinh_exp": + xy, z = points.split([2, 1], dim=-1) + return torch.cat([torch.sinh(xy), torch.exp(z)], dim=-1) + + else: + raise ValueError(f"Unknown remap type: {self.remap_type}") + + def extra_repr(self) -> str: + return f"remap_type='{self.remap_type}'" diff --git a/int8/vendor/sam3d_objects/pipeline/__init__.py b/int8/vendor/sam3d_objects/pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/int8/vendor/sam3d_objects/pipeline/inference_utils.py b/int8/vendor/sam3d_objects/pipeline/inference_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..aa5b0b26753bf0f184dbf370153d250d3b84566c --- /dev/null +++ b/int8/vendor/sam3d_objects/pipeline/inference_utils.py @@ -0,0 +1,252 @@ +# From sam3d_objects/pipeline/inference_utils.py (SAM License): the pose decoder and the sparse-structure +# pruning / downsampling, as they are. +import torch +import numpy as np +import logging +logger = logging.getLogger(__name__) +from pytorch3d.transforms import quaternion_to_matrix, Transform3d, matrix_to_quaternion +from sam3d_objects.data.dataset.tdfy.transforms_3d import compose_transform, decompose_transform +from sam3d_objects.data.dataset.tdfy.pose_target import PoseTargetConverter + + +ROTATION_6D_MEAN = torch.tensor( + [ + -0.06366084883674913, + 0.008438224692279752, + 0.00017084786438302483, + 0.0007126610473540038, + -0.0030916726538816417, + 0.5166093753457688, + ] +) + + +ROTATION_6D_STD = torch.tensor( + [ + 0.6656971967514863, + 0.6787012271867754, + 0.30345010594844524, + 0.4394504420678794, + 0.39817973931717104, + 0.6176286868761914, + ] +) + + +def pose_decoder( + pose_target_convention, +): + def decode(model_output_dict, scene_scale=None, scene_shift=None): + x = model_output_dict + + # BEGIN: copied from generative.py + key_mapping = { + "shape": "x_shape_latent", + "quaternion": "x_instance_rotation", + "6drotation": "x_instance_rotation_6d", + "6drotation_normalized": "x_instance_rotation_6d_normalized", + "translation": "x_instance_translation", + "scale": "x_instance_scale", + "translation_scale": "x_translation_scale", + } + + # Decodes for metrics + pose_target_dict = {} + for k, v in x.items(): + pose_target_dict[key_mapping.get(k, k)] = v + + # TODO: Hao & Bowen please do clean this up! + # Convert 6D rotation to quaternion if needed + if ( + "x_instance_rotation_6d" in pose_target_dict + or "x_instance_rotation_6d_normalized" in pose_target_dict + ): + # Extract the two 3D vectors + if "x_instance_rotation_6d_normalized" in pose_target_dict: + rot_6d = pose_target_dict[ + "x_instance_rotation_6d_normalized" + ] * ROTATION_6D_STD.to( + pose_target_dict["x_instance_rotation_6d_normalized"].device + ) + ROTATION_6D_MEAN.to( + pose_target_dict["x_instance_rotation_6d_normalized"].device + ) + else: + rot_6d = pose_target_dict["x_instance_rotation_6d"] + a1 = rot_6d[..., 0:3] + a2 = rot_6d[..., 3:6] + + # Normalize first vector + b1 = torch.nn.functional.normalize(a1, dim=-1) + + # Make second vector orthogonal to first + b2 = a2 - torch.sum(b1 * a2, dim=-1, keepdim=True) * b1 + b2 = torch.nn.functional.normalize(b2, dim=-1) + + # Compute third vector as cross product + b3 = torch.cross(b1, b2, dim=-1) + + # Stack to create rotation matrix + rotation_matrix = torch.stack([b1, b2, b3], dim=-1) + + # Convert to quaternion + quaternion = matrix_to_quaternion(rotation_matrix) + pose_target_dict["x_instance_rotation"] = quaternion + + if "x_instance_scale" in pose_target_dict: + pose_target_dict["x_instance_scale"] = torch.exp( + pose_target_dict["x_instance_scale"] + ) + + if "x_translation_scale" in pose_target_dict: + pose_target_dict["x_translation_scale"] = torch.exp( + pose_target_dict["x_translation_scale"] + ) + + pose_target_dict["pose_target_convention"] = [pose_target_convention] * x[ + "shape" + ].shape[0] + # END: copied from generative.py + + # Fake pointmap moments + device = x["shape"].device + _scene_scale = ( + scene_scale if scene_scale is not None else torch.tensor(1.0, device=device) + ) + _scene_shift = ( + scene_shift + if scene_shift is not None + else torch.tensor([[0, 0, 0]], device=device) + ) + pose_target_dict["x_scene_scale"] = _scene_scale + pose_target_dict["x_scene_center"] = _scene_shift + + # Convert to instance pose + pose_instance_dict = PoseTargetConverter.dicts_pose_target_to_instance_pose( + pose_target_convention=pose_target_convention, + x_instance_scale=pose_target_dict["x_instance_scale"], + x_instance_translation=pose_target_dict["x_instance_translation"], + x_instance_rotation=pose_target_dict["x_instance_rotation"], + x_translation_scale=pose_target_dict["x_translation_scale"], + x_scene_scale=pose_target_dict["x_scene_scale"], + x_scene_center=pose_target_dict["x_scene_center"], + ) + return { + "translation": pose_instance_dict["instance_position_l2c"].squeeze(0), + "rotation": pose_instance_dict["instance_quaternion_l2c"].squeeze(0), + "scale": pose_instance_dict["instance_scale_l2c"].squeeze(0).mean(-1, keepdim=True).expand(1,3), + } + + return decode + + +def prune_sparse_structure( + coord_batch, + max_neighbor_axes_dist=1, +): + coords, batch = coord_batch[:, 1:], coord_batch[:, 0].unsqueeze(-1) + device = coords.device + # 1) shift coords so minimum is zero + min_xyz = coords.min(0)[0] + coords0 = coords - min_xyz + # 2) build occupancy grid + max_xyz = coords0.max(0)[0] + 1 # size in each dim + D, H, W = max_xyz.tolist() + # shape (1,1,D,H,W) + occ = torch.zeros((1, 1, D, H, W), dtype=torch.uint8, device=device) + x, y, z = coords0.unbind(1) + occ[0, 0, x, y, z] = 1 + # 3) 3×3×3 convolution to count each voxel + neighbors + kernel = torch.ones( + ( + 1, + 1, + 2 * max_neighbor_axes_dist + 1, + 2 * max_neighbor_axes_dist + 1, + 2 * max_neighbor_axes_dist + 1, + ), + dtype=torch.uint8, + device=device, + ) + # pad so output is same size + pad = max_neighbor_axes_dist + counts = torch.nn.functional.conv3d(occ.float(), kernel.float(), padding=pad) + # interior voxels have count == (2*max_neighbor_axes_dist+1)**3 + full_count = (2 * max_neighbor_axes_dist + 1) ** 3 + # 4) lookup counts at each original coord + counts_at_pts = counts[0, 0, x, y, z] # (N,) + is_surface = counts_at_pts < full_count + # 5) return filtered batch+coords (shift back if you want original coords) + kept = is_surface.nonzero(as_tuple=False).squeeze(1) + out_batch = batch[kept] + out_coords = coords[kept] + coords = torch.cat([out_batch, out_coords], dim=1) + + return torch.cat([out_batch, out_coords], dim=1) + + +def downsample_sparse_structure( + coord_batch, + max_coords=42000, + downsample_factor=2, +): + """ + Downsample sparse structure coordinates when there are more than max_coords. + + Downsamples by rescaling coordinates, effectively shrinking the grid while preserving + the structure. The downsampled grid is centered in the original space. + + Args: + coord_batch: tensor of shape (N, 4) where [:, 0] is batch index and [:, 1:] are coords + max_coords: maximum number of coordinates to keep + 42000 should be safe number. Calculation: max(int32) / (64*768) ~= 43691 + Only needed for mesh decoding. + downsample_factor: factor by which to downsample (e.g., 2 means half resolution) + + Returns: + Downsampled coord_batch with coordinates rescaled if downsampling is needed + """ + if coord_batch.shape[0] <= max_coords: + return coord_batch, 1 + + # Extract coordinates and batch indices + coords = coord_batch[:, 1:].float() # Shape: (N, 3), convert to float for scaling + batch_indices = coord_batch[:, 0:1] # Shape: (N, 1) + + # Find the actual coordinate bounds + coords_min = coords.min(dim=0)[0] # Shape: (3,) + coords_max = coords.max(dim=0)[0] # Shape: (3,) + original_size = coords_max - coords_min + 1 # Add 1 since coordinates are discrete + + # Calculate target size after downsampling + target_size = original_size / downsample_factor + + # Calculate the offset to center the downsampled grid + offset = (original_size - target_size) / 2 + target_min = coords_min + offset + target_max = coords_min + offset + target_size - 1 + + # Normalize coordinates to [0, 1] within their actual range + coords_normalized = (coords - coords_min) / (coords_max - coords_min) + + # Scale to the target range + coords_rescaled = coords_normalized * (target_size - 1) + target_min + + # Round to integers to get discrete grid coordinates + coords_rescaled = torch.round(coords_rescaled).int() + + # Clamp to ensure we stay within bounds + coords_rescaled = torch.clamp(coords_rescaled, target_min.int(), target_max.int()) + + # Remove duplicates that may have been created by the downsampling + # Concatenate batch and coords for duplicate removal + combined = torch.cat([batch_indices, coords_rescaled], dim=1) + unique_combined = torch.unique(combined, dim=0) + + # If still too many after deduplication, randomly subsample + if unique_combined.shape[0] > max_coords: + indices = torch.randperm(unique_combined.shape[0], device=coord_batch.device)[ + :max_coords + ] + unique_combined = unique_combined[indices] + + return unique_combined.int(), downsample_factor