Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

set PYTORCH_ENABLE_MPS_FALLBACK in the runner, before anything imports torch

Adam Eivy50913cb4100e
diff --git a/server/services/imageTo3d/trellis2GenerateRunner.py b/server/services/imageTo3d/trellis2GenerateRunner.py
index 38ab6fe950..a24c2c6c5b 100644
--- a/server/services/imageTo3d/trellis2GenerateRunner.py
+++ b/server/services/imageTo3d/trellis2GenerateRunner.py
@@ -58,8 +58,35 @@ bare-``torch`` baseline, i.e. ~1.1s once per process against a multi-minute
render.
"""
-import argparse
+# ---------------------------------------------------------------------------
+# ENV PREAMBLE — must run before ANY import that can pull torch.
+#
+# This adapter is now the process entry point, so it inherits an ordering
+# constraint that used to be generate.py's alone. generate.py sets these with
+# `setdefault` at ITS module top and documents why: "MPS fallback MUST be set
+# before torch is imported anywhere (including transitively via flex_gemm).
+# Without this, segment_reduce and a few other ops crash instead of falling back
+# to CPU."
+#
+# When the adapter fronted only the 4K path and did nothing before `runpy`, that
+# held automatically. It no longer does: `_patch_decimation_target` imports
+# `o_voxel.postprocess`, which imports torch — so by the time generate.py ran its
+# own setdefault, torch was already initialized and the flag was inert. The
+# observable failure was `NotImplementedError: aten::segment_reduce is not
+# currently implemented for the MPS device`, raised from the classifier-free
+# guidance std() inside the first sampler step, i.e. every MPS render died ~3
+# minutes in having produced nothing.
+#
+# `setdefault`, not assignment, so an explicit caller-supplied value still wins —
+# and so this stays consistent with generate.py rather than fighting it.
import os
+
+os.environ.setdefault("PYTORCH_ENABLE_MPS_FALLBACK", "1")
+os.environ.setdefault("ATTN_BACKEND", "sdpa")
+os.environ.setdefault("SPARSE_ATTN_BACKEND", "sdpa")
+# ---------------------------------------------------------------------------
+
+import argparse
import runpy
import sys
from pathlib import Path
diff --git a/server/services/imageTo3d/trellis2GenerateRunner.test.js b/server/services/imageTo3d/trellis2GenerateRunner.test.js
index acc4deab9d..5a8780fe84 100644
--- a/server/services/imageTo3d/trellis2GenerateRunner.test.js
+++ b/server/services/imageTo3d/trellis2GenerateRunner.test.js
@@ -24,7 +24,12 @@ def simplify(points, faces, ratio=None, **kw):
return points, list(range(max(1, int(round(len(faces) * (1.0 - ratio))))))
`;
-const stubPostprocess = ({ backend = 'metal', hasDr = true }) => `_BACKEND = ${backend === null ? 'None' : `'${backend}'`}
+const stubPostprocess = ({ backend = 'metal', hasDr = true }) => `import os
+# Recorded AT IMPORT TIME. The real module imports torch, and
+# PYTORCH_ENABLE_MPS_FALLBACK is only honored if it is set before that happens —
+# so capturing it here is what makes the ordering testable without torch.
+ENV_AT_IMPORT = os.environ.get('PYTORCH_ENABLE_MPS_FALLBACK')
+_BACKEND = ${backend === null ? 'None' : `'${backend}'`}
_HAS_DR = ${hasDr ? 'True' : 'False'}
_HAS_FLEX_GEMM = True
CALLS = []
@@ -38,7 +43,7 @@ def to_glb(**kw):
// Mirrors the shape of upstream generate.py's Metal bake branch: derive a ratio
// from the 200K clamp, simplify, then hand the result to to_glb with the same
// clamp as `decimation_target`.
-const FAKE_GENERATE = `import argparse, json, fast_simplification, o_voxel.postprocess
+const FAKE_GENERATE = `import argparse, json, os, fast_simplification, o_voxel.postprocess
p = argparse.ArgumentParser()
p.add_argument("image")
p.add_argument("--output", default="out")
@@ -58,6 +63,8 @@ print("RESULT " + json.dumps({
"texture_size": a.texture_size,
"seed": a.seed,
"steps": a.steps,
+ "mps_fallback_at_o_voxel_import": o_voxel.postprocess.ENV_AT_IMPORT,
+ "mps_fallback_now": os.environ.get("PYTORCH_ENABLE_MPS_FALLBACK"),
}))
`;
@@ -105,6 +112,31 @@ describe.skipIf(!pyBin)('trellis2GenerateRunner', () => {
.toBe('local-import-ok:4096');
});
+ it('sets PYTORCH_ENABLE_MPS_FALLBACK before anything can import torch', () => {
+ // Regression guard, and the bug it guards is not hypothetical: this adapter
+ // imports o_voxel.postprocess (which imports torch) to install the decimation
+ // patch. generate.py sets this flag at ITS module top, which is too late once
+ // the adapter has already initialized torch — and MPS has no segment_reduce
+ // kernel, so every render died ~3 minutes in with NotImplementedError from the
+ // first sampler step. Asserting on the value the stub captured AT IMPORT is what
+ // makes the ordering, not just the final value, the thing under test.
+ writeStubs();
+ const r = resultOf(run(['--decimation-target', '1000000', '--', join(dir, 'generate.py'), 'a.png']));
+ expect(r.mps_fallback_at_o_voxel_import).toBe('1');
+ expect(r.mps_fallback_now).toBe('1');
+ });
+
+ it('lets an explicit caller env win over the preamble defaults', () => {
+ // setdefault, not assignment — otherwise the adapter would silently override a
+ // deliberate choice by whoever spawned it.
+ writeStubs();
+ const r = resultOf(run(
+ ['--', join(dir, 'generate.py'), 'a.png'],
+ { env: { PYTORCH_ENABLE_MPS_FALLBACK: '0' } },
+ ));
+ expect(r.mps_fallback_at_o_voxel_import).toBe('0');
+ });
+
it('passes upstream arguments through untouched after the `--` separator', () => {
writeStubs();
const r = resultOf(run([
diff --git a/server/services/imageTo3d/trellis2NormalBake.py b/server/services/imageTo3d/trellis2NormalBake.py
new file mode 100644
index 0000000000..8acd8dc873
--- /dev/null
+++ b/server/services/imageTo3d/trellis2NormalBake.py
@@ -0,0 +1,228 @@
+"""Bake a tangent-space normal map from the pre-decimation mesh onto the exported one.
+
+## Why
+
+Decimation is the largest single quality loss in the Apple Silicon path: the
+`1024_cascade` decoder emits ~22.7M faces and the exported GLB carries ~1M. Raising
+the target recovers silhouette and large-scale form, but a browser cannot be handed
+22.7M faces, so the fine surface relief is gone for good — as *geometry*. As
+*shading* it is recoverable, which is what a normal map is for: it re-encodes the
+high-resolution surface orientation into a texture the low-resolution mesh samples,
+so lighting responds to detail the triangles no longer carry.
+
+The correspondence this needs is the same one the base-color bake already computes
+(`o_voxel.postprocess.to_glb`: UV-rasterize the decimated mesh, interpolate a 3D
+position per texel, then `bvh.unsigned_distance(..., return_uvw=True)` against the
+source mesh). This module re-derives that correspondence as a post-pass rather than
+patching into third-party internals, and pays one extra BVH build plus one extra UV
+rasterization for it.
+
+## Why a post-pass and not a hook
+
+`to_glb` receives the mesh generate.py *already* pre-simplified, so its internal
+"original" is the decimated mesh — there is no high-resolution surface left inside it
+to sample from. The only place the full mesh exists is generate.py's scope, which the
+runner captures at its `fast_simplification.simplify` interception point. So the bake
+has to run outside `to_glb`, against that captured mesh.
+
+## Source cap
+
+A BVH over 22.7M faces is beyond any published Apple-Silicon result (mtlbvh's own fix
+commit reports a clean run at 8.6M; its regression test covers 498K). So the source is
+capped: above `max_source_faces` it is decimated to that ceiling *for the normal
+source only*. At the default that is still ~8x the geometry of the exported mesh, so
+nearly all the recoverable relief survives, while the BVH stays inside sizes anyone
+has actually run. This is a deliberate, documented ceiling rather than an attempt to
+find the true limit at the cost of the user's render.
+"""
+
+import numpy as np
+
+
+# mtlbvh's fix commit reports a clean result at this size; nothing published goes
+# higher. Also the point past which a 22.7M-face BVH stops being a known quantity.
+DEFAULT_MAX_SOURCE_FACES = 8_000_000
+
+# Texels per BVH query batch. The full 4096^2 atlas is 16.7M texels; querying them in
+# one call allocates several float32 (N,3) buffers at once, which is where a bake on a
+# memory-pressured machine would fall over rather than in the BVH itself.
+QUERY_CHUNK = 1_000_000
+
+
+def _unit(v, axis=-1, eps=1e-12):
+ """Normalize without dividing by zero — degenerate rows come back as zeros."""
+ n = np.linalg.norm(v, axis=axis, keepdims=True)
+ return np.divide(v, n, out=np.zeros_like(v), where=n > eps)
+
+
+def compute_vertex_normals(vertices, faces):
+ """Area-weighted vertex normals.
+
+ Area weighting rather than uniform: the source mesh comes out of a marching-style
+ decoder with wildly uneven triangle areas, and uniform averaging lets a cluster of
+ slivers outvote the one large triangle that actually describes the surface.
+ """
+ v = vertices[faces]
+ # Un-normalized cross product IS twice the triangle area times the unit normal,
+ # so accumulating it raw gives area weighting for free.
+ fn = np.cross(v[:, 1] - v[:, 0], v[:, 2] - v[:, 0])
+ out = np.zeros_like(vertices, dtype=np.float64)
+ for i in range(3):
+ np.add.at(out, faces[:, i], fn)
+ return _unit(out).astype(np.float32)
+
+
+def compute_uv_tangents(vertices, faces, uvs):
+ """Per-vertex tangents from UV derivatives (the Lengyel construction).
+
+ The normal map is tangent-space, so it is only meaningful against the same tangent
+ basis a renderer will reconstruct. glTF's convention is a right-handed basis built
+ from the UV gradient, which is what this computes; three.js and every other glTF
+ viewer rebuild it the same way, so a mismatch here shows up as lighting that moves
+ the wrong way rather than as an obvious error.
+ """
+ p = vertices[faces]
+ t = uvs[faces]
+ e1, e2 = p[:, 1] - p[:, 0], p[:, 2] - p[:, 0]
+ du1, du2 = t[:, 1] - t[:, 0], t[:, 2] - t[:, 0]
+ # Degenerate UV triangles (zero area in texture space) have no defined tangent.
+ # Their determinant is ~0; guard it and let those faces contribute nothing rather
+ # than exploding into NaN and poisoning every vertex they touch.
+ det = du1[:, 0] * du2[:, 1] - du2[:, 0] * du1[:, 1]
+ r = np.divide(1.0, det, out=np.zeros_like(det), where=np.abs(det) > 1e-12)
+ tangent = (e1 * du2[:, 1:2] - e2 * du1[:, 1:2]) * r[:, None]
+ out = np.zeros_like(vertices, dtype=np.float64)
+ for i in range(3):
+ np.add.at(out, faces[:, i], tangent)
+ return out.astype(np.float32)
+
+
+def _extract_mesh(glb):
+ """Pull the single UV-mapped mesh out of whatever to_glb returned.
+
+ trimesh hands back either a Trimesh or a Scene depending on version and content,
+ and the bake needs exactly one mesh with UVs. Raise rather than guess: silently
+ baking against the wrong geometry produces a plausible-looking normal map that is
+ subtly wrong everywhere, which is far worse than a clear failure.
+ """
+ meshes = list(glb.geometry.values()) if hasattr(glb, 'geometry') else [glb]
+ if len(meshes) != 1:
+ raise ValueError(f"normal bake expects exactly one mesh, got {len(meshes)}")
+ mesh = meshes[0]
+ uv = getattr(getattr(mesh, 'visual', None), 'uv', None)
+ if uv is None:
+ raise ValueError("normal bake requires the exported mesh to carry UVs")
+ return mesh, np.asarray(uv, dtype=np.float32)
+
+
+def bake_normal_map(
+ glb,
+ source_vertices,
+ source_faces,
+ texture_size,
+ max_source_faces=DEFAULT_MAX_SOURCE_FACES,
+ simplify=None,
+ verbose=False,
+):
+ """Attach a tangent-space normal map to `glb`, sampled from the source mesh.
+
+ Mutates and returns `glb`. `simplify` is injected (the runner passes the ORIGINAL
+ `fast_simplification.simplify`, because by bake time the module attribute has been
+ replaced by the decimation-target patch — calling the patched one here would
+ silently retarget the source cap to the viewer mesh's target and defeat the whole
+ pass).
+ """
+ import torch
+ import mtlbvh
+ import mtldiffrast.torch as dr
+ from PIL import Image
+
+ mesh, uvs = _extract_mesh(glb)
+ lo_v = np.asarray(mesh.vertices, dtype=np.float32)
+ lo_f = np.asarray(mesh.faces, dtype=np.int32)
+
+ src_v = np.asarray(source_vertices, dtype=np.float32)
+ src_f = np.asarray(source_faces, dtype=np.int32)
+ if len(src_f) > max_source_faces and simplify is not None:
+ if verbose:
+ print(f" normal source: {len(src_f):,} -> {max_source_faces:,} faces", flush=True)
+ src_v, src_f = simplify(src_v, src_f, 1.0 - (max_source_faces / len(src_f)))
+ src_v = np.asarray(src_v, dtype=np.float32)
+ src_f = np.asarray(src_f, dtype=np.int32)
+
+ # The source's own smooth normals are what gets encoded. Face normals would give a
+ # faceted map that reads as decoder noise at this triangle density.
+ src_vn = compute_vertex_normals(src_v, src_f)
+
+ device = torch.device('mps' if torch.backends.mps.is_available() else 'cpu')
+ ctx = dr.MtlRasterizeContext()
+
+ # Rasterize the EXPORTED mesh in UV space, exactly as the colour bake does: UVs to
+ # clip space, z=0, w=1. Chunked over faces with the same face-id-in-alpha trick, so
+ # a large atlas does not allocate one giant intermediate.
+ uv_t = torch.as_tensor(uvs, device=device)
+ lo_f_t = torch.as_tensor(lo_f, device=device, dtype=torch.int32)
+ uv_clip = torch.cat([
+ uv_t * 2 - 1,
+ torch.zeros_like(uv_t[:, :1]),
+ torch.ones_like(uv_t[:, :1]),
+ ], dim=-1).unsqueeze(0)
+ rast = torch.zeros((1, texture_size, texture_size, 4), device=device, dtype=torch.float32)
+ for i in range(0, lo_f.shape[0], 100_000):
+ chunk, _ = dr.rasterize(
+ ctx, uv_clip, lo_f_t[i:i + 100_000], resolution=[texture_size, texture_size],
+ )
+ hit = chunk[..., 3:4] > 0
+ chunk[..., 3:4] += i
+ rast = torch.where(hit, chunk, rast)
+ mask = rast[0, ..., 3] > 0
+
+ # Per-texel geometry of the low-res surface: position (where to sample the source),
+ # plus the tangent frame the result has to be expressed in.
+ lo_v_t = torch.as_tensor(lo_v, device=device)
+ lo_vn_t = torch.as_tensor(compute_vertex_normals(lo_v, lo_f), device=device)
+ lo_vt_t = torch.as_tensor(compute_uv_tangents(lo_v, lo_f, uvs), device=device)
+ pos = dr.interpolate(lo_v_t.unsqueeze(0), rast, lo_f_t)[0][0][mask]
+ n_lo = torch.nn.functional.normalize(
+ dr.interpolate(lo_vn_t.unsqueeze(0), rast, lo_f_t)[0][0][mask], dim=-1)
+ t_lo = dr.interpolate(lo_vt_t.unsqueeze(0), rast, lo_f_t)[0][0][mask]
+ # Gram-Schmidt: re-orthogonalize the interpolated tangent against the interpolated
+ # normal. Interpolation does not preserve orthogonality, and a skewed basis tilts
+ # every sampled normal by a varying amount across each triangle.
+ t_lo = torch.nn.functional.normalize(t_lo - n_lo * (t_lo * n_lo).sum(-1, keepdim=True), dim=-1)
+ b_lo = torch.cross(n_lo, t_lo, dim=-1)
+
+ bvh = mtlbvh.MtlBVH(torch.as_tensor(src_v), torch.as_tensor(src_f))
+ src_vn_t = torch.as_tensor(src_vn, device=pos.device)
+ src_f_t = torch.as_tensor(src_f, device=pos.device, dtype=torch.long)
+
+ out = torch.zeros((pos.shape[0], 3), device=pos.device, dtype=torch.float32)
+ for start in range(0, pos.shape[0], QUERY_CHUNK):
+ sl = slice(start, start + QUERY_CHUNK)
+ _, face_id, uvw = bvh.unsigned_distance(pos[sl], return_uvw=True)
+ # Interpolate the source's vertex normals at the hit barycentrics — this is the
+ # high-resolution orientation the exported triangles can no longer express.
+ n_hi = torch.nn.functional.normalize(
+ (src_vn_t[src_f_t[face_id.long()]] * uvw.unsqueeze(-1)).sum(dim=1), dim=-1)
+ # Project into the low-res tangent basis.
+ out[sl] = torch.stack([
+ (n_hi * t_lo[sl]).sum(-1),
+ (n_hi * b_lo[sl]).sum(-1),
+ (n_hi * n_lo[sl]).sum(-1),
+ ], dim=-1)
+ out = torch.nn.functional.normalize(out, dim=-1)
+
+ # Unmapped texels get flat (0,0,1) rather than black: a black normal texel decodes
+ # to a zero-length vector and renders as a hole in the lighting, and bilinear
+ # filtering drags that across every chart edge.
+ img = torch.zeros((texture_size, texture_size, 3), device=pos.device, dtype=torch.float32)
+ img[..., 2] = 1.0
+ img[mask] = out
+ encoded = ((img * 0.5 + 0.5).clamp(0, 1) * 255).round().to(torch.uint8).cpu().numpy()
+
+ material = mesh.visual.material
+ material.normalTexture = Image.fromarray(encoded, mode='RGB')
+ if verbose:
+ covered = int(mask.sum().item())
+ print(f" normal map: {texture_size}x{texture_size}, {covered:,} texels covered", flush=True)
+ return glb