"""SAM 3D Objects (Meta: a picture and an object mask -> the object's 3D mesh with vertex colours and its pose in the camera) with ONNX Runtime, reproducing InferencePipelinePointMap.run as the official notebook calls it (no mesh post-processing, no texture baking, no layout post-optimisation, vertex colours). python pipeline.py image.png mask.png out.glb [--seed 42] [--cpu] Stages (the folder's *.onnx; `vendor/` holds the original's own preprocessing / pose code, run with torch on the CPU): moge MoGe-v1 point map of the whole picture (the object's depth, the camera focal length) dino DINOv2-L/14-reg on the cropped and full picture and mask (4 passes, shared by both stages) ss_fuse the structure stage's condition tokens (+ the point-map patch embedder) ss_flow structure + pose: 25 Euler steps (t rescaled by 3), CFG 7 while t <= 0.5, the condition zeroed for the unconditional pass; latents shape [4096, 8], 6D rotation, translation, scale, translation scale ss_dec -> 64^3 occupancy; surface voxels kept (prune), downsampled past 42,000 slat_fuse the latent stage's condition tokens slat_flow 8 latent features per voxel: 25 Euler steps, CFG 1 while t <= 0.5 mesh_dec the mesh decoder up to 128^3 (voxels subdivided once) mesh_conv / mesh_gn / mesh_out its last block at 256^3, chunk by chunk (GroupNorm statistics over all voxels in numpy) -> FlexiCubes features; the mesh from those in numpy (FlexiCubes port, flexicubes_tables.npz) Needs numpy, scipy, onnxruntime-gpu, torch + torchvision (CPU is enough: the preprocessing runs the original's code), Pillow; trimesh to write GLB. """ from __future__ import annotations import argparse import json import math import sys import time from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent sys.path[:0] = [p for p in (str(HERE), str(HERE / "vendor")) if p not in sys.path] # pipeline_tables, vendor/ SEED = 42 # MoGe-v1 infer(resolution_level=9) runs at the top of the checkpoint's token range: sam3d.json "num_tokens" # (moge-vitl: trained_area_range [250000, 500000] -> [1275, 2551] tokens -> 2551). SS_STEPS, SS_RESCALE, SS_CFG, CFG_INTERVAL = 25, 3.0, 7.0, (0.0, 500.0) SLAT_STEPS, SLAT_RESCALE, SLAT_CFG = 25, 1.0, 1.0 TIME_SCALE = 1000.0 POSE_KEYS = ("6drotation_normalized", "translation", "scale", "translation_scale") # R3 camera -> PyTorch3D camera (look_at_view_transform(eye=(0, 0, -1), at=0, up=(0, -1, 0))): x -> -x, y -> -y CAM_R = np.diag([-1.0, -1.0, 1.0]).astype(np.float32) # ---------------------------------------------------------------- MoGe-v1 (MoGeModel.forward / infer around the graph) def moge_inputs(image, meta): """MoGeModel.forward's resizes and normalisation, DINOv2's position-embedding interpolation and the head's UV grids (the graph takes them as inputs: tracing would freeze them at one size). image: [1, 3, H, W] in [0, 1].""" import torch import torch.nn.functional as F try: from moge_min import normalized_view_plane_uv except ImportError: # the source folder (no vendor/ yet): MoGe itself from moge.utils.geometry_torch import normalized_view_plane_uv H, W = image.shape[-2:] f = ((meta["num_tokens"] * 14 ** 2) / (H * W)) ** 0.5 rw, rh = int(W * f), int(H * f) img = F.interpolate(image, (rh, rw), mode="bicubic", align_corners=False, antialias=True) img = (img - torch.tensor(meta["image_mean"]).view(1, 3, 1, 1)) / torch.tensor(meta["image_std"]).view(1, 3, 1, 1) img14 = F.interpolate(img, (rh // 14 * 14, rw // 14 * 14), mode="bilinear", align_corners=False, antialias=True) # DinoVisionTransformer.interpolate_pos_encoding(x, w, h) with w, h = the image's dims 2 and 3 pos = torch.from_numpy(np.load(HERE / "moge_pos_embed.npy")) N = pos.shape[1] - 1 M = int(math.sqrt(N)) w0, h0 = img14.shape[2] // 14, img14.shape[3] // 14 kw = {} if meta["interpolate_offset"]: kw["scale_factor"] = (float(w0 + meta["interpolate_offset"]) / M, float(h0 + meta["interpolate_offset"]) / M) else: kw["size"] = (w0, h0) pp = F.interpolate(pos[:, 1:].reshape(1, M, M, -1).permute(0, 3, 1, 2), mode="bicubic", antialias=meta["interpolate_antialias"], **kw) pos = torch.cat([pos[:, :1], pp.permute(0, 2, 3, 1).reshape(1, -1, pos.shape[-1])], 1) ph, pw = rh // 14, rw // 14 uvs = [normalized_view_plane_uv(width=pw * s, height=ph * s, aspect_ratio=rw / rh, dtype=torch.float32) for s in (1, 2, 4)] + [normalized_view_plane_uv(width=rw, height=rh, aspect_ratio=rw / rh, dtype=torch.float32)] feed = {"image14": img14, "pos_embed": pos} feed.update({f"uv{i}": u.permute(2, 0, 1)[None].contiguous() for i, u in enumerate(uvs)}) return {k: v.numpy().astype(np.float32) for k, v in feed.items()} def moge_outputs(points, mask, H, W, meta): """MoGeModel.forward's resize back to the picture + infer(force_projection=False, apply_mask=True).""" import torch import torch.nn.functional as F try: from moge_min import recover_focal_shift except ImportError: from moge.utils.geometry_torch import recover_focal_shift points = F.interpolate(torch.from_numpy(points), (H, W), mode="bilinear", align_corners=False, antialias=False) mask = F.interpolate(torch.from_numpy(mask), (H, W), mode="bilinear", align_corners=False, antialias=False) points, mask = points.permute(0, 2, 3, 1), mask.squeeze(1) if meta["remap_output"] == "exp": xy, z = points.split([2, 1], dim=-1) z = torch.exp(z) points = torch.cat([xy * z, z], dim=-1) elif meta["remap_output"] not in ("linear", False): raise ValueError(meta["remap_output"]) aspect = W / H mask_binary = mask > meta["mask_threshold"] focal, shift = recover_focal_shift(points, mask_binary) fx = focal / 2 * (1 + aspect ** 2) ** 0.5 / aspect fy = focal / 2 * (1 + aspect ** 2) ** 0.5 K = torch.zeros(1, 3, 3) K[:, 0, 0], K[:, 1, 1], K[:, 0, 2], K[:, 1, 2], K[:, 2, 2] = fx, fy, 0.5, 0.5, 1.0 points = points + torch.stack([torch.zeros_like(shift), torch.zeros_like(shift), shift], dim=-1)[..., None, None, :] points = torch.where(mask_binary[..., None], points, torch.inf) return points[0], K[0] # ---------------------------------------------------------------- preprocessing (the original's code, vendor/) U8_FLOAT = (np.arange(256) / 255).astype(np.float32) def to_float(u8): """image_to_float (image / 255 in float64, then float32) by lookup: the same values (all 256 checked), without the float64 copy (1 GB for a 30 MP RGBA picture).""" return U8_FLOAT[u8] def preprocessors(): """pipeline.yaml's ss_preprocessor / slat_preprocessor.""" from functools import partial import torchvision from sam3d_objects.data.dataset.tdfy.preprocessor import PreProcessor from sam3d_objects.data.dataset.tdfy.img_processing import pad_to_square_centered from sam3d_objects.data.dataset.tdfy import img_and_mask_transforms as T C, R = torchvision.transforms.Compose, torchvision.transforms.Resize img = C([partial(pad_to_square_centered), R(518)]) msk = C([partial(pad_to_square_centered), R(518, interpolation=0)]) ss = PreProcessor(img_mask_joint_transform=[], img_mask_pointmap_joint_transform=[ partial(T.resize_all_to_same_size), partial(T.crop_around_mask_with_padding, box_size_factor=1.2, padding_factor=0.0)], img_transform=img, mask_transform=msk, normalize_pointmap=True, pointmap_normalizer=T.ObjectCentricSSI(allow_scale_and_shift_override=True, use_scene_scale=True), pointmap_transform=C([partial(pad_to_square_centered), R(518, interpolation=0)])) slat = PreProcessor(img_transform=img, mask_transform=msk, img_mask_joint_transform=[ partial(T.crop_around_mask_with_padding, box_size_factor=1.2, padding_factor=0.0)]) return ss, slat def preprocess(rgba, pointmap, pre): """InferencePipelinePointMap.preprocess_image (rgba: uint8 [H, W, 4]; the mask in alpha).""" import torch from sam3d_objects.data.dataset.tdfy.img_and_mask_transforms import get_mask x = torch.from_numpy(to_float(rgba)).permute(2, 0, 1).contiguous() r = pre._process_image_mask_pointmap_mess(x[:3], get_mask(x, None, "ALPHA_CHANNEL"), pointmap) item = {k: r[k][None] for k in ("mask", "image", "rgb_image", "rgb_image_mask")} if pointmap is not None: for k in ("pointmap", "rgb_pointmap", "pointmap_scale", "pointmap_shift"): item[k] = r[k][None] return item # ---------------------------------------------------------------- the mesh decoder's 256^3 GroupNorm MESH_CHUNK = 1 << 18 def gn_stats(x, groups, eps, chunk=MESH_CHUNK): """GroupNorm statistics over all rows of x [N, C] (float64 sums, chunk by chunk): mean, 1 / sqrt(var + eps).""" C = x.shape[1] s1, s2 = np.zeros(groups), np.zeros(groups) for i in range(0, len(x), chunk): v = x[i:i + chunk].astype(np.float64).reshape(-1, groups, C // groups) s1 += v.sum((0, 2)) s2 += (v * v).sum((0, 2)) n = len(x) * (C // groups) mean = s1 / n return mean.astype(np.float32), (1 / np.sqrt(np.maximum(s2 / n - mean * mean, 0) + eps)).astype(np.float32) # ---------------------------------------------------------------- samplers def t_seq(steps, rescale): t = np.linspace(0, 1, steps + 1) return t / (1 + (rescale - 1) * (1 - t)) if rescale else t def euler(model, x, steps, rescale, cfg): """FlowMatching / ShortCut sampling with ClassifierFreeGuidance: x_{k+1} = x_k + v (t_{k+1} - t_k), v from the model at 1000 t; inside the interval (1000 t in [0, 500]) v = (1 + s) v_cond - s v_uncond, the unconditional pass with the condition zeroed (force_zeros_cond).""" ts = t_seq(steps, rescale) for t0, t1 in zip(ts[:-1], ts[1:]): tt = np.array([t0 * TIME_SCALE], np.float32) if cfg > 0 and CFG_INTERVAL[0] <= tt[0] <= CFG_INTERVAL[1]: vc, vu = model(x, tt, False), model(x, tt, True) v = {k: (1 + cfg) * vc[k] - cfg * vu[k] for k in vc} else: v = model(x, tt, False) x = {k: (x[k] + v[k] * np.float32(t1 - t0)).astype(np.float32) for k in x} return x # ---------------------------------------------------------------- the pipeline class Sam3DObjects: def __init__(self, folder=HERE, device="cuda"): import onnxruntime as ort if hasattr(ort, "preload_dlls"): ort.preload_dlls() self.d = Path(folder) self.meta = json.loads((self.d / "sam3d.json").read_text()) self.so = ort.SessionOptions() self.so.log_severity_level = 3 self.so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC cuda = {"use_tf32": "0", "arena_extend_strategy": "kSameAsRequested"} self.prov = ([("CUDAExecutionProvider", cuda)] if device == "cuda" else []) + ["CPUExecutionProvider"] self.ort = ort def session(self, name): return self.ort.InferenceSession(str(self.d / f"{name}.onnx"), self.so, providers=self.prov) @staticmethod def run(s, **feed): names = {i.name for i in s.get_inputs()} return s.run(None, {k: np.ascontiguousarray(v) for k, v in feed.items() if k in names}) def pointmap(self, rgba): """compute_pointmap: MoGe on the RGB picture, the points into PyTorch3D's camera convention, [3, H, W].""" import torch img = torch.from_numpy(to_float(rgba[..., :3])).permute(2, 0, 1)[None] H, W = img.shape[-2:] s = self.session("moge") pts, msk = self.run(s, **moge_inputs(img, self.meta["moge"])) del s points, K = moge_outputs(pts, msk, H, W, self.meta["moge"]) points = points @ torch.from_numpy(CAM_R) return points.permute(2, 0, 1).contiguous(), K def conditions(self, item): """DINOv2 on the 4 pictures (mask repeated to 3 channels): norm tokens for the ss stage, prenorm tokens for the slat stage.""" s = self.session("dino") out = {} for k in ("image", "rgb_image", "mask", "rgb_image_mask"): x = item[k].numpy() x = np.repeat(x, 3, 1) if x.shape[1] == 1 else x out[k] = self.run(s, pixels=x.astype(np.float32)) del s return out def structure(self, ss_item, toks, noise): """noise: {name: array} for shape [1, 4096, 8] and the pose latents.""" f = self.session("ss_fuse") cond = self.run(f, **{k: toks[k][0] for k in toks}, pointmap=ss_item["pointmap"].numpy(), rgb_pointmap=ss_item["rgb_pointmap"].numpy())[0] del f s = self.session("ss_flow") zero = np.zeros_like(cond) names = ("shape",) + POSE_KEYS def model(x, t, uncond): o = self.run(s, shape=x["shape"], rotation6d=x["6drotation_normalized"], translation=x["translation"], scale=x["scale"], translation_scale=x["translation_scale"], t=t, d=np.zeros(1, np.float32), cond=zero if uncond else cond) return dict(zip(names, o)) x = euler(model, {k: noise[k].astype(np.float32) for k in names}, SS_STEPS, SS_RESCALE, SS_CFG) del s z = x["shape"].transpose(0, 2, 1).reshape(1, 8, 16, 16, 16) logits = self.run(self.session("ss_dec"), z=z)[0] return x, logits def voxels_and_pose(self, x, logits, ss_item): """sample_sparse_structure's coordinates (prune, downsample) and the pose decoder.""" import torch from sam3d_objects.pipeline.inference_utils import (pose_decoder, prune_sparse_structure, downsample_sparse_structure) coords = torch.argwhere(torch.from_numpy(logits) > 0)[:, [0, 2, 3, 4]].int() coords = prune_sparse_structure(coords, max_neighbor_axes_dist=1) coords, factor = downsample_sparse_structure(coords) r = {k: torch.from_numpy(v) for k, v in x.items()} r.update(pose_decoder("ScaleShiftInvariant")(r, scene_scale=ss_item["pointmap_scale"], scene_shift=ss_item["pointmap_shift"])) pose = {"translation": r["translation"].numpy(), "rotation": r["rotation"].numpy(), "scale": (r["scale"] * factor).numpy()} return coords.numpy(), pose def latent(self, toks, coords, noise): import pipeline_tables as TB f = self.session("slat_fuse") cond = self.run(f, **{k: toks[k][1] for k in toks})[0] del f s = self.session("slat_flow") tb = dict(zip(TB.SLAT_NAMES, TB.slat_flow_tables(coords))) zero = np.zeros_like(cond) def model(x, t, uncond): return {"x": self.run(s, feats=x["x"], t=t, cond=zero if uncond else cond, **tb)[0]} x = euler(model, {"x": noise.astype(np.float32)}, SLAT_STEPS, SLAT_RESCALE, SLAT_CFG)["x"] del s return x * np.array(self.meta["slat_std"], np.float32) + np.array(self.meta["slat_mean"], np.float32) def mesh(self, slat, coords, chunk=MESH_CHUNK): """SLatMeshDecoder: mesh_dec to 128^3 (+ the last block's norm / SiLU); the 256^3 block chunk by chunk of its voxels: mesh_conv (its first conv, gathering from the 128^3 parents: child k of parent k // 8), the GroupNorm statistics of all voxels (numpy), mesh_gn (GroupNorm + SiLU), mesh_out (second conv + skip + output layer); then FlexiCubes in numpy.""" import pipeline_tables as TB tb = dict(zip(TB.MESH_NAMES, TB.mesh_dec_tables(coords))) nbr256 = tb.pop("nbr256") s = self.session("mesh_dec") h128, x128 = self.run(s, slat=slat.astype(np.float32), **tb) del s, tb M, N = len(h128), len(nbr256) s = self.session("mesh_conv") g = None for i in range(0, N, chunk): nb = nbr256[i:i + chunk] o = self.run(s, h=h128, nbr=np.where(nb == N, M, nb // 8))[0] if g is None: g = np.empty((N, o.shape[1]), o.dtype) g[i:i + chunk] = o del s, h128 mean, rstd = gn_stats(g, self.meta["mesh_gn"]["groups"], self.meta["mesh_gn"]["eps"], chunk) s = self.session("mesh_gn") for i in range(0, N, chunk): g[i:i + chunk] = self.run(s, f=g[i:i + chunk], mean=mean, rstd=rstd)[0] del s s = self.session("mesh_out") f = None for i in range(0, N, chunk): o = self.run(s, g=g, nbr=nbr256[i:i + chunk], xs=x128, par=np.arange(i, min(i + chunk, N), dtype=np.int64) // 8)[0] if f is None: f = np.empty((N, o.shape[1]), np.float32) f[i:i + chunk] = o del s, g, x128, nbr256 tables = dict(np.load(self.d / "flexicubes_tables.npz")) return TB.flexicubes(f, TB.subdivide(TB.subdivide(np.asarray(coords)[:, 1:])), tables) def __call__(self, image, mask, seed=SEED, log=print): import torch from PIL import Image rgba = np.array(image.convert("RGB")).astype(np.uint8) m = np.array(mask) m = (m[..., -1] if m.ndim == 3 else m) > 0 rgba = np.concatenate([rgba, (m.astype(np.uint8) * 255)[..., None]], -1) times, t0 = {}, time.time() pm, K = self.pointmap(rgba) times["pointmap"] = time.time() - t0 ss_pre, slat_pre = preprocessors() ss_item, slat_item = preprocess(rgba, pm, ss_pre), preprocess(rgba, None, slat_pre) t0 = time.time() toks = self.conditions(slat_item) times["conditions"] = time.time() - t0 g = torch.Generator().manual_seed(seed) noise = {k: torch.randn(shape, generator=g).numpy() for k, shape in sorted({"6drotation_normalized": (1, 1, 6), "scale": (1, 1, 3), "shape": (1, 4096, 8), "translation": (1, 1, 3), "translation_scale": (1, 1, 1)}.items())} t0 = time.time() x, logits = self.structure(ss_item, toks, noise) coords, pose = self.voxels_and_pose(x, logits, ss_item) times["structure"] = time.time() - t0 log(f"structure: {len(coords)} voxels") t0 = time.time() slat = self.latent(toks, coords, torch.randn(1, len(coords), 8, generator=g).numpy()[0]) times["latent"] = time.time() - t0 t0 = time.time() v, f, attrs = self.mesh(slat, coords) times["mesh"] = time.time() - t0 log("seconds: " + ", ".join(f"{k} {v_:.1f}" for k, v_ in times.items())) return v, f, attrs, pose, K.numpy() def save_mesh(path, v, f, attrs): """GLB with vertex colours (y-up, as TRELLIS's to_glb writes it: rotated -90 degrees about x).""" import trimesh v = v @ np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]], np.float32) col = (np.clip(attrs[:, :3], 0, 1) * 255).astype(np.uint8) trimesh.Trimesh(v, f, vertex_colors=col, process=False).export(path) if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("image") ap.add_argument("mask") ap.add_argument("out") ap.add_argument("--seed", type=int, default=SEED) ap.add_argument("--cpu", action="store_true") a = ap.parse_args() from PIL import Image p = Sam3DObjects(HERE, "cpu" if a.cpu else "cuda") v, f, attrs, pose, K = p(Image.open(a.image), Image.open(a.mask), a.seed) save_mesh(a.out, v, f, attrs) print(f"{a.out}: {len(v)} vertices, {len(f)} faces; pose", {k: np.round(v_, 4).tolist() for k, v_ in pose.items()})