int8 build of SAM 3D Objects
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+10
- int8/LICENSE-FlexiCubes.txtAdded+202
- int8/LICENSE-SAM.txtAdded+52
- int8/LICENSE-TRELLIS.txtAdded+21
- int8/__pycache__/pipeline.cpython-310.pycAdded
- int8/__pycache__/pipeline_tables.cpython-310.pycAdded
- int8/dino.onnxAdded+3
- int8/dino.onnx.dataAdded+3
- int8/flexicubes_tables.npzAdded+3
- int8/mesh_conv.onnxAdded+3
- int8/mesh_conv.onnx.dataAdded+3
- int8/mesh_dec.onnxAdded+3
- int8/mesh_dec.onnx.dataAdded+3
- int8/mesh_gn.onnxAdded+3
- int8/mesh_out.onnxAdded+3
- int8/mesh_out.onnx.dataAdded+3
- int8/moge.onnxAdded+3
- int8/moge.onnx.dataAdded+3
- int8/moge_pos_embed.npyAdded+3
- int8/pipeline.pyAdded+386
- int8/pipeline_tables.pyAdded+251
- int8/sam3d.jsonAdded+43
- int8/slat_flow.onnxAdded+3
- int8/slat_flow.onnx.dataAdded+3
- int8/slat_fuse.onnxAdded+3
- int8/slat_fuse.onnx.dataAdded+3
- int8/ss_dec.onnxAdded+3
- int8/ss_dec.onnx.dataAdded+3
- int8/ss_flow.onnxAdded+3
- int8/ss_flow.onnx.dataAdded+3
- int8/ss_fuse.onnxAdded+3
- int8/ss_fuse.onnx.dataAdded+3
- int8/vendor/LICENSE-MoGe.txtAdded+224
- int8/vendor/moge_min.pyAdded+116
- int8/vendor/pytorch3d/LICENSE-pytorch3d.txtAdded+30
- int8/vendor/pytorch3d/__init__.pyAdded+1
- int8/vendor/pytorch3d/common/__init__.pyAdded+1
- int8/vendor/pytorch3d/common/datatypes.pyAdded+60
- int8/vendor/pytorch3d/common/workaround/__init__.pyAdded+10
- int8/vendor/pytorch3d/common/workaround/symeig3x3.pyAdded+319
- int8/vendor/pytorch3d/common/workaround/utils.pyAdded+33
- int8/vendor/pytorch3d/transforms/__init__.pyAdded+41
- int8/vendor/pytorch3d/transforms/math.pyAdded+87
- int8/vendor/pytorch3d/transforms/rotation_conversions.pyAdded+601
- int8/vendor/pytorch3d/transforms/se3.pyAdded+223
- int8/vendor/pytorch3d/transforms/so3.pyAdded+270
- int8/vendor/pytorch3d/transforms/transform3d.pyAdded+909
- int8/vendor/sam3d_objects/LICENSE-SAM.txtAdded+52
- int8/vendor/sam3d_objects/__init__.pyAdded
- int8/vendor/sam3d_objects/data/__init__.pyAdded
42 unmodified lines4344454647484950515253545542 unmodified linesfp16/ss_dec.onnx.data filter=lfs diff=lfs merge=lfs -textfp16/ss_flow.onnx.data filter=lfs diff=lfs merge=lfs -textfp16/ss_fuse.onnx.data filter=lfs diff=lfs merge=lfs -textint8/dino.onnx.data filter=lfs diff=lfs merge=lfs -textint8/mesh_conv.onnx.data filter=lfs diff=lfs merge=lfs -textint8/mesh_dec.onnx.data filter=lfs diff=lfs merge=lfs -textint8/mesh_out.onnx.data filter=lfs diff=lfs merge=lfs -textint8/moge.onnx.data filter=lfs diff=lfs merge=lfs -textint8/slat_flow.onnx.data filter=lfs diff=lfs merge=lfs -textint8/slat_fuse.onnx.data filter=lfs diff=lfs merge=lfs -textint8/ss_dec.onnx.data filter=lfs diff=lfs merge=lfs -textint8/ss_flow.onnx.data filter=lfs diff=lfs merge=lfs -textint8/ss_fuse.onnx.data filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
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.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152SAM LicenseLast 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.123456789101112131415161718192021 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
SOFTWARE123version https://git-lfs.github.com/spec/v1oid sha256:4abdace1d2457b71d31b13696c4c3ef38eee0a909aa399079b1e5fbf8335d914size 345956123version https://git-lfs.github.com/spec/v1oid sha256:7dac4b145524d5245118c339b16ee1214ca0d4a972651e21874b999a5db86cd3size 1217486848123version https://git-lfs.github.com/spec/v1oid sha256:1d22bf7f2ec21cf0832e550593630551071f7bd26175c896f2361f82fd44786esize 2639123version https://git-lfs.github.com/spec/v1oid sha256:011ad908aa43800f5f994f6bdac82842b1e3b15ea38cee01777d890d9e314bf4size 26364123version https://git-lfs.github.com/spec/v1oid sha256:b039cb6b1cc1b6f32de79fda78315702e5db74bc71cc84d3ff4cdf65d1da2c82size 995328123version https://git-lfs.github.com/spec/v1oid sha256:4f251f0f0f158639cb06c6efc098516d5f78074518a14a11a42b55e9604d4197size 938468123version https://git-lfs.github.com/spec/v1oid sha256:747c4ef56d3d20aabba9a2a583e6372feb559d482e694b9faf652dc93d409658size 180317184123version https://git-lfs.github.com/spec/v1oid sha256:9f14e6e0daeed0a83d74af1bc63b15df70916d119297891c0e52bc5b012abfaesize 3139123version https://git-lfs.github.com/spec/v1oid sha256:81d16b8a1ae14a98b39d6f69b2162b70ce08f3cf2a3a03174031522126eca9d8size 27608123version https://git-lfs.github.com/spec/v1oid sha256:7464356dda053776c20d151b45f20aa6659faeb8c3b99c8bbf4f100f2e4bf500size 573312123version https://git-lfs.github.com/spec/v1oid sha256:bed5a78f547ff24d8009161a9c61a23a55b12907318253f6a78dcf8bedaa1191size 468757123version https://git-lfs.github.com/spec/v1oid sha256:63bcec2af5473b171329533fc7c9fad7cc8bb337e4abf4dd7a67b8f61bab392dsize 1251070464123version https://git-lfs.github.com/spec/v1oid sha256:73231693ad7d6dd37eeb9b6ab790dfa4198c68770856f1450ce348aff7da73d9size 5611648123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386"""SAM 3D Objects (Meta: a picture and an object mask -> the object's 3D mesh with vertex colours and its pose in thecamera) with ONNX Runtime, reproducing InferencePipelinePointMap.run as the official notebook calls it (no meshpost-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 argparseimport jsonimport mathimport sysimport timefrom pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parentsys.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.0TIME_SCALE = 1000.0POSE_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 -> -yCAM_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 GroupNormMESH_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)
# ---------------------------------------------------------------- samplersdef 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 pipelineclass 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()})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251"""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)12345678910111213141516171819202122232425262728293031323334353637383940414243{
"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
}
}123version https://git-lfs.github.com/spec/v1oid sha256:c930ecc4a1f423c8b571a25db278ef0849c76063ce11d0c72a481e856efcd6e3size 2031725123version https://git-lfs.github.com/spec/v1oid sha256:c0171fc2ada14808bdd41567e47b89cd61115ef51fe97bd326fa419d6881ad2csize 677782688123version https://git-lfs.github.com/spec/v1oid sha256:7046a06fe344ca5ef7e21ef8275908cff6241bb1b88a94dba533991dc47b7606size 8331123version https://git-lfs.github.com/spec/v1oid sha256:12e4f839d54f8fc46fa608755b0056912d187be899a6e6d1d2c3b4f8b1b3fd47size 69230592123version https://git-lfs.github.com/spec/v1oid sha256:c972c906757750ee25fcf51570958118c6aed4d9fb651a85b61b96e942906e6bsize 38730123version https://git-lfs.github.com/spec/v1oid sha256:cd5672e0eed77106948402a3fb3911e53f496c3e79f8dcb3efac5df21c079853size 294676864123version https://git-lfs.github.com/spec/v1oid sha256:cc314370ada72e18c3f31f56a172f8ae16dab9d905a12c3d92f48cea2c0bdc8fsize 3012727123version https://git-lfs.github.com/spec/v1oid sha256:c1b2ab3534475e2385735a7e6e1f4db74b3b2ee3057b1cca4a5bda08828e8157size 1038223722123version https://git-lfs.github.com/spec/v1oid sha256:e17b0b21223e736563538ddb23a8da66a85e170838fec19bc837ca96a24223afsize 57190123version https://git-lfs.github.com/spec/v1oid sha256:147c69c125551f57fb830129481c374c18e916ad73964e53fd7e9a4398c406ecsize 102957056123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116# 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_shift123456789101112131415161718192021222324252627282930BSD 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.1__version__ = "0.7.8" # vendored subset: transforms/ and common/ (BSD)1from .datatypes import Device, get_device, make_device123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# 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")12345678910# 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_3x3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319# 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)123456789101112131415161718192021222324252627282930313233# 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 det1234567891011121314151617181920212223242526272829303132333435363738394041# 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("_")]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687# 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601# 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,))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223# 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_angles123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270# 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 h123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909# 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)
return12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152SAM 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..gitattributes+10
int8/LICENSE-FlexiCubes.txtAdded+202
int8/LICENSE-SAM.txtAdded+52
int8/LICENSE-TRELLIS.txtAdded+21
int8/__pycache__/pipeline.cpython-310.pycAdded
int8/__pycache__/pipeline_tables.cpython-310.pycAdded
int8/dino.onnxAdded+3
int8/dino.onnx.dataAdded+3
int8/flexicubes_tables.npzAdded+3
int8/mesh_conv.onnxAdded+3
int8/mesh_conv.onnx.dataAdded+3
int8/mesh_dec.onnxAdded+3
int8/mesh_dec.onnx.dataAdded+3
int8/mesh_gn.onnxAdded+3
int8/mesh_out.onnxAdded+3
int8/mesh_out.onnx.dataAdded+3
int8/moge.onnxAdded+3
int8/moge.onnx.dataAdded+3
int8/moge_pos_embed.npyAdded+3
int8/pipeline.pyAdded+386
int8/pipeline_tables.pyAdded+251
int8/sam3d.jsonAdded+43
int8/slat_flow.onnxAdded+3
int8/slat_flow.onnx.dataAdded+3
int8/slat_fuse.onnxAdded+3
int8/slat_fuse.onnx.dataAdded+3
int8/ss_dec.onnxAdded+3
int8/ss_dec.onnx.dataAdded+3
int8/ss_flow.onnxAdded+3
int8/ss_flow.onnx.dataAdded+3
int8/ss_fuse.onnxAdded+3
int8/ss_fuse.onnx.dataAdded+3
int8/vendor/LICENSE-MoGe.txtAdded+224
int8/vendor/moge_min.pyAdded+116
int8/vendor/pytorch3d/LICENSE-pytorch3d.txtAdded+30
int8/vendor/pytorch3d/__init__.pyAdded+1
int8/vendor/pytorch3d/common/__init__.pyAdded+1
int8/vendor/pytorch3d/common/datatypes.pyAdded+60
int8/vendor/pytorch3d/common/workaround/__init__.pyAdded+10
int8/vendor/pytorch3d/common/workaround/symeig3x3.pyAdded+319
int8/vendor/pytorch3d/common/workaround/utils.pyAdded+33
int8/vendor/pytorch3d/transforms/__init__.pyAdded+41
int8/vendor/pytorch3d/transforms/math.pyAdded+87
int8/vendor/pytorch3d/transforms/rotation_conversions.pyAdded+601
int8/vendor/pytorch3d/transforms/se3.pyAdded+223
int8/vendor/pytorch3d/transforms/so3.pyAdded+270
int8/vendor/pytorch3d/transforms/transform3d.pyAdded+909
int8/vendor/sam3d_objects/LICENSE-SAM.txtAdded+52
int8/vendor/sam3d_objects/__init__.pyAdded
int8/vendor/sam3d_objects/data/__init__.pyAdded