SUPRA-Tex: 3D Generation with Super-Aligned Texture
Merge origin/main and complete the README for the code release
chensjtuafd0f87a8d3d
diff --cc LICENSEindex 0389956,0000000..feee28fmode 100644,000000..100644--- a/LICENSE+++ b/LICENSE@@@ -1,638 -1,0 +1,21 @@@+MIT License++Copyright (c) 2026 SUPRA-Tex Authors.++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.-- ========================================================================-- # Third-party notices-- SUPRA-Tex's original contributions are licensed under the project [MIT License](LICENSE).- That license does not replace the licenses of incorporated third-party code.- This source tree includes MIT, Apache-2.0, and DINOv3-licensed components.- The exclusions below describe unrelated components removed from this release.- The tree must not be described as entirely MIT-licensed or as having a- completed redistribution review.-- ## Microsoft and Tencent MIT components-- The sparse tensor modules, flow/autoencoder infrastructure, mesh representations,- rendering utilities, and inherited pipeline/training infrastructure include code- from Microsoft TRELLIS/TRELLIS.2 and Tencent's MIT-licensed 3D implementation.- Applicable upstream copyrights and full permission notices are retained in:-- - [Microsoft MIT license](LICENSE): Copyright (c) Microsoft Corporation.- - [Tencent MIT license](LICENSE): Copyright (c) 2026 Tencent.-- The SUPRA-Tex package and method names describe this project; they do not change- ownership of incorporated upstream code.-- `supratex/inference/mesh_export.py` adapts the O-Voxel exporter from Microsoft- TRELLIS.2 under the Microsoft MIT license above. Supra-Tex replaces its texture- conversion and gap-filling stage with packed GPU quantization and grouped Telea- operations; mesh processing and texture baking retain the upstream algorithm.-- The separately vendored geometry snapshot is in- [`deployment/runtime/geometry/pixal3d/`](deployment/runtime/geometry/pixal3d).- Its [snapshot notice](deployment/runtime/geometry/NOTICE.md),- [Microsoft MIT license](deployment/runtime/geometry/TRELLIS2-MIT.txt), and- [Tencent MIT license](deployment/runtime/geometry/TENCENT-MIT.txt) accompany it.-- The `timestep_embedding` implementation in- [`supratex/models/sparse_structure_flow.py`](supratex/models/sparse_structure_flow.py)- and its- [vendored geometry counterpart](deployment/runtime/geometry/pixal3d/models/sparse_structure_flow.py)- credits OpenAI's GLIDE. The applicable- [OpenAI GLIDE MIT license](LICENSE) retains- Copyright (c) 2021 OpenAI.-- ## FireRed material-model runtime-- `supratex/frontend/material_model/runtime/` includes code adapted from- FireRed-Image-Edit and the factorized material-model implementation. Incorporated- FireRed portions remain licensed under Apache License 2.0. Original source- copyright notices are retained, and adaptations for this distribution are marked- in the source files. The project MIT license applies to original SUPRA-Tex- contributions and does not relicense those upstream portions.-- The full [FireRed Apache-2.0 license](LICENSE) is included,- with the upstream statement: Copyright 2026 FireRed-Image-Edit Authors. All Rights Reserved.-- Release adaptations include the local inference entrypoint, explicit external- model/checkpoint paths, input validation, and a self-contained import layout.-- ## Vendored deployment code-- The following source code is present in this repository; it is not merely an- external installation requirement. The recorded snapshot origins and limits of- the available version information are in- [`deployment/runtime/SOURCE_PROVENANCE.json`](deployment/runtime/SOURCE_PROVENANCE.json).- Top-level licenses do not override the terms of incorporated subcomponents.-- | Distributed path | Source and applicable notices |- | --- | --- |- | [`deployment/runtime/qwen/`](deployment/runtime/qwen) | Qwen material-model runtime, including `diffsynth`; its top-level [Apache-2.0 license](deployment/runtime/qwen/LICENSE) is retained. The [runtime third-party notices](deployment/runtime/qwen/THIRD_PARTY_NOTICES.md) map MIT subcomponents and document the excluded YuE2 audio VAE and pipeline. |- | [`deployment/runtime/moge/`](deployment/runtime/moge) | Microsoft MoGe source under MIT. The bundled [license file](deployment/runtime/moge/LICENSE) contains both the Microsoft MIT license and the Apache-2.0 text for incorporated DINOv2 code. [`moge/model/dinov2/`](deployment/runtime/moge/moge/model/dinov2) retains Meta copyright and Apache-2.0 headers. |- | [`deployment/runtime/utils3d/`](deployment/runtime/utils3d) | EasternJournalist utils3d; [MIT license](deployment/runtime/utils3d/LICENSE), Copyright (c) 2022 EasternJournalist. |- | [`deployment/runtime/naf/`](deployment/runtime/naf) | Valeo NAF snapshot with its top-level [Apache-2.0 license](deployment/runtime/naf/LICENSE). The component-specific DINOv3, DPIR, and Restormer notices and the REDNet exclusion are listed below. |-- ### Component-specific source licenses-- | Distributed path | Upstream component | Retained license |- | --- | --- | --- |- | [`deployment/runtime/naf/src/layers/rope.py`](deployment/runtime/naf/src/layers/rope.py) | Meta DINOv3, as stated in the source header | [DINOv3 License Agreement](LICENSE); this is Meta's custom agreement, not MIT or Apache-2.0. |- | [`deployment/runtime/naf/src/model/ircnn.py`](deployment/runtime/naf/src/model/ircnn.py) | `cszn/DPIR`, `models/network_dncnn.py` | [MIT](LICENSE), Copyright (c) 2020 Kai Zhang. |- | [`deployment/runtime/naf/src/model/restormer.py`](deployment/runtime/naf/src/model/restormer.py) | `swz30/Restormer` | [MIT](LICENSE), Copyright (c) 2022 Syed Waqas Zamir and contributors. |- | [`deployment/runtime/qwen/diffsynth/models/ace_step_residual_fsq.py`](deployment/runtime/qwen/diffsynth/models/ace_step_residual_fsq.py) | `lucidrains/vector-quantize-pytorch`, `residual_fsq.py` | [MIT](LICENSE), Copyright (c) 2020 Phil Wang. |-- The five additional license texts were retrieved in full from these official- upstream files on 2026-10-14:-- - [DINOv3 license](https://raw.githubusercontent.com/facebookresearch/dinov3/main/LICENSE.md)- → [DINOv3 License Agreement](LICENSE).- - [vector-quantize-pytorch license](https://raw.githubusercontent.com/lucidrains/vector-quantize-pytorch/master/LICENSE)- → [vector-quantize-pytorch - MIT](LICENSE).- - [DPIR license](https://raw.githubusercontent.com/cszn/DPIR/master/LICENSE)- → [DPIR - MIT](LICENSE).- - [Restormer license](https://raw.githubusercontent.com/swz30/Restormer/main/LICENSE.md)- → [Restormer - MIT](LICENSE).- - [OpenAI GLIDE license](https://raw.githubusercontent.com/openai/glide-text2im/main/LICENSE)- → [OpenAI GLIDE - MIT](LICENSE).-- These upstream branch URLs record where the attached license texts were- obtained; they do not establish the exact revisions of the vendored source.-- ## Excluded source components-- The following unrelated functionality is excluded from this source release- because its source-permission records were incomplete:-- - The optional REDNet upsampler (`deployment/runtime/naf/src/model/rednet.py`)- and its package-level export have been removed. The NAF model used by the- geometry frontend and its Torch Hub entrypoint remain available.- - The YuE2 audio VAE (`deployment/runtime/qwen/diffsynth/models/yue2_vae.py`),- its model-registry entry, and the dependent music-generation pipeline- (`deployment/runtime/qwen/diffsynth/pipelines/yue2.py`) have been removed.- The Qwen-Image-2.1 image VAE, pipeline, and registry entries used by Supra-Tex- are separate components and remain available. The- [Qwen runtime notice](deployment/runtime/qwen/THIRD_PARTY_NOTICES.md)- records the same release boundary.-- These exclusions do not grant permission for the removed code or infer its- terms from the surrounding runtime's Apache-2.0 license.-- This is a map of identified sources and retained notices, not a certification- that every transitive source attribution or release obligation is complete.-- ## Separately installed dependencies and weights-- Separately installed packages such as PyTorch, FlexGEMM, CuMesh, O-Voxel,- nvdiffrast, attention extensions, Diffusers, and Transformers retain their own- upstream terms. The vendored sources listed above have their own notices even- when an installed package of the same name is also used.-- Model weights, including external Qwen, MoGe-2, NAF, and RMBG-2 weights, have- separate model terms. The MIT license for original SUPRA-Tex source does not- license model weights, adapters, or the base models from which they are derived.- In particular, Apache-2.0 runtime source does not establish the license of- Qwen-Image-2.1 weights or adapters. Follow the license and model card supplied- with each separately distributed weight artifact.-- ========================================================================-- Microsoft TRELLIS / TRELLIS.2 - MIT-- 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-- ========================================================================-- Tencent - MIT-- MIT License-- Copyright (c) 2026 Tencent.-- 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.-- ========================================================================-- OpenAI GLIDE - MIT-- MIT License-- Copyright (c) 2021 OpenAI-- 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.-- ========================================================================-- FireRed-Image-Edit - Apache-2.0--- 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 2026 FireRed-Image-Edit Authors. All Rights Reserved.-- 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.-- ========================================================================-- DINOv3 License Agreement-- # DINOv3 License-- *Last Updated: August 19, 2025*-- **“Agreement”** means the terms and conditions for use, reproduction, distribution and modification of the DINO Materials set forth herein.-- **“DINO 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- DINO 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 clicking “I Accept” below or by using or distributing any portion or element of the DINO Materials, you agree to be bound by this Agreement.-- ## 1. License Rights and Redistribution.-- a. <ins>Grant of Rights</ins>. 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 DINO Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the DINO Materials.-- b. <ins>Redistribution and Use</ins>.-- i. Distribution of DINO Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the DINO 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 DINO Materials.-- ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with DINO Materials, you must acknowledge the use of DINO Materials in your publication.-- iii. Your use of the DINO Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws.-- iv. Your use of the DINO Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the DINO Materials.-- v. You are not the target of Trade Controls and your use of DINO Materials must comply with Trade Controls. You agree not to use, or permit others to use, DINO 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 DINO 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 DINO 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 DINO 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 DINO MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE DINO 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 DINO Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the DINO 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 DINO 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 DINO Materials.-- ## 6. Term and Termination.-- The term of this Agreement will commence upon your acceptance of this Agreement or access to the DINO 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 DINO 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 DINO 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.-- ========================================================================-- DPIR - MIT-- MIT License-- Copyright (c) 2020 Kai Zhang ([email protected])-- 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.-- ========================================================================-- Restormer - MIT-- MIT License-- Copyright (c) 2022 Syed Waqas Zamir and contributors-- 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.-- ========================================================================-- vector-quantize-pytorch - MIT-- MIT License-- Copyright (c) 2020 Phil Wang-- 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.-- ========================================================================-- Qwen-Image-2.1 Research License - material adapter and external base weights-- Qwen RESEARCH LICENSE AGREEMENT-- Qwen RESEARCH LICENSE AGREEMENT Release Date: September 20, 2026-- By clicking to agree or by using or distributing any portion or element of the Qwen Materials, you will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.-- 1. Definitions- a. This Qwen RESEARCH LICENSE AGREEMENT (this "Agreement") shall mean the terms and conditions for use, reproduction, distribution and modification of the Materials as defined by this Agreement.- b. "We" (or "Us") shall mean Hangzhou Tongyi Laboratory Technology Co., Ltd.- c. "You" (or "Your") shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Materials for any purpose and in any field of use.- d. "Third Parties" shall mean individuals or legal entities that are not under common control with us or you.- e. "Qwen" shall mean the large language models, diffusion models, and software and algorithms, consisting of trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing distributed by us.- f. "Materials" shall mean, collectively, our proprietary Qwen and Documentation (and any portion thereof) made available under this Agreement.- g. "Source" form shall mean the preferred form for making modifications, including but not limited to model source code, documentation source, and configuration files.- h. "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.- i. "Non-Commercial" shall mean for research or evaluation purposes only.-- 2. Grant of Rights- a. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under our intellectual property or other rights owned by us embodied in the Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Materials FOR NON-COMMERCIAL PURPOSES ONLY.- b. You shall not use the Materials for any commercial purpose without obtaining a separate commercial license from us. If you wish to use the Materials commercially, you shall request a license from us at [email protected].-- 3. Redistribution- Subject to Section 2 (Grant of Rights), you may distribute copies or make the Materials, or derivative works thereof, available as part of a product or service that contains any of them, with or without modifications, and in Source or Object form, provided that you meet the following conditions:- a. You shall give any other recipients of the Materials or derivative works a copy of this Agreement;- b. You shall cause any modified files to carry prominent notices stating that you changed the files;- c. You shall retain in all copies of the Materials that you distribute the following attribution notices within a "Notice" text file distributed as a part of such copies: "Qwen is licensed under the Qwen RESEARCH LICENSE AGREEMENT, Copyright (c) 2026 Hangzhou Tongyi Laboratory Technology Co., Ltd. All Rights Reserved."; and- d. 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 terms and conditions of this Agreement.-- 4. Rules of use- a. The Materials may be subject to export controls or restrictions in China, the United States or other countries or regions. You shall comply with applicable laws and regulations in your use of the Materials.- b. If you use the Materials or any outputs or results therefrom to create, train, fine-tune, or improve an AI model that is distributed or made available, you shall prominently display “Built with Qwen” or “Improved using Qwen” in the related product documentation.- c. You shall not use "Qwen" as the primary name or identifier of any derivative works or products; reasonable descriptive use (e.g., "fine-tuned from Qwen Image") is permitted.-- 5. Intellectual Property- a. We retain ownership of all intellectual property rights in and to the Materials and derivatives made by or for us. Conditioned upon compliance with the terms and conditions of this Agreement, with respect to any derivative works and modifications of the Materials that are made by you, you are and will be the owner of such derivative works and modifications.- b. No trademark license is granted to use the trade names, trademarks, service marks, or product names of us, except as required to fulfill notice requirements under this Agreement or as required for reasonable and customary use in describing and redistributing the Materials.- c. If you commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against us or any entity alleging that the Materials or any output therefrom, or any part of the foregoing, infringe any intellectual property or other right owned or licensable by you, then all licenses granted to you under this Agreement shall terminate as of the date such lawsuit or other proceeding is commenced or brought.-- 6. Disclaimer of Warranty and Limitation of Liability- a. We are not obligated to support, update, provide training for, or develop any further version of the Qwen Materials or to grant any license thereto.- b. THE MATERIALS ARE PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. WE MAKE NO WARRANTY AND ASSUME NO RESPONSIBILITY FOR THE SAFETY OR STABILITY OF THE MATERIALS AND ANY OUTPUT THEREFROM.- c. IN NO EVENT SHALL WE BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE MATERIALS OR ANY OUTPUT OF IT, NO MATTER HOW IT’S CAUSED.- d. You will defend, indemnify and hold harmless us from and against any claim by any third party arising out of or related to your use or distribution of the Materials.-- 7. Survival and Termination.- a. The term of this Agreement shall commence upon your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.- b. We may terminate this Agreement if you breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, you must delete and cease use of the Materials. Sections 6 and 8 shall survive the termination of this Agreement.-- 8. Governing Law and Jurisdiction.- a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.- b. The People's Courts in Hangzhou City shall have exclusive jurisdiction over any dispute arising out of this Agreement.-- 9. Other Terms and Conditions.- a. Any arrangements, understandings, or agreements regarding the Material not stated herein are separate from and independent of the terms and conditions of this Agreement. You shall request a separate license from us, if you use the Materials in ways not expressly agreed to in this Agreement.- b. We shall not be bound by any additional or different terms or conditions communicated by you unless expressly agreed.diff --cc README.mdindex 7951827,6c97218..8ba10a6--- a/README.md+++ b/README.md@@@ -1,11 -1,11 +1,15 @@@<h1 align="center">SUPRA-Tex: 3D Generation with Super-Aligned Texture</h1>++<p align="center">++ <strong>English</strong> | <a href="README_zh-CN.md">简体中文</a>++</p>++<p align="center"><a href="https://supra-3d.github.io/supratex/"><img src="https://img.shields.io/badge/Project-Page-blue" alt="Project page"></a><a href="https://arxiv.org/abs/2610.22352"><img src="https://img.shields.io/badge/Paper-arXiv-b31b1b" alt="arXiv paper"></a><a href="https://huggingface.co/spaces/UniLat3D/Supra-Tex"><img src="https://img.shields.io/badge/Demo-Hugging_Face-blueviolet" alt="Online demo"></a><a href="https://huggingface.co/supra3d/supra-tex"><img src="https://img.shields.io/badge/Models-Hugging_Face-yellow" alt="Model weights"></a>-- <a href="#license"><img src="https://img.shields.io/badge/License-MIT-green" alt="Source license"></a>++ <a href="#license"><img src="https://img.shields.io/badge/License-MIT%20%2B%20third--party-green" alt="Source license"></a></p><p align="center">@@@ -48,50 -48,19 +52,226 @@@ Learn more on the [project page](https:## Release Notes--- **[2026-10-16]** Initial release of the [project page](https://supra-3d.github.io/supratex/) and README. Inference code will follow.++- **[2026-10-19]** Released the inference code: image-to-3D generation++ ([`infer.py`](infer.py)) and texturing of existing meshes++ ([`texturing.py`](texturing.py)).++- **[2026-10-19]** Released the [training overview](docs/train.md), a reference++ for the training workflow that you can follow to train your own models.++- **[2026-10-18]** The [SUPRA-Tex Studio](https://supra-3d.github.io/supratex/studio/studio.html)++ is open: take a tour of our SUPRA-Tex studio.++- **[2026-10-16]** Initial release of the [project page](https://supra-3d.github.io/supratex/),++ README, and [arXiv paper](https://arxiv.org/abs/2610.22352).## Pretrained ModelsOur models are available on [Hugging Face](https://huggingface.co/supra3d/supra-tex).--> **Note:** We are actively working to resolve model deployment issues and will make the model available for use as soon as they are resolved; results from the current version may be inconsistent and do not reflect the final model quality.++> **Note:** We are actively working to resolve model deployment issues. Until they are resolved, access to the models is temporarily gated: please request access on the [model page](https://huggingface.co/supra3d/supra-tex) and log in with `hf auth login` before downloading. Once the issues are resolved, the models will be openly available without an access request. Results from the current version may be inconsistent and do not reflect the final model quality.| Model | Parameters | Download || --- | --- | --- || SUPRA-Tex 3D Completion | 2.1B | [completion](https://huggingface.co/supra3d/supra-tex/tree/main/completion) || SUPRA-Tex Material Adapter | 33.6M trainable | [material](https://huggingface.co/supra3d/supra-tex/tree/main/material) |++## Installation++++SUPRA-Tex requires **Linux** with an **NVIDIA GPU**, a **CUDA 12.4** toolkit with++`nvcc`, Git, and a C++ compiler. The installer sets up a dedicated Python 3.10++Conda environment with PyTorch 2.6.0 and the native CUDA extensions:++++```bash++git clone https://github.com/Supra-3D/SUPRA-Tex.git++cd SUPRA-Tex++conda create -n supra-tex python=3.10 -y++conda activate supra-tex++python scripts/install_runtime.py --conda++```++++For faster attention, also install++[FlashAttention](https://github.com/Dao-AILab/flash-attention): FlashAttention-2++on Ampere, Ada, or Hopper GPUs, and FlashAttention-3 on Hopper. Without it,++inference uses PyTorch SDPA; once installed, it is selected automatically. See the++[installation guide](docs/installation.md#flashattention-recommended-for-speed)++for the commands.++++The full image-to-3D pipeline has been tested on an NVIDIA RTX 3090 (24 GB), where++CPU offload is enabled automatically. See the [installation guide](docs/installation.md)++for `venv` setup and manual installation, and++[GPU compatibility](docs/gpu_compatibility.md) for memory options.++++## Quick Start++++**1. Prepare the models.** Access to the++[SUPRA-Tex models](https://huggingface.co/supra3d/supra-tex) is temporarily gated++(see the [note above](#pretrained-models)), and the image-to-3D pipeline also uses++Meta's [DINOv3](https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m).++Request access on both model pages, log in with an approved account, then++download and assemble all models into `ckpts/ready`:++++```bash++hf auth login++python scripts/prepare_models.py++```++++Add `--with-rmbg` to prepare [RMBG-2](https://huggingface.co/briaai/RMBG-2.0)++for opaque RGB inputs; images with a foreground alpha channel do not need it.++RMBG-2 also requires access approval. To avoid it, use the public++[BiRefNet](https://huggingface.co/ZhengPeng7/BiRefNet), which RMBG-2 is built on++and which loads the same way: download it and pass its directory with++`--rmbg /path/to/BiRefNet` instead of `--with-rmbg`.++++**2. Check the runtime and run the bundled example** (the spiny whelk shell in++[`assets/`](assets)):++++```bash++python scripts/check_runtime.py++python scripts/run_example.py --output outputs/spiny_whelk_shell.glb++```++++**3. Generate a textured asset from your own image:**++++```bash++python scripts/run_example.py --input assets/metalwork_candle_jar.png \++ --output outputs/metalwork_candle_jar.glb++```++++This example uses the opaque RGB candle jar in [`assets/`](assets), so it needs++the RMBG-2 or BiRefNet model from step 1; replace `--input` with your own image.++The output is a GLB with base color, metallic, and roughness textures. A sibling++work directory keeps intermediate files and a `run.json` receipt.++++**Texture an existing mesh.** Given a mesh, its camera, a foreground image, and++reference-view material maps, complete the PBR textures directly. The repository++bundles the project-page pitcher plant mesh with its inputs in++[`assets/examples/pitcher_plant`](assets/examples/pitcher_plant), the default++input of `texturing.py`:++++```bash++python texturing.py --pipeline supra3d/supra-tex --output outputs/pitcher_plant_textured.glb++```++++Pass `--input-dir` to texture your own mesh; see [texturing](docs/texturing.md)++for the input format.++++## Improving Results++++The defaults suit most inputs. When a result falls short, these options help;++for run time, see [Inference Speed](#inference-speed).++++- **Refine fine detail.** For very small, intricate text and textures, add++ `--refine`. After export, it further refines the visible texture and aligns it++ with the input image. Refinement adds about two minutes on an RTX 3090, so it is++ off by default. In this example, the wiring table on the industrial disconnect++ switch packs a specification table, circuit symbols, and fine caution print into++ one label:++++ ```bash++ python scripts/run_example.py --input assets/industrial_disconnect_switch.png \++ --output outputs/wiring_table.glb --refine++ ```++++- **Start from a clean input.** Use a sharp image of one object that is fully in++ frame and fills most of it: the image is reduced to 1024 pixels on its longest++ side before cropping to the object, so a small object in a large frame loses++ detail. Prefer an RGBA image with a clean foreground alpha to automatic++ background removal. Only pixels with alpha of at least 254 serve as texture++ observations, so soft or noisy edges leave more to completion.++- **Check the alignment report.** Each run prints an `Observation: silhouette IoU`++ line that compares the geometry with the image foreground, with a warning++ below 0.9. Mismatched regions take their texture from completion rather than++ the image. Add `--geometry-scale-search` to calibrate the mesh scale, or try++ another `--seed` to resample geometry and completion.++- **Handle extra geometry.** Pixal3D geometry is sometimes misaligned with the++ image or carries extra pieces, which then receive texture the image never++ showed. Image-to-3D runs remove disconnected pieces that project mostly++ outside the image foreground before completion (`--no-remove-floaters` keeps++ them; `texturing.py` applies it with `--remove-floaters`). It keeps everything++ the foreground covers, so it does not remove pieces hidden behind the object or++ extra geometry attached to it. For those, try another `--seed`, or clean the++ mesh yourself and texture it with `texturing.py`.++- **Keep more geometric detail.** `--decimation-target` sets the exported face++ count (500,000 by default); raise it for intricate shapes.++++## Make It Yours++++Single-view inference observes only what the reference image shows; everything++else comes from completion. Dual-view texturing adds a second, generated++observation of the back so that the unseen side also follows an image. It works++in five stages, each a separate command in++[dual-view texturing](docs/dual_view.md):++++1. **Front inputs.** The image-to-3D frontend produces the mesh, camera, and++ reference-view material maps, recording which models produced them.++2. **Back normal pack.** The mesh is rendered from a back camera chosen around++ the opposite view, as a normal map and silhouette mask that share the same++ rasterization.++3. **Back image.** An image generator paints a back view that follows the normal++ pack, and a visual review accepts or rejects it. Our implementation runs++ GPT-6 Astra with its built-in image generation tool through the external Codex++ CLI; this is the only stage outside this repository.++4. **Back materials.** The accepted image is cut to the rendered silhouette, and++ the same material adapter predicts its albedo and metallic/roughness maps.++5. **Completion and refinement.** Both views become surface observations, with++ the front taking priority where they overlap, and a single completion run++ fills the rest. Refinement then projects each view into the texture atlas and++ repairs the UV gutters.++++The back image is the creative part: it decides what the unseen side looks like.++Stages 1, 2, 4, and 5 run locally, so the pipeline is ready for another back-view++generator. As foundation image models improve, dual-view results can improve++with them. See [dual-view texturing](docs/dual_view.md) for requirements and the++staged commands.++++## Documentation++++| Guide | Contents |++| --- | --- |++| [Quick start](docs/quickstart.md) | Installation, model preparation, and the first run in detail |++| [Method overview](docs/method.md) | Pipeline stages and where each is implemented |++| [Training overview](docs/train.md) | Data preparation and training workflow; training code is not released |++| [End-to-end inference](docs/end_to_end.md) | All `infer.py` options |++| [Material frontend](docs/frontend.md) | Foreground, camera, and reference-view material maps |++| [Geometry](docs/geometry.md) | Pixal3D geometry generation and optional scale search |++| [Texturing](docs/texturing.md) | `texturing.py` inputs and options |++| [Dual-view texturing](docs/dual_view.md) | Front/back observation fusion with a generated back view; back-view generation uses GPT-6 Astra through the external Codex CLI |++| [Model weights](docs/weights.md) | Model layouts and external dependencies |++| [GPU compatibility](docs/gpu_compatibility.md) | Attention backends, CPU offload, and tested GPUs |+++## Inference Speed++Most inference time on modest hardware goes to reading weights and moving them+between CPU and GPU, not to model compute. These settings help:+++- **Install FlashAttention.** FlashAttention-2, or FlashAttention-3 on Hopper, is++ faster than the PyTorch SDPA fallback and is selected automatically once++ installed ([commands](docs/installation.md#flashattention-recommended-for-speed)).+++- **Keep weights on an SSD.** The geometry and Qwen stages read tens of+ gigabytes of weights per run. On a hard disk, loading dominates both stages; an+ SSD cuts their load time by more than half.+- **Use a GPU with at least 48 GB.** GPUs with up to 24 GiB enable CPU offload+ automatically, which moves the Qwen model block by block during inference.+ Larger GPUs keep models resident, and the Qwen stage becomes much faster.+- **Use two GPUs.** The geometry and Qwen material stages are independent.+ `--parallel-frontend` runs them concurrently on the first two visible GPUs;+ `CUDA_VISIBLE_DEVICES` selects which ones. Both stages then hold their models+ in CPU memory at the same time, so check host RAM when offload is enabled.+- **Store geometry weights in their runtime precision.** The geometry flow+ checkpoints store float32 for blocks that run in bfloat16. Writing cast copies+ once halves the bytes read on every run and gives identical results:++ ```bash- python scripts/convert_geometry_weights.py --config ckpts/ready/models.json++ python scripts/convert_geometry_weights.py+ ```++ The copies (about 8 GB) are saved beside the originals and used automatically.+- **Geometry scale search is optional.** By default, geometry follows Pixal3D+ with a fixed mesh scale. `--geometry-scale-search` enables a bounded scale+ calibration that adds one sampling pass per probe (up to three).+- **Pre-tuned sparse-convolution kernels apply only to H800.** On H800 with+ PyTorch 2.6 (CUDA 12.4), Triton 3.2, and FlexGEMM 1.0, a measured kernel+ configuration is loaded. Other GPUs autotune these kernels on first use.+## AcknowledgmentsOur implementation builds on [TRELLIS.2](https://github.com/microsoft/TRELLIS.2)@@@ -101,12 -70,12 +281,13 @@@ making their work available## License--The 3D completion weights are released under the--[MIT License](https://opensource.org/license/mit). Original SUPRA-Tex source--will be released under the same license. **Built with Qwen:** the material--adapter uses the Qwen Research License for non-commercial research and--evaluation. Third-party code and external models retain their respective--licenses.++Original SUPRA-Tex source code and the 3D completion weights are released++under the [MIT License](LICENSE). The repository also includes third-party code++under MIT, Apache-2.0, and the DINOv3 License;++[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) lists each component and its++terms. **Built with Qwen:** the material adapter uses the Qwen Research License++for non-commercial research and evaluation. External models retain their++respective licenses.## Citationdiff --cc README_zh-CN.mdindex 0000000,0000000..f2be01enew file mode 100644--- /dev/null+++ b/README_zh-CN.md@@@ -1,0 -1,0 +1,263 @@@++<h1 align="center">SUPRA-Tex: 3D Generation with Super-Aligned Texture</h1>++++<p align="center">++ <a href="README.md">English</a> | <strong>简体中文</strong>++</p>++++<p align="center">++ <a href="https://supra-3d.github.io/supratex/"><img src="https://img.shields.io/badge/Project-Page-blue" alt="项目主页"></a>++ <a href="https://arxiv.org/abs/2610.22352"><img src="https://img.shields.io/badge/Paper-arXiv-b31b1b" alt="arXiv 论文"></a>++ <a href="https://huggingface.co/spaces/UniLat3D/Supra-Tex"><img src="https://img.shields.io/badge/Demo-Hugging_Face-blueviolet" alt="在线演示"></a>++ <a href="https://huggingface.co/supra3d/supra-tex"><img src="https://img.shields.io/badge/Models-Hugging_Face-yellow" alt="模型权重"></a>++ <a href="#许可证"><img src="https://img.shields.io/badge/License-MIT%20%2B%20third--party-green" alt="源码许可证"></a>++</p>++++<p align="center">++ <a href="https://chensjtu.github.io/">Chen Yang</a><sup>1*</sup>,++ <a href="https://jaminfong.cn/">Jiemin Fang</a><sup>1*†✉</sup>,++ <a href="https://mfp0610.github.io/">Fanpeng Meng</a><sup>1*</sup>,++ <a href="https://inso-13.github.io/">Zihao Huang</a><sup>1</sup>,<br>++ <a href="https://supra-3d.github.io/supratex/#paper">Jichen Pang</a><sup>2</sup>,++ <a href="https://wuguanjun0627.github.io/">Guanjun Wu</a><sup>3</sup>,++ <a href="https://supra-3d.github.io/supratex/#paper">Zhikuan Bao</a><sup>1</sup>,++ <a href="https://www.qitian1987.com/index.html">Qi Tian</a><sup>1✉</sup>++</p>++++<p align="center">++ <sup>1</sup>Huawei Inc. ++ <sup>2</sup>Shanghai Jiao Tong University ++ <sup>3</sup>Huazhong University of Science and Technology<br>++ <sup>*</sup>Equal contribution ++ <sup>†</sup>Project lead ++ <sup>✉</sup>Corresponding authors++</p>++++https://github.com/user-attachments/assets/ecc9e9ec-e91f-4eba-927d-86322796459a++++**SUPRA-Tex** 从单张图像生成带纹理的 3D 资产,保留文字、图案和材质边界等细节。++它先预测参考视角下的 PBR 材质,将其编码为与三维表面对齐的观测,再通过++**Interleaved Flow Transformer(交错式流 Transformer)** 补全不可见区域。++最终输出包含基础颜色、金属度和粗糙度贴图的 GLB,可在不同光照下重新渲染。++++- **与图像对齐的纹理。** 利用可见表面的观测引导三维材质生成,保留输入图像中的细节。++- **完整的 PBR 资产。** 为不可见表面生成材质,并导出支持不同光照条件下渲染的贴图。++- **图像生成 3D 与已有网格贴纹理。** 从图像生成资产,或结合匹配的相机和材质观测,为已有网格生成纹理。++++更多介绍请参阅[项目主页](https://supra-3d.github.io/supratex/),也可以体验++[在线演示](https://huggingface.co/spaces/UniLat3D/Supra-Tex)。++++## 更新日志++++- **[2026-10-19]** 发布推理代码,支持从图像生成 3D++ ([`infer.py`](infer.py))和为已有网格生成纹理([`texturing.py`](texturing.py))。++- **[2026-10-19]** 发布[训练参考文档](docs/train.md),可以参考该文档训练自己的模型。++- **[2026-10-18]** [SUPRA-Tex 工作室](https://supra-3d.github.io/supratex/studio/studio.html)++ 已开放,欢迎参观。++- **[2026-10-16]** 首次发布[项目主页](https://supra-3d.github.io/supratex/)、README 和++ [arXiv 论文](https://arxiv.org/abs/2610.22352)。++++## 预训练模型++++模型已发布至 [Hugging Face](https://huggingface.co/supra3d/supra-tex)。++++> **说明:** 我们正在解决模型部署问题。在问题解决前,模型暂时需要申请访问权限:请先在[模型页面](https://huggingface.co/supra3d/supra-tex)申请访问,并通过 `hf auth login` 登录后再下载。问题解决后,模型将直接开放,无需申请访问权限。当前版本的生成结果可能不稳定,不代表最终模型质量。++++| 模型 | 参数量 | 下载 |++| --- | --- | --- |++| SUPRA-Tex 三维材质补全模型 | 2.1B | [completion](https://huggingface.co/supra3d/supra-tex/tree/main/completion) |++| SUPRA-Tex 材质适配器 | 33.6M 可训练参数 | [material](https://huggingface.co/supra3d/supra-tex/tree/main/material) |++++## 安装++++SUPRA-Tex 需要 **Linux**、**NVIDIA GPU**、包含 `nvcc` 的 **CUDA 12.4** 工具包、++Git 和 C++ 编译器。安装脚本会在专用的 Python 3.10 Conda 环境中配置++PyTorch 2.6.0 和原生 CUDA 扩展:++++```bash++git clone https://github.com/Supra-3D/SUPRA-Tex.git++cd SUPRA-Tex++conda create -n supra-tex python=3.10 -y++conda activate supra-tex++python scripts/install_runtime.py --conda++```++++如需更快的 attention,请另外安装 [FlashAttention](https://github.com/Dao-AILab/flash-attention):++Ampere、Ada 或 Hopper GPU 安装 FlashAttention-2,Hopper GPU 可安装 FlashAttention-3。++未安装时推理使用 PyTorch SDPA;安装后会自动选用。安装命令见++[安装指南](docs/installation.md#flashattention-recommended-for-speed)。++++完整的图像生成 3D 流程已在 NVIDIA RTX 3090(24 GB)上测试,该显卡会自动启用 CPU 卸载。++`venv` 环境配置和手动安装请参阅[安装指南](docs/installation.md);++显存相关选项请参阅 [GPU 兼容性说明](docs/gpu_compatibility.md)。++++## 快速开始++++**1. 准备模型。** [SUPRA-Tex 模型](https://huggingface.co/supra3d/supra-tex)++暂时需要申请访问权限(见[上方说明](#预训练模型)),图像生成 3D 流程还使用 Meta 的++[DINOv3](https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m)。++请在这两个模型页面申请访问权限,使用已获批准的账号登录,然后将所有模型下载并整理到 `ckpts/ready`:++++```bash++hf auth login++python scripts/prepare_models.py++```++++对于不透明的 RGB 输入,添加 `--with-rmbg` 以准备++[RMBG-2](https://huggingface.co/briaai/RMBG-2.0);带前景 alpha 通道的图像无需此模型。++RMBG-2 同样需要申请访问权限。也可以使用公开的++[BiRefNet](https://huggingface.co/ZhengPeng7/BiRefNet):RMBG-2 基于该模型构建,二者的加载方式相同。++下载 BiRefNet 后,通过 `--rmbg /path/to/BiRefNet` 指定其目录,替代 `--with-rmbg`。++++**2. 检查运行环境并运行仓库附带的示例**([`assets/`](assets) 中的多刺海螺):++++```bash++python scripts/check_runtime.py++python scripts/run_example.py --output outputs/spiny_whelk_shell.glb++```++++**3. 使用自己的图像生成带纹理的 3D 资产:**++++```bash++python scripts/run_example.py --input assets/metalwork_candle_jar.png \++ --output outputs/metalwork_candle_jar.glb++```++++该示例使用 [`assets/`](assets) 中不带 alpha 的 RGB 金属香薰蜡烛罐图像,因此需要第 1 步中的++RMBG-2 或 BiRefNet 模型;将 `--input` 换成自己的图像即可。++输出为包含基础颜色、金属度和粗糙度贴图的 GLB。++输出文件旁的工作目录会保留中间文件和 `run.json` 运行记录。++++**为已有网格生成纹理。** 给定网格、对应相机、前景图像和参考视角的材质图,即可直接补全 PBR 纹理。++仓库在 [`assets/examples/pitcher_plant`](assets/examples/pitcher_plant) 中附带了项目主页上的++猪笼草网格及其输入文件,也是 `texturing.py` 的默认输入:++++```bash++python texturing.py --pipeline supra3d/supra-tex --output outputs/pitcher_plant_textured.glb++```++++通过 `--input-dir` 为自己的网格指定输入目录;输入格式请参阅[纹理生成指南](docs/texturing.md)。++++## 提升生成效果++++默认设置适用于大多数输入。如果结果不够理想,可以尝试以下方法;运行速度相关的设置见[推理速度](#推理速度)。++++- **进一步细化纹理。** 对于非常细小、精密的文字和纹理,可以添加 `--refine`:++ 导出后,它会进一步细化可见区域的纹理,并使其与输入图像对齐。++ 细化会增加耗时(RTX 3090 上约两分钟),因此默认关闭。++ 下面的示例中,工业隔离开关的接线表在一张标签上集中了规格表、电路符号和细小的警示文字:++++ ```bash++ python scripts/run_example.py --input assets/industrial_disconnect_switch.png \++ --output outputs/wiring_table.glb --refine++ ```++++- **使用干净的输入图像。** 使用清晰的单个物体图像,物体完整入镜且占据画面的大部分:++ 图像会先把长边缩小到 1024 像素再按物体裁剪,物体在大画面中占比过小会损失细节。++ 相比自动去背景,优先使用带干净前景 alpha 的 RGBA 图像。只有 alpha 不低于 254 的像素++ 会作为纹理观测,边缘柔化或有噪声时,更多区域需要依赖补全。++- **查看对齐报告。** 每次运行都会打印一行 `Observation: silhouette IoU`,比较几何与图像前景的++ 轮廓,低于 0.9 时会给出警告。不匹配的区域由补全生成纹理,而不是取自图像。++ 可以添加 `--geometry-scale-search` 校准网格尺度,或换一个 `--seed` 重新采样几何和补全。++- **处理多余几何。** Pixal3D 生成的几何有时会和图像对不齐,或者多出额外的部件,++ 这些部件会被赋予图像中并不存在的纹理。从图像生成 3D 时,默认会在补全前删除与主体不相连、++ 且投影大部分落在图像前景之外的部件(`--no-remove-floaters` 可保留;`texturing.py`++ 需加 `--remove-floaters` 才会启用)。前景覆盖范围内的几何都会保留,因此被物体挡住的碎片、++ 以及连在主体上的多余几何不会被删除。遇到这两类情况,可以换一个 `--seed` 重新生成,++ 或者自行清理网格后用 `texturing.py` 上色。++- **保留更多几何细节。** `--decimation-target` 设置导出的面数(默认 500,000),++ 复杂形状可以适当调高。++++## Make It Yours++++单视角推理只能观测到参考图中可见的部分,其余区域都由补全生成。dual-view++额外生成一张背面观测,让看不到的一侧也能参照图像生成纹理。它分为五个阶段,++每个阶段都是 [dual-view 文档](docs/dual_view.md)中的一条单独命令:++++1. **正面输入。** 图像生成 3D 的前端生成网格、相机和参考视角的材质图,并记录所用的模型。++2. **背面法线包。** 从相反方向附近选定的背面相机渲染网格,得到共用同一次光栅化的++ 法线图和轮廓 mask。++3. **背面图像。** 图像生成器按法线包绘制背面图,再由视觉审核决定是否采用。++ 我们的实现通过外部的 Codex CLI 调用 GPT-6 Astra 及其内置的图像生成工具,这是唯一不在本仓库内的阶段。++4. **背面材质。** 采用的图像按渲染轮廓裁切,再用同一个材质 adapter 预测 albedo 和金属度/粗糙度图。++5. **补全与细化。** 两个视角都转为表面观测,重叠处以正面为准,只运行一次补全来生成其余区域;++ 随后细化把每个视角投影进纹理图集,并修复 UV 边缘留白。++++背面图像是最有创造性的部分,它决定了看不到的一侧是什么样子。第 1、2、4、5++阶段都在本地运行,因此可以接入其他背面生成器。随着图像基础模型的发展,dual-view 的效果++也会随之提升。环境要求和分步命令见 [dual-view 文档](docs/dual_view.md)。++++## 文档++++| 指南 | 内容 |++| --- | --- |++| [快速开始](docs/quickstart.md) | 安装、模型准备和首次运行的详细步骤 |++| [方法概述](docs/method.md) | 流程各阶段及对应的代码实现 |++| [训练流程概述](docs/train.md) | 数据准备与训练流程;训练代码暂未开源 |++| [端到端推理](docs/end_to_end.md) | `infer.py` 的全部选项 |++| [材质前端](docs/frontend.md) | 前景处理、相机和参考视角材质图 |++| [几何生成](docs/geometry.md) | Pixal3D 几何生成和可选的尺度搜索 |++| [纹理生成](docs/texturing.md) | `texturing.py` 的输入格式与选项 |++| [双视角纹理生成](docs/dual_view.md) | 结合生成背面视角的前后视角观测融合;背面视角通过外部 Codex CLI 调用 GPT-6 Astra 生成 |++| [模型权重](docs/weights.md) | 模型目录结构和外部依赖 |++| [GPU 兼容性](docs/gpu_compatibility.md) | Attention 后端、CPU 卸载和已测试的 GPU |++++## 推理速度++++在硬件资源有限的情况下,推理耗时主要来自读取权重,以及在 CPU 和 GPU 之间搬运权重,++模型计算本身并非主要耗时。以下设置有助于加速:++++- **安装 FlashAttention。** FlashAttention-2(Hopper 上可用 FlashAttention-3)比默认回退的++ PyTorch SDPA 更快,安装后会自动选用([安装命令](docs/installation.md#flashattention-recommended-for-speed))。++++- **将权重放在 SSD 上。** 几何和 Qwen 阶段每次运行都需要读取数十 GB 的权重。++ 使用机械硬盘时,加载会占据这两个阶段的大部分耗时;使用 SSD 可将加载时间缩短一半以上。++- **使用至少 48 GB 显存的 GPU。** 显存不超过 24 GiB 的 GPU 会自动启用 CPU 卸载,++ 在推理时逐块搬运 Qwen 模型。更大显存的 GPU 可以让模型常驻显存,显著加快 Qwen 阶段。++- **使用两张 GPU。** 几何生成和 Qwen 材质预测相互独立。++ `--parallel-frontend` 会在前两张可见 GPU 上并行运行这两个阶段;++ 可通过 `CUDA_VISIBLE_DEVICES` 指定 GPU。此时两个阶段会同时在 CPU 内存中保留模型,++ 因此启用卸载时需留意主机内存容量。++- **按运行时精度存储几何权重。** 几何 flow 模型中以 bfloat16 运行的模块,++ 其 checkpoint 仍以 float32 存储。预先保存一次转换后的副本,可以将每次运行的读取量减半,++ 同时保持输出结果一致:++++ ```bash++ python scripts/convert_geometry_weights.py++ ```++++ 转换后的副本约为 8 GB,保存在原文件旁,并会被自动使用。++- **几何尺度搜索为可选项。** 默认按照 Pixal3D 的方式使用固定网格尺度。++ `--geometry-scale-search` 会启用有次数上限的尺度校准,每次探测增加一轮采样,最多三轮。++- **预调优的稀疏卷积内核配置仅适用于 H800。** 在 H800、PyTorch 2.6(CUDA 12.4)、++ Triton 3.2 和 FlexGEMM 1.0 的组合下,会加载经过实测的内核配置。++ 其他 GPU 会在首次使用时自动调优这些内核。++++## 致谢++++本项目基于 [TRELLIS.2](https://github.com/microsoft/TRELLIS.2)++和 [Pixal3D](https://github.com/TencentARC/Pixal3D) 构建。++同时感谢 Qwen-Image、FireRed-Image-Edit、MoGe、NAF、CuMesh、FlexGEMM++和 nvdiffrast 的作者公开其工作。++++## 许可证++++SUPRA-Tex 原创源码和三维材质补全模型权重采用 [MIT 许可证](LICENSE)。++仓库还包含采用 MIT、Apache-2.0 和 DINOv3 License 的第三方代码;++[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) 列出了各组件及其条款。++**Built with Qwen:** 材质适配器采用 Qwen Research License,供非商业研究和评估使用。++外部模型仍遵循各自的许可证。++++## 引用++++如果本项目对您的研究有帮助,请引用:++++```bibtex++@article{yang2026supratex,++ title = {{SUPRA-Tex}: 3D Generation with Super-Aligned Texture},++ author = {Yang, Chen and Fang, Jiemin and Meng, Fanpeng and Huang, Zihao++ and Pang, Jichen and Wu, Guanjun and Bao, Zhikuan and Tian, Qi},++ journal = {arXiv preprint arXiv:2610.22352},++ year = {2026},++ url = {https://arxiv.org/abs/2610.22352}++}++```diff --cc THIRD_PARTY_NOTICES.mdindex 0000000,0000000..f5c73ebnew file mode 100644--- /dev/null+++ b/THIRD_PARTY_NOTICES.md@@@ -1,0 -1,0 +1,628 @@@++# Third-Party Notices++++SUPRA-Tex's original source code is licensed under the [MIT License](LICENSE).++This repository also includes third-party code under MIT, Apache-2.0, and the++DINOv3 License. Those components remain under their own terms, which are mapped++below; the full texts are reproduced under [License texts](#license-texts).++++## Microsoft and Tencent MIT components++++The sparse tensor modules, flow/autoencoder infrastructure, mesh representations,++rendering utilities, and inherited pipeline/training infrastructure include code++from Microsoft TRELLIS/TRELLIS.2 and Tencent's MIT-licensed 3D implementation.++Applicable upstream copyrights and full permission notices are retained in:++++- [Microsoft MIT license](#microsoft-mit): Copyright (c) Microsoft Corporation.++- [Tencent MIT license](#tencent-mit): Copyright (c) 2026 Tencent.++++The SUPRA-Tex package and method names describe this project; they do not change++ownership of incorporated upstream code.++++`supratex/inference/mesh_export.py` adapts the O-Voxel exporter from Microsoft++TRELLIS.2 under the Microsoft MIT license above. Supra-Tex replaces its texture++conversion and gap-filling stage with packed GPU quantization and grouped Telea++operations; mesh processing and texture baking retain the upstream algorithm.++++The separately vendored geometry snapshot is in++[`deployment/runtime/geometry/pixal3d/`](deployment/runtime/geometry/pixal3d).++Its [snapshot notice](deployment/runtime/geometry/NOTICE.md),++[Microsoft MIT license](deployment/runtime/geometry/TRELLIS2-MIT.txt), and++[Tencent MIT license](deployment/runtime/geometry/TENCENT-MIT.txt) accompany it.++++The `timestep_embedding` implementation in++[`supratex/models/sparse_structure_flow.py`](supratex/models/sparse_structure_flow.py)++and its++[vendored geometry counterpart](deployment/runtime/geometry/pixal3d/models/sparse_structure_flow.py)++credits OpenAI's GLIDE. The applicable++[OpenAI GLIDE MIT license](#openai-glide-mit) retains++Copyright (c) 2021 OpenAI.++++## FireRed material-model runtime++++`supratex/frontend/material_model/runtime/` includes code adapted from++FireRed-Image-Edit and the factorized material-model implementation. Incorporated++FireRed portions remain licensed under Apache License 2.0. Original source++copyright notices are retained, and adaptations for this distribution are marked++in the source files. The project MIT license applies to original SUPRA-Tex++contributions and does not relicense those upstream portions.++++The full [FireRed Apache-2.0 license](#firered-apache-2.0) is included,++with the upstream statement: Copyright 2026 FireRed-Image-Edit Authors. All Rights Reserved.++++Release adaptations include the local inference entrypoint, explicit external++model/checkpoint paths, input validation, and a self-contained import layout.++++## Vendored deployment code++++The following source code is present in this repository; it is not merely an++external installation requirement. The recorded snapshot origins and limits of++the available version information are in++[`deployment/runtime/SOURCE_PROVENANCE.json`](deployment/runtime/SOURCE_PROVENANCE.json).++Top-level licenses do not override the terms of incorporated subcomponents.++++| Distributed path | Source and applicable notices |++| --- | --- |++| [`deployment/runtime/qwen/`](deployment/runtime/qwen) | Qwen material-model runtime, including `diffsynth`; its top-level [Apache-2.0 license](deployment/runtime/qwen/LICENSE) is retained. The [runtime third-party notices](deployment/runtime/qwen/THIRD_PARTY_NOTICES.md) map MIT subcomponents and document the excluded YuE2 audio VAE and pipeline. |++| [`deployment/runtime/moge/`](deployment/runtime/moge) | Microsoft MoGe source under MIT. The bundled [license file](deployment/runtime/moge/LICENSE) contains both the Microsoft MIT license and the Apache-2.0 text for incorporated DINOv2 code. [`moge/model/dinov2/`](deployment/runtime/moge/moge/model/dinov2) retains Meta copyright and Apache-2.0 headers. |++| [`deployment/runtime/utils3d/`](deployment/runtime/utils3d) | EasternJournalist utils3d; [MIT license](deployment/runtime/utils3d/LICENSE), Copyright (c) 2022 EasternJournalist. |++| [`deployment/runtime/naf/`](deployment/runtime/naf) | Valeo NAF snapshot with its top-level [Apache-2.0 license](deployment/runtime/naf/LICENSE). The component-specific DINOv3, DPIR, and Restormer notices and the REDNet exclusion are listed below. |++++### Component-specific source licenses++++| Distributed path | Upstream component | Retained license |++| --- | --- | --- |++| [`deployment/runtime/naf/src/layers/rope.py`](deployment/runtime/naf/src/layers/rope.py) | Meta DINOv3, as stated in the source header | [DINOv3 License Agreement](#dinov3-license); this is Meta's custom agreement, not MIT or Apache-2.0. |++| [`deployment/runtime/naf/src/model/ircnn.py`](deployment/runtime/naf/src/model/ircnn.py) | `cszn/DPIR`, `models/network_dncnn.py` | [MIT](#dpir-mit), Copyright (c) 2020 Kai Zhang. |++| [`deployment/runtime/naf/src/model/restormer.py`](deployment/runtime/naf/src/model/restormer.py) | `swz30/Restormer` | [MIT](#restormer-mit), Copyright (c) 2022 Syed Waqas Zamir and contributors. |++| [`deployment/runtime/qwen/diffsynth/models/ace_step_residual_fsq.py`](deployment/runtime/qwen/diffsynth/models/ace_step_residual_fsq.py) | `lucidrains/vector-quantize-pytorch`, `residual_fsq.py` | [MIT](#vector-quantize-pytorch-mit), Copyright (c) 2020 Phil Wang. |++++The five additional license texts were retrieved in full from these official++upstream files on 2026-10-14:++++- [DINOv3 license](https://raw.githubusercontent.com/facebookresearch/dinov3/main/LICENSE.md)++ → [DINOv3 License Agreement](#dinov3-license).++- [vector-quantize-pytorch license](https://raw.githubusercontent.com/lucidrains/vector-quantize-pytorch/master/LICENSE)++ → [vector-quantize-pytorch - MIT](#vector-quantize-pytorch-mit).++- [DPIR license](https://raw.githubusercontent.com/cszn/DPIR/master/LICENSE)++ → [DPIR - MIT](#dpir-mit).++- [Restormer license](https://raw.githubusercontent.com/swz30/Restormer/main/LICENSE.md)++ → [Restormer - MIT](#restormer-mit).++- [OpenAI GLIDE license](https://raw.githubusercontent.com/openai/glide-text2im/main/LICENSE)++ → [OpenAI GLIDE - MIT](#openai-glide-mit).++++These upstream branch URLs record where the attached license texts were++obtained; they do not establish the exact revisions of the vendored source.++++## Excluded source components++++The following unrelated functionality is not part of this source release:++++- The optional REDNet upsampler (`deployment/runtime/naf/src/model/rednet.py`)++ and its package-level export have been removed. The NAF model used by the++ geometry frontend and its Torch Hub entrypoint remain available.++- The YuE2 audio VAE (`deployment/runtime/qwen/diffsynth/models/yue2_vae.py`),++ its model-registry entry, and the dependent music-generation pipeline++ (`deployment/runtime/qwen/diffsynth/pipelines/yue2.py`) have been removed.++ The Qwen-Image-2.1 image VAE, pipeline, and registry entries used by Supra-Tex++ are separate components and remain available. The++ [Qwen runtime notice](deployment/runtime/qwen/THIRD_PARTY_NOTICES.md)++ records the same release boundary.++++These exclusions do not grant permission for the removed code or infer its++terms from the surrounding runtime's Apache-2.0 license.++++++## Separately installed dependencies and weights++++Separately installed packages such as PyTorch, FlexGEMM, CuMesh, O-Voxel,++nvdiffrast, attention extensions, Diffusers, and Transformers retain their own++upstream terms. The vendored sources listed above have their own notices even++when an installed package of the same name is also used.++++Model weights, including external Qwen, MoGe-2, NAF, and RMBG-2 weights, have++separate model terms. The MIT license for original SUPRA-Tex source does not++license model weights, adapters, or the base models from which they are derived.++In particular, Apache-2.0 runtime source does not establish the license of++Qwen-Image-2.1 weights or adapters. Follow the license and model card supplied++with each separately distributed weight artifact.++++## License texts++++<a id="microsoft-mit"></a>++++### Microsoft TRELLIS / TRELLIS.2 - MIT++++```text++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++```++++<a id="tencent-mit"></a>++++### Tencent - MIT++++```text++MIT License++++Copyright (c) 2026 Tencent.++++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.++```++++<a id="openai-glide-mit"></a>++++### OpenAI GLIDE - MIT++++```text++MIT License++++Copyright (c) 2021 OpenAI++++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.++```++++<a id="firered-apache-2.0"></a>++++### FireRed-Image-Edit - Apache-2.0++++```text++ 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 2026 FireRed-Image-Edit Authors. All Rights Reserved.++++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.++```++++<a id="dinov3-license"></a>++++### DINOv3 License Agreement++++```text++# DINOv3 License++++*Last Updated: August 19, 2025*++++**“Agreement”** means the terms and conditions for use, reproduction, distribution and modification of the DINO Materials set forth herein.++++**“DINO 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++DINO 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 clicking “I Accept” below or by using or distributing any portion or element of the DINO Materials, you agree to be bound by this Agreement.++++## 1. License Rights and Redistribution.++++a. <ins>Grant of Rights</ins>. 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 DINO Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the DINO Materials.++++b. <ins>Redistribution and Use</ins>.++++i. Distribution of DINO Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the DINO 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 DINO Materials.++++ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with DINO Materials, you must acknowledge the use of DINO Materials in your publication.++++iii. Your use of the DINO Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws.++++iv. Your use of the DINO Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the DINO Materials.++++v. You are not the target of Trade Controls and your use of DINO Materials must comply with Trade Controls. You agree not to use, or permit others to use, DINO 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 DINO 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 DINO 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 DINO 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 DINO MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE DINO 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 DINO Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the DINO 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 DINO 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 DINO Materials.++++## 6. Term and Termination.++++The term of this Agreement will commence upon your acceptance of this Agreement or access to the DINO 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 DINO 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 DINO 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.++```++++<a id="dpir-mit"></a>++++### DPIR - MIT++++```text++MIT License++++Copyright (c) 2020 Kai Zhang ([email protected])++++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.++```++++<a id="restormer-mit"></a>++++### Restormer - MIT++++```text++MIT License++++Copyright (c) 2022 Syed Waqas Zamir and contributors++++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.++```++++<a id="vector-quantize-pytorch-mit"></a>++++### vector-quantize-pytorch - MIT++++```text++MIT License++++Copyright (c) 2020 Phil Wang++++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.++```++++<a id="qwen-research-license"></a>++++### Qwen-Image-2.1 Research License - material adapter and external base weights++++```text++Qwen RESEARCH LICENSE AGREEMENT++++Qwen RESEARCH LICENSE AGREEMENT Release Date: September 20, 2026++++By clicking to agree or by using or distributing any portion or element of the Qwen Materials, you will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.++++1. Definitions++ a. This Qwen RESEARCH LICENSE AGREEMENT (this "Agreement") shall mean the terms and conditions for use, reproduction, distribution and modification of the Materials as defined by this Agreement.++ b. "We" (or "Us") shall mean Hangzhou Tongyi Laboratory Technology Co., Ltd.++ c. "You" (or "Your") shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Materials for any purpose and in any field of use.++ d. "Third Parties" shall mean individuals or legal entities that are not under common control with us or you.++ e. "Qwen" shall mean the large language models, diffusion models, and software and algorithms, consisting of trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing distributed by us.++ f. "Materials" shall mean, collectively, our proprietary Qwen and Documentation (and any portion thereof) made available under this Agreement.++ g. "Source" form shall mean the preferred form for making modifications, including but not limited to model source code, documentation source, and configuration files.++ h. "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.++ i. "Non-Commercial" shall mean for research or evaluation purposes only.++++2. Grant of Rights++ a. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under our intellectual property or other rights owned by us embodied in the Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Materials FOR NON-COMMERCIAL PURPOSES ONLY.++ b. You shall not use the Materials for any commercial purpose without obtaining a separate commercial license from us. If you wish to use the Materials commercially, you shall request a license from us at [email protected].++++3. Redistribution++Subject to Section 2 (Grant of Rights), you may distribute copies or make the Materials, or derivative works thereof, available as part of a product or service that contains any of them, with or without modifications, and in Source or Object form, provided that you meet the following conditions:++ a. You shall give any other recipients of the Materials or derivative works a copy of this Agreement;++ b. You shall cause any modified files to carry prominent notices stating that you changed the files;++ c. You shall retain in all copies of the Materials that you distribute the following attribution notices within a "Notice" text file distributed as a part of such copies: "Qwen is licensed under the Qwen RESEARCH LICENSE AGREEMENT, Copyright (c) 2026 Hangzhou Tongyi Laboratory Technology Co., Ltd. All Rights Reserved."; and++ d. 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 terms and conditions of this Agreement.++++4. Rules of use++ a. The Materials may be subject to export controls or restrictions in China, the United States or other countries or regions. You shall comply with applicable laws and regulations in your use of the Materials.++ b. If you use the Materials or any outputs or results therefrom to create, train, fine-tune, or improve an AI model that is distributed or made available, you shall prominently display “Built with Qwen” or “Improved using Qwen” in the related product documentation.++ c. You shall not use "Qwen" as the primary name or identifier of any derivative works or products; reasonable descriptive use (e.g., "fine-tuned from Qwen Image") is permitted.++++5. Intellectual Property++ a. We retain ownership of all intellectual property rights in and to the Materials and derivatives made by or for us. Conditioned upon compliance with the terms and conditions of this Agreement, with respect to any derivative works and modifications of the Materials that are made by you, you are and will be the owner of such derivative works and modifications.++ b. No trademark license is granted to use the trade names, trademarks, service marks, or product names of us, except as required to fulfill notice requirements under this Agreement or as required for reasonable and customary use in describing and redistributing the Materials.++ c. If you commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against us or any entity alleging that the Materials or any output therefrom, or any part of the foregoing, infringe any intellectual property or other right owned or licensable by you, then all licenses granted to you under this Agreement shall terminate as of the date such lawsuit or other proceeding is commenced or brought.++++6. Disclaimer of Warranty and Limitation of Liability++ a. We are not obligated to support, update, provide training for, or develop any further version of the Qwen Materials or to grant any license thereto.++ b. THE MATERIALS ARE PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. WE MAKE NO WARRANTY AND ASSUME NO RESPONSIBILITY FOR THE SAFETY OR STABILITY OF THE MATERIALS AND ANY OUTPUT THEREFROM.++ c. IN NO EVENT SHALL WE BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE MATERIALS OR ANY OUTPUT OF IT, NO MATTER HOW IT’S CAUSED.++ d. You will defend, indemnify and hold harmless us from and against any claim by any third party arising out of or related to your use or distribution of the Materials.++++7. Survival and Termination.++ a. The term of this Agreement shall commence upon your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.++ b. We may terminate this Agreement if you breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, you must delete and cease use of the Materials. Sections 6 and 8 shall survive the termination of this Agreement.++++8. Governing Law and Jurisdiction.++ a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.++ b. The People's Courts in Hangzhou City shall have exclusive jurisdiction over any dispute arising out of this Agreement.++++9. Other Terms and Conditions.++ a. Any arrangements, understandings, or agreements regarding the Material not stated herein are separate from and independent of the terms and conditions of this Agreement. You shall request a separate license from us, if you use the Materials in ways not expressly agreed to in this Agreement.++ b. We shall not be bound by any additional or different terms or conditions communicated by you unless expressly agreed.++```diff --cc assets/README.mdindex 4ae45b9,0000000..958abbbmode 100644,000000..100644--- a/assets/README.md+++ b/assets/README.md@@@ -1,21 -1,0 +1,36 @@@+# Example inputs+- Use these images with the [image-to-3D example](../README.md#image-to-3d).- `infer.py` defaults to `pitcher_plant.png` when `--input` is omitted.++Use these images with the [image-to-3D example](../README.md#quick-start).++`infer.py` and `scripts/run_example.py` default to `spiny_whelk_shell.png` when++`--input` is omitted.+To select another example, pass `--input assets/<filename>` from the repository root.++RGBA inputs include foreground masks and can use `--use-input-alpha` without RMBG-2.- For the RGB candle jar, omit `--use-input-alpha` and provide++For the RGB candle jar and cinema signage, omit `--use-input-alpha` and provide+`--rmbg-model /path/to/RMBG-2.0`.++| Example | File | Format |+| --- | --- | --- |- | [Pitcher plant (default)](pitcher_plant.png) | `pitcher_plant.png` | RGBA |- | [Spiny whelk shell](spiny_whelk_shell.png) | `spiny_whelk_shell.png` | RGBA |++| [Spiny whelk shell (default)](spiny_whelk_shell.png) | `spiny_whelk_shell.png` | RGBA |++| [Pitcher plant](pitcher_plant.png) | `pitcher_plant.png` | RGBA |+| [Banyan bonsai](banyan_bonsai.png) | `banyan_bonsai.png` | RGBA |+| [Potted moth orchid](potted_moth_orchid.png) | `potted_moth_orchid.png` | RGBA |- | [Motocross helmet](motocross_helmet.png) | `motocross_helmet.png` | RGBA |- | [Compact excavator](compact_excavator.png) | `compact_excavator.png` | RGBA |- | [Industrial disconnect switch](industrial_disconnect_switch.png) | `industrial_disconnect_switch.png` | RGBA |++| [Industrial disconnect switch (`--refine` example)](industrial_disconnect_switch.png) | `industrial_disconnect_switch.png` | RGBA |+| [Metalwork scented candle jar](metalwork_candle_jar.png) | `metalwork_candle_jar.png` | RGB |+| [Ceramic apothecary jar](ceramic_apothecary_jar.png) | `ceramic_apothecary_jar.png` | RGBA |++| [Cinema signage (dual-view example)](cinema_signage.png) | `cinema_signage.png` | RGB |++| [Bronze ding vessel](bronze_ding_vessel.png) | `bronze_ding_vessel.png` | RGBA |++| [Celadon brush washer](celadon_brush_washer.png) | `celadon_brush_washer.png` | RGBA |++| [Amber bird brooch](amber_bird_brooch.png) | `amber_bird_brooch.png` | RGBA |++| [Sheet music archive box](sheet_music_archive_box.png) | `sheet_music_archive_box.png` | RGBA |++| [Ginkgo lidded jar](ginkgo_lidded_jar.png) | `ginkgo_lidded_jar.png` | RGBA |++| [Hammered copper jar](hammered_copper_jar.png) | `hammered_copper_jar.png` | RGBA |++++## Texturing example++++[`examples/pitcher_plant/`](examples/pitcher_plant) is the default input of++`texturing.py`. It holds the project-page pitcher plant mesh in the canonical++frame (`geometry.npz`, 388,551 vertices and 494,890 faces), its MoGe-2 camera++(`camera.json`), the foreground condition (`condition_rgba.png`), and the++reference-view material maps (`albedo.png`, `mra.png`) predicted by the++released material adapter from `pitcher_plant.png`.diff --cc assets/amber_bird_brooch.pngindex 0000000,0000000..51fdc49new file mode 100644Binary files differdiff --cc assets/bronze_ding_vessel.pngindex 0000000,0000000..14f143anew file mode 100644Binary files differdiff --cc assets/celadon_brush_washer.pngindex 0000000,0000000..49fb556new file mode 100644Binary files differdiff --cc assets/cinema_signage.pngindex 0000000,0000000..cff067bnew file mode 100644Binary files differdiff --cc assets/examples/pitcher_plant/albedo.pngindex 0000000,0000000..499efc8new file mode 100644Binary files differdiff --cc assets/examples/pitcher_plant/camera.jsonindex 0000000,0000000..49573ebnew file mode 100644--- /dev/null+++ b/assets/examples/pitcher_plant/camera.json@@@ -1,0 -1,0 +1,5 @@@++{++ "camera_angle_x": 0.7837784322691138,++ "distance": 1.2098772525787354,++ "mesh_scale": 1.0++}diff --cc assets/examples/pitcher_plant/condition_rgba.pngindex 0000000,0000000..208f5eenew file mode 100644Binary files differdiff --cc assets/examples/pitcher_plant/geometry.npzindex 0000000,0000000..f3f7a06new file mode 100644Binary files differdiff --cc assets/examples/pitcher_plant/mra.pngindex 0000000,0000000..624b176new file mode 100644Binary files differdiff --cc assets/ginkgo_lidded_jar.pngindex 0000000,0000000..bc1bc5anew file mode 100644Binary files differdiff --cc assets/hammered_copper_jar.pngindex 0000000,0000000..c21566dnew file mode 100644Binary files differdiff --cc assets/sheet_music_archive_box.pngindex 0000000,0000000..b780309new file mode 100644Binary files differdiff --cc deployment/runtime/geometry/pixal3d/pipelines/rembg/RMBG2.pyindex 1a80922,0000000..d72779fmode 100644,000000..100644--- a/deployment/runtime/geometry/pixal3d/pipelines/rembg/RMBG2.py+++ b/deployment/runtime/geometry/pixal3d/pipelines/rembg/RMBG2.py@@@ -1,64 -1,0 +1,59 @@@+from typing import Optional+import os- from pathlib import Path++from transformers import AutoModelForImageSegmentation+import torch+from torchvision import transforms+from PIL import Image++- _CY_ROOT = os.environ.get("CY_ROOT", str(Path(__file__).parents[5]))- RMBG2_MODEL_PATH = os.environ.get(- "PIXAL3D_RMBG_MODEL_PATH",- os.path.join(_CY_ROOT, "model_ckpts", "RMBG-2.0"),- )- _REMOTE_MODEL_NAMES = {"ZhengPeng7/BiRefNet", "briaai/RMBG-2.0"}++# A local RMBG-2.0 or BiRefNet directory can replace the Hub model.++RMBG2_MODEL_PATH = os.environ.get("PIXAL3D_RMBG_MODEL_PATH", "briaai/RMBG-2.0")+++class RMBG2:+ def __init__(+ self,+ model_name: str = RMBG2_MODEL_PATH,+ alpha_threshold: Optional[float] = None,+ ):- if model_name in _REMOTE_MODEL_NAMES:++ if model_name == "briaai/RMBG-2.0":+ model_name = RMBG2_MODEL_PATH+ if alpha_threshold is not None and not 0.0 <= alpha_threshold <= 1.0:+ raise ValueError(f"alpha_threshold must be in [0, 1], got {alpha_threshold}")+ self.model_name = model_name+ self.alpha_threshold = alpha_threshold+ self.model = AutoModelForImageSegmentation.from_pretrained(+ model_name, trust_remote_code=True+ )+ self.model.eval()+ self.transform_image = transforms.Compose(+ [+ transforms.Resize((1024, 1024)),+ transforms.ToTensor(),+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),+ ]+ )++ def to(self, device: str):+ self.model.to(device)++ def cuda(self):+ self.model.cuda()++ def cpu(self):+ self.model.cpu()++ def __call__(self, image: Image.Image) -> Image.Image:+ image_size = image.size+ input_images = self.transform_image(image).unsqueeze(0).to("cuda")+ with torch.no_grad():+ preds = self.model(input_images)[-1].sigmoid().cpu()+ pred = preds[0].squeeze()+ pred_pil = transforms.ToPILImage()(pred)+ mask = pred_pil.resize(image_size)+ if self.alpha_threshold is not None:+ cutoff = int(round(self.alpha_threshold * 255))+ mask = mask.point([0 if value < cutoff else 255 for value in range(256)])+ image.putalpha(mask)+ return imagediff --cc deployment/runtime/qwen/THIRD_PARTY_NOTICES.mdindex 21879ed,0000000..9ae2bedmode 100644,000000..100644--- a/deployment/runtime/qwen/THIRD_PARTY_NOTICES.md+++ b/deployment/runtime/qwen/THIRD_PARTY_NOTICES.md@@@ -1,56 -1,0 +1,56 @@@+# Qwen runtime third-party notices++This directory contains the vendored Qwen material-model runtime, including+`diffsynth`. Its top-level [Apache License 2.0](LICENSE) is retained. Incorporated+third-party portions keep their own applicable licenses and copyright notices;+the top-level license does not convert them to Apache-2.0 or to the SUPRA-Tex+project's MIT license.++Paths in this notice are relative to `deployment/runtime/qwen/`. The repository- [third-party notices](../../../LICENSE) provide the wider source++[third-party notices](../../../THIRD_PARTY_NOTICES.md) provide the wider source+map. The [source provenance record](../SOURCE_PROVENANCE.json) identifies this+as a vendored runtime without an identified upstream Git revision.+The distribution includes the inference entry point and its shared local+training, validation, and encoding helpers.++## Identified MIT subcomponents++| Distributed source | Upstream source | Full license text |+| --- | --- | --- |- | [`diffsynth/models/ace_step_residual_fsq.py`](diffsynth/models/ace_step_residual_fsq.py) | [`lucidrains/vector-quantize-pytorch/residual_fsq.py`](https://github.com/lucidrains/vector-quantize-pytorch/blob/master/vector_quantize_pytorch/residual_fsq.py), as credited in the file header; Copyright (c) 2020 Phil Wang. | [vector-quantize-pytorch MIT license](../../../LICENSE). |- | The timestep embedding in [`diffsynth/models/step1x_connector.py`](diffsynth/models/step1x_connector.py) | [`openai/glide-text2im/glide_text2im/nn.py`](https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py), as credited in the implementation; Copyright (c) 2021 OpenAI. | [OpenAI GLIDE MIT license](../../../LICENSE). |++| [`diffsynth/models/ace_step_residual_fsq.py`](diffsynth/models/ace_step_residual_fsq.py) | [`lucidrains/vector-quantize-pytorch/residual_fsq.py`](https://github.com/lucidrains/vector-quantize-pytorch/blob/master/vector_quantize_pytorch/residual_fsq.py), as credited in the file header; Copyright (c) 2020 Phil Wang. | [vector-quantize-pytorch MIT license](../../../THIRD_PARTY_NOTICES.md#vector-quantize-pytorch-mit). |++| The timestep embedding in [`diffsynth/models/step1x_connector.py`](diffsynth/models/step1x_connector.py) | [`openai/glide-text2im/glide_text2im/nn.py`](https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py), as credited in the implementation; Copyright (c) 2021 OpenAI. | [OpenAI GLIDE MIT license](../../../THIRD_PARTY_NOTICES.md#openai-glide-mit). |++The MIT texts above were obtained from the respective official upstream+[vector-quantize-pytorch license](https://raw.githubusercontent.com/lucidrains/vector-quantize-pytorch/master/LICENSE)+and [GLIDE license](https://raw.githubusercontent.com/openai/glide-text2im/main/LICENSE)+on 2026-10-14. These URLs do not establish an exact revision for this runtime+snapshot. Apache-2.0 source headers elsewhere in this directory remain in place+and refer to the bundled [Apache-2.0 text](LICENSE).++## Excluded YuE2 audio functionality++This source release excludes the YuE2 audio VAE formerly at+`diffsynth/models/yue2_vae.py`, its model-registry entry, and the dependent+music-generation pipeline formerly at `diffsynth/pipelines/yue2.py`. Their+source-permission records for the VAE's incorporated stable-audio-tools and+NVIDIA portions were incomplete. The excluded code is not distributed here,+and no replacement license or permission is inferred from the runtime's+top-level Apache-2.0 license.++Supra-Tex's Qwen-Image-2.1 material inference uses the separate+[image VAE](diffsynth/models/qwen_image_21_vae.py) and+[image pipeline](diffsynth/pipelines/qwen_image_21.py), which remain included+with their model-registry entries. Other registry entries are unchanged;+the retained YuE2 model/tokenizer helpers do not provide the removed audio+pipeline.++This notice records identified sources; it is not a completed audit of every+source reference in this vendored snapshot. Other per-file source and copyright+attributions remain applicable.++## Model weights and adapters++This is a source-code notice. It does not license Qwen base model weights,+trained adapters, or other model artifacts. Each separately distributed weight+artifact must carry its applicable license and model card; the source runtime's+Apache-2.0 license and the project's MIT license do not determine those terms.diff --cc docs/dual_view.mdindex 5d895bc,0000000..81636b5mode 100644,000000..100644--- a/docs/dual_view.md+++ b/docs/dual_view.md@@@ -1,170 -1,0 +1,187 @@@+# Optional dual-view inference++Dual-view inference adds a generated back observation to the single-view+pipeline. Both views use the same geometry, material backend, model artifacts,+and material seed 42. Front observations take priority where they overlap.+++> **Note:** Automatic back-view generation runs GPT-6 Astra with its built-in++> image generation tool through the external Codex CLI (see++> [Requirements](#requirements)), which this repository does not provide. As++> foundation image models improve, dual-view results can improve with them.++> Without that access, use single-view inference; for small visible text, add++> `--refine` (see [texturing](texturing.md#texture-refinement)), which needs no++> external service.+++## Requirements++Use the existing [CUDA environment](installation.md) and prepared models.+Automatic back-image generation additionally invokes the `codex` executable+with the model and image tool configured in the+[generation harness](../supratex/backview/harness/README.md): the current code+requires `gpt-6-astra`, `ultra` reasoning, and built-in `image_gen.imagegen` access.+These capabilities are separate from the Python dependencies and are required+by the implementation; they are not supplied by this repository.++`--local-files-only` controls model loading and does not make image generation+offline. Reusing a prepared back package avoids a new generation request.+- This path accepts a 4096-pixel PNG atlas, a 500000-face decimation target,- and no `--gutter`. It requires a new output GLB and a fresh work directory.++Dual-view always refines both views: it projects each observed albedo into the++atlas and repairs the UV gutters from the observations, as++[`--refine`](texturing.md#texture-refinement) does for one view. It therefore++needs the 4096 PNG atlas; any face target works, and `--gutter` uses the++observation-guided gutter. If refinement fails, it is skipped with a warning and++the completed front/back result is written unrefined (`refine: skipped` in++`receipt.json`). It requires a new output GLB and a fresh work directory.++## Run automatically+- With the generation environment available:++With the generation environment available, `--dual-view` without `--input` uses++the cinema signage building from the project page (`assets/cinema_signage.png`):++```bash- python infer.py --pipeline supra3d/supra-tex \- --input assets/pitcher_plant.png \- --output outputs/object_dual_view.glb \- --work-dir outputs/object_dual_view_work \- --dual-view++python infer.py --pipeline supra3d/supra-tex --dual-view \++ --output outputs/cinema_signage_dual_view.glb \++ --work-dir outputs/cinema_signage_dual_view_work+```+++The image is opaque RGB, so `--pipeline` also prepares RMBG-2 for foreground++extraction (see [model preparation](quickstart.md#2-prepare-the-models)).+++The command prepares the front geometry and material maps, renders a back normal+pack, generates the back image, predicts matching material maps, and runs+completion followed by front/back texture reprojection. It records the front+material metadata automatically.++`--back-view-dir /path/to/prepared-back` reuses an existing prepared package.+Its geometry, camera, condition images, and metadata must match this run's front+inputs. To reuse retained front inputs as well, use the staged workflow below.++## Run the stages separately++### 1. Prepare front inputs++Generate geometry and reference material maps with provenance recording enabled:++```bash+TORCH_HOME="$PWD/ckpts/ready/torch" python -m supratex.frontend.pipeline \- --input assets/pitcher_plant.png --output work/front --use-input-alpha \++ --input assets/cinema_signage.png --output work/front \++ --rmbg-model ckpts/ready/external/rmbg2 \+ --moge-model ckpts/ready/external/moge2 \+ --geometry-package deployment/runtime/geometry \+ --geometry-model ckpts/ready/geometry \+ --material-base ckpts/ready/external/qwen-base \+ --material-model ckpts/ready/project/material \+ --record-material-provenance+```++The example uses the default [prepared installation](quickstart.md). If you+selected local overrides or another output directory, use the model paths and+NAF cache recorded in its `models.json`.- For an opaque RGB image, replace `--use-input-alpha` with- `--rmbg-model /path/to/RMBG-2.0`. The front directory must contain:++Prepare RMBG-2 with `--with-rmbg` (or BiRefNet with `--rmbg`) first. For an++RGBA input with foreground alpha, replace `--rmbg-model` with++`--use-input-alpha`. The front directory must contain:++```text+front/+ geometry.pt+ camera.json+ geometry_receipt.json+ condition_rgba.png+ condition_rgb.png+ albedo.png+ mra.png+ material_receipt.json+```++Keep the model files unchanged between front and back prediction. The receipts+bind the images, geometry, camera, backend, and model selection. The geometry+receipt must come from the current frontend. If using the optional FireRed+backend, custom `--firered-manifest` inputs are not accepted when recording+material provenance.++### 2. Render the back normal pack++```bash+python -m supratex.backview render \+ --input-dir work/front --output-dir work/back_pack+python -m supratex.backview validate \+ --pack-dir work/back_pack --input-dir work/front+```++The pack contains the front reference, `back_normal.png`, `back_mask.png`,+`cameras.json`, and an HTML preview. The renderer chooses a back camera around+the opposite view while matching foreground occupancy. Normal and mask images+share the same camera and rasterization. The accepted camera protocol is+`supratex.back_view_camera.v4`; regenerate older packs from the original inputs.++### 3. Generate and review the back image++First prepare the input snapshot and inspect the plan:++```bash+python -m supratex.backview generate \+ --pack-dir work/back_pack --run-root work/back_generation+```++Without `--execute`, this command makes no generation request. To execute:++```bash+python -m supratex.backview generate \+ --pack-dir work/back_pack --run-root work/back_generation \- --execute --workers 1++ --execute+python -m supratex.backview.harness audit --run-root work/back_generation+python -m supratex.backview.harness report --run-root work/back_generation+```++Inspect `work/back_generation/report/index.html`. A result needs successful+worker execution and an accepted visual review for the selected image. An+image file alone is insufficient. The default case ID is `input`; if using+`--case`, keep it consistent across generation and material preparation.++### 4. Prepare back material maps++```bash+python -m supratex.backview materials \+ --front-input-dir work/front --pack-dir work/back_pack \+ --run-root work/back_generation --output-dir work/back_input+python -m supratex.backview validate \+ --back-view-dir work/back_input --input-dir work/front+```++This stage selects the material backend and model artifacts recorded for the+front. It preserves the generated image, applies the rendered silhouette,+and writes matching condition images, material maps, and validation metadata.++### 5. Complete and validate the mesh++```bash+python texturing.py --pipeline supra3d/supra-tex \+ --input-dir work/front --back-view-dir work/back_input --dual-view \+ --output outputs/object_dual_view.glb --work-dir work/dual_view+python -m supratex.backview validate --work-dir work/dual_view+```++Front observations win overlap. Back-only observations extend the visible+material set, and completion runs once. Texture reprojection then processes+the front and back views while preserving front-protected texels.+`receipt.json` records the final result and its validation status. Failed+checks leave intermediate files and stop final output publication.++## Resume an interrupted run++For interrupted generation, reuse its run directory:++```bash+python -m supratex.backview.harness run \- --run-root work/back_generation --execute --workers 1++ --run-root work/back_generation --execute+```++Add `--retry-review` to request a new attempt after a rejected visual review.+Otherwise recovery can finish a missing review without requesting a new image.+After generation succeeds, run material preparation into a new output directory+and texturing into a fresh work directory. Full `infer.py` does not resume a+nonempty work directory.++Changing the geometry, camera, condition images, or selected model artifacts+requires matching back-view inputs. Do not reuse a package from another case.+The validation commands check that these inputs match.diff --cc docs/end_to_end.mdindex 03b2fec,0000000..5015768mode 100644,000000..100644--- a/docs/end_to_end.md+++ b/docs/end_to_end.md@@@ -1,156 -1,0 +1,167 @@@+# Image to textured mesh++`infer.py` takes one RGB/RGBA image and runs foreground extraction, camera+estimation, geometry generation, reference-view material prediction, 3D material+completion, and GLB export. Install the runtime with the+[setup guide](quickstart.md) before running these commands from the repository root.++## Run from a model release++```bash- python infer.py --pipeline supra3d/supra-tex \- --input assets/pitcher_plant.png \- --output outputs/pitcher_plant.glb++python infer.py --pipeline supra3d/supra-tex --output outputs/spiny_whelk_shell.glb+```++`--pipeline` accepts a model repository ID/URL, a local model repository directory,+or a local `pipeline.json`. It selects the Qwen-Image material backend, prepares+all required models under `ckpts/ready/`, and uses the manifest's inference+defaults. Use `--pipeline-revision` to select a Hub snapshot and `--models-dir`+to select another prepared-model directory.+++Without `--input`, `infer.py` uses the bundled `assets/spiny_whelk_shell.png`++(`assets/cinema_signage.png` with `--dual-view`); pass `--input path/to/image.png`++for your own image.+The bundled example has foreground alpha, which is reused automatically. For+an opaque RGB image, the pipeline also prepares RMBG-2. DINOv3 and RMBG-2 require+upstream access approval; see [model preparation](quickstart.md#2-prepare-the-models).+`--use-input-alpha` explicitly requires a non-opaque RGBA input.++Use a new `.glb` output path. The default work directory is+`<output stem>_work` beside it; `--work-dir` selects another empty or absent+directory. Existing outputs are never overwritten.++## Run with models prepared in advance++After the [preparation step](quickstart.md#2-prepare-the-models):++```bash- python scripts/check_runtime.py --config ckpts/ready/models.json- python scripts/run_example.py \- --config ckpts/ready/models.json \- --input assets/pitcher_plant.png \- --output outputs/pitcher_plant.glb++python scripts/check_runtime.py++python scripts/run_example.py --output outputs/spiny_whelk_shell.glb+```++The runner supplies local model/runtime paths, configures the NAF cache, and+runs with Hub access disabled. Add `--print-command` to inspect its invocation+without starting inference. For an opaque RGB input, prepare RMBG with+`--with-rmbg` first.++The runner accepts inference controls such as `--seed`, `--texture-size`,+`--attention`, `--low-vram`, and `--work-dir`. Model paths, revisions, the+material backend, and offline settings come from `--config` and cannot be+overridden through this launcher. Use `infer.py` directly for those changes.++## Inference controls++- `--seed` defaults to 42 for geometry and completion. Material prediction uses+ its fixed seed 42.+- `--attention auto` selects a compatible installed attention backend.+ `--attention sdpa` avoids the FlashAttention dependency.+- `--low-vram` enables CPU offload; `--no-low-vram` disables it. Automatic+ selection enables offload on GPUs with at most 24 GiB. See+ [GPU compatibility](gpu_compatibility.md) for memory and validation limits.+- Export defaults are `--texture-size 4096`, `--decimation-target 500000`, and+ `--texture-format png`; `webp` is also supported. Explicit values override+ manifest defaults.+- `--gutter` adds one texel of base-color padding outside UV charts. It is+ disabled by default and preserves covered texels, alpha, metallic/roughness,+ geometry, and UVs.++- Floater removal is on by default: before completion, disconnected geometry++ pieces that project mostly outside the image foreground are dropped, and a++ `Floaters:` line reports the count. `--no-remove-floaters` keeps them.++ Pieces hidden behind the object and extra geometry attached to it are kept;++ see [texturing](texturing.md#floating-geometry). The saved `geometry.pt` stays++ unchanged, and the dual-view back view is rendered from it.++- `--refine` further refines the visible texture after export and aligns it++ with the input image, keeping very small text and intricate detail sharp. It is++ off by default because it adds about two minutes on an RTX 3090. It needs the++ default 4096 PNG atlas, works with any face target and with `--gutter` (which++ then uses the observation-guided gutter). `--dual-view` always refines both++ views, so it implies `--refine`. If refinement fails, it is skipped with a++ warning and the unrefined result is written. Its receipts are under++ `<work-dir>/refine`.++ See [texturing](texturing.md#texture-refinement).++The Qwen material predictor uses 1024-square inputs, Torch attention, and a+single endpoint prediction. It produces albedo and metallic/roughness maps;+coverage in the MRA handoff comes from input alpha. Geometry keeps Pixal3D's+fixed mesh scale (`--geometry-initial-mesh-scale 1.0`) by default;+`--geometry-scale-search` enables bounded scale calibration. See+[geometry](geometry.md) for the calibration procedure and+[frontend](frontend.md) for material formats. `--parallel-frontend` runs the+geometry and Qwen material stages concurrently on the first two visible GPUs.++## Explicit model paths++To use the default prepared layout without `--pipeline` or the launcher:++```bash+TORCH_HOME="$PWD/ckpts/ready/torch" python infer.py \- --input assets/pitcher_plant.png --use-input-alpha \- --output outputs/object.glb \++ --output outputs/spiny_whelk_shell.glb \+ --moge-model ckpts/ready/external/moge2 \+ --geometry-package deployment/runtime/geometry \+ --geometry-model ckpts/ready/geometry \+ --material-base ckpts/ready/external/qwen-base \+ --material-model ckpts/ready/project/material \+ --pretrained ckpts/ready/project/completion \+ --trellis-root ckpts/ready/external/vae+```++Without `--pipeline`, `--moge-model`, `--geometry-package`, and+`--geometry-model` are required. The geometry directory must have its prepared+`pipeline.json`, model files, and local DINOv3 directory. Configure its local+NAF cache as shown above. If preparation used local overrides or another output+directory, use the corresponding paths in `models.json`.- For opaque RGB input, replace `--use-input-alpha` with- `--rmbg-model /path/to/RMBG-2.0`.++For opaque RGB input, add `--input` and `--rmbg-model /path/to/RMBG-2.0`.++Completion and material bundles can be local directories or Hub repository+IDs. `--revision`, `--geometry-revision`, and `--material-revision` select their+respective snapshots. `--cache-dir` selects a shared Hub cache and+`--local-files-only` requires local or cached weights.+With `--pipeline`, external-model overrides must be existing local paths;+completion and material overrides may also use Hub IDs.++To select individual completion artifacts, replace `--pretrained` with+`--model-config` and `--checkpoint`, keeping `--trellis-root`. See+[weights](weights.md) for the supported safetensors and legacy layouts.+The bundled Qwen runtime is selected automatically; `--qwen-runtime` and+`--qwen-deps` allow an alternate compatible runtime and dependency overlay.++FireRed is an optional backend for the explicit-path invocation. Set+`--material-backend firered` and provide its corresponding `--material-base`+and `--material-model`. The default release manifest and prepared-model runner+use Qwen-Image. FireRed does not support the CPU-offload path; use+`--no-low-vram` on devices where offload would otherwise be selected.+See [frontend](frontend.md) for FireRed's checkpoint format and explicit+weight/contract arguments.++## Outputs++```text+outputs/+ object.glb+ object_work/+ run.json+ input/+ condition_rgb.png+ condition_rgba.png+ geometry.pt+ camera.json+ albedo.png+ mra.png+ geometry/+ material/+```++`run.json` records progress, selected paths, and failures. A completed run has+`status: complete` and `stage: complete`; inspect the GLB separately for visual+quality. Final decoding/export can change mesh topology and UV layout.++A failed run keeps intermediate files for inspection. Preflight errors can+occur before `run.json` is created. Full inference does not resume a nonempty+work directory: choose a fresh directory, or reuse valid intermediate inputs+with the [frontend](frontend.md) and [texturing](texturing.md) entrypoints.++## Optional dual-view inference++`--dual-view` adds a generated back observation and requires a separate image+generation environment. It is disabled by default. See+[dual-view inference](dual_view.md) for prerequisites, staged commands, and+recovery.diff --cc docs/frontend.mdindex 4d7beb6,0000000..a73a4e0mode 100644,000000..100644--- a/docs/frontend.md+++ b/docs/frontend.md@@@ -1,167 -1,0 +1,166 @@@+# Image-to-Material Translation frontend+- Supra-Tex begins with foreground isolation, canonical-camera estimation, and- material prediction. The default `qwen-image` backend uses the Supra-Tex++SUPRA-Tex begins with foreground isolation, canonical-camera estimation, and++material prediction. The default `qwen-image` backend uses the SUPRA-Tex+Material Adapter based on Qwen-Image-2.1; `firered` selects the bundled factorized+modality-axis joint-attention model. Both produce the aligned albedo and MRA+maps used by surface-observation encoding.++Follow the fresh-checkout environment commands and CUDA extension instructions+in [Installation](installation.md). They install the pinned Python dependencies+and bundled MoGe-2/utils3d packages; the `frontend` extra alone is insufficient+for the native Qwen runtime.+The Qwen backend uses its native DiffSynth runtime and torch attention. The+FireRed backend selects FA3 for its material Transformer on compatible Hopper+setups and native Torch attention otherwise; its text encoder selects FA2 or+SDPA. The default Qwen backend supports `--low-vram` CPU offload. See+[GPU compatibility](gpu_compatibility.md) for device settings and validation+status, and [Weights](weights.md) for model artifacts.++After the [model preparation step](quickstart.md), run the frontend using the+prepared local paths. For an RGB input, prepare RMBG-2 as well:++```bash- python scripts/prepare_models.py --repo supra3d/supra-tex --with-rmbg++python scripts/prepare_models.py --with-rmbg+python -m supratex.frontend.pipeline --input input.png --output work \+ --rmbg-model ckpts/ready/external/rmbg2 \+ --moge-model ckpts/ready/external/moge2 \- --material-backend qwen-image \+ --material-base ckpts/ready/external/qwen-base \+ --material-model ckpts/ready/project/material+```++These paths assume the default preparation directory and no local model+overrides. The standalone frontend does not read `models.json`; when using a+different preparation directory or local overrides, supply the corresponding+paths recorded there. Without explicit material paths, this CLI falls back to+`ckpts/qwen-base` and `ckpts/qwen-material` under the source root.+The bundled Qwen runtime is selected automatically and uses packages installed in the active+Python environment. `--qwen-runtime` can select another compatible local runtime;+`--qwen-deps` optionally adds an existing dependency overlay. Base and model sources+also accept Hugging Face `namespace/repo` IDs; `--cache-dir` and+`--local-files-only` apply to resolution, and `--revision` selects the material+checkpoint revision. Runtime and dependency paths must be local directories.+For the same options on `infer.py`, use `--material-revision` instead of+`--revision` (which selects the completion model there).+Use a fresh output directory. The handoff contains `condition_rgba.png`,+`condition_rgb.png`, `camera.json`, `albedo.png`, and `mra.png`.++For an existing non-opaque foreground RGBA, omit `--with-rmbg` during preparation+and replace `--rmbg-model` with `--use-input-alpha` in the frontend command.+Foreground preprocessing writes a straight-color+`condition_rgba.png` and a matching black-premultiplied `condition_rgb.png`+after reducing the longest input dimension to at most 1024 pixels and applying+a square foreground crop with 10% padding. Qwen receives the straight+RGBA frame, resized once to its 1024-square model canvas; FireRed receives+the RGB condition. Do not premultiply Qwen's RGB channels before attaching alpha.++Foreground extraction uses input alpha or RMBG-2. Depth-based rejection occurs+later during 3D observation construction: alpha erosion and first-hit depth+discontinuity filtering discard unreliable observation pixels. It does not+erode the saved foreground image using MoGe depth. See [Texturing](texturing.md).++Supply geometry separately in the canonical frame, or set+`TORCH_HOME="$PWD/ckpts/ready/torch"` and add+`--geometry-package deployment/runtime/geometry --geometry-model ckpts/ready/geometry`+to generate the final mesh with Pixal3D's fixed mesh scale (add+`--geometry-scale-search` for bounded scale calibration). This uses the NAF+cache created by model preparation. See the+[geometry frontend](geometry.md) for source requirements and the matching+mesh/camera handoff.++## Qwen-Image material backend++With the default preparation layout, the model and runtime paths are:++```text+ckpts/ready/+ external/qwen-base/ # complete Qwen-Image-2.1 base+ project/material/+ adapter_model.safetensors+ adapter_config.json+deployment/runtime/+ qwen/ # bundled DiffSynth runtime+```++Keep the bundled runtime tree, including `diffsynth/` and+`examples/qwen_image_21/pbr/{infer,inference_utils,inference_offload}.py`.+The adapter requires its native JSON config and complete base model, including+processor, VAE, text encoder, and Transformer. The safe file includes learned- modality embeddings as well as LoRA and uses the Supra-Tex native loader.++modality embeddings as well as LoRA and uses the SUPRA-Tex native loader.+Legacy `checkpoint-0100000.pt` plus its matching `.complete.json` also remain+supported. Neither adapter format replaces the external base model.++Inference fixes the native prompts, 1024 resolution, seed 42, sigma 1,+one endpoint-prediction step, and torch attention. The outputs are albedo and+metallic/roughness only; there is no normal or AO prediction. Native RGBA+outputs remain under `material/native/`. Canonical `albedo.png` and `mra.png`+are RGB: MRA red is metallic, green is roughness, and blue is the input+coverage. Native MR blue is a constant 255 placeholder, which the adapter+replaces with input coverage for completion. This coverage is not a prediction+of material transparency. Metallic and roughness use linear 0–255 encoding;+albedo is sRGB.++## FireRed material backend++Select FireRed explicitly with its own base and material bundle:++```bash+python -m supratex.frontend.pipeline --input input.png --output work \+ --rmbg-model /models/rmbg2 --moge-model /models/moge2 \+ --material-backend firered --material-base /models/firered-base \+ --material-model /models/firered-material+```++The legacy `--firered-base` option also supplies the FireRed base path.+For this backend only, replace `--material-model` with all three explicit+artifact arguments:++```bash+--material-weights full_transformer.safetensors \+--material-spec joint_contract.json \+--material-checkpoint-manifest checkpoint_complete.json+```++Individual foreground, camera, and FireRed stages remain available:++```bash+python -m supratex.frontend.preprocess --input input.png --rmbg-model /models/rmbg2 \- --output-dir work --device cuda++ --output-dir work+python -m supratex.frontend.camera --image work/condition_rgb.png --model /models/moge2 \- --output work/camera.json --device cuda++ --output work/camera.json+python -m supratex.frontend.firered --base-model /models/firered-base \+ --condition work/condition_rgb.png --weights full_transformer.safetensors \+ --spec joint_contract.json --checkpoint-manifest checkpoint_complete.json --output work/material+```++The FireRed adapter invokes the selected package's `infer.py`. The bundled+package accepts a JSONL record containing the condition image and instructions;+the adapter creates this record automatically. Additional fields retained for+checkpoint compatibility are not used as material targets during inference.+After decoding, the+adapter fixes the blue channel of `<key>_mra.png` to 255 (normalized opacity 1)+everywhere, preserving metallic in red, roughness in green, and the albedo pixels.+The checkpoint's native material-alpha prompt is retained; its predicted blue+channel is replaced before the maps reach the 3D material encoder. Foreground+coverage continues to come from the separate condition mask.+The adapter copies its `<key>_albedo.png` and `<key>_mra.png` outputs to the canonical+`albedo.png` and `mra.png` primary material handoff names. Compatibility+copies named `firered_albedo.png` and `firered_mra.png` are also written.++The bundled FireRed package is source code only. It retains the factorized+`ModalityAxisJointAttention` modules and the exact `modality_joint_blocks.*`+parameter names used by the checkpoint. The base model, factorized transformer+weights, joint contract, and completion manifest must be supplied explicitly;+no model weight is included in this repository. The frontend requires a+checkpoint that produces 1024-by-1024 RGB maps. A compatible external package+may be selected with `--firered-package` in the complete frontend, or `--package`+in the standalone FireRed command; its own entrypoint contract then applies.++## Camera handoff++The camera receipt has `camera_angle_x`, `distance`, and `mesh_scale`. These+are the canonical fields consumed by the surface-observation path: camera at+`(0, 0, distance * mesh_scale)`, looking at the origin with +Y up. MoGe-2+intrinsics are normalized and its horizontal focal length determines both FOV+and canonical distance. The optional `image_width`, `image_height`, and model+receipt fields are provenance only.diff --cc docs/geometry.mdindex 141f826,0000000..d8b5b47mode 100644,000000..100644--- a/docs/geometry.md+++ b/docs/geometry.md@@@ -1,211 -1,0 +1,213 @@@+# Two-stage geometry frontend++The optional geometry frontend supports the public native Pixal3D pipeline+and the historical `paper` implementation. By default both keep Pixal3D's fixed+mesh scale; `--geometry-scale-search` adds bounded mesh-scale calibration with+the main geometry model. Only the final mesh and its matching canonical camera- are passed to Supra-Tex. Intermediate meshes are not saved by++are passed to SUPRA-Tex. Intermediate meshes are not saved by+this adapter.++## Requirements++The native geometry source is bundled at `deployment/runtime/geometry`.+The [source setup entrypoints](quickstart.md) install its dependencies and+prepare matching weights, DINO and the local NAF cache. No separate Pixal3D+source checkout is needed for the default path. Geometry requires CUDA and+runs in a separate process using the same interpreter. An external compatible+checkout can still be selected explicitly for the historical paper backend.++### Native Pixal3D++The adapter automatically selects the native backend when the source checkout+contains `pixal3d/pipelines/pixal3d_image_to_3d.py`. Its model root must contain+`pipeline.json`, the five geometry model stems referenced by+`args.models`, and a local DINOv3 model under `dino/`. A typical local layout is:++```text+ckpts/ready/geometry/+ pipeline.json+ ckpts/+ ss_flow_img_dit_1_3B_64_bf16.{json,safetensors}+ ss_dec_conv3d_16l8_fp16.{json,safetensors}+ slat_flow_img2shape_dit_1_3B_512_bf16.{json,safetensors}+ slat_flow_img2shape_dit_1_3B_1024_bf16.{json,safetensors}+ shape_dec_next_dc_f16c32_fp16.{json,safetensors}+ dino/+ config.json+ model.safetensors+```++The five model keys are `sparse_structure_flow_model`,+`sparse_structure_decoder`, `shape_slat_flow_model_512`,+`shape_slat_flow_model_1024`, and `shape_slat_decoder`. Their JSON and weight+files must remain inside the model root. DINO may instead use+`model.safetensors.index.json` with all its referenced local shards. The+repository ignores `ckpts/`, so these local checkpoint copies stay outside Git.+Only geometry networks are loaded. Model preparation assembles this directory+from the Pixal3D and DINOv3 downloads; the unmodified upstream Pixal3D snapshot+alone is not the complete model root expected here.+NAF requires the Torch Hub source at `${TORCH_HOME}/hub/valeoai_NAF_main` and+weights at `${TORCH_HOME}/hub/checkpoints/naf_release.pth`.+For the default prepared layout, set `TORCH_HOME="$PWD/ckpts/ready/torch"` when+running the standalone frontend or geometry CLI from the source root.+`infer.py --pipeline` and `scripts/run_example.py` set it from the prepared+configuration automatically.++The five native networks are constructed on `meta` and receive validated local+checkpoint tensors directly. Loading preserves the original constructor's+per-layer dtypes, including BF16 flow blocks and FP32 decoder boundary layers;+missing keys and incompatible shapes fail explicitly. This avoids initializing+a full set of parameters that would immediately be overwritten.++`scripts/convert_geometry_weights.py` can write `*.runtime.safetensors` copies++already cast to these dtypes beside the originals; when present they are loaded++instead, with identical results and about half the bytes read.++### Paper Pixal3D++For the historical backend, supply the [Pixal3D paper source](https://github.com/TencentARC/Pixal3D/tree/paper)+containing `pixal3dpipeline.py`, `pixal3dpipeline2stage.py`, and its `pixal3d/`+package, without the native source entry above. The adapter disables the+source's MoGe-v1 loader and reuses the prepared MoGe-2 camera. This backend+requires its own compatible model layout:++```text+geometry-weights/+ dense/+ dit/{config.json,model.safetensors}+ vae/{config.json,model.safetensors}+ conditioner/config.json+ scheduler/config.json+ sparse512/+ dit/{config.json,model.safetensors}+ vae/{config.json,model.safetensors}+ conditioner/config.json+ scheduler/config.json+ sparse1024/+ dit/{config.json,model.safetensors}+ vae/{config.json,model.safetensors}+ conditioner/config.json+ scheduler/config.json+```++All required configs and weights are checked before geometry launches. Paper scale+probes always use the main dense model (`use_dense_check=False`); optional+`dense/scale_init` files are neither required nor loaded. DINO/NAF dependencies+and their pretrained caches follow the external source's loading policy; they+are not included in the geometry checkpoint directory by this adapter.++## Complete image frontend++After [preparing the models](quickstart.md) with `--with-rmbg` for RGB inputs,+add the two geometry arguments to the [material frontend](frontend.md):++```bash+TORCH_HOME="$PWD/ckpts/ready/torch" python -m supratex.frontend.pipeline \+ --input inputs/reference.png --output inputs/object \+ --rmbg-model ckpts/ready/external/rmbg2 \+ --moge-model ckpts/ready/external/moge2 \+ --geometry-package deployment/runtime/geometry \+ --geometry-model ckpts/ready/geometry \- --material-backend qwen-image \+ --material-base ckpts/ready/external/qwen-base \+ --material-model ckpts/ready/project/material+```++The output includes `geometry.pt`, the final `camera.json`, condition RGB/RGBA,+albedo, and MRA, ready for `texturing.py`. For a foreground RGBA input, use+`--use-input-alpha` in place of `--rmbg-model`.++Geometry follows Pixal3D by default: the mesh scale stays at+`--geometry-initial-mesh-scale 1.0` and no scale probes run.+`--geometry-scale-search` enables the bounded calibration described below, with+`--geometry-target-padding 3` and `--geometry-max-iterations 2` by default.+Each probe adds one 64-cell sparse-structure sampling (about 10 s on an+RTX 3090; up to three probes). The model+source accepts a local directory or a `namespace/repo` containing the complete+model-root layout above; `--geometry-revision` selects its Hub revision.+`--cache-dir` and `--local-files-only` also apply to+geometry checkpoint resolution. Offline HF/Transformers flags are forwarded+to the geometry process; external torch-hub dependencies need their caches+prepared separately.++When scale search is enabled, the native adapter reuses sparse-structure image+features across scale probes and final sparse-structure conditioning within the+same inference. Shape stages+sample DINO/NAF features only at occupied coordinates, preserving the original+projection arithmetic and coordinate order. The receipt records these operations+under `conditioning_acceleration`.++## Geometry only++If the condition images and MoGe camera are already prepared, generate the+final mesh without loading the material model:++```bash+TORCH_HOME="$PWD/ckpts/ready/torch" python -m supratex.frontend.geometry \+ --package deployment/runtime/geometry --model ckpts/ready/geometry \+ --input-dir inputs/prepared --output-dir outputs/geometry+```++Use a fresh output directory. It receives `geometry.pt`, `camera.json`,+`geometry_receipt.json`, `geometry.log`, and copies of the condition images.+The original inputs are preserved. The receipt records the selected scale,+camera actually used for final generation, check-model usage, seed, and mesh+counts. Without `--geometry-scale-search`, its `scale_search` entry is+`{"enabled": false, "probes": [], "stop_reason": "disabled"}`. With it, the entry+records probes, scale bounds, selected padding, convergence, baseline fallback,+and the stopping reason; `dense_probe_calls` counts main-model probes and+`uses_dense_check_model` is false. The standalone geometry command accepts the+same option as `--scale-search`.+Native receipts identify `Pixal3D native geometry cascade` and record+`final_sparse_structure_resolution = 32` and final `resolution = 1024`.+In the complete frontend these diagnostics live under `geometry/`;+the final mesh and matching camera are copied to the main input directory.++## Scale and coordinate contract++With `--geometry-scale-search`, both backends use the paper scale-update formula+with the adapter's bounded selection policy. Without it, they generate directly at+the initial scale. The prepared MoGe-2 camera owns both FOV and distance.+By default, scale starts at 1.0 and the frontend computes+`distance = 0.5 / tan(FOV / 2)`.+The native backend uses this camera directly for 64-cell occupancy probes,+then generates a fresh 32-cell sparse structure and runs the 512/1024 shape+cascade. Its decoded mesh is already canonical and needs no rotation or scale+conversion.++The paper backend retains the original outer inference path. The source first+computes its own distance using initial scale and its image-padding convention;+before any probe, the hook replaces that shared distance tensor with the+prepared value. Its receipt retains both+`upstream_initial_generation_camera` and `initial_generation_camera` and records+the substitution. Both backends keep FOV and distance fixed throughout+calibration and final generation and record+`camera_distance_policy = preserve_prepared_demo_camera`.++Calibration aims for boundary padding in a 64-cubed occupancy grid. The default+initial scale is 1.0 and target padding is 3 cells; padding from 2 through 4 cells+is accepted. The baseline is probed first, followed by at most two scale updates+(three probes total). `--geometry-max-iterations` must be positive and can lower+the update budget; values above 2 still allow only two updates. Target padding+must be an integer from 1 through 30. Proposals are bounded to half through twice+the initial scale. Clipped candidates continue shrinking within those bounds.++Only nonempty, finite, integer occupancy coordinates inside the 64-cell grid+are valid. A candidate is safe when its padding reaches the lower acceptance+bound (2 cells by default). The search retains the safe candidate closest to+the target, even if it never reaches the acceptance range. A safe baseline is+retained unless a later safe candidate is closer; an unsafe baseline yields+to any safe candidate, even if that candidate has a larger target error. An+invalid later probe retains the best candidate already found. If no safe+candidate exists, calibration falls back to the baseline. This optimizes+occupancy padding, not FOV, pose, or image silhouette IoU.++The paper source exports its final mesh after rotating `(x,y,z)` to `(x,-z,y)` and+scaling by `0.5 / optimized_mesh_scale`. The adapter reverses the rotation+and multiplies by the selected scale, recovering the canonical mesh in+`[-0.5,0.5]`. The final camera retains the prepared generation distance and- selected `mesh_scale`; Supra-Tex projection and DDA both use effective distance++selected `mesh_scale`; SUPRA-Tex projection and DDA both use effective distance+`distance * mesh_scale`. This paired conversion preserves the source projection.+The original MoGe camera is retained under `moge_initial_camera` for provenance.+Falling back to scale 1.0 restores the prepared baseline camera parameters.+The paper and native models and image preprocessing differ, so identical+geometry across the two backends is not promised. A safer occupancy margin also+does not guarantee better shape, alignment, or texture quality.diff --cc docs/gpu_compatibility.mdindex 61d533f,0000000..e12c491mode 100644,000000..100644--- a/docs/gpu_compatibility.md+++ b/docs/gpu_compatibility.md@@@ -1,116 -1,0 +1,123 @@@+# GPU compatibility and low-VRAM inference++The inference entrypoints select an attention backend for the visible GPU.+The default Qwen image-to-textured-mesh pipeline also supports CPU offload.+Full-weight single-view inference has been validated with PyTorch SDPA on+H800 80 GB and RTX 3090 24 GB. The RTX 3090 run used CPU offload and the+default 4096-pixel texture atlas; see the measured configuration below.++## Device policy++| Device | Default attention, without environment overrides | Default CPU offload |+| --- | --- | --- |+| A100 40 / 80 GB | FA2 if available, otherwise PyTorch SDPA | Off |+| H100 / H800 80 GB | FA3 if available, then FA2, then SDPA | Off |+| RTX 3090 / 4090 24 GB | FA2 if available, otherwise SDPA | On |+| Other CUDA GPUs | Recognized supported FlashAttention backend, otherwise SDPA | On when total memory is at most 24 GiB |++FA3 requires Hopper hardware. The native CUDA extensions must also support+the selected GPU; attention selection alone does not establish support for+every device. Qwen material prediction keeps its native Torch attention.+The selected attention backend and offload policy are printed at startup;+the complete image-to-mesh run records them in `run.json`.++## Usage++Keep the model and input arguments from your existing command and add:++```bash+# Automatic device policy (the default).+--attention auto++# Explicit CPU offload, including on a larger GPU.+--low-vram++# No FlashAttention installation required; other CUDA extensions still apply.+--attention sdpa --low-vram++# Keep model weights resident when sufficient VRAM is available.+--no-low-vram+```++These options are accepted by `infer.py`, `texturing.py`, and the material+frontend CLI. `scripts/check_runtime.py` checks the installed runtime and model+files; it does not run full inference or measure whether the models fit in VRAM.++An explicit `--attention` value other than `auto` overrides both+`ATTN_BACKEND` and `SPARSE_ATTN_BACKEND`. With `auto`, `scripts/run_example.py`+and `infer.py --pipeline` clear these inherited values and select by hardware.+Direct `infer.py` without `--pipeline`, `texturing.py`, and the material+frontend respect them. For those direct commands, clear old FA3 overrides+before using an A100 or RTX GPU:++```bash+unset ATTN_BACKEND SPARSE_ATTN_BACKEND+```++`SUPRATEX_LOW_VRAM=1` or `0` overrides automatic memory selection; the explicit+`--low-vram` / `--no-low-vram` CLI options take precedence. Automatic selection+uses total device capacity, not currently free memory. It does not retry a+failed run or change quality settings after an out-of-memory error. Use one+request at a time when evaluating a device's capacity.++## What CPU offload changes++- **Geometry:** the native geometry pipeline already stages its models by+ inference phase.+- **Qwen materials:** base components load on CPU. VAE encoding, text encoding,+ DiT prediction, and VAE decoding run separately; language and DiT blocks+ move onto the GPU only for their forward pass, including attached adapters.+- **3D completion:** shape/material encoders run sequentially; the completion+ model releases GPU memory before decoding. Decoder layers are staged+ individually. Required sparse topology maps survive CPU handoffs, while+ recomputable caches and the optional observation cache are released.+- **Texture export:** attribute volumes upload when baking begins, and+ interpolation queries run in bounded chunks.++Weights, precision policy, input resolution, sampling parameters, and output+texture resolution are preserved. CPU offload does not quantize the model or+reduce the default 4096-pixel texture atlas. Different attention kernels can+introduce normal floating-point differences; identical output across GPU+families or backends is not promised.++System RAM must hold the offloaded models plus loading and inference workspaces.+Synchronous CPU-to-GPU transfers increase latency. Sparse activation size+depends on the input surface, and rendering/mesh processing also uses VRAM;+weight offload alone does not bound every stage's peak. The measurements below+describe the tested example, rather than a minimum system-RAM requirement.++The optional FireRed material backend has compatible attention selection, but+does not implement this CPU-offload path. Image-to-mesh inference rejects+FireRed with low-VRAM mode; use the default `qwen-image` backend for that mode.++## Validation status++The recorded full-pipeline validation on 2026-10-14 used H800 80 GB,- Python 3.10, PyTorch 2.6.0/cu124, SDPA, and CPU offload disabled. Both bundled- examples, `pitcher_plant.png` (RGBA) and `metalwork_candle_jar.png` (opaque RGB),++Python 3.10, PyTorch 2.6.0/cu124, SDPA, and CPU offload disabled. Two bundled++images, `pitcher_plant.png` (RGBA) and `metalwork_candle_jar.png` (opaque RGB),+completed image-to-GLB inference with 4096-square textures. The RGB example+used RMBG-2. This run used local copies of the release and upstream weights;+it did not test anonymous model downloads.++On 2026-10-16, one RTX 3090 24 GB completed the bundled RGBA example+`pitcher_plant.png` using Python 3.10, PyTorch 2.6.0/cu124, CUDA toolkit 12.4,+and `--attention sdpa --low-vram`. Full weights and the default 4096-square+textures were preserved. The first run, including kernel compilation, took+665 seconds. Sampling every five seconds recorded a peak device-memory use+of 12,593 MiB and a peak process-tree RSS sum of 32.4 GiB; shared pages can be+counted more than once in the RSS sum. The exported GLB passed mesh, UV, and+embedded-texture checks. This RTX 3090 run covered single-view RGBA input.+++On 2026-10-19, RTX 3090 GPUs with the same software and automatic CPU offload++ran the release defaults, including the `denoiser_step0030000.safetensors`++completion checkpoint: image-to-GLB inference on three project-page cases (a++metal candle tin, multimeter dial markings, and the disconnect-switch wiring++table), `--refine` on the wiring table, and `texturing.py` on the bundled++pitcher plant example. Dual-view inference was not part of these runs.+++When evaluating another device or input, check the complete pipeline and its+output, GPU memory, system RAM, and elapsed time. Qwen's `REPORT.json` records+only the material stage's peak allocated/reserved GPU memory.++See the [FlashAttention documentation](https://github.com/Dao-AILab/flash-attention)+for attention hardware and build requirements.diff --cc docs/installation.mdindex 3d328be,0000000..87b409amode 100644,000000..100644--- a/docs/installation.md+++ b/docs/installation.md@@@ -1,92 -1,0 +1,110 @@@+# Installation++For a new installation, use the [source setup guide](quickstart.md):++```bash+conda create -n supra-tex python=3.10 -y+conda activate supra-tex+python scripts/install_runtime.py --conda+```++The installer uses fixed public Python/CUDA dependencies and the bundled+project runtimes, then checks actual imports. `--dry-run` prints its plan.+It installs into the active Conda environment; model weights are prepared with+`scripts/prepare_models.py`. The commands below document manual installation.++The supported installation uses Linux x86_64, Python 3.10, PyTorch 2.6.0+cu124,+torchvision 0.21.0+cu124, and the CUDA 12.4 toolkit with `nvcc`. Run the following+commands from the repository root:++```bash+conda create -n supra-tex python=3.10 -y+conda activate supra-tex+python -m pip install pip==25.1.1 setuptools==80.9.0 wheel==0.45.1 packaging==25.0+python -m pip install torch==2.6.0+cu124 torchvision==0.21.0+cu124 --index-url https://download.pytorch.org/whl/cu124+python -m pip install -r deployment/runtime/requirements-python.txt+python -m pip install --no-build-isolation --no-deps -e .+python -m pip install --no-build-isolation --no-deps ./deployment/runtime/moge ./deployment/runtime/utils3d+python -m pip install --no-index --no-deps \+ 'https://github.com/SHI-Labs/NATTEN/releases/download/v0.17.5/natten-0.17.5%2Btorch260cu124-cp310-cp310-linux_x86_64.whl'+```++The [Python requirements](../deployment/runtime/requirements-python.txt) pin the+runtime packages, including Qwen's `peft` and `modelscope` imports. PyTorch and+compiled CUDA extensions are installed separately. The `frontend` extra alone+does not install all Qwen runtime dependencies. Use the bundled MoGe and utils3d+packages to preserve the APIs required by the frontend.++The native geometry/material encoder-decoder and GLB export use:++- [TRELLIS.2](https://github.com/microsoft/TRELLIS.2): pretrained shape and PBR+ VAE weights and the `o-voxel` extension from that repository.+- [FlexGEMM](https://github.com/JeffreyXiang/FlexGEMM): sparse convolution kernels.+- [CuMesh](https://github.com/JeffreyXiang/CuMesh): GPU mesh processing.+- [nvdiffrast](https://github.com/NVlabs/nvdiffrast): differentiable rasterization.+- [utils3d](https://github.com/EasternJournalist/utils3d): installed from the+ bundled `deployment/runtime/utils3d` source by the command above.++Build the CUDA extensions using the pinned commands in the+[dependency reference](../deployment/docs/DEPENDENCIES.md#runtime-installation-only-for-missing-software)+from the same environment and repository root. Then check the installation:++```bash+python -m pip check+python scripts/check_runtime.py --imports-only+```+- Inference defaults to `--attention auto`:- Hopper GPUs use FlashAttention-3 when its interface is importable; Ampere,- Ada, and Hopper can use FlashAttention-2; otherwise PyTorch SDPA is selected.- FA3 is Hopper-specific and is not required on A100 or RTX 3090/4090.- Install an optional [FlashAttention implementation](https://github.com/Dao-AILab/flash-attention)- that matches your GPU and CUDA/PyTorch build, or use `--attention sdpa`.++## FlashAttention (recommended for speed)++++The installer does not install FlashAttention by default, so inference falls back++to PyTorch SDPA. [FlashAttention](https://github.com/Dao-AILab/flash-attention)++is faster: FlashAttention-2 supports Ampere, Ada, and Hopper GPUs (A100,++RTX 30/40 series, H100/H800), and FlashAttention-3 is faster still on Hopper.++Install them into the same environment:++++```bash++# FlashAttention-2 (or rerun the installer with --flash-attn)++pip install flash-attn==2.8.3 --no-build-isolation++++# FlashAttention-3, Hopper only; builds from source++git clone https://github.com/Dao-AILab/flash-attention.git++cd flash-attention/hopper && python setup.py install++```++++Inference defaults to `--attention auto`, which picks the fastest installed++backend: FlashAttention-3 on Hopper, then FlashAttention-2, then SDPA. No flag is++needed after installation. Use `--attention sdpa` if an installed FlashAttention++build does not match your GPU or CUDA/PyTorch version.+Selected backends are printed at startup. Explicit backend requests are+validated and do not silently fall back.+The prepared-model runner and `infer.py --pipeline` clear inherited+`ATTN_BACKEND` and `SPARSE_ATTN_BACKEND` overrides when using `auto`. Direct+component commands respect them; see [GPU compatibility](gpu_compatibility.md)+for override precedence.++++## Runtime options+++GPUs with at most 24 GiB enable CPU offload automatically; `--low-vram` and+`--no-low-vram` override this policy. See [GPU compatibility](gpu_compatibility.md)+for the supported paths, memory tradeoffs, and hardware validation status.++The default Qwen-Image material backend uses torch attention and the+DiffSynth runtime bundled at `deployment/runtime/qwen`, selected automatically.+Its subprocess uses the active Python environment and the dependencies installed+above. Packages installed only with `pip --user` are excluded in the subprocess.++To use another compatible runtime, pass `--qwen-runtime /path/to/qwen-runtime`.+An optional `--qwen-deps /path/to/dependencies` adds an existing dependency+overlay; no overlay directory is needed for a standard installation. Preserve+the whole runtime, including its package and inference helpers. See+[Frontend](frontend.md) and [Weights](weights.md) for the base model and adapter+formats.++The selectable FireRed material backend uses the bundled model source. Its+material Transformer uses FA3 on supported Hopper setups and native Torch+attention otherwise; its Qwen text encoder selects FA2 when available or+SDPA. FireRed does not have the Qwen material backend's CPU-offload path.++After installation, [prepare the model weights](quickstart.md#2-prepare-the-models)+and run an example. The installer checks software dependencies without+downloading weights or running full inference.diff --cc docs/quickstart.mdindex b6153d6,0000000..efb1c5emode 100644,000000..100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@@ -1,146 -1,0 +1,165 @@@+# Quick start++This source directory contains the project runtime, including the native+geometry, Qwen PBR, MoGe, utils3d and NAF Python implementations. The steps below+install their dependencies, prepare model weights, and run an example.++## 1. Install the software++Use Linux x86_64, Conda, Git, a C++ compiler, an NVIDIA GPU/driver,+and a CUDA 12.4 toolkit with `nvcc`. From the source root:++```bash+conda create -n supra-tex python=3.10 -y+conda activate supra-tex+python scripts/install_runtime.py --conda --dry-run+python scripts/install_runtime.py --conda+```++The installer uses the active Conda environment. It installs+PyTorch 2.6.0/cu124, torchvision 0.21.0/cu124, the pinned Python requirements,+bundled MoGe/utils3d, NATTEN, and fixed public revisions of CuMesh, FlexGEMM,+nvdiffrast and TRELLIS.2's o-voxel extension. It then checks package dependencies,- CUDA access and actual runtime imports. SDPA requires neither FA2 nor FA3;- `--flash-attn` optionally builds FA2. Native compilation may take some time.++CUDA access and actual runtime imports. Native compilation may take some time.++FlashAttention is not installed by default and inference then uses SDPA;++FlashAttention-2/3 is faster and is selected automatically once installed (see++[FlashAttention](installation.md#flashattention-recommended-for-speed)).++Use a dedicated Conda environment rather than `base`. If you prefer `venv`,+run `python3.10 scripts/install_runtime.py --venv /path/to/new/environment`+instead, then activate it with `source /path/to/new/environment/bin/activate`.+The `--python /path/to/python3.10` option selects Python for venv creation only.+It stops on incompatible existing source checkouts instead of resetting them.+It can be rerun after a failed download/build using the same managed environment.+FlexGEMM is built from a temporary patched copy, so its install-time autotune+cache is written under the environment's `.cache/flex_gemm` instead of `~/.flex_gemm`.+See [installation details](installation.md) for manual setup.++## 2. Prepare the models++The [project model repository](https://huggingface.co/supra3d/supra-tex) contains+`pipeline.json`, the completion model, and the material adapter. See+[model weights](weights.md) for component layouts and external dependencies.++While we resolve model deployment issues, access to this repository is++temporarily gated: request access on its model page before preparation. The++models will be openly available without an access request once these issues++are resolved.++DINOv3 is required even for the default RGBA example and requires the+[publisher's access approval](https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m).+Log in with an approved Hugging Face account before downloading, or pass an+existing local DINO directory with `--dino`:++```bash+hf auth login+```++```bash- python scripts/prepare_models.py --repo supra3d/supra-tex --dry-run- python scripts/prepare_models.py --repo supra3d/supra-tex++python scripts/prepare_models.py --dry-run++python scripts/prepare_models.py+```++The preparation entrypoint fetches the project subdirectories and external+Qwen-Image-2.1, Pixal3D geometry, DINOv3, MoGe-2, TRELLIS.2 VAEs and NAF weights.+Component paths, external versions, file selections and inference defaults come+from the root `pipeline.json` at the requested project revision.+It assembles the geometry configuration, local DINO directory and NAF Torch Hub+cache, then writes `ckpts/ready/models.json`. Inference consumes these prepared+local files with Hub access disabled and uses the selected manifest's defaults.+The generated `models.json` records local runtime bindings; component architecture+and normalization are maintained only in their existing component configs.++For opaque RGB inputs, also request access to+[RMBG-2](https://huggingface.co/briaai/RMBG-2.0) and include it in preparation:++```bash- python scripts/prepare_models.py --repo supra3d/supra-tex --with-rmbg++python scripts/prepare_models.py --with-rmbg+```+- This also adds RMBG to an existing preparation in the same output directory.++To avoid RMBG-2's access request, use the public++[BiRefNet](https://huggingface.co/ZhengPeng7/BiRefNet) instead. RMBG-2 is built on++it and both load through the same foreground adapter; on our examples their++foreground masks agree closely (IoU above 0.99). Download it and pass its directory:++++```bash++hf download ZhengPeng7/BiRefNet --local-dir /path/to/BiRefNet++python scripts/prepare_models.py --rmbg /path/to/BiRefNet++```++++Either option also adds the foreground model to an existing preparation in the++same output directory.+Keep the original model sources and options; the script updates its generated+configuration without replacing user edits. Authentication is not stored in+`models.json`.++Use `--revision` to select a project snapshot, or `--repo /path/to/supra-tex`+for a local model repository root. `--pipeline /path/to/pipeline.json` selects+an explicit local manifest. `--completion` and `--material`+override the project subdirectories with existing local model directories or+separate Hub repositories. External local overrides are available as+`--qwen-base`, `--geometry`, `--dino`, `--vae`, `--moge`, `--naf-weights` and+`--rmbg`; run `python scripts/prepare_models.py --help` for their accepted layouts.+Local overrides avoid downloading those models but remain external file+dependencies. `--cache-dir` uses a shared Hugging Face cache and links the+prepared files to it; keep that cache available. Without an explicit cache,+downloads go into the prepared model directory. Use `--local-files-only` for+local files and cached downloads; NAF weights must already be prepared or+supplied through `--naf-weights`.++The default models occupy much more space than the source or adapter alone:+Qwen's complete foundation components, geometry networks and VAEs are required.+`--dry-run` previews selected sources and destinations without network access.+For a Hub repository it uses the bundled [configuration](../configs/pipeline.json); supply a local repository or+`--pipeline` to preview another manifest. A normal preparation run obtains the+manifest from the requested Hub revision.+Preparation reuses completed downloads after interruption. Retry using the+same arguments. If changing model sources, choose a new `--output-dir` and pass+its `models.json` to the checker and runner with `--config`. Existing local+models can be reused with the overrides above.++## 3. Check and run++```bash+python scripts/check_runtime.py- python scripts/run_example.py --output outputs/pitcher_plant.glb --attention sdpa++python scripts/run_example.py --output outputs/spiny_whelk_shell.glb+```+- The default bundled example has foreground alpha. For your own opaque RGB image,- prepare RMBG as above and run:++The default bundled example has foreground alpha. For an opaque RGB image, such++as the bundled candle jar, prepare RMBG as above and run:++```bash- python scripts/run_example.py --input path/to/image.png \- --output outputs/object.glb --attention sdpa++python scripts/run_example.py --input assets/metalwork_candle_jar.png \++ --output outputs/metalwork_candle_jar.glb+```+++Replace `--input` with your own image.+++`--print-command` shows the exact inference command without running it.+`--config` selects a different prepared `models.json`. The launcher uses this+checkout's runtime, reads manifest defaults and sets `TORCH_HOME` to its prepared+NAF cache. Explicit inference controls take precedence over the defaults;+model paths come from `models.json`. Use a new+output filename/work directory for every inference; existing results are kept.+The underlying [inference CLI](end_to_end.md) exposes further controls, including+CPU offload and the optional dual-view workflow.++Alternatively, prepare and run directly from one pipeline source:++```bash+python infer.py --pipeline supra3d/supra-tex \+ --input path/to/image.png --output outputs/object.glb+```++`--pipeline` also accepts a local model repository root or manifest file.+`--pipeline-revision` selects a Hub snapshot; `--models-dir` selects the prepared+model directory. The same upstream access requirements apply.++A successful full run produces a nonempty GLB and a sibling work directory+whose `run.json` has `status: complete` and `stage: complete`. Inspect the GLB+for visual quality separately. `check_runtime.py` checks model paths/headers,+actual Qwen and geometry imports, native extensions and a small CUDA operation;+passing it alone is not a full model inference result. `--imports-only` needs+no model weights; `--files-only` skips the CUDA/import probes.++The optional automatic dual-view mode needs its separately documented image+generation capability. The default single-view example does not require it.diff --cc docs/texturing.mdindex 1527df4,0000000..da23953mode 100644,000000..100644--- a/docs/texturing.md+++ b/docs/texturing.md@@@ -1,110 -1,0 +1,184 @@@+# Texture an existing mesh++`texturing.py` completes PBR materials for a supplied mesh using reference-view+material maps. Prepare the maps with the [material frontend](frontend.md) or+supply compatible maps yourself. Keep the mesh and its matching camera together;+the [geometry frontend](geometry.md) can produce them.++## Inputs++The input directory must contain:++- `geometry.pt`: a dictionary with `verts` (`float[N,3]`) and `faces` (`int[M,3]`).++ A compressed `geometry.npz` with the same `verts` and `faces` arrays is also++ accepted for single-view texturing; dual-view inputs use `geometry.pt`.+- `camera.json`: canonical `camera_angle_x` in radians and `distance`, with+ optional `mesh_scale`. The effective camera distance is `distance * mesh_scale`.+- `condition_rgba.png`: a square observation with foreground alpha, aligned+ with the mesh and camera.+- `albedo.png` and `mra.png`: RGB images at 1024 by 1024. MRA stores metallic,+ roughness, and alpha in R, G, and B respectively.++## Run++From the repository root after [installation](quickstart.md):++```bash+python texturing.py --pipeline supra3d/supra-tex \+ --input-dir inputs/object \+ --output outputs/textured_object.glb+```+++Without `--input-dir`, `texturing.py` uses the bundled++[pitcher plant example](../assets/examples/pitcher_plant): the project-page mesh++with its camera, foreground condition, and reference-view material maps.+++`--pipeline` accepts a model repository ID/URL, a local model repository directory,+or a local manifest file. This entrypoint loads only the completion model and+TRELLIS.2 VAEs. It does not generate the input geometry or reference material maps.+No separate `texturing.json` is needed.++The manifest supplies the seed, texture size, face target, texture format, and+attention defaults. Explicit CLI values take precedence. The bundled defaults+are seed 42, a 4096-pixel PNG atlas, a 500000-face target, and automatic attention.+Use `--low-vram` for CPU offload or `--attention sdpa` to avoid FlashAttention;+see [GPU compatibility](gpu_compatibility.md).++`--pipeline-revision` selects a Hub release snapshot. `--cache-dir` selects+the download cache; `--local-files-only` requires local or cached weights.+For a local release and separately stored VAEs:++```bash+python texturing.py \+ --pipeline /path/to/model-release/pipeline.json \+ --trellis-root /path/to/TRELLIS.2-4B --local-files-only \+ --input-dir inputs/object --output outputs/textured_object.glb+```++A local manifest's completion path is relative to that manifest. Its external+VAE source still applies unless overridden with `--trellis-root`.++## Alternate checkpoint layouts++Use `--pretrained /path/to/completion` and `--trellis-root /path/to/TRELLIS.2-4B`+in place of `--pipeline` for a standalone completion bundle. `--pretrained` also+accepts a Hub repository ID. `--revision` selects that bundle's revision;+`--pipeline-revision` selects the enclosing pipeline release when used together.++Individual legacy artifacts can be selected explicitly:++```bash+python texturing.py \+ --input-dir inputs/object --output outputs/textured_object.glb \+ --model-config configs/inference_model.json \+ --checkpoint /path/to/material_completion.pt \+ --trellis-root /path/to/sparse_encoders+```++The checked-in legacy config resolves decoder stems under `weights/scvae/`+and normalization relative to the config file. Populate those paths or update+the config to match your files. For the published safetensors layout, use the+release's `config.json` and all four external VAEs instead. See+[weights](weights.md) for the exact layouts.++## Completion and export++Completion uses a fixed 25-step Euler sampler with `rescale_t=3` and+`sigma_min=1e-5`. Visible observations use trusted alpha at least 254,+a 5-by-5 erosion at 1024 resolution, and a depth-discontinuity filter before+encoding material features. These filters leave the saved RGBA image unchanged.+++Each run prints an `Observation:` line that compares the projected geometry++silhouette with the image foreground (IoU, the fraction of the geometry inside++the image, and the fraction of the image covered by the geometry) and counts the++admitted and rejected trusted pixels. An IoU below 0.9 also prints a warning:++in mismatched regions the texture relies on completion rather than the image.+++The output must be a new `.glb` path. The mesh stays fixed while material+completion runs, but final decoding and export can change vertices, faces,+and UV layout. Input vertex arrays and UVs are not preserved by this workflow.++Optional `--gutter` adds one texel of base-color padding outside UV charts.+It is disabled by default and preserves covered texels, alpha, metallic/roughness,+geometry, and UVs. See the [image-to-3D guide](end_to_end.md) for export controls.+++## Texture refinement++++`--refine` further refines the texture that the reference view sees and aligns++it with the input image. It is off by default because it adds time. After++completion and export, it writes the observed albedo into the atlas texels visible from the reference++camera, then repairs the one-texel UV gutters from the observed albedo gradient.++The two steps always run together; they are the front half of dual-view texturing++and pass the same nineteen-phase render gates. Only base color changes;++metallic, roughness, geometry, UVs, and unseen regions stay as completed. Fine++print such as table entries and warning labels, which can blur through the++material latent, stays legible.++++The atlas must be the default 4096 PNG; any `--decimation-target` works.++`--gutter` may be combined with it: refinement then supplies the++observation-guided gutter instead of the export-time nearest-color padding,++which would only copy pre-refinement colors. `--dual-view` always applies the++same refinement to both views, so `--refine` is implied there. Intermediate meshes and++receipts go to `--work-dir` (default `<output stem>_refine` beside the GLB).++If refinement fails a render gate or errors, it is skipped with a warning: the++unrefined completion is written instead (with the export-time gutter when++`--gutter` is set), and the receipt records `refine: skipped` and the reason.++On an RTX 3090 it adds about two minutes.++++```bash++python texturing.py --pipeline supra3d/supra-tex --refine \++ --output outputs/pitcher_plant_refined.glb++```++++## Floating geometry++++Generated geometry can be misaligned with the image or contain extra pieces.++Those pieces receive completed texture that the image never showed. Floater++removal drops them before completion when they can be identified from the image++alone. Image-to-3D inference (`infer.py`) applies it by default++(`--no-remove-floaters` turns it off). `texturing.py` applies it only with++`--remove-floaters`, because a supplied mesh may intentionally extend beyond the++image:++++- The mesh is split into connected components; duplicate vertex positions, such++ as UV seams in an exported mesh, are welded first.++- Every component except the largest is projected into the reference view. A++ component is removed when fewer than half of its faces land inside the image++ foreground (alpha at least 128, dilated by 16 pixels at 1024 resolution to++ tolerate ordinary misalignment).++- Each run prints a `Floaters:` line with the removed components and faces. The++ input files are not modified. The check runs on the GPU and takes under a++ second for a 10-million-face mesh on an RTX 3090.++++Because the test uses only the reference view, it keeps everything the++foreground covers. It does not remove pieces hidden behind the object, which++cannot be told apart from genuine unseen parts such as the back of a plant, and++it does not affect extra geometry attached to the object. For those cases,++generate the geometry again with another `--seed`, or clean the mesh in a mesh++editor and texture it with `texturing.py`. On our test cases it removed nothing++from correctly generated geometry.++++```bash++python texturing.py --pipeline supra3d/supra-tex --remove-floaters \++ --input-dir inputs/object --output outputs/object_cleaned.glb++```+++## Optional dual-view texturing++A prepared back-view package can add observations of the unseen side:++```bash+python texturing.py --pipeline supra3d/supra-tex \+ --input-dir work/front --back-view-dir work/back_input --dual-view \+ --output outputs/object_dual_view.glb --work-dir work/dual_view++python -m supratex.backview validate --work-dir work/dual_view+```++This workflow requires matching geometry/material metadata for both- views; a raw normal image is insufficient. It uses a 4096 PNG atlas and a- 500000-face target, with `--gutter` disabled and a new work directory. Front- observations take priority where views overlap. See [dual-view inference](dual_view.md)- for preparation and validation commands. `--work-dir` is used only by this- optional path in `texturing.py`.++views; a raw normal image is insufficient. It always refines both views (see++[texture refinement](#texture-refinement)), so it needs the 4096 PNG atlas;++any face target works, `--gutter` uses the observation-guided gutter, and the++work directory must be new. Front observations take priority where views overlap. See [dual-view inference](dual_view.md)++for preparation and validation commands. In `texturing.py`, `--work-dir` applies++only to `--dual-view` and `--refine`.diff --cc docs/train.mdindex 0000000,0000000..8c1f175new file mode 100644--- /dev/null+++ b/docs/train.md@@@ -1,0 -1,0 +1,52 @@@++# Training Overview++++This repository currently provides inference code and pretrained models.++**We have no plans to release the training code at this time.** However, we++would like to share the overall SUPRA-Tex training workflow and the open-source++work it builds on to help others understand the method and conduct related++research.++++The workflow consists of data preparation, image-to-material prediction, and++observation-guided 3D material completion.++++## 1. Data Preparation: Following Pixal3D++++Our data processing workflow follows++[Pixal3D](https://github.com/TencentARC/Pixal3D). Starting from 3D assets with++PBR materials, we normalize the assets and render multiple views to obtain++aligned RGB images, material maps, and camera parameters.++++We then use pretrained encoders to extract sparse 3D latents for geometry and++complete materials. Visible materials from a reference view are projected onto++the object surface to construct partial material observations. Geometry,++complete materials, and partial observations must share the same 3D coordinate++frame.++++## 2. Image-to-Material Prediction: Built with DiffSynth-Studio++++The 2D material prediction stage is implemented with++[DiffSynth-Studio](https://github.com/modelscope/DiffSynth-Studio), using++Qwen-Image-2.1 as the base model to jointly predict albedo, metallic, and++roughness from a reference image.++++Training uses spatially aligned RGB images and material maps. We freeze the++pretrained backbone and adapt it to material prediction using LoRA and++learnable modality embeddings, with supervision on the material outputs in++latent space.++++## 3. 3D Material Completion: Following TRELLIS.2++++The 3D stage follows the sparse latent representation and Flow Matching++training approach of [TRELLIS.2](https://github.com/microsoft/TRELLIS.2),++with SUPRA-Tex's observation encoding and Interleaved Flow Transformer.++++During training, we add noise to the complete material latents and learn to++predict the flow velocity, conditioned on geometry latents and partial material++observations. Observation tokens remain fixed to guide generation. The training++objective covers all valid surface locations, teaching the model to preserve++visible details while completing materials in unseen regions.++++The 2D material predictor and 3D material completion model are trained++separately and connected during inference: materials are first predicted from++the input image, then encoded as 3D surface observations, and finally completed++into full PBR materials.diff --cc docs/weights.mdindex 56cfd35,0000000..d78a1b4mode 100644,000000..100644--- a/docs/weights.md+++ b/docs/weights.md@@@ -1,180 -1,0 +1,188 @@@+# Model weights++The project model repository is [supra3d/supra-tex](https://huggingface.co/supra3d/supra-tex).+Its [completion/](https://huggingface.co/supra3d/supra-tex/tree/main/completion)+and [material/](https://huggingface.co/supra3d/supra-tex/tree/main/material)+subdirectories contain the two project models;+all other weights remain external. The model repository's root `pipeline.json` selects these+components, pinned external dependencies and inference defaults. The source+preparation entrypoint reads it to obtain the complete model set:++```bash- python scripts/prepare_models.py --repo supra3d/supra-tex++python scripts/prepare_models.py+python scripts/check_runtime.py- python scripts/run_example.py --output outputs/pitcher_plant.glb++python scripts/run_example.py --output outputs/spiny_whelk_shell.glb+```++See [source setup](quickstart.md) for upstream access requirements and local+model overrides. The standalone directory descriptions below apply to the+downloaded subdirectories.+Sizes below use decimal GB/MB.++With the default repository and output directory, preparation writes+`ckpts/ready/models.json`, downloads the project models under+`ckpts/ready/project/`, and places external models under+`ckpts/ready/external/`. It also assembles `ckpts/ready/geometry/` and the NAF+cache under `ckpts/ready/torch/`. The example runner reads these paths from+`models.json`. Add `--with-rmbg` during preparation for RGB or opaque inputs;+the bundled example already has foreground alpha.++The same preparation flow accepts a local model repository root with+`--repo /path/to/supra-tex`. Use `--pipeline /path/to/pipeline.json` to select an+explicit local manifest, and `--local-files-only` to require local or cached+models. For direct image-to-3D inference, `infer.py --pipeline` prepares the+selected pipeline before running:++```bash+python infer.py --pipeline supra3d/supra-tex \+ --input path/to/image.png --output outputs/object.glb+```++`--pipeline-revision` selects the Hub snapshot and `--models-dir` selects the+prepared model directory. Explicit inference arguments override manifest+defaults. Model architecture and normalization remain in the component configs.++For an existing mesh and prepared material observations, use the same manifest+with `texturing.py`:++```bash+python texturing.py --pipeline supra3d/supra-tex \+ --input-dir inputs/object --output outputs/object.glb+```++This entrypoint resolves only the completion model and TRELLIS VAEs, using+the manifest defaults with explicit CLI overrides. It accepts a local release+directory or manifest file as well. `--pipeline-revision`, `--cache-dir`, and+`--local-files-only` control Hub resolution; `--trellis-root` supplies existing+local VAEs. See [texturing](texturing.md) for component overrides.++| We publish | Payload | License |+| --- | --- | --- |- | Supra-Tex 3D Completion | Full 2.1B-parameter model; approximately 8.38 GB, two safetensors shards | MIT |- | Supra-Tex Material Adapter | All 257 learned tensors; approximately 134.25 MB, one safetensors file | Qwen Research License |++| SUPRA-Tex 3D Completion | Full 2.1B-parameter model; default `denoiser_step0030000.safetensors`, approximately 8.38 GB, one safetensors file | MIT |++| SUPRA-Tex Material Adapter | All 257 learned tensors; approximately 134.25 MB, one safetensors file | Qwen Research License |++The material adapter is **Built with Qwen**. Its- [research license](../LICENSE) applies to++[research license](../THIRD_PARTY_NOTICES.md#qwen-research-license) applies to+the adapter. The source repository's MIT license does not replace those terms.++## Load the project models++The standalone completion model directory contains:++```text+completion/+ config.json+ partial_normalization.json- model.safetensors.index.json++ denoiser_step0030000.safetensors # default weights++ model.safetensors.index.json # earlier release, kept as a fallback+ model-00001-of-00002.safetensors+ model-00002-of-00002.safetensors+```+++`denoiser_step0030000.safetensors` is the default completion checkpoint: model++preparation downloads only it with `config.json` and `partial_normalization.json`,++and a completion directory that contains it uses it automatically. Both++checkpoints share the same architecture and normalization statistics. A directory++without it falls back to `model.safetensors` or the sharded index; select any++other weights explicitly with `--checkpoint`.+++For the standalone `--pretrained` invocation without `--pipeline`, supply the+externally downloaded TRELLIS.2 VAEs through `--trellis-root`:++```bash+python texturing.py \+ --input-dir inputs/object \+ --output outputs/object.glb \+ --pretrained /path/to/completion \+ --trellis-root /path/to/TRELLIS.2-4B+```++The VAE root may be the upstream repository root with a `ckpts/` directory,+that `ckpts/` directory itself, or another folder containing all four required+pairs listed below. Without an explicit argument the standalone release+looks under `completion/vae/`. External weights are not downloaded+implicitly by the completion loader.++When using `--pretrained` with this combined repository, pass the downloaded+`completion/` directory, not the repository root. Keep the separate `--trellis-root`+argument. The loader also accepts `namespace/repo` or `hf://namespace/repo`+for standalone repositories whose model files are at the root; `--revision`,+`--cache-dir` and `--local-files-only` control that Hub loading path.+`--model-config`, `--checkpoint` and `--trellis-root` can also be supplied+explicitly, overriding bundle defaults.+A single `model.safetensors` is supported as well as the indexed shards.++The material directory contains:++```text+material/+ adapter_config.json+ adapter_model.safetensors+```++Use it in the frontend or complete `infer.py` command:++```bash+--material-backend qwen-image \+--material-base /path/to/Qwen-Image-2.1 \+--material-model /path/to/material+```++The adapter retains attention LoRA **and modality embeddings**, in the native- Supra-Tex/Qwen PBR format. The 134 MB export excludes optimizer and RNG state;++SUPRA-Tex/Qwen PBR format. The 134 MB export excludes optimizer and RNG state;+it preserves every learned tensor and does not quantize the model. Its size+is not the full Qwen model size or a GPU memory requirement. The native+runtime loads the base first, then applies the learned state. Generic PEFT+or Transformers `AutoModel` loading is not supported by this format.++The default runtime produces albedo and metallic/roughness with fixed 1024+resolution, noise seed 42, Torch attention, and single-step endpoint prediction.+Input alpha supplies coverage in the canonical MRA blue channel. See+[the frontend guide](frontend.md) for image preparation and runtime dependencies.++## Download external models from their publishers++| External dependency | Needed for | Source |+| --- | --- | --- |+| Qwen-Image-2.1 | Material prediction | [Qwen](https://huggingface.co/Qwen/Qwen-Image-2.1) |+| Four TRELLIS.2 VAEs | 3D texture completion | [Microsoft TRELLIS.2-4B](https://huggingface.co/microsoft/TRELLIS.2-4B) |+| Pixal3D geometry | RGB-to-mesh | [TencentARC/Pixal3D](https://huggingface.co/TencentARC/Pixal3D) |+| MoGe-2 | Camera estimation | [Ruicheng/moge-2-vitl-normal](https://huggingface.co/Ruicheng/moge-2-vitl-normal) |+| DINOv3 and NAF | Geometry conditioning | [DINOv3](https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m), [NAF](https://github.com/valeoai/NAF) |+| RMBG-2 | Foreground extraction when input alpha is unavailable | [BRIA RMBG-2.0](https://huggingface.co/briaai/RMBG-2.0) |++These weights are not included in the project model subdirectories. Retain their upstream+license and model-card files; gated models require access from their publishers.+Required file patterns and recorded revisions are listed in the source+repository's [`configs/pipeline.json`](../configs/pipeline.json), under `external_models`.++For Qwen, keep all files under `transformer/`, `text_encoder/`, `vae/`, and+`processor/`, including every weight file/shard, the component configs,+shard indexes, tokenizer and processor assets.++For TRELLIS.2, each stem requires both `.json` and `.safetensors`:++```text+shape_enc_next_dc_f16c32_fp16+tex_enc_next_dc_f16c32_fp16+shape_dec_next_dc_f16c32_fp16+tex_dec_next_dc_f16c32_fp16+```++Standalone completion reads its architecture and all necessary normalization+values from the project config/statistics. It does not need the entire+upstream geometry `pipeline.json`; RGB geometry generation separately needs+Pixal3D's own model layout, described in [Geometry](geometry.md).++## Legacy and optional formats++Existing PT bundles remain accepted: `configs/inference_model.json`,+`configs/partial_normalization.json`, `weights/material_completion.pt`,+`weights/sparse_encoders/` and `weights/scvae/`. In this legacy layout decoder+paths remain relative to the model config. Existing Qwen+`checkpoint-0100000.pt` plus its matching `.complete.json` also remain supported;+safetensors exports use their JSON adapter config instead of that PT marker.++The optional `firered` backend and its full Transformer/contract files remain+supported by the code, but FireRed weights are outside this project release.+The default selected release uses the Qwen material backend.diff --cc infer.pyindex 16705a6,0000000..0f5aa6emode 100644,000000..100644--- a/infer.py+++ b/infer.py@@@ -1,335 -1,0 +1,346 @@@+#!/usr/bin/env python3+"""Generate a textured PBR mesh from one RGB/RGBA image."""+from __future__ import annotations++import argparse+import json+import math+import os+from pathlib import Path+import sys+++def _pipeline_overrides(args: argparse.Namespace) -> dict:+ """Validate explicit model selections before resolving a release."""+ overrides = {}+ for component, attribute in (("completion", "pretrained"), ("material", "material_model"),+ ("qwen-base", "material_base"), ("geometry", "geometry_model"),+ ("vae", "trellis_root"), ("moge2", "moge_model"), ("rmbg2", "rmbg_model")):+ value = getattr(args, attribute)+ if value is not None:+ if component not in ("completion", "material") and not Path(value).expanduser().exists():+ raise ValueError(f"--pipeline requires a local --{attribute.replace('_', '-')} override")+ overrides[component] = value+ if args.revision is not None:+ if args.pretrained is None:+ raise ValueError("--revision requires --pretrained with --pipeline; use --pipeline-revision for the release")+ overrides["completion_revision"] = args.revision+ if args.material_revision is not None:+ if args.material_model is None:+ raise ValueError("--material-revision requires --material-model with --pipeline")+ overrides["material_revision"] = args.material_revision+ return overrides+++def _prepare_pipeline(args: argparse.Namespace, overrides: dict, descriptor: dict, *, has_alpha: bool) -> dict:+ """Prepare the release already selected during argument validation."""+ from scripts.prepare_models import prepare_pipeline+ from scripts.run_example import read_config++ source = descriptor["repo_id"] if descriptor["kind"] == "hub" else args.pipeline+ revision = descriptor.get("revision") if descriptor["kind"] == "hub" else args.pipeline_revision+ prepared = prepare_pipeline(source, output_dir=args.models_dir, revision=revision,+ cache_dir=args.cache_dir, local_files_only=args.local_files_only,+ with_rmbg=not has_alpha,+ overrides=overrides)+ return read_config(prepared)+++def _validate_inference_options(args: argparse.Namespace) -> None:+ """Check explicit values first, then call again after release defaults."""+ from scripts.prepare_models import _pipeline++ if args.back_view_dir is not None and not args.dual_view:+ raise ValueError("--back-view-dir requires --dual-view")+ _pipeline.validate_export_options(args)+ if not math.isfinite(args.geometry_initial_mesh_scale) or args.geometry_initial_mesh_scale <= 0:+ raise ValueError("geometry-initial-mesh-scale must be finite and positive")+ if not 1 <= args.geometry_target_padding <= 30 or args.geometry_max_iterations < 1:+ raise ValueError("geometry-target-padding must be in [1, 30]; geometry-max-iterations must be positive")+ if not 0 <= args.resolution_level <= 9:+ raise ValueError("resolution-level must be in [0, 9]")+++def _validate_input_output(args: argparse.Namespace, *, require_rmbg: bool = True) -> tuple[Path, Path, Path, bool]:+ """Check local inputs and destinations without creating or downloading files."""+ image, output = args.input.expanduser().resolve(), args.output.expanduser().absolute()+ if output.suffix.lower() != ".glb":+ raise ValueError("--output must have a .glb suffix")+ if output.exists() or output.is_symlink():+ raise FileExistsError(f"refusing to overwrite existing output: {output}")+ output = output.resolve()+ work = (args.work_dir or output.parent / f"{output.stem}_work").expanduser().absolute()+ if work.is_symlink() and not work.exists():+ raise FileExistsError(f"--work-dir must be a fresh empty directory: {work}")+ work = work.resolve()+ if work.exists() and (not work.is_dir() or any(work.iterdir())):+ raise FileExistsError(f"--work-dir must be a fresh empty directory: {work}")+ for destination in (output, work):+ for parent in destination.parents:+ if parent.exists():+ if not parent.is_dir():+ raise NotADirectoryError(f"destination parent must be a directory: {parent}")+ break+ if not image.is_file():+ raise FileNotFoundError(f"input image is missing: {image}")+ from PIL import Image+ with Image.open(image) as source:+ low, high = source.getchannel("A").getextrema() if source.mode == "RGBA" else (255, 255)+ has_alpha = low < 255 and high > 0+ if args.use_input_alpha and not has_alpha:+ raise ValueError("--use-input-alpha requires a non-opaque RGBA input with foreground pixels")+ if require_rmbg and not has_alpha and not args.rmbg_model:+ raise ValueError("RGB/opaque input requires --rmbg-model")+ source.load()+ if args.dual_view and args.back_view_dir is None:+ import shutil+ if shutil.which("codex") is None:+ raise RuntimeError("automatic back generation requires Codex with gpt-6-astra and built-in image_gen")+ return image, output, work, has_alpha+++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)+ parser.add_argument("--pipeline", help="SUPRA-Tex release directory, pipeline.json, or HF repo ID; prepares and loads all stages")+ parser.add_argument("--pipeline-revision", help="HF revision of the complete SUPRA-Tex release")+ parser.add_argument("--models-dir", type=Path, help="prepared model directory for --pipeline (default: ckpts/ready)")+ parser.add_argument("--input", type=Path,- default=Path(__file__).resolve().parent / "assets/pitcher_plant.png",- help="source RGB/RGBA image (default: assets/pitcher_plant.png)")++ help="source RGB/RGBA image (default: assets/spiny_whelk_shell.png, or "++ "assets/cinema_signage.png with --dual-view)")+ parser.add_argument("--output", required=True, type=Path, help="new destination .glb file")+ parser.add_argument("--work-dir", type=Path, help="fresh intermediate directory (default: <output stem>_work beside the GLB)")+ parser.add_argument("--moge-model", help="local MoGe-2 checkpoint/directory or HF repo ID")+ parser.add_argument("--rmbg-model", help="local RMBG-2 directory or HF repo ID; required for RGB input")+ parser.add_argument("--use-input-alpha", action="store_true", help="require and reuse foreground RGBA alpha")+ parser.add_argument("--resolution-level", type=int, default=9, help="MoGe-2 resolution level")+ parser.add_argument("--geometry-package", type=Path, help="native or paper geometry source checkout; see docs/geometry.md")+ parser.add_argument("--geometry-model", help="local geometry weights directory or HF repo ID")+ parser.add_argument("--geometry-revision", help="geometry weights HF revision")+ parser.add_argument("--geometry-initial-mesh-scale", type=float, default=1.0)+ parser.add_argument("--geometry-scale-search", action="store_true",+ help="enable bounded mesh-scale calibration (default: Pixal3D fixed scale)")+ parser.add_argument("--parallel-frontend", action="store_true",+ help="run geometry and Qwen material concurrently on the first two visible GPUs")+ parser.add_argument("--geometry-target-padding", type=int, default=3, help="scale-search target padding")+ parser.add_argument("--geometry-max-iterations", type=int, default=2, help="scale-search update limit")+ parser.add_argument("--firered-package", type=Path, default=Path(__file__).resolve().parent / "supratex/frontend/material_model")+ parser.add_argument("--material-backend", choices=("qwen-image", "firered"), default="qwen-image")+ parser.add_argument("--material-base", help="selected backend base model: local directory or HF repo ID")+ parser.add_argument("--firered-base", help="legacy FireRed base option; requires --material-backend firered")+ parser.add_argument("--qwen-runtime", type=Path, help="native Qwen source snapshot (default: bundled runtime)")+ parser.add_argument("--qwen-deps", type=Path, help="optional Qwen dependency overlay; otherwise use the active Python environment")+ parser.add_argument("--material-model", help="local backend checkpoint bundle or HF repo ID")+ parser.add_argument("--material-revision", help="material checkpoint HF revision")+ parser.add_argument("--material-weights", type=Path)+ parser.add_argument("--material-spec", type=Path)+ parser.add_argument("--material-checkpoint-manifest", type=Path)+ parser.add_argument("--pretrained", help="local Supra-Tex completion bundle or HF repo ID")+ parser.add_argument("--revision", help="completion bundle HF revision")+ parser.add_argument("--model-config", type=Path, help="completion ABI JSON; overrides bundle config")+ parser.add_argument("--checkpoint", type=Path, help="completion weights; overrides bundle checkpoint")+ parser.add_argument("--trellis-root", type=Path, help="TRELLIS.2 VAE directory (all four components for HF releases)")+ parser.add_argument("--cache-dir", type=Path, help="shared HF download cache for all adapters")+ parser.add_argument("--local-files-only", action="store_true", help="resolve models locally without Hub downloads")+ parser.add_argument("--attention", choices=("auto", "flash_attn_3", "flash_attn", "sdpa", "xformers"),+ help="inference attention backend; auto selects by GPU and installed extensions")+ parser.add_argument("--low-vram", action=argparse.BooleanOptionalAction, default=None,+ help="CPU offload for Qwen and 3D stages; auto enabled on GPUs with up to 24 GiB")+ parser.add_argument("--seed", type=int, help="geometry and completion seed (material runner uses its fixed seed 42)")+ parser.add_argument("--texture-size", type=int)+ parser.add_argument("--decimation-target", type=int)+ parser.add_argument("--texture-format", choices=("png", "webp"))- parser.add_argument("--gutter", action="store_true", help="enable chart-isolated one-texel base-color gutter padding (default: disabled)")- parser.add_argument("--dual-view", action="store_true", help="add v4 back rendering, Astra/image_gen generation, and dual-view texturing")++ parser.add_argument("--gutter", action="store_true", help="enable chart-isolated one-texel base-color gutter padding (default: disabled); "++ "with --refine, the observation-guided gutter is used")++ parser.add_argument("--refine", action="store_true",++ help="refine the visible texture after export: write the observed reference-view albedo into the atlas "++ "and repair its UV gutters from the observation (sharper fine text and detail; needs the 4096 PNG "++ "atlas; adds about 2 minutes on an RTX 3090)")++ parser.add_argument("--remove-floaters", action=argparse.BooleanOptionalAction, default=True,++ help="before completion, drop disconnected geometry pieces that project mostly outside the "++ "image foreground (default: on); extra geometry attached to the object is kept")++ parser.add_argument("--dual-view", action="store_true", help="generate a back view (needs the external Codex CLI) and texture with both views; includes --refine for both views")+ parser.add_argument("--back-view-dir", type=Path, help="reuse a prepared, geometry-bound back package instead of generating a new back")+ args = parser.parse_args(argv)- from scripts.run_example import MODEL_KEYS, _pipeline_config, inference_defaults++ from scripts.run_example import MODEL_KEYS, _pipeline_config, default_input, inference_defaults++ if args.input is None:++ args.input = default_input(args.dual_view)+ if not args.pipeline and (args.pipeline_revision is not None or args.models_dir is not None):+ parser.error("--pipeline-revision and --models-dir require --pipeline")+ material_paths = (args.material_weights, args.material_spec, args.material_checkpoint_manifest)+ if args.pipeline and args.material_backend != "qwen-image":+ parser.error("--pipeline requires --material-backend qwen-image")+ if args.material_backend == "qwen-image" and (args.firered_base or any(material_paths)):+ parser.error("FireRed options require --material-backend firered")+ try:+ # Reject explicit argument/input errors before fetching any metadata.+ _validate_inference_options(args)+ if args.pipeline:+ overrides = _pipeline_overrides(args)+ _, _, _, has_alpha = _validate_input_output(args, require_rmbg=False)+ from scripts.prepare_models import _pipeline+ manifest, descriptor = _pipeline.resolve_pipeline(+ args.pipeline, revision=args.pipeline_revision, cache_dir=args.cache_dir,+ local_files_only=args.local_files_only)+ defaults = manifest["defaults"]+ else:+ defaults = inference_defaults()+ for key, value in defaults.items():+ if getattr(args, key) is None:+ setattr(args, key, value)+ # Release defaults can introduce a dual-view conflict; check before downloads.+ _validate_inference_options(args)+ if args.pipeline:+ prepared = _prepare_pipeline(args, overrides, descriptor, has_alpha=has_alpha)+ except (OSError, ValueError, RuntimeError) as error:+ parser.error(str(error))+ if args.pipeline:+ explicit_pretrained = args.pretrained is not None+ direct_overrides = {"geometry_package", "qwen_runtime", "qwen_deps", "model_config", "checkpoint"}+ for key in MODEL_KEYS:+ if prepared.get(key) is not None and (key not in direct_overrides or getattr(args, key) is None):+ if explicit_pretrained and key in ("model_config", "checkpoint"):+ continue+ action = parser._option_string_actions["--" + key.replace("_", "-")]+ value = prepared[key]+ setattr(args, key, action.type(value) if action.type else value)+ args.local_files_only = True+ args._pipeline_config = prepared+ if not all((args.moge_model, args.geometry_package, args.geometry_model)):+ parser.error("provide --pipeline or all of --moge-model, --geometry-package, and --geometry-model")+ if args.material_backend == "qwen-image":+ args.qwen_runtime = args.qwen_runtime or _pipeline_config().runtime_root(Path(__file__).resolve().parent) / "qwen"+ args.material_base = args.material_base or str(Path(__file__).resolve().parent / "ckpts/qwen-base")+ args.material_model = args.material_model or str(Path(__file__).resolve().parent / "ckpts/qwen-material")+ else:+ if args.qwen_runtime is not None or args.qwen_deps is not None:+ parser.error("--qwen-runtime and --qwen-deps require --material-backend qwen-image")+ if args.material_base and args.firered_base:+ parser.error("provide only one of --material-base and --firered-base")+ if not (args.material_base or args.firered_base):+ parser.error("FireRed requires --material-base or --firered-base")+ if args.material_model and any(material_paths):+ parser.error("--material-model cannot be combined with explicit material artifact paths")+ if not args.material_model and not all(material_paths):+ parser.error("provide --material-model or all three --material-weights, --material-spec, --material-checkpoint-manifest")+ if not args.pretrained and not all((args.model_config, args.checkpoint, args.trellis_root)):+ parser.error("provide --pretrained or all of --model-config, --checkpoint, and --trellis-root")+ return args+++def _completion_paths(args: argparse.Namespace) -> tuple[Path, Path, Path]:+ """Resolve local/Hub artifacts and check missing completion files before GPU work."""+ from supratex.weights import COMPLETION_ALLOW_PATTERNS, resolve_completion_artifacts, resolve_model_dir+ root = None+ if args.pretrained:+ root = resolve_model_dir(args.pretrained, revision=args.revision, cache_dir=args.cache_dir,+ local_files_only=args.local_files_only,+ allow_patterns=COMPLETION_ALLOW_PATTERNS)+ return resolve_completion_artifacts(root, model_config=args.model_config,+ checkpoint=args.checkpoint, trellis_root=args.trellis_root)+++def run(args: argparse.Namespace) -> Path:+ """Run the existing image frontend, then complete and export its generated mesh."""+ if getattr(args, "_pipeline_config", None) is not None:+ from scripts.run_example import runtime_environment+ environment = runtime_environment(args._pipeline_config, args.attention)+ for key in ("ATTN_BACKEND", "SPARSE_ATTN_BACKEND"):+ if key not in environment:+ os.environ.pop(key, None)+ os.environ.update(environment)+ for source in reversed(environment["PYTHONPATH"].split(os.pathsep)):+ if source not in sys.path:+ sys.path.insert(0, source)+ image, output, work, _ = _validate_input_output(args)+ from supratex.inference.runtime import configure_inference_runtime+ runtime = configure_inference_runtime(attention=getattr(args, "attention", "auto"),+ low_vram=getattr(args, "low_vram", None),+ material_backend=args.material_backend)+ # The adapters validate source compatibility and full checkpoint contents.+ from supratex.frontend.geometry import validate_source+ validate_source(args.geometry_package.expanduser())+ if args.material_backend == "qwen-image":+ from supratex.frontend.qwen_image import validate+ validate(args.qwen_runtime, args.material_base, args.material_model, deps=args.qwen_deps,+ revision=args.material_revision, cache_dir=args.cache_dir, local_files_only=args.local_files_only)+ elif not (args.firered_package.expanduser() / "infer.py").is_file():+ raise FileNotFoundError(f"material entrypoint is missing: {args.firered_package / 'infer.py'}")+ material_paths = {}+ for name in ("material_weights", "material_spec", "material_checkpoint_manifest"):+ path = getattr(args, name)+ if path is not None:+ path = path.expanduser().resolve()+ if not path.is_file():+ raise FileNotFoundError(f"missing {name}: {path}")+ material_paths[name] = path+ config, checkpoint, encoders = _completion_paths(args)+ from supratex.frontend.pipeline import run as run_frontend+ from supratex.inference import run_completion+ work.mkdir(parents=True, exist_ok=True)+ handoff = work / "input"+ receipt = {"status": "running", "stage": "frontend", "input": str(image), "output": str(output),+ "work_dir": str(work), "seed": args.seed, "gutter": args.gutter,+ "material_backend": args.material_backend, "material_seed": 42,+ "runtime": runtime,- "model_config": str(config), "checkpoint": str(checkpoint), "dual_view": args.dual_view}++ "model_config": str(config), "checkpoint": str(checkpoint), "dual_view": args.dual_view,++ "refine": args.refine, "remove_floaters": args.remove_floaters}+ def record() -> None:+ temporary = work / ".run.json.tmp"+ temporary.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8")+ temporary.replace(work / "run.json")+ record()+ try:+ print(f"[1/2] Foreground, MoGe-2, geometry, material maps -> {handoff}", flush=True)+ result = run_frontend(image, handoff, moge_model=args.moge_model, rmbg_model=args.rmbg_model,+ use_input_alpha=args.use_input_alpha, resolution_level=args.resolution_level,+ geometry_package=args.geometry_package.expanduser().resolve(), geometry_model=args.geometry_model,+ geometry_revision=args.geometry_revision, geometry_seed=args.seed,+ geometry_initial_mesh_scale=args.geometry_initial_mesh_scale,+ geometry_scale_search=args.geometry_scale_search,+ parallel_frontend=args.parallel_frontend,+ geometry_target_padding=args.geometry_target_padding,+ geometry_max_iterations=args.geometry_max_iterations,+ firered_package=args.firered_package.expanduser().resolve(), firered_base=args.firered_base,+ material_backend=args.material_backend, material_base=args.material_base,+ qwen_runtime=args.qwen_runtime if args.material_backend == "qwen-image" else None,+ qwen_deps=args.qwen_deps if args.material_backend == "qwen-image" else None,+ material_model=args.material_model, **material_paths,+ revision=args.material_revision, cache_dir=args.cache_dir, local_files_only=args.local_files_only,+ **({"record_material_provenance": True} if args.dual_view else {}))- optional = {}++ optional = {"refine": True, "work_dir": work / "refine"} if args.refine else {}+ if args.dual_view:+ receipt.update(stage="back_view", frontend=result)+ record()+ if args.back_view_dir is None:+ from supratex.backview.workflow import build_back_view+ back_dir = build_back_view(handoff, work / "back_view", cache_dir=args.cache_dir,+ local_files_only=args.local_files_only)+ else:+ back_dir = args.back_view_dir.expanduser().resolve()+ optional = {"back_view_dir": back_dir, "work_dir": work / "dual_view"}+ receipt["back_view_dir"] = str(back_dir)+ receipt.update(stage="completion", frontend=result)+ record()+ print(f"[2/2] Surface observations, PBR completion, GLB export -> {output}", flush=True)+ run_completion(input_dir=handoff, output=output, model_config=config, checkpoint=checkpoint,+ trellis_root=encoders, seed=args.seed, texture_size=args.texture_size,+ decimation_target=args.decimation_target, texture_format=args.texture_format, gutter=args.gutter,- **optional)++ remove_floaters=args.remove_floaters, **optional)+ if not output.is_file() or output.stat().st_size == 0:+ raise RuntimeError(f"completion did not emit a nonempty GLB: {output}")+ except Exception as error:+ receipt.update(status="failed", error=f"{type(error).__name__}: {error}")+ record()+ raise+ receipt.update(status="complete", stage="complete")+ record()+ print(f"Textured mesh: {output}\nIntermediate files and run receipt: {work}", flush=True)+ return output+++def main() -> None:+ run(parse_args())+++if __name__ == "__main__":+ main()diff --cc pyproject.tomlindex bf98591,0000000..1317ea2mode 100644,000000..100644--- a/pyproject.toml+++ b/pyproject.toml@@@ -1,29 -1,0 +1,29 @@@+[build-system]+requires = ["setuptools>=68"]+build-backend = "setuptools.build_meta"++[project]+name = "supra-tex"+version = "0.1.0"+description = "SUPRA-Tex: 3D Generation with Super-Aligned Texture"+readme = "README.md"+license = {file = "LICENSE"}+requires-python = ">=3.10"+dependencies = [+ "torch>=2.6", "torchvision>=0.21", "numpy", "Pillow", "scipy",+ "easydict", "tqdm", "einops", "safetensors", "huggingface-hub",+ "trimesh", "opencv-python-headless", "imageio", "imageio-ffmpeg", "numba",+]++[project.optional-dependencies]+frontend = ["transformers==4.57.3", "diffusers==0.37.1", "accelerate", "requests", "timm"]++[tool.setuptools]- license-files = ["LICENSE"]++license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md"]++[tool.setuptools.packages.find]+include = ["supratex*"]++[tool.setuptools.package-data]+"supratex.backview.harness" = ["prompts/*.txt", "README.md"]+diff --cc scripts/check_runtime.pyindex c59333e,0000000..de87b71mode 100644,000000..100644--- a/scripts/check_runtime.py+++ b/scripts/check_runtime.py@@@ -1,172 -1,0 +1,172 @@@+#!/usr/bin/env python3+"""Check the source release's real runtime imports and prepared model files."""+from __future__ import annotations++import argparse+import json+import os+from pathlib import Path+import subprocess+import sys++ROOT = Path(__file__).resolve().parents[1]+RUNTIME = ROOT / "deployment/runtime"+++def runtime_environment(config: dict | None = None) -> dict[str, str]:+ env = os.environ.copy()+ env.update(PYTHONNOUSERSITE="1", PYTHONDONTWRITEBYTECODE="1", HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1",+ FLEX_GEMM_USE_AUTOTUNE_CACHE="0", FLEX_GEMM_AUTOSAVE_AUTOTUNE_CACHE="0",+ PYTHONPATH=os.pathsep.join(str(p) for p in+ (ROOT, RUNTIME / "moge", RUNTIME / "utils3d")))+ if config and config.get("torch_home"):+ env["TORCH_HOME"] = config["torch_home"]+ return env+++def run_import_check(code: str, *, config: dict | None = None) -> str:+ result = subprocess.run([sys.executable, "-c", code], cwd=ROOT,+ env=runtime_environment(config), capture_output=True, text=True, timeout=300)+ if result.returncode:+ raise RuntimeError((result.stderr or result.stdout)[-5000:].strip())+ return result.stdout.strip()+++def import_checks(attention: str) -> list[tuple[str, str]]:+ bootstrap = ("from supratex.inference.runtime import configure_inference_runtime; "+ f"configure_inference_runtime(attention={attention!r}, material_backend='qwen-image'); ")+ return [+ ("Python, PyTorch and CUDA", """+import sys, torch, torchvision+if sys.version_info[:2] != (3, 10):+ raise RuntimeError('The supported installation uses Python 3.10')+if torch.__version__.split('+')[0] != '2.6.0' or torch.version.cuda != '12.4':+ raise RuntimeError('Expected PyTorch 2.6.0 with CUDA 12.4; got ' + str((torch.__version__, torch.version.cuda)))+if torchvision.__version__.split('+')[0] != '0.21.0':+ raise RuntimeError('Expected torchvision 0.21.0')+if not torch.cuda.is_available():+ raise RuntimeError('CUDA is unavailable; check the NVIDIA driver and GPU access')+x = torch.tensor([1., 2.], device='cuda')+assert (x * x).sum().item() == 5.+torch.cuda.synchronize()+print(torch.cuda.get_device_name(0))+"""),+ ("Native extensions, MoGe and utils3d", """+import torch, natten, natten.functional+import o_voxel, flex_gemm, cumesh, nvdiffrast.torch+import moge.model.v2, utils3d+if not (hasattr(natten.functional, 'na2d') or+ all(hasattr(natten.functional, n) for n in ('na2d_av', 'na2d_qk'))):+ raise RuntimeError('NATTEN does not expose the NAF attention API')+assert hasattr(utils3d, 'pt'), 'Bundled utils3d API is required'+print('Native modules and bundled camera utilities imported')+"""),+ ("Geometry and NAF implementation", bootstrap ++ f"import sys; sys.path.insert(0, {str(RUNTIME / 'geometry')!r}); "+ f"sys.path.insert(0, {str(RUNTIME / 'naf')!r}); "+ "from pixal3d.pipelines import Pixal3DImageTo3DPipeline; "+ "from pixal3d.modules.projected_image_feature_extractor import DinoV3ProjFeatureExtractor; "+ "import hubconf; print('Geometry, projection conditioner and NAF imported')"),+ ("Qwen models, PBR pipeline and inference helpers",+ f"import sys; sys.path.insert(0, {str(RUNTIME / 'qwen')!r}); "+ f"sys.path.insert(0, {str(RUNTIME / 'qwen/examples/qwen_image_21/pbr')!r}); "+ "import peft; "+ "import diffsynth.models.qwen_image_21_dit; "+ "import diffsynth.models.qwen_image_21_text_encoder; "+ "import diffsynth.models.qwen_image_21_vae; "+ "import diffsynth.pipelines.qwen_image_21; "+ "import diffsynth.pipelines.qwen_image_21_pbr; "+ "from inference_utils import build_model, decode_pair, endpoint_noise, checkpoint_component, explicit_load, PROMPT; "+ "import inference_offload; print('Actual Qwen model and helper imports passed')"),+ ("Completion implementation", bootstrap ++ "from supratex.inference import run_completion; "+ "from supratex.models import InterleavedFlowTransformer; "+ "print('Completion implementation imported')"),+ ]+++def require_nonempty(*paths: Path) -> None:+ for path in paths:+ if not path.is_file() or path.stat().st_size == 0:+ raise FileNotFoundError(f"Required nonempty file is missing: {path}")+++def file_checks(config: dict) -> list[tuple[str, object]]:+ sys.path.insert(0, str(ROOT))+ from supratex.frontend.geometry import validate_source, validate_model+ from supratex.frontend.qwen_image import validate+ from supratex.weights import resolve_completion_artifacts++ def completion():+ resolve_completion_artifacts(Path(config["pretrained"]),+ model_config=config.get("model_config"),+ checkpoint=config.get("checkpoint"),+ trellis_root=Path(config["trellis_root"]))++ moge = Path(config["moge_model"])+ checks = [+ ("Bundled geometry source", lambda: validate_source(Path(config["geometry_package"]))),+ ("Geometry and DINO model files", lambda: validate_model(+ Path(config["geometry_package"]), Path(config["geometry_model"]))),+ ("Qwen base and released material adapter", lambda: validate(+ Path(config["qwen_runtime"]), config["material_base"], config["material_model"],+ deps=Path(config["qwen_deps"]) if config.get("qwen_deps") else None, local_files_only=True)),+ ("Released completion and four sparse VAEs", completion),+ ("MoGe weights", lambda: require_nonempty(moge / "model.pt" if moge.is_dir() else moge)),+ ("NAF local source and weights", lambda: require_nonempty(+ Path(config["torch_home"]) / "hub/valeoai_NAF_main/hubconf.py",+ Path(config["torch_home"]) / "hub/checkpoints/naf_release.pth")),+ ]+ if config.get("rmbg_model"):+ checks.append(("RGB foreground model", lambda: require_nonempty(*(+ Path(config["rmbg_model"]) / name for name in- ("config.json", "model.safetensors", "BiRefNet_config.py", "birefnet.py", "preprocessor_config.json")))))++ ("config.json", "model.safetensors", "BiRefNet_config.py", "birefnet.py")))))+ return checks+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--config", type=Path, default=ROOT / "ckpts/ready/models.json")+ scope = parser.add_mutually_exclusive_group()+ scope.add_argument("--imports-only", action="store_true", help="check installed software without model weights")+ scope.add_argument("--files-only", action="store_true", help="validate model layout and headers without CUDA checks")+ parser.add_argument("--attention", choices=("auto", "sdpa", "flash_attn", "flash_attn_3", "xformers"), default="sdpa")+ args = parser.parse_args(argv)+ results = []++ def check(name, operation):+ print(f"[check] {name}", file=sys.stderr, flush=True)+ try:+ detail = operation()+ entry = {"check": name, "status": "passed"}+ if isinstance(detail, str) and detail:+ entry["detail"] = detail+ results.append(entry)+ except Exception as error:+ results.append({"check": name, "status": "failed", "error": str(error)})++ config = None+ if not args.imports_only:+ try:+ sys.path.insert(0, str(Path(__file__).resolve().parent))+ from run_example import read_config+ config = read_config(args.config)+ os.environ.update(HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1")+ os.environ["TORCH_HOME"] = config["torch_home"]+ checks = file_checks(config)+ except Exception as error:+ results.append({"check": "Prepared model configuration", "status": "failed", "error": str(error)})+ else:+ for name, operation in checks:+ check(name, operation)+ if not args.files_only:+ for name, code in import_checks(args.attention):+ check(name, lambda code=code: run_import_check(code, config=config))+ passed = bool(results) and all(entry["status"] == "passed" for entry in results)+ print(json.dumps({"status": "passed" if passed else "failed", "checks": results,+ "scope": "Model files and actual runtime imports; full image-to-GLB inference is a separate check"}, indent=2))+ return 0 if passed else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --cc scripts/install_runtime.pyindex 11b110f,0000000..672c3ebmode 100644,000000..100644--- a/scripts/install_runtime.py+++ b/scripts/install_runtime.py@@@ -1,356 -1,0 +1,356 @@@+#!/usr/bin/env python3+"""Install the recorded Linux/Python 3.10/CUDA 12.4 runtime into Conda or a venv.++No model weights are downloaded. Native sources come from the recorded public+revisions in deployment/docs/DEPENDENCIES.md. Run --dry-run to inspect commands+without creating directories, invoking subprocesses, or accessing the network.+"""++from __future__ import annotations++import argparse+import json+import os+from pathlib import Path+import platform+import re+import shlex+import shutil+import subprocess+import sys+import tempfile+++ROOT = Path(__file__).resolve().parents[1]+SOURCES = (+ ("CuMesh", "https://github.com/JeffreyXiang/CuMesh.git", "ef40f3ae4612ea3ec934b4151e019dc95c5d276b", ""),+ ("FlexGEMM", "https://github.com/JeffreyXiang/FlexGEMM.git", "b1965ad0ae4bc8488d13b5280afb54439ce27359", ""),+ ("nvdiffrast", "https://github.com/NVlabs/nvdiffrast.git", "253ac4fcea7de5f396371124af597e6cc957bfae", ""),+ ("TRELLIS.2", "https://github.com/microsoft/TRELLIS.2.git", "5565d240c4a494caaf9ece7a554542b76ffa36d3", "o-voxel"),+)+O_VOXEL_FLAGS = " ".join((+ "--extended-lambda", "-U__CUDA_NO_HALF_OPERATORS__",+ "-U__CUDA_NO_HALF_CONVERSIONS__", "-U__CUDA_NO_HALF2_OPERATORS__",+))+CONSTRAINTS = "torch==2.6.0+cu124\ntorchvision==0.21.0+cu124\n"+BUILD_TOOLS = ("pip==25.1.1", "setuptools==80.9.0", "wheel==0.45.1", "packaging==25.0")+# Official https://whl.natten.org/ index links this exact 0.17.5 release asset.+# The former shi-labs.com wheel index has an expired TLS certificate.+NATTEN_WHEEL = (+ "https://github.com/SHI-Labs/NATTEN/releases/download/v0.17.5/"+ "natten-0.17.5%2Btorch260cu124-cp310-cp310-linux_x86_64.whl"+)+NATTEN_VERSION = "0.17.5+torch260cu124"+PYTHON_PROBE = (+ "import json,sys; "+ "print(json.dumps({'version':list(sys.version_info[:2]),"+ "'prefix':sys.prefix,'base_prefix':sys.base_prefix}))"+)+TORCH_PROBE = (+ "import torch,torchvision; "+ "assert torch.__version__ == '2.6.0+cu124', torch.__version__; "+ "assert torchvision.__version__ == '0.21.0+cu124', torchvision.__version__; "+ "assert torch.version.cuda == '12.4', torch.version.cuda; "+ "assert torch.cuda.is_available(), 'No usable NVIDIA CUDA GPU/driver'; "+ "torch.empty(1, device='cuda'); torch.cuda.synchronize(); "+ "print('Torch 2.6.0 / CUDA 12.4 GPU check passed')"+)+++class InstallError(RuntimeError):+ """An actionable installation failure, with no automatic destructive repair."""+++def clean_environment(venv: Path, *, conda: bool = False) -> dict[str, str]:+ """Do not inherit Python overlays or pip destinations from the invoking shell."""+ env = {+ key: value for key, value in os.environ.items()+ if not key.startswith("PIP_") and key not in {+ "PYTHONPATH", "PYTHONHOME", "PYTHONUSERBASE", "VIRTUAL_ENV",+ "CONDA_PREFIX", "CONDA_DEFAULT_ENV",+ }+ }+ env.update({+ "PIP_CONFIG_FILE": os.devnull,+ "PIP_REQUIRE_VIRTUALENV": "false" if conda else "true",+ "PIP_DISABLE_PIP_VERSION_CHECK": "1",+ "PIP_CACHE_DIR": str(venv / ".cache" / "pip"),+ "TORCH_EXTENSIONS_DIR": str(venv / ".cache" / "torch_extensions"),+ "FLEX_GEMM_AUTOTUNE_CACHE_PATH": str(venv / ".cache" / "flex_gemm" / "autotune_cache.json"),+ "ATTN_BACKEND": "sdpa",+ "SPARSE_ATTN_BACKEND": "sdpa",+ "BUILD_TARGET": "cuda",+ })+ if conda:+ env["CONDA_PREFIX"] = str(venv)+ if "CONDA_DEFAULT_ENV" in os.environ:+ env["CONDA_DEFAULT_ENV"] = os.environ["CONDA_DEFAULT_ENV"]+ return env+++def capture(command: list[str], env: dict[str, str]) -> str:+ try:+ return subprocess.check_output(command, env=env, text=True, stderr=subprocess.STDOUT).strip()+ except (OSError, subprocess.CalledProcessError) as exc:+ detail = getattr(exc, "output", str(exc))+ raise InstallError(f"Command failed: {shlex.join(command)}\n{detail}") from exc+++def validate_venv_destination(venv: Path) -> None:+ if venv in {Path(sys.prefix).resolve(), Path(sys.base_prefix).resolve()}:+ raise InstallError("--venv cannot be the invoking Python environment. Choose a separate directory.")+ if not venv.exists():+ return+ config = venv / "pyvenv.cfg"+ if not config.is_file() or not (venv / "bin" / "python").is_file():+ raise InstallError(f"Refusing to overwrite {venv}: existing destination is not a complete venv. Choose a new --venv.")+ settings = dict(+ line.lower().strip().split("=", 1)+ for line in config.read_text().splitlines() if "=" in line+ )+ settings = {key.strip(): value.strip() for key, value in settings.items()}+ if settings.get("include-system-site-packages") != "false":+ raise InstallError(f"{venv} must have include-system-site-packages = false. Choose a new --venv.")+++def active_conda_environment() -> Path:+ prefix = os.environ.get("CONDA_PREFIX")+ if not prefix:+ raise InstallError("Activate a dedicated Conda environment first: conda activate supra-tex.")+ destination = Path(prefix).expanduser().resolve()+ conda_exe = os.environ.get("CONDA_EXE")+ if os.environ.get("CONDA_DEFAULT_ENV") == "base" or (+ conda_exe and Path(conda_exe).resolve().parent.parent == destination+ ):+ raise InstallError("Create and activate a dedicated Conda environment; do not install into base.")+ if (Path(sys.prefix).resolve() != destination+ or Path(sys.base_prefix).resolve() != destination):+ raise InstallError("Run this script with the active Conda environment's Python, without a nested venv.")+ if not (destination / "conda-meta").is_dir() or not (destination / "bin/python").is_file():+ raise InstallError(f"{destination} is not a complete Conda Python environment.")+ return destination+++def validate_target_python(info: dict, destination: Path, *, conda: bool = False) -> None:+ valid = info.get("version") == [3, 10] and Path(info["prefix"]).resolve() == destination+ if conda:+ valid = valid and Path(info["base_prefix"]).resolve() == destination+ else:+ valid = valid and info["prefix"] != info["base_prefix"]+ if not valid:+ raise InstallError(f"{destination} is not the expected Python 3.10 {'Conda environment' if conda else 'isolated venv'}.")+++def prerequisites(python: str, venv: Path, env: dict[str, str], *, conda: bool = False) -> dict[str, str]:+ """Validate before any directory creation, download, or package installation."""+ if platform.system() != "Linux":+ raise InstallError("This recorded native runtime requires Linux.")+ if platform.machine().lower() not in {"x86_64", "amd64"}:+ raise InstallError("The pinned NATTEN 0.17.5 wheel requires Linux x86_64.")+ if not conda:+ validate_venv_destination(venv)+ try:+ probe = PYTHON_PROBE if conda else "import venv,ensurepip; " + PYTHON_PROBE+ info = json.loads(capture([python, "-I", "-c", probe], env))+ except (ValueError, KeyError) as exc:+ raise InstallError("Could not determine the selected Python version.") from exc+ if info.get("version") != [3, 10]:+ hint = "Create a Conda environment with python=3.10." if conda else "Use --python /path/to/python3.10."+ raise InstallError(f"Python 3.10 is required; {python} reports {info.get('version')}. {hint}")+ if conda:+ validate_target_python(info, venv, conda=True)+ elif Path(info["prefix"]).resolve() == venv:+ raise InstallError("--venv cannot be the selected --python environment. Choose a separate directory.")+ if not shutil.which("git", path=env.get("PATH")):+ raise InstallError("git is missing from PATH; install git before rerunning.")+ compiler = shlex.split(env.get("CXX", "c++"))+ if not compiler or not shutil.which(compiler[0], path=env.get("PATH")):+ raise InstallError("A C++ compiler is required; install g++/c++ or set CXX to a working compiler.")+ capture([*compiler, "--version"], env)+ cuda_home = env.get("CUDA_HOME") or env.get("CUDA_PATH")+ nvcc = str(Path(cuda_home).expanduser() / "bin" / "nvcc") if cuda_home else shutil.which("nvcc", path=env.get("PATH"))+ if not nvcc or not Path(nvcc).is_file():+ raise InstallError("CUDA 12.4 nvcc is required. Install the CUDA toolkit and set CUDA_HOME or add its bin directory to PATH.")+ version = capture([nvcc, "--version"], env)+ if not re.search(r"release\s+12\.4(?:\D|$)", version):+ raise InstallError(f"CUDA toolkit 12.4 is required; {nvcc} reports:\n{version}")+ result = env.copy()+ result["CUDA_HOME"] = str(Path(cuda_home).expanduser().resolve() if cuda_home else Path(nvcc).resolve().parent.parent)+ result["PATH"] = os.pathsep.join((str(venv / "bin"), str(Path(result["CUDA_HOME"]) / "bin"), env.get("PATH", "")))+ return result+++def validate_checkout(path: Path, url: str, revision: str, env: dict[str, str]) -> None:+ """Reuse only the exact, clean checkout; never reset or clean user sources."""+ if not (path / ".git").exists():+ raise InstallError(f"Refusing to overwrite {path}: not a Git checkout. Choose a fresh environment.")+ git = ["git", "-C", str(path)]+ top = capture([*git, "rev-parse", "--show-toplevel"], env)+ origin = capture([*git, "remote", "get-url", "origin"], env)+ head = capture([*git, "rev-parse", "HEAD"], env)+ dirty = capture([*git, "status", "--porcelain", "--untracked-files=no"], env)+ if Path(top).resolve() != path.resolve() or origin.rstrip("/") != url or head != revision or dirty:+ raise InstallError(+ f"Refusing to alter existing checkout {path}: expected origin {url}, HEAD {revision}, "+ "and no tracked changes (including submodules). Repair it manually or choose a fresh environment."+ )+++def run(command: list[str], env: dict[str, str], dry_run: bool, extra_env: dict[str, str] | None = None) -> None:+ display = ["env", *(f"{key}={value}" for key, value in extra_env.items()), *command] if extra_env else command+ print("$ " + shlex.join(display), flush=True)+ if not dry_run:+ child_env = dict(env, **(extra_env or {}))+ try:+ subprocess.run(command, env=child_env, check=True)+ except (OSError, subprocess.CalledProcessError) as exc:+ raise InstallError(f"Installation stopped at: {shlex.join(command)}\n{exc}\nExisting files were kept; no rollback or deletion was attempted.") from exc+++def install_natten(pip: list[str], env: dict[str, str], dry_run: bool) -> None:+ # A direct wheel URL otherwise downloads again on each resumed installation.+ # Query only the target environment; the final import checks still verify its ABI.+ if dry_run:+ print(f"# Skip NATTEN download only if this environment already has distribution version {NATTEN_VERSION}; final import checks still run.")+ else:+ probe = (+ "from importlib.metadata import version, PackageNotFoundError\n"+ "try:\n print(version('natten'))\n"+ "except PackageNotFoundError:\n print('')\n"+ )+ installed = capture([pip[0], "-I", "-c", probe], env)+ if installed == NATTEN_VERSION:+ print(f"# NATTEN {NATTEN_VERSION} already installed in target environment; skipping download.")+ return+ run([*pip, "--no-deps", "--no-index", "--only-binary=:all:", NATTEN_WHEEL], env, dry_run)+++def install_flex_gemm(pip: list[str], source: Path, managed: Path,+ env: dict[str, str], dry_run: bool) -> None:+ """Redirect the pinned setup.py cache write without altering its checkout."""+ print(f"# FlexGEMM: build a temporary source copy under {managed}; "+ f"install and runtime cache: {env['FLEX_GEMM_AUTOTUNE_CACHE_PATH']}.")+ command = [*pip, "--no-build-isolation", "--no-deps"]+ if dry_run:+ run([*command, str(managed / "flex-gemm-build-<temporary>" / "FlexGEMM")], env, True)+ return+ old = '''os.makedirs(os.path.expanduser("~/.flex_gemm"), exist_ok=True)+shutil.copyfile(+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "autotune_cache.json"),+ os.path.expanduser('~/.flex_gemm/autotune_cache.json'),+)'''+ new = '''cache_path = os.environ["FLEX_GEMM_AUTOTUNE_CACHE_PATH"]+os.makedirs(os.path.dirname(cache_path), exist_ok=True)+shutil.copyfile(+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "autotune_cache.json"),+ cache_path,+)'''+ setup = (source / "setup.py").read_text()+ if setup.count(old) != 1:+ raise InstallError("FlexGEMM setup.py does not match the pinned cache-write block; refusing an unverified patch.")+ with tempfile.TemporaryDirectory(prefix="flex-gemm-build-", dir=managed) as temporary:+ build_source = Path(temporary) / "FlexGEMM"+ shutil.copytree(source, build_source, ignore=shutil.ignore_patterns(".git"))+ (build_source / "setup.py").write_text(setup.replace(old, new))+ run([*command, str(build_source)], env, False)+++def install(args: argparse.Namespace) -> None:+ venv = active_conda_environment() if args.conda else Path(args.venv).expanduser().resolve()+ selected_python = args.python or sys.executable+ python = shutil.which(selected_python) or str(Path(selected_python).expanduser().absolute())+ env = clean_environment(venv, conda=args.conda)+ managed = venv / "supra-tex-runtime"+ sources = managed / "sources"+ constraints = managed / "constraints.txt"+ target_python = str(venv / "bin" / "python")+ if args.conda:+ python = target_python+ pip = [target_python, "-I", "-m", "pip", "install", "--no-input"]+ dry = args.dry_run+ print(f"{'DRY RUN: no subprocesses, downloads, or writes.' if dry else 'Installing runtime.'}\nSource: {ROOT}\n{'Conda environment' if args.conda else 'Virtual environment'}: {venv}")+ print("Prerequisites: Linux x86_64; Python 3.10; git; C++ compiler; CUDA toolkit 12.4 nvcc; usable NVIDIA GPU/driver.")- print("Child processes ignore inherited Python overlays and pip configuration/destinations; caches stay in the target environment. Default attention is SDPA; FlashAttention is optional.")++ print("Child processes ignore inherited Python overlays and pip configuration/destinations; caches stay in the target environment. Without FlashAttention, inference uses SDPA; FlashAttention-2/3 is faster.")+ print("Native source pins identify upstream inputs, not verified equivalent binaries. FlexGEMM's install-time cache path is patched in a temporary copy; its original checkout stays unchanged.")+ if not dry:+ for required in (ROOT / "deployment/runtime/requirements-python.txt", ROOT / "deployment/runtime/moge/pyproject.toml", ROOT / "deployment/runtime/utils3d/pyproject.toml", ROOT / "scripts/check_runtime.py"):+ if not required.is_file():+ raise InstallError(f"Incomplete source release: missing {required}")+ env = prerequisites(python, venv, env, conda=args.conda)+ # Check all existing source trees before changing this environment.+ for name, url, revision, _ in SOURCES:+ path = sources / name+ if path.exists():+ validate_checkout(path, url, revision, env)+ if args.conda:+ print("# Install into the active Conda environment.")+ elif not venv.exists():+ run([python, "-I", "-m", "venv", str(venv)], env, dry)+ else:+ print("# Reuse only an isolated Python 3.10 venv; never clear an existing directory.")+ if not dry:+ info = json.loads(capture([target_python, "-I", "-c", PYTHON_PROBE], env))+ validate_target_python(info, venv, conda=args.conda)+ managed.mkdir(parents=True, exist_ok=True)+ sources.mkdir(exist_ok=True)+ constraints.write_text(CONSTRAINTS)+ print(f"# Write {constraints}: torch==2.6.0+cu124; torchvision==0.21.0+cu124")+ run([*pip, *BUILD_TOOLS], env, dry)+ run([*pip, "torch==2.6.0+cu124", "torchvision==0.21.0+cu124", "--index-url", "https://download.pytorch.org/whl/cu124"], env, dry)+ run([*pip, "--constraint", str(constraints), "-r", str(ROOT / "deployment/runtime/requirements-python.txt")], env, dry)+ run([*pip, "--no-build-isolation", "--no-deps", str(ROOT / "deployment/runtime/moge"), str(ROOT / "deployment/runtime/utils3d")], env, dry)+ run([*pip, "--no-build-isolation", "--no-deps", "-e", str(ROOT)], env, dry)+ install_natten(pip, env, dry)+ run([target_python, "-I", "-c", TORCH_PROBE], env, dry)+ for name, url, revision, subdir in SOURCES:+ path = sources / name+ if not path.exists():+ run(["git", "clone", "--no-checkout", url, str(path)], env, dry)+ run(["git", "-C", str(path), "checkout", "--detach", revision], env, dry)+ else:+ print(f"# Verify origin={url}, HEAD={revision}, and clean tracked files: {path}; no reset/clean.")+ run(["git", "-C", str(path), "submodule", "update", "--init", "--recursive"], env, dry)+ flags = None+ if name == "CuMesh":+ print("# CuMesh/cubvh: append --extended-lambda for its CUDA device lambdas without patching source.")+ flags = {"NVCC_APPEND_FLAGS": " ".join(filter(None, (env.get("NVCC_APPEND_FLAGS"), "--extended-lambda")))}+ elif subdir == "o-voxel":+ print("# o-voxel: NVCC_APPEND_FLAGS appends the recorded extended-lambda/half flags without patching source. This build still requires destination validation.")+ flags = {"NVCC_APPEND_FLAGS": " ".join(filter(None, (env.get("NVCC_APPEND_FLAGS"), O_VOXEL_FLAGS)))}+ if name == "FlexGEMM":+ install_flex_gemm(pip, path, managed, env, dry)+ else:+ run([*pip, "--no-build-isolation", "--no-deps", str(path / subdir)], env, dry, flags)+ if args.flash_attn:+ run([*pip, "--no-build-isolation", "--no-deps", "flash-attn==2.8.3"], env, dry)+ run([target_python, "-I", "-c", "import flash_attn; print(flash_attn.__version__)"], env, dry)+ run([target_python, "-I", "-m", "pip", "check"], env, dry)+ run([target_python, "-I", "-c", TORCH_PROBE], env, dry)+ run([target_python, "-I", str(ROOT / "scripts/check_runtime.py"), "--imports-only"], env, dry)+ if dry:+ print("Dry run complete. Prerequisites, builds, and imports have NOT been validated.")+ else:- print(f"Runtime dependency checks passed in {venv}. Model acquisition and an image-to-GLB run are still required for inference acceptance. Use --attention sdpa for the default runtime.")++ print(f"Runtime dependency checks passed in {venv}. Model acquisition and an image-to-GLB run are still required for inference acceptance. FlashAttention-2/3 is faster than SDPA; see docs/installation.md.")+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ destination = parser.add_mutually_exclusive_group()+ destination.add_argument("--conda", action="store_true", help="Install into the active Conda environment (recommended; activate it first)")+ destination.add_argument("--venv", default=".venv", help="Create/reuse an isolated venv instead (default without --conda: .venv)")+ parser.add_argument("--python", help="Python 3.10 executable used to create a venv (default: invoking Python; unavailable with --conda)")+ parser.add_argument("--dry-run", action="store_true", help="Print the complete plan without subprocesses, network, or filesystem writes")+ parser.add_argument("--flash-attn", action="store_true", help="Also build optional FlashAttention 2.8.3; default SDPA needs neither FA2 nor FA3")+ args = parser.parse_args(argv)+ if args.conda and args.python:+ parser.error("--python cannot be combined with --conda; use the active Conda environment's Python.")+ try:+ install(args)+ except (InstallError, OSError, ValueError) as exc:+ print(f"ERROR: {exc}", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --cc scripts/prepare_models.pyindex 91750f2,0000000..7caba90mode 100644,000000..100644--- a/scripts/prepare_models.py+++ b/scripts/prepare_models.py@@@ -1,541 -1,0 +1,552 @@@+#!/usr/bin/env python3+"""Download or bind Supra-Tex models, then publish a portable models.json.++Downloads use the inherited Hugging Face configuration and your existing access.+Local overrides are linked without copying large weights and remain dependencies+of the prepared tree. Cached Hub snapshots are also linked when using an explicit+cache or preparing offline; keep that cache available. No tensor data is loaded+and no checksums are computed.+"""+from __future__ import annotations++import argparse+import copy+import filecmp+import fnmatch+import importlib.util+import json+import os+from pathlib import Path+import shutil+import sys+import tempfile+from urllib.request import urlopen+++ROOT = Path(__file__).resolve().parents[1]+PROJECT_REPO = "supra3d/supra-tex"- COMPLETION_PATTERNS = ["config.json", "partial_normalization.json", "*.safetensors",- "*.safetensors.index.json", "LICENSE*", "README.md"]+MATERIAL_PATTERNS = ["adapter_config.json", "adapter_model.safetensors", "LICENSE*", "Notice", "README.md"]+GEOMETRY_KEYS = ("sparse_structure_flow_model", "sparse_structure_decoder",+ "shape_slat_flow_model_512", "shape_slat_flow_model_1024", "shape_slat_decoder")+VAE_STEMS = ("shape_enc_next_dc_f16c32_fp16", "tex_enc_next_dc_f16c32_fp16",+ "shape_dec_next_dc_f16c32_fp16", "tex_dec_next_dc_f16c32_fp16")+MARKER = ".prepare-models.json"++# Keep setup/help usable without importing the GPU-facing supratex package.+_spec = importlib.util.spec_from_file_location("_supratex_pipeline_config", ROOT / "supratex/pipeline_config.py")+_pipeline = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_pipeline)++_weights_spec = importlib.util.spec_from_file_location("_supratex_prepare_weights", ROOT / "supratex/weights.py")++_weights = importlib.util.module_from_spec(_weights_spec)++_weights_spec.loader.exec_module(_weights)++DEFAULT_COMPLETION_CHECKPOINT = _weights.DEFAULT_COMPLETION_CHECKPOINT++# The release keeps an older sharded model beside the default checkpoint; fetch++# only the default weights.++COMPLETION_PATTERNS = ["config.json", "partial_normalization.json", DEFAULT_COMPLETION_CHECKPOINT,++ "LICENSE*", "README.md"]+relative_name = _pipeline.relative_name+model_source = _pipeline.model_source+++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--repo", default=PROJECT_REPO, help="pipeline release directory or HF repo ID/URL (default: %(default)s)")+ parser.add_argument("--revision", help="project repository revision; defaults to its current main")+ parser.add_argument("--pipeline", type=Path, help="explicit local pipeline.json; otherwise read it from --repo")+ parser.add_argument("--completion-subdir", help="override the completion directory declared by pipeline.json")+ parser.add_argument("--material-subdir", help="override the material directory declared by pipeline.json")+ parser.add_argument("--completion", help="override with standalone completion directory, HF repo ID, or HF URL")+ parser.add_argument("--material", help="override with material adapter directory, HF repo ID, or HF URL")+ parser.add_argument("--completion-revision", help="revision for a separate --completion repository")+ parser.add_argument("--material-revision", help="revision for a separate --material repository")+ parser.add_argument("--output-dir", type=Path, default=ROOT / "ckpts/ready")+ parser.add_argument("--cache-dir", type=Path, help="Hugging Face cache for manifests and model snapshots; prepared files link to this cache, so keep it available")+ for name in ("qwen-base", "geometry", "dino", "vae", "moge", "rmbg", "naf-weights"):+ parser.add_argument("--" + name, type=Path, help="existing local override (no download)")+ parser.add_argument("--with-rmbg", action="store_true", help="also prepare RMBG for RGB inputs; default example uses RGBA")+ parser.add_argument("--local-files-only", action="store_true", help="use local files and cached Hub snapshots; never download")+ parser.add_argument("--dry-run", action="store_true", help="offline plan; remote repositories use the bundled pipeline preview")+ return parser.parse_args(argv)+++def local_override(value: Path, *, file_allowed: bool = False) -> dict:+ path = value.expanduser().resolve()+ if not path.exists():+ raise FileNotFoundError(f"local override does not exist: {path}")+ if not path.is_dir() and not (file_allowed and path.is_file()):+ raise ValueError(f"local override must be {'a directory or file' if file_allowed else 'a directory'}: {path}")+ return {"kind": "local", "path": str(path)}+++def build_plan(args: argparse.Namespace, *, resolve_remote: bool = False) -> dict:+ """Build a plan from one pipeline; offline previews never fetch metadata."""+ output = args.output_dir.expanduser().resolve()+ project = model_source(args.repo, args.revision)+ project_needed = [name for name in ("completion", "material") if getattr(args, name) is None]+ if args.pipeline is not None:+ pipeline = _pipeline.load_pipeline(args.pipeline)+ manifest_source = "explicit local pipeline"+ elif project["kind"] == "local":+ pipeline, project = _pipeline.resolve_pipeline(args.repo)+ manifest_source = "local release"+ elif resolve_remote and (project_needed or args.repo != PROJECT_REPO or args.revision):+ pipeline, project = _pipeline.resolve_pipeline(+ args.repo, revision=args.revision, cache_dir=args.cache_dir, local_files_only=args.local_files_only)+ manifest_source = "Hub pipeline at selected revision"+ else:+ pipeline = _pipeline.load_pipeline(ROOT / "configs/pipeline.json")+ manifest_source = "bundled preview; Hub pipeline is resolved before preparation" if project_needed else "bundled pipeline"+ manifest = pipeline["external_models"]+ operations, models = [], {}+ subdirs = {name: relative_name(getattr(args, name + "_subdir") or pipeline["models"][name])+ for name in ("completion", "material")}+ patterns = {"completion": COMPLETION_PATTERNS, "material": MATERIAL_PATTERNS}+ if project_needed and project["kind"] == "hub":+ operations.append(dict(project, name="project", destination="project",+ allow_patterns=["pipeline.json", "README.md", ".gitattributes"] ++ [f"{subdirs[name]}/{pattern}" for name in project_needed for pattern in patterns[name]]))+ for name in subdirs:+ value = getattr(args, name)+ if value is None:+ if project["kind"] == "local":+ models[name] = local_override(Path(project["path"]) / subdirs[name])+ else:+ models[name] = {"kind": "prepared", "path": f"project/{subdirs[name]}"}+ else:+ source = model_source(value, getattr(args, name + "_revision"))+ models[name] = source if source["kind"] == "local" else {"kind": "prepared", "path": name}+ if source["kind"] == "hub":+ operations.append(dict(source, name=name, destination=name, allow_patterns=patterns[name]))+ for key, flag in (("qwen-base", "qwen_base"), ("geometry", "geometry"), ("dino", "dino"),+ ("vae", "vae"), ("moge2", "moge"), ("rmbg2", "rmbg")):+ override = getattr(args, flag)+ if key == "rmbg2" and override is None and not args.with_rmbg:+ continue+ if override is not None:+ models[key] = local_override(override, file_allowed=key == "moge2")+ else:+ entry = manifest[key]+ destination = f"external/{key}"+ operations.append({"name": key, "kind": "hub", "repo_id": entry["repo_id"],+ "revision": entry["revision"], "allow_patterns": entry["allow_patterns"],+ "gated": entry.get("gated", False), "destination": destination})+ models[key] = {"kind": "prepared", "path": destination}+ if args.naf_weights is not None:+ models["naf"] = local_override(args.naf_weights, file_allowed=True)+ else:+ entry = manifest["naf"]+ destination = "external/naf/" + entry["filename"]+ operations.append({"name": "naf", "kind": "url", "url": entry["url"], "destination": destination})+ models["naf"] = {"kind": "prepared", "path": destination}+ for operation in operations:+ if args.local_files_only:+ operation["local_files_only"] = True+ if args.cache_dir is not None and operation["kind"] == "hub":+ operation["cache_dir"] = str(args.cache_dir.expanduser().resolve())+ return {"schema_version": 1, "output_dir": str(output), "downloads": operations, "models": models,+ "cache_dir": str(args.cache_dir.expanduser().resolve()) if args.cache_dir is not None else None,+ "local_files_only": args.local_files_only,+ "pipeline": pipeline, "pipeline_source": manifest_source,+ "bindings": {"geometry": "geometry/pipeline.json + five config/weight pairs + dino",+ "pipeline_source": "local geometry pipeline.json or deployment/runtime/geometry/pipeline.json",+ "vae": "all four encoder/decoder config/weight pairs under upstream ckpts/",+ "naf_source": "torch/hub/valeoai_NAF_main -> deployment/runtime/naf",+ "naf_weights": "torch/hub/checkpoints/naf_release.pth",+ "config": "models.json (generated paths and selected pipeline defaults)"},+ "access": "Gated repositories require your existing upstream permission and local HF authentication. HF_ENDPOINT is inherited.",+ "local_override_note": "Local overrides remain external dependencies; their absolute paths/links are intentionally machine-local."}+++def require_file(path: Path) -> Path:+ if not path.is_file() or path.stat().st_size == 0:+ raise FileNotFoundError(f"required model file is missing or empty: {path}")+ return path+++def check_index(path: Path) -> None:+ index = json.loads(require_file(path).read_text())+ mapping = index.get("weight_map")+ if not isinstance(mapping, dict) or not mapping:+ raise ValueError(f"checkpoint index requires a nonempty weight_map: {path}")+ for filename in set(mapping.values()):+ relative_name(filename)+ if not filename.endswith(".safetensors"):+ raise ValueError(f"index shard must be .safetensors: {filename}")+ require_file(path.parent / filename)+++def check_safe_weights(directory: Path, single: str = "model.safetensors") -> Path:+ index = directory / (single + ".index.json")+ weights = directory / single+ if index.is_file() and weights.is_file():+ raise ValueError(f"ambiguous single and sharded weights: {directory}")+ if index.is_file():+ check_index(index)+ return index+ return require_file(weights)++++def completion_checkpoint(directory: Path) -> Path:++ """Prefer the default completion weights; fall back to model.safetensors or its shards."""++ default = directory / DEFAULT_COMPLETION_CHECKPOINT++ return default if default.is_file() else check_safe_weights(directory)+++++def validate_inputs(paths: dict[str, Path]) -> tuple[dict, Path]:+ # Load the path-only helper directly: package __init__ imports GPU-facing+ # modules, and resolve_completion_artifacts performs deeper ABI validation.- spec = importlib.util.spec_from_file_location("_supratex_prepare_weights", ROOT / "supratex/weights.py")- module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)+ for key in ("completion", "material"):- module.resolve_model_dir(paths[key], local_files_only=True)++ _weights.resolve_model_dir(paths[key], local_files_only=True)+ completion = json.loads(require_file(paths["completion"] / "config.json").read_text())+ if completion.get("format") != "supratex_completion" or completion.get("schema_version") != 1:+ raise ValueError("completion requires the standalone Supra-Tex config.json (schema_version 1)")+ require_file(paths["completion"] / "partial_normalization.json")- checkpoint = check_safe_weights(paths["completion"])++ checkpoint = completion_checkpoint(paths["completion"])+ adapter = json.loads(require_file(paths["material"] / "adapter_config.json").read_text())+ if adapter.get("format") != "supratex_qwen_material_adapter" or adapter.get("weight_file") != "adapter_model.safetensors":+ raise ValueError("material requires the standalone Supra-Tex adapter_config.json and adapter_model.safetensors")+ require_file(paths["material"] / "adapter_model.safetensors")+ for name in ("preprocessor_config.json", "tokenizer_config.json", "tokenizer.json", "chat_template.jinja"):+ require_file(paths["qwen-base"] / "processor" / name)+ for name in ("vae", "text_encoder", "transformer"):+ component = paths["qwen-base"] / name+ require_file(component / "config.json")+ weights = list(component.glob("*.safetensors"))+ if not weights:+ raise FileNotFoundError(f"Qwen foundation component has no weights: {component}")+ for weight in weights:+ require_file(weight)+ for index in component.glob("*.safetensors.index.json"):+ check_index(index)+ # The geometry extractors normalize images directly and load only DINO's+ # model/config; a Transformers image-processor file is not required.+ require_file(paths["dino"] / "config.json")+ check_safe_weights(paths["dino"])+ if "rmbg2" in paths:- for name in ("config.json", "model.safetensors", "preprocessor_config.json", "BiRefNet_config.py", "birefnet.py"):++ # The foreground adapter normalizes images itself, so RMBG-2.0 and the++ # public BiRefNet release share this layout without an image processor.++ for name in ("config.json", "model.safetensors", "BiRefNet_config.py", "birefnet.py"):+ require_file(paths["rmbg2"] / name)+ paths["moge2"] = require_file(paths["moge2"] / "model.pt" if paths["moge2"].is_dir() else paths["moge2"])+ paths["naf"] = require_file(paths["naf"] / "naf_release.pth" if paths["naf"].is_dir() else paths["naf"])+ vae = paths["vae"] / "ckpts" if (paths["vae"] / "ckpts").is_dir() else paths["vae"]+ for stem in VAE_STEMS:+ for suffix in (".json", ".safetensors"):+ require_file(vae / (stem + suffix))+ pipeline_file = paths["geometry"] / "pipeline.json"+ if not pipeline_file.is_file():+ pipeline_file = _pipeline.runtime_root(ROOT) / "geometry/pipeline.json"+ pipeline = json.loads(require_file(pipeline_file).read_text())+ for key in GEOMETRY_KEYS:+ stem = relative_name(pipeline["args"]["models"][key])+ for suffix in (".json", ".safetensors"):+ require_file(paths["geometry"] / (stem + suffix))+ return pipeline, checkpoint+++def write_once(path: Path, text: str) -> None:+ """Accept identical products on retry, never overwrite an existing file."""+ if path.exists() or path.is_symlink():+ if path.is_symlink() or not path.is_file() or path.read_text() != text:+ raise FileExistsError(f"refusing to overwrite conflicting output: {path}")+ return+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("x", encoding="utf-8") as stream:+ stream.write(text)+++def json_text(value: dict) -> str:+ return json.dumps(value, indent=2) + "\n"+++def link_once(destination: Path, source: Path, *, relative: bool) -> None:+ target = os.path.relpath(source, destination.parent) if relative else str(source)+ if destination.is_symlink() and os.readlink(destination) == target:+ return+ if destination.exists() or destination.is_symlink():+ raise FileExistsError(f"refusing to overwrite conflicting output: {destination}")+ destination.parent.mkdir(parents=True, exist_ok=True)+ destination.symlink_to(target, target_is_directory=source.is_dir())+++def bind_cached_snapshot(destination: Path, cached: Path, patterns: list[str]) -> None:+ """Fill missing cached files only after checking every existing destination."""+ if not destination.exists() and not destination.is_symlink():+ link_once(destination, cached, relative=False)+ return+ if destination.is_symlink():+ if destination.resolve() == cached.resolve():+ return+ if not destination.is_dir():+ raise FileExistsError(f"refusing to overwrite conflicting output: {destination}")+ missing = []+ for source in sorted(cached.rglob("*")):+ relative = source.relative_to(cached)+ if not source.is_file() or not any(fnmatch.fnmatch(relative.as_posix(), pattern) for pattern in patterns):+ continue+ target = destination / relative+ parent = target.parent+ while parent != destination:+ if parent.is_symlink() or (parent.exists() and not parent.is_dir()):+ raise FileExistsError(f"refusing to modify conflicting output: {parent}")+ parent = parent.parent+ if target.exists() or target.is_symlink():+ if not target.is_file() or (not source.samefile(target) and not filecmp.cmp(source, target, shallow=False)):+ raise FileExistsError(f"refusing to overwrite conflicting output: {target}")+ else:+ if destination.is_symlink():+ raise FileExistsError(f"refusing to modify a conflicting cache binding: {destination}")+ missing.append((target, source))+ for target, source in missing:+ link_once(target, source, relative=False)+++def download(operation: dict, output: Path) -> None:+ destination = output / operation["destination"]+ if operation["kind"] == "url":+ if destination.exists():+ require_file(destination)+ return+ if operation.get("local_files_only"):+ raise FileNotFoundError("NAF weights are unavailable offline; supply --naf-weights or prepare them online first")+ destination.parent.mkdir(parents=True, exist_ok=True)+ temporary = destination.with_suffix(".pth.part")+ try:+ with urlopen(operation["url"], timeout=60) as response, temporary.open("wb") as target:+ expected_size = response.headers.get("Content-Length")+ shutil.copyfileobj(response, target)+ require_file(temporary)+ if expected_size is not None and temporary.stat().st_size != int(expected_size):+ raise ValueError("NAF response ended before its declared Content-Length")+ # A same-directory hard link publishes without replacing a file.+ os.link(temporary, destination)+ except Exception as error:+ raise RuntimeError("NAF download failed; retry or supply --naf-weights with the official naf_release.pth") from error+ finally:+ temporary.unlink(missing_ok=True)+ return+ from huggingface_hub import snapshot_download+ try:+ if operation.get("local_files_only"):+ try:+ cached = snapshot_download(repo_id=operation["repo_id"], revision=operation["revision"],+ allow_patterns=operation["allow_patterns"],+ cache_dir=operation.get("cache_dir"), local_files_only=True)+ except Exception:+ if destination.is_dir():+ # Online local_dir downloads may have no shared cache entry.+ # The caller validates all required files before publishing.+ return+ raise+ elif operation.get("cache_dir") is not None:+ # local_dir bypasses the shared cache in huggingface_hub, so an+ # explicit cache must use a snapshot and bind its files afterwards.+ cached = snapshot_download(repo_id=operation["repo_id"], revision=operation["revision"],+ allow_patterns=operation["allow_patterns"],+ cache_dir=operation["cache_dir"])+ else:+ snapshot_download(repo_id=operation["repo_id"], revision=operation["revision"],+ allow_patterns=operation["allow_patterns"], local_dir=str(destination),+ cache_dir=operation.get("cache_dir"))+ except Exception as error:+ status = getattr(getattr(error, "response", None), "status_code", None)+ access = operation.get("gated") or status in (401, 403) or "GatedRepo" in type(error).__name__+ detail = ("This upstream repository requires existing access permission and your own local HF authentication. "+ "Accept its publisher's terms and authenticate with your normal HF tooling, or provide a local override."+ if access else "Check the repository/revision and your network or local HF authentication, then retry.")+ # Do not interpolate exception text: upstream URLs can contain secrets.+ raise RuntimeError(f"Download failed for {operation['repo_id']}. {detail}") from None+ if operation.get("local_files_only") or operation.get("cache_dir") is not None:+ # Keep local conflict errors distinct from remote access failures.+ bind_cached_snapshot(destination, Path(cached), operation["allow_patterns"])+++def plan_identity(plan: dict) -> dict:+ """Transport/cache choices are not part of the prepared model identity."""+ identity = {key: copy.deepcopy(value) for key, value in plan.items()+ if key not in {"output_dir", "pipeline_source", "cache_dir", "local_files_only"}}+ identity["downloads"] = [{key: value for key, value in item.items()+ if key not in {"local_files_only", "cache_dir"}}+ for item in plan["downloads"]]+ return identity+++def without_rmbg(identity: dict) -> dict:+ identity = copy.deepcopy(identity)+ identity["models"].pop("rmbg2", None)+ identity["downloads"] = [item for item in identity["downloads"] if item["name"] != "rmbg2"]+ return identity+++def replace_owned_json(path: Path, value: dict, previous: dict, *, check_only: bool = False) -> None:+ """Atomically extend a generated file, rejecting user edits and symlinks."""+ text = json_text(value)+ if not path.exists() and not path.is_symlink():+ if not check_only:+ write_once(path, text)+ return+ if path.is_symlink() or not path.is_file() or path.read_text() not in {json_text(previous), text}:+ raise FileExistsError(f"refusing to overwrite conflicting output: {path}")+ if check_only or path.read_text() == text:+ return+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, prefix="." + path.name + ".", delete=False) as stream:+ temporary = Path(stream.name)+ try:+ stream.write(text)+ stream.close()+ os.replace(temporary, path)+ finally:+ temporary.unlink(missing_ok=True)+++def prepare(plan: dict) -> Path:+ plan = copy.deepcopy(plan)+ output = Path(plan["output_dir"])+ marker = output / MARKER+ if output.exists() and not output.is_dir():+ raise NotADirectoryError(output)+ if output.is_dir() and any(output.iterdir()) and not marker.is_file():+ raise FileExistsError(f"output directory is not owned by prepare_models.py; choose an empty --output-dir: {output}")+ previous = None+ identity = plan_identity(plan)+ if marker.exists():+ if marker.is_symlink():+ raise FileExistsError(f"refusing to overwrite conflicting output: {marker}")+ previous = json.loads(marker.read_text())+ if without_rmbg(previous) != without_rmbg(identity):+ raise FileExistsError(f"refusing to overwrite conflicting output: {marker}")+ if "rmbg2" in previous["models"]:+ old_downloads = [item for item in previous["downloads"] if item["name"] == "rmbg2"]+ if "rmbg2" in identity["models"]:+ new_downloads = [item for item in identity["downloads"] if item["name"] == "rmbg2"]+ if identity["models"]["rmbg2"] != previous["models"]["rmbg2"] or old_downloads != new_downloads:+ raise FileExistsError(f"refusing to overwrite conflicting output: {marker}")+ else:+ # Keep an existing optional dependency when switching to RGBA.+ plan["models"] = {**previous["models"], **plan["models"]}+ for operation in old_downloads:+ operation = copy.deepcopy(operation)+ if plan.get("local_files_only") or any(item.get("local_files_only") for item in plan["downloads"]):+ operation["local_files_only"] = True+ if plan.get("cache_dir") is not None:+ operation["cache_dir"] = plan["cache_dir"]+ position = next(index for index, item in enumerate(previous["downloads"]) if item["name"] == "rmbg2")+ plan["downloads"].insert(position, operation)+ identity = plan_identity(plan)+ else:+ write_once(marker, json_text(identity))+ paths = {name: Path(source["path"]) if source["kind"] == "local" else output / source["path"]+ for name, source in plan["models"].items()}+ existing_inputs_complete = False+ if any(operation.get("local_files_only") for operation in plan["downloads"]):+ try:+ validate_inputs(dict(paths))+ existing_inputs_complete = True+ except (OSError, ValueError, KeyError):+ pass+ # Check publisher-controlled access before downloading the large public bases.+ for operation in sorted(plan["downloads"], key=lambda item: not item.get("gated", False)):+ if operation.get("local_files_only") and existing_inputs_complete:+ continue+ download(operation, output)+ pipeline, checkpoint = validate_inputs(paths)+ geometry = output / "geometry"+ for key in GEOMETRY_KEYS:+ stem = pipeline["args"]["models"][key]+ write_once(geometry / (stem + ".json"), (paths["geometry"] / (stem + ".json")).read_text())+ link_once(geometry / (stem + ".safetensors"), paths["geometry"] / (stem + ".safetensors"),+ relative=plan["models"]["geometry"]["kind"] != "local")+ write_once(geometry / "pipeline.json", json_text(pipeline))+ link_once(geometry / "dino", paths["dino"], relative=plan["models"]["dino"]["kind"] != "local")+ runtime = _pipeline.runtime_root(ROOT)+ require_file(runtime / "naf/hubconf.py")+ link_once(output / "torch/hub/valeoai_NAF_main", runtime / "naf", relative=True)+ link_once(output / "torch/hub/checkpoints/naf_release.pth", paths["naf"], relative=plan["models"]["naf"]["kind"] != "local")++ def config_path(path: Path, local: bool = False) -> str:+ return str(path) if local else os.path.relpath(path, output)++ def model_path(name: str) -> str:+ return config_path(paths[name], plan["models"][name]["kind"] == "local")++ local_names = [key for key, value in plan["models"].items() if value["kind"] == "local"]+ config = {"moge_model": model_path("moge2"), "rmbg_model": model_path("rmbg2") if "rmbg2" in paths else None,+ "geometry_package": config_path(runtime / "geometry"), "geometry_model": "geometry",+ "qwen_runtime": config_path(runtime / "qwen"),+ "material_base": model_path("qwen-base"), "material_model": model_path("material"),+ "pretrained": model_path("completion"), "torch_home": "torch", "trellis_root": model_path("vae"),+ "model_config": config_path(paths["completion"] / "config.json", "completion" in local_names),+ "checkpoint": config_path(checkpoint, "completion" in local_names),+ "defaults": plan["pipeline"]["defaults"],+ "_meta": {"schema_version": 1, "local_overrides": local_names,+ "portability": "Relative paths resolve from models.json. Move with the source package; local overrides remain external dependencies.",+ "validation": "File presence and shard inventory only; run scripts/check_runtime.py before inference."}}+ result = output / "models.json"+ if "rmbg2" in identity["models"]:+ old_config = copy.deepcopy(config)+ old_config["rmbg_model"] = None+ old_config["_meta"]["local_overrides"] = [name for name in old_config["_meta"]["local_overrides"] if name != "rmbg2"]+ # Check for user edits before recording the extension. Recording the+ # dependency first lets either input type recover an interrupted publish.+ replace_owned_json(result, config, old_config, check_only=True)+ if previous is not None and previous != identity:+ replace_owned_json(marker, identity, previous)+ replace_owned_json(result, config, old_config)+ else:+ write_once(result, json_text(config))+ return result+++def prepare_pipeline(source: str | Path, *, output_dir: str | Path | None = None,+ revision: str | None = None, cache_dir: str | Path | None = None,+ local_files_only: bool = False,+ with_rmbg: bool = False, overrides: dict | None = None) -> Path:+ """Resolve a release and generate the runtime bindings used by inference."""+ source = Path(source).expanduser().absolute() if isinstance(source, Path) else source+ # A manifest filename denotes its release root as well as the selected config.+ local = Path(source).expanduser()+ manifest_file = local.is_file() or (not str(source).startswith(("https://", "hf://")) and local.suffix == ".json")+ argv = ["--repo", str(local.absolute().parent if manifest_file else source)]+ if manifest_file:+ argv.extend(("--pipeline", str(local)))+ if output_dir is not None:+ argv.extend(("--output-dir", str(output_dir)))+ if revision is not None:+ argv.extend(("--revision", revision))+ if cache_dir is not None:+ argv.extend(("--cache-dir", str(cache_dir)))+ if local_files_only:+ argv.append("--local-files-only")+ if with_rmbg:+ argv.append("--with-rmbg")+ flags = {"completion": "completion", "material": "material", "qwen-base": "qwen-base",+ "geometry": "geometry", "dino": "dino", "vae": "vae", "moge2": "moge",+ "rmbg2": "rmbg", "naf": "naf-weights",+ "completion_revision": "completion-revision", "material_revision": "material-revision"}+ for key, value in (overrides or {}).items():+ if key not in flags:+ raise ValueError(f"unknown pipeline model override: {key}")+ argv.extend(("--" + flags[key], str(value)))+ return prepare(build_plan(parse_args(argv), resolve_remote=True))+++def main(argv: list[str] | None = None) -> int:+ args = parse_args(argv)+ try:+ plan = build_plan(args, resolve_remote=not args.dry_run)+ if args.dry_run:+ print(json_text(plan), end="")+ else:+ result = prepare(plan)+ print(f"Prepared {result}")+ if any(value["kind"] == "local" for value in plan["models"].values()):+ print("Local overrides remain external dependencies; keep their original paths available.")+ print(f"Next: python scripts/check_runtime.py --config {result}")+ except (OSError, ValueError, KeyError, RuntimeError) as error:+ print(f"error: {error}", file=sys.stderr)+ return 2+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --cc scripts/run_example.pyindex c505959,0000000..1346b21mode 100644,000000..100644--- a/scripts/run_example.py+++ b/scripts/run_example.py@@@ -1,148 -1,0 +1,154 @@@+#!/usr/bin/env python3+"""Run the bundled RGBA example with prepared models and an isolated source path."""+from __future__ import annotations++import argparse+import importlib.util+import json+import os+from pathlib import Path+import shlex+import subprocess+import sys++ROOT = Path(__file__).resolve().parents[1]+MODEL_KEYS = ("moge_model", "rmbg_model", "geometry_package", "geometry_model", "qwen_runtime",+ "qwen_deps", "material_base", "material_model", "pretrained", "model_config", "checkpoint", "trellis_root")+PATH_KEYS = (*MODEL_KEYS, "torch_home")+++def _pipeline_config():+ """Load the lightweight shared helpers without importing GPU model modules."""+ spec = importlib.util.spec_from_file_location("supratex_pipeline_config", ROOT / "supratex/pipeline_config.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def inference_defaults(config: dict | None = None) -> dict:+ """Read defaults from the pipeline without importing GPU model modules."""+ module = _pipeline_config()+ defaults = module.default_pipeline()["defaults"]+ configured = (config or {}).get("defaults", {})+ if not isinstance(configured, dict):+ raise ValueError("models.json defaults must contain an object")+ defaults.update(configured)+ return module.validate_defaults(defaults)+++def read_config(path: Path) -> dict:+ """Resolve paths relative to models.json, preserving metadata for preflight."""+ path = Path(path).expanduser().resolve()+ config = json.loads(path.read_text())+ if not isinstance(config, dict):+ raise ValueError("models.json must contain an object")+ for key in PATH_KEYS:+ value = config.get(key)+ if value is None and key in ("rmbg_model", "qwen_deps", "model_config", "checkpoint"):+ continue+ if not isinstance(value, str) or not value:+ raise ValueError(f"models.json requires a nonempty {key} path")+ resolved = Path(value).expanduser()+ config[key] = str(resolved if resolved.is_absolute() else (path.parent / resolved).resolve())+ return config+++def parse_args(argv: list[str] | None = None) -> tuple[argparse.Namespace, list[str]]:+ parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)+ parser.add_argument("--config", type=Path, default=ROOT / "ckpts/ready/models.json")- parser.add_argument("--input", type=Path, help="default: bundled assets/pitcher_plant.png")++ parser.add_argument("--input", type=Path, help="default: assets/spiny_whelk_shell.png, or "++ "assets/cinema_signage.png with --dual-view")+ parser.add_argument("--output", type=Path, required=True, help="destination .glb")+ parser.add_argument("--use-input-alpha", action="store_true", help="explicitly require the input foreground alpha")+ parser.add_argument("--attention", choices=("auto", "flash_attn_3", "flash_attn", "sdpa", "xformers"),+ help="override the prepared pipeline's attention default")+ parser.add_argument("--low-vram", action=argparse.BooleanOptionalAction, default=None)+ parser.add_argument("--print-command", action="store_true", help="print without creating files or launching inference")+ args, extra = parser.parse_known_args(argv)+ if extra[:1] == ["--"]:+ extra = extra[1:]+ protected = {"--" + key.replace("_", "-") for key in MODEL_KEYS}+ protected.update(("--material-backend", "--local-files-only", "--cache-dir", "--revision", "--material-revision", "--geometry-revision",+ "--pipeline", "--pipeline-revision", "--models-dir"))+ if any(value.split("=", 1)[0] in protected for value in extra):+ parser.error("model paths and offline settings come from --config; additional arguments cannot override them")+ return args, extra+++def has_foreground_alpha(path: Path) -> bool:+ from PIL import Image+ with Image.open(path) as image:+ # The inference foreground contract accepts only an actual RGBA+ # input; converting LA or palette transparency here would hide a+ # mode that the inference process itself rejects.+ if image.mode != "RGBA":+ return False+ low, high = image.getchannel("A").getextrema()+ return low < 255 and high > 0++++def default_input(dual_view: bool) -> Path:++ """Bundled example: the whelk shell, or the cinema signage for dual-view."""++ return ROOT / "assets" / ("cinema_signage.png" if dual_view else "spiny_whelk_shell.png")+++++def build_command(args: argparse.Namespace, extra: list[str], config: dict) -> tuple[list[str], dict[str, str]]:+ defaults = inference_defaults(config)+ attention = args.attention or defaults["attention"]- image = (args.input or ROOT / "assets/pitcher_plant.png").expanduser().resolve()++ image = (args.input or default_input("--dual-view" in extra)).expanduser().resolve()+ if not image.is_file():+ raise FileNotFoundError(f"input image is missing: {image}")- use_alpha = args.use_input_alpha or args.input is None or has_foreground_alpha(image)++ use_alpha = args.use_input_alpha or has_foreground_alpha(image)+ if not use_alpha and not config.get("rmbg_model"):+ raise ValueError("RGB or opaque input requires RMBG: prepare with --with-rmbg or --rmbg, then use that models.json")+ command = [sys.executable, str(ROOT / "infer.py"), "--input", str(image), "--output",+ str(args.output.expanduser().resolve()), "--material-backend", "qwen-image", "--local-files-only",+ "--attention", attention]+ for key in ("seed", "texture_size", "decimation_target", "texture_format"):+ command.extend(("--" + key.replace("_", "-"), str(defaults[key])))+ if use_alpha:+ command.append("--use-input-alpha")+ if args.low_vram is not None:+ command.append("--low-vram" if args.low_vram else "--no-low-vram")+ for key in MODEL_KEYS:+ if config.get(key):+ command.extend(("--" + key.replace("_", "-"), config[key]))+ command.extend(extra)+ return command, runtime_environment(config, attention)+++def runtime_environment(config: dict, attention: str) -> dict[str, str]:+ """Use prepared caches and bundled sources consistently in both entrypoints."""+ runtime = _pipeline_config().runtime_root(ROOT)+ environment = os.environ.copy()+ environment.update(TORCH_HOME=config["torch_home"], HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1",+ HF_DATASETS_OFFLINE="1", PYTHONNOUSERSITE="1",+ PYTHONPATH=os.pathsep.join(str(path) for path in+ (ROOT, runtime / "moge", runtime / "utils3d")))+ if attention == "auto":+ environment.pop("ATTN_BACKEND", None)+ environment.pop("SPARSE_ATTN_BACKEND", None)+ else:+ environment.update(ATTN_BACKEND=attention, SPARSE_ATTN_BACKEND=attention)+ environment.setdefault("OMP_NUM_THREADS", "4")+ environment.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")+ return environment+++def main(argv: list[str] | None = None) -> int:+ args, extra = parse_args(argv)+ try:+ command, environment = build_command(args, extra, read_config(args.config))+ if args.print_command:+ print(shlex.join(command))+ return 0+ args.output.expanduser().resolve().parent.mkdir(parents=True, exist_ok=True)+ subprocess.run(command, cwd=ROOT, env=environment, check=True)+ except (OSError, ValueError, subprocess.CalledProcessError) as error:+ print(f"error: {error}", file=sys.stderr)+ return 2+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --cc supratex/frontend/material_model/runtime/pbr/conditioning.pyindex a42cc6a,0000000..2f7b8c2mode 100644,000000..100644--- a/supratex/frontend/material_model/runtime/pbr/conditioning.py+++ b/supratex/frontend/material_model/runtime/pbr/conditioning.py@@@ -1,178 -1,0 +1,178 @@@+# Adapted for SUPRA-Tex distribution (2026): packaged local inference runtime.- # Upstream FireRed portions remain under Apache-2.0; see LICENSE.++# Upstream FireRed portions remain under Apache-2.0; see THIRD_PARTY_NOTICES.md.+# Copyright (c) 2025 FireRed-Image-Edit. All rights reserved.+"""Image preprocessing and prompt conditioning for material inference."""+from __future__ import annotations++import math+from typing import List, Tuple++from PIL import Image+import torch+from torchvision import transforms+++DEFAULT_SYSTEM_PROMPT = "Describe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate."++DEFAULT_SYSTEM_PROMPT_T2I = "Describe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:"++ASPECT_RATIO_512 = {+ '0.25': [256.0, 1024.0], '0.26': [256.0, 992.0], '0.27': [256.0, 960.0], '0.28': [256.0, 928.0],+ '0.32': [288.0, 896.0], '0.33': [288.0, 864.0], '0.35': [288.0, 832.0], '0.4': [320.0, 800.0],+ '0.42': [320.0, 768.0], '0.48': [352.0, 736.0], '0.5': [352.0, 704.0], '0.52': [352.0, 672.0],+ '0.57': [384.0, 672.0], '0.6': [384.0, 640.0], '0.68': [416.0, 608.0], '0.72': [416.0, 576.0],+ '0.78': [448.0, 576.0], '0.82': [448.0, 544.0], '0.88': [480.0, 544.0], '0.94': [480.0, 512.0],+ '1.0': [512.0, 512.0], '1.07': [512.0, 480.0], '1.13': [544.0, 480.0], '1.21': [544.0, 448.0],+ '1.29': [576.0, 448.0], '1.38': [576.0, 416.0], '1.46': [608.0, 416.0], '1.67': [640.0, 384.0],+ '1.75': [672.0, 384.0], '2.0': [704.0, 352.0], '2.09': [736.0, 352.0], '2.4': [768.0, 320.0],+ '2.5': [800.0, 320.0], '2.89': [832.0, 288.0], '3.0': [864.0, 288.0], '3.11': [896.0, 288.0],+ '3.62': [928.0, 256.0], '3.75': [960.0, 256.0], '3.88': [992.0, 256.0], '4.0': [1024.0, 256.0]+}++CONDITION_IMAGE_SIZE = 384 * 384+++def calculate_shift(+ image_seq_len,+ base_seq_len: int = 256,+ max_seq_len: int = 4096,+ base_shift: float = 0.5,+ max_shift: float = 1.15,+):+ """根据图像序列长度计算 flow 的 shift 系数(线性插值)。"""+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)+ b = base_shift - m * base_seq_len+ mu = image_seq_len * m + b+ return mu++def get_embedding(source_exist, instructions, source_images, processor, text_encoder):+ def _extract_valid_hidden_states(+ hidden_states: torch.Tensor,+ attention_mask: torch.Tensor,+ ):+ batch_size = hidden_states.shape[0]+ valid_hidden_states = []+ for i in range(batch_size):+ valid_indices = attention_mask[i].nonzero(as_tuple=True)[0]+ valid_hidden_states.append(hidden_states[i][valid_indices])+ return valid_hidden_states++ with torch.no_grad():+ conversations = []+ if not source_exist:+ source_images = [[] for _ in range(len(instructions))]+ for instruction, source_images_sample in zip(instructions, source_images):+ system_prompt = DEFAULT_SYSTEM_PROMPT_T2I if not source_exist else DEFAULT_SYSTEM_PROMPT+ messages = [+ {"role": "system", "content": [{"type": "text", "text": system_prompt}]},+ {"role": "user", "content": []},+ ]+ for condition_image in source_images_sample:+ messages[1]["content"].append({"type": "image", "image": condition_image})+ messages[1]["content"].append({"type": "text", "text": instruction})+ conversations.append(messages)++ batch_inputs = processor.apply_chat_template(+ conversations,+ add_generation_prompt=True,+ padding=True,+ tokenize=True,+ return_tensors="pt",+ return_dict=True,+ ).to(text_encoder.device)++ encoder_hidden_states = text_encoder(+ input_ids=batch_inputs["input_ids"],+ attention_mask=batch_inputs["attention_mask"],+ pixel_values=batch_inputs["pixel_values"] if source_exist else None,+ image_grid_thw=batch_inputs["image_grid_thw"] if source_exist else None,+ output_hidden_states=True,+ )++ hidden_states = encoder_hidden_states.hidden_states[-1]+ split_hidden_states = _extract_valid_hidden_states(hidden_states, batch_inputs["attention_mask"])+ start_idx = 64 if source_exist else 34+ split_hidden_states = [e[start_idx:] for e in split_hidden_states]+ attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states]+ max_seq_len = max([e.size(0) for e in split_hidden_states])+ prompt_embeds = torch.stack(+ [torch.cat([u, u.new_zeros(max_seq_len - u.size(0), u.size(1))]) for u in split_hidden_states]+ )+ encoder_attention_mask = torch.stack(+ [torch.cat([u, u.new_zeros(max_seq_len - u.size(0))]) for u in attn_mask_list]+ )++ return prompt_embeds, encoder_attention_mask++def get_closest_ratio(height: float, width: float, ratios: dict = ASPECT_RATIO_512) -> Tuple[List[float], float]:+ aspect_ratio = height / width+ closest_ratio = min(ratios.keys(), key=lambda r: abs(float(r) - aspect_ratio))+ return ratios[closest_ratio], float(closest_ratio)++def calculate_dimensions(target_area: float, ratio: float) -> Tuple[int, int]:+ width = math.sqrt(target_area * ratio)+ height = width / ratio+ width = round(width / 32) * 32+ height = round(height / 32) * 32+ return int(width), int(height)++def resize_source_images_for_condition(+ source_images_list: List[List[Image.Image]],+ ref_height: int,+ ref_width: int,+ image_sample_size: int,+ condition_image_size: int = CONDITION_IMAGE_SIZE,+) -> List[List[Image.Image]]:+ """+ 对送入 text_encoder 的 source 图像做 Resize + CenterCrop,再缩放到 condition_image_size 对应尺寸。+ 参考尺寸为 (ref_height, ref_width)。source_images_list: 每样本多张 source 图的 list of list of PIL。+ 返回相同结构的 list of list of PIL Image。+ """+ if not source_images_list:+ return source_images_list+ return [+ apply_condition_transform_to_images(sample, ref_height, ref_width, image_sample_size, condition_image_size)+ for sample in source_images_list+ ]++def apply_condition_transform_to_images(+ images: List[Image.Image],+ ref_height: int,+ ref_width: int,+ image_sample_size: int,+ condition_image_size: int = CONDITION_IMAGE_SIZE,+) -> List[Image.Image]:+ """+ 对多张图像应用统一的 Resize+CenterCrop+最终缩放。参考尺寸 (ref_height, ref_width)。+ 返回与 images 等长的 list of PIL Image。+ """+ if not images:+ return []+ h, w = float(ref_height), float(ref_width)+ aspect_ratio_sample_size = {+ k: [x / 512 * image_sample_size for x in ASPECT_RATIO_512[k]]+ for k in ASPECT_RATIO_512+ }+ closest_size, _ = get_closest_ratio(h, w, ratios=aspect_ratio_sample_size)+ closest_size = [int(x / 16) * 16 for x in closest_size]+ closest_size = list(map(int, closest_size))+ if closest_size[0] / h > closest_size[1] / w:+ resize_size = (closest_size[0], int(w * closest_size[0] / h))+ else:+ resize_size = (int(h * closest_size[1] / w), closest_size[1])++ source_transform = transforms.Compose([+ transforms.Resize(resize_size, interpolation=transforms.InterpolationMode.BILINEAR),+ transforms.CenterCrop(closest_size),+ ])++ result = []+ for im in images:+ if im.mode != "RGB":+ im = im.convert("RGB")+ cropped = source_transform(im)+ width_c, height_c = cropped.size+ aspect_ratio = width_c / height_c+ new_width, new_height = calculate_dimensions(condition_image_size, aspect_ratio)+ result.append(cropped.resize((new_width, new_height), Image.Resampling.LANCZOS))+ return resultdiff --cc supratex/frontend/material_model/runtime/pbr/model_loading.pyindex 8f79c91,0000000..6fd1b36mode 100644,000000..100644--- a/supratex/frontend/material_model/runtime/pbr/model_loading.py+++ b/supratex/frontend/material_model/runtime/pbr/model_loading.py@@@ -1,136 -1,0 +1,136 @@@+# Adapted for SUPRA-Tex distribution (2026): packaged local inference runtime.- # Upstream FireRed portions remain under Apache-2.0; see LICENSE.++# Upstream FireRed portions remain under Apache-2.0; see THIRD_PARTY_NOTICES.md.+# Copyright (c) 2025 FireRed-Image-Edit. All rights reserved.+"""Strict checkpoint loading for the FireRed material inference model."""+from __future__ import annotations++import logging+from pathlib import Path++import torch++logger = logging.getLogger(__name__)+JOINT_MODULE_PREFIX = "modality_joint_blocks."+++def _require_exact_loading_info(loading_info, source: str) -> None:+ problems = {+ name: list(loading_info.get(name, []))+ for name in ("missing_keys", "unexpected_keys", "mismatched_keys", "error_msgs")+ if loading_info.get(name)+ }+ if problems:+ summary = ", ".join(f"{name}={len(values)}" for name, values in problems.items())+ raise RuntimeError(f"{source} transformer load is not exact: {summary}")++def _load_base_transformer(args, weight_dtype, *, use_layer3d_rope: bool = False):+ from .qwen_pbr_factorized import (+ PRODUCTION_JOINT_HEADS,+ PRODUCTION_JOINT_MODALITIES,+ PRODUCTION_JOINT_RANK,+ QwenImagePBRFactorizedTransformer2DModel,+ )++ loaded = QwenImagePBRFactorizedTransformer2DModel.from_pretrained(+ args.pretrained_model_name_or_path,+ subfolder="transformer",+ torch_dtype=weight_dtype,+ joint_sites=(),+ joint_modalities=PRODUCTION_JOINT_MODALITIES,+ joint_rank=PRODUCTION_JOINT_RANK,+ joint_heads=PRODUCTION_JOINT_HEADS,+ use_layer3d_rope=use_layer3d_rope,+ output_loading_info=True,+ )+ if not isinstance(loaded, tuple) or len(loaded) != 2:+ raise RuntimeError("custom transformer loader did not return loading information")+ transformer, loading_info = loaded+ _require_exact_loading_info(loading_info, "base")+ if tuple(transformer.joint_sites):+ raise RuntimeError("base transformer must load without joint modules")+ return transformer++def _resolve_full_transformer_checkpoint(path: str | Path) -> Path:+ checkpoint = Path(path)+ if checkpoint.is_dir():+ checkpoint = checkpoint / "diffusion_pytorch_model.safetensors"+ if not checkpoint.is_file():+ raise FileNotFoundError(f"full transformer checkpoint not found: {checkpoint}")+ return checkpoint++def _load_checkpoint_state(path: Path):+ if path.suffix == ".safetensors":+ from safetensors.torch import load_file++ state = load_file(str(path), device="cpu")+ else:+ state = torch.load(str(path), map_location="cpu", weights_only=True)+ if isinstance(state, dict) and "state_dict" in state:+ state = state["state_dict"]+ if not isinstance(state, dict):+ raise ValueError(f"transformer checkpoint must contain a state dict: {path}")+ return state++def _load_exact_full_transformer(+ transformer,+ checkpoint_path: str | Path,+ *,+ allow_joint_sidecar: bool = False,+) -> None:+ path = _resolve_full_transformer_checkpoint(checkpoint_path)+ state = _load_checkpoint_state(path)+ if allow_joint_sidecar:+ state = {+ name: value+ for name, value in state.items()+ if not name.startswith(JOINT_MODULE_PREFIX)+ }+ result = transformer.load_state_dict(state, strict=False)+ if result.missing_keys or result.unexpected_keys:+ raise RuntimeError(+ "full transformer checkpoint load is not exact: "+ f"missing_keys={len(result.missing_keys)}, "+ f"unexpected_keys={len(result.unexpected_keys)}"+ )+ logger.info( "Loaded exact full transformer checkpoint: %s", path)++def _resolve_joint_adapter_checkpoint(path: str | Path) -> Path:+ checkpoint = Path(path)+ if checkpoint.is_dir():+ checkpoint = checkpoint / "joint_adapter.safetensors"+ if not checkpoint.is_file():+ raise FileNotFoundError(f"joint adapter checkpoint not found: {checkpoint}")+ return checkpoint++def _load_exact_joint_adapter(transformer, checkpoint_path: str | Path) -> None:+ path = _resolve_joint_adapter_checkpoint(checkpoint_path)+ state = _load_checkpoint_state(path)+ expected = {+ name: parameter+ for name, parameter in transformer.named_parameters()+ if name.startswith(JOINT_MODULE_PREFIX)+ }+ actual_keys = set(state)+ expected_keys = set(expected)+ if actual_keys != expected_keys:+ missing = sorted(expected_keys - actual_keys)+ unexpected = sorted(actual_keys - expected_keys)+ raise RuntimeError(+ "joint adapter checkpoint is not exact: "+ f"missing={missing[:3]}, unexpected={unexpected[:3]}"+ )+ mismatched = [+ name+ for name, parameter in expected.items()+ if not isinstance(state[name], torch.Tensor)+ or tuple(state[name].shape) != tuple(parameter.shape)+ ]+ if mismatched:+ raise RuntimeError(f"joint adapter checkpoint shape mismatch: {mismatched[:3]}")+ result = transformer.load_state_dict(state, strict=False)+ if result.unexpected_keys:+ raise RuntimeError(+ "joint adapter checkpoint has unexpected keys after load: "+ f"{list(result.unexpected_keys)[:3]}"+ )+ logger.info( "Loaded exact joint adapter checkpoint: %s", path)diff --cc supratex/frontend/material_model/runtime/pbr/predict_joint_pbr.pyindex a1dfa60,0000000..41f4ef0mode 100644,000000..100644--- a/supratex/frontend/material_model/runtime/pbr/predict_joint_pbr.py+++ b/supratex/frontend/material_model/runtime/pbr/predict_joint_pbr.py@@@ -1,592 -1,0 +1,592 @@@+#!/usr/bin/env python+# Adapted for SUPRA-Tex distribution (2026): packaged local inference runtime.- # Upstream FireRed portions remain under Apache-2.0; see LICENSE.++# Upstream FireRed portions remain under Apache-2.0; see THIRD_PARTY_NOTICES.md.+"""Joint albedo/MRA/normal inference for the factorized PBR checkpoint.++The stock QwenImageEditPlusPipeline rejects prompt batches larger than one, so+it cannot exercise modality-axis attention. This runner keeps the accepted+pipeline preprocessing/scheduler/decoder semantics, but folds one physical+item into the fixed ``albedo, mra, normal`` batch and advances all three streams+together. Joint checkpoints are trained only at sigma=1, therefore this+runner intentionally accepts one-step, CFG-free inference. The checkpoint+contract selects the recorded 512/1024 resolution for v2/v3.+"""++from __future__ import annotations++import argparse+import importlib+import json+import os+import sys+import time+from pathlib import Path+from types import SimpleNamespace+++REPO = Path(__file__).absolute().parent.parent+sys.path.insert(0, str(REPO))+MODALITIES = ("albedo", "mra", "normal")+JOINT_ROUTES = ("aligned", "self_slot", "blockdiag")+++def log(message: str) -> None:+ print(f"[predict_joint_pbr {time.strftime('%H:%M:%S')}] {message}", flush=True)+++def output_path(out_dir: Path, item: dict, modality: str) -> Path:+ return out_dir / f"{item['key']}_{modality}.png"+++def load_items(path: Path, limit: int | None) -> list[dict]:+ required = {+ "key",+ "dataset",+ "sha",+ "asset_id",+ "view",+ "cond",+ "albedo_gt",+ "mra_gt",+ "normal_gt",+ "normal_valid",+ "instr_albedo",+ "instr_mra",+ "instr_normal",+ "split",+ }+ items = []+ seen = set()+ with path.open() as stream:+ for line_number, raw_line in enumerate(stream, 1):+ if not raw_line.strip():+ continue+ item = json.loads(raw_line)+ missing = required - set(item)+ if missing:+ raise ValueError(f"{path}:{line_number}: missing fields {sorted(missing)}")+ key = item["key"]+ if not isinstance(key, str) or not key or Path(key).name != key or key in {".", ".."} or "\\" in key:+ raise ValueError(f"{path}:{line_number}: key must be a single safe filename component")+ if item["key"] in seen:+ raise ValueError(f"{path}:{line_number}: duplicate key {item['key']}")+ if item["split"] != "eval":+ raise ValueError(f"{path}:{line_number}: expected split=eval")+ seen.add(item["key"])+ items.append(item)+ if limit is not None:+ items = items[:limit]+ if not items:+ raise ValueError(f"no evaluation items in {path}")+ return items+++def validate_checkpoint(checkpoint: Path, route: str) -> SimpleNamespace:+ manifest_path = checkpoint / "checkpoint_complete.json"+ contract_path = checkpoint / "joint_contract.json"+ run_contract_path = checkpoint.parent / "RUN_CONTRACT.json"+ adapter_path = checkpoint / "joint_adapter.safetensors"+ full_transformer_path = checkpoint / "diffusion_pytorch_model.safetensors"+ for path in (manifest_path, contract_path):+ if not path.is_file():+ raise FileNotFoundError(path)+ manifest = json.loads(manifest_path.read_text())+ contract = json.loads(contract_path.read_text())+ common_expected = {+ "sites": [29, 39, 49, 59],+ "modalities": list(MODALITIES),+ "rank": 256,+ "heads": 4,+ "training_route": "aligned",+ }+ schema = contract.get("schema")+ if schema == "pbr_joint_checkpoint_v1":+ expected = {+ **common_expected,+ "schema": schema,+ "trainable_tensor_count": 60,+ "trainable_parameter_count": 7_385_088,+ }+ input_size = 512+ elif schema in ("pbr_joint_checkpoint_v2", "pbr_joint_checkpoint_v3"):+ if not run_contract_path.is_file():+ raise FileNotFoundError(run_contract_path)+ run_contract = json.loads(run_contract_path.read_text())+ input_size = run_contract.get("resolution")+ if input_size not in (512, 1024):+ raise ValueError(+ f"unsupported joint-v2/v3 run resolution: {input_size!r}"+ )+ expected = {+ **common_expected,+ "schema": schema,+ "joint_tensor_count": 60,+ "joint_parameter_count": 7_385_088,+ "trainable_modules": ["modality_joint_blocks."],+ }+ backbone_low_lr = [+ f"transformer_blocks.{index}." for index in range(29, 50)+ ]+ if schema == "pbr_joint_checkpoint_v2":+ expected.update(+ low_lr_modules=backbone_low_lr,+ low_lr_ratio=0.0025,+ )+ if contract.get("fresh_joint_w_up_init_std") not in (0.0, 1e-4):+ expected["fresh_joint_w_up_init_std"] = "0.0 or 1e-4"+ residual_mode = "raw"+ else:+ low_lr_modules = contract.get("low_lr_modules")+ if low_lr_modules == []:+ expected.update(low_lr_modules=[], low_lr_ratio=None)+ elif low_lr_modules == backbone_low_lr:+ expected.update(+ low_lr_modules=backbone_low_lr,+ low_lr_ratio=0.0025,+ )+ else:+ expected["low_lr_modules"] = "[] or transformer blocks 29 through 49"+ residual_mode = contract.get("residual_mode")+ if residual_mode != "rms_scaled":+ expected["residual_mode"] = "rms_scaled"+ if contract.get("fresh_joint_w_up_init_std") not in (0.0, 3e-3):+ expected["fresh_joint_w_up_init_std"] = "0.0 or 0.003"+ if contract.get("source_joint_adapter_action") not in (+ "fresh", "loaded", "reset"+ ):+ expected["source_joint_adapter_action"] = "fresh, loaded, or reset"+ else:+ raise ValueError(f"unsupported joint checkpoint schema: {schema!r}")+ bad = {+ key: (contract.get(key), value)+ for key, value in expected.items()+ if contract.get(key) != value+ }+ if bad:+ raise ValueError(f"joint checkpoint contract mismatch: {bad}")+ if manifest.get("joint_contract") != contract:+ raise ValueError("checkpoint manifest is not bound to joint_contract.json")+ if schema == "pbr_joint_checkpoint_v1":+ if (manifest.get("global_step"), manifest.get("world_size"), manifest.get("seed")) \+ != (2000, 40, 42):+ raise ValueError(f"joint checkpoint step/world/seed mismatch: {manifest}")+ elif (+ manifest.get("format_version") != 2+ or not isinstance(manifest.get("global_step"), int)+ or manifest["global_step"] <= 0+ ):+ raise ValueError(f"joint-v2/v3 checkpoint manifest mismatch: {manifest}")+ if route in JOINT_ROUTES and schema == "pbr_joint_checkpoint_v1":+ if not adapter_path.is_file():+ raise FileNotFoundError(adapter_path)+ if route in JOINT_ROUTES and schema in (+ "pbr_joint_checkpoint_v2", "pbr_joint_checkpoint_v3"+ ):+ if not full_transformer_path.is_file():+ raise FileNotFoundError(full_transformer_path)+ return SimpleNamespace(+ schema=schema,+ input_size=input_size,+ adapter_path=adapter_path if schema == "pbr_joint_checkpoint_v1" else None,+ full_transformer_path=(+ full_transformer_path+ if schema in ("pbr_joint_checkpoint_v2", "pbr_joint_checkpoint_v3")+ else None+ ),+ residual_mode="raw" if schema != "pbr_joint_checkpoint_v3" else residual_mode,+ )+++def validate_payloads(items: list[dict]) -> None:+ fields = ("cond", "albedo_gt", "mra_gt", "normal_gt", "normal_valid")+ for item in items:+ missing = [item[field] for field in fields if not Path(item[field]).is_file()]+ if missing:+ raise FileNotFoundError(+ f"{item['key']}: missing payload(s): {missing[:3]}"+ )+++def load_source_rgb(path: str, size: int):+ from PIL import Image++ image = Image.open(path)+ if image.mode != "RGB":+ rgba = image.convert("RGBA")+ background = Image.new("RGBA", rgba.size, (0, 0, 0, 255))+ image = Image.alpha_composite(background, rgba).convert("RGB")+ if image.size != (size, size):+ image = image.resize((size, size), Image.Resampling.BICUBIC)+ return image+++def _flash_attention_available(module_name: str) -> bool:+ try:+ module = importlib.import_module(module_name)+ except (ImportError, OSError, RuntimeError):+ return False+ return all(+ callable(getattr(module, name, None))+ for name in ("flash_attn_func", "flash_attn_varlen_func")+ )+++def select_attention_backends(torch, device) -> tuple[str, str]:+ """Resolve inference attention without depending on the parent CLI package.++ The image transformer supports FA3 and native PyTorch SDPA. FA2 can still+ accelerate the text encoder when the image transformer uses native SDPA.+ An explicit SDPA selection applies to both components.+ """+ selected = os.environ.get("ATTN_BACKEND", "auto")+ if selected == "sdpa":+ return "native", "sdpa"+ supported = ("auto", "flash_attn_3", "flash_attn", "xformers", "naive", "flash_attn_4")+ if selected not in supported:+ raise ValueError(f"unsupported ATTN_BACKEND for FireRed: {selected!r}")++ device = torch.device(device)+ capability = (+ torch.cuda.get_device_capability(device)+ if device.type == "cuda" and torch.cuda.is_available()+ else (0, 0)+ )+ use_fa3 = (+ selected in ("auto", "flash_attn_3")+ and capability[0] == 9+ and _flash_attention_available("flash_attn_interface")+ )+ if selected == "flash_attn_3" and not use_fa3:+ raise RuntimeError(+ "ATTN_BACKEND=flash_attn_3 requires Hopper (SM90) and an importable "+ "flash_attn_interface extension; select sdpa for native attention"+ )+ use_fa2 = capability[0] in (8, 9) and _flash_attention_available("flash_attn")+ if selected == "flash_attn" and not use_fa2:+ raise RuntimeError(+ "ATTN_BACKEND=flash_attn requires an Ampere/Ada/Hopper GPU and an "+ "importable flash_attn extension; select sdpa for native attention"+ )+ return "fa3" if use_fa3 else "native", "flash_attention_2" if use_fa2 else "sdpa"+++def load_pipeline(args, device):+ import torch+ from diffusers import FlowMatchEulerDiscreteScheduler, QwenImageEditPlusPipeline++ image_backend, text_backend = select_attention_backends(torch, device)+ from pbr.model_loading import (+ _load_base_transformer,+ _load_exact_full_transformer,+ _load_exact_joint_adapter,+ )+ from pbr.qwen_pbr_factorized import (+ PBR_ATTENTION_FA3,+ PBR_ATTENTION_NATIVE,+ PRODUCTION_JOINT_HEADS,+ PRODUCTION_JOINT_MODALITIES,+ PRODUCTION_JOINT_RANK,+ PRODUCTION_JOINT_SITES,+ )++ model_args = SimpleNamespace(pretrained_model_name_or_path=str(args.base_model))+ transformer = _load_base_transformer(model_args, torch.bfloat16)+ if args.route == "base" or args.joint_spec.schema == "pbr_joint_checkpoint_v1":+ _load_exact_full_transformer(+ transformer,+ args.transformer_path,+ allow_joint_sidecar=args.route == "base",+ )+ if args.route in JOINT_ROUTES:+ transformer.attach_joint_modules(+ sites=PRODUCTION_JOINT_SITES,+ modalities=PRODUCTION_JOINT_MODALITIES,+ rank=PRODUCTION_JOINT_RANK,+ heads=PRODUCTION_JOINT_HEADS,+ residual_mode=args.joint_spec.residual_mode,+ )+ if args.joint_spec.schema == "pbr_joint_checkpoint_v1":+ _load_exact_joint_adapter(transformer, args.joint_spec.adapter_path)+ else:+ _load_exact_full_transformer(+ transformer, args.joint_spec.full_transformer_path+ )+ transformer.set_pbr_attention_backend(+ PBR_ATTENTION_FA3 if image_backend == "fa3" else PBR_ATTENTION_NATIVE,+ device=device,+ dtype=torch.bfloat16,+ )+ transformer.to(dtype=torch.bfloat16)+ transformer.requires_grad_(False)+ transformer.eval()++ pipe = QwenImageEditPlusPipeline.from_pretrained(+ str(args.base_model),+ transformer=transformer,+ torch_dtype=torch.bfloat16,+ local_files_only=True,+ )+ scheduler_config = dict(pipe.scheduler.config)+ scheduler_config["shift_terminal"] = None+ pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)+ pipe.to(device)+ pipe.text_encoder.set_attn_implementation(text_backend)+ pipe.set_progress_bar_config(disable=True)+ log(f"attention image={image_backend} text={text_backend}")+ return pipe+++def make_generators(torch, device, seed: int):+ # Keep per-modality noise independent, deterministic, and invariant to GPU+ # sharding. All routes use these exact three streams.+ offsets = (104_729, 209_759, 314_159)+ return [+ torch.Generator(device=device).manual_seed(seed + offset)+ for offset in offsets+ ]+++def encode_source(pipe, source, device, dtype, seed: int):+ import numpy as np+ import torch++ pixels = torch.from_numpy(+ np.asarray(source, dtype=np.float32).copy()+ ).permute(2, 0, 1).unsqueeze(0)+ pixels = (pixels / 127.5 - 1.0).to(device=device, dtype=dtype).unsqueeze(2)+ generator = torch.Generator(device=device).manual_seed(seed)+ source_latents = pipe._encode_vae_image(pixels, generator=generator)+ _, channels, _, height, width = source_latents.shape+ return pipe._pack_latents(source_latents, 1, channels, height, width)+++def encode_prompts(pipe, item: dict, source, input_size: int, device, dtype):+ from pbr.conditioning import get_embedding+ from pbr.conditioning import resize_source_images_for_condition++ prompts = [item[f"instr_{modality}"] for modality in MODALITIES]+ source_lists = resize_source_images_for_condition(+ [[source] for _ in MODALITIES],+ ref_height=input_size,+ ref_width=input_size,+ image_sample_size=input_size,+ )+ embeds, mask = get_embedding(+ True,+ prompts,+ source_lists,+ pipe.processor,+ pipe.text_encoder,+ )+ return embeds.to(device=device, dtype=dtype), mask.to(device=device)+++def generate_triplet(pipe, item: dict, args, device):+ import numpy as np+ import torch++ from pbr.conditioning import calculate_shift++ source = load_source_rgb(item["cond"], args.input_size)+ dtype = pipe.transformer.dtype+ prompt_embeds, prompt_mask = encode_prompts(+ pipe, item, source, args.input_size, device, dtype+ )+ source_latents = encode_source(pipe, source, device, dtype, args.seed)+ source_latents = source_latents.expand(len(MODALITIES), -1, -1)++ channels = pipe.transformer.config.in_channels // 4+ generators = make_generators(torch, device, args.seed)+ latents, _ = pipe.prepare_latents(+ images=None,+ batch_size=len(MODALITIES),+ num_channels_latents=channels,+ height=args.input_size,+ width=args.input_size,+ dtype=dtype,+ device=device,+ generator=generators,+ latents=None,+ )+ target_seq_len = latents.shape[1]+ grid = args.input_size // pipe.vae_scale_factor // 2+ img_shapes = [[(1, grid, grid), (1, grid, grid)] for _ in MODALITIES]++ sigmas = np.linspace(1.0, 1.0, 1)+ mu = calculate_shift(+ target_seq_len,+ pipe.scheduler.config.get("base_image_seq_len", 256),+ pipe.scheduler.config.get("max_image_seq_len", 4096),+ pipe.scheduler.config.get("base_shift", 0.5),+ pipe.scheduler.config.get("max_shift", 1.15),+ )+ pipe.scheduler.set_timesteps(sigmas=sigmas, device=device, mu=mu)+ pipe.scheduler.set_begin_index(0)++ with torch.inference_mode():+ for timestep in pipe.scheduler.timesteps:+ hidden_states = torch.cat([latents, source_latents], dim=1)+ model_timestep = timestep.expand(len(MODALITIES)).to(dtype) / 1000+ transformer_kwargs = {+ "hidden_states": hidden_states,+ "timestep": model_timestep,+ "guidance": None,+ "encoder_hidden_states_mask": prompt_mask,+ "encoder_hidden_states": prompt_embeds,+ "img_shapes": img_shapes,+ "attention_kwargs": {},+ "return_dict": False,+ }+ if args.route in JOINT_ROUTES:+ transformer_kwargs.update(+ pbr_joint_batch_size=1,+ pbr_joint_target_seq_len=target_seq_len,+ pbr_joint_route=args.route,+ )+ with pipe.transformer.cache_context("cond"):+ prediction = pipe.transformer(**transformer_kwargs)[0]+ prediction = prediction[:, :target_seq_len]+ latents = pipe.scheduler.step(+ prediction, timestep, latents, return_dict=False+ )[0]++ unpacked = pipe._unpack_latents(+ latents, args.input_size, args.input_size, pipe.vae_scale_factor+ ).to(pipe.vae.dtype)+ mean = torch.tensor(pipe.vae.config.latents_mean).view(+ 1, pipe.vae.config.z_dim, 1, 1, 1+ ).to(unpacked.device, unpacked.dtype)+ std = 1.0 / torch.tensor(pipe.vae.config.latents_std).view(+ 1, pipe.vae.config.z_dim, 1, 1, 1+ ).to(unpacked.device, unpacked.dtype)+ unpacked = unpacked / std + mean+ decoded = pipe.vae.decode(unpacked, return_dict=False)[0][:, :, 0]+ images = pipe.image_processor.postprocess(decoded, output_type="pil")+ if len(images) != len(MODALITIES):+ raise RuntimeError(f"decoder returned {len(images)} images, expected 3")+ return images+++def save_triplet(out_dir: Path, item: dict, images) -> None:+ for modality, image in zip(MODALITIES, images):+ destination = output_path(out_dir, item, modality)+ temporary = destination.with_name(destination.name + f".tmp.{os.getpid()}.png")+ image.save(temporary, format="PNG")+ os.replace(temporary, destination)+++def main() -> None:+ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)+ parser.add_argument("--items-jsonl", type=Path, required=True)+ parser.add_argument("--out-dir", type=Path, required=True)+ parser.add_argument("--base-model", type=Path, required=True)+ parser.add_argument("--transformer-path", type=Path, required=True)+ parser.add_argument("--joint-checkpoint", type=Path, required=True)+ parser.add_argument("--route", choices=("base",) + JOINT_ROUTES, required=True)+ parser.add_argument("--input-size", type=int, default=512)+ parser.add_argument("--steps", type=int, default=1)+ parser.add_argument("--cfg", type=float, default=1.0)+ parser.add_argument("--seed", type=int, default=42)+ parser.add_argument("--limit", type=int, default=None)+ parser.add_argument("--num-shards", type=int, default=1)+ parser.add_argument("--shard-index", type=int, default=0)+ parser.add_argument("--dry-run", action="store_true")+ args = parser.parse_args()++ if args.limit is not None and args.limit <= 0:+ parser.error("--limit must be positive")+ if args.num_shards < 1 or not 0 <= args.shard_index < args.num_shards:+ parser.error("require num_shards >= 1 and 0 <= shard_index < num_shards")++ for path in (args.base_model / "model_index.json", args.transformer_path):+ if not path.is_file():+ raise FileNotFoundError(path)+ args.joint_spec = validate_checkpoint(args.joint_checkpoint, args.route)+ if (+ args.input_size != args.joint_spec.input_size+ or args.steps != 1+ or args.cfg != 1.0+ ):+ parser.error(+ f"{args.joint_spec.schema} evaluation is pinned to "+ f"--input-size {args.joint_spec.input_size} --steps 1 --cfg 1"+ )+ items = load_items(args.items_jsonl, args.limit)+ validate_payloads(items)+ shard_items = items[args.shard_index::args.num_shards]+ args.out_dir.mkdir(parents=True, exist_ok=True)+ pending = [+ item for item in shard_items+ if not all(output_path(args.out_dir, item, modality).stat().st_size > 0+ if output_path(args.out_dir, item, modality).is_file() else False+ for modality in MODALITIES)+ ]+ log(+ f"route={args.route} shard={args.shard_index}/{args.num_shards} "+ f"items={len(shard_items)} pending={len(pending)} seed={args.seed} "+ f"protocol={args.input_size}/s1/cfg1 schema={args.joint_spec.schema}"+ )+ if args.dry_run:+ for item in shard_items[:10]:+ log(f"DRY {item['key']} -> {args.out_dir}")+ log("dry run complete; no model or GPU was loaded")+ return+ if not pending:+ log("nothing to do")+ return++ os.environ.setdefault("HF_HUB_OFFLINE", "1")+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")+ import torch++ if not torch.cuda.is_available():+ raise RuntimeError("CUDA is required")+ device = torch.device("cuda")+ torch.manual_seed(args.seed)+ log(f"loading model on {torch.cuda.get_device_name(device)}")+ pipe = load_pipeline(args, device)+ log("model ready")++ started = time.time()+ for index, item in enumerate(pending, 1):+ images = generate_triplet(pipe, item, args, device)+ save_triplet(args.out_dir, item, images)+ if index == 1 or index % 10 == 0 or index == len(pending):+ elapsed = time.time() - started+ rate = elapsed / index+ eta = rate * (len(pending) - index)+ log(+ f"{index}/{len(pending)} key={item['key']} "+ f"avg={rate:.2f}s/item eta={eta / 60:.1f}min"+ )++ manifest = {+ "schema": "joint_pbr_prediction_shard_v1",+ "route": args.route,+ "resolution": args.input_size,+ "steps": args.steps,+ "cfg": args.cfg,+ "seed": args.seed,+ "items_jsonl": str(args.items_jsonl.absolute()),+ "joint_checkpoint": str(args.joint_checkpoint.absolute()),+ "joint_checkpoint_schema": args.joint_spec.schema,+ "base_transformer": str(args.transformer_path.absolute()),+ "shard_index": args.shard_index,+ "num_shards": args.num_shards,+ "n_items": len(shard_items),+ "n_outputs": len(shard_items) * len(MODALITIES),+ "elapsed_seconds": time.time() - started,+ "peak_cuda_allocated_bytes": torch.cuda.max_memory_allocated(),+ "peak_cuda_reserved_bytes": torch.cuda.max_memory_reserved(),+ }+ manifest_path = args.out_dir / (+ f"prediction_shard_{args.shard_index:02d}_of_{args.num_shards:02d}.json"+ )+ temporary = manifest_path.with_name(manifest_path.name + f".tmp.{os.getpid()}")+ temporary.write_text(json.dumps(manifest, indent=2) + "\n")+ os.replace(temporary, manifest_path)+ log(f"DONE outputs={manifest['n_outputs']} manifest={manifest_path}")+++if __name__ == "__main__":+ main()diff --cc supratex/frontend/material_model/runtime/pbr/qwen_pbr_factorized.pyindex cf49bc1,0000000..75db182mode 100644,000000..100644--- a/supratex/frontend/material_model/runtime/pbr/qwen_pbr_factorized.py+++ b/supratex/frontend/material_model/runtime/pbr/qwen_pbr_factorized.py@@@ -1,853 -1,0 +1,853 @@@+# Adapted for SUPRA-Tex distribution (2026): packaged local inference runtime.- # Upstream FireRed portions remain under Apache-2.0; see LICENSE.++# Upstream FireRed portions remain under Apache-2.0; see THIRD_PARTY_NOTICES.md.+"""Factorized modality-axis attention for joint RGB-to-PBR prediction.++The stock Qwen image transformer continues to process each modality as an+independent folded-batch item. Small registered residual modules then mix the+three modalities at equal latent-grid positions after selected complete Qwen+blocks. The final up projection is zero initialized, so attaching the modules+is an exact no-op before training.+"""++from __future__ import annotations++from functools import lru_cache+from math import prod+from typing import Any, Sequence++import numpy as np+import torch+from torch import nn++from diffusers.configuration_utils import register_to_config+from diffusers.models.modeling_outputs import Transformer2DModelOutput+from diffusers.models.transformers.transformer_qwenimage import (+ QwenDoubleStreamAttnProcessor2_0,+ QwenImageTransformer2DModel,+ apply_rotary_emb_qwen,+ compute_text_seq_len_from_mask,+)+from diffusers.utils import apply_lora_scale, deprecate+++PRODUCTION_JOINT_MODALITIES = ("albedo", "mra", "normal")+PRODUCTION_JOINT_SITES = (29, 39, 49, 59)+PRODUCTION_JOINT_RANK = 256+PRODUCTION_JOINT_HEADS = 4++JOINT_RESIDUAL_RAW = "raw"+JOINT_RESIDUAL_RMS_SCALED = "rms_scaled"+JOINT_RESIDUAL_MODES = (JOINT_RESIDUAL_RAW, JOINT_RESIDUAL_RMS_SCALED)++PBR_ATTENTION_NATIVE = "native"+PBR_ATTENTION_FA3 = "fa3"+PBR_ATTENTION_BACKENDS = (PBR_ATTENTION_NATIVE, PBR_ATTENTION_FA3)++ROUTE_ALIGNED = 0+ROUTE_SELF_SLOT = 1+ROUTE_BLOCKDIAG = 2+_ROUTE_NAME_TO_CODE = {+ "aligned": ROUTE_ALIGNED,+ "self_slot": ROUTE_SELF_SLOT,+ "blockdiag": ROUTE_BLOCKDIAG,+}+++@lru_cache(maxsize=1)+def _load_flash_attention_3_ops():+ try:+ from flash_attn_interface import flash_attn_func, flash_attn_varlen_func+ except (ImportError, OSError, RuntimeError) as error:+ raise RuntimeError(+ "FireRed image attention requires the t2h FlashAttention-3 "+ "flash_attn_interface extension"+ ) from error+ return flash_attn_func, flash_attn_varlen_func+++@lru_cache(maxsize=16)+def validate_fa3_runtime(device: torch.device | str, dtype: torch.dtype) -> None:+ """Fail closed unless the selected worker can execute Hopper BF16/FP16 FA3."""++ device = torch.device(device)+ if device.type != "cuda" or not torch.cuda.is_available():+ raise RuntimeError("FireRed FA3 image attention requires a CUDA device")+ if dtype not in (torch.bfloat16, torch.float16):+ raise RuntimeError(+ "FireRed FA3 image attention requires bfloat16 or float16, "+ f"got {dtype}"+ )+ capability = torch.cuda.get_device_capability(device)+ if capability < (9, 0):+ raise RuntimeError(+ "FireRed FA3 image attention requires Hopper compute capability >= 9.0, "+ f"got {capability[0]}.{capability[1]}"+ )+ _load_flash_attention_3_ops()+++def prepare_fa3_key_mask_plan(+ attention_mask: torch.Tensor,+ query_seq_len: int,+) -> dict[str, torch.Tensor | int]:+ """Pack arbitrary valid K/V positions once for all Qwen transformer blocks.++ Qwen joint attention lays tokens out as ``[text, image]``. Because text is+ padded before the image suffix, its key mask is not necessarily a valid+ prefix. Diffusers' generic FA3-varlen backend slices ``K/V[:valid_len]``+ and would therefore drop real image tokens. This plan gathers the true+ boolean-mask positions while leaving every query in its original RoPE+ position.+ """++ if attention_mask.dtype != torch.bool or attention_mask.ndim != 2:+ raise ValueError(+ "FA3 Qwen attention_mask must be a 2D bool tensor, "+ f"got shape={tuple(attention_mask.shape)} dtype={attention_mask.dtype}"+ )+ batch_size, key_seq_len = attention_mask.shape+ query_seq_len = int(query_seq_len)+ if batch_size <= 0 or key_seq_len <= 0 or query_seq_len <= 0:+ raise ValueError("FA3 Qwen attention dimensions must be positive")++ key_lengths = attention_mask.sum(dim=1, dtype=torch.int32)+ if not bool((key_lengths > 0).all().item()):+ raise ValueError("every FA3 Qwen sample must retain at least one key token")+ key_indices = attention_mask.reshape(-1).nonzero(as_tuple=False).flatten()+ cu_seqlens_k = torch.zeros(+ batch_size + 1,+ dtype=torch.int32,+ device=attention_mask.device,+ )+ cu_seqlens_k[1:] = key_lengths.cumsum(dim=0)+ cu_seqlens_q = torch.arange(+ 0,+ (batch_size + 1) * query_seq_len,+ query_seq_len,+ dtype=torch.int32,+ device=attention_mask.device,+ )+ return {+ "key_indices": key_indices,+ "cu_seqlens_q": cu_seqlens_q,+ "cu_seqlens_k": cu_seqlens_k,+ "max_seqlen_q": query_seq_len,+ "max_seqlen_k": int(key_lengths.max().item()),+ }+++def flash_attention_3_with_key_mask(+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ *,+ attention_mask: torch.Tensor | None,+ mask_plan: dict[str, torch.Tensor | int] | None = None,+) -> torch.Tensor:+ """Run exact non-causal FA3 attention with Qwen's arbitrary key mask."""++ if query.ndim != 4 or key.ndim != 4 or value.ndim != 4:+ raise ValueError("FA3 Qwen Q/K/V must have shape [B, S, H, D]")+ if query.shape != key.shape or key.shape != value.shape:+ raise ValueError(+ "FA3 Qwen requires equal Q/K/V shapes, got "+ f"{tuple(query.shape)}, {tuple(key.shape)}, {tuple(value.shape)}"+ )+ if query.device != key.device or key.device != value.device:+ raise ValueError("FA3 Qwen Q/K/V must be on the same device")+ if query.dtype != key.dtype or key.dtype != value.dtype:+ raise ValueError("FA3 Qwen Q/K/V must have the same dtype")+ validate_fa3_runtime(query.device, query.dtype)+ flash_attn_func, flash_attn_varlen_func = _load_flash_attention_3_ops()++ query = query.contiguous()+ key = key.contiguous()+ value = value.contiguous()+ if attention_mask is None:+ return flash_attn_func(+ query,+ key,+ value,+ softmax_scale=None,+ causal=False,+ )++ if attention_mask.shape != query.shape[:2]:+ raise ValueError(+ "FA3 Qwen key mask must match [B, S], got "+ f"{tuple(attention_mask.shape)} for {tuple(query.shape[:2])}"+ )+ if attention_mask.device != query.device:+ raise ValueError("FA3 Qwen key mask must be on the Q/K/V device")+ if mask_plan is None:+ mask_plan = prepare_fa3_key_mask_plan(attention_mask, query.shape[1])++ batch_size, seq_len, heads, head_dim = query.shape+ key_indices = mask_plan["key_indices"]+ if not isinstance(key_indices, torch.Tensor) or key_indices.device != query.device:+ raise ValueError("invalid FA3 key_indices mask plan")+ flat_key = key.reshape(batch_size * seq_len, heads, head_dim)+ flat_value = value.reshape(batch_size * seq_len, heads, head_dim)+ packed_key = flat_key.index_select(0, key_indices)+ packed_value = flat_value.index_select(0, key_indices)+ packed_query = query.reshape(batch_size * seq_len, heads, head_dim)+ output = flash_attn_varlen_func(+ packed_query,+ packed_key,+ packed_value,+ mask_plan["cu_seqlens_q"],+ mask_plan["cu_seqlens_k"],+ int(mask_plan["max_seqlen_q"]),+ int(mask_plan["max_seqlen_k"]),+ softmax_scale=None,+ causal=False,+ )+ return output.reshape(batch_size, seq_len, heads, head_dim)+++class QwenDoubleStreamAttnProcessorFA3:+ """Qwen double-stream processor using mask-correct Hopper FA3 kernels."""++ _attention_backend = "_flash_3"+ _parallel_config = None++ def __init__(self) -> None:+ _load_flash_attention_3_ops()++ def __call__(+ self,+ attn,+ hidden_states: torch.Tensor,+ encoder_hidden_states: torch.Tensor | None = None,+ encoder_hidden_states_mask: torch.Tensor | None = None,+ attention_mask: torch.Tensor | None = None,+ image_rotary_emb: torch.Tensor | None = None,+ fa3_key_indices: torch.Tensor | None = None,+ fa3_cu_seqlens_q: torch.Tensor | None = None,+ fa3_cu_seqlens_k: torch.Tensor | None = None,+ fa3_max_seqlen_q: int | None = None,+ fa3_max_seqlen_k: int | None = None,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ if encoder_hidden_states is None:+ raise ValueError(+ "QwenDoubleStreamAttnProcessorFA3 requires encoder_hidden_states"+ )++ seq_txt = encoder_hidden_states.shape[1]+ img_query = attn.to_q(hidden_states)+ img_key = attn.to_k(hidden_states)+ img_value = attn.to_v(hidden_states)+ txt_query = attn.add_q_proj(encoder_hidden_states)+ txt_key = attn.add_k_proj(encoder_hidden_states)+ txt_value = attn.add_v_proj(encoder_hidden_states)++ img_query = img_query.unflatten(-1, (attn.heads, -1))+ img_key = img_key.unflatten(-1, (attn.heads, -1))+ img_value = img_value.unflatten(-1, (attn.heads, -1))+ txt_query = txt_query.unflatten(-1, (attn.heads, -1))+ txt_key = txt_key.unflatten(-1, (attn.heads, -1))+ txt_value = txt_value.unflatten(-1, (attn.heads, -1))++ if attn.norm_q is not None:+ img_query = attn.norm_q(img_query)+ if attn.norm_k is not None:+ img_key = attn.norm_k(img_key)+ if attn.norm_added_q is not None:+ txt_query = attn.norm_added_q(txt_query)+ if attn.norm_added_k is not None:+ txt_key = attn.norm_added_k(txt_key)++ if image_rotary_emb is not None:+ img_freqs, txt_freqs = image_rotary_emb+ img_query = apply_rotary_emb_qwen(img_query, img_freqs, use_real=False)+ img_key = apply_rotary_emb_qwen(img_key, img_freqs, use_real=False)+ txt_query = apply_rotary_emb_qwen(txt_query, txt_freqs, use_real=False)+ txt_key = apply_rotary_emb_qwen(txt_key, txt_freqs, use_real=False)++ joint_query = torch.cat([txt_query, img_query], dim=1)+ joint_key = torch.cat([txt_key, img_key], dim=1)+ joint_value = torch.cat([txt_value, img_value], dim=1)+ mask_plan = None+ if attention_mask is not None:+ required_plan = (+ fa3_key_indices,+ fa3_cu_seqlens_q,+ fa3_cu_seqlens_k,+ fa3_max_seqlen_q,+ fa3_max_seqlen_k,+ )+ if any(item is None for item in required_plan):+ raise ValueError("FA3 Qwen attention mask plan is incomplete")+ mask_plan = {+ "key_indices": fa3_key_indices,+ "cu_seqlens_q": fa3_cu_seqlens_q,+ "cu_seqlens_k": fa3_cu_seqlens_k,+ "max_seqlen_q": fa3_max_seqlen_q,+ "max_seqlen_k": fa3_max_seqlen_k,+ }+ joint_hidden_states = flash_attention_3_with_key_mask(+ joint_query,+ joint_key,+ joint_value,+ attention_mask=attention_mask,+ mask_plan=mask_plan,+ )+ joint_hidden_states = joint_hidden_states.flatten(2, 3).to(joint_query.dtype)++ txt_attn_output = joint_hidden_states[:, :seq_txt, :]+ img_attn_output = joint_hidden_states[:, seq_txt:, :]+ img_attn_output = attn.to_out[0](img_attn_output.contiguous())+ if len(attn.to_out) > 1:+ img_attn_output = attn.to_out[1](img_attn_output)+ txt_attn_output = attn.to_add_out(txt_attn_output.contiguous())+ return img_attn_output, txt_attn_output+++def _normalize_modalities(modalities: Sequence[str]) -> tuple[str, ...]:+ result = tuple(str(item) for item in modalities)+ if result != PRODUCTION_JOINT_MODALITIES:+ raise ValueError(+ "the first factorized PBR model fixes modality order to "+ f"{PRODUCTION_JOINT_MODALITIES}, got {result}"+ )+ return result+++def _normalize_sites(sites: Sequence[int], num_layers: int) -> tuple[int, ...]:+ result = tuple(int(site) for site in sites)+ if len(set(result)) != len(result):+ raise ValueError(f"joint sites must be unique, got {result}")+ if any(site < 0 or site >= num_layers for site in result):+ raise ValueError(f"joint sites must be within [0, {num_layers - 1}], got {result}")+ return result+++def _normalize_residual_mode(residual_mode: str) -> str:+ result = str(residual_mode)+ if result not in JOINT_RESIDUAL_MODES:+ raise ValueError(+ f"joint residual mode must be one of {JOINT_RESIDUAL_MODES}, got {result!r}"+ )+ return result+++class ModalityAxisJointAttention(nn.Module):+ """Mix equal-position modality tokens while keeping objects/tokens separate.++ Inputs use object-major folded-batch order: ``[B*M, L, D]`` where M is the+ fixed modality count. Attention is over the donor-modality axis only. The+ checkpointable forward accepts tensors exclusively.+ """++ def __init__(+ self,+ hidden_dim: int,+ rank: int = PRODUCTION_JOINT_RANK,+ heads: int = PRODUCTION_JOINT_HEADS,+ modalities: Sequence[str] = PRODUCTION_JOINT_MODALITIES,+ residual_mode: str = JOINT_RESIDUAL_RAW,+ ) -> None:+ super().__init__()+ self.hidden_dim = int(hidden_dim)+ self.rank = int(rank)+ self.heads = int(heads)+ self.modalities = _normalize_modalities(modalities)+ self.num_modalities = len(self.modalities)+ self.residual_mode = _normalize_residual_mode(residual_mode)++ if self.hidden_dim <= 0 or self.rank <= 0 or self.heads <= 0:+ raise ValueError("hidden_dim, rank, and heads must all be positive")+ if self.rank % self.heads != 0:+ raise ValueError(f"rank={self.rank} must be divisible by heads={self.heads}")+ self.head_dim = self.rank // self.heads+ self.scale = self.head_dim**-0.5++ self.norm = nn.LayerNorm(self.hidden_dim)+ self.w_down = nn.Linear(self.hidden_dim, self.rank)+ self.modality_embedding = nn.Parameter(torch.empty(self.num_modalities, self.rank))+ self.to_q = nn.Linear(self.rank, self.rank)+ self.to_k = nn.Linear(self.rank, self.rank)+ self.to_v = nn.Linear(self.rank, self.rank)+ self.to_out = nn.Linear(self.rank, self.rank)+ self.w_up = nn.Linear(self.rank, self.hidden_dim)++ nn.init.normal_(self.modality_embedding, mean=0.0, std=0.02)+ nn.init.zeros_(self.w_up.weight)+ nn.init.zeros_(self.w_up.bias)++ @staticmethod+ def _route_value(route_code: torch.Tensor) -> int:+ if not isinstance(route_code, torch.Tensor) or route_code.numel() != 1:+ raise ValueError("route_code must be a scalar tensor")+ route = int(route_code.detach().item())+ if route not in (ROUTE_ALIGNED, ROUTE_SELF_SLOT, ROUTE_BLOCKDIAG):+ raise ValueError(f"unknown joint route code: {route}")+ return route++ def forward(+ self,+ hidden_states: torch.Tensor,+ route_code: torch.Tensor,+ modality_attention_mask: torch.Tensor,+ ) -> torch.Tensor:+ """Return a modality-mixed residual update for target-prefix tokens."""++ if hidden_states.ndim != 3:+ raise ValueError(+ f"hidden_states must have shape [B*M, L, D], got {tuple(hidden_states.shape)}"+ )+ folded_batch, seq_len, hidden_dim = hidden_states.shape+ if hidden_dim != self.hidden_dim:+ raise ValueError(f"expected hidden dim {self.hidden_dim}, got {hidden_dim}")+ if folded_batch % self.num_modalities != 0:+ raise ValueError(+ f"folded batch {folded_batch} is not divisible by M={self.num_modalities}"+ )+ if seq_len <= 0:+ raise ValueError("the target token sequence must be non-empty")++ route = self._route_value(route_code)+ if route == ROUTE_BLOCKDIAG and self.training:+ raise ValueError("blockdiag is an evaluation-only intervention")++ if not isinstance(modality_attention_mask, torch.Tensor):+ raise ValueError("modality_attention_mask must be a tensor")+ if tuple(modality_attention_mask.shape) != (self.num_modalities, self.num_modalities):+ raise ValueError(+ "modality_attention_mask must have shape "+ f"[{self.num_modalities}, {self.num_modalities}], got "+ f"{tuple(modality_attention_mask.shape)}"+ )+ attention_mask = modality_attention_mask.to(device=hidden_states.device, dtype=torch.bool)+ if not bool(attention_mask.any(dim=-1).all().item()):+ raise ValueError("every modality query must have at least one permitted donor")+ if route == ROUTE_BLOCKDIAG:+ expected = torch.eye(self.num_modalities, dtype=torch.bool, device=hidden_states.device)+ if not torch.equal(attention_mask, expected):+ raise ValueError("blockdiag route requires an identity modality attention mask")++ batch_size = folded_batch // self.num_modalities+ # Object-major fold: flat index = object_index * M + modality_index.+ x = hidden_states.reshape(batch_size, self.num_modalities, seq_len, hidden_dim)+ x = x.permute(0, 2, 1, 3) # [B, L, M, D]+ z = self.w_down(self.norm(x)) # [B, L, M, R]++ modality_embedding = self.modality_embedding.to(dtype=z.dtype)+ query_input = z + modality_embedding.view(1, 1, self.num_modalities, self.rank)++ if route == ROUTE_SELF_SLOT:+ # Each query supplies its own content to all donor slots. Donor+ # modality embeddings keep the slots distinct before K/V.+ donor_input = z.unsqueeze(3).expand(-1, -1, -1, self.num_modalities, -1)+ else:+ # Every query sees the real aligned modality tokens at this object+ # and latent-grid position. Blockdiag changes only the edge mask.+ donor_input = z.unsqueeze(2).expand(-1, -1, self.num_modalities, -1, -1)+ donor_input = donor_input + modality_embedding.view(+ 1, 1, 1, self.num_modalities, self.rank+ )++ query = self.to_q(query_input).reshape(+ batch_size, seq_len, self.num_modalities, self.heads, self.head_dim+ )+ query = query.permute(0, 1, 3, 2, 4) # [B, L, H, Q, dh]++ key = self.to_k(donor_input).reshape(+ batch_size,+ seq_len,+ self.num_modalities,+ self.num_modalities,+ self.heads,+ self.head_dim,+ )+ value = self.to_v(donor_input).reshape_as(key)+ key = key.permute(0, 1, 4, 2, 3, 5) # [B, L, H, Q, K, dh]+ value = value.permute(0, 1, 4, 2, 3, 5)++ logits = (query.unsqueeze(-2) * key).sum(dim=-1) * self.scale+ mask = attention_mask.view(1, 1, 1, self.num_modalities, self.num_modalities)+ logits = logits.masked_fill(~mask, torch.finfo(logits.dtype).min)+ weights = torch.softmax(logits.float(), dim=-1).to(dtype=logits.dtype)+ context = (weights.unsqueeze(-1) * value).sum(dim=-2)+ context = context.permute(0, 1, 3, 2, 4).reshape(+ batch_size, seq_len, self.num_modalities, self.rank+ )+ delta = self.w_up(self.to_out(context))+ if self.residual_mode == JOINT_RESIDUAL_RMS_SCALED:+ # Qwen image residual states can reach 1e6--1e7 in BF16 even though+ # every following block consumes a LayerNorm-normalized view. A+ # raw adapter update therefore disappears at the residual add. In+ # the repaired parameterization, the adapter predicts a normalized+ # update and this detached RMS converts it back to the host unit.+ token_rms = torch.linalg.vector_norm(+ x, dim=-1, keepdim=True, dtype=torch.float32+ ) * (hidden_dim**-0.5)+ delta = delta * token_rms.detach().to(dtype=delta.dtype)+ output = x + delta+ return output.permute(0, 2, 1, 3).reshape(folded_batch, seq_len, hidden_dim)+++class QwenImagePBRFactorizedTransformer2DModel(QwenImageTransformer2DModel):+ """Qwen image transformer with registered factorized PBR joint modules."""++ @register_to_config+ def __init__(+ self,+ patch_size: int = 2,+ in_channels: int = 64,+ out_channels: int | None = 16,+ num_layers: int = 60,+ attention_head_dim: int = 128,+ num_attention_heads: int = 24,+ joint_attention_dim: int = 3584,+ guidance_embeds: bool = False,+ axes_dims_rope: tuple[int, int, int] = (16, 56, 56),+ zero_cond_t: bool = False,+ use_additional_t_cond: bool = False,+ use_layer3d_rope: bool = False,+ joint_sites: Sequence[int] = (),+ joint_modalities: Sequence[str] = PRODUCTION_JOINT_MODALITIES,+ joint_rank: int = PRODUCTION_JOINT_RANK,+ joint_heads: int = PRODUCTION_JOINT_HEADS,+ joint_residual_mode: str = JOINT_RESIDUAL_RAW,+ ) -> None:+ super().__init__(+ patch_size=patch_size,+ in_channels=in_channels,+ out_channels=out_channels,+ num_layers=num_layers,+ attention_head_dim=attention_head_dim,+ num_attention_heads=num_attention_heads,+ joint_attention_dim=joint_attention_dim,+ guidance_embeds=guidance_embeds,+ axes_dims_rope=axes_dims_rope,+ zero_cond_t=zero_cond_t,+ use_additional_t_cond=use_additional_t_cond,+ use_layer3d_rope=use_layer3d_rope,+ )+ self._pbr_attention_backend = PBR_ATTENTION_NATIVE+ self.modality_joint_blocks = nn.ModuleDict()+ self.joint_modalities = _normalize_modalities(joint_modalities)+ self.joint_rank = int(joint_rank)+ self.joint_heads = int(joint_heads)+ self.joint_residual_mode = _normalize_residual_mode(joint_residual_mode)++ normalized_sites = _normalize_sites(joint_sites, len(self.transformer_blocks))+ if normalized_sites:+ self._attach_joint_modules(+ sites=normalized_sites,+ modalities=self.joint_modalities,+ rank=self.joint_rank,+ heads=self.joint_heads,+ residual_mode=self.joint_residual_mode,+ update_config=True,+ )++ @property+ def joint_sites(self) -> tuple[int, ...]:+ return tuple(int(site) for site in self.modality_joint_blocks.keys())++ def _attach_joint_modules(+ self,+ sites: Sequence[int],+ modalities: Sequence[str],+ rank: int,+ heads: int,+ residual_mode: str,+ *,+ update_config: bool,+ ) -> None:+ if len(self.modality_joint_blocks) != 0:+ raise RuntimeError(f"joint modules are already attached at sites {self.joint_sites}")+ normalized_sites = _normalize_sites(sites, len(self.transformer_blocks))+ if not normalized_sites:+ raise ValueError("attach_joint_modules requires at least one site")+ normalized_modalities = _normalize_modalities(modalities)+ rank = int(rank)+ heads = int(heads)+ residual_mode = _normalize_residual_mode(residual_mode)+ if rank <= 0 or heads <= 0 or rank % heads != 0:+ raise ValueError(f"joint rank={rank} must be positive and divisible by heads={heads}")++ self.modality_joint_blocks.update(+ {+ str(site): ModalityAxisJointAttention(+ hidden_dim=self.inner_dim,+ rank=rank,+ heads=heads,+ modalities=normalized_modalities,+ residual_mode=residual_mode,+ )+ for site in normalized_sites+ }+ )+ self.joint_modalities = normalized_modalities+ self.joint_rank = rank+ self.joint_heads = heads+ self.joint_residual_mode = residual_mode+ if update_config:+ self.register_to_config(+ architecture_type="QwenImagePBRFactorized",+ joint_sites=list(normalized_sites),+ joint_modalities=list(normalized_modalities),+ joint_rank=rank,+ joint_heads=heads,+ joint_residual_mode=residual_mode,+ supported_joint_routes=["self_slot", "aligned"],+ blockdiag_eval_only=True,+ )++ def attach_joint_modules(+ self,+ sites: Sequence[int] = PRODUCTION_JOINT_SITES,+ modalities: Sequence[str] = PRODUCTION_JOINT_MODALITIES,+ rank: int = PRODUCTION_JOINT_RANK,+ heads: int = PRODUCTION_JOINT_HEADS,+ residual_mode: str = JOINT_RESIDUAL_RAW,+ ) -> None:+ """Attach initialized modules after an exact base-only load."""++ self._attach_joint_modules(+ sites=sites,+ modalities=modalities,+ rank=rank,+ heads=heads,+ residual_mode=residual_mode,+ update_config=True,+ )++ def set_pbr_attention_backend(+ self,+ backend: str,+ *,+ device: torch.device | str | None = None,+ dtype: torch.dtype | None = None,+ ) -> None:+ """Select the Qwen image-transformer attention kernel for this runtime."""++ backend = str(backend)+ if backend not in PBR_ATTENTION_BACKENDS:+ raise ValueError(+ f"pbr attention backend must be one of {PBR_ATTENTION_BACKENDS}, "+ f"got {backend!r}"+ )+ if backend == PBR_ATTENTION_FA3:+ if device is None or dtype is None:+ raise ValueError("FA3 backend selection requires runtime device and dtype")+ validate_fa3_runtime(device, dtype)+ processor_factory = QwenDoubleStreamAttnProcessorFA3+ else:+ processor_factory = QwenDoubleStreamAttnProcessor2_0++ for block in self.transformer_blocks:+ block.attn.set_processor(processor_factory())+ self._pbr_attention_backend = backend++ @staticmethod+ def _runtime_int(value: int | torch.Tensor | None, name: str) -> int:+ if isinstance(value, torch.Tensor):+ if value.numel() != 1:+ raise ValueError(f"{name} must be a scalar")+ value = int(value.detach().item())+ if not isinstance(value, int):+ raise ValueError(f"{name} must be an integer")+ return value++ @staticmethod+ def _runtime_route(value: str | int | torch.Tensor | None, device: torch.device) -> torch.Tensor:+ if isinstance(value, str):+ if value not in _ROUTE_NAME_TO_CODE:+ raise ValueError(f"unknown pbr_joint_route: {value!r}")+ code = _ROUTE_NAME_TO_CODE[value]+ elif isinstance(value, torch.Tensor):+ if value.numel() != 1:+ raise ValueError("pbr_joint_route tensor must be scalar")+ code = int(value.detach().item())+ elif isinstance(value, int):+ code = value+ else:+ raise ValueError("pbr_joint_route must be self_slot, aligned, or blockdiag")+ if code not in (ROUTE_ALIGNED, ROUTE_SELF_SLOT, ROUTE_BLOCKDIAG):+ raise ValueError(f"unknown pbr_joint_route code: {code}")+ return torch.tensor(code, dtype=torch.int64, device=device)++ @apply_lora_scale("attention_kwargs")+ def forward(+ self,+ hidden_states: torch.Tensor,+ encoder_hidden_states: torch.Tensor | None = None,+ encoder_hidden_states_mask: torch.Tensor | None = None,+ timestep: torch.LongTensor | None = None,+ img_shapes: list[tuple[int, int, int]] | None = None,+ txt_seq_lens: list[int] | None = None,+ guidance: torch.Tensor | None = None,+ attention_kwargs: dict[str, Any] | None = None,+ controlnet_block_samples=None,+ additional_t_cond=None,+ return_dict: bool = True,+ pbr_joint_batch_size: int | torch.Tensor | None = None,+ pbr_joint_target_seq_len: int | torch.Tensor | None = None,+ pbr_joint_route: str | int | torch.Tensor | None = None,+ ) -> torch.Tensor | Transformer2DModelOutput:+ """Run stock Qwen blocks and insert target-only modality adapters."""++ has_joint_modules = len(self.modality_joint_blocks) > 0+ runtime_values = (pbr_joint_batch_size, pbr_joint_target_seq_len, pbr_joint_route)+ if has_joint_modules and any(value is None for value in runtime_values):+ raise ValueError(+ "joint models require pbr_joint_batch_size, pbr_joint_target_seq_len, "+ "and pbr_joint_route"+ )+ if not has_joint_modules and any(value is not None for value in runtime_values):+ raise ValueError("joint runtime arguments were provided before joint modules were attached")++ if txt_seq_lens is not None:+ deprecate(+ "txt_seq_lens",+ "0.39.0",+ "Passing `txt_seq_lens` is deprecated and will be removed in version 0.39.0. "+ "Please use `encoder_hidden_states_mask` instead. "+ "The mask-based approach is more flexible and supports variable-length sequences.",+ standard_warn=False,+ )++ if has_joint_modules:+ batch_size = self._runtime_int(pbr_joint_batch_size, "pbr_joint_batch_size")+ target_seq_len = self._runtime_int(+ pbr_joint_target_seq_len, "pbr_joint_target_seq_len"+ )+ if batch_size <= 0:+ raise ValueError("pbr_joint_batch_size must be positive")+ expected_folded_batch = batch_size * len(self.joint_modalities)+ if hidden_states.shape[0] != expected_folded_batch:+ raise ValueError(+ "object-major folded batch mismatch: expected "+ f"B*M={expected_folded_batch}, got {hidden_states.shape[0]}"+ )+ if target_seq_len <= 0 or target_seq_len > hidden_states.shape[1]:+ raise ValueError(+ f"pbr_joint_target_seq_len must be in [1, {hidden_states.shape[1]}], "+ f"got {target_seq_len}"+ )+ route_code = self._runtime_route(pbr_joint_route, hidden_states.device)+ if int(route_code.item()) == ROUTE_BLOCKDIAG:+ modality_attention_mask = torch.eye(+ len(self.joint_modalities), dtype=torch.bool, device=hidden_states.device+ )+ else:+ modality_attention_mask = torch.ones(+ (len(self.joint_modalities), len(self.joint_modalities)),+ dtype=torch.bool,+ device=hidden_states.device,+ )+ else:+ target_seq_len = 0+ route_code = None+ modality_attention_mask = None++ hidden_states = self.img_in(hidden_states)+ timestep = timestep.to(hidden_states.dtype)++ if self.zero_cond_t:+ timestep = torch.cat([timestep, timestep * 0], dim=0)+ modulate_index = torch.tensor(+ [[0] * prod(sample[0]) + [1] * sum(prod(shape) for shape in sample[1:]) for sample in img_shapes],+ device=timestep.device,+ dtype=torch.int,+ )+ else:+ modulate_index = None++ encoder_hidden_states = self.txt_norm(encoder_hidden_states)+ encoder_hidden_states = self.txt_in(encoder_hidden_states)+ text_seq_len, _, encoder_hidden_states_mask = compute_text_seq_len_from_mask(+ encoder_hidden_states, encoder_hidden_states_mask+ )++ if guidance is not None:+ guidance = guidance.to(hidden_states.dtype) * 1000++ temb = (+ self.time_text_embed(timestep, hidden_states, additional_t_cond)+ if guidance is None+ else self.time_text_embed(timestep, guidance, hidden_states, additional_t_cond)+ )+ image_rotary_emb = self.pos_embed(+ img_shapes, max_txt_seq_len=text_seq_len, device=hidden_states.device+ )++ block_attention_kwargs = attention_kwargs.copy() if attention_kwargs is not None else {}+ if encoder_hidden_states_mask is not None:+ folded_batch, image_seq_len = hidden_states.shape[:2]+ image_mask = torch.ones(+ (folded_batch, image_seq_len), dtype=torch.bool, device=hidden_states.device+ )+ joint_attention_mask = torch.cat([encoder_hidden_states_mask, image_mask], dim=1)+ block_attention_kwargs["attention_mask"] = joint_attention_mask+ if self._pbr_attention_backend == PBR_ATTENTION_FA3:+ reserved = {+ "fa3_key_indices",+ "fa3_cu_seqlens_q",+ "fa3_cu_seqlens_k",+ "fa3_max_seqlen_q",+ "fa3_max_seqlen_k",+ }+ conflict = reserved.intersection(block_attention_kwargs)+ if conflict:+ raise ValueError(f"reserved FA3 attention kwargs supplied: {sorted(conflict)}")+ mask_plan = prepare_fa3_key_mask_plan(+ joint_attention_mask,+ query_seq_len=joint_attention_mask.shape[1],+ )+ block_attention_kwargs.update(+ {+ "fa3_key_indices": mask_plan["key_indices"],+ "fa3_cu_seqlens_q": mask_plan["cu_seqlens_q"],+ "fa3_cu_seqlens_k": mask_plan["cu_seqlens_k"],+ "fa3_max_seqlen_q": mask_plan["max_seqlen_q"],+ "fa3_max_seqlen_k": mask_plan["max_seqlen_k"],+ }+ )++ for index_block, block in enumerate(self.transformer_blocks):+ encoder_hidden_states, hidden_states = block(+ hidden_states=hidden_states,+ encoder_hidden_states=encoder_hidden_states,+ encoder_hidden_states_mask=None,+ temb=temb,+ image_rotary_emb=image_rotary_emb,+ joint_attention_kwargs=block_attention_kwargs,+ modulate_index=modulate_index,+ )++ mixer_key = str(index_block)+ if mixer_key in self.modality_joint_blocks:+ mixer = self.modality_joint_blocks[mixer_key]+ target_hidden = hidden_states[:, :target_seq_len]+ target_hidden = mixer(+ target_hidden,+ route_code,+ modality_attention_mask,+ )+ if target_seq_len == hidden_states.shape[1]:+ hidden_states = target_hidden+ else:+ # The adapter never reads or writes the common source suffix.+ hidden_states = torch.cat(+ [target_hidden, hidden_states[:, target_seq_len:]], dim=1+ )++ if controlnet_block_samples is not None:+ interval_control = int(+ np.ceil(len(self.transformer_blocks) / len(controlnet_block_samples))+ )+ hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]++ if self.zero_cond_t:+ temb = temb.chunk(2, dim=0)[0]+ hidden_states = self.norm_out(hidden_states, temb)+ output = self.proj_out(hidden_states)++ if not return_dict:+ return (output,)+ return Transformer2DModelOutput(sample=output)diff --cc supratex/inference/geometry_cleanup.pyindex 0000000,0000000..e2f657enew file mode 100644--- /dev/null+++ b/supratex/inference/geometry_cleanup.py@@@ -1,0 -1,0 +1,114 @@@++"""Optional removal of floating geometry that the reference image does not show.++++Generated geometry can contain disconnected pieces outside the object in the++image. A piece is removed when it is not the largest connected component and++most of its faces project outside the image foreground, which is dilated to++tolerate ordinary misalignment. Parts hidden behind the foreground, such as++the back of the object, still project inside it and are kept, as are parts of++any size that the image shows. Extra geometry connected to the object is not++affected.++"""++from __future__ import annotations++++import math++from typing import Any, Mapping++++import numpy as np++import torch++++FOREGROUND_ALPHA = 128++# Misalignment tolerance as a fraction of the image width (16 px at 1024).++MARGIN = 16 / 1024++MIN_INSIDE = 0.5++# Vertices closer than this are welded, so UV-seam duplicates stay connected.++WELD_STEP = 1e-6++KEY_BITS = 21++++++def _weld(vertices: torch.Tensor) -> torch.Tensor:++ """Map each vertex to the index of its quantized position."""++ low = vertices.amin(0)++ step = max(WELD_STEP, float((vertices.amax(0) - low).max()) / (2 ** KEY_BITS - 1))++ q = torch.round((vertices.double() - low) / step).long()++ key = (q[:, 0] << (2 * KEY_BITS)) | (q[:, 1] << KEY_BITS) | q[:, 2]++ return torch.unique(key, return_inverse=True)[1]++++++def _components(vertices: torch.Tensor, faces: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:++ """Label faces by connected component with parallel union-find.++++ Each round hooks every root to the smallest root among its edges, then++ compresses paths by pointer jumping; components halve per round.++ """++ welded = _weld(vertices)[faces]++ count = int(welded.max()) + 1++ first = torch.cat((welded[:, 0], welded[:, 1]))++ second = torch.cat((welded[:, 1], welded[:, 2]))++ parent = torch.arange(count, device=faces.device)++ while True:++ a, b = parent[first], parent[second]++ differ = a != b++ if not bool(differ.any()):++ break++ low, high = torch.minimum(a[differ], b[differ]), torch.maximum(a[differ], b[differ])++ parent.scatter_reduce_(0, high, low, reduce="amin")++ while True:++ jumped = parent[parent]++ if torch.equal(jumped, parent):++ break++ parent = jumped++ first, second = first[differ], second[differ]++ face_labels = torch.unique(parent[welded[:, 0]], return_inverse=True)[1]++ return face_labels, torch.bincount(face_labels)++++++def _project(points: torch.Tensor, camera: Mapping[str, Any]) -> tuple[torch.Tensor, torch.Tensor]:++ """Normalized image coordinates (y down) and camera depth, matching completion."""++ if "extrinsic" in camera:++ extrinsic = torch.as_tensor(camera["extrinsic"], dtype=points.dtype, device=points.device)++ intrinsic = torch.as_tensor(camera["intrinsic"], dtype=points.dtype, device=points.device)++ local = points @ extrinsic[:3, :3].T + extrinsic[:3, 3]++ uvw = local @ intrinsic.T++ return uvw[:, :2] / uvw[:, 2:3].clamp(min=1e-8), local[:, 2]++ distance = float(camera["distance"]) * float(camera.get("mesh_scale", 1.0))++ focal = 0.5 / math.tan(float(camera["camera_angle_x"]) / 2)++ depth = distance - points[:, 2]++ safe = depth.clamp(min=1e-8)++ return torch.stack((points[:, 0] / safe * focal + 0.5, -points[:, 1] / safe * focal + 0.5), dim=1), depth++++++def _foreground(alpha: np.ndarray) -> np.ndarray:++ """Foreground mask dilated by the misalignment margin."""++ from scipy.ndimage import distance_transform_edt++++ radius = max(1, round(MARGIN * alpha.shape[1]))++ return distance_transform_edt(alpha < FOREGROUND_ALPHA) <= radius++++++def remove_floaters(vertices: torch.Tensor, faces: torch.Tensor, camera: Mapping[str, Any],++ alpha: np.ndarray, device: str | None = None) -> tuple[torch.Tensor, torch.Tensor, dict[str, Any]]:++ """Drop disconnected components that project mostly outside the image foreground."""++ device = device or ("cuda" if torch.cuda.is_available() else "cpu")++ source_device = vertices.device++ vertices, faces = vertices.to(device), faces.to(device).long()++ face_labels, counts = _components(vertices, faces)++ report = {"components": int(len(counts)), "removed_components": 0, "removed_faces": 0, "faces": int(len(faces))}++ floating = None++ if len(counts) > 1:++ height, width = alpha.shape++ foreground = torch.from_numpy(_foreground(alpha)).to(device)++ uv, depth = _project(vertices[faces].mean(dim=1), camera)++ x = torch.floor(uv[:, 0] * width).long()++ y = torch.floor(uv[:, 1] * height).long()++ valid = (depth > 0) & (x >= 0) & (x < width) & (y >= 0) & (y < height)++ inside = torch.zeros_like(valid)++ inside[valid] = foreground[y[valid], x[valid]]++ inside_count = torch.bincount(face_labels, weights=inside.double(), minlength=len(counts))++ floating = inside_count < MIN_INSIDE * counts++ floating[torch.argmax(counts)] = False++ if floating is None or not bool(floating.any()):++ return vertices.to(source_device), faces.to(source_device), report++ kept_faces = faces[~floating[face_labels]]++ used, remap = torch.unique(kept_faces, return_inverse=True)++ report.update(removed_components=int(floating.sum()), removed_faces=int(counts[floating].sum()))++ return vertices[used].to(source_device), remap.reshape(kept_faces.shape).to(source_device), reportdiff --cc supratex/inference/mesh_export.pyindex 4e1066a,0000000..a23c3b3mode 100644,000000..100644--- a/supratex/inference/mesh_export.py+++ b/supratex/inference/mesh_export.py@@@ -1,372 -1,0 +1,372 @@@+# Copyright (c) Microsoft Corporation.- # Licensed under the MIT License; see LICENSE.++# Licensed under the MIT License; see THIRD_PARTY_NOTICES.md.+"""O-Voxel mesh export adapted for packed GPU texture postprocessing.++Geometry processing and baking follow TRELLIS.2's o-voxel/postprocess.py.+The local copy keeps export behavior independent of changes to the installed+O-Voxel package; only texture conversion and gap filling are adapted here.+"""+from typing import *+from tqdm import tqdm+import numpy as np+import torch+from PIL import Image+import trimesh+import trimesh.visual+from flex_gemm.ops.grid_sample import grid_sample_3d+import nvdiffrast.torch as dr+import cumesh++from .texture_export import prepare_texture_maps+++def _bake_in_chunks(attrs, mask, positions, *, vertices, faces, bvh, attr_volume,+ coords, grid_size, aabb, voxel_size, chunk_size=262144):+ """Bound BVH triangle and trilinear-query intermediates per atlas chunk."""+ rows = mask.flatten().nonzero().flatten()+ flattened = attrs.view(-1, attrs.shape[-1])+ sparse_coords = torch.cat([torch.zeros_like(coords[:, :1]), coords], dim=-1)+ shape = torch.Size([1, attr_volume.shape[1], *grid_size.tolist()])+ for start in range(0, positions.shape[0], chunk_size):+ stop = start + chunk_size+ _, face_id, uvw = bvh.unsigned_distance(positions[start:stop], return_uvw=True)+ triangle = vertices[faces[face_id.long()]]+ projected = (triangle * uvw.unsqueeze(-1)).sum(dim=1)+ flattened[rows[start:stop]] = grid_sample_3d(+ attr_volume, sparse_coords, shape=shape,+ grid=((projected - aabb[0]) / voxel_size).reshape(1, -1, 3),+ mode='trilinear',+ )+++def to_glb(+ vertices: torch.Tensor,+ faces: torch.Tensor,+ attr_volume: torch.Tensor,+ coords: torch.Tensor,+ attr_layout: Dict[str, slice],+ aabb: Union[list, tuple, np.ndarray, torch.Tensor],+ voxel_size: Union[float, list, tuple, np.ndarray, torch.Tensor] = None,+ grid_size: Union[int, list, tuple, np.ndarray, torch.Tensor] = None,+ decimation_target: int = 1000000,+ texture_size: int = 2048,+ remesh: bool = False,+ remesh_band: float = 1,+ remesh_project: float = 0.9,+ mesh_cluster_threshold_cone_half_angle_rad=np.radians(90.0),+ mesh_cluster_refine_iterations=0,+ mesh_cluster_global_iterations=1,+ mesh_cluster_smooth_strength=1,+ verbose: bool = False,+ use_tqdm: bool = False,+ low_vram: bool = False,+):+ """+ Convert an extracted mesh to a GLB file.+ Performs cleaning, optional remeshing, UV unwrapping, and texture baking from a volume.++ Args:+ vertices: (N, 3) tensor of vertex positions+ faces: (M, 3) tensor of vertex indices+ attr_volume: (L, C) features of a sprase tensor for attribute interpolation+ coords: (L, 3) tensor of coordinates for each voxel+ attr_layout: dictionary of slice objects for each attribute+ aabb: (2, 3) tensor of minimum and maximum coordinates of the volume+ voxel_size: (3,) tensor of size of each voxel+ grid_size: (3,) tensor of number of voxels in each dimension+ decimation_target: target number of vertices for mesh simplification+ texture_size: size of the texture for baking+ remesh: whether to perform remeshing+ remesh_band: size of the remeshing band+ remesh_project: projection factor for remeshing+ mesh_cluster_threshold_cone_half_angle_rad: threshold for cone-based clustering in uv unwrapping+ mesh_cluster_refine_iterations: number of iterations for refining clusters in uv unwrapping+ mesh_cluster_global_iterations: number of global iterations for clustering in uv unwrapping+ mesh_cluster_smooth_strength: strength of smoothing for clustering in uv unwrapping+ verbose: whether to print verbose messages+ use_tqdm: whether to use tqdm to display progress bar+ low_vram: keep the attribute volume on CPU during remeshing and bound+ BVH/attribute-query intermediates without changing atlas resolution+ """+ # --- Input Normalization (AABB, Voxel Size, Grid Size) ---+ normalization_device = 'cuda' if low_vram else coords.device+ if isinstance(aabb, (list, tuple)):+ aabb = np.array(aabb)+ if isinstance(aabb, np.ndarray):+ aabb = torch.tensor(aabb, dtype=torch.float32, device=normalization_device)+ if low_vram and isinstance(aabb, torch.Tensor):+ aabb = aabb.cuda()+ assert isinstance(aabb, torch.Tensor), f"aabb must be a list, tuple, np.ndarray, or torch.Tensor, but got {type(aabb)}"+ assert aabb.dim() == 2, f"aabb must be a 2D tensor, but got {aabb.shape}"+ assert aabb.size(0) == 2, f"aabb must have 2 rows, but got {aabb.size(0)}"+ assert aabb.size(1) == 3, f"aabb must have 3 columns, but got {aabb.size(1)}"++ # Calculate grid dimensions based on AABB and voxel size+ if voxel_size is not None:+ if isinstance(voxel_size, float):+ voxel_size = [voxel_size, voxel_size, voxel_size]+ if isinstance(voxel_size, (list, tuple)):+ voxel_size = np.array(voxel_size)+ if isinstance(voxel_size, np.ndarray):+ voxel_size = torch.tensor(voxel_size, dtype=torch.float32, device=normalization_device)+ if low_vram and isinstance(voxel_size, torch.Tensor):+ voxel_size = voxel_size.cuda()+ grid_size = ((aabb[1] - aabb[0]) / voxel_size).round().int()+ else:+ assert grid_size is not None, "Either voxel_size or grid_size must be provided"+ if isinstance(grid_size, int):+ grid_size = [grid_size, grid_size, grid_size]+ if isinstance(grid_size, (list, tuple)):+ grid_size = np.array(grid_size)+ if isinstance(grid_size, np.ndarray):+ grid_size = torch.tensor(grid_size, dtype=torch.int32, device=normalization_device)+ if low_vram and isinstance(grid_size, torch.Tensor):+ grid_size = grid_size.cuda()+ voxel_size = (aabb[1] - aabb[0]) / grid_size++ # Assertions for dimensions+ assert isinstance(voxel_size, torch.Tensor)+ assert voxel_size.dim() == 1 and voxel_size.size(0) == 3+ assert isinstance(grid_size, torch.Tensor)+ assert grid_size.dim() == 1 and grid_size.size(0) == 3++ if use_tqdm:+ pbar = tqdm(total=6, desc="Extracting GLB")+ if verbose:+ print(f"Original mesh: {vertices.shape[0]} vertices, {faces.shape[0]} faces")++ # Move data to GPU+ vertices = vertices.cuda()+ faces = faces.cuda()++ # Initialize CUDA mesh handler+ mesh = cumesh.CuMesh()+ mesh.init(vertices, faces)++ # --- Initial Mesh Cleaning ---+ # Fills holes as much as we can before processing+ mesh.fill_holes(max_hole_perimeter=3e-2)+ if verbose:+ print(f"After filling holes: {mesh.num_vertices} vertices, {mesh.num_faces} faces")+ vertices, faces = mesh.read()+ if use_tqdm:+ pbar.update(1)++ # Build BVH for the current mesh to guide remeshing+ if use_tqdm:+ pbar.set_description("Building BVH")+ if verbose:+ print(f"Building BVH for current mesh...", end='', flush=True)+ bvh = cumesh.cuBVH(vertices, faces)+ if use_tqdm:+ pbar.update(1)+ if verbose:+ print("Done")++ if use_tqdm:+ pbar.set_description("Cleaning mesh")+ if verbose:+ print("Cleaning mesh...")++ # --- Branch 1: Standard Pipeline (Simplification & Cleaning) ---+ if not remesh:+ # Step 1: Aggressive simplification (3x target)+ mesh.simplify(decimation_target * 3, verbose=verbose)+ if verbose:+ print(f"After inital simplification: {mesh.num_vertices} vertices, {mesh.num_faces} faces")++ # Step 2: Clean up topology (duplicates, non-manifolds, isolated parts)+ mesh.remove_duplicate_faces()+ mesh.repair_non_manifold_edges()+ mesh.remove_small_connected_components(1e-5)+ mesh.fill_holes(max_hole_perimeter=3e-2)+ if verbose:+ print(f"After initial cleanup: {mesh.num_vertices} vertices, {mesh.num_faces} faces")++ # Step 3: Final simplification to target count+ mesh.simplify(decimation_target, verbose=verbose)+ if verbose:+ print(f"After final simplification: {mesh.num_vertices} vertices, {mesh.num_faces} faces")++ # Step 4: Final Cleanup loop+ mesh.remove_duplicate_faces()+ mesh.repair_non_manifold_edges()+ mesh.remove_small_connected_components(1e-5)+ mesh.fill_holes(max_hole_perimeter=3e-2)+ if verbose:+ print(f"After final cleanup: {mesh.num_vertices} vertices, {mesh.num_faces} faces")++ # Step 5: Unify face orientations+ mesh.unify_face_orientations()++ # --- Branch 2: Remeshing Pipeline ---+ else:+ center = aabb.mean(dim=0)+ scale = (aabb[1] - aabb[0]).max().item()+ resolution = grid_size.max().item()++ # Perform Dual Contouring remeshing (rebuilds topology)+ mesh.init(*cumesh.remeshing.remesh_narrow_band_dc(+ vertices, faces,+ center = center,+ scale = (resolution + 3 * remesh_band) / resolution * scale,+ resolution = resolution,+ band = remesh_band,+ project_back = remesh_project, # Snaps vertices back to original surface+ verbose = verbose,+ bvh = bvh,+ ))+ if verbose:+ print(f"After remeshing: {mesh.num_vertices} vertices, {mesh.num_faces} faces")++ # Simplify and clean the remeshed result (similar logic to above)+ mesh.simplify(decimation_target, verbose=verbose)+ if verbose:+ print(f"After simplifying: {mesh.num_vertices} vertices, {mesh.num_faces} faces")++ if use_tqdm:+ pbar.update(1)+ if verbose:+ print("Done")+++ # --- UV Parameterization ---+ if use_tqdm:+ pbar.set_description("Parameterizing new mesh")+ if verbose:+ print("Parameterizing new mesh...")++ out_vertices, out_faces, out_uvs, out_vmaps = mesh.uv_unwrap(+ compute_charts_kwargs={+ "threshold_cone_half_angle_rad": mesh_cluster_threshold_cone_half_angle_rad,+ "refine_iterations": mesh_cluster_refine_iterations,+ "global_iterations": mesh_cluster_global_iterations,+ "smooth_strength": mesh_cluster_smooth_strength,+ },+ return_vmaps=True,+ verbose=verbose,+ )+ out_vertices = out_vertices.cuda()+ out_faces = out_faces.cuda()+ out_uvs = out_uvs.cuda()+ out_vmaps = out_vmaps.cuda()+ mesh.compute_vertex_normals()+ out_normals = mesh.read_vertex_normals()[out_vmaps]+ if low_vram:+ del mesh, out_vmaps+ torch.cuda.empty_cache()++ if use_tqdm:+ pbar.update(1)+ if verbose:+ print("Done")++ # --- Texture Baking (Attribute Sampling) ---+ if use_tqdm:+ pbar.set_description("Sampling attributes")+ if verbose:+ print("Sampling attributes...", end='', flush=True)++ # Setup differentiable rasterizer context+ ctx = dr.RasterizeCudaContext()+ # Prepare UV coordinates for rasterization (rendering in UV space)+ uvs_rast = torch.cat([out_uvs * 2 - 1, torch.zeros_like(out_uvs[:, :1]), torch.ones_like(out_uvs[:, :1])], dim=-1).unsqueeze(0)+ rast = torch.zeros((1, texture_size, texture_size, 4), device='cuda', dtype=torch.float32)++ # Rasterize in chunks to save memory+ for i in range(0, out_faces.shape[0], 100000):+ rast_chunk, _ = dr.rasterize(+ ctx, uvs_rast, out_faces[i:i+100000],+ resolution=[texture_size, texture_size],+ )+ mask_chunk = rast_chunk[..., 3:4] > 0+ rast_chunk[..., 3:4] += i # Store face ID in alpha channel+ rast = torch.where(mask_chunk, rast_chunk, rast)+ if low_vram and out_faces.shape[0]:+ del rast_chunk, mask_chunk++ # Mask of valid pixels in texture+ mask = rast[0, ..., 3] > 0++ # Interpolate 3D positions in UV space (finding 3D coord for every texel)+ pos = dr.interpolate(out_vertices.unsqueeze(0), rast, out_faces)[0][0]+ valid_pos = pos[mask]+ if low_vram:+ del pos, rast, uvs_rast, ctx+ torch.cuda.empty_cache()++ # Map these positions back to the *original* high-res mesh to get accurate attributes+ # This corrects geometric errors introduced by simplification/remeshing+ # Trilinear sampling from the attribute volume (Color, Material props)+ if low_vram:+ attrs = torch.zeros(texture_size, texture_size, attr_volume.shape[1], device='cuda')+ attr_volume, coords = attr_volume.cuda(), coords.cuda()+ _bake_in_chunks(attrs, mask, valid_pos, vertices=vertices, faces=faces, bvh=bvh,+ attr_volume=attr_volume, coords=coords, grid_size=grid_size,+ aabb=aabb, voxel_size=voxel_size)+ del attr_volume, coords, valid_pos, bvh, vertices, faces+ torch.cuda.empty_cache()+ else:+ _, face_id, uvw = bvh.unsigned_distance(valid_pos, return_uvw=True)+ orig_tri_verts = vertices[faces[face_id.long()]] # (N_new, 3, 3)+ valid_pos = (orig_tri_verts * uvw.unsqueeze(-1)).sum(dim=1)+ attrs = torch.zeros(texture_size, texture_size, attr_volume.shape[1], device='cuda')+ attrs[mask] = grid_sample_3d(+ attr_volume,+ torch.cat([torch.zeros_like(coords[:, :1]), coords], dim=-1),+ shape=torch.Size([1, attr_volume.shape[1], *grid_size.tolist()]),+ grid=((valid_pos - aabb[0]) / voxel_size).reshape(1, -1, 3),+ mode='trilinear',+ )+ if use_tqdm:+ pbar.update(1)+ if verbose:+ print("Done")++ # --- Texture Post-Processing & Material Construction ---+ if use_tqdm:+ pbar.set_description("Finalizing mesh")+ if verbose:+ print("Finalizing mesh...", end='', flush=True)++ base_color, metallic, roughness, alpha = prepare_texture_maps(attrs, mask, attr_layout)+ alpha_mode = 'OPAQUE'++ # Create PBR material+ # Standard PBR packs Metallic and Roughness into Blue and Green channels+ material = trimesh.visual.material.PBRMaterial(+ baseColorTexture=Image.fromarray(np.concatenate([base_color, alpha], axis=-1)),+ baseColorFactor=np.array([255, 255, 255, 255], dtype=np.uint8),+ metallicRoughnessTexture=Image.fromarray(np.concatenate([np.zeros_like(metallic), roughness, metallic], axis=-1)),+ metallicFactor=1.0,+ roughnessFactor=1.0,+ alphaMode=alpha_mode,+ doubleSided=True if not remesh else False,+ )++ # --- Coordinate System Conversion & Final Object ---+ vertices_np = out_vertices.cpu().numpy()+ faces_np = out_faces.cpu().numpy()+ uvs_np = out_uvs.cpu().numpy()+ normals_np = out_normals.cpu().numpy()++ # Swap Y and Z axes, invert Y (common conversion for GLB compatibility)+ vertices_np[:, 1], vertices_np[:, 2] = vertices_np[:, 2], -vertices_np[:, 1]+ normals_np[:, 1], normals_np[:, 2] = normals_np[:, 2], -normals_np[:, 1]+ uvs_np[:, 1] = 1 - uvs_np[:, 1] # Flip UV V-coordinate++ textured_mesh = trimesh.Trimesh(+ vertices=vertices_np,+ faces=faces_np,+ vertex_normals=normals_np,+ process=False,+ visual=trimesh.visual.TextureVisuals(uv=uvs_np, material=material)+ )++ if use_tqdm:+ pbar.update(1)+ pbar.close()+ if verbose:+ print("Done")++ return textured_meshdiff --cc supratex/inference/native_observation.pyindex 882ffab,0000000..e3a9118mode 100644,000000..100644--- a/supratex/inference/native_observation.py+++ b/supratex/inference/native_observation.py@@@ -1,364 -1,0 +1,413 @@@+"""Visible-surface material observations for Supra-Tex inference.++This module owns the public pixel-first DDA visibility contract. It has no+dataset, scheduler, or training dependency.+"""+from __future__ import annotations++import math+from typing import Any++import numpy as np+import torch++RESOLUTION = 1024+LATENT_RESOLUTION = 64+++def build_occupancy_index(coords: torch.Tensor) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ """Return an exact packed occupancy bitset and sorted row map."""+ values = coords.detach().cpu().numpy().astype(np.int64, copy=False)+ if values.ndim != 2 or values.shape[1] != 3:+ raise ValueError("surface coordinates must have shape [N,3]")+ if values.size and (values.min() < 0 or values.max() >= RESOLUTION):+ raise ValueError("surface coordinates are outside the material volume")+ keys = (values[:, 0] * RESOLUTION + values[:, 1]) * RESOLUTION + values[:, 2]+ order = np.argsort(keys)+ ordered = keys[order]+ if ordered.size > 1 and np.any(ordered[1:] == ordered[:-1]):+ raise ValueError("surface coordinates contain duplicate cells")+ bits = np.zeros((RESOLUTION ** 3 + 7) // 8, dtype=np.uint8)+ if keys.size:+ np.bitwise_or.at(bits, keys >> 3, np.left_shift(np.uint8(1), (keys & 7).astype(np.uint8)))+ return bits, ordered, order.astype(np.int64, copy=False)+++_DDA_BATCH_KERNEL: Any | None = None++def _dda_batch_kernel() -> Any:+ """Lazily compile the CPU DDA kernel so mesh-depth mode needs no Numba."""+ global _DDA_BATCH_KERNEL+ if _DDA_BATCH_KERNEL is not None:+ return _DDA_BATCH_KERNEL+ try:+ import numba+ except ImportError as error:+ raise RuntimeError("pixel_dda visibility requires numba") from error++ @numba.njit(parallel=True, cache=True)+ def kernel(+ ray_origin: np.ndarray,+ ray_directions: np.ndarray,+ occupancy_bits: np.ndarray,+ grid_min: float,+ grid_max: float,+ resolution: int,+ ) -> tuple[np.ndarray, np.ndarray]:+ ray_count = ray_directions.shape[0]+ owners = np.full((ray_count, 3), -1, dtype=np.int32)+ reasons = np.full(ray_count, 3, dtype=np.uint8)+ # Per-ray count of multi-axis (diagonal) steps. Written only at+ # ray_index, so prange stays race-free; summed by the caller.+ ties = np.zeros(ray_count, dtype=np.int64)+ cell_size = (grid_max - grid_min) / resolution+ slab_epsilon = 1e-14+ tie_epsilon = 1e-12++ for ray_index in numba.prange(ray_count):+ direction = ray_directions[ray_index]+ valid_ray = True+ for axis in range(3):+ if not np.isfinite(ray_origin[axis]) or not np.isfinite(direction[axis]):+ valid_ray = False+ if not valid_ray:+ continue+ if (+ abs(direction[0]) < slab_epsilon+ and abs(direction[1]) < slab_epsilon+ and abs(direction[2]) < slab_epsilon+ ):+ continue++ t_entry = -np.inf+ t_exit = np.inf+ intersects = True+ for axis in range(3):+ component = direction[axis]+ if abs(component) < slab_epsilon:+ if ray_origin[axis] < grid_min or ray_origin[axis] > grid_max:+ intersects = False+ break+ else:+ t1 = (grid_min - ray_origin[axis]) / component+ t2 = (grid_max - ray_origin[axis]) / component+ if t1 > t2:+ temporary = t1+ t1 = t2+ t2 = temporary+ if t1 > t_entry:+ t_entry = t1+ if t2 < t_exit:+ t_exit = t2+ if not intersects or t_entry > t_exit or t_exit < 0.0:+ reasons[ray_index] = 2+ continue++ t_start = max(t_entry, 0.0)+ # Enter the half-open grid interior deterministically. This avoids+ # floor(1024) for a ray entering exactly through the +AABB face.+ entry_epsilon = max(1e-12, abs(t_start) * 1e-12)+ point = ray_origin + (t_start + entry_epsilon) * direction+ current = np.empty(3, dtype=np.int32)+ step = np.zeros(3, dtype=np.int32)+ t_delta = np.full(3, np.inf, dtype=np.float64)+ t_max = np.full(3, np.inf, dtype=np.float64)+ for axis in range(3):+ cell = int(math.floor((point[axis] - grid_min) / cell_size))+ if cell < 0:+ cell = 0+ elif cell >= resolution:+ cell = resolution - 1+ current[axis] = cell+ component = direction[axis]+ if component > slab_epsilon:+ step[axis] = 1+ boundary = grid_min + (cell + 1) * cell_size+ t_max[axis] = (boundary - ray_origin[axis]) / component+ t_delta[axis] = cell_size / component+ elif component < -slab_epsilon:+ step[axis] = -1+ boundary = grid_min + cell * cell_size+ t_max[axis] = (boundary - ray_origin[axis]) / component+ t_delta[axis] = -cell_size / component++ max_steps = 3 * resolution + 3+ for _ in range(max_steps):+ key = (+ (np.int64(current[0]) * resolution + current[1]) * resolution+ + current[2]+ )+ byte_value = occupancy_bits[key >> 3]+ if byte_value & (1 << (key & 7)):+ owners[ray_index, 0] = current[0]+ owners[ray_index, 1] = current[1]+ owners[ray_index, 2] = current[2]+ reasons[ray_index] = 0+ break++ next_t = min(t_max[0], t_max[1], t_max[2])+ if not np.isfinite(next_t) or next_t > t_exit + tie_epsilon:+ reasons[ray_index] = 1+ break+ tolerance = tie_epsilon * max(1.0, abs(next_t))+ in_bounds = True+ # Step all axes crossed at the same ray parameter. This is the+ # half-open tie rule for edge/corner hits and is deterministic.+ crossed = 0+ for axis in range(3):+ if abs(t_max[axis] - next_t) <= tolerance:+ crossed += 1+ current[axis] += step[axis]+ t_max[axis] += t_delta[axis]+ if current[axis] < 0 or current[axis] >= resolution:+ in_bounds = False+ # A multi-axis step is a diagonal move, so it can skip cells that+ # share only an edge or corner. The rule is frozen and fixture+ # verified; count the events so the magnitude is known over a+ # full corpus (~2e12 rays) instead of assumed negligible.+ if crossed > 1:+ ties[ray_index] += 1+ if not in_bounds:+ reasons[ray_index] = 1+ break++ return owners, reasons, ties++ _DDA_BATCH_KERNEL = kernel+ return _DDA_BATCH_KERNEL++- def pixel_first_occupied(camera: dict[str, Any], occupancy: np.ndarray, trusted: torch.Tensor, depth_edge_rtol: float = 0.04) -> torch.Tensor:++# Optional admission rules, off by default. On well-aligned demo inputs they++# removed 3-10% of trusted pixels without a visible change, so the released++# behavior keeps only the depth-discontinuity rule.++SILHOUETTE_MARGIN = 0++GRAZING_COS = 0.0++++++def _admitted_pixels(depth: np.ndarray, missed: np.ndarray, focal: tuple[float, float], depth_edge_rtol: float,++ silhouette_margin: int = SILHOUETTE_MARGIN, grazing_cos: float = GRAZING_COS,++ stats: dict | None = None) -> np.ndarray:++ """Return pixels whose first-hit depth is a reliable observation.++++ ``depth`` is the first-hit view depth (NaN without a trusted hit) and++ ``missed`` marks trusted rays that left the volume, i.e. the image++ foreground outside the geometry silhouette. A local depth discontinuity++ always rejects a pixel. Two optional rules can also reject pixels near the++ geometry silhouette (``silhouette_margin`` pixels), where image/geometry++ misalignment lands colors on the wrong surface, and at grazing incidence++ (cosine below ``grazing_cos``, from the screen-space depth slope), where one++ pixel stretches over a large surface area.++ """++ import torch.nn.functional as F++++ masked = torch.from_numpy(depth)++ local_max = F.max_pool2d(masked.nan_to_num(-torch.inf)[None, None], 3, 1, 1)[0, 0]++ local_min = -F.max_pool2d((-masked).nan_to_num(-torch.inf)[None, None], 3, 1, 1)[0, 0]++ relative = ((local_max - local_min) / masked).nan_to_num(nan=0., posinf=0., neginf=0.)++ edge = relative.numpy() > depth_edge_rtol++ near_silhouette = np.zeros_like(edge)++ if silhouette_margin > 0 and missed.any():++ size = 2 * silhouette_margin + 1++ near_silhouette = F.max_pool2d(torch.from_numpy(missed).float()[None, None], size, 1, silhouette_margin)[0, 0].numpy() > 0++ grazing = np.zeros_like(edge)++ if grazing_cos > 0:++ # Central differences in pixels; a missing neighbour leaves NaN and is++ # not rejected here. Dividing by the pixel footprint (depth / focal)++ # turns the depth change into the surface slope along each image axis.++ dz_dx = np.full_like(depth, np.nan)++ dz_dy = np.full_like(depth, np.nan)++ dz_dx[:, 1:-1] = (depth[:, 2:] - depth[:, :-2]) * .5++ dz_dy[1:-1, :] = (depth[2:, :] - depth[:-2, :]) * .5++ with np.errstate(invalid="ignore", divide="ignore"):++ slope2 = (dz_dx * np.float32(focal[0]) / depth) ** 2 + (dz_dy * np.float32(focal[1]) / depth) ** 2++ grazing = slope2 > np.float32(1 / grazing_cos ** 2 - 1)++ hit = ~np.isnan(depth)++ admitted = hit & ~edge & ~near_silhouette & ~grazing++ if stats is not None:++ stats.update(trusted_rays=int(hit.sum() + missed.sum()), first_hits=int(hit.sum()),++ rejected_depth_edge=int((hit & edge).sum()),++ rejected_silhouette=int((hit & ~edge & near_silhouette).sum()),++ rejected_grazing=int((hit & ~edge & ~near_silhouette & grazing).sum()),++ admitted=int(admitted.sum()))++ return admitted++++++def pixel_first_occupied(camera: dict[str, Any], occupancy: np.ndarray, trusted: torch.Tensor, depth_edge_rtol: float = 0.04,++ stats: dict | None = None) -> torch.Tensor:+ """Map trusted camera pixels to their first occupied volume cell."""+ if "extrinsic" in camera:- return pixel_first_occupied_cv(camera, occupancy, trusted, depth_edge_rtol)++ return pixel_first_occupied_cv(camera, occupancy, trusted, depth_edge_rtol, stats=stats)+ if trusted.shape != (RESOLUTION, RESOLUTION):+ raise ValueError("trusted alpha mask must be 1024 by 1024")+ if "camera_angle_x" not in camera or "distance" not in camera:+ raise ValueError("camera must supply camera_angle_x and distance")+ ys, xs = torch.nonzero(trusted, as_tuple=True)+ x, y = xs.cpu().numpy(), ys.cpu().numpy()+ focal = 16.0 / math.tan(float(camera["camera_angle_x"]) / 2.0) * RESOLUTION / 32.0+ directions = np.column_stack(((x + .5 - RESOLUTION / 2) / focal, -(y + .5 - RESOLUTION / 2) / focal, -np.ones_like(x))).astype(np.float64)+ origin = np.array([0.0, 0.0, float(camera["distance"]) * float(camera.get("mesh_scale", 1.0))], dtype=np.float64)+ owners, reasons, _ties = _dda_batch_kernel()(origin, directions, occupancy, -0.5, 0.5, RESOLUTION)+ hit_mask = reasons == 0+ hit = owners[hit_mask]+ if not hit.size:+ raise RuntimeError("no trusted pixels intersect the material volume")- # Preserve the production first-hit-depth admission gate. It removes- # pixels at local internal-occlusion jumps before their owner cells become- # observations; applying it after unique-owner reduction would be wrong.- import torch.nn.functional as F++ # Admission runs per pixel, before owner cells are deduplicated; applying++ # it after unique-owner reduction would be wrong.+ depth = np.full((RESOLUTION, RESOLUTION), np.nan, dtype=np.float32)+ hit_depth = origin[2] - ((hit[:, 2].astype(np.float64) + .5) / RESOLUTION - .5)+ depth[y[hit_mask], x[hit_mask]] = hit_depth.astype(np.float32)- values = torch.from_numpy(depth)- valid = torch.from_numpy(~np.isnan(depth))- masked = torch.where(valid, values, torch.nan)- local_max = F.max_pool2d(masked.nan_to_num(-torch.inf)[None, None], 3, 1, 1)[0, 0]- local_min = -F.max_pool2d((-masked).nan_to_num(-torch.inf)[None, None], 3, 1, 1)[0, 0]- relative = ((local_max - local_min) / masked).nan_to_num(nan=0., posinf=0., neginf=0.)++ missed = np.zeros((RESOLUTION, RESOLUTION), dtype=bool)++ missed[y[~hit_mask], x[~hit_mask]] = True++ admitted = _admitted_pixels(depth, missed, (focal, focal), depth_edge_rtol, stats=stats)+ retained = hit_mask.copy()- retained[hit_mask] &= ~((relative.numpy() > depth_edge_rtol)[y[hit_mask], x[hit_mask]])++ retained[hit_mask] &= admitted[y[hit_mask], x[hit_mask]]+ hit = owners[retained]+ if not hit.size:- raise RuntimeError("depth-edge admission removed every first-hit observation")++ raise RuntimeError("observation admission removed every first-hit observation")+ keys = np.unique((hit[:, 0].astype(np.int64) * RESOLUTION + hit[:, 1]) * RESOLUTION + hit[:, 2])+ return torch.from_numpy(np.stack((keys // (RESOLUTION * RESOLUTION), (keys // RESOLUTION) % RESOLUTION, keys % RESOLUTION), axis=1).astype(np.int32))+++def camera_rays(camera: dict[str, Any], ys: np.ndarray, xs: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ """Build pixel-center rays from a complete OpenCV world-to-camera pose."""+ extrinsic = np.asarray(camera["extrinsic"], dtype=np.float64)+ intrinsic = np.asarray(camera.get("projection_intrinsic", camera.get("intrinsic")), dtype=np.float64)+ if extrinsic.shape != (4, 4) or intrinsic.shape != (3, 3):+ raise ValueError("DDA camera requires 4x4 extrinsic and normalized 3x3 intrinsic")+ if not np.isfinite(extrinsic).all() or not np.isfinite(intrinsic).all():+ raise ValueError("DDA camera matrices must be finite")+ rotation = extrinsic[:3, :3]+ if (not np.allclose(rotation @ rotation.T, np.eye(3), atol=1e-6, rtol=0)+ or not np.isclose(np.linalg.det(rotation), 1, atol=1e-6)+ or not np.allclose(extrinsic[3], [0, 0, 0, 1], atol=1e-8, rtol=0)):+ raise ValueError("DDA camera must contain a rigid world-to-camera transform")+ if (intrinsic[0, 0] <= 0 or intrinsic[1, 1] <= 0+ or not np.allclose(intrinsic[[0, 1, 2, 2], [1, 0, 0, 1]], 0, atol=1e-10)+ or intrinsic[2, 2] != 1):+ raise ValueError("DDA requires positive focal lengths and an unskewed normalized intrinsic")+ eye = np.ascontiguousarray(-rotation.T @ extrinsic[:3, 3])+ x = (xs.astype(np.float64) + .5 - intrinsic[0, 2] * RESOLUTION) / (intrinsic[0, 0] * RESOLUTION)+ y = (ys.astype(np.float64) + .5 - intrinsic[1, 2] * RESOLUTION) / (intrinsic[1, 1] * RESOLUTION)+ directions = np.ascontiguousarray(np.stack((x, y, np.ones_like(x)), axis=1) @ rotation)+ return eye, directions, rotation+++def pixel_hits_cv(camera: dict[str, Any], occupancy: np.ndarray, mask: np.ndarray) -> np.ndarray:+ """Return the raw first-hit silhouette, without trusted-mask depth filtering."""+ if mask.shape != (RESOLUTION, RESOLUTION) or mask.dtype != np.bool_:+ raise ValueError("DDA pixel mask must be a boolean observation-resolution image")+ ys, xs = np.nonzero(mask)+ eye, directions, _ = camera_rays(camera, ys, xs)+ _, reasons, _ = _dda_batch_kernel()(eye, directions, occupancy, -.5, .5, RESOLUTION)+ hits = np.zeros_like(mask)+ hits[ys[reasons == 0], xs[reasons == 0]] = True+ return hits+++def pixel_first_occupied_cv(camera: dict[str, Any], occupancy: np.ndarray, trusted: torch.Tensor,- depth_edge_rtol: float = .04) -> torch.Tensor:- """Apply the production first-hit and depth-edge rules to a full CV camera."""- import torch.nn.functional as F-++ depth_edge_rtol: float = .04, stats: dict | None = None) -> torch.Tensor:++ """Apply the production first-hit admission rules to a full CV camera."""+ if trusted.shape != (RESOLUTION, RESOLUTION) or trusted.dtype != torch.bool:+ raise ValueError("trusted alpha must be a boolean observation-resolution image")+ if not math.isfinite(depth_edge_rtol) or depth_edge_rtol < 0:+ raise ValueError("depth-edge tolerance must be finite and nonnegative")+ ys, xs = np.nonzero(trusted.detach().cpu().numpy())+ if not ys.size:+ raise RuntimeError("trusted alpha gate leaves no camera rays")+ eye, directions, rotation = camera_rays(camera, ys, xs)+ owners, reasons, _ = _dda_batch_kernel()(eye, directions, occupancy, -.5, .5, RESOLUTION)+ hits = reasons == 0+ if not hits.any():+ raise RuntimeError("no trusted pixels intersect the material volume")+ centers = (owners[hits].astype(np.float64) + .5) / RESOLUTION - .5+ hit_depth = ((centers - eye) @ rotation.T)[:, 2]+ if not np.isfinite(hit_depth).all() or not (hit_depth > 0).all():+ raise RuntimeError("first-hit owners must lie in front of the camera")+ depth = np.full((RESOLUTION, RESOLUTION), np.nan, dtype=np.float32)+ depth[ys[hits], xs[hits]] = hit_depth.astype(np.float32)- masked = torch.from_numpy(depth)- local_max = F.max_pool2d(masked.nan_to_num(-torch.inf)[None, None], 3, 1, 1)[0, 0]- local_min = -F.max_pool2d((-masked).nan_to_num(-torch.inf)[None, None], 3, 1, 1)[0, 0]- relative = ((local_max - local_min) / masked).nan_to_num(nan=0., posinf=0., neginf=0.)- retained = hits & ~(relative.numpy() > depth_edge_rtol)[ys, xs]++ missed = np.zeros((RESOLUTION, RESOLUTION), dtype=bool)++ missed[ys[~hits], xs[~hits]] = True++ intrinsic = np.asarray(camera.get("projection_intrinsic", camera.get("intrinsic")), dtype=np.float64)++ focal = (float(intrinsic[0, 0]) * RESOLUTION, float(intrinsic[1, 1]) * RESOLUTION)++ retained = hits & _admitted_pixels(depth, missed, focal, depth_edge_rtol, stats=stats)[ys, xs]+ kept = owners[retained].astype(np.int64, copy=False)+ if not kept.size:- raise RuntimeError("depth-edge admission removed every first-hit observation")++ raise RuntimeError("observation admission removed every first-hit observation")+ keys = np.unique((kept[:, 0] * RESOLUTION + kept[:, 1]) * RESOLUTION + kept[:, 2])+ return torch.from_numpy(np.stack((keys // (RESOLUTION * RESOLUTION),+ keys // RESOLUTION % RESOLUTION,+ keys % RESOLUTION), axis=1).astype(np.int32))+++def owner_rows(coords: torch.Tensor, owners: torch.Tensor, ordered: np.ndarray, order: np.ndarray) -> torch.Tensor:+ values = owners.cpu().numpy().astype(np.int64, copy=False)+ keys = (values[:, 0] * RESOLUTION + values[:, 1]) * RESOLUTION + values[:, 2]+ positions = np.searchsorted(ordered, keys)+ if positions.size and (np.any(positions >= ordered.size) or np.any(ordered[positions] != keys)):+ raise RuntimeError("visible owner is absent from the surface support")+ result = torch.zeros(coords.shape[0], dtype=torch.bool, device=coords.device)+ if positions.size:+ result[torch.as_tensor(order[positions], device=coords.device)] = True+ return result+++def boundary_distance_to_unobserved(surface_counts: torch.Tensor, observed_counts: torch.Tensor) -> torch.Tensor:+ """Exact sparse six-neighbour distance used by the observation message."""+ active = (surface_counts > 0).reshape(LATENT_RESOLUTION, LATENT_RESOLUTION, LATENT_RESOLUTION)+ observed = (observed_counts > 0).reshape_as(active)+ distance = torch.full(active.shape, -1, dtype=torch.int16, device=active.device)+ frontier = active & ~observed+ distance[frontier] = 0+ step = 0+ while bool(frontier.any()):+ expanded = torch.zeros_like(frontier)+ expanded[1:] |= frontier[:-1]; expanded[:-1] |= frontier[1:]+ expanded[:, 1:] |= frontier[:, :-1]; expanded[:, :-1] |= frontier[:, 1:]+ expanded[:, :, 1:] |= frontier[:, :, :-1]; expanded[:, :, :-1] |= frontier[:, :, 1:]+ frontier = expanded & active & (distance < 0)+ if not bool(frontier.any()):+ break+ step += 1+ distance[frontier] = step+ return distance.reshape(-1)+++def encode_partial(encoder: Any, coords: torch.Tensor, visible: torch.Tensor, rgb: torch.Tensor, mra: torch.Tensor, shape_coords: torch.Tensor, normalization: dict[str, Any], sparse: Any, device: str) -> Any:+ """Encode visible PBR rows into the frozen 34-channel observation message."""+ selected = coords[visible]+ features = torch.cat((rgb[visible], mra[visible]), dim=1).clamp(0, 1).float() * 2.0 - 1.0+ encoded = encoder(sparse.SparseTensor(features, torch.cat((torch.zeros_like(selected[:, :1]), selected), dim=1).int()), sample_posterior=False)+ raw = encoded.feats.float()+ if raw.ndim != 2 or raw.shape[1] != 32:+ raise RuntimeError("material encoder must emit 32 channels")+ blocks = coords // (RESOLUTION // LATENT_RESOLUTION)+ keys = (blocks[:, 0] * LATENT_RESOLUTION + blocks[:, 1]) * LATENT_RESOLUTION + blocks[:, 2]+ all_counts = torch.bincount(keys, minlength=LATENT_RESOLUTION ** 3)+ observed_counts = torch.bincount(keys[visible], minlength=LATENT_RESOLUTION ** 3)+ xyz = encoded.coords[:, 1:].long()+ latent_keys = (xyz[:, 0] * LATENT_RESOLUTION + xyz[:, 1]) * LATENT_RESOLUTION + xyz[:, 2]+ # The bounded grid already has exact occupancy counts. Enumerate occupied+ # keys instead of sorting millions of three-column surface coordinates.+ # Linear-key order is the same lexicographic order as unique(..., dim=0).+ expected_observed = torch.nonzero(observed_counts, as_tuple=False).flatten()+ if (bool(((xyz < 0) | (xyz >= LATENT_RESOLUTION)).any())+ or not torch.equal(torch.sort(latent_keys).values, expected_observed)):+ raise RuntimeError("encoded observation support differs from floor(visible_surface/16)")+ coverage = (observed_counts[latent_keys].float() / all_counts[latent_keys].float()).unsqueeze(1)+ expected_keys = torch.nonzero(all_counts, as_tuple=False).flatten()+ shape_xyz = shape_coords.long()+ shape_keys = (shape_xyz[:, 0] * LATENT_RESOLUTION + shape_xyz[:, 1]) * LATENT_RESOLUTION + shape_xyz[:, 2]+ sorted_shape = torch.sort(shape_keys).values+ if expected_keys.shape[0] != shape_keys.shape[0] or not torch.equal(expected_keys, sorted_shape):+ raise RuntimeError("pooled material support does not exactly match the shape latent support")+ positions = torch.searchsorted(sorted_shape, latent_keys)+ if bool((positions >= sorted_shape.shape[0]).any()) or not torch.equal(sorted_shape[positions], latent_keys):+ raise RuntimeError("encoded observation support is not a subset of full material support")+ boundary = boundary_distance_to_unobserved(all_counts, observed_counts)[latent_keys].to(dtype=coverage.dtype).unsqueeze(1)+ if bool((boundary == 0).any()) or bool((boundary < -1).any()):+ raise RuntimeError("invalid observed material boundary distance")+ mean = torch.as_tensor(normalization["mean"], dtype=raw.dtype, device=device).reshape(1, 32)+ std = torch.as_tensor(normalization["std"], dtype=raw.dtype, device=device).reshape(1, 32)+ if mean.shape[1] != 32 or std.shape[1] != 32 or not bool(torch.isfinite(std).all()) or not bool((std > 0).all()):+ raise ValueError("partial observation normalization must provide 32 finite positive standard deviations")+ return sparse.SparseTensor(torch.cat(((raw - mean) / std, coverage, boundary), dim=1), encoded.coords.int())diff --cc supratex/inference/pipeline.pyindex 7fd4be0,0000000..d7d526bmode 100644,000000..100644--- a/supratex/inference/pipeline.py+++ b/supratex/inference/pipeline.py@@@ -1,541 -1,0 +1,690 @@@+"""Observation-guided PBR completion and GLB export.++The public boundary begins with a mesh/camera/RGBA observation plus albedo and+MRA maps. Geometry prediction and 2D map prediction intentionally remain+outside this inference-only package.+"""+from __future__ import annotations++import json+import math+import os++import sys+from contextlib import contextmanager+from pathlib import Path+from typing import Any, Mapping++from . import native_observation+from .checkpoint import load_completion_state_dict, validate_completion_checkpoint++RESOLUTION = native_observation.RESOLUTION+LAYOUT = {"base_color": slice(0, 3), "metallic": slice(3, 4), "roughness": slice(4, 5), "alpha": slice(5, 6)}+# Released completion-model ABI. It is checked once, when the config is loaded.+MODEL_ABI = {"in_channels": 64, "out_channels": 32, "cond_channels": 0, "model_channels": 1536,+ "num_heads": 12, "num_blocks": 60, "base_block_policy": "alternating_u_x",+ "v11_init_policy": "odd_copy_even_identity", "direct_modulation_broadcast": True,+ "rope_freq": [1, 10000], "dtype": "float32"}+++def _file(path: str | Path, label: str) -> Path:+ value = Path(path)+ if not value.is_file():+ raise FileNotFoundError(f"missing {label}: {value}")+ return value+++def _normalization(value: Any, label: str) -> dict[str, list[float]]:+ if not isinstance(value, Mapping):+ raise ValueError(f"{label} normalization must be an object")+ result: dict[str, list[float]] = {}+ for key in ("mean", "std"):+ raw = value.get(key)+ if not isinstance(raw, list) or len(raw) != 32:+ raise ValueError(f"{label} normalization requires 32-value {key}")+ result[key] = [float(item) for item in raw]+ if not all(math.isfinite(item) for item in result["mean"] + result["std"]) or any(item <= 0 for item in result["std"]):+ raise ValueError(f"{label} normalization standard deviations must be positive")+ return result+++def load_contract(model_config: str | Path, checkpoint: str | Path) -> tuple[dict[str, Any], dict[str, Any], Path]:+ """Load the public model ABI without inspecting or hashing weight bytes."""+ config_path, checkpoint_path = _file(model_config, "model config"), _file(checkpoint, "checkpoint")+ try:+ config = json.loads(config_path.read_text(encoding="utf-8"))+ dataset = config["dataset"]["args"]+ model = config["models"]["denoiser"]+ args = model["args"]+ except (OSError, KeyError, TypeError, json.JSONDecodeError) as error:+ raise ValueError("model config does not satisfy the Supra-Tex inference ABI") from error+ if config.get("format") == "supratex_completion" and config.get("schema_version") != 1:+ raise ValueError("unsupported Supra-Tex completion config schema_version")+ if model.get("name") != "InterleavedFlowTransformer":+ raise ValueError("model config must select InterleavedFlowTransformer")+ if int(dataset.get("resolution", -1)) != RESOLUTION or dataset.get("attrs") != ["base_color", "metallic", "roughness", "alpha"]:+ raise ValueError("model config must describe 1024 base-color/metallic/roughness/alpha inputs")+ mismatched = {key: args.get(key) for key, expected in MODEL_ABI.items() if args.get(key) != expected}+ if mismatched:+ raise ValueError(f"model config does not match the released completion ABI: {mismatched}")+ if dataset.get("bridge_z_obs_args", {}).get("partial_support_mode") != "partial_messages":+ raise ValueError("model config requires partial observation messages")+ _normalization(dataset.get("shape_slat_normalization"), "shape")+ material = _normalization(dataset.get("pbr_slat_normalization"), "material")+ for key in ("pbr_mean", "pbr_std"):+ expected = material["mean" if key.endswith("mean") else "std"]+ if [float(value) for value in args.get(key, [])] != expected:+ raise ValueError(f"model {key} must exactly match material normalization")+ return config, dataset, checkpoint_path+++def _stem(path: str | Path, label: str) -> Path:+ stem = Path(path)+ _file(Path(f"{stem}.json"), f"{label} config")+ _file(Path(f"{stem}.safetensors"), f"{label} weights")+ return stem+++def load_completion_contract(model_config: str | Path, checkpoint: str | Path) -> tuple[dict[str, Any], dict[str, Any], Path, dict[str, list[float]]]:+ """Validate the model ABI and observation statistics without loading weights."""+ config, dataset, checkpoint_path = load_contract(model_config, checkpoint)+ validate_completion_checkpoint(checkpoint_path)+ path = Path(dataset["bridge_z_obs_args"]["partial_z_obs_normalization_path"])+ if not path.is_absolute():+ path = Path(model_config).expanduser().absolute().parent / path+ partial_stats = _normalization(json.loads(_file(path, "partial normalization").read_text(encoding="utf-8")), "partial observation")+ model_args = config["models"]["denoiser"]["args"]+ for key in ("partial_mean", "partial_std"):+ expected = partial_stats["mean" if key.endswith("mean") else "std"]+ if [float(value) for value in model_args.get(key, [])] != expected:+ raise ValueError(f"model {key} must exactly match partial-observation normalization")+ return config, dataset, checkpoint_path, partial_stats+++def _completion_vae_root(trellis_root: str | Path) -> Path:+ root = Path(trellis_root).expanduser()+ return root / "ckpts" if (root / "ckpts").is_dir() else root+++def completion_decoder_stems(config: Mapping[str, Any], dataset: Mapping[str, Any],+ model_config: str | Path, trellis_root: str | Path) -> dict[str, Path]:+ """Resolve release VAE dependencies or preserve legacy config-relative paths."""+ base = Path(model_config).expanduser().absolute().parent+ standalone = config.get("format") == "supratex_completion"+ if standalone:+ base = _completion_vae_root(trellis_root)+ stems = {}+ for key in ("pretrained_shape_slat_dec", "pretrained_pbr_slat_dec"):+ value = dataset.get(key)+ if not isinstance(value, str) or not value:+ raise ValueError(f"model config requires {key}")+ path = Path(value).expanduser()+ if standalone and (path.name != value or value in (".", "..") or "\\" in value):+ raise ValueError(f"standalone completion {key} must be a bare sparse VAE stem")+ stems[key] = path if path.is_absolute() else base / path+ return stems+++def validate_completion_artifacts(model_config: str | Path, checkpoint: str | Path,+ trellis_root: str | Path) -> tuple[dict[str, Any], dict[str, Any], Path, dict[str, list[float]]]:+ """Check completion metadata, safe-file headers, and all VAE files before GPU work."""+ contract = load_completion_contract(model_config, checkpoint)+ config, dataset, _, _ = contract+ ckpts = _completion_vae_root(trellis_root)+ stems = [ckpts / "shape_enc_next_dc_f16c32_fp16", ckpts / "tex_enc_next_dc_f16c32_fp16"]+ stems.extend(completion_decoder_stems(config, dataset, model_config, trellis_root).values())+ for stem in stems:+ _stem(stem, "completion artifact")+ return contract+++def _load_vae(models: Any, stem: Path) -> Any:+ """Build a sparse VAE on the meta device so weights are not randomly initialized first.++ Checkpoint tensors are cast to the constructor's dtypes, exactly as the+ copy-based loader does. Partial checkpoints or constructor-made tensors that+ a meta shell cannot materialize fall back to models.from_pretrained.+ """+ import torch+ from safetensors.torch import load_file++ config = json.loads(Path(f"{stem}.json").read_text(encoding="utf-8"))+ with torch.device("meta"):+ model = getattr(models, config["name"])(**config["args"])+ expected = model.state_dict()+ state = load_file(f"{stem}.safetensors", device="cpu")+ if state.keys() != expected.keys() or any(state[name].shape != target.shape for name, target in expected.items()):+ return models.from_pretrained(str(stem))+ model.load_state_dict({name: state[name].to(dtype=target.dtype) for name, target in expected.items()},+ strict=True, assign=True)+ if any(isinstance(value, torch.Tensor) and value.is_meta+ for module in model.modules() for value in (*module._parameters.values(), *module._buffers.values(), *vars(module).values())):+ return models.from_pretrained(str(stem))+ return model++- def _load_case(input_dir: str | Path, torch: Any, image: Any) -> dict[str, Any]:- root = Path(input_dir)- required = {name: _file(root / name, name) for name in ("geometry.pt", "camera.json", "condition_rgba.png", "albedo.png", "mra.png")}- geometry = torch.load(required["geometry.pt"], map_location="cpu", weights_only=True)++def _load_geometry(root: Path, torch: Any) -> tuple[Any, Any]:++ """Read geometry.pt, or a compressed geometry.npz with the same verts/faces arrays."""++ if not (root / "geometry.pt").is_file() and (root / "geometry.npz").is_file():++ import numpy as np++ with np.load(root / "geometry.npz") as arrays:++ try:++ return torch.from_numpy(arrays["verts"]).float().contiguous(), torch.from_numpy(arrays["faces"]).long().contiguous()++ except KeyError as error:++ raise ValueError("geometry.npz must contain arrays verts and faces") from error++ geometry = torch.load(_file(root / "geometry.pt", "geometry.pt or geometry.npz"), map_location="cpu", weights_only=True)+ try:- vertices, faces = geometry["verts"].float().contiguous(), geometry["faces"].long().contiguous()++ return geometry["verts"].float().contiguous(), geometry["faces"].long().contiguous()+ except (KeyError, AttributeError) as error:+ raise ValueError("geometry.pt must contain tensor keys verts and faces") from error++++++def _load_case(input_dir: str | Path, torch: Any, image: Any, remove_floaters: bool = False) -> dict[str, Any]:++ root = Path(input_dir)++ required = {name: _file(root / name, name) for name in ("camera.json", "condition_rgba.png", "albedo.png", "mra.png")}++ vertices, faces = _load_geometry(root, torch)+ if vertices.ndim != 2 or vertices.shape[1] != 3 or faces.ndim != 2 or faces.shape[1] != 3:- raise ValueError("geometry.pt must contain verts[N,3] and faces[M,3]")++ raise ValueError("geometry must contain verts[N,3] and faces[M,3]")+ rgba = image.open(required["condition_rgba.png"]).convert("RGBA")+ albedo, mra = image.open(required["albedo.png"]).convert("RGB"), image.open(required["mra.png"]).convert("RGB")+ if rgba.size[0] != rgba.size[1]:+ raise ValueError("condition_rgba.png must be square")+ if albedo.size != (RESOLUTION, RESOLUTION) or mra.size != (RESOLUTION, RESOLUTION):+ raise ValueError("albedo.png and mra.png must be 1024 by 1024 RGB maps")+ try:+ camera = json.loads(required["camera.json"].read_text(encoding="utf-8"))+ except json.JSONDecodeError as error:+ raise ValueError("camera.json must be valid JSON") from error+ if "camera_angle_x" not in camera or "distance" not in camera:+ raise ValueError("camera.json must provide canonical camera_angle_x and distance")++ if remove_floaters:++ import numpy as np++ from .geometry_cleanup import remove_floaters as clean++ vertices, faces, report = clean(vertices, faces, camera, np.asarray(rgba.getchannel("A")))++ vertices, faces = vertices.contiguous(), faces.contiguous()++ print(f"Floaters: removed {report['removed_components']} of {report['components']} components "++ f"({report['removed_faces']} of {report['faces']} faces)", flush=True)+ return {"vertices": vertices, "faces": faces, "rgba": rgba, "albedo": albedo, "mra": mra, "camera": camera}+++def _runtime() -> dict[str, Any]:+ from .runtime import configure_inference_runtime+ configure_inference_runtime()+ from .kernel_config import configure_sparse_kernels+ kernel_config = configure_sparse_kernels()+ if kernel_config["enabled"]:+ print(f"Sparse kernels: {kernel_config['preset']}", flush=True)+ import numpy as np+ import o_voxel+ import torch+ import torch.nn.functional as F+ import utils3d+ from PIL import Image, ImageFilter+ from supratex import models+ from supratex.modules import sparse+ from supratex.representations import MeshWithVoxel+ from .mesh_export import to_glb+ return locals()+++def _camera(spec: Mapping[str, Any], device: str, torch: Any, utils3d: Any) -> tuple[Any, Any]:+ if "extrinsic" in spec and ("projection_intrinsic" in spec or "intrinsic" in spec):+ intrinsic = spec.get("projection_intrinsic", spec.get("intrinsic"))+ external, projection = torch.as_tensor(spec["extrinsic"], dtype=torch.float32, device=device), torch.as_tensor(intrinsic, dtype=torch.float32, device=device)+ if external.shape != (4, 4) or projection.shape != (3, 3): raise ValueError("camera matrices must be 4x4 and 3x3")+ return external, projection+ if "distance" not in spec or "camera_angle_x" not in spec: raise ValueError("camera must supply distance and camera_angle_x")+ eye = torch.tensor([0., 0., float(spec["distance"]) * float(spec.get("mesh_scale", 1.0))], device=device)+ return utils3d.torch.extrinsics_look_at(eye, torch.zeros(3, device=device), torch.tensor([0., 1., 0.], device=device)), utils3d.torch.intrinsics_from_fov_xy(torch.tensor(float(spec["camera_angle_x"]), device=device), torch.tensor(float(spec["camera_angle_x"]), device=device))+++def _shape(vertices: Any, faces: Any, encoder: Any, runtime: Mapping[str, Any], device: str) -> tuple[Any, Any]:+ torch, o_voxel, sparse = runtime["torch"], runtime["o_voxel"], runtime["sparse"]+ indices, dual_vertices, intersected = o_voxel.convert.mesh_to_flexible_dual_grid(vertices=vertices.float().cpu().contiguous(), faces=faces.long().cpu().contiguous(), grid_size=RESOLUTION, aabb=[[-.5, -.5, -.5], [.5, .5, .5]], face_weight=1., boundary_weight=.2, regularization_weight=1e-2, timing=False)+ offsets = (dual_vertices.float() * RESOLUTION - indices.float()).clamp(0, 1)+ coords = torch.cat((torch.zeros_like(indices[:, :1]), indices), dim=1).int().to(device)+ vertices_sparse = sparse.SparseTensor(offsets.to(device), coords)+ with torch.no_grad(): latent = encoder(vertices_sparse, vertices_sparse.replace(intersected.bool().to(device)))+ return latent, sparse.SparseTensor(torch.zeros(coords.shape[0], 6, device=device), coords)++++ALIGNMENT_WARNING_IOU = .9++++++def _alignment_report(uv: Any, alpha: Any, admission: Mapping[str, int], np: Any, image: Any, image_filter: Any) -> dict[str, float]:++ """Compare the projected geometry silhouette with the image foreground and print the result."""++ pixels = (uv.detach().cpu().numpy() * RESOLUTION).astype(np.int64)++ inside = (pixels >= 0).all(1) & (pixels < RESOLUTION).all(1)++ splat = np.zeros((RESOLUTION, RESOLUTION), dtype=np.uint8)++ splat[pixels[inside, 1], pixels[inside, 0]] = 255++ # Surface cells project to about one pixel each; a 3x3 closing fills the gaps.++ silhouette = np.asarray(image.fromarray(splat).filter(image_filter.MaxFilter(3)).filter(image_filter.MinFilter(3))) > 0++ foreground = np.asarray(image.fromarray(alpha).resize((RESOLUTION, RESOLUTION), image.Resampling.NEAREST)) > 127++ overlap = float((silhouette & foreground).sum())++ report = {"silhouette_iou": overlap / max(float((silhouette | foreground).sum()), 1.),++ "geometry_inside_image": overlap / max(float(silhouette.sum()), 1.),++ "image_covered_by_geometry": overlap / max(float(foreground.sum()), 1.), **admission}++ rejected = [f"missed geometry {admission['trusted_rays'] - admission['first_hits']}",++ f"depth edge {admission['rejected_depth_edge']}"]++ rejected += [f"{label} {admission[key]}" for key, label in (("rejected_silhouette", "silhouette margin"),++ ("rejected_grazing", "grazing")) if admission[key]]++ print(f"Observation: silhouette IoU {report['silhouette_iou']:.3f} "++ f"(geometry inside image {report['geometry_inside_image']:.3f}, image covered {report['image_covered_by_geometry']:.3f}); "++ f"admitted {admission['admitted']} of {admission['trusted_rays']} trusted pixels ({', '.join(rejected)})", flush=True)++ if report["silhouette_iou"] < ALIGNMENT_WARNING_IOU:++ print(f"Warning: the image and geometry silhouettes disagree (IoU {report['silhouette_iou']:.3f} < "++ f"{ALIGNMENT_WARNING_IOU}); mismatched regions rely on completion rather than the image.", flush=True)++ return report+++++def _partial(surface: Any, shape: Any, case: Mapping[str, Any], external: Any, projection: Any, encoder: Any, normalization: Mapping[str, Any], runtime: Mapping[str, Any], device: str) -> Any:+ torch, F, np, image, image_filter, sparse = runtime["torch"], runtime["F"], runtime["np"], runtime["Image"], runtime["ImageFilter"], runtime["sparse"]+ coords = surface.coords[:, 1:].long(); points = (coords.float() + .5) / RESOLUTION - .5+ camera = (torch.cat((points, torch.ones_like(points[:, :1])), dim=1) @ external.T)[:, :3]+ uvw = camera @ projection.T; uv = uvw[:, :2] / uvw[:, 2:3].clamp(min=1e-8)+ grid = torch.stack((uv[:, 0] * 2 - 1, uv[:, 1] * 2 - 1), dim=1).view(1, 1, -1, 2)+ def sampled(source: Any) -> Any:+ data = np.asarray(source.convert("RGB").resize((RESOLUTION, RESOLUTION), image.Resampling.LANCZOS), dtype=np.float32).copy() / 255.+ return F.grid_sample(torch.from_numpy(data).permute(2, 0, 1).to(device)[None], grid, mode="bilinear", align_corners=False, padding_mode="border")[0, :, 0].T.clamp(0, 1)+ alpha = np.asarray(case["rgba"].getchannel("A"), dtype=np.uint8)+ mask = image.fromarray(np.where(alpha >= 254, 255, 0).astype(np.uint8)).resize((RESOLUTION, RESOLUTION), image.Resampling.NEAREST).filter(image_filter.MinFilter(5))+ trusted = torch.from_numpy(np.asarray(mask, dtype=np.uint8).copy() == 255)+ bits, ordered, order = native_observation.build_occupancy_index(coords)- owners = native_observation.pixel_first_occupied(dict(case["camera"]), bits, trusted)++ admission: dict[str, int] = {}++ owners = native_observation.pixel_first_occupied(dict(case["camera"]), bits, trusted, stats=admission)++ _alignment_report(uv, alpha, admission, np, image, image_filter)+ visible = native_observation.owner_rows(coords, owners, ordered, order)+ if not bool(visible.any()): raise RuntimeError("the trusted alpha gate leaves no observed material surface")+ with torch.no_grad():+ return native_observation.encode_partial(encoder, coords, visible, sampled(case["albedo"]), sampled(case["mra"]), shape.coords[:, 1:], dict(normalization), sparse, device)+++def _export(output: Path, representation: Any, texture_size: int, decimation_target: int, texture_format: str, runtime: Mapping[str, Any], *, gutter: bool = False, low_vram: bool = False) -> None:+ if output.suffix.lower() != ".glb": raise ValueError("output must have a .glb suffix")+ output.parent.mkdir(parents=True, exist_ok=True)+ lock = output.with_name(f".{output.name}.publish.lock")+ try:+ handle = lock.open("x")+ except FileExistsError as error:+ raise FileExistsError(f"another process is publishing {output}") from error+ handle.close()+ if output.exists():+ lock.unlink(missing_ok=True)+ raise FileExistsError(f"refusing to overwrite existing output: {output}")+ temporary = output.with_name(f".{output.stem}.tmp.{os.getpid()}.glb")+ try:+ scene = runtime["to_glb"](vertices=representation.vertices, faces=representation.faces, attr_volume=representation.attrs, coords=representation.coords, attr_layout=LAYOUT, grid_size=RESOLUTION, aabb=[[-.5, -.5, -.5], [.5, .5, .5]], decimation_target=decimation_target, texture_size=texture_size, remesh=True, remesh_band=1, remesh_project=0, use_tqdm=True, **({"low_vram": True} if low_vram else {}))+ if gutter:+ from .gutter import apply_gutter+ print(f"Gutter postprocess: {apply_gutter(scene)}", flush=True)+ scene.apply_transform(runtime["np"].asarray([[-1, 0, 0, 0], [0, 0, -1, 0], [0, -1, 0, 0], [0, 0, 0, 1]], dtype=runtime["np"].float64))+ scene.export(str(temporary), extension_webp=texture_format == "webp")+ if output.exists():+ raise FileExistsError(f"refusing to overwrite existing output: {output}")+ os.replace(temporary, output)+ finally:+ temporary.unlink(missing_ok=True)+ lock.unlink(missing_ok=True)+++def _stage_sparse(value: Any, device: str, *, keep_topology: bool = False) -> Any:+ """Transfer sparse data without retaining backend caches on its old device.++ SparseTensor.to()/cpu() share spatial/backend caches. Encoder subdivision+ maps are semantic: the decoders use them to reproduce the input surface,+ overriding predicted subdivisions. Preserve those maps when requested;+ convolution and attention caches are safe to recompute on the new device.+ """+ def transfer(item: Any) -> Any:+ if isinstance(item, dict):+ return {key: transfer(child) for key, child in item.items()}+ if isinstance(item, (list, tuple)):+ return type(item)(transfer(child) for child in item)+ if hasattr(item, "detach") and hasattr(item, "to"):+ return item.detach().to(device)+ return item+ staged = type(value)(value.feats.detach().to(device), value.coords.detach().to(device),+ shape=value._shape, scale=value._scale)+ if keep_topology:+ staged._spatial_cache = {+ scale: {name: transfer(item) for name, item in cache.items()+ if name.startswith(("channel2spatial_", "upsample_")) or name == "shape"}+ for scale, cache in value._spatial_cache.items()+ }+ return staged+++@contextmanager+def _completion_stage(model: Any, torch: Any, device: str, *, layer_offload: bool = False):+ """Own one model's residency, including cleanup after failed inference."""+ previous = getattr(model, "low_vram", False)+ try:+ if layer_offload:+ model.low_vram = True+ else:+ model.to(device)+ model.eval()+ with torch.no_grad():+ yield model+ finally:+ model.to("cpu")+ if layer_offload:+ model.low_vram = previous+ torch.cuda.empty_cache()+++def _run_completion_low_vram(*, case: Mapping[str, Any], back_case: Mapping[str, Any] | None,+ ckpts: Path, config: Mapping[str, Any], dataset: Mapping[str, Any],+ checkpoint_path: Path, partial_stats: Mapping[str, Any], resolved: Any,+ runtime: Mapping[str, Any], device: str, seed: int, output: str | Path,+ texture_size: int, decimation_target: int, texture_format: str, gutter: bool) -> dict[str, Any]:+ """Serialize completion stages and keep only their CPU handoffs alive."""+ torch, models = runtime["torch"], runtime["models"]+ print("Completion low VRAM: sequential models, CPU handoffs, decoder layer offload", flush=True)+ shape_encoder = _load_vae(models, _stem(ckpts / "shape_enc_next_dc_f16c32_fp16", "shape encoder"))+ with _completion_stage(shape_encoder, torch, device):+ shape, surface = _shape(case["vertices"], case["faces"], shape_encoder, runtime, device)+ shape_cpu = _stage_sparse(shape, "cpu", keep_topology=True)+ shape = _stage_sparse(shape, device)+ del shape_encoder+ texture_encoder = _load_vae(models, _stem(ckpts / "tex_enc_next_dc_f16c32_fp16", "material encoder"))+ dual_stats = {}+ with _completion_stage(texture_encoder, torch, device):+ if back_case is None:+ external, projection = _camera(case["camera"], device, torch, runtime["utils3d"])+ observation = _partial(surface, shape, case, external, projection, texture_encoder, partial_stats, runtime, device)+ del external, projection+ else:+ from .dual_view import encode_two_views+ observation, dual_stats = encode_two_views(surface, shape, case, back_case, texture_encoder,+ partial_stats, runtime, device)+ del texture_encoder, surface+ torch.cuda.empty_cache()++ from supratex.pipelines.observation_guided_completion import build_completion_model, sample_material_latents+ state = load_completion_state_dict(checkpoint_path, torch_module=torch)+ model = build_completion_model(config, state, assign_weights=True)+ del state+ with _completion_stage(model, torch, device):+ shape_condition = shape.replace(feats=(shape.feats - torch.as_tensor(dataset["shape_slat_normalization"]["mean"], device=device)[None]) / torch.as_tensor(dataset["shape_slat_normalization"]["std"], device=device)[None])+ noise = shape.replace(feats=torch.randn((shape.coords.shape[0], 32), generator=torch.Generator(device=device).manual_seed(int(seed)), device=device))+ print("Observation cache: disabled (low VRAM)", flush=True)+ sampled = sample_material_latents(model, noise, concat_cond=shape_condition, partial_z_obs=observation, steps=25, rescale_t=3., sigma_min=1e-5, use_observation_cache=False).samples+ if not torch.equal(sampled.coords, noise.coords) or sampled.feats.shape != noise.feats.shape:+ raise RuntimeError("material sampler changed sparse support or feature shape")+ generated = shape.replace(feats=sampled.feats.float() * torch.as_tensor(dataset["pbr_slat_normalization"]["std"], device=device)[None] + torch.as_tensor(dataset["pbr_slat_normalization"]["mean"], device=device)[None])+ generated_cpu = _stage_sparse(generated, "cpu")+ del model, shape, shape_condition, noise, sampled, generated, observation+ torch.cuda.empty_cache()++ # Reuse the encoder's exact support in both decoders. Do not carry GPU+ # convolution caches or the unused decoded mesh into material decoding.+ shape_decoder = _load_vae(models, _stem(resolved(dataset["pretrained_shape_slat_dec"]), "shape decoder"))+ shape_decoder.set_resolution(RESOLUTION)+ with _completion_stage(shape_decoder, torch, device, layer_offload=True):+ shape = _stage_sparse(shape_cpu, device, keep_topology=True)+ decoded_shape, guide = shape_decoder(shape, return_subs=True, return_mesh=False)+ guide_cpu = [_stage_sparse(value, "cpu") for value in guide]+ del shape_decoder, shape, decoded_shape, guide+ generated_cpu._spatial_cache = shape_cpu._spatial_cache+ del shape_cpu+ torch.cuda.empty_cache()++ material_decoder = _load_vae(models, _stem(resolved(dataset["pretrained_pbr_slat_dec"]), "material decoder"))+ with _completion_stage(material_decoder, torch, device, layer_offload=True):+ generated = _stage_sparse(generated_cpu, device, keep_topology=True)+ guide = [_stage_sparse(value, device) for value in guide_cpu]+ decoded = material_decoder(generated, guide_subs=guide) * .5 + .5+ if decoded.feats.shape[1] != 6: raise RuntimeError("material decoder must emit six PBR channels")+ decoded_cpu = _stage_sparse(decoded, "cpu")+ del material_decoder, generated, generated_cpu, guide, guide_cpu, decoded+ torch.cuda.empty_cache()+ representation = runtime["MeshWithVoxel"](case["vertices"], case["faces"], [-.5, -.5, -.5], 1. / RESOLUTION, decoded_cpu.coords[:, 1:].int(), decoded_cpu.feats.float().clamp(0, 1), torch.Size([1, 6, RESOLUTION, RESOLUTION, RESOLUTION]), layout=LAYOUT)+ del decoded_cpu+ _export(Path(output), representation, texture_size, decimation_target, texture_format, runtime, gutter=gutter, low_vram=True)+ return dual_stats++- def _run_completion(*, input_dir: str | Path, output: str | Path, model_config: str | Path, checkpoint: str | Path, trellis_root: str | Path, seed: int = 42, device: str = "cuda", texture_size: int = 4096, decimation_target: int = 500000, texture_format: str = "png", gutter: bool = False, back_case: Mapping[str, Any] | None = None) -> dict[str, Any]:++def _run_completion(*, input_dir: str | Path, output: str | Path, model_config: str | Path, checkpoint: str | Path, trellis_root: str | Path, seed: int = 42, device: str = "cuda", texture_size: int = 4096, decimation_target: int = 500000, texture_format: str = "png", gutter: bool = False, back_case: Mapping[str, Any] | None = None, remove_floaters: bool = False) -> dict[str, Any]:+ """Complete PBR texture from public input maps and write one new GLB."""+ if device != "cuda": raise ValueError("public material completion currently requires device='cuda'")+ if texture_size <= 0 or decimation_target <= 0 or texture_format not in {"png", "webp"}: raise ValueError("invalid GLB export settings")+ config, dataset, checkpoint_path, partial_stats = validate_completion_artifacts(model_config, checkpoint, trellis_root)+ decoder_stems = completion_decoder_stems(config, dataset, model_config, trellis_root)+ decoder_paths = {dataset[key]: path for key, path in decoder_stems.items()}+ def resolved(value: str) -> Path:+ return decoder_paths[value]+ runtime = _runtime(); torch, models = runtime["torch"], runtime["models"]+ if not torch.cuda.is_available(): raise RuntimeError("CUDA is unavailable")- case = _load_case(input_dir, torch, runtime["Image"]); ckpts = _completion_vae_root(trellis_root)++ case = _load_case(input_dir, torch, runtime["Image"], remove_floaters); ckpts = _completion_vae_root(trellis_root)+ if os.environ.get("SUPRATEX_LOW_VRAM", "0") == "1":+ return _run_completion_low_vram(case=case, back_case=back_case, ckpts=ckpts, config=config,+ dataset=dataset, checkpoint_path=checkpoint_path, partial_stats=partial_stats,+ resolved=resolved, runtime=runtime, device=device, seed=seed, output=output,+ texture_size=texture_size, decimation_target=decimation_target,+ texture_format=texture_format, gutter=gutter)+ shape_encoder = _load_vae(models, _stem(ckpts / "shape_enc_next_dc_f16c32_fp16", "shape encoder")).to(device).eval()+ texture_encoder = _load_vae(models, _stem(ckpts / "tex_enc_next_dc_f16c32_fp16", "material encoder")).to(device).eval()+ external, projection = _camera(case["camera"], device, torch, runtime["utils3d"])+ shape, surface = _shape(case["vertices"], case["faces"], shape_encoder, runtime, device)+ shape_encoder.to("cpu"); torch.cuda.empty_cache()+ dual_stats = {}+ if back_case is None:+ observation = _partial(surface, shape, case, external, projection, texture_encoder, partial_stats, runtime, device)+ else:+ from .dual_view import encode_two_views+ observation, dual_stats = encode_two_views(surface, shape, case, back_case, texture_encoder,+ partial_stats, runtime, device)+ texture_encoder.to("cpu"); torch.cuda.empty_cache()+ from supratex.pipelines.observation_guided_completion import build_completion_model, sample_material_latents+ state = load_completion_state_dict(checkpoint_path, torch_module=torch)+ model = build_completion_model(config, state, assign_weights=True).to(device).eval()+ del state+ shape_condition = shape.replace(feats=(shape.feats - torch.as_tensor(dataset["shape_slat_normalization"]["mean"], device=device)[None]) / torch.as_tensor(dataset["shape_slat_normalization"]["std"], device=device)[None])+ noise = shape.replace(feats=torch.randn((shape.coords.shape[0], 32), generator=torch.Generator(device=device).manual_seed(int(seed)), device=device))+ # Cache fixed observation work within this sample only. Retain ample room+ # for attention activations; low-memory devices keep the uncached path.+ cache_bytes = 2 * (len(model.blocks) + len(model.refiners)) * observation.feats.shape[0] * model.model_channels * 2+ free_bytes, _ = torch.cuda.mem_get_info(noise.feats.device)+ use_cache = free_bytes >= cache_bytes * 1.25 + 8 * 1024 ** 3+ print(f"Observation cache: {'enabled' if use_cache else 'disabled (memory headroom)'}", flush=True)+ sampled = sample_material_latents(model, noise, concat_cond=shape_condition, partial_z_obs=observation, steps=25, rescale_t=3., sigma_min=1e-5, use_observation_cache=use_cache).samples+ if not torch.equal(sampled.coords, noise.coords) or sampled.feats.shape != noise.feats.shape:+ raise RuntimeError("material sampler changed sparse support or feature shape")+ generated = shape.replace(feats=sampled.feats.float() * torch.as_tensor(dataset["pbr_slat_normalization"]["std"], device=device)[None] + torch.as_tensor(dataset["pbr_slat_normalization"]["mean"], device=device)[None])+ model.to("cpu"); torch.cuda.empty_cache()+ shape_stem, material_stem = _stem(resolved(dataset["pretrained_shape_slat_dec"]), "shape decoder"), _stem(resolved(dataset["pretrained_pbr_slat_dec"]), "material decoder")+ shape_decoder, material_decoder = _load_vae(models, shape_stem).to(device).eval(), _load_vae(models, material_stem).to(device).eval()+ shape_decoder.set_resolution(RESOLUTION)+ with torch.no_grad(): _, guide = shape_decoder(shape, return_subs=True); decoded = material_decoder(generated, guide_subs=guide) * .5 + .5+ if decoded.feats.shape[1] != 6: raise RuntimeError("material decoder must emit six PBR channels")+ representation = runtime["MeshWithVoxel"](case["vertices"].to(device), case["faces"].to(device), [-.5, -.5, -.5], 1. / RESOLUTION, decoded.coords[:, 1:].int(), decoded.feats.float().clamp(0, 1), torch.Size([1, 6, RESOLUTION, RESOLUTION, RESOLUTION]), layout=LAYOUT)+ _export(Path(output), representation, texture_size, decimation_target, texture_format, runtime, gutter=gutter)+ return dual_stats++++def _require_reprojection_atlas(texture_size: int, texture_format: str) -> None:++ from supratex.pipeline_config import REFINE_ATLAS++ if {"texture_size": texture_size, "texture_format": texture_format} != REFINE_ATLAS:++ raise ValueError("--refine and --dual-view require a 4096 PNG atlas")++++++def _publish(final: Path, output: Path, tag: str) -> None:++ """Copy a finished mesh to ``output`` without replacing another writer's file."""++ import shutil++ output.parent.mkdir(parents=True, exist_ok=True)++ temporary = output.with_name(f".{output.name}.{tag}.{os.getpid()}.tmp")++ try:++ with temporary.open("xb") as target, final.open("rb") as source:++ shutil.copyfileobj(source, target)++ os.link(temporary, output)++ finally:++ temporary.unlink(missing_ok=True)++++++def _publish_unrefined(native: Path, output: Path, gutter: bool, error: Exception) -> None:++ """Publish the completed mesh without refinement after a refinement failure."""++ print(f"WARNING: texture refinement failed and was skipped ({type(error).__name__}: {error}); "++ f"writing the unrefined result to {output}", file=sys.stderr, flush=True)++ if not gutter:++ _publish(native, output, "unrefined")++ return++ # Refinement normally supplies the gutter; apply the export-time one instead.++ import tempfile++ import trimesh++ from .gutter import apply_gutter++ scene = trimesh.load(native, force="scene")++ for mesh in scene.geometry.values():++ apply_gutter(mesh)++ with tempfile.TemporaryDirectory(dir=output.parent) as directory:++ padded = Path(directory) / "mesh.glb"++ scene.export(str(padded))++ _publish(padded, output, "unrefined")++++++def _run_front_reprojection(arguments: dict[str, Any], work_dir: str | Path | None) -> None:++ """Complete one view, then reproject its reference observation into the atlas."""++ from .dual_view import digest, write_json++++ output = Path(arguments["output"]).expanduser().resolve()++ work = Path(work_dir).expanduser().resolve() if work_dir else output.with_name(output.stem + "_refine")++ if output.suffix.lower() != ".glb":++ raise ValueError("output must have a .glb suffix")++ if output.exists():++ raise FileExistsError(f"refusing to overwrite existing output: {output}")++ if work.exists():++ raise FileExistsError(f"--refine work directory must be new: {work}")++ _require_reprojection_atlas(arguments["texture_size"], arguments["texture_format"])++ source = Path(arguments["input_dir"]).expanduser().resolve()++ work.mkdir(parents=True)++ # Reprojection always ends with its observation-guided one-texel gutter, so++ # the export-time nearest-color gutter (--gutter) is not applied first.++ receipt = {"profile": "supratex.front_refinement", "view": "front", "status": "running", "stage": "texture",++ "input": str(source), "output": str(output), "seed": arguments["seed"],++ "decimation_target": arguments["decimation_target"], "gutter": "continuous (reprojection)",++ "checkpoint": str(Path(arguments["checkpoint"]).expanduser().resolve()),++ "model_config": str(Path(arguments["model_config"]).expanduser().resolve())}++ write_json(work / "receipt.json", receipt)++ try:++ native = work / "preds/mesh.glb"++ _run_completion(**{**arguments, "input_dir": source, "output": native, "gutter": False})++ # Reprojection runs in separate CUDA workers; release cached blocks first.++ import gc++ import torch++ gc.collect()++ torch.cuda.empty_cache()++ receipt.update(stage="reprojection", native_mesh=str(native), native_mesh_sha256=digest(native))++ write_json(work / "receipt.json", receipt)++ from .reprojection import run_front_view++ try:++ final = run_front_view(native, source, work / "reproject")++ except Exception as error:++ _publish_unrefined(native, output, arguments["gutter"], error)++ receipt.update(status="valid", stage="complete", refine="skipped",++ refine_error=f"{type(error).__name__}: {error}", mesh=str(native),++ gutter="export-time" if arguments["gutter"] else False,++ output_sha256=digest(output))++ write_json(work / "receipt.json", receipt)++ return++ _publish(final, output, "reproject")++ receipt.update(status="valid", stage="complete", refine="applied", mesh=str(final),++ output_sha256=digest(output))++ write_json(work / "receipt.json", receipt)++ except Exception as error:++ receipt.update(status="failed", error=f"{type(error).__name__}: {error}")++ write_json(work / "receipt.json", receipt)++ raise+++++def run_completion(*, input_dir: str | Path, output: str | Path, model_config: str | Path,+ checkpoint: str | Path, trellis_root: str | Path, seed: int = 42,+ device: str = "cuda", texture_size: int = 4096,+ decimation_target: int = 500000, texture_format: str = "png", gutter: bool = False,- back_view_dir: str | Path | None = None, work_dir: str | Path | None = None) -> None:- """Complete one view by default, or validate and publish a dual-view result."""++ back_view_dir: str | Path | None = None, work_dir: str | Path | None = None,++ refine: bool = False, remove_floaters: bool = False) -> None:++ """Complete one view by default, optionally refining it, or publish a refined dual-view result."""+ arguments = dict(input_dir=input_dir, output=output, model_config=model_config,+ checkpoint=checkpoint, trellis_root=trellis_root, seed=seed, device=device,+ texture_size=texture_size, decimation_target=decimation_target,- texture_format=texture_format, gutter=gutter)++ texture_format=texture_format, gutter=gutter, remove_floaters=remove_floaters)++ # Dual-view refines both views itself, so --refine needs no separate pass there.++ if refine and back_view_dir is None:++ _run_front_reprojection(arguments, work_dir)++ return+ if back_view_dir is None:+ if work_dir is not None:- raise ValueError("completion --work-dir is reserved for dual-view inference")++ raise ValueError("completion --work-dir is reserved for dual-view inference or --refine")+ _run_completion(**arguments)+ return+ from .dual_view import CAMERA_PROTOCOL, PROTOCOL, digest, load_back_case, write_json- import shutil++ output = Path(output).expanduser().resolve()+ work = Path(work_dir).expanduser().resolve() if work_dir else output.with_name(output.stem + "_dual_view")+ if output.suffix.lower() != ".glb":+ raise ValueError("output must have a .glb suffix")+ if output.exists():+ raise FileExistsError(f"refusing to overwrite existing output: {output}")+ if work.exists():+ raise FileExistsError(f"dual-view work directory must be new: {work}")- from supratex.pipeline_config import DUAL_VIEW_EXPORT- export = {"texture_size": texture_size, "texture_format": texture_format, "decimation_target": decimation_target}- if gutter or export != DUAL_VIEW_EXPORT:- raise ValueError("dual-view reprojection requires a 4096 PNG atlas, 500000-face target, and no --gutter")++ _require_reprojection_atlas(texture_size, texture_format)+ front_root, back_root = Path(input_dir).expanduser().resolve(), Path(back_view_dir).expanduser().resolve()+ back = load_back_case(front_root, back_root)+ work.mkdir(parents=True)+ receipt = {"protocol": PROTOCOL, "camera_protocol": CAMERA_PROTOCOL, "view": "dual",+ "status": "running", "stage": "texture", "front_input": str(front_root),+ "back_input": str(back_root), "output": str(output),+ "checkpoint": str(Path(checkpoint).expanduser().resolve()),+ "model_config": str(Path(model_config).expanduser().resolve()),+ "seed": seed, "sampler": "Euler", "steps": 25,++ "decimation_target": decimation_target, "gutter": "continuous (reprojection)",+ "geometry_sha256": digest(front_root / "geometry.pt"),+ "cameras_sha256": digest(back_root / "cameras.json"),+ "front_material_receipt_sha256": digest(front_root / "material_receipt.json"),+ "back_material_receipt_sha256": digest(back_root / "material_receipt.json")}+ write_json(work / "receipt.json", receipt)+ try:+ native = work / "preds/mesh.glb"- arguments.update(input_dir=front_root, output=native, back_case=back)++ # Reprojection ends with its observation-guided gutter, so skip the export-time one.++ arguments.update(input_dir=front_root, output=native, back_case=back, gutter=False)+ stats = _run_completion(**arguments)+ # Reprojection runs in separate CUDA workers. Release the completion+ # allocator's inactive blocks before those processes create contexts.+ import gc+ import torch+ gc.collect()+ torch.cuda.empty_cache()+ write_json(work / "receipt_texture.json", {**receipt, "status": "success",+ "dual_stats": stats, "sampling_calls": 1, "mesh": str(native), "mesh_sha256": digest(native)})+ receipt.update(stage="reprojection")+ write_json(work / "receipt.json", receipt)+ from .reprojection import run_dual_view, validate_dual_view- final = run_dual_view(native, front_root, back_root, back["cameras"], work)- validation = validate_dual_view(work, raise_on_invalid=True)++ try:++ final = run_dual_view(native, front_root, back_root, back["cameras"], work)++ validation = validate_dual_view(work, raise_on_invalid=True)++ except Exception as error:++ final, validation, refine_error = None, None, error+ # Model and reprojection work can be long-running. Revalidate the+ # original inputs and generation evidence before publishing the mesh.+ load_back_case(front_root, back_root)+ bindings = {"geometry_sha256": front_root / "geometry.pt",+ "cameras_sha256": back_root / "cameras.json",+ "front_material_receipt_sha256": front_root / "material_receipt.json",+ "back_material_receipt_sha256": back_root / "material_receipt.json"}+ for key, path in bindings.items():+ if receipt[key] != digest(path):+ raise RuntimeError(f"input changed during dual-view completion: {key}")- output.parent.mkdir(parents=True, exist_ok=True)- temporary = output.with_name(f".{output.name}.dual-view.{os.getpid()}.tmp")- try:- with temporary.open("xb") as target, final.open("rb") as source:- shutil.copyfileobj(source, target)- # Atomic publication that cannot replace another writer's output.- os.link(temporary, output)- finally:- temporary.unlink(missing_ok=True)- receipt.update(status="valid", stage="complete", mesh=str(final), mesh_sha256=digest(final),- output_sha256=digest(output), dual_stats=stats,- postprocess_validation=validation, stitched_19_phase_checked=False)++ if final is None:++ _publish_unrefined(native, output, gutter, refine_error)++ receipt.update(status="valid", stage="complete", refine="skipped",++ refine_error=f"{type(refine_error).__name__}: {refine_error}", mesh=str(native),++ gutter="export-time" if gutter else False,++ mesh_sha256=digest(native), output_sha256=digest(output), dual_stats=stats)++ else:++ _publish(final, output, "dual-view")++ receipt.update(status="valid", stage="complete", refine="applied", mesh=str(final),++ mesh_sha256=digest(final), output_sha256=digest(output), dual_stats=stats,++ postprocess_validation=validation, stitched_19_phase_checked=False)+ write_json(work / "receipt.json", receipt)+ except Exception as error:+ receipt.update(status="failed", error=f"{type(error).__name__}: {error}")+ write_json(work / "receipt.json", receipt)+ raisediff --cc supratex/inference/reprojection/__init__.pyindex 3f040d4,0000000..c39e054mode 100644,000000..100644--- a/supratex/inference/reprojection/__init__.py+++ b/supratex/inference/reprojection/__init__.py@@@ -1,286 -1,0 +1,329 @@@- """Dual-view atlas reprojection with measured candidate acceptance gates.++"""Atlas reprojection with measured candidate acceptance gates.+- Both view candidates undergo sixteen train and three held-out phase renders.- The final atlas is stitched with exact front priority and binary preservation;- the stitched result is not itself subjected to another nineteen render phases.++Each reprojected view writes observed albedo into visible atlas texels, then++repairs one-texel UV gutters from the observed albedo gradient. Candidates++are re-rendered at nineteen validation phases (a 4x4 sub-pixel grid and three++off-grid offsets) and must pass every gate. Dual-view texturing++stitches front and back with exact front priority and binary preservation; the++stitched result is not itself subjected to another nineteen render phases.++Single-view texturing can reproject its reference view alone.+"""+from __future__ import annotations++import json+import shutil+import subprocess+import sys+from pathlib import Path+from typing import Any++from . import _glb+from ._common import (+ bind_file, check_binding, read_json, validate_candidate, write_json,+)+from ._transform import (+ atlas, back_to_front, camera_spec, front_protection, stitch,+ transform_glb, transformed_payload, validate_stitch,+)+- __all__ = ["run_dual_view", "validate_dual_view"]++__all__ = ["run_dual_view", "run_front_view", "validate_dual_view"]+PROFILE = "supratex.dual_view.reproject_continuous"+++def _prepare_inputs(source: Path, destination: Path, camera: dict[str, Any]) -> dict[str, Any]:+ """Align observation alpha and RGB once, preserving native albedo/MRA maps."""+ from PIL import Image++ names = ("condition_rgb.png", "condition_rgba.png", "albedo.png", "mra.png")+ bindings = {name: bind_file(source / name) for name in names}+ if (source / "camera.json").is_file():+ bindings["camera.json"] = bind_file(source / "camera.json")+ destination.mkdir(parents=True)+ with Image.open(source / "condition_rgb.png") as rgb, Image.open(source / "condition_rgba.png") as rgba:+ if rgb.size != rgba.size:+ raise ValueError("condition RGB and RGBA dimensions must agree")+ resized = rgb.convert("RGB").resize((1024, 1024), Image.Resampling.LANCZOS)+ alpha = rgba.convert("RGBA").getchannel("A").point(lambda value: 255 if value >= 254 else 0)+ alpha = alpha.resize((1024, 1024), Image.Resampling.NEAREST)+ resized.save(destination / "condition_rgb.png")+ aligned = resized.copy()+ aligned.putalpha(alpha)+ aligned.save(destination / "condition_rgba.png")+ for name in ("albedo.png", "mra.png"):+ with Image.open(source / name) as image:+ if image.size != (1024, 1024):+ raise ValueError(f"{name} must have native dimensions 1024 by 1024")+ image.convert("RGB").save(destination / name)+ write_json(destination / "camera.json", camera)+ return bindings+++def _command(module: str, arguments: list[str], log: Path) -> None:+ command = [sys.executable, "-m", f"supratex.inference.reprojection.{module}", *arguments]+ with log.open("x", encoding="utf-8") as stream:+ stream.write(json.dumps(command) + "\n")+ stream.flush()+ # Share the caller's process group so cancellation reaches GPU workers.+ process = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT)+ try:+ result = process.wait()+ except BaseException:+ process.terminate()+ process.wait()+ raise+ if result:+ raise RuntimeError(f"reprojection worker failed with exit code {result}; see {log}")+++def _run_side(baseline: Path, source: Path, output: Path, camera: dict[str, Any]) -> Path:- """Publish one view only after the B and continuous candidates pass."""++ """Publish one view only after the projection and continuous candidates pass."""+ output.mkdir(parents=True)+ baseline_binding = bind_file(baseline)+ code = {path.name: bind_file(path) for path in Path(__file__).parent.glob("*.py")}+ inputs = output / "inputs_1024"+ source_bindings = _prepare_inputs(source, inputs, camera)+ input_bindings = {path.name: bind_file(path) for path in inputs.iterdir() if path.is_file()}+ renderer = Path(__file__).with_name("_renderer.py").resolve()- project, continuous = output / "B", output / "continuous"++ project, continuous = output / "project", output / "continuous"+ _command("_project", [- "--arm", "B", "--baseline-glb", str(baseline),++ "--baseline-glb", str(baseline),+ "--source-albedo", str(inputs / "albedo.png"),+ "--source-rgba", str(inputs / "condition_rgba.png"),- "--camera", str(inputs / "camera.json"), "--evaluator", str(renderer),++ "--camera", str(inputs / "camera.json"), "--renderer", str(renderer),+ "--output", str(project),- ], output / "B.log")++ ], output / "project.log")+ validate_candidate(project, continuous=False)+ manifest = output / "continuous_inputs.json"+ write_json(manifest, [{"label": "observation", "baseline_glb": str(baseline),- "work": str(inputs), "b_output": str(project)}])++ "work": str(inputs), "project_output": str(project)}])+ _command("_continuous", [+ "--manifest", str(manifest), "--case", "observation",- "--evaluator", str(renderer), "--output", str(continuous),++ "--renderer", str(renderer), "--output", str(continuous),+ ], output / "continuous.log")+ validate_candidate(continuous, continuous=True)+ for name, record in source_bindings.items():+ check_binding(record, source / name)+ check_binding(baseline_binding, baseline)+ for name, record in code.items():+ check_binding(record, Path(__file__).with_name(name))+ final = output / "mesh.glb"+ shutil.copyfile(continuous / "candidate" / "mesh.glb", final)+ artifacts = {str(path.relative_to(output)): bind_file(path) for path in (+ project / "PLAN.json", project / "RECEIPT.json", project / "RESULT.json",+ project / "COMMON_DOMAIN.npz", project / "candidate" / "mesh.glb",+ continuous / "PLAN.json", continuous / "RECEIPT.json", continuous / "RESULT.json",+ continuous / "GUTTER_DIAGNOSTICS.npz", continuous / "candidate" / "mesh.glb",+ manifest, final,+ )}+ receipt = {+ "profile": PROFILE, "status": "valid", "baseline": baseline_binding,+ "source_inputs": source_bindings, "aligned_inputs": input_bindings,+ "code": code, "artifacts": artifacts, "mesh": str(final),- "gates": {"accepted": True, "B_accepted_all_19": True, "continuous_accepted_all_19": True},++ "gates": {"accepted": True, "project_accepted_all_19": True, "continuous_accepted_all_19": True},+ }+ write_json(output / "receipt.json", receipt)+ _validate_side(output)+ return final+++def _validate_side(output: Path) -> dict[str, Any]:+ import numpy as np++ receipt = read_json(output / "receipt.json")+ if receipt.get("profile") != PROFILE or receipt.get("status") != "valid":+ raise ValueError("invalid reprojection receipt profile or status")- if not all(receipt.get("gates", {}).get(key) is True for key in ("accepted", "B_accepted_all_19", "continuous_accepted_all_19")):++ if not all(receipt.get("gates", {}).get(key) is True for key in ("accepted", "project_accepted_all_19", "continuous_accepted_all_19")):+ raise ValueError("reprojection side is missing mandatory gates")+ baseline = check_binding(receipt["baseline"])+ required_inputs = {"condition_rgb.png", "condition_rgba.png", "albedo.png", "mra.png"}+ if not required_inputs.issubset(receipt.get("source_inputs", {})):+ raise ValueError("reprojection side has incomplete source bindings")+ if set(receipt.get("aligned_inputs", {})) != required_inputs | {"camera.json"}:+ raise ValueError("reprojection side has incomplete aligned input bindings")+ for record in receipt["source_inputs"].values():+ check_binding(record)+ for name, record in receipt["aligned_inputs"].items():+ check_binding(record, output / "inputs_1024" / name)+ expected_code = {path.name for path in Path(__file__).parent.glob("*.py")}+ if set(receipt.get("code", {})) != expected_code:+ raise ValueError("reprojection code bindings are incomplete")+ for name, record in receipt["code"].items():+ check_binding(record, Path(__file__).with_name(name))+ expected_artifacts = {- "B/PLAN.json", "B/RECEIPT.json", "B/RESULT.json", "B/COMMON_DOMAIN.npz", "B/candidate/mesh.glb",++ "project/PLAN.json", "project/RECEIPT.json", "project/RESULT.json", "project/COMMON_DOMAIN.npz",++ "project/candidate/mesh.glb",+ "continuous/PLAN.json", "continuous/RECEIPT.json", "continuous/RESULT.json",+ "continuous/GUTTER_DIAGNOSTICS.npz", "continuous/candidate/mesh.glb", "continuous_inputs.json", "mesh.glb",+ }+ if set(receipt.get("artifacts", {})) != expected_artifacts:+ raise ValueError("reprojection artifact bindings are incomplete")+ for name, record in receipt["artifacts"].items():+ check_binding(record, output / name)+ if Path(receipt.get("mesh", "")).resolve() != (output / "mesh.glb").resolve():+ raise ValueError("reprojection output mesh path changed")- for name, continuous in (("B", False), ("continuous", True)):++ for name, continuous in (("project", False), ("continuous", True)):+ validate_candidate(output / name, continuous=continuous)- bplan = read_json(output / "B" / "PLAN.json")- for key, path in {"baseline_glb": baseline, "source_albedo": output / "inputs_1024" / "albedo.png",- "source_rgba": output / "inputs_1024" / "condition_rgba.png",- "camera": output / "inputs_1024" / "camera.json"}.items():- if Path(bplan.get(key, "")).resolve() != path.resolve():- raise ValueError(f"B plan has an incorrect {key} binding")++ project_plan = read_json(output / "project" / "PLAN.json")++ expected_plan = {++ "baseline_glb": baseline,++ "source_albedo": output / "inputs_1024" / "albedo.png",++ "source_rgba": output / "inputs_1024" / "condition_rgba.png",++ "camera": output / "inputs_1024" / "camera.json",++ }++ for key, path in expected_plan.items():++ if Path(project_plan.get(key, "")).resolve() != path.resolve():++ raise ValueError(f"projection plan has an incorrect {key} binding")+ base_doc, base_binary, base_view, _, _, base_pixels = atlas(baseline)- for name in ("B/candidate/mesh.glb", "continuous/candidate/mesh.glb", "mesh.glb"):++ for name in ("project/candidate/mesh.glb", "continuous/candidate/mesh.glb", "mesh.glb"):+ candidate = output / name+ _glb._nonbase_identity_check(base_doc, base_binary, candidate, base_view)+ pixels = atlas(candidate)[-1]+ if pixels.shape != base_pixels.shape or (pixels.shape[-1] == 4 and not np.array_equal(pixels[..., 3], base_pixels[..., 3])):+ raise ValueError("candidate altered atlas dimensions or alpha")+ if bind_file(output / "mesh.glb")["sha256"] != bind_file(output / "continuous/candidate/mesh.glb")["sha256"]:+ raise ValueError("side output differs from its accepted continuous candidate")+ return receipt++++def run_front_view(native_glb: Path, input_dir: Path, output_dir: Path) -> Path:++ """Reproject the single reference view onto a single-view result.++++ This is the front half of dual-view texturing with the canonical reference++ camera from ``camera.json``. Inputs are staged under ``output_dir`` so their++ bindings stay valid; a missing ``condition_rgb.png`` is derived from the++ RGBA observation with black premultiplication, as the frontend writes it.++ """++ import numpy as np++ from PIL import Image++++ native, source = (Path(path).resolve(strict=True) for path in (native_glb, input_dir))++ output = Path(output_dir).resolve()++ if output.exists():++ raise FileExistsError(f"front reprojection requires a new destination: {output}")++ camera = read_json(source / "camera.json")++ try:++ camera = {"camera_angle_x": float(camera["camera_angle_x"]), "distance": float(camera["distance"]),++ "mesh_scale": float(camera.get("mesh_scale", 1.0))}++ except (KeyError, TypeError, ValueError) as error:++ raise ValueError("front reprojection requires a canonical camera with camera_angle_x and distance") from error++ staged = output / "source"++ staged.mkdir(parents=True)++ for name in ("condition_rgba.png", "albedo.png", "mra.png", "camera.json"):++ shutil.copyfile(source / name, staged / name)++ if (source / "condition_rgb.png").is_file():++ shutil.copyfile(source / "condition_rgb.png", staged / "condition_rgb.png")++ else:++ with Image.open(source / "condition_rgba.png") as image:++ rgba = np.asarray(image.convert("RGBA"), dtype=np.float32) / 255.++ Image.fromarray((np.clip(rgba[..., :3] * rgba[..., 3:4], 0, 1) * 255).astype(np.uint8)).save(staged / "condition_rgb.png")++ return _run_side(native, staged, output / "front", camera)+++++def run_dual_view(native_glb: Path, front_input_dir: Path, back_input_dir: Path,+ cameras: dict[str, Any], output_dir: Path) -> Path:+ """Run both measured reprojections and publish the stitched final GLB.++ The caller owns geometry, generated-image, and material-model provenance.+ This function binds the provided model-independent maps, camera pack, native- mesh, operator code, candidate gates, and final atlas in its own receipt.++ mesh, reprojection code, candidate gates, and final atlas in its own receipt.+ """+ native, front, back = (Path(path).resolve(strict=True) for path in (native_glb, front_input_dir, back_input_dir))+ output = Path(output_dir).resolve()+ raw = cameras.get("raw", cameras)+ front_camera, back_camera = camera_spec(raw, "front"), camera_spec(raw, "back")+ for path in (output / "post", output / "post_back"):+ if path.exists():+ raise FileExistsError(f"dual-view reprojection requires a new destination: {path}")+ output.mkdir(parents=True, exist_ok=True)+ final_dir = output / "post_back"+ final_dir.mkdir()+ try:+ write_json(final_dir / "cameras.json", raw)+ front_mesh = _run_side(native, front, output / "post", front_camera)+ rotation, translation, distance = back_to_front(raw["back"])+ rotated = final_dir / "rotated_baseline.glb"+ transform_glb(front_mesh, rotated, rotation, translation)+ canonical_back = {+ "extrinsic": [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, distance], [0, 0, 0, 1]],+ "projection_intrinsic": back_camera["projection_intrinsic"], "distance": distance,+ "camera_angle_x": back_camera["camera_angle_x"], "mesh_scale": 1.0,+ }+ back_mesh = _run_side(rotated, back, final_dir / "reproject", canonical_back)- protected = front_protection(output / "post" / "B" / "COMMON_DOMAIN.npz")++ protected = front_protection(output / "post" / "project" / "COMMON_DOMAIN.npz")+ final = final_dir / "mesh.glb"+ stitch_gates = stitch(front_mesh, back_mesh, protected, final)+ _validate_side(output / "post")+ _validate_side(final_dir / "reproject")+ receipt = {+ "profile": PROFILE, "status": "valid", "view": "dual", "mesh": str(final),+ "gates": {"accepted": True, "front_candidates_accepted_all_19": True,+ "back_candidates_accepted_all_19": True, **stitch_gates},+ "front_post_receipt": bind_file(output / "post" / "receipt.json"),+ "back_post_receipt": bind_file(final_dir / "reproject" / "receipt.json"),+ "camera_pack": bind_file(final_dir / "cameras.json"), "final_mesh": bind_file(final),- "front_protection": bind_file(output / "post" / "B" / "COMMON_DOMAIN.npz"),++ "front_protection": bind_file(output / "post" / "project" / "COMMON_DOMAIN.npz"),+ "back_transform": {"rotation": rotation.tolist(), "translation": translation.tolist(), "distance": distance},+ "validation_scope": "Both view candidates passed 19-phase gates; the stitched atlas has exact front priority and preserved non-base content.",+ }+ write_json(final_dir / "receipt.json", receipt)+ validate_dual_view(output, raise_on_invalid=True)+ return final+ except BaseException as error:+ failure = final_dir / "FAILED.json"+ if not failure.exists():+ write_json(failure, {"profile": PROFILE, "status": "failed", "error": f"{type(error).__name__}: {error}"})+ raise+++def validate_dual_view(output_dir: Path, *, raise_on_invalid: bool = False) -> dict[str, Any]:+ """Re-read the complete postprocess receipt chain and content bindings."""+ try:+ output = Path(output_dir).resolve()+ receipt = read_json(output / "post_back" / "receipt.json")+ if (output / "post_back" / "FAILED.json").exists():+ raise ValueError("dual-view reprojection has a recorded failure")+ if receipt.get("profile") != PROFILE or receipt.get("status") != "valid" or receipt.get("view") != "dual":+ raise ValueError("invalid dual-view reprojection identity or status")+ gates = receipt.get("gates", {})+ required = ("accepted", "front_candidates_accepted_all_19", "back_candidates_accepted_all_19",+ "front_priority_exact", "alpha_exact", "position_exact", "normal_exact", "uv_exact")+ if not all(gates.get(key) is True for key in required) or gates.get("final_19_phase_rendered") is not False:+ raise ValueError("dual-view reprojection gates or validation scope are incomplete")+ check_binding(receipt["front_post_receipt"], output / "post" / "receipt.json")+ check_binding(receipt["back_post_receipt"], output / "post_back" / "reproject" / "receipt.json")- check_binding(receipt["front_protection"], output / "post" / "B" / "COMMON_DOMAIN.npz")++ check_binding(receipt["front_protection"], output / "post" / "project" / "COMMON_DOMAIN.npz")+ camera_path = check_binding(receipt["camera_pack"], output / "post_back" / "cameras.json")+ final = check_binding(receipt["final_mesh"], output / "post_back" / "mesh.glb")+ if Path(receipt.get("mesh", "")).resolve() != final:+ raise ValueError("dual-view final mesh path is inconsistent")+ cameras = read_json(camera_path)+ front_camera = camera_spec(cameras, "front")+ back_camera = camera_spec(cameras, "back")+ rotation, translation, distance = back_to_front(cameras["back"])+ expected_transform = {"rotation": rotation.tolist(), "translation": translation.tolist(), "distance": distance}+ if receipt.get("back_transform") != expected_transform:+ raise ValueError("back transform differs from the camera pack")+ if read_json(output / "post" / "inputs_1024" / "camera.json") != front_camera:+ raise ValueError("front postprocess did not use the bound front camera")+ expected_back = {+ "extrinsic": [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, distance], [0, 0, 0, 1]],+ "projection_intrinsic": back_camera["projection_intrinsic"], "distance": distance,+ "camera_angle_x": back_camera["camera_angle_x"], "mesh_scale": 1.0,+ }+ if read_json(output / "post_back" / "reproject" / "inputs_1024" / "camera.json") != expected_back:+ raise ValueError("back postprocess did not use the canonicalized back camera")+ expected_document, expected_binary = transformed_payload(output / "post" / "mesh.glb", rotation, translation)+ actual_document, actual_binary = _glb._read_glb(output / "post_back" / "rotated_baseline.glb")+ if actual_document != expected_document or actual_binary != expected_binary:+ raise ValueError("temporary back mesh differs from the required rigid transform")+ _validate_side(output / "post")+ _validate_side(output / "post_back" / "reproject")- protected = front_protection(output / "post" / "B" / "COMMON_DOMAIN.npz")++ protected = front_protection(output / "post" / "project" / "COMMON_DOMAIN.npz")+ actual = validate_stitch(output / "post" / "mesh.glb", output / "post_back" / "reproject" / "mesh.glb", final, protected)+ if any(gates.get(key) != value for key, value in actual.items()):+ raise ValueError("stitched preservation evidence changed")+ return {"valid": True, "reason": "Both candidate chains and the stitched final mesh are current", "receipt": receipt}+ except (OSError, ValueError, KeyError, TypeError, RuntimeError) as error:+ if raise_on_invalid:+ raise+ return {"valid": False, "reason": str(error)}diff --cc supratex/inference/reprojection/_common.pyindex d846861,0000000..f36bdeamode 100644,000000..100644--- a/supratex/inference/reprojection/_common.py+++ b/supratex/inference/reprojection/_common.py@@@ -1,115 -1,0 +1,117 @@@+"""File bindings and measured acceptance checks shared by atlas operators."""+from __future__ import annotations++import hashlib+import json+import math+import os+from pathlib import Path+from typing import Any, Mapping++OUTSIDE_COLOR_MAX_ABS = 5 / 255.0+REPLAY_MAX_ABS = 1e-5- TRAIN = tuple((x / 4, y / 4) for x in range(4) for y in range(4))- HELD = ((.125, .375), (.375, .625), (.875, .125))++# Validation render phases, as sub-pixel camera offsets: a 4x4 grid plus three++# off-grid points. Both operators render every candidate at all nineteen.++GRID_PHASES = tuple((x / 4, y / 4) for x in range(4) for y in range(4))++OFFGRID_PHASES = ((.125, .375), (.375, .625), (.875, .125))+IDENTITY_GATES = (+ "materials_exact", "mesh_structure_exact", "node_structure_exact",+ "nonbase_buffer_views_exact",+)+++def outside_color_passes(value: float) -> bool:+ return math.isfinite(value) and 0 <= value <= OUTSIDE_COLOR_MAX_ABS+++def write_json(path: Path, value: Any) -> None:+ """Publish one new JSON artifact without overwriting an earlier result."""+ if path.exists():+ raise FileExistsError(f"refusing to overwrite {path}")+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")+ temporary.write_text(json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + "\n", encoding="utf-8")+ os.replace(temporary, path)+++def read_json(path: Path) -> dict[str, Any]:+ value = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(value, dict):+ raise ValueError(f"expected a JSON object: {path}")+ return value+++def bind_file(path: Path) -> dict[str, Any]:+ path = path.resolve(strict=True)+ if not path.is_file():+ raise ValueError(f"expected a regular file: {path}")+ digest = hashlib.sha256()+ with path.open("rb") as stream:+ for block in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(block)+ return {"path": str(path), "bytes": path.stat().st_size, "sha256": digest.hexdigest()}+++def check_binding(record: Mapping[str, Any], path: Path | None = None) -> Path:+ bound = Path(record["path"])+ if path is not None and bound.resolve() != path.resolve():+ raise ValueError(f"artifact path binding changed: {path}")+ if dict(record) != bind_file(bound):+ raise ValueError(f"artifact content binding changed: {bound}")+ return bound+++def load_renderer(path: Path):+ """Only the renderer shipped in this package may establish these gates."""+ from . import _renderer+ if path.resolve() != Path(_renderer.__file__).resolve():+ raise ValueError("reprojection requires the bundled SupraTex renderer")+ return _renderer+++def validate_candidate(directory: Path, *, continuous: bool) -> dict[str, Any]:+ """Read every phase receipt and validate numerical gates, not just status."""+ receipt = read_json(directory / "RECEIPT.json")+ if read_json(directory / "RESULT.json") != receipt:+ raise ValueError("candidate result and receipt disagree")+ if receipt.get("status") != "valid":+ raise ValueError(f"candidate was not accepted: {directory}")+ gates = receipt.get("gates", {})+ if gates.get("accepted") is not True or gates.get("all_19_phase_renders") is not True:+ raise ValueError("candidate lacks complete acceptance gates")+ if not all(gates.get("nonbase_identity", {}).get(key) is True for key in IDENTITY_GATES):+ raise ValueError("candidate lacks non-base preservation gates")+ if continuous:- if not all(gates.get(key) is True for key in ("UV_covered_exact", "B_active_exact", "blocked_exact", "alpha_exact")):++ if not all(gates.get(key) is True for key in ("UV_covered_exact", "project_active_exact", "blocked_exact", "alpha_exact")):+ raise ValueError("continuous candidate lacks atlas preservation gates")+ elif receipt.get("atlas", {}).get("alpha_exact") is not True:+ raise ValueError("projection candidate did not preserve alpha")+ candidate = directory / "candidate" / "mesh.glb"+ if Path(receipt.get("candidate_glb", "")).resolve() != candidate.resolve() or not candidate.is_file():+ raise ValueError("candidate mesh binding is missing or incorrect")- for split, expected in (("train", TRAIN), ("heldout", HELD)):++ for split, expected in (("grid", GRID_PHASES), ("offgrid", OFFGRID_PHASES)):+ rows = receipt.get("phase_results", {}).get(split, [])+ if len(rows) != len(expected):+ raise ValueError(f"incomplete {split} phase coverage")+ for phase, row in zip(expected, rows):+ if row.get("phase") != list(phase) or row.get("passes") is not True:+ raise ValueError("phase coordinates or acceptance changed")+ replay = float(row["quantized_atlas_replay_max"])+ if not math.isfinite(replay) or not 0 <= replay <= REPLAY_MAX_ABS:+ raise ValueError("renderer replay gate failed")+ if row.get("outside_source_hardtrust_max_abs_threshold") != OUTSIDE_COLOR_MAX_ABS:+ raise ValueError("outside-source color threshold changed")+ if not outside_color_passes(float(row["outside_source_hardtrust_delta_max_abs"])):+ raise ValueError("outside-source color gate failed")+ if row.get("mask_exact") is not True or row.get("mra_exact") is not True:+ raise ValueError("phase mask or material preservation gate is missing")+ folder = directory / "renders" / split / f"x{phase[0]:.3f}_y{phase[1]:.3f}"+ if read_json(folder / "PHASE_RECEIPT.json") != row:+ raise ValueError("phase detail differs from candidate receipt")+ evidence = row.get("evidence", {})- names = ("repair", "B") if continuous else ("candidate", "baseline")++ names = ("repair", "project") if continuous else ("candidate", "baseline")+ if set(evidence) != set(names):+ raise ValueError("phase lacks its two rendered evidence arrays")+ for name in names:+ check_binding(evidence[name], folder / f"{name}.npz")+ return receiptdiff --cc supratex/inference/reprojection/_continuous.pyindex 608b96e,0000000..3a7900dmode 100644,000000..100644--- a/supratex/inference/reprojection/_continuous.py+++ b/supratex/inference/reprojection/_continuous.py@@@ -1,389 -1,0 +1,514 @@@- """Repair one-texel UV gutters with observed continuous albedo gradients."""++"""Repair one-texel UV gutters with observed continuous albedo gradients.++++Each uncovered gutter texel next to an unblocked projected texel is anchored++to that nearest covered donor's projected RGB, then shifted by the predicted++albedo difference between the donor centre and the gutter centre extrapolated++on the donor's UV face. A gutter is written only if both samples have positive++camera depth, a finite non-degenerate UV face, bounded barycentrics, and fully++hard-trusted bilinear source footprints, and if its bilinear atlas taps avoid++untrusted pixels in all nineteen phases. Every UV-covered texel, blocked texel,++alpha, and all non-base GLB content stay exact.++"""+from __future__ import annotations+import argparse, copy, io, json, os, shutil, sys, time+from pathlib import Path- from ._common import OUTSIDE_COLOR_MAX_ABS, outside_color_passes, load_renderer, bind_file++from ._common import GRID_PHASES, OFFGRID_PHASES, OUTSIDE_COLOR_MAX_ABS, IDENTITY_GATES, outside_color_passes, load_renderer, bind_file+from . import _glb as fixed++from ._project import SCHEMA as PROJECT_SCHEMA++SCHEMA = 'supratex.reprojection.continuous'+SIZE = 4096+RES = 1024- TRAIN = tuple(((x / 4, y / 4) for x in range(4) for y in range(4)))- HELD = ((0.125, 0.375), (0.375, 0.625), (0.875, 0.125))+REJECT_UNSAFE = 1+REJECT_CHART = 2+REJECT_DEGENERATE_UV = 4+REJECT_SOURCE = 8++def write_once(path, value):+ if path.exists():+ raise FileExistsError(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + '\n')++def require(path, label):+ path = Path(path).absolute()+ if not path.is_file():+ raise FileNotFoundError(f'{label}: {path}')+ return path++def selected_case(manifest, label):+ found = [x for x in json.loads(require(manifest, 'manifest').read_text()) if x.get('label') == label]+ if len(found) != 1:+ raise ValueError(f'expected one manifest case for {label!r}')+ return found[0]++def assert_skew_barycentric_oracle(np):+ """Catch row/column and signed-area errors on a non-axis-aligned triangle."""+ tri = np.asarray(((0.11, 0.17), (0.83, 0.29), (0.26, 0.91)), np.float64)+ expected = np.asarray((0.19, 0.34, 0.47), np.float64)+ point = (tri * expected[:, None]).sum(0)+ basis = tri[:2] - tri[2]+ solved = np.linalg.solve(basis.T, point - tri[2])+ recovered = np.asarray((solved[0], solved[1], 1 - solved.sum()))+ if not np.allclose(recovered, expected, rtol=0, atol=1e-12):+ raise RuntimeError('skew barycentric oracle failed')++def main():+ ap = argparse.ArgumentParser(description=__doc__)+ ap.add_argument('--manifest', type=Path, required=True)+ ap.add_argument('--case', required=True)- ap.add_argument('--evaluator', type=Path, required=True)++ ap.add_argument('--renderer', type=Path, required=True)+ ap.add_argument('--output', type=Path, required=True)+ ap.add_argument('--gutter-radius', type=int, choices=(1,), default=1, help='Only one-texel gutter repair is supported.')+ a = ap.parse_args()+ if a.output.exists():+ raise FileExistsError(a.output)+ case = selected_case(a.manifest, a.case)- evaluator = require(a.evaluator, 'evaluator')- (work, bdir) = (Path(case['work']).absolute(), Path(case['b_output']).absolute())++ renderer = require(a.renderer, 'renderer')++ (work, pdir) = (Path(case['work']).absolute(), Path(case['project_output']).absolute())+ baseline = require(case['baseline_glb'], 'baseline GLB')- bglb = require(bdir / 'candidate/mesh.glb', 'accepted B GLB')++ pglb = require(pdir / 'candidate/mesh.glb', 'accepted projection GLB')+ camera_path = require(work / 'camera.json', 'camera')+ rgba_path = require(work / 'condition_rgba.png', 'condition RGBA')+ albedo_path = require(work / 'albedo.png', 'predicted albedo')- domain_path = require(bdir / 'COMMON_DOMAIN.npz', 'B common domain')- bplan = json.loads(require(bdir / 'PLAN.json', 'B PLAN').read_text())- bresult = json.loads(require(bdir / 'RESULT.json', 'B RESULT').read_text())- expected = {'arm': 'B', 'baseline_glb': str(baseline), 'camera': str(camera_path), 'source_albedo': str(albedo_path), 'source_rgba': str(rgba_path), 'evaluator': str(evaluator)}- if [k for (k, v) in expected.items() if bplan.get(k) != v]:- raise RuntimeError('B PLAN binding failed')- if bresult.get('status') != 'valid' or not bresult.get('gates', {}).get('accepted'):- raise RuntimeError('B source is not an accepted B result')- if Path(bresult.get('candidate_glb', '')).absolute() != bglb:- raise RuntimeError('B result candidate binding failed')- identity = bresult.get('gates', {}).get('nonbase_identity', {})- if not all((identity.get(k) for k in ('materials_exact', 'mesh_structure_exact', 'node_structure_exact', 'nonbase_buffer_views_exact'))):- raise RuntimeError('B non-base identity gate failed')- phases = bresult.get('phase_results', {}).get('train', []) + bresult.get('phase_results', {}).get('heldout', [])- if not bresult.get('gates', {}).get('all_19_phase_renders') or not bresult.get('atlas', {}).get('alpha_exact') or len(phases) != 19 or (not all((x.get('passes') for x in phases))):- raise RuntimeError('B alpha or 19-phase receipt binding failed')++ domain_path = require(pdir / 'COMMON_DOMAIN.npz', 'projection common domain')++ pplan = json.loads(require(pdir / 'PLAN.json', 'projection PLAN').read_text())++ presult = json.loads(require(pdir / 'RESULT.json', 'projection RESULT').read_text())++ expected = {++ 'schema': PROJECT_SCHEMA,++ 'baseline_glb': str(baseline),++ 'camera': str(camera_path),++ 'source_albedo': str(albedo_path),++ 'source_rgba': str(rgba_path),++ 'renderer': str(renderer),++ }++ if [k for (k, v) in expected.items() if pplan.get(k) != v]:++ raise RuntimeError('projection PLAN binding failed')++ if presult.get('status') != 'valid' or not presult.get('gates', {}).get('accepted'):++ raise RuntimeError('projection source is not an accepted projection result')++ if Path(presult.get('candidate_glb', '')).absolute() != pglb:++ raise RuntimeError('projection result candidate binding failed')++ identity = presult.get('gates', {}).get('nonbase_identity', {})++ if not all((identity.get(k) for k in IDENTITY_GATES)):++ raise RuntimeError('projection non-base identity gate failed')++ phase_results = presult.get('phase_results', {})++ phases = phase_results.get('grid', []) + phase_results.get('offgrid', [])++ if (not presult.get('gates', {}).get('all_19_phase_renders')++ or not presult.get('atlas', {}).get('alpha_exact')++ or len(phases) != 19++ or not all((x.get('passes') for x in phases))):++ raise RuntimeError('projection alpha or 19-phase receipt binding failed')+ a.output.mkdir(parents=True)+ shutil.copyfile(Path(__file__), a.output / 'CODE_SNAPSHOT.py')- write_once(a.output / 'PLAN.json', {'schema': 'supratex.reprojection.continuous', 'case': a.case, 'manifest': str(a.manifest.absolute()), 'accepted_b_glb': str(bglb), 'baseline_glb': str(baseline), 'camera': str(camera_path), 'evaluator': str(evaluator), 'source_albedo': str(albedo_path), 'source_rgba': str(rgba_path), 'common_domain': str(domain_path), 'train_phases': TRAIN, 'heldout_phases': HELD, 'gutter_radius': a.gutter_radius, 'operator': 'anchor each gutter to its accepted-B nearest covered donor RGB, then add the continuous predicted-albedo projection gradient from donor centre to extrapolated gutter centre', 'preservation': 'every UV-covered texel, blocked ID, alpha, mesh and all non-base GLB content remain exact', 'source_guard': 'requires positive camera depth, a finite non-degenerate UV face, bounded extrapolated barycentrics, and all four native source bilinear footprint pixels hard-trusted for both donor and extrapolated gutter samples', 'unsafe': 'all bilinear atlas taps of non-hard-trusted pixels from all 19 declared phases are excluded before writes', 'limits': 'Construction uses train and held-out phases for safety; held-out render is a validation phase, not independent selection.'})++ write_once(a.output / 'PLAN.json', {++ 'schema': SCHEMA,++ 'case': a.case,++ 'manifest': str(a.manifest.absolute()),++ 'project_glb': str(pglb),++ 'baseline_glb': str(baseline),++ 'camera': str(camera_path),++ 'renderer': str(renderer),++ 'source_albedo': str(albedo_path),++ 'source_rgba': str(rgba_path),++ 'common_domain': str(domain_path),++ 'grid_phases': GRID_PHASES,++ 'offgrid_phases': OFFGRID_PHASES,++ 'gutter_radius': a.gutter_radius,++ })+ os.environ['FLEX_GEMM_USE_AUTOTUNE_CACHE'] = '0'+ os.environ['FLEX_GEMM_AUTOSAVE_AUTOTUNE_CACHE'] = '0'+ import cv2+ import numpy as np+ import torch+ from PIL import Image+ assert_skew_barycentric_oracle(np)+ torch.backends.cuda.matmul.allow_tf32 = False+ torch.manual_seed(42)+ started = time.monotonic()- rm = load_renderer(evaluator)++ rm = load_renderer(renderer)+ rt = rm._runtime_imports()+ dr = rt['dr']+ camera = json.loads(camera_path.read_text())- (bdoc, bbin) = fixed._read_glb(bglb)- fixed._assert_fixed_scene(bdoc)- (ii, vi) = fixed._base_color_image_ref(bdoc)- (bimg, _, off, n) = fixed._decode_base_image(bdoc, bbin, ii, vi)- before = np.asarray(bimg).copy()++ (pdoc, pbin) = fixed._read_glb(pglb)++ fixed._assert_fixed_scene(pdoc)++ (ii, vi) = fixed._base_color_image_ref(pdoc)++ (pimg, _, off, n) = fixed._decode_base_image(pdoc, pbin, ii, vi)++ before = np.asarray(pimg).copy()+ (basedoc, basebin) = fixed._read_glb(baseline)+ fixed._assert_fixed_scene(basedoc)+ (baseii, basevi) = fixed._base_color_image_ref(basedoc)+ (baseimg, _, _, _) = fixed._decode_base_image(basedoc, basebin, baseii, basevi)+ base_before = np.asarray(baseimg).copy()+ if before.shape[:2] != (SIZE, SIZE):+ raise ValueError('requires 4096 atlas')+ if base_before.shape != before.shape:- raise RuntimeError('baseline/B baseColor image shape mismatch')++ raise RuntimeError('baseline/projection baseColor image shape mismatch')+ with np.load(domain_path, allow_pickle=False) as z:+ (active_ids, blocked_ids) = (z['active_texel_ids'].astype(np.int64), z['blocked_texel_ids'].astype(np.int64))- if len(active_ids) != int(bresult.get('atlas', {}).get('active_texels', -1)) or len(blocked_ids) != int(bresult.get('atlas', {}).get('blocked_texels', -1)) or len(np.unique(active_ids)) != len(active_ids) or (len(np.unique(blocked_ids)) != len(blocked_ids)):- raise RuntimeError('B common-domain count or uniqueness binding failed')++ project_atlas = presult.get('atlas', {})++ if (len(active_ids) != int(project_atlas.get('active_texels', -1))++ or len(blocked_ids) != int(project_atlas.get('blocked_texels', -1))++ or len(np.unique(active_ids)) != len(active_ids)++ or len(np.unique(blocked_ids)) != len(blocked_ids)):++ raise RuntimeError('projection common-domain count or uniqueness binding failed')+ (active, blocked) = (np.zeros(SIZE * SIZE, bool), np.zeros(SIZE * SIZE, bool))+ (active[active_ids], blocked[blocked_ids]) = (True, True)+ if np.any(blocked & ~active):- raise RuntimeError('blocked IDs must be in B active domain')- (vertices, faces_np, _, uv_np, _, _, factor, _, _) = rt['_load_textured_mesh'](bglb, rt)++ raise RuntimeError('blocked IDs must be in the projection active domain')++ (vertices, faces_np, _, uv_np, _, _, factor, _, _) = rt['_load_textured_mesh'](pglb, rt)+ if not np.allclose(factor, 1):+ raise RuntimeError('unexpected baseColorFactor')+ exported = torch.as_tensor(vertices, dtype=torch.float32, device='cuda')+ native = exported * torch.tensor((-1.0, 1.0, -1.0), device='cuda')+ faces = torch.as_tensor(faces_np, dtype=torch.int32, device='cuda').contiguous()+ uv = torch.as_tensor(uv_np, dtype=torch.float32, device='cuda')+ uv = torch.stack((uv[:, 0], 1 - uv[:, 1]), -1).contiguous()+ rgba = np.asarray(Image.open(rgba_path).convert('RGBA'))+ hard = cv2.erode((rgba[..., 3] >= 254).astype('uint8'), np.ones((5, 5), np.uint8)).astype(bool)+ source = np.asarray(Image.open(albedo_path).convert('RGB'), np.float32) / 255+ if hard.shape != (RES, RES) or source.shape[:2] != (RES, RES):+ raise ValueError('source inputs must be aligned 1024')+ hard_t = torch.as_tensor(hard, device='cuda')+ src = torch.as_tensor(source, device='cuda').permute(2, 0, 1)[None]+ trust = np.clip(cv2.distanceTransform(hard.astype('uint8'), cv2.DIST_L2, 3) / 4.0, 0, 1)+ trust_t = torch.as_tensor(trust, dtype=torch.float32, device='cuda')[None, None]+ (E, K) = rm._native_camera(camera, 'cuda', rt)+ original = rm._exported_glb_camera++ def pc(cam, device, runtime):+ (ex, inn) = original(cam, device, runtime)+ (dx, dy) = cam.get('front_atlas_phase', (0.0, 0.0))+ inn = inn.clone()+ inn[0, 2] += dx / RES+ inn[1, 2] += dy / RES+ return (ex, inn)+ rm._exported_glb_camera = pc++ def footprint(rows, uvs):+ tex = uvs[0].reshape(-1, 2)[rows] * SIZE - 0.5+ (xy, frac) = (tex.floor().long(), tex - tex.floor())+ (ids, weights) = ([], [])+ for (dx, dy) in ((0, 0), (1, 0), (0, 1), (1, 1)):+ ids.append((xy[:, 1] + dy) % SIZE * SIZE + (xy[:, 0] + dx) % SIZE)+ weights.append((frac[:, 0] if dx else 1 - frac[:, 0]) * (frac[:, 1] if dy else 1 - frac[:, 1]))+ return (torch.stack(ids, 1), torch.stack(weights, 1))++ def operation(phase):+ cam = copy.deepcopy(camera)+ cam['front_atlas_phase'] = phase+ (ee, kk) = pc(cam, 'cuda', rt)+ dist = rm._camera_distance(cam)+ proj = rt['intrinsics_to_projection'](kk, max(0.2, dist - 1), dist + 1)+ h = torch.cat((exported, torch.ones_like(exported[:, :1])), 1)+ (rast, _) = dr.rasterize(dr.RasterizeCudaContext(device='cuda'), (h @ (proj @ ee).T)[None].contiguous(), faces, (RES, RES))+ (uvs, _) = dr.interpolate(uv[None], rast, faces)+ (pts, _) = dr.interpolate(native[None], rast, faces)+ mask = (rast[0, ..., -1] > 0).cpu().numpy()+ rowsall = torch.as_tensor(np.flatnonzero(mask.reshape(-1)), device='cuda')+ xyz = pts[0].reshape(-1, 3)[rowsall]+ q = torch.cat((xyz, torch.ones_like(xyz[:, :1])), 1) @ E.T+ q = q[:, :3] @ K.T+ suv = q[:, :2] / q[:, 2:3].clamp_min(1e-08)+ near = torch.floor(suv * RES).long()+ inside = (near[:, 0] >= 0) & (near[:, 0] < RES) & (near[:, 1] >= 0) & (near[:, 1] < RES) & (q[:, 2] > 0)+ trusted = torch.zeros(len(rowsall), dtype=torch.bool, device='cuda')+ trusted[inside] = hard_t[near[inside, 1], near[inside, 0]]+ rows = rowsall[trusted]+ (idx, weights) = footprint(rows, uvs)+ unsafe_screen = np.zeros(RES * RES, np.uint8)+ unsafe_screen[rowsall[~trusted].cpu().numpy()] = 1+ unsafe_screen = cv2.dilate(unsafe_screen.reshape(RES, RES), np.ones((5, 5), np.uint8)) & mask+ unsafe_rows = torch.as_tensor(np.flatnonzero(unsafe_screen.reshape(-1)), device='cuda')+ unsafe = footprint(unsafe_rows, uvs)[0] if len(unsafe_rows) else torch.empty((0, 4), dtype=torch.long, device='cuda')+ target = rt['F'].grid_sample(src, (suv[trusted] * 2 - 1).reshape(1, 1, -1, 2), align_corners=False, padding_mode='zeros')[0, :, 0].T+ screen = np.zeros(RES * RES, bool)+ screen[rows.cpu().numpy()] = True- return {'phase': phase, 'idx': idx, 'w': weights, 'unsafe': unsafe, 'rows': rows, 'screen': screen.reshape(RES, RES), 'target': target}- operations = [operation(p) for p in TRAIN + HELD]- unsafe_ids = torch.unique(torch.cat([x['unsafe'].reshape(-1) for x in operations if x['unsafe'].numel()])) if any((x['unsafe'].numel() for x in operations)) else torch.empty(0, dtype=torch.long, device='cuda')++ return {++ 'phase': phase,++ 'idx': idx,++ 'w': weights,++ 'unsafe': unsafe,++ 'rows': rows,++ 'screen': screen.reshape(RES, RES),++ 'target': target,++ }++ operations = [operation(p) for p in GRID_PHASES + OFFGRID_PHASES]++ if any(x['unsafe'].numel() for x in operations):++ unsafe_ids = torch.unique(torch.cat([x['unsafe'].reshape(-1) for x in operations if x['unsafe'].numel()]))++ else:++ unsafe_ids = torch.empty(0, dtype=torch.long, device='cuda')+ unsafe = np.zeros(SIZE * SIZE, bool)+ unsafe[unsafe_ids.cpu().numpy()] = True+ uvclip = torch.cat((uv * 2 - 1, torch.zeros_like(uv[:, :1]), torch.ones_like(uv[:, :1])), 1)[None]+ (urast, _) = dr.rasterize(dr.RasterizeCudaContext(device='cuda'), uvclip, faces, (SIZE, SIZE))+ covered = (urast[0, ..., -1] > 0).cpu().numpy()+ (fcpu, uvcpu) = (faces.cpu().numpy(), uv.cpu().numpy())+ parent = np.arange(len(fcpu), dtype=np.int32)++ def root(i):+ while parent[i] != i:+ parent[i] = parent[parent[i]]+ i = parent[i]+ return i++ def join(i, j):+ (i, j) = (root(i), root(j))+ if i != j:+ parent[j] = i+ edges = {}+ for (fi, tri) in enumerate(fcpu):+ for (u, v) in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])):+ key = (int(min(u, v)), int(max(u, v)))+ if key in edges:+ join(fi, edges[key])+ else:+ edges[key] = fi+ face_chart = np.asarray([root(i) for i in range(len(fcpu))], np.int32)+ (_, face_chart) = np.unique(face_chart, return_inverse=True)+ primitive = urast[0, ..., -1].long().cpu().numpy() - 1+ chart = np.full((SIZE, SIZE), -1, np.int32)+ chart[covered] = face_chart[primitive[covered]]+ core = (active & ~blocked).reshape(SIZE, SIZE) & covered+ if np.any(active.reshape(SIZE, SIZE) & ~covered):- raise RuntimeError('B active domain includes uncovered texels')++ raise RuntimeError('projection active domain includes uncovered texels')+ base = ~covered & ~blocked.reshape(SIZE, SIZE)+ rejection = np.zeros((SIZE, SIZE), np.uint8)+ rejection[base & unsafe.reshape(SIZE, SIZE)] |= REJECT_UNSAFE+ candidate = np.zeros_like(core)+ (donor_y, donor_x) = (np.full(core.shape, -1, np.int32), np.full(core.shape, -1, np.int32))+ donor_chart = np.full_like(chart, -1)+ for (dy, dx) in ((-1, 0), (0, -1), (0, 1), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)):+ shifted = np.zeros_like(core)+ (sy, sx) = (slice(max(0, -dy), SIZE - max(0, dy)), slice(max(0, -dx), SIZE - max(0, dx)))+ (ty, tx) = (slice(max(0, dy), SIZE - max(0, -dy)), slice(max(0, dx), SIZE - max(0, -dx)))+ shifted[ty, tx] = core[sy, sx]+ add = shifted & base & ~unsafe.reshape(SIZE, SIZE)+ (ay, ax) = np.nonzero(add)+ labels = chart[ay - dy, ax - dx]+ for (y, x, label) in zip(ay.tolist(), ax.tolist(), labels.tolist()):+ if not candidate[y, x]:+ candidate[y, x] = True+ donor_y[y, x] = y - dy+ donor_x[y, x] = x - dx+ donor_chart[y, x] = label+ elif donor_chart[y, x] != label:+ donor_chart[y, x] = -1+ prechart = candidate.copy()+ for (dy, dx) in ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)):+ neigh = np.full_like(chart, -1)+ neigh[max(0, dy):SIZE - max(0, -dy), max(0, dx):SIZE - max(0, -dx)] = chart[max(0, -dy):SIZE - max(0, dy), max(0, -dx):SIZE - max(0, dx)]+ candidate &= (neigh < 0) | (neigh == donor_chart)+ candidate &= donor_chart >= 0+ rejection[prechart & ~candidate] |= REJECT_CHART+ (cy, cx) = np.nonzero(candidate)+ did = donor_y[cy, cx].astype(np.int64) * SIZE + donor_x[cy, cx]+ dfi = primitive.reshape(-1)[did]+ tri_uv = uvcpu[fcpu[dfi]].astype(np.float64)+ point_uv = np.stack(((cx + 0.5) / SIZE, (cy + 0.5) / SIZE), 1).astype(np.float64)+ basis = tri_uv[:, :2] - tri_uv[:, 2:3]+ det = basis[:, 0, 0] * basis[:, 1, 1] - basis[:, 0, 1] * basis[:, 1, 0]+ finite_face = np.isfinite(tri_uv).all((1, 2)) & (np.abs(det) > 1e-12)+ bary = np.full((len(cy), 3), np.nan, np.float32)+ good = finite_face+ delta = point_uv[good] - tri_uv[good, 2]+ bary[good, :2] = np.linalg.solve(np.swapaxes(basis[good], 1, 2), delta[..., None])[..., 0]+ bary[good, 2] = 1 - bary[good, 0] - bary[good, 1]+ good &= np.isfinite(bary).all(1) & (np.abs(bary).max(1) <= 8.0)+ rejection[cy[~good], cx[~good]] |= REJECT_DEGENERATE_UV+ tri_native = vertices[fcpu[dfi]].astype(np.float64) * np.array((-1.0, 1.0, -1.0), np.float64)+ xyz = (tri_native * bary[:, :, None]).sum(1)+ donor_uv = np.stack(((donor_x[cy, cx] + 0.5) / SIZE, (donor_y[cy, cx] + 0.5) / SIZE), 1)+ donor_delta = donor_uv - tri_uv[:, 2]+ donor_bary = np.full((len(cy), 3), np.nan, np.float32)+ donor_bary[good, :2] = np.linalg.solve(np.swapaxes(basis[good], 1, 2), donor_delta[good, ..., None])[..., 0]+ donor_bary[good, 2] = 1 - donor_bary[good, 0] - donor_bary[good, 1]+ good &= np.isfinite(donor_bary).all(1) & (np.abs(donor_bary).max(1) <= 8.0)+ donor_contained = (donor_bary >= -1e-05).all(1) & (donor_bary <= 1 + 1e-05).all(1)+ good &= donor_contained+ rejection[cy[~donor_contained], cx[~donor_contained]] |= REJECT_DEGENERATE_UV+ reconstructed_donor_uv = (tri_uv * donor_bary[:, :, None]).sum(1)+ donor_uv_error = np.abs(reconstructed_donor_uv - donor_uv).max(1)+ good &= donor_uv_error <= 1e-06+ rejection[cy[~good], cx[~good]] |= REJECT_DEGENERATE_UV+ donor_xyz = (tri_native * donor_bary[:, :, None]).sum(1)+ (atlas_native, _) = dr.interpolate(native[None], urast, faces)+ donor_surface = atlas_native[0, torch.as_tensor(donor_y[cy, cx], device='cuda'), torch.as_tensor(donor_x[cy, cx], device='cuda')].cpu().numpy()+ del atlas_native+ donor_surface_error = np.abs(donor_surface - donor_xyz).max(1)+ surface_checked = good.copy()+ surface_ok = donor_surface_error <= 1e-05+ good &= surface_ok+ rejection[cy[~surface_ok], cx[~surface_ok]] |= REJECT_DEGENERATE_UV++ def project_native(points):+ points_t = torch.as_tensor(points, dtype=torch.float32, device='cuda')+ q = torch.cat((points_t, torch.ones_like(points_t[:, :1])), 1) @ E.T+ q = q[:, :3] @ K.T+ return ((q[:, :2] / q[:, 2:3]).cpu().numpy(), q[:, 2].cpu().numpy())+ (source_uv, source_depth) = project_native(xyz)+ (donor_source_uv, donor_depth) = project_native(donor_xyz)+ cell = np.floor(np.where(np.isfinite(source_uv), source_uv, -2.0) * RES - 0.5).astype(np.int64)+ donor_cell = np.floor(np.where(np.isfinite(donor_source_uv), donor_source_uv, -2.0) * RES - 0.5).astype(np.int64)+ footprint_ok = good & np.isfinite(source_uv).all(1) & np.isfinite(donor_source_uv).all(1) & (source_depth > 0) & (donor_depth > 0)+ footprint_ok &= (cell[:, 0] >= 0) & (cell[:, 0] + 1 < RES) & (cell[:, 1] >= 0) & (cell[:, 1] + 1 < RES)+ footprint_ok &= (donor_cell[:, 0] >= 0) & (donor_cell[:, 0] + 1 < RES) & (donor_cell[:, 1] >= 0) & (donor_cell[:, 1] + 1 < RES)+ fi = np.flatnonzero(footprint_ok)+ if len(fi):- footprint_ok[fi] &= hard[cell[fi, 1], cell[fi, 0]] & hard[cell[fi, 1], cell[fi, 0] + 1] & hard[cell[fi, 1] + 1, cell[fi, 0]] & hard[cell[fi, 1] + 1, cell[fi, 0] + 1] & hard[donor_cell[fi, 1], donor_cell[fi, 0]] & hard[donor_cell[fi, 1], donor_cell[fi, 0] + 1] & hard[donor_cell[fi, 1] + 1, donor_cell[fi, 0]] & hard[donor_cell[fi, 1] + 1, donor_cell[fi, 0] + 1]++ footprint_ok[fi] &= (hard[cell[fi, 1], cell[fi, 0]] & hard[cell[fi, 1], cell[fi, 0] + 1]++ & hard[cell[fi, 1] + 1, cell[fi, 0]] & hard[cell[fi, 1] + 1, cell[fi, 0] + 1]++ & hard[donor_cell[fi, 1], donor_cell[fi, 0]] & hard[donor_cell[fi, 1], donor_cell[fi, 0] + 1]++ & hard[donor_cell[fi, 1] + 1, donor_cell[fi, 0]] & hard[donor_cell[fi, 1] + 1, donor_cell[fi, 0] + 1])+ donor_strength = rt['F'].grid_sample(trust_t, (torch.as_tensor(donor_source_uv, dtype=torch.float32, device='cuda') * 2 - 1).reshape(1, 1, -1, 2), align_corners=False, padding_mode='zeros')[0, 0, 0].cpu().numpy()+ endpoint_strength = rt['F'].grid_sample(trust_t, (torch.as_tensor(source_uv, dtype=torch.float32, device='cuda') * 2 - 1).reshape(1, 1, -1, 2), align_corners=False, padding_mode='zeros')[0, 0, 0].cpu().numpy()+ footprint_ok &= (donor_strength >= 1 - 1e-06) & (endpoint_strength >= 1 - 1e-06)+ sample_uv = torch.as_tensor(source_uv[footprint_ok], dtype=torch.float32, device='cuda')+ donor_sample_uv = torch.as_tensor(donor_source_uv[footprint_ok], dtype=torch.float32, device='cuda')+ sampled = rt['F'].grid_sample(src, (sample_uv * 2 - 1).reshape(1, 1, -1, 2), align_corners=False, padding_mode='zeros')[0, :, 0].T.cpu().numpy()+ donor_sampled = rt['F'].grid_sample(src, (donor_sample_uv * 2 - 1).reshape(1, 1, -1, 2), align_corners=False, padding_mode='zeros')[0, :, 0].T.cpu().numpy()+ source_rows = np.flatnonzero(footprint_ok)+ donor_base = base_before[donor_y[cy[source_rows], cx[source_rows]], donor_x[cy[source_rows], cx[source_rows]], :3].astype(np.float32) / 255+ donor_actual = before[donor_y[cy[source_rows], cx[source_rows]], donor_x[cy[source_rows], cx[source_rows]], :3].astype(np.float32) / 255+ donor_rebuilt = donor_base + donor_strength[source_rows, None] * (donor_sampled - donor_base)- donor_b_source_byte_error = np.full(len(cy), np.inf, np.float32)- donor_b_source_byte_error[source_rows] = np.abs(donor_rebuilt - donor_actual).max(1) * 255- donor_b_source_ok = donor_b_source_byte_error <= 1.0- rejection[cy[~footprint_ok | footprint_ok & ~donor_b_source_ok], cx[~footprint_ok | footprint_ok & ~donor_b_source_ok]] |= REJECT_SOURCE- continuous_ok = footprint_ok & donor_b_source_ok++ donor_project_byte_error = np.full(len(cy), np.inf, np.float32)++ donor_project_byte_error[source_rows] = np.abs(donor_rebuilt - donor_actual).max(1) * 255++ donor_project_ok = donor_project_byte_error <= 1.0++ source_rejected = ~footprint_ok | footprint_ok & ~donor_project_ok++ rejection[cy[source_rejected], cx[source_rejected]] |= REJECT_SOURCE++ continuous_ok = footprint_ok & donor_project_ok+ eligible = np.zeros_like(base)+ eligible[cy[continuous_ok], cx[continuous_ok]] = True+ after = before.copy()+ after[cy, cx, :3] = before[donor_y[cy, cx], donor_x[cy, cx], :3]+ if not np.array_equal(after[cy, cx, :3], before[donor_y[cy, cx], donor_x[cy, cx], :3]):- raise RuntimeError('accepted-B donor byte fallback failed')++ raise RuntimeError('projection donor byte fallback failed')+ (ey, ex) = np.nonzero(eligible)+ anchor = before[donor_y[ey, ex], donor_x[ey, ex], :3].astype(np.float32) / 255+ selected_rows = np.flatnonzero(continuous_ok)+ sample_indices = np.searchsorted(source_rows, selected_rows)+ after[ey, ex, :3] = np.clip((anchor + sampled[sample_indices] - donor_sampled[sample_indices]) * 255 + 0.5, 0, 255).astype(np.uint8)+ if not np.array_equal(after[covered], before[covered]):+ raise RuntimeError('UV covered preservation failed')+ if after.shape[-1] == 4 and (not np.array_equal(after[..., 3], before[..., 3])):+ raise RuntimeError('alpha changed')+ if not np.array_equal(after.reshape(-1, after.shape[-1])[active | blocked | unsafe], before.reshape(-1, before.shape[-1])[active | blocked | unsafe]):+ raise RuntimeError('active, blocked, or unsafe texels changed')+ eligible_ids = np.flatnonzero(eligible.reshape(-1))- np.savez_compressed(a.output / 'GUTTER_DIAGNOSTICS.npz', covered=covered, unsafe=unsafe.reshape(SIZE, SIZE), candidate=candidate, eligible=eligible, rejection=rejection, eligible_texel_ids=eligible_ids, donor_texel_ids=did[continuous_ok], donor_charts=donor_chart.reshape(-1)[eligible_ids], source_uv=source_uv[continuous_ok], donor_source_uv=donor_source_uv[continuous_ok], barycentric=bary[continuous_ok], donor_barycentric=donor_bary[continuous_ok], donor_uv_reconstruction_error=donor_uv_error[continuous_ok], donor_surface_error=donor_surface_error[continuous_ok], donor_strength=donor_strength[continuous_ok], endpoint_strength=endpoint_strength[continuous_ok], donor_b_source_byte_error=donor_b_source_byte_error[continuous_ok], gutter_radius=np.asarray(a.gutter_radius, dtype=np.int32))++ np.savez_compressed(++ a.output / 'GUTTER_DIAGNOSTICS.npz',++ covered=covered,++ unsafe=unsafe.reshape(SIZE, SIZE),++ candidate=candidate,++ eligible=eligible,++ rejection=rejection,++ eligible_texel_ids=eligible_ids,++ donor_texel_ids=did[continuous_ok],++ donor_charts=donor_chart.reshape(-1)[eligible_ids],++ source_uv=source_uv[continuous_ok],++ donor_source_uv=donor_source_uv[continuous_ok],++ barycentric=bary[continuous_ok],++ donor_barycentric=donor_bary[continuous_ok],++ donor_uv_reconstruction_error=donor_uv_error[continuous_ok],++ donor_surface_error=donor_surface_error[continuous_ok],++ donor_strength=donor_strength[continuous_ok],++ endpoint_strength=endpoint_strength[continuous_ok],++ donor_project_byte_error=donor_project_byte_error[continuous_ok],++ gutter_radius=np.asarray(a.gutter_radius, dtype=np.int32),++ )+ blob = io.BytesIO()+ Image.fromarray(after).save(blob, format='PNG')- odoc = copy.deepcopy(bdoc)- obin = fixed._replace_image_payload(odoc, bbin, vi, off, n, blob.getvalue())++ odoc = copy.deepcopy(pdoc)++ obin = fixed._replace_image_payload(odoc, pbin, vi, off, n, blob.getvalue())+ glb = a.output / 'candidate/mesh.glb'+ glb.parent.mkdir()+ fixed._write_glb(glb, odoc, obin)- preservation = fixed._nonbase_identity_check(bdoc, bbin, glb, vi)++ preservation = fixed._nonbase_identity_check(pdoc, pbin, glb, vi)++ def render(o, split):+ p = o['phase']+ folder = a.output / 'renders' / split / f'x{p[0]:.3f}_y{p[1]:.3f}'+ folder.mkdir(parents=True)+ cam = copy.deepcopy(camera)+ cam['front_atlas_phase'] = p- (ca, bb) = (rm.render_glb(glb, cam, folder / 'repair.png', resolution=RES, rt=rt), rm.render_glb(bglb, cam, folder / 'B.png', resolution=RES, rt=rt))++ ca = rm.render_glb(glb, cam, folder / 'repair.png', resolution=RES, rt=rt)++ pa = rm.render_glb(pglb, cam, folder / 'project.png', resolution=RES, rt=rt)+ with np.load(ca['attrs_npz']) as z:+ (ci, cm, cmra) = (z['albedo'], z['mask'].astype(bool), z['mra'])- with np.load(bb['attrs_npz']) as z:++ with np.load(pa['attrs_npz']) as z:+ (bi, bm, bmra) = (z['albedo'], z['mask'].astype(bool), z['mra'])+ if not np.array_equal(cm, bm) or not np.array_equal(cmra, bmra):+ raise RuntimeError('mask/MRA changed')+ target = np.zeros_like(ci)+ target.reshape(-1, 3)[o['rows'].cpu().numpy()] = o['target'].cpu().numpy()+ sel = o['screen'] & cm+ quant = torch.as_tensor(after[..., :3], dtype=torch.float32, device='cuda').reshape(-1, 3) / 255+ replay = (quant[o['idx']] * o['w'][..., None]).sum(1).cpu().numpy()+ actual = ci.reshape(-1, 3)[o['rows'].cpu().numpy()]+ outside = cm & ~o['screen']+ outdelta = float(np.abs(ci - bi)[outside].max()) if outside.any() else 0.0+ changed = cm & (np.abs(ci - bi).max(2) > 0)- r = {'phase': p, 'hardtrust_pixels': int(sel.sum()), 'repair_vs_source': rm._masked_metrics(ci, target, sel), 'B_vs_source': rm._masked_metrics(bi, target, sel), 'repair_vs_B_changed_pixels': int(changed.sum()), 'repair_vs_B': rm._masked_metrics(ci, bi, changed) if changed.any() else {'valid_pixels': 0}, 'quantized_atlas_replay_max': float(np.abs(replay - actual).max()), 'outside_source_hardtrust_max_abs_threshold': OUTSIDE_COLOR_MAX_ABS, 'outside_source_hardtrust_delta_max_abs': outdelta}++ r = {++ 'phase': p,++ 'hardtrust_pixels': int(sel.sum()),++ 'repair_vs_source': rm._masked_metrics(ci, target, sel),++ 'project_vs_source': rm._masked_metrics(bi, target, sel),++ 'repair_vs_project_changed_pixels': int(changed.sum()),++ 'repair_vs_project': rm._masked_metrics(ci, bi, changed) if changed.any() else {'valid_pixels': 0},++ 'quantized_atlas_replay_max': float(np.abs(replay - actual).max()),++ 'outside_source_hardtrust_max_abs_threshold': OUTSIDE_COLOR_MAX_ABS,++ 'outside_source_hardtrust_delta_max_abs': outdelta,++ }+ r['passes'] = bool(r['quantized_atlas_replay_max'] <= 1e-05 and outside_color_passes(outdelta))- r.update(mask_exact=True, mra_exact=True, evidence={'repair': bind_file(Path(ca['attrs_npz'])), 'B': bind_file(Path(bb['attrs_npz']))})++ r.update(mask_exact=True, mra_exact=True, evidence={'repair': bind_file(Path(ca['attrs_npz'])), 'project': bind_file(Path(pa['attrs_npz']))})+ write_once(folder / 'PHASE_RECEIPT.json', r)+ return r- results = [render(x, 'train' if i < len(TRAIN) else 'heldout') for (i, x) in enumerate(operations)]++ results = [render(x, 'grid' if i < len(GRID_PHASES) else 'offgrid') for (i, x) in enumerate(operations)]+ changed = np.any(after[..., :3] != before[..., :3], axis=-1)+ accepted = all((x['passes'] for x in results))- gate_ok = accepted and all((preservation.get(k) for k in ('materials_exact', 'mesh_structure_exact', 'node_structure_exact', 'nonbase_buffer_views_exact')))- receipt = {'status': 'valid' if gate_ok else 'invalid', 'candidate_glb': str(glb), 'seconds': time.monotonic() - started, 'gates': {'accepted': gate_ok, 'UV_covered_exact': True, 'B_active_exact': True, 'blocked_exact': True, 'alpha_exact': True, 'nonbase_identity': preservation, 'all_19_phase_renders': len(results) == 19}, 'atlas': {'UV_covered_texels': int(covered.sum()), 'UV_face_charts': int(face_chart.max() + 1), 'B_active_texels': int(active.sum()), 'blocked_texels': int(blocked.sum()), 'unsafe_all_phase_texels': int(unsafe.sum()), 'gutter_radius': a.gutter_radius, 'nearest_donor_uncovered_gutter_texels': int(candidate.sum()), 'continuous_eligible_uncovered_gutter_texels': int(eligible.sum()), 'changed_texels': int(changed.sum()), 'rejected_unsafe': int((rejection & REJECT_UNSAFE != 0).sum()), 'rejected_chart': int((rejection & REJECT_CHART != 0).sum()), 'rejected_degenerate_uv': int((rejection & REJECT_DEGENERATE_UV != 0).sum()), 'rejected_source_footprint_or_feather': int((rejection & REJECT_SOURCE != 0).sum()), 'donor_surface_oracle': {'threshold': 1e-05, 'checked': int(surface_checked.sum()), 'rejected': int((surface_checked & ~surface_ok).sum()), 'pre_filter_max': float(donor_surface_error[surface_checked].max()) if surface_checked.any() else 0.0, 'pre_filter_p99': float(np.quantile(donor_surface_error[surface_checked], 0.99)) if surface_checked.any() else 0.0, 'accepted_max': float(donor_surface_error[footprint_ok].max()) if footprint_ok.any() else 0.0}}, 'phase_results': {'train': results[:len(TRAIN)], 'heldout': results[len(TRAIN):]}, 'diagnostics': str(a.output / 'GUTTER_DIAGNOSTICS.npz'), 'code_snapshot': str(a.output / 'CODE_SNAPSHOT.py'), 'limits': 'Fixed-shape observed-source continuous-gutter candidate. It does not establish novel-view quality or model improvement.'}++ gate_ok = accepted and all((preservation.get(k) for k in IDENTITY_GATES))++ receipt = {++ 'status': 'valid' if gate_ok else 'invalid',++ 'schema': SCHEMA,++ 'candidate_glb': str(glb),++ 'seconds': time.monotonic() - started,++ 'gates': {++ 'accepted': gate_ok,++ 'UV_covered_exact': True,++ 'project_active_exact': True,++ 'blocked_exact': True,++ 'alpha_exact': True,++ 'nonbase_identity': preservation,++ 'all_19_phase_renders': len(results) == 19,++ },++ 'atlas': {++ 'UV_covered_texels': int(covered.sum()),++ 'UV_face_charts': int(face_chart.max() + 1),++ 'project_active_texels': int(active.sum()),++ 'blocked_texels': int(blocked.sum()),++ 'unsafe_all_phase_texels': int(unsafe.sum()),++ 'gutter_radius': a.gutter_radius,++ 'nearest_donor_uncovered_gutter_texels': int(candidate.sum()),++ 'continuous_eligible_uncovered_gutter_texels': int(eligible.sum()),++ 'changed_texels': int(changed.sum()),++ 'rejected_unsafe': int((rejection & REJECT_UNSAFE != 0).sum()),++ 'rejected_chart': int((rejection & REJECT_CHART != 0).sum()),++ 'rejected_degenerate_uv': int((rejection & REJECT_DEGENERATE_UV != 0).sum()),++ 'rejected_source_footprint_or_feather': int((rejection & REJECT_SOURCE != 0).sum()),++ 'donor_surface_oracle': {++ 'threshold': 1e-05,++ 'checked': int(surface_checked.sum()),++ 'rejected': int((surface_checked & ~surface_ok).sum()),++ 'pre_filter_max': float(donor_surface_error[surface_checked].max()) if surface_checked.any() else 0.0,++ 'pre_filter_p99': float(np.quantile(donor_surface_error[surface_checked], 0.99)) if surface_checked.any() else 0.0,++ 'accepted_max': float(donor_surface_error[footprint_ok].max()) if footprint_ok.any() else 0.0,++ },++ },++ 'phase_results': {'grid': results[:len(GRID_PHASES)], 'offgrid': results[len(GRID_PHASES):]},++ 'diagnostics': str(a.output / 'GUTTER_DIAGNOSTICS.npz'),++ 'code_snapshot': str(a.output / 'CODE_SNAPSHOT.py'),++ }+ write_once(a.output / 'RECEIPT.json', receipt)+ write_once(a.output / 'RESULT.json', receipt)+ if not gate_ok:+ raise RuntimeError('acceptance failed')+ print(json.dumps({'status': 'valid', 'candidate': str(glb), 'changed_texels': int(changed.sum())}))+if __name__ == '__main__':+ main()diff --cc supratex/inference/reprojection/_project.pyindex 42198d3,0000000..c635616mode 100644,000000..100644--- a/supratex/inference/reprojection/_project.py+++ b/supratex/inference/reprojection/_project.py@@@ -1,227 -1,0 +1,283 @@@+"""Project observed albedo at UV texel centres with measured 19-phase gates.++++Support is the union of atlas texels touched by the sixteen grid phases,++intersected with UV-covered texel centres whose source projection lands on++hard-trusted observation pixels (alpha >= 254, eroded by two pixels). Bilinear++atlas taps of pixels near untrusted observation regions are blocked. Each kept++texel T0 becomes T0 + s * (source - T0), where source is the bilinear predicted++albedo at the texel centre's projection and s is the observation trust. The++candidate GLB is then re-rendered at all grid and off-grid phases.+"""+from __future__ import annotations+import argparse, copy, io, json, os, sys, time+from pathlib import Path- from ._common import OUTSIDE_COLOR_MAX_ABS, outside_color_passes, load_renderer, bind_file++from ._common import GRID_PHASES, OFFGRID_PHASES, OUTSIDE_COLOR_MAX_ABS, outside_color_passes, load_renderer, bind_file+from . import _glb as fixed++SCHEMA = 'supratex.reprojection.project'+SIZE = 4096+RES = 1024- TRAIN = tuple(((x / 4, y / 4) for x in range(4) for y in range(4)))- HELD = ((0.125, 0.375), (0.375, 0.625), (0.875, 0.125))++def put(p, x):+ if p.exists():+ raise FileExistsError(p)+ p.write_text(json.dumps(x, indent=2, sort_keys=True, allow_nan=False) + '\n')++def main():+ ap = argparse.ArgumentParser(description=__doc__)- ap.add_argument('--arm', choices=('B',), required=True)+ ap.add_argument('--baseline-glb', type=Path, required=True)+ ap.add_argument('--source-albedo', type=Path, required=True)+ ap.add_argument('--source-rgba', type=Path, required=True)+ ap.add_argument('--camera', type=Path, required=True)- ap.add_argument('--evaluator', type=Path, required=True)++ ap.add_argument('--renderer', type=Path, required=True)+ ap.add_argument('--output', type=Path, required=True)+ a = ap.parse_args()+ if a.output.exists():+ raise FileExistsError(a.output)- for p in (a.baseline_glb, a.source_albedo, a.source_rgba, a.camera, a.evaluator):++ for p in (a.baseline_glb, a.source_albedo, a.source_rgba, a.camera, a.renderer):+ if not p.is_file():+ raise FileNotFoundError(p)+ a.output.mkdir(parents=True)- put(a.output / 'PLAN.json', {'arm': a.arm, 'baseline_glb': str(a.baseline_glb.absolute()), 'source_albedo': str(a.source_albedo.absolute()), 'source_rgba': str(a.source_rgba.absolute()), 'camera': str(a.camera.absolute()), 'evaluator': str(a.evaluator.absolute()), 'size': SIZE, 'resolution': RES, 'train_phases': TRAIN, 'heldout_phases': HELD, 'source': 'predicted albedo only; no GT read', 'support': 'common sixteen-phase union, intersected with covered source-hard-trusted UV-triangle centres; alpha>=254 source support eroded 2 pixels; two-pixel unsafe-surface footprint blacklist', 'B': 'atlas-centre UV-triangle final-surface projection then bilinear source albedo sample mixed as T0+s*(source-T0)', 'validation': 'actual GLB rerender at 16 train + 3 heldout phases'})++ put(a.output / 'PLAN.json', {++ 'schema': SCHEMA,++ 'baseline_glb': str(a.baseline_glb.absolute()),++ 'source_albedo': str(a.source_albedo.absolute()),++ 'source_rgba': str(a.source_rgba.absolute()),++ 'camera': str(a.camera.absolute()),++ 'renderer': str(a.renderer.absolute()),++ 'size': SIZE,++ 'resolution': RES,++ 'grid_phases': GRID_PHASES,++ 'offgrid_phases': OFFGRID_PHASES,++ })+ os.environ['FLEX_GEMM_USE_AUTOTUNE_CACHE'] = '0'+ os.environ['FLEX_GEMM_AUTOSAVE_AUTOTUNE_CACHE'] = '0'+ import cv2, numpy as np, torch+ from PIL import Image+ torch.backends.cuda.matmul.allow_tf32 = False+ torch.manual_seed(42)+ began = time.monotonic()- rm = load_renderer(a.evaluator)++ rm = load_renderer(a.renderer)+ rt = rm._runtime_imports()+ dr = rt['dr']+ camera = json.loads(a.camera.read_text())+ (doc, bin0) = fixed._read_glb(a.baseline_glb)+ fixed._assert_fixed_scene(doc)+ (ii, vi) = fixed._base_color_image_ref(doc)+ (im, _, off, n) = fixed._decode_base_image(doc, bin0, ii, vi)+ pix = np.asarray(im).copy()+ if pix.shape[:2] != (SIZE, SIZE):+ raise ValueError('requires 4096 atlas')+ vals = rt['_load_textured_mesh'](a.baseline_glb, rt)+ (vertices, faces, _, uv, _, _, factor, _, _) = vals+ if not np.allclose(factor, 1):+ raise RuntimeError('baseColorFactor')+ exported = torch.as_tensor(vertices, dtype=torch.float32, device='cuda')+ native = exported * torch.tensor((-1.0, 1.0, -1.0), device='cuda')+ faces = torch.as_tensor(faces, dtype=torch.int32, device='cuda').contiguous()+ uv = torch.as_tensor(uv, dtype=torch.float32, device='cuda')+ uv = torch.stack((uv[:, 0], 1 - uv[:, 1]), -1).contiguous()+ base = torch.as_tensor(pix[..., :3].copy(), dtype=torch.float32, device='cuda').reshape(-1, 3) / 255+ rgba = np.asarray(Image.open(a.source_rgba).convert('RGBA'))+ hard = cv2.erode((rgba[..., 3] >= 254).astype('uint8'), np.ones((5, 5), np.uint8)).astype(bool)+ albedo = np.asarray(Image.open(a.source_albedo).convert('RGB'), np.float32) / 255+ if albedo.shape[:2] != (RES, RES) or hard.shape != (RES, RES):+ raise ValueError('aligned source must be 1024')+ trust = np.clip(cv2.distanceTransform(hard.astype('uint8'), cv2.DIST_L2, 3) / 4.0, 0, 1)+ src = torch.as_tensor(albedo, device='cuda').permute(2, 0, 1)[None]+ trust_t = torch.as_tensor(trust, dtype=torch.float32, device='cuda')[None, None]+ hard_t = torch.as_tensor(hard, device='cuda')+ (E, K) = rm._native_camera(camera, 'cuda', rt)+ original = rm._exported_glb_camera++ def pc(cam, device, runtime):+ (ex, inn) = original(cam, device, runtime)+ (dx, dy) = cam.get('front_atlas_phase', (0.0, 0.0))+ inn = inn.clone()+ inn[0, 2] += dx / RES+ inn[1, 2] += dy / RES+ return (ex, inn)+ rm._exported_glb_camera = pc+- def op(phase, need_all=False):++ def op(phase):+ cam = copy.deepcopy(camera)+ cam['front_atlas_phase'] = phase+ (ee, kk) = pc(cam, 'cuda', rt)+ dist = rm._camera_distance(cam)+ proj = rt['intrinsics_to_projection'](kk, max(0.2, dist - 1), dist + 1)+ h = torch.cat((exported, torch.ones_like(exported[:, :1])), 1)+ (rast, _) = dr.rasterize(dr.RasterizeCudaContext(device='cuda'), (h @ (proj @ ee).T)[None].contiguous(), faces, (RES, RES))+ (uvs, _) = dr.interpolate(uv[None], rast, faces)+ (points, _) = dr.interpolate(native[None], rast, faces)+ mask = (rast[0, ..., -1] > 0).cpu().numpy()+ rowsall = torch.as_tensor(np.flatnonzero(mask.reshape(-1)), device='cuda')+ xyz = points[0].reshape(-1, 3)[rowsall]+ q = torch.cat((xyz, torch.ones_like(xyz[:, :1])), 1) @ E.T+ q = q[:, :3] @ K.T+ suv = q[:, :2] / q[:, 2:3].clamp_min(1e-08)+ near = torch.floor(suv * RES).long()+ inside = (near[:, 0] >= 0) & (near[:, 0] < RES) & (near[:, 1] >= 0) & (near[:, 1] < RES) & (q[:, 2] > 0)+ trusted = torch.zeros(len(rowsall), dtype=torch.bool, device='cuda')+ trusted[inside] = hard_t[near[inside, 1], near[inside, 0]]+ rows = rowsall[trusted]+ tsuv = suv[trusted]++ def fp(rr):+ t = uvs[0].reshape(-1, 2)[rr] * SIZE - 0.5+ xy = t.floor().long()+ f = t - xy+ ids = []+ ws = []+ for (dx, dy) in ((0, 0), (1, 0), (0, 1), (1, 1)):+ ids.append((xy[:, 1] + dy) % SIZE * SIZE + (xy[:, 0] + dx) % SIZE)+ ws.append((f[:, 0] if dx else 1 - f[:, 0]) * (f[:, 1] if dy else 1 - f[:, 1]))+ return (torch.stack(ids, 1), torch.stack(ws, 1))+ (idx, w) = fp(rows)+ unsafe = np.zeros(RES * RES, np.uint8)+ unsafe[rowsall[~trusted].cpu().numpy()] = 1+ unsafe = cv2.dilate(unsafe.reshape(RES, RES), np.ones((5, 5), np.uint8)) & mask+ ur = torch.as_tensor(np.flatnonzero(unsafe.reshape(-1)), device='cuda')+ outside = fp(ur)[0] if len(ur) else torch.empty((0, 4), device='cuda', dtype=torch.long)+ target = rt['F'].grid_sample(src, (tsuv * 2 - 1).reshape(1, 1, -1, 2), align_corners=False, padding_mode='zeros')[0, :, 0].T+ strength = rt['F'].grid_sample(trust_t, (tsuv * 2 - 1).reshape(1, 1, -1, 2), align_corners=False, padding_mode='zeros')[0, 0, 0]+ screen = np.zeros(RES * RES, bool)+ screen[rows.cpu().numpy()] = True- return {'phase': phase, 'idx': idx, 'w': w, 'outside': outside, 'target': target, 'strength': strength, 'rows': rows, 'screen': screen.reshape(RES, RES), 'uvs': uvs, 'points': points, 'rast': rast, 'trusted': trusted, 'rowsall': rowsall, 'suv': suv}- ops = [op(p) for p in TRAIN]++ return {++ 'phase': phase,++ 'idx': idx,++ 'w': w,++ 'outside': outside,++ 'target': target,++ 'strength': strength,++ 'rows': rows,++ 'screen': screen.reshape(RES, RES),++ }++ ops = [op(p) for p in GRID_PHASES]+ active = torch.unique(torch.cat([o['idx'].reshape(-1) for o in ops]))+ (rastuv, _) = dr.rasterize(dr.RasterizeCudaContext(device='cuda'), torch.cat((uv * 2 - 1, torch.zeros_like(uv[:, :1]), torch.ones_like(uv[:, :1])), 1)[None], faces, (SIZE, SIZE))+ (pxyz, _) = dr.interpolate(native[None], rastuv, faces)+ xy = torch.stack((active // SIZE, active % SIZE), 1)+ covered = rastuv[0, xy[:, 0], xy[:, 1], -1] > 0+ xyz = pxyz[0, xy[:, 0], xy[:, 1]]+ q = torch.cat((xyz, torch.ones_like(xyz[:, :1])), 1) @ E.T+ q = q[:, :3] @ K.T+ centre_suv = q[:, :2] / q[:, 2:3].clamp_min(1e-08)+ ne = torch.floor(centre_suv * RES).long()+ inside = (ne[:, 0] >= 0) & (ne[:, 0] < RES) & (ne[:, 1] >= 0) & (ne[:, 1] < RES) & (q[:, 2] > 0)+ centre_trust = torch.zeros(len(active), dtype=torch.bool, device='cuda')+ centre_trust[inside] = hard_t[ne[inside, 1], ne[inside, 0]]+ centre_keep = covered & centre_trust+ active = active[centre_keep]+ centre_suv = centre_suv[centre_keep]+ look = torch.full((SIZE * SIZE,), -1, dtype=torch.long, device='cuda')+ look[active] = torch.arange(len(active), device='cuda')- outids = torch.unique(torch.cat([o['outside'].reshape(-1) for o in ops if o['outside'].numel()])) if any((o['outside'].numel() for o in ops)) else torch.empty(0, dtype=torch.long, device='cuda')++ if any(o['outside'].numel() for o in ops):++ outids = torch.unique(torch.cat([o['outside'].reshape(-1) for o in ops if o['outside'].numel()]))++ else:++ outids = torch.empty(0, dtype=torch.long, device='cuda')+ blocked = torch.zeros(len(active), dtype=torch.bool, device='cuda')+ if len(outids):+ where = torch.searchsorted(active, outids)+ hit = (where < len(active)) & (active[where.clamp_max(len(active) - 1)] == outids)+ blocked[where[hit]] = True+ if active.numel() == 0 or not bool((~blocked).any()):+ raise RuntimeError('no unblocked trusted atlas texels remain')+ np.savez_compressed(a.output / 'COMMON_DOMAIN.npz', active_texel_ids=active.cpu().numpy(), blocked_texel_ids=active[blocked].cpu().numpy())+ for o in ops:+ compact = look[o['idx']]+ keep = (compact >= 0).all(1)+ for key in ('idx', 'w'):+ o[key] = o[key][keep]+ for key in ('target', 'strength', 'rows'):+ o[key] = o[key][keep]+ o['compact'] = compact[keep]+ o['allowed'] = (~blocked[o['compact']]).float()+ o['base'] = (base[o['idx']] * o['w'][..., None]).sum(1)+ o['screen'] = np.zeros((RES, RES), bool)+ o['screen'].reshape(-1)[o['rows'].cpu().numpy()] = True+ mode = 'uv_texel_centre_projection'+ corrected = base[active].clone()+ s = centre_suv+ sample = rt['F'].grid_sample(src, (s * 2 - 1).reshape(1, 1, -1, 2), align_corners=False, padding_mode='zeros')[0, :, 0].T+ strength = rt['F'].grid_sample(trust_t, (s * 2 - 1).reshape(1, 1, -1, 2), align_corners=False, padding_mode='zeros')[0, 0, 0]+ take = ~blocked+ corrected[take] = base[active][take] + strength[take, None] * (sample[take] - base[active][take])+ out = pix.copy()+ out.reshape(-1, out.shape[-1])[active.cpu().numpy(), :3] = (corrected.cpu().numpy() * 255 + 0.5).astype(np.uint8)+ blob = io.BytesIO()+ Image.fromarray(out).save(blob, format='PNG')+ od = copy.deepcopy(doc)+ ob = fixed._replace_image_payload(od, bin0, vi, off, n, blob.getvalue())+ candidate = a.output / 'candidate'+ candidate.mkdir()+ glb = candidate / 'mesh.glb'+ fixed._write_glb(glb, od, ob)+ pres = fixed._nonbase_identity_check(doc, bin0, glb, vi)++ def render(p, split):+ folder = a.output / 'renders' / split / f'x{p[0]:.3f}_y{p[1]:.3f}'+ folder.mkdir(parents=True)+ cam = copy.deepcopy(camera)+ cam['front_atlas_phase'] = p+ o = op(p)+ ca = rm.render_glb(glb, cam, folder / 'candidate.png', resolution=RES, rt=rt)+ ba = rm.render_glb(a.baseline_glb, cam, folder / 'baseline.png', resolution=RES, rt=rt)+ with np.load(ca['attrs_npz']) as z:+ (ci, cm, cmra) = (z['albedo'], z['mask'].astype(bool), z['mra'])+ with np.load(ba['attrs_npz']) as z:+ (bi, bm, bmra) = (z['albedo'], z['mask'].astype(bool), z['mra'])+ if not np.array_equal(cm, bm) or not np.array_equal(cmra, bmra):+ raise RuntimeError('mask/MRA changed')+ target = np.zeros_like(ci)+ target.reshape(-1, 3)[o['rows'].cpu().numpy()] = o['target'].cpu().numpy()+ sel = o['screen'] & cm- Image.fromarray((target * 255 + 0.5).astype(np.uint8)).save(folder / 'target_projected.png')++ Image.fromarray((target * 255 + 0.5).astype(np.uint8)).save(folder / 'target_projected.png', compress_level=1)+ quant = torch.as_tensor(out[..., :3], dtype=torch.float32, device='cuda').reshape(-1, 3) / 255+ replay = (quant[o['idx']] * o['w'][..., None]).sum(1).cpu().numpy()+ actual = ci.reshape(-1, 3)[o['rows'].cpu().numpy()]+ mx = float(np.abs(replay - actual).max())+ outside = cm & ~o['screen']+ oo = float(np.abs(ci - bi)[outside].max()) if outside.any() else 0.0- r = {'phase': p, 'pixels': int(sel.sum()), 'candidate_vs_source': rm._masked_metrics(ci, target, sel), 'baseline_vs_source': rm._masked_metrics(bi, target, sel), 'quantized_atlas_replay_max': mx, 'outside_source_hardtrust_max_abs_threshold': OUTSIDE_COLOR_MAX_ABS, 'outside_source_hardtrust_delta_max_abs': oo, 'passes': bool(mx <= 1e-05 and outside_color_passes(oo))}++ r = {++ 'phase': p,++ 'pixels': int(sel.sum()),++ 'candidate_vs_source': rm._masked_metrics(ci, target, sel),++ 'baseline_vs_source': rm._masked_metrics(bi, target, sel),++ 'quantized_atlas_replay_max': mx,++ 'outside_source_hardtrust_max_abs_threshold': OUTSIDE_COLOR_MAX_ABS,++ 'outside_source_hardtrust_delta_max_abs': oo,++ 'passes': bool(mx <= 1e-05 and outside_color_passes(oo)),++ }+ r.update(mask_exact=True, mra_exact=True, evidence={'candidate': bind_file(Path(ca['attrs_npz'])), 'baseline': bind_file(Path(ba['attrs_npz']))})+ put(folder / 'PHASE_RECEIPT.json', r)+ return r- train = [render(x, 'train') for x in TRAIN]- held = [render(x, 'heldout') for x in HELD]++ grid = [render(x, 'grid') for x in GRID_PHASES]++ offgrid = [render(x, 'offgrid') for x in OFFGRID_PHASES]+ changed = int(np.any(out[..., :3] != pix[..., :3], axis=-1).sum())- conv = True- ok = conv and all((x['passes'] for x in train + held))- result = {'status': 'valid' if ok else 'invalid', 'arm': a.arm, 'mode': mode, 'seconds': time.monotonic() - began, 'candidate_glb': str(glb), 'gates': {'accepted': ok, 'common_support_and_protection': True, 'nonbase_identity': pres, 'all_19_phase_renders': len(train) + len(held) == 19}, 'atlas': {'active_texels': int(len(active)), 'blocked_texels': int(blocked.sum()), 'changed_texels': changed, 'alpha_exact': bool(np.array_equal(out[..., 3], pix[..., 3])) if out.shape[-1] == 4 else True}, 'phase_results': {'train': train, 'heldout': held}, 'limits': 'Fixed-shape, observed-source front control. It does not establish novel-view quality or a model improvement.'}++ ok = all((x['passes'] for x in grid + offgrid))++ result = {++ 'status': 'valid' if ok else 'invalid',++ 'schema': SCHEMA,++ 'mode': mode,++ 'seconds': time.monotonic() - began,++ 'candidate_glb': str(glb),++ 'gates': {++ 'accepted': ok,++ 'common_support_and_protection': True,++ 'nonbase_identity': pres,++ 'all_19_phase_renders': len(grid) + len(offgrid) == 19,++ },++ 'atlas': {++ 'active_texels': int(len(active)),++ 'blocked_texels': int(blocked.sum()),++ 'changed_texels': changed,++ 'alpha_exact': bool(np.array_equal(out[..., 3], pix[..., 3])) if out.shape[-1] == 4 else True,++ },++ 'phase_results': {'grid': grid, 'offgrid': offgrid},++ }+ put(a.output / 'RECEIPT.json', result)+ put(a.output / 'RESULT.json', result)+ if not ok:+ raise RuntimeError('acceptance failed')+ print(json.dumps({'status': 'valid', 'candidate': str(glb)}))+if __name__ == '__main__':+ main()diff --cc supratex/inference/reprojection/_renderer.pyindex 787d05d,0000000..60bad41mode 100644,000000..100644--- a/supratex/inference/reprojection/_renderer.py+++ b/supratex/inference/reprojection/_renderer.py@@@ -1,170 -1,0 +1,207 @@@+"""Unlit full-camera rendering for measured atlas preservation gates."""+from __future__ import annotations+import math+from pathlib import Path+from typing import Any, Mapping+DEFAULT_RESOLUTION = 1024++# Phase gates render the same baseline and candidate many times; reloading a GLB++# decodes two 4096-square textures and recomputes normals each time. Keep the++# last two meshes' render tensors per process, keyed by file version.++_MESH_CACHE: dict[tuple, dict[str, Any]] = {}++_RASTER_CONTEXTS: dict[str, Any] = {}++def _load_textured_mesh(glb: Path, rt: dict[str, Any]) -> tuple[Any, Any, Any, Any, Any, Any, Any, float, float]:+ (np, trimesh) = (rt['np'], rt['trimesh'])+ loaded = trimesh.load(glb, process=False)+ mesh = next(iter(loaded.geometry.values())) if isinstance(loaded, trimesh.Scene) else loaded+ vertices = np.asarray(mesh.vertices, dtype=np.float32)+ faces = np.asarray(mesh.faces, dtype=np.int32)+ normals = np.asarray(mesh.vertex_normals, dtype=np.float32)+ visual = mesh.visual+ if vertices.size == 0 or faces.size == 0 or normals.shape != vertices.shape:+ raise ValueError('GLB mesh is empty or lacks usable vertex normals')+ if not hasattr(visual, 'uv') or visual.uv is None:+ raise ValueError('GLB mesh lacks UV coordinates')+ material = visual.material+ image = getattr(material, 'baseColorTexture', None)+ if image is None:+ raise ValueError('GLB mesh lacks a baseColorTexture')+ metallic_roughness_image = getattr(material, 'metallicRoughnessTexture', None)+ if metallic_roughness_image is None:+ raise ValueError('GLB mesh lacks metallicRoughnessTexture; refusing to label textured render as material-aware')+ texture = np.asarray(image.convert('RGB'), dtype=np.float32) / 255.0+ metallic_roughness = np.asarray(metallic_roughness_image.convert('RGB'), dtype=np.float32) / 255.0+ raw_factor = getattr(material, 'baseColorFactor', None)+ factor = np.asarray([1, 1, 1, 1] if raw_factor is None else raw_factor, dtype=np.float32)[:3]+ if factor.max(initial=1.0) > 1.0:+ factor /= 255.0+ metallic = getattr(material, 'metallicFactor', None)+ roughness = getattr(material, 'roughnessFactor', None)+ return (vertices, faces, normals, np.asarray(visual.uv, dtype=np.float32), texture.astype(np.float32), metallic_roughness.astype(np.float32), factor.astype(np.float32), float(1 if metallic is None else metallic), float(1 if roughness is None else roughness))++def _srgb_factor_torch(srgb: Any, factor: Any, torch: Any) -> Any:+ """Apply a glTF baseColorFactor in linear light and return sRGB samples."""+ linear = torch.where(srgb <= 0.04045, srgb / 12.92, ((srgb + 0.055) / 1.055).pow(2.4))+ linear = linear * torch.as_tensor(factor, dtype=srgb.dtype, device=srgb.device).view(1, 1, 1, 3)+ return torch.where(linear <= 0.0031308, linear * 12.92, 1.055 * linear.clamp_min(0).pow(1.0 / 2.4) - 0.055).clamp(0.0, 1.0)++def _runtime_imports() -> dict[str, Any]:+ """Import CUDA dependencies only when rendering is actually requested."""+ import numpy as np+ import torch+ import torch.nn.functional as F+ import trimesh+ import nvdiffrast.torch as dr+ import utils3d+ from PIL import Image+ from supratex.renderers.mesh_renderer import intrinsics_to_projection+ from ._renderer import _load_textured_mesh+ return locals()++def _check_resolution(resolution: int) -> None:+ if resolution <= 0:+ raise ValueError('resolution must be positive')++def _camera_distance(camera: Mapping[str, Any]) -> float:+ try:+ distance = float(camera['distance']) * float(camera.get('mesh_scale', 1.0))+ except (KeyError, TypeError, ValueError) as error:+ raise ValueError('camera requires canonical distance and optional mesh_scale') from error+ if not math.isfinite(distance) or distance <= 0:+ raise ValueError('camera distance * mesh_scale must be finite and positive')+ return distance++def _native_camera(camera: Mapping[str, Any], device: str, rt: Mapping[str, Any]) -> tuple[Any, Any]:+ """Return the baseline camera, accepting a full CV camera when supplied."""+ if 'extrinsic' in camera and ('projection_intrinsic' in camera or 'intrinsic' in camera):+ intrinsic_key = 'projection_intrinsic' if 'projection_intrinsic' in camera else 'intrinsic'+ extrinsic = rt['torch'].as_tensor(camera['extrinsic'], dtype=rt['torch'].float32, device=device)+ intrinsic = rt['torch'].as_tensor(camera[intrinsic_key], dtype=rt['torch'].float32, device=device)+ if extrinsic.shape != (4, 4) or intrinsic.shape != (3, 3):+ raise ValueError('full camera requires 4x4 extrinsic and 3x3 intrinsic')+ return (extrinsic, intrinsic)+ distance = _camera_distance(camera)+ try:+ fov = float(camera['camera_angle_x'])+ except (KeyError, TypeError, ValueError) as error:+ raise ValueError('canonical camera requires camera_angle_x') from error+ if not 0 < fov < math.pi:+ raise ValueError('camera_angle_x must be in (0, pi)')+ (torch, utils3d) = (rt['torch'], rt['utils3d'])+ eye = torch.tensor((0.0, 0.0, distance), dtype=torch.float32, device=device)+ target = torch.zeros(3, dtype=torch.float32, device=device)+ up = torch.tensor((0.0, 1.0, 0.0), dtype=torch.float32, device=device)+ extrinsic = utils3d.torch.extrinsics_look_at(eye, target, up)+ fov_t = torch.tensor(fov, dtype=torch.float32, device=device)+ return (extrinsic, utils3d.torch.intrinsics_from_fov_xy(fov_t, fov_t))++def _exported_glb_camera(camera: Mapping[str, Any], device: str, rt: Mapping[str, Any]):+ """Map exported vertices into the native camera, including off-axis poses."""+ (extrinsic, intrinsic) = _native_camera(camera, device, rt)+ sign = rt['torch'].diag(rt['torch'].tensor([-1.0, 1.0, -1.0, 1.0], device=device))+ return (extrinsic @ sign, intrinsic)++def _write_outputs(out: Path, albedo: Any, mra: Any, mask: Any, rt: Mapping[str, Any], save_attrs: bool) -> dict[str, str]:+ (np, Image) = (rt['np'], rt['Image'])+ out.parent.mkdir(parents=True, exist_ok=True)+ albedo_u8 = (np.clip(albedo, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8)+ mask_u8 = (np.asarray(mask, dtype=np.float32) >= 0.5).astype(np.uint8) * 255- Image.fromarray(albedo_u8, mode='RGB').save(out)++ # Diagnostic previews and evidence arrays use fast compression; the stored++ # values are unchanged and receipts bind whatever bytes are written.++ Image.fromarray(albedo_u8, mode='RGB').save(out, compress_level=1)+ mask_path = out.with_name(out.stem + '_mask.png')- Image.fromarray(mask_u8, mode='L').save(mask_path)++ Image.fromarray(mask_u8, mode='L').save(mask_path, compress_level=1)+ result = {'png': str(out), 'mask_png': str(mask_path)}+ if save_attrs:+ attrs_path = out.with_suffix('.npz')- np.savez_compressed(attrs_path, albedo=np.asarray(albedo, dtype=np.float32), mra=np.asarray(mra, dtype=np.float32), mask=np.asarray(mask, dtype=np.uint8))++ _save_npz(attrs_path, np, albedo=np.asarray(albedo, dtype=np.float32), mra=np.asarray(mra, dtype=np.float32), mask=np.asarray(mask, dtype=np.uint8))+ result['attrs_npz'] = str(attrs_path)+ return result+++def _save_npz(path: Path, np: Any, **arrays: Any) -> None:++ """Write a standard compressed .npz with zlib level 1 (numpy uses level 6)."""++ import zipfile++ with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED, compresslevel=1) as archive:++ for name, value in arrays.items():++ with archive.open(f'{name}.npy', 'w', force_zip64=True) as stream:++ np.lib.format.write_array(stream, np.asanyarray(value), allow_pickle=False)++++def _mesh_tensors(glb: Path, device: str, runtime: Mapping[str, Any]) -> dict[str, Any]:++ """Load a GLB once per file version and keep its render inputs on the device."""++ path = glb.resolve()++ stat = path.stat()++ key = (str(path), stat.st_mtime_ns, stat.st_size, device, id(runtime['_load_textured_mesh']))++ cached = _MESH_CACHE.get(key)++ if cached is None:++ torch = runtime['torch']++ (vertices, faces, _normals, uv, texture, mr_texture, factor, metallic_factor, roughness_factor) = runtime['_load_textured_mesh'](glb, runtime)++ uv_t = torch.as_tensor(uv, dtype=torch.float32, device=device)++ cached = {++ 'vertices': torch.as_tensor(vertices, dtype=torch.float32, device=device),++ 'faces': torch.as_tensor(faces, dtype=torch.int32, device=device).contiguous(),++ 'uv': torch.stack((uv_t[:, 0], 1.0 - uv_t[:, 1]), dim=-1).contiguous(),++ 'texture': torch.as_tensor(texture, dtype=torch.float32, device=device)[None].contiguous(),++ 'mr_texture': torch.as_tensor(mr_texture, dtype=torch.float32, device=device)[None].contiguous(),++ 'factor': factor, 'metallic_factor': metallic_factor, 'roughness_factor': roughness_factor,++ }++ while len(_MESH_CACHE) >= 2:++ _MESH_CACHE.pop(next(iter(_MESH_CACHE)))++ _MESH_CACHE[key] = cached++ return cached+++def render_glb(glb: str | Path, camera: Mapping[str, Any], out: str | Path, resolution: int=DEFAULT_RESOLUTION, *, device: str='cuda', rt: Mapping[str, Any] | None=None, save_attrs: bool=True) -> dict[str, str]:+ """Render an exported GLB through the supplied native-frame camera.++ Sample base color and MRA directly with nvdiffrast, without lighting.+ """+ _check_resolution(resolution)+ runtime = _runtime_imports() if rt is None else dict(rt)+ distance = _camera_distance(camera)+ (extrinsic, intrinsic) = _exported_glb_camera(camera, device, runtime)- values = runtime['_load_textured_mesh'](Path(glb), runtime)- (vertices, faces, _normals, uv, texture, mr_texture, factor, metallic_factor, roughness_factor) = values++ mesh = _mesh_tensors(Path(glb), device, runtime)+ (torch, dr) = (runtime['torch'], runtime['dr'])++ (vertices_t, faces_t, uv_t) = (mesh['vertices'], mesh['faces'], mesh['uv'])++ (factor, metallic_factor, roughness_factor) = (mesh['factor'], mesh['metallic_factor'], mesh['roughness_factor'])+ projection = runtime['intrinsics_to_projection'](intrinsic, max(0.2, distance - 1.0), distance + 1.0)- vertices_t = torch.as_tensor(vertices, dtype=torch.float32, device=device)- faces_t = torch.as_tensor(faces, dtype=torch.int32, device=device).contiguous()- uv_t = torch.as_tensor(uv, dtype=torch.float32, device=device)- uv_t = torch.stack((uv_t[:, 0], 1.0 - uv_t[:, 1]), dim=-1).contiguous()+ vertices_h = torch.cat((vertices_t, torch.ones_like(vertices_t[:, :1])), dim=-1)+ clip = vertices_h @ (projection @ extrinsic).T- glctx = dr.RasterizeCudaContext(device=device)++ glctx = _RASTER_CONTEXTS.get(device)++ if glctx is None:++ glctx = _RASTER_CONTEXTS[device] = dr.RasterizeCudaContext(device=device)+ (raster, _) = dr.rasterize(glctx, clip[None].contiguous(), faces_t, (resolution, resolution))+ mask = raster[..., -1] > 0+ (uv_pixel, _) = dr.interpolate(uv_t[None], raster, faces_t)- base = dr.texture(torch.as_tensor(texture, dtype=torch.float32, device=device)[None].contiguous(), uv_pixel, filter_mode='linear')++ base = dr.texture(mesh['texture'], uv_pixel, filter_mode='linear')+ base = _srgb_factor_torch(base, factor, torch)- mra = dr.texture(torch.as_tensor(mr_texture, dtype=torch.float32, device=device)[None].contiguous(), uv_pixel, filter_mode='linear')++ mra = dr.texture(mesh['mr_texture'], uv_pixel, filter_mode='linear')+ mra = torch.stack((mra[..., 2] * metallic_factor, mra[..., 1] * roughness_factor, torch.ones_like(mra[..., 0])), dim=-1).clamp(0.0, 1.0)+ base = torch.where(mask[..., None], base, torch.zeros_like(base))+ mra = torch.where(mask[..., None], mra, torch.zeros_like(mra))+ return _write_outputs(Path(out), base[0].detach().cpu().numpy(), mra[0].detach().cpu().numpy(), mask[0].detach().cpu().numpy(), runtime, save_attrs)++def _as_rgb(value: Any, name: str):+ import numpy as np+ array = np.asarray(value, dtype=np.float32)+ if array.ndim != 3 or array.shape[-1] != 3 or (not np.isfinite(array).all()) or (array.min() < 0) or (array.max() > 1):+ raise ValueError(f'{name} must be finite HxWx3 in [0,1]')+ return array++def _masked_metrics(prediction: Any, target: Any, mask: Any) -> dict[str, float | int | None]:+ import numpy as np+ (pred, truth, valid) = (_as_rgb(prediction, 'prediction'), _as_rgb(target, 'target'), np.asarray(mask, dtype=bool))+ if pred.shape != truth.shape or valid.shape != pred.shape[:2]:+ raise ValueError('prediction, target, and mask shapes must agree')+ count = int(valid.sum())+ if count == 0:+ return {'valid_pixels': 0, 'masked_mae': None, 'psnr_db': None, 'gradient_vector_mae': None}+ delta = pred[valid] - truth[valid]+ mse = float(np.mean(delta * delta))+ psnr = 100.0 if mse <= 1e-12 else min(100.0, -10.0 * math.log10(mse))++ def sobel(image: Any):+ padded = np.pad(image, ((1, 1), (1, 1), (0, 0)), mode='edge')+ dx = padded[:-2, 2:] + 2 * padded[1:-1, 2:] + padded[2:, 2:] - padded[:-2, :-2] - 2 * padded[1:-1, :-2] - padded[2:, :-2]+ dy = padded[2:, :-2] + 2 * padded[2:, 1:-1] + padded[2:, 2:] - padded[:-2, :-2] - 2 * padded[:-2, 1:-1] - padded[:-2, 2:]+ return np.stack((dx, dy), axis=-1)+ grad_delta = sobel(pred)[valid] - sobel(truth)[valid]+ return {'valid_pixels': count, 'masked_mae': float(np.abs(delta).mean()), 'psnr_db': float(psnr), 'gradient_vector_mae': float(np.abs(grad_delta).mean())}diff --cc supratex/pipeline_config.pyindex 9a5a2b3,0000000..a85363emode 100644,000000..100644--- a/supratex/pipeline_config.py+++ b/supratex/pipeline_config.py@@@ -1,191 -1,0 +1,192 @@@+"""Read the SUPRA-Tex release manifest without importing model runtimes."""+from __future__ import annotations++import json+import os+from pathlib import Path, PurePosixPath+import re+from urllib.parse import unquote, urlsplit+++ROOT = Path(__file__).resolve().parents[1]+++def runtime_root(root: Path) -> Path:+ """Locate the single runtime tree in a source checkout or legacy bundle."""+ source = root / "deployment/runtime"+ bundled = root / "runtime"+ return bundled if not source.is_dir() and bundled.is_dir() else source+++def relative_name(value: str) -> str:+ if (not isinstance(value, str) or not value or "\\" in value or ":" in value+ or PurePosixPath(value).is_absolute()+ or any(part in ("", ".", "..") for part in value.split("/"))+ or any(ord(char) < 32 for char in value)):+ raise ValueError(f"expected a relative path without traversal: {value!r}")+ return value+++def model_source(value: str | os.PathLike, revision: str | None = None) -> dict:+ """Normalize local directories and public-form HF IDs/URLs without networking."""+ local_only = isinstance(value, os.PathLike)+ value = os.fspath(value)+ if not isinstance(value, str) or not value:+ raise ValueError("model source must be a nonempty path or namespace/repo HF ID")+ if revision is not None and (not isinstance(revision, str) or not revision.strip()):+ raise ValueError("model revision must be a nonempty string")+ local = Path(value).expanduser()+ if local.exists():+ if not local.is_dir():+ raise NotADirectoryError(f"model source must be a directory: {local}")+ return {"kind": "local", "path": str(local.resolve())}+ if local_only or value.startswith(("/", "./", "../", "~")) or value in (".", ".."):+ raise FileNotFoundError(f"model directory does not exist: {local}")+ if value.startswith("https://"):+ url = urlsplit(value)+ if url.netloc != "huggingface.co" or url.query or url.fragment:+ raise ValueError("use a public-form https://huggingface.co/namespace/repo URL without credentials or query")+ parts = unquote(url.path).strip("/").split("/")+ if len(parts) == 4 and parts[2] == "tree":+ if revision is not None and revision != parts[3]:+ raise ValueError("HF URL revision conflicts with --revision")+ revision = parts[3]+ parts = parts[:2]+ if len(parts) != 2:+ raise ValueError("HF URL must select a repository root or /tree/<revision>")+ value = "/".join(parts)+ value = value.removeprefix("hf://")+ if (not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*/[A-Za-z0-9_][A-Za-z0-9_.-]*", value)+ or ".." in value or "--" in value or value.endswith((".", "-"))):+ raise ValueError("model source must be an existing directory or a namespace/repo HF ID or URL")+ return {"kind": "hub", "repo_id": value, "revision": revision}+++def _keys(value: object, required: set[str], name: str, optional: set[str] | None = None) -> None:+ if not isinstance(value, dict):+ raise ValueError(f"pipeline {name} must be an object")+ missing = required - value.keys()+ unknown = value.keys() - required - (optional or set())+ if missing or unknown:+ raise ValueError(f"pipeline {name} has missing keys {sorted(missing)} or unsupported keys {sorted(unknown)}")+++def load_pipeline(path: str | os.PathLike) -> dict:+ """Load and validate the data-only schema; component configs stay separate."""+ path = Path(path).expanduser()+ if not path.is_file():+ raise FileNotFoundError(f"pipeline manifest does not exist: {path}")+ manifest = json.loads(path.read_text(encoding="utf-8"))+ _keys(manifest, {"format", "schema_version", "models", "external_models", "defaults"}, "root")+ if (manifest["format"] != "supratex_pipeline" or type(manifest["schema_version"]) is not int+ or manifest["schema_version"] != 1):+ raise ValueError("pipeline requires format 'supratex_pipeline' and schema_version 1")+ _keys(manifest["models"], {"completion", "material"}, "models")+ for value in manifest["models"].values():+ relative_name(value)+ external = manifest["external_models"]+ _keys(external, {"qwen-base", "geometry", "moge2", "dino", "rmbg2", "vae", "naf"}, "external_models")+ for name, entry in external.items():+ if name == "naf":+ _keys(entry, {"url", "filename"}, "external_models.naf")+ filename = relative_name(entry["filename"])+ if "/" in filename:+ raise ValueError("pipeline NAF filename must be a single filename")+ if not isinstance(entry["url"], str):+ raise ValueError("pipeline NAF url must be an HTTPS URL")+ url = urlsplit(entry["url"])+ if (url.scheme != "https" or not url.hostname or url.username or url.password+ or url.query or url.fragment or not url.path+ or any(char.isspace() for char in entry["url"])):+ raise ValueError("pipeline NAF url must be an HTTPS URL without credentials or query")+ continue+ _keys(entry, {"repo_id", "revision", "allow_patterns"}, f"external_models.{name}", {"gated"})+ repo_id = entry["repo_id"]+ if not isinstance(repo_id, str):+ raise ValueError(f"pipeline {name} repo_id must be a namespace/repo HF ID")+ source = model_source("hf://" + repo_id, entry["revision"])+ if source["kind"] != "hub" or source["repo_id"] != repo_id or entry["revision"] is None:+ raise ValueError(f"pipeline {name} requires an HF repo_id and a nonempty revision")+ patterns = entry["allow_patterns"]+ if not isinstance(patterns, list) or not patterns:+ raise ValueError(f"pipeline {name} allow_patterns must be a nonempty list")+ for pattern in patterns:+ relative_name(pattern)+ if "gated" in entry and type(entry["gated"]) is not bool:+ raise ValueError(f"pipeline {name} gated must be a boolean")+ validate_defaults(manifest["defaults"])+ return manifest+++def validate_defaults(defaults: dict) -> dict:+ """Validate a complete defaults object, including resolved runtime configs."""+ _keys(defaults, {"seed", "texture_size", "decimation_target", "texture_format", "attention"}, "defaults")+ for name in ("seed", "texture_size", "decimation_target"):+ if type(defaults[name]) is not int or defaults[name] < (0 if name == "seed" else 1):+ raise ValueError(f"pipeline default {name} must be {'nonnegative' if name == 'seed' else 'positive'} integer")+ if defaults["texture_format"] not in ("png", "webp"):+ raise ValueError("pipeline default texture_format must be png or webp")+ if defaults["attention"] not in ("auto", "flash_attn_3", "flash_attn", "sdpa", "xformers"):+ raise ValueError("pipeline default attention is unsupported")+ return defaults++- # Dual-view reprojection is calibrated for this export only.- DUAL_VIEW_EXPORT = {"texture_size": 4096, "texture_format": "png", "decimation_target": 500000}++# Refinement reads and writes a 4096-square PNG base-color atlas.++REFINE_ATLAS = {"texture_size": 4096, "texture_format": "png"}+++def validate_export_options(args) -> None:+ """Check export options shared by infer.py and texturing.py; None means not yet resolved."""- if args.dual_view and (args.gutter or any(getattr(args, key) not in (None, value)- for key, value in DUAL_VIEW_EXPORT.items())):- raise ValueError("dual-view reprojection requires 4096 PNG, a 500000-face target, and no --gutter")++ # Dual-view always refines both views, so it implies --refine.++ if (args.dual_view or getattr(args, "refine", False)) and any(++ getattr(args, key) not in (None, value) for key, value in REFINE_ATLAS.items()):++ raise ValueError("--refine and --dual-view require the 4096 PNG atlas")+ if ((args.seed is not None and args.seed < 0)+ or (args.texture_size is not None and args.texture_size <= 0)+ or (args.decimation_target is not None and args.decimation_target <= 0)):+ raise ValueError("seed must be nonnegative; texture-size and decimation-target must be positive")+++def default_pipeline() -> dict:+ """Read the repository's canonical defaults, without maintaining a copy."""+ return load_pipeline(ROOT / "configs/pipeline.json")+++def resolve_pipeline(+ source: str | os.PathLike,+ *,+ revision: str | None = None,+ cache_dir: str | os.PathLike | None = None,+ local_files_only: bool = False,+) -> tuple[dict, dict]:+ """Return a manifest and its local release root or pinned Hub descriptor.++ Hub resolution downloads only ``pipeline.json``. The returned Hub revision+ follows its cache snapshot so subsequent component downloads use that same+ commit even if the requested branch changes in the meantime.+ """+ value = os.fspath(source)+ if not isinstance(value, str) or not value:+ raise ValueError("pipeline source must be a path or a namespace/repo HF ID")+ path = Path(value).expanduser()+ if path.is_file() or (not value.startswith(("https://", "hf://")) and path.suffix == ".json"):+ # Keep the logical path: an exported manifest can be a symlink, and its+ # component paths must still be relative to the selected release root.+ path = path.absolute()+ return load_pipeline(path), {"kind": "local", "path": str(path.parent)}+ descriptor = model_source(source, revision)+ if descriptor["kind"] == "local":+ return load_pipeline(Path(descriptor["path"]) / "pipeline.json"), descriptor+ from huggingface_hub import hf_hub_download++ try:+ path = Path(hf_hub_download(repo_id=descriptor["repo_id"], filename="pipeline.json",+ revision=descriptor["revision"], cache_dir=cache_dir,+ local_files_only=local_files_only))+ except Exception:+ detail = "a cached manifest is required in offline mode" if local_files_only else "check the repository, revision and your access"+ raise RuntimeError(f"Cannot load pipeline.json from {descriptor['repo_id']}; {detail}") from None+ manifest = load_pipeline(path)+ if path.parent.parent.name == "snapshots" and re.fullmatch(r"[0-9a-fA-F]{40}", path.parent.name):+ descriptor["revision"] = path.parent.name+ return manifest, descriptordiff --cc supratex/renderers/pbr_mesh_renderer.pyindex 14ded30,0000000..4f2e1b2mode 100644,000000..100644--- a/supratex/renderers/pbr_mesh_renderer.py+++ b/supratex/renderers/pbr_mesh_renderer.py@@@ -1,521 -1,0 +1,520 @@@+from typing import *+import torch+from easydict import EasyDict as edict+import numpy as np+import utils3d+from ..representations.mesh import Mesh, MeshWithVoxel, MeshWithPbrMaterial, TextureFilterMode, AlphaMode, TextureWrapMode+import torch.nn.functional as F+++def cube_to_dir(s, x, y):+ if s == 0: rx, ry, rz = torch.ones_like(x), -x, -y+ elif s == 1: rx, ry, rz = -torch.ones_like(x), x, -y+ elif s == 2: rx, ry, rz = x, y, torch.ones_like(x)+ elif s == 3: rx, ry, rz = x, -y, -torch.ones_like(x)+ elif s == 4: rx, ry, rz = x, torch.ones_like(x), -y+ elif s == 5: rx, ry, rz = -x, -torch.ones_like(x), -y+ return torch.stack((rx, ry, rz), dim=-1)+++def latlong_to_cubemap(latlong_map, res):+ if 'dr' not in globals():+ import nvdiffrast.torch as dr+ cubemap = torch.zeros(6, res[0], res[1], latlong_map.shape[-1], dtype=torch.float32, device='cuda')+ for s in range(6):+ gy, gx = torch.meshgrid(torch.linspace(-1.0 + 1.0 / res[0], 1.0 - 1.0 / res[0], res[0], device='cuda'),+ torch.linspace(-1.0 + 1.0 / res[1], 1.0 - 1.0 / res[1], res[1], device='cuda'),+ indexing='ij')+ v = F.normalize(cube_to_dir(s, gx, gy), dim=-1)++ tu = torch.atan2(v[..., 0:1], -v[..., 2:3]) / (2 * np.pi) + 0.5+ tv = torch.acos(torch.clamp(v[..., 1:2], min=-1, max=1)) / np.pi+ texcoord = torch.cat((tu, tv), dim=-1)++ cubemap[s, ...] = dr.texture(latlong_map[None, ...], texcoord[None, ...], filter_mode='linear')[0]+ return cubemap+++class EnvMap:+ def __init__(self, image: torch.Tensor):+ self.image = image++ @property+ def _backend(self):+ if not hasattr(self, '_nvdiffrec_envlight'):+ if 'EnvironmentLight' not in globals():+ from nvdiffrec_render.light import EnvironmentLight+ cubemap = latlong_to_cubemap(self.image, [512, 512])+ self._nvdiffrec_envlight = EnvironmentLight(cubemap)+ self._nvdiffrec_envlight.build_mips()+ return self._nvdiffrec_envlight++ def shade(self, gb_pos, gb_normal, kd, ks, view_pos, specular=True):+ return self._backend.shade(gb_pos, gb_normal, kd, ks, view_pos, specular)++ def sample(self, directions: torch.Tensor):+ if 'dr' not in globals():+ import nvdiffrast.torch as dr+ return dr.texture(+ self._backend.base.unsqueeze(0),+ directions.unsqueeze(0),+ boundary_mode='cube',+ )[0]+++def intrinsics_to_projection(+ intrinsics: torch.Tensor,+ near: float,+ far: float,+ ) -> torch.Tensor:+ """+ OpenCV intrinsics to OpenGL perspective matrix++ Args:+ intrinsics (torch.Tensor): [3, 3] OpenCV intrinsics matrix+ near (float): near plane to clip+ far (float): far plane to clip+ Returns:+ (torch.Tensor): [4, 4] OpenGL perspective matrix+ """+ fx, fy = intrinsics[0, 0], intrinsics[1, 1]+ cx, cy = intrinsics[0, 2], intrinsics[1, 2]+ ret = torch.zeros((4, 4), dtype=intrinsics.dtype, device=intrinsics.device)+ ret[0, 0] = 2 * fx+ ret[1, 1] = 2 * fy+ ret[0, 2] = 2 * cx - 1+ ret[1, 2] = - 2 * cy + 1+ ret[2, 2] = (far + near) / (far - near)+ ret[2, 3] = 2 * near * far / (near - far)+ ret[3, 2] = 1.+ return ret+++def screen_space_ambient_occlusion(+ depth: torch.Tensor,+ normal: torch.Tensor,+ perspective: torch.Tensor,+ radius: float = 0.1,+ bias: float = 1e-6,+ samples: int = 64,+ intensity: float = 1.0,+) -> torch.Tensor:+ """+ Screen space ambient occlusion (SSAO)++ Args:+ depth (torch.Tensor): [H, W, 1] depth image+ normal (torch.Tensor): [H, W, 3] normal image+ perspective (torch.Tensor): [4, 4] camera projection matrix+ radius (float): radius of the SSAO kernel+ bias (float): bias to avoid self-occlusion+ samples (int): number of samples to use for the SSAO kernel+ intensity (float): intensity of the SSAO effect+ Returns:+ (torch.Tensor): [H, W, 1] SSAO image+ """+ device = depth.device+ H, W, _ = depth.shape++ fx = perspective[0, 0]+ fy = perspective[1, 1]+ cx = perspective[0, 2]+ cy = perspective[1, 2]++ y_grid, x_grid = torch.meshgrid(+ (torch.arange(H, device=device) + 0.5) / H * 2 - 1,+ (torch.arange(W, device=device) + 0.5) / W * 2 - 1,+ indexing='ij'+ )+ x_view = (x_grid.float() - cx) * depth[..., 0] / fx+ y_view = (y_grid.float() - cy) * depth[..., 0] / fy+ view_pos = torch.stack([x_view, y_view, depth[..., 0]], dim=-1) # [H, W, 3]++ depth_feat = depth.permute(2, 0, 1).unsqueeze(0)+ occlusion = torch.zeros((H, W), device=device)++ # start sampling+ for _ in range(samples):+ # sample normal distribution, if inside, flip the sign+ rnd_vec = torch.randn(H, W, 3, device=device)+ rnd_vec = F.normalize(rnd_vec, p=2, dim=-1)+ dot_val = torch.sum(rnd_vec * normal, dim=-1, keepdim=True)+ sample_dir = torch.sign(dot_val) * rnd_vec+ scale = torch.rand(H, W, 1, device=device)+ scale = scale * scale+ sample_pos = view_pos + sample_dir * radius * scale+ sample_z = sample_pos[..., 2]++ # project to screen space+ z_safe = torch.clamp(sample_pos[..., 2], min=1e-5)+ proj_u = (sample_pos[..., 0] * fx / z_safe) + cx+ proj_v = (sample_pos[..., 1] * fy / z_safe) + cy+ grid = torch.stack([proj_u, proj_v], dim=-1).unsqueeze(0)+ geo_z = F.grid_sample(depth_feat, grid, mode='nearest', padding_mode='border').squeeze()+ range_check = torch.abs(geo_z - sample_z) < radius+ is_occluded = (geo_z <= sample_z - bias) & range_check+ occlusion += is_occluded.float()++ f_occ = occlusion / samples * intensity+ f_occ = torch.clamp(f_occ, 0.0, 1.0)++ return f_occ.unsqueeze(-1)+++def aces_tonemapping(x: torch.Tensor) -> torch.Tensor:+ """+ Applies ACES tone mapping curve to an HDR image tensor.+ Input: x - HDR tensor, shape (..., 3), range [0, +inf)+ Output: LDR tensor, same shape, range [0, 1]++ NOTE: This causes bright base_color objects to over-expose (appear white)+ compared to Blender's standard sRGB display transform. Use linear_to_srgb()+ instead for renders_cond alignment. See pbr_color_diff_debug_guide.md #5.+ """+ a = 2.51+ b = 0.03+ c = 2.43+ d = 0.59+ e = 0.14++ # Apply the ACES fitted curve+ mapped = (x * (a * x + b)) / (x * (c * x + d) + e)++ # Clamp to [0, 1] for display or saving+ return torch.clamp(mapped, 0.0, 1.0)+++def gamma_correction(x: torch.Tensor, gamma: float = 2.2) -> torch.Tensor:+ """+ Applies gamma correction to an HDR image tensor.+ """+ return torch.clamp(x ** (1.0 / gamma), 0.0, 1.0)+++def linear_to_srgb(x: torch.Tensor) -> torch.Tensor:+ """+ Standard linear-to-sRGB conversion matching Blender's sRGB display transform.++ Applies the official sRGB EOTF inverse:+ - For values <= 0.0031308: sRGB = 12.92 * linear+ - For values > 0.0031308: sRGB = 1.055 * linear^(1/2.4) - 0.055++ Input: x - linear HDR tensor, clamped to [0, +inf)+ Output: sRGB tensor, range [0, 1]+ """+ x = torch.clamp(x, 0.0)+ low = 12.92 * x+ high = 1.055 * torch.pow(torch.clamp(x, min=0.0031308), 1.0 / 2.4) - 0.055+ return torch.clamp(torch.where(x <= 0.0031308, low, high), 0.0, 1.0)+++class PbrMeshRenderer:+ """+ Renderer for the PBR mesh.++ Args:+ rendering_options (dict): Rendering options.+ """+ def __init__(self, rendering_options={}, device='cuda'):+ if 'dr' not in globals():+ import nvdiffrast.torch as dr++ self.rendering_options = edict({+ "resolution": None,+ "near": None,+ "far": None,+ "ssaa": 1,+ "peel_layers": 8,+ })+ self.rendering_options.update(rendering_options)+ self.glctx = dr.RasterizeCudaContext(device=device)+ self.device=device++ def render(+ self,+ mesh : Mesh,+ extrinsics: torch.Tensor,+ intrinsics: torch.Tensor,+ envmap : Union[EnvMap, Dict[str, EnvMap]],+ use_envmap_bg : bool = False,+ transformation : Optional[torch.Tensor] = None+ ) -> edict:+ """+ Render the mesh.++ Args:+ mesh : meshmodel+ extrinsics (torch.Tensor): (4, 4) camera extrinsics+ intrinsics (torch.Tensor): (3, 3) camera intrinsics+ envmap (Union[EnvMap, Dict[str, EnvMap]]): environment map or a dictionary of environment maps+ use_envmap_bg (bool): whether to use envmap as background+ transformation (torch.Tensor): (4, 4) transformation matrix++ Returns:+ edict based on return_types containing:+ shaded (torch.Tensor): [3, H, W] shaded color image+ normal (torch.Tensor): [3, H, W] normal image+ base_color (torch.Tensor): [3, H, W] base color image+ metallic (torch.Tensor): [H, W] metallic image+ roughness (torch.Tensor): [H, W] roughness image+ """+ if 'dr' not in globals():+ import nvdiffrast.torch as dr++ if not isinstance(envmap, dict):+ envmap = {'' : envmap}+ num_envmaps = len(envmap)++ resolution = self.rendering_options["resolution"]+ near = self.rendering_options["near"]+ far = self.rendering_options["far"]+ ssaa = self.rendering_options["ssaa"]++ if mesh.vertices.shape[0] == 0 or mesh.faces.shape[0] == 0 or \+ not torch.isfinite(mesh.vertices).all() or \+ mesh.faces.max() >= mesh.vertices.shape[0] or mesh.faces.min() < 0:+ if mesh.vertices.shape[0] > 0 and not torch.isfinite(mesh.vertices).all():+ print(f"[PbrMeshRenderer] WARNING: mesh vertices contain NaN/Inf, returning blank image.")+ if mesh.faces.shape[0] > 0 and mesh.vertices.shape[0] > 0 and \+ (mesh.faces.max() >= mesh.vertices.shape[0] or mesh.faces.min() < 0):+ print(f"[PbrMeshRenderer] WARNING: mesh faces contain out-of-bound indices "+ f"(max={mesh.faces.max().item()}, min={mesh.faces.min().item()}, "+ f"num_vertices={mesh.vertices.shape[0]}), returning blank image.")+ out_dict = edict(+ normal=torch.zeros((3, resolution, resolution), dtype=torch.float32, device=self.device),+ mask=torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device),+ base_color=torch.zeros((3, resolution, resolution), dtype=torch.float32, device=self.device),+ metallic=torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device),+ roughness=torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device),+ alpha=torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device),+ clay=torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device),+ )+ for i, k in enumerate(envmap.keys()):+ shaded_key = f"shaded_{k}" if k != '' else "shaded"+ out_dict[shaded_key] = torch.zeros((3, resolution, resolution), dtype=torch.float32, device=self.device)+ return out_dict++ rays_o, rays_d = utils3d.torch.get_image_rays(+ extrinsics, intrinsics, resolution * ssaa, resolution * ssaa+ )++ perspective = intrinsics_to_projection(intrinsics, near, far)++ full_proj = (perspective @ extrinsics).unsqueeze(0)+ extrinsics = extrinsics.unsqueeze(0)++ vertices = mesh.vertices.unsqueeze(0)+ vertices_orig = vertices.clone()+ vertices_homo = torch.cat([vertices, torch.ones_like(vertices[..., :1])], dim=-1)+ if transformation is not None:+ vertices_homo = torch.bmm(vertices_homo, transformation.unsqueeze(0).transpose(-1, -2))+ vertices = vertices_homo[..., :3].contiguous()+ vertices_camera = torch.bmm(vertices_homo, extrinsics.transpose(-1, -2))+ vertices_clip = torch.bmm(vertices_homo, full_proj.transpose(-1, -2))+ faces = mesh.faces++ v0 = vertices[0, mesh.faces[:, 0], :3]+ v1 = vertices[0, mesh.faces[:, 1], :3]+ v2 = vertices[0, mesh.faces[:, 2], :3]+ e0 = v1 - v0+ e1 = v2 - v0+ face_normal = torch.cross(e0, e1, dim=1)+ face_normal = F.normalize(face_normal, dim=1)++ out_dict = edict()+ shaded = torch.zeros((num_envmaps, resolution * ssaa, resolution * ssaa, 3), dtype=torch.float32, device=self.device)+ depth = torch.full((resolution * ssaa, resolution * ssaa, 1), 1e10, dtype=torch.float32, device=self.device)+ normal = torch.zeros((resolution * ssaa, resolution * ssaa, 3), dtype=torch.float32, device=self.device)+ max_w = torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device)+ alpha = torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device)+ with dr.DepthPeeler(self.glctx, vertices_clip, faces, (resolution * ssaa, resolution * ssaa)) as peeler:+ for _ in range(self.rendering_options["peel_layers"]):+ rast, rast_db = peeler.rasterize_next_layer()++ # Pos+ pos = dr.interpolate(vertices, rast, faces)[0][0]++ # Depth+ gb_depth = dr.interpolate(vertices_camera[..., 2:3].contiguous(), rast, faces)[0][0]++ # Normal+ gb_normal = dr.interpolate(face_normal.unsqueeze(0), rast, torch.arange(face_normal.shape[0], dtype=torch.int, device=self.device).unsqueeze(1).repeat(1, 3).contiguous())[0][0]+ gb_normal = torch.where(+ torch.sum(gb_normal * (pos - rays_o), dim=-1, keepdim=True) > 0,+ -gb_normal,+ gb_normal+ )+ gb_cam_normal = (extrinsics[..., :3, :3].reshape(1, 1, 3, 3) @ gb_normal.unsqueeze(-1)).squeeze(-1)+ if _ == 0:+ out_dict.normal = -gb_cam_normal * 0.5 + 0.5+ mask = (rast[0, ..., -1:] > 0).float()+ out_dict.mask = mask++ # PBR attributes+ if isinstance(mesh, MeshWithVoxel):+ if 'grid_sample_3d' not in globals():+ from flex_gemm.ops.grid_sample import grid_sample_3d+ mask = rast[..., -1:] > 0+ xyz = dr.interpolate(vertices_orig, rast, faces)[0]+ xyz = ((xyz - mesh.origin) / mesh.voxel_size).reshape(1, -1, 3)+ img = grid_sample_3d(+ mesh.attrs,+ torch.cat([torch.zeros_like(mesh.coords[..., :1]), mesh.coords], dim=-1),+ mesh.voxel_shape,+ xyz,+ mode='trilinear'+ )+ img = img.reshape(1, resolution * ssaa, resolution * ssaa, mesh.attrs.shape[-1]) * mask+ gb_basecolor = img[0, ..., mesh.layout['base_color']]+ gb_metallic = img[0, ..., mesh.layout['metallic']]+ gb_roughness = img[0, ..., mesh.layout['roughness']]+ gb_alpha = img[0, ..., mesh.layout['alpha']]+ elif isinstance(mesh, MeshWithPbrMaterial):+ tri_id = rast[0, :, :, -1:]+ mask = tri_id > 0+ uv_coords = mesh.uv_coords.reshape(1, -1, 2)+ texc, texd = dr.interpolate(+ uv_coords,+ rast,+ torch.arange(mesh.uv_coords.shape[0] * 3, dtype=torch.int, device=self.device).reshape(-1, 3),+ rast_db=rast_db,+ diff_attrs='all'+ )+ # Fix problematic texture coordinates+ texc = torch.nan_to_num(texc, nan=0.0, posinf=1e3, neginf=-1e3)+ texc = torch.clamp(texc, min=-1e3, max=1e3)+ texd = torch.nan_to_num(texd, nan=0.0, posinf=1e3, neginf=-1e3)+ texd = torch.clamp(texd, min=-1e3, max=1e3)+ mid = mesh.material_ids[(tri_id - 1).long()]+ gb_basecolor = torch.zeros((resolution * ssaa, resolution * ssaa, 3), dtype=torch.float32, device=self.device)+ gb_metallic = torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device)+ gb_roughness = torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device)+ gb_alpha = torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device)+ for id, mat in enumerate(mesh.materials):+ mat_mask = (mid == id).float() * mask.float()+ mat_texc = texc * mat_mask+ mat_texd = texd * mat_mask++ if mat.base_color_texture is not None:+ bc = dr.texture(+ mat.base_color_texture.image.unsqueeze(0),+ mat_texc,+ mat_texd,+ filter_mode='linear-mipmap-linear' if mat.base_color_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest',+ boundary_mode='clamp' if mat.base_color_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap'+ )[0]+ gb_basecolor += bc * mat.base_color_factor * mat_mask+ else:+ gb_basecolor += mat.base_color_factor * mat_mask++ if mat.metallic_texture is not None:+ m = dr.texture(+ mat.metallic_texture.image.unsqueeze(0),+ mat_texc,+ mat_texd,+ filter_mode='linear-mipmap-linear' if mat.metallic_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest',+ boundary_mode='clamp' if mat.metallic_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap'+ )[0]+ gb_metallic += m * mat.metallic_factor * mat_mask+ else:+ gb_metallic += mat.metallic_factor * mat_mask++ if mat.roughness_texture is not None:+ r = dr.texture(+ mat.roughness_texture.image.unsqueeze(0),+ mat_texc,+ mat_texd,+ filter_mode='linear-mipmap-linear' if mat.roughness_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest',+ boundary_mode='clamp' if mat.roughness_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap'+ )[0]+ gb_roughness += r * mat.roughness_factor * mat_mask+ else:+ gb_roughness += mat.roughness_factor * mat_mask++ if mat.alpha_mode == AlphaMode.OPAQUE:+ gb_alpha += 1.0 * mat_mask+ else:+ if mat.alpha_texture is not None:+ a = dr.texture(+ mat.alpha_texture.image.unsqueeze(0),+ mat_texc,+ mat_texd,+ filter_mode='linear-mipmap-linear' if mat.alpha_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest',+ boundary_mode='clamp' if mat.alpha_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap'+ )[0]+ if mat.alpha_mode == AlphaMode.MASK:+ gb_alpha += (a * mat.alpha_factor > mat.alpha_cutoff).float() * mat_mask+ elif mat.alpha_mode == AlphaMode.BLEND:+ gb_alpha += a * mat.alpha_factor * mat_mask+ else:+ if mat.alpha_mode == AlphaMode.MASK:+ gb_alpha += (mat.alpha_factor > mat.alpha_cutoff).float() * mat_mask+ elif mat.alpha_mode == AlphaMode.BLEND:+ gb_alpha += mat.alpha_factor * mat_mask+ if _ == 0:+ out_dict.base_color = gb_basecolor+ out_dict.metallic = gb_metallic+ out_dict.roughness = gb_roughness+ out_dict.alpha = gb_alpha++ # Shading- #TODO+ gb_basecolor = torch.clamp(gb_basecolor, 0.0, 1.0) ** 2.2+ # gb_basecolor = torch.clamp(gb_basecolor, 0.0, 1.0)+ gb_metallic = torch.clamp(gb_metallic, 0.0, 1.0)+ gb_roughness = torch.clamp(gb_roughness, 0.0, 1.0)+ gb_alpha = torch.clamp(gb_alpha, 0.0, 1.0)+ gb_orm = torch.cat([+ torch.zeros_like(gb_metallic),+ gb_roughness,+ gb_metallic,+ ], dim=-1)+ gb_shaded = torch.stack([+ e.shade(+ pos.unsqueeze(0),+ gb_normal.unsqueeze(0),+ gb_basecolor.unsqueeze(0),+ gb_orm.unsqueeze(0),+ rays_o,+ specular=True,+ )[0]+ for e in envmap.values()+ ], dim=0)++ # Compositing+ w = (1 - alpha) * gb_alpha+ depth = torch.where(w > max_w, gb_depth, depth)+ normal = torch.where(w > max_w, gb_cam_normal, normal)+ max_w = torch.maximum(max_w, w)+ shaded += w * gb_shaded+ alpha += w++ # Ambient occulusion+ f_occ = screen_space_ambient_occlusion(+ depth, normal, perspective, intensity=1.5+ )+ shaded *= (1 - f_occ)+ out_dict.clay = (1 - f_occ)++ # Background+ if use_envmap_bg:+ bg = torch.stack([e.sample(rays_d) for e in envmap.values()], dim=0)+ shaded += (1 - alpha) * bg++ for i, k in enumerate(envmap.keys()):+ shaded_key = f"shaded_{k}" if k != '' else "shaded"+ out_dict[shaded_key] = shaded[i]++ # SSAA+ for k in out_dict.keys():+ if ssaa > 1:+ out_dict[k] = F.interpolate(out_dict[k].unsqueeze(0).permute(0, 3, 1, 2), (resolution, resolution), mode='bilinear', align_corners=False, antialias=True)+ else:+ out_dict[k] = out_dict[k].permute(2, 0, 1)+ out_dict[k] = out_dict[k].squeeze()++ # Post processing: linear → sRGB (matches Blender's display transform)+ for k in envmap.keys():+ shaded_key = f"shaded_{k}" if k != '' else "shaded"+ out_dict[shaded_key] = linear_to_srgb(out_dict[shaded_key])++ return out_dictdiff --cc supratex/weights.pyindex f001d99,0000000..c39b54amode 100644,000000..100644--- a/supratex/weights.py+++ b/supratex/weights.py@@@ -1,114 -1,0 +1,120 @@@+"""Resolve model directories from local storage or the Hugging Face Hub."""++from pathlib import Path++++# Default completion weights inside a standalone release (RAW step 30000). The++# release also keeps the earlier sharded model, which is used only as a fallback.++DEFAULT_COMPLETION_CHECKPOINT = "denoiser_step0030000.safetensors"+COMPLETION_ALLOW_PATTERNS = [- "config.json", "partial_normalization.json", "*.safetensors", "*.safetensors.index.json",++ "config.json", "partial_normalization.json", DEFAULT_COMPLETION_CHECKPOINT,+ "configs/*.json", "weights/material_completion.pt", "weights/sparse_encoders/*.json",+ "weights/scvae/*.json", "vae/*.json", "vae/ckpts/*.json",+]+++def resolve_completion_artifacts(+ root: str | Path | None = None,+ *,+ model_config: str | Path | None = None,+ checkpoint: str | Path | None = None,+ trellis_root: str | Path | None = None,+) -> tuple[Path, Path, Path]:+ """Resolve and preflight a local completion release plus its sparse VAEs.++ Standalone releases contain root config/normalization and safe weights;+ their separately obtained VAEs live at ``trellis_root`` (or ``root/vae``).+ The original configs/weights bundle layout remains supported unchanged.+ """+ if root is not None:+ root = Path(root).expanduser().resolve()+ if not root.is_dir():+ raise NotADirectoryError(f"completion bundle is not a directory: {root}")+ standalone = (root / "config.json").is_file()+ if model_config is None:+ model_config = root / ("config.json" if standalone else "configs/inference_model.json")+ if checkpoint is None:- if standalone:++ if standalone and (root / DEFAULT_COMPLETION_CHECKPOINT).is_file():++ checkpoint = root / DEFAULT_COMPLETION_CHECKPOINT++ elif standalone:+ candidates = [root / name for name in ("model.safetensors", "model.safetensors.index.json")]+ existing = [path for path in candidates if path.is_file()]+ if len(existing) > 1:+ raise ValueError("completion bundle has both single and sharded weights; select --checkpoint explicitly")+ if not existing:- raise FileNotFoundError(f"missing completion checkpoint: expected model.safetensors or model.safetensors.index.json in {root}")++ raise FileNotFoundError(f"missing completion checkpoint: expected {DEFAULT_COMPLETION_CHECKPOINT}, "++ f"model.safetensors, or model.safetensors.index.json in {root}")+ checkpoint = existing[0]+ else:+ checkpoint = root / "weights/material_completion.pt"+ if trellis_root is None:+ trellis_root = root / ("vae" if standalone else "weights/sparse_encoders")+ if model_config is None or checkpoint is None or trellis_root is None:+ raise ValueError("provide a completion bundle or model_config, checkpoint, and trellis_root")+ # Snapshot files are symlinks to opaque cache blobs. Keep their logical+ # directory so config-relative metadata and index-relative shards resolve.+ paths = tuple(Path(path).expanduser().absolute() for path in (model_config, checkpoint, trellis_root))+ from .inference.pipeline import validate_completion_artifacts+ validate_completion_artifacts(*paths)+ return paths+++def resolve_model_dir(+ source: str | Path,+ *,+ revision: str | None = None,+ cache_dir: str | Path | None = None,+ local_files_only: bool = False,+ allow_patterns: list[str] | None = None,+) -> Path:+ """Return an existing directory for a local path or ``namespace/repo``.++ Local directories take precedence over Hub IDs. Use ``hf://namespace/repo``+ to identify a Hub source explicitly; use a ``Path`` or an explicit path+ prefix to ensure a missing local directory never triggers a download.+ """+ if not isinstance(source, (str, Path)):+ raise TypeError("Model source must be a local path or a Hugging Face repo ID")+ if source == "":+ raise ValueError("Invalid model source: expected a nonempty path or namespace/repo")++ local_path = Path(source).expanduser()+ if local_path.exists():+ if not local_path.is_dir():+ raise NotADirectoryError(f"Model source is not a directory: {local_path}")+ return local_path.resolve()++ if isinstance(source, Path) or local_path.is_absolute() or source.startswith(+ ("./", "../", "~/")+ ) or source in (".", "..", "~"):+ raise FileNotFoundError(f"Model directory does not exist: {local_path}")++ repo_id = source.removeprefix("hf://")+ # Keep Hub imports off the local loading path (and lightweight CLI help).+ from huggingface_hub import snapshot_download+ from huggingface_hub.utils import HFValidationError, validate_repo_id++ try:+ validate_repo_id(repo_id)+ if repo_id.count("/") != 1:+ raise ValueError("expected namespace/repo")+ except (HFValidationError, ValueError) as exc:+ raise ValueError(+ f"Invalid model source {source!r}: expected an existing local directory "+ "or a Hugging Face repo ID in namespace/repo form"+ ) from exc++ downloaded = Path(+ snapshot_download(+ repo_id=repo_id,+ revision=revision,+ cache_dir=cache_dir,+ local_files_only=local_files_only,+ allow_patterns=allow_patterns,+ )+ ).expanduser()+ if not downloaded.exists():+ raise FileNotFoundError(f"Downloaded model directory does not exist: {downloaded}")+ if not downloaded.is_dir():+ raise NotADirectoryError(f"Downloaded model source is not a directory: {downloaded}")+ return downloaded.resolve()diff --cc texturing.pyindex 5d93941,0000000..18777cemode 100644,000000..100644--- a/texturing.py+++ b/texturing.py@@@ -1,179 -1,0 +1,192 @@@+#!/usr/bin/env python3+"""Texture a supplied mesh with Supra-Tex PBR materials."""+from __future__ import annotations++import argparse+from pathlib import Path+++def _validate_options(args: argparse.Namespace) -> None:+ from scripts.prepare_models import _pipeline++ if args.dual_view != (args.back_view_dir is not None):+ raise ValueError("--dual-view and --back-view-dir must be provided together")- if args.work_dir is not None and not args.dual_view:- raise ValueError("--work-dir requires --dual-view")++ if args.work_dir is not None and not (args.dual_view or args.refine):++ raise ValueError("--work-dir requires --dual-view or --refine")+ _pipeline.validate_export_options(args)+++def _validate_pipeline_paths(args: argparse.Namespace) -> None:+ """Reject local input/output errors before fetching a manifest or weights."""+ from scripts.prepare_models import require_file++ args.input_dir = args.input_dir.expanduser().absolute()+ args.output = args.output.expanduser().absolute()+ if args.work_dir is not None:+ args.work_dir = args.work_dir.expanduser().absolute()- for name in ("geometry.pt", "camera.json", "condition_rgba.png", "albedo.png", "mra.png"):++ for name in ("camera.json", "condition_rgba.png", "albedo.png", "mra.png"):+ require_file(args.input_dir / name)++ if not any((args.input_dir / name).is_file() for name in ("geometry.pt", "geometry.npz")):++ raise FileNotFoundError(f"missing geometry.pt or geometry.npz in {args.input_dir}")+ for name in ("model_config", "checkpoint"):+ if getattr(args, name) is not None:+ require_file(getattr(args, name).expanduser())+ for name in ("trellis_root", "back_view_dir"):+ if getattr(args, name) is not None and not getattr(args, name).expanduser().is_dir():+ raise NotADirectoryError(f"--{name.replace('_', '-')} must be an existing directory")+ output = args.output.expanduser().absolute()+ if output.suffix.lower() != ".glb":+ raise ValueError("--output must have a .glb suffix")+ if output.exists() or output.is_symlink():+ raise FileExistsError(f"refusing to overwrite existing output: {output}")+ if args.work_dir is not None:+ work = args.work_dir.expanduser().absolute()+ if work.exists() or work.is_symlink():+ raise FileExistsError(f"--work-dir must be a new directory: {work}")+ for destination in (output, args.work_dir):+ if destination is not None:+ for parent in destination.expanduser().absolute().parents:+ if parent.exists():+ if not parent.is_dir():+ raise NotADirectoryError(f"destination parent must be a directory: {parent}")+ break+++def _prepare_pipeline(args: argparse.Namespace, manifest: dict, source: dict,+ completion: dict | None) -> None:+ """Resolve only completion and VAE weights, keeping the Hub cache reusable."""- from scripts.prepare_models import COMPLETION_PATTERNS, VAE_STEMS, check_safe_weights, require_file++ from scripts.prepare_models import COMPLETION_PATTERNS, VAE_STEMS, completion_checkpoint, require_file++ def snapshot(descriptor: dict, patterns: list[str]) -> Path:+ if descriptor["kind"] == "local":+ return Path(descriptor["path"])+ from huggingface_hub import snapshot_download+ try:+ return Path(snapshot_download(+ repo_id=descriptor["repo_id"], revision=descriptor.get("revision"),+ allow_patterns=patterns,+ cache_dir=str(args.cache_dir.expanduser()) if args.cache_dir is not None else None,+ local_files_only=args.local_files_only))+ except Exception:+ detail = "the required weights must already be cached" if args.local_files_only else "check the revision, network and your access"+ raise RuntimeError(f"Cannot load weights from {descriptor['repo_id']}; {detail}") from None++ if completion is not None:+ # Preserve standalone/legacy bundle overrides accepted by --pretrained.+ root = snapshot(completion, COMPLETION_PATTERNS + ["configs/*.json", "weights/material_completion.pt",+ "weights/sparse_encoders/*.json", "weights/scvae/*.json"])+ args.pretrained = str(root)+ elif args.model_config is None or args.checkpoint is None:+ subdir = manifest["models"]["completion"]+ root = snapshot(source, [f"{subdir}/{pattern}" for pattern in COMPLETION_PATTERNS]) / subdir+ args.pretrained = str(root)+ else:+ root = None+ if root is not None:+ standalone = (root / "config.json").is_file()+ if args.model_config is None:+ require_file(root / ("config.json" if standalone else "configs/inference_model.json"))+ if standalone:+ require_file(root / "partial_normalization.json")+ if args.checkpoint is None:+ if standalone:- check_safe_weights(root)++ completion_checkpoint(root)+ else:+ require_file(root / "weights/material_completion.pt")+ if args.trellis_root is None:+ entry = manifest["external_models"]["vae"]+ args.trellis_root = snapshot({"kind": "hub", **entry}, entry["allow_patterns"])+ vae = args.trellis_root.expanduser()+ vae = vae / "ckpts" if (vae / "ckpts").is_dir() else vae+ for stem in VAE_STEMS:+ for suffix in (".json", ".safetensors"):+ require_file(vae / (stem + suffix))+ args.local_files_only = True+++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description="Complete a PBR GLB from a mesh, camera, RGBA image, and material maps.",+ allow_abbrev=False)+ parser.add_argument("--pipeline", help="SUPRA-Tex release directory, pipeline.json, or HF repo ID; loads completion and VAE weights")+ parser.add_argument("--pipeline-revision", help="HF revision of the complete SUPRA-Tex release")- parser.add_argument("--input-dir", required=True, type=Path, help="directory containing geometry.pt, camera.json, condition_rgba.png, albedo.png, and mra.png")++ parser.add_argument("--input-dir", type=Path, default=Path(__file__).resolve().parent / "assets/examples/pitcher_plant",++ help="directory containing geometry.pt or geometry.npz, camera.json, condition_rgba.png, "++ "albedo.png, and mra.png (default: bundled assets/examples/pitcher_plant)")+ parser.add_argument("--output", required=True, type=Path, help="new destination GLB; an existing file is never replaced")+ parser.add_argument("--pretrained", help="local model bundle directory or Hugging Face namespace/repo")+ parser.add_argument("--revision", help="Hugging Face model revision")+ parser.add_argument("--cache-dir", type=Path, help="Hugging Face download cache")+ parser.add_argument("--local-files-only", action="store_true", help="use cached model files without network access")+ parser.add_argument("--attention", choices=("auto", "flash_attn_3", "flash_attn", "sdpa", "xformers"))+ parser.add_argument("--low-vram", action=argparse.BooleanOptionalAction, default=None,+ help="CPU offload; auto enabled on GPUs with up to 24 GiB")+ parser.add_argument("--model-config", type=Path, help="public Supra-Tex model ABI JSON; overrides bundle config")+ parser.add_argument("--checkpoint", type=Path, help="public material-completion checkpoint; overrides bundle weights")+ parser.add_argument("--trellis-root", type=Path, help="TRELLIS.2 VAE directory (all four components for HF releases)")+ parser.add_argument("--seed", type=int)+ parser.add_argument("--texture-size", type=int)+ parser.add_argument("--decimation-target", type=int)+ parser.add_argument("--texture-format", choices=("png", "webp"))- parser.add_argument("--gutter", action="store_true", help="enable chart-isolated one-texel base-color gutter padding (default: disabled)")- parser.add_argument("--dual-view", action="store_true", help="enable optional front/back observation fusion and validated reprojection")++ parser.add_argument("--gutter", action="store_true", help="enable chart-isolated one-texel base-color gutter padding (default: disabled); "++ "with --refine, the observation-guided gutter is used")++ parser.add_argument("--refine", action="store_true",++ help="refine the visible texture after export: write the observed reference-view albedo into the atlas "++ "and repair its UV gutters from the observation (sharper fine text and detail; needs the 4096 PNG "++ "atlas; adds about 2 minutes on an RTX 3090)")++ parser.add_argument("--remove-floaters", action="store_true",++ help="before completion, drop disconnected geometry pieces that project mostly outside the "++ "image foreground; extra geometry attached to the object is kept")++ parser.add_argument("--dual-view", action="store_true", help="add front/back observation fusion from a prepared back view; includes --refine for both views")+ parser.add_argument("--back-view-dir", type=Path, help="prepared v4 back-view package with generated RGBA, material maps and receipts")+ parser.add_argument("--work-dir", type=Path, help="new directory for dual-view intermediate meshes and receipts")+ args = parser.parse_args(argv)+ if not args.pipeline and args.pipeline_revision is not None:+ parser.error("--pipeline-revision requires --pipeline")+ if args.pipeline and args.revision is not None and args.pretrained is None:+ parser.error("--revision requires --pretrained with --pipeline; use --pipeline-revision for the release")+ try:+ _validate_options(args)+ if args.pipeline:+ from scripts.prepare_models import _pipeline+ completion = _pipeline.model_source(args.pretrained, args.revision) if args.pretrained is not None else None+ _validate_pipeline_paths(args)+ manifest, source = _pipeline.resolve_pipeline(+ args.pipeline, revision=args.pipeline_revision, cache_dir=args.cache_dir,+ local_files_only=args.local_files_only)+ defaults = manifest["defaults"]+ else:+ from scripts.run_example import inference_defaults+ defaults = inference_defaults()+ for key, value in defaults.items():+ if getattr(args, key) is None:+ setattr(args, key, value)+ _validate_options(args)+ if args.pipeline:+ _prepare_pipeline(args, manifest, source, completion)+ except (OSError, ValueError, RuntimeError) as error:+ parser.error(str(error))+ if not args.pretrained and not all((args.model_config, args.checkpoint, args.trellis_root)):+ parser.error("provide --pipeline, --pretrained, or all of --model-config, --checkpoint, and --trellis-root")+ return args+++def main() -> None:+ args = parse_args()+ from supratex.inference.runtime import configure_inference_runtime+ configure_inference_runtime(attention=args.attention, low_vram=args.low_vram)+ if args.pretrained:+ from supratex.weights import COMPLETION_ALLOW_PATTERNS, resolve_completion_artifacts, resolve_model_dir+ root = resolve_model_dir(args.pretrained, revision=args.revision, cache_dir=args.cache_dir,+ local_files_only=args.local_files_only,+ allow_patterns=COMPLETION_ALLOW_PATTERNS)+ args.model_config, args.checkpoint, args.trellis_root = resolve_completion_artifacts(+ root, model_config=args.model_config, checkpoint=args.checkpoint,+ trellis_root=args.trellis_root)+ from supratex.inference import run_completion- optional = {"back_view_dir": args.back_view_dir, "work_dir": args.work_dir} if args.dual_view else {}- run_completion(input_dir=args.input_dir, output=args.output, model_config=args.model_config, checkpoint=args.checkpoint, trellis_root=args.trellis_root, seed=args.seed, texture_size=args.texture_size, decimation_target=args.decimation_target, texture_format=args.texture_format, gutter=args.gutter, **optional)++ optional = ({"back_view_dir": args.back_view_dir, "work_dir": args.work_dir} if args.dual_view else++ {"refine": True, "work_dir": args.work_dir} if args.refine else {})++ run_completion(input_dir=args.input_dir, output=args.output, model_config=args.model_config, checkpoint=args.checkpoint, trellis_root=args.trellis_root, seed=args.seed, texture_size=args.texture_size, decimation_target=args.decimation_target, texture_format=args.texture_format, gutter=args.gutter, remove_floaters=args.remove_floaters, **optional)+++if __name__ == "__main__":+ main()