jennyxue commited on
Commit
1e9536e
·
verified ·
1 Parent(s): 153591f

int4 build of TripoSG

Browse files
.gitattributes CHANGED
@@ -35,3 +35,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  fp16/transformer.onnx.data filter=lfs diff=lfs merge=lfs -text
37
  int8/transformer.onnx.data filter=lfs diff=lfs merge=lfs -text
 
 
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  fp16/transformer.onnx.data filter=lfs diff=lfs merge=lfs -text
37
  int8/transformer.onnx.data filter=lfs diff=lfs merge=lfs -text
38
+ int4/transformer.onnx.data filter=lfs diff=lfs merge=lfs -text
int4/image_encoder.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:96a437dc2f3540e8253fdcaf1efe8df9d74313e11e8817faa04540e99b4176a3
3
+ size 311329410
int4/pipeline.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TripoSG image-to-3D with ONNX Runtime: the DINOv2 image encoder, the rectified-flow transformer and the shape VAE's
2
+ decoder (latent tokens once, then occupancy queries) as ONNX graphs, numpy around them, following the repository's
3
+ `prepare_image` (alpha path), `TripoSGPipeline` (50 Euler steps, classifier-free guidance 7) and
4
+ `hierarchical_extract_geometry` (occupancy on a 256^3 grid, refined to 512^3 in a band around the surface, then
5
+ marching cubes).
6
+
7
+ The input must be an RGBA image with the object matted (alpha): the repository's script removes the background with
8
+ BRIA RMBG-1.4, a separately licensed model that is not included here; any matting model works.
9
+ Needs numpy, scipy, scikit-image, onnxruntime (or onnxruntime-gpu) and Pillow; trimesh to save the mesh as .glb;
10
+ opencv-python (optional) to downscale inputs over 2000 px exactly as the original does.
11
+
12
+ python fp16/pipeline.py object.png mesh.glb [--steps 50] [--seed 42] [--cuda]
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+
21
+ MEAN = np.array([0.485, 0.456, 0.406], np.float32)[:, None, None]
22
+ STD = np.array([0.229, 0.224, 0.225], np.float32)[:, None, None]
23
+ BOUND = 1.005
24
+
25
+
26
+ def prepare(img, padding_ratio=0.1):
27
+ """The repository's load_image with a valid alpha: composite on white, crop to the alpha's bounding box, pad to a
28
+ square with a 10 % margin (white). Returns a PIL RGB image."""
29
+ from PIL import Image
30
+ img = img.convert("RGBA")
31
+ w, h = img.size
32
+ s = 2000 / max(w, h)
33
+ if s < 1: # the original: OpenCV's INTER_AREA (used when installed; else Pillow's box filter, per channel)
34
+ size = (int(w * s), int(h * s))
35
+ try:
36
+ import cv2
37
+ img = Image.fromarray(cv2.resize(np.asarray(img), size, interpolation=cv2.INTER_AREA), "RGBA")
38
+ except ImportError:
39
+ img = Image.merge("RGBA", [c.resize(size, Image.BOX) for c in img.split()])
40
+ a = np.asarray(img)
41
+ alpha = a[..., 3]
42
+ hist = np.histogram(alpha, bins=20, range=(0, 256))[0]
43
+ if not (hist[0] >= alpha.size * 0.01 and hist[-1] >= alpha.size * 0.01):
44
+ raise ValueError("needs an RGBA image with the object matted (transparent background)")
45
+ rows, cols = np.where(alpha > 0)
46
+ x, y = cols.min(), rows.min()
47
+ bw, bh = cols.max() - x + 1, rows.max() - y + 1
48
+ al = alpha.astype(np.float32)[..., None] / 255.0
49
+ rgb = a[..., :3].astype(np.float32) / 255.0 * al + (1 - al)
50
+ rgb = rgb[y:y + bh, x:x + bw]
51
+ if bw > bh:
52
+ l = int(bw * padding_ratio); t = int(l + (bw - bh) / 2)
53
+ else:
54
+ t = int(bh * padding_ratio); l = int(t + (bh - bw) / 2)
55
+ rgb = np.pad(rgb, ((t, t), (l, l), (0, 0)), constant_values=1.0)
56
+ return Image.fromarray((rgb * 255).astype(np.uint8))
57
+
58
+
59
+ def pixels(img):
60
+ """DINOv2's BitImageProcessor: shortest edge to 256 (bicubic), centre crop 224, ImageNet mean / std."""
61
+ from PIL import Image
62
+ w, h = img.size
63
+ if w <= h:
64
+ nw, nh = 256, int(256 * h / w)
65
+ else:
66
+ nw, nh = int(256 * w / h), 256
67
+ img = img.resize((nw, nh), Image.BICUBIC)
68
+ l, t = int(round((nw - 224) / 2.0)), int(round((nh - 224) / 2.0))
69
+ x = np.asarray(img.crop((l, t, l + 224, t + 224)), np.float32) / 255.0
70
+ return ((x.transpose(2, 0, 1) - MEAN) / STD)[None].astype(np.float32)
71
+
72
+
73
+ class TripoSG:
74
+ def __init__(self, folder, provider="cpu"):
75
+ import onnxruntime as ort
76
+ folder = Path(folder)
77
+ if provider != "cpu" and hasattr(ort, "preload_dlls"):
78
+ try:
79
+ ort.preload_dlls()
80
+ except Exception:
81
+ pass
82
+ so = ort.SessionOptions()
83
+ so.log_severity_level = 3
84
+ pv = ["CPUExecutionProvider"] if provider == "cpu" else [
85
+ ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}), "CPUExecutionProvider"]
86
+ self.s = {n: ort.InferenceSession(str(folder / f"{n}.onnx"), so, providers=pv)
87
+ for n in ("image_encoder", "transformer", "vae_tokens", "vae_query")}
88
+ self.ro = ort.RunOptions()
89
+ if provider != "cpu": # Windows: query batches differ in size, and the GPU arena would keep each one's buffers
90
+ self.ro.add_run_config_entry("memory.enable_memory_arena_shrinkage", "gpu:0")
91
+ self.dt = {n: {i.name: (np.float16 if i.type == "tensor(float16)" else np.float32) for i in s.get_inputs()}
92
+ for n, s in self.s.items()}
93
+
94
+ def run(self, name, **feeds):
95
+ feeds = {k: v.astype(self.dt[name][k]) if v.dtype.kind == "f" else v for k, v in feeds.items()}
96
+ return self.s[name].run(None, feeds, self.ro)[0]
97
+
98
+ def latents(self, px, noise, steps=50, guidance=7.0):
99
+ """Rectified flow: sigma from 1 to 0 in `steps` equal steps, x <- x + (sigma - sigma_next) * v; the
100
+ unconditional branch sees all-zero image embeddings."""
101
+ cond = self.run("image_encoder", pixel_values=px).astype(np.float32)
102
+ emb = np.concatenate([np.zeros_like(cond), cond])
103
+ sig = np.append(1.0 - np.arange(steps) / steps, 0.0)
104
+ x = noise.astype(np.float32)
105
+ for i in range(steps):
106
+ t = np.full((2,), sig[i] * 1000.0, np.float32)
107
+ v = self.run("transformer", latents=np.concatenate([x, x]), timestep=t, image_embeds=emb).astype(np.float32)
108
+ v = v[:1] + guidance * (v[1:] - v[:1])
109
+ x = x + (sig[i] - sig[i + 1]) * v
110
+ return x
111
+
112
+ def query(self, tokens, pts, chunk=50000):
113
+ out = [self.run("vae_query", points=pts[None, i:i + chunk], tokens=tokens)[0, :, 0].astype(np.float32)
114
+ for i in range(0, len(pts), chunk)]
115
+ return np.concatenate(out)
116
+
117
+ def geometry(self, z, dense_depth=8, depth=9):
118
+ """hierarchical_extract_geometry: logits on a 2^dense_depth grid over [-1.005, 1.005]^3; per level, upsample
119
+ (nearest), re-query the voxels within the band |2 sigmoid(l) - 1| < 1 (all but saturated ones), dilated 5^3 (3^3
120
+ at 512), at the finer resolution; marching cubes at 0."""
121
+ from scipy import ndimage
122
+ from skimage import measure
123
+ tokens = self.run("vae_tokens", latents=z)
124
+ n = 2 ** dense_depth
125
+ ax = np.linspace(-BOUND, BOUND, n, dtype=np.float16).astype(np.float32)
126
+ g = np.stack(np.meshgrid(ax, ax, ax, indexing="ij"), -1).reshape(-1, 3)
127
+ grid = self.query(tokens, g).astype(np.float16).reshape(n, n, n)
128
+ g = None
129
+ for k in range(depth - dense_depth):
130
+ size = 2 ** (dense_depth + k + 1)
131
+ off = size / 2
132
+ hi = grid.repeat(2, 0).repeat(2, 1).repeat(2, 2)
133
+ # in float16 as the original: sigmoid saturates to exactly 0 / 1 (outside the band) beyond |logit| ~ 7.6
134
+ sg = (1 / (1 + np.exp(-grid[1:-1, 1:-1, 1:-1].astype(np.float32)))).astype(np.float16)
135
+ band = np.zeros(grid.shape, bool)
136
+ band[1:-1, 1:-1, 1:-1] = np.abs(sg * np.float16(2) - np.float16(1)) < 1.0
137
+ sg = None
138
+ band = ndimage.maximum_filter(band, size=5 if size // 2 < 512 else 3, mode="constant")
139
+ lo = np.argwhere(band).astype(np.int64)
140
+ hc = (lo[:, None, :] * 2 + np.array([[a, b, c] for a in (0, 1) for b in (0, 1) for c in (0, 1)])).reshape(-1, 3)
141
+ f16 = lambda x: np.asarray(x, np.float32).astype(np.float16).astype(np.float32) # one float16 op
142
+ pts = f16((hc - off).astype(np.float32) * (BOUND / off))
143
+ vals = self.query(tokens, pts).astype(np.float16)
144
+ idx = f16(f16(pts * (off / BOUND)) + off).astype(np.int32) # truncated, as the original's int cast
145
+ hi[idx[:, 0], idx[:, 1], idx[:, 2]] = vals
146
+ grid = hi
147
+ v, f, _, _ = measure.marching_cubes(grid.astype(np.float32), 0, method="lewiner")
148
+ v = v / (2 ** depth) * (2 * BOUND) - BOUND
149
+ return v.astype(np.float32), np.ascontiguousarray(f)
150
+
151
+ def __call__(self, img, steps=50, guidance=7.0, seed=42, noise=None, pixel_values=None):
152
+ px = pixels(prepare(img)) if pixel_values is None else pixel_values
153
+ if noise is None:
154
+ noise = np.random.default_rng(seed).standard_normal((1, 2048, 64)).astype(np.float32)
155
+ return self.geometry(self.latents(px, noise, steps, guidance))
156
+
157
+
158
+ if __name__ == "__main__":
159
+ import argparse
160
+ from PIL import Image
161
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
162
+ ap.add_argument("image"); ap.add_argument("output")
163
+ ap.add_argument("--steps", type=int, default=50); ap.add_argument("--seed", type=int, default=42)
164
+ ap.add_argument("--dir", default=str(Path(__file__).resolve().parent)); ap.add_argument("--cuda", action="store_true")
165
+ a = ap.parse_args()
166
+ v, f = TripoSG(a.dir, "cuda" if a.cuda else "cpu")(Image.open(a.image), a.steps, seed=a.seed)
167
+ import trimesh
168
+ trimesh.Trimesh(v, f).export(a.output)
int4/transformer.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46fed9ae739d7fb2d910ae71b10b08d24043e07f369d213947b87125a1a60044
3
+ size 1014529
int4/transformer.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:31be3128255418ddfa84ffcabfc24144430c54554e73abd36f8b567204ee63c9
3
+ size 858894336
int4/vae_query.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f19c0eee94b952153204c8ffae7b8b0249660758649c55137c363904f2522cc8
3
+ size 25315647
int4/vae_tokens.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d15d71fe54f8c24181b96882bd5995e5501d53fcf681f096c2961d939ff3a272
3
+ size 202956655