"""TRELLIS text-conditioned (xlarge) with ONNX Runtime: a text prompt -> a mesh with vertex colours. The CLIP text encoder, the sparse-structure flow and decoder, the structured-latent flow and the mesh decoder as ONNX graphs; numpy around them, following the official TrellisTextTo3DPipeline (microsoft/TRELLIS): - CLIP ViT-L/14 features of the prompt and of the empty prompt (classifier-free guidance); - the sparse structure: 25 flow-matching Euler steps on a 16^3 x 8 latent (time rescaled by 3, guidance 7.5 for t in [0.5, 0.95]), decoded to 64^3 occupancy; the occupied voxels are the structure; - the structured latent: the same sampler over 8 features per voxel, then the latent normalisation undone; - the mesh decoder's FlexiCubes features at 256^3 and FlexiCubes extraction (ported to numpy: dual vertices from a weighted average of the edge crossings, quads split by the learned gamma), vertex colours from its colour channels. The sparse operations (submanifold convolutions, pooling, Swin windows) run inside the graphs from index tables built here from the voxel coordinates. The Gaussian and radiance-field decoders are not included. Needs numpy, onnxruntime-gpu (or onnxruntime) and tokenizers; trimesh to write the mesh. python fp16/pipeline.py "A chair looking like a avocado." chair.glb [--cuda] [--seed 1] """ from __future__ import annotations import itertools from pathlib import Path import numpy as np STEPS, CFG, CFG_INTERVAL, RESCALE_T, SIGMA_MIN = 25, 7.5, (0.5, 0.95), 3.0, 1e-5 SLAT_MEAN = np.array([-2.1687545776367188, -0.004347046371549368, -0.13352349400520325, -0.08418072760105133, -0.5271206498146057, 0.7238689064979553, -1.1414450407028198, 1.2039363384246826], np.float32) SLAT_STD = np.array([2.377650737762451, 2.386378288269043, 2.124418020248413, 2.1748552322387695, 2.663944721221924, 2.371192216873169, 2.6217446327209473, 2.684523105621338], np.float32) OFF27 = np.array(list(itertools.product((-1, 0, 1), repeat=3)), np.int64) # kernel order (dx, dy, dz) SUB8 = np.array(list(itertools.product((0, 1), repeat=3)), np.int64) # SparseSubdivide's child order WINDOW = 8 # ------------------------------------------------------------------------------------------------ the prompt def clip_ids(prompt, tokenizer_json, length=77): """The CLIP tokenizer as the pipeline calls it (max_length 77, padding 'max_length', truncation): BOS, BPE, EOS, padded with <|endoftext|>.""" from tokenizers import Tokenizer tok = Tokenizer.from_file(str(tokenizer_json)) ids = tok.encode(prompt).ids eos = tok.token_to_id("<|endoftext|>") if len(ids) > length: ids = ids[:length - 1] + [eos] return np.array([ids + [eos] * (length - len(ids))], np.int64) # ------------------------------------------------------------------------------------------------ index tables def neighbours(xyz, offsets=OFF27): """[N, K] index of each voxel's neighbour at each offset (N where there is none).""" xyz = np.asarray(xyz, np.int64) n = len(xyz) R = int(xyz.max()) + 4 key = lambda p: ((p[:, 0] + 1) * R + (p[:, 1] + 1)) * R + (p[:, 2] + 1) k = key(xyz) order = np.argsort(k, kind="stable") ks = k[order] out = np.full((n, len(offsets)), n, np.int64) for j, o in enumerate(offsets): q = key(xyz + o) pos = np.minimum(np.searchsorted(ks, q), n - 1) hit = ks[pos] == q out[hit, j] = order[pos[hit]] return out def with_batch(xyz): return np.concatenate([np.zeros((len(xyz), 1), np.int32), np.asarray(xyz, np.int32)], 1) def slat_flow_tables(coords): """coords [N, 4] (batch 0, x, y, z at 64^3) -> coords64, nbr64, coords32, nbr32, down_child, down_cnt, up_idx.""" xyz = np.asarray(coords)[:, 1:].astype(np.int64) coarse, inv = np.unique(xyz // 2, axis=0, return_inverse=True) # SparseDownsample's order inv = inv.reshape(-1) m = len(coarse) cnt = np.bincount(inv, minlength=m) order = np.argsort(inv, kind="stable") start = np.concatenate([[0], np.cumsum(cnt)[:-1]]) slot = np.arange(len(xyz)) - start[inv[order]] child = np.full((m, 8), len(xyz), np.int64) child[inv[order], slot] = order return (with_batch(xyz), neighbours(xyz), with_batch(coarse), neighbours(coarse), child, cnt.astype(np.float32)[:, None], inv.astype(np.int64)) def windows(xyz, shift, size=WINDOW): """The Swin partition (calc_window_partition): voxels grouped by window, padded to the fullest window. Returns fwd [W, L] (index, N = padding), mask [W, L] (0 / -inf) and bwd [N] (position in the W * L layout).""" s = np.asarray(xyz, np.int64) + shift nw = (s.max(0) + 1 + size - 1) // size wid = ((s[:, 0] // size) * nw[1] + s[:, 1] // size) * nw[2] + s[:, 2] // size uw, winv, wcnt = np.unique(wid, return_inverse=True, return_counts=True) winv = winv.reshape(-1) L, Wn, n = int(wcnt.max()), len(uw), len(s) order = np.argsort(winv, kind="stable") start = np.concatenate([[0], np.cumsum(wcnt)[:-1]]) slot = np.empty(n, np.int64) slot[order] = np.arange(n) - start[winv[order]] fwd = np.full((Wn, L), n, np.int64) fwd[winv, slot] = np.arange(n) mask = np.where(fwd < n, 0.0, -np.inf).astype(np.float32) return fwd, mask, (winv * L + slot).astype(np.int64) def subdivide(xyz): return ((np.asarray(xyz, np.int64) * 2)[:, None] + SUB8[None]).reshape(-1, 3) def mesh_dec_tables(coords): """coords [N, 4] -> coords64, the two Swin partitions (shift 0, 4), nbr128, nbr256.""" xyz = np.asarray(coords)[:, 1:].astype(np.int64) x128 = subdivide(xyz) x256 = subdivide(x128) return (with_batch(xyz),) + windows(xyz, 0) + windows(xyz, WINDOW // 2) + (neighbours(x128), neighbours(x256)) def mesh_dec_coords256(coords): return with_batch(subdivide(subdivide(np.asarray(coords)[:, 1:]))) # ------------------------------------------------------------------------------------------------ FlexiCubes # A numpy port of the FlexiCubes extraction TRELLIS uses (NVIDIA FlexiCubes, Apache-2.0, at TRELLIS's submodule # 815e075; LICENSE-FlexiCubes.txt; its lookup tables in flexicubes_tables.npz), inference path only. The original runs # on the dense 256^3 grid; here only the cubes that can hold the surface (those with a corner the decoder wrote a # negative SDF to) are visited, in the dense grid's order, so vertices and faces come out in the original's order. CORNERS = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]], np.int64) CUBE_EDGES = np.array([0, 1, 1, 5, 4, 5, 0, 4, 2, 3, 3, 7, 6, 7, 2, 6, 2, 0, 3, 1, 7, 5, 6, 4], np.int64) QUAD_SPLIT_1, QUAD_SPLIT_2 = np.array([0, 1, 2, 0, 2, 3]), np.array([0, 1, 3, 3, 1, 2]) def _interp(w, x): """FlexiCubes._linear_interp: zero crossing along each edge (w [E, 2, 1], x [E, 2, C]).""" w2 = np.concatenate([w[:, 1:2], -w[:, 0:1]], 1) return (x * w2).sum(1) / w2.sum(1) def _index_add(n, idx, val): out = np.zeros((n,) + val.shape[1:], np.float32) np.add.at(out, idx, val) return out def flexicubes(feats, xyz, tables, res=256, weight_scale=0.99): """SparseFeatures2Mesh.__call__ (use_color) + FlexiCubes.__call__ (training=False) for one shape. feats [N, 101] (sdf 8, deform 8 x 3, weights 21, colour 8 x 6), xyz [N, 3] at res^3. Returns vertices [V, 3] in [-0.5, 0.5]^3, faces [F, 3], vertex attributes [V, 6] (colour, normal map).""" f32 = np.float32 feats = np.asarray(feats, f32) xyz = np.asarray(xyz, np.int64) n = len(xyz) R = res + 1 sdf = feats[:, 0:8] + f32(-1.0 / res) deform = feats[:, 8:32].reshape(n, 8, 3) weights = feats[:, 32:53] color = feats[:, 53:101].reshape(n, 8, 6) # sparse_cube2verts: every voxel's 8 corners, per-vertex mean over the voxels sharing it vkey = lambda p: (p[..., 0] * R + p[..., 1]) * R + p[..., 2] vid = vkey(xyz[:, None] + CORNERS[None]).reshape(-1) tv, inv = np.unique(vid, return_inverse=True) inv = inv.reshape(-1) attrs = np.concatenate([sdf[..., None], deform, color], -1).reshape(-1, 10) cnt = np.bincount(inv, minlength=len(tv)).astype(f32) vattr = np.stack([np.bincount(inv, attrs[:, c], minlength=len(tv)) for c in range(10)], 1).astype(f32) vattr /= cnt[:, None] def lookup(q): pos = np.minimum(np.searchsorted(tv, q), len(tv) - 1) return pos, tv[pos] == q def sdf_of(q): pos, hit = lookup(q) return np.where(hit, vattr[pos, 0], f32(1.0)) # untouched grid vertices: outside (1) def pos_of(q): pos, hit = lookup(q) d = np.where(hit[..., None], vattr[pos, 1:4], f32(0.0)) g = np.stack([q // (R * R), (q // R) % R, q % R], -1).astype(f32) return g / f32(res) - f32(0.5) + f32((1 - 1e-8) / (res * 2)) * np.tanh(d) def color_of(q): pos, hit = lookup(q) c = np.where(hit[..., None], vattr[pos, 4:10], f32(0.0)) return (1 / (1 + np.exp(-c))).astype(f32) # candidate cubes: those with a corner among the vertices with a negative SDF, in dense (x, y, z) order neg = tv[vattr[:, 0] < 0] nv = np.stack([neg // (R * R), (neg // R) % R, neg % R], -1) cc = (nv[:, None] - CORNERS[None]).reshape(-1, 3) cc = cc[((cc >= 0) & (cc < res)).all(1)] ckey = np.unique((cc[:, 0] * res + cc[:, 1]) * res + cc[:, 2]) cxyz = np.stack([ckey // (res * res), (ckey // res) % res, ckey % res], -1) cube_v = vkey(cxyz[:, None] + CORNERS[None]) # [C, 8] occ = sdf_of(cube_v) < 0 s = occ.sum(1) surf = (s > 0) & (s < 8) ckey, cxyz, cube_v, occ = ckey[surf], cxyz[surf], cube_v[surf], occ[surf] S = len(ckey) if S == 0: return np.zeros((0, 3), f32), np.zeros((0, 3), np.int64), np.zeros((0, 6), f32) # weights: the decoder's per-voxel values where a voxel exists, 0 elsewhere (the dense grid's zeros) ikey = (xyz[:, 0] * res + xyz[:, 1]) * res + xyz[:, 2] io = np.argsort(ikey) pos = np.minimum(np.searchsorted(ikey[io], ckey), n - 1) hit = ikey[io][pos] == ckey w = np.where(hit[:, None], weights[io[pos]], f32(0.0)) beta = np.tanh(w[:, :12]) * f32(weight_scale) + f32(1) alpha = np.tanh(w[:, 12:20]) * f32(weight_scale) + f32(1) gamma = (1 / (1 + np.exp(-w[:, 20]))).astype(f32) * f32(weight_scale) + f32((1 - weight_scale) / 2) # _get_case_id (the C16 / C19 ambiguity resolved against the adjacent cube) case = (occ * (1 << np.arange(8))).sum(1) pc = tables["check_table"][case] to_check = np.nonzero(pc[:, 0] == 1)[0] adj = cxyz[to_check] + pc[to_check, 1:4] within = ((adj >= 0) & (adj < res)).all(1) to_check, adj = to_check[within], adj[within] akey = (adj[:, 0] * res + adj[:, 1]) * res + adj[:, 2] chk_keys = np.sort(ckey[pc[:, 0] == 1]) if len(chk_keys) and len(akey): p = np.minimum(np.searchsorted(chk_keys, akey), len(chk_keys) - 1) flip_case = chk_keys[p] == akey case[to_check[flip_case]] = pc[to_check[flip_case], -1] # _identify_surf_edges edges = cube_v[:, CUBE_EDGES].reshape(-1, 2) big = R ** 3 ue_key, e_inv, e_cnt = np.unique(edges[:, 0] * big + edges[:, 1], return_inverse=True, return_counts=True) e_inv = e_inv.reshape(-1) ue = np.stack([ue_key // big, ue_key % big], 1) mask_edges = (sdf_of(ue) < 0).sum(1) == 1 surf_edges_mask = mask_edges[e_inv] counts = e_cnt[e_inv] mapping = np.full(len(ue), -1, np.int64) mapping[mask_edges] = np.arange(mask_edges.sum()) idx_map = mapping[e_inv] # [S * 12] surf_edges = ue[mask_edges] # _compute_vd alpha12 = alpha[:, CUBE_EDGES].reshape(-1, 2) # [S * 12, 2] se_x = pos_of(surf_edges.reshape(-1)).reshape(-1, 2, 3) se_s = sdf_of(surf_edges.reshape(-1)).reshape(-1, 2, 1) se_c = color_of(surf_edges.reshape(-1)).reshape(-1, 2, 6) num_vd = tables["num_vd_table"][case] eg, eg_vd, eg_cube, vd_gamma = [], [], [], [] total = 0 for num in np.unique(num_vd): cur = num_vd == num ncur = int(cur.sum()) * int(num) g = tables["dmc_table"][case[cur], :num].reshape(-1, num * 7) g_vd = (np.arange(ncur)[:, None].repeat(7, 1) + total).reshape(g.shape) total += ncur g_cube = np.nonzero(cur)[0][:, None].repeat(num * 7, 1) m = g != -1 eg.append(g[m]) eg_vd.append(g_vd[m]) eg_cube.append(g_cube[m]) vd_gamma.append(gamma[cur][:, None].repeat(num, 1).reshape(-1)) eg, eg_vd, eg_cube, vd_gamma = (np.concatenate(v) for v in (eg, eg_vd, eg_cube, vd_gamma)) flat = eg_cube * 12 + eg idx_group = idx_map[flat] sw = se_s[idx_group] * alpha12[flat][:, :, None] ue_group = _interp(sw, se_x[idx_group]) beta_group = beta.reshape(-1)[flat][:, None] beta_sum = _index_add(total, eg_vd, beta_group) vd = _index_add(total, eg_vd, ue_group * beta_group) / beta_sum vd_color = _index_add(total, eg_vd, _interp(sw, se_c[idx_group]) * beta_group) / beta_sum vd_idx_map = np.zeros(S * 12, np.int64) vd_idx_map[flat] = eg_vd # _triangulate (inference: each quad split along the diagonal with the larger gamma product) gm = (counts == 4) & surf_edges_mask group = idx_map[gm] vd_idx = vd_idx_map[gm] order = np.argsort(group, kind="stable") edge_indices = group[order] quad = vd_idx[order].reshape(-1, 4) s_e = sdf_of(surf_edges[edge_indices.reshape(-1, 4)[:, 0]].reshape(-1)).reshape(-1, 2) flip = s_e[:, 0] > 0 quad = np.concatenate([quad[flip][:, [0, 1, 3, 2]], quad[~flip][:, [2, 3, 1, 0]]]) qg = vd_gamma[quad] split = (qg[:, 0] * qg[:, 2]) > (qg[:, 1] * qg[:, 3]) faces = np.where(split[:, None], quad[:, QUAD_SPLIT_1], quad[:, QUAD_SPLIT_2]).reshape(-1, 3) return vd.astype(f32), faces, vd_color.astype(f32) # ------------------------------------------------------------------------------------------------ the runtime def t_schedule(steps=STEPS, rescale_t=RESCALE_T): t = np.linspace(1, 0, steps + 1) return rescale_t * t / (1 + (rescale_t - 1) * t) class TrellisText: def __init__(self, folder, provider="cpu"): import onnxruntime as ort self.folder, self.ort = Path(folder), ort if provider != "cpu" and hasattr(ort, "preload_dlls"): try: ort.preload_dlls() except Exception: pass self.pv = ["CPUExecutionProvider"] if provider == "cpu" else [ ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested", "use_tf32": "0"}), "CPUExecutionProvider"] self.ro = ort.RunOptions() if provider != "cpu": self.ro.add_run_config_entry("memory.enable_memory_arena_shrinkage", "gpu:0") self.s = {} self.tables = dict(np.load(self.folder / "flexicubes_tables.npz")) def session(self, name): if name not in self.s: so = self.ort.SessionOptions() so.log_severity_level = 3 so.graph_optimization_level = self.ort.GraphOptimizationLevel.ORT_ENABLE_BASIC self.s[name] = self.ort.InferenceSession(str(self.folder / f"{name}.onnx"), so, providers=self.pv) return self.s[name] def release(self, *names): for n in names: self.s.pop(n, None) def run(self, name, feed): s = self.session(name) names = {i.name for i in s.get_inputs()} # a table a graph doesn't use was pruned from its inputs return s.run(None, {k: v for k, v in feed.items() if k in names}, self.ro)[0] def encode(self, prompt): tok = self.folder / "tokenizer.json" c = self.run("clip", {"input_ids": clip_ids(prompt, tok)}) nc = self.run("clip", {"input_ids": clip_ids("", tok)}) self.release("clip") return c.astype(np.float32), nc.astype(np.float32) @staticmethod def _euler(x, velocity, steps, interval, rescale_t): """FlowEulerGuidanceIntervalSampler.sample: x -= (t - t_prev) v; inside the guidance interval v is the guided velocity, outside it the condition's alone.""" ts = t_schedule(steps, rescale_t) for t, tp in zip(ts[:-1], ts[1:]): v = velocity(x, np.array([1000 * t], np.float32), interval[0] <= t <= interval[1]) x = (x - np.float32(t - tp) * v).astype(np.float32) return x def sparse_structure(self, cond, neg, noise, steps=STEPS, cfg=CFG, interval=CFG_INTERVAL, rescale_t=RESCALE_T): def velocity(x, t, guided): if not guided: return self.run("ss_flow", {"x": x, "t": t, "cond": cond}) v = self.run("ss_flow", {"x": np.concatenate([x, x]), "t": np.concatenate([t, t]), "cond": np.concatenate([cond, neg])}) # both rows in one batch return (1 + cfg) * v[:1] - cfg * v[1:] z = self._euler(np.asarray(noise, np.float32), velocity, steps, interval, rescale_t) self.release("ss_flow") logits = self.run("ss_dec", {"z": z}) self.release("ss_dec") return z, logits, np.argwhere(logits > 0)[:, [0, 2, 3, 4]].astype(np.int32) def structured_latent(self, cond, neg, coords, noise, steps=STEPS, cfg=CFG, interval=CFG_INTERVAL, rescale_t=RESCALE_T): names = ("coords64", "nbr64", "coords32", "nbr32", "down_child", "down_cnt", "up_idx") tb = dict(zip(names, slat_flow_tables(coords))) def velocity(x, t, guided): v = self.run("slat_flow", {"feats": x, "t": t, "cond": cond, **tb}) if not guided: return v return (1 + cfg) * v - cfg * self.run("slat_flow", {"feats": x, "t": t, "cond": neg, **tb}) x = self._euler(np.asarray(noise, np.float32), velocity, steps, interval, rescale_t) self.release("slat_flow") return x * SLAT_STD[None] + SLAT_MEAN[None] def mesh_features(self, slat, coords): names = ("coords64", "win0_fwd", "win0_mask", "win0_bwd", "win4_fwd", "win4_mask", "win4_bwd", "nbr128", "nbr256") tb = dict(zip(names, mesh_dec_tables(coords))) f = self.run("mesh_dec", {"slat": np.asarray(slat, np.float32), **tb}) self.release("mesh_dec") return f, subdivide(subdivide(np.asarray(coords)[:, 1:])) def mesh(self, slat, coords): f, xyz = self.mesh_features(slat, coords) return flexicubes(f, xyz, self.tables) def __call__(self, prompt, seed=None, ss_noise=None, slat_noise=None): rng = np.random.default_rng(seed) c, nc = self.encode(prompt) if ss_noise is None: ss_noise = rng.standard_normal((1, 8, 16, 16, 16)).astype(np.float32) _, _, coords = self.sparse_structure(c, nc, ss_noise) if slat_noise is None: slat_noise = rng.standard_normal((len(coords), 8)).astype(np.float32) return self.mesh(self.structured_latent(c, nc, coords, slat_noise), coords) def save_mesh(path, v, f, attrs): """The mesh with its 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__": import argparse ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("prompt") ap.add_argument("out") ap.add_argument("--seed", type=int) ap.add_argument("--dir", default=str(Path(__file__).resolve().parent)) ap.add_argument("--cuda", action="store_true") a = ap.parse_args() v, f, attrs = TrellisText(a.dir, "cuda" if a.cuda else "cpu")(a.prompt, a.seed) save_mesh(a.out, v, f, attrs) print(len(v), "vertices,", len(f), "faces")