Instructions to use OzzyGT/Pixal3D_Modular with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use OzzyGT/Pixal3D_Modular with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("OzzyGT/Pixal3D_Modular", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
Add Pixal3D modular blocks
Browse files- .gitignore +1 -0
- LICENSE +201 -0
- LICENSE-PIXAL3D +21 -0
- NOTICE +6 -0
- README.md +83 -0
- decoders.py +207 -0
- denoise.py +261 -0
- encoders.py +209 -0
- guidance.py +82 -0
- modular_blocks_pixal3d.py +183 -0
- modular_config.json +7 -0
- normalization.py +136 -0
- projection.py +87 -0
- resolvable.py +19 -0
- stages.py +75 -0
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
LICENSE-PIXAL3D
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Tencent.
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
NOTICE
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The camera projection (projection.py) and the latent normalization statistics (normalization.py) are adapted from:
|
| 2 |
+
Pixal3D, Copyright (c) 2026 Tencent, MIT (see LICENSE-PIXAL3D).
|
| 3 |
+
https://github.com/TencentARC/Pixal3D
|
| 4 |
+
Reference revision: f7cf384
|
| 5 |
+
The remaining block code is original and licensed under Apache-2.0 (see LICENSE).
|
| 6 |
+
The package contains no learned weights. Converted checkpoint licensing is separate.
|
README.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
library_name: diffusers
|
| 4 |
+
pipeline_tag: image-to-3d
|
| 5 |
+
base_model:
|
| 6 |
+
- TencentARC/Pixal3D
|
| 7 |
+
tags:
|
| 8 |
+
- pixal3d
|
| 9 |
+
- modular-diffusers
|
| 10 |
+
- image-to-3d
|
| 11 |
+
---
|
| 12 |
+
# Pixal3D Modular
|
| 13 |
+
|
| 14 |
+
Modular Diffusers blocks for [Pixal3D](https://github.com/TencentARC/Pixal3D), from a prepared image to sparse geometry and material attributes. Model code and converted weights are packaged separately in `Pixal3D`.
|
| 15 |
+
|
| 16 |
+
## Usage
|
| 17 |
+
|
| 18 |
+
Requires PyTorch, Diffusers with Modular Pipelines, Transformers with DINOv3 support, Accelerate, Safetensors, NumPy and Pillow. Tested with Diffusers `0.41.0` and Transformers `5.20.2`.
|
| 19 |
+
|
| 20 |
+
```python
|
| 21 |
+
import math
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from diffusers import ModularPipelineBlocks
|
| 25 |
+
from diffusers.utils import load_image
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
blocks = ModularPipelineBlocks.from_pretrained(
|
| 29 |
+
"OzzyGT/Pixal3D_Modular",
|
| 30 |
+
trust_remote_code=True,
|
| 31 |
+
components_repo="OzzyGT/Pixal3D",
|
| 32 |
+
trust_components_code=True,
|
| 33 |
+
)
|
| 34 |
+
pipe = blocks.init_pipeline()
|
| 35 |
+
flow_names = (
|
| 36 |
+
"sparse_structure_flow_model",
|
| 37 |
+
"shape_slat_flow_model_512",
|
| 38 |
+
"shape_slat_flow_model_1024",
|
| 39 |
+
"tex_slat_flow_model_1024",
|
| 40 |
+
)
|
| 41 |
+
dtypes = {spec.name: torch.float32 for spec in blocks.expected_components}
|
| 42 |
+
dtypes.update({name: torch.bfloat16 for name in (*flow_names, "image_encoder")})
|
| 43 |
+
pipe.load_components(dtype=dtypes)
|
| 44 |
+
pipe.to("cuda")
|
| 45 |
+
|
| 46 |
+
image = load_image("https://huggingface.co/datasets/OzzyGT/diffusers-examples/resolve/main/Pixal3D/Pixal3D_jester_input.png")
|
| 47 |
+
result = pipe(
|
| 48 |
+
image=image,
|
| 49 |
+
camera_angle_x=math.radians(33.85),
|
| 50 |
+
distance=1.643,
|
| 51 |
+
mesh_scale=1.0,
|
| 52 |
+
resolution=1024,
|
| 53 |
+
num_inference_steps=12,
|
| 54 |
+
generator=torch.Generator().manual_seed(42),
|
| 55 |
+
output=["geometry", "materials", "actual_resolution"],
|
| 56 |
+
)
|
| 57 |
+
geometry = result["geometry"]
|
| 58 |
+
materials = result["materials"]
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
The bf16 model does not fit fully on a 32 GB GPU; use CPU offloading or the SDNQ [INT8](https://huggingface.co/OzzyGT/Pixal3D_sdnq_dynamic_8bit) and [INT4](https://huggingface.co/OzzyGT/Pixal3D_sdnq_dynamic_4bit) versions.
|
| 62 |
+
|
| 63 |
+
The example uses `trust_remote_code=True`, which loads these blocks, and `trust_components_code=True`, which allows the model repository's custom classes.
|
| 64 |
+
|
| 65 |
+
> **Note:** both flags run Python code downloaded from the Hub: `trust_remote_code=True` runs the code of the blocks repository, and `trust_components_code=True` runs the code shipped in the `components_repo`. Only use them with repositories you trust, and review their code before passing different ones.
|
| 66 |
+
|
| 67 |
+
Input is one prepared RGB/RGBA image. RGBA is composited on black, then resized; there is no automatic foreground extraction or crop. Camera parameters must correspond to that prepared image.
|
| 68 |
+
|
| 69 |
+
## Outputs
|
| 70 |
+
|
| 71 |
+
- `geometry`: integer `(batch, x, y, z)` cell coordinates, vertex offsets, three edge-intersection flags and quad weights for flexible-dual-grid extraction.
|
| 72 |
+
- `materials`: matching cell coordinates and six attributes, with layout `base_color[0:3]`, `metallic[3:4]`, `roughness[4:5]`, `alpha[5:6]`.
|
| 73 |
+
- `actual_resolution`: effective grid resolution. A 1536 request can fall back in steps of 128 to 1024 when the token limit is exceeded.
|
| 74 |
+
|
| 75 |
+
Coordinates retain the original model convention (Y-up in the reference mesh viewer). Grid positions become normalized object coordinates through `(cell + vertex_offset) / actual_resolution - 0.5`; these are not meters. No game-engine axis conversion or mesh export is performed. Mesh extraction, hole filling and texture baking are separate operations for the consumer.
|
| 76 |
+
|
| 77 |
+
The blocks expose image encoding, NAF upsampling, projection, denoising, normalization and decoding as separate stages. The initial workflow supports one view and one sample. The four flow stages use their own scheduler/guider components, with the shape stages sharing settings. Guidance rescaling follows Pixal3D's clean-sample calculation.
|
| 78 |
+
|
| 79 |
+
## Licensing
|
| 80 |
+
|
| 81 |
+
The blocks are [Apache-2.0](LICENSE), with the camera projection and latent statistics adapted from [TencentARC/Pixal3D](https://github.com/TencentARC/Pixal3D) under [MIT](LICENSE-PIXAL3D). See [NOTICE](NOTICE). This repository contains no model weights. Model components retain their own licenses: Pixal3D MIT, NAF Apache-2.0, and DINOv3's separate terms. See the model repository's license files and provenance notice. No background-removal or preview-rendering dependencies are included.
|
| 82 |
+
|
| 83 |
+
Validation: pretrained flow/structure components passed FP32 reference checks. NAF matched native NATTEN at 64, 512 and 1024 feature sizes (maximum error 0.0000141). Both sparse decoders matched the original FlexGEMM FP32 implementation on a latent patch, including identical subdivision coordinates (maximum error 0.000168). Full 12-step generation passed at 1024 and 1536 on RTX 5090. The tested mixed-precision setup uses BF16 for DINOv3 and the four flow models, with FP32 NAF and decoders. Synchronous two-block group offloading is verified; asynchronous streaming and other GPUs are not covered by these checks.
|
decoders.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from diffusers import ModelMixin
|
| 3 |
+
from diffusers.modular_pipelines.modular_pipeline_utils import (
|
| 4 |
+
ComponentSpec,
|
| 5 |
+
InputParam,
|
| 6 |
+
OutputParam,
|
| 7 |
+
)
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
|
| 10 |
+
from .resolvable import ResolvableBlock
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Pixal3DStructureDecodeStep(ResolvableBlock):
|
| 14 |
+
model_name = "pixal3d"
|
| 15 |
+
|
| 16 |
+
@property
|
| 17 |
+
def description(self):
|
| 18 |
+
return "Decode structure latents and extract occupied sparse coordinates."
|
| 19 |
+
|
| 20 |
+
@property
|
| 21 |
+
def expected_components(self):
|
| 22 |
+
return self.resolve([ComponentSpec("sparse_structure_decoder", ModelMixin)])
|
| 23 |
+
|
| 24 |
+
@property
|
| 25 |
+
def inputs(self):
|
| 26 |
+
return [
|
| 27 |
+
InputParam("latents", required=True, type_hint=torch.Tensor),
|
| 28 |
+
InputParam(
|
| 29 |
+
"structure_resolution",
|
| 30 |
+
default=32,
|
| 31 |
+
type_hint=int,
|
| 32 |
+
description="Occupancy grid size; the decoded 64^3 grid is max-pooled down to it.",
|
| 33 |
+
),
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
@property
|
| 37 |
+
def intermediate_outputs(self):
|
| 38 |
+
return [OutputParam("coords", type_hint=torch.Tensor)]
|
| 39 |
+
|
| 40 |
+
@torch.no_grad()
|
| 41 |
+
def __call__(self, components, state):
|
| 42 |
+
b = self.get_block_state(state)
|
| 43 |
+
model = components.sparse_structure_decoder
|
| 44 |
+
occupancy = model(b.latents.to(model.device)) > 0
|
| 45 |
+
if occupancy.shape[2] != b.structure_resolution:
|
| 46 |
+
if occupancy.shape[2] % b.structure_resolution:
|
| 47 |
+
raise ValueError("Structure resolution must divide the decoded grid size")
|
| 48 |
+
ratio = occupancy.shape[2] // b.structure_resolution
|
| 49 |
+
occupancy = F.max_pool3d(occupancy.float(), ratio, ratio) > 0.5
|
| 50 |
+
b.coords = torch.argwhere(occupancy)[:, [0, 2, 3, 4]].int()
|
| 51 |
+
self.set_block_state(state, b)
|
| 52 |
+
return components, state
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class Pixal3DShapeUpsampleStep(ResolvableBlock):
|
| 56 |
+
model_name = "pixal3d"
|
| 57 |
+
|
| 58 |
+
@property
|
| 59 |
+
def description(self):
|
| 60 |
+
return "Use the shape decoder to generate the high-resolution sparse coordinate set."
|
| 61 |
+
|
| 62 |
+
@property
|
| 63 |
+
def expected_components(self):
|
| 64 |
+
return self.resolve([ComponentSpec("shape_slat_decoder", ModelMixin)])
|
| 65 |
+
|
| 66 |
+
@property
|
| 67 |
+
def inputs(self):
|
| 68 |
+
return [
|
| 69 |
+
InputParam("shape_latents", required=True, type_hint=torch.Tensor),
|
| 70 |
+
InputParam("coords", required=True, type_hint=torch.Tensor),
|
| 71 |
+
InputParam("resolution", default=1024, type_hint=int, description="Output grid resolution: 1024 or 1536."),
|
| 72 |
+
InputParam(
|
| 73 |
+
"max_num_tokens",
|
| 74 |
+
default=49152,
|
| 75 |
+
type_hint=int,
|
| 76 |
+
description="Token budget; 1536 falls back in steps of 128 until the sparse grid fits.",
|
| 77 |
+
),
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def intermediate_outputs(self):
|
| 82 |
+
return [
|
| 83 |
+
OutputParam("coords", type_hint=torch.Tensor),
|
| 84 |
+
OutputParam("actual_resolution", type_hint=int),
|
| 85 |
+
]
|
| 86 |
+
|
| 87 |
+
@torch.no_grad()
|
| 88 |
+
def __call__(self, components, state):
|
| 89 |
+
b = self.get_block_state(state)
|
| 90 |
+
if b.resolution not in (1024, 1536):
|
| 91 |
+
raise ValueError("Supported resolutions are 1024 and 1536")
|
| 92 |
+
model = components.shape_slat_decoder
|
| 93 |
+
coords = model(
|
| 94 |
+
b.shape_latents[0].to(model.device),
|
| 95 |
+
b.coords.to(model.device),
|
| 96 |
+
upsample_times=4,
|
| 97 |
+
)["coords"]
|
| 98 |
+
resolution = b.resolution
|
| 99 |
+
while True:
|
| 100 |
+
grid = resolution // 16
|
| 101 |
+
quantized = torch.cat(
|
| 102 |
+
[
|
| 103 |
+
coords[:, :1],
|
| 104 |
+
((coords[:, 1:] + 0.5) / 512 * (grid - 1)).round().int(),
|
| 105 |
+
],
|
| 106 |
+
1,
|
| 107 |
+
).unique(dim=0)
|
| 108 |
+
if len(quantized) < b.max_num_tokens or resolution == 1024:
|
| 109 |
+
break
|
| 110 |
+
resolution -= 128
|
| 111 |
+
b.coords = quantized
|
| 112 |
+
b.actual_resolution = resolution
|
| 113 |
+
self.set_block_state(state, b)
|
| 114 |
+
return components, state
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class Pixal3DShapeDecodeStep(ResolvableBlock):
|
| 118 |
+
model_name = "pixal3d"
|
| 119 |
+
|
| 120 |
+
@property
|
| 121 |
+
def description(self):
|
| 122 |
+
return "Decode shape latents into a flexible dual grid and texture subdivision guides."
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
def expected_components(self):
|
| 126 |
+
return self.resolve([ComponentSpec("shape_slat_decoder", ModelMixin)])
|
| 127 |
+
|
| 128 |
+
@property
|
| 129 |
+
def inputs(self):
|
| 130 |
+
return [
|
| 131 |
+
InputParam("shape_latents", required=True, type_hint=torch.Tensor),
|
| 132 |
+
InputParam("coords", required=True, type_hint=torch.Tensor),
|
| 133 |
+
]
|
| 134 |
+
|
| 135 |
+
@property
|
| 136 |
+
def intermediate_outputs(self):
|
| 137 |
+
return [
|
| 138 |
+
OutputParam("geometry", type_hint=dict),
|
| 139 |
+
OutputParam("subdivisions", type_hint=list),
|
| 140 |
+
]
|
| 141 |
+
|
| 142 |
+
@torch.no_grad()
|
| 143 |
+
def __call__(self, components, state):
|
| 144 |
+
b = self.get_block_state(state)
|
| 145 |
+
model = components.shape_slat_decoder
|
| 146 |
+
decoded = model(
|
| 147 |
+
b.shape_latents[0].to(model.device),
|
| 148 |
+
b.coords.to(model.device),
|
| 149 |
+
return_subs=True,
|
| 150 |
+
)
|
| 151 |
+
features = decoded["features"]
|
| 152 |
+
b.geometry = {
|
| 153 |
+
"coords": decoded["coords"],
|
| 154 |
+
"vertex_offsets": 2 * features[:, :3].sigmoid() - 0.5,
|
| 155 |
+
"intersected": features[:, 3:6] > 0,
|
| 156 |
+
"quad_weights": F.softplus(features[:, 6:7]),
|
| 157 |
+
}
|
| 158 |
+
b.subdivisions = decoded["subdivisions"]
|
| 159 |
+
self.set_block_state(state, b)
|
| 160 |
+
return components, state
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class Pixal3DTextureDecodeStep(ResolvableBlock):
|
| 164 |
+
model_name = "pixal3d"
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def description(self):
|
| 168 |
+
return "Decode material attributes on the shape subdivision grid, without texture baking."
|
| 169 |
+
|
| 170 |
+
@property
|
| 171 |
+
def expected_components(self):
|
| 172 |
+
return self.resolve([ComponentSpec("tex_slat_decoder", ModelMixin)])
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def inputs(self):
|
| 176 |
+
return [
|
| 177 |
+
InputParam("texture_latents", required=True, type_hint=torch.Tensor),
|
| 178 |
+
InputParam("coords", required=True, type_hint=torch.Tensor),
|
| 179 |
+
InputParam("subdivisions", required=True, type_hint=list),
|
| 180 |
+
]
|
| 181 |
+
|
| 182 |
+
@property
|
| 183 |
+
def intermediate_outputs(self):
|
| 184 |
+
return [OutputParam("materials", type_hint=dict)]
|
| 185 |
+
|
| 186 |
+
@torch.no_grad()
|
| 187 |
+
def __call__(self, components, state):
|
| 188 |
+
b = self.get_block_state(state)
|
| 189 |
+
model = components.tex_slat_decoder
|
| 190 |
+
guides = [{k: v.to(model.device) for k, v in sub.items()} for sub in b.subdivisions]
|
| 191 |
+
decoded = model(
|
| 192 |
+
b.texture_latents[0].to(model.device),
|
| 193 |
+
b.coords.to(model.device),
|
| 194 |
+
guide_subs=guides,
|
| 195 |
+
)
|
| 196 |
+
b.materials = {
|
| 197 |
+
"coords": decoded["coords"],
|
| 198 |
+
"attributes": decoded["features"] * 0.5 + 0.5,
|
| 199 |
+
"layout": {
|
| 200 |
+
"base_color": [0, 3],
|
| 201 |
+
"metallic": [3, 4],
|
| 202 |
+
"roughness": [4, 5],
|
| 203 |
+
"alpha": [5, 6],
|
| 204 |
+
},
|
| 205 |
+
}
|
| 206 |
+
self.set_block_state(state, b)
|
| 207 |
+
return components, state
|
denoise.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, field
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from diffusers import ModelMixin, SchedulerMixin
|
| 5 |
+
from diffusers.modular_pipelines import LoopSequentialPipelineBlocks
|
| 6 |
+
from diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec, InputParam, OutputParam
|
| 7 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 8 |
+
|
| 9 |
+
from .guidance import Pixal3DGuidance
|
| 10 |
+
from .resolvable import ResolvableBlock
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass(frozen=True)
|
| 14 |
+
class Pixal3DStage:
|
| 15 |
+
"""Components and guidance settings of one flow stage."""
|
| 16 |
+
|
| 17 |
+
transformer: str
|
| 18 |
+
scheduler: str
|
| 19 |
+
guider: str
|
| 20 |
+
guider_config: dict = field(default_factory=dict)
|
| 21 |
+
sparse: bool = True
|
| 22 |
+
concat_cond: bool = False
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
STRUCTURE_STAGE = Pixal3DStage(
|
| 26 |
+
"sparse_structure_flow_model",
|
| 27 |
+
"structure_scheduler",
|
| 28 |
+
"structure_guider",
|
| 29 |
+
{"guidance_scale": 7.5, "guidance_rescale": 0.7, "guidance_interval": (0.6, 1.0)},
|
| 30 |
+
sparse=False,
|
| 31 |
+
)
|
| 32 |
+
SHAPE_GUIDANCE = {"guidance_scale": 7.5, "guidance_rescale": 0.5, "guidance_interval": (0.6, 1.0)}
|
| 33 |
+
SHAPE_LOW_STAGE = Pixal3DStage("shape_slat_flow_model_512", "shape_scheduler", "shape_guider", SHAPE_GUIDANCE)
|
| 34 |
+
SHAPE_HIGH_STAGE = Pixal3DStage("shape_slat_flow_model_1024", "shape_scheduler", "shape_guider", SHAPE_GUIDANCE)
|
| 35 |
+
TEXTURE_STAGE = Pixal3DStage(
|
| 36 |
+
"tex_slat_flow_model_1024",
|
| 37 |
+
"texture_scheduler",
|
| 38 |
+
"texture_guider",
|
| 39 |
+
{"guidance_scale": 1.0, "guidance_rescale": 0.0, "guidance_interval": (0.6, 0.9)},
|
| 40 |
+
concat_cond=True,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Pixal3DPrepareLatentsStep(ResolvableBlock):
|
| 45 |
+
model_name = "pixal3d"
|
| 46 |
+
|
| 47 |
+
def __init__(self, stage: Pixal3DStage):
|
| 48 |
+
self.stage = stage
|
| 49 |
+
super().__init__()
|
| 50 |
+
|
| 51 |
+
@property
|
| 52 |
+
def description(self):
|
| 53 |
+
return "Draw the initial noise for a dense structure volume or for the sparse shape/texture tokens."
|
| 54 |
+
|
| 55 |
+
@property
|
| 56 |
+
def expected_components(self):
|
| 57 |
+
return self.resolve([ComponentSpec(self.stage.transformer, ModelMixin)])
|
| 58 |
+
|
| 59 |
+
@property
|
| 60 |
+
def inputs(self):
|
| 61 |
+
inputs = [InputParam.template("generator")]
|
| 62 |
+
if self.stage.sparse:
|
| 63 |
+
inputs.append(
|
| 64 |
+
InputParam("coords", required=True, type_hint=torch.Tensor, description="Sparse (N, 4) coordinates.")
|
| 65 |
+
)
|
| 66 |
+
if self.stage.concat_cond:
|
| 67 |
+
inputs.append(
|
| 68 |
+
InputParam("concat_cond", required=True, type_hint=torch.Tensor, description="Shape latents.")
|
| 69 |
+
)
|
| 70 |
+
return inputs
|
| 71 |
+
|
| 72 |
+
@property
|
| 73 |
+
def intermediate_outputs(self):
|
| 74 |
+
return [OutputParam("latents", type_hint=torch.Tensor, description="Initial noise for this stage.")]
|
| 75 |
+
|
| 76 |
+
@torch.no_grad()
|
| 77 |
+
def __call__(self, components, state):
|
| 78 |
+
b = self.get_block_state(state)
|
| 79 |
+
config = getattr(components, self.stage.transformer).config
|
| 80 |
+
if not self.stage.sparse:
|
| 81 |
+
shape = (1, config.in_channels, *([config.resolution] * 3))
|
| 82 |
+
else:
|
| 83 |
+
if len(b.coords) == 0:
|
| 84 |
+
raise ValueError("Nonempty sparse coordinates are required")
|
| 85 |
+
channels = config.in_channels - (b.concat_cond.shape[-1] if self.stage.concat_cond else 0)
|
| 86 |
+
shape = (1, len(b.coords), channels)
|
| 87 |
+
b.latents = randn_tensor(
|
| 88 |
+
shape, generator=b.generator, device=components._execution_device, dtype=torch.float32
|
| 89 |
+
)
|
| 90 |
+
self.set_block_state(state, b)
|
| 91 |
+
return components, state
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class Pixal3DSetTimestepsStep(ResolvableBlock):
|
| 95 |
+
model_name = "pixal3d"
|
| 96 |
+
|
| 97 |
+
def __init__(self, stage: Pixal3DStage):
|
| 98 |
+
self.stage = stage
|
| 99 |
+
super().__init__()
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def description(self):
|
| 103 |
+
return "Set the shifted flow-matching sigmas for this stage."
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def expected_components(self):
|
| 107 |
+
return self.resolve([ComponentSpec(self.stage.scheduler, SchedulerMixin)])
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def inputs(self):
|
| 111 |
+
return [InputParam.template("num_inference_steps", default=12)]
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
def intermediate_outputs(self):
|
| 115 |
+
return [OutputParam("timesteps", type_hint=list, description="Sigmas in [0, 1], one per step.")]
|
| 116 |
+
|
| 117 |
+
def __call__(self, components, state):
|
| 118 |
+
b = self.get_block_state(state)
|
| 119 |
+
scheduler = getattr(components, self.stage.scheduler)
|
| 120 |
+
scheduler.set_timesteps(b.num_inference_steps)
|
| 121 |
+
b.timesteps = scheduler.timesteps
|
| 122 |
+
self.set_block_state(state, b)
|
| 123 |
+
return components, state
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class Pixal3DLoopDenoiser(ResolvableBlock):
|
| 127 |
+
model_name = "pixal3d"
|
| 128 |
+
# Conditional batches use the image features; the unconditional batch uses zeros of the same shape.
|
| 129 |
+
_guider_input_fields = {
|
| 130 |
+
"global_features": ("global_features", "negative_global_features"),
|
| 131 |
+
"projected_features": ("projected_features", "negative_projected_features"),
|
| 132 |
+
"latents": "latents",
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
def __init__(self, stage: Pixal3DStage):
|
| 136 |
+
self.stage = stage
|
| 137 |
+
super().__init__()
|
| 138 |
+
|
| 139 |
+
@property
|
| 140 |
+
def description(self):
|
| 141 |
+
return "Step within the denoising loop: run the flow model for each guider batch and combine them."
|
| 142 |
+
|
| 143 |
+
@property
|
| 144 |
+
def expected_components(self):
|
| 145 |
+
return self.resolve(
|
| 146 |
+
[
|
| 147 |
+
ComponentSpec(self.stage.transformer, ModelMixin),
|
| 148 |
+
ComponentSpec(
|
| 149 |
+
self.stage.guider,
|
| 150 |
+
Pixal3DGuidance,
|
| 151 |
+
default_creation_method="from_config",
|
| 152 |
+
config=self.stage.guider_config,
|
| 153 |
+
),
|
| 154 |
+
]
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
@property
|
| 158 |
+
def inputs(self):
|
| 159 |
+
return [
|
| 160 |
+
InputParam("global_features", required=True, type_hint=torch.Tensor, description="DINOv3 global tokens."),
|
| 161 |
+
InputParam(
|
| 162 |
+
"projected_features", required=True, type_hint=torch.Tensor, description="Camera-projected features."
|
| 163 |
+
),
|
| 164 |
+
]
|
| 165 |
+
|
| 166 |
+
@torch.no_grad()
|
| 167 |
+
def __call__(self, components, block_state, i, t):
|
| 168 |
+
model = getattr(components, self.stage.transformer)
|
| 169 |
+
guider = getattr(components, self.stage.guider)
|
| 170 |
+
guider.set_state(step=i, num_inference_steps=len(block_state.timesteps), timestep=t)
|
| 171 |
+
batches = guider.prepare_inputs_from_block_state(block_state, self._guider_input_fields)
|
| 172 |
+
latents = block_state.latents
|
| 173 |
+
timestep = torch.full((latents.shape[0],), 1000 * t, device=latents.device, dtype=torch.float32)
|
| 174 |
+
for batch in batches:
|
| 175 |
+
guider.prepare_models(model)
|
| 176 |
+
batch.noise_pred = model(
|
| 177 |
+
latents,
|
| 178 |
+
timestep,
|
| 179 |
+
batch.global_features,
|
| 180 |
+
batch.projected_features,
|
| 181 |
+
coords=block_state.model_coords,
|
| 182 |
+
concat_cond=block_state.model_concat_cond,
|
| 183 |
+
)
|
| 184 |
+
guider.cleanup_models(model)
|
| 185 |
+
block_state.noise_pred = guider(batches).pred
|
| 186 |
+
return components, block_state
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class Pixal3DLoopAfterDenoiser(ResolvableBlock):
|
| 190 |
+
model_name = "pixal3d"
|
| 191 |
+
|
| 192 |
+
def __init__(self, stage: Pixal3DStage):
|
| 193 |
+
self.stage = stage
|
| 194 |
+
super().__init__()
|
| 195 |
+
|
| 196 |
+
@property
|
| 197 |
+
def description(self):
|
| 198 |
+
return "Step within the denoising loop: take one Euler step with the guided velocity."
|
| 199 |
+
|
| 200 |
+
@property
|
| 201 |
+
def expected_components(self):
|
| 202 |
+
return self.resolve([ComponentSpec(self.stage.scheduler, SchedulerMixin)])
|
| 203 |
+
|
| 204 |
+
@torch.no_grad()
|
| 205 |
+
def __call__(self, components, block_state, i, t):
|
| 206 |
+
scheduler = getattr(components, self.stage.scheduler)
|
| 207 |
+
prediction = block_state.noise_pred
|
| 208 |
+
block_state.latents = scheduler.step(prediction, t, block_state.latents.to(prediction.device)).prev_sample
|
| 209 |
+
return components, block_state
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class Pixal3DDenoiseLoop(LoopSequentialPipelineBlocks):
|
| 213 |
+
model_name = "pixal3d"
|
| 214 |
+
|
| 215 |
+
def __init__(self, stage: Pixal3DStage):
|
| 216 |
+
self.stage = stage
|
| 217 |
+
self.block_classes = [Pixal3DLoopDenoiser(stage), Pixal3DLoopAfterDenoiser(stage)]
|
| 218 |
+
self.block_names = ["denoiser", "after_denoiser"]
|
| 219 |
+
super().__init__()
|
| 220 |
+
|
| 221 |
+
@property
|
| 222 |
+
def description(self):
|
| 223 |
+
return (
|
| 224 |
+
"Iteratively denoise one stage's latents over `timesteps`. Each iteration runs:\n"
|
| 225 |
+
" - `Pixal3DLoopDenoiser`: flow model per guider batch, then guidance\n"
|
| 226 |
+
" - `Pixal3DLoopAfterDenoiser`: Euler step"
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
@property
|
| 230 |
+
def loop_inputs(self):
|
| 231 |
+
inputs = [
|
| 232 |
+
InputParam("timesteps", required=True, type_hint=list, description="From the set-timesteps step."),
|
| 233 |
+
InputParam("latents", required=True, type_hint=torch.Tensor, description="From the prepare-latents step."),
|
| 234 |
+
]
|
| 235 |
+
if self.stage.sparse:
|
| 236 |
+
inputs.append(InputParam("coords", required=True, type_hint=torch.Tensor))
|
| 237 |
+
if self.stage.concat_cond:
|
| 238 |
+
inputs.append(InputParam("concat_cond", required=True, type_hint=torch.Tensor))
|
| 239 |
+
return inputs
|
| 240 |
+
|
| 241 |
+
@property
|
| 242 |
+
def loop_intermediate_outputs(self):
|
| 243 |
+
return [OutputParam("latents", type_hint=torch.Tensor, description="Denoised latents of this stage.")]
|
| 244 |
+
|
| 245 |
+
@torch.no_grad()
|
| 246 |
+
def __call__(self, components, state):
|
| 247 |
+
b = self.get_block_state(state)
|
| 248 |
+
device = components._execution_device
|
| 249 |
+
b.latents = b.latents.to(device)
|
| 250 |
+
b.global_features = b.global_features.to(device)
|
| 251 |
+
b.projected_features = b.projected_features.to(device)
|
| 252 |
+
b.negative_global_features = torch.zeros_like(b.global_features)
|
| 253 |
+
b.negative_projected_features = torch.zeros_like(b.projected_features)
|
| 254 |
+
b.model_coords = b.coords[None, :, 1:].to(device) if self.stage.sparse else None
|
| 255 |
+
b.model_concat_cond = b.concat_cond.to(device) if self.stage.concat_cond else None
|
| 256 |
+
with self.progress_bar(total=len(b.timesteps)) as progress_bar:
|
| 257 |
+
for i, t in enumerate(b.timesteps):
|
| 258 |
+
components, b = self.loop_step(components, b, i=i, t=t)
|
| 259 |
+
progress_bar.update()
|
| 260 |
+
self.set_block_state(state, b)
|
| 261 |
+
return components, state
|
encoders.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
from diffusers import ModelMixin
|
| 4 |
+
from diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec, InputParam, OutputParam
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
from transformers import DINOv3ViTModel
|
| 8 |
+
|
| 9 |
+
from .projection import ProjGrid
|
| 10 |
+
from .resolvable import ResolvableBlock
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Pixal3DImageEncodeStep(ResolvableBlock):
|
| 14 |
+
model_name = "pixal3d"
|
| 15 |
+
|
| 16 |
+
def __init__(self, image_size: int):
|
| 17 |
+
self.image_size = image_size
|
| 18 |
+
super().__init__()
|
| 19 |
+
|
| 20 |
+
@property
|
| 21 |
+
def description(self):
|
| 22 |
+
return f"Encode the prepared image at {self.image_size}px into DINOv3 global tokens and patch features."
|
| 23 |
+
|
| 24 |
+
@property
|
| 25 |
+
def expected_components(self):
|
| 26 |
+
return self.resolve([ComponentSpec("image_encoder", DINOv3ViTModel)])
|
| 27 |
+
|
| 28 |
+
@property
|
| 29 |
+
def inputs(self):
|
| 30 |
+
return [
|
| 31 |
+
InputParam(
|
| 32 |
+
"image",
|
| 33 |
+
required=True,
|
| 34 |
+
type_hint=Image.Image,
|
| 35 |
+
description="Prepared RGB or RGBA image; RGBA is composited on black. No background removal or crop.",
|
| 36 |
+
),
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def intermediate_outputs(self):
|
| 41 |
+
return [
|
| 42 |
+
OutputParam("image_tensor", type_hint=torch.Tensor, description="Resized image, B 3 H W in [0, 1]."),
|
| 43 |
+
OutputParam("global_features", type_hint=torch.Tensor, description="CLS and register tokens."),
|
| 44 |
+
OutputParam("patch_features", type_hint=torch.Tensor, description="Patch features, B C h w."),
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
@torch.no_grad()
|
| 48 |
+
def __call__(self, components, state):
|
| 49 |
+
block = self.get_block_state(state)
|
| 50 |
+
image = block.image
|
| 51 |
+
if not isinstance(image, Image.Image):
|
| 52 |
+
raise TypeError("image must be a prepared PIL image")
|
| 53 |
+
if image.mode == "RGBA":
|
| 54 |
+
background = Image.new("RGBA", image.size, (0, 0, 0, 255))
|
| 55 |
+
image = Image.alpha_composite(background, image).convert("RGB")
|
| 56 |
+
image = image.convert("RGB").resize((self.image_size, self.image_size), Image.Resampling.LANCZOS)
|
| 57 |
+
pixels = torch.from_numpy(np.array(image).astype(np.float32) / 255).permute(2, 0, 1)[None]
|
| 58 |
+
model = components.image_encoder
|
| 59 |
+
pixels = pixels.to(model.device)
|
| 60 |
+
mean = pixels.new_tensor([0.485, 0.456, 0.406])[None, :, None, None]
|
| 61 |
+
std = pixels.new_tensor([0.229, 0.224, 0.225])[None, :, None, None]
|
| 62 |
+
# The reference reads the last layer before the encoder's final norm and applies an unlearned layer norm.
|
| 63 |
+
normalized = (pixels - mean) / std
|
| 64 |
+
raw = model(normalized.to(model.dtype), output_hidden_states=True).hidden_states[-1]
|
| 65 |
+
features = F.layer_norm(raw, raw.shape[-1:])
|
| 66 |
+
global_count = 1 + model.config.num_register_tokens
|
| 67 |
+
patches = self.image_size // model.config.patch_size
|
| 68 |
+
block.image_tensor = pixels
|
| 69 |
+
block.global_features = features[:, :global_count]
|
| 70 |
+
block.patch_features = (
|
| 71 |
+
features[:, global_count:].reshape(1, patches, patches, -1).permute(0, 3, 1, 2).contiguous()
|
| 72 |
+
)
|
| 73 |
+
self.set_block_state(state, block)
|
| 74 |
+
return components, state
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class Pixal3DUpsampleFeaturesStep(ResolvableBlock):
|
| 78 |
+
model_name = "pixal3d"
|
| 79 |
+
|
| 80 |
+
def __init__(self, feature_size: int):
|
| 81 |
+
self.feature_size = feature_size
|
| 82 |
+
super().__init__()
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def description(self):
|
| 86 |
+
return f"Upsample the patch features to {self.feature_size}x{self.feature_size} with NAF."
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def expected_components(self):
|
| 90 |
+
return self.resolve([ComponentSpec("feature_upsampler", ModelMixin)])
|
| 91 |
+
|
| 92 |
+
@property
|
| 93 |
+
def inputs(self):
|
| 94 |
+
return [
|
| 95 |
+
InputParam("image_tensor", required=True, type_hint=torch.Tensor),
|
| 96 |
+
InputParam("patch_features", required=True, type_hint=torch.Tensor),
|
| 97 |
+
]
|
| 98 |
+
|
| 99 |
+
@property
|
| 100 |
+
def intermediate_outputs(self):
|
| 101 |
+
return [OutputParam("upsampled_features", type_hint=torch.Tensor, description="NAF-upsampled features.")]
|
| 102 |
+
|
| 103 |
+
@torch.no_grad()
|
| 104 |
+
def __call__(self, components, state):
|
| 105 |
+
b = self.get_block_state(state)
|
| 106 |
+
model = components.feature_upsampler
|
| 107 |
+
b.upsampled_features = model(
|
| 108 |
+
b.image_tensor.to(device=model.device, dtype=model.dtype),
|
| 109 |
+
b.patch_features.to(device=model.device, dtype=model.dtype),
|
| 110 |
+
(self.feature_size, self.feature_size),
|
| 111 |
+
)
|
| 112 |
+
self.set_block_state(state, b)
|
| 113 |
+
return components, state
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class Pixal3DProjectFeaturesStep(ResolvableBlock):
|
| 117 |
+
"""Project image features onto the stage's 3D grid.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
image_size: Resolution the features were encoded at.
|
| 121 |
+
grid_resolution: Projection grid size. `None` derives it from `actual_resolution // 16`.
|
| 122 |
+
grid_from_model: Read the grid size from this component's `config.resolution` instead (dense stage).
|
| 123 |
+
sparse: Sample only at `coords` and concatenate the NAF-upsampled features.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
model_name = "pixal3d"
|
| 127 |
+
|
| 128 |
+
def __init__(self, image_size: int, grid_resolution: int | None = None, grid_from_model=None, sparse=True):
|
| 129 |
+
self.image_size = image_size
|
| 130 |
+
self.grid_resolution = grid_resolution
|
| 131 |
+
self.grid_from_model = grid_from_model
|
| 132 |
+
self.sparse = sparse
|
| 133 |
+
self._grids = {}
|
| 134 |
+
super().__init__()
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def description(self):
|
| 138 |
+
target = "selected sparse coordinates" if self.sparse else "a dense grid"
|
| 139 |
+
return f"Project {self.image_size}px image features onto {target}."
|
| 140 |
+
|
| 141 |
+
@property
|
| 142 |
+
def expected_components(self):
|
| 143 |
+
return self.resolve([ComponentSpec(self.grid_from_model, ModelMixin)] if self.grid_from_model else [])
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def inputs(self):
|
| 147 |
+
inputs = [
|
| 148 |
+
InputParam("patch_features", required=True, type_hint=torch.Tensor),
|
| 149 |
+
InputParam(
|
| 150 |
+
"camera_angle_x", required=True, type_hint=float, description="Horizontal field of view, radians."
|
| 151 |
+
),
|
| 152 |
+
InputParam(
|
| 153 |
+
"distance",
|
| 154 |
+
required=True,
|
| 155 |
+
type_hint=float,
|
| 156 |
+
description="Camera distance in the normalized source coordinate system.",
|
| 157 |
+
),
|
| 158 |
+
InputParam(
|
| 159 |
+
"mesh_scale", default=1.0, type_hint=float, description="Object scale; 1.0 fills the unit box."
|
| 160 |
+
),
|
| 161 |
+
]
|
| 162 |
+
if self.sparse:
|
| 163 |
+
inputs += [
|
| 164 |
+
InputParam("upsampled_features", required=True, type_hint=torch.Tensor),
|
| 165 |
+
InputParam("coords", required=True, type_hint=torch.Tensor, description="Sparse (N, 4) coordinates."),
|
| 166 |
+
]
|
| 167 |
+
if self.grid_resolution is None and self.grid_from_model is None:
|
| 168 |
+
inputs.append(InputParam("actual_resolution", required=True, type_hint=int))
|
| 169 |
+
return inputs
|
| 170 |
+
|
| 171 |
+
@property
|
| 172 |
+
def intermediate_outputs(self):
|
| 173 |
+
return [OutputParam("projected_features", type_hint=torch.Tensor, description="B N C projected features.")]
|
| 174 |
+
|
| 175 |
+
def _grid(self, grid_resolution, device):
|
| 176 |
+
key = (grid_resolution, device)
|
| 177 |
+
if key not in self._grids:
|
| 178 |
+
self._grids[key] = ProjGrid(grid_resolution, self.image_size).to(device)
|
| 179 |
+
return self._grids[key]
|
| 180 |
+
|
| 181 |
+
@torch.no_grad()
|
| 182 |
+
def __call__(self, components, state):
|
| 183 |
+
b = self.get_block_state(state)
|
| 184 |
+
if not 0 < b.camera_angle_x < np.pi or b.distance <= 0 or b.mesh_scale <= 0:
|
| 185 |
+
raise ValueError("FOV must be in (0, pi), distance and mesh_scale must be positive")
|
| 186 |
+
if self.grid_from_model:
|
| 187 |
+
grid_resolution = getattr(components, self.grid_from_model).config.resolution
|
| 188 |
+
elif self.grid_resolution is None:
|
| 189 |
+
grid_resolution = b.actual_resolution // 16
|
| 190 |
+
else:
|
| 191 |
+
grid_resolution = self.grid_resolution
|
| 192 |
+
device = b.patch_features.device
|
| 193 |
+
grid = self._grid(grid_resolution, device)
|
| 194 |
+
camera = [torch.tensor([v], device=device) for v in (b.camera_angle_x, b.distance, b.mesh_scale)]
|
| 195 |
+
indices = None
|
| 196 |
+
if self.sparse:
|
| 197 |
+
coords = b.coords.long().to(device)
|
| 198 |
+
if coords.ndim != 2 or coords.shape[1] != 4 or (coords[:, 0] != 0).any():
|
| 199 |
+
raise ValueError("Coordinates must have shape (N,4) with batch index 0")
|
| 200 |
+
if ((coords[:, 1:] < 0) | (coords[:, 1:] >= grid_resolution)).any():
|
| 201 |
+
raise ValueError("Coordinates fall outside the projection grid")
|
| 202 |
+
indices = (coords[:, 1] * grid_resolution + coords[:, 2]) * grid_resolution + coords[:, 3]
|
| 203 |
+
projected = grid(b.patch_features.float(), *camera, grid_indices=indices)
|
| 204 |
+
if self.sparse:
|
| 205 |
+
upsampled = grid(b.upsampled_features.to(device).float(), *camera, grid_indices=indices)
|
| 206 |
+
projected = torch.cat([projected, upsampled], -1)
|
| 207 |
+
b.projected_features = projected
|
| 208 |
+
self.set_block_state(state, b)
|
| 209 |
+
return components, state
|
guidance.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from diffusers.configuration_utils import register_to_config
|
| 2 |
+
from diffusers.guiders.guider_utils import BaseGuidance, GuiderOutput
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Pixal3DGuidance(BaseGuidance):
|
| 6 |
+
"""Classifier-free guidance with Pixal3D's sigma interval and clean-sample (x0) rescaling.
|
| 7 |
+
|
| 8 |
+
Guidance is active while the current sigma lies inside `guidance_interval`; outside it, or with
|
| 9 |
+
`guidance_scale=1`, only the conditional prediction is computed. The rescale matches the standard
|
| 10 |
+
deviation of the guided x0 estimate to the conditional one, which needs the current `latents`.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
_input_predictions = ["pred_cond", "pred_uncond"]
|
| 14 |
+
|
| 15 |
+
@register_to_config
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
guidance_scale=7.5,
|
| 19 |
+
guidance_rescale=0.7,
|
| 20 |
+
guidance_interval=(0.6, 1.0),
|
| 21 |
+
sigma_min=1e-5,
|
| 22 |
+
enabled=True,
|
| 23 |
+
):
|
| 24 |
+
super().__init__(enabled=enabled)
|
| 25 |
+
|
| 26 |
+
@property
|
| 27 |
+
def _scale(self):
|
| 28 |
+
sigma = self._timestep
|
| 29 |
+
low, high = self.config.guidance_interval
|
| 30 |
+
if self._enabled and sigma is not None and low <= sigma <= high:
|
| 31 |
+
return self.config.guidance_scale
|
| 32 |
+
return 1.0
|
| 33 |
+
|
| 34 |
+
@property
|
| 35 |
+
def is_conditional(self):
|
| 36 |
+
return self._count_prepared == 1
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def num_conditions(self):
|
| 40 |
+
return 1 if self._scale in (0, 1) else 2
|
| 41 |
+
|
| 42 |
+
def _predictions(self):
|
| 43 |
+
# guidance_scale=0 is purely unconditional; 1 (or outside the interval) is purely conditional.
|
| 44 |
+
if self._scale == 0:
|
| 45 |
+
return ["pred_uncond"]
|
| 46 |
+
return self._input_predictions[: self.num_conditions]
|
| 47 |
+
|
| 48 |
+
def prepare_inputs(self, data):
|
| 49 |
+
return [self._prepare_batch(data, i, name) for i, name in self._identified_predictions()]
|
| 50 |
+
|
| 51 |
+
def prepare_inputs_from_block_state(self, data, input_fields):
|
| 52 |
+
return [
|
| 53 |
+
self._prepare_batch_from_block_state(input_fields, data, i, name)
|
| 54 |
+
for i, name in self._identified_predictions()
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
def _identified_predictions(self):
|
| 58 |
+
return [(self._input_predictions.index(name), name) for name in self._predictions()]
|
| 59 |
+
|
| 60 |
+
def __call__(self, data):
|
| 61 |
+
predictions = {getattr(d, self._identifier_key): d.noise_pred for d in data}
|
| 62 |
+
return self.forward(**predictions, latents=data[0].latents)
|
| 63 |
+
|
| 64 |
+
def forward(self, pred_cond=None, pred_uncond=None, latents=None):
|
| 65 |
+
if pred_cond is None:
|
| 66 |
+
return GuiderOutput(pred=pred_uncond)
|
| 67 |
+
if pred_uncond is None:
|
| 68 |
+
return GuiderOutput(pred=pred_cond)
|
| 69 |
+
latents = latents.to(pred_cond.device)
|
| 70 |
+
pred_uncond = pred_uncond.to(pred_cond.device)
|
| 71 |
+
scale = self._scale
|
| 72 |
+
result = scale * pred_cond + (1 - scale) * pred_uncond
|
| 73 |
+
if self.config.guidance_rescale > 0:
|
| 74 |
+
sigma_min = self.config.sigma_min
|
| 75 |
+
sigma = sigma_min + (1 - sigma_min) * self._timestep
|
| 76 |
+
clean_pos = (1 - sigma_min) * latents - sigma * pred_cond
|
| 77 |
+
clean_cfg = (1 - sigma_min) * latents - sigma * result
|
| 78 |
+
dims = list(range(1, latents.ndim))
|
| 79 |
+
rescaled = clean_cfg * (clean_pos.std(dim=dims, keepdim=True) / clean_cfg.std(dim=dims, keepdim=True))
|
| 80 |
+
clean = self.config.guidance_rescale * rescaled + (1 - self.config.guidance_rescale) * clean_cfg
|
| 81 |
+
result = ((1 - sigma_min) * latents - clean) / sigma
|
| 82 |
+
return GuiderOutput(pred=result, pred_cond=pred_cond, pred_uncond=pred_uncond)
|
modular_blocks_pixal3d.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from diffusers.modular_pipelines import ModularPipeline, SequentialPipelineBlocks
|
| 5 |
+
from diffusers.modular_pipelines.modular_pipeline_utils import InsertableDict, OutputParam
|
| 6 |
+
from diffusers.utils.dynamic_modules_utils import get_class_from_dynamic_module
|
| 7 |
+
from huggingface_hub import file_exists
|
| 8 |
+
from huggingface_hub.errors import HFValidationError
|
| 9 |
+
from transformers import DINOv3ViTModel
|
| 10 |
+
|
| 11 |
+
from .decoders import (
|
| 12 |
+
Pixal3DShapeDecodeStep,
|
| 13 |
+
Pixal3DShapeUpsampleStep,
|
| 14 |
+
Pixal3DStructureDecodeStep,
|
| 15 |
+
Pixal3DTextureDecodeStep,
|
| 16 |
+
)
|
| 17 |
+
from .denoise import (
|
| 18 |
+
SHAPE_HIGH_STAGE,
|
| 19 |
+
SHAPE_LOW_STAGE,
|
| 20 |
+
STRUCTURE_STAGE,
|
| 21 |
+
TEXTURE_STAGE,
|
| 22 |
+
Pixal3DDenoiseLoop,
|
| 23 |
+
Pixal3DPrepareLatentsStep,
|
| 24 |
+
Pixal3DSetTimestepsStep,
|
| 25 |
+
)
|
| 26 |
+
from .encoders import Pixal3DImageEncodeStep, Pixal3DProjectFeaturesStep, Pixal3DUpsampleFeaturesStep
|
| 27 |
+
from .guidance import Pixal3DGuidance # noqa: F401
|
| 28 |
+
from .normalization import SHAPE_MEAN, SHAPE_STD, TEXTURE_MEAN, TEXTURE_STD # noqa: F401
|
| 29 |
+
|
| 30 |
+
# Expose transitive dependencies to the Hub custom-code collector.
|
| 31 |
+
from .projection import ProjGrid # noqa: F401
|
| 32 |
+
from .resolvable import ResolvableBlock # noqa: F401
|
| 33 |
+
from .stages import Pixal3DShapeNormalizeStep, Pixal3DTextureConditionStep, Pixal3DTextureNormalizeStep
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _stage(prefix, stage):
|
| 37 |
+
return [
|
| 38 |
+
(f"{prefix}_prepare_latents", Pixal3DPrepareLatentsStep(stage)),
|
| 39 |
+
(f"{prefix}_set_timesteps", Pixal3DSetTimestepsStep(stage)),
|
| 40 |
+
(f"{prefix}_denoise", Pixal3DDenoiseLoop(stage)),
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
Pixal3DBlockSequence = InsertableDict(
|
| 45 |
+
[
|
| 46 |
+
("structure_image_encoder", Pixal3DImageEncodeStep(image_size=512)),
|
| 47 |
+
(
|
| 48 |
+
"structure_projection",
|
| 49 |
+
Pixal3DProjectFeaturesStep(image_size=512, grid_from_model=STRUCTURE_STAGE.transformer, sparse=False),
|
| 50 |
+
),
|
| 51 |
+
*_stage("structure", STRUCTURE_STAGE),
|
| 52 |
+
("structure_decode", Pixal3DStructureDecodeStep()),
|
| 53 |
+
("shape_low_features", Pixal3DUpsampleFeaturesStep(feature_size=512)),
|
| 54 |
+
("shape_low_projection", Pixal3DProjectFeaturesStep(image_size=512, grid_resolution=32)),
|
| 55 |
+
*_stage("shape_low", SHAPE_LOW_STAGE),
|
| 56 |
+
("shape_low_normalize", Pixal3DShapeNormalizeStep()),
|
| 57 |
+
("shape_upsample", Pixal3DShapeUpsampleStep()),
|
| 58 |
+
("shape_high_image_encoder", Pixal3DImageEncodeStep(image_size=1024)),
|
| 59 |
+
("shape_high_features", Pixal3DUpsampleFeaturesStep(feature_size=512)),
|
| 60 |
+
("shape_high_projection", Pixal3DProjectFeaturesStep(image_size=1024)),
|
| 61 |
+
*_stage("shape_high", SHAPE_HIGH_STAGE),
|
| 62 |
+
("shape_high_normalize", Pixal3DShapeNormalizeStep()),
|
| 63 |
+
("texture_condition", Pixal3DTextureConditionStep()),
|
| 64 |
+
("texture_features", Pixal3DUpsampleFeaturesStep(feature_size=1024)),
|
| 65 |
+
("texture_projection", Pixal3DProjectFeaturesStep(image_size=1024)),
|
| 66 |
+
*_stage("texture", TEXTURE_STAGE),
|
| 67 |
+
("texture_normalize", Pixal3DTextureNormalizeStep()),
|
| 68 |
+
("shape_decode", Pixal3DShapeDecodeStep()),
|
| 69 |
+
("texture_decode", Pixal3DTextureDecodeStep()),
|
| 70 |
+
]
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _component_source(entry, name, repo, revision):
|
| 75 |
+
"""Return (module, class, repo, subfolder, revision) for one `modular_model_index.json` entry.
|
| 76 |
+
|
| 77 |
+
The model repository's own index names a module file (or `transformers`); its components load from `repo`, so a
|
| 78 |
+
local copy stays local even if the index records Hub ids. An index written by `pipe.save_pretrained()` stores
|
| 79 |
+
dotted module paths into the dynamic-module cache (or null with a `type_hint`) and the location of each component.
|
| 80 |
+
"""
|
| 81 |
+
module, cls = entry[0], entry[1]
|
| 82 |
+
spec = entry[2] if len(entry) > 2 and entry[2] else {}
|
| 83 |
+
if module is not None and "." not in module:
|
| 84 |
+
return module, cls, repo, spec.get("subfolder") or name, revision
|
| 85 |
+
if module is None:
|
| 86 |
+
module, cls = spec["type_hint"]
|
| 87 |
+
return (
|
| 88 |
+
module.rsplit(".", 1)[-1],
|
| 89 |
+
cls,
|
| 90 |
+
spec.get("pretrained_model_name_or_path") or repo,
|
| 91 |
+
spec.get("subfolder") or name,
|
| 92 |
+
spec.get("revision") or revision,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _has_file(repo, filename, revision):
|
| 97 |
+
if Path(str(repo)).is_dir():
|
| 98 |
+
return (Path(str(repo)) / filename).is_file()
|
| 99 |
+
try:
|
| 100 |
+
return file_exists(str(repo), filename, revision=revision)
|
| 101 |
+
except (HFValidationError, OSError):
|
| 102 |
+
return False
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _code_repo(module, candidates):
|
| 106 |
+
"""First (repo, revision) holding `<module>.py`.
|
| 107 |
+
|
| 108 |
+
A saved pipeline's components point at the save directory, which holds weights but not the model code.
|
| 109 |
+
"""
|
| 110 |
+
for repo, revision in candidates:
|
| 111 |
+
if _has_file(repo, f"{module}.py", revision):
|
| 112 |
+
return repo, revision
|
| 113 |
+
raise OSError(
|
| 114 |
+
f"Could not find {module}.py in {[str(repo) for repo, _ in candidates]}. A pipeline saved with "
|
| 115 |
+
"`save_pretrained` keeps only weights; copy the model repository's .py files into it."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _leaves(block):
|
| 120 |
+
if not block.sub_blocks:
|
| 121 |
+
yield block
|
| 122 |
+
for child in block.sub_blocks.values():
|
| 123 |
+
yield from _leaves(child)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class Pixal3DBlocks(SequentialPipelineBlocks):
|
| 127 |
+
model_name = "pixal3d"
|
| 128 |
+
block_classes = Pixal3DBlockSequence.values()
|
| 129 |
+
block_names = Pixal3DBlockSequence.keys()
|
| 130 |
+
|
| 131 |
+
def __init__(self, components_repo=None, components_revision=None, trust_components_code=False):
|
| 132 |
+
super().__init__()
|
| 133 |
+
self.components_repo = components_repo
|
| 134 |
+
self.components_revision = components_revision
|
| 135 |
+
if components_repo is None:
|
| 136 |
+
return
|
| 137 |
+
if not trust_components_code:
|
| 138 |
+
raise ValueError("Set trust_components_code=True to load the model repository code")
|
| 139 |
+
index = ModularPipeline.load_config(components_repo, revision=components_revision)
|
| 140 |
+
names = [s.name for s in super().expected_components if s.default_creation_method == "from_pretrained"]
|
| 141 |
+
sources = {name: _component_source(index[name], name, components_repo, components_revision) for name in names}
|
| 142 |
+
# Code can live in any repo the index references, the given repo first.
|
| 143 |
+
candidates = [(components_repo, components_revision)] + [(r, v) for _, _, r, _, v in sources.values()]
|
| 144 |
+
candidates = list(dict.fromkeys(candidates))
|
| 145 |
+
overrides = {}
|
| 146 |
+
for name, (module, cls, repo, subfolder, revision) in sources.items():
|
| 147 |
+
if name == "image_encoder":
|
| 148 |
+
type_hint = DINOv3ViTModel
|
| 149 |
+
else:
|
| 150 |
+
code_repo, code_revision = _code_repo(module, candidates)
|
| 151 |
+
type_hint = get_class_from_dynamic_module(
|
| 152 |
+
code_repo,
|
| 153 |
+
module_file=f"{module}.py",
|
| 154 |
+
class_name=cls,
|
| 155 |
+
revision=code_revision,
|
| 156 |
+
trust_remote_code=True,
|
| 157 |
+
)
|
| 158 |
+
overrides[name] = dict(
|
| 159 |
+
type_hint=type_hint, pretrained_model_name_or_path=str(repo), subfolder=subfolder, revision=revision
|
| 160 |
+
)
|
| 161 |
+
# The block instances are shared module-level objects; give this pipeline its own copies to carry the specs.
|
| 162 |
+
self.sub_blocks = copy.deepcopy(self.sub_blocks)
|
| 163 |
+
for leaf in _leaves(self):
|
| 164 |
+
leaf.component_overrides = overrides
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def description(self):
|
| 168 |
+
return "Pixal3D single-image generation to flexible-dual-grid geometry and voxel material attributes."
|
| 169 |
+
|
| 170 |
+
@property
|
| 171 |
+
def outputs(self):
|
| 172 |
+
return [
|
| 173 |
+
OutputParam(
|
| 174 |
+
"geometry", type_hint=dict, description="Flexible dual grid: coords, offsets, flags, weights."
|
| 175 |
+
),
|
| 176 |
+
OutputParam("materials", type_hint=dict, description="Per-cell base color, metallic, roughness, alpha."),
|
| 177 |
+
OutputParam(
|
| 178 |
+
"actual_resolution", type_hint=int, description="Effective grid resolution (1536 can fall back)."
|
| 179 |
+
),
|
| 180 |
+
OutputParam("shape_latents", type_hint=object),
|
| 181 |
+
OutputParam("texture_latents", type_hint=object),
|
| 182 |
+
OutputParam("coords", type_hint=object),
|
| 183 |
+
]
|
modular_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "Pixal3DBlocks",
|
| 3 |
+
"_diffusers_version": "0.41.0.dev0",
|
| 4 |
+
"auto_map": {
|
| 5 |
+
"ModularPipelineBlocks": "modular_blocks_pixal3d.Pixal3DBlocks"
|
| 6 |
+
}
|
| 7 |
+
}
|
normalization.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
SHAPE_MEAN = [
|
| 2 |
+
0.781296,
|
| 3 |
+
0.018091,
|
| 4 |
+
-0.495192,
|
| 5 |
+
-0.558457,
|
| 6 |
+
1.06053,
|
| 7 |
+
0.093252,
|
| 8 |
+
1.518149,
|
| 9 |
+
-0.933218,
|
| 10 |
+
-0.732996,
|
| 11 |
+
2.604095,
|
| 12 |
+
-0.118341,
|
| 13 |
+
-2.143904,
|
| 14 |
+
0.495076,
|
| 15 |
+
-2.179512,
|
| 16 |
+
-2.130751,
|
| 17 |
+
-0.996944,
|
| 18 |
+
0.261421,
|
| 19 |
+
-2.217463,
|
| 20 |
+
1.260067,
|
| 21 |
+
-0.150213,
|
| 22 |
+
3.790713,
|
| 23 |
+
1.481266,
|
| 24 |
+
-1.046058,
|
| 25 |
+
-1.523667,
|
| 26 |
+
-0.059621,
|
| 27 |
+
2.22078,
|
| 28 |
+
1.621212,
|
| 29 |
+
0.87723,
|
| 30 |
+
0.567247,
|
| 31 |
+
-3.175944,
|
| 32 |
+
-3.186688,
|
| 33 |
+
1.578665,
|
| 34 |
+
]
|
| 35 |
+
SHAPE_STD = [
|
| 36 |
+
5.972266,
|
| 37 |
+
4.706852,
|
| 38 |
+
5.44501,
|
| 39 |
+
5.209927,
|
| 40 |
+
5.32022,
|
| 41 |
+
4.547237,
|
| 42 |
+
5.020802,
|
| 43 |
+
5.444004,
|
| 44 |
+
5.226681,
|
| 45 |
+
5.683095,
|
| 46 |
+
4.831436,
|
| 47 |
+
5.286469,
|
| 48 |
+
5.652043,
|
| 49 |
+
5.367606,
|
| 50 |
+
5.525084,
|
| 51 |
+
4.730578,
|
| 52 |
+
4.805265,
|
| 53 |
+
5.124013,
|
| 54 |
+
5.530808,
|
| 55 |
+
5.619001,
|
| 56 |
+
5.10393,
|
| 57 |
+
5.41767,
|
| 58 |
+
5.269677,
|
| 59 |
+
5.547194,
|
| 60 |
+
5.634698,
|
| 61 |
+
5.235274,
|
| 62 |
+
6.110351,
|
| 63 |
+
5.511298,
|
| 64 |
+
6.237273,
|
| 65 |
+
4.879207,
|
| 66 |
+
5.347008,
|
| 67 |
+
5.405691,
|
| 68 |
+
]
|
| 69 |
+
TEXTURE_MEAN = [
|
| 70 |
+
3.501659,
|
| 71 |
+
2.212398,
|
| 72 |
+
2.226094,
|
| 73 |
+
0.251093,
|
| 74 |
+
-0.026248,
|
| 75 |
+
-0.687364,
|
| 76 |
+
0.439898,
|
| 77 |
+
-0.928075,
|
| 78 |
+
0.029398,
|
| 79 |
+
-0.339596,
|
| 80 |
+
-0.869527,
|
| 81 |
+
1.038479,
|
| 82 |
+
-0.972385,
|
| 83 |
+
0.126042,
|
| 84 |
+
-1.129303,
|
| 85 |
+
0.455149,
|
| 86 |
+
-1.209521,
|
| 87 |
+
2.069067,
|
| 88 |
+
0.544735,
|
| 89 |
+
2.569128,
|
| 90 |
+
-0.323407,
|
| 91 |
+
2.293,
|
| 92 |
+
-1.925608,
|
| 93 |
+
-1.217717,
|
| 94 |
+
1.213905,
|
| 95 |
+
0.971588,
|
| 96 |
+
-0.023631,
|
| 97 |
+
0.10675,
|
| 98 |
+
2.021786,
|
| 99 |
+
0.250524,
|
| 100 |
+
-0.662387,
|
| 101 |
+
-0.768862,
|
| 102 |
+
]
|
| 103 |
+
TEXTURE_STD = [
|
| 104 |
+
2.665652,
|
| 105 |
+
2.743913,
|
| 106 |
+
2.765121,
|
| 107 |
+
2.595319,
|
| 108 |
+
3.037293,
|
| 109 |
+
2.291316,
|
| 110 |
+
2.144656,
|
| 111 |
+
2.911822,
|
| 112 |
+
2.969419,
|
| 113 |
+
2.501689,
|
| 114 |
+
2.154811,
|
| 115 |
+
3.163343,
|
| 116 |
+
2.621215,
|
| 117 |
+
2.381943,
|
| 118 |
+
3.186697,
|
| 119 |
+
3.021588,
|
| 120 |
+
2.295916,
|
| 121 |
+
3.234985,
|
| 122 |
+
3.233086,
|
| 123 |
+
2.26014,
|
| 124 |
+
2.874801,
|
| 125 |
+
2.810596,
|
| 126 |
+
3.29272,
|
| 127 |
+
2.674999,
|
| 128 |
+
2.680878,
|
| 129 |
+
2.372054,
|
| 130 |
+
2.451546,
|
| 131 |
+
2.353556,
|
| 132 |
+
2.995195,
|
| 133 |
+
2.379849,
|
| 134 |
+
2.786195,
|
| 135 |
+
2.77519,
|
| 136 |
+
]
|
projection.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from TencentARC/Pixal3D, Copyright (c) 2026 Tencent, MIT (see LICENSE-PIXAL3D).
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def project_points_to_image_batch(
|
| 9 |
+
points_3d: torch.Tensor,
|
| 10 |
+
transform_matrix: torch.Tensor,
|
| 11 |
+
camera_angle_x: torch.Tensor,
|
| 12 |
+
resolution: int,
|
| 13 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 14 |
+
"""Project 3D points to pixel coordinates with a pinhole camera (32 mm sensor width).
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
points_3d: B N 3 points.
|
| 18 |
+
transform_matrix: B 4 4 camera-to-world matrices.
|
| 19 |
+
camera_angle_x: B horizontal fields of view, radians.
|
| 20 |
+
resolution: Square image resolution in pixels.
|
| 21 |
+
|
| 22 |
+
Returns:
|
| 23 |
+
Pixel coordinates (B N 2), depth (B N) and a mask of points inside the view (B N).
|
| 24 |
+
"""
|
| 25 |
+
batch, count = points_3d.shape[:2]
|
| 26 |
+
ones = torch.ones(batch, count, 1, device=points_3d.device, dtype=points_3d.dtype)
|
| 27 |
+
points_homogeneous = torch.cat([points_3d, ones], dim=-1)
|
| 28 |
+
world_to_camera = torch.linalg.inv(transform_matrix.float()).to(transform_matrix.dtype)
|
| 29 |
+
points_camera = torch.bmm(points_homogeneous, world_to_camera.transpose(-2, -1))[..., :3]
|
| 30 |
+
x_cam, y_cam, z_cam = points_camera.unbind(-1)
|
| 31 |
+
depth = -z_cam
|
| 32 |
+
sensor_width = 32.0
|
| 33 |
+
focal_length = 16.0 / torch.tan(camera_angle_x / 2.0)
|
| 34 |
+
focal_length_pixels = (focal_length * resolution / sensor_width).unsqueeze(1)
|
| 35 |
+
x_ndc = focal_length_pixels * x_cam / (-z_cam + 1e-08)
|
| 36 |
+
y_ndc = focal_length_pixels * y_cam / (-z_cam + 1e-08)
|
| 37 |
+
x_pixel = x_ndc + resolution / 2.0
|
| 38 |
+
y_pixel = -y_ndc + resolution / 2.0
|
| 39 |
+
valid_mask = (x_pixel >= 0) & (x_pixel < resolution) & (y_pixel >= 0) & (y_pixel < resolution) & (depth > 0)
|
| 40 |
+
return torch.stack([x_pixel, y_pixel], dim=-1), depth, valid_mask
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ProjGrid(nn.Module):
|
| 44 |
+
"""Project a 3D grid (or selected grid cells) into the front view and sample image features there."""
|
| 45 |
+
|
| 46 |
+
def __init__(self, grid_resolution: int, image_resolution: int):
|
| 47 |
+
super().__init__()
|
| 48 |
+
self.image_resolution = image_resolution
|
| 49 |
+
one_dim = torch.linspace(-1, 1, grid_resolution)
|
| 50 |
+
x, y, z = torch.meshgrid(one_dim, one_dim, one_dim, indexing="ij")
|
| 51 |
+
rotation_matrix = torch.tensor([[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]])
|
| 52 |
+
grid_points = torch.matmul(torch.stack((x, y, z), dim=-1), rotation_matrix.T).reshape(-1, 3)
|
| 53 |
+
self.register_buffer("grid_points", grid_points)
|
| 54 |
+
front_view_transform_matrix = torch.tensor(
|
| 55 |
+
[
|
| 56 |
+
[1.0, 0.0, 0.0, 0.0],
|
| 57 |
+
[0.0, 0.0, -1.0, -2.0],
|
| 58 |
+
[0.0, 1.0, 0.0, 0.0],
|
| 59 |
+
[0.0, 0.0, 0.0, 1.0],
|
| 60 |
+
]
|
| 61 |
+
)
|
| 62 |
+
self.register_buffer("front_view_transform_matrix", front_view_transform_matrix)
|
| 63 |
+
|
| 64 |
+
def forward(
|
| 65 |
+
self,
|
| 66 |
+
features_map: torch.Tensor,
|
| 67 |
+
camera_angle_x: torch.Tensor,
|
| 68 |
+
distance: torch.Tensor,
|
| 69 |
+
mesh_scale: torch.Tensor,
|
| 70 |
+
grid_indices: torch.Tensor | None = None,
|
| 71 |
+
) -> torch.Tensor:
|
| 72 |
+
"""Sample a B C H W feature map at the projected grid points; returns B N C."""
|
| 73 |
+
batch = features_map.shape[0]
|
| 74 |
+
grid_points = self.grid_points
|
| 75 |
+
if grid_indices is not None:
|
| 76 |
+
grid_points = grid_points[grid_indices]
|
| 77 |
+
grid_points = grid_points.expand(batch, -1, -1)
|
| 78 |
+
grid_points = grid_points / mesh_scale.unsqueeze(-1).unsqueeze(-1) / 2
|
| 79 |
+
transform_matrix = self.front_view_transform_matrix.expand(batch, -1, -1).clone()
|
| 80 |
+
transform_matrix[:, 1, 3] = -distance
|
| 81 |
+
image_points, _, _ = project_points_to_image_batch(
|
| 82 |
+
grid_points, transform_matrix, camera_angle_x, self.image_resolution
|
| 83 |
+
)
|
| 84 |
+
image_points_norm = (image_points + 0.5) / self.image_resolution * 2 - 1
|
| 85 |
+
sample_grid = image_points_norm.view(batch, -1, 1, 2)
|
| 86 |
+
sampled = F.grid_sample(features_map, sample_grid, mode="bilinear", align_corners=False, padding_mode="border")
|
| 87 |
+
return sampled.squeeze(-1).permute(0, 2, 1)
|
resolvable.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import replace
|
| 2 |
+
|
| 3 |
+
from diffusers.modular_pipelines import ModularPipelineBlocks
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class ResolvableBlock(ModularPipelineBlocks):
|
| 7 |
+
"""Leaf block whose generic component specs can carry the model repository's resolved classes and location.
|
| 8 |
+
|
| 9 |
+
`Pixal3DBlocks(components_repo=...)` fills `component_overrides`, so a sub-block popped out of the pipeline still
|
| 10 |
+
loads the right custom classes from the right repository.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
component_overrides = {}
|
| 14 |
+
|
| 15 |
+
def resolve(self, specs):
|
| 16 |
+
return [
|
| 17 |
+
replace(spec, **self.component_overrides[spec.name]) if spec.name in self.component_overrides else spec
|
| 18 |
+
for spec in specs
|
| 19 |
+
]
|
stages.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from diffusers.modular_pipelines.modular_pipeline_utils import InputParam, OutputParam
|
| 3 |
+
|
| 4 |
+
from .normalization import SHAPE_MEAN, SHAPE_STD, TEXTURE_MEAN, TEXTURE_STD
|
| 5 |
+
from .resolvable import ResolvableBlock
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Pixal3DShapeNormalizeStep(ResolvableBlock):
|
| 9 |
+
model_name = "pixal3d"
|
| 10 |
+
|
| 11 |
+
@property
|
| 12 |
+
def description(self):
|
| 13 |
+
return "Restore shape latents to the decoder training distribution."
|
| 14 |
+
|
| 15 |
+
@property
|
| 16 |
+
def inputs(self):
|
| 17 |
+
return [InputParam("latents", required=True, type_hint=torch.Tensor, description="Denoised shape latents.")]
|
| 18 |
+
|
| 19 |
+
@property
|
| 20 |
+
def intermediate_outputs(self):
|
| 21 |
+
return [OutputParam("shape_latents", type_hint=torch.Tensor, description="Shape latents for the decoder.")]
|
| 22 |
+
|
| 23 |
+
def __call__(self, components, state):
|
| 24 |
+
b = self.get_block_state(state)
|
| 25 |
+
b.shape_latents = b.latents * b.latents.new_tensor(SHAPE_STD) + b.latents.new_tensor(SHAPE_MEAN)
|
| 26 |
+
self.set_block_state(state, b)
|
| 27 |
+
return components, state
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Pixal3DTextureConditionStep(ResolvableBlock):
|
| 31 |
+
model_name = "pixal3d"
|
| 32 |
+
|
| 33 |
+
@property
|
| 34 |
+
def description(self):
|
| 35 |
+
return "Normalize the shape latents into the texture flow model's concatenated condition."
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def inputs(self):
|
| 39 |
+
return [InputParam("shape_latents", required=True, type_hint=torch.Tensor)]
|
| 40 |
+
|
| 41 |
+
@property
|
| 42 |
+
def intermediate_outputs(self):
|
| 43 |
+
return [OutputParam("concat_cond", type_hint=torch.Tensor, description="Normalized shape latents.")]
|
| 44 |
+
|
| 45 |
+
def __call__(self, components, state):
|
| 46 |
+
b = self.get_block_state(state)
|
| 47 |
+
b.concat_cond = (b.shape_latents - b.shape_latents.new_tensor(SHAPE_MEAN)) / b.shape_latents.new_tensor(
|
| 48 |
+
SHAPE_STD
|
| 49 |
+
)
|
| 50 |
+
self.set_block_state(state, b)
|
| 51 |
+
return components, state
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class Pixal3DTextureNormalizeStep(ResolvableBlock):
|
| 55 |
+
model_name = "pixal3d"
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def description(self):
|
| 59 |
+
return "Restore material latents to the decoder training distribution."
|
| 60 |
+
|
| 61 |
+
@property
|
| 62 |
+
def inputs(self):
|
| 63 |
+
return [InputParam("latents", required=True, type_hint=torch.Tensor, description="Denoised material latents.")]
|
| 64 |
+
|
| 65 |
+
@property
|
| 66 |
+
def intermediate_outputs(self):
|
| 67 |
+
return [
|
| 68 |
+
OutputParam("texture_latents", type_hint=torch.Tensor, description="Material latents for the decoder.")
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
def __call__(self, components, state):
|
| 72 |
+
b = self.get_block_state(state)
|
| 73 |
+
b.texture_latents = b.latents * b.latents.new_tensor(TEXTURE_STD) + b.latents.new_tensor(TEXTURE_MEAN)
|
| 74 |
+
self.set_block_state(state, b)
|
| 75 |
+
return components, state
|