Added Auto Retopo works on CUDA

This commit is contained in:
Bruno Fargnoli 2026-07-08 23:08:30 +02:00
parent ae4049af48
commit 3d0b2cc98a
15 changed files with 553 additions and 40 deletions

View file

@ -36,7 +36,28 @@ run.bat
```
First run creates `.venv`, installs `requirements.txt`, and serves on
`0.0.0.0:8200`. Override with env vars:
`0.0.0.0:8200`.
### GPU acceleration (NVIDIA)
On first setup `run.bat` runs `detect_cuda.py`: if an NVIDIA GPU is present it
installs `requirements-nvidia.txt` (NVIDIA Warp) plus the `cupy-cudaXXx` wheel
matching the CUDA version reported by `nvidia-smi` (e.g. CUDA 13.x → `cupy-cuda13x`).
These accelerate the Auto Retopo **watertight-shell** (CuPy) and **surface-projection**
(Warp) stages; the **remesh** stage has no GPU port and always runs on the CPU.
Both are auto-detected at runtime, so the service falls back to CPU when they are
absent. Two setup env vars:
| Variable | Effect |
| -------------------------- | --------------------------------------------------- |
| `MESHTOOLS_SKIP_GPU=1` | Skip GPU detection/install (CPU-only setup) |
| `MESHTOOLS_CUPY_PACKAGE` | Force a specific CuPy wheel, e.g. `cupy-cuda12x` |
To add GPU support to an existing `.venv`, activate it and run
`pip install -r requirements-nvidia.txt` then `pip install cupy-cuda13x` (match
your CUDA major).
Override host/port etc. with env vars:
| Variable | Default |
| -------------------------- | ------------------------ |

View file

@ -99,6 +99,13 @@ class AutoRetopoOptions(BaseModel):
relax_strength: float = Field(default=0.4, ge=0.0, le=1.0,
description="Tangential relaxation factor per iteration.")
# --- compute backend (shell stage only) ---
device: Literal["auto", "cpu", "cuda"] = Field(
default="auto",
description="Compute backend for the watertight shell stage: 'auto' uses an NVIDIA "
"GPU (via CuPy) when available and falls back to CPU; 'cpu' forces CPU; "
"'cuda' forces GPU. Other stages always run on CPU.")
# --- misc ---
seed: int = Field(default=0, ge=0, description="RNG seed for reproducibility.")

View file

@ -10,6 +10,7 @@ import trimesh
from ..schemas import AutoRetopoOptions
from .autoretopo import AutoRetopo, RetopoConfig
from .autoretopo import gpu
def run_auto_retopo(mesh: trimesh.Trimesh, options: AutoRetopoOptions, progress=None) -> tuple[trimesh.Trimesh, dict, None]:
@ -33,11 +34,18 @@ def run_auto_retopo(mesh: trimesh.Trimesh, options: AutoRetopoOptions, progress=
project_iters=options.project_iters,
project_clamp=options.project_clamp,
relax_strength=options.relax_strength,
device=options.device,
seed=options.seed,
verbose=False,
)
result = AutoRetopo(cfg).run(mesh, progress=progress)
try:
result = AutoRetopo(cfg).run(mesh, progress=progress)
finally:
# Long-running server: hand each run's GPU pool back to the driver so the
# footprint doesn't accumulate across Auto Retopo requests. Also runs on
# the error path (e.g. a shell-stage OOM) so a failed run cleans up too.
gpu.free_gpu_memory()
stats = {
"metrics": result.metrics,

View file

@ -36,6 +36,12 @@ class RetopoConfig:
project_clamp: float = 1.5 # max per-vertex move as a multiple of local edge length
relax_strength: float = 0.4 # tangential relaxation factor per iteration (0..1)
# --- compute backend (shell stage only) ---
device: str = "auto" # "auto": GPU if an NVIDIA CUDA device + CuPy are
# present, else CPU. "cpu" forces CPU; "cuda" forces
# GPU (errors if unavailable). Only the watertight
# shell stage is GPU-accelerated; everything else is CPU.
# --- misc ---
seed: int = 0
verbose: bool = True

View file

@ -0,0 +1,178 @@
"""Optional CUDA acceleration for the grid-based shell stage.
The watertight-shell stage (surface voxelization, morphological closing, the
Euclidean distance-transform signed-distance field and its Gaussian blur) is
embarrassingly-parallel dense-array work that maps 1:1 onto CuPy and
`cupyx.scipy.ndimage`. This module resolves a *backend* — an array module (`xp`)
plus an ndimage module (`ndi`) — from a device request, falling back to
NumPy/SciPy whenever CuPy is missing or no NVIDIA GPU is present.
Everything else in the pipeline (marching cubes, and all the pymeshlab
remesh/decimate/quad work) stays on the CPU: those algorithms have no CUDA
drop-in, so the shell stage is the only place a GPU helps here.
Nothing imports CuPy at module load: the import is attempted lazily and cached,
so the service runs unchanged on machines without a CUDA toolkit and never pays
the import cost when running on CPU.
"""
from __future__ import annotations
import numpy as np
from scipy import ndimage as _cpu_ndi
# Cache: (cupy_module, cupyx_ndimage_module) once a GPU is confirmed usable,
# False once we've probed and found none. None means "not probed yet".
_gpu = None
# Cache for the (separate, optional) NVIDIA Warp runtime used by the projection
# stage's GPU closest-point queries. Same tri-state convention as `_gpu`.
_warp = None
def _probe_gpu():
global _gpu
if _gpu is not None:
return _gpu
try:
import cupy as cp
from cupyx.scipy import ndimage as cndi
if cp.cuda.runtime.getDeviceCount() < 1:
_gpu = False
return _gpu
# Touch the device so a driver/toolkit mismatch surfaces here (at probe
# time) rather than deep inside a run.
cp.zeros(1, dtype=cp.float32).sum()
_gpu = (cp, cndi)
except Exception:
_gpu = False
return _gpu
def cuda_available() -> bool:
"""True when CuPy is importable and at least one NVIDIA CUDA device works."""
return bool(_probe_gpu())
def gpu_name() -> str | None:
g = _probe_gpu()
if not g:
return None
cp = g[0]
try:
name = cp.cuda.runtime.getDeviceProperties(0)["name"]
return name.decode() if isinstance(name, (bytes, bytearray)) else str(name)
except Exception:
return "CUDA device"
def _probe_warp():
"""Lazily import NVIDIA Warp and confirm a usable CUDA device.
Warp is a distinct optional dependency from CuPy (it powers the projection
stage's GPU closest-point queries, not the shell grid ops), so it gets its
own probe. Never imported at module load.
"""
global _warp
if _warp is not None:
return _warp
try:
import warp as wp
# Suppress the init banner. Warp >= 1.x renamed `config.quiet` to a log
# level; set whichever the installed version exposes.
try:
wp.config.log_level = wp.LOG_WARNING
except Exception:
try:
wp.config.quiet = True
except Exception:
pass
wp.init()
if wp.get_cuda_device_count() < 1:
_warp = False
return _warp
_warp = wp
except Exception:
_warp = False
return _warp
def warp_cuda_available() -> bool:
"""True when NVIDIA Warp is importable and a CUDA device is present."""
return bool(_probe_warp())
def free_gpu_memory():
"""Release cached device memory held by the GPU backends back to the driver.
Both CuPy and Warp keep freed device blocks in an internal pool for reuse, so
in a long-running server the GPU footprint of each Auto Retopo run stays
resident (and ratchets up to the largest run's peak) — visible in nvidia-smi
as memory that "never clears". Call this once per run, after the result is
back on the host.
Uses the cached probe results only (never triggers a probe), so it is a cheap
no-op on CPU-only installs or runs that never touched the GPU.
"""
g, w = _gpu, _warp
if not g and not w:
return
import gc
# Drop any now-unreferenced Warp meshes/arrays (their finalizers free the
# device buffers) before asking the pools to release blocks.
gc.collect()
if g:
try:
cp = g[0]
cp.get_default_memory_pool().free_all_blocks()
cp.get_default_pinned_memory_pool().free_all_blocks()
except Exception:
pass
if w:
try:
w.synchronize()
except Exception:
pass
class Backend:
"""A resolved compute backend: `.xp` (array module) + `.ndi` (ndimage)."""
def __init__(self, xp, ndi, on_gpu: bool, name: str):
self.xp = xp
self.ndi = ndi
self.on_gpu = on_gpu
self.name = name
def asarray(self, a):
return self.xp.asarray(a)
def tonumpy(self, a):
"""Bring an array back to host memory regardless of backend."""
if self.on_gpu:
return self.xp.asnumpy(a)
return np.asarray(a)
def resolve_backend(device: str = "auto") -> Backend:
"""Pick a compute backend from a device request.
device:
"auto" — GPU when an NVIDIA CUDA device and CuPy are both available,
otherwise CPU (the default; never raises).
"cuda" — GPU; raises RuntimeError if unavailable (explicit user choice).
"cpu" — always NumPy/SciPy.
"""
device = (device or "auto").lower()
if device == "cpu":
return Backend(np, _cpu_ndi, False, "CPU")
g = _probe_gpu()
if g:
cp, cndi = g
return Backend(cp, cndi, True, gpu_name() or "CUDA")
if device == "cuda":
raise RuntimeError(
"CUDA device requested but unavailable. Install the optional CuPy "
"wheel matching your CUDA toolkit (e.g. `pip install cupy-cuda12x`) "
"and ensure an NVIDIA GPU is present.")
return Backend(np, _cpu_ndi, False, "CPU")

View file

@ -15,7 +15,7 @@ import numpy as np
import trimesh
from .config import RetopoConfig
from . import ingest, shell, remesh, project, metrics, meshutil
from . import ingest, shell, remesh, project, metrics, meshutil, gpu
class RetopoResult:
@ -73,8 +73,13 @@ class AutoRetopo:
# Stage 1: base layer
t0 = time.time()
report("shell", 0.08, "Building watertight shell" if cfg.watertight else "Preparing surface")
backend = gpu.resolve_backend(cfg.device) # cached probe; also used for the UI message
report("shell",
0.08,
(f"Building watertight shell ({backend.name})" if cfg.watertight
else "Preparing surface"))
if cfg.watertight:
self._log(f"[shell] backend={backend.name} (device={cfg.device})")
res = cfg.shell_resolution
fitted, peak_mb = shell.fit_resolution_to_budget(original, res, cfg.max_memory_gb)
if fitted != res:
@ -82,7 +87,7 @@ class AutoRetopo:
f"{cfg.max_memory_gb:.1f} GB budget (est. peak {peak_mb:.0f} MB)")
V, F = shell.voxel_shell(original, fitted, cfg.shell_close_iter,
cfg.shell_smooth, cfg.shell_samples_per_pitch,
taubin_steps=cfg.shell_taubin)
taubin_steps=cfg.shell_taubin, device=cfg.device)
V, F = shell.largest_component(V, F)
self._log(f"[shell] {len(F)} faces (watertight base)")
else:
@ -120,11 +125,17 @@ class AutoRetopo:
# only in surface mode, where the remesher already reprojects onto the
# original and a closest-point snap on noisy hard surfaces hurts.
t0 = time.time()
report("project", 0.72, "Projecting to surface")
if cfg.project and (cfg.watertight or not cfg.preserve_features):
do_project = cfg.project and (cfg.watertight or not cfg.preserve_features)
proj_backend = ("GPU (Warp)" if (do_project and cfg.device != "cpu"
and gpu.warp_cuda_available()) else "CPU")
report("project", 0.72,
f"Projecting to surface ({proj_backend})" if do_project else "Projecting to surface")
if do_project:
self._log(f"[project] backend={proj_backend}")
V = project.project_to_surface(
V, F, original, iters=cfg.project_iters,
clamp=cfg.project_clamp, relax_strength=cfg.relax_strength)
clamp=cfg.project_clamp, relax_strength=cfg.relax_strength,
device=cfg.device)
V, F = remesh.finalize_watertight(V, F, verbose=cfg.verbose) if cfg.watertight else remesh.clean_slivers(V, F)
t["project"] = time.time() - t0

View file

@ -28,6 +28,35 @@ from __future__ import annotations
import numpy as np
import trimesh
from . import gpu
class _TrimeshSurfaceQuery:
"""CPU closest-point query wrapper matching WarpSurfaceQuery's 2-tuple return
(drops trimesh's distance term, which this stage does not use)."""
def __init__(self, target_mesh):
self._pq = trimesh.proximity.ProximityQuery(target_mesh)
def on_surface(self, pts):
closest, _dist, tid = self._pq.on_surface(pts)
return np.asarray(closest), np.asarray(tid)
def _make_surface_query(target_mesh, device):
"""Build a closest-point query, GPU-accelerated (NVIDIA Warp) when the device
request allows and a Warp+CUDA runtime is present; CPU (trimesh) otherwise.
Both backends expose `.on_surface(pts) -> (closest_points, face_ids)`.
"""
if device != "cpu" and gpu.warp_cuda_available():
try:
from .warp_proximity import WarpSurfaceQuery
return WarpSurfaceQuery(target_mesh)
except Exception:
pass # fall back to CPU if Warp construction/compile fails
return _TrimeshSurfaceQuery(target_mesh)
def _vertex_adjacency(n_verts, F):
e = np.vstack([F[:, [0, 1]], F[:, [1, 2]], F[:, [2, 0]]])
@ -62,7 +91,7 @@ def _lap_smooth(D, idx, ptr, deg, rounds, alpha=0.7):
def project_to_surface(V, F, target_mesh, iters=8, clamp=1.5, relax_strength=0.4,
field_smooth_rounds=3, final_snap_clamp=0.4):
field_smooth_rounds=3, final_snap_clamp=0.4, device="auto"):
"""Project (V,F) onto target_mesh.
Per iteration: (1) tangential relaxation - slide each vertex toward its
@ -72,7 +101,19 @@ def project_to_surface(V, F, target_mesh, iters=8, clamp=1.5, relax_strength=0.4
smoothed as a field before applying (kills crease zigzag and thin-geometry
punch-through). A final clamped normal-only micro-snap firms up creases.
`clamp` is kept for API compatibility."""
pq = trimesh.proximity.ProximityQuery(target_mesh)
pq = _make_surface_query(target_mesh, device)
try:
return _project(pq, V, F, target_mesh, iters, relax_strength,
field_smooth_rounds, final_snap_clamp)
finally:
# Release the (GPU) BVH as soon as projection is done, regardless of how
# we exit, so it doesn't linger until the next garbage-collection cycle.
if hasattr(pq, "free"):
pq.free()
def _project(pq, V, F, target_mesh, iters, relax_strength,
field_smooth_rounds, final_snap_clamp):
tgt_fn = np.asarray(target_mesh.face_normals)
adjacency = _vertex_adjacency(len(V), F)
idx, ptr, deg = _csr(adjacency)
@ -87,7 +128,7 @@ def project_to_surface(V, F, target_mesh, iters=8, clamp=1.5, relax_strength=0.4
d -= normals * np.sum(d * normals, axis=1)[:, None]
Vc = Vc + relax_strength * d
# smoothed displacement toward the original surface
closest, _, tid = pq.on_surface(Vc)
closest, tid = pq.on_surface(Vc)
D = closest - Vc
agree = np.sum(normals * tgt_fn[tid], axis=1) >= 0.0
D *= agree[:, None]
@ -96,7 +137,7 @@ def project_to_surface(V, F, target_mesh, iters=8, clamp=1.5, relax_strength=0.4
if final_snap_clamp:
normals = trimesh.Trimesh(Vc, F, process=False).vertex_normals
closest, _, tid = pq.on_surface(Vc)
closest, tid = pq.on_surface(Vc)
D = closest - Vc
agree = np.sum(normals * tgt_fn[tid], axis=1) >= 0.0
D *= agree[:, None]

View file

@ -33,9 +33,10 @@ input triangle count or size.
from __future__ import annotations
import numpy as np
import trimesh
from scipy import ndimage
from skimage import measure
from .gpu import resolve_backend
def _lattice_bary(k: int) -> np.ndarray:
"""Barycentric lattice for subdivision level k: (i/k, j/k, 1-i/k-j/k), i+j<=k."""
@ -45,25 +46,35 @@ def _lattice_bary(k: int) -> np.ndarray:
return np.stack([a, b, 1.0 - a - b], axis=1) # (P, 3)
def bounded_surface_voxelize(mesh, pitch, samples_per_pitch=2.0, kmax=128, chunk=200_000):
def bounded_surface_voxelize(mesh, pitch, samples_per_pitch=2.0, kmax=128,
chunk=200_000, backend=None):
"""Memory-bounded surface voxelization.
Returns (occupancy_grid: bool[X,Y,Z], origin: float[3]). The occupancy is the set
of voxels touched by the surface, sampled densely enough (lattice spacing <=
pitch/samples_per_pitch) that flood-fill cannot leak through. Peak memory is
O(grid + chunk), independent of triangle size distribution.
The grid lives on `backend`'s array module (CuPy on GPU, NumPy on CPU); the
barycentric lattice, einsum scatter and clamp all run there. `origin` stays a
NumPy array — it is consumed on the host after marching cubes.
"""
be = backend or resolve_backend("cpu")
xp = be.xp
lo = mesh.bounds[0].astype(np.float64)
hi = mesh.bounds[1].astype(np.float64)
pad = 3
dims = (np.ceil((hi - lo) / pitch).astype(int) + 1 + 2 * pad)
origin = lo - pad * pitch
grid = np.zeros(tuple(int(d) for d in dims), dtype=bool)
dmax = np.array(dims, np.int32) - 1
grid = xp.zeros(tuple(int(d) for d in dims), dtype=bool)
dmax = xp.asarray(np.array(dims, np.int32) - 1)
origin_x = xp.asarray(origin)
tris = np.asarray(mesh.triangles, np.float64) # (F, 3, 3)
if len(tris) == 0:
return grid, origin
# Edge lengths / subdivision level `k` are cheap and stay on the host so the
# np.unique bucketing below drives the (GPU or CPU) scatter loop identically.
edges = np.stack([
np.linalg.norm(tris[:, 1] - tris[:, 0], axis=1),
np.linalg.norm(tris[:, 2] - tris[:, 1], axis=1),
@ -73,21 +84,22 @@ def bounded_surface_voxelize(mesh, pitch, samples_per_pitch=2.0, kmax=128, chunk
for kk in np.unique(k):
sel = np.where(k == kk)[0]
bary = _lattice_bary(int(kk)) # (P, 3)
bary = xp.asarray(_lattice_bary(int(kk))) # (P, 3)
P = len(bary)
step = max(1, chunk // max(P, 1)) # rows per chunk so rows*P<=chunk
for s in range(0, len(sel), step):
T = tris[sel[s:s + step]] # (m, 3, 3)
pts = np.einsum("pj,mjc->mpc", bary, T).reshape(-1, 3)
vi = np.floor((pts - origin) / pitch).astype(np.int32)
np.clip(vi, 0, dmax, out=vi)
T = xp.asarray(tris[sel[s:s + step]]) # (m, 3, 3)
pts = xp.einsum("pj,mjc->mpc", bary, T).reshape(-1, 3)
vi = xp.floor((pts - origin_x) / pitch).astype(xp.int32)
vi = xp.clip(vi, 0, dmax)
grid[vi[:, 0], vi[:, 1], vi[:, 2]] = True
return grid, origin
def voxel_shell(mesh: trimesh.Trimesh, resolution: int = 256,
close_iter: int = 1, smooth_sigma: float = 1.4,
samples_per_pitch: float = 2.0, taubin_steps: int = 10):
samples_per_pitch: float = 2.0, taubin_steps: int = 10,
device: str = "auto"):
"""Watertight shell via an EDT signed-distance field.
Earlier versions extracted the iso-surface from a *blurred binary* occupancy,
@ -100,26 +112,32 @@ def voxel_shell(mesh: trimesh.Trimesh, resolution: int = 256,
real features survive. A few Taubin passes on the dense shell remove what's
left; the projection stage later restores exact geometry from the original.
"""
be = resolve_backend(device)
xp, ndi = be.xp, be.ndi
diag = float(np.linalg.norm(mesh.extents))
pitch = diag / max(32, int(resolution))
dense, origin = bounded_surface_voxelize(mesh, pitch, samples_per_pitch)
if not dense.any():
# Grid ops (voxelize -> close -> EDT -> blur) run on the resolved backend;
# marching cubes and Taubin below have no CUDA drop-in, so the field is
# brought back to host memory before them.
dense, origin = bounded_surface_voxelize(mesh, pitch, samples_per_pitch, backend=be)
if not bool(dense.any()):
raise RuntimeError("Voxelization produced an empty volume; lower shell_resolution.")
solid = ndimage.binary_dilation(dense, iterations=close_iter) if close_iter else dense.copy()
solid = ndimage.binary_fill_holes(solid)
solid = ndi.binary_dilation(dense, iterations=close_iter) if close_iter else dense.copy()
solid = ndi.binary_fill_holes(solid)
if close_iter:
solid = ndimage.binary_erosion(solid, iterations=close_iter)
solid = ndi.binary_erosion(solid, iterations=close_iter)
solid |= dense
del dense
# signed distance: positive outside, negative inside; zero level = surface
sdf = ndimage.distance_transform_edt(~solid).astype(np.float32)
sdf -= ndimage.distance_transform_edt(solid).astype(np.float32)
sdf = ndi.distance_transform_edt(~solid).astype(xp.float32)
sdf -= ndi.distance_transform_edt(solid).astype(xp.float32)
del solid
if smooth_sigma:
sdf = ndimage.gaussian_filter(sdf, float(smooth_sigma))
sdf = ndi.gaussian_filter(sdf, float(smooth_sigma))
sdf = be.tonumpy(sdf)
verts, faces, _, _ = measure.marching_cubes(sdf, level=0.0)
del sdf

View file

@ -0,0 +1,74 @@
"""GPU closest-point-on-surface queries via NVIDIA Warp.
This module is imported *lazily* — only after `gpu.warp_cuda_available()` has
confirmed a working Warp+CUDA install — so the top-level `import warp` (and the
`@wp.kernel` compilation below) never runs on CPU-only machines.
`WarpSurfaceQuery` mirrors the slice of `trimesh.proximity.ProximityQuery` that
the projection stage uses: build once from the target mesh, then answer batched
closest-point queries, returning `(closest_points, face_ids)` exactly like
`ProximityQuery.on_surface` (minus the distance, which the caller discards).
"""
from __future__ import annotations
import numpy as np
import warp as wp
@wp.kernel
def _closest_point_kernel(mesh: wp.uint64,
points: wp.array(dtype=wp.vec3),
max_dist: wp.float32,
out_pts: wp.array(dtype=wp.vec3),
out_face: wp.array(dtype=wp.int32)):
i = wp.tid()
p = points[i]
query = wp.mesh_query_point_no_sign(mesh, p, max_dist)
if query.result:
out_pts[i] = wp.mesh_eval_position(mesh, query.face, query.u, query.v)
out_face[i] = query.face
else:
# No hit within max_dist (shouldn't happen given the generous cap):
# leave the point where it is and point at face 0 so the caller's
# normal-agreement guard simply rejects the (zero) move.
out_pts[i] = p
out_face[i] = wp.int32(0)
class WarpSurfaceQuery:
"""One-time BVH build over `target_mesh`, then GPU closest-point queries."""
def __init__(self, target_mesh, device: str = "cuda"):
self.device = device
V = np.ascontiguousarray(target_mesh.vertices, dtype=np.float32)
F = np.ascontiguousarray(np.asarray(target_mesh.faces).reshape(-1), dtype=np.int32)
with wp.ScopedDevice(device):
self._points = wp.array(V, dtype=wp.vec3)
self._indices = wp.array(F, dtype=wp.int32)
self.mesh = wp.Mesh(points=self._points, indices=self._indices)
# Generous search cap so the BVH query always reaches the surface; the
# remesh already rides close to the original, so this only bounds the
# (rare) worst case.
diag = float(np.linalg.norm(target_mesh.extents))
self._max_dist = float(max(diag * 4.0, 1e-6))
def on_surface(self, pts):
pts = np.ascontiguousarray(pts, dtype=np.float32)
n = len(pts)
with wp.ScopedDevice(self.device):
q = wp.array(pts, dtype=wp.vec3)
out_pts = wp.zeros(n, dtype=wp.vec3)
out_face = wp.zeros(n, dtype=wp.int32)
wp.launch(_closest_point_kernel, dim=n,
inputs=[self.mesh.id, q, self._max_dist, out_pts, out_face])
wp.synchronize()
closest = out_pts.numpy().astype(np.float64)
tid = out_face.numpy().astype(np.int64)
return closest, tid
def free(self):
"""Drop the device-side BVH and buffers. CPython refcounting runs each
Warp array's finalizer immediately, returning the memory to Warp's pool;
gpu.free_gpu_memory() then releases the pool to the driver."""
self.mesh = None
self._points = None
self._indices = None

View file

@ -0,0 +1,69 @@
"""Detect an NVIDIA GPU + its CUDA version and print the matching CuPy wheel.
Used by run.bat during first-time setup to auto-install GPU acceleration. Prints
the pip package name (e.g. ``cupy-cuda13x``) to stdout when an NVIDIA GPU is
found, and nothing when there isn't — so the caller can branch on empty output.
Diagnostics go to stderr. Relies only on the standard library + ``nvidia-smi``.
Override the choice with the ``MESHTOOLS_CUPY_PACKAGE`` environment variable
(e.g. set it to ``cupy-cuda12x`` to force a specific wheel).
"""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import sys
# CuPy publishes one wheel per CUDA major line. Its wheels bundle the CUDA
# runtime, so they only require a driver new enough for that major — a wheel for
# an older major still runs on a newer driver.
_WHEELS = {11: "cupy-cuda11x", 12: "cupy-cuda12x", 13: "cupy-cuda13x"}
def cuda_major() -> int | None:
"""Return the CUDA major version reported by nvidia-smi, or None."""
exe = shutil.which("nvidia-smi")
if not exe:
return None
try:
out = subprocess.run([exe], capture_output=True, text=True, timeout=20).stdout
except Exception:
return None
# Matches both classic "CUDA Version: 12.4" and newer "CUDA UMD Version: 13.3".
m = re.search(r"CUDA(?:\s+\w+)?\s+Version:\s*(\d+)\.(\d+)", out)
return int(m.group(1)) if m else None
def wheel_for_major(major: int) -> str:
pkg = _WHEELS.get(major)
if pkg:
return pkg
known = sorted(_WHEELS)
if major > known[-1]:
# Newer driver than we know about: newest wheel is forward-compatible.
print(f"[detect_cuda] CUDA {major}.x newer than known wheels; "
f"using {_WHEELS[known[-1]]}.", file=sys.stderr)
return _WHEELS[known[-1]]
# Older than anything we ship a mapping for.
print(f"[detect_cuda] CUDA {major}.x older than supported CuPy wheels; "
f"trying {_WHEELS[known[0]]} (may not work).", file=sys.stderr)
return _WHEELS[known[0]]
def main() -> None:
override = os.environ.get("MESHTOOLS_CUPY_PACKAGE")
if override:
print(override.strip())
return
major = cuda_major()
if major is None:
# No NVIDIA GPU / driver -> print nothing; caller does a CPU-only install.
print("[detect_cuda] No NVIDIA GPU detected (nvidia-smi absent or no CUDA "
"version reported).", file=sys.stderr)
return
print(wheel_for_major(major))
if __name__ == "__main__":
main()

View file

@ -0,0 +1,22 @@
# GPU acceleration for Auto Retopo on NVIDIA cards.
#
# run.bat installs this automatically (on first-time setup) when it detects an
# NVIDIA GPU, alongside a `cupy-cudaXXx` wheel chosen to match your CUDA version.
# Both accelerators are optional and auto-detected at runtime — the service falls
# back to CPU when they are absent.
#
# Manual install:
# pip install -r requirements-nvidia.txt
# pip install cupy-cuda13x # match your CUDA major: 11x / 12x / 13x
#
# Which stage each package accelerates:
# warp-lang -> "Projecting to surface" (GPU closest-point queries)
# cupy -> "Building watertight shell" (voxelize / morphology / EDT / blur)
# The "Building clean topology" (remesh) stage has no GPU port and always runs
# on the CPU.
warp-lang>=1.0
# NOTE: CuPy is intentionally NOT listed here — the correct wheel depends on your
# CUDA version (cupy-cuda11x / cupy-cuda12x / cupy-cuda13x), so run.bat detects
# and installs it separately. Install it yourself when setting up manually.

View file

@ -14,4 +14,11 @@ pymeshlab>=2023.12 # isotropic remesh / decimation / quad conversion
# --- Optional ----------------------------------------------------------------
matplotlib>=3.8 # only needed for the CLI's UV-layout / compare PNGs
retree
rtree
# --- Optional GPU acceleration (Auto Retopo) ---------------------------------
# GPU packages live in requirements-nvidia.txt and are NOT installed from this
# file. run.bat auto-detects an NVIDIA GPU on first setup and installs them
# (Warp + the cupy-cudaXXx wheel matching your CUDA version); both are also
# auto-detected at runtime with a CPU fallback when absent. See
# requirements-nvidia.txt to install them manually.

View file

@ -1,20 +1,58 @@
@echo off
:: Start the 3D Gen Studio Python mesh-processing service.
:: Creates a local virtual environment on first run, installs deps, then serves.
setlocal
:: On first run: creates a local virtual environment, installs the base (CPU)
:: requirements, then auto-detects an NVIDIA GPU and installs matching GPU
:: acceleration (Warp + the correct cupy-cudaXXx wheel for your CUDA version).
setlocal enabledelayedexpansion
cd /d "%~dp0"
if not exist ".venv\Scripts\python.exe" (
echo Creating virtual environment...
python -m venv .venv
call ".venv\Scripts\activate.bat"
python -m pip install --upgrade pip
pip install -r requirements.txt
call :setup || goto :error
) else (
call ".venv\Scripts\activate.bat"
)
:: Override host/port via env if needed, e.g. set MESHTOOLS_PORT=8200
python main.py
goto :eof
endlocal
:setup
echo Creating virtual environment...
python -m venv .venv || exit /b 1
call ".venv\Scripts\activate.bat"
python -m pip install --upgrade pip
echo.
echo Installing base (CPU) requirements...
pip install -r requirements.txt || exit /b 1
:: --- Optional NVIDIA GPU acceleration -------------------------------------
:: detect_cuda.py prints the matching CuPy wheel (e.g. cupy-cuda13x) when an
:: NVIDIA GPU is present, or nothing otherwise. Force a specific wheel with
:: MESHTOOLS_CUPY_PACKAGE, or skip GPU deps entirely with MESHTOOLS_SKIP_GPU=1.
echo.
if defined MESHTOOLS_SKIP_GPU (
echo MESHTOOLS_SKIP_GPU set -- skipping GPU acceleration ^(CPU-only install^).
exit /b 0
)
echo Detecting NVIDIA GPU / CUDA version...
set "CUPY_PKG="
for /f "usebackq delims=" %%p in (`python detect_cuda.py`) do set "CUPY_PKG=%%p"
if defined CUPY_PKG (
echo NVIDIA GPU detected -- installing GPU acceleration: !CUPY_PKG! + Warp
pip install -r requirements-nvidia.txt || exit /b 1
pip install "!CUPY_PKG!" || exit /b 1
echo GPU acceleration installed.
) else (
echo No NVIDIA GPU detected -- CPU-only install. Auto Retopo will run on the CPU.
)
exit /b 0
:error
echo.
echo Setup failed. See the messages above.
exit /b 1

View file

@ -1,7 +1,7 @@
// Auto Retopo mode left panel. Exposes every autoretopo.RetopoConfig field, runs
// the retopology via the Python mesh-tools service, and offers Keep/Revert on the
// result. Presentational: option state + handlers come from MeshEditorPage.
import { RangeField, NumberField, ToggleField } from './MeshToolField'
import { RangeField, NumberField, ToggleField, SelectField } from './MeshToolField'
import MeshToolResult from './MeshToolResult'
import MeshToolProgress from './MeshToolProgress'
@ -179,6 +179,18 @@ export default function AutoRetopoToolsPanel({
hint="Tangential relaxation factor per iteration" />
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Compute</span>
<SelectField label="Device" value={o.device}
onChange={v => setOption('device', v)} disabled={fieldsDisabled}
options={[
{ value: 'auto', label: 'Auto (GPU if NVIDIA)' },
{ value: 'cpu', label: 'CPU' },
{ value: 'cuda', label: 'CUDA (NVIDIA GPU)' },
]}
hint="Runs the watertight-shell stage (CuPy) and the surface-projection stage (NVIDIA Warp) on NVIDIA GPUs; falls back to CPU when unavailable. Remesh / 'Building clean topology' always runs on the CPU." />
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Misc</span>
<NumberField label="Seed" min={0} step={1}

View file

@ -191,6 +191,7 @@ const DEFAULT_AUTO_RETOPO_OPTIONS = {
project_iters: 10,
project_clamp: 1.5,
relax_strength: 0.4,
device: 'auto',
seed: 0,
}