Idol: a single image to 3D Gaussians. Inference SDK and demo.
Python
initial commit
alex44lel4702a7f00850
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..3c26326--- /dev/null+++ b/.gitignore@@ -0,0 +1,22 @@+# python+__pycache__/+*.py[cod]+*.egg-info/+build/+dist/+.venv/+uv.lock++# tooling+.ruff_cache/++# outputs and weights+/outputs/+*.ply+*.safetensors+*.pt++# os / editor+.DS_Store+.idea/+.vscode/diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..d645695--- /dev/null+++ b/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..433936c--- /dev/null+++ b/README.md@@ -0,0 +1,152 @@+# Idol++**A single image to 3DGS object model**++Idol turns one picture of an object into a 3D Gaussian splat. Give it a render, a generated image or a photo: it removes the background, frames the object and generates up to 1,048,576 Gaussians, including the sides the picture never showed. It runs on consumer GPUs, using 7.2 GB of VRAM and can run in under 2 seconds.++<div align="center">++[](https://huggingface.co/speridlabs/idol)+[](https://huggingface.co/spaces/speridlabs/idol)+[](https://www.python.org/downloads/)++</div>++|  |  |+|---|---|+|  |  |++Each pair: the input image and the generated object turning. The+[demo](https://huggingface.co/spaces/speridlabs/idol) has 93 more examples ready to run and takes your own images as well.++## Model++| | |+|---|---|+| Output | 3D Gaussians: 32,768 to 1,048,576 (default 262,144), standard 3DGS `.ply` |+| DiT | 370M parameters |+| Image conditioning | DINOv3 ViT-H+ and FLUX.2 VAE |+| Decoder | 288M parameters |+| Background removal | BiRefNet |+| Sampler | Euler, 50 steps, classifier-free guidance 3.0, time shift 3.0 |++## Install++```bash+pip install -e . # Python >= 3.10, PyTorch >= 2.5+pip install -e ".[demo]" # + Gradio, to run the demo locally+```++The weights are downloaded from Hugging Face on first use, you need to request access to+[facebook/dinov3-vith16plus-pretrain-lvd1689m](https://huggingface.co/facebook/dinov3-vith16plus-pretrain-lvd1689m)+and [black-forest-labs/FLUX.2-dev](https://huggingface.co/black-forest-labs/FLUX.2-dev) first, then log in with+`hf auth login`.++`flash-attn`, if installed, is used for attention; otherwise PyTorch's `scaled_dot_product_attention` is (same+result, slower). Set `ATTN_BACKEND=sdpa` or `ATTN_BACKEND=flash_attn` to choose.++## Inference++```bash+python -m idol.sample --image photo.jpg --mode real+python -m idol.sample --image renders/ --mode synthetic --out outputs+```++For each image this writes `<name>.ply` (open it in any Gaussian splat viewer), `<name>_input.png` (the image the model saw, after background+removal and cropping) and `<name>_camera.json` (the predicted camera of the input).++**Pick the mode for your input:**++| `--mode` | for |+|---|---|+| `synthetic` (default) | computer generated images|+| `real` | real world photographs |++Other flags:++| flag | default | |+|---|---|---|+| `--seed` | 42 | same seed, same object |+| `--steps` | 50 | sampling steps |+| `--cfg_strength` | 3.0 | classifier-free guidance |+| `--rescale_t` | 3.0 | time shift: higher spends more steps at high noise |+| `--num_gaussians` | 262144 | 32,768 to 1,048,576, a multiple of 32 |+| `--dinov3_dtype` | bf16 | `fp32` runs the DINOv3 encoder in full precision (1.7 GB more memory) |+| `--weights` | `speridlabs/idol` | a Hugging Face repo or a local folder |+| `--no_optimize` | optimized | turn off the faster sampling (see below) |++**Faster sampling is on by default on GPU** The first image in a process is slower while it pytorch compiles; the rest run at full+speed.++### Python API++```python+from idol import IdolPipeline++pipeline = IdolPipeline.from_pretrained("speridlabs/idol")+output = pipeline("photo.jpg", mode="real", seed=42, num_gaussians=1_048_576)+output.gaussian.save_ply("photo.ply")+output.preprocessed_image.save("photo_input.png")+```++### Demo++The Gradio app behind the [Hugging Face Space](https://huggingface.co/spaces/speridlabs/idol) is in `demo/`,+with the example images. It runs on ZeroGPU there and on any local GPU:++```bash+pip install -e ".[demo]"+cd demo && python app.py+```++## More details about the model++| Component | Parameters | Precision on GPU | Weights in VRAM |+|---|---|---|---|+| DiT (denoiser) | 370.6M | FP16 transformer blocks; FP32 embeddings and norms | ~0.8–1.0 GB |+| Octree decoder | 50.8M | FP16 transformer blocks; FP32 embeddings and norms | ~0.1–0.2 GB |+| Gaussian decoder | 237.3M | FP16 transformer blocks; FP32 embeddings and norms | ~0.5–0.9 GB |+| BiRefNet (background removal) | 220.7M | FP16 | ~0.44 GB |+| DINOv3 ViT-H+/16 | 840.6M | bf16 | ~1.68 GB |+| FLUX.2 VAE | 84.1M | bf16 (FP32 checkpoint, cast on load) | ~0.17 GB |+| **Full request** | **~1.80B** | mostly FP16 / bf16, some FP32 | **~3.7–4.4 GB of weights, 7.2 GB peak** |++## Benchmark++Idol, TripoSplat, TRELLIS and LGM, scored at the input view (PSNR, SSIM, LPIPS, IoU) and at seven new views+(DINOv2, CLIP, sharpness distance). Mean scores, 1 × H100 per model. Bold is the best in each column.++| Model | Setting | PSNR ↑ | SSIM ↑ | LPIPS ↓ | IoU ↑ | DINOv2 ↑ | CLIP ↑ | Sharpness distance ↓ | Request time ↓ |+|---|---|---|---|---|---|---|---|---|---|+| **Idol** | 50 steps, 262,144 Gaussians | 12.25 | **0.726** | **0.213** | **0.862** | **0.781** | **0.885** | **0.81** | 6.8 s |+| TripoSplat | 50 steps, 262,144 Gaussians | 11.76 | 0.712 | 0.225 | 0.860 | 0.743 | 0.868 | 1.03 | 9.9 s |+| TRELLIS | Paper setting, 50 + 50 steps | 11.89 | 0.716 | 0.235 | 0.845 | 0.754 | 0.868 | 0.97 | 7.1 s |+| LGM | Default, 65,536 Gaussians | **12.46**\* | 0.722 | 0.237 | 0.834 | 0.575 | 0.784 | 1.22 | **1.1 s** |++\* LGM has the highest PSNR despite visibly blurry results, because PSNR averages squared pixel error.++## Across GPUs++One image to 262,144 Gaussians in 3.4 s. Request time at 50 steps: median over 8 images, with the same code and+settings on every GPU, one GPU per machine.++| GPU | VRAM | Request time |+|---|---|---|+| B300 | 269 GB | 3.4 s |+| B200 | 179 GB | 3.6 s |+| H200 | 140 GB | 6.6 s |+| H100 | 80 GB | 6.7 s |+| RTX 5090 | 32 GB | 14.1 s |+| A100 | 80 GB | 16.3 s |+| L40S | 45 GB | 16.6 s |+| RTX 4090 | 24 GB | 19.1 s |+| RTX 3080 | 10 GB | 46.2 s |+| L4 | 22 GB | 54.6 s |++## Acknowledgements++Idol builds on [TripoSplat](https://github.com/VAST-AI-Research/TripoSplat). It uses+[DINOv3](https://github.com/facebookresearch/dinov3), the [FLUX.2](https://huggingface.co/black-forest-labs/FLUX.2-dev)+VAE and [BiRefNet](https://github.com/ZhengPeng7/BiRefNet).++**Made with ❤️ by [speridlabs.com](https://speridlabs.com)**diff --git a/assets/gallery/armchair.webp b/assets/gallery/armchair.webpnew file mode 100644index 0000000..4c3487aBinary files /dev/null and b/assets/gallery/armchair.webp differdiff --git a/assets/gallery/avocado.webp b/assets/gallery/avocado.webpnew file mode 100644index 0000000..fbfd346Binary files /dev/null and b/assets/gallery/avocado.webp differdiff --git a/assets/gallery/axolotl.webp b/assets/gallery/axolotl.webpnew file mode 100644index 0000000..0ebd109Binary files /dev/null and b/assets/gallery/axolotl.webp differdiff --git a/assets/gallery/lamp.webp b/assets/gallery/lamp.webpnew file mode 100644index 0000000..d0d424dBinary files /dev/null and b/assets/gallery/lamp.webp differdiff --git a/demo/README.md b/demo/README.mdnew file mode 100644index 0000000..f73db9e--- /dev/null+++ b/demo/README.md@@ -0,0 +1,21 @@+---+title: Idol+emoji: 🗿+colorFrom: gray+colorTo: red+sdk: gradio+sdk_version: 5.49.1+python_version: '3.12'+app_file: app.py+pinned: false+license: apache-2.0+short_description: One image to a 3D object (Gaussian splats)+---++# Idol demo++Speridlabs Gradio demo. `app.py` is the UI; `model.py` is the model.+`examples/presets.json` lists each example image with the settings it is run with.++The Space needs an `HF_TOKEN` secret from an account with access to+`facebook/dinov3-vith16plus-pretrain-lvd1689m` and `black-forest-labs/FLUX.2-dev` (the image encoders).diff --git a/demo/app.py b/demo/app.pynew file mode 100644index 0000000..112fc82--- /dev/null+++ b/demo/app.py@@ -0,0 +1,234 @@+import json+import random+from pathlib import Path++import gradio as gr++try:+ import spaces # Hugging Face ZeroGPU; imported before the model so its CUDA placement is deferred++ gpu = spaces.GPU(duration=120)+except ImportError:+ def gpu(fn):+ return fn++import model # noqa: E402++# The splat viewer opens every object at orbit radius 5; this factor zooms it in on load (5.5/10 zoom instead of 3/10).+VIEWER_ZOOM = 5.5 / 3+++NAME = "Idol"+TAGLINE = "<strong>One image in, a 3D object out.</strong> Idol turns a single picture of an object into " \+ "3D Gaussians splat. Pick an example below, or <em>upload your own.</em>"+LINKS = {"Code": "https://github.com/speridlabs/idol-sdk",+ "Weights": "https://huggingface.co/speridlabs/idol"}++ROOT = Path(__file__).parent+PRESETS = json.loads((ROOT / "examples/presets.json").read_text())+MODE_LABEL = {mode: label for label, mode in model.MODES.items()}+# the example shown when the page opens, with its splat and model input generated beforehand with its own settings+DEFAULT_EXAMPLE = next(p for p in PRESETS if p["image"] == "examples/obj-backpack.webp")+DEFAULT_PLY = ROOT / "examples/default-obj-backpack.ply"+GAUSSIAN_LABEL = {count: label for label, count in model.GAUSSIANS.items()}+++@gpu+def infer(image, mode, steps, cfg_scale, rescale_t, seed, randomize, gaussians):+ if image is None:+ raise gr.Error("Upload an image or pick an example first.")+ if randomize:+ seed = random.randint(0, 2**31 - 1)+ ply, prepared = model.generate(image, model.MODES[mode], int(steps), cfg_scale, rescale_t, int(seed),+ model.GAUSSIANS[gaussians])+ return ply, prepared, seed+++def meta(gaussians, steps):+ return f'<div class="sl-meta"><span>{gaussians} Gaussians · {int(steps)} steps</span></div>'+++def run(image, mode, steps, cfg_scale, rescale_t, seed, randomize, gaussians):+ ply, _, seed = infer(image, mode, steps, cfg_scale, rescale_t, seed, randomize, gaussians)+ return ply, seed, meta(gaussians, steps)+++def show_default_example():+ if not DEFAULT_PLY.exists(): # the .ply ships with the Space only; without it the viewer starts empty+ return None, ""+ p = DEFAULT_EXAMPLE+ return str(DEFAULT_PLY), meta(GAUSSIAN_LABEL[p["num_gaussians"]], p["steps"])+++def shuffle_examples():+ # every visitor sees the examples in a new random order; the order is kept so a click maps back to its preset+ order = random.sample(range(len(PRESETS)), len(PRESETS))+ return [str(ROOT / PRESETS[i]["image"]) for i in order], order+++def pick(order, evt: gr.SelectData):+ p = PRESETS[order[evt.index]]+ return (str(ROOT / p["image"]), MODE_LABEL[p["mode"]], p["steps"], p["cfg"], p["rescale_t"], p["seed"], False,+ GAUSSIAN_LABEL[p["num_gaussians"]])+++FONT = [gr.themes.GoogleFont("Inter", weights=(400, 500, 600, 700)), "ui-sans-serif", "system-ui", "sans-serif"]+MONO = [gr.themes.GoogleFont("IBM Plex Mono", weights=(400, 500, 600, 700)), "ui-monospace", "monospace"]+theme = gr.themes.Base(font=FONT, font_mono=MONO, radius_size=gr.themes.sizes.radius_none,+ text_size=gr.themes.sizes.text_lg).set(+ body_background_fill="#ffffff", body_background_fill_dark="#000000",+ body_text_color="#000000", body_text_color_dark="#ffffff",+ block_background_fill="#ffffff", block_background_fill_dark="#000000",+ background_fill_primary="#ffffff", background_fill_primary_dark="#000000",+ background_fill_secondary="#f7f7f7", background_fill_secondary_dark="#111111",+ border_color_primary="#e3e3e3", border_color_primary_dark="rgba(255,255,255,0.15)",+ block_border_color="#e3e3e3", block_border_color_dark="rgba(255,255,255,0.15)", block_shadow="none",+ input_background_fill="#ffffff", input_background_fill_dark="#000000",+ input_border_color="#d4d4d4", input_border_color_dark="rgba(255,255,255,0.25)",+ input_border_color_focus="#000000", input_border_color_focus_dark="#ffffff",+ button_primary_background_fill="#000000", button_primary_background_fill_dark="#ffffff",+ button_primary_background_fill_hover="#d94a1f", button_primary_background_fill_hover_dark="#d94a1f",+ button_primary_text_color="#ffffff", button_primary_text_color_dark="#000000",+ color_accent="#d94a1f", color_accent_soft="#fbe7e0", slider_color="#d94a1f", slider_color_dark="#d94a1f",+ checkbox_background_color_selected="#000000", checkbox_background_color_selected_dark="#ffffff",+)+CSS = """+:root { --sl-fg: #000; --sl-fg-2: #444; --sl-fg-3: #6b6b6b; --sl-rule: #e3e3e3; }+.dark { --sl-fg: #fff; --sl-fg-2: rgba(255,255,255,.75); --sl-fg-3: rgba(255,255,255,.55);+ --sl-rule: rgba(255,255,255,.15); }+.gradio-container { max-width: 1280px !important; margin: 0 auto !important; padding: 0 32px !important; }+footer { display: none !important; }+.sl-head { padding: 40px 0 28px; border-bottom: 1px solid var(--sl-rule); margin-bottom: 8px; }+.sl-label, .sl-meta, .sl-links a, .sl-links button, .sl-section, .block-label, .label-wrap span, label > span {+ font-family: 'IBM Plex Mono', ui-monospace, monospace !important; text-transform: uppercase;+ letter-spacing: .12em; font-size: 13px !important; font-weight: 600 !important; color: var(--sl-fg-3) !important; }+.gradio-container { font-weight: 500; }+.sl-head h1 { margin: 14px 0 0; font-size: clamp(56px, 6.4vw, 104px); font-weight: 700; line-height: .86;+ letter-spacing: -0.055em; color: var(--sl-fg); }+.sl-row { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 16px 40px; }+.sl-head p { margin: 18px 0 0; max-width: 60ch; font-size: 19px; font-weight: 500; line-height: 1.5; color: var(--sl-fg-2); }+.sl-head p strong { color: var(--sl-fg); font-weight: 600; }+.sl-head p em { color: #d94a1f; font-style: normal; font-weight: 600; }+.sl-links { display: flex; gap: 10px; }+.sl-links a, .sl-links button { display: inline-flex; align-items: center; height: 40px; padding: 0 20px;+ border: 1px solid var(--sl-fg); background: transparent; color: var(--sl-fg) !important; text-decoration: none;+ cursor: pointer; transition: background .15s, color .15s; }+.sl-links a:hover, .sl-links button:hover { background: var(--sl-fg); color: var(--body-background-fill) !important; }+#sl-theme { width: 44px; padding: 0; justify-content: center; font-size: 19px !important; letter-spacing: 0; }+#sl-theme::before { content: "☾"; }+.dark #sl-theme::before { content: "☀"; }+.sl-meta { display: flex; gap: 16px; white-space: nowrap; padding-top: 6px; font-size: 12px !important;+ font-weight: 400 !important; color: var(--sl-fg-2) !important; }+div.sl-section { font-weight: 700 !important; }+.sl-section { border-top: 1px solid var(--sl-rule); padding-top: 28px !important; margin-top: 28px; }+#generate { height: 52px; font-size: 17px; font-weight: 600; letter-spacing: .01em; }+#result { background: #0c0c0c; }+#result img { object-fit: contain; }+#presets .thumbnail-item { border: 0 !important; box-shadow: none !important; overflow: hidden; }+#presets .thumbnail-item img { transition: transform .6s ease-out; }+#presets .thumbnail-item:hover img { transform: scale(1.04); }+#presets .caption-label { display: none; }+#presets .grid-wrap { max-height: none !important; height: auto !important; overflow: visible !important; }+#sl-settings > .label-wrap span { color: var(--sl-fg) !important; font-weight: 600; }+#presets .thumbnail-item.selected { outline: 2px solid #d94a1f; outline-offset: -2px; }+/* only the input image stretches, so the input column ends where the viewer ends; the viewer keeps its height */+#sl-main > .column > *, #sl-main > .column > .form > * { flex-grow: 0 !important; }+#sl-main > .column:first-child > #sl-input { flex: 1 1 0 !important; height: auto !important; min-height: 360px; }+#sl-input .image-container, #sl-input .upload-container { min-height: 0; }+/* icons: larger and drawn with a thicker stroke */+.icon-button > div.small, .icon-button > div.x-small { width: 20px; height: 20px; }+#result .icon-button-wrapper button > div { width: 24px; height: 24px; }+.source-selection button svg, .icon-button svg { stroke-width: 2.5; }+.source-selection button { width: 28px; height: 28px; }+/* sliders: same width for the min/max labels and the number boxes, so all tracks start and end at the same x */+#sl-settings .slider_input_container .min_value, #sl-settings .slider_input_container .max_value {+ flex: 0 0 2.6em; }+#sl-settings .slider_input_container .min_value { text-align: left; }+#sl-settings .slider_input_container .max_value { text-align: right; }+#sl-settings .tab-like-container input[type="number"] { width: 64px; flex: 0 0 64px; }+@media (max-width: 760px) {+ .sl-head { padding-top: 24px; }+ #presets .grid-container { grid-template-columns: repeat(3, minmax(0, 1fr)) !important; }+ #sl-meta-spacer { display: none !important; }+}+"""+# Runs once when the page loads. Three jobs: (1) file requests carry the session cookies: the splat viewer fetches+# the .ply with `credentials: "omit"`, which a private Space answers with a 404, so the generated object never+# appeared; (2) each loaded splat opens zoomed in by VIEWER_ZOOM; (3) dark by default; the header toggle flips+# gradio's `dark` class and remembers the choice.+THEME_JS = """() => {+ const VIEWER_ZOOM = VIEWER_ZOOM_VALUE;+ const originalFetch = window.fetch.bind(window);+ window.fetch = (resource, options) => {+ const url = typeof resource === 'string' ? resource : (resource && resource.url) || '';+ if (url.includes('/gradio_api/file=')) options = Object.assign({}, options, { credentials: 'same-origin' });+ // the splat viewer fetches the .ply right after creating its orbit camera (radius 5): zoom that camera in with+ // one wheel step. Its wheel handler does radius += deltaY * 0.025 * (0.1 + 0.9 * (radius - 0.1) / 29.9).+ const canvas = document.querySelector('#result canvas');+ if (canvas && url.split('?')[0].endsWith('.ply')) {+ const startRadius = 5, targetRadius = startRadius / VIEWER_ZOOM;+ const wheelScale = 0.025 * (0.1 + 0.9 * (startRadius - 0.1) / 29.9);+ canvas.dispatchEvent(new WheelEvent('wheel', { deltaY: (targetRadius - startRadius) / wheelScale, cancelable: true }));+ }+ return originalFetch(resource, options);+ };+ const set = (dark) => { document.body.classList.toggle('dark', dark); localStorage.setItem('sl-theme', dark ? 'dark' : 'light'); };+ set(localStorage.getItem('sl-theme') !== 'light');+ document.addEventListener('click', (e) => { if (e.target.closest('#sl-theme')) set(!document.body.classList.contains('dark')); });+}""".replace("VIEWER_ZOOM_VALUE", f"{VIEWER_ZOOM:.6f}")+# Page padding on phones. It lives in <head> because gradio scopes every rule inside the custom CSS under the page+# container, so a rule that targets the container itself (or the <main> around it) never matches from there.+PHONE_HEAD = """<style>@media (max-width: 760px) {+ .gradio-container { padding: 0 16px !important; }+ main.fillable.app { padding-left: 0 !important; padding-right: 0 !important; }+}</style>"""+LINK_HTML = "".join(f'<a href="{u}" target="_blank">{t}</a>' for t, u in LINKS.items())+HEAD = f"""+<div class="sl-head">+ <span class="sl-label">Speridlabs · Research</span>+ <div class="sl-row">+ <h1>{NAME}</h1>+ <div class="sl-links">{LINK_HTML}<button id="sl-theme" type="button" aria-label="Toggle light/dark"></button></div>+ </div>+ <p>{TAGLINE}</p>+</div>+"""++first = DEFAULT_EXAMPLE+with gr.Blocks(title=f"{NAME} · Speridlabs", theme=theme, css=CSS, js=THEME_JS, head=PHONE_HEAD) as demo:+ gr.HTML(HEAD)+ with gr.Row(equal_height=True, elem_id="sl-main"):+ with gr.Column(scale=5):+ image = gr.Image(value=str(ROOT / first["image"]), type="pil", image_mode="RGBA", label="Input image",+ sources=["upload", "clipboard"], height=360, elem_id="sl-input")+ mode = gr.Radio(list(model.MODES), value=MODE_LABEL[first["mode"]], label="Input type")+ run_btn = gr.Button("Generate", variant="primary", elem_id="generate")+ with gr.Accordion("Settings", open=False, elem_id="sl-settings"):+ gaussians = gr.Dropdown(list(model.GAUSSIANS), value=GAUSSIAN_LABEL[first["num_gaussians"]],+ label="Gaussians")+ steps = gr.Slider(10, 100, value=first["steps"], step=1, label="Steps")+ cfg_scale = gr.Slider(0.0, 10.0, value=first["cfg"], step=0.1, label="Guidance scale")+ rescale_t = gr.Slider(1.0, 6.0, value=first["rescale_t"], step=0.1, label="Time shift")+ seed = gr.Number(value=first["seed"], precision=0, label="Seed")+ randomize = gr.Checkbox(value=False, label="Random seed")+ with gr.Column(scale=7):+ result = gr.Model3D(show_label=False, elem_id="result", height="min(640px, 92vw)",+ clear_color=(0.05, 0.05, 0.05, 1.0))+ with gr.Row():+ gr.Column(scale=5, min_width=0, elem_id="sl-meta-spacer")+ with gr.Column(scale=7):+ info = gr.HTML("")+ gr.HTML('<div class="sl-section">Examples — click to load the image and its settings</div>')+ presets = gr.Gallery(None, columns=6, rows=4, height="auto",+ object_fit="contain", allow_preview=False, show_label=False, show_share_button=False,+ show_download_button=False, elem_id="presets")+ order = gr.State()+ inputs = [image, mode, steps, cfg_scale, rescale_t, seed, randomize, gaussians]+ run_btn.click(run, inputs, [result, seed, info], show_progress_on=result)+ presets.select(pick, order, [image, mode, steps, cfg_scale, rescale_t, seed, randomize, gaussians])+ demo.load(shuffle_examples, None, [presets, order], show_progress="hidden")+ # loaded after the page script, so the viewer's .ply request already carries the cookies and gets the zoom+ demo.load(show_default_example, None, [result, info], show_progress="hidden")++if __name__ == "__main__":+ demo.queue().launch()diff --git a/demo/examples/fig-alien.webp b/demo/examples/fig-alien.webpnew file mode 100644index 0000000..26e2aefBinary files /dev/null and b/demo/examples/fig-alien.webp differdiff --git a/demo/examples/fig-axolotl.webp b/demo/examples/fig-axolotl.webpnew file mode 100644index 0000000..19a1b15Binary files /dev/null and b/demo/examples/fig-axolotl.webp differdiff --git a/demo/examples/fig-barista.webp b/demo/examples/fig-barista.webpnew file mode 100644index 0000000..a023c2cBinary files /dev/null and b/demo/examples/fig-barista.webp differdiff --git a/demo/examples/fig-bear-hoodie.webp b/demo/examples/fig-bear-hoodie.webpnew file mode 100644index 0000000..1a0e4a7Binary files /dev/null and b/demo/examples/fig-bear-hoodie.webp differdiff --git a/demo/examples/fig-cowboy.webp b/demo/examples/fig-cowboy.webpnew file mode 100644index 0000000..e4047eeBinary files /dev/null and b/demo/examples/fig-cowboy.webp differdiff --git a/demo/examples/fig-dj.webp b/demo/examples/fig-dj.webpnew file mode 100644index 0000000..86bec11Binary files /dev/null and b/demo/examples/fig-dj.webp differdiff --git a/demo/examples/fig-dog-corgi.webp b/demo/examples/fig-dog-corgi.webpnew file mode 100644index 0000000..49488f6Binary files /dev/null and b/demo/examples/fig-dog-corgi.webp differdiff --git a/demo/examples/fig-explorer.webp b/demo/examples/fig-explorer.webpnew file mode 100644index 0000000..f7b0321Binary files /dev/null and b/demo/examples/fig-explorer.webp differdiff --git a/demo/examples/fig-football.webp b/demo/examples/fig-football.webpnew file mode 100644index 0000000..801fd87Binary files /dev/null and b/demo/examples/fig-football.webp differdiff --git a/demo/examples/fig-fox.webp b/demo/examples/fig-fox.webpnew file mode 100644index 0000000..a4498fbBinary files /dev/null and b/demo/examples/fig-fox.webp differdiff --git a/demo/examples/fig-ghost.webp b/demo/examples/fig-ghost.webpnew file mode 100644index 0000000..466e776Binary files /dev/null and b/demo/examples/fig-ghost.webp differdiff --git a/demo/examples/fig-grandma.webp b/demo/examples/fig-grandma.webpnew file mode 100644index 0000000..ce7e8bbBinary files /dev/null and b/demo/examples/fig-grandma.webp differdiff --git a/demo/examples/fig-knight.webp b/demo/examples/fig-knight.webpnew file mode 100644index 0000000..7cbcc40Binary files /dev/null and b/demo/examples/fig-knight.webp differdiff --git a/demo/examples/fig-panda.webp b/demo/examples/fig-panda.webpnew file mode 100644index 0000000..49e3d02Binary files /dev/null and b/demo/examples/fig-panda.webp differdiff --git a/demo/examples/fig-robot-cute.webp b/demo/examples/fig-robot-cute.webpnew file mode 100644index 0000000..6bc2705Binary files /dev/null and b/demo/examples/fig-robot-cute.webp differdiff --git a/demo/examples/fig-robot-mech.webp b/demo/examples/fig-robot-mech.webpnew file mode 100644index 0000000..c0aa43eBinary files /dev/null and b/demo/examples/fig-robot-mech.webp differdiff --git a/demo/examples/fig-rockstar.webp b/demo/examples/fig-rockstar.webpnew file mode 100644index 0000000..97f2dc8Binary files /dev/null and b/demo/examples/fig-rockstar.webp differdiff --git a/demo/examples/fig-snowman.webp b/demo/examples/fig-snowman.webpnew file mode 100644index 0000000..f353962Binary files /dev/null and b/demo/examples/fig-snowman.webp differdiff --git a/demo/examples/fig-viking.webp b/demo/examples/fig-viking.webpnew file mode 100644index 0000000..04431fdBinary files /dev/null and b/demo/examples/fig-viking.webp differdiff --git a/demo/examples/fig-zombie.webp b/demo/examples/fig-zombie.webpnew file mode 100644index 0000000..d7c8df5Binary files /dev/null and b/demo/examples/fig-zombie.webp differdiff --git a/demo/examples/food-avocado.webp b/demo/examples/food-avocado.webpnew file mode 100644index 0000000..883e8ebBinary files /dev/null and b/demo/examples/food-avocado.webp differdiff --git a/demo/examples/food-bread-loaf.webp b/demo/examples/food-bread-loaf.webpnew file mode 100644index 0000000..ecf9327Binary files /dev/null and b/demo/examples/food-bread-loaf.webp differdiff --git a/demo/examples/food-cupcake.webp b/demo/examples/food-cupcake.webpnew file mode 100644index 0000000..23f9636Binary files /dev/null and b/demo/examples/food-cupcake.webp differdiff --git a/demo/examples/food-donut.webp b/demo/examples/food-donut.webpnew file mode 100644index 0000000..34e8eaeBinary files /dev/null and b/demo/examples/food-donut.webp differdiff --git a/demo/examples/food-gingerbread-house.webp b/demo/examples/food-gingerbread-house.webpnew file mode 100644index 0000000..439f39bBinary files /dev/null and b/demo/examples/food-gingerbread-house.webp differdiff --git a/demo/examples/food-grapes.webp b/demo/examples/food-grapes.webpnew file mode 100644index 0000000..95a3447Binary files /dev/null and b/demo/examples/food-grapes.webp differdiff --git a/demo/examples/food-lollipop.webp b/demo/examples/food-lollipop.webpnew file mode 100644index 0000000..68e264aBinary files /dev/null and b/demo/examples/food-lollipop.webp differdiff --git a/demo/examples/food-macarons.webp b/demo/examples/food-macarons.webpnew file mode 100644index 0000000..359263bBinary files /dev/null and b/demo/examples/food-macarons.webp differdiff --git a/demo/examples/food-mango.webp b/demo/examples/food-mango.webpnew file mode 100644index 0000000..7bbe89dBinary files /dev/null and b/demo/examples/food-mango.webp differdiff --git a/demo/examples/food-mushroom.webp b/demo/examples/food-mushroom.webpnew file mode 100644index 0000000..f4a917eBinary files /dev/null and b/demo/examples/food-mushroom.webp differdiff --git a/demo/examples/food-strawberry.webp b/demo/examples/food-strawberry.webpnew file mode 100644index 0000000..020a8eeBinary files /dev/null and b/demo/examples/food-strawberry.webp differdiff --git a/demo/examples/fur-bar-stool.webp b/demo/examples/fur-bar-stool.webpnew file mode 100644index 0000000..938cdefBinary files /dev/null and b/demo/examples/fur-bar-stool.webp differdiff --git a/demo/examples/fur-barcelona.webp b/demo/examples/fur-barcelona.webpnew file mode 100644index 0000000..cc78ea2Binary files /dev/null and b/demo/examples/fur-barcelona.webp differdiff --git a/demo/examples/fur-bean-bag.webp b/demo/examples/fur-bean-bag.webpnew file mode 100644index 0000000..0a13f77Binary files /dev/null and b/demo/examples/fur-bean-bag.webp differdiff --git a/demo/examples/fur-chair-papasan.webp b/demo/examples/fur-chair-papasan.webpnew file mode 100644index 0000000..d67a2d1Binary files /dev/null and b/demo/examples/fur-chair-papasan.webp differdiff --git a/demo/examples/fur-chair-tulip-red.webp b/demo/examples/fur-chair-tulip-red.webpnew file mode 100644index 0000000..72f59c3Binary files /dev/null and b/demo/examples/fur-chair-tulip-red.webp differdiff --git a/demo/examples/fur-chaise.webp b/demo/examples/fur-chaise.webpnew file mode 100644index 0000000..01cc7e9Binary files /dev/null and b/demo/examples/fur-chaise.webp differdiff --git a/demo/examples/fur-chesterfield.webp b/demo/examples/fur-chesterfield.webpnew file mode 100644index 0000000..734c511Binary files /dev/null and b/demo/examples/fur-chesterfield.webp differdiff --git a/demo/examples/fur-daybed.webp b/demo/examples/fur-daybed.webpnew file mode 100644index 0000000..ad26f1aBinary files /dev/null and b/demo/examples/fur-daybed.webp differdiff --git a/demo/examples/fur-desk-chair-vintage.webp b/demo/examples/fur-desk-chair-vintage.webpnew file mode 100644index 0000000..fd5cf22Binary files /dev/null and b/demo/examples/fur-desk-chair-vintage.webp differdiff --git a/demo/examples/fur-desk-writing.webp b/demo/examples/fur-desk-writing.webpnew file mode 100644index 0000000..5077018Binary files /dev/null and b/demo/examples/fur-desk-writing.webp differdiff --git a/demo/examples/fur-dresser-memphis.webp b/demo/examples/fur-dresser-memphis.webpnew file mode 100644index 0000000..3bb61d4Binary files /dev/null and b/demo/examples/fur-dresser-memphis.webp differdiff --git a/demo/examples/fur-egg-chair.webp b/demo/examples/fur-egg-chair.webpnew file mode 100644index 0000000..f806508Binary files /dev/null and b/demo/examples/fur-egg-chair.webp differdiff --git a/demo/examples/fur-gaming-chair.webp b/demo/examples/fur-gaming-chair.webpnew file mode 100644index 0000000..a1a0083Binary files /dev/null and b/demo/examples/fur-gaming-chair.webp differdiff --git a/demo/examples/fur-globe-bar.webp b/demo/examples/fur-globe-bar.webpnew file mode 100644index 0000000..b586e29Binary files /dev/null and b/demo/examples/fur-globe-bar.webp differdiff --git a/demo/examples/fur-lounge-velvet-green.webp b/demo/examples/fur-lounge-velvet-green.webpnew file mode 100644index 0000000..93e77caBinary files /dev/null and b/demo/examples/fur-lounge-velvet-green.webp differdiff --git a/demo/examples/fur-loveseat-leather.webp b/demo/examples/fur-loveseat-leather.webpnew file mode 100644index 0000000..a6a6e4bBinary files /dev/null and b/demo/examples/fur-loveseat-leather.webp differdiff --git a/demo/examples/fur-trunk-steamer.webp b/demo/examples/fur-trunk-steamer.webpnew file mode 100644index 0000000..66242b3Binary files /dev/null and b/demo/examples/fur-trunk-steamer.webp differdiff --git a/demo/examples/fur-vanity.webp b/demo/examples/fur-vanity.webpnew file mode 100644index 0000000..a307db4Binary files /dev/null and b/demo/examples/fur-vanity.webp differdiff --git a/demo/examples/fur-velvet-armchair-emerald.webp b/demo/examples/fur-velvet-armchair-emerald.webpnew file mode 100644index 0000000..9709c2cBinary files /dev/null and b/demo/examples/fur-velvet-armchair-emerald.webp differdiff --git a/demo/examples/fur-wingback.webp b/demo/examples/fur-wingback.webpnew file mode 100644index 0000000..04d307bBinary files /dev/null and b/demo/examples/fur-wingback.webp differdiff --git a/demo/examples/iris-robot-duck.webp b/demo/examples/iris-robot-duck.webpnew file mode 100644index 0000000..e0522e0Binary files /dev/null and b/demo/examples/iris-robot-duck.webp differdiff --git a/demo/examples/iris-scooter.webp b/demo/examples/iris-scooter.webpnew file mode 100644index 0000000..2654cbaBinary files /dev/null and b/demo/examples/iris-scooter.webp differdiff --git a/demo/examples/logo-award.webp b/demo/examples/logo-award.webpnew file mode 100644index 0000000..106233fBinary files /dev/null and b/demo/examples/logo-award.webp differdiff --git a/demo/examples/logo-chess.webp b/demo/examples/logo-chess.webpnew file mode 100644index 0000000..fa9b1e3Binary files /dev/null and b/demo/examples/logo-chess.webp differdiff --git a/demo/examples/logo-gold-trophy.webp b/demo/examples/logo-gold-trophy.webpnew file mode 100644index 0000000..e8d4858Binary files /dev/null and b/demo/examples/logo-gold-trophy.webp differdiff --git a/demo/examples/logo-marble-dark-a.webp b/demo/examples/logo-marble-dark-a.webpnew file mode 100644index 0000000..4dc4082Binary files /dev/null and b/demo/examples/logo-marble-dark-a.webp differdiff --git a/demo/examples/logo-marble.webp b/demo/examples/logo-marble.webpnew file mode 100644index 0000000..92af4a0Binary files /dev/null and b/demo/examples/logo-marble.webp differdiff --git a/demo/examples/logo-pretzel.webp b/demo/examples/logo-pretzel.webpnew file mode 100644index 0000000..6a24b8cBinary files /dev/null and b/demo/examples/logo-pretzel.webp differdiff --git a/demo/examples/nb-armchair.webp b/demo/examples/nb-armchair.webpnew file mode 100644index 0000000..cc0ebe9Binary files /dev/null and b/demo/examples/nb-armchair.webp differdiff --git a/demo/examples/nb-bird-wood.webp b/demo/examples/nb-bird-wood.webpnew file mode 100644index 0000000..e1857c7Binary files /dev/null and b/demo/examples/nb-bird-wood.webp differdiff --git a/demo/examples/nb-boombox.webp b/demo/examples/nb-boombox.webpnew file mode 100644index 0000000..07f2c3eBinary files /dev/null and b/demo/examples/nb-boombox.webp differdiff --git a/demo/examples/nb-castle-iso.webp b/demo/examples/nb-castle-iso.webpnew file mode 100644index 0000000..1aca059Binary files /dev/null and b/demo/examples/nb-castle-iso.webp differdiff --git a/demo/examples/nb-cupcake.webp b/demo/examples/nb-cupcake.webpnew file mode 100644index 0000000..a75ee0cBinary files /dev/null and b/demo/examples/nb-cupcake.webp differdiff --git a/demo/examples/nb-dragon-anime.webp b/demo/examples/nb-dragon-anime.webpnew file mode 100644index 0000000..1c89e77Binary files /dev/null and b/demo/examples/nb-dragon-anime.webp differdiff --git a/demo/examples/nb-house-tiny.webp b/demo/examples/nb-house-tiny.webpnew file mode 100644index 0000000..f746a88Binary files /dev/null and b/demo/examples/nb-house-tiny.webp differdiff --git a/demo/examples/nb-microscope.webp b/demo/examples/nb-microscope.webpnew file mode 100644index 0000000..62dd145Binary files /dev/null and b/demo/examples/nb-microscope.webp differdiff --git a/demo/examples/nb-trophy.webp b/demo/examples/nb-trophy.webpnew file mode 100644index 0000000..943818cBinary files /dev/null and b/demo/examples/nb-trophy.webp differdiff --git a/demo/examples/obj-backpack.webp b/demo/examples/obj-backpack.webpnew file mode 100644index 0000000..86b6d34Binary files /dev/null and b/demo/examples/obj-backpack.webp differdiff --git a/demo/examples/obj-bicycle-helmet.webp b/demo/examples/obj-bicycle-helmet.webpnew file mode 100644index 0000000..79385daBinary files /dev/null and b/demo/examples/obj-bicycle-helmet.webp differdiff --git a/demo/examples/obj-birdhouse.webp b/demo/examples/obj-birdhouse.webpnew file mode 100644index 0000000..859d92eBinary files /dev/null and b/demo/examples/obj-birdhouse.webp differdiff --git a/demo/examples/obj-boot-hiking.webp b/demo/examples/obj-boot-hiking.webpnew file mode 100644index 0000000..79122a5Binary files /dev/null and b/demo/examples/obj-boot-hiking.webp differdiff --git a/demo/examples/obj-dumbbell.webp b/demo/examples/obj-dumbbell.webpnew file mode 100644index 0000000..f2827a5Binary files /dev/null and b/demo/examples/obj-dumbbell.webp differdiff --git a/demo/examples/obj-handbag.webp b/demo/examples/obj-handbag.webpnew file mode 100644index 0000000..b2fe731Binary files /dev/null and b/demo/examples/obj-handbag.webp differdiff --git a/demo/examples/obj-lunchbox.webp b/demo/examples/obj-lunchbox.webpnew file mode 100644index 0000000..7d16006Binary files /dev/null and b/demo/examples/obj-lunchbox.webp differdiff --git a/demo/examples/obj-mailbox.webp b/demo/examples/obj-mailbox.webpnew file mode 100644index 0000000..cbb00e3Binary files /dev/null and b/demo/examples/obj-mailbox.webp differdiff --git a/demo/examples/obj-microscope-brass.webp b/demo/examples/obj-microscope-brass.webpnew file mode 100644index 0000000..4c6449fBinary files /dev/null and b/demo/examples/obj-microscope-brass.webp differdiff --git a/demo/examples/obj-perfume.webp b/demo/examples/obj-perfume.webpnew file mode 100644index 0000000..f9998d1Binary files /dev/null and b/demo/examples/obj-perfume.webp differdiff --git a/demo/examples/obj-polaroid-stack.webp b/demo/examples/obj-polaroid-stack.webpnew file mode 100644index 0000000..f578bf8Binary files /dev/null and b/demo/examples/obj-polaroid-stack.webp differdiff --git a/demo/examples/obj-power-drill.webp b/demo/examples/obj-power-drill.webpnew file mode 100644index 0000000..83e19ebBinary files /dev/null and b/demo/examples/obj-power-drill.webp differdiff --git a/demo/examples/obj-roller-skate.webp b/demo/examples/obj-roller-skate.webpnew file mode 100644index 0000000..26335f1Binary files /dev/null and b/demo/examples/obj-roller-skate.webp differdiff --git a/demo/examples/obj-stand-mixer.webp b/demo/examples/obj-stand-mixer.webpnew file mode 100644index 0000000..8779076Binary files /dev/null and b/demo/examples/obj-stand-mixer.webp differdiff --git a/demo/examples/obj-watering-can.webp b/demo/examples/obj-watering-can.webpnew file mode 100644index 0000000..33bbc55Binary files /dev/null and b/demo/examples/obj-watering-can.webp differdiff --git a/demo/examples/presets.json b/demo/examples/presets.jsonnew file mode 100644index 0000000..0453d04--- /dev/null+++ b/demo/examples/presets.json@@ -0,0 +1,942 @@+[+ {+ "image": "examples/nb-armchair.webp",+ "title": "Armchair",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-zombie.webp",+ "title": "Zombie",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-explorer.webp",+ "title": "Explorer",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-cowboy.webp",+ "title": "Cowboy",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-viking.webp",+ "title": "Viking",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-barista.webp",+ "title": "Barista",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-axolotl.webp",+ "title": "Axolotl",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-bear-hoodie.webp",+ "title": "Bear hoodie",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-dj.webp",+ "title": "Dj",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-ghost.webp",+ "title": "Ghost",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-grandma.webp",+ "title": "Grandma",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-rockstar.webp",+ "title": "Rockstar",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-snowman.webp",+ "title": "Snowman",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-alien.webp",+ "title": "Alien",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-dog-corgi.webp",+ "title": "Dog corgi",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-panda.webp",+ "title": "Panda",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-robot-cute.webp",+ "title": "Robot cute",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-knight.webp",+ "title": "Knight",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-robot-mech.webp",+ "title": "Robot mech",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-football.webp",+ "title": "Football",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fig-fox.webp",+ "title": "Fox",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-wingback.webp",+ "title": "Wingback",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-dresser-memphis.webp",+ "title": "Dresser memphis",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-barcelona.webp",+ "title": "Barcelona",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-bar-stool.webp",+ "title": "Bar stool",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-chair-tulip-red.webp",+ "title": "Chair tulip red",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-chaise.webp",+ "title": "Chaise",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-chesterfield.webp",+ "title": "Chesterfield",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-daybed.webp",+ "title": "Daybed",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-desk-writing.webp",+ "title": "Desk writing",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-egg-chair.webp",+ "title": "Egg chair",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-gaming-chair.webp",+ "title": "Gaming chair",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-lounge-velvet-green.webp",+ "title": "Lounge velvet green",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-loveseat-leather.webp",+ "title": "Loveseat leather",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-velvet-armchair-emerald.webp",+ "title": "Velvet armchair emerald",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-chair-papasan.webp",+ "title": "Chair papasan",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-trunk-steamer.webp",+ "title": "Trunk steamer",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-vanity.webp",+ "title": "Vanity",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-desk-chair-vintage.webp",+ "title": "Desk chair vintage",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-bean-bag.webp",+ "title": "Bean bag",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/fur-globe-bar.webp",+ "title": "Globe bar",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-handbag.webp",+ "title": "Handbag",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-roller-skate.webp",+ "title": "Roller skate",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-backpack.webp",+ "title": "Backpack",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-birdhouse.webp",+ "title": "Birdhouse",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-lunchbox.webp",+ "title": "Lunchbox",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-watering-can.webp",+ "title": "Watering can",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-boot-hiking.webp",+ "title": "Boot hiking",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-microscope-brass.webp",+ "title": "Microscope brass",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-perfume.webp",+ "title": "Perfume",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-polaroid-stack.webp",+ "title": "Polaroid stack",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-power-drill.webp",+ "title": "Power drill",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-stand-mixer.webp",+ "title": "Stand mixer",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-bicycle-helmet.webp",+ "title": "Bicycle helmet",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-mailbox.webp",+ "title": "Mailbox",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/obj-dumbbell.webp",+ "title": "Dumbbell",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/food-cupcake.webp",+ "title": "Cupcake",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/food-lollipop.webp",+ "title": "Lollipop",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/food-macarons.webp",+ "title": "Macarons",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/food-avocado.webp",+ "title": "Avocado",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/food-mango.webp",+ "title": "Mango",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/food-mushroom.webp",+ "title": "Mushroom",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/food-gingerbread-house.webp",+ "title": "Gingerbread house",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/food-bread-loaf.webp",+ "title": "Bread loaf",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/food-donut.webp",+ "title": "Donut",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/food-strawberry.webp",+ "title": "Strawberry",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/food-grapes.webp",+ "title": "Grapes",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/toy-robot-tin.webp",+ "title": "Robot tin",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/toy-armor-helmet.webp",+ "title": "Armor helmet",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/toy-buddha.webp",+ "title": "Buddha",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/toy-castle.webp",+ "title": "Castle",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/toy-submarine.webp",+ "title": "Submarine",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/toy-train.webp",+ "title": "Train",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/toy-chess-king.webp",+ "title": "Chess king",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/nb-trophy.webp",+ "title": "Trophy",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/nb-boombox.webp",+ "title": "Boombox",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/nb-cupcake.webp",+ "title": "Cupcake",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/nb-dragon-anime.webp",+ "title": "Dragon anime",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/nb-microscope.webp",+ "title": "Microscope",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/nb-castle-iso.webp",+ "title": "Castle iso",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/nb-house-tiny.webp",+ "title": "House tiny",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/nb-bird-wood.webp",+ "title": "Bird wood",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/logo-gold-trophy.webp",+ "title": "Gold trophy",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/logo-award.webp",+ "title": "Award",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/logo-chess.webp",+ "title": "Chess",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/logo-marble.webp",+ "title": "Marble",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/logo-marble-dark-a.webp",+ "title": "Marble dark a",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/logo-pretzel.webp",+ "title": "Pretzel",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/x-agent-charm-keychain.webp",+ "title": "Agent charm keychain",+ "mode": "synthetic",+ "seed": 42,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/x-jade-chess-king.webp",+ "title": "Jade chess king",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/x-minesweeper-mine.webp",+ "title": "Minesweeper mine",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/iris-robot-duck.webp",+ "title": "Robot duck",+ "mode": "synthetic",+ "seed": 1,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/iris-scooter.webp",+ "title": "Scooter",+ "mode": "synthetic",+ "seed": 1,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ },+ {+ "image": "examples/scene-garden-a.webp",+ "title": "Garden a",+ "mode": "synthetic",+ "seed": 7,+ "steps": 50,+ "cfg": 3.0,+ "rescale_t": 3.0,+ "num_gaussians": 262144+ }+]diff --git a/demo/examples/scene-garden-a.webp b/demo/examples/scene-garden-a.webpnew file mode 100644index 0000000..1a6772fBinary files /dev/null and b/demo/examples/scene-garden-a.webp differdiff --git a/demo/examples/toy-armor-helmet.webp b/demo/examples/toy-armor-helmet.webpnew file mode 100644index 0000000..6cbdedeBinary files /dev/null and b/demo/examples/toy-armor-helmet.webp differdiff --git a/demo/examples/toy-buddha.webp b/demo/examples/toy-buddha.webpnew file mode 100644index 0000000..05a55e8Binary files /dev/null and b/demo/examples/toy-buddha.webp differdiff --git a/demo/examples/toy-castle.webp b/demo/examples/toy-castle.webpnew file mode 100644index 0000000..277d104Binary files /dev/null and b/demo/examples/toy-castle.webp differdiff --git a/demo/examples/toy-chess-king.webp b/demo/examples/toy-chess-king.webpnew file mode 100644index 0000000..94b14f3Binary files /dev/null and b/demo/examples/toy-chess-king.webp differdiff --git a/demo/examples/toy-robot-tin.webp b/demo/examples/toy-robot-tin.webpnew file mode 100644index 0000000..1f95838Binary files /dev/null and b/demo/examples/toy-robot-tin.webp differdiff --git a/demo/examples/toy-submarine.webp b/demo/examples/toy-submarine.webpnew file mode 100644index 0000000..4804040Binary files /dev/null and b/demo/examples/toy-submarine.webp differdiff --git a/demo/examples/toy-train.webp b/demo/examples/toy-train.webpnew file mode 100644index 0000000..66a574aBinary files /dev/null and b/demo/examples/toy-train.webp differdiff --git a/demo/examples/x-agent-charm-keychain.webp b/demo/examples/x-agent-charm-keychain.webpnew file mode 100644index 0000000..68bf390Binary files /dev/null and b/demo/examples/x-agent-charm-keychain.webp differdiff --git a/demo/examples/x-jade-chess-king.webp b/demo/examples/x-jade-chess-king.webpnew file mode 100644index 0000000..dd114fcBinary files /dev/null and b/demo/examples/x-jade-chess-king.webp differdiff --git a/demo/examples/x-minesweeper-mine.webp b/demo/examples/x-minesweeper-mine.webpnew file mode 100644index 0000000..226294aBinary files /dev/null and b/demo/examples/x-minesweeper-mine.webp differdiff --git a/demo/model.py b/demo/model.pynew file mode 100644index 0000000..070a163--- /dev/null+++ b/demo/model.py@@ -0,0 +1,23 @@+import os+import tempfile+import uuid++from idol import IdolPipeline++MODES = {'Synthetic': 'synthetic', 'Real photo': 'real'}+GAUSSIANS = {'65,536': 65536, '131,072': 131072, '262,144': 262144, '524,288': 524288, '1,048,576': 1048576}+DEFAULTS = {'steps': 50, 'cfg': 3.0, 'rescale_t': 3.0, 'gaussians': '262,144', 'seed': 42}++# Weights load once at import; on ZeroGPU the CUDA placement is deferred to the GPU worker.+# ZeroGPU does not support torch.compile, so the Space samples without the optimized path.+pipeline = IdolPipeline.from_pretrained(os.environ.get('IDOL_WEIGHTS', 'speridlabs/idol'), device='cuda',+ optimize=not os.environ.get('SPACES_ZERO_GPU'))+OUTPUT_DIR = tempfile.mkdtemp(prefix='idol-')+++def generate(image, mode, steps, cfg_strength, rescale_t, seed, num_gaussians):+ output = pipeline(image, mode=mode, seed=seed, steps=steps, cfg_strength=cfg_strength, rescale_t=rescale_t,+ num_gaussians=num_gaussians)+ path = os.path.join(OUTPUT_DIR, f'idol-seed{seed}-{num_gaussians}-{uuid.uuid4().hex[:8]}.ply')+ output.gaussian.save_ply(path)+ return path, output.preprocessed_imagediff --git a/demo/requirements.txt b/demo/requirements.txtnew file mode 100644index 0000000..b380e83--- /dev/null+++ b/demo/requirements.txt@@ -0,0 +1 @@+idol @ git+https://github.com/speridlabs/idol-sdkdiff --git a/idol/__init__.py b/idol/__init__.pynew file mode 100644index 0000000..13b3e7a--- /dev/null+++ b/idol/__init__.py@@ -0,0 +1,4 @@+from .gaussian import Gaussian+from .pipeline import IdolOutput, IdolPipeline++__version__ = '0.1.0'diff --git a/idol/camera.py b/idol/camera.pynew file mode 100644index 0000000..e460297--- /dev/null+++ b/idol/camera.py@@ -0,0 +1,18 @@+import math++import numpy as np+import torch+++def decode_camera(camera_latent: torch.Tensor) -> dict:+ """camera_latent [5] -> yaw and pitch (radians), radius and vertical field of view (degrees)."""+ direction, inverse_distance, half_width = camera_latent[:3].float(), float(camera_latent[3]), float(camera_latent[4])+ norm = float(torch.norm(direction))+ dx, dy, dz = (direction / norm).tolist() if norm > 1e-6 else (0.0, 0.0, 1.0)+ if inverse_distance < 1e-3: # orthographic+ radius = 1000.0+ fov = math.degrees(2 * math.atan(half_width / radius))+ else:+ radius = 1.0 / inverse_distance+ fov = math.degrees(2 * math.atan(half_width * inverse_distance))+ return {'yaw': math.atan2(dx, dy), 'pitch': math.asin(float(np.clip(dz, -1.0, 1.0))), 'radius': radius, 'fov': fov}diff --git a/idol/conditioning.py b/idol/conditioning.pynew file mode 100644index 0000000..be723dd--- /dev/null+++ b/idol/conditioning.py@@ -0,0 +1,91 @@+import torch+import torch.nn.functional as F+from tensordict import TensorDict++IMAGENET_MEAN = (0.485, 0.456, 0.406)+IMAGENET_STD = (0.229, 0.224, 0.225)+DTYPES = {'fp32': torch.float32, 'bf16': torch.bfloat16, 'fp16': torch.float16}+_ACCESSIBLE_REPOS = set()+++class EncoderAccessError(RuntimeError):+ """The Hugging Face account in use cannot download one of the gated image encoders."""+++def require_encoder_access(repos):+ """Stop with an explanation, before anything large is downloaded, when the gated encoder repos are not readable.++ Network problems are not treated as missing access: the encoders may already be in the local cache."""+ import os++ from huggingface_hub import auth_check, get_token+ from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError++ if os.environ.get('HF_HUB_OFFLINE', '0').lower() in ('1', 'true', 'yes'):+ return+ denied = []+ for repo in repos:+ if repo in _ACCESSIBLE_REPOS:+ continue+ try:+ auth_check(repo)+ _ACCESSIBLE_REPOS.add(repo)+ except (GatedRepoError, RepositoryNotFoundError):+ denied.append(repo)+ except Exception:+ pass+ if not denied:+ return+ pages = '\n'.join(f' https://huggingface.co/{repo}' for repo in denied)+ if get_token() is None:+ reason = 'You are not logged in to Hugging Face, and these image encoders are gated:'+ steps = ('1. Accept the terms on each page above with your Hugging Face account.\n'+ '2. Log in: run `hf auth login`, or set the HF_TOKEN environment variable to a token of that account.')+ else:+ reason = 'Your Hugging Face account does not have access yet to these gated image encoders:'+ steps = ('1. Accept the terms on each page above (approval can take a while).\n'+ '2. Make sure the token in use (`hf auth whoami`) belongs to the account that accepted them.')+ raise EncoderAccessError(f'Idol needs two image encoders that are downloaded from Hugging Face.\n{reason}\n'+ f'{pages}\n{steps}')+++class ImageEncoder:+ def __init__(self, dinov3_repo: str, flux2_vae_repo: str,+ dinov3_dtype: str = 'bf16', device: str = 'cuda'):+ from diffusers.models import AutoencoderKLFlux2+ from transformers import AutoModel++ self.device = torch.device(device)+ self.dinov3 = AutoModel.from_pretrained(dinov3_repo, torch_dtype=DTYPES[dinov3_dtype])+ self.dinov3 = self.dinov3.eval().requires_grad_(False).to(self.device)+ self.flux2_vae = AutoencoderKLFlux2.from_pretrained(flux2_vae_repo, subfolder='vae',+ torch_dtype=torch.bfloat16)+ self.flux2_vae = self.flux2_vae.eval().requires_grad_(False).to(self.device)++ def _dinov3_tokens(self, images):+ mean = torch.tensor(IMAGENET_MEAN, device=images.device).view(1, 3, 1, 1)+ std = torch.tensor(IMAGENET_STD, device=images.device).view(1, 3, 1, 1)+ images = (images.float() - mean) / std+ dtype = next(self.dinov3.parameters()).dtype+ tokens = self.dinov3(pixel_values=images.to(dtype)).last_hidden_state.float()+ return F.layer_norm(tokens, tokens.shape[-1:])++ def _flux2_tokens(self, images):+ vae = self.flux2_vae+ latents = vae.encode(images.to(torch.bfloat16) * 2 - 1).latent_dist.sample()+ batch, channels, height, width = latents.shape+ latents = latents.view(batch, channels, height // 2, 2, width // 2, 2).permute(0, 1, 3, 5, 2, 4)+ latents = latents.reshape(batch, channels * 4, height // 2, width // 2)+ mean = vae.bn.running_mean.view(1, -1, 1, 1).to(latents.device, latents.dtype)+ std = torch.sqrt(vae.bn.running_var.view(1, -1, 1, 1) + vae.config.batch_norm_eps).to(latents.device, latents.dtype)+ tokens = ((latents - mean) / std).float().flatten(2).transpose(1, 2).contiguous()+ padding = torch.zeros(batch, 5, tokens.shape[2], dtype=tokens.dtype, device=tokens.device)+ return torch.cat([padding, tokens], dim=1)++ @torch.no_grad()+ def __call__(self, images: torch.Tensor) -> TensorDict:+ """images: [B, 3, 1024, 1024] in [0, 1] -> TensorDict(feature1=DINOv3 tokens, feature2=FLUX.2 VAE tokens)."""+ images = images.to(self.device)+ feature1 = self._dinov3_tokens(images)+ feature2 = self._flux2_tokens(images)+ return TensorDict({'feature1': feature1, 'feature2': feature2}, batch_size=feature1.shape[0])diff --git a/idol/gaussian.py b/idol/gaussian.pynew file mode 100644index 0000000..0fa5708--- /dev/null+++ b/idol/gaussian.py@@ -0,0 +1,70 @@+import numpy as np+import torch+import torch.nn.functional as F+from plyfile import PlyData, PlyElement+++def inverse_sigmoid(x):+ return torch.log(x / (1 - x))+++def inverse_softplus(x):+ return x + torch.log(-torch.expm1(-x))+++class Gaussian:+ """Built from the Gaussian decoder's raw outputs; the activated values are what renderers and PLY files use.++ xyz [N, 3] positions, features_dc [N, 1, 3] colour (degree-0 spherical harmonics), scaling [N, 3],+ rotation [N, 4] unit quaternions (w, x, y, z), opacity [N, 1]. The object is z-up, inside [-0.5, 0.5]^3."""++ def __init__(self, raw_xyz, features_dc, raw_scaling, raw_rotation, raw_opacity,+ scaling_bias: float, opacity_bias: float, minimum_kernel_size: float):+ device = raw_xyz.device+ aabb = torch.tensor([-0.5, -0.5, -0.5, 1.0, 1.0, 1.0], dtype=torch.float32, device=device)+ scaling_offset = inverse_softplus(torch.tensor(scaling_bias)).to(device)+ opacity_offset = inverse_sigmoid(torch.tensor(opacity_bias)).to(device)+ rotation_offset = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device)++ self.xyz = raw_xyz * aabb[None, 3:] + aabb[None, :3]+ self.features_dc = features_dc+ scaling = F.softplus(raw_scaling + scaling_offset)+ self.scaling = torch.sqrt(torch.square(scaling) + minimum_kernel_size ** 2)+ self.rotation = F.normalize(raw_rotation + rotation_offset[None, :])+ self.opacity = torch.sigmoid(raw_opacity + opacity_offset)++ def save_ply(self, path):+ """Write the standard 3D Gaussian Splatting PLY (z-up object turned to the y-up convention viewers use)."""+ xyz = self.xyz.detach().cpu().numpy()+ normals = np.zeros_like(xyz)+ f_dc = self.features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()+ # Clamp before the inverse activations: a saturated opacity (exactly 1.0 after the sigmoid) or a zero+ # scale would otherwise be written as +/-inf, which some PLY viewers reject.+ eps = 1e-6+ opacities = inverse_sigmoid(self.opacity.clamp(eps, 1 - eps)).detach().cpu().numpy()+ scale = torch.log(self.scaling.clamp_min(eps)).detach().cpu().numpy()+ rotation = self.rotation.detach().cpu().numpy()++ # z-up -> y-up: rotate +90 degrees about x, i.e. (x, y, z) -> (x, -z, y)+ xyz = np.stack([xyz[:, 0], -xyz[:, 2], xyz[:, 1]], axis=1)+ rotation = quaternion_multiply(np.array([np.sqrt(0.5), np.sqrt(0.5), 0.0, 0.0]), rotation)++ attributes = np.concatenate((xyz, normals, f_dc, opacities, scale, rotation), axis=1).astype(np.float32)+ names = ['x', 'y', 'z', 'nx', 'ny', 'nz', 'f_dc_0', 'f_dc_1', 'f_dc_2', 'opacity',+ 'scale_0', 'scale_1', 'scale_2', 'rot_0', 'rot_1', 'rot_2', 'rot_3']+ elements = np.empty(attributes.shape[0], dtype=[(name, 'f4') for name in names])+ for column, name in enumerate(names):+ elements[name] = attributes[:, column]+ PlyData([PlyElement.describe(elements, 'vertex')]).write(path)+++def quaternion_multiply(a, b):+ """Hamilton product a * b of (w, x, y, z) quaternions; a is one quaternion, b is (N, 4)."""+ aw, ax, ay, az = a+ bw, bx, by, bz = b[:, 0], b[:, 1], b[:, 2], b[:, 3]+ return np.stack([+ aw * bw - ax * bx - ay * by - az * bz,+ aw * bx + ax * bw + ay * bz - az * by,+ aw * by - ax * bz + ay * bw + az * bx,+ aw * bz + ax * by - ay * bx + az * bw,+ ], axis=1)diff --git a/idol/models/__init__.py b/idol/models/__init__.pynew file mode 100644index 0000000..f1f05e2--- /dev/null+++ b/idol/models/__init__.py@@ -0,0 +1,3 @@+from .birefnet import BiRefNet+from .decoder import GaussianFixedlenDecoder, OctreeProbabilityFixedlenDecoder+from .dit import LatentSeqMMFlowModeldiff --git a/idol/models/birefnet.py b/idol/models/birefnet.pynew file mode 100644index 0000000..983a93c--- /dev/null+++ b/idol/models/birefnet.py@@ -0,0 +1,491 @@+import math++import numpy as np+import torch+import torch.nn as nn+import torch.nn.functional as F+from torchvision.ops import deform_conv2d+++# -- Swin Transformer (Swin-Large preset) -------------------------------------++class _SwinMlp(nn.Module):+ def __init__(self, in_features, hidden_features=None, out_features=None):+ super().__init__()+ hidden_features = hidden_features or in_features+ out_features = out_features or in_features+ self.fc1 = nn.Linear(in_features, hidden_features)+ self.act = nn.GELU()+ self.fc2 = nn.Linear(hidden_features, out_features)++ def forward(self, x):+ return self.fc2(self.act(self.fc1(x)))+++def _window_partition(x, window_size):+ B, H, W, C = x.shape+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)+ return x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)+++def _window_reverse(windows, window_size, H, W):+ B = int(windows.shape[0] / (H * W / window_size / window_size))+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)+ return x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)+++class _WindowAttention(nn.Module):+ def __init__(self, dim, window_size, num_heads):+ super().__init__()+ self.dim = dim+ self.window_size = window_size+ self.num_heads = num_heads+ head_dim = dim // num_heads+ self.scale = head_dim ** -0.5++ self.relative_position_bias_table = nn.Parameter(+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads))+ coords_h = torch.arange(window_size[0])+ coords_w = torch.arange(window_size[1])+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing="ij"))+ coords_flatten = torch.flatten(coords, 1)+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]+ relative_coords = relative_coords.permute(1, 2, 0).contiguous()+ relative_coords[:, :, 0] += window_size[0] - 1+ relative_coords[:, :, 1] += window_size[1] - 1+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1+ self.register_buffer("relative_position_index", relative_coords.sum(-1))++ self.qkv = nn.Linear(dim, dim * 3, bias=True)+ self.proj = nn.Linear(dim, dim)++ def forward(self, x, mask=None):+ B_, N, C = x.shape+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)+ q, k, v = qkv[0], qkv[1], qkv[2]+ q = q * self.scale+ attn = q @ k.transpose(-2, -1)+ bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(+ self.window_size[0] * self.window_size[1],+ self.window_size[0] * self.window_size[1], -1)+ attn = attn + bias.permute(2, 0, 1).contiguous().unsqueeze(0)+ if mask is not None:+ nW = mask.shape[0]+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)+ attn = attn.view(-1, self.num_heads, N, N)+ attn = attn.softmax(dim=-1)+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)+ return self.proj(x)+++class _SwinBlock(nn.Module):+ def __init__(self, dim, num_heads, window_size, shift_size, mlp_ratio=4.0):+ super().__init__()+ self.dim = dim+ self.window_size = window_size+ self.shift_size = shift_size+ self.norm1 = nn.LayerNorm(dim)+ self.attn = _WindowAttention(dim, (window_size, window_size), num_heads)+ self.norm2 = nn.LayerNorm(dim)+ self.mlp = _SwinMlp(dim, int(dim * mlp_ratio))+ self.H = None+ self.W = None++ def forward(self, x, mask_matrix):+ B, L, C = x.shape+ H, W = self.H, self.W+ shortcut = x+ x = self.norm1(x).view(B, H, W, C)+ pad_r = (self.window_size - W % self.window_size) % self.window_size+ pad_b = (self.window_size - H % self.window_size) % self.window_size+ x = F.pad(x, (0, 0, 0, pad_r, 0, pad_b))+ _, Hp, Wp, _ = x.shape+ if self.shift_size > 0:+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))+ attn_mask = mask_matrix+ else:+ shifted_x = x+ attn_mask = None+ x_windows = _window_partition(shifted_x, self.window_size).view(+ -1, self.window_size * self.window_size, C)+ attn_windows = self.attn(x_windows, mask=attn_mask).view(+ -1, self.window_size, self.window_size, C)+ shifted_x = _window_reverse(attn_windows, self.window_size, Hp, Wp)+ if self.shift_size > 0:+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))+ else:+ x = shifted_x+ if pad_r > 0 or pad_b > 0:+ x = x[:, :H, :W, :].contiguous()+ x = x.view(B, H * W, C)+ x = shortcut + x+ x = x + self.mlp(self.norm2(x))+ return x+++class _PatchMerging(nn.Module):+ def __init__(self, dim):+ super().__init__()+ self.dim = dim+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)+ self.norm = nn.LayerNorm(4 * dim)++ def forward(self, x, H, W):+ B, L, C = x.shape+ x = x.view(B, H, W, C)+ x0 = x[:, 0::2, 0::2, :]+ x1 = x[:, 1::2, 0::2, :]+ x2 = x[:, 0::2, 1::2, :]+ x3 = x[:, 1::2, 1::2, :]+ x = torch.cat([x0, x1, x2, x3], -1).view(B, -1, 4 * C)+ return self.reduction(self.norm(x))+++class _SwinBasicLayer(nn.Module):+ def __init__(self, dim, depth, num_heads, window_size, mlp_ratio=4.0, downsample=True):+ super().__init__()+ self.window_size = window_size+ self.shift_size = window_size // 2+ self.depth = depth+ self.blocks = nn.ModuleList([+ _SwinBlock(dim=dim, num_heads=num_heads, window_size=window_size,+ shift_size=0 if (i % 2 == 0) else window_size // 2,+ mlp_ratio=mlp_ratio)+ for i in range(depth)+ ])+ self.downsample = _PatchMerging(dim) if downsample else None++ def forward(self, x, H, W):+ Hp = int(math.ceil(H / self.window_size)) * self.window_size+ Wp = int(math.ceil(W / self.window_size)) * self.window_size+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device)+ h_slices = (slice(0, -self.window_size),+ slice(-self.window_size, -self.shift_size),+ slice(-self.shift_size, None))+ w_slices = (slice(0, -self.window_size),+ slice(-self.window_size, -self.shift_size),+ slice(-self.shift_size, None))+ cnt = 0+ for h in h_slices:+ for w in w_slices:+ img_mask[:, h, w, :] = cnt+ cnt += 1+ mask_windows = _window_partition(img_mask, self.window_size).view(-1, self.window_size ** 2)+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)) \+ .masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)+ for blk in self.blocks:+ blk.H, blk.W = H, W+ x = blk(x, attn_mask)+ if self.downsample is not None:+ x_down = self.downsample(x, H, W)+ Wh, Ww = (H + 1) // 2, (W + 1) // 2+ return x, H, W, x_down, Wh, Ww+ return x, H, W, x, H, W+++class _SwinPatchEmbed(nn.Module):+ def __init__(self, patch_size=4, in_channels=3, embed_dim=192):+ super().__init__()+ self.patch_size = (patch_size, patch_size)+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)+ self.norm = nn.LayerNorm(embed_dim)+ self.embed_dim = embed_dim++ def forward(self, x):+ x = self.proj(x)+ Wh, Ww = x.size(2), x.size(3)+ x = x.flatten(2).transpose(1, 2)+ x = self.norm(x)+ return x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)+++class _SwinLarge(nn.Module):+ def __init__(self):+ super().__init__()+ embed_dim = 192+ depths = [2, 2, 18, 2]+ num_heads = [6, 12, 24, 48]+ window_size = 12+ self.num_layers = len(depths)+ self.embed_dim = embed_dim+ self.patch_embed = _SwinPatchEmbed(patch_size=4, in_channels=3, embed_dim=embed_dim)+ self.layers = nn.ModuleList([+ _SwinBasicLayer(+ dim=int(embed_dim * 2 ** i),+ depth=depths[i],+ num_heads=num_heads[i],+ window_size=window_size,+ downsample=(i < self.num_layers - 1),+ ) for i in range(self.num_layers)+ ])+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]+ self.num_features = num_features+ for i in range(self.num_layers):+ self.add_module(f"norm{i}", nn.LayerNorm(num_features[i]))++ def forward(self, x):+ x = self.patch_embed(x)+ Wh, Ww = x.size(2), x.size(3)+ x = x.flatten(2).transpose(1, 2)+ outs = []+ for i in range(self.num_layers):+ x_out, H, W, x, Wh, Ww = self.layers[i](x, Wh, Ww)+ norm_layer = getattr(self, f"norm{i}")+ x_out = norm_layer(x_out)+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()+ outs.append(out)+ return tuple(outs)+++# -- ASPP-Deformable -----------------------------------------------------------++class _DeformableConv2d(nn.Module):+ def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False):+ super().__init__()+ if isinstance(kernel_size, int):+ kernel_size = (kernel_size, kernel_size)+ self.stride = (stride, stride) if isinstance(stride, int) else stride+ self.padding = padding+ self.offset_conv = nn.Conv2d(in_channels, 2 * kernel_size[0] * kernel_size[1],+ kernel_size=kernel_size, stride=stride, padding=padding, bias=True)+ self.modulator_conv = nn.Conv2d(in_channels, 1 * kernel_size[0] * kernel_size[1],+ kernel_size=kernel_size, stride=stride, padding=padding, bias=True)+ self.regular_conv = nn.Conv2d(in_channels, out_channels,+ kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)++ def forward(self, x):+ offset = self.offset_conv(x)+ modulator = 2.0 * torch.sigmoid(self.modulator_conv(x))+ return deform_conv2d(+ input=x, offset=offset,+ weight=self.regular_conv.weight, bias=self.regular_conv.bias,+ padding=self.padding, mask=modulator, stride=self.stride,+ )+++class _ASPPModuleDeformable(nn.Module):+ def __init__(self, in_channels, planes, kernel_size, padding):+ super().__init__()+ self.atrous_conv = _DeformableConv2d(in_channels, planes, kernel_size=kernel_size,+ stride=1, padding=padding, bias=False)+ self.bn = nn.BatchNorm2d(planes)+ self.relu = nn.ReLU(inplace=True)++ def forward(self, x):+ return self.relu(self.bn(self.atrous_conv(x)))+++class _ASPPDeformable(nn.Module):+ def __init__(self, in_channels, out_channels=None, parallel_block_sizes=(1, 3, 7)):+ super().__init__()+ if out_channels is None:+ out_channels = in_channels+ inter = 256+ self.aspp1 = _ASPPModuleDeformable(in_channels, inter, 1, padding=0)+ self.aspp_deforms = nn.ModuleList([+ _ASPPModuleDeformable(in_channels, inter, k, padding=k // 2)+ for k in parallel_block_sizes+ ])+ self.global_avg_pool = nn.Sequential(+ nn.AdaptiveAvgPool2d((1, 1)),+ nn.Conv2d(in_channels, inter, 1, stride=1, bias=False),+ nn.BatchNorm2d(inter),+ nn.ReLU(inplace=True),+ )+ self.conv1 = nn.Conv2d(inter * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False)+ self.bn1 = nn.BatchNorm2d(out_channels)+ self.relu = nn.ReLU(inplace=True)++ def forward(self, x):+ x1 = self.aspp1(x)+ x_aspp_deforms = [m(x) for m in self.aspp_deforms]+ x5 = self.global_avg_pool(x)+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)+ y = torch.cat((x1, *x_aspp_deforms, x5), dim=1)+ return self.relu(self.bn1(self.conv1(y)))+++# -- Decoder blocks ------------------------------------------------------------++class _BasicDecBlk(nn.Module):+ def __init__(self, in_channels, out_channels, inter_channels=64):+ super().__init__()+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)+ self.bn_in = nn.BatchNorm2d(inter_channels)+ self.relu_in = nn.ReLU(inplace=True)+ self.dec_att = _ASPPDeformable(in_channels=inter_channels)+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)+ self.bn_out = nn.BatchNorm2d(out_channels)++ def forward(self, x):+ x = self.relu_in(self.bn_in(self.conv_in(x)))+ x = self.dec_att(x)+ x = self.bn_out(self.conv_out(x))+ return x+++class _BasicLatBlk(nn.Module):+ def __init__(self, in_channels, out_channels):+ super().__init__()+ self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)++ def forward(self, x):+ return self.conv(x)+++class _SimpleConvs(nn.Module):+ def __init__(self, in_channels, out_channels, inter_channels=64):+ super().__init__()+ self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)++ def forward(self, x):+ return self.conv_out(self.conv1(x))+++# -- Image → patch-stack helper -----------------------------------------------++def _image2patches(image, patch_ref):+ """einops 'b c (hg h) (wg w) -> b (c hg wg) h w' without einops."""+ b, c, h_full, w_full = image.shape+ hg, wg = h_full // patch_ref.shape[-2], w_full // patch_ref.shape[-1]+ h, w = h_full // hg, w_full // wg+ # (b, c, hg*h, wg*w) -> (b, c, hg, h, wg, w) -> (b, c, hg, wg, h, w) -> (b, c*hg*wg, h, w)+ return image.view(b, c, hg, h, wg, w).permute(0, 1, 2, 4, 3, 5).reshape(b, c * hg * wg, h, w)+++# -- Decoder + top-level BiRefNet ---------------------------------------------++class _BiRefNetDecoder(nn.Module):+ def __init__(self, channels=(3072, 1536, 768, 384)):+ super().__init__()+ c = channels+ self.ipt_blk5 = _SimpleConvs(2 ** 10 * 3, c[0] // 8, inter_channels=64)+ self.ipt_blk4 = _SimpleConvs(2 ** 8 * 3, c[0] // 8, inter_channels=64)+ self.ipt_blk3 = _SimpleConvs(2 ** 6 * 3, c[1] // 8, inter_channels=64)+ self.ipt_blk2 = _SimpleConvs(2 ** 4 * 3, c[2] // 8, inter_channels=64)+ self.ipt_blk1 = _SimpleConvs(2 ** 0 * 3, c[3] // 8, inter_channels=64)++ self.decoder_block4 = _BasicDecBlk(c[0] + c[0] // 8, c[1])+ self.decoder_block3 = _BasicDecBlk(c[1] + c[0] // 8, c[2])+ self.decoder_block2 = _BasicDecBlk(c[2] + c[1] // 8, c[3])+ self.decoder_block1 = _BasicDecBlk(c[3] + c[2] // 8, c[3] // 2)+ self.conv_out1 = nn.Sequential(nn.Conv2d(c[3] // 2 + c[3] // 8, 1, 1, 1, 0))++ self.lateral_block4 = _BasicLatBlk(c[1], c[1])+ self.lateral_block3 = _BasicLatBlk(c[2], c[2])+ self.lateral_block2 = _BasicLatBlk(c[3], c[3])++ # gradient-decoder-triggering (gdt) attention: used at inference to+ # gate p4/p3/p2.+ _N = 16+ def _gdt_branch(in_c):+ return nn.Sequential(nn.Conv2d(in_c, _N, 3, 1, 1), nn.BatchNorm2d(_N), nn.ReLU(inplace=True))+ self.gdt_convs_4 = _gdt_branch(c[1])+ self.gdt_convs_3 = _gdt_branch(c[2])+ self.gdt_convs_2 = _gdt_branch(c[3])++ def _head_1x1():+ return nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))+ self.gdt_convs_attn_4 = _head_1x1()+ self.gdt_convs_attn_3 = _head_1x1()+ self.gdt_convs_attn_2 = _head_1x1()++ def forward(self, x, x1, x2, x3, x4):+ x4 = torch.cat((x4, self.ipt_blk5(_image2patches(x, x4))), 1)+ p4 = self.decoder_block4(x4)+ p4 = p4 * self.gdt_convs_attn_4(self.gdt_convs_4(p4)).sigmoid()+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)+ _p3 = _p4 + self.lateral_block4(x3)++ _p3 = torch.cat((_p3, self.ipt_blk4(_image2patches(x, _p3))), 1)+ p3 = self.decoder_block3(_p3)+ p3 = p3 * self.gdt_convs_attn_3(self.gdt_convs_3(p3)).sigmoid()+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)+ _p2 = _p3 + self.lateral_block3(x2)++ _p2 = torch.cat((_p2, self.ipt_blk3(_image2patches(x, _p2))), 1)+ p2 = self.decoder_block2(_p2)+ p2 = p2 * self.gdt_convs_attn_2(self.gdt_convs_2(p2)).sigmoid()+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)+ _p1 = _p2 + self.lateral_block2(x1)++ _p1 = torch.cat((_p1, self.ipt_blk2(_image2patches(x, _p1))), 1)+ _p1 = self.decoder_block1(_p1)+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)++ _p1 = torch.cat((_p1, self.ipt_blk1(_image2patches(x, _p1))), 1)+ return self.conv_out1(_p1)+++class BiRefNet(nn.Module):+ """BiRefNet (ZhengPeng7/BiRefNet) with the Swin-L backbone: forward(x) returns the alpha map in [0, 1],+ remove_background(image) returns the RGBA PIL image."""++ INPUT_SIZE = (1024, 1024)+ # backbone channel counts post mul_scl_ipt='cat' (doubled from raw Swin-L)+ _CHANNELS = (3072, 1536, 768, 384)+ _NORM_MEAN = (0.485, 0.456, 0.406)+ _NORM_STD = (0.229, 0.224, 0.225)++ def __init__(self):+ super().__init__()+ self.bb = _SwinLarge()+ cxt = list(self._CHANNELS[1:][::-1][-3:]) # = [384, 768, 1536]+ self.squeeze_module = nn.Sequential(+ _BasicDecBlk(self._CHANNELS[0] + sum(cxt), self._CHANNELS[0])+ )+ self.decoder = _BiRefNetDecoder(channels=self._CHANNELS)++ @property+ def device(self):+ return next(self.parameters()).device++ @property+ def dtype(self):+ return next(self.parameters()).dtype++ def _forward_enc(self, x):+ x1, x2, x3, x4 = self.bb(x)+ # mul_scl_ipt='cat': re-run backbone at half resolution, concat features+ B, C, H, W = x.shape+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H // 2, W // 2),+ mode='bilinear', align_corners=True))+ x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], 1)+ x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], 1)+ x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], 1)+ x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], 1)+ # cxt: upsample x1/x2/x3 to x4 spatial and concat for the squeeze input+ x4 = torch.cat([+ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True),+ F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True),+ F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True),+ x4,+ ], 1)+ return x1, x2, x3, x4++ def forward(self, x):+ x1, x2, x3, x4 = self._forward_enc(x)+ x4 = self.squeeze_module(x4)+ logits = self.decoder(x, x1, x2, x3, x4)+ return torch.sigmoid(logits)++ @torch.no_grad()+ def remove_background(self, image) -> "Image.Image":+ from PIL import Image+ W, H = image.size+ arr = np.array(image, dtype=np.float32) / 255.0+ t = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0)+ t = F.interpolate(t, size=self.INPUT_SIZE, mode='bilinear', align_corners=True)+ mean = torch.tensor(self._NORM_MEAN).view(1, 3, 1, 1)+ std = torch.tensor(self._NORM_STD).view(1, 3, 1, 1)+ t = ((t - mean) / std).to(device=self.device, dtype=self.dtype)+ alpha = self.forward(t)+ alpha = F.interpolate(alpha.float(), size=(H, W), mode='bilinear', align_corners=True)[0, 0]+ a = (alpha.clamp(0, 1) * 255).to(torch.uint8).cpu().numpy()+ rgba = image.copy()+ rgba.putalpha(Image.fromarray(a, mode="L"))+ return rgba++diff --git a/idol/models/decoder.py b/idol/models/decoder.pynew file mode 100644index 0000000..b1323dd--- /dev/null+++ b/idol/models/decoder.py@@ -0,0 +1,186 @@+from typing import List++import torch+import torch.nn as nn+import torch.nn.functional as F++from ..gaussian import Gaussian+from .layers import (ModulatedTransformerCrossOnlyBlock, PcdAbsolutePositionEmbedderv2, SinusoidalEmbedder,+ TransformerCrossBlock, convert_module_to_f16)+++class OctreeProbabilityFixedlenDecoder(nn.Module):+ def __init__(self, model_channels: int, cond_channels: int, num_blocks: int, num_heads: int,+ mlp_ratio: float = 4.0):+ super().__init__()+ self.dtype = torch.float16+ self.in_proj = nn.Linear(3, model_channels)+ self.pos_embedder = PcdAbsolutePositionEmbedderv2(channels=model_channels, in_channels=3)+ self.input_layer = nn.Linear(model_channels, model_channels)+ self.l_embedder = SinusoidalEmbedder(model_channels, max_period=1024, two_pi=True)+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(model_channels, 6 * model_channels, bias=True))+ self.blocks = nn.ModuleList([+ ModulatedTransformerCrossOnlyBlock(model_channels, ctx_channels=cond_channels, num_heads=num_heads,+ mlp_ratio=mlp_ratio)+ for _ in range(num_blocks)+ ])+ self.out_proj = nn.Linear(model_channels, 2 ** 3)+ self.blocks.apply(convert_module_to_f16)++ def forward(self, x: torch.Tensor, level: torch.Tensor, cond: torch.Tensor) -> torch.Tensor:+ """x: cell centres [B, L, 3] in [0, 1]; level: the cells' octree resolution [B]; cond: latent [B, Lc, C].+ Returns the logits [B, L, 8] of how each cell's points split among its 8 children."""+ B, L, _ = x.shape+ h = self.in_proj(x) + self.pos_embedder(x.view(-1, 3)).view(B, L, -1)+ h = self.input_layer(h)+ level_emb = self.adaLN_modulation(self.l_embedder(level.type(h.dtype))).type(self.dtype)+ out = h.type(self.dtype)+ context = cond.type(self.dtype)+ for block in self.blocks:+ out = block(out, level_emb, context)+ out = out.type(h.dtype).type(cond.dtype)+ return self.out_proj(F.layer_norm(out, out.shape[-1:]))++ @staticmethod+ @torch.no_grad()+ def sample(model, cond: torch.Tensor, num_points: int, level: int) -> torch.Tensor:+ """Place num_points anchor points [B, num_points, 3] in [0, 1]^3, descending the octree to ``level``."""+ B = cond.shape[0]+ device = cond.device+ child_offset = torch.tensor([[i, j, k] for k in [0, 1] for j in [0, 1] for i in [0, 1]], dtype=torch.long,+ device=device)+ prev_coords_int = torch.zeros(B, 1, 3, dtype=torch.long, device=device)+ prev_counts = torch.full((B, 1), num_points, dtype=torch.long, device=device)+ batch_indices_range = torch.arange(B, device=device).unsqueeze(1)++ for l in range(1, level + 1):+ res_p = 1 << (l - 1)+ parent_coords_norm = (prev_coords_int.to(torch.float32) + 0.5) / res_p+ res_tensor = torch.full((B,), 1 << l, dtype=torch.long, device=device)+ pred_probs = torch.softmax(model(parent_coords_norm, res_tensor, cond), dim=-1) # [B, Np, 8]+ sampled = systematic_sample(pred_probs, prev_counts).flatten(1, 2) # [B, Np*8]+ child_coords_int = (prev_coords_int[:, :, None, :] * 2 + child_offset[None, None, :, :]).flatten(1, 2)++ # keep the children that received points, packed to the front+ mask = sampled > 0+ max_valid = mask.sum(dim=1).max().item()+ valid_scatter_indices = (mask.cumsum(dim=1) - 1)[mask]+ valid_batch_indices = batch_indices_range.expand_as(mask)[mask]+ prev_coords_int = torch.zeros(B, max_valid, 3, dtype=child_coords_int.dtype, device=device)+ prev_coords_int[valid_batch_indices, valid_scatter_indices] = child_coords_int[mask]+ prev_counts = torch.zeros(B, max_valid, dtype=sampled.dtype, device=device)+ prev_counts[valid_batch_indices, valid_scatter_indices] = sampled[mask]++ # each point lands at a uniformly random position inside its leaf cell+ coords_int = torch.repeat_interleave(prev_coords_int.flatten(0, 1), prev_counts.flatten(0, 1),+ dim=0).reshape(B, num_points, -1)+ return (coords_int.to(torch.float32) + torch.rand_like(coords_int, dtype=torch.float32)) / (1 << level)++[email protected]_grad()+def systematic_sample(probs: torch.Tensor, counts: torch.Tensor) -> torch.Tensor:+ """Split counts[...] items among the P bins of probs[..., P] by systematic resampling -> [..., P] counts."""+ batch_shape = counts.shape+ B = counts.numel()+ P = probs.size(-1)+ device = probs.device+ probs = probs.view(B, P)+ counts = counts.view(B)++ # normalise, with a uniform fallback for zero-sum rows+ probs = probs.to(torch.float32).clamp_min_(0)+ row_sums = probs.sum(1, keepdim=True)+ zero_mask = row_sums.eq(0)+ probs = probs / row_sums.clamp_min_(1)+ if zero_mask.any():+ probs = probs.clone()+ probs[zero_mask.expand_as(probs)] = 1.0 / P++ counts = counts.to(device=device, dtype=torch.long)+ out = torch.zeros(B, P, dtype=torch.long, device=device)+ cdf = probs.cumsum(dim=1).clamp(max=1.0 - 1e-12)+ unique_n, inv = counts.unique(sorted=False, return_inverse=True)+ for index, n in enumerate(unique_n.tolist()):+ if n == 0:+ continue+ rows = (inv == index).nonzero(as_tuple=False).squeeze(1)+ r = rows.numel()+ u0 = torch.rand(r, 1, device=device) / float(n) # random offset in [0, 1/n)+ grid = torch.arange(n, device=device, dtype=torch.float32)[None, :] / float(n) # stratified points+ us = (u0 + grid).clamp(max=1.0 - 1e-12)+ idx = torch.searchsorted(cdf.index_select(0, rows), us).clamp_max(P - 1)+ buf = torch.zeros(r, P, dtype=torch.float32, device=device)+ buf.scatter_add_(1, idx, torch.ones_like(idx, dtype=buf.dtype))+ out.index_copy_(0, rows, buf.to(torch.long))+ return out.view(*batch_shape, P)+++class GaussianFixedlenDecoder(nn.Module):+ def __init__(self, in_channels: int, model_channels: int, cond_channels: int, num_blocks: int, num_heads: int,+ representation_config: dict, mlp_ratio: float = 4.0):+ super().__init__()+ self.dtype = torch.float16+ self.rep_config = representation_config+ per_anchor = representation_config['num_gaussians']+ # output channels per anchor: offset (3), colour (3), scale (3), rotation (4), opacity (1), offset scale (1)+ self.layout = {+ '_xyz': (3,),+ '_features_dc': (1, 3),+ '_scaling': (3,),+ '_rotation': (4,),+ '_opacity': (1,),+ '_offset_scale': (1,),+ }+ start = 0+ self.ranges = {}+ for name, shape in self.layout.items():+ size = per_anchor * int(torch.tensor(shape).prod())+ self.ranges[name] = (start, start + size)+ start += size++ self.in_proj = nn.Linear(in_channels, model_channels)+ self.pos_embedder = PcdAbsolutePositionEmbedderv2(channels=model_channels, in_channels=3)+ self.input_layer = nn.Linear(model_channels, model_channels)+ self.blocks = nn.ModuleList([+ TransformerCrossBlock(model_channels, ctx_channels=cond_channels, num_heads=num_heads, mlp_ratio=mlp_ratio)+ for _ in range(num_blocks)+ ])+ self.out_proj = nn.Linear(model_channels, start)+ # fixed per-Gaussian offset pattern and the base offset scale, stored with the weights+ self.register_buffer('points_offset_perturbation', torch.zeros(per_anchor, 3))+ self.register_buffer('base_offset_scale', torch.zeros(()))+ self.blocks.apply(convert_module_to_f16)++ def forward(self, points: torch.Tensor, cond: torch.Tensor) -> torch.Tensor:+ """points: anchors [B, L, 3]; cond: latent [B, Lc, C] -> per-anchor outputs [B, L, 32 x 15]"""+ B, L, C = points.shape+ h = self.in_proj(points) + self.pos_embedder(points.view(-1, C)).view(B, L, -1)+ h = self.input_layer(h)+ out = h.type(self.dtype)+ context = cond.type(self.dtype)+ for block in self.blocks:+ out = block(out, context)+ out = out.type(h.dtype).type(cond.dtype)+ return self.out_proj(F.layer_norm(out, out.shape[-1:]))++ def _slice(self, features, name):+ start, end = self.ranges[name]+ return features[:, :, start:end].reshape(features.shape[0], -1, self.rep_config['num_gaussians'],+ *self.layout[name])++ def to_representation(self, points: torch.Tensor, features: torch.Tensor) -> List[Gaussian]:+ config = self.rep_config+ offset_scale = F.softplus(self._slice(features, '_offset_scale') + self.base_offset_scale)+ offset = self._slice(features, '_xyz') * config['lr']['_xyz'] + self.points_offset_perturbation+ offset = torch.tanh(offset) * 0.5 * config['perturbe_size'] * offset_scale++ objects = []+ for i in range(features.shape[0]):+ raw = {name: (self._slice(features[i:i + 1], name)[0].flatten(0, 1) * config['lr'][name])+ for name in ('_features_dc', '_scaling', '_rotation', '_opacity')}+ objects.append(Gaussian(+ raw_xyz=(offset[i] + points[i, :, None, :]).flatten(0, 1),+ features_dc=raw['_features_dc'], raw_scaling=raw['_scaling'], raw_rotation=raw['_rotation'],+ raw_opacity=raw['_opacity'], scaling_bias=config['scaling_bias'],+ opacity_bias=config['opacity_bias'], minimum_kernel_size=config['3d_filter_kernel_size']))+ return objectsdiff --git a/idol/models/dit.py b/idol/models/dit.pynew file mode 100644index 0000000..a7f5d09--- /dev/null+++ b/idol/models/dit.py@@ -0,0 +1,122 @@+# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_wan.py+# The original license is as follows:+#+# Copyright 2025 The Wan Team and The HuggingFace Team. 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.+"""The denoiser: a rectified-flow transformer over the object latent (8192 tokens) and the input camera (1 token),+conditioned on the image tokens. Joint attention over [latent, image, camera] with learned rotary positions."""+import torch+import torch.nn as nn+import torch.nn.functional as F+from tensordict import TensorDict++from .layers import (MLP, PcdAbsolutePositionEmbedder, RePo3DRotaryEmbedding, SinusoidalEmbedder,+ UnifiedTransformerBlock, convert_module_to_f16)+++class LatentSeqMMFlowModel(nn.Module):+ def __init__(+ self,+ q_token_length: int,+ in_channels: int,+ cam_channels: int,+ model_channels: int,+ cond_channels: int,+ cond2_channels: int,+ num_blocks: int,+ num_refiner_blocks: int = 2,+ num_heads: int = 16,+ num_head_channels: int = 64,+ mlp_ratio: float = 4,+ ):+ super().__init__()+ self.q_token_length = q_token_length+ self.in_channels = in_channels+ self.cam_channels = cam_channels+ self.dtype = torch.float16++ def blocks(count, modulation=True):+ return nn.ModuleList([UnifiedTransformerBlock(model_channels, num_heads=num_heads, mlp_ratio=mlp_ratio,+ modulation=modulation) for _ in range(count)])++ def rope_layers(count):+ return nn.ModuleList([RePo3DRotaryEmbedding(model_channels, num_heads=num_heads,+ head_dim=num_head_channels) for _ in range(count)])++ self.t_embedder = SinusoidalEmbedder(model_channels)+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(model_channels, 6 * model_channels, bias=True))+ self.input_layer = nn.Linear(in_channels, model_channels)+ self.cond_embedder = nn.Linear(cond_channels, model_channels)+ self.cond_embedder2 = nn.Linear(cond2_channels, model_channels)++ # positions of the latent tokens (a fixed scrambled Sobol sequence, stored with the weights)+ self.register_buffer("pos_pe", torch.zeros(1, q_token_length, 3))+ self.pos_embedder = PcdAbsolutePositionEmbedder(model_channels)+ self.noise_repo_layers = rope_layers(num_refiner_blocks)+ self.context_repo_layers = rope_layers(num_refiner_blocks)+ self.repo_layers = rope_layers(num_blocks)++ # each stream is refined on its own, then all tokens go through the joint blocks+ self.noise_refiner = blocks(num_refiner_blocks)+ self.context_refiner = blocks(num_refiner_blocks, modulation=False)+ self.cam_refiner = MLP(cam_channels, model_channels, model_channels, mlp_layer_num=num_refiner_blocks)+ self.blocks = blocks(num_blocks)++ self.shift_table = nn.Parameter(torch.zeros(1, 2, model_channels))+ self.out_layer = nn.Linear(model_channels, in_channels)+ self.cam_out_layer = nn.Linear(model_channels, cam_channels)++ self.blocks.apply(convert_module_to_f16)+ self.noise_refiner.apply(convert_module_to_f16)+ self.context_refiner.apply(convert_module_to_f16)++ def forward(self, x: TensorDict, t: torch.Tensor, cond: TensorDict) -> TensorDict:+ """+ Args:+ x: TensorDict with 'latent' [B, 8192, 16] and 'camera' [B, 1, 5]+ t: [B] time in [0, 1000]+ cond: TensorDict with 'feature1' [B, L_c, 1280] (DINOv3) and 'feature2' [B, L_c, 128] (FLUX.2 VAE)+ Returns:+ the velocity, a TensorDict shaped like x+ """+ z, cam = x['latent'], x['camera']+ h_x = self.input_layer(z).type(self.dtype)+ h_cond = self.cond_embedder(cond['feature1']) + self.cond_embedder2(cond['feature2'])+ h_cond = h_cond.type(self.dtype)++ t_emb = self.t_embedder(t)+ t_mod = self.adaLN_modulation(t_emb).type(self.dtype)++ h_x = h_x + self.pos_embedder(self.pos_pe).type(self.dtype)+ for repo, block in zip(self.noise_repo_layers, self.noise_refiner):+ h_x = block(h_x, mod=t_mod, rotary_emb=repo(h_x))+ for repo, block in zip(self.context_repo_layers, self.context_refiner):+ h_cond = block(h_cond, mod=None, rotary_emb=repo(h_cond))+ h_cam = self.cam_refiner(cam).type(self.dtype)++ h = torch.cat([h_x, h_cond, h_cam], dim=1)+ for repo, block in zip(self.repo_layers, self.blocks):+ h = block(h, mod=t_mod, rotary_emb=repo(h))++ h_x = h[:, :z.shape[1]].type(z.dtype)+ h_x = F.layer_norm(h_x, h_x.shape[-1:])+ h_cam = h[:, -cam.shape[1]:].type(cam.dtype)+ h_cam = F.layer_norm(h_cam, h_cam.shape[-1:])+ shift, scale = (self.shift_table + t_emb.unsqueeze(1)).chunk(2, dim=1)+ h_x = h_x * (1 + scale) + shift+ h_cam = h_cam * (1 + scale) + shift++ out = TensorDict({'latent': self.out_layer(h_x)}, batch_size=x.batch_size)+ out['camera'] = self.cam_out_layer(h_cam)+ return outdiff --git a/idol/models/layers.py b/idol/models/layers.pynew file mode 100644index 0000000..fda51c5--- /dev/null+++ b/idol/models/layers.py@@ -0,0 +1,325 @@+import importlib.util+import os+from typing import Optional++import numpy as np+import torch+import torch.nn as nn+import torch.nn.functional as F+from torch.nn.attention import SDPBackend, sdpa_kernel++# flash-attn when it is installed, PyTorch SDPA otherwise (same result, flash-attn is faster).+# Override with ATTN_BACKEND=flash_attn|sdpa|sdpa_cudnn (sdpa_cudnn: PyTorch SDPA restricted to the cuDNN kernel,+# which IdolPipeline(optimize=True) selects for the denoiser while sampling).+ATTN_BACKEND = os.environ.get('ATTN_BACKEND',+ 'flash_attn' if importlib.util.find_spec('flash_attn') is not None else 'sdpa')+if ATTN_BACKEND not in ('flash_attn', 'sdpa', 'sdpa_cudnn'):+ raise ValueError(f'Unknown attention backend: {ATTN_BACKEND}')+if ATTN_BACKEND == 'flash_attn':+ import flash_attn+++def scaled_dot_product_attention(*args) -> torch.Tensor:+ """(qkv [N, L, 3, H, C]) or (q [N, L, H, C], k [N, S, H, C], v [N, S, H, C]) -> [N, L, H, C]."""+ if ATTN_BACKEND == 'flash_attn':+ if len(args) == 1:+ return flash_attn.flash_attn_qkvpacked_func(args[0])+ return flash_attn.flash_attn_func(*args)+ q, k, v = args[0].unbind(dim=2) if len(args) == 1 else args+ q, k, v = q.permute(0, 2, 1, 3), k.permute(0, 2, 1, 3), v.permute(0, 2, 1, 3)+ if ATTN_BACKEND == 'sdpa_cudnn':+ with sdpa_kernel(SDPBackend.CUDNN_ATTENTION):+ out = F.scaled_dot_product_attention(q, k, v)+ else:+ out = F.scaled_dot_product_attention(q, k, v)+ return out.permute(0, 2, 1, 3)+++def convert_module_to_f16(module):+ if isinstance(module, nn.Linear):+ for parameter in module.parameters():+ parameter.data = parameter.data.half()+++class LayerNorm32(nn.LayerNorm):+ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return super().forward(x.float()).type(x.dtype)+++class MultiHeadRMSNorm(nn.Module):+ def __init__(self, dim: int, heads: int):+ super().__init__()+ self.scale = dim ** 0.5+ self.gamma = nn.Parameter(torch.ones(heads, dim))++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return (F.normalize(x.float(), dim=-1) * self.gamma * self.scale).to(x.dtype)+++class FeedForwardNet(nn.Module):+ def __init__(self, channels: int, mlp_ratio: float = 4.0):+ super().__init__()+ self.mlp = nn.Sequential(+ nn.Linear(channels, int(channels * mlp_ratio)),+ nn.GELU(approximate="tanh"),+ nn.Linear(int(channels * mlp_ratio), channels),+ )++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return self.mlp(x)+++class MLP(nn.Module):+ def __init__(self, channels: int, inner_channels: int, channels_out: int, mlp_layer_num: int = 2):+ super().__init__()+ layers = []+ for i in range(mlp_layer_num - 1):+ layers.append(nn.Linear(channels if i == 0 else inner_channels, inner_channels))+ layers.append(nn.GELU(approximate="tanh"))+ layers.append(nn.Linear(inner_channels, channels_out))+ self.mlp = nn.Sequential(*layers)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return self.mlp(x)+++# -- Positional and scalar embeddings ----------------------------------------++class PcdAbsolutePositionEmbedder(nn.Module):+ """Sinusoidal embedding of 3D positions in [0, 1] (the denoiser's latent token positions)."""+ def __init__(self, channels: int, in_channels: int = 3, max_res=16):+ super().__init__()+ self.channels = channels+ self.in_channels = in_channels+ self.freq_dim = channels // in_channels // 2+ freqs_2exp = torch.arange(max_res, dtype=torch.float32)+ res_dim = max(0, self.freq_dim - max_res)+ freqs_res = torch.arange(res_dim, dtype=torch.float32) / res_dim * max_res+ self.freqs = 2 ** torch.cat([freqs_2exp, freqs_res], dim=0)[:self.freq_dim]++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ *dims, _ = x.shape+ self.freqs = self.freqs.to(x.device)+ out = torch.outer(x.reshape(-1), self.freqs) * 2 * torch.pi+ embed = torch.cat([torch.sin(out), torch.cos(out)], dim=-1).reshape(*dims, -1)+ if embed.shape[-1] < self.channels:+ embed = torch.cat([embed, torch.zeros(*dims, self.channels - embed.shape[-1], device=embed.device)], dim=-1)+ return embed+++class PcdAbsolutePositionEmbedderv2(nn.Module):+ """Sinusoidal embedding of 3D points in [0, 1] (the decoders' query points)."""+ def __init__(self, channels: int, in_channels: int = 3, max_res: int = 10):+ super().__init__()+ self.channels = channels+ self.freq_dim = channels // in_channels // 2+ logs = torch.linspace(0.0, float(max_res), steps=self.freq_dim, dtype=torch.float32)+ self.register_buffer("freqs", torch.pow(2.0, logs), persistent=False)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ N = x.shape[0]+ freqs = self.freqs.to(x.device, dtype=x.dtype)+ ang = x.unsqueeze(-1) * freqs * torch.pi+ embed = torch.cat([torch.sin(ang), torch.cos(ang)], dim=-1).reshape(N, -1)+ if embed.shape[1] < self.channels:+ embed = torch.cat([embed, torch.zeros(N, self.channels - embed.shape[1], device=embed.device,+ dtype=embed.dtype)], dim=-1)+ return embed+++class SinusoidalEmbedder(nn.Module):+ """Embeds a scalar per batch element (diffusion time, octree level) into a vector."""+ def __init__(self, hidden_size, frequency_embedding_size=256, max_period=10000, two_pi=False):+ super().__init__()+ self.mlp = nn.Sequential(+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),+ nn.SiLU(),+ nn.Linear(hidden_size, hidden_size, bias=True),+ )+ self.frequency_embedding_size = frequency_embedding_size+ self.max_period = max_period+ self.two_pi = two_pi++ def forward(self, t):+ half = self.frequency_embedding_size // 2+ freqs = torch.exp(+ -np.log(self.max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half+ ).to(device=t.device)+ args = t[:, None].float() * freqs[None]+ if self.two_pi:+ args = args * 2 * torch.pi+ return self.mlp(torch.cat([torch.cos(args), torch.sin(args)], dim=-1))+++def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:+ """hidden_states [B, L, H, D] rotated by the complex frequencies freqs [B, L, H or 1, D/2], or by the same+ rotation as real (cos, sin) pairs [B, L, H, D/2, 2]."""+ if not freqs.is_complex():+ # the complex product written out, so torch.compile can fuse it+ x0, x1 = hidden_states.float().reshape(*hidden_states.shape[:-1], -1, 2).unbind(-1)+ cos, sin = freqs.unbind(-1)+ return torch.stack([x0 * cos - x1 * sin, x0 * sin + x1 * cos], dim=-1).flatten(-2).type_as(hidden_states)+ x_rotated = torch.view_as_complex(hidden_states.float().reshape(*hidden_states.shape[:-1], -1, 2))+ x_rotated = x_rotated * freqs+ x_out = torch.view_as_real(x_rotated).reshape(*x_rotated.shape[:-1], -1)+ return x_out.type_as(hidden_states)+++def clamp_mul(x, f):+ f_t = f.tanh()+ return x * f_t + x.detach() * (f - f_t)+++class RePo3DRotaryEmbedding(nn.Module):+ """Learned rotary position: each token's features predict a 3D offset per head, turned into RoPE angles."""+ # True: return (cos, sin) pairs instead of a complex tensor, which torch.compile cannot fuse (optimize=True sets it)+ real_valued = False++ def __init__(self, model_channels: int, num_heads: int, head_dim: int, repo_hidden_ratio: float = 0.125,+ max_freq: float = 16.0):+ super().__init__()+ self.num_heads = num_heads+ repo_hidden_size = int(model_channels * repo_hidden_ratio)+ self.norm = LayerNorm32(model_channels)+ self.gate_map = nn.Linear(model_channels, repo_hidden_size, bias=False)+ self.content_map = nn.Linear(model_channels, repo_hidden_size, bias=False)+ self.act = nn.SiLU()+ self.final_map = nn.Linear(repo_hidden_size, 3 * num_heads, bias=False)+ # head_dim split into 3 parts for x, y, z+ dim_0 = dim_1 = 2 * (head_dim // 6)+ dims = [dim_0, dim_1, head_dim - dim_0 - dim_1]+ freqs = [torch.linspace(1.0, float(max_freq), steps=d // 2, dtype=torch.float32) for d in dims]+ self.freqs_0 = nn.Parameter(freqs[0])+ self.freqs_1 = nn.Parameter(freqs[1])+ self.freqs_2 = nn.Parameter(freqs[2])++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ h = self.norm(hidden_states.float())+ out = self.final_map(self.act(self.gate_map(h)) * self.content_map(h))+ B, L, _ = out.shape+ delta_pos = out.reshape(B, L, self.num_heads, 3)+ ang_0 = clamp_mul(delta_pos[..., 0].unsqueeze(-1), self.freqs_0) * torch.pi+ ang_1 = clamp_mul(delta_pos[..., 1].unsqueeze(-1), self.freqs_1) * torch.pi+ ang_2 = clamp_mul(delta_pos[..., 2].unsqueeze(-1), self.freqs_2) * torch.pi+ ang = torch.cat([ang_0, ang_1, ang_2], dim=-1)+ if self.real_valued:+ return torch.stack([ang.cos(), ang.sin()], dim=-1)+ return torch.polar(torch.ones_like(ang), ang).type(torch.complex64)+++# -- Attention ---------------------------------------------------------------++class MultiHeadAttention(nn.Module):+ """Self or cross attention with RMS-normalised queries and keys (the decoders)."""+ def __init__(self, channels: int, num_heads: int, ctx_channels: Optional[int] = None, cross: bool = False):+ super().__init__()+ self.num_heads = num_heads+ self.cross = cross+ head_dim = channels // num_heads+ if cross:+ self.to_q = nn.Linear(channels, channels)+ self.to_kv = nn.Linear(ctx_channels, channels * 2)+ else:+ self.to_qkv = nn.Linear(channels, channels * 3)+ self.q_rms_norm = MultiHeadRMSNorm(head_dim, num_heads)+ self.k_rms_norm = MultiHeadRMSNorm(head_dim, num_heads)+ self.to_out = nn.Linear(channels, channels)++ def forward(self, x: torch.Tensor, context: Optional[torch.Tensor] = None) -> torch.Tensor:+ B, L, C = x.shape+ if self.cross:+ q = self.q_rms_norm(self.to_q(x).reshape(B, L, self.num_heads, -1))+ k, v = self.to_kv(context).reshape(B, context.shape[1], 2, self.num_heads, -1).unbind(dim=2)+ h = scaled_dot_product_attention(q, self.k_rms_norm(k), v)+ else:+ q, k, v = self.to_qkv(x).reshape(B, L, 3, self.num_heads, -1).unbind(dim=2)+ h = scaled_dot_product_attention(torch.stack([self.q_rms_norm(q), self.k_rms_norm(k), v], dim=2))+ return self.to_out(h.reshape(B, L, -1))+++class RopeMultiHeadAttention(nn.Module):+ """Self attention with rotary embeddings and RMS-normalised queries and keys (the denoiser)."""+ def __init__(self, channels: int, num_heads: int):+ super().__init__()+ self.num_heads = num_heads+ self.head_dim = channels // num_heads+ self.qkv = nn.Linear(channels, channels * 3)+ self.q_norm = MultiHeadRMSNorm(self.head_dim, num_heads)+ self.k_norm = MultiHeadRMSNorm(self.head_dim, num_heads)+ self.out = nn.Linear(channels, channels)++ def forward(self, x: torch.Tensor, rope_emb: torch.Tensor) -> torch.Tensor:+ B, L, C = x.shape+ q, k, v = self.qkv(x).reshape(B, L, 3, self.num_heads, self.head_dim).unbind(2)+ q = self.q_norm(apply_rotary_emb(q, rope_emb))+ k = self.k_norm(apply_rotary_emb(k, rope_emb))+ return self.out(scaled_dot_product_attention(q, k, v).reshape(B, L, C))+++# -- Transformer blocks ------------------------------------------------------++class UnifiedTransformerBlock(nn.Module):+ """Denoiser block: RoPE self attention + FFN, modulated by the diffusion time through a shared adaLN plus+ this block's own shift table (modulation=False for the condition refiner, which has plain LayerNorms)."""+ def __init__(self, channels: int, num_heads: int, mlp_ratio: float = 4.0, modulation: bool = True):+ super().__init__()+ self.modulation = modulation+ self.norm1 = LayerNorm32(channels, elementwise_affine=not modulation, eps=1e-6)+ self.norm2 = LayerNorm32(channels, elementwise_affine=not modulation, eps=1e-6)+ self.attn = RopeMultiHeadAttention(channels, num_heads=num_heads)+ self.mlp = FeedForwardNet(channels, mlp_ratio=mlp_ratio)+ if modulation:+ self.shift_table = nn.Parameter(torch.zeros(1, 6 * channels))++ def forward(self, x: torch.Tensor, mod: Optional[torch.Tensor], rotary_emb: torch.Tensor) -> torch.Tensor:+ if not self.modulation:+ x = x + self.attn(self.norm1(x), rope_emb=rotary_emb)+ return x + self.mlp(self.norm2(x))+ mod = mod + self.shift_table.type(mod.dtype)+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = mod.chunk(6, dim=1)+ h = self.norm1(x)+ h = h * (1 + scale_msa.unsqueeze(1)) + shift_msa.unsqueeze(1)+ h = self.attn(h, rope_emb=rotary_emb)+ x = x + h * gate_msa.unsqueeze(1)+ h = self.norm2(x)+ h = h * (1 + scale_mlp.unsqueeze(1)) + shift_mlp.unsqueeze(1)+ h = self.mlp(h)+ return x + h * gate_mlp.unsqueeze(1)+++class TransformerCrossBlock(nn.Module):+ """Gaussian decoder block: self attention + cross attention to the latent + FFN."""+ def __init__(self, channels: int, ctx_channels: int, num_heads: int, mlp_ratio: float = 4.0):+ super().__init__()+ self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6)+ self.norm2 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6)+ self.norm3 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6)+ self.self_attn = MultiHeadAttention(channels, num_heads=num_heads)+ self.cross_attn = MultiHeadAttention(channels, num_heads=num_heads, ctx_channels=ctx_channels, cross=True)+ self.mlp = FeedForwardNet(channels, mlp_ratio=mlp_ratio)++ def forward(self, x: torch.Tensor, context: torch.Tensor) -> torch.Tensor:+ x = x + self.self_attn(self.norm1(x))+ x = x + self.cross_attn(self.norm2(x), context)+ return x + self.mlp(self.norm3(x))+++class ModulatedTransformerCrossOnlyBlock(nn.Module):+ """Octree decoder block: cross attention to the latent + FFN, modulated by the octree level (shared adaLN)."""+ def __init__(self, channels: int, ctx_channels: int, num_heads: int, mlp_ratio: float = 4.0):+ super().__init__()+ self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6)+ self.norm2 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6)+ self.cross_attn = MultiHeadAttention(channels, num_heads=num_heads, ctx_channels=ctx_channels, cross=True)+ self.mlp = FeedForwardNet(channels, mlp_ratio=mlp_ratio)++ def forward(self, x: torch.Tensor, mod: torch.Tensor, context: torch.Tensor) -> torch.Tensor:+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = mod.chunk(6, dim=1)+ h = self.norm1(x)+ h = h * (1 + scale_msa.unsqueeze(1)) + shift_msa.unsqueeze(1)+ h = self.cross_attn(h, context)+ x = x + h * gate_msa.unsqueeze(1)+ h = self.norm2(x)+ h = h * (1 + scale_mlp.unsqueeze(1)) + shift_mlp.unsqueeze(1)+ h = self.mlp(h)+ return x + h * gate_mlp.unsqueeze(1)diff --git a/idol/pipeline.py b/idol/pipeline.pynew file mode 100644index 0000000..677789c--- /dev/null+++ b/idol/pipeline.py@@ -0,0 +1,153 @@+import json+import os+import types+from contextlib import contextmanager+from dataclasses import dataclass+from typing import Optional, Union++import numpy as np+import torch+from PIL import Image+from safetensors.torch import load_file+from tensordict import TensorDict++from .camera import decode_camera+from .conditioning import ImageEncoder, require_encoder_access+from .gaussian import Gaussian+from .models import BiRefNet, GaussianFixedlenDecoder, LatentSeqMMFlowModel, OctreeProbabilityFixedlenDecoder+from .models import layers+from .models.layers import RePo3DRotaryEmbedding, UnifiedTransformerBlock+from .preprocess import CROP_MARGIN, preprocess_image+from .sampler import sample_flow++DEFAULT_REPO = 'speridlabs/idol'+WEIGHT_FILES = ['config.json', 'denoiser.safetensors', 'decoder.safetensors', 'decoder_gs.safetensors',+ 'birefnet.safetensors']+++@dataclass+class IdolOutput:+ gaussian: Gaussian # the object; .save_ply(path) writes a standard 3DGS PLY+ preprocessed_image: Image.Image # the 1024 x 1024 image the model saw (background removed, cropped)+ camera: dict # predicted input camera: yaw, pitch (radians), radius, fov (degrees)+++def compile_for_sampling(denoiser):+ """torch.compile the denoiser's transformer blocks and RePo layers, once per class and bound to this model's+ instances only (the decoders stay eager), and switch the RePo layers to real-valued RoPE."""+ compiled = {}+ for module in denoiser.modules():+ if isinstance(module, RePo3DRotaryEmbedding):+ module.real_valued = True+ if isinstance(module, (UnifiedTransformerBlock, RePo3DRotaryEmbedding)):+ if type(module) not in compiled:+ compiled[type(module)] = torch.compile(type(module).forward, dynamic=False)+ module.forward = types.MethodType(compiled[type(module)], module)+++class IdolPipeline:+ """optimize (default on, CUDA only): ~1.7x faster sampling at the same output quality: compiled denoiser+ (torch.compile), conditional and unconditional passes batched together, cuDNN attention and TF32 matmuls while+ sampling. The first generation in a process compiles first. optimize=False runs everything eagerly."""+ def __init__(self, weights_dir: str, device: Optional[str] = None, dinov3_dtype: str = 'bf16',+ optimize: bool = True):+ self.device = torch.device(device or ('cuda' if torch.cuda.is_available() else 'cpu'))+ with open(os.path.join(weights_dir, 'config.json')) as f:+ self.config = json.load(f)+ encoders = self.config['image_encoders']+ require_encoder_access([encoders['dinov3'], encoders['flux2_vae']])++ def load(model, name):+ model.load_state_dict(load_file(os.path.join(weights_dir, f'{name}.safetensors')), strict=True)+ return model.eval().requires_grad_(False).to(self.device)++ self.denoiser = load(LatentSeqMMFlowModel(**self.config['denoiser']['args']), 'denoiser')+ self.decoder = load(OctreeProbabilityFixedlenDecoder(**self.config['decoder']['args']), 'decoder')+ self.decoder_gs = load(GaussianFixedlenDecoder(**self.config['decoder_gs']['args']), 'decoder_gs')+ self.background_remover = load(BiRefNet(), 'birefnet')+ if self.device.type == 'cuda':+ self.background_remover.half()+ self.image_encoder = ImageEncoder(encoders['dinov3'], encoders['flux2_vae'], dinov3_dtype=dinov3_dtype,+ device=self.device)+ self.optimize = optimize and self.device.type == 'cuda'+ if self.optimize:+ compile_for_sampling(self.denoiser)++ @classmethod+ def from_pretrained(cls, repo_or_dir: str = DEFAULT_REPO, **kwargs) -> 'IdolPipeline':+ if os.path.isdir(repo_or_dir):+ return cls(repo_or_dir, **kwargs)+ from huggingface_hub import hf_hub_download, snapshot_download+ # check the gated image encoders before downloading the ~3 GB of weights+ with open(hf_hub_download(repo_or_dir, 'config.json')) as f:+ encoders = json.load(f)['image_encoders']+ require_encoder_access([encoders['dinov3'], encoders['flux2_vae']])+ return cls(snapshot_download(repo_or_dir, allow_patterns=WEIGHT_FILES), **kwargs)++ def preprocess(self, image: Union[str, Image.Image], mode: str = 'synthetic',+ crop_margin: Optional[float] = None) -> Image.Image:+ """mode 'synthetic' (renders, generated images of one object: crop 1.2) or 'real' (photos: crop 1.7);+ crop_margin overrides the mode's value."""+ if isinstance(image, str):+ image = Image.open(image)+ margin = crop_margin if crop_margin is not None else CROP_MARGIN[mode]+ return preprocess_image(image, background_remover=self.background_remover,+ image_size=self.config['image_size'], crop_margin=margin)++ @torch.no_grad()+ def __call__(+ self,+ image: Union[str, Image.Image],+ mode: str = 'synthetic',+ seed: int = 42,+ steps: int = 50,+ cfg_strength: float = 3.0,+ rescale_t: float = 3.0,+ num_gaussians: int = 262144,+ crop_margin: Optional[float] = None,+ verbose: bool = False,+ ) -> IdolOutput:+ """Generate the 3D Gaussians of the object in ``image``.++ mode / crop_margin: see ``preprocess``.+ num_gaussians: 32,768 to 1,048,576, rounded down to a multiple of 32."""+ prepared = self.preprocess(image, mode=mode, crop_margin=crop_margin)+ pixels = torch.from_numpy(np.array(prepared)).permute(2, 0, 1).float().div(255.0)[None].to(self.device)++ torch.manual_seed(seed)+ cond = self.image_encoder(pixels)+ noise = TensorDict({+ 'latent': torch.randn(1, self.denoiser.q_token_length, self.denoiser.in_channels, device=self.device),+ 'camera': torch.randn(1, 1, self.denoiser.cam_channels, device=self.device),+ }, batch_size=1, device=self.device)+ with self._sampling_settings():+ sample = sample_flow(self.denoiser, noise, cond=cond, neg_cond=cond.apply(torch.zeros_like),+ steps=steps, rescale_t=rescale_t, cfg_strength=cfg_strength, verbose=verbose,+ batch_cfg=self.optimize)+ gaussian = self.decode(sample['latent'], num_gaussians)+ return IdolOutput(gaussian=gaussian, preprocessed_image=prepared, camera=decode_camera(sample['camera'][0, 0]))++ @contextmanager+ def _sampling_settings(self):+ """optimize=True: cuDNN attention and TF32 matmuls for the denoiser only (cuDNN is slower in the decoders)."""+ if not self.optimize:+ yield+ return+ backend, tf32 = layers.ATTN_BACKEND, torch.backends.cuda.matmul.allow_tf32+ layers.ATTN_BACKEND = 'sdpa_cudnn'+ torch.backends.cuda.matmul.allow_tf32 = True+ try:+ yield+ finally:+ layers.ATTN_BACKEND = backend+ torch.backends.cuda.matmul.allow_tf32 = tf32++ @torch.no_grad()+ def decode(self, latent: torch.Tensor, num_gaussians: int = 262144) -> Gaussian:+ """Latent [1, 8192, 16] -> Gaussians: the octree decoder places num_gaussians / 32 anchor points, the+ Gaussian decoder turns each anchor into 32 Gaussians."""+ per_anchor = self.decoder_gs.rep_config['num_gaussians']+ anchors = OctreeProbabilityFixedlenDecoder.sample(self.decoder, latent,+ num_points=max(1, int(num_gaussians) // per_anchor),+ level=self.config['max_voxel_level'])+ return self.decoder_gs.to_representation(anchors, self.decoder_gs(anchors, latent))[0]diff --git a/idol/preprocess.py b/idol/preprocess.pynew file mode 100644index 0000000..38c3caf--- /dev/null+++ b/idol/preprocess.py@@ -0,0 +1,37 @@+import numpy as np+from PIL import Image, ImageFilter++# How much room the square crop leaves around the object: crop side = object bounding box x margin, so the+# object spans 1 / margin of the image. Renders of single objects work best tight; photos with a looser crop.+CROP_MARGIN = {'synthetic': 1.2, 'real': 1.7}+++def has_real_alpha(image: Image.Image) -> bool:+ return image.mode == 'RGBA' and np.array(image.getchannel(3), dtype=np.int32).min() < 255+++def preprocess_image(image: Image.Image, background_remover, image_size: int = 1024,+ crop_margin: float = 1.2) -> Image.Image:+ """Return the RGB image the encoders see.++ Resize so the short side is ``image_size``; if the image has no real alpha, ``background_remover`` (BiRefNet)+ predicts one; erode the alpha by 1 px so no background-coloured fringe survives; crop a square of+ side ``crop_margin`` x the object's bounding box; resize to ``image_size``; composite on black."""+ width, height = image.size+ scale = image_size / min(width, height)+ image = image.resize((max(1, int(round(width * scale))), max(1, int(round(height * scale)))), Image.LANCZOS)+ if not has_real_alpha(image):+ image = background_remover.remove_background(image.convert('RGB'))+ image.putalpha(image.getchannel(3).filter(ImageFilter.MinFilter(3)))+ alpha = np.array(image.getchannel(3))+ ys, xs = np.nonzero(alpha)+ if len(xs) == 0:+ raise ValueError('no object found in the image (the alpha channel is empty)')+ left, top, right, bottom = xs.min(), ys.min(), xs.max(), ys.max()+ center_x, center_y = (left + right) / 2, (top + bottom) / 2+ half = max(right - left, bottom - top) / 2 * crop_margin+ image = image.crop([int(center_x - half), int(center_y - half), int(center_x + half), int(center_y + half)])+ image = image.resize((image_size, image_size), Image.LANCZOS)+ composite = Image.new('RGB', (image_size, image_size), (0, 0, 0))+ composite.paste(image, mask=image.split()[3])+ return compositediff --git a/idol/sample.py b/idol/sample.pynew file mode 100644index 0000000..7ff6b47--- /dev/null+++ b/idol/sample.py@@ -0,0 +1,57 @@+import argparse+import json+import os++from .conditioning import EncoderAccessError+from .pipeline import IdolPipeline++IMAGE_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.webp', '.bmp')+++def main():+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument('--image', required=True, help='an image, or a folder of images')+ parser.add_argument('--out', default='outputs')+ parser.add_argument('--mode', choices=['synthetic', 'real'], default='synthetic',+ help="'synthetic': renders and generated images of one object (crop 1.2); "+ "'real': photos (crop 1.7)")+ parser.add_argument('--crop_margin', type=float, default=None,+ help='override the crop: square side = object bounding box x this')+ parser.add_argument('--seed', type=int, default=42)+ parser.add_argument('--steps', type=int, default=50)+ parser.add_argument('--cfg_strength', type=float, default=3.0, help='classifier-free guidance strength')+ parser.add_argument('--rescale_t', type=float, default=3.0, help='time-step shift towards high noise')+ parser.add_argument('--num_gaussians', type=int, default=262144,+ help='32,768 to 1,048,576, a multiple of 32')+ parser.add_argument('--weights', default='speridlabs/idol', help='Hugging Face repo or local folder')+ parser.add_argument('--dinov3_dtype', choices=['bf16', 'fp32'], default='bf16')+ parser.add_argument('--no_optimize', dest='optimize', action='store_false',+ help='turn off the faster sampling (torch.compile, batched guidance, cuDNN attention, TF32) '+ 'that is on by default on GPU')+ args = parser.parse_args()++ if os.path.isdir(args.image):+ images = sorted(os.path.join(args.image, name) for name in os.listdir(args.image)+ if name.lower().endswith(IMAGE_EXTENSIONS))+ else:+ images = [args.image]+ os.makedirs(args.out, exist_ok=True)++ try:+ pipeline = IdolPipeline.from_pretrained(args.weights, dinov3_dtype=args.dinov3_dtype, optimize=args.optimize)+ except EncoderAccessError as error:+ raise SystemExit(f'error: {error}')+ for path in images:+ name = os.path.splitext(os.path.basename(path))[0]+ output = pipeline(path, mode=args.mode, crop_margin=args.crop_margin, seed=args.seed, steps=args.steps,+ cfg_strength=args.cfg_strength, rescale_t=args.rescale_t,+ num_gaussians=args.num_gaussians, verbose=True)+ output.gaussian.save_ply(os.path.join(args.out, f'{name}.ply'))+ output.preprocessed_image.save(os.path.join(args.out, f'{name}_input.png'))+ with open(os.path.join(args.out, f'{name}_camera.json'), 'w') as f:+ json.dump(output.camera, f, indent=2)+ print(f'{name}: {args.out}/{name}.ply')+++if __name__ == '__main__':+ main()diff --git a/idol/sampler.py b/idol/sampler.pynew file mode 100644index 0000000..ad45c4f--- /dev/null+++ b/idol/sampler.py@@ -0,0 +1,33 @@+import numpy as np+import torch+from tqdm import tqdm++[email protected]_grad()+def sample_flow(model, noise, cond, neg_cond, steps: int = 50, rescale_t: float = 3.0, cfg_strength: float = 3.0,+ verbose: bool = True, batch_cfg: bool = False):+ """Integrate from noise (t = 1) to data (t = 0) in ``steps`` Euler steps.++ rescale_t shifts the time grid towards t = 1 (more steps at high noise).+ cfg_strength: guided velocity = (1 + w) * v(cond) - w * v(neg_cond).+ batch_cfg: run cond and neg_cond as one batch-2 forward instead of two passes (same formula, faster on GPU)."""++ def velocity(sample, t, condition):+ return model(sample, torch.tensor([1000 * t] * sample.shape[0], device=sample.device, dtype=torch.float32),+ condition)++ sample = noise+ t_seq = np.linspace(1, 0, steps + 1)+ t_seq = rescale_t * t_seq / (1 + (rescale_t - 1) * t_seq)+ for i in tqdm(range(steps), desc='Sampling', disable=not verbose):+ t, t_prev = t_seq[i], t_seq[i + 1]+ if cfg_strength > 0 and batch_cfg:+ n = sample.shape[0]+ both = velocity(torch.cat([sample, sample]), t, torch.cat([cond, neg_cond]))+ v = (1 + cfg_strength) * both[:n] - cfg_strength * both[n:]+ else:+ v = velocity(sample, t, cond)+ if cfg_strength > 0:+ v = (1 + cfg_strength) * v - cfg_strength * velocity(sample, t, neg_cond)+ sample = sample - v * (t - t_prev)+ return samplediff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 0000000..83f3544--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,30 @@+[project]+name = "idol"+version = "0.1.0"+description = "Idol: a single image to 3D Gaussians"+readme = "README.md"+license = "Apache-2.0"+requires-python = ">=3.10"+dependencies = [+ "torch>=2.5",+ "torchvision>=0.20",+ "transformers>=4.56",+ "diffusers>=0.36",+ "huggingface_hub>=0.34",+ "safetensors>=0.4",+ "tensordict>=0.8",+ "numpy>=1.26",+ "pillow>=10.0",+ "plyfile>=1.0",+ "tqdm>=4.66",+]++[project.optional-dependencies]+demo = ["gradio==5.49.1", "spaces"]++[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["idol"]