Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions stable_fast_3d/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
STABILITY AI COMMUNITY LICENSE AGREEMENT
Last Updated: July 5, 2024


I. INTRODUCTION

This Agreement applies to any individual person or entity ("You", "Your" or "Licensee") that uses or distributes any portion or element of the Stability AI Materials or Derivative Works thereof for any Research & Non-Commercial or Commercial purpose. Capitalized terms not otherwise defined herein are defined in Section V below.


This Agreement is intended to allow research, non-commercial, and limited commercial uses of the Models free of charge. In order to ensure that certain limited commercial uses of the Models continue to be allowed, this Agreement preserves free access to the Models for people or organizations generating annual revenue of less than US $1,000,000 (or local currency equivalent).


By clicking "I Accept" or by using or distributing or using any portion or element of the Stability Materials or Derivative Works, You agree that You have read, understood and are bound by the terms of this Agreement. If You are acting on behalf of a company, organization or other entity, then "You" includes you and that entity, and You agree that You: (i) are an authorized representative of such entity with the authority to bind such entity to this Agreement, and (ii) You agree to the terms of this Agreement on that entity's behalf.

II. RESEARCH & NON-COMMERCIAL USE LICENSE

Subject to the terms of this Agreement, Stability AI grants You a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable and royalty-free limited license under Stability AI's intellectual property or other rights owned by Stability AI embodied in the Stability AI Materials to use, reproduce, distribute, and create Derivative Works of, and make modifications to, the Stability AI Materials for any Research or Non-Commercial Purpose. "Research Purpose" means academic or scientific advancement, and in each case, is not primarily intended for commercial advantage or monetary compensation to You or others. "Non-Commercial Purpose" means any purpose other than a Research Purpose that is not primarily intended for commercial advantage or monetary compensation to You or others, such as personal use (i.e., hobbyist) or evaluation and testing.

III. COMMERCIAL USE LICENSE

Subject to the terms of this Agreement (including the remainder of this Section III), Stability AI grants You a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable and royalty-free limited license under Stability AI's intellectual property or other rights owned by Stability AI embodied in the Stability AI Materials to use, reproduce, distribute, and create Derivative Works of, and make modifications to, the Stability AI Materials for any Commercial Purpose. "Commercial Purpose" means any purpose other than a Research Purpose or Non-Commercial Purpose that is primarily intended for commercial advantage or monetary compensation to You or others, including but not limited to, (i) creating, modifying, or distributing Your product or service, including via a hosted service or application programming interface, and (ii) for Your business's or organization's internal operations.
If You are using or distributing the Stability AI Materials for a Commercial Purpose, You must register with Stability AI at (https://stability.ai/community-license). If at any time You or Your Affiliate(s), either individually or in aggregate, generate more than USD $1,000,000 in annual revenue (or the equivalent thereof in Your local currency), regardless of whether that revenue is generated directly or indirectly from the Stability AI Materials or Derivative Works, any licenses granted to You under this Agreement shall terminate as of such date. You must request a license from Stability AI at (https://stability.ai/enterprise) , which Stability AI may grant to You in its sole discretion. If you receive Stability AI Materials, or any Derivative Works thereof, from a Licensee as part of an integrated end user product, then Section III of this Agreement will not apply to you.

IV. GENERAL TERMS

Your Research, Non-Commercial, and Commercial License(s) under this Agreement are subject to the following terms.
a. Distribution & Attribution. If You distribute or make available the Stability AI Materials or a Derivative Work to a third party, or a product or service that uses any portion of them, You shall: (i) provide a copy of this Agreement to that third party, (ii) retain the following attribution notice within a "Notice" text file distributed as a part of such copies: "This Stability AI Model is licensed under the Stability AI Community License, Copyright © Stability AI Ltd. All Rights Reserved", and (iii) prominently display "Powered by Stability AI" on a related website, user interface, blogpost, about page, or product documentation. If You create a Derivative Work, You may add your own attribution notice(s) to the "Notice" text file included with that Derivative Work, provided that You clearly indicate which attributions apply to the Stability AI Materials and state in the "Notice" text file that You changed the Stability AI Materials and how it was modified.
b. Use Restrictions. Your use of the Stability AI Materials and Derivative Works, including any output or results of the Stability AI Materials or Derivative Works, must comply with applicable laws and regulations (including Trade Control Laws and equivalent regulations) and adhere to the Documentation and Stability AI's AUP, which is hereby incorporated by reference. Furthermore, You will not use the Stability AI Materials or Derivative Works, or any output or results of the Stability AI Materials or Derivative Works, to create or improve any foundational generative AI model (excluding the Models or Derivative Works).
c. Intellectual Property.
(i) Trademark License. No trademark licenses are granted under this Agreement, and in connection with the Stability AI Materials or Derivative Works, You may not use any name or mark owned by or associated with Stability AI or any of its Affiliates, except as required under Section IV(a) herein.
(ii) Ownership of Derivative Works. As between You and Stability AI, You are the owner of Derivative Works You create, subject to Stability AI's ownership of the Stability AI Materials and any Derivative Works made by or for Stability AI.
(iii) Ownership of Outputs. As between You and Stability AI, You own any outputs generated from the Models or Derivative Works to the extent permitted by applicable law.
(iv) Disputes. If You or Your Affiliate(s) institute litigation or other proceedings against Stability AI (including a cross-claim or counterclaim in a lawsuit) alleging that the Stability AI Materials, Derivative Works or associated outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by You, then any licenses granted to You under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Stability AI from and against any claim by any third party arising out of or related to Your use or distribution of the Stability AI Materials or Derivative Works in violation of this Agreement.
(v) Feedback. From time to time, You may provide Stability AI with verbal and/or written suggestions, comments or other feedback related to Stability AI's existing or prospective technology, products or services (collectively, "Feedback"). You are not obligated to provide Stability AI with Feedback, but to the extent that You do, You hereby grant Stability AI a perpetual, irrevocable, royalty-free, fully-paid, sub-licensable, transferable, non-exclusive, worldwide right and license to exploit the Feedback in any manner without restriction. Your Feedback is provided "AS IS" and You make no warranties whatsoever about any Feedback.
d. Disclaimer Of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE STABILITY AI MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OR LAWFULNESS OF USING OR REDISTRIBUTING THE STABILITY AI MATERIALS, DERIVATIVE WORKS OR ANY OUTPUT OR RESULTS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE STABILITY AI MATERIALS, DERIVATIVE WORKS AND ANY OUTPUT AND RESULTS.
e. Limitation Of Liability. IN NO EVENT WILL STABILITY AI OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF STABILITY AI OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
f. Term And Termination. The term of this Agreement will commence upon Your acceptance of this Agreement or access to the Stability AI Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Stability AI may terminate this Agreement if You are in breach of any term or condition of this Agreement. Upon termination of this Agreement, You shall delete and cease use of any Stability AI Materials or Derivative Works. Section IV(d), (e), and (g) shall survive the termination of this Agreement.
g. Governing Law. This Agreement will be governed by and constructed in accordance with the laws of the United States and the State of California without regard to choice of law principles, and the UN Convention on Contracts for International Sale of Goods does not apply to this Agreement.

V. DEFINITIONS

"Affiliate(s)" means any entity that directly or indirectly controls, is controlled by, or is under common control with the subject entity; for purposes of this definition, "control" means direct or indirect ownership or control of more than 50% of the voting interests of the subject entity.
"Agreement" means this Stability AI Community License Agreement.
"AUP" means the Stability AI Acceptable Use Policy available at https://stability.ai/use-policy, as may be updated from time to time.
"Derivative Work(s)" means (a) any derivative work of the Stability AI Materials as recognized by U.S. copyright laws and (b) any modifications to a Model, and any other model created which is based on or derived from the Model or the Model's output, including"fine tune" and "low-rank adaptation" models derived from a Model or a Model's output, but do not include the output of any Model.
"Documentation" means any specifications, manuals, documentation, and other written information provided by Stability AI related to the Software or Models.
"Model(s)" means, collectively, Stability AI's proprietary models and algorithms, including machine-learning models, trained model weights and other elements of the foregoing listed on Stability's Core Models Webpage available at, https://stability.ai/core-models, as may be updated from time to time.
"Stability AI" or "we" means Stability AI Ltd. and its Affiliates.
"Software" means Stability AI's proprietary software made available under this Agreement now or in the future.
"Stability AI Materials" means, collectively, Stability's proprietary Models, Software and Documentation (and any portion or combination thereof) made available under this Agreement.
"Trade Control Laws" means any applicable U.S. and non-U.S. export control and trade sanctions laws and regulations.
18 changes: 18 additions & 0 deletions stable_fast_3d/NOTICE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Notice

**This folder (`stable_fast_3d/`) is licensed differently from the rest of this repository.** The rest of `mlx-examples` is MIT-licensed (see the repository root `LICENSE`); this folder is a Derivative Work of [Stability-AI/stable-fast-3d](https://github.com/Stability-AI/stable-fast-3d) and is licensed under the **Stability AI Community License** (see `stable_fast_3d/LICENSE`), which is not sublicensable to MIT terms.

This Stability AI Model is licensed under the Stability AI Community License, Copyright © Stability AI Ltd. All Rights Reserved.

Powered by Stability AI.

## Changes made in this Derivative Work

Reimplemented the full SF3D inference pipeline natively in [MLX](https://github.com/ml-explore/mlx) (Apple Silicon, unified memory):

- Neural forward pass (`camera_embedder.py`, `dinov2.py`, `backbone.py`, `post_processor.py`, `decoder.py`): camera embedder, DINOv2 image tokenizer with per-layer AdaLN modulation, two-stream interleaved transformer backbone, pixel-shuffle post-processor, triplane query sampler, material decoder. Validated module-by-module against the original PyTorch model to float32 tolerance.
- Mesh finishing (`isosurface.py`, `uv_unwrap.py`, `texture_baker.py`): marching-tetrahedra isosurface extraction, UV unwrapping, texture baking, reimplemented in MLX/numpy (previously PyTorch/CPU-only).

No model weights are redistributed here; `weights.py` downloads and converts the checkpoint from the gated [stabilityai/stable-fast-3d](https://huggingface.co/stabilityai/stable-fast-3d) Hugging Face repo at runtime, and downloads the fixed tetrahedra grid (`load/tets/160_tets.npz`, a Stability AI-authored geometric asset, not a trained weight) from the upstream GitHub repo. Both remain under the original license terms.

Standalone reference implementation (development history, module-by-module validation scripts, more detail): https://github.com/bahaehmimdi/stable-fast-3d-mlx
103 changes: 103 additions & 0 deletions stable_fast_3d/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
Stable Fast 3D
==============

[Stable Fast 3D (SF3D)](https://github.com/Stability-AI/stable-fast-3d) in
MLX. SF3D is Stability AI's feedforward single-image -> textured 3D mesh
model. This is a native MLX reimplementation of the full inference pipeline
- no PyTorch, no MPS fallback.

> **License note:** unlike the rest of `mlx-examples` (MIT), this folder is
> licensed under the **Stability AI Community License** - see `LICENSE` and
> `NOTICE.md`. The underlying model is also gated on Hugging Face; you must
> request access before you can download the checkpoint.

Why a separate port: the official PyTorch implementation's MPS backend on
Apple Silicon is slow (full model reload + inference on every generation).
On an M1 Pro, this MLX port brings a single generation from **7-9 minutes**
down to **~12.4 seconds** end-to-end (~34-44x), with the neural forward
pass and mesh finishing (UV unwrap, texture baking) both running in
100% MLX/numpy.

Installation
------------

```
pip install -r requirements.txt
```

The model is gated at [Hugging Face](https://huggingface.co/stabilityai/stable-fast-3d):

1. Request access [here](https://huggingface.co/stabilityai/stable-fast-3d).
2. Create a read-access token [here](https://huggingface.co/settings/tokens).
3. `huggingface-cli login` and enter the token.

Usage
-----

```
python image_to_3d.py chair.png output.glb
```

The checkpoint (~4GB) is downloaded and converted to MLX format on first
run, then cached at `~/.cache/mlx-stable-fast-3d/`.

Or from Python:

```python
from PIL import Image
from stable_fast_3d import StableFast3D

model = StableFast3D() # loads weights once
model.run(Image.open("chair.png"), "output.glb")
```

`StableFast3D.run` accepts `foreground_ratio`, `remove_bg` (background
removal via `rembg`; set `False` if your image already has a clean alpha
channel), and `bake_resolution` (texture resolution, default 512).

What's not ported
------------------

- **CLIP-based material estimation** (`image_estimator` in the original) -
roughness/metallic use fixed constants instead of a real per-image
estimate. Not needed for a raw textured mesh.
- **Illumination estimation** (`global_estimator`) - opt-in in the
original, not requested by default, not ported.
- **Remeshing** (quad/triangle) - the original repo's optional
post-processing step; out of scope here, use the original repo's
`run.py --remesh_option` if you need it.

Speed comparison
-----------------

Measured on an M1 Pro, single generation, model already loaded:

| Version | Backend | Time | Detail |
|---|---|---|---|
| Original SF3D | PyTorch/CUDA (reference hardware) | 7-9 min | Full model reload every generation, no Mac-specific optimization |
| This port, neural pass only | MLX (network) + PyTorch/MPS (finishing) | ~48s | 0.5s weight load + 5.3s MLX inference + 40.8s torch/MPS subprocess (isosurface, UV, texture) |
| This port, full pipeline | 100% MLX + numpy | ~12.4s | 0.4s weight load + 5.4s neural pass + 7.0s MLX/numpy finishing |

Validation
----------

Each module was validated against the original PyTorch model's intermediate
tensors to float32 tolerance (max-abs-diff < 1e-4 throughout the neural
pass), then checked end-to-end: feeding this port's `scene_codes` into the
original (unmodified) PyTorch mesh-extraction code produces an identical
mesh (same vertex/face counts, vertex positions matching to 2.2e-5 max /
1.8e-7 mean) as a mesh produced by a fresh, real PyTorch forward pass on
the same image. Full module-by-module validation scripts and development
history: https://github.com/bahaehmimdi/stable-fast-3d-mlx.

Citation
--------

```BibTeX
@article{sf3d2024,
title={SF3D: Stable Fast 3D Mesh Reconstruction with UV-unwrapping and Illumination Disentanglement},
author={Boss, Mark and Huang, Zixuan and Vasishta, Aaryaman and Jampani, Varun},
journal={arXiv preprint},
year={2024}
}
```
43 changes: 43 additions & 0 deletions stable_fast_3d/image_to_3d.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import argparse

from PIL import Image

from stable_fast_3d import StableFast3D


def main():
parser = argparse.ArgumentParser(
description="Single-image to textured 3D mesh (SF3D, native MLX)."
)
parser.add_argument("image", help="Path to the input image.")
parser.add_argument(
"output",
nargs="?",
default="output.glb",
help="Output GLB path (default: output.glb).",
)
parser.add_argument("--foreground-ratio", type=float, default=0.85)
parser.add_argument(
"--no-remove-bg",
action="store_true",
help="Skip background removal (image already has a clean alpha/background).",
)
parser.add_argument("--bake-resolution", type=int, default=512)
parser.add_argument("--verbose", action="store_true")
args = parser.parse_args()

model = StableFast3D()
image = Image.open(args.image)
out = model.run(
image,
args.output,
foreground_ratio=args.foreground_ratio,
remove_bg=not args.no_remove_bg,
bake_resolution=args.bake_resolution,
verbose=args.verbose,
)
print(out)


if __name__ == "__main__":
main()
8 changes: 8 additions & 0 deletions stable_fast_3d/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
mlx>=0.18
numpy
pillow
huggingface-hub
safetensors
rembg
onnxruntime
trimesh
3 changes: 3 additions & 0 deletions stable_fast_3d/stable_fast_3d/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .pipeline import StableFast3D

__all__ = ["StableFast3D"]
Loading