Skip to content

[Apple Silicon] Add MPS and Metal inference support#175

Open
Jourloy wants to merge 17 commits into
microsoft:mainfrom
Jourloy:main
Open

[Apple Silicon] Add MPS and Metal inference support#175
Jourloy wants to merge 17 commits into
microsoft:mainfrom
Jourloy:main

Conversation

@Jourloy

@Jourloy Jourloy commented Jul 17, 2026

Copy link
Copy Markdown

Summary

This PR adds source-native Apple Silicon support to TRELLIS.2.

On arm64 macOS, the automatic backend selects PyTorch MPS together with capability-probed Metal extensions. The existing CUDA/Linux route remains available, while macOS receives explicit fallbacks for operations that are unavailable or unstable on MPS.

This addresses the Apple Silicon / MPS portion of #74. It intentionally does not close the AMD or Intel parts of that issue.

What changed

  • Add automatic Apple Silicon backend resolution:
    • PyTorch MPS for model inference
    • flex_gemm Metal sparse convolution and sparse attention
    • mtldiffrast Metal rasterization
    • mtlmesh / mtlbvh mesh and BVH operations
  • Add capability probes before enabling individual Metal components.
  • Add controlled fallback paths:
    • pure-PyTorch sparse convolution
    • PyTorch SDPA attention
    • CPU mesh extraction
    • KDTree texture baking
  • Use SDPA for dense attention on macOS while preserving the upstream flash_attn default on other platforms.
  • Add actionable diagnostics for MPS OOM, empty meshes, and Metal watchdog/BVH failures.
  • Add a reproducible Python 3.11 macOS setup:
    • primary pair: PyTorch 2.13.0 / torchvision 0.28.0
    • ABI fallback: PyTorch 2.11.0 / torchvision 0.26.0
    • pinned Metal extension revisions
    • pip check, MPS, SDPA, MLX, KDTree, raster, and BVH probes
  • Pin the runtime model revisions and support strict offline loading from a dedicated Hugging Face cache.
  • Preserve authored RGBA transparency; opaque inputs still use the official RMBG-2.0 model.
  • Add a CLI for reproducible image-to-3D generation with:
    • auto, mps, and experimental mlx backend selection
    • Metal/KDTree baker selection
    • 512, 1024, and 1024 cascade pipelines
    • deterministic seeds and configurable texture size
    • no default triangle limit
  • Produce reproducible artifacts:
    • raw_full.glb
    • candidate_pbr.glb
    • meta.json with revisions, timings, hashes, bounds, backend probes, and fallback attempts
  • Preserve generated UV0, base color, metallic, roughness, and alpha during PBR export.
  • Add an experimental MLX backend with small numerical parity tests. End-to-end acceptance still uses PyTorch MPS.

The PBR fallback order is:

  1. full-resolution Metal bake
  2. full-resolution KDTree bake
  3. technical ~200k-face candidate with Metal
  4. technical ~200k-face candidate with KDTree

raw_full.glb is never decimated, and every fallback is recorded in meta.json.

Validation

Tested on:

  • Apple M4 Max, 36 GB unified memory
  • macOS 26.4
  • Python 3.11.15
  • PyTorch 2.13.0
  • torchvision 0.28.0

Automated checks:

  • 28 passed in the pytest suite
  • standalone Metal sparse-convolution integration smoke passed
  • dense, masked, and production split-K Metal kernels produced equivalent output
  • MPS, SDPA, Metal sparse attention, raster, BVH, KDTree, and MLX probes passed
  • strict offline model-cache verification passed
  • pip check and compileall passed
  • simulated Metal BVH failure selected the expected full-resolution KDTree fallback

End-to-end generation:

  • pipeline: 512
  • seed: 42
  • texture size: 1024
  • input: repository example RGBA image
  • raw_full.glb: 3,090,522 triangles
  • candidate_pbr.glb: 3,025,626 triangles
  • first full-resolution Metal PBR attempt succeeded
  • technical decimation was not used
  • wall time: 1004.60 seconds
  • maximum RSS: 17.82 GB
  • completed without OOM

The resulting glTF 2.0 files were validated for non-empty geometry, UV0, vertex normals, consistent bounds, and embedded base-color, metallic-roughness, and alpha textures.

The official RMBG-2.0 path was also tested separately with an opaque input and produced a non-trivial alpha mask.

Compatibility and known limitations

  • End-to-end testing was performed on Apple M4 Max only.
  • The CUDA/Linux route is retained but was not end-to-end tested on CUDA hardware in this environment.
  • PyTorch currently runs segment_reduce through its CPU fallback on MPS. This is functional but affects performance.
  • MLX support is experimental and currently covered by small parity tests rather than end-to-end acceptance.
  • DINOv3 and RMBG-2.0 require accepted Hugging Face access terms and authentication.
  • The macOS setup currently depends on pinned Metal extension forks.
  • This is a large change. I am happy to split the core MPS/Metal backend, setup/CLI, and experimental MLX work into separate PRs if that is easier to review.

Credits

This work builds on and preserves the authorship of the Apple backend work from:

The CLI diagnostics and fallback design were also informed by:

pedronaugusto and others added 17 commits July 17, 2026 07:51
The default Darwin path used to be a try/except ImportError, which only
catches build failures. With the mtlgemm round 1 fixes shipped, the more
common failure mode for end users will be running an *older* mtlgemm that
still returns CPU tensors from MPS calls — that doesn't fail import, it
fails with a cryptic LayerNorm crash inside the model on the first conv.

The new probe runs a tiny SparseConv3d on MPS and checks the output
device. If anything breaks (import, build, dispatch, return-device), fall
back to the pure-PyTorch backend rather than crashing inside the model.

Tensors in the probe are built on CPU then moved to MPS because some
PyTorch builds lack int/fp16 torch.zeros kernels on MPS — that's a
PyTorch issue, separate from anything we control here.

Plus: end-to-end smoke test (test_flex_gemm_integration.py) that
exercises both Algorithm.IMPLICIT_GEMM and Algorithm.MASKED_IMPLICIT_GEMM
through a real SparseConv3d → F.layer_norm chain on MPS. Confirms both
algorithms return MPS tensors of the right dtype and produce equivalent
output.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The original probe only exercised Algorithm.IMPLICIT_GEMM. A stale install
where dense works but the masked cache/dispatch path is broken (e.g. the
pre-round-2 aliased-to-dense fallback) would select flex_gemm and crash at
the first MASKED_IMPLICIT_GEMM call inside the decoder. Probe both.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Wires the new mtlgemm fused sparse attention kernel through the ATTN
backend selector. Dispatches to the fused Metal kernel when
max(max_q, max_kv) <= 256 (where the naive per-thread-serial-KV kernel
beats SDPA-padded on M3 Max), and falls through to an inline SDPA-padded
path for larger max_seqlen. Opt in via ATTN_BACKEND=flex_gemm_sparse_attn
or SPARSE_ATTN_BACKEND=flex_gemm_sparse_attn. Default on Darwin stays
'sdpa' — the threshold-based fallback doesn't yet prove a universal
win across the pipeline's attention shape distribution.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
SparseGroupNorm / SparseLayerNorm used torch.zeros_like which fails with
"DispatchStub: missing kernel for mps" on PyTorch builds compiled with
both CUDA and MPS backends (the user's local build hit this). Added a
_zeros_like_safe helper that builds zeros on CPU and transfers when the
reference tensor is on MPS; Apple Silicon unified memory makes the
transfer metadata-only, so the overhead vs a working MPS zeros kernel
is negligible. On CPU, behaves identically to torch.zeros_like.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…path precedent

The 256-cap inside the flex_gemm_sparse_attn branch was a hold-over from
the early naive Metal kernel (round 3). The current backend is flash-
attention-v2 with simdgroup matmul + simd-shuffle softmax row reductions
and wins at every measured shape including max_seqlen=2048. The CUDA
backends above (xformers / flash_attn / flash_attn_3) never fork on
max_seqlen — match that precedent.

Safety-valve preserved as FLEX_GEMM_ATTN_MAX_SEQLEN=N env var: when set,
falls back to SDPA-padded above the cap. Useful only on PyTorch builds
where the Accelerate-SDPA-CPU-bounce happens to win at a specific shape
(measured crossover sits beyond 768 on fp32, higher on fp16).
End-to-end micro-bench for the production decoder block at res=32 ch=64
with seqlens=[256, 192, 128, 64]. Three stages reported (convs-only /
attn-only / combined block) at fp16, vs the all-SDPA-padded baseline.
Used to track the cumulative effect of the mtlgemm flash-attention-v2
fwd + bwd work on the actual decoder hot path.
…lex_gemm probe passes

The flex_gemm_sparse_attn backend is now flash-attention-v2 with
simdgroup_matrix_multiply_accumulate for Q@K^T and P@V plus simd-shuffle
softmax row reductions, and wins 5–15× over SDPA-padded-CPU-bounce at
every measured shape including max_seqlen=2048. Production decoder block
on M3 Max: 5.04× wall-clock vs all-SDPA-padded baseline (3.49 ms vs
17.57 ms), entirely from this change being the default.

The existing __flex_gemm_works_on_mps() probe covers the same package
the attention path lives in, so the gate is identical: if conv probe
passes, set both CONV='flex_gemm' and ATTN='flex_gemm_sparse_attn'.
SPARSE_ATTN_BACKEND= (or ATTN_BACKEND=) env override is unchanged.

Also fix benchmarks/e2e_decoder.py to inject the repo root into
sys.path so it runs as `python benchmarks/e2e_decoder.py` from any cwd.
The mtlgemm Metal extension's metal_context.mm calls
at::mps::dispatch_sync_with_rethrow, which was added to that namespace
in PyTorch 2.11.0 (pytorch/pytorch#167445, merged 2025-11-11). Earlier
stable releases (2.6 – 2.10) only expose it under at::native::mps::,
so installing mtlgemm against them fails the C++ extension build.

torchvision pinned to >=0.26.0 (matches torch 2.11) to keep the
torch/torchvision wheel pair ABI-compatible on resolution.
@microsoft-github-policy-service

Copy link
Copy Markdown

@Jourloy please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, 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 Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants