jennyxue commited on
Commit
eeea5fa
·
verified ·
1 Parent(s): 2f31b95

int8 build of TRELLIS text-conditioned

Browse files
.gitattributes CHANGED
@@ -38,3 +38,8 @@ fp16/mesh_dec.onnx.data filter=lfs diff=lfs merge=lfs -text
38
  fp16/slat_flow.onnx.data filter=lfs diff=lfs merge=lfs -text
39
  fp16/ss_dec.onnx.data filter=lfs diff=lfs merge=lfs -text
40
  fp16/ss_flow.onnx.data filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
38
  fp16/slat_flow.onnx.data filter=lfs diff=lfs merge=lfs -text
39
  fp16/ss_dec.onnx.data filter=lfs diff=lfs merge=lfs -text
40
  fp16/ss_flow.onnx.data filter=lfs diff=lfs merge=lfs -text
41
+ int8/clip.onnx.data filter=lfs diff=lfs merge=lfs -text
42
+ int8/mesh_dec.onnx.data filter=lfs diff=lfs merge=lfs -text
43
+ int8/slat_flow.onnx.data filter=lfs diff=lfs merge=lfs -text
44
+ int8/ss_dec.onnx.data filter=lfs diff=lfs merge=lfs -text
45
+ int8/ss_flow.onnx.data filter=lfs diff=lfs merge=lfs -text
int8/LICENSE-CLIP.txt ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 OpenAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
int8/LICENSE-FlexiCubes.txt ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
int8/LICENSE-TRELLIS.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) Microsoft Corporation.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE
int8/clip.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de594e18e59c34ccf87a022bd2df1cd922c15407fcc0637e2726403af402bf44
3
+ size 189939
int8/clip.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab7f2bbbdf2c50b241d34454d7a33bd45b53bc1e25978bcffec488c0beb047ea
3
+ size 492241920
int8/flexicubes_tables.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d22bf7f2ec21cf0832e550593630551071f7bd26175c896f2361f82fd44786e
3
+ size 2639
int8/mesh_dec.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb626eec211d6a0eb192aaebae7e4e09b63a7577e2a69627fe9162c057eebca3
3
+ size 460604
int8/mesh_dec.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14dd1588a5d46f7989e1c8d678048a46e8cb06b58a4b7f8a62732df5f9bf05e0
3
+ size 181885824
int8/pipeline.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TRELLIS text-conditioned (xlarge) with ONNX Runtime: a text prompt -> a mesh with vertex colours. The CLIP text
2
+ encoder, the sparse-structure flow and decoder, the structured-latent flow and the mesh decoder as ONNX graphs; numpy
3
+ around them, following the official TrellisTextTo3DPipeline (microsoft/TRELLIS):
4
+ - CLIP ViT-L/14 features of the prompt and of the empty prompt (classifier-free guidance);
5
+ - 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
6
+ [0.5, 0.95]), decoded to 64^3 occupancy; the occupied voxels are the structure;
7
+ - the structured latent: the same sampler over 8 features per voxel, then the latent normalisation undone;
8
+ - the mesh decoder's FlexiCubes features at 256^3 and FlexiCubes extraction (ported to numpy: dual vertices from a
9
+ weighted average of the edge crossings, quads split by the learned gamma), vertex colours from its colour channels.
10
+ The sparse operations (submanifold convolutions, pooling, Swin windows) run inside the graphs from index tables built
11
+ here from the voxel coordinates. The Gaussian and radiance-field decoders are not included.
12
+
13
+ Needs numpy, onnxruntime-gpu (or onnxruntime) and tokenizers; trimesh to write the mesh.
14
+
15
+ python fp16/pipeline.py "A chair looking like a avocado." chair.glb [--cuda] [--seed 1]
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import itertools
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+
25
+ STEPS, CFG, CFG_INTERVAL, RESCALE_T, SIGMA_MIN = 25, 7.5, (0.5, 0.95), 3.0, 1e-5
26
+ SLAT_MEAN = np.array([-2.1687545776367188, -0.004347046371549368, -0.13352349400520325, -0.08418072760105133,
27
+ -0.5271206498146057, 0.7238689064979553, -1.1414450407028198, 1.2039363384246826], np.float32)
28
+ SLAT_STD = np.array([2.377650737762451, 2.386378288269043, 2.124418020248413, 2.1748552322387695, 2.663944721221924,
29
+ 2.371192216873169, 2.6217446327209473, 2.684523105621338], np.float32)
30
+ OFF27 = np.array(list(itertools.product((-1, 0, 1), repeat=3)), np.int64) # kernel order (dx, dy, dz)
31
+ SUB8 = np.array(list(itertools.product((0, 1), repeat=3)), np.int64) # SparseSubdivide's child order
32
+ WINDOW = 8
33
+
34
+
35
+ # ------------------------------------------------------------------------------------------------ the prompt
36
+ def clip_ids(prompt, tokenizer_json, length=77):
37
+ """The CLIP tokenizer as the pipeline calls it (max_length 77, padding 'max_length', truncation): BOS, BPE, EOS,
38
+ padded with <|endoftext|>."""
39
+ from tokenizers import Tokenizer
40
+ tok = Tokenizer.from_file(str(tokenizer_json))
41
+ ids = tok.encode(prompt).ids
42
+ eos = tok.token_to_id("<|endoftext|>")
43
+ if len(ids) > length:
44
+ ids = ids[:length - 1] + [eos]
45
+ return np.array([ids + [eos] * (length - len(ids))], np.int64)
46
+
47
+
48
+ # ------------------------------------------------------------------------------------------------ index tables
49
+ def neighbours(xyz, offsets=OFF27):
50
+ """[N, K] index of each voxel's neighbour at each offset (N where there is none)."""
51
+ xyz = np.asarray(xyz, np.int64)
52
+ n = len(xyz)
53
+ R = int(xyz.max()) + 4
54
+ key = lambda p: ((p[:, 0] + 1) * R + (p[:, 1] + 1)) * R + (p[:, 2] + 1)
55
+ k = key(xyz)
56
+ order = np.argsort(k, kind="stable")
57
+ ks = k[order]
58
+ out = np.full((n, len(offsets)), n, np.int64)
59
+ for j, o in enumerate(offsets):
60
+ q = key(xyz + o)
61
+ pos = np.minimum(np.searchsorted(ks, q), n - 1)
62
+ hit = ks[pos] == q
63
+ out[hit, j] = order[pos[hit]]
64
+ return out
65
+
66
+
67
+ def with_batch(xyz):
68
+ return np.concatenate([np.zeros((len(xyz), 1), np.int32), np.asarray(xyz, np.int32)], 1)
69
+
70
+
71
+ def slat_flow_tables(coords):
72
+ """coords [N, 4] (batch 0, x, y, z at 64^3) -> coords64, nbr64, coords32, nbr32, down_child, down_cnt, up_idx."""
73
+ xyz = np.asarray(coords)[:, 1:].astype(np.int64)
74
+ coarse, inv = np.unique(xyz // 2, axis=0, return_inverse=True) # SparseDownsample's order
75
+ inv = inv.reshape(-1)
76
+ m = len(coarse)
77
+ cnt = np.bincount(inv, minlength=m)
78
+ order = np.argsort(inv, kind="stable")
79
+ start = np.concatenate([[0], np.cumsum(cnt)[:-1]])
80
+ slot = np.arange(len(xyz)) - start[inv[order]]
81
+ child = np.full((m, 8), len(xyz), np.int64)
82
+ child[inv[order], slot] = order
83
+ return (with_batch(xyz), neighbours(xyz), with_batch(coarse), neighbours(coarse), child,
84
+ cnt.astype(np.float32)[:, None], inv.astype(np.int64))
85
+
86
+
87
+ def windows(xyz, shift, size=WINDOW):
88
+ """The Swin partition (calc_window_partition): voxels grouped by window, padded to the fullest window.
89
+ Returns fwd [W, L] (index, N = padding), mask [W, L] (0 / -inf) and bwd [N] (position in the W * L layout)."""
90
+ s = np.asarray(xyz, np.int64) + shift
91
+ nw = (s.max(0) + 1 + size - 1) // size
92
+ wid = ((s[:, 0] // size) * nw[1] + s[:, 1] // size) * nw[2] + s[:, 2] // size
93
+ uw, winv, wcnt = np.unique(wid, return_inverse=True, return_counts=True)
94
+ winv = winv.reshape(-1)
95
+ L, Wn, n = int(wcnt.max()), len(uw), len(s)
96
+ order = np.argsort(winv, kind="stable")
97
+ start = np.concatenate([[0], np.cumsum(wcnt)[:-1]])
98
+ slot = np.empty(n, np.int64)
99
+ slot[order] = np.arange(n) - start[winv[order]]
100
+ fwd = np.full((Wn, L), n, np.int64)
101
+ fwd[winv, slot] = np.arange(n)
102
+ mask = np.where(fwd < n, 0.0, -np.inf).astype(np.float32)
103
+ return fwd, mask, (winv * L + slot).astype(np.int64)
104
+
105
+
106
+ def subdivide(xyz):
107
+ return ((np.asarray(xyz, np.int64) * 2)[:, None] + SUB8[None]).reshape(-1, 3)
108
+
109
+
110
+ def mesh_dec_tables(coords):
111
+ """coords [N, 4] -> coords64, the two Swin partitions (shift 0, 4), nbr128, nbr256."""
112
+ xyz = np.asarray(coords)[:, 1:].astype(np.int64)
113
+ x128 = subdivide(xyz)
114
+ x256 = subdivide(x128)
115
+ return (with_batch(xyz),) + windows(xyz, 0) + windows(xyz, WINDOW // 2) + (neighbours(x128), neighbours(x256))
116
+
117
+
118
+ def mesh_dec_coords256(coords):
119
+ return with_batch(subdivide(subdivide(np.asarray(coords)[:, 1:])))
120
+
121
+
122
+ # ------------------------------------------------------------------------------------------------ FlexiCubes
123
+ # A numpy port of the FlexiCubes extraction TRELLIS uses (NVIDIA FlexiCubes, Apache-2.0, at TRELLIS's submodule
124
+ # 815e075; LICENSE-FlexiCubes.txt; its lookup tables in flexicubes_tables.npz), inference path only. The original runs
125
+ # on the dense 256^3 grid; here only the cubes that can hold the surface (those with a corner the decoder wrote a
126
+ # negative SDF to) are visited, in the dense grid's order, so vertices and faces come out in the original's order.
127
+ 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)
128
+ 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)
129
+ QUAD_SPLIT_1, QUAD_SPLIT_2 = np.array([0, 1, 2, 0, 2, 3]), np.array([0, 1, 3, 3, 1, 2])
130
+
131
+
132
+ def _interp(w, x):
133
+ """FlexiCubes._linear_interp: zero crossing along each edge (w [E, 2, 1], x [E, 2, C])."""
134
+ w2 = np.concatenate([w[:, 1:2], -w[:, 0:1]], 1)
135
+ return (x * w2).sum(1) / w2.sum(1)
136
+
137
+
138
+ def _index_add(n, idx, val):
139
+ out = np.zeros((n,) + val.shape[1:], np.float32)
140
+ np.add.at(out, idx, val)
141
+ return out
142
+
143
+
144
+ def flexicubes(feats, xyz, tables, res=256, weight_scale=0.99):
145
+ """SparseFeatures2Mesh.__call__ (use_color) + FlexiCubes.__call__ (training=False) for one shape.
146
+ feats [N, 101] (sdf 8, deform 8 x 3, weights 21, colour 8 x 6), xyz [N, 3] at res^3.
147
+ Returns vertices [V, 3] in [-0.5, 0.5]^3, faces [F, 3], vertex attributes [V, 6] (colour, normal map)."""
148
+ f32 = np.float32
149
+ feats = np.asarray(feats, f32)
150
+ xyz = np.asarray(xyz, np.int64)
151
+ n = len(xyz)
152
+ R = res + 1
153
+ sdf = feats[:, 0:8] + f32(-1.0 / res)
154
+ deform = feats[:, 8:32].reshape(n, 8, 3)
155
+ weights = feats[:, 32:53]
156
+ color = feats[:, 53:101].reshape(n, 8, 6)
157
+ # sparse_cube2verts: every voxel's 8 corners, per-vertex mean over the voxels sharing it
158
+ vkey = lambda p: (p[..., 0] * R + p[..., 1]) * R + p[..., 2]
159
+ vid = vkey(xyz[:, None] + CORNERS[None]).reshape(-1)
160
+ tv, inv = np.unique(vid, return_inverse=True)
161
+ inv = inv.reshape(-1)
162
+ attrs = np.concatenate([sdf[..., None], deform, color], -1).reshape(-1, 10)
163
+ cnt = np.bincount(inv, minlength=len(tv)).astype(f32)
164
+ vattr = np.stack([np.bincount(inv, attrs[:, c], minlength=len(tv)) for c in range(10)], 1).astype(f32)
165
+ vattr /= cnt[:, None]
166
+
167
+ def lookup(q):
168
+ pos = np.minimum(np.searchsorted(tv, q), len(tv) - 1)
169
+ return pos, tv[pos] == q
170
+
171
+ def sdf_of(q):
172
+ pos, hit = lookup(q)
173
+ return np.where(hit, vattr[pos, 0], f32(1.0)) # untouched grid vertices: outside (1)
174
+
175
+ def pos_of(q):
176
+ pos, hit = lookup(q)
177
+ d = np.where(hit[..., None], vattr[pos, 1:4], f32(0.0))
178
+ g = np.stack([q // (R * R), (q // R) % R, q % R], -1).astype(f32)
179
+ return g / f32(res) - f32(0.5) + f32((1 - 1e-8) / (res * 2)) * np.tanh(d)
180
+
181
+ def color_of(q):
182
+ pos, hit = lookup(q)
183
+ c = np.where(hit[..., None], vattr[pos, 4:10], f32(0.0))
184
+ return (1 / (1 + np.exp(-c))).astype(f32)
185
+ # candidate cubes: those with a corner among the vertices with a negative SDF, in dense (x, y, z) order
186
+ neg = tv[vattr[:, 0] < 0]
187
+ nv = np.stack([neg // (R * R), (neg // R) % R, neg % R], -1)
188
+ cc = (nv[:, None] - CORNERS[None]).reshape(-1, 3)
189
+ cc = cc[((cc >= 0) & (cc < res)).all(1)]
190
+ ckey = np.unique((cc[:, 0] * res + cc[:, 1]) * res + cc[:, 2])
191
+ cxyz = np.stack([ckey // (res * res), (ckey // res) % res, ckey % res], -1)
192
+ cube_v = vkey(cxyz[:, None] + CORNERS[None]) # [C, 8]
193
+ occ = sdf_of(cube_v) < 0
194
+ s = occ.sum(1)
195
+ surf = (s > 0) & (s < 8)
196
+ ckey, cxyz, cube_v, occ = ckey[surf], cxyz[surf], cube_v[surf], occ[surf]
197
+ S = len(ckey)
198
+ if S == 0:
199
+ return np.zeros((0, 3), f32), np.zeros((0, 3), np.int64), np.zeros((0, 6), f32)
200
+ # weights: the decoder's per-voxel values where a voxel exists, 0 elsewhere (the dense grid's zeros)
201
+ ikey = (xyz[:, 0] * res + xyz[:, 1]) * res + xyz[:, 2]
202
+ io = np.argsort(ikey)
203
+ pos = np.minimum(np.searchsorted(ikey[io], ckey), n - 1)
204
+ hit = ikey[io][pos] == ckey
205
+ w = np.where(hit[:, None], weights[io[pos]], f32(0.0))
206
+ beta = np.tanh(w[:, :12]) * f32(weight_scale) + f32(1)
207
+ alpha = np.tanh(w[:, 12:20]) * f32(weight_scale) + f32(1)
208
+ gamma = (1 / (1 + np.exp(-w[:, 20]))).astype(f32) * f32(weight_scale) + f32((1 - weight_scale) / 2)
209
+ # _get_case_id (the C16 / C19 ambiguity resolved against the adjacent cube)
210
+ case = (occ * (1 << np.arange(8))).sum(1)
211
+ pc = tables["check_table"][case]
212
+ to_check = np.nonzero(pc[:, 0] == 1)[0]
213
+ adj = cxyz[to_check] + pc[to_check, 1:4]
214
+ within = ((adj >= 0) & (adj < res)).all(1)
215
+ to_check, adj = to_check[within], adj[within]
216
+ akey = (adj[:, 0] * res + adj[:, 1]) * res + adj[:, 2]
217
+ chk_keys = np.sort(ckey[pc[:, 0] == 1])
218
+ if len(chk_keys) and len(akey):
219
+ p = np.minimum(np.searchsorted(chk_keys, akey), len(chk_keys) - 1)
220
+ flip_case = chk_keys[p] == akey
221
+ case[to_check[flip_case]] = pc[to_check[flip_case], -1]
222
+ # _identify_surf_edges
223
+ edges = cube_v[:, CUBE_EDGES].reshape(-1, 2)
224
+ big = R ** 3
225
+ ue_key, e_inv, e_cnt = np.unique(edges[:, 0] * big + edges[:, 1], return_inverse=True, return_counts=True)
226
+ e_inv = e_inv.reshape(-1)
227
+ ue = np.stack([ue_key // big, ue_key % big], 1)
228
+ mask_edges = (sdf_of(ue) < 0).sum(1) == 1
229
+ surf_edges_mask = mask_edges[e_inv]
230
+ counts = e_cnt[e_inv]
231
+ mapping = np.full(len(ue), -1, np.int64)
232
+ mapping[mask_edges] = np.arange(mask_edges.sum())
233
+ idx_map = mapping[e_inv] # [S * 12]
234
+ surf_edges = ue[mask_edges]
235
+ # _compute_vd
236
+ alpha12 = alpha[:, CUBE_EDGES].reshape(-1, 2) # [S * 12, 2]
237
+ se_x = pos_of(surf_edges.reshape(-1)).reshape(-1, 2, 3)
238
+ se_s = sdf_of(surf_edges.reshape(-1)).reshape(-1, 2, 1)
239
+ se_c = color_of(surf_edges.reshape(-1)).reshape(-1, 2, 6)
240
+ num_vd = tables["num_vd_table"][case]
241
+ eg, eg_vd, eg_cube, vd_gamma = [], [], [], []
242
+ total = 0
243
+ for num in np.unique(num_vd):
244
+ cur = num_vd == num
245
+ ncur = int(cur.sum()) * int(num)
246
+ g = tables["dmc_table"][case[cur], :num].reshape(-1, num * 7)
247
+ g_vd = (np.arange(ncur)[:, None].repeat(7, 1) + total).reshape(g.shape)
248
+ total += ncur
249
+ g_cube = np.nonzero(cur)[0][:, None].repeat(num * 7, 1)
250
+ m = g != -1
251
+ eg.append(g[m])
252
+ eg_vd.append(g_vd[m])
253
+ eg_cube.append(g_cube[m])
254
+ vd_gamma.append(gamma[cur][:, None].repeat(num, 1).reshape(-1))
255
+ eg, eg_vd, eg_cube, vd_gamma = (np.concatenate(v) for v in (eg, eg_vd, eg_cube, vd_gamma))
256
+ flat = eg_cube * 12 + eg
257
+ idx_group = idx_map[flat]
258
+ sw = se_s[idx_group] * alpha12[flat][:, :, None]
259
+ ue_group = _interp(sw, se_x[idx_group])
260
+ beta_group = beta.reshape(-1)[flat][:, None]
261
+ beta_sum = _index_add(total, eg_vd, beta_group)
262
+ vd = _index_add(total, eg_vd, ue_group * beta_group) / beta_sum
263
+ vd_color = _index_add(total, eg_vd, _interp(sw, se_c[idx_group]) * beta_group) / beta_sum
264
+ vd_idx_map = np.zeros(S * 12, np.int64)
265
+ vd_idx_map[flat] = eg_vd
266
+ # _triangulate (inference: each quad split along the diagonal with the larger gamma product)
267
+ gm = (counts == 4) & surf_edges_mask
268
+ group = idx_map[gm]
269
+ vd_idx = vd_idx_map[gm]
270
+ order = np.argsort(group, kind="stable")
271
+ edge_indices = group[order]
272
+ quad = vd_idx[order].reshape(-1, 4)
273
+ s_e = sdf_of(surf_edges[edge_indices.reshape(-1, 4)[:, 0]].reshape(-1)).reshape(-1, 2)
274
+ flip = s_e[:, 0] > 0
275
+ quad = np.concatenate([quad[flip][:, [0, 1, 3, 2]], quad[~flip][:, [2, 3, 1, 0]]])
276
+ qg = vd_gamma[quad]
277
+ split = (qg[:, 0] * qg[:, 2]) > (qg[:, 1] * qg[:, 3])
278
+ faces = np.where(split[:, None], quad[:, QUAD_SPLIT_1], quad[:, QUAD_SPLIT_2]).reshape(-1, 3)
279
+ return vd.astype(f32), faces, vd_color.astype(f32)
280
+
281
+
282
+ # ------------------------------------------------------------------------------------------------ the runtime
283
+ def t_schedule(steps=STEPS, rescale_t=RESCALE_T):
284
+ t = np.linspace(1, 0, steps + 1)
285
+ return rescale_t * t / (1 + (rescale_t - 1) * t)
286
+
287
+
288
+ class TrellisText:
289
+ def __init__(self, folder, provider="cpu"):
290
+ import onnxruntime as ort
291
+ self.folder, self.ort = Path(folder), ort
292
+ if provider != "cpu" and hasattr(ort, "preload_dlls"):
293
+ try:
294
+ ort.preload_dlls()
295
+ except Exception:
296
+ pass
297
+ self.pv = ["CPUExecutionProvider"] if provider == "cpu" else [
298
+ ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested", "use_tf32": "0"}),
299
+ "CPUExecutionProvider"]
300
+ self.ro = ort.RunOptions()
301
+ if provider != "cpu":
302
+ self.ro.add_run_config_entry("memory.enable_memory_arena_shrinkage", "gpu:0")
303
+ self.s = {}
304
+ self.tables = dict(np.load(self.folder / "flexicubes_tables.npz"))
305
+
306
+ def session(self, name):
307
+ if name not in self.s:
308
+ so = self.ort.SessionOptions()
309
+ so.log_severity_level = 3
310
+ so.graph_optimization_level = self.ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
311
+ self.s[name] = self.ort.InferenceSession(str(self.folder / f"{name}.onnx"), so, providers=self.pv)
312
+ return self.s[name]
313
+
314
+ def release(self, *names):
315
+ for n in names:
316
+ self.s.pop(n, None)
317
+
318
+ def run(self, name, feed):
319
+ s = self.session(name)
320
+ names = {i.name for i in s.get_inputs()} # a table a graph doesn't use was pruned from its inputs
321
+ return s.run(None, {k: v for k, v in feed.items() if k in names}, self.ro)[0]
322
+
323
+ def encode(self, prompt):
324
+ tok = self.folder / "tokenizer.json"
325
+ c = self.run("clip", {"input_ids": clip_ids(prompt, tok)})
326
+ nc = self.run("clip", {"input_ids": clip_ids("", tok)})
327
+ self.release("clip")
328
+ return c.astype(np.float32), nc.astype(np.float32)
329
+
330
+ @staticmethod
331
+ def _euler(x, velocity, steps, interval, rescale_t):
332
+ """FlowEulerGuidanceIntervalSampler.sample: x -= (t - t_prev) v; inside the guidance interval v is the
333
+ guided velocity, outside it the condition's alone."""
334
+ ts = t_schedule(steps, rescale_t)
335
+ for t, tp in zip(ts[:-1], ts[1:]):
336
+ v = velocity(x, np.array([1000 * t], np.float32), interval[0] <= t <= interval[1])
337
+ x = (x - np.float32(t - tp) * v).astype(np.float32)
338
+ return x
339
+
340
+ def sparse_structure(self, cond, neg, noise, steps=STEPS, cfg=CFG, interval=CFG_INTERVAL, rescale_t=RESCALE_T):
341
+ def velocity(x, t, guided):
342
+ if not guided:
343
+ return self.run("ss_flow", {"x": x, "t": t, "cond": cond})
344
+ v = self.run("ss_flow", {"x": np.concatenate([x, x]), "t": np.concatenate([t, t]),
345
+ "cond": np.concatenate([cond, neg])}) # both rows in one batch
346
+ return (1 + cfg) * v[:1] - cfg * v[1:]
347
+ z = self._euler(np.asarray(noise, np.float32), velocity, steps, interval, rescale_t)
348
+ self.release("ss_flow")
349
+ logits = self.run("ss_dec", {"z": z})
350
+ self.release("ss_dec")
351
+ return z, logits, np.argwhere(logits > 0)[:, [0, 2, 3, 4]].astype(np.int32)
352
+
353
+ def structured_latent(self, cond, neg, coords, noise, steps=STEPS, cfg=CFG, interval=CFG_INTERVAL,
354
+ rescale_t=RESCALE_T):
355
+ names = ("coords64", "nbr64", "coords32", "nbr32", "down_child", "down_cnt", "up_idx")
356
+ tb = dict(zip(names, slat_flow_tables(coords)))
357
+
358
+ def velocity(x, t, guided):
359
+ v = self.run("slat_flow", {"feats": x, "t": t, "cond": cond, **tb})
360
+ if not guided:
361
+ return v
362
+ return (1 + cfg) * v - cfg * self.run("slat_flow", {"feats": x, "t": t, "cond": neg, **tb})
363
+ x = self._euler(np.asarray(noise, np.float32), velocity, steps, interval, rescale_t)
364
+ self.release("slat_flow")
365
+ return x * SLAT_STD[None] + SLAT_MEAN[None]
366
+
367
+ def mesh_features(self, slat, coords):
368
+ names = ("coords64", "win0_fwd", "win0_mask", "win0_bwd", "win4_fwd", "win4_mask", "win4_bwd", "nbr128",
369
+ "nbr256")
370
+ tb = dict(zip(names, mesh_dec_tables(coords)))
371
+ f = self.run("mesh_dec", {"slat": np.asarray(slat, np.float32), **tb})
372
+ self.release("mesh_dec")
373
+ return f, subdivide(subdivide(np.asarray(coords)[:, 1:]))
374
+
375
+ def mesh(self, slat, coords):
376
+ f, xyz = self.mesh_features(slat, coords)
377
+ return flexicubes(f, xyz, self.tables)
378
+
379
+ def __call__(self, prompt, seed=None, ss_noise=None, slat_noise=None):
380
+ rng = np.random.default_rng(seed)
381
+ c, nc = self.encode(prompt)
382
+ if ss_noise is None:
383
+ ss_noise = rng.standard_normal((1, 8, 16, 16, 16)).astype(np.float32)
384
+ _, _, coords = self.sparse_structure(c, nc, ss_noise)
385
+ if slat_noise is None:
386
+ slat_noise = rng.standard_normal((len(coords), 8)).astype(np.float32)
387
+ return self.mesh(self.structured_latent(c, nc, coords, slat_noise), coords)
388
+
389
+
390
+ def save_mesh(path, v, f, attrs):
391
+ """The mesh with its vertex colours, y-up as TRELLIS's to_glb writes it (rotated -90 degrees about x)."""
392
+ import trimesh
393
+ v = v @ np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]], np.float32)
394
+ col = (np.clip(attrs[:, :3], 0, 1) * 255).astype(np.uint8)
395
+ trimesh.Trimesh(v, f, vertex_colors=col, process=False).export(path)
396
+
397
+
398
+ if __name__ == "__main__":
399
+ import argparse
400
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
401
+ ap.add_argument("prompt")
402
+ ap.add_argument("out")
403
+ ap.add_argument("--seed", type=int)
404
+ ap.add_argument("--dir", default=str(Path(__file__).resolve().parent))
405
+ ap.add_argument("--cuda", action="store_true")
406
+ a = ap.parse_args()
407
+ v, f, attrs = TrellisText(a.dir, "cuda" if a.cuda else "cpu")(a.prompt, a.seed)
408
+ save_mesh(a.out, v, f, attrs)
409
+ print(len(v), "vertices,", len(f), "faces")
int8/slat_flow.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3848ac1f8fc6adb65a7a38bcd5a3b4affa5db7dc304767e7ec6f921a60c7376
3
+ size 2379942
int8/slat_flow.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51628bd0586ee9bc735609f6b43ee2005cb25b2503a1073ecf3efaf64f8e1600
3
+ size 1141731072
int8/ss_dec.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:23afc83ea18f0ce014a592065bffb90e358e8453b0e5c1247582359d67871790
3
+ size 39172
int8/ss_dec.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c092fd40b354ba5f2cc0e3a118b2b0bca19ce398bcf11da9df1fd8e3718db645
3
+ size 147578240
int8/ss_flow.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72a9601ae0648c2dcd9f3d9a7ffdf386d6531aef4062ecf5cb1cab8b8a552d4c
3
+ size 1866124
int8/ss_flow.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e6f848d2f585d6c2a01cb1efae80d987664a22daa3d0b644b0ce707559b56793
3
+ size 1058817280
int8/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff