fp16 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
- fp16/LICENSE-FlexiCubes.txtAdded+202
- fp16/LICENSE-SAM.txtAdded+52
- fp16/LICENSE-TRELLIS.txtAdded+21
- fp16/__pycache__/pipeline.cpython-310.pycAdded
- fp16/__pycache__/pipeline_tables.cpython-310.pycAdded
- fp16/dino.onnxAdded+3
- fp16/dino.onnx.dataAdded+3
- fp16/flexicubes_tables.npzAdded+3
- fp16/mesh_conv.onnxAdded+3
- fp16/mesh_conv.onnx.dataAdded+3
- fp16/mesh_dec.onnxAdded+3
- fp16/mesh_dec.onnx.dataAdded+3
- fp16/mesh_gn.onnxAdded+3
- fp16/mesh_out.onnxAdded+3
- fp16/mesh_out.onnx.dataAdded+3
- fp16/moge.onnxAdded+3
- fp16/moge.onnx.dataAdded+3
- fp16/moge_pos_embed.npyAdded+3
- fp16/pipeline.pyAdded+386
- fp16/pipeline_tables.pyAdded+251
- fp16/sam3d.jsonAdded+43
- fp16/slat_flow.onnxAdded+3
- fp16/slat_flow.onnx.dataAdded+3
- fp16/slat_fuse.onnxAdded+3
- fp16/slat_fuse.onnx.dataAdded+3
- fp16/ss_dec.onnxAdded+3
- fp16/ss_dec.onnx.dataAdded+3
- fp16/ss_flow.onnxAdded+3
- fp16/ss_flow.onnx.dataAdded+3
- fp16/ss_fuse.onnxAdded+3
- fp16/ss_fuse.onnx.dataAdded+3
- fp16/vendor/LICENSE-MoGe.txtAdded+224
- fp16/vendor/__pycache__/moge_min.cpython-310.pycAdded
- fp16/vendor/moge_min.pyAdded+116
- fp16/vendor/pytorch3d/LICENSE-pytorch3d.txtAdded+30
- fp16/vendor/pytorch3d/__init__.pyAdded+1
- fp16/vendor/pytorch3d/__pycache__/__init__.cpython-310.pycAdded
- fp16/vendor/pytorch3d/common/__init__.pyAdded+1
- fp16/vendor/pytorch3d/common/__pycache__/__init__.cpython-310.pycAdded
- fp16/vendor/pytorch3d/common/__pycache__/datatypes.cpython-310.pycAdded
- fp16/vendor/pytorch3d/common/datatypes.pyAdded+60
- fp16/vendor/pytorch3d/common/workaround/__init__.pyAdded+10
- fp16/vendor/pytorch3d/common/workaround/__pycache__/__init__.cpython-310.pycAdded
- fp16/vendor/pytorch3d/common/workaround/__pycache__/symeig3x3.cpython-310.pycAdded
- fp16/vendor/pytorch3d/common/workaround/__pycache__/utils.cpython-310.pycAdded
- fp16/vendor/pytorch3d/common/workaround/symeig3x3.pyAdded+319
- fp16/vendor/pytorch3d/common/workaround/utils.pyAdded+33
- fp16/vendor/pytorch3d/transforms/__init__.pyAdded+41
- fp16/vendor/pytorch3d/transforms/__pycache__/__init__.cpython-310.pycAdded
32 unmodified lines3334353637383940414243444532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textfp16/dino.onnx.data filter=lfs diff=lfs merge=lfs -textfp16/mesh_conv.onnx.data filter=lfs diff=lfs merge=lfs -textfp16/mesh_dec.onnx.data filter=lfs diff=lfs merge=lfs -textfp16/mesh_out.onnx.data filter=lfs diff=lfs merge=lfs -textfp16/moge.onnx.data filter=lfs diff=lfs merge=lfs -textfp16/slat_flow.onnx.data filter=lfs diff=lfs merge=lfs -textfp16/slat_fuse.onnx.data filter=lfs diff=lfs merge=lfs -textfp16/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 -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:934a9a3c9f1497eff5230d3bc65b28134b79cb264ad736cba40656e328ab6240size 1959965123version https://git-lfs.github.com/spec/v1oid sha256:a7604b23aaf5fff576ba27d980a1403bb45905b00ce3d61c763c3549c822c33bsize 1203701280123version 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:8c6f3de387ea873bea29f16587ba78706a6d6a20894a0665cc7aff9a296b552bsize 2903255123version https://git-lfs.github.com/spec/v1oid sha256:d27cd65f33135c1c1c30dbb84a3a2582f9a44ed62d1481ca2377b167d4fad973size 1937102890123version 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("_")].gitattributes+10
fp16/LICENSE-FlexiCubes.txtAdded+202
fp16/LICENSE-SAM.txtAdded+52
fp16/LICENSE-TRELLIS.txtAdded+21
fp16/__pycache__/pipeline.cpython-310.pycAdded
fp16/__pycache__/pipeline_tables.cpython-310.pycAdded
fp16/dino.onnxAdded+3
fp16/dino.onnx.dataAdded+3
fp16/flexicubes_tables.npzAdded+3
fp16/mesh_conv.onnxAdded+3
fp16/mesh_conv.onnx.dataAdded+3
fp16/mesh_dec.onnxAdded+3
fp16/mesh_dec.onnx.dataAdded+3
fp16/mesh_gn.onnxAdded+3
fp16/mesh_out.onnxAdded+3
fp16/mesh_out.onnx.dataAdded+3
fp16/moge.onnxAdded+3
fp16/moge.onnx.dataAdded+3
fp16/moge_pos_embed.npyAdded+3
fp16/pipeline.pyAdded+386
fp16/pipeline_tables.pyAdded+251
fp16/sam3d.jsonAdded+43
fp16/slat_flow.onnxAdded+3
fp16/slat_flow.onnx.dataAdded+3
fp16/slat_fuse.onnxAdded+3
fp16/slat_fuse.onnx.dataAdded+3
fp16/ss_dec.onnxAdded+3
fp16/ss_dec.onnx.dataAdded+3
fp16/ss_flow.onnxAdded+3
fp16/ss_flow.onnx.dataAdded+3
fp16/ss_fuse.onnxAdded+3
fp16/ss_fuse.onnx.dataAdded+3
fp16/vendor/LICENSE-MoGe.txtAdded+224
fp16/vendor/__pycache__/moge_min.cpython-310.pycAdded
fp16/vendor/moge_min.pyAdded+116
fp16/vendor/pytorch3d/LICENSE-pytorch3d.txtAdded+30
fp16/vendor/pytorch3d/__init__.pyAdded+1
fp16/vendor/pytorch3d/__pycache__/__init__.cpython-310.pycAdded
fp16/vendor/pytorch3d/common/__init__.pyAdded+1
fp16/vendor/pytorch3d/common/__pycache__/__init__.cpython-310.pycAdded
fp16/vendor/pytorch3d/common/__pycache__/datatypes.cpython-310.pycAdded
fp16/vendor/pytorch3d/common/datatypes.pyAdded+60
fp16/vendor/pytorch3d/common/workaround/__init__.pyAdded+10
fp16/vendor/pytorch3d/common/workaround/__pycache__/__init__.cpython-310.pycAdded
fp16/vendor/pytorch3d/common/workaround/__pycache__/symeig3x3.cpython-310.pycAdded
fp16/vendor/pytorch3d/common/workaround/__pycache__/utils.cpython-310.pycAdded
fp16/vendor/pytorch3d/common/workaround/symeig3x3.pyAdded+319
fp16/vendor/pytorch3d/common/workaround/utils.pyAdded+33
fp16/vendor/pytorch3d/transforms/__init__.pyAdded+41
fp16/vendor/pytorch3d/transforms/__pycache__/__init__.cpython-310.pycAdded